From a38bcb9bc5bc5cca8e44661751ca2a6f49351dd8 Mon Sep 17 00:00:00 2001 From: cryppadotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 11 Nov 2026 14:30:38 +0000 Subject: [PATCH] fix(queue): retain chat bindings on resolved card continuations Co-Authored-By: Paperclip --- doc/execution-semantics.md | 9 ++++ ...-reviewed-chat-binding.integration.test.ts | 49 +++++++++++++++++++ .../adapters/chat-wake-delivered.test.ts | 31 ++++++++++-- .../modules/wake-queue/adapters/postgres.ts | 6 ++- .../modules/wake-queue/application/ports.ts | 2 + .../wake-queue/application/use-cases.ts | 7 +++ 6 files changed, 98 insertions(+), 6 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 1812b0839ae..33aea94a672 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -5653,6 +5653,15 @@ rollback requires a server that reads this envelope and the supported settled warm journal, including its PRP v2 idle goal suffix. Earlier local-only readers and readers lacking that suffix handling remain outside that rollback contract. +### Resolved cards queued behind chat runs + +A resolved card is an independent continuation. Its saved chat message IDs +remain authorization bindings even if a prior run received those messages. +Queue promotion retains live, same-task message bindings for that continuation; +deleted and self-authored messages still drop out. The new run must pass current +chat authorization. Ordinary message-only wakes whose input was consumed remain +cancelled and cannot start another turn. + ### Stop a failed native retry A failed native run can still own a scheduled same-run bootstrap retry. The 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 b385ced0352..4dc32cbdd09 100644 --- a/server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts +++ b/server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts @@ -3,6 +3,7 @@ import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, + agentWakeupRequests, companies, createDb, heartbeatRuns, @@ -42,6 +43,9 @@ import { commitNativeStatusDecision } from "../services/native-runtime/status-de import { NATIVE_STATUS_ARBITER_POLICY_VERSION } from "../services/native-runtime/status-arbiter.js"; import { recoveryService } from "../services/recovery/service.js"; +import { createReleaseIssueExecution } from "../modules/wake-queue/application/use-cases.js"; +import { createPostgresWakeQueueAdapter } from "../modules/wake-queue/adapters/postgres.js"; + describe.each(["slack", "discord"] as const)("reviewed %s execution binding", (provider) => { let temporary: Awaited>; let db: ReturnType; @@ -315,6 +319,51 @@ describe.each(["slack", "discord"] as const)("reviewed %s execution binding", (p .toBe("pending"); }, 30_000); + it("attests a resolved card after queue promotion even when its chat message was already delivered", async () => { + const [previousIssue] = await db.select().from(issues).where(eq(issues.id, issueId)); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, runId)); + const finishingRunId = randomUUID(), wakeId = randomUUID(); + const continuation = { ...context, interactionId, interactionKind: "request_confirmation", interactionStatus: "accepted" }; + await db.insert(heartbeatRuns).values({ id: finishingRunId, companyId, agentId, + status: "succeeded", invocationSource: "assignment", triggerDetail: "system", + startedAt: new Date(Date.now() + 1_000), finishedAt: new Date(Date.now() + 2_000), + contextSnapshot: context }); + await db.update(issues).set({ executionRunId: finishingRunId }).where(eq(issues.id, issueId)); + await db.update(issueThreadInteractions).set({ status: "accepted", resolvedByUserId: userId, resolvedAt: new Date() }) + .where(eq(issueThreadInteractions.id, interactionId)); + await db.insert(agentWakeupRequests).values({ id: wakeId, companyId, agentId, + source: "automation", triggerDetail: "system", reason: "issue_commented", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: userId, + payload: { issueId, mutation: "interaction", interactionId, interactionKind: "request_confirmation", + interactionStatus: "accepted", wakeCommentId: commentId, _paperclipWakeContext: continuation } }); + try { + const release = createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { + resolveResponsibleUserId: async () => userId, + getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }), + resolveSessionBeforeForWakeup: async () => null, + }), recovery: {} as never, + }); + const released = await release({ companyId, runId: finishingRunId, now: new Date() }); + const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)); + expect(released.outcome.kind, JSON.stringify(wake)).toBe("promoted"); + const [promoted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, wake.runId!)); + await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, promoted.id)); + const authorize = () => attestReviewedExternalChatRun({ db, companyId, agentId, issueId, + runId: promoted.id, contextSnapshot: promoted.contextSnapshot! }); + await expect(authorize()).resolves.toBe(true); + await db.update(chatEndpointResources).set({ enabled: false }).where(eq(chatEndpointResources.id, resourceId)); + await expect(authorize()).resolves.toBe(false); + await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, promoted.id)); + } finally { + await db.update(chatEndpointResources).set({ enabled: true }).where(eq(chatEndpointResources.id, resourceId)); + await db.update(issueThreadInteractions).set({ status: "pending", resolvedByUserId: null, resolvedAt: null }) + .where(eq(issueThreadInteractions.id, interactionId)); + await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId)); + await restoreSuccessorLock(previousIssue); + } + }); + it("attests existing execution ownership while preserving real pending governance and checkout state", async () => { const [before] = await db .select() diff --git a/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts b/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts index 438adc20b17..dca587afee6 100644 --- a/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts +++ b/server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts @@ -36,7 +36,7 @@ describe.skipIf(!support.supported)("release of a saved chat wake whose message await database?.cleanup(); }); - async function seed(delivered: boolean) { + async function seed(delivered: boolean, interaction = false) { const [issue] = await db.insert(issues).values({ companyId, title: "Review a pull request", status: "in_review", assigneeAgentId: agentId }).returning(); const [message] = await db.insert(issueComments).values({ companyId, issueId: issue.id, authorUserId: "chat-user", @@ -50,7 +50,7 @@ describe.skipIf(!support.supported)("release of a saved chat wake whose message await db.update(issues).set({ executionRunId: run.id, executionLockedAt: new Date() }).where(eq(issues.id, issue.id)); const context = { issueId: issue.id, taskId: issue.id, source: "chat:github", wakeReason: "External chat message received", wakeSource: "assignment", chatConversationId: randomUUID(), commentId: message.id, wakeCommentId: message.id, - wakeCommentIds: [message.id] }; + wakeCommentIds: [message.id], ...(interaction ? { interactionId: randomUUID(), interactionKind: "request_confirmation", interactionStatus: "accepted" } : {}) }; const wakeId = randomUUID(); const { idempotencyKey } = createDurableChatWakeupRequest({ id: wakeId, companyId, agentId, issueId: issue.id, commentId: message.id, requestedByActorType: "user", requestedByActorId: "chat-user", requestedAt: new Date(), @@ -58,9 +58,9 @@ describe.skipIf(!support.supported)("release of a saved chat wake whose message const [wake] = await db.insert(agentWakeupRequests).values({ id: wakeId, idempotencyKey, companyId, agentId, source: "assignment", triggerDetail: "system", reason: "External chat message received", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: "chat-user", - payload: { issueId: issue.id, mutation: "chat_message_received", wakeCommentId: message.id, _paperclipWakeContext: context }, + payload: { issueId: issue.id, mutation: interaction ? "interaction" : "chat_message_received", wakeCommentId: message.id, _paperclipWakeContext: context }, }).returning(); - return { issue, run, wake }; + return { issue, run, wake, message }; } function release(unexpected: () => never) { @@ -83,6 +83,29 @@ describe.skipIf(!support.supported)("release of a saved chat wake whose message rows.filter(row => row.contextSnapshot?.issueId === saved.payload?.issueId && row.id !== run.id))).toEqual([]); }); + it("keeps the live chat binding when an accepted card queues behind a run that received its message", async () => { + const { issue, run, wake, message } = await seed(true, true); + const release = createReleaseIssueExecution({ + issueLock: createPostgresWakeQueueAdapter(db, { + resolveResponsibleUserId: async () => "chat-user", + getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }), + resolveSessionBeforeForWakeup: async () => null, + } as never), + recovery: {} as never, + }); + const result = await release({ companyId, runId: run.id, now: new Date() }); + expect(result.outcome.kind).toBe("promoted"); + const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)); + const [promoted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, saved.runId!)); + expect(promoted.contextSnapshot).toMatchObject({ + issueId: issue.id, source: "chat:github", + interactionStatus: "accepted", + wakeCommentIds: [message.id], + }); + const [locked] = await db.select().from(issues).where(eq(issues.id, issue.id)); + expect(locked.executionRunId).toBe(promoted.id); + }); + it("does not report a delivered chat message as not started", async () => { const { wake } = await seed(true); const action = { id: wake.id, companyId, kind: "inbound_wakeup", conversationId: randomUUID(), deliveryId: randomUUID(), diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 07c2bb718c2..52c183ec686 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -316,7 +316,7 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru } }, - async getQueuedCommentLiveness({ companyId, issueId, wakeAgentId, finishingRunId, finishingRunAgentId, queuedCommentIds }) { + async getQueuedCommentLiveness({ companyId, issueId, wakeAgentId, finishingRunId, finishingRunAgentId, queuedCommentIds, retainDeliveredCommentBindings }) { // Malformed ids (for example an 8-char short form written into a wake // payload) can never match a comment row, but Postgres rejects the whole // `inArray` statement on the first invalid uuid and blocks every queued @@ -338,7 +338,9 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru // received would deliver them twice and can reopen finished work. const delivered = await deliveredQueuedCommentIds(tx, { companyId, issueId, agentId: wakeAgentId, commentIds: liveAndUnauthored }); - const liveNonSelfCommentIds = liveAndUnauthored.filter(commentId => !delivered.has(commentId)); + const liveNonSelfCommentIds = retainDeliveredCommentBindings + ? liveAndUnauthored + : liveAndUnauthored.filter(commentId => !delivered.has(commentId)); const containedSelfAuthoredComment = rows.some( (row) => targetsFinishingRunAgent && !row.deletedAt && row.createdByRunId === finishingRunId, ); diff --git a/server/src/modules/wake-queue/application/ports.ts b/server/src/modules/wake-queue/application/ports.ts index 7cf3cc4e7c8..209cd02d87a 100644 --- a/server/src/modules/wake-queue/application/ports.ts +++ b/server/src/modules/wake-queue/application/ports.ts @@ -125,6 +125,8 @@ export interface WakeQueueTransaction { finishingRunId: string; finishingRunAgentId: string; queuedCommentIds: string[]; + /** A resolved card still needs its live message edge for chat authorization. */ + retainDeliveredCommentBindings?: boolean; }): Promise<{ liveNonSelfCommentIds: string[]; containedSelfAuthoredComment: boolean; diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index 3a74a7aa2f9..1319490b2b9 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -240,6 +240,13 @@ async function runReleaseDrain( finishingRunId: run.id, finishingRunAgentId: run.agentId, queuedCommentIds: candidate.queuedCommentIds, + // The message is an authorization edge for this independent response, + // even when an earlier turn already received the message itself. + ...(candidate.payload.mutation === "interaction" && + readNonEmptyString(candidate.deferredContextSeed.interactionId) && + ["accepted", "answered", "rejected"].includes(String(candidate.deferredContextSeed.interactionStatus)) && + readNonEmptyString(candidate.deferredContextSeed.source)?.startsWith("chat:") + ? { retainDeliveredCommentBindings: true } : {}), }); } // A length mismatch is the only way the lists can differ: the adapter derives `liveNonSelfCommentIds` with `.filter`, so it is always a subsequence of `queuedCommentIds`.