Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: pre-landing review fixes
garrytan1873c62a7c9d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2a1ae9e749..0e5e064c39 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,7 +16,7 @@ identifiers and attribution are available in the pre-removal Git revision### 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.+- 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 on master newer than stable with a successful full soak of its exact tree, both default cells for at least 2 hours with privacy probes run, 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, and `dry_run=false` needs an admin or maintainer before it writes anything.- `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.diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex ff3a7f2f35..08b63b9d20 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -657,10 +657,12 @@ and keeps stable between one day and one week behind what matters: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.+ commit is on master and 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. The soak must be+ the full default one: both the 65 ms and 2 ms cells, at least 2 hours each,+ with privacy probes run, so a short smoke dispatch never qualifies. On the important-only path the candidate must contain the fix.It is promoted through the same `promote()` as a manual promotion, so everycheck above still applies and the record's `promoted_by` is`schedule (.github/workflows/stable-daily.yml)` with the reason in `reason`.@@ -670,7 +672,7 @@ and keeps stable between one day and one week behind what matters:- **Who.** A schedule event runs only the workflow file as merged on thedefault branch, so a scheduled run promotes by rule without a maintainer. Amanual dispatch defaults to `dry_run` (report only); `dry_run=false` needs an- admin or maintainer. It shares the `promote-stable` concurrency group, so it+ admin or maintainer before it dispatches a soak or promotes. It shares the `promote-stable` concurrency group, so itnever 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 whilediff --git a/scripts/promote-stable.ts b/scripts/promote-stable.tsindex dd32b0495c..c8d8897a30 100644--- a/scripts/promote-stable.ts+++ b/scripts/promote-stable.ts@@ -104,6 +104,26 @@ export function scheduleAuthorized(env: NodeJS.ProcessEnv, repo: string): booleareturn env.GITHUB_EVENT_NAME === 'schedule' && (env.GITHUB_WORKFLOW_REF ?? '').startsWith(`${repo}/${DAILY_WORKFLOW}@refs/heads/`);}+/** The branch release.yml mints release tags from; a scheduled promotion only takes a release whose commit is on it. */+export const RELEASE_BRANCH_REF = 'refs/remotes/origin/master';++export async function onReleaseBranch(deps: PromoteDeps, commit: string): Promise<boolean> {+ return (await deps.git(['merge-base', '--is-ancestor', commit, RELEASE_BRANCH_REF])).code === 0;+}++/** The scheduled daily check promotes by rule; everyone else needs the admin or maintain role. */+export async function authorize(deps: PromoteDeps): Promise<void> {+ if (deps.scheduled) {+ deps.log(`[promote-stable] scheduled daily check (${DAILY_WORKFLOW} on the default branch): promoting by rule.`);+ return;+ }+ // `permission` is the legacy base role (maintain reads as write); `role_name` names maintain.+ const perm = await deps.ghApi(`repos/${deps.repo}/collaborators/${encodeURIComponent(deps.actor)}/permission`) as { permission?: string; role_name?: string };+ const role = perm.role_name || perm.permission || 'none';+ if (perm.permission !== 'admin' && !PROMOTER_ROLES.has(role)) throw new Refusal(`${deps.actor} has the ${role} role on ${deps.repo}; only admins and maintainers promote to stable, so ask one to dispatch this workflow.`);+ deps.log(`[promote-stable] ${deps.actor} has the ${role} role: allowed to promote.`);+}+export function compareVersions(a: string, b: string): number {const pa = a.split('.').map(Number);const pb = b.split('.').map(Number);@@ -205,15 +225,7 @@ export async function currentStable(deps: PromoteDeps): Promise<{ version: strinexport async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promise<Promotion> {const { version, rollback, reason } = inputs;- if (deps.scheduled) {- deps.log(`[promote-stable] scheduled daily check (${DAILY_WORKFLOW} on the default branch): promoting by rule.`);- } else {- // `permission` is the legacy base role (maintain reads as write); `role_name` names maintain.- const perm = await deps.ghApi(`repos/${deps.repo}/collaborators/${encodeURIComponent(deps.actor)}/permission`) as { permission?: string; role_name?: string };- const role = perm.role_name || perm.permission || 'none';- if (perm.permission !== 'admin' && !PROMOTER_ROLES.has(role)) throw new Refusal(`${deps.actor} has the ${role} role on ${deps.repo}; only admins and maintainers promote to stable, so ask one to dispatch this workflow.`);- deps.log(`[promote-stable] ${deps.actor} has the ${role} role: allowed to promote.`);- }+ await authorize(deps);if (!VERSION_RE.test(version)) throw new Refusal(`version "${version}" is not a release version; pass the VERSION of a published release, like 0.60.361.0.`);if (rollback && !reason.trim()) throw new Refusal(ROLLBACK_NEEDS_REASON);@@ -221,6 +233,7 @@ export async function promote(deps: PromoteDeps, inputs: PromoteInputs): Promiseif (!(await refExists(deps, `${releaseRef}^{commit}`))) throw new Refusal(`There is no release tag v${version}; promote a version release.yml has already published.`);const commit = await gitOut(deps, ['rev-parse', `${releaseRef}^{commit}`], `Could not resolve ${releaseRef}; re-run this workflow.`);const tree = await gitOut(deps, ['rev-parse', `${releaseRef}^{tree}`], `Could not resolve the tree of ${releaseRef}; re-run this workflow.`);+ if (deps.scheduled && !(await onReleaseBranch(deps, commit))) throw new Refusal(`v${version} (${commit}) is not on master; the scheduled check only promotes a release minted from master, so a maintainer decides on this one.`);const taggedVersion = (await deps.git(['show', `${releaseRef}:VERSION`])).stdout.trim();if (taggedVersion !== version) throw new Refusal(`v${version}'s VERSION file says "${taggedVersion || 'nothing'}"; promote a tag release.yml minted for its own VERSION.`);let release: { draft?: boolean };diff --git a/scripts/stable-daily.ts b/scripts/stable-daily.tsindex 2e218c4e74..d4e05dab07 100644--- a/scripts/stable-daily.ts+++ b/scripts/stable-daily.ts@@ -13,9 +13,9 @@* 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+ * 3. The candidate is the newest release on master newer than stable whose exact+ * git tree passed a full (SOAK_SHAPE) 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.@@ -30,7 +30,7 @@ import { appendFileSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'import { tmpdir } from 'node:os';import { join } from 'node:path';import {- compareVersions, currentStable, processDeps, promote, Refusal, requireSoakWorkflow, scheduleAuthorized, STABLE_REF,+ authorize, compareVersions, currentStable, onReleaseBranch, processDeps, promote, Refusal, requireSoakWorkflow, scheduleAuthorized, STABLE_REF,type PromoteDeps, type Promotion,} from './promote-stable.ts';@@ -38,11 +38,16 @@ 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;+/** The full soak a scheduled promotion requires: production-soak.yml's default cells and hours, with privacy probes run. */+export const SOAK_SHAPE = { rtts: [65, 2], hours: 2 } 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 Scoreboard {+ label?: string; rtt_ms?: number | null; hours?: number | null; elapsed_s?: number | null; privacy?: { probes?: number };+ gates?: Array<{ id: string; pass: boolean | null }>;+}export interface DailyDeps extends PromoteDeps {ghPost(path: string, body: unknown): Promise<void>;@@ -79,6 +84,17 @@ export function integrityFailures(boards: Scoreboard[]): string[] {return failures;}+/** Ways a soak falls short of the full default soak (SOAK_SHAPE): a missing cell, a short run, no privacy probes. */+export function shapeFailures(boards: Scoreboard[]): string[] {+ const failures = SOAK_SHAPE.rtts.filter(rtt => !boards.some(b => b.rtt_ms === rtt)).map(rtt => `no ${rtt} ms cell`);+ for (const b of boards) {+ const cell = b.label ?? 'cell';+ if ((b.hours ?? 0) < SOAK_SHAPE.hours || (b.elapsed_s ?? 0) < SOAK_SHAPE.hours * 3600) failures.push(`${cell}: ran ${b.elapsed_s ?? 0} s of a ${SOAK_SHAPE.hours} h soak`);+ if (!((b.privacy?.probes ?? 0) > 0)) failures.push(`${cell}: no privacy probes ran`);+ }+ 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.`);@@ -96,6 +112,7 @@ async function treeOf(deps: PromoteDeps, commit: string): Promise<string | 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);+ if (!deps.dryRun) await authorize(deps);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.');@@ -111,7 +128,9 @@ export async function daily(deps: DailyDeps): Promise<DailyResult> {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}`]) });+ const commit = await ok(deps, ['rev-parse', `refs/tags/${tag}^{commit}`]);+ if (!(await onReleaseBranch(deps, commit))) { deps.log(`[stable-daily] skipping ${tag}: ${commit} is not on master.`); continue; }+ releases.push({ version, 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}.` };@@ -153,7 +172,8 @@ export async function daily(deps: DailyDeps): Promise<DailyResult> {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));+ const boards = await deps.scoreboards(run.id);+ const failures = [...integrityFailures(boards), ...shapeFailures(boards)];if (failures.length === 0) { chosen = run; break; }deps.log(`[stable-daily] not promotable: v${rel.version} soak ${run.html_url}: ${failures.join(', ')}.`);}diff --git a/test/scripts/stable-daily.test.ts b/test/scripts/stable-daily.test.tsindex fdb113d40e..961756ef1f 100644--- a/test/scripts/stable-daily.test.ts+++ b/test/scripts/stable-daily.test.ts@@ -17,15 +17,15 @@ 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 { daily, integrityFailures, parseRecord, shapeFailures, 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,+const CLEAN: Scoreboard[] = [2, 65].map(rtt => ({+ label: `rtt${rtt}`, rtt_ms: rtt, hours: 2, elapsed_s: 7204, privacy: { probes: 40 },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: '' });@@ -34,6 +34,8 @@ 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;+ /** origin/master's commit (default head); a release tag above it is off master. */+ master?: number;releases: Record<string, number>;stable: { version: string; commit: number; message: string };importantPrs?: Array<{ number: number; merge: number }>;@@ -57,6 +59,7 @@ function world(w: World) {};for (const [v, c] of Object.entries(w.releases)) tags[`v${v}`] = { commit: c, object: sha(c) };const commitOf = (spec: string): number | null => {+ if (spec === 'refs/remotes/origin/master') return w.master ?? w.head;const name = spec.replace(/^refs\/tags\//, '');if (tags[name]) return tags[name]!.commit;const n = Number.parseInt(spec.replace(/^c+/, ''), 10);@@ -170,6 +173,12 @@ describe('integrity gates', () => {expect(integrityFailures([{ label: 'rtt2', gates: [] }])).toHaveLength(5);});+ test('a soak short of the full default shape is not promotable: a missing cell, a short run, no privacy probes', () => {+ expect(shapeFailures(CLEAN)).toEqual([]);+ const smoke: Scoreboard[] = [{ ...CLEAN[0]!, hours: 0.01, elapsed_s: 36, privacy: { probes: 0 } }];+ expect(shapeFailures(smoke)).toEqual(['no 65 ms cell', 'rtt2: ran 36 s of a 2 h soak', 'rtt2: no privacy probes ran']);+ });+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' });});@@ -267,6 +276,37 @@ describe('daily: weekly floor', () => {expect([...w.posts, ...none.posts]).toEqual([]);});+ test('a smoke-sized soak with every gate passing is not promoted', async () => {+ const smoke: Scoreboard[] = [{ ...CLEAN[0]!, hours: 0.01, elapsed_s: 36 }];+ const w = world(base({ stable: old, runs: [soak(9, 4, { boards: smoke })] }));+ const r = await daily(w.deps);+ expect(r.action).toBe('waiting');+ expect(w.pushes).toEqual([]);+ expect(w.logs.some(l => l.includes('no 65 ms cell'))).toBe(true);+ });++ test('a release tag whose commit is not on master is never soaked or promoted by the schedule', async () => {+ const w = world(base({ stable: old, master: 3, runs: [soak(9, 3), soak(10, 4)] }));+ const r = await daily(w.deps);+ expect(r.action === 'promoted' && r.promotion.version).toBe('1.0.3');+ expect(w.logs.some(l => l.includes('skipping v1.0.4'))).toBe(true);+ const fresh = world(base({ stable: old, master: 3 }));+ expect(await daily(fresh.deps)).toMatchObject({ action: 'soak_dispatched', version: '1.0.3' });+ const direct = world(base({ master: 3, runs: [soak(10, 4)] }));+ const error = await promote(direct.deps, { version: '1.0.4', soakRunUrl: `https://github.com/${REPO}/actions/runs/10`, scoreboardUrl: '', rollback: false, reason: '' }).then(() => null, e => e);+ expect(error).toBeInstanceOf(Refusal);+ expect((error as Error).message).toMatch(/not on master/);+ });++ test('a manual dispatch with dry_run=false needs the maintainer role before it dispatches anything', async () => {+ const w = world(base({ stable: old, scheduled: false }));+ const error = await daily(w.deps).then(() => null, e => e);+ expect(error).toBeInstanceOf(Refusal);+ expect((error as Error).message).toMatch(/has the none role/);+ expect(w.posts).toEqual([]);+ expect(w.pushes).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');