Skip to content

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.

feat(cli): identify inherited main failures and reworks [V1]

Corey Olson2b9d6d7e4d96
diff --git a/src/board.js b/src/board.js
index 0480572d..f9a876c8 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1961,10 +1961,10 @@ function milestonePriorities(board) {
* and `shared` names them (N20). A held lane offers nothing new (N22).
*
* @param {any} board
- * @param {{ agentId: string, lane: string, verify?: boolean, policy?: string, familyPolicy?: string, runnable?: boolean, routes?: string[], warm?: string[] }} who
+ * @param {{ agentId: string, lane: string, verify?: boolean, policy?: string, familyPolicy?: string, runnable?: boolean, routes?: string[], warm?: string[], priority?: number[] }} who
* @returns {{ item: any | null, reasons: string[], shared?: string[] }}
*/
-export function nextFor(board, { agentId, lane, verify = false, policy = 'any', familyPolicy = 'off', runnable = false, routes = ROUTES, warm = [] }) {
+export function nextFor(board, { agentId, lane, verify = false, policy = 'any', familyPolicy = 'off', runnable = false, routes = ROUTES, warm = [], priority = [] }) {
const route = routeOf(board, agentId);
const tier = (entry) => ROUTES.indexOf(entry.item_route);
const allItems = listItems(board).reverse();
@@ -2005,12 +2005,24 @@ export function nextFor(board, { agentId, lane, verify = false, policy = 'any',
if (paused) return { item: null, reasons: [`${paused.hold_by} holds the ${lane} lane: ${paused.hold_reason}`, ...reasons] };
const milestonePriority = milestonePriorities(board);
const recent = new Set(warm);
+ const mainRed = new Set(priority);
const laneItems = items.filter((entry) => entry.item_status === 'open' && entry.item_lane === lane);
const mine = laneItems
.filter((entry) => !itemHold(board, entry.item_id))
.map((entry, order) => ({ entry, order, shared: itemFiles(entry).filter((path) => recent.has(path)) }))
.sort((first, second) => milestonePriority(first.entry) - milestonePriority(second.entry)
- || tier(second.entry) - tier(first.entry) || second.shared.length - first.shared.length || first.order - second.order);
+ || tier(second.entry) - tier(first.entry)
+ || second.shared.length - first.shared.length || first.order - second.order);
+ // Move only evidenced reworks ahead of their own tier; with no evidence, normal order is exact.
+ for (const route of ROUTES) {
+ const routeTier = ROUTES.indexOf(route);
+ const selected = mine.findIndex(({ entry }) => tier(entry) === routeTier && mainRed.has(entry.item_id));
+ const firstTierItem = mine.findIndex(({ entry }) => tier(entry) === routeTier);
+ if (selected > firstTierItem && firstTierItem >= 0) {
+ const [rework] = mine.splice(selected, 1);
+ mine.splice(firstTierItem, 0, rework);
+ }
+ }
for (const { entry, shared } of mine) {
const waiting = (entry.item_after ? entry.item_after.split(',').map(Number) : [])
.map((id) => current(board, itemById(board, id)))
diff --git a/src/cli.js b/src/cli.js
index 0d086584..a5037c6a 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -53,6 +53,7 @@ import {
import { briefFiles } from './brief.js';
import { checkBaseline, prepareCheckBaseline, sayCheckBaseline } from './check-baseline.js';
import { retryCheckBaselines, startCheckBaseline } from './check-baseline-worker.js';
+import { compareMainFailures, mainRedMessage, mainRedReworkItems } from './main-red.js';
import { runItems } from './run.js';
import { parseProblems, sweepItems } from './sweep.js';
import { renderSpecView } from './view.js';
@@ -1707,7 +1708,13 @@ async function submitHere(ctx, id) {
// Every submit proves its frozen check and reachable tests anew on this exact commit (V4,V16).
// A full-gate stamp never substitutes for either proof; only an actual full fallback may stamp.
const gate = await runSubmitGate(root, ctx.config, { base: claimHead, trunk: acceptedMain.commit, check: frozenCheck(held), onWait: gateWaitReporter(ctx.io) });
- 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 (!gate.isGreen) {
+ const message = `the submission proof is red at ${commit.slice(0, 12)}; fix it, commit, submit again. ${submitGateReport(gate)}`;
+ let comparison = { main: null, files: [], unavailable: 'main comparison could not be completed' };
+ try { comparison = await compareMainFailures(root, gate.profile, gateWaitReporter(ctx.io)); } catch { /* Keep the original gate refusal if main evidence is unavailable. */ }
+ const mainNote = withBoard(ctx, board => mainRedMessage(root, board, gate.profile, comparison));
+ throw new Refused('GATE_RED', `${message}${mainNote ? `\n${mainNote}` : ''}`);
+ }
if (headCommit(root) !== commit || !isClean(root)) {
throw new Refused(
'MOVED_DURING_GATE',
@@ -1844,7 +1851,8 @@ async function nextOnce(ctx, values) {
return await ordered(ctx, board, 'reserveNextReview', [{ agentId: me.id, lane: me.lane, leaseMs: ctx.config.reviewLeaseMs, policy: ctx.config.verify.policy, familyPolicy: ctx.config.verify.family, runnable: values.runnable, routes: values.routes }]);
}
const warm = warmFiles(ctx, board, me);
- const { item, reasons, shared } = store.nextFor(board, { agentId: me.id, lane: me.lane, runnable: values.runnable, routes: values.routes, warm });
+ const { item, reasons, shared } = store.nextFor(board, { agentId: me.id, lane: me.lane, runnable: values.runnable, routes: values.routes, warm,
+ priority: mainRedReworkItems(ctx.info.root, board) });
const held = item?.item_status === 'claimed';
const offer = held ? null : store.reviewOffer(board, { agentId: me.id, lane: me.lane, policy: ctx.config.verify.policy,
familyPolicy: ctx.config.verify.family, ratio: ctx.config.verify.reviewRatio, runnable: values.runnable, routes: values.routes });
diff --git a/src/main-red.js b/src/main-red.js
new file mode 100644
index 00000000..10de4eac
--- /dev/null
+++ b/src/main-red.js
@@ -0,0 +1,252 @@
+/** Fresh per-file main comparisons for inherited submit reds [V1]. */
+import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
+import { join, relative, resolve, sep } from 'node:path';
+import { tmpdir } from 'node:os';
+import { runProfiledShell, withGateSlot } from './gate.js';
+import { cleanGitEnvironment, mainCheckout } from './git.js';
+import { mainPolicy, policyAt } from './trusted-policy.js';
+import { parseSpec } from './spec.js';
+import { listItems } from './board.js';
+import { takeResource } from './resources.js';
+import { Refused } from './refused.js';
+
+const CACHE_RELATIVE = 'pullboard/main-red.json';
+
+/** Quote one shell argument appended to the configured focused test command. */
+function shellWord(value) {
+ return `'${String(value).replaceAll("'", "'\\''")}'`;
+}
+
+/** Resolve one test filename from runner output to a safe repository-relative path. */
+function testPath(root, value) {
+ if (typeof value !== 'string' || !value) return null;
+ const absolute = resolve(root, value);
+ const path = relative(root, absolute);
+ if (!path || path === '..' || path.startsWith(`..${sep}`) || path.startsWith(sep)) return null;
+ return path.split(sep).join('/');
+}
+
+/** Unique failed test files actually named by the runner profile. */
+function failingFiles(root, profile) {
+ const files = new Set();
+ for (const test of profile?.tests ?? []) if (test.passed === false) {
+ const path = testPath(root, test.file);
+ if (path) files.add(path);
+ }
+ // TAP file rows represent crashes; JUnit suite rows include passing files too.
+ const formats = String(profile?.format ?? '').split('+');
+ if (formats.includes('tap') && !formats.includes('junit')) {
+ for (const file of profile?.files ?? []) {
+ const path = testPath(root, file.path);
+ if (path) files.add(path);
+ }
+ }
+ return [...files].sort();
+}
+
+/** The common Git directory holds local machine evidence shared by this repo's worktrees. */
+function cacheFile(root) {
+ const result = spawnSync('git', ['--no-replace-objects', 'rev-parse', '--path-format=absolute', '--git-common-dir'], {
+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8',
+ });
+ if (result.status !== 0) throw new Refused('NO_POLICY', 'the repository common Git directory cannot be read for the local main comparison cache');
+ return join(result.stdout.trim(), CACHE_RELATIVE);
+}
+
+/** Read only well-formed, machine-local cached outcomes; malformed data is treated as a miss. */
+function readCache(file) {
+ try {
+ const stat = lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || stat.size > 4 * 1024 * 1024) return { version: 1, entries: {} };
+ const value = JSON.parse(readFileSync(file, 'utf8'));
+ if (value.version !== 1 || !value.entries || typeof value.entries !== 'object' || Array.isArray(value.entries)) return { version: 1, entries: {} };
+ const entries = {};
+ for (const [commit, files] of Object.entries(value.entries)) {
+ if (!/^[0-9a-f]{40,64}$/u.test(commit) || !files || typeof files !== 'object' || Array.isArray(files)) continue;
+ entries[commit] = {};
+ for (const [path, outcome] of Object.entries(files)) {
+ if (typeof path === 'string' && path && ['red', 'green'].includes(outcome?.result)) entries[commit][path] = { result: outcome.result };
+ }
+ }
+ return { version: 1, entries };
+ } catch (error) {
+ if (error?.code === 'ENOENT') return { version: 1, entries: {} };
+ return { version: 1, entries: {} };
+ }
+}
+
+/** Atomically persist a focused result without writing anything to board state or the worktree. */
+function writeCache(file, value) {
+ const directory = join(file, '..');
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
+ try {
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
+ renameSync(temporary, file);
+ } finally {
+ rmSync(temporary, { force: true });
+ }
+}
+
+/** Run Git with repository selectors cleared, keeping the main snapshot isolated. */
+function gitCall(cwd, args, env) {
+ return spawnSync('git', ['--no-replace-objects', ...args], {
+ cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 32 * 1024 * 1024,
+ });
+}
+
+/** Build one clean temporary checkout at the exact main commit and always remove it. */
+function withMainCheckout(root, commit, run) {
+ const directory = join(tmpdir(), `pullboard-main-red-${randomUUID()}`);
+ mkdirSync(directory, { mode: 0o700 });
+ const checkout = join(directory, 'checkout');
+ const env = cleanGitEnvironment();
+ try {
+ const cloned = gitCall(root, ['clone', '--quiet', '--shared', '--no-checkout', '--', root, checkout], env);
+ if (cloned.status !== 0) return { unavailable: 'temporary main checkout could not be prepared' };
+ const selected = gitCall(checkout, ['checkout', '--quiet', '--force', '--detach', commit], env);
+ if (selected.status !== 0) return { unavailable: 'the exact main commit could not be checked out temporarily' };
+ const clean = gitCall(checkout, ['status', '--porcelain', '--untracked-files=all'], env);
+ const head = gitCall(checkout, ['rev-parse', '--verify', 'HEAD^{commit}'], env);
+ if (clean.status !== 0 || clean.stdout !== '' || head.status !== 0 || head.stdout.trim() !== commit) {
+ return { unavailable: 'the temporary main checkout was not clean at the captured commit' };
+ }
+ return run(checkout);
+ } finally {
+ rmSync(directory, { recursive: true, force: true });
+ }
+}
+
+/**
+ * Compare named failed files against one captured main snapshot. Each result is cached by exact
+ * commit and file; later submits reuse completed results rather than rerunning the same file.
+ *
+ * @param {string} root
+ * @param {object} profile
+ * @param {(state:object)=>void} [onWait]
+ * @returns {Promise<{ main: string|null, files: Array<{file:string,result:'red'|'green'}>, unavailable?: string }>}
+ */
+export async function compareMainFailures(root, profile, onWait) {
+ const main = mainCheckout(root);
+ if (!main?.commit) return { main: null, files: [], unavailable: 'the primary checkout has no committed main snapshot' };
+ const policy = policyAt(root, main.commit);
+ if (typeof policy.config.affectedTests !== 'string' || !policy.config.affectedTests.trim()) {
+ return { main: main.commit, files: [], unavailable: 'no focused test runner configured' };
+ }
+ const files = failingFiles(root, profile);
+ if (!files.length) return { main: main.commit, files: [], unavailable: 'the runner did not name failed test files' };
+ const file = cacheFile(root);
+ const cacheLease = await takeResource({
+ name: 'main-red-cache', capacity: 1, scope: 'repo', root,
+ agent: process.env.PULLBOARD_AGENT ?? `pid-${process.pid}`,
+ onWait,
+ });
+ try { return await withGateSlot(root, () => {
+ let cache = readCache(file);
+ const results = [];
+ const missing = files.filter(path => !['red', 'green'].includes(cache.entries[main.commit]?.[path]?.result));
+ if (missing.length) {
+ const outcomes = {};
+ for (const path of missing) {
+ const measured = withMainCheckout(root, main.commit, checkout => {
+ const command = `${policy.config.affectedTests.trimEnd()} ${shellWord('./' + path)}`;
+ const run = runProfiledShell(checkout, command, { gateSlotHeld: true });
+ return { result: run.isGreen ? 'green' : 'red' };
+ });
+ if (measured.unavailable) return { main: main.commit, files: [], unavailable: measured.unavailable };
+ outcomes[path] = measured;
+ }
+ cache = readCache(file);
+ const prior = cache.entries[main.commit] && typeof cache.entries[main.commit] === 'object' && !Array.isArray(cache.entries[main.commit])
+ ? cache.entries[main.commit] : {};
+ cache.entries[main.commit] = { ...prior, ...outcomes };
+ try { writeCache(file, cache); }
+ catch { return { main: main.commit, files: [], unavailable: 'main results could not be saved to the machine-local cache' }; }
+ }
+ for (const path of files) results.push({ file: path, result: cache.entries[main.commit][path].result });
+ return { main: main.commit, files: results };
+ }, { onWait });
+ } finally { cacheLease.release(); }
+}
+
+/** Map one or more main-red file results only when the row and its open owner are unambiguous. */
+export function mainRedAttribution(root, board, comparison) {
+ const redFiles = comparison.files.filter(entry => entry.result === 'red').map(entry => entry.file);
+ if (!redFiles.length || !comparison.main) return { redFiles, row: null, item: null };
+ const matches = matchingReworks(root, board, comparison.main, redFiles);
+ return matches.length === 1
+ ? { redFiles, ...matches[0] }
+ : { redFiles, row: null, item: null };
+}
+
+/** Add only evidence the exact-main focused reruns established to an existing GATE_RED refusal. */
+export function mainRedMessage(root, board, profile, comparison) {
+ if (comparison.unavailable === 'no focused test runner configured') {
+ return 'main not checked: no focused test runner configured (affectedTests)';
+ }
+ if (!comparison.files.length) return '';
+ const attribution = mainRedAttribution(root, board, comparison);
+ const names = (profile?.tests ?? []).filter(test => test.passed === false)
+ .map(test => test.name ? `${test.file ?? 'unknown file'} (${test.name})` : test.file)
+ .filter(Boolean);
+ const redFiles = attribution.redFiles;
+ if (!redFiles.length) return '';
+ if (attribution.item && attribution.row) {
+ const file = attribution.file;
+ const testNames = names.length ? `: ${names.join(', ')}` : '';
+ return `inherited main red for approved row ${attribution.row.id} (${file}${testNames}); open rework #${attribution.item.item_id} owns it\nnext: land #${attribution.item.item_id} first, then submit again`;
+ }
+ return `also red on main: ${redFiles.join(', ')}${names.length ? ` (${names.join(', ')})` : ''}`;
+}
+
+/** Current-main red files that uniquely identify one approved row and one open rework item. */
+export function mainRedReworkItems(root, board) {
+ const main = mainCheckout(root);
+ if (!main?.commit) return [];
+ let cache;
+ let policy;
+ try {
+ cache = readCache(cacheFile(root));
+ policy = mainPolicy(root);
+ } catch { return []; }
+ if (policy.commit !== main.commit) return [];
+ const current = cache.entries[main.commit];
+ if (!current) return [];
+ let spec;
+ try {
+ const result = gitCall(root, ['show', `${main.commit}:${policy.config.spec}`], cleanGitEnvironment());
+ if (result.status !== 0) return [];
+ spec = parseSpec(result.stdout, { strictGrammarVersion: false });
+ } catch { return []; }
+ const redFiles = Object.entries(current).filter(([, result]) => result.result === 'red').map(([path]) => path);
+ const matches = matchingReworks(root, board, main.commit, redFiles, { policy, spec, items: listItems(board, { all: true }) });
+ return matches.length === 1 ? [matches[0].item.item_id] : [];
+}
+
+/** Resolve exact-main approved rows and open items without using the candidate's spec text. */
+function matchingReworks(root, board, commit, files, loaded = null) {
+ let policy = loaded?.policy;
+ let spec = loaded?.spec;
+ let items = loaded?.items;
+ try {
+ policy ??= policyAt(root, commit);
+ if (!spec) {
+ const result = gitCall(root, ['show', `${commit}:${policy.config.spec}`], cleanGitEnvironment());
+ if (result.status !== 0) return [];
+ spec = parseSpec(result.stdout, { strictGrammarVersion: false });
+ }
+ items ??= listItems(board, { all: true });
+ } catch { return []; }
+ const open = items.filter(item => item.item_status === 'open');
+ const matches = [];
+ for (const file of files) {
+ const rows = spec.rows.filter(row => row.status === 'approved' && row.gate === file);
+ if (rows.length !== 1) continue;
+ const row = rows[0];
+ const owners = open.filter(item => item.item_spec_ids.split(',').map(id => id.trim()).includes(row.id));
+ if (owners.length === 1) matches.push({ file, row, item: owners[0] });
+ }
+ return matches;
+}
diff --git a/test/main-red.test.js b/test/main-red.test.js
new file mode 100644
index 00000000..0328dc0d
--- /dev/null
+++ b/test/main-red.test.js
@@ -0,0 +1,304 @@
+/** A red submit compares only its failed files with exact main and guides an inherited rework [V1]. */
+import assert from 'node:assert/strict';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { delimiter, dirname, join } from 'node:path';
+import { after, test } from 'node:test';
+import { runFixtureChild, runFixtureGit } from './fixture-child.js';
+
+const BIN = join(import.meta.dirname, '../bin/pullboard.js');
+const roots = [];
+
+after(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+});
+
+/** Write one file under a fixture repository, creating its parent directories. */
+function put(root, path, value) {
+ const file = join(root, path);
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(file, value);
+}
+
+/** Run the real CLI in a private checkout and preserve its separate output streams. */
+function cli(root, env, ...args) {
+ const result = runFixtureChild(process.execPath, [BIN, ...args], { cwd: root, env, encoding: 'utf8' });
+ return { code: result.status, out: result.stdout ?? '', err: result.failure ?? result.stderr ?? '' };
+}
+
+/** Commit fixture state with the isolated test identity and the requested spec citation. */
+function commit(root, env, subject = 'chore: fixture state') {
+ runFixtureGit(['add', '-A'], { cwd: root, env });
+ runFixtureGit(['commit', '-q', '-m', subject], { cwd: root, env });
+ return runFixtureGit(['rev-parse', 'HEAD'], { cwd: root, env }).trim();
+}
+
+/** Quote one executable path for the fixture's real CLI shim. */
+function shellWord(value) { return "'" + String(value).replaceAll("'", "'\\''") + "'"; }
+
+/** Create a private real-Git board with a selected native Node test command. */
+function fixture(t, { spec, source, affectedTests = 'node test/runner.js' }) {
+ const directory = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-main-red-')));
+ roots.push(directory);
+ t.after(() => rmSync(directory, { recursive: true, force: true }));
+ const root = join(directory, 'repo');
+ mkdirSync(root);
+ const bin = join(directory, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);
+ chmodSync(join(bin, 'pullboard'), 0o755);
+ const env = {
+ ...process.env,
+ PATH: [bin, process.env.PATH].filter(Boolean).join(delimiter),
+ GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Fixture Agent', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Fixture Agent', GIT_COMMITTER_EMAIL: '[email protected]',
+ PULLBOARD_HOME: join(directory, 'home'), PULLBOARD_MACHINE_HOME: join(directory, 'machine'),
+ PULLBOARD_MODEL: 'Fixture Model', MAIN_RED_RUNS: join(directory, 'main-runs.log'),
+ };
+ delete env.PULLBOARD_RELAY_TOKEN;
+ delete env.NODE_TEST_CONTEXT;
+ runFixtureGit(['init', '-q', '-b', 'main'], { cwd: root, env });
+ assert.equal(cli(root, env, 'init').code, 0);
+ put(root, 'pullboard.json', JSON.stringify({
+ gate: 'node test/runner.js',
+ ...(affectedTests ? { affectedTests } : {}),
+ lanes: { core: { owns: ['test/'], specs: ['G'] } },
+ }, null, 2) + '\n');
+ put(root, 'package.json', '{"type":"module"}\n');
+ put(root, 'SPEC.md', spec);
+ put(root, 'test/inherited.test.js', source);
+ put(root, 'test/runner.js', [
+ "import { appendFileSync } from 'node:fs';",
+ "import { spawnSync } from 'node:child_process';",
+ "if (process.env.MAIN_RED_RUNS) appendFileSync(process.env.MAIN_RED_RUNS, `${process.cwd()}\\n`);",
+ "const files = process.argv.slice(2).length ? process.argv.slice(2) : ['test/inherited.test.js'];",
+ "const result = spawnSync(process.execPath, ['--test', ...files], { cwd: process.cwd(), env: process.env, encoding: 'utf8' });",
+ "if (result.stdout) process.stdout.write(result.stdout);",
+ "if (result.stderr) process.stderr.write(result.stderr);",
+ 'process.exitCode = result.status ?? 1;',
+ ].join('\n') + '\n');
+ commit(root, env);
+ return { directory, root, env };
+}
+
+/** Add each specified item through the actual coordinator CLI. */
+function addItems(box, rows) {
+ return rows.map(({ title, specId, route = 'mid' }) => {
+ const file = { G1: 'test/inherited.test.js', G2: 'test/unrelated.test.js', G3: 'test/earlier.test.js', G4: 'test/middle.test.js' }[specId];
+ const result = cli(box.root, box.env, 'add', 'core', title, '--specs', specId, '--route', route,
+ '--criterion', title, '--check', 'true', '--brief', `Files: ${file}\nTest: ${title}`);
+ assert.equal(result.code, 0, result.err || result.out);
+ return Number(/^#(\d+)$/mu.exec(result.out)?.[1]);
+ });
+}
+
+/** Create and join a real builder worktree through Pullboard. */
+function builder(box) {
+ const made = cli(box.root, box.env, 'worktree', 'core', '--route', 'mid', '--model', 'Fixture Model', '--json');
+ assert.equal(made.code, 0, made.err || made.out);
+ const root = JSON.parse(made.out).path;
+ return { root, run: (...args) => cli(root, box.env, ...args) };
+}
+
+/** Assert the public refusal identifies both next steps and excludes false unique attribution. */
+function inheritedMessage(result, { row, item, testFile = 'test/inherited.test.js' } = {}) {
+ assert.equal(result.code, 1, result.out || result.err);
+ assert.match(result.err, /\[GATE_RED\]/u);
+ assert.match(result.err, /also red on main|inherited main red/u);
+ assert.match(result.err, new RegExp(testFile.replaceAll('.', '\\.'), 'u'));
+ if (row && item) {
+ assert.match(result.err, new RegExp(`approved row ${row} .*open rework #${item} owns it`, 'u'));
+ assert.ok(result.err.trimEnd().endsWith(`next: land #${item} first, then submit again`));
+ } else {
+ assert.doesNotMatch(result.err, /approved row|open rework #\d+/u);
+ }
+}
+
+const RED_SPEC = [
+ '# Main red fixture\n\n## G · Goals',
+ '- G1 [approved, must] The inherited test proves the row. | gate: test/inherited.test.js',
+ '- G2 [approved, must] An unrelated change has a separate test. | gate: test/unrelated.test.js',
+ '- G3 [approved, must] Earlier milestone work has a separate row. | gate: test/earlier.test.js',
+ '- G4 [approved, must] Middle milestone work has a separate row. | gate: test/middle.test.js',
+].join('\n') + '\n';
+const FAILING_TEST = [
+ "import assert from 'node:assert/strict';",
+ "import { test } from 'node:test';",
+ "test('the inherited behavior remains broken [V1]', () => assert.equal(1, 2));",
+].join('\n') + '\n';
+
+test('an inherited red names the rework that owns it [V1]', async (t) => {
+ await t.test('a prioritized rework already first in its tier stays first [V1]', (sub) => {
+ const box = fixture(sub, { spec: RED_SPEC, source: FAILING_TEST });
+ const [rework, submitItem] = addItems(box, [
+ { title: 'First same-tier rework', specId: 'G1' },
+ { title: 'Second same-tier submit', specId: 'G2' },
+ ]);
+ const submitter = builder(box);
+ assert.equal(submitter.run('claim', String(submitItem)).code, 0);
+ put(submitter.root, 'test/inherited.test.js', `${FAILING_TEST}// candidate-only comment\n`);
+ commit(submitter.root, box.env, 'test(core): capture inherited red [G1]');
+ inheritedMessage(submitter.run('submit', String(submitItem)), { row: 'G1', item: rework });
+ const next = builder(box).run('next', '--json');
+ assert.equal(next.code, 0, next.err);
+ assert.equal(JSON.parse(next.out).item.item_id, rework);
+ });
+
+ await t.test('one inherited row names its open owner, reuses exact-main cache, and leads only within its tier [V1]', (sub) => {
+ const box = fixture(sub, { spec: RED_SPEC, source: FAILING_TEST });
+ const [rework, submitItem, earlier, middle] = addItems(box, [
+ { title: 'Repair inherited gate', specId: 'G1' },
+ { title: 'Unrelated submit', specId: 'G2' },
+ { title: 'Earlier light work', specId: 'G3', route: 'light' },
+ { title: 'Middle milestone work', specId: 'G4' },
+ ]);
+ assert.ok(rework && submitItem && earlier && middle);
+ assert.equal(cli(box.root, box.env, 'milestone', 'add', 'Early', '--items', String(earlier)).code, 0);
+ assert.equal(cli(box.root, box.env, 'milestone', 'add', 'Middle', '--items', String(middle)).code, 0);
+ assert.equal(cli(box.root, box.env, 'milestone', 'add', 'Later', '--items', String(rework)).code, 0);
+
+ const withoutEvidence = builder(box);
+ const ordinary = withoutEvidence.run('next', '--json');
+ assert.equal(ordinary.code, 0, ordinary.err);
+ assert.equal(JSON.parse(ordinary.out).item.item_id, earlier, 'without current-main evidence, original milestone order remains unchanged');
+ const normalMid = builder(box);
+ const normalOffer = normalMid.run('next', '--json');
+ assert.equal(normalOffer.code, 0, normalOffer.err);
+ assert.equal(JSON.parse(normalOffer.out).item.item_id, middle, 'without evidence, same-tier milestone order remains unchanged');
+ assert.equal(normalMid.run('release', String(middle)).code, 0);
+
+ const submitter = builder(box);
+ assert.equal(submitter.run('claim', String(submitItem)).code, 0);
+ put(submitter.root, 'test/inherited.test.js', `${FAILING_TEST}// candidate-only comment\n`);
+ commit(submitter.root, box.env, 'test(core): select inherited red [G1]');
+ let red = submitter.run('submit', String(submitItem));
+ inheritedMessage(red, { row: 'G1', item: rework });
+ const main = runFixtureGit(['rev-parse', 'main'], { cwd: box.root, env: box.env }).trim();
+ const common = runFixtureGit(['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: submitter.root, env: box.env }).trim();
+ const cachePath = join(common, 'pullboard/main-red.json');
+ const cache = JSON.parse(readFileSync(cachePath, 'utf8'));
+ assert.equal(cache.entries[main]['test/inherited.test.js'].result, 'red');
+ assert.equal((readFileSync(cachePath).length > 0), true);
+ assert.equal(statSync(cachePath).mode & 0o077, 0, 'the result cache is private to this machine account');
+ const firstCount = readFileSync(box.env.MAIN_RED_RUNS, 'utf8').trim().split('\n').length;
+ assert.equal(firstCount, 2, 'one selected candidate run and one exact-main run occurred');
+
+ put(submitter.root, 'test/inherited.test.js', `${FAILING_TEST}// second candidate-only comment\n`);
+ commit(submitter.root, box.env, 'test(core): retry inherited red [G1]');
+ red = submitter.run('submit', String(submitItem));
+ inheritedMessage(red, { row: 'G1', item: rework });
+ const secondCount = readFileSync(box.env.MAIN_RED_RUNS, 'utf8').trim().split('\n').length;
+ assert.equal(secondCount, firstCount + 1, 'the second submit reuses the current-main file result');
+
+ const afterEvidence = builder(box);
+ const offered = afterEvidence.run('next', '--json');
+ assert.equal(offered.code, 0, offered.err);
+ assert.equal(JSON.parse(offered.out).item.item_id, rework, 'the unique main-red rework leads an earlier-milestone item within the same tier');
+ const middleHolder = builder(box);
+ assert.equal(middleHolder.run('claim', String(middle)).code, 0, 'a different builder can claim the non-priority same-tier item');
+ assert.equal(afterEvidence.run('release', String(rework)).code, 0, 'release the selected rework before asking for another claim');
+ const sole = afterEvidence.run('next', '--json');
+ assert.equal(sole.code, 0, sole.err);
+ assert.equal(JSON.parse(sole.out).item.item_id, rework, 'the only eligible same-tier item is never removed by prioritization');
+ assert.equal(afterEvidence.run('release', String(rework)).code, 0);
+ assert.equal(middleHolder.run('release', String(middle)).code, 0);
+ put(box.root, 'README.md', 'A new main commit has no cached comparison yet.\n');
+ const newMain = commit(box.root, box.env, 'chore: advance main fixture');
+ assert.notEqual(newMain, main);
+ const afterMainChange = builder(box).run('next', '--json');
+ assert.equal(afterMainChange.code, 0, afterMainChange.err);
+ assert.equal(JSON.parse(afterMainChange.out).item.item_id, middle, 'a cache for the former main cannot reorder the current main');
+ });
+
+ await t.test('multiple approved rows never produce a guessed row or item [V1]', (sub) => {
+ const spec = [
+ '# Ambiguous gate fixture\n\n## G · Goals',
+ '- G1 [approved, must] First gate row. | gate: test/inherited.test.js',
+ '- G2 [approved, must] Second gate row. | gate: test/inherited.test.js',
+ '- G3 [approved, must] Submit row. | gate: test/unrelated.test.js',
+ '- G4 [approved, must] Earlier work row. | gate: test/earlier.test.js',
+ ].join('\n') + '\n';
+ const box = fixture(sub, { spec, source: FAILING_TEST });
+ const [first, second, earlier, submitItem] = addItems(box, [
+ { title: 'First possible repair', specId: 'G1' },
+ { title: 'Second possible repair', specId: 'G2' },
+ { title: 'Earlier milestone work', specId: 'G4' },
+ { title: 'Unrelated submit', specId: 'G3' },
+ ]);
+ const submitter = builder(box);
+ assert.equal(submitter.run('claim', String(submitItem)).code, 0);
+ put(submitter.root, 'test/inherited.test.js', `${FAILING_TEST}// candidate-only comment\n`);
+ commit(submitter.root, box.env, 'test(core): select ambiguous inherited red [G3]');
+ const red = submitter.run('submit', String(submitItem));
+ inheritedMessage(red);
+ assert.doesNotMatch(red.err, new RegExp(`#${first}|#${second}`, 'u'));
+ assert.equal(cli(box.root, box.env, 'milestone', 'add', 'Early', '--items', String(earlier)).code, 0);
+ assert.equal(cli(box.root, box.env, 'milestone', 'add', 'Later', '--items', `${first},${second}`).code, 0);
+ const next = builder(box).run('next', '--json');
+ assert.equal(next.code, 0, next.err);
+ assert.equal(JSON.parse(next.out).item.item_id, earlier, 'ambiguous rows leave next in its original milestone order');
+ });
+
+ await t.test('a row with several open owners does not prioritize either owner [V1]', (sub) => {
+ const spec = [
+ '# Multiple owner fixture\n\n## G · Goals',
+ '- G1 [approved, must] Inherited gate row. | gate: test/inherited.test.js',
+ '- G2 [approved, must] Submit row. | gate: test/unrelated.test.js',
+ '- G3 [approved, must] Earlier work row. | gate: test/earlier.test.js',
+ ].join('\n') + '\n';
+ const box = fixture(sub, { spec, source: FAILING_TEST });
+ const [first, second, earlier, submitItem] = addItems(box, [
+ { title: 'First possible repair', specId: 'G1' },
+ { title: 'Second possible repair', specId: 'G1' },
+ { title: 'Earlier milestone work', specId: 'G3' },
+ { title: 'Unrelated submit', specId: 'G2' },
+ ]);
+ assert.equal(cli(box.root, box.env, 'milestone', 'add', 'Early', '--items', String(earlier)).code, 0);
+ assert.equal(cli(box.root, box.env, 'milestone', 'add', 'Later', '--items', `${first},${second}`).code, 0);
+ const submitter = builder(box);
+ assert.equal(submitter.run('claim', String(submitItem)).code, 0);
+ put(submitter.root, 'test/inherited.test.js', `${FAILING_TEST}// candidate-only comment\n`);
+ commit(submitter.root, box.env, 'test(core): select multiply-owned inherited red [G2]');
+ const red = submitter.run('submit', String(submitItem));
+ inheritedMessage(red);
+ assert.doesNotMatch(red.err, new RegExp(`#${first}|#${second}`, 'u'));
+ const next = builder(box).run('next', '--json');
+ assert.equal(next.code, 0, next.err);
+ assert.equal(JSON.parse(next.out).item.item_id, earlier, 'several open owners leave next in its original milestone order');
+ });
+
+ await t.test('a candidate-only red keeps the old refusal text [V1]', (sub) => {
+ const green = "import assert from 'node:assert/strict';\nassert.equal(1, 1);\n";
+ const box = fixture(sub, { spec: RED_SPEC, source: green });
+ const [, submitItem] = addItems(box, [
+ { title: 'Repair unrelated gate row', specId: 'G1' },
+ { title: 'Candidate-only submit', specId: 'G2' },
+ ]);
+ const submitter = builder(box);
+ assert.equal(submitter.run('claim', String(submitItem)).code, 0);
+ put(submitter.root, 'test/inherited.test.js', "import assert from 'node:assert/strict';\nassert.equal(1, 2);\n");
+ commit(submitter.root, box.env, 'test(core): introduce candidate-only red [G2]');
+ const red = submitter.run('submit', String(submitItem));
+ assert.equal(red.code, 1, red.out || red.err);
+ assert.match(red.err, /\[GATE_RED\]/u);
+ assert.doesNotMatch(red.err, /also red on main|inherited main red|main not checked/u);
+ });
+
+ await t.test('without a focused runner the old refusal names the missing config key [V1]', (sub) => {
+ const box = fixture(sub, { spec: RED_SPEC, source: FAILING_TEST, affectedTests: '' });
+ const [, submitItem] = addItems(box, [
+ { title: 'Repair inherited gate', specId: 'G1' },
+ { title: 'Unrelated submit', specId: 'G2' },
+ ]);
+ const submitter = builder(box);
+ assert.equal(submitter.run('claim', String(submitItem)).code, 0);
+ put(submitter.root, 'test/inherited.test.js', `${FAILING_TEST}// candidate-only comment\n`);
+ commit(submitter.root, box.env, 'test(core): select red without focused runner [G2]');
+ const red = submitter.run('submit', String(submitItem));
+ assert.equal(red.code, 1, red.out || red.err);
+ assert.match(red.err, /\[GATE_RED\]/u);
+ assert.match(red.err, /main not checked: no focused test runner configured \(affectedTests\)/u);
+ assert.equal(readFileSync(box.env.MAIN_RED_RUNS, 'utf8').trim().split('\n').length, 1, 'the main comparison does not run a second full gate');
+ });
+});