Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(claw-test): stop timed-out phases with their process group (#6775)

garrytan6608c27dd253
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 00d32179f7..062564e14a 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -33,7 +33,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/check-resolvable.ts` — Standalone CLI wrapper over `checkResolvable()`. Exports `parseFlags`, `resolveSkillsDir`, `DEFERRED`, `runCheckResolvable`. Exit rule: **1 on any issue (warnings OR errors)**, stricter than doctor's `ok` flag. Stable JSON envelope `{ok, skillsDir, report, autoFix, deferred, error, message}` — same shape on success and error. `--fix` runs `autoFixDryViolations` BEFORE `checkResolvable` (same ordering as doctor). `scripts/skillify-check.ts` subprocess-calls `gbrain check-resolvable --json` (cached per process) and fails loud on binary-missing. AGENTS.md workspaces resolve natively (see `src/core/resolver-filenames.ts`). `DEFERRED[]` is empty. Resolver lookup is the multi-file merge in `src/core/check-resolvable.ts` — entries collected from every `RESOLVER.md`/`AGENTS.md` across the skills dir AND its parent, deduped by `skillPath` (first occurrence wins). Uses `autoDetectSkillsDirReadOnly` so `cd ~ && gbrain check-resolvable` finds bundled skills via the install-path fallback; `--fix` carries the same install-path safety gate (refuses to write when `detected.source === 'install_path'`).
-- `src/commands/claw-test.ts` + `src/core/claw-test/` — `gbrain claw-test [--scenario <name>] [--live --agent <name>]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real agent subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Scripted phases: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`; top-level status is `healthy|warnings|unhealthy`) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first via `seed-pglite.ts`, NO init — the migration is the scenario under test), prepends a per-run `gbrain` PATH shim so the BRIEF's bare `gbrain` runs this checkout, hands `BRIEF.md` to the agent runner, then verifies a scenario-declared success ORACLE (`oracle: {query, min_results, files_exist}` in scenario.json; upgrade uses a non-mutating schema-version probe via `readPgliteSchemaVersion` — doctor would auto-migrate and pass a do-nothing agent). Child-side friction merges into the parent's friction file before tempdir cleanup. Four runners ship (`src/core/claw-test/runners/{openclaw,hermes,grok,opencode}.ts`; shared `detectBinary`/`filterAllowlistEnv` live in `agent-runner.ts`): openclaw invokes `openclaw agent --local --agent <name> --message <brief>`; hermes invokes `hermes -z <brief>` (`$HERMES_BIN` > `which hermes`; `HERMES_HOME` passthrough is the env-allowlist delta; shared `BASE_ENV_ALLOWLIST` + `validateBinPathEnv` live in `agent-runner.ts`); grok (xAI Grok Build, observed shapes in `docs/mcp/GROK-CLI-PIN.md`) invokes `grok -p <brief> --output-format plain` (`$GROK_BIN` > `which grok`; delta `GROK_HOME` + `XAI_API_KEY`; writes a version preamble into the transcript and warns loudly when the operator's `~/.claude.json` registers gbrain — grok reads vendor MCP configs for trusted folders); opencode (SST, observed shapes in `docs/mcp/OPENCODE-CLI-PIN.md`) invokes `opencode run <brief> --format default` (`$OPENCODE_BIN` > `which opencode`; delta = the EXPLICIT multi-provider keys XAI/Google/Gemini/OpenRouter — BASE carries only Anthropic+OpenAI — plus XDG dirs, OPENCODE_CONFIG(_DIR), and OPENCODE_DISABLE_AUTOUPDATE; OPENCODE_CONFIG_CONTENT deliberately absent, it is a config-shadow channel; no `--auto` — MCP tools fire without it; bare-semver version preamble is the SST-vs-claimant discriminator; warns loudly when the user-global opencode config carries mcp.gbrain). Live-lane posture: the OPERATOR's configured agent + hermetic brain; the fully hermetic lanes are `test/e2e/install-real-hermes.serial.test.ts`, `test/e2e/install-real-grok.serial.test.ts`, and `test/e2e/install-real-opencode.serial.test.ts` (split-gated a step past grok: opencode's anonymous free tier drives MCP tool calls keyless, so even the nonce SMOKE — with a STRUCTURAL `gbrain_*` tool_use assert via `parseOpencodeJsonl` — runs in the keyless tier; the paid anthropic leg self-validates its pinned model id against the authed `opencode models` list before any spend) (grok door is split-gated: keyless compat tier needs only the binary — `mcp doctor` is grok's honest discriminator, proving the seven-verb surface keyless; paid SMOKE additionally needs `XAI_API_KEY` and asserts a per-run nonce fact, never the committed one). Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure (so a 256KB burst cannot stall the child). Env knobs (harness escape hatches, all optional): `GBRAIN_BIN_OVERRIDE` (child gbrain binary; validated absolute/no-dotdot/no-metacharacter because it's interpolated into the PATH shim — under the bun runtime the harness otherwise synthesizes a launcher so children never exec bun itself), `GBRAIN_CLAW_PHASE_TIMEOUT_MS` (per-phase child wall clock, default 5 min), `GBRAIN_CLAW_AGENT_TIMEOUT_MS` (live agent turn wall clock, default 10 min).
+- `src/commands/claw-test.ts` + `src/core/claw-test/` — `gbrain claw-test [--scenario <name>] [--live --agent <name>]`. End-to-end "fresh user" friction harness. Two modes: scripted (CI gate, agent-free) and live (real agent subprocess, $1–2 in tokens). Sets `GBRAIN_HOME=<tempdir>` for hermeticity and captures gbrain's `--progress-json` events from each child's stderr to verify expected phases ran (`import.files`, `extract.links_fs`, `doctor.db_checks`). Scripted phases: setup → install_brain (`gbrain init --pglite`) → import (`--no-embed`) → query → extract → verify (`gbrain doctor --json`; top-level status is `healthy|warnings|unhealthy`) → render. Live mode STAGES the scenario before the agent turn (fresh-install: brain pages + AGENTS.md stub + init; upgrade: seed-first via `seed-pglite.ts`, NO init — the migration is the scenario under test), prepends a per-run `gbrain` PATH shim so the BRIEF's bare `gbrain` runs this checkout, hands `BRIEF.md` to the agent runner, then verifies a scenario-declared success ORACLE (`oracle: {query, min_results, files_exist}` in scenario.json; upgrade uses a non-mutating schema-version probe via `readPgliteSchemaVersion` — doctor would auto-migrate and pass a do-nothing agent). Child-side friction merges into the parent's friction file before tempdir cleanup. Four runners ship (`src/core/claw-test/runners/{openclaw,hermes,grok,opencode}.ts`; shared `detectBinary`/`filterAllowlistEnv` live in `agent-runner.ts`): openclaw invokes `openclaw agent --local --agent <name> --message <brief>`; hermes invokes `hermes -z <brief>` (`$HERMES_BIN` > `which hermes`; `HERMES_HOME` passthrough is the env-allowlist delta; shared `BASE_ENV_ALLOWLIST` + `validateBinPathEnv` live in `agent-runner.ts`); grok (xAI Grok Build, observed shapes in `docs/mcp/GROK-CLI-PIN.md`) invokes `grok -p <brief> --output-format plain` (`$GROK_BIN` > `which grok`; delta `GROK_HOME` + `XAI_API_KEY`; writes a version preamble into the transcript and warns loudly when the operator's `~/.claude.json` registers gbrain — grok reads vendor MCP configs for trusted folders); opencode (SST, observed shapes in `docs/mcp/OPENCODE-CLI-PIN.md`) invokes `opencode run <brief> --format default` (`$OPENCODE_BIN` > `which opencode`; delta = the EXPLICIT multi-provider keys XAI/Google/Gemini/OpenRouter — BASE carries only Anthropic+OpenAI — plus XDG dirs, OPENCODE_CONFIG(_DIR), and OPENCODE_DISABLE_AUTOUPDATE; OPENCODE_CONFIG_CONTENT deliberately absent, it is a config-shadow channel; no `--auto` — MCP tools fire without it; bare-semver version preamble is the SST-vs-claimant discriminator; warns loudly when the user-global opencode config carries mcp.gbrain). Live-lane posture: the OPERATOR's configured agent + hermetic brain; the fully hermetic lanes are `test/e2e/install-real-hermes.serial.test.ts`, `test/e2e/install-real-grok.serial.test.ts`, and `test/e2e/install-real-opencode.serial.test.ts` (split-gated a step past grok: opencode's anonymous free tier drives MCP tool calls keyless, so even the nonce SMOKE — with a STRUCTURAL `gbrain_*` tool_use assert via `parseOpencodeJsonl` — runs in the keyless tier; the paid anthropic leg self-validates its pinned model id against the authed `opencode models` list before any spend) (grok door is split-gated: keyless compat tier needs only the binary — `mcp doctor` is grok's honest discriminator, proving the seven-verb surface keyless; paid SMOKE additionally needs `XAI_API_KEY` and asserts a per-run nonce fact, never the committed one). Transcript capture (`transcript-capture.ts`) uses `fs.createWriteStream` with `'drain'`-event backpressure (so a 256KB burst cannot stall the child). Env knobs (harness escape hatches, all optional): `GBRAIN_BIN_OVERRIDE` (child gbrain binary; validated absolute/no-dotdot/no-metacharacter because it's interpolated into the PATH shim — under the bun runtime the harness otherwise synthesizes a launcher so children never exec bun itself), `GBRAIN_CLAW_PHASE_TIMEOUT_MS` (per-phase child wall clock, default 5 min; each phase child leads its own process group on POSIX, so the timeout's SIGTERM→SIGKILL, a relayed SIGINT (second SIGINT kills), the process-cleanup pass on SIGTERM/SIGHUP and the phase's settle all signal the whole group (#6775)), `GBRAIN_CLAW_AGENT_TIMEOUT_MS` (live agent turn wall clock, default 10 min).
- `src/commands/code-def.ts` + `src/commands/code-refs.ts` — symbol definition + references lookup. Query `content_chunks.symbol_name` or chunk_text ILIKE with `page_kind='code'` filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard `searchKeyword` `DISTINCT ON (slug)` collapse so multiple call-sites from the same file surface. The JSON envelope (CLI + the `code_def`/`code_refs` MCP ops) carries `status` + `ready` from `src/core/code-graph-readiness.ts` so a `count:0` result is distinguishable as `not_built` (no code indexed) vs `ready` (genuinely no match); human output prints a one-line hint when not ready. Both commands resolve `--source <id>` (space or inline `=` spelling) and the ambient source scope through the shared `code-scope.ts` resolver, matching `code-callers`/`code-callees`; `--all-sources` restores the brain-wide read. `code-intel/read-scope.ts` applies the same source, live-page, visibility and current-projection policy to result queries and filtered-type diagnostics. Result identity includes source_id. Partial as well as empty results carry readiness; trusted-local operation wrappers retain their documented brain-wide behavior.
diff --git a/scripts/check-windows-hide.ts b/scripts/check-windows-hide.ts
index 84f7e06ff5..533cf2246a 100644
--- a/scripts/check-windows-hide.ts
+++ b/scripts/check-windows-hide.ts
@@ -42,7 +42,6 @@ const ALLOWLIST: Record<string, string> = {
*/
const NOT_YET_MIGRATED: Record<string, string> = {
'src/commands/bootstrap.ts': 'not yet migrated: open PR #6283, #6319 edits this file',
- 'src/commands/claw-test.ts': 'not yet migrated: open PR #6775 edits this file',
'src/commands/eval-longmemeval.ts': 'not yet migrated: open PR #6790 edits this file',
'src/commands/serve.ts': 'not yet migrated: open PR #6437 edits this file',
'src/commands/setup.ts': 'not yet migrated: open PR #6406 edits this file',
diff --git a/src/commands/claw-test.ts b/src/commands/claw-test.ts
index 33ea5640d7..3607401ddc 100644
--- a/src/commands/claw-test.ts
+++ b/src/commands/claw-test.ts
@@ -16,12 +16,13 @@
* for the full design rationale (D1–D23 decisions).
*/
-import { spawn } from 'child_process';
+import { spawn } from '../core/spawn.ts';
import { mkdtempSync, writeFileSync, mkdirSync, rmSync, existsSync, readFileSync, appendFileSync, chmodSync, cpSync, lstatSync } from 'fs';
import { join, resolve, basename, dirname } from 'path';
import { fileURLToPath } from 'url';
import { tmpdir } from 'os';
import { randomBytes } from 'crypto';
+import { registerCleanup } from '../core/process-cleanup.ts';
import { logFriction, frictionDir, frictionFile } from '../core/friction.ts';
import { loadScenario, listScenarios, readBrief, type ScenarioConfig } from '../core/claw-test/scenarios.ts';
import { parseProgressEvents, verifyExpectedPhases } from '../core/claw-test/progress-tail.ts';
@@ -799,7 +800,15 @@ function invokeGbrain(
): Promise<PhaseOutcome> {
return new Promise((resolvePromise) => {
const start = Date.now();
- const child = spawn(bin, argv, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], shell: false });
+ // #6775: on POSIX the phase leads its own process group, so every stop
+ // (timeout, interrupt, settle) reaches what it started too: a grandchild
+ // that ignores SIGTERM, or one that outlives the leader holding the pipes.
+ const grouped = process.platform !== 'win32';
+ const child = spawn(bin, argv, { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], shell: false, detached: grouped });
+ const signalPhase = (signal: NodeJS.Signals | 0): boolean => {
+ if (!child.pid) return false;
+ try { process.kill(grouped ? -child.pid : child.pid, signal); return true; } catch { return false; }
+ };
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
child.stdout?.on('data', (b: Buffer) => stdout.push(b));
@@ -810,16 +819,37 @@ function invokeGbrain(
// SIGKILL if it lingers.
let timedOut = false;
let killTimer: ReturnType<typeof setTimeout> | null = null;
+ const escalate = () => { if (!killTimer) killTimer = setTimeout(() => signalPhase('SIGKILL'), 10_000); };
const wallClockTimer = setTimeout(() => {
timedOut = true;
- try { child.kill('SIGTERM'); } catch { /* already gone */ }
- killTimer = setTimeout(() => {
- try { child.kill('SIGKILL'); } catch { /* already gone */ }
- }, 10_000);
+ signalPhase('SIGTERM');
+ escalate();
}, SUBPROCESS_TIMEOUT_MS);
+ // A group of its own no longer receives the terminal's Ctrl-C, and
+ // process-cleanup deliberately leaves SIGINT to commands, so relay it: the
+ // first SIGINT is forwarded (SIGKILL after the grace), a second kills.
+ let interrupts = 0;
+ const onSigint = () => {
+ interrupts++;
+ if (interrupts > 1) { signalPhase('SIGKILL'); return; }
+ signalPhase('SIGINT');
+ escalate();
+ };
+ process.on('SIGINT', onSigint);
+ // SIGTERM/SIGHUP and crashes exit through process-cleanup's pass (3 s
+ // deadline): stop the group there before the harness exits.
+ const releaseCleanup = registerCleanup('claw-test phase process group', async () => {
+ if (!signalPhase('SIGTERM')) return;
+ for (let waited = 0; waited < 1_500 && signalPhase(0); waited += 100) {
+ await new Promise((r) => setTimeout(r, 100));
+ }
+ if (signalPhase(0)) signalPhase('SIGKILL');
+ });
const clearTimers = () => {
clearTimeout(wallClockTimer);
if (killTimer) clearTimeout(killTimer);
+ process.off('SIGINT', onSigint);
+ releaseCleanup();
};
let settled = false;
@@ -827,6 +857,8 @@ function invokeGbrain(
if (settled) return;
settled = true;
clearTimers();
+ // The leader is gone; whatever it left in its group goes with it.
+ if (grouped) signalPhase('SIGKILL');
let stderrText = Buffer.concat(stderr).toString('utf-8');
if (timedOut) stderrText += `\nharness: killed after ${SUBPROCESS_TIMEOUT_MS}ms phase timeout`;
const stdoutText = Buffer.concat(stdout).toString('utf-8');
diff --git a/test/claw-test.slow.test.ts b/test/claw-test.slow.test.ts
index b3adda7a50..cef3675303 100644
--- a/test/claw-test.slow.test.ts
+++ b/test/claw-test.slow.test.ts
@@ -375,6 +375,84 @@ describe('gbrain claw-test — adversarial-gate regression pins', () => {
}
}, 60_000);
+ // #6775: a phase runs in its own process group, so a timeout, an interrupt
+ // and the phase's settle stop every process it started, not just its leader.
+ const phaseGroupState = (pid: number) => spawnSync('ps', ['-o', 'stat=', '-p', String(pid)], { encoding: 'utf-8' }).stdout.trim();
+ const phaseGoneAfter = async (pid: number, ms: number) => {
+ const deadline = Date.now() + ms;
+ for (;;) {
+ const state = phaseGroupState(pid);
+ if (!state || state.startsWith('Z')) return true;
+ if (Date.now() > deadline) return false;
+ await Bun.sleep(50);
+ }
+ };
+ /** A fake gbrain whose every invocation leaves a grandchild that ignores TERM and INT, records its pid, and waits. */
+ const writeHangingGbrain = (tmp: string, kidFile: string) => {
+ const fake = join(tmp, 'hang-group-gbrain');
+ writeFileSync(fake, '#!/bin/sh\nsh -c \'trap "" TERM INT; echo $$ > "' + kidFile + '"; exec sleep 60\' &\nwait\n', 'utf-8');
+ chmodSync(fake, 0o755);
+ return fake;
+ };
+
+ test('phase timeout stops the whole phase process group, including a grandchild that ignores SIGTERM', async () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'claw-test-e2e-group-'));
+ const kidFile = join(tmp, 'kid.pid');
+ let kid = 0;
+ try {
+ const fake = writeHangingGbrain(tmp, kidFile);
+ const result = spawnSync(BIN_PATH, ['claw-test', '--scenario', 'fresh-install'], {
+ cwd: REPO_ROOT,
+ env: { ...process.env, GBRAIN_HOME: tmp, GBRAIN_BIN_OVERRIDE: fake, GBRAIN_CLAW_SCENARIOS_DIR: SCENARIOS_DIR, GBRAIN_CLAW_PHASE_TIMEOUT_MS: '2000' },
+ encoding: 'utf-8',
+ timeout: 45_000,
+ });
+ expect(result.signal).toBeNull();
+ expect(result.status).toBe(1);
+ kid = Number(readFileSync(kidFile, 'utf-8').trim());
+ expect(kid).toBeGreaterThan(0);
+ expect(await phaseGoneAfter(kid, 3000)).toBe(true);
+ } finally {
+ if (kid) { try { process.kill(kid, 'SIGKILL'); } catch { /* gone */ } }
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ for (const [signal, code] of [['SIGINT', 130], ['SIGTERM', 143]] as const) {
+ test(signal + ' during a phase stops its process group (exit ' + code + ', no surviving descendant)', async () => {
+ const tmp = mkdtempSync(join(tmpdir(), 'claw-test-e2e-interrupt-'));
+ const kidFile = join(tmp, 'kid.pid');
+ let kid = 0;
+ let run: ReturnType<typeof Bun.spawn> | undefined;
+ try {
+ const fake = writeHangingGbrain(tmp, kidFile);
+ run = Bun.spawn([process.execPath, join(REPO_ROOT, 'src', 'cli.ts'), 'claw-test', '--scenario', 'fresh-install'], {
+ cwd: REPO_ROOT,
+ env: { ...process.env, GBRAIN_HOME: tmp, GBRAIN_BIN_OVERRIDE: fake, GBRAIN_CLAW_SCENARIOS_DIR: SCENARIOS_DIR, GBRAIN_CLAW_PHASE_TIMEOUT_MS: '60000' },
+ stdin: 'ignore',
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ const deadline = Date.now() + 20_000;
+ while (!existsSync(kidFile) && Date.now() < deadline) await Bun.sleep(25);
+ expect(existsSync(kidFile)).toBe(true);
+ await Bun.sleep(200);
+ kid = Number(readFileSync(kidFile, 'utf-8').trim());
+ run.kill(signal);
+ const exit = await Promise.race([run.exited, Bun.sleep(20_000).then(() => 'timeout' as const)]);
+ expect(exit).toBe(code);
+ expect(await phaseGoneAfter(kid, 3000)).toBe(true);
+ const out = await new Response(run.stdout as ReadableStream).text();
+ const runDir = out.match(/^tempdir(?: kept at)?: (.+)$/m)?.[1];
+ if (runDir) rmSync(runDir.trim(), { recursive: true, force: true });
+ } finally {
+ run?.kill('SIGKILL');
+ if (kid) { try { process.kill(kid, 'SIGKILL'); } catch { /* gone */ } }
+ rmSync(tmp, { recursive: true, force: true });
+ }
+ }, 60_000);
+ }
+
test('fail-closed doctor oracle: doctor exiting 0 with unparsable output FAILS the live run', () => {
// A wrapper gbrain that answers `doctor` with a non-JSON banner and exit 0
// — the pre-fix oracle only rejected literal "unhealthy" and passed this.