From 93111b175ba07ff4f1536f2bbc574c8edf8ad549 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:37:46 -0600 Subject: [PATCH] fix(wake-queue): keep the child-completion reason when a person's comment merges into its held wake (#21918) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The wake queue holds new work for a task while an agent run is active. A later wake for the same task merges into the held wake > - A parent task must not finish while a finished child's result is still waiting for a parent turn. The finish gate checks for this pending child result > - The gate finds the held child-completion wake by its context wake reason > - When a person's comment merged into that held wake, the merge replaced the wake reason with `issue_commented`. The gate then did not see the pending child result > - This pull request keeps every merged reason in the held wake and makes the gate read that list > - The benefit is that a merge keeps the meaning of both wakes: the comment is delivered, and the pending child result still blocks a premature finish ## Linked Issues or Issue Description Refs #21914 **What happened?** A restart test held a child-completion wake behind a running parent run. A person then posted a comment. The comment wake merged into the held wake. After the merge, the held wake's `_paperclipWakeContext.wakeReason` was `issue_commented`, not `issue_children_completed`. `hasPendingNativeChildCompletion` matches held wakes by that field only. So the finish gate could no longer see the pending child result. **Expected behavior** The held wake keeps both reasons. The finish gate still sees the pending child result. The next run still receives the person's comment. **Steps to reproduce** 1. Start a run for a parent task. 2. Hold a child-completion wake behind the run. 3. Post a person's comment on the parent. The comment wake merges into the held wake. 4. Call `hasPendingNativeChildCompletion` for the running parent run. It returns `false`. **Paperclip version or commit** `master` at 20b0d4e5a5. **Relevant logs or output** The suspected effect on finish timing in the test run was not real. The two rejected finish calls failed for other reasons: the first had invalid tool input (a missing `remainingWork` field) and the second had no accessible deliverable. Both happened before the comment merge. Also, the run had already read the finished child before the merge, so the gate was already satisfied for that child. The gap is real for a run that has not read the child yet. The new test proves it. ## What Changed - `admitWakeBehindIssueExecution` records `wakeReasons` in the merged held-wake context when two different reasons merge. `wakeReason` keeps the latest reason, as before, so comment delivery and person-wake handling do not change. - New `withMergedWakeReasons` helper in the wake-queue domain context module. - `hasPendingNativeChildCompletion` matches a held wake when `wakeReason` is `issue_children_completed` or when `wakeReasons` contains it. - New embedded-Postgres test in `heartbeat-comment-wake-batching.test.ts`: a child-completion wake is held behind a running parent, then a person's comment merges in. The gate still sees the pending child result, and the next run receives the comment. ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-comment-wake-batching.test.ts src/__tests__/native-child-task-read-routes.test.ts src/modules/wake-queue` passes (16 files, 400 tests). This includes both #21914 reopen tests. - `cd server && npx vitest run src/__tests__/native-status-arbiter-corpus.test.ts src/services/workspace-recovery-admission.test.ts src/__tests__/heartbeat-held-comment-wake.test.ts` passes (343 tests). - `cd server && npx tsc --noEmit` passes. - Red check: with only the source change reverted, the new test fails. The merged context has no `wakeReasons`, and the gate check after the merge fails with `expected false to be true`. - `pnpm verify` exits 2 (an opaque setup dependency). Required CI supplies broad coverage. ## Risks - Low risk. The change adds one context key on merged held wakes and widens one gate query. `wakeReason` does not change. - A wider gate can hold a parent finish for a child result that a merge used to hide. That is the intended behavior. The gate still ignores a child result that the run already read. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use (shell, file edits, test runs). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../heartbeat-comment-wake-batching.test.ts | 45 ++++++++++++++++++- .../wake-queue/application/use-cases.ts | 14 +++--- .../src/modules/wake-queue/domain/context.ts | 17 +++++++ .../native-child-completion-delivery.ts | 3 +- 4 files changed, 72 insertions(+), 7 deletions(-) diff --git a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts index 77a75841b62..2e7c35ed30b 100644 --- a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts +++ b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts @@ -33,6 +33,7 @@ import { } from "@paperclipai/db"; import { runningProcesses } from "../adapters/index.js"; import { heartbeatService } from "../services/heartbeat.ts"; +import { hasPendingNativeChildCompletion } from "../services/native-runtime/native-child-completion-delivery.js"; import { issueThreadInteractionService } from "../services/issue-thread-interactions.js"; import { isRetiredExternalChatQuestionSource, questionResponseDeliveryService } from "../services/question-response-delivery.js"; import { SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY } from "../services/recovery/index.ts"; @@ -2207,7 +2208,8 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { const childCompletionIntentId = randomUUID(); const childCompletionWakeId = randomUUID(); - const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed" }; + const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed", + nativeChildCompletionDecisionId: randomUUID(), completedChildIssueId: randomUUID() }; await db.insert(agentWakeupRequests).values([{ id: childCompletionIntentId, companyId, agentId, source: "automation", triggerDetail: "system", reason: "issue_children_completed", status: "coalesced", @@ -2239,6 +2241,47 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { }, 90_000); } + it("keeps a pending child completion visible to the finish gate after a person's comment merges into its deferred wake", async () => { + const gateway = await createControlledGatewayServer(); + try { + const { companyId, agentId, issueId, heartbeat, firstRun, childCompletionWakeId } = + await startAssignedRunWithDeferredChildCompletion({ gateway, title: "Child result and person comment behind a run" }); + const pendingChildCompletion = () => hasPendingNativeChildCompletion(db, { + companyId, issueId, agentId, runId: firstRun.id, sourceIntentId: null, + }); + expect(await pendingChildCompletion()).toBe(true); + + const personComment = await db.insert(issueComments) + .values(wakeUserCommentRow(companyId, issueId, "user-1", "Also include the summary table")) + .returning().then((rows) => rows[0]); + expect(await heartbeat.wakeup(agentId, { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: personComment.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: personComment.id, wakeCommentId: personComment.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + })).toBeNull(); + const merged = await selectDeferredWakeForAgent(companyId, agentId); + expect(merged?.id).toBe(childCompletionWakeId); + expect((merged?.payload as Record)._paperclipWakeContext).toMatchObject({ + wakeReason: "issue_commented", + wakeReasons: ["issue_children_completed", "issue_commented"], + wakeCommentIds: [personComment.id], + }); + expect(await pendingChildCompletion()).toBe(true); + + await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id); + await waitFor(() => gateway.getAgentPayloads().length >= 2, 90_000); + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)) + .orderBy(asc(heartbeatRuns.createdAt)); + expect(runs[1]?.wakeupRequestId).toBe(childCompletionWakeId); + expect(String(gateway.getAgentPayloads()[1]?.message ?? "")).toContain("Also include the summary table"); + } finally { + gateway.releaseFirstWait(); + await gateway.close(); + } + }, 120_000); + it("reopens a finished task when a person's comment joined a deferred system wake during the run", async () => { const gateway = await createControlledGatewayServer(); try { diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index f10416fe4c8..fb6a31c0f61 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -1,5 +1,5 @@ import { readWakeChatConversationId } from "../../run-dispatch/index.js"; -import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun } from "../domain/context.js"; +import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun, withMergedWakeReasons } from "../domain/context.js"; import { QUEUED_MESSAGES_DELIVERED_REASON } from "../domain/policy.js"; import { decideQueuedCommentAction, @@ -979,12 +979,16 @@ export function createAdmitWakeBehindIssueExecution(deps: { }); if (existingDeferred && !existingDeferred.payload?.interactionId && !existingDeferred.deferredContext.interactionId) { - const mergedDeferredContext = deps.helpers.mergeCoalescedContextSnapshot( + const mergedDeferredContext = withMergedWakeReasons( + deps.helpers.mergeCoalescedContextSnapshot( + existingDeferred.deferredContext, + input.contextSnapshot, + { + preserveExistingInteractionContinuation: true, + }, + ), existingDeferred.deferredContext, input.contextSnapshot, - { - preserveExistingInteractionContinuation: true, - }, ); const mergedPayload = { ...existingDeferred.payload, diff --git a/server/src/modules/wake-queue/domain/context.ts b/server/src/modules/wake-queue/domain/context.ts index 7ce30654bdd..51a7c6e91f7 100644 --- a/server/src/modules/wake-queue/domain/context.ts +++ b/server/src/modules/wake-queue/domain/context.ts @@ -89,6 +89,23 @@ export function wakeMustNotJoinActiveRun( wakeChatConversationsConflict(activeRunContext, wakeContext); } +const WAKE_REASONS_KEY = "wakeReasons"; + +function readWakeReasons(context: unknown): string[] { + const parsed = parseObject(context); + const listed = Array.isArray(parsed[WAKE_REASONS_KEY]) ? parsed[WAKE_REASONS_KEY] as unknown[] : []; + return [...listed, parsed.wakeReason].flatMap((value) => readNonEmptyString(value) ?? []); +} + +export function withMergedWakeReasons( + merged: Record, + existing: unknown, + incoming: unknown, +): Record { + const reasons = [...new Set([...readWakeReasons(existing), ...readWakeReasons(incoming)])]; + return reasons.length > 1 ? { ...merged, [WAKE_REASONS_KEY]: reasons } : merged; +} + export function hasRetainedExternalChatRetry(context: unknown): boolean { const active = parseObject(context); const activeSource = readNonEmptyString(active.source); diff --git a/server/src/services/native-runtime/native-child-completion-delivery.ts b/server/src/services/native-runtime/native-child-completion-delivery.ts index 0ae2377fd5c..7d367edfa59 100644 --- a/server/src/services/native-runtime/native-child-completion-delivery.ts +++ b/server/src/services/native-runtime/native-child-completion-delivery.ts @@ -34,7 +34,8 @@ export async function hasPendingNativeChildCompletion(db: Db, input: NativeChild eq(agentWakeupRequests.agentId, input.agentId), or(eq(agentWakeupRequests.reason, "issue_children_completed"), and(eq(agentWakeupRequests.reason, "issue_execution_deferred"), - sql`${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'wakeReason' = 'issue_children_completed'`)), + sql`(${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'wakeReason' = 'issue_children_completed' + or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'wakeReasons' @> '["issue_children_completed"]'::jsonb)`)), eq(agentWakeupRequests.requestedByActorType, "system"), or(eq(agentWakeupRequests.requestedByActorId, "native-status-committer"), sql`${agentWakeupRequests.requestedByActorId} like 'native-status-wake-dispatch:%'`),