fix(antigravity): the CLI's own state directory is not a swarm escape

A real swarm whose coordinator loads the swarm_pane skill writes its plan
with write_file to <gemini-dir>/antigravity-cli/brain/<session>/
.system_generated/swarm/plan.json, inside the private state directory
Paperclip gives the CLI. The outside-change guard treated that as a write
outside the task folder and stopped the swarm (3 of 7 recorded turns).

The guard now exempts exactly this run's --gemini-dir, resolved through
symlinks and `..`, for file tools and shell writes alike. A sibling of it,
a `..` escape, a symlink out of it and the real ~/.gemini still stop the
swarm; the fake CLI covers the plan turn and each negative.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 13:21:08 -06:00
1 parent 3d4cf276fa
commit 4f26416e1c
6 files changed
+144 -9

No files matched your search

@@ -9,6 +9,12 @@ const workspace = join(root, "task");
const home = join(root, "home");
mkdirSync(workspace); mkdirSync(home);
symlinkSync(home, join(workspace, "to-home"));
// The CLI's private --gemini-dir for this run, as Paperclip lays it out (<agent home>/antigravity-cli).
const stateDirectory = join(root, "agent-home", "antigravity-cli");
const SESSION = "9c3e4522-32a6-436f-94dd-427b32a6d896";
mkdirSync(join(stateDirectory, "antigravity-cli", "brain", SESSION), { recursive: true });
mkdirSync(`${stateDirectory}-evil`);
symlinkSync(home, join(stateDirectory, "to-home"));
afterAll(() => rmSync(root, { recursive: true, force: true }));
const shell = (command: string) => ({ sessionUpdate: "tool_call", kind: "execute", name: "run_command", args: { CommandLine: command } });
@@ -63,3 +69,52 @@ describe("changes outside the task folder in visible tool calls", () => {
expect(antigravityOutsideChange({ sessionUpdate: "agent_message_chunk", content: { text: "write /etc/x" } }, workspace, home)).toBeNull();
});
});
/**
* The plan write recorded from a real CLI 1.5.15 swarm turn whose coordinator
* loaded the `swarm_pane` skill (2026-11-24, run1): `write_file` into the CLI's
* own state under `--gemini-dir`. Only the paths are rewritten to this test's folders.
*/
const PLAN = JSON.stringify({ goal: { title: "Build tiny static unit-converter web page", line: "Write HTML, CSS, JS, and README, then verify everything." },
tasks: { "html-writer": "Write index.html with converter form", verifier: "Verify files, links, and JS logic", monitor: "Watch swarm for stalls" },
threads: [{ id: "t-page", title: "Unit-converter page files", goal: "Create index.html in the workspace.", tasks: ["html-writer"] }] }, null, 2);
const planPath = join(stateDirectory, "antigravity-cli", "brain", SESSION, ".system_generated", "swarm", "plan.json");
const planWrite = (path: string, sessionUpdate = "tool_call") => ({
sessionUpdate, toolCallId: "call_13884031054897948910", name: "write_file", status: sessionUpdate === "tool_call" ? "in_progress" : "completed", kind: "edit",
title: `File ${path}`, locations: [{ path }], args: { Content: PLAN, Overwrite: true, Path: path },
...(sessionUpdate === "tool_call" ? {} : { rawOutput: {}, content: [{ type: "diff", path, newText: PLAN }] }),
});
describe("the CLI's own private state directory for this run", () => {
it("is not a workspace escape: the swarm_pane plan write from a real swarm turn", () => {
expect(antigravityOutsideChange(planWrite(planPath), workspace, home, stateDirectory)).toBeNull();
expect(antigravityOutsideChange(planWrite(planPath, "tool_call_update"), workspace, home, stateDirectory)).toBeNull();
// The CLI titles it relative to the task folder; a relative path resolves the same way.
expect(antigravityOutsideChange(edit(`../agent-home/antigravity-cli/antigravity-cli/brain/${SESSION}/notes.md`), workspace, home, stateDirectory)).toBeNull();
expect(antigravityOutsideChange(shell(`printf x > ${join(stateDirectory, "antigravity-cli", "brain", SESSION, "board.jsonl")}`), workspace, home, stateDirectory)).toBeNull();
expect(antigravityOutsideChange(edit(stateDirectory), workspace, home, stateDirectory)).toBeNull();
});
it("is exempt only when the runtime names it for this run", () => {
expect(antigravityOutsideChange(planWrite(planPath), workspace, home)).toBe(planPath);
expect(antigravityOutsideChange(planWrite(planPath), workspace, home, null)).toBe(planPath);
});
it.each<[string, string]>([
["a sibling whose name starts with the state directory's", join(`${stateDirectory}-evil`, "plan.json")],
["a .. escape out of it", `${stateDirectory}/antigravity-cli/brain/../../../escape.json`],
["its parent", join(stateDirectory, "..", "plan.json")],
["a symlink inside it that points outside", join(stateDirectory, "to-home", "plan.json")],
["the user's real ~/.gemini", `~/.gemini/antigravity-cli/brain/${SESSION}/.system_generated/swarm/plan.json`],
])("still stops a change in %s", (_name, path) => {
expect(antigravityOutsideChange(planWrite(path), workspace, home, stateDirectory)).toBe(path);
expect(antigravityOutsideChange(shell(`printf x > '${path}'`), workspace, home, stateDirectory)).toBe(path);
});
it("is ignored when it would cover the home or the whole disk", () => {
expect(antigravityOutsideChange(edit("~/notes.txt"), workspace, home, home)).toBe("~/notes.txt");
expect(antigravityOutsideChange(edit("~/notes.txt"), workspace, home, root)).toBe("~/notes.txt");
expect(antigravityOutsideChange(edit("/etc/x.txt"), workspace, home, "/")).toBe("/etc/x.txt");
expect(antigravityOutsideChange(edit("/etc/x.txt"), workspace, home, "relative/dir")).toBe("/etc/x.txt");
});
});
@@ -130,8 +130,25 @@ export function shellWriteTargets(command: string): string[] {
return targets.filter(target => !/\$(?!\{?HOME\}?(?:\/|$))/.test(target));
}
/** The first path outside the task folder that a visible tool call would change, or null. */
export function antigravityOutsideChange(update: unknown, workspace: string, home: string): string | null {
/**
* The CLI's own private state directory (`--gemini-dir`) for this run, resolved
* through symlinks, or null when it must not be exempt: not given, relative, the
* filesystem root, or one that holds the home.
*/
function privateStateRoot(directory: string | null | undefined, home: string): string | null {
if (!directory || !isAbsolute(directory)) return null;
const real = realResolved(resolve(directory));
if (dirname(real) === real || !outside(realResolved(resolve(home)), real)) return null;
return real;
}
/**
* The first path outside the task folder that a visible tool call would change, or null.
* Changes inside `privateStateDirectory`, the `--gemini-dir` Paperclip gave the CLI for
* this run, are the CLI's own bookkeeping (the swarm_pane skill writes its plan there)
* and are not escapes. Paths are compared after resolving `..` and symlinks.
*/
export function antigravityOutsideChange(update: unknown, workspace: string, home: string, privateStateDirectory?: string | null): string | null {
const value = record(update);
if (value.sessionUpdate !== "tool_call" && value.sessionUpdate !== "tool_call_update") return null;
const kind = String(value.kind ?? "");
@@ -149,9 +166,10 @@ export function antigravityOutsideChange(update: unknown, workspace: string, hom
}
let root = workspace;
try { root = realpathSync(workspace); } catch { /* keep the given path */ }
const stateRoot = privateStateRoot(privateStateDirectory, home);
for (const candidate of candidates) {
const resolved = expand(candidate, workspace, home);
if (resolved && outside(resolved, root)) return candidate;
if (resolved && outside(resolved, root) && (stateRoot === null || outside(resolved, stateRoot))) return candidate;
}
return null;
}
@@ -19,16 +19,19 @@ function setup(scenario: string, overrides: Partial<AcpxRuntimePortOpenOptions>
const workerPidFile = join(root, "worker.pid");
const cwd = join(root, "workspace");
mkdirSync(cwd);
// The run's private --gemini-dir, laid out as Paperclip does: <agent home>/antigravity-cli.
const geminiDirectory = join(root, "agent-home", "antigravity-cli");
mkdirSync(geminiDirectory, { recursive: true });
const options = {
command: {
spawn: (_args: readonly string[] = [], spawnOptions: Record<string, unknown> = {}) => spawn(process.execPath, [FIXTURE], {
spawn: (_args: readonly string[] = [], spawnOptions: Record<string, unknown> = {}) => spawn(process.execPath, [FIXTURE, "--gemini-dir", geminiDirectory], {
...spawnOptions, detached: true, stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, FAKE_AGY_SCENARIO: scenario, FAKE_AGY_LOG: log, FAKE_AGY_WORKER_PID_FILE: workerPidFile },
}),
close: async () => {},
},
profile: { agent: "antigravity", reportedModelId: "gemini-3.8-flash-low", qualificationModel: "gemini-3.8-flash-low" },
cwd, stateDirectory: root, providerSessionKey: "key", permissionMode: "approve-reads", mode: "swarm",
cwd, stateDirectory: root, antigravityStateDirectory: geminiDirectory, providerSessionKey: "key", permissionMode: "approve-reads", mode: "swarm",
permissionPolicy: {}, launchEnvironment: {}, credentialFenceFds: null, activateCredentialFenceOwner: null,
systemInstructions: "Paperclip instructions",
mcpServers: [{ name: "paperclip", url: "http://127.0.0.1:9/mcp", bearerToken: "bridge-secret", runnerOwned: true }],
@@ -36,7 +39,7 @@ function setup(scenario: string, overrides: Partial<AcpxRuntimePortOpenOptions>
...overrides,
} as unknown as AcpxRuntimePortOpenOptions;
const clientMessages = () => existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)) : [];
return { root, cwd, options, clientMessages, workerPidFile };
return { root, cwd, geminiDirectory, options, clientMessages, workerPidFile };
}
async function runTurn(scenario: string, extra: { helperWaitTimeoutMs?: number; onEvent?: (event: AcpRuntimeEvent, cancel: () => Promise<void>) => void } = {}) {
@@ -167,6 +170,19 @@ describe("Antigravity CLI swarm runtime", () => {
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE", message: expect.stringMatching(/outside the task folder/) } });
});
it("keeps running when the coordinator writes its swarm_pane plan into its own private state directory", async () => {
const run = await runTurn("plan");
expect(run.result).toMatchObject({ status: "completed" });
expect(readFileSync(join(run.cwd, "a.txt"), "utf8")).toBe("A");
const plan = join(run.geminiDirectory, "antigravity-cli", "brain", "e6536314-e108-4ecd-a0cf-efa59061510d", ".system_generated", "swarm", "plan.json");
expect(JSON.parse(readFileSync(plan, "utf8")).tasks["writer-a"]).toBe("Write a.txt");
});
it.each(["plan-sibling", "plan-dotdot", "plan-symlink", "plan-home"])("still stops a plan write that leaves the private state directory: %s", async scenario => {
const run = await runTurn(scenario);
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE", message: expect.stringMatching(/outside the task folder/) } });
});
it("allows reading outside the task folder when the change lands inside it", async () => {
const run = await runTurn("shell-read");
expect(run.result).toMatchObject({ status: "completed" });
@@ -423,7 +423,7 @@ export async function openAntigravitySwarmRuntime(
`Swarm stopped: helper ${escaped} was asked to work on its own copy of the task folder, which Paperclip does not allow.`));
return;
}
const outside = antigravityOutsideChange(update, workspace, home);
const outside = antigravityOutsideChange(update, workspace, home, options.antigravityStateDirectory);
if (outside) {
halt(new AntigravitySwarmError("ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE",
`Swarm stopped: it tried to change ${outside}, which is outside the task folder.`));
@@ -207,6 +207,8 @@ export interface AcpxRuntimePortOpenOptions {
profile: QualifiedAcpxProfile;
cwd: string;
stateDirectory: string;
/** The Antigravity CLI's private `--gemini-dir` for this run (swarm route only). */
antigravityStateDirectory?: string;
providerSessionKey: string;
permissionMode: NativeAcpxPermissionMode;
readOnly?: boolean;
@@ -723,6 +725,7 @@ export class AcpxRuntimeHost {
profile,
cwd: binding.workspacePath,
stateDirectory: sandbox.stateDirectory,
...(swarmStateDirectory === null ? {} : { antigravityStateDirectory: swarmStateDirectory }),
providerSessionKey: binding.profileSessionKey,
restoringSession: options.expectedIdentity !== undefined,
permissionMode: binding.permissionMode,
@@ -23,12 +23,20 @@
// shell-escape the coordinator runs `printf E > /tmp/...` (the CLI's shell sandbox allows temp dirs)
// shell-read the coordinator reads outside the workspace and copies into it (allowed)
// cautious-brief a helper brief says "Do not create debug.log"; the run is correct
// plan the coordinator loads swarm_pane and writes its plan.json into its own
// --gemini-dir (recorded shape, run1); the run is correct
// plan-sibling | plan-dotdot | plan-symlink | plan-home the same plan write aimed at
// <gemini-dir>-evil, a .. escape out of it, a symlink inside it pointing
// outside, and the real ~/.gemini; never written, the swarm must stop
// FAKE_AGY_LOG (optional) appends every client message, one JSON per line.
import { spawn } from "node:child_process";
import { appendFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { appendFileSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
const scenario = process.env.FAKE_AGY_SCENARIO ?? "success";
// Like the real CLI, private state lives under --gemini-dir (it adds its own antigravity-cli/ inside).
const geminiDirectory = process.argv[process.argv.indexOf("--gemini-dir") + 1];
const log = message => { if (process.env.FAKE_AGY_LOG) appendFileSync(process.env.FAKE_AGY_LOG, `${JSON.stringify(message)}\n`); };
const write = message => process.stdout.write(`${JSON.stringify(message)}\n`);
const update = (sessionId, value) => write({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: value } });
@@ -59,6 +67,33 @@ const addWriters = async () => {
? "Wait for writer-a and writer-b, then read a.txt and b.txt. Do not create debug.log or any other file. Write docs.google.com links only if v1.2 asks." : "Wait for writer-a and writer-b, then read a.txt and b.txt and report." });
await tool("swarm", { action: "add", name: "monitor", workspace: "inherit", brief: "You are this swarm's stall monitor. Load the swarm_monitor skill and follow it." });
};
const PLAN = `${JSON.stringify({ goal: { title: "Write a.txt and b.txt", line: "Two writers, then verify." },
tasks: { "writer-a": "Write a.txt", "writer-b": "Write b.txt", verifier: "Verify a.txt and b.txt", monitor: "Watch swarm for stalls" },
threads: [{ id: "t-files", title: "Task files", goal: "Create a.txt and b.txt in the workspace.", tasks: ["writer-a", "writer-b"] },
{ id: "t-verify", title: "Verification and swarm health", goal: "Confirm both files.", tasks: ["verifier", "monitor"] }] }, null, 2)}\n`;
const planPath = () => {
const brain = join(geminiDirectory, "antigravity-cli", "brain", state.sessionId);
return {
plan: join(brain, ".system_generated", "swarm", "plan.json"),
"plan-sibling": join(`${geminiDirectory}-evil`, "antigravity-cli", "brain", state.sessionId, "plan.json"),
"plan-dotdot": `${brain}/../../../../escape-plan.json`,
"plan-symlink": join(brain, "link", "plan.json"),
"plan-home": `~/.gemini/antigravity-cli/brain/${state.sessionId}/.system_generated/swarm/plan.json`,
}[scenario];
};
/** The swarm_pane plan write as CLI 1.5.15 reports it: write_file, kind edit, args Content/Overwrite/Path. */
const writePlan = async path => {
const toolCallId = "call_13884031054897948910";
const args = { Content: PLAN, Overwrite: true, Path: path };
const shape = { toolCallId, name: "write_file", kind: "edit", title: `File ${path}`, locations: [{ path }], args };
update(state.sessionId, { sessionUpdate: "tool_call", status: "in_progress", ...shape });
if (scenario !== "plan") { if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); return false; }
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, PLAN);
await sleep(2);
update(state.sessionId, { sessionUpdate: "tool_call_update", status: "completed", ...shape, rawOutput: {}, content: [{ type: "diff", path, newText: PLAN }] });
return true;
};
const writeFiles = () => {
writeFileSync(join(state.cwd, "a.txt"), "A");
writeFileSync(join(state.cwd, "b.txt"), "B");
@@ -96,6 +131,14 @@ async function prompt(id, params) {
}
if (scenario === "escape") { await tool("swarm", { action: "add", name: "writer-a", workspace: "branch", brief: "Write a.txt." }); if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
await addWriters();
if (scenario.startsWith("plan")) {
if (scenario === "plan-symlink") {
const brain = join(geminiDirectory, "antigravity-cli", "brain", state.sessionId);
mkdirSync(brain, { recursive: true });
symlinkSync(tmpdir(), join(brain, "link"));
}
if (!await writePlan(planPath())) return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } });
}
say("I have configured and launched the swarm.\n\nRun /swarm board (default shortcut alt+s) to open the live board.");
if (scenario === "cancel" || scenario === "die") {
// A helper is a real descendant in the CLI's process group.