Skip to content

The open-source app everyone uses to manage agents at work

fix(runtime): retain cancelled workspaces before reconstruction (#16700)

Dotta6bec153410bc
diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md
index 8ba7717df6..e03d218631 100644
--- a/doc/native-workspace-finalization-recovery.md
+++ b/doc/native-workspace-finalization-recovery.md
@@ -369,11 +369,15 @@ from saved sources** to board operators with `runtime:manage`. Select the surviv
attachments, describe the missing work, and record the observed external action
outcomes. A retained or unverified sandbox must use the existing export or file
recovery path instead.
+The source task may still display `in_progress` after an older controller's
+run-only Stop. Reconstruction accepts that inactive state only with no execution
+or checkout owner and the same source, recovery and status-version checks; an
+operator does not need to manufacture a separate blocker merely to record recovery.
`POST /api/issues/{id}/recovery-actions/reconstruct-workspace` records this choice.
It validates the source run, accepted result, prepared descriptor, exact destroyed
lease, current task owner and status version. It rejects active copyback owners,
-competing recovery, newer executions, and attachments from another task or company.
+competing recovery, unreconciled newer executions, and attachments from another task or company.
The transaction records attachment hashes and a durable fresh-session delivery
intent. The old run, result, descriptor and failed finalization remain intact.
Repeated submissions adopt the original intent. Normal admission rechecks source
@@ -387,3 +391,30 @@ Bounded retries keep the same reconstruction authority. Dispatch verifies the
system wake and predecessor chain back to the approved first run. It rechecks
the saved sources, remaining retry limits and current recovery obligations.
Unrelated executions and uncertain predecessor outcomes still stop dispatch.
+
+A later native run-only cancellation may coexist with the older loss decision
+only after its exact Stop acknowledgement, stopped lease receipts, and board
+file-only repair have been recorded. Its external-action outcome must be
+`not_performed`; an unknown or performed action stays held. Reconstruction saves
+the identities and hashes of those repair decisions. Queue claim and dispatch
+recheck the same evidence, so a changed receipt or another later run requires a
+fresh decision. The cancelled run stays cancelled and is never replayed.
+
+Stop also preserves a native workspace prepared before `paperclip_finish`.
+The executor pins its files before releasing the environment. Startup and periodic
+recovery process a bounded batch of historical acknowledged cancellations that
+missed this step. The existing stop-only cleanup worker retains their exact
+sandboxes and records provider receipts; this does not reopen a task or start
+another turn. The normal file-only repair control remains required before an
+older lost-work reconstruction can proceed.
+If file retention loses the task lock, teardown keeps the source active for a
+later pass. Historical sources already stopping or stopped remain eligible under
+the existing exact-source checks. A stopped source requires the independent
+stop-and-retain receipts and must not have a competing allocation owner.
+Active warm allocations keep the same retention retry path. Only historical
+stopping or stopped sources require the ephemeral policy, because a reusable
+released allocation may already have a new owner.
+For a cancelled native run, the file-recovery form also offers an optional
+confirmation that no external actions were performed. Leave it unchecked unless
+the run history verifies that fact. The default records files without certifying
+action outcomes. Changing the selected source clears the evidence and confirmations.
diff --git a/maps/agent-access-map/recovery.md b/maps/agent-access-map/recovery.md
index 5a764e09a7..bb1c639631 100644
--- a/maps/agent-access-map/recovery.md
+++ b/maps/agent-access-map/recovery.md
@@ -189,6 +189,9 @@ Reconstruction also requires board runtime management. It verifies exact source
destruction and same-task attachment hashes, records lost work and external action
outcomes, and admits one fresh continuation through normal execution gates. The
old failed export remains failed. A retained or uncertain source cannot use it.
+An intervening native run-only cancellation requires its own acknowledged Stop,
+confirmed stopped leases, board file repair and `not_performed` action outcome.
+The reconstruction records and rechecks that exact proof; other later runs stay denied.
Retained legacy file-only repair requires the board, exact stopped-source receipts,
and recovered-file evidence. It can record repair for a successful legacy turn
without changing its result or authorizing replay. Queued and running sources
diff --git a/maps/agent-access-map/workspaces.md b/maps/agent-access-map/workspaces.md
index ffaef2f422..105f2992f1 100644
--- a/maps/agent-access-map/workspaces.md
+++ b/maps/agent-access-map/workspaces.md
@@ -9,6 +9,10 @@ result is a durable fresh-session admission request, subject to current executio
gates. It grants no additional tool access, budget, work window or permission to
repeat completed actions. Attachments must belong to the same task and company.
The original failed run and lost-export evidence remain unchanged.
+Later native run-only cancellations can coexist only with confirmed lease stops,
+board file-only repair and an external-action outcome of `not_performed`.
+Their immutable evidence is checked again at dispatch. Historical cancellation
+retention runs internally and grants no new agent operation or authority.
Review date: 2026-10-12. Source commit: `58e16dbddfc9c8d0cf60867f9d9847f0feda055b`.
Native REST transport reconciled in this change; see the
diff --git a/maps/feature-map/workspaces.md b/maps/feature-map/workspaces.md
index 71fd81b538..64d735e10e 100644
--- a/maps/feature-map/workspaces.md
+++ b/maps/feature-map/workspaces.md
@@ -24,6 +24,12 @@ Select surviving task attachments, record lost work and external action outcomes
then rebuild through fresh-session admission. The old failed run remains failed.
Bounded bootstrap retries retain this decision and recheck their system wake,
predecessors, saved files and current execution gates before provider startup.
+Later cancelled runs require their own confirmed stop and board file repair.
+Their evidence is preserved with the reconstruction and rechecked before dispatch.
+Stop retains unfinished native files; startup also repairs missing historical
+retention without replaying the cancelled turn.
+Cancelled native file recovery can record a verified no-action outcome. Its
+confirmation stays optional and resets when the source changes.
Retained sandboxes keep their existing export recovery path. Automated coverage:
[reconstruction](../../server/src/services/native-runtime/native-workspace-reconstruction.test.ts).
Live staging acceptance remains separate from these regression tests.
diff --git a/packages/shared/src/types/execution-projection.ts b/packages/shared/src/types/execution-projection.ts
index 2a8fb29bbc..24e697fc31 100644
--- a/packages/shared/src/types/execution-projection.ts
+++ b/packages/shared/src/types/execution-projection.ts
@@ -87,5 +87,6 @@ export interface ExecutionReconciliation {
descriptorSha256: string;
missingWork: string;
sources: Array<{ attachmentId: string; sha256: string; byteSize: number; filename: string | null }>;
+ interveningExecutions?: Array<{ runId: string; recoveryActionId: string; evidenceSha256: string }>;
};
}
diff --git a/server/src/services/execution-blocker.ts b/server/src/services/execution-blocker.ts
index 2d2ae87c85..f2d9b5b435 100644
--- a/server/src/services/execution-blocker.ts
+++ b/server/src/services/execution-blocker.ts
@@ -54,7 +54,8 @@ export function executionBlockerPredicate() {
export async function getExecutionBlocker(db: Db, companyId: string, issueId: string, options?: { conversationResetCommentId?: string | null }): Promise<ExecutionBlocker | null> {
const [conversation] = await db.select({ agentId: issues.conversationAgentId,
boundaryId: issues.conversationBoundaryCommentId, status: issues.status,
- assigneeAgentId: issues.assigneeAgentId, statusVersion: issues.statusVersion }).from(issues).where(and(
+ assigneeAgentId: issues.assigneeAgentId, statusVersion: issues.statusVersion,
+ executionRunId: issues.executionRunId, checkoutRunId: issues.checkoutRunId }).from(issues).where(and(
eq(issues.companyId, companyId), eq(issues.id, issueId),
)).limit(1);
// Resetting model context cannot repair or recover a workspace. This hold
@@ -108,7 +109,8 @@ export async function getExecutionBlocker(db: Db, companyId: string, issueId: st
)).limit(1) : [];
const canReconstructWorkspace = Boolean(exportLease && hasRemoteTerminationReceipt(exportLease)
&& (exportLease.metadata?.remoteExecutionTermination as { state?: string } | undefined)?.state === "destroyed"
- && !action.evidence.executionReconciliation && conversation?.status === "blocked" && conversation.assigneeAgentId === run?.agentId);
+ && !action.evidence.executionReconciliation && conversation && ["blocked", "in_progress"].includes(conversation.status)
+ && !conversation.executionRunId && !conversation.checkoutRunId && conversation.assigneeAgentId === run?.agentId);
const reconstructionPending = Boolean((action.evidence.executionReconciliation as { workspaceReconstruction?: unknown } | undefined)?.workspaceReconstruction
&& action.evidence.continuationDelivery === "pending");
const queue = await db.select({ payload: agentWakeupRequests.payload }).from(agentWakeupRequests).where(and(
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 474559cd29..31c26160a2 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -3536,6 +3536,7 @@ export function heartbeatService(
return;
}
if (err instanceof NativeCancellationPendingRecoveryError) {
+ await preserveNativeWorkspaceOnFailure();
await cancelRunInternal(
run.id,
"Recovered durable native run cancellation",
diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts
index 80384df1c8..1b79b61b0d 100644
--- a/server/src/services/heartbeat/recovery.ts
+++ b/server/src/services/heartbeat/recovery.ts
@@ -1,4 +1,5 @@
import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js";
+import { preserveCancelledNativeWorkspaces } from "../native-runtime/native-failed-workspace-recovery.js";
import { nativeWorkspaceExportPendingForLease, pendingNativeWorkspaceFinalizationCondition } from "../native-runtime/native-workspace-finalization-state.js";
import { CHAT_COMPLETION_WAKE_REASON } from "../chat-completion-delivery.js";
import {
@@ -914,6 +915,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
environmentRuntime,
onWorkspaceSettled: settleRecoveredNativeWorkspace,
});
+ await preserveCancelledNativeWorkspaces(db);
scheduleRetainedNativeSessionCleanup();
const intent = await readHotRestartIntent().catch((error) => {
logger.warn(
@@ -1921,6 +1923,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
}
async function reapOrphanedRuns(opts?: { staleThresholdMs?: number }) {
+ await preserveCancelledNativeWorkspaces(db);
const staleThresholdMs = opts?.staleThresholdMs ?? 0;
const now = new Date();
// Recovery never launches a provider or infers stopped ownership from
diff --git a/server/src/services/heartbeat/run-control.test.ts b/server/src/services/heartbeat/run-control.test.ts
index d140f7f234..c92207fbdb 100644
--- a/server/src/services/heartbeat/run-control.test.ts
+++ b/server/src/services/heartbeat/run-control.test.ts
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import type { Db } from "@paperclipai/db";
-import { agents, agentWakeupRequests, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues, projects } from "@paperclipai/db";
+import { agents, agentWakeupRequests, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, projects } from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
@@ -19,6 +19,7 @@ import { createHeartbeatRunState } from "./run-state.js";
import { createHeartbeatRunPreparation } from "./run-preparation.js";
import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js";
import { createHeartbeatRunControl, type HeartbeatRunControlDependencies } from "./run-control.js";
+import { preserveCancelledNativeWorkspaces } from "../native-runtime/native-failed-workspace-recovery.js";
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
vi.mock("../adapter-execution-control.js", async (importOriginal) => {
@@ -196,6 +197,56 @@ describe.skipIf(!support.supported)("heartbeat run-control database wiring", ()
return run;
}
+ it.each(["ephemeral", "reuse_by_environment"] as const)("keeps %s cancellation eligible for retention when teardown loses the task lock", async leasePolicy => {
+ const { company, agent } = await fixture();
+ const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Retain cancelled work",
+ status: "in_progress", assigneeAgentId: agent.id }).returning();
+ const runId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID();
+ await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id,
+ issueId: issue.id, nativeIssueId: issue.id, runtimeMode: "native", status: "cancelled", finishedAt: new Date(),
+ runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared",
+ descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null,
+ workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } },
+ resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator", nativeCancellation: {
+ schema: "paperclip.native-cancellation.v1", runId, companyId: company.id, issueId: issue.id,
+ scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true,
+ intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(),
+ } },
+ });
+ await db.insert(nativeRunFinalizations).values({ runId, companyId: company.id, issueId: issue.id,
+ phase: "terminal_failure", failureCode: "native_retry_cancelled" });
+ await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId,
+ issueId: issue.id, provider: "daytona", providerLeaseId, status: "active", leasePolicy,
+ metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } });
+ const deps = callbacks(db), control = createHeartbeatRunControl(db, deps);
+ let ready!: () => void, release!: () => void;
+ const acquired = new Promise<void>(resolve => { ready = resolve; });
+ const released = new Promise<void>(resolve => { release = resolve; });
+ const holding = db.transaction(async tx => {
+ await tx.select().from(issues).where(eq(issues.id, issue.id)).for("update");
+ ready(); await released;
+ });
+ await acquired;
+ try {
+ await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id,
+ status: "cancelled", providerResourceDisposition: "stop_and_retain" });
+ expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled();
+ expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0])
+ .toMatchObject({ status: "active", leasePolicy });
+ } finally { release(); await holding; }
+ await preserveCancelledNativeWorkspaces(db);
+ expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0])
+ .toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" });
+ await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id,
+ status: "cancelled", providerResourceDisposition: "destroy" });
+ expect(deps.envOrchestrator.releaseForRun).toHaveBeenCalledWith(expect.objectContaining({
+ heartbeatRunId: runId, providerResourceDisposition: "stop_and_retain",
+ }));
+ expect(deps.options.closeWarmNativeSessionsForRun).not.toHaveBeenCalled();
+ expect((await deps.getRun(runId))?.status).toBe("cancelled");
+ expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0].status).toBe("in_progress");
+ }, 15_000);
+
it("reports a missing run without entering cancellation", async () => {
const deps = callbacks(db);
await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(randomUUID())).rejects.toThrow("Heartbeat run not found");
diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts
index 7f4a8bf8a2..3e4e0ff026 100644
--- a/server/src/services/heartbeat/run-control.ts
+++ b/server/src/services/heartbeat/run-control.ts
@@ -5,6 +5,9 @@ import {
type WakeupOptions,
} from "./run-preparation.js";
import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js";
+import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";
+import { preserveNativeFailedWorkspace } from "../native-runtime/native-failed-workspace-recovery.js";
+import { readNativeWorkspaceSyncReference } from "../native-runtime/native-workspace-sync.js";
import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
import {
nativeRetryCancellationCommitCondition,
@@ -288,10 +291,24 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
// Recovery can finish workspace copy-back outside the executor's finally.
// Successful copy-back does not earn warm retention for a failed turn.
const status = leaseOwnerRun?.status ?? input.status;
- const providerResourceDisposition = providerResourceDispositionForTerminalRun(
+ let providerResourceDisposition = providerResourceDispositionForTerminalRun(
input.providerResourceDisposition,
status,
);
+ if (leaseOwnerRun?.runtimeMode === "native" && status === "cancelled"
+ && readNativeWorkspaceSyncReference(leaseOwnerRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared"
+ && !nativeRunHasNoWorkspaceAccess(leaseOwnerRun)) {
+ try {
+ const preserved = await preserveNativeFailedWorkspace(db, leaseOwnerRun, { allowPreterminal: true });
+ if (!preserved || !hasRequiredWorkspaceRecovery(preserved.resultJson)) return;
+ } catch {
+ // Keep the active source eligible for the bounded retention sweep.
+ // Teardown must not release it after retention lost a lock or DB write.
+ logger.warn({ runId: input.runId }, "Deferred cancelled workspace teardown until file retention is recorded");
+ return;
+ }
+ providerResourceDisposition = "stop_and_retain";
+ }
if (providerResourceDisposition === "destroy") {
const closeResult = await (
options.closeWarmNativeSessionsForRun ??
diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts
index 0ab36f5fc7..22570efdb0 100644
--- a/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts
+++ b/server/src/services/native-runtime/native-failed-workspace-recovery.test.ts
@@ -5,8 +5,8 @@ import { activityLog, agents, companies, createDb, environmentLeases, environmen
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { getExecutionBlocker } from "../execution-blocker.js";
import { markExecutionReconciliation, validateExecutionReconciliation } from "../execution-recovery-resolution.js";
-import { settleStopOnlyCleanup } from "../sandbox-stop-and-retain.js";
-import { preserveNativeFailedWorkspace } from "./native-failed-workspace-recovery.js";
+import { prepareSandboxStopAndRetain, settleStopOnlyCleanup } from "../sandbox-stop-and-retain.js";
+import { preserveCancelledNativeWorkspaces, preserveNativeFailedWorkspace } from "./native-failed-workspace-recovery.js";
import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js";
import { NativeWorkspaceFinalizationBusyError } from "./native-workspace-finalization-ownership.js";
import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js";
@@ -51,6 +51,80 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
const readLease = async (id: string) => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, id)))[0]!;
const actions = async (issueId: string) => db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId));
+ it.each(["acknowledged", "warm", "pending", "foreign", "owned"])("pins historical cancelled work only after an exact Stop acknowledgement: %s", async kind => {
+ const f = await seed();
+ if (kind === "warm") await db.update(environmentLeases).set({ leasePolicy: "reuse_by_environment" }).where(eq(environmentLeases.id, f.lease.id));
+ await db.update(heartbeatRuns).set({ status: "cancelled", nativePhase: "observed", finishedAt: new Date(),
+ resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator", nativeCancellation: {
+ schema: "paperclip.native-cancellation.v1", runId: f.runId,
+ companyId: kind === "foreign" ? randomUUID() : f.companyId, issueId: f.issueId,
+ scope: "run", reasonCode: "cancellation_run_only", dispatchState: kind === "pending" ? "pending" : "acknowledged",
+ dispatched: true, intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(),
+ } },
+ }).where(eq(heartbeatRuns.id, f.runId));
+ if (kind === "owned") await db.update(nativeRunFinalizations).set({ leaseOwner: "current-controller" })
+ .where(eq(nativeRunFinalizations.runId, f.runId));
+ await preserveCancelledNativeWorkspaces(db);
+ const current = await readRun(f.runId);
+ expect(current).toMatchObject({ status: "cancelled", resultJson: { nativeCancellation: { scope: "run" } } });
+ expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].status).toBe("in_progress");
+ const pinned = kind === "acknowledged" || kind === "warm";
+ expect(await readLease(f.lease.id)).toMatchObject(pinned
+ ? { status: "pending_cleanup", leasePolicy: "retain_on_failure", metadata: { sandboxStopAndRetain: { runId: f.runId } } }
+ : { status: "active", leasePolicy: "ephemeral" });
+ expect(await actions(f.issueId)).toHaveLength(pinned ? 1 : 0);
+ expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1);
+ });
+ it("keeps another cancelled workspace recoverable when one task row is locked", async () => {
+ const busy = await seed(), free = await seed();
+ for (const f of [busy, free]) await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(),
+ resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator", nativeCancellation: {
+ schema: "paperclip.native-cancellation.v1", runId: f.runId, companyId: f.companyId, issueId: f.issueId,
+ scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true,
+ intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(),
+ } },
+ }).where(eq(heartbeatRuns.id, f.runId));
+ let release!: () => void, ready!: () => void;
+ const released = new Promise<void>(resolve => { release = resolve; });
+ const acquired = new Promise<void>(resolve => { ready = resolve; });
+ const holding = db.transaction(async tx => {
+ await tx.select().from(issues).where(eq(issues.id, busy.issueId)).for("update");
+ ready(); await released;
+ });
+ await acquired;
+ try {
+ for (let pass = 0; pass < 3; pass++) await preserveCancelledNativeWorkspaces(db);
+ expect(await readLease(busy.lease.id)).toMatchObject({ status: "active" });
+ expect(await readLease(free.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" });
+ } finally { release(); await holding; }
+ }, 15_000);
+ it.each(["pending_cleanup", "released"])("keeps an exact %s cancellation eligible until its file hold is recorded", async status => {
+ const f = await seed();
+ await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(),
+ resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator", nativeCancellation: {
+ schema: "paperclip.native-cancellation.v1", runId: f.runId, companyId: f.companyId, issueId: f.issueId,
+ scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true,
+ intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(),
+ } },
+ }).where(eq(heartbeatRuns.id, f.runId));
+ const stopping = await prepareSandboxStopAndRetain(db, f.lease);
+ if (!stopping) throw new Error("Expected the exact stop-only source");
+ if (status === "pending_cleanup") {
+ await preserveCancelledNativeWorkspaces(db);
+ expect((await readRun(f.runId)).resultJson).not.toHaveProperty("workspaceRestoreRecovery");
+ expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "ephemeral" });
+ }
+ await settleStopOnlyCleanup(db, stopping, { attemptId: String(stopping.metadata?.pendingCleanupAttemptId),
+ receipt: { providerLeaseId: f.lease.providerLeaseId, state: "stopped" } });
+ for (let pass = 0; pass < 3; pass++) await preserveCancelledNativeWorkspaces(db);
+ expect(await readLease(f.lease.id)).toMatchObject({ status: "released", leasePolicy: "retain_on_failure",
+ metadata: { remoteExecutionTermination: { state: "stopped" } } });
+ expect(await readRun(f.runId)).toMatchObject({ status: "cancelled", resultJson: {
+ workspaceRestoreRecovery: { leaseIds: [f.lease.id] },
+ } });
+ expect(await actions(f.issueId)).toHaveLength(1);
+ });
+
it("pins only the exact unexported source and exposes a file-only recovery card", async () => {
const f = await seed();
const [other] = await db.insert(environmentLeases).values({ companyId: f.companyId, heartbeatRunId: f.runId,
diff --git a/server/src/services/native-runtime/native-failed-workspace-recovery.ts b/server/src/services/native-runtime/native-failed-workspace-recovery.ts
index b36df60f52..76abcdefd3 100644
--- a/server/src/services/native-runtime/native-failed-workspace-recovery.ts
+++ b/server/src/services/native-runtime/native-failed-workspace-recovery.ts
@@ -1,4 +1,4 @@
-import { and, eq, gt, isNull, sql } from "drizzle-orm";
+import { and, asc, eq, gt, inArray, isNull, or, sql } from "drizzle-orm";
import { environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { recordRequiredWorkspaceRestoreFailure } from "../legacy-execution-recovery.js";
import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";
@@ -6,12 +6,15 @@ import { logActivity } from "../activity-log.js";
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js";
import { NativeWorkspaceFinalizationBusyError } from "./native-workspace-finalization-ownership.js";
+import { hasAcknowledgedNativeStopIntent } from "../acknowledged-native-stop.js";
+import { logger } from "../../middleware/logger.js";
export async function preserveNativeFailedWorkspace(db: Db, selected: typeof heartbeatRuns.$inferSelect, options: { allowPreterminal?: boolean; restartRecovery?: NativeRestartRecoveryClaim } = {}) {
if (readNativeWorkspaceSyncReference(selected.runnerProfileJson?.nativeWorkspaceSync)?.state !== "prepared") return;
const issueId = selected.nativeIssueId ?? selected.issueId ?? selected.contextSnapshot?.issueId;
if (typeof issueId !== "string") return;
return db.transaction(async tx => {
+ await tx.execute(sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`);
const [task] = await tx.select({ id: issues.id }).from(issues).where(and(
eq(issues.id, issueId), eq(issues.companyId, selected.companyId),
)).for("update");
@@ -75,3 +78,49 @@ export async function preserveNativeFailedWorkspace(db: Db, selected: typeof hea
return retained;
});
}
+
+const cancelledWorkspaceCursors = new WeakMap<Db, string>();
+
+/** Older controllers could acknowledge Stop without pinning prepared files.
+ * Record only the file obligation; the existing stop-only cleanup worker owns
+ * provider teardown. This never resumes a turn or changes the task's status. */
+export async function preserveCancelledNativeWorkspaces(db: Db) {
+ const select = (cursor?: string) => db.selectDistinct({ runId: heartbeatRuns.id })
+ .from(environmentLeases).innerJoin(heartbeatRuns, and(
+ eq(heartbeatRuns.id, environmentLeases.heartbeatRunId), eq(heartbeatRuns.companyId, environmentLeases.companyId),
+ )).innerJoin(nativeRunFinalizations, and(eq(nativeRunFinalizations.runId, heartbeatRuns.id),
+ eq(nativeRunFinalizations.companyId, heartbeatRuns.companyId), eq(nativeRunFinalizations.issueId, heartbeatRuns.nativeIssueId)))
+ .where(and(or(eq(environmentLeases.status, "active"), and(
+ inArray(environmentLeases.status, ["pending_cleanup", "released"]), eq(environmentLeases.leasePolicy, "ephemeral"),
+ )), eq(heartbeatRuns.runtimeMode, "native"),
+ eq(heartbeatRuns.status, "cancelled"), eq(nativeRunFinalizations.phase, "terminal_failure"),
+ isNull(nativeRunFinalizations.resultId), isNull(nativeRunFinalizations.leaseOwner),
+ sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' = 'prepared'`,
+ sql`${heartbeatRuns.resultJson}->'nativeCancellation'->>'dispatchState' = 'acknowledged'`,
+ cursor ? gt(heartbeatRuns.id, cursor) : undefined,
+ )).orderBy(asc(heartbeatRuns.id)).limit(5);
+ let candidates = await select(cancelledWorkspaceCursors.get(db));
+ if (!candidates.length) {
+ cancelledWorkspaceCursors.delete(db);
+ candidates = await select();
+ }
+ for (const candidate of candidates) {
+ cancelledWorkspaceCursors.set(db, candidate.runId);
+ const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, candidate.runId));
+ if (run && hasAcknowledgedNativeStopIntent(run)) {
+ try { await preserveNativeFailedWorkspace(db, run, { allowPreterminal: true }); }
+ catch (error) {
+ if (error instanceof NativeWorkspaceFinalizationBusyError) continue;
+ let current: unknown = error;
+ let code: string | null = null;
+ for (let depth = 0; depth < 4 && current && typeof current === "object"; depth++) {
+ const value = current as { code?: unknown; cause?: unknown };
+ if (value.code === "55P03" || value.code === "57014") { code = value.code; break; }
+ current = value.cause;
+ }
+ if (!code) throw error;
+ logger.warn({ runId: run.id, code }, "Cancelled native workspace retention is waiting for its current owner");
+ }
+ }
+ }
+}
diff --git a/server/src/services/native-runtime/native-reconstruction-intervening-executions.ts b/server/src/services/native-runtime/native-reconstruction-intervening-executions.ts
new file mode 100644
index 0000000000..7df90f90ac
--- /dev/null
+++ b/server/src/services/native-runtime/native-reconstruction-intervening-executions.ts
@@ -0,0 +1,72 @@
+import { and, eq, inArray, ne, sql } from "drizzle-orm";
+import { environmentLeases, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db";
+import type { ExecutionReconciliation } from "@paperclipai/shared";
+import { hasAcknowledgedNativeStopIntent } from "../acknowledged-native-stop.js";
+import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js";
+import { hasRequiredWorkspaceRecovery } from "../workspace-restore-recovery-state.js";
+import { nativeSha256 } from "./canonical.js";
+import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
+
+type RecordedExecution = NonNullable<NonNullable<ExecutionReconciliation["workspaceReconstruction"]>["interveningExecutions"]>;
+type InterveningRun = Pick<typeof heartbeatRuns.$inferSelect,
+ "id" | "companyId" | "agentId" | "nativeIssueId" | "runtimeMode" | "status" | "finishedAt" | "runnerProfileJson" | "resultJson">;
+
+/** A later run is not made harmless by its terminal status. Only an audited
+ * run-only cancellation with independently recorded file repair can be kept
+ * alongside the older loss decision. Preserve its exact proof through dispatch. */
+export async function reconciledInterveningExecutions(db: Db, source: typeof heartbeatRuns.$inferSelect,
+ runs: InterveningRun[]): Promise<RecordedExecution | null> {
+ const recorded: RecordedExecution = [];
+ for (const run of runs) {
+ if (run.companyId !== source.companyId || run.agentId !== source.agentId || run.nativeIssueId !== source.nativeIssueId
+ || run.runtimeMode !== "native" || run.status !== "cancelled" || !run.finishedAt
+ || !hasAcknowledgedNativeStopIntent(run) || !hasRequiredWorkspaceRecovery(run.resultJson)
+ || run.runnerProfileJson?.nativeWorkspaceFinalizationOwner) return null;
+ const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(
+ eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.runId, run.id),
+ eq(nativeRunFinalizations.issueId, run.nativeIssueId!),
+ )).for("share");
+ if (!coordinator || coordinator.phase !== "terminal_failure" || coordinator.failureCode !== "native_retry_cancelled"
+ || coordinator.leaseOwner || coordinator.resultId || coordinator.nextAttemptAt || coordinator.failureDetail?.successorRunId) return null;
+ const [result] = await db.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
+ eq(nativeRunResults.companyId, run.companyId), eq(nativeRunResults.runId, run.id),
+ )).limit(1);
+ if (result) return null;
+ const reference = readNativeWorkspaceSyncReference(run.runnerProfileJson?.nativeWorkspaceSync);
+ const leases = await db.select().from(environmentLeases).where(and(
+ eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id),
+ )).for("share");
+ if (!reference || !leases.some(lease => lease.id === reference.leaseId && lease.providerLeaseId === reference.providerLeaseId)
+ || leases.some(lease => lease.issueId !== run.nativeIssueId || !hasRemoteTerminationReceipt(lease)
+ || lease.metadata?.pendingCleanupInFlight === true
+ || (lease.metadata?.remoteExecutionTermination as { state?: string } | undefined)?.state !== "stopped")) return null;
+ for (const lease of leases) {
+ const [other] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
+ ne(environmentLeases.id, lease.id), eq(environmentLeases.provider, lease.provider!),
+ eq(environmentLeases.providerLeaseId, lease.providerLeaseId!), inArray(environmentLeases.status, ["active", "retained", "pending_cleanup"]),
+ )).limit(1);
+ if (other) return null;
+ }
+ const actions = await db.select().from(issueRecoveryActions).where(and(
+ eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, run.nativeIssueId!),
+ eq(issueRecoveryActions.status, "resolved"), eq(issueRecoveryActions.outcome, "restored"),
+ sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`,
+ )).for("share");
+ const repairs = actions.filter(action => {
+ const decision = action.evidence.executionReconciliation as ExecutionReconciliation | undefined;
+ return action.evidence.runId === run.id && action.kind === "active_run_watchdog" && action.ownerType === "board"
+ && action.returnOwnerAgentId === null && hasRequiredWorkspaceRecovery(action.evidence)
+ && action.evidence.continuationDelivery === "not_requested" && decision?.runId === run.id
+ && decision.providerStopped === true && decision.actionOutcome === "not_performed"
+ && typeof decision.workspaceRepairEvidence === "string" && decision.workspaceRepairEvidence.trim().length >= 20;
+ });
+ if (repairs.length !== 1) return null;
+ const repair = repairs[0];
+ recorded.push({ runId: run.id, recoveryActionId: repair.id, evidenceSha256: nativeSha256({
+ runId: run.id, finishedAt: run.finishedAt.toISOString(), reference, recovery: run.resultJson?.workspaceRestoreRecovery,
+ reconciliation: repair.evidence.executionReconciliation,
+ leases: leases.map(lease => ({ id: lease.id, receipt: lease.metadata?.remoteExecutionTermination })).sort((a, b) => a.id.localeCompare(b.id)),
+ }) });
+ }
+ return recorded.sort((a, b) => a.runId.localeCompare(b.runId));
+}
diff --git a/server/src/services/native-runtime/native-workspace-reconstruction.test.ts b/server/src/services/native-runtime/native-workspace-reconstruction.test.ts
index 1c9df21bab..5a3551f8a4 100644
--- a/server/src/services/native-runtime/native-workspace-reconstruction.test.ts
+++ b/server/src/services/native-runtime/native-workspace-reconstruction.test.ts
@@ -9,10 +9,12 @@ import { errorHandler } from "../../middleware/index.js";
import { issueRoutes } from "../../routes/issues.js";
import { getExecutionBlocker } from "../execution-blocker.js";
import { admitExplicitNativeContinuation } from "../explicit-native-continuation.js";
-import { deliverReconciledExecutions } from "../execution-recovery-resolution.js";
+import { deliverReconciledExecutions, markExecutionReconciliation, validateExecutionReconciliation } from "../execution-recovery-resolution.js";
import { heartbeatService } from "../heartbeat.js";
import { remoteTerminationReceipt } from "../remote-execution-termination.js";
import { reconstructNativeWorkspace } from "./native-workspace-reconstruction.js";
+import { preserveNativeFailedWorkspace } from "./native-failed-workspace-recovery.js";
+import { settleStopOnlyCleanup } from "../sandbox-stop-and-retain.js";
import { createRunDispatch } from "../../modules/run-dispatch/index.js";
import { drainHeartbeatRunsToQuiescence } from "../../__tests__/helpers/drain-heartbeat-runs.js";
const providerExecute = vi.hoisted(() => vi.fn(async () => ({ exitCode: 0, signal: null, timedOut: false,
@@ -70,6 +72,119 @@ describe("reconstruction after confirmed native workspace loss", () => {
app.use((req, _res, next) => { (req as unknown as { actor: unknown }).actor = actor; next(); });
app.use("/api", issueRoutes(db, {} as never)); app.use(errorHandler); return app;
}
+ async function interveningCancelledRun(f: Awaited<ReturnType<typeof seed>>, repairFiles = true) {
+ const runId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID();
+ const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId,
+ issueId: f.issueId, nativeIssueId: f.issueId, scopeKind: "issue", runtimeMode: "native", status: "cancelled",
+ nativePhase: "observed", createdAt: new Date("2026-05-02T00:00:00Z"), finishedAt: new Date("2026-05-02T00:01:00Z"),
+ contextSnapshot: { issueId: f.issueId }, resultJson: { cancelledByActorType: "user", cancelledByUserId: f.actorId,
+ nativeCancellation: { schema: "paperclip.native-cancellation.v1", runId, companyId: f.companyId, issueId: f.issueId,
+ scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true,
+ intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID() } },
+ runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared",
+ descriptorSha256: "d".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null,
+ workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } },
+ }).returning();
+ await db.insert(nativeRunFinalizations).values({ runId, companyId: f.companyId, issueId: f.issueId,
+ phase: "terminal_failure", failureCode: "native_retry_cancelled" });
+ await db.insert(environmentLeases).values({ id: leaseId, companyId: f.companyId, issueId: f.issueId,
+ heartbeatRunId: runId, provider: "daytona", providerLeaseId, status: "active", leasePolicy: "ephemeral",
+ metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } });
+ if (!repairFiles) return { runId, leaseId, actionId: null };
+ await preserveNativeFailedWorkspace(db, run, { allowPreterminal: true });
+ const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId));
+ await settleStopOnlyCleanup(db, lease, { attemptId: String(lease.metadata?.pendingCleanupAttemptId),
+ receipt: { providerLeaseId, state: "stopped" } });
+ const repair = (await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)))
+ .find(action => action.evidence.runId === runId)!;
+ const decision = { runId, providerStopped: true as const, actionOutcome: "not_performed" as const,
+ outcomeEvidence: "Acknowledged interruption before any recorded tool or external action.",
+ workspaceRepairEvidence: "The exact stopped allocation was inspected; no source edits were made and the host baseline is unchanged." };
+ await validateExecutionReconciliation({ db, companyId: f.companyId, issueId: f.issueId, agentId: f.agentId,
+ sourceRunId: runId, decision, workspaceRepairOnly: true });
+ await markExecutionReconciliation(db, repair, decision, f.actorId, undefined, { workspaceRepairOnly: true });
+ await db.update(issueRecoveryActions).set({ status: "resolved", outcome: "restored" }).where(eq(issueRecoveryActions.id, repair.id));
+ return { runId, leaseId, actionId: repair.id };
+ }
+ it.each(["blocked", "in_progress"] as const)("reconstructs an inactive %s task after an intervening cancelled run was stopped and its files reconciled", async status => {
+ const f = await seed();
+ const [current] = await db.update(issues).set({ status }).where(eq(issues.id, f.issueId)).returning();
+ f.request.expectedStatusVersion = current.statusVersion;
+ const later = await interveningCancelledRun(f);
+ const visible = await request(app()).get(`/api/issues/${f.issueId}`).expect(200);
+ expect(visible.body.executionBlocker).toMatchObject({
+ runId: f.runId, canReconstructWorkspace: true, workspaceRecoveryStatusVersion: current.statusVersion,
+ });
+ await request(app()).post(`/api/issues/${f.issueId}/recovery-actions/reconstruct-workspace`).send(f.body).expect(202);
+ const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));
+ expect(action.evidence.executionReconciliation).toMatchObject({ workspaceReconstruction: {
+ interveningExecutions: [{ runId: later.runId, recoveryActionId: later.actionId, evidenceSha256: expect.stringMatching(/^[a-f0-9]{64}$/) }],
+ } });
+ expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, later.runId)))[0].status).toBe("cancelled");
+ });
+ it("pins a historical cancelled workspace through public heartbeat startup without replaying its turn", async () => {
+ const f = await seed();
+ const later = await interveningCancelledRun(f, false);
+ const heartbeat = runningHeartbeat = heartbeatService(db, { runtimeEnv: { PAPERCLIP_IN_WORKTREE: "false" } });
+ await heartbeat.recoverNativeRunsAfterRestart();
+ expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, later.leaseId)))[0])
+ .toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure",
+ metadata: { sandboxStopAndRetain: { runId: later.runId } } });
+ expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, later.runId)))[0].status).toBe("cancelled");
+ expect((await db.select().from(issues).where(eq(issues.id, f.issueId)))[0].status).toBe("blocked");
+ expect(providerExecute).not.toHaveBeenCalled();
+ });
+ it.each(["unrepaired", "unconfirmed", "foreign_agent", "missing_ack", "performed_action", "rebound"] as const)
+ ("refuses an intervening cancellation without its complete proof: %s", async kind => {
+ const f = await seed();
+ const later = await interveningCancelledRun(f, kind !== "unrepaired");
+ if (kind === "unconfirmed") await db.update(environmentLeases).set({ metadata: {} }).where(eq(environmentLeases.id, later.leaseId));
+ if (kind === "foreign_agent") {
+ const [agent] = await db.insert(agents).values({ companyId: f.companyId, name: "Different owner", adapterType: "paperclip_runner" }).returning();
+ await db.update(heartbeatRuns).set({ agentId: agent.id }).where(eq(heartbeatRuns.id, later.runId));
+ }
+ if (kind === "missing_ack") await db.update(heartbeatRuns).set({ resultJson: {} }).where(eq(heartbeatRuns.id, later.runId));
+ if (kind === "performed_action") {
+ const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, later.actionId!));
+ await db.update(issueRecoveryActions).set({ evidence: { ...action.evidence, executionReconciliation: {
+ ...(action.evidence.executionReconciliation as object), actionOutcome: "mixed",
+ } } }).where(eq(issueRecoveryActions.id, action.id));
+ }
+ if (kind === "rebound") {
+ const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, later.leaseId));
+ await db.insert(environmentLeases).values({ companyId: f.companyId, heartbeatRunId: f.runId, issueId: f.issueId,
+ provider: lease.provider, providerLeaseId: lease.providerLeaseId, status: "active" });
+ }
+ await expect(reconstructNativeWorkspace(f)).rejects.toThrow();
+ expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId)))[0].evidence)
+ .not.toHaveProperty("executionReconciliation");
+ });
+ it.each(["unchanged", "changed_evidence", "extra_reconciled"] as const)
+ ("rechecks the recorded intervening executions at final provider handoff: %s", async kind => {
+ const f = await seed();
+ const later = await interveningCancelledRun(f);
+ await reconstructNativeWorkspace(f);
+ await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" });
+ const heartbeat = heartbeatService(db, { runtimeEnv: {} });
+ await deliverReconciledExecutions(db, heartbeat.wakeup);
+ const [source] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId));
+ const successorId = String(source.evidence.continuationRunId);
+ expect(successorId).not.toBe("undefined");
+ await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, successorId));
+ await db.update(issues).set({ status: "in_progress", executionRunId: successorId }).where(eq(issues.id, f.issueId));
+ if (kind === "changed_evidence") {
+ const [action] = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, later.actionId!));
+ await db.update(issueRecoveryActions).set({ evidence: { ...action.evidence, executionReconciliation: {
+ ...(action.evidence.executionReconciliation as object), workspaceRepairEvidence: "A different later statement cannot replace the frozen original file proof.",
+ } } }).where(eq(issueRecoveryActions.id, action.id));
+ }
+ if (kind === "extra_reconciled") await interveningCancelledRun(f);
+ const dispatch = vi.fn(async () => "provider entered");
+ const result = await createRunDispatch(db).dispatchResolvedInteractionIfCurrent({ companyId: f.companyId,
+ runId: successorId, expectedStatus: "running", dispatch });
+ expect(result.dispatched).toBe(kind === "unchanged");
+ expect(dispatch).toHaveBeenCalledTimes(kind === "unchanged" ? 1 : 0);
+ });
it("keeps a falsely resolved export visible and prevents conversation reset from hiding it", async () => {
const f = await seed();
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ runId: f.runId, workspaceRepairRequired: true, canReconstructWorkspace: true });
@@ -98,7 +213,7 @@ describe("reconstruction after confirmed native workspace loss", () => {
expect((await db.select().from(companies).where(eq(companies.id, f.companyId)))[0].budgetMonthlyCents).toBe(10000);
expect((await db.select().from(agents).where(eq(agents.id, f.agentId)))[0].budgetMonthlyCents).toBe(5000);
});
- it.each(["retained", "receipt", "lease", "owner", "coordinator", "copyback", "newer", "status", "version", "attachment", "result"] as const)("rejects stale or unsafe reconstruction: %s", async kind => {
+ it.each(["retained", "receipt", "lease", "owner", "coordinator", "copyback", "newer", "status", "version", "attachment", "result", "execution", "checkout"] as const)("rejects stale or unsafe reconstruction: %s", async kind => {
const f = await seed();
const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.leaseId));
if (kind === "retained") await db.update(environmentLeases).set({ metadata: { remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: f.providerLeaseId, state: "stopped" }) } }).where(eq(environmentLeases.id, f.leaseId));
@@ -109,9 +224,12 @@ describe("reconstruction after confirmed native workspace loss", () => {
if (kind === "copyback") await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceFinalizationOwner: { token: "other-worker" } } }).where(eq(heartbeatRuns.id, f.runId));
if (kind === "newer") await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, contextSnapshot: { issueId: f.issueId }, status: "succeeded" });
if (kind === "status") await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.issueId));
+ if (kind === "execution") await db.update(issues).set({ executionRunId: f.runId }).where(eq(issues.id, f.issueId));
+ if (kind === "checkout") await db.update(issues).set({ checkoutRunId: f.runId }).where(eq(issues.id, f.issueId));
if (kind === "version") f.request.expectedStatusVersion += 1;
if (kind === "attachment") f.request.attachmentIds = [(await seed()).attachmentId];
if (kind === "result") await db.update(nativeRunResults).set({ schemaStatus: "rejected" }).where(eq(nativeRunResults.id, f.resultId));
+ if (kind === "execution" || kind === "checkout") expect((await getExecutionBlocker(db, f.companyId, f.issueId))?.canReconstructWorkspace).not.toBe(true);
await expect(reconstructNativeWorkspace(f)).rejects.toThrow();
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, f.issueId))).toHaveLength(0);
expect((await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.actionId)))[0].evidence).not.toHaveProperty("executionReconciliation");
diff --git a/server/src/services/native-runtime/native-workspace-reconstruction.ts b/server/src/services/native-runtime/native-workspace-reconstruction.ts
index e83eb9bd53..07191d7b41 100644
--- a/server/src/services/native-runtime/native-workspace-reconstruction.ts
+++ b/server/src/services/native-runtime/native-workspace-reconstruction.ts
@@ -9,6 +9,7 @@ import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js"
import { legacyExecutionNeedsReconciliationWithEvidence } from "../legacy-execution-recovery.js";
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
import { nativeSha256 } from "./canonical.js";
+import { reconciledInterveningExecutions } from "./native-reconstruction-intervening-executions.js";
const causes = ["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"];
const object = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
@@ -53,7 +54,7 @@ export async function validateNativeWorkspaceReconstruction(db: Db, input: {
|| !["active", "escalated", "resolved"].includes(action.status)
|| (action.status === "resolved" && action.resolutionNote !== "new_source_execution_path" && !object(action.evidence.executionReconciliation).workspaceReconstruction)
|| issue.assigneeAgentId !== run.agentId || action.returnOwnerAgentId !== run.agentId
- || !(input.successorRunId ? ["todo", "in_progress"] : ["blocked", "todo"]).includes(issue.status)
+ || !(input.successorRunId ? ["todo", "in_progress"] : ["blocked", "todo", "in_progress"]).includes(issue.status)
|| (issue.executionRunId && issue.executionRunId !== input.successorRunId)
|| (issue.checkoutRunId && issue.checkoutRunId !== input.successorRunId)) throw changed();
const reference = readNativeWorkspaceSyncReference(object(run.runnerProfileJson).nativeWorkspaceSync);
@@ -69,12 +70,25 @@ export async function validateNativeWorkspaceReconstruction(db: Db, input: {
ne(environmentLeases.id, lease.id), eq(environmentLeases.provider, lease.provider!), eq(environmentLeases.providerLeaseId, lease.providerLeaseId!),
inArray(environmentLeases.status, ["active", "retained", "pending_cleanup"]),
)).limit(1);
- const [newer] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
+ const newer = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
+ nativeIssueId: heartbeatRuns.nativeIssueId, runtimeMode: heartbeatRuns.runtimeMode,
+ status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt,
+ runnerProfileJson: sql<Record<string, unknown>>`jsonb_build_object(
+ 'nativeWorkspaceSync', ${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync',
+ 'nativeWorkspaceFinalizationOwner', ${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceFinalizationOwner')`,
+ resultJson: sql<Record<string, unknown>>`jsonb_build_object(
+ 'cancelledByActorType', ${heartbeatRuns.resultJson}->'cancelledByActorType',
+ 'cancelledByUserId', ${heartbeatRuns.resultJson}->'cancelledByUserId',
+ 'nativeCancellation', ${heartbeatRuns.resultJson}->'nativeCancellation',
+ 'workspaceRestoreFailure', ${heartbeatRuns.resultJson}->'workspaceRestoreFailure',
+ 'workspaceRestoreRecovery', ${heartbeatRuns.resultJson}->'workspaceRestoreRecovery')`,
+ }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), ne(heartbeatRuns.id, run.id),
input.successorRunId ? notInArray(heartbeatRuns.id, [input.successorRunId, ...(input.predecessorRunIds ?? [])]) : undefined,
or(eq(heartbeatRuns.nativeIssueId, issue.id), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issue.id}`),
or(gt(heartbeatRuns.createdAt, run.createdAt), inArray(heartbeatRuns.status, ["queued", "running"])),
- )).limit(1);
+ )).limit(65).for("update");
+ const interveningExecutions = newer.length <= 64 ? await reconciledInterveningExecutions(db, run, newer) : null;
const [otherAction] = await db.select({ id: issueRecoveryActions.id }).from(issueRecoveryActions).where(and(
eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.sourceIssueId, issue.id),
ne(issueRecoveryActions.id, action.id), inArray(issueRecoveryActions.status, ["active", "escalated"]),
@@ -84,21 +98,22 @@ export async function validateNativeWorkspaceReconstruction(db: Db, input: {
eq(nativeRunResults.id, coordinator.resultId ?? "00000000-0000-0000-0000-000000000000"),
eq(nativeRunResults.completionContractId, run.completionContractId ?? "00000000-0000-0000-0000-000000000000"), eq(nativeRunResults.schemaStatus, "accepted"),
)).limit(1);
- if (otherLease || newer || otherAction || !result) throw changed();
+ if (otherLease || !interveningExecutions || otherAction || !result) throw changed();
const decision = action.evidence.executionReconciliation as ExecutionReconciliation | undefined;
if (decision?.workspaceReconstruction) {
const reconstruction = decision.workspaceReconstruction;
if ((!input.successorRunId && issue.status !== "todo") || decision.runId !== run.id || reconstruction.schema !== "paperclip.workspace-reconstruction.v1"
|| (input.successorRunId && (action.evidence.continuationRunId !== (input.continuationRootRunId ?? input.successorRunId) || action.evidence.continuationDelivery !== "delivered"))
|| reconstruction.leaseId !== lease.id || reconstruction.resultId !== result.id
- || reconstruction.descriptorSha256 !== reference.descriptorSha256 || !reconstruction.sources?.length) throw changed();
+ || reconstruction.descriptorSha256 !== reference.descriptorSha256 || !reconstruction.sources?.length
+ || nativeSha256(reconstruction.interveningExecutions ?? []) !== nativeSha256(interveningExecutions)) throw changed();
const files = await db.select({ attachmentId: issueAttachments.id, sha256: assets.sha256 }).from(issueAttachments)
.innerJoin(assets, and(eq(assets.id, issueAttachments.assetId), eq(assets.companyId, input.companyId)))
.where(and(eq(issueAttachments.companyId, input.companyId), eq(issueAttachments.issueId, input.issueId),
inArray(issueAttachments.id, reconstruction.sources.map(source => source.attachmentId)))).for("share");
if (files.length !== reconstruction.sources.length || reconstruction.sources.some(source => !files.some(file => file.attachmentId === source.attachmentId && file.sha256 === source.sha256))) throw changed();
}
- return { issue, run, action, reference, lease, result };
+ return { issue, run, action, reference, lease, result, interveningExecutions };
}
export async function validateReconstructedWorkspaceDispatch(db: Db, run: typeof heartbeatRuns.$inferSelect) {
@@ -146,7 +161,8 @@ export async function reconstructNativeWorkspace(input: {
const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, input.companyId), eq(issues.id, input.issueId))).for("update");
const [prior] = await tx.select().from(issueRecoveryActions).where(and(eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.sourceIssueId, input.issueId), eq(issueRecoveryActions.id, request.actionId)));
if (prior?.evidence.workspaceReconstructionRequest === requestSha256) return { replayed: true, publication: null };
- if (!issue || issue.status !== "blocked" || issue.statusVersion !== request.expectedStatusVersion || prior?.evidence.executionReconciliation) throw changed();
+ if (!issue || !["blocked", "in_progress"].includes(issue.status)
+ || issue.statusVersion !== request.expectedStatusVersion || prior?.evidence.executionReconciliation) throw changed();
const source = await validateNativeWorkspaceReconstruction(db, { ...input, ...request });
const files = await tx.select({ attachmentId: issueAttachments.id, sha256: assets.sha256, byteSize: assets.byteSize, filename: assets.originalFilename })
.from(issueAttachments).innerJoin(assets, and(eq(assets.id, issueAttachments.assetId), eq(assets.companyId, input.companyId)))
@@ -157,7 +173,8 @@ export async function reconstructNativeWorkspace(input: {
const decision: ExecutionReconciliation = { runId: request.runId, providerStopped: true,
actionOutcome: request.actionOutcome, outcomeEvidence: request.outcomeEvidence,
workspaceReconstruction: { schema: "paperclip.workspace-reconstruction.v1", leaseId: source.lease.id,
- resultId: source.result.id, descriptorSha256: source.reference.descriptorSha256, missingWork: request.missingWork, sources: files } };
+ resultId: source.result.id, descriptorSha256: source.reference.descriptorSha256, missingWork: request.missingWork, sources: files,
+ ...(source.interveningExecutions.length ? { interveningExecutions: source.interveningExecutions } : {}) } };
await markExecutionReconciliation(db, source.action, decision, input.actorId);
const now = new Date();
await tx.update(issueRecoveryActions).set({ status: "resolved", outcome: "handed_back", resolvedAt: now, updatedAt: now,
diff --git a/ui/src/components/WorkspaceFileRecovery.test.tsx b/ui/src/components/WorkspaceFileRecovery.test.tsx
index 013c33995e..d6085406f2 100644
--- a/ui/src/components/WorkspaceFileRecovery.test.tsx
+++ b/ui/src/components/WorkspaceFileRecovery.test.tsx
@@ -38,6 +38,40 @@ describe.each(["legacy_execution_requires_reconciliation", "native_continuation_
await act(async () => Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Record file recovery")!.click());
await act(async () => { await new Promise(resolve => setTimeout(resolve, 10)); });
}
+ it("records an optional verified no-action outcome only for the selected cancelled native run", async () => {
+ await mount({ blocker: { ...blocker, runStatus: "cancelled" } });
+ await enterEvidence(); await confirm();
+ const label = Array.from(container.querySelectorAll("label"))
+ .find(node => node.textContent === "I verified that this run performed no external actions.");
+ if (cause === "native_continuation_requires_reconciliation") {
+ expect(label).toBeDefined();
+ const input = document.getElementById(label!.htmlFor)!;
+ await act(async () => input.click());
+ } else expect(label).toBeUndefined();
+ await submit();
+ expect(resolve).toHaveBeenCalledWith("task", expect.objectContaining({ executionReconciliation: expect.objectContaining({
+ actionOutcome: cause === "native_continuation_requires_reconciliation" ? "not_performed" : "mixed",
+ }) }));
+ });
+ it("leaves external action outcomes uncertified by default for cancelled runs", async () => {
+ await mount({ blocker: { ...blocker, runStatus: "cancelled" } });
+ await enterEvidence(); await confirm(); await submit();
+ expect(resolve).toHaveBeenCalledWith("task", expect.objectContaining({ executionReconciliation: expect.objectContaining({
+ actionOutcome: "mixed", outcomeEvidence: expect.stringContaining("does not replay the source run or certify its external action outcomes"),
+ }) }));
+ });
+ it.each(["runId", "recoveryActionId"] as const)("clears source evidence and confirmations when %s changes", async field => {
+ await mount({ blocker: { ...blocker, runStatus: "cancelled" } });
+ await enterEvidence(); await confirm();
+ const label = Array.from(container.querySelectorAll("label"))
+ .find(node => node.textContent === "I verified that this run performed no external actions.");
+ if (label) await act(async () => document.getElementById(label.htmlFor)!.click());
+ await mount({ blocker: { ...blocker, runStatus: "cancelled", [field]: "another-source" } });
+ expect(container.querySelector("textarea")?.value).toBe("");
+ expect(Array.from(container.querySelectorAll('[role="checkbox"]')).every(node => node.getAttribute("aria-checked") === "false")).toBe(true);
+ expect(Array.from(container.querySelectorAll("button")).find(node => node.textContent === "Record file recovery")?.disabled).toBe(true);
+ expect(resolve).not.toHaveBeenCalled();
+ });
it.each(["blocked", "in_progress", "in_review", "done", "cancelled"] as Issue["status"][])("records verified source files without changing the %s task", async issueStatus => {
await mount({ issueStatus });
const button = Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Record file recovery")!;
diff --git a/ui/src/components/WorkspaceFileRecovery.tsx b/ui/src/components/WorkspaceFileRecovery.tsx
index e82f6dbad4..f19518c87a 100644
--- a/ui/src/components/WorkspaceFileRecovery.tsx
+++ b/ui/src/components/WorkspaceFileRecovery.tsx
@@ -7,32 +7,45 @@ import { Checkbox } from "./ui/checkbox";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
-export function WorkspaceFileRecovery({ issueId, issueStatus, blocker, canManage, onRecorded }: {
+type WorkspaceFileRecoveryProps = {
issueId: string;
issueStatus: Issue["status"];
blocker: ExecutionBlocker;
canManage: boolean;
onRecorded: () => void;
-}) {
+};
+
+export function WorkspaceFileRecovery(props: WorkspaceFileRecoveryProps) {
+ const { blocker } = props;
+ if (!blocker.workspaceRepairRequired || !blocker.canRecordWorkspaceRepair ||
+ !["legacy_execution_requires_reconciliation", "native_continuation_requires_reconciliation"].includes(blocker.cause)
+ || !blocker.recoveryActionId || !blocker.runId) return null;
+ return <WorkspaceFileRecoveryForm key={`${props.issueId}:${blocker.recoveryActionId}:${blocker.runId}`} {...props} />;
+}
+
+function WorkspaceFileRecoveryForm({ issueId, issueStatus, blocker, canManage, onRecorded }: WorkspaceFileRecoveryProps) {
const noteId = useId();
const confirmationId = useId();
+ const noActionsId = useId();
const [evidence, setEvidence] = useState("");
const [confirmed, setConfirmed] = useState(false);
+ const [noActions, setNoActions] = useState(false);
+ const canConfirmNoActions = blocker.cause === "native_continuation_requires_reconciliation" && blocker.runStatus === "cancelled";
+ const noActionsConfirmed = canConfirmNoActions && noActions;
const record = useMutation({
mutationFn: () => issuesApi.resolveRecoveryAction(issueId, {
actionId: blocker.recoveryActionId!, outcome: "restored", sourceIssueStatus: issueStatus,
resolutionNote: evidence.trim(),
executionReconciliation: {
- runId: blocker.runId!, providerStopped: true, actionOutcome: "mixed",
- outcomeEvidence: "This request records recovered workspace files only. It does not replay the source run or certify its external action outcomes.",
+ runId: blocker.runId!, providerStopped: true, actionOutcome: noActionsConfirmed ? "not_performed" : "mixed",
+ outcomeEvidence: noActionsConfirmed
+ ? "The board operator verified that this run performed no external actions. This request records recovered workspace files and does not replay the source run."
+ : "This request records recovered workspace files only. It does not replay the source run or certify its external action outcomes.",
workspaceRepairEvidence: evidence.trim(),
},
}),
onSuccess: onRecorded,
});
- if (!blocker.workspaceRepairRequired || !blocker.canRecordWorkspaceRepair ||
- !["legacy_execution_requires_reconciliation", "native_continuation_requires_reconciliation"].includes(blocker.cause)
- || !blocker.recoveryActionId || !blocker.runId) return null;
return <section aria-label="Record workspace file recovery" className="flex w-full flex-col gap-2">
{record.isSuccess ? <p role="status">File recovery recorded. The task status is unchanged. Continue the task when it is ready.</p>
: canManage ? <>
@@ -44,6 +57,10 @@ export function WorkspaceFileRecovery({ issueId, issueStatus, blocker, canManage
<Checkbox id={confirmationId} checked={confirmed} onCheckedChange={value => setConfirmed(value === true)} disabled={record.isPending} />
<Label htmlFor={confirmationId}>I recovered and verified the original workspace files.</Label>
</div>
+ {canConfirmNoActions && <div className="flex items-center gap-2">
+ <Checkbox id={noActionsId} checked={noActions} onCheckedChange={value => setNoActions(value === true)} disabled={record.isPending} />
+ <Label htmlFor={noActionsId}>I verified that this run performed no external actions.</Label>
+ </div>}
<p className="text-muted-foreground">This records file recovery. It keeps the current task status and does not start a run. Paperclip verifies that the original execution stopped.</p>
<div className="flex justify-end">
<Button disabled={record.isPending || !confirmed || evidence.trim().length < 20} onClick={() => record.mutate()}>