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(runners): route GUI-marked files to logged-in runners [C7,V4]
Corey Olsona93dfb53becc
diff --git a/bin/run-tests.js b/bin/run-tests.jsindex 1d707e28..b1422924 100644--- a/bin/run-tests.js+++ b/bin/run-tests.js@@ -1504,6 +1504,9 @@ async function main(args) {}const actions = await (await import('../src/test-action-cache.js')).planTestActions(process.cwd(), args, { fullSuite, landing: process.env[LANDING_RUN_ENV] === '1', listFiles: () => fullSuite ? trackedDefaultTestFiles(process.cwd(), process.env) : explicitTestFiles(args) });if (actions.done) return;+ const { testsNeedGui } = await import('../src/gui-admission.js');+ const guiFiles = actions.files ?? (fullSuite ? trackedDefaultTestFiles(process.cwd(), process.env) : explicitTestFiles(args));+ const gui = testsNeedGui(process.cwd(), guiFiles);let signal = null;/** Keep sandbox lifetime inside the held lease, including the complete child process. */const shardLabel = process.env[LANDING_SHARD_ENV];@@ -1584,7 +1587,7 @@ async function main(args) {process.stdout.write(result.output);process.exitCode = result.exitCode;}, {- browser, kind: fullSuite ? 'gate' : 'focused', shortEligible,+ browser, gui, kind: fullSuite ? 'gate' : 'focused', shortEligible,remote: Boolean(canShipRunner),onWait: ({ holders, runnerUnavailable }) => {if (runnerUnavailable) {diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex 9b2213fc..2a5f5b71 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -57,9 +57,9 @@ Each move checks its guards in this order and refuses with the first one that do| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), builderFirstRefusal (REOPEN_HELD_FOR_BUILDER), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED) || release | open, claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), releaseOwnsWork (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) || lapse | claimed | open | clock, when its lease runs out | none |-| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or LAND_TIMEOUT_CUSTODY or LAND_GATE_OUTPUT or SLOT_DB_LOCKED or RUNNER_BROWSER_SLOT_REQUIRED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |+| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or RUNNER_GUI_SESSION_REQUIRED or LAND_TIMEOUT_CUSTODY or LAND_GATE_OUTPUT or SLOT_DB_LOCKED or RUNNER_BROWSER_SLOT_REQUIRED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) || reserve | submitted | submitted | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), roadmapReadable (MILESTONES_CORRUPT), itemExists (NO_ITEM), inState (NOT_SUBMITTED), reviewCooldownElapsed (REVIEW_COOLDOWN), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD) |-| accept | submitted, verified | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), itemCheckGreen (CHECK_RED or SLOT_DB_LOCKED or CHECK_UNVERIFIED or GUARD_CANNOT_FAIL or GUARD_NOT_FOUND), proofNoted (PROOF_REQUIRED), result (VERDICT_ENVIRONMENT), result (LAND_HEADER), result (ENGINE_VERSION) |+| accept | submitted, verified | verified | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonIsMet (BAD_REASON), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), itemCheckGreen (CHECK_RED or RUNNER_GUI_SESSION_REQUIRED or SLOT_DB_LOCKED or CHECK_UNVERIFIED or GUARD_CANNOT_FAIL or GUARD_NOT_FOUND), proofNoted (PROOF_REQUIRED), result (VERDICT_ENVIRONMENT), result (LAND_HEADER), result (ENGINE_VERSION) || reject | submitted, verified | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), result (VERDICT_ENVIRONMENT), result (LAND_HEADER), result (ENGINE_VERSION), result (NOT_YOURS), result (CLOSED) || reopen | submitted, verified | open | coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_REQUIRED), trunkConflicts (NOT_CONFLICTING or CONFLICT_FILES or NO_TRUNK or MERGE_CHECK_FAILED), conflictAccepted (NOT_ACCEPTED or BAD_CONFLICT or ENGINE_VERSION), result (BAD_CONFIG) || escalate | open, claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED) |@@ -132,12 +132,14 @@ Each move checks its guards in this order and refuses with the first one that do| RATCHET_ROSE | every touched doctrine check counts (exit 0 or 1), none rises above its committed count and no changed file gains a problem; watch-mode rules only count, only when accepted main has an approved doctrine rule with gate: check | fix the new problems, commit, submit again; only the person's signature raises count: || RATCHET_UNCOUNTED | every touched doctrine check counts (exit 0 or 1), none rises above its committed count and no changed file gains a problem; watch-mode rules only count, only when accepted main has an approved doctrine rule with gate: check | fix the check so it exits 0 or 1 within its timeout, then submit again || CHECK_RED | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | reject the failing behavior; the builder fixes and resubmits |+| RUNNER_GUI_SESSION_REQUIRED | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | nothing to do: the run reruns locally; log in to a GUI session on the runner before sending GUI-marked files there || SLOT_DB_LOCKED | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | the run never started, so it is not a red; rerun the same command once the named process releases the slot database || CHECK_UNVERIFIED | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | restore the frozen install or check environment and retry || GUARD_CANNOT_FAIL | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | reject: the check stays green with the named guard reverted || GUARD_NOT_FOUND | the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance | the named guard is not in the submitted commit; ask the coordinator to fix it || CRITERION_PROVES_NOTHING | the item's check does not already pass on main, or the person accepted that exact check, only when accepted main sets checks.provesNothing to "hold" | set a check that fails before the work, or the person runs pullboard check accept <id> || GATE_RED | the gate, which submit runs itself every time, is green at HEAD | fix what the digest names, commit, submit again |+| RUNNER_GUI_SESSION_REQUIRED | the gate, which submit runs itself every time, is green at HEAD | nothing to do: the run reruns locally; log in to a GUI session on the runner before sending GUI-marked files there || LAND_TIMEOUT_CUSTODY | the gate, which submit runs itself every time, is green at HEAD | inspect the saved timed gate cleanup state and stop only its proven owned processes before starting another landing || LAND_GATE_OUTPUT | the gate, which submit runs itself every time, is green at HEAD | inspect the retained timed gate output directory and free disk space, then start another landing || SLOT_DB_LOCKED | the gate, which submit runs itself every time, is green at HEAD | the run never started, so it is not a red; rerun the same command once the named process releases the slot database |diff --git a/src/commands/resources.js b/src/commands/resources.jsindex a593f949..a105f5b7 100644--- a/src/commands/resources.js+++ b/src/commands/resources.js@@ -45,6 +45,6 @@ export async function run(io) {for (const holder of resource.holders) io.say(` held by ${agentDisplayName(agents, ctx.config, holder.agent)}${holder.repo ? ` in ${holder.repo}` : ''}${resourceRunLabel(holder, shortSlots)} since ${holder.since}`);resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${resourceRunLabel(waiter, shortSlots)}; class ${waiter.queueClass}${waiter.agedFrom ? `, aged up from ${waiter.agedFrom}` : ''}`));}- for (const runner of runners) io.say(`runner ${runner.host}: ${runner.inUse}/${runner.slots} slots, ${runner.browserInUse}/${runner.browser} browser${runner.unavailable ? ' (unavailable; re-register after checking the host)' : ''}`);+ for (const runner of runners) io.say(`runner ${runner.host}: ${runner.inUse}/${runner.slots} slots, ${runner.browserInUse}/${runner.browser} browser, GUI ${runner.gui === true ? 'yes' : runner.gui === false ? 'no' : 'unknown'}${runner.unavailable ? ' (unavailable; re-register after checking the host)' : ''}`);return 0;}diff --git a/src/commands/runner.js b/src/commands/runner.jsindex e4cf32a9..568d82ee 100644--- a/src/commands/runner.js+++ b/src/commands/runner.js@@ -16,7 +16,7 @@ export function runnerCommand(io, { first, second, rest, values }) {// Registered capacity is what each runner enforces, whatever its own settings say (#1066).const runners = runnerResourceStatus(loadMachineSettings().runners ?? []);io.result?.({ runners });- io.say(runners.length ? runners.map(runner => `${runner.host}: ${runner.slots} slots, ${runner.browser} browser${runner.draining ? ' (draining)' : ''}`).join('\n') : 'no runners registered');+ io.say(runners.length ? runners.map(runner => `${runner.host}: ${runner.slots} slots, ${runner.browser} browser, GUI ${runner.gui === true ? 'yes' : runner.gui === false ? 'no' : 'unknown'}${runner.draining ? ' (draining)' : ''}`).join('\n') : 'no runners registered');return 0;}if (first === 'remove') {diff --git a/src/gate.js b/src/gate.jsindex 1665d6d2..0477b5ed 100644--- a/src/gate.js+++ b/src/gate.js@@ -4,6 +4,7 @@* tree's id in the git dir, so the same tree is never checked twice. An agent sees a digest of the* run, not the run (V10): a passing suite's output costs tokens and says nothing.*/+import { checkNeedsGui, projectNeedsGui, testsNeedGui } from './gui-admission.js';import {spawn,spawnSync,@@ -530,16 +531,16 @@ function hasPipeline(command) {* hold (gate.memoryFloorMB) holds short slots too, since a short run uses the same machine memory.** @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, remote?: boolean, agent?: string, item?: string|number, kind?: string, onWait?: (state: object) => void, onReceipt?: (receipt: object) => void, readMemory?: typeof readMachineMemory }} [options] - Queue class, short-slot eligibility, remote eligibility, progress reporter, the run's receipt once its slot is released (#836) and, for tests, the machine memory reader.+ * @param {{ landing?: boolean, itemCheck?: boolean, shortEligible?: boolean, diagnostic?: boolean, browser?: boolean, gui?: boolean, remote?: boolean, agent?: string, item?: string|number, kind?: string, onWait?: (state: object) => void, onReceipt?: (receipt: object) => void, readMemory?: typeof readMachineMemory }} [options] - Queue class, short-slot eligibility, remote eligibility, progress reporter, the run's receipt once its slot is released (#836) and, for tests, the machine memory reader.* @returns {Promise<any>} The action's result after releasing its lease.*/export async function withGateSlot(root, action, options = {}) {try { return await withOneGateSlot(root, action, options); }catch (error) {- if (error?.code !== 'RUNNER_BROWSER_SLOT_REQUIRED' || options.remote === false) throw error;+ if (!['RUNNER_BROWSER_SLOT_REQUIRED', 'RUNNER_GUI_SESSION_REQUIRED'].includes(error?.code) || options.remote === false) throw error;// The runner's red attempt stays on record beside the local rerun.const attempt = error.runnerAttempt ?? { host: '', exitCode: null, output: '' };- process.stderr.write(`${error.message}; its attempt (exit ${attempt.exitCode}):\n${attempt.output}${attempt.output.endsWith('\n') || !attempt.output ? '' : '\n'}rerunning it locally with a browser slot\n`);+ process.stderr.write(`${error.message}; its attempt (exit ${attempt.exitCode}):\n${attempt.output}${attempt.output.endsWith('\n') || !attempt.output ? '' : '\n'}rerunning it locally with the required capabilities\n`);const result = await withOneGateSlot(root, action, { ...options, remote: false, browser: true });if (result && typeof result === 'object') result.runnerAttempt = attempt;return result;@@ -553,7 +554,7 @@ export async function withLandingGateSlot(root, action, options = {}) {}/** One gate admission and its action; withGateSlot may call it again for a local rerun. */-async function withOneGateSlot(root, action, { landing = false, itemCheck = false, shortEligible = false, diagnostic = false, browser = false, remote = true, agent, item = '', kind = '', onWait, onReceipt, readMemory = readMachineMemory } = {}) {+async function withOneGateSlot(root, action, { landing = false, itemCheck = false, shortEligible = false, diagnostic = false, browser = false, gui = false, remote = true, agent, item = '', kind = '', onWait, onReceipt, readMemory = readMachineMemory } = {}) {const tracker = startReceipt();const receiptKind = kind || (landing ? 'landing' : 'gate');/** Hand the run its receipt tracker and slot, then record its receipt once the slot is released (#836). */@@ -594,6 +595,7 @@ async function withOneGateSlot(root, action, { landing = false, itemCheck = falsitemCheck,diagnostic,browser,+ gui,allowIdleCapacityUpdate: true,remote: remote && Boolean(source),runnerProvider: () => loadMachineSettings().runners ?? [],@@ -605,7 +607,7 @@ async function withOneGateSlot(root, action, { landing = false, itemCheck = falstry {while (true) {lease.source = source;- lease.runMetadata = { landing, itemCheck, diagnostic, item: String(item), kind };+ lease.runMetadata = { landing, itemCheck, diagnostic, gui, item: String(item), kind };timed(lease).tracker.mark('actionAt');try { return await action(lease); }catch (error) {@@ -654,7 +656,7 @@ export async function runGate(root, config, { trustStamp = true, onWait, landingawait recordRun(onFailure, run);return run;}, {- landing, browser: true, agent, item, kind: landing ? 'landing' : 'gate', onWait,+ landing, browser: true, gui: projectNeedsGui(root), agent, item, kind: landing ? 'landing' : 'gate', onWait,});}@@ -749,7 +751,7 @@ export async function runStaticChecks(root, config, { agent, item = '', onWait,refuseSandboxBlocked(run);if (!run.isGreen) throw new Refused('GATE_RED', `static checks are red; fix the named source before running proof:\n${digestOf(run.output)}`);return run;- }, { browser, agent, item, kind: 'static', itemCheck: true, shortEligible: true, onWait });+ }, { browser, gui: await checkNeedsGui(root, command), agent, item, kind: 'static', itemCheck: true, shortEligible: true, onWait });}/**@@ -787,6 +789,7 @@ 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;+ const gui = (check ? await checkNeedsGui(root, check) : false) || ((selection.full && !deferFullFallback && !deferSelection) ? projectNeedsGui(root) : testsNeedGui(root, proofFiles));return await withGateSlot(root, async (lease) => {pinRunMain(lease, onFailure);const startedAt = Date.now();@@ -841,7 +844,7 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,command: !deferFullFallback && selection.full ? config.gate : `${config.affectedTests.trimEnd()} ${proofFiles.map(path => commandWord('./' + path)).join(' ')}`, lease });await recordRun(onFailure, proof);return finish(proof);- }, { browser, agent, item, kind, itemCheck: true, onWait });+ }, { browser, gui, agent, item, kind, itemCheck: true, onWait });}/** The durable words a submission and its reviewers read for an affected selection moved to the landing gate. */diff --git a/src/gui-admission.js b/src/gui-admission.jsnew file mode 100644index 00000000..d9b3d2bc--- /dev/null+++ b/src/gui-admission.js@@ -0,0 +1,25 @@+/** Explicit test-file desktop requirements, independent of Chrome command-line flags [C7,V4]. */+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { explicitCheckFiles } from './browser-admission.js';++/** Only an explicit file annotation requests a GUI; --headless does not establish this capability. */+export function testsNeedGui(root, files) {+ return files.some(file => {+ try { return /^\s*(?:\/\*\*?[^]*?@pullboard-test-gui\b[^]*?\*\/)/u.test(readFileSync(resolve(root, file), 'utf8')); }+ catch { return false; } // Missing files retain their normal execution failure; they cannot add an inferred capability.+ });+}++/** Read the project's tracked Node test files when an opaque full gate supplies no explicit selection. */+export function projectNeedsGui(root) {+ const result = spawnSync('git', ['ls-files', '-z', '--', 'test', 'tests'], { cwd: root, encoding: 'utf8', maxBuffer: 8 * 1024 ** 2 });+ return result.status === 0 && testsNeedGui(root, result.stdout.split('\0').filter(file => /\.test\.[cm]?js$/u.test(file)));+}++/** Classify an explicit accepted check by its selected files; opaque commands conservatively use the project's annotations. */+export async function checkNeedsGui(root, command) {+ const files = await explicitCheckFiles(root, command);+ return files ? testsNeedGui(root, files) : projectNeedsGui(root);+}diff --git a/src/gui-session.js b/src/gui-session.jsnew file mode 100644index 00000000..b644afe6--- /dev/null+++ b/src/gui-session.js@@ -0,0 +1,38 @@+/** Read this execution user's Darwin GUI-domain availability without environment guesses. */+import {+ spawnSync,+} from 'node:child_process';++/**+ * Return a fresh GUI-domain observation: true, known absent false, or unknown null.+ * Injected dependencies are for isolated unit fixtures, not capability attestations.+ *+ * @param {object} [options]+ * @param {typeof spawnSync} [options.run] - bounded native-command runner+ * @param {string} [options.platform] - fixture platform; production uses this process+ * @param {() => number} [options.getuid] - fixture UID reader; production uses this process+ * @returns {boolean | null}+ */+export function guiSession({ run = spawnSync, platform = process.platform, getuid = process.getuid } = {}) {+ if (platform !== 'darwin' || typeof getuid !== 'function') return null;+ let uid;+ try { uid = getuid(); }+ catch { return null; } // Unavailable identity cannot establish this execution user's domain.+ if (!Number.isInteger(uid) || uid < 0 || uid >= 0xffffffff) return null;+ let result;+ try {+ result = run('/bin/launchctl', ['print', `gui/${uid}`], {+ encoding: 'utf8',+ stdio: ['ignore', 'ignore', 'pipe'],+ timeout: 1_000,+ killSignal: 'SIGKILL',+ maxBuffer: 4_096,+ env: { ...process.env, LANG: 'C', LC_ALL: 'C' },+ });+ } catch { return null; } // Spawn, timeout and read failures provide no negative capability fact.+ if (!result || result.error || result.signal || !Number.isInteger(result.status)) return null;+ if (result.status === 0) return true;+ const missing = /(?:^|\r?\n)Could not find domain for(?:[^\r\n]*)?(?:\r?\n|$)/u;+ if (typeof result.stderr === 'string' && missing.test(result.stderr)) return false;+ return null;+}diff --git a/src/landing-shards.js b/src/landing-shards.jsindex 023af9cb..19d17f72 100644--- a/src/landing-shards.js+++ b/src/landing-shards.js@@ -28,6 +28,7 @@ import {gitChildEnv,repoInfo,} from './git.js';+import { testsNeedGui } from './gui-admission.js';import { parseProcessCensus } from './process-census.js';import {BROWSER_SLOT_HELD_ENV,@@ -282,7 +283,7 @@ export function landingSource(root) {}/** Runner refusals that mean the host could not run the shard right now, so a local rerun is sound. */-const RERUN_REFUSALS = new Set(['RUNNER_SETUP_REFUSED', 'RESOURCE_LEASE_LOST', 'RUNNER_BROWSER_SLOT_REQUIRED']);+const RERUN_REFUSALS = new Set(['RUNNER_SETUP_REFUSED', 'RESOURCE_LEASE_LOST', 'RUNNER_BROWSER_SLOT_REQUIRED', 'RUNNER_GUI_SESSION_REQUIRED']);/*** How a sharded landing answers a runner that gave no test result. A lost host or transport, or a@@ -323,7 +324,7 @@ class NotNeeded extends Error {}* holds; `write` receives the merged log.* @returns {Promise<{ isGreen: boolean, balance: string, shards: object[], files: object[] }>}*/-export async function runLandingShards({ root, runner, files, count, inherited = null, needsBrowser = async () => true, write = text => process.stdout.write(text), remoteRun }) {+export async function runLandingShards({ root, runner, files, count, inherited = null, needsBrowser = async () => true, needsGui = shardFiles => testsNeedGui(root, shardFiles), write = text => process.stdout.write(text), remoteRun }) {const { withLandingGateSlot } = await import('./gate.js');const runners = await import('./runners.js');const { RunnerDropped } = runners;@@ -353,7 +354,7 @@ export async function runLandingShards({ root, runner, files, count, inherited =/** Tell the parent's lane that a shard became free to take or finished. */const signalChange = () => { const resolveChange = wake; changed = new Promise(next => { wake = next; }); resolveChange(); };const entries = await Promise.all(plan.map(async (shard, index) => ({ shard, label: `${index + 1}/${total}`,- browser: await needsBrowser(shard.files), claimed: false, localOnly: false, done: false, attempts: [], status: null })));+ browser: await needsBrowser(shard.files), gui: await needsGui(shard.files), claimed: false, localOnly: false, done: false, attempts: [], status: null })));/** Run one attempt of a shard on a lease: a local child, or the runner it names. */const attempt = async (entry, lease) => {@@ -378,7 +379,7 @@ export async function runLandingShards({ root, runner, files, count, inherited =const command = `${LANDING_SHARD_ENV}=${word(entry.label)} ${['node', './bin/run-tests.js', ...entry.shard.files].map(word).join(' ')}`;try {const run = await runOnRunnerAsync(root, command, { runner: lease.runner, source: lease.source, browser: lease.browser,- metadata: { ...(lease.runMetadata ?? {}), landing: true }, signal: stop });+ metadata: { ...(lease.runMetadata ?? {}), landing: true, gui: entry.gui }, signal: stop });return { attempt: number, host: lease.runner.host, outcome: run.isGreen ? 'green' : 'red', output: run.output, wallMs: Date.now() - started };} catch (error) {// A stop ends the runner's transport on purpose; that shard was stopped, not dropped.@@ -447,7 +448,7 @@ export async function runLandingShards({ root, runner, files, count, inherited =if (lease.runner && quarantined.has(lease.runner.host)) return 'divert';entry.claimed = true;await runOnLease(entry, lease);- }, { landing: true, browser: entry.browser, remote: !localOnly, kind: 'landing', item: `shard ${entry.label}`,+ }, { landing: true, browser: entry.browser, gui: entry.gui, remote: !localOnly, kind: 'landing', item: `shard ${entry.label}`,onWait: () => { if (entry.claimed || entry.done || stop.aborted) throw new NotNeeded(); } });running.then(result => {if (result !== 'divert' || entry.claimed || entry.done) return;@@ -469,7 +470,7 @@ export async function runLandingShards({ root, runner, files, count, inherited =/** The parent's own slot: run free shards one after another until every shard is done. */const lane = async () => {while (!entries.every(entry => entry.done) && !failures.length) {- const next = entries.find(entry => !entry.claimed && !entry.done);+ const next = entries.find(entry => !entry.claimed && !entry.done && (!entry.gui || !inherited.runner || inherited.runner.gui === true));if (!next) { await changed; continue; }next.claimed = true;await runOnLease(next, inherited);diff --git a/src/machine.js b/src/machine.jsindex 9b12b9ba..c731ab04 100644--- a/src/machine.js+++ b/src/machine.js@@ -173,10 +173,10 @@ export const GUARDS = [{ id: 'noUnverifiedStack', refuse: 'STACKED_ON_UNVERIFIED', rule: "the candidate range contains no other item's unverified submitted commit", next: 'wait for that item to be accepted, or rebuild without its commits', source: 'cli' },{ id: 'infraExplained', refuse: 'INFRA_NOTE_REQUIRED', rule: 'edits to tests or gate files that existed at claim carry an explanation', next: 'pullboard submit <id> --infra "<why>"', source: 'cli' },{ id: 'doctrineHolds', refuse: 'RATCHET_ROSE', alsoRefuses: [{ code: 'RATCHET_UNCOUNTED', next: 'fix the check so it exits 0 or 1 within its timeout, then submit again' }], rule: "every touched doctrine check counts (exit 0 or 1), none rises above its committed count and no changed file gains a problem; watch-mode rules only count", next: "fix the new problems, commit, submit again; only the person's signature raises count:", source: 'cli', when: 'only when accepted main has an approved doctrine rule with gate: check' },- { id: 'itemCheckGreen', refuse: 'CHECK_RED', alsoRefuses: [{ code: 'SLOT_DB_LOCKED', next: 'the run never started, so it is not a red; rerun the same command once the named process releases the slot database' }, { code: 'CHECK_UNVERIFIED', next: 'restore the frozen install or check environment and retry' }, { code: 'GUARD_CANNOT_FAIL', next: 'reject: the check stays green with the named guard reverted' }, { code: 'GUARD_NOT_FOUND', next: 'the named guard is not in the submitted commit; ask the coordinator to fix it' }], rule: 'the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance', next: 'reject the failing behavior; the builder fixes and resubmits', source: 'cli' },+ { id: 'itemCheckGreen', refuse: 'CHECK_RED', alsoRefuses: [{ code: 'RUNNER_GUI_SESSION_REQUIRED', next: 'nothing to do: the run reruns locally; log in to a GUI session on the runner before sending GUI-marked files there' }, { code: 'SLOT_DB_LOCKED', next: 'the run never started, so it is not a red; rerun the same command once the named process releases the slot database' }, { code: 'CHECK_UNVERIFIED', next: 'restore the frozen install or check environment and retry' }, { code: 'GUARD_CANNOT_FAIL', next: 'reject: the check stays green with the named guard reverted' }, { code: 'GUARD_NOT_FOUND', next: 'the named guard is not in the submitted commit; ask the coordinator to fix it' }], rule: 'the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance', next: 'reject the failing behavior; the builder fixes and resubmits', source: 'cli' },{ id: 'checkProvesSomething', refuse: 'CRITERION_PROVES_NOTHING', rule: "the item's check does not already pass on main, or the person accepted that exact check", next: 'set a check that fails before the work, or the person runs pullboard check accept <id>', source: 'cli', when: 'only when accepted main sets checks.provesNothing to "hold"' },- { id: 'gateGreen', refuse: 'GATE_RED', alsoRefuses: [{ code: 'LAND_TIMEOUT_CUSTODY', next: 'inspect the saved timed gate cleanup state and stop only its proven owned processes before starting another landing' }, { code: 'LAND_GATE_OUTPUT', next: 'inspect the retained timed gate output directory and free disk space, then start another landing' }, { code: 'SLOT_DB_LOCKED', next: 'the run never started, so it is not a red; rerun the same command once the named process releases the slot database' }, { code: 'RUNNER_BROWSER_SLOT_REQUIRED', next: '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' }, { code: 'PIPEFAIL_UNAVAILABLE', next: 'rewrite the gate without a pipe' }], rule: 'the gate, which submit runs itself every time, is green at HEAD', next: 'fix what the digest names, commit, submit again', source: 'cli' },+ { id: 'gateGreen', refuse: 'GATE_RED', alsoRefuses: [{ code: 'RUNNER_GUI_SESSION_REQUIRED', next: 'nothing to do: the run reruns locally; log in to a GUI session on the runner before sending GUI-marked files there' }, { code: 'LAND_TIMEOUT_CUSTODY', next: 'inspect the saved timed gate cleanup state and stop only its proven owned processes before starting another landing' }, { code: 'LAND_GATE_OUTPUT', next: 'inspect the retained timed gate output directory and free disk space, then start another landing' }, { code: 'SLOT_DB_LOCKED', next: 'the run never started, so it is not a red; rerun the same command once the named process releases the slot database' }, { code: 'RUNNER_BROWSER_SLOT_REQUIRED', next: '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' }, { code: 'PIPEFAIL_UNAVAILABLE', next: 'rewrite the gate without a pipe' }], rule: 'the gate, which submit runs itself every time, is green at HEAD', next: 'fix what the digest names, commit, submit again', source: 'cli' },{ id: 'queuedItemLease', refuse: 'ITEM_LEASE_LOST', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or restore a spec written for grammar 1, then retry' }, { code: 'SPEC_BEHIND_MAIN', next: 'merge main into this worktree, then renew the claim and retry' }, { code: 'NOT_A_REPO', next: 'restore the worktree Git metadata, then retry the command' }, { code: 'NO_CONFIG', next: 'restore pullboard.json in this worktree, then retry the command' }], rule: 'the caller still owns the same live item claim or review and can renew it against the frozen criterion', next: 'claim or reserve the item again before retrying the command', source: 'cli', when: 'while submit or an accept waits for a machine slot, and once immediately before admission' },{ id: 'treeStillDuringGate', refuse: 'MOVED_DURING_GATE', rule: 'when the gate ends, HEAD and every tracked file are as they were when it started', next: 'leave the worktree alone until the gate finishes, then submit again', source: 'cli' },{ id: 'childrenDone', refuse: 'CHILDREN_OPEN', rule: 'every child item is verified or withdrawn', next: 'finish the child items, or the coordinator withdraws them', source: 'board' },diff --git a/src/next-steps.js b/src/next-steps.jsindex 00d741ad..2e361c32 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -225,6 +225,7 @@ export const NEXT_STEPS = Object.freeze({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_GUI_SESSION_REQUIRED: 'nothing to do: the run reruns locally; log in to a GUI session on the runner before sending GUI-marked files there',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/resources.js b/src/resources.jsindex 33a38370..6e1e2650 100644--- a/src/resources.js+++ b/src/resources.js@@ -125,6 +125,7 @@ function openQueue(file) {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, 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 TABLE IF NOT EXISTS runner_gui (host TEXT PRIMARY KEY, gui INTEGER, observed_at TEXT NOT NULL);CREATE TABLE IF NOT EXISTS runner_draining (host TEXT PRIMARY KEY, runner TEXT NOT NULL);CREATE INDEX IF NOT EXISTS waiter_name_ticket ON waiter(name, ticket);`);for (const table of ['holder', 'waiter']) {@@ -139,6 +140,7 @@ function openQueue(file) {if (!columns.includes('lease_until')) db.exec(`ALTER TABLE ${table} ADD COLUMN lease_until 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('gui')) db.exec('ALTER TABLE waiter ADD COLUMN gui 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');}@@ -324,18 +326,18 @@ function queueOrder(scope) {/** Read the complete resource line with the metadata every admission view orders identically. */function queuedWaiters(db, name) {- return db.prepare('SELECT ticket, pid, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind, lease_until AS leaseUntil, classed, release_aware, board_key, release_rank, queue_ticket, short_eligible AS shortEligible FROM waiter WHERE name = ?').all(name);+ return db.prepare('SELECT ticket, pid, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, gui, remote, item, kind, lease_until AS leaseUntil, classed, release_aware, board_key, release_rank, queue_ticket, short_eligible AS shortEligible FROM waiter WHERE name = ?').all(name);}/** 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, leaseUntil, shortSlot, shortEligible, ...entry }) => ({ ...entry, landing: entry.landing === 1,+ const project = ({ diagnostic, browser, gui, remote, runner, item, kind, leaseUntil, 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 } : {}),+ ...(browser === 1 ? { browser: true } : {}), ...(gui === 1 ? { gui: true } : {}), ...(remote === 1 ? { remote: true } : {}),...(runner ? { runner } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}), ...(leaseUntil ? { leaseUntil } : {}) });// Browser is an additional capability on a gate lease, not a second partially held row.const where = name === 'browser' ? 'name = ? AND browser = 1' : 'name = ?';@@ -410,11 +412,11 @@ function validatedRunners(value) {if (!runner || typeof runner.host !== 'string' || !runner.host.trim() || runner.host.trim() !== runner.host|| !Number.isSafeInteger(runner.slots) || runner.slots < 1|| !Number.isSafeInteger(runner.browser) || runner.browser < 0 || runner.browser > runner.slots- || seen.has(runner.host)) {+ || seen.has(runner.host) || runner.gui !== undefined && runner.gui !== null && typeof runner.gui !== 'boolean') {throw new Refused('BAD_RUNNER_POOL', 'runners require unique nonempty hosts, positive slots, and browser capacity from zero through slots');}seen.add(runner.host);- return { host: runner.host, slots: runner.slots, browser: runner.browser,+ return { host: runner.host, slots: runner.slots, browser: runner.browser, ...(runner.gui !== undefined ? { gui: runner.gui } : {}),...(typeof runner.node === 'string' ? { node: runner.node } : {}),...(typeof runner.root === 'string' ? { root: runner.root } : {}) };});@@ -465,14 +467,19 @@ function gateAdmission(db, ticket, capacity, shortCapacity, runners, order = ARR}if (waiter.remote === 1) {const compatible = runners.filter(runner => {- if (unavailable.has(runner.host) || (waiter.browser === 1 && runner.browser < 1)) return false;+ const observed = db.prepare('SELECT gui FROM runner_gui WHERE host = ?').get(runner.host);+ const gui = observed ? observed.gui === 1 : runner.gui === true;+ if (unavailable.has(runner.host) || (waiter.browser === 1 && runner.browser < 1) || (waiter.gui === 1 && !gui)) return false;const used = usage.get(runner.host);return used.slots < runner.slots && (waiter.browser !== 1 || used.browsers < runner.browser);});// A landing spreads its active shards before filling another slot on the same runner.// Choose under this transaction's holder snapshot, so concurrent acquisitions cannot tie on stale use.if (waiter.landing === 1) compatible.sort((left, right) => usage.get(left.host).slots - usage.get(right.host).slots);- if (compatible.length) return { ...compatible[0], shortSlot: false };+ if (compatible.length) {+ const observed = db.prepare('SELECT gui FROM runner_gui WHERE host = ?').get(compatible[0].host);+ return { ...compatible[0], ...(observed ? { gui: observed.gui === null ? null : observed.gui === 1 } : {}), shortSlot: false };+ }}const earlierLanding = waiters.some(other => other.landing === 1 && other.ticket < waiter.ticket);if (waiter.shortEligible === 1 && !earlierLanding && localShortUsed < shortCapacity@@ -513,13 +520,23 @@ export function runnerResourceStatus(runners) {.all(runnerResourceName(runner.host));if (runner.draining && !holders.length) return [];const unavailable = db.prepare('SELECT since, detail FROM runner_unavailable WHERE host = ?').get(runner.host);- return [{ ...runner, inUse: holders.length, browserInUse: holders.filter(holder => holder.browser === 1).length,+ const observed = db.prepare('SELECT gui, observed_at FROM runner_gui WHERE host = ?').get(runner.host);+ return [{ ...runner, gui: runner.gui ?? null, ...(observed ? { gui: observed.gui === null ? null : observed.gui === 1, guiObservedAt: observed.observed_at } : {}), inUse: holders.length, browserInUse: holders.filter(holder => holder.browser === 1).length,unavailable: Boolean(unavailable), ...(unavailable ? { unavailableSince: unavailable.since, unavailableReason: unavailable.detail } : {}), holders }];});});} finally { db.close(); }}+/** Persist only an authenticated worker's fresh GUI observation; unknown replaces stale positive capability. */+export function recordRunnerGui(host, gui) {+ if (typeof host !== 'string' || !host.trim() || ![true, false, null].includes(gui)) throw new Refused('BAD_RUNNER_POOL', 'runner GUI observations require a host and true, false, or unknown');+ const db = open(machineResourceFile());+ try { update(db, () => db.prepare('INSERT INTO runner_gui(host, gui, observed_at) VALUES (?, ?, ?) ON CONFLICT(host) DO UPDATE SET gui = excluded.gui, observed_at = excluded.observed_at')+ .run(host, gui === null ? null : Number(gui), new Date().toISOString())); }+ finally { db.close(); }+}+/** Serialize runner changes with admission; removal may drain active leases instead of refusing. */export function updateRunnerSettings(host, persist, { drain = false } = {}) {if (typeof host !== 'string' || !host.trim() || host.trim() !== host || typeof persist !== 'function') {@@ -710,6 +727,7 @@ export async function takeResource(options) {const shortEligible = options.shortEligible === true;const diagnostic = options.diagnostic === true;const browser = options.browser === true;+ const gui = options.gui === true;const remote = options.remote === true;// This synchronous provider is used inside the admission transaction; callers must// limit it to a bounded local configuration read, never Git, process inspection or network work.@@ -792,7 +810,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, release_aware, board_key, release_rank, queue_ticket, 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)), 1, boardKey, releaseRank, resume?.queueTicket ?? null, Number(shortEligible));+ const inserted = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, release_aware, board_key, release_rank, queue_ticket, short_eligible, gui) 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)), 1, boardKey, releaseRank, resume?.queueTicket ?? null, Number(shortEligible), Number(gui));initialTicket = Number(inserted.lastInsertRowid);}}));@@ -814,11 +832,11 @@ 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, release_aware, board_key, release_rank, queue_ticket, 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), 1, boardKey, releaseRank, resume?.queueTicket ?? null, Number(shortEligible));+ 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, release_aware, board_key, release_rank, queue_ticket, short_eligible, gui) 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), 1, boardKey, releaseRank, resume?.queueTicket ?? null, Number(shortEligible), Number(gui));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, release_aware, board_key, release_rank, queue_ticket, 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), 1, boardKey, releaseRank, resume?.queueTicket ?? null, Number(shortEligible));+ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, release_aware, board_key, release_rank, queue_ticket, short_eligible, gui) 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), 1, boardKey, releaseRank, resume?.queueTicket ?? null, Number(shortEligible), Number(gui));initialTicket = Number(rejoined.lastInsertRowid);return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order, shortCapacity: options.shortCapacityProvider?.() ?? 0 }), rejoined: true } };}@@ -921,8 +939,8 @@ export async function takeResource(options) {requeueOpportunity = requeueTicket;}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, release_aware, board_key, release_rank, queue_ticket, 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 && !local), marker, 1, boardKey, releaseRank, requeueOpportunity, Number(shortEligible));+ db.prepare('INSERT INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, release_aware, board_key, release_rank, queue_ticket, short_eligible, gui) 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 && !local), marker, 1, boardKey, releaseRank, requeueOpportunity, Number(shortEligible), Number(gui));});} catch (error) {transferred = false;diff --git a/src/runner-worker.js b/src/runner-worker.jsindex de922387..3764e462 100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@ -34,6 +34,7 @@ import { fileURLToPath } from 'node:url';import * as resourceApi from './resources.js';import { createDescendantTracker } from './runner-custody.js';import { Refused } from './refused.js';+import { guiSession } from './gui-session.js';import {gateStages,stagedScript,@@ -169,6 +170,7 @@ async function readSpec() {|| typeof value.pipefail !== 'boolean' || !Number.isSafeInteger(value.slots) || value.slots < 1|| !Number.isSafeInteger(value.browser) || value.browser < 0|| typeof value.browserRequired !== 'boolean'+ || value.guiRequired !== undefined && typeof value.guiRequired !== 'boolean'|| (value.browserByLaunch !== undefined && typeof value.browserByLaunch !== 'boolean')|| !value.runtime || typeof value.runtime !== 'object' || !value.runtime.files || typeof value.runtime.files !== 'object'|| typeof value.runtime.sha256 !== 'string') throw new Error('invalid work specification');@@ -200,7 +202,7 @@ async function readSpec() {tagNames.add(tag.name);if (tag.chain.length ? tag.chain[0] !== tag.object : tag.object !== tag.peeledCommit) throw new Error('invalid tag manifest');}- const runtimeNames = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js'];+ const runtimeNames = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js', 'gui-session.js'];if (Object.keys(value.runtime.files).length !== runtimeNames.length|| runtimeNames.some(name => typeof value.runtime.files[name] !== 'string')) throw new Error('invalid work specification');if (createHash('sha256').update(JSON.stringify(value.runtime.files)).digest('hex') !== value.runtime.sha256) throw new Error('invalid trusted runtime');@@ -746,7 +748,7 @@ async function runCommand(spec, root, env, sink, tracker) {async function receipt(spec, fields, sink) {await flushStdout();const body = { id: spec.id, commit: spec.commit, tree: spec.tree, code: fields.code, signal: fields.signal,- environment: executionEnvironment(),+ environment: executionEnvironment(), gui: fields.gui ?? null,runtimeSha256: spec.runtime.sha256, toolingSha256: spec.tooling.sha256, root: fields.root ?? '', outputSha256: sink.hash.digest('hex'), wallMs: Math.max(0, Date.now() - sink.wallStart),// The execution host's load and the pinned main this run used, so a paired rerun here can be judged (#925).main: typeof spec.main === 'string' ? spec.main : null, load: { average: loadavg(), cpus: availableParallelism(), freeMB: Math.floor(freemem() / 1048576) },@@ -798,6 +800,7 @@ async function main() {let tracker = null;let runDirectory;let setupStep = 'runner directories';+ let gui = null;let final = { code: 1, signal: null, root: '' };try {const runnerHome = isAbsolute(process.env.HOME || '') ? process.env.HOME : userInfo().homedir;@@ -837,6 +840,8 @@ async function main() {item: spec.item ?? '', kind: spec.kind ?? 'remote-command',onWait: () => assertTransportLive(),}, machineHomePath);+ gui = guiSession();+ if (spec.guiRequired && gui !== true) throw new Refused('RUNNER_GUI_SESSION_REQUIRED', 'log in to a GUI session on this runner or keep GUI-marked files local');const canonicalMachineHome = machineHomePath;tracker = createDescendantTracker(runDirectory, {tick: reportCleanupTimeout, timedOut: () => cleanupTimedOut,@@ -879,7 +884,7 @@ async function main() {}if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); process.exitCode = 1; stopReading(); return; }cleanupStage = 'result receipt';- await receipt(spec, final, sink);+ await receipt(spec, { ...final, gui }, sink);clearTimeout(cleanupTimer);process.exitCode = 0;stopReading();diff --git a/src/runners.js b/src/runners.jsindex 728c526a..4f064451 100644--- a/src/runners.js+++ b/src/runners.js@@ -52,6 +52,7 @@ import {untracked,} from './git.js';import { Refused } from './refused.js';+import { recordRunnerGui } from './resources.js';import {gateStages,readStages,@@ -68,7 +69,7 @@ const MAX_BLOB_BYTES = 8 * 1024 ** 2;const MAX_HISTORY_TAGS = 1_024;const MAX_TAG_CHAIN = 8;const TOOL_ROOT = fileURLToPath(new URL('../', import.meta.url));-const RUNTIME_NAMES = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js'];+const RUNTIME_NAMES = ['runner-custody.js', 'resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js', 'sandbox-denial.js', 'gate-stages.js', 'child-journal-preload.js', 'execution-environment.js', 'gui-session.js'];/** Validate an SSH destination as one argument, never a command or an SSH option. */export function validateRunner(value) {@@ -77,13 +78,14 @@ export function validateRunner(value) {|| !Number.isSafeInteger(value.browser) || value.browser < 0 || value.browser > value.slots) {throw new Refused('BAD_RUNNER', 'use an SSH host or alias, positive --slots, and --browser from zero through slots');}+ if (value.gui !== undefined && value.gui !== null && typeof value.gui !== 'boolean') throw new Refused('BAD_RUNNER', 'runner gui must be true, false, or unknown');for (const key of ['node', 'root']) {if (value[key] !== undefined && (typeof value[key] !== 'string' || /[\u0000-\u001f\u007f]/u.test(value[key])|| !(value[key].startsWith('/') && value[key].length > 1 || key === 'node' && value[key] === 'node'))) {throw new Refused('BAD_RUNNER', `runner ${key} must be an absolute remote path${key === 'node' ? ' or node' : ''}`);}}- return { host: value.host, slots: value.slots, browser: value.browser,+ return { host: value.host, slots: value.slots, browser: value.browser, ...(value.gui !== undefined ? { gui: value.gui } : {}),...(value.node ? { node: value.node } : {}), ...(value.root ? { root: value.root } : {}) };}@@ -490,7 +492,7 @@ function requestFor(root, command, { runner, source, browser = false, byLaunch,const projection = metadata.landing === true && Array.isArray(waivers) ? waivers.filter(entry => ['file', 'name'].includes(entry?.kind) && typeof entry.test === 'string' && entry.test).map(({ kind, test }) => ({ kind, test })) : [];if (secretsIn([{ path: 'runner continuation', line: 1, text: JSON.stringify(projection) }]).length) throw new Refused('RUNNER_SECRET', 'the continuation projection contains a possible secret; keep this run local');const spec = { version: 1, id: randomUUID(), repoId, ...(originBase ? { origin, originBase } : {}), runtime, tooling, tags, ...current, command, pipefail, slots: runner.slots,- browser: runner.browser, browserRequired: browser, landing: metadata.landing === true,+ browser: runner.browser, browserRequired: browser, guiRequired: metadata.gui === true, landing: metadata.landing === true,...(metadata.landing === true && metadata.timeoutMs ? { timeoutMs: metadata.timeoutMs } : {}),// The classification this controller used, so the runner never reclassifies by its own settings (#1043).browserByLaunch: byLaunch ?? carriedBrowserByLaunch() ?? readMachineSettingsFile()?.gate?.browserByLaunch === true,@@ -529,6 +531,15 @@ function resultFrom(request, result) {|| receipt.outputSha256 !== createHash('sha256').update(output).digest('hex')) {throw new RunnerDropped(request.runner.host);}+ if (receipt.gui !== undefined && ![true, false, null].includes(receipt.gui)) throw new RunnerDropped(request.runner.host);+ // This field is bound to this exact request and output digest, never read from command text.+ recordRunnerGui(request.runner.host, receipt.gui ?? null);+ if (receipt.refused === 'RUNNER_GUI_SESSION_REQUIRED') {+ if (!request.spec.guiRequired || receipt.gui === true || receipt.code === 0) throw new RunnerDropped(request.runner.host);+ const refused = new Refused('RUNNER_GUI_SESSION_REQUIRED', `runner ${request.runner.host} has no confirmed GUI session at job start; rerun this GUI-marked file locally or register a logged-in GUI runner`);+ refused.runnerAttempt = { host: request.runner.host, exitCode: receipt.code, output: output.toString('utf8'), gui: receipt.gui ?? null };+ throw refused;+ }if (receipt.timedOut !== undefined && (receipt.timedOut !== true || !request.spec.timeoutMs || receipt.code === 0)) throw new RunnerDropped(request.runner.host);if (receipt.refused !== undefined) {if (typeof receipt.refused !== 'string' || !/^[A-Z][A-Z0-9_]{0,63}$/u.test(receipt.refused) || receipt.code === 0) throw new RunnerDropped(request.runner.host);@@ -560,7 +571,7 @@ function resultFrom(request, result) {throw refused;}return { isGreen: receipt.code === 0 && !receipt.signal, output: text, sandboxBlocked, ...(receipt.timedOut ? { timedOut: true } : {}),- environment: receipt.environment ?? null,+ environment: receipt.environment ?? null, executionCapabilities: { gui: receipt.gui ?? null },...(request.spec.stageMarker ? { stages: staged?.stages ?? null } : {}),seconds: Math.round(receipt.wallMs / 1000), exitCode: receipt.code,executionRunner: request.runner.host, executionRoot: receipt.root, remoteWallMs: receipt.wallMs,diff --git a/test/chrome-fixture.test.js b/test/chrome-fixture.test.jsindex 579dc1d4..f4976867 100644--- a/test/chrome-fixture.test.js+++ b/test/chrome-fixture.test.js@@ -1,3 +1,4 @@+/** @pullboard-test-gui *//** The shared Chrome fixture bounds startup and removes profiles only after the owned process group exits [C7]. */import assert from 'node:assert/strict';import { once } from 'node:events';diff --git a/test/gui-admission.test.js b/test/gui-admission.test.jsnew file mode 100644index 00000000..126aac15--- /dev/null+++ b/test/gui-admission.test.js@@ -0,0 +1,32 @@+/** GUI requirements are explicit file metadata and fresh execution-user domain observations [C7,V4]. */+import assert from 'node:assert/strict';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { test } from 'node:test';+import { testsNeedGui } from '../src/gui-admission.js';+import { guiSession } from '../src/gui-session.js';++test('GUI admission reads an explicit file marker rather than Chrome headless arguments [C7,V4]', t => {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-gui-marker-'));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ writeFileSync(join(root, 'native.test.js'), '/** @pullboard-test-gui */\nconst flags = ["--headless=new"];');+ writeFileSync(join(root, 'ordinary.test.js'), 'const flags = ["--headless=new"];');+ assert.equal(testsNeedGui(root, ['native.test.js']), true);+ assert.equal(testsNeedGui(root, ['ordinary.test.js']), false);+ assert.equal(testsNeedGui(root, ['missing.test.js']), false);+});++test('GUI-domain observations distinguish confirmed presence, known absence, and unknown [C7,V4]', () => {+ const calls = [];+ const present = guiSession({ platform: 'darwin', getuid: () => 501, run: (...args) => { calls.push(args); return { status: 0, signal: null }; } });+ assert.equal(present, true);+ assert.deepEqual(calls[0].slice(0, 2), ['/bin/launchctl', ['print', 'gui/501']]);+ assert.equal(calls[0][2].timeout, 1000);+ assert.equal(guiSession({ platform: 'darwin', getuid: () => 501, run: () => ({ status: 113, stderr: 'Could not find domain for\n' }) }), false);+ assert.equal(guiSession({ platform: 'darwin', getuid: () => 501, run: () => ({ status: 125, stderr: 'Could not print domain: 125: Domain does not support specified action\n' }) }), null);+ assert.equal(guiSession({ platform: 'darwin', getuid: () => 501, run: () => ({ status: 0, error: new Error('timeout') }) }), null);+ assert.equal(guiSession({ platform: 'darwin', getuid: () => 501, run: () => ({ status: null, signal: 'SIGKILL' }) }), null);+ assert.equal(guiSession({ platform: 'darwin', getuid: () => -1, run: () => { throw new Error('must not run'); } }), null);+ assert.equal(guiSession({ platform: 'linux', run: () => { throw new Error('must not run'); } }), null);+});diff --git a/test/landing-shards.test.js b/test/landing-shards.test.jsindex e28835fb..1d964d36 100644--- a/test/landing-shards.test.js+++ b/test/landing-shards.test.js@@ -59,6 +59,36 @@ process.stdout.write(JSON.stringify({ green: result.isGreen, calls }));`;assert.equal(measured.calls[0].gui, true, 'the selected runner carries its explicit GUI capability');});+test('a GUI-marked shard waits for a local slot when runner GUI capability is unknown [C7,V4]', t => {+ const box = fixture({ runner: true });+ t.after(() => rmSync(box.dir, { recursive: true, force: true }));+ const script = `import { withGateSlot } from ${JSON.stringify(pathToFileURL(join(SOURCE, 'src/gate.js')).href)};+import { runLandingShards } from ${JSON.stringify(pathToFileURL(join(SOURCE, 'src/landing-shards.js')).href)};+const root = ${JSON.stringify(box.repo)};+let release;+let entered;+const ready = new Promise(resolve => { entered = resolve; });+const freed = new Promise(resolve => { release = resolve; });+const result = await withGateSlot(root, async () => {+ const held = withGateSlot(root, async () => { entered(); await freed; }, { remote: false });+ await ready;+ const timer = setTimeout(release, 250);+ try {+ return await runLandingShards({ root, runner: ${JSON.stringify(join(box.repo, 'bin/run-tests.js'))},+ files: ['./test/a.test.js'], count: 1, needsBrowser: async () => false, needsGui: async () => true,+ remoteRun: async () => { throw new Error('an unknown GUI runner must not execute this shard'); }, write: () => {} });+ } finally { clearTimeout(timer); release(); await held; }+}, { remote: false });+process.stdout.write(JSON.stringify(result));`;+ const env = { ...box.env };+ delete env.NODE_TEST_CONTEXT;+ const result = runFixtureChild(process.execPath, ['--input-type=module', '-e', script], { cwd: box.repo, env, encoding: 'utf8' });+ assert.equal(result.status, 0, result.context);+ const measured = JSON.parse(result.stdout);+ assert.equal(measured.isGreen, true);+ assert.equal(measured.shards[0].attempts[0].host, 'local');+});+test('six shards land on six different runners [C7,V4]', (t) => {const box = fixture({ runner: false });t.after(() => rmSync(box.dir, { recursive: true, force: true }));