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
fix(gate): classify browser checks [C7]
Corey Olson875f372c81ab
diff --git a/src/browser-admission.js b/src/browser-admission.jsindex 2c3ba71c..c7057ed7 100644--- a/src/browser-admission.js+++ b/src/browser-admission.js@@ -1,10 +1,201 @@/** Classify whether selected tests may launch Chrome; uncertainty keeps browser coverage enabled. */+import { createHash } from 'node:crypto';+import { accessSync, constants } from 'node:fs';import { readFile, realpath, stat } from 'node:fs/promises';import { posix, relative, resolve, sep } from 'node:path';import { commonJsIn, importsIn } from './module-imports.js';+import { cleanGitEnvironment, git } from './git.js';const MODULE_SUFFIXES = ['.js', '.mjs', '.cjs', '.cts', '.json'];const CHROME_FIXTURE = 'test/chrome-fixture.js';+const JOURNEYS_TEST = 'test/journeys.test.js';+const TEST_RUNNER = 'bin/run-tests.js';+const TRUSTED_TEST_RUNNER_BLOB = '2166ff4052d4c24835aff3de561948843d4ff30c';+const TRUSTED_TEST_RUNNER_SHA256 = '03df8bbb82585ff10df88ec4ecba9354301f73c091fd7eecddf1d57a84ef47f5';+const VALUE_OPTIONS = new Set(['--test-concurrency', '--test-name-pattern', '--test-shard', '--test-skip-pattern', '--test-timeout']);+const FLAG_OPTIONS = new Set(['--test-only']);+/** Known read-only or test-runner child-process modules; hash pins prevent path-only exemptions. */+const SAFE_CHILD_PROCESS_MODULES = new Map([+ ['test/fixture-child.js', { hash: '77013ed0773d16e439fc1ab235364a612d9a9d19b911dc406050e0e5a512517e', reason: 'shared fixture runner for explicit fixture commands' }],+ ['src/git.js', { hash: '35b278a548b95a55e142df2058092e7ea7ab80453d40acc9f22a86bcf68ca5ff', reason: 'runs Git commands for repository inspection' }],+ ['src/module-imports.js', { hash: 'a4853eca3cbb4140391a1003dfe145fb8e6ad46dfb06b2c4285c66fbc97fa2de', reason: 'runs the Node parser in an isolated child' }],+ ['src/resources.js', { hash: 'cd57aa2ac72315d10f07ae4b15af7ffd399d0c34b14e326651ed281b83553bee', reason: 'reads process identity with /bin/ps' }],+]);++/** Split a literal shell command into words, refusing expansion, operators, and incomplete quoting. */+function literalShellWords(command) {+ if (typeof command !== 'string' || !command.trim()) return null;+ const words = [];+ let word = '';+ let started = false;+ let quote = '';+ for (const character of command) {+ if (character === '\n' || character === '\r') return null;+ if (quote === "'") {+ if (character === "'") quote = '';+ else word += character;+ started = true;+ continue;+ }+ if (quote === '"') {+ if (character === '"') quote = '';+ else if ('$`\\'.includes(character)) return null;+ else word += character;+ started = true;+ continue;+ }+ if (character === '"' || character === "'") { quote = character; started = true; continue; }+ if (/\s/u.test(character)) {+ if (started) { words.push(word); word = ''; started = false; }+ continue;+ }+ if (';&|<>$`(){}*?[]\\'.includes(character)) return null;+ word += character;+ started = true;+ }+ if (quote) return null;+ if (started) words.push(word);+ return words;+}++/** Parse only explicit Node test-runner files and the small, literal option set used by frozen checks. */+function explicitRunnerFiles(args) {+ const files = [];+ for (let index = 0; index < args.length; index += 1) {+ const argument = args[index];+ if (argument.startsWith('-')) {+ const separator = argument.indexOf('=');+ const name = separator < 0 ? argument : argument.slice(0, separator);+ if (VALUE_OPTIONS.has(name)) {+ if (separator < 0 && ++index >= args.length) return null;+ if (separator >= 0 && !argument.slice(separator + 1)) return null;+ continue;+ }+ if (FLAG_OPTIONS.has(name) && separator < 0) continue;+ return null;+ }+ files.push(argument);+ }+ return files.length && files.every(file => /^test\/.+\.test\.(?:js|mjs|cjs|cts)$/u.test(file)) ? files : null;+}++/** Resolve a command word through PATH using the same inherited environment as the check shell.+ * @param {string} command+ * @param {string | undefined} pathValue+ * @returns {string | null}+ */+function resolveExecutable(command, pathValue = process.env.PATH) {+ if (command.includes('/')) return resolve(command);+ const suffixes = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD;.BAT').split(';') : [''];+ for (const directory of (pathValue ?? '').split(process.platform === 'win32' ? ';' : ':')) {+ for (const suffix of suffixes) {+ const candidate = resolve(directory || '.', command + suffix);+ try { accessSync(candidate, constants.X_OK); return candidate; } catch { /* continue through PATH */ }+ }+ }+ return null;+}++/** Recognize the exact output-capture and grep shape used by frozen named-test checks. */+function capturedRunner(command) {+ const opening = /^([A-Za-z_][A-Za-z0-9_]*)=\$\(/u.exec(command);+ if (!opening) return null;+ const variable = opening[1];+ const ending = ' 2>&1)';+ const bodyEnd = command.indexOf(ending, opening[0].length);+ if (bodyEnd < 0) return null;+ const inner = command.slice(opening[0].length, bodyEnd);+ let suffix = command.slice(bodyEnd + ending.length);+ const first = `; printf "%s\\n" "$${variable}"; printf "%s\\n" "$${variable}" | grep -Eq "`;+ const second = `" && printf "%s\\n" "$${variable}" | grep -Eq "`;+ if (!suffix.startsWith(first)) return null;+ suffix = suffix.slice(first.length);+ const split = suffix.indexOf(second);+ if (split < 0 || !suffix.endsWith('"')) return null;+ const patterns = [suffix.slice(0, split), suffix.slice(split + second.length, -1)];+ if (!patterns[0].startsWith('^[[:space:]]*ok [0-9]+ - ') || patterns[0].includes('$')+ || patterns[1] !== '^# fail 0$' || patterns.some(pattern => /["\\`]/u.test(pattern))) return null;+ return inner;+}++/** Read a commit's regular-file map so verification classifies only the submitted source tree. */+function committedFiles(root, commit) {+ if (typeof commit !== 'string' || !/^[0-9a-f]{40,64}$/iu.test(commit)) return null;+ let output;+ try {+ output = git(root, ['--no-replace-objects', '-c', 'core.quotepath=false', 'ls-tree', '-rz', '--full-tree', commit], {+ env: cleanGitEnvironment(), maxBuffer: 64 * 1024 * 1024,+ });+ } catch { return null; }+ if (!output) return null;+ const files = new Map();+ for (const record of output.split('\0').filter(Boolean)) {+ const tab = record.indexOf('\t');+ if (tab < 0) return null;+ const [mode, type, object] = record.slice(0, tab).split(' ');+ files.set(record.slice(tab + 1), { mode, type, object });+ }+ return files;+}++/** Read a regular committed blob, rejecting symlinks and non-file objects as uncertain. */+function committedSource(root, files, path) {+ const entry = files.get(path);+ if (!entry || entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode)) return null;+ try {+ return git(root, ['--no-replace-objects', 'cat-file', 'blob', entry.object], {+ env: cleanGitEnvironment(), maxBuffer: 16 * 1024 * 1024,+ });+ } catch { return null; }+}++/** Resolve a module edge against a committed tree without following symlinks. */+function committedTarget(files, importer, request) {+ if (typeof request !== 'string' || !request.startsWith('.')) return null;+ const raw = request.split(/[?#]/u)[0];+ const base = posix.normalize(posix.join(posix.dirname(importer), raw));+ if (base === '..' || base.startsWith('../') || base.startsWith('/')) return null;+ const candidates = posix.extname(base) ? [base] : [base, ...MODULE_SUFFIXES.map(suffix => base + suffix), ...MODULE_SUFFIXES.map(suffix => posix.join(base, `index${suffix}`))];+ const found = candidates.filter(candidate => files.has(candidate));+ return found.length === 1 && ['100644', '100755'].includes(files.get(found[0]).mode) ? found[0] : null;+}++/** 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);+}++/** Parse the frozen check and classify its explicit test files, failing closed on unknown shell. */+export async function checkNeedsBrowser(root, command, { commit, env = process.env } = {}) {+ if (env.NODE_OPTIONS) return true;+ let words = literalShellWords(command);+ if (!words) {+ const inner = capturedRunner(command);+ if (!inner) return true;+ const grep = resolveExecutable('grep', env.PATH);+ if (!grep || !['/usr/bin/grep', '/bin/grep'].includes(await realpath(grep).catch(() => ''))) return true;+ words = literalShellWords(inner);+ }+ if (!words || words.length < 3) return true;+ const node = resolveExecutable(words[0], env.PATH);+ if (!node || await realpath(node).catch(() => '') !== await realpath(process.execPath).catch(() => '')) return true;+ const runner = resolve(root, words[1]);+ if (runner !== resolve(root, TEST_RUNNER)) return true;+ const files = explicitRunnerFiles(words.slice(2));+ if (!files) return true;+ if (files.some(file => file === JOURNEYS_TEST || file === 'test/cockpit' || file.startsWith('test/cockpit/'))) return true;+ if (commit) {+ const committed = committedFiles(root, commit);+ const runnerEntry = committed?.get(TEST_RUNNER);+ if (!runnerEntry || runnerEntry.type !== 'blob' || !['100644', '100755'].includes(runnerEntry.mode)+ || runnerEntry.object !== TRUSTED_TEST_RUNNER_BLOB) return true;+ return testsNeedBrowserInTree(root, files, committed);+ }+ if (await realpath(runner).catch(() => '') !== await realpath(resolve(root, TEST_RUNNER)).catch(() => '')) return true;+ const runnerSource = await readFile(runner, 'utf8').catch(() => '');+ if (createHash('sha256').update(runnerSource).digest('hex') !== TRUSTED_TEST_RUNNER_SHA256) return true;+ return testsNeedBrowser(root, files);+}/** Convert an in-root absolute or relative selection to a normalized repository-relative path. */function repositoryPath(root, file) {@@ -44,12 +235,12 @@ async function localTarget(root, importer, request) {return found.length === 1 ? found[0] : null;}-/** Return true for full or uncertain selections, cockpit tests, or imports reaching the Chrome fixture. */-export async function testsNeedBrowser(root, files) {+/** Classify test imports from either the current checkout or one immutable committed tree. */+async function testsNeedBrowserInTree(root, files, committed = null) {if (!Array.isArray(files) || files.length === 0) return true;const normalized = files.map((file) => repositoryPath(root, file));if (normalized.some((file) => file === null)) return true;- if (normalized.some((file) => file === 'test/cockpit' || file.startsWith('test/cockpit/'))) return true;+ if (normalized.some((file) => file === JOURNEYS_TEST || file === 'test/cockpit' || file.startsWith('test/cockpit/'))) return true;let frontier = [...new Set(normalized)];const seen = new Set();@@ -63,21 +254,36 @@ export async function testsNeedBrowser(root, files) {if (path === CHROME_FIXTURE) return true;if (path.endsWith('.json')) continue;if (/\.(?:cjs|cts)$/u.test(path)) return true;- const absolute = resolve(root, ...path.split('/'));- if (!(await staysInside(root, absolute))) return true;paths.push(path);- sources.push(await readFile(absolute, 'utf8'));+ if (committed) {+ const source = committedSource(root, committed, path);+ if (source === null) return true;+ sources.push(source);+ } else {+ const absolute = resolve(root, ...path.split('/'));+ if (!(await staysInside(root, absolute))) return true;+ sources.push(await readFile(absolute, 'utf8'));+ }}if (!sources.length) break;+ if (paths.some((path, index) => (path.startsWith('test/') || SAFE_CHILD_PROCESS_MODULES.has(path))+ && namesChromeLauncher(sources[index]))) return true;if (commonJsIn(sources).some(Boolean)) return true;const imports = importsIn(sources);const next = new Set();for (let index = 0; index < imports.length; index += 1) {for (const request of imports[index]) {+ if (request === 'node:child_process') {+ const policy = SAFE_CHILD_PROCESS_MODULES.get(paths[index]);+ if (!policy || createHash('sha256').update(sources[index]).digest('hex') !== policy.hash) return true;+ continue;+ }if (request === 'node:module') return true;if (request.startsWith('node:')) continue;if (!request.startsWith('.')) return true;- const target = await localTarget(root, paths[index], request);+ const target = committed+ ? committedTarget(committed, paths[index], request)+ : await localTarget(root, paths[index], request);if (!target) return true;if (target === CHROME_FIXTURE) return true;if (!target.endsWith('.json') && !seen.has(target)) next.add(target);@@ -90,3 +296,8 @@ export async function testsNeedBrowser(root, files) {return true;}}++/** Return true for full or uncertain selections, cockpit tests, or imports reaching the Chrome fixture. */+export async function testsNeedBrowser(root, files) {+ return testsNeedBrowserInTree(root, files);+}diff --git a/src/cli.js b/src/cli.jsindex 6da76760..ba94d254 100644--- a/src/cli.js+++ b/src/cli.js@@ -18,6 +18,7 @@ import { agentSessionDigest, requirePersonChannel } from './person.js';import { bindLocalSession, localSessionMatches } from './agent-session.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';import { digestOf, gateReport, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';+import { checkNeedsBrowser } from './browser-admission.js';import { bareWorktreeFinding, codeIsFromMain, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, patchId, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';import {FIX_NOTE,@@ -2201,7 +2202,8 @@ async function verifyHere(ctx, id, { second, values }) {if (digest !== item.item_frozen_digest) throw new Refused('CRITERIA_CHANGED', 'the criterion changed; ask the coordinator to refreeze this item before checking it');const trunk = requireTrunkMerge(root, commit);refuseUnverifiedStack(root, board, item, commit, trunk);- check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs, gateLease: lease }), { browser: true, agent: me.id, item: String(id), kind: 'review', itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ const browser = await checkNeedsBrowser(root, frozenCheck(item), { commit });+ check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs, gateLease: lease }), { browser, agent: me.id, item: String(id), kind: 'review', itemCheck: true, onWait: gateWaitReporter(ctx.io) });verificationProfile = check.profile ?? null;const evidence = check.checked? `\nlast output lines (up to 40):\n${(check.outputTail ?? '(no output)').split('\n').map((line) => ` ${line}`).join('\n')}\nfull output file: ${check.outputPath ?? `(unavailable${check.outputError ? `: ${check.outputError}` : ''})`}`@@ -2604,7 +2606,8 @@ function workCommands(io, args) {throw new Refused('CHECK_CONFIRM', `the check set by ${authorName} was not run: ${check}; run pullboard check ${item.item_id} --yes after reading the command, or answer yes at the prompt`);}}- const run = await withGateSlot(ctx.info.root, (lease) => runProfiledShell(ctx.info.root, check, { waitMs: lease.waitMs, artifactPrefix: `pullboard-check-${item.item_id}`, persistLog: true, gateLease: lease }), { browser: true, agent: caller, item: String(item.item_id), kind: 'check', itemCheck: true, onWait: gateWaitReporter(io) });+ const browser = await checkNeedsBrowser(ctx.info.root, check);+ const run = await withGateSlot(ctx.info.root, (lease) => runProfiledShell(ctx.info.root, check, { waitMs: lease.waitMs, artifactPrefix: `pullboard-check-${item.item_id}`, persistLog: true, gateLease: lease }), { browser, agent: caller, item: String(item.item_id), kind: 'check', itemCheck: true, onWait: gateWaitReporter(io) });io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check, by, report: run.isGreen ? '' : digestOf(run.output) });const timings = timingDigest(run.profile);const compact = timings && !run.profile.files.lengthdiff --git a/src/gate.js b/src/gate.jsindex 765f004b..1928892a 100644--- a/src/gate.js+++ b/src/gate.js@@ -14,7 +14,7 @@ import { Refused } from './refused.js';import { GATE_SLOT_HELD_ENV, gateSlotEnvironment, inheritedGateSlot, takeResource } from './resources.js';import { loadMachineSettings } from './settings.js';import { selectAffectedTests } from './affected-tests.js';-import { testsNeedBrowser } from './browser-admission.js';+import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';import { timingFromOutput, timingRunner } from './timing.js';const STAMP = 'pullboard-gate-green';@@ -320,7 +320,7 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,const selection = config.affectedTests? selectAffectedTests(root, { base, trunk, changed }): { full: true, reason: 'affected-test selection is not enabled for this project', files: [] };- const browser = Boolean(check) || selection.full || await testsNeedBrowser(root, selection.files);+ const browser = (check ? await checkNeedsBrowser(root, check) : false) || selection.full || await testsNeedBrowser(root, selection.files);return await withGateSlot(root, (lease) => {const startedAt = Date.now();const log = gitPath(root, 'pullboard-submit.log');diff --git a/test/resources.test.js b/test/resources.test.jsindex 08f065b9..7d8d81d0 100644--- a/test/resources.test.js+++ b/test/resources.test.js@@ -1,21 +1,24 @@/** Real-process resource queue and lease coverage [Q1,Q2,Q3]. */import assert from 'node:assert/strict';-import { startFixtureChild as spawn, runFixtureChild as spawnSync, reportFixtureChildFailure, runFixtureChild } from './fixture-child.js';+import { startFixtureChild as spawn, runFixtureChild as spawnSync, reportFixtureChildFailure, runFixtureChild, runFixtureChildAsync, runFixtureGit } from './fixture-child.js';import { performance } from 'node:perf_hooks';import { once } from 'node:events';-import { chmodSync, existsSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, copyFileSync, cpSync, existsSync, mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, watch, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join, resolve } from 'node:path';+import { dirname, join, resolve } from 'node:path';import { pathToFileURL } from 'node:url';import { createInterface } from 'node:readline';import { after, test } from 'node:test';import { DatabaseSync } from 'node:sqlite';import { listResources, setResourceCapacity, takeResource } from '../src/resources.js';+import { checkNeedsBrowser } from '../src/browser-admission.js';const TEMP = [];const CHILDREN = new Set();const MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/resources.js')).href;const GATE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/gate.js')).href;+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+const TEST_RUNNER = resolve(import.meta.dirname, '../bin/run-tests.js');const POOL_MODULE_WORKER = `import { takeResource } from ${JSON.stringify(MODULE)};let announced = false;@@ -35,6 +38,14 @@ try {}} finally { lease.release(); }`;+const SUBMIT_CHECK = `+import { runSubmitGate } from ${JSON.stringify(GATE_MODULE)};+const [root, base, check] = process.argv.slice(1);+const result = await runSubmitGate(root, { gate: 'true', affectedTests: 'node bin/run-tests.js test/cpu-check.test.js' }, {+ base, changed: ['test/cpu-check.test.js'], check, agent: 'submit-check', item: '636',+});+process.stdout.write(JSON.stringify({ green: result.isGreen, full: result.full, reason: result.reason, files: result.files, checkGreen: result.check.green }) + '\\n');+`;const PROCESS_INFO_POLICY = '(version 1)(allow default)(deny process-info*)';const SANDBOX_EXEC = process.platform === 'darwin' && existsSync('/usr/bin/sandbox-exec');const PERL_FORK = process.platform === 'darwin' && existsSync('/usr/bin/perl');@@ -83,6 +94,50 @@ function fixture() {return { dir, home, first, second, env: { ...process.env, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: home } };}+/** Wait for a fixture command to create a marker file, with a hang ceiling only for failure. */+function waitForMarker(path, timeoutMs = 10_000) {+ if (existsSync(path)) return Promise.resolve();+ const watcher = watch(dirname(path), { persistent: false });+ return new Promise((resolveMarker, rejectMarker) => {+ const timer = setTimeout(() => rejectMarker(new Error(`timed out waiting for ${path}`)), timeoutMs);+ const check = () => {+ if (!existsSync(path)) return;+ clearTimeout(timer);+ watcher.close();+ resolveMarker();+ };+ watcher.on('error', error => { clearTimeout(timer); rejectMarker(error); });+ watcher.on('change', check);+ watcher.on('rename', check);+ check();+ }).finally(() => watcher.close());+}++/** Create a minimal real board whose CPU check and affected tests share the private gate pool. */+function checkProject(box) {+ const repo = box.first;+ runFixtureGit(['branch', '-M', 'main'], { cwd: repo, env: box.env });+ const initialized = runFixtureChild(process.execPath, [BIN, 'init'], { cwd: repo, env: box.env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.stderr);+ const configPath = join(repo, 'pullboard.json');+ const config = JSON.parse(readFileSync(configPath, 'utf8'));+ writeFileSync(configPath, `${JSON.stringify({ ...config, gate: 'true', spec: 'SPEC.md', affectedTests: 'node bin/run-tests.js', lanes: { web: { owns: ['web/'], specs: ['G1'] } }, shared: [] }, null, 2)}\n`);+ writeFileSync(join(repo, 'SPEC.md'), '# CPU check fixture\n\n## G · Goals\n- G1 [approved, must] The fixture keeps its board. | gate: true\n');+ writeFileSync(join(repo, 'package.json'), '{"type":"module"}\n');+ mkdirSync(join(repo, 'bin'), { recursive: true });+ cpSync(resolve(import.meta.dirname, '../src'), join(repo, 'src'), { recursive: true });+ copyFileSync(TEST_RUNNER, join(repo, 'bin/run-tests.js'));+ mkdirSync(join(repo, 'test'), { recursive: true });+ writeFileSync(join(repo, 'test/unrelated.test.js'), "import { test } from 'node:test'; test('unrelated test', () => {});\n");+ runFixtureGit(['add', '-A'], { cwd: repo, env: box.env });+ runFixtureGit(['-c', 'core.hooksPath=/dev/null', '-c', 'user.name=Resource fixture', '-c', '[email protected]', 'commit', '-q', '-m', 'fixture: initialize board'], { cwd: repo, env: box.env });+ const base = runFixtureGit(['rev-parse', 'HEAD'], { cwd: repo, env: box.env });+ writeFileSync(join(repo, 'test/cpu-check.test.js'), `import { writeFileSync } from 'node:fs';\nimport { test } from 'node:test';\ntest('item check marker', () => writeFileSync('item-check-started', 'started'));\ntest('submit check marker', () => writeFileSync('submit-check-started', 'started'));\n`);+ runFixtureGit(['add', 'test/cpu-check.test.js'], { cwd: repo, env: box.env });+ runFixtureGit(['-c', 'core.hooksPath=/dev/null', '-c', 'user.name=Resource fixture', '-c', '[email protected]', 'commit', '-q', '-m', 'test: add CPU check'], { cwd: repo, env: box.env });+ return { repo, base };+}+/** Create the previous private queue schema so simultaneous openers exercise its migration. */function oldSchema(box) {mkdirSync(box.home, { recursive: true });@@ -296,6 +351,61 @@ async function release(child) {assert.equal(code, 0, child.errors);}+test('a non-browser check does not wait for the browser slot [C7]', async () => {+ const box = fixture();+ const { repo, base } = checkProject(box);+ const itemCheck = 'node bin/run-tests.js --test-name-pattern "item check marker" test/cpu-check.test.js';+ const submitCheck = 'node bin/run-tests.js --test-name-pattern "submit check marker" test/cpu-check.test.js';+ assert.equal(await checkNeedsBrowser(repo, itemCheck), false, 'an explicit CPU-only test file is classifiable');+ assert.equal(await checkNeedsBrowser(repo, 'node bin/run-tests.js test/cockpit/brief.test.js'), true,+ 'known browser suites remain browser-gated');+ const added = runFixtureChild(process.execPath, [BIN, 'add', 'coordinator', 'CPU check item', '--check', itemCheck, '--wait', '--json'], {+ cwd: repo, env: box.env, encoding: 'utf8',+ });+ assert.equal(added.status, 0, added.stderr);+ const item = JSON.parse(added.stdout).item.item_id;+ assert.equal(existsSync(join(repo, 'item-check-started')), false, 'the setup baseline ran in its private clone');++ const browserHolder = poolWorker(box, { agent: 'check-browser-holder', browser: true, item: '636', kind: 'gate' });+ await acquired(browserHolder);+ const itemMarker = join(repo, 'item-check-started');+ const itemStarted = waitForMarker(itemMarker);+ const itemRun = runFixtureChildAsync(process.execPath, [BIN, 'check', String(item), '--yes'], { cwd: repo, env: box.env });+ let itemResult;+ try {+ await itemStarted;+ assert.ok(privateList(box).find(({ name }) => name === 'browser')?.holders.some(({ agent }) => agent === 'check-browser-holder'),+ 'the item check starts while the unrelated browser lease remains held');+ } finally {+ await release(browserHolder);+ itemResult = await itemRun;+ }+ assert.equal(itemResult.status, 0, itemResult.failure ?? itemResult.stderr);+ assert.equal(readFileSync(itemMarker, 'utf8'), 'started');++ const nextBrowserHolder = poolWorker(box, { agent: 'submit-browser-holder', browser: true, item: '636', kind: 'gate' });+ await acquired(nextBrowserHolder);+ const submitMarker = join(repo, 'submit-check-started');+ const submitStarted = waitForMarker(submitMarker);+ const submitRun = runFixtureChildAsync(process.execPath, ['--input-type=module', '-e', SUBMIT_CHECK, repo, base, submitCheck], { cwd: repo, env: box.env });+ let submitResult;+ let submitStartFailure = null;+ try {+ try { await submitStarted; }+ catch (error) { submitStartFailure = error; }+ assert.ok(privateList(box).find(({ name }) => name === 'browser')?.holders.some(({ agent }) => agent === 'submit-browser-holder'),+ 'the submission check starts while the unrelated browser lease remains held');+ } finally {+ await release(nextBrowserHolder);+ submitResult = await submitRun;+ }+ assert.equal(submitStartFailure, null, `${submitStartFailure?.message ?? ''}\n${submitResult.stdout}\n${submitResult.stderr}`);+ assert.equal(submitResult.status, 0, submitResult.failure ?? submitResult.stderr);+ assert.deepEqual(JSON.parse(submitResult.stdout), {+ green: true, full: false, reason: '', files: ['test/cpu-check.test.js'], checkGreen: true,+ }, submitResult.stderr);+});+/** Kill and reap every fixture worker before deleting its private files. */after(async () => {const running = [...CHILDREN];diff --git a/test/test-resources.test.js b/test/test-resources.test.jsindex a3ee076f..ddb3d5ef 100644--- a/test/test-resources.test.js+++ b/test/test-resources.test.js@@ -1,10 +1,13 @@/** Browser admission follows current test dependencies without executing them [C7]. */import assert from 'node:assert/strict';-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { dirname, join } from 'node:path';+import { delimiter, dirname, join, resolve } from 'node:path';import { test } from 'node:test';-import { testsNeedBrowser } from '../src/browser-admission.js';+import { checkNeedsBrowser, testsNeedBrowser } from '../src/browser-admission.js';++const TEST_RUNNER = resolve(import.meta.dirname, '../bin/run-tests.js');/** Create source files for a dependency graph whose modules must never execute during admission. */function sourceFixture(t, files) {@@ -17,6 +20,17 @@ function sourceFixture(t, files) {return root;}+/** Commit a private source fixture with a deterministic identity for immutable review coverage. */+function commitSourceFixture(root) {+ for (const args of [['init', '-q', '-b', 'main'], ['add', '-A'], ['-c', 'user.name=Fixture', '-c', '[email protected]', 'commit', '-q', '-m', 'fixture']]) {+ const result = spawnSync('git', args, { cwd: root, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr);+ }+ const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' });+ assert.equal(head.status, 0, head.stderr);+ return head.stdout.trim();+}+test('ordinary focused tests need no browser and admission never executes their modules [C7]', async t => {const root = sourceFixture(t, {'test/plain.test.js': "import '../helper.js'; import assert from 'node:assert/strict';",@@ -73,3 +87,52 @@ test('only actual CommonJS loader words trigger browser admission in JavaScript'node:module can create a loader through aliases or computed properties');assert.equal(await testsNeedBrowser(root, ['test/browser.test.cjs']), true);});++test('frozen checks classify only explicit source-backed test commands [C7]', async t => {+ const root = sourceFixture(t, {+ 'test/plain.test.js': "import '../helper.js'; import assert from 'node:assert/strict';",+ 'helper.js': "import { writeFileSync } from 'node:fs'; writeFileSync(new URL('./executed', import.meta.url), 'bad');",+ });+ mkdirSync(join(root, 'bin'), { recursive: true });+ mkdirSync(join(root, 'test'), { recursive: true });+ cpSync(resolve(import.meta.dirname, '../src'), join(root, 'src'), { recursive: true });+ copyFileSync(TEST_RUNNER, join(root, 'bin/run-tests.js'));+ writeFileSync(join(root, 'package.json'), '{"type":"module"}\n');+ writeFileSync(join(root, 'test/resources.test.js'), "import { test } from 'node:test'; test('a non-browser check does not wait for the browser slot', () => {});\n");+ const command = 'out=$(node bin/run-tests.js --test-name-pattern "a non-browser check does not wait for the browser slot" test/resources.test.js 2>&1); printf "%s\\n" "$out"; printf "%s\\n" "$out" | grep -Eq "^[[:space:]]*ok [0-9]+ - .*a non-browser check does not wait for the browser slot" && printf "%s\\n" "$out" | grep -Eq "^# fail 0$"';+ const classifyEnv = { ...process.env, PATH: [dirname(process.execPath), '/usr/bin', '/bin'].join(delimiter) };+ assert.equal(await checkNeedsBrowser(root, command, { env: classifyEnv }), false);+ assert.equal(await checkNeedsBrowser(root, command, { env: classifyEnv }), false,+ 'the supported captured runner form remains statically classifiable');+ for (const opaque of [+ 'node bin/run-tests.js test/plain.test.js; touch side-effect',+ 'node bin/run-tests.js test/*.test.js',+ 'node bin/run-tests.js test/journeys.test.js',+ 'node bin/run-tests.js test/cockpit/brief.test.js',+ 'node --test-reporter spec bin/run-tests.js test/plain.test.js',+ 'npm test',+ ]) assert.equal(await checkNeedsBrowser(root, opaque), true, opaque);++ copyFileSync(resolve(import.meta.dirname, './fixture-child.js'), join(root, 'test/fixture-child.js'));+ writeFileSync(join(root, 'test/known-fixture.test.js'), "import './fixture-child.js';\n");+ assert.equal(await testsNeedBrowser(root, ['test/known-fixture.test.js']), false,+ 'the hash-pinned shared fixture child helper remains CPU-only');+ writeFileSync(join(root, 'test/fixture-child.js'), "import { spawn } from 'node:child_process'; spawn('google-chrome', []);\n");+ assert.equal(await testsNeedBrowser(root, ['test/known-fixture.test.js']), true,+ 'changing an allowlisted helper invalidates its source hash and detects the Chrome launcher');++ writeFileSync(join(root, 'test/launcher.test.js'), "import { spawn } from 'node:child_process'; spawn('google-chrome', []);\n");+ assert.equal(await testsNeedBrowser(root, ['test/launcher.test.js']), true,+ 'a test source that names a Chrome launcher remains browser-required');+ writeFileSync(join(root, 'test/computed-launch.test.js'), "import { spawn } from 'node:child_process'; spawn(process.env.BROWSER, []);\n");+ assert.equal(await testsNeedBrowser(root, ['test/computed-launch.test.js']), true,+ 'an unknown computed child-process target remains browser-required');++ const commit = commitSourceFixture(root);+ assert.equal(await checkNeedsBrowser(root, command, { commit, env: classifyEnv }), false,+ 'review admission reads test and runner blobs from the immutable commit');+ writeFileSync(join(root, 'helper.js'), "import './test/chrome-fixture.js';");+ assert.equal(await testsNeedBrowser(root, ['test/plain.test.js']), true, 'live checks follow the current checkout');+ assert.equal(await checkNeedsBrowser(root, command, { commit, env: classifyEnv }), false,+ 'review checks follow the exact submitted commit rather than a later checkout edit');+});