Skip to content

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

fix(view): keep lsof probes nonblocking [N26,C7]

Corey Olson7c74b0937712
diff --git a/src/cli.js b/src/cli.js
index 5799fdb9..30bfa8e9 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -329,7 +329,7 @@ import {
} from './serve.js';
import {
forgetView,
- portHolder,
+ busyViewPortRefusal,
rememberView,
runningView,
} from './view-session.js';
@@ -1978,10 +1978,7 @@ async function viewHere(io, values) {
// The background child is handed --port explicitly, so the default is matched by number.
let hosted = false;
try { hosted = port !== 0 && port === defaultViewPort(); } catch { /* A malformed override names no default port. */ }
- const holder = hosted ? portHolder(port) : null;
- const stop = holder && (process.platform === 'win32' ? `taskkill /PID ${holder.pid} /T` : `kill ${holder.pid}`);
- error = new Refused('PORT_BUSY', !hosted ? `port ${port} is in use: name another with --port N, or use --port 0 to take a free one`
- : `port ${port} is in use${holder ? ` by ${holder.name} (pid ${holder.pid})` : ''}, and pullboard.dev looks for your view on that port: stop ${holder ? `it with ${stop}` : 'the other view there'}, then run pullboard view again`);
+ error = busyViewPortRefusal(port, hosted);
}
if (process.env.PULLBOARD_VIEW_BACKGROUND_CHILD === '1' && process.send) {
process.send({ type: 'startup-error', code: error.code ?? 'VIEW_START', message: error.message });
diff --git a/src/resources.js b/src/resources.js
index 8c02b713..75f54ac2 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -505,12 +505,16 @@ async function readBiggestProcesses(platform, run, readLink, count = 3) {
return match ? { pid: Number(match[1]), bytes: Number(match[2]) * 1024, name: basename(match[3].trim()) } : null;
}).filter(Boolean).sort((left, right) => right.bytes - left.bytes).slice(0, count);
return Promise.all(listed.map(async (entry) => {
- let cwd = '';
+ let cwd = '', cwdFailure = '';
try {
if (platform === 'linux') cwd = await readLink(`/proc/${entry.pid}/cwd`);
- else cwd = /^n(.*)$/mu.exec(await run('/usr/sbin/lsof', ['-a', '-d', 'cwd', '-p', String(entry.pid), '-Fn']))?.[1] ?? '';
- } catch { /* Another user's process hides its directory; the pid and size still name it. */ }
- return { ...entry, cwd };
+ else cwd = /^n(.*)$/mu.exec(await run('/usr/sbin/lsof', ['-b', '-a', '-d', 'cwd', '-p', String(entry.pid), '-Fn']))?.[1] ?? '';
+ } catch (error) {
+ const code = typeof error.code === 'string' && /^[A-Z0-9_]+$/u.test(error.code) ? error.code : 'unavailable';
+ cwdFailure = `an unreadable directory for pid ${entry.pid} (${platform === 'linux' ? 'readlink' : 'lsof'} ${code})`;
+ }
+ if (!cwd && !cwdFailure) cwdFailure = `an unreadable directory for pid ${entry.pid} (no directory reported)`;
+ return { ...entry, cwd, ...(cwdFailure ? { cwdFailure } : {}) };
}));
}
@@ -562,7 +566,7 @@ export function memoryVerdict(reading, floorBytes) {
const why = [critical ? 'pressure is critical' : '', low ? 'free memory is under the floor' : ''].filter(Boolean).join(' and ');
const pressure = reading.pressure === 'unknown' ? 'pressure not reported' : `pressure ${reading.pressure}`;
const state = `${pressure}, ${memorySize(reading.availableBytes)} free of ${memorySize(reading.totalBytes)}${off ? '' : ` (floor ${memorySize(floorBytes)})`}`;
- const biggest = (reading.processes ?? []).map(({ pid, name, bytes, cwd }) => `pid ${pid} ${name} ${memorySize(bytes)} in ${cwd || 'an unreadable directory'}`).join('; ');
+ const biggest = (reading.processes ?? []).map(({ pid, name, bytes, cwd, cwdFailure }) => `pid ${pid} ${name} ${memorySize(bytes)} in ${cwd || cwdFailure || 'an unreadable directory'}`).join('; ');
const verdict = off ? 'hold off (set gate.memoryFloorMB to turn it on)' : held ? `holding the gate queue because ${why}` : 'admitting';
return { checked: true, held, line: `memory: ${verdict}: ${state}${biggest ? `; biggest: ${biggest}` : ''}` };
}
diff --git a/src/view-session.js b/src/view-session.js
index 28b64ee7..b5c34398 100644
--- a/src/view-session.js
+++ b/src/view-session.js
@@ -1,5 +1,6 @@
/** Private runtime records that let an unattended CLI hand off its live view link. */
import { spawnSync } from 'node:child_process';
+import { Refused } from './refused.js';
import {
chmodSync,
existsSync,
@@ -123,14 +124,30 @@ function listenerProgram(pid, listedName) {
* @returns {{ pid: number, name: string } | null}
*/
export function portHolder(port) {
+ return readPortHolder(port).holder;
+}
+
+/** Inspect only a listener's public identity; nonblocking filesystem probes keep dead mounts out of port diagnosis. */
+function readPortHolder(port) {
+ /** Keep the failed target and OS code, never process arguments or arbitrary tool output. */
+ const unavailable = reason => ({ holder: null, issue: `could not read the listener on port ${port} (lsof ${reason})` });
const lsof = ['/usr/sbin/lsof', '/usr/bin/lsof'].find((file) => existsSync(file));
- if (!lsof) return null;
- const listed = spawnSync(lsof, ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fpc'], { encoding: 'utf8', timeout: 2_000 });
+ if (!lsof) return unavailable('not installed');
+ const listed = spawnSync(lsof, ['-b', '-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-Fpc'], { encoding: 'utf8', timeout: 2_000 });
+ if (listed.error || listed.status !== 0) return unavailable(listed.error?.code ?? `exit ${listed.status}`);
const pids = [...String(listed.stdout ?? '').matchAll(/^p(\d+)$/gmu)].map((match) => Number(match[1]));
- // One listener is an answer; none or several (an unusual shared socket) names no single process.
- if (listed.status !== 0 || pids.length !== 1 || !Number.isInteger(pids[0]) || pids[0] < 1) return null;
+ if (pids.length !== 1 || !Number.isInteger(pids[0]) || pids[0] < 1) return unavailable('no single listener reported');
const pid = pids[0];
- if (readSession(port)?.pid === pid) return { pid, name: 'pullboard view' };
+ if (readSession(port)?.pid === pid) return { holder: { pid, name: 'pullboard view' }, issue: '' };
const listedName = /^c(.+)$/mu.exec(listed.stdout)?.[1]?.trim() || 'a program';
- return { pid, name: listenerProgram(pid, listedName) };
+ return { holder: { pid, name: listenerProgram(pid, listedName) }, issue: '' };
+}
+
+/** Keep the original busy-port recovery while naming a failed listener lookup instead of inventing a process to stop. */
+export function busyViewPortRefusal(port, hosted) {
+ if (!hosted) return new Refused('PORT_BUSY', `port ${port} is in use: name another with --port N, or use --port 0 to take a free one`);
+ const { holder, issue } = readPortHolder(port);
+ const stop = holder && (process.platform === 'win32' ? `taskkill /PID ${holder.pid} /T` : `kill ${holder.pid}`);
+ const identity = holder ? ` by ${holder.name} (pid ${holder.pid})` : issue ? ` (${issue})` : '';
+ return new Refused('PORT_BUSY', `port ${port} is in use${identity}, and pullboard.dev looks for your view on that port: stop ${holder ? `it with ${stop}` : 'the other view there'}, then run pullboard view again`);
}
diff --git a/test/cleanup-diagnostics.js b/test/cleanup-diagnostics.js
index 27c32318..2aa2f6f1 100644
--- a/test/cleanup-diagnostics.js
+++ b/test/cleanup-diagnostics.js
@@ -1,7 +1,7 @@
/** Capture bounded filesystem and live-holder evidence for a fixture cleanup failure. */
import { readdirSync, rmSync, statSync } from 'node:fs';
import { runFixtureChild as spawnSync } from './fixture-child.js';
-import { join } from 'node:path';
+import { join, resolve, sep } from 'node:path';
const FILE_OWNER_TIMEOUT_MS = 8_000;
@@ -28,8 +28,14 @@ function newestEntries(directory) {
/** 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: FILE_OWNER_TIMEOUT_MS,
+ // +D needs readlink/stat, which -b deliberately avoids; filter kernel-reported names instead.
+ const root = resolve(directory);
+ const roots = [root];
+ if (process.platform === 'darwin' && /^\/(?:private\/)?(?:tmp|var|etc)(?:\/|$)/u.test(root)) {
+ roots.push(root.startsWith('/private/') ? root.slice('/private'.length) : '/private' + root);
+ }
+ const result = spawnSync('lsof', ['-b', '-nP', '-Fpcn'], {
+ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: FILE_OWNER_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024,
});
if (result.error?.code === 'ETIMEDOUT') return `unavailable (ETIMEDOUT after ${FILE_OWNER_TIMEOUT_MS} ms)`;
if (result.error) return `unavailable (${result.error.code ?? result.error.message})`;
@@ -42,7 +48,7 @@ function fileOwners(directory) {
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);
+ else if (line.startsWith('n') && current.pid && roots.some(root => value === root || value.startsWith(root + sep))) current.paths.push(value);
}
return owners.filter(owner => owner.paths.length)
.slice(0, 12)
diff --git a/test/lsof-lookups.test.js b/test/lsof-lookups.test.js
new file mode 100644
index 00000000..96a708b4
--- /dev/null
+++ b/test/lsof-lookups.test.js
@@ -0,0 +1,72 @@
+/** Nonblocking process diagnostics preserve their target and safe failure information [C7,N26]. */
+import assert from 'node:assert/strict';
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { test } from 'node:test';
+import { readMachineMemory, memoryVerdict } from '../src/resources.js';
+import { cleanupFailureReport } from './cleanup-diagnostics.js';
+
+/** Inject only the documented OS-tool boundary; all production parsing and failure rendering still run. */
+async function memoryProbe(fail = false) {
+ const calls = [];
+ const reading = await readMachineMemory({ platform: 'darwin', processes: true,
+ /** Return deterministic memory/process readings and capture the real cwd-probe argv. */
+ async run(command, args) {
+ if (command.endsWith('/sysctl')) return '1 20 17179869184';
+ if (command.endsWith('/ps')) return '43210 4096 fixture-node';
+ assert.equal(command, '/usr/sbin/lsof'); calls.push(args);
+ if (fail) throw Object.assign(new Error('private cwd lookup timed out'), { code: 'ETIMEDOUT' });
+ return 'n/private/fixture-cwd';
+ },
+ });
+ return { reading, calls };
+}
+
+test('memory process directories use nonblocking lsof without losing successful cwd data [C7]', async () => {
+ const { reading, calls } = await memoryProbe();
+ assert.equal(reading.checked, true);
+ assert.ok(calls.length > 0 && calls.every(args => args.includes('-b')));
+ assert.equal(reading.processes[0].cwd, '/private/fixture-cwd');
+});
+
+test('a failed process-directory lookup names its pid and failure while memory admission remains available [C7]', async () => {
+ const { reading } = await memoryProbe(true);
+ assert.equal(reading.checked, true);
+ const result = memoryVerdict(reading, reading.totalBytes);
+ assert.equal(result.held, true);
+ assert.match(result.line, /43210/u);
+ assert.match(result.line, /directory.*lsof.*ETIMEDOUT/iu);
+});
+
+/** Quote only a private fixture path as one literal shell word. */
+function shellWord(value) { return "'" + value.replaceAll("'", "'\\''") + "'"; }
+
+test('cleanup ownership probes request nonblocking lsof and retain scoped holder evidence [C7]', t => {
+ const root = mkdtempSync(join(tmpdir(), 'pullboard-lsof-flags-'));
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ const output = join(root, 'args.txt'), path = join(root, 'lsof');
+ const script = '#!/bin/sh\n' + 'printf "%s\\n" "$@" > ' + shellWord(output)
+ + '\nprintf "%s\\n" ' + shellWord('p99999\ncUNRELATED_PRIVATE_PROCESS\nn/private/unrelated/PRIVATE_OTHER_PATH\np43210\ncfixture-node\nn' + root + '/held.txt\nn/private/unrelated/PRIVATE_OTHER_PATH') + '\n';
+ writeFileSync(path, script);
+ chmodSync(path, 0o700);
+ const old = process.env.PATH; process.env.PATH = root;
+ let report;
+ try { report = cleanupFailureReport(Object.assign(new Error('private cleanup failed'), { code: 'ENOTEMPTY', path: root }), root); }
+ finally { process.env.PATH = old; }
+ assert.ok(readFileSync(output, 'utf8').split('\n').includes('-b'));
+ assert.match(report, /pid=43210 command=fixture-node/u);
+ assert.ok(report.includes(root + '/held.txt'));
+ assert.doesNotMatch(report, /PRIVATE_OTHER_PATH|UNRELATED_PRIVATE_PROCESS/u, 'unrelated descriptor names and processes never enter fixture diagnostics');
+});
+
+test('literal process-directory and cleanup helper probes all retain the nonblocking flag [C7]', () => {
+ const paths = ['../src/resources.js', './cleanup-diagnostics.js', './view-port.test.js'];
+ let calls = 0;
+ for (const path of paths) {
+ const source = readFileSync(new URL(path, import.meta.url), 'utf8');
+ const probes = source.matchAll(/(?:spawnSync|run|runFixtureProcessTool)\(\s*(['"])(?:\/usr\/(?:sbin|bin)\/)?lsof\1\s*,\s*\[([^\]]*)\]/gu);
+ for (const probe of probes) { calls++; assert.match(probe[2], /['"]-b['"]/u, path + ' uses nonblocking lsof'); }
+ }
+ assert.ok(calls >= 4, 'the census covers memory, cleanup and both fixture identity probes');
+});
diff --git a/test/view-port.test.js b/test/view-port.test.js
index 1784124b..71381ae6 100644
--- a/test/view-port.test.js
+++ b/test/view-port.test.js
@@ -393,8 +393,8 @@ function readFixtureViewIdentity(pid) {
cwd = readlinkSync(`/proc/${pid}/cwd`);
executable = readlinkSync(`/proc/${pid}/exe`);
} else if (process.platform === 'darwin') {
- const cwdOutput = runFixtureProcessTool('/usr/sbin/lsof', ['-a', '-d', 'cwd', '-p', String(pid), '-Fn']);
- const executableOutput = runFixtureProcessTool('/usr/sbin/lsof', ['-a', '-d', 'txt', '-p', String(pid), '-Fn']);
+ const cwdOutput = runFixtureProcessTool('/usr/sbin/lsof', ['-b', '-a', '-d', 'cwd', '-p', String(pid), '-Fn']);
+ const executableOutput = runFixtureProcessTool('/usr/sbin/lsof', ['-b', '-a', '-d', 'txt', '-p', String(pid), '-Fn']);
cwd = /^n(.*)$/mu.exec(cwdOutput)?.[1];
const expectedExecutable = realpathSync(process.execPath);
executable = executableOutput.split(/\r?\n/u).filter((line) => line.startsWith('n'))
@@ -695,3 +695,38 @@ test('a broken pipe during view shutdown is observed until the listener really c
assert.ok(probes >= 3, 'success requires a later real connection refusal');
assert.equal(listener.listening, false);
});
+
+
+test('listener lookups use nonblocking lsof and name an unreadable port [N26,C7]', () => {
+ const script = String.raw`
+import fs from 'node:fs';
+import childProcess from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+const original = { exists: fs.existsSync, spawn: childProcess.spawnSync };
+const calls = [];
+fs.existsSync = path => ['/usr/sbin/lsof', '/usr/bin/lsof'].includes(path) || original.exists(path);
+childProcess.spawnSync = (command, args) => {
+ if (!command.endsWith('/lsof')) throw new Error('unexpected private probe');
+ calls.push(args);
+ return { status: null, stdout: '', error: { code: 'ETIMEDOUT' } };
+};
+syncBuiltinESMExports();
+try {
+ const module = await import(process.argv[1]);
+ module.portHolder(31337);
+ const refusal = module.busyViewPortRefusal?.(31337, true);
+ console.log(JSON.stringify({ calls, message: refusal?.message ?? '' }));
+} finally {
+ fs.existsSync = original.exists; childProcess.spawnSync = original.spawn;
+ syncBuiltinESMExports();
+}
+`;
+ const result = runFixtureChild(process.execPath, ['--input-type=module', '-e', script,
+ new URL('../src/view-session.js', import.meta.url).href], { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ const document = JSON.parse(result.stdout);
+ assert.ok(document.calls.length > 0);
+ assert.ok(document.calls.every(args => args.includes('-b')), 'a dead mount cannot make a listener lookup use blocking filesystem probes');
+ assert.match(document.message, /port 31337/u);
+ assert.match(document.message, /could not read.*listener.*ETIMEDOUT/iu);
+});