mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 13:01:05 +01:00
fix(wake-queue): reopen a finished task for a person's comment merged into a system wake (#21914)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The wake queue holds new input for a task while an agent run is active, and releases it when the run ends > - A person's comment on a task always reopens the task when the run that closed it did not receive the comment > - A restart test found a person's comment that was posted while the run was finishing. The run marked the task done and no later run started. The comment was lost > - The comment joined a deferred child-completion wake that a system actor requested. The release step only looked at the wake requester, which was "system", so it did not see the person > - This pull request makes the release step look at who wrote the undelivered comments in the wake > - The benefit is that a person's comment is never dropped because it shares a queued wake with system work ## Linked Issues or Issue Description **What happened?** A person posted a comment on a task while the assigned agent's run was active. The run then marked the task done. The task stayed done, and no run received the comment. The deferred wake that held the comment was cancelled with "Deferred execution wake no longer applies to a terminal task". **Expected behavior** The task reopens and a new run receives the person's comment. **Steps to reproduce** 1. Start a run for a task. 2. While the run is active, let the system defer a wake for the same task (for example, a child task completes). 3. Post a comment as a person. The comment wake merges into the deferred system wake. 4. Let the run mark the task done. 5. The task stays done. No run receives the comment. **Paperclip version or commit** `master` atb4fa1c7fb1(first seen atc5218f5ec4). **Relevant logs or output** The merged deferred wake had `reason = issue_execution_deferred` and `requestedByActorType = system`. Its payload held the person's comment id. The coalesced comment receipt had `requestedByActorType = user`. Release cancelled the merged wake as terminal-task work. ## What Changed - `getCommentSelfAuthorship` in the wake-queue Postgres adapter also returns `includesPersonComment`. This value is true when one of the wake's undelivered comments was written by a person and not by an agent run. - `promoteDeferredWake` reopens a done or cancelled task when `includesPersonComment` is true, also when the wake requester is the system. - The delivered-comment filter is not changed. A comment that a run already received does not reopen the task. - New embedded-Postgres tests in `heartbeat-comment-wake-batching.test.ts`: - A person's comment merges into a deferred child-completion wake during a run. The run closes the task. The task reopens and the next run receives the comment. This test is red on `master` with the exact production cancel reason. - Negative: the person's comment in the merged wake is the comment that the closing run received as its input. The task stays done and no new run starts. ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-comment-wake-batching.test.ts src/modules/wake-queue` passes (15 files, 391 tests). - `cd server && npx vitest run src/__tests__/heartbeat-held-comment-wake.test.ts src/__tests__/heartbeat-issue-rewake-throttle.test.ts src/__tests__/heartbeat-answer-behind-settling-run.test.ts` passes (57 tests). - `cd server && npx tsc --noEmit` passes. - Red check: with only the source change reverted, the new positive test fails with `expected 'Deferred execution wake no longer app…' to be null`. - `pnpm verify` exits 2 (an opaque setup dependency). Required CI supplies broad coverage. ## Risks - Low risk. The change only adds a reopen reason for a done or cancelled task. The comment must be live, undelivered, not written by the finishing run, and written by a person. - A comment from a local CLI agent can carry a user id. The check excludes comments that have a creating run or an agent author, so these comments do not count as person comments. > 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
77ddf260bf
commit
20b0d4e5a5
5 files changed
+177
-5
No files matched your search
@@ -2164,6 +2164,169 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => {
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
async function startAssignedRunWithDeferredChildCompletion(input: {
|
||||
gateway: Awaited<ReturnType<typeof createControlledGatewayServer>>;
|
||||
title: string;
|
||||
firstRunComment?: boolean;
|
||||
}) {
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`;
|
||||
const heartbeat = heartbeatService(db);
|
||||
await db.insert(companies).values(wakeCompanyRow(companyId, issuePrefix));
|
||||
await grantFixtureWorkspaceAccess(companyId, ["responsible-user", "user-1"]);
|
||||
await db.insert(agents).values(wakeGatewayAgentRow(agentId, companyId, "Gateway Agent", input.gateway));
|
||||
await db.insert(issues).values(wakeIssueRow(issueId, companyId, input.title, agentId, issuePrefix));
|
||||
|
||||
const firstRunComment = input.firstRunComment
|
||||
? await db.insert(issueComments)
|
||||
.values(wakeUserCommentRow(companyId, issueId, "user-1", "Start with this instruction"))
|
||||
.returning().then((rows) => rows[0])
|
||||
: null;
|
||||
const firstRun = await heartbeat.wakeup(agentId, firstRunComment
|
||||
? {
|
||||
source: "automation", triggerDetail: "system", reason: "issue_commented",
|
||||
payload: { issueId, commentId: firstRunComment.id },
|
||||
contextSnapshot: { issueId, taskId: issueId, commentId: firstRunComment.id, wakeCommentId: firstRunComment.id,
|
||||
wakeReason: "issue_commented" },
|
||||
requestedByActorType: "user", requestedByActorId: "user-1",
|
||||
}
|
||||
: {
|
||||
source: "assignment", triggerDetail: "system", reason: "issue_assigned",
|
||||
payload: { issueId }, contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned" },
|
||||
requestedByActorType: "user", requestedByActorId: "user-1",
|
||||
});
|
||||
expect(firstRun).not.toBeNull();
|
||||
await waitFor(async () => {
|
||||
const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, firstRun!.id)).then((rows) => rows[0] ?? null);
|
||||
return run?.status === "running";
|
||||
});
|
||||
await waitFor(() => input.gateway.getAgentPayloads().length >= 1);
|
||||
|
||||
const childCompletionIntentId = randomUUID();
|
||||
const childCompletionWakeId = randomUUID();
|
||||
const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed" };
|
||||
await db.insert(agentWakeupRequests).values([{
|
||||
id: childCompletionIntentId, companyId, agentId, source: "automation", triggerDetail: "system",
|
||||
reason: "issue_children_completed", status: "coalesced",
|
||||
requestedByActorType: "system", requestedByActorId: "native-status-committer",
|
||||
payload: { issueId, taskId: issueId }, finishedAt: new Date(),
|
||||
}, {
|
||||
id: childCompletionWakeId, companyId, agentId, source: "automation", triggerDetail: "system",
|
||||
reason: "issue_execution_deferred", status: "deferred_issue_execution",
|
||||
requestedByActorType: "system", requestedByActorId: `native-status-wake-dispatch:${childCompletionIntentId}`,
|
||||
payload: { issueId, taskId: issueId, _paperclipWakeContext: childCompletionContext },
|
||||
}]);
|
||||
return { companyId, agentId, issueId, heartbeat, firstRun: firstRun!, firstRunComment, childCompletionWakeId };
|
||||
}
|
||||
|
||||
async function closeIssueAndFinishFirstRun(
|
||||
gateway: Awaited<ReturnType<typeof createControlledGatewayServer>>,
|
||||
issueId: string,
|
||||
firstRunId: string,
|
||||
) {
|
||||
await db.update(issues).set({
|
||||
status: "done", completedAt: new Date(), executionRunId: null, executionAgentNameKey: null,
|
||||
executionLockedAt: null, updatedAt: new Date(),
|
||||
}).where(eq(issues.id, issueId));
|
||||
gateway.releaseFirstWait();
|
||||
await waitFor(async () => {
|
||||
const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, firstRunId)).then((rows) => rows[0] ?? null);
|
||||
return run?.status === "succeeded";
|
||||
}, 90_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 {
|
||||
const { companyId, agentId, issueId, heartbeat, firstRun, childCompletionWakeId } =
|
||||
await startAssignedRunWithDeferredChildCompletion({ gateway, title: "Person comment behind a child result" });
|
||||
|
||||
const personComment = await db.insert(issueComments)
|
||||
.values(wakeUserCommentRow(companyId, issueId, "user-1", "Additional requirement posted while the run was finishing"))
|
||||
.returning().then((rows) => rows[0]);
|
||||
const commentWake = 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",
|
||||
});
|
||||
expect(commentWake).toBeNull();
|
||||
const merged = await selectDeferredWakeForAgent(companyId, agentId);
|
||||
expect(merged).toMatchObject({ id: childCompletionWakeId, requestedByActorType: "system" });
|
||||
expect(JSON.stringify(merged?.payload)).toContain(personComment.id);
|
||||
|
||||
await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id);
|
||||
|
||||
await waitFor(async () => {
|
||||
const wake = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null);
|
||||
return wake?.status !== "deferred_issue_execution";
|
||||
}, 30_000);
|
||||
const settledWake = await db.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error })
|
||||
.from(agentWakeupRequests).where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null);
|
||||
expect(settledWake?.error).toBeNull();
|
||||
expect(settledWake?.status).not.toBe("cancelled");
|
||||
await waitFor(() => gateway.getAgentPayloads().length >= 2, 90_000);
|
||||
const issueAfter = await db.select({ status: issues.status, completedAt: issues.completedAt })
|
||||
.from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null);
|
||||
expect(issueAfter).toMatchObject({ status: "in_progress", completedAt: null });
|
||||
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId))
|
||||
.orderBy(asc(heartbeatRuns.createdAt));
|
||||
expect(runs).toHaveLength(2);
|
||||
expect(runs[1]?.wakeupRequestId).toBe(childCompletionWakeId);
|
||||
expect(String(gateway.getAgentPayloads()[1]?.message ?? "")).toContain(
|
||||
"Additional requirement posted while the run was finishing",
|
||||
);
|
||||
} finally {
|
||||
gateway.releaseFirstWait();
|
||||
await gateway.close();
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it("keeps a finished task closed when the only person comment in a deferred system wake was the run's own input", async () => {
|
||||
const gateway = await createControlledGatewayServer();
|
||||
try {
|
||||
const { companyId, agentId, issueId, heartbeat, firstRun, firstRunComment, childCompletionWakeId } =
|
||||
await startAssignedRunWithDeferredChildCompletion({
|
||||
gateway, title: "Delivered person comment behind a child result", firstRunComment: true,
|
||||
});
|
||||
|
||||
const repeatedWake = await heartbeat.wakeup(agentId, {
|
||||
source: "automation", triggerDetail: "system", reason: "issue_commented",
|
||||
payload: { issueId, commentId: firstRunComment!.id },
|
||||
contextSnapshot: { issueId, taskId: issueId, commentId: firstRunComment!.id, wakeCommentId: firstRunComment!.id,
|
||||
wakeReason: "issue_commented" },
|
||||
requestedByActorType: "user", requestedByActorId: "user-1",
|
||||
});
|
||||
expect(repeatedWake).toBeNull();
|
||||
const merged = await selectDeferredWakeForAgent(companyId, agentId);
|
||||
expect(merged?.id).toBe(childCompletionWakeId);
|
||||
expect(JSON.stringify(merged?.payload)).toContain(firstRunComment!.id);
|
||||
|
||||
await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id);
|
||||
|
||||
await waitFor(async () => {
|
||||
const wake = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null);
|
||||
return wake?.status === "cancelled";
|
||||
}, 90_000);
|
||||
const issueAfter = await db.select({ status: issues.status }).from(issues)
|
||||
.where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null);
|
||||
expect(issueAfter?.status).toBe("done");
|
||||
const runs = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId));
|
||||
expect(runs.map((run) => run.id)).toEqual([firstRun.id]);
|
||||
expect(gateway.getAgentPayloads()).toHaveLength(1);
|
||||
} finally {
|
||||
gateway.releaseFirstWait();
|
||||
await gateway.close();
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it("cancels a deferred comment wake when its only queued comment is deleted before promotion", async () => {
|
||||
const gateway = await createControlledGatewayServer();
|
||||
const companyId = randomUUID();
|
||||
|
||||
@@ -474,10 +474,18 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru
|
||||
|
||||
async getCommentSelfAuthorship({ companyId, issueId, finishingRunId, commentIds }) {
|
||||
const rows = await tx
|
||||
.select({ createdByRunId: issueComments.createdByRunId })
|
||||
.select({
|
||||
createdByRunId: issueComments.createdByRunId, authorType: issueComments.authorType,
|
||||
authorUserId: issueComments.authorUserId, authorAgentId: issueComments.authorAgentId,
|
||||
derivedAuthorAgentId: issueComments.derivedAuthorAgentId, deletedAt: issueComments.deletedAt,
|
||||
})
|
||||
.from(issueComments)
|
||||
.where(and(eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), inArray(issueComments.id, commentIds)));
|
||||
return { allSelfAuthored: rows.length > 0 && rows.every((row) => row.createdByRunId === finishingRunId) };
|
||||
return {
|
||||
allSelfAuthored: rows.length > 0 && rows.every((row) => row.createdByRunId === finishingRunId),
|
||||
includesPersonComment: rows.some((row) => !row.deletedAt && row.authorUserId !== null && row.createdByRunId === null &&
|
||||
row.authorAgentId === null && row.derivedAuthorAgentId === null && (row.authorType === "user" || row.authorType === null)),
|
||||
};
|
||||
},
|
||||
|
||||
async isWatcherCommentDuringFinishingRun({ companyId, issueId, finishingRunId, commentIds }) {
|
||||
|
||||
@@ -178,7 +178,7 @@ export interface WakeQueueTransaction {
|
||||
issueId: string;
|
||||
finishingRunId: string;
|
||||
commentIds: string[];
|
||||
}): Promise<{ allSelfAuthored: boolean }>;
|
||||
}): Promise<{ allSelfAuthored: boolean; includesPersonComment: boolean }>;
|
||||
/** Proves all candidate comments only report completed child work in the finishing parent's own run. */
|
||||
isCompletedDelegationMention(input: {
|
||||
companyId: string;
|
||||
|
||||
@@ -115,7 +115,7 @@ function createFakeTransaction(overrides: Partial<WakeQueueTransaction> = {}): W
|
||||
reason: null,
|
||||
releasePolicy: null,
|
||||
})),
|
||||
getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: false })),
|
||||
getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: false, includesPersonComment: false })),
|
||||
isWatcherCommentDuringFinishingRun: vi.fn(async () => false),
|
||||
owedInteractionAnswer: vi.fn(async (): Promise<"deliver" | "blocked" | null> => null),
|
||||
isCompletedDelegationMention: vi.fn(async () => false),
|
||||
@@ -681,7 +681,7 @@ describe("releaseIssueExecution", () => {
|
||||
liveNonSelfCommentIds: scenario === "done_missing" || scenario === "done_self" ? [] : commentIds,
|
||||
containedSelfAuthoredComment: scenario === "done_self",
|
||||
})),
|
||||
getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: scenario === "done_self" })),
|
||||
getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: scenario === "done_self", includesPersonComment: false })),
|
||||
isWatcherCommentDuringFinishingRun: vi.fn(async () => scenario === "done_watcher_during_run"),
|
||||
reopenIssue: vi.fn(async () => ({ ...ISSUE, status: "todo" })),
|
||||
});
|
||||
|
||||
@@ -392,6 +392,7 @@ async function promoteDeferredWake(
|
||||
shouldReopen =
|
||||
!selfAuthorship.allSelfAuthored &&
|
||||
(workingCandidate.requestedByActorType === "user" ||
|
||||
selfAuthorship.includesPersonComment ||
|
||||
workingCandidate.wakeReason === "issue_reopened_via_comment" ||
|
||||
// The agent watching the task posted it while the run that closed the
|
||||
// task was active. That agent receives the completed result and can
|
||||
|
||||
Reference in new issue
Block a user