Wire native Daytona qualification and warm ACP journeys

Withhold native tasks until exact owned observers are armed, preserve sealed retirement proof before environment teardown, and register explicit local and Daytona warm continuity cases.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-09-29 17:26:29 -05:00
1 parent 84a52694af
commit fe92554788
17 files changed
+585 -188

No files matched your search

+5
View File
@@ -16,3 +16,8 @@ PAPERCLIP_E2E_DAYTONA_IMAGE=ghcr.io/paperclipai/paperclip-daytona-runner@sha256:
# Optional, explicit subscription qualification only. Supply privately at runtime;
# never commit an actual auth.json payload. API-key profiles do not use this value.
# GROK_AUTH_JSON=
# Native Cursor/Pi/Copilot Daytona fixtures additionally require exact executable
# digests from that immutable Linux image (not the local controller binaries).
# PAPERCLIP_E2E_DAYTONA_NODE_SHA256=sha256:REPLACE_ME
# PAPERCLIP_E2E_DAYTONA_RUNNERD_SHA256=sha256:REPLACE_ME
+20 -5
View File
@@ -260,8 +260,9 @@ is explicit-only. No private control-plane hooks or direct database writes are u
## Pi native boundaries
The explicit-only `pi-native` suite has three local candidate cells and no automatic
retries. `native-questions` answers the real runner-owned Pi select, confirm, input
The explicit-only `pi-native` suite has four local and three Daytona candidate
cells, with no automatic retries. The remote suite excludes automatic deny-all
because its initial native file read is itself denied. `native-questions` answers the real runner-owned Pi select, confirm, input
and editor tool through four durable browser cards, reloading before every answer.
Undisclosed text and independent workspace JSON prove delivery to the same live run.
Pi's SDK cannot distinguish negative confirmation from dismissal; the expected
@@ -279,7 +280,8 @@ no database writes, private hooks, or fabricated provider results are allowed.
## Copilot native protection
The explicit-only `copilot-protection` suite has two local, one-run cells (120s
The explicit-only `copilot-protection` suite has two cases on local and Daytona,
each with one run (120s
provider timeout, 300s attempt budget). `native-permission-deny-write` denies one
exact native edit through its browser card, waits for the delivered rejection and
failed tool, then cancels through the public run API. Its expected outcome is a
@@ -290,7 +292,7 @@ change makes no-effect coverage incomplete; stat polling alone cannot pass.
`attached-async-settlement` starts a fixed finite command with explicit async mode
and `detach:false`, then asks the model to attempt immediate completion. A one-shot
private local socket accepts only the fixture nonce, never an executable or command;
private socket in the tested environment accepts only the fixture nonce, never an executable or command;
the test owns/reaps a predeclared child and records its actual exit before releasing
the provider-launched client. The independent marker, client retirement, native shell
linkage and actual durable turn terminal must agree. Fixture resources close in a
@@ -314,10 +316,23 @@ retained warm daemon as a leaked per-run process or signals an API-provided PID.
Directory-watch coverage also rejects parent device/inode replacement or removal.
The manual `cursor-native` suite has four local Cursor candidate cells with
The manual `cursor-native` suite has four cases on each of local and Daytona with
one expected provider run each and a 120-second provider deadline. Browser
choices, rejection feedback, native origin/decision receipts, workspace checks
and provider retirement are independently checked. Failed or missing cleanup
assertions fail the final report even if the native interaction passed. No
native callback, private-HOME artifact export, or paid qualification is inferred
from a semantic question or plan result.
### Remote native proof scope
Remote native cells require the exact authenticated lease, run, immutable image
and executable bindings documented in [the runbook](README.md#remote-native-evidence-and-warm-continuation).
Action publication follows observer readiness and a saved baseline. The observer
seals before environment destruction and retains file bytes on the host; no
post-deletion RPC or host-copy-back evidence may satisfy remote no-effect or
retirement checks. Runtime-internal files are an explicit scoped exclusion.
`human-permission-denial` requires native request/tool correlation, the browser's
exact Decline, delivered denial and failed write, and unchanged file evidence
through retirement. All normal project and company boundaries apply.
+46 -5
View File
@@ -124,6 +124,7 @@ Shell variables take precedence over the local file. The recognized names are:
- `CURSOR_AUTH_TOKEN` (extended Cursor candidate)
- `COPILOT_GITHUB_TOKEN` (extended Copilot candidate)
- `PAPERCLIP_E2E_DAYTONA_IMAGE` (Daytona only)
- `PAPERCLIP_E2E_DAYTONA_NODE_SHA256` and `PAPERCLIP_E2E_DAYTONA_RUNNERD_SHA256` (native Cursor/Pi/Copilot Daytona fixtures; exact `sha256:...` executable digests from that image)
The image must be an immutable `image@sha256:...` reference. The launcher
reports missing variable names but never prints values. It passes raw provider
@@ -1280,8 +1281,10 @@ mock control plane. Neither suite substitutes for the other.
### Pi native Product fixtures
The separate `pi-native` suite defines three explicit local Pi cells:
`native-questions`, `agent-files-fresh-run`, and `restrictive-denial`. It uses the
The separate `pi-native` suite defines seven explicit Pi cells: native questions,
agent-file persistence and browser permission denial on local and Daytona, plus
a local-only automatic `restrictive-denial` case. The latter cannot use the remote
setup read under `deny-all`, so it is explicitly excluded there. It uses the
pinned candidate profile and exact OpenRouter model. It is excluded from `--all`,
never automatically retries, and retains qualification as pending until live proof.
Reserve and reconcile each paid cell just as for `extended-harnesses`.
@@ -1296,11 +1299,13 @@ the durable browser form bridge. The existing five extended-harness journeys
continue to prove semantic Paperclip questions and planning separately. Personal
file persistence uses two fresh task runs and independent byte checks; restrictive
denial uses one run and requires both a failed tool receipt and no file effect.
`human-permission-denial` additionally requires the exact browser Decline response,
delivered native denial and independent file/process observation through retirement.
See [the fixture contract](FIXTURES.md#pi-native-boundaries) for the exact oracles
and the limits of reconnect evidence.
The manual `copilot-protection` suite selects only two local Copilot candidate
cells. Discover them with `pnpm test:e2e:runner -- --list --suite copilot-protection`.
The manual `copilot-protection` suite selects two Copilot candidate cases on
each of local and Daytona (four cells). Discover them with `pnpm test:e2e:runner -- --list --suite copilot-protection`.
See [Copilot native protection](./FIXTURES.md#copilot-native-protection) for the
expected cancelled negative test, finite attached-process oracle, evidence limits,
and required rebuilt runtime. Registration is not a qualification claim.
@@ -1308,7 +1313,8 @@ and required rebuilt runtime. Registration is not a qualification claim.
### Cursor native interactions (candidate)
The explicit-only local `cursor-native` suite exercises the native Cursor
The explicit-only `cursor-native` suite has eight local/Daytona cells exercising
the native Cursor
question callback, plan rejection/revision/acceptance, plan cancellation, and
permission denial across browser reload. List it with
`pnpm test:e2e:runner -- --list --suite cursor-native`. The fixture configures
@@ -1323,3 +1329,38 @@ responsibility. These cases remain unqualified until paid runs pass.
The full native plan text is retained in the interaction card. Exporting a plan
file from Cursor's private HOME as a downloadable Paperclip artifact remains a
separate capability gap; these callback tests do not claim that export works.
### Remote native evidence and warm continuation
All three native suites use an operator-published instruction file to withhold
actual work until independent observers are armed inside the exact owned Daytona
sandbox. The initial task only reads that file. Explicitly typed setup reads are
separate from the native operation under test; unknown or extra writes/commands
still fail. SDK 0.203.0, immutable image and executable digests, public run/lease
ownership, sandbox labels and workspace sentinel are verified before execution.
The observer watches registered targets (including transient create/delete), user
workspace changes and the exact runner process plus descendants. The single
controller-owned `.paperclip-runtime/paperclip-runner` subtree is excluded from
user-file inventory and mutation counts: it holds the binary, provider pack,
context and active runtime state. Its location and identity remain checked, and
test targets cannot use it. This exclusion is recorded in evidence; it does not
claim that runtime-internal writes are covered by the user-file oracle.
A sealed receipt and bounded file bytes must reach the host before lease cleanup.
Missing receipts, incomplete watches, ambiguous or reused process identities, and
unproven retirement fail the cell. Sandbox deletion and host file copy-back cannot
substitute for remote proof. The observed PRP environment identifier is retained
as unverified metadata; the remote process is bound through the exact sandbox,
run ID, lifecycle, process group and executable digest. Same-UID observer isolation
is not an adversarial operating-system sandbox test.
`--suite rich-acp-warm-continuity` adds six explicit cells: all three providers on
local and Daytona. Three browser-driven turns must preserve native session,
provider session, runner instance, PID/start identity and project workspace.
Daytona also requires one continuously running sandbox and created/resumed/resumed
lease history. Each turn has a 120-second limit; each three-run cell has a
420-second budget and must be reserved accordingly. Existing Codex warm cells
remain separate. All these suites are excluded from `--all`, never automatically
retry, and remain pending qualification until their paid evidence passes.
+3 -3
View File
@@ -91,10 +91,10 @@ describe("runner E2E catalog", () => {
expect(localIntegrityTasks).toHaveLength(2);
expect(openRouterBreadthTasks).toHaveLength(3);
expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([
4, 3, 2, 30, 3, 16, 16, 2, 8, 46, 23, 47, 20, 52, 28, 18, 6, 6, 10, 48, 16, 10, 2,
8, 7, 4, 6, 30, 3, 16, 16, 2, 8, 46, 23, 47, 20, 52, 28, 18, 6, 6, 10, 48, 16, 10, 2,
]);
expect(validateRunnerCatalog()).toHaveLength(416);
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(416);
expect(validateRunnerCatalog()).toHaveLength(432);
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(432);
expect(
runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"),
).toHaveLength(48);
+22 -8
View File
@@ -970,7 +970,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 },
];
},
};
@@ -1035,22 +1035,36 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [
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: [localEnvironment], tasks: cursorNativeTasks, expectedMatrixSize: 4,
definitionMetadata: { version: 1, qualification: "pending", scheduling: "explicit-only", profileVersion: QUALIFIED_ACPX_PROFILES.cursor.agentProfileVersion, modeAdmission: "native-config-ack", artifactExport: "pending-private-home" },
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: "pi-native", label: "Pi native boundaries", manualOnly: true,
description: "Explicit local Pi native forms, registered agent files and restrictive permission qualification.",
description: "Pi native forms, registered agent files and human permission denial on local and Daytona execution; automatic deny-all remains local-only.",
groups: ["native"], profiles: extendedHarnessProfiles.filter(profile => profile.qualificationCandidate === "pi"),
environments: [localEnvironment], tasks: piNativeTasks, expectedMatrixSize: 3,
definitionMetadata: { version: 1, qualification: "pending", scheduling: "explicit-only", profileVersion: QUALIFIED_ACPX_PROFILES.pi.agentProfileVersion },
environments: runnerEnvironments, tasks: piNativeTasks, expectedMatrixSize: 7,
excludedExecutionIds: ["pi-native.runner-acpx-pi.daytona.restrictive-denial"],
definitionMetadata: { version: 2, qualification: "pending", scheduling: "explicit-only", profileVersion: QUALIFIED_ACPX_PROFILES.pi.agentProfileVersion, remoteDenyAll: "unsupported-native-bootstrap-read-is-denied", remoteEvidence: "owned-lease-sealed-observer" },
},
{
id: "copilot-protection", label: "Copilot native protection", manualOnly: true,
description: "Exact native denial with explicit operator cancellation, and attached command settlement with independent process evidence.",
groups: ["native"], profiles: extendedHarnessProfiles.filter(profile => profile.qualificationCandidate === "copilot"),
environments: [localEnvironment], tasks: copilotProtectionTasks, expectedMatrixSize: 2,
definitionMetadata: { version: 1, qualification: "pending", scheduling: "explicit-only", evidence: "copilot_tool_evidence_v1", profileVersion: QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion, denialTerminal: "explicit-public-cancellation", settlement: "attached-finite-command-only" },
environments: runnerEnvironments, tasks: copilotProtectionTasks, expectedMatrixSize: 4,
definitionMetadata: { version: 2, qualification: "pending", scheduling: "explicit-only", evidence: "copilot_tool_evidence_v1", profileVersion: QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion, denialTerminal: "explicit-public-cancellation", settlement: "attached-finite-command-only", remoteEvidence: "owned-lease-sealed-observer" },
},
{
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, Copilot and Pi.",
groups: ["native", "warm"],
profiles: extendedHarnessProfiles.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: 6,
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,
+17 -1
View File
@@ -1,5 +1,5 @@
import { expect, it } from "vitest";
import { verifyCleanupAssertions } from "./cleanup-verification.js";
import { runCleanupWithObservers, verifyCleanupAssertions } from "./cleanup-verification.js";
it("retains a failed cleanup proof and still closes every later observer", async () => {
let closed = 0;
@@ -21,3 +21,19 @@ it("refuses an assertion that silently omits its proof", 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" });
});
+15
View File
@@ -20,3 +20,18 @@ export async function verifyCleanupAssertions(assertions: readonly CleanupAssert
}
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 };
}
+2 -2
View File
@@ -4,14 +4,14 @@ export interface CopilotToolNotice {
observedAtMs: number; seq: number;
stage: "tool" | "permission_requested" | "permission_delivered";
status?: "pending" | "in_progress" | "completed" | "failed";
operation?: "edit" | "execute"; target?: string; requestId?: string;
operation?: "edit" | "execute" | "read"; target?: string; requestId?: string;
declineOffered?: boolean; outcome?: "allow_once" | "allow_always" | "reject_once" | "cancel";
commandSha256?: string; mode?: "sync" | "async"; detach?: boolean;
shellId?: string; commandToolCallId?: string; shellState?: "started" | "completed"; exitCode?: number;
}
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: ["edit", "execute"], outcome: ["allow_once", "allow_always", "reject_once", "cancel"], mode: ["sync", "async"], shellState: ["started", "completed"] };
const enums = { stage: ["tool", "permission_requested", "permission_delivered"], status: ["pending", "in_progress", "completed", "failed"], operation: ["edit", "execute", "read"], outcome: ["allow_once", "allow_always", "reject_once", "cancel"], mode: ["sync", "async"], shellState: ["started", "completed"] };
const names = new Set(["stage", "toolCallId", "status", "operation", "target", "requestId", "declineOffered", "outcome", "commandSha256", "mode", "detach", "shellId", "commandToolCallId", "shellState", "exitCode"]);
export function readCopilotToolEvidence(rows: readonly unknown[], expectedRunId: string): CopilotToolNotice[] {
const result: CopilotToolNotice[] = [];
@@ -22,9 +22,10 @@ function projected(name: string) {
return { rows, notices: readCopilotToolEvidence(rows, "run") };
}
describe("Copilot Product protection integration", () => {
it("registers exactly two explicit local cells with honest terminal expectations", () => {
it("registers two explicit cases on both environments with honest terminal expectations", () => {
const cells = runnerMatrix.filter(x => x.suite.id === "copilot-protection");
expect(cells).toHaveLength(2); expect(cells.every(c => c.environment.id === "local" && c.profile.qualificationCandidate === "copilot" && c.task.expectedRunCount === 1)).toBe(true);
expect(cells).toHaveLength(4); expect(new Set(cells.map(c => c.environment.id))).toEqual(new Set(["local", "daytona"]));
expect(cells.every(c => c.profile.qualificationCandidate === "copilot" && c.task.expectedRunCount === 1)).toBe(true);
expect(cells.find(c => c.task.id === "native-permission-deny-write")!.task.expectedTerminalState).toEqual({ issue: "in_progress", run: "cancelled" });
expect(selectRunnerExecutions(parseRunnerSelectors(["--all"])).some(x => x.suite.id === "copilot-protection")).toBe(false);
});
@@ -1,3 +1,4 @@
import { assertRemoteNativeEvidencePrerequisites } from "./prerequisites.js";
import { describe, expect, it } from "vitest";
import { runnerMatrix, runnerSuites, extendedHarnessProfiles, extendedHarnessFileTask } from "./catalog.js";
import { buildRunnerE2EProcessEnvironment, buildPaperclipServerEnvironment } from "./harness-env.js";
@@ -37,6 +38,39 @@ describe("extended ACP harness qualification", () => {
expect(buildRunnerE2EProcessEnvironment(ambient, []).PAPERCLIP_RUNNER_ACPX_QUALIFICATION).toBeUndefined();
expect(() => buildRunnerE2EProcessEnvironment({}, [{ ...cell, suite: { ...cell.suite, manualOnly: false } }])).toThrow("explicit");
});
it("adds six explicit local/Daytona warm cells without admitting them implicitly", () => {
const warm = runnerMatrix.filter(cell => cell.suite.id === "rich-acp-warm-continuity");
expect(warm).toHaveLength(6);
expect(new Set(warm.map(cell => cell.profile.qualificationCandidate))).toEqual(new Set(["cursor", "copilot", "pi"]));
for (const cell of warm) {
expect(cell.task).toMatchObject({ flow: "warm_three_turn", expectedRunCount: 3 });
expect(cell.task.buildMatchers("nonce", cell)).toContainEqual({ kind: "environment", expected: cell.environment.id });
const config = cell.profile.buildAgent({ executionId: "warm", environmentId: "env", environmentFixtureId: cell.environment.id, workspacePath: "/tmp/workspace", secretRefs: { [cell.profile.credential]: { type: "secret_ref", secretId: "11111111-1111-4111-8111-111111111111", version: "latest" } } }).adapterConfig;
expect(config).toMatchObject({ lifecycleMode: "warm", idleTimeoutMs: 300_000, timeoutSec: 120 });
expect(JSON.parse(buildRunnerE2EProcessEnvironment({}, [cell]).PAPERCLIP_RUNNER_ACPX_QUALIFICATION!)).toEqual([{ agent: cell.profile.qualificationCandidate, model: cell.profile.model }]);
expect(() => buildRunnerE2EProcessEnvironment({}, [{ ...cell, suite: { ...cell.suite, manualOnly: false } }])).toThrow("explicit");
}
expect(selectRunnerExecutions(parseRunnerSelectors(["--all"])).some(cell => cell.suite.id === "rich-acp-warm-continuity")).toBe(false);
});
it("admits native qualification only for its matching provider and explicit suite", () => {
for (const suiteId of ["cursor-native", "pi-native", "copilot-protection"]) {
const cells = runnerMatrix.filter(cell => cell.suite.id === suiteId);
expect(new Set(cells.map(cell => cell.environment.id))).toEqual(new Set(["local", "daytona"]));
for (const cell of cells) {
expect(buildRunnerE2EProcessEnvironment({}, [cell]).PAPERCLIP_RUNNER_ACPX_QUALIFICATION).toBeDefined();
expect(() => buildRunnerE2EProcessEnvironment({}, [{ ...cell, profile: { ...cell.profile, qualificationCandidate: cell.profile.qualificationCandidate === "pi" ? "cursor" : "pi" } }])).toThrow("explicit");
}
}
});
it("requires both image executable pins for remote native cases before setup", () => {
const remote = runnerMatrix.filter(cell => cell.environment.id === "daytona" && ["cursor-native", "pi-native", "copilot-protection"].includes(cell.suite.id));
const valid = { PAPERCLIP_E2E_DAYTONA_NODE_SHA256: `sha256:${"a".repeat(64)}`, PAPERCLIP_E2E_DAYTONA_RUNNERD_SHA256: `sha256:${"b".repeat(64)}` };
expect(() => assertRemoteNativeEvidencePrerequisites(remote, valid)).not.toThrow();
for (const field of Object.keys(valid)) expect(() => assertRemoteNativeEvidencePrerequisites(remote, { ...valid, [field]: "latest" })).toThrow(field);
expect(() => assertRemoteNativeEvidencePrerequisites(remote, {})).toThrow("exact image executable digests");
expect(() => assertRemoteNativeEvidencePrerequisites(selected, {})).not.toThrow();
expect(() => assertRemoteNativeEvidencePrerequisites(runnerMatrix.filter(cell => cell.environment.id === "local"), {})).not.toThrow();
});
it("grades the actual file independently of the model's validation claim", () => {
const cell = selected.find(cell => cell.task.id === "file-edit-validate")!;
expect(extendedHarnessFileTask.buildMatchers("nonce", cell)).toContainEqual({ kind: "file_exact", path: "extended-nonce.txt", expected: "verified-nonce\n" });
+4 -1
View File
@@ -116,7 +116,10 @@ export function buildRunnerE2EProcessEnvironment(
const agent = execution.profile.qualificationCandidate;
if (!agent) continue;
const admittedSuite = execution.suite.id === "extended-harnesses"
|| (execution.suite.id === "pi-native" && agent === "pi" && execution.environment.id === "local");
|| execution.suite.id === "rich-acp-warm-continuity"
|| (execution.suite.id === "pi-native" && agent === "pi")
|| (execution.suite.id === "cursor-native" && agent === "cursor")
|| (execution.suite.id === "copilot-protection" && agent === "copilot");
if (!admittedSuite || !execution.suite.manualOnly) {
throw new Error("Candidate qualification requires an explicit provider qualification suite");
}
+2 -1
View File
@@ -49,7 +49,7 @@ import {
type MatrixExecution,
type RunnerE2EResult,
} from "./types.js";
import { assertRunnerE2EPrerequisites } from "./prerequisites.js";
import { assertRemoteNativeEvidencePrerequisites, assertRunnerE2EPrerequisites } from "./prerequisites.js";
import {
reapNewDetachedDarwinSharedMemory,
snapshotDarwinSharedMemory,
@@ -1100,6 +1100,7 @@ async function main() {
assertRunnerE2EPrerequisites(executions);
await loadLocalEnvironment(process.env);
assertRemoteNativeEvidencePrerequisites(executions, process.env);
const missingCredentials = [
...new Set(
executions.flatMap((execution) => execution.requiredCredentials),
+1 -1
View File
@@ -306,7 +306,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",
+12
View File
@@ -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", "pi_native", "copilot_protection"].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,97 @@
import { expect, it, vi } from "vitest";
import { createRemoteNativeBootstrap } from "./remote-native-bootstrap.js";
import type { RemoteFixtureApi, RemoteNativeFixture } from "./remote-native-fixtures.js";
function harness() {
const order: string[] = [];
const issue = { id: "issue", companyId: "company", assigneeAgentId: "agent" };
const run = { id: "run", companyId: "company", agentId: "agent", status: "running" };
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() + 5000, evidence: vi.fn(async () => { 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("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();
});
+103
View File
@@ -0,0 +1,103 @@
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 { pollUntil } from "./api.js";
import { bindRemoteNativeFixture, type RemoteFixtureApi, type RemoteFixtureDaytona, type RemoteNativeFixture } from "./remote-native-fixtures.js";
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, run shell commands, create or modify any file, ask replacement questions, or 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");
await pollUntil({
label: "owned native qualification run", deadlineAt: Math.min(input.deadlineAt, Date.now() + 20_000), intervalMs: 100,
load: async () => {
const [issue, run] = await Promise.all([
input.api.get<Record<string, any>>(`/api/issues/${request.issueId}`),
input.api.get<Record<string, any>>(`/api/heartbeat-runs/${request.runId}`),
]);
if (issue.id !== request.issueId || issue.companyId !== input.companyId || issue.assigneeAgentId !== input.agentId
|| run.companyId !== input.companyId || run.agentId !== input.agentId || run.id !== request.runId) {
throw new Error("Remote bootstrap task/run ownership is unproven");
}
return run;
},
accept: run => run.status === "running",
reject: run => ["queued", "running"].includes(run.status) ? undefined : "Native qualification run stopped before observer setup",
});
const leases = await pollUntil({
label: "owned native qualification lease", deadlineAt: Math.min(input.deadlineAt, Date.now() + 20_000), intervalMs: 100,
load: () => input.api.get<Array<Record<string, any>>>(`/api/environments/${input.environmentId}/leases`),
accept: rows => rows.filter(row => row.heartbeatRunId === request.runId && row.issueId === request.issueId && row.status === "active" && row.providerLeaseId).length === 1,
reject: rows => rows.filter(row => row.heartbeatRunId === request.runId).length > 1 ? "Ambiguous native qualification lease" : undefined,
});
const lease = leases.find(row => row.heartbeatRunId === request.runId && row.issueId === request.issueId && row.status === "active")!;
const 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,
});
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;
}
},
};
}
+199 -159
View File
@@ -1,5 +1,6 @@
import { runCursorNativeFlow } from "./cursor-native-flow.js";
import { verifyCleanupAssertions, type CleanupAssertion } from "./cleanup-verification.js";
import { createRemoteNativeBootstrap, createRemoteFixtureClient } from "./remote-native-bootstrap.js";
import { runCleanupWithObservers, verifyCleanupAssertions, type CleanupAssertion } from "./cleanup-verification.js";
import { runCopilotProtectionFlow } from "./copilot-protection-flow.js";
import { runPiNativeFlow } from "./pi-native-flow.js";
import { completionQualityControls, completionQualityStatus, judgeCompletionQuality, reserveCompletionQuality, type CompletionQualityRecord } from "./completion-quality.js";
@@ -597,6 +598,15 @@ for (const execution of executions) {
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);
@@ -835,6 +845,18 @@ for (const execution of executions) {
daytonaImage: process.env.PAPERCLIP_E2E_DAYTONA_IMAGE,
});
const remoteBootstrap = execution.environment.id === "daytona"
&& ["cursor_native", "pi_native", "copilot_protection"].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 === "api-response-reading") {
const source = await api.post<{ id: string }>(`/api/companies/${fixtures.company.id}/issues`, {
title: `Synthetic diagnostic evidence ${nonce}`,
@@ -897,10 +919,7 @@ for (const execution of executions) {
observe: (currentIssue, currentRuns) => { issue = currentIssue as IssueRecord; selectedRuns = currentRuns as RunRecord[]; },
capture: captureScreenshot,
evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
registerCleanupAssertion: assertion => {
if (cleanupAssertions.length >= 8) throw new Error("Cleanup assertion bound exceeded");
cleanupAssertions.push(assertion);
},
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 }));
@@ -911,6 +930,7 @@ for (const execution of executions) {
observe: (currentIssue, currentRuns) => { issue = currentIssue as IssueRecord; selectedRuns = currentRuns as RunRecord[]; },
capture: captureScreenshot,
evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
remoteBootstrap, registerCleanupAssertion: remoteBootstrap ? registerBeforeEnvironmentTeardownAssertion : registerCleanupAssertion,
});
issue = story.issue as IssueRecord; selectedRuns = story.runs as RunRecord[];
matcherResults = story.checks.map(check => ({ matcher: { kind: "json_path" as const, path: `piNative.${check.id}`, expected: true }, passed: check.passed, detail: check.detail }));
@@ -920,6 +940,7 @@ for (const execution of executions) {
observe: (currentIssue, currentRuns) => { issue = currentIssue as IssueRecord; selectedRuns = currentRuns as RunRecord[]; },
capture: captureScreenshot,
evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
remoteBootstrap, registerBeforeEnvironmentTeardownAssertion,
});
issue = story.issue as IssueRecord; selectedRuns = story.runs as RunRecord[];
matcherResults = story.checks.map(check => ({ matcher: { kind: "json_path" as const, path: `copilotProtection.${check.id}`, expected: true }, passed: check.passed, detail: check.detail }));
@@ -1529,7 +1550,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 }) => {
@@ -1577,78 +1598,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`,
);
}
}
turnEvidence.push({
turn: completedTurn,
@@ -1663,7 +1687,7 @@ for (const execution of executions) {
);
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(
@@ -2144,22 +2168,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 ||
@@ -2242,71 +2268,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 ?? {}),
@@ -2656,13 +2687,22 @@ 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);
}
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);
}
},
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";