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
test(timing): guard fixed wall-clock margins [C7]
Corey Olson51185fa7bc5d
diff --git a/test/api.test.js b/test/api.test.jsindex b92a6c8a..993f231c 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -562,7 +562,7 @@ test('[A1] long-running servers flush one JSON document before shutdown', asyncrejectReady(new Error(reportFixtureChildFailure({ command: process.execPath, args, status, signal,elapsedMs: performance.now() - startedAt, stderr, env: box.env, detail })));};- const timeout = setTimeout(() => failStartup('server readiness deadline (10000ms) expired'), 10_000);+ const timeout = setTimeout(() => failStartup('server readiness deadline (10000ms) expired'), 10_000); // budget: hang ceiling for private server readiness; no throughput claim.child.stdout.on('data', () => {try {const document = JSON.parse(stdout);@@ -752,7 +752,7 @@ async function startApi(t, box) {rejectReady(new Error(reportFixtureChildFailure({ command: process.execPath, args, status, signal,elapsedMs: performance.now() - startedAt, stderr, env: box.env, detail })));};- const timeout = setTimeout(() => failStartup('serve readiness deadline (10000ms) expired'), 10_000);+ const timeout = setTimeout(() => failStartup('serve readiness deadline (10000ms) expired'), 10_000); // budget: hang ceiling for private serve readiness; no throughput claim.const check = () => {try {const parsed = JSON.parse(stdout);diff --git a/test/approved-row-changes.test.js b/test/approved-row-changes.test.jsindex ecd1fd24..2bd16892 100644--- a/test/approved-row-changes.test.js+++ b/test/approved-row-changes.test.js@@ -210,8 +210,7 @@ test('[C7] cleanup diagnostics name the owner when lsof is slow', async () => {const owners = report.split('open-file owners:\n')[1] ?? '';if (hasLsof) assert.match(owners, new RegExp(`pid=${writer.pid}\\b`));else assert.match(owners, /^unavailable \(lsof exit (?:126|127)\)$/);- assert.ok(captureElapsedMs >= 4_000, `the lsof shim waited four seconds: ${captureElapsedMs}ms`);- assert.ok(captureElapsedMs < 10_000, `the 8000ms subprocess budget stayed within its 10000ms wall ceiling: ${captureElapsedMs}ms`);+ assert.ok(captureElapsedMs >= 4_000, `the lsof shim waited four seconds: ${captureElapsedMs}ms`); // budget: declared four-second sleep in the private lsof shim.});test('[C7] cleanup diagnostics report the lsof timeout budget', () => {@@ -234,7 +233,6 @@ test('[C7] cleanup diagnostics report the lsof timeout budget', () => {process.env.PATH = originalPath;rmSync(directory, { recursive: true, force: true });}- assert.ok(captureElapsedMs < 10_000, `the 8000ms subprocess budget stayed within its 10000ms wall ceiling: ${captureElapsedMs}ms`);assert.match(report, /open-file owners:\nunavailable \(ETIMEDOUT after 8000 ms\)$/);});diff --git a/test/chrome-fixture.test.js b/test/chrome-fixture.test.jsindex 15c24efb..3512b52e 100644--- a/test/chrome-fixture.test.js+++ b/test/chrome-fixture.test.js@@ -77,7 +77,7 @@ test('removes the profile only after every Chrome process exits [C7]', async (t)await waitForFile(scripts.helperReady);const closedAt = Date.now();await chrome.close();- assert.ok(Date.now() - closedAt >= 1_300, 'close waited while the helper kept writing after the leader exited');+ assert.ok(Date.now() - closedAt >= 1_300, 'close waited while the helper kept writing after the leader exited'); // budget: declared delayed helper write (1.5 seconds); close must wait for it.assert.equal(readFileSync(scripts.lateWrite, 'utf8'), 'finished', 'the helper finished its delayed profile write');assert.doesNotThrow(() => rmSync(profile, { recursive: true }), 'one profile removal succeeds after the group is empty');removed = true;@@ -105,7 +105,7 @@ test('a missing DevTools port fails once with stderr and elapsed launch time [C7}), (error) => {assert.match(error.message, /did not publish its DevTools port/u);assert.match(error.message, /elapsed \d+ms; 30000ms DevTools budget/u);- assert.ok(Number(/elapsed (\d+)ms/u.exec(error.message)[1]) >= 30_000, 'the stand-in exercised the actual default startup budget');+ assert.ok(Number(/elapsed (\d+)ms/u.exec(error.message)[1]) >= 30_000, 'the stand-in exercised the actual default startup budget'); // budget: declared production DevTools startup deadline is 30000ms.assert.match(error.message, /NO_PORT_STAND_IN_STDERR/u);return true;});@@ -141,7 +141,7 @@ test("a DevTools port timeout names Chrome's state [C7]", async (t) => {assert.match(error.message, /elapsed \d+ms; 2000ms DevTools budget/u);assert.match(error.message, /load average \[/u);const elapsed = Number(/Chrome startup state:.*elapsed (\d+)ms/u.exec(error.message)?.[1]);- assert.ok(elapsed >= startupTimeoutMs, `the live stand-in reached the startup budget: ${error.message}`);+ assert.ok(elapsed >= startupTimeoutMs, `the live stand-in reached the startup budget: ${error.message}`); // budget: declared 2000ms startup deadline must actually expire.return true;});assert.equal(readFileSync(liveMarker, 'utf8'), 'start\n', 'the live stand-in launched only once');@@ -282,12 +282,12 @@ test('a DevTools timer that fires early still times out at its budget [C7]', asyconst pending = new Map();const send = createSender(socket, pending, () => 1, 250, { max: 0 }, new Set(), timers);const result = send('Runtime.evaluate', {}, 'early timer').catch(error => error);- assert.equal(scheduled[0].delay, 250, 'the first timer receives the full command budget');+ assert.equal(scheduled[0].delay, 250, 'the first timer receives the full command budget'); // budget: declared 250ms command allowance on a simulated clock, not machine speed.now += 249;scheduled.shift().callback();assert.equal(scheduled.length, 1, 'a timer firing 1ms early is re-armed');- assert.equal(scheduled[0].delay, 1, 'the re-armed timer uses only the remaining budget');+ assert.equal(scheduled[0].delay, 1, 'the re-armed timer uses only the remaining budget'); // budget: declared simulated clock advanced 249ms of its 250ms allowance.now += 1;scheduled.shift().callback();@@ -347,11 +347,11 @@ test('a wait that throws while the page changes keeps waiting [C7]', async (t) =const alwaysThrows = '(() => { throw new Error("persistent evaluation failure"); })()';const startedAt = Date.now();- await assert.rejects(chrome.waitFor(alwaysThrows, 350, 'always-throwing expression'), (error) => {+ await assert.rejects(chrome.waitFor(alwaysThrows, 350, 'always-throwing expression'), (error) => { // budget: declared 350ms operation deadline for an always-throwing condition.assert.match(error.message, /did not arrive within 350ms/u);assert.match(error.message, /persistent evaluation failure/u);assert.ok(error.message.includes(alwaysThrows), 'deadline diagnostic names the expression');- assert.ok(Date.now() - startedAt >= 350, 'the wait polls through its requested deadline');+ assert.ok(Date.now() - startedAt >= 350, 'the wait polls through its requested deadline'); // budget: declared 350ms operation deadline must actually expire.return true;});diff --git a/test/e2e-cli.test.js b/test/e2e-cli.test.jsindex 9a09acaa..ea77cf70 100644--- a/test/e2e-cli.test.js+++ b/test/e2e-cli.test.js@@ -65,7 +65,7 @@ test('the tour runs a reject and its rework on a throwaway repo, in under thirtyconst started = Date.now();const shown = spawnSync(process.execPath, [BIN, 'tour'], { cwd: box.dir, env: plainEnv, encoding: 'utf8' });assert.equal(shown.status, 0, `${shown.stdout}${shown.stderr}`);- assert.ok(Date.now() - started < 30_000, 'thirty seconds');+ assert.ok(Date.now() - started < 30_000, 'thirty seconds'); // budget: approved row N10 states thirty seconds.assert.doesNotMatch(shown.stdout, /\u001b\[/, 'piped output stays plain');assert.match(shown.stdout, /review-1 \(Scripted\) \$ pullboard verify 1 reject --reason BEHAVIOR_MISMATCH/);assert.match(shown.stdout, /sent back: #1 BEHAVIOR_MISMATCH by review-1 \(Scripted\): greet\(''\) returns "Hello, !"/);diff --git a/test/fixture-child.test.js b/test/fixture-child.test.jsindex 0c3dff4f..96b668b8 100644--- a/test/fixture-child.test.js+++ b/test/fixture-child.test.js@@ -38,7 +38,7 @@ test('a fixture child killed or failed names its command, signal and stderr [C7]assert.match(killed.failure, /command: .*setInterval/u);assert.match(killed.failure, /signal: SIGTERM/u);const elapsed = /elapsed: (\d+)ms/u.exec(killed.failure);- assert.ok(Number(elapsed?.[1]) - (readyAt - startedAt) >= 80, killed.failure);+ assert.ok(Number(elapsed?.[1]) - (readyAt - startedAt) >= 80, killed.failure); // budget: declared 80ms termination timer starts after the child readiness handshake.assert.match(killed.failure, /stderr: sleeping child/u);assert.throws(() => runFixtureExecFile(process.execPath, ['-e', "console.error('exec stderr'); process.exit(6)"], { encoding: 'utf8' }),diff --git a/test/gate-profile.test.js b/test/gate-profile.test.jsindex 8cacf301..c9e0fae4 100644--- a/test/gate-profile.test.js+++ b/test/gate-profile.test.js@@ -100,7 +100,7 @@ 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);+ const timer = setTimeout(() => reject(new Error('gate slot holder did not start')), 10_000); // budget: hang ceiling for the private gate holder readiness handshake.child.once('error', error => { clearTimeout(timer); reject(error); });child.stdout.once('data', data => {clearTimeout(timer);@@ -157,7 +157,7 @@ test('a timing profile records two runner invocations and the real gate-slot wai}let gateTimer;const timeout = new Promise((_, reject) => {- gateTimer = setTimeout(() => reject(new Error('private gate did not finish within 60 seconds')), 60_000);+ gateTimer = setTimeout(() => reject(new Error('private gate did not finish within 60 seconds')), 60_000); // budget: hang ceiling for private gate completion; no throughput claim.});let status;try { [status] = await Promise.race([gateExited, timeout]); }@@ -186,11 +186,11 @@ test('a timing profile records two runner invocations and the real gate-slot waiassert.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.ok(profile.waitMs >= 100, `recorded queue wait ${profile.waitMs}ms`); // budget: declared 300ms queue hold; recorded wait must include it.+ assert.ok(profile.wallMs > 0 && elapsedMs + 30 >= profile.waitMs + profile.wallMs, `${elapsedMs}ms total vs ${profile.waitMs}ms wait + ${profile.wallMs}ms wall`); // budget: measured queue and work durations compared to their enclosing clock; 30ms rounding allowance.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.tests.find(test => test.name === '[redacted GitHub token]').durationMs >= 130, 'the actual slow test duration is retained');+ assert.ok(profile.tests.find(test => test.name === '[redacted GitHub token]').durationMs >= 130, 'the actual slow test duration is retained'); // budget: declared 150ms slow-test sleep must appear in its timing profile.assert.doesNotMatch(result.stdout, /slowest test files:/);assert.ok(!result.stdout.includes(FAKE_SECRET));assert.ok(!readFileSync(profilePath, 'utf8').includes(FAKE_SECRET));@@ -237,7 +237,7 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,assert.equal(statSync(directPath).mode & 0o777, 0o600);const directProfile = JSON.parse(readFileSync(directPath, 'utf8'));assert.deepEqual(directProfile.files, []);- assert.ok(directProfile.tests.find(test => test.name === 'slow timing profile check').durationMs >= 30);+ assert.ok(directProfile.tests.find(test => test.name === 'slow timing profile check').durationMs >= 30); // budget: declared 40ms slow-test sleep must appear in its timing profile.assert.ok(existsSync(directPath.slice(0, -'.profile.json'.length) + '.log'));assert.equal(box.run(box.web, 'submit', '1').status, 0);@@ -255,7 +255,7 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,const verified = JSON.parse(readFileSync(verifyPath, 'utf8'));assert.ok(verified.waitMs >= 0 && verified.wallMs > 0);assert.deepEqual(verified.files, []);- assert.ok(verified.tests.find(test => test.name === 'slow timing profile check').durationMs >= 30);+ assert.ok(verified.tests.find(test => test.name === 'slow timing profile check').durationMs >= 30); // budget: declared 40ms slow-test sleep must appear in its timing profile.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);@@ -285,7 +285,7 @@ test('item-check and ACCEPT timing profiles sit beside their sanitized logs [C7,assert.equal(shellVerify.state, 'pass');assert.deepEqual(shellVerify.profile.files, []);assert.deepEqual(shellVerify.profile.tests, []);- assert.equal(shellVerify.profile.waitMs, 17);+ assert.equal(shellVerify.profile.waitMs, 17); // budget: declared synthetic waitMs=17 input is retained exactly, not elapsed wall work.assert.ok(shellVerify.profile.wallMs > 0 && existsSync(shellVerify.profilePath));const context = process.env.NODE_TEST_CONTEXT;delete process.env.NODE_TEST_CONTEXT;@@ -404,7 +404,7 @@ async function runProfileSubmission(box, queue) {try {result = await Promise.race([submit.finished,- new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('private profile submit exceeded 60 seconds')), 60_000); }),+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('private profile submit exceeded 60 seconds')), 60_000); }), // budget: hang ceiling for private submission completion; no throughput claim.]);} finally {clearTimeout(timer);@@ -511,21 +511,21 @@ test('a submit timing profile records both phases and one queue wait for selecteassert.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`);+ if (scenario.queue) assert.ok(checkProfile.waitMs >= 100, `actual queued check waited ${checkProfile.waitMs}ms`); // budget: declared 300ms private queue hold must appear in the recorded wait.const proofProfile = JSON.parse(readFileSync(gate.proofProfilePath, 'utf8'));const combined = JSON.parse(readFileSync(gate.profilePath, 'utf8'));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.ok(checkProfile.tests[0].durationMs >= 50); // budget: declared 70ms frozen-check sleep must appear in its profile.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,+ assert.ok(combined.wallMs >= checkProfile.wallMs + proofProfile.wallMs - 25, // budget: measured check and proof phase durations; 25ms rounding allowance.'the combined wall time includes both measured phases without adding their queue waits');- assert.ok(submission.elapsedMs + 50 >= combined.waitMs + combined.wallMs,+ assert.ok(submission.elapsedMs + 50 >= combined.waitMs + combined.wallMs, // budget: measured combined wait/work against the enclosing clock; 50ms rounding allowance.`${submission.elapsedMs}ms total vs ${combined.waitMs}ms one wait + ${combined.wallMs}ms combined work`);assert.deepEqual(combined.files, []);assert.ok(combined.tests.some(value => value.name === 'frozen check profile sample [C7]'));diff --git a/test/gate-resource.test.js b/test/gate-resource.test.jsindex 158843c9..47887741 100644--- a/test/gate-resource.test.js+++ b/test/gate-resource.test.js@@ -296,7 +296,7 @@ test('[Q4] SIGKILL during a gate releases its machine slot for the next process'assert.equal((await dead.closed).signal, 'SIGKILL');const result = await Promise.race([next.closed,- new Promise((_, reject) => setTimeout(() => reject(new Error('successor did not acquire the freed slot')), 5_000)),+ new Promise((_, reject) => setTimeout(() => reject(new Error('successor did not acquire the freed slot')), 5_000)), // budget: hang ceiling for a freed slot acquisition; no throughput claim.]);assert.equal(result.code, 0, next.stderrText);assert.ok(events(box).includes('next start'));diff --git a/test/gate-timing-output.test.js b/test/gate-timing-output.test.jsindex 67af0acf..9f6ea3b1 100644--- a/test/gate-timing-output.test.js+++ b/test/gate-timing-output.test.js@@ -24,7 +24,7 @@ test('timing profile reads direct and native TAP without inventing file rows [C7assert.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.ok(direct.profile.tests.some(entry => entry.name.includes('slow direct sample') && entry.durationMs >= 100)); // budget: declared 130ms slow sample must appear in the measured duration.assert.equal(direct.profile.format, 'tap');assert.equal(direct.profile.unavailable, null);} else {@@ -32,8 +32,8 @@ test('timing profile reads direct and native TAP without inventing file rows [C7assert.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);+ assert.equal(direct.profile.waitMs, 17); // budget: declared synthetic waitMs=17 input is retained exactly.+ assert.ok(direct.profile.wallMs >= 100); // budget: declared 130ms slow sample contributes to measured wall time.});await t.test('native default output preserves caller argv and execArgv [C7,V10]', () => {@@ -55,7 +55,7 @@ test('timing profile reads direct and native TAP without inventing file rows [C7assert.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);+ assert.equal(native.profile.waitMs, 17); // budget: declared synthetic waitMs=17 input is retained exactly.});await t.test('explicit TAP reporter remains caller-selected and retains its timing [C7,V10]', () => {@@ -64,7 +64,7 @@ test('timing profile reads direct and native TAP without inventing file rows [C7assert.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.ok(explicit.profile.tests.some(entry => entry.name.includes('slow direct sample') && entry.durationMs >= 100)); // budget: declared 130ms slow sample must appear in the measured duration.assert.deepEqual(explicit.profile.files, []);});});@@ -75,7 +75,7 @@ test('timing profile reads caller-selected native JUnit stdout [C7,V10]', () =>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.ok(run.profile.tests.some(value=>value.name==='native JUnit slow sample' && value.durationMs>=100)); // budget: declared 130ms slow sample must appear in the measured duration.assert.deepEqual(run.profile.files,[],'native JUnit supplies no explicit file duration');});@@ -87,11 +87,11 @@ test('timing profile uses only actual JUnit file and test metadata [C7,V10]', ()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.ok(failed.profile.wallMs >= 100); // budget: declared 130ms JUnit fixture sleep contributes to wall time.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.ok(failed.profile.files.some(file => file.path === 'timed/suite.test.js' && file.durationMs >= 100)); // budget: declared 130ms JUnit fixture sleep is emitted as file duration.+ assert.ok(failed.profile.tests.some(entry => entry.file === 'timed/suite.test.js' && entry.name === 'slow & measured' && entry.durationMs >= 100 && !entry.passed)); // budget: declared 130ms JUnit fixture sleep is emitted as test duration.+ assert.equal(failed.profile.waitMs, 17); // budget: declared synthetic waitMs=17 input is retained exactly.assert.match(gateReport({ ...failed, log: failed.logPath }), /slowest test files:[\s\S]*timed\/suite\.test\.js/);});@@ -113,7 +113,7 @@ test('timing profile leaves unsupported runner commands and destinations untouchassert.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.equal(result.profile.waitMs, 17); // budget: declared synthetic waitMs=17 input is retained exactly.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/);diff --git a/test/http-fixture.test.js b/test/http-fixture.test.jsindex 241602db..a4dfc1da 100644--- a/test/http-fixture.test.js+++ b/test/http-fixture.test.js@@ -61,7 +61,7 @@ async function startView(t, box) {fail(new Error(reportFixtureChildFailure({ command: process.execPath, args, status, signal,elapsedMs: performance.now() - startedAt, stderr, env: box.env, detail })));};- const timer = setTimeout(() => failStartup('view readiness deadline (30000ms) expired'), 30_000);+ const timer = setTimeout(() => failStartup('view readiness deadline (30000ms) expired'), 30_000); // budget: hang ceiling for private view readiness; no throughput claim.child.stdout.setEncoding('utf8').on('data', (part) => {stdout += part;try {diff --git a/test/person.test.js b/test/person.test.jsindex 979778e7..c2be21e6 100644--- a/test/person.test.js+++ b/test/person.test.js@@ -192,7 +192,7 @@ async function startView(t, box, extraEnv = {}) {fail(new Error(reportFixtureChildFailure({ command: process.execPath, args, status, signal,elapsedMs: performance.now() - startedAt, stderr: diagnostics, env: box.env, detail })));};- const timer = setTimeout(() => failStartup('private view readiness deadline (10000ms) expired'), 10_000);+ const timer = setTimeout(() => failStartup('private view readiness deadline (10000ms) expired'), 10_000); // budget: hang ceiling for private view readiness; no throughput claim.child.stdout.on('data', (part) => {output += part;try {diff --git a/test/relay-browser-fixture.test.js b/test/relay-browser-fixture.test.jsindex 0b5a7314..82287919 100644--- a/test/relay-browser-fixture.test.js+++ b/test/relay-browser-fixture.test.js@@ -100,7 +100,7 @@ test('relay idle readiness waits for a real held request and then observes its cconst deadline = Date.now() + relayWorkBudgetMs(1);while (box.stateReadStarted() === before && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20));assert.ok(box.stateReadStarted() > before);- await assert.rejects(chrome.waitForRelayIdle(200), /did not become idle within 200ms/);+ await assert.rejects(chrome.waitForRelayIdle(200), /did not become idle within 200ms/); // budget: declared 200ms idle deadline for a deliberately stalled page.release();assert.equal(await chrome.pollTask(task), 200);await chrome.waitForRelayIdle();diff --git a/test/relay-person-actions.test.js b/test/relay-person-actions.test.jsindex 58d9cb37..83dc9ae0 100644--- a/test/relay-person-actions.test.js+++ b/test/relay-person-actions.test.js@@ -248,7 +248,7 @@ test('a person action completes with late native snapshots after 8 seconds [H12,assert.equal(status.result.code, 0, 'the real native CLI reports success');const delays = box.snapshotWriteDelays().slice(delayedBefore);assertSnapshotCheckpoints(status.result.snapshotTrace, 3);- assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds'); // budget: declared eight-second native snapshot delay (7900ms lower bound).timing.finish();timing.begin('paired-browser request completion poll', '85,000 ms in-page poll; 110,000 ms outer CDP task bound');const completed = await waitRequest(chrome, link.board, action.result.request.id, 'done');diff --git a/test/relay-person-outbox.test.js b/test/relay-person-outbox.test.jsindex ee124d3c..0f4d2bb5 100644--- a/test/relay-person-outbox.test.js+++ b/test/relay-person-outbox.test.js@@ -126,7 +126,7 @@ test('real Chrome keeps an interrupted person request sealed and retries it onceassert.equal(status.result.snapshotUploads, trace.length);assert.equal(status.result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length), 'the child deadline follows this run’s observed upload count');assertSnapshotCheckpoints(trace, 3);- assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds'); // budget: declared eight-second native snapshot delay (7900ms lower bound).const completed = await waitForRequest(chrome, link.board, requestId, 'done');const exported = (await box.cli('export')).document;const shouts = exported.tables.shout.filter(row => row.shout_from === 'person' && row.shout_text === text);diff --git a/test/relay-person-requests.test.js b/test/relay-person-requests.test.jsindex 0a1d0e21..5be5fa02 100644--- a/test/relay-person-requests.test.js+++ b/test/relay-person-requests.test.js@@ -251,7 +251,7 @@ test('real paired Chrome transports a person shout while its native snapshot isassert.equal(status.result.snapshotUploads, trace.length);assert.equal(status.result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length), 'the child deadline follows this run’s observed upload count');assertSnapshotCheckpoints(trace, 3);- assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds'); // budget: declared eight-second native snapshot delay (7900ms lower bound).timing.finish();timing.begin('paired-browser request completion poll', '85,000 ms in-page poll; 110,000 ms outer CDP task bound');const latest = await waitForRequest(chrome, link.board, receipt.result.request.id, 'done');@@ -296,7 +296,7 @@ test('real paired Chrome approval remains pending until coordinator applies andassert.equal(native.result.code, 0);const delays = box.snapshotWriteDelays().slice(delayedBefore);assertSnapshotCheckpoints(native.result.snapshotTrace, 4);- assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every approval snapshot by 8 seconds');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every approval snapshot by 8 seconds'); // budget: declared eight-second approval snapshot delay (7900ms lower bound).const pendingState = await waitForRequest(chrome, link.board, approval.result.request.id, 'waiting', true);assert.equal(readFileSync(row.path, 'utf8'), before, 'the received approval records a row decision but does not edit SPEC.md');const decisionEvents = (await box.cli('export')).document.tables.event.filter(event => event.event_kind === 'row_decision' && event.event_by === 'person');@@ -410,7 +410,7 @@ test('coordinator decline resolves a paired approval request with a reason and lassert.equal(native.result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length),'the decline status deadline follows its observed uploads');assertSnapshotCheckpoints(trace, 4);- assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every decline snapshot by 8 seconds');+ assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every decline snapshot by 8 seconds'); // budget: declared eight-second decline snapshot delay (7900ms lower bound).const pending = (await finalState(chrome, link.board)).state.personRequests.find(record => record.id === queued.result.request.id);assert.equal(pending.status, 'waiting');assert.ok(Number.isSafeInteger(pending.coordinatorRequest));@@ -455,7 +455,7 @@ test('a timed-out checkpoint PUT retries identical ciphertext through the nativeassertSnapshotCheckpoints(trace, 3);assert.equal(trace.length, 4, 'one product abort adds exactly one transport attempt');assert.equal(trace[1].abort?.name, 'TimeoutError');- assert.ok(trace[1].elapsedMs >= 9900, 'the actual ten-second product request bound expired');+ assert.ok(trace[1].elapsedMs >= 9900, 'the actual ten-second product request bound expired'); // budget: declared ten-second product request deadline (9900ms lower bound).assert.equal(trace[2].sequence, trace[1].sequence);assert.equal(trace[2].ciphertext, trace[1].ciphertext);assert.equal(trace[2].status, 200);@@ -493,7 +493,7 @@ test('a newer acknowledged checkpoint covers an earlier timed-out PUT [H16,C7]',assertSnapshotCheckpoints(trace, 3);assert.equal(trace.length, 3, 'a newer committed checkpoint supersedes the timed-out projection');assert.equal(trace[0].abort?.name, 'TimeoutError');- assert.ok(trace[0].elapsedMs >= 9900, 'the actual ten-second product request bound expired');+ assert.ok(trace[0].elapsedMs >= 9900, 'the actual ten-second product request bound expired'); // budget: declared ten-second product request deadline (9900ms lower bound).assert.ok(trace[1].sequence > trace[0].sequence);assert.ok(trace[2].sequence > trace[1].sequence);assert.equal(trace[2].status, 200);diff --git a/test/relay-retention.test.js b/test/relay-retention.test.jsindex 488df0b5..b2601ed0 100644--- a/test/relay-retention.test.js+++ b/test/relay-retention.test.js@@ -279,7 +279,7 @@ test('[H18] a move holding the shared process lock refreshes activity before an/** Await a specific worker phase with a bounded deadline, without relying on a startup sleep. */function phase(kind) {return new Promise((resolve, reject) => {- const timer = setTimeout(() => { waiters.delete(check); reject(new Error('fixture worker phase timed out')); }, 10_000);+ const timer = setTimeout(() => { waiters.delete(check); reject(new Error('fixture worker phase timed out')); }, 10_000); // budget: hang ceiling for a private worker phase handshake; no throughput claim./** Resolve only the requested safe phase, and surface a fixed refusal code on worker failure. */function check() {const failure = messages.find((entry) => entry.kind === 'failed');diff --git a/test/relay-setup-once.test.js b/test/relay-setup-once.test.jsindex 2cb168ef..06905a28 100644--- a/test/relay-setup-once.test.js+++ b/test/relay-setup-once.test.js@@ -331,7 +331,7 @@ test('a set-up-once run stretched past 30 seconds still gets its approval card [const stretchStarted = Date.now();await new Promise(resolve => setTimeout(resolve, 40_100));const elapsed = Date.now() - stretchStarted;- assert.ok(elapsed >= 40_000, 'the fixture waits at least 40 real seconds; it does not advance a frozen relay clock');+ assert.ok(elapsed >= 40_000, 'the fixture waits at least 40 real seconds; it does not advance a frozen relay clock'); // budget: declared 40100ms fixture sleep must span at least 40 real seconds.const delayed = await project(box, 'delayed-approval-project');const proposal = JSON.parse(readFileSync(machineFile, 'utf8')).approvals.find(entry => entry.root === delayed);diff --git a/test/relay-snapshot-recovery.test.js b/test/relay-snapshot-recovery.test.jsindex 8a2831bd..5c8cdfbf 100644--- a/test/relay-snapshot-recovery.test.js+++ b/test/relay-snapshot-recovery.test.js@@ -77,7 +77,7 @@ test('a delayed native checkpoint recovers the real page after its visible timeoconst timeoutText = 'The relay snapshot has not caught up to this move. Retry this board.';await chrome.waitFor('document.querySelector("#relay-notice")?.textContent.includes(' + JSON.stringify(timeoutText) + ')',45_000, 'actual fifteen-second native checkpoint timeout');- assert.ok(Date.now() - started >= 14_000, 'the production wait elapsed; no clock or fetch was replaced');+ assert.ok(Date.now() - started >= 14_000, 'the production wait elapsed; no clock or fetch was replaced'); // budget: declared fifteen-second native checkpoint wait (14000ms lower bound).assert.equal(await chrome.evaluate('document.querySelector("#chain").textContent.includes(' + JSON.stringify(recovered) + ')'), false);const native = openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));diff --git a/test/resources.test.js b/test/resources.test.jsindex 01a6d6c0..c7692eba 100644--- a/test/resources.test.js+++ b/test/resources.test.js@@ -320,7 +320,7 @@ test('[Q1,Q2] a waiting landing keeps a current holder from taking the second slawait release(secondHolder);assert.equal((await event(landing)).acquired, 'landing');- await assert.rejects(event(secondSlot, 250), /worker timed out/u, 'the holder cannot take its second slot ahead of a waiting landing');+ await assert.rejects(event(secondSlot, 250), /worker timed out/u, 'the holder cannot take its second slot ahead of a waiting landing'); // budget: declared negative observation window while an explicitly held landing blocks this waiter.await release(landing);assert.equal((await event(secondSlot)).acquired, 'same-run');await release(secondSlot);@@ -509,7 +509,7 @@ test('[Q2,Q3] a stopped head waiter keeps its place ahead of the next process',const second = worker(box, { agent: 'second' });assert.equal((await event(second)).waiting, 2);await release(holder);- await assert.rejects(event(second, 800), /worker timed out/u, 'the second waiter cannot jump the stopped head');+ await assert.rejects(event(second, 800), /worker timed out/u, 'the second waiter cannot jump the stopped head'); // budget: declared negative observation window while the stopped queue head blocks this waiter.first.kill('SIGCONT');assert.equal((await event(first)).acquired, 'stopped-first');await release(first);@@ -541,8 +541,8 @@ test('[Q3] a live stalled holder keeps its place beyond the lease timeout', asynassert.equal((await event(holder)).acquired, 'stalled-holder');const waiter = worker(box, { agent: 'queued-behind-live-holder', env: { TZ: 'Pacific/Honolulu', PATH: '/usr/bin' } });assert.equal((await event(waiter)).waiting, 1);- await assert.rejects(event(waiter, 20_500), /worker timed out/u, 'a live OS process must not be evicted when its heartbeat pauses');- assert.equal((await event(holder, 5_000)).resumed, true);+ await assert.rejects(event(waiter, 20_500), /worker timed out/u, 'a live OS process must not be evicted when its heartbeat pauses'); // budget: declared 22000ms holder stall; observe it still held at 20500ms.+ assert.equal((await event(holder, 5_000)).resumed, true); // budget: hang ceiling for the stalled holder resume handshake; no throughput claim.await release(holder);assert.equal((await event(waiter)).acquired, 'queued-behind-live-holder');await release(waiter);@@ -596,8 +596,8 @@ test('[Q3] an unreadable process identity keeps a live holder', { skip: !SANDBOXassert.equal((await acquired(holder)).acquired, 'sandbox-live-holder');const waiter = worker(box, { agent: 'sandbox-live-waiter', sandboxProcessInfo: true });assert.equal((await event(waiter)).waiting, 1);- await assert.rejects(event(waiter, 20_500), /worker timed out/u, 'denied process-info access is not proof that a live PID died');- assert.equal((await event(holder, 8_000)).resumed, true);+ await assert.rejects(event(waiter, 20_500), /worker timed out/u, 'denied process-info access is not proof that a live PID died'); // budget: declared 22000ms holder stall with denied process-info access; observe at 20500ms.+ assert.equal((await event(holder, 8_000)).resumed, true); // budget: hang ceiling for the stalled holder resume handshake; no throughput claim.await release(holder);assert.equal((await acquired(waiter)).acquired, 'sandbox-live-waiter');await release(waiter);@@ -777,7 +777,7 @@ test('[Q4] a red gate releases its lease before the same process starts anothertry {const result = await Promise.race([closed,- new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('the red gate kept its lease and blocked the same process')), 5_000); }),+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('the red gate kept its lease and blocked the same process')), 5_000); }), // budget: hang ceiling for the same process to reacquire its released gate slot.]);assert.equal(result.code, 0, stderr);assert.deepEqual(JSON.parse(stdout.trim()), { firstGreen: false, secondGreen: true });diff --git a/test/row-decisions.test.js b/test/row-decisions.test.jsindex e6b9e7f7..75be1fab 100644--- a/test/row-decisions.test.js+++ b/test/row-decisions.test.js@@ -214,7 +214,7 @@ async function startView(t, box, extraEnv = {}) {rejectDocument(new Error(reportFixtureChildFailure({ command: process.execPath, args, status, signal,elapsedMs: performance.now() - startedAt, stderr, env, detail })));};- const timer = setTimeout(() => failStartup('view readiness deadline (10000ms) expired'), 10_000);+ const timer = setTimeout(() => failStartup('view readiness deadline (10000ms) expired'), 10_000); // budget: hang ceiling for private view readiness; no throughput claim.child.stdout.on('data', (chunk) => {stdout += chunk;try {diff --git a/test/wall-clock-budgets.js b/test/wall-clock-budgets.jsnew file mode 100644index 00000000..3e72d9d9--- /dev/null+++ b/test/wall-clock-budgets.js@@ -0,0 +1,148 @@+/** Find unexplained wall-clock judgments in test source, without executing it [C7]. */+import { readdirSync, readFileSync } from 'node:fs';+import { join, relative } from 'node:path';++/** Mask comments and quoted fixture text while retaining exact offsets and comment lines. */+function codeOnly(source) {+ const comments = new Map();+ let code = '', line = 1;+ for (let i = 0; i < source.length;) {+ const start = i, firstLine = line;+ const quote = source[i];+ if (quote === '"' || quote === "'" || quote === '`') {+ i++;+ while (i < source.length) {+ if (source[i] === '\\') { i += 2; continue; }+ if (source[i++] === quote) break;+ }+ } else if (source.startsWith('//', i)) {+ i = source.indexOf('\n', i);+ if (i < 0) i = source.length;+ comments.set(firstLine, source.slice(start, i));+ } else if (source.startsWith('/*', i)) {+ const end = source.indexOf('*/', i + 2);+ i = end < 0 ? source.length : end + 2;+ source.slice(start, i).split('\n').forEach((part, offset) => comments.set(firstLine + offset, part));+ } else if (quote === '/' && (/[=(:,!&|?;{}\[]\s*$/u.test(code) || /\breturn\s*$/u.test(code))) {+ let characterClass = false;+ i++;+ while (i < source.length) {+ if (source[i] === '\\') { i += 2; continue; }+ if (source[i] === '[') characterClass = true;+ if (source[i] === ']') characterClass = false;+ if (source[i++] === '/' && !characterClass) break;+ }+ while (/[a-z]/iu.test(source[i] ?? '') && i < source.length) i++;+ const skipped = source.slice(start, i);+ const masked = skipped.replace(/[^\n]/gu, ' ');+ code += /\belapsed\b/iu.test(skipped) ? masked.replace(/ {7}/u, 'elapsed') : masked;+ line += skipped.split('\n').length - 1;+ continue;+ } else {+ code += source[i++];+ if (quote === '\n') line++;+ continue;+ }+ const skipped = source.slice(start, i);+ code += skipped.replace(/[^\n]/gu, ' ');+ line += skipped.split('\n').length - 1;+ }+ return { code, comments };+}++/** Read a balanced call or condition, including nested callbacks, from masked source. */+function parenthesized(code, opening) {+ let depth = 0;+ for (let end = opening; end < code.length; end++) {+ if (code[end] === '(') depth++;+ if (code[end] === ')' && --depth === 0) return code.slice(opening, end + 1);+ }+ return code.slice(opening);+}++/** Recognize a direct clock observation or an elapsed-time variable/property. */+function observesTime(expression, aliases) {+ return /\b(?:Date|performance)\s*\.\s*now\s*\(|\bhrtime\s*\(|\b\w*(?:elapsed|duration|wallMs|waitMs|delay)\w*\b(?!\s*\()/iu.test(expression)+ || [...aliases].some(name => new RegExp(`\\b${name}\\b`, 'u').test(expression));+}++/** Split a call at its own commas, never at a nested assertion, callback or argument. */+function argumentsOf(call) {+ const args = [];+ let depth = 0, start = 1;+ for (let i = 1; i < call.length - 1; i++) {+ if ('([{'.includes(call[i])) depth++;+ if (')]}'.includes(call[i])) depth--;+ if (call[i] === ',' && depth === 0) { args.push(call.slice(start, i)); start = i + 1; }+ }+ args.push(call.slice(start, -1));+ return args;+}++/** Recognize literal arguments of wait helpers without crossing their closing parenthesis. */+function literalWait(expression, literals) {+ for (const match of expression.matchAll(/\b(?:\w*wait\w*|event|\w*ClosesWithin|\w*Healthy|\w*Ready)\s*\(/giu)) {+ const call = parenthesized(expression, match.index + match[0].lastIndexOf('('));+ if (argumentsOf(call).some(arg => /^\s*[1-9][0-9_]*\s*$/u.test(arg) || literals.has(arg.trim()))) return true;+ }+ return false;+}++/** Find every literal timing judgment and return its original file, line and source text. */+export function fixedWallMargins(source, file) {+ const { code, comments } = codeOnly(source);+ const lines = source.split('\n');+ const aliases = new Set(), literals = new Set();+ for (const match of code.matchAll(/\b(?:const|let|var)\s+(\w+)\s*=\s*([^;\n]+)/gu)) {+ if (observesTime(match[2], aliases) && /\b(?:Date|performance)\s*\.\s*now\s*\([^)]*\)\s*-/u.test(match[2])) aliases.add(match[1]);+ if (/^\s*[1-9][0-9_]*\s*$/u.test(match[2])) literals.add(match[1]);+ }+ const found = new Map();+ /** Require a same-line reason, including an explicit approved-spec promise that cannot be relaxed. */+ function record(offset, reason) {+ const line = code.slice(0, offset).split('\n').length;+ if (/\bbudget:\s*[^\n]*(?:measur|baseline|deriv|declared|hang|ceiling|approved row [A-Z]\d)[^\n]*\S/iu.test(comments.get(line) ?? '')) return;+ found.set(line, `${file}:${line}: ${reason}: ${lines[line - 1].trim()}`);+ }+ const literal = '(?:[1-9][0-9_]*(?:\\.[0-9_]+)?)';+ const margin = new RegExp(`(?:[<>]=?\\s*${literal}\\b|\\b${literal}\\s*[<>]=?)`, 'u');+ for (const match of code.matchAll(/\bassert(?:\s*\.\s*(\w+))?\s*\(/gu)) {+ const call = parenthesized(code, match.index + match[0].lastIndexOf('('));+ const args = argumentsOf(call), expression = args[0];+ const fixedAlias = [...literals].some(name => new RegExp(`[<>]=?\\s*${name}\\s*$|^\\s*${name}\\s*[<>]=?`, 'u').test(expression));+ if (observesTime(expression, aliases) && (margin.test(expression) || fixedAlias || /^(equal|strictEqual)$/u.test(match[1] ?? '') && new RegExp(`^\\s*${literal}\\s*$`, 'u').test(args[1] ?? ''))) {+ record(match.index, 'literal elapsed-time margin');+ }+ if ((match[1] === 'rejects' || /\bawait\s+/u.test(expression)) && literalWait(expression, literals)) record(match.index, 'literal wait judged by an assertion');+ }+ for (const match of code.matchAll(/\bsetTimeout\s*\(/gu)) {+ const call = parenthesized(code, match.index + match[0].lastIndexOf('('));+ if (/\b(?:reject|throw|fail\w*)\b/iu.test(call) && /,\s*[1-9][0-9_]*\s*\)$/u.test(call)) record(match.index, 'literal timeout reports failure');+ }+ for (const match of code.matchAll(/\bif\s*\(/gu)) {+ const opening = match.index + match[0].lastIndexOf('(');+ const call = parenthesized(code, opening);+ const following = code.slice(opening + call.length, opening + call.length + 100);+ if (/\bawait\s+/u.test(call) && literalWait(call, literals)+ && /\b(?:throw|return\s+(?:false|null))\b/u.test(following)) record(match.index, 'literal wait reports failure');+ }+ return [...found.values()];+}++/** Scan every test file under a checkout, including nested tests and documentation tests. */+export function wallClockViolations(root) {+ const found = [];+ /** Walk source directories without visiting generated artifacts, dependencies or preserved work. */+ function visit(directory) {+ for (const entry of readdirSync(directory, { withFileTypes: true })) {+ const path = join(directory, entry.name);+ if (entry.isDirectory()) {+ if (!['.git', 'node_modules', 'work'].includes(entry.name)) visit(path);+ } else if (entry.isFile() && /(?:^test[-_.].+|.+[-_.]test)\.[cm]?js$/u.test(entry.name)) {+ found.push(...fixedWallMargins(readFileSync(path, 'utf8'), relative(root, path).replaceAll('\\', '/')));+ }+ }+ }+ visit(root);+ return found.sort();+}diff --git a/test/wall-clock-budgets.test.js b/test/wall-clock-budgets.test.jsnew file mode 100644index 00000000..55558c53--- /dev/null+++ b/test/wall-clock-budgets.test.js@@ -0,0 +1,39 @@+/** Keep test timing judgments accountable to their actual work [C7]. */+import assert from 'node:assert/strict';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { test } from 'node:test';+import { wallClockViolations } from './wall-clock-budgets.js';++test('no test judges work by a fixed wall-clock margin [C7]', () => {+ assert.deepEqual(wallClockViolations(fileURLToPath(new URL('..', import.meta.url))), []);+});++test('the clock-margin guard catches planted source and names its file and line [C7]', () => {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-wall-clock-'));+ try {+ mkdirSync(join(root, 'nested'));+ const file = join(root, 'nested', 'planted.test.mjs');+ const bare = 'const start = Date.now();\nassert.ok(Date.now() - start < 30_000);\n';+ writeFileSync(file, bare);+ assert.match(wallClockViolations(root).join('\n'), /nested\/planted\.test\.mjs:2: literal elapsed-time margin/u);+ assert.throws(() => assert.deepEqual(wallClockViolations(root), []), error =>+ error.code === 'ERR_ASSERTION' && /nested\/planted\.test\.mjs:2/u.test(error.message), 'a planted bare clock margin makes the real guard red');+ writeFileSync(file, bare.replace('< 30_000);', '< 30_000); // budget: hang ceiling only; no throughput claim.'));+ assert.deepEqual(wallClockViolations(root), []);+ writeFileSync(file, 'const spent = performance.now() - start;\nassert.ok(spent < 1500);\nawait assert.rejects(waitFor(child, 1500));\n');+ assert.deepEqual(wallClockViolations(root).map(line => Number(/:(\d+):/u.exec(line)[1])), [2, 3]);+ writeFileSync(file, 'const budgetMs = 1500;\nassert.ok(elapsed < budgetMs);\nawait assert.rejects(waitFor(child, budgetMs));\n');+ assert.deepEqual(wallClockViolations(root).map(line => Number(/:(\d+):/u.exec(line)[1])), [2, 3]);+ writeFileSync(file, 'const text = "assert.ok(Date.now() - start < 1)";\nassert.equal(response.status, 200);\nassert.ok(elapsed < measuredBaseline * 3);\n');+ assert.deepEqual(wallClockViolations(root), []);+ writeFileSync(file, 'if (!await childClosesWithin(child, 1500)) return null;\nsetTimeout(() => reject(new Error("late")), 1500);\nassert.ok(elapsed < 1500); // budget: because I said so\n');+ assert.deepEqual(wallClockViolations(root).map(line => Number(/:(\d+):/u.exec(line)[1])), [1, 2, 3]);+ writeFileSync(file, 'await assert.rejects(browser(), error => {\n assert.ok(elapsed >= 30000); // budget: declared startup timeout.\n});\nassert.equal((await event(worker)).waiting, 1);\nassert.equal(durationMs("2h"), 7200000);\nconst matcher = /[\'"`]/u;\nassert.ok(Date.now() - start < 1500);\n');+ assert.deepEqual(wallClockViolations(root).map(line => Number(/:(\d+):/u.exec(line)[1])), [7]);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+});