diff --git a/server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts b/server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts index 4dc32cbdd09..1b538d99577 100644 --- a/server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts +++ b/server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts @@ -25,6 +25,7 @@ import { nativeRunResults, statusDecisionEffects, workAssessments, + type Db, } from "@paperclipai/db"; import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils"; import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; @@ -38,6 +39,7 @@ import { } from "../services/native-runtime/chat-attachment-reuse.js"; import * as chatAttachmentReuse from "../services/native-runtime/chat-attachment-reuse.js"; import { decideIssueReviewPathRecovery } from "../services/recovery/review-path-recovery.js"; +import { materializeNativeToolReceiptLimitContinuation } from "../services/native-runtime/native-provider-capacity-retry.js"; import { resolveCurrentWakeCommentsBinding } from "../services/native-runtime/current-wake-comments.js"; import { commitNativeStatusDecision } from "../services/native-runtime/status-decision-committer.js"; import { NATIVE_STATUS_ARBITER_POLICY_VERSION } from "../services/native-runtime/status-arbiter.js"; @@ -451,6 +453,50 @@ describe.each(["slack", "discord"] as const)("reviewed %s execution binding", (p }); }); + it("reauthorizes a fresh-session continuation of a reviewed chat turn from its message batch", async () => { + const failedRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: failedRunId, companyId, agentId, status: "cancelled", runtimeMode: "native", nativeIssueId: issueId, + invocationSource: "assignment", triggerDetail: "system", + contextSnapshot: { ...context, paperclipHarnessCheckedOut: false, paperclipExternalChatExecutionBound: true }, + }); + const retryId = await db.transaction((tx) => materializeNativeToolReceiptLimitContinuation({ + tx: tx as unknown as Db, companyId, issueId, runId: failedRunId, agentId, + })); + const [retry] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retryId)); + const retryContext = retry!.contextSnapshot as Record; + const [before] = await db.select().from(issues).where(eq(issues.id, issueId)); + await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, retryId)); + await db.update(issues).set({ executionRunId: retryId }).where(eq(issues.id, issueId)); + const reasons: string[] = []; + const attestRetry = () => attestReviewedExternalChatRun({ + db, ...binding, runId: retryId, contextSnapshot: { ...retryContext }, onDenied: (reason) => reasons.push(reason), + }); + try { + await expect(attestRetry()).resolves.toBe(true); + expect(reasons).toEqual([]); + await db.update(companyMemberships).set({ status: "suspended" }).where(eq(companyMemberships.principalId, userId)); + try { + await expect(attestRetry()).resolves.toBe(false); + expect(reasons).toEqual(["principal_denied"]); + } finally { + await db.update(companyMemberships).set({ status: "active" }).where(eq(companyMemberships.principalId, userId)); + } + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]) + .toEqual({ ...before, executionRunId: retryId, updatedAt: expect.any(Date) }); + } finally { + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retryId)); + } + expect(retryContext).toMatchObject({ source: `chat:${provider}`, wakeCommentIds: [commentId], retryOfRunId: failedRunId }); + expect(retryContext).not.toHaveProperty("paperclipHarnessCheckedOut"); + expect(retryContext).not.toHaveProperty("paperclipExternalChatExecutionBound"); + expect(decideIssueReviewPathRecovery({ + issueId, sourceRunId: retryId, assigneeAgentId: agentId, contextSnapshot: retryContext, + reviewAttention: { state: "stalled", paths: [], reason: "Review path consumed" }, existingWake: false, + })).toMatchObject({ kind: "enqueue", contextSnapshot: { wakeCommentIds: [commentId] } }); + }); + it("denies recovery after access revocation or a changed company, task, or message binding", async () => { await withReviewRecovery(async (recovery) => { await expect(attest(recovery)).resolves.toBe(true); diff --git a/server/src/services/native-runtime/fresh-session-retry-context.test.ts b/server/src/services/native-runtime/fresh-session-retry-context.test.ts new file mode 100644 index 00000000000..c7edd3f9146 --- /dev/null +++ b/server/src/services/native-runtime/fresh-session-retry-context.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { freshSessionRetryContext } from "./fresh-session-retry-context.js"; + +const consumed = { + wakeCommentId: "c2", wakeCommentIds: ["c1", "c2"], commentId: "c2", commentIds: ["c1", "c2"], latestCommentId: "c2", + explicitUserContinuation: true, resumeIntent: true, followUpRequested: true, paperclipWake: {}, paperclipWakeComment: {}, + paperclipTaskMarkdown: "task", paperclipTurnContext: {}, +}; + +describe("freshSessionRetryContext", () => { + it("drops consumed wake input from an ordinary task run", () => { + const context = freshSessionRetryContext({ issueId: "issue", source: "issue.comment", paperclipHarnessCheckedOut: true, ...consumed }); + expect(context).toEqual({ issueId: "issue", source: "issue.comment", paperclipHarnessCheckedOut: true }); + }); + + it.each(["chat:github", "chat:slack:recovery"])("keeps the admitted %s message batch without the failed run's proofs", (source) => { + const context = freshSessionRetryContext({ + issueId: "issue", source, chatConversationId: "conversation", paperclipHarnessCheckedOut: false, + paperclipExternalChatExecutionBound: true, ...consumed, + }); + expect(context).toEqual({ + issueId: "issue", source, chatConversationId: "conversation", + wakeCommentIds: ["c1", "c2"], wakeCommentId: "c2", commentId: "c2", + }); + }); + + it("does not invent a batch or keep one for sources outside the run-bound chat boundary", () => { + expect(freshSessionRetryContext({ source: "chat:github", wakeCommentId: "c1" })).toEqual({ source: "chat:github" }); + expect(freshSessionRetryContext({ source: "chat:agentmail", wakeCommentIds: ["c1"] })).toEqual({ source: "chat:agentmail" }); + expect(freshSessionRetryContext(null)).toEqual({}); + }); +}); diff --git a/server/src/services/native-runtime/fresh-session-retry-context.ts b/server/src/services/native-runtime/fresh-session-retry-context.ts new file mode 100644 index 00000000000..de2bdd2d7b6 --- /dev/null +++ b/server/src/services/native-runtime/fresh-session-retry-context.ts @@ -0,0 +1,25 @@ +import { extractWakeCommentIds } from "../../modules/run-dispatch/index.js"; +import { boundExternalChatProvider } from "./external-chat-provider.js"; + +const CONSUMED_WAKE_INPUT_KEYS = [ + "explicitUserContinuation", "wakeCommentId", "wakeCommentIds", "commentId", + "commentIds", "latestCommentId", "resumeIntent", "followUpRequested", + "paperclipWake", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact", + "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownAssignmentCompact", "paperclipTurnContext", +] as const; + +const DISPATCH_ATTESTATION_KEYS = ["paperclipHarnessCheckedOut", "paperclipExternalChatExecutionBound"] as const; + +export function freshSessionRetryContext(predecessor: Record | null | undefined) { + const context: Record = { ...predecessor }; + const chatCommentIds = boundExternalChatProvider(context.source) ? extractWakeCommentIds(context) : []; + for (const key of CONSUMED_WAKE_INPUT_KEYS) delete context[key]; + if (chatCommentIds.length === 0) return context; + for (const key of DISPATCH_ATTESTATION_KEYS) delete context[key]; + return { + ...context, + wakeCommentIds: chatCommentIds, + wakeCommentId: chatCommentIds.at(-1), + commentId: chatCommentIds.at(-1), + }; +} diff --git a/server/src/services/native-runtime/native-provider-capacity-retry.ts b/server/src/services/native-runtime/native-provider-capacity-retry.ts index 98d5db313e0..636bf4606d2 100644 --- a/server/src/services/native-runtime/native-provider-capacity-retry.ts +++ b/server/src/services/native-runtime/native-provider-capacity-retry.ts @@ -12,6 +12,7 @@ import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_HINT, NATIV import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_CONTINUATION_DELAY_MS, NATIVE_AGENT_BLOCKER_HINT, NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS, NATIVE_AGENT_BLOCKER_MESSAGE } from "./native-agent-blocker.js"; import { NativeStatusRaceError } from "./status-decision-committer.js"; +import { freshSessionRetryContext } from "./fresh-session-retry-context.js"; type NativeRetryTarget = { tx: Db; @@ -112,18 +113,8 @@ async function materializeNativeFreshSessionRetry(input: NativeRetryTarget, lane const now = new Date(); const dueAt = new Date(now.getTime() + lane.delayMs(attempt)); const retryId = randomUUID(); - const predecessorContext = { ...run.contextSnapshot }; - // Resume receipts and delivered wake input belong to the failed run. The - // new turn has ordinary task authority; history comes from retryOfRunId. - // Match the consumed-input boundary used by native safe replacements. - for (const key of [ - "explicitUserContinuation", "wakeCommentId", "wakeCommentIds", "commentId", - "commentIds", "latestCommentId", "resumeIntent", "followUpRequested", - "paperclipWake", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact", - "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownAssignmentCompact", "paperclipTurnContext", - ]) delete predecessorContext[key]; const contextSnapshot = { - ...predecessorContext, + ...freshSessionRetryContext(run.contextSnapshot), issueId: input.issueId, taskId: input.issueId, forceFreshSession: true, diff --git a/server/src/services/native-runtime/native-safe-replacement.ts b/server/src/services/native-runtime/native-safe-replacement.ts index 0ca6f833b50..bcb960876bc 100644 --- a/server/src/services/native-runtime/native-safe-replacement.ts +++ b/server/src/services/native-runtime/native-safe-replacement.ts @@ -22,6 +22,7 @@ import { } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema } from "@paperclipai/shared"; import { decideNativeReplacement, type NativeReplacementDecision } from "./native-replacement-evidence.js"; +import { freshSessionRetryContext } from "./fresh-session-retry-context.js"; import { issueService } from "../issues.js"; import { issueRecoveryActionService } from "../issue-recovery-actions.js"; import { buildExecutionContinuation } from "../execution-continuation.js"; @@ -778,17 +779,8 @@ export async function reconcileSafeNativeReplacements( } const successorRunId = randomUUID(); const dueAt = new Date(now.getTime() + 30_000); - const predecessorContext = { ...record(run.contextSnapshot) }; - // History comes from the failed source run. Consumed wake fields must - // not grant this automatic retry fresh comment/resume authority. - for (const key of [ - "explicitUserContinuation", "wakeCommentId", "wakeCommentIds", "commentId", - "commentIds", "latestCommentId", "resumeIntent", "followUpRequested", - "paperclipWake", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact", - "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownAssignmentCompact", "paperclipTurnContext", - ]) delete predecessorContext[key]; const context = { - ...predecessorContext, + ...freshSessionRetryContext(record(run.contextSnapshot)), issueId: task.id, retryOfRunId: run.id, wakeReason: NATIVE_SAFE_REPLACEMENT_REASON,