The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(recovery): route recovery by failure cause (#9634)
Dottad32ed8844356
diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.mdindex fabb879125..4fff1753c8 100644--- a/doc/SPEC-implementation.md+++ b/doc/SPEC-implementation.md@@ -498,6 +498,8 @@ V1 non-terminal liveness rule:- invalid external-wait recovery queues at most one normal-model continuation per source-state fingerprint, then requires a real blocker or explicit recovery action instead of repeating equivalent recovery wakes; new durable source activity may establish a new fingerprint- when Paperclip cannot safely infer the next action, it surfaces the problem through visible blocked/recovery work instead of silently completing or reassigning work- explicit recovery actions are the liveness primitive; source-scoped actions are the default form, issue-backed recovery is a fallback for independent repair work or safety boundaries, and comments alone are evidence rather than a healthy liveness path+- source-scoped recovery routing is cause-keyed: lost processes, missing successful-run dispositions, and output-inactivity terminations retry the original agent when invokable; provider-quota failures create/reuse a scheduled wait-recovery monitor without a takeover wake; workspace validation and unknown causes route to the manager ladder+- recovery-scoped wakes replace the normal deliverable execution contract with a cause-specific recovery contract, and successful repair returns the issue to the recorded original owner by default while recording `handed_back` versus `owner_completed`Detailed ownership, execution, blocker, active-run watchdog, crash-recovery, and non-terminal liveness semantics are documented in `doc/execution-semantics.md`.diff --git a/packages/adapter-utils/src/server-utils.test.ts b/packages/adapter-utils/src/server-utils.test.tsindex 4a5f8c8f85..4ce82bbbe6 100644--- a/packages/adapter-utils/src/server-utils.test.ts+++ b/packages/adapter-utils/src/server-utils.test.ts@@ -774,12 +774,75 @@ describe("renderPaperclipWakePrompt", () => {]) {expect(prompt).toContain("Execution contract: take concrete action in this heartbeat");expect(prompt).toContain("clear final disposition");+ expect(prompt).toContain("Immediately before returning, verify that Paperclip records one of those dispositions");+ expect(prompt).toContain("a successful process exit or final response is not sufficient");+ expect(prompt).toContain("If no valid disposition is recorded, record it now and do not end the run");expect(prompt).toContain("evidence, not valid liveness paths by themselves");expect(prompt).toContain("Use child issues for long or parallel delegated work instead of polling");expect(prompt).toContain("named unblock owner/action");}});+ it.each([+ [+ "process_lost",+ "Try again — resume from durable progress; don't redo completed steps.",+ ],+ [+ "successful_run_missing_state",+ "Your run completed but left no final disposition.",+ ],+ [+ "provider_quota",+ "Verify or create the wait-recovery monitor for the provider quota reset",+ ],+ [+ "codex_output_inactivity_monitor",+ "Your run was killed by the output-inactivity monitor",+ ],+ [+ "workspace_validation_failed",+ "Recover/fix the workspace (worktree, branch, workspace link)",+ ],+ [+ "stranded_assigned_issue",+ "Fix the underlying problem (auth, config, adapter, budget…)",+ ],+ ])("replaces the generic execution contract for %s recovery wakes", (cause, instruction) => {+ const prompt = renderPaperclipWakePrompt({+ reason: "source_scoped_recovery_action",+ issue: {+ id: "issue-1",+ identifier: "PAP-14092",+ title: "Recover work",+ status: "blocked",+ },+ recovery: {+ cause,+ failureSummary: "adapter stopped",+ originalAssignee: { id: "agent-1", name: "Coder" },+ attemptCount: 2,+ maxAttempts: 3,+ nextAction: "Restore the execution path.",+ },+ commentWindow: { requestedCount: 0, includedCount: 0, missingCount: 0 },+ comments: [],+ fallbackFetchNeeded: false,+ }, { includeExecutionContract: true });++ expect(prompt).toContain(+ "Recovery contract: your job is to RECOVER this task, not to do the work. Do not produce the deliverable yourself.",+ );+ expect(prompt).toContain(instruction);+ expect(prompt).toContain("Fallback preference order: (1) send back to Coder");+ expect(prompt).toContain(`- recovery cause: ${cause}`);+ expect(prompt).toContain("- failure summary: adapter stopped");+ expect(prompt).toContain("- original assignee: Coder");+ expect(prompt).toContain("- recovery attempt: 2/3");+ expect(prompt).toContain("- next action: Restore the execution path.");+ expect(prompt).not.toContain("Execution contract: take concrete action");+ });+it("keeps exactly one execution contract in a composed fresh heartbeat prompt", () => {const wakePrompt = renderPaperclipWakePrompt({reason: "issue_assigned",diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.tsindex acb4d305ed..d3e6b4e73a 100644--- a/packages/adapter-utils/src/server-utils.ts+++ b/packages/adapter-utils/src/server-utils.ts@@ -627,8 +627,19 @@ type PaperclipWakeExecutionWorkspace = {branchName: string | null;};+type PaperclipWakeRecovery = {+ cause: string | null;+ failureSummary: string | null;+ originalAssignee: { id: string | null; name: string | null } | null;+ attemptCount: number | null;+ maxAttempts: number | null;+ nextAction: string | null;+ routingFallbackReason: string | null;+};+type PaperclipWakePayload = {reason: string | null;+ recovery: PaperclipWakeRecovery | null;issue: PaperclipWakeIssue | null;checkedOutByHarness: boolean;dependencyBlockedInteraction: boolean;@@ -658,6 +669,26 @@ type PaperclipWakePayload = {fallbackFetchNeeded: boolean;};+function normalizePaperclipWakeRecovery(value: unknown): PaperclipWakeRecovery | null {+ const recovery = parseObject(value);+ const cause = asString(recovery.cause, "").trim() || null;+ if (!cause) return null;+ const originalAssignee = parseObject(recovery.originalAssignee);+ const originalAssigneeId = asString(originalAssignee.id, "").trim() || null;+ const originalAssigneeName = asString(originalAssignee.name, "").trim() || null;+ return {+ cause,+ failureSummary: asString(recovery.failureSummary, "").trim() || null,+ originalAssignee: originalAssigneeId || originalAssigneeName+ ? { id: originalAssigneeId, name: originalAssigneeName }+ : null,+ attemptCount: typeof recovery.attemptCount === "number" ? recovery.attemptCount : null,+ maxAttempts: typeof recovery.maxAttempts === "number" ? recovery.maxAttempts : null,+ nextAction: asString(recovery.nextAction, "").trim() || null,+ routingFallbackReason: asString(recovery.routingFallbackReason, "").trim() || null,+ };+}+function normalizePaperclipWakeIssue(value: unknown): PaperclipWakeIssue | null {const issue = parseObject(value);const id = asString(issue.id, "").trim() || null;@@ -1203,6 +1234,7 @@ export function normalizePaperclipWakePayload(value: unknown): PaperclipWakePayl: [];const livenessContinuation = normalizePaperclipWakeLivenessContinuation(payload.livenessContinuation);const taskWatchdog = normalizePaperclipWakeTaskWatchdog(payload.taskWatchdog);+ const recovery = normalizePaperclipWakeRecovery(payload.recovery);const childIssueSummaries = Array.isArray(payload.childIssueSummaries)? payload.childIssueSummaries.map((entry) => normalizePaperclipWakeChildIssueSummary(entry))@@ -1222,12 +1254,13 @@ export function normalizePaperclipWakePayload(value: unknown): PaperclipWakePaylconst activeTreeHold = normalizePaperclipWakeTreeHoldSummary(payload.activeTreeHold);const checkboxSelection = normalizePaperclipWakeCheckboxSelection(payload.checkboxSelection);const executionWorkspace = normalizePaperclipWakeExecutionWorkspace(payload.executionWorkspace);- if (comments.length === 0 && commentIds.length === 0 && annotationDeltas.length === 0 && childIssueSummaries.length === 0 && unresolvedBlockerIssueIds.length === 0 && unresolvedBlockerSummaries.length === 0 && !activeTreeHold && !executionStage && !continuationSummary && !planReviewContext && !livenessContinuation && !taskWatchdog && !checkboxSelection && !executionWorkspace && !normalizePaperclipWakeIssue(payload.issue)) {+ if (comments.length === 0 && commentIds.length === 0 && annotationDeltas.length === 0 && childIssueSummaries.length === 0 && unresolvedBlockerIssueIds.length === 0 && unresolvedBlockerSummaries.length === 0 && !activeTreeHold && !executionStage && !continuationSummary && !planReviewContext && !livenessContinuation && !taskWatchdog && !checkboxSelection && !executionWorkspace && !recovery && !normalizePaperclipWakeIssue(payload.issue)) {return null;}return {reason: asString(payload.reason, "").trim() || null,+ recovery,issue: normalizePaperclipWakeIssue(payload.issue),checkedOutByHarness: asBoolean(payload.checkedOutByHarness, false),dependencyBlockedInteraction: asBoolean(payload.dependencyBlockedInteraction, false),@@ -1264,6 +1297,11 @@ export function stringifyPaperclipWakePayload(value: unknown): string | null {return JSON.stringify(normalized);}+export function isPaperclipRecoveryWakePayload(value: unknown): boolean {+ const normalized = normalizePaperclipWakePayload(value);+ return Boolean(normalized?.recovery || normalized?.reason === "source_scoped_recovery_action");+}+export function readPaperclipIssueWorkModeFromContext(value: unknown): string | null {const context = parseObject(value);const issue = parseObject(context.paperclipIssue);@@ -1287,6 +1325,28 @@ export function renderPaperclipWakePrompt(const hasWakeCommentBatch =normalized.comments.length > 0 || normalized.includedCount > 0 || normalized.requestedCount > 0;const executionStage = normalized.executionStage;+ const recovery = normalized.recovery;+ const recoveryScoped = Boolean(recovery || normalized.reason === "source_scoped_recovery_action");+ const originalAssigneeLabel = recovery?.originalAssignee?.name ??+ recovery?.originalAssignee?.id ??+ "the original assignee";+ const recoveryInstruction = (() => {+ switch (recovery?.cause) {+ case "process_lost":+ return `Your previous run on this issue was lost (${recovery.failureSummary ?? "no failure summary available"}). Try again — resume from durable progress; don't redo completed steps.`;+ case "successful_run_missing_state":+ case "successful_run_missing_issue_disposition":+ return "Your run completed but left no final disposition. Post a comment summarizing the state and set the correct disposition (`done` / `in_review` / `blocked` / `in_progress` with a live path). Do not start new work.";+ case "provider_quota":+ return "Verify or create the wait-recovery monitor for the provider quota reset, then stop. Do not take over the task.";+ case "codex_output_inactivity_monitor":+ return "Your run was killed by the output-inactivity monitor, likely during a long quiet build/test phase. Go again from durable progress.";+ case "workspace_validation_failed":+ return `Recover/fix the workspace (worktree, branch, workspace link), then hand the issue back to ${originalAssigneeLabel} for the actual work. Do not do the deliverable work.`;+ default:+ return `Fix the underlying problem (auth, config, adapter, budget…) so the task can run again, then hand it back to ${originalAssigneeLabel}. You DO NOT do the work. Doing the deliverable yourself requires an explicit escalation note explaining why no assignee path works.`;+ }+ })();const principalLabel = (principal: PaperclipWakeExecutionPrincipal | null) => {if (!principal || !principal.type) return "unknown";if (principal.type === "agent") return principal.agentId ? `agent ${principal.agentId}` : "agent";@@ -1312,12 +1372,19 @@ export function renderPaperclipWakePrompt(}};- const executionContractLines = includeExecutionContract+ const executionContractLines = recoveryScoped? [- "Execution contract: take concrete action in this heartbeat when the issue is actionable; do not stop at a plan unless planning was requested. Leave durable progress and then give the issue a clear final disposition before ending the heartbeat: `done`, `in_review` with a real reviewer/approval/interaction path, `blocked` with first-class blockers or a named unblock owner/action, delegated follow-up issues with blockers, or `in_progress` only when a live continuation path exists. Use child issues for long or parallel delegated work instead of polling. Comments, documents, screenshots, work products, and `Remaining` bullets are evidence, not valid liveness paths by themselves.",+ "Recovery contract: your job is to RECOVER this task, not to do the work. Do not produce the deliverable yourself.",+ `Cause-specific instruction: ${recoveryInstruction}`,+ `Fallback preference order: (1) send back to ${originalAssigneeLabel} with a retry instruction; (2) fix the runtime/adapter/workspace problem, then send it back; (3) reassign to another agent with the right specialty; (4) convert to an explicit manual-review state for the board.`,"",]- : [];+ : includeExecutionContract+ ? [+ "Execution contract: take concrete action in this heartbeat when the issue is actionable; do not stop at a plan unless planning was requested. Leave durable progress and then give the issue a clear final disposition before ending the heartbeat: `done`, `in_review` with a real reviewer/approval/interaction path, `blocked` with first-class blockers or a named unblock owner/action, delegated follow-up issues with blockers, or `in_progress` only when a live continuation path exists. Immediately before returning, verify that Paperclip records one of those dispositions; a successful process exit or final response is not sufficient. If no valid disposition is recorded, record it now and do not end the run. Use child issues for long or parallel delegated work instead of polling. Comments, documents, screenshots, work products, and `Remaining` bullets are evidence, not valid liveness paths by themselves.",+ "",+ ]+ : [];const wakeSummaryLines = [`- reason: ${normalized.reason ?? "unknown"}`,`- issue: ${normalized.issue?.identifier ?? normalized.issue?.id ?? "unknown"}${normalized.issue?.title ? ` ${normalized.issue.title}` : ""}`,@@ -1328,6 +1395,18 @@ export function renderPaperclipWakePrompt(]: []),`- fallback fetch needed: ${normalized.fallbackFetchNeeded ? "yes" : "no"}`,+ ...(recoveryScoped+ ? [+ `- recovery cause: ${recovery?.cause ?? "unknown"}`,+ `- failure summary: ${recovery?.failureSummary ?? "unknown"}`,+ `- original assignee: ${originalAssigneeLabel}`,+ `- recovery attempt: ${recovery?.attemptCount ?? "unknown"}${recovery?.maxAttempts ? `/${recovery.maxAttempts}` : ""}`,+ `- next action: ${recovery?.nextAction ?? "unknown"}`,+ ...(recovery?.routingFallbackReason+ ? [`- routing fallback: ${recovery.routingFallbackReason}`]+ : []),+ ]+ : []),];const lines = resumedSession? [diff --git a/packages/adapters/claude-local/src/server/execute.ts b/packages/adapters/claude-local/src/server/execute.tsindex 5d555478b8..3fa8da3f60 100644--- a/packages/adapters/claude-local/src/server/execute.ts+++ b/packages/adapters/claude-local/src/server/execute.ts@@ -39,6 +39,7 @@ import {refreshPaperclipWorkspaceEnvForExecution,renderTemplate,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,rewriteWorkspaceCwdEnvVarsForExecution,shapePaperclipWorkspaceEnvForExecution,stringifyPaperclipWakePayload,@@ -792,7 +793,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec: "";const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, { resumedSession: Boolean(sessionId) });const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;- const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData);+ const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(promptTemplate, templateData);const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();const taskContextNote = asString(context.paperclipTaskMarkdown, "").trim();const prompt = joinPromptSections([diff --git a/packages/adapters/codex-local/src/server/execute.ts b/packages/adapters/codex-local/src/server/execute.tsindex 36fa7ae2c1..c62eba981f 100644--- a/packages/adapters/codex-local/src/server/execute.ts+++ b/packages/adapters/codex-local/src/server/execute.ts@@ -35,6 +35,7 @@ import {resolvePaperclipDesiredSkillNames,renderTemplate,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,stringifyPaperclipWakePayload,DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,joinPromptSections,@@ -962,7 +963,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExecif (preparedRuntimeConfig.notes.length > 0) {commandNotes.unshift(...preparedRuntimeConfig.notes);}- const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData);+ const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(promptTemplate, templateData);const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();const prompt = joinPromptSections([promptInstructionsPrefix,diff --git a/packages/adapters/cursor-cloud/src/server/execute.ts b/packages/adapters/cursor-cloud/src/server/execute.tsindex d2695a9304..65c2701915 100644--- a/packages/adapters/cursor-cloud/src/server/execute.ts+++ b/packages/adapters/cursor-cloud/src/server/execute.ts@@ -19,6 +19,7 @@ import {parseObject,readPaperclipIssueWorkModeFromContext,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,renderTemplate,stringifyPaperclipWakePayload,} from "@paperclipai/adapter-utils/server-utils";@@ -395,7 +396,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec? renderTemplate(bootstrapPromptTemplate, templateData).trim(): "";const renderedPrompt =- canReuseSession && wakePrompt.length > 0+ (canReuseSession && wakePrompt.length > 0) || isPaperclipRecoveryWakePayload(context.paperclipWake)? "": renderTemplate(promptTemplate, templateData).trim();const paperclipEnvNote = renderPaperclipEnvNote(remoteEnv);diff --git a/packages/adapters/cursor-local/src/server/execute.ts b/packages/adapters/cursor-local/src/server/execute.tsindex 65d43b9f95..b2b5cac742 100644--- a/packages/adapters/cursor-local/src/server/execute.ts+++ b/packages/adapters/cursor-local/src/server/execute.ts@@ -40,6 +40,7 @@ import {removeMaintainerOnlySkillSymlinks,renderTemplate,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,stringifyPaperclipWakePayload,DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,joinPromptSections,@@ -559,7 +560,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec: "";const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, { resumedSession: Boolean(sessionId) });const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;- const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData);+ const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(promptTemplate, templateData);const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();const paperclipEnvNote = renderPaperclipEnvNote(env);const prompt = joinPromptSections([diff --git a/packages/adapters/gemini-local/src/server/execute.ts b/packages/adapters/gemini-local/src/server/execute.tsindex 530b545aa3..c2302445d8 100644--- a/packages/adapters/gemini-local/src/server/execute.ts+++ b/packages/adapters/gemini-local/src/server/execute.ts@@ -43,6 +43,7 @@ import {parseObject,renderTemplate,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,stringifyPaperclipWakePayload,DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,runChildProcess,@@ -546,7 +547,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec: "";const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, { resumedSession: Boolean(sessionId) });const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;- const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData);+ const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(promptTemplate, templateData);const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();const paperclipEnvNote = renderPaperclipEnvNote(env);const apiAccessNote = renderApiAccessNote(env);diff --git a/packages/adapters/grok-local/src/server/execute.ts b/packages/adapters/grok-local/src/server/execute.tsindex ecd17cb561..4622c3de6e 100644--- a/packages/adapters/grok-local/src/server/execute.ts+++ b/packages/adapters/grok-local/src/server/execute.ts@@ -33,6 +33,7 @@ import {readPaperclipRuntimeSkillEntries,renderTemplate,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,resolvePaperclipDesiredSkillNames,stringifyPaperclipWakePayload,refreshPaperclipWorkspaceEnvForExecution,@@ -412,7 +413,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec};const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, { resumedSession: Boolean(sessionId) });const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;- const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData);+ const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(promptTemplate, templateData);const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();const paperclipEnvNote = renderPaperclipEnvNote(env);const apiAccessNote = renderApiAccessNote(env);diff --git a/packages/adapters/hermes/src/gateway/server/execute.ts b/packages/adapters/hermes/src/gateway/server/execute.tsindex 9ec76e0965..ae60c1e338 100644--- a/packages/adapters/hermes/src/gateway/server/execute.ts+++ b/packages/adapters/hermes/src/gateway/server/execute.ts@@ -9,6 +9,7 @@ import {parseObject,readPaperclipIssueWorkModeFromContext,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,stringifyPaperclipWakePayload,} from "@paperclipai/adapter-utils/server-utils";import {@@ -277,12 +278,16 @@ function buildInput(ctx: AdapterExecutionContext, paperclipApiUrl: string | null...(paperclipApiUrl ? [`- Paperclip API URL: ${paperclipApiUrl}`] : []),...(issueWorkMode ? [`- Issue work mode: ${issueWorkMode}`] : []),"",- "Execution contract:",- "- Take concrete action in this run when the task is actionable.",- "- Do not stop at a plan unless the issue asks for planning only.",- "- Leave durable progress and update the issue to a clear final disposition.",- "- Use X-Paperclip-Run-Id on mutating Paperclip API requests when a Paperclip API key is available.",- "",+ ...(isPaperclipRecoveryWakePayload(ctx.context.paperclipWake)+ ? []+ : [+ "Execution contract:",+ "- Take concrete action in this run when the task is actionable.",+ "- Do not stop at a plan unless the issue asks for planning only.",+ "- Leave durable progress and update the issue to a clear final disposition.",+ "- Use X-Paperclip-Run-Id on mutating Paperclip API requests when a Paperclip API key is available.",+ "",+ ]),wakePrompt,...(sessionHandoff ? ["", sessionHandoff] : []),...(taskMarkdown ? ["", taskMarkdown] : []),diff --git a/packages/adapters/hermes/src/server/execute.ts b/packages/adapters/hermes/src/server/execute.tsindex 0a0f76ff84..fd4c7d03bd 100644--- a/packages/adapters/hermes/src/server/execute.ts+++ b/packages/adapters/hermes/src/server/execute.ts@@ -36,6 +36,7 @@ import {joinPromptSections,renderPaperclipWakePrompt,stringifyPaperclipWakePayload,+ isPaperclipRecoveryWakePayload,} from "@paperclipai/adapter-utils/server-utils";import {@@ -191,7 +192,9 @@ export function buildPrompt(paperclipRunIdEnv: "PAPERCLIP_RUN_ID",};- const rendered = renderTemplate(renderConditionalSections(template, vars), vars);+ const rendered = isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(renderConditionalSections(template, vars), vars);return joinPromptSections([wakePrompt,sessionHandoffMarkdown,diff --git a/packages/adapters/opencode-local/src/server/execute.ts b/packages/adapters/opencode-local/src/server/execute.tsindex a85d8530c6..4f05a6611f 100644--- a/packages/adapters/opencode-local/src/server/execute.ts+++ b/packages/adapters/opencode-local/src/server/execute.ts@@ -37,6 +37,7 @@ import {refreshPaperclipWorkspaceEnvForExecution,renderTemplate,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,stringifyPaperclipWakePayload,DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,runChildProcess,@@ -545,7 +546,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec: "";const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, { resumedSession: Boolean(sessionId) });const shouldUseResumeDeltaPrompt = Boolean(sessionId) && wakePrompt.length > 0;- const renderedPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData);+ const renderedPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(promptTemplate, templateData);const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();const prompt = joinPromptSections([instructionsPrefix,diff --git a/packages/adapters/pi-local/src/server/execute.ts b/packages/adapters/pi-local/src/server/execute.tsindex 43fac2beba..cf1eb672c6 100644--- a/packages/adapters/pi-local/src/server/execute.ts+++ b/packages/adapters/pi-local/src/server/execute.ts@@ -41,6 +41,7 @@ import {removeMaintainerOnlySkillSymlinks,renderTemplate,renderPaperclipWakePrompt,+ isPaperclipRecoveryWakePayload,stringifyPaperclipWakePayload,DEFAULT_PAPERCLIP_AGENT_PROMPT_TEMPLATE,runChildProcess,@@ -606,7 +607,9 @@ export async function execute(ctx: AdapterExecutionContext): Promise<AdapterExec: "";const wakePrompt = renderPaperclipWakePrompt(context.paperclipWake, { resumedSession: canResumeSession });const shouldUseResumeDeltaPrompt = canResumeSession && wakePrompt.length > 0;- const renderedHeartbeatPrompt = shouldUseResumeDeltaPrompt ? "" : renderTemplate(promptTemplate, templateData);+ const renderedHeartbeatPrompt = shouldUseResumeDeltaPrompt || isPaperclipRecoveryWakePayload(context.paperclipWake)+ ? ""+ : renderTemplate(promptTemplate, templateData);const sessionHandoffNote = asString(context.paperclipSessionHandoffMarkdown, "").trim();const userPrompt = joinPromptSections([renderedBootstrapPrompt,diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.tsindex e62ce48c0b..fc3db2e9ec 100644--- a/packages/shared/src/constants.ts+++ b/packages/shared/src/constants.ts@@ -322,6 +322,8 @@ export type IssueRecoveryActionOwnerType = (typeof ISSUE_RECOVERY_ACTION_OWNER_Texport const ISSUE_RECOVERY_ACTION_OUTCOMES = ["restored",+ "handed_back",+ "owner_completed","delegated","false_positive","blocked",diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.tsindex 78ca629263..015a9c1196 100644--- a/server/src/__tests__/heartbeat-process-recovery.test.ts+++ b/server/src/__tests__/heartbeat-process-recovery.test.ts@@ -1005,6 +1005,8 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {});if (input.cause === "execution_review_participant_recovery") {expect(action.nextAction).toContain("failed review participant path");+ } else if (input.cause === "process_lost") {+ expect(action.nextAction).toContain("Retry the original assignee from durable progress");} else {expect(action.nextAction).toContain(input.kind === "missing_disposition" ? "valid issue disposition" : "Restore a live execution path",@@ -1374,6 +1376,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {runId: secondAttempt.runId,previousStatus: "in_progress",retryReason: "issue_continuation_needed",+ cause: "process_lost",});});@@ -4428,6 +4431,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {runId,previousStatus: "todo",retryReason: "assignment_recovery",+ cause: "process_lost",});expect(JSON.stringify(recoveryAction.evidence)).not.toContain("sk-test-recovery-secret");@@ -4827,6 +4831,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {runId,previousStatus: "in_progress",retryReason: "issue_continuation_needed",+ cause: "process_lost",});const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId));diff --git a/server/src/__tests__/heartbeat-workspace-branch-containment.test.ts b/server/src/__tests__/heartbeat-workspace-branch-containment.test.tsindex c9e9418d21..8e1b942679 100644--- a/server/src/__tests__/heartbeat-workspace-branch-containment.test.ts+++ b/server/src/__tests__/heartbeat-workspace-branch-containment.test.ts@@ -693,8 +693,9 @@ async function expectContainedWorkspaceBranchFailure(input: {}),nextAction: expect.stringContaining("choose a new execution workspace"),wakePolicy: expect.objectContaining({- type: "manual_repair_required",- reason: "workspace_validation_failed",+ type: "wake_owner",+ reason: "source_scoped_recovery_action",+ ownerAgentId: expect.any(String),}),});diff --git a/server/src/__tests__/issue-recovery-actions.test.ts b/server/src/__tests__/issue-recovery-actions.test.tsindex 136c9efb92..94948961aa 100644--- a/server/src/__tests__/issue-recovery-actions.test.ts+++ b/server/src/__tests__/issue-recovery-actions.test.ts@@ -23,6 +23,7 @@ import {} from "./helpers/embedded-postgres.js";import { errorHandler } from "../middleware/index.js";import { issueRoutes } from "../routes/issues.js";+import { buildPaperclipWakePayload } from "../services/heartbeat.js";import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";import { recoveryService } from "../services/recovery/service.js";@@ -217,14 +218,17 @@ describeEmbeddedPostgres("issue recovery actions", () => {});}- function createApp(actor: any = { type: "board", source: "local_implicit" }) {+ function createApp(+ actor: any = { type: "board", source: "local_implicit" },+ opts: Parameters<typeof issueRoutes>[2] = {},+ ) {const app = express();app.use(express.json());app.use((req, _res, next) => {(req as any).actor = actor;next();});- app.use("/api", issueRoutes(db, {} as any));+ app.use("/api", issueRoutes(db, {} as any, opts));app.use(errorHandler);return app;}@@ -324,6 +328,126 @@ describeEmbeddedPostgres("issue recovery actions", () => {});});+ it.each([+ ["process_lost", undefined, "coder"],+ ["adapter_failed", "successful_run_missing_state", "coder"],+ ["codex_output_inactivity_monitor", undefined, "coder"],+ ["workspace_validation_failed", "workspace_validation_failed", "manager"],+ ["adapter_failed", undefined, "manager"],+ ] as const)(+ "routes %s recovery through the cause-keyed playbook",+ async (errorCode, explicitCause, expectedOwner) => {+ const { managerId, coderId, sourceIssue } = await seedCompany();+ const enqueueWakeup = vi.fn(async () => null);+ const recovery = recoveryService(db, { enqueueWakeup });+ const latestRun = {+ id: randomUUID(),+ agentId: coderId,+ status: errorCode === "adapter_failed" && explicitCause === "successful_run_missing_state"+ ? "succeeded"+ : "failed",+ error: `${errorCode} failure`,+ errorCode,+ contextSnapshot: { retryReason: "issue_continuation_needed" },+ livenessState: "needs_followup",+ resultJson: errorCode === "workspace_validation_failed"+ ? { workspaceValidation: { reason: "missing_workspace", fingerprint: "workspace:test" } }+ : null,+ } as const;++ await recovery.escalateStrandedAssignedIssue({+ issue: sourceIssue,+ previousStatus: "in_progress",+ latestRun,+ ...(explicitCause ? { recoveryCause: explicitCause } : {}),+ });++ const expectedOwnerId = expectedOwner === "coder" ? coderId : managerId;+ const [action] = await db+ .select()+ .from(issueRecoveryActions)+ .where(eq(issueRecoveryActions.sourceIssueId, sourceIssue.id));+ expect(action?.ownerAgentId).toBe(expectedOwnerId);+ expect(enqueueWakeup).toHaveBeenCalledWith(+ expectedOwnerId,+ expect.objectContaining({+ reason: "source_scoped_recovery_action",+ payload: expect.objectContaining({+ recoveryCause: explicitCause ?? (errorCode === "adapter_failed" ? "stranded_assigned_issue" : errorCode),+ }),+ }),+ );+ },+ );++ it("creates a quota wait-recovery monitor without enqueueing a takeover wake", async () => {+ const { companyId, coderId, sourceIssue } = await seedCompany();+ const runId = randomUUID();+ await seedHeartbeatRun({ companyId, agentId: coderId, runId, issueId: sourceIssue.id, status: "failed" });+ const enqueueWakeup = vi.fn(async () => null);+ const recovery = recoveryService(db, { enqueueWakeup });+ const retryAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();++ await recovery.escalateStrandedAssignedIssue({+ issue: sourceIssue,+ previousStatus: "in_progress",+ latestRun: {+ id: runId,+ agentId: coderId,+ status: "failed",+ error: "provider usage limit exceeded",+ errorCode: "adapter_failed",+ contextSnapshot: { retryReason: "issue_continuation_needed" },+ livenessState: "needs_followup",+ resultJson: { errorFamily: "provider_quota", providerQuotaRetryNotBefore: retryAt },+ },+ });++ expect(enqueueWakeup).not.toHaveBeenCalled();+ const [action] = await db+ .select()+ .from(issueRecoveryActions)+ .where(eq(issueRecoveryActions.sourceIssueId, sourceIssue.id));+ expect(action).toMatchObject({+ cause: "provider_quota",+ ownerType: "system",+ ownerAgentId: null,+ returnOwnerAgentId: coderId,+ wakePolicy: expect.objectContaining({ type: "monitor_only" }),+ monitorPolicy: expect.objectContaining({ type: "wait_recovery", retryAgentId: coderId }),+ });+ const scheduled = await db+ .select()+ .from(heartbeatRuns)+ .where(eq(heartbeatRuns.status, "scheduled_retry"));+ expect(scheduled).toHaveLength(1);+ expect(scheduled[0]).toMatchObject({+ agentId: coderId,+ scheduledRetryReason: "provider_quota_recovery",+ });+ expect(scheduled[0]?.contextSnapshot).toMatchObject({+ issueId: sourceIssue.id,+ wakeReason: "provider_quota_recovery",+ });+ expect(scheduled[0]?.contextSnapshot).not.toHaveProperty("recoveryActionId");+ expect(scheduled[0]?.contextSnapshot).not.toHaveProperty("recoveryCause");+ const wakePayload = await buildPaperclipWakePayload({+ db,+ companyId,+ contextSnapshot: scheduled[0]?.contextSnapshot as Record<string, unknown>,+ });+ expect(wakePayload?.reason).toBe("provider_quota_recovery");+ expect(wakePayload?.recovery).toBeNull();+ const [updatedIssue] = await db+ .select()+ .from(issues)+ .where(eq(issues.id, sourceIssue.id));+ expect(updatedIssue).toMatchObject({+ status: "blocked",+ assigneeAgentId: coderId,+ });+ });+it("reuses the same source-scoped action when latest run IDs change while the cause stays the same", async () => {const { companyId, managerId, coderId, sourceIssue } = await seedCompany();const enqueueWakeup = vi.fn(async () => null);@@ -464,14 +588,22 @@ describeEmbeddedPostgres("issue recovery actions", () => {}),nextAction: expect.stringContaining("git worktree branch incoherence"),wakePolicy: expect.objectContaining({- type: "manual_repair_required",- reason: "workspace_validation_failed",+ type: "wake_owner",+ reason: "source_scoped_recovery_action",+ ownerAgentId: expect.any(String),}),});const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, sourceIssue.id));expect(comments.filter((comment) => comment.body.includes(`Recovery action: \`${actionRows[0]?.id}\``))).toHaveLength(1);- expect(enqueueWakeup).not.toHaveBeenCalled();+ expect(enqueueWakeup).toHaveBeenCalledTimes(2);+ expect(enqueueWakeup).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ reason: "source_scoped_recovery_action",+ payload: expect.objectContaining({ recoveryCause: "workspace_validation_failed" }),+ }),+ );});it("keeps the source issue blocked when source-scoped wakeup is claimed synchronously", async () => {@@ -613,6 +745,49 @@ describeEmbeddedPostgres("issue recovery actions", () => {expect(list.body.actions).toHaveLength(1);});+ it("projects recovery action metadata into the structured wake payload", async () => {+ const { companyId, managerId, coderId, sourceIssueId } = await seedCompany();+ const action = await issueRecoveryActionService(db).upsertSourceScoped({+ companyId,+ sourceIssueId,+ kind: "workspace_validation",+ ownerType: "agent",+ ownerAgentId: managerId,+ previousOwnerAgentId: coderId,+ returnOwnerAgentId: coderId,+ cause: "workspace_validation_failed",+ fingerprint: "workspace:wake-payload",+ evidence: {+ failureSummary: "Worktree branch does not match the pinned branch.",+ routingFallbackReason: null,+ },+ nextAction: "Repair the worktree, then return the issue to the coder.",+ wakePolicy: { type: "wake_owner" },+ maxAttempts: 3,+ });++ const payload = await buildPaperclipWakePayload({+ db,+ companyId,+ contextSnapshot: {+ issueId: sourceIssueId,+ wakeReason: "source_scoped_recovery_action",+ recoveryActionId: action.id,+ recoveryCause: action.cause,+ },+ });++ expect(payload?.recovery).toEqual({+ cause: "workspace_validation_failed",+ failureSummary: "Worktree branch does not match the pinned branch.",+ originalAssignee: { id: coderId, name: "Coder" },+ attemptCount: 1,+ maxAttempts: 3,+ nextAction: "Repair the worktree, then return the issue to the coder.",+ routingFallbackReason: null,+ });+ });+it("resolves an active recovery action and removes it from active projections", async () => {const { companyId, managerId, sourceIssueId } = await seedCompany();const recoveryActionSvc = issueRecoveryActionService(db);@@ -648,7 +823,7 @@ describeEmbeddedPostgres("issue recovery actions", () => {expect(resolved.body.recoveryAction).toMatchObject({id: action.id,status: "resolved",- outcome: "restored",+ outcome: "owner_completed",resolutionNote: "Operator confirmed the source issue is complete.",});expect(resolved.body.recoveryAction.resolvedAt).toBeTruthy();@@ -666,6 +841,99 @@ describeEmbeddedPostgres("issue recovery actions", () => {);});+ it("hands restored work back to the recorded return owner and records the outcome", async () => {+ const { companyId, managerId, coderId, sourceIssueId } = await seedCompany();+ await db+ .update(issues)+ .set({ status: "blocked", assigneeAgentId: managerId })+ .where(eq(issues.id, sourceIssueId));+ const recoveryActionSvc = issueRecoveryActionService(db);+ const action = await recoveryActionSvc.upsertSourceScoped({+ companyId,+ sourceIssueId,+ kind: "workspace_validation",+ ownerType: "agent",+ ownerAgentId: managerId,+ previousOwnerAgentId: coderId,+ returnOwnerAgentId: coderId,+ cause: "workspace_validation_failed",+ fingerprint: "workspace:fingerprint",+ evidence: { latestRunId: "run-1" },+ nextAction: "Repair the workspace and hand the issue back.",+ wakePolicy: { type: "wake_owner" },+ });++ const enqueueRecoveryActionWakeup = vi.fn(async () => null);+ const resolved = await request(createApp(undefined, {+ recoveryActionEnqueueWakeup: enqueueRecoveryActionWakeup,+ }))+ .post(`/api/issues/${sourceIssueId}/recovery-actions/resolve`)+ .send({+ actionId: action.id,+ outcome: "restored",+ sourceIssueStatus: "todo",+ resolutionNote: "Workspace repaired.",+ })+ .expect(200);++ expect(resolved.body.issue).toMatchObject({+ id: sourceIssueId,+ status: "todo",+ assigneeAgentId: coderId,+ activeRecoveryAction: null,+ });+ expect(resolved.body.recoveryAction).toMatchObject({+ id: action.id,+ status: "resolved",+ outcome: "handed_back",+ });+ expect(enqueueRecoveryActionWakeup).toHaveBeenCalledWith(+ coderId,+ expect.objectContaining({+ reason: "issue_recovery_action_restored",+ payload: expect.objectContaining({ issueId: sourceIssueId, recoveryActionId: action.id }),+ }),+ );+ });++ it("does not enqueue a restored wake when todo status and assignee are unchanged", async () => {+ const { companyId, managerId, coderId, sourceIssueId } = await seedCompany();+ await db+ .update(issues)+ .set({ status: "todo", assigneeAgentId: coderId })+ .where(eq(issues.id, sourceIssueId));+ const recoveryActionSvc = issueRecoveryActionService(db);+ const action = await recoveryActionSvc.upsertSourceScoped({+ companyId,+ sourceIssueId,+ kind: "workspace_validation",+ ownerType: "agent",+ ownerAgentId: managerId,+ previousOwnerAgentId: coderId,+ returnOwnerAgentId: coderId,+ cause: "workspace_validation_failed",+ fingerprint: "workspace:already-restored",+ evidence: { latestRunId: "run-1" },+ nextAction: "Confirm the workspace remains healthy.",+ wakePolicy: { type: "wake_owner" },+ });++ const enqueueRecoveryActionWakeup = vi.fn(async () => null);+ await request(createApp(undefined, {+ recoveryActionEnqueueWakeup: enqueueRecoveryActionWakeup,+ }))+ .post(`/api/issues/${sourceIssueId}/recovery-actions/resolve`)+ .send({+ actionId: action.id,+ outcome: "restored",+ sourceIssueStatus: "todo",+ resolutionNote: "Workspace was already restored.",+ })+ .expect(200);++ expect(enqueueRecoveryActionWakeup).not.toHaveBeenCalled();+ });+it("resolves an active recovery action by returning the source issue to todo", async () => {const { companyId, managerId, sourceIssueId } = await seedCompany();await db@@ -1049,7 +1317,7 @@ describeEmbeddedPostgres("issue recovery actions", () => {expect(resolved.body.recoveryAction).toMatchObject({id: action.id,status: "resolved",- outcome: "restored",+ outcome: "owner_completed",});});diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.tsindex a7bf135606..85d93c7467 100644--- a/server/src/routes/issues.ts+++ b/server/src/routes/issues.ts@@ -2551,6 +2551,10 @@ export function issueRoutes(searchRateLimiter?: CompanySearchRateLimiter;pluginWorkerManager?: PluginWorkerManager;taskWatchdogEnqueueWakeup?: TaskWatchdogServiceDeps["enqueueWakeup"] | null;+ recoveryActionEnqueueWakeup?: (+ agentId: string,+ options: Parameters<ReturnType<typeof heartbeatService>["wakeup"]>[1],+ ) => ReturnType<ReturnType<typeof heartbeatService>["wakeup"]>;issueListDiagnostics?: IssueListDiagnostics;approveToolActionRequest?: (input: {companyId: string;@@ -2567,6 +2571,7 @@ export function issueRoutes(const heartbeat = heartbeatService(db, {pluginWorkerManager: opts.pluginWorkerManager,});+ const enqueueRecoveryActionWakeup = opts.recoveryActionEnqueueWakeup ?? heartbeat.wakeup;const feedback = feedbackService(db);const companiesSvc = companyService(db);let searchSvc = opts.searchService ?? null;@@ -5513,6 +5518,14 @@ export function issueRoutes(}const actor = getActorInfo(req);+ const handBackAgentId = outcome === "restored" && sourceIssueStatus === "todo"+ ? activeRecoveryAction?.returnOwnerAgentId ?? null+ : null;+ const recordedOutcome = handBackAgentId+ ? "handed_back"+ : outcome === "restored" && sourceIssueStatus === "done"+ ? "owner_completed"+ : outcome;const updateFields = sourceIssueStatus ? { status: sourceIssueStatus } : {};await assertAgentInReviewReviewPath({existing,@@ -5547,6 +5560,7 @@ export function issueRoutes(id,{status: sourceIssueStatus,+ ...(handBackAgentId ? { assigneeAgentId: handBackAgentId } : {}),actorAgentId: actor.agentId ?? null,actorUserId: actor.actorType === "user" ? actor.actorId : null,},@@ -5562,7 +5576,7 @@ export function issueRoutes(sourceIssueId: existing.id,actionId: actionId ?? null,status: actionStatus,- outcome,+ outcome: recordedOutcome,resolutionNote: resolutionNote ?? null,},tx,@@ -5617,32 +5631,36 @@ export function issueRoutes(if (sourceIssueStatus === "todo" &&- existing.status !== result.issue.status &&- result.issue.assigneeAgentId+ result.issue.assigneeAgentId &&+ (existing.status !== result.issue.status ||+ existing.assigneeAgentId !== result.issue.assigneeAgentId)) {- void heartbeat.wakeup(result.issue.assigneeAgentId, {- source: "automation",- triggerDetail: "system",- reason: "issue_recovery_action_restored",- payload: {- issueId: result.issue.id,- recoveryActionId: result.recoveryAction.id,- mutation: "recovery_action_resolution",- },- requestedByActorType: actor.actorType,- requestedByActorId: actor.actorId,- contextSnapshot: {- issueId: result.issue.id,- taskId: result.issue.id,- wakeReason: "issue_recovery_action_restored",- source: "issue.recovery_action_resolution",- recoveryActionId: result.recoveryAction.id,- },- }).catch((err) =>+ try {+ await enqueueRecoveryActionWakeup(result.issue.assigneeAgentId, {+ source: "automation",+ triggerDetail: "system",+ reason: "issue_recovery_action_restored",+ payload: {+ issueId: result.issue.id,+ recoveryActionId: result.recoveryAction.id,+ mutation: "recovery_action_resolution",+ },+ requestedByActorType: actor.actorType,+ requestedByActorId: actor.actorId,+ contextSnapshot: {+ issueId: result.issue.id,+ taskId: result.issue.id,+ wakeReason: "issue_recovery_action_restored",+ source: "issue.recovery_action_resolution",+ recoveryActionId: result.recoveryAction.id,+ },+ });+ } catch (err) {logger.warn({ err, issueId: result.issue.id, agentId: result.issue.assigneeAgentId },"failed to wake agent after recovery action restored issue",- ));+ );+ }}res.json({diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.tsindex a284d3a145..58941ca95f 100644--- a/server/src/services/heartbeat.ts+++ b/server/src/services/heartbeat.ts@@ -4554,9 +4554,45 @@ export async function buildPaperclipWakePayload(input: {}): null;const payloadTruncated = truncated || planReviewContext?.truncated === true;+ const recoveryActionId = readNonEmptyString(input.contextSnapshot.recoveryActionId);+ const recoveryCause = readNonEmptyString(input.contextSnapshot.recoveryCause);+ const recoveryAction = recoveryActionId+ ? await input.db+ .select()+ .from(issueRecoveryActions)+ .where(and(+ eq(issueRecoveryActions.id, recoveryActionId),+ eq(issueRecoveryActions.companyId, input.companyId),+ ))+ .then((rows) => rows[0] ?? null)+ : null;+ const recoveryEvidence = parseObject(recoveryAction?.evidence);+ const originalAssigneeId = recoveryAction?.returnOwnerAgentId ?? recoveryAction?.previousOwnerAgentId ?? null;+ const originalAssignee = originalAssigneeId+ ? await input.db+ .select({ id: agents.id, name: agents.name })+ .from(agents)+ .where(and(eq(agents.id, originalAssigneeId), eq(agents.companyId, input.companyId)))+ .then((rows) => rows[0] ?? null)+ : null;return {reason: readNonEmptyString(input.contextSnapshot.wakeReason),+ recovery: recoveryAction || recoveryCause+ ? {+ cause: recoveryAction?.cause ?? recoveryCause,+ failureSummary: readNonEmptyString(recoveryEvidence.failureSummary),+ originalAssignee: originalAssignee+ ? { id: originalAssignee.id, name: originalAssignee.name }+ : originalAssigneeId+ ? { id: originalAssigneeId, name: null }+ : null,+ attemptCount: recoveryAction?.attemptCount ?? null,+ maxAttempts: recoveryAction?.maxAttempts ?? null,+ nextAction: recoveryAction?.nextAction ?? null,+ routingFallbackReason: readNonEmptyString(recoveryEvidence.routingFallbackReason),+ }+ : null,issue: issueSummary? {id: issueSummary.id,@@ -7987,7 +8023,7 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {}).where(eq(heartbeatRuns.id, run.id));}- const handoffRun = await enqueueWakeup(run.agentId, {+ const handoffRun = await enqueueWakeup(decision.targetAgentId, {source: "automation",triggerDetail: "system",reason: FINISH_SUCCESSFUL_RUN_HANDOFF_REASON,diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.tsindex 6ad4b557de..90b24a6a2f 100644--- a/server/src/services/recovery/service.ts+++ b/server/src/services/recovery/service.ts@@ -140,6 +140,9 @@ type SuccessfulLatestIssueRun = NonNullable<LatestIssueRun> & { status: "succeedtype StrandedRecoveryCause =| "stranded_assigned_issue"+ | "process_lost"+ | "provider_quota"+ | "codex_output_inactivity_monitor"| "workspace_validation_failed"| "configuration_incomplete"| "execution_review_participant_recovery"@@ -155,6 +158,33 @@ type SuccessfulRunHandoffRecoveryEvidence = {maxHandoffAttempts: number;};+const PROVIDER_QUOTA_RECOVERY_DEFAULT_BACKOFF_MS = 15 * 60 * 1000;++function readRecoveryRunErrorFamily(latestRun: LatestIssueRun) {+ const result = parseObject(latestRun?.resultJson);+ return readNonEmptyString(result.errorFamily);+}++function isProviderQuotaRecovery(latestRun: LatestIssueRun) {+ if (latestRun?.errorCode === "provider_quota") return true;+ if (readRecoveryRunErrorFamily(latestRun) === "provider_quota") return true;+ if (latestRun?.errorCode !== "adapter_failed") return false;+ return /(?:usage|rate|quota) limit|quota (?:exceeded|reset)|try again after/i.test(latestRun.error ?? "");+}++function resolveStrandedRecoveryCause(+ latestRun: LatestIssueRun,+ explicitCause?: StrandedRecoveryCause,+): StrandedRecoveryCause {+ if (explicitCause) return explicitCause;+ if (isProviderQuotaRecovery(latestRun)) return "provider_quota";+ if (latestRun?.errorCode === "process_lost") return "process_lost";+ if (latestRun?.errorCode === "codex_output_inactivity_monitor") {+ return "codex_output_inactivity_monitor";+ }+ return "stranded_assigned_issue";+}+function readWorkspaceValidationPayload(latestRun: LatestIssueRun): Record<string, unknown> | null {const payload = parseObject(parseObject(latestRun?.resultJson).workspaceValidation);return Object.keys(payload).length > 0 ? payload : null;@@ -2296,6 +2326,67 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })return null;}+ async function resolveInvokableRecoveryAgentId(+ issue: typeof issues.$inferSelect,+ agentId: string | null | undefined,+ ) {+ if (!agentId) return null;+ const candidate = await getAgent(agentId);+ if (!candidate || candidate.companyId !== issue.companyId) return null;+ const budgetBlock = await budgets.getInvocationBlock(issue.companyId, candidate.id, {+ issueId: issue.id,+ projectId: issue.projectId,+ });+ return (await isAgentInvokable(candidate)) && !budgetBlock ? candidate.id : null;+ }++ async function resolveStrandedRecoveryRouting(input: {+ issue: typeof issues.$inferSelect;+ latestRun: LatestIssueRun;+ recoveryCause: StrandedRecoveryCause;+ preferredOwnerAgentId?: string | null;+ }) {+ const originalAgentId = input.latestRun?.agentId ?? input.issue.assigneeAgentId;+ const returnOwnerAgentId = input.issue.assigneeAgentId ?? originalAgentId;+ const routeToOriginal = input.recoveryCause === "process_lost" ||+ input.recoveryCause === SUCCESSFUL_RUN_MISSING_STATE_REASON ||+ input.recoveryCause === "codex_output_inactivity_monitor";+ if (input.recoveryCause === "provider_quota") {+ const retryAgentId = await resolveInvokableRecoveryAgentId(input.issue, originalAgentId);+ if (!retryAgentId) {+ return {+ ownerAgentId: await resolveStrandedIssueRecoveryOwnerAgentId(input.issue),+ returnOwnerAgentId: originalAgentId,+ routingFallbackReason: "The original assignee is not invokable; quota recovery fell through to the manager ladder.",+ };+ }+ return {+ ownerAgentId: null,+ returnOwnerAgentId: retryAgentId,+ routingFallbackReason: null,+ };+ }+ if (routeToOriginal) {+ const ownerAgentId = await resolveInvokableRecoveryAgentId(input.issue, originalAgentId);+ if (ownerAgentId) {+ return { ownerAgentId, returnOwnerAgentId: originalAgentId, routingFallbackReason: null };+ }+ return {+ ownerAgentId: await resolveStrandedIssueRecoveryOwnerAgentId(input.issue),+ returnOwnerAgentId: originalAgentId,+ routingFallbackReason: "The original assignee is not invokable; recovery fell through to the manager ladder.",+ };+ }+ return {+ ownerAgentId: await resolveStrandedIssueRecoveryOwnerAgentId(+ input.issue,+ input.preferredOwnerAgentId,+ ),+ returnOwnerAgentId,+ routingFallbackReason: null,+ };+ }+function buildStrandedIssueRecoveryDescription(input: {issue: typeof issues.$inferSelect;latestRun: LatestIssueRun;@@ -2542,35 +2633,48 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })recoveryOwnerAgentId?: string | null;successfulRunHandoffEvidence?: SuccessfulRunHandoffRecoveryEvidence | null;}) {- const recoveryCause = input.recoveryCause ?? "stranded_assigned_issue";- const ownerAgentId = await resolveStrandedIssueRecoveryOwnerAgentId(- input.issue,- input.recoveryOwnerAgentId,- );+ const recoveryCause = resolveStrandedRecoveryCause(input.latestRun, input.recoveryCause);+ const routing = await resolveStrandedRecoveryRouting({+ issue: input.issue,+ latestRun: input.latestRun,+ recoveryCause,+ preferredOwnerAgentId: input.recoveryOwnerAgentId,+ });+ const ownerAgentId = routing.ownerAgentId;const now = new Date();const action = await recoveryActionsSvc.upsertSourceScoped({companyId: input.issue.companyId,sourceIssueId: input.issue.id,kind: strandedRecoveryActionKind(recoveryCause),- ownerType: ownerAgentId ? "agent" : "board",+ ownerType: recoveryCause === "provider_quota" && !ownerAgentId ? "system" : ownerAgentId ? "agent" : "board",ownerAgentId,previousOwnerAgentId: input.issue.assigneeAgentId,- returnOwnerAgentId: input.issue.assigneeAgentId,+ returnOwnerAgentId: routing.returnOwnerAgentId,cause: recoveryCause,fingerprint: strandedRecoveryActionFingerprint({issue: input.issue,recoveryCause,latestRun: input.latestRun,}),- evidence: buildStrandedRecoveryActionEvidence({- issue: input.issue,- latestRun: input.latestRun,- previousStatus: input.previousStatus,- recoveryCause,- successfulRunHandoffEvidence: input.successfulRunHandoffEvidence,- }),+ evidence: {+ ...buildStrandedRecoveryActionEvidence({+ issue: input.issue,+ latestRun: input.latestRun,+ previousStatus: input.previousStatus,+ recoveryCause,+ successfulRunHandoffEvidence: input.successfulRunHandoffEvidence,+ }),+ failureSummary: summarizeRunFailureForIssueComment(input.latestRun)?.trim() ?? null,+ routingFallbackReason: routing.routingFallbackReason,+ },nextAction: recoveryCause === SUCCESSFUL_RUN_MISSING_STATE_REASON? "Choose and record a valid issue disposition without copying transcript content."+ : recoveryCause === "process_lost"+ ? "Retry the original assignee from durable progress without redoing completed steps."+ : recoveryCause === "provider_quota"+ ? "Wait for provider quota recovery, then retry the original assignee; do not wake a takeover owner."+ : recoveryCause === "codex_output_inactivity_monitor"+ ? "Retry the same agent from durable progress after the output-inactivity termination.": recoveryCause === "workspace_validation_failed"? readWorkspaceValidationPayload(input.latestRun)?.reason === "git_worktree_branch_incoherence"? "Repair the source issue git worktree branch incoherence, or choose a new execution workspace, before resuming adapter execution."@@ -2580,7 +2684,12 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup }): recoveryCause === "execution_review_participant_recovery"? "Repair the failed review participant path, restore the source issue to in_review with a live reviewer, or record an intentional manual resolution.": "Restore a live execution path, fix the runtime/adapter failure, or record an intentional manual resolution.",- wakePolicy: recoveryCause === "workspace_validation_failed" || recoveryCause === "configuration_incomplete"+ wakePolicy: recoveryCause === "provider_quota" && !ownerAgentId+ ? {+ type: "monitor_only",+ reason: recoveryCause,+ }+ : recoveryCause === "configuration_incomplete"? {type: "manual_repair_required",reason: recoveryCause,@@ -2596,7 +2705,9 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })type: "board_escalation",reason: "no_invokable_recovery_owner",},- monitorPolicy: null,+ monitorPolicy: recoveryCause === "provider_quota" && !ownerAgentId+ ? { type: "wait_recovery", retryAgentId: routing.returnOwnerAgentId }+ : null,maxAttempts: null,lastAttemptAt: now,});@@ -2610,7 +2721,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })latestRun: LatestIssueRun;recoveryCause: StrandedRecoveryCause;}) {- if (input.recoveryCause === "workspace_validation_failed") return;+ if (input.recoveryCause === "provider_quota" && !input.action.ownerAgentId) return;if (input.recoveryCause === "configuration_incomplete") return;if (!input.action.ownerAgentId) return;await deps.enqueueWakeup(input.action.ownerAgentId, {@@ -2641,6 +2752,111 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })});}+ function readProviderQuotaRetryAt(latestRun: LatestIssueRun, now: Date) {+ const result = parseObject(latestRun?.resultJson);+ const context = parseObject(latestRun?.contextSnapshot);+ const raw = result.providerQuotaRetryNotBefore ??+ result.retryNotBefore ??+ result.transientRetryNotBefore ??+ context.providerQuotaRetryNotBefore ??+ context.transientRetryNotBefore;+ if (typeof raw === "string" || typeof raw === "number" || raw instanceof Date) {+ const parsed = new Date(raw);+ if (!Number.isNaN(parsed.getTime()) && parsed.getTime() > now.getTime()) return parsed;+ }+ return new Date(now.getTime() + PROVIDER_QUOTA_RECOVERY_DEFAULT_BACKOFF_MS);+ }++ async function ensureProviderQuotaWaitRecoveryMonitor(input: {+ issue: typeof issues.$inferSelect;+ latestRun: LatestIssueRun;+ actionId: string;+ agentId: string;+ }) {+ const existing = await db+ .select()+ .from(heartbeatRuns)+ .where(and(+ eq(heartbeatRuns.companyId, input.issue.companyId),+ eq(heartbeatRuns.agentId, input.agentId),+ eq(heartbeatRuns.status, "scheduled_retry"),+ sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${input.issue.id}`,+ ))+ .orderBy(desc(heartbeatRuns.scheduledRetryAt))+ .limit(1)+ .then((rows) => rows[0] ?? null);+ if (existing) return existing;++ const now = new Date();+ const retryAt = readProviderQuotaRetryAt(input.latestRun, now);+ return db.transaction(async (tx) => {+ const wakeup = await tx+ .insert(agentWakeupRequests)+ .values({+ companyId: input.issue.companyId,+ agentId: input.agentId,+ source: "automation",+ triggerDetail: "system",+ reason: "provider_quota_recovery",+ payload: withRecoveryModelProfileHint({+ issueId: input.issue.id,+ retryOfRunId: input.latestRun?.id ?? null,+ retryReason: "provider_quota_recovery",+ providerQuotaRetryNotBefore: retryAt.toISOString(),+ }, "normal_model"),+ status: "queued",+ requestedByActorType: "system",+ requestedByActorId: null,+ idempotencyKey: `provider_quota_recovery:${input.issue.id}:${retryAt.toISOString()}`,+ updatedAt: now,+ })+ .returning()+ .then((rows) => rows[0]!);+ const scheduledRun = await tx+ .insert(heartbeatRuns)+ .values({+ companyId: input.issue.companyId,+ agentId: input.agentId,+ invocationSource: "automation",+ triggerDetail: "system",+ status: "scheduled_retry",+ wakeupRequestId: wakeup.id,+ retryOfRunId: input.latestRun?.id ?? null,+ scheduledRetryAt: retryAt,+ scheduledRetryAttempt: 1,+ scheduledRetryReason: "provider_quota_recovery",+ contextSnapshot: withRecoveryModelProfileHint({+ issueId: input.issue.id,+ taskId: input.issue.id,+ wakeReason: "provider_quota_recovery",+ retryReason: "provider_quota_recovery",+ providerQuotaRetryNotBefore: retryAt.toISOString(),+ }, "normal_model"),+ updatedAt: now,+ })+ .returning()+ .then((rows) => rows[0]!);+ await tx+ .update(agentWakeupRequests)+ .set({ runId: scheduledRun.id, updatedAt: now })+ .where(eq(agentWakeupRequests.id, wakeup.id));+ await tx+ .update(issueRecoveryActions)+ .set({+ monitorPolicy: {+ type: "wait_recovery",+ retryAgentId: input.agentId,+ scheduledRunId: scheduledRun.id,+ retryAt: retryAt.toISOString(),+ },+ timeoutAt: retryAt,+ updatedAt: now,+ })+ .where(eq(issueRecoveryActions.id, input.actionId));+ return scheduledRun;+ });+ }+function buildRecoveryIssueInPlaceEscalationComment(input: {issue: typeof issues.$inferSelect;previousStatus: StrandedPreviousStatus;@@ -2818,7 +3034,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })});}- const recoveryCause = input.recoveryCause ?? "stranded_assigned_issue";+ const recoveryCause = resolveStrandedRecoveryCause(input.latestRun, input.recoveryCause);const recoveryAction = await ensureSourceScopedStrandedRecoveryAction({issue: input.issue,previousStatus: input.previousStatus,@@ -2827,6 +3043,17 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })recoveryOwnerAgentId: input.recoveryOwnerAgentId,successfulRunHandoffEvidence: input.successfulRunHandoffEvidence,});+ const isProviderQuotaWait = recoveryCause === "provider_quota" &&+ !recoveryAction.ownerAgentId &&+ Boolean(recoveryAction.returnOwnerAgentId);+ if (isProviderQuotaWait && recoveryAction.returnOwnerAgentId) {+ await ensureProviderQuotaWaitRecoveryMonitor({+ issue: input.issue,+ latestRun: input.latestRun,+ actionId: recoveryAction.id,+ agentId: recoveryAction.returnOwnerAgentId,+ });+ }const blockerIds = await existingUnresolvedBlockerIssueIds(input.issue.companyId, input.issue.id);const updated = await issuesSvc.update(input.issue.id, {status: "blocked",@@ -2834,6 +3061,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })assigneeAgentId: recoveryAction.ownerAgentId ?? input.issue.assigneeAgentId,});if (!updated) return null;+ if (isProviderQuotaWait) return updated;const prefix = await getCompanyIssuePrefix(input.issue.companyId);const recoveryOwner = recoveryAction.ownerAgentId ? await getAgent(recoveryAction.ownerAgentId) : null;diff --git a/server/src/services/recovery/successful-run-handoff.test.ts b/server/src/services/recovery/successful-run-handoff.test.tsindex 25a99cbb21..0f26913d22 100644--- a/server/src/services/recovery/successful-run-handoff.test.ts+++ b/server/src/services/recovery/successful-run-handoff.test.ts@@ -62,11 +62,12 @@ function decide(overrides: Partial<Parameters<typeof decideSuccessfulRunHandoff>}describe("successful run handoff decision", () => {- it("queues one corrective handoff wake for a successful progress run without a visible next action", () => {+ it("queues one status-only corrective wake to the original agent when a successful run has no disposition", () => {const decision = decide();expect(decision.kind).toBe("enqueue");if (decision.kind !== "enqueue") return;+ expect(decision.targetAgentId).toBe(run.agentId);expect(decision.idempotencyKey).toBe("finish_successful_run_handoff:issue-1:run-1:1");expect(decision.payload).toMatchObject({issueId: "issue-1",@@ -91,6 +92,9 @@ describe("successful run handoff decision", () => {allowDocumentUpdates: false,resumeRequiresNormalModel: true,});+ expect(decision.instruction).toContain(+ "This is a status-only retry to the original agent. Record a disposition; do not start new work.",+ );expect(decision.instruction).toContain("Resolve the missing disposition before creating or revising any new artifacts");expect(decision.instruction).toContain("Choose **exactly one** outcome");expect(decision.instruction).toContain("record an explicit continuation path");diff --git a/server/src/services/recovery/successful-run-handoff.ts b/server/src/services/recovery/successful-run-handoff.tsindex b0f0b94dbd..a7ce9ee155 100644--- a/server/src/services/recovery/successful-run-handoff.ts+++ b/server/src/services/recovery/successful-run-handoff.ts@@ -77,6 +77,7 @@ export function noticeMetadataReferencesRecoveryAction(export type SuccessfulRunHandoffDecision =| {kind: "enqueue";+ targetAgentId: string;idempotencyKey: string;payload: Record<string, unknown>;contextSnapshot: Record<string, unknown>;@@ -319,6 +320,8 @@ export function buildSuccessfulRunHandoffInstruction(input: {return [`Your previous run on ${issueLabel} succeeded, but the issue is still in \`in_progress\` and Paperclip cannot identify a valid issue disposition.`,"",+ "This is a status-only retry to the original agent. Record a disposition; do not start new work.",+ "","Resolve the missing disposition before creating or revising any new artifacts. Choose **exactly one** outcome and perform the matching Paperclip action:","","**Is the issue finished?**",@@ -423,6 +426,7 @@ export function decideSuccessfulRunHandoff(input: {return {kind: "enqueue",+ targetAgentId: run.agentId,idempotencyKey: buildFinishSuccessfulRunHandoffIdempotencyKey({issueId: issue.id,sourceRunId: run.id,diff --git a/ui/src/components/IssueRecoveryActionCard.tsx b/ui/src/components/IssueRecoveryActionCard.tsxindex da9197221c..e4d9e0e60d 100644--- a/ui/src/components/IssueRecoveryActionCard.tsx+++ b/ui/src/components/IssueRecoveryActionCard.tsx@@ -200,6 +200,8 @@ const STATE_TONE: Record<RecoveryCardCardState, {const OUTCOME_LABEL: Record<IssueRecoveryActionOutcome, string> = {restored: "restored",+ handed_back: "handed back to original owner",+ owner_completed: "completed by recovery owner",delegated: "delegated to follow-up",false_positive: "false positive",blocked: "blocked",