Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
test(view): a test Chrome dies with the test that started it
Corey Olson51d820bd63a3
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.jsindex 46a2eb9b..ad538c1a 100644--- a/test/chrome-fixture.js+++ b/test/chrome-fixture.js@@ -1,4 +1,5 @@/** Shared isolated Chrome launcher with bounded startup and complete process-group cleanup [C7]. */+import { execFileSync, spawn as spawnGuardian } from 'node:child_process';import { startFixtureChild as spawn } from './fixture-child.js';import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';import { loadavg, tmpdir } from 'node:os';@@ -149,12 +150,71 @@ export function requireBrowserSlot() {if (process.env.PULLBOARD_TEST_BROWSER_SLOT === 'none') throw browserSlotRefusal('through test/chrome-fixture.js');}+/**+ * The guardian program: poll the watched pids and, once any is gone, take down the Chrome process group.+ * It runs in its own session so the owner's death, by any signal, cannot take it along, and it ends by itself+ * once the group is empty. Escalating to SIGKILL after two seconds covers Chrome helpers that ignore SIGTERM.+ */+const GUARDIAN_SOURCE = `+const [group, ...watched] = process.argv.slice(1).map(Number);+const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };+let signalledAt = 0;+setInterval(() => {+ if (!alive(-group)) process.exit(0);+ if (watched.every(alive)) return;+ if (!signalledAt) { signalledAt = Date.now(); try { process.kill(-group, 'SIGTERM'); } catch {} }+ else if (Date.now() - signalledAt >= 2000) { try { process.kill(-group, 'SIGKILL'); } catch {} }+}, 250);+`;++let runnerAncestor;++/**+ * Find the test runner above this process: the nearest ancestor whose command runs bin/run-tests.js itself.+ * The walk uses `ps -o ppid=,command= -p <pid>`, which macOS and Linux share, runs once per process,+ * and answers null for a direct `node --test`, where only the owner is guarded.+ */+export function findRunnerAncestor() {+ if (runnerAncestor !== undefined) return runnerAncestor;+ runnerAncestor = null;+ try {+ let pid = process.pid;+ for (let depth = 0; depth < 32 && pid > 1; depth += 1) {+ const row = execFileSync('ps', ['-o', 'ppid=,command=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();+ const match = /^(\d+)\s+(.*)$/su.exec(row);+ if (!match) break;+ pid = Number(match[1]);+ const ancestor = execFileSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });+ // The runner's own `node --test` child carries bin/run-tests.js only as its --import; it is not the runner.+ if (/(?:^|[\s/])bin\/run-tests\.js(?:\s|$)/u.test(ancestor) && !/\s--(?:test|import)\b/u.test(ancestor)) { runnerAncestor = pid; break; }+ }+ } catch { /* No readable ancestry means the guardian watches the owner alone. */ }+ return runnerAncestor;+}++/**+ * Tie a detached Chrome process group to the processes that own it [C7].+ * A SIGKILLed owner runs no cleanup, so the group would outlive it for days; this starts a tiny detached+ * guardian that kills the group within about a second of the owner, or the runner above it, disappearing.+ * The group leader's pid is the group id.+ */+export function guardChromeGroup(groupId, { ownerPid = process.pid } = {}) {+ if (process.platform === 'win32' || !Number.isSafeInteger(groupId) || groupId <= 1) return null;+ const watched = [ownerPid, findRunnerAncestor()].filter((pid) => Number.isSafeInteger(pid) && pid > 1);+ const guardian = spawnGuardian(process.execPath, ['-e', GUARDIAN_SOURCE, String(groupId), ...watched.map(String)],+ { detached: true, stdio: 'ignore' });+ guardian.on('error', () => {});+ guardian.unref();+ return guardian.pid ?? null;+}+/** Launch an executable as a detached process group and retain its stderr and launch timing. */export function launchChromeProcess({ executable, args = [], env = process.env, cleanupTimeoutMs = CLEANUP_TIMEOUT_MS } = {}) {requireBrowserSlot();if (!executable) throw new Error('Chrome was not found; install Chrome or set PULLBOARD_CHROME.');const launchedAt = Date.now();const child = spawn(executable, args, { detached: true, env, stdio: ['ignore', 'ignore', 'pipe'] });+ if (child.pid) guardChromeGroup(child.pid);let stderr = '';let launchError = null;child.stderr.setEncoding('utf8');diff --git a/test/cockpit/chrome-owner-probe.mjs b/test/cockpit/chrome-owner-probe.mjsnew file mode 100644index 00000000..78faca14--- /dev/null+++ b/test/cockpit/chrome-owner-probe.mjs@@ -0,0 +1,13 @@+/** A stand-in test file for test/cockpit/stable.test.js: it opens Chrome through one launcher, reports ready, and idles [C7]. */+import { writeFileSync } from 'node:fs';+import { findChromeExecutable, launchChromeProcess, startChrome as openChrome } from '../chrome-fixture.js';+import { chromeExecutable, openSnapshotChrome } from './fixture.js';++const profile = process.env.PROBE_PROFILE;+if (process.env.PROBE_LAUNCHER === 'startChrome') await openChrome({ profileDirectory: profile });+else if (process.env.PROBE_LAUNCHER === 'launchChromeProcess') {+ launchChromeProcess({ executable: findChromeExecutable(), args: ['--headless=new', '--no-first-run',+ '--use-mock-keychain', '--password-store=basic', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'] });+} else await openSnapshotChrome(chromeExecutable(), 'about:blank', profile);+writeFileSync(process.env.PROBE_READY, String(process.pid));+setInterval(() => {}, 1000);diff --git a/test/cockpit/fixture.js b/test/cockpit/fixture.jsindex 5f18a1f9..01ba3124 100644--- a/test/cockpit/fixture.js+++ b/test/cockpit/fixture.js@@ -10,7 +10,7 @@ import vm from 'node:vm';import { stableChrome, press, tapTouch } from './stable.js';import { closeBoard, openBoard } from '../../src/board.js';import { fetchFresh } from '../http-fixture.js';-import { requireBrowserSlot } from '../chrome-fixture.js';+import { guardChromeGroup, requireBrowserSlot } from '../chrome-fixture.js';import { disableFixtureBackgroundView } from './background-view-fixture.js';@@ -659,6 +659,7 @@ async function startSnapshotChrome(executable, profile, { timeoutMs = 30_000, siconst startedAt = Date.now();requireBrowserSlot();const child = spawn(executable, args, { detached: true, stdio: ['ignore', 'ignore', 'pipe'] });+ if (child.pid) guardChromeGroup(child.pid);const stopped = new Promise((resolve) => child.once('close', (code, signal) => resolve({ code, signal })));let stopPromise;let onAbort;diff --git a/test/cockpit/stable.test.js b/test/cockpit/stable.test.jsnew file mode 100644index 00000000..3932e99c--- /dev/null+++ b/test/cockpit/stable.test.js@@ -0,0 +1,87 @@+/** A test Chrome never outlives the test that started it: every launcher ties Chrome to its owner [C7]. */+import assert from 'node:assert/strict';+import { execFileSync, spawn } from 'node:child_process';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import test from 'node:test';+import { fileURLToPath } from 'node:url';+import { findChromeExecutable } from '../chrome-fixture.js';++const ROOT = fileURLToPath(new URL('../../', import.meta.url));+const PROBE = join(ROOT, 'test/cockpit/chrome-owner-probe.mjs');+const DEATH_BUDGET_MS = 10_000; // budget: the item's declared bound for Chrome to exit after its owner dies.+const READY_BUDGET_MS = 600_000; // budget: hang ceiling for one real Chrome launch, including a wait for a gate browser slot.++/** The launchers the tests use, by the name the probe file takes. */+const LAUNCHERS = {+ startChrome: 'startChrome in test/chrome-fixture.js (relay, seal, journeys, README capture, perf)',+ launchChromeProcess: 'launchChromeProcess in test/chrome-fixture.js',+ openSnapshotChrome: 'openSnapshotChrome in test/cockpit/fixture.js (every cockpit story)',+};++/**+ * List the live processes of one Chrome by its private profile path.+ * The profile path is unique to this test, so nothing else matches it.+ */+function chromeProcesses(profile) {+ const rows = execFileSync('ps', ['-axo', 'pid=,pgid=,command='], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });+ return rows.split('\n').filter((row) => row.includes(`--user-data-dir=${profile}`))+ .map((row) => row.trim().split(/\s+/u)).map(([pid, pgid]) => ({ pid: Number(pid), pgid: Number(pgid) }));+}++/** Wait for the probe's ready file, failing early if the process that should write it has ended. */+async function waitForReady(file, child, budgetMs) {+ const startedAt = Date.now();+ while (Date.now() - startedAt < budgetMs) {+ if (existsSync(file)) return Number(readFileSync(file, 'utf8'));+ if (child.exitCode !== null || child.signalCode !== null) throw new Error('the owner ended before Chrome was ready');+ await new Promise((resolve) => setTimeout(resolve, 200));+ }+ throw new Error(`Chrome was not ready within ${budgetMs}ms`);+}++/** Wait until no process of this Chrome remains, returning the elapsed milliseconds, or null when the budget passes. */+async function waitForChromeGone(profile, budgetMs) {+ const startedAt = Date.now();+ while (Date.now() - startedAt < budgetMs) {+ if (chromeProcesses(profile).length === 0) return Date.now() - startedAt;+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ return chromeProcesses(profile).length === 0 ? Date.now() - startedAt : null;+}++/** Stop only the process groups and pids this test recorded, never anything found by name. */+function stopRecorded(profile, pids) {+ for (const { pgid } of chromeProcesses(profile)) { try { process.kill(-pgid, 'SIGKILL'); } catch { /* Already gone. */ } }+ for (const pid of pids) { try { process.kill(pid, 'SIGKILL'); } catch { /* Already gone. */ } }+}++for (const [launcher, name] of Object.entries(LAUNCHERS)) {+ for (const killed of ['owner', 'runner']) {+ test(`Chrome from ${name} exits within 10 s of its ${killed} dying by SIGKILL [C7]`, {+ timeout: READY_BUDGET_MS + DEATH_BUDGET_MS + 30_000,+ skip: !findChromeExecutable() && 'Chrome is not installed',+ }, async (t) => {+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-owner-death-'));+ const profile = join(directory, 'profile');+ const readyFile = join(directory, 'ready');+ const recorded = [];+ t.after(() => { stopRecorded(profile, recorded); rmSync(directory, { recursive: true, force: true }); });+ const env = { ...process.env, PROBE_LAUNCHER: launcher, PROBE_PROFILE: profile, PROBE_READY: readyFile };+ // The runner case starts the probe the way the gate does, as a test file under bin/run-tests.js.+ const victim = killed === 'owner'+ ? spawn(process.execPath, [PROBE], { cwd: ROOT, env, stdio: 'ignore' })+ : spawn(process.execPath, ['bin/run-tests.js', 'test/cockpit/chrome-owner-probe.mjs'], { cwd: ROOT, env, stdio: 'ignore' });+ recorded.push(victim.pid);+ recorded.push(await waitForReady(readyFile, victim, READY_BUDGET_MS)); // budget: hang ceiling for Chrome to start, including a gate browser-slot wait; no speed claim.+ const before = chromeProcesses(profile);+ assert.ok(before.length > 0, 'the owner holds a live Chrome before it is killed');+ const ended = new Promise((resolve) => victim.once('exit', (code, signal) => resolve(signal)));+ process.kill(victim.pid, 'SIGKILL');+ assert.equal(await ended, 'SIGKILL', `the ${killed} died by SIGKILL`);+ const gone = await waitForChromeGone(profile, DEATH_BUDGET_MS); // budget: the item's declared bound on Chrome outliving its dead owner.+ assert.notEqual(gone, null, `Chrome (${before.length} processes, pids ${before.map(row => row.pid).join(',')}) survived its ${killed} for ${DEATH_BUDGET_MS}ms`); // budget: the item's declared 10 s bound.+ });+ }+}