Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

test(core): diagnose fixture cleanup writers [C7]

Corey Olson4e82e777499a
diff --git a/bin/run-tests.js b/bin/run-tests.js
index fd2604eb..450d814a 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -121,9 +121,13 @@ function testEnvironment(sandbox) {
env.TEMP = sandbox;
env.GIT_CONFIG_GLOBAL = '/dev/null';
env.GIT_CONFIG_NOSYSTEM = '1';
- env.GIT_CONFIG_COUNT = '1';
+ env.GIT_CONFIG_COUNT = '3';
env.GIT_CONFIG_KEY_0 = 'user.useConfigOnly';
env.GIT_CONFIG_VALUE_0 = 'true';
+ env.GIT_CONFIG_KEY_1 = 'gc.auto';
+ env.GIT_CONFIG_VALUE_1 = '0';
+ env.GIT_CONFIG_KEY_2 = 'maintenance.auto';
+ env.GIT_CONFIG_VALUE_2 = 'false';
env.PATH = [shims, process.env.PATH].filter(Boolean).join(delimiter);
delete env.PULLBOARD_RELAY_TOKEN; // Fixtures must supply their own scoped credentials, never an agent’s live bearer.
delete env.NODE_TEST_CONTEXT;
diff --git a/test/approved-row-changes.test.js b/test/approved-row-changes.test.js
index 1d93e21b..e4e19fb2 100644
--- a/test/approved-row-changes.test.js
+++ b/test/approved-row-changes.test.js
@@ -1,11 +1,13 @@
/** Approved-row edits need an exact person decision or staged SSH receipt [S19,V3]. */
import assert from 'node:assert/strict';
-import { execFileSync, spawnSync } from 'node:child_process';
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { execFileSync, spawn, spawnSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
+import { once } from 'node:events';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { after, test } from 'node:test';
import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';
+import { removeFixtureDirectory } from './cleanup-diagnostics.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
const TEMP_DIRS = [];
@@ -19,7 +21,16 @@ const SPEC = `# Approved row edit fixture
/** Delete every private repo, key and home created by this file. */
function cleanup() {
- for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });
+ for (const dir of TEMP_DIRS) removeFixtureDirectory(dir);
+}
+
+/** Wait for an owned child to close, clearing the timeout as soon as it settles. */
+function waitForClose(closePromise, timeoutMs) {
+ let timer;
+ return Promise.race([
+ closePromise,
+ new Promise(resolvePromise => { timer = setTimeout(() => resolvePromise(false), timeoutMs); }),
+ ]).finally(() => clearTimeout(timer));
}
after(cleanup);
@@ -42,7 +53,7 @@ function shellWord(value) {
function fixture(t, { signer = false, doctrine = false } = {}) {
const dir = mkdtempSync(join(tmpdir(), 'pullboard-approved-row-'));
TEMP_DIRS.push(dir);
- t.after(() => rmSync(dir, { recursive: true, force: true }));
+ t.after(() => removeFixtureDirectory(dir));
const root = join(dir, 'repo');
const bin = join(dir, 'bin');
mkdirSync(root);
@@ -57,6 +68,13 @@ function fixture(t, { signer = false, doctrine = false } = {}) {
PULLBOARD_MACHINE_HOME: join(dir, 'machine-home'),
GIT_CONFIG_GLOBAL: '/dev/null',
GIT_CONFIG_NOSYSTEM: '1',
+ GIT_CONFIG_COUNT: '3',
+ GIT_CONFIG_KEY_0: 'user.useConfigOnly',
+ GIT_CONFIG_VALUE_0: 'true',
+ GIT_CONFIG_KEY_1: 'gc.auto',
+ GIT_CONFIG_VALUE_1: '0',
+ GIT_CONFIG_KEY_2: 'maintenance.auto',
+ GIT_CONFIG_VALUE_2: 'false',
};
/** Run Git while preserving this fixture's local identity and the hook's active index. */
function git(...args) {
@@ -95,6 +113,60 @@ function fixture(t, { signer = false, doctrine = false } = {}) {
return { dir, root, env, git, pullboard };
}
+test('[C7] cleanup diagnostics capture a forced late writer without hiding ENOTEMPTY', async (t) => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-cleanup-control-'));
+ t.after(() => removeFixtureDirectory(directory));
+ const target = join(directory, 'repo');
+ mkdirSync(target);
+ writeFileSync(join(target, 'initial'), 'force a real non-empty-directory error');
+ const lateFile = join(target, 'late-write');
+ const source = `const fs = require('node:fs'); let descriptor; process.stdin.setEncoding('utf8'); process.stdin.on('data', data => { if (data.includes('write')) { descriptor = fs.openSync(${JSON.stringify(lateFile)}, 'w'); fs.writeSync(descriptor, 'written after the cleanup failure'); console.log('late-write-ready'); } if (data.includes('exit')) { if (descriptor !== undefined) fs.closeSync(descriptor); process.exit(0); } }); console.log('writer-ready');`;
+ const writer = spawn(process.execPath, ['-e', source], { stdio: ['pipe', 'pipe', 'pipe'], env: { PATH: process.env.PATH } });
+ const writerClosed = once(writer, 'close').then(() => true, () => true);
+ let output = '';
+ writer.stdout.setEncoding('utf8');
+ writer.stdout.on('data', chunk => { output += chunk; });
+ /** Wait for a child control handshake while keeping the owning test responsible for cleanup. */
+ const waitForOutput = async (text) => {
+ const deadline = Date.now() + 5_000;
+ while (!output.includes(text) && Date.now() < deadline) await new Promise(resolvePromise => setTimeout(resolvePromise, 10));
+ assert.ok(output.includes(text), `writer output did not include ${text}: ${output}`);
+ };
+ try {
+ await waitForOutput('writer-ready');
+ let report = '';
+ let failure;
+ try {
+ removeFixtureDirectory(target, {
+ remove: () => {
+ try { rmdirSync(target); } catch (error) { failure = error; }
+ assert.equal(failure?.code, 'ENOTEMPTY', 'the control uses a real filesystem cleanup failure');
+ writer.stdin.write('write\n');
+ const deadline = Date.now() + 5_000;
+ while (!existsSync(lateFile) && Date.now() < deadline) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10);
+ assert.ok(existsSync(lateFile), 'the child made a real late file after cleanup failed');
+ throw failure;
+ },
+ emit: message => { report += message; },
+ });
+ } catch (error) { failure = error; }
+ assert.equal(failure?.code, 'ENOTEMPTY', 'diagnostic capture preserves the original cleanup error');
+ assert.match(report, /late-write/);
+ const lateMtime = new Date(statSync(lateFile).mtimeMs).toISOString();
+ assert.ok(report.includes(lateMtime), `the report records the actual late-file mtime ${lateMtime}`);
+ const owners = report.split('open-file owners:\n')[1] ?? '';
+ if (process.platform === 'darwin') assert.match(owners, new RegExp(`pid=${writer.pid}\\b`));
+ else 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);
+ if (!closed) writer.kill('SIGTERM');
+ if (!closed) closed = await waitForClose(writerClosed, 2_000);
+ if (!closed) writer.kill('SIGKILL');
+ if (!closed) await writerClosed;
+ }
+});
+
/** Replace one row's prose while preserving status, tier and every trailing field. */
function setRowText(box, id, text) {
const file = join(box.root, 'SPEC.md');
diff --git a/test/check.test.js b/test/check.test.js
index 6e46c0a6..b4675362 100644
--- a/test/check.test.js
+++ b/test/check.test.js
@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { after, test } from 'node:test';
+import { removeFixtureDirectory } from './cleanup-diagnostics.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
const TEMP_DIRS = [];
@@ -16,7 +17,7 @@ const SPEC = `# Check ownership fixture
`;
after(() => {
- for (const dir of TEMP_DIRS) rmSync(dir, { recursive: true, force: true });
+ for (const dir of TEMP_DIRS) removeFixtureDirectory(dir);
});
/** Quote a literal executable path for the fixture hook's POSIX shim. */
diff --git a/test/cleanup-diagnostics.js b/test/cleanup-diagnostics.js
new file mode 100644
index 00000000..44871dcf
--- /dev/null
+++ b/test/cleanup-diagnostics.js
@@ -0,0 +1,67 @@
+/** Capture bounded filesystem and live-holder evidence for a fixture cleanup failure. */
+import { readdirSync, rmSync, statSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+
+/** List the newest filesystem entries below a failed cleanup path. */
+function newestEntries(directory) {
+ const entries = [];
+ /** Walk only the failing fixture tree and retain paths with their actual mtimes. */
+ function visit(path) {
+ let children;
+ try { children = readdirSync(path, { withFileTypes: true }); }
+ catch (error) { entries.push({ path, error: error.code ?? error.message, mtimeMs: 0 }); return; }
+ for (const child of children) {
+ const file = join(path, child.name);
+ try {
+ const stat = statSync(file);
+ entries.push({ path: file, mtimeMs: stat.mtimeMs });
+ if (child.isDirectory()) visit(file);
+ } catch (error) { entries.push({ path: file, error: error.code ?? error.message, mtimeMs: 0 }); }
+ }
+ }
+ visit(directory);
+ return entries.sort((left, right) => right.mtimeMs - left.mtimeMs).slice(0, 12);
+}
+
+/** Report processes with open files under the fixture tree without exposing arguments or environment. */
+function fileOwners(directory) {
+ const result = spawnSync('lsof', ['-nP', '-Fpcn', '+D', directory], {
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 3_000,
+ });
+ if (result.error) return `unavailable (${result.error.code ?? result.error.message})`;
+ if (result.status !== 0 && !result.stdout) return `unavailable (lsof exit ${result.status})`;
+ const owners = [];
+ let current = {};
+ for (const line of (result.stdout ?? '').split('\n')) {
+ const value = line.slice(1);
+ if (line.startsWith('p')) {
+ current = { pid: value, command: '', paths: [] };
+ owners.push(current);
+ } else if (line.startsWith('c') && current.pid) current.command = value;
+ else if (line.startsWith('n') && current.pid) current.paths.push(value);
+ }
+ return owners.filter(owner => owner.paths.length)
+ .slice(0, 12)
+ .map(owner => `pid=${owner.pid} command=${owner.command || '(unknown)'} paths=${owner.paths.slice(0, 3).join(',')}`)
+ .join('\n') || 'none';
+}
+
+/** Format evidence after a real ENOTEMPTY error, keeping paths scoped to the fixture. */
+export function cleanupFailureReport(error, directory) {
+ const entries = newestEntries(directory);
+ const listing = entries.map(entry => ` ${new Date(entry.mtimeMs).toISOString()} ${entry.path}${entry.error ? ` (${entry.error})` : ''}`).join('\n') || ' (no entries found)';
+ return `cleanup ${error.code ?? 'error'} at ${error.path ?? directory}\nnewest fixture entries:\n${listing}\nopen-file owners:\n${fileOwners(directory)}`;
+}
+
+/** Remove a test fixture and retain bounded evidence if a concurrent writer prevents cleanup.
+ * @param {string} directory
+ * @param {{ remove?: () => void, emit?: (message: string) => void }} [options] - Real filesystem operation and evidence sink, overridable for a deterministic control.
+ */
+export function removeFixtureDirectory(directory, { remove = () => rmSync(directory, { recursive: true, force: true }), emit = message => process.stderr.write(message) } = {}) {
+ try { remove(); }
+ catch (error) {
+ if (error.code === 'ENOTEMPTY') emit(`${cleanupFailureReport(error, error.path ?? directory)}\n`);
+ throw error;
+ }
+}
diff --git a/test/test-runner.test.js b/test/test-runner.test.js
index 028252c7..054f9dd5 100644
--- a/test/test-runner.test.js
+++ b/test/test-runner.test.js
@@ -10,9 +10,13 @@ import { test } from 'node:test';
test('tests run without inherited Git identity or config and refuse ambient pullboard [C7, S13]', (t) => {
assert.equal(process.env.GIT_CONFIG_GLOBAL, '/dev/null');
assert.equal(process.env.GIT_CONFIG_NOSYSTEM, '1');
- assert.equal(process.env.GIT_CONFIG_COUNT, '1');
+ assert.equal(process.env.GIT_CONFIG_COUNT, '3');
assert.equal(process.env.GIT_CONFIG_KEY_0, 'user.useConfigOnly');
assert.equal(process.env.GIT_CONFIG_VALUE_0, 'true');
+ assert.equal(process.env.GIT_CONFIG_KEY_1, 'gc.auto');
+ assert.equal(process.env.GIT_CONFIG_VALUE_1, '0');
+ assert.equal(process.env.GIT_CONFIG_KEY_2, 'maintenance.auto');
+ assert.equal(process.env.GIT_CONFIG_VALUE_2, 'false');
assert.equal(process.env.GIT_AUTHOR_NAME, undefined);
assert.equal(process.env.GIT_AUTHOR_EMAIL, undefined);
assert.equal(process.env.GIT_COMMITTER_NAME, undefined);
@@ -29,6 +33,12 @@ test('tests run without inherited Git identity or config and refuse ambient pull
const identity = spawnSync('git', ['var', 'GIT_AUTHOR_IDENT'], { cwd: root, encoding: 'utf8' });
assert.notEqual(identity.status, 0, 'Git refuses to infer an author identity from the machine');
assert.match(identity.stderr, /author identity unknown/i);
+ const autoGc = spawnSync('git', ['config', '--get', 'gc.auto'], { cwd: root, encoding: 'utf8' });
+ const autoMaintenance = spawnSync('git', ['config', '--get', 'maintenance.auto'], { cwd: root, encoding: 'utf8' });
+ assert.equal(autoGc.status, 0, autoGc.stderr);
+ assert.equal(autoGc.stdout.trim(), '0');
+ assert.equal(autoMaintenance.status, 0, autoMaintenance.stderr);
+ assert.equal(autoMaintenance.stdout.trim(), 'false');
const refused = spawnSync('pullboard', ['init'], { cwd: root, encoding: 'utf8' });
assert.equal(refused.status, 1);