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(gate): core-24's short-slot handoff as found [C7]
Corey Olson094a3b0431b2
diff --git a/bin/run-tests.js b/bin/run-tests.jsindex a2cd2931..93e4be33 100644--- a/bin/run-tests.js+++ b/bin/run-tests.js@@ -2,7 +2,7 @@/*** Run the test suite with a private home, no inherited Git identity or config, and a refusing CLI shim.*/-import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, lstatSync, realpathSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';import { basename, delimiter, dirname, join, relative, resolve, sep } from 'node:path';import { fileURLToPath } from 'node:url';import { execFile, execFileSync, spawnSync } from 'node:child_process';@@ -1147,16 +1147,21 @@ async function runLandingTests(args, env, concurrency) {}let nodeOptionsWithValues;+let knownNodeOptions;/** Read Node option arity from this runtime so supported option values cannot bypass the machine pool. */function optionTakesValue(argument) {if (!nodeOptionsWithValues) {nodeOptionsWithValues = new Set();+ knownNodeOptions = new Set();const help = execFileSync(process.execPath, ['--help'], { encoding: 'utf8' });for (const line of help.split(/\r?\n/u)) {const signature = line.match(/^ (-\S.*?)(?: {2,}|$)/u)?.[1];- if (!signature || !signature.includes('=') || signature.includes('[=')) continue;- for (const option of signature.matchAll(/--?[A-Za-z][A-Za-z0-9-]*/gu)) nodeOptionsWithValues.add(option[0]);+ if (!signature) continue;+ for (const option of signature.matchAll(/--?[A-Za-z][A-Za-z0-9-]*/gu)) {+ knownNodeOptions.add(option[0]);+ if (signature.includes('=') && !signature.includes('[=')) nodeOptionsWithValues.add(option[0]);+ }}}@@ -1196,6 +1201,30 @@ function explicitTestFiles(args) {return files;}+/** Admit only explicit regular in-root files; directories and uncertain options remain ordinary. */+function namesOnlyTestFiles(args) {+ let takesValue = false;+ for (const argument of args) {+ if (takesValue) { takesValue = false; continue; }+ if (argument === '--') break;+ if (!argument.startsWith('-')) continue;+ const option = argument.split('=', 1)[0].replaceAll('_', '-');+ const requiresValue = optionTakesValue(option);+ if (!knownNodeOptions.has(option)) return false;+ if (!argument.includes('=')) takesValue = requiresValue;+ }+ if (takesValue || process.env.NODE_OPTIONS) return false;+ const files = explicitTestFiles(args);+ if (!files.length) return false;+ try {+ const root = realpathSync(process.cwd());+ return files.every(file => {+ const path = resolve(root, file);+ return lstatSync(path).isFile() && realpathSync(path).startsWith(root + sep);+ });+ } catch { return false; }+}+/** Select repository test entry files while keeping imported helpers out of direct discovery. */function isDefaultTestFile(path) {const normalized = path.replaceAll('\\', '/');@@ -1308,6 +1337,7 @@ async function main(args) {}args = sharding.args;const fullSuite = !hasTestFiles(args);+ const shortEligible = namesOnlyTestFiles(args);let browser = fullSuite;if (!browser) {const { testsNeedBrowser } = await import('../src/browser-admission.js');@@ -1349,7 +1379,7 @@ async function main(args) {}}if (scopedMarker) {- const inherited = inheritedGateSlot({ root: process.cwd(), browser });+ const inherited = inheritedGateSlot({ root: process.cwd(), browser, fullSuite: !shortEligible });if (inherited) await run(gateSlotEnvironment(inherited));else await acquire();} else if (legacyHeld) {@@ -1377,7 +1407,7 @@ async function main(args) {process.stdout.write(result.output);process.exitCode = result.exitCode;}, {- browser, kind: fullSuite ? 'gate' : 'focused',+ browser, kind: fullSuite ? 'gate' : 'focused', shortEligible,remote: Boolean(canShipRunner),onWait: ({ holders, runnerUnavailable }) => {if (runnerUnavailable) {diff --git a/docs/api.md b/docs/api.mdindex 75ddc138..1cae332b 100644--- a/docs/api.md+++ b/docs/api.md@@ -8,7 +8,9 @@ Decision shouts without a recipient go to the agent's coordinator, or to `personA successful command returns the fields listed below. `version` is always the number `1`. The catalog lists required top-level fields; nested objects and arrays are command data, and optional top-level fields may be added.-`pullboard settings` reads machine-wide settings from the OS account's `~/.pullboard/settings.json`; the gate queue database is beside it. This location does not follow `HOME` or `PULLBOARD_HOME`, so agents with private board homes still share one machine gate limit. Set `PULLBOARD_MACHINE_HOME` to an explicit directory only when a separate private machine settings and gate pool is intended; tests use this override. `pullboard settings gateSlots <n>` changes the gate queue capacity, which defaults to `2`. Capacity changes are refused while a gate is running or waiting, so existing holders and FIFO order remain intact.+Resource pool output includes the configured `gate.shortSlots`; holder entries identify an assigned `slot` (`gate` or `short`), and queued entries may report `requestedSlot: "short-eligible"`. These fields describe queue allocation and do not change the `gateSlots` value.++`pullboard settings` reads machine-wide settings from the OS account's `~/.pullboard/settings.json`; the gate queue database is beside it. This location does not follow `HOME` or `PULLBOARD_HOME`, so agents with private board homes still share one machine gate limit. Set `PULLBOARD_MACHINE_HOME` to an explicit directory only when a separate private machine settings and gate pool is intended; tests use this override. `pullboard settings gateSlots <n>` changes the ordinary gate queue capacity, which defaults to `2`. `pullboard settings gate.shortSlots <n>` sets the optional named-check pool (default `0`, off). Short capacity does not increase `gateSlots`, and whole suites never use it. Capacity changes are refused while the shared gate queue is active, so existing holders and FIFO order remain intact.Browser-free check admission is opt-in per machine with `"gate": { "browserFreeChecks": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the reviewed test classifier can let checks use a CPU-only gate slot. An absent or false setting keeps every check browser-gated, and uncertain or unsupported test commands remain browser-gated even when enabled. The same setting controls the wider frozen-check classification introduced in 0.8.26.diff --git a/src/browser-admission.js b/src/browser-admission.jsindex 03d15ee9..acdd30a4 100644--- a/src/browser-admission.js+++ b/src/browser-admission.js@@ -224,24 +224,73 @@ function browserFallback(onFallback, file, reason) {return true;}-/** 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, onFallback } = {}) {- if (env.NODE_OPTIONS) return browserFallback(onFallback, '<frozen check>', 'NODE_OPTIONS may load an unclassified module');+/** Parse the same literal frozen-runner grammar used by browser admission, returning a reason on uncertainty. */+async function explicitCheckSelection(root, command, { env = process.env } = {}) {+ if (env.NODE_OPTIONS) return { file: '<frozen check>', reason: 'NODE_OPTIONS may load an unclassified module' };let words = literalShellWords(command);if (!words) {const inner = capturedRunner(command);- if (!inner) return browserFallback(onFallback, '<frozen check>', 'shell syntax is outside the supported literal capture form');+ if (!inner) return { file: '<frozen check>', reason: 'shell syntax is outside the supported literal capture form' };const grep = resolveExecutable('grep', env.PATH);- if (!grep || !['/usr/bin/grep', '/bin/grep'].includes(await realpath(grep).catch(() => ''))) return browserFallback(onFallback, '<frozen check>', 'capture wrapper does not resolve the system grep');+ if (!grep || !['/usr/bin/grep', '/bin/grep'].includes(await realpath(grep).catch(() => ''))) {+ return { file: '<frozen check>', reason: 'capture wrapper does not resolve the system grep' };+ }words = literalShellWords(inner);}- if (!words || words.length < 3) return browserFallback(onFallback, '<frozen check>', 'command is not an explicit Node test selection');+ if (!words || words.length < 3) return { file: '<frozen check>', reason: 'command is not an explicit Node test selection' };const node = resolveExecutable(words[0], env.PATH);- if (!node || await realpath(node).catch(() => '') !== await realpath(process.execPath).catch(() => '')) return browserFallback(onFallback, '<frozen check>', 'Node executable does not resolve to this runtime');- const runner = resolve(root, words[1]);- if (runner !== resolve(root, TEST_RUNNER)) return browserFallback(onFallback, '<frozen check>', 'runner is not bin/run-tests.js in this repository');+ if (!node || await realpath(node).catch(() => '') !== await realpath(process.execPath).catch(() => '')) {+ return { file: '<frozen check>', reason: 'Node executable does not resolve to this runtime' };+ }+ if (resolve(root, words[1]) !== resolve(root, TEST_RUNNER)) {+ return { file: '<frozen check>', reason: 'runner is not bin/run-tests.js in this repository' };+ }const files = explicitRunnerFiles(words.slice(2));- if (!files) return browserFallback(onFallback, '<frozen check>', 'runner options or test selection are not statically understood');+ if (!files) return { file: '<frozen check>', reason: 'runner options or test selection are not statically understood' };+ return { files };+}++/** Return exact parser-backed named files only when the runner and selected files are real in-root sources.+ * @param {string} root+ * @param {string} command+ * @param {{commit?:string,env?:NodeJS.ProcessEnv}} [options]+ * @returns {Promise<string[]|null>}+ */+export async function explicitCheckFiles(root, command, { commit, env = process.env } = {}) {+ const selection = await explicitCheckSelection(root, command, { env });+ if (!selection.files) return null;+ if (commit) {+ const committed = committedFiles(root, commit);+ if (!committed) return null;+ const runner = committed.get(TEST_RUNNER);+ if (!runner || runner.type !== 'blob' || !['100644', '100755'].includes(runner.mode)) return null;+ if (selection.files.some(file => {+ const entry = committed.get(file);+ return !entry || entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode);+ })) return null;+ return selection.files;+ }+ const runnerPath = resolve(root, TEST_RUNNER);+ if (await realpath(runnerPath).catch(() => '') !== await realpath(resolve(root, TEST_RUNNER)).catch(() => '')) return null;+ const runnerInfo = await lstat(runnerPath).catch(() => null);+ let runnerInside = false;+ try { runnerInside = await staysInside(root, runnerPath); } catch { /* unresolved paths remain ordinary */ }+ if (!runnerInfo?.isFile() || runnerInfo.isSymbolicLink() || !runnerInside) return null;+ for (const file of selection.files) {+ const absolute = resolve(root, file);+ const info = await lstat(absolute).catch(() => null);+ let inside = false;+ try { inside = await staysInside(root, absolute); } catch { /* unresolved paths remain ordinary */ }+ if (!info?.isFile() || info.isSymbolicLink() || !inside) return null;+ }+ return selection.files;+}++/** 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, onFallback } = {}) {+ const selection = await explicitCheckSelection(root, command, { env });+ if (!selection.files) return browserFallback(onFallback, selection.file, selection.reason);+ const { files } = selection;if (files.some(file => file === JOURNEYS_TEST || file === 'test/cockpit' || file.startsWith('test/cockpit/'))) return true;if (commit) {const committed = committedFiles(root, commit);@@ -249,6 +298,7 @@ export async function checkNeedsBrowser(root, command, { commit, env = process.eif (!runnerEntry || runnerEntry.type !== 'blob' || !['100644', '100755'].includes(runnerEntry.mode)) return browserFallback(onFallback, TEST_RUNNER, 'committed runner is missing or is not a regular file');return testsNeedBrowserInTree(root, files, committed, onFallback);}+ const runner = resolve(root, TEST_RUNNER);if (await realpath(runner).catch(() => '') !== await realpath(resolve(root, TEST_RUNNER)).catch(() => '')) return browserFallback(onFallback, TEST_RUNNER, 'runner resolves outside the expected repository path');const runnerInfo = await lstat(runner).catch(() => null);let runnerInside = false;diff --git a/src/cli.js b/src/cli.jsindex cbebab1c..b951e558 100644--- a/src/cli.js+++ b/src/cli.js@@ -19,7 +19,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, refuseSandboxBlocked, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';-import { checkNeedsBrowser } from './browser-admission.js';+import { checkNeedsBrowser, explicitCheckFiles } 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,@@ -85,7 +85,7 @@ import { flowLines, flowAlertLine } from './stats-flow.js';import { releaseHeadlinesBetween } from './changelog.js';import { exportBoard, importBoard } from './exchange.js';import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';-import { addRunner, browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, setBrowserSlots, setGateSlots } from './settings.js';+import { addRunner, browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, setBrowserSlots, setGateShortSlots, setGateSlots } from './settings.js';import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';import { autoLinkProject, relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';import { readRelayMachine } from './relay-machine.js';@@ -1925,16 +1925,19 @@ function readCommands(io, { first, second, rest, values }) {resources: () => {const ctx = context(io);const agents = withBoard(ctx, (board) => store.listAgents(board));- const browserSlots = loadMachineSettings().browserSlots;+ const machineSettings = loadMachineSettings();+ const browserSlots = machineSettings.browserSlots;+ const shortSlots = machineSettings.gate.shortSlots;const resources = [...listResources({ scope: 'machine' }).map((resource) => ({ ...resource, scope: 'machine' })),...listResources({ scope: 'repo', root: ctx.info.root }).map((resource) => ({ ...resource, scope: 'repo' })),];const runners = runnerResourceStatus(loadMachineSettings().runners ?? []);const queue = gateQueueSettings();- io.result?.({ resources, runners, browserSlots, queue });+ io.result?.({ resources, runners, browserSlots, queue, gate: { shortSlots } });io.say(`browserSlots (machine setting): ${browserSlots}`);io.say(`machine queue order (gate.queue.reviewsFirst ${queue.reviewsFirst}): ${queue.reviewsFirst ? `landing, review, submit, other; a waiting run moves up one class every ${queue.agingMinutes} minutes` : 'landings first, then arrival'}`);+ io.say(`gate.shortSlots (machine setting): ${shortSlots}`);if (!resources.length) io.say('no resources have been used');for (const resource of resources) {io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})${resource.order === 'arrival' ? '; an older pullboard is waiting, so this line is in arrival order, landings first' : ''}`);@@ -2468,8 +2471,10 @@ 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);- const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(root, frozenCheck(item), { commit, onFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });- 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) });+ const frozenCommand = frozenCheck(item);+ const shortEligible = Boolean(await explicitCheckFiles(root, frozenCommand, { commit }));+ const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(root, frozenCommand, { commit, onFallback: browserAdmissionReporter(ctx.io, ctx.io.relayJson) });+ check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs, gateLease: lease }), { browser, agent: me.id, item: String(id), kind: 'review', itemCheck: true, shortEligible, onWait: gateWaitReporter(ctx.io) });refuseSandboxBlocked(check);verificationProfile = check.profile ?? null;const evidence = check.checked@@ -2950,8 +2955,9 @@ 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 shortEligible = Boolean(await explicitCheckFiles(ctx.info.root, check));const browser = !browserFreeChecksEnabled() || await checkNeedsBrowser(ctx.info.root, check, { onFallback: browserAdmissionReporter(io, values.json) });- 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) });+ 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, shortEligible, onWait: gateWaitReporter(io) });refuseSandboxBlocked(run);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);@@ -3133,7 +3139,7 @@ function workCommands(io, args) {/** Label the kind and item of a queued run without hiding older queue-class labels. */function resourceRunLabel(entry) {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);+ const details = [entry.slot === 'short' ? 'short slot' : '', entry.requestedSlot === 'short-eligible' ? 'short eligible' : '', entry.kind !== priority ? entry.kind : '', entry.item ? `#${entry.item}` : '', entry.browser ? 'browser' : ''].filter(Boolean);return `${priority ? ` (${priority})` : ''}${details.length ? ` (${details.join(', ')})` : ''}`;}@@ -3181,18 +3187,22 @@ function settingsCommand(io, { first, second, rest }) {io.say(`browserSlots: ${settings.browserSlots}`);io.say(`gate.queue.reviewsFirst: ${queue.reviewsFirst}${queue.reviewsFirst ? '' : ' (landings first, then arrival order)'}`);io.say(`gate.queue.agingMinutes: ${queue.agingMinutes}${queue.reviewsFirst ? '' : ' (used only while reviewsFirst is true)'}`);+ io.say(`gate.shortSlots: ${settings.gate.shortSlots}`);return 0;}- if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {- throw new Refused('USAGE', 'pullboard settings gateSlots <n> | browserSlots <n>');+ if (!['gateSlots', 'browserSlots', 'gate.shortSlots'].includes(first) || !second || rest.length) {+ throw new Refused('USAGE', 'pullboard settings gateSlots <n> | browserSlots <n> | gate.shortSlots <n>');}- if (!/^[1-9]\d*$/u.test(second) || !Number.isSafeInteger(Number(second))) {+ const pattern = first === 'gate.shortSlots' ? /^(?:0|[1-9]\d*)$/u : /^[1-9]\d*$/u;+ if (!pattern.test(second) || !Number.isSafeInteger(Number(second))) {+ if (first === 'gate.shortSlots') throw new Refused('BAD_SHORT_SLOTS', 'gate.shortSlots must be a nonnegative integer');if (first === 'gateSlots') throw new Refused('USAGE', 'pullboard settings gateSlots <positive integer>');- throw new Refused(first === 'browserSlots' ? 'BAD_BROWSER_SLOTS' : 'BAD_GATE_SLOTS', `${first} must be a positive integer; run pullboard settings ${first} <n>`);+ throw new Refused('BAD_BROWSER_SLOTS', `browserSlots must be a positive integer; run pullboard settings browserSlots <n>`);}- const settings = first === 'browserSlots' ? setBrowserSlots(Number(second)) : setGateSlots(Number(second));+ const settings = first === 'browserSlots' ? setBrowserSlots(Number(second))+ : first === 'gate.shortSlots' ? setGateShortSlots(Number(second)) : setGateSlots(Number(second));io.result?.({ settings });- io.say(`${first} set to ${settings[first]}`);+ io.say(`${first} set to ${first === 'gate.shortSlots' ? settings.gate.shortSlots : settings[first]}`);return 0;}diff --git a/src/gate.js b/src/gate.jsindex 6b0a99e3..afe76efd 100644--- a/src/gate.js+++ b/src/gate.js@@ -16,7 +16,7 @@ import { Refused } from './refused.js';import { GATE_SLOT_HELD_ENV, gateSlotEnvironment, inheritedGateSlot, takeResource } from './resources.js';import { browserFreeChecksEnabled, loadMachineSettings } from './settings.js';import { selectAffectedTests } from './affected-tests.js';-import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';+import { checkNeedsBrowser, explicitCheckFiles, testsNeedBrowser } from './browser-admission.js';import { timingFromOutput, timingRunner } from './timing.js';import { landingShardProfile } from './landing-shards.js';import { RunnerDropped, runOnRunner, runOnRunnerAsync, runnerSource } from './runners.js';@@ -498,23 +498,27 @@ function hasPipeline(command) {/** Run work under the machine queue: landings first, then every other eligible waiter in arrival order.** @param {string} root - Checkout used to locate the machine resource database.- * @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.+ * @param {(lease: { waitMs: number, token?: string, pool?: string, browser?: boolean, slotClass?: 'gate'|'short', release: () => void }) => any | Promise<any>} action - Work to perform while holding a slot.+ * @param {{ landing?: boolean, itemCheck?: boolean, shortEligible?: 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, browser = false, remote = true, agent, item = '', kind = '', onWait } = {}) {- const inherited = inheritedGateSlot({ root, browser });+export async function withGateSlot(root, action, { landing = false, itemCheck = false, shortEligible = false, diagnostic = false, browser = false, remote = true, agent, item = '', kind = '', onWait } = {}) {+ if (shortEligible && (landing || diagnostic)) throw new Refused('BAD_SHORT_SLOT_REQUEST', 'short gate slots are only available to named non-landing, non-diagnostic runs');+ const inherited = inheritedGateSlot({ root, browser, fullSuite: !shortEligible });if (inherited) {try { return await action(inherited); }finally { inherited.release(); }}const settingsProvider = () => loadMachineSettings();const capacityProvider = () => settingsProvider().gateSlots;+ const shortCapacityProvider = () => settingsProvider().gate.shortSlots;const source = runnerSource(root);let lease = await takeResource({name: 'gate',capacity: capacityProvider(),capacityProvider,+ shortCapacityProvider,+ shortEligible,browserCapacityProvider: () => settingsProvider().browserSlots,scope: 'machine',root,@@ -534,7 +538,7 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =try {while (true) {lease.source = source;- lease.runMetadata = { landing, itemCheck, diagnostic, item: String(item), kind };+ lease.runMetadata = { landing, itemCheck, shortEligible, diagnostic, item: String(item), kind };try { return await action(lease); }catch (error) {if (!(error instanceof RunnerDropped) || !lease.runner || !lease.requeueRunner) throw error;@@ -621,6 +625,21 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,? (proofFiles.length > 0 && (!allowBrowserFreeChecks || await testsNeedBrowser(root, proofFiles, { onFallback: onBrowserFallback }))): (selection.full || !allowBrowserFreeChecks || await testsNeedBrowser(root, proofFiles, { onFallback: onBrowserFallback }));const browser = checkUsesBrowser || proofUsesBrowser;+ // Only an explicit runner command over exactly the selected files can use short capacity.+ // Opaque configured runners, opaque item checks, and full selections stay ordinary.+ const proofCommand = proofFiles.length && config.affectedTests?.trim()+ ? `${config.affectedTests.trimEnd()} ${proofFiles.map(path => commandWord('./' + path)).join(' ')}`+ : '';+ // The parser accepts canonical repository-relative test paths; the executed command keeps its existing ./ spelling.+ const proofSelectionCommand = proofFiles.length && config.affectedTests?.trim()+ ? `${config.affectedTests.trimEnd()} ${proofFiles.map(commandWord).join(' ')}`+ : '';+ const parsedProofFiles = proofSelectionCommand ? await explicitCheckFiles(root, proofSelectionCommand) : null;+ const exactNamedProof = parsedProofFiles !== null+ && JSON.stringify(parsedProofFiles) === JSON.stringify(proofFiles);+ const namedCheck = check ? await explicitCheckFiles(root, check) : [];+ const shortEligible = namedCheck !== null && (!proofFiles.length || exactNamedProof)+ && (Boolean(check) || proofFiles.length > 0) && (deferFullFallback || !selection.full);return await withGateSlot(root, (lease) => {const startedAt = Date.now();const log = gitPath(root, 'pullboard-submit.log');@@ -659,14 +678,13 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,if (!deferFullFallback && selection.full) proof = fullGateRun(root, config, false, { waitMs: proofWait, log: proofLog, gateLease: lease });else if (!proofFiles.length) proof = { isGreen: true, output: '', seconds: 0, isCached: false, log: '' };else {- const command = `${config.affectedTests.trimEnd()} ${proofFiles.map(path => commandWord('./' + path)).join(' ')}`;- proof = { ...runProfiledShell(root, command, { waitMs: proofWait, profileFile: `${proofLog}.profile.json`, gateLease: lease }), isCached: false, log: proofLog };+ proof = { ...runProfiledShell(root, proofCommand, { waitMs: proofWait, profileFile: `${proofLog}.profile.json`, gateLease: lease }), isCached: false, log: proofLog };writeFileSync(proofLog, proof.output);}const phase = deferFullFallback ? `submit invariants: ${invariants.length ? invariants.join(', ') : 'none'}; full suite deferred to the landing gate` : selection.full ? 'full gate' : 'affected tests';writeFileSync(log, `item check:\n${criterion.output}\n${phase}:\n${proof.output}`);return finish(proof);- }, { browser, agent, item, kind, itemCheck: true, onWait });+ }, { browser, agent, item, kind, itemCheck: true, shortEligible, onWait });}/** Describe precisely which submission proof ran, including absent checks and full fallbacks. */diff --git a/src/next-steps.js b/src/next-steps.jsindex d8afe8fe..bde998fc 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -42,6 +42,8 @@ export const NEXT_STEPS = Object.freeze({BAD_LANE: 'choose a lane name made of lowercase letters, digits and dashes, then retry pullboard lane add',BAD_LANE_PATH: 'give pullboard lane add a folder path inside the repository, relative to its root',BAD_GATE_SLOTS: 'choose a positive gateSlots value no lower than browserSlots shown by pullboard settings: pullboard settings gateSlots <n>',+ BAD_SHORT_SLOTS: 'set a nonnegative gate.shortSlots value: pullboard settings gate.shortSlots <n>',+ BAD_SHORT_SLOT_REQUEST: 'use a parser-confirmed named non-landing machine gate request; opaque and other requests use ordinary gate slots',BAD_BROWSER_SLOTS: 'choose browserSlots from 1 through gateSlots shown by pullboard settings: pullboard settings browserSlots <n>',BAD_MACHINE_SETTINGS: 'fix or remove the machine settings file the message names, then run pullboard settings',MACHINE_HOME_NOT_WRITABLE: 'give the agent write access to the named machine-home directory, or run the command outside the sandbox',@@ -124,6 +126,7 @@ export const NEXT_STEPS = Object.freeze({GATE_SLOT_LEASE_REQUIRED: 'start the child test process with the live gate lease',GATE_SLOT_MARKER_INVALID: 'restart the child with gateSlotEnvironment(lease)',GATE_SLOT_TOKEN_REQUIRED: 'restart the child with gateSlotEnvironment(lease)',+ SHORT_SLOT_FULL_SUITE: 'start the full suite through the ordinary gate queue; short slots are only for named files',GIT_GRAFTS: 'ask the coordinator to remove the git graft file: pullboard shout coordinator "please remove .git/info/grafts"',HEAD_NOT_NEW: 'commit the rework, then pullboard submit <id>',HELD: 'take another item: pullboard next',diff --git a/src/resources.js b/src/resources.jsindex dc6c48d0..d12960b7 100644--- a/src/resources.js+++ b/src/resources.js@@ -20,6 +20,7 @@ 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';+export const GATE_SLOT_CLASS_ENV = 'PULLBOARD_GATE_SLOT_CLASS';/** Reserve a distinct resource row for each configured remote host. */function runnerResourceName(host) { return `runner:${host}`; }@@ -27,13 +28,15 @@ function runnerResourceName(host) { return `runner:${host}`; }/** Build child markers that identify the exact machine queue lease and its browser capacity. */export function gateSlotEnvironment(lease) {if (lease?.runner) throw new Refused('REMOTE_GATE_SLOT_NOT_INHERITABLE', 'remote runner leases cannot be inherited through local gate markers');- if (!lease || lease.name !== 'gate' || lease.scope !== 'machine' || typeof lease.pool !== 'string' || typeof lease.token !== 'string') {+ if (!lease || lease.name !== 'gate' || lease.scope !== 'machine' || typeof lease.pool !== 'string' || typeof lease.token !== 'string'+ || !['gate', 'short'].includes(lease.slotClass)) {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,+ [GATE_SLOT_CLASS_ENV]: lease.slotClass,[BROWSER_SLOT_HELD_ENV]: lease.browser ? '1' : '',};}@@ -83,9 +86,9 @@ function openQueue(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, browser INTEGER NOT NULL DEFAULT 0, item TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT '', runner TEXT NOT NULL DEFAULT '');+ 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 '', runner TEXT NOT NULL DEFAULT '', short_slot INTEGER NOT NULL DEFAULT 0);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, browser INTEGER NOT NULL DEFAULT 0, item TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT '', remote 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 '', remote INTEGER NOT NULL DEFAULT 0, short_eligible INTEGER NOT NULL DEFAULT 0);CREATE TABLE IF NOT EXISTS runner_unavailable (host TEXT PRIMARY KEY, since TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '');CREATE INDEX IF NOT EXISTS waiter_name_ticket ON waiter(name, ticket);`);for (const table of ['holder', 'waiter']) {@@ -98,7 +101,9 @@ function openQueue(file) {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 ''`);if (table === 'holder' && !columns.includes('runner')) db.exec("ALTER TABLE holder ADD COLUMN runner TEXT NOT NULL DEFAULT ''");+ if (table === 'holder' && !columns.includes('short_slot')) db.exec('ALTER TABLE holder ADD COLUMN short_slot INTEGER NOT NULL DEFAULT 0');if (table === 'waiter' && !columns.includes('remote')) db.exec('ALTER TABLE waiter ADD COLUMN remote INTEGER NOT NULL DEFAULT 0');+ if (table === 'waiter' && !columns.includes('short_eligible')) db.exec('ALTER TABLE waiter ADD COLUMN short_eligible INTEGER NOT NULL DEFAULT 0');}// Marks a waiter whose process admits by class; an older pullboard leaves it 0.if (!db.prepare('PRAGMA table_info(waiter)').all().some(({ name }) => name === 'classed')) {@@ -283,8 +288,11 @@ function admissionRank(waiters, now, order) {/** Current holders and the waiting line in admission order, each waiter naming its class (aged only while class order is on). */function snapshot(db, name, order = ARRIVAL_ORDER, now = Date.now()) {/** Preserve older public entries while naming diagnostics as a distinct queue class. */- const project = ({ diagnostic, browser, remote, runner, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,+ const project = ({ diagnostic, browser, remote, runner, item, kind, shortSlot, shortEligible, ...entry }) => ({ ...entry, landing: entry.landing === 1,itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),+ ...(['gate', 'browser'].includes(name) && shortSlot === 1 ? { slot: 'short' } : {}),+ ...(['gate', 'browser'].includes(name) && shortSlot === 0 ? { slot: 'gate' } : {}),+ ...(['gate', 'browser'].includes(name) && shortEligible === 1 ? { requestedSlot: 'short-eligible' } : {}),...(browser === 1 ? { browser: true } : {}), ...(remote === 1 ? { remote: true } : {}),...(runner ? { runner } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}) });// Browser is an additional capability on a gate lease, not a second partially held row.@@ -293,11 +301,11 @@ function snapshot(db, name, order = ARRIVAL_ORDER, now = Date.now()) {const runnerHost = name.startsWith('runner:') ? name.slice('runner:'.length) : '';const holderWhere = runnerHost ? 'name = ?' : where;const holderValues = [sourceName];- const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, runner, item, kind FROM holder WHERE ${holderWhere} ORDER BY since, token`).all(...holderValues).map(project);+ const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, runner, item, kind, short_slot AS shortSlot FROM holder WHERE ${holderWhere} ORDER BY since, token`).all(...holderValues).map(project);const queued = db.prepare('SELECT classed FROM waiter WHERE name = ?').all(sourceName);const rank = admissionRank(queued, now, order);const ageMs = order.reviewsFirst ? order.ageMs : Infinity;- const line = db.prepare(`SELECT ticket, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind, classed FROM waiter WHERE ${where}`).all(sourceName)+ const line = db.prepare(`SELECT ticket, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind, classed, short_eligible AS shortEligible FROM waiter WHERE ${where}`).all(sourceName).sort((left, right) => rank(left) - rank(right) || left.ticket - right.ticket).map(({ ticket, classed, ...entry }) => {const current = queueClass(entry, now, ageMs);@@ -308,9 +316,9 @@ function snapshot(db, name, order = ARRIVAL_ORDER, now = Date.now()) {}/** Count reported or admissible queue position separately so blocked work cannot distort the visible line. */-function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now(), order = ARRIVAL_ORDER } = {}) {+function waiterPosition(db, name, ticket, { eligibleOnly = false, shortCapacity = 0, now = Date.now(), order = ARRIVAL_ORDER } = {}) {const queueName = name === 'browser' ? 'gate' : name;- const waiters = db.prepare('SELECT ticket, pid, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, kind, classed FROM waiter WHERE name = ? ORDER BY ticket').all(queueName);+ const waiters = db.prepare('SELECT ticket, pid, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, kind, classed, short_eligible AS shortEligible FROM waiter WHERE name = ? ORDER BY ticket').all(queueName);const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(queueName);const browserCapacity = db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get()?.capacity ?? 1;const browserBusy = db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count >= browserCapacity;@@ -327,6 +335,13 @@ function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now&& (!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;+ // When a configured short slot can admit this waiter past ordinary work, report its+ // position in the compatible short line, while preserving any earlier landing barrier.+ if (name === 'gate' && current.shortEligible === 1 && shortCapacity > 0) {+ const earlierLandings = line.filter((waiter) => waiter.landing === 1 && waiter.ticket < ticket);+ if (earlierLandings.length) return earlierLandings.length + 1;+ return line.filter((waiter) => waiter.shortEligible === 1 && waiter.ticket <= ticket).length;+ }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);@@ -368,12 +383,13 @@ function validatedRunners(value) {* @param {number} [now] - The clock reading to age against.* @returns {{host:string,slots:number,browser:number}|null}*/-function gateAdmission(db, ticket, capacity, runners, order = ARRIVAL_ORDER, now = Date.now()) {- const queued = db.prepare("SELECT ticket, pid, since, landing, item_check AS itemCheck, diagnostic, browser, remote, kind, classed FROM waiter WHERE name = 'gate'").all();+function gateAdmission(db, ticket, capacity, shortCapacity, runners, order = ARRIVAL_ORDER, now = Date.now()) {+ const queued = db.prepare("SELECT ticket, pid, since, landing, item_check AS itemCheck, diagnostic, browser, remote, kind, classed, short_eligible AS shortEligible FROM waiter WHERE name = 'gate'").all();const rank = admissionRank(queued, now, order);const waiters = queued.sort((left, right) => rank(left) - rank(right) || left.ticket - right.ticket);- const holders = db.prepare("SELECT pid, landing, browser FROM holder WHERE name = 'gate'").all();- const localUsed = holders.length;+ const holders = db.prepare("SELECT pid, landing, browser, short_slot AS shortSlot FROM holder WHERE name = 'gate'").all();+ const localUsed = holders.filter(holder => holder.shortSlot !== 1).length;+ const localShortUsed = holders.filter(holder => holder.shortSlot === 1).length;const localBrowsers = holders.filter(holder => holder.browser === 1).length;const browserCapacity = db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get()?.capacity ?? 1;const usage = new Map(runners.map(runner => {@@ -393,16 +409,21 @@ function gateAdmission(db, ticket, capacity, runners, order = ARRIVAL_ORDER, nowfunction available(waiter) {if (blockedByLanding(waiter)) return null;if (localUsed < capacity && (waiter.browser !== 1 || localBrowsers < browserCapacity)) {- return { host: '', slots: capacity, browser: waiter.browser === 1 ? 1 : 0 };+ return { host: '', slots: capacity, browser: waiter.browser === 1 ? 1 : 0, shortSlot: false };}if (waiter.remote === 1) {for (const runner of runners) {if (unavailable.has(runner.host) || (waiter.browser === 1 && runner.browser < 1)) continue;const used = usage.get(runner.host);if (used.slots >= runner.slots || (waiter.browser === 1 && used.browsers >= runner.browser)) continue;- return runner;+ return { ...runner, shortSlot: false };}}+ const earlierLanding = waiters.some(other => other.landing === 1 && other.ticket < waiter.ticket);+ if (waiter.shortEligible === 1 && !earlierLanding && localShortUsed < shortCapacity+ && (waiter.browser !== 1 || localBrowsers < browserCapacity)) {+ return { host: '', slots: shortCapacity, browser: waiter.browser === 1 ? 1 : 0, shortSlot: true };+ }return null;}for (const runner of runners) {@@ -465,8 +486,8 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr/*** Join the queue in its admission class (landing, review, submit, other), aging up over time; FIFO by ticket within a class.*- * @param {{ name: string, capacity: number, capacityProvider?: () => number, browserCapacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, remote?: boolean, runnerProvider?: () => Array<{host:string,slots:number,browser:number}>, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean, _resume?: object }} options - Resource identity, queue class and optional remote executor pool.- * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, runner?: {host:string,slots:number,browser:number}, waitMs: number, release: () => void, renew: () => void, requeueRunner?: () => Promise<object> }>}+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, shortCapacityProvider?: () => number, browserCapacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, shortEligible?: boolean, diagnostic?: boolean, browser?: boolean, remote?: boolean, runnerProvider?: () => Array<{host:string,slots:number,browser:number}>, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean, _resume?: object }} options - Resource identity, queue class and optional remote executor pool.+ * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, slotClass: 'gate'|'short', runner?: {host:string,slots:number,browser:number}, waitMs: number, release: () => void, renew: () => void, requeueRunner?: () => Promise<object> }>}*/export async function takeResource(options) {const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;@@ -475,6 +496,7 @@ export async function takeResource(options) {if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');const landing = options.landing === true;const itemCheck = options.itemCheck === true;+ const shortEligible = options.shortEligible === true;const diagnostic = options.diagnostic === true;const browser = options.browser === true;const remote = options.remote === true;@@ -489,6 +511,7 @@ export async function takeResource(options) {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 (shortEligible && (name !== 'gate' || scope !== 'machine' || landing || diagnostic)) throw new Refused('BAD_SHORT_SLOT_REQUEST', 'short gate slots are only available to named non-landing, non-diagnostic machine gate runs');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 db = open(file, scope === 'machine');@@ -509,7 +532,9 @@ export async function takeResource(options) {let initialTicket = resume?.ticket;update(db, () => {const currentCapacity = options.capacityProvider?.() ?? capacity;+ const currentShortCapacity = options.shortCapacityProvider?.() ?? 0;if (!Number.isSafeInteger(currentCapacity) || currentCapacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');+ if (!Number.isSafeInteger(currentShortCapacity) || currentShortCapacity < 0) throw new Refused('BAD_SHORT_SLOTS', 'gate.shortSlots must be a nonnegative integer');const row = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name);if (row && row.capacity !== currentCapacity) {const state = snapshot(db, name);@@ -538,7 +563,7 @@ export async function takeResource(options) {if (!resume) {// Remote eligibility is metadata on this same ticket; the kind and flags decide the// admission class, and the ticket keeps arrival order within it.- const inserted = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(queueOrder(scope)));+ const inserted = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, short_eligible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(queueOrder(scope)), Number(shortEligible));initialTicket = Number(inserted.lastInsertRowid);}});@@ -552,28 +577,28 @@ export async function takeResource(options) {const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);if (!waiter) {if (resume && initialTicket) {- db.prepare('INSERT OR IGNORE INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(initialTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(order));- return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order }), rejoined: true } };+ db.prepare('INSERT OR IGNORE INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, short_eligible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(initialTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(order), Number(shortEligible));+ return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order, shortCapacity: options.shortCapacityProvider?.() ?? 0 }), rejoined: true } };}queuedAt = new Date().toISOString();- const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(order));+ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, short_eligible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(order), Number(shortEligible));initialTicket = Number(rejoined.lastInsertRowid);- return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order }), rejoined: true } };+ return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order, shortCapacity: options.shortCapacityProvider?.() ?? 0 }), rejoined: true } };}// The marker follows this poll's setting, so a change mid-wait reaches every process's ranking.db.prepare('UPDATE waiter SET heartbeat = ?, classed = ? WHERE token = ?').run(Date.now(), classedMarker(order), token);const spot = snapshot(db, name, order);- const reportPosition = waiterPosition(db, name, waiter.ticket, { order });+ const reportPosition = waiterPosition(db, name, waiter.ticket, { order, shortCapacity: options.shortCapacityProvider?.() ?? 0 });const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;const executor = name === 'gate'- ? gateAdmission(db, waiter.ticket, limit, runners, order)+ ? gateAdmission(db, waiter.ticket, limit, options.shortCapacityProvider?.() ?? 0, runners, order): (waiterPosition(db, name, waiter.ticket, { eligibleOnly: true, order }) === 1 && spot.holders.length < limit ? { host: '' } : null);if (executor) {db.prepare('DELETE FROM waiter WHERE token = ?').run(token);const acquiredAt = new Date().toISOString();const holderName = executor.host ? runnerResourceName(executor.host) : name;- db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, runner) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, holderName, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, executor.host);- return { acquired: true, state: { ...spot, position: 0 }, ticket: waiter.ticket, runner: executor.host ? executor : undefined };+ db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, runner, short_slot) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, holderName, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, executor.host, Number(executor.shortSlot === true));+ return { acquired: true, state: { ...spot, position: 0 }, ticket: waiter.ticket, runner: executor.host ? executor : undefined, shortSlot: executor.shortSlot === true };}return { acquired: false, state: { ...spot, position: reportPosition } };});@@ -641,8 +666,8 @@ export async function takeResource(options) {requeueTicket = Math.min(0, minimumTicket ?? 0) - 1;}db.prepare('DELETE FROM holder WHERE token = ?').run(token);- db.prepare('INSERT INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')- .run(requeueTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), marker);+ db.prepare('INSERT INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, short_eligible) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')+ .run(requeueTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), marker, Number(shortEligible));});} catch (error) {transferred = false;@@ -653,7 +678,7 @@ export async function takeResource(options) {return takeResource({ ...options, _resume: { token, ticket: requeueTicket ?? acquired.ticket,queuedAt, requestedAt, priorWaitMs: acquiredWaitMs, waitStartedAt: Date.now() } });};- return { name, scope, token, pool, browser, ...(acquired.runner ? { runner: acquired.runner } : {}),+ return { name, scope, token, pool, browser, slotClass: acquired.shortSlot ? 'short' : 'gate', ...(acquired.runner ? { runner: acquired.runner } : {}),waitMs: acquiredWaitMs, release, renew,...(acquired.runner ? { requeueRunner } : {}) };}@@ -668,9 +693,10 @@ 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 } = {}) {+export function inheritedGateSlot({ root = process.cwd(), browser = false, fullSuite = true } = {}) {const markedPool = process.env[GATE_SLOT_POOL_ENV] ?? '';const token = process.env[GATE_SLOT_TOKEN_ENV] ?? '';+ const markedClass = process.env[GATE_SLOT_CLASS_ENV] ?? 'gate';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 = canonicalResourceFile(machineResourceFile());@@ -681,14 +707,17 @@ export function inheritedGateSlot({ root = process.cwd(), browser = false } = {}const db = open(pool, true);let holder;try {- holder = update(db, () => db.prepare("SELECT browser FROM holder WHERE name = 'gate' AND token = ?").get(token));+ holder = update(db, () => db.prepare("SELECT browser, short_slot AS shortSlot 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 slotClass = holder.shortSlot === 1 ? 'short' : 'gate';+ if (markedClass !== slotClass) throw new Refused('GATE_SLOT_MARKER_INVALID', 'the inherited slot class does not match its live gate lease; restart the parent runner');+ if (slotClass === 'short' && fullSuite) throw new Refused('SHORT_SLOT_FULL_SUITE', 'a full suite cannot inherit a short gate slot; start it through the ordinary gate queue');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,+ name: 'gate', scope: 'machine', token, pool, browser: holder.browser === 1, slotClass, waitMs: 0,release() {}, renew() {},};}diff --git a/src/settings.js b/src/settings.jsindex b9eead48..afa17214 100644--- a/src/settings.js+++ b/src/settings.js@@ -12,12 +12,13 @@ export { gateQueueSettings, machineSettingsFile };const DEFAULT_GATE_SLOTS = 2;const DEFAULT_BROWSER_SLOTS = 1;+const DEFAULT_SHORT_SLOTS = 0;/** Read and validate machine settings, preserving any unrelated settings. */export function loadMachineSettings() {const file = machineSettingsFile();const value = readMachineSettingsFile(file);- if (!value) return { gateSlots: DEFAULT_GATE_SLOTS, browserSlots: DEFAULT_BROWSER_SLOTS };+ if (!value) return { gateSlots: DEFAULT_GATE_SLOTS, browserSlots: DEFAULT_BROWSER_SLOTS, gate: { shortSlots: DEFAULT_SHORT_SLOTS } };if (value.gate?.browserFreeChecks !== undefined && typeof value.gate.browserFreeChecks !== 'boolean') {throw new Refused('BAD_MACHINE_SETTINGS', `gate.browserFreeChecks in ${file} must be true or false`);}@@ -26,6 +27,10 @@ export function loadMachineSettings() {if (!Number.isSafeInteger(gateSlots) || gateSlots < 1) {throw new Refused('BAD_GATE_SLOTS', `gateSlots in ${file} must be a positive integer; run pullboard settings gateSlots <n>`);}+ const shortSlots = value.gate?.shortSlots ?? DEFAULT_SHORT_SLOTS;+ if (!Number.isSafeInteger(shortSlots) || shortSlots < 0) {+ throw new Refused('BAD_SHORT_SLOTS', `gate.shortSlots in ${file} must be a nonnegative integer; run pullboard settings gate.shortSlots <n>`);+ }const browserSlots = value.browserSlots ?? DEFAULT_BROWSER_SLOTS;if (!Number.isSafeInteger(browserSlots) || browserSlots < 1 || browserSlots > gateSlots) {throw new Refused('BAD_BROWSER_SLOTS', `browserSlots in ${file} must be a positive integer no greater than gateSlots (${gateSlots}); run pullboard settings browserSlots <n>`);@@ -38,7 +43,7 @@ export function loadMachineSettings() {if (seen.has(runner.host)) throw new Refused('BAD_MACHINE_SETTINGS', 'runner hosts must be unique; remove the duplicate machine setting');seen.add(runner.host);}- return { ...value, gateSlots, browserSlots, ...(runners.length ? { runners } : {}) };+ return { ...value, gateSlots, browserSlots, gate: { ...value.gate, shortSlots }, ...(runners.length ? { runners } : {}) };}/** Browser-free check admission is deliberately opt-in per machine. */@@ -70,6 +75,19 @@ export function setGateSlots(capacity) {return next;}+/** Set short admission capacity only while the shared gate queue is idle. */+export function setGateShortSlots(capacity) {+ if (!Number.isSafeInteger(capacity) || capacity < 0) throw new Refused('BAD_SHORT_SLOTS', 'gate.shortSlots must be a nonnegative integer; run pullboard settings gate.shortSlots <n>');+ let next;+ const current = loadMachineSettings();+ setResourceCapacity({ name: 'gate', capacity: current.gateSlots, scope: 'machine', persist: () => {+ const latest = loadMachineSettings();+ next = { ...latest, gate: { ...latest.gate, shortSlots: capacity } };+ writeMachineSettings(next);+ } });+ return next;+}+/** Set machine browser capacity only when its browser holders and waiters are empty. */export function setBrowserSlots(capacity) {if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_BROWSER_SLOTS', 'browserSlots must be a positive integer; run pullboard settings browserSlots <n>');diff --git a/test/gate-resource.test.js b/test/gate-resource.test.jsindex 1f701ce6..9bd40154 100644--- a/test/gate-resource.test.js+++ b/test/gate-resource.test.js@@ -6,11 +6,13 @@ import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { after, test } from 'node:test';import { pathToFileURL } from 'node:url';-import { GATE_SLOT_HELD_ENV } from '../src/resources.js';+import { BROWSER_SLOT_HELD_ENV, GATE_SLOT_CLASS_ENV, GATE_SLOT_HELD_ENV, GATE_SLOT_POOL_ENV, GATE_SLOT_TOKEN_ENV } from '../src/resources.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const RUNNER = resolve(import.meta.dirname, '../bin/run-tests.js');const GATE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/gate.js')).href;+const RESOURCE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/resources.js')).href;+const BROWSER_ADMISSION_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/browser-admission.js')).href;const PROBE_NAME = 'machine gate slot runner probe [Q4]';const PROBE_PATTERN = '^machine gate slot runner probe \\[Q4\\]$';const PROBE_PATH_ENV = 'PULLBOARD_GATE_RESOURCE_PROBE_PATH';@@ -72,12 +74,89 @@ function launchTestRunner(box, root, args, marker, release, extraEnv = {}) {return child;}-/** Launch a real process that holds the production diagnostic resource class until released. */+/** Launch a synthetic ordinary or short gate lease holder until released. */+function launchLeaseFixture(box, root, name, started, release, waiting, shortEligible = false) {+ const script = join(box.dir, `${name}.mjs`);+ writeFileSync(script, `import { existsSync, renameSync, writeFileSync } from 'node:fs';+import { withGateSlot } from ${JSON.stringify(GATE_MODULE)};+/** Publish a complete fixture marker atomically. */+function publish(file, value) { writeFileSync(file + '.tmp', value); renameSync(file + '.tmp', file); }+await withGateSlot(process.cwd(), async lease => {+ publish(${JSON.stringify(started)}, lease.slotClass);+ while (!existsSync(${JSON.stringify(release)})) await new Promise(done => setTimeout(done, 10));+}, { shortEligible: ${JSON.stringify(shortEligible)}, kind: 'fixture-lease', agent: ${JSON.stringify(name)}, onWait: state => publish(${JSON.stringify(waiting)}, String(state.position)) });+`);+ const child = spawn(process.execPath, [script], { cwd: root, env: box.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ child.stdoutText = '';+ child.stderrText = '';+ child.stdout.setEncoding('utf8');+ child.stderr.setEncoding('utf8');+ child.stdout.on('data', chunk => { child.stdoutText += chunk; });+ child.stderr.on('data', chunk => { child.stderrText += chunk; });+ CHILDREN.add(child);+ child.closed = new Promise(resolveClose => child.once('close', (code, signal) => {+ CHILDREN.delete(child);+ resolveClose({ code, signal });+ }));+ return child;+}++/** Create one named-file probe that records the inherited gate class and can wait for release. */+function shortProbeSuite(box, name) {+ const root = join(box.dir, name);+ const tests = join(root, 'test');+ mkdirSync(tests, { recursive: true });+ writeFileSync(join(tests, 'short-probe.test.js'), `import { existsSync, renameSync, writeFileSync } from 'node:fs';+import { test } from 'node:test';+test(${JSON.stringify(PROBE_NAME)}, async () => {+ const marker = process.env.${PROBE_PATH_ENV};+ if (marker) {+ const temporary = marker + '.tmp';+ writeFileSync(temporary, JSON.stringify({ slotClass: process.env[${JSON.stringify(GATE_SLOT_CLASS_ENV)}],+ pool: process.env[${JSON.stringify(GATE_SLOT_POOL_ENV)}], token: process.env[${JSON.stringify(GATE_SLOT_TOKEN_ENV)}] }));+ renameSync(temporary, marker);+ }+ const release = process.env.${PROBE_RELEASE_ENV};+ while (release && !existsSync(release)) await new Promise(done => setTimeout(done, 10));+});+`);+ return root;+}++/** Launch a child that proves a named-file lease refuses full-suite inheritance. */+function fullSuiteInheritanceProbe(box, root, lease) {+ const script = join(box.dir, 'full-suite-inheritance.mjs');+ writeFileSync(script, `import { inheritedGateSlot } from ${JSON.stringify(RESOURCE_MODULE)};+try {+ inheritedGateSlot({ root: process.cwd(), fullSuite: true });+ process.exitCode = 2;+} catch (error) {+ process.stdout.write(String(error.code ?? 'unknown'));+ if (error.code !== 'SHORT_SLOT_FULL_SUITE') process.exitCode = 1;+}+`);+ return spawnSync(process.execPath, [script], { cwd: root, env: {+ ...box.env, [GATE_SLOT_HELD_ENV]: '1', [GATE_SLOT_POOL_ENV]: lease.pool,+ [GATE_SLOT_TOKEN_ENV]: lease.token, [GATE_SLOT_CLASS_ENV]: lease.slotClass,+ [BROWSER_SLOT_HELD_ENV]: '',+ }, encoding: 'utf8' });+}++/** Set the fixture machine capacities through the public settings command. */+function setShortSlots(box, root, gateSlots, shortSlots) {+ const gate = spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', String(gateSlots)], { cwd: root, env: box.env, encoding: 'utf8' });+ assert.equal(gate.status, 0, gate.failure ?? gate.stderr);+ const short = spawnSync(process.execPath, [BIN, 'settings', 'gate.shortSlots', String(shortSlots)], { cwd: root, env: box.env, encoding: 'utf8' });+ assert.equal(short.status, 0, short.failure ?? short.stderr);+}++/** Launch a synthetic main-red diagnostic holder, which must stay in ordinary capacity. */function launchDiagnostic(box, root, name, started, release, waiting) {const script = join(box.dir, `${name}.mjs`);writeFileSync(script, `import { existsSync, renameSync, writeFileSync } from 'node:fs';import { withGateSlot } from ${JSON.stringify(GATE_MODULE)};/** Publish a complete handshake so its visible file always contains its value. */+/** Publish a complete fixture marker atomically. */function publish(file, value) { writeFileSync(file + '.tmp', value); renameSync(file + '.tmp', file); }await withGateSlot(process.cwd(), async () => {publish(${JSON.stringify(started)}, 'started');@@ -560,6 +639,128 @@ syncBuiltinESMExports();assert.equal(readFileSync(marker, 'utf8'), '1', 'the final marker contains the complete slot value');});+test('short classification accepts only explicit parser-backed named runner commands [C7]', async () => {+ const { explicitCheckFiles } = await import(BROWSER_ADMISSION_MODULE);+ const root = process.cwd();+ assert.deepEqual(await explicitCheckFiles(root, `${quote(process.execPath)} bin/run-tests.js test/gate-resource.test.js`), ['test/gate-resource.test.js']);+ assert.equal(await explicitCheckFiles(root, 'npm test test/gate-resource.test.js'), null, 'opaque configured runners remain ordinary');+ assert.equal(await explicitCheckFiles(root, 'node bin/run-tests.js $(printf test/gate-resource.test.js)'), null, 'shell expansion is not classified');+ assert.equal(await explicitCheckFiles(root, 'node bin/run-tests.js --unknown test/gate-resource.test.js'), null, 'unknown options stay ordinary');+ assert.equal(await explicitCheckFiles(root, 'node bin/run-tests.js test/gate-resource.test.js', { env: { ...process.env, NODE_OPTIONS: '--trace-warnings' } }), null, 'runtime injection stays ordinary');+ assert.equal(await explicitCheckFiles(root, 'node bin/run-tests.js test/short-missing.test.js'), null, 'missing files stay ordinary');+ const committed = runFixtureChild('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' });+ assert.equal(committed.status, 0, committed.stderr);+ assert.deepEqual(await explicitCheckFiles(root, `${quote(process.execPath)} bin/run-tests.js test/gate-resource.test.js`, { commit: committed.stdout.trim() }),+ ['test/gate-resource.test.js'], 'frozen checks classify the submitted file map');+});++test('a short check never waits behind whole suites [C7]', async () => {+ const enabled = fixture();+ const holderRoots = [gateRepo(enabled, 'whole-one'), gateRepo(enabled, 'whole-two')];+ const gateRoot = holderRoots[0];+ const focusedRoot = shortProbeSuite(enabled, 'short-focused');+ const defaultSettings = spawnSync(process.execPath, [BIN, 'settings', '--json'], { cwd: gateRoot, env: enabled.env, encoding: 'utf8' });+ assert.equal(defaultSettings.status, 0, defaultSettings.failure ?? defaultSettings.stderr);+ assert.equal(JSON.parse(defaultSettings.stdout).settings.gate.shortSlots, 0, 'short capacity defaults to off');+ setShortSlots(enabled, gateRoot, 2, 1);+ const settingsView = spawnSync(process.execPath, [BIN, 'settings', '--json'], { cwd: gateRoot, env: enabled.env, encoding: 'utf8' });+ assert.equal(settingsView.status, 0, settingsView.failure ?? settingsView.stderr);+ assert.equal(JSON.parse(settingsView.stdout).settings.gate.shortSlots, 1);+ const invalidShortSlots = spawnSync(process.execPath, [BIN, 'settings', 'gate.shortSlots', '--json', '--', '-1'], { cwd: gateRoot, env: enabled.env, encoding: 'utf8' });+ assert.notEqual(invalidShortSlots.status, 0, 'negative short capacity is refused');+ assert.match(`${invalidShortSlots.stdout}${invalidShortSlots.stderr}`, /BAD_SHORT_SLOTS|nonnegative integer/u);+ const releases = holderRoots.map((_, index) => join(enabled.dir, `release-whole-${index}`));+ const started = holderRoots.map((_, index) => join(enabled.dir, `whole-${index}.started`));+ const waiting = holderRoots.map((_, index) => join(enabled.dir, `whole-${index}.waiting`));+ const holders = holderRoots.map((root, index) => launchLeaseFixture(enabled, root, `whole-${index}`, started[index], releases[index], waiting[index]));+ let short;+ let wholeWaiter;+ let directoryRun;+ const directoryStarted = join(enabled.dir, 'directory-request.started');+ const directoryRelease = join(enabled.dir, 'release-directory-request');+ const requestRelease = join(enabled.dir, 'release-short-request');+ const requestStarted = join(enabled.dir, 'short-request.started');+ const fullRelease = join(enabled.dir, 'release-full-request');+ const fullStarted = join(enabled.dir, 'full-request.started');+ const fullWaiting = join(enabled.dir, 'full-request.waiting');+ try {+ await waitFor(() => started.every(file => existsSync(file)), 'both synthetic ordinary gate leases to hold');+ wholeWaiter = launchLeaseFixture(enabled, gateRoot, 'ordinary-request', fullStarted, fullRelease, fullWaiting, false);+ await waitFor(() => existsSync(fullWaiting), 'an earlier ordinary-class request to queue behind the holders');+ directoryRun = launchTestRunner(enabled, focusedRoot, ['test/'], directoryStarted, directoryRelease);+ await waitFor(() => existsSync(directoryStarted) || directoryRun.stderrText.includes('waiting for a gate slot:') || directoryRun.exitCode !== null,+ 'the directory selection to report admission or its queued state');+ assert.ok(directoryRun.stderrText.includes('waiting for a gate slot:'), 'a directory operand must queue in the ordinary pool');+ assert.equal(existsSync(directoryStarted), false, 'a whole-directory selection cannot use a short slot');+ short = launchTestRunner(enabled, focusedRoot, ['--disable-warning', 'ExperimentalWarning', '--title', 'short-focused-probe', 'test/short-probe.test.js'], requestStarted, requestRelease);+ await waitFor(() => existsSync(requestStarted) || short.stderrText.includes('waiting for a gate slot:'),+ 'the named-file runner to publish admission or its queued state');+ assert.ok(existsSync(requestStarted), 'a named-file run starts before the ordinary holders release');+ const shortLease = JSON.parse(readFileSync(requestStarted, 'utf8'));+ assert.equal(shortLease.slotClass, 'short', 'the named test inherits the assigned short slot class');+ const fullInheritance = fullSuiteInheritanceProbe(enabled, gateRoot, shortLease);+ assert.equal(fullInheritance.status, 0, fullInheritance.stderr);+ assert.equal(fullInheritance.stdout, 'SHORT_SLOT_FULL_SUITE', 'a full-suite child cannot inherit a short lease');+ assert.equal(existsSync(fullStarted), false, 'an ordinary-class request cannot use the available short slot');+ const status = spawnSync(process.execPath, [BIN, 'resources', '--json'], { cwd: gateRoot, env: enabled.env, encoding: 'utf8' });+ assert.equal(status.status, 0, status.failure ?? status.stderr);+ const resourceOutput = JSON.parse(status.stdout);+ assert.equal(resourceOutput.gate.shortSlots, 1, 'pool status reports configured short capacity');+ const gateStatus = resourceOutput.resources.find(resource => resource.name === 'gate');+ assert.equal(gateStatus.holders.filter(holder => holder.slot === 'short').length, 1, 'pool status labels the actual short holder');+ assert.equal(gateStatus.capacity, 2, 'short capacity is not added to ordinary gateSlots');+ assert.equal(gateStatus.holders.filter(holder => holder.slot === 'gate').length, 2, 'ordinary holders retain the gate slot class');+ } finally {+ for (const release of [...releases, requestRelease, fullRelease, directoryRelease]) writeFileSync(release, 'release\n');+ await Promise.all([...holders, short, wholeWaiter, directoryRun].filter(Boolean).map(child => child.closed));+ }+ for (const child of [...holders, short, wholeWaiter, directoryRun].filter(Boolean)) {+ const result = await child.closed;+ if (child === directoryRun && result.code !== 0) {+ assert.equal(result.code, 1, `${child.stderrText}${child.stdoutText}`);+ assert.match(child.stdoutText, /ERR_UNSUPPORTED_DIR_IMPORT/u, 'this runtime may refuse directory operands after ordinary admission');+ } else assert.equal(result.code, 0, `${child.stderrText}${child.stdoutText}`);+ assert.equal(result.signal, null);+ }++ const disabled = fixture();+ const disabledRoot = gateRepo(disabled, 'whole-disabled-one');+ const disabledRoot2 = gateRepo(disabled, 'whole-disabled-two');+ setShortSlots(disabled, disabledRoot, 2, 0);+ const disabledReleases = [join(disabled.dir, 'release-disabled-1'), join(disabled.dir, 'release-disabled-2')];+ const disabledStarts = [join(disabled.dir, 'disabled-one.started'), join(disabled.dir, 'disabled-two.started')];+ const disabledWaits = [join(disabled.dir, 'disabled-one.waiting'), join(disabled.dir, 'disabled-two.waiting')];+ const disabledHolders = [+ launchLeaseFixture(disabled, disabledRoot, 'disabled-one', disabledStarts[0], disabledReleases[0], disabledWaits[0]),+ launchLeaseFixture(disabled, disabledRoot2, 'disabled-two', disabledStarts[1], disabledReleases[1], disabledWaits[1]),+ ];+ let disabledRequest;+ const disabledRequestRelease = join(disabled.dir, 'release-disabled-request');+ const disabledRequestStarted = join(disabled.dir, 'disabled-request.started');+ try {+ await waitFor(() => disabledStarts.every(file => existsSync(file)), 'both disabled-pool ordinary leases to hold');+ const disabledFocusedRoot = shortProbeSuite(disabled, 'disabled-focused');+ disabledRequest = launchTestRunner(disabled, disabledFocusedRoot, ['--disable-warning', 'ExperimentalWarning', '--title', 'disabled-focused-probe', 'test/short-probe.test.js'], disabledRequestStarted, disabledRequestRelease);+ await waitFor(() => disabledRequest.stderrText.includes('waiting for a gate slot:'), 'the named run-tests request to wait when shortSlots is zero');+ assert.equal(existsSync(disabledRequestStarted), false, 'zero shortSlots preserves ordinary full-pool blocking');+ const waitingStatus = spawnSync(process.execPath, [BIN, 'resources', '--json'], { cwd: disabledRoot, env: disabled.env, encoding: 'utf8' });+ assert.equal(waitingStatus.status, 0, waitingStatus.failure ?? waitingStatus.stderr);+ const waitingGate = JSON.parse(waitingStatus.stdout).resources.find(resource => resource.name === 'gate');+ assert.ok(waitingGate.line.some(waiter => waiter.requestedSlot === 'short-eligible'), 'pool status identifies a queued short-eligible request');+ for (const release of disabledReleases) writeFileSync(release, 'release\n');+ await waitFor(() => existsSync(disabledRequestStarted), 'the named request to proceed after an ordinary slot is released');+ assert.equal(JSON.parse(readFileSync(disabledRequestStarted, 'utf8')).slotClass, 'gate');+ } finally {+ for (const release of [...disabledReleases, disabledRequestRelease]) writeFileSync(release, 'release\n');+ await Promise.all([...disabledHolders, disabledRequest].filter(Boolean).map(child => child.closed));+ }+ for (const child of [...disabledHolders, disabledRequest].filter(Boolean)) {+ const result = await child.closed;+ assert.equal(result.code, 0, `${child.stderrText}${child.stdoutText}`);+ assert.equal(result.signal, null);+ }+});+test('a focused run queues behind a held gate slot [Q4,C7]', async () => {const box = fixture();const release = join(box.dir, 'release-focused-holder');