Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(gate): profile every submission phase [C7,V10]
Corey Olsondd4859ba75f6
diff --git a/bin/gate-profile-reporter.js b/bin/gate-profile-reporter.jsnew file mode 100644index 00000000..25d6ea28--- /dev/null+++ b/bin/gate-profile-reporter.js@@ -0,0 +1,56 @@+/** Preserve per-file and per-test timings from Node's real test events [C7,V10]. */+import { Transform } from 'node:stream';+import { relative, resolve } from 'node:path';++const files = new Map();+const completions = [];++/** Collect Node events without changing the TAP reporter sent to stdout. */+const reporter = new Transform({+ writableObjectMode: true,+ transform(event, encoding, callback) {+ const data = event.data ?? {};+ if (event.type === 'test:summary' && typeof data.file === 'string' && Number.isFinite(data.duration_ms)) {+ const path = relative(process.cwd(), resolve(data.file));+ files.set(path, { path, durationMs: data.duration_ms, summaryIndex: completions.length });+ }+ if (event.type === 'test:complete' && data.details?.type === 'test' && typeof data.file === 'string' && Number.isFinite(data.details.duration_ms)) {+ completions.push({+ file: relative(process.cwd(), resolve(data.file)), name: data.name,+ durationMs: data.details.duration_ms, passed: data.details.passed === true,+ line: data.line, column: data.column,+ });+ }+ callback();+ },+ flush(callback) {+ const wrappers = new Set();+ // A file that crashes before its summary still has a synthetic completion.+ for (const test of completions) {+ if (!files.has(test.file) && test.line === 1 && test.column === 1+ && typeof test.name === 'string' && resolve(test.name) === resolve(test.file)) {+ files.set(test.file, { path: test.file, durationMs: test.durationMs, summaryIndex: null });+ }+ }+ for (const file of files.values()) {+ // Node's synthetic file completion may precede the file's buffered events+ // or follow its summary. Remove just that boundary event, retaining even+ // real tests deliberately named after their file at line 1, column 1.+ const candidates = completions.flatMap((test, index) => test.file === file.path && test.line === 1 && test.column === 1+ && typeof test.name === 'string' && resolve(test.name) === resolve(file.path) ? [index] : []);+ const wrapper = file.summaryIndex === null ? candidates.at(-1)+ : candidates.find(index => index >= file.summaryIndex) ?? candidates[0];+ if (wrapper !== undefined) {+ wrappers.add(wrapper);+ file.durationMs = completions[wrapper].durationMs;+ }+ }+ this.push(JSON.stringify({+ files: [...files.values()].map(({ summaryIndex, ...file }) => file),+ tests: completions.filter((test, index) => !wrappers.has(index)).map(({ line, column, ...test }) => test),+ }));+ callback();+ },+});++export default reporter;diff --git a/bin/run-tests.js b/bin/run-tests.jsindex fd2604eb..614bb506 100644--- a/bin/run-tests.js+++ b/bin/run-tests.js@@ -7,11 +7,13 @@ import { delimiter, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { execFileSync, spawnSync } from 'node:child_process';import { tmpdir } from 'node:os';+import { randomUUID } from 'node:crypto';import { after, afterEach, beforeEach } from 'node:test';import { Worker } from 'node:worker_threads';import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';const runner = fileURLToPath(import.meta.url);+const profileReporter = fileURLToPath(new URL('./gate-profile-reporter.js', import.meta.url));export const DEFAULT_TEST_TIMEOUT_MS = 660_000;const watchdogSource = `@@ -128,6 +130,8 @@ function testEnvironment(sandbox) {delete env.PULLBOARD_RELAY_TOKEN; // Fixtures must supply their own scoped credentials, never an agent’s live bearer.delete env.NODE_TEST_CONTEXT;delete env.PULLBOARD_TEST_FILE;+ // Keep fixture-spawned test commands from being counted as part of this runner invocation.+ delete env.PULLBOARD_TEST_TIMING_PROFILE;return env;}@@ -140,13 +144,34 @@ function testEnvironment(sandbox) {*/function runTests(args, env) {const reporter = args.some((argument) => argument === '--test-reporter' || argument.startsWith('--test-reporter='));+ const destination = args.some(argument => argument === '--test-reporter-destination' || argument.startsWith('--test-reporter-destination='));+ const profileBase = process.env.PULLBOARD_TEST_TIMING_PROFILE;+ const profileFile = profileBase ? `${profileBase}.${process.pid}.${randomUUID()}.json` : null;+ const reporters = profileFile ? [+ ...(!destination ? ['--test-reporter-destination=stdout'] : []),+ `--test-reporter=${profileReporter}`, `--test-reporter-destination=${profileFile}`,+ ] : [];+ const callerArgs = [...args];+ if (profileFile) {+ // Reporter and destination arrays pair by position; append after the caller's options.+ let afterReporters = 0;+ for (let at = 0; at < args.length; at += 1) {+ if (['--test-reporter', '--test-reporter-destination'].includes(args[at])) {+ afterReporters = at + 2;+ at += 1;+ } else if (args[at].startsWith('--test-reporter=') || args[at].startsWith('--test-reporter-destination=')) {+ afterReporters = at + 1;+ }+ }+ callerArgs.splice(afterReporters, 0, ...reporters);+ }const nodeArgs = ['--disable-warning=ExperimentalWarning','--test',...(!reporter ? ['--test-reporter=tap'] : []),'--import',runner,- ...args,+ ...callerArgs,];return spawnSync(process.execPath, nodeArgs, { env, stdio: 'inherit' });}diff --git a/src/cli.js b/src/cli.jsindex 2e09f19a..2cfbe20c 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, runSubmitGate, submitGateReport, withGateSlot } from './gate.js';+import { digestOf, gateReport, runGate, runProfiledShell, runSubmitGate, submitGateReport, timingDigest, withGateSlot } from './gate.js';import { bareWorktreeFinding, contains, differFromHead, git, gitChildEnv, headCommit, headTree, invalidateGitFacts, isClean, mainCheckout, repoInfo, resolveCommit, tryGit, untracked, withGitFacts } from './git.js';import {FIX_NOTE,@@ -1719,7 +1719,8 @@ 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: submitGateReport(gate), files: gate.files, full: gate.full, reason: gate.reason, check: gate.check });+ return reportSubmission(ctx, id, commit, { green: gate.isGreen, report: submitGateReport(gate), files: gate.files, full: gate.full, reason: gate.reason, check: gate.check,+ log: gate.log, profile: gate.profile, profilePath: gate.profilePath, proofLog: gate.proofLog, proofProfilePath: gate.proofProfilePath });}/** Report and pin the original submitted commit, including a recovered acknowledged outcome. */@@ -1747,6 +1748,7 @@ async function verifyHere(ctx, id, { second, values }) {const decision = { accept: 'ACCEPT', reject: 'REJECT' }[String(second ?? '').toLowerCase()];if (!decision) throw new Refused('USAGE', 'pullboard verify <id> accept, or reject --reason CODE --note "..."');const { root } = ctx.info;+ let verificationProfile = null;const result = await withBoard(ctx, async (board) => {checkMainVerifier(ctx, board, values);const me = whoAmI(ctx, board);@@ -1778,12 +1780,15 @@ async function verifyHere(ctx, id, { second, values }) {if (decision === 'ACCEPT') {if (digest !== item.item_frozen_digest) throw new Refused('CRITERIA_CHANGED', 'the criterion changed; ask the coordinator to refreeze this item before checking it');requireTrunkMerge(root, commit);- check = await withGateSlot(root, () => checkAtCommit(root, item), { itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ check = await withGateSlot(root, (lease) => checkAtCommit(root, item, { waitMs: lease.waitMs }), { itemCheck: true, onWait: gateWaitReporter(ctx.io) });+ verificationProfile = check.profile ?? null;const evidence = check.checked? `\nlast output lines (up to 40):\n${(check.outputTail ?? '(no output)').split('\n').map((line) => ` ${line}`).join('\n')}\nfull output file: ${check.outputPath ?? `(unavailable${check.outputError ? `: ${check.outputError}` : ''})`}`: '';- if (check.state === 'unverified') throw new Refused('CHECK_UNVERIFIED', `the frozen ${check.stage} could not be verified at the submitted commit; restore the install or check environment, then retry verification; output digest:\n${check.report.replace(/^/gm, ' ')}${evidence}`);- if (check.state === 'red') throw new Refused('CHECK_RED', `the frozen item check is red at the submitted commit (${check.stage}); check.install may be needed for dependencies; reject with the failing behavior or ask the builder to fix and resubmit; output digest:\n${check.report.replace(/^/gm, ' ')}${evidence}`);+ const checkTimings = timingDigest(check.profile);+ const timingEvidence = check.profilePath ? `\n${checkTimings}\ntiming profile: ${check.profilePath}` : '';+ if (check.state === 'unverified') throw new Refused('CHECK_UNVERIFIED', `the frozen ${check.stage} could not be verified at the submitted commit; restore the install or check environment, then retry verification; output digest:\n${check.report.replace(/^/gm, ' ')}${evidence}${timingEvidence}`);+ if (check.state === 'red') throw new Refused('CHECK_RED', `the frozen item check is red at the submitted commit (${check.stage}); check.install may be needed for dependencies; reject with the failing behavior or ask the builder to fix and resubmit; output digest:\n${check.report.replace(/^/gm, ' ')}${evidence}${timingEvidence}`);const receipt = store.events(board, { itemId: id }).filter(event => event.event_kind === 'submit').map(event => JSON.parse(event.event_detail)).find(event => event.commit === commit);submissionPaths(root, item, commit, { mainCommit: receipt?.policyCommit, dependencies: dependencySnapshots(board.db, item) });requireTrunkMerge(root, commit); // Re-read after the frozen check, before accepting.@@ -1801,8 +1806,10 @@ async function verifyHere(ctx, id, { second, values }) {}]);});ctx.io.result?.({ id, ...result });+ const verifiedSummary = timingDigest(verificationProfile);+ const verifiedTiming = result.decision === 'ACCEPT' && verificationProfile && verifiedSummary ? `\n${verifiedSummary}\ntiming profile: ${verificationProfile.profilePath ?? '(not saved)'}` : '';ctx.io.say(result.decision === 'ACCEPT'- ? `verified #${id}: ${result.reason}${result.check === 'none' ? '; no frozen check ran' : ''}`+ ? `verified #${id}: ${result.reason}${result.check === 'none' ? '; no frozen check ran' : ''}${verifiedTiming}`: `rejected #${id}: ${result.reason}; it is open again for rework`);return 0;}@@ -2158,9 +2165,14 @@ function workCommands(io, args) {throw new Refused('CHECK_CONFIRM', `the check set by ${by} was not run: ${check}; run pullboard check ${item.item_id} --yes after reading the command, or answer yes at the prompt`);}}- const run = await withGateSlot(ctx.info.root, () => runShell(ctx.info.root, check), { itemCheck: true, onWait: gateWaitReporter(io) });+ const run = await withGateSlot(ctx.info.root, (lease) => runProfiledShell(ctx.info.root, check, { waitMs: lease.waitMs, artifactPrefix: `pullboard-check-${item.item_id}`, persistLog: true }), { itemCheck: true, onWait: gateWaitReporter(io) });io.result?.({ id: item.item_id, green: run.isGreen, seconds: run.seconds, check, by, report: run.isGreen ? '' : digestOf(run.output) });io.say(`check ${run.isGreen ? 'green' : 'red'} in ${run.seconds}s: ${check}`);+ const timings = timingDigest(run.profile);+ if (timings) {+ io.say(timings);+ io.say(`timing profile: ${run.profilePath}`);+ }if (!run.isGreen) io.say(digestOf(run.output).replace(/^/gm, ' '));return run.isGreen ? 0 : 1;},diff --git a/src/gate.js b/src/gate.jsindex 0a73a7ae..43c8c2c0 100644--- a/src/gate.js+++ b/src/gate.js@@ -5,13 +5,15 @@* run, not the run (V10): a passing suite's output costs tokens and says nothing.*/import { spawnSync } from 'node:child_process';-import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';+import { basename, dirname, join } from 'node:path';import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';+import { secretsIn } from './hooks.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';@@ -93,20 +95,109 @@ export function isStampedGreen(root) {** @param {string} root* @param {string} command+ * @param {{ env?: NodeJS.ProcessEnv }} [options] - Additional child environment values.* @returns {{ isGreen: boolean, output: string, seconds: number }}*/-export function runShell(root, command) {+export function runShell(root, command, { env = {} } = {}) {const started = Date.now();// Newlines, not spaces, around the command, so a trailing comment in it cannot swallow the `)`.- const result = spawnSync(`(\n${command}\n) 2>&1`, { cwd: root, env: gitChildEnv(root), shell: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', maxBuffer: 2 ** 30 });+ const result = spawnSync(`(\n${command}\n) 2>&1`, { cwd: root, env: { ...gitChildEnv(root), ...env }, shell: true, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', maxBuffer: 2 ** 30 });invalidateGitFacts();return { isGreen: result.status === 0, output: `${result.stdout ?? ''}${result.stderr ?? ''}`, seconds: Math.round((Date.now() - started) / 1000) };}+/** Replace a possible secret-bearing line before persisting a direct item-check log. */+function safeLog(output) {+ return output.split('\n').map((line, index) => {+ if (Buffer.byteLength(line, 'utf8') > 64 * 1024) return '[redacted output line exceeds 64 KiB safe-scan limit]';+ const findings = secretsIn([{ path: 'item check output', line: index + 1, text: line }]);+ return findings.length ? `[redacted ${findings.map(finding => finding.slice(0, finding.lastIndexOf(' at '))).join(', ')}]` : line;+ }).join('\n');+}++/** Run a command with Node's event reporter and persist its timing profile beside its log.+ * @param {string} root+ * @param {string} command+ * @param {{ waitMs?: number, artifactDirectory?: string, artifactPrefix?: string, persistLog?: boolean, profileFile?: string }} [options]+ * @returns {{ isGreen: boolean, output: string, seconds: number, profile: object, profilePath: string, logPath: string|null }}+ */+export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory, artifactPrefix = 'pullboard-gate', persistLog = false, profileFile } = {}) {+ const directory = artifactDirectory ?? dirname(gitPath(root, LOG));+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ const id = randomUUID();+ const eventsDirectory = join(directory, `.${artifactPrefix}-${id}.timings`);+ mkdirSync(eventsDirectory, { mode: 0o700 });+ const eventsPath = join(eventsDirectory, 'events.json');+ const profilePath = profileFile ?? join(directory, `${artifactPrefix}-${id}.profile.json`);+ const logPath = persistLog ? join(directory, `${artifactPrefix}-${id}.log`) : null;+ const started = Date.now();+ try {+ const run = runShell(root, command, { env: { PULLBOARD_TEST_TIMING_PROFILE: eventsPath } });+ const events = readTimingProfiles(eventsPath);+ const profile = writeTimingProfile(profilePath, {+ version: 1,+ waitMs: Math.max(0, Math.round(waitMs)),+ wallMs: Math.max(0, Date.now() - started),+ files: events.files,+ tests: events.tests,+ });+ if (logPath) writeFileSync(logPath, safeLog(run.output), { mode: 0o600 });+ return { ...run, profile, profilePath, logPath };+ } finally { rmSync(eventsDirectory, { recursive: true, force: true }); }+}++/** Persist one sanitized timing profile as a private artifact.+ * @param {string} path+ * @param {{ files?: Array<object>, tests?: Array<object>, [key: string]: any }} profile+ * @returns {object} The sanitized profile written to disk.+ */+export function writeTimingProfile(path, profile) {+ /** Sanitize one reporter-controlled string before persistence or display.+ * @param {unknown} value+ * @param {string} label+ * @returns {unknown}+ */+ const sanitize = (value, label) => {+ if (typeof value !== 'string') return value;+ if (Buffer.byteLength(value, 'utf8') > 64 * 1024) return '[redacted profile field exceeds 64 KiB safe-scan limit]';+ const findings = secretsIn([{ path: `timing profile ${label}`, line: 1, text: value }]);+ return findings.length ? `[redacted ${findings.map(finding => finding.slice(0, finding.lastIndexOf(' at '))).join(', ')}]` : value;+ };+ /** Accept only measured, nonnegative durations from reporter events. */+ const validDuration = value => Number.isFinite(value) && value >= 0;+ const files = (profile.files ?? []).filter(file => typeof file?.path === 'string' && validDuration(file.durationMs))+ .map(file => ({ path: sanitize(file.path, 'file path'), durationMs: file.durationMs }));+ const tests = (profile.tests ?? []).filter(test => typeof test?.file === 'string' && typeof test?.name === 'string' && validDuration(test.durationMs))+ .map(test => ({ file: sanitize(test.file, 'test file'), name: sanitize(test.name, 'test name'), durationMs: test.durationMs, passed: test.passed === true }));+ const sanitized = {+ version: 1,+ waitMs: validDuration(profile.waitMs) ? profile.waitMs : 0,+ wallMs: validDuration(profile.wallMs) ? profile.wallMs : null,+ files,+ tests,+ };+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });+ writeFileSync(path, `${JSON.stringify(sanitized, null, 2)}\n`, { mode: 0o600 });+ return sanitized;+}++/** Combine distinct Node reporter invocations whose names share a private per-run prefix. */+function readTimingProfiles(prefix) {+ const directory = dirname(prefix);+ const base = `${basename(prefix)}.`;+ const profiles = [];+ let names = [];+ try { names = readdirSync(directory).filter(name => name.startsWith(base) && name.endsWith('.json')); } catch { return { files: [], tests: [] }; }+ for (const name of names) {+ try { profiles.push(JSON.parse(readFileSync(join(directory, name), 'utf8'))); } catch { /* Ignore incomplete reporters from a killed test process. */ }+ }+ return { files: profiles.flatMap(profile => Array.isArray(profile.files) ? profile.files : []), tests: profiles.flatMap(profile => Array.isArray(profile.tests) ? profile.tests : []) };+}+/** Run work under the machine gate queue, keeping landing gates ahead of ordinary gates and item checks last.** @param {string} root - Checkout used to locate the machine resource database.- * @param {() => any | Promise<any>} action - Work to perform while holding a slot.+ * @param {(lease: { waitMs: number }) => any | Promise<any>} action - Work to perform while holding a slot.* @param {{ landing?: boolean, itemCheck?: boolean, onWait?: (state: object) => void }} [options] - Queue class and progress reporter.* @returns {Promise<any>} The action's result after releasing its lease.*/@@ -125,7 +216,7 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =onWait,});try {- return await action();+ return await action(lease);} finally {lease.release();}@@ -142,25 +233,24 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =* @param {string} root* @param {any} config* @param {{ trustStamp?: boolean, onWait?: (state: object) => void, landing?: boolean }} [options]- * @returns {Promise<{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string }>}+ * @returns {Promise<{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string, profile?: object, profilePath?: string }>}*/export async function runGate(root, config, { trustStamp = true, onWait, landing = false } = {}) {if (!config.gate.trim()) {throw 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 });+ return await withGateSlot(root, (lease) => fullGateRun(root, config, trustStamp, { waitMs: lease.waitMs }), { 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) {+function fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPath(root, LOG) } = {}) {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);+ const { isGreen, output, seconds, profile, profilePath } = runProfiledShell(root, config.gate, { waitMs, profileFile: `${log}.profile.json` });writeFileSync(log, output);if (isGreen && before !== null && committedTree(root) === before) writeFileSync(gitPath(root, STAMP), `${before}\n`);- return { isGreen, isCached: false, output, seconds, log };+ return { isGreen, isCached: false, output, seconds, log, profile, profilePath };}/** Quote a fixed executable or selected path without permitting shell expansion. */@@ -180,24 +270,45 @@ function commandWord(value) {export async function runSubmitGate(root, config, { base, trunk, 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, trunk, changed });- return await withGateSlot(root, () => {- const criterion = check ? runShell(root, check) : { isGreen: true, output: '', seconds: 0 };- const receipt = { command: check, green: criterion.isGreen, seconds: criterion.seconds, checked: Boolean(check) };+ return await withGateSlot(root, (lease) => {+ const startedAt = Date.now();const log = gitPath(root, 'pullboard-submit.log');+ const checkLog = `${log}.check.log`;+ const proofLog = `${log}.proof.log`;+ const criterion = check ? runProfiledShell(root, check, {+ waitMs: lease.waitMs, profileFile: `${checkLog}.profile.json`,+ }) : { isGreen: true, output: '', seconds: 0 };+ if (check) writeFileSync(checkLog, safeLog(criterion.output), { mode: 0o600 });+ const receipt = { command: check, green: criterion.isGreen, seconds: criterion.seconds, checked: Boolean(check),+ ...(check ? { log: checkLog, profilePath: criterion.profilePath, profile: criterion.profile } : {}) };+ /** Persist the whole submission's wall time and queue wait once, alongside its combined raw log. */+ const finish = (proof) => {+ const profilePath = `${log}.profile.json`;+ const profiles = [criterion.profile, proof.profile].filter(Boolean);+ const profile = writeTimingProfile(profilePath, {+ waitMs: lease.waitMs, wallMs: Math.max(0, Date.now() - startedAt),+ files: profiles.flatMap(value => value.files), tests: profiles.flatMap(value => value.tests),+ });+ return { ...proof, log, seconds: criterion.seconds + proof.seconds, ...selection, check: receipt,+ profile, profilePath, proofProfilePath: proof.profilePath, proofLog: proof.log };+ };if (!criterion.isGreen) {writeFileSync(log, criterion.output);- return { isGreen: false, isCached: false, output: criterion.output, seconds: criterion.seconds, log, ...selection, check: receipt };+ return finish({ isGreen: false, isCached: false, output: criterion.output, seconds: 0, log: '' });}+ // The proof already owns this lease: its phase profile has no additional queue wait.+ const proofWait = check ? 0 : lease.waitMs;let proof;- if (selection.full) proof = fullGateRun(root, config);- else if (!selection.files.length) proof = { isGreen: true, output: '', seconds: 0, isCached: false, log };+ if (selection.full) proof = fullGateRun(root, config, false, { waitMs: proofWait, log: proofLog });+ 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 };+ proof = { ...runProfiledShell(root, command, { waitMs: proofWait, profileFile: `${proofLog}.profile.json` }), isCached: false, log: proofLog };+ writeFileSync(proofLog, proof.output);}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 };+ return finish(proof);}, { onWait });}@@ -205,18 +316,35 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,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);+ const timings = timingDigest(gate.profile);+ const detail = timings ? `\n${timings}\ntiming profile: ${gate.profilePath}` : '';+ const result = gate.isGreen && !gate.full ? `affected tests green in ${gate.seconds}s${detail}` : gateReport(gate);return `${check}; ${selection}; ${result}`;}+/** Show the ten slowest files, preserving actual Node timings rather than parsing TAP titles.+ * @param {{ files?: Array<{path: string, durationMs: number}> }|null} profile+ * @returns {string}+ */+export function timingDigest(profile) {+ if (!profile?.files?.length) return '';+ const rows = [...profile.files].filter(file => typeof file.path === 'string' && Number.isFinite(file.durationMs) && file.durationMs >= 0).sort((left, right) => right.durationMs - left.durationMs).slice(0, 10);+ return `slowest test files:\n${rows.map(file => ` ${file.path}: ${(file.durationMs / 1000).toFixed(2)}s`).join('\n')}`;+}+/*** What an agent sees of a gate run (V10): one line when green; when red, the digest and where the* whole output is.*- * @param {{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string }} gate+ * @param {{ isGreen: boolean, isCached: boolean, output: string, seconds: number, log: string, profile?: object, profilePath?: string }} gate* @returns {string}*/export function gateReport(gate) {- if (gate.isGreen) return gate.isCached ? 'gate green (this tree already passed)' : `gate green in ${gate.seconds}s`;- return `gate red in ${gate.seconds}s:\n${digestOf(gate.output).replace(/^/gm, ' ')}\nthe whole output is in ${gate.log}`;+ const timings = timingDigest(gate.profile);+ const profilePath = timings && gate.profilePath ? `\ntiming profile: ${gate.profilePath}` : '';+ if (gate.isGreen) {+ const summary = gate.isCached ? 'gate green (this tree already passed)' : `gate green in ${gate.seconds}s`;+ return timings ? `${summary}\n${timings}${profilePath}` : summary;+ }+ return `gate red in ${gate.seconds}s:\n${digestOf(gate.output).replace(/^/gm, ' ')}\n${timings ? `${timings}\n` : ''}the whole output is in ${gate.log}${profilePath}`;}diff --git a/src/resources.js b/src/resources.jsindex 8c1beff7..df64faf9 100644--- a/src/resources.js+++ b/src/resources.js@@ -162,7 +162,7 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr* Join the queue, preserving FIFO within landing, ordinary-gate, and item-check classes.** @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.- * @returns {Promise<{ name: string, scope: string, token: string, release: () => void, renew: () => void }>}+ * @returns {Promise<{ name: string, scope: string, token: string, waitMs: number, release: () => void, renew: () => void }>}*/export async function takeResource(options) {const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;@@ -174,6 +174,7 @@ export async function takeResource(options) {const file = databaseFile(scope, root);const db = open(file);const token = randomUUID();+ const requestedAt = Date.now();const pid = process.pid;const agent = options.agent ?? process.env.PULLBOARD_AGENT ?? `pid-${pid}`;const started = processStarted(pid);@@ -243,7 +244,7 @@ export async function takeResource(options) {throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);}};- return { name, scope, token, release, renew };+ return { name, scope, token, waitMs: Math.max(0, Date.now() - requestedAt), release, renew };}options.onWait?.(acquired.state);await pause(POLL_MS);diff --git a/src/trusted-policy.js b/src/trusted-policy.jsindex 90f1ae3b..44adeea9 100644--- a/src/trusted-policy.js+++ b/src/trusted-policy.js@@ -1,10 +1,10 @@/** Coordinator policy and immutable submission checks cannot come from a builder's candidate [V4,V16,L3,M3]. */import { randomUUID } from 'node:crypto';import { spawnSync } from 'node:child_process';-import { digestOf } from './gate.js';-import { closeSync, existsSync, mkdtempSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeSync } from 'node:fs';+import { digestOf, writeTimingProfile } from './gate.js';+import { closeSync, existsSync, mkdtempSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, writeSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { basename, dirname, join } from 'node:path';import { StringDecoder } from 'node:string_decoder';import { fileURLToPath } from 'node:url';import { configFromSource } from './config.js';@@ -125,8 +125,12 @@ export function frozenCheck(item) {return frozen?.check ?? (item.item_frozen ? '' : item.item_check ?? '');}-/** Run the frozen check at the exact submitted commit in a private clone, leaving live worktrees untouched. */-export function checkAtCommit(root, item) {+/** Run the frozen check at the exact submitted commit in a private clone, leaving live worktrees untouched.+ * @param {string} root+ * @param {object} item+ * @param {{ waitMs?: number }} [options] - Queue wait before the private check started.+ */+export function checkAtCommit(root, item, { waitMs = 0 } = {}) {const command = frozenCheck(item);if (!command) return { state: 'pass', green: true, checked: false, report: '' };let config;@@ -140,16 +144,21 @@ export function checkAtCommit(root, item) {mkdirSync(home, { mode: 0o700 });const verifierHome = process.env.HOME ?? process.env.USERPROFILE;const npmCache = process.env.npm_config_cache ?? join(verifierHome ?? home, '.npm');- const env = { ...cleanGitEnvironment(), HOME: home, PULLBOARD_HOME: join(home, '.pullboard'), PULLBOARD_MACHINE_HOME: join(home, 'machine'), GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', npm_config_cache: npmCache };+ const timingEventsPath = join(scratch, 'check-timings.events.json');+ const env = { ...cleanGitEnvironment(), HOME: home, PULLBOARD_HOME: join(home, '.pullboard'), PULLBOARD_MACHINE_HOME: join(home, 'machine'), GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1', npm_config_cache: npmCache, PULLBOARD_TEST_TIMING_PROFILE: timingEventsPath };delete env.PULLBOARD_RELAY_TOKEN;let installOutput = '';let checkOutput = '';+ const checkStartedAt = Date.now();let installLogPath = '';let checkLogPath = '';+ let timingProfile = { files: [], tests: [] };/** Format one completed check phase with the private captures and durable artifact locations. */- const finish = (state, stage) => checkResult(state, stage, installOutput, checkOutput, {- root, item, installLogPath, checkLogPath,- });+ const finish = (state, stage) => {+ const events = readTimingProfiles(timingEventsPath);+ timingProfile = { ...events, wallMs: Math.max(0, Date.now() - checkStartedAt) };+ return checkResult(state, stage, installOutput, checkOutput, { root, item, installLogPath, checkLogPath, timingProfile, waitMs });+ };try {const common = policyGit(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();const clone = spawnSync('git', ['clone', '--quiet', '--shared', '--no-checkout', common, copy], { env, stdio: 'ignore' });@@ -176,7 +185,10 @@ export function checkAtCommit(root, item) {if (run.status === null) return finish('unverified', 'check could not start (CHECK_RUNNER)');return finish(run.status === 0 ? 'pass' : 'red', run.status === 0 ? 'check' : `check failed (exit ${run.status})`);} catch { return finish('unverified', 'check could not complete'); }- finally { rmSync(scratch, { recursive: true, force: true }); }+ finally {+ removeTimingProfiles(timingEventsPath);+ rmSync(scratch, { recursive: true, force: true });+ }}/** Run one shell command in a bounded private process group and capture its combined output. */@@ -202,6 +214,31 @@ function runPrivateCommand(root, env, command, timeout, logPath) {}}+/** Read every reporter invocation produced by this private check, including nested npm scripts.+ * @param {string} prefix+ * @returns {{ files: Array<object>, tests: Array<object> }}+ */+function readTimingProfiles(prefix) {+ const directory = dirname(prefix);+ const base = `${basename(prefix)}.`;+ let names = [];+ try { names = readdirSync(directory).filter(name => name.startsWith(base) && name.endsWith('.json')); } catch { return { files: [], tests: [] }; }+ const profiles = [];+ for (const name of names) {+ try { profiles.push(JSON.parse(readFileSync(join(directory, name), 'utf8'))); } catch { /* Ignore a reporter interrupted with its process. */ }+ }+ return { files: profiles.flatMap(profile => Array.isArray(profile.files) ? profile.files : []), tests: profiles.flatMap(profile => Array.isArray(profile.tests) ? profile.tests : []) };+}++/** Remove the private reporter artifacts before the scratch clone is discarded.+ * @param {string} prefix+ */+function removeTimingProfiles(prefix) {+ const directory = dirname(prefix);+ const base = `${basename(prefix)}.`;+ try { for (const name of readdirSync(directory)) if (name.startsWith(base) && name.endsWith('.json')) rmSync(join(directory, name), { force: true }); } catch { /* No reporter artifacts were created. */ }+}+const CHECK_LOG_READ_BYTES = 32 * 1024;const CHECK_LINE_SCAN_LIMIT = 64 * 1024;const CHECK_OVERSIZED_LINE = '[redacted output line exceeds 64 KiB safe-scan limit]';@@ -315,7 +352,7 @@ function streamSanitizedLog(path, fallback, label, writeArtifact) {}/** Persist a sanitized full diagnostic outside the temporary checkout so a refusal can name it. */-function checkResult(state, stage, installCapture, checkCapture, { root = '', item = {}, installLogPath = '', checkLogPath = '' } = {}) {+function checkResult(state, stage, installCapture, checkCapture, { root = '', item = {}, installLogPath = '', checkLogPath = '', timingProfile = null, waitMs = 0 } = {}) {const boundedInstall = secretScanned(installCapture, 'check install capture');const boundedCheck = secretScanned(checkCapture, 'frozen check capture');const install = digestOf(boundedInstall) || '(no output)';@@ -324,7 +361,7 @@ function checkResult(state, stage, installCapture, checkCapture, { root = '', itlet outputPath = null;let outputError = null;let artifactFd = null;- if (state !== 'pass' && root) {+ if (root && (state !== 'pass' || checkLogPath || timingProfile)) {try {const common = policyGit(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']).trim();const directory = join(common, 'pullboard', 'check-output');@@ -360,15 +397,23 @@ function checkResult(state, stage, installCapture, checkCapture, { root = '', it};let installLog;let checkLog;+ let profilePath = null;try {installLog = writePhase('install', installLogPath, installCapture, 'check install output', '(no output)');appendArtifact('\n');checkLog = writePhase('check', checkLogPath, checkCapture, 'frozen check output',!checkLogPath && !checkCapture ? '(not run or no output)' : '(no output)');if (artifactFd !== null) closeSync(artifactFd);+ if (outputPath && timingProfile) {+ profilePath = `${outputPath}.profile.json`;+ const profile = writeTimingProfile(profilePath, { version: 1, waitMs: Math.max(0, Math.round(waitMs)), wallMs: timingProfile.wallMs ?? null, files: timingProfile.files ?? [], tests: timingProfile.tests ?? [] });+ timingProfile = profile;+ }} catch (error) {if (artifactFd !== null) { try { closeSync(artifactFd); } catch { /* The descriptor may already be closed. */ } }if (outputPath) { try { rmSync(outputPath, { force: true }); } catch { /* Keep the refusal typed if cleanup also fails. */ } }+ if (profilePath) { try { rmSync(profilePath, { force: true }); } catch { /* Keep the refusal typed if cleanup also fails. */ } }+ profilePath = null;outputPath = null;outputError = error.code ?? 'CHECK_DIAGNOSTIC';installLog = streamSanitizedLog('', installCapture, 'check install capture', null);@@ -380,5 +425,5 @@ function checkResult(state, stage, installCapture, checkCapture, { root = '', itconst failure = state === 'red' ? 'failed' : /timed out/u.test(stage) ? 'timed out': /could not start/u.test(stage) ? "couldn't start" : state === 'unverified' ? 'could not be verified' : 'passed';const output = `install output:\n${boundedInstall || '(no output)'}\ncheck output:\n${boundedCheck || '(not run or no output)'}`;- return { state, green: state === 'pass', checked: true, stage, failure, report, output, outputTail, outputPath, outputError };+ return { state, green: state === 'pass', checked: true, stage, failure, report, output, outputTail, outputPath, outputError, profilePath, profile: timingProfile ? { ...timingProfile, profilePath } : null };}diff --git a/test/gate-profile.test.js b/test/gate-profile.test.jsnew file mode 100644index 00000000..2fd9b22a--- /dev/null+++ b/test/gate-profile.test.js@@ -0,0 +1,522 @@+/** Real gate, item-check and verifier profiles use Node's test events [C7,V10]. */+import assert from 'node:assert/strict';+import { execFileSync, spawn, spawnSync } from 'node:child_process';+import { once } from 'node:events';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { after, test } from 'node:test';+import { listResources } from '../src/resources.js';+import { checkAtCommit } from '../src/trusted-policy.js';+import * as store from '../src/board.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+const RUNNER = resolve(import.meta.dirname, '../bin/run-tests.js');+const RESOURCE_MODULE = resolve(import.meta.dirname, '../src/resources.js');+const TEMP = [];+const SPEC = '# Demo\n\n## G · Goals\n- G1 [approved, must] The page renders. | gate: web test\n- G2 [approved, must] The API answers. | gate: api test\n';+const CONFIG = { gate: 'true', spec: 'SPEC.md', verify: 'any', lease: '2h', lanes: { web: { owns: ['web/'], specs: ['G1'] }, api: { owns: ['api/'], specs: ['G2'] } }, shared: ['docs/'] };+const FAKE_SECRET = 'ghp_' + 'A'.repeat(36);++after(() => { for (const dir of TEMP) rmSync(dir, { recursive: true, force: true }); });++/** Create an isolated CLI sandbox and real local Git helpers. */+function sandbox() {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-profile-')));+ TEMP.push(dir);+ const home = join(dir, 'home');+ mkdirSync(home, { recursive: true });+ const shims = join(dir, 'bin');+ mkdirSync(shims);+ writeFileSync(join(shims, 'pullboard'), `#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(BIN)} "$@"\n`);+ chmodSync(join(shims, 'pullboard'), 0o755);+ const env = {+ ...process.env,+ PATH: process.env.PATH,+ 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: home,+ PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),+ };+ for (const key of Object.keys(env)) if (key.startsWith('GIT_') && !['GIT_CONFIG_GLOBAL', 'GIT_CONFIG_NOSYSTEM', 'GIT_AUTHOR_NAME', 'GIT_AUTHOR_EMAIL', 'GIT_COMMITTER_NAME', 'GIT_COMMITTER_EMAIL'].includes(key)) delete env[key];+ const git = (cwd, ...args) => execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: 'pipe' }).trim();+ const run = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8', timeout: 60_000 });+ return { dir, home, shims, env, git, run };+}++/** Make installed Git hooks resolve the real private CLI after repository initialization. */+function installPrivatePullboardPath(box) {+ const entries = (box.env.PATH ?? '').split(':');+ box.env.PATH = [box.shims, ...entries.filter(entry => entry !== box.shims)].join(':');+}++/** Create a coordinator repo configured with one actual project gate. */+function gateRepo(box, gate) {+ const repo = join(box.dir, 'gate-repo');+ mkdirSync(repo);+ box.git(repo, 'init', '-q', '-b', 'main');+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate }));+ writeFileSync(join(repo, 'SPEC.md'), '# Demo\n\n## G · Goals\n- G1 [approved, must] It works. | gate: test\n');+ box.git(repo, 'add', '-A');+ box.git(repo, 'commit', '-q', '-m', 'chore: configure timing gate');+ assert.equal(box.run(repo, 'add', 'coordinator', 'Work').status, 0);+ assert.equal(box.run(repo, 'claim', '1').status, 0);+ return { repo, ...box };+}++/** Create a project repo and one joined web worktree for CLI item-check fixtures. */+function project(box = sandbox()) {+ const repo = join(box.dir, 'project-repo');+ mkdirSync(repo);+ box.git(repo, 'init', '-q', '-b', 'main');+ assert.equal(box.run(repo, 'init').status, 0);+ installPrivatePullboardPath(box);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify(CONFIG, null, 2));+ writeFileSync(join(repo, 'SPEC.md'), SPEC);+ box.git(repo, 'add', '-A');+ box.git(repo, 'commit', '-q', '-m', 'chore: set up profile project');+ const web = join(box.dir, 'web-1');+ box.git(repo, 'worktree', 'add', '-q', web, '-b', 'web/one');+ assert.match(box.run(web, 'join', 'web').stdout, /joined as web-1/);+ return { ...box, repo, web };+}++/** Commit one actual lane change without involving board mutation. */+function featureCommit(box, cwd) {+ box.git(cwd, 'add', '-A');+ const tree = box.git(cwd, 'write-tree');+ const commit = box.git(cwd, 'commit-tree', tree, '-p', 'HEAD', '-m', 'feat(web): add timing fixture [G1]');+ box.git(cwd, 'update-ref', 'HEAD', commit);+ return commit;+}++/** Hold the only private machine gate slot until the real gate queues behind it. */+async function occupyGateSlot(box, repo) {+ const source = `import { takeResource } from ${JSON.stringify(RESOURCE_MODULE)};\nconst lease = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: ${JSON.stringify(repo)}, agent: 'profile-test-holder' });\nconsole.log('ready');\nfor await (const line of process.stdin) if (line.trim() === 'release') { lease.release(); break; }`;+ const child = spawn(process.execPath, ['--input-type=module', '-e', source], { cwd: repo, env: box.env, stdio: ['pipe', 'pipe', 'pipe'] });+ const ready = new Promise((resolveReady, reject) => {+ const timer = setTimeout(() => reject(new Error('gate slot holder did not start')), 10_000);+ child.once('error', error => { clearTimeout(timer); reject(error); });+ child.stdout.once('data', data => {+ clearTimeout(timer);+ if (String(data).includes('ready')) resolveReady();+ else reject(new Error(`unexpected gate holder output: ${data}`));+ });+ });+ await ready;+ return child;+}++test('a timing profile records two runner invocations and the real gate-slot wait [C7,V10]', async () => {+ const box = sandbox();+ const slowName = `slow timing profile ${FAKE_SECRET}`;+ const fixture = gateRepo(box, 'true');+ mkdirSync(join(fixture.repo, 'timed'));+ writeFileSync(join(fixture.repo, 'timed/fast.test.js'), "import { test } from 'node:test'; test('fast timing profile sample', async t => { await t.test('nested timing profile sample', () => {}); });\n");+ writeFileSync(join(fixture.repo, 'timed/slow.test.js'), `import { test } from 'node:test'; test(${JSON.stringify(slowName)}, async () => new Promise(resolve => setTimeout(resolve, 150)));\n`);+ writeFileSync(join(fixture.repo, 'timed/fail.test.js'), "import assert from 'node:assert/strict'; import { test } from 'node:test'; test('failing timing profile sample', () => assert.equal(1, 2));\n");+ box.git(fixture.repo, 'add', 'timed');+ box.git(fixture.repo, 'commit', '-q', '-m', 'test: add timing profile fixtures');+ const runner = `'${RUNNER.replaceAll("'", "'\\''")}'`;+ const command = `node ${runner} timed/fast.test.js && node ${runner} timed/slow.test.js`;+ writeFileSync(join(fixture.repo, 'pullboard.json'), JSON.stringify({ gate: command }));+ box.git(fixture.repo, 'add', 'pullboard.json');+ box.git(fixture.repo, 'commit', '-q', '-m', 'test: configure profiled runner gate');+ mkdirSync(box.home, { recursive: true });+ writeFileSync(join(box.home, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const holder = await occupyGateSlot(box, fixture.repo);+ const holderExited = once(holder, 'exit');+ const gate = spawn(process.execPath, [BIN, 'gate'], { cwd: fixture.repo, env: box.env, stdio: ['ignore', 'pipe', 'pipe'] });+ const gateExited = once(gate, 'exit');+ const gateOutput = [];+ gate.stdout.on('data', chunk => gateOutput.push(chunk));+ gate.stderr.on('data', chunk => gateOutput.push(chunk));+ let result;+ const started = Date.now();+ const previousHome = process.env.PULLBOARD_HOME;+ process.env.PULLBOARD_HOME = box.home;+ let queued = false;+ let holderReleased = false;+ try {+ for (let attempt = 0; attempt < 100; attempt += 1) {+ queued = listResources({ scope: 'machine', root: fixture.repo }).find(resource => resource.name === 'gate')?.line.some(waiter => waiter.agent !== 'profile-test-holder') ?? false;+ if (queued) break;+ await new Promise(resolve => setTimeout(resolve, 25));+ }+ if (queued) await new Promise(resolve => setTimeout(resolve, 300));+ if (holder.exitCode === null) {+ holderReleased = true;+ holder.stdin.end('release\n');+ }+ let gateTimer;+ const timeout = new Promise((_, reject) => {+ gateTimer = setTimeout(() => reject(new Error('private gate did not finish within 60 seconds')), 60_000);+ });+ let status;+ try { [status] = await Promise.race([gateExited, timeout]); }+ finally { clearTimeout(gateTimer); }+ result = { status, stdout: Buffer.concat(gateOutput).toString('utf8'), stderr: '' };+ } finally {+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (!holderReleased && holder.exitCode === null) holder.stdin.end('release\n');+ if (holder.exitCode === null) {+ await Promise.race([holderExited.catch(() => {}), new Promise(resolve => setTimeout(resolve, 2_000))]);+ }+ if (holder.exitCode === null) holder.kill('SIGTERM');+ if (gate.exitCode === null && gate.signalCode === null) gate.kill('SIGTERM');+ await Promise.allSettled([holderExited, gateExited]);+ }+ assert.ok(queued, 'the gate joined the real private machine queue');+ const elapsedMs = Date.now() - started;+ assert.equal(result.status, 0, result.stderr);+ assert.match(result.stdout, /slowest test files:[\s\S]*slow\.test\.js:/);+ const profilePath = /timing profile: ([^\n]+)/.exec(result.stdout)?.[1];+ assert.ok(profilePath, result.stdout);+ assert.ok(profilePath.endsWith('pullboard-gate.log.profile.json'), 'the full gate profile is paired with its canonical raw log');+ assert.ok(existsSync(profilePath.slice(0, -'.profile.json'.length)));+ const profile = JSON.parse(readFileSync(profilePath, 'utf8'));+ assert.equal(statSync(profilePath).mode & 0o777, 0o600);+ assert.ok(profile.waitMs >= 100, `recorded queue wait ${profile.waitMs}ms`);+ assert.ok(profile.wallMs > 0 && elapsedMs + 30 >= profile.waitMs + profile.wallMs, `${elapsedMs}ms total vs ${profile.waitMs}ms wait + ${profile.wallMs}ms wall`);+ assert.deepEqual(profile.files.map(file => file.path).sort(), ['timed/fast.test.js', 'timed/slow.test.js']);+ assert.deepEqual(profile.tests.map(test => test.name).sort(), ['[redacted GitHub token]', 'fast timing profile sample', 'nested timing profile sample'].sort());+ assert.ok(profile.files.find(file => file.path.endsWith('slow.test.js')).durationMs >= 130);+ assert.ok(profile.tests.find(test => test.name === '[redacted GitHub token]').durationMs >= 130, 'the actual slow test duration is retained');+ assert.match(result.stdout.split('slowest test files:\n')[1]?.split('\n')[0] ?? '', /^\s*timed\/slow\.test\.js:/);+ assert.ok(!result.stdout.includes(FAKE_SECRET));+ assert.ok(!readFileSync(profilePath, 'utf8').includes(FAKE_SECRET));+ assert.match(readFileSync(profilePath, 'utf8'), /redacted GitHub token/);++ writeFileSync(join(fixture.repo, 'pullboard.json'), JSON.stringify({ gate: `${command} && node ${runner} timed/fail.test.js` }));+ box.git(fixture.repo, 'add', 'pullboard.json');+ box.git(fixture.repo, 'commit', '-q', '-m', 'test: configure red profiled runner gate');+ const red = box.run(fixture.repo, 'gate');+ assert.equal(red.status, 1, red.stdout);+ assert.match(red.stdout, /gate red in \d+s:[\s\S]*slowest test files:[\s\S]*slow\.test\.js:/);+ const redProfilePath = /timing profile: ([^\n]+)/.exec(red.stdout)?.[1];+ assert.ok(redProfilePath, red.stdout);+ const redProfile = JSON.parse(readFileSync(redProfilePath, 'utf8'));+ assert.equal(statSync(redProfilePath).mode & 0o777, 0o600);+ assert.equal(redProfile.tests.length, 4);+ assert.equal(redProfile.tests.find(test => test.name === 'failing timing profile sample').passed, false);+ assert.match(red.stdout.split('slowest test files:\n')[1]?.split('\n')[0] ?? '', /^\s*timed\/slow\.test\.js:/);+});++test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,V10]', () => {+ const box = project();+ const runner = `'${RUNNER.replaceAll("'", "'\\''")}'`;+ const command = `node ${runner} .timed/fast.test.js .timed/slow.test.js`;+ mkdirSync(join(box.repo, '.timed'));+ writeFileSync(join(box.repo, '.timed/fast.test.js'), "import { test } from 'node:test'; test('fast timing profile check', () => {});\n");+ writeFileSync(join(box.repo, '.timed/slow.test.js'), "import { test } from 'node:test'; test('slow timing profile check', async () => new Promise(resolve => setTimeout(resolve, 40)));\n");+ box.git(box.repo, 'add', '.timed');+ box.git(box.repo, 'commit', '-q', '-m', 'test: add timing profile check fixtures');+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');+ assert.equal(box.run(box.repo, 'add', 'web', 'Profiled check', '--specs', 'G1', '--criterion', 'the runner writes timings', '--check', command).status, 0);+ assert.equal(box.run(box.web, 'claim', '1').status, 0);+ mkdirSync(join(box.web, 'web'));+ writeFileSync(join(box.web, 'web/timing.txt'), 'profiled');+ const commit = featureCommit(box, box.web);++ const direct = box.run(box.web, 'check', '--yes');+ assert.equal(direct.status, 0, direct.stderr);+ assert.match(direct.stdout, /slowest test files:[\s\S]*slow\.test\.js:/);+ const directPath = /timing profile: ([^\n]+)/.exec(direct.stdout)?.[1];+ assert.ok(directPath, direct.stdout);+ assert.equal(statSync(directPath).mode & 0o777, 0o600);+ const directProfile = JSON.parse(readFileSync(directPath, 'utf8'));+ assert.ok(directProfile.files.some(file => file.path.endsWith('.timed/slow.test.js')));+ assert.ok(directProfile.tests.find(test => test.name === 'slow timing profile check').durationMs >= 30);+ assert.ok(existsSync(directPath.slice(0, -'.profile.json'.length) + '.log'));++ assert.equal(box.run(box.web, 'submit', '1').status, 0);+ const review = join(box.dir, 'timing-profile-review');+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);+ assert.match(box.run(review, 'join', 'api').stdout, /joined as api/);+ const accepted = box.run(review, 'verify', '1', 'accept', '--note', 'timings were retained');+ assert.equal(accepted.status, 0, accepted.stderr);+ assert.match(accepted.stdout, /slowest test files:[\s\S]*slow\.test\.js:/);+ const verifyPath = /timing profile: ([^\n]+)/.exec(accepted.stdout)?.[1];+ assert.ok(verifyPath, accepted.stdout);+ assert.ok(verifyPath.endsWith('.log.profile.json'));+ assert.equal(statSync(verifyPath).mode & 0o777, 0o600);+ assert.equal(statSync(verifyPath.slice(0, -'.profile.json'.length)).mode & 0o777, 0o600);+ const verified = JSON.parse(readFileSync(verifyPath, 'utf8'));+ assert.ok(verified.waitMs >= 0 && verified.wallMs > 0);+ assert.ok(verified.files.some(file => file.path.endsWith('.timed/slow.test.js')));+ assert.ok(verified.tests.find(test => test.name === 'slow timing profile check').durationMs >= 30);++ assert.equal(box.run(box.repo, 'add', 'web', 'Shell-only check', '--specs', 'G1', '--criterion', 'shell-only checks still save timings', '--check', 'true').status, 0);+ assert.equal(box.run(box.web, 'claim', '2').status, 0);+ const shellCheck = box.run(box.web, 'check', '2', '--yes');+ assert.equal(shellCheck.status, 0, shellCheck.stderr);+ const gitDirectory = box.git(box.web, 'rev-parse', '--absolute-git-dir');+ const shellProfileName = readdirSync(gitDirectory).find(name => name.startsWith('pullboard-check-2-') && name.endsWith('.profile.json'));+ assert.ok(shellProfileName, 'a shell-only direct check persists its timing profile');+ const shellProfilePath = join(gitDirectory, shellProfileName);+ const shellProfile = JSON.parse(readFileSync(shellProfilePath, 'utf8'));+ assert.equal(statSync(shellProfilePath).mode & 0o777, 0o600);+ assert.ok(existsSync(shellProfilePath.slice(0, -'.profile.json'.length) + '.log'));+ assert.deepEqual(shellProfile.files, []);+ assert.deepEqual(shellProfile.tests, []);+ assert.ok(shellProfile.wallMs > 0);++ writeFileSync(join(box.web, 'web/shell-only.txt'), 'shell only');+ const shellCommit = featureCommit(box, box.web);+ assert.equal(box.run(box.web, 'submit', '2').status, 0);++ const board = store.openBoard(join(box.repo, '.git/pullboard/board.sqlite'));+ let item;+ try { item = store.getItem(board, 2); }+ finally { store.closeBoard(board); }+ const frozen = JSON.parse(item.item_frozen);+ const shellVerify = checkAtCommit(box.repo, { ...item, item_commit: shellCommit, item_frozen: JSON.stringify({ ...frozen, check: 'true' }) }, { waitMs: 17 });+ assert.equal(shellVerify.state, 'pass');+ assert.deepEqual(shellVerify.profile.files, []);+ assert.deepEqual(shellVerify.profile.tests, []);+ assert.equal(shellVerify.profile.waitMs, 17);+ assert.ok(shellVerify.profile.wallMs > 0 && existsSync(shellVerify.profilePath));+});+++test('a timing profile keeps every selected file while its digest names only ten [C7,V10]', () => {+ const box = sandbox();+ const fixture = gateRepo(box, 'true');+ mkdirSync(join(fixture.repo, 'timed'));+ const paths = Array.from({ length: 12 }, (_, index) => `timed/selected-${index}.test.js`);+ for (const [index, path] of paths.entries()) {+ writeFileSync(join(fixture.repo, path), `import { test } from 'node:test'; test('selected timing case ${index}', () => {});\n`);+ }+ writeFileSync(join(fixture.repo, 'timed/unselected.test.js'), "throw new Error('an unselected file must not run');\n");+ const command = `node '${RUNNER.replaceAll("'", "'\\''")}' ${paths.join(' ')}`;+ writeFileSync(join(fixture.repo, 'pullboard.json'), JSON.stringify({ gate: command }));+ box.git(fixture.repo, 'add', '-A');+ box.git(fixture.repo, 'commit', '-q', '-m', 'test: select twelve timing files');+ const result = box.run(fixture.repo, 'gate');+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const profilePath = /timing profile: ([^\n]+)/.exec(result.stdout)?.[1];+ assert.ok(profilePath, result.stdout);+ assert.ok(profilePath.endsWith('pullboard-gate.log.profile.json'), 'the full gate profile is paired with its canonical raw log');+ assert.ok(existsSync(profilePath.slice(0, -'.profile.json'.length)));+ const profile = JSON.parse(readFileSync(profilePath, 'utf8'));+ assert.deepEqual(profile.files.map(file => file.path).sort(), paths.slice().sort());+ assert.equal(profile.tests.length, paths.length, 'all selected top-level cases are recorded exactly once');+ const digest = result.stdout.split('slowest test files:\n')[1].split('\ntiming profile:')[0].split('\n');+ assert.equal(digest.length, 10, 'the digest is bounded to ten files');+ const slowest = profile.files.slice().sort((left, right) => right.durationMs - left.durationMs).slice(0, 10);+ assert.deepEqual(digest, slowest.map(file => ` ${file.path}: ${(file.durationMs / 1000).toFixed(2)}s`));++ writeFileSync(join(fixture.repo, 'timed/crash.test.js'), 'process.exit(7);\n');+ writeFileSync(join(fixture.repo, 'pullboard.json'), JSON.stringify({ gate: `node '${RUNNER.replaceAll("'", "'\\''")}' timed/crash.test.js` }));+ box.git(fixture.repo, 'add', '-A');+ box.git(fixture.repo, 'commit', '-q', '-m', 'test: profile a crashing test file');+ const crashed = box.run(fixture.repo, 'gate');+ assert.equal(crashed.status, 1, crashed.stdout);+ const crashPath = /timing profile: ([^\n]+)/.exec(crashed.stdout)?.[1];+ assert.ok(crashPath, crashed.stdout);+ const crashProfile = JSON.parse(readFileSync(crashPath, 'utf8'));+ assert.deepEqual(crashProfile.files.map(file => file.path), ['timed/crash.test.js']);+ assert.ok(crashProfile.files[0].durationMs > 0, 'a crashed process has its measured file duration');+ assert.deepEqual(crashProfile.tests, [], 'the process wrapper is not an actual test case');+});++/** Start a private submit process and collect its separate streams until close. */+function startProfiledSubmit(box, cwd) {+ const child = spawn(process.execPath, [BIN, 'submit', '1', '--json'], {+ cwd, env: box.env, stdio: ['ignore', 'pipe', 'pipe'],+ });+ const stdout = [];+ const stderr = [];+ child.stdout.on('data', chunk => stdout.push(chunk));+ child.stderr.on('data', chunk => stderr.push(chunk));+ const finished = new Promise(resolveFinished => child.once('close', (code, signal) => resolveFinished({+ code, signal, stdout: Buffer.concat(stdout).toString('utf8'), stderr: Buffer.concat(stderr).toString('utf8'),+ })));+ return { child, finished };+}++/** Let one bounded timer settle while a private child or queue lease is cleaned up. */+function waitProfileCleanup(ms) {+ return new Promise(resolveCleanup => setTimeout(resolveCleanup, ms));+}++/** Copy the production runner's complete static import closure into the real fixture repo. */+function copyProfileRunner(box) {+ const source = resolve(import.meta.dirname, '..');+ mkdirSync(join(box.repo, 'bin'), { recursive: true });+ mkdirSync(join(box.repo, 'src'), { recursive: true });+ for (const file of ['bin/run-tests.js', 'bin/gate-profile-reporter.js', 'src/person.js', 'src/refused.js']) {+ writeFileSync(join(box.repo, file), readFileSync(join(source, file)));+ }+}++/** Run one real submission with an optional real machine-slot wait and await every owned child. */+async function runProfileSubmission(box, queue) {+ const holder = queue ? await occupyGateSlot(box, box.repo) : null;+ const holderExited = holder+ ? (holder.exitCode === null ? once(holder, 'exit') : Promise.resolve())+ : null;+ const submit = startProfiledSubmit(box, box.web);+ const priorHome = process.env.PULLBOARD_HOME;+ const startedAt = Date.now();+ let queued = false;+ let released = false;+ let result;+ process.env.PULLBOARD_HOME = box.home;+ try {+ if (holder) {+ for (let attempt = 0; attempt < 120; attempt += 1) {+ queued = listResources({ scope: 'machine', root: box.repo })+ .find(resource => resource.name === 'gate')?.line.some(waiter => waiter.agent !== 'profile-test-holder') ?? false;+ if (queued || submit.child.exitCode !== null) break;+ await waitProfileCleanup(25);+ }+ if (queued) await waitProfileCleanup(300);+ if (holder.exitCode === null) {+ released = true;+ holder.stdin.end('release\n');+ }+ }+ let timer;+ try {+ result = await Promise.race([+ submit.finished,+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('private profile submit exceeded 60 seconds')), 60_000); }),+ ]);+ } finally {+ clearTimeout(timer);+ }+ } finally {+ if (priorHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = priorHome;+ if (holder && holder.exitCode === null) {+ if (!released) holder.stdin.end('release\n');+ await Promise.race([holderExited, waitProfileCleanup(2_000)]);+ if (holder.exitCode === null) holder.kill('SIGTERM');+ if (holder.exitCode === null) await holderExited;+ }+ if (submit.child.exitCode === null && submit.child.signalCode === null) {+ submit.child.kill('SIGTERM');+ await submit.finished;+ }+ }+ return { result, queued, elapsedMs: Date.now() - startedAt };+}++test('a submit timing profile records both phases and one queue wait for selected and full proofs [C7,V4,V16]', async () => {+ for (const scenario of [+ { name: 'affected subset', full: false, queue: true },+ { name: 'full fallback', full: true, queue: false },+ ]) {+ const box = project();+ const trace = join(box.dir, `${scenario.name.replaceAll(' ', '-')}.trace`);+ box.env.PROFILE_TRACE = trace;+ mkdirSync(box.home, { recursive: true });+ writeFileSync(join(box.home, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const checkCommand = 'node bin/run-tests.js timed/check.test.js';+ const gateCommand = 'node bin/run-tests.js';+ writeFileSync(join(box.repo, 'package.json'), JSON.stringify({ type: 'module' }));+ copyProfileRunner(box);+ mkdirSync(join(box.repo, 'timed'), { recursive: true });+ mkdirSync(join(box.repo, 'api'), { recursive: true });+ mkdirSync(join(box.repo, 'web'), { recursive: true });+ writeFileSync(join(box.repo, 'timed/check.test.js'), [+ "import { appendFileSync } from 'node:fs';",+ "import { test } from 'node:test';",+ "test('frozen check profile sample [C7]', async () => {",+ " appendFileSync(process.env.PROFILE_TRACE, 'check\\n');",+ ' await new Promise(resolve => setTimeout(resolve, 70));',+ '});',+ ].join('\n') + '\n');+ writeFileSync(join(box.repo, 'web/value.js'), 'export const value = 7;\n');+ writeFileSync(join(box.repo, 'web/affected.test.js'), [+ "import assert from 'node:assert/strict';",+ "import { appendFileSync } from 'node:fs';",+ "import { test } from 'node:test';",+ "import { value } from './value.js';",+ "test('affected proof profile sample [C7]', () => {",+ " appendFileSync(process.env.PROFILE_TRACE, 'web\\n');",+ ' assert.equal(value, 7);',+ '});',+ ].join('\n') + '\n');+ writeFileSync(join(box.repo, 'api/untouched.test.js'), [+ "import assert from 'node:assert/strict';",+ "import { appendFileSync } from 'node:fs';",+ "import { test } from 'node:test';",+ "test('unaffected proof profile sample [C7]', () => {",+ " appendFileSync(process.env.PROFILE_TRACE, 'api\\n');",+ ' assert.equal(1, 1);',+ '});',+ ].join('\n') + '\n');+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate: gateCommand }, null, 2));+ box.git(box.repo, 'add', '-A');+ box.git(box.repo, 'commit', '-q', '-m', 'test: build isolated submit profile fixture');+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');+ const added = box.run(box.repo, 'add', 'web', `Profile ${scenario.name}`, '--specs', 'G1',+ '--criterion', 'submit profiles both check and proof', '--check', checkCommand, '--wait');+ assert.equal(added.status, 0, added.stderr || added.stdout);+ assert.equal(box.run(box.web, 'claim', '1').status, 0);+ writeFileSync(trace, ''); // Ignore the real --wait baseline execution in submission counts.+ writeFileSync(join(box.web, 'web/value.js'), 'export const value = 7; // changed lane module\n');+ if (scenario.full) writeFileSync(join(box.web, 'web/README.txt'), 'unsupported path forces the configured gate\n');+ featureCommit(box, box.web);++ const submission = await runProfileSubmission(box, scenario.queue);+ assert.equal(submission.result.code, 0, submission.result.stderr || submission.result.stdout);+ assert.equal(submission.queued, scenario.queue, `${scenario.name} observes only the planned real gate wait`);+ const receipt = JSON.parse(submission.result.stdout);+ const gate = receipt.gate;+ assert.equal(gate.green, true);+ assert.equal(gate.full, scenario.full);+ assert.equal(gate.check.green, true);+ assert.equal(gate.check.checked, true);+ assert.equal(gate.check.command, checkCommand);+ assert.equal(gate.reason === '', !scenario.full);+ if (scenario.full) assert.deepEqual(gate.files, ['api/untouched.test.js', 'timed/check.test.js', 'web/affected.test.js']);+ if (!scenario.full) assert.deepEqual(gate.files, ['web/affected.test.js']);+ if (scenario.full) assert.match(gate.reason, /web\/README\.txt/u);++ assert.ok(gate.check.log.endsWith('pullboard-submit.log.check.log'));+ assert.equal(gate.check.profilePath, `${gate.check.log}.profile.json`);+ assert.ok(existsSync(gate.check.log));+ assert.ok(gate.proofLog.endsWith('pullboard-submit.log.proof.log'));+ assert.equal(gate.proofProfilePath, `${gate.proofLog}.profile.json`);+ assert.ok(existsSync(gate.proofLog));+ assert.equal(gate.profilePath, `${gate.log}.profile.json`);+ assert.ok(existsSync(gate.log));++ const checkProfile = JSON.parse(readFileSync(gate.check.profilePath, 'utf8'));+ if (scenario.queue) assert.ok(checkProfile.waitMs >= 100, `actual queued check waited ${checkProfile.waitMs}ms`);+ const proofProfile = JSON.parse(readFileSync(gate.proofProfilePath, 'utf8'));+ const combined = JSON.parse(readFileSync(gate.profilePath, 'utf8'));+ assert.deepEqual(checkProfile.files.map(file => file.path), ['timed/check.test.js']);+ assert.ok(checkProfile.files[0].durationMs >= 50, 'the check profile retains the real slow check file duration');+ assert.equal(checkProfile.tests[0].name, 'frozen check profile sample [C7]');+ assert.ok(checkProfile.tests[0].durationMs >= 50);+ assert.deepEqual(proofProfile.files.map(file => file.path).sort(), scenario.full+ ? ['api/untouched.test.js', 'timed/check.test.js', 'web/affected.test.js']+ : ['web/affected.test.js']);+ assert.ok(proofProfile.files.every(file => file.durationMs > 0));+ assert.equal(proofProfile.waitMs, 0, 'the second phase reuses the submission lease instead of queueing again');+ assert.equal(combined.waitMs, checkProfile.waitMs, 'the combined profile records the real queue wait once');+ assert.ok(combined.wallMs >= checkProfile.wallMs + proofProfile.wallMs - 25,+ 'the combined wall time includes both measured phases without adding their queue waits');+ assert.ok(submission.elapsedMs + 50 >= combined.waitMs + combined.wallMs,+ `${submission.elapsedMs}ms total vs ${combined.waitMs}ms one wait + ${combined.wallMs}ms combined work`);+ assert.ok(combined.files.some(file => file.path === 'timed/check.test.js'));+ assert.ok(combined.files.some(file => file.path === 'web/affected.test.js'));+ if (scenario.full) assert.ok(combined.files.some(file => file.path === 'api/untouched.test.js'));++ const ran = readFileSync(trace, 'utf8').trim().split(/\r?\n/u).sort();+ assert.equal(ran.filter(line => line === 'check').length, scenario.full ? 2 : 1,+ 'the item check runs once; a full fallback also includes that file in its test suite');+ assert.equal(ran.filter(line => line === 'web').length, 1);+ assert.equal(ran.filter(line => line === 'api').length, scenario.full ? 1 : 0,+ 'unaffected files run only when selection correctly falls back to the full gate');+ }+});diff --git a/test/run-tests-reporter.test.js b/test/run-tests-reporter.test.jsindex ddba3e0d..a67b7482 100644--- a/test/run-tests-reporter.test.js+++ b/test/run-tests-reporter.test.js@@ -1,7 +1,7 @@/** Keep the production runner's report stable across Node versions and caller options [C7]. */import assert from 'node:assert/strict';import { spawnSync } from 'node:child_process';-import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs';+import { mkdtempSync, readdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';@@ -69,3 +69,41 @@ test('run-tests prints TAP on every Node version and keeps a caller reporter [C7assert.ok(!splitCallerReporter.childArgs.includes('--test-reporter=tap'), 'the default does not override the separate caller option');assert.doesNotMatch(splitCallerReporter.output, /^TAP version \d+/mu);});++/** Run the actual runner with timing output and a caller reporter enabled. */+function runProfileReporterFixture(t, reporterArgs = []) {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-run-tests-profile-reporter-'));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const fixture = join(root, 'profile-reporter.test.js');+ const profileBase = join(root, 'profile');+ writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' }));+ writeFileSync(fixture, "import { test } from 'node:test';\ntest('profile reporter fixture [C7]', () => {});\n");+ const result = spawnSync(process.execPath, [runner, ...reporterArgs, fixture], {+ cwd: root,+ env: { ...process.env, PULLBOARD_TEST_TIMING_PROFILE: profileBase },+ encoding: 'utf8',+ timeout: 15_000,+ });+ const profileName = readdirSync(root).find((name) => name.startsWith('profile.'));+ const rawProfile = profileName ? readFileSync(join(root, profileName), 'utf8') : '';+ assert.match(rawProfile, /^\{"files":/u, 'the private destination receives timing JSON');+ const profile = JSON.parse(rawProfile);+ return { result, output: `${result.stdout ?? ''}${result.stderr ?? ''}`, profile };+}++test('run-tests keeps caller reporter output visible beside a timing profile [C7]', (t) => {+ for (const reporterArgs of [+ ['--test-reporter=spec'],+ ['--test-reporter', 'spec'],+ ['--test-reporter=spec', '--test-reporter-destination=stdout'],+ ['--test-reporter', 'spec', '--test-reporter-destination', 'stdout'],+ ]) {+ const run = runProfileReporterFixture(t, reporterArgs);+ assert.equal(run.result.status, 0, run.output);+ assert.ok(run.profile, 'the timing profile is still written as JSON');+ assert.equal(run.profile.tests.length, 1);+ assert.equal(run.profile.tests[0].name, 'profile reporter fixture [C7]');+ assert.match(run.output, /ℹ tests 1/u, 'the caller’s spec reporter remains on stdout');+ assert.doesNotMatch(run.output, /^\{"files":/mu, 'profile JSON does not replace caller output');+ }+});