Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(eval): stop guarded evaluations with their whole process group (#6776)
garrytan2ffe358d34da
diff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.mdindex d26f93d0eb..d995ead0e4 100644--- a/docs/architecture/key-files/tooling-and-tests.md+++ b/docs/architecture/key-files/tooling-and-tests.md@@ -49,7 +49,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `.github/workflows/e2e.yml` + `scripts/verify-nightly-e2e.ts` — full E2E discovery runs on four weighted, independent Postgres workers, sequential fresh Bun processes within each. Schedules and explicit default-false `full_corpus` manual dispatches share the same full-profile jobs, aggregation, reports and receipts; ordinary selection is unchanged and full manual runs have their own concurrency group. Each worker bootstraps its guarded service schema through `setupLegacyEmbeddingDB()` under a keyless temporary home before tests. No selected-lane exclusions apply. Workers publish distinct `e2e-N` coverage manifests and successful executed-file receipts; full-profile `e2e-status` requires successful job results plus exact, disjoint, same-commit partitions. The advisory report validates those receipts before merging all four multi-file LCOV lanes. Coverage count is not executed-file count: skip-only files may emit no LCOV. `test/scripts/nightly-e2e.test.ts`, `e2e-runner.test.ts`, `ci-gates.test.ts` and `merge-lcov.test.ts` pin discovery, isolation, failure/cancellation, artifacts and completeness. See docs/TESTING.md for cross-lane coverage responsibilities.-- `scripts/eval-spend-guard.sh` — hard spend cap for paid eval runs: `scripts/eval-spend-guard.sh <cap_usd> <estimate_usd> -- <command...>`. INVARIANT: a paid command never launches when ledger total + estimate would exceed the cap, and every launch is appended to the ledger whether or not it succeeded, so the running total can only under-state spend if the command itself lies about its cost. FAILS CLOSED on anything it cannot account for: a missing ledger (a missing file is NOT a $0 ledger — the first run sets `GBRAIN_EVAL_SPEND_LEDGER_INIT=1`, which prints a loud NEW LEDGER line), an unparseable ledger line (named by line number), a signed or malformed amount (a negative estimate would drive the ledger backwards). Ledger `$GBRAIN_EVAL_SPEND_LEDGER` (default `~/gbrain-lme-receipts/spend.jsonl`): every launch writes TWO rows sharing a `run_id` — a `status: running` reservation appended BEFORE the command starts (cost = the estimate, so a concurrent guard already counts it) and a `status: done` reconciliation after it exits (actual cost, exit code); the sum is reconciled rows + unreconciled reservations, so a guard killed by INT/TERM/HUP (trap-reconciled at the estimate) or SIGKILL (reservation left standing) never under-counts, and an unwritable ledger refuses the launch — the child gets TERM, then KILL after `GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS` (default 10). Legacy single-row lines `{ts, estimate_usd, cost_usd, exit_code, command}` still count. The recorded cost comes from `$GBRAIN_EVAL_ACTUAL_COST_FILE` (exported to the child as a scratch path when unset; bare unsigned number or JSON with `cost_usd`) only when positive, else the estimate (over-stating is the safe direction). Amounts normalize to `%.6f`; awk/grep/sed only — no jq or bun at runtime. Exit: the wrapped command's code · 2 usage · 3 refused. Pinned by `test/eval-spend-guard.test.ts`.+- `scripts/eval-spend-guard.sh` — hard spend cap for paid eval runs: `scripts/eval-spend-guard.sh <cap_usd> <estimate_usd> -- <command...>`. INVARIANT: a paid command never launches when ledger total + estimate would exceed the cap, and every launch is appended to the ledger whether or not it succeeded, so the running total can only under-state spend if the command itself lies about its cost. FAILS CLOSED on anything it cannot account for: a missing ledger (a missing file is NOT a $0 ledger — the first run sets `GBRAIN_EVAL_SPEND_LEDGER_INIT=1`, which prints a loud NEW LEDGER line), an unparseable ledger line (named by line number), a signed or malformed amount (a negative estimate would drive the ledger backwards). Ledger `$GBRAIN_EVAL_SPEND_LEDGER` (default `~/gbrain-lme-receipts/spend.jsonl`): every launch writes TWO rows sharing a `run_id` — a `status: running` reservation appended BEFORE the command starts (cost = the estimate, so a concurrent guard already counts it) and a `status: done` reconciliation after it exits (actual cost, exit code); the sum is reconciled rows + unreconciled reservations, so a guard killed by INT/TERM/HUP (trap-reconciled at the estimate) or SIGKILL (reservation left standing) never under-counts, and an unwritable ledger refuses the launch — the command's process group gets TERM, then KILL after `GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS` (default 10); terminal stdin is EOF. Legacy single-row lines `{ts, estimate_usd, cost_usd, exit_code, command}` still count. The recorded cost comes from `$GBRAIN_EVAL_ACTUAL_COST_FILE` (exported to the child as a scratch path when unset; bare unsigned number or JSON with `cost_usd`) only when positive, else the estimate (over-stating is the safe direction). Amounts normalize to `%.6f`; awk/grep/sed only — no jq or bun at runtime. Exit: the wrapped command's code · 2 usage · 3 refused. Pinned by `test/eval-spend-guard.test.ts`.- `scripts/generate-plugin-tree.ts` + `scripts/check-plugin-tree.sh` + `plugin/` — generator, byte-diff drift gate (in the skills commit gate), and the committed curated skill tree both plugin lanes ship (70 skills + shared conventions/_*.md deps + a generated README carrying the CLI-primary starter note).diff --git a/docs/eval-bench.md b/docs/eval-bench.mdindex 3d50bdfe0d..9df85d3c74 100644--- a/docs/eval-bench.md+++ b/docs/eval-bench.md@@ -765,7 +765,15 @@ reader pins and the judge pins all land on one receipt.`--yes` (exit 2); at run time the lane soft-stops at the cap and stamps theremaining rows `judge_skipped: "budget"`. An unpriced judge model requires`--max-usd off`. Reader spend is not metered here — wrap a paid receipt in- `scripts/eval-spend-guard.sh`.+ `scripts/eval-spend-guard.sh`. The guard runs the command in its own+ process group and stops the whole group (helpers and grandchildren+ included) on interruption, after the kill grace, and when the command+ exits leaving processes behind. A process group cannot read the terminal,+ so a terminal stdin is replaced with EOF and the guard prints a notice;+ pipe or redirect input if the command needs any (piped and file stdin pass+ through). No eval entrypoint reads stdin; a TTY-only Ctrl-C grace window+ (such as `eval suspected-contradictions`' cost notice) proceeds as it does+ off a terminal, and Ctrl-C reaches the guard, which stops the run.Row fields with `--judge`: exactly one of `judge_correct` / `judge_error`(+ `judge_error_detail`) / `judge_skipped`, plus `judge_model`,diff --git a/scripts/eval-spend-guard.sh b/scripts/eval-spend-guard.shindex ddd3221984..d627d6b40d 100755--- a/scripts/eval-spend-guard.sh+++ b/scripts/eval-spend-guard.sh@@ -53,6 +53,17 @@# reservation stays on the books. Where `flock` exists, audit → cap check →# reservation is serialized across concurrent guards via <ledger>.lock.#+# Process groups (#6776): the command runs as a monitor-mode job (`set -m`),+# so it gets its own process group and every stop (a trapped signal, the kill+# grace, a normal exit that left helpers behind) signals the whole group, not+# just its leader; a grandchild that ignores SIGTERM is SIGKILLed with the rest.+# A background group cannot read the controlling terminal (SIGTTIN would stop+# it with the reservation open), so a TERMINAL stdin is replaced with EOF+# (/dev/null) and the guard says so; piped or file stdin is passed through+# unchanged. Interactive commands are not supported: pipe or redirect their+# input. (A terminal set to `stty tostop` also stops a background group that+# writes to it; redirect the command's output there.)+## The audit itself is fail-closed: a ledger that exists but cannot be read, an# awk that exits non-zero, or an audit line that is not `<int> <int> <decimal># <int> …` refuses the launch (exit 3) — an empty audit must never read as $0.@@ -252,26 +263,35 @@ reconcile() { # <cost> <exit_code>; returns 1 when the ledger append failsecho "eval-spend-guard: recorded cost \$${1} (exit $2); ledger now ${AFTER}" >&2}-# Stop the command: SIGTERM, then up to KILL_GRACE seconds (10 by default;-# GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS overrides) before SIGKILL, so a-# command that ignores SIGTERM cannot keep the guard — and its reservation —-# hanging forever. Polled in 0.1 s steps; `wait` reaps it either way.+# Stop the command's process group: SIGTERM, then up to KILL_GRACE seconds (10+# by default; GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS overrides) before+# SIGKILL, so a command (or a grandchild) that ignores SIGTERM cannot keep the+# guard — and its reservation — hanging forever, nor outlive it. Polled in+# 0.1 s steps; `wait` reaps the leader either way.KILL_GRACE="${GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS:-10}"case "$KILL_GRACE" in ''|*[!0-9]*) KILL_GRACE=10 ;; esac+group_alive() { # <pgid>; falls back to kill -0 where ps cannot list processes+ local all+ all="$(ps -A -o pid=,pgid=,stat= 2>/dev/null)" || { kill -0 -- "-$1" 2>/dev/null; return; }+ printf '%s\n' "$all" | awk -v g="$1" '$2 == g && $3 !~ /^Z/ { f = 1 } END { exit !f }'+}CHILD=""stop_child() {+ local i=0[ -n "$CHILD" ] || return 0- kill -TERM "$CHILD" 2>/dev/null- i=0- while [ "$i" -lt "$((KILL_GRACE * 10))" ] && kill -0 "$CHILD" 2>/dev/null; do- sleep 0.1- i=$((i + 1))- done- if kill -0 "$CHILD" 2>/dev/null; then- echo "eval-spend-guard: command did not exit within ${KILL_GRACE}s of SIGTERM — sending SIGKILL" >&2- kill -KILL "$CHILD" 2>/dev/null+ if group_alive "$CHILD"; then+ kill -TERM -- "-$CHILD" 2>/dev/null || kill -TERM "$CHILD" 2>/dev/null+ while [ "$i" -lt "$((KILL_GRACE * 10))" ] && group_alive "$CHILD"; do+ sleep 0.1+ i=$((i + 1))+ done+ if group_alive "$CHILD"; then+ echo "eval-spend-guard: command did not exit within ${KILL_GRACE}s of SIGTERM — sending SIGKILL" >&2+ kill -KILL -- "-$CHILD" 2>/dev/null || kill -KILL "$CHILD" 2>/dev/null+ fifiwait "$CHILD" 2>/dev/null+ CHILD=""}on_signal() { # <signal number>trap - INT TERM HUP@@ -282,6 +302,7 @@ on_signal() { # <signal number>}on_exit() { # <exit status>[ "$RESERVED" = "1" ] || return 0+ stop_childreconcile "$EST" "$1" || exit 3}# Traps BEFORE the reservation: a signal in the append→launch window must@@ -305,12 +326,30 @@ fiexec 9>&- # release the lock (if held) before the command startsecho "eval-spend-guard: reserved \$${EST} (run $RUN_ID)" >&2+# A background process group cannot read the controlling terminal (SIGTTIN+# would stop it with the reservation open), so a terminal stdin becomes EOF.+# Piped and file stdin pass through.+if [ -t 0 ]; then+ echo "eval-spend-guard: stdin is a terminal, which the command's own process group cannot read; its stdin is EOF (/dev/null). Pipe or redirect input if it needs any." >&2+ exec </dev/null+fi+# Run the command as a job so a trapped signal interrupts `wait` (a foreground# child would defer the trap until it exited). `<&0` keeps the child's stdin.+# Monitor mode gives the job its own process group (pgid = its pid) without an+# external setsid, which macOS does not ship.+set -m"$@" <&0 &CHILD=$!+set +mwait "$CHILD"CODE=$?+# Settle: anything the command left running in its group is stopped too.+if group_alive "$CHILD"; then+ echo "eval-spend-guard: the command exited but left processes in its process group; stopping them" >&2+ stop_child+fi+CHILD=""trap - INT TERM HUP# Actual cost: bare unsigned number or JSON with unsigned cost_usd, and itdiff --git a/test/eval-spend-guard.test.ts b/test/eval-spend-guard.test.tsindex 31f20001bf..e377ec1d08 100644--- a/test/eval-spend-guard.test.ts+++ b/test/eval-spend-guard.test.ts@@ -603,3 +603,103 @@ describe('eval-spend-guard.sh', () => {expect(ledgerRows().length).toBe(4);});});++// ---------------------------------------------------------------------------+// Process groups (#6776). The guarded command runs in its own process group:+// a signal, the kill grace or a normal exit stops every process in it.+// ---------------------------------------------------------------------------++/** Alive and not a zombie (an orphan's zombie is reaped by init shortly after). */+function alive(pid: number): boolean {+ if (!pid) return false;+ const state = spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf-8' }).stdout.trim();+ return state !== '' && !state.startsWith('Z');+}+async function waitDead(pid: number, ms = 5000): Promise<boolean> {+ const t0 = Date.now();+ while (alive(pid)) {+ if (Date.now() - t0 > ms) return false;+ await new Promise((r) => setTimeout(r, 50));+ }+ return true;+}+function readPid(file: string): number {+ return Number(readFileSync(file, 'utf-8').trim());+}+function killQuietly(...pids: number[]): void {+ for (const pid of pids) {+ if (!pid) continue;+ try { process.kill(-pid, 'SIGKILL'); } catch { /* not a group or gone */ }+ try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ }+ }+}+/** A TERM-ignoring grandchild that writes its pid, under a leader that writes its own. */+function groupCommand(leaderPid: string, kidPid: string, leaderSeconds = 30): string[] {+ return ['sh', '-c', 'echo $$ > "' + leaderPid + '"; sh -c \'trap "" TERM; echo $$ > "' + kidPid + '"; exec sleep 30\' & exec sleep ' + leaderSeconds];+}+describe('eval-spend-guard.sh process groups (#6776)', () => {+ test('a SIGTERMed guard stops the whole process group, including a grandchild that ignores SIGTERM (exit 143)', async () => {+ const leaderFile = join(dir, 'leader.pid');+ const kidFile = join(dir, 'kid.pid');+ const g = start(['10', '4', '--', ...groupCommand(leaderFile, kidFile)], { GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS: '1' });+ let kid = 0;+ let leader = 0;+ try {+ await waitFor(() => existsSync(kidFile) && existsSync(leaderFile), 'the command pids');+ await new Promise((r) => setTimeout(r, 200));+ kid = readPid(kidFile);+ leader = readPid(leaderFile);+ g.child.kill('SIGTERM');+ const { code } = await g.exit;+ expect(code).toBe(143);+ expect(await waitDead(leader)).toBe(true);+ expect(await waitDead(kid)).toBe(true);+ expect(doneRows()[0]?.exit_code).toBe(143);+ } finally {+ killQuietly(kid, leader);+ }+ }, 20_000);++ test('a command that exits normally but leaves a helper in its group: the helper is stopped when the guard settles', async () => {+ const helperFile = join(dir, 'helper.pid');+ // Async: the leftover helper holds the guard's stdout/stderr open, so a+ // spawnSync would wait for the pipes rather than the guard.+ const g = start(['10', '1', '--', 'sh', '-c', 'sleep 30 & echo $! > "' + helperFile + '"; exit 0'], { GBRAIN_EVAL_SPEND_GUARD_KILL_GRACE_SECONDS: '1' });+ const { code } = await g.exit;+ const helper = existsSync(helperFile) ? readPid(helperFile) : 0;+ try {+ expect(code).toBe(0);+ expect(helper).toBeGreaterThan(0);+ expect(await waitDead(helper)).toBe(true);+ expect(doneRows()[0]?.exit_code).toBe(0);+ } finally {+ killQuietly(helper);+ }+ }, 20_000);++ test('piped stdin still reaches the command', () => {+ const r = spawnSync('bash', [SCRIPT, '5', '1', '--', 'sh', '-c', 'read value; printf "received:%s" "$value"'], {+ cwd: ROOT, env: guardEnv(), input: 'example-input\n', encoding: 'utf-8', timeout: 15_000,+ });+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('received:example-input');+ });++ test.skipIf(process.platform === 'win32')('terminal stdin becomes EOF with a notice instead of a command stuck reading the terminal', async () => {+ let screen = '';+ let proc: ReturnType<typeof Bun.spawn> | undefined;+ try {+ proc = Bun.spawn(['bash', SCRIPT, '5', '1', '--', 'sh', '-c', 'if read value; then echo READ-LINE; else echo READ-EOF; fi'], {+ cwd: ROOT,+ env: guardEnv(),+ terminal: { cols: 200, rows: 20, data(_t: unknown, d: Uint8Array) { screen += new TextDecoder().decode(d); } },+ } as unknown as Parameters<typeof Bun.spawn>[1]);+ const exit = await Promise.race([proc.exited, new Promise<'timeout'>((r) => setTimeout(() => r('timeout'), 8000))]);+ expect(exit).toBe(0);+ expect(screen).toContain('READ-EOF');+ expect(screen).toContain('stdin is a terminal');+ } finally {+ proc?.kill('SIGKILL');+ }+ }, 15_000);+});