diff --git a/doc/plans/2026-11-22-antigravity-qualification.md b/doc/plans/2026-11-22-antigravity-qualification.md index ec1f7c659ce..e4345481acc 100644 --- a/doc/plans/2026-11-22-antigravity-qualification.md +++ b/doc/plans/2026-11-22-antigravity-qualification.md @@ -410,3 +410,14 @@ profile stays **pending** until an operator grants the flip. Facts above: local darwin-arm64 instance at commit 438ae60922, 2026-11-25, Google subscription sign-in. + +### Re-check of the swarm fixes (local, 2026-11-25, commit cd8bcfba16) + +| Gate | Result | +| --- | --- | +| Usage on Stop (Flash) | Passed live: the stopped run recorded 36,910 in / 869 out tokens | +| Usage on a killed CLI | Still 0 live: CLI 1.5.15 streams no token counts during a swarm prompt and reports them only when the turn ends, so a killed run has nothing to keep. Documented; not estimated | +| Kill text and automatic recovery | Passed live: the failure says the CLI exited and files stay in the task folder, with no Retry; Paperclip recovered with a fresh swarm and the task finished | +| Settings receipt in the run record | Passed live: one provider notice with requested and confirmed model, thinking level, mode, channel, CLI version and account match | +| Thread text | Passed live: no terminal hint, no stray ".", no local paths or `file://` links, no mention of the swarm rules | +| Helper processes after a killed CLI | Gap found live: helper shell commands lead their own process groups, outlived the killed CLI by about 14 s, one wrote a file 14 s after the kill, and the failure was recorded only when they exited (they held the CLI's output pipe). Fixed in a later pull request: the swarm records every process the CLI starts and stops them all before a failed or stopped turn is reported and on shutdown, and a lost CLI is detected on exit. Proven with the fake CLI (kill, Stop, shutdown; an unrelated process survives); live proof pending | diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.test.ts new file mode 100644 index 00000000000..900a249afac --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.test.ts @@ -0,0 +1,150 @@ +import { spawn } from "node:child_process"; +import { describe, expect, it } from "vitest"; +import { + LineageState, parseProcStat, parsePsTable, readProcessTable, trackAntigravityProcessLineage, + type LineageEntry, type ProcessTableRead, +} from "./antigravity-process-lineage.js"; + +const entry = (pid: number, ppid: number, pgid: number, started: number, extra: Partial = {}): LineageEntry => + ({ pid, ppid, pgid, sid: null, started, zombie: false, ...extra }); +const pids = (observation: { live: LineageEntry[] }) => observation.live.map(item => item.pid).sort((a, b) => a - b); +const self = () => entry(process.pid, 1, process.pid, 1); +const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } }; +/** A tracker whose first read records `member` and whose later reads come from `later`. */ +const trackWith = (member: LineageEntry, later: () => Promise) => { + let reads = 0; + return trackAntigravityProcessLineage(member.pid, { sampleIntervalMs: 60_000, + readTable: async () => (++reads === 1 ? { entries: [self(), member], unreadable: [] } : later()) }); +}; + +describe("Antigravity process lineage", () => { + it("keeps a helper that leads its own group after the CLI dies and it is re-parented, with its children", () => { + const state = new LineageState(100); + // CLI 100 starts helper shell 200 as its own group leader; 200 starts 201. + expect(pids(state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11), entry(201, 200, 200, 12), entry(300, 1, 300, 5)]))).toEqual([100, 200, 201]); + // CLI killed: 200 is re-parented to init; 201 forks 202 after its parent exited. + expect(pids(state.observe([entry(200, 1, 200, 11), entry(202, 1, 200, 13), entry(300, 1, 300, 5)]))).toEqual([200, 202]); + }); + + it("keeps a process in a session a member leads after it left the member's group and its parent exited", () => { + const state = new LineageState(100); + // Helper 200 calls setsid (session and group 200); its wrapper 201 starts a job that moves to group 202. + state.observe([entry(100, 50, 100, 10, { sid: 40 }), entry(200, 100, 200, 11, { sid: 200 }), entry(201, 200, 200, 12, { sid: 200 })]); + // The wrapper exited before the job was ever seen; the job is re-parented to init. + expect(pids(state.observe([entry(200, 100, 200, 11, { sid: 200 }), entry(202, 1, 202, 13, { sid: 200 }), entry(300, 1, 300, 14, { sid: 40 })]))).toEqual([200, 202]); + }); + + it("never claims an unrelated process: same user, earlier start, a reused PID or a reused group id", () => { + const state = new LineageState(100); + state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11)]); + // 200 exits; an unrelated process later reuses PID 200 and leads group 200. + expect(pids(state.observe([entry(100, 50, 100, 10), entry(200, 1, 200, 99), entry(201, 200, 200, 100), entry(400, 50, 400, 9)]))).toEqual([100]); + // A process that started before the CLI is never its child. + expect(pids(state.observe([entry(100, 50, 100, 10), entry(500, 100, 500, 3)]))).toEqual([100]); + }); + + it("drops zombies and a root whose PID now names another process", () => { + const state = new LineageState(100); + state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11)]); + expect(pids(state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11, { zombie: true })]))).toEqual([100]); + expect(pids(state.observe([entry(100, 50, 100, 77)]))).toEqual([]); + }); + + it("keeps a member whose details could not be read unresolved instead of treating it as gone", () => { + const state = new LineageState(100); + state.observe([entry(100, 50, 100, 10), entry(200, 100, 200, 11)]); + expect(state.observe({ entries: [], unreadable: [200] })).toEqual({ live: [], unresolved: [200] }); + expect(state.observe({ entries: [], unreadable: [] })).toEqual({ live: [], unresolved: [] }); + }); + + it("parses macOS ps output: live, zombie and unreadable rows; rejects output that is not a process table", () => { + const read = parsePsTable([ + " 100 1 100 Ss Tue Nov 24 10:00:00 2026", + " 200 100 200 Z Tue Nov 24 10:00:01 2026", + " 300 100 200 S+ garbled", + "", + ].join("\n")); + expect(read.entries).toEqual([ + { pid: 100, ppid: 1, pgid: 100, sid: null, started: Date.UTC(2026, 10, 24, 10, 0, 0), zombie: false }, + { pid: 200, ppid: 100, pgid: 200, sid: null, started: Date.UTC(2026, 10, 24, 10, 0, 1), zombie: true }, + ]); + expect(read.unreadable).toEqual([300]); + expect(parsePsTable("")).toEqual({ entries: [], unreadable: [] }); + expect(() => parsePsTable("PID PPID PGID STAT STARTED\n")).toThrow(/Unexpected/); + }); + + it("parses Linux /proc stat lines, including a command name with spaces and parentheses", () => { + const fields = ["S", "100", "200", "300", ...Array.from({ length: 15 }, () => "0"), "123456", "0"]; + expect(parseProcStat(42, `42 (a (b) c) ${fields.join(" ")}`)).toEqual({ pid: 42, ppid: 100, pgid: 200, sid: 300, started: 123456, zombie: false }); + expect(parseProcStat(42, "42 (x) Z")).toBeNull(); + }); + + it("reads this host's process table, including this process with its parent", async () => { + const table = await readProcessTable(); + const current = table.entries.find(item => item.pid === process.pid); + expect(current).toMatchObject({ ppid: process.ppid, zombie: false }); + expect(Number.isSafeInteger(current?.started)).toBe(true); + }); + + it.each<[string, () => Promise]>([ + ["a failed read", async () => { throw new Error("unavailable"); }], + ["an empty read", async () => ({ entries: [], unreadable: [] })], + ["a read that does not list this process", async () => ({ entries: [entry(4, 1, 4, 1)], unreadable: [] })], + ["a read where the recorded member is unreadable", async () => ({ entries: [self()], unreadable: [999_999] })], + ])("never proves the lineage gone from %s, and a later call tries again", async (_name, bad) => { + let read = bad; + const lineage = trackWith(entry(999_999, 1, 999_999, 2), () => read()); + await new Promise(resolve => setTimeout(resolve, 20)); + await expect(lineage.terminate()).rejects.toThrow(/could not be stopped/); + read = async () => ({ entries: [self()], unreadable: [] }); + await expect(lineage.terminate()).resolves.toBeUndefined(); + }, 10_000); + + it("signals the members it found even when that read was slower than the whole deadline", async () => { + const helper = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + try { + let reads = 0; + const lineage = trackAntigravityProcessLineage(helper.pid, { sampleIntervalMs: 60_000, readTable: async () => { + const table = await readProcessTable(); + if (++reads === 2) await new Promise(resolve => setTimeout(resolve, 1_700)); + return table; + } }); + await new Promise(resolve => setTimeout(resolve, 200)); + await lineage.terminate(); + expect(alive(helper.pid!)).toBe(false); + } finally { try { process.kill(helper.pid!, "SIGKILL"); } catch { /* gone */ } } + }, 10_000); + + it("never signals a recorded PID whose start time no longer matches", async () => { + const unrelated = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + try { + await new Promise(resolve => setTimeout(resolve, 100)); + const real = (await readProcessTable()).entries.find(item => item.pid === unrelated.pid)!; + // The tracker's reads say an older process held this PID; the re-read before the signal disagrees. + let reads = 0; + const older = { ...real, started: real.started - 5_000 }; + const lineage = trackAntigravityProcessLineage(unrelated.pid, { sampleIntervalMs: 60_000, + readTable: async () => ({ entries: [self(), ...(++reads <= 2 ? [older] : [])], unreadable: [] }) }); + await new Promise(resolve => setTimeout(resolve, 20)); + await lineage.terminate(); + expect(alive(unrelated.pid!)).toBe(true); + } finally { try { process.kill(unrelated.pid!, "SIGKILL"); } catch { /* gone */ } } + }); + + it("stops a detached grandchild of a dead root and leaves an unrelated process running", async () => { + const unrelated = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + // The root starts a detached grandchild (its own group) and exits soon after. + const root = spawn(process.execPath, ["-e", `const c = require("node:child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); console.log(c.pid); setTimeout(() => process.exit(0), 300);`], { stdio: ["ignore", "pipe", "ignore"] }); + const lineage = trackAntigravityProcessLineage(root.pid, { sampleIntervalMs: 20 }); + const grandchild = await new Promise(resolve => root.stdout.once("data", chunk => resolve(Number(String(chunk).trim())))); + await new Promise(resolve => root.once("exit", resolve)); + try { + expect(alive(grandchild)).toBe(true); + await lineage.terminate(); + expect(alive(grandchild)).toBe(false); + expect(alive(unrelated.pid!)).toBe(true); + } finally { + for (const pid of [grandchild, unrelated.pid!]) { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } } + } + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.ts new file mode 100644 index 00000000000..ddbe65e6fdf --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-process-lineage.ts @@ -0,0 +1,238 @@ +import { execFile } from "node:child_process"; +import { readdir, readFile } from "node:fs/promises"; + +/** + * Every process the swarm route's `agy acp` launcher and its helpers start, + * recorded while they are still visible, so they can all be stopped when the + * CLI exits for any reason. + * + * The CLI starts each helper shell command as its own process-group leader. + * When the CLI dies those commands are re-parented, so signalling the + * launcher's group (retireAntigravityProcess) does not reach them. + * + * runnerd's LineageTracker (runner-core process_lineage.rs) records the whole + * sidecar's lineage and stops all of it, the sidecar included, when the + * sidecar is torn down. It has no operation for one subtree, and the swarm + * needs this subtree stopped while the sidecar keeps serving the run: before a + * lost, stopped or timed-out swarm turn is reported. This tracker applies + * runnerd's membership rules to the CLI's subtree only: + * - a process belongs when its parent belongs (and started no later than it); + * - or when it is in a group or session a member leads and started no earlier + * than that leader (sessions on Linux; macOS `ps` reports no session id); + * - identity is PID plus start time, re-read immediately before each signal, + * so a reused PID is never signalled; + * - a recorded member whose details cannot be read stays unresolved, and a + * table read that does not list this process is rejected: neither proves + * the lineage gone; + * - membership never depends on a command name, so other `agy` processes of + * the same user are never touched. + */ +export interface LineageEntry { pid: number; ppid: number; pgid: number; sid: number | null; started: number; zombie: boolean } + +/** One read of the process table: readable entries, and PIDs that exist but could not be read. */ +export interface ProcessTableRead { entries: LineageEntry[]; unreadable: number[] } + +export interface LineageObservation { live: LineageEntry[]; unresolved: number[] } + +export class LineageState { + readonly #members = new Map(); + readonly #groups = new Map(); + readonly #sessions = new Map(); + readonly #root: { pid: number; started: number | null }; + + constructor(rootPid: number) { this.#root = { pid: rootPid, started: null }; } + + /** Updates membership from one table read, applied in the order reads were taken. */ + observe(read: ProcessTableRead | readonly LineageEntry[]): LineageObservation { + const { entries, unreadable } = Array.isArray(read) ? { entries: read as readonly LineageEntry[], unreadable: [] as number[] } : read as ProcessTableRead; + const byPid = new Map(entries.map(entry => [entry.pid, entry])); + const unknown = new Set(unreadable); + const root = byPid.get(this.#root.pid); + if (root && !root.zombie && (this.#root.started === null || this.#root.started === root.started)) { + this.#root.started = root.started; + this.#members.set(root.pid, root.started); + } + // A PID that now names a different process is forgotten first, so it can + // never admit that process's children. Members that merely exited are + // forgotten only after admission: a child whose parent exited since the + // last read is still found through that parent's recorded group or session. + for (const records of [this.#members, this.#groups, this.#sessions]) { + for (const [id, started] of records) { + const current = byPid.get(id); + if (current && current.started !== started) records.delete(id); + } + } + const record = (entry: LineageEntry) => { + this.#members.set(entry.pid, entry.started); + if (entry.pgid === entry.pid) this.#groups.set(entry.pid, entry.started); + if (entry.sid === entry.pid) this.#sessions.set(entry.pid, entry.started); + }; + for (let changed = true; changed;) { + changed = false; + for (const entry of entries) { + if (entry.zombie || this.#members.has(entry.pid) || entry.pid <= 1 || entry.pid === process.pid) continue; + const leader = (records: Map, id: number | null) => id !== null && (records.get(id) ?? Infinity) <= entry.started; + if (leader(this.#members, entry.ppid) || leader(this.#groups, entry.pgid) || leader(this.#sessions, entry.sid)) { + record(entry); + changed = true; + } + } + } + const live: LineageEntry[] = []; + const unresolved: number[] = []; + for (const [pid, started] of this.#members) { + const entry = byPid.get(pid); + if (!entry) { + // Its exit is proven only when the PID is absent, not when it is unreadable. + if (unknown.has(pid)) unresolved.push(pid); else this.#members.delete(pid); + continue; + } + if (entry.started !== started || entry.zombie) { this.#members.delete(pid); continue; } + record(entry); + live.push(entry); + } + return { live, unresolved }; + } +} + +/** `/bin/ps -A -o pid=,ppid=,pgid=,stat=,lstart=` output, read with LANG=C and TZ=UTC. */ +export function parsePsTable(output: string): ProcessTableRead { + const entries: LineageEntry[] = []; + const unreadable: number[] = []; + for (const line of output.split("\n")) { + if (!line.trim()) continue; + const [pid, ppid, pgid, stat, ...start] = line.trim().split(/\s+/); + if (!pid || !/^\d+$/.test(pid)) throw new Error("Unexpected process table output"); + const started = start.length === 5 ? Date.parse(`${start.join(" ")} UTC`) : Number.NaN; + if (!/^\d+$/.test(ppid ?? "") || !/^\d+$/.test(pgid ?? "") || !/^[A-Za-z+<>NLsWX-]+$/.test(stat ?? "") || !Number.isFinite(started)) { + unreadable.push(Number(pid)); + continue; + } + entries.push({ pid: Number(pid), ppid: Number(ppid), pgid: Number(pgid), sid: null, started, zombie: stat!.startsWith("Z") }); + } + return { entries, unreadable }; +} + +/** `/proc//stat` content: state ppid pgrp session ... starttime follow the command name. */ +export function parseProcStat(pid: number, stat: string): LineageEntry | null { + const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(" "); + const [ppid, pgid, sid, started] = [fields[1], fields[2], fields[3], fields[19]].map(Number); + if (![ppid, pgid, sid, started].every(Number.isSafeInteger) || !fields[0]) return null; + return { pid, ppid: ppid!, pgid: pgid!, sid: sid!, started: started!, zombie: fields[0] === "Z" || fields[0] === "X" }; +} + +async function readLinuxEntry(pid: number): Promise { + try { return parseProcStat(pid, await readFile(`/proc/${pid}/stat`, "utf8")) ?? "unreadable"; } + catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" || (error as NodeJS.ErrnoException).code === "ESRCH" ? "gone" : "unreadable"; } +} + +function runPs(args: string[]): Promise { + return new Promise((resolve, reject) => execFile("/bin/ps", args, { + encoding: "utf8", timeout: 2_000, maxBuffer: 8 * 1024 * 1024, env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C", TZ: "UTC" }, + }, (error, stdout) => error ? reject(error) : resolve(stdout))); +} + +/** One read of this host's process table: /proc on Linux, /bin/ps on macOS. Numbers only; never arguments or environment. */ +export async function readProcessTable(platform: NodeJS.Platform = process.platform): Promise { + let read: ProcessTableRead; + if (platform === "linux") { + const pids = (await readdir("/proc")).filter(name => /^\d+$/.test(name)).map(Number); + const rows = await Promise.all(pids.map(async pid => ({ pid, row: await readLinuxEntry(pid) }))); + read = { + entries: rows.flatMap(({ row }) => typeof row === "object" ? [row] : []), + unreadable: rows.flatMap(({ pid, row }) => row === "unreadable" ? [pid] : []), + }; + } else if (platform === "darwin") { + read = parsePsTable(await runPs(["-A", "-o", "pid=,ppid=,pgid=,stat=,lstart="])); + } else { + throw new Error("Antigravity process lineage is not supported on this platform"); + } + return assertCompleteRead(read); +} + +/** A read that does not list this very process cannot prove anything absent. */ +function assertCompleteRead(read: ProcessTableRead): ProcessTableRead { + if (!read.entries.some(entry => entry.pid === process.pid)) throw new Error("The process table read is incomplete"); + return read; +} + +/** The current start time of each PID still alive and readable (one `ps` for all of them on macOS). */ +async function currentStarts(pids: readonly number[]): Promise> { + const starts = new Map(); + if (pids.length === 0) return starts; + if (process.platform === "linux") { + for (const pid of pids) { + const row = await readLinuxEntry(pid); + if (typeof row === "object" && !row.zombie) starts.set(pid, row.started); + } + return starts; + } + const output = await runPs(["-o", "pid=,ppid=,pgid=,stat=,lstart=", "-p", pids.join(",")]).catch(() => ""); + let read: ProcessTableRead = { entries: [], unreadable: [] }; + try { read = parsePsTable(output); } catch { /* nothing is signalled */ } + for (const entry of read.entries) if (!entry.zombie) starts.set(entry.pid, entry.started); + return starts; +} + +export interface AntigravityProcessLineage { + /** + * Stops every recorded process that is still alive and proves none remain. + * A proven result is kept; a call after a failed one tries again. + */ + terminate(): Promise; +} + +const DEFAULT_SAMPLE_INTERVAL_MS = 200; +const TERMINATE_DEADLINE_MS = 1_500; + +/** Records the lineage of `rootPid` at once, then every `sampleIntervalMs` until terminate(). */ +export function trackAntigravityProcessLineage(rootPid: number | undefined, options: { + sampleIntervalMs?: number; readTable?: () => Promise; +} = {}): AntigravityProcessLineage { + if (rootPid === undefined || process.platform === "win32") return { terminate: async () => {} }; + const readTable = options.readTable ?? (() => readProcessTable()); + const state = new LineageState(rootPid); + let stopped = false; + let timer: ReturnType | undefined; + // Reads are applied in the order they were taken, never two at once. + let reading: Promise = Promise.resolve(); + const sample = (): Promise => { + const next = reading.catch(() => undefined).then(() => readTable()).then(read => state.observe(assertCompleteRead(read))); + reading = next; + return next; + }; + const loop = () => { + if (stopped) return; + void sample().catch(() => undefined).finally(() => { + if (stopped) return; + timer = setTimeout(loop, options.sampleIntervalMs ?? DEFAULT_SAMPLE_INTERVAL_MS); + timer.unref?.(); + }); + }; + loop(); + let termination: Promise | null = null; + return { + terminate: () => termination ??= (async () => { + stopped = true; + if (timer) clearTimeout(timer); + const deadline = Date.now() + TERMINATE_DEADLINE_MS; + for (let round = 0; ; round++) { + // A fresh read each round: a member that forked meanwhile is found by its parent, group or session. + // A failed read proves nothing, so it is retried until the deadline. + const observed = await sample().catch(() => null); + if (observed && observed.live.length === 0 && observed.unresolved.length === 0) return; + // The first round signals what it found even when that read was slow; later rounds keep the deadline. + if (round > 0 && Date.now() >= deadline) throw new Error("Antigravity helper processes could not be stopped"); + // Re-read the identities just before the signals: a PID reused since the read is never signalled. + const live = observed?.live ?? []; + const starts = await currentStarts(live.map(entry => entry.pid)); + for (const entry of live) { + if (starts.get(entry.pid) !== entry.started) continue; + try { process.kill(entry.pid, "SIGKILL"); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } + } + await new Promise(resolve => setTimeout(resolve, 50)); + } + })().catch(error => { termination = null; throw error; }), + }; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts index 3039be5e7a3..668b0906baa 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts @@ -1,6 +1,7 @@ -import { execFile, type ChildProcessWithoutNullStreams } from "node:child_process"; +import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { lstat, mkdir, realpath } from "node:fs/promises"; import { isAbsolute, join, resolve } from "node:path"; +import { readProcessTable } from "./antigravity-process-lineage.js"; export async function checkAntigravityPrivateHome(home: string): Promise { if (!isAbsolute(home) || home.includes("\0") || resolve(home) !== home || await realpath(home) !== home) throw new Error("Invalid Antigravity private home"); @@ -44,12 +45,9 @@ export async function retireAntigravityProcess(child: ChildProcessWithoutNullStr else if (code === "EPERM" && process.platform === "darwin") { // Darwin reports EPERM for some groups containing only orphaned // zombies. Read numeric state only; never process arguments/env. - const output = await new Promise((resolve, reject) => execFile("/bin/ps", ["-axo", "pid=,pgid=,stat="], { - encoding: "utf8", timeout: 1_000, maxBuffer: 1024 * 1024, env: { PATH: "/usr/bin:/bin", LANG: "C" }, - }, (error, stdout) => error ? reject(error) : resolve(stdout))); - const rows = output.trim().split("\n").filter(Boolean).map(line => line.trim().split(/\s+/)); - if (rows.some(row => row.length !== 3 || !/^\d+$/.test(row[0]!) || !/^\d+$/.test(row[1]!) || !/^[A-Za-z+<>NLsWX-]+$/.test(row[2]!))) throw new Error("Antigravity process retirement could not be confirmed"); - groupAlive = rows.some(row => Number(row[1]) === child.pid && !row[2]!.startsWith("Z")); + const table = await readProcessTable("darwin").catch(() => null); + if (!table || table.unreadable.length > 0) throw new Error("Antigravity process retirement could not be confirmed"); + groupAlive = table.entries.some(entry => entry.pgid === child.pid && !entry.zombie); } else throw error; } } diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts index 4dbe433b347..6e0555229cf 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts @@ -6,6 +6,7 @@ import { afterEach, describe, expect, it } from "vitest"; import type { AcpRuntimeEvent } from "acpx/runtime"; import { ANTIGRAVITY_SWARM_INSTRUCTIONS, antigravityCliAccountMatch, antigravitySwarmPaperclipTool, openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js"; import { acpxProfileActivity } from "./profile-activity.js"; +import { readProcessTable } from "./antigravity-process-lineage.js"; import { persistedAcpxTurnUsage } from "./usage-accounting.js"; import { antigravityAccountDigest } from "./antigravity-swarm-route.js"; import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; @@ -444,6 +445,97 @@ describe("Antigravity CLI swarm runtime", () => { expect(alive(worker)).toBe(false); }); + describe("helpers that lead their own process groups", () => { + const HELPER_DELAY_MS = 2_500; + const waitFor = async (check: () => boolean, timeoutMs = 5_000) => { + const deadline = Date.now() + timeoutMs; + while (!check()) { if (Date.now() > deadline) throw new Error("timed out"); await new Promise(resolve => setTimeout(resolve, 10)); } + }; + const siblings: number[] = []; + afterEach(() => { for (const pid of siblings.splice(0)) { try { process.kill(pid, "SIGKILL"); } catch { /* gone */ } } }); + + async function startOrphanSwarm(dependencies: Parameters[1] = {}, helperDelayMs = HELPER_DELAY_MS) { + const context = setup("orphan-helpers"); + const spawnChild = context.options.command.spawn; + let cliPid = 0; + (context.options.command as { spawn: typeof spawnChild }).spawn = (args, spawnOptions = {}, lifetime) => { + // setup() builds the fake CLI's environment from process.env at spawn time. + process.env.FAKE_AGY_HELPER_DELAY_MS = String(helperDelayMs); + let child: ReturnType; + try { child = spawnChild(args, spawnOptions, lifetime); } finally { delete process.env.FAKE_AGY_HELPER_DELAY_MS; } + cliPid = child.pid!; + return child; + }; + // An unrelated process of the same OS user, not started by this run's CLI. + const sibling = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { detached: true, stdio: "ignore" }); + siblings.push(sibling.pid!); + const runtime = await openAntigravitySwarmRuntime(context.options, { lineageSampleIntervalMs: 20, cancelGraceMs: 500, ...dependencies }); + const turn = runtime.startTurn({ text: envelope(SWARM_REQUEST), requestId: "run-1:turn-1" }); + void (async () => { for await (const _event of turn.events) { /* drain */ } })(); + await waitFor(() => existsSync(context.workerPidFile) && readFileSync(context.workerPidFile, "utf8").length > 0); + const helper = Number(readFileSync(context.workerPidFile, "utf8")); + siblings.push(helper); // cleaned up after the test if it ever survives + // Let the lineage record the helper while the CLI still runs. + await new Promise(resolve => setTimeout(resolve, 150)); + expect(alive(helper)).toBe(true); + return { ...context, runtime, turn, helper, sibling: sibling.pid!, cliPid, late: join(context.cwd, "late.txt") }; + } + const settledAfterHelperDeadline = () => new Promise(resolve => setTimeout(resolve, HELPER_DELAY_MS + 500)); + + it("stops them before reporting a killed CLI, without waiting on the pipe they hold, and leaves other processes alone", async () => { + const run = await startOrphanSwarm(); + process.kill(run.cliPid, "SIGKILL"); + const result = await run.turn.result; + // The helper is already gone when the failure is reported. + expect(alive(run.helper)).toBe(false); + expect(result).toMatchObject({ status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST", retryable: true } }); + await run.runtime.close({ reason: "done" }); + await settledAfterHelperDeadline(); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }); + + it("does not report a recoverable failure while it cannot prove the helpers stopped, and stops them on a later close", async () => { + let tableReadable = true; + const run = await startOrphanSwarm({ readProcessTable: async () => { + if (!tableReadable) throw new Error("process table unavailable"); + return readProcessTable(); + } }, 60_000); + tableReadable = false; + process.kill(run.cliPid, "SIGKILL"); + expect(await run.turn.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_FAILED", retryable: false, + message: expect.stringMatching(/could not confirm that all of its helpers stopped/) } }); + // The helper outlives the failed cleanup, so the later close is what stops it. + expect(alive(run.helper)).toBe(true); + tableReadable = true; + await run.runtime.close({ reason: "done" }); + expect(alive(run.helper)).toBe(false); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }, 20_000); + + it("stops them on Stop before the stopped turn is reported", async () => { + const run = await startOrphanSwarm(); + await run.turn.cancel({ reason: "Stop" }); + expect(await run.turn.result).toMatchObject({ status: "cancelled" }); + expect(alive(run.helper)).toBe(false); + await run.runtime.close({ reason: "done" }); + await settledAfterHelperDeadline(); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }); + + it("stops them when the runner shuts the runtime down mid-swarm", async () => { + const run = await startOrphanSwarm(); + await run.runtime.close({ reason: "shutdown" }); + expect(alive(run.helper)).toBe(false); + expect(alive(run.cliPid)).toBe(false); + await settledAfterHelperDeadline(); + expect(existsSync(run.late)).toBe(false); + expect(alive(run.sibling)).toBe(true); + }); + }); + const trackPid = (options: AcpxRuntimePortOpenOptions) => { const tracked = { pid: 0 }; const spawnChild = options.command.spawn; diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts index f39bdd99a19..4c89d8e28f5 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -5,6 +5,7 @@ import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime"; import { userInfo } from "node:os"; import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js"; import { retireAntigravityProcess } from "./antigravity-process.js"; +import { trackAntigravityProcessLineage, type ProcessTableRead } from "./antigravity-process-lineage.js"; import { antigravityOutsideChange } from "./antigravity-swarm-paths.js"; import { antigravityAccountDigest, antigravitySwarmChannelLabel, antigravitySwarmLogFile } from "./antigravity-swarm-route.js"; import { @@ -49,6 +50,9 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 60_000; const DEFAULT_HELPER_WAIT_TIMEOUT_MS = 20 * 60_000; const DEFAULT_CANCEL_GRACE_MS = 5_000; const READBACK_TIMEOUT_MS = 5_000; +const EXIT_OUTPUT_GRACE_MS = 200; +const RETIREMENT_ATTEMPTS = 3; +const CLEANUP_UNPROVEN_MESSAGE = "The swarm stopped, but Paperclip could not confirm that all of its helpers stopped, so it did not continue the task on its own. Files the helpers wrote stay in the task folder. Check them before you send /swarm again."; const SNAPSHOT_LIMIT = 20_000; const SKIPPED_DIRECTORIES = new Set([".git", "node_modules", ".venv", "__pycache__"]); // The CLI's sandbox refusing a helper's change outside the task folder. A denial @@ -69,6 +73,10 @@ export interface AntigravitySwarmRuntimeDependencies { /** Test seam: runs at every await point between launch and settle. */ onStage?: (stage: AntigravitySwarmStage) => void | Promise; awaitProviderOwnership?: (child: ChildProcess) => Promise; + /** Test seam: how often the CLI's process lineage is recorded. */ + lineageSampleIntervalMs?: number; + /** Test seam: reads the host's process table for the lineage. */ + readProcessTable?: () => Promise; } type Json = Record; @@ -106,7 +114,14 @@ class Connection { onLost: () => void = () => {}; constructor(readonly child: ChildProcessWithoutNullStreams) { - this.exited = new Promise(resolve => child.once("close", () => resolve())); + // Exit, not close: helpers the CLI started inherit its output pipe and can + // hold it open long after the CLI died. Output already written is read for + // a short moment after exit; the lost CLI cannot answer anything later. + this.exited = new Promise(resolve => child.once("exit", () => { + if (child.stdout.readableEnded || child.stdout.destroyed) { resolve(); return; } + const timer = setTimeout(resolve, EXIT_OUTPUT_GRACE_MS); + child.stdout.once("close", () => { clearTimeout(timer); resolve(); }); + })); child.stdout.setEncoding("utf8"); child.stdout.on("data", (chunk: string) => { this.#buffer += chunk; @@ -366,8 +381,15 @@ export async function openAntigravitySwarmRuntime( ? { credentialFenceFds: options.credentialFenceFds, activateCredentialFenceOwner: options.activateCredentialFenceOwner } : undefined; const child = options.command.spawn([], { cwd: options.cwd, env: { ...options.launchEnvironment } }, lifetime) as ChildProcessWithoutNullStreams; const connection = new Connection(child); + // Helpers lead their own process groups, so stopping the launcher's group is + // not enough: everything the CLI started is recorded while it runs and is + // stopped with it (see antigravity-process-lineage.ts). + const lineage = trackAntigravityProcessLineage(child.pid, { sampleIntervalMs: dependencies.lineageSampleIntervalMs, readTable: dependencies.readProcessTable }); let retirement: Promise | null = null; - const retire = () => retirement ??= retireAntigravityProcess(child, connection.exited); + // Only a proven retirement is kept: after a failure, the next call tries again. + const retire = () => retirement ??= retireAntigravityProcess(child, connection.exited) + .finally(() => lineage.terminate()) + .catch((error: unknown) => { retirement = null; throw error; }); let updateListener: ((params: Json) => void) | null = null; let readback: (() => void) | null = null; @@ -724,7 +746,19 @@ export async function openAntigravitySwarmRuntime( active = turn; const onAbort = () => { void turn.cancel(); }; input.signal?.addEventListener("abort", onAbort, { once: true }); - turn.result = runTurn(input, events, markStarted).finally(() => { + // A swarm turn is the port's only turn. Unless it completed, the CLI and + // every process it started are stopped before the outcome is reported, so + // nothing keeps writing in the task folder and recovery never races them. + turn.result = runTurn(input, events, markStarted).then(async result => { + if (result.status === "completed") return result; + for (let attempt = 1; ; attempt++) { + try { await retire(); return result; } catch { + // Without proof that every helper stopped, Paperclip must not continue + // the task on its own in the same folder: report a failure it does not recover. + if (attempt >= RETIREMENT_ATTEMPTS) return failed("ANTIGRAVITY_SWARM_FAILED", CLEANUP_UNPROVEN_MESSAGE); + } + } + }).finally(() => { markStarted(); events.end(); input.signal?.removeEventListener("abort", onAbort); diff --git a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs index 4566aac14b8..18eb3b9a5cf 100644 --- a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs +++ b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs @@ -12,6 +12,10 @@ // cancel helpers keep running (a real child process) until session/cancel; the CLI // streams a token count, then answers the stopped prompt with its usage so far // die the CLI streams a token count, then exits in the middle of the swarm +// orphan-helpers a helper runs as its own process-group leader holding the CLI's output +// pipe (as the real CLI's helper shells do) and writes late.txt in the +// workspace after FAKE_AGY_HELPER_DELAY_MS; the CLI never stops it itself. +// The test kills the CLI, stops the turn or closes the runtime. // refusal the provider refusal arrives as ordinary text with end_turn // quota the 429 quota refusal, as seen live on 2026-11-24 // wrong-version | no-auto | wrong-mode | wrong-model receipt mismatches @@ -185,6 +189,14 @@ async function prompt(id, params) { } // The terminal hint arrives in pieces, as recorded live: the hint complete without its period, then the period alone. for (const chunk of ["I have configured and launched the swarm.\n", "\nRun /swarm board (default shortcut alt+s) to open the live board", "."]) say(chunk); + if (scenario === "orphan-helpers") { + const late = join(state.cwd, "late.txt"); + const helper = spawn(process.execPath, ["-e", `setTimeout(() => require("node:fs").writeFileSync(${JSON.stringify(late)}, "late"), ${Number(process.env.FAKE_AGY_HELPER_DELAY_MS ?? 3000)})`], + { detached: true, stdio: ["ignore", "inherit", "inherit"] }); + if (process.env.FAKE_AGY_WORKER_PID_FILE) writeFileSync(process.env.FAKE_AGY_WORKER_PID_FILE, String(helper.pid)); + if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); + return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled", usage: stoppedUsage } }); + } if (scenario === "cancel" || scenario === "die") { update(state.sessionId, { sessionUpdate: "usage_update", used: 52000, size: 1048576, _meta: { usage: streamedUsage } }); // A helper is a real descendant in the CLI's process group.