From f0caee6f95a4ac7f0cb60a880d01ca56ad03fd67 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Wed, 18 Nov 2026 19:24:41 -0800 Subject: [PATCH] Use one automatic goal steering decision for task comments (#22277) ## Thinking Path > - Paperclip can deliver a saved task comment to an agent already working on a goal. > - Both posting a comment and editing a task with a comment perform this decision. > - Each handler previously checked eligibility, queued the same command, waited for its result, and decided whether to wake the agent. > - Separate copies make changes to the fallback rules difficult to verify. > - Both routes now call one wake-queue use case for automatic goal steering. ## Linked Issues or Issue Description **What existing behavior does this improve?** Automatic goal steering after saving a comment on a task. **Subsystem affected** Server task admission. **Current behavior** The comment POST and issue PATCH each implement live steering and its fallback. **Proposed behavior** One use case returns whether the current runner acknowledged the comment. The routes continue through their existing boundary wake logic when delivery is unavailable or fails. **Additional context** Builds on #22276. The explicit board Steer click and automatic goal steering have separate acknowledgement contracts. ## What Changed - Keep the assignee, self-comment, and external-conversation guards together with the active goal decision. - Preserve the comment-derived command ID, the route's selected agent, and completion-error reporting. - Drive both HTTP routes with a single comment through success, unavailable transport, and rejected completion. ## Verification On 74e19141dc, both HTTP route suites passed all 158 tests and server typecheck passed. The initial fixture crossed the test file size limit. The final revision shares one existing service mock across Vitest resets and reduces the file to 974 lines. Eight table-driven cases cover each route with one comment and an acknowledged, rejected, timed-out or unavailable live command. Run `pnpm exec vitest run server/src/__tests__/issue-update-comment-wakeup-routes.test.ts server/src/__tests__/issue-comment-reopen-routes.test.ts`, `pnpm --filter @paperclipai/server typecheck`, and `node scripts/check-module-boundaries.mjs`. ## Risks Returning success too early would suppress the task wake and lose the comment as input. A confirmed delivery must suppress the duplicate wake. Both routes exercise these outcomes. ## Model Used OpenAI GPT-6.2 Sol (`gpt-6.2-sol`) implemented the change. OpenAI Codex directed the work, reviewed the diff, and ran qualification. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/heartbeat-internals.md | 5 + ...issue-update-comment-wakeup-routes.test.ts | 124 ++++++++---------- .../automatic-goal-comment-steering.ts | 54 ++++++++ server/src/modules/wake-queue/index.ts | 1 + server/src/routes/issues.ts | 100 ++------------ 5 files changed, 124 insertions(+), 160 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..4d6b6851457 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), @@ -76,7 +84,7 @@ vi.mock("../services/runner-goals.js", () => ({ RunnerGoalConflictError: class RunnerGoalConflictError extends Error {}, })); -vi.mock("../services/index.js", () => ({ +const createServicesMock = vi.hoisted(() => () => ({ companyService: () => ({ getById: vi.fn(async () => ({ id: "company-1" })), }), @@ -145,6 +153,7 @@ vi.mock("../services/index.js", () => ({ }), workProductService: () => ({}), })); +vi.mock("../services/index.js", createServicesMock); function registerModuleMocks() { vi.doMock("../services/external-objects.js", () => ({ @@ -154,75 +163,7 @@ function registerModuleMocks() { }), })); - vi.doMock("../services/index.js", () => ({ - companyService: () => ({ - getById: vi.fn(async () => ({ id: "company-1" })), - }), - accessService: () => ({ - canUser: vi.fn(async () => true), - decide: mockAccessDecide, - hasPermission: vi.fn(async () => true), - }), - agentService: () => ({ - getById: vi.fn(async () => null), - resolveByReference: vi.fn(async (_companyId: string, raw: string) => ({ - ambiguous: false, - agent: { id: raw }, - })), - }), - companySkillService: () => ({ - completeTestRunForIssue: vi.fn(async () => null), - }), - documentAnnotationService: () => ({ remapOpenThreadsForDocument: async () => [] }), - documentService: () => ({}), - executionWorkspaceService: () => ({}), - feedbackService: () => ({ - listIssueVotesForUser: vi.fn(async () => []), - saveIssueVote: vi.fn(async () => ({ vote: null, consentEnabledNow: false, sharingEnabled: false })), - }), - goalService: () => ({}), - heartbeatService: () => mockHeartbeatService, - instanceSettingsService: () => ({ - get: vi.fn(async () => ({ - id: "instance-settings-1", - general: { - censorUsernameInLogs: false, - feedbackDataSharingPreference: "prompt", - }, - })), - listCompanyIds: vi.fn(async () => ["company-1"]), - }), - issueApprovalService: () => ({}), - issueReferenceService: () => ({ - deleteDocumentSource: async () => undefined, - diffIssueReferenceSummary: () => ({ - addedReferencedIssues: [], - removedReferencedIssues: [], - currentReferencedIssues: [], - }), - emptySummary: () => ({ outbound: [], inbound: [] }), - listIssueReferenceSummary: async () => ({ outbound: [], inbound: [] }), - syncComment: async () => undefined, - syncDocument: async () => undefined, - syncIssue: async () => undefined, - }), - issueRecoveryActionService: () => ({ - getActiveForIssue: vi.fn(async () => null), - listActiveForIssues: vi.fn(async () => new Map()), - }), - issueTreeControlService: () => ({ getActivePauseHoldGate: mockPauseGate }), - issueService: () => mockIssueService, - issueThreadInteractionService: () => mockIssueThreadInteractionService, - logActivity: vi.fn(async () => undefined), - projectService: () => ({}), - questionResponseDeliveryService: () => ({ - deliver: vi.fn(async () => undefined), - }), - routineService: () => ({ - syncRunStatusForIssue: vi.fn(async () => undefined), - }), - workProductService: () => ({}), - })); + vi.doMock("../services/index.js", createServicesMock); } async function loadAppModules() { @@ -905,6 +846,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 f77a4a36cd3..8f1092dacc0 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -251,6 +251,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, @@ -3754,6 +3755,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; @@ -16397,49 +16406,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 = @@ -19722,7 +19689,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({ @@ -19982,51 +19948,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