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.

fix(gate): profile the caller output unchanged [C7,V10]

Corey Olson66b44d9e807f
diff --git a/bin/gate-profile-reporter.js b/bin/gate-profile-reporter.js
deleted file mode 100644
index 25d6ea28..00000000
--- a/bin/gate-profile-reporter.js
+++ /dev/null
@@ -1,56 +0,0 @@
-/** 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.js
index 92f2c63e..450d814a 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -7,13 +7,11 @@ 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 = `
@@ -134,8 +132,6 @@ 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;
}
@@ -148,34 +144,13 @@ 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,
- ...callerArgs,
+ ...args,
];
return spawnSync(process.execPath, nodeArgs, { env, stdio: 'inherit' });
}
diff --git a/src/gate.js b/src/gate.js
index 952b9d72..cd2d7abc 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -6,14 +6,15 @@
*/
import { spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
-import { basename, dirname, join } from 'node:path';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { 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 { timingFromOutput, timingRunner } from './timing.js';
const STAMP = 'pullboard-gate-green';
const LOG = 'pullboard-gate.log';
@@ -125,35 +126,25 @@ function safeLog(output) {
}).join('\n');
}
-/** Run a command with Node's event reporter and persist its timing profile beside its log.
+/** Run the unchanged caller command and profile only timings already present in its output.
* @param {string} root
* @param {string} command
* @param {{ waitMs?: number, artifactDirectory?: string, artifactPrefix?: string, persistLog?: boolean, profileFile?: string, pipefail?: boolean }} [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, pipefail = false } = {}) {
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 }, pipefail });
- 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 }); }
+ const run = runShell(root, command, { pipefail });
+ const profile = writeTimingProfile(profilePath, {
+ ...timingFromOutput(run.output, timingRunner(command)),
+ waitMs: Math.max(0, Math.round(waitMs)), wallMs: Math.max(0, Date.now() - started),
+ });
+ if (logPath) writeFileSync(logPath, safeLog(run.output), { mode: 0o600 });
+ return { ...run, profile, profilePath, logPath };
}
/** Persist one sanitized timing profile as a private artifact.
@@ -177,7 +168,7 @@ export function writeTimingProfile(path, profile) {
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))
+ const tests = (profile.tests ?? []).filter(test => (typeof test?.file === 'string' || test?.file === null) && 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,
@@ -185,25 +176,15 @@ export function writeTimingProfile(path, profile) {
wallMs: validDuration(profile.wallMs) ? profile.wallMs : null,
files,
tests,
+ runner: sanitize(profile.runner ?? 'shell', 'runner'),
+ format: sanitize(profile.format ?? 'none', 'format'),
+ unavailable: sanitize(profile.unavailable ?? null, 'availability'),
};
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 : []) };
-}
-
/** Conservatively detect a pipe when the configured gate shell cannot enforce every stage's status. */
function hasPipeline(command) {
for (let index = 0; index < command.length; index += 1) {
@@ -308,6 +289,9 @@ export async function runSubmitGate(root, config, { base, trunk, changed, check,
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),
+ runner: [...new Set(profiles.map(value => value.runner))].join(', '),
+ format: [...new Set(profiles.map(value => value.format))].join('+'),
+ unavailable: profiles.some(value => value.unavailable) ? 'per-test timing unavailable: output was not TAP or JUnit (one or more phases)' : null,
});
return { ...proof, log, seconds: criterion.seconds + proof.seconds, ...selection, check: receipt,
profile, profilePath, proofProfilePath: proof.profilePath, proofLog: proof.log };
@@ -341,14 +325,14 @@ export function submitGateReport(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}
- */
+/** Show wall and queue wait for every run; rank files only when their durations were printed. */
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')}`;
+ if (!profile) return '';
+ const measured = value => Number.isFinite(value) ? `${(value / 1000).toFixed(2)}s` : 'unavailable';
+ const summary = `timing (${profile.runner ?? 'shell'}): wall ${measured(profile.wallMs)}, slot wait ${measured(profile.waitMs)}`;
+ 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);
+ const files = rows.length ? `\nslowest test files:\n${rows.map(file => ` ${file.path}: ${(file.durationMs / 1000).toFixed(2)}s`).join('\n')}` : '';
+ return `${summary}${profile.unavailable ? `\n${profile.unavailable}` : ''}${files}`;
}
/**
diff --git a/src/timing.js b/src/timing.js
new file mode 100644
index 00000000..28639104
--- /dev/null
+++ b/src/timing.js
@@ -0,0 +1,142 @@
+/** Read durations already printed by a caller's test runner, without changing its command [C7,V10]. */
+import { closeSync, openSync, readSync } from 'node:fs';
+import { StringDecoder } from 'node:string_decoder';
+
+const MAX_LINE = 64 * 1024;
+
+/** Name the executable or familiar test runner without persisting the command's arguments. */
+export function timingRunner(command) {
+ const known = /\b(go\s+test|cargo\s+test|dotnet\s+test|npm\s+test|pytest|node|mvn|gradle|rspec)\b/u.exec(command);
+ return known?.[1] ?? (command.trim().split(/\s+/u)[0]?.replace(/^.*[/\\]/u, '').replaceAll(/["']/gu, '').slice(0, 80) || 'shell');
+}
+
+/** Decode only XML's built-in and numeric entities; never resolve external entities. */
+function xmlText(value) {
+ return value.replace(/&(?:#(x[0-9a-f]+|[0-9]+)|(amp|lt|gt|quot|apos));/giu, (whole, number, named) => {
+ if (number) {
+ const point = Number.parseInt(number.startsWith('x') ? number.slice(1) : number, number.startsWith('x') ? 16 : 10);
+ return point > 0 && point <= 0x10ffff && !(point >= 0xd800 && point <= 0xdfff) ? String.fromCodePoint(point) : whole;
+ }
+ return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }[named.toLowerCase()];
+ });
+}
+
+/** Read quoted JUnit attributes without executing XML declarations or markup. */
+function attributes(source) {
+ return Object.fromEntries([...source.matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/gu)]
+ .map(match => [match[1], xmlText(match[2] ?? match[3])]));
+}
+
+/** Accept only finite, nonnegative printed measurements. */
+function duration(value, scale = 1) {
+ if (typeof value !== 'string' || !/^(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/iu.test(value)) return null;
+ const measured = Number(value) * scale;
+ return Number.isFinite(measured) && measured >= 0 ? measured : null;
+}
+
+/** Parse existing TAP diagnostics and JUnit tags, retaining no inferred file durations.
+ * @param {string|Iterable<string>} output - Complete output, or bounded lines from a private log.
+ * @param {string} runner - Value-free runner identity for unsupported output.
+ */
+export function timingFromOutput(output, runner = 'shell') {
+ const files = [];
+ const tests = [];
+ const formats = new Set();
+ const suites = [];
+ let tap = null;
+ let junit = null;
+ let xmlPending = '';
+ /** Finish a TAP diagnostic block only when it actually carries a duration. */
+ const finishTap = () => {
+ if (tap?.durationMs !== null && tap?.durationMs !== undefined && tap.type !== 'suite') {
+ // Node's crashed-file wrapper has an exitCode and a matching source location, not a case.
+ if (tap.exitCode && (tap.file === tap.name || tap.file?.endsWith('/' + tap.name))) files.push({ path: tap.name, durationMs: tap.durationMs });
+ else tests.push({ file: tap.file, name: tap.name, durationMs: tap.durationMs, passed: tap.passed });
+ }
+ tap = null;
+ };
+ /** Finish a JUnit testcase, including a self-closing success or a nested failure. */
+ const finishJunit = () => {
+ if (junit && junit.durationMs !== null) tests.push(junit);
+ junit = null;
+ };
+ for (const raw of typeof output === 'string' ? output.split(/\r?\n/u) : output) {
+ if (Buffer.byteLength(raw, 'utf8') > MAX_LINE) continue;
+ const line = raw.trim();
+ if (/^TAP version \d+$/u.test(line)) formats.add('tap');
+ const result = /^(not ok|ok)\s+\d+(?:\s*-\s*(.*?))?(?:\s+#\s*(?:SKIP|TODO)\b.*)?$/iu.exec(line);
+ if (result) {
+ finishTap();
+ formats.add('tap');
+ tap = { name: result[2] ?? '', file: null, durationMs: null, type: null, passed: result[1] === 'ok', exitCode: false, indent: raw.length - raw.trimStart().length };
+ } else if (tap) {
+ const field = /^(duration_ms|type|location|exitCode):\s*(.*)$/u.exec(line);
+ if (field && raw.length - raw.trimStart().length === tap.indent + 2) {
+ const value = field[2].replace(/^(['"])(.*)\1$/u, '$2');
+ if (field[1] === 'duration_ms') tap.durationMs = duration(value);
+ if (field[1] === 'type') tap.type = value;
+ if (field[1] === 'location') tap.file = value.replace(/:\d+:\d+$/u, '');
+ if (field[1] === 'exitCode') tap.exitCode = true;
+ }
+ if (line === '...') finishTap();
+ }
+ // Tags can span lines, but keep their pending text bounded like the diagnostic scanner.
+ const xml = xmlPending ? xmlPending + '\n' + raw : raw;
+ const tags = [...xml.matchAll(/<(\/?)([\w:.-]+)\b([^<>]*?)(\/?)>/gu)];
+ for (const tag of tags) {
+ const name = tag[2].split(':').at(-1);
+ const closing = tag[1] === '/';
+ const selfClosing = tag[4] === '/';
+ const attrs = attributes(tag[3]);
+ if (name === 'testsuites' || name === 'testsuite') formats.add('junit');
+ if (name === 'testsuite' && !closing) {
+ const suite = { file: attrs.file ?? null, durationMs: duration(attrs.time, 1000) };
+ if (suite.file && suite.durationMs !== null) files.push({ path: suite.file, durationMs: suite.durationMs });
+ if (!selfClosing) suites.push(suite);
+ } else if (name === 'testsuite' && closing) suites.pop();
+ if (name === 'testcase' && !closing) {
+ formats.add('junit');
+ finishJunit();
+ junit = { file: attrs.file ?? suites.at(-1)?.file ?? null, name: attrs.name ?? '', durationMs: duration(attrs.time, 1000), passed: true };
+ if (selfClosing) finishJunit();
+ } else if (name === 'testcase' && closing) finishJunit();
+ if (!closing && (name === 'failure' || name === 'error') && junit) junit.passed = false;
+ }
+ const end = tags.length ? tags.at(-1).index + tags.at(-1)[0].length : 0;
+ const remainder = xml.slice(end);
+ const opening = remainder.lastIndexOf('<');
+ xmlPending = opening >= 0 && remainder.length - opening <= MAX_LINE ? remainder.slice(opening) : '';
+ }
+ finishTap();
+ const format = [...formats].join('+') || 'none';
+ return { files, tests, runner, format,
+ unavailable: formats.size ? null : 'per-test timing unavailable: output was not TAP or JUnit' };
+}
+
+/** Iterate a complete log in bounded chunks, discarding only oversized diagnostic lines. */
+function* logLines(path) {
+ const fd = openSync(path, 'r');
+ const decoder = new StringDecoder('utf8');
+ const chunk = Buffer.alloc(32 * 1024);
+ let pending = '';
+ let oversized = false;
+ try {
+ let count;
+ while ((count = readSync(fd, chunk, 0, chunk.length, null)) > 0) {
+ const parts = (pending + decoder.write(chunk.subarray(0, count))).split('\n');
+ pending = parts.pop();
+ for (const [index, line] of parts.entries()) {
+ if ((!oversized || index > 0) && Buffer.byteLength(line, 'utf8') <= MAX_LINE) yield line.replace(/\r$/u, '');
+ }
+ if (parts.length) oversized = false;
+ if (Buffer.byteLength(pending, 'utf8') > MAX_LINE) { pending = ''; oversized = true; }
+ }
+ pending += decoder.end();
+ if (!oversized && pending) yield pending;
+ } finally { closeSync(fd); }
+}
+
+/** Read the private worker's full output without trusting its bounded diagnostic capture. */
+export function timingFromLog(path, runner) {
+ return timingFromOutput(logLines(path), runner);
+}
diff --git a/src/trusted-policy.js b/src/trusted-policy.js
index 01f586aa..cc7cda0e 100644
--- a/src/trusted-policy.js
+++ b/src/trusted-policy.js
@@ -2,9 +2,10 @@
import { randomUUID } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { digestOf, writeTimingProfile } from './gate.js';
-import { closeSync, existsSync, mkdtempSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, rmSync, writeSync } from 'node:fs';
+import { timingFromOutput, timingFromLog, timingRunner } from './timing.js';
+import { closeSync, existsSync, mkdtempSync, mkdirSync, openSync, readFileSync, readSync, rmSync, writeSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { basename, dirname, join } from 'node:path';
+import { join } from 'node:path';
import { StringDecoder } from 'node:string_decoder';
import { fileURLToPath } from 'node:url';
import { configFromSource } from './config.js';
@@ -144,8 +145,7 @@ export function checkAtCommit(root, item, { waitMs = 0 } = {}) {
mkdirSync(home, { mode: 0o700 });
const verifierHome = process.env.HOME ?? process.env.USERPROFILE;
const npmCache = process.env.npm_config_cache ?? join(verifierHome ?? home, '.npm');
- 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 };
+ 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 };
delete env.PULLBOARD_RELAY_TOKEN;
let installOutput = '';
let checkOutput = '';
@@ -155,7 +155,8 @@ export function checkAtCommit(root, item, { waitMs = 0 } = {}) {
let timingProfile = { files: [], tests: [] };
/** Format one completed check phase with the private captures and durable artifact locations. */
const finish = (state, stage) => {
- const events = readTimingProfiles(timingEventsPath);
+ const runner = timingRunner(command);
+ const events = checkLogPath && existsSync(checkLogPath) ? timingFromLog(checkLogPath, runner) : timingFromOutput(checkOutput, runner);
timingProfile = { ...events, wallMs: Math.max(0, Date.now() - checkStartedAt) };
return checkResult(state, stage, installOutput, checkOutput, { root, item, installLogPath, checkLogPath, timingProfile, waitMs });
};
@@ -205,7 +206,6 @@ export function checkAtCommit(root, item, { waitMs = 0 } = {}) {
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 {
- removeTimingProfiles(timingEventsPath);
rmSync(scratch, { recursive: true, force: true });
}
}
@@ -233,31 +233,6 @@ 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]';
@@ -425,7 +400,7 @@ function checkResult(state, stage, installCapture, checkCapture, { root = '', it
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 ?? [] });
+ const profile = writeTimingProfile(profilePath, { ...timingProfile, waitMs: Math.max(0, Math.round(waitMs)) });
timingProfile = profile;
}
} catch (error) {
diff --git a/test/gate-profile.test.js b/test/gate-profile.test.js
index 2fd9b22a..6ada7ba5 100644
--- a/test/gate-profile.test.js
+++ b/test/gate-profile.test.js
@@ -1,4 +1,4 @@
-/** Real gate, item-check and verifier profiles use Node's test events [C7,V10]. */
+/** Real gate, item-check and verifier profiles parse emitted timings [C7,V10]. */
import assert from 'node:assert/strict';
import { execFileSync, spawn, spawnSync } from 'node:child_process';
import { once } from 'node:events';
@@ -12,6 +12,7 @@ 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 CALLER_REPORTER = resolve(import.meta.dirname, 'timing-reporter-fixture.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';
@@ -174,7 +175,7 @@ test('a timing profile records two runner invocations and the real gate-slot wai
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:/);
+ assert.match(result.stdout, /timing \(node\): wall/);
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');
@@ -183,11 +184,10 @@ test('a timing profile records two runner invocations and the real gate-slot wai
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.files, [], 'ordinary TAP supplies no file wall measurements');
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.doesNotMatch(result.stdout, /slowest test files:/);
assert.ok(!result.stdout.includes(FAKE_SECRET));
assert.ok(!readFileSync(profilePath, 'utf8').includes(FAKE_SECRET));
assert.match(readFileSync(profilePath, 'utf8'), /redacted GitHub token/);
@@ -197,14 +197,14 @@ test('a timing profile records two runner invocations and the real gate-slot wai
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:/);
+ assert.match(red.stdout, /gate red in \d+s:/);
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:/);
+ assert.doesNotMatch(red.stdout, /slowest test files:/);
});
test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,V10]', () => {
@@ -214,6 +214,8 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,
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");
+ writeFileSync(join(box.repo, '.timed/middle.test.mjs'), "import { test } from 'node:test'; test('buried timing profile sample', () => {});\n");
+ writeFileSync(join(box.repo, '.timed/middle-output.mjs'), "import {spawnSync} from 'node:child_process'; const noise=['-e',\"process.stdout.write(('harmless padding '.repeat(30)+'\\\\n').repeat(10000))\"]; spawnSync(process.execPath,noise,{stdio:'inherit'}); const child=spawnSync(process.execPath,['--test-reporter=tap','.timed/middle.test.mjs'],{stdio:'inherit'}); spawnSync(process.execPath,noise,{stdio:'inherit'}); process.exitCode=child.status;\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');
@@ -225,12 +227,12 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,
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:/);
+ assert.match(direct.stdout, /timing \(node\): wall/);
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.deepEqual(directProfile.files, []);
assert.ok(directProfile.tests.find(test => test.name === 'slow timing profile check').durationMs >= 30);
assert.ok(existsSync(directPath.slice(0, -'.profile.json'.length) + '.log'));
@@ -240,7 +242,7 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,
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:/);
+ assert.match(accepted.stdout, /timing \(node\): wall/);
const verifyPath = /timing profile: ([^\n]+)/.exec(accepted.stdout)?.[1];
assert.ok(verifyPath, accepted.stdout);
assert.ok(verifyPath.endsWith('.log.profile.json'));
@@ -248,7 +250,7 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,
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.deepEqual(verified.files, []);
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);
@@ -281,6 +283,16 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,
assert.deepEqual(shellVerify.profile.tests, []);
assert.equal(shellVerify.profile.waitMs, 17);
assert.ok(shellVerify.profile.wallMs > 0 && existsSync(shellVerify.profilePath));
+ const context = process.env.NODE_TEST_CONTEXT;
+ delete process.env.NODE_TEST_CONTEXT;
+ let buried;
+ try { buried = checkAtCommit(box.repo, { ...item, item_commit: shellCommit, item_frozen: JSON.stringify({ ...frozen, check: 'node .timed/middle-output.mjs' }) }); }
+ finally { if (context !== undefined) process.env.NODE_TEST_CONTEXT = context; }
+
+ assert.equal(buried.state, 'pass', buried.report);
+ assert.doesNotMatch(buried.output, /buried timing profile sample/u, 'the bounded worker capture omits the middle');
+ assert.ok(buried.profile.tests.some(value => value.name === 'buried timing profile sample'), 'the complete private log retains middle timing data');
+
});
@@ -293,7 +305,7 @@ test('a timing profile keeps every selected file while its digest names only ten
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(' ')}`;
+ const command = `node '${RUNNER.replaceAll("'", "'\\''")}' --test-reporter='${CALLER_REPORTER}' ${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');
@@ -350,7 +362,7 @@ 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']) {
+ for (const file of ['bin/run-tests.js', 'src/person.js', 'src/refused.js']) {
writeFileSync(join(box.repo, file), readFileSync(join(source, file)));
}
}
@@ -453,7 +465,7 @@ test('a submit timing profile records both phases and one queue wait for selecte
' assert.equal(1, 1);',
'});',
].join('\n') + '\n');
- writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate: gateCommand }, null, 2));
+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ ...CONFIG, gate: gateCommand, ...(scenario.full ? {} : { affectedTests: 'node bin/run-tests.js' }) }, 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');
@@ -477,9 +489,9 @@ test('a submit timing profile records both phases and one queue wait for selecte
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, []);
if (!scenario.full) assert.deepEqual(gate.files, ['web/affected.test.js']);
- if (scenario.full) assert.match(gate.reason, /web\/README\.txt/u);
+ if (scenario.full) assert.match(gate.reason, /affected-test selection is not enabled/u);
assert.ok(gate.check.log.endsWith('pullboard-submit.log.check.log'));
assert.equal(gate.check.profilePath, `${gate.check.log}.profile.json`);
@@ -494,23 +506,23 @@ test('a submit timing profile records both phases and one queue wait for selecte
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.deepEqual(checkProfile.files, [], 'TAP test timings are not invented file measurements');
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.deepEqual(proofProfile.files, []);
+ assert.deepEqual(proofProfile.tests.map(value => value.name).sort(), scenario.full
+ ? ['unaffected proof profile sample [C7]', 'frozen check profile sample [C7]', 'affected proof profile sample [C7]'].sort()
+ : ['affected proof profile sample [C7]']);
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'));
+ assert.deepEqual(combined.files, []);
+ assert.ok(combined.tests.some(value => value.name === 'frozen check profile sample [C7]'));
+ assert.ok(combined.tests.some(value => value.name === 'affected proof profile sample [C7]'));
+ if (scenario.full) assert.ok(combined.tests.some(value => value.name === 'unaffected proof profile sample [C7]'));
const ran = readFileSync(trace, 'utf8').trim().split(/\r?\n/u).sort();
assert.equal(ran.filter(line => line === 'check').length, scenario.full ? 2 : 1,
diff --git a/test/gate-timing-output.test.js b/test/gate-timing-output.test.js
new file mode 100644
index 00000000..e7a3bbb2
--- /dev/null
+++ b/test/gate-timing-output.test.js
@@ -0,0 +1,129 @@
+/** Timing profiles parse the caller's unchanged TAP or JUnit output [C7,V10]. */
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { test } from 'node:test';
+import { gateReport, runProfiledShell } from '../src/gate.js';
+
+const TEMP = [];
+const savedContext = process.env.NODE_TEST_CONTEXT;
+const savedOptions = process.env.NODE_OPTIONS;
+test.before(() => { delete process.env.NODE_TEST_CONTEXT; delete process.env.NODE_OPTIONS; });
+test.after(() => { if (savedContext === undefined) delete process.env.NODE_TEST_CONTEXT; else process.env.NODE_TEST_CONTEXT = savedContext; if (savedOptions === undefined) delete process.env.NODE_OPTIONS; else process.env.NODE_OPTIONS = savedOptions; });
+
+test('timing profile reads direct and native TAP without inventing file rows [C7,V10]', async t => {
+ const repo = makeRepo();
+ const caseFile = join(repo, 'timed', 'slow.test.mjs');
+ mkdirSync(join(repo, 'timed'));
+ writeFileSync(caseFile, "import { test } from 'node:test'; test('slow direct sample', async () => new Promise(resolve => setTimeout(resolve, 130)));");
+
+ await t.test('direct node execution keeps its printed duration [C7,V10]', () => {
+ const direct = runProfiledShell(repo, 'node timed/slow.test.mjs', { artifactDirectory: join(repo, 'artifacts'), persistLog: true, waitMs: 17 });
+ assert.equal(direct.isGreen, true, direct.output);
+ assert.match(direct.output, /slow direct sample/);
+ if (/^TAP version \d+/mu.test(direct.output)) {
+ assert.ok(direct.profile.tests.some(entry => entry.name.includes('slow direct sample') && entry.durationMs >= 100));
+ assert.equal(direct.profile.format, 'tap');
+ assert.equal(direct.profile.unavailable, null);
+ } else {
+ assert.equal(direct.profile.format, 'none');
+ assert.equal(direct.profile.unavailable, 'per-test timing unavailable: output was not TAP or JUnit');
+ }
+ assert.deepEqual(direct.profile.files, [], 'test timing without a file timing must not become a file row');
+ assert.equal(direct.profile.waitMs, 17);
+ assert.ok(direct.profile.wallMs >= 100);
+ });
+
+ await t.test('native default output preserves caller argv and execArgv [C7,V10]', () => {
+ const trace = join(repo, 'invocation.json');
+ const script = join(repo, 'timed', 'invocation.test.mjs');
+ writeFileSync(script, `import { writeFileSync } from 'node:fs'; import { test } from 'node:test'; writeFileSync(${JSON.stringify(trace)}, JSON.stringify({ argv: process.argv.slice(1), execArgv: process.execArgv, nodeOptions: process.env.NODE_OPTIONS ?? '' })); test('native default sample', () => {});`);
+ const command = 'node --test timed/invocation.test.mjs';
+ const native = runProfiledShell(repo, command, { artifactDirectory: join(repo, 'artifacts'), persistLog: true, waitMs: 17 });
+ assert.equal(native.isGreen, true, native.output);
+ assert.match(native.output, /native default sample/);
+ assert.deepEqual(JSON.parse(readFileSync(trace, 'utf8')), { argv: [script], execArgv: [], nodeOptions: '' });
+ assert.deepEqual(native.profile.files, [], 'default TAP does not provide a trustworthy file-duration row');
+ if (/^TAP version \d+/mu.test(native.output)) assert.ok(native.profile.tests.some(entry => entry.name.includes('native default sample')));
+ else assert.equal(native.profile.unavailable, 'per-test timing unavailable: output was not TAP or JUnit');
+ assert.equal(native.profile.waitMs, 17);
+ });
+
+ await t.test('explicit TAP reporter remains caller-selected and retains its timing [C7,V10]', () => {
+ const command = 'node --test-reporter=tap --test timed/slow.test.mjs';
+ const explicit = runProfiledShell(repo, command, { artifactDirectory: join(repo, 'artifacts'), persistLog: true, waitMs: 17 });
+ assert.equal(explicit.isGreen, true, explicit.output);
+ assert.match(explicit.output, /TAP version 13/);
+ assert.match(explicit.output, /slow direct sample/);
+ assert.ok(explicit.profile.tests.some(entry => entry.name.includes('slow direct sample') && entry.durationMs >= 100));
+ assert.deepEqual(explicit.profile.files, []);
+ });
+});
+
+test('timing profile reads caller-selected native JUnit stdout [C7,V10]', () => {
+ const repo = makeRepo();
+ writeFileSync(join(repo, 'junit.test.mjs'), "import {test} from 'node:test'; test('native JUnit slow sample', async()=>new Promise(resolve=>setTimeout(resolve,130)));\n");
+ const run = runProfiledShell(repo, 'node --test --test-reporter=junit junit.test.mjs', {artifactDirectory:join(repo,'artifacts'),persistLog:true,waitMs:17});
+ assert.equal(run.isGreen,true,run.output);
+ assert.equal(run.profile.format,'junit');
+ assert.ok(run.profile.tests.some(value=>value.name==='native JUnit slow sample' && value.durationMs>=100));
+ assert.deepEqual(run.profile.files,[],'native JUnit supplies no explicit file duration');
+});
+
+test('timing profile uses only actual JUnit file and test metadata [C7,V10]', () => {
+ const repo = makeRepo();
+ const commandFile = join(repo, 'emit-junit.mjs');
+ writeFileSync(commandFile, `import { writeFileSync } from 'node:fs'; const start = Date.now(); await new Promise(resolve => setTimeout(resolve, 130)); const seconds = ((Date.now() - start) / 1000).toFixed(3); process.stdout.write('<testsuite name="suite" file="timed/suite.test.js" time="' + seconds + '"><testcase name="slow &amp; measured" file="timed/suite.test.js" time="' + seconds + '"><failure message="expected red"/></testcase></testsuite>\\n'); process.exitCode = 1;`);
+ const command = 'node emit-junit.mjs';
+ const failed = runProfiledShell(repo, command, { artifactDirectory: join(repo, 'artifacts'), persistLog: true, waitMs: 17 });
+ assert.equal(failed.isGreen, false);
+ assert.match(failed.output, /testsuite/);
+ assert.ok(failed.profile.wallMs >= 100);
+ assert.equal(failed.profile.format, 'junit');
+ assert.ok(failed.profile.files.some(file => file.path === 'timed/suite.test.js' && file.durationMs >= 100));
+ assert.ok(failed.profile.tests.some(entry => entry.file === 'timed/suite.test.js' && entry.name === 'slow & measured' && entry.durationMs >= 100 && !entry.passed));
+ assert.equal(failed.profile.waitMs, 17);
+ assert.match(gateReport({ ...failed, log: failed.logPath }), /slowest test files:[\s\S]*timed\/suite\.test\.js/);
+});
+
+test('timing profile leaves unsupported runner commands and destinations untouched [C7,V10]', () => {
+ const repo = makeRepo();
+ const testFile = join(repo, 'one.test.mjs');
+ writeFileSync(testFile, "import { test } from 'node:test'; test('unsupported runner sample', () => {});\n");
+ const spec = runProfiledShell(repo, 'node --test-reporter=spec --test one.test.mjs', {artifactDirectory:join(repo,'artifacts'),persistLog:true,waitMs:17});
+ assert.equal(spec.isGreen,true,spec.output);
+ assert.match(spec.output,/unsupported runner sample/u);
+ assert.equal(spec.profile.format,'none');
+ assert.equal(spec.profile.unavailable,'per-test timing unavailable: output was not TAP or JUnit');
+ const destination = join(repo, 'caller-junit.xml');
+ const command = `node --test-reporter=junit --test-reporter-destination=${shellWord(destination)} --test one.test.mjs`;
+ const result = runProfiledShell(repo, command, { artifactDirectory: join(repo, 'artifacts'), persistLog: true, waitMs: 17 });
+ assert.equal(result.isGreen, true, result.output);
+ assert.deepEqual(result.profile.files, []);
+ assert.deepEqual(result.profile.tests, []);
+ assert.equal(result.profile.format, 'none');
+ assert.match(result.profile.runner, /node/);
+ assert.equal(result.profile.unavailable, 'per-test timing unavailable: output was not TAP or JUnit');
+ assert.equal(result.profile.waitMs, 17);
+ assert.ok(result.profile.wallMs >= 0);
+ assert.match(gateReport({ ...result, log: result.logPath }), /per-test timing unavailable: output was not TAP or JUnit/);
+ assert.match(gateReport({ ...result, log: result.logPath }), /node/);
+ assert.match(readFileSync(destination, 'utf8'), /testsuite/);
+});
+
+/** Initialize a real temporary Git checkout for the public profiling API. */
+function makeRepo() {
+ const repo = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-timing-output-')));
+ TEMP.push(repo);
+ execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: repo });
+ return repo;
+}
+
+/** Quote one path for the shell command passed unchanged to the profiler. */
+function shellWord(value) {
+ return `'${value.replaceAll("'", "'\\''")}'`;
+}
+
+test.after(() => { for (const path of TEMP) rmSync(path, { recursive: true, force: true }); });
diff --git a/test/run-tests-reporter.test.js b/test/run-tests-reporter.test.js
index 9f67360a..5691a783 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 { runFixtureChild as spawnSync } from './fixture-child.js';
-import { mkdtempSync, readdirSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -10,7 +10,7 @@ import { test } from 'node:test';
const runner = fileURLToPath(new URL('../bin/run-tests.js', import.meta.url));
/** Create a fixture that observes actual child arguments and returns the runner result. */
-function runReporterFixture(t, reporterArgs = []) {
+function runReporterFixture(t, reporterArgs = [], extraEnv = {}) {
const root = mkdtempSync(join(tmpdir(), 'pullboard-run-tests-reporter-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
const fixture = join(root, 'reporter.test.js');
@@ -36,6 +36,7 @@ syncBuiltinESMExports();
cwd: root,
env: {
...process.env,
+ ...extraEnv,
NODE_OPTIONS: `--import="${preload}"`,
PULLBOARD_REPORTER_CAPTURE_FILE: capture,
},
@@ -69,40 +70,16 @@ test('run-tests prints TAP on every Node version and keeps a caller reporter [C7
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) => {
+test('run-tests never injects timing reporters beside caller reporter options [C7,V10]', (t) => {
for (const reporterArgs of [
- ['--test-reporter=spec'],
- ['--test-reporter', 'spec'],
+ ['--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);
+ const run = runReporterFixture(t, reporterArgs, { PULLBOARD_TEST_TIMING_PROFILE: join(tmpdir(), 'must-not-inject') });
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');
+ assert.deepEqual(run.childArgs.slice(4, -1), reporterArgs, 'only the exact caller reporter flags reach Node');
+ assert.match(run.output, /ℹ tests 1/u);
+ assert.doesNotMatch(run.output, /gate-profile-reporter|"files":/u);
}
});
diff --git a/test/timing-reporter-fixture.js b/test/timing-reporter-fixture.js
new file mode 100644
index 00000000..e78b2d30
--- /dev/null
+++ b/test/timing-reporter-fixture.js
@@ -0,0 +1,30 @@
+/** Caller-owned JUnit reporter used only by real timing integration fixtures [C7,V10]. */
+import { relative, resolve } from 'node:path';
+
+/** Escape actual event names before printing a caller-selected XML report. */
+function xml(value) {
+ return String(value).replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
+}
+
+/** Emit only measured Node events; file summaries and cases remain separate measurements. */
+export default async function* junit(events) {
+ const files = new Map();
+ const tests = [];
+ for await (const event of events) {
+ const data = event.data ?? {};
+ if (event.type === 'test:summary' && data.file && Number.isFinite(data.duration_ms)) files.set(data.file, data.duration_ms);
+ if (event.type === 'test:complete' && data.details?.type === 'test' && data.file && Number.isFinite(data.details.duration_ms)) {
+ if (data.line === 1 && data.column === 1 && resolve(data.name) === resolve(data.file)) continue;
+ tests.push({file:data.file,name:data.name,durationMs:data.details.duration_ms,passed:data.details.passed===true});
+ }
+ }
+ yield '<testsuites>\n';
+ for (const [file, durationMs] of files) {
+ yield `<testsuite file="${xml(relative(process.cwd(),file))}" time="${durationMs/1000}">\n`;
+ for (const entry of tests.filter(value=>value.file===file)) {
+ yield `<testcase name="${xml(entry.name)}" time="${entry.durationMs/1000}">${entry.passed?'':'<failure/>'}</testcase>\n`;
+ }
+ yield '</testsuite>\n';
+ }
+ yield '</testsuites>\n';
+}