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.

fix(queue): preserve live admission across every caller [C7,Q1,Q2,Q3,Q4]

Corey Olsonc80563b5bdf9
diff --git a/bin/run-tests.js b/bin/run-tests.js
index 3b9c5478..2166ff40 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -426,7 +426,7 @@ async function main(args) {
const fullSuite = !hasTestFiles(args);
let browser = fullSuite;
if (!browser) {
- const { testsNeedBrowser } = await import('../src/test-resources.js');
+ const { testsNeedBrowser } = await import('../src/browser-admission.js');
browser = await testsNeedBrowser(process.cwd(), explicitTestFiles(args));
}
let signal = null;
@@ -448,8 +448,7 @@ async function main(args) {
if (inherited) run(gateSlotEnvironment(inherited));
else await acquire();
} else if (legacyHeld) {
- if (browser) throw new Error('this legacy gate marker does not include the browser slot; restart the parent runner with a scoped gate lease before running browser tests');
- run({ [GATE_SLOT_HELD_ENV]: '1' });
+ throw new Error('this legacy gate marker does not identify a live machine gate lease; restart the parent runner with a scoped gate lease');
} else await acquire();
/** Acquire all required capabilities before creating the sandbox or starting test processes. */
diff --git a/src/test-resources.js b/src/browser-admission.js
similarity index 92%
rename from src/test-resources.js
rename to src/browser-admission.js
index e01b41aa..2c3ba71c 100644
--- a/src/test-resources.js
+++ b/src/browser-admission.js
@@ -1,9 +1,9 @@
/** Classify whether selected tests may launch Chrome; uncertainty keeps browser coverage enabled. */
import { readFile, realpath, stat } from 'node:fs/promises';
import { posix, relative, resolve, sep } from 'node:path';
-import { importsIn } from './module-imports.js';
+import { commonJsIn, importsIn } from './module-imports.js';
-const MODULE_SUFFIXES = ['.js', '.mjs', '.cjs', '.json'];
+const MODULE_SUFFIXES = ['.js', '.mjs', '.cjs', '.cts', '.json'];
const CHROME_FIXTURE = 'test/chrome-fixture.js';
/** Convert an in-root absolute or relative selection to a normalized repository-relative path. */
@@ -62,16 +62,19 @@ export async function testsNeedBrowser(root, files) {
seen.add(path);
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 (!sources.length) break;
+ 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:module') return true;
if (request.startsWith('node:')) continue;
if (!request.startsWith('.')) return true;
const target = await localTarget(root, paths[index], request);
diff --git a/src/cli.js b/src/cli.js
index 677305ca..be9bbd1d 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -2695,9 +2695,9 @@ function workCommands(io, args) {
/** Label the kind and item of a queued run without hiding older queue-class labels. */
function resourceRunLabel(entry) {
- const kind = entry.kind || (entry.landing ? 'landing' : entry.itemCheck ? 'item check' : '');
- const labels = [kind, entry.item ? `#${entry.item}` : '', entry.browser ? 'browser' : ''].filter(Boolean);
- return labels.length ? ` (${labels.join(', ')})` : '';
+ const priority = entry.landing ? 'landing' : entry.itemCheck ? 'item check' : entry.diagnostic ? 'diagnostic' : '';
+ const details = [entry.kind !== priority ? entry.kind : '', entry.item ? `#${entry.item}` : '', entry.browser ? 'browser' : ''].filter(Boolean);
+ return `${priority ? ` (${priority})` : ''}${details.length ? ` (${details.join(', ')})` : ''}`;
}
/** Name a known board seat for queue diagnostics without requiring an unjoined checkout to join. */
diff --git a/src/gate.js b/src/gate.js
index 011c48f4..c7136c7e 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 './test-resources.js';
+import { testsNeedBrowser } from './browser-admission.js';
import { timingFromOutput, timingRunner } from './timing.js';
const STAMP = 'pullboard-gate-green';
diff --git a/src/land.js b/src/land.js
index aef3839a..03816629 100644
--- a/src/land.js
+++ b/src/land.js
@@ -127,7 +127,7 @@ async function gateGroup(state, label) {
mkdirSync(directory, { recursive: true });
const logPath = join(directory, `${label}-${state.batch.revision}.log`);
await save(state, { state: 'gating', tip: headCommit(state.batch.root), logPath });
- const gate = await runGate(state.batch.root, state.config, { trustStamp: false, landing: true, onWait: state.onWait });
+ const gate = await runGate(state.batch.root, state.config, { trustStamp: false, landing: true, agent: 'coordinator', onWait: state.onWait });
copyFileSync(gate.log, logPath);
if (gate.profilePath) copyFileSync(gate.profilePath, `${logPath}.profile.json`);
const result = { ...gate, failures: landingFailures(gate.output, state.batch.root), tree, logPath };
@@ -146,8 +146,8 @@ async function diagnose(state, failures) {
const runner = state.config.affectedTests || (/\.[cm]?js$/u.test(file) ? 'node --test' : null);
if (!runner) throw new Refused('LAND_DIAGNOSTIC', `no runner can isolate ${file}; configure affectedTests for the project’s test runner`);
const result = await withGateSlot(state.batch.root, (lease) => runProfiledShell(state.batch.root, `${runner} ${quote(file)}`, {
- waitMs: lease.waitMs, artifactDirectory: dirname(state.batch.logPath), artifactPrefix: 'diagnostic', persistLog: true, pipefail: true, gateSlotHeld: true,
- }), { landing: true, onWait: state.onWait });
+ waitMs: lease.waitMs, artifactDirectory: dirname(state.batch.logPath), artifactPrefix: 'diagnostic', persistLog: true, pipefail: true, gateLease: lease,
+ }), { landing: true, browser: true, agent: 'coordinator', kind: 'land-diagnostic', onWait: state.onWait });
state.diagnosed.set(file, result.isGreen);
await save(state, { diagnostics: [...state.diagnosed].map(([test, isGreen]) => ({ test, isGreen })) });
if (result.isGreen) flakes.push(file);
diff --git a/src/module-imports.js b/src/module-imports.js
index d90dbad6..99e989f8 100644
--- a/src/module-imports.js
+++ b/src/module-imports.js
@@ -46,6 +46,10 @@ function look(sources) {
/** Every place the whole word import appears, in code or not; Unicode letters count as part of a word. */
const IMPORT = /(?<![\p{ID_Continue}$\u200c\u200d#])import(?![\p{ID_Continue}$\u200c\u200d])/gu;
+/** CommonJS loader words, matched with the same identifier boundaries as import. */
+const COMMON_JS = /(?<![\p{ID_Continue}$\u200c\u200d#])(?:require|createRequire)(?![\p{ID_Continue}$\u200c\u200d])/gu;
+/** Unicode escapes can spell any identifier character, so V8 probes them without decoding source. */
+const UNICODE_ESCAPE = /\\u(?:[\da-fA-F]{4}|\{[\da-fA-F]{1,6}\})/gu;
/** Whitespace and comments, which may sit between import, its parenthesis and its argument. A line comment ends at any line terminator. */
const GAP = /^(?:\s|\/\/[^\n\r\u2028\u2029]*|\/\*[\s\S]*?\*\/)*/;
@@ -117,3 +121,29 @@ export function importsIn(sources) {
return [...looks[index].imports, ...dynamic.map((at) => dynamicAt(source, at))];
});
}
+
+/** Detect actual CommonJS loader words without executing source; invalid modules are conservatively unknown.
+ *
+ * @param {string[]} sources
+ * @returns {boolean[]}
+ */
+export function commonJsIn(sources) {
+ const occurrences = sources.map((source) => [...new Set([
+ ...[...source.matchAll(COMMON_JS)].map((match) => match.index),
+ ...[...source.matchAll(UNICODE_ESCAPE)].map((match) => match.index),
+ ])]);
+ const variants = sources.flatMap((source, index) =>
+ occurrences[index].map((at) => `${source.slice(0, at)}\u0000${source.slice(at)}`),
+ );
+ const looks = look([...sources, ...variants]);
+ let next = sources.length;
+ return sources.map((source, index) => {
+ if (!looks[index].compiles) return true;
+ let found = false;
+ for (const _at of occurrences[index]) {
+ if (!looks[next].compiles) found = true;
+ next += 1;
+ }
+ return found;
+ });
+}
diff --git a/src/resources.js b/src/resources.js
index 7636de91..13629938 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -1,7 +1,7 @@
/** Machine and repository queues persist leases; diagnostics yield to landings, gates and item checks [Q1,Q2,Q3,V18]. */
-import { mkdirSync } from 'node:fs';
+import { mkdirSync, realpathSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
-import { dirname, join, resolve } from 'node:path';
+import { basename, dirname, join, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { repoInfo } from './git.js';
@@ -36,11 +36,33 @@ export function gateSlotEnvironment(lease) {
/** Resolve the local database for the requested scope. */
function databaseFile(scope, root) {
if (scope === 'board') throw new Refused('BOARD_SCOPE_UNAVAILABLE', 'board-scoped resources need the relay; run pullboard relay on');
- if (scope === 'machine') return join(machineHome(), 'resources.sqlite');
+ if (scope === 'machine') return machineResourceFile();
if (scope === 'repo') return join(repoInfo(root).commonDir, 'pullboard', 'resources.sqlite');
throw new Refused('BAD_RESOURCE_SCOPE', `unknown resource scope "${scope}"; use machine or repo`);
}
+/** Resolve the database path for the machine-wide resource pool. */
+function machineResourceFile() {
+ return join(machineHome(), 'resources.sqlite');
+}
+
+/** Canonicalize an absolute resource path without creating a missing foreign pool. */
+function canonicalResourceFile(file) {
+ let candidate = resolve(file);
+ const missing = [];
+ while (true) {
+ try {
+ return resolve(realpathSync(candidate), ...missing);
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ const parent = dirname(candidate);
+ if (parent === candidate) throw error;
+ missing.unshift(basename(candidate));
+ candidate = parent;
+ }
+ }
+}
+
/** Open and initialize the small durable queue database. */
function open(file) {
mkdirSync(dirname(file), { recursive: true });
@@ -214,8 +236,10 @@ export async function takeResource(options) {
if (landing && itemCheck) throw new Refused('BAD_RESOURCE_PRIORITY', 'a gate slot cannot be both a landing and an item check');
if (diagnostic && (landing || itemCheck)) throw new Refused('BAD_RESOURCE_PRIORITY', 'a diagnostic slot cannot also be a landing or an item check');
const file = databaseFile(scope, root);
- const pool = resolve(file);
const db = open(file);
+ let pool;
+ try { pool = canonicalResourceFile(file); }
+ catch (error) { db.close(); throw error; }
const token = randomUUID();
const requestedAt = Date.now();
const pid = process.pid;
@@ -321,9 +345,9 @@ export function inheritedGateSlot({ root = process.cwd(), browser = false } = {}
const token = process.env[GATE_SLOT_TOKEN_ENV] ?? '';
if (!markedPool && !token) return null;
if (!markedPool) throw new Refused('GATE_SLOT_MARKER_INVALID', 'the inherited gate token has no pool marker; start the child with gateSlotEnvironment(lease)');
- const pool = resolve(databaseFile('machine', root));
+ const pool = canonicalResourceFile(machineResourceFile());
// A process with a different PULLBOARD_MACHINE_HOME is independent and must join its own queue.
- if (markedPool !== pool) return null;
+ if (canonicalResourceFile(markedPool) !== pool) return null;
if (process.env[GATE_SLOT_HELD_ENV] !== '1') throw new Refused('GATE_SLOT_MARKER_INVALID', 'the inherited gate lease is missing its legacy held marker; start the child with gateSlotEnvironment(lease)');
if (!token) throw new Refused('GATE_SLOT_TOKEN_REQUIRED', 'the inherited gate pool marker has no lease token; restart the child with gateSlotEnvironment(lease)');
const db = open(pool);
diff --git a/test/gate-profile.test.js b/test/gate-profile.test.js
index c9e0fae4..f9f3b574 100644
--- a/test/gate-profile.test.js
+++ b/test/gate-profile.test.js
@@ -2,7 +2,7 @@
import assert from 'node:assert/strict';
import { execFileSync, spawn, spawnSync } from 'node:child_process';
import { once } from 'node:events';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { after, test } from 'node:test';
@@ -365,10 +365,12 @@ function waitProfileCleanup(ms) {
function copyProfileRunner(box) {
const source = resolve(import.meta.dirname, '..');
mkdirSync(join(box.repo, 'bin'), { recursive: true });
- mkdirSync(join(box.repo, 'src'), { recursive: true });
- for (const file of ['bin/run-tests.js', 'src/person.js', 'src/refused.js']) {
- writeFileSync(join(box.repo, file), readFileSync(join(source, file)));
- }
+ writeFileSync(join(box.repo, 'bin/run-tests.js'), readFileSync(join(source, 'bin/run-tests.js')));
+ const fixtureSource = join(box.repo, 'src');
+ if (existsSync(fixtureSource)) {
+ assert.deepEqual(readdirSync(fixtureSource), [], 'the profile fixture has no local source files to overwrite');
+ } else mkdirSync(fixtureSource, { recursive: true });
+ cpSync(join(source, 'src'), fixtureSource, { recursive: true });
}
/** Run one real submission with an optional real machine-slot wait and await every owned child. */
diff --git a/test/land.test.js b/test/land.test.js
index 32c24b9b..6ebbbdb4 100644
--- a/test/land.test.js
+++ b/test/land.test.js
@@ -536,6 +536,49 @@ test('land bisects a real red, skips named conflicts and refuses an unverified s
assert.equal(calls(box).length, afterCalls, 'known unchanged red is not retried');
});
+test('land diagnostics inherit their browser gate lease [C7]', () => {
+ const box = landProject();
+ const marker = join(box.dir, 'land-diagnostic-lease.json');
+ const inspector = join(box.dir, 'inspect-land-diagnostic-lease.mjs');
+ const resourcesUrl = new URL('../src/resources.js', import.meta.url).href;
+ writeFileSync(inspector, [
+ "import { writeFileSync } from 'node:fs';",
+ `import { inheritedGateSlot } from ${JSON.stringify(resourcesUrl)};`,
+ "const lease = inheritedGateSlot({ root: process.cwd(), browser: true });",
+ "if (!lease?.browser) throw new Error('focused diagnosis did not inherit its browser lease');",
+ `writeFileSync(${JSON.stringify(marker)}, JSON.stringify({ file: process.argv[2], held: process.env.PULLBOARD_GATE_SLOT_HELD ?? '', pool: process.env.PULLBOARD_GATE_SLOT_POOL ?? '', token: process.env.PULLBOARD_GATE_SLOT_TOKEN ?? '', browser: process.env.PULLBOARD_BROWSER_SLOT_HELD ?? '', inheritedBrowser: lease.browser }));`,
+ ].join('\n'));
+
+ const configPath = join(box.repo, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ config.affectedTests = `node ${JSON.stringify(inspector)}`;
+ writeFileSync(configPath, JSON.stringify(config, null, 2));
+ box.git(box.repo, 'add', 'pullboard.json');
+ const configCommit = box.tryGit(box.repo, 'commit', '-q', '-m', 'chore: inspect landing diagnostic lease');
+ assert.equal(configCommit.status, 0, configCommit.stderr);
+ const configPush = box.tryGit(box.repo, 'push', '-q', 'origin', 'main');
+ assert.equal(configPush.status, 0, configPush.stderr);
+
+ const entry = itemWorktree(box, 1, FILES[0]);
+ box.env.LAND_SUPPRESS_RED = '1';
+ try {
+ submitItem(box, entry, 'RED\n');
+ acceptItem(box, entry);
+ } finally {
+ delete box.env.LAND_SUPPRESS_RED;
+ }
+ const result = json(box, box.repo, 'land');
+ assert.equal(result.batch.state, 'flaky', 'the full gate is red while its isolated diagnosis passes');
+ assert.deepEqual(result.flakes.map(({ test: file }) => file), [FILES[0]]);
+ const inherited = JSON.parse(readFileSync(marker, 'utf8'));
+ assert.equal(inherited.file, FILES[0]);
+ assert.equal(inherited.held, '1');
+ assert.ok(inherited.pool, 'the child names the machine resource pool');
+ assert.ok(inherited.token, 'the child names the live gate lease token');
+ assert.equal(inherited.browser, '1');
+ assert.equal(inherited.inheritedBrowser, true);
+});
+
test('land holds a flake without retries and person waivers cover every failure at the exact tree [B3,R3]', () => {
const box = landProject();
const entries = verifiedFour(box, { flaky: [0, 1] });
diff --git a/test/machine.test.js b/test/machine.test.js
index 075c7117..cf2ca418 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -29,6 +29,11 @@ const NOT_MOVES = {
ONE_COORDINATOR: 'registering who is asking, before any move',
BAD_MACHINE_SETTINGS: 'machine-wide settings checked before a command runs',
BAD_GATE_SLOTS: 'machine-wide gate capacity checked before a command runs',
+ GATE_SLOT_LEASE_REQUIRED: 'a nested runner must receive its live machine gate lease before starting',
+ GATE_SLOT_MARKER_INVALID: 'an inherited machine gate capability is validated before nested work starts',
+ GATE_SLOT_TOKEN_REQUIRED: 'an inherited machine gate capability needs its exact lease token',
+ GATE_SLOT_LEASE_LOST: 'the exact machine gate lease must still be live before nested work starts',
+ BROWSER_SLOT_REQUIRED: 'browser capacity must be held before a nested browser command can run',
NO_AGENT: 'a linked coordinator must already be registered before an item move',
REMOTE_COORDINATOR_MODEL: 'a linked replica cannot redeclare the coordinator model; use the coordinator checkout',
EVENT_LOG_VERSION: 'the local board format is checked before opening it for an item move',
diff --git a/test/resource-inheritance.test.js b/test/resource-inheritance.test.js
index 06df1bdd..6cb0debd 100644
--- a/test/resource-inheritance.test.js
+++ b/test/resource-inheritance.test.js
@@ -1,8 +1,8 @@
/** Scoped machine-lease inheritance checks [Q1,Q2,Q3]. */
import assert from 'node:assert/strict';
-import { mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join, resolve } from 'node:path';
+import { join } from 'node:path';
import { after, test } from 'node:test';
import {
BROWSER_SLOT_HELD_ENV,
@@ -66,7 +66,7 @@ test('a same-pool child reuses the live gate lease without taking another slot [
try {
const markers = gateSlotEnvironment(lease);
assert.equal(markers[GATE_SLOT_HELD_ENV], '1');
- assert.equal(markers[GATE_SLOT_POOL_ENV], resolve(join(home, 'resources.sqlite')));
+ assert.equal(markers[GATE_SLOT_POOL_ENV], realpathSync(join(home, 'resources.sqlite')));
assert.equal(markers[GATE_SLOT_TOKEN_ENV], lease.token);
assert.equal(markers[BROWSER_SLOT_HELD_ENV], '');
const reused = withEnvironment({ PULLBOARD_MACHINE_HOME: home, ...markers }, () => inheritedGateSlot({ root: process.cwd() }));
@@ -78,6 +78,25 @@ test('a same-pool child reuses the live gate lease without taking another slot [
} finally { lease.release(); }
});
+/** Prove a symlinked machine-home path reuses the exact live database lease at capacity one. */
+test('a symlink alias to the same machine pool reuses its live gate lease [Q1,Q2,Q3]', async () => {
+ const realHome = machinePool();
+ const aliasParent = machinePool();
+ const aliasHome = join(aliasParent, 'machine-home');
+ symlinkSync(realHome, aliasHome, 'dir');
+ const lease = await acquireGate(realHome);
+ try {
+ const markers = gateSlotEnvironment(lease);
+ const reused = withEnvironment({ PULLBOARD_MACHINE_HOME: aliasHome, ...markers }, () => inheritedGateSlot({ root: process.cwd() }));
+ assert.ok(reused, 'the symlink spelling identifies the live parent pool');
+ assert.equal(lease.pool, realpathSync(join(realHome, 'resources.sqlite')));
+ assert.equal(reused.token, lease.token, 'the aliased child reuses the parent token rather than joining its own queue');
+ assert.equal(reused.pool, lease.pool, 'both spellings identify the same canonical database file');
+ reused.release();
+ assert.equal(resourcesAt(realHome).find((resource) => resource.name === 'gate').holders.length, 1, 'the child release leaves the parent lease alive');
+ } finally { lease.release(); }
+});
+
/** Prove a marker scoped to another machine database is ignored and does not suppress local acquisition. */
test('foreign-pool markers are ignored and the child acquires from its own pool [Q1,Q2,Q3]', async () => {
const parentHome = machinePool();
diff --git a/test/run-tests.test.js b/test/run-tests.test.js
index 0c8260aa..7a446166 100644
--- a/test/run-tests.test.js
+++ b/test/run-tests.test.js
@@ -466,6 +466,23 @@ function launchFocusedPoolRunner(fixture, testFile, extraEnv = {}) {
return child;
}
+test('a legacy held marker alone cannot bypass focused test admission [C7]', t => {
+ const fixture = makeFocusedPoolFixture(t);
+ const env = {
+ ...process.env,
+ PULLBOARD_MACHINE_HOME: fixture.machine,
+ PULLBOARD_GATE_SLOT_HELD: '1',
+ PULLBOARD_C7_SECOND_STARTED: fixture.secondStarted,
+ };
+ for (const key of ['PULLBOARD_GATE_SLOT_POOL', 'PULLBOARD_GATE_SLOT_TOKEN', 'PULLBOARD_BROWSER_SLOT_HELD']) delete env[key];
+ const result = runFixtureChild(process.execPath, [fixture.runner, 'test/second.test.js'], {
+ cwd: fixture.root, env, encoding: 'utf8',
+ });
+ assert.equal(result.status, 1, 'a self-declared legacy marker does not prove a live reservation');
+ assert.match(result.stderr, /live machine gate lease/u);
+ assert.equal(existsSync(fixture.secondStarted), false, 'the unadmitted test never starts');
+});
+
/** Read the real machine queue from the fixture pool while preserving this test process's environment. */
function focusedPoolSnapshot(machine) {
const previous = process.env.PULLBOARD_MACHINE_HOME;
diff --git a/test/test-resources.test.js b/test/test-resources.test.js
index 1b915a89..a3ee076f 100644
--- a/test/test-resources.test.js
+++ b/test/test-resources.test.js
@@ -4,7 +4,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { test } from 'node:test';
-import { testsNeedBrowser } from '../src/test-resources.js';
+import { testsNeedBrowser } from '../src/browser-admission.js';
/** Create source files for a dependency graph whose modules must never execute during admission. */
function sourceFixture(t, files) {
@@ -49,3 +49,27 @@ test('full, cockpit and uncertain test selections reserve browser capacity [C7]'
assert.equal(await testsNeedBrowser(root, files), true);
}
});
+
+test('only actual CommonJS loader words trigger browser admission in JavaScript source [C7]', async t => {
+ const root = sourceFixture(t, {
+ 'test/mentions.test.js': "// require('./chrome-fixture.js') and createRequire are only comments\nconst note = 'require createRequire';\nconst pattern = /require|createRequire/;",
+ 'test/require.test.js': 'const load = require;',
+ 'test/create-require.test.js': "import { createRequire } from 'node:module'; const load = createRequire(import.meta.url);",
+ 'test/escaped-require.test.js': 'const load = requ\\u0069re;',
+ 'test/escaped-create-require.test.js': 'const load = createRequ\\u0069re;',
+ 'test/escaped-text.test.js': '// requ\\u0069re and createRequ\\u0069re are just comment text\nconst note = "requ\\u0069re createRequ\\u0069re";',
+ 'test/module-computed.test.js': "import * as runtime from 'node:module'; const load = runtime['create' + 'Require'];",
+ 'test/browser.test.cjs': "require('./chrome-fixture.js');",
+ });
+ assert.equal(await testsNeedBrowser(root, ['test/mentions.test.js']), false,
+ 'comments, strings, and regular-expression text do not represent CommonJS loading');
+ assert.equal(await testsNeedBrowser(root, ['test/require.test.js']), true);
+ assert.equal(await testsNeedBrowser(root, ['test/create-require.test.js']), true);
+ assert.equal(await testsNeedBrowser(root, ['test/escaped-require.test.js']), true);
+ assert.equal(await testsNeedBrowser(root, ['test/escaped-create-require.test.js']), true);
+ assert.equal(await testsNeedBrowser(root, ['test/escaped-text.test.js']), false,
+ 'Unicode escape text in comments and strings does not represent an identifier');
+ assert.equal(await testsNeedBrowser(root, ['test/module-computed.test.js']), true,
+ 'node:module can create a loader through aliases or computed properties');
+ assert.equal(await testsNeedBrowser(root, ['test/browser.test.cjs']), true);
+});