diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md index a06a2d8bf9a..1711f60e366 100644 --- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md +++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md @@ -387,48 +387,12 @@ authority as submission. Core requires preparation version 1 for native plugin execution. It validates and saves the result before it submits its configuration ID. -### Stopped source reconciliation +### Stopped source fields -A plugin’s `describe` response advertises `codexSourceRecoveryVersion: 1` for -Codex App Server and `acpxSourceRecoveryVersion: 1` for ACPX. It can advertise -either, both, or neither. Each field means the host can verify and restore a -stopped source for that provider without starting another turn. Core requires -the field for the selected provider and verifies the run’s eligibility. - -Core admission recognizes native Codex and qualified Claude through ACPX. ACPX -Codex is a different provider and cannot use either attestation. Claude admission -checks both saved and current profiles against Runner’s qualified catalog; -decodable historical profiles do not authorize recovery. Preparation, submission -and attachment retain that provider binding. Runner’s launch factory normalizes -Claude’s model, mode, permissions, effort and runtime content before Core compares -them with the saved source or current owner. Core revalidates the claim and -profiles after worker replies. This admission does not activate executor recovery. -It grants no replacement authority or exception to deterministic recovery refusals. - -The authenticated request belongs to -the current run while `prepare` and `submit` carry the predecessor Runner identity. -Core derives this relationship from its saved source-consumer claim; a mismatched -run ID alone never grants recovery. Both operations must name the same `resumeFrom`, exact source Runner identity, and current -`accountIdentity`. The request and lease still belong to the current run. -Preparation must save this source binding with its new configuration. Submission -must verify the same binding before it starts the source process. - -Core requires the source run to have a committed successful result, an encrypted -PRP journal, confirmed physical termination, and no other source consumer. Core -claims the source under the current native controller lease. This does not change -the source run's status or result. A stale source controller cannot write its -journal after this claim. Workspace export and settlement holds still apply. -After source submission, the same current owner can prepare its attachment with -the exact source as `priorIdentity`. This does not grant ordinary warm reuse. - -The provider must verify the original account, workspace, runtime, and source -ownership before launch. The provider must reject saved active goals, pending tools, ambiguous starts, and -uncertain work before launch. Runner verifies that a saved idle provider remains -idle when restored. -Until the existing authenticated `run.attach` operation changes authority, the -Core retains semantic inputs and sends no fresh predecessor business commands -while the restored source reconciles its journal and known cleanup. Ordinary suspended recovery and live attachment keep their existing -checks. Providers that omit the capability do not support predecessor recovery. +A `describe` response can include `codexSourceRecoveryVersion: 1` and +`acpxSourceRecoveryVersion: 1`. Core accepts these fields for compatibility and +does not use them. Core does not prepare or submit a predecessor's launch under +a later run. ## Launch authentication validation diff --git a/server/src/__tests__/environment-task-authority.integration.test.ts b/server/src/__tests__/environment-task-authority.integration.test.ts index ce1b237a087..fbede5e10e3 100644 --- a/server/src/__tests__/environment-task-authority.integration.test.ts +++ b/server/src/__tests__/environment-task-authority.integration.test.ts @@ -170,8 +170,7 @@ databaseSuite("environment task lease authority", () => { await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, provider: "plugin:fixture:tasks", providerLeaseId: "tombstoned-task", status: "active", leasePolicy: "reuse_by_environment", metadata: { driver: "plugin", pluginId, pluginKey: pluginId, driverKey: "tasks", runnerTaskLease: true, runnerTaskReused: false, - runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: retained, - runnerTaskSourceRecovery: { schema: "fixture" } } }); + runnerTaskDispatched: false, runnerTaskExecutionStopped: true, runnerTaskSessionRetained: retained } }); const calls: string[] = []; const workers = { getWorker: () => ({ supportedMethods: ["environmentTask", "environmentAcquireLease"] }), call: async (_plugin: string, method: string, params: any, _timeout?: number, _sink?: unknown, settled?: () => void) => { @@ -196,7 +195,7 @@ databaseSuite("environment task lease authority", () => { expect(calls).toEqual(["status:tombstoned-task", "complete:tombstoned-task", "environmentAcquireLease", "describe:replacement-task"]); expect(lease.providerLeaseId).toBe("replacement-task"); expect(lease.metadata).toMatchObject({ runnerTaskExecutionStopped: false, runnerTaskDispatched: false, - runnerTaskSessionRetained: false, runnerTaskSourceRecovery: { schema: "fixture" } }); + runnerTaskSessionRetained: false }); } else { expect(calls).toEqual(["describe:tombstoned-task"]); expect(lease.providerLeaseId).toBe("tombstoned-task"); diff --git a/server/src/services/environment-retained-orphan-settlement.ts b/server/src/services/environment-retained-orphan-settlement.ts index 911a295299c..50bd5cd7018 100644 --- a/server/src/services/environment-retained-orphan-settlement.ts +++ b/server/src/services/environment-retained-orphan-settlement.ts @@ -112,7 +112,7 @@ export function softlyHeldSql(now?: Date) { function alwaysHeldSql() { return sql`(${environmentLeases.metadata} ?| array['nativeWorkspaceExportResume', 'sandboxStopAndRetain', - 'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', 'runnerTaskSourceConsumer', ${REUSABLE_SANDBOX_KEPT_AFTER_REPLACEMENT_KEY}] + 'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', ${REUSABLE_SANDBOX_KEPT_AFTER_REPLACEMENT_KEY}] or ${abandonedWorkspaceFilesHeldOnLeaseRowSql()} or coalesce(${environmentLeases.metadata}->>'pendingCleanupInFlight', 'false') = 'true' or coalesce(${environmentLeases.metadata}#>>'{legacyShutdownWorkspaceSettlement,state}' = 'pending', false) @@ -190,8 +190,8 @@ export async function nextRetainedOrphanDueAt(db: Db, now: Date): Promise | undefined; if (shutdown?.state === "pending") return "legacy_shutdown_fence"; diff --git a/server/src/services/environment-task-runtime.ts b/server/src/services/environment-task-runtime.ts index ded4de1a616..3169aa83034 100644 --- a/server/src/services/environment-task-runtime.ts +++ b/server/src/services/environment-task-runtime.ts @@ -18,7 +18,6 @@ import { pluginRegistryService } from "./plugin-registry.js"; import { remoteTerminationReceipt } from "./remote-execution-termination.js"; import type { PluginWorkerManager } from "./plugin-worker-manager.js"; import { NativeExecutionContext } from "./native-runtime/native-execution-context.js"; -import { assertPluginTaskSourceAttachment, assertPluginTaskSourceRecovery } from "./native-runtime/plugin-task-source-recovery.js"; import { pluginAgentRuntimeIdentity } from "./plugin-agent-runtime-state.js"; import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js"; import { assertPluginTaskOwnershipDispatch, PluginTaskOwnershipPendingError, readyPortableTaskSource, reconcilePluginTaskAdmission } from "./plugin-task-ownership.js"; @@ -212,11 +211,6 @@ export async function executeEnvironmentTask(db: Db, workers: Pick>'portableTaskCheckpointUnavailable', 'false') != 'true' and ${environmentLeases.metadata}->'portableTaskPredecessor' = ${JSON.stringify(metadata.portableTaskPredecessor)}::jsonb` : undefined; - if (runner && !sourceRecovery && ((!checkpointIdentity || !resumeFrom) && !(ownCheckpoint && operation.kind !== "read_file") && runner.runId !== (activeProbe ? probe.runId : run?.id) || (!resumeFrom && runner.leaseId !== lease.id && !ownCheckpoint && !warmAttachment) + if (runner && ((!checkpointIdentity || !resumeFrom) && !(ownCheckpoint && operation.kind !== "read_file") && runner.runId !== (activeProbe ? probe.runId : run?.id) || (!resumeFrom && runner.leaseId !== lease.id && !ownCheckpoint && !warmAttachment) || (activeProbe && (runner.sessionId !== probe.sessionId || (launches && operation.projectIds.length > 0))))) { throw new Error("Plugin-provided Runner execution identity mismatch"); } let stoppedSourceCheckpoint = false; - if (runner && resumeFrom && !sourceRecovery) { + if (runner && resumeFrom) { const inspectCheckpoint = operation.kind === "read_state"; const sources = await db.select({ id: environmentLeases.id, runId: environmentLeases.heartbeatRunId, metadata: environmentLeases.metadata }).from(environmentLeases).where(and( eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.provider, lease.provider!), @@ -648,14 +638,6 @@ export async function executeEnvironmentTask(db: Db, workers: Pick { await f.db.update(environmentLeases).set({ metadata: { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId: f.companyId, runId: f.runId, leaseId, provider: "daytona", providerLeaseId, state: "destroyed", confirmedAt: confirmedAt.toISOString() }, - runnerTaskSourceConsumer: { leaseId: consumerLeaseId, runId: consumerRunId, accountIdentity: "owned-fixture-account", identity } } }) + portableTaskSuccessor: { targetLeaseId: consumerLeaseId, sourceLeaseId: leaseId, operation: { identity } } } }) .where(eq(environmentLeases.id, leaseId)); await f.db.insert(environmentLeases).values({ id: consumerLeaseId, companyId: f.companyId, heartbeatRunId: consumerRunId, - issueId: f.issueId, provider: "daytona", providerLeaseId: randomUUID(), status: "active", metadata: { runnerTaskSourceRecovery: { - schema: "paperclip.runner.source-recovery.v1", sourceLeaseId: leaseId, consumerLeaseId, consumerRunId, - accountIdentity: "owned-fixture-account", controllerBootId: f.owner.bootId, controllerGeneration: 1, identity } } }); + issueId: f.issueId, provider: "daytona", providerLeaseId: randomUUID(), status: "active", metadata: { portableTaskOwnershipReady: true, + portableTaskPredecessor: { targetLeaseId: consumerLeaseId, sourceLeaseId: leaseId, operation: { identity } } } }); const lateCheckpoint = { ...checkpoint, reset: false, changedRecords: new Map([["cursor", checkpoint.records.get("cursor")!]]), removedRecords: [] }; await expect(nativeRunnerCheckpointWriter(f.db, { ...f.owner, authorityRunId: consumerRunId, generation: 1, leaseOwner: "late-source-consumer" })(lateCheckpoint)).rejects.toThrow("native_runner_checkpoint_retired"); diff --git a/server/src/services/native-runtime/native-source-recovery-ownership.ts b/server/src/services/native-runtime/native-source-recovery-ownership.ts index 5d5ff564584..de48978b61f 100644 --- a/server/src/services/native-runtime/native-source-recovery-ownership.ts +++ b/server/src/services/native-runtime/native-source-recovery-ownership.ts @@ -1,4 +1,4 @@ -import { and, asc, eq, exists, inArray, or, sql } from "drizzle-orm"; +import { and, asc, eq, exists, inArray, sql } from "drizzle-orm"; import { environmentLeases, nativeRunFinalizations, nativeRunnerCheckpoints, type Db } from "@paperclipai/db"; import { inspectDurablePrpCheckpointHeader, type DurablePrpCheckpoint } from "../../vendor/paperclip-runner/index.js"; import { nativeSha256 } from "./canonical.js"; @@ -19,8 +19,7 @@ export async function readNativeSourceConsumers(tx: Transaction, companyId: stri sql`${nativeRunnerCheckpoints.material}->>'schema' like 'paperclip.native-runner-checkpoint-retirement.%'`))); return tx.select({ id: environmentLeases.id, metadata: environmentLeases.metadata, retired }).from(environmentLeases).where(and( eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId), - or(sql`${environmentLeases.metadata}->'runnerTaskSourceConsumer' is not null`, - sql`${environmentLeases.metadata}->'portableTaskSuccessor' is not null`))); + sql`${environmentLeases.metadata}->'portableTaskSuccessor' is not null`)); } /** Physical source consumption revokes the completed controller's late writer. */ @@ -36,29 +35,12 @@ export async function assertNativeSourceCheckpointConsumer(tx: Transaction, owne const header = checkpoint.records.get("header"); const identity = header ? inspectDurablePrpCheckpointHeader(header) : null; const portable = record(source.metadata?.portableTaskSuccessor); - if (source.metadata?.portableTaskSuccessor !== undefined) { - if (typeof portable.targetLeaseId !== "string" || portable.sourceLeaseId !== source.id || - !identity || nativeSha256(record(portable.operation).identity ?? null) !== nativeSha256(identity)) return deny(); - const [target] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId), - eq(environmentLeases.id, portable.targetLeaseId))); - if (!target || target.heartbeatRunId !== owner.authorityRunId || target.status !== "active" || target.releasedAt || - target.expiresAt && target.expiresAt.getTime() <= Date.now() || - target.metadata?.portableTaskOwnershipReady !== true || target.metadata.portableTaskSuccessor !== undefined || - nativeSha256(target.metadata.portableTaskPredecessor ?? null) !== nativeSha256(portable)) return deny(); - return; - } - const consumer = record(source.metadata?.runnerTaskSourceConsumer); - if (typeof consumer.leaseId !== "string" || consumer.runId !== owner.authorityRunId) return deny(); - const [lease] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId), - eq(environmentLeases.id, consumer.leaseId))); - const recovery = record(lease?.metadata?.runnerTaskSourceRecovery); - const expected = record(recovery.identity); - if (!lease || lease.heartbeatRunId !== owner.authorityRunId || lease.status !== "active" || lease.releasedAt || - lease.expiresAt && lease.expiresAt.getTime() <= Date.now() || - recovery.schema !== "paperclip.runner.source-recovery.v1" || recovery.sourceLeaseId !== source.id || - recovery.consumerLeaseId !== lease.id || recovery.consumerRunId !== owner.authorityRunId || - typeof recovery.accountIdentity !== "string" || recovery.accountIdentity !== consumer.accountIdentity || - recovery.controllerBootId !== owner.bootId || recovery.controllerGeneration !== owner.generation || - ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"].some(key => - typeof expected[key] !== "string" || expected[key] !== record(identity)[key] || expected[key] !== record(consumer.identity)[key])) return deny(); + if (typeof portable.targetLeaseId !== "string" || portable.sourceLeaseId !== source.id || + !identity || nativeSha256(record(portable.operation).identity ?? null) !== nativeSha256(identity)) return deny(); + const [target] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, owner.companyId), + eq(environmentLeases.id, portable.targetLeaseId))); + if (!target || target.heartbeatRunId !== owner.authorityRunId || target.status !== "active" || target.releasedAt || + target.expiresAt && target.expiresAt.getTime() <= Date.now() || + target.metadata?.portableTaskOwnershipReady !== true || target.metadata.portableTaskSuccessor !== undefined || + nativeSha256(target.metadata.portableTaskPredecessor ?? null) !== nativeSha256(portable)) return deny(); } diff --git a/server/src/services/native-runtime/plugin-runner-task.test.ts b/server/src/services/native-runtime/plugin-runner-task.test.ts index ecca8fe3712..34e4b4ec3d5 100644 --- a/server/src/services/native-runtime/plugin-runner-task.test.ts +++ b/server/src/services/native-runtime/plugin-runner-task.test.ts @@ -59,21 +59,16 @@ describe("plugin native Runner ownership", () => { it("publishes current trusted recovery authority through warm owner rebind", () => { const { task } = provider(); - const input = { taskId: "task", task, projectIds: [], harness: "codex", authorityRunId: "first-owner", codexSourceRecoveryVersion: 1 as const, adoptIdentity: requirements.identity }; + const input = { taskId: "task", task, projectIds: [], harness: "codex", authorityRunId: "first-owner", adoptIdentity: requirements.identity }; const owner = createPluginRunnerTaskOwner(input); expect(owner.driver.authorityRunId).toBe("first-owner"); - expect(owner.driver.codexSourceRecoveryVersion).toBe(1); - owner.rebind({ ...input, authorityRunId: "next-owner", codexSourceRecoveryVersion: undefined }); + owner.rebind({ ...input, authorityRunId: "next-owner" }); expect(owner.driver.authorityRunId).toBe("next-owner"); - expect(owner.driver.codexSourceRecoveryVersion).toBeUndefined(); }); - it.each(["capability", "source", "identity", "account", "provider", "adoption"])("refuses an unqualified predecessor preparation: %s", async mode => { + it.each(["codex", "claude"])("refuses to prepare a predecessor's %s launch", async harness => { const { task } = provider(); - const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness: mode === "provider" ? "claude" : "codex", - authorityRunId: "next", codexSourceRecoveryVersion: mode === "capability" ? undefined : 1, - resumeFrom: mode === "source" ? undefined : "source-task", priorIdentity: mode === "identity" ? undefined : requirements.identity, - accountIdentity: mode === "account" ? undefined : "selected-account", ...(mode === "adoption" ? { adoptIdentity: requirements.identity } : {}), - }); + const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness, authorityRunId: "next", + resumeFrom: "source-task", priorIdentity: requirements.identity, accountIdentity: "selected-account" }); await expect(prepare(owner)).rejects.toThrow("source reconciliation unavailable"); expect(task).not.toHaveBeenCalled(); }); @@ -88,7 +83,7 @@ describe("plugin native Runner ownership", () => { expect(task.mock.calls.map(([operation]) => operation.kind)).toEqual(["check_project_auth"]); } finally { context.finish(); } }); - it.each(["same-run", "suspended-predecessor"])("keeps ordinary %s preparation independent of predecessor capability", async mode => { + it.each(["same-run", "suspended-predecessor"])("keeps ordinary %s preparation", async mode => { const { task } = provider(); const identity = mode === "same-run" ? requirements.identity : { ...requirements.identity, runId: "next" }; const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness: "codex", projectAuthCheckVersion: 1, @@ -110,28 +105,6 @@ describe("plugin native Runner ownership", () => { expect(task.mock.calls.map(([op]) => op).filter(op => op.kind === "prepare").at(-1)).toMatchObject({ resumeFrom: "source-task" }); } finally { await registration.release("detach"); } }); - it("prepares and submits exact A, then prepares B without copying or reconciling A again", async () => { - const { task } = provider(); - const owner = createPluginRunnerTaskOwner({ taskId: "task", task, projectIds: [], harness: "codex", projectAuthCheckVersion: 1, pollMs: 1, - authorityRunId: "next", codexSourceRecoveryVersion: 1, resumeFrom: "source-task", priorIdentity: requirements.identity, - accountIdentity: "selected-account" }); - await expect(prepare(owner, { ...requirements, identity: { ...requirements.identity, runId: "foreign" } })).rejects.toThrow("source reconciliation unavailable"); - await prepare(owner); - const registration = await owner.registration({} as never, "run"); - try { - owner.launcher(launchSpec()); - await vi.waitFor(() => expect(task.mock.calls.some(([op]) => op.kind === "submit")).toBe(true)); - const initial = task.mock.calls.map(([op]) => op).filter(op => ["prepare", "submit"].includes(op.kind)); - expect(initial).toEqual([expect.objectContaining({ kind: "prepare", resumeFrom: "source-task", requirements: expect.objectContaining({ identity: requirements.identity }) }), - expect.objectContaining({ kind: "submit", resumeFrom: "source-task", runner: expect.objectContaining({ runId: "run", turnId: "turn", itemId: "item" }) })]); - await prepare(owner); - expect(task.mock.calls.map(([op]) => op).filter(op => op.kind === "prepare").at(-1)).toMatchObject({ resumeFrom: "source-task" }); - await prepare(owner, { ...requirements, identity: { ...requirements.identity, runId: "next", turnId: "next-turn", itemId: "next-item" } }); - const attached = task.mock.calls.map(([op]) => op).filter(op => op.kind === "prepare").at(-1); - expect(attached).toMatchObject({ priorIdentity: requirements.identity, requirements: { identity: { runId: "next" } } }); - expect(attached).not.toHaveProperty("recoveryPurpose"); expect(attached).not.toHaveProperty("resumeFrom"); - } finally { await registration.release("detach"); } - }); it.each(["finish", "rebind"])("does not send startup Stop after the context %s", mode => { const context = new NativeExecutionContext({ binding: { companyId: "company", agentId: "agent", runId: "run" } } as never, 1_000); const next = new NativeExecutionContext(context.execution, 1_000); diff --git a/server/src/services/native-runtime/plugin-runner-task.ts b/server/src/services/native-runtime/plugin-runner-task.ts index a578b9bd246..f9b9bb9cfac 100644 --- a/server/src/services/native-runtime/plugin-runner-task.ts +++ b/server/src/services/native-runtime/plugin-runner-task.ts @@ -41,7 +41,6 @@ export function createPluginRunnerTaskOwner(input: { priorIdentity?: DurableRecoveryIdentity; /** Current authenticated lease owner; the restored PRP identity may belong to its predecessor. */ authorityRunId?: string; - codexSourceRecoveryVersion?: 1; credentialIdentity?: string; accountIdentity?: string; credential?: PluginEnvironmentTaskCredential; @@ -147,10 +146,7 @@ export function createPluginRunnerTaskOwner(input: { return recovery; } const authorityRunId = input.authorityRunId ?? input.executionContext?.execution.binding.runId; - const sourceRecovery = !!authorityRunId && requirements.identity.runId !== authorityRunId; - if (sourceRecovery && (input.codexSourceRecoveryVersion !== 1 || !input.resumeFrom || !input.priorIdentity || !input.accountIdentity || - input.harness !== "codex" || input.adoptIdentity || Object.entries(input.priorIdentity).some(([key, value]) => - requirements.identity[key as keyof DurableRecoveryIdentity] !== value))) { + if (authorityRunId && requirements.identity.runId !== authorityRunId) { throw new Error("Plugin Runner source reconciliation unavailable"); } if (input.githubBroker && input.githubCredentialBrokerVersion !== 1) { @@ -161,7 +157,7 @@ export function createPluginRunnerTaskOwner(input: { ...(preparationDigest ? { preparationDigest, runDigest: runnerLaunchRunDigest(preparationDigest, requirements) } : {}), ...(input.githubBroker ? { githubBroker: input.githubBroker } : {}), projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}), - ...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId || sourceRecovery) + ...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId) ? { resumeFrom: input.resumeFrom } : {}), ...(input.accountIdentity ? { accountIdentity: input.accountIdentity } : {}), ...(launched && preparedIdentity && requirements.identity.runId !== preparedIdentity.runId @@ -468,7 +464,6 @@ export function createPluginRunnerTaskOwner(input: { }, get authorityRunId() { return input.authorityRunId ?? input.executionContext?.execution.binding.runId; }, get relaunchReleasedRunner() { return launched && input.resumeIdentityVersion === 1 ? input.relaunch?.source : undefined; }, - get codexSourceRecoveryVersion() { return input.codexSourceRecoveryVersion; }, prepareLaunch, authorizeRunnerAdoption, readRunnerState, runnerProcessLauncher: launcher, // The provider resolves the authorized retained task before each state operation. prepareExternalRunnerState: async () => {}, diff --git a/server/src/services/native-runtime/plugin-task-source-recovery.ts b/server/src/services/native-runtime/plugin-task-source-recovery.ts deleted file mode 100644 index d10bfbacaf9..00000000000 --- a/server/src/services/native-runtime/plugin-task-source-recovery.ts +++ /dev/null @@ -1,247 +0,0 @@ -import { and, eq, inArray, sql } from "drizzle-orm"; -import { agents, companies, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db"; -import { environmentTaskOperationSchema, type PluginEnvironmentTaskOperation } from "@paperclipai/plugin-sdk"; -import { createRunnerProviderLaunch, parseNativeExecutionInput, parseNativeRuntimeContext, QUALIFIED_ACPX_PROFILES, inspectDurablePrpCheckpointHeader, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; -import { resolvePluginTaskResume } from "../plugin-task-resume.js"; -import { legacyShutdownWorkspaceResourceProtected } from "../legacy-shutdown-workspace-settlement.js"; -import { NativeExecutionContext } from "./native-execution-context.js"; -import { isCurrentNativeControllerProcess } from "./native-restart-recovery.js"; -import { nativeWorkspaceExportPendingForResource } from "./native-workspace-finalization-state.js"; -import { lockSourceRecoveryCoordinators } from "./native-source-recovery-ownership.js"; -import { loadNativeRunnerCheckpointHeader } from "./native-runner-checkpoint.js"; -import { nativeSha256 as fingerprint } from "./canonical.js"; - -type Requirements = Extract["requirements"]; -type Identity = Requirements["identity"]; -type Harness = "codex" | "claude"; -type Transaction = Parameters[0]>[0]; -const keys = ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"] as const; -const record = (value: unknown): Record => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; -const deny = (): never => { throw new Error("native_source_recovery_ownership_unverified"); }; - -function sourceHarness(execution: NativeExecutionInput): Harness | null { - const provider = execution.provider; - if (provider.kind === "codex") return "codex"; - if (provider.kind !== "acpx" || provider.agent !== "claude") return null; - const qualified = QUALIFIED_ACPX_PROFILES.claude; - return qualified.qualificationStatus !== "pending" && Object.entries(provider.profile).every(([key, value]) => - qualified[key as keyof typeof qualified] === value) ? "claude" : null; -} - -function requestHarness(requirements: Requirements): Harness | null { - return requirements.provider === "codex" ? "codex" - : requirements.provider === "acpx" && requirements.settings.acpxAgent === "claude" ? "claude" : null; -} - -function matchesLaunchPolicy(requirements: Requirements, execution: NativeExecutionInput): boolean { - if (requestHarness(requirements) !== sourceHarness(execution)) return false; - const provider = execution.provider; - if (provider.kind !== "acpx") return true; - let prepared: Record; - try { - prepared = createRunnerProviderLaunch({ ...requirements, provider: "acpx", settings: { - acpxAgent: "claude", acpxMode: requirements.settings.acpxMode, - acpxPermissionMode: requirements.settings.acpxPermissionMode, - acpxPermissionModePinned: requirements.settings.acpxPermissionModePinned, claudeEffort: requirements.settings.claudeEffort, - }, runtimeContext: requirements.runtimeContext === null ? null : parseNativeRuntimeContext(requirements.runtimeContext) }, { - options: {}, root: "/", cwd: "/", codexHome: "/", providerNodeCommand: "", opencodeProxyPath: "", acpxSidecarPath: "", - }); - } catch { return false; } - return prepared.model === provider.model && prepared.agent === provider.agent && prepared.mode === provider.mode && - prepared.permissionMode === (provider.permissionMode ?? "approve-all") && prepared.permissionModePinned === true && - prepared.claudeEffort === ("claudeEffort" in provider ? provider.claudeEffort : undefined) && - record(prepared.providerPolicy).readOnly === ("executionMode" in execution && execution.executionMode === "plan") && - record(prepared.runtimeContext).aggregateDigest === ("runtimeContext" in execution ? execution.runtimeContext.aggregateDigest : undefined); -} - -export type PluginTaskSourceRecovery = { - schema: "paperclip.runner.source-recovery.v1"; - resumeFrom: string; - sourceLeaseId: string; - identity: Identity; - consumerLeaseId: string; - consumerRunId: string; - controllerBootId: string; - controllerGeneration: number; - contextId: string; - accountIdentity: string; - sourceProfileSha256: string; - consumerProfileSha256: string; -}; - -function readRecovery(value: unknown): PluginTaskSourceRecovery | null { - const v = record(value); - const identity = environmentTaskOperationSchema.safeParse({ kind: "read_state", identity: v.identity }); - return v.schema === "paperclip.runner.source-recovery.v1" && identity.success && - ["resumeFrom", "sourceLeaseId", "consumerLeaseId", "consumerRunId", "controllerBootId", "contextId", "accountIdentity"].every(key => typeof v[key] === "string" && v[key] !== "") && - Number.isSafeInteger(v.controllerGeneration) && Number(v.controllerGeneration) >= 0 && - [v.sourceProfileSha256, v.consumerProfileSha256].every(hash => typeof hash === "string" && /^[a-f0-9]{64}$/.test(hash)) - ? v as unknown as PluginTaskSourceRecovery : null; -} - -function pinnedSource(recovery: PluginTaskSourceRecovery) { - const { controllerBootId: _boot, controllerGeneration: _generation, contextId: _context, ...source } = recovery; - return source; -} - -async function inspect(tx: Transaction, input: { - companyId: string; leaseId: string; context: NativeExecutionContext; identity: Identity; resumeFrom: string; accountIdentity: string; -}, expected?: PluginTaskSourceRecovery) { - input.context.assertOpen(); - const binding = input.context.execution.binding; - if (binding.companyId !== input.companyId || input.identity.runId === binding.runId) return deny(); - await tx.execute(sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`); - const owners = await lockSourceRecoveryCoordinators(tx, input.companyId, [input.identity.runId, binding.runId]); - const owner = owners.find(value => value.runId === binding.runId), prior = owners.find(value => value.runId === input.identity.runId); - // NOWAIT preserves the established coordinator-first order without waiting - // behind a workspace-maintenance path which already holds the issue. - const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, input.companyId), eq(issues.id, binding.issueId))).for("update", { noWait: true }); - const runs = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, input.companyId), - inArray(heartbeatRuns.id, [input.identity.runId, binding.runId]))); - const current = runs.find(value => value.id === binding.runId), source = runs.find(value => value.id === input.identity.runId); - const [lease] = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.id, input.leaseId))).for("update"); - const [agent] = await tx.select().from(agents).where(and(eq(agents.companyId, input.companyId), eq(agents.id, binding.agentId))); - const [company] = await tx.select().from(companies).where(eq(companies.id, input.companyId)); - if (!owner || !owner.leaseOwner || !owner.leaseExpiresAt || owner.leaseExpiresAt.getTime() <= Date.now() || - !isCurrentNativeControllerProcess(owner) || owner.resultId || ["committed", "applied", "terminal_failure"].includes(owner.phase) || - !prior || prior.phase !== "committed" || !prior.resultId || prior.leaseOwner || - !current || current.status !== "running" || current.nativeIssueId !== binding.issueId || current.agentId !== binding.agentId || current.resultJson?.nativeCancellation || - !source || source.status !== "succeeded" || !source.finishedAt || source.runtimeMode !== "native" || source.agentId !== binding.agentId || source.nativeIssueId !== binding.issueId || - source.runnerInstanceId !== input.identity.runnerInstanceId || source.nativeSessionId !== input.identity.normalizedSessionId || - !issue || issue.executionRunId !== binding.runId || issue.assigneeAgentId !== binding.agentId || issue.status !== "in_progress" || - company?.status !== "active" || agent?.lifecycleState !== "ready" || ["paused", "terminated", "pending_approval"].includes(agent.status) || - !lease || lease.heartbeatRunId !== binding.runId || lease.issueId !== binding.issueId || lease.status !== "active" || lease.releasedAt || - lease.expiresAt && lease.expiresAt.getTime() <= Date.now() || lease.metadata?.runnerTaskRetiring === true) return deny(); - input.context.assertNativeLease({ bootId: owner.controllerBootId!, leaseOwner: owner.leaseOwner, generation: owner.controllerGeneration }); - const header = await loadNativeRunnerCheckpointHeader(tx, { companyId: input.companyId, issueId: binding.issueId, runId: source.id }); - const protocolIdentity = header ? inspectDurablePrpCheckpointHeader(header) : null; - if (!protocolIdentity || keys.some(key => protocolIdentity[key] !== input.identity[key])) return deny(); - const sourceExecution = parseNativeExecutionInput(source.runnerProfileJson?.nativeExecutionInput); - const consumerExecution = parseNativeExecutionInput(current.runnerProfileJson?.nativeExecutionInput); - const harness = sourceHarness(sourceExecution); - if (!harness || harness !== sourceHarness(consumerExecution) || - sourceExecution.binding.companyId !== input.companyId || sourceExecution.binding.issueId !== binding.issueId || - sourceExecution.binding.agentId !== binding.agentId || sourceExecution.binding.runId !== source.id || - sourceExecution.session.normalizedSessionId !== input.identity.normalizedSessionId || - fingerprint(consumerExecution) !== fingerprint(input.context.execution)) return deny(); - const sourceTask = await resolvePluginTaskResume(tx as unknown as Db, { companyId: input.companyId, leaseId: input.leaseId, - priorIdentity: input.identity, inspectCheckpoint: true }); - if (sourceTask !== input.resumeFrom) return deny(); - const sources = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId), - eq(environmentLeases.heartbeatRunId, source.id), eq(environmentLeases.providerLeaseId, sourceTask))).for("update"); - if (sources.length !== 1) return deny(); - const sourceLease = sources[0]!; - const saved = record(sourceLease.metadata?.runnerTaskIdentity); - const aliases = { runnerInstanceId: "runnerId", environmentLeaseId: "leaseId", runId: "runId", normalizedSessionId: "sessionId", turnId: "turnId", itemId: "itemId" } as const; - if (keys.some(key => saved[aliases[key]] !== input.identity[key]) || - await nativeWorkspaceExportPendingForResource(tx as unknown as Db, sourceLease, binding.runId) || - await legacyShutdownWorkspaceResourceProtected(tx as unknown as Db, sourceLease)) return deny(); - const allocations = await tx.select().from(environmentLeases).where(and(eq(environmentLeases.provider, sourceLease.provider!), - eq(environmentLeases.providerLeaseId, sourceTask))); - if (allocations.some(value => value.companyId !== input.companyId || - value.id !== sourceLease.id && value.id !== lease.id && ["active", "retained", "pending_cleanup"].includes(value.status))) return deny(); - const recovery: PluginTaskSourceRecovery = { schema: "paperclip.runner.source-recovery.v1", identity: input.identity, - resumeFrom: sourceTask, sourceLeaseId: sourceLease.id, consumerLeaseId: lease.id, consumerRunId: binding.runId, - controllerBootId: owner.controllerBootId!, controllerGeneration: owner.controllerGeneration, contextId: input.context.id, accountIdentity: input.accountIdentity, - sourceProfileSha256: fingerprint(source.runnerProfileJson?.nativeExecutionInput), consumerProfileSha256: fingerprint(current.runnerProfileJson?.nativeExecutionInput) }; - if (expected && fingerprint(recovery) !== fingerprint(expected)) return deny(); - input.context.assertOpen(); - if (owner.leaseExpiresAt.getTime() <= Date.now() || lease.expiresAt && lease.expiresAt.getTime() <= Date.now()) return deny(); - return { recovery, sourceLease, lease, sourceExecution, consumerExecution, owner }; -} - -/** Only current B's native authority can consume succeeded A for maintenance. */ -export async function claimPluginTaskSourceRecovery(db: Db, input: { - companyId: string; leaseId: string; context: NativeExecutionContext; identity: Identity; resumeFrom: string; accountIdentity: string; - codexSourceRecoveryVersion?: 1; acpxSourceRecoveryVersion?: 1; - matchesExecution(source: NativeExecutionInput): boolean; -}): Promise { - const harness = sourceHarness(input.context.execution); - if (!harness || (harness === "codex" ? input.codexSourceRecoveryVersion : input.acpxSourceRecoveryVersion) !== 1 || !input.accountIdentity) return deny(); - return db.transaction(async tx => { - const inspected = await inspect(tx, input); - if (!input.matchesExecution(inspected.sourceExecution)) return deny(); - const { recovery, sourceLease, lease } = inspected; - if (Object.hasOwn(lease.metadata ?? {}, "runnerTaskSourceRecovery")) { - const saved = readRecovery(lease.metadata?.runnerTaskSourceRecovery); - if (!saved || fingerprint(pinnedSource(saved)) !== fingerprint(pinnedSource(recovery))) return deny(); - } - const consumer = { leaseId: lease.id, runId: recovery.consumerRunId, resumeFrom: recovery.resumeFrom, - identity: recovery.identity, accountIdentity: recovery.accountIdentity }; - const existing = sourceLease.metadata?.runnerTaskSourceConsumer; - if (existing && fingerprint(existing) !== fingerprint(consumer)) return deny(); - const others = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and( - eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.provider, sourceLease.provider!), - sql`${environmentLeases.id} <> ${lease.id}`, - sql`${environmentLeases.metadata}->>'runnerTaskResumeFrom' = ${input.resumeFrom}`)); - if (others.length) return deny(); - input.context.assertOpen(); - if (inspected.owner.leaseExpiresAt!.getTime() <= Date.now()) return deny(); - await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskSourceConsumer: consumer })}::jsonb` }) - .where(eq(environmentLeases.id, sourceLease.id)); - await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskSourceRecovery: recovery })}::jsonb` }) - .where(eq(environmentLeases.id, lease.id)); - return recovery; - }); -} - -async function assertSourceIdentity(db: Db, input: { - companyId: string; leaseId: string; context: NativeExecutionContext | undefined; - identity: Identity; harness: Harness; requirements?: Requirements; accountIdentity?: string; resumeFrom?: string; requireDispatched?: boolean; -}): Promise { - if (!input.context) return deny(); - const { identity } = input; - return db.transaction(async tx => { - const [lease] = await tx.select({ metadata: environmentLeases.metadata }).from(environmentLeases).where(and( - eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.id, input.leaseId))); - const expected = readRecovery(lease?.metadata?.runnerTaskSourceRecovery); - if (!expected || keys.some(key => expected.identity[key] !== identity[key]) || - input.resumeFrom !== undefined && expected.resumeFrom !== input.resumeFrom || expected.accountIdentity !== input.accountIdentity) return deny(); - const inspected = await inspect(tx, { ...input, context: input.context!, resumeFrom: expected.resumeFrom, accountIdentity: expected.accountIdentity }, expected); - if (sourceHarness(inspected.sourceExecution) !== input.harness) return deny(); - if (input.requirements) { - const execution = input.requirements.identity.runId === expected.identity.runId ? inspected.sourceExecution - : input.requirements.identity.runId === expected.consumerRunId ? inspected.consumerExecution : undefined; - if (!execution || !matchesLaunchPolicy(input.requirements, execution)) return deny(); - } - if (input.requireDispatched && (inspected.lease.metadata?.runnerTaskDispatched !== true || - inspected.lease.metadata?.runnerTaskExecutionStopped === true)) return deny(); - const consumer = record(inspected.sourceLease.metadata?.runnerTaskSourceConsumer); - if (consumer.leaseId !== input.leaseId || consumer.runId !== expected.consumerRunId || consumer.resumeFrom !== expected.resumeFrom || consumer.accountIdentity !== expected.accountIdentity || - fingerprint(consumer.identity) !== fingerprint(identity)) return deny(); - return expected; - }); -} - -/** The worker never derives this exception from an arbitrary mismatched run ID. */ -export async function assertPluginTaskSourceRecovery(db: Db, input: { - companyId: string; leaseId: string; context: NativeExecutionContext | undefined; - operation: Extract; -}): Promise { - const operation = input.operation; - const harness = operation.kind === "prepare" ? requestHarness(operation.requirements) - : operation.runner.harness === "codex" || operation.runner.harness === "claude" ? operation.runner.harness : null; - if (!harness || !operation.resumeFrom || !operation.accountIdentity || - (operation.kind === "prepare" ? !!operation.priorIdentity : !operation.preparedLaunchId || !operation.launch)) return deny(); - const identity = operation.kind === "prepare" ? operation.requirements.identity : { - runnerInstanceId: operation.runner.runnerId, environmentLeaseId: operation.runner.leaseId, runId: operation.runner.runId, - normalizedSessionId: operation.runner.sessionId, turnId: operation.runner.turnId, itemId: operation.runner.itemId, - }; - return assertSourceIdentity(db, { ...input, identity, harness, ...(operation.kind === "prepare" ? { requirements: operation.requirements } : {}), - resumeFrom: operation.resumeFrom, accountIdentity: operation.accountIdentity }); -} - -/** A fresh source incarnation can attach B without pretending it was warm reuse. */ -export async function assertPluginTaskSourceAttachment(db: Db, input: { - companyId: string; leaseId: string; context: NativeExecutionContext | undefined; - operation: Extract; -}): Promise { - const { operation } = input, target = operation.requirements.identity; - const harness = requestHarness(operation.requirements); - if (!harness || !operation.priorIdentity || operation.resumeFrom) return deny(); - const recovery = await assertSourceIdentity(db, { ...input, harness, requirements: operation.requirements, identity: operation.priorIdentity, - accountIdentity: operation.accountIdentity, requireDispatched: true }); - if (target.runId !== recovery.consumerRunId || ["runnerInstanceId", "environmentLeaseId", "normalizedSessionId"].some(key => - target[key as keyof Identity] !== recovery.identity[key as keyof Identity])) return deny(); - return recovery; -} diff --git a/server/src/services/plugin-task-ownership.ts b/server/src/services/plugin-task-ownership.ts index c7f86b60217..8c81afa1a36 100644 --- a/server/src/services/plugin-task-ownership.ts +++ b/server/src/services/plugin-task-ownership.ts @@ -107,7 +107,6 @@ async function ownershipClaim(db: Db, input: { typeof source.metadata.driverKey !== "string" || source.metadata.driverKey !== target.metadata.driverKey || source.metadata.runnerTaskLease !== true || target.metadata.runnerTaskLease !== true || source.metadata.runnerTaskRetiring === true || source.metadata.reusableLeaseSuccessor !== undefined || - source.metadata.runnerTaskSourceConsumer !== undefined || !["retained", "released", "expired"].includes(source.status) || target.status !== "active" || target.releasedAt || target.metadata.runnerTaskRetiring === true || target.expiresAt && target.expiresAt.getTime() <= Date.now() || diff --git a/server/src/services/plugin-task-resume.ts b/server/src/services/plugin-task-resume.ts index 0f6ab97a9c4..38fa15b703a 100644 --- a/server/src/services/plugin-task-resume.ts +++ b/server/src/services/plugin-task-resume.ts @@ -71,11 +71,8 @@ export async function resolvePluginTaskResume(db: Db, input: { // A retained PRP lease is logical; later provider tasks have different physical lease IDs. const candidates = rows.filter(row => { const identity = row.lease.metadata?.runnerTaskIdentity as Record | undefined; - const consumer = row.lease.metadata?.runnerTaskSourceConsumer as { leaseId?: unknown; runId?: unknown; resumeFrom?: unknown } | null | undefined; return row.lease.id !== input.leaseId && row.run.id === input.priorIdentity.runId && row.lease.metadata?.portableTaskSuccessor === undefined && - (!Object.hasOwn(row.lease.metadata ?? {}, "runnerTaskSourceConsumer") || - consumer?.leaseId === input.leaseId && consumer.runId === next?.run.id && consumer.resumeFrom === row.lease.providerLeaseId) && (input.inspectCheckpoint || row.lease.metadata?.runnerTaskSessionRetained === true) && identity?.runnerId === input.priorIdentity.runnerInstanceId && identity.leaseId === input.priorIdentity.environmentLeaseId && identity.sessionId === input.priorIdentity.normalizedSessionId && identity.runId === input.priorIdentity.runId && diff --git a/server/src/services/warm-sandbox-expiry.ts b/server/src/services/warm-sandbox-expiry.ts index dcbfb598c18..4261d5350e2 100644 --- a/server/src/services/warm-sandbox-expiry.ts +++ b/server/src/services/warm-sandbox-expiry.ts @@ -76,7 +76,7 @@ export function warmSandboxExpiryCandidateCondition() { sql`${environmentLeases.provider} is not null and ${environmentLeases.provider} <> 'local'`, sql`${environmentLeases.providerLeaseId} is not null`, sql`not (coalesce(${environmentLeases.metadata}, '{}'::jsonb) ?| array['nativeWorkspaceExportResume', - 'sandboxStopAndRetain', 'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', 'runnerTaskSourceConsumer', + 'sandboxStopAndRetain', 'workspaceRestoreRecovery', 'workspaceRecoveryCleanup', 'portableTaskSuccessor', 'reusableLeaseSuccessor', 'reusableSandboxLeaseSuperseded', ${REUSABLE_SANDBOX_KEPT_AFTER_REPLACEMENT_KEY}])`, sql`coalesce(${environmentLeases.metadata}->>'pendingCleanupInFlight', 'false') <> 'true'`,