fix: preserve restore failure results and stop unsafe retries (#14035)

Preserve agent output and earlier execution errors when workspace restore fails. Report the restore phase and confirmed saved-plan links. Require verified repair before retrying unsafe archives, while preserving approval states and the retry budget.

Verified with full CI, 506 focused regression tests, and Greptile 5/5 with all review threads resolved.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-09-25 11:34:31 -07:00
1 parent 5b09d66183
commit bd6caf51bb
29 files changed
+595 -60

No files matched your search

@@ -264,6 +264,9 @@ describeEmbeddedPostgres("heartbeat list", () => {
summary: "completed",
stdout: oversizedStdout,
nestedHuge: { payload: oversizedNestedPayload },
workspaceRestoreFailure: "restore_unsafe_archive",
finalResponseRecorded: true,
executionBeforeRestore: { errorCode: "model_error", exitCode: 2, timedOut: false },
},
});
@@ -275,6 +278,9 @@ describeEmbeddedPostgres("heartbeat list", () => {
truncated: true,
truncationReason: "oversized_result_json",
stdoutTruncated: true,
workspaceRestoreFailure: "restore_unsafe_archive",
finalResponseRecorded: true,
executionBeforeRestore: { errorCode: "model_error", exitCode: 2, timedOut: false },
});
expect(typeof result?.stdout).toBe("string");
expect((result?.stdout as string).length).toBeLessThan(oversizedStdout.length);
@@ -250,6 +250,30 @@ describeEmbeddedPostgres("heartbeat bounded retry scheduling", () => {
});
}
it.each(["restore_unsafe_archive", "restore_lock_timeout"])("keeps the existing retry budget for %s", async (classification) => {
const runId = randomUUID(), companyId = randomUUID(), agentId = randomUUID();
const now = new Date("2026-04-20T12:00:00.000Z");
await seedRetryFixture({ runId, companyId, agentId, now, errorCode: "workspace_restore_failed", resultJson: {
workspaceRestoreFailure: classification, conversationContinuation: "continue_conversation_v1", errorFamily: "transient_upstream",
} });
const issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Restore fixture", status: "in_progress", assigneeAgentId: agentId });
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId, wakeReason: "issue_assigned" } }).where(eq(heartbeatRuns.id, runId));
const result = await heartbeat.scheduleBoundedRetry(runId, { now, random: () => 0 });
if (classification === "restore_unsafe_archive") {
expect(result).toMatchObject({ outcome: "not_scheduled", errorCode: "legacy_execution_requires_reconciliation" });
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
} else {
expect(result.outcome).toBe("scheduled");
if (result.outcome !== "scheduled" || !result.run) throw new Error("Expected a bounded retry");
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "workspace_restore_failed", scheduledRetryAttempt: 2,
resultJson: { workspaceRestoreFailure: classification, conversationContinuation: "continue_conversation_v1", errorFamily: "transient_upstream" },
}).where(eq(heartbeatRuns.id, result.run.id));
expect(await heartbeat.scheduleBoundedRetry(result.run.id, { now, random: () => 0 })).toMatchObject({ outcome: "retry_exhausted" });
}
});
it("reuses one failure successor across concurrent and repeated scheduling", async () => {
const runId = randomUUID(), companyId = randomUUID(), agentId = randomUUID();
const now = new Date("2026-04-20T12:00:00.000Z");
+28 -1
View File
@@ -5,6 +5,7 @@ import {
activityLog,
agents,
documentRevisions,
documents,
environmentLeases,
environments,
heartbeatRunEvents,
@@ -15,7 +16,7 @@ import {
issueWorkProducts,
workspaceOperations,
} from "@paperclipai/db";
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared";
import { hasWorkspaceRestoreFailure, safeWorkspaceRestorePath, ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "@paperclipai/shared";
import { logger } from "../middleware/logger.js";
import { visibleIssueCondition } from "./issue-visibility.js";
import { classifyRunLiveness } from "./run-liveness.js";
@@ -87,6 +88,13 @@ export function activityService(db: Db) {
when ${heartbeatRuns.resultJson} is null then null
else jsonb_strip_nulls(jsonb_build_object(
'conversationReset', ${heartbeatRuns.resultJson} -> 'conversationReset',
'workspaceRestoreFailure', case when ${heartbeatRuns.resultJson} ->> 'workspaceRestoreFailure'
in ('restore_permission_denied', 'restore_lock_timeout', 'restore_unsafe_archive', 'restore_failed')
then ${heartbeatRuns.resultJson} -> 'workspaceRestoreFailure' end,
'workspaceRestorePath', case when length(${heartbeatRuns.resultJson} ->> 'workspaceRestorePath') <= 180
then ${heartbeatRuns.resultJson} -> 'workspaceRestorePath' end,
'finalResponseRecorded', case when jsonb_typeof(${heartbeatRuns.resultJson} -> 'finalResponseRecorded') = 'boolean'
then ${heartbeatRuns.resultJson} -> 'finalResponseRecorded' end,
'billingType', coalesce(${heartbeatRuns.resultJson} -> 'billingType', ${heartbeatRuns.resultJson} -> 'billing_type'),
'billing_type', coalesce(${heartbeatRuns.resultJson} -> 'billing_type', ${heartbeatRuns.resultJson} -> 'billingType'),
'costUsd', coalesce(
@@ -489,6 +497,16 @@ export function activityService(db: Db) {
}
const executionByRunId = await executionProjectionsForRuns(db, companyId, runIds);
// Only stored, current plan revisions can support a saved-plan link.
// Do not trust an adapter's claim that it wrote a document.
const [savedPlan] = runs.some((run) => hasWorkspaceRestoreFailure(run.resultJson))
? await db.select({ revisionId: documentRevisions.id, runId: documentRevisions.createdByRunId })
.from(issueDocuments)
.innerJoin(documents, and(eq(documents.id, issueDocuments.documentId), eq(documents.companyId, companyId)))
.innerJoin(documentRevisions, and(eq(documentRevisions.id, documents.latestRevisionId), eq(documentRevisions.documentId, documents.id), eq(documentRevisions.companyId, companyId)))
.where(and(eq(issueDocuments.companyId, companyId), eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, "plan")))
.limit(1)
: [];
return runs.map((run) => {
const leaseRow = leaseByRunId.get(run.runId);
const leaseMetadata = leaseRow?.lease.metadata ?? null;
@@ -500,6 +518,15 @@ export function activityService(db: Db) {
: null;
return {
...run,
resultJson: run.resultJson ? {
...run.resultJson,
...(Object.hasOwn(run.resultJson, "workspaceRestorePath") ? {
workspaceRestorePath: safeWorkspaceRestorePath(run.resultJson.workspaceRestorePath),
} : {}),
...(hasWorkspaceRestoreFailure(run.resultJson) ? {
...(savedPlan?.runId === run.runId ? { savedPlanRevisionId: savedPlan.revisionId } : {}),
} : {}),
} : null,
execution: executionByRunId.get(run.runId) ?? null,
environment: leaseRow
? {
@@ -16,7 +16,7 @@ export function isConversationAdapter(adapterType: string): boolean {
export const CONVERSATION_CONTINUATION_POLICY = "continue_conversation_v1";
export function hasConversationContinuationPolicy(result: Record<string, unknown> | null | undefined): boolean {
return result?.conversationContinuation === CONVERSATION_CONTINUATION_POLICY;
return result?.workspaceRestoreFailure !== "restore_unsafe_archive" && result?.conversationContinuation === CONVERSATION_CONTINUATION_POLICY;
}
/** Persisted by the server when it claims the run, before remote provisioning. */
@@ -52,6 +52,7 @@ export async function historicalAdapterType(db: Db, run: typeof heartbeatRuns.$i
}
export async function runUsedConversationAdapter(db: Db, run: typeof heartbeatRuns.$inferSelect): Promise<boolean> {
if (run.resultJson?.workspaceRestoreFailure === "restore_unsafe_archive") return false;
if (hasConversationContinuationPolicy(run.resultJson)) return true;
const adapterType = await historicalAdapterType(db, run);
return adapterType !== null && isConversationAdapter(adapterType);
@@ -70,6 +71,7 @@ export function conversationRecoveryActionPredicate() {
and ${heartbeatRuns.id}::text = ${issueRecoveryActions.evidence}->>'runId'
and coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${issueRecoveryActions.sourceIssueId}::text
and ${heartbeatRuns.runtimeMode} = 'legacy'
and coalesce(${heartbeatRuns.resultJson}->>'workspaceRestoreFailure', '') <> 'restore_unsafe_archive'
and ${inArray(heartbeatRuns.status, ['failed', 'timed_out', 'interrupted', 'cancelled'])}
and ${conversationRunPredicate()}
and ${or(
+10 -2
View File
@@ -19,9 +19,17 @@ export async function getExecutionBlocker(db: Db, companyId: string, issueId: st
boundaryId: issues.conversationBoundaryCommentId }).from(issues).where(and(
eq(issues.companyId, companyId), eq(issues.id, issueId),
)).limit(1);
// Resetting model context cannot make an unsafe workspace safe. This hold
// survives conversation boundaries until the existing repair/reconciliation path clears it.
const [restoreHold] = await db.select().from(issueRecoveryActions).where(and(
eq(issueRecoveryActions.companyId, companyId),
eq(issueRecoveryActions.sourceIssueId, issueId),
executionBlockerPredicate(),
sql`${issueRecoveryActions.evidence}->>'workspaceRestoreFailure' = 'restore_unsafe_archive'`,
)).orderBy(desc(issueRecoveryActions.updatedAt)).limit(1);
// A persisted user /new is an ordered context command, not a retry of uncertain work.
// The normal issue execution lock still serializes it behind any active turn.
if (conversation?.agentId && options?.conversationResetCommentId) {
if (!restoreHold && conversation?.agentId && options?.conversationResetCommentId) {
const [command] = await db.select().from(issueComments).where(and(
eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId),
eq(issueComments.id, options.conversationResetCommentId),
@@ -36,7 +44,7 @@ export async function getExecutionBlocker(db: Db, companyId: string, issueId: st
const ownership = await getConversationOwnershipBlocker(db, companyId, issueId);
if (ownership) return { ...ownership, recoveryActionId: null };
const [action] = await db.select().from(issueRecoveryActions).where(and(
const [action] = restoreHold ? [restoreHold] : await db.select().from(issueRecoveryActions).where(and(
eq(issueRecoveryActions.companyId, companyId),
eq(issueRecoveryActions.sourceIssueId, issueId),
executionBlockerPredicate(),
@@ -1,3 +1,4 @@
import { hasWorkspaceRestoreFailure } from "@paperclipai/shared";
import { randomUUID } from "node:crypto";
import { conversationRecoveryActionPredicate, getConversationOwnershipBlocker } from "./conversation-continuation.js";
import { persistActivity } from "./activity-log.js";
@@ -70,6 +71,10 @@ export async function validateExecutionReconciliation(input: {
"The recovery source or task owner changed. Inspect the current execution before continuing.",
);
}
if (hasWorkspaceRestoreFailure(run.resultJson) &&
(!decision.workspaceRepairEvidence || decision.workspaceRepairEvidence.trim().length < 20)) {
throw conflict("Verify safe workspace staging or repair and record workspaceRepairEvidence before continuing this run.");
}
for (const pid of [
run.processPid,
run.processGroupId ? -run.processGroupId : null,
@@ -471,7 +476,9 @@ export async function settleUnrecoverableExecutions(
(!task.executionRunId || task.executionRunId === run.id) &&
(!task.checkoutRunId || task.checkoutRunId === run.id);
const note = current
? "Automatic recovery stopped. Recorded work is preserved; actions with unverified outcomes will not be repeated."
? hasWorkspaceRestoreFailure(run.resultJson)
? "Workspace repair required. Verify safe staging or repair before continuing. Saved work and approval decisions remain in force."
: "Automatic recovery stopped. Recorded work is preserved; actions with unverified outcomes will not be repeated."
: "Recovery closed because the task's owner, execution, or status changed. No work was replayed.";
let nativeFailureBlock = action.evidence.nativeFailureBlock;
if (current) {
@@ -643,6 +643,25 @@ const support = await getEmbeddedPostgresTestSupport();
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toBeNull();
});
it.each(["issue_commented", "retry_failed_run"])("does not bypass an unsafe restore hold through %s", async reason => {
const f = await seed();
await db.update(agents).set({ adapterType: "grok_local" }).where(eq(agents.id, f.agentId));
await db.update(heartbeatRuns).set({ runtimeMode: "legacy", processPid: null,
errorCode: "workspace_restore_failed", resultJson: { workspaceRestoreFailure: "restore_unsafe_archive", conversationContinuation: "continue_conversation_v1" },
}).where(eq(heartbeatRuns.id, f.sourceRunId));
await db.delete(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.sourceRunId));
await db.update(issueRecoveryActions).set({ cause: "legacy_execution_requires_reconciliation" }).where(eq(issueRecoveryActions.sourceIssueId, f.issueId));
const blocked = vi.fn();
expect(await db.transaction(tx => admitExplicitNativeContinuation({ ...f, reason,
commentId: reason === "issue_commented" ? f.commentId : null,
failedRunId: reason === "retry_failed_run" ? f.sourceRunId : null,
onBlocked: blocked, db: tx as unknown as typeof db,
}))).toBeNull();
expect(blocked).toHaveBeenCalledWith("workspace_repair_required", expect.any(String));
expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ runId: f.sourceRunId });
});
it.each(["issue_commented", "retry_failed_run"])("continues a legacy Daytona run lost before adapter.invoke: %s", async reason => {
const f = await seed();
await db.update(agents).set({ adapterType: "claude_local" }).where(eq(agents.id, f.agentId));
@@ -194,6 +194,9 @@ export async function admitExplicitNativeContinuation(input: {
if (!lockedRun || lockedRun.status !== run.status || lockedRun.agentId !== run.agentId ||
lockedRun.finishedAt?.getTime() !== run.finishedAt.getTime()) return null;
run = lockedRun;
if (run.resultJson?.workspaceRestoreFailure === "restore_unsafe_archive") {
return blocked("workspace_repair_required", "Verify safe workspace staging or repair before continuing. Your message is saved.");
}
const cancelledStartup = await isCancelledNativeStartup(db, run, coordinator);
if (cancelledStartup) cancelledStartupIds.add(run.id);
if (run.runtimeMode !== "native" && !unusedAdmission && !legacyUserTurn && !cancelledStartup) return null;
+38 -6
View File
@@ -1,3 +1,5 @@
import { applyWorkspaceRestoreFailure } from "@paperclipai/adapter-utils/workspace-restore-result";
import { hasWorkspaceRestoreFailure } from "@paperclipai/shared";
import { externalConversationStateSql, nonIdleSlackIssueCondition } from "./slack-conversation-state.js";
import { settleSlackConversation } from "./slack-conversation-lifecycle.js";
import { publicChatTaskUrl } from "./chat-task-url.js";
@@ -3423,6 +3425,21 @@ const heartbeatRunSafeResultJsonColumn = sql<Record<string, unknown> | null>`
'error', left(${heartbeatRuns.resultJson} ->> 'error', ${HEARTBEAT_RUN_RESULT_SUMMARY_MAX_CHARS}),
'stdout', left(${heartbeatRuns.resultJson} ->> 'stdout', ${HEARTBEAT_RUN_RESULT_OUTPUT_MAX_CHARS}),
'stderr', left(${heartbeatRuns.resultJson} ->> 'stderr', ${HEARTBEAT_RUN_RESULT_OUTPUT_MAX_CHARS}),
'workspaceRestoreFailure', case when ${heartbeatRuns.resultJson} ->> 'workspaceRestoreFailure'
in ('restore_permission_denied', 'restore_lock_timeout', 'restore_unsafe_archive', 'restore_failed')
then ${heartbeatRuns.resultJson} -> 'workspaceRestoreFailure' end,
'finalResponseRecorded', case when jsonb_typeof(${heartbeatRuns.resultJson} -> 'finalResponseRecorded') = 'boolean'
then ${heartbeatRuns.resultJson} -> 'finalResponseRecorded' end,
'executionBeforeRestore', case when jsonb_typeof(${heartbeatRuns.resultJson} -> 'executionBeforeRestore') = 'object'
then jsonb_strip_nulls(jsonb_build_object(
'errorCode', left(${heartbeatRuns.resultJson} #>> '{executionBeforeRestore,errorCode}', 128),
'exitCode', case when jsonb_typeof(${heartbeatRuns.resultJson} #> '{executionBeforeRestore,exitCode}') = 'number'
and length(${heartbeatRuns.resultJson} #>> '{executionBeforeRestore,exitCode}') < 16
then ${heartbeatRuns.resultJson} #> '{executionBeforeRestore,exitCode}' end,
'signal', left(${heartbeatRuns.resultJson} #>> '{executionBeforeRestore,signal}', 50),
'timedOut', case when jsonb_typeof(${heartbeatRuns.resultJson} #> '{executionBeforeRestore,timedOut}') = 'boolean'
then ${heartbeatRuns.resultJson} #> '{executionBeforeRestore,timedOut}' end
)) end,
'stdoutTruncated', case
when length(${heartbeatRuns.resultJson} ->> 'stdout') > ${HEARTBEAT_RUN_RESULT_OUTPUT_MAX_CHARS}
then to_jsonb(true)
@@ -24382,9 +24399,9 @@ export function heartbeatService(
if (!guardedDispatch.dispatched) return;
adapterResult = await guardedDispatch.resultPromise;
}
// Adapter returned cleanly, which means its workspace-restore finally
// block also ran without throwing. Record the workspace_finalize
// barrier so dependents that share this executionWorkspace can wake.
adapterResult = applyWorkspaceRestoreFailure(adapterResult);
// A returned result can include a failed restore. Keep the workspace
// barrier closed until required files have been restored.
// If recording the barrier itself fails, propagate as a run failure
// rather than silently leaving dependents stranded behind a missing
// finalize row.
@@ -24400,15 +24417,16 @@ export function heartbeatService(
eq(heartbeatRuns.status, "running"),
),
);
await recordWorkspaceFinalize("succeeded");
const workspaceFinalizeStatus = hasWorkspaceRestoreFailure(adapterResult.resultJson) ? "failed" : "succeeded";
await recordWorkspaceFinalize(workspaceFinalizeStatus);
if (adapterResult.nativeFinalization) {
adapterResult.nativeFinalization.workspaceFinalizeStatus =
"succeeded";
workspaceFinalizeStatus;
try {
const finalized = await finalizeNativeRun({
db,
runId: run.id,
workspaceFinalizeStatus: "succeeded",
workspaceFinalizeStatus,
preserveProviderAttempt: Boolean(nativeWorkspaceSync),
});
await dispatchPendingNativeStatusWakeups({
@@ -26933,6 +26951,7 @@ export function heartbeatService(
}
let reconciledSourceRunId: string | null = null;
let reconciledRestoreRetryCount: number | null = null;
if (executionReconciliationWake) {
const actionId = readNonEmptyString(
enrichedContextSnapshot.recoveryActionId,
@@ -27036,6 +27055,15 @@ export function heartbeatService(
}
if (action.evidence.continuationDelivery !== "pending")
return { kind: "skipped" as const };
const [reconciledRun] = await tx.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.id, sourceRunId),
));
if (hasWorkspaceRestoreFailure(reconciledRun?.resultJson)) {
if ((readNonEmptyString(decision.workspaceRepairEvidence)?.length ?? 0) < 20)
return { kind: "skipped" as const };
// Repair does not reset the remaining automatic retry budget.
reconciledRestoreRetryCount = executionFailureRetryCount(reconciledRun!);
}
reconciledSourceRunId = sourceRunId;
}
@@ -27982,6 +28010,10 @@ export function heartbeatService(
...(reconciledSourceRunId
? { retryOfRunId: reconciledSourceRunId }
: {}),
...(reconciledRestoreRetryCount !== null ? {
scheduledRetryAttempt: reconciledRestoreRetryCount,
scheduledRetryReason: "transient_failure",
} : {}),
})
.returning()
.then((rows) => rows[0]);
@@ -71,3 +71,18 @@ it("retries a busy AI subscription only when no provider work started", () => {
expect(legacyExecutionNeedsReconciliation({ ...waiting, resultJson: {} })).toBe(true);
expect(legacyExecutionNeedsReconciliation({ ...waiting, resultJson: { executionRecovery: { kind: "ai_connection_wait", providerWorkStarted: true } } })).toBe(true);
});
it.each(["failed", "timed_out", "cancelled"])("holds an unsafe archive after %s even with conversation or bootstrap evidence", (status) => {
expect(legacyExecutionNeedsReconciliation({ runtimeMode: "legacy", status, errorCode: "workspace_restore_failed", resultJson: {
workspaceRestoreFailure: "restore_unsafe_archive", conversationContinuation: "continue_conversation_v1",
executionRecovery: { kind: "bootstrap", providerWorkStarted: false }, stopReason: "max_turns",
} })).toBe(true);
});
it("retains conversation retry eligibility for a transient restore lock timeout", () => {
expect(legacyExecutionNeedsReconciliation({ runtimeMode: "legacy", status: "failed", errorCode: "workspace_restore_failed", resultJson: {
workspaceRestoreFailure: "restore_lock_timeout", conversationContinuation: "continue_conversation_v1",
} })).toBe(false);
});
@@ -1,7 +1,8 @@
import { hasWorkspaceRestoreFailure } from "@paperclipai/shared";
import { normalizeMaxTurnStopReason } from "./heartbeat-stop-metadata.js";
import { hasConversationContinuationPolicy } from "./conversation-continuation.js";
import { randomUUID } from "node:crypto";
import { and, eq, inArray, sql } from "drizzle-orm";
import { and, eq, inArray, or, sql } from "drizzle-orm";
import { heartbeatRuns, issueRecoveryActions, issues, type Db } from "@paperclipai/db";
import { issueRecoveryActionService } from "./issue-recovery-actions.js";
import { parseIssueExecutionState } from "./issue-execution-policy.js";
@@ -20,6 +21,8 @@ export function legacyExecutionNeedsReconciliation(
!["failed", "timed_out", "interrupted", "cancelled"].includes(run.status)
)
return false;
// A fresh model turn cannot repair or verify unrestored files.
if (run.resultJson?.workspaceRestoreFailure === "restore_unsafe_archive") return true;
// A fresh conversation turn lets the agent decide what remains. The retry
// scheduler, not an action-outcome hold, owns the automatic attempt limit.
if (hasConversationContinuationPolicy(run.resultJson)) return false;
@@ -116,13 +119,21 @@ export async function terminalizeLegacyExecution(input: {
!["done", "cancelled"].includes(task.status)
) {
// Periodic stranded-work checks may revisit this terminal run before its
// reconciled continuation is dispatched. Preserve the recorded decision.
// reconciled continuation is dispatched. Preserve the recorded decision
// and an existing unsafe-workspace hold instead of creating another one.
const [reconciled] = await tx.select({ id: issueRecoveryActions.id })
.from(issueRecoveryActions).where(and(
eq(issueRecoveryActions.companyId, run.companyId),
eq(issueRecoveryActions.sourceIssueId, task.id),
eq(issueRecoveryActions.status, "resolved"),
sql`${issueRecoveryActions.evidence}->'executionReconciliation'->>'runId' = ${run.id}`,
or(
sql`${issueRecoveryActions.evidence}->'executionReconciliation'->>'runId' = ${run.id}`,
and(
sql`${issueRecoveryActions.evidence}->>'runId' = ${run.id}`,
sql`${issueRecoveryActions.evidence}->>'workspaceRestoreFailure' = 'restore_unsafe_archive'`,
sql`${issueRecoveryActions.evidence}->'automaticRecovery'->>'replay' = 'blocked'`,
),
),
)).limit(1);
if (reconciled) return updated;
await issueRecoveryActionService(tx as unknown as Db).upsertSourceScoped({
@@ -137,11 +148,13 @@ export async function terminalizeLegacyExecution(input: {
runId: run.id,
...(isCurrentReviewer ? { reviewParticipantAgentId: run.agentId } : {}),
originalFailureCode: updated.errorCode,
...(hasWorkspaceRestoreFailure(updated.resultJson) ? { workspaceRestoreFailure: updated.resultJson!.workspaceRestoreFailure } : {}),
adapterRecovery: "unsupported_or_unknown",
attempt: executionFailureRetryCount(run) + 1,
},
nextAction:
"Inspect the stopped provider and recorded actions, then reconcile their outcomes before continuing. This adapter has not established a safe resume checkpoint.",
nextAction: hasWorkspaceRestoreFailure(updated.resultJson)
? "Verify safe workspace staging or repair, then reconcile the stopped run before continuing. Saved work and approval decisions remain in force."
: "Inspect the stopped provider and recorded actions, then reconcile their outcomes before continuing. This adapter has not established a safe resume checkpoint.",
maxAttempts: 3,
wakePolicy: null,
supersedeOnIdentityChange: true,
@@ -1,7 +1,9 @@
import { getExecutionBlocker } from "../execution-blocker.js";
import { createRunDispatch, deriveCommentId } from "../../modules/run-dispatch/index.js";
import { buildExecutionContinuation } from "../execution-continuation.js";
import { issueService } from "../issues.js";
import { activityService } from "../activity.js";
import { instanceSettingsService } from "../instance-settings.js";
import { buildPaperclipWakePayload, heartbeatService } from "../heartbeat.js";
import { legacyExecutionNeedsReconciliation, terminalizeLegacyExecution } from "../legacy-execution-recovery.js";
import { deliverExecutionStatuses } from "../execution-status-delivery.js";
@@ -27,6 +29,10 @@ import {
heartbeatRuns,
issueRecoveryActions,
issueComments,
issueThreadInteractions,
issueDocuments,
documents,
documentRevisions,
issues,
nativeRunFinalizations,
} from "@paperclipai/db";
@@ -361,6 +367,76 @@ const support = externalDatabaseUrl
expect(legacyExecutionNeedsReconciliation({ ...run, status: "failed", resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } })).toBe(false);
expect(legacyExecutionNeedsReconciliation({ ...run, status: "failed", scheduledRetryAttempt: 2, resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } })).toBe(true);
});
it.each(["pending", "accepted", "rejected", "expired"] as const)("preserves %s approval and saved work while unsafe restore recovery is repeated", async (status) => {
const source = await seed();
const documentId = randomUUID(), revisionId = randomUUID(), interactionId = randomUUID();
await db.insert(documents).values({ id: documentId, companyId: source.companyId, title: "Plan", latestBody: "Only the two approved changes.", latestRevisionId: revisionId });
await db.insert(documentRevisions).values({ id: revisionId, companyId: source.companyId, documentId, revisionNumber: 1, body: "Only the two approved changes.", createdByRunId: source.runId });
await db.insert(issueDocuments).values({ companyId: source.companyId, issueId: source.issueId, documentId, key: "plan" });
await db.insert(issueComments).values({ companyId: source.companyId, issueId: source.issueId, authorAgentId: source.agentId, createdByRunId: source.runId, body: "The plan is saved." });
await db.insert(issueThreadInteractions).values({
id: interactionId, companyId: source.companyId, issueId: source.issueId, kind: "request_confirmation", status,
sourceRunId: source.runId, createdByAgentId: source.agentId,
resolvedByUserId: status === "accepted" || status === "rejected" ? "board-user" : null,
resolvedAt: status === "pending" ? null : new Date(),
payload: { version: 1, prompt: "Review the scoped plan.", target: { type: "issue_document", key: "plan", revisionId } },
result: status === "pending" ? null : { version: 1, outcome: status === "expired" ? "superseded_by_comment" : status },
});
const [run] = await db.update(heartbeatRuns).set({
runtimeMode: "legacy", errorCode: "workspace_restore_failed", scheduledRetryAttempt: 1, scheduledRetryReason: "transient_failure",
runnerProfileJson: { adapterDispatch: { adapterType: "grok_local" } },
resultJson: { workspaceRestoreFailure: "restore_unsafe_archive", conversationContinuation: "continue_conversation_v1", summary: "The plan is saved.", workspaceRestorePath: "/tmp/private-clone/file", savedPlanRevisionId: randomUUID() },
}).where(eq(heartbeatRuns.id, source.runId)).returning();
const [resetComment] = await db.insert(issueComments).values({ companyId: source.companyId, issueId: source.issueId, authorUserId: "board-user", body: "/new" }).returning();
await db.update(issues).set({ conversationAgentId: source.agentId, conversationUserId: "board-user", conversationState: "active", conversationBoundaryCommentId: resetComment.id }).where(eq(issues.id, source.issueId));
const activityRuns = await activityService(db).runsForIssue(source.companyId, source.issueId);
expect(activityRuns.find((row) => row.runId === source.runId)?.resultJson).toMatchObject({ workspaceRestoreFailure: "restore_unsafe_archive", savedPlanRevisionId: revisionId, workspaceRestorePath: null });
const before = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId));
const savedComments = await db.select().from(issueComments).where(eq(issueComments.issueId, source.issueId));
for (let attempt = 0; attempt < 2; attempt++) {
await terminalizeLegacyExecution({ db, run, status: "failed" });
await settleUnrecoverableExecutions(db);
}
const [task] = await db.select().from(issues).where(eq(issues.id, source.issueId));
expect(task.status).toBe("blocked");
const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, source.issueId));
expect(actions).toHaveLength(1);
const [action] = actions;
expect(action).toMatchObject({ outcome: "blocked", evidence: { automaticRecovery: { replay: "blocked" }, workspaceRestoreFailure: "restore_unsafe_archive" } });
expect(action.nextAction).toContain("Workspace repair required");
expect(await getExecutionBlocker(db, source.companyId, source.issueId, { conversationResetCommentId: resetComment.id })).toMatchObject({ runId: source.runId });
const decision = { runId: source.runId, providerStopped: true as const, actionOutcome: "mixed" as const, outcomeEvidence: "Verified saved plan and comment. Workspace copy-back failed." };
const input = { db, companyId: source.companyId, issueId: source.issueId, agentId: source.agentId, sourceRunId: source.runId, decision };
await expect(validateExecutionReconciliation(input)).rejects.toThrow("workspaceRepairEvidence");
const verified = { ...decision, workspaceRepairEvidence: "Verified fresh confined staging after repairing the unsafe fixture link." };
await expect(validateExecutionReconciliation({ ...input, decision: verified })).resolves.toMatchObject({ id: source.runId });
await markExecutionReconciliation(db, action, verified, "operator");
// Occupy the only agent slot. Exercise real admission without a provider.
await instanceSettingsService(db).updateExperimental({ enableAgentChat: true });
await db.update(agents).set({ status: "active", adapterType: "grok_local", runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } }).where(eq(agents.id, source.agentId));
await db.update(issues).set({ responsibleUserId: "board-user" }).where(eq(issues.id, source.issueId));
await db.insert(heartbeatRuns).values({ companyId: source.companyId, agentId: source.agentId, status: "running" });
const heartbeat = heartbeatService(db);
const wake = vi.fn(heartbeat.wakeup);
await deliverReconciledExecutions(db, wake as unknown as Parameters<typeof deliverReconciledExecutions>[1]);
await deliverReconciledExecutions(db, wake as unknown as Parameters<typeof deliverReconciledExecutions>[1]);
expect(wake).toHaveBeenCalledTimes(1);
const [successor] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, source.runId));
expect(successor).toMatchObject({ status: "queued", scheduledRetryAttempt: 1, scheduledRetryReason: "transient_failure" });
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, successor.id));
const [original] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, source.runId));
expect(original).toMatchObject({ status: "failed", errorCode: "workspace_restore_failed", resultJson: run.resultJson });
const continuation = await buildExecutionContinuation({ db, companyId: source.companyId, issueId: source.issueId, agentId: source.agentId, context: { previousRunId: source.runId }, summary: null, exposeLowTrustRaw: false });
if (status === "accepted" || status === "rejected") expect(continuation.humanResponses).toContainEqual(expect.objectContaining({ id: interactionId, status }));
else expect(continuation.humanResponses).not.toContainEqual(expect.objectContaining({ id: interactionId }));
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, source.issueId))).toEqual(before);
expect(await db.select().from(issueComments).where(eq(issueComments.issueId, source.issueId))).toEqual(savedComments);
expect(await db.select().from(documentRevisions).where(eq(documentRevisions.documentId, documentId))).toHaveLength(1);
const [savedDocument] = await db.select().from(documents).where(eq(documents.id, documentId));
expect(savedDocument).toMatchObject({ latestBody: "Only the two approved changes.", latestRevisionId: revisionId });
});
it("does not reopen a reconciled legacy run while continuation is pending", async () => {
const source = await seed();
const [run] = await db.update(heartbeatRuns).set({ runtimeMode: "legacy", status: "cancelled" }).where(eq(heartbeatRuns.id, source.runId)).returning();