Skip to content

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.

feat(gate): only files that launch Chrome take a browser slot [C7,O5]

Corey Olsonb924c7ca3d56
diff --git a/bin/run-tests.js b/bin/run-tests.js
index c5498a3c..06d5da2c 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -1239,7 +1239,10 @@ async function executeTests(args, sandbox, gateMarkers, fullSuite, concurrency)
// This is an inner file limit; the real machine gate/browser lease remains unchanged.
env.PULLBOARD_TEST_BROWSER_RESOURCE = 'test-browser-files:' + randomUUID();
env.PULLBOARD_TEST_BROWSER_CAPACITY = String(concurrency.browser);
+ // Each file's worker classifies itself; the machine setting reaches it here, since tests get a private machine home.
+ env.PULLBOARD_TEST_BROWSER_BY_LAUNCH = concurrency.byLaunch ? '1' : '';
delete env.PULLBOARD_TEST_BROWSER_OWNER_PID;
+ delete env.PULLBOARD_TEST_BROWSER_SLOT;
let selectedArgs = args;
if (fullSuite) {
let files;
@@ -1278,7 +1281,8 @@ async function main(args) {
try {
testTimeoutMs();
const { testConcurrency } = await import('../src/gate.js');
- concurrency = testConcurrency(process.cwd());
+ const { browserByLaunchEnabled } = await import('../src/settings.js');
+ concurrency = { ...testConcurrency(process.cwd()), byLaunch: browserByLaunchEnabled() };
} catch (error) {
process.stderr.write(`${error.message}\n`);
process.exitCode = 1;
@@ -1396,13 +1400,20 @@ if (process.argv[1] && resolve(process.argv[1]) === runner) {
&& !process.env.PULLBOARD_TEST_BROWSER_OWNER_PID) {
// The worker is announced to #589 before it can wait here; admission remains before file import/body.
process.env.PULLBOARD_TEST_BROWSER_OWNER_PID = String(process.pid);
+ // The test body never sees the setting itself: its own fixtures classify with their own machine settings.
+ const byLaunch = process.env.PULLBOARD_TEST_BROWSER_BY_LAUNCH === '1';
+ delete process.env.PULLBOARD_TEST_BROWSER_BY_LAUNCH;
const { testsNeedBrowser } = await import('../src/browser-admission.js');
- if (await testsNeedBrowser(process.cwd(), [process.argv[1]])) {
+ if (await testsNeedBrowser(process.cwd(), [process.argv[1]], { byLaunch })) {
const { takeResource } = await import('../src/resources.js');
const lease = await takeResource({ name: process.env.PULLBOARD_TEST_BROWSER_RESOURCE,
capacity: Number(process.env.PULLBOARD_TEST_BROWSER_CAPACITY), kind: 'test-browser-file', root: process.cwd() });
// Hold through file cleanup and process exit, including abort/watchdog paths.
process.once('exit', () => lease.release());
+ if (byLaunch) process.env.PULLBOARD_TEST_BROWSER_SLOT = 'held';
+ } else if (byLaunch) {
+ // test/chrome-fixture.js refuses a launch from this file and its children by name (BROWSER_SLOT_REQUIRED).
+ process.env.PULLBOARD_TEST_BROWSER_SLOT = 'none';
}
}
if (!landingWorker) installTestWatchdog();
diff --git a/docs/api.md b/docs/api.md
index fd626f8b..fe29da15 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -12,6 +12,8 @@ A successful command returns the fields listed below. `version` is always the nu
Browser-free check admission is opt-in per machine with `"gate": { "browserFreeChecks": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the reviewed test classifier can let checks use a CPU-only gate slot. An absent or false setting keeps every check browser-gated, and uncertain or unsupported test commands remain browser-gated even when enabled. The same setting controls the wider frozen-check classification introduced in 0.8.26.
+Classifying test files by launch is opt-in per machine with `"gate": { "browserByLaunch": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the test runner gives a test file a browser slot only when its import graph reaches a real Chrome launch: an import of `startChrome` or `launchChromeProcess` (or any binding other than the launch-free helpers) from `test/chrome-fixture.js`, directly or through a helper, or a process starter beside a Chrome executable reference. Cockpit test files keep the browser slot. Every other file runs without one, and a file that launches Chrome through `test/chrome-fixture.js` while classified browser-free fails at once with `BROWSER_SLOT_REQUIRED` naming the file. An absent or false setting classifies exactly as before, and the launch guard is inert.
+
When `add` or `edit` supplies a new nonempty check, it records the item before measuring that check in a background temporary checkout of the captured `main` commit. Use `--wait` to wait for the measurement before returning, or `args.wait: true` for an HTTP add/edit move. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, request?, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `pending`, `green`, `red`, or `unavailable`. A background request carries an opaque `request` identity; an older completion cannot overwrite a newly edited or cleared check.
An item's HTTP detail, and each item in the full board state, include `check` and, when recorded, `checkBaseline` with the same observation fields. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when showing or reserving the item for review, and when filing it with `--wait`. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. Captured observations and completions travel through ordered board moves, so replicas store results without executing commands. A completed result awaiting relay delivery stays on the measuring device and is retried by the next normal CLI command.
diff --git a/src/browser-admission.js b/src/browser-admission.js
index 03d15ee9..f4791ff4 100644
--- a/src/browser-admission.js
+++ b/src/browser-admission.js
@@ -10,7 +10,16 @@ const CHROME_FIXTURE = 'test/chrome-fixture.js';
const FIXTURE_CHILD = 'test/fixture-child.js';
const JOURNEYS_TEST = 'test/journeys.test.js';
const TEST_RUNNER = 'bin/run-tests.js';
+/** Chrome fixture exports that never start a browser; any other binding, a new export included, counts as a launch. */
+const LAUNCH_FREE_CHROME_EXPORTS = new Set(['findChromeExecutable', 'requireBrowserSlot', 'waitForTargetAbsent', 'createWaiter', 'createSender',
+ 'createEvaluator', 'createPageStepEvaluator']);
+/** Imports that let a module start another process or module, which by launch counts only with a Chrome reference. */
+const PROCESS_STARTERS = new Set(['node:child_process', 'node:worker_threads', 'node:cluster', 'node:module', 'node:vm']);
+/** A Chrome executable named in source: the paths and variable a direct launcher uses outside the guarded fixture. */
+const CHROME_EXECUTABLE = /PULLBOARD_CHROME|google-chrome|Google Chrome|chromium|puppeteer|playwright/iu;
const VALUE_OPTIONS = new Set(['--test-concurrency', '--test-name-pattern', '--test-shard', '--test-skip-pattern', '--test-timeout']);
+/** What module-imports reports for a dynamic import whose target is not one plain string. */
+const COMPUTED_IMPORT = '(computed)';
const FLAG_OPTIONS = new Set(['--test-only']);
/** Path-scoped child-process exceptions with a short reason for each reviewed non-Chrome helper. */
const SAFE_CHILD_PROCESS_MODULES = new Map([
@@ -189,6 +198,28 @@ function safeFixtureChildImport(source, request) {
try { return !importsIn([remaining])[0].includes(request); } catch { return false; }
}
+/** By launch, a Chrome fixture import is launch-free only as single-line named imports of launch-free exports.
+ * Anything else (a launch export, a namespace, default or dynamic import, a re-export of everything) is a launch.
+ * @param {string} source
+ * @param {string} request
+ * @returns {boolean}
+ */
+function launchFreeChromeImport(source, request) {
+ const escaped = request.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
+ const named = new RegExp(`^[ \\t]*(?:import|export)[ \\t]*\\{([^}\\r\\n]*)\\}[ \\t]*from[ \\t]*(['"])${escaped}\\2[ \\t]*;?[ \\t]*$`, 'u');
+ let removed = false;
+ const remaining = source.split(/\r?\n/u).filter(line => {
+ const match = named.exec(line);
+ if (!match) return true;
+ const names = match[1].split(',').map(part => part.trim()).filter(Boolean).map(part => part.split(/\s+as\s+/u)[0].trim());
+ if (!names.length || !names.every(name => LAUNCH_FREE_CHROME_EXPORTS.has(name))) return true;
+ removed = true;
+ return false;
+ }).join('\n');
+ if (!removed) return false;
+ try { return !importsIn([remaining])[0].includes(request); } catch { return false; }
+}
+
/** Detect direct literal Chrome launchers without treating help text or refusal messages as launches. */
function namesChromeLauncher(source) {
return /\b(?:spawn|spawnSync|exec|execSync|execFile|execFileSync|fork)\s*\(\s*(['"`])[^'"`\r\n]*\b(?:chrome|chromium|playwright|puppeteer)\b/iu.test(source);
@@ -210,6 +241,14 @@ function usesDynamicBuiltinLoader(source) {
});
}
+/**
+ * Read gate.browserByLaunch; an unreadable settings file keeps today's broad classification, the safe side.
+ * Loaded on demand: callers that pass byLaunch (the runner's per-file admission) never open settings.
+ */
+async function browserByLaunchSetting() {
+ try { return (await import('./settings.js')).browserByLaunchEnabled(); } catch { return false; }
+}
+
/** Report a one-line explanation when uncertainty reserves browser capacity.
* @param {(decision:{file:string,reason:string})=>void|undefined} onFallback
* @param {string} file
@@ -295,8 +334,47 @@ async function localTarget(root, importer, request) {
return found.length === 1 ? found[0] : null;
}
-/** Classify test imports from either the current checkout or one immutable committed tree. */
-async function testsNeedBrowserInTree(root, files, committed = null, onFallback) {
+/**
+ * Parse each source's CommonJS use and imports once, in one child per batch, reusing earlier parses.
+ * A source that loads CommonJS is never import-parsed, since the caller refuses it first.
+ *
+ * @param {string[]} sources
+ * @param {Map<string, {commonJs:boolean, imports:string[]}>} memo
+ * @returns {{commonJs:boolean, imports:string[]}[]}
+ */
+function parsedSources(sources, memo) {
+ const fresh = [...new Set(sources.filter(source => !memo.has(source)))];
+ if (fresh.length) {
+ const commonJs = commonJsIn(fresh);
+ const plain = fresh.filter((_, index) => !commonJs[index]);
+ const imports = plain.length ? importsIn(plain) : [];
+ fresh.forEach((source, index) => memo.set(source, { commonJs: commonJs[index], imports: [] }));
+ plain.forEach((source, index) => { memo.get(source).imports = imports[index]; });
+ }
+ return sources.map(source => memo.get(source));
+}
+
+/**
+ * Classify test imports from either the current checkout or one immutable committed tree.
+ *
+ * By default any path to the Chrome fixture, or any process or module starter the walk cannot follow,
+ * reserves the browser. With byLaunch (machine setting gate.browserByLaunch) a file is browser-bound
+ * only when its graph reaches a real launch: a Chrome fixture binding that starts Chrome, or a process
+ * starter beside a Chrome executable reference. Cockpit files keep the browser until their own
+ * fixture carries the BROWSER_SLOT_REQUIRED guard, and the guard at test/chrome-fixture.js's launch
+ * point fails any launch the narrower walk misses.
+ *
+ * @param {string} root
+ * @param {string[]} files
+ * @param {Map<string, {mode:string,type:string,object:string}> | null} committed
+ * @param {((decision:{file:string,reason:string})=>void) | undefined} onFallback
+ * @param {boolean} [byLaunch] - unset reads gate.browserByLaunch from this machine's settings
+ * @param {Map<string, {commonJs:boolean, imports:string[]}>} [memo] - parses shared across one census of many files
+ * @param {Map<string, boolean>} [launchFree] - Chrome fixture import verdicts shared the same way
+ * @returns {Promise<boolean>}
+ */
+async function testsNeedBrowserInTree(root, files, committed = null, onFallback, byLaunch = undefined, memo = new Map(), launchFree = new Map()) {
+ byLaunch ??= await browserByLaunchSetting();
if (!Array.isArray(files) || files.length === 0) return browserFallback(onFallback, '<test selection>', 'selection is empty or unavailable');
const normalized = files.map((file) => repositoryPath(root, file));
if (normalized.some((file) => file === null)) return browserFallback(onFallback, '<test selection>', 'a selected path is outside the repository');
@@ -311,7 +389,7 @@ async function testsNeedBrowserInTree(root, files, committed = null, onFallback)
for (const path of frontier) {
if (seen.has(path)) continue;
seen.add(path);
- if (path === CHROME_FIXTURE) return true;
+ if (path === CHROME_FIXTURE && !byLaunch) return true;
if (path.endsWith('.json')) continue;
if (/\.(?:cjs|cts)$/u.test(path)) return browserFallback(onFallback, path, 'CommonJS loader behavior is not statically classified');
paths.push(path);
@@ -328,14 +406,17 @@ async function testsNeedBrowserInTree(root, files, committed = null, onFallback)
if (!sources.length) break;
if (paths.some((path, index) => (path.startsWith('test/') || SAFE_CHILD_PROCESS_MODULES.has(path))
&& namesChromeLauncher(sources[index]))) return true;
- const dynamicLoaderIndex = sources.findIndex(usesDynamicBuiltinLoader);
+ // By launch, a process or module starter launches a browser only beside a Chrome executable reference.
+ const starts = sources.map(source => byLaunch && usesDynamicBuiltinLoader(source));
+ const dynamicLoaderIndex = byLaunch ? -1 : sources.findIndex(usesDynamicBuiltinLoader);
if (dynamicLoaderIndex >= 0) return browserFallback(onFallback, paths[dynamicLoaderIndex], 'dynamic process builtin loading can load an unclassified module');
- const commonJsIndex = commonJsIn(sources).findIndex(Boolean);
+ const commonJsIndex = parsedSources(sources, memo).findIndex(parsed => parsed.commonJs);
if (commonJsIndex >= 0) return browserFallback(onFallback, paths[commonJsIndex], 'CommonJS loading is not statically classified');
- const imports = importsIn(sources);
+ const imports = parsedSources(sources, memo).map(parsed => parsed.imports);
const next = new Set();
for (let index = 0; index < imports.length; index += 1) {
for (const request of imports[index]) {
+ if (byLaunch && PROCESS_STARTERS.has(request)) { starts[index] = true; continue; }
if (request === 'node:child_process') {
const policy = SAFE_CHILD_PROCESS_MODULES.get(paths[index]);
if (!policy) return browserFallback(onFallback, paths[index], 'child_process use has no reviewed path-and-reason exception');
@@ -349,17 +430,26 @@ async function testsNeedBrowserInTree(root, files, committed = null, onFallback)
return browserFallback(onFallback, paths[index], 'node:vm can evaluate an unclassified module');
}
if (request.startsWith('node:')) continue;
+ if (byLaunch && request === COMPUTED_IMPORT) { starts[index] = true; continue; }
if (!request.startsWith('.')) return browserFallback(onFallback, paths[index], `non-local import ${request} is not classified`);
const target = committed
? committedTarget(committed, paths[index], request)
: await localTarget(root, paths[index], request);
if (!target) return browserFallback(onFallback, paths[index], `import ${request} is missing or ambiguous`);
if (target === FIXTURE_CHILD && !safeFixtureChildImport(sources[index], request)) {
- return browserFallback(onFallback, paths[index], 'fixture-child import exposes a generic caller-selected process target');
+ if (byLaunch) starts[index] = true;
+ else return browserFallback(onFallback, paths[index], 'fixture-child import exposes a generic caller-selected process target');
+ }
+ if (target === CHROME_FIXTURE) {
+ if (!byLaunch) return true;
+ const key = `${request}\0${sources[index]}`;
+ if (!launchFree.has(key)) launchFree.set(key, launchFreeChromeImport(sources[index], request));
+ if (!launchFree.get(key)) return true;
+ continue;
}
- if (target === CHROME_FIXTURE) return true;
if (!target.endsWith('.json') && !seen.has(target)) next.add(target);
}
+ if (starts[index] && CHROME_EXECUTABLE.test(sources[index])) return true;
}
frontier = [...next];
}
@@ -369,7 +459,35 @@ async function testsNeedBrowserInTree(root, files, committed = null, onFallback)
}
}
-/** Return true for full or uncertain selections, cockpit tests, or imports reaching the Chrome fixture. */
-export async function testsNeedBrowser(root, files, { onFallback } = {}) {
- return testsNeedBrowserInTree(root, files, null, onFallback);
+/**
+ * Return true for full or uncertain selections, cockpit tests, or imports reaching the Chrome fixture;
+ * with byLaunch, only for cockpit tests, uncertain graphs and graphs that reach a real Chrome launch.
+ *
+ * @param {string} root
+ * @param {string[]} files
+ * @param {{onFallback?:(decision:{file:string,reason:string})=>void, byLaunch?:boolean}} [options] - unset byLaunch reads gate.browserByLaunch
+ * @returns {Promise<boolean>}
+ */
+export async function testsNeedBrowser(root, files, { onFallback, byLaunch } = {}) {
+ return testsNeedBrowserInTree(root, files, null, onFallback, byLaunch);
+}
+
+/**
+ * Classify each file on its own, as the runner admits each test file, sharing parses across the set.
+ * This is the census behind gate.browserByLaunch: the files it returns are the ones that take a slot.
+ *
+ * @param {string} root
+ * @param {string[]} files
+ * @param {{byLaunch?:boolean}} [options] - unset reads gate.browserByLaunch
+ * @returns {Promise<string[]>}
+ */
+export async function browserBoundFiles(root, files, { byLaunch } = {}) {
+ byLaunch ??= await browserByLaunchSetting();
+ const memo = new Map();
+ const launchFree = new Map();
+ const bound = [];
+ for (const file of files) {
+ if (await testsNeedBrowserInTree(root, [file], null, undefined, byLaunch, memo, launchFree)) bound.push(file);
+ }
+ return bound;
}
diff --git a/src/help.js b/src/help.js
index 7d2958d2..8cc3ac4b 100644
--- a/src/help.js
+++ b/src/help.js
@@ -21,6 +21,7 @@ Set up
pullboard resources local resource holders and their FIFO queues
pullboard settings [gateSlots <n> | browserSlots <n>] view or set machine capacity (gate default 2; browser default 1)
browser-free check slots are opt-in: gate.browserFreeChecks in ~/.pullboard/settings.json (default false)
+ a test file takes a browser slot only if it launches Chrome: gate.browserByLaunch (default false)
pullboard runner add <ssh-host> --slots <n> --browser <n> [--node <remote-path>] [--root <remote-path>]
register SSH test capacity; no runner sign-in; root defaults to ~/.pullboard-runner
pullboard view [--project] [--port N] [--no-open] every project on this machine in your browser; default http://127.0.0.1:${DEFAULT_VIEW_PORT}
diff --git a/src/settings.js b/src/settings.js
index 4169a4c6..dd564cdd 100644
--- a/src/settings.js
+++ b/src/settings.js
@@ -31,6 +31,9 @@ export function loadMachineSettings() {
if (value.gate?.browserFreeChecks !== undefined && typeof value.gate.browserFreeChecks !== 'boolean') {
throw new Refused('BAD_MACHINE_SETTINGS', `gate.browserFreeChecks in ${file} must be true or false`);
}
+ if (value.gate?.browserByLaunch !== undefined && typeof value.gate.browserByLaunch !== 'boolean') {
+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.browserByLaunch in ${file} must be true or false`);
+ }
const gateSlots = value.gateSlots ?? DEFAULT_GATE_SLOTS;
if (!Number.isSafeInteger(gateSlots) || gateSlots < 1) {
throw new Refused('BAD_GATE_SLOTS', `gateSlots in ${file} must be a positive integer; run pullboard settings gateSlots <n>`);
@@ -55,6 +58,14 @@ export function browserFreeChecksEnabled() {
return loadMachineSettings().gate?.browserFreeChecks === true;
}
+/**
+ * Classifying a test file as browser-bound only when it reaches a real Chrome launch is opt-in per
+ * machine; off, any path to the Chrome fixture or an unfollowed process starter takes a browser slot.
+ */
+export function browserByLaunchEnabled() {
+ return loadMachineSettings().gate?.browserByLaunch === true;
+}
+
/** Atomically replace machine settings without exposing a partial JSON file. */
function writeMachineSettings(settings) {
const file = machineSettingsFile();
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.js
index 33b99e9c..2b8616da 100644
--- a/test/chrome-fixture.js
+++ b/test/chrome-fixture.js
@@ -3,7 +3,8 @@ 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';
import { monitorEventLoopDelay } from 'node:perf_hooks';
-import { join, resolve } from 'node:path';
+import { isAbsolute, join, relative, resolve } from 'node:path';
+import { Refused } from '../src/refused.js';
const STARTUP_TIMEOUT_MS = 30_000;
const COMMAND_TIMEOUT_MS = 15_000;
@@ -137,8 +138,24 @@ async function stopProcessGroup(child, stopped, timeoutMs = CLEANUP_TIMEOUT_MS)
if (!await waitForLeaderExit(stopped, timeoutMs)) throw new Error('Isolated Chrome did not close after its process group exited.');
}
+/**
+ * Refuse a Chrome launch from a test file the runner admitted without a browser slot [C7].
+ * With gate.browserByLaunch on, the runner marks each file's worker held or none; a launch under none
+ * means the classifier missed a launch path, so the file fails here by name before Chrome starts,
+ * and a wrong classification can never run Chrome outside the slot. Without a marker this is inert.
+ */
+export function requireBrowserSlot() {
+ if (process.env.PULLBOARD_TEST_BROWSER_SLOT !== 'none') return;
+ const absolute = process.env.PULLBOARD_TEST_FILE ? resolve(process.env.PULLBOARD_TEST_FILE) : '';
+ const local = absolute ? relative(process.cwd(), absolute) : '';
+ const file = !absolute ? 'this test file' : (local && !local.startsWith('..') && !isAbsolute(local) ? local : absolute).split('\\').join('/');
+ throw new Refused('BROWSER_SLOT_REQUIRED', `${file} launched Chrome, but the gate classified it browser-free, so it holds no browser slot; import startChrome or launchChromeProcess from test/chrome-fixture.js in that file's own import graph so the gate admits it with a browser slot`,
+ `import startChrome or launchChromeProcess from test/chrome-fixture.js in ${file}'s import graph, then run it again`);
+}
+
/** 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'] });
@@ -177,6 +194,7 @@ export async function startChrome({
diagnosticTimeoutMs = 750,
env = process.env,
} = {}) {
+ requireBrowserSlot();
if (!executable) throw new Error('Chrome was not found; install Chrome or set PULLBOARD_CHROME.');
const ownedProfile = !profileDirectory;
const profile = resolve(profileDirectory ?? mkdtempSync(join(tmpdir(), 'pullboard-chrome-')));
diff --git a/test/test-resources.test.js b/test/test-resources.test.js
index 8888962c..7018b40f 100644
--- a/test/test-resources.test.js
+++ b/test/test-resources.test.js
@@ -1,11 +1,13 @@
+/** @pullboard-test-input test-tree */
+/** @pullboard-test-input source-tree */
/** Browser admission follows current test dependencies without executing them [C7]. */
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
-import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { delimiter, dirname, join, resolve } from 'node:path';
import { test } from 'node:test';
-import { checkNeedsBrowser, testsNeedBrowser } from '../src/browser-admission.js';
+import { browserBoundFiles, checkNeedsBrowser, testsNeedBrowser } from '../src/browser-admission.js';
const TEST_RUNNER = resolve(import.meta.dirname, '../bin/run-tests.js');
@@ -228,3 +230,161 @@ test('Unicode ranges do not turn ordinary tests into browser files [C7]', async
'an escaped loader identifier still requires conservative browser admission');
assert.equal(await testsNeedBrowser(root, ['test/escaped-braced-loader.test.js']), true);
});
+
+/** The 42 files that launched Chrome in core-197's full census run on main 8b8dc50e (shout 11748). */
+const CENSUS_LAUNCHED = [
+ 'test/chrome-fixture.test.js', 'test/cockpit/activity.test.js', 'test/cockpit/addresses.test.js', 'test/cockpit/agents.test.js',
+ 'test/cockpit/demo.test.js', 'test/cockpit/doctrine.test.js', 'test/cockpit/fixture.test.js', 'test/cockpit/item-waits.test.js',
+ 'test/cockpit/items.test.js', 'test/cockpit/layout.test.js', 'test/cockpit/live.test.js', 'test/cockpit/local-origin.test.js',
+ 'test/cockpit/needs.test.js', 'test/cockpit/newcomer.test.js', 'test/cockpit/perf.test.js', 'test/cockpit/projects.test.js',
+ 'test/cockpit/prose.test.js', 'test/cockpit/references.test.js', 'test/cockpit/relay.test.js', 'test/cockpit/roadmap.test.js',
+ 'test/cockpit/scope.test.js', 'test/cockpit/search.test.js', 'test/cockpit/shared-wait.test.js', 'test/cockpit/shout-overlap.test.js',
+ 'test/cockpit/shouts.test.js', 'test/cockpit/snapshot.test.js', 'test/cockpit/spec.test.js', 'test/cockpit/stats.test.js',
+ 'test/relay-agent.test.js', 'test/relay-approval-delivery.test.js', 'test/relay-browser-fixture.test.js', 'test/relay-browser.test.js',
+ 'test/relay-device-confirmation.test.js', 'test/relay-person-actions.test.js', 'test/relay-person-credential.test.js',
+ 'test/relay-person-outbox.test.js', 'test/relay-person-page.test.js', 'test/relay-person-requests.test.js',
+ 'test/relay-setup-once.test.js', 'test/relay-snapshot-recovery.test.js', 'test/relay-snapshot-size.test.js', 'test/seal.test.js',
+];
+
+/** Git's environment without hook or outer-repository variables, so fixture git commands see only their own repo. */
+function plainGitEnvironment() {
+ return Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')));
+}
+
+/**
+ * A private runner checkout with the real runner, src/ and Chrome fixture, a private machine home whose
+ * settings file says whether gate.browserByLaunch is on, and a stand-in Chrome that only logs its arguments.
+ */
+function runnerFixture(t, tests) {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-browser-by-launch-')));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ mkdirSync(join(root, 'bin'));
+ mkdirSync(join(root, 'test'));
+ mkdirSync(join(root, 'machine'));
+ writeFileSync(join(root, 'package.json'), '{"type":"module"}\n');
+ copyFileSync(TEST_RUNNER, join(root, 'bin/run-tests.js'));
+ cpSync(resolve(import.meta.dirname, '../src'), join(root, 'src'), { recursive: true });
+ for (const helper of ['chrome-fixture.js', 'fixture-child.js']) copyFileSync(resolve(import.meta.dirname, helper), join(root, 'test', helper));
+ for (const [path, source] of Object.entries(tests)) writeFileSync(join(root, path), source);
+ const chrome = join(root, 'stand-in-browser');
+ writeFileSync(chrome, '#!/bin/sh\nprintf "%s\\n" "$1" >> "$PULLBOARD_FIXTURE_LAUNCHES"\n');
+ chmodSync(chrome, 0o755);
+ const init = spawnSync('git', ['init', '-q'], { cwd: root, env: plainGitEnvironment(), encoding: 'utf8' });
+ assert.equal(init.status, 0, init.stderr);
+ /** Run the copied runner on named files with gate.browserByLaunch set as given; return its output and records. */
+ function run(byLaunch, files) {
+ writeFileSync(join(root, 'machine/settings.json'), `${JSON.stringify({ gate: { browserByLaunch: byLaunch } })}\n`);
+ for (const record of ['markers', 'launches']) rmSync(join(root, record), { force: true });
+ const env = plainGitEnvironment();
+ for (const key of Object.keys(env)) {
+ if (key.startsWith('PULLBOARD_GATE_SLOT_') || key.startsWith('PULLBOARD_TEST_BROWSER_')) delete env[key];
+ }
+ for (const key of ['NODE_TEST_CONTEXT', 'NODE_OPTIONS', 'PULLBOARD_BROWSER_SLOT_HELD', 'PULLBOARD_TEST_FILE']) delete env[key];
+ Object.assign(env, { PULLBOARD_MACHINE_HOME: join(root, 'machine'), PULLBOARD_FIXTURE_MARKERS: join(root, 'markers'),
+ PULLBOARD_FIXTURE_LAUNCHES: join(root, 'launches'), FIXTURE_BROWSER: chrome });
+ const result = spawnSync(process.execPath, ['bin/run-tests.js', ...files], { cwd: root, env, encoding: 'utf8' });
+ /** Read one record file the fixture tests append to, empty when nothing wrote it. */
+ const lines = name => existsSync(join(root, name)) ? readFileSync(join(root, name), 'utf8').split('\n').filter(Boolean) : [];
+ return { status: result.status, output: `${result.stdout}\n${result.stderr}`, markers: lines('markers').sort(), launches: lines('launches').sort() };
+ }
+ return { root, run };
+}
+
+/** A fixture test body that records which browser slot marker its worker set: held, none, or unset. */
+const RECORD_MARKER = name => `import { appendFileSync } from 'node:fs';
+import { test } from 'node:test';
+test('${name} records its browser slot marker', () => {
+ appendFileSync(process.env.PULLBOARD_FIXTURE_MARKERS, \`${name}=\${process.env.PULLBOARD_TEST_BROWSER_SLOT ?? 'unset'}\\n\`);
+});
+`;
+
+test('only a file that reaches a browser launch takes a browser slot [C7,O5]', async t => {
+ const root = sourceFixture(t, {
+ 'test/chrome-fixture.js': "throw new Error('admission must never launch or evaluate Chrome');",
+ 'test/helpers.test.js': "import { spawnSync } from 'node:child_process';\nimport { createWaiter, findChromeExecutable } from './chrome-fixture.js';\nvoid spawnSync; void createWaiter; void findChromeExecutable;",
+ 'test/launch.test.js': "import { startChrome } from './chrome-fixture.js';\nvoid startChrome;",
+ 'test/renamed.test.js': "import { launchChromeProcess as begin } from './chrome-fixture.js';\nvoid begin;",
+ 'test/wrapped.test.js': "import { open } from '../wrapper.js';\nvoid open;",
+ 'wrapper.js': "import { startChrome as launch } from './test/chrome-fixture.js';\nexport const open = () => launch();",
+ 'test/everything.test.js': "import * as chrome from './chrome-fixture.js';\nvoid chrome;",
+ 'test/direct.test.js': "import { spawnSync } from 'node:child_process';\nspawnSync(process.env.PULLBOARD_CHROME, ['--version']);",
+ 'test/spawner.test.js': "import { spawnSync } from 'node:child_process';\nspawnSync('git', ['status']);",
+ });
+ const byLaunch = file => testsNeedBrowser(root, [file], { byLaunch: true });
+ assert.equal(await byLaunch('test/helpers.test.js'), false,
+ 'importing launch-free Chrome fixture helpers and child_process takes no browser slot by launch');
+ assert.equal(await byLaunch('test/spawner.test.js'), false, 'a process starter with no Chrome reference takes no browser slot by launch');
+ for (const file of ['launch', 'renamed', 'wrapped', 'everything', 'direct']) {
+ assert.equal(await byLaunch(`test/${file}.test.js`), true, `${file}: a graph that reaches a Chrome launch takes the browser slot`);
+ }
+ assert.equal(await byLaunch('test/cockpit/items.test.js'), true,
+ 'cockpit files keep the browser slot until test/cockpit/fixture.js carries the launch guard (#741)');
+ for (const file of ['helpers', 'spawner']) {
+ assert.equal(await testsNeedBrowser(root, [`test/${file}.test.js`], { byLaunch: false }), true,
+ `${file}: with gate.browserByLaunch off, classification is exactly today's`);
+ }
+
+ const repository = resolve(import.meta.dirname, '..');
+ const listed = spawnSync('git', ['ls-files', '-z', 'test'], { cwd: repository, env: plainGitEnvironment(), encoding: 'utf8' });
+ assert.equal(listed.status, 0, listed.stderr);
+ const tracked = listed.stdout.split('\0').filter(path => /\.test\.(?:js|mjs)$/u.test(path)).sort();
+ const bound = await browserBoundFiles(repository, tracked, { byLaunch: true });
+ const missed = CENSUS_LAUNCHED.filter(file => tracked.includes(file) && !bound.includes(file));
+ assert.deepEqual(missed, [], 'every file that launched Chrome in the census is classified browser-bound');
+ assert.ok(bound.length <= 50,
+ `about 42 of ${tracked.length} test files are browser-bound by launch (42 launched, plus cockpit files until #741); got ${bound.length}: ${bound.join(', ')}`);
+
+ const runner = runnerFixture(t, {
+ 'test/plain.test.js': `import { spawnSync } from 'node:child_process';\nvoid spawnSync;\n${RECORD_MARKER('plain')}`,
+ 'test/launcher.test.js': `import { launchChromeProcess } from './chrome-fixture.js';\n${RECORD_MARKER('launcher')}
+test('launcher starts the stand-in browser inside its slot', async () => {
+ const browser = launchChromeProcess({ executable: process.env.FIXTURE_BROWSER, args: ['launcher'] });
+ await browser.stopped;
+ await browser.close();
+});
+`,
+ });
+ const on = runner.run(true, ['test/plain.test.js', 'test/launcher.test.js']);
+ assert.equal(on.status, 0, on.output);
+ assert.deepEqual(on.markers, ['launcher=held', 'plain=none'],
+ 'by launch, only the launching file takes a browser slot; the child_process file runs without one');
+ assert.deepEqual(on.launches, ['launcher'], 'a file holding the slot launches as before');
+ const off = runner.run(false, ['test/plain.test.js', 'test/launcher.test.js']);
+ assert.equal(off.status, 0, off.output);
+ assert.deepEqual(off.markers, ['launcher=unset', 'plain=unset'], 'with the setting off the runner sets no marker, as today');
+});
+
+test('a file that launches Chrome unclassified fails by name [C7,O5]', async t => {
+ const hidden = `import { test } from 'node:test';
+test('hidden launches through a computed import', async () => {
+ const chrome = await import(['.', 'chrome-fixture.js'].join('/'));
+ const browser = chrome.launchChromeProcess({ executable: process.env.FIXTURE_BROWSER, args: ['hidden'] });
+ await browser.stopped;
+ await browser.close();
+});
+`;
+ const runner = runnerFixture(t, {
+ 'test/hidden.test.js': hidden,
+ 'test/child.test.js': `import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { test } from 'node:test';
+test('child launches from a process the test starts', () => {
+ const result = spawnSync(process.execPath, ['test/launch-helper.mjs'], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+});
+`,
+ 'test/launch-helper.mjs': "import { launchChromeProcess } from './chrome-fixture.js';\nconst browser = launchChromeProcess({ executable: process.env.FIXTURE_BROWSER, args: ['child'] });\nawait browser.stopped;\nawait browser.close();\n",
+ });
+ assert.equal(await testsNeedBrowser(runner.root, ['test/hidden.test.js'], { byLaunch: true }), false,
+ 'the fixture really is misclassified: a computed import hides the launch from the static walk');
+ assert.equal(await testsNeedBrowser(runner.root, ['test/child.test.js'], { byLaunch: true }), false,
+ 'the fixture really is misclassified: the launch is in a child process outside the import graph');
+ const on = runner.run(true, ['test/hidden.test.js', 'test/child.test.js']);
+ assert.notEqual(on.status, 0, on.output);
+ assert.match(on.output, /\[BROWSER_SLOT_REQUIRED\] test\/hidden\.test\.js launched Chrome/u, 'the in-process launch fails by file name');
+ assert.match(on.output, /\[BROWSER_SLOT_REQUIRED\] test\/child\.test\.js launched Chrome/u, 'a launch from the file\'s child process fails by file name');
+ assert.deepEqual(on.launches, [], 'the refused launches never started a browser outside the slot');
+ const off = runner.run(false, ['test/hidden.test.js']);
+ assert.equal(off.status, 0, off.output);
+ assert.deepEqual(off.launches, ['hidden'], 'with gate.browserByLaunch off the guard is inert and the file launches as today');
+});