From f80eab832fb671499e790e39dd0d2081530df36c Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Wed, 23 Sep 2026 12:20:40 -0700 Subject: [PATCH] Harden wake payload cleanup and resumed turn guidance Remove empty remote directories after an ambiguous creation response, without recursively deleting paths whose creation was not acknowledged. Keep resumed turns from reading a previous large wake file after the next wake returns to inline delivery. Cover both transitions and failure paths. Use spawnSync to inspect the intentional Linux E2BIG regression, since execFile can throw synchronously outside its custom promisify wrapper. Validation: adapter typecheck, 479 focused tests, and native Linux CI confirmed the original launch limit. No secrets found in the staged diff. Co-Authored-By: Paperclip --- .../src/acpx-engine/execute.test.ts | 14 ++++++-- .../adapter-utils/src/acpx-engine/execute.ts | 2 +- .../src/wake-payload-env.test.ts | 32 +++++++++++++++---- .../adapter-utils/src/wake-payload-env.ts | 11 +++++-- 4 files changed, 47 insertions(+), 12 deletions(-) diff --git a/packages/adapter-utils/src/acpx-engine/execute.test.ts b/packages/adapter-utils/src/acpx-engine/execute.test.ts index 8c105c8cd24..17911436d7f 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.test.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.test.ts @@ -397,13 +397,18 @@ describe("shared ACPX engine runtime behavior", () => { const config = { agent: "custom", agentCommand: "node ./fake-acp.js", cwd: root, stateDir: path.join(root, "state") }; let sessionParams: unknown; const paths: string[] = []; - for (const marker of ["first", "resumed"]) { - const description = marker + "🙂 complete context ".repeat(40_000); + for (const marker of ["first", "resumed", "small"]) { + const description = marker + "🙂 complete context ".repeat(marker === "small" ? 1 : 40_000); const run = await runExecutor(config, { runtime: sessionParams ? { sessionParams } : {}, context: { taskId: "issue-1", paperclipWake: { issue: { id: "issue-1", identifier: "TEST-1", description } } }, inspectSession: async (input) => { const env = (input.sessionOptions as { env: Record }).env; + if (marker === "small") { + expect(JSON.parse(env.PAPERCLIP_WAKE_PAYLOAD_JSON!).issue.description).toBe(description); + expect(env.PAPERCLIP_WAKE_PAYLOAD_PATH).toBeUndefined(); + return; + } expect(env.PAPERCLIP_WAKE_PAYLOAD_JSON).toBeUndefined(); const filePath = env.PAPERCLIP_WAKE_PAYLOAD_PATH!; paths.push(filePath); @@ -411,6 +416,11 @@ describe("shared ACPX engine runtime behavior", () => { }, }); sessionParams = run.result.sessionParams; + if (marker === "small") { + expect(String(run.meta[0]?.prompt)).toContain("do not read a previous turn's wake payload file"); + for (const filePath of paths) expect(String(run.meta[0]?.prompt)).not.toContain(filePath); + continue; + } expect(String(run.meta[0]?.prompt)).toContain(JSON.stringify(paths.at(-1))); expect(String(run.meta[0]?.prompt)).toContain("takes precedence over any older wake environment"); await expect(fs.stat(paths.at(-1)!)).rejects.toMatchObject({ code: "ENOENT" }); diff --git a/packages/adapter-utils/src/acpx-engine/execute.ts b/packages/adapter-utils/src/acpx-engine/execute.ts index 8a3137e9cd1..6f2100a486d 100644 --- a/packages/adapter-utils/src/acpx-engine/execute.ts +++ b/packages/adapter-utils/src/acpx-engine/execute.ts @@ -3018,7 +3018,7 @@ async function buildPrompt(ctx: AdapterExecutionContext, resumedSession: boolean : renderTemplate(promptTemplate, templateData); const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim(); const paperclipEnvNote = externalChatTurn ? "" : renderPaperclipEnvNote(env); - const wakePayloadFileNote = externalChatTurn ? "" : renderWakePayloadFileNote(env); + const wakePayloadFileNote = externalChatTurn ? "" : renderWakePayloadFileNote(env, resumedSession); const apiAccessNote = externalChatTurn ? "" : renderApiAccessNote(env); const prompt = joinPromptSections([ promptInstructionsPrefix, diff --git a/packages/adapter-utils/src/wake-payload-env.test.ts b/packages/adapter-utils/src/wake-payload-env.test.ts index ca4e5bfa009..98cf40d07e3 100644 --- a/packages/adapter-utils/src/wake-payload-env.test.ts +++ b/packages/adapter-utils/src/wake-payload-env.test.ts @@ -1,4 +1,4 @@ -import { execFile } from "node:child_process"; +import { execFile, spawnSync } from "node:child_process"; import { createHash } from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; @@ -72,9 +72,11 @@ describe("lossless wake payload transport", () => { await expect(fs.stat(path.dirname(received.path))).rejects.toMatchObject({ code: "ENOENT" }); }); - it.skipIf(process.platform !== "linux")("reproduces Linux E2BIG when the original payload is used as an env entry", async () => { - await expect(exec(process.execPath, ["-e", ""], { env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload } })) - .rejects.toMatchObject({ code: "E2BIG" }); + it.skipIf(process.platform !== "linux")("reproduces Linux E2BIG when the original payload is used as an env entry", () => { + // execFile's custom promisify wrapper can throw synchronously on E2BIG. + // spawnSync exposes the native launch error without that Promise boundary. + const result = spawnSync(process.execPath, ["-e", ""], { env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload } }); + expect(result.error).toMatchObject({ code: "E2BIG" }); }); it("cleans up when the child cannot start", async () => { @@ -106,11 +108,13 @@ describe("lossless wake payload transport", () => { }); it("cleans up after a timeout", async () => { - const result = await runChildProcess("timeout-wake", process.execPath, ["-e", "console.log(process.env.PAPERCLIP_WAKE_PAYLOAD_PATH); setInterval(() => {}, 1000)"], { + const mkdtemp = vi.spyOn(fs, "mkdtemp"); + const result = await runChildProcess("timeout-wake", process.execPath, ["-e", "setInterval(() => {}, 1000)"], { cwd: os.tmpdir(), env: { PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, timeoutSec: 0.2, graceSec: 1, onLog: async () => {}, }); expect(result.timedOut).toBe(true); - await expect(fs.stat(path.dirname(result.stdout.trim()))).rejects.toMatchObject({ code: "ENOENT" }); + const directory = await mkdtemp.mock.results[0]!.value; + await expect(fs.stat(directory)).rejects.toMatchObject({ code: "ENOENT" }); }); it("delivers exact bytes through bounded remote commands and cleans up after the remote child", async () => { @@ -151,6 +155,22 @@ describe("lossless wake payload transport", () => { await expect(fs.stat(directory)).rejects.toMatchObject({ code: "ENOENT" }); }); + it.each([false, true])("safely cleans up an ambiguous directory creation failure (occupied=%s)", async (occupied) => { + let directory = ""; + await expect(prepareWakePayloadEnv({ PAPERCLIP_WAKE_PAYLOAD_JSON: payload }, async (script) => { + if (script.startsWith("umask 077 && mkdir")) { + directory = script.match(/'(\/tmp\/paperclip-wake-[^']+)'/)![1]!; + cleanup.push(() => fs.rm(directory, { recursive: true, force: true })); + await fs.mkdir(directory, { mode: 0o700 }); + if (occupied) await fs.writeFile(path.join(directory, "other-owner"), "preserve this"); + throw new Error(occupied ? "directory exists" : "acknowledgement lost after mkdir"); + } + return (await exec("sh", ["-c", script])).stdout; + })).rejects.toThrow("Could not create the private wake payload directory."); + if (occupied) expect(await fs.readFile(path.join(directory, "other-owner"), "utf8")).toBe("preserve this"); + else await expect(fs.stat(directory)).rejects.toMatchObject({ code: "ENOENT" }); + }); + it("rejects configured file paths and keeps wake contents out of invocation logs", () => { expect(isForbiddenConfigEnvKey("PAPERCLIP_WAKE_PAYLOAD_PATH")).toBe(true); const logged = redactEnvForLogs({ PAPERCLIP_WAKE_PAYLOAD_JSON: payload }); diff --git a/packages/adapter-utils/src/wake-payload-env.ts b/packages/adapter-utils/src/wake-payload-env.ts index 029c06fc9a6..2a6382d831f 100644 --- a/packages/adapter-utils/src/wake-payload-env.ts +++ b/packages/adapter-utils/src/wake-payload-env.ts @@ -47,10 +47,13 @@ export async function prepareWakePayloadEnv( if (remoteCommand) { directory = `/tmp/paperclip-wake-${randomUUID()}`; filePath = `${directory}/payload.json`; - // Do not remove a pre-existing path when exclusive creation fails. + // A provider can lose the acknowledgement after mkdir succeeds. On that + // ambiguous path only remove an empty directory: never recursively remove + // a pre-existing path whose exclusive creation was not acknowledged. try { await remoteCommand(`umask 077 && mkdir -m 700 ${quote(directory)}`); } catch { + await remoteCommand(`rmdir -- ${quote(directory)}`).catch(() => {}); throw new Error("Could not create the private wake payload directory."); } cleanup = async () => { await remoteCommand(`rm -rf -- ${quote(directory)}`); }; @@ -87,8 +90,10 @@ export async function prepareWakePayloadEnv( return { env, filePath, cleanup }; } -export function renderWakePayloadFileNote(env: Record): string { +export function renderWakePayloadFileNote(env: Record, resumedSession = false): string { const filePath = env[PATH_KEY]; - if (!filePath) return ""; + if (!filePath) return resumedSession + ? "Use the current wake context in this prompt. A resumed process may retain wake environment variables from an earlier turn; do not read a previous turn's wake payload file." + : ""; return `The complete structured wake payload for this turn is in ${JSON.stringify(filePath)}. Read this JSON file if you need the structured wake context. This turn's path takes precedence over any older wake environment retained by a resumed session. The file is removed when this turn ends.`; }