Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(runner): a runner runs at its registered capacity [C7]
Corey Olson56bef7fa0ea8
diff --git a/src/commands/runner.js b/src/commands/runner.jsindex c062bb38..24303721 100644--- a/src/commands/runner.js+++ b/src/commands/runner.js@@ -4,11 +4,20 @@ import {} from '../refused.js';import {addRunner,+ loadMachineSettings,removeRunner,} from '../settings.js';-/** Add or remove machine-level SSH capacity without requiring a board identity or runner account. */+/** List, add or remove machine-level SSH capacity without requiring a board identity or runner account. */export function runnerCommand(io, { first, second, rest, values }) {+ if (first === 'list') {+ if (second || rest.length || Object.keys(values).some(key => key !== 'json')) throw new Refused('USAGE', 'pullboard runner list');+ // Registered capacity is what each runner enforces, whatever its own settings say (#1066).+ const runners = loadMachineSettings().runners ?? [];+ io.result?.({ runners });+ io.say(runners.length ? runners.map(runner => `${runner.host}: ${runner.slots} slots, ${runner.browser} browser`).join('\n') : 'no runners registered');+ return 0;+ }if (first === 'remove') {if (!second || second.trim() !== second || rest.length || Object.keys(values).some(key => key !== 'json')) {throw new Refused('USAGE', 'pullboard runner remove <ssh-host>');diff --git a/src/help.js b/src/help.jsindex 062bbf19..629142c7 100644--- a/src/help.js+++ b/src/help.js@@ -33,6 +33,7 @@ Set upshort slots for runs that name their test files are opt-in: pullboard settings gate.shortSlots <n> (default 0)pullboard runner add <ssh-host> --slots <n> --browser <n> [--node <remote-path>] [--root <remote-path>]register SSH test capacity; no runner sign-in; root defaults to ~/.pullboard-runner+ pullboard runner list each runner's registered slots and browsers, which it runs atpullboard view [--project] [--port N] [--no-open] every project on this machine in your browser; default http://127.0.0.1:${DEFAULT_VIEW_PORT}items, shouts, doctrine, agents and activity; --port 0 chooses a free port--project limits this view to the registered project for this repositorydiff --git a/src/next-steps.js b/src/next-steps.jsindex 3bd9ad1a..fb45f828 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -215,6 +215,7 @@ export const NEXT_STEPS = Object.freeze({BRIEF_LANE: 'split the item by lane, or add the other lane\'s part as its own item and wait on it with --after',BRIEF_TOO_LONG: 'shorten the brief and point to a longer doc by path, or pass --brief-file <file>',BROWSER_SLOT_REQUIRED: 'release the gate lease and take it again with browser: true',+ RUNNER_CAPACITY_BUSY: 'nothing to do on that runner: rerun once its running jobs end, and it runs at its new registered size',RUNNER_BROWSER_SLOT_REQUIRED: 'nothing to do: the run reruns on a local gate slot; if it repeats, set gate.browserByLaunch the same on this machine and that runner',CANNOT_SIGN: 'sign only approved rows: pullboard spec signoff <approved ids>',CHECKOUT_SESSION: 'run pullboard takeover from the agent session that owns this checkout',diff --git a/src/runner-worker.js b/src/runner-worker.jsindex 0f5b95b8..91e5b08b 100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@ -37,6 +37,7 @@ import {pathToFileURL,} from 'node:url';import * as resourceApi from './resources.js';+import { Refused } from './refused.js';import { parseProcessCensus } from './process-census.js';import {gateStages,@@ -843,6 +844,30 @@ async function acquireResourceApi(api, options, machineHomePath) {}}+/**+ * Size this machine's gate and browser pools to the capacity the controller registered, carried in+ * the job (#1066). A lower registration waits for an idle pool, and is refused by name until then.+ */+function registeredCapacity(api, spec, root, machineHomePath) {+ const previous = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_MACHINE_HOME = machineHomePath;+ try {+ /** Set one pool row; a busy pool cannot shrink, so this run is refused rather than oversubscribed. */+ const size = (name, capacity) => {+ try { return api.setResourceCapacity({ name, capacity, scope: 'machine', root }).capacity; }+ catch (error) {+ if (error?.code !== 'RESOURCE_BUSY') throw error;+ throw new Refused('RUNNER_CAPACITY_BUSY', `this runner is registered with ${capacity} ${name} slot(s), fewer than its busy pool holds; it shrinks once its running jobs end`);+ }+ };+ // A runner registered with no browsers never receives a browser run, so its browser row is left alone.+ return { gateCapacity: size('gate', spec.slots), browserCapacity: spec.browser > 0 ? size('browser', spec.browser) : 1 };+ } finally {+ if (previous === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previous;+ }+}+/** Bound Git diagnostics and hide runner-private paths, URL credentials and credential assignments. */function safeGitDiagnostic(value, root, env) {let text = String(value).replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, '').replace(/\r\n?/gu, '\n').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/gu, '');@@ -1271,19 +1296,8 @@ async function main() {setupPrivatePaths.add(machineHomePath);setupStep = 'trusted resource API';api = loadResourceApi(spec.runtime);- const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;- let resources;- try {- process.env.PULLBOARD_MACHINE_HOME = machineHomePath;- resources = api.listResources({ scope: 'machine', root: runnerRoot });- } finally {- if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;- else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;- }- const gateCapacity = resources.find(resource => resource.name === 'gate')?.capacity ?? Math.min(spec.slots, 2);- // pullboard settings browserSlots writes this row and settings.json under one lock, so the row carries- // this machine's setting without reading settings.json; a machine that set nothing keeps one browser slot.- const browserCapacity = resources.find(resource => resource.name === 'browser')?.capacity ?? 1;+ // The registration travels with the job; this machine's own settings never size a runner (#1066).+ const { gateCapacity, browserCapacity } = registeredCapacity(api, spec, runnerRoot, machineHomePath);setupStep = 'job directories';const base = join(runnerRoot, 'jobs');mkdirSync(base, { recursive: true, mode: 0o700 });diff --git a/test/runner-capacity-fixture.js b/test/runner-capacity-fixture.jsnew file mode 100644index 00000000..618a6f09--- /dev/null+++ b/test/runner-capacity-fixture.js@@ -0,0 +1,135 @@+/** A runner runs as many jobs and browser jobs as it was registered with, whatever its own settings say [C7,O5]. */+import assert from 'node:assert/strict';+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { listResources, takeResource } from '../src/resources.js';+import { runFixtureChild } from './fixture-child.js';+import { HOST, installSshStandIn, shellQuote } from './runner-ssh-fixture.js';++/** Read one machine pool row through the public resource API, selecting that machine's home. */+function poolAt(machineHome, root, name) {+ const previous = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ try { return listResources({ scope: 'machine', root }).find(resource => resource.name === name) ?? null; }+ finally {+ if (previous === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previous;+ }+}++/**+ * Poll an observable fixture state, failing at once with the controller's output if a run exits first.+ * Without the early exit a refused remote setup would only show up as an unexplained timeout.+ */+async function waitForRunState(runs, check, label) {+ const deadline = Date.now() + 60_000; // budget: remote checkout plus admission for four real workers.+ while (true) {+ const state = check();+ if (state) return state;+ for (const run of runs) {+ if (run.result) throw new Error(`${label}: run ${run.item} exited first\n${run.result.stdout.slice(-4_000)}\n${run.result.stderr.slice(-4_000)}`);+ }+ if (Date.now() >= deadline) throw new Error(`${label}: state did not arrive`);+ await new Promise(resolveWait => setTimeout(resolveWait, 20)); // budget: polling interval for a public pool state.+ }+}++/**+ * Register a stand-in runner with 4 slots and 3 browsers, then hold 3 browser runs and 1 plain run on it+ * at once: first with no settings on the runner, then with the runner's own settings at 1 and 1.+ */+export async function runnerUsesRegisteredCapacity(t, { cli, git, observe, startQueueController, gateResult }) {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-capacity-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const markers = join(dir, 'markers');+ const requests = join(dir, 'ssh-requests.jsonl');+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome, markers]) mkdirSync(folder, { recursive: true });+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Runner Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Runner Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const remoteEnv = { ...env, HOME: remoteHome, PULLBOARD_HOME: remoteHome, PULLBOARD_MACHINE_HOME: remoteMachineHome };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'tracked.txt'), 'committed runner source\n');+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare runner capacity fixture');+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '4', '--browser', '3', '--json');+ assert.equal(added.status, 0, added.context);++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ const runs = [];+ /** Start one run that holds its runner slot until the test writes its release marker. */+ const startHeld = (item, browser) => {+ const started = join(markers, `${item}.started`);+ const release = join(markers, `${item}.release`);+ const code = `const fs=require('node:fs'); fs.writeFileSync(${JSON.stringify(started)}, 'started\\n');+const timer=setInterval(()=>{ if (fs.existsSync(${JSON.stringify(release)})) clearInterval(timer); }, 5);`;+ const observed = observe(startQueueController(repo, env, `node -e ${shellQuote(code)}`, { item, queueMarker: null, firstItem: null, browser }));+ const run = { item, started, release, ...observed, result: null };+ observed.closed.then(result => { run.result = result; });+ runs.push(run);+ return run;+ };+ /** Hold three browser runs and one plain run on the runner at once, check its pools, then release them green. */+ const holdFour = async (label) => {+ const four = [startHeld(`${label}-b1`, true), startHeld(`${label}-b2`, true), startHeld(`${label}-b3`, true), startHeld(`${label}-plain`, false)];+ await waitForRunState(four, () => four.every(run => existsSync(run.started)), `${label}: all four runs start on the runner at once`);+ const gate = poolAt(remoteMachineHome, repo, 'gate');+ const browser = poolAt(remoteMachineHome, repo, 'browser');+ assert.equal(gate.capacity, 4, `${label}: the runner's gate pool is its registered 4 slots`);+ assert.equal(gate.holders.length, 4, `${label}: four runs hold runner slots`);+ assert.equal(browser.capacity, 3, `${label}: the runner's browser pool is its registered 3 browsers`);+ assert.equal(browser.holders.length, 3, `${label}: three browser runs hold runner browsers`);+ for (const run of four) writeFileSync(run.release, 'release\n');+ for (const result of await Promise.all(four.map(run => run.closed))) {+ assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);+ assert.equal(gateResult(result.stdout).runner, HOST, 'the run executed on the runner');+ }+ };+ let held;+ try {+ // Fill the controller's own gate so every run below goes to the runner.+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'fixture-local-holder', item: 'local-holder', kind: 'force-registered-runner' });+ await holdFour('unset');+ // The runner machine's own settings neither lower nor raise what its registration gives it.+ for (const [key, value] of [['browserSlots', '1'], ['gateSlots', '1']]) {+ const setting = cli(repo, remoteEnv, 'settings', key, value, '--json');+ assert.equal(setting.status, 0, setting.context);+ }+ await holdFour('lowered');+ const listed = cli(repo, env, 'runner', 'list');+ assert.equal(listed.status, 0, listed.context);+ assert.match(listed.stdout, new RegExp(`^${HOST.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}: 4 slots, 3 browser$`, 'mu'), 'runner list prints the registered capacity');+ } finally {+ held?.release();+ for (const run of runs) writeFileSync(run.release, 'cleanup-release\n');+ // A remote setup that never answers must not hold the test file open: stop its controller.+ const settled = Promise.all(runs.map(run => run.closed));+ const ceiling = new Promise(resolveCeiling => { const timer = setTimeout(resolveCeiling, 20_000); timer.unref(); }); // budget: released runs finish well inside this.+ await Promise.race([settled, ceiling]);+ for (const run of runs) if (!run.result) run.child.kill('SIGTERM');+ await settled;+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+}diff --git a/test/runners.test.js b/test/runners.test.jsindex f54344a9..594ff7b8 100644--- a/test/runners.test.js+++ b/test/runners.test.js@@ -23,6 +23,7 @@ import { sourceSetupFailureFixture } from './runner-source-setup-fixture.js';import { runnerSourceRefusalCases } from './runner-source-refusal-fixture.js';import { writeCacheProbe, writeProbe } from './runner-probe-fixture.js';import { browserFreeRunnerCheck, browserRefusalTextStaysRed } from './runner-browser-free-fixture.js';+import { runnerUsesRegisteredCapacity } from './runner-capacity-fixture.js';/** Per-phase deadlines for one runner round trip; together they stay near the 60-second hang ceiling. */const ROUND_TRIP_DEADLINES = { dispatch: 20_000, 'remote run': 30_000, 'result return': 10_000 }; // budget: a stuck runner fails by name in about a minute, far under the 660-second per-test limit.@@ -232,7 +233,7 @@ function processIsAlive(pid) {}/** Start an API child that requeues only an incomplete runner transport on its original ticket. */-function startQueueController(repo, env, command, { item, queueMarker, firstItem = 'retry-first', remote = true, toolingRoot = resolve(import.meta.dirname, '..') } = {}) {+function startQueueController(repo, env, command, { item, queueMarker, firstItem = 'retry-first', remote = true, browser = true, toolingRoot = resolve(import.meta.dirname, '..') } = {}) {const sourceRoot = realpathSync(toolingRoot);const gateUrl = pathToFileURL(join(committedToolingSnapshot(sourceRoot, env), 'src', 'gate.js')).href;const snapshot = TOOLING_SNAPSHOTS.get(sourceRoot);@@ -249,7 +250,7 @@ const result = await withGateSlot(root, async lease => {process.stdout.write('PULLBOARD_RUN_RESULT ' + JSON.stringify({ isGreen: run.isGreen, runner: run.profile.executionRunner }) + '\\n');return run;},- { browser: true, remote: ${remote}, item: ${JSON.stringify(item)}, kind: 'runner-retry-test', agent: ${JSON.stringify(item)},+ { browser: ${browser}, remote: ${remote}, item: ${JSON.stringify(item)}, kind: 'runner-retry-test', agent: ${JSON.stringify(item)},onWait(state) {const rows = state.line ?? [];if (queueMarker && rows.some(row => row.item === ${JSON.stringify(item)}) && (firstItem === null || rows.some(row => row.item === firstItem))) {@@ -1361,11 +1362,9 @@ test('a refused remote setup fails the run by name [C7]', async (t) => {installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests, stderrLog: remoteStderr });const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');assert.equal(added.status, 0, added.context);- // The runner's own pool holds rows no browser gate lease can match, so the worker's request is refused.- onMachine(remoteMachineHome, () => {- setResourceCapacity({ name: 'gate', capacity: 1, scope: 'machine', root: repo });- setResourceCapacity({ name: 'browser', capacity: 2, scope: 'machine', root: repo });- });+ // The runner's own pool is busy at more slots than its registration, so the worker's request is refused.+ let remoteHolder = await onMachine(remoteMachineHome, () => takeResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,+ agent: 'fixture-remote-holder', item: 'remote-holder', kind: 'force-busy-runner' }));const previousHome = process.env.PULLBOARD_HOME;const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;@@ -1386,8 +1385,8 @@ test('a refused remote setup fails the run by name [C7]', async (t) => {assert.ok(Date.now() - startedAt < 30_000); // budget: declared 30-second completion ceiling in the frozen #690 criterion.assert.notEqual(result.status, 0, 'a refused remote setup is a failed run');const said = `${result.stdout}${result.stderr}`;- // Before #684 the worker's own request is refused as a capacity mismatch; after it, as a browser capacity above the gate.- assert.match(result.stderr, new RegExp(`\\[RUNNER_SETUP_REFUSED\\] runner ${HOST} refused this run before it started: \\[(?:RESOURCE_CAPACITY_MISMATCH|BAD_BROWSER_SLOTS)\\]`, 'u'),+ // Since #1066 the registration sizes the runner's pool, and a busy pool cannot shrink to it.+ assert.match(result.stderr, new RegExp(`\\[RUNNER_SETUP_REFUSED\\] runner ${HOST} refused this run before it started: \\[RUNNER_CAPACITY_BUSY\\]`, 'u'),`the failure names the runner host and the refusal code\n${said}`);assert.equal(result.stdout.includes('PULLBOARD_RUN_RESULT'), false, 'the refused run reports no test result');assert.equal(existsSync(ran), false, 'the command never ran');@@ -1399,6 +1398,8 @@ test('a refused remote setup fails the run by name [C7]', async (t) => {assert.equal(ended[0].workerStarted, true);assert.equal(ended[0].code, 0, 'the worker exits after its receipt');+ remoteHolder.release();+ remoteHolder = null;const remote = onMachine(remoteMachineHome, () => listResources({ scope: 'machine', root: repo }));for (const resource of remote) {assert.deepEqual([resource.holders.length, resource.line.length], [0, 0], `runner pool ${resource.name} keeps no holder or waiter`);@@ -1408,6 +1409,7 @@ test('a refused remote setup fails the run by name [C7]', async (t) => {assert.deepEqual(local.find(resource => resource.name === 'gate').line, [], 'the run is not left waiting in the controller queue');} finally {held?.release();+ remoteHolder?.release();if (run) {const ceiling = new Promise(resolve => { const timer = setTimeout(resolve, 20_000); timer.unref(); }); // budget: a hung controller must not hold the test file open.if (!(await Promise.race([run.closed.then(() => true), ceiling]))) run.child.kill('SIGTERM');@@ -1613,138 +1615,7 @@ console.log('RUNNER_CLEANUP_TIMEOUT_BODY_RAN');}});-/** Read one machine pool's browser row through the public resource API, selecting that machine's home. */-function browserPoolAt(machineHome, root) {- const previous = process.env.PULLBOARD_MACHINE_HOME;- process.env.PULLBOARD_MACHINE_HOME = machineHome;- try { return listResources({ scope: 'machine', root }).find(resource => resource.name === 'browser') ?? null; }- finally {- if (previous === undefined) delete process.env.PULLBOARD_MACHINE_HOME;- else process.env.PULLBOARD_MACHINE_HOME = previous;- }-}--/**- * Poll an observable fixture state, failing at once with the controller's output if a run exits first.- * Without the early exit a refused remote setup would only show up as an unexplained timeout.- */-async function waitForRunState(runs, check, label) {- const deadline = Date.now() + 30_000; // budget: bound remote checkout plus admission for two real workers.- while (true) {- const state = check();- if (state) return state;- for (const run of runs) {- if (run.result) throw new Error(`${label}: run ${run.item} exited first\n${run.result.stdout.slice(-4_000)}\n${run.result.stderr.slice(-4_000)}`);- }- if (Date.now() >= deadline) throw new Error(`${label}: state did not arrive`);- await new Promise(resolve => setTimeout(resolve, 20)); // budget: polling interval for a public pool state.- }-}--test('a runner admits as many browser runs as its machine allows [C7,O5]', async (t) => {- const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-browser-slots-')));- t.after(() => rmSync(dir, { recursive: true, force: true }));- const home = join(dir, 'home');- const machineHome = join(home, '.pullboard');- const remoteHome = join(dir, 'worker-home');- const remoteMachineHome = join(remoteHome, '.pullboard');- const repo = join(dir, 'repo');- const worker = join(dir, 'second-machine');- const bin = join(dir, 'bin');- const markers = join(dir, 'markers');- const requests = join(dir, 'ssh-requests.jsonl');- for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome, markers]) mkdirSync(folder, { recursive: true });- writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));- const env = {- ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,- PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',- GIT_AUTHOR_NAME: 'Runner Fixture', GIT_AUTHOR_EMAIL: '[email protected]',- GIT_COMMITTER_NAME: 'Runner Fixture', GIT_COMMITTER_EMAIL: '[email protected]',- };- const remoteEnv = { ...env, HOME: remoteHome, PULLBOARD_HOME: remoteHome, PULLBOARD_MACHINE_HOME: remoteMachineHome };- const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });- assert.equal(initialized.status, 0, initialized.context);- writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));- writeFileSync(join(repo, 'tracked.txt'), 'committed runner source\n');- git(repo, env, 'add', 'pullboard.json', 'tracked.txt');- git(repo, env, 'commit', '-q', '-m', 'test: prepare runner browser capacity fixture');- installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });- // The controller may send two browser runs at once, so only the runner's own pool can hold one back.- const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '2', '--browser', '2', '--json');- assert.equal(added.status, 0, added.context);-- const previousHome = process.env.PULLBOARD_HOME;- const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;- process.env.PULLBOARD_HOME = home;- process.env.PULLBOARD_MACHINE_HOME = machineHome;- const runs = [];- /** Start one browser run that holds its runner slot until the test writes its release marker. */- const startHeld = (item) => {- const started = join(markers, `${item}.started`);- const release = join(markers, `${item}.release`);- const code = `const fs=require('node:fs'); fs.writeFileSync(${JSON.stringify(started)}, 'started\\n');-const timer=setInterval(()=>{ if (fs.existsSync(${JSON.stringify(release)})) clearInterval(timer); }, 5);`;- const observed = observe(startQueueController(repo, env, `node -e ${shellQuote(code)}`, { item, queueMarker: null, firstItem: null }));- const run = { item, started, release, ...observed, result: null };- observed.closed.then(result => { run.result = result; });- runs.push(run);- return run;- };- /** Release runs and check that each one came back green from the runner. */- const finish = async (pair) => {- for (const run of pair) writeFileSync(run.release, 'release\n');- for (const result of await Promise.all(pair.map(run => run.closed))) {- assert.equal(result.status, 0, `${result.stdout}${result.stderr}`);- assert.equal(gateResult(result.stdout).runner, HOST, 'the run executed on the runner');- }- };- let held;- try {- // Fill the controller's own gate so every run below goes to the runner.- held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,- agent: 'fixture-local-holder', item: 'local-holder', kind: 'force-registered-runner' });-- // A runner machine that set nothing admits one browser run; the second waits in its pool.- const unset = [startHeld('unset-a'), startHeld('unset-b')];- const queued = await waitForRunState(unset, () => {- const browser = browserPoolAt(remoteMachineHome, repo);- return browser?.holders.length === 1 && browser.line.length === 1 ? browser : null;- }, 'unset runner: one browser holder and one browser waiter');- assert.equal(queued.capacity, 1, 'a runner with no browserSlots setting keeps one browser slot');- const [first, second] = queued.holders[0].item === 'unset-a' ? unset : [...unset].reverse();- assert.equal(queued.line[0].item, second.item);- await waitForRunState(unset, () => existsSync(first.started), 'unset runner: the admitted run starts');- assert.equal(existsSync(second.started), false, 'the second browser run has not started while the first holds the only slot');- writeFileSync(first.release, 'release\n');- await waitForRunState([second], () => existsSync(second.started), 'unset runner: the waiting run starts after the first ends');- await finish(unset);-- // The runner machine sets browserSlots 2: both browser runs hold its slots at the same time.- const setting = cli(repo, remoteEnv, 'settings', 'browserSlots', '2', '--json');- assert.equal(setting.status, 0, setting.context);- const configured = [startHeld('two-a'), startHeld('two-b')];- await waitForRunState(configured, () => configured.every(run => existsSync(run.started)), 'runner set to 2: both browser runs start');- const both = browserPoolAt(remoteMachineHome, repo);- assert.equal(both.capacity, 2, 'the runner pool uses its machine browserSlots setting');- assert.deepEqual(both.holders.map(holder => holder.item).sort(), ['two-a', 'two-b']);- assert.equal(both.line.length, 0, 'no browser run waits on a runner set to 2');- await finish(configured);- } finally {- held?.release();- for (const run of runs) writeFileSync(run.release, 'cleanup-release\n');- // A remote setup that never answers must not hold the test file open: stop its controller.- const settled = Promise.all(runs.map(run => run.closed));- const ceiling = new Promise(resolve => { const timer = setTimeout(resolve, 20_000); timer.unref(); }); // budget: released runs finish well inside this.- await Promise.race([settled, ceiling]);- for (const run of runs) if (!run.result) run.child.kill('SIGTERM');- await settled;- if (previousHome === undefined) delete process.env.PULLBOARD_HOME;- else process.env.PULLBOARD_HOME = previousHome;- if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;- else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;- }-});-+test('a runner uses the capacity it was registered with [C7,O5]', { timeout: 180_000 }, t => runnerUsesRegisteredCapacity(t, { cli, git, observe, startQueueController, gateResult })); // budget: two rounds of four concurrent runner round trips.test('review655 a registered runner honors the same live person waiver at landing [B3,R3,C7]', { timeout: 120_000 }, async (t) => {const { createE2eHelpers } = await import('./e2e-helpers.js');