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(cli): submit frozen checks and affected tests [V4,V16]
Corey Olson006f646e8e7c
diff --git a/src/affected-tests.js b/src/affected-tests.jsnew file mode 100644index 00000000..3baec9f1--- /dev/null+++ b/src/affected-tests.js@@ -0,0 +1,119 @@+/** Select committed Node test files through import edges; uncertainty requires the full gate [V4,C7]. */+import { spawnSync } from 'node:child_process';+import { posix } from 'node:path';+import { cleanGitEnvironment } from './git.js';+import { importsIn } from './module-imports.js';++const MODULE = /\.[cm]?js$/u;+const TEST = /\.(?:test|spec)\.[cm]?js$/u;+const GLOBAL = new Set(['bin/run-tests.js', 'package.json', 'package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'src/gate.js', 'src/cli.js', 'src/hooks.js', 'src/trusted-policy.js', 'src/affected-tests.js', 'src/module-imports.js']);++/** Read exact objects from this checkout, ignoring ambient Git selectors and replacement refs. */+function selectionGit(root, args) {+ const result = spawnSync('git', ['--no-replace-objects', '-c', 'core.quotepath=false', ...args], {+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 128 * 1024 * 1024,+ });+ if (result.status !== 0) throw new Error('the committed import graph could not be read');+ return result.stdout;+}++/** Read all committed module blobs in one Git batch, preserving exact names and source bytes. */+function modulesAt(root, commit) {+ const tracked = selectionGit(root, ['ls-tree', '-r', '-z', commit]).split('\0').filter(Boolean).map(record => {+ const tab = record.indexOf('\t');+ const [mode, type, hash] = record.slice(0, tab).split(' ');+ return { mode, type, hash, path: record.slice(tab + 1) };+ });+ const entries = tracked.filter(entry => MODULE.test(entry.path));+ // V8 compiles a require() expression as ESM too, but cannot supply its CommonJS edges.+ if (entries.some(entry => entry.path.endsWith('.js'))) {+ const policy = JSON.parse(selectionGit(root, ['show', `${commit}:package.json`]));+ if (policy.type !== 'module' || tracked.some(entry => entry.path.endsWith('/package.json'))) {+ throw new Error('CommonJS or nested package scopes cannot supply a complete ES-module import graph');+ }+ }+ if (entries.some(entry => entry.type !== 'blob' || entry.mode === '120000' || entry.path.endsWith('.cjs'))) {+ throw new Error('a tracked module uses an unsupported file mode or CommonJS');+ }+ if (!entries.length) return new Map();+ const hashes = [...new Set(entries.map(entry => entry.hash))];+ const result = spawnSync('git', ['--no-replace-objects', 'cat-file', '--batch'], {+ cwd: root, env: cleanGitEnvironment(), input: hashes.join('\n') + '\n', maxBuffer: 128 * 1024 * 1024,+ });+ if (result.status !== 0) throw new Error('committed module blobs could not be read');+ const sources = new Map();+ let at = 0;+ for (const hash of hashes) {+ const end = result.stdout.indexOf(10, at);+ const [actual, type, count] = result.stdout.subarray(at, end).toString().split(' ');+ const size = Number(count);+ if (actual !== hash || type !== 'blob' || !Number.isSafeInteger(size) || size < 0) throw new Error('committed module batch is incomplete');+ at = end + 1;+ sources.set(hash, result.stdout.subarray(at, at + size).toString('utf8'));+ at += size + 1;+ }+ return new Map(entries.map(entry => [entry.path, sources.get(entry.hash)]));+}++/** Compile import edges for one tree; computed imports stay attached to their importing file. */+function graphAt(root, commit) {+ const modules = modulesAt(root, commit);+ const paths = [...modules.keys()];+ const imports = importsIn([...modules.values()]);+ const reverse = new Map();+ const unknown = new Map();+ paths.forEach((path, index) => {+ for (const target of imports[index]) {+ if (target === 'node:module') { unknown.set(path, 'a reached module may create CommonJS imports'); continue; }+ if (target.startsWith('node:')) continue;+ if (!target.startsWith('.')) {+ unknown.set(path, target === '(computed)' ? 'non-literal dynamic import' : 'unresolved package import');+ continue;+ }+ const dependency = posix.normalize(posix.join(posix.dirname(path), target.split(/[?#]/u)[0]));+ if (dependency.startsWith('../')) { unknown.set(path, 'import outside the repository'); continue; }+ if (!reverse.has(dependency)) reverse.set(dependency, new Set());+ reverse.get(dependency).add(path);+ }+ });+ return { paths, reverse, unknown };+}++/**+ * Select changed tests and every transitive importer in the old and new trees. Old edges cover+ * deletions and renames; process launches and filesystem reads are deliberately not import edges.+ *+ * @param {string} root+ * @param {{base:string, commit?:string, changed?:string[]}} options+ * @returns {{full:boolean, reason:string, files:string[]}}+ */+export function selectAffectedTests(root, { base, commit = 'HEAD', changed }) {+ let files = [];+ try {+ changed ??= selectionGit(root, ['diff', '--no-renames', '--name-only', '-z', base, commit]).split('\0').filter(Boolean);+ const after = graphAt(root, commit);+ files = after.paths.filter(path => TEST.test(path)).sort();+ const fallback = changed.find(path => GLOBAL.has(path) || path.startsWith('.githooks/'));+ if (fallback) return { full: true, reason: `${fallback} controls the gate or dependency selection`, files };+ if (!files.length) return { full: true, reason: 'no committed Node test files can be selected', files };+ const unsupported = changed.find(path => !MODULE.test(path));+ if (unsupported) return { full: true, reason: `import selection cannot compute the effect of ${unsupported}`, files };+ const before = graphAt(root, base);+ const reached = new Set(changed);+ const queue = [...changed];+ for (let at = 0; at < queue.length; at += 1) {+ const path = queue[at];+ for (const graph of [before, after]) {+ if (graph.unknown.has(path)) return { full: true, reason: `${graph.unknown.get(path)} in reached file ${path}`, files };+ for (const importer of graph.reverse.get(path) ?? []) {+ if (!reached.has(importer)) { reached.add(importer); queue.push(importer); }+ }+ }+ }+ const selected = files.filter(path => reached.has(path));+ if (selected.length === files.length) return { full: true, reason: 'the change reaches every test file', files };+ return { full: false, reason: '', files: selected };+ } catch (error) {+ return { full: true, reason: `import selection could not be computed: ${error.message}`, files };+ }+}diff --git a/src/cli.js b/src/cli.jsindex c0d16e39..7d52afb7 100644--- a/src/cli.js+++ b/src/cli.js@@ -14,7 +14,7 @@ import { doctrineHistory, loadDoctrine } from './doctrine.js';import { agentSessionDigest, requirePersonChannel } from './person.js';import { bindLocalSession } from './agent-session.js';import { decisionProjection, planRowApply, prepareRowDecisions, restoreRowApply, writeRowApply } from './row-decisions.js';-import { digestOf, gateReport, runGate, runShell, withGateSlot } from './gate.js';+import { digestOf, gateReport, runGate, runShell, runSubmitGate, submitGateReport, withGateSlot } from './gate.js';import { bareWorktreeFinding, contains, differFromHead, git, headCommit, headTree, isClean, mainCheckout, repoInfo, resolveCommit, tryGit, untracked } from './git.js';import {FIX_NOTE,@@ -129,7 +129,7 @@ Workthe command and its author print first; the project gate is pullboard gatepullboard claim <id> take or renew a lease; the first claim freezes the criterionpullboard release <id> hand it back- pullboard submit <id> needs a clean tree and the gate green at HEAD (alias: done)+ pullboard submit <id> needs a clean tree, item check and affected tests green at HEAD (alias: done)pullboard verify <id> accept --note "what you broke or which edge you tried, and what happened"pullboard verify <id> reject --reason TEST_FAILURE --note "what failed"any --note can be --note-file <file>, which keeps quotes, $ and backticks intact@@ -862,7 +862,7 @@ function dirtyFiles(root) {function filesSince(root, id, from, to) {if (!from) return [];const others = [`--exclude=refs/pullboard/items/${id}/*`, '--glob=refs/pullboard/items/*'];- const result = tryGit(root, ['log', '--first-parent', '--no-merges', '--format=', '--name-only', to, '--not', from, ...others]);+ const result = tryGit(root, ['log', '--first-parent', '--no-merges', '--no-renames', '--format=', '--name-only', to, '--not', from, ...others]);return result.status === 0 ? [...new Set(result.stdout.split('\n').filter(Boolean))].sort() : [];}@@ -1548,11 +1548,10 @@ async function submitHere(ctx, id) {const commit = headCommit(root);if (!commit) throw new Refused('NO_COMMIT', 'nothing committed yet');requireTrunkMerge(root, commit);- // Submit runs the gate itself, every time: a stamp from an earlier run is a file any agent can- // write, so it never stands in for this run (V16). It starts on the commit submitted, and must end- // on it too. What the gate's own code does in between is the submitted tree's, under review.- const gate = await runGate(root, ctx.config, { trustStamp: false, onWait: gateWaitReporter(ctx.io) });- if (!gate.isGreen) throw new Refused('GATE_RED', `the gate is red at ${commit.slice(0, 12)}; fix it, commit, submit again. ${gateReport(gate)}`);+ // Every submit proves its frozen check and reachable tests anew on this exact commit (V4,V16).+ // A full-gate stamp never substitutes for either proof; only an actual full fallback may stamp.+ const gate = await runSubmitGate(root, ctx.config, { base: claimHead, changed: filesSince(root, id, claimHead, commit), check: frozenCheck(held), onWait: gateWaitReporter(ctx.io) });+ if (!gate.isGreen) throw new Refused('GATE_RED', `the submission proof is red at ${commit.slice(0, 12)}; fix it, commit, submit again. ${submitGateReport(gate)}`);if (headCommit(root) !== commit || !isClean(root)) {throw new Refused('MOVED_DURING_GATE',@@ -1561,7 +1560,7 @@ async function submitHere(ctx, id) {}requireTrunkMerge(root, commit); // The trunk may have moved while the gate ran.await withBoard(ctx, async (board) => await ordered(ctx, board, 'submit', [id, { agentId: me.id, commit, tree: headTree(root) ?? '', files: filesSince(root, id, claimHead, commit), policyCommit: acceptedMain.commit }]));- return reportSubmission(ctx, id, commit, { green: gate.isGreen, report: gateReport(gate) });+ return reportSubmission(ctx, id, commit, { green: gate.isGreen, report: submitGateReport(gate), files: gate.files, full: gate.full, reason: gate.reason, check: gate.check });}/** Report and pin the original submitted commit, including a recovered acknowledged outcome. */diff --git a/src/gate.js b/src/gate.jsindex ff91eccb..1abea688 100644--- a/src/gate.js+++ b/src/gate.js@@ -10,6 +10,8 @@ import { gitChildEnv, gitPath, headTree, isClean, untracked } from './git.js';import { Refused } from './refused.js';import { takeResource } from './resources.js';import { loadMachineSettings } from './settings.js';+import { selectAffectedTests } from './affected-tests.js';+import { join } from 'node:path';const STAMP = 'pullboard-gate-green';const LOG = 'pullboard-gate.log';@@ -133,8 +135,8 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =* streams in order, is kept whole in the git dir and returned for a digest.** A passed tree is marked by a stamp file in the git dir, which any agent can write. So the stamp- * only saves a run where nothing is proven by it, such as pre-push (C3); submit needs a run of its- * own and passes `trustStamp: false` (V16).+ * only saves a run where nothing is proven by it, such as pre-push (C3). A submission that falls+ * back to the full gate always runs it afresh (V16).** @param {string} root* @param {any} config@@ -146,17 +148,64 @@ export async function runGate(root, config, { trustStamp = true, onWait, landingthrow new Refused('NO_GATE', 'no gate configured; set "gate" in pullboard.json, e.g. "npm test"');}if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };+ return await withGateSlot(root, () => fullGateRun(root, config, trustStamp), { landing, onWait });+}++/** Run a full gate while its caller owns the queue lease; only a full run may stamp its tree. */+function fullGateRun(root, config, trustStamp = false) {+ if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };+ const before = committedTree(root);+ const { isGreen, output, seconds } = runShell(root, config.gate);+ const log = gitPath(root, LOG);+ writeFileSync(log, output);+ if (isGreen && before !== null && committedTree(root) === before) writeFileSync(gitPath(root, STAMP), `${before}\n`);+ return { isGreen, isCached: false, output, seconds, log };+}++/** Quote a fixed executable or selected path without permitting shell expansion. */+function commandWord(value) {+ return `'${String(value).replaceAll("'", "'\\''")}'`;+}++/**+ * Prove the frozen item check and selected imports under one lease. Subsets neither read nor write+ * the full-gate stamp. An uncertain selection runs the full configured gate and records its reason.+ *+ * @param {string} root+ * @param {any} config+ * @param {{base:string, changed:string[], check:string, onWait?:(state:object)=>void}} options+ * @returns {Promise<any>}+ */+export async function runSubmitGate(root, config, { base, changed, check, onWait }) {+ if (!config.gate.trim()) throw new Refused('NO_GATE', 'no gate configured; set "gate" in pullboard.json, e.g. "npm test"');+ const selection = selectAffectedTests(root, { base, changed });return await withGateSlot(root, () => {- if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };- const before = committedTree(root);- const { isGreen, output, seconds } = runShell(root, config.gate);- const log = gitPath(root, LOG);- writeFileSync(log, output);- if (isGreen && before !== null && committedTree(root) === before) {- writeFileSync(gitPath(root, STAMP), `${before}\n`);+ const criterion = check ? runShell(root, check) : { isGreen: true, output: '', seconds: 0 };+ const receipt = { command: check, green: criterion.isGreen, seconds: criterion.seconds, checked: Boolean(check) };+ const log = gitPath(root, 'pullboard-submit.log');+ if (!criterion.isGreen) {+ writeFileSync(log, criterion.output);+ return { isGreen: false, isCached: false, output: criterion.output, seconds: criterion.seconds, log, ...selection, check: receipt };}- return { isGreen, isCached: false, output, seconds, log };- }, { landing, onWait });+ let proof;+ if (selection.full) proof = fullGateRun(root, config);+ else if (!selection.files.length) proof = { isGreen: true, output: '', seconds: 0, isCached: false, log };+ else {+ const runner = existsSync(join(root, 'bin/run-tests.js')) ? [process.execPath, 'bin/run-tests.js'] : [process.execPath, '--test'];+ const command = [...runner, ...selection.files.map(path => './' + path)].map(commandWord).join(' ');+ proof = { ...runShell(root, command), isCached: false, log };+ }+ writeFileSync(log, `item check:\n${criterion.output}\n${selection.full ? 'full gate' : 'affected tests'}:\n${proof.output}`);+ return { ...proof, log, seconds: criterion.seconds + proof.seconds, ...selection, check: receipt };+ }, { onWait });+}++/** Describe precisely which submission proof ran, including absent checks and full fallbacks. */+export function submitGateReport(gate) {+ const check = gate.check.checked ? `item check ${gate.check.green ? 'green' : 'red'} in ${gate.check.seconds}s` : 'no item check';+ const selection = gate.full ? `full gate: ${gate.reason}` : `affected tests: ${gate.files.length ? gate.files.join(', ') : 'none'}`;+ const result = gate.isGreen && !gate.full ? `affected tests green in ${gate.seconds}s` : gateReport(gate);+ return `${check}; ${selection}; ${result}`;}/**diff --git a/src/module-imports.js b/src/module-imports.jsnew file mode 100644index 00000000..955f4864--- /dev/null+++ b/src/module-imports.js@@ -0,0 +1,112 @@+/** Parse import edges without evaluating repository code, using V8 rather than a JavaScript grammar guess [V4,C7]. */+import { spawnSync } from 'node:child_process';++/**+ * A child Node that compiles each source on its stdin as an ES module and reports, for each, whether+ * it compiles and the modules it imports statically, as V8 lists them.+ */+const PARSER = [+ "import vm from 'node:vm';",+ "import { readFileSync } from 'node:fs';",+ "const sources = JSON.parse(readFileSync(0, 'utf8'));",+ '/** Compile one source without executing repository code. */',+ 'const look = (source) => {',+ ' try {',+ ' const module = new vm.SourceTextModule(source);',+ ' return { compiles: true, imports: module.moduleRequests ? module.moduleRequests.map((request) => request.specifier) : module.dependencySpecifiers };',+ ' } catch {',+ ' return { compiles: false, imports: [] };',+ ' }',+ '};',+ 'process.stdout.write(JSON.stringify(sources.map(look)));',+].join('\n');++/**+ * What V8 makes of each source, all in one child process.+ *+ * @param {string[]} sources+ * @returns {{ compiles: boolean, imports: string[] }[]}+ */+function look(sources) {+ const child = spawnSync(process.execPath, ['--experimental-vm-modules', '--disable-warning=ExperimentalWarning', '--input-type=module', '-e', PARSER], {+ input: JSON.stringify(sources),+ encoding: 'utf8',+ maxBuffer: 2 ** 26,+ });+ if (child.status !== 0) throw new Error('V8 import parser failed: ' + (child.error?.message ?? child.stderr));+ return JSON.parse(child.stdout);+}++/** Every place the whole word import appears, in code or not; Unicode letters count as part of a word. */+const IMPORT = /(?<![\p{ID_Continue}$\u200c\u200d#])import(?![\p{ID_Continue}$\u200c\u200d])/gu;++/** Whitespace and comments, which may sit between import, its parenthesis and its argument. A line comment ends at any line terminator. */+const GAP = /^(?:\s|\/\/[^\n\r\u2028\u2029]*|\/\*[\s\S]*?\*\/)*/;++/** What a dynamic import of anything but a plain string loads: unknown, so never node: or relative. */+const COMPUTED = '(computed)';++/**+ * The text from `at` on, past whitespace and comments.+ *+ * @param {string} source+ * @param {number} at+ * @returns {string}+ */+function pastGap(source, at) {+ const rest = source.slice(at);+ return rest.slice(GAP.exec(rest)[0].length);+}++/**+ * What an import(...) call at `at` loads: its argument when that is one plain string, decoded, or+ * COMPUTED for anything else, a string whose escapes do not decode included. Only called on words+ * V8 has confirmed are import calls in code.+ *+ * @param {string} source+ * @param {number} at+ * @returns {string}+ */+function dynamicAt(source, at) {+ const argument = pastGap(pastGap(source, at + 'import'.length), 1);+ const literal = /^(['"])(?:\\[\s\S]|(?!\1)[^\\\n\r])*\1/.exec(argument);+ if (!literal) return COMPUTED;+ const after = pastGap(argument, literal[0].length)[0];+ if (after !== ')' && after !== ',') return COMPUTED;+ try {+ return new Function(`return ${literal[0]};`)();+ } catch {+ return COMPUTED;+ }+}++/**+ * Every module each source imports. V8 lists the static ones: import and export-from statements and+ * side-effect imports. For each import followed by a parenthesis, V8 also decides two things: a NUL+ * put before the word breaks the module only when the word is code, not text in a string, template,+ * comment or regular expression; and putting 1 in its place still compiles only when the word is a+ * call, not a property name after a dot. Only then is the argument read, and an argument that is not+ * one plain string is reported as COMPUTED, which no rule allows. A method named import, in a class+ * or object, still reads as a call: the scan errs toward a false alarm, never a miss.+ *+ * @param {string[]} sources - Each one a module that compiles.+ * @returns {string[][]}+ */+export function importsIn(sources) {+ const calls = sources.map((source) => [...source.matchAll(IMPORT)].map((match) => match.index).filter((at) => pastGap(source, at + 'import'.length)[0] === '('));+ const variants = sources.flatMap((source, index) =>+ calls[index].flatMap((at) => [`${source.slice(0, at)}\u0000${source.slice(at)}`, `${source.slice(0, at)}1${source.slice(at + 'import'.length)}`]),+ );+ const looks = look([...sources, ...variants]);+ let next = sources.length;+ return sources.map((source, index) => {+ if (!looks[index].compiles) throw new Error('source does not compile as an ES module');+ const dynamic = calls[index].filter(() => {+ const isCode = !looks[next].compiles;+ const isCall = looks[next + 1].compiles;+ next += 2;+ return isCode && isCall;+ });+ return [...looks[index].imports, ...dynamic.map((at) => dynamicAt(source, at))];+ });+}diff --git a/test/e2e.test.js b/test/e2e.test.jsindex 1326e10d..17e14b6f 100644--- a/test/e2e.test.js+++ b/test/e2e.test.js@@ -362,7 +362,7 @@ test('submit needs a clean tree, nothing untracked, and the gate green at HEAD [rmSync(join(box.web, 'web', 'stray.txt'));const submitted = box.run(box.web, 'submit', '1');assert.equal(submitted.code, 0, submitted.err);- assert.match(submitted.out, /submitted #1 at [0-9a-f]{12}; gate green/);+ assert.match(submitted.out, /submitted #1 at [0-9a-f]{12}; no item check; full gate: no committed Node test files can be selected; gate green in \d+s/);const head = box.git(box.web, 'rev-parse', 'HEAD');assert.equal(box.git(box.repo, 'rev-parse', `refs/pullboard/items/1/${head.slice(0, 12)}`), head, 'submit pins the commit');});@@ -1912,7 +1912,15 @@ function attackCommit(box, cwd) {return commit;}-/** Submit a fixture whose private check reads an ignored dependency folder. */+/** Seed a legacy receipt from the old full-gate-only submit rule, for independent verifier audits. */+function historicalCheckSubmission(box, commit) {+ box.git(box.web, 'update-ref', `refs/pullboard/items/1/${commit.slice(0, 12)}`, commit);+ const board = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));+ try { store.submit(board, 1, { agentId: 'web-1', commit, tree: box.git(box.web, 'rev-parse', `${commit}^{tree}`) }); }+ finally { store.closeBoard(board); }+}++/** Retain historical submissions whose private check needs an install, fails, or times out. */function privateCheckSubmission({ install = '', timeout = '5m', check }) {const box = project('true');const config = JSON.parse(readFileSync(join(box.repo, 'pullboard.json'), 'utf8'));@@ -1927,7 +1935,7 @@ function privateCheckSubmission({ install = '', timeout = '5m', check }) {writeFileSync(join(box.web, 'web/.gitignore'), '.deps/\n');writeFileSync(join(box.web, 'web/index.html'), 'fixture');const commit = attackCommit(box, box.web);- assert.equal(box.run(box.web, 'submit', '1').code, 0);+ historicalCheckSubmission(box, commit);const review = join(box.dir, 'private-check-review');box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);assert.equal(box.run(review, 'join', 'api').code, 0);@@ -2233,7 +2241,10 @@ test('accept reruns the frozen check at the submission even when the reviewer remkdirSync(join(box.web, 'web'));writeFileSync(join(box.web, 'web/RED_CHECK'), 'red');const commit = attackCommit(box, box.web);- assert.equal(box.run(box.web, 'submit', '1').code, 0, 'the project gate passes while the separate item check is red');+ const blocked = box.run(box.web, 'submit', '1');+ assert.equal(blocked.code, 1, 'current submit refuses the red frozen check even when the project gate passes');+ assert.match(blocked.err, /GATE_RED/);+ historicalCheckSubmission(box, commit); // Legacy receipts must still be independently checked.const review = join(box.dir, 'exact-review');box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);assert.equal(box.run(review, 'join', 'api').code, 0);diff --git a/test/submit-gate.test.js b/test/submit-gate.test.jsnew file mode 100644index 00000000..77c260f9--- /dev/null+++ b/test/submit-gate.test.js@@ -0,0 +1,276 @@+/**+ * Submit proves its frozen item check and the import closure its change can reach; only a full+ * selection can stand in for the project gate, which still runs at landing [V4,C7,V16].+ */+import assert from 'node:assert/strict';+import { execFileSync, spawnSync } from 'node:child_process';+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { after, test } from 'node:test';+import { selectAffectedTests } from '../src/affected-tests.js';++const BIN = resolveBin();+const dirs = [];+const SPEC = '# Submit proof fixture\n\n## G · Goals\n- G1 [approved, must] The selected test proves the change. | gate: test\n';++after(() => {+ for (const dir of dirs) rmSync(dir, { recursive: true, force: true });+});++/** Resolve the real CLI relative to this test without importing any project dependencies. */+function resolveBin() {+ return join(import.meta.dirname, '../bin/pullboard.js');+}++/** Create a private Git repository with a deterministic identity and isolated Pullboard home. */+function privateRepo(t) {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-submit-gate-')));+ dirs.push(dir);+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const root = join(dir, 'repo');+ mkdirSync(root);+ const env = {+ ...process.env,+ GIT_CONFIG_GLOBAL: '/dev/null',+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Test Agent',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Test Agent',+ GIT_COMMITTER_EMAIL: '[email protected]',+ PULLBOARD_HOME: join(dir, 'home'),+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),+ };+ delete env.PULLBOARD_RELAY_TOKEN;+ delete env.NODE_TEST_CONTEXT;+ /** Run real Git in this fixture with only the fixture's configured identity. */+ const git = (...args) => execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: 'pipe' }).trim();+ /** Run the real local CLI, retaining JSON stdout and refusal stderr separately. */+ const run = (...args) => {+ const result = spawnSync(process.execPath, [BIN, ...args], { cwd: root, env, encoding: 'utf8', timeout: 90_000 });+ return { code: result.status, out: result.stdout ?? '', err: result.stderr ?? '' };+ };+ git('init', '-q', '-b', 'main');+ assert.equal(run('init').code, 0);+ mkdirSync(join(root, 'node_modules/.bin'), { recursive: true });+ symlinkSync(BIN, join(root, 'node_modules/.bin/pullboard'));+ appendFileSync(join(root, '.git/info/exclude'), '\nnode_modules/\n');+ put(root, 'SPEC.md', SPEC);+ put(root, 'package.json', '{"type":"module"}\n');+ return { dir, root, env, git, run };+}++/** Write a fixture file, creating its parent directory when needed. */+function put(root, path, text) {+ const file = join(root, path);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, text);+}++/** Commit the fixture state using a valid Pullboard message. */+function commitAll(box, message = 'chore: fixture state') {+ box.git('add', '-A');+ box.git('commit', '-q', '-m', message);+ return box.git('rev-parse', 'HEAD');+}++/** Seed a small import graph with three independently discoverable test files. */+function seedGraph(box) {+ put(box.root, 'src/a.js', 'export const value = 1;\n');+ put(box.root, 'src/middle.js', "export { value } from './a.js';\n");+ put(box.root, 'src/entry.js', "export const load = () => import('./middle.js');\n");+ put(box.root, 'src/other.js', 'export const other = true;\n');+ put(box.root, 'test/a.test.js', "import '../src/entry.js';\n");+ put(box.root, 'test/b.test.js', "import '../src/other.js';\n");+ put(box.root, 'test/c.test.js', "import assert from 'node:assert/strict';\nassert.ok(true);\n");+ return commitAll(box);+}++test('one source change selects its direct and transitive static, re-export and literal dynamic importers [V4,C7]', (t) => {+ const box = privateRepo(t);+ const base = seedGraph(box);+ put(box.root, 'src/a.js', 'export const value = 2;\n');+ const commit = commitAll(box, 'feat(core): update source [G1]');++ const selection = selectAffectedTests(box.root, { base, commit });+ assert.equal(selection.full, false);+ assert.deepEqual(selection.files, ['test/a.test.js']);+ assert.equal(selection.reason, '');+});++test('changed tests are selected and deleting or renaming a source retains importers of its old path [V4,C7]', (t) => {+ const box = privateRepo(t);+ const base = seedGraph(box);++ put(box.root, 'test/c.test.js', "import assert from 'node:assert/strict';\nassert.ok(true, 'changed test');\n");+ let commit = commitAll(box, 'test(core): update a test [G1]');+ let selection = selectAffectedTests(box.root, { base, commit });+ assert.deepEqual(selection.files, ['test/c.test.js'], 'a changed test includes itself');++ const renameBase = commit;+ box.git('mv', 'src/a.js', 'src/renamed.js');+ commit = commitAll(box, 'refactor(core): rename a source [G1]');+ selection = selectAffectedTests(box.root, { base: renameBase, commit });+ assert.equal(selection.full, false);+ assert.deepEqual(selection.files, ['test/a.test.js'], 'the old source path still reaches its importer');+});++test('unknown imports and broad inputs fall back explicitly, while an all-test closure is full [V4,C7]', (t) => {+ const box = privateRepo(t);+ const base = seedGraph(box);+ put(box.root, 'src/a.js', "export const load = name => import('./' + name + '.js');\n");+ const commit = commitAll(box, 'feat(core): add dynamic loading [G1]');+ const dynamic = selectAffectedTests(box.root, { base, commit });+ assert.equal(dynamic.full, true, 'a non-literal dynamic import fails closed');+ assert.match(dynamic.reason, /dynamic|compute|select/i);++ for (const path of ['bin/run-tests.js', 'package.json', 'package-lock.json', 'src/gate.js', 'src/affected-tests.js']) {+ const broad = selectAffectedTests(box.root, { base, commit, changed: [path] });+ assert.equal(broad.full, true, `${path} requires the full gate`);+ assert.ok(broad.reason, `${path} explains the fallback`);+ }++ put(box.root, 'src/a.js', 'export const value = 3;\n');+ put(box.root, 'test/b.test.js', "import '../src/a.js';\n");+ put(box.root, 'test/c.test.js', "import '../src/a.js';\n");+ const allTestsCommit = commitAll(box, 'test(core): cover shared source [G1]');+ const allTests = selectAffectedTests(box.root, { base, commit: allTestsCommit, changed: ['src/a.js'] });+ assert.equal(allTests.full, true, 'when every test is reached, the selection is the full gate');+ assert.deepEqual(allTests.files, ['test/a.test.js', 'test/b.test.js', 'test/c.test.js']);+});++test('submit runs the frozen check and affected test only; landing and explicit gate remain full [V4,C7,V16]', (t) => {+ const box = privateRepo(t);+ const checkCommand = 'node -e "require(\'node:fs\').appendFileSync(process.env.ITEM_CHECK_MARKER, \'check\')"';+ const checkMarker = join(box.dir, 'item-check.log');+ box.env.ITEM_CHECK_MARKER = checkMarker;+ put(box.root, 'pullboard.json', JSON.stringify({ gate: 'node --test', spec: 'SPEC.md', verify: 'any', lease: '2h' }, null, 2));+ put(box.root, 'SPEC.md', SPEC);+ put(box.root, 'src/a.js', 'export const value = 1;\n');+ put(box.root, 'test/a.test.js', [+ "import assert from 'node:assert/strict';",+ "import { appendFileSync } from 'node:fs';",+ "import { value } from '../src/a.js';",+ "appendFileSync(process.env.AFFECTED_MARKER, 'affected\\n');",+ "assert.equal(value, 2);",+ ].join('\n'));+ put(box.root, 'test/b.test.js', [+ "import assert from 'node:assert/strict';",+ "assert.fail('independent test must not block this submit');",+ ].join('\n'));+ commitAll(box);+ const added = box.run('add', 'coordinator', 'Source change', '--check', checkCommand);+ assert.equal(added.code, 0, added.err);+ assert.equal(box.run('claim', '1').code, 0);++ put(box.root, 'src/a.js', 'export const value = 2;\n');+ const commit = commitAll(box, 'feat(core): update selected source [G1]');+ const marker = join(box.dir, 'affected-ran.log');+ box.env.AFFECTED_MARKER = marker;+ rmSync(checkMarker, { force: true });+ const stamp = join(box.root, box.git('rev-parse', '--git-path', 'pullboard-gate-green'));+ writeFileSync(stamp, 'forged-stamp-must-not-change\n');++ const submitted = box.run('submit', '1', '--json');+ assert.equal(submitted.code, 0, submitted.err || submitted.out);+ const receipt = JSON.parse(submitted.out);+ assert.equal(receipt.id, 1);+ assert.equal(receipt.commit, commit);+ assert.equal(receipt.gate.green, true);+ assert.equal(receipt.gate.full, false);+ assert.deepEqual(receipt.gate.files, ['test/a.test.js']);+ assert.equal(receipt.gate.reason, '');+ assert.equal(receipt.gate.check.command, checkCommand);+ assert.equal(receipt.gate.check.green, true);+ assert.ok(existsSync(checkMarker), 'submit executes the item check rather than merely reporting it');+ assert.equal(readFileSync(checkMarker, 'utf8'), 'check', 'the frozen item check actually ran at submit');+ assert.ok(existsSync(marker), 'submit executes the selected test rather than merely reporting it');+ assert.equal(readFileSync(marker, 'utf8'), 'affected\n', 'submit really ran the selected test despite the full-gate stamp');+ assert.equal(readFileSync(stamp, 'utf8'), 'forged-stamp-must-not-change\n', 'subset proof never writes the full-gate stamp');++ rmSync(stamp);+ const explicit = box.run('gate');+ assert.notEqual(explicit.code, 0, 'the explicit configured full gate still sees the unrelated red test');+ assert.match(`${explicit.out}\n${explicit.err}`, /gate red/);+ const remote = join(box.dir, 'remote.git');+ box.git('init', '-q', '--bare', remote);+ box.git('remote', 'add', 'origin', remote);+ const landing = spawnSync('git', ['push', '-q', 'origin', 'main'], { cwd: box.root, env: box.env, encoding: 'utf8', timeout: 90_000 });+ assert.notEqual(landing.status, 0, 'the landing pre-push hook still runs the full gate');+ assert.match(`${landing.stdout ?? ''}\n${landing.stderr ?? ''}`, /gate is red|not ok 2/);+ assert.equal(existsSync(stamp), false, 'neither subset nor red full gate leaves a green full-gate stamp');+});++test('submit without a frozen check reports no item check and still runs affected tests [V4,C7,V16]', (t) => {+ const box = privateRepo(t);+ put(box.root, 'pullboard.json', JSON.stringify({ gate: 'node --test' }));+ put(box.root, 'src/a.js', 'export const value = 1;\n');+ put(box.root, 'test/a.test.js', "import '../src/a.js'; import { appendFileSync } from 'node:fs'; appendFileSync(process.env.AFFECTED_MARKER, 'ran');\n");+ put(box.root, 'test/b.test.js', "import assert from 'node:assert/strict'; assert.fail('unrelated');\n");+ commitAll(box);+ assert.equal(box.run('add', 'coordinator', 'No frozen command').code, 0);+ assert.equal(box.run('claim', '1').code, 0);+ put(box.root, 'src/a.js', 'export const value = 2;\n');+ commitAll(box, 'feat(core): update selected source [G1]');+ const marker = join(box.dir, 'without-check.log');+ box.env.AFFECTED_MARKER = marker;+ const result = box.run('submit', '1', '--json');+ assert.equal(result.code, 0, result.err);+ const receipt = JSON.parse(result.out);+ assert.match(receipt.gate.report, /no item check/u);+ assert.equal(receipt.gate.check.checked, false);+ assert.equal(receipt.gate.full, false);+ assert.deepEqual(receipt.gate.files, ['test/a.test.js']);+ assert.ok(existsSync(marker), 'the affected test ran without an item check');+ assert.equal(readFileSync(marker, 'utf8'), 'ran');+});++test('a red frozen item check refuses submit before affected tests run [V4,C7,V16]', (t) => {+ const box = privateRepo(t);+ put(box.root, 'pullboard.json', JSON.stringify({ gate: 'node --test' }));+ seedGraph(box);+ const added = box.run('add', 'coordinator', 'Frozen check', '--check', 'node -e "process.exit(process.env.CHECK_REFUSE ? 1 : 0)"');+ assert.equal(added.code, 0, added.err);+ assert.equal(box.run('claim', '1').code, 0);+ put(box.root, 'src/a.js', 'export const value = 2;\n');+ commitAll(box, 'feat(core): update selected source [G1]');+ box.env.CHECK_REFUSE = '1';+ const refused = box.run('submit', '1');+ assert.equal(refused.code, 1, refused.out);+ assert.match(refused.err, /GATE_RED/u);+ assert.match(refused.err, /item check red/u);+});+++test('CommonJS and nested package scopes fall back instead of silently missing require edges [V4,V16]', (t) => {+ const common = privateRepo(t);+ put(common.root, 'package.json', '{"type":"commonjs"}\n');+ put(common.root, 'src/a.js', 'module.exports = 1;\n');+ put(common.root, 'test/a.test.js', "require('../src/a.js');\n");+ put(common.root, 'test/b.test.js', "require('node:assert/strict').ok(true);\n");+ const base = commitAll(common);+ put(common.root, 'src/a.js', 'module.exports = 2;\n');+ const commit = commitAll(common, 'feat(core): change CommonJS source [G1]');+ const selection = selectAffectedTests(common.root, { base, commit });+ assert.equal(selection.full, true, 'require import edges cannot be silently omitted');+ assert.match(selection.reason, /CommonJS|package scope/u);++ const nested = privateRepo(t);+ seedGraph(nested);+ put(nested.root, 'legacy/package.json', '{"type":"commonjs"}\n');+ put(nested.root, 'legacy/value.js', 'module.exports = 1;\n');+ const nestedBase = commitAll(nested);+ put(nested.root, 'legacy/value.js', 'module.exports = 2;\n');+ const nestedCommit = commitAll(nested, 'feat(core): change nested CommonJS source [G1]');+ const scoped = selectAffectedTests(nested.root, { base: nestedBase, commit: nestedCommit });+ assert.equal(scoped.full, true, 'nested package policy makes a single ESM graph incomplete');+ assert.match(scoped.reason, /package scope/u);++ const esm = privateRepo(t);+ const esmBase = seedGraph(esm);+ put(esm.root, 'src/a.js', "import { createRequire } from 'node:module'; export const load = createRequire(import.meta.url);\n");+ const esmCommit = commitAll(esm, 'feat(core): create a CommonJS loader [G1]');+ const loader = selectAffectedTests(esm.root, { base: esmBase, commit: esmCommit });+ assert.equal(loader.full, true, 'a reached CommonJS loader also makes the ESM import graph incomplete');+ assert.match(loader.reason, /CommonJS/u);+});