From 7636441c4619cd233cc884dee43e9e11ace5aa8e Mon Sep 17 00:00:00 2001 From: paperclipbugbot Date: Wed, 2 Dec 2026 02:26:46 -0800 Subject: [PATCH] fix(recovery): hold an agent comment wake behind a refused workspace writer hold (#23475) 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 > - A run fails setup with "The workspace still has an unfinished writer or save operation." when the task's remote workspace is still held by an earlier writer run that did not finish its save, and the hold refuses a start. > - #22103 and #23446 stopped the assigned-work sweep, the bounded retry and stranded recovery from starting runs behind such a hold. On staging, the failures are now single runs, not pairs. > - The remaining single failures come from comment wakes. An agent comments on a task (for example, an automated status note), and the route wakes the assignee. The assignee's latest run on that task already failed on the same refused hold, so the new run can only fail the same way. > - The blocker-stall wake already checks this case before it wakes a waiter. The comment wake paths do not check it. > - This pull request makes the comment wake paths skip the assignee wake for an agent-authored comment while the assignee's latest run on the task failed on that hold and the hold still refuses a start. > - The benefit is no new failed run for each automated comment on a held task. The comment stays on the task, and the existing recovery continues the task when the hold settles. ## Linked Issues or Issue Description Refs #22103 Refs #23446 Refs #21221 **What happened?** On staging, after #22103 and #23446 were deployed, two runs failed setup with the writer-pending message (`setup_failed`, before provider work). Each run was started by an agent comment on a task: one through `issue.comment`, one through `issue.comment.reopen`. Both tasks have workspaces whose writer run ended long ago with an unsaved workspace, so the hold refuses a start. In one task, the assignee's previous run had already failed setup on the same hold. No retry followed either failure, so #23446 works. But every new automated comment on such a task starts one more run that fails. **Expected behavior** An agent comment does not start a run that can only fail setup on a refused workspace hold. The comment is kept. The task continues through stranded-work recovery and the released-writer pass when the hold settles. A person's comment still wakes the assignee. **Steps to reproduce** 1. Bind an in-progress task to an execution workspace whose remote writer is an ended run with dirty, unsaved state, so the hold refuses a start. 2. Fail the assignee's latest run on the task with `setup_failed` and the writer-pending message. 3. As another agent, post a comment on the task (`POST /api/issues/:id/comments`, or `PATCH /api/issues/:id` with `comment`). 4. Before this change, the route wakes the assignee, and the new run fails setup on the same hold. **Paperclip version or commit** `master` at 5a956b724. **Deployment mode** Hosted (cloud sandbox workspaces). ## What Changed - `server/src/services/remote-workspace-writer-hold.ts`: add `agentTaskWorkspaceHoldRefusesStart(db, { companyId, issueId, agentId })`. It reads the agent's latest run on the task (indexed on company, `contextSnapshot.issueId` and `createdAt`). It returns true only when that run failed setup on the writer hold and the hold still refuses a start (`failedRunWorkspaceHoldRefusesStart` from #23446). - `server/src/routes/issues.ts`: the POST comment and PATCH comment wake paths skip the assignee wake when the actor is an agent and that check is true. In the PATCH path, the same result (read once per request) also holds the `issue_status_changed` wake, for example when an agent moves a blocked task to `todo` with a comment. The check runs only when the route would otherwise wake the assignee. If the check fails to read, the wake goes through as before. - Person comments, a settled hold, and a later run of the assignee on the task all keep today's behavior. - The rule needs evidence that reservation already refused this hold (the latest run failed on it). Reservation can still release an unchanged or superseded writer before it reads the hold, so a hold read alone could hold a wake that reservation would admit. - Tests: `released-writer-escalation.test.ts` checks the helper against Postgres: true behind the refused hold, false for another agent, false after the hold releases, and false after a later run. `issue-comment-reopen-routes.test.ts` checks both wake paths: an agent comment behind a refusing hold wakes nobody, a person's comment still wakes the assignee and does not read the hold, and an agent comment wakes the assignee when the hold does not refuse. A PATCH that moves a blocked task to `todo` with an agent comment wakes the assignee zero times behind a refusing hold and once otherwise. ## Verification - `cd server && npx vitest run src/__tests__/issue-comment-reopen-routes.test.ts src/__tests__/released-writer-escalation.test.ts`: 123/123 and all released-writer tests pass. - With the route check disabled, the two "agent comment behind a refusing hold" cases fail (one wake, expected none). With only the status-wake check removed, the blocked-to-`todo` case fails. - Related suites (11 files: issue comment routes, comment wakeups, queued comments, scheduled retry routes, retry scheduling, assigned-work invariant, released-writer escalation): 457/457 pass. ## Risks - Low. The new read runs only for an agent-authored comment that would wake the assignee. It is one indexed query, plus the workspace hold read only when the latest run failed on the hold. - An agent comment on a task behind a refused hold no longer starts a run. The assignee reads the comment on its next run, which stranded-work recovery and the released-writer pass start when the hold settles. - Person comments are unchanged. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, git, GitHub CLI) and code execution. ## 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 - [ ] I have updated relevant documentation to reflect my changes (not needed: no command or documented behavior 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../issue-comment-reopen-routes.test.ts | 52 +++++++++++++++++++ .../released-writer-escalation.test.ts | 19 ++++++- server/src/routes/issues.ts | 39 ++++++++++++-- .../services/remote-workspace-writer-hold.ts | 14 ++++- 4 files changed, 118 insertions(+), 6 deletions(-) diff --git a/server/src/__tests__/issue-comment-reopen-routes.test.ts b/server/src/__tests__/issue-comment-reopen-routes.test.ts index 66fd8f24682..983bc810ab8 100644 --- a/server/src/__tests__/issue-comment-reopen-routes.test.ts +++ b/server/src/__tests__/issue-comment-reopen-routes.test.ts @@ -258,6 +258,12 @@ vi.mock("../services/external-objects.js", () => ({ externalObjectService: () => mockExternalObjectService, })); +const mockAgentTaskWorkspaceHoldRefusesStart = vi.hoisted(() => vi.fn(async (_db: unknown, _input: Record) => false)); +vi.mock("../services/remote-workspace-writer-hold.js", async importOriginal => ({ + ...await importOriginal(), + agentTaskWorkspaceHoldRefusesStart: mockAgentTaskWorkspaceHoldRefusesStart, +})); + vi.mock("../services/cross-issue-influence-limit.js", () => ({ observeCrossIssueInfluence: mockObserveCrossIssueInfluence, crossIssueInfluenceLimitError: mockCrossIssueInfluenceLimitError, @@ -631,6 +637,52 @@ describe("issue comment reopen routes", () => { ); }); + it.each([ + ["post", true, true, 0], ["patch", true, true, 0], ["post", false, true, 1], ["patch", false, true, 1], ["post", true, false, 1], + ] as const)("%s comment (agent author: %s) behind a refusing workspace hold (%s) wakes the assignee %i time(s)", + async (method, agentAuthor, refuses, wakes) => { + const issue = makeIssue("in_progress"); + mockIssueService.getById.mockResolvedValue(issue); + mockIssueService.update.mockImplementation(async (_id: string, patch: Record) => + makeIssueUpdateReceipt(issue, patch)); + mockAgentTaskWorkspaceHoldRefusesStart.mockReset().mockResolvedValue(refuses); + const app = request(await installActor(createApp(), agentAuthor + ? { ...agentActor("33333333-3333-4333-8333-333333333333"), runId: "77777777-7777-4777-8777-777777777777" } : undefined)); + + const res = method === "post" ? await app.post(`/api/issues/${issue.id}/comments`).send({ body: "note" }) + : await app.patch(`/api/issues/${issue.id}`).send({ comment: "note" }); + + expect(res.status, JSON.stringify(res.body)).toBe(method === "post" ? 201 : 200); + if (agentAuthor) await vi.waitFor(() => expect(mockAgentTaskWorkspaceHoldRefusesStart).toHaveBeenCalledWith(mockDb, + { companyId: issue.companyId, issueId: issue.id, agentId: issue.assigneeAgentId })); + else expect(mockAgentTaskWorkspaceHoldRefusesStart).not.toHaveBeenCalled(); + await new Promise(resolve => setImmediate(resolve)); + await vi.waitFor(() => expect(mockHeartbeatService.wakeup.mock.calls.filter(([agentId, wake]) => + agentId === issue.assigneeAgentId && wake.reason === "issue_commented")).toHaveLength(wakes)); + }); + + it.each([[true, 0], [false, 1]] as const)( + "an agent PATCH moving a blocked task to todo with a comment behind a refusing workspace hold (%s) wakes the assignee %i time(s)", + async (refuses, wakes) => { + const issue = makeIssue("blocked"); + mockIssueService.getById.mockResolvedValue(issue); + mockIssueService.update.mockImplementation(async (_id: string, patch: Record) => + makeIssueUpdateReceipt(issue, patch)); + mockAgentTaskWorkspaceHoldRefusesStart.mockReset().mockResolvedValue(refuses); + mockAccessService.decide.mockImplementation(async (input: { action?: string }) => ({ + allowed: input.action !== "tasks:manage_active_checkouts", action: input.action, + reason: "allow_visible_issue_write", explanation: "Allowed by the shared visible-issue write rule." })); + const app = request(await installActor(createApp(), + { ...agentActor("33333333-3333-4333-8333-333333333333"), runId: "77777777-7777-4777-8777-777777777777" })); + + const res = await app.patch(`/api/issues/${issue.id}`).send({ comment: "note", status: "todo" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockAgentTaskWorkspaceHoldRefusesStart).toHaveBeenCalledTimes(1); + await new Promise(resolve => setImmediate(resolve)); + expect(mockHeartbeatService.wakeup.mock.calls.filter(([agentId]) => agentId === issue.assigneeAgentId)).toHaveLength(wakes); + }); + it.each(["comment", "update"])("accepts an authorized cross-task %s without restoring the target's files", async operation => { const issue = { ...makeIssue("done"), executionWorkspaceId: "33333333-3333-4333-8333-333333333333" }; const actor = { ...agentActor(), source: "agent_jwt", runId: "66666666-6666-4666-8666-666666666666" }; diff --git a/server/src/__tests__/released-writer-escalation.test.ts b/server/src/__tests__/released-writer-escalation.test.ts index 62d3c534c24..60792622299 100644 --- a/server/src/__tests__/released-writer-escalation.test.ts +++ b/server/src/__tests__/released-writer-escalation.test.ts @@ -13,8 +13,8 @@ import { createStorageService } from "../storage/service.js"; import { createReusableLeaseHandoff } from "../services/environment-lease-handoff.js"; import { heartbeatService } from "../services/heartbeat.js"; import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; -import { readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, remoteWorkspaceHoldRefusesStart } - from "../services/remote-workspace-writer-hold.js"; +import { agentTaskWorkspaceHoldRefusesStart, readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, + remoteWorkspaceHoldRefusesStart } from "../services/remote-workspace-writer-hold.js"; import { REMOTE_WORKSPACE_ABANDONED_EPOCH_SCHEMA } from "../services/remote-workspace-epoch-abandonment.js"; import { reserveRemoteWorkspace } from "../services/remote-workspaces.js"; import { continueTasksAfterWorkspaceWriterReleased, RELEASED_WORKSPACE_WRITER_OUTCOME } @@ -230,6 +230,21 @@ describePostgres("a task stranded behind its own workspace's ended writer", () = expect(wakesFor(f.task.id)).toHaveLength(1); }, 60_000); + it("holds an agent comment wake only while the agent's latest run failed on the hold that still refuses a start", async () => { + const f = await seedStrandedTask({ laterDecision: null }); + const refuses = (agentId = f.agentId) => agentTaskWorkspaceHoldRefusesStart(db, { companyId: f.companyId, issueId: f.task.id, agentId }); + expect(await refuses()).toBe(true); + expect(await refuses(randomUUID())).toBe(false); + + await f.releaseWriter(); + expect(await refuses()).toBe(false); + + const g = await seedStrandedTask({ laterDecision: null }); + await db.insert(heartbeatRuns).values({ companyId: g.companyId, agentId: g.agentId, issueId: g.task.id, status: "succeeded", + finishedAt: new Date(), contextSnapshot: { issueId: g.task.id } }); + expect(await agentTaskWorkspaceHoldRefusesStart(db, { companyId: g.companyId, issueId: g.task.id, agentId: g.agentId })).toBe(false); + }, 60_000); + it("delivers a wake that a crash left pending, and keeps backing off a refused one", async () => { const f = await seedStrandedTask({ laterDecision: null }); await f.releaseWriter(); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 0048ee3535e..47762806d9f 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -349,6 +349,7 @@ import { isCloudTrialWorkGateExemptOriginKind, } from "../services/cloud-trial-inference.js"; import { shouldWakeAssigneeForIssueComment } from "../services/issue-comment-wakeup.js"; +import { agentTaskWorkspaceHoldRefusesStart } from "../services/remote-workspace-writer-hold.js"; import { createSecretProposalsService } from "../services/secret-proposals.js"; import { renderOnboardingGreeting, @@ -3695,6 +3696,17 @@ async function recordAgentChildTaskRead(db: Db, req: Request, issue: { id: strin .catch(error => logger.warn({ err: error, runId: req.actor.runId }, "could not record the child task a run read")); } +async function agentWakeHeldByWorkspace(db: Db, input: { + actorType: string; companyId: string; issueId: string; assigneeAgentId: string; +}): Promise { + if (input.actorType !== "agent") return false; + return agentTaskWorkspaceHoldRefusesStart(db, { companyId: input.companyId, issueId: input.issueId, agentId: input.assigneeAgentId }) + .catch(error => { + logger.warn({ err: error, issueId: input.issueId }, "could not read the task workspace hold before an agent-requested wake"); + return false; + }); +} + /** How long a Retry answer waits for admission before it reports the saved request as accepted. */ const TASK_RETRY_ANSWER_ADMISSION_WAIT_MS = 5_000; @@ -17413,13 +17425,23 @@ export function issueRoutes( }); } + let assigneeWakeHeld: Promise | null = null; + const assigneeWakeHeldByWorkspace = (assigneeAgentId: string) => + (assigneeWakeHeld ??= agentWakeHeldByWorkspace(db, { + actorType: actor.actorType, + companyId: issue.companyId, + issueId: issue.id, + assigneeAgentId, + })); + if ( !assigneeChanged && (statusChangedFromBacklog || statusChangedFromBlockedToTodo || statusChangedFromClosedToTodo || userResumedFromReviewToTodo) && - issue.assigneeAgentId + issue.assigneeAgentId && + !(await assigneeWakeHeldByWorkspace(issue.assigneeAgentId)) ) { addWakeup(issue.assigneeAgentId, { source: "automation", @@ -17471,7 +17493,8 @@ export function issueRoutes( assigneeId && !assigneeChanged && !goalCommentSteered && - shouldWakeAssigneeForComment + shouldWakeAssigneeForComment && + !(await assigneeWakeHeldByWorkspace(assigneeId)) ) { addWakeup(assigneeId, { source: "automation", @@ -20974,7 +20997,17 @@ export function issueRoutes( reopened, currentStatus: wakeIssueSnapshot.status, }); - if (assigneeId && !goalCommentSteered && shouldWakeAssigneeForComment) { + if ( + assigneeId && + !goalCommentSteered && + shouldWakeAssigneeForComment && + !(await agentWakeHeldByWorkspace(db, { + actorType: actor.actorType, + companyId: currentIssue.companyId, + issueId: currentIssue.id, + assigneeAgentId: assigneeId, + })) + ) { if (reopened) { addWakeup(assigneeId, { source: "automation", diff --git a/server/src/services/remote-workspace-writer-hold.ts b/server/src/services/remote-workspace-writer-hold.ts index b51f254bd50..af7c98ae7fb 100644 --- a/server/src/services/remote-workspace-writer-hold.ts +++ b/server/src/services/remote-workspace-writer-hold.ts @@ -1,4 +1,4 @@ -import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { and, desc, eq, inArray, or, sql } from "drizzle-orm"; import { environmentLeases, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, workspaceOperations, type Db } from "@paperclipai/db"; import { readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema, type RemoteWorkspaceAuthority } from "@paperclipai/shared"; @@ -185,6 +185,18 @@ export async function failedRunWorkspaceHoldRefusesStart(tx: Db, run: { return remoteWorkspaceHoldRefusesStart(await readRemoteWorkspaceWriterHold(tx, { companyId: run.companyId, authority, runId: run.id }), now); } +export async function agentTaskWorkspaceHoldRefusesStart(tx: Db, input: { + companyId: string; issueId: string; agentId: string; +}, now = Date.now()): Promise { + const [latest] = await tx.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, errorCode: heartbeatRuns.errorCode, + error: heartbeatRuns.error, contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${input.issueId}`)) + .orderBy(desc(heartbeatRuns.createdAt)).limit(1); + if (!latest) return false; + return failedRunWorkspaceHoldRefusesStart(tx, { ...latest, issueId: input.issueId }, now); +} + /** * Abandons a dirty remote workspace epoch whose ended writer was already * superseded by a recorded successor run, once that successor has also ended