Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(pane): keep live panes when the sweep cannot read the process table
Jack Rudenkocbf79965e290
diff --git a/ai-docs/architecture/pane-session.md b/ai-docs/architecture/pane-session.mdindex 2ca04989..eaa0bac9 100644--- a/ai-docs/architecture/pane-session.md+++ b/ai-docs/architecture/pane-session.md@@ -818,6 +818,15 @@ on its panes: without them a SIGKILLed MCP server would leave REPLs running andfirst spawn on a root, a process sweeps it once (`ensureSwept`): records whose owner is dead andwhose watcher is gone are killed after identity checks and removed; a recordless`magmux-c<pid>-*.sock` whose owner is dead is probed and cleaned.++ **A process table without this process decides nothing.** Every table read maps a `ps` failure+ to `[]` (EPERM in a macOS sandbox that refuses the setuid `/bin/ps`, EAGAIN/EMFILE, `maxBuffer`),+ and an empty table reads as "owner dead, watcher gone". So the sweep checks+ `processTableTrusted` on each read and, when this process is absent, keeps the pane: no kill,+ no unlink. Measured 2026-10-21: in the madbench home sandbox a voter's nested MCP server ran the+ sweep on the shared root and deleted a live voter's launch dir and record about 4 s after it+ started. A nested MCP server also does not sweep at all: it registers no session tools and never+ spawns a pane.3. **Shutdown hooks.** SIGINT, SIGTERM, SIGHUP and, for the MCP server, stdin EOF/close run theowner's `before` (the MCP server ends its session and team records there) and then reap every panein parallel, then exit 128 + n (0 for stdin). `stats-buffer.ts` used to exit synchronously ondiff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex 6cbb14a2..531bfcb5 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -2500,7 +2500,9 @@ async function main() {// The startup sweep: panes whose owner died (and whose watcher died too) are reaped// after an identity check. Asynchronous, and once per root per process — the first// pane's own sweep (ensureSwept in startPaneSession) is this one, not a second `ps`.- void ensureSwept(sockRootFor()).catch(() => undefined);+ // A nested server registers no session tools and never spawns a pane, so it has+ // nothing to sweep.+ if (!nested) void ensureSwept(sockRootFor()).catch(() => undefined);}/**diff --git a/packages/cli/src/pane/pane-registry.ts b/packages/cli/src/pane/pane-registry.tsindex 575db2d1..f6d796bf 100644--- a/packages/cli/src/pane/pane-registry.ts+++ b/packages/cli/src/pane/pane-registry.ts@@ -11,7 +11,8 @@* 3. the shutdown hooks below (signals, stdin EOF), a parallel ≤ 3 s reap.** Every signal to a process that is not this process's own unreaped child is preceded- * by an identity check from `process-identity.ts`.+ * by an identity check from `process-identity.ts`. A process table that does not list+ * this process (`processTableTrusted`) decides nothing: the sweep keeps the pane.*/import {@@ -44,6 +45,7 @@ import {liveEscaped,mergeSnapshots,parseGroupFile,+ processTableTrusted,readProcessTable,readProcessTableAsync,recordPathOf,@@ -80,12 +82,12 @@ export class PaneLimitError extends Error {let ownStart: string | null = null;-/** This process's `lstart` (one `ps` call, cached). */+/** 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);- ownStart = row?.lstart ?? "";- return ownStart;+ if (row) ownStart = row.lstart;+ return row?.lstart ?? "";}export function ownerAlive(@@ -465,6 +467,10 @@ async function killVerified(rec: PaneRecord, root: string): Promise<SweepTargetsasync 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+ return;+ }if (ownerAlive(rec, table)) return;const watcher = rec.watcherPid ? table.find((r) => r.pid === rec.watcherPid) : undefined;if (watcher && isPaneWatcherCommand(watcher.command, rec.paneId)) {@@ -475,6 +481,10 @@ async function sweepRecord(rec: PaneRecord, root: string, out: SweepResult): Proconst 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 =(t0.group && groupCheck(after, t0.group)) ||liveEscaped(after, t0.group).length > 0 ||@@ -508,6 +518,10 @@ 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+ return;+ }if (ownerOfIdAlive(id, table)) return;const sockPath = join(root, name);let client: MagmuxClient | null = null;diff --git a/packages/cli/src/pane/process-identity.ts b/packages/cli/src/pane/process-identity.tsindex 4bfa8cb9..72f3004a 100644--- a/packages/cli/src/pane/process-identity.ts+++ b/packages/cli/src/pane/process-identity.ts@@ -104,6 +104,16 @@ export function readProcessTable(): PsRow[] {}}+/**+ * 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.+ */+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[]> {return new Promise((resolve) => {diff --git a/packages/cli/src/pane/process-table-trusted.test.ts b/packages/cli/src/pane/process-table-trusted.test.tsnew file mode 100644index 00000000..adcdd580--- /dev/null+++ b/packages/cli/src/pane/process-table-trusted.test.ts@@ -0,0 +1,29 @@+// REGRESSION: team voters in a ps-less sandbox lose their launch dir; proxied pane child hits the API-key dialog — Fixed in /dev:fix session dev-fix-20261021-011007-a7c3++import { describe, expect, test } from "bun:test";+import { type PsRow, processTableTrusted, readProcessTable } from "./process-identity.js";++function row(pid: number): PsRow {+ return { pid, ppid: 0, pgid: 0, lstart: "", command: "" };+}++describe("processTableTrusted", () => {+ test("A1: an empty process table is untrusted", () => {+ expect(processTableTrusted([])).toBe(false);+ });++ test("A1: a nonempty table without this process is untrusted", () => {+ expect(processTableTrusted([row(process.pid + 1), row(process.pid + 2)])).toBe(false);+ });++ test("A1: a table containing this process is trusted", () => {+ expect(processTableTrusted([row(process.pid)])).toBe(true);+ expect(processTableTrusted([row(process.pid + 1), row(process.pid)])).toBe(true);+ });++ test("A1: the real process table is trusted in an unsandboxed run", () => {+ 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.tsnew file mode 100644index 00000000..b25653e1--- /dev/null+++ b/packages/cli/src/pane/sweep-untrusted-table.test.ts@@ -0,0 +1,163 @@+// REGRESSION: team voters in a ps-less sandbox lose their launch dir; proxied pane child hits the API-key dialog — Fixed in /dev:fix session dev-fix-20261021-011007-a7c3++import { afterEach, describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { join } from "node:path";+import {+ type PaneRecord,+ type SweepResult,+ sweepOrphanPanes,+ writeRecord,+} from "./pane-registry.js";+import { readProcessTable, recordPathOf, sockPathOf } from "./process-identity.js";++const SANDBOX_EXEC = "/usr/bin/sandbox-exec";+const SANDBOX_PROFILE = '(version 1)(allow default)(deny process-exec (literal "/bin/ps"))';+const HELPER = join(import.meta.dir, "test-helpers", "sweep-in-sandbox.ts");+const noSandbox = process.platform !== "darwin" || !existsSync(SANDBOX_EXEC);+const roots: string[] = [];++interface SandboxSweep {+ processTableRows: number;+ result: SweepResult;+}++afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++function makeRoot(): string {+ const root = realpathSync(mkdtempSync("/tmp/sw-"));+ roots.push(root);+ chmodSync(root, 0o700);+ mkdirSync(join(root, "panes"), { mode: 0o700 });+ return root;+}++function livePaneId(): string {+ return `c${process.pid}-${Date.now().toString(36)}-t01-abcdef`;+}++function makeLiveRecord(root: string): PaneRecord {+ const paneId = livePaneId();+ const launcherDir = mkdtempSync(join(root, "launch-"));+ const turnDir = mkdtempSync(join(root, "launch-"));+ const ownerStart = execFileSync("ps", ["-o", "lstart=", "-p", String(process.pid)], {+ encoding: "utf8",+ env: { ...process.env, LC_ALL: "C" },+ })+ .trim()+ .replace(/\s+/g, " ");+ expect(ownerStart.length).toBeGreaterThan(0);+ const rec: PaneRecord = {+ paneId,+ ownerPid: process.pid,+ ownerStart,+ watcherPid: null,+ magmuxPid: null,+ panePid: null,+ sessionUuid: crypto.randomUUID(),+ sockPath: sockPathOf(root, paneId),+ launcherDir,+ turnDir,+ createdAt: new Date().toISOString(),+ };+ writeFileSync(join(turnDir, "turn-1.md"), "Keep this live owner's prompt.\n");+ writeFileSync(rec.sockPath, "");+ writeRecord(root, rec);+ return rec;+}++function recordFiles(root: string, rec: PaneRecord) {+ return {+ record: existsSync(recordPathOf(root, rec.paneId)),+ launcherDir: existsSync(rec.launcherDir),+ turnDir: existsSync(rec.turnDir),+ turnFile: existsSync(join(rec.turnDir, "turn-1.md")),+ socket: existsSync(rec.sockPath),+ };+}++const allRecordFilesPresent = {+ record: true,+ launcherDir: true,+ turnDir: true,+ turnFile: true,+ socket: true,+};++function sandboxSweep(root: string): SandboxSweep {+ const stdout = execFileSync(+ SANDBOX_EXEC,+ ["-p", SANDBOX_PROFILE, process.execPath, HELPER, root],+ { encoding: "utf8", timeout: 15_000 }+ );+ return JSON.parse(stdout) as SandboxSweep;+}++describe("sweep with an untrusted process table", () => {+ test.skipIf(noSandbox)(+ "A2: denied ps keeps a live owner's record, launch dirs, turn file and socket",+ () => {+ const root = makeRoot();+ const rec = makeLiveRecord(root);+ expect(recordFiles(root, rec)).toEqual(allRecordFilesPresent);++ const swept = sandboxSweep(root);+ expect(swept.processTableRows).toBe(0);+ expect({ files: recordFiles(root, rec), result: swept.result }).toEqual({+ files: allRecordFilesPresent,+ result: { reaped: [], cleaned: [], kept: [rec.paneId] },+ });+ },+ 20_000+ );++ test.skipIf(noSandbox)(+ "A3: denied ps keeps a recordless socket whose embedded owner is alive",+ () => {+ const root = makeRoot();+ const paneId = livePaneId();+ const socket = sockPathOf(root, paneId);+ writeFileSync(socket, "");+ expect(existsSync(recordPathOf(root, paneId))).toBe(false);+ expect(existsSync(socket)).toBe(true);++ const swept = sandboxSweep(root);+ expect(swept.processTableRows).toBe(0);+ expect({+ socketExists: existsSync(socket),+ cleaned: swept.result.cleaned,+ reaped: swept.result.reaped,+ }).toEqual({ socketExists: true, cleaned: [], reaped: [] });+ },+ 20_000+ );++ test("A4: working ps keeps the same live-owner record, launch dirs, turn file and socket", async () => {+ const root = makeRoot();+ const rec = makeLiveRecord(root);+ expect(recordFiles(root, rec)).toEqual(allRecordFilesPresent);+ expect(readProcessTable().some((row) => row.pid === process.pid)).toBe(true);++ const result = await sweepOrphanPanes(root);+ expect({+ files: recordFiles(root, rec),+ cleaned: result.cleaned,+ reaped: result.reaped,+ }).toEqual({+ files: allRecordFilesPresent,+ cleaned: [],+ reaped: [],+ });+ }, 20_000);+});diff --git a/packages/cli/src/pane/test-helpers/sweep-in-sandbox.ts b/packages/cli/src/pane/test-helpers/sweep-in-sandbox.tsnew file mode 100644index 00000000..c3e98873--- /dev/null+++ b/packages/cli/src/pane/test-helpers/sweep-in-sandbox.ts@@ -0,0 +1,11 @@+// REGRESSION: team voters in a ps-less sandbox lose their launch dir; proxied pane child hits the API-key dialog — Fixed in /dev:fix session dev-fix-20261021-011007-a7c3++import { sweepOrphanPanes } from "../pane-registry.js";+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 result = await sweepOrphanPanes(root);+process.stdout.write(`${JSON.stringify({ processTableRows, result })}\n`);