Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): add pane process identity and the generated pane watcher
Jack Rudenko08ba88d6eeab
diff --git a/packages/cli/src/pane/process-identity.test.ts b/packages/cli/src/pane/process-identity.test.tsnew file mode 100644index 00000000..bc1e784f--- /dev/null+++ b/packages/cli/src/pane/process-identity.test.ts@@ -0,0 +1,245 @@+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 { join } from "node:path";+import {+ type PaneIdentity,+ type PsRow,+ WATCHER_FUNCTIONS,+ WATCHER_SCRIPT,+ formatGroupFile,+ groupCheck,+ isLaunchDirPath,+ isPaneMagmuxCommand,+ isPaneWatcherCommand,+ mergeSnapshots,+ paneIdentityMatches,+ parseGroupFile,+ parsePsTable,+ verifiedGroupSnapshot,+} from "./process-identity.js";+import { FIXTURES } from "./test-helpers/fixtures.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.+const fx = JSON.parse(readFileSync(join(FIXTURES, "ps", "live-pane.json"), "utf8")) as {+ paneId: string;+ sessionUuid: string;+ sockRoot: string;+ panePid: number;+ ps: string;+};+const table = parsePsTable(fx.ps);+const magRow = table.find((r) => r.command.includes("magmux --headless")) as PsRow;+const leader = table.find((r) => r.pid === fx.panePid) as PsRow;+const watcherRow = table.find((r) => r.command.startsWith("/bin/sh -c")) as PsRow;+const ctlDir = (+ magRow.command.match(/'([^']+)\/pane-launch\.sh'/) as RegExpMatchArray+)[1] as string;+const pane: PaneIdentity = { paneId: fx.paneId, sessionUuid: fx.sessionUuid, ctlDir };++const scratch = mkdtempSync("/tmp/pid-test-");+afterAll(() => rmSync(scratch, { recursive: true, force: true }));++describe("parsePsTable on a real table", () => {+ test("three rows: watcher, magmux (own group), the pane leader (own group)", () => {+ expect(table).toHaveLength(3);+ expect(magRow.pgid).toBe(magRow.pid);+ expect(leader.pgid).toBe(leader.pid);+ expect(leader.ppid).toBe(magRow.pid);+ expect(leader.lstart).toMatch(/^\w{3} \w{3} \d+ \d\d:\d\d:\d\d \d{4}$/);+ });++ test("the watcher is recognised by argv0 + pane id (the sweep's 'watcher alive' check)", () => {+ expect(isPaneWatcherCommand(watcherRow.command, fx.paneId)).toBe(true);+ expect(isPaneWatcherCommand(watcherRow.command, "c1-other-t01-000000")).toBe(false);+ });+});++describe("TS predicates", () => {+ test("magmux is identified by `--id <paneId> --sock-dir`, never by pid", () => {+ expect(isPaneMagmuxCommand(magRow.command, fx.paneId)).toBe(true);+ expect(isPaneMagmuxCommand(magRow.command, "c1-other-t01-000000")).toBe(false);+ expect(isPaneMagmuxCommand(leader.command, fx.paneId)).toBe(false);+ expect(isPaneMagmuxCommand(watcherRow.command, fx.paneId)).toBe(false);+ });++ test("a pane member carries --session-id <uuid> or <ctlDir>/pane-launch.sh", () => {+ expect(paneIdentityMatches(leader.command, pane)).toBe(true);+ expect(+ paneIdentityMatches(leader.command, { ...pane, sessionUuid: "x", ctlDir: "/nope" })+ ).toBe(false);+ const preExec = `/bin/sh -c . '${ctlDir}/pane-launch.sh'`;+ expect(paneIdentityMatches(preExec, { ...pane, sessionUuid: "x" })).toBe(true);+ });++ test("the verified snapshot is the pgid's members, only while one still carries the identity", () => {+ const snap = verifiedGroupSnapshot(table, fx.panePid, pane);+ expect(snap).toEqual({+ pgid: fx.panePid,+ members: [{ pid: leader.pid, lstart: leader.lstart }],+ });+ expect(+ verifiedGroupSnapshot(table, fx.panePid, { ...pane, sessionUuid: "x", ctlDir: "/n" })+ ).toBeNull();+ expect(verifiedGroupSnapshot(table, 1, pane)).toBeNull();+ });++ test("group check: passes on a recorded (pid, start); fails on the same pid with another start", () => {+ const snap = verifiedGroupSnapshot(table, fx.panePid, pane);+ expect(groupCheck(table, snap)).toBe(true);+ const reused = table.map((r) =>+ r.pid === leader.pid ? { ...r, lstart: "Thu Jan 1 00:00:00 2099" } : r+ );+ expect(groupCheck(reused, snap)).toBe(false);+ expect(+ groupCheck(+ table.filter((r) => r.pid !== leader.pid),+ snap+ )+ ).toBe(false);+ expect(groupCheck(table, null)).toBe(false);+ });++ test("an unidentifiable survivor still passes when it was recorded (the orphan_grandchild case)", () => {+ const grandchild: PsRow = {+ pid: 999_001,+ ppid: 1,+ pgid: fx.panePid,+ lstart: leader.lstart,+ command: "sleep 300",+ };+ const withChild = [...table, grandchild];+ const snap = verifiedGroupSnapshot(withChild, fx.panePid, pane);+ const leaderGone = withChild.filter((r) => r.pid !== leader.pid);+ expect(verifiedGroupSnapshot(leaderGone, fx.panePid, pane)).toBeNull();+ expect(groupCheck(leaderGone, snap)).toBe(true);+ });++ test("group file round trip and snapshot merge", () => {+ const snap = verifiedGroupSnapshot(table, fx.panePid, pane);+ expect(parseGroupFile(formatGroupFile(snap!))).toEqual(snap);+ const merged = mergeSnapshots(snap, { pgid: fx.panePid, members: [{ pid: 5, lstart: "x" }] });+ expect(merged?.members).toHaveLength(2);+ expect(mergeSnapshots(snap, { pgid: 7, members: [] })).toBe(snap);+ });+});++/** Run the watcher's shell functions against the same real table through a fake `ps`. */+function shell(script: string, opts: { ctl?: string; root?: string } = {}): string {+ const bin = join(scratch, "bin");+ mkdirSync(bin, { recursive: true });+ // the watcher's own ps format: pid=,pgid=,lstart=,command= (the TS table minus ppid)+ const shellTable = table.map((r) => `${r.pid} ${r.pgid} ${r.lstart} ${r.command}`).join("\n");+ writeFileSync(join(scratch, "table.txt"), `${shellTable}\n`);+ // honours `-p <pid>` with `-o command=` (mag_ok) and prints the whole table otherwise+ writeFileSync(+ join(bin, "ps"),+ `#!/bin/sh\npid=""\nwhile [ $# -gt 0 ]; do [ "$1" = -p ] && pid=$2; shift; done\nif [ -n "$pid" ]; then awk -v p="$pid" '$1 == p { $1 = ""; $2 = ""; $3 = ""; $4 = ""; $5 = ""; $6 = ""; $7 = ""; sub(/^ +/, ""); print }' ${join(scratch, "table.txt")}; else cat ${join(scratch, "table.txt")}; fi\n`,+ { mode: 0o755 }+ );+ const r = spawnSync(+ "/bin/sh",+ [+ "-c",+ `${WATCHER_FUNCTIONS}\n${script}`,+ "claudish-pane-watcher",+ fx.paneId,+ fx.sessionUuid,+ opts.ctl ?? ctlDir,+ "s",+ "r",+ "t",+ opts.root ?? fx.sockRoot,+ ],+ { encoding: "utf8", env: { PATH: `${bin}:/usr/bin:/bin` } }+ );+ return (r.stdout ?? "").trim();+}++describe("the generated watcher shell agrees with the TS predicates on the same table", () => {+ test("the script parses under bash's sh and under dash", () => {+ expect(spawnSync("/bin/sh", ["-n", "-c", WATCHER_SCRIPT]).status).toBe(0);+ const dash = spawnSync("dash", ["-n", "-c", WATCHER_SCRIPT]);+ if (!dash.error) expect(dash.status).toBe(0);+ });++ test("mag_ok / find_mag", () => {+ expect(shell(`mag=${magRow.pid}; mag_ok && echo Y || echo N`)).toBe("Y");+ expect(shell(`mag=${leader.pid}; mag_ok && echo Y || echo N`)).toBe("N");+ expect(shell(`find_mag && echo "$mag"`)).toBe(String(magRow.pid));+ });++ test("group_ok by identity, by recorded member, and refused for a reused pid", () => {+ expect(shell(`pg=${fx.panePid}; group_ok && echo Y || echo N`)).toBe("Y");+ const ctl = join(scratch, "launch-AbC123");+ mkdirSync(ctl, { recursive: true });+ const snap = verifiedGroupSnapshot(table, fx.panePid, pane)!;+ writeFileSync(join(ctl, "group"), formatGroupFile(snap));+ // ctl differs from the leader's argv and the uuid is wrong → only the recorded member can pass+ const r1 = spawnSync(+ "/bin/sh",+ [+ "-c",+ `${WATCHER_FUNCTIONS}\npg=${fx.panePid}; group_ok && echo Y || echo N`,+ "w",+ fx.paneId,+ "wrong-uuid",+ ctl,+ "s",+ "r",+ "t",+ scratch,+ ],+ {+ encoding: "utf8",+ env: { PATH: `${join(scratch, "bin")}:/usr/bin:/bin` },+ }+ );+ expect(r1.stdout.trim()).toBe(groupCheck(table, snap) ? "Y" : "N");+ writeFileSync(+ join(ctl, "group"),+ formatGroupFile({+ pgid: fx.panePid,+ members: [{ pid: leader.pid, lstart: "Thu Jan 1 00:00:00 2099" }],+ })+ );+ const r2 = spawnSync(+ "/bin/sh",+ [+ "-c",+ `${WATCHER_FUNCTIONS}\npg=${fx.panePid}; group_ok && echo Y || echo N`,+ "w",+ fx.paneId,+ "wrong-uuid",+ ctl,+ "s",+ "r",+ "t",+ scratch,+ ],+ {+ encoding: "utf8",+ env: { PATH: `${join(scratch, "bin")}:/usr/bin:/bin` },+ }+ );+ expect(r2.stdout.trim()).toBe("N");+ });++ test("launch_dir_ok ≡ isLaunchDirPath (R3-M2): direct child, launch-XXXXXX, real dir", () => {+ const root = mkdtempSync(join(scratch, "root-"));+ const good = join(root, "launch-AbC123");+ mkdirSync(good);+ const nested = join(root, "x", "launch-AbC123");+ mkdirSync(nested, { recursive: true });+ const badName = join(root, "launch-AbC12");+ mkdirSync(badName);+ const link = join(root, "launch-LnK123");+ symlinkSync(good, link);+ for (const p of [good, nested, badName, link, join(root, "launch-NoNe12"), "/etc"]) {+ const sh = shell(`launch_dir_ok "${p}" && echo Y || echo N`, { root });+ expect(sh).toBe(isLaunchDirPath(root, p) ? "Y" : "N");+ }+ expect(isLaunchDirPath(root, good)).toBe(true);+ });+});diff --git a/packages/cli/src/pane/process-identity.ts b/packages/cli/src/pane/process-identity.tsnew file mode 100644index 00000000..8282bb48--- /dev/null+++ b/packages/cli/src/pane/process-identity.ts@@ -0,0 +1,354 @@+/**+ * The ONE definition of "this pid is that pane's magmux" and "this process group is+ * that pane's group" (architecture §2.11, D15, X-C1), used by the reap, the startup+ * sweep and — as generated shell — the pane watcher.+ *+ * Identity is never a bare pid. A pid is reused; a pane id is not (it embeds the owner+ * pid, the owner's start time and six random hex digits), and a (pid, start time) pair+ * cannot be impersonated by a new process. So:+ *+ * - magmux: its command line contains `--id <paneId> --sock-dir`;+ * - a pane group member: its command line contains `--session-id <uuid>` or+ * `<ctlDir>/pane-launch.sh` (the pane leader before and after its `exec`, bun, claude);+ * - the pane group: some process whose pgid is the recorded pgid has a (pid, start time)+ * pair in the member set recorded while the group's identity was verified. A pgid is+ * not reused while any member lives, so a passing check proves the group is the+ * pane's — even when only an unidentifiable grandchild is left.+ *+ * Every process-table read is ONE `LC_ALL=C ps -ax -ww -o pid=,ppid=,pgid=,lstart=,command=`+ * (portable across macOS and Linux; `ps -g` means different things on the two).+ *+ * Paths are validated before any `rm` (R3-M2): a control or turn directory is a DIRECT+ * child of the socket root named `launch-` + six `[A-Za-z0-9]`; a socket is exactly+ * `<root>/magmux-<paneId>.sock`; a record is exactly `<root>/panes/<paneId>.json`.+ */++import { execFile, execFileSync } from "node:child_process";+import { lstatSync } from "node:fs";+import { basename, dirname, join } from "node:path";++export interface PsRow {+ pid: number;+ ppid: number;+ pgid: number;+ /** `lstart`, whitespace collapsed: `Mon Oct 6 12:34:56 2026` */+ lstart: string;+ command: string;+}++/** One verified member of a pane group. */+export interface GroupMember {+ pid: number;+ lstart: string;+}++export interface GroupSnapshot {+ pgid: number;+ members: GroupMember[];+}++/** What identifies one pane's processes. */+export interface PaneIdentity {+ paneId: string;+ sessionUuid: string;+ /** the control directory holding `pane-launch.sh` */+ ctlDir: string;+}++const PS_ARGS = ["-ax", "-ww", "-o", "pid=,ppid=,pgid=,lstart=,command="];+const PS_ROW = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d\d:\d\d:\d\d\s+\d{4})\s?(.*)$/;++export function collapse(s: string): string {+ return s.trim().replace(/\s+/g, " ");+}++/** Parse `ps -o pid=,ppid=,pgid=,lstart=,command=` output. Unparseable rows are dropped. */+export function parsePsTable(text: string): PsRow[] {+ const rows: PsRow[] = [];+ for (const line of text.split("\n")) {+ const m = line.match(PS_ROW);+ if (!m) continue;+ rows.push({+ pid: Number(m[1]),+ ppid: Number(m[2]),+ pgid: Number(m[3]),+ lstart: collapse(m[4] ?? ""),+ command: (m[5] ?? "").trim(),+ });+ }+ return rows;+}++const PS_ENV = { PATH: "/bin:/usr/bin:/usr/sbin:/sbin", LC_ALL: "C" };++/** The whole process table, synchronously (exit hooks, the sweep). */+export function readProcessTable(): PsRow[] {+ try {+ return parsePsTable(+ execFileSync("ps", PS_ARGS, {+ env: PS_ENV,+ encoding: "utf8",+ maxBuffer: 64 * 1024 * 1024,+ stdio: ["ignore", "pipe", "ignore"],+ })+ );+ } catch {+ return [];+ }+}++/** The whole process table without blocking the event loop (the registry tick). */+export function readProcessTableAsync(): Promise<PsRow[]> {+ return new Promise((resolve) => {+ execFile(+ "ps",+ PS_ARGS,+ { env: PS_ENV, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },+ (err, stdout) => resolve(err ? [] : parsePsTable(String(stdout)))+ );+ });+}++/** `lstart` of one pid, or null when it is gone. */+export function lstartOf(pid: number, table?: PsRow[]): string | null {+ const rows = table ?? readProcessTable();+ return rows.find((r) => r.pid === pid)?.lstart ?? null;+}++/* ───────────────────────────── needles ───────────────────────────── */++/** What magmux's argv carries for pane `paneId`. Shell form: `--id $1 --sock-dir`. */+export function magmuxNeedle(paneId: string): string {+ return `--id ${paneId} --sock-dir`;+}++/** What every identifiable pane member's argv carries. Shell form: `--session-id $2`. */+export function sessionNeedle(sessionUuid: string): string {+ return `--session-id ${sessionUuid}`;+}++/** The launcher the pane leader runs before its `exec`. Shell form: `$3/pane-launch.sh`. */+export function launcherNeedle(ctlDir: string): string {+ return `${ctlDir}/pane-launch.sh`;+}++export function isPaneMagmuxCommand(command: string, paneId: string): boolean {+ return command.includes(magmuxNeedle(paneId));+}++/** `pid` is, right now, pane `paneId`'s magmux. */+export function isPaneMagmux(pid: number, paneId: string, table?: PsRow[]): boolean {+ 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). */+export function findPaneMagmux(paneId: string, table?: PsRow[]): PsRow[] {+ return (table ?? readProcessTable()).filter((r) => isPaneMagmuxCommand(r.command, paneId));+}++export function paneIdentityMatches(command: string, pane: PaneIdentity): boolean {+ return (+ command.includes(sessionNeedle(pane.sessionUuid)) ||+ command.includes(launcherNeedle(pane.ctlDir))+ );+}++/**+ * The verified snapshot of group `pgid`: every member's (pid, start time), but only when+ * at least one member still carries the pane's identity. Null otherwise.+ */+export function verifiedGroupSnapshot(+ table: PsRow[],+ pgid: number,+ pane: PaneIdentity+): GroupSnapshot | null {+ if (!Number.isInteger(pgid) || pgid <= 1) return null;+ const members = table.filter((r) => r.pgid === pgid);+ if (!members.some((r) => paneIdentityMatches(r.command, pane))) return null;+ return { pgid, members: members.map((r) => ({ pid: r.pid, lstart: r.lstart })) };+}++/** Merge a fresh snapshot into a recorded one (members only accumulate). */+export function mergeSnapshots(+ a: GroupSnapshot | null,+ b: GroupSnapshot | null+): GroupSnapshot | null {+ if (!a) return b;+ if (!b || b.pgid !== a.pgid) return a;+ const seen = new Set(a.members.map((m) => `${m.pid} ${m.lstart}`));+ const members = [...a.members];+ for (const m of b.members) if (!seen.has(`${m.pid} ${m.lstart}`)) members.push(m);+ return { pgid: a.pgid, members };+}++/**+ * The group check, before every group signal: some LIVE process whose pgid is the+ * recorded pgid has a (pid, start time) pair in the recorded members.+ */+export function groupCheck(table: PsRow[], snap: GroupSnapshot | null): boolean {+ if (!snap || !Number.isInteger(snap.pgid) || snap.pgid <= 1) return false;+ const keys = new Set(snap.members.map((m) => `${m.pid} ${collapse(m.lstart)}`));+ return table.some((r) => r.pgid === snap.pgid && keys.has(`${r.pid} ${r.lstart}`));+}++/** Serialise a snapshot as the `group` file: the pgid, then one `pid lstart` line per member. */+export function formatGroupFile(snap: GroupSnapshot): string {+ return `${snap.pgid}\n${snap.members.map((m) => `${m.pid} ${collapse(m.lstart)}`).join("\n")}\n`;+}++export function parseGroupFile(text: string): GroupSnapshot | null {+ const lines = text.split("\n").filter((l) => l.trim());+ const pgid = Number(lines[0]);+ if (!Number.isInteger(pgid) || pgid <= 1) return null;+ const members: GroupMember[] = [];+ for (const l of lines.slice(1)) {+ const m = l.match(/^(\d+) (.+)$/);+ if (m) members.push({ pid: Number(m[1]), lstart: collapse(m[2] ?? "") });+ }+ return { pgid, members };+}++/* ───────────────────────────── paths (R3-M2) ───────────────────────────── */++export const LAUNCH_DIR_RE = /^launch-[A-Za-z0-9]{6}$/;++/** A control or turn directory: a real (non-symlink) directory, a direct child of `root`. */+export function isLaunchDirPath(root: string, p: string): boolean {+ if (dirname(p) !== root || !LAUNCH_DIR_RE.test(basename(p))) return false;+ try {+ const st = lstatSync(p);+ return st.isDirectory() && !st.isSymbolicLink();+ } catch {+ return false;+ }+}++export function sockPathOf(root: string, paneId: string): string {+ return join(root, `magmux-${paneId}.sock`);+}++export function recordPathOf(root: string, paneId: string): string {+ return join(root, "panes", `${paneId}.json`);+}++export function isPaneSockPath(root: string, p: string, paneId: string): boolean {+ return p === sockPathOf(root, paneId);+}++export function isPaneRecordPath(root: string, p: string, paneId: string): boolean {+ return p === recordPathOf(root, paneId);+}++/* ───────────────────────────── the watcher, as shell ───────────────────────────── */++/**+ * Shell versions of the predicates above. Positional parameters (values are NEVER+ * interpolated into the script): $1 paneId, $2 sessionUuid, $3 ctlDir, $4 sockPath,+ * $5 recordPath, $6 turnDir, $7 sockRoot. `ps` and `pgrep` come from PATH, so a test can+ * source these functions against a recorded table.+ */+export const WATCHER_FUNCTIONS = `+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=; }+mag=""+mag_ok() {+ case "$mag" in (''|*[!0-9]*) return 1;; esac+ ps -ww -o command= -p "$mag" 2>/dev/null | N="--id $PANE --sock-dir" awk 'index($0, ENVIRON["N"]) { f = 1 } END { exit !f }'+}+find_mag() {+ if [ -f "$CTL/magmux.pid" ]; then mag=$(head -n 1 "$CTL/magmux.pid"); fi+ mag_ok && return 0+ mag=$(pstable | N="--id $PANE --sock-dir" awk 'index($0, ENVIRON["N"]) { print $1; exit }')+ mag_ok+}+pg=""+ident_in_pg() {+ pstable | P="$pg" A="--session-id $UUID" B="$CTL/pane-launch.sh" awk '$2 == ENVIRON["P"] && (index($0, ENVIRON["A"]) || index($0, ENVIRON["B"])) { f = 1 } END { exit !f }'+}+member_in_pg() {+ [ -f "$CTL/group" ] || return 1+ pstable | P="$pg" awk '$2 == ENVIRON["P"] { print $1 " " $3 " " $4 " " $5 " " $6 " " $7 }' | grep -Fxq -f "$CTL/group"+}+group_ok() {+ case "$pg" in (''|*[!0-9]*|0|1) return 1;; esac+ member_in_pg || ident_in_pg+}+find_pg() {+ pg=""+ if [ -f "$CTL/group" ]; then pg=$(head -n 1 "$CTL/group"); fi+ case "$pg" in (''|*[!0-9]*) pg="";; esac+ if [ -z "$pg" ] && mag_ok; then+ lead=$(pgrep -P "$mag" | head -n 1)+ [ -n "$lead" ] && pg=$(ps -o pgid= -p "$lead" | tr -d ' ')+ fi+ group_ok+}+alive() { group_ok || mag_ok; }+settle_wait() { i=0; while [ "$i" -lt "$1" ] && alive; do sleep 0.2; i=$((i + 1)); done; }+launch_dir_ok() {+ case "$1" in ("$ROOT"/launch-??????) ;; (*) return 1;; esac+ b=\${1#"$ROOT"/launch-}+ case "$b" in (*[!A-Za-z0-9]*) return 1;; esac+ [ -d "$1" ] && [ ! -L "$1" ]+}+`;++/** The pane watcher's main body, run after the functions. */+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).+find_mag+find_pg+for s in TERM KILL; do+ alive || break+ group_ok && kill -"$s" -"$pg" 2>/dev/null+ mag_ok && kill -"$s" "$mag" 2>/dev/null+ if [ "$s" = TERM ]; then settle_wait 10; else settle_wait 5; fi+done+alive && exit 1+[ "$SOCKP" = "$ROOT/magmux-$PANE.sock" ] && rm -f -- "$SOCKP"+[ "$REC" = "$ROOT/panes/$PANE.json" ] && rm -f -- "$REC"+launch_dir_ok "$CTL" && rm -rf -- "$CTL"+launch_dir_ok "$TURN" && rm -rf -- "$TURN"+exit 0+`;++export const WATCHER_SCRIPT = `${WATCHER_FUNCTIONS}${WATCHER_MAIN}`;++/** `argv[0]` the watcher runs under; the sweep recognises a live watcher by it. */+export const WATCHER_ARGV0 = "claudish-pane-watcher";++export interface WatcherArgs {+ paneId: string;+ sessionUuid: string;+ ctlDir: string;+ sockPath: string;+ recordPath: string;+ turnDir: string;+ sockRoot: string;+}++/** `/bin/sh` argv for one watcher: values only as positional parameters. */+export function watcherArgv(a: WatcherArgs): string[] {+ return [+ "-c",+ WATCHER_SCRIPT,+ WATCHER_ARGV0,+ a.paneId,+ a.sessionUuid,+ a.ctlDir,+ a.sockPath,+ a.recordPath,+ a.turnDir,+ a.sockRoot,+ ];+}++/** A process table row is pane `paneId`'s watcher. */+export function isPaneWatcherCommand(command: string, paneId: string): boolean {+ return command.includes(` ${WATCHER_ARGV0} ${paneId} `);+}diff --git a/packages/cli/src/pane/test-fixtures/ps/live-pane.json b/packages/cli/src/pane/test-fixtures/ps/live-pane.jsonnew file mode 100644index 00000000..cdcb07d4--- /dev/null+++ b/packages/cli/src/pane/test-fixtures/ps/live-pane.json@@ -0,0 +1,7 @@+{+ "paneId": "c94698-muw5tusq-t01-f3762b",+ "sessionUuid": "511fd190-5ff6-4692-bcaf-e2879c6b9469",+ "sockRoot": "/tmp/cpt-958e59a8",+ "panePid": 94706,+ "ps": "94704 94698 94704 Tue Oct 6 15:09:49 2026 /bin/sh -c \\012set -f\\012export LC_ALL=C\\012PANE=$1 UUID=$2 CTL=$3 SOCKP=$4 REC=$5 TURN=$6 ROOT=$7\\012pstable() { ps -ax -ww -o pid=,pgid=,lstart=,command=; }\\012mag=\"\"\\012mag_ok() {\\012 case \"$mag\" in (''|*[!0-9]*) return 1;; esac\\012 pstable | while read -r p g d1 d2 d3 d4 d5 cmd; do\\012 [ \"$p\" = \"$mag\" ] || continue\\012 case \"$cmd\" in (*\"--id $PANE --sock-dir\"*) echo y;; esac\\012 break\\012 done | grep -q y\\012}\\012find_mag() {\\012 if [ -f \"$CTL/magmux.pid\" ]; then mag=$(head -n 1 \"$CTL/magmux.pid\"); fi\\012 mag_ok && return 0\\012 mag=$(pstable | while read -r p g d1 d2 d3 d4 d5 cmd; do\\012 case \"$cmd\" in (*\"--id $PANE --sock-dir\"*) echo \"$p\"; break;; esac\\012 done)\\012 mag_ok\\012}\\012pg=\"\"\\012ident_in_pg() {\\012 pstable | while read -r p g d1 d2 d3 d4 d5 cmd; do\\012 [ \"$g\" = \"$pg\" ] || continue\\012 case \"$cmd\" in (*\"--session-id $UUID\"*|*\"$CTL/pane-launch.sh\"*) echo y; break;; esac\\012 done | grep -q y\\012}\\012member_in_pg() {\\012 [ -f \"$CTL/group\" ] || return 1\\012 pstable | while read -r p g d1 d2 d3 d4 d5 cmd; do\\012 [ \"$g\" = \"$pg\" ] || continue\\012 if grep -Fxq -- \"$p $d1 $d2 $d3 $d4 $d5\" \"$CTL/group\"; then echo y; break; fi\\012 done | grep -q y\\012}\\012group_ok() {\\012 case \"$pg\" in (''|*[!0-9]*|0|1) return 1;; esac\\012 member_in_pg || ident_in_pg\\012}\\012find_pg() {\\012 pg=\"\"\\012 if [ -f \"$CTL/group\" ]; then pg=$(head -n 1 \"$CTL/group\"); fi\\012 case \"$pg\" in (''|*[!0-9]*) pg=\"\";; esac\\012 if [ -z \"$pg\" ] && mag_ok; then\\012 lead=$(pgrep -P \"$mag\" | head -n 1)\\012 [ -n \"$lead\" ] && pg=$(ps -o pgid= -p \"$lead\" | tr -d ' ')\\012 fi\\012 group_ok\\012}\\012launch_dir_ok() {\\012 case \"$1\" in (\"$ROOT\"/launch-??????) ;; (*) return 1;; esac\\012 b=${1#\"$ROOT\"/launch-}\\012 case \"$b\" in (*[!A-Za-z0-9]*) return 1;; esac\\012 [ -d \"$1\" ] && [ ! -L \"$1\" ]\\012}\\012\\012while IFS= read -r l; do [ \"$l\" = done ] && exit 0; done\\012# EOF without \"done\": the owner is gone (SIGKILL included: the kernel closed its end).\\012find_mag\\012find_pg\\012for s in TERM KILL; do\\012 group_ok && kill -\"$s\" -\"$pg\" 2>/dev/null\\012 mag_ok && kill -\"$s\" \"$mag\" 2>/dev/null\\012 [ \"$s\" = TERM ] && sleep 2\\012done\\012sleep 1\\012if group_ok || mag_ok; then exit 1; fi\\012[ \"$SOCKP\" = \"$ROOT/magmux-$PANE.sock\" ] && rm -f -- \"$SOCKP\"\\012[ \"$REC\" = \"$ROOT/panes/$PANE.json\" ] && rm -f -- \"$REC\"\\012launch_dir_ok \"$CTL\" && rm -rf -- \"$CTL\"\\012launch_dir_ok \"$TURN\" && rm -rf -- \"$TURN\"\\012exit 0\\012 claudish-pane-watcher c94698-muw5tusq-t01-f3762b 511fd190-5ff6-4692-bcaf-e2879c6b9469 /tmp/cpt-958e59a8/launch-l6DJCS /tmp/cpt-958e59a8/magmux-c94698-muw5tusq-t01-f3762b.sock /tmp/cpt-958e59a8/panes/c94698-muw5tusq-t01-f3762b.json /tmp/cpt-958e59a8/launch-K8Q8dA /tmp/cpt-958e59a8\n94705 94698 94705 Tue Oct 6 15:09:49 2026 /opt/ubrew/bin/magmux --headless --no-status --id c94698-muw5tusq-t01-f3762b --sock-dir /tmp/cpt-958e59a8 -e . '/tmp/cpt-958e59a8/launch-l6DJCS/pane-launch.sh'\n94706 94705 94706 Tue Oct 6 15:09:49 2026 /opt/u/.bun/bin/bun run /opt/u/mag/claudish/.claude/worktrees/claudish-mcp-magmux/packages/cli/src/pane/test-helpers/fake-interactive-child.ts -i --model contract-fake-model -y --quiet --session-id 511fd190-5ff6-4692-bcaf-e2879c6b9469 --add-dir /tmp/cpt-958e59a8/launch-K8Q8dA"+}