Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ci: darwin-x64 posts a diag/native-heartbeat commit status that survives a wedged runner
garrytan00bb80d9f339
diff --git a/.github/workflows/native-locks.yml b/.github/workflows/native-locks.ymlindex ee5b2b9c28..10d239e5cd 100644--- a/.github/workflows/native-locks.yml+++ b/.github/workflows/native-locks.yml@@ -63,6 +63,10 @@ jobs:name: ${{ matrix.target }} / Bun ${{ matrix.bun }}runs-on: ${{ fromJSON('{"linux-x64-glibc":"ubicloud-standard-4-ubuntu-2404","linux-arm64-glibc":"ubicloud-standard-4-arm-ubuntu-2404","darwin-arm64":"macos-26","darwin-x64":"macos-26-intel","win32-x64":"windows-2022","win32-arm64":"windows-11-arm"}')[matrix.target] }}timeout-minutes: 15+ # statuses: the darwin-x64 heartbeat below (one commit status context, diag/native-heartbeat).+ permissions:+ contents: read+ statuses: writestrategy:fail-fast: falsematrix:@@ -78,6 +82,18 @@ jobs:shell: bashrun: echo "GBRAIN_JOB_DEADLINE=$(( $(date +%s) + 15 * 60 ))" >> "$GITHUB_ENV"- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262+ # A wedged darwin-x64 runner uploads no log at all (#7457's cell, #7419, #7303, #7238), so a background loop posts+ # the current step or suite, free memory, swap, load and the busiest process names as the commit status+ # diag/native-heartbeat; GitHub keeps every status, so the last one before a wedge survives it. Nothing on a+ # fork's pull request, whose token cannot write.+ - name: Start the diagnostic heartbeat+ if: matrix.target == 'darwin-x64'+ 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 }}+ GBRAIN_HEARTBEAT_CELL: ${{ matrix.target }}/${{ matrix.bun }}+ run: bash scripts/native/heartbeat.sh start- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6with:bun-version: ${{ matrix.bun }}@@ -140,6 +156,7 @@ jobs:local left=$((stop_at - $(date +%s)))if [ "$left" -le 0 ]; then echo "::error::$1 not run: the job timeout is near"; return 1; filocal limit=$((left < bound_s ? left : bound_s))+ GBRAIN_HEARTBEAT_ENABLED=1 bash scripts/native/heartbeat.sh mark "$1" || truebun --no-env-file test --timeout=180000 "$1" &pid=$!for _ in $(seq 1 "$limit"); do@@ -174,6 +191,16 @@ jobs:fibun scripts/native/compiled-smoke.ts --binary bin/gbrain-native-validationbun scripts/native/cli-persistence-smoke.ts --binary bin/gbrain-native-validation+ # The terminal status, naming the job result: a run that ends, even cancelled, leaves nothing pending; a machine+ # that dies keeps its last heartbeat.+ - name: Stop the diagnostic heartbeat+ if: always() && matrix.target == 'darwin-x64'+ 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 }}+ GBRAIN_HEARTBEAT_CELL: ${{ matrix.target }}/${{ matrix.bun }}+ run: bash scripts/native/heartbeat.sh stop "${{ job.status }}"windows-backup-console:name: Windows PowerShell console probe / ${{ matrix.runner }} / Bun ${{ matrix.bun }}diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 28f3d46a2f..9d0360e326 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -1049,6 +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 cell's diag/native-heartbeat commit status (native-locks.yml).+ permissions:+ contents: read+ statuses: writewith:scope: ${{ needs.changes.outputs.native-scope }}diff --git a/scripts/native/heartbeat.sh b/scripts/native/heartbeat.shnew file mode 100755index 0000000000..6396327d46--- /dev/null+++ b/scripts/native/heartbeat.sh@@ -0,0 +1,104 @@+#!/usr/bin/env bash+# scripts/native/heartbeat.sh: the darwin-x64 native-locks heartbeat.+#+# A wedged macOS runner uploads no log at all, not even for the steps that passed, so while the job runs a background+# loop posts its state as the commit status `diag/native-heartbeat`. GitHub keeps every status a commit receives, so the+# last one before a wedge shows what was running. A status carries only the cell, the current step or suite and its+# elapsed seconds, free memory, swap in use, the load average and the busiest process names; never the environment.+#+# heartbeat.sh start start the loop (it posts on every label change and every GBRAIN_HEARTBEAT_INTERVAL_S)+# heartbeat.sh mark LABEL the current step or suite; needs no token, the loop posts it+# heartbeat.sh stop RESULT end the loop and post the terminal `success` status, so nothing is left pending+# heartbeat.sh describe print the description the next status would carry+#+# start and stop read GH_TOKEN, GITHUB_REPOSITORY, GBRAIN_HEARTBEAT_SHA and GBRAIN_HEARTBEAT_CELL. Every command does+# nothing unless GBRAIN_HEARTBEAT_ENABLED=1 (the workflow sets 0 for a fork's pull request, whose token cannot write).+# bash 3.2 compatible.+set -u++CONTEXT='diag/native-heartbeat'+dir="${GBRAIN_HEARTBEAT_DIR:-${RUNNER_TEMP:-/tmp}/gbrain-native-heartbeat}"+interval="${GBRAIN_HEARTBEAT_INTERVAL_S:-30}"++safe() { tr -cd 'A-Za-z0-9._/-' | cut -c1-"$1"; }++mem_free_pct() {+ if command -v memory_pressure >/dev/null 2>&1; then+ memory_pressure -Q 2>/dev/null | awk -F': *' '/free percentage/ { gsub(/%/, "", $2); print $2; exit }'+ elif [ -r /proc/meminfo ]; then+ awk '/^MemTotal:/ { t = $2 } /^MemAvailable:/ { a = $2 } END { if (t) printf "%d", a * 100 / t }' /proc/meminfo+ fi+}++swap_used() {+ if [ "$(uname)" = Darwin ]; then+ sysctl -n vm.swapusage 2>/dev/null | awk '{ for (i = 1; i < NF; i++) if ($i == "used") { print $(i + 2); exit } }'+ elif [ -r /proc/meminfo ]; then+ awk '/^SwapTotal:/ { t = $2 } /^SwapFree:/ { f = $2 } END { printf "%dM", (t - f) / 1024 }' /proc/meminfo+ fi+}++load_1m() {+ if [ "$(uname)" = Darwin ]; then sysctl -n vm.loadavg 2>/dev/null | awk '{ print $2 }'+ elif [ -r /proc/loadavg ]; then awk '{ print $1 }' /proc/loadavg+ fi+}++top_names() {+ ps -A -o %cpu= -o comm= 2>/dev/null | sort -rn | head -3 | awk '{ $1 = ""; n = split($0, p, "/"); name = p[n];+ gsub(/[^A-Za-z0-9._-]/, "", name); printf "%s%s", sep, substr(name, 1, 24); sep = "," }'+}++describe() {+ local label since now cell+ label=$(cat "$dir/label" 2>/dev/null || echo setup)+ since=$(cat "$dir/since" 2>/dev/null || date +%s)+ now=$(date +%s)+ cell=$(printf '%s' "${GBRAIN_HEARTBEAT_CELL:-}" | safe 32)+ printf '%s %s %ss | free %s%% | swap %s | load %s | top %s' "$cell" "$(printf '%s' "${label##*/}" | safe 48)" "$((now - since))" \+ "$(mem_free_pct)" "$(swap_used)" "$(load_1m)" "$(top_names)" | tr -cd 'A-Za-z0-9 ._/|%:,=+-' | cut -c1-140+}++post() {+ local url="${GITHUB_SERVER_URL:-https://github.com}/${GITHUB_REPOSITORY:-}/actions/runs/${GITHUB_RUN_ID:-}"+ curl -sS --max-time 10 -o /dev/null -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 || true+}++loop() {+ local end last="" label next=0 now+ end=$(( ${GBRAIN_JOB_DEADLINE:-$(( $(date +%s) + 1200 ))} + 300 ))+ while [ ! -e "$dir/stopped" ] && [ "$(date +%s)" -lt "$end" ]; do+ label=$(cat "$dir/label" 2>/dev/null)+ now=$(date +%s)+ if [ "$label" != "$last" ] || [ "$now" -ge "$next" ]; then+ post pending "$(describe)"+ last=$label+ next=$((now + interval))+ fi+ sleep 2+ done+}++[ "${GBRAIN_HEARTBEAT_ENABLED:-0}" = 1 ] || exit 0+case "${1:-}" in+ start)+ mkdir -p "$dir" && rm -f "$dir/stopped"+ echo setup > "$dir/label"; date +%s > "$dir/since"+ loop </dev/null >/dev/null 2>&1 &+ echo $! > "$dir/pid"+ ;;+ mark)+ mkdir -p "$dir"+ printf '%s\n' "${2:-}" > "$dir/label"; date +%s > "$dir/since"+ ;;+ stop)+ touch "$dir/stopped"+ pid=$(cat "$dir/pid" 2>/dev/null) && kill "$pid" 2>/dev/null+ post success "$(printf '%s finished %s |%s' "$(printf '%s' "${GBRAIN_HEARTBEAT_CELL:-}" | safe 32)" "$(printf '%s' "${2:-}" | safe 16)" "$(describe | cut -d'|' -f2-)" | cut -c1-140)"+ ;;+ describe) describe; echo ;;+ *) echo "usage: heartbeat.sh start | mark LABEL | stop RESULT | describe" >&2; exit 2 ;;+esacdiff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 9f45d65411..0db60ce761 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -307,7 +307,7 @@ test/scripts/ci-runner-routing.test.ts CI runner routing 7 readFileSynctest/scripts/classify-tests.test.ts classify-tests detectors 23 bun-file,doctor-source-helper,exec-scan,readFileSync,source-surface-helpertest/scripts/classify-tests.test.ts structural-suites manifest 1 readFileSynctest/scripts/coverage-diff-gate.test.ts exemptions 3 readFileSync-test/scripts/data-safety-native-workflow.test.ts data-safety native CI coverage 20 readFileSync+test/scripts/data-safety-native-workflow.test.ts data-safety native CI coverage 21 readFileSynctest/scripts/e2e-backend-matrix.test.ts scripts/e2e-backend-matrix.txt 3 readFileSynctest/scripts/e2e-live-key-only.test.ts shared live-key E2E exclusion list 4 readFileSynctest/scripts/e2e-matrix.test.ts frozen E2E matrix 9 readFileSyncdiff --git a/test/scripts/data-safety-native-workflow.test.ts b/test/scripts/data-safety-native-workflow.test.tsindex 094f019664..725b54e9d5 100644--- a/test/scripts/data-safety-native-workflow.test.ts+++ b/test/scripts/data-safety-native-workflow.test.ts@@ -34,6 +34,32 @@ const suites = [];describe('data-safety native CI coverage', () => {+ test('the darwin-x64 cell posts diag/native-heartbeat statuses from its first step to its last, never on a fork pull request', () => {+ const job = workflow.jobs.native as typeof workflow.jobs.native & { permissions?: Record<string, string> };+ expect(job.permissions).toEqual({ contents: 'read', statuses: 'write' });+ const names = job.steps.map(step => step.name ?? step.uses ?? '');+ const start = job.steps.findIndex(step => step.name === 'Start the diagnostic heartbeat');+ const stop = job.steps.findIndex(step => step.name === 'Stop the diagnostic heartbeat');+ expect(names[start - 1]).toStartWith('actions/checkout@');+ expect(stop).toBe(job.steps.length - 1);+ const 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 }}',+ GBRAIN_HEARTBEAT_CELL: '${{ matrix.target }}/${{ matrix.bun }}',+ };+ expect(job.steps[start]).toEqual({ name: 'Start the diagnostic heartbeat', if: "matrix.target == 'darwin-x64'", env, run: 'bash scripts/native/heartbeat.sh start' });+ expect(job.steps[stop]).toEqual({ name: 'Stop the diagnostic heartbeat', if: "always() && matrix.target == 'darwin-x64'", env,+ run: 'bash scripts/native/heartbeat.sh stop "${{ job.status }}"' });+ for (const step of job.steps) if (step !== job.steps[start] && step !== job.steps[stop]) expect(JSON.stringify(step)).not.toContain('github.token');+ const safety = job.steps.find(entry => entry.name === 'Verify native data-safety contracts')!;+ expect(safety.run).toContain(' GBRAIN_HEARTBEAT_ENABLED=1 bash scripts/native/heartbeat.sh mark "$1" || true\n bun --no-env-file test --timeout=180000 "$1" &');+ 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' });+ });+test('the opt-in console diagnostic has an isolated Windows matrix without filtering the acceptance suites', () => {const job = workflow.jobs['windows-backup-console'];expect(job['runs-on']).toBe('${{ matrix.runner }}');diff --git a/test/scripts/native-heartbeat.test.ts b/test/scripts/native-heartbeat.test.tsnew file mode 100644index 0000000000..62b761cbd4--- /dev/null+++ b/test/scripts/native-heartbeat.test.ts@@ -0,0 +1,89 @@+/**+ * scripts/native/heartbeat.sh: the darwin-x64 native-locks heartbeat. A wedged macOS runner uploads no log, so the job+ * posts its state as the commit status diag/native-heartbeat while it runs. A fake curl on PATH records every post.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join, resolve } from 'path';++const SCRIPT = resolve(import.meta.dir, '../../scripts/native/heartbeat.sh');+const SECRET = 'planted-secret-value-example';+const TOKEN = 'ghs_fake_token_example';+const roots: string[] = [];+afterAll(() => { for (const root of roots) rmSync(root, { recursive: true, force: true }); });++type Post = { url: string; state: string; context: string; description: string; target_url: string };++function sandbox() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-heartbeat-'));+ roots.push(root);+ const bin = join(root, 'bin');+ const log = join(root, 'posts.ndjson');+ Bun.spawnSync(['mkdir', '-p', bin]);+ writeFileSync(join(bin, 'curl'), `#!/usr/bin/env bash+url="" 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+printf '{"url":"%s","body":%s}\\n' "$url" "$data" >> "${log}"+`);+ chmodSync(join(bin, 'curl'), 0o755);+ const env = (extra: Record<string, string> = {}): Record<string, string> => ({+ PATH: `${bin}:${process.env.PATH}`, HOME: root, GH_TOKEN: TOKEN, GITHUB_REPOSITORY: 'owner-example/repo-example', GITHUB_RUN_ID: '42',+ GBRAIN_HEARTBEAT_SHA: 'abc123', GBRAIN_HEARTBEAT_CELL: 'darwin-x64/1.4.4', GBRAIN_HEARTBEAT_DIR: join(root, 'state'),+ GBRAIN_HEARTBEAT_INTERVAL_S: '1', GBRAIN_HEARTBEAT_ENABLED: '1', GBRAIN_PLANTED_SECRET: SECRET, ...extra,+ });+ const run = (args: string[], extra?: Record<string, string>) => Bun.spawnSync(['bash', SCRIPT, ...args], { env: env(extra), stdout: 'pipe', stderr: 'pipe' });+ const posts = (): Post[] => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').filter(Boolean).map(line => {+ const { url, body } = JSON.parse(line) as { url: string; body: Omit<Post, 'url'> };+ return { url, ...body };+ }) : [];+ return { root, run, posts };+}++const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };++describe('native heartbeat (diag/native-heartbeat)', () => {+ test('posts pending heartbeats naming the current suite, then one terminal success, all on one context with no secret', async () => {+ const box = sandbox();+ expect(box.run(['start']).exitCode).toBe(0);+ const pid = Number(readFileSync(join(box.root, 'state', 'pid'), 'utf8'));+ expect(box.run(['mark', 'test/backup-portability-native.serial.test.ts']).exitCode).toBe(0);+ await Bun.sleep(3500);+ expect(box.run(['stop', 'success']).exitCode).toBe(0);+ await Bun.sleep(500);+ expect(alive(pid)).toBe(false);+ const posts = box.posts();+ expect(posts.length).toBeGreaterThanOrEqual(3);+ for (const post of posts) {+ expect(post.context).toBe('diag/native-heartbeat');+ expect(post.url).toBe('https://api.github.com/repos/owner-example/repo-example/statuses/abc123');+ expect(post.target_url).toBe('https://github.com/owner-example/repo-example/actions/runs/42');+ expect(post.description.length).toBeLessThanOrEqual(140);+ expect(post.description).not.toContain(SECRET);+ expect(post.description).not.toContain(TOKEN);+ expect(post.description).toMatch(/^darwin-x64\/1\.4\.4 /);+ expect(post.description).toMatch(/\| free \d*% \| swap \S* \| load \S* \| top /);+ }+ expect(posts.slice(0, -1).every(post => post.state === 'pending')).toBe(true);+ expect(posts.some(post => post.description.includes(' backup-portability-native.serial.test.ts '))).toBe(true);+ expect(posts.at(-1)!.state).toBe('success');+ expect(posts.at(-1)!.description).toMatch(/^darwin-x64\/1\.4\.4 finished success \| /);+ }, 30_000);++ test('does nothing when disabled (a fork pull request)', async () => {+ const box = sandbox();+ for (const args of [['start'], ['mark', 'test/x.test.ts'], ['stop', 'success']]) expect(box.run(args, { GBRAIN_HEARTBEAT_ENABLED: '0' }).exitCode).toBe(0);+ await Bun.sleep(1500);+ expect(box.posts()).toEqual([]);+ expect(existsSync(join(box.root, 'state'))).toBe(false);+ }, 30_000);++ test('the loop ends on its own past the job deadline', async () => {+ const box = sandbox();+ expect(box.run(['start'], { GBRAIN_JOB_DEADLINE: String(Math.floor(Date.now() / 1000) - 400) }).exitCode).toBe(0);+ const pid = Number(readFileSync(join(box.root, 'state', 'pid'), 'utf8'));+ await Bun.sleep(1000);+ expect(alive(pid)).toBe(false);+ expect(box.posts()).toEqual([]);+ }, 30_000);+});