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(core): refresh fixture connections [N38,C7]
Corey Olsonffec7795f0f3
diff --git a/test/api-http.test.js b/test/api-http.test.jsindex 52c698a7..fcbb3880 100644--- a/test/api-http.test.js+++ b/test/api-http.test.js@@ -13,6 +13,7 @@ import { createApiHandler } from '../src/api-http.js';import { registryFile, registerProject } from '../src/projects.js';import { Refused } from '../src/refused.js';import * as store from '../src/board.js';+import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');@@ -69,7 +70,7 @@ async function httpBox(t, { includeMissing = false } = {}) {const origin = url.origin;/** Make a real HTTP call and decode its single versioned response. */async function call(path, value, headers = {}) {- const response = await fetch(origin + path, {+ const response = await fetchFresh(origin + path, {method: value === undefined ? 'GET' : 'POST',headers: { 'x-pullboard-key': key, ...(value === undefined ? {} : { 'content-type': 'application/json' }), ...headers },...(value === undefined ? {} : { body: JSON.stringify(value) }),@@ -151,7 +152,7 @@ test('[A2, N33, N35] API listing refreshes live labels and preserves missing-entconst key = url.searchParams.get('k');/** Fetch the authenticated board catalog through the real local HTTP server. */async function listing() {- const response = await fetch(url.origin + '/api/v1/boards', { headers: { 'x-pullboard-key': key } });+ const response = await fetchFresh(url.origin + '/api/v1/boards', { headers: { 'x-pullboard-key': key } });assert.equal(response.status, 200);return response.json();}@@ -322,7 +323,7 @@ test('[A2] a live HTTP stream follows CLI writes and reconnects after Last-Eventconst initial = await box.call(box.path + '/events');const after = initial.document.events.at(-1).event_id;const controller = new AbortController();- const response = await fetch(box.origin + box.path + '/events?after=' + after, { headers: { 'x-pullboard-key': box.key, accept: 'text/event-stream' }, signal: controller.signal });+ const response = await fetchFresh(box.origin + box.path + '/events?after=' + after, { headers: { 'x-pullboard-key': box.key, accept: 'text/event-stream' }, signal: controller.signal });assert.match(response.headers.get('content-type'), /text\/event-stream/);const reader = response.body.getReader();let buffered = '';@@ -349,7 +350,7 @@ test('[A2] a live HTTP stream follows CLI writes and reconnects after Last-Eventassert.equal(live.id, live.document.event.event_id);await reader.cancel();controller.abort();- const replay = await fetch(box.origin + box.path + '/events?after=0', { headers: { 'x-pullboard-key': box.key, 'last-event-id': String(live.id) } });+ const replay = await fetchFresh(box.origin + box.path + '/events?after=0', { headers: { 'x-pullboard-key': box.key, 'last-event-id': String(live.id) } });assert.deepEqual((await replay.json()).events, []);const invalid = await box.call(box.path + '/events?after=1.5');assert.equal(invalid.status, 400);@@ -358,7 +359,7 @@ test('[A2] a live HTTP stream follows CLI writes and reconnects after Last-Eventtest('[A2] local auth, origin, unknown board and malformed calls refuse without moving', async (t) => {const box = await httpBox(t);- const unauthenticated = await fetch(box.origin + '/api/v1/boards');+ const unauthenticated = await fetchFresh(box.origin + '/api/v1/boards');assert.equal(unauthenticated.status, 401);assert.equal((await unauthenticated.json()).error.code, 'AUTH_REQUIRED');const badSecret = await box.call('/api/v1/boards', undefined, { 'x-pullboard-key': 'incorrect-private-fixture-key' });@@ -369,7 +370,7 @@ test('[A2] local auth, origin, unknown board and malformed calls refuse withoutassert.equal(unknown.status, 404);const unknownStream = await box.call('/api/v1/boards/' + '0'.repeat(32) + '/events', undefined, { accept: 'text/event-stream' });assert.equal(unknownStream.status, 404);- const malformed = await fetch(box.origin + box.path + '/moves', { method: 'POST', headers: { 'x-pullboard-key': box.key, 'content-type': 'application/json' }, body: '{broken' });+ const malformed = await fetchFresh(box.origin + box.path + '/moves', { method: 'POST', headers: { 'x-pullboard-key': box.key, 'content-type': 'application/json' }, body: '{broken' });assert.equal(malformed.status, 400);assert.equal((await malformed.json()).error.code, 'BAD_REQUEST');const unsupported = await box.call(box.path + '/moves', { verb: 'run', args: { agent: 'unsafe' } });@@ -438,7 +439,7 @@ test('[A2] shared transport stops a live stream when its caller loses access', at.after(() => controller.abort());const timeout = setTimeout(() => controller.abort(), 10_000);t.after(() => clearTimeout(timeout));- const response = await fetch('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + '/events?after=' + records().at(-1).event_id, { headers: { accept: 'text/event-stream' }, signal: controller.signal });+ const response = await fetchFresh('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + '/events?after=' + records().at(-1).event_id, { headers: { accept: 'text/event-stream' }, signal: controller.signal });const reader = response.body.getReader();await reader.read();authorized = false;@@ -468,7 +469,7 @@ test('[A2] adapters without a committed-code capability return a versioned refusawait new Promise((done) => server.listen(0, '127.0.0.1', done));t.after(() => new Promise((done) => { handler.close(); server.close(done); }));const id = 'fixture-board';- const response = await fetch('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + '/code?ref=secret.txt%3A1%40abcdef0');+ const response = await fetchFresh('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + '/code?ref=secret.txt%3A1%40abcdef0');const document = await response.json();assert.equal(response.status, 400);assert.equal(document.version, 1);diff --git a/test/api.test.js b/test/api.test.jsindex 565a22c0..67c564ff 100644--- a/test/api.test.js+++ b/test/api.test.js@@ -21,6 +21,7 @@ import { allShouts, closeBoard, EVENT_LOG_VERSION, openBoard } from '../src/boarimport { presentationShout, relayPresentation } from '../src/relay-presentation.js';import { JSON_SHAPES } from '../src/json.js';import { SSH_SHELL_MARKERS } from '../src/person.js';+import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const TEMP_DIRS = [];@@ -692,11 +693,11 @@ async function startApi(t, box) {return { child, document, origin: parsed.origin, secret, stderr: () => stderr };}-/** Send one bounded HTTP request to the fixture API, authenticating by header unless overridden. */+/** Send one bounded HTTP request to the fixture API on its own connection, authenticating by header unless overridden. */function apiFetch(api, path, options = {}) {const { noSecret = false, ...requestOptions } = options;const headers = { ...(noSecret ? {} : { 'x-pullboard-key': api.secret }), ...requestOptions.headers };- return fetch(new URL(path, api.origin), { ...requestOptions, headers, signal: requestOptions.signal ?? AbortSignal.timeout(10_000) });+ return fetchFresh(new URL(path, api.origin), { ...requestOptions, headers, signal: requestOptions.signal ?? AbortSignal.timeout(10_000) });}/** Parse and validate a versioned API refusal. */diff --git a/test/e2e-cli.test.js b/test/e2e-cli.test.jsindex c56f70c1..bff20ef5 100644--- a/test/e2e-cli.test.js+++ b/test/e2e-cli.test.js@@ -26,6 +26,7 @@ import { checkAtCommit } from '../src/trusted-policy.js';import * as store from '../src/board.js';import { createE2eHelpers } from './e2e-helpers.js';+import { fetchFresh } from './http-fixture.js';const e2e = createE2eHelpers();after(e2e.cleanup);const {@@ -128,13 +129,13 @@ test('the tour registers a labelled demo that view lists and forget removes [N10const view = await startView(box, box.repo);try {- const listing = await fetch(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': view.key } });+ const listing = await fetchFresh(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': view.key } });assert.equal(listing.status, 200);assert.deepEqual((await listing.json()).boards.map(({ root, name }) => [root, name]), [[box.repo, 'repo'], [demoRoot, 'demo']]);const forgotten = box.run(box.dir, 'forget', demoRoot);assert.equal(forgotten.code, 0, forgotten.err);assert.match(forgotten.out, /forgot/);- const after = await fetch(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': view.key } });+ const after = await fetchFresh(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': view.key } });assert.deepEqual((await after.json()).boards.map(({ root, name }) => [root, name]), [[box.repo, 'repo']]);} finally {await view.stop();diff --git a/test/e2e-helpers.js b/test/e2e-helpers.jsindex 2a0ec8b9..5e28d9e4 100644--- a/test/e2e-helpers.js+++ b/test/e2e-helpers.js@@ -10,6 +10,7 @@ import { connect } from 'node:net';import { join, resolve } from 'node:path';import * as store from '../src/board.js';import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';+import { fetchFresh } from './http-fixture.js';/** Create isolated real-repository helpers for one parallel end-to-end test file. */export function createE2eHelpers() {@@ -167,7 +168,7 @@ async function startView(box, cwd) {* Keeping these paths in one fixture lets the API assertions stay independent of page auth.*/const page = async () => {- const response = await fetch(link, { redirect: 'manual' });+ const response = await fetchFresh(link, { redirect: 'manual' });if (response.status === 200) return response;assert.equal(response.status, 303, 'the printed link either serves the legacy page or exchanges its key');@@ -187,13 +188,13 @@ async function startView(box, cwd) {assert.ok(attributes.some((attribute) => /^samesite=strict$/iu.test(attribute)), 'the session cookie is SameSite=Strict');assert.ok(attributes.some((attribute) => /^path=\/$/iu.test(attribute)), 'the session cookie is scoped to the view');- const pageResponse = await fetch(location, { headers: { cookie: pair }, redirect: 'manual' });+ const pageResponse = await fetchFresh(location, { headers: { cookie: pair }, redirect: 'manual' });assert.equal(pageResponse.status, 200, 'the cookie jar fetches the page after the exchange');return pageResponse;};/** Read the public listing through the view's real authenticated API. */const boards = async () => {- const response = await fetch(`${base}/api/v1/boards`, { headers });+ const response = await fetchFresh(`${base}/api/v1/boards`, { headers });return { status: response.status, document: await response.json() };};/** Resolve a registered board id and read its public state. */@@ -202,7 +203,7 @@ async function startView(box, cwd) {if (listing.status !== 200) return listing;const board = listing.document.boards.find((entry) => entry.root === root);if (!board) return { ...listing.document, project: null };- const response = await fetch(`${base}/api/v1/boards/${encodeURIComponent(board.id)}/state`, { headers });+ const response = await fetchFresh(`${base}/api/v1/boards/${encodeURIComponent(board.id)}/state`, { headers });return { ...listing.document, project: (await response.json()).state };};/** Send a public move to the registered board or a deliberately unknown id. */@@ -210,7 +211,7 @@ async function startView(box, cwd) {const listing = await boards();const board = listing.document.boards?.find((entry) => entry.root === root);const id = board?.id ?? '0'.repeat(32);- const response = await fetch(`${base}/api/v1/boards/${encodeURIComponent(id)}/moves`, {+ const response = await fetchFresh(`${base}/api/v1/boards/${encodeURIComponent(id)}/moves`, {method: 'POST',headers: { ...headers, 'content-type': 'application/json' },body: JSON.stringify(body),diff --git a/test/e2e-view.test.js b/test/e2e-view.test.jsindex dd7d8cad..d773b503 100644--- a/test/e2e-view.test.js+++ b/test/e2e-view.test.js@@ -26,6 +26,7 @@ import { checkAtCommit } from '../src/trusted-policy.js';import * as store from '../src/board.js';import { createE2eHelpers } from './e2e-helpers.js';+import { fetchFresh } from './http-fixture.js';const e2e = createE2eHelpers();after(e2e.cleanup);const {@@ -42,8 +43,8 @@ test('view serves every project on this machine, on loopback, behind its secretassert.deepEqual(registry.projects.map((entry) => entry.root), [box.repo]);const view = await startView(box, box.repo);try {- assert.equal((await fetch(`${view.base}/`)).status, 403, 'no secret');- const badSecret = await fetch(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': 'guess' } });+ assert.equal((await fetchFresh(`${view.base}/`)).status, 403, 'no secret');+ const badSecret = await fetchFresh(`${view.base}/api/v1/boards`, { headers: { 'x-pullboard-key': 'guess' } });assert.equal(badSecret.status, 401, 'a wrong secret');assert.equal((await badSecret.json()).error.code, 'AUTH_REQUIRED');const page = await view.page();@@ -97,7 +98,7 @@ test('from the view the person adds items, shouts and holds lanes, through the Cassert.equal(unknown.document.error.code, 'NO_BOARD');const before = await view.state(box.repo);const target = before.boards.find((entry) => entry.root === box.repo);- const stranger = await fetch(`${view.base}/api/v1/boards/${encodeURIComponent(target.id)}/moves`, {+ const stranger = await fetchFresh(`${view.base}/api/v1/boards/${encodeURIComponent(target.id)}/moves`, {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify({ verb: 'shout', args: { to: 'all', text: 'unauthorized move' } }),diff --git a/test/git-calls.test.js b/test/git-calls.test.jsindex 966fea40..109f7405 100644--- a/test/git-calls.test.js+++ b/test/git-calls.test.js@@ -9,6 +9,7 @@ import { main } from '../src/cli.js';import { headCommit, withGitFacts } from '../src/git.js';import { serveApi } from '../src/api.js';import { pathToFileURL } from 'node:url';+import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const RUN_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/run.js')).href;@@ -135,12 +136,12 @@ function advanceHead(box, label, branch = 'main') {async function readServedBranchCode(api, branch) {const address = new URL(api.url);const headers = { 'x-pullboard-key': address.searchParams.get('k') };- const listing = await fetch(address, { headers });+ const listing = await fetchFresh(address, { headers });assert.equal(listing.status, 200);const board = (await listing.json()).boards[0];assert.ok(board?.id, 'the fixture board is listed');const path = `${address.pathname}/${encodeURIComponent(board.id)}/code?ref=${encodeURIComponent(`SPEC.md:1@${branch}`)}`;- const response = await fetch(address.origin + path, { headers });+ const response = await fetchFresh(address.origin + path, { headers });const document = await response.json();assert.equal(response.status, 200, JSON.stringify(document));return document.code.commit;diff --git a/test/http-fixture.js b/test/http-fixture.jsnew file mode 100644index 00000000..1f37b9dd--- /dev/null+++ b/test/http-fixture.js@@ -0,0 +1,43 @@+/** Fixture HTTP requests never reuse an idle connection, so a stalled test cannot meet a closed socket [C7]. */++/**+ * Send one request to a live fixture server on a connection of its own, and name the cause if it fails.+ *+ * The view and API servers close a keep-alive socket after Node's default 5 s of idle. A test that+ * blocks its own event loop for longer, with spawnSync of a CLI for one, sends its next request on a+ * pooled socket the server has already closed, and fetch reports the reset only as "fetch failed".+ * Asking for connection: close leaves no idle socket behind, so no later request can land on one.+ *+ * @param {string | URL} url+ * @param {RequestInit} [init]+ * @returns {Promise<Response>}+ */+export async function fetchFresh(url, init = {}) {+ const headers = new Headers(init.headers);+ headers.set('connection', 'close');+ try {+ return await fetch(url, { ...init, headers });+ } catch (error) {+ // The path names the request; the query is left out because fixtures carry their key there.+ const message = `${init.method ?? 'GET'} ${new URL(url).pathname} failed: ${causeChain(error)}`;+ // A network failure keeps fetch's shape, a TypeError whose cause holds the socket error, so a caller+ // that reads error.cause.code still can. An abort or a timeout is rethrown as it is.+ if (error instanceof TypeError) throw new TypeError(message, { cause: error.cause ?? error });+ throw error;+ }+}++/**+ * Describe an error and every cause beneath it, so "fetch failed" says which socket error it hides.+ *+ * @param {unknown} error+ * @returns {string}+ */+export function causeChain(error) {+ const links = [];+ for (let current = error; current !== undefined && current !== null && links.length < 8; current = current.cause) {+ const label = typeof current.code === 'string' ? current.code : current.name;+ links.push([label, current.message ?? String(current)].filter(Boolean).join(': '));+ }+ return links.join(' <- ');+}diff --git a/test/http-fixture.test.js b/test/http-fixture.test.jsnew file mode 100644index 00000000..cccf3c49--- /dev/null+++ b/test/http-fixture.test.js@@ -0,0 +1,115 @@+/** Fixture requests reach a live server even after the test blocked its own event loop past keep-alive [C7]. */+import assert from 'node:assert/strict';+import { execFileSync, spawn, spawnSync } from 'node:child_process';+import { once } from 'node:events';+import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs';+import { createServer } from 'node:http';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { test } from 'node:test';+import { serveApi } from '../src/api.js';+import { main } from '../src/cli.js';+import { fetchFresh } from './http-fixture.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');+/** Longer than the 5 s keep-alive the view and API servers inherit from node:http. */+const BLOCKED_MS = 6_000;++/** Block this event loop the way a synchronous CLI child does, without spending CPU on it. */+function blockEventLoop(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++/** Build a private initialized board with its own home, so the view serves only this fixture. */+function privateBoard(t) {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-http-fixture-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const root = join(dir, 'repo');+ const home = join(dir, 'home');+ mkdirSync(root);+ mkdirSync(home);+ const env = { ...process.env, HOME: home, PULLBOARD_HOME: home, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' };+ execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: root, env });+ const init = spawnSync(process.execPath, [BIN, 'init', '--json'], { cwd: root, env, encoding: 'utf8' });+ assert.equal(init.status, 0, `${init.stdout}${init.stderr}`);+ return { root, env };+}++/** Start the real view as a child process, stop it with the test, and return its origin and key. */+async function startView(t, box) {+ const child = spawn(process.execPath, [BIN, 'view', '--no-open', '--port', '0', '--json'], {+ cwd: box.root, env: box.env, stdio: ['ignore', 'pipe', 'pipe'],+ });+ const closed = once(child, 'close');+ t.after(async () => {+ if (child.exitCode !== null || child.signalCode !== null) return;+ child.kill('SIGTERM');+ await closed;+ });+ let stdout = '';+ let stderr = '';+ child.stderr.setEncoding('utf8').on('data', (part) => { stderr += part; });+ const document = await new Promise((ready, fail) => {+ const timer = setTimeout(() => fail(new Error(`view printed no address within 30 s: ${stderr}`)), 30_000);+ child.stdout.setEncoding('utf8').on('data', (part) => {+ stdout += part;+ try { ready(JSON.parse(stdout)); clearTimeout(timer); }+ catch { /* Wait until the one JSON document is complete. */ }+ });+ child.once('close', (code) => { clearTimeout(timer); fail(new Error(`view exited ${code} before printing its address: ${stderr}`)); });+ });+ const url = new URL(document.url);+ return { origin: url.origin, key: url.searchParams.get('k') };+}++test('[C7] each fixture request opens its own connection, and a failed one names its socket error', async (t) => {+ const sockets = [];+ const connection = [];+ const server = createServer((req, res) => {+ sockets.push(req.socket);+ connection.push(req.headers.connection);+ res.end('ok');+ });+ server.listen(0, '127.0.0.1');+ await once(server, 'listening');+ t.after(() => { if (server.listening) { server.closeAllConnections(); server.close(); } });+ const origin = `http://127.0.0.1:${server.address().port}`;+ for (let index = 0; index < 3; index += 1) assert.equal(await (await fetchFresh(`${origin}/`)).text(), 'ok');+ assert.deepEqual(connection, ['close', 'close', 'close'], 'every request asks the server to close its connection');+ assert.equal(new Set(sockets).size, 3, 'no request reuses a pooled connection');++ server.closeAllConnections();+ await new Promise((done) => server.close(done));+ await assert.rejects(fetchFresh(`${origin}/api/v1/boards?k=fixture-secret`), (error) => {+ assert.match(error.message, /^GET \/api\/v1\/boards failed: TypeError: fetch failed <- ECONNREFUSED: /u);+ assert.doesNotMatch(error.message, /fixture-secret/u, 'the request key stays out of the failure');+ assert.ok(error instanceof TypeError, 'the failure keeps the shape fetch gives it');+ assert.equal(error.cause?.code, 'ECONNREFUSED', 'its cause still carries the socket error code');+ return true;+ });+});++test('[C7] a fixture request after a blocked event loop reaches the view child and the in-process API', async (t) => {+ const box = privateBoard(t);+ const view = await startView(t, box);+ const api = await serveApi({ runCommand: main, projects: () => [{ root: box.root, name: 'HTTP fixture' }] });+ t.after(() => api.close());+ const apiUrl = new URL(api.url);+ const servers = [['the view child', view.origin, view.key], ['the in-process API', apiUrl.origin, apiUrl.searchParams.get('k')]];+ /** List boards from each live server, as the suite's live-server requests do. */+ async function listBoards(when) {+ for (const [name, origin, key] of servers) {+ const response = await fetchFresh(`${origin}/api/v1/boards`, { headers: { 'x-pullboard-key': key } });+ assert.equal(response.status, 200, `${name} answers ${when}`);+ assert.ok(Array.isArray((await response.json()).boards), `${name} returns its board listing ${when}`);+ }+ }+ // Two rounds first: with a pooled connection, the second round leaves an idle socket to reuse.+ await listBoards('before the stall');+ await listBoards('before the stall, again');+ blockEventLoop(BLOCKED_MS);+ await assert.doesNotReject(+ listBoards(`after a ${BLOCKED_MS / 1000} s blocked event loop`),+ 'fresh connections still reach both servers after a blocked event loop',+ );+});diff --git a/test/person.test.js b/test/person.test.jsindex 8f7cac37..9e9dc79e 100644--- a/test/person.test.js+++ b/test/person.test.js@@ -8,6 +8,7 @@ import { DatabaseSync } from 'node:sqlite';import { once } from 'node:events';import { test } from 'node:test';import { SSH_SHELL_MARKERS } from '../src/person.js';+import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const MARKERS = {@@ -196,7 +197,7 @@ async function startView(t, box, extraEnv = {}) {const secret = address.searchParams.get('k');assert.ok(secret, 'the actual view starts with its private session credentials');/** Send bounded authenticated requests through the same adapter the view uses. */- const request = (path, options = {}) => fetch(new URL(path, address.origin), {+ const request = (path, options = {}) => fetchFresh(new URL(path, address.origin), {...options, headers: { 'x-pullboard-key': secret, ...options.headers }, signal: AbortSignal.timeout(10_000),});return request;diff --git a/test/project-meta.test.js b/test/project-meta.test.jsindex bdf73a76..fff8cedd 100644--- a/test/project-meta.test.js+++ b/test/project-meta.test.js@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { test } from 'node:test';import { serveView } from '../src/serve.js';+import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');@@ -47,7 +48,7 @@ test('the API exposes configured repo/project names, refreshed labels, stale warconst link = new URL(view.url);/** Read the public listing without pruning unavailable registered roots. */const boards = async () => {- const response = await fetch(`${link.origin}/api/v1/boards`, { headers: { 'x-pullboard-key': link.searchParams.get('k') } });+ const response = await fetchFresh(`${link.origin}/api/v1/boards`, { headers: { 'x-pullboard-key': link.searchParams.get('k') } });assert.equal(response.status, 200);const document = await response.json();assert.equal(document.version, 1);diff --git a/test/relay-agent.test.js b/test/relay-agent.test.jsindex 93f8e128..c8fd55f3 100644--- a/test/relay-agent.test.js+++ b/test/relay-agent.test.js@@ -14,6 +14,7 @@ import { ENGINE_VERSION } from '../src/machine.js';import { decodeBoardKey, unseal } from '../src/seal.js';import { frozenCriterion, parseSpec } from '../src/spec.js';import { relayClientFixture } from './relay-client-fixture.js';+import { fetchFresh } from './http-fixture.js';/** Invoke one real CLI command without retaining stderr or exposing private command output. */function runCli(root, env, cli, args) {@@ -158,7 +159,7 @@ test('ordered agent joins mint scoped tokens and retain authenticated native actconst tokenUrl = new URL(`/api/v1/boards/${personState.board}/tokens`, localApi.url);tokenUrl.searchParams.set('k', new URL(localApi.url).searchParams.get('k'));const apiHeaders = { 'content-type': 'application/json' };- const apiListResponse = await fetch(tokenUrl, { headers: apiHeaders });+ const apiListResponse = await fetchFresh(tokenUrl, { headers: apiHeaders });assert.equal(apiListResponse.status, 200, 'local API reads the real relay token inventory');const apiList = await apiListResponse.json();assert.deepEqual(apiList.tokens.map((row) => row.agent).sort(), [firstAgent, secondAgent].sort());@@ -182,7 +183,7 @@ test('ordered agent joins mint scoped tokens and retain authenticated native actconst revoke = await box.cli('relay', 'revoke', firstTokenRow.id);assert.equal(revoke.code, 0, 'CLI revokes one listed opaque token id');- const apiRevokeResponse = await fetch(tokenUrl, {+ const apiRevokeResponse = await fetchFresh(tokenUrl, {method: 'POST', headers: apiHeaders, body: JSON.stringify({ id: firstTokenRow.id }),});assert.equal(apiRevokeResponse.status, 200, 'local API accepts the opaque id-only revocation body');diff --git a/test/relay-client.test.js b/test/relay-client.test.jsindex a33ea186..ebdbf257 100644--- a/test/relay-client.test.js+++ b/test/relay-client.test.js@@ -22,6 +22,7 @@ import { appliedSequence, prepareEngineMove } from '../src/engine.js';import { storeBoardKey } from '../src/relay-key.js';import { ENGINE_VERSION } from '../src/machine.js';import { presentationShout } from '../src/relay-presentation.js';+import { fetchFresh } from './http-fixture.js';const SIGN_INS = new Map();@@ -574,7 +575,7 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lconst localApi = await serveApi({ runCommand: apiCommand, projects: () => [{ root: clones[0], name: 'Clone API' }] });try {const address = new URL(localApi.url);- const response = await fetch(`${address.origin}/api/v1/boards/${boardId}/moves`, {+ const response = await fetchFresh(`${address.origin}/api/v1/boards/${boardId}/moves`, {method: 'POST', headers: { 'x-pullboard-key': address.searchParams.get('k'), 'content-type': 'application/json' },body: JSON.stringify({ verb: 'add', args: { lane: 'web', title: 'This API item' } }),});@@ -589,7 +590,7 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lconst apiLostHeaders = { 'x-pullboard-key': address.searchParams.get('k'), 'content-type': 'application/json' };const beforeLostApi = relay.uploads.length;relay.dropNextReply({ offline: true });- const lostApi = await fetch(`${address.origin}/api/v1/boards/${boardId}/moves`, {+ const lostApi = await fetchFresh(`${address.origin}/api/v1/boards/${boardId}/moves`, {method: 'POST', headers: apiLostHeaders, body: apiLostBody,});const lostApiResult = await lostApi.json();@@ -597,7 +598,7 @@ test('[H3,H16] three cloned linked replicas order competing claims and recover lassert.equal(lostApiResult.error.code, 'RELAY_UNAVAILABLE');relay.failReads(false);await cli(clones[0], envs[0], 'status');- const apiRetry = await fetch(`${address.origin}/api/v1/boards/${boardId}/moves`, {+ const apiRetry = await fetchFresh(`${address.origin}/api/v1/boards/${boardId}/moves`, {method: 'POST', headers: apiLostHeaders, body: apiLostBody,});const apiRetryResult = await apiRetry.json();diff --git a/test/relay.test.js b/test/relay.test.jsindex a87cb45d..613886e6 100644--- a/test/relay.test.js+++ b/test/relay.test.js@@ -13,6 +13,7 @@ import { serveRelay } from '../relay/service.js';import { githubFixture } from './relay-fixture.js';import { relayClientFixture } from './relay-client-fixture.js';import { serveView } from '../src/serve.js';+import { fetchFresh } from './http-fixture.js';/** Use real private SQLite and an actual HTTP provider with a controllable expiry clock. */async function fixture(t, options = {}) {@@ -500,7 +501,7 @@ test('offline linked reads use the local board, moves refuse, and the same relaylet view;try {view = await serveView({ port: 0 });- const page = await fetch(view.url);+ const page = await fetchFresh(view.url);assert.equal(page.status, 200, 'the real local view page remains available');assert.match(page.headers.get('content-type') ?? '', /text\/html/);@@ -517,14 +518,14 @@ test('offline linked reads use the local board, moves refuse, and the same relayconst viewKey = new URL(view.url).searchParams.get('k');const localBoardsUrl = new URL('/api/v1/boards', view.url);localBoardsUrl.searchParams.set('k', viewKey);- const localBoardsResponse = await fetch(localBoardsUrl);+ const localBoardsResponse = await fetchFresh(localBoardsUrl);assert.equal(localBoardsResponse.status, 200, 'the local view API remains available offline');const localBoards = await localBoardsResponse.json();const localBoard = localBoards.boards.find(board => board.root === box.root);assert.ok(localBoard, 'the local view still lists the linked project from its local registry');const localStateUrl = new URL(`/api/v1/boards/${localBoard.id}/state`, view.url);localStateUrl.searchParams.set('k', viewKey);- const localStateResponse = await fetch(localStateUrl);+ const localStateResponse = await fetchFresh(localStateUrl);assert.equal(localStateResponse.status, 200);const localState = await localStateResponse.json();assert.ok(localState.state.items.some(item => item.title === 'private cleanup fixture item'),@@ -542,7 +543,7 @@ test('offline linked reads use the local board, moves refuse, and the same relay}const viewMoveUrl = new URL(`/api/v1/boards/${localBoard.id}/moves`, view.url);viewMoveUrl.searchParams.set('k', viewKey);- const viewMove = await fetch(viewMoveUrl, {+ const viewMove = await fetchFresh(viewMoveUrl, {method: 'POST', headers: { 'content-type': 'application/json' },body: JSON.stringify({ verb: 'add', args: { lane: box.lane, title: 'refused offline view move' } }),});diff --git a/test/review-queue-cli.test.js b/test/review-queue-cli.test.jsindex 191cf3d3..5097630c 100644--- a/test/review-queue-cli.test.js+++ b/test/review-queue-cli.test.js@@ -10,6 +10,7 @@ import * as store from '../src/board.js';import { main } from '../src/cli.js';import { serveApi } from '../src/api.js';import { loadConfig } from '../src/config.js';+import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const HOUR = 3_600_000;@@ -142,9 +143,9 @@ test('[Q1,V15,A2] authenticated API next returns a real unreserved offer and exprunCommand: (args, io) => main(args, { ...io, clock: box.clock }) });t.after(() => api.close());const boardId = store.boardId(box.board);- /** Send one bounded authenticated move through the real local HTTP adapter. */+ /** Send one bounded authenticated move through the real local HTTP adapter, on its own connection. */async function next(args) {- const response = await fetch(`${new URL(api.url).origin}/api/v1/boards/${boardId}/moves`, { method: 'POST',+ const response = await fetchFresh(`${new URL(api.url).origin}/api/v1/boards/${boardId}/moves`, { method: 'POST',headers: { 'x-pullboard-key': apiKey, 'content-type': 'application/json' },body: JSON.stringify({ verb: 'next', agent: box.builderId, args }), signal: AbortSignal.timeout(30_000) });assert.equal(response.status, 200, await response.clone().text());diff --git a/test/row-decisions.test.js b/test/row-decisions.test.jsindex 376710cc..93830a19 100644--- a/test/row-decisions.test.js+++ b/test/row-decisions.test.js@@ -8,6 +8,7 @@ import { DatabaseSync } from 'node:sqlite';import { after, test } from 'node:test';import { parseSpec } from '../src/spec.js';import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';+import { fetchFresh } from './http-fixture.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const SPEC_FILE = 'SPEC.md';@@ -215,7 +216,7 @@ async function startView(t, box, extraEnv = {}) {/** Send a bounded authenticated request to the live view adapter. */async function request(path, options = {}) {try {- return await fetch(new URL(path, address.origin), {+ return await fetchFresh(new URL(path, address.origin), {...options,headers: { 'x-pullboard-key': key, ...options.headers },signal: AbortSignal.timeout(10_000),@@ -224,14 +225,18 @@ async function startView(t, box, extraEnv = {}) {let timer;await Promise.race([closed, new Promise((resolveStatus) => { timer = setTimeout(resolveStatus, 500); })]);clearTimeout(timer);- const causeCode = error?.cause?.code ?? error?.code ?? 'no-code';+ const causeCode = error?.cause?.cause?.code ?? error?.cause?.code ?? error?.code ?? 'no-code';+ const causeChain = [];+ for (let current = error; current !== undefined && current !== null && causeChain.length < 8; current = current.cause) {+ causeChain.push([current.code ?? current.name, current.message].filter(Boolean).join(': '));+ }const processStatus = child.exitCode !== null? `exit code=${child.exitCode}`: child.signalCode !== null ? `signal=${child.signalCode}`: spawnError ? `spawn error code=${spawnError.code ?? spawnError.name}` : 'still running';const stderr = [...stderrTail, ...(stderrPartial ? [stderrPartial] : [])].slice(-20);const lines = stderr.length ? stderr.join('\n') : '<no stderr output>';- throw new Error(`view request failed after 1 attempt (no retry): fetch cause code=${causeCode}; child ${processStatus}; stderr last 20 lines:\n${lines}`, { cause: error });+ throw new Error(`view request failed after 1 attempt (no retry): fetch cause code=${causeCode}; cause chain ${causeChain.join(' <- ')}; child ${processStatus}; stderr last 20 lines:\n${lines}`, { cause: error });}}request.stopView = stopView;diff --git a/test/stats-cli.test.js b/test/stats-cli.test.jsindex 115932d1..187ea65d 100644--- a/test/stats-cli.test.js+++ b/test/stats-cli.test.js@@ -9,6 +9,7 @@ import * as store from '../src/board.js';import { main } from '../src/cli.js';import { proofStats } from '../src/stats.js';import { serveApi } from '../src/api.js';+import { fetchFresh } from './http-fixture.js';/** Capture the real CLI without spawning a second model or changing the machine's registry. */async function run(root, args) {@@ -91,7 +92,7 @@ test('[R1,R2,A2] local HTTP state exposes exactly the command statistics', asynct.after(() => api.close());const url = new URL(api.url);const headers = { 'x-pullboard-key': url.searchParams.get('k') };- const response = await fetch(`${url.origin}/api/v1/boards/${store.boardId(board)}/state`, { headers });+ const response = await fetchFresh(`${url.origin}/api/v1/boards/${store.boardId(board)}/state`, { headers });assert.equal(response.status, 200);const document = await response.json();const command = await run(root, ['stats', '--json']);diff --git a/test/thread.test.js b/test/thread.test.jsindex 540b9d1d..54caaf7b 100644--- a/test/thread.test.js+++ b/test/thread.test.js@@ -12,6 +12,7 @@ import * as store from '../src/board.js';import { applyEngineMove, prepareEngineMove } from '../src/engine.js';import { ENGINE_VERSION } from '../src/machine.js';import { exportBoard, importBoard } from '../src/exchange.js';+import { fetchFresh } from './http-fixture.js';const HOUR = 3_600_000;const SHA = 'a'.repeat(40);@@ -252,13 +253,13 @@ async function threadHttpBox(t) {t.after(() => api.close());const url = new URL(api.url);const key = url.searchParams.get('k');- const catalogResponse = await fetch(url.origin + '/api/v1/boards', { headers: { 'x-pullboard-key': key } });+ const catalogResponse = await fetchFresh(url.origin + '/api/v1/boards', { headers: { 'x-pullboard-key': key } });assert.equal(catalogResponse.status, 200);const catalog = await catalogResponse.json();const id = catalog.boards[0].id;- /** Send an authenticated JSON request and return its HTTP status and decoded body. */+ /** Send an authenticated JSON request on its own connection and return its HTTP status and decoded body. */async function call(path, value) {- const response = await fetch(url.origin + path, {+ const response = await fetchFresh(url.origin + path, {method: value === undefined ? 'GET' : 'POST',headers: { 'x-pullboard-key': key, ...(value === undefined ? {} : { 'content-type': 'application/json' }) },...(value === undefined ? {} : { body: JSON.stringify(value) }),