Use one automatic goal steering decision for task comments

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip committed 2026-11-18 17:30:13 -08:00
1 parent a3d18b1b66
commit 1e83ba0ec1
5 files changed
+121 -90

No files matched your search

+5
View File
@@ -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
@@ -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<typeof import("../realtime/runner-prp-ws.js")>(),
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<void>((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,
@@ -0,0 +1,54 @@
import type { Issue, RunnerGoalProjection } from "@paperclipai/shared";
type AutomaticGoalCommentSteeringPorts = {
readGoal(
companyId: string,
issueId: string,
assigneeAgentId: string,
): Promise<{ goal: Pick<NonNullable<RunnerGoalProjection["goal"]>, "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<unknown> } | 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<Issue, "id" | "companyId" | "assigneeAgentId" | "externalConversationState">,
actor: { actorType: "agent" | "user"; actorId: string },
comment: { id: string; body: string },
): Promise<boolean> {
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;
}
};
}
+1
View File
@@ -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";
+11 -89
View File
@@ -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<ReturnType<typeof svc.addComment>>;
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