import { execFile } from "node:child_process"; import { mkdtemp, rm } from "node:fs/promises"; import { createServer, type IncomingMessage, type Server as HttpServer } from "node:http"; import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { createDb, getEmbeddedPostgresTestSupport, projects, startEmbeddedPostgresTestDatabase, } from "@paperclipai/db"; import { PaperclipError, paperclip } from "@paperclipai/shared/sdk"; import { createApp } from "../app.js"; import type { StorageService } from "../storage/types.js"; const execFileAsync = promisify(execFile); const __dirname = path.dirname(fileURLToPath(import.meta.url)); const CLI_TSX_BIN = path.resolve(__dirname, "../../../cli/node_modules/.bin/tsx"); const CLI_ENTRY = path.resolve(__dirname, "../../../cli/src/index.ts"); const noopStorage: StorageService = { provider: "local_disk", putFile: async () => ({ provider: "local_disk", objectKey: "noop", contentType: "application/octet-stream", byteSize: 0, sha256: "0".repeat(64), originalFilename: null, }), getObject: async () => { throw new Error("not used in headless e2e test"); }, headObject: async () => ({ exists: false }), deleteObject: async () => {}, }; const external = process.env.PAPERCLIP_TEST_DATABASE_URL; const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); const databaseSuite = support.supported ? describe : describe.skip; databaseSuite("Headless Paperclip full-stack E2E (createApp + SDK + pc CLI)", () => { let db: ReturnType; let temporary: Awaited> | undefined; let server: HttpServer; let apiBase: string; let tempHomeDir: string; let appShutdown: (() => Promise) | undefined; beforeAll(async () => { tempHomeDir = await mkdtemp(path.join(os.tmpdir(), "pc-headless-e2e-")); if (external) { db = createDb(external); } else { temporary = await startEmbeddedPostgresTestDatabase("headless-e2e-"); db = createDb(temporary.connectionString); } const app = await createApp(db, { uiMode: "none", serverPort: 0, storageService: noopStorage, deploymentMode: "local_trusted", deploymentExposure: "private", allowedHostnames: ["127.0.0.1", "localhost"], bindHost: "127.0.0.1", authReady: true, companyDeletionEnabled: true, decisionServiceOptions: {} as never, serverMetricsEnabled: false, localPluginDir: path.join(tempHomeDir, "empty-plugins"), }); appShutdown = app.locals.paperclipShutdown as (() => Promise) | undefined; server = createServer(app); await new Promise((resolve) => { server.listen(0, "127.0.0.1", () => resolve()); }); const addr = server.address() as AddressInfo; apiBase = `http://127.0.0.1:${addr.port}`; }, 90_000); afterAll(async () => { if (server) { await new Promise((resolve) => server.close(() => resolve())); } await appShutdown?.(); await db?.$client.end(); await temporary?.cleanup(); if (tempHomeDir) { await rm(tempHomeDir, { recursive: true, force: true }).catch(() => {}); } }, 60_000); it("drives zero-ceremony channels, DAG queues, fenced leases, 1-liner ask/approve, CAS labels, and agent identity via paperclip() SDK", async () => { const pc = paperclip({ apiBase, homeDir: tempHomeDir }); // 1. Minute-0 post auto-resolves/creates default company + lazy #general channel const kickoff = await pc .as("lead") .post("general", "Ship v2\n\nAll headless primitives wired into createApp.", { labels: { release: "v2" }, }); expect(kickoff.channel).toBe("general"); expect(kickoff.scope).toBe("channel"); expect(kickoff.status).toBe("backlog"); expect(kickoff.isPassivePost).toBe(true); expect(kickoff.actorProfile).toBe("lead"); expect(kickoff.kvLabels).toEqual({ release: "v2" }); // Standard GET /api/issues/:id from a browser UI caller (with Referer) still returns the full standard Issue const uiRes = await fetch(`${apiBase}/api/issues/${kickoff.id}`, { headers: { referer: `${apiBase}/issues/${kickoff.identifier}` }, }); expect(uiRes.status).toBe(200); const uiIssue = (await uiRes.json()) as { id: string; identifier: string; scope: string }; expect(uiIssue.id).toBe(kickoff.id); expect(uiIssue.scope).toBe("channel"); // Reply with --after optimistic concurrency const firstReply = await pc.as("reviewer").reply(kickoff.identifier, "Looks solid!"); await expect( pc.as("other").reply(kickoff.identifier, "Stale reply", { after: "00000000-0000-0000-0000-000000000000" }), ).rejects.toMatchObject({ status: 409, code: "stale_reply_cursor" }); const secondReply = await pc .as("lead") .reply(kickoff.identifier, "Confirmed after firstReply", { after: firstReply.id }); expect(secondReply.actorProfile).toBe("lead"); const threadDetail = await pc.read(kickoff.identifier); expect(threadDetail.kind).toBe("thread"); if (threadDetail.kind === "thread") { expect(threadDetail.comments.length).toBe(2); } // 2. Create a real project so we can prove projectId resolution by slug on plan.json await db.insert(projects).values({ companyId: kickoff.companyId, name: "Checkout Service", status: "in_progress", }); // 3. Register a custom immutable JSON Schema const schemaCreated = await pc.schemas.create({ name: "smoke-summary", version: 1, jsonSchema: { type: "object", required: ["passed", "durationMs"], properties: { passed: { type: "boolean" }, durationMs: { type: "integer", minimum: 0 }, }, additionalProperties: false, }, }); expect(schemaCreated.created).toBe(true); // 4. Submit a 2-step DAG plan with project slug + resultSchema const plan = await pc.as("planner").tasks.createPlan( "ci/checkout", [ { key: "unit", title: "Run unit suite", priority: "high", labels: { stage: "test" }, }, { key: "e2e", title: "Run checkout smoke", needs: ["unit"], resultSchema: "smoke-summary@1", labels: { stage: "verify" }, }, ], { projectId: "checkout-service", idempotencyKey: "plan-checkout-v1", }, ); expect(plan.tasks).toHaveLength(2); expect(plan.idempotentReplay).toBe(false); expect(plan.tasks[0]!.issue.projectId).toBeTruthy(); // Idempotent replay returns exact same tasks const planReplay = await pc.as("planner").tasks.createPlan( "ci/checkout", [ { key: "unit", title: "Run unit suite", priority: "high", labels: { stage: "test" }, }, { key: "e2e", title: "Run checkout smoke", needs: ["unit"], resultSchema: "smoke-summary@1", labels: { stage: "verify" }, }, ], { projectId: "checkout-service", idempotencyKey: "plan-checkout-v1", }, ); expect(planReplay.idempotentReplay).toBe(true); expect(planReplay.tasks[0]!.id).toBe(plan.tasks[0]!.id); // 5. Claim from subtree "ci/" -> only "unit" is ready because "e2e" needs "unit" const claimedUnit = await pc.as("worker-a").tasks.claim({ channel: "ci/", ready: true }); expect(claimedUnit).not.toBeNull(); expect(claimedUnit!.task.title).toBe("Run unit suite"); expect(await pc.as("worker-b").tasks.claim({ channel: "ci/", ready: true })).toBeNull(); // Start waiting for "e2e" to become ready, then complete "unit" const waitReadyPromise = pc.wait("ci/", { event: "task.ready", after: claimedUnit!.cursor, timeout: "5s", }); await claimedUnit!.complete("Unit tests green"); const readyEvent = await waitReadyPromise; expect(readyEvent).not.toBeNull(); expect(readyEvent!.issueId).toBe(plan.tasks[1]!.id); // 6. Claim "e2e", ask a humanOnly question (stateless pool auto-releases lease & blocks!), then approve const claimedE2e = await pc.as("worker-b").tasks.claim({ channel: "ci/", ready: true }); expect(claimedE2e).not.toBeNull(); expect(claimedE2e!.task.id).toBe(plan.tasks[1]!.id); const asked = await claimedE2e!.ask("Approve production smoke target?", { humanOnly: true, }); expect(asked.status).toBe("pending"); // Human approves -> requeues to todo! const approved = await pc.approve(claimedE2e!.task.identifier, { note: "Approved for staging-mirror", }); expect(approved.status).toBe("answered"); // Re-claim unblocked "e2e" and verify resultSchema enforcement on complete const reclaimedE2e = await pc.as("worker-c").tasks.claim({ channel: "ci/", ready: true }); expect(reclaimedE2e).not.toBeNull(); expect(reclaimedE2e!.claimEpoch).toBeGreaterThan(claimedE2e!.claimEpoch); await expect( reclaimedE2e!.complete({ data: { passed: "wrong-type" } as never }), ).rejects.toMatchObject({ status: 422, code: "result_schema_validation_failed" }); const completedE2e = await reclaimedE2e!.complete({ message: "Smoke passed", data: { passed: true, durationMs: 412 }, }); expect(completedE2e.status).toBe("done"); // 7. Atomic CAS label update const casOk = await pc.label(completedE2e.identifier, { set: { stage: "shipped" }, if: { stage: "verify" }, }); expect(casOk.kvLabels.stage).toBe("shipped"); await expect( pc.label(completedE2e.identifier, { set: { stage: "duplicate" }, if: { stage: "verify" }, }), ).rejects.toMatchObject({ status: 409, code: "label_conflict" }); // 8. Connect a registered headless agent "@guard" -> unauthenticated --as guard fails 409! const connectRes = await fetch( `${apiBase}/api/companies/${kickoff.companyId}/agents/connect`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "guard", role: "security" }), }, ); expect(connectRes.status).toBe(201); const connected = (await connectRes.json()) as { apiKey: string; agentId: string }; await expect(pc.as("guard").whoami()).rejects.toBeInstanceOf(PaperclipError); await expect(pc.as("guard").whoami()).rejects.toMatchObject({ status: 409, code: "profile_matches_registered_agent", }); const authedGuard = paperclip({ apiBase, apiKey: connected.apiKey, homeDir: tempHomeDir, }); const guardWhoami = await authedGuard.whoami(); expect(guardWhoami.principalType).toBe("agent"); expect(guardWhoami.agentId).toBe(connected.agentId); expect(guardWhoami.agentName).toBe("guard"); }, 90_000); it("drives `pc` CLI persona including `tasks run` lease wrapper end-to-end", async () => { const cliEnv = { ...process.env, HOME: tempHomeDir, PAPERCLIP_HOME: path.join(tempHomeDir, ".paperclip"), PAPERCLIP_API_URL: apiBase, PAPERCLIP_CLI_PERSONA: "pc", }; const runCli = async (args: string[]) => { const { stdout } = await execFileAsync(CLI_TSX_BIN, [CLI_ENTRY, ...args], { env: cliEnv, timeout: 20_000, }); return stdout.trim(); }; const whoamiJson = JSON.parse(await runCli(["whoami", "--json"])) as { companyPrefix: string; principalType: string; }; expect(whoamiJson.companyPrefix).toBe("PC"); expect(whoamiJson.principalType).toBe("local_trusted"); const posted = JSON.parse( await runCli([ "post", "deploys", "Deployed commit abc1234", "--as", "release-bot", "--label", "env=staging", "--json", ]), ) as { identifier: string; channel: string; isPassivePost: boolean }; expect(posted.channel).toBe("deploys"); expect(posted.isPassivePost).toBe(true); // Human-formatted `pc read ` omits `[backlog]` on passive posts and does not fail on tagLabels const humanReadPost = await runCli(["read", posted.identifier]); expect(humanReadPost).toContain(posted.identifier); expect(humanReadPost).not.toContain("[backlog]"); // `pc channels list [prefix]`, `pc label --set --if k=null`, `pc schemas` / `get` / `create --version --schema` const channelsOut = await runCli(["channels", "list", "deploys"]); expect(channelsOut).toContain("#deploys"); const labelOut = await runCli([ "label", posted.identifier, "--set", "stage=verified", "--if", "stage=null", ]); expect(labelOut).toContain("stage=verified"); await runCli([ "schemas", "create", "cli-smoke", "--version", "1", "--schema", '{"type":"object","required":["ok"],"properties":{"ok":{"type":"boolean"}}}', ]); const schemaInspect = await runCli(["schemas", "get", "cli-smoke@1"]); expect(schemaInspect).toContain("cli-smoke@1"); const createdTask = JSON.parse( await runCli([ "tasks", "create", "runner-pool", "Execute child wrapper test", "--label", "suite=cli", "--json", ]), ) as { id: string; identifier: string; status: string }; expect(createdTask.status).toBe("todo"); // `pc tasks` and `pc tasks list` without --channel include open channel tasks const tasksDefaultOut = await runCli(["tasks"]); expect(tasksDefaultOut).toContain(createdTask.identifier); const tasksListOut = await runCli(["tasks", "list", "--label", "suite=cli"]); expect(tasksListOut).toContain(createdTask.identifier); // `pc ask --choices --human-only` + `pc approve --answer` + `pc schedule list` / `cancel` await runCli([ "ask", createdTask.identifier, "Proceed with wrapper run?", "--choices", "yes,no", "--human-only", "--as", "pool-runner", ]); await runCli(["approve", createdTask.identifier, "--answer", "yes"]); const afterApproveRead = await runCli(["read", createdTask.identifier]); expect(afterApproveRead).toContain("-> yes"); const schedId = await runCli([ "schedule", "deploys", "Delayed check", "--in", "10m", "--post", "-q", ]); const schedListOut = await runCli(["schedule", "list"]); expect(schedListOut).toContain(schedId); await runCli(["schedule", "cancel", schedId]); // `pc wait` WITHOUT --after ignores historical `posted` in #deploys and blocks for the next new event! const livePoster = paperclip({ apiBase, homeDir: tempHomeDir }).as("cron-bot"); let waitRequestSeen = false; let notifyWaitRequest: (() => void) | null = null; const waitRequestArrived = new Promise((resolve) => { notifyWaitRequest = resolve; }); const onServerRequest = (req: IncomingMessage) => { if (!waitRequestSeen && req.url?.includes("/events/wait")) { waitRequestSeen = true; notifyWaitRequest?.(); } }; server.on("request", onServerRequest); let postInterval: ReturnType | null = null; let waitedPing: { identifier: string | null; actor: { profile: string | null } }; try { const waitPromise = runCli([ "wait", "deploys", "--event", "thread.posted", "--timeout", "15s", "--json", ]); await waitRequestArrived; postInterval = setInterval(() => { void livePoster.post("deploys", "Scheduled live ping"); }, 250); waitedPing = JSON.parse(await waitPromise) as { identifier: string | null; actor: { profile: string | null }; }; } finally { server.off("request", onServerRequest); if (postInterval) clearInterval(postInterval); } expect(waitedPing.actor.profile).toBe("cron-bot"); expect(waitedPing.identifier).not.toBe(posted.identifier); // `pc agent connect` redacts PAPERCLIP_API_KEY on stdout while saving real key in 0600 profile const connectStdout = await runCli([ "agent", "connect", "cli-scanner", "--role", "engineer", "--ttl", "7d", ]); expect(connectStdout).toContain("pcp_••••••••"); expect(connectStdout).not.toMatch(/PAPERCLIP_API_KEY='pcp_[A-Za-z0-9_-]{10,}'/); const scannerWho = JSON.parse(await runCli(["whoami", "--as", "cli-scanner", "--json"])) as { principalType: string; agentName: string | null; }; expect(scannerWho.principalType).toBe("agent"); expect(scannerWho.agentName).toBe("cli-scanner"); // `pc tasks run` claims the task, injects PAPERCLIP_* env vars, runs child with shell: false, and completes it! await runCli([ "tasks", "run", "--channel", "runner-pool", "--as", "pool-runner", "--lease", "60s", "--", process.execPath, "-e", "if (!process.env.PAPERCLIP_TASK_ID || !process.env.PAPERCLIP_CLAIM_TOKEN) process.exit(2);", ]); const pc = paperclip({ apiBase, homeDir: tempHomeDir }); const afterRun = await pc.read(createdTask.identifier); expect(afterRun.kind).toBe("thread"); if (afterRun.kind === "thread") { expect(afterRun.issue.status).toBe("done"); } }, 90_000); });