Files
PaperClipAI/server/src/__tests__/headless-e2e-sdk-cli.test.ts
T
DottaandPaperclip ea56320e10 feat(board): add headless channels, fenced task queues, paperclipai/sdk, and pc CLI (#23330)
<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Multi-agent workflows and terminal scripts often need lightweight
shared channels, structured task queues, and scriptable CLI/SDK
primitives without building a full project UI first.
> - Today, Paperclip issues require board-oriented setup, lack lazy
hierarchical channels, lack fenced task claim leases, and lack a
zero-dependency TypeScript SDK and short CLI alias for fast script
coordination.
> - Without fenced leases, blocking queue claims, CAS key-value labels,
and race-free event streaming, multiple headless workers collide on
shared work or fall back to wasteful polling loops.
> - This pull request adds headless channels, versioned JSON schemas,
topological `plan.json` batch creation, fenced task queues with `FOR
UPDATE SKIP LOCKED` claims, CAS key-value labels, one-line ask/confirm
interactions, SSE event streaming, `paperclipai/sdk`, and the `pc` CLI
with `paperclipai up`.
> - The benefit is zero-ceremony, machine-readable, race-safe
coordination across terminal agents, CI scripts, and local Paperclip
servers while staying compatible with existing Web UI issue threads.

## Linked Issues or Issue Description

**Subsystem affected**

Cross-cutting (`packages/db`, `packages/shared`, `server/`, `cli/`,
`doc/`, `skills/`)

**Problem or motivation**

Agents and terminal workflows need a fast way to post updates, queue DAG
tasks, claim work without double-execution, ask humans for approval, and
wait on board events without browser setup or polling loops. Existing
Paperclip routes assume UI-driven projects, lack fenced claim leases for
pools of workers, and lack a minimal `pc` CLI and `paperclipai/sdk`
client.

**Proposed solution**

Build a headless coordination layer directly on top of Paperclip
`issues` and `issue_comments` using `issues.scope = 'channel'`:

- **Database & Contracts (`packages/db`, `packages/shared`)**: Add
`0511_pale_kronos.sql` (`issues.scope`) and `0512_stormy_the_hood.sql`
for lazy hierarchical `channels`, `channel_access_members`, immutable
`company_schemas`, monotonic `board_events`, `scheduled_board_posts`,
`issue_batch_idempotency_keys`, scoped `board_api_keys`,
`agent_identity_policy`, `kv_labels`, `schema_blocks`, and fenced claim
leases. Export Zod contracts, DAG sorting, KV CAS helpers, and the
zero-dependency `paperclip()` SDK (`packages/shared/src/sdk/`),
including an in-memory test backend.
- **Server APIs & Workers (`server/`)**: Add routes and services for
progressive `--as` actor resolution (`open_local_profiles`,
`delegated_profiles`, `strict_agent_keys`), `pc agent connect` auth
challenges, lazy channels, CAS `kv-labels`, versioned schemas,
topological batch creation, `FOR UPDATE SKIP LOCKED` pool claims with
fenced TTL renewal/release/complete/fail, one-line
`ask`/`confirm`/`approve`/`reject` interactions, SSE cursor streaming
(`events/wait`, `events/stream`), and sleep-aware lease expiry and
scheduled post workers.
- **CLI, Launcher & Docs (`cli/`, `doc/`, `skills/`)**: Expose the `pc`
binary alias and `paperclipai/sdk` export, add the zero-prompt
`paperclipai up` / `pc up` local launcher, add `pc` commands (`post`,
`reply`, `read`, `channels`, `label`, `tasks`, `ask`, `confirm`,
`approve`, `reject`, `schemas`, `schedule`, `tail`, `wait`, `agent
connect/login`), add documentation (`doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`), and add
`skills/paperclip-lite/SKILL.md`.

**Alternatives considered**

- **Separate message and queue tables outside `issues`**: Rejected
because channel posts and queued tasks would lose Paperclip identifiers
(`PC-1`), comments, attachments, privacy ACLs, and direct Web UI issue
URLs (`/<prefix>/issues/PC-1`).
- **Advisory locks or polling loops for task workers**: Rejected because
advisory locks drop on reconnect across laptop sleep, and polling wastes
tokens and prevents database sleep. Fenced `(claimToken, claimEpoch)`
TTL leases with `events/wait` and `waitSec` solve both safely.

**Roadmap alignment**

Extends core Paperclip agent orchestration and CLI workflows with a
headless board, SDK, and queue primitive without altering existing Web
UI board behavior.

**Additional context**

This PR builds on the `issues.scope` surface visibility foundation from
#23329 (included as the base commit in this stacked branch so CI and
reviewers can test the full integration against `master`).

## What Changed

- **Schema & Migrations (`packages/db`)**: Added online-compatible
migrations `0511_pale_kronos.sql` and `0512_stormy_the_hood.sql`, schema
definitions (`channels.ts`, `company_schemas.ts`, `headless_board.ts`),
and column extensions on `issues`, `issue_comments`, `companies`,
`board_api_keys`, and `cli_auth_challenges`.
- **Shared Contracts & SDK (`packages/shared`)**: Added
`packages/shared/src/headless/*` (channels, events, identity, labels,
leases, DAG plans, schemas) and `packages/shared/src/sdk/*`
(`paperclip()` client, env loader, SSE parser, and in-memory backend).
- **Server Routes & Services (`server/`)**: Added
`headless-channels-schemas.ts`, `headless-queues-events.ts`,
`headless-identity.ts` routes and supporting services
(`headless-channels.ts`, `headless-common.ts`,
`headless-events-schedules-interactions.ts`, `headless-identity.ts`,
`headless-labels-batch.ts`, `headless-schemas.ts`,
`headless-task-queue.ts`), plus `issues.scope` visibility isolation and
`board-auth.ts` extensions.
- **CLI & SDK Export (`cli/`, `scripts/`)**: Exposed `pc` bin alias and
`paperclipai/sdk` entrypoint, added `up.ts` zero-prompt launcher and
`cli/src/commands/board/*` commands (`post`, `reply`, `read`,
`channels`, `label`, `tasks`, `ask`, `confirm`, `approve`, `reject`,
`schemas`, `schedule`, `tail`, `wait`, `agent`).
- **Docs, Skill & Runner Registry (`doc/`, `skills/`,
`tests/runner-e2e/`)**: Added `doc/CHANNELS-AND-QUEUES.md`,
`doc/CLI.md`, `doc/HEADLESS-TUTORIALS.md`, plan docs,
`skills/paperclip-lite/SKILL.md`, and synchronized
`tests/runner-e2e/source-sdk-public-inputs.json`.

## Verification

- `pnpm --filter @paperclipai/shared build` — passed.
- `pnpm --filter @paperclipai/db check:migrations` — passed
(`0511_pale_kronos.sql` and `0512_stormy_the_hood.sql` verified
online-compatible, 2 new migrations since `630cf0423024`, none blocked).
- `node tests/runner-e2e/source-sdk-public-inputs.mjs $(git rev-parse
HEAD) --check` — passed (`598` inputs, `changed: false`).
- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts
tests/runner-e2e/source-sdk-public-inputs.test.mjs` — 13/13 tests
passed.
- `node scripts/check-maps.mjs` — passed (`35` areas, `192` capability
IDs aligned).
- `pnpm exec vitest run packages/shared/src/headless/headless.test.ts
packages/shared/src/sdk/sdk.test.ts
cli/src/__tests__/headless-board-cli.test.ts` — 3 files, 22/22 tests
passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/issue-scope-visibility.test.ts
src/__tests__/headless-channels-schemas-batch.test.ts
src/__tests__/headless-identity-auth.test.ts
src/__tests__/headless-queues-leases-events.test.ts
src/__tests__/headless-e2e-sdk-cli.test.ts` — 5 files, 25/25 tests
passed.
- `pnpm --filter @paperclipai/shared typecheck && pnpm --filter
@paperclipai/db typecheck && pnpm --filter @paperclipai/server typecheck
&& pnpm --filter paperclipai typecheck` — all passed.
- `pnpm --filter paperclipai build` — passed.

## Risks

- **Two new migrations (`0511`, `0512`)**: Both migrations are marked
online-compatible (`NOT VALID` constraints validated afterwards,
`CONCURRENTLY` index creation, idempotent statements for
non-transactional execution) and checked by `check:migrations`. If
#23329 lands separately with `0511` modified or renumbered, this branch
will rebase on top cleanly.
- **Large surface area (91 files)**: Changes are primarily additive new
modules (`headless-*`, `cli/src/commands/board/*`,
`packages/shared/src/headless/*`, `packages/shared/src/sdk/*`); existing
Web UI board behavior remains isolated via `issues.scope`.
- **Full repository Vitest suite**: Only the targeted headless, SDK,
CLI, server, and runner-e2e pin suites ran locally after rebasing; full
cross-package CI checks will validate the remaining suite.

## Model Used

- Google DeepMind Antigravity (Gemini coding agent) with tool use and
code execution

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 08:12:19 -06:00

507 lines
17 KiB
TypeScript

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<typeof createDb>;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
let server: HttpServer;
let apiBase: string;
let tempHomeDir: string;
let appShutdown: (() => Promise<void>) | 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<void>) | undefined;
server = createServer(app);
await new Promise<void>((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<void>((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 <id>` 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<void>((resolve) => {
notifyWaitRequest = resolve;
});
const onServerRequest = (req: IncomingMessage) => {
if (!waitRequestSeen && req.url?.includes("/events/wait")) {
waitRequestSeen = true;
notifyWaitRequest?.();
}
};
server.on("request", onServerRequest);
let postInterval: ReturnType<typeof setInterval> | 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);
});