Merge current master recovery and provider-pack changes

This commit is contained in:
Codex committed 2026-11-15 12:30:35 -06:00
commit d4c21a451a
16 files changed
+721 -28

No files matched your search

@@ -0,0 +1,38 @@
import { randomUUID } from "node:crypto";
import { expect, it } from "vitest";
import { heartbeatRuns, issues } from "@paperclipai/db";
import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js";
describeIssueRecovery("stranded-task check of a terminal latest run", () => {
const state = issueRecoveryFixture({ meter: true });
async function seed(run: Partial<typeof heartbeatRuns.$inferInsert>) {
const f = await state.fixture();
const issueId = randomUUID(), runId = randomUUID();
await state.db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Checked task", status: "in_progress",
assigneeAgentId: f.agentId });
await state.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "failed",
invocationSource: "manual", contextSnapshot: { issueId }, finishedAt: new Date(Date.now() - 60_000), errorCode: "process_lost",
...run });
return { ...f, issueId, runId };
}
async function leaseReads(f: { companyId: string; issueId: string }) {
state.meter.startLog();
await state.heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.issueId,
skipExternalConversationSettlement: true, skipRelatedRecovery: true });
return state.meter.stopLog().filter(entry => /^select "controller_lease_expires_at" from "heartbeat_runs"/.test(entry.sql.trim()));
}
it("does not read the controller lease of a native latest run, which can never still be settling", async () => {
const f = await seed({ runtimeMode: "native", controllerBootId: randomUUID(),
controllerLeaseExpiresAt: new Date(Date.now() + 60_000) });
expect(await leaseReads(f)).toEqual([]);
}, 120_000);
it("still reads the unexpired controller lease of a legacy run another server is settling", async () => {
const f = await seed({ runtimeMode: "legacy", controllerBootId: randomUUID(),
controllerLeaseExpiresAt: new Date(Date.now() + 60_000) });
expect(await leaseReads(f)).toHaveLength(1);
}, 120_000);
});
@@ -98,6 +98,24 @@ describe.skipIf(!support.supported)("provider-owned fresh retry reservations", (
expect(settled.metadata?.workspaceProviderRemoved).toBe(true);
expect(cache.release).toHaveBeenCalledTimes(2);
});
it("prepares provider storage for a fresh retry that follows a workspace the provider does not own", async () => {
const f = await createPluginWorkspaceFixture(db); await enable(f.pluginId);
const [previous] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: f.input.projectId,
projectWorkspaceId: f.input.projectWorkspaceId, sourceIssueId: f.issueId, mode: "isolated_workspace",
strategyType: "project_primary", name: "Fresh task workspace", status: "active", providerType: "adapter_managed" }).returning();
await db.update(issues).set({ executionWorkspaceId: previous.id, workspaceBindingRevision: 1 }).where(eq(issues.id, f.issueId));
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.runId));
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.input.agentId,
issueId: f.issueId, status: "running" }).returning();
const fresh = { attemptId: randomUUID(), sourceRunId: f.runId, previousWorkspaceId: previous.id, recoverySnapshots: [] };
const workspace = await preparePluginWorkspace(db, f.workers, { ...f.input, runId: run.id,
existingWorkspaceId: previous.id, fresh, expectedBindingRevision: 1 });
expect(workspace).not.toBeNull();
expect(workspace!.id).not.toBe(previous.id);
expect(workspace!.providerType).toBe("plugin");
expect(f.calls).toHaveLength(1);
expect(f.calls[0].operation).toMatchObject({ kind: "prepare", fresh, branchName: null });
});
it("rejects a changed task revision before calling the provider", async () => {
const f = await fixture(); await enable(f.pluginId);
await db.update(issues).set({ workspaceBindingRevision: 2 }).where(eq(issues.id, f.issueId));
@@ -0,0 +1,304 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, companies, createDb, environmentLeases, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns,
issues, nativeRunFinalizations, workspaceOperations } from "@paperclipai/db";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { notifyExecutionRunWork } from "../services/execution-control-notifications.js";
import { executionControlSchedule, registerExecutionControlWork } from "../services/execution-control-work.js";
import { registerOwnershipReconciliationWork } from "../services/native-runtime/native-finalization-reconciler.js";
import { OWNABLE_KINDS } from "../services/recovery/ownership-registry.js";
import { createOwnershipReportState, recheckSettlingKinds, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js";
import { invalidateNativeReplacementDiscovery, reconcileSafeNativeReplacements } from "../services/native-runtime/native-safe-replacement.js";
import { notifyRunDispatch } from "../services/run-dispatch-notifications.js";
import { readRemoteWorkspaceAuthority } from "@paperclipai/shared";
import { idleWorkSnapshot } from "../services/task-admission.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000);
const quiesced = () => ({ schema: "paperclip.remote-workspace-save-work.v1", activeIds: [], unknown: false,
owners: {}, quiescedAt: minutesAgo(600).toISOString() });
type Census = { statements: number; locks: number; byShape: Map<string, { count: number; locks: number }> };
function shapeOf(query: string) {
const text = query.replace(/\s+/g, " ").trim();
const table = /\bfrom "?([a-z_]+)"?/i.exec(text)?.[1] ?? /^(?:update|insert into) "?([a-z_]+)"?/i.exec(text)?.[1] ?? "?";
const verb = text.split(" ")[0]!.toLowerCase();
return `${verb} ${table}${/ for (update|share|no key update)\b/i.test(text) ? " FOR UPDATE" : ""}`;
}
function callerOf(stack: string) {
const frame = stack.split("\n").slice(1).find(line => line.includes("/server/src/services/")
&& !line.includes("delivery-work-coordinator") && !line.includes("task-admission") && !line.includes("activity-log"));
const match = frame && /services\/([^:)]+):(\d+)/.exec(frame);
return match ? `${match[1]}:${match[2]}` : "?";
}
describe.skipIf(!support.supported)("recovery passes over settled records (census)", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let meter: ReturnType<typeof meterDatabaseStatements>;
let home: string;
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
const errors: unknown[] = [];
let companyId: string, agentId: string;
beforeAll(async () => {
home = await mkdtemp(join(tmpdir(), "recovery-census-home-"));
vi.stubEnv("PAPERCLIP_HOME", home);
vi.stubEnv("SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR", join(home, "orphan-spool"));
database = await startEmbeddedPostgresTestDatabase("recovery-settled-census-");
db = createDb(database.connectionString, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
meter = meterDatabaseStatements(db, database.connectionString);
}, 120_000);
afterAll(async () => {
meter?.uninstall(); await db?.$client.end({ timeout: 1 }); await database?.cleanup();
vi.unstubAllEnvs();
await rm(home, { recursive: true, force: true });
});
beforeEach(async () => {
await db.execute(sql`truncate execution_workspace_snapshots, workspace_operations, execution_workspaces, activity_log,
native_run_finalizations, heartbeat_runs, issues, agents, companies cascade`);
companyId = randomUUID(); agentId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Census", issuePrefix: `C${companyId.slice(0, 6)}` });
await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer", adapterType: "paperclip_runner" });
});
afterEach(async () => {
await coordinator?.stop(); coordinator = undefined;
vi.useRealTimers();
expect(errors.splice(0)).toEqual([]);
});
const runRow = (values: Partial<typeof heartbeatRuns.$inferInsert> = {}) => ({ id: randomUUID(), companyId, agentId,
status: "failed", invocationSource: "manual", finishedAt: minutesAgo(600), errorCode: "process_lost", ...values });
const workspaceRow = (authority: { epoch: number; writerRunId: string | null; dirty: boolean; location?: boolean }) => {
const id = randomUUID();
return { id, companyId, mode: "isolated_workspace", strategyType: "test", name: id,
metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: authority.epoch, snapshotId: null,
source: { kind: "git", repoUrl: "https://example.invalid/repo.git", ref: null }, dirty: authority.dirty,
writerRunId: authority.writerRunId,
location: authority.location ? { environmentId: randomUUID(), leaseId: randomUUID(), providerLeaseId: `sandbox-${id}`,
remoteCwd: "/workspace/root" } : null } } };
};
type Rows = { runs: Array<ReturnType<typeof runRow>>; workspaces: Array<ReturnType<typeof workspaceRow>>;
operations: Array<typeof workspaceOperations.$inferInsert>; snapshots: Array<typeof executionWorkspaceSnapshots.$inferInsert> };
function ledgerRow(rows: Rows, input: { workspaceId: string; runId: string; epoch: number; status: "pending" | "uploaded"; objectKey?: string | null }) {
const operationId = randomUUID(), snapshotId = randomUUID();
rows.operations.push({ id: operationId, companyId, executionWorkspaceId: input.workspaceId,
heartbeatRunId: input.runId, phase: "remote_workspace_snapshot", status: "failed",
metadata: { epoch: input.epoch, boundary: "final", generation: 1, saveWork: quiesced() } });
rows.snapshots.push({ id: snapshotId, companyId, executionWorkspaceId: input.workspaceId,
sourceOperationId: operationId, sourceRunId: input.runId, generation: 1, epoch: input.epoch, status: input.status,
objectKey: input.objectKey ?? null, deleteAfter: new Date(Date.now() + 7 * 86400_000), createdAt: minutesAgo(600),
updatedAt: minutesAgo(600) });
return snapshotId;
}
async function insert(rows: Rows) {
if (rows.runs.length) await db.insert(heartbeatRuns).values(rows.runs);
if (rows.workspaces.length) await db.insert(executionWorkspaces).values(rows.workspaces);
if (rows.operations.length) await db.insert(workspaceOperations).values(rows.operations);
if (rows.snapshots.length) await db.insert(executionWorkspaceSnapshots).values(rows.snapshots);
}
/** The staging shape: history that recovery can no longer change, plus a few live runs. */
async function seedStagingShape() {
const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] };
for (let index = 0; index < 100; index++) {
const writer = runRow(index % 2 === 0 ? { executionStage: "executing", runtimeMode: "native",
runtimeModeResolvedAt: minutesAgo(601) } : { status: "succeeded", executionStage: "executing" });
const workspace = workspaceRow({ epoch: 1, writerRunId: writer.id, dirty: true, location: true });
rows.runs.push(writer); rows.workspaces.push(workspace);
if (index % 2 === 0) ledgerRow(rows, { workspaceId: workspace.id, runId: writer.id, epoch: 1, status: "pending" });
}
for (let index = 0; index < 100; index++) {
const source = runRow({ status: "succeeded" });
const workspace = workspaceRow({ epoch: 2, writerRunId: null, dirty: false });
rows.runs.push(source); rows.workspaces.push(workspace);
ledgerRow(rows, { workspaceId: workspace.id, runId: source.id, epoch: 1, status: "uploaded",
objectKey: `${companyId}/snapshots/${index}.pcws` });
}
const finished: Array<typeof issues.$inferInsert> = [], finalizations: Array<typeof nativeRunFinalizations.$inferInsert> = [];
for (let index = 0; index < 20; index++) {
const issueId = randomUUID();
finished.push({ id: issueId, companyId, title: `Finished ${index}`, status: "done", assigneeAgentId: agentId });
const failed = runRow({ runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId },
runnerProfileJson: { recoveryEventInventoryVersion: 1, nativeExecutionInput: { provider: { kind: "codex" },
workspace: { cwd: tmpdir() } } } });
rows.runs.push(failed);
finalizations.push({ runId: failed.id, companyId, issueId, phase: "terminal_failure", attempt: 1,
failureCode: "native_provider_terminal_failed", failureDetail: { originalFailureCode: "fixture_checkpoint_unusable" } });
}
const live: Array<{ runId: string; issueId: string }> = [];
for (let index = 0; index < 7; index++) {
const issueId = randomUUID();
const liveRun = runRow({ status: "running", runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId },
finishedAt: null, errorCode: null, startedAt: minutesAgo(1) });
finished.push({ id: issueId, companyId, title: `Live ${index}`, status: "in_progress", assigneeAgentId: agentId });
rows.runs.push(liveRun);
live.push({ runId: liveRun.id, issueId });
}
await db.insert(issues).values(finished);
await insert(rows);
await db.insert(nativeRunFinalizations).values(finalizations);
for (const entry of live) await db.update(issues).set({ executionRunId: entry.runId }).where(sql`id = ${entry.issueId}`);
return live;
}
async function start() {
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true,
onError: error => errors.push(error) });
const ownership = registerOwnershipReconciliationWork(db, coordinator, () => true);
const replacement = registerExecutionControlWork(coordinator, [replacementDuty()]);
await Promise.all([ownership.ready, replacement.ready]);
}
function replacementDuty() {
return { queue: DELIVERY_QUEUES.executionReplacement,
run: () => reconcileSafeNativeReplacements(db, new Date(), { verifyStoppedSession: async () => null }),
next: executionControlSchedule(db).replacement, onSettled: () => invalidateNativeReplacementDiscovery(db),
settleEmptyWhilePaused: true };
}
async function advance(ms: number, onTick?: () => Promise<void>) {
const until = Date.now() + ms;
while (Date.now() < until) {
await onTick?.();
await vi.advanceTimersByTimeAsync(Math.min(10_000, until - Date.now())); await delay(1);
while (idleWorkSnapshot().active > 0) await delay(5);
}
}
async function census(work: () => Promise<unknown>): Promise<Census> {
const result: Census = { statements: 0, locks: 0, byShape: new Map() };
meter.startLog({ stacks: true });
try { await work(); } finally {
for (const entry of meter.stopLog()) {
const lock = / for (update|share|no key update)\b/i.test(entry.sql);
const key = `${shapeOf(entry.sql)} <- ${callerOf(entry.stack ?? "")}`;
const row = result.byShape.get(key) ?? { count: 0, locks: 0 };
row.count += 1; if (lock) row.locks += 1;
result.byShape.set(key, row);
result.statements += 1; if (lock) result.locks += 1;
}
}
return result;
}
function table(label: string, result: Census) {
const rows = [...result.byShape].sort((a, b) => b[1].count - a[1].count).slice(0, 20)
.map(([key, value]) => ` ${String(value.count).padStart(6)} ${String(value.locks).padStart(5)} ${key}`);
return `${label}: ${result.statements} statements, ${result.locks} row locks\n${rows.join("\n")}`;
}
const hint = async (live: Array<{ runId: string; issueId: string }>) => {
for (const { runId, issueId } of live) {
await db.transaction(async tx => {
await notifyRunDispatch(tx, { companyId, runId, issueId });
await notifyExecutionRunWork(tx, { companyId, runId, issueId });
});
}
};
it("counts statements and row locks of one pass of each worker over staging-shaped history", async () => {
await seedStagingShape();
const state = createOwnershipReportState();
await runOwnershipReconciliationPass(db, { state });
await runOwnershipReconciliationPass(db, { state });
const fullPass = await census(() => runOwnershipReconciliationPass(db, { state }));
const watchPass = await census(() => recheckSettlingKinds(db));
const duty = replacementDuty();
await duty.run();
invalidateNativeReplacementDiscovery(db);
const replacementPass = await census(async () => { await duty.run(); await duty.next(); });
console.log([table("ownership full pass", fullPass), table("ownership watch re-check", watchPass),
table("execution replacement pass", replacementPass)].join("\n\n"));
const settled = (result: Census) => [...result.byShape.keys()].filter(key =>
/remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key));
expect({ full: settled(fullPass), watch: settled(watchPass) }).toEqual({ full: [], watch: [] });
expect(fullPass.locks).toBe(0);
expect(watchPass.statements).toBeLessThanOrEqual(30);
expect(replacementPass.statements).toBeLessThanOrEqual(3);
}, 300_000);
it("runs no statements for half an hour once only settled history is left, and takes no row locks while runs are active", async () => {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
const live = await seedStagingShape();
await start(); await advance(60_000);
await db.update(issues).set({ executionRunId: null, status: "done" }).where(sql`execution_run_id is not null`);
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(sql`status = 'running'`);
await advance(60_000);
const idle = await census(() => advance(30 * 60_000));
await db.update(heartbeatRuns).set({ status: "running", finishedAt: null })
.where(sql`id in (${sql.join(live.map(entry => sql`${entry.runId}`), sql`, `)})`);
const active = await census(() => advance(10 * 60_000, () => hint(live)));
console.log([table("idle 30 min", idle), table("active 10 min", active)].join("\n\n"));
expect(idle.statements).toBe(0);
expect(active.locks).toBe(0);
expect([...active.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]);
}, 1_200_000);
it("still settles every record that can change promptly, beside staging-shaped history", async () => {
await seedStagingShape();
const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] };
const preparing = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) });
const preparedWorkspace = workspaceRow({ epoch: 1, writerRunId: preparing.id, dirty: true, location: true });
const saver = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) });
const movedWorkspace = workspaceRow({ epoch: 3, writerRunId: null, dirty: false });
const stuckWriter = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) });
const stuckWorkspace = workspaceRow({ epoch: 1, writerRunId: stuckWriter.id, dirty: true, location: true });
const leaseRun = runRow({ finishedAt: minutesAgo(2) });
rows.runs.push(preparing, saver, stuckWriter, leaseRun);
rows.workspaces.push(preparedWorkspace, movedWorkspace, stuckWorkspace);
const abandoned = ledgerRow(rows, { workspaceId: movedWorkspace.id, runId: saver.id, epoch: 1, status: "pending" });
const held = ledgerRow(rows, { workspaceId: stuckWorkspace.id, runId: stuckWriter.id, epoch: 1, status: "pending" });
await insert(rows);
const [lease] = await db.insert(environmentLeases).values({ companyId, heartbeatRunId: leaseRun.id, status: "active" }).returning();
const ledger = async (id: string) => (await db.select().from(executionWorkspaceSnapshots)
.where(eq(executionWorkspaceSnapshots.id, id)))[0]!;
const state = createOwnershipReportState();
const first = await runOwnershipReconciliationPass(db, { state });
const kind = (id: string) => first.kinds.find(entry => entry.kind === id)!;
expect(kind("remote_workspace_unsaved_files")).toMatchObject({ settled: 1 });
expect(readRemoteWorkspaceAuthority((await db.select().from(executionWorkspaces)
.where(eq(executionWorkspaces.id, preparedWorkspace.id)))[0]!.metadata)).toMatchObject({ dirty: false, writerRunId: null, epoch: 2 });
expect((await ledger(abandoned)).status).toBe("deleted");
expect((await ledger(held)).status).toBe("pending");
expect(kind("environment_run_lease_active")).toMatchObject({ inProgress: 1, settled: 1 });
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease!.id)))[0]!.status).toBe("pending_cleanup");
await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { ...readRemoteWorkspaceAuthority(stuckWorkspace.metadata)!,
epoch: 2, writerRunId: null, dirty: false, location: null } } }).where(eq(executionWorkspaces.id, stuckWorkspace.id));
const second = await runOwnershipReconciliationPass(db, { state });
expect(second.kinds.find(entry => entry.kind === "remote_snapshot_ledger")).toMatchObject({ settled: 1 });
expect((await ledger(held)).status).toBe("deleted");
const settledPass = await census(() => runOwnershipReconciliationPass(db, { state }));
expect([...settledPass.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]);
}, 300_000);
it("skips a dirty workspace whose writer id is not a UUID without failing the listing", async () => {
const valid = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) });
const rows: Rows = { runs: [valid], workspaces: [workspaceRow({ epoch: 1, writerRunId: valid.id, dirty: true, location: true })],
operations: [], snapshots: [] };
const malformed = workspaceRow({ epoch: 1, writerRunId: null, dirty: true, location: true });
malformed.metadata.remoteWorkspace.writerRunId = "not-a-run-id" as unknown as null;
rows.workspaces.push(malformed);
await insert(rows);
const kind = OWNABLE_KINDS.find(entry => entry.id === "remote_workspace_unsaved_files")!;
const listed = await kind.listInProgress!(db, 200, 0);
expect(listed.records.map(record => record.recordId)).toEqual([rows.workspaces[0]!.id]);
}, 120_000);
});
@@ -130,7 +130,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js";
import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js";
import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
import { uploadVerifiedProviderPack } from "./provider-pack-upload.js";
import { selectRemotePiCompanion } from "./remote-pi-companion.js";
import { scheduledResumeContinuationAllowed } from "./scheduled-resume-continuation.js";
@@ -14672,6 +14672,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
signal?: AbortSignal;
trace?: NativeRunTrace;
onLog?: (stream: "stdout" | "stderr", chunk: string) => void | Promise<void>;
acceptProvenanceDifferences?: boolean;
}): Promise<{ root: string; manifest: RemoteProviderPackManifest; source: "staged" | "preinstalled" | "uploaded" }> {
const remoteTarget = input.target, remoteCommandRunner = input.runner;
const configuredProviderPackRoot = input.configuredProviderPackRoot;
@@ -14679,10 +14680,10 @@ export async function prepareRemoteProviderPackOnTarget(input: {
const stagedRemoteProviderPackRoot = posix.join(remoteTarget.remoteCwd, ".paperclip-runtime", "paperclip-runner", "provider-pack");
let activeRemoteProviderPackRoot: string | null = null;
let preinstalledProviderPackRoots: string[] = [];
const verifyRemoteProviderPack = async (packRoot: string) => {
await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner,
cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest });
};
let selectedProviderPackManifest = expectedProviderPackManifest;
const verifyRemoteProviderPack = (packRoot: string, acceptProvenance = false) =>
verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, cwd: remoteTarget.remoteCwd, packRoot,
manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true });
const discoverPreinstalledProviderPack = async () => {
if (!remoteTarget || !remoteCommandRunner) return [];
const result = await remoteCommandRunner.execute({
@@ -14704,16 +14705,16 @@ export async function prepareRemoteProviderPackOnTarget(input: {
verifyStaged: () => measureNativeRunnerSpan(
input.trace,
"provider_pack.verify",
() => verifyRemoteProviderPack(stagedRemoteProviderPackRoot),
async () => { selectedProviderPackManifest = await verifyRemoteProviderPack(stagedRemoteProviderPackRoot, true); },
),
usePreinstalled: async (onRejected) => useVerifiedPreinstalledRemoteProviderPack({
onRejected,
candidates: preinstalledProviderPackRoots = await measureNativeRunnerSpan(input.trace, "provider_pack.discover", discoverPreinstalledProviderPack),
verifyAndLink: async (preinstalledProviderPack) => {
await measureNativeRunnerSpan(
const preinstalledManifest = await measureNativeRunnerSpan(
input.trace,
"provider_pack.verify_preinstalled",
() => verifyRemoteProviderPack(preinstalledProviderPack),
() => verifyRemoteProviderPack(preinstalledProviderPack, true),
);
const escapedSource = preinstalledProviderPack.replaceAll(
"'",
@@ -14740,6 +14741,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
throw providerPackIncompatible("link_failed", "preinstalled provider pack could not be linked");
}
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
selectedProviderPackManifest = preinstalledManifest;
await input.onLog?.(
"stderr",
"[paperclip-runner] using manifest-matched preinstalled provider pack\n",
@@ -14774,9 +14776,10 @@ export async function prepareRemoteProviderPackOnTarget(input: {
targetPath: stagedRemoteProviderPackRoot,
mode: 0o700,
}),
verifyUploaded: () => verifyRemoteProviderPack(stagedRemoteProviderPackRoot),
verifyUploaded: async () => { await verifyRemoteProviderPack(stagedRemoteProviderPackRoot); },
});
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
selectedProviderPackManifest = expectedProviderPackManifest;
},
});
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
@@ -14786,7 +14789,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
"[paperclip-runner] reusing manifest-matched provider pack from the workspace\n",
);
}
return { root: activeRemoteProviderPackRoot!, manifest: expectedProviderPackManifest, source: packSource };
return { root: activeRemoteProviderPackRoot!, manifest: selectedProviderPackManifest, source: packSource };
}
/** Read selection identity only; verify controller contents only if upload is needed. */
@@ -17214,7 +17217,13 @@ async function createRunnerdBackendWithinSessionClaim(
target: remoteTarget, runner: remoteCommandRunner, configuredProviderPackRoot,
manifest: expectedProviderPackManifest, trace: input.trace, onLog: input.onLog,
signal: sourceSignals.length ? AbortSignal.any(sourceSignals) : undefined,
acceptProvenanceDifferences: providerPackProvenanceReuseAllowed({ retainProviderPack, explicitProviderPackSelection,
authoritySelectable: providerPackAuthority !== null }),
});
if (prepared.manifest.digest !== expectedProviderPackManifest.digest) {
providerPackAuthority!.select(prepared.manifest);
expectedProviderPackManifest = prepared.manifest;
}
activeRemoteProviderPackRoot = prepared.root;
providerPackVerified = true;
}
@@ -69,6 +69,7 @@ it("keeps historical/source packs without an archive on the existing path", asyn
it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk", async version => {
const { pack } = version === "v2" ? await layeredFixture() : await fixture();
const archivePath = version === "v2" ? `${pack}.archives/overlay.tar.zst` : `${pack}.tar.zst`;
await fs.utimes(archivePath, new Date(), new Date(Date.now() + 60_000));
const controller = new AbortController();
const handle = await fs.open(archivePath, "r");
const prototype = Object.getPrototypeOf(handle) as typeof handle;
@@ -85,6 +86,25 @@ it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk
} finally { streaming.mockRestore(); }
});
it("hashes an unchanged verified archive once per server process and again after it changes", async () => {
const { pack } = await fixture();
const archivePath = `${pack}.tar.zst`;
const handle = await fs.open(archivePath, "r");
const prototype = Object.getPrototypeOf(handle) as typeof handle;
await handle.close();
const streaming = vi.spyOn(prototype, "createReadStream");
try {
await expect(readProviderPackArchive(pack, digest)).resolves.toMatchObject({ sourcePath: archivePath });
expect(streaming).not.toHaveBeenCalled();
const original = await fs.readFile(archivePath);
const corrupted = Buffer.from(original);
corrupted[corrupted.length - 1] ^= 0xff;
await fs.writeFile(archivePath, corrupted);
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("sha256_mismatch");
expect(streaming).toHaveBeenCalledOnce();
} finally { streaming.mockRestore(); }
});
async function layeredFixture() {
const { root, pack } = await fixture();
await fs.writeFile(path.join(pack, "bin", "large"), Buffer.alloc(1024 * 1024, 42), { mode: 0o755 });
@@ -28,6 +28,10 @@ const validArchive = (value: unknown): value is Archive => {
export const invalidArchive = (reason: string, cause?: unknown) =>
new Error(`runner_remote_provider_archive_invalid: ${reason}`, cause === undefined ? undefined : { cause });
const verifiedArchives = new Set<string>();
const archiveIdentity = (path: string, expected: Archive, metadata: { dev: number; ino: number; size: number; mtimeMs: number; ctimeMs: number }) =>
[path, expected.sha256, metadata.dev, metadata.ino, metadata.size, metadata.mtimeMs, metadata.ctimeMs].join("\0");
export async function verifyArchive(path: string, expected: Archive, signal?: AbortSignal) {
signal?.throwIfAborted();
let file;
@@ -37,10 +41,14 @@ export async function verifyArchive(path: string, expected: Archive, signal?: Ab
const metadata = await file.stat();
if (!metadata.isFile()) throw invalidArchive("archive_not_file");
if (metadata.size !== expected.bytes) throw invalidArchive("size_mismatch");
const identity = archiveIdentity(path, expected, metadata);
if (verifiedArchives.has(identity)) return;
const hash = createHash("sha256");
for await (const chunk of file.createReadStream({ autoClose: false, signal })) hash.update(chunk);
signal?.throwIfAborted();
if (hash.digest("hex") !== expected.sha256) throw invalidArchive("sha256_mismatch");
if (verifiedArchives.size >= 1_024) verifiedArchives.clear();
verifiedArchives.add(identity);
} finally { await file.close(); }
}
@@ -0,0 +1,188 @@
import { execFile } from "node:child_process";
import { createHash, randomBytes } from "node:crypto";
import { chmod, cp, mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, posix } from "node:path";
import { promisify } from "node:util";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import { QUALIFIED_ACPX_PROFILES, QUALIFIED_ACPX_VERSION } from "../../vendor/paperclip-runner/index.js";
import { prepareRemoteProviderPackOnTarget, resolveRemoteProviderPackSource, sha256DirectoryTree } from "./native-session-executor.js";
import { canonicalProviderPackJson } from "./remote-provider-pack-verification.js";
const exec = promisify(execFile);
const EXECUTE_LATENCY_MS = 150;
const TRANSFER_LATENCY_MS = 300;
const TRANSFER_BYTES_PER_SECOND = 10 * 1024 * 1024;
const LARGE_ARTIFACT_BYTES = 24 * 1024 * 1024;
const sha = (value: string | Buffer) => `sha256:${createHash("sha256").update(value).digest("hex")}`;
async function writePack(root: string, revision: string, large: Buffer, distSuffix = "") {
const files: Record<string, string | Buffer> = {
"node_modules/node/bin/node": `#!/bin/sh\nexec '${process.execPath}' "$@"\n`,
"node_modules/.bin/opencode": "#!/bin/sh\necho 1.18.34\n",
"node_modules/opencode-ai/bin/opencode.exe": large,
"node_modules/opencode-ai/package.json": JSON.stringify({ version: "1.18.34" }),
"node_modules/acpx/package.json": JSON.stringify({ version: QUALIFIED_ACPX_VERSION }),
"node_modules/@agentclientprotocol/claude-agent-acp/package.json": JSON.stringify({ version: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion }),
"node_modules/@agentclientprotocol/codex-acp/package.json": JSON.stringify({ version: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion }),
"pnpm-lock.yaml": "lockfileVersion: '9.0'\n",
"dist/cli/opencode-app-server-proxy.cjs": `module.exports = "proxy${distSuffix}";\n`,
"dist/cli/acpx-runtime-sidecar.cjs": "module.exports = 'sidecar';\n",
"dist/providers/grok/launcher.cjs": "module.exports = 'grok';\n",
};
for (const [path, content] of Object.entries(files)) {
await mkdir(dirname(join(root, path)), { recursive: true });
await writeFile(join(root, path), content);
}
await chmod(join(root, "node_modules/node/bin/node"), 0o755);
await chmod(join(root, "node_modules/.bin/opencode"), 0o755);
const artifact = (path: string) => ({ path, sha256: sha(files[path]!) });
const proxy = artifact("dist/cli/opencode-app-server-proxy.cjs"), sidecar = artifact("dist/cli/acpx-runtime-sidecar.cjs");
const distDigest = sha256DirectoryTree(join(root, "dist"));
const payload = {
pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, opencode: "1.18.34", acpx: QUALIFIED_ACPX_VERSION,
claudeAcp: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion, codexAcp: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion,
grok: QUALIFIED_ACPX_PROFILES.grok.agentRuntimeVersion },
target: { platform: process.platform, architecture: process.arch },
runnerSourceRevision: revision.repeat(40),
distDigest,
bridgeDigest: `sha256:${createHash("sha256").update(proxy.sha256).update("\n").update(sidecar.sha256).update("\n").update(distDigest).digest("hex")}`,
acpxProfileDigests: { grok: QUALIFIED_ACPX_PROFILES.grok.commandDigest, claude: QUALIFIED_ACPX_PROFILES.claude.commandDigest,
codex: QUALIFIED_ACPX_PROFILES.codex.commandDigest },
artifacts: {
grokLauncher: artifact("dist/providers/grok/launcher.cjs"), nodeCommand: artifact("node_modules/node/bin/node"),
productionLock: artifact("pnpm-lock.yaml"), opencodeCommand: artifact("node_modules/.bin/opencode"),
opencodeExecutable: artifact("node_modules/opencode-ai/bin/opencode.exe"), opencodeProxy: proxy, acpxSidecar: sidecar,
},
};
await writeFile(join(root, "provider-pack.json"), JSON.stringify({ schema: "paperclip-runner/remote-provider-pack/v1",
digest: sha(canonicalProviderPackJson(payload)), payload }));
}
async function directoryBytes(root: string): Promise<number> {
let total = 0;
for (const entry of await readdir(root, { withFileTypes: true, recursive: true })) {
if (entry.isFile()) total += (await stat(join(entry.parentPath, entry.name))).size;
}
return total;
}
function assertConfinedSandboxPath(remoteDir: string, candidate: string) {
const root = posix.normalize(remoteDir);
const normalized = posix.normalize(candidate);
if (normalized !== root && !normalized.startsWith(`${root}/`)) {
throw new Error(`sync target path escapes the workspace remote dir: ${candidate}`);
}
}
function simulatedSandbox(home: string, workspace: string) {
const usage = { simulatedMs: 0, executes: 0, bytesUploaded: 0 };
const runner: CommandManagedRuntimeRunner = {
execute: async request => {
usage.executes += 1;
usage.simulatedMs += EXECUTE_LATENCY_MS;
try {
const result = await exec(request.command, request.args ?? [], { cwd: request.cwd, env: { ...process.env, HOME: home }, maxBuffer: 1 << 24 });
return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stdout: result.stdout, stderr: result.stderr };
} catch (error) {
const failed = error as Error & { code?: number; stdout?: string; stderr?: string };
return { exitCode: typeof failed.code === "number" ? failed.code : 127, signal: null, pid: null, startedAt: null, timedOut: false,
stdout: failed.stdout ?? "", stderr: failed.stderr ?? String(error) };
}
},
syncIn: async operations => {
const results = [];
for (const operation of operations) {
let bytes = 0;
for (const file of operation.files) {
if (file.kind !== "directory" || !file.sourcePath) throw new Error("unexpected transfer");
assertConfinedSandboxPath(workspace, file.targetPath);
bytes += await directoryBytes(file.sourcePath);
await mkdir(dirname(file.targetPath), { recursive: true });
await cp(file.sourcePath, file.targetPath, { recursive: true });
}
usage.bytesUploaded += bytes;
usage.simulatedMs += TRANSFER_LATENCY_MS + (bytes / TRANSFER_BYTES_PER_SECOND) * 1000;
results.push({ operationId: operation.operationId, filesTransferred: operation.files.length, bytesTransferred: bytes });
}
return { operations: results };
},
};
return { runner, usage };
}
type Scenario = "exact" | "same_content_other_build" | "different_content" | "corrupted" | "none";
describe("provider pack selection harness", () => {
let root: string;
let large: Buffer;
let server: ReturnType<typeof resolveRemoteProviderPackSource>;
const rows: string[] = [];
beforeAll(async () => {
root = await mkdtemp(join(tmpdir(), "provider-pack-harness-"));
large = randomBytes(LARGE_ARTIFACT_BYTES);
await writePack(join(root, "server-pack"), "b", large);
server = resolveRemoteProviderPackSource(join(root, "server-pack"));
});
afterAll(async () => {
if (rows.length) process.stdout.write(`\nprovider pack harness (execute ${EXECUTE_LATENCY_MS} ms, transfer ${TRANSFER_LATENCY_MS} ms + ${TRANSFER_BYTES_PER_SECOND / 1024 / 1024} MiB/s)\n${rows.join("\n")}\n`);
await rm(root, { recursive: true, force: true });
});
const run = async (scenario: Scenario, acceptProvenanceDifferences: boolean) => {
const sandbox = await mkdtemp(join(root, `${scenario}-`));
const home = join(sandbox, "home"), workspace = join(sandbox, "workspace");
await mkdir(workspace, { recursive: true });
const image = join(home, ".local/share/paperclip-runner/provider-pack");
if (scenario === "exact") await writePack(image, "b", large);
if (scenario === "same_content_other_build") await writePack(image, "a", large);
if (scenario === "different_content") await writePack(image, "a", large, "-older");
if (scenario === "corrupted") {
await writePack(image, "a", large);
await writeFile(join(image, "dist/cli/acpx-runtime-sidecar.cjs"), "tampered\n");
}
const { runner, usage } = simulatedSandbox(home, workspace);
const cpuBefore = process.cpuUsage();
const startedAt = performance.now();
const prepared = await prepareRemoteProviderPackOnTarget({
target: { kind: "remote", transport: "sandbox", remoteCwd: workspace, runner } as never,
runner, configuredProviderPackRoot: server.configuredRoot, manifest: server.manifest, acceptProvenanceDifferences,
});
const wallMs = performance.now() - startedAt;
const cpu = process.cpuUsage(cpuBefore);
rows.push(`${scenario.padEnd(26)} ${acceptProvenanceDifferences ? "after " : "before"} source=${prepared.source.padEnd(12)} `
+ `modelled=${((wallMs + usage.simulatedMs) / 1000).toFixed(2)}s uploaded=${(usage.bytesUploaded / 1024 / 1024).toFixed(1)}MiB `
+ `executes=${usage.executes} serverCpu=${((cpu.user + cpu.system) / 1000).toFixed(0)}ms dbStatements=0`);
return { prepared, usage };
};
it("confines simulated uploads to the workspace", async () => {
const { runner } = simulatedSandbox(root, join(root, "workspace"));
await expect(runner.syncIn!([{ operationId: "escape", files: [{ kind: "directory", sourcePath: join(root, "server-pack"),
targetPath: join(root, "workspace", "..", "outside"), mode: 0o700 }] }])).rejects.toThrow("escapes the workspace");
});
it.each<[Scenario, "preinstalled" | "uploaded", "preinstalled" | "uploaded"]>([
["exact", "preinstalled", "preinstalled"],
["same_content_other_build", "uploaded", "preinstalled"],
["different_content", "uploaded", "uploaded"],
["corrupted", "uploaded", "uploaded"],
["none", "uploaded", "uploaded"],
])("selects the pack for %s (before: %s, after: %s)", async (scenario, before, after) => {
const previous = await run(scenario, false);
expect(previous.prepared.source).toBe(before);
expect(previous.prepared.manifest).toEqual(server.manifest);
const current = await run(scenario, true);
expect(current.prepared.source).toBe(after);
expect(current.usage.bytesUploaded).toBe(after === "uploaded" ? previous.usage.bytesUploaded : 0);
if (scenario === "same_content_other_build") {
expect(current.prepared.manifest.digest).not.toBe(server.manifest.digest);
expect(current.prepared.manifest.payload.runnerSourceRevision).toBe("a".repeat(40));
expect({ ...current.prepared.manifest.payload, runnerSourceRevision: null })
.toEqual({ ...server.manifest.payload, runnerSourceRevision: null });
} else {
expect(current.prepared.manifest).toEqual(server.manifest);
}
}, 120_000);
});
@@ -120,6 +120,24 @@ describe("installed provider pack compatibility", () => {
if (field === "digest") pack.digest = sha("corrupt");
await expect(check(pack)).rejects.toThrow("runner_remote_provider_artifact_incompatible");
});
it("accepts a reported installed manifest only when its sealed content equals the expected pack", async () => {
const expected = manifest("b");
const report = (installed: unknown) => vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => ({
exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "",
stdout: request.args?.[0] === "--version" ? "1.18.34\n"
: `\npaperclip-pack-manifest=${Buffer.from(JSON.stringify(installed)).toString("base64")}\n` }));
const input = { cwd: "/workspace", packRoot: "/opt/paperclip-runner/provider-pack", manifest: expected, acceptProvenance: true };
const otherBuild = manifest("b");
otherBuild.payload.runnerSourceRevision = "a".repeat(40);
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(reseal(otherBuild)) } })).resolves.toEqual(reseal(otherBuild));
const otherContent = reseal({ ...otherBuild, payload: { ...otherBuild.payload, contractDigest: sha("other") } });
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report(otherContent) } }))
.rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" });
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: report({ ...reseal(otherBuild), digest: sha("unsealed") }) } }))
.rejects.toMatchObject({ failureCheck: "installed_manifest_invalid" });
await expect(verifyRemoteProviderPack({ ...input, acceptProvenance: false, runner: { execute: report(reseal(otherBuild)) } }))
.resolves.toEqual(expected);
});
it("does not reuse image packs when the controller's bundled pack records no contract digest", async () => {
const current = manifest("b");
delete current.payload.contractDigest;
@@ -105,7 +105,7 @@ function compatibleInstallation<T extends ProviderPackIdentity>(
return structuredClone(actual);
}
export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false }: {
export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false }: {
runner: CommandManagedRuntimeRunner;
cwd: string;
packRoot: string;
@@ -114,6 +114,7 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
provider?: PackProvider;
requireExactIdentity?: boolean;
requireCurrentOpenCodeProxy?: boolean;
acceptProvenance?: boolean;
}): Promise<T> {
if (installation) {
if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required");
@@ -138,7 +139,10 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
"const canonical=(v)=>Array.isArray(v)?'['+v.map(canonical).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}':JSON.stringify(v)",
"let manifest;try{manifest=JSON.parse(actual)}catch{fail('manifest_invalid','provider pack manifest invalid')}",
"const differing=(a,b)=>[...new Set([...Object.keys(a||{}),...Object.keys(b||{})])].sort().filter(k=>canonical((a||{})[k])!==canonical((b||{})[k]))",
"if(canonical(manifest)!==expected){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}",
"const provenance=process.argv[3]==='provenance'",
"const content=(m)=>{const c=JSON.parse(JSON.stringify(m??null))??{};delete c.digest;if(c.payload&&typeof c.payload==='object'){delete c.payload.runnerSourceRevision;delete c.payload.runnerInputsDigest}return canonical(c)}",
"const sealed=manifest?.digest==='sha256:'+crypto.createHash('sha256').update(canonical(manifest?.payload)).digest('hex')",
"if(canonical(manifest)!==expected&&!(provenance&&sealed&&content(manifest)===content(JSON.parse(expected)))){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}",
"const hash=(p)=>{try{return 'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')}catch{return 'unreadable'}}",
"const walk=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}",
"const tree=(treeRoot)=>{try{return walk(treeRoot)}catch{return 'unreadable'}}",
@@ -152,14 +156,16 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
"const packageVersion=(pkg)=>{try{return JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version}catch{return null}}",
"const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}",
"for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version:'+pkg,pkg+' version mismatch')",
"if(provenance)process.stdout.write('\\npaperclip-pack-manifest='+Buffer.from(canonical(manifest)).toString('base64')+'\\n')",
].join(";");
await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({
const verified = await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({
command: providerNodeCommand,
args: ["-e", verifyScript, packRoot, expected],
args: ["-e", verifyScript, packRoot, expected, ...(acceptProvenance ? ["provenance"] : [])],
cwd: cwd,
bypassSession: true,
timeoutMs: 30_000,
}), "provider pack verification"));
const selected = acceptProvenance ? sameContentManifest(manifest, verified.stdout) : manifest;
const opencodeCommand = posix.join(
packRoot,
manifest.payload.artifacts.opencodeCommand.path,
@@ -176,5 +182,27 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
) {
throw providerPackIncompatible("opencode_version", "OpenCode version mismatch");
}
return structuredClone(manifest);
return structuredClone(selected);
}
const PROVENANCE_FIELDS = ["runnerSourceRevision", "runnerInputsDigest"] as const;
export function providerPackContent(manifest: ProviderPackIdentity): string {
const payload: Record<string, unknown> = { ...manifest.payload };
for (const field of PROVENANCE_FIELDS) delete payload[field];
return canonicalProviderPackJson({ schema: manifest.schema, payload });
}
function sameContentManifest<T extends ProviderPackIdentity>(expected: T, stdout: string): T {
const encoded = /paperclip-pack-manifest=([A-Za-z0-9+/=]{1,200000})/.exec(stdout)?.[1];
let installed: T | null = null;
try { installed = encoded ? JSON.parse(Buffer.from(encoded, "base64").toString("utf8")) as T : null; } catch {}
if (!installed?.payload || installed.schema !== expected.schema
|| installed.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(installed.payload)).digest("hex")}`
|| providerPackContent(installed) !== providerPackContent(expected)
|| !/^[0-9a-f]{40}(?:-dirty)?$/.test(installed.payload.runnerSourceRevision)
|| (installed.payload.runnerInputsDigest !== undefined && !/^[0-9a-f]{64}$/.test(installed.payload.runnerInputsDigest))) {
throw providerPackIncompatible("installed_manifest_invalid", "installed provider pack identity is invalid");
}
return installed;
}
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { createNativeRunTrace } from "./native-run-trace.js";
import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
describe("remote provider verification", () => {
const ok = { exitCode: 0, timedOut: false, stdout: "verified", stderr: "", signal: null };
@@ -124,6 +124,17 @@ describe("remote provider pack reuse", () => {
});
describe("same-content pack reuse across builds", () => {
it.each([
[{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: true }, true],
[{ retainProviderPack: true, explicitProviderPackSelection: false, authoritySelectable: true }, false],
[{ retainProviderPack: false, explicitProviderPackSelection: true, authoritySelectable: true }, false],
[{ retainProviderPack: false, explicitProviderPackSelection: false, authoritySelectable: false }, false],
])("allows provenance-only differences only for an unbound run: %j", (input, allowed) => {
expect(providerPackProvenanceReuseAllowed(input)).toBe(allowed);
});
});
describe("ordinary ACPX image artifacts", () => {
const provider = (agent: string) => ({ kind: "acpx", agent, model: "selected-model" } as Parameters<typeof shouldUseBundledAcpxImageAssets>[0]["provider"]);
it.each(["cursor", "copilot"])("selects bundled artifacts for remote %s without an operator override", agent => {
@@ -13,6 +13,15 @@ export function shouldUseBundledAcpxImageAssets(input: {
["cursor", "copilot", "kimi"].includes(input.provider.agent);
}
/** A run may adopt a same-content pack from another build only when no saved or operator-selected identity binds it. */
export function providerPackProvenanceReuseAllowed(input: {
retainProviderPack: boolean;
explicitProviderPackSelection: boolean;
authoritySelectable: boolean;
}): boolean {
return !input.retainProviderPack && !input.explicitProviderPackSelection && input.authoritySelectable;
}
type VerificationCommandResult = {
exitCode: number | null;
timedOut: boolean;
+2 -1
View File
@@ -133,7 +133,8 @@ export async function preparePluginWorkspace(
),
)
: [];
if (prior && prior.providerType !== "plugin" && !priorBinding && !prior.metadata?.workspaceProviderOwner) return null;
// A fresh attempt starts from the project source, so storage the provider does not own does not decide it.
if (!input.fresh && prior && prior.providerType !== "plugin" && !priorBinding && !prior.metadata?.workspaceProviderOwner) return null;
const owner = priorBinding?.pluginId ?? prior?.metadata?.workspaceProviderOwner ??
(!existing && input.selectedProviderPluginId !== undefined ? input.selectedProviderPluginId :
!existing && project ? (await effectiveProjectWorkspacePolicy(db, input.companyId, project.executionWorkspacePolicy, false))?.storageProviderPluginId : null);
@@ -38,8 +38,8 @@ import {
} from "../native-runtime/native-accepted-result-lease-settlement.js";
import { settleClaimedWakeRequest } from "./wake-request-claimed-settlement.js";
import { settleAbandonedRemoteSnapshotSave, settleAbandonedWorkspaceCommandOperation, settleAbandonedWorkspaceFinalizeAttempt } from "./workspace-finalize-attempt-settlement.js";
import { settlePreparationOnlyRemoteWorkspaceEpoch } from "./remote-workspace-unsaved-files-settlement.js";
import { settleAbandonedRemoteSnapshotLedger } from "./remote-snapshot-ledger-settlement.js";
import { preparationOnlyWriterCondition, settlePreparationOnlyRemoteWorkspaceEpoch } from "./remote-workspace-unsaved-files-settlement.js";
import { retirableRemoteSnapshotLedgerCondition, settleAbandonedRemoteSnapshotLedger } from "./remote-snapshot-ledger-settlement.js";
import { LOCAL_WORKSPACE_COMMAND_PHASES, runtimeControlOperationOwnerStamp, settleRuntimeControlOperation } from "../workspace-operations.js";
import { copybackOwnerHoldOwner, settleCopybackOwnerHold } from "./copyback-owner-hold.js";
import { applyObservedFenceProviderProof, observedWorkspaceFenceOwner, settleObservedWorkspaceFence } from "./observed-workspace-fence.js";
@@ -968,7 +968,8 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [
listInProgress: async (db, limit, offset) => {
const rows = await db.select({ id: executionWorkspaces.id, companyId: executionWorkspaces.companyId,
metadata: executionWorkspaces.metadata, updatedAt: executionWorkspaces.updatedAt }).from(executionWorkspaces)
.where(sql`(${executionWorkspaces.metadata}->'remoteWorkspace'->>'dirty')::boolean is true`).orderBy(asc(executionWorkspaces.id)).limit(limit + 1).offset(offset);
.where(and(sql`(${executionWorkspaces.metadata}->'remoteWorkspace'->>'dirty')::boolean is true`,
preparationOnlyWriterCondition())).orderBy(asc(executionWorkspaces.id)).limit(limit + 1).offset(offset);
const result = page(rows, limit);
return { truncated: result.truncated, records: result.rows.map(row => {
const writerRunId = str(json(json(row.metadata).remoteWorkspace).writerRunId);
@@ -983,7 +984,7 @@ export const OWNABLE_KINDS: readonly OwnableKind[] = [
listInProgress: async (db, limit, offset) => {
const rows = await db.select({ id: executionWorkspaceSnapshots.id, companyId: executionWorkspaceSnapshots.companyId,
sourceRunId: executionWorkspaceSnapshots.sourceRunId, updatedAt: executionWorkspaceSnapshots.updatedAt })
.from(executionWorkspaceSnapshots).where(inArray(executionWorkspaceSnapshots.status, ["pending", "uploaded"])).orderBy(asc(executionWorkspaceSnapshots.id)).limit(limit + 1).offset(offset);
.from(executionWorkspaceSnapshots).where(retirableRemoteSnapshotLedgerCondition()).orderBy(asc(executionWorkspaceSnapshots.id)).limit(limit + 1).offset(offset);
const result = page(rows, limit);
return { truncated: result.truncated, records: result.rows.map(row => ({
recordId: row.id, companyId: row.companyId, runId: row.sourceRunId, issueId: null,
@@ -1,4 +1,4 @@
import { and, eq, isNull, sql } from "drizzle-orm";
import { and, eq, isNull, sql, type SQL } from "drizzle-orm";
import { executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns, workspaceOperations, type Db } from "@paperclipai/db";
import { readRemoteWorkspaceAuthority } from "@paperclipai/shared";
import { persistActivity, publishActivity, type ActivityPublication } from "../activity-log.js";
@@ -14,6 +14,16 @@ const TERMINAL_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out",
type Snapshot = typeof executionWorkspaceSnapshots.$inferSelect;
export function retirableRemoteSnapshotLedgerCondition(): SQL {
return and(eq(executionWorkspaceSnapshots.status, "pending"), isNull(executionWorkspaceSnapshots.objectKey),
sql`not exists (select 1 from workspace_operations operation where operation.company_id = ${executionWorkspaceSnapshots.companyId}
and operation.id = ${executionWorkspaceSnapshots.sourceOperationId} and operation.phase <> 'remote_workspace_snapshot')`,
sql`not exists (select 1 from execution_workspaces workspace where workspace.company_id = ${executionWorkspaceSnapshots.companyId}
and workspace.id = ${executionWorkspaceSnapshots.executionWorkspaceId}
and workspace.metadata->'remoteWorkspace'->>'writerRunId' = ${executionWorkspaceSnapshots.sourceRunId}::text
and workspace.metadata->'remoteWorkspace'->>'epoch' = ${executionWorkspaceSnapshots.epoch}::text)`)!;
}
export async function retireEndedRemoteSnapshotLedgerRow(tx: Db, input: {
companyId: string; snapshotId: string; now: Date; proof: string;
}): Promise<{ retired: true; snapshot: Snapshot; status: "deleted" | "delete_requested" } | { retired: false; reason: string }> {
@@ -1,4 +1,4 @@
import { and, eq, inArray, like, or, sql } from "drizzle-orm";
import { and, eq, inArray, like, or, sql, type SQL } from "drizzle-orm";
import { executionWorkspaces, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db";
import { readRemoteWorkspaceAuthority } from "@paperclipai/shared";
import type { OwnerProof } from "../owner-proof.js";
@@ -11,17 +11,36 @@ const TERMINAL_RUN_STATUSES = ["succeeded", "failed", "cancelled", "timed_out",
const WORK_STARTED_EVENT_TYPES = ["adapter.invoke", "adapter.progress"];
const WORK_STARTED_EVENT_PREFIXES = ["turn.", "provider.", "native.process_"];
const WRITER_RUN_ID = sql`${executionWorkspaces.metadata}->'remoteWorkspace'->>'writerRunId'`;
export function preparationOnlyWriterCondition(): SQL {
const workStarted = sql.join([
sql`event.event_type in (${sql.join(WORK_STARTED_EVENT_TYPES.map(type => sql`${type}`), sql`, `)})`,
...WORK_STARTED_EVENT_PREFIXES.map(prefix => sql`event.event_type like ${`${prefix}%`}`),
], sql` or `);
return sql`(${WRITER_RUN_ID} is null or exists (select 1 from heartbeat_runs writer
where writer.id = (case when ${WRITER_RUN_ID} ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
then (${WRITER_RUN_ID})::uuid end) and writer.company_id = ${executionWorkspaces.companyId}
and writer.execution_stage = 'preparing' and writer.runtime_mode_resolved_at is null
and writer.process_pid is null and writer.process_group_id is null
and writer.native_session_id is null and writer.runner_instance_id is null
and not exists (select 1 from native_run_finalizations finalization
where finalization.company_id = writer.company_id and finalization.run_id = writer.id)
and not exists (select 1 from heartbeat_run_events event where event.run_id = writer.id and (${workStarted}))))`;
}
export async function settlePreparationOnlyRemoteWorkspaceEpoch(db: Db, record: InProgressRecord,
context: { now: Date; proof: OwnerProof }): Promise<SettleOutcome> {
if (record.owner.kind !== "run" || !record.runId || !record.companyId) return { settled: false, reason: "owner_not_provable" };
const runId = record.runId, companyId = record.companyId;
return db.transaction(async (transaction): Promise<SettleOutcome> => {
const tx = transaction as unknown as Db;
const [run] = await tx.select({ status: heartbeatRuns.status, executionStage: heartbeatRuns.executionStage,
const readRun = () => tx.select({ status: heartbeatRuns.status, executionStage: heartbeatRuns.executionStage,
runtimeModeResolvedAt: heartbeatRuns.runtimeModeResolvedAt, processPid: heartbeatRuns.processPid,
processGroupId: heartbeatRuns.processGroupId, nativeSessionId: heartbeatRuns.nativeSessionId,
runnerInstanceId: heartbeatRuns.runnerInstanceId })
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId))).for("update");
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId)));
const [run] = await readRun();
if (!run || !TERMINAL_RUN_STATUSES.includes(run.status)) return { settled: false, reason: "owner_run_active" };
if (run.runtimeModeResolvedAt || run.executionStage !== "preparing") return { settled: false, reason: "writer_reached_runtime", watch: false };
const [finalization] = await tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
@@ -44,6 +63,10 @@ export async function settlePreparationOnlyRemoteWorkspaceEpoch(db: Db, record:
eq(workspaceOperations.phase, "remote_workspace_snapshot"), inArray(workspaceOperations.status, ["running", "pending"]),
sql`${workspaceOperations.metadata}->>'epoch' = ${String(authority.epoch)}`)).limit(1);
if (save) return { settled: false, reason: "save_in_flight" };
const [locked] = await readRun().for("update");
if (!locked || !TERMINAL_RUN_STATUSES.includes(locked.status)) return { settled: false, reason: "owner_run_active" };
if (locked.runtimeModeResolvedAt || locked.executionStage !== "preparing" || locked.processPid || locked.processGroupId
|| locked.nativeSessionId || locked.runnerInstanceId) return { settled: false, reason: "writer_reached_runtime", watch: false };
// A preparation that restored the saved version and then did nothing else
// left exactly that version in its root. When the durable unchanged-baseline
// proof holds, hand the workspace on at its saved version and keep the root,
+10 -3
View File
@@ -322,6 +322,8 @@ type LatestIssueRun =
retryOfRunId?: string | null;
scheduledRetryReason?: string | null;
runnerProfileJson?: unknown;
runtimeMode?: string | null;
controllerBootId?: string | null;
})
| null;
type SuccessfulLatestIssueRun = NonNullable<LatestIssueRun> & {
@@ -1099,6 +1101,8 @@ export function recoveryService(
retryOfRunId: heartbeatRuns.retryOfRunId,
scheduledRetryReason: heartbeatRuns.scheduledRetryReason,
runnerProfileJson: heartbeatRuns.runnerProfileJson,
runtimeMode: heartbeatRuns.runtimeMode,
controllerBootId: heartbeatRuns.controllerBootId,
})
.from(heartbeatRuns)
.where(
@@ -1208,8 +1212,11 @@ export function recoveryService(
* a live execution; another process proves it with its unexpired controller
* lease, which it clears once settlement (retry scheduling, claim release)
* is done. This process's own lease without a live execution is stale. */
async function terminalRunSettlingUntil(companyId: string, runId: string): Promise<Date | null> {
async function terminalRunSettlingUntil(companyId: string, runId: string,
known?: { runtimeMode?: string | null; controllerBootId?: string | null }): Promise<Date | null> {
if (deps.liveRunExecutions?.has(runId)) return new Date(Date.now() + 30_000);
if (known?.runtimeMode !== undefined && (known.runtimeMode !== "legacy" || !known.controllerBootId
|| known.controllerBootId === legacyControllerBootId)) return null;
const [run] = await db.select({ leaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt })
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId),
eq(heartbeatRuns.runtimeMode, "legacy"), sql`${heartbeatRuns.controllerBootId} is not null`,
@@ -4755,7 +4762,7 @@ export function recoveryService(
|| await isAutomaticRecoverySuppressedByPauseHold(db, issue.companyId, issue.id, treeControlSvc)) continue;
// Another server is still settling the run: look again when its lease
// lapses, since later generic skips may never reach their own check.
const settlingUntil = await terminalRunSettlingUntil(issue.companyId, run.id);
const settlingUntil = await terminalRunSettlingUntil(issue.companyId, run.id, latestRun);
if (settlingUntil) {
onDeferredDeadline?.(settlingUntil.getTime());
handled.add(issue.id);
@@ -4937,7 +4944,7 @@ export function recoveryService(
// and releases the claim itself. Escalating in that window clears the
// claim the retry needs. Re-check once its controller lease lapses.
const settlingUntil = latestRun && isTerminalIssueRun(latestRun)
? await terminalRunSettlingUntil(issue.companyId, latestRun.id) : null;
? await terminalRunSettlingUntil(issue.companyId, latestRun.id, latestRun) : null;
if (settlingUntil) {
opts?.onDeferredDeadline?.(settlingUntil.getTime());
result.skipped += 1;