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
fix(test): guard awaited timing ceilings and all test sources [C7]
Corey Olsonefdb2b946ef9
diff --git a/test/approved-row-changes.test.js b/test/approved-row-changes.test.jsindex 2bd16892..c5b85078 100644--- a/test/approved-row-changes.test.js+++ b/test/approved-row-changes.test.js@@ -161,9 +161,9 @@ test('[C7] cleanup diagnostics capture a forced late writer without hiding ENOTEelse assert.ok(owners.includes(`pid=${writer.pid}`) || owners.startsWith('unavailable'), owners);} finally {if (writer.exitCode === null && writer.signalCode === null) writer.stdin.end('exit\n');- let closed = await waitForClose(writerClosed, 2_000);+ let closed = await waitForClose(writerClosed, 2_000); // budget: declared two-second cleanup grace before escalating termination; no throughput claim.if (!closed) writer.kill('SIGTERM');- if (!closed) closed = await waitForClose(writerClosed, 2_000);+ if (!closed) closed = await waitForClose(writerClosed, 2_000); // budget: declared two-second cleanup grace before SIGKILL; no throughput claim.if (!closed) writer.kill('SIGKILL');if (!closed) await writerClosed;}@@ -200,9 +200,9 @@ test('[C7] cleanup diagnostics name the owner when lsof is slow', async () => {} finally {process.env.PATH = originalPath;if (writer.exitCode === null && writer.signalCode === null) writer.stdin.end();- let closed = await waitForClose(writerClosed, 2_000);+ let closed = await waitForClose(writerClosed, 2_000); // budget: declared two-second cleanup grace before escalating termination; no throughput claim.if (!closed) writer.kill('SIGTERM');- if (!closed) closed = await waitForClose(writerClosed, 2_000);+ if (!closed) closed = await waitForClose(writerClosed, 2_000); // budget: declared two-second cleanup grace before SIGKILL; no throughput claim.if (!closed) writer.kill('SIGKILL');if (!closed) await writerClosed;rmSync(directory, { recursive: true, force: true });@@ -223,12 +223,9 @@ test('[C7] cleanup diagnostics report the lsof timeout budget', () => {chmodSync(lsof, 0o755);const error = Object.assign(new Error('forced non-empty fixture cleanup'), { code: 'ENOTEMPTY', path: directory });let report;- let captureElapsedMs = 0;try {process.env.PATH = `${shimDir}:${originalPath}`;- const captureStarted = Date.now();- try { report = cleanupFailureReport(error, directory); }- finally { captureElapsedMs = Date.now() - captureStarted; }+ report = cleanupFailureReport(error, directory);} finally {process.env.PATH = originalPath;rmSync(directory, { recursive: true, force: true });diff --git a/test/chrome-fixture.test.js b/test/chrome-fixture.test.jsindex 59ec2c32..8e7767d1 100644--- a/test/chrome-fixture.test.js+++ b/test/chrome-fixture.test.js@@ -251,7 +251,7 @@ test('a failed DevTools command names its CDP error [C7]', {let chrome;try {chrome = await startChrome({ url: `${origin}/before` });- await chrome.waitFor("location.pathname === '/before' && document.body.textContent === 'before'", 5_000, 'initial document ready'); // budget: bounds a missing local fixture document+ await chrome.waitFor("location.pathname === '/before' && document.body.textContent === 'before'", 5_000, 'initial document ready'); // budget: hang ceiling for the private initial document handshake; no throughput claim.const navigationUrl = `${origin}/after`;const navigation = chrome.evaluate(`(() => {@@ -265,7 +265,7 @@ test('a failed DevTools command names its CDP error [C7]', {assert.match(navigationError.message, /CDP error -\d+: .+/u);assert.match(navigationError.message, /Inspected target navigated or closed/u);assert.match(navigationError.message, /page navigated since command was sent: yes \(Page\.(?:frameStartedNavigating|frameNavigated)\)/u);- await chrome.waitFor("location.pathname === '/after' && document.body.textContent === 'after'", 5_000, 'replacement document ready'); // budget: bounds a missing local fixture document+ await chrome.waitFor("location.pathname === '/after' && document.body.textContent === 'after'", 5_000, 'replacement document ready'); // budget: hang ceiling for the private replacement document handshake; no throughput claim.assert.equal(afterRequests, 1, 'the pending evaluation lost a race with one real HTTP navigation');const rejected = await chrome.send('Runtime.noSuchCommand', {}, 'unsupported CDP method').then(() => null, (error) => error);@@ -293,7 +293,7 @@ test('a stalled condition uses its remaining operation budget [C7]', {scheduler.enable();const startedAt = Date.now();let failure;- try { await chrome.waitFor('new Promise(() => {})', budgetMs, 'bounded condition'); }+ try { await chrome.waitFor('new Promise(() => {})', budgetMs, 'bounded condition'); } // budget: declared 250ms operation deadline for a deliberately unresolved page condition.catch (error) { failure = error; }const elapsedMs = Date.now() - startedAt;scheduler.disable();@@ -378,7 +378,7 @@ test('a wait that throws while the page changes keeps waiting [C7]', async (t) =const chrome = await startChrome({ url: `http://127.0.0.1:${server.address().port}/before` });try {- await chrome.waitFor("typeof window.goNext === 'function'", 5_000, 'initial document ready');+ await chrome.waitFor("typeof window.goNext === 'function'", 5_000, 'initial document ready'); // budget: hang ceiling for the private navigation control handshake; no throughput claim.await chrome.evaluate('setTimeout(() => window.goNext(), 0); true');const expression = "location.pathname === '/next' && document.body === null ? (() => { if (!window.__gapNotified) { window.__gapNotified = true; fetch('/observed-null'); } return document.body.textContent.includes('ready'); })() : document.body?.textContent.includes('ready') === true";const waiting = chrome.waitFor(expression, 5_000, 'wait for the replacement document')diff --git a/test/gate-resource.test.js b/test/gate-resource.test.jsindex 47887741..5a8e01d8 100644--- a/test/gate-resource.test.js+++ b/test/gate-resource.test.js@@ -173,7 +173,7 @@ test('[Q4,O5,O6] gate processes run one at a time in FIFO order when machine sloassert.equal(setting.status, 0, setting.stderr);assert.equal(JSON.parse(setting.stdout).settings.gateSlots, 1);const first = launch(box, roots[0]);- await waitFor(() => events(box).includes('first start') && !events(box).includes('first end'), 'first gate to remain active', 30_000);+ await waitFor(() => events(box).includes('first start') && !events(box).includes('first end'), 'first gate to remain active', 30_000); // budget: hang ceiling for the private first-gate marker handshake; no throughput claim.const second = launch(box, roots[1]);await waitFor(() => second.stdoutText.includes('place 1'), 'second gate to enter the FIFO line');assert.match(second.stdoutText, /1 running/);@@ -268,7 +268,7 @@ test('[Q4] an exact-tree cached gate starts while another machine gate holds theassert.equal(warm.status, 0, warm.stderr);const priorCount = events(box).filter((line) => line.startsWith('cached ')).length;const holder = launch(box, holderRoot);- await waitFor(() => events(box).includes('holder start') && !events(box).includes('holder end'), 'uncached holder gate to remain active', 30_000);+ await waitFor(() => events(box).includes('holder start') && !events(box).includes('holder end'), 'uncached holder gate to remain active', 30_000); // budget: hang ceiling for the private holder-gate marker handshake; no throughput claim.const refusedChange = spawnSync(process.execPath, [BIN, 'settings', 'gateSlots', '2', '--json'], { cwd: cachedRoot, env: box.env, encoding: 'utf8' });assert.equal(refusedChange.status, 1);assert.equal(JSON.parse(refusedChange.stdout).error.code, 'RESOURCE_BUSY');@@ -392,7 +392,7 @@ test('a raw full-suite run takes a machine gate slot [Q4]', async () => {try {await waitFor(() => events(box).includes('full-suite-holder start'), 'the fixture gate to hold its only machine slot');fullRun = launchTestRunner(box, suiteRoot, args, marker, releaseProbe);- const outcome = await waitFor(() => {+ const outcome = await waitFor(() => { // budget: hang ceiling for the raw runner to announce its actual queue state; no throughput claim.if (fullRun.stderrText.includes('waiting for a gate slot:')) return 'waiting';if (existsSync(marker)) return 'ran';return false;@@ -469,7 +469,7 @@ syncBuiltinESMExports();const runner = launchTestRunner(box, root, [], marker, null, env);let assertionError;try {- await waitFor(() => existsSync(ready), 'the probe write to pause after creating its destination', 30_000);+ await waitFor(() => existsSync(ready), 'the probe write to pause after creating its destination', 30_000); // budget: hang ceiling for the private paused-write marker handshake; no throughput claim.if (existsSync(marker)) assert.equal(readFileSync(marker, 'utf8'), '1', 'a visible marker already has its complete slot value');} catch (error) {assertionError = error;@@ -499,7 +499,7 @@ test('a focused run takes no slot [Q4]', async () => {'--disable-warning', 'ExperimentalWarning', '--title', 'focused-slot-probe','test/probe.test.js',], marker);- const outcome = await waitFor(() => {+ const outcome = await waitFor(() => { // budget: hang ceiling for the focused runner to announce its actual start state; no throughput claim.if (existsSync(marker)) return 'ran';if (focusedRun.stderrText.includes('waiting for a gate slot:')) return 'waiting';return false;@@ -529,7 +529,7 @@ test('a full run nested under a held gate does not take a second slot [Q4]', asysetOneGateSlot(box, gateRoot);const nestedGate = launch({ ...box, env: { ...box.env, [PROBE_PATH_ENV]: marker } }, gateRoot);try {- const outcome = await waitFor(() => {+ const outcome = await waitFor(() => { // budget: hang ceiling for the nested runner marker handshake; no throughput claim.if (existsSync(marker)) return 'completed';if (existsSync(output) && readFileSync(output, 'utf8').includes('waiting for a gate slot:')) return 'queued';return false;diff --git a/test/land.test.js b/test/land.test.jsindex 5e69ce45..9afc0c89 100644--- a/test/land.test.js+++ b/test/land.test.js@@ -333,7 +333,7 @@ test('land bisect adoption retains completed gates, isolated diagnostics and oriwriteFileSync(box.release, 'release');if (child.exitCode === null && child.signalCode === null) { try { process.kill(-child.pid, 'SIGKILL'); } catch {} }});- await waitFor(() => existsSync(box.entered), 'third full gate inside bisection', 20000);+ await waitFor(() => existsSync(box.entered), 'third full gate inside bisection', 20000); // budget: hang ceiling for the third private bisection gate entry handshake; no throughput claim.const interrupted = json(box, box.repo, 'resume').landingBatches.at(-1);assert.equal(interrupted.items.length, 2, 'the current half differs from the original four candidates');assert.equal(interrupted.gateResults.length, 2);diff --git a/test/relay-approval-delivery.test.js b/test/relay-approval-delivery.test.jsindex 4d6ab8ce..38c49ae3 100644--- a/test/relay-approval-delivery.test.js+++ b/test/relay-approval-delivery.test.js@@ -186,7 +186,7 @@ test('an approval delivered while the page is busy still becomes a card [H15,H12})()`;const preloadScript = await chrome.send('Page.addScriptToEvaluateOnNewDocument', { source: preload });await chrome.send('Page.reload');- await chrome.waitFor('window.__keyLoadGate?.started === true', 20_000, 'the real browser is loading its wrapped board key');+ await chrome.waitFor('window.__keyLoadGate?.started === true', 20_000, 'the real browser is loading its wrapped board key'); // budget: hang ceiling for the deliberately held key-load stage handshake; no throughput claim.const firstToken = await issueToken(box, 'approval-key-load');const keyLoad = await startRevocation(box, native, firstToken.id);const deviceId = JSON.parse(readFileSync(join(box.env.PULLBOARD_HOME, 'relay-machine/state.json'), 'utf8')).devices[0].deviceId;@@ -234,7 +234,7 @@ test('an approval delivered while the page is busy still becomes a card [H15,H12await holdNextApprovalDecrypt(chrome);const secondToken = await issueToken(box, 'approval-render');const render = await startRevocation(box, native, secondToken.id);- await chrome.waitFor('window.__approvalDecrypt?.started === true', 20_000, 'the real sealed approval is being decrypted before rendering');+ await chrome.waitFor('window.__approvalDecrypt?.started === true', 20_000, 'the real sealed approval is being decrypted before rendering'); // budget: hang ceiling for the deliberately held approval-decrypt stage handshake; no throughput claim.assert.equal(await chrome.evaluate(`document.querySelector('#phone-approve-${render.context.id}') === null`), true,'the card is not asserted before actual decryption finishes');assert.ok((await chrome.evaluate('window.__approvalObservations')).some(poll => poll.ids.includes(render.context.id)),@@ -263,7 +263,7 @@ test('an approval delivered while the page is busy still becomes a card [H15,H12await chrome.waitFor(`document.querySelector('#phone-approve-${earlier.context.id}') !== null`);await holdAuthorizeResponse(chrome, earlier.context.id);await chrome.evaluate(`document.querySelector('#phone-approve-${earlier.context.id}').click()`);- await chrome.waitFor('window.__authorizeGate?.started === true', 20_000, 'the first real approval is in flight');+ await chrome.waitFor('window.__authorizeGate?.started === true', 20_000, 'the first real approval is in flight'); // budget: hang ceiling for the deliberately held authorize-response stage handshake; no throughput claim.const second = await startRevocation(box, native, deviceId);assert.equal(second.context.action, 'revoke-device');await chrome.waitFor(`document.querySelector('#phone-approve-${second.context.id}') !== null`);diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.jsindex 5d5ba067..692d128e 100644--- a/test/relay-client-fixture.js+++ b/test/relay-client-fixture.js@@ -196,7 +196,7 @@ globalThis.fetch = function tracedFetch(input, init) {let revokeOnNextListing = false;const boardsWithoutSnapshots = new Map();const injectedSnapshotWriteDelayMs = Number(process.env.PULLBOARD_TEST_SNAPSHOT_WRITE_DELAY_MS ?? 0);- assert.ok(Number.isSafeInteger(injectedSnapshotWriteDelayMs) && injectedSnapshotWriteDelayMs >= 0 && injectedSnapshotWriteDelayMs <= 15000,+ assert.ok(Number.isSafeInteger(injectedSnapshotWriteDelayMs) && injectedSnapshotWriteDelayMs >= 0 && injectedSnapshotWriteDelayMs <= 15000, // budget: declared snapshot-delay fixture input range is 0..15000ms; configuration validation, not throughput.'injected snapshot delay is within the product wait bound');let snapshotWriteDelayMs = 0;let oneSnapshotDelay = null;diff --git a/test/relay-snapshot-recovery.test.js b/test/relay-snapshot-recovery.test.jsindex 5c8cdfbf..fae8d3bc 100644--- a/test/relay-snapshot-recovery.test.js+++ b/test/relay-snapshot-recovery.test.js@@ -75,7 +75,7 @@ test('a delayed native checkpoint recovers the real page after its visible timeoconst sent = await upload(box, { ...link, token: agent.token }, 'moves', 1, await encoded(key, move, link.board, 'move', 1));const started = Date.now();const 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) + ')',+ await chrome.waitFor('document.querySelector("#relay-notice")?.textContent.includes(' + JSON.stringify(timeoutText) + ')', // budget: hang ceiling for observing the declared fifteen-second checkpoint timeout; no throughput claim.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'); // budget: declared fifteen-second native checkpoint wait (14000ms lower bound).assert.equal(await chrome.evaluate('document.querySelector("#chain").textContent.includes(' + JSON.stringify(recovered) + ')'), false);diff --git a/test/seal.test.js b/test/seal.test.jsindex ed7d6e0f..f2637888 100644--- a/test/seal.test.js+++ b/test/seal.test.js@@ -216,7 +216,7 @@ test('headless Chrome loads the unchanged module and exchanges sealed bytes withawait new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));try {chrome = await startChrome({ executable, profileDirectory: profile, url: 'http://127.0.0.1:' + server.address().port + '/' });- await chrome.waitFor("document.body.dataset.sealResult === 'pass'", 30_000);+ await chrome.waitFor("document.body.dataset.sealResult === 'pass'", 30_000); // budget: hang ceiling for the private browser interoperability result handshake; no throughput claim.} catch (error) {assert.fail(`Chrome interoperability failed; requested fixture routes: ${[...requests].sort().join(', ')}; ${error.message}`);}diff --git a/test/wall-clock-budgets.js b/test/wall-clock-budgets.jsindex 3e72d9d9..06a882f5 100644--- a/test/wall-clock-budgets.js+++ b/test/wall-clock-budgets.js@@ -101,7 +101,7 @@ export function fixedWallMargins(source, file) {/** 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;+ if (/\bbudget:\s*[^\n]*(?:measur|baseline|deriv|declared|hang|ceiling|approved row [A-Z]\d|after\s+[1-9][0-9,_]*\s*ms)[^\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_]+)?)';@@ -113,7 +113,11 @@ export function fixedWallMargins(source, file) {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');+ if ((['rejects', 'doesNotReject'].includes(match[1]) || /\bawait\s+/u.test(expression)) && literalWait(expression, literals)) record(match.index, 'literal wait judged by an assertion');+ }+ for (const match of code.matchAll(/\bawait\s+(?:\w+\s*\.\s*)*\w*waitFor\w*\s*\(/giu)) {+ const call = parenthesized(code, match.index + match[0].lastIndexOf('('));+ if (literalWait(match[0] + call.slice(1), literals)) record(match.index, 'literal awaited wait can fail the test');}for (const match of code.matchAll(/\bsetTimeout\s*\(/gu)) {const call = parenthesized(code, match.index + match[0].lastIndexOf('('));@@ -133,12 +137,13 @@ export function fixedWallMargins(source, file) {export function wallClockViolations(root) {const found = [];/** Walk source directories without visiting generated artifacts, dependencies or preserved work. */- function visit(directory) {+ function visit(directory, underTestDirectory = false) {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)) {+ if (!['.git', 'node_modules', 'work'].includes(entry.name)) visit(path, underTestDirectory || entry.name === 'test');+ } else if (entry.isFile() && /\.[cm]?js$/u.test(entry.name)+ && (underTestDirectory || /^(?:test|test[-_.].+|.+[-_.]test)\.[cm]?js$/u.test(entry.name))) {found.push(...fixedWallMargins(readFileSync(path, 'utf8'), relative(root, path).replaceAll('\\', '/')));}}diff --git a/test/wall-clock-budgets.test.js b/test/wall-clock-budgets.test.jsindex 55558c53..edf20ec8 100644--- a/test/wall-clock-budgets.test.js+++ b/test/wall-clock-budgets.test.js@@ -23,8 +23,12 @@ test('the clock-margin guard catches planted source and names its file and lineerror.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, 'assert.ok(Date.now() - start > 10_000); // budget: the stand-in publishes DevToolsActivePort after 10,100 ms.\n');+ assert.deepEqual(wallClockViolations(root), [], 'a concrete fixture publication delay explains the budget without special vocabulary');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, 'await assert.doesNotReject(waitFor(child, 1500));\nawait chrome.waitFor(ready, 1500);\n');+ assert.deepEqual(wallClockViolations(root).map(line => Number(/:(\d+):/u.exec(line)[1])), [1, 2]);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');@@ -33,6 +37,12 @@ test('the clock-margin guard catches planted source and names its file and lineassert.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]);+ writeFileSync(file, '');+ mkdirSync(join(root, 'test'));+ writeFileSync(join(root, 'test', 'helper.js'), bare);+ writeFileSync(join(root, 'test.js'), bare);+ assert.deepEqual(wallClockViolations(root).map(line => line.split(':')[0]).sort(), ['test.js', 'test/helper.js'],+ 'plain test.js and every JavaScript file under test/ are part of native discovery');} finally {rmSync(root, { recursive: true, force: true });}