Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ci: a Linux watcher job finalizes a darwin-x64 heartbeat its cell left pending, and the cell logs why each failed post failed
garrytan86b13d0c5179
diff --git a/.github/workflows/native-locks.yml b/.github/workflows/native-locks.ymlindex b6dc24784f..05daab818e 100644--- a/.github/workflows/native-locks.yml+++ b/.github/workflows/native-locks.yml@@ -202,6 +202,37 @@ jobs:GBRAIN_HEARTBEAT_CELL: ${{ matrix.target }}/${{ matrix.bun }}run: bash scripts/native/heartbeat.sh stop "${{ job.status }}"+ # The darwin-x64 runner sometimes cannot reach the API when a cell ends (#7499: all three attempts of the cell's terminal+ # post timed out), so its diag/native-heartbeat/<cell> status stays pending on a job that passed. This Linux job runs+ # after every cell and posts success, naming the cell's real conclusion and last heartbeat, on any cell context still+ # pending (scripts/native/heartbeat-finalize.ts). Nothing on a fork's pull request, whose token cannot write.+ heartbeat-finalize:+ name: darwin-x64 heartbeat finalize+ needs: [native]+ if: ${{ always() && inputs.scope != 'smoke' }}+ runs-on: ubicloud-standard-2-ubuntu-2404+ timeout-minutes: 5+ # statuses: the darwin-x64 cells' diag/native-heartbeat/<cell> contexts; actions: read the run's jobs and conclusions.+ permissions:+ actions: read+ contents: read+ statuses: write+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262+ with:+ persist-credentials: false+ sparse-checkout: scripts/native/heartbeat-finalize.ts+ sparse-checkout-cone-mode: false+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6+ with:+ bun-version: 1.4.4+ - name: Finalize darwin-x64 heartbeats left pending+ env:+ GH_TOKEN: ${{ github.token }}+ GBRAIN_HEARTBEAT_ENABLED: ${{ (github.event.pull_request.head.repo.full_name || github.repository) == github.repository && '1' || '0' }}+ GBRAIN_HEARTBEAT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}+ run: bun scripts/native/heartbeat-finalize.ts+windows-backup-console:name: Windows PowerShell console probe / ${{ matrix.runner }} / Bun ${{ matrix.bun }}# Named exception: PR scope reduction, covered by scope=full runs (docs/TESTING.md#event-parity).diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex d3b34093fd..7ac58bfb49 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -1049,8 +1049,10 @@ jobs:needs: [changes]if: ${{ needs.changes.outputs.reuse != 'true' && ((github.event_name != 'pull_request' || needs.changes.outputs.native-scope != 'smoke') && (github.event_name != 'workflow_dispatch' || (inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base))) }}uses: ./.github/workflows/native-locks.yml- # statuses: the darwin-x64 cells' diag/native-heartbeat/<cell> commit statuses (native-locks.yml).+ # statuses: the darwin-x64 cells' diag/native-heartbeat/<cell> commit statuses (native-locks.yml); actions: read for its+ # heartbeat-finalize job, which reads the run's job conclusions.permissions:+ actions: readcontents: readstatuses: writewith:diff --git a/scripts/native/heartbeat-finalize.ts b/scripts/native/heartbeat-finalize.tsnew file mode 100644index 0000000000..80387de6fa--- /dev/null+++ b/scripts/native/heartbeat-finalize.ts@@ -0,0 +1,77 @@+#!/usr/bin/env bun+/**+ * scripts/native/heartbeat-finalize.ts: the Linux watcher that ends every darwin-x64 heartbeat a cell left pending.+ *+ * A darwin-x64 cell posts its own terminal `success` status (scripts/native/heartbeat.sh stop), but that runner sometimes+ * cannot reach the API when the cell ends: on #7499 all three attempts of the terminal post timed out, so+ * `diag/native-heartbeat/darwin-x64/1.4.4` stayed pending on a job that passed. This job runs after every native cell,+ * on a Linux runner, reads each darwin-x64 cell's conclusion from the run, and posts `success` naming that conclusion on+ * any cell context whose latest status is still pending. A context the cell finished itself, or never posted, is left alone.+ * The description names the cell, its real conclusion and the time of its last heartbeat, so a wedge stays readable.+ *+ * Reads GH_TOKEN, GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_API_URL, GITHUB_SERVER_URL and GBRAIN_HEARTBEAT_SHA; does+ * nothing unless GBRAIN_HEARTBEAT_ENABLED=1 (a fork's pull request token cannot write). A failure is a warning, never a+ * failed job: the status is diagnostic.+ */++const env = process.env;+const api = env.GITHUB_API_URL ?? 'https://api.github.com';+const repo = env.GITHUB_REPOSITORY ?? '';+const sha = env.GBRAIN_HEARTBEAT_SHA ?? '';+const backoffMs = Number(env.GBRAIN_HEARTBEAT_FINALIZE_BACKOFF_MS ?? 2000);+const CELL = /(?:^|\/ )darwin-x64 \/ Bun (\S+)$/;++type Job = { name: string; status: string; conclusion: string | null; html_url: string };+type Status = { context: string; state: string; created_at: string };++async function call<T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T> {+ let last = '';+ for (let attempt = 1; attempt <= 3; attempt++) {+ try {+ const response = await fetch(`${api}${path}`, { method, signal: AbortSignal.timeout(15_000),+ headers: { Authorization: `Bearer ${env.GH_TOKEN ?? ''}`, Accept: 'application/vnd.github+json' },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ if (response.ok) return await response.json() as T;+ last = `HTTP ${response.status}`;+ if (response.status < 500 && response.status !== 429) break;+ } catch (error) {+ last = error instanceof Error ? error.name : 'request failed';+ }+ if (attempt < 3) await Bun.sleep(backoffMs * attempt);+ }+ throw new Error(`${method} ${path.split('?')[0]} failed: ${last}`);+}++async function latestStatus(context: string): Promise<Status | null> {+ for (let page = 1; page <= 10; page++) {+ const statuses = await call<Status[]>('GET', `/repos/${repo}/commits/${sha}/statuses?per_page=100&page=${page}`);+ const hit = statuses.find(status => status.context === context);+ if (hit) return hit;+ if (statuses.length < 100) return null;+ }+ return null;+}++async function main(): Promise<void> {+ if (env.GBRAIN_HEARTBEAT_ENABLED !== '1') return;+ const jobs: Job[] = [];+ for (let page = 1; ; page++) {+ const batch = await call<{ jobs: Job[] }>('GET', `/repos/${repo}/actions/runs/${env.GITHUB_RUN_ID ?? ''}/jobs?filter=latest&per_page=100&page=${page}`);+ jobs.push(...batch.jobs);+ if (batch.jobs.length < 100) break;+ }+ for (const job of jobs) {+ const bun = CELL.exec(job.name)?.[1];+ if (!bun || job.status !== 'completed') continue;+ const cell = `darwin-x64/${bun}`.replace(/[^A-Za-z0-9._/-]/g, '').slice(0, 32);+ const context = `diag/native-heartbeat/${cell}`;+ const latest = await latestStatus(context);+ if (!latest || latest.state !== 'pending') { console.log(`${context}: ${latest ? `already ${latest.state}` : 'no heartbeat'}`); continue; }+ const conclusion = (job.conclusion ?? 'unknown').replace(/[^a-z_]/g, '').slice(0, 16);+ const description = `${cell} finished ${conclusion} | finalized by the watcher job; last heartbeat ${latest.created_at.slice(11, 19)}Z`.slice(0, 140);+ await call('POST', `/repos/${repo}/statuses/${sha}`, { state: 'success', context, description, target_url: job.html_url });+ console.log(`${context}: finalized (${conclusion}; the cell's own terminal post never landed)`);+ }+}++await main().catch(error => { console.log(`::warning::darwin-x64 heartbeat finalize: ${error instanceof Error ? error.message : String(error)}`); });diff --git a/scripts/native/heartbeat.sh b/scripts/native/heartbeat.shindex db16b8e93a..985d933311 100755--- a/scripts/native/heartbeat.sh+++ b/scripts/native/heartbeat.sh@@ -61,12 +61,17 @@ describe() {"$(mem_free_pct)" "$(swap_used)" "$(load_1m)" "$(top_names)" | tr -cd 'A-Za-z0-9 ._/|%:,=+-' | cut -c1-140}+# A failed post names curl's exit code and the HTTP status on stderr (the loop discards it; stop's lands in the job log).post() {- local url="${GITHUB_SERVER_URL:-https://github.com}/${GITHUB_REPOSITORY:-}/actions/runs/${GITHUB_RUN_ID:-}"- curl -fsS --max-time 10 -o /dev/null -X POST \+ local url="${GITHUB_SERVER_URL:-https://github.com}/${GITHUB_REPOSITORY:-}/actions/runs/${GITHUB_RUN_ID:-}" code rc+ code=$(curl -sS --max-time 10 -o /dev/null -w '%{http_code}' -X POST \-H "Authorization: Bearer ${GH_TOKEN:-}" -H 'Accept: application/vnd.github+json' \"${GITHUB_API_URL:-https://api.github.com}/repos/${GITHUB_REPOSITORY:-}/statuses/${GBRAIN_HEARTBEAT_SHA:-}" \- -d "{\"state\":\"$1\",\"context\":\"$CONTEXT\",\"description\":\"$2\",\"target_url\":\"$url\"}" >/dev/null 2>&1+ -d "{\"state\":\"$1\",\"context\":\"$CONTEXT\",\"description\":\"$2\",\"target_url\":\"$url\"}" 2>/dev/null)+ rc=$?+ case "$code" in 2[0-9][0-9]) [ "$rc" = 0 ] && return 0 ;; esac+ echo "heartbeat: $1 post failed (curl exit $rc, HTTP ${code:-000})" >&2+ return 1}loop() {diff --git a/test/scripts/data-safety-native-workflow.test.ts b/test/scripts/data-safety-native-workflow.test.tsindex 725b54e9d5..2a0b1a6062 100644--- a/test/scripts/data-safety-native-workflow.test.ts+++ b/test/scripts/data-safety-native-workflow.test.ts@@ -57,7 +57,22 @@ describe('data-safety native CI coverage', () => {const caller = (load(readFileSync(join(import.meta.dir, '../../.github/workflows/test.yml'), 'utf8')) as {jobs: Record<string, { uses?: string; permissions?: Record<string, string> }> }).jobs['native-locks']!;expect(caller.uses).toBe('./.github/workflows/native-locks.yml');- expect(caller.permissions).toEqual({ contents: 'read', statuses: 'write' });+ expect(caller.permissions).toEqual({ actions: 'read', contents: 'read', statuses: 'write' });+ });++ test('a Linux job after every cell finalizes a darwin-x64 heartbeat its cell left pending, never on a fork pull request', () => {+ const finalize = (workflow.jobs as unknown as Record<string, { needs: string[]; if: string; 'runs-on': string; permissions: Record<string, string>; steps: Step[] }>)['heartbeat-finalize']!;+ expect(finalize.needs).toEqual(['native']);+ expect(finalize.if).toBe("${{ always() && inputs.scope != 'smoke' }}");+ expect(finalize['runs-on']).toBe('ubicloud-standard-2-ubuntu-2404');+ expect(finalize.permissions).toEqual({ actions: 'read', contents: 'read', statuses: 'write' });+ const step = finalize.steps.at(-1)!;+ expect(step).toEqual({ name: 'Finalize darwin-x64 heartbeats left pending', run: 'bun scripts/native/heartbeat-finalize.ts', env: {+ GH_TOKEN: '${{ github.token }}',+ GBRAIN_HEARTBEAT_ENABLED: "${{ (github.event.pull_request.head.repo.full_name || github.repository) == github.repository && '1' || '0' }}",+ GBRAIN_HEARTBEAT_SHA: '${{ github.event.pull_request.head.sha || github.sha }}',+ } });+ for (const other of finalize.steps.slice(0, -1)) expect(JSON.stringify(other)).not.toContain('github.token');});test('the opt-in console diagnostic has an isolated Windows matrix without filtering the acceptance suites', () => {diff --git a/test/scripts/native-heartbeat-finalize.test.ts b/test/scripts/native-heartbeat-finalize.test.tsnew file mode 100644index 0000000000..8f00952b66--- /dev/null+++ b/test/scripts/native-heartbeat-finalize.test.ts@@ -0,0 +1,140 @@+/**+ * scripts/native/heartbeat-finalize.ts: the Linux watcher that ends a darwin-x64 heartbeat its cell left pending. A fake+ * GitHub API (Bun.serve) answers the run's jobs and the commit's statuses and records every status post; the end-to-end+ * case drives scripts/native/heartbeat.sh with the real curl against the same fake, which refuses the cell's (curl's)+ * terminal post the way an unreachable API does, and only that one.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join, resolve } from 'path';++const FINALIZE = resolve(import.meta.dir, '../../scripts/native/heartbeat-finalize.ts');+const HEARTBEAT = resolve(import.meta.dir, '../../scripts/native/heartbeat.sh');+const TOKEN = 'ghs_fake_token_example';+const roots: string[] = [];+afterAll(() => { for (const root of roots) rmSync(root, { recursive: true, force: true }); });++type Status = { state: string; context: string; description: string; target_url?: string; created_at: string };+type Job = { name: string; status: string; conclusion: string | null; html_url: string };++function fakeGitHub(jobs: Job[], seed: Status[] = [], opts: { failPosts?: (body: Status, agent: string) => number | null } = {}) {+ const statuses: Status[] = [...seed];+ const posts: Status[] = [];+ const auth: string[] = [];+ let clock = Date.parse('2026-10-24T21:46:48Z');+ const server = Bun.serve({ port: 0, async fetch(request) {+ const url = new URL(request.url);+ auth.push(request.headers.get('authorization') ?? '');+ if (url.pathname === '/repos/owner-example/repo-example/actions/runs/42/jobs') {+ expect(url.searchParams.get('filter')).toBe('latest');+ return Response.json({ total_count: jobs.length, jobs });+ }+ if (url.pathname === '/repos/owner-example/repo-example/commits/abc123/statuses') {+ const page = Number(url.searchParams.get('page') ?? 1), per = Number(url.searchParams.get('per_page') ?? 30);+ return Response.json([...statuses].reverse().slice((page - 1) * per, page * per));+ }+ if (url.pathname === '/repos/owner-example/repo-example/statuses/abc123' && request.method === 'POST') {+ const body = await request.json() as Status;+ const code = opts.failPosts?.(body, request.headers.get('user-agent') ?? '') ?? null;+ if (code) return new Response('unavailable', { status: code });+ const status = { ...body, created_at: new Date(clock += 1000).toISOString() };+ statuses.push(status); posts.push(status);+ return Response.json(status, { status: 201 });+ }+ return new Response('not found', { status: 404 });+ } });+ return { server, posts, statuses, auth, api: `http://127.0.0.1:${server.port}`, latest: (context: string) => [...statuses].reverse().find(s => s.context === context) };+}++const env = (api: string, extra: Record<string, string> = {}) => ({ PATH: process.env.PATH ?? '', HOME: tmpdir(), GH_TOKEN: TOKEN,+ GITHUB_REPOSITORY: 'owner-example/repo-example', GITHUB_RUN_ID: '42', GITHUB_API_URL: api, GBRAIN_HEARTBEAT_SHA: 'abc123',+ GBRAIN_HEARTBEAT_ENABLED: '1', GBRAIN_HEARTBEAT_FINALIZE_BACKOFF_MS: '10', ...extra });+// Async spawns: the fake API answers on this process's event loop, which a spawnSync would block.+async function spawn(argv: string[], vars: Record<string, string>) {+ const child = Bun.spawn(argv, { env: vars, stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);+ return { exitCode, stdout, stderr, out: stdout + stderr };+}+const finalize = (api: string, extra?: Record<string, string>) => spawn(['bun', FINALIZE], env(api, extra));+const cellJob = (bun: string, conclusion = 'success', status = 'completed'): Job =>+ ({ name: `native-locks / darwin-x64 / Bun ${bun}`, status, conclusion, html_url: `https://github.com/owner-example/repo-example/actions/runs/42/job/${bun}` });+const pending = (bun: string, at: string): Status =>+ ({ state: 'pending', context: `diag/native-heartbeat/darwin-x64/${bun}`, description: `darwin-x64/${bun} backup-portability-native.serial.test.ts 32s`, created_at: at });++describe('darwin-x64 heartbeat finalize (the Linux watcher)', () => {+ test('a cell whose terminal post never landed is finalized success, naming its real conclusion and last heartbeat', async () => {+ const gh = fakeGitHub([cellJob('1.4.4'), cellJob('1.4.0', 'failure'), { name: 'native-locks / linux-x64-glibc / Bun 1.4.4', status: 'completed', conclusion: 'success', html_url: 'x' }],+ [pending('1.4.4', '2026-10-24T21:46:48Z'), pending('1.4.0', '2026-10-24T21:50:01Z')]);+ try {+ const run = await finalize(gh.api);+ expect(run.exitCode).toBe(0);+ expect(gh.posts).toHaveLength(2);+ expect(gh.latest('diag/native-heartbeat/darwin-x64/1.4.4')).toMatchObject({ state: 'success',+ description: 'darwin-x64/1.4.4 finished success | finalized by the watcher job; last heartbeat 21:46:48Z',+ target_url: 'https://github.com/owner-example/repo-example/actions/runs/42/job/1.4.4' });+ expect(gh.latest('diag/native-heartbeat/darwin-x64/1.4.0')!.description).toStartWith('darwin-x64/1.4.0 finished failure | ');+ for (const post of gh.posts) { expect(post.description.length).toBeLessThanOrEqual(140); expect(post.description).not.toContain(TOKEN); }+ expect(gh.auth.every(header => header === `Bearer ${TOKEN}`)).toBe(true);+ expect(run.out).not.toContain(TOKEN);+ } finally { gh.server.stop(true); }+ });++ test('a context the cell finished itself, one it never posted, and a cell still running are left alone', async () => {+ const done: Status = { state: 'success', context: 'diag/native-heartbeat/darwin-x64/1.4.4', description: 'darwin-x64/1.4.4 finished success | free 89%', created_at: '2026-10-24T21:47:30Z' };+ const gh = fakeGitHub([cellJob('1.4.4'), cellJob('1.4.0'), cellJob('1.4.9', null as never, 'in_progress')],+ [pending('1.4.4', '2026-10-24T21:46:48Z'), done, pending('1.4.9', '2026-10-24T21:47:00Z')]);+ try {+ expect((await finalize(gh.api)).exitCode).toBe(0);+ expect(gh.posts).toEqual([]);+ } finally { gh.server.stop(true); }+ });++ test('finds the cell context past the first page of statuses', async () => {+ const noise = Array.from({ length: 150 }, (_, i): Status => ({ state: 'success', context: `ci/other-${i}`, description: 'x', created_at: '2026-10-24T21:00:00Z' }));+ const gh = fakeGitHub([cellJob('1.4.4')], [pending('1.4.4', '2026-10-24T21:46:48Z'), ...noise]);+ try {+ expect((await finalize(gh.api)).exitCode).toBe(0);+ expect(gh.latest('diag/native-heartbeat/darwin-x64/1.4.4')!.state).toBe('success');+ } finally { gh.server.stop(true); }+ });++ test('a post the API keeps refusing is retried three times, then warns without failing the job', async () => {+ let tries = 0;+ const gh = fakeGitHub([cellJob('1.4.4')], [pending('1.4.4', '2026-10-24T21:46:48Z')], { failPosts: () => { tries++; return 503; } });+ try {+ const run = await finalize(gh.api);+ expect(run.exitCode).toBe(0);+ expect(tries).toBe(3);+ expect(run.out).toContain('::warning::darwin-x64 heartbeat finalize: POST /repos/owner-example/repo-example/statuses/abc123 failed: HTTP 503');+ } finally { gh.server.stop(true); }+ });++ test('does nothing when disabled (a fork pull request)', async () => {+ const gh = fakeGitHub([cellJob('1.4.4')], [pending('1.4.4', '2026-10-24T21:46:48Z')]);+ try {+ expect((await finalize(gh.api, { GBRAIN_HEARTBEAT_ENABLED: '0' })).exitCode).toBe(0);+ expect(gh.auth).toEqual([]);+ } finally { gh.server.stop(true); }+ });++ test('end to end: the cell terminal post fails every attempt and stays pending, then the watcher ends it on the real conclusion', async () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-heartbeat-finalize-'));+ roots.push(root);+ const gh = fakeGitHub([cellJob('1.4.4')], [], { failPosts: (body, agent) => body.state === 'success' && agent.startsWith('curl/') ? 503 : null });+ const cellEnv = env(gh.api, { GBRAIN_HEARTBEAT_CELL: 'darwin-x64/1.4.4', GBRAIN_HEARTBEAT_DIR: join(root, 'state'), GBRAIN_HEARTBEAT_INTERVAL_S: '1' });+ const heartbeat = (args: string[]) => spawn(['bash', HEARTBEAT, ...args], cellEnv);+ try {+ expect((await heartbeat(['start'])).exitCode).toBe(0);+ await Bun.sleep(1500);+ const stop = await heartbeat(['stop', 'success']);+ expect(stop.exitCode).toBe(0);+ expect(stop.stderr.match(/heartbeat: success post failed \(curl exit 0, HTTP 503\)/g)).toHaveLength(3);+ expect(gh.latest('diag/native-heartbeat/darwin-x64/1.4.4')!.state).toBe('pending');+ expect((await finalize(gh.api)).exitCode).toBe(0);+ const final = gh.latest('diag/native-heartbeat/darwin-x64/1.4.4')!;+ expect(final.state).toBe('success');+ expect(final.description).toMatch(/^darwin-x64\/1\.4\.4 finished success \| finalized by the watcher job; last heartbeat \d\d:\d\d:\d\dZ$/);+ } finally { await heartbeat(['stop', 'success']); gh.server.stop(true); }+ }, 30_000);+});diff --git a/test/scripts/native-heartbeat.test.ts b/test/scripts/native-heartbeat.test.tsindex a01e0dbe2b..7a9d240bca 100644--- a/test/scripts/native-heartbeat.test.ts+++ b/test/scripts/native-heartbeat.test.ts@@ -25,11 +25,12 @@ function sandbox() {// a number in <root>/fail-success makes that many success posts fail the way a timed-out curl does.writeFileSync(join(bin, 'curl'), `#!/usr/bin/env bashurl="" data=""-while [ $# -gt 0 ]; do case "$1" in -d) data="$2"; shift 2 ;; -H|-o|-X|--max-time) shift 2 ;; -*) shift ;; *) url="$1"; shift ;; esac; done+while [ $# -gt 0 ]; do case "$1" in -d) data="$2"; shift 2 ;; -H|-o|-X|-w|--max-time) shift 2 ;; -*) shift ;; *) url="$1"; shift ;; esac; donecase "$data" in *'"state":"pending"'*) sleep "\${CURL_PENDING_DELAY_S:-0}" ;; esacfails=$(cat "${root}/fail-success" 2>/dev/null || echo 0)case "$data" in *'"state":"success"'*) if [ "$fails" -gt 0 ]; then echo $((fails - 1)) > "${root}/fail-success"; exit 28; fi ;; esacprintf '{"url":"%s","body":%s}\\n' "$url" "$data" >> "${log}"+printf 200`);chmodSync(join(bin, 'curl'), 0o755);const env = (extra: Record<string, string> = {}): Record<string, string> => ({