Skip to content

The open-source app everyone uses to manage agents at work

31.5 KB
Raw Blame
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { createPromptContextFixture } from "@paperclipai/adapter-utils/test-fixtures/prompt-context";

const {
  runChildProcess,
  ensureCommandResolvable,
  resolveCommandForLogs,
  prepareWorkspaceForSshExecution,
  restoreWorkspaceFromSshExecution,
  runSshCommand,
  syncDirectoryToSsh,
  startAdapterExecutionTargetPaperclipBridge,
} = vi.hoisted(() => ({
  runChildProcess: vi.fn(async () => ({
    exitCode: 0,
    signal: null,
    timedOut: false,
    stdout: JSON.stringify({
      type: "turn_end",
      message: {
        role: "assistant",
        content: "done",
        usage: {
          input: 10,
          output: 20,
          cacheRead: 0,
          cost: { total: 0.01 },
        },
      },
      toolResults: [],
    }),
    stderr: "",
    pid: 123,
    startedAt: new Date().toISOString(),
  })),
  ensureCommandResolvable: vi.fn(async () => undefined),
  resolveCommandForLogs: vi.fn(async () => "ssh://[email protected]:2222/remote/workspace :: pi"),
  prepareWorkspaceForSshExecution: vi.fn(async () => ({ gitBacked: false })),
  restoreWorkspaceFromSshExecution: vi.fn(async () => undefined),
  runSshCommand: vi.fn(async () => ({
    stdout: "",
    stderr: "",
    exitCode: 0,
  })),
  syncDirectoryToSsh: vi.fn(async () => undefined),
  startAdapterExecutionTargetPaperclipBridge: vi.fn(async () => ({
    env: {
      PAPERCLIP_API_URL: "http://127.0.0.1:4310",
      PAPERCLIP_API_KEY: "bridge-token",
      PAPERCLIP_API_BRIDGE_MODE: "queue_v1",
    },
    stop: async () => {},
  })),
}));

vi.mock("@paperclipai/adapter-utils/server-utils", async () => {
  const actual = await vi.importActual<typeof import("@paperclipai/adapter-utils/server-utils")>(
    "@paperclipai/adapter-utils/server-utils",
  );
  return {
    ...actual,
    ensureCommandResolvable,
    resolveCommandForLogs,
    runChildProcess,
  };
});

vi.mock("@paperclipai/adapter-utils/ssh", async () => {
  const actual = await vi.importActual<typeof import("@paperclipai/adapter-utils/ssh")>(
    "@paperclipai/adapter-utils/ssh",
  );
  return {
    ...actual,
    prepareWorkspaceForSshExecution,
    restoreWorkspaceFromSshExecution,
    runSshCommand,
    syncDirectoryToSsh,
  };
});

vi.mock("@paperclipai/adapter-utils/execution-target", async () => {
  const actual = await vi.importActual<typeof import("@paperclipai/adapter-utils/execution-target")>(
    "@paperclipai/adapter-utils/execution-target",
  );
  return {
    ...actual,
    startAdapterExecutionTargetPaperclipBridge,
  };
});

vi.mock("./models.js", async () => {
  const actual = await vi.importActual<typeof import("./models.js")>("./models.js");
  return {
    ...actual,
    ensurePiModelConfiguredAndAvailable: vi.fn(async () => [
      { id: "openai/gpt-5.4-mini", label: "openai/gpt-5.4-mini" },
    ]),
  };
});

import { execute } from "./execute.js";

describe("pi remote execution", () => {
  const cleanupDirs: string[] = [];

  afterEach(async () => {
    vi.clearAllMocks();
    while (cleanupDirs.length > 0) {
      const dir = cleanupDirs.pop();
      if (!dir) continue;
      await rm(dir, { recursive: true, force: true }).catch(() => undefined);
    }
  });

  it("prepares the workspace, syncs Pi skills, and restores workspace changes for remote SSH execution", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-"));
    cleanupDirs.push(rootDir);
    const workspaceDir = path.join(rootDir, "workspace");
    const alternateWorkspaceDir = path.join(rootDir, "workspace-other");
    const managedRemoteWorkspace = "/remote/workspace/.paperclip-runtime/runs/run-1/workspace";
    await mkdir(workspaceDir, { recursive: true });
    await mkdir(alternateWorkspaceDir, { recursive: true });

    const result = await execute({
      runId: "run-1",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: null,
        sessionParams: null,
        sessionDisplayId: null,
        taskKey: null,
      },
      config: {
        command: "pi",
        model: "openai/gpt-5.4-mini",
      },
      context: {
        paperclipWorkspace: {
          cwd: workspaceDir,
          source: "project_primary",
        },
        paperclipWorkspaces: [
          {
            workspaceId: "workspace-1",
            cwd: workspaceDir,
            repoUrl: "https://github.com/paperclipai/paperclip.git",
            repoRef: "main",
          },
          {
            workspaceId: "workspace-2",
            cwd: alternateWorkspaceDir,
            repoUrl: "https://github.com/paperclipai/paperclip.git",
            repoRef: "feature/other",
          },
        ],
      },
      executionTransport: {
        remoteExecution: {
          host: "127.0.0.1",
          port: 2222,
          username: "fixture",
          remoteWorkspacePath: "/remote/workspace",
          remoteCwd: "/remote/workspace",
          privateKey: "PRIVATE KEY",
          knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
          strictHostKeyChecking: true,
        },
      },
      onLog: async () => {},
    });

    expect(result.sessionParams).toMatchObject({
      cwd: managedRemoteWorkspace,
      remoteExecution: {
        transport: "ssh",
        host: "127.0.0.1",
        port: 2222,
        username: "fixture",
        remoteCwd: managedRemoteWorkspace,
      },
    });
    expect(String(result.sessionId)).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/`);
    expect(prepareWorkspaceForSshExecution).toHaveBeenCalledTimes(1);
    expect(syncDirectoryToSsh).toHaveBeenCalledTimes(2);
    expect(syncDirectoryToSsh).toHaveBeenCalledWith(expect.objectContaining({
      remoteDir: `${managedRemoteWorkspace}/.paperclip-runtime/pi/skills`,
      followSymlinks: true,
    }));
    expect(runSshCommand).toHaveBeenCalledWith(
      expect.anything(),
      expect.stringContaining(".paperclip-runtime/pi/sessions"),
      expect.anything(),
    );
    const call = runChildProcess.mock.calls[0] as unknown as
      | [string, string, string[], { env: Record<string, string>; remoteExecution?: { remoteCwd: string } | null }]
      | undefined;
    expect(call?.[2]).toContain("--session");
    expect(call?.[2]).toContain("--skill");
    expect(call?.[2]).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/skills`);
    expect(call?.[2]).toContain("--extension");
    expect(call?.[2]).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/attribution/openrouter-attribution.mjs`);
    expect(call?.[3].env.PAPERCLIP_WORKSPACE_CWD).toBe(managedRemoteWorkspace);
    expect(JSON.parse(call?.[3].env.PAPERCLIP_WORKSPACES_JSON ?? "[]")).toEqual([
      {
        workspaceId: "workspace-1",
        cwd: managedRemoteWorkspace,
        repoUrl: "https://github.com/paperclipai/paperclip.git",
        repoRef: "main",
      },
      {
        workspaceId: "workspace-2",
        repoUrl: "https://github.com/paperclipai/paperclip.git",
        repoRef: "feature/other",
      },
    ]);
    expect(call?.[3].env.PAPERCLIP_API_URL).toBe("http://127.0.0.1:4310");
    expect(call?.[3].env.PAPERCLIP_API_BRIDGE_MODE).toBe("queue_v1");
    expect(call?.[3].remoteExecution?.remoteCwd).toBe(managedRemoteWorkspace);
    expect(startAdapterExecutionTargetPaperclipBridge).toHaveBeenCalledTimes(1);
    expect(restoreWorkspaceFromSshExecution).toHaveBeenCalledTimes(1);
  });

  it("ships the managed Pi agent config and repoints PI_CODING_AGENT_DIR when PAPERCLIP_PI_PROVIDERS is set", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-providers-"));
    cleanupDirs.push(rootDir);
    const workspaceDir = path.join(rootDir, "workspace");
    const managedRemoteWorkspace = "/remote/workspace/.paperclip-runtime/runs/run-providers/workspace";
    await mkdir(workspaceDir, { recursive: true });

    const providers = {
      tensorix: {
        baseUrl: "http://gateway.example.svc.cluster.local:8080/anthropic",
        apiKey: "{env:ANTHROPIC_API_KEY}",
        api: "anthropic-messages",
        models: [{ id: "deepseek/deepseek-chat-v3.1", name: "DeepSeek v3.1" }],
      },
    };

    await execute({
      runId: "run-providers",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: null,
        sessionParams: null,
        sessionDisplayId: null,
        taskKey: null,
      },
      config: {
        command: "pi",
        model: "tensorix/deepseek/deepseek-chat-v3.1",
        env: {
          PAPERCLIP_PI_PROVIDERS: JSON.stringify(providers),
          ANTHROPIC_API_KEY: "sk-bf-REALVK",
        },
      },
      context: {
        paperclipWorkspace: {
          cwd: workspaceDir,
          source: "project_primary",
        },
      },
      executionTransport: {
        remoteExecution: {
          host: "127.0.0.1",
          port: 2222,
          username: "fixture",
          remoteWorkspacePath: "/remote/workspace",
          remoteCwd: "/remote/workspace",
          privateKey: "PRIVATE KEY",
          knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
          strictHostKeyChecking: true,
        },
      },
      onLog: async () => {},
    });

    expect(syncDirectoryToSsh).toHaveBeenCalledWith(expect.objectContaining({
      remoteDir: `${managedRemoteWorkspace}/.paperclip-runtime/pi/agentConfig`,
    }));
    const call = runChildProcess.mock.calls[0] as unknown as
      | [string, string, string[], { env: Record<string, string> }]
      | undefined;
    expect(call?.[3].env.PI_CODING_AGENT_DIR).toBe(
      `${managedRemoteWorkspace}/.paperclip-runtime/pi/agentConfig`,
    );
    expect(call?.[2]).toContain("--provider");
    expect(call?.[2]).toContain("tensorix");
    expect(call?.[2]).toContain("--model");
    expect(call?.[2]).toContain("deepseek/deepseek-chat-v3.1");
  });

  it("resumes saved Pi sessions for remote SSH execution only when the identity matches", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-resume-"));
    cleanupDirs.push(rootDir);
    const workspaceDir = path.join(rootDir, "workspace");
    const managedRemoteWorkspace = "/remote/workspace/.paperclip-runtime/runs/run-ssh-resume/workspace";
    await mkdir(workspaceDir, { recursive: true });

    runSshCommand.mockImplementation(async (...args: unknown[]) => {
      const command = String(args[1] ?? "");
      if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
        return {
          stdout: `${JSON.stringify({ type: "session", cwd: managedRemoteWorkspace })}\n`,
          stderr: "",
          exitCode: 0,
        };
      }
      return {
        stdout: "",
        stderr: "",
        exitCode: 0,
      };
    });

    await execute({
      runId: "run-ssh-resume",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: `${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/session-123.jsonl`,
        sessionParams: {
          sessionId: `${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/session-123.jsonl`,
          cwd: managedRemoteWorkspace,
          remoteExecution: {
            transport: "ssh",
            host: "127.0.0.1",
            port: 2222,
            username: "fixture",
            remoteCwd: managedRemoteWorkspace,
          },
        },
        sessionDisplayId: "session-123",
        taskKey: null,
      },
      config: {
        command: "pi",
        model: "openai/gpt-5.4-mini",
      },
      context: {
        paperclipWorkspace: {
          cwd: workspaceDir,
          source: "project_primary",
        },
      },
      executionTransport: {
        remoteExecution: {
          host: "127.0.0.1",
          port: 2222,
          username: "fixture",
          remoteWorkspacePath: "/remote/workspace",
          remoteCwd: "/remote/workspace",
          privateKey: "PRIVATE KEY",
          knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
          strictHostKeyChecking: true,
        },
      },
      onLog: async () => {},
    });

    const call = runChildProcess.mock.calls[0] as unknown as [string, string, string[]] | undefined;
    expect(call?.[2]).toContain("--session");
    expect(call?.[2]).toContain(`${managedRemoteWorkspace}/.paperclip-runtime/pi/sessions/session-123.jsonl`);
  });

  it("starts a fresh remote Pi session when the saved session header cwd points at a different workspace", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-stale-session-"));
    cleanupDirs.push(rootDir);
    const workspaceDir = path.join(rootDir, "workspace");
    await mkdir(workspaceDir, { recursive: true });

    runSshCommand.mockImplementation(async (...args: unknown[]) => {
      const command = String(args[1] ?? "");
      if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
        return {
          stdout: `${JSON.stringify({ type: "session", cwd: "/remote/old-workspace" })}\n`,
          stderr: "",
          exitCode: 0,
        };
      }
      return {
        stdout: "",
        stderr: "",
        exitCode: 0,
      };
    });

    await execute({
      runId: "run-ssh-stale-session",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
        sessionParams: {
          sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
          cwd: "/remote/workspace",
          remoteExecution: {
            transport: "ssh",
            host: "127.0.0.1",
            port: 2222,
            username: "fixture",
            remoteCwd: "/remote/workspace",
          },
        },
        sessionDisplayId: "session-123",
        taskKey: null,
      },
      config: {
        command: "pi",
        model: "openai/gpt-5.4-mini",
      },
      context: {
        paperclipWorkspace: {
          cwd: workspaceDir,
          source: "project_primary",
        },
      },
      executionTransport: {
        remoteExecution: {
          host: "127.0.0.1",
          port: 2222,
          username: "fixture",
          remoteWorkspacePath: "/remote/workspace",
          remoteCwd: "/remote/workspace",
          privateKey: "PRIVATE KEY",
          knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
          strictHostKeyChecking: true,
        },
      },
      onLog: async () => {},
    });

    const managedRemoteWorkspaceFresh = "/remote/workspace/.paperclip-runtime/runs/run-ssh-stale-session/workspace";
    const call = runChildProcess.mock.calls[0] as unknown as [string, string, string[]] | undefined;
    const sessionIndex = call?.[2].indexOf("--session") ?? -1;
    expect(sessionIndex).toBeGreaterThanOrEqual(0);
    const usedSession = sessionIndex >= 0 ? call?.[2][sessionIndex + 1] : null;
    expect(usedSession).toContain(`${managedRemoteWorkspaceFresh}/.paperclip-runtime/pi/sessions/`);
    expect(usedSession).not.toBe("/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl");
  });

  it("starts a fresh remote Pi session when the saved session header is empty or unreadable", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-empty-header-"));
    cleanupDirs.push(rootDir);
    const workspaceDir = path.join(rootDir, "workspace");
    await mkdir(workspaceDir, { recursive: true });

    runSshCommand.mockImplementation(async (...args: unknown[]) => {
      const command = String(args[1] ?? "");
      if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
        return { stdout: "", stderr: "", exitCode: 0 };
      }
      return { stdout: "", stderr: "", exitCode: 0 };
    });

    await execute({
      runId: "run-ssh-empty-header",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
        sessionParams: {
          sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
          cwd: "/remote/workspace",
          remoteExecution: {
            transport: "ssh",
            host: "127.0.0.1",
            port: 2222,
            username: "fixture",
            remoteCwd: "/remote/workspace",
          },
        },
        sessionDisplayId: "session-123",
        taskKey: null,
      },
      config: { command: "pi", model: "openai/gpt-5.4-mini" },
      context: {
        paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
      },
      executionTransport: {
        remoteExecution: {
          host: "127.0.0.1",
          port: 2222,
          username: "fixture",
          remoteWorkspacePath: "/remote/workspace",
          remoteCwd: "/remote/workspace",
          privateKey: "PRIVATE KEY",
          knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
          strictHostKeyChecking: true,
        },
      },
      onLog: async () => {},
    });

    const call = runChildProcess.mock.calls[0] as unknown as [string, string, string[]] | undefined;
    const sessionIndex = call?.[2].indexOf("--session") ?? -1;
    expect(sessionIndex).toBeGreaterThanOrEqual(0);
    const usedSession = sessionIndex >= 0 ? call?.[2][sessionIndex + 1] : null;
    expect(usedSession).not.toBe("/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl");
  });

  it("starts a fresh remote Pi session when the remote head command fails", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-head-failure-"));
    cleanupDirs.push(rootDir);
    const workspaceDir = path.join(rootDir, "workspace");
    await mkdir(workspaceDir, { recursive: true });

    runSshCommand.mockImplementation(async (...args: unknown[]) => {
      const command = String(args[1] ?? "");
      if (command.includes("head -n 1") && command.includes("session-123.jsonl")) {
        throw Object.assign(new Error("ssh: connect failed"), {
          stdout: "",
          stderr: "ssh: connect failed",
          code: "ENOENT",
        });
      }
      return { stdout: "", stderr: "", exitCode: 0 };
    });

    await execute({
      runId: "run-ssh-head-failure",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
        sessionParams: {
          sessionId: "/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl",
          cwd: "/remote/workspace",
          remoteExecution: {
            transport: "ssh",
            host: "127.0.0.1",
            port: 2222,
            username: "fixture",
            remoteCwd: "/remote/workspace",
          },
        },
        sessionDisplayId: "session-123",
        taskKey: null,
      },
      config: { command: "pi", model: "openai/gpt-5.4-mini", bootstrapPromptTemplate: "BOOTSTRAP {{run.id}}" },
      context: {
        ...createPromptContextFixture(),
        paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
      },
      executionTransport: {
        remoteExecution: {
          host: "127.0.0.1",
          port: 2222,
          username: "fixture",
          remoteWorkspacePath: "/remote/workspace",
          remoteCwd: "/remote/workspace",
          privateKey: "PRIVATE KEY",
          knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
          strictHostKeyChecking: true,
        },
      },
      onLog: async () => {},
    });

    const call = runChildProcess.mock.calls[0] as unknown as [string, string, string[]] | undefined;
    const sessionIndex = call?.[2].indexOf("--session") ?? -1;
    expect(sessionIndex).toBeGreaterThanOrEqual(0);
    const usedSession = sessionIndex >= 0 ? call?.[2][sessionIndex + 1] : null;
    expect(usedSession).not.toBe("/remote/workspace/.paperclip-runtime/pi/sessions/session-123.jsonl");
    const prompt = String(call?.[2].at(-1) ?? "");
    expect(prompt).toContain("## Owned assignment");
    expect(prompt).toContain("BOOTSTRAP run-ssh-head-failure");
    expect(prompt).toContain("comment-scope");
  });

  it("delivers the owned assignment and ordered wake comments through Pi's prompt", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-context-ownership-"));
    cleanupDirs.push(rootDir);
    await mkdir(rootDir, { recursive: true });
    const fixture = createPromptContextFixture();
    let deliveredPrompt = "";

    await execute({
      runId: "run-context-ownership",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
      config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
      context: { ...fixture, paperclipWorkspace: { cwd: rootDir, source: "project_primary" } },
      onLog: async () => {},
    } as never);

    const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
    deliveredPrompt = String(call?.[2].at(-1) ?? "");
    expect(deliveredPrompt).toContain(fixture.paperclipTaskMarkdownAssignment);
    expect(deliveredPrompt.indexOf("Append the same ledger entry.")).toBeLessThan(
      deliveredPrompt.lastIndexOf("Append the same ledger entry."),
    );
    expect(deliveredPrompt.indexOf("comment-first")).toBeLessThan(
      deliveredPrompt.indexOf("comment-second"),
    );
    expect(deliveredPrompt.indexOf("comment-second")).toBeLessThan(
      deliveredPrompt.indexOf("comment-scope"),
    );
    expect(deliveredPrompt).toContain("Change the final scope to the launch checklist.");
  });

  it("keeps the default Paperclip policy in the system carrier without duplicating it in user input", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-default-policy-"));
    cleanupDirs.push(rootDir);

    await execute({
      runId: "run-default-policy",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
      config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
      context: {},
      onLog: async () => {},
    } as never);

    const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
    const args = call?.[2] ?? [];
    const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
    const userPrompt = args.at(-1) ?? "";
    expect(systemPrompt).toContain("You are agent agent-1 (Pi Builder).");
    expect(userPrompt).not.toContain("You are agent agent-1 (Pi Builder).");
  });

  it("preserves custom prompt templates in both configured carriers", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-custom-policy-"));
    cleanupDirs.push(rootDir);

    await execute({
      runId: "run-custom-policy",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
      config: {
        command: "pi",
        model: "openai/gpt-5.4-mini",
        cwd: rootDir,
        promptTemplate: "CUSTOM POLICY {{run.id}}",
      },
      context: {},
      onLog: async () => {},
    } as never);

    const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
    const args = call?.[2] ?? [];
    const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
    const userPrompt = args.at(-1) ?? "";
    expect(systemPrompt).toBe("CUSTOM POLICY run-custom-policy");
    expect(userPrompt).toBe("CUSTOM POLICY run-custom-policy");
  });

  it("keeps resumed default identity and connection guidance in the system carrier", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-resumed-policy-"));
    cleanupDirs.push(rootDir);
    const sessionPath = path.join(rootDir, "session.jsonl");
    await writeFile(sessionPath, `${JSON.stringify({ type: "session", cwd: rootDir })}\n`, "utf8");

    await execute({
      runId: "run-resumed-policy",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: sessionPath,
        sessionParams: { sessionId: sessionPath, cwd: rootDir },
        sessionDisplayId: "session-resumed-policy",
        taskKey: null,
      },
      config: { command: "pi", model: "openai/gpt-5.4-mini", cwd: rootDir },
      context: createPromptContextFixture(),
      onLog: async () => {},
    } as never);

    const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
    const args = call?.[2] ?? [];
    const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
    const userPrompt = args.at(-1) ?? "";
    expect(systemPrompt).toContain("You are agent agent-1 (Pi Builder).");
    expect(systemPrompt).toContain("Connection tools:");
    expect(systemPrompt).not.toContain("Execution contract:");
    expect(userPrompt).not.toContain("Execution contract:");
  });

  it("keeps default identity in system input when custom prompt uses loaded instructions", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-instructions-policy-"));
    cleanupDirs.push(rootDir);
    const sessionPath = path.join(rootDir, "session.jsonl");
    const instructionsPath = path.join(rootDir, "AGENTS.md");
    await writeFile(sessionPath, `${JSON.stringify({ type: "session", cwd: rootDir })}\n`, "utf8");
    await writeFile(instructionsPath, "Loaded instructions for this run.\n", "utf8");

    await execute({
      runId: "run-instructions-policy",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: sessionPath,
        sessionParams: { sessionId: sessionPath, cwd: rootDir },
        sessionDisplayId: "session-instructions-policy",
        taskKey: null,
      },
      config: {
        command: "pi",
        model: "openai/gpt-5.4-mini",
        cwd: rootDir,
        instructionsFilePath: "AGENTS.md",
        promptTemplate: "CUSTOM POLICY {{run.id}}",
      },
      context: createPromptContextFixture(),
      onLog: async () => {},
    } as never);

    const call = runChildProcess.mock.calls.at(-1) as unknown as [string, string, string[]] | undefined;
    const args = call?.[2] ?? [];
    const systemPrompt = args[args.indexOf("--append-system-prompt") + 1] ?? "";
    const userPrompt = args.at(-1) ?? "";
    expect(systemPrompt).toContain("Loaded instructions for this run.");
    expect(systemPrompt).toContain("You are agent agent-1 (Pi Builder).");
    expect(systemPrompt).toContain("Connection tools:");
    expect(systemPrompt).not.toContain("Execution contract:");
    expect(userPrompt).not.toContain("CUSTOM POLICY run-instructions-policy");
    expect(userPrompt).not.toContain("Execution contract:");
  });

  it("compacts streamed chunks while parsing the untouched raw stdout result", async () => {
    const rootDir = await mkdtemp(path.join(os.tmpdir(), "paperclip-pi-remote-log-boundary-"));
    cleanupDirs.push(rootDir);
    const workspaceDir = path.join(rootDir, "workspace");
    await mkdir(workspaceDir, { recursive: true });

    const sessionLine = JSON.stringify({ type: "session", id: "session-boundary", cwd: "/remote/workspace" });
    const messageLine = JSON.stringify({
      type: "message_update",
      message: {
        role: "assistant",
        content: [{ type: "text", text: "Hello πŸ˜€" }],
      },
      assistantMessageEvent: {
        type: "text_delta",
        contentIndex: 0,
        delta: "Hello πŸ˜€",
        partial: {
          role: "assistant",
          content: [{ type: "text", text: "Hello πŸ˜€" }],
        },
      },
    });
    const toolUpdateLine = JSON.stringify({
      type: "tool_execution_update",
      toolCallId: "tc-boundary",
      toolName: "bash",
      args: { command: "printf progress" },
      partialResult: {
        content: [{ type: "text", text: "large cumulative output".repeat(1_000) }],
        details: {},
      },
    });
    // CRLF on the passthrough session line, LF on the transformed message,
    // and no newline on the final line exercise every buffering exit path.
    const rawStdout = `${sessionLine}\r\n${messageLine}\n${toolUpdateLine}`;

    runChildProcess.mockImplementationOnce(async (...args: unknown[]) => {
      const options = args[3] as {
        onLog?: (stream: "stdout" | "stderr", chunk: string) => Promise<void>;
      };
      const emojiSplit = rawStdout.indexOf("πŸ˜€") + 1;
      await options.onLog?.("stdout", rawStdout.slice(0, emojiSplit));
      await options.onLog?.("stderr", "diagnostic stderr\n");
      await options.onLog?.("stdout", rawStdout.slice(emojiSplit));
      return {
        exitCode: 0,
        signal: null,
        timedOut: false,
        stdout: rawStdout,
        stderr: "diagnostic stderr\n",
        pid: 456,
        startedAt: new Date().toISOString(),
      };
    });

    const logs: Array<{ stream: "stdout" | "stderr"; chunk: string }> = [];
    const result = await execute({
      runId: "run-log-boundary",
      agent: {
        id: "agent-1",
        companyId: "company-1",
        name: "Pi Builder",
        adapterType: "pi_local",
        adapterConfig: {},
      },
      runtime: {
        sessionId: null,
        sessionParams: null,
        sessionDisplayId: null,
        taskKey: null,
      },
      config: {
        command: "pi",
        model: "openai/gpt-5.4-mini",
        stdoutLogMode: "compact",
      },
      context: {
        paperclipWorkspace: { cwd: workspaceDir, source: "project_primary" },
      },
      executionTransport: {
        remoteExecution: {
          host: "127.0.0.1",
          port: 2222,
          username: "fixture",
          remoteWorkspacePath: "/remote/workspace",
          remoteCwd: "/remote/workspace",
          privateKey: "PRIVATE KEY",
          knownHosts: "[127.0.0.1]:2222 ssh-ed25519 AAAA",
          strictHostKeyChecking: true,
        },
      },
      onLog: async (stream, chunk) => {
        logs.push({ stream, chunk });
      },
    });

    const stdoutLog = logs.filter((entry) => entry.stream === "stdout").map((entry) => entry.chunk).join("");
    expect(stdoutLog).toContain(`${sessionLine}\r\n`);
    expect(stdoutLog).toContain('"type":"message_update"');
    expect(stdoutLog).toContain('"delta":"Hello πŸ˜€"');
    expect(stdoutLog).toContain('"sourceEventType":"tool_execution_update"');
    expect(stdoutLog).not.toContain("large cumulative output");
    expect(logs).toContainEqual({ stream: "stderr", chunk: "diagnostic stderr\n" });

    expect(result.summary).toBe("Hello πŸ˜€");
    expect(result.resultJson).toEqual({ stdout: rawStdout, stderr: "diagnostic stderr\n" });
  });
});