mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 03:36:57 +01:00
Integrate pinned Cursor ACP runtime and explicit public setup
Consolidate Cursor v10 onto current controller behavior, retain admission gates, and prepare native interaction and cleanup qualification. Add the public provisioner and ordinary provider-pack assets. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
2a8a99e4a5
commit
e2b89b6302
199 files changed
+20293
-851
No files matched your search
@@ -0,0 +1,9 @@
|
||||
/** The embedded driver and runtime sidecar are the two production ACPX bridges.
|
||||
* Keep provider and native method exact; semantic tools are not native proof.
|
||||
*/
|
||||
export function hasAcpxNativeOrigin(origin: unknown, provider: string, method: string): boolean {
|
||||
if (origin === null || typeof origin !== "object" || Array.isArray(origin)) return false;
|
||||
const value = origin as Record<string, unknown>;
|
||||
return (value.adapter === "acpx-runtime" || value.adapter === "acpx-runtime-sidecar")
|
||||
&& value.provider === provider && value.method === method;
|
||||
}
|
||||
+19
-3
@@ -9,6 +9,22 @@ async function failureMessage(response: APIResponse, method: string) {
|
||||
return `${method} ${response.url()} returned ${response.status()}${text ? `: ${text}` : ""}`;
|
||||
}
|
||||
|
||||
/** Preserve HTTP status independently of diagnostic response text. */
|
||||
export class RunnerApiHttpError extends Error {
|
||||
constructor(readonly status: number, message: string) { super(message); this.name = "RunnerApiHttpError"; }
|
||||
}
|
||||
|
||||
/** Admission-only diagnostics. Never retain the rejected value or its cause. */
|
||||
export class RemoteAdmissionReadError extends Error {
|
||||
constructor(
|
||||
readonly endpoint: "issue" | "run" | "leases",
|
||||
readonly failureClass: "candidate_failure" | "transient_infrastructure" | "permanent_infrastructure",
|
||||
) {
|
||||
super(`Remote admission ${endpoint} read failed (${failureClass}); diagnostics withheld`);
|
||||
this.name = "RemoteAdmissionReadError";
|
||||
}
|
||||
}
|
||||
|
||||
export class RunnerApi {
|
||||
readonly baseURL: string;
|
||||
|
||||
@@ -18,9 +34,9 @@ export class RunnerApi {
|
||||
this.baseURL = `http://127.0.0.1:${port}`;
|
||||
}
|
||||
|
||||
async get<T>(path: string): Promise<T> {
|
||||
const response = await this.request.get(path);
|
||||
if (!response.ok()) throw new Error(await failureMessage(response, "GET"));
|
||||
async get<T>(path: string, options?: { timeout: number }): Promise<T> {
|
||||
const response = await (options ? this.request.get(path, options) : this.request.get(path));
|
||||
if (!response.ok()) throw new RunnerApiHttpError(response.status(), await failureMessage(response, "GET"));
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
|
||||
@@ -136,10 +136,10 @@ describe("runner E2E catalog", () => {
|
||||
expect(localIntegrityTasks).toHaveLength(2);
|
||||
expect(openRouterBreadthTasks).toHaveLength(3);
|
||||
expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([
|
||||
6, 30, 3, 16, 16, 2, 6, 8, 46, 23, 50, 6, 20, 26, 52, 28, 18, 2, 6, 6, 12, 10, 48, 16, 10, 2, 1, 1,
|
||||
6, 8, 2, 2, 30, 3, 16, 16, 2, 6, 8, 46, 23, 50, 6, 20, 26, 52, 28, 18, 2, 6, 6, 12, 10, 48, 16, 10, 2, 1, 1,
|
||||
]);
|
||||
expect(validateRunnerCatalog()).toHaveLength(470);
|
||||
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(470);
|
||||
expect(validateRunnerCatalog()).toHaveLength(482);
|
||||
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(482);
|
||||
expect(
|
||||
runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"),
|
||||
).toHaveLength(48);
|
||||
|
||||
@@ -2,6 +2,8 @@ import { nativeCompletionTasks, nativeCompletionDefinitionDigest } from "./nativ
|
||||
import { nativeCompletionProfile, NATIVE_COMPLETION_BUDGET_CENTS } from "./native-completion-defaults.js";
|
||||
import { chatConfirmationTasks } from "./chat-cases.js";
|
||||
import { hiringTemplateTasks, hiringTemplateProfile, hiringTemplateDefinitionDigest } from "./hiring-template-cases.js";
|
||||
import { nativeActiveStopTasks } from "./native-active-stop-tasks.js";
|
||||
import { cursorNativeTasks } from "./cursor-native-cases.js";
|
||||
import { instructionPersistenceTask } from "./instruction-persistence.js";
|
||||
import { apiResponseReadingTask } from "./api-response-reading.js";
|
||||
import { taskTitleTasks, taskTitleDefinitionDigest, TASK_TITLE_BUDGET_CENTS } from "./task-titles.js";
|
||||
@@ -987,7 +989,7 @@ export const daytonaWarmContinuityTask: RunnerTaskFixture = {
|
||||
{ kind: "issue_status", expected: "done" },
|
||||
{ kind: "run_status", expected: "succeeded" },
|
||||
{ kind: "runtime_mode", expected: execution.profile.expectedRuntimeMode },
|
||||
{ kind: "environment", expected: "daytona" },
|
||||
{ kind: "environment", expected: execution.environment.id },
|
||||
];
|
||||
},
|
||||
};
|
||||
@@ -1088,6 +1090,33 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [
|
||||
environments: [localEnvironment], tasks: blockerTasks, expectedMatrixSize: 6,
|
||||
definitionMetadata: { version: 1, instructions: "production-coordination-skill", grading: "saved-human-decision-ownership-and-resume", scheduling: "explicit-only" },
|
||||
},
|
||||
{
|
||||
id: "cursor-native", label: "Cursor native interactions", manualOnly: true,
|
||||
description: "Native question continuation, revision-bound plan decisions and restrictive permission denial with independent process and file evidence.",
|
||||
groups: ["native"], profiles: extendedHarnessProfiles.filter(profile => profile.qualificationCandidate === "cursor"),
|
||||
environments: runnerEnvironments, tasks: cursorNativeTasks, expectedMatrixSize: 8,
|
||||
definitionMetadata: { version: 2, qualification: "pending", scheduling: "explicit-only", profileVersion: QUALIFIED_ACPX_PROFILES.cursor.agentProfileVersion, modeAdmission: "native-config-ack", artifactExport: "pending-private-home", remoteEvidence: "owned-lease-sealed-observer" },
|
||||
},
|
||||
{
|
||||
id: "native-active-stop", label: "Stop an unanswered native permission", manualOnly: true,
|
||||
description: "Stop while one exact Cursor native permission remains unanswered; require cancelled provider settlement, caller-owned acknowledgement, stale-answer refusal and independent retirement/no effects.",
|
||||
groups: ["native"], profiles: extendedHarnessProfiles.filter(profile => profile.qualificationCandidate === "cursor"),
|
||||
environments: runnerEnvironments, tasks: nativeActiveStopTasks, expectedMatrixSize: 2,
|
||||
definitionMetadata: { version: 4, qualification: "pending", scheduling: "explicit-only", evidence: "paperclip.e2e.native-active-stop-settlement.v2", pendingObservation: "retained-api-before-caller-uuid-stop", normalCompletionAccepted: false, permissionPolicy: "approve-reads", lifecycle: "per_turn", remoteEvidence: "paperclip.e2e.native-active-stop-remote-retirement.v1", remoteObservationCoverage: "continuous-through-owned-process-retirement", filesystemAfterRemoteRetirementObserved: false, localObservationCoverage: "four-phases-through-cleanup", providerDeath: "not-covered" },
|
||||
},
|
||||
{
|
||||
id: "rich-acp-warm-continuity", label: "Rich ACP warm continuity", manualOnly: true,
|
||||
description: "Three browser-driven turns with stable native session, runner process and workspace identity for Cursor.",
|
||||
groups: ["native", "warm"],
|
||||
profiles: extendedHarnessProfiles.filter(profile => profile.qualificationCandidate === "cursor").map(profile => ({ ...profile, buildAgent(input: AgentFixtureBuildInput) {
|
||||
const agent = profile.buildAgent(input);
|
||||
return { ...agent, adapterConfig: { ...agent.adapterConfig as Record<string, unknown>, lifecycleMode: "warm", idleTimeoutMs: 300_000 } };
|
||||
} })),
|
||||
environments: [localEnvironment, daytonaWarmEnvironment],
|
||||
tasks: [{ ...daytonaWarmContinuityTask, turnTimeoutMs: 120_000, attemptTimeoutMs: { local: 420_000, daytona: 420_000 } }],
|
||||
expectedMatrixSize: 2,
|
||||
definitionMetadata: { version: 1, qualification: "pending", scheduling: "explicit-only", identity: "native-session-runner-provider-session-process-start" },
|
||||
},
|
||||
{
|
||||
id: "extended-harnesses", label: "Extended ACP harnesses", manualOnly: true,
|
||||
description: "Explicit candidate qualification through real Paperclip tools, browser interactions, file edits and restart recovery.",
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { runCleanupWithObservers, verifyCleanupAssertions } from "./cleanup-verification.js";
|
||||
|
||||
it("retains a failed cleanup proof and still closes every later observer", async () => {
|
||||
let closed = 0;
|
||||
const result = await verifyCleanupAssertions([
|
||||
async () => { throw new Error("provider still alive"); },
|
||||
async () => [{ id: "no-effect", passed: false, detail: "target changed" }],
|
||||
async () => { closed++; return [{ id: "observer-closed", passed: true, detail: "closed" }]; },
|
||||
]);
|
||||
expect(closed).toBe(1);
|
||||
expect(result.errors).toHaveLength(2);
|
||||
expect(result.checks).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ id: "no-effect", passed: false }),
|
||||
expect.objectContaining({ id: "observer-closed", passed: true }),
|
||||
]));
|
||||
});
|
||||
|
||||
it("refuses an assertion that silently omits its proof", async () => {
|
||||
const result = await verifyCleanupAssertions([async () => []]);
|
||||
expect(result.errors).toHaveLength(1);
|
||||
expect(result.checks[0]?.passed).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
it("collects remote proof before environment destruction, preserving every cleanup error", async () => {
|
||||
const calls: string[] = [];
|
||||
const result = await runCleanupWithObservers({
|
||||
retireRuns: async () => { calls.push("retire"); throw new Error("cancel failed"); },
|
||||
assertions: [
|
||||
async () => { calls.push("proof1"); throw new Error("receipt missing"); },
|
||||
async () => { calls.push("proof2"); return [{ id: "sealed", passed: true, detail: "sealed before deletion" }]; },
|
||||
],
|
||||
teardown: async () => { calls.push("teardown"); throw new Error("delete failed"); },
|
||||
});
|
||||
expect(calls).toEqual(["retire", "proof1", "proof2", "teardown"]);
|
||||
expect(result.errors.map(error => (error as Error).message)).toEqual(["cancel failed", "receipt missing", "delete failed"]);
|
||||
expect(result.checks).toContainEqual({ id: "sealed", passed: true, detail: "sealed before deletion" });
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
export interface CleanupCheck { id: string; passed: boolean; detail: string }
|
||||
export type CleanupAssertion = () => Promise<CleanupCheck[]>;
|
||||
|
||||
/** Always finish every registered observer, even when an earlier proof fails. */
|
||||
export async function verifyCleanupAssertions(assertions: readonly CleanupAssertion[]) {
|
||||
const checks: CleanupCheck[] = [], errors: unknown[] = [];
|
||||
for (const [index, assertion] of assertions.entries()) {
|
||||
try {
|
||||
const result = await assertion();
|
||||
if (!Array.isArray(result) || result.length === 0 || result.some(check =>
|
||||
!check || typeof check.id !== "string" || !check.id || typeof check.passed !== "boolean" || typeof check.detail !== "string")) {
|
||||
throw new Error("Cleanup assertion did not return complete checks");
|
||||
}
|
||||
checks.push(...result);
|
||||
if (result.some(check => !check.passed)) throw new Error("Cleanup assertion reported a failed check");
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
checks.push({ id: `assertion-${index}-completed`, passed: false, detail: error instanceof Error ? error.message : "Cleanup assertion failed" });
|
||||
}
|
||||
}
|
||||
return { checks, errors };
|
||||
}
|
||||
|
||||
/** Collect remote proof before destroying its environment, even if cancellation
|
||||
* fails. A missing proof fails qualification but never skips owned teardown. */
|
||||
export async function runCleanupWithObservers(input: {
|
||||
retireRuns(): Promise<void>;
|
||||
assertions: readonly CleanupAssertion[];
|
||||
teardown(): Promise<void>;
|
||||
}) {
|
||||
const errors: unknown[] = [];
|
||||
try { await input.retireRuns(); } catch (error) { errors.push(error); }
|
||||
const verification = await verifyCleanupAssertions(input.assertions);
|
||||
errors.push(...verification.errors);
|
||||
try { await input.teardown(); } catch (error) { errors.push(error); }
|
||||
return { checks: verification.checks, errors };
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { parsePaperclipQuestionResponse } from "../../packages/paperclip-runner/src/contracts/question-set.js";
|
||||
import { normalizeCursorPlanRequest } from "../../packages/paperclip-runner/src/drivers/acpx/cursor-extensions.js";
|
||||
import { cursorNativePlanResponse, findCursorNativeRequest, hasCursorNativeCardBinding } from "./cursor-native-flow.js";
|
||||
import { cursorDeniedCommand, type CursorToolNotice } from "./cursor-native-evidence.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { cursorNativeCaseDesigns, cursorNativePrompt, hasDeliveredCursorNativeRequest, hasCursorPlanDecision, hasCursorDenialBoundary, CURSOR_DENIAL_SAMPLE_PHASES, hasExactCursorNativeResponse } from "./cursor-native-cases.js";
|
||||
|
||||
const proof = (adapter = "acpx-runtime") => {
|
||||
const wrap = (eventType: string, sourceSeq: number, payload: unknown) => ({ runId: "run", protocolSchemaVersion: 1, payload: { prpEvent: {
|
||||
schema: "paperclip.prp.event.v1", schemaVersion: 1, runId: "run", turnId: "turn", eventType, sourceSeq, payload,
|
||||
} } });
|
||||
return [wrap("runtime_request.created", 1, { request: { requestId: "request", turnId: "turn", type: "input", status: "pending", origin: { adapter, provider: "cursor", method: "cursor/ask_question" } } }),
|
||||
wrap("runtime_request.resolved", 2, { requestId: "request", turnId: "turn", action: "submit" })];
|
||||
};
|
||||
const grade = (events: unknown[]) => hasDeliveredCursorNativeRequest({ events, runId: "run", turnId: "turn", requestId: "request", method: "cursor/ask_question", action: "submit" });
|
||||
describe("prepared Cursor native qualification", () => {
|
||||
it("has four fixed native-only designs and bounded prompts", () => {
|
||||
expect(cursorNativeCaseDesigns).toHaveLength(4);
|
||||
for (const design of cursorNativeCaseDesigns) expect(cursorNativePrompt(design.id, "test-nonce")).toContain("Do not substitute");
|
||||
expect(() => cursorNativePrompt("native-write-deny-reconnect", "../escape")).toThrow();
|
||||
});
|
||||
it("requires correlated native origin and response delivery evidence", () => { expect(grade(proof())).toBe(true); expect(grade([])).toBe(false); });
|
||||
it("rejects semantic substitutions and permission fallbacks", () => {
|
||||
for (const method of ["request_human_input", "session/request_permission", "cursor/create_plan"]) {
|
||||
const rows = proof(); (rows[0]!.payload.prpEvent.payload as any).request.origin.method = method; expect(grade(rows)).toBe(false);
|
||||
}
|
||||
});
|
||||
it("rejects missing, duplicated and expired delivery", () => {
|
||||
const rows = proof(); expect(grade(rows.slice(0, 1))).toBe(false); expect(grade([...rows, rows[1]])).toBe(false);
|
||||
rows[1]!.payload.prpEvent.eventType = "runtime_request.expired"; expect(grade(rows)).toBe(false);
|
||||
});
|
||||
it("rejects mismatched run, turn and event ordering", () => {
|
||||
let rows = proof(); rows[1]!.runId = "foreign"; expect(grade(rows)).toBe(false);
|
||||
rows = proof(); rows[1]!.payload.prpEvent.turnId = "stale"; expect(grade(rows)).toBe(false);
|
||||
rows = proof(); rows[1]!.payload.prpEvent.sourceSeq = 0; expect(grade(rows)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("binds plan decisions to the full revision and rejects stale answers", () => {
|
||||
const id = `plan-${"a".repeat(64)}`;
|
||||
const questionSet = { questions: [{ id }] };
|
||||
const answer = { schema: "paperclip.question_response.v1", answers: { [id]: { selectedOptionIds: ["accept"] } } };
|
||||
expect(hasCursorPlanDecision(questionSet, answer, "accept")).toBe(true);
|
||||
expect(hasCursorPlanDecision({ questions: [{ id: `plan-${"b".repeat(64)}` }] }, answer, "accept")).toBe(false);
|
||||
expect(hasCursorPlanDecision(questionSet, answer, "reject")).toBe(false);
|
||||
});
|
||||
it.each(["acpx-runtime", "acpx-runtime-sidecar"])("requires supported denial choices, native IDs and complete no-effect boundaries via %s", adapter => {
|
||||
const input = { request: { requestId: "request", turnId: "turn", type: "permission", status: "pending", details: { toolCallId: "tool" },
|
||||
origin: { adapter, provider: "cursor", method: "session/request_permission" },
|
||||
choices: [{ key: "accept" }, { key: "decline" }, { key: "cancel" }] }, expectedRequestId: "request", expectedToolCallId: "tool", path: "/fixture/denied.txt", runId: "run", turnId: "turn",
|
||||
notices: ([{ stage: "tool", status: "pending" }, { stage: "permission_requested", requestId: "request", declineOffered: true }, { stage: "permission_delivered", requestId: "request", outcome: "reject_once" }, { stage: "tool", status: "failed" }].map((row, index) => ({ ...row, seq: index + 1, runId: "run", sessionId: "session", turnId: "turn", toolCallId: "tool", operation: "execute", commandSha256: cursorDeniedCommand("/fixture/denied.txt").commandSha256 })) as CursorToolNotice[]),
|
||||
samples: CURSOR_DENIAL_SAMPLE_PHASES.map((phase, observedAt) => ({ phase, observedAt, absent: true, path: "/fixture/denied.txt" })) };
|
||||
expect(hasCursorDenialBoundary(input)).toBe(true);
|
||||
for (const origin of [{ ...input.request.origin, adapter: "semantic" }, { ...input.request.origin, provider: "pi" }, { ...input.request.origin, method: "request_human_input" }]) {
|
||||
expect(hasCursorDenialBoundary({ ...input, request: { ...input.request, origin } })).toBe(false);
|
||||
}
|
||||
expect(hasCursorDenialBoundary({ ...input, samples: input.samples.slice(1) })).toBe(false);
|
||||
expect(hasCursorDenialBoundary({ ...input, expectedToolCallId: "foreign" })).toBe(false);
|
||||
input.samples[2]!.absent = false; expect(hasCursorDenialBoundary(input)).toBe(false); input.samples[2]!.absent = true;
|
||||
input.request.choices.push({ key: "accept_for_session" }); expect(hasCursorDenialBoundary(input)).toBe(false);
|
||||
});
|
||||
|
||||
it("requires exact delivered answer bytes rather than a saved or different answer", () => {
|
||||
const rows = proof(); const response = { schema: "paperclip.question_response.v1", answers: { q: { selectedOptionIds: ["chosen"] } } };
|
||||
(rows[1]!.payload.prpEvent.payload as any).response = response;
|
||||
const input = { events: rows, runId: "run", turnId: "turn", requestId: "request", method: "cursor/ask_question" as const, action: "submit" as const, response };
|
||||
expect(hasExactCursorNativeResponse(input)).toBe(true);
|
||||
expect(hasExactCursorNativeResponse({ ...input, response: { ...response, answers: { q: { selectedOptionIds: ["other"] } } } })).toBe(false);
|
||||
expect(hasExactCursorNativeResponse({ ...input, events: rows.slice(0, 1) })).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
it.each(["accept", "cancel", "reject"] as const)("recognizes canonical delivered native plan %s without an empty optional answer", decision => {
|
||||
const native = normalizeCursorPlanRequest({ toolCallId: "native-plan", plan: "Verify the revised plan.", todos: [] });
|
||||
const planId = native.questionSet.questions[0]!.id;
|
||||
const response = cursorNativePlanResponse(planId, decision, " Keep exact feedback 漢字\nSecond line ");
|
||||
const delivered = parsePaperclipQuestionResponse(native.questionSet, response);
|
||||
const rows = proof();
|
||||
(rows[0]!.payload.prpEvent.payload as any).request.origin.method = "cursor/create_plan";
|
||||
(rows[1]!.payload.prpEvent.payload as any).response = delivered;
|
||||
const input = { events: rows, runId: "run", turnId: "turn", requestId: "request", method: "cursor/create_plan" as const, action: "submit" as const, response };
|
||||
expect(hasCursorPlanDecision(native.questionSet, response, decision)).toBe(true);
|
||||
expect(hasExactCursorNativeResponse(input)).toBe(true);
|
||||
expect(native.resolve(delivered).outcome.outcome).toBe({ accept: "accepted", cancel: "cancelled", reject: "rejected" }[decision]);
|
||||
if (decision === "reject") expect(delivered.answers.reason?.text).toBe(" Keep exact feedback 漢字\nSecond line ");
|
||||
else {
|
||||
expect(delivered.answers).not.toHaveProperty("reason");
|
||||
expect(hasExactCursorNativeResponse({ ...input, response: { ...response, answers: { ...response.answers, reason: {} } } })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
// Retained paid sidecar plan callback exposed both origin and JSONB key-order drift.
|
||||
it.each(["acpx-runtime", "acpx-runtime-sidecar"])("recognizes a native plan and its durable card via %s", adapter => {
|
||||
const input = normalizeCursorPlanRequest({ toolCallId: "native-plan", name: "Fixture plan", plan: "Verify complete Markdown.", todos: [{ id: "first", content: "Read", status: "pending" }, { id: "second", content: "Check", status: "pending" }] }).questionSet;
|
||||
const rows = proof(adapter);
|
||||
const request = (rows[0]!.payload.prpEvent.payload as any).request;
|
||||
request.origin.method = "cursor/create_plan";
|
||||
request.input = input;
|
||||
const event = findCursorNativeRequest(rows, "cursor/create_plan", "request")!;
|
||||
expect(event).toBe(rows[0]!.payload.prpEvent);
|
||||
expect(hasDeliveredCursorNativeRequest({ events: rows, runId: "run", turnId: "turn", requestId: "request", method: "cursor/create_plan", action: "submit" })).toBe(true);
|
||||
const reorder = (value: any): any => Array.isArray(value) ? value.map(reorder) : value !== null && typeof value === "object"
|
||||
? Object.fromEntries(Object.entries(value).reverse().map(([key, nested]) => [key, reorder(nested)])) : value;
|
||||
const card = { sourceRunId: "run", continuationPolicy: "none", payload: { runtimeRequestId: "request", questionSet: reorder(input) } };
|
||||
expect(JSON.stringify(card.payload.questionSet)).not.toBe(JSON.stringify(input));
|
||||
expect(hasCursorNativeCardBinding(card, event, "run")).toBe(true);
|
||||
expect(hasCursorNativeCardBinding(card, event, "other-run")).toBe(false);
|
||||
expect(hasCursorNativeCardBinding({ ...card, continuationPolicy: "resume" }, event, "run")).toBe(false);
|
||||
const changed = structuredClone(card);
|
||||
changed.payload.questionSet.questions[0].options[0].label = "Changed choice";
|
||||
expect(hasCursorNativeCardBinding(changed, event, "run")).toBe(false);
|
||||
const reordered = structuredClone(card);
|
||||
reordered.payload.questionSet.questions[0].options.reverse();
|
||||
expect(hasCursorNativeCardBinding(reordered, event, "run")).toBe(false);
|
||||
expect(findCursorNativeRequest(rows, "cursor/create_plan", "other-request")).toBeUndefined();
|
||||
expect(findCursorNativeRequest(rows, "cursor/ask_question", "request")).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(["acpx-runtime", "acpx-runtime-sidecar"])("rejects foreign native request identity or origin via %s", adapter => {
|
||||
for (const patch of [{ adapter: "unknown" }, { adapter: "acpx-runtime-sidecar-unknown" }, { adapter: "semantic" }, { provider: "pi" }, { method: "request_human_input" }]) {
|
||||
const rows = proof(adapter);
|
||||
Object.assign((rows[0]!.payload.prpEvent.payload as any).request.origin, patch);
|
||||
expect(grade(rows)).toBe(false);
|
||||
expect(findCursorNativeRequest(rows, "cursor/ask_question", "request")).toBeUndefined();
|
||||
}
|
||||
for (const patch of [{ requestId: "foreign" }, { turnId: "stale" }]) {
|
||||
const rows = proof(adapter);
|
||||
Object.assign((rows[0]!.payload.prpEvent.payload as any).request, patch);
|
||||
expect(grade(rows)).toBe(false);
|
||||
}
|
||||
const rows = proof(adapter);
|
||||
expect(grade([...rows, rows[0]!])).toBe(false);
|
||||
expect(grade([...rows, rows[1]!])).toBe(false);
|
||||
rows[1]!.payload.prpEvent.turnId = "stale";
|
||||
expect(grade(rows)).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { hasAcpxNativeOrigin } from "./acpx-native-origin.js";
|
||||
import type { BootstrapReadProof } from "./native-bootstrap-read-proof.js";
|
||||
import { cursorDeniedCommand, hasCursorDeniedCommand, type CursorToolNotice } from "./cursor-native-evidence.js";
|
||||
import type { RunnerTaskFixture } from "./types.js";
|
||||
|
||||
/** Native-only contracts; shared catalog registration is explicit-only.
|
||||
* A successful semantic request_human_input/write_document never satisfies these.
|
||||
* Native question/plan tool availability must first be established on the exact
|
||||
* authenticated model/mode; a prompt cannot force an absent provider tool.
|
||||
*/
|
||||
export const cursorNativeCaseDesigns = [
|
||||
{ id: "native-question-reconnect", method: "cursor/ask_question", cursorMode: "plan", permissionMode: "approve-all", expectedRunCount: 1 },
|
||||
{ id: "native-plan-reject-revise-accept", method: "cursor/create_plan", cursorMode: "plan", permissionMode: "approve-all", expectedRunCount: 1 },
|
||||
{ id: "native-plan-cancel", method: "cursor/create_plan", cursorMode: "plan", permissionMode: "approve-all", expectedRunCount: 1 },
|
||||
{ id: "native-write-deny-reconnect", method: "session/request_permission", cursorMode: "agent", permissionMode: "approve-reads", expectedRunCount: 1 },
|
||||
] as const;
|
||||
export type CursorNativeMethod = typeof cursorNativeCaseDesigns[number]["method"];
|
||||
|
||||
export function cursorNativePrompt(id: typeof cursorNativeCaseDesigns[number]["id"], nonce: string): string {
|
||||
if (!/^[a-z0-9-]{1,80}$/i.test(nonce)) throw new Error("Invalid fixture nonce");
|
||||
const finish = `Finish this negative or interactive test only after its actual native tool result arrives. Use paperclip_finish once with the current completion contract revision and satisfied objective, summary CURSOR-NATIVE-${nonce}, no remaining work, then emit that exact summary. Do not substitute a Paperclip question or plan tool for the native tool.`;
|
||||
if (id === "native-question-reconnect") return [
|
||||
"Call Cursor's native AskQuestion exactly once. Ask two required choice questions: color with IDs cobalt/Cobalt and amber/Amber, and trees with IDs cedar/Cedar and maple/Maple allowing multiple selections. Wait for the actual answers. Do not infer the selected options or answer your own questions.",
|
||||
"Do not write any file. After the actual result, form your completion summary from the returned native option IDs: CURSOR-NATIVE-" + nonce + "-<colorId>-<treeIdsSortedAndJoinedByPlus>. Use that exact computed summary for paperclip_finish and your final answer. The reviewer chooses the options; do not guess them. Do not substitute request_human_input, a permission question, prose, or a command-based prompt. If the native tool is absent, report that limitation without claiming completion.",
|
||||
"Call paperclip_finish once only after the native tool returns, using the current completion contract revision and satisfied objective with no remaining work. Wait for acceptance, then emit the exact computed summary.",
|
||||
].join("\n");
|
||||
if (id === "native-plan-reject-revise-accept" || id === "native-plan-cancel") return [
|
||||
`Use Cursor's native CreatePlan to propose a plan named Cursor native ${nonce} with Markdown, an overview, two stable todo IDs, and a named phase. Begin the Markdown with standalone line CURSOR-PLAN-BEGIN-${nonce} and end with standalone line CURSOR-PLAN-END-${nonce}. Preserve both boundary lines on revision. Do not perform implementation before acceptance.`,
|
||||
"Wait for the actual native decision. If cancelled, stop planning without retry or implementation; cancellation is the expected result of this negative test. If rejected, incorporate its exact feedback into one revised native CreatePlan request and wait again. Do not silently accept your plan, write a Paperclip plan, or substitute a semantic confirmation. If unavailable, report that limitation without claiming completion.", id === "native-plan-reject-revise-accept" ? "After the revised plan is accepted, end this planning turn. Keep the selected Plan mode; do not implement, change modes, call paperclip_finish, or start another turn. The controller must leave this unfinished task waiting for the user’s next message. Do not substitute a semantic confirmation or completion call." : finish,
|
||||
].join("\n");
|
||||
return [
|
||||
`Attempt exactly one native shell operation using the exact command supplied below by the fixture. This is a deliberate denial test. Wait for the actual permission decision. After denial, do not retry, write another path, invoke a fallback tool, call paperclip_finish, or work around the denial. Wait for the operator to cancel this unfinished task. Do not substitute another tool or operation.`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
type JsonRecord = Record<string, unknown>;
|
||||
const record = (value: unknown): JsonRecord => value !== null && typeof value === "object" && !Array.isArray(value) ? value as JsonRecord : {};
|
||||
|
||||
/** Grade public persisted PRP events, not assistant prose or a synthetic wire.
|
||||
* The final Product flow must additionally inspect the real card, its browser
|
||||
* action/reconnect, independent bytes, and the succeeded terminal run.
|
||||
*/
|
||||
export function hasDeliveredCursorNativeRequest(input: {
|
||||
events: readonly unknown[]; runId: string; turnId: string; requestId: string;
|
||||
method: CursorNativeMethod; action: "submit" | "decline";
|
||||
}): boolean {
|
||||
if (![input.runId, input.turnId, input.requestId].every(value => typeof value === "string" && value.trim())) return false;
|
||||
const rows = input.events.map(record).map(row => ({ row, event: record(record(row.payload).prpEvent) }))
|
||||
.filter(({ row, event }) => row.runId === input.runId && event.runId === input.runId
|
||||
&& event.turnId === input.turnId && event.schema === "paperclip.prp.event.v1"
|
||||
&& event.schemaVersion === 1 && row.protocolSchemaVersion === 1);
|
||||
const created = rows.filter(({ event }) => event.eventType === "runtime_request.created"
|
||||
&& record(record(event.payload).request).requestId === input.requestId);
|
||||
if (created.length !== 1) return false;
|
||||
const request = record(record(created[0]!.event.payload).request);
|
||||
const origin = record(request.origin);
|
||||
if (!hasAcpxNativeOrigin(origin, "cursor", input.method)
|
||||
|| request.turnId !== input.turnId || request.status !== "pending") return false;
|
||||
if (input.method === "session/request_permission" ? request.type !== "permission" : request.type !== "input") return false;
|
||||
const outcomes = rows.filter(({ event }) => ["runtime_request.resolved", "runtime_request.expired", "runtime_request.cancelled"].includes(String(event.eventType))
|
||||
&& record(event.payload).requestId === input.requestId);
|
||||
return outcomes.length === 1 && outcomes[0]!.event.eventType === "runtime_request.resolved"
|
||||
&& record(outcomes[0]!.event.payload).action === input.action
|
||||
&& record(outcomes[0]!.event.payload).turnId === input.turnId
|
||||
&& Number.isSafeInteger(created[0]!.event.sourceSeq) && Number.isSafeInteger(outcomes[0]!.event.sourceSeq)
|
||||
&& (created[0]!.event.sourceSeq as number) >= 0
|
||||
&& (outcomes[0]!.event.sourceSeq as number) > (created[0]!.event.sourceSeq as number);
|
||||
}
|
||||
|
||||
/** Decision must address the exact displayed revision, not merely its title. */
|
||||
export function hasCursorPlanDecision(questionSet: unknown, response: unknown, decision: "accept" | "reject" | "cancel"): boolean {
|
||||
const questions = record(questionSet).questions;
|
||||
if (!Array.isArray(questions)) return false;
|
||||
const plans = questions.map(record).filter(question => typeof question.id === "string" && /^plan-[a-f0-9]{64}$/.test(question.id));
|
||||
if (plans.length !== 1) return false;
|
||||
const answers = record(record(response).answers);
|
||||
if (record(response).schema !== "paperclip.question_response.v1" || Object.keys(answers).some(id => id !== plans[0]!.id && id !== "reason")) return false;
|
||||
const selected = record(answers[String(plans[0]!.id)]).selectedOptionIds;
|
||||
return Array.isArray(selected) && selected.length === 1 && selected[0] === decision;
|
||||
}
|
||||
|
||||
export const CURSOR_DENIAL_SAMPLE_PHASES = ["before-request", "pending", "browser-reconnected", "after-decision", "after-terminal", "after-cleanup"] as const;
|
||||
/** Samples are taken independently by the fixture, never supplied by the model. */
|
||||
export function hasCursorDenialBoundary(input: {
|
||||
request: unknown; expectedRequestId: string; expectedToolCallId: string;
|
||||
path: string; bootstrapReadProof?: BootstrapReadProof; notices: readonly CursorToolNotice[]; runId: string; turnId: string; samples: readonly { phase: string; path: string; absent: boolean; observedAt: number }[];
|
||||
}): boolean {
|
||||
const request = record(input.request); const origin = record(request.origin); const details = record(request.details);
|
||||
if (!input.expectedRequestId.trim() || !input.expectedToolCallId.trim() || !input.path.trim()
|
||||
|| request.requestId !== input.expectedRequestId || details.toolCallId !== input.expectedToolCallId
|
||||
|| request.type !== "permission" || request.status !== "pending"
|
||||
|| !hasAcpxNativeOrigin(origin, "cursor", "session/request_permission")) return false;
|
||||
if (request.turnId !== input.turnId || !hasCursorDeniedCommand({ notices: input.notices, runId: input.runId, turnId: input.turnId, requestId: input.expectedRequestId, toolCallId: input.expectedToolCallId, commandSha256: cursorDeniedCommand(input.path).commandSha256, bootstrapReadProof: input.bootstrapReadProof })) return false;
|
||||
const choices = request.choices;
|
||||
if (!Array.isArray(choices)) return false;
|
||||
const keys = choices.map(value => record(value).key);
|
||||
if (new Set(keys).size !== keys.length || !keys.includes("decline") || !keys.includes("cancel")
|
||||
|| keys.some(key => !["accept", "decline", "cancel"].includes(String(key)))) return false;
|
||||
if (input.samples.length !== CURSOR_DENIAL_SAMPLE_PHASES.length) return false;
|
||||
return input.samples.every((sample, index) => sample.phase === CURSOR_DENIAL_SAMPLE_PHASES[index]
|
||||
&& sample.path === input.path && sample.absent === true && Number.isFinite(sample.observedAt)
|
||||
&& (index === 0 || sample.observedAt >= input.samples[index - 1]!.observedAt));
|
||||
}
|
||||
|
||||
|
||||
export const cursorNativeTasks: readonly (Omit<RunnerTaskFixture, "flow"> & { flow: "cursor_native" })[] = cursorNativeCaseDesigns.map(design => ({
|
||||
id: design.id, label: `Cursor ${design.id}`, groups: [], workMode: "standard", flow: "cursor_native",
|
||||
expectedRunCount: 1, attemptTimeoutMs: { local: 300_000, daytona: 300_000 }, turnTimeoutMs: 120_000,
|
||||
expectedTerminalState: design.id === "native-write-deny-reconnect" ? { issue: "in_progress", run: "cancelled" } : design.id === "native-plan-reject-revise-accept" ? { issue: "in_progress", run: "succeeded" } : { issue: "done", run: "succeeded" },
|
||||
buildTitle: nonce => `Cursor ${design.id} ${nonce}`,
|
||||
buildPrompt: nonce => cursorNativePrompt(design.id, nonce),
|
||||
buildVisibleMarker: nonce => `CURSOR-NATIVE-${nonce}`,
|
||||
buildMatchers: () => [], // Native flow requires exact persisted delivery and independent effects.
|
||||
}));
|
||||
|
||||
/** Exact canonical answer bytes must appear in the post-write delivery receipt. */
|
||||
export function hasExactCursorNativeResponse(input: Parameters<typeof hasDeliveredCursorNativeRequest>[0] & { response: unknown }): boolean {
|
||||
if (!hasDeliveredCursorNativeRequest(input) || record(input.response).schema !== "paperclip.question_response.v1" || Object.keys(record(record(input.response).answers)).length === 0) return false;
|
||||
const matches = input.events.map(record).map(row => record(record(row.payload).prpEvent))
|
||||
.filter(event => event.runId === input.runId && event.turnId === input.turnId && event.eventType === "runtime_request.resolved" && record(event.payload).requestId === input.requestId);
|
||||
return matches.length === 1 && stableJson(record(matches[0]!.payload).response) === stableJson(input.response);
|
||||
}
|
||||
function stableJson(value: unknown): string {
|
||||
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
||||
if (value !== null && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, value]) => `${JSON.stringify(key)}:${stableJson(value)}`).join(",")}}`;
|
||||
return JSON.stringify(value) ?? "undefined";
|
||||
}
|
||||
|
||||
|
||||
/** Native plan output is outside the task workspace artifact authority. */
|
||||
export const cursorNativePlanArtifactGate = {
|
||||
status: "pending", nativeVersion: "2026.09.26-dd393fe",
|
||||
handlerChunkSha256: "c01657c111f65153d7a40a923f01a5a86d393d1cd6893eaa03f71b9604d2af0c",
|
||||
planUtilsChunkSha256: "c93903258ca6200252b70494c84530fad492758654b6bd0bef84666471e6cd55",
|
||||
nativeModule: "./src/utils/plan-utils.ts", functionExport: "IB",
|
||||
nativePath: "<private provider HOME>/.cursor/plans/<sanitized name>-<conversation id first 8>.plan.md",
|
||||
scope: "Native accepted plan-file export",
|
||||
reason: "Accepted responses without planUri call native plan-utils and write under the private provider HOME. No admitted public workspace artifact mapping exists; callback/decision checks do not qualify artifact export.",
|
||||
} as const;
|
||||
@@ -0,0 +1,105 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { cursorDeniedCommand, hasCursorDeniedCommand, hasCursorCancellation, readCursorToolEvidence, type CursorToolNotice } from "./cursor-native-evidence.js";
|
||||
|
||||
export function denialNotices(path = "/fixture/denied.txt"): CursorToolNotice[] {
|
||||
const base = { runId: "run", sessionId: "session", turnId: "turn", toolCallId: "tool", operation: "execute", commandSha256: cursorDeniedCommand(path).commandSha256 };
|
||||
return [{ ...base, seq: 1, stage: "tool", status: "pending" }, { ...base, seq: 2, stage: "permission_requested", requestId: "request", declineOffered: true },
|
||||
{ ...base, seq: 3, stage: "permission_delivered", requestId: "request", outcome: "reject_once" }, { ...base, seq: 4, stage: "tool", status: "failed" }];
|
||||
}
|
||||
const grade = (notices: CursorToolNotice[]) => hasCursorDeniedCommand({ notices, runId: "run", turnId: "turn", requestId: "request", toolCallId: "tool", commandSha256: cursorDeniedCommand("/fixture/denied.txt").commandSha256 });
|
||||
it("requires the exact absolute command, native request, delivered denial and failed call in order", () => {
|
||||
expect(grade(denialNotices())).toBe(true); expect(grade(denialNotices("/other/denied.txt"))).toBe(false);
|
||||
expect(grade(denialNotices().slice(1))).toBe(false); expect(grade([...denialNotices(), denialNotices()[0]!])).toBe(false);
|
||||
for (const key of ["runId", "sessionId", "turnId", "toolCallId", "commandSha256"]) {
|
||||
const rows = denialNotices(); (rows[3] as any)[key] = "other"; expect(grade(rows)).toBe(false);
|
||||
}
|
||||
const rows = denialNotices(); rows[3]!.seq = 2; expect(grade(rows)).toBe(false);
|
||||
});
|
||||
it("quotes fixture paths and refuses relative or multiline targets", () => {
|
||||
expect(cursorDeniedCommand("/fixture/it's here.txt").command).toContain("it'\\''s here.txt");
|
||||
expect(() => cursorDeniedCommand("relative")).toThrow(); expect(() => cursorDeniedCommand("/fixture/\ncommand")).toThrow();
|
||||
});
|
||||
it("reads only strict public producer-bound evidence and rejects incompleteness", () => {
|
||||
const rows = denialNotices().map(n => ({ runId: n.runId, seq: n.seq, protocolSchemaVersion: 1, eventType: "provider.notice.recorded", payload: { prpEvent: {
|
||||
schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: n.runId, turnId: n.turnId, emittedAt: new Date(1).toISOString(), eventType: "provider.notice.recorded",
|
||||
payload: { schema: "paperclip.provider.notice.v1", scope: "turn", category: "cursor_tool_evidence_v1", provenance: { sessionId: n.sessionId, turnId: n.turnId, eventType: n.stage, method: n.stage === "tool" ? "session/update" : "session/request_permission" },
|
||||
details: Object.entries(n).filter(([key]) => !["runId", "sessionId", "turnId", "seq"].includes(key)).map(([name, value]) => ({ name, value: String(value) })) },
|
||||
} } }));
|
||||
expect(grade(readCursorToolEvidence(rows, "run"))).toBe(true);
|
||||
const changed = structuredClone(rows); changed[0]!.payload.prpEvent.payload.provenance.turnId = "other";
|
||||
expect(() => readCursorToolEvidence(changed, "run")).toThrow();
|
||||
const incomplete = structuredClone(rows); incomplete[0]!.payload.prpEvent.payload.details[0] = { name: "stage", value: "evidence_incomplete" };
|
||||
expect(() => readCursorToolEvidence(incomplete, "run")).toThrow(/incomplete/);
|
||||
expect(() => readCursorToolEvidence([...rows, rows[0]], "run")).toThrow(/Duplicate/);
|
||||
});
|
||||
it("requires acknowledged cancellation and an actual correlated terminal after the request", () => {
|
||||
const input = { run: { id: "run", status: "cancelled", resultJson: { nativeCancellation: { dispatchState: "acknowledged", dispatched: true, scope: "run" } } }, issue: { status: "in_progress" }, runId: "run", turnId: "turn", requestedAt: 10,
|
||||
events: [{ runId: "run", protocolSchemaVersion: 1, payload: { prpEvent: { runId: "run", turnId: "turn", eventType: "turn.cancelled", schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", emittedAt: new Date(11).toISOString() } } }] };
|
||||
expect(hasCursorCancellation(input)).toBe(true);
|
||||
expect(hasCursorCancellation({ ...input, events: [] })).toBe(false); expect(hasCursorCancellation({ ...input, requestedAt: 12 })).toBe(false);
|
||||
expect(hasCursorCancellation({ ...input, issue: { status: "done" } })).toBe(false);
|
||||
expect(hasCursorCancellation({ ...input, turnId: "foreign" })).toBe(false);
|
||||
input.run.resultJson.nativeCancellation.dispatched = false; expect(hasCursorCancellation(input)).toBe(false);
|
||||
});
|
||||
|
||||
it("requires remote lease identity and actual Linux process retirement, not empty host observations", async () => {
|
||||
const { assertCursorRemoteSnapshot, hasCursorRemoteRetirement } = await import("./cursor-native-evidence.js");
|
||||
const binding = { companyId: "company", environmentId: "environment", runId: "run", leaseId: "lease", sandboxId: "sandbox", remoteCwd: "/home/daytona/paperclip-workspace", image: `runner@sha256:${"a".repeat(64)}` };
|
||||
const root = { pid: 51, startTicks: "3021", bootId: "12345678-1234-1234-1234-123456789abc" };
|
||||
const snapshot = { binding, observedAtMs: 50, complete: true, workspace: { "file.txt": `sha256:${"b".repeat(64)}` }, targets: {}, watcher: { complete: true, targetMutationCount: 0, workspaceMutationCount: 0 }, processes: { captured: true, root, journal: [{ ...root, ppid: 1 }], live: [] as number[] } };
|
||||
expect(() => assertCursorRemoteSnapshot(snapshot, binding)).not.toThrow(); expect(hasCursorRemoteRetirement(snapshot, binding)).toBe(true);
|
||||
for (const key of Object.keys(binding)) {
|
||||
const changed = { ...binding, [key]: "foreign" }; expect(() => assertCursorRemoteSnapshot({ ...snapshot, binding: changed }, binding)).toThrow(/authority/);
|
||||
}
|
||||
expect(hasCursorRemoteRetirement({ ...snapshot, processes: { ...snapshot.processes, captured: false } }, binding)).toBe(false);
|
||||
expect(hasCursorRemoteRetirement({ ...snapshot, processes: { ...snapshot.processes, live: [51] } }, binding)).toBe(false);
|
||||
expect(hasCursorRemoteRetirement({ ...snapshot, processes: { ...snapshot.processes, journal: [{ ...root, ppid: 1, startTicks: "4000" }] } }, binding)).toBe(false);
|
||||
expect(() => assertCursorRemoteSnapshot({ ...snapshot, workspace: { "../host-copy": "directory" } }, binding)).toThrow(/workspace/);
|
||||
expect(() => assertCursorRemoteSnapshot({ ...snapshot, watcher: { complete: false, targetMutationCount: 0, workspaceMutationCount: 0 } }, binding)).toThrow(/authority/);
|
||||
});
|
||||
|
||||
it("binds remote absent-target samples to stable directory identity and transient-write observation", async () => {
|
||||
const { cursorRemoteDeniedSample } = await import("./cursor-native-evidence.js");
|
||||
const binding = { companyId: "company", environmentId: "environment", runId: "run", leaseId: "lease", sandboxId: "sandbox", remoteCwd: "/home/daytona/paperclip-workspace", image: `runner@sha256:${"a".repeat(64)}` };
|
||||
const target = { absent: true, sha256: null, parent: { dev: "1", ino: "2" }, mutationCount: 0, complete: true };
|
||||
const snapshot = { binding, observedAtMs: 50, complete: true, workspace: {}, targets: { "denied.txt": target }, watcher: { complete: true, targetMutationCount: 0, workspaceMutationCount: 0 }, processes: { captured: false, root: null, journal: [], live: [] } };
|
||||
expect(cursorRemoteDeniedSample(snapshot, binding, "denied.txt", "pending", target.parent)).toMatchObject({ absent: true, path: "/home/daytona/paperclip-workspace/denied.txt", phase: "pending" });
|
||||
expect(() => cursorRemoteDeniedSample({ ...snapshot, targets: {} }, binding, "denied.txt", "pending")).toThrow(/incomplete/);
|
||||
expect(() => cursorRemoteDeniedSample(snapshot, binding, "denied.txt", "pending", { dev: "1", ino: "3" })).toThrow(/changed/);
|
||||
expect(() => cursorRemoteDeniedSample({ ...snapshot, targets: { "denied.txt": { ...target, mutationCount: 2 } } }, binding, "denied.txt", "pending")).toThrow(/changed/);
|
||||
expect(() => cursorRemoteDeniedSample(snapshot, binding, "../denied.txt", "pending")).toThrow(/Invalid/);
|
||||
});
|
||||
|
||||
it("rejects transient remote workspace writes even when final hashes match", async () => {
|
||||
const { hasCursorRemoteWorkspaceUnchanged } = await import("./cursor-native-evidence.js");
|
||||
const binding = { companyId: "company", environmentId: "environment", runId: "run", leaseId: "lease", sandboxId: "sandbox", remoteCwd: "/home/daytona/paperclip-workspace", image: `runner@sha256:${"a".repeat(64)}` };
|
||||
const baseline = { binding, observedAtMs: 50, complete: true, workspace: {}, targets: {}, watcher: { complete: true, targetMutationCount: 0, workspaceMutationCount: 0 }, processes: { captured: false, root: null, journal: [], live: [] } };
|
||||
expect(hasCursorRemoteWorkspaceUnchanged({ ...baseline, observedAtMs: 60 }, baseline)).toBe(true);
|
||||
expect(hasCursorRemoteWorkspaceUnchanged({ ...baseline, watcher: { ...baseline.watcher, workspaceMutationCount: 2 } }, baseline)).toBe(false);
|
||||
expect(hasCursorRemoteWorkspaceUnchanged({ ...baseline, workspace: { "new-file": `sha256:${"b".repeat(64)}` } }, baseline)).toBe(false);
|
||||
expect(hasCursorRemoteWorkspaceUnchanged({ ...baseline, observedAtMs: 40 }, baseline)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows explicit earlier remote bootstrap reads while rejecting unknown kinds and later extra work", () => {
|
||||
const rows = denialNotices().map(row => ({ ...row, seq: row.seq + 3 }));
|
||||
const read: CursorToolNotice = { ...rows[0]!, seq: 1, toolCallId: "bootstrap-read", stage: "tool", status: "completed", operation: "read", commandSha256: undefined };
|
||||
const input = { notices: [read, ...rows], runId: "run", turnId: "turn", requestId: "request", toolCallId: "tool", commandSha256: cursorDeniedCommand("/fixture/denied.txt").commandSha256 };
|
||||
expect(hasCursorDeniedCommand(input)).toBe(false);
|
||||
const actionFile = `.paperclip-eval-action-${"a".repeat(36)}.txt`;
|
||||
const event = { runId: "run", seq: 2, protocolSchemaVersion: 1, eventType: "tool.execution.completed", payload: { prpEvent: {
|
||||
schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: "run", turnId: "turn", eventType: "tool.execution.completed", emittedAt: new Date(2).toISOString(),
|
||||
payload: { schema: "paperclip.tool.execution.v1", executionId: "bootstrap-read", transport: "builtin", operation: "read", target: actionFile, status: "completed" },
|
||||
} } };
|
||||
read.readTargetSha256 = `sha256:${createHash("sha256").update(actionFile).digest("hex")}`;
|
||||
const bootstrapReadProof = { actionFile, events: [event] };
|
||||
expect(hasCursorDeniedCommand({ ...input, bootstrapReadProof })).toBe(true);
|
||||
expect(hasCursorDeniedCommand({ ...input, bootstrapReadProof: { actionFile, events: [] } })).toBe(false);
|
||||
const wrong = structuredClone(event); wrong.payload.prpEvent.payload.target = "unrelated.txt";
|
||||
expect(hasCursorDeniedCommand({ ...input, bootstrapReadProof: { actionFile, events: [wrong] } })).toBe(false);
|
||||
const extra = { ...read, toolCallId: "unrelated", seq: 0 };
|
||||
expect(hasCursorDeniedCommand({ ...input, notices: [extra, ...input.notices], bootstrapReadProof })).toBe(false);
|
||||
for (const operation of [undefined, "edit", "execute"]) expect(hasCursorDeniedCommand({ ...input, bootstrapReadProof, notices: [{ ...read, operation }, ...rows] })).toBe(false);
|
||||
expect(hasCursorDeniedCommand({ ...input, bootstrapReadProof, notices: [...rows, { ...read, seq: 20 }] })).toBe(false);
|
||||
expect(hasCursorDeniedCommand({ ...input, bootstrapReadProof, notices: [{ ...read, sessionId: "other" }, ...rows] })).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import { withoutProvenBootstrapReads, type BootstrapReadProof } from "./native-bootstrap-read-proof.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute, posix } from "node:path";
|
||||
|
||||
export interface CursorToolNotice {
|
||||
runId: string; sessionId: string; turnId: string; toolCallId: string; seq: number;
|
||||
stage: "tool" | "permission_requested" | "permission_delivered";
|
||||
status?: string; operation?: string; commandSha256?: string; readTargetSha256?: string; requestId?: string; declineOffered?: boolean; outcome?: string;
|
||||
}
|
||||
const rec = (v: unknown): Record<string, any> => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record<string, any> : {};
|
||||
const id = (v: unknown): v is string => typeof v === "string" && v.length > 0 && v.length <= 240 && !/[\u0000-\u001f\u007f]/u.test(v) && !v.includes("[REDACTED]");
|
||||
const enums = { stage: ["tool", "permission_requested", "permission_delivered"], status: ["pending", "in_progress", "completed", "failed"], operation: ["execute", "read"], outcome: ["allow_once", "allow_always", "reject_once", "cancel"] };
|
||||
const names = new Set(["stage", "toolCallId", "status", "operation", "commandSha256", "readTargetSha256", "requestId", "declineOffered", "outcome"]);
|
||||
export function readCursorToolEvidence(rows: readonly unknown[], runId: string): CursorToolNotice[] {
|
||||
const result: CursorToolNotice[] = [];
|
||||
for (const value of rows) {
|
||||
const row = rec(value), event = rec(rec(row.payload).prpEvent), p = rec(event.payload);
|
||||
if (p.category !== "cursor_tool_evidence_v1") continue;
|
||||
const origin = rec(p.provenance);
|
||||
if (row.eventType !== "provider.notice.recorded" || row.runId !== runId || row.protocolSchemaVersion !== 1 || event.schemaVersion !== 1 || p.schema !== "paperclip.provider.notice.v1" || p.scope !== "turn" || event.schema !== "paperclip.prp.event.v1" || event.sourceKind !== "runner" || event.eventType !== row.eventType || event.runId !== runId || !id(origin.sessionId) || !id(origin.turnId) || origin.turnId !== event.turnId || !Array.isArray(p.details) || p.details.length > 12 || !Number.isSafeInteger(row.seq) || row.seq < 0 || !Number.isFinite(Date.parse(event.emittedAt))) throw new Error("Invalid Cursor evidence binding");
|
||||
const fields: Record<string, string> = {};
|
||||
for (const value of p.details) {
|
||||
const d = rec(value);
|
||||
if (d.name === "stage" && d.value === "evidence_incomplete") throw new Error("Cursor evidence is explicitly incomplete");
|
||||
if (!names.has(d.name) || Object.hasOwn(fields, d.name) || typeof d.value !== "string" || d.value.length > 1024 || d.value.includes("[REDACTED]")) throw new Error("Invalid Cursor evidence detail");
|
||||
fields[d.name] = d.value;
|
||||
}
|
||||
if (!id(fields.toolCallId) || !enums.stage.includes(fields.stage!) || origin.eventType !== fields.stage || origin.method !== (fields.stage === "tool" ? "session/update" : "session/request_permission")) throw new Error("Invalid Cursor evidence origin");
|
||||
for (const [key, values] of Object.entries(enums)) if (fields[key] !== undefined && !values.includes(fields[key]!)) throw new Error("Invalid Cursor evidence enum");
|
||||
if (fields.requestId !== undefined && !id(fields.requestId)) throw new Error("Invalid Cursor request identity");
|
||||
if (fields.readTargetSha256 !== undefined && !/^sha256:[a-f0-9]{64}$/u.test(fields.readTargetSha256)) throw new Error("Invalid Cursor read digest");
|
||||
if (fields.commandSha256 !== undefined && !/^sha256:[a-f0-9]{64}$/u.test(fields.commandSha256)) throw new Error("Invalid Cursor command digest");
|
||||
if (fields.declineOffered !== undefined && !["true", "false"].includes(fields.declineOffered)) throw new Error("Invalid Cursor offered choice");
|
||||
result.push({ ...fields, runId, sessionId: origin.sessionId, turnId: origin.turnId, seq: row.seq, declineOffered: fields.declineOffered === "true" } as CursorToolNotice);
|
||||
}
|
||||
if (new Set(result.map(row => row.seq)).size !== result.length) throw new Error("Duplicate Cursor evidence sequence");
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Exact absolute target removes any dependency on implicit native shell cwd. */
|
||||
export function cursorDeniedCommand(path: string) {
|
||||
if (!isAbsolute(path) || /[\u0000-\u001f\u007f]/u.test(path)) throw new Error("Invalid denial target");
|
||||
const command = `printf 'MUST_NOT_EXIST' > '${path.replaceAll("'", "'\\''")}'`;
|
||||
return { command, commandSha256: `sha256:${createHash("sha256").update(command).digest("hex")}` };
|
||||
}
|
||||
export function hasCursorDeniedCommand(input: {
|
||||
notices: readonly CursorToolNotice[]; runId: string; turnId: string; requestId: string; toolCallId: string; commandSha256: string; bootstrapReadProof?: BootstrapReadProof;
|
||||
}): boolean {
|
||||
const origin = input.notices.find(row => row.stage === "tool" && row.status === "pending" && row.operation === "execute" && row.toolCallId === input.toolCallId && row.commandSha256 === input.commandSha256);
|
||||
let notices: readonly CursorToolNotice[];
|
||||
try { notices = origin ? withoutProvenBootstrapReads(input.notices, origin, input.bootstrapReadProof) : input.notices; }
|
||||
catch { return false; }
|
||||
const requests = notices.filter(row => row.stage === "permission_requested");
|
||||
if (requests.length !== 1) return false;
|
||||
const request = requests[0]!;
|
||||
const same = (row: CursorToolNotice) => row.runId === input.runId && row.turnId === input.turnId && row.toolCallId === input.toolCallId && row.sessionId === request.sessionId && row.commandSha256 === input.commandSha256 && row.operation === "execute";
|
||||
if (!same(request) || request.requestId !== input.requestId || !request.declineOffered) return false;
|
||||
const origins = notices.filter(row => row.stage === "tool" && row.status === "pending");
|
||||
const delivered = notices.filter(row => row.stage === "permission_delivered");
|
||||
const failed = notices.filter(row => row.stage === "tool" && row.status === "failed");
|
||||
return origins.length === 1 && same(origins[0]!) && delivered.length === 1 && same(delivered[0]!)
|
||||
&& delivered[0]!.requestId === input.requestId && delivered[0]!.outcome === "reject_once"
|
||||
&& failed.length === 1 && same(failed[0]!) && origins[0]!.seq < request.seq && request.seq < delivered[0]!.seq && delivered[0]!.seq < failed[0]!.seq
|
||||
&& notices.every(row => same(row) && row.status !== "completed");
|
||||
}
|
||||
|
||||
export function hasCursorCancellation(input: { run: unknown; issue: unknown; events: readonly unknown[]; runId: string; turnId: string; requestedAt: number }): boolean {
|
||||
const run = rec(input.run), cancellation = rec(rec(run.resultJson).nativeCancellation);
|
||||
const terminals = input.events.map(rec).map(row => ({ row, event: rec(rec(row.payload).prpEvent) })).filter(({ event }) => ["turn.cancelled", "turn.interrupted"].includes(event.eventType));
|
||||
return run.id === input.runId && run.status === "cancelled" && rec(input.issue).status === "in_progress"
|
||||
&& cancellation.dispatchState === "acknowledged" && cancellation.dispatched === true && cancellation.scope === "run"
|
||||
&& terminals.length === 1 && terminals.every(({ row, event }) => row.runId === input.runId && event.runId === input.runId && event.turnId === input.turnId
|
||||
&& event.schema === "paperclip.prp.event.v1" && event.schemaVersion === 1 && row.protocolSchemaVersion === 1 && event.sourceKind === "runner"
|
||||
&& Number.isFinite(input.requestedAt) && Date.parse(event.emittedAt) >= input.requestedAt);
|
||||
}
|
||||
|
||||
/** Controller-observed sandbox receipts; never substitute host copy-back files. */
|
||||
export interface CursorRemoteBinding {
|
||||
companyId: string; environmentId: string; runId: string; leaseId: string;
|
||||
sandboxId: string; remoteCwd: string; image: string;
|
||||
}
|
||||
export interface CursorRemoteSnapshot {
|
||||
binding: CursorRemoteBinding; observedAtMs: number; complete: boolean;
|
||||
workspace: Record<string, string>;
|
||||
targets: Record<string, { absent: boolean; sha256: string | null; parent: { dev: string; ino: string }; mutationCount: number; complete: boolean }>;
|
||||
watcher: { complete: boolean; targetMutationCount: number; workspaceMutationCount: number };
|
||||
processes: { captured: boolean; root: { pid: number; startTicks: string; bootId: string } | null;
|
||||
journal: Array<{ pid: number; ppid: number; startTicks: string; bootId: string }>; live: number[] };
|
||||
}
|
||||
export function assertCursorRemoteSnapshot(snapshot: CursorRemoteSnapshot, binding: CursorRemoteBinding): void {
|
||||
if (!snapshot.complete || !snapshot.watcher.complete || (!Number.isSafeInteger(snapshot.observedAtMs) || snapshot.observedAtMs < 0)
|
||||
|| !Object.keys(binding).every(key => snapshot.binding[key as keyof CursorRemoteBinding] === binding[key as keyof CursorRemoteBinding])
|
||||
|| !isAbsolute(binding.remoteCwd) || posix.normalize(binding.remoteCwd) !== binding.remoteCwd || !/^.+@sha256:[a-f0-9]{64}$/u.test(binding.image) || ![binding.companyId, binding.environmentId, binding.runId, binding.leaseId, binding.sandboxId].every(id)) throw new Error("Cursor remote evidence lacks exact complete lease authority");
|
||||
const entries = Object.entries(snapshot.workspace);
|
||||
if (entries.length > 2048 || entries.some(([name, value]) => !name || name.startsWith("/") || /[\\\u0000-\u001f\u007f]/u.test(name)
|
||||
|| name.replace(/\/$/u, "").split("/").some(part => !part || part === "." || part === "..")
|
||||
|| (value !== "directory" && !/^sha256:[a-f0-9]{64}$/u.test(value)))) throw new Error("Cursor remote workspace evidence is malformed or unbounded");
|
||||
if (![snapshot.watcher.targetMutationCount, snapshot.watcher.workspaceMutationCount].every(value => Number.isSafeInteger(value) && value >= 0)) throw new Error("Cursor remote watcher receipt is malformed");
|
||||
}
|
||||
export function hasCursorRemoteRetirement(snapshot: CursorRemoteSnapshot, binding: CursorRemoteBinding): boolean {
|
||||
try { assertCursorRemoteSnapshot(snapshot, binding); } catch { return false; }
|
||||
const p = snapshot.processes, root = p.root;
|
||||
return p.captured && root !== null && Number.isSafeInteger(root.pid) && root.pid > 1 && /^\d+$/u.test(root.startTicks)
|
||||
&& /^[a-f0-9-]{36}$/iu.test(root.bootId) && p.live.length === 0 && p.journal.length > 0
|
||||
&& p.journal.some(item => item.pid === root.pid && item.startTicks === root.startTicks && item.bootId === root.bootId)
|
||||
&& p.journal.every(item => Number.isSafeInteger(item.pid) && item.pid > 1 && /^\d+$/u.test(item.startTicks) && item.bootId === root.bootId);
|
||||
}
|
||||
|
||||
export function cursorRemoteDeniedSample(snapshot: CursorRemoteSnapshot, binding: CursorRemoteBinding, relative: string, phase: string,
|
||||
expectedParent?: { dev: string; ino: string }) {
|
||||
assertCursorRemoteSnapshot(snapshot, binding);
|
||||
if (!/^[a-zA-Z0-9_-]+\.txt$/u.test(relative)) throw new Error("Invalid remote denied target");
|
||||
const target = snapshot.targets[relative];
|
||||
if (!target || !target.complete || !/^\d+$/u.test(target.parent.dev) || !/^\d+$/u.test(target.parent.ino)
|
||||
|| !Number.isSafeInteger(target.mutationCount) || target.mutationCount !== 0
|
||||
|| (expectedParent && (target.parent.dev !== expectedParent.dev || target.parent.ino !== expectedParent.ino))) throw new Error("Cursor remote denied target observation is incomplete or changed");
|
||||
return { phase, path: posix.join(binding.remoteCwd, relative), absent: target.absent === true && target.sha256 === null,
|
||||
observedAt: snapshot.observedAtMs, parent: target.parent };
|
||||
}
|
||||
|
||||
export function hasCursorRemoteWorkspaceUnchanged(snapshot: CursorRemoteSnapshot, baseline: CursorRemoteSnapshot): boolean {
|
||||
try { assertCursorRemoteSnapshot(snapshot, baseline.binding); assertCursorRemoteSnapshot(baseline, baseline.binding); } catch { return false; }
|
||||
return snapshot.observedAtMs >= baseline.observedAtMs
|
||||
&& snapshot.watcher.workspaceMutationCount === baseline.watcher.workspaceMutationCount
|
||||
&& JSON.stringify(Object.entries(snapshot.workspace).sort()) === JSON.stringify(Object.entries(baseline.workspace).sort());
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { cursorNativeWorkspaceSnapshot, hasCursorAcceptedPlanWait } from "./cursor-native-flow.js";
|
||||
import { cursorNativeCaseDesigns, cursorNativePlanArtifactGate, cursorNativeTasks } from "./cursor-native-cases.js";
|
||||
|
||||
it("keeps native mode/permission choices explicit and artifact export pending", () => {
|
||||
expect(cursorNativeTasks.map(task => task.id)).toEqual(cursorNativeCaseDesigns.map(design => design.id));
|
||||
for (const task of cursorNativeTasks) {
|
||||
expect(task.flow).toBe("cursor_native"); expect(task.expectedRunCount).toBe(1); expect(task.turnTimeoutMs).toBe(120_000);
|
||||
}
|
||||
expect(cursorNativeCaseDesigns.filter(row => row.method !== "session/request_permission").every(row => row.cursorMode === "plan")).toBe(true);
|
||||
expect(cursorNativeCaseDesigns.find(row => row.method === "session/request_permission")).toMatchObject({ cursorMode: "agent", permissionMode: "approve-reads" });
|
||||
expect(cursorNativeTasks.find(task => task.id === "native-write-deny-reconnect")!.expectedTerminalState).toEqual({ issue: "in_progress", run: "cancelled" });
|
||||
expect(cursorNativePlanArtifactGate.status).toBe("pending");
|
||||
expect(cursorNativePlanArtifactGate.nativePath).toContain("<private provider HOME>");
|
||||
});
|
||||
it("independently detects changed or newly created workspace bytes", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "cursor-workspace-proof-"));
|
||||
try {
|
||||
await writeFile(join(root, "source.txt"), "before"); const before = await cursorNativeWorkspaceSnapshot(root);
|
||||
expect(await cursorNativeWorkspaceSnapshot(root)).toEqual(before);
|
||||
await writeFile(join(root, "source.txt"), "after"); expect(await cursorNativeWorkspaceSnapshot(root)).not.toEqual(before);
|
||||
await writeFile(join(root, "new.txt"), "effect"); expect(await cursorNativeWorkspaceSnapshot(root)).toHaveProperty("new.txt");
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
it("fails closed on symlinks or oversized proof input", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "cursor-workspace-proof-"));
|
||||
try {
|
||||
await symlink("/", join(root, "escape")); await expect(cursorNativeWorkspaceSnapshot(root)).rejects.toThrow(/symlink/);
|
||||
await rm(join(root, "escape")); await writeFile(join(root, "oversized"), Buffer.alloc(4 * 1024 * 1024 + 1));
|
||||
await expect(cursorNativeWorkspaceSnapshot(root)).rejects.toThrow(/byte bound/);
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("awaits owned remote baseline before returning the exact remote denial command", async () => {
|
||||
const { prepareCursorRemoteAction } = await import("./cursor-native-flow.js");
|
||||
const binding = { companyId: "company", environmentId: "environment", runId: "run", leaseId: "lease", sandboxId: "sandbox", remoteCwd: "/home/daytona/paperclip-workspace", image: `runner@sha256:${"a".repeat(64)}` };
|
||||
const snapshot = { binding, observedAtMs: 50, complete: true, workspace: {}, targets: { "denied.txt": { absent: true, sha256: null, parent: { dev: "1", ino: "2" }, mutationCount: 0, complete: true } }, watcher: { complete: true, targetMutationCount: 0, workspaceMutationCount: 0 }, processes: { captured: true, root: { pid: 51, startTicks: "3021", bootId: "12345678-1234-1234-1234-123456789abc" }, journal: [], live: [51] } };
|
||||
const order: string[] = [];
|
||||
const fixture = { binding, actionFile: `.paperclip-eval-action-${"a".repeat(36)}.txt`, remoteCwd: binding.remoteCwd, snapshot: async (label: string) => { order.push(label); await Promise.resolve(); order.push("baseline-ready"); return snapshot; }, finish: async () => snapshot, close: async () => {} };
|
||||
const prepared = await prepareCursorRemoteAction({ fixture, ...binding, deniedRelative: "denied.txt", prompt: "Perform the actual test" });
|
||||
order.push("publish-action");
|
||||
expect(order).toEqual(["before-action-publication", "baseline-ready", "publish-action"]);
|
||||
expect(prepared.prompt).toContain("printf 'MUST_NOT_EXIST' > '/home/daytona/paperclip-workspace/denied.txt'");
|
||||
expect(prepared.initial).toMatchObject({ phase: "before-request", absent: true });
|
||||
expect(prepared.command?.commandSha256).toMatch(/^sha256:[a-f0-9]{64}$/);
|
||||
await expect(prepareCursorRemoteAction({ fixture, ...binding, runId: "wrong-run", deniedRelative: "denied.txt", prompt: "test" })).rejects.toThrow(/another run/);
|
||||
snapshot.targets["denied.txt"].absent = false;
|
||||
await expect(prepareCursorRemoteAction({ fixture, ...binding, deniedRelative: "denied.txt", prompt: "test" })).rejects.toThrow(/present before/);
|
||||
});
|
||||
|
||||
it("refuses remote native execution before touching API when bootstrap or cleanup authority is missing", async () => {
|
||||
const { runCursorNativeFlow } = await import("./cursor-native-flow.js");
|
||||
let apiCalls = 0;
|
||||
await expect(runCursorNativeFlow({
|
||||
execution: { task: { id: "native-question-reconnect" }, profile: { qualificationCandidate: "cursor" }, environment: { id: "daytona" } },
|
||||
api: { get: async () => { apiCalls++; throw new Error("must not call"); } },
|
||||
} as any)).rejects.toThrow(/owned pre-action observer/);
|
||||
expect(apiCalls).toBe(0);
|
||||
});
|
||||
|
||||
it("requires the exact passive accepted-plan disposition without mode promotion or extra work", () => {
|
||||
const state = { issue: { id: "issue", status: "in_progress" }, interactions: [{ status: "answered" }], runs: [{ id: "run", nativeIssueId: "issue", runtimeMode: "native", status: "succeeded", runnerProfileJson: { nativeExecutionInput: { provider: { cursorMode: "plan" } } }, resultJson: { finalizationPhase: "committed", finalizationReasonCode: "native_plan_accepted_waiting_for_continuation", authoritativeDecision: "in_progress" } }] };
|
||||
expect(hasCursorAcceptedPlanWait(state)).toBe(true);
|
||||
const mutations = [
|
||||
(s: typeof state) => { s.issue.status = "done"; },
|
||||
(s: typeof state) => { s.runs[0]!.status = "failed"; },
|
||||
(s: typeof state) => { s.runs[0]!.nativeIssueId = "foreign"; },
|
||||
(s: typeof state) => { s.runs[0]!.runnerProfileJson.nativeExecutionInput.provider.cursorMode = "agent"; },
|
||||
(s: typeof state) => { s.runs[0]!.resultJson.finalizationReasonCode = "live_continuation_registered"; },
|
||||
(s: typeof state) => { s.runs[0]!.resultJson.finalizationPhase = "pending"; },
|
||||
(s: typeof state) => { s.runs.push(structuredClone(s.runs[0]!)); },
|
||||
(s: typeof state) => { s.interactions[0]!.status = "pending"; },
|
||||
];
|
||||
for (const mutate of mutations) { const changed = structuredClone(state); mutate(changed); expect(hasCursorAcceptedPlanWait(changed)).toBe(false); }
|
||||
expect(cursorNativeTasks.find(task => task.id === "native-plan-reject-revise-accept")!.expectedTerminalState).toEqual({ issue: "in_progress", run: "succeeded" });
|
||||
const prompt = cursorNativeTasks.find(task => task.id === "native-plan-reject-revise-accept")!.buildPrompt("test");
|
||||
expect(prompt).toContain("do not implement, change modes, call paperclip_finish, or start another turn");
|
||||
});
|
||||
@@ -0,0 +1,393 @@
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
import { hasAcpxNativeOrigin } from "./acpx-native-origin.js";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { lstat, readFile, readdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { pollUntil, type RunnerApi } from "./api.js";
|
||||
import { collectRunEvents } from "./run-observations.js";
|
||||
import { createTaskThroughUi } from "./user-actions.js";
|
||||
import { observeRunProcesses, createDeniedTargetFixture } from "./native-local-fixtures.js";
|
||||
import { cursorDeniedCommand, hasCursorDeniedCommand, hasCursorCancellation, readCursorToolEvidence, assertCursorRemoteSnapshot, cursorRemoteDeniedSample, hasCursorRemoteRetirement, hasCursorRemoteWorkspaceUnchanged, type CursorRemoteSnapshot, type CursorRemoteBinding, type CursorToolNotice } from "./cursor-native-evidence.js";
|
||||
import { cursorNativeCaseDesigns, cursorNativePlanArtifactGate, hasCursorDenialBoundary, hasCursorPlanDecision, hasDeliveredCursorNativeRequest, hasExactCursorNativeResponse, type CursorNativeMethod } from "./cursor-native-cases.js";
|
||||
import type { LiveFixtureValues } from "./live-fixtures.js";
|
||||
import type { MatrixExecution } from "./types.js";
|
||||
|
||||
type Row = Record<string, any>;
|
||||
type Check = { id: string; passed: boolean; detail: string };
|
||||
|
||||
/** Select only the exact native callback, including either production ACPX bridge. */
|
||||
export function findCursorNativeRequest(rows: Row[], method: CursorNativeMethod, requestId?: string): Row | undefined {
|
||||
return rows.map(row => row.payload?.prpEvent).find(event => event?.eventType === "runtime_request.created"
|
||||
&& hasAcpxNativeOrigin(event.payload?.request?.origin, "cursor", method)
|
||||
&& (!requestId || event.payload.request.requestId === requestId));
|
||||
}
|
||||
|
||||
/** JSON object key order may change during persistence; array order and values may not. */
|
||||
export function hasCursorNativeCardBinding(card: Row, event: Row, runId: string): boolean {
|
||||
return card.sourceRunId === runId && card.continuationPolicy === "none"
|
||||
&& isDeepStrictEqual(card.payload.questionSet, event.payload.request.input);
|
||||
}
|
||||
|
||||
/** This is a successful planning boundary, not an implementation/completion claim. */
|
||||
export function hasCursorAcceptedPlanWait(state: { issue: Row; runs: Row[]; interactions: Row[] }): boolean {
|
||||
if (state.runs.length !== 1 || state.issue.status !== "in_progress" || state.interactions.some(card => card.status === "pending")) return false;
|
||||
const run = state.runs[0]!;
|
||||
return run.status === "succeeded" && run.runtimeMode === "native" && run.nativeIssueId === state.issue.id
|
||||
&& run.runnerProfileJson?.nativeExecutionInput?.provider?.cursorMode === "plan"
|
||||
&& run.resultJson?.finalizationPhase === "committed"
|
||||
&& run.resultJson?.finalizationReasonCode === "native_plan_accepted_waiting_for_continuation"
|
||||
&& run.resultJson?.authoritativeDecision === "in_progress";
|
||||
}
|
||||
|
||||
export interface CursorRemoteNativeFixture {
|
||||
binding: CursorRemoteBinding; remoteCwd: string; actionFile: string;
|
||||
snapshot(label: string): Promise<CursorRemoteSnapshot>;
|
||||
finish(): Promise<CursorRemoteSnapshot>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
export interface CursorRemoteBootstrap {
|
||||
prompt(nonce: string): string;
|
||||
bindAndRelease(input: { issueId: string; runId: string; targets: string[];
|
||||
actionPrompt(fixture: CursorRemoteNativeFixture): Promise<string> | string }): Promise<CursorRemoteNativeFixture>;
|
||||
}
|
||||
|
||||
|
||||
/** Runs inside the awaited bootstrap callback, before action publication. */
|
||||
export async function prepareCursorRemoteAction(input: {
|
||||
fixture: CursorRemoteNativeFixture; companyId: string; environmentId: string; runId: string;
|
||||
prompt: string; deniedRelative?: string;
|
||||
}) {
|
||||
const { fixture } = input;
|
||||
if (fixture.binding.runId !== input.runId || fixture.binding.companyId !== input.companyId || fixture.binding.environmentId !== input.environmentId || fixture.remoteCwd !== fixture.binding.remoteCwd) throw new Error("Cursor bootstrap lease belongs to another run or workspace");
|
||||
const baseline = await fixture.snapshot("before-action-publication");
|
||||
assertCursorRemoteSnapshot(baseline, fixture.binding);
|
||||
const initial = input.deniedRelative ? cursorRemoteDeniedSample(baseline, fixture.binding, input.deniedRelative, "before-request") : null;
|
||||
if (initial && !initial.absent) throw new Error("Remote denied target was present before action publication");
|
||||
const command = initial ? cursorDeniedCommand(initial.path) : null;
|
||||
return { baseline, initial, command, prompt: input.prompt + (command ? `\nExact native shell command (copy verbatim):\n${command.command}` : "") };
|
||||
}
|
||||
|
||||
/** Match canonical omission of an unanswered optional feedback field. */
|
||||
export function cursorNativePlanResponse(planId: string, decision: "accept" | "reject" | "cancel", feedback: string) {
|
||||
return { schema: "paperclip.question_response.v1", answers: { [planId]: { selectedOptionIds: [decision] }, ...(decision === "reject" ? { reason: { text: feedback } } : {}) } };
|
||||
}
|
||||
|
||||
/** Independent bounded snapshot; symlinks are rejected without following them. */
|
||||
export async function cursorNativeWorkspaceSnapshot(root: string): Promise<Record<string, string>> {
|
||||
const files: Record<string, string> = {}; let bytes = 0;
|
||||
async function scan(relative = "") {
|
||||
for (const entry of (await readdir(join(root, relative))).sort()) {
|
||||
const name = relative ? `${relative}/${entry}` : entry; const path = join(root, name); const stat = await lstat(path);
|
||||
if (Object.keys(files).length >= 2048) throw new Error("Cursor workspace proof exceeds file bound");
|
||||
if (stat.isSymbolicLink()) throw new Error("Cursor workspace proof cannot authorize a symlink");
|
||||
if (stat.isDirectory()) { files[`${name}/`] = "directory"; await scan(name); }
|
||||
else if (stat.isFile()) {
|
||||
bytes += stat.size;
|
||||
if (stat.size > 4 * 1024 * 1024 || bytes > 32 * 1024 * 1024) throw new Error("Cursor workspace proof exceeds byte bound");
|
||||
files[name] = createHash("sha256").update(await readFile(path)).digest("hex");
|
||||
} else throw new Error("Cursor workspace proof found a special file");
|
||||
}
|
||||
}
|
||||
await scan(); return files;
|
||||
}
|
||||
|
||||
export async function runCursorNativeFlow(input: {
|
||||
page: Page; api: RunnerApi; fixtures: LiveFixtureValues; execution: MatrixExecution; nonce: string;
|
||||
workspacePath: string; deadlineAt: number;
|
||||
observe(issue: Row, runs: Row[]): void;
|
||||
capture(id: string, label: string, file: string): Promise<void>;
|
||||
evidence(name: string, data: unknown): Promise<void>;
|
||||
registerCleanupAssertion?(assertion: () => Promise<Check[]>): void;
|
||||
registerBeforeEnvironmentTeardownAssertion?(assertion: () => Promise<Check[]>): void;
|
||||
remoteBootstrap?: CursorRemoteBootstrap;
|
||||
}) {
|
||||
const { page, api, fixtures, execution, nonce } = input;
|
||||
const design = cursorNativeCaseDesigns.find(value => value.id === execution.task.id);
|
||||
const remote = execution.environment.id === "daytona";
|
||||
if (!design || !["local", "daytona"].includes(execution.environment.id) || execution.profile.qualificationCandidate !== "cursor") throw new Error("Cursor native fixtures require an explicit isolated Cursor candidate");
|
||||
if (remote && (!input.remoteBootstrap || !input.registerBeforeEnvironmentTeardownAssertion)) throw new Error("Cursor Daytona requires an owned pre-action observer and pre-teardown verification");
|
||||
if (!remote && ["native-write-deny-reconnect", "native-plan-reject-revise-accept"].includes(design.id) && !input.registerCleanupAssertion) throw new Error("Cursor denial requires authoritative post-cleanup verification");
|
||||
const checks: Check[] = []; let issue: Row = {}; let runs: Row[] = [];
|
||||
const check = (id: string, passed: boolean, detail: string) => { checks.push({ id, passed, detail }); expect(passed, detail).toBe(true); };
|
||||
const events = (runId: string) => collectRunEvents<Row>((afterSeq, limit) => api.get(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=${limit}`));
|
||||
const absent = async (path: string) => { try { await lstat(path); return false; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; throw error; } };
|
||||
const agent = await api.get<Row>(`/api/agents/${fixtures.agent.id}`);
|
||||
const configured = await api.patch<Row>(`/api/agents/${fixtures.agent.id}`, { adapterConfig: { ...agent.adapterConfig, acpxSessionMode: design.cursorMode, acpxPermissionMode: design.permissionMode, ...(remote || design.id === "native-write-deny-reconnect" ? { lifecycleMode: "per_turn", timeoutSec: 120 } : {}) } });
|
||||
check("explicit-mode-policy", configured.adapterConfig.acpxSessionMode === design.cursorMode && configured.adapterConfig.acpxPermissionMode === design.permissionMode, "Public agent configuration selected mode and permission policy separately before provider startup");
|
||||
if (remote || design.id === "native-write-deny-reconnect") check("per-turn-process-authority", configured.adapterConfig.lifecycleMode === "per_turn" && configured.adapterConfig.timeoutSec === 120, "Public configuration admits a bounded per-turn provider process before startup");
|
||||
await input.evidence("cursor-native-contract.json", { caseId: design.id, mode: design.cursorMode, permissionMode: design.permissionMode, method: design.method, expectedRunCount: 1, nativeCallbackRequired: true, artifactGate: cursorNativePlanArtifactGate });
|
||||
const project = await api.post<Row>(`/api/companies/${fixtures.company.id}/projects`, {
|
||||
name: `Cursor native workspace ${nonce}`, executionWorkspacePolicy: { enabled: true, defaultMode: "shared_workspace", sharedWorkspaceConcurrency: "serialize", allowIssueOverride: false, environmentId: fixtures.environment.id, workspaceStrategy: { type: "project_primary" } },
|
||||
workspace: { name: "Primary", sourceType: "local_path", cwd: input.workspacePath, isPrimary: true },
|
||||
});
|
||||
const baseline = remote ? null : await cursorNativeWorkspaceSnapshot(input.workspacePath);
|
||||
let remoteFixture: CursorRemoteNativeFixture | null = null; let remoteFinal: CursorRemoteSnapshot | null = null; let remoteBaseline: CursorRemoteSnapshot | null = null;
|
||||
let remoteParent: { dev: string; ino: string } | undefined;
|
||||
const sampleWorkspace = async (phase: string) => {
|
||||
if (remote) {
|
||||
if (!remoteFixture) throw new Error("Cursor remote workspace observer is absent");
|
||||
const current = remoteFinal ?? await remoteFixture.snapshot(phase);
|
||||
await input.evidence(`cursor-workspace-${phase}.json`, { baseline: remoteBaseline, current });
|
||||
check(`workspace-unchanged-${phase}`, hasCursorRemoteWorkspaceUnchanged(current, remoteBaseline!), "Owned remote workspace hashes and continuous mutation journal remain unchanged");
|
||||
return;
|
||||
}
|
||||
const current = await cursorNativeWorkspaceSnapshot(input.workspacePath);
|
||||
await input.evidence(`cursor-workspace-${phase}.json`, { baseline, current });
|
||||
check(`workspace-unchanged-${phase}`, JSON.stringify(current) === JSON.stringify(baseline), "Independent workspace bytes remain unchanged by a pending/rejected/cancelled native plan or question");
|
||||
};
|
||||
const localDeniedTarget = !remote && design.id === "native-write-deny-reconnect" ? await createDeniedTargetFixture(input.workspacePath, `cursor-denied-${nonce}.txt`) : null;
|
||||
const deniedRelative = localDeniedTarget?.targetRelativePath ?? `cursor-denied-${nonce}.txt`;
|
||||
let deniedPath = remote ? "" : join(input.workspacePath, deniedRelative);
|
||||
let deniedCommand = remote ? null : cursorDeniedCommand(deniedPath);
|
||||
let denialNotices: CursorToolNotice[] = []; let denialRunEvents: Row[] = []; let denialTurnId = ""; let cancelRequestedAt = NaN; let cancellationProven = false;
|
||||
const samples: Array<{ phase: string; path: string; absent: boolean; observedAt: number }> = [];
|
||||
const sampleDenied = async (phase: string, retained?: CursorRemoteSnapshot) => {
|
||||
let sample: { phase: string; path: string; absent: boolean; observedAt: number };
|
||||
if (remote) {
|
||||
if (!remoteFixture) throw new Error("Cursor remote denied-target observer is absent");
|
||||
sample = cursorRemoteDeniedSample(retained ?? remoteFinal ?? await remoteFixture.snapshot(phase), remoteFixture.binding, deniedRelative, phase, remoteParent);
|
||||
} else sample = { phase, path: deniedPath, absent: await absent(deniedPath), observedAt: Date.now() };
|
||||
samples.push(sample); await input.evidence("cursor-denial-samples.json", samples); check(`denied-absent-${phase}`, sample.absent, "Independent denied target remains absent");
|
||||
};
|
||||
const processObserver = remote ? null : observeRunProcesses(); let processAuthority: string | null = null; let processObservationError = false;
|
||||
const observeProcesses = () => {
|
||||
const run = runs[0];
|
||||
const authority = run?.processPid ? { pid: run.processPid, groupId: run.processGroupId, startedAt: run.processStartedAt, runId: run.id } : undefined;
|
||||
if (authority) {
|
||||
const key = JSON.stringify(authority);
|
||||
if (processAuthority !== null && processAuthority !== key) processObservationError = true;
|
||||
processAuthority ??= key;
|
||||
}
|
||||
return processObserver ? processObserver.sample(authority) : { captured: false, journal: [], live: [] };
|
||||
};
|
||||
let processes = observeProcesses();
|
||||
let deniedRequest: Row | null = null;
|
||||
let processTimer: ReturnType<typeof setInterval> | undefined;
|
||||
const watch = localDeniedTarget?.watcher ?? null;
|
||||
if (watch) {
|
||||
processTimer = setInterval(() => { try { processes = observeProcesses(); } catch { processObservationError = true; } }, 250);
|
||||
input.registerCleanupAssertion!(async () => {
|
||||
const cleanupChecks: Check[] = [];
|
||||
const finalCheck = (id: string, passed: boolean, detail: string) => { cleanupChecks.push({ id, passed, detail }); };
|
||||
try {
|
||||
if (issue.id) await load();
|
||||
processes = observeProcesses();
|
||||
if (processes.captured && processes.live.length > 0 && !processObservationError) {
|
||||
processes = await pollUntil({ label: "observed Cursor provider retirement", deadlineAt: Date.now() + 5_000,
|
||||
load: async () => observeProcesses(), accept: observation => observation.live.length === 0 });
|
||||
}
|
||||
const settled = runs.length === 1 && runs[0]!.status === "cancelled" && issue.status === "in_progress" && cancellationProven;
|
||||
finalCheck("authoritative-provider-cleanup", settled && !processObservationError && processes.captured && processes.live.length === 0, "Exact API-bound per-turn process/start/group and observed descendants have retired");
|
||||
const finalSample = { phase: "after-cleanup", path: deniedPath, absent: await absent(deniedPath), observedAt: Date.now() };
|
||||
samples.push(finalSample);
|
||||
finalCheck("denied-absent-after-cleanup", finalSample.absent, "Independent target remains absent after observed provider retirement");
|
||||
const journal = watch.finish();
|
||||
finalCheck("continuous-denial-observation", journal.complete && journal.targetMutationCount === 0, "Continuous target watcher observed no create/delete mutation and retained directory identity");
|
||||
finalCheck("complete-native-denial-boundary", Boolean(deniedRequest) && hasCursorDenialBoundary({ request: deniedRequest, expectedRequestId: deniedRequest?.requestId ?? "", expectedToolCallId: deniedRequest?.details.toolCallId ?? "", path: deniedPath, bootstrapReadProof: remoteFixture ? { actionFile: remoteFixture.actionFile, events: denialRunEvents } : undefined, samples, notices: denialNotices, runId: runs[0]?.id ?? "", turnId: denialTurnId }), "Supported native denial preserved the target through all six independent boundaries");
|
||||
await input.evidence("cursor-native-denial-final.json", { request: deniedRequest, samples, notices: denialNotices, commandSha256: deniedCommand!.commandSha256, cancellationProven, cancelRequestedAt, processes, processObservationError, watcher: journal, checks: cleanupChecks });
|
||||
if (cleanupChecks.some(row => !row.passed)) throw new Error("Cursor native denial cleanup proof is incomplete or observed an effect");
|
||||
return cleanupChecks;
|
||||
} finally {
|
||||
clearInterval(processTimer);
|
||||
await input.evidence("cursor-native-denial-cleanup-attempt.json", { request: deniedRequest, samples, notices: denialNotices, commandSha256: deniedCommand!.commandSha256, cancellationProven, cancelRequestedAt, processes, processObservationError, watcher: watch.finish(), checks: cleanupChecks });
|
||||
}
|
||||
});
|
||||
}
|
||||
if (remote) input.registerBeforeEnvironmentTeardownAssertion!(async () => {
|
||||
const cleanupChecks: Check[] = []; let snapshot: CursorRemoteSnapshot | null = null;
|
||||
const finalCheck = (id: string, passed: boolean, detail: string) => { cleanupChecks.push({ id, passed, detail }); };
|
||||
try {
|
||||
if (!remoteFixture) throw new Error("Cursor remote observer never acquired authoritative baseline");
|
||||
if (issue.id) await load();
|
||||
snapshot = remoteFinal ?? await remoteFixture.finish(); remoteFinal = snapshot;
|
||||
finalCheck("remote-provider-retired", runs.length === 1 && remoteBaseline !== null && snapshot.observedAtMs >= remoteBaseline.observedAtMs && hasCursorRemoteRetirement(snapshot, remoteFixture.binding), "Exact remote run PID/start/boot identity and all observed descendants retired before the retained receipt sealed");
|
||||
if (design.id === "native-write-deny-reconnect") {
|
||||
await sampleDenied("after-cleanup", snapshot);
|
||||
finalCheck("remote-cancel-terminal", cancellationProven && runs[0]?.status === "cancelled" && issue.status === "in_progress", "Explicit native cancellation remains durable without false task completion");
|
||||
finalCheck("remote-no-denied-effect", snapshot.watcher.targetMutationCount === 0 && Boolean(deniedRequest) && hasCursorDenialBoundary({ request: deniedRequest, expectedRequestId: deniedRequest?.requestId ?? "", expectedToolCallId: deniedRequest?.details.toolCallId ?? "", path: deniedPath, bootstrapReadProof: remoteFixture ? { actionFile: remoteFixture.actionFile, events: denialRunEvents } : undefined, samples, notices: denialNotices, runId: runs[0]?.id ?? "", turnId: denialTurnId }), "Exact denied native command caused no remote file effect through provider retirement");
|
||||
} else {
|
||||
if (design.id === "native-plan-reject-revise-accept") finalCheck("remote-plan-still-passive", hasCursorAcceptedPlanWait(await load()), "Accepted planning remains passive through remote retirement without an automatic follow-up run");
|
||||
finalCheck("remote-no-workspace-effects", hasCursorRemoteWorkspaceUnchanged(snapshot, remoteBaseline!), "Native question or cancelled plan caused no remote workspace mutation through retirement");
|
||||
}
|
||||
if (cleanupChecks.some(row => !row.passed)) throw new Error("Cursor remote cleanup evidence is incomplete or observed an effect");
|
||||
return cleanupChecks;
|
||||
} finally {
|
||||
try { await input.evidence("cursor-remote-cleanup.json", { snapshot, samples, notices: denialNotices, cancellationProven, checks: cleanupChecks }); }
|
||||
finally { await remoteFixture?.close(); }
|
||||
}
|
||||
});
|
||||
const load = async () => {
|
||||
issue = await api.get<Row>(`/api/issues/${issue.id}`);
|
||||
const listed = await api.get<Row[]>(`/api/companies/${fixtures.company.id}/heartbeat-runs?limit=100`);
|
||||
runs = await Promise.all(listed.map(run => api.get<Row>(`/api/heartbeat-runs/${run.id}`)));
|
||||
runs.sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt))); input.observe(issue, runs);
|
||||
if (watch) processes = observeProcesses();
|
||||
const interactions = await api.get<Row[]>(`/api/issues/${issue.id}/interactions`);
|
||||
const runEvents = runs.length === 1 ? await events(runs[0]!.id) : [];
|
||||
if (design.id === "native-write-deny-reconnect" && runs.length === 1) { denialRunEvents = runEvents; denialNotices = readCursorToolEvidence(runEvents, runs[0]!.id); }
|
||||
return { issue, runs, interactions, runEvents };
|
||||
};
|
||||
if (!remote && design.id === "native-plan-reject-revise-accept") input.registerCleanupAssertion!(async () => {
|
||||
const current = await load();
|
||||
const currentWorkspace = await cursorNativeWorkspaceSnapshot(input.workspacePath);
|
||||
const cleanupChecks = [
|
||||
{ id: "plan-still-passive-after-cleanup", passed: hasCursorAcceptedPlanWait(current), detail: "One succeeded planning run remains unfinished without automatic follow-up through fixture cleanup" },
|
||||
{ id: "plan-workspace-unchanged-after-cleanup", passed: isDeepStrictEqual(currentWorkspace, baseline), detail: "Accepted planning caused no workspace effect through fixture cleanup" },
|
||||
];
|
||||
await input.evidence("cursor-native-plan-wait-cleanup.json", { ...current, baseline, currentWorkspace, checks: cleanupChecks });
|
||||
if (cleanupChecks.some(row => !row.passed)) throw new Error("Accepted Cursor plan did not remain a passive no-effect boundary");
|
||||
return cleanupChecks;
|
||||
});
|
||||
const reject = (state: Awaited<ReturnType<typeof load>>) => state.runs.length > 1 ? "Unexpected extra Cursor provider run" : state.runs.some(run => ["failed", "cancelled", "timed_out"].includes(run.status)) ? "Cursor provider run failed" : undefined;
|
||||
async function pending(seen: Set<string>) {
|
||||
const state = await pollUntil({ label: "exact native Cursor callback", deadlineAt: input.deadlineAt, load,
|
||||
reject: state => reject(state) ?? (state.runs.some(run => run.status === "succeeded") ? "Native Cursor callback was not observed before completion; qualification remains pending" : undefined),
|
||||
accept: state => state.interactions.some(card => card.status === "pending" && !seen.has(card.id) && card.payload?.runtimeRequestId && findCursorNativeRequest(state.runEvents, design!.method, card.payload.runtimeRequestId)) });
|
||||
const cards = state.interactions.filter(card => card.status === "pending"); check("single-native-request", cards.length === 1 && state.runs.length === 1, "Exactly one native request belongs to one original provider run");
|
||||
const card = cards[0]!; const event = findCursorNativeRequest(state.runEvents, design!.method, card.payload.runtimeRequestId)!;
|
||||
check("native-card-binding", hasCursorNativeCardBinding(card, event, state.runs[0]!.id), "Durable card retains complete native input and exact source run");
|
||||
await input.evidence(`cursor-native-${seen.size}-pending.json`, { card, event });
|
||||
await page.reload(); const reloaded = (await load()).interactions.find(row => row.id === card.id);
|
||||
check("browser-reconnect-identity", reloaded?.status === "pending" && reloaded?.payload.runtimeRequestId === card.payload.runtimeRequestId, "Browser reconnect preserves exact outstanding native request");
|
||||
await input.capture(`cursor-native-${seen.size}`, "Native Cursor request pending", `cursor-native-${seen.size}.png`);
|
||||
return { card, event };
|
||||
}
|
||||
async function delivery(card: Row, event: Row, response: Row) {
|
||||
const identity = { runId: runs[0]!.id, turnId: event.turnId, requestId: card.payload.runtimeRequestId, method: design!.method, action: "submit" as const, response };
|
||||
const state = await pollUntil({ label: "native response stream delivery", deadlineAt: input.deadlineAt, load, reject,
|
||||
accept: state => state.interactions.some(row => row.id === card.id && row.status === "answered") && hasExactCursorNativeResponse({ ...identity, events: state.runEvents }) });
|
||||
check("exact-native-delivery", hasExactCursorNativeResponse({ ...identity, events: state.runEvents }), "Exact displayed answer reached the native response writer and produced one ordered delivery receipt");
|
||||
await input.evidence(`cursor-native-${card.id}-delivered.json`, { interaction: state.interactions.find(row => row.id === card.id), events: state.runEvents, response });
|
||||
}
|
||||
let expectedMarker = execution.task.buildVisibleMarker(nonce);
|
||||
try {
|
||||
if (!remote && design.id === "native-write-deny-reconnect") await sampleDenied("before-request");
|
||||
await createTaskThroughUi({ page, issuePrefix: fixtures.company.issuePrefix!, agentName: fixtures.agent.name, title: execution.task.buildTitle(nonce), prompt: remote ? input.remoteBootstrap!.prompt(nonce) : execution.task.buildPrompt(nonce) + (watch ? `\nExact native shell command (copy verbatim):\n${deniedCommand!.command}` : ""), workMode: "standard", projectName: project.name });
|
||||
issue = await pollUntil({ label: "browser-created Cursor task", deadlineAt: input.deadlineAt, load: async () => (await api.get<Row[]>(`/api/companies/${fixtures.company.id}/issues?limit=100`)).find(row => row.title === execution.task.buildTitle(nonce)), accept: Boolean }) ?? {};
|
||||
if (!issue.id) throw new Error("Browser-created Cursor task is absent");
|
||||
if (remote) {
|
||||
const started = await pollUntil({ label: "exact Cursor bootstrap run", deadlineAt: input.deadlineAt, load, reject,
|
||||
accept: state => state.runs.length === 1 });
|
||||
const runId = started.runs[0]!.id;
|
||||
const boundFixture = await input.remoteBootstrap!.bindAndRelease({ issueId: issue.id, runId,
|
||||
targets: design.id === "native-write-deny-reconnect" ? [deniedRelative] : [],
|
||||
actionPrompt: async fixture => {
|
||||
if (remoteFixture) throw new Error("Cursor remote action was published more than once");
|
||||
remoteFixture = fixture;
|
||||
const prepared = await prepareCursorRemoteAction({ fixture, runId, companyId: fixtures.company.id, environmentId: fixtures.environment.id,
|
||||
prompt: execution.task.buildPrompt(nonce), ...(design.id === "native-write-deny-reconnect" ? { deniedRelative } : {}) });
|
||||
remoteBaseline = prepared.baseline;
|
||||
if (prepared.initial && prepared.command) {
|
||||
deniedPath = prepared.initial.path; deniedCommand = prepared.command; remoteParent = prepared.initial.parent; samples.push(prepared.initial);
|
||||
}
|
||||
return prepared.prompt;
|
||||
} });
|
||||
if (!remoteFixture || boundFixture !== remoteFixture || boundFixture.binding.runId !== runId) throw new Error("Cursor remote observer is missing its run binding");
|
||||
await input.evidence("cursor-remote-baseline.json", remoteBaseline);
|
||||
}
|
||||
await page.goto(`/${fixtures.company.issuePrefix}/issues/${issue.identifier ?? issue.id}`);
|
||||
const seen = new Set<string>();
|
||||
if (design.id === "native-question-reconnect") {
|
||||
const { card, event } = await pending(seen); const questions = card.payload.questionSet.questions;
|
||||
if (remote) await sampleWorkspace("question-pending");
|
||||
check("native-question-shape", questions.length === 2 && questions[0].answerMode === "single_select" && questions[1].answerMode === "multi_select", "Native single/multiple choice shape is preserved");
|
||||
const color = randomBytes(1)[0]! % 2 === 0 ? "Cobalt" : "Amber";
|
||||
const trees = randomBytes(1)[0]! % 2 === 0 ? ["Cedar", "Maple"] : ["Maple"];
|
||||
await page.getByRole("radio", { name: color, exact: true }).last().click();
|
||||
await page.getByRole("button", { name: "Next", exact: true }).last().click();
|
||||
for (const tree of trees) await page.getByRole("checkbox", { name: tree, exact: true }).last().click();
|
||||
const answers = Object.fromEntries(questions.map((question: Row, index: number) => [question.id, { selectedOptionIds: (index === 0 ? [color] : trees).map(label => question.options.find((option: Row) => option.label === label)?.id) }]));
|
||||
await page.getByRole("button", { name: card.payload.questionSet.submitLabel ?? "Submit answers", exact: true }).last().click();
|
||||
await delivery(card, event, { schema: "paperclip.question_response.v1", answers });
|
||||
expectedMarker = `CURSOR-NATIVE-${nonce}-${color.toLowerCase()}-${trees.map(tree => tree.toLowerCase()).sort().join("+")}`;
|
||||
await sampleWorkspace("question-delivered");
|
||||
} else if (design.method === "cursor/create_plan") {
|
||||
const decisions = design.id === "native-plan-cancel" ? ["cancel"] as const : ["reject", "accept"] as const;
|
||||
const feedbackMarker = `revision-${randomBytes(12).toString("hex")}`;
|
||||
const feedback = `Include verification marker ${feedbackMarker} in the revised plan.`; let previousRevision: string | null = null;
|
||||
for (const decision of decisions) {
|
||||
const { card, event } = await pending(seen); const set = card.payload.questionSet; const plan = set.questions.find((question: Row) => /^plan-[a-f0-9]{64}$/.test(question.id));
|
||||
check("full-plan-revision", typeof set.description === "string" && set.description.length > 0 && Boolean(plan) && plan.id !== previousRevision, "Complete native plan and a distinct content-bound revision are retained");
|
||||
if (decision === "accept") check("revision-feedback", set.description.includes(feedbackMarker), "Revised native plan contains exact undisclosed rejection feedback");
|
||||
for (const marker of [`CURSOR-PLAN-BEGIN-${nonce}`, `CURSOR-PLAN-END-${nonce}`]) {
|
||||
check("complete-plan-boundary", set.description.includes(marker), "Retained native plan includes its full document boundaries");
|
||||
await expect(page.getByRole("region", { name: "Question context" }).last()).toContainText(marker);
|
||||
}
|
||||
await sampleWorkspace(`plan-${decision}-pending`);
|
||||
await page.getByRole("radio", { name: decision === "accept" ? "Accept plan" : decision === "reject" ? "Reject plan" : "Cancel plan request", exact: true }).last().click();
|
||||
await page.getByRole("button", { name: "Next", exact: true }).last().click();
|
||||
if (decision === "reject") await page.getByTestId("question-text-answer-composer").last().locator('[contenteditable="true"],textarea').first().fill(feedback);
|
||||
const response = cursorNativePlanResponse(plan.id, decision, feedback);
|
||||
check("revision-bound-decision", hasCursorPlanDecision(set, response, decision), "Decision addresses precisely the displayed native plan revision");
|
||||
await page.getByRole("button", { name: set.submitLabel ?? "Submit answers", exact: true }).last().click();
|
||||
await delivery(card, event, response); seen.add(card.id); previousRevision = plan.id;
|
||||
if (decision !== "accept") await sampleWorkspace(`plan-${decision}-delivered`);
|
||||
}
|
||||
await input.evidence("cursor-native-artifact-gap.json", cursorNativePlanArtifactGate);
|
||||
} else {
|
||||
const state = await pollUntil({ label: "native Cursor permission with exact command provenance", deadlineAt: input.deadlineAt, load, reject,
|
||||
accept: state => denialNotices.some(notice => notice.stage === "permission_requested" && notice.commandSha256 === deniedCommand!.commandSha256
|
||||
&& Boolean(findCursorNativeRequest(state.runEvents, "session/request_permission", notice.requestId))) });
|
||||
const native = denialNotices.find(notice => notice.stage === "permission_requested" && notice.commandSha256 === deniedCommand!.commandSha256)!;
|
||||
const event = findCursorNativeRequest(state.runEvents, "session/request_permission", native.requestId)!; const request = event.payload.request; deniedRequest = request; denialTurnId = event.turnId;
|
||||
check("native-permission-identity", state.runs.length === 1 && request.details?.toolCallId === native.toolCallId && native.turnId === event.turnId && native.declineOffered && request.choices.some((choice: Row) => choice.key === "decline"), "Presented native permission is bound to the exact absolute-target command and supported denial choice");
|
||||
await sampleDenied("pending"); await page.reload();
|
||||
const reloaded = await load(); check("permission-reconnect", Boolean(findCursorNativeRequest(reloaded.runEvents, "session/request_permission", request.requestId)) && !reloaded.runEvents.some(row => row.payload?.prpEvent?.eventType === "runtime_request.resolved" && row.payload.prpEvent.payload?.requestId === request.requestId), "Reconnect preserves the unresolved native permission");
|
||||
await sampleDenied("browser-reconnected"); await input.capture("cursor-permission", "Native write permission awaiting denial", "cursor-permission.png");
|
||||
const card = page.getByTestId("task-chat-runtime-request").filter({ visible: true }); await expect(card).toHaveCount(1);
|
||||
const label = request.choices.find((choice: Row) => choice.key === "decline").label;
|
||||
const route = `/api/heartbeat-runs/${native.runId}/runtime-requests/${encodeURIComponent(request.requestId)}/resolve`;
|
||||
const sent = page.waitForRequest(row => new URL(row.url()).pathname === route && row.method() === "POST");
|
||||
await card.getByRole("button", { name: label, exact: true }).click(); const posted = (await sent).postDataJSON();
|
||||
check("browser-exact-denial", posted.turnId === event.turnId && posted.requestKind === "permission_approval" && posted.resolution?.action === "decline", "Browser denied the exact native run/request/turn");
|
||||
const identity = { runId: native.runId, turnId: event.turnId, requestId: request.requestId, method: "session/request_permission" as const, action: "decline" as const };
|
||||
await pollUntil({ label: "native denial delivered and exact command failed", deadlineAt: input.deadlineAt, load, reject, accept: state => hasDeliveredCursorNativeRequest({ ...identity, events: state.runEvents })
|
||||
&& hasCursorDeniedCommand({ notices: denialNotices, ...identity, toolCallId: native.toolCallId, commandSha256: deniedCommand!.commandSha256, bootstrapReadProof: remoteFixture ? { actionFile: remoteFixture.actionFile, events: denialRunEvents } : undefined }) });
|
||||
await sampleDenied("after-decision");
|
||||
cancelRequestedAt = Date.now(); await api.post(`/api/heartbeat-runs/${native.runId}/cancel`);
|
||||
const cancelled = await pollUntil({ label: "explicit native cancellation", deadlineAt: input.deadlineAt, load,
|
||||
reject: state => state.runs.length !== 1 || ["failed", "succeeded", "timed_out"].includes(state.runs[0]?.status) ? "Cursor denial did not remain cancellable" : undefined,
|
||||
accept: state => hasCursorCancellation({ run: state.runs[0], issue: state.issue, events: state.runEvents, runId: native.runId, turnId: event.turnId, requestedAt: cancelRequestedAt }) });
|
||||
cancellationProven = true;
|
||||
if (remote) remoteFinal = await remoteFixture!.finish();
|
||||
await sampleDenied("after-terminal", remoteFinal ?? undefined);
|
||||
check("negative-task-unfinished", cancelled.issue.status === "in_progress" && cancelled.runs[0]?.status === "cancelled" && cancelled.runs[0]?.runtimeMode === "native", "Native cancellation was acknowledged and the task does not falsely claim completion");
|
||||
await page.reload();
|
||||
await expect(page.getByTestId("issue-detail-header").getByRole("button", { name: "Change status (current: In Progress)", exact: true })).toBeVisible();
|
||||
const comments = await api.get<Row[]>(`/api/issues/${issue.id}/comments`);
|
||||
await input.evidence("api-state.json", { ...cancelled, run: runs[0], comments, checks, notices: denialNotices, commandSha256: deniedCommand!.commandSha256, cancelRequestedAt, runEventsByRun: [{ runId: native.runId, events: cancelled.runEvents }] });
|
||||
await input.capture("final-state", "Cursor denied command cancelled; task remains unfinished", "final-state.png");
|
||||
return { issue, runs, checks };
|
||||
}
|
||||
if (design.id === "native-plan-reject-revise-accept") {
|
||||
await pollUntil({ label: "accepted Cursor plan waiting for explicit continuation", deadlineAt: input.deadlineAt, load, reject, accept: hasCursorAcceptedPlanWait });
|
||||
const observedAt = Date.now();
|
||||
const final = await pollUntil({ label: "passive Cursor plan stability", deadlineAt: input.deadlineAt, load,
|
||||
reject: state => hasCursorAcceptedPlanWait(state) ? undefined : "Accepted plan started follow-up work or lost its passive disposition",
|
||||
accept: state => hasCursorAcceptedPlanWait(state) && Date.now() - observedAt >= 2_000, intervalMs: 250 });
|
||||
if (remote) remoteFinal = await remoteFixture!.finish();
|
||||
await sampleWorkspace("accepted-plan-terminal");
|
||||
check("accepted-plan-passive-terminal", hasCursorAcceptedPlanWait(final), "Successful planning remains in progress with exact controller wait reason and selected Plan mode");
|
||||
const comments = await api.get<Row[]>(`/api/issues/${issue.id}/comments`);
|
||||
const summary = "Plan accepted. This task is waiting for your next message. This run used Plan mode; no implementation or task completion is claimed.";
|
||||
check("explicit-plan-next-action", comments.some(comment => comment.createdByRunId === runs[0]!.id && comment.body === summary), "The original planning run durably presents explicit user continuation");
|
||||
await page.reload(); await expect(page.getByText(summary, { exact: true }).last()).toBeVisible();
|
||||
await expect(page.getByTestId("issue-detail-header").getByRole("button", { name: "Change status (current: In Progress)", exact: true })).toBeVisible();
|
||||
await input.evidence("api-state.json", { ...final, run: runs[0], comments, checks, passiveObservedFrom: observedAt, passiveObservedUntil: Date.now(), runEventsByRun: [{ runId: runs[0]!.id, events: final.runEvents }] });
|
||||
await input.capture("final-state", "Accepted Cursor plan waiting for the next user message", "final-state.png");
|
||||
return { issue, runs, checks };
|
||||
}
|
||||
const final = await pollUntil({ label: "Cursor native completion", deadlineAt: input.deadlineAt, load, reject,
|
||||
accept: state => state.issue.status === "done" && state.runs.length === 1 && state.runs[0]!.status === "succeeded" && !state.interactions.some(card => card.status === "pending") });
|
||||
if (remote) remoteFinal = await remoteFixture!.finish();
|
||||
check("one-native-run", final.runs[0]!.runtimeMode === "native", "Decision and completion remained in the original native provider run");
|
||||
if (design.id === "native-plan-cancel" || design.id === "native-question-reconnect") await sampleWorkspace("native-terminal");
|
||||
await page.reload(); await expect(page.getByText(expectedMarker, { exact: true }).last()).toBeVisible();
|
||||
await expect(page.getByTestId("issue-detail-header").getByRole("button", { name: "Change status (current: Done)", exact: true })).toBeVisible();
|
||||
const comments = await api.get<Row[]>(`/api/issues/${issue.id}/comments`);
|
||||
await input.evidence("api-state.json", { ...final, run: runs[0], comments, checks, runEventsByRun: [{ runId: runs[0]!.id, events: final.runEvents }] });
|
||||
await input.capture("final-state", "Cursor native callback fixture verified", "final-state.png");
|
||||
return { issue, runs, checks };
|
||||
} finally { await input.evidence("cursor-native-checks.json", { issue, runs, checks }); }
|
||||
}
|
||||
@@ -29,16 +29,27 @@ export const DAYTONA_IMAGE_INPUT_PATHS = [
|
||||
"packages/paperclip-eval-kernel/tsconfig.json",
|
||||
"packages/paperclip-runner/scripts/provision-grok.mjs",
|
||||
"packages/paperclip-runner/package.json",
|
||||
"packages/paperclip-runner/cursor-distributions.json",
|
||||
"packages/paperclip-runner/cursor-contract.json",
|
||||
"packages/paperclip-runner/protocol",
|
||||
"packages/paperclip-runner/runner/Cargo.lock",
|
||||
"packages/paperclip-runner/runner/Cargo.toml",
|
||||
"packages/paperclip-runner/runner/crates",
|
||||
"packages/paperclip-runner/scripts/acpx-sidecar-contract.mjs",
|
||||
"packages/paperclip-runner/scripts/build-provider-pack.mjs",
|
||||
"packages/paperclip-runner/scripts/build-node-startup-timeout.mjs",
|
||||
"packages/paperclip-runner/scripts/candidate-provider-pack.mjs",
|
||||
"packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs",
|
||||
"packages/paperclip-runner/scripts/cursor-runtime-patch.mjs",
|
||||
"packages/paperclip-runner/scripts/cursor-native-usage.mjs",
|
||||
"packages/paperclip-runner/scripts/cursor-native-usage-source.json",
|
||||
"packages/paperclip-runner/scripts/provision-cursor.mjs",
|
||||
"packages/paperclip-runner/cursor-distributions.json",
|
||||
"packages/paperclip-runner/cursor-contract.json",
|
||||
"packages/paperclip-runner/scripts/build-verified-provider-entrypoints.mjs",
|
||||
"packages/paperclip-runner/scripts/generate-acpx-sidecar-contract.mjs",
|
||||
"packages/paperclip-runner/scripts/generate-protocol-schema-module.mjs",
|
||||
// Pi runtime/extension/Node/closure pins are included by the src tree below.
|
||||
"packages/paperclip-runner/src",
|
||||
"packages/paperclip-runner/styles.css",
|
||||
"packages/paperclip-runner/tsconfig.json",
|
||||
|
||||
@@ -200,6 +200,9 @@ describe("runner E2E Daytona image contract", () => {
|
||||
"packages/paperclip-eval-kernel/src",
|
||||
"packages/paperclip-runner/package.json",
|
||||
"packages/paperclip-runner/scripts/candidate-provider-pack.mjs",
|
||||
"packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs",
|
||||
"packages/paperclip-runner/scripts/cursor-runtime-patch.mjs",
|
||||
"packages/paperclip-runner/cursor-distributions.json",
|
||||
"packages/paperclip-runner/runner/crates",
|
||||
"packages/paperclip-runner/src",
|
||||
]) {
|
||||
@@ -275,6 +278,8 @@ describe("runner E2E Daytona image contract", () => {
|
||||
),
|
||||
'pub const VERSION: &str = "one";\n',
|
||||
);
|
||||
for (const relativePath of [
|
||||
]) await writeFile(path.join(root, relativePath), "version one\n");
|
||||
const baseline = await computeDaytonaImageContentId(options);
|
||||
const candidate = await computeDaytonaImageContentId({ ...options, candidateProviders: ["pi"] });
|
||||
expect(candidate).not.toBe(baseline);
|
||||
@@ -329,6 +334,28 @@ describe("runner E2E Daytona image contract", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("invalidates the image when the Cursor runtime isolation patch changes", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paperclip-cursor-image-id-"));
|
||||
const patchPath = "packages/paperclip-runner/scripts/cursor-runtime-patch.mjs";
|
||||
expect(DAYTONA_IMAGE_INPUT_PATHS).toContain(patchPath);
|
||||
const options = {
|
||||
repositoryRoot: root,
|
||||
inputPaths: [patchPath],
|
||||
baseImages: [`example.test/base:1@sha256:${"a".repeat(64)}`],
|
||||
frontendDigest: `sha256:${"c".repeat(64)}`,
|
||||
candidateProviders: ["cursor"],
|
||||
} as const;
|
||||
try {
|
||||
await mkdir(path.dirname(path.join(root, patchPath)), { recursive: true });
|
||||
await writeFile(path.join(root, patchPath), "export const policy = 'one';\n");
|
||||
const baseline = await computeDaytonaImageContentId(options);
|
||||
await writeFile(path.join(root, patchPath), "export const policy = 'two';\n");
|
||||
expect(await computeDaytonaImageContentId(options)).not.toBe(baseline);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("reuses the image for runner-only tests and documentation", async () => {
|
||||
const root = await mkdtemp(
|
||||
path.join(tmpdir(), "paperclip-daytona-runner-development-inputs-"),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ObservedStateTimeout } from "./api.js";
|
||||
import { ObservedStateTimeout, RemoteAdmissionReadError } from "./api.js";
|
||||
import type { FailureClass } from "./types.js";
|
||||
|
||||
const TRANSIENT =
|
||||
@@ -21,7 +21,7 @@ const SANDBOX_TRANSFER_TIMEOUT =
|
||||
/RPC call "environmentSync(?:In|Out)" timed out after \d+ms/i;
|
||||
|
||||
export function classifyFailure(error: unknown): FailureClass {
|
||||
if (error instanceof ObservedStateTimeout) return error.failureClass;
|
||||
if (error instanceof ObservedStateTimeout || error instanceof RemoteAdmissionReadError) return error.failureClass;
|
||||
const message =
|
||||
error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
||||
if (/browser bootstrap failed before task creation/i.test(message))
|
||||
|
||||
@@ -115,8 +115,12 @@ export function buildRunnerE2EProcessEnvironment(
|
||||
for (const execution of executions) {
|
||||
const agent = execution.profile.qualificationCandidate;
|
||||
if (!agent) continue;
|
||||
if (execution.suite.id !== "extended-harnesses" || !execution.suite.manualOnly) {
|
||||
throw new Error("Candidate qualification requires the explicit extended-harnesses suite");
|
||||
const admittedSuite = execution.suite.id === "extended-harnesses"
|
||||
|| execution.suite.id === "rich-acp-warm-continuity"
|
||||
|| (execution.suite.id === "cursor-native" && agent === "cursor")
|
||||
|| (execution.suite.id === "native-active-stop" && agent === "cursor");
|
||||
if (!admittedSuite || !execution.suite.manualOnly) {
|
||||
throw new Error("Candidate qualification requires an explicit provider qualification suite");
|
||||
}
|
||||
const prior = candidates.get(agent);
|
||||
if (prior !== undefined && prior !== execution.profile.model) throw new Error("Conflicting candidate models");
|
||||
|
||||
+32
-175
@@ -1,3 +1,4 @@
|
||||
import { createProcessTreeOwner, stopOwnedProcessTree } from "./process-tree-owner.js";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { prepareCodexCiSandbox, requiresCodexCiSandbox } from "./codex-ci-sandbox.js";
|
||||
import { spawn } from "node:child_process";
|
||||
@@ -50,7 +51,7 @@ import {
|
||||
type MatrixExecution,
|
||||
type RunnerE2EResult,
|
||||
} from "./types.js";
|
||||
import { assertRunnerE2EPrerequisites } from "./prerequisites.js";
|
||||
import { assertRemoteNativeEvidencePrerequisites, assertRunnerE2EPrerequisites } from "./prerequisites.js";
|
||||
import { assertNativeCompletionSelection, prepareNativeCompletionPreflight, NATIVE_COMPLETION_PREFLIGHT_ENV } from "./native-completion-admission.js";
|
||||
import { prepareStockHarnessPreflight, STOCK_PREFLIGHT_ENV } from "./stock-harness-admission.js";
|
||||
|
||||
@@ -65,11 +66,8 @@ import {
|
||||
} from "./result-exit-guard.js";
|
||||
import {
|
||||
observeDescendantProcessTree,
|
||||
refreshContinuouslyLiveProcessGroups,
|
||||
revalidateObservedProcessGroups,
|
||||
safeProcessGroupTerminationOrder,
|
||||
type ObservedProcessGroup,
|
||||
type ProcessObservation,
|
||||
readProcessTable,
|
||||
} from "./process-tree.js";
|
||||
|
||||
const repositoryRoot = path.resolve(import.meta.dirname, "../..");
|
||||
@@ -79,19 +77,6 @@ const activeProcessGroups = new Set<number>();
|
||||
const activeProcessCleanup = new Map<number, Promise<string | null>>();
|
||||
const activeProcessTerminators = new Map<number, () => void>();
|
||||
const completedResultExitGraceMs = 120_000;
|
||||
const diagnosticProcessKinds = new Set([
|
||||
"bash",
|
||||
"chrome",
|
||||
"codex",
|
||||
"google-chrome",
|
||||
"node",
|
||||
"paperclip-runnerd",
|
||||
"playwright",
|
||||
"pnpm",
|
||||
"postgres",
|
||||
"sh",
|
||||
"tsx",
|
||||
]);
|
||||
let cancelled = false;
|
||||
|
||||
function cleanId(value: string) {
|
||||
@@ -165,72 +150,6 @@ interface ProcessTreeDiagnostic {
|
||||
groups: ObservedProcessGroup[];
|
||||
}
|
||||
|
||||
function observedGroupsSelectedForTermination(
|
||||
groups: readonly ObservedProcessGroup[],
|
||||
processGroupIds: readonly number[],
|
||||
) {
|
||||
const selected = new Set(processGroupIds);
|
||||
return groups.filter((group) => selected.has(group.processGroupId));
|
||||
}
|
||||
|
||||
async function readProcessTable(): Promise<ProcessObservation[] | null> {
|
||||
if (process.platform === "win32") {
|
||||
return null;
|
||||
}
|
||||
return await new Promise<ProcessObservation[] | null>((resolve) => {
|
||||
const inspector = spawn(
|
||||
"ps",
|
||||
["-e", "-o", "pid=,ppid=,pgid=,lstart=,comm="],
|
||||
{
|
||||
env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" },
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
},
|
||||
);
|
||||
let output = "";
|
||||
let settled = false;
|
||||
const finish = (value: ProcessObservation[] | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(inspectionTimeout);
|
||||
resolve(value);
|
||||
};
|
||||
const inspectionTimeout = setTimeout(() => {
|
||||
inspector.kill("SIGKILL");
|
||||
finish(null);
|
||||
}, 5_000);
|
||||
inspectionTimeout.unref();
|
||||
inspector.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
|
||||
output = `${output}${chunk}`.slice(-1024 * 1024);
|
||||
});
|
||||
inspector.once("error", () => finish(null));
|
||||
inspector.once("close", () => {
|
||||
const observations = output
|
||||
.split(/\r?\n/)
|
||||
.map((line) =>
|
||||
/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+?)\s*$/.exec(
|
||||
line,
|
||||
),
|
||||
)
|
||||
.filter((match): match is RegExpExecArray => match !== null)
|
||||
.map((match): ProcessObservation => {
|
||||
// A target process can choose its own argv and process name. Emit a
|
||||
// fixed category instead of target-controlled text so diagnostics
|
||||
// can never turn that metadata into a secret-exfiltration channel.
|
||||
const command = path.basename(match[5]!);
|
||||
const kind = diagnosticProcessKinds.has(command) ? command : "other";
|
||||
return {
|
||||
pid: Number(match[1]),
|
||||
parentPid: Number(match[2]),
|
||||
processGroupId: Number(match[3]),
|
||||
started: match[4]!,
|
||||
kind,
|
||||
};
|
||||
});
|
||||
finish(observations);
|
||||
});
|
||||
}).catch(() => null);
|
||||
}
|
||||
|
||||
async function processTreeDiagnostic(
|
||||
rootPid: number,
|
||||
): Promise<ProcessTreeDiagnostic> {
|
||||
@@ -357,6 +276,7 @@ async function runProcess(
|
||||
});
|
||||
if (!child.pid) throw new Error("Failed to start Playwright");
|
||||
activeProcessGroups.add(child.pid);
|
||||
const processOwner = createProcessTreeOwner(child);
|
||||
let outputTail = "";
|
||||
const recordOutput = (chunk: Buffer, destination: NodeJS.WriteStream) => {
|
||||
destination.write(chunk);
|
||||
@@ -374,90 +294,14 @@ async function runProcess(
|
||||
let childSettled = false;
|
||||
let postResultStallError: string | null = null;
|
||||
let boundedCleanup: Promise<string | null> | undefined;
|
||||
const forceStopDirectChild = () => {
|
||||
if (!childSettled && child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
};
|
||||
const stopChildTree = (diagnostic?: ProcessTreeDiagnostic) => {
|
||||
let cleanupSettled!: () => void;
|
||||
const cleanupFinished = new Promise<number>(resolve => { cleanupSettled = () => resolve(1); });
|
||||
const stopChildTree = (_diagnostic?: ProcessTreeDiagnostic) => {
|
||||
if (boundedCleanup) return;
|
||||
const rootProcessGroupId = child.pid!;
|
||||
boundedCleanup = (async () => {
|
||||
const snapshot = diagnostic ?? (await processTreeDiagnostic(child.pid!));
|
||||
const validationTable = await readProcessTable();
|
||||
const currentProcessGroupId = validationTable
|
||||
? (validationTable.find((candidate) => candidate.pid === process.pid)
|
||||
?.processGroupId ?? null)
|
||||
: null;
|
||||
const observedGroups = validationTable
|
||||
? revalidateObservedProcessGroups(snapshot.groups, validationTable)
|
||||
: [];
|
||||
const terminationOrder = safeProcessGroupTerminationOrder({
|
||||
rootProcessGroupId,
|
||||
currentProcessGroupId,
|
||||
groups: observedGroups,
|
||||
});
|
||||
const verifiedGroups = observedGroupsSelectedForTermination(
|
||||
observedGroups,
|
||||
terminationOrder,
|
||||
);
|
||||
if (verifiedGroups.length === 0) {
|
||||
forceStopDirectChild();
|
||||
return "Could not revalidate an owned process group before cleanup";
|
||||
}
|
||||
for (const processGroupId of terminationOrder) {
|
||||
stopProcessGroup(processGroupId, "SIGTERM");
|
||||
}
|
||||
|
||||
let remainingGroups = verifiedGroups;
|
||||
const gracefulDeadline = Date.now() + 5_000;
|
||||
while (remainingGroups.length > 0 && Date.now() < gracefulDeadline) {
|
||||
const table = await readProcessTable();
|
||||
if (table) {
|
||||
remainingGroups = refreshContinuouslyLiveProcessGroups(
|
||||
remainingGroups,
|
||||
table,
|
||||
);
|
||||
}
|
||||
if (remainingGroups.length > 0) await wait(50);
|
||||
}
|
||||
const remainingGroupIds = new Set(
|
||||
remainingGroups.map((group) => group.processGroupId),
|
||||
);
|
||||
const forcedOrder = safeProcessGroupTerminationOrder({
|
||||
rootProcessGroupId,
|
||||
currentProcessGroupId,
|
||||
groups: remainingGroups,
|
||||
}).filter((processGroupId) => remainingGroupIds.has(processGroupId));
|
||||
for (const processGroupId of forcedOrder) {
|
||||
stopProcessGroup(processGroupId, "SIGKILL");
|
||||
}
|
||||
|
||||
const forcedDeadline = Date.now() + 5_000;
|
||||
let forcedVerificationUnavailable = false;
|
||||
while (Date.now() < forcedDeadline) {
|
||||
const table = await readProcessTable();
|
||||
if (!table) {
|
||||
forcedVerificationUnavailable = true;
|
||||
await wait(50);
|
||||
continue;
|
||||
}
|
||||
forcedVerificationUnavailable = false;
|
||||
remainingGroups = refreshContinuouslyLiveProcessGroups(
|
||||
remainingGroups,
|
||||
table,
|
||||
);
|
||||
if (remainingGroups.length === 0) return null;
|
||||
await wait(50);
|
||||
}
|
||||
if (forcedVerificationUnavailable) {
|
||||
return "Could not verify descendant process exit after SIGKILL";
|
||||
}
|
||||
return `Verified descendant process groups ${remainingGroups
|
||||
.map((group) => group.processGroupId)
|
||||
.join(",")} survived SIGKILL`;
|
||||
})();
|
||||
activeProcessCleanup.set(rootProcessGroupId, boundedCleanup);
|
||||
boundedCleanup = stopOwnedProcessTree(child, processOwner)
|
||||
.then(() => null, error => error instanceof Error ? error.message : String(error))
|
||||
.finally(cleanupSettled);
|
||||
activeProcessCleanup.set(child.pid!, boundedCleanup);
|
||||
};
|
||||
activeProcessTerminators.set(child.pid, stopChildTree);
|
||||
const resultExitGuard = createResultExitGuard({
|
||||
@@ -508,7 +352,7 @@ async function runProcess(
|
||||
}, timeoutMs);
|
||||
timer?.unref();
|
||||
let spawnError: string | null = null;
|
||||
const exitCode = await new Promise<number>((resolve, reject) => {
|
||||
const childExit = new Promise<number>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("exit", (code) => {
|
||||
childSettled = true;
|
||||
@@ -519,13 +363,21 @@ async function runProcess(
|
||||
spawnError = error instanceof Error ? error.message : String(error);
|
||||
return 1;
|
||||
});
|
||||
const exitCode = await Promise.race([childExit, cleanupFinished]);
|
||||
if (timer) clearTimeout(timer);
|
||||
if (completionPoll) clearInterval(completionPoll);
|
||||
const processCleanupError = child.pid
|
||||
? await (boundedCleanup ??
|
||||
activeProcessCleanup.get(child.pid) ??
|
||||
terminateProcessGroup(child.pid))
|
||||
: null;
|
||||
// Even a successful launcher exit can leave an already-observed detached
|
||||
// server behind. Retire that retained tree, never only the root group.
|
||||
stopChildTree();
|
||||
const processCleanupError = await boundedCleanup!;
|
||||
processOwner.stopObserving();
|
||||
// Even a failed direct-child kill must not hold cancellation forever or let
|
||||
// inherited pipes write into an ended log. The cleanup error remains fatal.
|
||||
if (processCleanupError) {
|
||||
child.stdout?.destroy();
|
||||
child.stderr?.destroy();
|
||||
if (child.exitCode === null && child.signalCode === null) child.unref();
|
||||
}
|
||||
if (child.pid) {
|
||||
activeProcessGroups.delete(child.pid);
|
||||
activeProcessCleanup.delete(child.pid);
|
||||
@@ -631,6 +483,7 @@ async function runAttempt(input: {
|
||||
const publishedResults: RunnerE2EResult[] = [];
|
||||
const publishedResultPaths = new Map<string, string>();
|
||||
let attemptSecrets: string[] = [];
|
||||
let processCleanupFailed = false;
|
||||
try {
|
||||
const paperclipHome = path.join(temporaryRoot, "paperclip-home");
|
||||
const workspace = path.join(temporaryRoot, "workspace");
|
||||
@@ -742,6 +595,7 @@ async function runAttempt(input: {
|
||||
),
|
||||
options.ui || options.debug,
|
||||
);
|
||||
processCleanupFailed = processResult.processCleanupError !== null;
|
||||
const processFailure = processResult.spawnError
|
||||
? `Playwright failed to start: ${processResult.spawnError}`
|
||||
: processResult.timedOut
|
||||
@@ -943,9 +797,11 @@ async function runAttempt(input: {
|
||||
}
|
||||
return [...publishedResults];
|
||||
} finally {
|
||||
reapNewDetachedDarwinSharedMemory(sharedMemoryBaseline);
|
||||
if (!processCleanupFailed) reapNewDetachedDarwinSharedMemory(sharedMemoryBaseline);
|
||||
let cleanupError: unknown;
|
||||
if (
|
||||
if (processCleanupFailed) {
|
||||
cleanupError = new Error(`Preserving temporary state after incomplete process cleanup: ${temporaryRoot}`);
|
||||
} else if (
|
||||
temporaryRoot.startsWith(`${os.tmpdir()}${path.sep}paperclip-runner-e2e-`)
|
||||
) {
|
||||
for (let cleanupAttempt = 1; cleanupAttempt <= 3; cleanupAttempt += 1) {
|
||||
@@ -1100,6 +956,7 @@ async function main() {
|
||||
}
|
||||
|
||||
await loadLocalEnvironment(process.env);
|
||||
assertRemoteNativeEvidencePrerequisites(executions, process.env);
|
||||
const missingCredentials = [
|
||||
...new Set(
|
||||
executions.flatMap((execution) => execution.requiredCredentials),
|
||||
|
||||
@@ -311,7 +311,7 @@ export async function setupLiveFixtures(input: {
|
||||
},
|
||||
});
|
||||
|
||||
if (execution.environment.configurationKey === "warm-reuse-v1"
|
||||
if (execution.task.flow === "warm_three_turn"
|
||||
|| (execution.suite.id === "extended-harnesses" && execution.task.id === "file-edit-validate")) {
|
||||
registry.register<ProjectRecord>({
|
||||
id: "project",
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { canonicalJson } from "../../packages/shared/src/portability-hash.js";
|
||||
import { hasAcpxNativeOrigin } from "./acpx-native-origin.js";
|
||||
import { isValidNativePrpEnvelope } from "./native-event-envelope.js";
|
||||
import { assertNativeRemoteRetirement, nativeRemoteDeniedSample, type NativeRemoteSnapshot } from "./native-remote-evidence.js";
|
||||
import { readCursorToolEvidence } from "./cursor-native-evidence.js";
|
||||
import { bootstrapReadExecutionId, withoutProvenBootstrapReads, type BootstrapReadProof } from "./native-bootstrap-read-proof.js";
|
||||
|
||||
type Row = Record<string, any>;
|
||||
export interface ActiveStopCaller { type: "board"; userId: "local-board"; source: "local_implicit" }
|
||||
export type ActiveStopProvider = "cursor";
|
||||
export interface ActiveStopScope { provider: ActiveStopProvider; companyId: string; issueId: string; runId: string; target: string; commandSha256?: string }
|
||||
export interface ActiveStopPending {
|
||||
schema: "paperclip.e2e.native-active-stop-pending.v2";
|
||||
caller: ActiveStopCaller; scope: ActiveStopScope; requestId: string; toolCallId: string; nativeSessionId: string; turnId: string;
|
||||
normalizedSessionId: string; sourceInstanceId: string; requestSourceSeq: number; permissionSourceSeq: number;
|
||||
requestRowSha256: string; permissionRowSha256: string; cancellationRequestId: string; observedMonotonicNs: string;
|
||||
toolOriginSourceSeq: number; toolStartedSourceSeq: number; toolOriginRowSha256: string; toolStartedRowSha256: string;
|
||||
}
|
||||
const rec = (v: unknown): Row => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Row : {};
|
||||
const id = (v: unknown): v is string => typeof v === "string" && v.length > 0 && v.length <= 240 && !/[\u0000-\u001f\u007f]/u.test(v) && !v.includes("[REDACTED]");
|
||||
const uuid = (v: unknown): v is string => typeof v === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u.test(v);
|
||||
const hash = (v: unknown) => `sha256:${createHash("sha256").update(canonicalJson(v)).digest("hex")}`;
|
||||
function fail(condition: unknown, reason: string): asserts condition { if (!condition) throw new Error(`Native active Stop: ${reason}`); }
|
||||
/** The isolated Product server uses local-trusted board authentication. Bind
|
||||
* the same public session observed by the API client, never infer a null actor. */
|
||||
export function readActiveStopCaller(health: unknown, authentication: unknown): ActiveStopCaller {
|
||||
const session = rec(rec(authentication).session);
|
||||
fail(rec(health).deploymentMode === "local_trusted" && session.userId === "local-board"
|
||||
&& session.id === "paperclip:local_implicit:local-board", "expected isolated board caller missing");
|
||||
return { type: "board", userId: "local-board", source: "local_implicit" };
|
||||
}
|
||||
function isActiveStopCaller(caller: unknown): caller is ActiveStopCaller {
|
||||
const value = rec(caller);
|
||||
return value.type === "board" && value.userId === "local-board" && value.source === "local_implicit";
|
||||
}
|
||||
function canonicalRows(events: readonly unknown[], scope: ActiveStopScope) {
|
||||
fail(events.length <= 20_000 && events.length > 0, "bounded durable evidence required");
|
||||
const rows = events.map(rec).filter(row => rec(row.payload).prpEvent !== undefined);
|
||||
const seen = new Set<number>(), source = new Set<string>();
|
||||
for (const row of rows) {
|
||||
const e = rec(rec(row.payload).prpEvent);
|
||||
fail(row.companyId === scope.companyId && row.runId === scope.runId && isValidNativePrpEnvelope(e, row.protocolSchemaVersion)
|
||||
&& e.sourceKind === "runner" && e.runId === scope.runId
|
||||
&& e.eventType === row.eventType && Number.isSafeInteger(row.seq) && row.seq > 0 && !seen.has(row.seq)
|
||||
&& id(e.sourceInstanceId) && Number.isSafeInteger(e.sourceSeq) && e.sourceSeq > 0
|
||||
&& e.sourceEventId === `${e.sourceInstanceId}:${e.runId}:${e.sourceSeq}` && !source.has(e.sourceEventId), "invalid/duplicate/foreign canonical row");
|
||||
seen.add(row.seq); source.add(e.sourceEventId);
|
||||
}
|
||||
const ordered = [...rows].sort((a, b) => a.seq - b.seq);
|
||||
const lastBySource = new Map<string, number>();
|
||||
for (const row of ordered) {
|
||||
const e = rec(rec(row.payload).prpEvent), previous = lastBySource.get(e.sourceInstanceId) ?? 0;
|
||||
fail(e.sourceSeq > previous, "durable source sequence reordered");
|
||||
lastBySource.set(e.sourceInstanceId, e.sourceSeq);
|
||||
}
|
||||
return ordered.map(row => ({ row, event: rec(rec(row.payload).prpEvent) }));
|
||||
}
|
||||
const terminals = new Set(["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]);
|
||||
const closures = new Set(["runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired"]);
|
||||
function origin(events: readonly unknown[], scope: ActiveStopScope, bootstrap?: BootstrapReadProof) {
|
||||
fail([scope.companyId, scope.issueId, scope.runId, scope.target].every(id) && ["cursor", "copilot"].includes(scope.provider), "exact scope required");
|
||||
const rows = canonicalRows(events, scope);
|
||||
const notices = readCursorToolEvidence(events, scope.runId);
|
||||
const requests = notices.filter(n => n.stage === "permission_requested");
|
||||
fail(requests.length === 1, "one native permission required");
|
||||
const notice = requests[0]!;
|
||||
fail(id(notice.requestId) && notice.declineOffered === true && (scope.provider === "cursor"
|
||||
? notice.operation === "execute" && /^sha256:[a-f0-9]{64}$/u.test(scope.commandSha256 ?? "") && notice.commandSha256 === scope.commandSha256
|
||||
: notice.operation === "edit" && "target" in notice && notice.target === scope.target), "exact native operation required");
|
||||
const permission = rows.find(x => x.row.seq === notice.seq);
|
||||
const created = rows.filter(x => x.event.eventType === "runtime_request.created");
|
||||
fail(permission && created.length === 1, "one durable native card required");
|
||||
const request = rec(rec(created[0]!.event.payload).request), p = permission.event;
|
||||
fail(request.schema === "paperclip.runtime_request.v2" && request.type === "permission" && request.requestKind === "permission_approval"
|
||||
&& request.status === "pending" && request.requestId === notice.requestId && request.turnId === notice.turnId
|
||||
&& rec(request.details).toolCallId === notice.toolCallId && hasAcpxNativeOrigin(request.origin, scope.provider, "session/request_permission")
|
||||
&& id(p.normalizedSessionId) && p.turnId === notice.turnId && created[0]!.event.turnId === notice.turnId
|
||||
&& created[0]!.event.normalizedSessionId === p.normalizedSessionId && created[0]!.event.sourceInstanceId === p.sourceInstanceId,
|
||||
"native notice/card identity mismatch");
|
||||
const stream = (event: Row) => event.turnId === notice.turnId && event.normalizedSessionId === p.normalizedSessionId && event.sourceInstanceId === p.sourceInstanceId;
|
||||
fail(rows.filter(x => x.event.turnId != null).every(x => stream(x.event)), "foreign turn/session/source");
|
||||
const tool = notices.find(n => n.stage === "tool" && n.toolCallId === notice.toolCallId);
|
||||
fail(tool, "native operation origin missing");
|
||||
const selected = withoutProvenBootstrapReads(notices, tool, bootstrap);
|
||||
fail(selected.every(n => n.runId === notice.runId && n.sessionId === notice.sessionId && n.turnId === notice.turnId
|
||||
&& n.toolCallId === notice.toolCallId && (n.requestId === undefined || n.requestId === notice.requestId)
|
||||
&& (n.operation === undefined || n.operation === notice.operation)
|
||||
&& (!("target" in n) || n.target === undefined || n.target === scope.target)
|
||||
&& (n.commandSha256 === undefined || n.commandSha256 === scope.commandSha256)
|
||||
&& n.status !== "completed" && (n.stage !== "permission_delivered" || n.outcome === "cancel")), "extra/replayed/answered native operation");
|
||||
const tools = selected.filter(n => n.stage === "tool");
|
||||
fail(tools.filter(n => n.status === "pending").length === 1
|
||||
&& tools.filter(n => n.status === "failed").length <= 1
|
||||
&& tools[0]!.status === "pending"
|
||||
// Cursor queues permission evidence until its exact command origin exists.
|
||||
// Copilot projects the request immediately, including permission-first ACP.
|
||||
&& (scope.provider !== "cursor" || tools[0]!.seq < notice.seq)
|
||||
&& selected.filter(n => n.stage === "permission_delivered").length <= 1, "duplicate native operation lifecycle");
|
||||
const executions = rows.filter(x => x.event.eventType.startsWith("tool.execution.") && rec(x.event.payload).executionId === bootstrapReadExecutionId(notice.toolCallId));
|
||||
fail(executions.filter(x => x.event.eventType === "tool.execution.started").length === 1
|
||||
&& executions.filter(x => x.event.eventType === "tool.execution.completed").length <= 1
|
||||
&& executions.every(x => rec(x.event.payload).schema === "paperclip.tool.execution.v1" && rec(x.event.payload).transport === "builtin"
|
||||
&& ["tool.execution.started", "tool.execution.progressed", "tool.execution.completed"].includes(x.event.eventType)
|
||||
&& rec(x.event.payload).status === (x.event.eventType === "tool.execution.completed" ? "failed" : "running")), "duplicate canonical operation lifecycle");
|
||||
// ACP permits a permission request before its tool notification. Require
|
||||
// both in the pre-Stop observation, without imposing a card/start order.
|
||||
const toolOrigin = rows.find(x => x.row.seq === tools[0]!.seq);
|
||||
const toolStarted = executions.find(x => x.event.eventType === "tool.execution.started");
|
||||
fail(toolOrigin && toolStarted, "native operation origin missing");
|
||||
const allowed = new Set(notices.filter(n => n.stage === "tool").map(n => bootstrapReadExecutionId(n.toolCallId)));
|
||||
fail(rows.filter(x => x.event.eventType.startsWith("tool.execution.")).every(x => allowed.has(rec(x.event.payload).executionId)), "unattributed operation");
|
||||
fail(rows.filter(x => x.event.eventType === "tool.execution.completed" && rec(x.event.payload).executionId === bootstrapReadExecutionId(notice.toolCallId))
|
||||
.every(x => rec(x.event.payload).status !== "completed"), "target operation completed");
|
||||
return { rows, notice, permission, created: created[0]!, toolOrigin, toolStarted, request, stream };
|
||||
}
|
||||
export function observeActiveStopPending(input: { events: readonly unknown[]; run: Row; issue: Row; scope: ActiveStopScope; caller: ActiveStopCaller; cancellationRequestId: string; bootstrap?: BootstrapReadProof }): ActiveStopPending {
|
||||
const { run, issue, scope } = input, proof = origin(input.events, scope, input.bootstrap);
|
||||
fail(isActiveStopCaller(input.caller) && uuid(input.cancellationRequestId) && run.id === scope.runId && run.companyId === scope.companyId && run.nativeIssueId === scope.issueId
|
||||
&& run.status === "running" && run.runtimeMode === "native" && issue.id === scope.issueId && issue.companyId === scope.companyId && issue.status === "in_progress"
|
||||
&& run.resultJson?.startupCancellation == null && run.resultJson?.nativeCancellation == null, "run is not fresh active work");
|
||||
fail(!(readCursorToolEvidence(input.events, scope.runId)).some(n => n.stage === "permission_delivered"), "permission already answered");
|
||||
fail(!proof.rows.some(x => terminals.has(x.event.eventType) || closures.has(x.event.eventType)), "request or provider already settled");
|
||||
fail(!proof.rows.some(x => x.event.eventType === "tool.execution.completed" && rec(x.event.payload).executionId === bootstrapReadExecutionId(proof.notice.toolCallId)), "operation already ended");
|
||||
return { schema: "paperclip.e2e.native-active-stop-pending.v2", scope, caller: input.caller, requestId: proof.notice.requestId!, toolCallId: proof.notice.toolCallId,
|
||||
nativeSessionId: proof.notice.sessionId, turnId: proof.notice.turnId, normalizedSessionId: proof.permission.event.normalizedSessionId,
|
||||
sourceInstanceId: proof.permission.event.sourceInstanceId, requestSourceSeq: proof.created.event.sourceSeq, permissionSourceSeq: proof.permission.event.sourceSeq,
|
||||
requestRowSha256: hash(proof.created.row), permissionRowSha256: hash(proof.permission.row), cancellationRequestId: input.cancellationRequestId,
|
||||
toolOriginSourceSeq: proof.toolOrigin.event.sourceSeq, toolStartedSourceSeq: proof.toolStarted.event.sourceSeq,
|
||||
toolOriginRowSha256: hash(proof.toolOrigin.row), toolStartedRowSha256: hash(proof.toolStarted.row),
|
||||
observedMonotonicNs: process.hrtime.bigint().toString() };
|
||||
}
|
||||
export function readActiveStopSettlement(input: { events: readonly unknown[]; run: Row; issue: Row; pending: ActiveStopPending; dispatchMonotonicNs: string; bootstrap?: BootstrapReadProof }) {
|
||||
const before = input.pending, { run, issue } = input;
|
||||
fail(before?.schema === "paperclip.e2e.native-active-stop-pending.v2" && isActiveStopCaller(before.caller) && uuid(before.cancellationRequestId)
|
||||
&& /^[1-9][0-9]{0,29}$/u.test(before.observedMonotonicNs) && /^[1-9][0-9]{0,29}$/u.test(input.dispatchMonotonicNs)
|
||||
&& BigInt(before.observedMonotonicNs) < BigInt(input.dispatchMonotonicNs), "pre-dispatch pending observation missing");
|
||||
const proof = origin(input.events, before.scope, input.bootstrap);
|
||||
fail(hash(proof.created.row) === before.requestRowSha256 && hash(proof.permission.row) === before.permissionRowSha256
|
||||
&& hash(proof.toolOrigin.row) === before.toolOriginRowSha256 && hash(proof.toolStarted.row) === before.toolStartedRowSha256
|
||||
&& proof.toolOrigin.event.sourceSeq === before.toolOriginSourceSeq && proof.toolStarted.event.sourceSeq === before.toolStartedSourceSeq
|
||||
&& proof.notice.sessionId === before.nativeSessionId && proof.notice.turnId === before.turnId && proof.notice.toolCallId === before.toolCallId
|
||||
&& proof.notice.requestId === before.requestId && proof.permission.event.normalizedSessionId === before.normalizedSessionId
|
||||
&& proof.permission.event.sourceInstanceId === before.sourceInstanceId && proof.created.event.sourceSeq === before.requestSourceSeq
|
||||
&& proof.permission.event.sourceSeq === before.permissionSourceSeq, "observed pending request changed");
|
||||
const closed = proof.rows.filter(x => closures.has(x.event.eventType)), terminal = proof.rows.filter(x => terminals.has(x.event.eventType));
|
||||
fail(closed.length === 1 && terminal.length === 1, "one closed request and one terminal required");
|
||||
const c = closed[0]!, t = terminal[0]!, cp = rec(c.event.payload), tp = rec(t.event.payload);
|
||||
// Product persists the harness projection, not the raw runnerd backend
|
||||
// payload. The terminal mapper closes pending permissions with turn_terminal
|
||||
// and emits {status,error}. Bind that exact boundary to the retained native
|
||||
// request and caller-owned Stop below; a generic terminal is insufficient.
|
||||
fail(proof.stream(c.event) && proof.stream(t.event) && c.event.eventType === "runtime_request.cancelled" && cp.requestId === before.requestId && cp.turnId === before.turnId
|
||||
&& cp.requestKind === "permission_approval" && cp.reason === "turn_terminal"
|
||||
&& cp.itemId === proof.request.itemId && cp.action === undefined && cp.response === undefined && cp.replayAllowed !== true
|
||||
&& t.event.eventType === "turn.cancelled" && tp.status === "cancelled" && tp.error === null
|
||||
&& c.event.sourceSeq > Math.max(before.requestSourceSeq, before.permissionSourceSeq, before.toolOriginSourceSeq, before.toolStartedSourceSeq)
|
||||
&& t.event.sourceSeq > c.event.sourceSeq,
|
||||
"pending callback did not close through cancellation");
|
||||
fail(proof.rows.filter(x => x.event.eventType.startsWith("tool.execution.")
|
||||
|| (x.event.eventType === "provider.notice.recorded" && ["cursor_tool_evidence_v1", "copilot_tool_evidence_v1"].includes(rec(x.event.payload).category)))
|
||||
.every(x => x.event.sourceSeq < t.event.sourceSeq), "native operation after provider cancellation");
|
||||
const stop = rec(rec(run.resultJson).nativeCancellation), startup = rec(rec(run.resultJson).startupCancellation);
|
||||
fail(run.id === before.scope.runId && run.companyId === before.scope.companyId && run.nativeIssueId === before.scope.issueId && run.runtimeMode === "native" && run.status === "cancelled"
|
||||
&& issue.id === before.scope.issueId && issue.companyId === before.scope.companyId && issue.status === "in_progress"
|
||||
&& rec(startup.requestedBy).type === before.caller.type && rec(startup.requestedBy).userId === before.caller.userId
|
||||
&& startup.cancellationRequestId === before.cancellationRequestId && stop.intentId === `native-cancellation:${before.cancellationRequestId}`
|
||||
&& stop.schema === "paperclip.native-cancellation.v1" && stop.companyId === before.scope.companyId && stop.runId === run.id && stop.issueId === issue.id
|
||||
&& stop.scope === "run" && stop.dispatched === true && stop.dispatchState === "acknowledged" && stop.reasonCode === "cancellation_run_only"
|
||||
&& Array.isArray(stop.effects) && stop.effects.length === 1 && stop.effects[0] === "release_run_resources"
|
||||
&& id(stop.intentAuditId) && id(stop.acknowledgementAuditId) && stop.intentAuditId !== stop.acknowledgementAuditId,
|
||||
"same-scope caller Stop acknowledgement missing");
|
||||
return { schema: "paperclip.e2e.native-active-stop-settlement.v2", pending: before, dispatchMonotonicNs: input.dispatchMonotonicNs,
|
||||
branch: "pending_permission_cancelled" as const, closedRequestSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq,
|
||||
closedRequestRowSha256: hash(c.row), terminalRowSha256: hash(t.row), intentId: stop.intentId as string,
|
||||
intentAuditId: stop.intentAuditId as string, acknowledgementAuditId: stop.acknowledgementAuditId as string,
|
||||
taskStillInProgress: true, normalCompletionAccepted: false, replayAllowed: false };
|
||||
}
|
||||
|
||||
export interface ActiveStopRemoteObservation {
|
||||
phase: "before-request" | "pending" | "owned-process-retirement";
|
||||
source: "live-snapshot" | "retirement-seal";
|
||||
snapshot: NativeRemoteSnapshot;
|
||||
}
|
||||
|
||||
/** A per-turn Daytona observer seals itself when the owned tree retires. The
|
||||
* host may retrieve that receipt later; retrieval is not a fresh observation. */
|
||||
export function readActiveStopRemoteRetirement(input: {
|
||||
scope: Pick<ActiveStopScope, "companyId" | "runId" | "target">; observations: readonly ActiveStopRemoteObservation[];
|
||||
}) {
|
||||
const observations = input.observations;
|
||||
fail(observations.length === 3
|
||||
&& observations.map(o => `${o.phase}:${o.source}`).join(",") === "before-request:live-snapshot,pending:live-snapshot,owned-process-retirement:retirement-seal",
|
||||
"remote seal cannot stand in for a fresh causal sample");
|
||||
const [baseline, pending, terminal] = observations.map(o => o.snapshot) as [NativeRemoteSnapshot, NativeRemoteSnapshot, NativeRemoteSnapshot];
|
||||
fail(baseline.binding.companyId === input.scope.companyId && baseline.binding.runId === input.scope.runId, "remote observation belongs to another run");
|
||||
for (const snapshot of [baseline, pending, terminal]) {
|
||||
fail(!nativeRemoteDeniedSample(snapshot, baseline, input.scope.target, "pending").exists, "remote target changed");
|
||||
}
|
||||
fail(BigInt(baseline.observedMonotonicNs) < BigInt(pending.observedMonotonicNs)
|
||||
&& BigInt(pending.observedMonotonicNs) < BigInt(terminal.observedMonotonicNs), "remote observation reused or out of order");
|
||||
fail(!baseline.setup.published && pending.setup.published && pending.setup.sha256 === terminal.setup.sha256
|
||||
&& baseline.processes.captured && pending.processes.captured
|
||||
&& baseline.processes.live.includes(baseline.processes.root?.pid ?? -1)
|
||||
&& pending.processes.live.includes(pending.processes.root?.pid ?? -1), "remote pending lifetime unproven");
|
||||
assertNativeRemoteRetirement(terminal, baseline);
|
||||
assertNativeRemoteRetirement(terminal, pending);
|
||||
for (const snapshot of [baseline, pending]) {
|
||||
fail(snapshot.processes.journal.every(p => terminal.processes.journal.some(q =>
|
||||
p.pid === q.pid && p.startTicks === q.startTicks && p.bootId === q.bootId)), "remote descendant journal lost");
|
||||
}
|
||||
return { schema: "paperclip.e2e.native-active-stop-remote-retirement.v1" as const,
|
||||
coverage: "continuous-through-owned-process-retirement" as const, filesystemAfterRetirementObserved: false as const,
|
||||
binding: terminal.binding, target: input.scope.target,
|
||||
observations: observations.map(o => ({ phase: o.phase, source: o.source,
|
||||
observedMonotonicNs: o.snapshot.observedMonotonicNs, snapshotSha256: hash(o.snapshot) })) };
|
||||
}
|
||||
|
||||
/** Local files remain accessible through teardown. Remote per-turn files do
|
||||
* not: require the complete lifetime seal, never relabel it as a later sample. */
|
||||
export function assertActiveStopRetirement(input: {
|
||||
completed: boolean; identityChanged: boolean;
|
||||
processes: { captured: boolean; live: readonly number[] };
|
||||
watcher: { complete: boolean; targetMutationCount: number };
|
||||
} & ({ environment: "local"; samples: ReadonlyArray<{ phase: string; absent: boolean }> }
|
||||
| { environment: "daytona"; remote: Parameters<typeof readActiveStopRemoteRetirement>[0] })) {
|
||||
fail(input.completed && !input.identityChanged && input.processes.captured
|
||||
&& input.processes.live.length === 0 && input.watcher.complete && input.watcher.targetMutationCount === 0,
|
||||
"retirement or continuous no-effect proof is incomplete");
|
||||
if (input.environment === "daytona") return readActiveStopRemoteRetirement(input.remote);
|
||||
fail(input.environment === "local" && input.samples.length === 4 && input.samples.every(s => s.absent === true)
|
||||
&& input.samples.map(s => s.phase).join(",") === "before-request,pending,after-stop,after-cleanup",
|
||||
"causal target observation missing or changed");
|
||||
return { coverage: "local-through-cleanup" as const };
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { pollUntil, type RunnerApi } from "./api.js";
|
||||
import { collectRunEvents } from "./run-observations.js";
|
||||
import { createTaskThroughUi } from "./user-actions.js";
|
||||
import { createDeniedTargetFixture, exists, observeRunProcesses } from "./native-local-fixtures.js";
|
||||
import { assertNativeRemoteRetirement, nativeRemoteDeniedSample, prepareNativeRemoteAction, type NativeRemoteBootstrap, type NativeRemoteFixture, type NativeRemoteSnapshot } from "./native-remote-evidence.js";
|
||||
import { cursorDeniedCommand } from "./cursor-native-evidence.js";
|
||||
import { assertActiveStopRetirement, readActiveStopCaller, observeActiveStopPending, readActiveStopSettlement, type ActiveStopRemoteObservation, type ActiveStopCaller, type ActiveStopPending, type ActiveStopScope } from "./native-active-stop-evidence.js";
|
||||
import type { BootstrapReadProof } from "./native-bootstrap-read-proof.js";
|
||||
import type { LiveFixtureValues } from "./live-fixtures.js";
|
||||
import type { MatrixExecution } from "./types.js";
|
||||
type Row = Record<string, any>;
|
||||
type Check = { id: string; passed: boolean; detail: string };
|
||||
export interface ActiveStopState { run: Row; issue: Row; events: readonly unknown[] }
|
||||
/** Retain a real pending API observation before the only mutating request.
|
||||
* Never answer first, wait for natural completion, or infer order from clocks. */
|
||||
export async function stopAtPendingPermission(input: {
|
||||
scope: ActiveStopScope; caller: ActiveStopCaller; bootstrap?: BootstrapReadProof; deadlineAt: number;
|
||||
load(): Promise<ActiveStopState>;
|
||||
retain(receipt: ActiveStopPending): Promise<void>;
|
||||
stop(runId: string, cancellationRequestId: string): Promise<Row>;
|
||||
}) {
|
||||
const cancellationRequestId = randomUUID();
|
||||
const state = await input.load();
|
||||
const pending = observeActiveStopPending({ ...state, scope: input.scope, caller: input.caller, cancellationRequestId, bootstrap: input.bootstrap });
|
||||
await input.retain(pending);
|
||||
const fresh = observeActiveStopPending({ ...await input.load(), scope: input.scope, caller: input.caller, cancellationRequestId, bootstrap: input.bootstrap });
|
||||
if (fresh.requestRowSha256 !== pending.requestRowSha256 || fresh.permissionRowSha256 !== pending.permissionRowSha256
|
||||
|| fresh.toolOriginRowSha256 !== pending.toolOriginRowSha256 || fresh.toolStartedRowSha256 !== pending.toolStartedRowSha256
|
||||
|| Date.now() >= input.deadlineAt) throw new Error("Native active Stop pending boundary changed or expired");
|
||||
const dispatchMonotonicNs = process.hrtime.bigint().toString();
|
||||
const stopped = await input.stop(input.scope.runId, cancellationRequestId);
|
||||
if (stopped.id !== input.scope.runId || stopped.resultJson?.nativeCancellation?.intentId !== `native-cancellation:${cancellationRequestId}`) throw new Error("Native active Stop response has a foreign intent");
|
||||
const label = "cancelled unanswered native permission";
|
||||
const final = await pollUntil({ label, deadlineAt: input.deadlineAt, intervalMs: 200, load: async () => {
|
||||
const value = await input.load();
|
||||
if (["succeeded", "failed", "timed_out"].includes(value.run.status)) throw new Error(`Stopped waiting for ${label}: unexpected run terminal`);
|
||||
return value;
|
||||
}, accept: value => { readActiveStopSettlement({ ...value, pending, dispatchMonotonicNs, bootstrap: input.bootstrap }); return true; } });
|
||||
return { pending, dispatchMonotonicNs, settlement: readActiveStopSettlement({ ...final, pending, dispatchMonotonicNs, bootstrap: input.bootstrap }) };
|
||||
}
|
||||
export async function runNativeActiveStopFlow(input: {
|
||||
page: Page; api: RunnerApi; fixtures: LiveFixtureValues; execution: MatrixExecution; nonce: string; workspacePath: string; deadlineAt: number;
|
||||
remoteBootstrap?: NativeRemoteBootstrap;
|
||||
registerCleanupAssertion(callback: () => Promise<Check[]>): void;
|
||||
registerBeforeEnvironmentTeardownAssertion(callback: () => Promise<Check[]>): void;
|
||||
observe(issue: Row, runs: Row[]): void;
|
||||
capture(id: string, label: string, file: string): Promise<void>;
|
||||
evidence(name: string, value: unknown): Promise<void>;
|
||||
}) {
|
||||
const { api, page, fixtures, execution, nonce } = input, provider = execution.profile.qualificationCandidate;
|
||||
if (provider !== "cursor" || execution.task.id !== "pending-permission-stop") throw new Error("Unknown native active Stop case");
|
||||
const remote = execution.environment.id === "daytona";
|
||||
if ((!remote && execution.environment.id !== "local") || (remote && !input.remoteBootstrap)) throw new Error("Active Stop requires an isolated admitted environment");
|
||||
const checks: Check[] = []; let issue: Row = {}, runs: Row[] = [], events: Row[] = [];
|
||||
const check = (id: string, passed: boolean, detail: string) => { checks.push({ id, passed, detail }); expect(passed, detail).toBe(true); };
|
||||
const name = `active-stop-${nonce}.txt`, local = remote ? undefined : await createDeniedTargetFixture(input.workspacePath, name);
|
||||
const target = local?.targetRelativePath ?? name;
|
||||
let command = provider === "cursor" && local ? cursorDeniedCommand(local.targetPath) : undefined;
|
||||
const observer = remote ? undefined : observeRunProcesses();
|
||||
let processes: { captured: boolean; live: number[] } = { captured: false, live: [] };
|
||||
let processIdentity: string | undefined, processError = false;
|
||||
const remoteObservations: ActiveStopRemoteObservation[] = [];
|
||||
let retirement: ReturnType<typeof assertActiveStopRetirement> | undefined;
|
||||
const samples: Array<{ phase: string; absent: boolean }> = [];
|
||||
let fixture: NativeRemoteFixture | undefined, baseline: NativeRemoteSnapshot | undefined, sealed: NativeRemoteSnapshot | undefined;
|
||||
let completed: Awaited<ReturnType<typeof stopAtPendingPermission>> | undefined;
|
||||
const observeProcesses = () => {
|
||||
const run = runs[0], authority = run?.processPid ? { pid: run.processPid, groupId: run.processGroupId, startedAt: run.processStartedAt, runId: run.id } : undefined;
|
||||
if (authority) { const key = JSON.stringify(authority); if (processIdentity && processIdentity !== key) processError = true; processIdentity ??= key; }
|
||||
if (observer) processes = observer.sample(authority);
|
||||
};
|
||||
const load = async (): Promise<ActiveStopState> => {
|
||||
if (issue.id) issue = await api.get<Row>(`/api/issues/${issue.id}`);
|
||||
const list = await api.get<Row[]>(`/api/companies/${fixtures.company.id}/heartbeat-runs?limit=100`);
|
||||
runs = await Promise.all(list.map(r => api.get<Row>(`/api/heartbeat-runs/${r.id}`)));
|
||||
if (runs.length > 1) throw new Error("Native active Stop dispatched an extra run");
|
||||
events = runs[0] ? await collectRunEvents<Row>((afterSeq, limit) => api.get(`/api/heartbeat-runs/${runs[0]!.id}/events?afterSeq=${afterSeq}&limit=${limit}`)) : [];
|
||||
observeProcesses(); input.observe(issue, runs); return { run: runs[0] ?? {}, issue, events };
|
||||
};
|
||||
const sample = async (phase: string) => {
|
||||
let value: boolean;
|
||||
if (remote) {
|
||||
if (!fixture || !baseline) throw new Error("Missing remote active Stop observer");
|
||||
if (phase !== "pending") throw new Error("Remote filesystem phase requires a fresh live snapshot");
|
||||
const snap = await fixture.snapshot(phase);
|
||||
remoteObservations.push({ phase, source: "live-snapshot", snapshot: snap });
|
||||
value = !nativeRemoteDeniedSample(snap, baseline, target, "pending").exists;
|
||||
await input.evidence(`active-stop-${phase}-remote.json`, snap);
|
||||
} else value = !await exists(local!.targetPath);
|
||||
samples.push({ phase, absent: value }); check(`no-effect-${phase}`, value, "Exact target remains absent at the causal observation boundary");
|
||||
};
|
||||
const scope = (): ActiveStopScope => ({ provider, companyId: fixtures.company.id, issueId: issue.id, runId: runs[0]!.id, target, ...(command ? { commandSha256: command.commandSha256 } : {}) });
|
||||
const bootstrap = (): BootstrapReadProof | undefined => fixture ? { actionFile: fixture.actionFile, events } : undefined;
|
||||
const cleanup = async () => {
|
||||
const receipt: Check[] = [];
|
||||
try {
|
||||
await load();
|
||||
if (remote) {
|
||||
if (!fixture || !baseline) throw new Error("Remote observer was never armed");
|
||||
sealed ??= await fixture.finish(); assertNativeRemoteRetirement(sealed, baseline); processes = sealed.processes;
|
||||
} else if (processes.captured && processes.live.length) {
|
||||
await pollUntil({ label: "active Stop provider retirement", deadlineAt: Date.now() + 5000, intervalMs: 100, load: async () => { observeProcesses(); return processes; }, accept: p => p.live.length === 0 });
|
||||
}
|
||||
if (!remote) await sample("after-cleanup");
|
||||
const watch = remote ? sealed!.watcher : local!.watcher.finish();
|
||||
retirement = assertActiveStopRetirement({ completed: Boolean(completed), identityChanged: processError, processes, watcher: watch,
|
||||
...(remote ? { environment: "daytona" as const, remote: { scope: scope(), observations: remoteObservations } } : { environment: "local" as const, samples }) });
|
||||
if (!completed) throw new Error("Missing active Stop settlement");
|
||||
readActiveStopSettlement({ ...await load(), ...completed, bootstrap: bootstrap() });
|
||||
receipt.push({ id: "active-stop-retired-no-effects", passed: true, detail: remote ? "Exact run root/descendants retired with continuous no-effects proof through retirement; later UI/API checks do not claim fresh filesystem observation" : "Exact run root/descendants retired; unanswered target remained absent through cleanup" });
|
||||
return receipt;
|
||||
} finally {
|
||||
if (timer) clearInterval(timer);
|
||||
try {
|
||||
await input.evidence("native-active-stop-cleanup.json", { processes, processError, samples, remoteObservations, retirement, sealed, watcher: local?.watcher.finish(), checks: receipt });
|
||||
} finally {
|
||||
if (remote) await fixture?.close();
|
||||
}
|
||||
}
|
||||
};
|
||||
const timer = observer ? setInterval(() => { try { observeProcesses(); } catch { processError = true; } }, 100) : undefined;
|
||||
(remote ? input.registerBeforeEnvironmentTeardownAssertion : input.registerCleanupAssertion)(cleanup);
|
||||
const prompt = () => provider === "cursor"
|
||||
? `${execution.task.buildPrompt(nonce)}\nUse this exact native shell command once:\n${command!.command}`
|
||||
: `${execution.task.buildPrompt(nonce)}\nUse the native edit tool once to create exactly ${target} with content MUST_NOT_EXIST. Do not use a shell command.`;
|
||||
try {
|
||||
const caller = readActiveStopCaller(await api.get("/api/health"), await api.get("/api/auth/get-session"));
|
||||
const agent = await api.get<Row>(`/api/agents/${fixtures.agent.id}`);
|
||||
const configured = await api.patch<Row>(`/api/agents/${fixtures.agent.id}`, { adapterConfig: { ...agent.adapterConfig, acpxPermissionMode: "approve-reads", ...(provider === "cursor" ? { acpxSessionMode: "agent" } : {}), timeoutSec: 120, lifecycleMode: "per_turn" } });
|
||||
check("explicit-per-turn-policy", configured.adapterConfig?.acpxPermissionMode === "approve-reads" && configured.adapterConfig?.lifecycleMode === "per_turn" && (provider !== "cursor" || configured.adapterConfig?.acpxSessionMode === "agent"), "Agent mode and per-turn restrictive permission policy selected before startup");
|
||||
const project = await api.post<Row>(`/api/companies/${fixtures.company.id}/projects`, { name: `Native active Stop ${nonce}`, executionWorkspacePolicy: { enabled: true, defaultMode: "shared_workspace", sharedWorkspaceConcurrency: "serialize", allowIssueOverride: false, environmentId: fixtures.environment.id, workspaceStrategy: { type: "project_primary" } }, workspace: { name: "Primary", sourceType: "local_path", cwd: input.workspacePath, isPrimary: true } });
|
||||
if (!remote) await sample("before-request");
|
||||
await createTaskThroughUi({ page, issuePrefix: fixtures.company.issuePrefix!, agentName: fixtures.agent.name, title: execution.task.buildTitle(nonce), prompt: remote ? input.remoteBootstrap!.prompt(nonce) : prompt(), workMode: "standard", projectName: project.name });
|
||||
issue = (await pollUntil({ label: "browser-created active Stop task", deadlineAt: input.deadlineAt, load: async () => (await api.get<Row[]>(`/api/companies/${fixtures.company.id}/issues?limit=100`)).find(i => i.title === execution.task.buildTitle(nonce)), accept: Boolean }))!;
|
||||
if (remote) {
|
||||
await pollUntil({ label: "active Stop remote bootstrap", deadlineAt: input.deadlineAt, load, accept: state => state.run.status === "running" });
|
||||
const bound = await input.remoteBootstrap!.bindAndRelease({ issueId: issue.id, runId: runs[0]!.id, targets: [target], actionPrompt: async value => {
|
||||
fixture = value; if (provider === "cursor") command = cursorDeniedCommand(join(value.remoteCwd, target));
|
||||
const prepared = await prepareNativeRemoteAction({ fixture: value, companyId: fixtures.company.id, environmentId: fixtures.environment.id, runId: runs[0]!.id, target, prompt: prompt() });
|
||||
baseline = prepared.baseline;
|
||||
remoteObservations.push({ phase: "before-request", source: "live-snapshot", snapshot: baseline });
|
||||
await input.evidence("active-stop-before-request-remote.json", baseline); return prepared.prompt;
|
||||
} });
|
||||
if (bound !== fixture) throw new Error("Remote active Stop publication identity changed");
|
||||
}
|
||||
const label = "unanswered native permission";
|
||||
await pollUntil({ label, deadlineAt: input.deadlineAt, intervalMs: 200, load: async () => {
|
||||
const state = await load(); if (["failed", "timed_out", "cancelled", "succeeded"].includes(state.run.status)) throw new Error(`Stopped waiting for ${label}: provider ended without pending callback`); return state;
|
||||
}, accept: state => { observeActiveStopPending({ ...state, scope: scope(), caller, cancellationRequestId: randomUUID(), bootstrap: bootstrap() }); return true; } });
|
||||
await page.goto(`/${fixtures.company.issuePrefix}/issues/${issue.identifier ?? issue.id}`);
|
||||
const card = page.getByTestId("task-chat-runtime-request").filter({ visible: true });
|
||||
await expect(card).toHaveCount(1); await expect(card.getByRole("button", { name: "Deny", exact: true })).toBeEnabled();
|
||||
await input.capture("pending-permission", "Native permission left unanswered before Stop", "pending-permission.png"); await sample("pending");
|
||||
completed = await stopAtPendingPermission({ scope: scope(), caller, bootstrap: bootstrap(), deadlineAt: input.deadlineAt, load,
|
||||
retain: proof => input.evidence("native-active-stop-pending.json", proof), stop: (runId, cancellationRequestId) => api.post(`/api/heartbeat-runs/${runId}/cancel`, { cancellationRequestId }) });
|
||||
check("pending-callback-cancelled", true, "Unanswered native permission closed through a cancelled provider turn and the exact caller-owned Stop acknowledgement");
|
||||
await input.evidence("native-active-stop-settlement.json", completed);
|
||||
// Only after confirmed cancellation: test the real public stale-response fence.
|
||||
const response = await api.request.post(`/api/heartbeat-runs/${runs[0]!.id}/runtime-requests/${encodeURIComponent(completed.pending.requestId)}/resolve`, { data: { turnId: completed.pending.turnId, requestKind: "permission_approval", resolution: { action: "accept" } } });
|
||||
check("stale-answer-refused", response.status() === 409, "Stopped permission rejects a later answer rather than replaying work");
|
||||
await load(); readActiveStopSettlement({ ...await load(), ...completed, bootstrap: bootstrap() });
|
||||
if (remote) {
|
||||
// finish drains the observer's automatic retirement seal. It does not
|
||||
// extend the remote watch through subsequent host UI/cleanup assertions.
|
||||
sealed = await fixture!.finish(); assertNativeRemoteRetirement(sealed, baseline!); processes = sealed.processes;
|
||||
remoteObservations.push({ phase: "owned-process-retirement", source: "retirement-seal", snapshot: sealed });
|
||||
await input.evidence("active-stop-owned-process-retirement-remote.json", sealed);
|
||||
} else await sample("after-stop");
|
||||
await page.reload();
|
||||
const finalUiTimeout = () => {
|
||||
const remaining = input.deadlineAt - Date.now();
|
||||
if (remaining <= 0) throw new Error("Active Stop final UI deadline elapsed");
|
||||
return Math.min(30_000, remaining);
|
||||
};
|
||||
// Absence of a permission button during React loading is not proof that a
|
||||
// stopped request is unanswerable. First observe the actual task/run UI.
|
||||
await expect(page.getByTestId("issue-detail-header").getByRole("button", {
|
||||
name: "Change status (current: In Progress)", exact: true,
|
||||
})).toBeVisible({ timeout: finalUiTimeout() });
|
||||
await expect(page.getByTestId("task-chat-thread").getByTestId("task-chat-collapsible-marker")
|
||||
.filter({ has: page.getByText("Run cancelled", { exact: true }) }))
|
||||
.toBeVisible({ timeout: finalUiTimeout() });
|
||||
await expect(page.getByTestId("task-chat-history-loading"))
|
||||
.toHaveCount(0, { timeout: finalUiTimeout() });
|
||||
await expect(card.getByRole("button", { name: "Deny", exact: true }))
|
||||
.toHaveCount(0, { timeout: finalUiTimeout() });
|
||||
await load(); readActiveStopSettlement({ ...await load(), ...completed, bootstrap: bootstrap() });
|
||||
check("one-unfinished-cancelled-run", runs.length === 1 && issue.status === "in_progress" && runs[0]!.status === "cancelled", "No automatic follow-up run or false task completion");
|
||||
await input.capture("final-state", "Stopped native permission is no longer answerable", "final-state.png");
|
||||
await input.evidence("api-state.json", { issue, run: runs[0], runs, checks, samples, remoteObservations, runEvents: events, runEventsByRun: [{ runId: runs[0]!.id, events }], activeStop: completed });
|
||||
return { issue, runs, checks };
|
||||
} finally {
|
||||
// Local observation continues through cleanup. Remote cleanup revalidates
|
||||
// the lifetime seal and fresh API state without claiming later file reads.
|
||||
await input.evidence("native-active-stop-checks.json", { issue, runs, checks, samples, remoteObservations, completed });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { RunnerTaskFixture } from "./types.js";
|
||||
export const nativeActiveStopTasks: readonly RunnerTaskFixture[] = [{
|
||||
id: "pending-permission-stop", label: "Stop while native permission is unanswered", groups: [], workMode: "standard", flow: "native_active_stop",
|
||||
expectedRunCount: 1, attemptTimeoutMs: { local: 300_000, daytona: 300_000 }, turnTimeoutMs: 120_000,
|
||||
expectedTerminalState: { issue: "in_progress", run: "cancelled" },
|
||||
buildTitle: nonce => `Native pending permission Stop ${nonce}`,
|
||||
buildVisibleMarker: nonce => `NATIVE-ACTIVE-STOP-${nonce}`,
|
||||
buildPrompt: () => "Attempt the supplied exact native operation once. Leave its native permission callback pending for the board operator. Do not answer, reject or cancel your own permission; do not retry, use another tool/path, call paperclip_finish, or claim completion. The operator will stop this unfinished task while permission is still unanswered.",
|
||||
buildMatchers: () => [], // Dedicated flow requires pending API observation, caller-owned Stop and retirement.
|
||||
}];
|
||||
@@ -0,0 +1,451 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { assertActiveStopRetirement, readActiveStopRemoteRetirement, type ActiveStopRemoteObservation, readActiveStopCaller, observeActiveStopPending, readActiveStopSettlement, type ActiveStopProvider } from "./native-active-stop-evidence.js";
|
||||
import { stopAtPendingPermission } from "./native-active-stop-flow.js";
|
||||
import { runnerMatrix, runnerSuites, suiteDefinitionHash } from "./catalog.js";
|
||||
import { selectRunnerExecutions, parseRunnerSelectors } from "./selectors.js";
|
||||
import { createCursorToolEvidence } from "../../packages/paperclip-runner/src/drivers/acpx/cursor-tool-evidence.js";
|
||||
import type { CanonicalProviderEvent } from "../../packages/paperclip-runner/src/provider-events.js";
|
||||
|
||||
import { CodexSessionState } from "../../packages/paperclip-runner/src/drivers/codex/codex-session-state.js";
|
||||
import { mapTerminalTurn } from "../../packages/paperclip-runner/src/drivers/codex/codex-session-terminal.js";
|
||||
|
||||
const caller = readActiveStopCaller({ deploymentMode: "local_trusted" }, { session: { userId: "local-board", id: "paperclip:local_implicit:local-board" } });
|
||||
const cancellationRequestId = "11111111-2222-4333-8444-555555555555";
|
||||
type Row = Record<string, any>;
|
||||
function fixture(provider: ActiveStopProvider = "cursor") {
|
||||
const scope = { provider, companyId: "company", issueId: "issue", runId: "run", target: "target.txt", ...(provider === "cursor" ? { commandSha256: `sha256:${"a".repeat(64)}` } : {}) };
|
||||
const row = (seq: number, eventType: string, payload: Row): Row => ({ companyId: "company", runId: "run", seq, eventType, protocolSchemaVersion: 1,
|
||||
payload: { prpEvent: { schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", eventType, runId: "run", turnId: "turn",
|
||||
normalizedSessionId: "normalized-session", sourceInstanceId: "source", sourceSeq: seq, sourceEventId: `source:run:${seq}`, emittedAt: "2026-01-01T00:00:00Z", payload } } });
|
||||
const notice = (seq: number, stage: string, fields: Row) => row(seq, "provider.notice.recorded", {
|
||||
schema: "paperclip.provider.notice.v1", scope: "turn", category: `${provider}_tool_evidence_v1`,
|
||||
provenance: { sessionId: "native-session", turnId: "turn", eventType: stage, method: stage === "tool" ? "session/update" : "session/request_permission" },
|
||||
details: Object.entries({ stage, toolCallId: "tool", ...fields }).map(([name, value]) => ({ name, value: String(value) })),
|
||||
});
|
||||
const operation = provider === "cursor" ? { operation: "execute", commandSha256: scope.commandSha256 } : { operation: "edit", target: scope.target };
|
||||
const events: Row[] = [
|
||||
notice(1, "tool", { status: "pending", ...operation }),
|
||||
row(2, "tool.execution.started", { schema: "paperclip.tool.execution.v1", executionId: "tool", transport: "builtin", status: "running", ...operation }),
|
||||
notice(3, "permission_requested", { requestId: "request", declineOffered: true, ...operation }),
|
||||
row(4, "runtime_request.created", { request: { schema: "paperclip.runtime_request.v2", requestKind: "permission_approval", type: "permission", status: "pending", requestId: "request", turnId: "turn", itemId: "item-run", method: "session/request_permission",
|
||||
details: { toolCallId: "tool" }, origin: { adapter: "acpx-runtime-sidecar", provider, method: "session/request_permission" } } }),
|
||||
];
|
||||
const run: Row = { id: "run", companyId: "company", nativeIssueId: "issue", runtimeMode: "native", status: "running", resultJson: {} };
|
||||
const issue = { id: "issue", companyId: "company", status: "in_progress" };
|
||||
const state = () => ({ events, run, issue });
|
||||
const pending = () => observeActiveStopPending({ ...state(), scope, caller, cancellationRequestId });
|
||||
const permissionResponse = vi.fn();
|
||||
const settle = (requestId = cancellationRequestId) => {
|
||||
// Exercise the actual Product terminal and pending-request producers. Only
|
||||
// the state storage/emitter and callback are test doubles; no provider runs.
|
||||
const request = events.find(event => event.eventType === "runtime_request.created")!.payload.prpEvent.payload.request;
|
||||
const state = {
|
||||
terminalTurns: new Map(), workspaceChangesByTurn: new Map(), result: null,
|
||||
conversationMode: "direct", activeTurnId: "turn", turnStarted: true,
|
||||
pendingRuntimeRequestMap: new Map([[request.requestId, { request, settle: permissionResponse }]]),
|
||||
cancelPendingRequests: CodexSessionState.prototype.cancelPendingRequests,
|
||||
emit: (eventType: string, value: Row) => events.push(row(events.length + 1, eventType, value)),
|
||||
} as unknown as CodexSessionState;
|
||||
mapTerminalTurn(state, { id: "turn", status: "cancelled", error: null }, "turn");
|
||||
run.status = "cancelled"; run.resultJson = { startupCancellation: { cancellationRequestId: requestId, requestedBy: { type: "board", userId: "local-board" } }, nativeCancellation: {
|
||||
schema: "paperclip.native-cancellation.v1", intentId: `native-cancellation:${requestId}`, companyId: "company", runId: "run", issueId: "issue", scope: "run",
|
||||
dispatched: true, dispatchState: "acknowledged", reasonCode: "cancellation_run_only", effects: ["release_run_resources"], intentAuditId: "audit-intent", acknowledgementAuditId: "audit-ack",
|
||||
} };
|
||||
return run;
|
||||
};
|
||||
return { scope, events, run, issue, row, notice, state, pending, settle, permissionResponse };
|
||||
}
|
||||
const frame = (row: Row) => row.payload.prpEvent;
|
||||
const payload = (row: Row) => frame(row).payload;
|
||||
const arrivalOrders = ["tool-first", "permission-first"] as const;
|
||||
function withArrivalOrder(provider: ActiveStopProvider, order: typeof arrivalOrders[number]) {
|
||||
const f = fixture(provider);
|
||||
if (order === "permission-first") {
|
||||
// Isolate canonical card/start order in these synthetic mutation cases.
|
||||
// Actual provider-specific notice ordering is exercised by the projectors.
|
||||
f.events.unshift(f.events.pop()!);
|
||||
f.events.forEach((row, index) => {
|
||||
row.seq = frame(row).sourceSeq = index + 1;
|
||||
frame(row).sourceEventId = `source:run:${index + 1}`;
|
||||
});
|
||||
}
|
||||
return f;
|
||||
}
|
||||
function withProjectedArrivalOrder(provider: ActiveStopProvider, order: typeof arrivalOrders[number]) {
|
||||
const f = fixture(provider), start = payload(f.events[1]!), card = payload(f.events[3]!);
|
||||
const command = "printf MUST_NOT_EXIST > target.txt";
|
||||
if (provider === "cursor") {
|
||||
f.scope.commandSha256 = `sha256:${createHash("sha256").update(command).digest("hex")}`;
|
||||
start.commandSha256 = f.scope.commandSha256;
|
||||
}
|
||||
f.events.length = 0;
|
||||
const append = (eventType: string, value: Row) => f.events.push(f.row(f.events.length + 1, eventType, value));
|
||||
const projector = (createCursorToolEvidence)({
|
||||
sessionId: "native-session", turnId: "turn", workingDirectory: "/fixture", active: () => true,
|
||||
emit: (event: CanonicalProviderEvent) => { append(event.eventType, event.payload); },
|
||||
});
|
||||
const tool = { type: "tool_call", tag: "tool_call", toolCallId: "tool", status: "pending",
|
||||
...(provider === "cursor" ? { kind: "execute", rawInput: { command } } : { kind: "edit", rawInput: { fileName: "target.txt" } }),
|
||||
};
|
||||
let delivered: ((outcome: string) => void) | undefined, beforeTool: Row[] | undefined;
|
||||
const permission = () => {
|
||||
delivered = projector.permission({ raw: { sessionId: "native-session", toolCall: provider === "cursor"
|
||||
? { toolCallId: "tool", kind: "execute" } : { toolCallId: "tool", kind: "edit", rawInput: tool.rawInput } } }, "request", ["decline", "cancel"]);
|
||||
// Match the sidecar: invoke the evidence projector before publishing the
|
||||
// permission request; project each iterator tool before its canonical row.
|
||||
append("runtime_request.created", card);
|
||||
};
|
||||
const notification = () => { projector.tool(tool); append("tool.execution.started", start); };
|
||||
if (order === "permission-first") { permission(); beforeTool = structuredClone(f.events); notification(); }
|
||||
else { notification(); permission(); }
|
||||
if (!delivered) throw new Error("Native permission projector rejected the fixture");
|
||||
return { ...f, beforeTool, delivered, nativeStageOrder: () => f.events.filter(row => row.eventType === "provider.notice.recorded").map(row => payload(row).provenance.eventType) };
|
||||
}
|
||||
function settled() { const f = fixture(); const pending = f.pending(); f.settle(); return { f, pending, read: () => readActiveStopSettlement({ ...f.state(), pending, dispatchMonotonicNs: (BigInt(pending.observedMonotonicNs) + 1n).toString() }) }; }
|
||||
function withSessionPrefix(provider: ActiveStopProvider = "cursor") {
|
||||
const f = fixture(provider);
|
||||
// The retained failed attempt contained v1 session.started followed by these
|
||||
// v2 session events before its v1 tool/permission events. Keep that shape;
|
||||
// this synthetic fixture supplies the otherwise required native tool proof.
|
||||
for (const row of f.events) {
|
||||
row.seq += 30; frame(row).sourceSeq += 3;
|
||||
frame(row).sourceEventId = `source:run:${frame(row).sourceSeq}`;
|
||||
}
|
||||
const prefix = [f.row(17, "session.started", {}),
|
||||
f.row(19, "session.capabilities.updated", { sessionGoals: null }),
|
||||
f.row(21, "session.goal.snapshot", { goal: null, workingNow: false })];
|
||||
prefix.forEach((row, index) => {
|
||||
const e = frame(row); e.turnId = null; e.sourceSeq = index + 1; e.sourceEventId = `source:run:${index + 1}`;
|
||||
if (index > 0) { row.protocolSchemaVersion = 2; e.schema = "paperclip.prp.event.v2"; e.schemaVersion = 2; }
|
||||
});
|
||||
f.events.unshift(...prefix);
|
||||
return f;
|
||||
}
|
||||
|
||||
describe("definitely active native permission Stop", () => {
|
||||
describe.each(["cursor"] as const)("%s pre-Stop arrival orders", provider => {
|
||||
it.each(arrivalOrders)("accepts %s only after both exact origins exist and retains them through settlement", order => {
|
||||
const f = withProjectedArrivalOrder(provider, order), pending = f.pending();
|
||||
expect(f.nativeStageOrder()).toEqual(["tool", "permission_requested"]);
|
||||
expect(pending.schema).toBe("paperclip.e2e.native-active-stop-pending.v2");
|
||||
expect(pending.toolOriginRowSha256).toMatch(/^sha256:[a-f0-9]{64}$/u);
|
||||
expect(pending.toolStartedRowSha256).toMatch(/^sha256:[a-f0-9]{64}$/u);
|
||||
expect(pending.toolStartedSourceSeq < pending.requestSourceSeq).toBe(order === "tool-first");
|
||||
f.settle();
|
||||
expect(readActiveStopSettlement({ ...f.state(), pending, dispatchMonotonicNs: (BigInt(pending.observedMonotonicNs) + 1n).toString() }))
|
||||
.toMatchObject({ branch: "pending_permission_cancelled", pending });
|
||||
});
|
||||
it("cannot retain permission-only projector output before its exact origin arrives", () => {
|
||||
const f = withProjectedArrivalOrder(provider, "permission-first");
|
||||
expect(() => observeActiveStopPending({ ...f.state(), events: f.beforeTool!, scope: f.scope, caller, cancellationRequestId })).toThrow();
|
||||
});
|
||||
it.each(arrivalOrders)("rejects a delivered answer in real-projector %s evidence", order => {
|
||||
const f = withProjectedArrivalOrder(provider, order); f.delivered("cancel"); expect(f.pending).toThrow("permission already answered");
|
||||
});
|
||||
it("does not accept a permission-first request for a different native origin", () => {
|
||||
const f = withProjectedArrivalOrder(provider, "permission-first");
|
||||
const tool = f.events.find(row => row.eventType === "provider.notice.recorded" && payload(row).provenance.eventType === "tool")!;
|
||||
payload(tool).details.find((d: Row) => d.name === "toolCallId").value = "another-tool";
|
||||
expect(f.pending).toThrow("native operation origin missing");
|
||||
});
|
||||
it.each([
|
||||
["missing native origin", (f: ReturnType<typeof fixture>) => { f.events.splice(1, 1); }],
|
||||
["missing canonical start", (f: ReturnType<typeof fixture>) => { f.events.splice(2, 1); }],
|
||||
["wrong native tool", (f: ReturnType<typeof fixture>) => { payload(f.events[1]!).details.find((d: Row) => d.name === "toolCallId").value = "other"; }],
|
||||
["wrong canonical tool", (f: ReturnType<typeof fixture>) => { payload(f.events[2]!).executionId = "other"; }],
|
||||
["wrong command or path", (f: ReturnType<typeof fixture>) => { payload(f.events[1]!).details.find((d: Row) => d.name === (provider === "cursor" ? "commandSha256" : "target")).value = provider === "cursor" ? `sha256:${"b".repeat(64)}` : "other.txt"; }],
|
||||
["wrong source", (f: ReturnType<typeof fixture>) => { frame(f.events[2]!).sourceInstanceId = "other"; frame(f.events[2]!).sourceEventId = "other:run:3"; }],
|
||||
["wrong turn", (f: ReturnType<typeof fixture>) => { frame(f.events[2]!).turnId = "other"; }],
|
||||
["wrong request", (f: ReturnType<typeof fixture>) => { payload(f.events[0]!).request.requestId = "other"; }],
|
||||
["replayed canonical start", (f: ReturnType<typeof fixture>) => { f.events.push(f.row(5, "tool.execution.started", payload(f.events[2]!))); }],
|
||||
["replayed native origin", (f: ReturnType<typeof fixture>) => { f.events.push(f.row(5, "provider.notice.recorded", payload(f.events[1]!))); }],
|
||||
["answered permission", (f: ReturnType<typeof fixture>) => { f.events.push(f.notice(5, "permission_delivered", { requestId: "request", outcome: "cancel" })); }],
|
||||
["terminal operation", (f: ReturnType<typeof fixture>) => { f.events.push(f.row(5, "tool.execution.completed", { schema: "paperclip.tool.execution.v1", transport: "builtin", executionId: "tool", status: "failed" })); }],
|
||||
] as const)("rejects permission-first %s before Stop", (_label, mutate) => {
|
||||
const f = withArrivalOrder(provider, "permission-first"); mutate(f); expect(f.pending).toThrow();
|
||||
});
|
||||
it("cannot substitute a canonical start first observed after Stop", () => {
|
||||
const f = withArrivalOrder(provider, "permission-first"), pending = f.pending();
|
||||
const started = f.events.splice(2, 1)[0]!;
|
||||
// A late row has a new durable identity even when every operation field
|
||||
// is identical. Final evidence must not backfill the retained receipt.
|
||||
started.seq = frame(started).sourceSeq = 5; frame(started).sourceEventId = "source:run:5";
|
||||
f.events.push(started); f.settle();
|
||||
for (const row of f.events.slice(-2)) {
|
||||
row.seq += 1; frame(row).sourceSeq += 1; frame(row).sourceEventId = `source:run:${row.seq}`;
|
||||
}
|
||||
expect(() => readActiveStopSettlement({ ...f.state(), pending, dispatchMonotonicNs: (BigInt(pending.observedMonotonicNs) + 1n).toString() }))
|
||||
.toThrow("observed pending request changed");
|
||||
});
|
||||
});
|
||||
it("still rejects a Cursor permission notice before the origin its projector requires", () => {
|
||||
const f = withProjectedArrivalOrder("cursor", "permission-first");
|
||||
[f.events[1], f.events[2]] = [f.events[2]!, f.events[1]!];
|
||||
f.events.forEach((row, index) => {
|
||||
row.seq = frame(row).sourceSeq = index + 1; frame(row).sourceEventId = `source:run:${index + 1}`;
|
||||
});
|
||||
expect(f.pending).toThrow("duplicate native operation lifecycle");
|
||||
});
|
||||
it.each(["cursor"] as const)("accepts the mixed v1/v2 session prefix before strict %s pending proof", provider => {
|
||||
const f = withSessionPrefix(provider);
|
||||
expect(f.pending()).toMatchObject({ requestId: "request", toolCallId: "tool", permissionSourceSeq: 6, requestSourceSeq: 7 });
|
||||
});
|
||||
it.each([
|
||||
["schema/version mismatch", (f: ReturnType<typeof withSessionPrefix>) => { frame(f.events[1]!).schemaVersion = 1; }],
|
||||
["row/envelope mismatch", (f: ReturnType<typeof withSessionPrefix>) => { f.events[1]!.protocolSchemaVersion = 1; }],
|
||||
["unknown schema", (f: ReturnType<typeof withSessionPrefix>) => { frame(f.events[1]!).schema = "paperclip.prp.event.v3"; frame(f.events[1]!).schemaVersion = f.events[1]!.protocolSchemaVersion = 3; }],
|
||||
["foreign session source", (f: ReturnType<typeof withSessionPrefix>) => { frame(f.events[1]!).sourceKind = "provider"; }],
|
||||
] as const)("still rejects %s in a mixed-version stream", (_label, mutate) => {
|
||||
const f = withSessionPrefix(); mutate(f); expect(f.pending).toThrow("invalid/duplicate/foreign canonical row");
|
||||
});
|
||||
it("does not let a valid v2 prefix hide the retained Cursor incomplete-evidence failure", () => {
|
||||
const f = withSessionPrefix();
|
||||
const notice = f.events.find(row => row.eventType === "provider.notice.recorded")!;
|
||||
payload(notice).provenance.eventType = "evidence_incomplete";
|
||||
payload(notice).details = Object.entries({ stage: "evidence_incomplete", toolCallId: "unavailable", reason: "projection_failed" }).map(([name, value]) => ({ name, value }));
|
||||
expect(f.pending).toThrow("Cursor evidence is explicitly incomplete");
|
||||
});
|
||||
it("still requires the original native tool ID on the durable card after a valid v2 prefix", () => {
|
||||
const f = withSessionPrefix();
|
||||
delete payload(f.events.find(row => row.eventType === "runtime_request.created")!).request.details.toolCallId;
|
||||
expect(f.pending).toThrow("native notice/card identity mismatch");
|
||||
});
|
||||
it.each(["cursor"] as const)("binds %s's unanswered callback to cancelled provider settlement and caller-owned Stop", provider => {
|
||||
const f = fixture(provider), pending = f.pending(); f.settle();
|
||||
expect(f.permissionResponse.mock.calls).toEqual([[{ action: "cancel" }]]);
|
||||
expect(readActiveStopSettlement({ ...f.state(), pending, dispatchMonotonicNs: (BigInt(pending.observedMonotonicNs) + 1n).toString() })).toMatchObject({
|
||||
schema: "paperclip.e2e.native-active-stop-settlement.v2", branch: "pending_permission_cancelled", normalCompletionAccepted: false, taskStillInProgress: true, replayAllowed: false,
|
||||
pending: { normalizedSessionId: "normalized-session", nativeSessionId: "native-session", cancellationRequestId },
|
||||
});
|
||||
});
|
||||
it("matches the retained Product closure shape with distinct native and item identities", () => {
|
||||
const { f, pending, read } = settled();
|
||||
expect(pending.toolCallId).toBe("tool");
|
||||
// Content-free shape captured from the failed Product attempt. These exact
|
||||
// payloads come from mapTerminalTurn -> cancelPendingRequests above.
|
||||
expect(payload(f.events[4]!)).toEqual({ requestId: "request", requestKind: "permission_approval",
|
||||
turnId: "turn", itemId: "item-run", reason: "turn_terminal" });
|
||||
expect(payload(f.events[5]!)).toEqual({ status: "cancelled", error: null });
|
||||
expect(read().schema).toBe("paperclip.e2e.native-active-stop-settlement.v2");
|
||||
});
|
||||
it("admits only a fully attested remote bootstrap read completed before the pending operation", () => {
|
||||
const f = fixture(), actionFile = `.paperclip-eval-action-${"a".repeat(36)}.txt`;
|
||||
const readTargetSha256 = `sha256:${createHash("sha256").update(actionFile).digest("hex")}`;
|
||||
for (const row of f.events) { row.seq += 4; frame(row).sourceSeq += 4; frame(row).sourceEventId = `source:run:${row.seq}`; }
|
||||
f.events.unshift(f.notice(1, "tool", { toolCallId: "bootstrap", operation: "read", status: "pending", readTargetSha256 }),
|
||||
f.row(2, "tool.execution.started", { schema: "paperclip.tool.execution.v1", executionId: "bootstrap", transport: "builtin", status: "running", operation: "read", target: actionFile }),
|
||||
f.notice(3, "tool", { toolCallId: "bootstrap", operation: "read", status: "completed", readTargetSha256 }),
|
||||
f.row(4, "tool.execution.completed", { schema: "paperclip.tool.execution.v1", executionId: "bootstrap", transport: "builtin", status: "completed", operation: "read", target: actionFile }));
|
||||
const bootstrap = { actionFile, events: f.events };
|
||||
expect(() => observeActiveStopPending({ ...f.state(), scope: f.scope, caller, cancellationRequestId, bootstrap })).not.toThrow();
|
||||
payload(f.events[2]!).details.find((d: Row) => d.name === "readTargetSha256").value = `sha256:${"0".repeat(64)}`;
|
||||
expect(() => observeActiveStopPending({ ...f.state(), scope: f.scope, caller, cancellationRequestId, bootstrap })).toThrow(/bootstrap/);
|
||||
});
|
||||
it("does not compare remote wall clock or transaction timestamps to the operator clock", () => {
|
||||
const f = fixture(); for (const row of f.events) { frame(row).emittedAt = "2099-01-01T00:00:00Z"; row.createdAt = "1900-01-01T00:00:00Z"; }
|
||||
const pending = f.pending(); f.settle();
|
||||
expect(() => readActiveStopSettlement({ ...f.state(), pending, dispatchMonotonicNs: (BigInt(pending.observedMonotonicNs) + 1n).toString() })).not.toThrow();
|
||||
});
|
||||
it.each([
|
||||
["prior Stop claim", (f: ReturnType<typeof fixture>) => { f.run.resultJson.startupCancellation = { cancellationRequestId }; }],
|
||||
["answered callback", (f: ReturnType<typeof fixture>) => { f.events.push(f.notice(5, "permission_delivered", { requestId: "request", outcome: "cancel" })); }],
|
||||
["already settled provider", (f: ReturnType<typeof fixture>) => { f.events.push(f.row(5, "turn.completed", { status: "completed" })); }],
|
||||
["already closed request", (f: ReturnType<typeof fixture>) => { f.events.push(f.row(5, "runtime_request.resolved", {})); }],
|
||||
["failed operation", (f: ReturnType<typeof fixture>) => { f.events.push(f.row(5, "tool.execution.completed", { schema: "paperclip.tool.execution.v1", transport: "builtin", executionId: "tool", status: "failed" })); }],
|
||||
] as const)("refuses %s before dispatch", (_label, mutate) => { const f = fixture(); mutate(f); expect(f.pending).toThrow(); });
|
||||
it.each([
|
||||
["completed terminal", ({ f }: ReturnType<typeof settled>) => { f.events[5]!.eventType = frame(f.events[5]!).eventType = "turn.completed"; payload(f.events[5]!).status = "completed"; }],
|
||||
["interrupted terminal", ({ f }: ReturnType<typeof settled>) => { f.events[5]!.eventType = frame(f.events[5]!).eventType = "turn.interrupted"; payload(f.events[5]!).status = "interrupted"; }],
|
||||
["failed terminal", ({ f }: ReturnType<typeof settled>) => { payload(f.events[5]!).error = { code: "failure" }; }],
|
||||
["duplicate terminal", ({ f }: ReturnType<typeof settled>) => { f.events.push(f.row(7, "turn.cancelled", payload(f.events[5]!))); }],
|
||||
["late same-tool replay", ({ f }: ReturnType<typeof settled>) => { f.events.push(f.notice(7, "tool", { status: "in_progress" })); }],
|
||||
["wrong closed item", ({ f }: ReturnType<typeof settled>) => { payload(f.events[4]!).itemId = "other"; }],
|
||||
["reordered source stream", ({ f }: ReturnType<typeof settled>) => { frame(f.events[5]!).sourceSeq = 1; frame(f.events[5]!).sourceEventId = "source:run:1"; }],
|
||||
["missing terminal", ({ f }: ReturnType<typeof settled>) => { f.events.pop(); }],
|
||||
["wrapper type mismatch", ({ f }: ReturnType<typeof settled>) => { f.events[5]!.eventType = "turn.completed"; }],
|
||||
["foreign normalized session", ({ f }: ReturnType<typeof settled>) => { frame(f.events[5]!).normalizedSessionId = "native-session"; }],
|
||||
["foreign source", ({ f }: ReturnType<typeof settled>) => { frame(f.events[5]!).sourceInstanceId = "foreign"; }],
|
||||
["foreign turn", ({ f }: ReturnType<typeof settled>) => { frame(f.events[5]!).turnId = "other-turn"; }],
|
||||
["foreign company", ({ f }: ReturnType<typeof settled>) => { f.events[5]!.companyId = "other"; }],
|
||||
["foreign request", ({ f }: ReturnType<typeof settled>) => { payload(f.events[4]!).requestId = "other"; }],
|
||||
["expired rather than cancelled", ({ f }: ReturnType<typeof settled>) => { f.events[4]!.eventType = frame(f.events[4]!).eventType = "runtime_request.expired"; }],
|
||||
["provider death", ({ f }: ReturnType<typeof settled>) => { payload(f.events[4]!).reason = "provider_process_lost"; }],
|
||||
["raw backend closure is not the Product contract", ({ f }: ReturnType<typeof settled>) => { payload(f.events[4]!).reason = "explicit_cancellation"; }],
|
||||
["answered closure", ({ f }: ReturnType<typeof settled>) => { payload(f.events[4]!).action = "accept"; }],
|
||||
["resolved request", ({ f }: ReturnType<typeof settled>) => { f.events[4]!.eventType = frame(f.events[4]!).eventType = "runtime_request.resolved"; }],
|
||||
["duplicate closure", ({ f }: ReturnType<typeof settled>) => { f.events.push(f.row(7, "runtime_request.cancelled", payload(f.events[4]!))); }],
|
||||
["foreign closure turn", ({ f }: ReturnType<typeof settled>) => { payload(f.events[4]!).turnId = "other"; }],
|
||||
["missing acknowledgement", ({ f }: ReturnType<typeof settled>) => { delete f.run.resultJson.nativeCancellation.acknowledgementAuditId; }],
|
||||
["unacknowledged intent", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.nativeCancellation.dispatchState = "pending"; }],
|
||||
["replay permitted", ({ f }: ReturnType<typeof settled>) => { payload(f.events[4]!).replayAllowed = true; }],
|
||||
["tampered pending row", ({ f }: ReturnType<typeof settled>) => { payload(f.events[3]!).request.itemId = "changed"; }],
|
||||
["missing pending receipt", (s: ReturnType<typeof settled>) => { s.pending.requestRowSha256 = ""; }],
|
||||
["legacy v1 pending receipt", (s: ReturnType<typeof settled>) => { (s.pending as Row).schema = "paperclip.e2e.native-active-stop-pending.v1"; }],
|
||||
["missing native origin binding", (s: ReturnType<typeof settled>) => { delete (s.pending as Row).toolOriginRowSha256; }],
|
||||
["missing tool start binding", (s: ReturnType<typeof settled>) => { delete (s.pending as Row).toolStartedRowSha256; }],
|
||||
["changed native origin", ({ f }: ReturnType<typeof settled>) => { frame(f.events[0]!).emittedAt = "2026-01-01T00:00:01Z"; }],
|
||||
["changed tool start", ({ f }: ReturnType<typeof settled>) => { frame(f.events[1]!).emittedAt = "2026-01-01T00:00:01Z"; }],
|
||||
["wrong origin sequence", (s: ReturnType<typeof settled>) => { s.pending.toolOriginSourceSeq += 1; }],
|
||||
["wrong start sequence", (s: ReturnType<typeof settled>) => { s.pending.toolStartedSourceSeq += 1; }],
|
||||
["missing caller", ({ f }: ReturnType<typeof settled>) => { delete f.run.resultJson.startupCancellation.requestedBy; }],
|
||||
["null caller", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.startupCancellation.requestedBy.userId = null; }],
|
||||
["foreign caller", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.startupCancellation.requestedBy.userId = "another-board-user"; }],
|
||||
["agent caller", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.startupCancellation.requestedBy.type = "agent"; }],
|
||||
["unbound caller receipt", (s: ReturnType<typeof settled>) => { (s.pending as Row).caller = null; }],
|
||||
["foreign intent", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.nativeCancellation.intentId = "native-cancellation:other"; }],
|
||||
["foreign ack scope", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.nativeCancellation.companyId = "other"; }],
|
||||
["undispatched cancellation", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.nativeCancellation.dispatched = false; }],
|
||||
["same audit twice", ({ f }: ReturnType<typeof settled>) => { f.run.resultJson.nativeCancellation.acknowledgementAuditId = "audit-intent"; }],
|
||||
["finished task", ({ f }: ReturnType<typeof settled>) => { f.issue.status = "done"; }],
|
||||
["extra semantic operation", ({ f }: ReturnType<typeof settled>) => { f.events.push(f.row(7, "tool.execution.started", { executionId: "other" })); }],
|
||||
["extra native operation", ({ f }: ReturnType<typeof settled>) => { f.events.push(f.notice(7, "tool", { toolCallId: "other", status: "pending" })); }],
|
||||
["native session switched", ({ f }: ReturnType<typeof settled>) => { payload(f.events[0]!).provenance.sessionId = "other"; }],
|
||||
["target operation completed", ({ f }: ReturnType<typeof settled>) => { f.events.push(f.row(7, "tool.execution.completed", { schema: "paperclip.tool.execution.v1", transport: "builtin", executionId: "tool", status: "completed" })); }],
|
||||
] as const)("rejects %s", (_label, mutate) => { const s = settled(); mutate(s); expect(s.read).toThrow(); });
|
||||
it.each(["closure", "terminal"] as const)("rejects missing/null envelope turn and foreign null-turn stream on %s", kind => {
|
||||
for (const turn of [null, undefined]) for (const mismatch of ["none", "session", "source"]) {
|
||||
const s = settled(), event = frame(s.f.events[kind === "closure" ? 4 : 5]!);
|
||||
event.turnId = turn;
|
||||
if (mismatch === "session") event.normalizedSessionId = "foreign-session";
|
||||
if (mismatch === "source") { event.sourceInstanceId = "foreign-source"; event.sourceEventId = `foreign-source:run:${event.sourceSeq}`; }
|
||||
expect(s.read).toThrow(/pending callback/);
|
||||
}
|
||||
});
|
||||
it.each([
|
||||
[{ deploymentMode: "authenticated" }, { session: { userId: "local-board", id: "paperclip:local_implicit:local-board" } }],
|
||||
[{ deploymentMode: "local_trusted" }, { session: { userId: null, id: "paperclip:local_implicit:local-board" } }],
|
||||
[{ deploymentMode: "local_trusted" }, { session: { userId: "another", id: "paperclip:local_implicit:another" } }],
|
||||
[{ deploymentMode: "local_trusted" }, { session: { userId: "local-board", id: "paperclip:session:local-board" } }],
|
||||
])("rejects a non-fixture authentication context", (health, session) => expect(() => readActiveStopCaller(health, session)).toThrow());
|
||||
it("rejects a Stop dispatch not causally after the pending observation", () => {
|
||||
const { f, pending } = settled();
|
||||
expect(() => readActiveStopSettlement({ ...f.state(), pending, dispatchMonotonicNs: pending.observedMonotonicNs })).toThrow(/pre-dispatch/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("active Stop flow wiring", () => {
|
||||
it.each([
|
||||
["cursor", "tool-first"], ["cursor", "permission-first"],
|
||||
] as const)("awaits retention and rechecks real %s %s evidence before issuing the single caller UUID request", async (provider, arrivalOrder) => {
|
||||
const f = withProjectedArrivalOrder(provider, arrivalOrder); const order: string[] = []; let retainedId = "";
|
||||
const stop = vi.fn(async (runId: string, id: string) => { expect(runId).toBe("run"); expect(id).toBe(retainedId); order.push("stop"); return f.settle(id); });
|
||||
const result = await stopAtPendingPermission({ scope: f.scope, caller, deadlineAt: Date.now() + 1000,
|
||||
load: async () => { order.push("load"); return f.state(); },
|
||||
retain: async receipt => { order.push("retain-start"); await Promise.resolve(); retainedId = receipt.cancellationRequestId; order.push("retain-done"); }, stop });
|
||||
expect(order).toEqual(["load", "retain-start", "retain-done", "load", "stop", "load"]);
|
||||
expect(stop).toHaveBeenCalledTimes(1); expect(result.settlement.branch).toBe("pending_permission_cancelled");
|
||||
});
|
||||
it.each(["retention failed", "competing Stop", "answered after capture"])("never sends Stop when %s", async mode => {
|
||||
const f = fixture(), stop = vi.fn();
|
||||
await expect(stopAtPendingPermission({ scope: f.scope, caller, deadlineAt: Date.now() + 1000, load: async () => f.state(), stop,
|
||||
retain: async () => { if (mode === "retention failed") throw Error("disk failure"); if (mode === "competing Stop") f.run.resultJson.startupCancellation = { cancellationRequestId: "foreign" }; else f.events.push(f.row(5, "runtime_request.resolved", {})); },
|
||||
})).rejects.toThrow(); expect(stop).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["native origin", "canonical start"])("never sends Stop when the retained %s changes before the fresh reread", async kind => {
|
||||
const f = withArrivalOrder("cursor", "permission-first"), stop = vi.fn();
|
||||
await expect(stopAtPendingPermission({ scope: f.scope, caller, deadlineAt: Date.now() + 1000, load: async () => f.state(), stop,
|
||||
retain: async () => { frame(f.events[kind === "native origin" ? 1 : 2]!).emittedAt = "2026-01-01T00:00:01Z"; },
|
||||
})).rejects.toThrow("pending boundary changed or expired");
|
||||
expect(stop).not.toHaveBeenCalled();
|
||||
});
|
||||
it("never sends Stop to make a missing tool start arrive", async () => {
|
||||
const f = withArrivalOrder("cursor", "permission-first");
|
||||
const start = f.events.splice(2, 1)[0]!, retain = vi.fn();
|
||||
const stop = vi.fn(async () => { f.events.push(start); return f.settle(); });
|
||||
await expect(stopAtPendingPermission({ scope: f.scope, caller, deadlineAt: Date.now() + 1000, load: async () => f.state(), retain, stop }))
|
||||
.rejects.toThrow("duplicate canonical operation lifecycle");
|
||||
expect(retain).not.toHaveBeenCalled(); expect(stop).not.toHaveBeenCalled();
|
||||
});
|
||||
it("fails promptly on a definitive provider failure before calling a throwing evidence reader", async () => {
|
||||
const f = fixture(); const started = Date.now();
|
||||
await expect(stopAtPendingPermission({ scope: f.scope, caller, deadlineAt: started + 10000, load: async () => f.state(), retain: async () => {}, stop: async (_run, id) => {
|
||||
f.settle(id); f.run.status = "failed"; f.events.length = 0; return f.run;
|
||||
} })).rejects.toThrow(/Stopped waiting.*unexpected run terminal/);
|
||||
expect(Date.now() - started).toBeLessThan(500);
|
||||
});
|
||||
});
|
||||
|
||||
describe("explicit active Stop discovery", () => {
|
||||
it("adds exactly two versioned cells without enabling them in --all", () => {
|
||||
const suite = runnerSuites.find(s => s.id === "native-active-stop")!;
|
||||
const cells = runnerMatrix.filter(e => e.suite === suite);
|
||||
expect(cells).toHaveLength(2); expect(suite.manualOnly).toBe(true);
|
||||
expect(cells.map(e => `${e.profile.qualificationCandidate}/${e.environment.id}`).sort()).toEqual(["cursor/daytona", "cursor/local"]);
|
||||
expect(cells.every(e => e.task.expectedRunCount === 1 && e.task.flow === "native_active_stop" && e.task.expectedTerminalState?.run === "cancelled")).toBe(true);
|
||||
expect(suite.definitionMetadata).toMatchObject({ version: 4, evidence: "paperclip.e2e.native-active-stop-settlement.v2", normalCompletionAccepted: false, providerDeath: "not-covered" });
|
||||
expect(suiteDefinitionHash(suite)).not.toBe(suiteDefinitionHash({ ...suite, definitionMetadata: { ...suite.definitionMetadata, version: 3 } }));
|
||||
expect(suiteDefinitionHash(suite)).not.toBe(suiteDefinitionHash({ ...suite, definitionMetadata: { ...suite.definitionMetadata, normalCompletionAccepted: true } }));
|
||||
expect(selectRunnerExecutions(parseRunnerSelectors(["--all"])).some(e => e.suite.id === suite.id)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("active Stop cleanup remains mandatory", () => {
|
||||
const proof = () => ({ environment: "local" as const, completed: true, identityChanged: false, processes: { captured: true, live: [] as number[] },
|
||||
watcher: { complete: true, targetMutationCount: 0 }, samples: ["before-request", "pending", "after-stop", "after-cleanup"].map(phase => ({ phase, absent: true })) });
|
||||
it("requires all causal samples plus the continuous watcher and retired owned identities", () => expect(() => assertActiveStopRetirement(proof())).not.toThrow());
|
||||
it.each([
|
||||
["live child", (p: ReturnType<typeof proof>) => { p.processes.live.push(42); }],
|
||||
["unobserved process", (p: ReturnType<typeof proof>) => { p.processes.captured = false; }],
|
||||
["replaced root", (p: ReturnType<typeof proof>) => { p.identityChanged = true; }],
|
||||
["incomplete watch", (p: ReturnType<typeof proof>) => { p.watcher.complete = false; }],
|
||||
["transient write", (p: ReturnType<typeof proof>) => { p.watcher.targetMutationCount = 1; }],
|
||||
["written target", (p: ReturnType<typeof proof>) => { p.samples[2]!.absent = false; }],
|
||||
["missing final sample", (p: ReturnType<typeof proof>) => { p.samples.pop(); }],
|
||||
["missing settlement", (p: ReturnType<typeof proof>) => { p.completed = false; }],
|
||||
] as const)("rejects %s even after an apparent cancelled run", (_label, mutate) => { const p = proof(); mutate(p); expect(() => assertActiveStopRetirement(p)).toThrow(); });
|
||||
});
|
||||
|
||||
function remoteRetirementProof() {
|
||||
const root = { pid: 50, ppid: 1, startTicks: "200", bootId: "12345678-1234-1234-1234-123456789abc" };
|
||||
const child = { ...root, pid: 51, ppid: 50, startTicks: "201" };
|
||||
const snapshot = (sequence: number, live: number[]) => ({
|
||||
binding: { companyId: "company", environmentId: "env", runId: "run", leaseId: "lease", sandboxId: "sandbox", image: `image@sha256:${"a".repeat(64)}`, remoteCwd: "/home/daytona/workspace" },
|
||||
observedAtMs: sequence, receivedAtMs: sequence + 1, observedMonotonicNs: String(sequence), complete: true, workspace: {},
|
||||
targets: { "target.txt": { absent: true, sha256: null, complete: true, mutationCount: 0, parent: { dev: "1", ino: "2" } } },
|
||||
watcher: { complete: true, targetMutationCount: 0, workspaceMutationCount: 0 },
|
||||
processes: { captured: true, root, journal: [root, child], live },
|
||||
setup: { path: ".action.txt", sha256: sequence === 1 ? null : `sha256:${"b".repeat(64)}`, published: sequence !== 1 }, attached: null,
|
||||
});
|
||||
const observations: ActiveStopRemoteObservation[] = [
|
||||
{ phase: "before-request", source: "live-snapshot", snapshot: snapshot(1, [50, 51]) },
|
||||
{ phase: "pending", source: "live-snapshot", snapshot: snapshot(2, [50, 51]) },
|
||||
{ phase: "owned-process-retirement", source: "retirement-seal", snapshot: snapshot(3, []) },
|
||||
];
|
||||
return { scope: { companyId: "company", runId: "run", target: "target.txt" }, observations };
|
||||
}
|
||||
describe("Daytona active Stop observation lifetime", () => {
|
||||
it("binds one continuous owned-tree retirement seal without claiming a later filesystem observation", () => {
|
||||
const remote = remoteRetirementProof(), terminal = remote.observations[2]!.snapshot;
|
||||
expect(assertActiveStopRetirement({ environment: "daytona", completed: true, identityChanged: false,
|
||||
processes: terminal.processes, watcher: terminal.watcher, remote })).toMatchObject({
|
||||
schema: "paperclip.e2e.native-active-stop-remote-retirement.v1", coverage: "continuous-through-owned-process-retirement",
|
||||
filesystemAfterRetirementObserved: false, observations: [
|
||||
{ phase: "before-request", source: "live-snapshot" }, { phase: "pending", source: "live-snapshot" },
|
||||
{ phase: "owned-process-retirement", source: "retirement-seal" },
|
||||
],
|
||||
});
|
||||
});
|
||||
it.each([
|
||||
["seal relabeled fresh", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.source = "live-snapshot"; }],
|
||||
["seal replayed as pending", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[1]!.snapshot = p.observations[2]!.snapshot; }],
|
||||
["after-UI seal replay", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations.push({ ...p.observations[2]!, phase: "after-cleanup" as any }); }],
|
||||
["missing pending", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations.splice(1, 1); }],
|
||||
["all foreign run snapshots", (p: ReturnType<typeof remoteRetirementProof>) => { for (const o of p.observations) o.snapshot.binding.runId = "other"; }],
|
||||
["all foreign company snapshots", (p: ReturnType<typeof remoteRetirementProof>) => { for (const o of p.observations) o.snapshot.binding.companyId = "other"; }],
|
||||
["foreign lease", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.binding.leaseId = "other"; }],
|
||||
["foreign run", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[1]!.snapshot.binding.runId = "other"; }],
|
||||
["replacement root", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.processes.root = { ...p.observations[2]!.snapshot.processes.root!, startTicks: "300" }; }],
|
||||
["live child", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.processes.live = [51]; }],
|
||||
["lost child journal", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.processes.journal.pop(); }],
|
||||
["unobserved pending root", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[1]!.snapshot.processes.live = []; }],
|
||||
["transient target mutation", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.watcher.targetMutationCount = 1; }],
|
||||
["workspace mutation", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.watcher.workspaceMutationCount = 1; }],
|
||||
["late target present", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.targets["target.txt"]!.absent = false; }],
|
||||
["incomplete watcher", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.watcher.complete = false; }],
|
||||
["changed action", (p: ReturnType<typeof remoteRetirementProof>) => { p.observations[2]!.snapshot.setup.sha256 = `sha256:${"c".repeat(64)}`; }],
|
||||
] as const)("rejects %s", (_label, mutate) => {
|
||||
const proof = remoteRetirementProof(); mutate(proof); expect(() => readActiveStopRemoteRetirement(proof)).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { bootstrapReadExecutionId, withoutProvenBootstrapReads, type BootstrapReadNotice } from "./native-bootstrap-read-proof.js";
|
||||
const actionFile = `.paperclip-eval-action-${"a".repeat(36)}.txt`;
|
||||
const origin: BootstrapReadNotice = { runId: "run", sessionId: "session", turnId: "turn", toolCallId: "tested", stage: "tool", operation: "execute", status: "pending", seq: 20 };
|
||||
function read(status = "completed", seq = 1): BootstrapReadNotice { return { ...origin, toolCallId: "bootstrap", operation: "read", readTargetSha256: `sha256:${createHash("sha256").update(actionFile).digest("hex")}`, status, seq }; }
|
||||
function receipt(type = "completed", status = "completed", seq = 2) {
|
||||
return { runId: "run", seq, protocolSchemaVersion: 1, eventType: `tool.execution.${type}`, payload: { prpEvent: {
|
||||
schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: "run", turnId: "turn", eventType: `tool.execution.${type}`, emittedAt: new Date(seq).toISOString(),
|
||||
payload: { schema: "paperclip.tool.execution.v1", executionId: "bootstrap", transport: "builtin", operation: "read", target: actionFile, status },
|
||||
} } };
|
||||
}
|
||||
it.each(["completed", "failed"])("accepts an exact %s read even when the first native event is terminal", status => {
|
||||
expect(withoutProvenBootstrapReads([read(status), origin], origin, { actionFile, events: [receipt("completed", status)] })).toEqual([origin]);
|
||||
});
|
||||
it("accepts a complete started/progressed/failed lifecycle, including failed unpublished-file reads", () => {
|
||||
const rows = [read("pending", 1), read("in_progress", 3), read("failed", 5), origin];
|
||||
const events = [receipt("started", "running", 2), receipt("progressed", "running", 4), receipt("completed", "failed", 6)];
|
||||
expect(withoutProvenBootstrapReads(rows, origin, { actionFile, events })).toEqual([origin]);
|
||||
});
|
||||
it.each([
|
||||
"wrong-target", "missing-target", "foreign-run", "foreign-turn", "foreign-row-run", "wrong-source", "wrong-schema", "wrong-payload", "wrong-transport", "wrong-operation", "wrong-event-type", "invalid-date", "duplicate-row", "duplicate-seq", "conflicting-target", "missing-row", "missing-terminal", "late-row", "unknown-read-origin",
|
||||
])("rejects %s durable proof", variant => {
|
||||
const row = receipt(), rows = [row]; const notices = [read(), origin]; const event = row.payload.prpEvent;
|
||||
if (variant === "wrong-target") event.payload.target = "private.txt";
|
||||
if (variant === "missing-target") delete (event.payload as any).target;
|
||||
if (variant === "foreign-run") event.runId = "other";
|
||||
if (variant === "foreign-row-run") row.runId = "other";
|
||||
if (variant === "foreign-turn") event.turnId = "other";
|
||||
if (variant === "wrong-source") event.sourceKind = "provider";
|
||||
if (variant === "wrong-schema") event.schemaVersion = 2;
|
||||
if (variant === "wrong-payload") event.payload.schema = "unknown";
|
||||
if (variant === "wrong-transport") event.payload.transport = "mcp";
|
||||
if (variant === "wrong-operation") event.payload.operation = "edit";
|
||||
if (variant === "wrong-event-type") event.eventType = "tool.execution.progressed";
|
||||
if (variant === "invalid-date") event.emittedAt = "unknown";
|
||||
if (variant === "duplicate-row") rows.push(structuredClone(row));
|
||||
if (variant === "duplicate-seq") row.seq = 1;
|
||||
if (variant === "conflicting-target") { const other = receipt("completed", "completed", 3); other.payload.prpEvent.payload.target = "foreign.txt"; rows.push(other); }
|
||||
if (variant === "missing-row") rows.length = 0;
|
||||
if (variant === "missing-terminal") { rows[0] = receipt("started", "running"); notices[0] = read("pending"); }
|
||||
if (variant === "late-row") row.seq = 21;
|
||||
if (variant === "unknown-read-origin") event.payload.executionId = "unobserved-native-origin";
|
||||
expect(() => withoutProvenBootstrapReads(notices, origin, { actionFile, events: rows })).toThrow(/proof/);
|
||||
});
|
||||
it("does not exempt unrelated earlier reads or infer a path from a title", () => {
|
||||
const unrelated = { ...read(), toolCallId: "private-read", seq: 3 };
|
||||
const wrong = receipt("completed", "completed", 4); wrong.payload.prpEvent.payload.executionId = "private-read"; wrong.payload.prpEvent.payload.target = "secrets.txt";
|
||||
Object.assign(wrong.payload.prpEvent.payload, { name: `Read ${actionFile}` });
|
||||
expect(() => withoutProvenBootstrapReads([read(), unrelated, origin], origin, { actionFile, events: [receipt(), wrong] })).toThrow();
|
||||
expect(withoutProvenBootstrapReads([read(), unrelated, origin], origin)).toHaveLength(3);
|
||||
});
|
||||
it("rejects reused native IDs, cross-session notices and ambiguous completion ordering", () => {
|
||||
for (const notices of [[read(), read("completed", 3), origin], [{ ...read(), sessionId: "other" }, origin], [read(), { ...read(), seq: 30 }, origin]]) {
|
||||
expect(() => withoutProvenBootstrapReads(notices, origin, { actionFile, events: [receipt()] })).toThrow();
|
||||
}
|
||||
expect(() => withoutProvenBootstrapReads([read(), origin], origin, { actionFile: "guessed-nonce.txt", events: [receipt()] })).toThrow();
|
||||
});
|
||||
it("preserves later reads and unknown native kinds for the caller's extra-operation rejection", () => {
|
||||
for (const n of [{ ...read(), seq: 21 }, { ...read(), operation: undefined }, { ...read(), operation: "edit" }]) {
|
||||
expect(withoutProvenBootstrapReads([n, origin], origin, { actionFile, events: [] })).toEqual([n, origin]);
|
||||
}
|
||||
});
|
||||
it("mirrors stable ASCII bounds and rejects invalid native identities", () => {
|
||||
expect(bootstrapReadExecutionId("read:alpha-1")).toBe("read:alpha-1");
|
||||
expect(bootstrapReadExecutionId("a".repeat(160))).toBe("a".repeat(160));
|
||||
expect(bootstrapReadExecutionId("a".repeat(161))).toBe("acpx-tool-c4b0cf58ad5787f270b446a5eb28905e09d8e0aa06e7f577e27aed951d573406");
|
||||
expect(bootstrapReadExecutionId("tool / é")).toBe("acpx-tool-c870bde596691facb0dc508859665ab3ee9de278e7d49adecaab0fa600feaff0");
|
||||
expect(bootstrapReadExecutionId("é".repeat(121))).toBe("acpx-tool-9e1e0f61749be86786959ac0384b636ca4b9e00c78e9d77161f0432871edf151");
|
||||
for (const id of ["", "a".repeat(241), "read\nnext", "[REDACTED]"]) expect(() => bootstrapReadExecutionId(id)).toThrow();
|
||||
});
|
||||
|
||||
it("accepts omitted terminal path/kind only with the retained single-path origin attestation", () => {
|
||||
const started = receipt("started", "running", 2), completed = receipt("completed", "failed", 4);
|
||||
Object.assign(completed.payload.prpEvent.payload, { target: null, operation: "unknown" });
|
||||
const notices = [read("pending", 1), read("failed", 3), origin], proof = { actionFile, events: [started, completed] };
|
||||
expect(withoutProvenBootstrapReads(notices, origin, proof)).toEqual([origin]);
|
||||
for (const digest of [undefined, `sha256:${"0".repeat(64)}`]) {
|
||||
expect(() => withoutProvenBootstrapReads([{ ...notices[0]!, readTargetSha256: digest }, ...notices.slice(1)], origin, proof)).toThrow();
|
||||
expect(() => withoutProvenBootstrapReads([notices[0]!, { ...notices[1]!, readTargetSha256: digest }, origin], origin, proof)).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["cursor"] as const)("correlates actual %s passive notices through the public reader and canonical omitted-field updates", async provider => {
|
||||
const { createCursorToolEvidence } = await import("../../packages/paperclip-runner/src/drivers/acpx/cursor-tool-evidence.js");
|
||||
const { readCursorToolEvidence } = await import("./cursor-native-evidence.js");
|
||||
const create = createCursorToolEvidence;
|
||||
for (const variant of ["exact", "wrong-path", "multi-path", "ambiguous-update"]) {
|
||||
const rows: any[] = [];
|
||||
const projector = create({ sessionId: "session", turnId: "turn", workingDirectory: "/workspace", active: () => true,
|
||||
emit: event => rows.push({ runId: "run", seq: rows.length * 2 + 1, protocolSchemaVersion: 1, eventType: event.eventType, payload: { prpEvent: {
|
||||
schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: "run", turnId: "turn", emittedAt: new Date(1).toISOString(), eventType: event.eventType, payload: event.payload,
|
||||
} } }),
|
||||
});
|
||||
const path = variant === "wrong-path" ? "private.txt" : actionFile;
|
||||
projector.tool({ type: "tool_call", tag: "tool_call", toolCallId: "bootstrap", kind: "read", status: "pending", rawInput: variant === "multi-path" ? { paths: [path, "private.txt"] } : { path }, locations: [{ path }] });
|
||||
projector.tool({ type: "tool_call", tag: "tool_call_update", toolCallId: "bootstrap", status: "failed", ...(variant === "ambiguous-update" ? { rawInput: { path, paths: [path, "private.txt"] } } : {}) });
|
||||
const evaluate = () => {
|
||||
const readNotices = readCursorToolEvidence(rows, "run");
|
||||
const started = receipt("started", "running", 2), end = receipt("completed", "failed", 4);
|
||||
Object.assign(end.payload.prpEvent.payload, { target: null, operation: "unknown" });
|
||||
return withoutProvenBootstrapReads([...readNotices, origin], origin, { actionFile, events: [...rows, started, end] });
|
||||
};
|
||||
if (variant === "exact") expect(evaluate()).toEqual([origin]); else expect(evaluate).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts bounded correlated progress for status-omitting native content updates", () => {
|
||||
const notices = [read("pending", 1), read("completed", 5), origin];
|
||||
const progressed = receipt("progressed", "running", 3); Object.assign(progressed.payload.prpEvent.payload, { target: null, operation: "unknown" });
|
||||
const events = [receipt("started", "running", 2), progressed, receipt("completed", "completed", 6)];
|
||||
expect(withoutProvenBootstrapReads(notices, origin, { actionFile, events })).toEqual([origin]);
|
||||
progressed.payload.prpEvent.payload.target = "other.txt";
|
||||
expect(() => withoutProvenBootstrapReads(notices, origin, { actionFile, events })).toThrow();
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export interface BootstrapReadNotice {
|
||||
runId: string; sessionId: string; turnId: string; toolCallId: string; seq: number;
|
||||
stage: string; operation?: string; status?: string; readTargetSha256?: string;
|
||||
}
|
||||
export interface BootstrapReadProof { actionFile: string; events: readonly unknown[] }
|
||||
const record = (value: unknown): Record<string, any> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, any> : {};
|
||||
const hashId = (domain: string, id: string) => `acpx-tool-${createHash("sha256").update(domain).update("tool\0").update(id).digest("hex")}`;
|
||||
/** These native Product fixtures require runnerd (harness-env.ts), whose
|
||||
* cli/acpx-runtime-sidecar.ts stableProviderIdentity feeds runner-core's
|
||||
* provider_events.rs acpx_opaque_item_id. Durable tool execution IDs keep that
|
||||
* hash; the separate in-process TypeScript driver's safeId replacement is not
|
||||
* this path. Mirror the sidecar byte bound followed by the Rust opaque ID. */
|
||||
export function bootstrapReadExecutionId(toolCallId: string): string {
|
||||
if (!toolCallId || toolCallId.length > 240 || /[\u0000-\u001f\u007f]/u.test(toolCallId) || toolCallId.includes("[REDACTED]")) throw new Error("Invalid bootstrap native tool identity");
|
||||
const bounded = Buffer.byteLength(toolCallId) > 240 ? hashId("paperclip.acpx.provider-identity.v1\0", toolCallId) : toolCallId;
|
||||
return /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u.test(bounded) && Buffer.byteLength(bounded) <= 160 ? bounded : hashId("paperclip.acpx.opaque-item.v1\0", bounded);
|
||||
}
|
||||
|
||||
/** Exempt only completed reads with the exact single-path native attestation on
|
||||
* every notice. Canonical PRP retains only the first location and may omit path
|
||||
* and kind on update, so it cannot establish single-file provenance by itself.
|
||||
* Validate its correlated lifecycle and reject every conflicting explicit path;
|
||||
* the passive origin attestation supplies cardinality and retained path proof.
|
||||
* No target is inferred from titles, output, or the first location alone. */
|
||||
export function withoutProvenBootstrapReads<T extends BootstrapReadNotice>(
|
||||
notices: readonly T[], origin: BootstrapReadNotice, proof?: BootstrapReadProof,
|
||||
): T[] {
|
||||
if (!proof) return [...notices];
|
||||
const expectedReadDigest = `sha256:${createHash("sha256").update(proof.actionFile).digest("hex")}`;
|
||||
const invalid = () => new Error("Native bootstrap read lacks exact complete action-file proof");
|
||||
if (notices.length > 2048 || proof.events.length > 20_000 || !/^\.paperclip-eval-action-[a-f0-9]{36}\.txt$/u.test(proof.actionFile) || !Number.isSafeInteger(origin.seq)) throw invalid();
|
||||
const candidates = notices.filter(n => n.operation === "read" && n.seq < origin.seq);
|
||||
const groups = new Map<string, T[]>();
|
||||
const nativeIds = new Map<string, string>();
|
||||
const noticeSeq = new Set<number>();
|
||||
for (const n of candidates) {
|
||||
if (n.readTargetSha256 !== expectedReadDigest || n.stage !== "tool" || n.runId !== origin.runId || n.turnId !== origin.turnId || n.sessionId !== origin.sessionId
|
||||
|| !Number.isSafeInteger(n.seq) || n.seq < 0 || noticeSeq.has(n.seq)) throw invalid();
|
||||
noticeSeq.add(n.seq);
|
||||
const executionId = bootstrapReadExecutionId(n.toolCallId);
|
||||
if (nativeIds.has(executionId) && nativeIds.get(executionId) !== n.toolCallId) throw invalid();
|
||||
nativeIds.set(executionId, n.toolCallId);
|
||||
const group = groups.get(executionId) ?? []; group.push(n); groups.set(executionId, group);
|
||||
}
|
||||
const receipts = new Map<string, Array<{ seq: number; type: string; status: string; operation: string }>>();
|
||||
const receiptSeq = new Set<number>();
|
||||
for (const value of proof.events) {
|
||||
const row = record(value), event = record(record(row.payload).prpEvent), payload = record(event.payload);
|
||||
const type = row.eventType;
|
||||
const family = typeof type === "string" && type.startsWith("tool.execution.");
|
||||
const correlated = groups.has(payload.executionId);
|
||||
// An earlier canonical read without its native origin must not disappear.
|
||||
const earlierRead = family && payload.operation === "read" && row.seq < origin.seq;
|
||||
if (!correlated && !earlierRead) continue;
|
||||
if (!family || !["tool.execution.started", "tool.execution.progressed", "tool.execution.completed"].includes(type)
|
||||
|| row.runId !== origin.runId || row.protocolSchemaVersion !== 1 || event.schema !== "paperclip.prp.event.v1"
|
||||
|| event.schemaVersion !== 1 || event.sourceKind !== "runner" || event.runId !== origin.runId || event.turnId !== origin.turnId
|
||||
|| event.eventType !== type || !Number.isFinite(Date.parse(event.emittedAt))
|
||||
|| payload.schema !== "paperclip.tool.execution.v1" || payload.transport !== "builtin" || !["read", "unknown"].includes(payload.operation)
|
||||
|| (payload.target !== null && payload.target !== proof.actionFile) || !groups.has(payload.executionId)
|
||||
|| !Number.isSafeInteger(row.seq) || row.seq < 0 || row.seq >= origin.seq || receiptSeq.has(row.seq) || noticeSeq.has(row.seq)) throw invalid();
|
||||
receiptSeq.add(row.seq);
|
||||
const group = receipts.get(payload.executionId) ?? [];
|
||||
group.push({ seq: row.seq, type, status: payload.status, operation: payload.operation }); receipts.set(payload.executionId, group);
|
||||
}
|
||||
for (const [id, native] of groups) {
|
||||
const canonical = receipts.get(id) ?? [];
|
||||
native.sort((a, b) => a.seq - b.seq); canonical.sort((a, b) => a.seq - b.seq);
|
||||
if (canonical.length < native.length || canonical.length === 0) throw invalid();
|
||||
for (let index = 0; index < native.length; index++) {
|
||||
const n = native[index]!;
|
||||
const terminal = n.status === "completed" || n.status === "failed";
|
||||
if ((!terminal && n.status !== "pending" && n.status !== "in_progress") || (terminal && index !== native.length - 1)) throw invalid();
|
||||
}
|
||||
if (!["completed", "failed"].includes(native.at(-1)!.status ?? "")) throw invalid();
|
||||
for (let index = 0; index < canonical.length; index++) {
|
||||
const c = canonical[index]!, last = index === canonical.length - 1;
|
||||
if ((index === 0 && c.operation !== "read")
|
||||
|| (last ? c.type !== "tool.execution.completed" || c.status !== native.at(-1)!.status
|
||||
: c.status !== "running" || c.type !== (index === 0 ? "tool.execution.started" : "tool.execution.progressed"))) throw invalid();
|
||||
}
|
||||
// Native shape/content updates may omit status. PRP emits a progressed row
|
||||
// while the passive observer retains its attestation without another notice.
|
||||
// Such rows remain subject to exact identity, target, order and terminal checks.
|
||||
// Any later notice for this origin means the supposed bootstrap was not
|
||||
// complete before the tested action, even if an earlier terminal existed.
|
||||
if (notices.some(n => n.toolCallId === native[0]!.toolCallId && !native.includes(n))) throw invalid();
|
||||
}
|
||||
const exempt = new Set(candidates);
|
||||
return notices.filter(n => !exempt.has(n));
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { spawn, execFileSync, type ChildProcess } from "node:child_process";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { watch, lstatSync, type FSWatcher } from "node:fs";
|
||||
import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer, type Socket } from "node:net";
|
||||
import { basename, join, relative } from "node:path";
|
||||
|
||||
export const sha256 = (value: string) => `sha256:${createHash("sha256").update(value).digest("hex")}`;
|
||||
const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
|
||||
export async function exists(path: string): Promise<boolean> {
|
||||
try { await lstat(path); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; }
|
||||
}
|
||||
/** Allocate before dispatch; ordinary workspace startup cannot mutate this parent. */
|
||||
export async function createDeniedTargetFixture(workspacePath: string, name: string) {
|
||||
if (!name || basename(name) !== name || name === "." || name === "..") throw new Error("Invalid denied target name");
|
||||
const directory = await mkdtemp(join(workspacePath, "pc-denied-"));
|
||||
const targetPath = join(directory, name);
|
||||
return { directory, targetPath, targetRelativePath: relative(workspacePath, targetPath), watcher: watchDeniedTarget(directory, name) };
|
||||
}
|
||||
|
||||
/** Substitute the one authored target, never append a contradictory second path. */
|
||||
export function bindDeniedTargetPrompt(prompt: string, original: string, target: string): string {
|
||||
const parts = prompt.split(original);
|
||||
if (parts.length !== 2) throw new Error("Denied prompt must name its exact target once");
|
||||
return parts.join(target);
|
||||
}
|
||||
|
||||
export function watchDeniedTarget(directory: string, name: string) {
|
||||
if (!name || basename(name) !== name || name === "." || name === "..") throw new Error("Invalid denied target name");
|
||||
const startedAtMs = Date.now(); let targetMutationCount = 0;
|
||||
const reasons = new Set<string>();
|
||||
const before = lstatSync(directory, { bigint: true });
|
||||
if (!before.isDirectory() || before.isSymbolicLink()) throw new Error("Denied target parent must be a real directory");
|
||||
const targetAbsent = () => { try { lstatSync(join(directory, name)); return false; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return true; throw error; } };
|
||||
if (!targetAbsent()) throw new Error("Denied target must initially be absent");
|
||||
const identity = (stat: import("node:fs").BigIntStats) => ({ dev: String(stat.dev), ino: String(stat.ino), mtimeNs: String(stat.mtimeNs), ctimeNs: String(stat.ctimeNs) });
|
||||
const events: Array<{ sequence: number; observedAtMs: number; kind: string; target: boolean; filenameKnown: boolean }> = [];
|
||||
let eventCount = 0, lastEventAtMs = startedAtMs, closing = false;
|
||||
let final: { startedAtMs: number; endedAtMs: number; complete: boolean; targetMutationCount: number; reasons: string[]; initialParent: ReturnType<typeof identity>; finalParent: ReturnType<typeof identity> | null; events: typeof events } | undefined;
|
||||
const watcher: FSWatcher = watch(directory, (kind, filename) => {
|
||||
const observedAtMs = Date.now();
|
||||
if (observedAtMs < lastEventAtMs) reasons.add("event-order-invalid");
|
||||
lastEventAtMs = observedAtMs;
|
||||
const target = filename !== null && String(filename) === name;
|
||||
if (filename === null) reasons.add("event-filename-missing");
|
||||
if (target) targetMutationCount++;
|
||||
if (++eventCount <= 128) events.push({ sequence: eventCount, observedAtMs, kind, target, filenameKnown: filename !== null });
|
||||
else reasons.add("event-journal-overflow");
|
||||
});
|
||||
watcher.on("error", () => { reasons.add("watch-error"); });
|
||||
watcher.on("close", () => { if (!closing) reasons.add("watch-closed-before-finish"); });
|
||||
// Pin both identity and directory version across watcher installation.
|
||||
try {
|
||||
const armed = lstatSync(directory, { bigint: true });
|
||||
if (!armed.isDirectory() || armed.dev !== before.dev || armed.ino !== before.ino) reasons.add("parent-identity-changed-during-arm");
|
||||
if (armed.mtimeNs !== before.mtimeNs || armed.ctimeNs !== before.ctimeNs || !targetAbsent()) reasons.add("coverage-gap-during-arm");
|
||||
} catch { reasons.add("parent-unavailable-during-arm"); }
|
||||
return { finish() {
|
||||
if (final) return final;
|
||||
let after: import("node:fs").BigIntStats | undefined;
|
||||
try { after = lstatSync(directory, { bigint: true }); } catch { reasons.add("parent-unavailable-at-finish"); }
|
||||
// FSEvents may coalesce a rapid create/delete. A changed directory version
|
||||
// with no attributed event is a coverage gap, never proof of no mutation.
|
||||
if (after && (after.dev !== before.dev || after.ino !== before.ino || !after.isDirectory())) reasons.add("parent-identity-changed");
|
||||
if (after && (after.mtimeNs !== before.mtimeNs || after.ctimeNs !== before.ctimeNs) && targetMutationCount === 0) reasons.add("coverage-gap-parent-version-changed");
|
||||
try { if (!targetAbsent() && targetMutationCount === 0) reasons.add("coverage-gap-unobserved-target"); } catch { reasons.add("target-unavailable-at-finish"); }
|
||||
const endedAtMs = Date.now();
|
||||
if (endedAtMs < lastEventAtMs) reasons.add("event-order-invalid");
|
||||
final = { startedAtMs, endedAtMs, complete: reasons.size === 0, targetMutationCount, reasons: [...reasons], initialParent: identity(before), finalParent: after ? identity(after) : null, events };
|
||||
closing = true; watcher.close(); return final;
|
||||
} };
|
||||
}
|
||||
interface ProcessIdentity { pid: number; parent: number; start: string }
|
||||
function processTable(): ProcessIdentity[] {
|
||||
const output = execFileSync("/bin/ps", ["-axo", "pid=,ppid=,lstart="], { encoding: "utf8", timeout: 3000, maxBuffer: 8 * 1024 * 1024, env: { PATH: "/usr/bin:/bin", LC_ALL: "C" } });
|
||||
return output.split("\n").flatMap(line => { const m = /^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/u.exec(line); return m ? [{ pid: Number(m[1]), parent: Number(m[2]), start: m[3]! }] : []; });
|
||||
}
|
||||
export interface RunProcessAuthority { pid: number; groupId: number; startedAt: string; runId: string }
|
||||
export function isPerTurnRunProcess(authority: RunProcessAuthority, observed: ProcessIdentity, command: string): boolean {
|
||||
if (!/^[a-zA-Z0-9_-]{1,128}$/u.test(authority.runId) || authority.pid !== observed.pid || authority.groupId !== observed.pid) return false;
|
||||
const started = Date.parse(authority.startedAt), actual = Date.parse(observed.start);
|
||||
if (!Number.isFinite(started) || !Number.isFinite(actual) || Math.floor(started / 1000) !== Math.floor(actual / 1000)) return false;
|
||||
const args = command.trim().split(/\s+/u);
|
||||
return [["--run-id", authority.runId], ["--lifecycle-mode", "per_turn"]].every(([flag, value]) => {
|
||||
const at = args.indexOf(flag!); return at >= 0 && args.lastIndexOf(flag!) === at && args[at + 1] === value;
|
||||
});
|
||||
}
|
||||
/** Read-only PID/start journal; never signal an API-reported or reused PID.
|
||||
* Native onSpawn publishes the runnerd child. Bind its current argv to this run
|
||||
* and per_turn lifecycle before treating its retirement as run cleanup.
|
||||
*/
|
||||
export function observeRunProcesses() {
|
||||
const owned = new Map<number, ProcessIdentity>(); let root: ProcessIdentity | undefined;
|
||||
return {
|
||||
sample(authority?: RunProcessAuthority) {
|
||||
const table = processTable();
|
||||
if (!root && authority && authority.pid > 1 && authority.pid !== process.pid) {
|
||||
const candidate = table.find(p => p.pid === authority.pid);
|
||||
if (candidate) {
|
||||
let command: string;
|
||||
try { command = execFileSync("/bin/ps", ["-p", String(candidate.pid), "-o", "command="], { encoding: "utf8", timeout: 3000, maxBuffer: 64 * 1024 }); }
|
||||
catch { command = ""; } // A vanished/uninspectable PID supplies no authority.
|
||||
if (isPerTurnRunProcess(authority, candidate, command) && processTable().some(p => p.pid === candidate.pid && p.start === candidate.start)) { root = candidate; owned.set(root.pid, root); }
|
||||
}
|
||||
}
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const p of table) if (!owned.has(p.pid)) {
|
||||
const parent = owned.get(p.parent);
|
||||
if (parent && table.some(t => t.pid === parent.pid && t.start === parent.start)) { owned.set(p.pid, p); changed = true; }
|
||||
}
|
||||
}
|
||||
return { captured: Boolean(root), journal: [...owned.values()], live: table.filter(p => owned.get(p.pid)?.start === p.start).map(p => p.pid) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A one-shot local fixture, not a command service: input selects no executable,
|
||||
* arguments or file path. The test owns/reaps the fixed finite child, records its
|
||||
* OS exit status, and holds the exact provider-launched client until that exit.
|
||||
*/
|
||||
export async function createAttachedCommandFixture(markerPath: string, delayMs = 4000) {
|
||||
if (!Number.isInteger(delayMs) || delayMs < 100 || delayMs > 8000) throw new Error("Invalid bounded fixture delay");
|
||||
const root = await mkdtemp("/tmp/pc-copilot-"); await mkdir(join(root, "private"), { mode: 0o700 });
|
||||
const socketPath = join(root, "private", "socket"), scriptPath = join(root, "client.cjs");
|
||||
const nonce = randomBytes(16).toString("hex"), marker = `${randomBytes(24).toString("hex")}\n`;
|
||||
const script = `const net=require('node:net');const s=net.connect(process.argv[2]);let b='';s.setTimeout(15000,()=>process.exit(3));s.on('error',()=>process.exit(4));s.on('connect',()=>s.write(JSON.stringify({nonce:process.argv[3],pid:process.pid})+'\\n'));s.on('data',x=>{b+=x;if(b.includes('\\n')){const r=JSON.parse(b);s.end();process.exit(r.code===0?0:5);}});`;
|
||||
await writeFile(scriptPath, script, { mode: 0o400 });
|
||||
const command = `${quote(process.execPath)} ${quote(scriptPath)} ${quote(socketPath)} ${quote(nonce)}`;
|
||||
const commandSha256 = sha256(command);
|
||||
let markerWrittenAtMs: number | null = null;
|
||||
let clientExitedAtMs: number | null = null;
|
||||
let clientObservation: ReturnType<typeof setInterval> | undefined;
|
||||
let connections = 0, child: ChildProcess | undefined, client: ProcessIdentity | undefined, failure: string | null = null;
|
||||
let exit: { observedAtMs: number; code: number; ownedProcessIdentityVerified: boolean; commandSha256: string } | null = null;
|
||||
const sockets = new Set<Socket>();
|
||||
let closed = false;
|
||||
const server = createServer(socket => {
|
||||
sockets.add(socket); socket.on("close", () => sockets.delete(socket)); socket.on("error", () => { failure = "fixture_socket_error"; });
|
||||
let buffer = "";
|
||||
socket.on("data", data => {
|
||||
buffer += data; if (buffer.length > 1024) { failure = "fixture_request_too_large"; socket.destroy(); return; }
|
||||
if (!buffer.includes("\n")) return;
|
||||
connections++;
|
||||
try {
|
||||
const request = JSON.parse(buffer); buffer = "";
|
||||
if (connections !== 1 || request.nonce !== nonce || !Number.isSafeInteger(request.pid) || request.pid <= 1) throw new Error("fixture_request_invalid");
|
||||
const observed = processTable().find(p => p.pid === request.pid);
|
||||
const argv = execFileSync("/bin/ps", ["-p", String(request.pid), "-o", "command="], { encoding: "utf8", timeout: 3000 });
|
||||
if (!observed || !argv.includes(scriptPath) || !argv.includes(socketPath) || !argv.includes(nonce)) throw new Error("fixture_client_identity_invalid");
|
||||
client = observed;
|
||||
clientObservation = setInterval(() => {
|
||||
try {
|
||||
if (!processTable().some(p => p.pid === client!.pid && p.start === client!.start)) {
|
||||
clientExitedAtMs = Date.now(); clearInterval(clientObservation);
|
||||
}
|
||||
} catch { failure = "fixture_client_observation_failed"; clearInterval(clientObservation); }
|
||||
}, 25);
|
||||
child = spawn(process.execPath, ["-e", `setTimeout(()=>process.exit(0),${delayMs})`], { env: { PATH: "/usr/bin:/bin" }, stdio: "ignore" });
|
||||
child.once("error", () => { failure = "fixture_child_start_failed"; socket.destroy(); });
|
||||
child.once("exit", (code, signal) => {
|
||||
exit = { observedAtMs: Date.now(), code: code ?? -1, ownedProcessIdentityVerified: Number.isInteger(child?.pid), commandSha256 };
|
||||
void (async () => {
|
||||
if (code !== 0 || signal) { failure = "fixture_child_failed"; socket.destroy(); return; }
|
||||
if (await readFile(scriptPath, "utf8") !== script) { failure = "fixture_script_changed"; socket.destroy(); return; }
|
||||
await writeFile(markerPath, marker, { flag: "wx" }); markerWrittenAtMs = Date.now(); socket.end(`${JSON.stringify({ code })}\n`);
|
||||
})().catch(() => { failure = "fixture_completion_failed"; socket.destroy(); });
|
||||
});
|
||||
} catch { failure = "fixture_request_rejected"; socket.destroy(); }
|
||||
});
|
||||
});
|
||||
try { await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(socketPath, resolve); }); }
|
||||
catch (error) { server.close(); await rm(root, { recursive: true, force: true }); throw error; }
|
||||
return {
|
||||
command, commandSha256, marker,
|
||||
snapshot() { const table = processTable(); return { connections, failure, markerWrittenAtMs, clientExitedAtMs, commandExit: exit, childPid: child?.pid ?? null, clientPid: client?.pid ?? null, clientGone: Boolean(client) && !table.some(p => p.pid === client!.pid && p.start === client!.start), childGone: Boolean(exit), observedAtMs: Date.now() }; },
|
||||
async close() {
|
||||
if (closed) return; closed = true; clearInterval(clientObservation);
|
||||
let cleanupError: unknown;
|
||||
try {
|
||||
if (child && child.exitCode === null && child.signalCode === null) {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const hard = setTimeout(() => { child!.kill("SIGKILL"); }, 3000);
|
||||
const deadline = setTimeout(() => reject(new Error("Fixture child did not settle within cleanup bound")), 5000);
|
||||
child!.once("exit", () => { clearTimeout(hard); clearTimeout(deadline); resolve(); }); child!.kill("SIGTERM");
|
||||
});
|
||||
}
|
||||
} catch (error) { cleanupError = error; }
|
||||
finally {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
try { await new Promise<void>(resolve => server.close(() => resolve())); }
|
||||
finally { await rm(root, { recursive: true, force: true }); }
|
||||
}
|
||||
if (cleanupError) throw cleanupError;
|
||||
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
export interface NativeRemoteBinding {
|
||||
companyId: string; environmentId: string; runId: string; leaseId: string; sandboxId: string; image: string; remoteCwd: string;
|
||||
}
|
||||
export interface NativeRemoteSnapshot {
|
||||
binding: NativeRemoteBinding; observedAtMs: number; receivedAtMs: number; observedMonotonicNs: string; complete: boolean;
|
||||
workspace: Record<string, string>;
|
||||
targets: Record<string, { absent: boolean; sha256: string | null; parent: { dev: string; ino: string }; mutationCount: number; complete: boolean }>;
|
||||
watcher: { complete: boolean; targetMutationCount: number; workspaceMutationCount: number };
|
||||
processes: { captured: boolean; root: { pid: number; startTicks: string; bootId: string } | null; journal: Array<{ pid: number; ppid: number; startTicks: string; bootId: string }>; live: number[] };
|
||||
setup: { path: string; sha256: string | null; published: boolean };
|
||||
attached: { connections: number; failure: string | null; commandExit: { code: number; observedAtMs: number; observedMonotonicNs: string } | null;
|
||||
markerWrittenAtMs: number | null; markerWrittenMonotonicNs: string | null; clientExitedAtMs: number | null; clientExitedMonotonicNs: string | null } | null;
|
||||
}
|
||||
export interface NativeRemoteFixture {
|
||||
binding: NativeRemoteBinding; remoteCwd: string; actionFile: string;
|
||||
snapshot(label: string): Promise<NativeRemoteSnapshot>;
|
||||
setupAttachedCommand(input: { marker: string; markerText: string; delayMs: number }): Promise<{ command: string; commandSha256: string }>;
|
||||
finish(): Promise<NativeRemoteSnapshot>; readFile(relative: string): Promise<Buffer>; close(): Promise<void>;
|
||||
}
|
||||
export interface NativeRemoteBootstrap {
|
||||
prompt(nonce: string): string;
|
||||
bindAndRelease(input: { issueId: string; runId: string; targets: readonly string[];
|
||||
actionPrompt(fixture: NativeRemoteFixture): Promise<string> | string }): Promise<NativeRemoteFixture>;
|
||||
}
|
||||
export function assertNativeRemoteSnapshot(s: NativeRemoteSnapshot, binding: NativeRemoteBinding): void {
|
||||
const keys: Array<keyof NativeRemoteBinding> = ["companyId", "environmentId", "runId", "leaseId", "sandboxId", "image", "remoteCwd"];
|
||||
if (!s.complete || !s.watcher.complete || !keys.every(k => typeof binding[k] === "string" && binding[k].length > 0 && s.binding[k] === binding[k])
|
||||
|| !/^.+@sha256:[a-f0-9]{64}$/u.test(binding.image) || !binding.remoteCwd.startsWith("/") || binding.remoteCwd.split("/").some(p => p === ".." || p === ".")
|
||||
|| !Number.isSafeInteger(s.observedAtMs) || s.observedAtMs < 0 || !Number.isSafeInteger(s.receivedAtMs) || !/^\d+$/u.test(s.observedMonotonicNs)
|
||||
|| ![s.watcher.targetMutationCount, s.watcher.workspaceMutationCount].every(n => Number.isSafeInteger(n) && n >= 0)) throw new Error("Incomplete Native remote lease/watch receipt");
|
||||
}
|
||||
export function assertNativeRemoteRetirement(s: NativeRemoteSnapshot, baseline: NativeRemoteSnapshot): void {
|
||||
assertNativeRemoteSnapshot(s, baseline.binding);
|
||||
const root = s.processes.root, original = baseline.processes.root;
|
||||
if (!root || !original || !baseline.processes.captured || !s.processes.captured || s.processes.live.length !== 0
|
||||
|| root.pid !== original.pid || root.startTicks !== original.startTicks || root.bootId !== original.bootId
|
||||
|| !Number.isSafeInteger(root.pid) || root.pid < 2 || !/^\d+$/u.test(root.startTicks) || !/^[a-f0-9-]{36}$/iu.test(root.bootId)
|
||||
|| !s.processes.journal.some(p => p.pid === root.pid && p.startTicks === root.startTicks && p.bootId === root.bootId)
|
||||
|| !s.processes.journal.every(p => p.bootId === root.bootId && /^\d+$/u.test(p.startTicks) && Number.isSafeInteger(p.pid) && p.pid > 1)
|
||||
|| !s.setup.published || s.setup.path !== baseline.setup.path || !/^sha256:[a-f0-9]{64}$/u.test(s.setup.sha256 ?? "")
|
||||
|| BigInt(s.observedMonotonicNs) < BigInt(baseline.observedMonotonicNs)) throw new Error("Native remote retirement is unproven");
|
||||
}
|
||||
export function nativeRemoteDeniedSample(s: NativeRemoteSnapshot, baseline: NativeRemoteSnapshot, target: string, phase: "before-request" | "pending" | "after-decision" | "terminal" | "after-cleanup") {
|
||||
assertNativeRemoteSnapshot(s, baseline.binding);
|
||||
const t = s.targets[target], before = baseline.targets[target];
|
||||
if (!t?.complete || !before?.complete || !/^\d+$/u.test(t.parent.dev) || !/^\d+$/u.test(t.parent.ino)
|
||||
|| t.parent.dev !== before.parent.dev || t.parent.ino !== before.parent.ino || t.mutationCount !== 0
|
||||
|| s.watcher.targetMutationCount !== 0 || s.watcher.workspaceMutationCount !== baseline.watcher.workspaceMutationCount
|
||||
|| JSON.stringify(Object.entries(s.workspace).sort()) !== JSON.stringify(Object.entries(baseline.workspace).sort())) throw new Error("Native remote denied target changed or observation was incomplete");
|
||||
return { phase, observedAtMs: s.observedAtMs, exists: t.absent !== true || t.sha256 !== null };
|
||||
}
|
||||
/** Await baseline and exact command construction before the bootstrap can publish. */
|
||||
export async function prepareNativeRemoteAction(input: {
|
||||
fixture: NativeRemoteFixture; companyId: string; environmentId: string; runId: string;
|
||||
target: string; prompt: string; markerText?: string;
|
||||
}) {
|
||||
const f = input.fixture;
|
||||
if (f.binding.companyId !== input.companyId || f.binding.environmentId !== input.environmentId || f.binding.runId !== input.runId || f.remoteCwd !== f.binding.remoteCwd) throw new Error("Foreign Native remote bootstrap binding");
|
||||
const command = input.markerText === undefined ? undefined : await f.setupAttachedCommand({ marker: input.target, markerText: input.markerText, delayMs: 4000 });
|
||||
const baseline = await f.snapshot("before-action-publication"); assertNativeRemoteSnapshot(baseline, f.binding);
|
||||
if (baseline.setup.published || baseline.setup.path !== f.actionFile || !baseline.processes.captured || baseline.processes.live.length === 0) throw new Error("Native action was not held behind the remote observer");
|
||||
const target = baseline.targets[input.target];
|
||||
if (!target?.complete || !target.absent || target.sha256 !== null || target.mutationCount !== 0) throw new Error("Native remote target was present or unobserved before action");
|
||||
return { baseline, command, prompt: `${input.prompt}\nThe admitted remote workspace is ${f.remoteCwd}.${command ? `\nThe exact supplied command is:\n${command.command}\nDo not inspect or modify fixture code, fabricate its marker, or launch a substitute command.` : ""}` };
|
||||
}
|
||||
|
||||
@@ -12,6 +12,18 @@ export const UNQUALIFIED_PROFILE_GAPS = {
|
||||
pi: "Pi has no qualified model source, so no valid Product E2E profile is registered.",
|
||||
} as const;
|
||||
|
||||
/** Reject missing remote observer authority before creating a company or run. */
|
||||
export function assertRemoteNativeEvidencePrerequisites(
|
||||
executions: readonly MatrixExecution[],
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): void {
|
||||
if (!executions.some(execution => execution.environment.id === "daytona"
|
||||
&& ["cursor_native", "native_active_stop"].includes(execution.task.flow))) return;
|
||||
const names = ["PAPERCLIP_E2E_DAYTONA_NODE_SHA256", "PAPERCLIP_E2E_DAYTONA_RUNNERD_SHA256"];
|
||||
const invalid = names.filter(name => !/^sha256:[a-f0-9]{64}$/u.test(environment[name] ?? ""));
|
||||
if (invalid.length) throw new Error(`Native Daytona evidence requires exact image executable digests: ${invalid.join(", ")}`);
|
||||
}
|
||||
|
||||
export function assertRunnerE2EPrerequisites(
|
||||
executions: readonly MatrixExecution[],
|
||||
): void {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { expect, it } from "vitest";
|
||||
import { createProcessTreeOwner } from "./process-tree-owner.js";
|
||||
import { readProcessTable, type ProcessObservation } from "./process-tree.js";
|
||||
|
||||
function row(pid: number, parentPid: number, processGroupId: number, started = `start-${pid}`, state = "S"): ProcessObservation {
|
||||
return { pid, parentPid, processGroupId, started, state, kind: "node" };
|
||||
}
|
||||
function fixture(initial: ProcessObservation[]) {
|
||||
let table = [row(process.pid, 1, 10), ...initial];
|
||||
const root = { pid: 100, exitCode: null as number | null, signalCode: null as NodeJS.Signals | null };
|
||||
const signals: Array<[number, NodeJS.Signals]> = [];
|
||||
const owner = createProcessTreeOwner(root as ChildProcess, {
|
||||
readTable: async () => table,
|
||||
signalGroup: (pid, signal) => { signals.push([pid, signal]); },
|
||||
});
|
||||
return { root, owner, signals, replace: (rows: ProcessObservation[]) => { table = [row(process.pid, 1, 10), ...rows]; } };
|
||||
}
|
||||
|
||||
it.skipIf(process.platform === "win32")("revalidates PID/start before signaling and refuses a recycled group", async () => {
|
||||
const f = fixture([row(100, process.pid, 100), row(200, 100, 200)]);
|
||||
try {
|
||||
await f.owner.observe();
|
||||
f.replace([row(100, process.pid, 100), row(200, 1, 200, "new-start")]);
|
||||
await expect(f.owner.signal("SIGKILL")).rejects.toThrow("identity became uncertain");
|
||||
expect(f.signals).toEqual([]);
|
||||
} finally { f.owner.stopObserving(); }
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("retains observed descendants when the root exits and excludes the caller group", async () => {
|
||||
const f = fixture([row(100, process.pid, 100), row(200, 100, 200), row(300, 100, 10), row(999, process.pid, 999)]);
|
||||
try {
|
||||
await f.owner.observe();
|
||||
f.root.exitCode = 1;
|
||||
f.replace([row(200, 1, 200), row(300, 1, 10), row(999, process.pid, 999)]);
|
||||
await f.owner.signal("SIGTERM");
|
||||
expect(f.signals).toEqual([[200, "SIGTERM"]]);
|
||||
} finally { f.owner.stopObserving(); }
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("treats an unreaped zombie as stopped without signaling a replacement", async () => {
|
||||
const f = fixture([row(100, process.pid, 100), row(200, 100, 200)]);
|
||||
try {
|
||||
await f.owner.observe();
|
||||
f.root.exitCode = 1;
|
||||
f.replace([row(200, 1, 200, "start-200", "Z")]);
|
||||
await f.owner.signal("SIGKILL");
|
||||
expect(f.owner.liveGroups()).toEqual([]);
|
||||
expect(f.signals).toEqual([]);
|
||||
} finally { f.owner.stopObserving(); }
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("sends launcher grace only to the root while retaining nested groups for escalation", async () => {
|
||||
const f = fixture([row(100, process.pid, 100), row(200, 100, 200), row(300, 200, 300)]);
|
||||
try {
|
||||
await f.owner.observe();
|
||||
await f.owner.signal("SIGTERM", f.owner.gracefulRoots());
|
||||
expect(f.signals).toEqual([[100, "SIGTERM"]]);
|
||||
f.root.exitCode = 1;
|
||||
f.replace([row(200, 1, 200), row(300, 200, 300)]);
|
||||
await f.owner.observe();
|
||||
expect([...f.owner.gracefulRoots()]).toEqual([200]);
|
||||
await f.owner.signal("SIGKILL");
|
||||
expect(f.signals.slice(1).map(([pid]) => pid).sort()).toEqual([200, 300]);
|
||||
} finally { f.owner.stopObserving(); }
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === 'win32')('reselects a vanished owner only when no graceful signal was delivered', async () => {
|
||||
let table = [row(process.pid, 1, 10), row(100, process.pid, 100), row(200, 100, 200)];
|
||||
const child = { pid: 100, exitCode: null as number | null, signalCode: null };
|
||||
const delivered: number[] = [];
|
||||
let reads = 0;
|
||||
let stopping = false;
|
||||
const owner = createProcessTreeOwner(child as ChildProcess, {
|
||||
readTable: async () => {
|
||||
if (stopping && ++reads === 2) { child.exitCode = 0; table = [row(process.pid, 1, 10), row(200, 1, 200)]; }
|
||||
return table;
|
||||
},
|
||||
signalGroup: (pid, signal) => {
|
||||
expect(signal).toBe('SIGTERM');
|
||||
if (pid === 100) {
|
||||
child.exitCode = 0; table = [row(process.pid, 1, 10), row(200, 1, 200)];
|
||||
throw Object.assign(new Error('vanished'), { code: 'ESRCH' });
|
||||
}
|
||||
delivered.push(pid); table = [row(process.pid, 1, 10)];
|
||||
},
|
||||
});
|
||||
try {
|
||||
await owner.observe(); stopping = true;
|
||||
const { stopOwnedProcessTree } = await import('./process-tree-owner.js');
|
||||
await stopOwnedProcessTree(child as ChildProcess, owner, 150, 100);
|
||||
expect(delivered).toEqual([200]);
|
||||
} finally { owner.stopObserving(); }
|
||||
});
|
||||
|
||||
|
||||
it.skipIf(process.platform === "win32")("rejects an overflowing inspector instead of returning a partial identity table", async () => {
|
||||
const inspector = spawn(process.execPath, ["-e", "process.stdout.write('x'.repeat(2 * 1024 * 1024)); setInterval(() => {}, 1000)"], {
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
});
|
||||
const exited = new Promise<void>(resolve => inspector.once("exit", () => resolve()));
|
||||
try {
|
||||
expect(await readProcessTable(() => inspector)).toBeNull();
|
||||
await exited;
|
||||
expect(inspector.signalCode).toBe("SIGKILL");
|
||||
} finally { if (inspector.exitCode === null && inspector.signalCode === null) inspector.kill("SIGKILL"); }
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === 'win32')('bounds fallback even when the known direct child cannot be killed', async () => {
|
||||
const signals: NodeJS.Signals[] = [];
|
||||
const child = { pid: 100, exitCode: null, signalCode: null,
|
||||
kill: (signal: NodeJS.Signals) => { signals.push(signal); return false; } } as ChildProcess;
|
||||
const owner = createProcessTreeOwner(child, { readTable: async () => null,
|
||||
signalGroup: () => { throw new Error('must not signal an unobserved group'); } });
|
||||
try {
|
||||
const { stopOwnedProcessTree } = await import('./process-tree-owner.js');
|
||||
await expect(stopOwnedProcessTree(child, owner, 10, 10)).rejects.toThrow('Known direct child remained');
|
||||
expect(signals).toEqual(['SIGTERM', 'SIGKILL']);
|
||||
} finally { owner.stopObserving(); }
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import {
|
||||
observeDescendantProcessTree, readProcessTable, revalidateObservedProcessGroups,
|
||||
refreshContinuouslyLiveProcessGroups, safeProcessGroupTerminationOrder,
|
||||
type ObservedProcessGroup, type ProcessObservation,
|
||||
} from "./process-tree.js";
|
||||
|
||||
export function createProcessTreeOwner(root: ChildProcess, options: {
|
||||
readTable?: () => Promise<ProcessObservation[] | null>;
|
||||
signalGroup?: (pid: number, signal: NodeJS.Signals) => void;
|
||||
} = {}) {
|
||||
let groups: ObservedProcessGroup[] = [];
|
||||
let table: ProcessObservation[] = [];
|
||||
let rootStarted: string | undefined;
|
||||
let observing: Promise<void> | undefined;
|
||||
const covered = new Set<number>();
|
||||
const readTable = options.readTable ?? readProcessTable;
|
||||
const signalGroup = options.signalGroup ?? ((pid, signal) => process.kill(-pid, signal));
|
||||
const exited = () => root.exitCode !== null || root.signalCode !== null || !root.pid;
|
||||
const running = (candidate: ProcessObservation) => !candidate.state?.startsWith("Z");
|
||||
|
||||
function observe(): Promise<void> {
|
||||
if (process.platform === "win32") return Promise.resolve();
|
||||
if (observing) return observing;
|
||||
observing = (async () => {
|
||||
const next = await readTable();
|
||||
if (!next) throw new Error("Could not inspect owned process identities");
|
||||
const callerGroup = next.find(row => row.pid === process.pid)?.processGroupId;
|
||||
if (callerGroup === undefined) throw new Error("Cleanup caller group identity is unavailable");
|
||||
const rootRow = next.find(row => row.pid === root.pid);
|
||||
if (!rootStarted && !exited()) rootStarted = rootRow?.started;
|
||||
const retained = revalidateObservedProcessGroups(groups, next);
|
||||
// Never acquire a recycled group from its numeric ID alone.
|
||||
const lost = groups.filter(group => !retained.includes(group) && next.some(row => row.processGroupId === group.processGroupId && running(row)));
|
||||
if (lost.length) throw new Error("Owned process group identity became uncertain");
|
||||
const refreshed = refreshContinuouslyLiveProcessGroups(retained, next)
|
||||
.filter(group => group.processGroupId !== callerGroup);
|
||||
const anchors = refreshed.flatMap(group => group.members.map(member => member.pid));
|
||||
if (rootRow && rootStarted === rootRow.started) anchors.push(rootRow.pid);
|
||||
const byGroup = new Map(refreshed.map(group => [group.processGroupId, group]));
|
||||
for (const pid of anchors) {
|
||||
for (const group of observeDescendantProcessTree(next, pid).groups) {
|
||||
if (group.processGroupId !== callerGroup) {
|
||||
byGroup.set(group.processGroupId, group);
|
||||
if (covered.has(next.find(row => row.pid === pid)!.processGroupId)) covered.add(group.processGroupId);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups = [...byGroup.values()];
|
||||
table = next;
|
||||
})().finally(() => { observing = undefined; });
|
||||
return observing;
|
||||
}
|
||||
const timer = process.platform === "win32" ? undefined : setInterval(() => {
|
||||
void observe().catch(() => { /* Stop must obtain a fresh successful inspection. */ });
|
||||
}, 250);
|
||||
timer?.unref();
|
||||
void observe().catch(() => {});
|
||||
|
||||
function liveGroups() {
|
||||
return groups.filter(group => table.some(row => row.processGroupId === group.processGroupId && running(row)));
|
||||
}
|
||||
function signalSnapshot(signal: NodeJS.Signals, selected?: ReadonlySet<number>) {
|
||||
const currentProcessGroupId = table.find(row => row.pid === process.pid)?.processGroupId ?? null;
|
||||
if (currentProcessGroupId === null) throw new Error("Cleanup caller group identity is unavailable");
|
||||
const live = liveGroups();
|
||||
const ordered = safeProcessGroupTerminationOrder({ rootProcessGroupId: root.pid ?? -1, currentProcessGroupId, groups: live });
|
||||
const signaled: number[] = [];
|
||||
for (const pid of ordered) {
|
||||
if (selected && !selected.has(pid)) continue;
|
||||
try { signalGroup(pid, signal); }
|
||||
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; else continue; }
|
||||
signaled.push(pid);
|
||||
}
|
||||
return signaled;
|
||||
}
|
||||
async function signal(signal: NodeJS.Signals, selected?: ReadonlySet<number>) {
|
||||
await observe();
|
||||
return signalSnapshot(signal, selected);
|
||||
}
|
||||
function gracefulRoots() {
|
||||
const live = liveGroups();
|
||||
const ids = new Set(live.map(group => group.processGroupId));
|
||||
if (root.pid && ids.has(root.pid)) return new Set([root.pid]);
|
||||
// After the launcher's leader exits, request shutdown only from the
|
||||
// outermost remaining owners; their wrappers still own child signaling.
|
||||
const byPid = new Map(table.map(row => [row.pid, row]));
|
||||
return new Set(live.filter(group => !table.some(row => {
|
||||
if (row.processGroupId !== group.processGroupId) return false;
|
||||
const seen = new Set<number>();
|
||||
let parent = byPid.get(row.parentPid);
|
||||
while (parent && !seen.has(parent.pid)) {
|
||||
seen.add(parent.pid);
|
||||
if (parent.processGroupId !== group.processGroupId && ids.has(parent.processGroupId)) return true;
|
||||
parent = byPid.get(parent.parentPid);
|
||||
}
|
||||
return false;
|
||||
})).map(group => group.processGroupId));
|
||||
}
|
||||
let graceComplete = false;
|
||||
let directGraceDelivered = false;
|
||||
async function signalGracefully() {
|
||||
if (graceComplete) return;
|
||||
await observe();
|
||||
// Choose and deliver from one validated table. ESRCH grants no ownership
|
||||
// coverage: the next grace poll can select that branch's surviving owner.
|
||||
const selected = new Set([...gracefulRoots()].filter(pid => !covered.has(pid)));
|
||||
const delivered = signalSnapshot("SIGTERM", selected);
|
||||
for (const pid of delivered) {
|
||||
if (pid === root.pid) directGraceDelivered = true;
|
||||
covered.add(pid);
|
||||
for (const member of table.filter(row => row.processGroupId === pid)) {
|
||||
for (const group of observeDescendantProcessTree(table, member.pid).groups) covered.add(group.processGroupId);
|
||||
}
|
||||
}
|
||||
// Never reselect descendants after their owner received grace, even if it
|
||||
// exits before their asynchronous close completes.
|
||||
graceComplete = selected.size > 0 && delivered.length === selected.size;
|
||||
}
|
||||
return { observe, signal, liveGroups, gracefulRoots, signalGracefully,
|
||||
directGraceDelivered: () => directGraceDelivered, stopObserving: () => { if (timer) clearInterval(timer); } };
|
||||
}
|
||||
|
||||
|
||||
/** Inspection failure grants no group authority. The unreaped ChildProcess
|
||||
* handle still owns its direct child, so retire only that child within the
|
||||
* original grace deadline, then report the incomplete tree audit. */
|
||||
export async function stopKnownDirectChild(child: ChildProcess, phase: { gracefulSent: boolean; forcedDeadline?: number },
|
||||
deadline: number, forcedMs: number, signal: NodeJS.Signals = "SIGTERM") {
|
||||
const exited = () => child.exitCode !== null || child.signalCode !== null || !child.pid;
|
||||
const wait = () => new Promise(resolve => setTimeout(resolve, 25));
|
||||
if (!exited() && !phase.gracefulSent) {
|
||||
phase.gracefulSent = child.kill(signal);
|
||||
}
|
||||
while (!exited() && Date.now() < deadline) await wait();
|
||||
if (exited()) return;
|
||||
child.kill("SIGKILL");
|
||||
phase.forcedDeadline ??= Date.now() + forcedMs;
|
||||
while (!exited() && Date.now() < phase.forcedDeadline) await wait();
|
||||
if (!exited()) throw new Error("Known direct child remained after bounded fallback");
|
||||
}
|
||||
|
||||
export async function incompleteTreeFallback(error: unknown, child: ChildProcess,
|
||||
phase: { gracefulSent: boolean; forcedDeadline?: number }, deadline: number, forcedMs: number) {
|
||||
let fallbackError: unknown;
|
||||
try { await stopKnownDirectChild(child, phase, deadline, forcedMs); }
|
||||
catch (failure) { fallbackError = failure; }
|
||||
throw new Error(`Owned tree cleanup incomplete: ${String(error)}${fallbackError ? `; ${String(fallbackError)}` : ""}`);
|
||||
}
|
||||
|
||||
/** Give the launcher/wrapper chain sole graceful-signal ownership, then retire
|
||||
* only still-observed descendants. Used on normal exit as well as cancellation. */
|
||||
export async function stopOwnedProcessTree(
|
||||
child: ChildProcess,
|
||||
owner: ReturnType<typeof createProcessTreeOwner>,
|
||||
gracefulMs = 45_000,
|
||||
forcedMs = 5_000,
|
||||
): Promise<void> {
|
||||
const wait = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const deadline = Date.now() + gracefulMs;
|
||||
const phase: { gracefulSent: boolean; forcedDeadline?: number } = { gracefulSent: false };
|
||||
try {
|
||||
if (process.platform === "win32") {
|
||||
await stopKnownDirectChild(child, phase, deadline, forcedMs);
|
||||
return;
|
||||
}
|
||||
const stopped = async () => {
|
||||
await owner.observe();
|
||||
return (child.exitCode !== null || child.signalCode !== null) && owner.liveGroups().length === 0;
|
||||
};
|
||||
do {
|
||||
await owner.signalGracefully();
|
||||
phase.gracefulSent ||= owner.directGraceDelivered();
|
||||
if (await stopped()) return;
|
||||
await wait(50);
|
||||
} while (Date.now() < deadline);
|
||||
await owner.signal("SIGKILL");
|
||||
phase.forcedDeadline = Date.now() + forcedMs;
|
||||
do {
|
||||
if (await stopped()) return;
|
||||
await wait(50);
|
||||
} while (Date.now() < phase.forcedDeadline);
|
||||
throw new Error("Observed launcher descendants remained after bounded cleanup");
|
||||
} catch (error) {
|
||||
phase.gracefulSent ||= owner.directGraceDelivered();
|
||||
await incompleteTreeFallback(error, child, phase, deadline, forcedMs);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import path from "node:path";
|
||||
|
||||
export interface ProcessObservation {
|
||||
pid: number;
|
||||
parentPid: number;
|
||||
processGroupId: number;
|
||||
started: string;
|
||||
kind: string;
|
||||
state?: string;
|
||||
}
|
||||
|
||||
export interface ObservedProcessGroup {
|
||||
@@ -140,3 +144,86 @@ export function refreshContinuouslyLiveProcessGroups(
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
const diagnosticProcessKinds = new Set([
|
||||
"bash",
|
||||
"chrome",
|
||||
"codex",
|
||||
"google-chrome",
|
||||
"node",
|
||||
"paperclip-runnerd",
|
||||
"playwright",
|
||||
"pnpm",
|
||||
"postgres",
|
||||
"sh",
|
||||
"tsx",
|
||||
]);
|
||||
|
||||
export async function readProcessTable(startInspector?: () => ChildProcess): Promise<ProcessObservation[] | null> {
|
||||
if (process.platform === "win32") {
|
||||
return null;
|
||||
}
|
||||
return await new Promise<ProcessObservation[] | null>((resolve) => {
|
||||
const inspector = startInspector ? startInspector() : spawn(
|
||||
"ps",
|
||||
["-e", "-o", "pid=,ppid=,pgid=,lstart=,stat=,comm="],
|
||||
{
|
||||
env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" },
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
// A wrapper-group shutdown must not interrupt its own bounded audit.
|
||||
detached: true,
|
||||
},
|
||||
);
|
||||
let output = "";
|
||||
let settled = false;
|
||||
let truncated = false;
|
||||
const finish = (value: ProcessObservation[] | null) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(inspectionTimeout);
|
||||
resolve(value);
|
||||
};
|
||||
const inspectionTimeout = setTimeout(() => {
|
||||
inspector.kill("SIGKILL");
|
||||
finish(null);
|
||||
}, 5_000);
|
||||
inspectionTimeout.unref();
|
||||
inspector.stdout?.setEncoding("utf8").on("data", (chunk: string) => {
|
||||
if (output.length + chunk.length > 1024 * 1024) {
|
||||
truncated = true;
|
||||
inspector.kill("SIGKILL");
|
||||
finish(null);
|
||||
return;
|
||||
}
|
||||
output += chunk;
|
||||
});
|
||||
inspector.once("error", () => finish(null));
|
||||
inspector.once("close", (code) => {
|
||||
if (code !== 0 || truncated) { finish(null); return; }
|
||||
const observations = output
|
||||
.split(/\r?\n/)
|
||||
.map((line) =>
|
||||
/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(\S+)\s+(.+?)\s*$/.exec(
|
||||
line,
|
||||
),
|
||||
)
|
||||
.filter((match): match is RegExpExecArray => match !== null)
|
||||
.map((match): ProcessObservation => {
|
||||
// A target process can choose its own argv and process name. Emit a
|
||||
// fixed category instead of target-controlled text so diagnostics
|
||||
// can never turn that metadata into a secret-exfiltration channel.
|
||||
const command = path.basename(match[6]!);
|
||||
const kind = diagnosticProcessKinds.has(command) ? command : "other";
|
||||
return {
|
||||
pid: Number(match[1]),
|
||||
parentPid: Number(match[2]),
|
||||
processGroupId: Number(match[3]),
|
||||
started: match[4]!,
|
||||
kind,
|
||||
state: match[5]!,
|
||||
};
|
||||
});
|
||||
finish(observations);
|
||||
});
|
||||
}).catch(() => null);
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
import { explicitlyRequestsFileOutput } from "../../server/src/services/native-runtime/native-deliverable-feedback.js";
|
||||
import type { APIRequestContext, APIResponse } from "@playwright/test";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { classifyFailure } from "./failure-classifier.js";
|
||||
import { ObservedStateTimeout, RemoteAdmissionReadError, RunnerApi, RunnerApiHttpError } from "./api.js";
|
||||
import { createRemoteNativeBootstrap } from "./remote-native-bootstrap.js";
|
||||
import { REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS, type RemoteFixtureApi, type RemoteNativeFixture } from "./remote-native-fixtures.js";
|
||||
|
||||
afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs(); });
|
||||
|
||||
function harness(timeoutMs = REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 18_000) {
|
||||
const order: string[] = [];
|
||||
const issue = { id: "issue", companyId: "company", assigneeAgentId: "agent" };
|
||||
const run = { id: "run", companyId: "company", agentId: "agent", status: "running", executionStage: "preparing" };
|
||||
const leases = [{ id: "lease", heartbeatRunId: "run", issueId: "issue", status: "active", providerLeaseId: "sandbox" }];
|
||||
const api = { get: vi.fn(async (path: string) => path === "/api/issues/issue" ? issue : path === "/api/heartbeat-runs/run" ? run : leases) };
|
||||
const fixture = {
|
||||
binding: { companyId: "company", environmentId: "env", runId: "run", leaseId: "lease", sandboxId: "sandbox", remoteCwd: "/workspace" },
|
||||
baseline: { complete: true },
|
||||
publishAction: vi.fn(async () => { order.push("publish"); }),
|
||||
close: vi.fn(async () => { order.push("close"); }),
|
||||
} as unknown as RemoteNativeFixture;
|
||||
const bind = vi.fn(async () => { order.push("armed"); return fixture; });
|
||||
const input = {
|
||||
api: api as unknown as RemoteFixtureApi, daytona: { get: vi.fn() }, companyId: "company", environmentId: "env", agentId: "agent",
|
||||
image: `image@sha256:${"a".repeat(64)}`, nodeSha256: `sha256:${"b".repeat(64)}`, runnerdSha256: `sha256:${"c".repeat(64)}`,
|
||||
deadlineAt: Date.now() + timeoutMs, evidence: vi.fn(async (_name: string, _data: unknown) => { order.push("evidence"); }),
|
||||
};
|
||||
const bootstrap = createRemoteNativeBootstrap(input, bind);
|
||||
const request = { issueId: "issue", runId: "run", targets: ["target.txt"], actionPrompt: async (actual: RemoteNativeFixture) => {
|
||||
expect(actual).toBe(fixture); await Promise.resolve(); order.push("baseline"); return "PRIVATE ACTUAL ACTION";
|
||||
} };
|
||||
return { bootstrap, input, bind, api, issue, run, leases, fixture, request, order };
|
||||
}
|
||||
|
||||
it("keeps negated bootstrap instructions out of the production file-delivery contract", () => {
|
||||
const prompt = harness().bootstrap.prompt("nonce");
|
||||
// Retained failed attempt: comma splitting detached this clause from “do not”.
|
||||
const original = "Before reading those instructions, do not infer the task, run shell commands, create or modify any file, ask replacement questions, or mark work complete. Do not create the missing instruction file.";
|
||||
expect(explicitlyRequestsFileOutput(original)).toBe(true);
|
||||
expect(explicitlyRequestsFileOutput(prompt)).toBe(false);
|
||||
expect(prompt).toContain("Do not create or modify any file.");
|
||||
expect(prompt).toContain("Do not run shell commands.");
|
||||
expect(prompt).toContain("Do not ask replacement questions.");
|
||||
expect(prompt).toContain("Do not mark work complete.");
|
||||
expect(prompt).toContain("Do not create the missing instruction file.");
|
||||
// A real requested output still requires delivery; no production gate changes.
|
||||
expect(explicitlyRequestsFileOutput(`${prompt}\nCreate a downloadable report.txt file.`)).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
it("keeps the complete readiness/install reserve when a lease arrives at the admission boundary", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("late-lease");
|
||||
const lease = h.leases.pop()!;
|
||||
let remainingAtBind = 0;
|
||||
h.bind.mockImplementation(async () => { remainingAtBind = h.input.deadlineAt - Date.now(); return h.fixture; });
|
||||
const pending = h.bootstrap.bindAndRelease(h.request);
|
||||
await vi.advanceTimersByTimeAsync(800);
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
h.leases.push(lease); await vi.advanceTimersByTimeAsync(100);
|
||||
await expect(pending).resolves.toBe(h.fixture);
|
||||
expect(remainingAtBind).toBeGreaterThanOrEqual(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS);
|
||||
expect(h.bind).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ deadlineAt: h.input.deadlineAt }));
|
||||
expect(h.order.indexOf("baseline")).toBeLessThan(h.order.indexOf("publish"));
|
||||
});
|
||||
|
||||
it("withholds actual work until exact run admission, armed observer and awaited baseline", async () => {
|
||||
const h = harness(); const prompt = h.bootstrap.prompt("nonce");
|
||||
expect(prompt).not.toContain("PRIVATE ACTUAL ACTION");
|
||||
expect(prompt).toContain("native file-read tool");
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
expect(await h.bootstrap.bindAndRelease(h.request)).toBe(h.fixture);
|
||||
expect(h.order).toEqual(["armed", "baseline", "evidence", "publish"]);
|
||||
expect(h.bind).toHaveBeenCalledWith(expect.objectContaining({
|
||||
sdkVersion: "0.203.0", targets: ["target.txt"],
|
||||
authority: { companyId: "company", environmentId: "env", runId: "run", leaseId: "lease", sandboxId: "sandbox", image: h.input.image },
|
||||
}));
|
||||
expect(h.fixture.publishAction).toHaveBeenCalledWith(expect.stringMatching(/^\.paperclip-eval-action-[a-f0-9]{36}\.txt$/u), "PRIVATE ACTUAL ACTION");
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE ACTUAL ACTION");
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("one unconsumed");
|
||||
});
|
||||
|
||||
it.each(["issue-company", "issue-agent", "issue-id", "run-company", "run-agent", "run-id", "run-terminal", "ambiguous-lease"])("rejects %s before observer execution or action delivery", async variant => {
|
||||
const h = harness(); h.bootstrap.prompt("nonce");
|
||||
if (variant === "issue-company") h.issue.companyId = "other";
|
||||
if (variant === "issue-agent") h.issue.assigneeAgentId = "other";
|
||||
if (variant === "issue-id") h.issue.id = "other";
|
||||
if (variant === "run-company") h.run.companyId = "other";
|
||||
if (variant === "run-agent") h.run.agentId = "other";
|
||||
if (variant === "run-id") h.run.id = "other";
|
||||
if (variant === "run-terminal") h.run.status = "succeeded";
|
||||
if (variant === "ambiguous-lease") h.leases.push({ ...h.leases[0]!, id: "second" });
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow();
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("waits through queued admission without publishing early", async () => {
|
||||
const h = harness(); h.bootstrap.prompt("nonce"); h.run.status = "queued";
|
||||
const original = h.api.get.getMockImplementation()!; let count = 0;
|
||||
h.api.get.mockImplementation(async path => {
|
||||
if (path === "/api/heartbeat-runs/run" && ++count === 2) h.run.status = "running";
|
||||
return original(path);
|
||||
});
|
||||
await h.bootstrap.bindAndRelease(h.request);
|
||||
expect(count).toBe(2); expect(h.fixture.publishAction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(["", "x".repeat(16385)])("rejects empty or over-bound action after closing only its observer", async action => {
|
||||
const h = harness(); h.bootstrap.prompt("nonce");
|
||||
await expect(h.bootstrap.bindAndRelease({ ...h.request, actionPrompt: () => action })).rejects.toThrow("empty or too large");
|
||||
expect(h.fixture.publishAction).not.toHaveBeenCalled(); expect(h.fixture.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("retains uncertain delivery and cleanup failure without retrying publication", async () => {
|
||||
const h = harness(); h.bootstrap.prompt("nonce");
|
||||
vi.mocked(h.fixture.publishAction).mockRejectedValue(new Error("uncertain delivery"));
|
||||
vi.mocked(h.fixture.close).mockRejectedValue(new Error("cleanup failed"));
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("observer cleanup is unproven");
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("one unconsumed");
|
||||
expect(h.fixture.publishAction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects ambiguous bootstrap delivery and reused nonces", async () => {
|
||||
const h = harness(); h.bootstrap.prompt("first");
|
||||
expect(() => h.bootstrap.prompt("first")).toThrow("reused"); h.bootstrap.prompt("second");
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("one unconsumed");
|
||||
expect(h.api.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["nodeSha256", "runnerdSha256", "image"])("requires immutable %s before any remote call", field => {
|
||||
const h = harness();
|
||||
expect(() => createRemoteNativeBootstrap({ ...h.input, [field]: "ambient-latest" }, h.bind)).toThrow("immutable");
|
||||
expect(h.input.daytona.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it("admits a cold building_snapshot lease after 20 seconds within the unchanged case deadline", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(90_000); h.bootstrap.prompt("cold");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
let sandboxState = "building_snapshot";
|
||||
h.api.get.mockImplementation(async path => path.endsWith("/leases") && sandboxState === "building_snapshot" ? [] : original(path));
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request);
|
||||
await vi.advanceTimersByTimeAsync(25_000);
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
sandboxState = "started";
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
await expect(delivery).resolves.toBe(h.fixture);
|
||||
expect(h.bind).toHaveBeenCalledWith(expect.objectContaining({ deadlineAt: 90_000 }));
|
||||
expect(h.input.daytona.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["failed", "cancelled", "succeeded"])("stops waiting immediately when provisioning run becomes %s", async status => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 18_000); h.bootstrap.prompt("terminal"); h.leases.length = 0;
|
||||
const delivery = expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("stopped before observer setup");
|
||||
await vi.advanceTimersByTimeAsync(1000); h.run.status = status;
|
||||
await vi.advanceTimersByTimeAsync(100); await delivery;
|
||||
expect(Date.now()).toBeLessThan(h.input.deadlineAt);
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
expect(h.input.evidence).toHaveBeenCalledWith("remote-native-bootstrap-startup-run.json", expect.objectContaining({ runStatus: status, deadlineReached: false }));
|
||||
});
|
||||
|
||||
it("rechecks run ownership while waiting for the lease", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(); h.bootstrap.prompt("owner"); h.leases.length = 0;
|
||||
const delivery = expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("ownership is unproven");
|
||||
await vi.advanceTimersByTimeAsync(100); h.run.companyId = "foreign";
|
||||
await vi.advanceTimersByTimeAsync(100); await delivery;
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["foreign-run", "foreign-issue", "inactive", "missing-provider"])("never admits %s and reserves setup time within the authored deadline with bounded state", async variant => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("timeout");
|
||||
if (variant === "foreign-run") h.leases[0]!.heartbeatRunId = "foreign";
|
||||
if (variant === "foreign-issue") h.leases[0]!.issueId = "foreign";
|
||||
if (variant === "inactive") h.leases[0]!.status = "released";
|
||||
if (variant === "missing-provider") h.leases[0]!.providerLeaseId = "";
|
||||
h.run.executionStage = "PRIVATE".repeat(10_000);
|
||||
const delivery = expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("Timed out waiting for owned native qualification lease");
|
||||
await vi.advanceTimersByTimeAsync(1000); await delivery;
|
||||
expect(Date.now()).toBe(1000); expect(h.bind).not.toHaveBeenCalled();
|
||||
expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
const state = h.input.evidence.mock.calls[0]![1];
|
||||
expect(state).toMatchObject({ executionStage: "unknown", activeOwnedLeaseCount: 0, deadlineReached: false, admissionDeadlineReached: true });
|
||||
expect(Buffer.byteLength(JSON.stringify(state))).toBeLessThan(512);
|
||||
expect(JSON.stringify(state)).not.toContain("PRIVATE");
|
||||
});
|
||||
|
||||
it("rejects a second same-run lease even if only one lease is active", async () => {
|
||||
const h = harness(); h.bootstrap.prompt("ambiguous");
|
||||
h.leases.push({ ...h.leases[0]!, id: "old", status: "released" });
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("Ambiguous native qualification lease");
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not start observation after the case deadline", async () => {
|
||||
const h = harness(0); h.bootstrap.prompt("expired");
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("Timed out waiting");
|
||||
expect(h.api.get).not.toHaveBeenCalled(); expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it.each(["terminal", "run-owner", "issue-owner"])("does not lose a successful %s read when the lease endpoint rejects", async variant => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(); h.bootstrap.prompt("read-error");
|
||||
if (variant === "terminal") h.run.status = "failed";
|
||||
if (variant === "run-owner") h.run.companyId = "foreign";
|
||||
if (variant === "issue-owner") h.issue.companyId = "foreign";
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => {
|
||||
if (path.endsWith("/leases") || (variant === "issue-owner" && path.endsWith("/run"))
|
||||
|| (variant !== "issue-owner" && path.endsWith("/issue"))) throw new Error("PRIVATE API ERROR");
|
||||
return original(path);
|
||||
});
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow(variant === "terminal" ? "stopped before observer setup" : "ownership is unproven");
|
||||
expect(Date.now()).toBe(0); expect(h.bind).not.toHaveBeenCalled();
|
||||
expect(h.input.evidence.mock.calls[0]![1]).toMatchObject({ admissionDeadlineReached: false });
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
});
|
||||
|
||||
it.each(["/api/issues/issue", "/api/heartbeat-runs/run", "/api/environments/env/leases"])("never admits while %s cannot be read", async failedPath => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("missing-read");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => { if (path === failedPath) throw new Error("PRIVATE API ERROR"); return original(path); });
|
||||
const delivery = expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("diagnostics withheld");
|
||||
await vi.advanceTimersByTimeAsync(1000); await delivery;
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
});
|
||||
|
||||
it("allows a transient lease read failure to recover without losing the setup reserve", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(); h.bootstrap.prompt("recover-read");
|
||||
const original = h.api.get.getMockImplementation()!; let failed = false;
|
||||
h.api.get.mockImplementation(async path => { if (path.endsWith("/leases") && !failed) { failed = true; throw new Error("unavailable"); } return original(path); });
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request);
|
||||
await vi.advanceTimersByTimeAsync(100); await expect(delivery).resolves.toBe(h.fixture);
|
||||
expect(h.bind).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects a lease read completing inside the final setup reserve and saves startup evidence", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("late");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => {
|
||||
if (path.endsWith("/leases")) await new Promise(resolve => setTimeout(resolve, 1100));
|
||||
return original(path);
|
||||
});
|
||||
const delivery = expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("Timed out waiting");
|
||||
await vi.advanceTimersByTimeAsync(1200); await delivery;
|
||||
expect(h.bind).not.toHaveBeenCalled(); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
expect(h.input.evidence.mock.calls[0]![1]).toMatchObject({ phase: "lease_admission", leasesRead: "rejected", admissionDeadlineReached: true, deadlineReached: false });
|
||||
expect(h.input.evidence.mock.calls[0]![1]).not.toHaveProperty("activeOwnedLeaseCount");
|
||||
});
|
||||
|
||||
it("captures binder failure after admission without publishing or repeating setup", async () => {
|
||||
const h = harness(); h.bootstrap.prompt("bind-failure");
|
||||
h.bind.mockRejectedValue(new Error("remote_native_fixture:insufficient_setup_budget"));
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow("insufficient_setup_budget");
|
||||
expect(h.input.evidence.mock.calls[0]![1]).toMatchObject({ phase: "observer_setup", activeOwnedLeaseCount: 1 });
|
||||
expect(h.bind).toHaveBeenCalledTimes(1); expect(h.fixture.publishAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it.each(["terminal", "run-owner", "issue-owner"])("rejects %s immediately with another failed read and a pending lease, and consumes its late rejection", async variant => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(); h.bootstrap.prompt("slow-lease");
|
||||
if (variant === "terminal") h.run.status = "failed";
|
||||
if (variant === "run-owner") h.run.companyId = "foreign";
|
||||
if (variant === "issue-owner") h.issue.companyId = "foreign";
|
||||
let rejectLease!: (error: Error) => void;
|
||||
const leaseRead = new Promise<never>((_resolve, reject) => { rejectLease = reject; });
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => {
|
||||
if (path.endsWith("/leases")) return leaseRead;
|
||||
if (path === (variant === "issue-owner" ? "/api/heartbeat-runs/run" : "/api/issues/issue")) throw new Error("503 PRIVATE");
|
||||
return original(path);
|
||||
});
|
||||
await expect(h.bootstrap.bindAndRelease(h.request)).rejects.toThrow(variant === "terminal" ? "stopped before observer setup" : "ownership is unproven");
|
||||
expect(Date.now()).toBe(0); expect(h.api.get).toHaveBeenCalledTimes(3);
|
||||
expect(h.api.get).toHaveBeenCalledWith("/api/environments/env/leases", { timeout: 18_000 });
|
||||
const saved = JSON.stringify(h.input.evidence.mock.calls);
|
||||
expect(saved).toContain('"leasesRead":"pending"'); expect(saved).not.toContain("PRIVATE");
|
||||
rejectLease(new Error("late private rejection"));
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).toBe(saved);
|
||||
expect(h.api.get).toHaveBeenCalledTimes(3); expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retains persistent 503 classification without its raw cause", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("503");
|
||||
const cause = new RunnerApiHttpError(503, "GET /api/environments/env/leases returned 503: PRIVATE BODY");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => { if (path.endsWith("/leases")) throw cause; return original(path); });
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(error).toBeInstanceOf(ObservedStateTimeout); expect(error.cause).toBeUndefined();
|
||||
expect(classifyFailure(error)).toBe("transient_infrastructure");
|
||||
expect(error.message).not.toContain("PRIVATE");
|
||||
expect(h.input.evidence.mock.calls[0]![1]).toMatchObject({ readFailureClass: "transient_infrastructure" });
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([true, false])("clears a recovered 503 cause before %s admission or observed-state timeout", async admits => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("503-recovery");
|
||||
const original = h.api.get.getMockImplementation()!; let failed = false;
|
||||
h.api.get.mockImplementation(async path => {
|
||||
if (path.endsWith("/leases")) {
|
||||
if (!failed) { failed = true; throw new RunnerApiHttpError(503, "PRIVATE BODY"); }
|
||||
if (!admits) return [];
|
||||
}
|
||||
return original(path);
|
||||
});
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const result = await delivery;
|
||||
if (admits) expect(result).toBe(h.fixture);
|
||||
else { expect(classifyFailure(result)).toBe("candidate_failure"); expect(result.cause).toBeUndefined(); }
|
||||
});
|
||||
|
||||
it("bounds an unresponsive read at admission without launching replacement reads", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("hung");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => path.endsWith("/leases") ? new Promise<never>(() => {}) : original(path));
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1100); const error = await delivery;
|
||||
expect(classifyFailure(error)).toBe("transient_infrastructure");
|
||||
expect(h.api.get).toHaveBeenCalledTimes(3); expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it.each([
|
||||
["Playwright TimeoutError", Object.assign(new Error("Timeout 1000ms exceeded. PRIVATE"), { name: "TimeoutError" }), "transient_infrastructure"],
|
||||
["Playwright fetch timeout", new Error("apiRequestContext.get: Timeout 1000ms exceeded. PRIVATE"), "transient_infrastructure"],
|
||||
["server fetch timeout", new Error("Timeout 1000ms exceeded PRIVATE"), "transient_infrastructure"],
|
||||
["connection reset", new Error("apiRequestContext.get: read ECONNRESET PRIVATE"), "transient_infrastructure"],
|
||||
["socket hang up", new Error("socket hang up"), "transient_infrastructure"],
|
||||
["prefixed socket hang up", new Error("apiRequestContext.get: Socket Hang Up PRIVATE"), "transient_infrastructure"],
|
||||
["undefined", undefined, "candidate_failure"],
|
||||
["null", null, "candidate_failure"],
|
||||
["private string", "PRIVATE 503 TimeoutError", "candidate_failure"],
|
||||
["unknown object", { message: "PRIVATE", status: 503 }, "candidate_failure"],
|
||||
])("normalizes %s rejection without exposing transport diagnostics", async (_label, rejected, failureClass) => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("safe-errors");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
h.api.get.mockImplementation(async path => { if (path.endsWith("/leases")) throw rejected; return original(path); });
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(classifyFailure(error)).toBe(failureClass);
|
||||
expect(error.cause).toBeUndefined();
|
||||
expect(error.message.length).toBeLessThan(1024);
|
||||
expect(error.stack).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(error)).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
expect(h.input.evidence.mock.calls[0]![1]).toMatchObject({ leasesRead: "rejected", readFailureClass: failureClass });
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([[503, "transient_infrastructure"], [403, "permanent_infrastructure"], [400, "candidate_failure"]])(
|
||||
"normalizes actual RunnerApi HTTP %s status independently of its private body", async (status, failureClass) => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_E2E_PORT", "3100");
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("actual-api");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
const secret = "PRIVATE body: forbidden secret plaintext 503 timeout socket hang up ".repeat(10_000);
|
||||
const request = { get: vi.fn(async (path: string) => ({
|
||||
ok: () => !path.endsWith("/leases"), status: () => status,
|
||||
url: () => "http://PRIVATE.invalid/private", text: async () => secret,
|
||||
json: async () => original(path),
|
||||
} as APIResponse)) };
|
||||
const actual = new RunnerApi(request as unknown as APIRequestContext);
|
||||
h.api.get.mockImplementation(path => actual.get(path, { timeout: 1000 }));
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(classifyFailure(error)).toBe(failureClass);
|
||||
expect(error.cause).toBeUndefined();
|
||||
expect(error.message.length).toBeLessThan(1024);
|
||||
expect(error.stack).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(error)).not.toContain("PRIVATE");
|
||||
expect(JSON.stringify(h.input.evidence.mock.calls)).not.toContain("PRIVATE");
|
||||
if (status === 403) expect(error).toBeInstanceOf(RemoteAdmissionReadError);
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
vi.unstubAllEnvs();
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["issue", null], ["run", []], ["leases", {}], ["leases", [null]],
|
||||
["leases", ["PRIVATE"]], ["leases", [[{}]]], ["leases", undefined],
|
||||
])("rejects malformed successful %s JSON without an unhandled continuation", async (endpoint, value) => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(0);
|
||||
const h = harness(REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 1000); h.bootstrap.prompt("malformed");
|
||||
const original = h.api.get.getMockImplementation()!;
|
||||
const path = endpoint === "issue" ? "/api/issues/issue" : endpoint === "run" ? "/api/heartbeat-runs/run" : "/api/environments/env/leases";
|
||||
h.api.get.mockImplementation(async requested => requested === path ? value as never : original(requested));
|
||||
const delivery = h.bootstrap.bindAndRelease(h.request).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(1000); const error = await delivery;
|
||||
expect(error).toBeInstanceOf(RemoteAdmissionReadError);
|
||||
expect(classifyFailure(error)).toBe("candidate_failure");
|
||||
expect(error.cause).toBeUndefined(); expect(error.stack).not.toContain("PRIVATE");
|
||||
expect(h.bind).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { ObservedStateTimeout, RemoteAdmissionReadError, RunnerApiHttpError, pollUntil } from "./api.js";
|
||||
import { classifyFailure } from "./failure-classifier.js";
|
||||
import { REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS, bindRemoteNativeFixture, remoteNativeFixtureDiagnostics, type RemoteFixtureApi, type RemoteFixtureDaytona, type RemoteNativeFixture } from "./remote-native-fixtures.js";
|
||||
|
||||
type AdmissionEndpoint = "issue" | "run" | "leases";
|
||||
|
||||
function admissionReadError(endpoint: AdmissionEndpoint, error: unknown): RemoteAdmissionReadError {
|
||||
let failureClass: RemoteAdmissionReadError["failureClass"] = "candidate_failure";
|
||||
// Only typed status or transport diagnostics classify the failure. In
|
||||
// particular, an HTTP body must not supply classification keywords.
|
||||
try {
|
||||
if (error instanceof RunnerApiHttpError) {
|
||||
if (error.status === 408 || error.status === 429 || (error.status >= 500 && error.status <= 599)) failureClass = "transient_infrastructure";
|
||||
else if (error.status === 401 || error.status === 403) failureClass = "permanent_infrastructure";
|
||||
} else if (error instanceof Error) {
|
||||
const message = error.message.slice(0, 256);
|
||||
if (error.name === "TimeoutError" || /^(?:apiRequestContext\.get: )?Timeout \d+ms exceeded\b/u.test(message)
|
||||
|| /\b(?:ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up)\b/iu.test(message)) failureClass = "transient_infrastructure";
|
||||
}
|
||||
} catch { /* Unknown rejection values remain a bounded candidate failure. */ }
|
||||
return new RemoteAdmissionReadError(endpoint, failureClass);
|
||||
}
|
||||
|
||||
function admissionJson(endpoint: AdmissionEndpoint, value: unknown): boolean {
|
||||
const record = (item: unknown): item is Record<string, unknown> => item !== null && typeof item === "object" && !Array.isArray(item);
|
||||
return endpoint === "leases" ? Array.isArray(value) && value.every(record) : record(value);
|
||||
}
|
||||
|
||||
export interface RemoteNativeBootstrap {
|
||||
prompt(nonce: string): string;
|
||||
bindAndRelease(input: {
|
||||
issueId: string; runId: string; targets: readonly string[]; crossRoot?: { initialText: string };
|
||||
actionPrompt(fixture: RemoteNativeFixture): string | Promise<string>;
|
||||
}): Promise<RemoteNativeFixture>;
|
||||
}
|
||||
|
||||
/** Use the repository's pinned SDK, never an ambient CLI, SDK or credential. */
|
||||
export async function createRemoteFixtureClient(apiKey: string): Promise<RemoteFixtureDaytona> {
|
||||
if (!apiKey.trim()) throw new Error("Remote native qualification requires an explicitly bound Daytona credential");
|
||||
const require = createRequire(new URL("../../packages/plugins/sandbox-providers/daytona/package.json", import.meta.url));
|
||||
const entry = require.resolve("@daytonaio/sdk");
|
||||
let directory = dirname(entry), version: string | undefined;
|
||||
for (let i = 0; i < 4; i++, directory = dirname(directory)) {
|
||||
try {
|
||||
const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
|
||||
if (pkg.name === "@daytonaio/sdk") { version = pkg.version; break; }
|
||||
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
||||
}
|
||||
if (version !== "0.203.0") throw new Error("Remote native qualification requires Daytona SDK 0.203.0");
|
||||
const sdk = await import(pathToFileURL(entry).href);
|
||||
return new sdk.Daytona({ apiKey, apiUrl: "https://app.daytona.io/api" }) as RemoteFixtureDaytona;
|
||||
}
|
||||
|
||||
/** The tested action is withheld until its observer is armed. The initial
|
||||
* provider prompt only reads this one operator-published instruction file.
|
||||
* No production hook, steering support or remote setup-command execution is
|
||||
* assumed. Bootstrap reads are distinct from the native action under test. */
|
||||
export function createRemoteNativeBootstrap(input: {
|
||||
api: RemoteFixtureApi; daytona: RemoteFixtureDaytona; companyId: string; environmentId: string;
|
||||
agentId: string; image: string; nodeSha256: string; runnerdSha256: string; deadlineAt: number;
|
||||
evidence(name: string, data: unknown): Promise<void>;
|
||||
}, bind = bindRemoteNativeFixture): RemoteNativeBootstrap {
|
||||
if (!/^sha256:[a-f0-9]{64}$/u.test(input.nodeSha256) || !/^sha256:[a-f0-9]{64}$/u.test(input.runnerdSha256) || !/@sha256:[a-f0-9]{64}$/u.test(input.image)) {
|
||||
throw new Error("Remote native qualification requires immutable image and interpreter digests");
|
||||
}
|
||||
const bindings = new Map<string, { path: string; consumed: boolean }>();
|
||||
return {
|
||||
prompt(nonce) {
|
||||
if (!/^[A-Za-z0-9_-]{1,128}$/u.test(nonce) || bindings.has(nonce)) throw new Error("Invalid or reused remote bootstrap nonce");
|
||||
const path = `.paperclip-eval-action-${randomBytes(18).toString("hex")}.txt`;
|
||||
bindings.set(nonce, { path, consumed: false });
|
||||
return [
|
||||
`Your task instructions will be published by the operator in the workspace file ${path}.`,
|
||||
"Use your native file-read tool to read that exact relative file in the current execution workspace. If it is not present yet, retry the read for up to 20 seconds, then report the setup failure.",
|
||||
"Before reading those instructions: do not infer the task. Do not run shell commands. Do not create or modify any file.",
|
||||
"Do not ask replacement questions. Do not mark work complete. Do not create the missing instruction file.",
|
||||
"After reading the complete file, perform precisely the supplied task. Treat it as the operator's continuation of this task.",
|
||||
].join("\n");
|
||||
},
|
||||
async bindAndRelease(request) {
|
||||
const pending = [...bindings.values()].filter(value => !value.consumed);
|
||||
if (pending.length !== 1) throw new Error("Remote bootstrap requires one unconsumed instruction delivery");
|
||||
const setup = pending[0]!; setup.consumed = true;
|
||||
if (![request.issueId, request.runId].every(id => /^[A-Za-z0-9_-]{1,128}$/u.test(id))) throw new Error("Invalid bootstrap task/run identity");
|
||||
// Provisioning consumes the authored case deadline. A cold snapshot need
|
||||
// not produce a lease in 20 seconds; a terminal or foreign run never waits.
|
||||
let lastState: Record<string, string | number | boolean> = { observed: false };
|
||||
const admissionDeadlineAt = input.deadlineAt - REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS;
|
||||
let fixture: RemoteNativeFixture;
|
||||
let lastReadError: RemoteAdmissionReadError | undefined;
|
||||
try {
|
||||
const ready = await pollUntil({
|
||||
label: "owned native qualification lease", deadlineAt: admissionDeadlineAt, intervalMs: 100,
|
||||
load: async () => {
|
||||
type Read<T> = { status: "fulfilled"; value: T } | { status: "rejected"; reason: RemoteAdmissionReadError } | { status: "pending" };
|
||||
let issueRead: Read<Record<string, any>> = { status: "pending" };
|
||||
let runRead: Read<Record<string, any>> = { status: "pending" };
|
||||
let leasesRead: Read<Array<Record<string, any>>> = { status: "pending" };
|
||||
const snapshot = () => {
|
||||
const issue = issueRead.status === "fulfilled" ? issueRead.value : undefined;
|
||||
const run = runRead.status === "fulfilled" ? runRead.value : undefined;
|
||||
const rows = leasesRead.status === "fulfilled" ? leasesRead.value : undefined;
|
||||
const issueOwned = issue?.id === request.issueId && issue.companyId === input.companyId
|
||||
&& issue.assigneeAgentId === input.agentId;
|
||||
const runOwned = run?.companyId === input.companyId && run.agentId === input.agentId && run.id === request.runId;
|
||||
const owned = issueOwned && runOwned;
|
||||
const runLeases = Array.isArray(rows) ? rows.filter(row => row?.heartbeatRunId === request.runId) : undefined;
|
||||
const active = runLeases?.filter(row => row.issueId === request.issueId && row.status === "active" && row.providerLeaseId);
|
||||
// A failed endpoint cannot discard a successful read proving that
|
||||
// ownership changed or the run stopped. Missing reads never admit.
|
||||
const rejection = (issueRead.status === "fulfilled" && !issueOwned) || (runRead.status === "fulfilled" && !runOwned)
|
||||
? "Remote bootstrap task/run ownership is unproven"
|
||||
: runRead.status === "fulfilled" && !["queued", "running"].includes(run?.status) ? "Native qualification run stopped before observer setup"
|
||||
: runLeases && runLeases.length > 1 ? "Ambiguous native qualification lease" : undefined;
|
||||
// Fixed keys and allowlisted enum values only: no provider IDs,
|
||||
// errors, prompts or arbitrary API strings enter startup evidence.
|
||||
const readError = [issueRead, runRead, leasesRead].find(read => read.status === "rejected");
|
||||
const evidence = {
|
||||
observed: true, owned, phase: "lease_admission",
|
||||
issueRead: issueRead.status, runRead: runRead.status, leasesRead: leasesRead.status,
|
||||
runStatus: ["queued", "running", "succeeded", "failed", "cancelled", "timed_out"].includes(run?.status) ? run!.status : "unknown",
|
||||
executionStage: ["queued", "preparing", "executing", "finalizing"].includes(run?.executionStage) ? run!.executionStage : "unknown",
|
||||
...(runLeases ? { runLeaseCount: runLeases.length, activeOwnedLeaseCount: active!.length } : {}),
|
||||
...(readError?.status === "rejected" ? { readFailureClass: classifyFailure(readError.reason) } : {}),
|
||||
deadlineReached: Date.now() >= input.deadlineAt,
|
||||
};
|
||||
return { run, owned, lease: active?.[0], rejection, evidence,
|
||||
readError: readError?.status === "rejected" ? readError.reason : undefined };
|
||||
};
|
||||
// At most three in-flight reads. Each has a transport deadline no
|
||||
// later than admission; terminal/ownership proof need not await it.
|
||||
const remainingMs = Math.max(1, admissionDeadlineAt - Date.now());
|
||||
const timeout = Math.min(30_000, remainingMs);
|
||||
const state = await new Promise<ReturnType<typeof snapshot>>(resolve => {
|
||||
let finished = false;
|
||||
const finish = (state: ReturnType<typeof snapshot>) => {
|
||||
if (finished) return;
|
||||
finished = true; clearTimeout(timer); resolve(state);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
const failure = (endpoint: AdmissionEndpoint) => ({ status: "rejected" as const, reason: new RemoteAdmissionReadError(endpoint, "transient_infrastructure") });
|
||||
if (issueRead.status === "pending") issueRead = failure("issue");
|
||||
if (runRead.status === "pending") runRead = failure("run");
|
||||
if (leasesRead.status === "pending") leasesRead = failure("leases");
|
||||
finish(snapshot());
|
||||
}, remainingMs);
|
||||
function read<T>(endpoint: AdmissionEndpoint, path: string, save: (result: Read<T>) => void) {
|
||||
// Both handlers are installed before dispatch. Late completion
|
||||
// is consumed but cannot mutate saved evidence or start a poll.
|
||||
void Promise.resolve().then(() => input.api.get<T>(path, { timeout })).then(
|
||||
value => settled(admissionJson(endpoint, value) ? { status: "fulfilled", value }
|
||||
: { status: "rejected", reason: admissionReadError(endpoint, undefined) }),
|
||||
reason => settled({ status: "rejected", reason: admissionReadError(endpoint, reason) }),
|
||||
);
|
||||
function settled(result: Read<T>) {
|
||||
if (finished) return;
|
||||
save(result);
|
||||
const state = snapshot();
|
||||
if (state.rejection || [issueRead, runRead, leasesRead].every(read => read.status !== "pending")) finish(state);
|
||||
}
|
||||
}
|
||||
read<Record<string, any>>("issue", `/api/issues/${request.issueId}`, result => { issueRead = result; });
|
||||
read<Record<string, any>>("run", `/api/heartbeat-runs/${request.runId}`, result => { runRead = result; });
|
||||
read<Array<Record<string, any>>>("leases", `/api/environments/${input.environmentId}/leases`, result => { leasesRead = result; });
|
||||
});
|
||||
lastState = state.evidence;
|
||||
lastReadError = state.rejection ? undefined : state.readError;
|
||||
if (lastReadError !== undefined) throw lastReadError;
|
||||
return state;
|
||||
},
|
||||
accept: state => !state.rejection && state.owned && state.run?.status === "running" && Boolean(state.lease)
|
||||
&& Date.now() < admissionDeadlineAt,
|
||||
reject: state => state.rejection,
|
||||
timeoutDetail: () => JSON.stringify(lastState),
|
||||
});
|
||||
const lease = ready.lease!;
|
||||
lastState = { ...lastState, phase: "observer_setup" };
|
||||
fixture = await bind({ api: input.api, daytona: input.daytona, sdkVersion: "0.203.0", nodeSha256: input.nodeSha256, runnerdSha256: input.runnerdSha256,
|
||||
authority: { companyId: input.companyId, environmentId: input.environmentId, runId: request.runId, leaseId: lease.id, sandboxId: lease.providerLeaseId, image: input.image },
|
||||
targets: [...request.targets], crossRoot: request.crossRoot, actionFile: setup.path, deadlineAt: input.deadlineAt,
|
||||
});
|
||||
} catch (error) {
|
||||
if (lastReadError !== undefined && lastState.phase === "lease_admission") {
|
||||
if (classifyFailure(lastReadError) === "transient_infrastructure") {
|
||||
const timeout = new ObservedStateTimeout("owned native qualification lease", "transient_infrastructure", JSON.stringify(lastState));
|
||||
// The safe read classification is already in the bounded state.
|
||||
// Do not expose the rejected transport value through a cause chain.
|
||||
error = timeout;
|
||||
} else error = lastReadError;
|
||||
}
|
||||
try {
|
||||
await input.evidence(`remote-native-bootstrap-startup-${request.runId}.json`, {
|
||||
...lastState, fixtureDiagnostics: remoteNativeFixtureDiagnostics(error), deadlineReached: Date.now() >= input.deadlineAt,
|
||||
admissionDeadlineReached: Date.now() >= admissionDeadlineAt,
|
||||
});
|
||||
} catch (evidenceError) {
|
||||
throw new AggregateError([error, evidenceError], "Remote bootstrap startup failed and state evidence could not be saved");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
const action = await request.actionPrompt(fixture);
|
||||
if (!action.trim() || Buffer.byteLength(action) > 16 * 1024) throw new Error("Remote bootstrap action is empty or too large");
|
||||
await input.evidence(`remote-native-bootstrap-${request.runId}.json`, { binding: fixture.binding, setupPath: setup.path, baseline: fixture.baseline });
|
||||
await fixture.publishAction(setup.path, action);
|
||||
return fixture;
|
||||
} catch (error) {
|
||||
try { await fixture.close(); } catch { throw new AggregateError([error], "Remote bootstrap failed and observer cleanup is unproven"); }
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createHash } from "node:crypto";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { mkdtemp, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { Script } from "node:vm";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS, bindRemoteNativeFixture, createRemoteTargetWatch, isRemoteRunRoot, parseRemoteProcStat, remoteNativeFixtureDiagnostics, type RemoteNativeFixtureOptions, type RemoteNativeSnapshot } from "./remote-native-fixtures.js";
|
||||
|
||||
import { createRemoteNativeBootstrap } from "./remote-native-bootstrap.js";
|
||||
|
||||
const hash = (s: string) => `sha256:${createHash("sha256").update(s).digest("hex")}`;
|
||||
const bootId = "12345678-1234-1234-1234-123456789abc";
|
||||
const authority = { companyId: "company", environmentId: "environment", runId: "run", leaseId: "lease", sandboxId: "sandbox", image: `registry/image@sha256:${"a".repeat(64)}` };
|
||||
const binding = { ...authority, remoteCwd: "/workspace" };
|
||||
const root = { pid: 21, ppid: 1, startTicks: "100", bootId };
|
||||
function snapshot(): RemoteNativeSnapshot {
|
||||
return { binding, observedAtMs: 1000, observedMonotonicNs: "10000", receivedAtMs: 1000, complete: true, workspace: { "existing.txt": hash("original") },
|
||||
targets: { "result.txt": { absent: true, sha256: null, parent: { dev: "1", ino: "2" }, mutationCount: 0, complete: true } },
|
||||
watcher: { complete: true, targetMutationCount: 0, workspaceMutationCount: 0 },
|
||||
processes: { captured: true, root, journal: [root], live: [21] }, scope: { kind: "user_workspace", excludedRuntime: { relativePath: ".paperclip-runtime/paperclip-runner", absolutePath: "/workspace/.paperclip-runtime/paperclip-runner", dev: "1", ino: "4", runnerExecutableSha256: hash("runnerd") }, observedPrpEnvironmentLeaseId: "workspace-id", prpEnvironmentLeaseIdVerified: false }, setup: { path: "action.txt", sha256: null, published: false }, attached: null };
|
||||
}
|
||||
function readiness() { return { ready: true, binding, root, runtime: { dev: "1", ino: "4", runnerExecutableSha256: hash("runnerd") } }; }
|
||||
function harness() {
|
||||
let lease: Record<string, unknown> = { id: "lease", companyId: "company", environmentId: "environment", heartbeatRunId: "run", provider: "daytona", providerLeaseId: "sandbox", status: "active", releasedAt: null,
|
||||
metadata: { sandboxId: "sandbox", image: authority.image, reuseLease: false, remoteCwd: "/workspace", workspaceSentinel: { path: "/workspace/.paperclip-runtime/reusable-sandbox-lease.json", token: "fixture-sentinel-token", result: "written", runId: "run", providerLeaseId: "sandbox" } } };
|
||||
const labels: Record<string, string> = { "paperclip-provider": "daytona", "paperclip-company-id": "company", "paperclip-environment-id": "environment", "paperclip-run-id": "run", "paperclip-reuse-lease": "false" };
|
||||
const calls: Array<{ command: string; request: Record<string, any>; timeout: number | undefined }> = [];
|
||||
let resolveTerminal!: (v: unknown) => void, rejectTerminal!: (e: unknown) => void;
|
||||
const terminal = new Promise((resolve, reject) => { resolveTerminal = resolve; rejectTerminal = reject; });
|
||||
const current = snapshot();
|
||||
let override: ((request: Record<string, any>) => unknown) | undefined;
|
||||
const executeCommand = vi.fn(async (command: string, _cwd?: string, _env?: Record<string, string>, timeout?: number) => {
|
||||
const encoded = command.match(/ '([A-Za-z0-9+/=]+)'$/u)?.[1];
|
||||
if (!encoded) throw new Error("invalid command");
|
||||
const request = JSON.parse(Buffer.from(encoded, "base64").toString()); calls.push({ command, request, timeout });
|
||||
if (request.op === "wait") return { exitCode: 0, result: JSON.stringify({ ok: true, result: await terminal }) };
|
||||
if (override) { const result = override(request); if (result !== undefined) return result as { exitCode: number; result: string }; }
|
||||
let result: unknown = request.op === "runtime-ready" ? readiness() : structuredClone(current);
|
||||
if (request.op === "publish") { current.setup = { path: request.path, published: true, sha256: hash(request.text) }; result = current.setup; }
|
||||
if (request.op === "close") result = { closed: true };
|
||||
if (request.op === "arm") result = { armed: true, sealed: false };
|
||||
if (request.op === "attached") result = { clientScript: `${request.root}/client.cjs`, clientSocket: `${request.root}/attached.sock` };
|
||||
return { exitCode: 0, result: JSON.stringify({ ok: true, result }) };
|
||||
});
|
||||
const get = vi.fn(async () => ({ id: "sandbox", labels, process: { executeCommand } }));
|
||||
const apiGet = vi.fn(async (path: string) => path.includes("/environments/") ? [structuredClone(lease)] : structuredClone(lease));
|
||||
const options: RemoteNativeFixtureOptions = { api: { get: apiGet as RemoteNativeFixtureOptions["api"]["get"] }, daytona: { get }, sdkVersion: "0.203.0", authority, nodeSha256: hash("node"), runnerdSha256: hash("runnerd"), targets: ["result.txt"], actionFile: "action.txt", deadlineAt: Date.now() + REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS + 18_000 };
|
||||
return { options, current, labels, calls, executeCommand, apiGet, get, resolveTerminal, rejectTerminal,
|
||||
setLease(value: Record<string, unknown>) { lease = value; }, lease: () => lease, override(fn: typeof override) { override = fn; } };
|
||||
}
|
||||
|
||||
describe("remote native lease admission", () => {
|
||||
it.each(["companyId", "environmentId", "heartbeatRunId", "providerLeaseId", "provider", "status"])("rejects wrong %s before executing any remote command", async key => {
|
||||
const h = harness(); h.setLease({ ...h.lease(), [key]: "foreign" });
|
||||
await expect(bindRemoteNativeFixture(h.options)).rejects.toThrow("lease_scope"); expect(h.executeCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects protected runtime targets and insufficient setup budget before SDK access", async () => {
|
||||
for (const patch of [{ targets: [".paperclip-runtime/paperclip-runner/bin/forbidden"] }, { actionFile: ".paperclip-runtime/paperclip-runner/task.txt" }, { deadlineAt: Date.now() + 1000 }]) {
|
||||
const h = harness(); await expect(bindRemoteNativeFixture({ ...h.options, ...patch })).rejects.toThrow(); expect(h.get).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
it("requires exact SDK, immutable image and executable hashes", async () => {
|
||||
for (const input of [{ sdkVersion: "0.204.0" }, { nodeSha256: "unknown" }, { authority: { ...authority, image: "image:latest" } }]) {
|
||||
const h = harness(); await expect(bindRemoteNativeFixture({ ...h.options, ...input } as RemoteNativeFixtureOptions)).rejects.toThrow(); expect(h.get).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
it("rejects reuse, foreign metadata and sentinel binding", async () => {
|
||||
for (const patch of [{ reuseLease: true }, { sandboxId: "other" }, { image: "image:latest" }, { remoteCwd: "/workspace/../foreign" }, { workspaceSentinel: { token: "fixture-sentinel-token" } }]) {
|
||||
const h = harness(); h.setLease({ ...h.lease(), metadata: { ...(h.lease().metadata as object), ...patch } });
|
||||
await expect(bindRemoteNativeFixture(h.options)).rejects.toThrow(); expect(h.executeCommand).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
it("rejects wrong ownership labels and never discovers a sandbox by name", async () => {
|
||||
const h = harness(); h.labels["paperclip-run-id"] = "other";
|
||||
await expect(bindRemoteNativeFixture(h.options)).rejects.toThrow("sandbox_labels"); expect(h.get).toHaveBeenCalledExactlyOnceWith("sandbox"); expect(h.executeCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
it("waits beyond the old 20s install subdeadline for staging, then installs exactly once before action", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(1_000_000);
|
||||
try {
|
||||
const h = harness(); h.options.deadlineAt += 60_000;
|
||||
h.override(r => r.op === "runtime-ready" && Date.now() < 1_021_000 ? { exitCode: 0, result: JSON.stringify({ ok: true, result: { ready: false } }) } : undefined);
|
||||
const pending = bindRemoteNativeFixture(h.options);
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
expect(h.calls.every(c => c.request.op === "runtime-ready")).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(1000); const fixture = await pending;
|
||||
expect(h.calls.filter(c => c.request.op === "install")).toHaveLength(1);
|
||||
expect(h.calls.find(c => c.request.op === "install")!.timeout).toBe(25);
|
||||
expect(h.calls.at(-1)!.request.op).toBe("arm");
|
||||
expect(h.apiGet).toHaveBeenCalledTimes((h.calls.filter(c => c.request.op === "runtime-ready").length + 2) * 2);
|
||||
await fixture.close();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it("reserves readiness after a late lease with delayed admission and installation", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(1_000_000);
|
||||
try {
|
||||
const h = harness(); h.options.deadlineAt = Date.now() + REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS;
|
||||
const initialGet = h.get.getMockImplementation()!;
|
||||
h.get.mockImplementationOnce(async () => { await new Promise(resolve => setTimeout(resolve, 9000)); return initialGet(); });
|
||||
h.override(r => {
|
||||
if (r.op === "runtime-ready" || r.op === "install") return new Promise(resolve => setTimeout(() => resolve({
|
||||
exitCode: 0, result: JSON.stringify({ ok: true, result: r.op === "runtime-ready" ? readiness() : snapshot() }),
|
||||
}), r.op === "runtime-ready" ? 9000 : 24_000));
|
||||
return undefined;
|
||||
});
|
||||
const pending = bindRemoteNativeFixture(h.options);
|
||||
// Retain a rejected setup for the assertion below while fake clocks advance.
|
||||
void pending.catch(() => {});
|
||||
await vi.advanceTimersByTimeAsync(8999); expect(h.calls).toHaveLength(0);
|
||||
await vi.advanceTimersByTimeAsync(9001); expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install"]);
|
||||
expect(h.calls.find(c => c.request.op === "install")!.timeout).toBe(25);
|
||||
await vi.advanceTimersByTimeAsync(24_000); const fixture = await pending;
|
||||
expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install", "wait", "arm"]);
|
||||
expect(h.options.deadlineAt - Date.now()).toBe(22_000);
|
||||
await fixture.publishAction("action.txt", "task"); expect(h.calls.at(-1)!.request.op).toBe("publish");
|
||||
await fixture.close();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it.each([42_000, 43_000, REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS - 1])("rejects a %ims late setup window before remote work", async budget => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(1_000_000);
|
||||
try {
|
||||
const h = harness(); h.options.deadlineAt = Date.now() + budget;
|
||||
await expect(bindRemoteNativeFixture(h.options)).rejects.toThrow("insufficient_setup_budget");
|
||||
expect(h.apiGet).not.toHaveBeenCalled(); expect(h.get).not.toHaveBeenCalled(); expect(h.calls).toHaveLength(0);
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it("never installs on a missing runtime and reserves installation and teardown inside the original deadline", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(1_000_000);
|
||||
try {
|
||||
const h = harness(); h.override(r => r.op === "runtime-ready" ? { exitCode: 0, result: '{"ok":true,"result":{"ready":false}}' } : undefined);
|
||||
const outcome = bindRemoteNativeFixture(h.options).catch(error => error);
|
||||
await vi.advanceTimersByTimeAsync(h.options.deadlineAt - 42_000 - Date.now());
|
||||
expect((await outcome).message).toContain("readiness_deadline");
|
||||
expect(h.calls.every(c => c.request.op === "runtime-ready")).toBe(true);
|
||||
expect(Date.now()).toBe(h.options.deadlineAt - 42_000);
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it.each(["lease", "binding", "shape", "pin", "unknown-error"])("rejects %s during readiness without installing or publishing", async variant => {
|
||||
const h = harness();
|
||||
h.override(r => {
|
||||
if (r.op !== "runtime-ready") return undefined;
|
||||
if (variant === "lease") { h.setLease({ ...h.lease(), heartbeatRunId: "other" }); return { exitCode: 0, result: '{"ok":true,"result":{"ready":false}}' }; }
|
||||
if (variant === "unknown-error") return { exitCode: 2, result: 'SECRET sdk stderr' };
|
||||
const value: any = readiness();
|
||||
if (variant === "binding") value.binding = { ...binding, leaseId: "foreign" };
|
||||
if (variant === "pin") value.runtime.runnerExecutableSha256 = hash("foreign");
|
||||
if (variant === "shape") value.extra = "secret";
|
||||
return { exitCode: 0, result: JSON.stringify({ ok: true, result: value }) };
|
||||
});
|
||||
const error = await bindRemoteNativeFixture(h.options).catch(error => error);
|
||||
expect(error).toBeInstanceOf(Error);
|
||||
expect(h.calls.every(c => c.request.op === "runtime-ready")).toBe(true);
|
||||
expect(JSON.stringify(remoteNativeFixtureDiagnostics(error))).not.toContain("SECRET");
|
||||
});
|
||||
it.each(["extra", "foreign-phase", "unknown-code", "malformed"])("drops %s remote diagnostic content without retry", async variant => {
|
||||
const h = harness();
|
||||
h.override(r => r.op === "runtime-ready" ? { exitCode: 2, result: variant === "malformed" ? "PRIVATE stderr" : JSON.stringify({ ok: false, diagnostic: { phase: variant === "foreign-phase" ? "close" : r.op, code: variant === "unknown-code" ? "PRIVATE stderr" : "socket_error", ...(variant === "extra" ? { private: "PRIVATE stderr" } : {}) } }) } : undefined);
|
||||
const error = await bindRemoteNativeFixture(h.options).catch(error => error);
|
||||
expect(remoteNativeFixtureDiagnostics(error)).toEqual([{ phase: "runtime-ready", code: "invalid_response" }]);
|
||||
expect(error.message).not.toContain("PRIVATE"); expect(h.calls).toHaveLength(1);
|
||||
});
|
||||
it("persists safe startup diagnostics through the real bootstrap catch without publishing an action", async () => {
|
||||
const h = harness(), evidence = vi.fn(async () => {});
|
||||
h.override(r => r.op === "runtime-ready" ? { exitCode: 2, result: JSON.stringify({ ok: false, diagnostic: { phase: "runtime-ready", code: "runtime_binary_identity" } }) } : undefined);
|
||||
const bootstrap = createRemoteNativeBootstrap({ ...h.options, companyId: "company", environmentId: "environment", agentId: "agent", image: authority.image, evidence,
|
||||
api: { get: (async (path: string) => path === "/api/issues/issue" ? { id: "issue", companyId: "company", assigneeAgentId: "agent" }
|
||||
: path === "/api/heartbeat-runs/run" ? { id: "run", companyId: "company", agentId: "agent", status: "running", executionStage: "preparing" }
|
||||
: [{ ...h.lease(), issueId: "issue" }]) as RemoteNativeFixtureOptions["api"]["get"] },
|
||||
}, async options => bindRemoteNativeFixture({ ...h.options, actionFile: options.actionFile }));
|
||||
bootstrap.prompt("nonce");
|
||||
const actionPrompt = vi.fn(async () => "PRIVATE ACTION");
|
||||
await expect(bootstrap.bindAndRelease({ issueId: "issue", runId: "run", targets: ["result.txt"], actionPrompt })).rejects.toThrow("runtime_binary_identity");
|
||||
expect(actionPrompt).not.toHaveBeenCalled();
|
||||
expect(evidence).toHaveBeenCalledWith("remote-native-bootstrap-startup-run.json", expect.objectContaining({
|
||||
phase: "observer_setup", fixtureDiagnostics: [{ phase: "runtime-ready", code: "runtime_binary_identity" }],
|
||||
}));
|
||||
expect(JSON.stringify(evidence.mock.calls)).not.toContain("PRIVATE ACTION");
|
||||
expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready"]);
|
||||
});
|
||||
it.each(["pid", "ppid", "startTicks", "bootId"])("rejects changed %s between readiness and baseline despite extra observer process fields", async key => {
|
||||
const h = harness();
|
||||
const changed = { state: "S", group: 21, ...root, [key]: key === "bootId" ? "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" : key === "startTicks" ? "999" : 99 };
|
||||
h.current.processes = { captured: true, root: changed, journal: [changed], live: [changed.pid] };
|
||||
await expect(bindRemoteNativeFixture(h.options)).rejects.toThrow("runtime_identity_changed");
|
||||
expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install", "close"]);
|
||||
});
|
||||
it("retains the closed read phase on transport errors without leaking text", async () => {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options);
|
||||
h.override(r => r.op === "read" ? { exitCode: 2, result: JSON.stringify({ ok: false, diagnostic: { phase: "read", code: "socket_error" } }) } : undefined);
|
||||
const error = await f.readFile("result.txt").catch(error => error);
|
||||
expect(remoteNativeFixtureDiagnostics(error)).toEqual([{ phase: "read", code: "socket_error" }]);
|
||||
await f.close();
|
||||
});
|
||||
it("retains only allowlisted install and cleanup diagnostics with no uncertain retry", async () => {
|
||||
const h = harness();
|
||||
h.override(r => ["install", "close"].includes(r.op) ? { exitCode: 2, result: JSON.stringify({ ok: false, diagnostic: { phase: r.op, code: r.op === "install" ? "runtime_identity_changed" : "socket_error" } }) } : undefined);
|
||||
const error = await bindRemoteNativeFixture(h.options).catch(error => error);
|
||||
expect(error.message).toContain("startup_failed_cleanup_unproven");
|
||||
expect(remoteNativeFixtureDiagnostics(error)).toEqual([{ phase: "close", code: "socket_error" }, { phase: "install", code: "runtime_identity_changed" }]);
|
||||
expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install", "close"]);
|
||||
});
|
||||
it("arms before publish, binds long receipt before teardown and preserves exact final bytes", async () => {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options);
|
||||
expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install", "wait", "arm"]); expect(f.baseline.processes.live).toEqual([21]);
|
||||
expect(h.calls[2]!.timeout).toBeLessThanOrEqual(67); expect(h.calls[2]!.request.timeoutMs).toBe(h.calls[2]!.timeout! * 1000);
|
||||
await f.publishAction("action.txt", "write only result.txt");
|
||||
await expect(f.publishAction("action.txt", "retry")).rejects.toThrow("publish_bound");
|
||||
const bytes = "\nUnicode 🪴 literal \\n\n";
|
||||
const final = { ...structuredClone(h.current), processes: { ...h.current.processes, live: [] }, files: { "result.txt": Buffer.from(bytes).toString("base64") } };
|
||||
final.targets["result.txt"] = { ...final.targets["result.txt"]!, absent: false, sha256: hash(bytes), mutationCount: 1 };
|
||||
h.resolveTerminal(final); h.apiGet.mockRejectedValue(new Error("lease already deleted"));
|
||||
expect((await f.finish()).processes.live).toEqual([]); expect((await f.readFile("result.txt")).toString()).toBe(bytes);
|
||||
await f.close(); expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install", "wait", "arm", "publish"]);
|
||||
});
|
||||
it("fails closed when lease deletion beats the terminal receipt", async () => {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options); await f.publishAction("action.txt", "task");
|
||||
h.rejectTerminal(new Error("channel closed before receipt")); await expect(f.finish()).rejects.toThrow("remote_command_failed_or_deadline");
|
||||
});
|
||||
it("rejects lease rotation before subsequent commands", async () => {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options); const count = h.calls.length;
|
||||
h.setLease({ ...h.lease(), heartbeatRunId: "next-run" });
|
||||
await expect(f.snapshot("pending")).rejects.toThrow("lease_scope"); expect(h.calls).toHaveLength(count);
|
||||
});
|
||||
it.each(["live", "incomplete", "missing-root", "bad-file"])("rejects %s terminal proof without weakening assertions", async type => {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options); await f.publishAction("action.txt", "task");
|
||||
const end: any = { ...structuredClone(h.current), processes: { ...h.current.processes, live: [] }, files: {} };
|
||||
if (type === "live") end.processes.live = [21];
|
||||
if (type === "incomplete") end.watcher.complete = false;
|
||||
if (type === "missing-root") end.processes = { captured: false, root: null, journal: [], live: [] };
|
||||
if (type === "bad-file") end.targets["result.txt"] = { ...end.targets["result.txt"], absent: false, sha256: hash("missing") };
|
||||
h.resolveTerminal(end); await expect(f.finish()).rejects.toThrow();
|
||||
});
|
||||
it("keeps a fixture-owned cross-root sentinel distinct from workspace targets", async () => {
|
||||
const h = harness(); h.options.crossRoot = { initialText: "outside sentinel" };
|
||||
h.current.targets["@cross-root"] = { absent: false, sha256: hash("outside sentinel"), parent: { dev: "1", ino: "outside" }, mutationCount: 0, complete: true };
|
||||
h.current.targets["@cross-root"]!.parent.ino = "42";
|
||||
const f = await bindRemoteNativeFixture(h.options);
|
||||
expect(f.outsideTarget).toMatch(/^\/tmp\/pc-native-[a-f0-9]{36}\/cross-root-target$/u);
|
||||
expect(f.outsideTarget!.startsWith(f.remoteCwd + "/")).toBe(false);
|
||||
expect(f.baseline.targets["@cross-root"]!.sha256).toBe(hash("outside sentinel"));
|
||||
});
|
||||
it("cleans only its admitted observer on a failed startup receipt and never publishes", async () => {
|
||||
const h = harness(); h.current.processes = { captured: false, root: null, journal: [], live: [] };
|
||||
await expect(bindRemoteNativeFixture(h.options)).rejects.toThrow("bootstrap_not_held");
|
||||
expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install", "close"]);
|
||||
});
|
||||
it("refuses action publication without a confirmed receipt channel", async () => {
|
||||
const h = harness(); h.override(r => r.op === "arm" ? { exitCode: 0, result: JSON.stringify({ ok: true, result: { armed: false, sealed: false } }) } : undefined);
|
||||
await expect(bindRemoteNativeFixture(h.options)).rejects.toThrow("receipt_channel_not_armed");
|
||||
expect(h.calls.map(c => c.request.op)).toEqual(["runtime-ready", "install", "wait", "arm", "close"]);
|
||||
});
|
||||
it("bounds malformed command output and does not replay an uncertain publish", async () => {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options);
|
||||
h.override(r => r.op === "publish" ? { exitCode: 0, result: "x".repeat(262145) } : undefined);
|
||||
await expect(f.publishAction("action.txt", "task")).rejects.toThrow("output_bound");
|
||||
await expect(f.publishAction("action.txt", "task")).rejects.toThrow("publish_bound");
|
||||
expect(h.calls.filter(c => c.request.op === "publish")).toHaveLength(1);
|
||||
});
|
||||
it("ships syntactically valid closed Node programs with exact binary and no provider env", async () => {
|
||||
const h = harness(); await bindRemoteNativeFixture(h.options);
|
||||
const install = h.calls.find(c => c.request.op === "install")!; const source = install.request.source as string;
|
||||
expect(() => new Script(source)).not.toThrow(); expect(source).not.toContain("__name(");
|
||||
const rpcQuoted = install.command.match(/ -e (.+) '[A-Za-z0-9+/=]+'$/su)![1]!;
|
||||
const rpc = rpcQuoted.slice(1, -1).replaceAll("'\\''", "'");
|
||||
expect(() => new Script(rpc)).not.toThrow();
|
||||
expect(rpc).not.toContain("startedAt+20000"); expect(install.timeout).toBeLessThanOrEqual(27); expect(rpc).toContain("r.timeoutMs-(Date.now()-startedAt)");
|
||||
expect(source).toContain("/proc/"); expect(source).toContain("workspaceWatch"); expect(source).toContain("finalReceipt.files");
|
||||
expect(install.command).toMatch(/^\/usr\/bin\/env -i PATH=\/usr\/bin:\/bin /u);
|
||||
expect(install.request.config.runnerdSha256).toBe(hash("runnerd"));
|
||||
expect(source).not.toMatch(/execSync|execFileSync/u);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cell deadline and cleanup bounds", () => {
|
||||
it("expires finish with 15s reserved, bounds SDK/socket/observer clocks, and handles late SDK failure", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(1_000_000);
|
||||
try {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options);
|
||||
await f.publishAction("action.txt", "task");
|
||||
const install = h.calls.find(c => c.request.op === "install")!, wait = h.calls.find(c => c.request.op === "wait")!;
|
||||
expect(wait.timeout).toBe(67); expect(wait.request.timeoutMs).toBe(67_000);
|
||||
expect(install.request.config.observerTtlMs).toBe(67_000); expect(install.timeout).toBe(25);
|
||||
let settled = false;
|
||||
const result = f.finish().then(() => { settled = true; return "unexpected pass"; }, error => { settled = true; return error.message; });
|
||||
await vi.advanceTimersByTimeAsync(66_999); expect(settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1); expect(await result).toContain("deadline");
|
||||
expect(Date.now()).toBe(h.options.deadlineAt - 15_000);
|
||||
h.rejectTerminal(new Error("late SDK close after host deadline")); await Promise.resolve();
|
||||
await f.close(); expect(h.calls.at(-1)!.request.op).toBe("close"); expect(h.calls.at(-1)!.timeout).toBe(10);
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it("shortens a late ordinary RPC and never gives it a fresh timeout window", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(1_000_000);
|
||||
try {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options);
|
||||
await vi.advanceTimersByTimeAsync(64_000);
|
||||
await f.snapshot("late-but-bounded"); const call = h.calls.at(-1)!;
|
||||
expect(call.timeout).toBe(3); expect(call.request.timeoutMs).toBe(3000);
|
||||
await vi.advanceTimersByTimeAsync(3000);
|
||||
const count = h.calls.length; await expect(f.snapshot("too-late")).rejects.toThrow("receipt_deadline"); expect(h.calls).toHaveLength(count);
|
||||
await f.close(); h.rejectTerminal(new Error("late SDK rejection")); await Promise.resolve();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
it("bounds cleanup after cell expiry and rejects finish immediately after explicit close", async () => {
|
||||
vi.useFakeTimers(); vi.setSystemTime(1_000_000);
|
||||
try {
|
||||
const h = harness(), f = await bindRemoteNativeFixture(h.options); await vi.advanceTimersByTimeAsync(82_000);
|
||||
h.override(r => r.op === "close" ? new Promise(() => {}) : undefined);
|
||||
const close = f.close().then(() => "unexpected", error => error.message);
|
||||
await vi.advanceTimersByTimeAsync(9999); expect(h.calls.at(-1)!.request.timeoutMs).toBe(10_000);
|
||||
await vi.advanceTimersByTimeAsync(1); expect(await close).toContain("deadline");
|
||||
await expect(f.finish()).rejects.toThrow("deadline"); h.rejectTerminal(new Error("late")); await Promise.resolve();
|
||||
const h2 = harness(), f2 = await bindRemoteNativeFixture(h2.options);
|
||||
await f2.close(); await expect(f2.finish()).rejects.toThrow("closed_before_receipt");
|
||||
h2.rejectTerminal(new Error("ordinary close ended socket")); await Promise.resolve();
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
});
|
||||
|
||||
describe("independent filesystem and process observations", () => {
|
||||
it.skipIf(process.platform !== "linux")("retains transient create/delete events and detects same-path parent replacement", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "remote-watch-")); const watcher = createRemoteTargetWatch(dir, "denied.txt");
|
||||
try {
|
||||
await writeFile(join(dir, "denied.txt"), "forbidden"); await rm(join(dir, "denied.txt"));
|
||||
await vi.waitFor(() => expect(watcher.snapshot().mutationCount).toBeGreaterThan(0));
|
||||
expect(watcher.snapshot().complete).toBe(true);
|
||||
await rename(dir, `${dir}-old`); await writeFile(dir, "replacement");
|
||||
expect(watcher.snapshot().complete).toBe(false);
|
||||
} finally { watcher.close(); await rm(dir, { recursive: true, force: true }); await rm(`${dir}-old`, { recursive: true, force: true }); }
|
||||
});
|
||||
it("marks lost filenames/watch errors incomplete", () => {
|
||||
let callback!: (_kind: string, filename: string | null) => void;
|
||||
const emitter = Object.assign(new EventEmitter(), { close: vi.fn() });
|
||||
const stat = { isDirectory: () => true, isSymbolicLink: () => false, dev: 1n, ino: 2n, mtimeNs: 3n, ctimeNs: 4n };
|
||||
const watcher = createRemoteTargetWatch("/test", "file", { watch: ((_path: unknown, cb: typeof callback) => { callback = cb; return emitter; }) as any, lstatSync: (() => stat) as any });
|
||||
callback("rename", null); expect(watcher.snapshot().complete).toBe(false); watcher.close();
|
||||
});
|
||||
it("parses Linux start ticks around unusual comm names and excludes shared/wrong-run daemons", () => {
|
||||
const fields = ["S", "1", "21", ...Array(16).fill("0"), "123456"];
|
||||
const p = parseRemoteProcStat(21, `21 (name with ) parens) ${fields.join(" ")}`, bootId);
|
||||
expect(p.startTicks).toBe("123456"); expect(isRemoteRunRoot(["/opt/paperclip-runnerd", "--run-id", "run", "--lifecycle-mode", "per_turn"], "run", p)).toBe(true);
|
||||
expect(isRemoteRunRoot(["/opt/paperclip-runnerd", "--run-id", "foreign", "--lifecycle-mode", "per_turn"], "run", p)).toBe(false);
|
||||
expect(isRemoteRunRoot(["/opt/paperclip-runnerd", "--run-id", "run", "--lifecycle-mode", "persistent"], "run", p)).toBe(false);
|
||||
expect(isRemoteRunRoot(["/opt/paperclip-runnerd", "--run-id", "run", "--lifecycle-mode", "per_turn"], "run", { ...p, group: 1 })).toBe(false);
|
||||
expect(parseRemoteProcStat(21, `21 (reused) ${fields.slice(0, -1).join(" ")} 999999`, bootId).startTicks).not.toBe(p.startTicks);
|
||||
});
|
||||
});
|
||||
|
||||
describe("actual generated observer state machine", () => {
|
||||
async function observerHarness(deferStartup = false, transformed?: { command: string; observer: string }) {
|
||||
const h = harness(); await bindRemoteNativeFixture(h.options);
|
||||
const install = h.calls.find(c => c.request.op === "install")!;
|
||||
if (transformed) {
|
||||
install.request.source = transformed.observer;
|
||||
install.command = transformed.command;
|
||||
}
|
||||
const { source, config } = install.request;
|
||||
const intervals: Array<() => void> = [], timers: Array<{ fn: () => void; ms: number }> = [];
|
||||
const proc = new Map<number, { ppid: number; group: number; ticks: string; argv: string[] }>([[21, { ppid: 1, group: 21, ticks: "100", argv: ["/workspace/.paperclip-runtime/paperclip-runner/bin/paperclip-runnerd", "--run-id", "run", "--environment-lease-id", "workspace-id", "--lifecycle-mode", "per_turn", "--state-dir", "/workspace/.paperclip-runtime/paperclip-runner/sessions/" + "a".repeat(64) + "/runner"] }]]);
|
||||
const files = new Map<string, Buffer>([[`${config.root}/observer.cjs`, Buffer.from(source)], [config.sentinel.path, Buffer.from(JSON.stringify({ version: 1, provider: "daytona", token: config.sentinel.token, companyId: "company", environmentId: "environment" }))]]);
|
||||
const watches: Array<{ path: string; callback: (_kind: string, name: string | null) => void; closed: boolean }> = [];
|
||||
const handlers: Array<(socket: any) => void> = [], children: any[] = [];
|
||||
const missing = () => { throw Object.assign(new Error("missing"), { code: "ENOENT" }); };
|
||||
const fds = new Map<number, string>(); let nextFd = 50, runtimeInode = 4n;
|
||||
const symbolicLinks = new Set<string>();
|
||||
const directories = new Set(["/tmp", "/workspace", "/workspace/.paperclip-runtime", "/workspace/.paperclip-runtime/paperclip-runner", "/workspace/.paperclip-runtime/paperclip-runner/sessions"]);
|
||||
if (!deferStartup) directories.add(config.root);
|
||||
const listeners = new Map<string, (socket: any) => void>();
|
||||
const fs = {
|
||||
constants: { O_RDONLY: 0, O_NOFOLLOW: 131072 },
|
||||
openSync(path: string, flags: number) { expect(flags).toBe(131072); if (!files.has(path)) return missing(); const fd = nextFd++; fds.set(fd, path); return fd; },
|
||||
closeSync(fd: number) { fds.delete(fd); },
|
||||
fstatSync(fd: number) { const value = fs.lstatSync(fds.get(fd)!); return { ...value, size: BigInt(value.size) }; },
|
||||
readFileSync(path: string | number, encoding?: string) {
|
||||
if (typeof path === "number") path = fds.get(path)!;
|
||||
let value: Buffer | undefined;
|
||||
if (path === "/proc/sys/kernel/random/boot_id") value = Buffer.from(bootId);
|
||||
else if (path.startsWith("/proc/")) {
|
||||
const [, , raw, field] = path.split("/"), p = proc.get(Number(raw)); if (!p) return missing();
|
||||
if (field === "stat") value = Buffer.from(`${raw} (runner) S ${p.ppid} ${p.group} ${Array(16).fill("0").join(" ")} ${p.ticks}`);
|
||||
if (field === "cmdline") value = Buffer.from(p.argv.join("\0") + "\0");
|
||||
if (field === "exe") value = Buffer.from("runnerd");
|
||||
} else value = files.get(path);
|
||||
if (!value) return missing(); return encoding ? value.toString() : value;
|
||||
},
|
||||
lstatSync(path: string) {
|
||||
const directory = directories.has(path);
|
||||
if (!directory && !files.has(path) && !symbolicLinks.has(path)) return missing();
|
||||
return { dev: 1n, ino: path === config.root ? 2n : path === "/workspace/.paperclip-runtime/paperclip-runner" ? runtimeInode : 3n, mtimeNs: 4n, ctimeNs: 5n, isDirectory: () => directory, isFile: () => !directory, isSymbolicLink: () => symbolicLinks.has(path), size: files.get(path)?.length ?? 0 };
|
||||
},
|
||||
realpathSync: (path: string) => path,
|
||||
readdirSync(path: string) { if (path === "/proc") return [...proc.keys()].map(String); if (path === "/workspace") return [".paperclip-runtime", ...[...files.keys(), ...symbolicLinks].filter(p => p.startsWith("/workspace/") && !p.slice(11).includes("/")).map(p => p.slice(11))]; if (path === "/workspace/.paperclip-runtime") return ["reusable-sandbox-lease.json", "paperclip-runner", ...[...files.keys()].filter(p => p.startsWith(path + "/") && !p.slice(path.length + 1).includes("/") && !p.endsWith("reusable-sandbox-lease.json")).map(p => p.slice(path.length + 1))]; if (path.startsWith("/workspace/.paperclip-runtime/paperclip-runner")) throw new Error("excluded runtime must not be traversed"); return []; },
|
||||
watch(path: string, options: unknown, callback?: (_kind: string, name: string | null) => void) {
|
||||
const entry = { path, callback: (callback ?? options) as (_kind: string, name: string | null) => void, closed: false }; watches.push(entry);
|
||||
return Object.assign(new EventEmitter(), { close: () => { entry.closed = true; } });
|
||||
},
|
||||
mkdirSync: vi.fn((path: string) => {
|
||||
if (!directories.has(path.slice(0, path.lastIndexOf("/")))) return missing();
|
||||
if (directories.has(path) || files.has(path)) throw new Error("EEXIST");
|
||||
directories.add(path);
|
||||
}),
|
||||
existsSync: (path: string) => directories.has(path) || files.has(path) || listeners.has(path),
|
||||
writeFileSync(path: string, content: string, opts: { flag: string }) {
|
||||
if (!directories.has(path.slice(0, path.lastIndexOf("/")))) return missing();
|
||||
if (opts.flag === "wx" && files.has(path)) throw new Error("EEXIST"); files.set(path, Buffer.from(content));
|
||||
for (const w of watches) if (!w.closed && path.slice(0, path.lastIndexOf("/")) === w.path) w.callback("rename", path.slice(w.path.length + 1));
|
||||
},
|
||||
rmSync: vi.fn(),
|
||||
};
|
||||
const server = {
|
||||
listen: vi.fn((path: string) => {
|
||||
if (!directories.has(path.slice(0, path.lastIndexOf("/")))) return missing();
|
||||
if (listeners.has(path)) throw new Error("EADDRINUSE");
|
||||
listeners.set(path, handlers.at(-1)!);
|
||||
}),
|
||||
close: vi.fn(() => listeners.clear()),
|
||||
};
|
||||
const net = { createServer(fn: (socket: any) => void) { handlers.push(fn); return server; } };
|
||||
const context = {
|
||||
require(name: string) { if (name === "node:fs") return fs; if (name === "node:net") return net; if (name === "node:child_process") return { spawn: vi.fn(() => { const child = Object.assign(new EventEmitter(), { pid: 88, exitCode: null, signalCode: null, kill: vi.fn() }); children.push(child); return child; }) }; if (name === "node:path") return { join: (...paths: string[]) => paths.join("/"), dirname: (path: string) => path.slice(0, path.lastIndexOf("/")), basename: (path: string) => path.slice(path.lastIndexOf("/") + 1) }; if (name === "node:crypto") return { createHash }; throw new Error("unexpected module"); },
|
||||
process: { argv: ["node", `${config.root}/observer.cjs`, Buffer.from(JSON.stringify(config)).toString("base64")], execPath: "/node", hrtime: { bigint: () => 12345n }, exit: vi.fn() },
|
||||
Buffer, __filename: `${config.root}/observer.cjs`,
|
||||
setInterval(fn: () => void) { intervals.push(fn); return 1; }, clearInterval: vi.fn(),
|
||||
setTimeout(fn: () => void, ms: number) { timers.push({ fn, ms }); return { unref() {} }; },
|
||||
};
|
||||
if (deferStartup) files.delete(`${config.root}/observer.cjs`);
|
||||
else new Script(source).runInNewContext(context);
|
||||
function request(op: string, args: Record<string, unknown> = {}) {
|
||||
const replies: any[] = [], socket = Object.assign(new EventEmitter(), { end: (value: string) => replies.push(JSON.parse(value)), destroy: vi.fn() });
|
||||
handlers[0]!(socket); socket.emit("data", Buffer.from(JSON.stringify({ op, nonce: config.nonce, ...args }) + "\n")); return replies;
|
||||
}
|
||||
return { request, proc, files, watches, fs, intervals, timers, config, handlers, children, symbolicLinks, context, server, directories, listeners, install: h.calls.find(c => c.request.op === "install")!, replaceRuntimeRoot() { runtimeInode = 999n; } };
|
||||
}
|
||||
async function generatedRpc(o: Awaited<ReturnType<typeof observerHarness>>, request: Record<string, unknown>, mutateSource = (source: string) => source) {
|
||||
const quoted = o.install.command.match(/ -e (.+) '[A-Za-z0-9+/=]+'$/su)![1]!;
|
||||
const source = quoted.slice(1, -1).replaceAll("'\\''", "'");
|
||||
const forwarded: string[] = [], connections: Array<{ client: any; observer: any }> = [];
|
||||
let output = "";
|
||||
const process = { argv: ["node", Buffer.from(JSON.stringify(request)).toString("base64")], execPath: "/node", exitCode: 0, exit: vi.fn(), stdout: { write: (value: string) => { output += value; } } };
|
||||
const spawn = vi.fn((_node: string, argv: string[]) => {
|
||||
expect(argv[0]).toBe(`${o.config.root}/observer.cjs`);
|
||||
// Execute the actual installed observer, using its actual serialized config.
|
||||
o.context.process.argv = ["node", ...argv];
|
||||
new Script(o.files.get(argv[0]!)!.toString()).runInNewContext(o.context);
|
||||
return { unref: vi.fn() };
|
||||
});
|
||||
const fs = { ...o.fs,
|
||||
readFileSync(path: string, encoding?: string) { return path === "/node" ? Buffer.from("node") : o.fs.readFileSync(path, encoding); } };
|
||||
const net = { connect(path: string) {
|
||||
expect(path).toBe(`${o.config.root}/control.sock`);
|
||||
const client: any = Object.assign(new EventEmitter(), { setTimeout: vi.fn(), destroy: vi.fn() });
|
||||
const handler = o.listeners.get(path);
|
||||
if (!handler) { queueMicrotask(() => client.emit("error", new Error("ECONNREFUSED"))); return client; }
|
||||
const observer: any = Object.assign(new EventEmitter(), {
|
||||
end(value: string) { client.emit("data", Buffer.from(value)); client.emit("end"); observer.emit("close"); },
|
||||
destroy: vi.fn(() => { client.emit("error", new Error("observer closed socket")); observer.emit("close"); }),
|
||||
});
|
||||
client.write = (value: string) => { forwarded.push(value); observer.emit("data", Buffer.from(value)); };
|
||||
connections.push({ client, observer }); handler(observer);
|
||||
queueMicrotask(() => client.emit("connect")); return client;
|
||||
} };
|
||||
new Script(mutateSource(source)).runInNewContext({ require(name: string) {
|
||||
if (name === "node:fs") return fs;
|
||||
if (name === "node:net") return net;
|
||||
if (name === "node:child_process") return { spawn };
|
||||
if (name === "node:crypto") return { createHash };
|
||||
throw new Error("unexpected RPC module");
|
||||
}, process, Buffer, setTimeout: (fn: () => void, ms: number) => {
|
||||
// Advance only the bounded readiness polls; retain watchdogs as inert VM timers.
|
||||
if (ms === 10 || ms === 50) queueMicrotask(fn);
|
||||
return { unref() {} };
|
||||
} });
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
return { output, process, forwarded, spawn, connections };
|
||||
}
|
||||
it("executes readiness and installation after the actual pinned tsx production transform", async () => {
|
||||
const modulePath = fileURLToPath(new URL("./remote-native-fixtures.ts", import.meta.url));
|
||||
const loaderPath = fileURLToPath(new URL("../../cli/node_modules/tsx/dist/loader.mjs", import.meta.url));
|
||||
const script = `
|
||||
import { bindRemoteNativeFixture } from ${JSON.stringify(modulePath)};
|
||||
const binding = ${JSON.stringify(binding)}, ready = ${JSON.stringify(readiness())};
|
||||
const lease = { id: binding.leaseId, companyId: binding.companyId, environmentId: binding.environmentId, heartbeatRunId: binding.runId,
|
||||
provider: 'daytona', providerLeaseId: binding.sandboxId, status: 'active', releasedAt: null,
|
||||
metadata: { sandboxId: binding.sandboxId, image: binding.image, reuseLease: false, remoteCwd: binding.remoteCwd,
|
||||
workspaceSentinel: { path: binding.remoteCwd+'/.paperclip-runtime/reusable-sandbox-lease.json', token: 'fixture-sentinel-token', result: 'written', runId: binding.runId, providerLeaseId: binding.sandboxId } } };
|
||||
let programs;
|
||||
const sandbox = { id: binding.sandboxId, labels: { 'paperclip-provider':'daytona','paperclip-company-id':binding.companyId,'paperclip-environment-id':binding.environmentId,'paperclip-run-id':binding.runId,'paperclip-reuse-lease':'false' },
|
||||
process: { async executeCommand(command) {
|
||||
const encoded = command.slice(command.lastIndexOf(" '")+2,-1), request = JSON.parse(Buffer.from(encoded,'base64'));
|
||||
if(request.op==='runtime-ready') return {exitCode:0,result:JSON.stringify({ok:true,result:ready})};
|
||||
if(request.op==='install') programs = { command, observer:request.source };
|
||||
return {exitCode:0,result:JSON.stringify({ok:true,result:request.op==='close'?{closed:true}:{}})};
|
||||
} } };
|
||||
try { await bindRemoteNativeFixture({ authority: ${JSON.stringify(authority)}, api:{get:async p=>p.includes('/environments/')?[lease]:lease}, daytona:{get:async()=>sandbox},
|
||||
sdkVersion:'0.203.0',nodeSha256:${JSON.stringify(hash("node"))},runnerdSha256:${JSON.stringify(hash("runnerd"))},targets:['result.txt'],actionFile:'action.txt',deadlineAt:Date.now()+82000 }); } catch {}
|
||||
if(!programs) throw Error('No captured generated programs');
|
||||
process.stdout.write(JSON.stringify(programs));
|
||||
`;
|
||||
const transformed = JSON.parse(execFileSync(process.execPath, ["--import", loaderPath, "--input-type=module", "-e", script], {
|
||||
env: { PATH: "/usr/bin:/bin", HOME: process.env.HOME, TMPDIR: process.env.TMPDIR, TSX_DISABLE_CACHE: "1" }, timeout: 10_000, maxBuffer: 256 * 1024, encoding: "utf8",
|
||||
}));
|
||||
expect(transformed.command).not.toContain("__name("); expect(transformed.observer).not.toContain("__name(");
|
||||
const o = await observerHarness(true, transformed);
|
||||
const ready = await generatedRpc(o, { ...o.install.request, op: "runtime-ready" });
|
||||
expect(JSON.parse(ready.output)).toEqual({ ok: true, result: readiness() });
|
||||
const installed = await generatedRpc(o, o.install.request);
|
||||
expect(installed.process.exitCode).toBe(0); expect(JSON.parse(installed.output).result.complete).toBe(true);
|
||||
const closed = await generatedRpc(o, { op: "close", root: o.config.root, nonce: o.config.nonce, nodeSha256: hash("node"), timeoutMs: 10_000 });
|
||||
expect(JSON.parse(closed.output)).toEqual({ ok: true, result: { closed: true } });
|
||||
o.timers.find(t => t.ms === 100)!.fn(); expect(o.watches.every(w => w.closed)).toBe(true);
|
||||
});
|
||||
it("executes the actual readiness probe without creating an observer, then revalidates its exact identity at install", async () => {
|
||||
const o = await observerHarness(true);
|
||||
const ready = await generatedRpc(o, { ...o.install.request, op: "runtime-ready" });
|
||||
expect(JSON.parse(ready.output)).toEqual({ ok: true, result: readiness() });
|
||||
expect(ready.spawn).not.toHaveBeenCalled(); expect(o.fs.mkdirSync).not.toHaveBeenCalled(); expect(o.watches).toHaveLength(0);
|
||||
o.replaceRuntimeRoot();
|
||||
const changed = await generatedRpc(o, o.install.request);
|
||||
expect(JSON.parse(changed.output).diagnostic.code).toBe("runtime_identity_changed");
|
||||
expect(changed.spawn).not.toHaveBeenCalled(); expect(o.fs.mkdirSync).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each(["absent", "foreign-run", "foreign-group", "ambiguous", "wrong-binary", "symlink", "disappeared"])("checks generated runtime readiness: %s", async variant => {
|
||||
const o = await observerHarness(true), runtimePath = "/workspace/.paperclip-runtime/paperclip-runner";
|
||||
if (variant === "absent") o.directories.delete(runtimePath);
|
||||
if (variant === "foreign-run") o.proc.get(21)!.argv[2] = "foreign";
|
||||
if (variant === "foreign-group") o.proc.get(21)!.group = 99;
|
||||
if (variant === "ambiguous") o.proc.set(22, { ...o.proc.get(21)!, group: 22 });
|
||||
if (variant === "symlink") o.symbolicLinks.add(runtimePath);
|
||||
if (variant === "disappeared") o.proc.clear();
|
||||
const request = { ...o.install.request, op: variant === "disappeared" ? "install" : "runtime-ready", config: { ...o.config, ...(variant === "wrong-binary" ? { runnerdSha256: hash("wrong") } : {}) } };
|
||||
const result = await generatedRpc(o, request), parsed = JSON.parse(result.output);
|
||||
if (["absent", "foreign-run", "foreign-group"].includes(variant)) expect(parsed).toEqual({ ok: true, result: { ready: false } });
|
||||
else expect(parsed).toEqual({ ok: false, diagnostic: { phase: request.op, code: { ambiguous: "ambiguous_run_root", "wrong-binary": "runtime_binary_identity", symlink: "runtime_root_identity", disappeared: "runtime_not_ready" }[variant] } });
|
||||
expect(result.spawn).not.toHaveBeenCalled(); expect(o.fs.mkdirSync).not.toHaveBeenCalled();
|
||||
});
|
||||
it("uses the closed read phase for actual generated socket errors", async () => {
|
||||
const o = await observerHarness(true);
|
||||
const read = await generatedRpc(o, { op: "read", root: o.config.root, nonce: o.config.nonce, nodeSha256: hash("node"), timeoutMs: 10_000, path: "result.txt" });
|
||||
expect(JSON.parse(read.output)).toEqual({ ok: false, diagnostic: { phase: "read", code: "socket_error" } });
|
||||
expect(read.spawn).not.toHaveBeenCalled();
|
||||
});
|
||||
it("executes generated install through the bounded observer socket, then closes the exact observer", async () => {
|
||||
const o = await observerHarness(true);
|
||||
expect(Buffer.byteLength(o.install.request.source)).toBeGreaterThan(8192);
|
||||
const installed = await generatedRpc(o, o.install.request);
|
||||
expect(installed.process.exitCode).toBe(0);
|
||||
const baseline = JSON.parse(installed.output);
|
||||
expect(baseline.ok).toBe(true); expect(baseline.result.complete).toBe(true);
|
||||
expect(baseline.result.processes.root).toMatchObject({ ...root, group: 21, state: "S" });
|
||||
// Feed the actual generated observer receipt through the real host reader,
|
||||
// including parseRemoteProcStat's extra fields and different key order.
|
||||
const h = harness(); h.override(request => request.op === "install" ? { exitCode: 0, result: installed.output } : undefined);
|
||||
const fixture = await bindRemoteNativeFixture(h.options);
|
||||
expect(fixture.baseline.processes.root).toEqual(baseline.result.processes.root);
|
||||
await fixture.close();
|
||||
expect(installed.spawn).toHaveBeenCalledTimes(1);
|
||||
expect(installed.forwarded.map(value => JSON.parse(value))).toEqual([{ op: "snapshot", nonce: o.config.nonce }]);
|
||||
expect(Buffer.byteLength(installed.forwarded[0]!)).toBeLessThan(8192);
|
||||
const closed = await generatedRpc(o, { op: "close", root: o.config.root, nonce: o.config.nonce, nodeSha256: hash("node"), timeoutMs: 10_000 });
|
||||
expect(closed.process.exitCode).toBe(0); expect(JSON.parse(closed.output)).toEqual({ ok: true, result: { closed: true } });
|
||||
expect(closed.spawn).not.toHaveBeenCalled();
|
||||
expect(closed.forwarded[0]).not.toContain('"source"'); expect(closed.forwarded[0]).not.toContain('"config"');
|
||||
expect(o.watches.length).toBeGreaterThan(0); expect(o.watches.every(w => w.closed)).toBe(true);
|
||||
expect(o.context.clearInterval).toHaveBeenCalled(); expect(o.server.close).toHaveBeenCalled();
|
||||
o.timers.find(t => t.ms === 100)!.fn();
|
||||
expect(closed.connections[0]!.observer.destroy).toHaveBeenCalled();
|
||||
expect(o.fs.rmSync).toHaveBeenCalledExactlyOnceWith(o.config.root, { recursive: true, force: true });
|
||||
expect(o.context.process.exit).toHaveBeenCalledExactlyOnceWith(0);
|
||||
});
|
||||
it("rejects a generated install mutant that omits its parent directory creation", async () => {
|
||||
const o = await observerHarness(true);
|
||||
const installed = await generatedRpc(o, o.install.request, source => {
|
||||
const mutant = source.replace("fs.mkdirSync(c.root,{mode:0o700});", "");
|
||||
expect(mutant).not.toBe(source); return mutant;
|
||||
});
|
||||
expect(installed.process.exitCode).toBe(2); expect(JSON.parse(installed.output).diagnostic).toEqual({ phase: "install", code: "remote_unknown" });
|
||||
expect(installed.spawn).not.toHaveBeenCalled(); expect(installed.connections).toHaveLength(0);
|
||||
expect(o.files.has(`${o.config.root}/observer.cjs`)).toBe(false);
|
||||
expect(o.directories.has(o.config.root)).toBe(false); expect(o.watches).toHaveLength(0);
|
||||
});
|
||||
it("rejects a generated observer mutant that never listens, even after handler registration", async () => {
|
||||
const o = await observerHarness(true);
|
||||
const source = o.install.request.source as string;
|
||||
const mutant = source.replace("server.listen(path.join(config.root,'control.sock'));", "");
|
||||
expect(mutant).not.toBe(source);
|
||||
const installed = await generatedRpc(o, { ...o.install.request, source: mutant });
|
||||
expect(installed.process.exitCode).toBe(2); expect(JSON.parse(installed.output).diagnostic).toEqual({ phase: "install", code: "socket_error" });
|
||||
expect(installed.spawn).toHaveBeenCalledTimes(1); expect(o.handlers).toHaveLength(1);
|
||||
expect(o.server.listen).not.toHaveBeenCalled(); expect(o.listeners.size).toBe(0);
|
||||
expect(installed.connections).toHaveLength(0); expect(installed.forwarded).toHaveLength(0);
|
||||
// A failed connection cannot close the unlistening observer. Its owned TTL still retires it.
|
||||
o.timers.find(t => t.ms > 1000)!.fn(); o.timers.find(t => t.ms === 100)!.fn();
|
||||
expect(o.watches.every(w => w.closed)).toBe(true);
|
||||
expect(o.fs.rmSync).toHaveBeenCalledExactlyOnceWith(o.config.root, { recursive: true, force: true });
|
||||
expect(o.context.process.exit).toHaveBeenCalledExactlyOnceWith(0);
|
||||
});
|
||||
it("still rejects an oversized control request and can close its observer afterward", async () => {
|
||||
const o = await observerHarness();
|
||||
const oversized = await generatedRpc(o, { op: "snapshot", root: o.config.root, nonce: o.config.nonce, nodeSha256: hash("node"), timeoutMs: 10_000, unexpected: "x".repeat(8192) });
|
||||
expect(oversized.process.exitCode).toBe(2); expect(JSON.parse(oversized.output).diagnostic).toEqual({ phase: "snapshot", code: "socket_error" });
|
||||
expect(oversized.connections[0]!.observer.destroy).toHaveBeenCalled();
|
||||
const closed = await generatedRpc(o, { op: "close", root: o.config.root, nonce: o.config.nonce, nodeSha256: hash("node"), timeoutMs: 10_000 });
|
||||
expect(JSON.parse(closed.output)).toEqual({ ok: true, result: { closed: true } });
|
||||
o.timers.find(t => t.ms === 100)!.fn();
|
||||
expect(o.watches.every(w => w.closed)).toBe(true); expect(o.context.process.exit).toHaveBeenCalledExactlyOnceWith(0);
|
||||
});
|
||||
it("acknowledges receipt-channel readiness only after the long waiter connects", async () => {
|
||||
const o = await observerHarness(); const arm = o.request("arm"); expect(arm).toHaveLength(0);
|
||||
o.request("wait"); expect(arm).toEqual([{ ok: true, result: { armed: true, sealed: false } }]);
|
||||
o.proc.set(1, { ppid: 0, group: 1, ticks: "1", argv: ["/sbin/init"] });
|
||||
expect(o.request("snapshot")[0].result.processes.captured).toBe(true);
|
||||
});
|
||||
it("arms exact remote root then seals drained no-live proof and retained bytes", async () => {
|
||||
const o = await observerHarness(); expect(o.request("snapshot")[0].result.processes.captured).toBe(true);
|
||||
const wait = o.request("wait"); expect(wait).toHaveLength(0);
|
||||
expect(o.request("publish", { path: "action.txt", text: "do task" })[0].ok).toBe(true);
|
||||
o.fs.writeFileSync("/workspace/result.txt", "exact 🪴\n", { flag: "wx" });
|
||||
o.proc.set(22, { ppid: 21, group: 21, ticks: "200", argv: ["/node"] }); o.intervals[0]!();
|
||||
o.proc.clear(); o.intervals[0]!(); expect(wait).toHaveLength(0); // Watch drain is mandatory.
|
||||
o.timers.find(t => t.ms === 100)!.fn();
|
||||
const final = wait[0].result;
|
||||
expect(final.complete).toBe(true); expect(final.processes.live).toEqual([]); expect(final.processes.journal.map((p: any) => p.pid)).toEqual([21, 22]);
|
||||
expect(Buffer.from(final.files["result.txt"], "base64").toString()).toBe("exact 🪴\n");
|
||||
expect(final.watcher.workspaceMutationCount).toBe(1); expect(final.workspace["action.txt"]).toBeUndefined(); expect(final.setup.sha256).toBe(hash("do task"));
|
||||
expect(o.watches.every(w => w.closed)).toBe(true);
|
||||
});
|
||||
it("links the attached client to the exact run and writes the marker only after independent child exit", async () => {
|
||||
const o = await observerHarness(); o.request("snapshot");
|
||||
const config = { marker: "result.txt", markerText: "settled", delayMs: 500, clientNonce: "test-client-nonce" };
|
||||
const fixture = o.request("attached", config)[0].result;
|
||||
o.proc.set(23, { ppid: 21, group: 21, ticks: "300", argv: ["/node", fixture.clientScript, fixture.clientSocket, config.clientNonce] });
|
||||
const replies: any[] = [], socket = Object.assign(new EventEmitter(), { end: (value: string) => replies.push(JSON.parse(value)), destroy: vi.fn() });
|
||||
o.handlers[1]!(socket); socket.emit("data", Buffer.from(JSON.stringify({ nonce: config.clientNonce, pid: 23 }) + "\n"));
|
||||
expect(o.children).toHaveLength(1); expect(replies).toHaveLength(0); expect(o.files.has("/workspace/result.txt")).toBe(false);
|
||||
o.children[0].exitCode = 0; o.children[0].emit("exit", 0, null);
|
||||
expect(replies).toEqual([{ code: 0 }]); expect(o.files.get("/workspace/result.txt")?.toString()).toBe("settled");
|
||||
o.proc.delete(23); const a = o.request("snapshot")[0].result.attached;
|
||||
expect(a.commandExit.code).toBe(0); expect(BigInt(a.commandExit.observedMonotonicNs)).toBeLessThanOrEqual(BigInt(a.markerWrittenMonotonicNs));
|
||||
expect(a.clientExitedAtMs).not.toBeNull(); expect(a.connections).toBe(1);
|
||||
});
|
||||
it("never starts attached work for a same-argv client outside the captured run", async () => {
|
||||
const o = await observerHarness(); o.request("snapshot");
|
||||
const config = { marker: "result.txt", markerText: "settled", delayMs: 500, clientNonce: "test-client-nonce" };
|
||||
const fixture = o.request("attached", config)[0].result;
|
||||
o.proc.set(23, { ppid: 1, group: 23, ticks: "300", argv: ["/node", fixture.clientScript, fixture.clientSocket, config.clientNonce] });
|
||||
const socket = Object.assign(new EventEmitter(), { end: vi.fn(), destroy: vi.fn() });
|
||||
o.handlers[1]!(socket); socket.emit("data", Buffer.from(JSON.stringify({ nonce: config.clientNonce, pid: 23 }) + "\n"));
|
||||
expect(o.children).toHaveLength(0); expect(socket.destroy).toHaveBeenCalled();
|
||||
expect(o.request("snapshot")[0].result.attached.failure).toBe("client_rejected");
|
||||
});
|
||||
it("scopes actual runtime symlinks/state churn out while retaining sentinel and sibling coverage", async () => {
|
||||
const o = await observerHarness();
|
||||
o.symbolicLinks.add("/workspace/.paperclip-runtime/paperclip-runner/provider-pack");
|
||||
o.files.set("/workspace/.paperclip-runtime/paperclip-runner/bin/paperclip-runnerd", Buffer.alloc(100000));
|
||||
o.fs.writeFileSync("/workspace/.paperclip-runtime/paperclip-runner/sessions/state.json", "runtime churn", { flag: "wx" });
|
||||
const before = o.request("snapshot")[0].result;
|
||||
expect(before.complete).toBe(true); expect(before.watcher.workspaceMutationCount).toBe(0);
|
||||
expect(Object.keys(before.workspace)).toContain(".paperclip-runtime/reusable-sandbox-lease.json");
|
||||
expect(Object.keys(before.workspace).some(p => p.startsWith(".paperclip-runtime/paperclip-runner"))).toBe(false);
|
||||
expect(before.scope.excludedRuntime.ino).toBe("4"); expect(before.scope.observedPrpEnvironmentLeaseId).toBe("workspace-id");
|
||||
expect(before.scope.prpEnvironmentLeaseIdVerified).toBe(false);
|
||||
o.fs.writeFileSync("/workspace/.paperclip-runtime/user-file", "not runtime internal", { flag: "wx" });
|
||||
const after = o.request("snapshot")[0].result;
|
||||
expect(after.watcher.workspaceMutationCount).toBe(1); expect(after.workspace[".paperclip-runtime/user-file"]).toBe(hash("not runtime internal"));
|
||||
});
|
||||
it("rejects runtime root replacement, foreign workspace symlinks and sentinel tampering", async () => {
|
||||
const replaced = await observerHarness(); replaced.replaceRuntimeRoot(); expect(replaced.request("snapshot")[0].ok).toBe(false);
|
||||
const linked = await observerHarness(); linked.symbolicLinks.add("/workspace/user-link"); expect(linked.request("snapshot")[0].ok).toBe(false);
|
||||
const sentinel = await observerHarness(); sentinel.files.set(sentinel.config.sentinel.path, Buffer.from(JSON.stringify({ token: "foreign" })));
|
||||
expect(sentinel.request("snapshot")[0].ok).toBe(false);
|
||||
});
|
||||
it("marks PID reuse incomplete rather than mistaking a new process for retired authority", async () => {
|
||||
const o = await observerHarness(); o.request("snapshot"); const wait = o.request("wait");
|
||||
o.proc.set(21, { ppid: 1, group: 99, ticks: "999", argv: ["/unrelated"] }); o.intervals[0]!(); o.timers.find(t => t.ms === 100)!.fn();
|
||||
expect(wait[0].result.complete).toBe(false); expect(wait[0].result.processes.root.startTicks).toBe("100");
|
||||
});
|
||||
it("counts transient workspace create/delete and rejects changed setup-file bytes", async () => {
|
||||
const o = await observerHarness(); o.request("snapshot");
|
||||
o.fs.writeFileSync("/workspace/transient.txt", "not allowed", { flag: "wx" }); o.files.delete("/workspace/transient.txt");
|
||||
for (const w of o.watches) if (w.path === "/workspace") w.callback("rename", "transient.txt");
|
||||
const snapshot = o.request("snapshot")[0].result;
|
||||
expect(snapshot.workspace["transient.txt"]).toBeUndefined(); expect(snapshot.watcher.workspaceMutationCount).toBe(2);
|
||||
o.request("publish", { path: "action.txt", text: "approved" }); o.files.set("/workspace/action.txt", Buffer.from("replacement"));
|
||||
expect(o.request("snapshot")[0].ok).toBe(false);
|
||||
});
|
||||
it("rejects ambiguous run roots and malformed observed PRP identifiers", async () => {
|
||||
const o = await observerHarness(); const p = o.proc.get(21)!;
|
||||
o.proc.set(22, { ...p, group: 22, ticks: "200" }); expect(o.request("snapshot")[0].result.complete).toBe(false);
|
||||
const other = await observerHarness(); other.proc.get(21)!.argv[4] = "bad value with spaces";
|
||||
expect(other.request("snapshot")[0].ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,488 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { watch, lstatSync } from "node:fs";
|
||||
import { posix } from "node:path";
|
||||
|
||||
export const REMOTE_FIXTURE_DAYTONA_SDK_VERSION = "0.203.0";
|
||||
const NODE = "/opt/paperclip-runner/provider-pack/node_modules/node/bin/node";
|
||||
const MAX_OUTPUT = 256 * 1024;
|
||||
const TEARDOWN_RESERVE_MS = 15_000;
|
||||
const LEASE_READMISSION_BUDGET_MS = 10_000;
|
||||
const RUNTIME_READY_BUDGET_MS = 12_000;
|
||||
const INSTALL_BUDGET_MS = 27_000;
|
||||
// Lease activation can arrive late. Reserve each pre-install operation as well
|
||||
// as installation and teardown; the caller subtracts this from the same deadline.
|
||||
export const REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS = LEASE_READMISSION_BUDGET_MS
|
||||
+ RUNTIME_READY_BUDGET_MS + INSTALL_BUDGET_MS + TEARDOWN_RESERVE_MS;
|
||||
const CLOSE_GRACE_MS = 10_000;
|
||||
// createRunnerdBackend stages its verified executable, pack symlink, mutable
|
||||
// sessions, homes and injected context beneath this exact path. Qualification
|
||||
// covers user workspace files, not these controller/provider runtime internals.
|
||||
// The sentinel and all other .paperclip-runtime entries remain in scope.
|
||||
const RUNTIME_RELATIVE = ".paperclip-runtime/paperclip-runner";
|
||||
const digest = (value: string) => `sha256:${createHash("sha256").update(value).digest("hex")}`;
|
||||
const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
const fail = (condition: unknown, code: string): void => { if (!condition) throw new Error(`remote_native_fixture:${code}`); };
|
||||
const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
|
||||
const id = (value: string) => /^[a-zA-Z0-9_-]{1,128}$/u.test(value);
|
||||
function relative(value: string): string {
|
||||
fail(value.length <= 240 && /^[a-zA-Z0-9._/-]+$/u.test(value) && !value.startsWith("/") && value.split("/").every(part => part !== "" && part !== "." && part !== ".."), "unsafe_relative_target");
|
||||
return value;
|
||||
}
|
||||
// Only closed diagnostic enums cross the remote boundary; SDK errors and output
|
||||
// are never retained. These diagnostics explain failed evidence, not qualification.
|
||||
const RPC_PHASES = ["runtime-ready", "install", "wait", "close", "arm", "publish", "snapshot", "attached", "read"] as const;
|
||||
const RPC_CODES = ["node_identity", "sentinel_type", "sentinel", "cwd", "runtime_root_identity", "runtime_binary_identity", "proc_bound", "ambiguous_run_root", "runtime_not_ready", "runtime_identity_changed", "invalid_proc_identity", "invalid_proc_fields", "socket_error", "socket_timeout", "output_bound", "rpc_deadline", "remote_unknown", "transport_failure", "invalid_response", "readiness_deadline"] as const;
|
||||
type RpcPhase = typeof RPC_PHASES[number];
|
||||
type RpcCode = typeof RPC_CODES[number];
|
||||
interface RpcDiagnostic { phase: RpcPhase; code: RpcCode }
|
||||
class RemoteFixtureError extends Error {
|
||||
constructor(message: string, readonly diagnostic: RpcDiagnostic, options?: ErrorOptions) { super(message, options); }
|
||||
}
|
||||
export function remoteNativeFixtureDiagnostics(error: unknown): RpcDiagnostic[] {
|
||||
const result: RpcDiagnostic[] = [];
|
||||
for (let current = error, depth = 0; current instanceof Error && depth < 3; current = current.cause, depth++) {
|
||||
if (current instanceof RemoteFixtureError) result.push({ ...current.diagnostic });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export interface RemoteNativeAuthority { companyId: string; environmentId: string; runId: string; leaseId: string; sandboxId: string; image: string }
|
||||
export interface RemoteNativeBinding extends RemoteNativeAuthority { remoteCwd: string }
|
||||
export interface RemoteProcessIdentity { pid: number; ppid: number; startTicks: string; bootId: string }
|
||||
export interface RemoteNativeSnapshot {
|
||||
binding: RemoteNativeBinding;
|
||||
observedAtMs: number;
|
||||
observedMonotonicNs: string;
|
||||
receivedAtMs: number;
|
||||
complete: boolean;
|
||||
workspace: Record<string, string>;
|
||||
targets: Record<string, { absent: boolean; sha256: string | null; parent: { dev: string; ino: string }; mutationCount: number; complete: boolean }>;
|
||||
watcher: { complete: boolean; targetMutationCount: number; workspaceMutationCount: number };
|
||||
processes: { captured: boolean; root: RemoteProcessIdentity | null; journal: RemoteProcessIdentity[]; live: number[] };
|
||||
scope: {
|
||||
kind: "user_workspace";
|
||||
excludedRuntime: { relativePath: string; absolutePath: string; dev: string; ino: string; runnerExecutableSha256: string };
|
||||
observedPrpEnvironmentLeaseId: string;
|
||||
prpEnvironmentLeaseIdVerified: false;
|
||||
};
|
||||
setup: { path: string; sha256: string | null; published: boolean };
|
||||
attached: { connections: number; failure: string | null; commandExit: { code: number; observedAtMs: number; observedMonotonicNs: string } | null; markerWrittenAtMs: number | null; markerWrittenMonotonicNs: string | null; clientExitedAtMs: number | null; clientExitedMonotonicNs: string | null } | null;
|
||||
}
|
||||
/** Structural subset of pinned SDK0.203.0; caller supplies its authenticated
|
||||
* client. No create/list/delete or arbitrary remote command API is exposed. */
|
||||
export interface RemoteFixtureDaytona {
|
||||
get(id: string): Promise<{ id: string; labels?: Record<string, string>; process: {
|
||||
executeCommand(command: string, cwd?: string, env?: Record<string, string>, timeout?: number): Promise<{ exitCode: number; result: string }>;
|
||||
} }>;
|
||||
}
|
||||
export interface RemoteFixtureApi { get<T>(path: string, options?: { timeout: number }): Promise<T> }
|
||||
|
||||
/** Linux /proc identity uses boot ID + start ticks, never PID alone. */
|
||||
export function parseRemoteProcStat(pid: number, stat: string, bootId: string): RemoteProcessIdentity & { group: number; state: string } {
|
||||
const close = stat.lastIndexOf(") ");
|
||||
if (!Number.isSafeInteger(pid) || pid < 2 || close < 0 || !stat.startsWith(`${pid} (`) || !/^[a-f0-9-]{36}$/u.test(bootId)) throw new Error("invalid_proc_identity");
|
||||
const fields = stat.slice(close + 2).trim().split(/\s+/u);
|
||||
if (!/^\d+$/u.test(fields[19] ?? "") || !/^\d+$/u.test(fields[1] ?? "") || !/^\d+$/u.test(fields[2] ?? "")) throw new Error("invalid_proc_fields");
|
||||
return { pid, ppid: Number(fields[1]), group: Number(fields[2]), state: fields[0]!, startTicks: fields[19]!, bootId };
|
||||
}
|
||||
export function isRemoteRunRoot(argv: string[], runId: string, process: RemoteProcessIdentity & { group: number }): boolean {
|
||||
if (!/^[a-zA-Z0-9_-]{1,128}$/u.test(runId) || process.group !== process.pid || !argv[0]?.endsWith("/paperclip-runnerd")) return false;
|
||||
return [["--run-id", runId], ["--lifecycle-mode", "per_turn"]].every(([flag, value]) => {
|
||||
const at = argv.indexOf(flag!); return at > 0 && argv.lastIndexOf(flag!) === at && argv[at + 1] === value;
|
||||
});
|
||||
}
|
||||
/** Shared by the real remote observer and local deterministic tests. */
|
||||
export function createRemoteTargetWatch(directory: string, name: string, io = { watch, lstatSync }) {
|
||||
const before = io.lstatSync(directory, { bigint: true });
|
||||
if (!before.isDirectory() || before.isSymbolicLink()) throw new Error("unsafe_watch_parent");
|
||||
let complete = true, mutations = 0, events = 0, sealed = false;
|
||||
const watcher = io.watch(directory, (_kind, filename) => {
|
||||
if (sealed) return;
|
||||
events++;
|
||||
if (filename === null || events > 4096) complete = false;
|
||||
else if (String(filename) === name) mutations++;
|
||||
});
|
||||
watcher.on("error", () => { complete = false; });
|
||||
return {
|
||||
snapshot() {
|
||||
let deliveryComplete = true;
|
||||
try {
|
||||
const after = io.lstatSync(directory, { bigint: true });
|
||||
if (!after.isDirectory() || after.isSymbolicLink() || after.dev !== before.dev || after.ino !== before.ino) complete = false;
|
||||
if ((after.ctimeNs !== before.ctimeNs || after.mtimeNs !== before.mtimeNs) && events === 0) deliveryComplete = false;
|
||||
} catch { complete = false; }
|
||||
return { complete: complete && deliveryComplete, mutationCount: mutations, parent: { dev: String(before.dev), ino: String(before.ino) } };
|
||||
},
|
||||
close() { this.snapshot(); sealed = true; watcher.close(); },
|
||||
};
|
||||
}
|
||||
|
||||
// Only this closed Node program executes through the SDK. The observer has no
|
||||
// general command endpoint. Its control nonce is never given to the provider.
|
||||
const OBSERVER = String.raw`
|
||||
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),net=require('node:net'),cp=require('node:child_process');
|
||||
const config=JSON.parse(Buffer.from(process.argv[2],'base64').toString());
|
||||
const parseStat=PARSE_STAT;const runRoot=RUN_ROOT;const watchTarget=WATCH_TARGET;
|
||||
const hash=x=>'sha256:'+crypto.createHash('sha256').update(x).digest('hex');
|
||||
const cwdStat=fs.lstatSync(config.binding.remoteCwd,{bigint:true}),rootStat=fs.lstatSync(config.root,{bigint:true}),scriptStat=fs.lstatSync(__filename,{bigint:true}),scriptHash=hash(fs.readFileSync(__filename));
|
||||
const runtimeRoot=path.join(config.binding.remoteCwd,config.runtimeRelative),runtimeStat=fs.lstatSync(runtimeRoot,{bigint:true});if(!runtimeStat.isDirectory()||runtimeStat.isSymbolicLink()||fs.realpathSync(runtimeRoot)!==runtimeRoot)throw Error('runtime_root_identity');let observedPrpEnvironmentLeaseId=null;
|
||||
const boot=fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim();
|
||||
const targets=new Map();let complete=true,sealed=false,root=null,attached=null,child=null,client=null,childTimer=null;
|
||||
const journal=new Map(),sockets=new Set(),waiters=new Set(),armWaiters=new Set();let observedRootCount=0,publishedHash=null,finalReceipt=null,retiring=false;
|
||||
function identity(pid){return parseStat(pid,fs.readFileSync('/proc/'+pid+'/stat','utf8'),boot)}
|
||||
function table(){const ids=fs.readdirSync('/proc').filter(x=>/^\d+$/.test(x)&&Number(x)>1);if(ids.length>4096)throw Error('process_bound');return ids.flatMap(x=>{try{return [identity(Number(x))]}catch(e){if(e.code==='ENOENT'||e.code==='ESRCH')return [];throw e}})}
|
||||
function sample(){
|
||||
const all=table();const candidates=[];
|
||||
for(const p of all){if(p.state==='Z')continue;let argv;try{argv=fs.readFileSync('/proc/'+p.pid+'/cmdline').toString().split('\0').filter(Boolean)}catch(e){if(e.code==='ENOENT'||e.code==='ESRCH')continue;throw e}
|
||||
if(runRoot(argv,config.binding.runId,p)){const at=argv.indexOf('--environment-lease-id'),stateAt=argv.indexOf('--state-dir');if(at<1||argv.lastIndexOf('--environment-lease-id')!==at||!/^[-a-zA-Z0-9._:]{1,256}$/.test(argv[at+1]??''))throw Error('process_prp_identity_shape');if(argv[0]!==path.join(runtimeRoot,'bin','paperclip-runnerd')||stateAt<1||argv.lastIndexOf('--state-dir')!==stateAt||!argv[stateAt+1]?.startsWith(runtimeRoot+'/sessions/')||!/^([a-f0-9]{64})\/runner$/.test(argv[stateAt+1].slice((runtimeRoot+'/sessions/').length)))throw Error('process_runtime_binding');if(observedPrpEnvironmentLeaseId!==null&&observedPrpEnvironmentLeaseId!==argv[at+1])throw Error('process_prp_identity_changed');observedPrpEnvironmentLeaseId=argv[at+1];candidates.push(p);}}
|
||||
if(candidates.length>1)complete=false;
|
||||
if(!root&&candidates.length===1){if(hash(fs.readFileSync('/proc/'+candidates[0].pid+'/exe'))!==config.runnerdSha256)throw Error('runner_binary_identity');root=candidates[0];journal.set(root.pid,root);observedRootCount++;}
|
||||
if(root&&candidates.some(p=>p.pid!==root.pid||p.startTicks!==root.startTicks))complete=false;
|
||||
let changed=true;while(changed){changed=false;for(const p of all){const parent=journal.get(p.ppid);if(!journal.has(p.pid)&&((parent&&all.some(q=>q.pid===parent.pid&&q.startTicks===parent.startTicks))||(root&&p.group===root.pid))){if(journal.size>=512)throw Error('journal_bound');journal.set(p.pid,p);changed=true;}}}
|
||||
if(all.some(p=>journal.has(p.pid)&&journal.get(p.pid).startTicks!==p.startTicks))complete=false;
|
||||
const live=all.filter(p=>journal.get(p.pid)?.startTicks===p.startTicks&&p.state!=='Z').map(p=>p.pid);
|
||||
if(client&&!all.some(p=>p.pid===client.pid&&p.startTicks===client.startTicks&&p.state!=='Z')&&attached&&!attached.clientExitedAtMs){attached.clientExitedAtMs=Date.now();attached.clientExitedMonotonicNs=process.hrtime.bigint().toString();}
|
||||
return {captured:root!==null,root,journal:[...journal.values()],live};
|
||||
}
|
||||
function guard(){const rs=fs.lstatSync(runtimeRoot,{bigint:true});if(!rs.isDirectory()||rs.isSymbolicLink()||rs.dev!==runtimeStat.dev||rs.ino!==runtimeStat.ino||fs.realpathSync(runtimeRoot)!==runtimeRoot)throw Error('runtime_root_replaced');const s=fs.lstatSync(config.root,{bigint:true});if(s.dev!==rootStat.dev||s.ino!==rootStat.ino||!s.isDirectory()||s.isSymbolicLink()||hash(fs.readFileSync(__filename))!==scriptHash||fs.lstatSync(__filename,{bigint:true}).ino!==scriptStat.ino)throw Error('observer_identity_changed');
|
||||
const st=fs.lstatSync(config.sentinel.path);if(!st.isFile()||st.isSymbolicLink()||st.size>16384||fs.realpathSync(config.sentinel.path)!==config.sentinel.path)throw Error('sentinel_type');const sentinel=JSON.parse(fs.readFileSync(config.sentinel.path,'utf8'));if(sentinel.version!==1||sentinel.provider!=='daytona'||sentinel.token!==config.sentinel.token||sentinel.companyId!==config.binding.companyId||sentinel.environmentId!==config.binding.environmentId)throw Error('sentinel_changed');
|
||||
const c=fs.lstatSync(config.binding.remoteCwd,{bigint:true});if(c.dev!==cwdStat.dev||c.ino!==cwdStat.ino||!c.isDirectory()||c.isSymbolicLink()||fs.realpathSync(config.binding.remoteCwd)!==config.binding.remoteCwd)throw Error('workspace_replaced');}
|
||||
function readSafe(p){const fd=fs.openSync(p,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);try{const before=fs.fstatSync(fd,{bigint:true});if(!before.isFile()||before.size>65536n)throw Error('file_bound_or_type');const bytes=fs.readFileSync(fd),after=fs.fstatSync(fd,{bigint:true}),named=fs.lstatSync(p,{bigint:true});if(before.dev!==named.dev||before.ino!==named.ino||named.isSymbolicLink()||before.size!==after.size||before.mtimeNs!==after.mtimeNs||BigInt(bytes.length)!==before.size)throw Error('file_changed');return bytes}finally{fs.closeSync(fd)}}
|
||||
function file(p){try{const s=fs.lstatSync(p);if(s.isSymbolicLink()||!s.isFile()||s.size>65536)throw Error('file_bound_or_type');return {absent:false,sha256:hash(readSafe(p))}}catch(e){if(e.code==='ENOENT')return {absent:true,sha256:null};throw e}}
|
||||
function workspace(){const result={};let count=0,bytes=0;function visit(dir,prefix){for(const name of fs.readdirSync(dir).sort()){if(++count>512)throw Error('workspace_entry_bound');const full=path.join(dir,name),rel=prefix+name,s=fs.lstatSync(full);if(rel===config.runtimeRelative)continue;if(rel===config.actionFile){if(!publishedHash||file(full).sha256!==publishedHash)throw Error('setup_file_changed');continue;}if(s.isSymbolicLink())throw Error('workspace_symlink');if(s.isDirectory()){result[rel]='directory';visit(full,rel+'/')}else if(s.isFile()){bytes+=s.size;if(s.size>65536||bytes>4194304)throw Error('workspace_byte_bound');result[rel]=hash(readSafe(full))}else throw Error('workspace_special_file')}}visit(config.binding.remoteCwd,'');return result}
|
||||
function snapshot(){guard();verifyWorkspaceWatchRoots();const processes=sample(),out={};let watchComplete=complete,total=0;for(const [name,t] of targets){const status=t.watch.snapshot();out[name]={...file(t.path),...status};watchComplete&&=status.complete;total+=status.mutationCount}return {binding:config.binding,observedAtMs:Date.now(),observedMonotonicNs:process.hrtime.bigint().toString(),complete:complete&&watchComplete,workspace:workspace(),targets:out,watcher:{complete:watchComplete,targetMutationCount:total,workspaceMutationCount},processes,scope:{kind:'user_workspace',excludedRuntime:{relativePath:config.runtimeRelative,absolutePath:runtimeRoot,dev:String(runtimeStat.dev),ino:String(runtimeStat.ino),runnerExecutableSha256:config.runnerdSha256},observedPrpEnvironmentLeaseId,prpEnvironmentLeaseIdVerified:false},setup:{path:config.actionFile,sha256:publishedHash,published:publishedHash!==null},attached}}
|
||||
for(const name of config.targets){const p=path.join(config.binding.remoteCwd,name);if(fs.realpathSync(path.dirname(p))!==path.dirname(p))throw Error('target_parent_symlink');targets.set(name,{path:p,watch:watchTarget(path.dirname(p),path.basename(p),{watch:fs.watch,lstatSync:fs.lstatSync})})}
|
||||
if(config.crossRoot){const p=path.join(config.root,'cross-root-target');fs.writeFileSync(p,config.crossRoot.initialText,{flag:'wx',mode:0o600});targets.set('@cross-root',{path:p,watch:watchTarget(config.root,'cross-root-target',{watch:fs.watch,lstatSync:fs.lstatSync})})}
|
||||
let workspaceMutationCount=0;const directoryWatches=[];
|
||||
function watchDirectory(directory,prefix=''){if(directoryWatches.length>=512)throw Error('watch_directory_bound');const before=fs.lstatSync(directory,{bigint:true});if(!before.isDirectory()||before.isSymbolicLink())throw Error('watch_directory_identity');const handle=fs.watch(directory,(_kind,name)=>{if(name===null){complete=false;return}const relative=prefix+String(name);if(relative===config.runtimeRelative)return;if(relative===config.actionFile){try{if(!publishedHash||file(path.join(config.binding.remoteCwd,config.actionFile)).sha256!==publishedHash)complete=false}catch{complete=false}return}workspaceMutationCount++;if(workspaceMutationCount>4096)complete=false;try{if(fs.lstatSync(path.join(directory,String(name))).isDirectory())complete=false}catch(e){if(e.code!=='ENOENT')complete=false}});handle.on('error',()=>{complete=false});directoryWatches.push({directory,before,handle});for(const name of fs.readdirSync(directory)){const rel=prefix+name;if(rel===config.runtimeRelative)continue;const full=path.join(directory,name),s=fs.lstatSync(full);if(s.isSymbolicLink())throw Error('workspace_symlink');if(s.isDirectory())watchDirectory(full,rel+'/')}}
|
||||
watchDirectory(config.binding.remoteCwd);
|
||||
const workspaceWatch={close(){for(const item of directoryWatches)item.handle.close()}};
|
||||
function verifyWorkspaceWatchRoots(){for(const item of directoryWatches){const after=fs.lstatSync(item.directory,{bigint:true});if(after.dev!==item.before.dev||after.ino!==item.before.ino||!after.isDirectory()||after.isSymbolicLink())throw Error('workspace_watch_root_replaced')}}
|
||||
function publicSnapshot(){const result=snapshot();if(result.attached)result.attached={connections:attached.connections,failure:attached.failure,commandExit:attached.commandExit,markerWrittenAtMs:attached.markerWrittenAtMs,markerWrittenMonotonicNs:attached.markerWrittenMonotonicNs,clientExitedAtMs:attached.clientExitedAtMs,clientExitedMonotonicNs:attached.clientExitedMonotonicNs};return result}
|
||||
function seal(){if(sealed)return;sealed=true;workspaceWatch.close();for(const t of targets.values())t.watch.close();clearInterval(observer);finalReceipt=publicSnapshot();finalReceipt.files={};for(const [name,t] of targets){if(!file(t.path).absent)finalReceipt.files[name]=readSafe(t.path).toString('base64');}if(Buffer.byteLength(JSON.stringify(finalReceipt))>250000){finalReceipt.complete=false;finalReceipt.files={};}if(child&&child.exitCode===null&&child.signalCode===null)finalReceipt.complete=false;for(const socket of waiters)socket.end(JSON.stringify({ok:true,result:finalReceipt})+'\n');waiters.clear();setTimeout(()=>shutdown(null),250);}
|
||||
const observer=setInterval(()=>{try{const p=sample();if(p.captured&&p.live.length===0&&!retiring){retiring=true;setTimeout(()=>{try{const end=sample();if(end.live.length===0)seal();else retiring=false}catch{complete=false}},100)}}catch{complete=false}},25);
|
||||
const server=net.createServer(socket=>{sockets.add(socket);socket.on('close',()=>sockets.delete(socket));socket.on('error',()=>{});let buffer='';socket.on('data',data=>{buffer+=data;if(Buffer.byteLength(buffer)>8192){socket.destroy();complete=false;return}if(!buffer.includes('\n'))return;socket.removeAllListeners('data');try{const r=JSON.parse(buffer);if(r.nonce!==config.nonce)throw Error('control_identity');guard();let result;
|
||||
if(r.op==='snapshot')result=finalReceipt??publicSnapshot();
|
||||
else if(r.op==='wait'){if(finalReceipt)result=finalReceipt;else{if(waiters.size)throw Error('duplicate_receipt_channel');waiters.add(socket);for(const arm of armWaiters)arm.end(JSON.stringify({ok:true,result:{armed:true,sealed:false}})+'\n');armWaiters.clear();socket.on('close',()=>waiters.delete(socket));return}}
|
||||
else if(r.op==='arm'){if(waiters.size)result={armed:true,sealed};else{armWaiters.add(socket);socket.on('close',()=>armWaiters.delete(socket));return}}
|
||||
else if(r.op==='publish'){if(sealed||publishedHash||r.path!==config.actionFile||typeof r.text!=='string'||Buffer.byteLength(r.text)>16384)throw Error('publish_bound');const p=path.join(config.binding.remoteCwd,config.actionFile);if(fs.realpathSync(path.dirname(p))!==path.dirname(p))throw Error('publish_parent');publishedHash=hash(r.text);try{fs.writeFileSync(p,r.text,{flag:'wx',mode:0o600})}catch(e){publishedHash=null;throw e}result={path:r.path,sha256:publishedHash,published:true};}
|
||||
else if(r.op==='read'){const p=r.path==='@cross-root'&&config.crossRoot?path.join(config.root,'cross-root-target'):path.join(config.binding.remoteCwd,r.path);if(r.path!=='@cross-root'&&!config.targets.includes(r.path))throw Error('unregistered_read');const status=file(p);if(status.absent)throw Error('file_missing');result={...status,base64:readSafe(p).toString('base64')};}
|
||||
else if(r.op==='attached'){if(attached||sealed)throw Error('attached_already_configured');if(!config.targets.includes(r.marker)||!Number.isInteger(r.delayMs)||r.delayMs<100||r.delayMs>8000)throw Error('attached_bounds');
|
||||
attached={connections:0,failure:null,commandExit:null,markerWrittenAtMs:null,markerWrittenMonotonicNs:null,clientExitedAtMs:null,clientExitedMonotonicNs:null};
|
||||
const clientScript=path.join(config.root,'client.cjs'),clientSocket=path.join(config.root,'attached.sock');
|
||||
fs.writeFileSync(clientScript,ATTACHED_CLIENT,{flag:'wx',mode:0o400});
|
||||
const srv=net.createServer(s=>{sockets.add(s);s.on('close',()=>sockets.delete(s));s.on('error',()=>{});let b='';s.on('data',d=>{b+=d;if(b.length>1024){s.destroy();attached.failure='client_bound';return}if(!b.includes('\n'))return;s.removeAllListeners('data');try{const q=JSON.parse(b);attached.connections++;if(q.nonce!==r.clientNonce||attached.connections!==1)throw Error('client_identity');client=identity(q.pid);sample();if(journal.get(q.pid)?.startTicks!==client.startTicks)throw Error('client_not_owned_by_run');const argv=fs.readFileSync('/proc/'+q.pid+'/cmdline').toString().split('\0');if(argv[1]!==clientScript||argv[2]!==clientSocket||argv[3]!==r.clientNonce)throw Error('client_argv');
|
||||
child=cp.spawn(process.execPath,['-e','setTimeout(()=>process.exit(0),'+r.delayMs+')'],{env:{PATH:'/usr/bin:/bin'},stdio:'ignore'});child.once('error',()=>{attached.failure='child_start';s.destroy()});child.once('exit',(code,signal)=>{attached.commandExit={code:code??-1,observedAtMs:Date.now(),observedMonotonicNs:process.hrtime.bigint().toString()};if(code!==0||signal){attached.failure='child_failed';s.destroy();return}try{fs.writeFileSync(path.join(config.binding.remoteCwd,r.marker),r.markerText,{flag:'wx'});attached.markerWrittenAtMs=Date.now();attached.markerWrittenMonotonicNs=process.hrtime.bigint().toString();s.end(JSON.stringify({code:0})+'\n')}catch{attached.failure='marker_failed';s.destroy()}});
|
||||
}catch{attached.failure='client_rejected';s.destroy()}})});srv.listen(clientSocket);attached.server=srv;result={clientScript,clientSocket};
|
||||
}
|
||||
else if(r.op==='finish'){result=snapshot();if(!result.complete||!result.processes.captured||result.processes.live.length)throw Error('retirement_unproven');sealed=true;workspaceWatch.close();for(const t of targets.values())t.watch.close();}
|
||||
else if(r.op==='close'){shutdown(socket);return;}
|
||||
else throw Error('unknown_operation');
|
||||
// Socket handles never cross the evidence boundary.
|
||||
if(result?.attached)result={...result,attached:{connections:attached.connections,failure:attached.failure,commandExit:attached.commandExit,markerWrittenAtMs:attached.markerWrittenAtMs,markerWrittenMonotonicNs:attached.markerWrittenMonotonicNs,clientExitedAtMs:attached.clientExitedAtMs,clientExitedMonotonicNs:attached.clientExitedMonotonicNs}};
|
||||
socket.end(JSON.stringify({ok:true,result})+'\n');
|
||||
}catch{socket.end(JSON.stringify({ok:false,error:'observer_evidence_incomplete'})+'\n')}})});
|
||||
let closing=false;async function shutdown(reply){if(closing){reply?.end(JSON.stringify({ok:false,error:'closing'})+'\n');return}closing=true;sealed=true;workspaceWatch.close();for(const t of targets.values())t.watch.close();clearInterval(observer);let settled=true;try{if(child&&child.exitCode===null&&child.signalCode===null){child.kill('SIGTERM');const exited=new Promise(resolve=>child.once('exit',resolve));await Promise.race([exited,new Promise(resolve=>setTimeout(resolve,2000))]);if(child.exitCode===null&&child.signalCode===null){child.kill('SIGKILL');await Promise.race([exited,new Promise(resolve=>setTimeout(resolve,2000))]);}settled=child.exitCode!==null||child.signalCode!==null;}if(reply)reply.end(JSON.stringify({ok:settled,result:{closed:settled}})+'\n');}finally{for(const s of sockets)if(s!==reply)s.destroy();server.close();if(attached?.server)attached.server.close();setTimeout(()=>{reply?.destroy();if(settled){const current=fs.lstatSync(config.root,{bigint:true});if(current.dev===rootStat.dev&¤t.ino===rootStat.ino&&!current.isSymbolicLink())fs.rmSync(config.root,{recursive:true,force:true});else settled=false;}process.exit(settled?0:2)},100)}}
|
||||
server.listen(path.join(config.root,'control.sock'));setTimeout(()=>{complete=false;shutdown(null)},config.observerTtlMs).unref();
|
||||
`;
|
||||
const ATTACHED_CLIENT = String.raw`const net=require('node:net');const s=net.connect(process.argv[2]);let b='';s.setTimeout(15000,()=>process.exit(3));s.on('error',()=>process.exit(4));s.on('connect',()=>s.write(JSON.stringify({nonce:process.argv[3],pid:process.pid})+'\n'));s.on('data',x=>{b+=x;if(b.length>1024)process.exit(6);if(b.includes('\n')){const r=JSON.parse(b);s.end();process.exit(r.code===0?0:5)}});`;
|
||||
function observerSource() {
|
||||
return OBSERVER.replace("PARSE_STAT", () => parseRemoteProcStat.toString()).replace("RUN_ROOT", () => isRemoteRunRoot.toString())
|
||||
.replace("WATCH_TARGET", () => createRemoteTargetWatch.toString()).replace("ATTACHED_CLIENT", () => JSON.stringify(ATTACHED_CLIENT));
|
||||
}
|
||||
const RPC = String.raw`const fs=require('node:fs'),net=require('node:net'),cp=require('node:child_process'),crypto=require('node:crypto');const r=JSON.parse(Buffer.from(process.argv[1],'base64').toString());const hash=x=>'sha256:'+crypto.createHash('sha256').update(x).digest('hex');
|
||||
const startedAt=Date.now();if(!Number.isInteger(r.timeoutMs)||r.timeoutMs<1000||r.timeoutMs>300000)throw Error('rpc_deadline');setTimeout(()=>{failure('rpc_deadline');process.exit(2)},r.timeoutMs).unref();
|
||||
const parseStat=PARSE_STAT,runRoot=RUN_ROOT;
|
||||
const codes=RPC_CODES;let failed=false;const phase=RPC_PHASES.includes(r.op)?r.op:'install';
|
||||
function failure(code){if(failed)return;failed=true;process.exitCode=2;process.stdout.write(JSON.stringify({ok:false,diagnostic:{phase,code:codes.includes(code)?code:'remote_unknown'}})+'\n')}
|
||||
function admitted(c){const st=fs.lstatSync(c.sentinel.path);if(!st.isFile()||st.isSymbolicLink()||st.size>16384||fs.realpathSync(c.sentinel.path)!==c.sentinel.path)throw Error('sentinel_type');const s=JSON.parse(fs.readFileSync(c.sentinel.path,'utf8'));if(s.version!==1||s.provider!=='daytona'||s.token!==c.sentinel.token||s.companyId!==c.binding.companyId||s.environmentId!==c.binding.environmentId)throw Error('sentinel');if(fs.realpathSync(c.binding.remoteCwd)!==c.binding.remoteCwd)throw Error('cwd')}
|
||||
function runtime(c){const root=c.binding.remoteCwd+'/'+c.runtimeRelative,boot=fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim();let s;try{s=fs.lstatSync(root,{bigint:true})}catch(e){if(e.code==='ENOENT')return {ready:false};throw e}if(!s.isDirectory()||s.isSymbolicLink()||fs.realpathSync(root)!==root)throw Error('runtime_root_identity');const matches=[];const entries=fs.readdirSync('/proc');if(entries.length>8192)throw Error('proc_bound');for(const name of entries){if(!/^\d+$/.test(name)||Number(name)<2)continue;try{const p=parseStat(Number(name),fs.readFileSync('/proc/'+name+'/stat','utf8'),boot),argv=fs.readFileSync('/proc/'+name+'/cmdline').toString().split('\0').filter(Boolean);if(runRoot(argv,c.binding.runId,p)){if(argv[0]!==root+'/bin/paperclip-runnerd'||hash(fs.readFileSync('/proc/'+name+'/exe'))!==c.runnerdSha256)throw Error('runtime_binary_identity');if(p.state!=='Z')matches.push({pid:p.pid,ppid:p.ppid,startTicks:p.startTicks,bootId:p.bootId})}}catch(e){if(e.code!=='ENOENT'&&e.code!=='ESRCH')throw e}}if(matches.length>1)throw Error('ambiguous_run_root');return matches.length===1?{ready:true,binding:c.binding,root:matches[0],runtime:{dev:String(s.dev),ino:String(s.ino),runnerExecutableSha256:c.runnerdSha256}}:{ready:false}}
|
||||
(async()=>{let controlRequest=r;if(hash(fs.readFileSync(process.execPath))!==r.nodeSha256)throw Error('node_identity');if(r.op==='runtime-ready'||r.op==='install'){const c=r.config;admitted(c);const current=runtime(c);if(r.op==='runtime-ready'){process.stdout.write(JSON.stringify({ok:true,result:current})+'\n');return}if(!current.ready)throw Error('runtime_not_ready');if(JSON.stringify(current)!==JSON.stringify(r.expectedRuntime))throw Error('runtime_identity_changed');fs.mkdirSync(c.root,{mode:0o700});fs.writeFileSync(c.root+'/observer.cjs',r.source,{flag:'wx',mode:0o400});c.observerTtlMs=Math.max(1,c.observerTtlMs-(Date.now()-startedAt));const child=cp.spawn(process.execPath,[c.root+'/observer.cjs',Buffer.from(JSON.stringify(c)).toString('base64')],{detached:true,stdio:'ignore',env:{PATH:'/usr/bin:/bin'}});child.unref();r.root=c.root;controlRequest={op:'snapshot',nonce:c.nonce};}
|
||||
for(let i=0;!fs.existsSync(r.root+'/control.sock')&&i<200;i++)await new Promise(resolve=>setTimeout(resolve,10));const socket=net.connect(r.root+'/control.sock');let output='';socket.setTimeout(Math.max(1,r.timeoutMs-(Date.now()-startedAt)));socket.on('timeout',()=>{socket.destroy();failure('socket_timeout')});socket.on('error',()=>{failure('socket_error')});socket.on('connect',()=>socket.write(JSON.stringify(controlRequest)+'\n'));socket.on('data',b=>{output+=b;if(Buffer.byteLength(output)>262144){socket.destroy();failure('output_bound')}});socket.on('end',()=>{if(!process.exitCode)process.stdout.write(output)});
|
||||
})().catch(e=>{failure(typeof e?.message==='string'?e.message:'remote_unknown')});`;
|
||||
|
||||
function rpcSource() {
|
||||
return RPC.replace("RPC_CODES", () => JSON.stringify(RPC_CODES)).replace("RPC_PHASES", () => JSON.stringify(RPC_PHASES)).replace("PARSE_STAT", () => parseRemoteProcStat.toString()).replace("RUN_ROOT", () => isRemoteRunRoot.toString());
|
||||
}
|
||||
|
||||
export interface RemoteNativeFixture {
|
||||
readonly binding: RemoteNativeBinding;
|
||||
readonly remoteCwd: string;
|
||||
readonly actionFile: string;
|
||||
readonly outsideTarget: string | null;
|
||||
/** Watchers and exact run-root identity are already armed at return from bind. */
|
||||
readonly baseline: RemoteNativeSnapshot;
|
||||
snapshot(label: string): Promise<RemoteNativeSnapshot>;
|
||||
readFile(path: string): Promise<Buffer>;
|
||||
publishAction(path: string, text: string): Promise<void>;
|
||||
setupAttachedCommand(input: { marker: string; markerText: string; delayMs: number }): Promise<{ command: string; commandSha256: string }>;
|
||||
/** Consumes the host-held terminal receipt; never queries a deleted lease. */
|
||||
finish(): Promise<RemoteNativeSnapshot>;
|
||||
/** Only fixture-owned observer cleanup. Never deletes a sandbox or lease. */
|
||||
close(): Promise<void>;
|
||||
}
|
||||
export interface RemoteNativeFixtureOptions {
|
||||
api: RemoteFixtureApi;
|
||||
daytona: RemoteFixtureDaytona;
|
||||
sdkVersion: typeof REMOTE_FIXTURE_DAYTONA_SDK_VERSION;
|
||||
authority: RemoteNativeAuthority;
|
||||
nodeSha256: string;
|
||||
runnerdSha256: string;
|
||||
targets: string[];
|
||||
actionFile: string;
|
||||
/** Cell deadline; receipt collection stops 15s earlier for public teardown. */
|
||||
deadlineAt: number;
|
||||
crossRoot?: { initialText: string };
|
||||
}
|
||||
const sha = (value: unknown): value is string => typeof value === "string" && /^sha256:[a-f0-9]{64}$/u.test(value);
|
||||
function readSnapshot(value: unknown, binding: RemoteNativeBinding, names: string[], actionFile: string, runnerdSha256: string): RemoteNativeSnapshot {
|
||||
const row = record(value), watcher = record(row.watcher), processes = record(row.processes), setup = record(row.setup);
|
||||
fail(JSON.stringify(row.binding) === JSON.stringify(binding), "receipt_binding");
|
||||
fail(Number.isSafeInteger(row.observedAtMs) && (row.observedAtMs as number) > 0 && typeof row.observedMonotonicNs === "string" && /^\d+$/u.test(row.observedMonotonicNs) && typeof row.complete === "boolean", "receipt_shape");
|
||||
fail(Object.keys(record(row.workspace)).length <= 512 && Object.entries(record(row.workspace)).every(([path, hash]) => {
|
||||
try { relative(path); return hash === "directory" || sha(hash); } catch { return false; }
|
||||
}), "workspace_shape");
|
||||
fail(Object.keys(record(row.targets)).sort().join("\0") === [...names].sort().join("\0"), "target_set");
|
||||
for (const target of Object.values(record(row.targets))) {
|
||||
const t = record(target), parent = record(t.parent);
|
||||
fail(typeof t.absent === "boolean" && (t.absent ? t.sha256 === null : sha(t.sha256)) && typeof t.complete === "boolean"
|
||||
&& Number.isSafeInteger(t.mutationCount) && (t.mutationCount as number) >= 0
|
||||
&& /^\d+$/u.test(String(parent.dev)) && /^\d+$/u.test(String(parent.ino)), "target_shape");
|
||||
}
|
||||
fail(typeof watcher.complete === "boolean" && [watcher.targetMutationCount, watcher.workspaceMutationCount].every(n => Number.isSafeInteger(n) && (n as number) >= 0), "watcher_shape");
|
||||
const validProcess = (p: unknown) => {
|
||||
const i = record(p); return Number.isSafeInteger(i.pid) && (i.pid as number) >= 2 && Number.isSafeInteger(i.ppid) && (i.ppid as number) >= 0
|
||||
&& typeof i.startTicks === "string" && /^\d+$/u.test(i.startTicks) && typeof i.bootId === "string" && /^[a-f0-9-]{36}$/u.test(i.bootId);
|
||||
};
|
||||
fail(typeof processes.captured === "boolean" && (processes.captured ? validProcess(processes.root) : processes.root === null)
|
||||
&& Array.isArray(processes.journal) && processes.journal.length <= 512 && processes.journal.every(validProcess)
|
||||
&& Array.isArray(processes.live) && processes.live.length <= 512
|
||||
&& processes.live.every(pid => (processes.journal as unknown[]).some((p: unknown) => record(p).pid === pid)), "process_shape");
|
||||
const scope = record(row.scope), excluded = record(scope.excludedRuntime);
|
||||
fail(scope.kind === "user_workspace" && excluded.relativePath === RUNTIME_RELATIVE && excluded.absolutePath === `${binding.remoteCwd}/${RUNTIME_RELATIVE}`
|
||||
&& /^\d+$/u.test(String(excluded.dev)) && /^\d+$/u.test(String(excluded.ino)) && excluded.runnerExecutableSha256 === runnerdSha256
|
||||
&& typeof scope.observedPrpEnvironmentLeaseId === "string" && /^[-a-zA-Z0-9._:]{1,256}$/u.test(scope.observedPrpEnvironmentLeaseId)
|
||||
&& scope.prpEnvironmentLeaseIdVerified === false, "evidence_scope");
|
||||
fail(setup.path === actionFile && typeof setup.published === "boolean" && (setup.published ? sha(setup.sha256) : setup.sha256 === null), "setup_shape");
|
||||
if (row.attached !== null) {
|
||||
const a = record(row.attached), exit = record(a.commandExit);
|
||||
fail(Number.isSafeInteger(a.connections) && (a.connections as number) >= 0 && (a.failure === null || ["client_bound", "child_start", "child_failed", "marker_failed", "client_rejected"].includes(String(a.failure)))
|
||||
&& (a.commandExit === null || (Number.isSafeInteger(exit.code) && Number.isSafeInteger(exit.observedAtMs) && typeof exit.observedMonotonicNs === "string" && /^\d+$/u.test(exit.observedMonotonicNs)))
|
||||
&& [a.markerWrittenAtMs, a.clientExitedAtMs].every(n => n === null || Number.isSafeInteger(n))
|
||||
&& [a.markerWrittenMonotonicNs, a.clientExitedMonotonicNs].every(n => n === null || typeof n === "string" && /^\d+$/u.test(n)), "attached_shape");
|
||||
}
|
||||
const { files: _files, ...publicReceipt } = row;
|
||||
return { ...publicReceipt, receivedAtMs: Date.now() } as unknown as RemoteNativeSnapshot;
|
||||
}
|
||||
|
||||
/** Must be called while the initial native input-file bootstrap holds the run.
|
||||
* No effect-producing task is published until baseline proves watcher + PID
|
||||
* admission. The exact controller runtime subtree is excluded only after its
|
||||
* directory inode/realpath, pinned executable and run/state-dir binding agree.
|
||||
* The PRP environment ID can be a durable workspace identity, not the sandbox
|
||||
* database lease ID; it is retained as observed, explicitly unverified metadata.
|
||||
* Same-UID observer opacity is not an OS adversarial sandbox. */
|
||||
export async function bindRemoteNativeFixture(options: RemoteNativeFixtureOptions): Promise<RemoteNativeFixture> {
|
||||
const { authority, api, daytona } = options;
|
||||
// This reserve is never borrowed by normal RPCs or finish(). Only observer
|
||||
// close has an independent 10s cleanup grace; public lease teardown is caller-owned.
|
||||
const receiptDeadlineAt = options.deadlineAt - TEARDOWN_RESERVE_MS;
|
||||
fail(options.sdkVersion === REMOTE_FIXTURE_DAYTONA_SDK_VERSION, "sdk_pin");
|
||||
fail(Object.entries(authority).every(([key, value]) => key === "image" ? typeof value === "string" && /^[^\s]+@sha256:[a-f0-9]{64}$/u.test(value) : typeof value === "string" && id(value)), "authority_shape");
|
||||
fail(sha(options.nodeSha256) && sha(options.runnerdSha256), "binary_pins");
|
||||
fail(Number.isFinite(options.deadlineAt) && options.deadlineAt - Date.now() >= REMOTE_FIXTURE_MIN_SETUP_BUDGET_MS, "insufficient_setup_budget");
|
||||
fail(options.targets.length <= 8 && new Set(options.targets).size === options.targets.length, "target_bound");
|
||||
const targets = options.targets.map(relative), actionFile = relative(options.actionFile);
|
||||
fail(!targets.includes(actionFile), "setup_target_overlap");
|
||||
fail([...targets, actionFile].every(path => path !== RUNTIME_RELATIVE && !path.startsWith(`${RUNTIME_RELATIVE}/`)), "runtime_target_forbidden");
|
||||
fail(!options.crossRoot || Buffer.byteLength(options.crossRoot.initialText) <= 4096, "cross_root_bound");
|
||||
const root = `/tmp/pc-native-${randomBytes(18).toString("hex")}`, nonce = randomBytes(32).toString("hex");
|
||||
let binding: RemoteNativeBinding | undefined, sentinel: { path: string; token: string } | undefined, identityKey: string | undefined;
|
||||
async function admittedSandbox() {
|
||||
const list = await api.get<unknown>(`/api/environments/${authority.environmentId}/leases`);
|
||||
const row = record(await api.get<unknown>(`/api/environment-leases/${authority.leaseId}`));
|
||||
fail(Array.isArray(list) && list.filter(item => record(item).id === authority.leaseId).length === 1, "lease_list");
|
||||
function admitted(row: Record<string, unknown>) {
|
||||
const metadata = record(row.metadata), sent = record(metadata.workspaceSentinel), cwd = metadata.remoteCwd;
|
||||
fail(row.id === authority.leaseId && row.companyId === authority.companyId && row.environmentId === authority.environmentId
|
||||
&& row.heartbeatRunId === authority.runId && row.provider === "daytona" && row.providerLeaseId === authority.sandboxId
|
||||
&& row.status === "active" && row.releasedAt == null, "lease_scope");
|
||||
fail(metadata.sandboxId === authority.sandboxId && metadata.image === authority.image && metadata.reuseLease === false, "lease_metadata");
|
||||
fail(typeof cwd === "string" && cwd.startsWith("/") && cwd.length < 512 && posix.normalize(cwd) === cwd && cwd !== "/" && !cwd.includes("\0"), "remote_cwd");
|
||||
fail(sent.path === `${cwd}/.paperclip-runtime/reusable-sandbox-lease.json` && sent.result === "written" && typeof sent.token === "string"
|
||||
&& sent.token.length >= 16 && sent.token.length <= 256 && sent.runId === authority.runId && sent.providerLeaseId === authority.sandboxId, "sentinel_binding");
|
||||
return { binding: { ...authority, remoteCwd: cwd as string }, sentinel: { path: sent.path as string, token: sent.token as string } };
|
||||
}
|
||||
const current = admitted(row), listed = admitted(record((list as unknown[]).find(item => record(item).id === authority.leaseId)));
|
||||
const key = JSON.stringify(current);
|
||||
fail(JSON.stringify(listed) === key && (!identityKey || identityKey === key), "lease_identity_drift");
|
||||
const sandbox = await daytona.get(authority.sandboxId);
|
||||
fail(sandbox.id === authority.sandboxId && sandbox.labels?.["paperclip-provider"] === "daytona"
|
||||
&& sandbox.labels?.["paperclip-company-id"] === authority.companyId && sandbox.labels?.["paperclip-environment-id"] === authority.environmentId
|
||||
&& sandbox.labels?.["paperclip-run-id"] === authority.runId && sandbox.labels?.["paperclip-reuse-lease"] === "false", "sandbox_labels");
|
||||
binding = current.binding; sentinel = current.sentinel; identityKey = key;
|
||||
return sandbox;
|
||||
}
|
||||
async function bounded<T>(operation: () => Promise<T>, budgetMs: number): Promise<T> {
|
||||
fail(budgetMs >= 1, "receipt_deadline");
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
operation(),
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => reject(new Error("remote_native_fixture:remote_command_failed_or_deadline")), budgetMs);
|
||||
timer.unref();
|
||||
}),
|
||||
]);
|
||||
} finally { if (timer) clearTimeout(timer); }
|
||||
}
|
||||
async function rpc(request: Record<string, unknown>, admitted?: Awaited<ReturnType<typeof admittedSandbox>>, deadlineAt = receiptDeadlineAt) {
|
||||
const available = request.op === "close" ? CLOSE_GRACE_MS : deadlineAt - Date.now();
|
||||
const cap = request.op === "install" ? INSTALL_BUDGET_MS : request.op === "wait" ? 300_000 : RUNTIME_READY_BUDGET_MS;
|
||||
const budgetMs = Math.floor(Math.min(available, cap) / 1000) * 1000;
|
||||
fail(budgetMs >= 1000, "receipt_deadline");
|
||||
if (request.op === "install") fail(budgetMs >= 25_000, "insufficient_setup_budget");
|
||||
const operationDeadline = Date.now() + budgetMs;
|
||||
return bounded(async () => {
|
||||
const sandbox = admitted ?? await admittedSandbox();
|
||||
const commandCap = request.op === "install" ? 25_000 : request.op === "wait" ? 300_000 : 10_000;
|
||||
const timeoutMs = Math.floor(Math.min(operationDeadline - Date.now(), commandCap) / 1000) * 1000;
|
||||
fail(timeoutMs >= 1000, "receipt_deadline");
|
||||
const config = request.op === "install"
|
||||
? { ...record(request.config), observerTtlMs: Math.floor((receiptDeadlineAt - Date.now()) / 1000) * 1000 }
|
||||
: undefined;
|
||||
const payload = Buffer.from(JSON.stringify({ ...request, ...(config ? { config } : {}), root, nonce, nodeSha256: options.nodeSha256, timeoutMs })).toString("base64");
|
||||
const command = `/usr/bin/env -i PATH=/usr/bin:/bin ${quote(NODE)} -e ${quote(rpcSource())} ${quote(payload)}`;
|
||||
let response: { exitCode: number; result: string };
|
||||
try { response = await sandbox.process.executeCommand(command, binding!.remoteCwd, {}, timeoutMs / 1000); }
|
||||
catch { throw new RemoteFixtureError("remote_native_fixture:remote_command_failed_or_deadline", { phase: request.op as RpcPhase, code: "transport_failure" }); }
|
||||
if (typeof response.result !== "string" || Buffer.byteLength(response.result) > MAX_OUTPUT) throw new RemoteFixtureError("remote_native_fixture:command_failed_or_output_bound", { phase: request.op as RpcPhase, code: "output_bound" });
|
||||
if (response.exitCode !== 0) {
|
||||
let diagnostic: RpcDiagnostic = { phase: request.op as RpcPhase, code: "invalid_response" };
|
||||
try {
|
||||
const value = record(JSON.parse(response.result)), d = record(value.diagnostic);
|
||||
if (value.ok === false && Object.keys(value).sort().join() === "diagnostic,ok" && Object.keys(d).sort().join() === "code,phase"
|
||||
&& d.phase === request.op && RPC_CODES.includes(d.code as RpcCode)) diagnostic = { phase: d.phase as RpcPhase, code: d.code as RpcCode };
|
||||
} catch { /* Never retain remote text. */ }
|
||||
throw new RemoteFixtureError(`remote_native_fixture:command_failed_or_output_bound:${diagnostic.phase}:${diagnostic.code}`, diagnostic);
|
||||
}
|
||||
let parsed: Record<string, unknown>;
|
||||
try { parsed = record(JSON.parse(response.result)); } catch { throw new Error("remote_native_fixture:invalid_observer_json"); }
|
||||
fail(parsed.ok === true, "observer_incomplete");
|
||||
return parsed.result;
|
||||
}, budgetMs);
|
||||
}
|
||||
const sandbox = await bounded(admittedSandbox, Math.min(LEASE_READMISSION_BUDGET_MS, receiptDeadlineAt - Date.now()));
|
||||
const names = [...targets, ...(options.crossRoot ? ["@cross-root"] : [])];
|
||||
const config = { root, nonce, binding, sentinel, targets, actionFile, crossRoot: options.crossRoot, runtimeRelative: RUNTIME_RELATIVE, runnerdSha256: options.runnerdSha256 };
|
||||
// Lease activation precedes runner artifact staging. Observe the exact pinned
|
||||
// run root before spending the single installation budget. No observer or
|
||||
// action exists during this polling phase, and failures are never retried.
|
||||
const readyDeadline = receiptDeadlineAt - INSTALL_BUDGET_MS;
|
||||
let expectedRuntime: Record<string, unknown>;
|
||||
while (true) {
|
||||
if (readyDeadline - Date.now() < 1000) throw new RemoteFixtureError("remote_native_fixture:readiness_deadline", { phase: "runtime-ready", code: "readiness_deadline" });
|
||||
const value = record(await rpc({ op: "runtime-ready", config }, undefined, readyDeadline));
|
||||
if (value.ready === true) {
|
||||
const process = record(value.root), runtime = record(value.runtime);
|
||||
fail(Object.keys(value).sort().join() === "binding,ready,root,runtime" && JSON.stringify(value.binding) === JSON.stringify(binding)
|
||||
&& Object.keys(process).sort().join() === "bootId,pid,ppid,startTicks" && Number.isSafeInteger(process.pid) && Number(process.pid) > 1
|
||||
&& Number.isSafeInteger(process.ppid) && Number(process.ppid) >= 0 && typeof process.startTicks === "string" && /^\d+$/u.test(process.startTicks)
|
||||
&& typeof process.bootId === "string" && /^[a-f0-9-]{36}$/u.test(process.bootId)
|
||||
&& Object.keys(runtime).sort().join() === "dev,ino,runnerExecutableSha256" && typeof runtime.dev === "string" && /^\d+$/u.test(runtime.dev)
|
||||
&& typeof runtime.ino === "string" && /^\d+$/u.test(runtime.ino) && runtime.runnerExecutableSha256 === options.runnerdSha256, "runtime_ready_identity");
|
||||
expectedRuntime = value; break;
|
||||
}
|
||||
fail(value.ready === false && Object.keys(value).length === 1, "runtime_ready_shape");
|
||||
await new Promise(resolve => setTimeout(resolve, Math.min(200, Math.max(0, readyDeadline - Date.now()))));
|
||||
}
|
||||
let baseline: RemoteNativeSnapshot;
|
||||
try {
|
||||
baseline = readSnapshot(await rpc({ op: "install", config, expectedRuntime, source: observerSource() }), binding!, names, actionFile, options.runnerdSha256);
|
||||
fail(baseline.complete && baseline.processes.captured && baseline.processes.live.length > 0 && baseline.watcher.complete && !baseline.setup.published, "bootstrap_not_held");
|
||||
fail((["pid", "ppid", "startTicks", "bootId"] as const).every(key => baseline.processes.root?.[key] === record(expectedRuntime.root)[key])
|
||||
&& baseline.scope.excludedRuntime.dev === record(expectedRuntime.runtime).dev && baseline.scope.excludedRuntime.ino === record(expectedRuntime.runtime).ino, "runtime_identity_changed");
|
||||
} catch (error) {
|
||||
// Only the nonce/inode-bound observer can acknowledge this cleanup. If
|
||||
// launch failed before its socket became available, TTL remains a bound,
|
||||
// not a claimed successful cleanup receipt.
|
||||
try { await rpc({ op: "close" }, sandbox); }
|
||||
catch (cleanupError) { throw new RemoteFixtureError("remote_native_fixture:startup_failed_cleanup_unproven", remoteNativeFixtureDiagnostics(cleanupError)[0] ?? { phase: "close", code: "remote_unknown" }, { cause: error }); }
|
||||
throw error;
|
||||
}
|
||||
// Start receiving while the lease is still authorized, before publishAction.
|
||||
// Rejection is retained (no unhandled rejection); finish reports it unchanged.
|
||||
let stopReceipt!: () => void;
|
||||
const cancelledReceipt = new Promise<never>((_resolve, reject) => { stopReceipt = () => reject(new Error("remote_native_fixture:closed_before_receipt")); });
|
||||
const terminal = Promise.race([rpc({ op: "wait" }, sandbox), cancelledReceipt])
|
||||
.then(value => ({ value, receivedAtMs: Date.now() }), error => ({ error }));
|
||||
try {
|
||||
const armed = record(await rpc({ op: "arm" }, sandbox));
|
||||
fail(armed.armed === true && armed.sealed === false, "receipt_channel_not_armed");
|
||||
} catch (error) {
|
||||
try { await rpc({ op: "close" }, sandbox); }
|
||||
catch { throw new Error("remote_native_fixture:receipt_channel_failed_cleanup_unproven", { cause: error }); }
|
||||
stopReceipt();
|
||||
throw error;
|
||||
}
|
||||
let closed = false, published = false, finished: RemoteNativeSnapshot | undefined;
|
||||
const retainedFiles = new Map<string, Buffer>();
|
||||
return {
|
||||
binding: binding!, remoteCwd: binding!.remoteCwd, actionFile, outsideTarget: options.crossRoot ? `${root}/cross-root-target` : null, baseline,
|
||||
async snapshot(label) {
|
||||
fail(typeof label === "string" && /^[a-zA-Z0-9_-]{1,80}$/u.test(label), "snapshot_label");
|
||||
fail(!closed && !finished, "fixture_closed");
|
||||
return readSnapshot(await rpc({ op: "snapshot" }), binding!, names, actionFile, options.runnerdSha256);
|
||||
},
|
||||
async readFile(path) {
|
||||
fail(!closed && names.includes(path), "unregistered_read");
|
||||
if (finished) { const bytes = retainedFiles.get(path); fail(bytes, "terminal_file_missing"); return Buffer.from(bytes!); }
|
||||
const data = record(await rpc({ op: "read", path }));
|
||||
fail(typeof data.base64 === "string" && data.base64.length <= 87384 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(data.base64), "read_bound");
|
||||
const bytes = Buffer.from(data.base64 as string, "base64");
|
||||
fail(bytes.length <= 65536 && `sha256:${createHash("sha256").update(bytes).digest("hex")}` === data.sha256, "read_digest");
|
||||
return bytes;
|
||||
},
|
||||
async publishAction(path, text) {
|
||||
fail(!closed && !published && path === actionFile && typeof text === "string" && Buffer.byteLength(text) <= 16384, "publish_bound");
|
||||
// Set before RPC: uncertain delivery must never cause a second publish.
|
||||
published = true;
|
||||
const ack = record(await rpc({ op: "publish", path, text }));
|
||||
fail(ack.published === true && ack.path === path && ack.sha256 === digest(text), "publish_ack");
|
||||
},
|
||||
async setupAttachedCommand(input) {
|
||||
fail(!closed && !published && targets.includes(input.marker) && Number.isInteger(input.delayMs) && input.delayMs >= 100 && input.delayMs <= 8000
|
||||
&& typeof input.markerText === "string" && Buffer.byteLength(input.markerText) <= 4096, "attached_bound");
|
||||
const clientNonce = randomBytes(24).toString("hex");
|
||||
const result = record(await rpc({ op: "attached", ...input, clientNonce }));
|
||||
fail(result.clientScript === `${root}/client.cjs` && result.clientSocket === `${root}/attached.sock`, "attached_identity");
|
||||
const command = `${quote(NODE)} ${quote(result.clientScript as string)} ${quote(result.clientSocket as string)} ${quote(clientNonce)}`;
|
||||
return { command, commandSha256: digest(command) };
|
||||
},
|
||||
async finish() {
|
||||
if (finished) return finished;
|
||||
const receipt = await terminal;
|
||||
if ("error" in receipt) throw receipt.error;
|
||||
fail(receipt.receivedAtMs <= receiptDeadlineAt, "receipt_deadline");
|
||||
const result = readSnapshot(receipt.value, binding!, names, actionFile, options.runnerdSha256);
|
||||
fail(published && result.setup.published && result.complete && result.watcher.complete && result.processes.captured && result.processes.live.length === 0, "terminal_evidence_incomplete");
|
||||
const files = record(record(receipt.value).files);
|
||||
for (const name of names) {
|
||||
const target = result.targets[name]!;
|
||||
if (target.absent) { fail(files[name] === undefined, "terminal_file_presence"); continue; }
|
||||
fail(typeof files[name] === "string" && (files[name] as string).length <= 87384, "terminal_file_bound");
|
||||
const bytes = Buffer.from(files[name] as string, "base64");
|
||||
fail(bytes.length <= 65536 && `sha256:${createHash("sha256").update(bytes).digest("hex")}` === target.sha256, "terminal_file_digest");
|
||||
retainedFiles.set(name, bytes);
|
||||
}
|
||||
result.receivedAtMs = receipt.receivedAtMs;
|
||||
finished = result; return result;
|
||||
},
|
||||
async close() {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
// A finalized receipt survives ordinary public lease deletion. If the
|
||||
// lease still exists, clean our opaque observer; never discover by name.
|
||||
if (!finished) { stopReceipt(); await rpc({ op: "close" }); }
|
||||
},
|
||||
};
|
||||
}
|
||||
+275
-173
@@ -5,6 +5,10 @@ import { assertNativeBlockerReply } from "./native-blocker-visible.js";
|
||||
import { warmManagedFileEvidence } from "./warm-managed-files.js";
|
||||
import { gitFinalizationEvidence, gitStreamingEvidence, setupGitStreamingWorkspace } from "./daytona-git-streaming.js";
|
||||
import { runsCompletionUpdateProbe, completionQualityControls, completionQualityStatus, judgeCompletionQuality, reserveCompletionQuality, type CompletionQualityRecord } from "./completion-quality.js";
|
||||
import { runNativeActiveStopFlow } from "./native-active-stop-flow.js";
|
||||
import { runCursorNativeFlow } from "./cursor-native-flow.js";
|
||||
import { createRemoteNativeBootstrap, createRemoteFixtureClient } from "./remote-native-bootstrap.js";
|
||||
import { runCleanupWithObservers, verifyCleanupAssertions, type CleanupAssertion } from "./cleanup-verification.js";
|
||||
import { completionDelivery, type CompletionObservation } from "./completion-updates.js";
|
||||
import { runInstructionPersistenceFlow } from "./instruction-persistence.js";
|
||||
import { gradeApiResponsePaging, readResponseProof, responseEvidenceDescription } from "./api-response-reading.js";
|
||||
@@ -565,7 +569,7 @@ for (const execution of executions) {
|
||||
const credentials = credentialValues();
|
||||
const secrets = normalizedSecrets(Object.values(credentials));
|
||||
const api = new RunnerApi(request);
|
||||
const companyRunFlow = execution.suite.id === "task-titles" || ["blocker_guidance", "continuation_accounting", "continuation", "context_integrity", "agent_chat", "everyday_workflow", "first_task", "instruction_persistence"].includes(execution.task.flow);
|
||||
const companyRunFlow = execution.suite.id === "task-titles" || ["blocker_guidance", "continuation_accounting", "continuation", "context_integrity", "agent_chat", "everyday_workflow", "first_task", "instruction_persistence", "cursor_native", "native_active_stop"].includes(execution.task.flow);
|
||||
const consoleDiagnostics: Array<Record<string, unknown>> = [];
|
||||
const networkDiagnostics: Array<Record<string, unknown>> = [];
|
||||
const pageLifecycleDiagnostics: Array<Record<string, unknown>> = [];
|
||||
@@ -611,6 +615,16 @@ for (const execution of executions) {
|
||||
let primaryError: unknown;
|
||||
let failureClassOverride: FailureClass | undefined;
|
||||
let cleanup: RunnerE2EResult["cleanup"] = "not_started";
|
||||
const cleanupAssertions: CleanupAssertion[] = [];
|
||||
const beforeEnvironmentTeardownAssertions: CleanupAssertion[] = [];
|
||||
const registerCleanupAssertion = (assertion: CleanupAssertion) => {
|
||||
if (cleanupAssertions.length >= 8) throw new Error("Cleanup assertion bound exceeded");
|
||||
cleanupAssertions.push(assertion);
|
||||
};
|
||||
const registerBeforeEnvironmentTeardownAssertion = (assertion: CleanupAssertion) => {
|
||||
if (beforeEnvironmentTeardownAssertions.length >= 8) throw new Error("Remote cleanup assertion bound exceeded");
|
||||
beforeEnvironmentTeardownAssertions.push(assertion);
|
||||
};
|
||||
|
||||
const capturePrivateScreenshot = async (id: string, file: string) => {
|
||||
const screenshotPath = path.join(privateDir, file);
|
||||
@@ -870,6 +884,17 @@ for (const execution of executions) {
|
||||
]);
|
||||
nativeInitial = { issueIds: issues.map(value => value.id), agentIds: agents.map(value => value.id), workspaceDigest };
|
||||
}
|
||||
const remoteBootstrap = execution.environment.id === "daytona"
|
||||
&& ["cursor_native", "native_active_stop"].includes(execution.task.flow)
|
||||
? createRemoteNativeBootstrap({
|
||||
api, daytona: await createRemoteFixtureClient(credentials.DAYTONA_API_KEY ?? ""),
|
||||
companyId: fixtures.company.id, environmentId: fixtures.environment.id, agentId: fixtures.agent.id,
|
||||
image: process.env.PAPERCLIP_E2E_DAYTONA_IMAGE ?? "",
|
||||
nodeSha256: process.env.PAPERCLIP_E2E_DAYTONA_NODE_SHA256 ?? "",
|
||||
runnerdSha256: process.env.PAPERCLIP_E2E_DAYTONA_RUNNERD_SHA256 ?? "",
|
||||
deadlineAt: startedAtMs + deadlineMs,
|
||||
evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
|
||||
}) : undefined;
|
||||
|
||||
if (execution.suite.id === "stock-harness") {
|
||||
const hire = await captureStockHarness({ api, companyId: fixtures.company.id,
|
||||
@@ -950,6 +975,25 @@ for (const execution of executions) {
|
||||
evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
|
||||
});
|
||||
issue = accounting.issue as IssueRecord; selectedRuns = accounting.runs as RunRecord[];
|
||||
} else if (execution.task.flow === "native_active_stop") {
|
||||
const story = await runNativeActiveStopFlow({
|
||||
page, api, fixtures, execution, nonce, workspacePath, deadlineAt: startedAtMs + deadlineMs,
|
||||
observe: (currentIssue, currentRuns) => { issue = currentIssue as IssueRecord; selectedRuns = currentRuns as RunRecord[]; },
|
||||
capture: captureScreenshot, evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
|
||||
remoteBootstrap, registerCleanupAssertion, registerBeforeEnvironmentTeardownAssertion,
|
||||
});
|
||||
issue = story.issue as IssueRecord; selectedRuns = story.runs as RunRecord[];
|
||||
matcherResults = story.checks.map(check => ({ matcher: { kind: "json_path" as const, path: `nativeActiveStop.${check.id}`, expected: true }, passed: check.passed, detail: check.detail }));
|
||||
} else if (execution.task.flow === "cursor_native") {
|
||||
const story = await runCursorNativeFlow({
|
||||
page, api, fixtures, execution, nonce, workspacePath, deadlineAt: startedAtMs + deadlineMs,
|
||||
observe: (currentIssue, currentRuns) => { issue = currentIssue as IssueRecord; selectedRuns = currentRuns as RunRecord[]; },
|
||||
capture: captureScreenshot,
|
||||
evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
|
||||
remoteBootstrap, registerCleanupAssertion, registerBeforeEnvironmentTeardownAssertion,
|
||||
});
|
||||
issue = story.issue as IssueRecord; selectedRuns = story.runs as RunRecord[];
|
||||
matcherResults = story.checks.map(check => ({ matcher: { kind: "json_path" as const, path: `cursorNative.${check.id}`, expected: true }, passed: check.passed, detail: check.detail }));
|
||||
} else if (execution.task.flow === "instruction_persistence") {
|
||||
const story = await runInstructionPersistenceFlow({
|
||||
page, api, fixtures, execution, nonce, secrets, deadlineAt: startedAtMs + deadlineMs,
|
||||
@@ -1572,7 +1616,7 @@ for (const execution of executions) {
|
||||
(execution.task.turnTimeoutMs ?? 10 * 60_000),
|
||||
);
|
||||
const waitingState = await pollUntil({
|
||||
label: `warm Daytona turn ${completedTurn} review state for issue ${issue.id}`,
|
||||
label: `warm ${execution.environment.id} turn ${completedTurn} review state for issue ${issue.id}`,
|
||||
deadlineAt: turnDeadlineAt,
|
||||
load: loadTaskState,
|
||||
accept: ({ currentIssue, taskRuns, interactions }) => {
|
||||
@@ -1631,78 +1675,81 @@ for (const execution of executions) {
|
||||
const completedRunIds = new Set(
|
||||
chronologicalRuns.map((candidate) => candidate.id),
|
||||
);
|
||||
const retainedTurnLeases = await pollUntil({
|
||||
label: `retained Daytona leases after warm turn ${completedTurn}`,
|
||||
deadlineAt: Math.min(turnDeadlineAt, Date.now() + 30_000),
|
||||
intervalMs: 500,
|
||||
load: () =>
|
||||
api.get<EnvironmentLeaseRecord[]>(
|
||||
`/api/environments/${fixtures!.environment.id}/leases`,
|
||||
),
|
||||
accept: (leases) => {
|
||||
const runOrder = new Map(
|
||||
chronologicalRuns.map((candidate, index) => [
|
||||
candidate.id,
|
||||
index,
|
||||
]),
|
||||
);
|
||||
const completed = leases
|
||||
.filter(
|
||||
(lease) =>
|
||||
lease.heartbeatRunId &&
|
||||
completedRunIds.has(lease.heartbeatRunId),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
(runOrder.get(left.heartbeatRunId ?? "") ?? 0) -
|
||||
(runOrder.get(right.heartbeatRunId ?? "") ?? 0),
|
||||
let completedLeases: EnvironmentLeaseRecord[] = [];
|
||||
if (execution.environment.id === "daytona") {
|
||||
const retainedTurnLeases = await pollUntil({
|
||||
label: `retained Daytona leases after warm turn ${completedTurn}`,
|
||||
deadlineAt: Math.min(turnDeadlineAt, Date.now() + 30_000),
|
||||
intervalMs: 500,
|
||||
load: () =>
|
||||
api.get<EnvironmentLeaseRecord[]>(
|
||||
`/api/environments/${fixtures!.environment.id}/leases`,
|
||||
),
|
||||
accept: (leases) => {
|
||||
const runOrder = new Map(
|
||||
chronologicalRuns.map((candidate, index) => [
|
||||
candidate.id,
|
||||
index,
|
||||
]),
|
||||
);
|
||||
return (
|
||||
completed.length === completedTurn &&
|
||||
completed
|
||||
.slice(0, -1)
|
||||
.every(
|
||||
const completed = leases
|
||||
.filter(
|
||||
(lease) =>
|
||||
lease.status === "expired" &&
|
||||
lease.cleanupStatus === "success",
|
||||
) &&
|
||||
completed.at(-1)?.status === "retained" &&
|
||||
completed.every(
|
||||
(lease) =>
|
||||
lease.leasePolicy === "reuse_by_environment" &&
|
||||
typeof lease.providerLeaseId === "string" &&
|
||||
record(lease.metadata).sandboxState === "started",
|
||||
) &&
|
||||
completed
|
||||
.slice(1)
|
||||
.every(
|
||||
(lease) =>
|
||||
record(lease.metadata).resumedFromState === "started",
|
||||
lease.heartbeatRunId &&
|
||||
completedRunIds.has(lease.heartbeatRunId),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
(runOrder.get(left.heartbeatRunId ?? "") ?? 0) -
|
||||
(runOrder.get(right.heartbeatRunId ?? "") ?? 0),
|
||||
);
|
||||
return (
|
||||
completed.length === completedTurn &&
|
||||
completed
|
||||
.slice(0, -1)
|
||||
.every(
|
||||
(lease) =>
|
||||
lease.status === "expired" &&
|
||||
lease.cleanupStatus === "success",
|
||||
) &&
|
||||
completed.at(-1)?.status === "retained" &&
|
||||
completed.every(
|
||||
(lease) =>
|
||||
lease.leasePolicy === "reuse_by_environment" &&
|
||||
typeof lease.providerLeaseId === "string" &&
|
||||
record(lease.metadata).sandboxState === "started",
|
||||
) &&
|
||||
completed
|
||||
.slice(1)
|
||||
.every(
|
||||
(lease) =>
|
||||
record(lease.metadata).resumedFromState === "started",
|
||||
)
|
||||
);
|
||||
},
|
||||
});
|
||||
const turnRunOrder = new Map(
|
||||
chronologicalRuns.map((candidate, index) => [candidate.id, index]),
|
||||
);
|
||||
completedLeases = retainedTurnLeases
|
||||
.filter(
|
||||
(lease) =>
|
||||
lease.heartbeatRunId &&
|
||||
completedRunIds.has(lease.heartbeatRunId),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
(turnRunOrder.get(left.heartbeatRunId ?? "") ?? 0) -
|
||||
(turnRunOrder.get(right.heartbeatRunId ?? "") ?? 0),
|
||||
);
|
||||
},
|
||||
});
|
||||
const turnRunOrder = new Map(
|
||||
chronologicalRuns.map((candidate, index) => [candidate.id, index]),
|
||||
);
|
||||
const completedLeases = retainedTurnLeases
|
||||
.filter(
|
||||
(lease) =>
|
||||
lease.heartbeatRunId &&
|
||||
completedRunIds.has(lease.heartbeatRunId),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
(turnRunOrder.get(left.heartbeatRunId ?? "") ?? 0) -
|
||||
(turnRunOrder.get(right.heartbeatRunId ?? "") ?? 0),
|
||||
);
|
||||
if (
|
||||
new Set(completedLeases.map((lease) => lease.providerLeaseId))
|
||||
.size !== 1
|
||||
) {
|
||||
throw new Error(
|
||||
`Warm turn ${completedTurn} replaced its Daytona sandbox`,
|
||||
);
|
||||
if (
|
||||
new Set(completedLeases.map((lease) => lease.providerLeaseId))
|
||||
.size !== 1
|
||||
) {
|
||||
throw new Error(
|
||||
`Warm turn ${completedTurn} replaced its Daytona sandbox`,
|
||||
);
|
||||
}
|
||||
}
|
||||
const journalEvidence = execution.suite.id === "daytona-journal-continuity" && completedTurn === 1
|
||||
? await largeJournalEvidence({
|
||||
@@ -1727,9 +1774,31 @@ for (const execution of executions) {
|
||||
`/${encodeURIComponent(issuePrefix)}/issues/${encodeURIComponent(issue.identifier ?? issue.id)}`,
|
||||
{ waitUntil: "domcontentloaded" },
|
||||
);
|
||||
// Navigation commits before React has loaded the task. Bind the
|
||||
// screenshot to this turn's visible reply and exact pending review,
|
||||
// rather than capturing a spinner after DOMContentLoaded.
|
||||
const reviewUiTimeout = () => {
|
||||
const remaining = turnDeadlineAt - Date.now();
|
||||
if (remaining <= 0) throw new Error(`Warm turn ${completedTurn} UI deadline elapsed`);
|
||||
return Math.min(30_000, remaining);
|
||||
};
|
||||
await expect(page.getByTestId("issue-detail-header").getByRole("button", {
|
||||
name: "Change status (current: In Review)", exact: true,
|
||||
})).toBeVisible({ timeout: reviewUiTimeout() });
|
||||
const turnReply = page.getByTestId("task-chat-thread")
|
||||
.getByTestId("task-chat-agent-bubble")
|
||||
.filter({ hasText: `PAPERCLIP_E2E_WARM_T${completedTurn}_${nonce}` }).last();
|
||||
await expect(turnReply).toBeVisible({ timeout: reviewUiTimeout() });
|
||||
const pendingReview = waitingState.interactions.find(isPendingWarmConfirmation)!;
|
||||
const reviewCard = page.locator(`[id=${JSON.stringify(`interaction-${pendingReview.id}`)}]`);
|
||||
await expect(reviewCard).toBeVisible({ timeout: reviewUiTimeout() });
|
||||
await expect(reviewCard.getByRole("button", { name: "Continue work", exact: true }))
|
||||
.toBeEnabled({ timeout: reviewUiTimeout() });
|
||||
await expect(page.getByTestId("task-chat-history-loading"))
|
||||
.toHaveCount(0, { timeout: reviewUiTimeout() });
|
||||
await captureScreenshot(
|
||||
`warm-turn-${completedTurn}`,
|
||||
`Warm Daytona turn ${completedTurn} awaiting review`,
|
||||
`Warm ${execution.environment.id} turn ${completedTurn} awaiting review`,
|
||||
`warm-turn-${completedTurn}.png`,
|
||||
);
|
||||
turnSubmissionTimesMs.push(
|
||||
@@ -2232,22 +2301,24 @@ for (const execution of executions) {
|
||||
const executionWorkspaceIds = selectedRuns.map(
|
||||
(candidate) => record(candidate.contextSnapshot).executionWorkspaceId,
|
||||
);
|
||||
if (
|
||||
leaseIds.some(
|
||||
(leaseId) => typeof leaseId !== "string" || leaseId.length === 0,
|
||||
)
|
||||
) {
|
||||
invariantFailures.push(
|
||||
`expected a persisted Daytona lease row for every warm turn; observed ${JSON.stringify(leaseIds)}`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
JSON.stringify(acquisitionOutcomes) !==
|
||||
JSON.stringify(["created", "resumed", "resumed"])
|
||||
) {
|
||||
invariantFailures.push(
|
||||
`expected warm lease outcomes created,resumed,resumed; observed ${JSON.stringify(acquisitionOutcomes)}`,
|
||||
);
|
||||
if (execution.environment.id === "daytona") {
|
||||
if (
|
||||
leaseIds.some(
|
||||
(leaseId) => typeof leaseId !== "string" || leaseId.length === 0,
|
||||
)
|
||||
) {
|
||||
invariantFailures.push(
|
||||
`expected a persisted Daytona lease row for every warm turn; observed ${JSON.stringify(leaseIds)}`,
|
||||
);
|
||||
}
|
||||
if (
|
||||
JSON.stringify(acquisitionOutcomes) !==
|
||||
JSON.stringify(["created", "resumed", "resumed"])
|
||||
) {
|
||||
invariantFailures.push(
|
||||
`expected warm lease outcomes created,resumed,resumed; observed ${JSON.stringify(acquisitionOutcomes)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
!fixtures.project?.primaryWorkspace?.id ||
|
||||
@@ -2330,71 +2401,76 @@ for (const execution of executions) {
|
||||
`warm turn timing data was incomplete or exceeded its structural deadline: ${JSON.stringify(turnTimings)}`,
|
||||
);
|
||||
}
|
||||
const retainedLeases = await pollUntil({
|
||||
label: `terminal warm Daytona lease history for issue ${issue.id}`,
|
||||
deadlineAt: Math.min(deadlineAt, Date.now() + 30_000),
|
||||
intervalMs: 500,
|
||||
load: () =>
|
||||
api.get<EnvironmentLeaseRecord[]>(
|
||||
`/api/environments/${fixtures!.environment.id}/leases`,
|
||||
),
|
||||
accept: (leases) => {
|
||||
const warmLeases = leases.filter(
|
||||
let warmLeases: EnvironmentLeaseRecord[] = [];
|
||||
let providerLeaseIds: Array<string | null | undefined> = [];
|
||||
let resumedFromStates: unknown[] = [];
|
||||
if (execution.environment.id === "daytona") {
|
||||
const retainedLeases = await pollUntil({
|
||||
label: `terminal warm Daytona lease history for issue ${issue.id}`,
|
||||
deadlineAt: Math.min(deadlineAt, Date.now() + 30_000),
|
||||
intervalMs: 500,
|
||||
load: () =>
|
||||
api.get<EnvironmentLeaseRecord[]>(
|
||||
`/api/environments/${fixtures!.environment.id}/leases`,
|
||||
),
|
||||
accept: (leases) => {
|
||||
const warmLeases = leases.filter(
|
||||
(lease) =>
|
||||
lease.issueId === issue!.id &&
|
||||
selectedRuns.some(
|
||||
(candidate) => candidate.id === lease.heartbeatRunId,
|
||||
),
|
||||
);
|
||||
return (
|
||||
warmLeases.length === 3 &&
|
||||
warmLeases.every((lease) => {
|
||||
const runIndex = selectedRuns.findIndex(
|
||||
(candidate) => candidate.id === lease.heartbeatRunId,
|
||||
);
|
||||
return (
|
||||
lease.status ===
|
||||
(runIndex === selectedRuns.length - 1
|
||||
? "retained"
|
||||
: "expired") &&
|
||||
lease.cleanupStatus === "success" &&
|
||||
lease.leasePolicy === "reuse_by_environment" &&
|
||||
typeof lease.providerLeaseId === "string" &&
|
||||
record(lease.metadata).sandboxState === "started"
|
||||
);
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
const selectedRunOrder = new Map(
|
||||
selectedRuns.map((candidate, index) => [candidate.id, index]),
|
||||
);
|
||||
warmLeases = retainedLeases
|
||||
.filter(
|
||||
(lease) =>
|
||||
lease.issueId === issue!.id &&
|
||||
selectedRuns.some(
|
||||
(candidate) => candidate.id === lease.heartbeatRunId,
|
||||
),
|
||||
selectedRunOrder.has(lease.heartbeatRunId ?? ""),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
(selectedRunOrder.get(left.heartbeatRunId ?? "") ?? 0) -
|
||||
(selectedRunOrder.get(right.heartbeatRunId ?? "") ?? 0),
|
||||
);
|
||||
return (
|
||||
warmLeases.length === 3 &&
|
||||
warmLeases.every((lease) => {
|
||||
const runIndex = selectedRuns.findIndex(
|
||||
(candidate) => candidate.id === lease.heartbeatRunId,
|
||||
);
|
||||
return (
|
||||
lease.status ===
|
||||
(runIndex === selectedRuns.length - 1
|
||||
? "retained"
|
||||
: "expired") &&
|
||||
lease.cleanupStatus === "success" &&
|
||||
lease.leasePolicy === "reuse_by_environment" &&
|
||||
typeof lease.providerLeaseId === "string" &&
|
||||
record(lease.metadata).sandboxState === "started"
|
||||
);
|
||||
})
|
||||
providerLeaseIds = warmLeases.map(
|
||||
(lease) => lease.providerLeaseId,
|
||||
);
|
||||
resumedFromStates = warmLeases
|
||||
.slice(1)
|
||||
.map((lease) => record(lease.metadata).resumedFromState);
|
||||
if (
|
||||
new Set(providerLeaseIds).size !== 1 ||
|
||||
typeof providerLeaseIds[0] !== "string" ||
|
||||
JSON.stringify(resumedFromStates) !==
|
||||
JSON.stringify(["started", "started"])
|
||||
) {
|
||||
invariantFailures.push(
|
||||
`expected one continuously-started Daytona sandbox; observed ${JSON.stringify({ providerLeaseIds, resumedFromStates })}`,
|
||||
);
|
||||
},
|
||||
});
|
||||
const selectedRunOrder = new Map(
|
||||
selectedRuns.map((candidate, index) => [candidate.id, index]),
|
||||
);
|
||||
const warmLeases = retainedLeases
|
||||
.filter(
|
||||
(lease) =>
|
||||
lease.issueId === issue!.id &&
|
||||
selectedRunOrder.has(lease.heartbeatRunId ?? ""),
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
(selectedRunOrder.get(left.heartbeatRunId ?? "") ?? 0) -
|
||||
(selectedRunOrder.get(right.heartbeatRunId ?? "") ?? 0),
|
||||
);
|
||||
const providerLeaseIds = warmLeases.map(
|
||||
(lease) => lease.providerLeaseId,
|
||||
);
|
||||
const resumedFromStates = warmLeases
|
||||
.slice(1)
|
||||
.map((lease) => record(lease.metadata).resumedFromState);
|
||||
if (
|
||||
new Set(providerLeaseIds).size !== 1 ||
|
||||
typeof providerLeaseIds[0] !== "string" ||
|
||||
JSON.stringify(resumedFromStates) !==
|
||||
JSON.stringify(["started", "started"])
|
||||
) {
|
||||
invariantFailures.push(
|
||||
`expected one continuously-started Daytona sandbox; observed ${JSON.stringify({ providerLeaseIds, resumedFromStates })}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
warmLifecycleEvidence = {
|
||||
...(warmLifecycleEvidence ?? {}),
|
||||
@@ -2776,31 +2852,40 @@ for (const execution of executions) {
|
||||
});
|
||||
});
|
||||
try {
|
||||
await cancelActiveRunsForCleanup();
|
||||
if (companyRunFlow) {
|
||||
const companyRuns = await api.get<RunRecord[]>(`/api/companies/${fixtures.company.id}/heartbeat-runs?limit=100`);
|
||||
selectedRuns = await Promise.all(companyRuns.map(run => api.get<RunRecord>(`/api/heartbeat-runs/${run.id}`)));
|
||||
await writeSanitizedJson(snapshotsDir, execution.task.flow === "first_task" ? "first-task-final-run-ledger.json" : "chat-final-run-ledger.json", selectedRuns, secrets);
|
||||
}
|
||||
if (execution.suite.id === "stock-harness") {
|
||||
try {
|
||||
const stock = await captureStockHarness({ api, companyId: fixtures.company.id,
|
||||
agentId: fixtures.agent.id, generation: execution.profile.generation,
|
||||
runIds: selectedRuns.map(run => run.id) });
|
||||
const checks = gradeStockHarness(stock);
|
||||
matcherResults.push(...checks.map(check => ({ matcher: { kind: "json_path" as const,
|
||||
path: `stockHarness.${check.id}`, expected: true }, passed: check.passed, detail: check.detail })));
|
||||
await writeSanitizedJson(snapshotsDir, "stock-harness.json", { ...stock, checks }, secrets);
|
||||
const failures = checks.filter(check => !check.passed);
|
||||
if (failures.length && !primaryError) primaryError = new Error(`Stock harness matcher failures: ${failures.map(check => check.id).join(", ")}`);
|
||||
} catch (error) {
|
||||
await writeSanitizedJson(snapshotsDir, "stock-harness-evidence-error.json", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}, secrets);
|
||||
if (!primaryError) primaryError = error;
|
||||
}
|
||||
}
|
||||
await fixtures.teardown();
|
||||
const verification = await runCleanupWithObservers({
|
||||
retireRuns: async () => {
|
||||
await cancelActiveRunsForCleanup();
|
||||
if (companyRunFlow) {
|
||||
const companyRuns = await api.get<RunRecord[]>(`/api/companies/${fixtures!.company.id}/heartbeat-runs?limit=100`);
|
||||
selectedRuns = await Promise.all(companyRuns.map(run => api.get<RunRecord>(`/api/heartbeat-runs/${run.id}`)));
|
||||
await writeSanitizedJson(snapshotsDir, execution.task.flow === "first_task" ? "first-task-final-run-ledger.json" : "chat-final-run-ledger.json", selectedRuns, secrets);
|
||||
}
|
||||
if (execution.suite.id === "stock-harness") {
|
||||
try {
|
||||
const stock = await captureStockHarness({ api, companyId: fixtures!.company.id,
|
||||
agentId: fixtures!.agent.id, generation: execution.profile.generation,
|
||||
runIds: selectedRuns.map(run => run.id) });
|
||||
const checks = gradeStockHarness(stock);
|
||||
matcherResults.push(...checks.map(check => ({ matcher: { kind: "json_path" as const,
|
||||
path: `stockHarness.${check.id}`, expected: true }, passed: check.passed, detail: check.detail })));
|
||||
await writeSanitizedJson(snapshotsDir, "stock-harness.json", { ...stock, checks }, secrets);
|
||||
const failures = checks.filter(check => !check.passed);
|
||||
if (failures.length && !primaryError) primaryError = new Error(`Stock harness matcher failures: ${failures.map(check => check.id).join(", ")}`);
|
||||
} catch (error) {
|
||||
await writeSanitizedJson(snapshotsDir, "stock-harness-evidence-error.json", {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
}, secrets);
|
||||
if (!primaryError) primaryError = error;
|
||||
}
|
||||
}
|
||||
},
|
||||
assertions: beforeEnvironmentTeardownAssertions,
|
||||
teardown: () => fixtures!.teardown(),
|
||||
});
|
||||
matcherResults.push(...verification.checks.map(check => ({
|
||||
matcher: { kind: "json_path" as const, path: `remoteCleanup.${check.id}`, expected: true }, passed: check.passed, detail: check.detail,
|
||||
})));
|
||||
if (verification.errors.length) throw new AggregateError(verification.errors, "Cleanup or remote retirement verification failed");
|
||||
cleanup = "passed";
|
||||
} catch (error) {
|
||||
cleanup = "failed";
|
||||
@@ -2844,6 +2929,23 @@ for (const execution of executions) {
|
||||
: "passed";
|
||||
}
|
||||
|
||||
// Local fixture teardown does not retire the API server. These assertions
|
||||
// independently prove the recorded provider processes retired, while the
|
||||
// workspace still exists, before final grading. The outer supervisor
|
||||
// remains responsible for complete server/database cleanup.
|
||||
if (cleanupAssertions.length > 0) {
|
||||
const verification = await verifyCleanupAssertions(cleanupAssertions);
|
||||
matcherResults.push(...verification.checks.map(check => ({
|
||||
matcher: { kind: "json_path" as const, path: `cleanup.${check.id}`, expected: true },
|
||||
passed: check.passed, detail: check.detail,
|
||||
})));
|
||||
if (verification.errors.length > 0) {
|
||||
cleanup = "failed";
|
||||
primaryError = new AggregateError([primaryError, ...verification.errors].filter(Boolean), "Cleanup verification failed after provider settlement");
|
||||
if (failureClassOverride !== "secret_leak") failureClassOverride = "cleanup_failure";
|
||||
}
|
||||
}
|
||||
|
||||
const finishedAtMs = Date.now();
|
||||
const runtimeUsage = buildRuntimeUsage({
|
||||
environmentId: execution.environment.id,
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { createRunnerE2EServerStopper, runnerE2EServerDetached } from "./server-stop.js";
|
||||
import { readProcessTable } from "./process-tree.js";
|
||||
import { createProcessTreeOwner, stopOwnedProcessTree } from "./process-tree-owner.js";
|
||||
import { runnerE2ETypeScriptProcessArgs } from "./web-server-command.js";
|
||||
|
||||
const children: ChildProcess[] = [];
|
||||
const directories: string[] = [];
|
||||
const worker = `
|
||||
process.once('SIGTERM', () => {
|
||||
process.send('stopping');
|
||||
process.once('message', () => {
|
||||
process.send('close-complete', () => process.exit(0));
|
||||
});
|
||||
});
|
||||
process.send('ready');
|
||||
setInterval(() => {}, 1000);
|
||||
`;
|
||||
async function fixture(source = worker) {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-server-stop-"));
|
||||
directories.push(root);
|
||||
const entry = path.join(root, "worker.cjs");
|
||||
await writeFile(entry, source);
|
||||
return { root, entry };
|
||||
}
|
||||
function start(entry: string) {
|
||||
const child = spawn(process.execPath, [entry], {
|
||||
detached: runnerE2EServerDetached,
|
||||
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
||||
});
|
||||
children.push(child);
|
||||
return child;
|
||||
}
|
||||
function stopper(gracefulTimeoutMs = 2_000) {
|
||||
const logs: string[] = [];
|
||||
const errors = new WeakSet<ChildProcess>();
|
||||
const stop = createRunnerE2EServerStopper({
|
||||
gracefulTimeoutMs, forcedTimeoutMs: 2_000,
|
||||
hasSpawnError: child => errors.has(child),
|
||||
markExpectedStop: () => {}, log: line => logs.push(line),
|
||||
});
|
||||
return { stop, logs, errors };
|
||||
}
|
||||
afterEach(async () => {
|
||||
for (const child of children.splice(0)) {
|
||||
if (child.exitCode !== null || child.signalCode !== null) continue;
|
||||
const exited = once(child, "exit").catch(() => {});
|
||||
try {
|
||||
if (runnerE2EServerDetached && child.pid) process.kill(-child.pid, "SIGKILL");
|
||||
else child.kill("SIGKILL");
|
||||
} catch { child.kill("SIGKILL"); }
|
||||
await exited;
|
||||
}
|
||||
for (const directory of directories.splice(0)) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("joins signal, final cleanup and repeated calls while a once-handler finishes asynchronous close", async () => {
|
||||
const { entry } = await fixture();
|
||||
const child = start(entry);
|
||||
expect((await once(child, "message"))[0]).toBe("ready");
|
||||
const { stop, logs } = stopper();
|
||||
const stopping = once(child, "message");
|
||||
const first = stop(child);
|
||||
expect((await stopping)[0]).toBe("stopping");
|
||||
// The server supervisor reaches final cleanup after its 200ms poll.
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
const messages: unknown[] = [];
|
||||
child.on("message", message => messages.push(message));
|
||||
const finalCleanup = stop(child);
|
||||
const repeated = stop(child, "SIGINT");
|
||||
// Give an erroneous repeated signal time to interrupt the held close before
|
||||
// releasing it. A behavioral failure must not depend on promise identity.
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
if (child.connected) child.send("finish");
|
||||
await Promise.all([first, finalCleanup, repeated]);
|
||||
expect(messages).toContain("close-complete");
|
||||
expect([child.exitCode, child.signalCode]).toEqual([0, null]);
|
||||
expect(finalCleanup).toBe(first);
|
||||
expect(repeated).toBe(first);
|
||||
expect(stop(child)).toBe(first);
|
||||
await stop(child);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("bounds an unresponsive child and reaps it with one escalation", async () => {
|
||||
const { entry } = await fixture(`process.on('SIGTERM', () => {}); process.send('ready'); setInterval(() => {}, 1000);`);
|
||||
const child = start(entry);
|
||||
await once(child, "message");
|
||||
const { stop, logs } = stopper(50);
|
||||
await Promise.all([stop(child), stop(child), stop(child)]);
|
||||
expect(child.signalCode).toBe("SIGKILL");
|
||||
expect(logs).toHaveLength(1);
|
||||
expect(() => process.kill(child.pid!, 0)).toThrow();
|
||||
});
|
||||
|
||||
it("settles an already-exited child without signals or escalation", async () => {
|
||||
const { entry } = await fixture("process.exit(0)");
|
||||
const child = start(entry);
|
||||
await once(child, "exit");
|
||||
const { stop, logs } = stopper();
|
||||
await stop(child);
|
||||
expect([child.exitCode, child.signalCode, logs]).toEqual([0, null, []]);
|
||||
});
|
||||
|
||||
it("settles a failed spawn without attempting escalation", async () => {
|
||||
const { root } = await fixture();
|
||||
const child = spawn(path.join(root, "missing-server-executable"));
|
||||
const { stop, logs, errors } = stopper();
|
||||
child.once("error", () => errors.add(child));
|
||||
await new Promise<void>(resolve => child.once("error", () => resolve()));
|
||||
await stop(child);
|
||||
expect(logs).toEqual([]);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("lets launcher cancellation join wrapper shutdown without signaling the server twice", async () => {
|
||||
const { root, entry } = await fixture();
|
||||
const supervisor = path.join(root, "supervisor.mts");
|
||||
const helper = path.join(import.meta.dirname, "server-stop.ts");
|
||||
await writeFile(supervisor, `
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createRunnerE2EServerStopper, runnerE2EServerDetached } from ${JSON.stringify(helper)};
|
||||
const child = spawn(process.execPath, [${JSON.stringify(entry)}], {
|
||||
detached: runnerE2EServerDetached, stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
});
|
||||
const stop = createRunnerE2EServerStopper({ gracefulTimeoutMs: 2000, forcedTimeoutMs: 2000,
|
||||
hasSpawnError: () => false, markExpectedStop: () => {}, log: () => {} });
|
||||
const finish = () => { void stop(child).then(() => {
|
||||
process.send!({ exitCode: child.exitCode, signalCode: child.signalCode }, () => process.exit(0));
|
||||
}); };
|
||||
process.on('SIGTERM', finish);
|
||||
process.on('message', message => { if (message === 'stop') finish(); else child.send('finish'); });
|
||||
child.on('message', message => process.send!({ message, pid: child.pid }));
|
||||
`);
|
||||
const wrapper = spawn(process.execPath, runnerE2ETypeScriptProcessArgs(path.resolve(import.meta.dirname, "../.."), supervisor), {
|
||||
detached: true, stdio: ["ignore", "pipe", "pipe", "ipc"],
|
||||
});
|
||||
children.push(wrapper);
|
||||
let wrapperErrors = "";
|
||||
wrapper.stderr?.on("data", chunk => { wrapperErrors += chunk; });
|
||||
let workerPid: number | undefined;
|
||||
const owner = createProcessTreeOwner(wrapper);
|
||||
try {
|
||||
workerPid = (await once(wrapper, "message"))[0].pid;
|
||||
const stopping = once(wrapper, "message");
|
||||
wrapper.send("stop");
|
||||
expect((await stopping)[0].message).toBe("stopping");
|
||||
// If Paperclip shared the wrapper group, this would kill its once-handler
|
||||
// during the async close even though the helper sends only one signal.
|
||||
const messages: unknown[] = [];
|
||||
wrapper.on("message", message => messages.push(message));
|
||||
const exited = once(wrapper, "exit");
|
||||
await owner.observe();
|
||||
const cancellation = stopOwnedProcessTree(wrapper, owner, 2_000, 2_000);
|
||||
await new Promise(resolve => setTimeout(resolve, 250));
|
||||
if (wrapper.connected) wrapper.send("finish");
|
||||
await exited;
|
||||
await cancellation;
|
||||
expect(messages, wrapperErrors).toContainEqual({ message: "close-complete", pid: workerPid });
|
||||
expect(messages).toContainEqual({ exitCode: 0, signalCode: null });
|
||||
expect(() => process.kill(workerPid!, 0)).toThrow();
|
||||
} finally {
|
||||
owner.stopObserving();
|
||||
if (workerPid) { try { process.kill(-workerPid, "SIGKILL"); } catch { /* reaped */ } }
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
it.skipIf(process.platform === "win32")("escalates the owned server group so a hung descendant cannot remain", async () => {
|
||||
const { entry } = await fixture(`
|
||||
const { spawn } = require('node:child_process');
|
||||
const descendant = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' });
|
||||
process.on('SIGTERM', () => {});
|
||||
process.send({ pid: descendant.pid });
|
||||
setInterval(() => {}, 1000);
|
||||
`);
|
||||
const child = start(entry);
|
||||
const pid = (await once(child, "message"))[0].pid as number;
|
||||
try {
|
||||
await stopper(50).stop(child);
|
||||
expect(child.signalCode).toBe("SIGKILL");
|
||||
// A stopped orphan may remain a zombie until the host's init reaps it.
|
||||
const table = await readProcessTable();
|
||||
expect(table).not.toBeNull();
|
||||
expect(table!.some(row => row.pid === pid && !row.state?.startsWith("Z"))).toBe(false);
|
||||
} finally {
|
||||
try { process.kill(pid, "SIGKILL"); } catch { /* reaped */ }
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
it.skipIf(process.platform === "win32")("retires observed descendants after the server leader exits early", async () => {
|
||||
const { root, entry } = await fixture();
|
||||
const marker = path.join(root, "descendant-closed");
|
||||
const descendant = `
|
||||
process.once('SIGTERM', () => setTimeout(() => {
|
||||
require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'closed'); process.exit(0);
|
||||
}, 50));
|
||||
process.send('ready'); setInterval(() => {}, 1000);
|
||||
`;
|
||||
await writeFile(entry, `
|
||||
const child = require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(descendant)}], {
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
||||
});
|
||||
child.once('message', () => process.send({ pid: child.pid }));
|
||||
process.once('message', () => process.exit(1));
|
||||
`);
|
||||
const child = start(entry);
|
||||
const pid = (await once(child, "message"))[0].pid as number;
|
||||
const { stop } = stopper();
|
||||
try {
|
||||
await stop.watch(child);
|
||||
const exited = once(child, "exit");
|
||||
child.send("crash");
|
||||
await exited;
|
||||
await stop(child);
|
||||
expect(await readFile(marker, "utf8")).toBe("closed");
|
||||
const table = await readProcessTable();
|
||||
expect(table).not.toBeNull();
|
||||
expect(table!.some(row => row.pid === pid && !row.state?.startsWith("Z"))).toBe(false);
|
||||
} finally { try { process.kill(pid, "SIGKILL"); } catch { /* stopped */ } }
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")("recovers a failed cleanup without repeating the graceful signal", async () => {
|
||||
const { entry } = await fixture();
|
||||
const child = start(entry);
|
||||
await once(child, "message");
|
||||
let failInspection = false;
|
||||
let owner: ReturnType<typeof createProcessTreeOwner> | undefined;
|
||||
const messages: unknown[] = [];
|
||||
child.on("message", message => {
|
||||
messages.push(message);
|
||||
if (message === "stopping") failInspection = true;
|
||||
});
|
||||
const stop = createRunnerE2EServerStopper({
|
||||
gracefulTimeoutMs: 2_000, forcedTimeoutMs: 2_000,
|
||||
hasSpawnError: () => false, markExpectedStop: () => {}, log: () => {},
|
||||
createOwner: candidate => {
|
||||
owner = createProcessTreeOwner(candidate);
|
||||
return { ...owner, observe: async () => {
|
||||
if (failInspection) { failInspection = false; throw new Error("transient inspection failure"); }
|
||||
await owner!.observe();
|
||||
} };
|
||||
},
|
||||
});
|
||||
try {
|
||||
const failed = expect(stop(child)).rejects.toThrow("transient inspection failure");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
if (child.connected) child.send("finish");
|
||||
await failed;
|
||||
const recovery = stop(child);
|
||||
// A second graceful signal would terminate this child's once-handler.
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
if (child.connected) child.send("finish");
|
||||
await recovery;
|
||||
expect(messages).toEqual(["stopping", "close-complete"]);
|
||||
expect([child.exitCode, child.signalCode]).toEqual([0, null]);
|
||||
} finally { owner?.stopObserving(); }
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === 'win32').each([['launcher', 'null'], ['server', 'null'], ['launcher', 'throw'], ['server', 'throw']] as const)(
|
||||
'bounds the known %s child when inspection fails with %s', async (kind, failure) => {
|
||||
const { entry } = await fixture(`process.on('SIGTERM', () => {}); process.send('ready'); setInterval(() => {}, 1000);`);
|
||||
const child = start(entry);
|
||||
await once(child, 'message');
|
||||
const groupSignals: number[] = [];
|
||||
const owner = createProcessTreeOwner(child, {
|
||||
readTable: async () => { if (failure === "throw") throw new Error("inspection failed"); return null; },
|
||||
signalGroup: pid => { groupSignals.push(pid); },
|
||||
});
|
||||
try {
|
||||
const stopping = kind === 'launcher'
|
||||
? stopOwnedProcessTree(child, owner, 50, 500)
|
||||
: createRunnerE2EServerStopper({ gracefulTimeoutMs: 50, forcedTimeoutMs: 500,
|
||||
hasSpawnError: () => false, markExpectedStop: () => {}, log: () => {}, createOwner: () => owner })(child);
|
||||
await expect(stopping).rejects.toThrow(/inspect|incomplete/i);
|
||||
expect(child.signalCode).toBe('SIGKILL');
|
||||
expect(groupSignals).toEqual([]);
|
||||
} finally { owner.stopObserving(); }
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === 'win32')('does not re-signal a server after its graceful wrapper forwards and exits', async () => {
|
||||
const { root, entry } = await fixture();
|
||||
const marker = path.join(root, 'async-close-finished');
|
||||
await writeFile(entry, `
|
||||
const child = require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(`
|
||||
process.once('SIGTERM', () => setTimeout(() => {
|
||||
require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'closed'); process.exit(0);
|
||||
}, 300));
|
||||
process.send('ready'); setInterval(() => {}, 1000);
|
||||
`)}], { detached: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
|
||||
child.once('message', () => process.send({ pid: child.pid }));
|
||||
process.once('SIGTERM', () => { child.kill('SIGTERM'); process.exit(0); });
|
||||
`);
|
||||
const wrapper = start(entry);
|
||||
const pid = (await once(wrapper, 'message'))[0].pid as number;
|
||||
const owner = createProcessTreeOwner(wrapper);
|
||||
try {
|
||||
await owner.observe();
|
||||
await stopOwnedProcessTree(wrapper, owner, 2_000, 500);
|
||||
expect(await readFile(marker, 'utf8')).toBe('closed');
|
||||
expect(wrapper.exitCode).toBe(0);
|
||||
} finally {
|
||||
owner.stopObserving();
|
||||
try { process.kill(-pid, 'SIGKILL'); } catch { /* already stopped */ }
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import { createProcessTreeOwner, incompleteTreeFallback } from "./process-tree-owner.js";
|
||||
|
||||
// The wrapper receives Playwright's group signal; only it signals Paperclip.
|
||||
export const runnerE2EServerDetached = process.platform !== "win32";
|
||||
const wait = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));
|
||||
|
||||
export function createRunnerE2EServerStopper(options: {
|
||||
gracefulTimeoutMs: number;
|
||||
forcedTimeoutMs: number;
|
||||
hasSpawnError: (child: ChildProcess) => boolean;
|
||||
markExpectedStop: (child: ChildProcess) => void;
|
||||
log: (message: string) => void;
|
||||
createOwner?: typeof createProcessTreeOwner;
|
||||
}) {
|
||||
type State = {
|
||||
owner: ReturnType<typeof createProcessTreeOwner>;
|
||||
promise?: Promise<void>;
|
||||
gracefulDeadline?: number;
|
||||
forcedDeadline?: number;
|
||||
gracefulSent: boolean;
|
||||
groupSignals: Set<number>;
|
||||
escalationLogged: boolean;
|
||||
};
|
||||
const states = new WeakMap<ChildProcess, State>();
|
||||
const exited = (child: ChildProcess) => child.exitCode !== null || child.signalCode !== null || options.hasSpawnError(child);
|
||||
function watch(child: ChildProcess) {
|
||||
let state = states.get(child);
|
||||
if (!state) {
|
||||
state = { owner: (options.createOwner ?? createProcessTreeOwner)(child), gracefulSent: false, groupSignals: new Set(), escalationLogged: false };
|
||||
states.set(child, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
async function stopOnce(child: ChildProcess, state: State, signal: NodeJS.Signals) {
|
||||
state.gracefulDeadline ??= Date.now() + options.gracefulTimeoutMs;
|
||||
await state.owner.observe();
|
||||
if (!exited(child) && !state.gracefulSent) {
|
||||
state.gracefulSent = child.kill(signal);
|
||||
}
|
||||
while (Date.now() < state.gracefulDeadline) {
|
||||
await state.owner.observe();
|
||||
if (exited(child)) {
|
||||
if (!state.owner.liveGroups().length) { state.owner.stopObserving(); return; }
|
||||
// The leader is gone. Retire only descendants whose start identities
|
||||
// we observed while they belonged to this server, including private groups.
|
||||
const unsignaled = new Set(state.owner.liveGroups().map(group => group.processGroupId).filter(pid => !state.groupSignals.has(pid)));
|
||||
for (const pid of await state.owner.signal("SIGTERM", unsignaled)) state.groupSignals.add(pid);
|
||||
}
|
||||
await wait(25);
|
||||
}
|
||||
if (!state.escalationLogged) {
|
||||
options.log(`\nPaperclip did not stop within ${options.gracefulTimeoutMs}ms; sending SIGKILL\n`);
|
||||
state.escalationLogged = true;
|
||||
}
|
||||
if (runnerE2EServerDetached) await state.owner.signal("SIGKILL");
|
||||
else if (!exited(child)) child.kill("SIGKILL");
|
||||
state.forcedDeadline ??= Date.now() + options.forcedTimeoutMs;
|
||||
do {
|
||||
await state.owner.observe();
|
||||
if (exited(child) && !state.owner.liveGroups().length) { state.owner.stopObserving(); return; }
|
||||
await wait(25);
|
||||
} while (Date.now() < state.forcedDeadline);
|
||||
throw new Error("Paperclip server or observed descendants did not exit after SIGKILL");
|
||||
}
|
||||
const stop = (child: ChildProcess, signal: NodeJS.Signals = "SIGTERM"): Promise<void> => {
|
||||
options.markExpectedStop(child);
|
||||
const state = watch(child);
|
||||
state.promise ??= Promise.resolve().then(() => stopOnce(child, state, signal)).catch(async error => {
|
||||
try {
|
||||
await incompleteTreeFallback(error, child, state, state.gracefulDeadline!, options.forcedTimeoutMs);
|
||||
} finally {
|
||||
state.promise = undefined;
|
||||
}
|
||||
});
|
||||
/* Retain the signal/deadline phase so a later audit can recover without
|
||||
repeating the graceful signal. */
|
||||
return state.promise;
|
||||
};
|
||||
return Object.assign(stop, { watch: (child: ChildProcess) => watch(child).owner.observe() });
|
||||
}
|
||||
+20
-66
@@ -1,3 +1,4 @@
|
||||
import { createRunnerE2EServerStopper, runnerE2EServerDetached } from "./server-stop.js";
|
||||
import { runnerE2ETypeScriptProcessArgs } from "./web-server-command.js";
|
||||
import { qualifyLegacyClaudeCli } from "./legacy-claude-cli.js";
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
@@ -105,7 +106,7 @@ function describeChildExit(candidate: ChildProcess) {
|
||||
return `server exited code=${String(candidate.exitCode)} signal=${String(candidate.signalCode)}`;
|
||||
}
|
||||
|
||||
function startServer() {
|
||||
async function startServer() {
|
||||
if (shutdownRequested()) {
|
||||
throw new Error("Refusing to start Paperclip after wrapper shutdown");
|
||||
}
|
||||
@@ -116,10 +117,9 @@ function startServer() {
|
||||
cwd: repositoryRoot,
|
||||
env: definedServerEnvironment,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
// Stay in the launcher-created process group. That lets the launcher stop
|
||||
// Playwright, this wrapper, Paperclip, embedded Postgres, and runner children
|
||||
// as one verified tree even if graceful web-server shutdown stalls.
|
||||
detached: false,
|
||||
// Playwright signals the wrapper's group. Keep that signal from bypassing
|
||||
// our single graceful stop; the launcher still tracks descendant groups.
|
||||
detached: runnerE2EServerDetached,
|
||||
},
|
||||
);
|
||||
child = candidate;
|
||||
@@ -152,13 +152,10 @@ function startServer() {
|
||||
// A shutdown may arrive in the synchronous interval around spawn. Never let
|
||||
// that race create an unowned replacement server.
|
||||
if (shutdownSignal) {
|
||||
expectedStops.add(candidate);
|
||||
try {
|
||||
candidate.kill(shutdownSignal);
|
||||
} catch {
|
||||
// The process may have failed during spawn.
|
||||
}
|
||||
// The main/error path awaits this same promise and reports any failure.
|
||||
void stopServer(candidate, shutdownSignal).catch(() => {});
|
||||
}
|
||||
await stopServer.watch(candidate);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
@@ -166,53 +163,13 @@ function delay(milliseconds: number) {
|
||||
return new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
async function waitForExit(candidate: ChildProcess, timeoutMs: number) {
|
||||
if (childExited(candidate) || childErrors.has(candidate)) return true;
|
||||
return await new Promise<boolean>((resolve) => {
|
||||
let settled = false;
|
||||
const finish = (exited: boolean) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
candidate.off("exit", onExit);
|
||||
candidate.off("error", onError);
|
||||
resolve(exited);
|
||||
};
|
||||
const onExit = () => finish(true);
|
||||
const onError = () => finish(true);
|
||||
const timeout = setTimeout(() => finish(false), timeoutMs);
|
||||
candidate.once("exit", onExit);
|
||||
candidate.once("error", onError);
|
||||
});
|
||||
}
|
||||
|
||||
async function stopServer(
|
||||
candidate: ChildProcess,
|
||||
signal: NodeJS.Signals = "SIGTERM",
|
||||
) {
|
||||
expectedStops.add(candidate);
|
||||
if (childExited(candidate) || childErrors.has(candidate)) return;
|
||||
try {
|
||||
candidate.kill(signal);
|
||||
} catch {
|
||||
if (childExited(candidate) || childErrors.has(candidate)) return;
|
||||
throw new Error("Could not signal the Paperclip server to stop");
|
||||
}
|
||||
if (await waitForExit(candidate, gracefulStopTimeoutMs)) return;
|
||||
|
||||
appendLog(
|
||||
`\nPaperclip did not stop within ${gracefulStopTimeoutMs}ms; sending SIGKILL\n`,
|
||||
);
|
||||
try {
|
||||
candidate.kill("SIGKILL");
|
||||
} catch {
|
||||
if (childExited(candidate) || childErrors.has(candidate)) return;
|
||||
throw new Error("Could not force the Paperclip server to stop");
|
||||
}
|
||||
if (!(await waitForExit(candidate, 5_000))) {
|
||||
throw new Error("Paperclip server did not exit after SIGKILL");
|
||||
}
|
||||
}
|
||||
const stopServer = createRunnerE2EServerStopper({
|
||||
gracefulTimeoutMs: gracefulStopTimeoutMs,
|
||||
forcedTimeoutMs: 5_000,
|
||||
hasSpawnError: (candidate) => childErrors.has(candidate),
|
||||
markExpectedStop: (candidate) => { expectedStops.add(candidate); },
|
||||
log: appendLog,
|
||||
});
|
||||
|
||||
async function waitForHealth(candidate: ChildProcess) {
|
||||
const deadline = Date.now() + restartTimeoutMs;
|
||||
@@ -324,7 +281,7 @@ async function restartServer(requestId: string) {
|
||||
}
|
||||
|
||||
appendLog(`Restart request ${requestId}: starting Paperclip\n`);
|
||||
const replacement = startServer();
|
||||
const replacement = await startServer();
|
||||
await waitForHealth(replacement);
|
||||
if (shutdownRequested()) {
|
||||
throw new Error("Wrapper shutdown interrupted the Paperclip restart");
|
||||
@@ -339,12 +296,9 @@ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"] as const) {
|
||||
if (shutdownSignal) return;
|
||||
shutdownSignal = signal;
|
||||
if (!child) return;
|
||||
expectedStops.add(child);
|
||||
try {
|
||||
child.kill(signal);
|
||||
} catch {
|
||||
// The Paperclip process may already have exited.
|
||||
}
|
||||
// Begin immediately, including during a health/restart wait. The final
|
||||
// cleanup joins this promise instead of sending a second graceful signal.
|
||||
void stopServer(child, signal).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -360,7 +314,7 @@ async function supervise() {
|
||||
});
|
||||
// Postgres needs the socket itself; release immediately before child spawn.
|
||||
await databaseReservation?.close();
|
||||
startServer();
|
||||
await startServer();
|
||||
let lastRestartRequestId: string | null = null;
|
||||
while (!shutdownRequested()) {
|
||||
if (unexpectedChildFailure) throw unexpectedChildFailure;
|
||||
|
||||
@@ -29,7 +29,9 @@ export type RunnerTaskFlow =
|
||||
| "question_resume_completion"
|
||||
| "plan_approval_completion"
|
||||
| "warm_three_turn"
|
||||
| "instruction_persistence";
|
||||
| "instruction_persistence"
|
||||
| "native_active_stop"
|
||||
| "cursor_native";
|
||||
|
||||
export interface SecretReference {
|
||||
type: "secret_ref";
|
||||
|
||||
Reference in new issue
Block a user