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
feat(queue): admit browser and test work together [C7,Q1,Q2,Q3,Q4]
Corey Olsonea2ae870cda9
diff --git a/bin/run-tests.js b/bin/run-tests.jsindex 9e56b68a..3b9c5478 100644--- a/bin/run-tests.js+++ b/bin/run-tests.js@@ -182,7 +182,7 @@ function shellWord(value) {* @param {string} sandbox* @returns {NodeJS.ProcessEnv}*/-function testEnvironment(sandbox) {+function testEnvironment(sandbox, gateMarkers = {}) {const home = join(sandbox, 'home');const shims = join(sandbox, 'bin');mkdirSync(home, { recursive: true });@@ -223,6 +223,7 @@ function testEnvironment(sandbox) {delete env.PULLBOARD_RELAY_TOKEN; // Fixtures must supply their own scoped credentials, never an agent’s live bearer.delete env.NODE_TEST_CONTEXT;delete env.PULLBOARD_TEST_FILE;+ Object.assign(env, gateMarkers);return env;}@@ -279,6 +280,23 @@ function hasTestFiles(args) {return false;}+/** Extract explicit test paths while skipping option values, returning an empty list for discovery. */+function explicitTestFiles(args) {+ const files = [];+ let takesValue = false;+ for (let index = 0; index < args.length; index += 1) {+ const argument = args[index];+ if (takesValue) { takesValue = false; continue; }+ if (argument === '--') { files.push(...args.slice(index + 1)); break; }+ if (argument.startsWith('-')) {+ if (!argument.includes('=')) takesValue = optionTakesValue(argument);+ continue;+ }+ files.push(argument);+ }+ return files;+}+/** Match Node's default test-file patterns against a Git path for this runtime. */function isDefaultTestFile(path, includeTypeScript) {const normalized = path.replaceAll('\\', '/');@@ -357,9 +375,8 @@ function shardArguments(args) {}/** Run tests in the disposable environment, preserving a marker only when a parent holds the slot. */-function executeTests(args, sandbox, gateSlotHeld, fullSuite) {- const env = testEnvironment(sandbox);- if (gateSlotHeld) env.PULLBOARD_GATE_SLOT_HELD = '1';+function executeTests(args, sandbox, gateMarkers, fullSuite) {+ const env = testEnvironment(sandbox, gateMarkers);let selectedArgs = args;if (fullSuite) {let files;@@ -407,32 +424,55 @@ async function main(args) {}args = sharding.args;const fullSuite = !hasTestFiles(args);- const inheritedSlot = process.env.PULLBOARD_GATE_SLOT_HELD === '1';+ let browser = fullSuite;+ if (!browser) {+ const { testsNeedBrowser } = await import('../src/test-resources.js');+ browser = await testsNeedBrowser(process.cwd(), explicitTestFiles(args));+ }let signal = null;/** Keep sandbox lifetime inside the held lease, including the complete child process. */- const run = (gateSlotHeld) => {+ const run = (gateMarkers) => {const sandbox = mkdtempSync(join(tmpdir(), 'pullboard-test-run-'));try {- const result = executeTests(args, sandbox, gateSlotHeld, fullSuite);+ const result = executeTests(args, sandbox, gateMarkers, fullSuite);signal = result.signal;process.exitCode = result.status ?? 1;} finally { rmSync(sandbox, { recursive: true, force: true }); }};- if (inheritedSlot) run(true);- else {- // Direct runs, focused or full, use the public queue; preload-only imports never call main.- const [{ withGateSlot }, { loadMachineSettings }] = await Promise.all([- import('../src/gate.js'), import('../src/settings.js'),- ]);- const capacity = loadMachineSettings().gateSlots;- let announced = false;- await withGateSlot(process.cwd(), () => run(true), {- onWait: ({ holders }) => {- if (announced) return;- announced = true;- process.stderr.write(`waiting for a gate slot: ${holders.length} of ${capacity} in use\n`);- },- });+ try {+ const { GATE_SLOT_HELD_ENV, GATE_SLOT_POOL_ENV, GATE_SLOT_TOKEN_ENV, gateSlotEnvironment, inheritedGateSlot } = await import('../src/resources.js');+ const scopedMarker = process.env[GATE_SLOT_POOL_ENV] || process.env[GATE_SLOT_TOKEN_ENV];+ const legacyHeld = process.env[GATE_SLOT_HELD_ENV] === '1';+ if (scopedMarker) {+ const inherited = inheritedGateSlot({ root: process.cwd(), browser });+ 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' });+ } else await acquire();++ /** Acquire all required capabilities before creating the sandbox or starting test processes. */+ async function acquire() {+ // Direct runs use the public queue, requesting gate and browser capacity atomically when needed.+ const [{ withGateSlot }, { loadMachineSettings }] = await Promise.all([+ import('../src/gate.js'), import('../src/settings.js'),+ ]);+ const capacity = loadMachineSettings().gateSlots;+ let announced = false;+ await withGateSlot(process.cwd(), (lease) => run(gateSlotEnvironment(lease)), {+ browser, kind: fullSuite ? 'gate' : 'focused',+ onWait: ({ holders }) => {+ if (announced) return;+ announced = true;+ process.stderr.write(`waiting for a gate slot: ${holders.length} of ${capacity} in use\n`);+ },+ });+ }+ } catch (error) {+ process.stderr.write(`run-tests: ${error.message}\n`);+ process.exitCode = 1;+ return;}if (signal) process.kill(process.pid, signal);}diff --git a/src/cli.js b/src/cli.jsindex ca4f7c0e..677305ca 100644--- a/src/cli.js+++ b/src/cli.js@@ -1707,8 +1707,8 @@ function readCommands(io, { first, second, rest, values }) {if (!resources.length) io.say('no resources have been used');for (const resource of resources) {io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})`);- for (const holder of resource.holders) io.say(` held by ${agentDisplayName(agents, ctx.config, holder.agent)}${holder.repo ? ` in ${holder.repo}` : ''}${holder.landing ? ' (landing)' : holder.itemCheck ? ' (item check)' : ''} since ${holder.since}`);- resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${waiter.landing ? ' (landing)' : waiter.itemCheck ? ' (item check)' : ''}`));+ for (const holder of resource.holders) io.say(` held by ${agentDisplayName(agents, ctx.config, holder.agent)}${holder.repo ? ` in ${holder.repo}` : ''}${resourceRunLabel(holder)} since ${holder.since}`);+ resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${resourceRunLabel(waiter)}`));}return 0;},@@ -2021,7 +2021,7 @@ async function submitHere(ctx, id) {withBoard(ctx, (board) => refuseUnverifiedStack(root, board, held, commit, trunk));// Every submit proves its frozen check and reachable tests anew on this exact commit (V4,V16).// A full-gate stamp never substitutes for either proof; only an actual full fallback may stamp.- const gate = await runSubmitGate(root, ctx.config, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), onWait: gateWaitReporter(ctx.io) });+ const gate = await runSubmitGate(root, ctx.config, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), agent: me.id, item: String(id), onWait: gateWaitReporter(ctx.io) });if (!gate.isGreen) {const message = `the submission proof is red at ${commit.slice(0, 12)}; fix it, commit, submit again. ${submitGateReport(gate)}`;// No submission can follow this verdict. Read-only main comparisons must not retain the seat's write lease.@@ -2112,7 +2112,7 @@ 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, gateSlotHeld: true }), { itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ 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) });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}` : ''})`}`@@ -2515,7 +2515,7 @@ 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, gateSlotHeld: true }), { itemCheck: true, onWait: gateWaitReporter(io) });+ 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) });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.length@@ -2693,6 +2693,18 @@ 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(', ')})` : '';+}++/** Name a known board seat for queue diagnostics without requiring an unjoined checkout to join. */+function resourceAgent(ctx) {+ return ctx.info.isMain ? COORDINATOR : withBoard(ctx, board => store.agentAt(board, ctx.info.root)?.agent_id);+}+/** Build a de-duplicated queue message for a gate waiting on machine capacity. */function gateWaitReporter(io) {let last = '';@@ -3082,7 +3094,7 @@ async function hookCommand(io, { first, second }) {if (waived && isClean(info.root) && !untracked(info.root).length) io.say(`pre-push: exact landing tree covered by live person waivers in batch ${waived.id}; no ordinary green stamp`);else if (recordedException) problems = ['the landing proof has an expired or missing person waiver; ask the person for a new expiring waiver'];else {- const gate = await runGate(info.root, ctx.config, { landing, onWait: gateWaitReporter(io) });+ const gate = await runGate(info.root, ctx.config, { landing, agent: resourceAgent(ctx), onWait: gateWaitReporter(io) });if (gate.isCached) io.say('pre-push: the gate passed on this exact tree; not running it twice');if (!gate.isGreen) problems = [`the gate is red; fix it before pushing. ${gateReport(gate)}`];}@@ -3227,7 +3239,7 @@ async function runCommand(argv, io) {}if (command === 'gate') {const ctx = context(io);- const gate = await runGate(ctx.info.root, mainPolicy(ctx.info.root).config, { landing: values.landing, onWait: gateWaitReporter(io) });+ const gate = await runGate(ctx.info.root, mainPolicy(ctx.info.root).config, { landing: values.landing, agent: resourceAgent(ctx), onWait: gateWaitReporter(io) });io.result?.({ green: gate.isGreen, report: gateReport(gate) });io.say(gateReport(gate));return gate.isGreen ? 0 : 1;diff --git a/src/gate.js b/src/gate.jsindex f730d7ab..011c48f4 100644--- a/src/gate.js+++ b/src/gate.js@@ -11,9 +11,10 @@ import { dirname, join } from 'node:path';import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';import { secretsIn } from './hooks.js';import { Refused } from './refused.js';-import { GATE_SLOT_HELD_ENV, takeResource } from './resources.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 { timingFromOutput, timingRunner } from './timing.js';const STAMP = 'pullboard-gate-green';@@ -129,16 +130,17 @@ function safeLog(output) {/** Run the unchanged caller command and profile only timings already present in its output.* @param {string} root* @param {string} command- * @param {{ waitMs?: number, artifactDirectory?: string, artifactPrefix?: string, persistLog?: boolean, profileFile?: string, pipefail?: boolean, gateSlotHeld?: boolean }} [options]+ * @param {{ waitMs?: number, artifactDirectory?: string, artifactPrefix?: string, persistLog?: boolean, profileFile?: string, pipefail?: boolean, gateSlotHeld?: boolean, gateLease?: object }} [options]*/-export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory, artifactPrefix = 'pullboard-gate', persistLog = false, profileFile, pipefail = false, gateSlotHeld = false } = {}) {+export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory, artifactPrefix = 'pullboard-gate', persistLog = false, profileFile, pipefail = false, gateSlotHeld = false, gateLease } = {}) {const directory = artifactDirectory ?? dirname(gitPath(root, LOG));mkdirSync(directory, { recursive: true, mode: 0o700 });const id = randomUUID();const profilePath = profileFile ?? join(directory, `${artifactPrefix}-${id}.profile.json`);const logPath = persistLog ? join(directory, `${artifactPrefix}-${id}.log`) : null;const started = Date.now();- const run = runShell(root, command, { pipefail, env: gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {} });+ const inherited = gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {};+ const run = runShell(root, command, { pipefail, env: inherited });const profile = writeTimingProfile(profilePath, {...timingFromOutput(run.output, timingRunner(command)),waitMs: Math.max(0, Math.round(waitMs)), wallMs: Math.max(0, Date.now() - started),@@ -150,12 +152,13 @@ export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory,/** Run an independent focused comparison without blocking other holders of the machine pool.* @param {string} root* @param {string} command- * @param {{ waitMs?: number, gateSlotHeld?: boolean }} [options]+ * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object }} [options]* @returns {Promise<object>} The unchanged shell verdict and its private timing profile.*/-export async function runProfiledShellAsync(root, command, { waitMs = 0, gateSlotHeld = false } = {}) {+export async function runProfiledShellAsync(root, command, { waitMs = 0, gateSlotHeld = false, gateLease } = {}) {const started = Date.now();- const env = { ...gitChildEnv(root), ...(gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {}) };+ const inherited = gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {};+ const env = { ...gitChildEnv(root), ...inherited };const child = spawn(`(\n${command}\n) 2>&1`, { cwd: root, env, shell: true, stdio: ['ignore', 'pipe', 'pipe'] });const chunks = [];let bytes = 0;@@ -230,11 +233,16 @@ function hasPipeline(command) {/** Run work under the machine queue: landing gates, ordinary gates, item checks, then diagnostics.** @param {string} root - Checkout used to locate the machine resource database.- * @param {(lease: { waitMs: number }) => any | Promise<any>} action - Work to perform while holding a slot.- * @param {{ landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, onWait?: (state: object) => void }} [options] - Queue class and progress reporter.+ * @param {(lease: { waitMs: number, token?: string, pool?: string, browser?: boolean, release: () => void }) => any | Promise<any>} action - Work to perform while holding a slot.+ * @param {{ landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, agent?: string, item?: string|number, kind?: string, onWait?: (state: object) => void }} [options] - Queue class and progress reporter.* @returns {Promise<any>} The action's result after releasing its lease.*/-export async function withGateSlot(root, action, { landing = false, itemCheck = false, diagnostic = false, onWait } = {}) {+export async function withGateSlot(root, action, { landing = false, itemCheck = false, diagnostic = false, browser = false, agent, item = '', kind = '', onWait } = {}) {+ const inherited = inheritedGateSlot({ root, browser });+ if (inherited) {+ try { return await action(inherited); }+ finally { inherited.release(); }+ }const capacityProvider = () => loadMachineSettings().gateSlots;const lease = await takeResource({name: 'gate',@@ -243,9 +251,13 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =scope: 'machine',root,repo: root,+ agent,+ item: String(item),+ kind,landing,itemCheck,diagnostic,+ browser,allowIdleCapacityUpdate: true,onWait,});@@ -266,22 +278,24 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =** @param {string} root* @param {any} config- * @param {{ trustStamp?: boolean, onWait?: (state: object) => void, landing?: boolean }} [options]+ * @param {{ trustStamp?: boolean, onWait?: (state: object) => void, landing?: boolean, agent?: string, item?: string|number }} [options]* @returns {Promise<{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string, profile?: object, profilePath?: string }>}*/-export async function runGate(root, config, { trustStamp = true, onWait, landing = false } = {}) {+export async function runGate(root, config, { trustStamp = true, onWait, landing = false, agent, item = '' } = {}) {if (!config.gate.trim()) {throw new Refused('NO_GATE', 'no gate configured; set "gate" in pullboard.json, e.g. "npm test"');}if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };- return await withGateSlot(root, (lease) => fullGateRun(root, config, trustStamp, { waitMs: lease.waitMs }), { landing, onWait });+ return await withGateSlot(root, (lease) => fullGateRun(root, config, trustStamp, { waitMs: lease.waitMs, gateLease: lease }), {+ landing, browser: true, agent, item, kind: landing ? 'landing' : 'gate', onWait,+ });}/** Run a full gate while its caller owns the queue lease; only a full run may stamp its tree. */-function fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPath(root, LOG) } = {}) {+function fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPath(root, LOG), gateLease } = {}) {if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };const before = committedTree(root);- const { isGreen, output, seconds, profile, profilePath } = runProfiledShell(root, config.gate, { waitMs, pipefail: true, profileFile: `${log}.profile.json`, gateSlotHeld: true });+ const { isGreen, output, seconds, profile, profilePath } = runProfiledShell(root, config.gate, { waitMs, pipefail: true, profileFile: `${log}.profile.json`, gateLease });writeFileSync(log, output);if (isGreen && before !== null && committedTree(root) === before) writeFileSync(gitPath(root, STAMP), `${before}\n`);return { isGreen, isCached: false, output, seconds, log, profile, profilePath };@@ -298,21 +312,22 @@ function commandWord(value) {** @param {string} root* @param {any} config- * @param {{base:string|null, trunk?:string, changed?:string[], check:string, onWait?:(state:object)=>void}} options+ * @param {{base:string|null, trunk?:string, changed?:string[], check:string, agent?:string, item?:string|number, kind?:string, onWait?:(state:object)=>void}} options* @returns {Promise<any>}*/-export async function runSubmitGate(root, config, { base, trunk, changed, check, onWait }) {+export async function runSubmitGate(root, config, { base, trunk, changed, check, agent, item = '', kind = 'submit', onWait }) {if (!config.gate.trim()) throw new Refused('NO_GATE', 'no gate configured; set "gate" in pullboard.json, e.g. "npm test"');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);return await withGateSlot(root, (lease) => {const startedAt = Date.now();const log = gitPath(root, 'pullboard-submit.log');const checkLog = `${log}.check.log`;const proofLog = `${log}.proof.log`;const criterion = check ? runProfiledShell(root, check, {- waitMs: lease.waitMs, profileFile: `${checkLog}.profile.json`, gateSlotHeld: true,+ waitMs: lease.waitMs, profileFile: `${checkLog}.profile.json`, gateLease: lease,}) : { isGreen: true, output: '', seconds: 0 };if (check) writeFileSync(checkLog, safeLog(criterion.output), { mode: 0o600 });const receipt = { command: check, green: criterion.isGreen, seconds: criterion.seconds, checked: Boolean(check),@@ -338,16 +353,16 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,// The proof already owns this lease: its phase profile has no additional queue wait.const proofWait = check ? 0 : lease.waitMs;let proof;- if (selection.full) proof = fullGateRun(root, config, false, { waitMs: proofWait, log: proofLog });+ if (selection.full) proof = fullGateRun(root, config, false, { waitMs: proofWait, log: proofLog, gateLease: lease });else if (!selection.files.length) proof = { isGreen: true, output: '', seconds: 0, isCached: false, log: '' };else {const command = `${config.affectedTests.trimEnd()} ${selection.files.map(path => commandWord('./' + path)).join(' ')}`;- proof = { ...runProfiledShell(root, command, { waitMs: proofWait, profileFile: `${proofLog}.profile.json`, gateSlotHeld: true }), isCached: false, log: proofLog };+ proof = { ...runProfiledShell(root, command, { waitMs: proofWait, profileFile: `${proofLog}.profile.json`, gateLease: lease }), isCached: false, log: proofLog };writeFileSync(proofLog, proof.output);}writeFileSync(log, `item check:\n${criterion.output}\n${selection.full ? 'full gate' : 'affected tests'}:\n${proof.output}`);return finish(proof);- }, { onWait });+ }, { browser, agent, item, kind, itemCheck: true, onWait });}/** Describe precisely which submission proof ran, including absent checks and full fallbacks. */diff --git a/src/main-red.js b/src/main-red.jsindex 5604a31c..c6004099 100644--- a/src/main-red.js+++ b/src/main-red.js@@ -167,7 +167,7 @@ export async function compareMainFailures(root, profile, onWait, output = '') {await withGateSlot(root, async lease => {const measured = await withMainCheckout(root, main.commit, async checkout => {const command = `${policy.config.affectedTests.trimEnd()} ${shellWord('./' + path)}`;- const run = await runProfiledShellAsync(checkout, command, { gateSlotHeld: true, waitMs: lease.waitMs });+ const run = await runProfiledShellAsync(checkout, command, { gateLease: lease, waitMs: lease.waitMs });return { result: run.isGreen ? 'green' : 'red' };});if (measured.unavailable) throw new Error(measured.unavailable);@@ -176,7 +176,7 @@ export async function compareMainFailures(root, profile, onWait, output = '') {cache.entries[main.commit] ??= {};cache.entries[main.commit][path] = measured;writeCache(file, cache);- }, { diagnostic: true, onWait });+ }, { diagnostic: true, browser: true, agent: process.env.PULLBOARD_AGENT, kind: 'main-red', onWait });}catch (error) { failed ??= error; }}diff --git a/src/resources.js b/src/resources.jsindex 01837c9e..7636de91 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 { execFileSync } from 'node:child_process';-import { dirname, join } from 'node:path';+import { dirname, join, resolve } from 'node:path';import { randomUUID } from 'node:crypto';import { DatabaseSync } from 'node:sqlite';import { repoInfo } from './git.js';@@ -16,6 +16,22 @@ const processIdentities = new Map();/** Mark child commands whose parent already owns a machine gate slot. */export const GATE_SLOT_HELD_ENV = 'PULLBOARD_GATE_SLOT_HELD';+export const GATE_SLOT_POOL_ENV = 'PULLBOARD_GATE_SLOT_POOL';+export const GATE_SLOT_TOKEN_ENV = 'PULLBOARD_GATE_SLOT_TOKEN';+export const BROWSER_SLOT_HELD_ENV = 'PULLBOARD_BROWSER_SLOT_HELD';++/** Build child markers that identify the exact machine queue lease and its browser capacity. */+export function gateSlotEnvironment(lease) {+ if (!lease || lease.name !== 'gate' || lease.scope !== 'machine' || typeof lease.pool !== 'string' || typeof lease.token !== 'string') {+ throw new Refused('GATE_SLOT_LEASE_REQUIRED', 'pass the live machine gate lease when starting a child test process');+ }+ return {+ [GATE_SLOT_HELD_ENV]: '1',+ [GATE_SLOT_POOL_ENV]: lease.pool,+ [GATE_SLOT_TOKEN_ENV]: lease.token,+ [BROWSER_SLOT_HELD_ENV]: lease.browser ? '1' : '',+ };+}/** Resolve the local database for the requested scope. */function databaseFile(scope, root) {@@ -35,9 +51,9 @@ function open(file) {db.exec('BEGIN IMMEDIATE');transaction = true;db.exec(`CREATE TABLE IF NOT EXISTS resource (name TEXT PRIMARY KEY, capacity INTEGER NOT NULL);- CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0);+ CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0, browser INTEGER NOT NULL DEFAULT 0, item TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT '');CREATE INDEX IF NOT EXISTS holder_name ON holder(name);- CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0);+ CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0, browser INTEGER NOT NULL DEFAULT 0, item TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT '');CREATE INDEX IF NOT EXISTS waiter_name_ticket ON waiter(name, ticket);`);for (const table of ['holder', 'waiter']) {const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(({ name }) => name);@@ -45,6 +61,9 @@ function open(file) {if (!columns.includes('landing')) db.exec(`ALTER TABLE ${table} ADD COLUMN landing INTEGER NOT NULL DEFAULT 0`);if (!columns.includes('item_check')) db.exec(`ALTER TABLE ${table} ADD COLUMN item_check INTEGER NOT NULL DEFAULT 0`);if (!columns.includes('diagnostic')) db.exec(`ALTER TABLE ${table} ADD COLUMN diagnostic INTEGER NOT NULL DEFAULT 0`);+ if (!columns.includes('browser')) db.exec(`ALTER TABLE ${table} ADD COLUMN browser INTEGER NOT NULL DEFAULT 0`);+ if (!columns.includes('item')) db.exec(`ALTER TABLE ${table} ADD COLUMN item TEXT NOT NULL DEFAULT ''`);+ if (!columns.includes('kind')) db.exec(`ALTER TABLE ${table} ADD COLUMN kind TEXT NOT NULL DEFAULT ''`);}db.exec('COMMIT');transaction = false;@@ -133,32 +152,41 @@ function update(db, action) {/** Current holders and the landing-first line, then gates, item checks and diagnostics. */function snapshot(db, name) {/** Preserve older public entries while naming diagnostics as a distinct queue class. */- const project = ({ diagnostic, ...entry }) => ({ ...entry, landing: entry.landing === 1,- itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}) });- const holders = db.prepare('SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic FROM holder WHERE name = ? ORDER BY since, token').all(name).map(project);- const line = db.prepare('SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic FROM waiter WHERE name = ? ORDER BY landing DESC, diagnostic, item_check, ticket').all(name).map(project);+ const project = ({ diagnostic, browser, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,+ itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),+ ...(browser === 1 ? { browser: true } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}) });+ // Browser is an additional capability on a gate lease, not a second partially held row.+ const where = name === 'browser' ? 'name = ? AND browser = 1' : 'name = ?';+ const sourceName = name === 'browser' ? 'gate' : name;+ const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM holder WHERE ${where} ORDER BY since, token`).all(sourceName).map(project);+ const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM waiter WHERE ${where} ORDER BY landing DESC, diagnostic, item_check, ticket`).all(sourceName).map(project);return { holders, line };}-/** Count eligible waiters ahead of a ticket by priority and FIFO order; a holder cannot monopolize a landing. */-function waiterPosition(db, name, ticket) {- const waiters = db.prepare('SELECT ticket, pid, agent, repo, landing, item_check AS itemCheck FROM waiter WHERE name = ? ORDER BY ticket').all(name);- const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(name);+/** Count reported or admissible queue position separately so blocked work cannot distort the visible line. */+function waiterPosition(db, name, ticket, { eligibleOnly = false } = {}) {+ const queueName = name === 'browser' ? 'gate' : name;+ const waiters = db.prepare('SELECT ticket, pid, agent, repo, landing, item_check AS itemCheck, browser FROM waiter WHERE name = ? ORDER BY ticket').all(queueName);+ const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(queueName);+ const browserBusy = db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count > 0;/** A live process owns its leases even if it changes descriptive agent or repository labels. */const holdsSlot = (waiter) => holders.some((holder) => holder.pid === waiter.pid);/** Leave a waiting independent landing a slot before a holder takes another lease. */const blockedByLanding = (waiter) => holdsSlot(waiter)&& waiters.some((other) => other.landing === 1 && other.pid !== waiter.pid);- const eligible = waiters.filter((waiter) => !blockedByLanding(waiter));- const current = waiters.find((waiter) => waiter.ticket === ticket);- if (!current) return eligible.length + 1;- const currentIndex = eligible.findIndex((waiter) => waiter.ticket === ticket);- if (currentIndex < 0) return Math.max(2, eligible.length + 1);/** Map queue entries to their declared precedence class. */// Keep the older client's ranking: diagnostic takers yield their FIFO ticket to later checks.const rank = (waiter) => waiter.landing === 1 ? 0 : waiter.itemCheck === 1 ? 2 : 1;+ const line = name === 'browser' ? waiters.filter((waiter) => waiter.browser === 1) : waiters;+ const considered = line.filter((waiter) => !blockedByLanding(waiter)+ // Browser availability affects admission only; reported positions retain every browser waiter.+ && (!eligibleOnly || name === 'browser' || waiter.browser !== 1 || !browserBusy));+ const current = line.find((waiter) => waiter.ticket === ticket);+ if (!current) return eligibleOnly ? Number.MAX_SAFE_INTEGER : line.length + 1;+ const currentIndex = considered.findIndex((waiter) => waiter.ticket === ticket);+ if (currentIndex < 0) return eligibleOnly ? Number.MAX_SAFE_INTEGER : Math.max(2, considered.length + 1);const currentRank = rank(current);- return eligible.filter((waiter) => rank(waiter) < currentRank || (rank(waiter) === currentRank && waiter.ticket <= ticket)).length;+ return considered.filter((waiter) => rank(waiter) < currentRank || (rank(waiter) === currentRank && waiter.ticket <= ticket)).length;}/** Pause briefly between durable queue checks. */@@ -167,8 +195,8 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr/*** Join the existing queue; diagnostics rejoin behind later item checks so older clients agree on priority.*- * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.- * @returns {Promise<{ name: string, scope: string, token: string, waitMs: number, release: () => void, renew: () => void }>}+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.+ * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}*/export async function takeResource(options) {const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;@@ -177,9 +205,16 @@ export async function takeResource(options) {const landing = options.landing === true;const itemCheck = options.itemCheck === true;const diagnostic = options.diagnostic === true;+ const browser = options.browser === true;+ const item = options.item ?? '';+ const kind = options.kind ?? '';+ if (browser && name !== 'gate') throw new Refused('BAD_BROWSER_RESOURCE', 'browser capacity can only be acquired together with the machine gate; request name "gate" with browser: true');+ if (name === 'browser' && !browser) throw new Refused('BAD_BROWSER_RESOURCE', 'browser capacity is acquired only as part of a gate lease; request name "gate" with browser: true');+ if (typeof item !== 'string' || typeof kind !== 'string') throw new Refused('BAD_RESOURCE_METADATA', 'resource item and kind metadata must be text');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);const token = randomUUID();const requestedAt = Date.now();@@ -201,35 +236,43 @@ export async function takeResource(options) {db.prepare('UPDATE resource SET capacity = ? WHERE name = ?').run(currentCapacity, name);}db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO NOTHING').run(name, currentCapacity);+ if (browser) {+ const browserResource = db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get();+ if (browserResource && browserResource.capacity !== 1) throw new Refused('RESOURCE_CAPACITY_MISMATCH', 'resource "browser" has fixed capacity 1');+ db.prepare("INSERT INTO resource(name, capacity) VALUES ('browser', 1) ON CONFLICT(name) DO NOTHING").run();+ }// Older queue clients see diagnostics as item checks, never as ordinary gates.- db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic));+ db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);});while (true) {const acquired = update(db, () => {let waiter = db.prepare('SELECT ticket, landing, item_check AS itemCheck, diagnostic FROM waiter WHERE token = ?').get(token);if (!waiter) {queuedAt = new Date().toISOString();- const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic));+ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);return { acquired: false, state: { ...snapshot(db, name), position: waiterPosition(db, name, Number(rejoined.lastInsertRowid)), rejoined: true } };}if (diagnostic && db.prepare('SELECT 1 FROM waiter WHERE name=? AND diagnostic=0 AND item_check=1 AND ticket>? LIMIT 1').get(name, waiter.ticket)) {// An older item-check client only knows FIFO within its class. Move behind it so both// old and new callers agree who goes first instead of waiting on one another forever.db.prepare('DELETE FROM waiter WHERE token=?').run(token);- const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), 0, 1, 1);+ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), 0, 1, 1, Number(browser), item, kind);waiter = { ticket: Number(rejoined.lastInsertRowid) };}db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);const spot = snapshot(db, name);- const position = waiterPosition(db, name, waiter.ticket);+ const reportPosition = waiterPosition(db, name, waiter.ticket);+ const admissionPosition = waiterPosition(db, name, waiter.ticket, { eligibleOnly: true });const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;- if (position === 1 && spot.holders.length < limit) {+ const browserAdmissionPosition = browser ? waiterPosition(db, 'browser', waiter.ticket, { eligibleOnly: true }) : 0;+ const browserHolders = browser ? db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count : 0;+ if (admissionPosition === 1 && spot.holders.length < limit && (!browser || (browserAdmissionPosition === 1 && browserHolders < 1))) {db.prepare('DELETE FROM waiter WHERE token = ?').run(token);const acquiredAt = new Date().toISOString();- db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic));+ db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);return { acquired: true, state: { ...spot, position: 0 } };}- return { acquired: false, state: { ...spot, position } };+ return { acquired: false, state: { ...spot, position: reportPosition } };});if (acquired.acquired) {let released = false;@@ -260,7 +303,7 @@ export async function takeResource(options) {throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);}};- return { name, scope, token, waitMs: Math.max(0, Date.now() - requestedAt), release, renew };+ return { name, scope, token, pool, browser, waitMs: Math.max(0, Date.now() - requestedAt), release, renew };}options.onWait?.(acquired.state);await pause(POLL_MS);@@ -272,10 +315,37 @@ export async function takeResource(options) {}}+/** Reuse a same-machine gate lease in a child without queueing or acquiring a partial browser slot. */+export function inheritedGateSlot({ root = process.cwd(), browser = false } = {}) {+ const markedPool = process.env[GATE_SLOT_POOL_ENV] ?? '';+ 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));+ // A process with a different PULLBOARD_MACHINE_HOME is independent and must join its own queue.+ if (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);+ let holder;+ try {+ holder = update(db, () => db.prepare("SELECT browser FROM holder WHERE name = 'gate' AND token = ?").get(token));+ } finally { db.close(); }+ if (!holder) throw new Refused('GATE_SLOT_LEASE_LOST', 'the inherited gate lease is missing or expired; remove stale gate markers or let the parent reacquire the gate slot');+ const expectedBrowserMarker = holder.browser === 1 ? '1' : '';+ if (process.env[BROWSER_SLOT_HELD_ENV] !== expectedBrowserMarker) throw new Refused('GATE_SLOT_MARKER_INVALID', 'the inherited browser marker does not match its live gate lease; restart the child with gateSlotEnvironment(lease)');+ if (browser && holder.browser !== 1) throw new Refused('BROWSER_SLOT_REQUIRED', 'the inherited gate lease does not hold the browser slot; release it and reacquire gate with browser: true before launching Chrome');+ return {+ name: 'gate', scope: 'machine', token, pool, browser: holder.browser === 1, waitMs: 0,+ release() {}, renew() {},+ };+}+/** Change a resource's capacity only while its queue is empty, persisting related settings under the same lock. */export function setResourceCapacity({ name, capacity, scope = 'machine', root = process.cwd(), persist = () => {} }) {if (typeof name !== 'string' || !name.trim() || name.trim() !== name) throw new Refused('BAD_RESOURCE_NAME', 'resource name must be nonempty trimmed text');if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');+ if (name === 'browser' && capacity !== 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'browser resource capacity is fixed at 1');const db = open(databaseFile(scope, root));try {return update(db, () => {diff --git a/src/test-resources.js b/src/test-resources.jsnew file mode 100644index 00000000..e01b41aa--- /dev/null+++ b/src/test-resources.js@@ -0,0 +1,89 @@+/** 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';++const MODULE_SUFFIXES = ['.js', '.mjs', '.cjs', '.json'];+const CHROME_FIXTURE = 'test/chrome-fixture.js';++/** Convert an in-root absolute or relative selection to a normalized repository-relative path. */+function repositoryPath(root, file) {+ if (typeof file !== 'string' || !file) return null;+ const absoluteRoot = resolve(root);+ const absolute = resolve(absoluteRoot, file);+ const rel = relative(absoluteRoot, absolute);+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`)) return null;+ return rel.split(sep).join('/');+}++/** Check that a resolved path stays inside the real repository, including through symlinks. */+async function staysInside(root, absolute) {+ const [realRoot, realTarget] = await Promise.all([realpath(root), realpath(absolute)]);+ return realTarget.startsWith(realRoot + sep);+}++/** Resolve one literal relative module request using file metadata, returning null when ambiguous. */+async function localTarget(root, 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 = [];+ for (const candidate of candidates) {+ const absolute = resolve(root, ...candidate.split('/'));+ try {+ if (!(await staysInside(root, absolute))) return null;+ if ((await stat(absolute)).isFile()) found.push(candidate);+ } catch (error) {+ if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error;+ }+ }+ 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) {+ 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;++ let frontier = [...new Set(normalized)];+ const seen = new Set();+ try {+ while (frontier.length) {+ const paths = [];+ const sources = [];+ for (const path of frontier) {+ if (seen.has(path)) continue;+ seen.add(path);+ if (path === CHROME_FIXTURE) return true;+ if (path.endsWith('.json')) continue;+ 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;+ 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.startsWith('node:')) continue;+ if (!request.startsWith('.')) return true;+ const target = 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);+ }+ }+ frontier = [...next];+ }+ return false;+ } catch {+ return true;+ }+}diff --git a/src/trusted-policy.js b/src/trusted-policy.jsindex aad545dd..76f2c7b4 100644--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { StringDecoder } from 'node:string_decoder';import { fileURLToPath } from 'node:url';-import { GATE_SLOT_HELD_ENV } from './resources.js';+import { GATE_SLOT_HELD_ENV, gateSlotEnvironment } from './resources.js';import { configFromSource } from './config.js';import { cleanGitEnvironment, gitConfig, invalidateGitFacts, mainCheckout, refuseGrafts } from './git.js';import { secretsIn } from './hooks.js';@@ -146,9 +146,9 @@ export function frozenCheck(item) {/** Run the frozen check at the exact submitted commit in a private clone, leaving live worktrees untouched.* @param {string} root* @param {object} item- * @param {{ waitMs?: number, gateSlotHeld?: boolean }} [options] - Queue wait before the private check started.+ * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object }} [options] - Queue wait before the private check started.*/-export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false } = {}) {+export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false, gateLease } = {}) {const command = frozenCheck(item);if (!command) return { state: 'pass', green: true, checked: false, report: '' };let config;@@ -163,7 +163,8 @@ export function checkAtCommit(root, item, { waitMs = 0, gateSlotHeld = false } =const verifierHome = process.env.HOME ?? process.env.USERPROFILE;const npmCache = process.env.npm_config_cache ?? join(verifierHome ?? home, '.npm');const env = { ...cleanGitEnvironment(), HOME: home, PULLBOARD_HOME: join(home, '.pullboard'), PULLBOARD_MACHINE_HOME: join(home, 'machine'), GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', npm_config_cache: npmCache };- if (gateSlotHeld) env[GATE_SLOT_HELD_ENV] = '1';+ if (gateLease) Object.assign(env, gateSlotEnvironment(gateLease));+ else if (gateSlotHeld) env[GATE_SLOT_HELD_ENV] = '1';delete env.PULLBOARD_RELAY_TOKEN;let installOutput = '';let checkOutput = '';diff --git a/test/resource-inheritance.test.js b/test/resource-inheritance.test.jsnew file mode 100644index 00000000..06df1bdd--- /dev/null+++ b/test/resource-inheritance.test.js@@ -0,0 +1,145 @@+/** Scoped machine-lease inheritance checks [Q1,Q2,Q3]. */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { after, test } from 'node:test';+import {+ BROWSER_SLOT_HELD_ENV,+ GATE_SLOT_HELD_ENV,+ GATE_SLOT_POOL_ENV,+ GATE_SLOT_TOKEN_ENV,+ gateSlotEnvironment,+ inheritedGateSlot,+ listResources,+ takeResource,+} from '../src/resources.js';++const TEMP = [];++/** Remove every private machine pool after its test releases its lease. */+function removeTemporaryPools() {+ for (const path of TEMP) rmSync(path, { recursive: true, force: true });+}++after(removeTemporaryPools);++/** Make a private machine-home directory for one lease test. */+function machinePool() {+ const path = mkdtempSync(join(tmpdir(), 'pullboard-resource-inheritance-'));+ TEMP.push(path);+ return path;+}++/** Apply environment values only for a synchronous operation, then restore them immediately. */+function withEnvironment(values, action) {+ const previous = new Map(Object.keys(values).map((key) => [key, process.env[key]]));+ for (const [key, value] of Object.entries(values)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ try { return action(); }+ finally {+ for (const [key, value] of previous) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+}++/** Acquire a machine gate lease while restoring the caller's machine-home override before awaiting it. */+function acquireGate(home, browser = false) {+ return withEnvironment({ PULLBOARD_MACHINE_HOME: home }, () => takeResource({+ name: 'gate', capacity: 1, browser, root: process.cwd(), agent: `inheritance-${browser ? 'browser' : 'gate'}`,+ }));+}++/** Read one private resource snapshot without retaining its machine-home override. */+function resourcesAt(home) {+ return withEnvironment({ PULLBOARD_MACHINE_HOME: home }, () => listResources());+}++/** Prove a child reuses the exact live lease at capacity one without consuming another slot. */+test('a same-pool child reuses the live gate lease without taking another slot [Q1,Q2,Q3]', async () => {+ const home = machinePool();+ const lease = await acquireGate(home);+ 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_TOKEN_ENV], lease.token);+ assert.equal(markers[BROWSER_SLOT_HELD_ENV], '');+ const reused = withEnvironment({ PULLBOARD_MACHINE_HOME: home, ...markers }, () => inheritedGateSlot({ root: process.cwd() }));+ assert.deepEqual({ name: reused.name, scope: reused.scope, pool: reused.pool, token: reused.token, browser: reused.browser, waitMs: reused.waitMs }, {+ name: 'gate', scope: 'machine', pool: lease.pool, token: lease.token, browser: false, waitMs: 0,+ });+ reused.release();+ assert.equal(resourcesAt(home)[0].holders.length, 1, 'the child release is inert and 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();+ const childHome = machinePool();+ const parentLease = await acquireGate(parentHome);+ let childLease;+ try {+ const markers = gateSlotEnvironment(parentLease);+ const inherited = withEnvironment({ PULLBOARD_MACHINE_HOME: childHome, ...markers }, () => inheritedGateSlot({ root: process.cwd() }));+ assert.equal(inherited, null, 'a token belonging to another resolved machine database is not reused');+ childLease = await withEnvironment({ PULLBOARD_MACHINE_HOME: childHome, ...markers }, () => takeResource({+ name: 'gate', capacity: 1, root: process.cwd(), agent: 'foreign-pool-independent',+ }));+ assert.notEqual(childLease.pool, parentLease.pool);+ assert.equal(resourcesAt(childHome)[0].holders.length, 1, 'the foreign marker did not suppress local acquisition');+ } finally {+ childLease?.release();+ parentLease.release();+ }+});++/** Prove a released token cannot be reused even when its pool marker still matches. */+test('a released same-pool token is refused instead of being inherited [Q1,Q2,Q3]', async () => {+ const home = machinePool();+ const lease = await acquireGate(home);+ const markers = gateSlotEnvironment(lease);+ lease.release();+ assert.throws(+ () => withEnvironment({ PULLBOARD_MACHINE_HOME: home, ...markers }, () => inheritedGateSlot({ root: process.cwd() })),+ (error) => error.code === 'GATE_SLOT_LEASE_LOST',+ );+});++/** Prove a Chrome child cannot queue while carrying only the parent's ordinary gate slot. */+test('a browser child refuses a live gate-only lease without joining the queue [Q1,Q2,Q3]', async () => {+ const home = machinePool();+ const lease = await acquireGate(home);+ try {+ const markers = gateSlotEnvironment(lease);+ assert.throws(+ () => withEnvironment({ PULLBOARD_MACHINE_HOME: home, ...markers }, () => inheritedGateSlot({ root: process.cwd(), browser: true })),+ (error) => error.code === 'BROWSER_SLOT_REQUIRED',+ );+ const gate = resourcesAt(home).find((resource) => resource.name === 'gate');+ assert.equal(gate.line.length, 0, 'refusing the missing browser capacity creates no waiter');+ assert.equal(gate.holders.length, 1, 'the parent keeps its original gate lease');+ } finally { lease.release(); }+});++/** Prove the browser marker must match the live holder row, including its positive held value. */+test('a forged browser marker is refused against the live composite lease [Q1,Q2,Q3]', async () => {+ const home = machinePool();+ const lease = await acquireGate(home, true);+ try {+ const markers = gateSlotEnvironment(lease);+ assert.equal(markers[BROWSER_SLOT_HELD_ENV], '1');+ const valid = withEnvironment({ PULLBOARD_MACHINE_HOME: home, ...markers }, () => inheritedGateSlot({ root: process.cwd(), browser: true }));+ assert.equal(valid.browser, true);+ const forged = { ...markers, [BROWSER_SLOT_HELD_ENV]: '' };+ assert.throws(+ () => withEnvironment({ PULLBOARD_MACHINE_HOME: home, ...forged }, () => inheritedGateSlot({ root: process.cwd(), browser: true })),+ (error) => error.code === 'GATE_SLOT_MARKER_INVALID',+ );+ } finally { lease.release(); }+});diff --git a/test/resources.test.js b/test/resources.test.jsindex c7692eba..4a1cd3fa 100644--- a/test/resources.test.js+++ b/test/resources.test.js@@ -16,6 +16,24 @@ 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 POOL_MODULE_WORKER = `+import { takeResource } from ${JSON.stringify(MODULE)};+let announced = false;+const [root, agent, browserText, item, kind] = process.argv.slice(1);+const lease = await takeResource({+ name: 'gate', capacity: 2, scope: 'machine', root, agent,+ browser: browserText === 'true', item, kind, itemCheck: kind === 'review',+ onWait: (state) => {+ if (!announced) { announced = true; console.log(JSON.stringify({ queued: state })); }+ },+});+try {+ console.log(JSON.stringify({ acquired: agent }));+ for await (const line of process.stdin) {+ if (String(line).trim() === 'release') break;+ }+} finally { lease.release(); }+`;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');@@ -157,6 +175,48 @@ function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = boreturn child;}+/** Launch a dedicated gate-pool worker carrying browser and review metadata. */+function poolWorker(box, { agent, browser = false, item = '', kind = '' }) {+ const workerArgs = ['--input-type=module', '-e', POOL_MODULE_WORKER, box.first, agent, String(browser), item, kind];+ const startedAt = performance.now();+ const child = spawn(process.execPath, workerArgs, {+ env: box.env, stdio: ['pipe', 'pipe', 'pipe'],+ });+ child.startedAt = startedAt;+ child.spawnEnv = box.env;+ child.lines = createInterface({ input: child.stdout });+ child.errors = '';+ child.pendingLines = [];+ child.lineWaiters = [];+ child.exitResult = null;+ child.failureReported = false;+ let spawnError = null;+ child.once('error', (error) => { spawnError = error; });+ child.finished = new Promise((resolveExit) => child.once('close', (code, signal) => {+ child.exitResult = { code, signal };+ CHILDREN.delete(child);+ if ((code !== 0 || signal || spawnError) && !child.failureReported) {+ child.failureReported = true;+ child.failure = reportFixtureChildFailure({ command: process.execPath, args: workerArgs, status: code, signal,+ elapsedMs: performance.now() - startedAt, stderr: child.errors, env: box.env,+ detail: spawnError?.message ?? '' });+ }+ for (const waiter of child.lineWaiters.splice(0)) {+ clearTimeout(waiter.timer);+ waiter.reject(new Error(child.failure ?? `pool worker exited ${code}/${signal}: ${child.errors}`));+ }+ resolveExit(child.exitResult);+ }));+ child.stderr.setEncoding('utf8').on('data', (chunk) => { child.errors += chunk; });+ child.lines.on('line', (line) => {+ const waiter = child.lineWaiters.shift();+ if (waiter) { clearTimeout(waiter.timer); waiter.resolve(line); }+ else child.pendingLines.push(line);+ });+ CHILDREN.add(child);+ return child;+}+/** Read the next worker event, failing promptly with its stderr if it exits unexpectedly. */async function event(child, timeoutMs = 10_000) {if (child.pendingLines.length) return JSON.parse(child.pendingLines.shift());@@ -306,6 +366,59 @@ test('[Q1,Q2] landing waiters jump ordinary gates but keep FIFO within each clasawait release(ordinarySecond);});+test('the pool alone orders submits, reviews and browser runs [C7]', async () => {+ const box = fixture();+ const firstHolder = poolWorker(box, { agent: 'submit-one' });+ const secondHolder = poolWorker(box, { agent: 'submit-two' });+ assert.equal((await acquired(firstHolder)).acquired, 'submit-one');+ assert.equal((await acquired(secondHolder)).acquired, 'submit-two');++ const firstReview = poolWorker(box, { agent: 'review-one', browser: true, item: '618', kind: 'review' });+ const firstQueued = await event(firstReview);+ assert.equal(firstQueued.queued.position, 1, 'a review waits while both submit slots are occupied');+ let browser = privateList(box).find(({ name }) => name === 'browser');+ assert.ok(browser, 'the pool must expose browser capacity and its waiting review');+ assert.equal(browser.capacity, 1, 'the browser pool has its fixed single slot');+ assert.deepEqual(browser.line.map(({ agent, browser: ownsBrowser, itemCheck, item, kind }) =>+ [agent, ownsBrowser, itemCheck, item, kind]), [['review-one', true, true, '618', 'review']]);++ // Releasing one holder is the only signal; the oldest eligible review acquires on its own poll.+ await release(firstHolder);+ assert.equal((await acquired(firstReview)).acquired, 'review-one');+ let gate = privateList(box).find(({ name }) => name === 'gate');+ assert.ok(gate.holders.some(({ agent, browser: ownsBrowser, itemCheck, item, kind }) =>+ agent === 'review-one' && ownsBrowser && itemCheck && item === '618' && kind === 'review'));++ const secondReview = poolWorker(box, { agent: 'review-two', browser: true, item: '619', kind: 'review' });+ const secondQueued = await event(secondReview);+ assert.equal(secondQueued.queued.position, 1, 'the browser waiter reports its actual queue position');+ const thirdSubmit = poolWorker(box, { agent: 'submit-three' });+ const submitQueued = await event(thirdSubmit);+ assert.equal(submitQueued.queued.position, 1,+ 'a browser waiter does not head-of-line block ordinary gate work');+ browser = privateList(box).find(({ name }) => name === 'browser');+ assert.deepEqual(browser.line.map(({ agent, itemCheck, item, kind }) => [agent, itemCheck, item, kind]), [+ ['review-two', true, '619', 'review'],+ ], 'the active browser review is listed as a holder, not as a waiter');+ assert.ok(browser.holders.some(({ agent, browser: ownsBrowser, itemCheck, item, kind }) =>+ agent === 'review-one' && ownsBrowser && itemCheck && item === '618' && kind === 'review'));++ // A free gate slot appears while the browser slot remains held; the queued submit proceeds.+ await release(secondHolder);+ assert.equal((await acquired(thirdSubmit)).acquired, 'submit-three');+ assert.ok(privateList(box).find(({ name }) => name === 'browser').line+ .some(({ agent }) => agent === 'review-two'), 'the second review stays queued while the browser slot is occupied');++ // Releasing both older leases lets the oldest eligible browser waiter proceed without a message.+ await release(thirdSubmit);+ await release(firstReview);+ assert.equal((await acquired(secondReview)).acquired, 'review-two');+ gate = privateList(box).find(({ name }) => name === 'gate');+ assert.ok(gate.holders.some(({ agent, browser: ownsBrowser, itemCheck, item, kind }) =>+ agent === 'review-two' && ownsBrowser && itemCheck && item === '619' && kind === 'review'));+ await release(secondReview);+});+test('[Q1,Q2] a waiting landing keeps a current holder from taking the second slot [Q1,Q2]', async () => {const box = fixture();const firstHolder = worker(box, { capacity: 2, agent: 'same-run' });diff --git a/test/test-resources.test.js b/test/test-resources.test.jsnew file mode 100644index 00000000..1b915a89--- /dev/null+++ b/test/test-resources.test.js@@ -0,0 +1,51 @@+/** 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 { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { test } from 'node:test';+import { testsNeedBrowser } from '../src/test-resources.js';++/** Create source files for a dependency graph whose modules must never execute during admission. */+function sourceFixture(t, files) {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-browser-admission-'));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ for (const [path, source] of Object.entries(files)) {+ mkdirSync(dirname(join(root, path)), { recursive: true });+ writeFileSync(join(root, path), source);+ }+ return root;+}++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';",+ 'helper.js': "import { writeFileSync } from 'node:fs'; writeFileSync(new URL('./executed', import.meta.url), 'bad');",+ });+ assert.equal(await testsNeedBrowser(root, ['./test/plain.test.js']), false);+ assert.equal(await testsNeedBrowser(root, [join(root, 'test/plain.test.js')]), false);+ assert.equal(existsSync(join(root, 'executed')), false);+});++test('a focused test acquires browser admission through its helper and current source edits [C7]', async t => {+ const root = sourceFixture(t, {+ 'test/plain.test.js': "import '../helper.js';",+ 'helper.js': "import assert from 'node:assert/strict';",+ 'test/chrome-fixture.js': "throw new Error('admission must never launch or evaluate Chrome');",+ });+ assert.equal(await testsNeedBrowser(root, ['test/plain.test.js']), false);+ writeFileSync(join(root, 'helper.js'), "import './test/chrome-fixture.js';");+ assert.equal(await testsNeedBrowser(root, ['test/plain.test.js']), true,+ 'admission reads the edited dependency, rather than a cached or committed graph');+});++test('full, cockpit and uncertain test selections reserve browser capacity [C7]', async t => {+ const root = sourceFixture(t, {+ 'test/computed.test.js': "const module = './helper.js'; await import(module);",+ 'test/broken.test.js': 'this is not valid javascript @',+ });+ for (const files of [undefined, [], ['test/cockpit/items.test.js'], ['test/missing.test.js'],+ ['test/computed.test.js'], ['test/broken.test.js'], [join(root, '../outside.test.js')]]) {+ assert.equal(await testsNeedBrowser(root, files), true);+ }+});