From 1e83ba0ec132c57bcb898fb8db24261b92cb3b64 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 18 Nov 2026 17:30:13 -0800 Subject: [PATCH] Use one automatic goal steering decision for task comments Co-Authored-By: Paperclip --- doc/heartbeat-internals.md | 5 + ...issue-update-comment-wakeup-routes.test.ts | 51 ++++++++- .../automatic-goal-comment-steering.ts | 54 ++++++++++ server/src/modules/wake-queue/index.ts | 1 + server/src/routes/issues.ts | 100 ++---------------- 5 files changed, 121 insertions(+), 90 deletions(-) create mode 100644 server/src/modules/wake-queue/application/automatic-goal-comment-steering.ts diff --git a/doc/heartbeat-internals.md b/doc/heartbeat-internals.md index f89d45b0992..e80d6e66ecc 100644 --- a/doc/heartbeat-internals.md +++ b/doc/heartbeat-internals.md @@ -249,6 +249,11 @@ They read only the queued run's runtime mode. Mutation locks retain complete wake and run rows, so edits, ordering, interruption, and saved execution inputs keep their existing write contract. +Wake-queue also handles automatic steering for a saved task comment when an +active session goal is working. It suppresses the assignee's comment wake after +the live runner acknowledges delivery. When the live command cannot deliver the +comment, the comment follows the route's normal wake rules. + The task composer offers Steer when the native session has an active provider turn that accepts steering. Wake-queue locks the task and receipt for the click, then locks and rereads the run after the provider acknowledges delivery. It diff --git a/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts b/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts index 0d11642f44f..eab421b48f8 100644 --- a/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts +++ b/server/src/__tests__/issue-update-comment-wakeup-routes.test.ts @@ -60,10 +60,18 @@ const mockIssueThreadInteractionService = vi.hoisted(() => ({ expireStaleRequestConfirmationsForIssueDocument: vi.fn(async () => []), })); const mockRunnerGoalService = vi.hoisted(() => ({ - projection: vi.fn(async () => null), + projection: vi.fn(async (): Promise<{ goal: { status: "active" }; workingNow: boolean } | null> => null), act: vi.fn(), })); +const mockQueueLiveRunnerPrpCommand = vi.hoisted(() => vi.fn< + typeof import("../realtime/runner-prp-ws.js").queueLiveRunnerPrpCommand +>()); +vi.mock("../realtime/runner-prp-ws.js", async (importOriginal) => ({ + ...await importOriginal(), + queueLiveRunnerPrpCommand: mockQueueLiveRunnerPrpCommand, +})); + vi.mock("../services/native-runtime/native-question-bridge.js", () => ({ deliverNativeQuestionResponse: vi.fn(async () => "not_native"), nativeQuestionRunToCancel: vi.fn(async () => null), @@ -905,6 +913,47 @@ describe("issue update comment wakeups", () => { expect(mockIssueService.update.mock.calls.every(([id]) => id === existing.id)).toBe(true); }); + it.each((["post", "patch"] as const).flatMap((method) => + (["acknowledged", "rejected", "timeout", "unavailable"] as const).map((delivery) => ({ method, delivery })), + ))("uses automatic goal steering for $method comments with $delivery delivery", async ({ method, delivery }) => { + const existing = makeIssue({ status: "in_progress", assigneeAgentId: ASSIGNEE_AGENT_ID, assigneeUserId: null }); + const body = "Use a darker shade of blue."; + const comment = { id: "goal-steering-comment", issueId: existing.id, companyId: existing.companyId, body }; + mockIssueService.getById.mockResolvedValue(existing); + mockIssueService.update.mockResolvedValue(existing); + mockIssueService.addComment.mockResolvedValue(comment); + mockRunnerGoalService.projection.mockResolvedValue({ goal: { status: "active" }, workingNow: true }); + const commandId = `goal_comment_${comment.id}`; + mockQueueLiveRunnerPrpCommand.mockImplementation(() => delivery === "unavailable" ? null : { + runId: SOURCE_RUN_ID, + commandId, + controllerSeq: 1, + completion: delivery === "acknowledged" ? Promise.resolve(null) : Promise.reject(new Error(delivery)), + }); + + const app = await createApp(); + const res = method === "post" + ? await request(app).post(`/api/issues/${existing.id}/comments`).send({ body }) + : await request(app).patch(`/api/issues/${existing.id}`).send({ comment: body }); + + expect(res.status).toBe(method === "post" ? 201 : 200); + expect(mockIssueService.addComment).toHaveBeenCalledOnce(); + expect(mockRunnerGoalService.projection).toHaveBeenCalledExactlyOnceWith(existing.companyId, existing.id, ASSIGNEE_AGENT_ID); + expect(mockQueueLiveRunnerPrpCommand).toHaveBeenCalledExactlyOnceWith({ + companyId: existing.companyId, issueId: existing.id, agentId: ASSIGNEE_AGENT_ID, + type: "turn.steer", payload: { text: body }, commandId, + }); + await new Promise((resolve) => setImmediate(resolve)); + if (delivery === "acknowledged") { + expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled(); + } else { + expect(mockHeartbeatService.wakeup).toHaveBeenCalledExactlyOnceWith(ASSIGNEE_AGENT_ID, expect.objectContaining({ + reason: "issue_commented", + payload: expect.objectContaining({ issueId: existing.id, commentId: comment.id }), + })); + } + }); + it("preserves an explicit resume on a run-authenticated top-level comment", async () => { const existing = makeIssue({ assigneeAgentId: ASSIGNEE_AGENT_ID, diff --git a/server/src/modules/wake-queue/application/automatic-goal-comment-steering.ts b/server/src/modules/wake-queue/application/automatic-goal-comment-steering.ts new file mode 100644 index 00000000000..9451aab6b2a --- /dev/null +++ b/server/src/modules/wake-queue/application/automatic-goal-comment-steering.ts @@ -0,0 +1,54 @@ +import type { Issue, RunnerGoalProjection } from "@paperclipai/shared"; + +type AutomaticGoalCommentSteeringPorts = { + readGoal( + companyId: string, + issueId: string, + assigneeAgentId: string, + ): Promise<{ goal: Pick, "status"> | null; workingNow: boolean } | null>; + queueCommand(input: { + companyId: string; + issueId: string; + agentId: string; + type: "turn.steer"; + payload: { text: string }; + commandId: string; + }): { runId: string; completion: Promise } | null; + reportCommandFailure(details: { err: unknown; issueId: string; commentId: string; runId: string }): void; +}; + +/** True only when the live runner acknowledges delivery of this saved comment. */ +export function createAutomaticGoalCommentSteering(ports: AutomaticGoalCommentSteeringPorts) { + return async function steerAutomaticGoalComment( + issue: Pick, + actor: { actorType: "agent" | "user"; actorId: string }, + comment: { id: string; body: string }, + ): Promise { + const agentId = issue.assigneeAgentId; + // External conversation messages need the attributed boundary wake and return-thread receipt. + if (!agentId || issue.externalConversationState || (actor.actorType === "agent" && actor.actorId === agentId)) { + return false; + } + + const goal = await ports.readGoal(issue.companyId, issue.id, agentId); + if (goal?.goal?.status !== "active" || !goal.workingNow) return false; + + const command = ports.queueCommand({ + companyId: issue.companyId, + issueId: issue.id, + agentId, + type: "turn.steer", + payload: { text: comment.body }, + commandId: `goal_comment_${comment.id}`, + }); + if (!command) return false; + + try { + await command.completion; + return true; + } catch (err) { + ports.reportCommandFailure({ err, issueId: issue.id, commentId: comment.id, runId: command.runId }); + return false; + } + }; +} diff --git a/server/src/modules/wake-queue/index.ts b/server/src/modules/wake-queue/index.ts index 6c7852e85cc..e6c0819d013 100644 --- a/server/src/modules/wake-queue/index.ts +++ b/server/src/modules/wake-queue/index.ts @@ -30,6 +30,7 @@ export type { ReleaseOutcome, RunSummary, } from "./application/types.js"; +export { createAutomaticGoalCommentSteering } from "./application/automatic-goal-comment-steering.js"; export { WakeQueueApplicationError } from "./application/types.js"; export { hasRetainedExternalChatRetry } from "./domain/context.js"; export { QUEUED_MESSAGES_DELIVERED_REASON } from "./domain/policy.js"; diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 809d38117d2..7f5c4bbc610 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -250,6 +250,7 @@ import { queueLiveRunnerPrpCommand } from "../realtime/runner-prp-ws.js"; import { questionResponseDeliveryService } from "../services/question-response-delivery.js"; import { emitAgentTaskRunById } from "../services/agent-task-run-telemetry.js"; import { + createAutomaticGoalCommentSteering, createQueuedCommentQueue, requireQueuedCommentMutationTarget, QueuedCommentMutationError, @@ -3753,6 +3754,14 @@ export function issueRoutes( } }, }); + const steerAutomaticGoalComment = createAutomaticGoalCommentSteering({ + readGoal: runnerGoals.projection, + queueCommand: queueLiveRunnerPrpCommand, + reportCommandFailure: (details) => logger.warn( + details, + "failed to steer an active session goal; falling back to a boundary wake", + ), + }); const stopRunnerGoalForOwnershipChange = async (input: { companyId: string; issueId: string; @@ -16394,49 +16403,7 @@ export function issueRoutes( : await addCommentAndReceipt(db); await issueReferencesSvc.syncComment(comment.id); await externalObjectsSvc.syncCommentSafely(comment.id); - if ( - issue.assigneeAgentId && - !issue.externalConversationState && - !( - actor.actorType === "agent" && - actor.actorId === issue.assigneeAgentId - ) - ) { - const goalProjection = await runnerGoals.projection( - issue.companyId, - issue.id, - issue.assigneeAgentId, - ); - if ( - goalProjection?.goal?.status === "active" && - goalProjection.workingNow - ) { - const steer = queueLiveRunnerPrpCommand({ - companyId: issue.companyId, - issueId: issue.id, - agentId: issue.assigneeAgentId, - type: "turn.steer", - payload: { text: comment.body }, - commandId: `goal_comment_${comment.id}`, - }); - if (steer) { - try { - await steer.completion; - goalCommentSteered = true; - } catch (err) { - logger.warn( - { - err, - issueId: issue.id, - commentId: comment.id, - runId: steer.runId, - }, - "failed to steer an active session goal; falling back to a boundary wake", - ); - } - } - } - } + goalCommentSteered = await steerAutomaticGoalComment(issue, actor, comment); const commentReferenceSummaryAfter = await issueReferencesSvc.listIssueReferenceSummary(issue.id); const commentReferenceDiff = @@ -19719,7 +19686,6 @@ export function issueRoutes( // Without a single transaction, a 422 (or any error) thrown by the status update after the // comment is inserted would leave an orphan comment without the corresponding state change. let comment: Awaited>; - let goalCommentSteered = false; let fastResponseEnqueued = false; if (shouldAutoApproveReviewComment) { const transition = applyIssueExecutionPolicyTransition({ @@ -19979,51 +19945,7 @@ export function issueRoutes( }); else await issueReferencesSvc.syncComment(comment.id); await externalObjectsSvc.syncCommentSafely(comment.id); - if ( - currentIssue.assigneeAgentId && - // Slack-linked messages need the normal attributed wake boundary so - // the accepted requester and return-thread receipt travel with the run. - !currentIssue.externalConversationState && - !( - actor.actorType === "agent" && - actor.actorId === currentIssue.assigneeAgentId - ) - ) { - const goalProjection = await runnerGoals.projection( - currentIssue.companyId, - currentIssue.id, - currentIssue.assigneeAgentId, - ); - if ( - goalProjection?.goal?.status === "active" && - goalProjection.workingNow - ) { - const steer = queueLiveRunnerPrpCommand({ - companyId: currentIssue.companyId, - issueId: currentIssue.id, - agentId: currentIssue.assigneeAgentId, - type: "turn.steer", - payload: { text: comment.body }, - commandId: `goal_comment_${comment.id}`, - }); - if (steer) { - try { - await steer.completion; - goalCommentSteered = true; - } catch (err) { - logger.warn( - { - err, - issueId: currentIssue.id, - commentId: comment.id, - runId: steer.runId, - }, - "failed to steer an active session goal; falling back to a boundary wake", - ); - } - } - } - } + const goalCommentSteered = await steerAutomaticGoalComment(currentIssue, actor, comment); if (actor.runId) { await heartbeat