Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(pane): keep the MCP server alive when ps cannot run in a sandbox

Jack Rudenko72f3c624fdea
diff --git a/packages/cli/src/pane/pane-registry.test.ts b/packages/cli/src/pane/pane-registry.test.ts
index d35d0960..59295db6 100644
--- a/packages/cli/src/pane/pane-registry.test.ts
+++ b/packages/cli/src/pane/pane-registry.test.ts
@@ -16,10 +16,12 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
+import { createServer } from "node:net";
import { join } from "node:path";
import { waitForExit } from "../process-tree.js";
import {
MIN_MAGMUX_VERSION,
+ OWNER_START36,
assertMagmuxAvailable,
ensureSockRoot,
spawnPaneWatcher,
@@ -30,6 +32,7 @@ import {
type PaneRecord,
type RegisteredPane,
livePaneCount,
+ ownerAlive,
ownerStartOfSelf,
readRecord,
readRecords,
@@ -48,7 +51,6 @@ import {
isPaneRecordPath,
isPaneSockPath,
isPaneWatcherCommand,
- readProcessTable,
recordPathOf,
sockPathOf,
} from "./process-identity.js";
@@ -59,7 +61,9 @@ import {
killLeftovers,
makePaneTestEnv,
orphanReport,
+ requireProcessTable,
waitNoOrphans,
+ withProcessTableUnavailable,
} from "./test-helpers/hermetic-env.js";
const OWNER = join(import.meta.dir, "test-helpers", "pane-owner.ts");
@@ -202,11 +206,32 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_
expect(alive(rec.watcherPid as number)).toBe(true);
s.cancel();
await s.reaped();
- expect(readProcessTable().some((r) => isPaneWatcherCommand(r.command, s.paneId))).toBe(false);
+ expect(requireProcessTable().some((r) => isPaneWatcherCommand(r.command, s.paneId))).toBe(
+ false
+ );
expect(existsSync(s.sockPath)).toBe(false);
expect(readRecord(t.sockRoot, s.paneId)).toBeNull();
}, 30_000);
+ test("with the process table unavailable a pane starts, records its pid and reaps by its handle", async () => {
+ const t = env();
+ const { s, uuid } = await withProcessTableUnavailable(async () => {
+ const started = await hangSession(t);
+ // onSnapshot → setPanePid → readProcessTableAsync, which rejected unhandled
+ for (let i = 0; i < 100 && !readRecord(t.sockRoot, started.s.paneId)?.panePid; i++)
+ await Bun.sleep(50);
+ await Bun.sleep(200);
+ expect(readRecord(t.sockRoot, started.s.paneId)?.panePid).toBeGreaterThan(0);
+ started.s.cancel();
+ await started.s.reaped();
+ return started;
+ });
+ expect(s.snapshot().state).toBe("CANCELLED");
+ expect(readRecord(t.sockRoot, s.paneId)).toBeNull();
+ const left = await waitNoOrphans({ sockRoot: t.sockRoot, ids: [uuid] });
+ expect(left).toEqual({ processes: [], files: [] });
+ }, 30_000);
+
test("GATE: owner SIGKILL with two panes → both watchers remove group, magmux, socket, dirs, record (≤ 5 s); no watcher pipe leaked", async () => {
const t = env();
const { proc, info } = await startOwner(t, 2);
@@ -470,7 +495,7 @@ describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_
await s.reaped();
expect(livePaneCount(t.sockRoot)).toBe(0);
expect(
- readProcessTable().some(
+ requireProcessTable().some(
(r) => r.command.includes("claudish-pane-watcher") && r.command.includes(t.sockRoot)
)
).toBe(false);
@@ -566,7 +591,7 @@ describe("escaped background shells (code-review iteration 2, M2)", () => {
panePid: () => wrapperPid,
group: null,
} as unknown as RegisteredPane;
- refreshGroupOf(pane, readProcessTable());
+ refreshGroupOf(pane, requireProcessTable());
expect(pane.group?.escaped?.map((m) => m.pid)).toEqual([bgPid]);
wrapper.stdin?.write("die\n"); // claude dies without its own cleanup
@@ -574,7 +599,7 @@ describe("escaped background shells (code-review iteration 2, M2)", () => {
expect(psField(bgPid, "ppid")).toBe(1);
// a refresh in the window between claude's death and the wrapper's exit, while the
// wrapper still carries the identity (so the fresh snapshot is a verified one)
- const table = readProcessTable();
+ const table = requireProcessTable();
expect(table.find((r) => r.pid === wrapperPid)?.command).toContain(`--session-id ${uuid}`);
refreshGroupOf(pane, table);
expect(pane.group?.members.some((m) => m.pid === wrapperPid)).toBe(true);
@@ -708,3 +733,73 @@ describe("reservations", () => {
expect(reservedPaneCount()).toBe(before);
});
});
+
+describe("with the process table unavailable (a sandbox refuses ps): every pane is assumed alive", () => {
+ /** A pane of THIS live process, as another owner's sweep or count would find it. */
+ function liveOwnerPane(t: PaneTestEnv, label: string): PaneRecord {
+ const root = ensureSockRoot(t.sockRoot);
+ const paneId = `c${process.pid}-${OWNER_START36}-t${label}-abcdef`;
+ const ctl = join(root, `launch-${label}Ctl1`);
+ const turn = join(root, `launch-${label}Trn1`);
+ mkdirSync(ctl, { mode: 0o700 });
+ mkdirSync(turn, { mode: 0o700 });
+ const rec: PaneRecord = {
+ paneId,
+ ownerPid: process.pid,
+ ownerStart: ownerStartOfSelf(), // read while the table is still readable
+ watcherPid: null,
+ magmuxPid: null,
+ panePid: null,
+ sessionUuid: crypto.randomUUID(),
+ sockPath: join(root, `magmux-${paneId}.sock`),
+ launcherDir: ctl,
+ turnDir: turn,
+ createdAt: new Date().toISOString(),
+ };
+ writeFileSync(rec.sockPath, "");
+ writeRecord(root, rec);
+ return rec;
+ }
+
+ test("the sweep keeps a live owner's record, socket and dirs", async () => {
+ const t = env();
+ const rec = liveOwnerPane(t, "sw");
+ const r = await withProcessTableUnavailable(() => sweepOrphanPanes(t.sockRoot));
+ expect(r.kept).toContain(rec.paneId);
+ expect(r.cleaned).toEqual([]);
+ expect(readRecord(t.sockRoot, rec.paneId)).not.toBeNull();
+ for (const p of [rec.sockPath, rec.launcherDir, rec.turnDir]) expect(existsSync(p)).toBe(true);
+ });
+
+ test("the sweep leaves a recordless live socket alone", async () => {
+ const t = env();
+ const root = ensureSockRoot(t.sockRoot);
+ const sock = join(root, `magmux-c${process.pid}-${OWNER_START36}-tls-abcdef.sock`);
+ const server = createServer((c) => c.end());
+ await new Promise<void>((resolve) => server.listen(sock, resolve));
+ try {
+ const r = await withProcessTableUnavailable(() => sweepOrphanPanes(root));
+ expect(r.cleaned).toEqual([]);
+ expect(existsSync(sock)).toBe(true);
+ } finally {
+ server.close();
+ }
+ }, 20_000);
+
+ test("the pane limit counts a live owner's record", async () => {
+ const t = env();
+ liveOwnerPane(t, "lc");
+ expect(livePaneCount(t.sockRoot)).toBe(1);
+ expect(await withProcessTableUnavailable(() => livePaneCount(t.sockRoot))).toBe(1);
+ });
+
+ test("a record written with no ownerStart (its owner could not read ps) counts its live owner", () => {
+ const table = requireProcessTable();
+ expect(ownerAlive({ ownerPid: process.pid, ownerStart: "" }, table)).toBe(true);
+ expect(ownerAlive({ ownerPid: deadPid(), ownerStart: "" }, table)).toBe(false);
+ // a recorded start time still tells a reused pid apart
+ expect(
+ ownerAlive({ ownerPid: process.pid, ownerStart: "Thu Jan 1 00:00:00 1970" }, table)
+ ).toBe(false);
+ });
+});
diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.ts
index f6d796bf..385af09a 100644
--- a/packages/cli/src/pane/pane-registry.ts
+++ b/packages/cli/src/pane/pane-registry.ts
@@ -45,7 +45,6 @@ import {
liveEscaped,
mergeSnapshots,
parseGroupFile,
- processTableTrusted,
readProcessTable,
readProcessTableAsync,
recordPathOf,
@@ -85,17 +84,21 @@ let ownStart: string | null = null;
/** This process's `lstart` (one `ps` call, cached only when it found this process). */
export function ownerStartOfSelf(): string {
if (ownStart) return ownStart;
- const row = readProcessTable().find((r) => r.pid === process.pid);
+ const row = readProcessTable()?.find((r) => r.pid === process.pid);
if (row) ownStart = row.lstart;
return row?.lstart ?? "";
}
+/**
+ * The record's owner is alive: same pid, same start time. A record written while its owner
+ * could not read the table has no `ownerStart`, so its live pid alone counts as the owner.
+ */
export function ownerAlive(
rec: Pick<PaneRecord, "ownerPid" | "ownerStart">,
table: PsRow[]
): boolean {
const row = table.find((r) => r.pid === rec.ownerPid);
- return !!row && row.lstart === rec.ownerStart;
+ return !!row && (!rec.ownerStart || row.lstart === rec.ownerStart);
}
/* ───────────────────────────── records ───────────────────────────── */
@@ -270,7 +273,8 @@ async function tick(): Promise<void> {
if (ticking || live.size === 0) return;
ticking = true;
try {
- refreshGroups(await readProcessTableAsync());
+ const table = await readProcessTableAsync();
+ if (table) refreshGroups(table);
for (const p of live.values()) if (p.reapFailed) await p.retryReap();
} finally {
ticking = false;
@@ -279,10 +283,15 @@ async function tick(): Promise<void> {
/* ───────────────────────────── the pane limit ───────────────────────────── */
-/** Records with a live owner whose reap has not finished, across every owner, plus our reservations. */
+/**
+ * Records with a live owner whose reap has not finished, across every owner, plus our
+ * reservations. With the table unavailable every such record's owner counts as alive.
+ */
export function livePaneCount(root: string = sockRootFor()): number {
const table = readProcessTable();
- const counted = readRecords(root).filter((r) => !r.reapFailed && ownerAlive(r, table)).length;
+ const counted = readRecords(root).filter(
+ (r) => !r.reapFailed && (!table || ownerAlive(r, table))
+ ).length;
return counted + reserved;
}
@@ -454,9 +463,10 @@ function sweepTargets(rec: PaneRecord, root: string, table: PsRow[]): SweepTarge
}
async function killVerified(rec: PaneRecord, root: string): Promise<SweepTargets> {
- const t = sweepTargets(rec, root, readProcessTable());
+ // an unavailable table verifies nothing, so nothing below is signalled
+ const t = sweepTargets(rec, root, readProcessTable() ?? []);
for (const sig of ["SIGTERM", "SIGKILL"] as const) {
- const table = readProcessTable();
+ const table = readProcessTable() ?? [];
if (t.group && groupCheck(table, t.group)) signal(-t.group.pgid, sig);
for (const pid of liveEscaped(table, t.group)) signal(pid, sig);
if (t.mag && isPaneMagmux(t.mag, rec.paneId, table)) signal(t.mag, sig);
@@ -467,8 +477,8 @@ async function killVerified(rec: PaneRecord, root: string): Promise<SweepTargets
async function sweepRecord(rec: PaneRecord, root: string, out: SweepResult): Promise<void> {
const table = readProcessTable();
- if (!processTableTrusted(table)) {
- out.kept.push(rec.paneId); // ps failed: absence is unknown, never dead
+ if (!table) {
+ out.kept.push(rec.paneId); // nothing can be verified: the owner may be alive
return;
}
if (ownerAlive(rec, table)) return;
@@ -481,11 +491,8 @@ async function sweepRecord(rec: PaneRecord, root: string, out: SweepResult): Pro
const anyVerified = (t0.group && groupCheck(table, t0.group)) || t0.mag !== null;
if (anyVerified) await killVerified(rec, root);
const after = readProcessTable();
- if (!processTableTrusted(after)) {
- out.kept.push(rec.paneId);
- return;
- }
const stillAlive =
+ !after ||
(t0.group && groupCheck(after, t0.group)) ||
liveEscaped(after, t0.group).length > 0 ||
(t0.mag !== null && isPaneMagmux(t0.mag, rec.paneId, after));
@@ -518,8 +525,8 @@ function ownerOfIdAlive(id: string, table: PsRow[]): boolean {
async function sweepRecordlessSocket(root: string, name: string, out: SweepResult): Promise<void> {
const id = name.slice("magmux-".length, -".sock".length);
const table = readProcessTable();
- if (!processTableTrusted(table)) {
- out.kept.push(id); // ps failed: a live magmux socket must not be unlinked
+ if (!table) {
+ out.kept.push(id); // the owner may be alive and the socket a live magmux's
return;
}
if (ownerOfIdAlive(id, table)) return;
diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.ts
index 3c244227..cbc5605c 100644
--- a/packages/cli/src/pane/pane-session.ts
+++ b/packages/cli/src/pane/pane-session.ts
@@ -964,7 +964,9 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
this.panePidValue = pid;
updateRecord(this.root, this.paneId, { panePid: pid });
// never a synchronous ps on the event loop: a stalled loop gets our socket dropped as a slow consumer
- void readProcessTableAsync().then((t) => refreshGroupOf(this, t));
+ void readProcessTableAsync().then((t) => {
+ if (t) refreshGroupOf(this, t);
+ });
}
private onFrame(f: MagmuxFrame): void {
@@ -3394,6 +3396,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
/** Step 0: refresh the verified group while its members still carry their identity. */
private async captureGroupBeforeReap(): Promise<void> {
const table = await readProcessTableAsync();
+ if (!table) return;
if (!this.panePidValue && this.magmux?.pid) {
const lead = table.find((r) => r.ppid === this.magmux?.pid && r.pgid === r.pid);
if (lead) {
@@ -3404,10 +3407,14 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
refreshGroupOf(this, table);
}
- /** The verified group, or a recorded escaped descendant (own process group), is alive. */
+ /**
+ * The verified group, or a recorded escaped descendant (own process group), is alive.
+ * True while the table is unavailable: the reap stays unverified and keeps its files.
+ */
private async groupAlive(): Promise<boolean> {
if (!this.group) return false;
const table = await readProcessTableAsync();
+ if (!table) return true;
return groupCheck(table, this.group) || liveEscaped(table, this.group).length > 0;
}
@@ -3415,6 +3422,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
private async backstopTargets(): Promise<number[]> {
if (!this.group) return [];
const table = await readProcessTableAsync();
+ if (!table) return [];
return [
...(groupCheck(table, this.group) ? [-this.group.pgid] : []),
...liveEscaped(table, this.group),
diff --git a/packages/cli/src/pane/process-identity-spawn-failure.test.ts b/packages/cli/src/pane/process-identity-spawn-failure.test.ts
deleted file mode 100644
index 0bd214ae..00000000
--- a/packages/cli/src/pane/process-identity-spawn-failure.test.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-/**
- * readProcessTableAsync must never reject: every caller (`void ….then(…)` in setPanePid, the
- * registry tick, the reap) assumes "[] on failure", the contract its sync twin already honours.
- *
- * Node's spawn contract (Bun copies it) reports only ENOENT/EACCES/EAGAIN/EMFILE/ENFILE through
- * the execFile callback and THROWS every other errno synchronously. A macOS sandbox refuses to
- * exec the setuid /bin/ps with EPERM, so the throw escapes the Promise executor, the promise
- * rejects, and the unhandled rejection exits the MCP server with code 1.
- *
- * Kept apart from process-identity.test.ts because it mocks node:child_process, and Bun's
- * mock.module is process-global: the mock below passes every call through to the real execFile
- * unless a test arms it, and the real module is restored in afterAll.
- */
-
-import { afterAll, afterEach, describe, expect, mock, test } from "bun:test";
-import { spawnSync } from "node:child_process";
-import * as __realChildProcess from "node:child_process";
-import { existsSync } from "node:fs";
-import { join } from "node:path";
-
-const __realChildProcessExports = { ...__realChildProcess };
-
-/** When set, the mocked execFile throws this synchronously, as spawn does for EPERM. */
-let syncSpawnError: NodeJS.ErrnoException | null = null;
-
-mock.module("node:child_process", () => ({
- ...__realChildProcessExports,
- execFile: (...args: unknown[]) => {
- if (syncSpawnError) throw syncSpawnError;
- return (__realChildProcessExports.execFile as (...a: unknown[]) => unknown)(...args);
- },
-}));
-
-afterEach(() => {
- syncSpawnError = null;
-});
-
-afterAll(() => {
- mock.module("node:child_process", () => __realChildProcessExports);
-});
-
-import { readProcessTableAsync } from "./process-identity.js";
-
-function epermSpawnError(): NodeJS.ErrnoException {
- const err = new Error(
- "EPERM: operation not permitted, posix_spawn 'ps'"
- ) as NodeJS.ErrnoException;
- err.code = "EPERM";
- err.errno = -1;
- err.syscall = "spawn";
- err.path = "ps";
- return err;
-}
-
-describe("readProcessTableAsync — spawn failure", () => {
- // REGRESSION: readProcessTableAsync rejects when execFile throws synchronously (EPERM from a macOS sandbox refusing setuid /bin/ps) — Fixed in /dev:fix session dev-fix-20261020-182839-b87ae677
- test("resolves to [] instead of rejecting when execFile throws EPERM synchronously", async () => {
- syncSpawnError = epermSpawnError();
-
- const rows = await readProcessTableAsync();
-
- expect(rows).toEqual([]);
- });
-
- test("reads the real table when spawn succeeds (control: the mock passes through)", async () => {
- const rows = await readProcessTableAsync();
-
- expect(rows.some((r) => r.pid === process.pid)).toBe(true);
- });
-});
-
-const SANDBOX_EXEC = "/usr/bin/sandbox-exec";
-const IS_DARWIN = process.platform === "darwin";
-const HAVE_SANDBOX = IS_DARWIN && existsSync(SANDBOX_EXEC);
-if (!HAVE_SANDBOX) {
- console.warn(
- `SKIP readProcessTableAsync sandbox test: needs macOS with ${SANDBOX_EXEC} (platform=${process.platform}). ` +
- "CI's macOS runner must satisfy this, or the real EPERM path is untested."
- );
-}
-
-describe.skipIf(!HAVE_SANDBOX)(
- "readProcessTableAsync — inside a macOS sandbox (darwin only)",
- () => {
- // REGRESSION: readProcessTableAsync rejects when execFile throws synchronously (EPERM from a macOS sandbox refusing setuid /bin/ps) — Fixed in /dev:fix session dev-fix-20261020-182839-b87ae677
- test("resolves to 0 rows and the process exits 0 when the sandbox refuses /bin/ps", () => {
- const modulePath = join(import.meta.dir, "process-identity.ts");
- // `void …then(…)` is the shape of the real call site (pane-session setPanePid): a rejection
- // here is unhandled and exits the process with code 1.
- const script =
- `import { readProcessTableAsync } from ${JSON.stringify(modulePath)};\n` +
- `void readProcessTableAsync().then((t) => { console.log("rows " + t.length); process.exit(0); });\n` +
- "setInterval(() => {}, 1000);\n" +
- `setTimeout(() => { console.log("timeout"); process.exit(3); }, 10000);\n`;
-
- const res = spawnSync(
- SANDBOX_EXEC,
- ["-p", "(version 1)(allow default)", process.execPath, "--no-env-file", "-e", script],
- { encoding: "utf8", timeout: 20_000 }
- );
-
- expect({
- status: res.status,
- stdout: res.stdout.trim(),
- stderr: res.stderr.includes("EPERM"),
- }).toEqual({
- status: 0,
- stdout: "rows 0",
- stderr: false,
- });
- });
- }
-);
diff --git a/packages/cli/src/pane/process-identity.test.ts b/packages/cli/src/pane/process-identity.test.ts
index 428bedd1..3d291515 100644
--- a/packages/cli/src/pane/process-identity.test.ts
+++ b/packages/cli/src/pane/process-identity.test.ts
@@ -1,6 +1,14 @@
import { afterAll, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
import { join } from "node:path";
import {
type GroupSnapshot,
@@ -18,10 +26,14 @@ import {
paneIdentityMatches,
parseGroupFile,
parsePsTable,
+ readProcessTable,
+ readProcessTableAsync,
sameSnapshot,
+ setPsSpawnForTest,
verifiedGroupSnapshot,
} from "./process-identity.js";
import { FIXTURES } from "./test-helpers/fixtures.js";
+import { SANDBOX_REFUSED_PS, withProcessTableUnavailable } from "./test-helpers/hermetic-env.js";
// A REAL `ps -ax -ww -o pid=,ppid=,pgid=,lstart=,command=` of one live pane (watcher, magmux,
// pane leader), captured by impl3/capture-ps.ts; home paths redacted to /opt/u.
@@ -324,3 +336,111 @@ describe("the generated watcher shell agrees with the TS predicates on the same
expect(isLaunchDirPath(root, good)).toBe(true);
});
});
+
+describe("the process table when ps cannot run (macOS refuses the setuid ps in any sandbox)", () => {
+ test("a real read lists the reader itself, synchronously and asynchronously", async () => {
+ expect(readProcessTable()?.some((r) => r.pid === process.pid)).toBe(true);
+ expect((await readProcessTableAsync())?.some((r) => r.pid === process.pid)).toBe(true);
+ });
+
+ test("readProcessTableAsync resolves null, never rejects, when execFile throws synchronously", async () => {
+ // Bun throws EPERM from execFile itself; an unguarded executor rejected, and the MCP
+ // server's unhandled rejection (setPanePid) exited it with status 1
+ await withProcessTableUnavailable(async () => {
+ await expect(readProcessTableAsync()).resolves.toBeNull();
+ expect(readProcessTable()).toBeNull();
+ });
+ });
+
+ test("a failure passed to the callback, and output with no row, read as unavailable too", async () => {
+ const prev = setPsSpawnForTest({
+ ...SANDBOX_REFUSED_PS,
+ execFile: (_f, _a, _o, cb) => cb(Object.assign(new Error("ps: exit 1"), { code: 1 }), ""),
+ });
+ try {
+ expect(await readProcessTableAsync()).toBeNull();
+ } finally {
+ setPsSpawnForTest(prev);
+ }
+ const real = setPsSpawnForTest({
+ execFileSync: () => "\n",
+ execFile: (_f, _a, _o, cb) => cb(null, ""),
+ });
+ try {
+ expect(readProcessTable()).toBeNull();
+ expect(await readProcessTableAsync()).toBeNull();
+ } finally {
+ setPsSpawnForTest(real);
+ }
+ });
+
+ test.skipIf(process.platform !== "darwin" || !existsSync("/usr/bin/sandbox-exec"))(
+ "inside a real macOS sandbox: both reads are unavailable and the process exits 0",
+ () => {
+ // `void …then(…)` is the shape of the real call site (pane-session setPanePid): a
+ // rejection there is unhandled and exits the process with code 1.
+ const modulePath = join(import.meta.dir, "process-identity.ts");
+ const script =
+ `import { readProcessTable, readProcessTableAsync } from ${JSON.stringify(modulePath)};\n` +
+ `const sync = readProcessTable();\n` +
+ `void readProcessTableAsync().then((t) => { console.log(String(sync) + " " + String(t)); process.exit(0); });\n` +
+ "setInterval(() => {}, 1000);\n" +
+ `setTimeout(() => { console.log("timeout"); process.exit(3); }, 10000);\n`;
+ const res = spawnSync(
+ "/usr/bin/sandbox-exec",
+ ["-p", "(version 1)(allow default)", process.execPath, "--no-env-file", "-e", script],
+ { encoding: "utf8", timeout: 20_000 }
+ );
+ expect({ status: res.status, stdout: res.stdout.trim() }).toEqual({
+ status: 0,
+ stdout: "null null",
+ });
+ },
+ 30_000
+ );
+});
+
+/** The whole watcher script, its owner already gone (stdin at EOF), against a stand-in `ps`. */
+function watcherAfterOwnerDeath(psBody: string): {
+ status: number | null;
+ left: Record<string, boolean>;
+} {
+ const root = mkdtempSync(join(scratch, "wroot-"));
+ const bin = join(root, "bin");
+ mkdirSync(bin);
+ writeFileSync(join(bin, "ps"), `#!/bin/sh\n${psBody}\n`, { mode: 0o755 });
+ const paneId = "c1-zz-twatch-abcdef";
+ const ctl = join(root, "launch-CtL123");
+ const turn = join(root, "launch-TuRn12");
+ const sock = join(root, `magmux-${paneId}.sock`);
+ const rec = join(root, "panes", `${paneId}.json`);
+ mkdirSync(ctl);
+ mkdirSync(turn);
+ mkdirSync(join(root, "panes"));
+ writeFileSync(sock, "");
+ writeFileSync(rec, "{}");
+ const r = spawnSync(
+ "/bin/sh",
+ ["-c", WATCHER_SCRIPT, "claudish-pane-watcher", paneId, "uuid", ctl, sock, rec, turn, root],
+ { encoding: "utf8", input: "", env: { PATH: `${bin}:/usr/bin:/bin` } }
+ );
+ const left = Object.fromEntries(
+ Object.entries({ ctl, turn, sock, rec }).map(([k, p]) => [k, existsSync(p)])
+ );
+ return { status: r.status, left };
+}
+
+describe("the watcher when its owner dies and ps cannot run", () => {
+ test("nothing verifiable: exit 1, the socket, record and dirs are kept for a later sweep", () => {
+ // what /bin/sh reports when the sandbox refuses the exec
+ const r = watcherAfterOwnerDeath('echo "ps: Operation not permitted" >&2; exit 126');
+ expect(r.status).toBe(1);
+ expect(r.left).toEqual({ ctl: true, turn: true, sock: true, rec: true });
+ });
+
+ test("control: a readable table with no pane process left → files removed, exit 0", () => {
+ const r = watcherAfterOwnerDeath(`echo " 1 1 ${leader.lstart} /sbin/launchd"`);
+ expect(r.status).toBe(0);
+ expect(r.left).toEqual({ ctl: false, turn: false, sock: false, rec: false });
+ });
+});
diff --git a/packages/cli/src/pane/process-identity.ts b/packages/cli/src/pane/process-identity.ts
index 72f3004a..8551138a 100644
--- a/packages/cli/src/pane/process-identity.ts
+++ b/packages/cli/src/pane/process-identity.ts
@@ -86,55 +86,99 @@ export function parsePsTable(text: string): PsRow[] {
return rows;
}
+/**
+ * The process table, or null when it is UNAVAILABLE: `ps` could not run, failed, or
+ * printed no row. A readable table is never empty (it lists the reader), so null never
+ * means "no process": every caller treats what it would have looked up as possibly
+ * alive — no reap, no sweep, no file removed, no owner counted dead.
+ *
+ * Measured: macOS refuses to exec the setuid `/bin/ps` from ANY Seatbelt sandbox, even
+ * `sandbox-exec -p '(version 1)(allow default)'` (EPERM, `posix_spawn 'ps'`), so inside
+ * one every read is null for the life of the process.
+ */
+export type ProcessTable = PsRow[] | null;
+
const PS_ENV = { PATH: "/bin:/usr/bin:/usr/sbin:/sbin", LC_ALL: "C" };
+const PS_OPTIONS = { env: PS_ENV, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 } as const;
+
+type PsOptions = typeof PS_OPTIONS;
+
+/** How `ps` is spawned: node's `execFile`/`execFileSync`, narrowed to the one call made. */
+export interface PsSpawn {
+ execFileSync(file: string, args: string[], opts: PsOptions & { stdio: StdioPipeOut }): string;
+ execFile(
+ file: string,
+ args: string[],
+ opts: PsOptions,
+ cb: (err: Error | null, stdout: string) => void
+ ): unknown;
+}
+
+type StdioPipeOut = ["ignore", "pipe", "ignore"];
+
+let psSpawn: PsSpawn = { execFile, execFileSync };
+
+/** @internal tests: replace how `ps` is spawned; returns the previous spawn, to restore. */
+export function setPsSpawnForTest(next: PsSpawn): PsSpawn {
+ const prev = psSpawn;
+ psSpawn = next;
+ return prev;
+}
-/** The whole process table, synchronously (exit hooks, the sweep). */
-export function readProcessTable(): PsRow[] {
+/**
+ * Whether rows a `ps` run printed are a real table: they list THIS process. A run that
+ * failed part way (EAGAIN/EMFILE, maxBuffer) or printed something else does not, and no
+ * liveness or destructive decision may be taken from it.
+ */
+export function processTableTrusted(rows: PsRow[]): boolean {
+ return rows.some((r) => r.pid === process.pid);
+}
+
+/**
+ * The table one `ps` run gives: its parsed stdout, or null when the run produced no output
+ * or no trusted table (`processTableTrusted`). Both readers end here, so they agree on
+ * what "unavailable" is.
+ */
+function tableOf(stdout: string | null): ProcessTable {
+ if (stdout === null) return null;
+ const rows = parsePsTable(stdout);
+ return processTableTrusted(rows) ? rows : null;
+}
+
+/** The whole process table, synchronously (exit hooks, the sweep); null when unavailable. */
+export function readProcessTable(): ProcessTable {
+ let stdout: string | null;
try {
- return parsePsTable(
- execFileSync("ps", PS_ARGS, {
- env: PS_ENV,
- encoding: "utf8",
- maxBuffer: 64 * 1024 * 1024,
- stdio: ["ignore", "pipe", "ignore"],
- })
- );
+ stdout = psSpawn.execFileSync("ps", PS_ARGS, {
+ ...PS_OPTIONS,
+ stdio: ["ignore", "pipe", "ignore"],
+ });
} catch {
- return [];
+ stdout = null;
}
+ return tableOf(stdout);
}
/**
- * A table that does not list THIS process was not read: ps failed (EPERM in a macOS
- * sandbox that refuses the setuid /bin/ps, EAGAIN/EMFILE, maxBuffer). Every read path maps
- * failure to [], so "absent from the table" means "unknown", never "dead". No liveness or
- * destructive decision may be taken from such a table.
+ * The whole process table without blocking the event loop (the registry tick); null when
+ * unavailable. Never rejects: Bun throws a spawn failure (EPERM in a sandbox) from
+ * `execFile` itself rather than passing it to the callback, so the call is guarded too.
*/
-export function processTableTrusted(table: PsRow[]): boolean {
- return table.some((r) => r.pid === process.pid);
-}
-
-/** The whole process table without blocking the event loop (the registry tick). */
-export function readProcessTableAsync(): Promise<PsRow[]> {
+export function readProcessTableAsync(): Promise<ProcessTable> {
return new Promise((resolve) => {
try {
- execFile(
- "ps",
- PS_ARGS,
- { env: PS_ENV, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
- (err, stdout) => resolve(err ? [] : parsePsTable(String(stdout)))
+ psSpawn.execFile("ps", PS_ARGS, PS_OPTIONS, (err, stdout) =>
+ resolve(tableOf(err ? null : String(stdout)))
);
} catch {
- // spawn throws synchronously for errnos other than ENOENT/EACCES/EAGAIN/EMFILE/ENFILE:
- // EPERM when a macOS sandbox refuses to exec the setuid /bin/ps. Keep the never-reject contract.
- resolve([]);
+ resolve(tableOf(null));
}
});
}
-/** `lstart` of one pid, or null when it is gone. */
+/** `lstart` of one pid; null when it is gone or the table is unavailable. */
export function lstartOf(pid: number, table?: PsRow[]): string | null {
- const rows = table ?? readProcessTable();
+ const rows = table ?? readProcessTable() ?? [];
return rows.find((r) => r.pid === pid)?.lstart ?? null;
}
@@ -159,16 +203,16 @@ export function isPaneMagmuxCommand(command: string, paneId: string): boolean {
return command.includes(magmuxNeedle(paneId));
}
-/** `pid` is, right now, pane `paneId`'s magmux. */
+/** `pid` is, right now, verifiably pane `paneId`'s magmux (false when the table is unavailable). */
export function isPaneMagmux(pid: number, paneId: string, table?: PsRow[]): boolean {
- const rows = table ?? readProcessTable();
+ const rows = table ?? readProcessTable() ?? [];
const row = rows.find((r) => r.pid === pid);
return !!row && isPaneMagmuxCommand(row.command, paneId);
}
-/** Every magmux process carrying pane `paneId` (normally zero or one). */
+/** Every magmux process verifiably carrying pane `paneId` (normally zero or one). */
export function findPaneMagmux(paneId: string, table?: PsRow[]): PsRow[] {
- return (table ?? readProcessTable()).filter((r) => isPaneMagmuxCommand(r.command, paneId));
+ return (table ?? readProcessTable() ?? []).filter((r) => isPaneMagmuxCommand(r.command, paneId));
}
export function paneIdentityMatches(command: string, pane: PaneIdentity): boolean {
@@ -378,6 +422,7 @@ set -f
export LC_ALL=C
PANE=$1 UUID=$2 CTL=$3 SOCKP=$4 REC=$5 TURN=$6 ROOT=$7
pstable() { ps -ax -ww -o pid=,pgid=,lstart=,command=; }
+ps_ok() { ps -o pid= -p $$ >/dev/null 2>&1; }
mag=""
mag_ok() {
case "$mag" in (''|*[!0-9]*) return 1;; esac
@@ -429,6 +474,9 @@ launch_dir_ok() {
const WATCHER_MAIN = `
while IFS= read -r l; do [ "$l" = done ] && exit 0; done
# EOF without "done": the owner is gone (SIGKILL included: the kernel closed its end).
+# No readable table (a sandbox refuses the setuid ps): nothing can be verified, so nothing
+# is signalled or removed; the files stay for a sweep that can read the table.
+ps_ok || exit 1
find_mag
find_pg
for s in TERM KILL; do
diff --git a/packages/cli/src/pane/process-table-trusted.test.ts b/packages/cli/src/pane/process-table-trusted.test.ts
index adcdd580..d1b40012 100644
--- a/packages/cli/src/pane/process-table-trusted.test.ts
+++ b/packages/cli/src/pane/process-table-trusted.test.ts
@@ -22,7 +22,7 @@ describe("processTableTrusted", () => {
});
test("A1: the real process table is trusted in an unsandboxed run", () => {
- const table = readProcessTable();
+ const table = readProcessTable() ?? [];
expect(table.some((entry) => entry.pid === process.pid)).toBe(true);
expect(processTableTrusted(table)).toBe(true);
});
diff --git a/packages/cli/src/pane/sweep-untrusted-table.test.ts b/packages/cli/src/pane/sweep-untrusted-table.test.ts
index b25653e1..5f04edb2 100644
--- a/packages/cli/src/pane/sweep-untrusted-table.test.ts
+++ b/packages/cli/src/pane/sweep-untrusted-table.test.ts
@@ -147,7 +147,7 @@ describe("sweep with an untrusted process table", () => {
const root = makeRoot();
const rec = makeLiveRecord(root);
expect(recordFiles(root, rec)).toEqual(allRecordFilesPresent);
- expect(readProcessTable().some((row) => row.pid === process.pid)).toBe(true);
+ expect(readProcessTable()?.some((row) => row.pid === process.pid)).toBe(true);
const result = await sweepOrphanPanes(root);
expect({
diff --git a/packages/cli/src/pane/test-helpers/hermetic-env.ts b/packages/cli/src/pane/test-helpers/hermetic-env.ts
index ab2dd8f4..6d071f09 100644
--- a/packages/cli/src/pane/test-helpers/hermetic-env.ts
+++ b/packages/cli/src/pane/test-helpers/hermetic-env.ts
@@ -27,7 +27,12 @@ import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { findMagmuxBinaryOrNull } from "../../launcher/magmux-binary.js";
import { projectDirNameFor } from "../../mcp-session/home-dir.js";
-import { readProcessTable } from "../process-identity.js";
+import {
+ type PsRow,
+ type PsSpawn,
+ readProcessTable,
+ setPsSpawnForTest,
+} from "../process-identity.js";
export const FAKE_CHILD = join(import.meta.dir, "fake-interactive-child.ts");
export const MAGMUX = findMagmuxBinaryOrNull();
@@ -124,6 +129,46 @@ export interface OrphanReport {
files: string[];
}
+/**
+ * The process table, or a throw: an unavailable table must fail a test, never read as
+ * "no process" (an orphan check on it would pass with every orphan still running).
+ */
+export function requireProcessTable(): PsRow[] {
+ const table = readProcessTable();
+ if (!table) throw new Error("process table unavailable: ps could not run");
+ return table;
+}
+
+/** The spawn failure Bun throws from `execFile` itself inside a macOS Seatbelt sandbox. */
+function sandboxEperm(): Error {
+ return Object.assign(new Error("EPERM: operation not permitted, posix_spawn 'ps'"), {
+ code: "EPERM",
+ syscall: "spawn",
+ path: "ps",
+ errno: -1,
+ });
+}
+
+/** `ps` as a sandbox leaves it: both spawns throw synchronously, as Bun does there. */
+export const SANDBOX_REFUSED_PS: PsSpawn = {
+ execFileSync() {
+ throw sandboxEperm();
+ },
+ execFile() {
+ throw sandboxEperm();
+ },
+};
+
+/** Run `fn` with the process table unavailable (`ps` refused), then restore the real spawn. */
+export async function withProcessTableUnavailable<T>(fn: () => T | Promise<T>): Promise<T> {
+ const prev = setPsSpawnForTest(SANDBOX_REFUSED_PS);
+ try {
+ return await fn();
+ } finally {
+ setPsSpawnForTest(prev);
+ }
+}
+
export function orphanReport(o: {
sockRoot: string;
ids?: string[];
@@ -131,7 +176,7 @@ export function orphanReport(o: {
}): OrphanReport {
const needles = [o.sockRoot, ...(o.ids ?? [])];
const pgids = new Set((o.pgids ?? []).filter((p) => p > 1));
- const processes = readProcessTable()
+ const processes = requireProcessTable()
.filter((r) => r.pid !== process.pid)
.filter((r) => needles.some((n) => r.command.includes(n)) || pgids.has(r.pgid))
.map((r) => `${r.pid} ${r.pgid} ${r.command.slice(0, 200)}`);
@@ -161,7 +206,7 @@ export async function waitNoOrphans(
/** SIGKILL anything a failed test left behind (by sockRoot / session id needles only). */
export function killLeftovers(o: { sockRoot: string; ids?: string[] }): void {
const needles = [o.sockRoot, ...(o.ids ?? [])];
- for (const r of readProcessTable()) {
+ for (const r of requireProcessTable()) {
if (r.pid === process.pid) continue;
if (needles.some((n) => r.command.includes(n))) {
try {
diff --git a/packages/cli/src/pane/test-helpers/sweep-in-sandbox.ts b/packages/cli/src/pane/test-helpers/sweep-in-sandbox.ts
index c3e98873..90621d2b 100644
--- a/packages/cli/src/pane/test-helpers/sweep-in-sandbox.ts
+++ b/packages/cli/src/pane/test-helpers/sweep-in-sandbox.ts
@@ -6,6 +6,6 @@ import { readProcessTable } from "../process-identity.js";
const root = process.argv[2];
if (!root) throw new Error("Expected a temporary pane root argument");
-const processTableRows = readProcessTable().length;
+const processTableRows = readProcessTable()?.length ?? 0;
const result = await sweepOrphanPanes(root);
process.stdout.write(`${JSON.stringify({ processTableRows, result })}\n`);
diff --git a/packages/cli/src/team-start-failure.test.ts b/packages/cli/src/team-start-failure.test.ts
index 86524429..18208350 100644
--- a/packages/cli/src/team-start-failure.test.ts
+++ b/packages/cli/src/team-start-failure.test.ts
@@ -15,8 +15,7 @@ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import { chmodSync, existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
-import { readProcessTable } from "./pane/process-identity.js";
-import { orphanReport } from "./pane/test-helpers/hermetic-env.js";
+import { orphanReport, requireProcessTable } from "./pane/test-helpers/hermetic-env.js";
import { setupSession, startModels } from "./team-orchestrator.js";
import {
MAGMUX,
@@ -66,7 +65,7 @@ describe.skipIf(!MAGMUX)("team spawn-loop failure", () => {
}).catch((err: unknown) => err);
await waitUntil(
() =>
- readProcessTable().some(
+ requireProcessTable().some(
(r) =>
r.command.includes("--model fake-ignore_term") && r.command.includes(panes.sockRoot)
),