perf(ci): shard native-server and chat lanes and split >85s Vitest files (#22974)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI runs Vitest suites across five lanes: Runner native
server, general chat, general server, serialized server, and Runner
package tests.
> - Even after pre-baked AMIs and 8-vCPU runners, single-shard `vitest
native server`, 2-shard `general-chat`, and several oversized
single-file Vitest specs still exceed the 85s per-shard ceiling and
dominate pull request wall-clock time.
> - Splitting those oversized test files and expanding AWS sharding
where needed lowers the slowest Vitest shard under the sub-3-minute pull
request budget while preserving every test case and keeping
`ubuntu-latest` fallback fan-out compact.
> - This pull request shards `vitest native server` (`1 -> 2` on AWS,
`1` on hosted runners) and `general-chat` (`2 -> 3` on AWS, `1` on
hosted runners), splits the remaining `>85s` single-file Vitest tails
across all five lanes into focused `<1,000 LOC` sibling test files with
shared harnesses, and refreshes the four Vitest timing manifests.
> - The benefit is faster pull request feedback with lower tail variance
across every Vitest lane and zero deleted tests.

## Linked Issues or Issue Description

Refs #22916

**What existing behavior does this improve?**
Pull request Vitest shard wall-clock time across `vitest native server`,
`general-chat`, `general server`, `serialized server`, and `Runner
vitest package`.

**Current behavior**
Single-shard `vitest native server`, 2-shard `general-chat`, and several
monolithic test files still run above 85s on 8-vCPU AWS PR runners,
holding back pull request CI completion.

**Proposed behavior**
Expand AWS sharding for `vitest native server` (`1 -> 2` with
`release_crate: true` on both, `1` compacted shard on `ubuntu-latest`)
and `general-chat` (`2 -> 3` on AWS, `1` on `ubuntu-latest`), split the
remaining oversized single-file Vitest suites into focused sibling files
under 1,000 LOC with shared test harnesses, and refresh the four Vitest
shard duration manifests so LPT packing balances the split files
immediately.

**Reason and benefit**
Cuts Vitest critical-path wall clock under 95s per shard while
preserving 100% of test coverage, lane ownership boundaries, and compact
33-job `ubuntu-latest` fallback fan-out.

**Breaking changes**
None. Pure test-file refactoring and shard matrix configuration.

## What Changed

- Expanded AWS sharding in `.github/ci-task-matrix.json`,
`.github/workflows/pr-trusted.yml`, and `scripts/run-vitest-stable.mjs`:
- `Verify Paperclip Runner (vitest native server)`: `1 -> 2` shards on
AWS (`release_crate: true` on both), `1` shard on `ubuntu-latest` via
`HOSTED_SHARD_COUNTS["ci:runner-vitest"] = 1` and
`nativeServerLanePattern`.
- `General tests (chat)`: `2 -> 3` shards on AWS, `1` shard on
`ubuntu-latest`.
- Split the remaining `>85s` single-file Vitest tails across all five
lanes into focused `<1,000 LOC` sibling test files with shared harnesses
(zero deleted tests, zero cross-test-file imports, anchor filenames and
lane ownership preserved):
- Runner package lane (`packages/paperclip-runner`): split oversized
daemon/provider integration files.
- Native server lane: split `native-ingress-bootstrap-retry` while
keeping `native-ingress-bootstrap-retry-opencode` strictly in
`native-runner`.
- Chat lane: split oversized Telegram/GitHub/connection-management
integration tests.
- General server lane: split `tool-gateway-service.test.ts` and
`attention-service` tests using shared harnesses.
- Serialized server lane: split `heartbeat-dependency-scheduling` /
`native-wakes` and `agent-adapter-validation` tests, keeping serialized
ownership intact.
- Refreshed all four Vitest shard duration manifests
(`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`scripts/chat-shard-durations.json`,
`scripts/general-server-shard-durations.json`,
`scripts/serialized-shard-durations.json`) and updated CI contract
tests.

## Verification

- Ran all CI contract suites after rebasing onto `origin/master`:
- `node --test .github/scripts/tests/ci-plan.test.mjs
scripts/ci/runner-release-crate-cache.test.mjs
scripts/ci/run-vitest-stable-shard.test.mjs
scripts/ci/run-vitest-stable-pr-mode.test.mjs
scripts/ci/runner-vitest-package-lanes.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/e2e-shard.test.mjs scripts/ci/check-test-budget.test.mjs`
  - `node scripts/check-test-budget.mjs`
  - `node scripts/check-maps.mjs`
- Verified every new test file is under 1,000 LOC, zero cross-test-file
imports exist, zero files are missing from the four timing manifests,
and `ubuntu-latest` remains strictly at 33 jobs.

## Risks

- Low risk: pure test-file refactoring and shard matrix expansion with
zero production code changes.
- Reverted cleanly by a single `git revert` if any shard balance or
manifest adjustment is needed.

## Model Used

- Google Gemini (Antigravity / Gemini 4 Neon (High), tool use and code
execution enabled).

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-11-25 13:52:16 -06:00
1 parent 7563842165
commit 331e1a9fd3
47 files changed
+11760 -10252

No files matched your search

@@ -43,7 +43,19 @@ const laneCount = laneMatch ? Number(laneMatch[2]) : null;
if (laneMatch && (laneCount < 1 || laneIndex < 1 || laneIndex > laneCount)) {
fail(`invalid package lane: ${laneArgs[0]}`);
}
const nativeServerOnly = args.includes("--native-server");
const nativeArgs = args.filter((value) => value === "--native-server" || value.startsWith("--native-server="));
const nativeMatch = nativeArgs.length === 1
? /^--native-server(?:=(\d+)\/(\d+))?$/.exec(nativeArgs[0])
: null;
if (nativeArgs.length > 1 || (nativeArgs.length === 1 && !nativeMatch)) {
fail(`unrecognized native server argument: ${nativeArgs.join(" ")}`);
}
const nativeServerOnly = nativeArgs.length === 1;
const nativeLaneIndex = nativeMatch?.[1] ? Number(nativeMatch[1]) : null;
const nativeLaneCount = nativeMatch?.[2] ? Number(nativeMatch[2]) : null;
if (nativeLaneCount !== null && (nativeLaneCount < 1 || nativeLaneIndex < 1 || nativeLaneIndex > nativeLaneCount)) {
fail(`invalid native server lane: ${nativeArgs[0]}`);
}
if ([shardArg, laneMatch, nativeServerOnly].filter(Boolean).length > 1) {
fail("--shard, --package-lane and --native-server are mutually exclusive");
}
@@ -88,6 +100,10 @@ if (laneMatch) {
packageArgs = separateWorkloads ? args.filter((arg) => arg !== shardArg) : args;
}
const nativeServerShardArgs = nativeLaneCount !== null && nativeLaneCount > 1
? ["--shard-index", String(nativeLaneIndex - 1), "--shard-count", String(nativeLaneCount)]
: [];
const plannedCommands = [
{ command: "pnpm", args: ["run", "ensure:eval-build-deps"], cwd: packageRoot },
{ command: "pnpm", args: ["run", "build:rust"], cwd: packageRoot },
@@ -97,7 +113,7 @@ const plannedCommands = [
...(runNativeRunnerGroup
? [{
command: "pnpm",
args: ["test:run:general", "--", "--group", "general-server-native-runner"],
args: ["test:run:general", "--", "--group", "general-server-native-runner", ...nativeServerShardArgs],
cwd: workspaceRoot,
}]
: []),
@@ -110,6 +126,7 @@ if (dryRun) {
runNativeRunnerGroup,
runPackageTests,
...(packageLane ? { packageLane } : {}),
...(nativeLaneCount !== null ? { nativeServerLane: { index: nativeLaneIndex, count: nativeLaneCount } } : {}),
plannedCommands,
}, null, 2));
process.exit(0);
@@ -11,9 +11,9 @@
}
],
"coverage": {
"measured": 400,
"measured": 402,
"withSetup": 0,
"inventory": 404
"inventory": 410
},
"durations": {
"packages/paperclip-runner/devtools/browser/src/live/transcript-model.test.ts": 365,
@@ -79,8 +79,10 @@
"packages/paperclip-runner/src/contracts/runner-version.test.ts": 100,
"packages/paperclip-runner/src/contracts/runtime-context.test.ts": 100,
"packages/paperclip-runner/src/contracts/tool-input-variants.test.ts": 166,
"packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts": 96282,
"packages/paperclip-runner/src/control-plane/cursor-cloud-runner-launch.test.ts": 104673,
"packages/paperclip-runner/src/control-plane/acpx-controller-adoption.test.ts": 44200,
"packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts": 51800,
"packages/paperclip-runner/src/control-plane/cursor-cloud-runner-launch.test.ts": 48200,
"packages/paperclip-runner/src/control-plane/cursor-cloud-runner-questions.test.ts": 50000,
"packages/paperclip-runner/src/control-plane/durable-prp-checkpoint-records.test.ts": 439,
"packages/paperclip-runner/src/control-plane/durable-prp-control-plane.test.ts": 32565,
"packages/paperclip-runner/src/control-plane/relaunched-runner.test.ts": 144,
@@ -10,9 +10,11 @@ const slowFiles = [
"runnerd-codex-transport-held-calls.test.ts",
"runnerd-codex-transport-provider-turns.test.ts",
"cursor-cloud-runner-launch.test.ts",
"cursor-cloud-runner-questions.test.ts",
"runnerd-codex-transport-deadlines.test.ts",
"opencode-server-driver.test.ts",
"acpx-controller-recovery.test.ts",
"acpx-controller-adoption.test.ts",
"runnerd-acpx-provider-turn.test.ts",
"runnerd-codex-transport-warm-attachment.test.ts",
"runnerd-opencode-streaming-tools.test.ts",
@@ -0,0 +1,307 @@
import { createServer as createNetServer } from "node:net";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { beforeAll, expect, it, vi } from "vitest";
import { createCapabilityRunnerdCodexTransport } from "../live/runnerd-codex-transport.js";
import { CodexAppServerDriver } from "../drivers/codex/codex-app-server-driver.js";
import { createCodexTaskEnvelope } from "../contracts/codex.js";
import type { PrpEvent } from "../protocol/replay-contract.js";
import {
acpxRecoveryBinary,
acpxRecoveryExpectedRunnerDigest,
acpxRecoveryExpectedRunnerVersion,
acpxRecoveryIdentity,
createAcpxRecoveryFixture,
ensureAcpxRecoveryRunnerBuilt,
} from "./acpx-controller-recovery.harness.js";
const binary = acpxRecoveryBinary;
const identity = acpxRecoveryIdentity;
const expectedRunnerVersion = acpxRecoveryExpectedRunnerVersion;
const fixture = createAcpxRecoveryFixture;
let expectedRunnerDigest: string;
beforeAll(() => {
expectedRunnerDigest = ensureAcpxRecoveryRunnerBuilt();
}, 150_000);
it("keeps the original native ACPX process and active turn through controller replacement",async()=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Keep working"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
await run.stopController();
writeFileSync(resolve(run.root,"action"),"progress");
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"progress-receipt"),"utf8")).toBe(String(pid)),{timeout:3000});
expect(()=>process.kill(pid,0)).not.toThrow();
await run.replaceController();
const result=await run.command("session.snapshot",{includePendingRuntimeRequests:true});
expect(result).toMatchObject({status:"completed",result:{result:{runtimeRequestsLive:true,activeProviderTurnId:"provider-turn-1"}}});
expect(run.launches()).toHaveLength(1);
expect(()=>process.kill(pid,0)).not.toThrow();
writeFileSync(resolve(run.root,"action"),"complete");
await vi.waitFor(()=>expect(run.controller().store.state.committedEvents.some(event=>event.eventType==="turn.completed")).toBe(true),{timeout:5000});
}finally{await run.cleanup();}
},60000);
it("adopts the live ACPX execution through the production native transport",async()=>{
const run=await fixture();
let adopted:ReturnType<typeof createCapabilityRunnerdCodexTransport>|undefined;
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Retain this exact execution"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
await run.stopController();run.restoreCheckpoint();
const launcher=vi.fn(()=>{throw new Error("duplicate runner launch");});
const options:Parameters<typeof createCapabilityRunnerdCodexTransport>[0]={
provider:"acpx",acpxAgent:"claude",stateDirectory:run.root,
runnerBinary:binary,runnerArtifact:{version:expectedRunnerVersion,digest:expectedRunnerDigest ?? acpxRecoveryExpectedRunnerDigest()},prpIdentity:identity,
resumeProviderSession:{driverSessionId:"record-1",providerSessionId:"agent-1"},
runnerProcessLauncher:launcher,controlPlaneRegistration:run.adoptController,
runnerReconnectGraceMs:10000,
adoptExistingRunner:{pid:run.child.pid!,processGroupId:run.child.pid!,startedAt:run.startedAt,
isAlive:()=>{try{process.kill(run.child.pid!,0);return true;}catch{return false;}},
signal:signal=>{try{process.kill(-run.child.pid!,signal);return true;}catch{return false;}}},
};
adopted=createCapabilityRunnerdCodexTransport(options);
adopted.transport.setServerRequestHandler(async()=>({success:true,contentItems:[]}));
expect(await adopted.transport.request("thread/read",{})).toMatchObject({thread:{id:"record-1",sessionId:"agent-1",turns:[{id:"provider-turn-1",status:"inProgress"}]}});
expect(adopted.evidence().runnerPid).toBe(run.child.pid);
expect(run.launches()).toHaveLength(1);
expect(()=>process.kill(pid,0)).not.toThrow();
expect(launcher).not.toHaveBeenCalled();
await adopted.detachControllerForRestart();
await adopted.transport.close("old controller finalizer");
expect(()=>process.kill(pid,0)).not.toThrow();
adopted=createCapabilityRunnerdCodexTransport(options);
adopted.transport.setServerRequestHandler(async()=>({success:true,contentItems:[]}));
expect(await adopted.transport.request("thread/read",{})).toMatchObject({thread:{id:"record-1",sessionId:"agent-1",turns:[{id:"provider-turn-1",status:"inProgress"}]}});
expect(adopted.evidence().runnerPid).toBe(run.child.pid);
expect(run.launches()).toHaveLength(1);
expect(launcher).not.toHaveBeenCalled();
}finally{
await adopted?.transport.close().catch(()=>undefined);
await run.cleanup();
}
},60000);
it.each(["running","finished"] as const)("adopts the %s turn the runner accepted for a controller that died before checkpointing it (RC-59)",async(phase)=>{
const run=await fixture();
let adopted:ReturnType<typeof createCapabilityRunnerdCodexTransport>|undefined;
try{
await run.ready();
// The dying controller sends turn.start and dies before the provider
// accepts it. The runner accepts and starts the turn while no controller
// is attached, so the replacement receives the result and the start.
writeFileSync(resolve(run.root,"hold-turn-start"),"1");
run.controller().queueCommand("turn.start",{turnId:"provider-turn-1",text:"Continue the follow-up"},"command-dying-turn",true);
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8")).toContain("turn.start"),{timeout:5000});
await run.stopController();run.restoreCheckpoint();
writeFileSync(resolve(run.root,"release-turn-start"),"1");
await vi.waitFor(()=>expect(existsSync(resolve(run.root,"turn-start-receipt"))).toBe(true),{timeout:5000});
if(phase==="finished"){
// The provider also finishes the turn before any controller returns.
writeFileSync(resolve(run.root,"action"),"complete");
await vi.waitFor(()=>expect(existsSync(resolve(run.root,"complete-receipt"))).toBe(true),{timeout:5000});
}
const options:Parameters<typeof createCapabilityRunnerdCodexTransport>[0]={
provider:"acpx",acpxAgent:"claude",stateDirectory:run.root,
runnerBinary:binary,runnerArtifact:{version:expectedRunnerVersion,digest:expectedRunnerDigest ?? acpxRecoveryExpectedRunnerDigest()},prpIdentity:identity,
resumeProviderSession:{driverSessionId:"record-1",providerSessionId:"agent-1"},
runnerProcessLauncher:()=>{throw new Error("duplicate runner launch");},controlPlaneRegistration:run.adoptController,
runnerReconnectGraceMs:10000,environment:{PAPERCLIP_WORKSPACE_CWD:run.root},
adoptExistingRunner:{pid:run.child.pid!,processGroupId:run.child.pid!,startedAt:run.startedAt,
isAlive:()=>{try{process.kill(run.child.pid!,0);return true;}catch{return false;}},
signal:signal=>{try{process.kill(-run.child.pid!,signal);return true;}catch{return false;}}},
};
adopted=createCapabilityRunnerdCodexTransport(options);
expect(adopted.transport.controllerAcceptedTurnId?.()).toBeNull();
const driver=new CodexAppServerDriver({conversationMode:"direct",
taskEnvelope:createCodexTaskEnvelope({objective:"Complete the fixture turn",contractRevision:"fixture",criteria:[]}),
transportFactory:()=>adopted!.transport,workingDirectoryAuthority:"remote_runner",environment:{PAPERCLIP_WORKSPACE_CWD:run.root},
capabilities:{goals:false,threadLineage:false},driverIdentity:{kind:"acpx_runtime",displayName:"Claude via ACPX",version:"fixture"}});
const recovery=await driver.recoverSession({driverKind:"acpx_runtime",driverSessionId:"record-1",providerSessionId:"agent-1",
runId:identity.runId,normalizedSessionId:identity.normalizedSessionId,activeTurnId:null});
expect(recovery.recovered,recovery.reason).toBe(true);
const session=recovery.session!;
expect(adopted.transport.controllerAcceptedTurnId?.()).toBe("provider-turn-1");
if(phase==="running"){
expect((await session.snapshot()).activeTurnId).toBe("provider-turn-1");
writeFileSync(resolve(run.root,"action"),"complete");
}
const events:PrpEvent[]=[];
for await(const event of session.events()){
events.push(event);
if(event.eventType.startsWith("turn.")&&!["turn.accepted","turn.started"].includes(event.eventType))break;
}
expect(events.filter(event=>event.eventType.startsWith("turn.")).map(event=>[event.eventType,event.turnId])).toEqual([
["turn.accepted","provider-turn-1"],["turn.started","provider-turn-1"],["turn.completed","provider-turn-1"]]);
expect(events.some(event=>event.eventType==="session.failed")).toBe(false);
// Neither the turn's replayed notifications nor its terminal fail the session afterwards.
await new Promise(settle=>setTimeout(settle,500));
const settled=await session.snapshot();
expect(settled.terminalTurns?.map(turn=>turn.turnId)).toEqual(["provider-turn-1"]);
expect(settled.activeTurnId??null).toBeNull();
// The session passed protocol validation, so the next turn reaches the
// Runner. (The scripted sidecar has no second-turn suspension support.)
const next=await session.startTurn({message:{role:"user",text:"Next turn"}}).then(()=>null,(error:unknown)=>String(error));
expect(next??"").not.toMatch(/unexpected turn|turn_binding_mismatch|session cannot start/);
expect(run.launches()).toHaveLength(1);
expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8").split("\n").filter(command=>command==="turn.start")).toHaveLength(1);
}finally{
await adopted?.transport.close().catch(()=>undefined);
await run.cleanup();
}
},60000);
it.each(["legacy", "stale"])("reconnects before requesting a %s sidecar terminal goal",async(mode)=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Finish while disconnected"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
const port=Number(new URL(run.controller().connectUrl).port);
await run.stopController();
writeFileSync(resolve(run.root,"hold-goal"),"1");
if(mode==="stale") writeFileSync(resolve(run.root,"stale-goal"),"1");
writeFileSync(resolve(run.root,"action"),"complete");
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"complete-receipt"),"utf8")).toBe(String(pid)),{timeout:3000});
// Observe two actual dial attempts after the terminal arrived, including a backoff cycle.
let attempts=0;
const probe=createNetServer(socket=>{attempts++;socket.destroy();});
await new Promise<void>((ready,reject)=>{probe.once("error",reject);probe.listen(port,"127.0.0.1",ready);});
try {
await vi.waitFor(()=>expect(attempts).toBeGreaterThanOrEqual(2),{timeout:5000});
expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8").split("\n").filter(command=>command==="session.goal.get")).toHaveLength(1);
} finally {
await new Promise<void>(done=>probe.close(()=>done()));
}
await run.replaceController();
// The legacy terminal needs a fresh goal. Holding its reply must not hold off authentication.
await vi.waitFor(()=>expect(run.controller().store.state.connectionCount).toBeGreaterThan(1),{timeout:5000});
writeFileSync(resolve(run.root,"release-goal"),"1");
await vi.waitFor(()=>expect(run.controller().store.state.committedEvents.some(event=>event.eventType==="turn.completed")).toBe(true),{timeout:5000});
expect(await run.command("session.snapshot",{includePendingRuntimeRequests:true})).toMatchObject({status:"completed",result:{result:{runtimeRequestsLive:true,activeProviderTurnId:null}}});
expect(run.launches()).toHaveLength(1);
expect(()=>process.kill(pid,0)).not.toThrow();
}finally{await run.cleanup();}
},60000);
it("durably drains noisy active output and one offline terminal before its controller returns", async () => {
const run = await fixture(undefined, undefined, 0, 60_000);
const runnerState = () => JSON.parse(readFileSync(resolve(run.root, "runner/runner-state.json"), "utf8"));
try {
await run.ready();
expect(await run.command("turn.start", { turnId: "provider-turn-1", text: "Finish the admitted work offline" })).toMatchObject({ status: "completed" });
const pid = run.launches()[0].pid;
await run.stopController();
writeFileSync(resolve(run.root, "offline-action"), "burst");
await vi.waitFor(() => expect(runnerState().outbox.some((event: any) => event.envelope.payload.payload.text?.startsWith("offline-287:"))).toBe(true), { timeout: 20_000 });
writeFileSync(resolve(run.root, "action"), "complete");
await vi.waitFor(() => expect(runnerState().outbox.filter((event: any) => event.eventType === "turn.completed")).toHaveLength(1), { timeout: 5000 });
const offline = runnerState();
expect(offline.peakOutboxBytes).toBeLessThanOrEqual(offline.maxOutboxBytes);
expect(() => process.kill(pid, 0)).not.toThrow();
await run.replaceController();
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.some(event => event.sourceSeq === offline.nextSourceSeq - 1)).toBe(true), { timeout: 10_000 });
const replay = new Map(run.controller().store.state.committedEvents.map(event => [event.sourceSeq, event.sourceEventId]));
for (const event of offline.outbox) expect(replay.get(event.sourceSeq)).toBe(event.envelope.payload.sourceEventId);
expect(run.controller().store.state.committedEvents.filter(event => event.eventType === "turn.completed")).toHaveLength(1);
expect(run.launches()).toHaveLength(1);
expect(readFileSync(resolve(run.root, "commands.jsonl"), "utf8").split("\n").filter(command => command === "turn.start")).toHaveLength(1);
} finally { await run.cleanup(); }
}, 90_000);
it("remains silent at an offline approval and resolves the original request exactly once after adoption", async () => {
const run = await fixture();
const runnerState = () => JSON.parse(readFileSync(resolve(run.root, "runner/runner-state.json"), "utf8"));
try {
await run.ready();
expect(await run.command("turn.start", { turnId: "provider-turn-1", text: "Wait for approval" })).toMatchObject({ status: "completed" });
await run.stopController();
writeFileSync(resolve(run.root, "offline-action"), "approval");
await vi.waitFor(() => expect(runnerState().outbox.some((event: any) => event.eventType === "runtime_request.created")).toBe(true), { timeout: 5000 });
const waiting = runnerState();
await new Promise(resolveSilence => setTimeout(resolveSilence, 250));
expect(runnerState().nextSourceSeq).toBe(waiting.nextSourceSeq);
expect(existsSync(resolve(run.root, "approval-effects"))).toBe(false);
await run.replaceController();
const snapshot = await run.command("session.snapshot", { includePendingRuntimeRequests: true });
expect(snapshot).toMatchObject({ status: "completed", result: { result: {
activeProviderTurnId: "provider-turn-1", runtimeRequestsLive: true,
pendingRuntimeRequests: [{ requestId: "permission-1", type: "permission", status: "pending" }],
} } });
expect(existsSync(resolve(run.root, "approval-effects"))).toBe(false);
const resolution = await run.command("request.resolve", { requestId: "permission-1", resolution: { action: "accept" } });
expect(resolution).toMatchObject({ status: "completed" });
expect(await run.command("request.resolve", { requestId: "permission-1", resolution: { action: "accept" } })).toMatchObject({ status: "failed" });
expect(readFileSync(resolve(run.root, "approval-effects"), "utf8")).toBe("approved\n");
writeFileSync(resolve(run.root, "action"), "complete");
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.filter(event => event.eventType === "turn.completed")).toHaveLength(1), { timeout: 5000 });
expect(run.launches()).toHaveLength(1);
} finally { await run.cleanup(); }
}, 60_000);
it("distinguishes a provider-process crash from controller replacement",async()=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Keep working"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
await run.stopController();
writeFileSync(resolve(run.root,"action"),"exit");
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"exit-receipt"),"utf8")).toBe(String(pid)),{timeout:3000});
await vi.waitFor(async()=>{
for(const port of run.launches()[0].ports.slice(0,2)) await new Promise<void>((resolveFree,reject)=>{
const probe=createNetServer();probe.once("error",reject);
probe.listen(port,"127.0.0.1",()=>probe.close(error=>error?reject(error):resolveFree()));
});
},{timeout:3000});
await vi.waitFor(() => {
const saved = JSON.parse(readFileSync(resolve(run.root, "runner/runner-state.json"), "utf8"));
expect(saved.outbox.filter((event: any) => event.eventType === "turn.failed")).toHaveLength(1);
}, { timeout: 5000 });
await run.replaceController();
const result=await run.command("session.snapshot",{includePendingRuntimeRequests:true});
expect(result,JSON.stringify(result)).toMatchObject({status:"failed",result:{result:{
code:"command_execution_failed", message:"ACPX request snapshot requires the surviving provider",
}}});
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.filter(event => event.eventType === "turn.failed")).toHaveLength(1), { timeout: 5000 });
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.find(event => event.eventType === "run.terminal")?.envelope).toMatchObject({ payload: { payload: { reportedWorkDisposition: "needs_review" } } }), { timeout: 5000 });
expect(run.launches()).toHaveLength(1);
}finally{await run.cleanup();}
},60000);
it("requires a surviving provider when requesting a live snapshot after explicit close",async()=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("session.close")).toMatchObject({status:"completed"});
expect(run.child.exitCode).toBeNull();
await run.stopController();
await run.replaceController();
const result=await run.command("session.snapshot",{includePendingRuntimeRequests:true});
expect(result).toMatchObject({status:"failed",result:{result:{message:"ACPX request snapshot requires the surviving provider"}}});
expect(run.launches()).toHaveLength(1);
}finally{await run.cleanup();}
},60000);
it("names a refused reload of the saved conversation after provider death so the server replaces it",async()=>{
const run=await fixture();
try{
await run.ready();
// The Runner and its provider die together. The replacement Runner
// reloads the saved conversation in a new provider process, and the
// sidecar refuses that reload by name.
writeFileSync(resolve(run.root,"reload-refusal"),"ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE");
await run.restartRunner();
const restored=await run.command("session.snapshot");
expect(restored,JSON.stringify(restored)).toMatchObject({status:"failed",result:{result:{
code:"command_execution_failed",classification:"provider_state_incompatible",
}}});
expect(JSON.stringify(restored)).not.toContain("native_session_interrupted");
expect(run.launches()).toHaveLength(2);
expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8").trim().split("\n").slice(-2)).toEqual(["initialize","session.open"]);
}finally{await run.cleanup();}
},60000);
@@ -0,0 +1,238 @@
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import { createHash } from "node:crypto";
import { createServer as createNetServer } from "node:net";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { expect, vi } from "vitest";
import { DurablePrpControlPlane, decodeDurablePrpCheckpoint, spawnRunner, type DurablePrpCheckpoint } from "./durable-prp-control-plane.js";
import { copyOwnedNodeRuntime } from "../test-support/owned-node-runtime.js";
import { GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION } from "../drivers/acpx/generated-sidecar-contract.js";
import type { AcpxCandidateStartupAdmission } from "../drivers/acpx/candidate-admission.js";
const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
export const acpxRecoveryBinary = process.env.PAPERCLIP_ACPX_REPRO_BINARY ?? resolve(packageRoot, "runner/target/debug/paperclip-runnerd");
export const acpxRecoveryProfiles = JSON.parse(readFileSync(process.env.PAPERCLIP_ACPX_REPRO_PROFILES ?? resolve(packageRoot, "acpx-profiles.json"), "utf8"));
const defaultProfile = acpxRecoveryProfiles.profiles.claude;
const digest = (path: string) => "sha256:" + createHash("sha256").update(readFileSync(path)).digest("hex");
export const acpxRecoveryIdentity = {
runnerInstanceId: "runner-acpx-recovery",
environmentLeaseId: "lease-acpx-recovery",
runId: "run-1",
normalizedSessionId: "session-1",
turnId: "durable-turn-1",
itemId: "item-1",
};
export const acpxRecoveryExpectedRunnerVersion = "0.3.0";
let cachedRunnerDigest: string | undefined;
export function ensureAcpxRecoveryRunnerBuilt(): string {
if (!process.env.PAPERCLIP_ACPX_REPRO_BINARY) {
execFileSync("cargo", ["build", "--locked", "--manifest-path", resolve(packageRoot, "runner/Cargo.toml"),
"-p", "paperclip-runner-core", "--bin", "paperclip-runnerd"], { timeout: 120_000, stdio: "pipe" });
}
cachedRunnerDigest = digest(acpxRecoveryBinary);
return cachedRunnerDigest;
}
export function acpxRecoveryExpectedRunnerDigest(): string {
if (!cachedRunnerDigest) {
cachedRunnerDigest = digest(acpxRecoveryBinary);
}
return cachedRunnerDigest;
}
function sidecarSource(root: string, selectedProfile = defaultProfile, agent = "claude") {
return [
"const fs = require('node:fs'); const net = require('node:net'); const rl = require('node:readline'); const {randomInt}=require('node:crypto');",
"const root = " + JSON.stringify(root) + ";",
"const profileDigest = " + JSON.stringify(selectedProfile.commandDigest) + ";",
"const protocolVersion = " + GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION + ";",
"const send = value => process.stdout.write(JSON.stringify(value) + '\\n');",
"let identity, runId, turnId = null, sequence = 0, lastAction = '', lastOfflineAction = '', pendingPermission = false;",
"let goalRevision=0; const goalSnapshot=()=>({schema:'paperclip.session_goal.snapshot.v1',providerRevision:++goalRevision,goal:null,workingNow:false,sessionGoals:{availability:'unsupported',actions:[],autonomousUpdates:false,persistentAcrossResume:false,maxObjectiveChars:4000,tokenBudgetControl:false,usageReporting:false}});",
"const event = (eventType, payload) => send({protocolVersion, sequence:++sequence, eventType, runId, turnId, payload});",
"(async () => {",
" const lease = async () => {for(let attempt=0;attempt<64;attempt++){const s=net.createServer();try{await new Promise((resolve,reject)=>{s.once('error',reject);s.listen(randomInt(49152,65536),'127.0.0.1',resolve);});return s;}catch(error){if(error.code!=='EADDRINUSE')throw error;}}throw new Error('No lifetime fence port available');};",
" const fences = await Promise.all([0,0,0].map(lease));",
" const ports = fences.map(s=>s.address().port); fences[2].close();",
" fs.appendFileSync(root+'/launches.jsonl', JSON.stringify({pid:process.pid, ports})+'\\n');",
" const reply = (r,result) => send({protocolVersion,id:r.id,ok:true,result});",
" const lines=rl.createInterface({input:process.stdin}); lines.on('close',()=>process.exit(0)); lines.on('line', line => {",
" const r=JSON.parse(line), p=r.params || {};",
" fs.appendFileSync(root+'/commands.jsonl',r.command+'\\n');",
" if(r.command==='session.open'&&p.expectedIdentity&&fs.existsSync(root+'/reload-refusal')){send({protocolVersion,id:r.id,ok:false,error:{code:fs.readFileSync(root+'/reload-refusal','utf8'),message:'The saved conversation cannot be reloaded in this process.',retryable:false}});return;}",
" if(r.command==='session.open'&&fs.existsSync(root+'/startup-failure.json')){send({protocolVersion,id:r.id,ok:false,error:{code:'ACPX_SESSION_ENSURE_FAILED',message:'Internal error',retryable:false,providerFailure:JSON.parse(fs.readFileSync(root+'/startup-failure.json','utf8'))}});return;}",
" switch(r.command) {",
" case 'initialize': reply(r,{protocolVersion,sidecarPid:process.pid,profile:{agent:" + JSON.stringify(agent) + "},capabilities:{persistentSessions:true,exactModelVerification:true,permissions:'runner_policy',semanticTools:'runner_bridge',structuredInput:'paperclip.question_set.v1'}});break;",
" case 'session.open': identity={kind:'acpx',normalizedSessionId:p.normalizedSessionId,acpxRecordId:'record-1',backendSessionId:'backend-1',agentSessionId:'agent-1',profileDigest,workspaceDigest:'sha256:'+'2'.repeat(64),requestedModel:p.model,effectiveModel:p.model,permissionMode:p.permissionMode,mode:p.mode,piThinkingLevel:p.piThinkingLevel,claudeEffort:p.claudeEffort,grokEffort:p.grokEffort,grokDisableWebSearch:p.grokDisableWebSearch,providerLifetimeFenceCandidates:ports};reply(r,{sidecarPid:process.pid,identity,status:{},turnControls:{steering:false,queuedFollowUp:false}});break;",
" case 'run.attach': runId=p.runId; reply(r,{runId,catalogRevision:p.catalogRevision});break;",
" case 'session.goal.get': if(fs.existsSync(root+'/hold-goal')){const timer=setInterval(()=>{if(fs.existsSync(root+'/release-goal')){clearInterval(timer);reply(r,goalSnapshot());}},10);}else reply(r,goalSnapshot());break;",
" case 'turn.start': {const start=()=>{turnId=p.turnId;reply(r,{turnId,turnControls:{steering:false,queuedFollowUp:false}});event('runtime.event',{type:'text_delta',text:'started'});fs.writeFileSync(root+'/turn-start-receipt',String(process.pid));};if(fs.existsSync(root+'/hold-turn-start')){const timer=setInterval(()=>{if(fs.existsSync(root+'/release-turn-start')){clearInterval(timer);start();}},10);}else start();break;}",
" case 'session.snapshot': reply(r,{identity,runId,turnId,pendingRuntimeRequests:pendingPermission?[{requestId:'permission-1',type:'permission',turnId}]:[]});break;",
" case 'permission.resolve': if(!pendingPermission)throw new Error('duplicate approval effect');pendingPermission=false;fs.appendFileSync(root+'/approval-effects','approved\\n');reply(r,{resolved:true});break;",
" case 'turn.cancel': reply(r,{cancelled:true});event('runtime.turn_terminal',{status:'interrupted'});turnId=null;break;",
" case 'session.suspend': reply(r,{identity});break;",
" case 'session.close': reply(r,{closed:true});break;",
" default: reply(r,{});",
" }",
" });",
" setInterval(()=>{if(!turnId)return;let action;try{action=fs.readFileSync(root+'/action','utf8');}catch{return;}if(action===lastAction)return;lastAction=action;if(action==='progress'){event('runtime.event',{type:'text_delta',text:'work-during-outage'});fs.writeFileSync(root+'/progress-receipt',String(process.pid));}if(action==='complete'){event('runtime.turn_terminal',{status:'completed',...(fs.existsSync(root+'/stale-goal')?{goalAtTerminal:{...goalSnapshot(),providerRevision:0}}:!fs.existsSync(root+'/hold-goal')?{goalAtTerminal:goalSnapshot()}:{})});turnId=null;fs.writeFileSync(root+'/complete-receipt',String(process.pid));}if(action==='exit'){fs.writeFileSync(root+'/exit-receipt',String(process.pid));process.exit(9);}},10);",
" setInterval(()=>{if(!turnId)return;let action;try{action=fs.readFileSync(root+'/offline-action','utf8');}catch{return;}if(action===lastOfflineAction)return;lastOfflineAction=action;if(action==='burst'){for(let i=0;i<288;i++)event('runtime.event',{type:'text_delta',text:'offline-'+i+':'+'x'.repeat(512)});}if(action==='approval'){pendingPermission=true;event('runtime.permission_requested',{requestId:'permission-1',kind:'edit',title:'Write the file?',choices:[{key:'accept',label:'Allow once'},{key:'cancel',label:'Deny'}]});}},10);",
"})().catch(e=>{process.stderr.write(String(e));process.exit(1);});",
].join("\n");
}
export async function createAcpxRecoveryFixture(
maxLifetimeMs?: number,
candidateAdmission?: AcpxCandidateStartupAdmission,
beforeLaunchDelayMs = 0,
reconnectGraceMs = 15_000,
) {
const expectedRunnerDigest = acpxRecoveryExpectedRunnerDigest();
const root = mkdtempSync(resolve(tmpdir(), "acpx-controller-recovery-"));
const { executable: nodeCommand } = await copyOwnedNodeRuntime(resolve(root, "node"));
const stateDirectory = resolve(root, "control-plane");
const script = resolve(root, "sidecar.cjs");
const agent = candidateAdmission ? "antigravity" : "claude", selectedProfile = acpxRecoveryProfiles.profiles[agent];
writeFileSync(script, sidecarSource(root, selectedProfile, agent), { mode: 0o700 });
const runtime = resolve(root, "runtime");
const descriptor = { kind: "acpx", provider: "acpx", driver: "acpx_runtime", providerVersion: acpxRecoveryProfiles.acpxVersion,
agent, model: candidateAdmission?.model ?? "scripted-model", acpxVersion: acpxRecoveryProfiles.acpxVersion,
agentServerPackage: selectedProfile.agentServerPackage, agentServerVersion: selectedProfile.agentServerVersion,
agentRuntimePackage: selectedProfile.agentRuntimePackage, agentRuntimeVersion: selectedProfile.agentRuntimeVersion,
commandDigest: selectedProfile.commandDigest, sidecarCommand: nodeCommand, sidecarArgs: [script],
runtimeDirectory: runtime, normalizedSessionId: acpxRecoveryIdentity.normalizedSessionId, runId: acpxRecoveryIdentity.runId,
cwd: root, instructions: "Do the supplied synthetic task.", permissionMode: "approve-reads", permissionModePinned: true,
...(selectedProfile.requiresProviderPolicy ? { providerPolicy: { readOnly: true } } : {}),
runtimeContext: null };
let checkpoint!: DurablePrpCheckpoint;
const create = () => {
const controller = new DurablePrpControlPlane({
stateDirectory,
identity: acpxRecoveryIdentity,
expectedRunnerVersion: acpxRecoveryExpectedRunnerVersion,
expectedRunnerDigest,
});
controller.setCheckpointPersistence(async saved => { checkpoint = saved; });
return controller;
};
let controller = create();
await controller.start();
const port = Number(new URL(controller.connectUrl).port);
// Establish one absolute fixture grant before issuing its one-use ticket.
// Bootstrap preparation and the actual daemon share this deadline.
const deadlineAt = candidateAdmission?.expiresAt ?? (maxLifetimeMs === undefined ? undefined : Date.now() + maxLifetimeMs);
const ticket = controller.issueBootstrapTicket(deadlineAt === undefined ? 5_000 : deadlineAt - Date.now());
await controller.flushCheckpoint();
if (beforeLaunchDelayMs) await new Promise(resolveDelay => setTimeout(resolveDelay, beforeLaunchDelayMs));
let diagnostics = "";
const args = ["--connect-url", controller.connectUrl, "--state-dir", resolve(root, "runner"),
"--runner-id", acpxRecoveryIdentity.runnerInstanceId, "--environment-lease-id", acpxRecoveryIdentity.environmentLeaseId,
"--run-id", acpxRecoveryIdentity.runId, "--session-id", acpxRecoveryIdentity.normalizedSessionId, "--turn-id", acpxRecoveryIdentity.turnId, "--item-id", acpxRecoveryIdentity.itemId,
"--runner-version", acpxRecoveryExpectedRunnerVersion, "--runner-digest", expectedRunnerDigest, "--max-runtime-ms", "0",
"--reconnect-grace-ms", String(reconnectGraceMs), "--reconnect-delay-ms", "25", "--acpx-launch-authority-digest", "sha256:" + "d".repeat(64),
"--acpx-sidecar-command", nodeCommand, "--acpx-sidecar-command-sha256", digest(nodeCommand),
"--acpx-sidecar-script", script, "--acpx-sidecar-script-sha256", digest(script),
...(candidateAdmission ? ["--acpx-candidate-admission-json", JSON.stringify(candidateAdmission)] : [])];
const startedAt = new Date().toISOString();
// Exercise daemon authority independently of the TypeScript TTL clamp.
const bounded = maxLifetimeMs === undefined ? undefined : spawnRunner({
connectUrl: controller.connectUrl, stateDirectory: resolve(root, "runner"), identity: acpxRecoveryIdentity, ticket,
maxOutboxBytes: 16 * 1024 * 1024, p0ReserveBytes: 1024 * 1024,
maxRuntimeMs: 0, maxLifetimeMs: deadlineAt! - Date.now(), reconnectGraceMs,
runnerBinaryPath: acpxRecoveryBinary, runnerVersion: acpxRecoveryExpectedRunnerVersion, runnerDigest: expectedRunnerDigest,
acpxLaunchProfile: { ...(candidateAdmission ? { candidateAdmission } : {}), authorityDigest: `sha256:${"d".repeat(64)}`, command: nodeCommand, commandSha256: digest(nodeCommand),
sidecarScript: script, sidecarScriptSha256: digest(script) },
environment: { PATH: process.env.PATH },
});
const launchRunner = (runnerTicket: string) => spawn(acpxRecoveryBinary, args, { env: { PATH: process.env.PATH, PAPERCLIP_RUNNER_BOOTSTRAP_TICKET: runnerTicket }, stdio: ["ignore", "ignore", "pipe"], detached: true });
let child = bounded?.child as ChildProcess | undefined ?? launchRunner(ticket);
let exit = once(child, "exit");
child.stderr!.on("data", bytes => { diagnostics = (diagnostics + String(bytes)).slice(-4096); });
let commandNumber = 0;
async function command(type: string, payload: Record<string, unknown> = {}) {
const id = "command-" + (++commandNumber);
controller.queueCommand(type, payload, id, true);
try {
await vi.waitFor(() => {
expect(child.exitCode, "runner exit; " + diagnostics).toBeNull();
expect(child.signalCode, "runner signal; " + diagnostics).toBeNull();
expect(["completed", "failed"]).toContain(controller.getCommand(id)?.status);
}, { timeout: type === "session.open" ? 35_000 : 8000 });
} catch (error) {
let runnerDiagnostics: unknown;
try { runnerDiagnostics = JSON.parse(readFileSync(resolve(root, "runner/runner-state.json"), "utf8")).diagnostics?.slice(-8); } catch { /* Startup may not have created state. */ }
throw new Error("Hermetic Runner command did not settle: " + JSON.stringify({ id, type,
authenticatedConnections: controller.activeRunnerConnectionCount(), command: controller.getCommand(id),
malformedFrames: controller.store.state.malformedFrames, acceptedConnections: controller.store.state.connectionCount,
lastCommittedEvents: controller.store.state.committedEvents.slice(-4).map(event => ({ sourceSeq: event.sourceSeq, eventType: event.eventType })),
remainingLifetimeMs: deadlineAt === undefined ? null : deadlineAt - Date.now(),
exitCode: child.exitCode, signalCode: child.signalCode, stderr: diagnostics, runnerDiagnostics }).slice(-8192), { cause: error });
}
return controller.getCommand(id)!;
}
const ready = async () => {
const prepared = await command("run.prepare", { provider: descriptor });
expect(prepared, JSON.stringify(prepared)).toMatchObject({ status: "completed" });
const opened = await command("session.open");
expect(opened, JSON.stringify(opened)).toMatchObject({ status: "completed" });
};
const stopped = async () => {
await controller.stop(); await controller.drainPendingConnectionProcessing(); await controller.flushCheckpoint();
};
const restoreCheckpoint = () => {
rmSync(stateDirectory, { recursive: true, force: true });
decodeDurablePrpCheckpoint(checkpoint.records).restoreSessionDirectory(root);
};
return {
root, child, exit, command, ready, descriptor, startedAt, deadlineAt, processGroupId: bounded?.processGroupId ?? child.pid,
controller: () => controller,
stopController: stopped,
restoreCheckpoint,
adoptController: async (next: DurablePrpControlPlane) => {
controller = next; await controller.start(port);
return { connectUrl: controller.connectUrl, release: () => controller.stop() };
},
replaceController: async () => {
restoreCheckpoint();
controller = create(); await controller.start(port);
},
launches: () => readFileSync(resolve(root, "launches.jsonl"), "utf8").trim().split("\n").map(line => JSON.parse(line)),
/** Kills the Runner and every provider it launched, then starts a replacement Runner on the same state. */
restartRunner: async () => {
try { process.kill(-child.pid!, "SIGKILL"); } catch {}
await exit;
for (const line of readFileSync(resolve(root, "launches.jsonl"), "utf8").trim().split("\n")) {
try { process.kill((JSON.parse(line) as { pid: number }).pid, "SIGKILL"); } catch {}
}
const replacementTicket = controller.issueBootstrapTicket(5_000);
await controller.flushCheckpoint();
child = launchRunner(replacementTicket);
exit = once(child, "exit");
child.stderr!.on("data", bytes => { diagnostics = (diagnostics + String(bytes)).slice(-4096); });
},
cleanup: async () => {
await controller.stop();
if (child.exitCode === null && child.signalCode === null) { try { process.kill(-child.pid!, "SIGKILL"); } catch {} }
await exit;
try {
for (const line of readFileSync(resolve(root, "launches.jsonl"), "utf8").trim().split("\n")) {
const launch = JSON.parse(line) as { pid: number; ports: number[] };
await vi.waitFor(async () => {
for (const port of launch.ports.slice(0, 2)) await new Promise<void>((resolveFree, reject) => {
const probe = createNetServer();
probe.once("error", reject);
probe.listen(port, "127.0.0.1", () => probe.close(error => error ? reject(error) : resolveFree()));
});
}, { timeout: 3_000 });
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
rmSync(root, { recursive: true, force: true });
},
};
}
@@ -1,81 +1,24 @@
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
import { once } from "node:events";
import { createHash } from "node:crypto";
import { createServer as createNetServer } from "node:net";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { beforeAll, expect, it, vi } from "vitest";
import { DurablePrpControlPlane, decodeDurablePrpCheckpoint, spawnRunner, type DurablePrpCheckpoint } from "./durable-prp-control-plane.js";
import { copyOwnedNodeRuntime } from "../test-support/owned-node-runtime.js";
import { GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION } from "../drivers/acpx/generated-sidecar-contract.js";
import { createCapabilityRunnerdCodexTransport } from "../live/runnerd-codex-transport.js";
import { bindAcpxCandidateAdmission, type AcpxCandidateStartupAdmission } from "../drivers/acpx/candidate-admission.js";
import { bindAcpxCandidateAdmission } from "../drivers/acpx/candidate-admission.js";
import { ANTIGRAVITY_DISTRIBUTION_PINS } from "../drivers/acpx/generated-profiles.js";
import { CodexAppServerDriver } from "../drivers/codex/codex-app-server-driver.js";
import { createCodexTaskEnvelope } from "../contracts/codex.js";
import type { PrpEvent } from "../protocol/replay-contract.js";
import {
acpxRecoveryIdentity,
acpxRecoveryProfiles,
createAcpxRecoveryFixture,
ensureAcpxRecoveryRunnerBuilt,
} from "./acpx-controller-recovery.harness.js";
const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
const binary = process.env.PAPERCLIP_ACPX_REPRO_BINARY ?? resolve(packageRoot, "runner/target/debug/paperclip-runnerd");
const profiles = JSON.parse(readFileSync(process.env.PAPERCLIP_ACPX_REPRO_PROFILES ?? resolve(packageRoot, "acpx-profiles.json"), "utf8"));
const profile = profiles.profiles.claude;
const digest = (path: string) => "sha256:" + createHash("sha256").update(readFileSync(path)).digest("hex");
const identity = { runnerInstanceId: "runner-acpx-recovery", environmentLeaseId: "lease-acpx-recovery",
runId: "run-1", normalizedSessionId: "session-1", turnId: "durable-turn-1", itemId: "item-1" };
const expectedRunnerVersion = "0.3.0";
let expectedRunnerDigest: string;
const profiles = acpxRecoveryProfiles;
const identity = acpxRecoveryIdentity;
const fixture = createAcpxRecoveryFixture;
beforeAll(() => {
if (!process.env.PAPERCLIP_ACPX_REPRO_BINARY) {
execFileSync("cargo", ["build", "--locked", "--manifest-path", resolve(packageRoot, "runner/Cargo.toml"),
"-p", "paperclip-runner-core", "--bin", "paperclip-runnerd"], { timeout: 120_000, stdio: "pipe" });
}
expectedRunnerDigest = digest(binary);
ensureAcpxRecoveryRunnerBuilt();
}, 150_000);
function sidecarSource(root: string, selectedProfile = profile, agent = "claude") {
return [
"const fs = require('node:fs'); const net = require('node:net'); const rl = require('node:readline'); const {randomInt}=require('node:crypto');",
"const root = " + JSON.stringify(root) + ";",
"const profileDigest = " + JSON.stringify(selectedProfile.commandDigest) + ";",
"const protocolVersion = " + GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION + ";",
"const send = value => process.stdout.write(JSON.stringify(value) + '\\n');",
"let identity, runId, turnId = null, sequence = 0, lastAction = '', lastOfflineAction = '', pendingPermission = false;",
"let goalRevision=0; const goalSnapshot=()=>({schema:'paperclip.session_goal.snapshot.v1',providerRevision:++goalRevision,goal:null,workingNow:false,sessionGoals:{availability:'unsupported',actions:[],autonomousUpdates:false,persistentAcrossResume:false,maxObjectiveChars:4000,tokenBudgetControl:false,usageReporting:false}});",
"const event = (eventType, payload) => send({protocolVersion, sequence:++sequence, eventType, runId, turnId, payload});",
"(async () => {",
" const lease = async () => {for(let attempt=0;attempt<64;attempt++){const s=net.createServer();try{await new Promise((resolve,reject)=>{s.once('error',reject);s.listen(randomInt(49152,65536),'127.0.0.1',resolve);});return s;}catch(error){if(error.code!=='EADDRINUSE')throw error;}}throw new Error('No lifetime fence port available');};",
" const fences = await Promise.all([0,0,0].map(lease));",
" const ports = fences.map(s=>s.address().port); fences[2].close();",
" fs.appendFileSync(root+'/launches.jsonl', JSON.stringify({pid:process.pid, ports})+'\\n');",
" const reply = (r,result) => send({protocolVersion,id:r.id,ok:true,result});",
" const lines=rl.createInterface({input:process.stdin}); lines.on('close',()=>process.exit(0)); lines.on('line', line => {",
" const r=JSON.parse(line), p=r.params || {};",
" fs.appendFileSync(root+'/commands.jsonl',r.command+'\\n');",
" if(r.command==='session.open'&&p.expectedIdentity&&fs.existsSync(root+'/reload-refusal')){send({protocolVersion,id:r.id,ok:false,error:{code:fs.readFileSync(root+'/reload-refusal','utf8'),message:'The saved conversation cannot be reloaded in this process.',retryable:false}});return;}",
" if(r.command==='session.open'&&fs.existsSync(root+'/startup-failure.json')){send({protocolVersion,id:r.id,ok:false,error:{code:'ACPX_SESSION_ENSURE_FAILED',message:'Internal error',retryable:false,providerFailure:JSON.parse(fs.readFileSync(root+'/startup-failure.json','utf8'))}});return;}",
" switch(r.command) {",
" case 'initialize': reply(r,{protocolVersion,sidecarPid:process.pid,profile:{agent:" + JSON.stringify(agent) + "},capabilities:{persistentSessions:true,exactModelVerification:true,permissions:'runner_policy',semanticTools:'runner_bridge',structuredInput:'paperclip.question_set.v1'}});break;",
" case 'session.open': identity={kind:'acpx',normalizedSessionId:p.normalizedSessionId,acpxRecordId:'record-1',backendSessionId:'backend-1',agentSessionId:'agent-1',profileDigest,workspaceDigest:'sha256:'+'2'.repeat(64),requestedModel:p.model,effectiveModel:p.model,permissionMode:p.permissionMode,mode:p.mode,piThinkingLevel:p.piThinkingLevel,claudeEffort:p.claudeEffort,grokEffort:p.grokEffort,grokDisableWebSearch:p.grokDisableWebSearch,providerLifetimeFenceCandidates:ports};reply(r,{sidecarPid:process.pid,identity,status:{},turnControls:{steering:false,queuedFollowUp:false}});break;",
" case 'run.attach': runId=p.runId; reply(r,{runId,catalogRevision:p.catalogRevision});break;",
" case 'session.goal.get': if(fs.existsSync(root+'/hold-goal')){const timer=setInterval(()=>{if(fs.existsSync(root+'/release-goal')){clearInterval(timer);reply(r,goalSnapshot());}},10);}else reply(r,goalSnapshot());break;",
" case 'turn.start': {const start=()=>{turnId=p.turnId;reply(r,{turnId,turnControls:{steering:false,queuedFollowUp:false}});event('runtime.event',{type:'text_delta',text:'started'});fs.writeFileSync(root+'/turn-start-receipt',String(process.pid));};if(fs.existsSync(root+'/hold-turn-start')){const timer=setInterval(()=>{if(fs.existsSync(root+'/release-turn-start')){clearInterval(timer);start();}},10);}else start();break;}",
" case 'session.snapshot': reply(r,{identity,runId,turnId,pendingRuntimeRequests:pendingPermission?[{requestId:'permission-1',type:'permission',turnId}]:[]});break;",
" case 'permission.resolve': if(!pendingPermission)throw new Error('duplicate approval effect');pendingPermission=false;fs.appendFileSync(root+'/approval-effects','approved\\n');reply(r,{resolved:true});break;",
" case 'turn.cancel': reply(r,{cancelled:true});event('runtime.turn_terminal',{status:'interrupted'});turnId=null;break;",
" case 'session.suspend': reply(r,{identity});break;",
" case 'session.close': reply(r,{closed:true});break;",
" default: reply(r,{});",
" }",
" });",
" setInterval(()=>{if(!turnId)return;let action;try{action=fs.readFileSync(root+'/action','utf8');}catch{return;}if(action===lastAction)return;lastAction=action;if(action==='progress'){event('runtime.event',{type:'text_delta',text:'work-during-outage'});fs.writeFileSync(root+'/progress-receipt',String(process.pid));}if(action==='complete'){event('runtime.turn_terminal',{status:'completed',...(fs.existsSync(root+'/stale-goal')?{goalAtTerminal:{...goalSnapshot(),providerRevision:0}}:!fs.existsSync(root+'/hold-goal')?{goalAtTerminal:goalSnapshot()}:{})});turnId=null;fs.writeFileSync(root+'/complete-receipt',String(process.pid));}if(action==='exit'){fs.writeFileSync(root+'/exit-receipt',String(process.pid));process.exit(9);}},10);",
" setInterval(()=>{if(!turnId)return;let action;try{action=fs.readFileSync(root+'/offline-action','utf8');}catch{return;}if(action===lastOfflineAction)return;lastOfflineAction=action;if(action==='burst'){for(let i=0;i<288;i++)event('runtime.event',{type:'text_delta',text:'offline-'+i+':'+'x'.repeat(512)});}if(action==='approval'){pendingPermission=true;event('runtime.permission_requested',{requestId:'permission-1',kind:'edit',title:'Write the file?',choices:[{key:'accept',label:'Allow once'},{key:'cancel',label:'Deny'}]});}},10);",
"})().catch(e=>{process.stderr.write(String(e));process.exit(1);});",
].join("\n");
}
it("preserves a startup provider failure through the real sidecar transport and restored controller journal", async () => {
const run = await fixture();
const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup",
@@ -93,146 +36,6 @@ it("preserves a startup provider failure through the real sidecar transport and
} finally { await run.cleanup(); }
}, 60_000);
async function fixture(maxLifetimeMs?: number, candidateAdmission?: AcpxCandidateStartupAdmission, beforeLaunchDelayMs = 0, reconnectGraceMs = 15_000) {
const root = mkdtempSync(resolve(tmpdir(), "acpx-controller-recovery-"));
const { executable: nodeCommand } = await copyOwnedNodeRuntime(resolve(root, "node"));
const stateDirectory = resolve(root, "control-plane");
const script = resolve(root, "sidecar.cjs");
const agent = candidateAdmission ? "antigravity" : "claude", selectedProfile = profiles.profiles[agent];
writeFileSync(script, sidecarSource(root, selectedProfile, agent), { mode: 0o700 });
const runtime = resolve(root, "runtime");
const descriptor = { kind: "acpx", provider: "acpx", driver: "acpx_runtime", providerVersion: profiles.acpxVersion,
agent, model: candidateAdmission?.model ?? "scripted-model", acpxVersion: profiles.acpxVersion,
agentServerPackage: selectedProfile.agentServerPackage, agentServerVersion: selectedProfile.agentServerVersion,
agentRuntimePackage: selectedProfile.agentRuntimePackage, agentRuntimeVersion: selectedProfile.agentRuntimeVersion,
commandDigest: selectedProfile.commandDigest, sidecarCommand: nodeCommand, sidecarArgs: [script],
runtimeDirectory: runtime, normalizedSessionId: identity.normalizedSessionId, runId: identity.runId,
cwd: root, instructions: "Do the supplied synthetic task.", permissionMode: "approve-reads", permissionModePinned: true,
...(selectedProfile.requiresProviderPolicy ? { providerPolicy: { readOnly: true } } : {}),
runtimeContext: null };
let checkpoint!: DurablePrpCheckpoint;
const create = () => {
const controller = new DurablePrpControlPlane({ stateDirectory, identity, expectedRunnerVersion, expectedRunnerDigest });
controller.setCheckpointPersistence(async saved => { checkpoint = saved; });
return controller;
};
let controller = create();
await controller.start();
const port = Number(new URL(controller.connectUrl).port);
// Establish one absolute fixture grant before issuing its one-use ticket.
// Bootstrap preparation and the actual daemon share this deadline.
const deadlineAt = candidateAdmission?.expiresAt ?? (maxLifetimeMs === undefined ? undefined : Date.now() + maxLifetimeMs);
const ticket = controller.issueBootstrapTicket(deadlineAt === undefined ? 5_000 : deadlineAt - Date.now());
await controller.flushCheckpoint();
if (beforeLaunchDelayMs) await new Promise(resolveDelay => setTimeout(resolveDelay, beforeLaunchDelayMs));
let diagnostics = "";
const args = ["--connect-url",controller.connectUrl,"--state-dir",resolve(root,"runner"),
"--runner-id",identity.runnerInstanceId,"--environment-lease-id",identity.environmentLeaseId,
"--run-id",identity.runId,"--session-id",identity.normalizedSessionId,"--turn-id",identity.turnId,"--item-id",identity.itemId,
"--runner-version",expectedRunnerVersion,"--runner-digest",expectedRunnerDigest,"--max-runtime-ms","0",
"--reconnect-grace-ms",String(reconnectGraceMs),"--reconnect-delay-ms","25","--acpx-launch-authority-digest","sha256:"+"d".repeat(64),
"--acpx-sidecar-command",nodeCommand,"--acpx-sidecar-command-sha256",digest(nodeCommand),
"--acpx-sidecar-script",script,"--acpx-sidecar-script-sha256",digest(script),
...(candidateAdmission ? ["--acpx-candidate-admission-json", JSON.stringify(candidateAdmission)] : [])];
const startedAt = new Date().toISOString();
// Exercise daemon authority independently of the TypeScript TTL clamp.
const bounded = maxLifetimeMs === undefined ? undefined : spawnRunner({
connectUrl: controller.connectUrl, stateDirectory: resolve(root, "runner"), identity, ticket,
maxOutboxBytes: 16 * 1024 * 1024, p0ReserveBytes: 1024 * 1024,
maxRuntimeMs: 0, maxLifetimeMs: deadlineAt! - Date.now(), reconnectGraceMs,
runnerBinaryPath: binary, runnerVersion: expectedRunnerVersion, runnerDigest: expectedRunnerDigest,
acpxLaunchProfile: { ...(candidateAdmission ? { candidateAdmission } : {}), authorityDigest: `sha256:${"d".repeat(64)}`, command: nodeCommand, commandSha256: digest(nodeCommand),
sidecarScript: script, sidecarScriptSha256: digest(script) },
environment: { PATH: process.env.PATH },
});
const launchRunner = (runnerTicket: string) => spawn(binary,args,{env:{PATH:process.env.PATH,PAPERCLIP_RUNNER_BOOTSTRAP_TICKET:runnerTicket},stdio:["ignore","ignore","pipe"],detached:true});
let child = bounded?.child as ChildProcess | undefined ?? launchRunner(ticket);
let exit = once(child,"exit");
child.stderr!.on("data",bytes=>{diagnostics=(diagnostics+String(bytes)).slice(-4096);});
let commandNumber=0;
async function command(type:string,payload:Record<string,unknown>={}) {
const id="command-"+(++commandNumber);
controller.queueCommand(type,payload,id,true);
try {
await vi.waitFor(()=>{
expect(child.exitCode,"runner exit; "+diagnostics).toBeNull();
expect(child.signalCode,"runner signal; "+diagnostics).toBeNull();
expect(["completed","failed"]).toContain(controller.getCommand(id)?.status);
},{timeout:type === "session.open" ? 35_000 : 8000});
} catch (error) {
let runnerDiagnostics: unknown;
try { runnerDiagnostics = JSON.parse(readFileSync(resolve(root, "runner/runner-state.json"), "utf8")).diagnostics?.slice(-8); } catch { /* Startup may not have created state. */ }
throw new Error("Hermetic Runner command did not settle: " + JSON.stringify({ id, type,
authenticatedConnections: controller.activeRunnerConnectionCount(), command: controller.getCommand(id),
malformedFrames: controller.store.state.malformedFrames, acceptedConnections: controller.store.state.connectionCount,
lastCommittedEvents: controller.store.state.committedEvents.slice(-4).map(event => ({ sourceSeq: event.sourceSeq, eventType: event.eventType })),
remainingLifetimeMs: deadlineAt === undefined ? null : deadlineAt - Date.now(),
exitCode: child.exitCode, signalCode: child.signalCode, stderr: diagnostics, runnerDiagnostics }).slice(-8192), { cause: error });
}
return controller.getCommand(id)!;
}
const ready = async () => {
const prepared = await command("run.prepare",{provider:descriptor});
expect(prepared, JSON.stringify(prepared)).toMatchObject({status:"completed"});
const opened = await command("session.open");
expect(opened, JSON.stringify(opened)).toMatchObject({status:"completed"});
};
const stopped = async () => {
await controller.stop(); await controller.drainPendingConnectionProcessing(); await controller.flushCheckpoint();
};
const restoreCheckpoint = () => {
rmSync(stateDirectory,{recursive:true,force:true});
decodeDurablePrpCheckpoint(checkpoint.records).restoreSessionDirectory(root);
};
return {root,child,exit,command,ready,descriptor,startedAt,deadlineAt,processGroupId: bounded?.processGroupId ?? child.pid,
controller:()=>controller,
stopController:stopped,
restoreCheckpoint,
adoptController:async(next:DurablePrpControlPlane)=>{
controller=next;await controller.start(port);
return {connectUrl:controller.connectUrl,release:()=>controller.stop()};
},
replaceController:async()=>{
restoreCheckpoint();
controller=create();await controller.start(port);
},
launches:()=>readFileSync(resolve(root,"launches.jsonl"),"utf8").trim().split("\n").map(line=>JSON.parse(line)),
/** Kills the Runner and every provider it launched, then starts a replacement Runner on the same state. */
restartRunner:async()=>{
try{process.kill(-child.pid!,"SIGKILL");}catch{}
await exit;
for(const line of readFileSync(resolve(root,"launches.jsonl"),"utf8").trim().split("\n")){
try{process.kill((JSON.parse(line) as {pid:number}).pid,"SIGKILL");}catch{}
}
const replacementTicket=controller.issueBootstrapTicket(5_000);
await controller.flushCheckpoint();
child=launchRunner(replacementTicket);
exit=once(child,"exit");
child.stderr!.on("data",bytes=>{diagnostics=(diagnostics+String(bytes)).slice(-4096);});
},
cleanup:async()=>{
await controller.stop();
if(child.exitCode===null && child.signalCode===null){try{process.kill(-child.pid!,"SIGKILL");}catch{}}
await exit;
try {
for (const line of readFileSync(resolve(root,"launches.jsonl"),"utf8").trim().split("\n")) {
const launch = JSON.parse(line) as { pid: number; ports: number[] };
await vi.waitFor(async () => {
for (const port of launch.ports.slice(0, 2)) await new Promise<void>((resolveFree, reject) => {
const probe = createNetServer();
probe.once("error", reject);
probe.listen(port, "127.0.0.1", () => probe.close(error => error ? reject(error) : resolveFree()));
});
}, { timeout: 3_000 });
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
rmSync(root,{recursive:true,force:true});
},
};
}
async function assertActiveExpiry(candidate = false) {
// One fixed grant covers the six-second cold delay, the native thirty-second
// startup bound, and active-turn headroom. The fixture must not time out
@@ -275,284 +78,3 @@ it("expires an active provider turn after a cold bootstrap delay and physically
it.skipIf(process.platform !== "darwin" || process.arch !== "arm64")(
"retires an active exact Antigravity candidate at absolute operator expiry with no caller runtime limit",
() => assertActiveExpiry(true), 60_000);
it("keeps the original native ACPX process and active turn through controller replacement",async()=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Keep working"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
await run.stopController();
writeFileSync(resolve(run.root,"action"),"progress");
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"progress-receipt"),"utf8")).toBe(String(pid)),{timeout:3000});
expect(()=>process.kill(pid,0)).not.toThrow();
await run.replaceController();
const result=await run.command("session.snapshot",{includePendingRuntimeRequests:true});
expect(result).toMatchObject({status:"completed",result:{result:{runtimeRequestsLive:true,activeProviderTurnId:"provider-turn-1"}}});
expect(run.launches()).toHaveLength(1);
expect(()=>process.kill(pid,0)).not.toThrow();
writeFileSync(resolve(run.root,"action"),"complete");
await vi.waitFor(()=>expect(run.controller().store.state.committedEvents.some(event=>event.eventType==="turn.completed")).toBe(true),{timeout:5000});
}finally{await run.cleanup();}
},60000);
it("adopts the live ACPX execution through the production native transport",async()=>{
const run=await fixture();
let adopted:ReturnType<typeof createCapabilityRunnerdCodexTransport>|undefined;
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Retain this exact execution"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
await run.stopController();run.restoreCheckpoint();
const launcher=vi.fn(()=>{throw new Error("duplicate runner launch");});
const options:Parameters<typeof createCapabilityRunnerdCodexTransport>[0]={
provider:"acpx",acpxAgent:"claude",stateDirectory:run.root,
runnerBinary:binary,runnerArtifact:{version:expectedRunnerVersion,digest:expectedRunnerDigest},prpIdentity:identity,
resumeProviderSession:{driverSessionId:"record-1",providerSessionId:"agent-1"},
runnerProcessLauncher:launcher,controlPlaneRegistration:run.adoptController,
runnerReconnectGraceMs:10000,
adoptExistingRunner:{pid:run.child.pid!,processGroupId:run.child.pid!,startedAt:run.startedAt,
isAlive:()=>{try{process.kill(run.child.pid!,0);return true;}catch{return false;}},
signal:signal=>{try{process.kill(-run.child.pid!,signal);return true;}catch{return false;}}},
};
adopted=createCapabilityRunnerdCodexTransport(options);
adopted.transport.setServerRequestHandler(async()=>({success:true,contentItems:[]}));
expect(await adopted.transport.request("thread/read",{})).toMatchObject({thread:{id:"record-1",sessionId:"agent-1",turns:[{id:"provider-turn-1",status:"inProgress"}]}});
expect(adopted.evidence().runnerPid).toBe(run.child.pid);
expect(run.launches()).toHaveLength(1);
expect(()=>process.kill(pid,0)).not.toThrow();
expect(launcher).not.toHaveBeenCalled();
await adopted.detachControllerForRestart();
await adopted.transport.close("old controller finalizer");
expect(()=>process.kill(pid,0)).not.toThrow();
adopted=createCapabilityRunnerdCodexTransport(options);
adopted.transport.setServerRequestHandler(async()=>({success:true,contentItems:[]}));
expect(await adopted.transport.request("thread/read",{})).toMatchObject({thread:{id:"record-1",sessionId:"agent-1",turns:[{id:"provider-turn-1",status:"inProgress"}]}});
expect(adopted.evidence().runnerPid).toBe(run.child.pid);
expect(run.launches()).toHaveLength(1);
expect(launcher).not.toHaveBeenCalled();
}finally{
await adopted?.transport.close().catch(()=>undefined);
await run.cleanup();
}
},60000);
it.each(["running","finished"] as const)("adopts the %s turn the runner accepted for a controller that died before checkpointing it (RC-59)",async(phase)=>{
const run=await fixture();
let adopted:ReturnType<typeof createCapabilityRunnerdCodexTransport>|undefined;
try{
await run.ready();
// The dying controller sends turn.start and dies before the provider
// accepts it. The runner accepts and starts the turn while no controller
// is attached, so the replacement receives the result and the start.
writeFileSync(resolve(run.root,"hold-turn-start"),"1");
run.controller().queueCommand("turn.start",{turnId:"provider-turn-1",text:"Continue the follow-up"},"command-dying-turn",true);
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8")).toContain("turn.start"),{timeout:5000});
await run.stopController();run.restoreCheckpoint();
writeFileSync(resolve(run.root,"release-turn-start"),"1");
await vi.waitFor(()=>expect(existsSync(resolve(run.root,"turn-start-receipt"))).toBe(true),{timeout:5000});
if(phase==="finished"){
// The provider also finishes the turn before any controller returns.
writeFileSync(resolve(run.root,"action"),"complete");
await vi.waitFor(()=>expect(existsSync(resolve(run.root,"complete-receipt"))).toBe(true),{timeout:5000});
}
const options:Parameters<typeof createCapabilityRunnerdCodexTransport>[0]={
provider:"acpx",acpxAgent:"claude",stateDirectory:run.root,
runnerBinary:binary,runnerArtifact:{version:expectedRunnerVersion,digest:expectedRunnerDigest},prpIdentity:identity,
resumeProviderSession:{driverSessionId:"record-1",providerSessionId:"agent-1"},
runnerProcessLauncher:()=>{throw new Error("duplicate runner launch");},controlPlaneRegistration:run.adoptController,
runnerReconnectGraceMs:10000,environment:{PAPERCLIP_WORKSPACE_CWD:run.root},
adoptExistingRunner:{pid:run.child.pid!,processGroupId:run.child.pid!,startedAt:run.startedAt,
isAlive:()=>{try{process.kill(run.child.pid!,0);return true;}catch{return false;}},
signal:signal=>{try{process.kill(-run.child.pid!,signal);return true;}catch{return false;}}},
};
adopted=createCapabilityRunnerdCodexTransport(options);
expect(adopted.transport.controllerAcceptedTurnId?.()).toBeNull();
const driver=new CodexAppServerDriver({conversationMode:"direct",
taskEnvelope:createCodexTaskEnvelope({objective:"Complete the fixture turn",contractRevision:"fixture",criteria:[]}),
transportFactory:()=>adopted!.transport,workingDirectoryAuthority:"remote_runner",environment:{PAPERCLIP_WORKSPACE_CWD:run.root},
capabilities:{goals:false,threadLineage:false},driverIdentity:{kind:"acpx_runtime",displayName:"Claude via ACPX",version:"fixture"}});
const recovery=await driver.recoverSession({driverKind:"acpx_runtime",driverSessionId:"record-1",providerSessionId:"agent-1",
runId:identity.runId,normalizedSessionId:identity.normalizedSessionId,activeTurnId:null});
expect(recovery.recovered,recovery.reason).toBe(true);
const session=recovery.session!;
expect(adopted.transport.controllerAcceptedTurnId?.()).toBe("provider-turn-1");
if(phase==="running"){
expect((await session.snapshot()).activeTurnId).toBe("provider-turn-1");
writeFileSync(resolve(run.root,"action"),"complete");
}
const events:PrpEvent[]=[];
for await(const event of session.events()){
events.push(event);
if(event.eventType.startsWith("turn.")&&!["turn.accepted","turn.started"].includes(event.eventType))break;
}
expect(events.filter(event=>event.eventType.startsWith("turn.")).map(event=>[event.eventType,event.turnId])).toEqual([
["turn.accepted","provider-turn-1"],["turn.started","provider-turn-1"],["turn.completed","provider-turn-1"]]);
expect(events.some(event=>event.eventType==="session.failed")).toBe(false);
// Neither the turn's replayed notifications nor its terminal fail the session afterwards.
await new Promise(settle=>setTimeout(settle,500));
const settled=await session.snapshot();
expect(settled.terminalTurns?.map(turn=>turn.turnId)).toEqual(["provider-turn-1"]);
expect(settled.activeTurnId??null).toBeNull();
// The session passed protocol validation, so the next turn reaches the
// Runner. (The scripted sidecar has no second-turn suspension support.)
const next=await session.startTurn({message:{role:"user",text:"Next turn"}}).then(()=>null,(error:unknown)=>String(error));
expect(next??"").not.toMatch(/unexpected turn|turn_binding_mismatch|session cannot start/);
expect(run.launches()).toHaveLength(1);
expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8").split("\n").filter(command=>command==="turn.start")).toHaveLength(1);
}finally{
await adopted?.transport.close().catch(()=>undefined);
await run.cleanup();
}
},60000);
it.each(["legacy", "stale"])("reconnects before requesting a %s sidecar terminal goal",async(mode)=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Finish while disconnected"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
const port=Number(new URL(run.controller().connectUrl).port);
await run.stopController();
writeFileSync(resolve(run.root,"hold-goal"),"1");
if(mode==="stale") writeFileSync(resolve(run.root,"stale-goal"),"1");
writeFileSync(resolve(run.root,"action"),"complete");
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"complete-receipt"),"utf8")).toBe(String(pid)),{timeout:3000});
// Observe two actual dial attempts after the terminal arrived, including a backoff cycle.
let attempts=0;
const probe=createNetServer(socket=>{attempts++;socket.destroy();});
await new Promise<void>((ready,reject)=>{probe.once("error",reject);probe.listen(port,"127.0.0.1",ready);});
try {
await vi.waitFor(()=>expect(attempts).toBeGreaterThanOrEqual(2),{timeout:5000});
expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8").split("\n").filter(command=>command==="session.goal.get")).toHaveLength(1);
} finally {
await new Promise<void>(done=>probe.close(()=>done()));
}
await run.replaceController();
// The legacy terminal needs a fresh goal. Holding its reply must not hold off authentication.
await vi.waitFor(()=>expect(run.controller().store.state.connectionCount).toBeGreaterThan(1),{timeout:5000});
writeFileSync(resolve(run.root,"release-goal"),"1");
await vi.waitFor(()=>expect(run.controller().store.state.committedEvents.some(event=>event.eventType==="turn.completed")).toBe(true),{timeout:5000});
expect(await run.command("session.snapshot",{includePendingRuntimeRequests:true})).toMatchObject({status:"completed",result:{result:{runtimeRequestsLive:true,activeProviderTurnId:null}}});
expect(run.launches()).toHaveLength(1);
expect(()=>process.kill(pid,0)).not.toThrow();
}finally{await run.cleanup();}
},60000);
it("durably drains noisy active output and one offline terminal before its controller returns", async () => {
const run = await fixture(undefined, undefined, 0, 60_000);
const runnerState = () => JSON.parse(readFileSync(resolve(run.root, "runner/runner-state.json"), "utf8"));
try {
await run.ready();
expect(await run.command("turn.start", { turnId: "provider-turn-1", text: "Finish the admitted work offline" })).toMatchObject({ status: "completed" });
const pid = run.launches()[0].pid;
await run.stopController();
writeFileSync(resolve(run.root, "offline-action"), "burst");
await vi.waitFor(() => expect(runnerState().outbox.some((event: any) => event.envelope.payload.payload.text?.startsWith("offline-287:"))).toBe(true), { timeout: 20_000 });
writeFileSync(resolve(run.root, "action"), "complete");
await vi.waitFor(() => expect(runnerState().outbox.filter((event: any) => event.eventType === "turn.completed")).toHaveLength(1), { timeout: 5000 });
const offline = runnerState();
expect(offline.peakOutboxBytes).toBeLessThanOrEqual(offline.maxOutboxBytes);
expect(() => process.kill(pid, 0)).not.toThrow();
await run.replaceController();
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.some(event => event.sourceSeq === offline.nextSourceSeq - 1)).toBe(true), { timeout: 10_000 });
const replay = new Map(run.controller().store.state.committedEvents.map(event => [event.sourceSeq, event.sourceEventId]));
for (const event of offline.outbox) expect(replay.get(event.sourceSeq)).toBe(event.envelope.payload.sourceEventId);
expect(run.controller().store.state.committedEvents.filter(event => event.eventType === "turn.completed")).toHaveLength(1);
expect(run.launches()).toHaveLength(1);
expect(readFileSync(resolve(run.root, "commands.jsonl"), "utf8").split("\n").filter(command => command === "turn.start")).toHaveLength(1);
} finally { await run.cleanup(); }
}, 90_000);
it("remains silent at an offline approval and resolves the original request exactly once after adoption", async () => {
const run = await fixture();
const runnerState = () => JSON.parse(readFileSync(resolve(run.root, "runner/runner-state.json"), "utf8"));
try {
await run.ready();
expect(await run.command("turn.start", { turnId: "provider-turn-1", text: "Wait for approval" })).toMatchObject({ status: "completed" });
await run.stopController();
writeFileSync(resolve(run.root, "offline-action"), "approval");
await vi.waitFor(() => expect(runnerState().outbox.some((event: any) => event.eventType === "runtime_request.created")).toBe(true), { timeout: 5000 });
const waiting = runnerState();
await new Promise(resolveSilence => setTimeout(resolveSilence, 250));
expect(runnerState().nextSourceSeq).toBe(waiting.nextSourceSeq);
expect(existsSync(resolve(run.root, "approval-effects"))).toBe(false);
await run.replaceController();
const snapshot = await run.command("session.snapshot", { includePendingRuntimeRequests: true });
expect(snapshot).toMatchObject({ status: "completed", result: { result: {
activeProviderTurnId: "provider-turn-1", runtimeRequestsLive: true,
pendingRuntimeRequests: [{ requestId: "permission-1", type: "permission", status: "pending" }],
} } });
expect(existsSync(resolve(run.root, "approval-effects"))).toBe(false);
const resolution = await run.command("request.resolve", { requestId: "permission-1", resolution: { action: "accept" } });
expect(resolution).toMatchObject({ status: "completed" });
expect(await run.command("request.resolve", { requestId: "permission-1", resolution: { action: "accept" } })).toMatchObject({ status: "failed" });
expect(readFileSync(resolve(run.root, "approval-effects"), "utf8")).toBe("approved\n");
writeFileSync(resolve(run.root, "action"), "complete");
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.filter(event => event.eventType === "turn.completed")).toHaveLength(1), { timeout: 5000 });
expect(run.launches()).toHaveLength(1);
} finally { await run.cleanup(); }
}, 60_000);
it("distinguishes a provider-process crash from controller replacement",async()=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("turn.start",{turnId:"provider-turn-1",text:"Keep working"})).toMatchObject({status:"completed"});
const pid=run.launches()[0].pid;
await run.stopController();
writeFileSync(resolve(run.root,"action"),"exit");
await vi.waitFor(()=>expect(readFileSync(resolve(run.root,"exit-receipt"),"utf8")).toBe(String(pid)),{timeout:3000});
await vi.waitFor(async()=>{
for(const port of run.launches()[0].ports.slice(0,2)) await new Promise<void>((resolveFree,reject)=>{
const probe=createNetServer();probe.once("error",reject);
probe.listen(port,"127.0.0.1",()=>probe.close(error=>error?reject(error):resolveFree()));
});
},{timeout:3000});
await vi.waitFor(() => {
const saved = JSON.parse(readFileSync(resolve(run.root, "runner/runner-state.json"), "utf8"));
expect(saved.outbox.filter((event: any) => event.eventType === "turn.failed")).toHaveLength(1);
}, { timeout: 5000 });
await run.replaceController();
const result=await run.command("session.snapshot",{includePendingRuntimeRequests:true});
expect(result,JSON.stringify(result)).toMatchObject({status:"failed",result:{result:{
code:"command_execution_failed", message:"ACPX request snapshot requires the surviving provider",
}}});
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.filter(event => event.eventType === "turn.failed")).toHaveLength(1), { timeout: 5000 });
await vi.waitFor(() => expect(run.controller().store.state.committedEvents.find(event => event.eventType === "run.terminal")?.envelope).toMatchObject({ payload: { payload: { reportedWorkDisposition: "needs_review" } } }), { timeout: 5000 });
expect(run.launches()).toHaveLength(1);
}finally{await run.cleanup();}
},60000);
it("requires a surviving provider when requesting a live snapshot after explicit close",async()=>{
const run=await fixture();
try{
await run.ready();
expect(await run.command("session.close")).toMatchObject({status:"completed"});
expect(run.child.exitCode).toBeNull();
await run.stopController();
await run.replaceController();
const result=await run.command("session.snapshot",{includePendingRuntimeRequests:true});
expect(result).toMatchObject({status:"failed",result:{result:{message:"ACPX request snapshot requires the surviving provider"}}});
expect(run.launches()).toHaveLength(1);
}finally{await run.cleanup();}
},60000);
it("names a refused reload of the saved conversation after provider death so the server replaces it",async()=>{
const run=await fixture();
try{
await run.ready();
// The Runner and its provider die together. The replacement Runner
// reloads the saved conversation in a new provider process, and the
// sidecar refuses that reload by name.
writeFileSync(resolve(run.root,"reload-refusal"),"ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE");
await run.restartRunner();
const restored=await run.command("session.snapshot");
expect(restored,JSON.stringify(restored)).toMatchObject({status:"failed",result:{result:{
code:"command_execution_failed",classification:"provider_state_incompatible",
}}});
expect(JSON.stringify(restored)).not.toContain("native_session_interrupted");
expect(run.launches()).toHaveLength(2);
expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8").trim().split("\n").slice(-2)).toEqual(["initialize","session.open"]);
}finally{await run.cleanup();}
},60000);
@@ -1,47 +1,12 @@
import { createHash } from "node:crypto";
import { RUNNER_TOOL_SCOPE_TOKEN_HEADER } from "../drivers/runner-tool-bridge.js";
import { execFileSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
import { cp, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { request } from "node:http";
import { fileURLToPath } from "node:url";
import { expect, it, vi } from "vitest";
import { createRunnerdNativeSessionBackend } from "../backends/codex-native-backend.js";
import type { NativeExecutionInputV5 } from "../contracts/native-execution.js";
import { canonicalNativeRuntimeContextDigest, NATIVE_RUNTIME_ASSET_SCHEMA, PAPERCLIP_EXECUTION_PROMPT, PAPERCLIP_EXECUTION_PROMPT_REVISION, nativeRuntimePromptDigest } from "../contracts/runtime-context.js";
import { executeNativeSession } from "../native-session-runtime.js";
import type { PrpEvent, PrpStructuredRunResult } from "../protocol/replay-contract.js";
import type { DurablePrpControlPlane } from "./durable-prp-control-plane.js";
import { createRunnerdCodexTransport, defaultCapabilityRunnerdBinary } from "../live/runnerd-codex-transport.js";
import { copyOwnedNodeRuntime } from "../test-support/owned-node-runtime.js";
async function privateCloudNodeCommand(root: string): Promise<string> {
const directory = join(root, "provider-node");
await mkdir(directory, { mode: 0o700 });
const { executable } = await copyOwnedNodeRuntime(directory);
// Keep Node's name so the verified launcher selects its descriptor loader.
const command = join(directory, process.platform === "win32" ? "node.exe" : "node");
await rename(executable, command);
return command;
}
function buildPrivateCursorCloudProxy(proxyPath: string): void {
const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
const builderUrl = new URL("../../scripts/build-verified-provider-entrypoints.mjs", import.meta.url).href;
execFileSync(process.execPath, ["--input-type=module", "-e", [
"import { writeFile } from 'node:fs/promises';",
`const { bundleVerifiedProviderEntrypoints } = await import(${JSON.stringify(builderUrl)});`,
"const item = (await bundleVerifiedProviderEntrypoints({ write: false })).find(value => value.entrypoint.name === 'cursor-cloud-app-server-proxy');",
`await writeFile(${JSON.stringify(proxyPath)}, item.verifiedResult.outputFiles[0].contents, { mode: 0o600 });`,
].join("\n")], { cwd: packageRoot, timeout: 20_000, stdio: "pipe" });
}
async function currentCloudScopeHeader(runtime: string, sessionId: string): Promise<string> {
const name = `checkpoint-${createHash("sha256").update(sessionId).digest("hex")}.json`;
const checkpoint = JSON.parse(await readFile(join(runtime, name), "utf8"));
expect(checkpoint.relayTurnToken).toMatch(/^[A-Za-z0-9_-]{43}$/);
return `Bearer ${checkpoint.relayTurnToken}`;
}
import { buildPrivateCursorCloudProxy, currentCloudScopeHeader, privateCloudNodeCommand } from "./cursor-cloud-runner.harness.js";
it("settles a create rejected during real-facade Stop before cold recovery and the next run", async () => {
const root = await mkdtemp("/tmp/cc-rejected-stop-");
@@ -289,175 +254,6 @@ it("preserves native Cloud tool identity and redacted output through the real Ru
}
}, 30_000);
async function cloudQuestionHandoff(terminalDelayMs: number, governed: boolean, planning = false) {
const root = await mkdtemp("/tmp/cc-question-");
const runtime = join(root, "cloud");
const configPath = join(runtime, "config.json");
const socketPath = join(root, "mcp.sock");
const proxyPath = join(root, "cloud-proxy.cjs");
const fetchLog = join(root, "controlled-fetches.jsonl");
buildPrivateCursorCloudProxy(proxyPath);
const providerNodeCommand = await privateCloudNodeCommand(root);
const runId = "run-22222222-2222-4222-8222-222222222222";
const fixture = Buffer.from(`;(() => {
const assert = require('node:assert/strict'), fs = require('node:fs');
let agentId = '', status = 'RUNNING';
const now = '2026-10-28T00:00:00Z', runId = ${JSON.stringify(runId)};
const json = value => new Response(JSON.stringify(value), { headers: { 'content-type': 'application/json' } });
const run = () => ({ id: runId, agentId, status, createdAt: now, updatedAt: now });
globalThis.fetch = async (input, init = {}) => {
const target = new URL(String(input)); assert.equal(target.origin, 'https://api.cursor.com');
const path = target.pathname, method = init.method ?? 'GET';
fs.appendFileSync(${JSON.stringify(fetchLog)}, JSON.stringify({ method, path }) + '\\n', { mode: 0o600 });
if (path === '/v1/agents' && method === 'POST') {
if (${planning}) {
const body = JSON.parse(String(init.body));
assert.equal(body.mode, 'agent');
const envelope = JSON.parse(body.prompt.text.split('\\n\\nPaperclip task:\\n').at(-1));
assert.equal(envelope.executionMode, 'plan');
assert.equal(envelope.task.workMode, 'planning');
assert.equal(envelope.planningContext.baseRevisionId, 'plan-revision-3');
assert.equal(envelope.planningContext.markdown, '# Pinned canonical plan');
}
agentId = JSON.parse(String(init.body)).agentId;
return json({ agent: { id: agentId, status: 'ACTIVE', env: { type: 'cloud' }, url: 'https://cursor.com/agents/' + agentId, createdAt: now, updatedAt: now, latestRunId: runId }, run: run() });
}
assert.equal(path.startsWith('/v1/agents/' + agentId + '/runs/' + runId), true);
if (path.endsWith('/stream') && method === 'GET') return new Response(new ReadableStream({ start(controller) {
init.signal?.addEventListener('abort', () => { try { controller.close(); } catch {} }, { once: true });
} }), { headers: { 'content-type': 'text/event-stream' } });
if (path.endsWith('/cancel') && method === 'POST') { await new Promise(resolve => setTimeout(resolve, ${terminalDelayMs})); status = 'FINISHED'; return json({ id: runId }); }
if (path.endsWith('/' + runId) && method === 'GET') return json(run());
throw new Error('Unexpected controlled Cloud request');
};
})();\n`);
const builtProxy = await readFile(proxyPath);
const firstLine = builtProxy.indexOf(10) + 1;
await writeFile(proxyPath, Buffer.concat([builtProxy.subarray(0, firstLine), fixture, builtProxy.subarray(firstLine)]), { mode: 0o600 });
await mkdir(runtime, { mode: 0o700 });
const normalizedSessionId = "cloud-question-session";
const cursorCloud = { schema: "paperclip.cursor-cloud.config.v1" as const, repos: [{ url: "https://github.com/example/repo" }] };
await writeFile(configPath, JSON.stringify({ ...cursorCloud, binding: { companyId: "company", agentId: "agent", issueId: "issue", normalizedSessionId } }), { mode: 0o600 });
let authority: DurablePrpControlPlane | undefined;
const bundle = createRunnerdCodexTransport({
provider: "cursor_cloud", cursorCloud, stateDirectory: join(root, "runner-session"),
runnerBinary: defaultCapabilityRunnerdBinary(), providerNodeCommand, cursorCloudProxyPath: proxyPath,
cursorCloudProxySha256: `sha256:${createHash("sha256").update(await readFile(proxyPath)).digest("hex")}`,
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
prpIdentity: { runnerInstanceId: "runner-cloud-question", environmentLeaseId: "lease-cloud-question",
runId: "00000000-0000-4000-8000-000000000763", normalizedSessionId, turnId: "turn-cloud-question", itemId: "item-cloud-question" },
environment: {
PATH: process.env.PATH, CURSOR_API_KEY: "synthetic-cloud-launch-key",
PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH: configPath, PAPERCLIP_CURSOR_CLOUD_ARTIFACT_ROOT: join(runtime, "artifacts"),
PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH: socketPath, PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN: "synthetic-cloud-relay-token",
PAPERCLIP_CURSOR_CLOUD_RELAY_URL: "https://relay.example.test/mcp", PAPERCLIP_CURSOR_CLOUD_RELAY_EXPIRES_AT: String(Date.now() + 60_000),
},
controlPlaneRegistration: async core => { authority = core; await core.start(); return { release: () => undefined }; },
});
const questionApplied = vi.fn(async () => ({ success: true, contentItems: [{ type: "inputText", text: JSON.stringify({ status: "applied", questionId: "question-controlled" }) }] }));
bundle.transport.setServerRequestHandler(questionApplied);
const mcp = async (body: Record<string, unknown>, sessionId?: string): Promise<{ sessionId?: string; value: any }> => {
const scopeHeader = await currentCloudScopeHeader(runtime, normalizedSessionId);
return new Promise((accept, reject) => {
const req = request({ socketPath, path: "/mcp", method: "POST", headers: { Authorization: "Bearer synthetic-cloud-relay-token", [RUNNER_TOOL_SCOPE_TOKEN_HEADER]: scopeHeader, "content-type": "application/json", ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}) } }, response => {
let text = "";
response.on("data", chunk => { text += chunk; });
response.on("end", () => accept({ sessionId: response.headers["mcp-session-id"] as string | undefined, value: JSON.parse(text) }));
});
req.on("error", reject);
req.end(JSON.stringify({ jsonrpc: "2.0", ...body }));
});
};
try {
if (governed) {
await writeFile(join(root, "AGENTS.md"), "Keep assigned instructions.");
const digest = "0".repeat(64);
const context = {
prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: root, fileCount: 1, totalBytes: 27 } },
skills: [], mcp: { assignmentSetId: "none", digest, bindingId: null },
};
const input: NativeExecutionInputV5 = {
schema: "paperclip.native-execution-input.v5", executionMode: planning ? "plan" : "default",
planningContext: planning ? { documentId: "plan-document", baseRevisionId: "plan-revision-3", baseRevisionNumber: 3,
markdown: "# Pinned canonical plan", sha256: createHash("sha256").update("# Pinned canonical plan").digest("hex"), reviewContext: { feedback: "Keep the requested scope" } } : null,
binding: { companyId: "company", agentId: "agent", issueId: "issue", runId: "00000000-0000-4000-8000-000000000763", executionWorkspaceId: "workspace" },
task: { identifier: "CLOUD-QUESTION", title: "Ask the assigned question", description: null, prompt: "Ask before proceeding.", workMode: planning ? "planning" : "standard" },
workspace: { cwd: root, repoUrl: null, repoRef: null, branchName: null },
session: { normalizedSessionId, driverKind: "cursor_cloud_api", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
provider: { kind: "cursor_cloud", model: "explicit-model", cursorCloud },
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
completionContract: { id: "contract", sha256: digest, schemaVersion: "paperclip.completion-contract.v1", contract: { revision: "1", objective: "Ask before proceeding.", criteria: [{ id: "question", requirement: "Request the response." }] } },
interactionResponses: [], credentialBindings: [],
};
const yielded: PrpStructuredRunResult = {
schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", summary: "Waiting for the requested response.",
completionClaim: { contractRevision: "1", objectiveSatisfied: false, criteria: [{ criterionId: "question", status: "unknown", evidenceRefs: ["interaction:pending"] }], remainingWork: [{ description: "Resume after the response.", blocksCompletion: true }] },
evidence: [{ ref: "interaction:pending" }], verification: [], attentionRequests: [], artifacts: [{ kind: "issue_thread_interaction", ref: "interaction:pending" }],
continuation: { kind: "response_wake", summary: "Resume from the answer.", idempotencyKey: "interaction-response:pending" },
};
const backend = createRunnerdNativeSessionBackend(input, { runnerInstanceId: "runner-cloud-question", transportFactory: () => bundle.transport,
dynamicTools: [{ name: "request_human_input", description: "Ask the user a required question.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }],
dynamicToolHandler: questionApplied,
});
const history: PrpEvent[] = [];
const completeRun = vi.fn(async () => undefined);
const execution = executeNativeSession({ input, backend, runnerInstanceId: "runner-cloud-question", controlPlaneInstanceId: "control-cloud-question", timeoutMs: 120_000,
controlPlane: {
async openRun() {}, async checkpointSession() {}, completeRun,
async appendEvent(event: PrpEvent) { history.push(event); return { cursor: history.length, highestContiguousSourceSeq: event.sourceSeq, disposition: "committed" }; },
async replayEvents(replay) { return { events: history.filter(event => event.sourceInstanceId === replay.sourceInstanceId && event.sourceSeq > replay.afterSourceSeq), highestContiguousSourceSeq: 0 }; },
},
resolveGovernedWait: ({ event }) => event.eventType === "item.completed" && event.payload.kind === "dynamicToolCall" ? yielded : null,
});
void execution.catch(() => undefined);
await Promise.race([execution, vi.waitFor(() => expect(authority?.store.state.commands.some(command => command.type === "turn.start" && command.status === "completed")).toBe(true), { timeout: 10_000 })]);
const initialized = await mcp({ id: 0, method: "initialize" });
const response = await mcp({ id: 1, method: "tools/call", params: { name: "request_human_input", arguments: {} } }, initialized.sessionId);
expect(response.value.result.isError).not.toBe(true);
await expect(execution).resolves.toMatchObject({ result: yielded });
expect(completeRun).toHaveBeenCalledOnce();
expect(history.some(event => event.eventType === "turn.interrupted")).toBe(true);
} else {
const opened = await bundle.transport.request("thread/start", { cwd: root, model: "explicit-model", baseInstructions: "Ask the assigned question.", dynamicTools: [{ name: "request_human_input", description: "Ask the user a required question.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }] });
const threadId = (opened.thread as { id: string }).id;
const started = await bundle.transport.request("turn/start", { threadId, input: [{ type: "text", text: "Ask before proceeding." }] });
const initialized = await mcp({ id: 0, method: "initialize" });
const response = await mcp({ id: 1, method: "tools/call", params: { name: "request_human_input", arguments: {} } }, initialized.sessionId);
expect(response.value.result.isError).not.toBe(true);
expect(JSON.stringify(response.value)).toContain("question-controlled");
expect(questionApplied).toHaveBeenCalledOnce();
await bundle.transport.request("turn/interrupt", { threadId, turnId: (started.turn as { id: string }).id });
await vi.waitFor(() => expect(authority!.store.state.committedEvents.some(event => event.eventType === "turn.interrupted")).toBe(true), { timeout: 5_000 });
expect(authority!.store.state.commands.some(command => command.type === "turn.stop")).toBe(false);
expect(authority!.store.state.committedEvents.filter(event => ["turn.interrupted", "turn.completed", "turn.failed"].includes(event.eventType))).toHaveLength(1);
expect(authority!.store.state.commands.filter(command => command.type === "semantic_tool.result")).toHaveLength(1);
}
await bundle.transport.close();
expect(bundle.evidence().runnerExited).toBe(true);
await expect(stat(socketPath)).rejects.toHaveProperty("code", "ENOENT");
const calls = (await readFile(fetchLog, "utf8")).trim().split("\n").map(line => JSON.parse(line));
expect(calls.filter(call => call.path === "/v1/agents" && call.method === "POST")).toHaveLength(1);
expect(calls.filter(call => call.path.endsWith("/cancel") && call.method === "POST")).toHaveLength(1);
} finally {
await bundle.transport.close().catch(() => undefined);
await authority?.stop();
await rm(root, { recursive: true, force: true });
}
}
it.each([0, 18_000])("delivers an applied Cloud question and courtesy-interrupt terminal without Stop (%ims)", async terminalDelayMs => {
await cloudQuestionHandoff(terminalDelayMs, false);
}, 40_000);
it.each([0, 18_000])("settles a governed Cloud question after its allowed cancellation latency (%ims)", async terminalDelayMs => {
await cloudQuestionHandoff(terminalDelayMs, true);
}, 45_000);
it("preserves semantic planning and its pinned revision through the real Rust Cloud default harness", async () => {
await cloudQuestionHandoff(0, true, true);
}, 30_000);
async function cloudColdAuthorityRotation(instructions: string, validShutdown = true) {
const root = await mkdtemp("/tmp/cc-cold-rotation-");
const runtime = join(root, "cloud");
@@ -0,0 +1,183 @@
import { createHash } from "node:crypto";
import { RUNNER_TOOL_SCOPE_TOKEN_HEADER } from "../drivers/runner-tool-bridge.js";
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { request } from "node:http";
import { expect, it, vi } from "vitest";
import { createRunnerdNativeSessionBackend } from "../backends/codex-native-backend.js";
import type { NativeExecutionInputV5 } from "../contracts/native-execution.js";
import { canonicalNativeRuntimeContextDigest, NATIVE_RUNTIME_ASSET_SCHEMA, PAPERCLIP_EXECUTION_PROMPT, PAPERCLIP_EXECUTION_PROMPT_REVISION, nativeRuntimePromptDigest } from "../contracts/runtime-context.js";
import { executeNativeSession } from "../native-session-runtime.js";
import type { PrpEvent, PrpStructuredRunResult } from "../protocol/replay-contract.js";
import type { DurablePrpControlPlane } from "./durable-prp-control-plane.js";
import { createRunnerdCodexTransport, defaultCapabilityRunnerdBinary } from "../live/runnerd-codex-transport.js";
import { buildPrivateCursorCloudProxy, currentCloudScopeHeader, privateCloudNodeCommand } from "./cursor-cloud-runner.harness.js";
async function cloudQuestionHandoff(terminalDelayMs: number, governed: boolean, planning = false) {
const root = await mkdtemp("/tmp/cc-question-");
const runtime = join(root, "cloud");
const configPath = join(runtime, "config.json");
const socketPath = join(root, "mcp.sock");
const proxyPath = join(root, "cloud-proxy.cjs");
const fetchLog = join(root, "controlled-fetches.jsonl");
buildPrivateCursorCloudProxy(proxyPath);
const providerNodeCommand = await privateCloudNodeCommand(root);
const runId = "run-22222222-2222-4222-8222-222222222222";
const fixture = Buffer.from(`;(() => {
const assert = require('node:assert/strict'), fs = require('node:fs');
let agentId = '', status = 'RUNNING';
const now = '2026-10-28T00:00:00Z', runId = ${JSON.stringify(runId)};
const json = value => new Response(JSON.stringify(value), { headers: { 'content-type': 'application/json' } });
const run = () => ({ id: runId, agentId, status, createdAt: now, updatedAt: now });
globalThis.fetch = async (input, init = {}) => {
const target = new URL(String(input)); assert.equal(target.origin, 'https://api.cursor.com');
const path = target.pathname, method = init.method ?? 'GET';
fs.appendFileSync(${JSON.stringify(fetchLog)}, JSON.stringify({ method, path }) + '\\n', { mode: 0o600 });
if (path === '/v1/agents' && method === 'POST') {
if (${planning}) {
const body = JSON.parse(String(init.body));
assert.equal(body.mode, 'agent');
const envelope = JSON.parse(body.prompt.text.split('\\n\\nPaperclip task:\\n').at(-1));
assert.equal(envelope.executionMode, 'plan');
assert.equal(envelope.task.workMode, 'planning');
assert.equal(envelope.planningContext.baseRevisionId, 'plan-revision-3');
assert.equal(envelope.planningContext.markdown, '# Pinned canonical plan');
}
agentId = JSON.parse(String(init.body)).agentId;
return json({ agent: { id: agentId, status: 'ACTIVE', env: { type: 'cloud' }, url: 'https://cursor.com/agents/' + agentId, createdAt: now, updatedAt: now, latestRunId: runId }, run: run() });
}
assert.equal(path.startsWith('/v1/agents/' + agentId + '/runs/' + runId), true);
if (path.endsWith('/stream') && method === 'GET') return new Response(new ReadableStream({ start(controller) {
init.signal?.addEventListener('abort', () => { try { controller.close(); } catch {} }, { once: true });
} }), { headers: { 'content-type': 'text/event-stream' } });
if (path.endsWith('/cancel') && method === 'POST') { await new Promise(resolve => setTimeout(resolve, ${terminalDelayMs})); status = 'FINISHED'; return json({ id: runId }); }
if (path.endsWith('/' + runId) && method === 'GET') return json(run());
throw new Error('Unexpected controlled Cloud request');
};
})();\n`);
const builtProxy = await readFile(proxyPath);
const firstLine = builtProxy.indexOf(10) + 1;
await writeFile(proxyPath, Buffer.concat([builtProxy.subarray(0, firstLine), fixture, builtProxy.subarray(firstLine)]), { mode: 0o600 });
await mkdir(runtime, { mode: 0o700 });
const normalizedSessionId = "cloud-question-session";
const cursorCloud = { schema: "paperclip.cursor-cloud.config.v1" as const, repos: [{ url: "https://github.com/example/repo" }] };
await writeFile(configPath, JSON.stringify({ ...cursorCloud, binding: { companyId: "company", agentId: "agent", issueId: "issue", normalizedSessionId } }), { mode: 0o600 });
let authority: DurablePrpControlPlane | undefined;
const bundle = createRunnerdCodexTransport({
provider: "cursor_cloud", cursorCloud, stateDirectory: join(root, "runner-session"),
runnerBinary: defaultCapabilityRunnerdBinary(), providerNodeCommand, cursorCloudProxyPath: proxyPath,
cursorCloudProxySha256: `sha256:${createHash("sha256").update(await readFile(proxyPath)).digest("hex")}`,
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
prpIdentity: { runnerInstanceId: "runner-cloud-question", environmentLeaseId: "lease-cloud-question",
runId: "00000000-0000-4000-8000-000000000763", normalizedSessionId, turnId: "turn-cloud-question", itemId: "item-cloud-question" },
environment: {
PATH: process.env.PATH, CURSOR_API_KEY: "synthetic-cloud-launch-key",
PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH: configPath, PAPERCLIP_CURSOR_CLOUD_ARTIFACT_ROOT: join(runtime, "artifacts"),
PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH: socketPath, PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN: "synthetic-cloud-relay-token",
PAPERCLIP_CURSOR_CLOUD_RELAY_URL: "https://relay.example.test/mcp", PAPERCLIP_CURSOR_CLOUD_RELAY_EXPIRES_AT: String(Date.now() + 60_000),
},
controlPlaneRegistration: async core => { authority = core; await core.start(); return { release: () => undefined }; },
});
const questionApplied = vi.fn(async () => ({ success: true, contentItems: [{ type: "inputText", text: JSON.stringify({ status: "applied", questionId: "question-controlled" }) }] }));
bundle.transport.setServerRequestHandler(questionApplied);
const mcp = async (body: Record<string, unknown>, sessionId?: string): Promise<{ sessionId?: string; value: any }> => {
const scopeHeader = await currentCloudScopeHeader(runtime, normalizedSessionId);
return new Promise((accept, reject) => {
const req = request({ socketPath, path: "/mcp", method: "POST", headers: { Authorization: "Bearer synthetic-cloud-relay-token", [RUNNER_TOOL_SCOPE_TOKEN_HEADER]: scopeHeader, "content-type": "application/json", ...(sessionId ? { "Mcp-Session-Id": sessionId } : {}) } }, response => {
let text = "";
response.on("data", chunk => { text += chunk; });
response.on("end", () => accept({ sessionId: response.headers["mcp-session-id"] as string | undefined, value: JSON.parse(text) }));
});
req.on("error", reject);
req.end(JSON.stringify({ jsonrpc: "2.0", ...body }));
});
};
try {
if (governed) {
await writeFile(join(root, "AGENTS.md"), "Keep assigned instructions.");
const digest = "0".repeat(64);
const context = {
prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: root, fileCount: 1, totalBytes: 27 } },
skills: [], mcp: { assignmentSetId: "none", digest, bindingId: null },
};
const input: NativeExecutionInputV5 = {
schema: "paperclip.native-execution-input.v5", executionMode: planning ? "plan" : "default",
planningContext: planning ? { documentId: "plan-document", baseRevisionId: "plan-revision-3", baseRevisionNumber: 3,
markdown: "# Pinned canonical plan", sha256: createHash("sha256").update("# Pinned canonical plan").digest("hex"), reviewContext: { feedback: "Keep the requested scope" } } : null,
binding: { companyId: "company", agentId: "agent", issueId: "issue", runId: "00000000-0000-4000-8000-000000000763", executionWorkspaceId: "workspace" },
task: { identifier: "CLOUD-QUESTION", title: "Ask the assigned question", description: null, prompt: "Ask before proceeding.", workMode: planning ? "planning" : "standard" },
workspace: { cwd: root, repoUrl: null, repoRef: null, branchName: null },
session: { normalizedSessionId, driverKind: "cursor_cloud_api", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
provider: { kind: "cursor_cloud", model: "explicit-model", cursorCloud },
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
completionContract: { id: "contract", sha256: digest, schemaVersion: "paperclip.completion-contract.v1", contract: { revision: "1", objective: "Ask before proceeding.", criteria: [{ id: "question", requirement: "Request the response." }] } },
interactionResponses: [], credentialBindings: [],
};
const yielded: PrpStructuredRunResult = {
schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", summary: "Waiting for the requested response.",
completionClaim: { contractRevision: "1", objectiveSatisfied: false, criteria: [{ criterionId: "question", status: "unknown", evidenceRefs: ["interaction:pending"] }], remainingWork: [{ description: "Resume after the response.", blocksCompletion: true }] },
evidence: [{ ref: "interaction:pending" }], verification: [], attentionRequests: [], artifacts: [{ kind: "issue_thread_interaction", ref: "interaction:pending" }],
continuation: { kind: "response_wake", summary: "Resume from the answer.", idempotencyKey: "interaction-response:pending" },
};
const backend = createRunnerdNativeSessionBackend(input, { runnerInstanceId: "runner-cloud-question", transportFactory: () => bundle.transport,
dynamicTools: [{ name: "request_human_input", description: "Ask the user a required question.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }],
dynamicToolHandler: questionApplied,
});
const history: PrpEvent[] = [];
const completeRun = vi.fn(async () => undefined);
const execution = executeNativeSession({ input, backend, runnerInstanceId: "runner-cloud-question", controlPlaneInstanceId: "control-cloud-question", timeoutMs: 120_000,
controlPlane: {
async openRun() {}, async checkpointSession() {}, completeRun,
async appendEvent(event: PrpEvent) { history.push(event); return { cursor: history.length, highestContiguousSourceSeq: event.sourceSeq, disposition: "committed" }; },
async replayEvents(replay) { return { events: history.filter(event => event.sourceInstanceId === replay.sourceInstanceId && event.sourceSeq > replay.afterSourceSeq), highestContiguousSourceSeq: 0 }; },
},
resolveGovernedWait: ({ event }) => event.eventType === "item.completed" && event.payload.kind === "dynamicToolCall" ? yielded : null,
});
void execution.catch(() => undefined);
await Promise.race([execution, vi.waitFor(() => expect(authority?.store.state.commands.some(command => command.type === "turn.start" && command.status === "completed")).toBe(true), { timeout: 10_000 })]);
const initialized = await mcp({ id: 0, method: "initialize" });
const response = await mcp({ id: 1, method: "tools/call", params: { name: "request_human_input", arguments: {} } }, initialized.sessionId);
expect(response.value.result.isError).not.toBe(true);
await expect(execution).resolves.toMatchObject({ result: yielded });
expect(completeRun).toHaveBeenCalledOnce();
expect(history.some(event => event.eventType === "turn.interrupted")).toBe(true);
} else {
const opened = await bundle.transport.request("thread/start", { cwd: root, model: "explicit-model", baseInstructions: "Ask the assigned question.", dynamicTools: [{ name: "request_human_input", description: "Ask the user a required question.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }] });
const threadId = (opened.thread as { id: string }).id;
const started = await bundle.transport.request("turn/start", { threadId, input: [{ type: "text", text: "Ask before proceeding." }] });
const initialized = await mcp({ id: 0, method: "initialize" });
const response = await mcp({ id: 1, method: "tools/call", params: { name: "request_human_input", arguments: {} } }, initialized.sessionId);
expect(response.value.result.isError).not.toBe(true);
expect(JSON.stringify(response.value)).toContain("question-controlled");
expect(questionApplied).toHaveBeenCalledOnce();
await bundle.transport.request("turn/interrupt", { threadId, turnId: (started.turn as { id: string }).id });
await vi.waitFor(() => expect(authority!.store.state.committedEvents.some(event => event.eventType === "turn.interrupted")).toBe(true), { timeout: 5_000 });
expect(authority!.store.state.commands.some(command => command.type === "turn.stop")).toBe(false);
expect(authority!.store.state.committedEvents.filter(event => ["turn.interrupted", "turn.completed", "turn.failed"].includes(event.eventType))).toHaveLength(1);
expect(authority!.store.state.commands.filter(command => command.type === "semantic_tool.result")).toHaveLength(1);
}
await bundle.transport.close();
expect(bundle.evidence().runnerExited).toBe(true);
await expect(stat(socketPath)).rejects.toHaveProperty("code", "ENOENT");
const calls = (await readFile(fetchLog, "utf8")).trim().split("\n").map(line => JSON.parse(line));
expect(calls.filter(call => call.path === "/v1/agents" && call.method === "POST")).toHaveLength(1);
expect(calls.filter(call => call.path.endsWith("/cancel") && call.method === "POST")).toHaveLength(1);
} finally {
await bundle.transport.close().catch(() => undefined);
await authority?.stop();
await rm(root, { recursive: true, force: true });
}
}
it.each([0, 18_000])("delivers an applied Cloud question and courtesy-interrupt terminal without Stop (%ims)", async terminalDelayMs => {
await cloudQuestionHandoff(terminalDelayMs, false);
}, 40_000);
it.each([0, 18_000])("settles a governed Cloud question after its allowed cancellation latency (%ims)", async terminalDelayMs => {
await cloudQuestionHandoff(terminalDelayMs, true);
}, 45_000);
it("preserves semantic planning and its pinned revision through the real Rust Cloud default harness", async () => {
await cloudQuestionHandoff(0, true, true);
}, 30_000);
@@ -0,0 +1,35 @@
import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process";
import { mkdir, readFile, rename } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { expect } from "vitest";
import { copyOwnedNodeRuntime } from "../test-support/owned-node-runtime.js";
export async function privateCloudNodeCommand(root: string): Promise<string> {
const directory = join(root, "provider-node");
await mkdir(directory, { mode: 0o700 });
const { executable } = await copyOwnedNodeRuntime(directory);
// Keep Node's name so the verified launcher selects its descriptor loader.
const command = join(directory, process.platform === "win32" ? "node.exe" : "node");
await rename(executable, command);
return command;
}
export function buildPrivateCursorCloudProxy(proxyPath: string): void {
const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
const builderUrl = new URL("../../scripts/build-verified-provider-entrypoints.mjs", import.meta.url).href;
execFileSync(process.execPath, ["--input-type=module", "-e", [
"import { writeFile } from 'node:fs/promises';",
`const { bundleVerifiedProviderEntrypoints } = await import(${JSON.stringify(builderUrl)});`,
"const item = (await bundleVerifiedProviderEntrypoints({ write: false })).find(value => value.entrypoint.name === 'cursor-cloud-app-server-proxy');",
`await writeFile(${JSON.stringify(proxyPath)}, item.verifiedResult.outputFiles[0].contents, { mode: 0o600 });`,
].join("\n")], { cwd: packageRoot, timeout: 20_000, stdio: "pipe" });
}
export async function currentCloudScopeHeader(runtime: string, sessionId: string): Promise<string> {
const name = `checkpoint-${createHash("sha256").update(sessionId).digest("hex")}.json`;
const checkpoint = JSON.parse(await readFile(join(runtime, name), "utf8"));
expect(checkpoint.relayTurnToken).toMatch(/^[A-Za-z0-9_-]{43}$/);
return `Bearer ${checkpoint.relayTurnToken}`;
}