fix(github): keep published reviews and settle every status comment (#22672)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Review agents answer GitHub pull requests through one shared main PR
comment and one comment per inline request
> - Paperclip writes status notices into these comments: "Work is
paused", "This turn ended without publishing a final response", "Working
on this…"
> - On recent PRs these notices replaced finished reviews, and many
never changed again, even after the task was done
> - People then see a stale status instead of the review, and work that
waits on the review slows down
> - This pull request keeps published reviews in place and makes every
status comment settle
> - The benefit is that the PR always shows the latest real review, and
no placeholder stays open after the task is idle

## Linked Issues or Issue Description

**Describe the bug**
Review bot comments on GitHub pull requests show "Work is paused. Your
request is saved." or "This turn ended without publishing a final
response." after the review finished. The comment never updates. Inline
replies stay at "Working on this…".

**Steps to reproduce**
1. A review agent publishes a review in the main PR comment.
2. Two more review requests arrive. The task becomes blocked for a short
time, or the run for a request ends without a reply.
3. The main PR comment now shows the status notice. The review is gone.
4. Separately: request A's run ends and request B's run starts a few
seconds later. A's inline comment stays "Working on this…" forever.

**Expected behavior**
A status notice for one request never replaces a published review in the
shared main PR comment. Every request comment settles once the run that
woke for it is finished and the task is idle.

**Evidence**
GitHub edit history shows the overwrite on all six settled stuck
comments across #22528, #22591, #22611, #22626 (two bots) and #22635.
Example: on #22626 the "Ponytail Paperclip Review — 3/5" body was
replaced by "Work is paused" at 14:28 and again at 14:56; Feynman's
reply was replaced and then patched nine times in four minutes. The task
ran 15 back-to-back runs about 3 seconds apart, so the old "latest run
only" check never matched the earlier requests.

## What Changed

- `writeGitHubResponseComment` takes a `status` flag. In the shared main
PR comment, a status notice never replaces a published reply or a newer
response. That request settles as final against the existing comment
(`published_response_kept` / `status_superseded`) instead of throwing
and retrying.
- Status notices carry a `paperclip-response-kind:status` marker. Known
status texts posted before this change count as status too, so a later
status may still replace them.
- `readGitHubResponseRun` / `readGitHubResponseRuns` return
`finishedRequestRunId`: the latest finished run that woke for the
request. It is part of the same statement, so the batched sweep keeps
its statement budget.
- `githubResponseExecution` settles a request from that run once the
task's latest run is finished, the latest run belongs to another
request, and the task is not blocked.
- `processTerminalResponses` selects a request when any finished run
woke for it, not only the latest run.

## Verification

- New red/green integration tests in
`server/src/__tests__/chat-channels.integration.test.ts`:
- `keeps the published review in the main GitHub PR comment when a later
request has only a status: ended_without_reply / paused` (red before:
body became the status text)
- `settles a GitHub working comment whose run finished just before
another request's run started` (red before: body stayed "Working on
this…")
- Updated older tests that asserted the old rule (status replaces the
review) to assert the review stays and the request settles final.
- `response-run-state.test.ts` equivalence reference now also computes
the finished request run; passes over the randomized fixture.
- `terminal-response-work.test.ts` statement budget passes (the first
fallback did one query per row; it now reads in the same statement).
- Local: all GitHub tests in the integration file passed (536) before
the batching refactor; after it, the targeted tests plus
`server/src/services/chat-channels/github/` and related files pass
(438). `tsc --noEmit` for server is clean. CI covers the full suite.

## Risks

- Behavior change: when a newer request is paused or ends without a
reply, the main PR comment keeps the earlier review instead of showing
the status. The status stays visible in the Paperclip task.
- A request whose run finished without a reply now settles to "ended
without publishing a final response" once the task is idle, even if a
later continuation run covered it in another thread.
- No migration.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use 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
- [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
- [ ] 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:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-23 14:54:42 -06:00
1 parent 2821af0b52
commit 8ce422e45d
7 files changed
+349 -46

No files matched your search

@@ -3196,7 +3196,9 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
if (scenario === "pending_publication") {
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
expect(response.result?.final).not.toBe(true);
expect(response).toMatchObject({ status: "failed", result: { retryable: true, code: "acknowledgement_unconfirmed" } });
// Waiting for the reply to settle spends no delivery retry.
expect(response.status).toBe("processed");
expect(response.result?.attempts).toBeUndefined();
} else if (pendingPresentation) {
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
expect(response.result?.final).not.toBe(true);
@@ -3216,16 +3218,14 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
commentAction: "none", reasonCodes: [missing ? "no_final_response" : "yielded_control_plane_wait"] },
} }).where(eq(heartbeatRuns.id, next.id));
await responses.processPending();
if (failed || missing) expect(f.responseComments.get(originalId)!.body).toContain(failed
? "This turn stopped before completing" : "This turn ended without publishing a final response");
else expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
// A status for the new request never replaces the published review.
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
expect((await readChatActionsById(response.id))[0]).toMatchObject({
status: failed || missing ? "processed" : "cancelled", result: { final: true },
});
} else {
expect(f.responseComments.get(originalId)!.body).toContain(scenario === "failed"
? "This turn stopped before completing" : "This turn ended without publishing a final response");
expect(response).toMatchObject({ status: "processed", result: { final: true } });
expect(f.responseComments.get(originalId)!.body).toBe(originalBody);
expect(response).toMatchObject({ status: "processed", result: { final: true, code: "published_response_kept" } });
}
const writes = f.responseWrites.length;
await responses.processPending();
@@ -3272,6 +3272,94 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
expect(f.responseComments.get(originalId)?.body).toContain("Second assessment");
expect(f.responseWrites.filter(write => write.method === "POST")).toHaveLength(1);
});
it.each(["ended_without_reply", "paused"] as const)(
"keeps the published review in the main GitHub PR comment when a later request has only a status: %s", async statusCase => {
const f = await publicationRetryFixture();
await f.service.execute(f.session, "submit_review", f.assessment, "first-review");
const [mainId] = [...f.responseComments.keys()];
expect(f.responseComments.get(mainId)?.body).toContain("Advisory review");
const committed = { status: "succeeded" as const, nativePhase: "committed", resultJson: {
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "none" } } };
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, f.run.id));
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
// Production saw several queued re-review requests while one run owned
// the task: the run's own request ends without a reply, and the older
// queued request is shown as paused while the task is blocked.
for (const id of ["41802", "41803"]) await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
trigger: "mention", message: makeMessage({ id, text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
await githubResponseCommentService(db, f.providerFetch).processPending();
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41803",
}) }).returning();
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, next.id));
if (statusCase === "paused") {
await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.conversation.issueId!));
} else {
await githubResponseCommentService(db, f.providerFetch).failRun({ companyId: f.companyId, endpointId: f.endpoint.id,
issueId: f.conversation.issueId!, runId: next.id,
body: "This turn ended without publishing a final response. See the Paperclip task for details." });
}
for (let pass = 0; pass < 3; pass++) await githubResponseCommentService(db, f.providerFetch).processPending();
expect([...f.responseComments.keys()]).toEqual([mainId]);
const body = f.responseComments.get(mainId)?.body ?? "";
expect(body).toContain("Advisory review");
expect(body).not.toContain("Work is paused");
expect(body).not.toContain("without publishing a final response");
// Requests with a status settle against the kept review instead of
// retrying. Unpaused, the older queued request still waits for its run.
const open = await db.select({ id: chatActions.id }).from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
eq(chatActions.kind, "github_response_comment"), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
expect(open).toHaveLength(statusCase === "paused" ? 0 : 1);
});
it("settles an older request's status without replacing a newer main GitHub PR placeholder", async () => {
const f = await toolReplyFixture("github:paperclipai/paperclip:418");
// The first request's run stopped before the next request arrived.
await db.update(heartbeatRuns).set({ status: "failed", updatedAt: new Date(Date.now() - 60_000) })
.where(eq(heartbeatRuns.id, f.run.id));
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
trigger: "mention", message: makeMessage({ id: "41802", text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
const responses = githubResponseCommentService(db, f.providerFetch);
await responses.processPending();
await responses.processPending();
expect(f.responseComments.size).toBe(1);
const body = [...f.responseComments.values()][0].body;
expect(body).not.toContain("stopped before completing");
const [first] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
eq(chatActions.kind, "github_response_comment"))).orderBy(asc(chatActions.createdAt)).limit(1);
expect(first).toMatchObject({ status: "processed", result: { final: true, code: "status_superseded" } });
});
it("settles a GitHub working comment whose run finished just before another request's run started", async () => {
const f = await toolReplyFixture();
const [firstId] = [...f.responseComments.keys()];
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
const committed = { status: "succeeded" as const, nativePhase: "committed", resultJson: {
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "none" } } };
// The first request's run ends without a reply, and the next request's run
// starts before any sweep sees the first run as the task's latest.
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, f.run.id));
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
trigger: "mention", message: makeMessage({ id: "41802", text: "One more thing", userId: "42", userName: "octocat", mentioned: true }) });
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802",
}) }).returning();
const responses = githubResponseCommentService(db, f.providerFetch);
await responses.processPending();
// Work is still running on the task, so the first request waits.
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, next.id));
await responses.processPending();
expect(f.responseComments.get(firstId)?.body).toContain("ended without publishing a final response");
const open = await db.select({ id: chatActions.id }).from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
eq(chatActions.kind, "github_response_comment"), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
expect(open).toEqual([]);
const writes = f.responseWrites.length;
await responses.processPending();
expect(f.responseWrites).toHaveLength(writes);
});
it("ignores a review request addressed to an external GitHub bot", async () => {
const f = await subscribedGitHubFixture("github:paperclipai/paperclip:419");
const wakeCount = f.wakeup.mock.calls.length;
@@ -3431,8 +3519,10 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
trigger: "mention", message: makeMessage({ id: "41802", text: "New request", userId: "42", userName: "octocat", mentioned: true }) });
await githubResponseCommentService(db, f.providerFetch).processPending();
// The published reply stays; the paused request is not marked handled.
const body = [...f.responseComments.values()][0].body;
expect(body).toContain("paused");
expect(body).toContain("Earlier result");
expect(body).not.toContain("paused");
expect(body).not.toContain("has been handled");
expect(f.responseComments.size).toBe(1);
});
@@ -1,6 +1,6 @@
import type { Db } from "@paperclipai/db";
import { githubRunReplyState } from "../../chat-run-publications.js";
import { readGitHubResponseRun, type GitHubResponseRunRead } from "./response-run-state.js";
import { FINISHED_RUN_STATUSES, readGitHubResponseRun, type GitHubResponseRunRead, type GitHubResponseRunState } from "./response-run-state.js";
export { responseRunColumns as githubResponseRunColumns } from "./response-run-state.js";
export type GitHubResponseExecutionInput = {
@@ -14,22 +14,35 @@ export type GitHubResponseExecutionInput = {
deliveryCreatedAt: Date;
};
const finished = (status: string | undefined) => (FINISHED_RUN_STATUSES as readonly string[]).includes(status ?? "");
/** Whether the task is idle and this request settles from the earlier run that
* woke for it, because the latest run belongs to another request. */
export function settlesFromRequestRun(state: GitHubResponseRunState, issueStatus: string) {
return !!state.latestRun && finished(state.latestRun.status) && !state.ownsLatestRequest &&
issueStatus !== "blocked" && !!state.finishedRequestRun;
}
/** `read` is this request's state from a batched page read, if the caller has it. */
export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput, read?: GitHubResponseRunRead) {
const state = read ?? await readGitHubResponseRun(db, input);
if ("forbidden" in state) throw state.forbidden;
const { latestRun, ownsLatestRequest } = state;
const { latestRun, ownsLatestRequest, finishedRequestRun } = state;
const requestRunning = ownsLatestRequest && latestRun?.status === "running";
const terminal = latestRun && ["succeeded", "failed", "interrupted", "timed_out", "cancelled"].includes(latestRun.status);
const run = terminal && (ownsLatestRequest || input.issueStatus === "blocked") ? latestRun : null;
const terminal = latestRun && finished(latestRun.status);
// Once the task is idle, a request whose own run finished earlier settles
// from that run; otherwise its placeholder would wait for a run that never comes.
const requestRun = settlesFromRequestRun(state, input.issueStatus) ? finishedRequestRun : null;
const run = requestRun ?? (terminal && (ownsLatestRequest || input.issueStatus === "blocked") ? latestRun : null);
const answersRequest = ownsLatestRequest || !!requestRun;
const reply = run && ownsLatestRequest ? await githubRunReplyState(db, {
const reply = run && answersRequest ? await githubRunReplyState(db, {
companyId: input.companyId, endpointId: input.endpointId, issueId: input.issueId, runId: run.id,
}) : "none";
const paused = !!run ? input.issueStatus === "blocked" && !ownsLatestRequest
const paused = !!run ? input.issueStatus === "blocked" && !answersRequest
: input.issueStatus === "blocked" && latestRun?.status !== "running";
const presentationPending = !!run && ownsLatestRequest && run.nativePresentationPending && reply === "none";
const passiveResponseWait = !!run && ownsLatestRequest && run.passiveResponseWait && reply === "none";
const presentationPending = !!run && answersRequest && run.nativePresentationPending && reply === "none";
const passiveResponseWait = !!run && answersRequest && run.passiveResponseWait && reply === "none";
const body = presentationPending ? undefined : run ? reply === "confirmed" ? "This request has been handled. See the response in this conversation."
: paused ? "Work is paused. Your request is saved. See the Paperclip task for details."
: run.status === "succeeded" ? "This turn ended without publishing a final response. See the Paperclip task for details."
@@ -40,6 +53,6 @@ export async function githubResponseExecution(db: Db, input: GitHubResponseExecu
versionAt: run ? new Date(Math.max(run.updatedAt.getTime(), input.deliveryCreatedAt.getTime()))
: paused ? input.deliveryCreatedAt : undefined,
version: JSON.stringify([latestRun?.id ?? null, latestRun?.status ?? null,
latestRun?.updatedAt.toISOString() ?? null, ownsLatestRequest, input.issueStatus === "blocked", reply]),
latestRun?.updatedAt.toISOString() ?? null, ownsLatestRequest, input.issueStatus === "blocked", reply, requestRun?.id ?? null]),
};
}
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { and, desc, eq, or, sql } from "drizzle-orm";
import { and, inArray, desc, eq, or, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { chatMessageLinks, createDb, heartbeatRuns, type Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
@@ -31,6 +31,36 @@ async function previousReadGitHubResponseRun(db: Db, input: Input) {
return { latestRun, ownsLatestRequest };
}
/** The request's own run when it has finished: the latest run that woke for
* the request (by wake comment or accepted identity context), only if finished. */
async function referenceFinishedRequestRun(db: Db, input: Input) {
if (!input.issueId) return { finished: null, ownRunActive: false };
const [own] = await db.select(responseRunColumns).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId),
sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${input.issueId}`,
sql`exists (select 1 from ${chatMessageLinks} l where l.company_id = ${input.companyId}::uuid
and l.endpoint_id = ${input.endpointId}::uuid and l.delivery_id = ${input.deliveryId}::uuid and l.direction = 'inbound'
and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'
or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text
or exists (select 1 from run_identity_contexts c where c.id = ${heartbeatRuns.activeIdentityContextId}
and c.run_id = ${heartbeatRuns.id} and c.company_id = ${heartbeatRuns.companyId} and c.status = 'accepted'
and c.message_id = l.comment_id)))`,
)).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);
const finishedStatuses = ["succeeded", "failed", "interrupted", "timed_out", "cancelled"];
const done = !!own && finishedStatuses.includes(own.status);
// Whether an older run of the request finished while its newest one is still active.
const [older] = own && !done ? await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId),
inArray(heartbeatRuns.status, finishedStatuses),
sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${input.issueId}`,
sql`exists (select 1 from ${chatMessageLinks} l where l.company_id = ${input.companyId}::uuid
and l.endpoint_id = ${input.endpointId}::uuid and l.delivery_id = ${input.deliveryId}::uuid and l.direction = 'inbound'
and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'
or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`,
)).limit(1) : [];
return { finished: done ? own : null, olderFinishedWhileActive: !!older };
}
function random(seed: number) {
let state = seed >>> 0;
return () => {
@@ -187,7 +217,8 @@ suite("GitHub response run state", () => {
before.push(await previousReadGitHubResponseRun(db, input));
after.push(await readGitHubResponseRun(db, input));
}
expect(after).toEqual(before);
// The prior production query stays the oracle for the latest run and ownership.
expect(after.map(({ finishedRequestRun: _, ...state }) => state)).toEqual(before);
expect(before.filter(result => result.ownsLatestRequest).length).toBeGreaterThan(20);
expect(before.filter(result => result.latestRun && !result.ownsLatestRequest).length).toBeGreaterThan(20);
expect(before.filter(result => !result.latestRun).length).toBeGreaterThan(20);
@@ -195,6 +226,20 @@ suite("GitHub response run state", () => {
.toEqual(new Set(["native", "legacy"]));
}, 120_000);
it("returns the request's own run only once it has finished", async () => {
let olderFinishedWhileActive = 0, finished = 0;
for (const input of inputs()) {
const state = await readGitHubResponseRun(db, input);
const reference = await referenceFinishedRequestRun(db, input);
// An older finished run never stands in for the request's own run that is still active.
expect(state.finishedRequestRun?.id ?? null, JSON.stringify(input)).toBe(state.latestRun ? reference.finished?.id ?? null : null);
if (reference.olderFinishedWhileActive) olderFinishedWhileActive++;
if (state.finishedRequestRun) finished++;
}
expect(olderFinishedWhileActive).toBeGreaterThan(0);
expect(finished).toBeGreaterThan(20);
}, 120_000);
it("reads a page of requests in one latest-run statement with the state each single read returns", async () => {
const all = inputs();
const single = [];
@@ -204,7 +249,12 @@ suite("GitHub response run state", () => {
let batch;
try { batch = await readGitHubResponseRuns(db, all); } finally { db.$client.options.debug = prior; }
expect(batch).toEqual(single);
expect(statements.filter(query => /from "heartbeat_runs"|join "heartbeat_runs"/.test(query))).toHaveLength(1);
// One statement for the latest runs, plus one for the earlier finished
// runs of the page when any request has one.
const runReads = statements.filter(query => /from "heartbeat_runs"|join "heartbeat_runs"/.test(query));
expect(runReads.filter(query => /github_response_request/.test(query))).toHaveLength(1);
expect(runReads.length).toBe(batch.some(state => "finishedRequestRun" in state && state.finishedRequestRun &&
state.finishedRequestRun.id !== state.latestRun?.id) ? 2 : 1);
}, 120_000);
it("reads a few runs of the issue, not the agent's whole run history", async () => {
@@ -1,8 +1,14 @@
import { and, eq, sql, type SQL } from "drizzle-orm";
import { chatMessageLinks, heartbeatRuns, type Db } from "@paperclipai/db";
import { and, eq, inArray, sql, type SQL } from "drizzle-orm";
import { chatMessageLinks, heartbeatRuns, runIdentityContexts, type Db } from "@paperclipai/db";
import type { HttpError } from "../../../errors.js";
import { chatRunSourceMessageId, chatRunSourceMessageIds } from "../run-origin.js";
/** Run statuses after which a run publishes nothing more for its request. */
export const FINISHED_RUN_STATUSES = ["succeeded", "failed", "interrupted", "timed_out", "cancelled"] as const;
/** `status in (...)` for FINISHED_RUN_STATUSES, for raw SQL over a run alias. */
export const finishedRunStatusSql = (status: SQL) =>
sql`${status} in (${sql.raw(FINISHED_RUN_STATUSES.map(value => `'${value}'`).join(", "))})`;
export const responseRunColumns = {
id: heartbeatRuns.id,
companyId: heartbeatRuns.companyId,
@@ -54,7 +60,10 @@ export type GitHubResponseRunInput = {
deliveryId: string; sourceMessageId: string | null;
};
type RunRow = Omit<Awaited<ReturnType<typeof readRunRows>>[number], "ordinal">;
export type GitHubResponseRunState = { latestRun: Omit<RunRow, "wokeForRequest"> | undefined; ownsLatestRequest: boolean };
type ResponseRun = Omit<RunRow, "wokeForRequest" | "requestRunId">;
export type GitHubResponseRunState = { latestRun: ResponseRun | undefined; ownsLatestRequest: boolean;
/** The latest finished run that woke for this request, which can differ from the latest run. */
finishedRequestRun: ResponseRun | null };
/** The state of one request of a batch, or the 403 that its single read throws. */
export type GitHubResponseRunRead = GitHubResponseRunState | { forbidden: HttpError };
@@ -76,12 +85,39 @@ const latestRunId = (of: Of) => sql`(select latest.id from (
and r.context_snapshot->>'issueId' = ${of.issueId}::text and r.agent_id = ${of.agentId}::uuid
order by r.created_at desc, r.id desc limit 1)
) latest order by latest.created_at desc, latest.id desc limit 1)`;
/** Whether the run woke for one of the request's inbound comments. */
const wokeForRequest = (of: Of) => sql<boolean>`exists (select 1 from ${chatMessageLinks} l
/** Whether one of the request's inbound comments matches `match`. */
const requestLink = (of: Of, match: (commentId: SQL) => SQL) => sql<boolean>`exists (select 1 from ${chatMessageLinks} l
where l.company_id = ${of.companyId}::uuid and l.endpoint_id = ${of.endpointId}::uuid
and l.delivery_id = ${of.deliveryId}::uuid and l.direction = 'inbound'
and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'
or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`;
and l.delivery_id = ${of.deliveryId}::uuid and l.direction = 'inbound' and (${match(sql`l.comment_id`)}))`;
/** Whether a run with this context snapshot woke for the comment. */
const wokeFor = (snapshot: SQL, commentId: SQL) => sql`${commentId}::text = ${snapshot}->>'wakeCommentId'
or coalesce(${snapshot}->'wakeCommentIds', '[]'::jsonb) ? ${commentId}::text`;
/** Whether the run woke for one of the request's inbound comments. */
const wokeForRequest = (of: Of) => requestLink(of, commentId => wokeFor(sql`${heartbeatRuns.contextSnapshot}`, commentId));
/** The request's own run when it has finished: the latest run that woke for
* the request, by a wake comment or by an accepted identity context for the
* request's comment. Null while that run is still queued or running. A newer
* run woken by another request can follow it within seconds, so the task's
* latest run alone cannot say how this request ended. */
/** Whether the run aliased `run` is bound to the issue: its native issue, else
* its context snapshot's issue. Index-friendly form of
* coalesce(native_issue_id, context_snapshot->>'issueId'). */
export const runBoundToIssue = (run: SQL, issueId: Value) => sql`(${run}.native_issue_id = ${issueId}::uuid
or (${run}.native_issue_id is null and ${run}.context_snapshot->>'issueId' = ${issueId}::text))`;
/** Whether the run aliased `run` woke for the comment: by a wake comment, or by
* an accepted identity context for that comment. */
export const runWokeForComment = (run: SQL, commentId: SQL) => sql`(${wokeFor(sql`${run}.context_snapshot`, commentId)}
or exists (select 1 from ${runIdentityContexts} c where c.id = ${run}.active_identity_context_id
and c.run_id = ${run}.id and c.company_id = ${run}.company_id and c.status = 'accepted' and c.message_id = ${commentId}))`;
const finishedRequestRunId = (of: Of) => sql<string | null>`(select case
when ${finishedRunStatusSql(sql`q.status`)} then q.id end
from ${heartbeatRuns} q
where q.company_id = ${of.companyId}::uuid and q.agent_id = ${of.agentId}::uuid
and ${runBoundToIssue(sql`q`, of.issueId)}
and ${requestLink(of, commentId => runWokeForComment(sql`q`, commentId))}
order by q.created_at desc, q.id desc limit 1)`;
const request = sql.identifier("github_response_request");
const column = (name: string) => sql`${request}.${sql.identifier(name)}`;
@@ -94,7 +130,7 @@ const columns: Array<[keyof Of, string]> = [["companyId", "company_id"], ["endpo
async function readRunRows(db: Db, inputs: Array<GitHubResponseRunInput & { issueId: string }>) {
const of = Object.fromEntries(columns.map(([key, name]) => [key, column(name)])) as Of;
return db.select({ ordinal: sql<number>`${column("ordinal")}`.mapWith(Number), ...responseRunColumns,
wokeForRequest: wokeForRequest(of) })
wokeForRequest: wokeForRequest(of), requestRunId: finishedRequestRunId(of) })
.from(sql`unnest(${sql.join(columns.map(([key]) => sql`${sql.param(inputs.map(input => input[key]))}::uuid[]`), sql`, `)})
with ordinality as ${request}(${sql.join([...columns.map(([, name]) => sql.identifier(name)), sql.identifier("ordinal")], sql`, `)})
cross join lateral (select ${latestRunId(of)} as id) latest_request_run`)
@@ -102,24 +138,36 @@ async function readRunRows(db: Db, inputs: Array<GitHubResponseRunInput & { issu
sql`${heartbeatRuns.companyId} = ${column("company_id")}`));
}
function ownership(input: GitHubResponseRunInput, row: RunRow | undefined, originMessageId: string | null): GitHubResponseRunState {
if (!row) return { latestRun: undefined, ownsLatestRequest: false };
const { wokeForRequest: requestRunIsLatest, ...latestRun } = row;
function ownership(input: GitHubResponseRunInput, row: RunRow | undefined, originMessageId: string | null,
finished: Map<string, ResponseRun>): GitHubResponseRunState {
if (!row) return { latestRun: undefined, ownsLatestRequest: false, finishedRequestRun: null };
const { wokeForRequest: requestRunIsLatest, requestRunId, ...latestRun } = row;
const ownsLatestRequest = requestRunIsLatest ||
(!!input.sourceMessageId && originMessageId === input.sourceMessageId);
return { latestRun, ownsLatestRequest };
return { latestRun, ownsLatestRequest,
finishedRequestRun: !requestRunId ? null : requestRunId === latestRun.id ? latestRun : finished.get(requestRunId) ?? null };
}
/** The response columns of the earlier finished runs of the rows, in one statement. */
async function readFinishedRuns(db: Db, rows: RunRow[]) {
const ids = [...new Set(rows.flatMap(row => row.requestRunId && row.requestRunId !== row.id ? [row.requestRunId] : []))];
const found = new Map<string, ResponseRun>();
if (!ids.length) return found;
for (const run of await db.select(responseRunColumns).from(heartbeatRuns).where(inArray(heartbeatRuns.id, ids))) found.set(run.id, run);
return found;
}
/** Shared request ownership and presentation state for delivery and recovery. */
export async function readGitHubResponseRun(db: Db, input: GitHubResponseRunInput): Promise<GitHubResponseRunState> {
const { issueId } = input;
if (!issueId) return { latestRun: undefined, ownsLatestRequest: false };
if (!issueId) return { latestRun: undefined, ownsLatestRequest: false, finishedRequestRun: null };
const of = { ...input, issueId };
const [row] = await db.select({ ...responseRunColumns, wokeForRequest: wokeForRequest(of) }).from(heartbeatRuns)
const [row] = await db.select({ ...responseRunColumns, wokeForRequest: wokeForRequest(of),
requestRunId: finishedRequestRunId(of) }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId(of)}`));
const originMessageId = row?.activeIdentityContextId ? await chatRunSourceMessageId(db, row,
{ allowLegacyWakeComment: true, provider: "github" }) : null;
return ownership(input, row, originMessageId);
return ownership(input, row, originMessageId, await readFinishedRuns(db, row ? [row] : []));
}
/** `readGitHubResponseRun` for a page of requests: one latest-run read for the
@@ -134,11 +182,12 @@ export async function readGitHubResponseRuns(db: Db, inputs: GitHubResponseRunIn
}
const runs = [...new Map([...found.values()].filter(row => row.activeIdentityContextId).map(row => [row.id, row])).values()];
const checked = await chatRunSourceMessageIds(db, runs, { allowLegacyWakeComment: true, provider: "github" });
const finished = await readFinishedRuns(db, [...found.values()]);
const origins = new Map(runs.map((run, index) => [run.id, checked[index]!]));
return inputs.map((input, index) => {
const row = found.get(index);
const origin = row ? origins.get(row.id) : undefined;
if (origin && "forbidden" in origin) return { forbidden: origin.forbidden };
return ownership(input, row, origin?.messageId ?? null);
return ownership(input, row, origin?.messageId ?? null, finished);
});
}
@@ -9,6 +9,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notific
import { idleWorkSnapshot } from "../../task-admission.js";
import { registerGitHubAcknowledgementWork } from "./acknowledgement-work.js";
import { registerGitHubTerminalResponseWork } from "./terminal-response-work.js";
import { readGitHubResponseRuns } from "./response-run-state.js";
const support = await getEmbeddedPostgresTestSupport();
@@ -131,7 +132,8 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", ()
const sweep = statements.filter(query => /"chat_actions"|heartbeat_runs|run_identity_contexts|chat_message_links/.test(query));
return {
statements: sweep.length,
provenance: sweep.filter(query => /from "run_identity_contexts"/.test(query)).length,
// Requester provenance reads, not the page read that names identity contexts in a subquery.
provenance: sweep.filter(query => /from "run_identity_contexts"/.test(query) && !/github_response_request/.test(query)).length,
};
}
const finals = async (actionIds: string[]) => (await db.select({ result: chatActions.result }).from(chatActions)
@@ -167,6 +169,51 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", ()
expect(first.statements).toBeLessThanOrEqual(2 * 5);
}, 300_000);
it("settles requests whose own run finished before another request's run, with a batched page read", async () => {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
const f = await seed();
const base = Date.UTC(2026, 9, 28);
// Each waiting request's own run finished just before the newest request's
// run started. Half are linked by a wake comment, half only by an accepted
// identity context for the request's comment.
for (const [index, request] of f.stale.entries()) {
const issueNumber = f.runs.findIndex(run => run.issueId === request.issueId) + 1;
const runId = randomUUID(), contextId = randomUUID(), byIdentity = index % 2 === 1;
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId,
nativeIssueId: request.issueId, issueId: request.issueId, scopeKind: "issue", status: "succeeded",
responsibleUserId: "requester", activeIdentityContextId: byIdentity ? contextId : null,
contextSnapshot: byIdentity ? { issueId: request.issueId } : { issueId: request.issueId, wakeCommentId: request.commentId },
createdAt: new Date(base + issueNumber * 3_600_000 - (index + 1) * 1_000) });
if (byIdentity) await db.insert(runIdentityContexts).values({ id: contextId, companyId: f.companyId, runId, revision: 1,
responsibleUserId: "requester", messageId: request.commentId, cause: "chat_request", correlationId: runId, status: "accepted" });
}
const inputs = f.stale.map(request => ({ companyId: f.companyId, endpointId: f.endpointId, agentId: f.agentId,
issueId: request.issueId, deliveryId: request.deliveryId, sourceMessageId: request.commentId }));
let reads: Awaited<ReturnType<typeof readGitHubResponseRuns>> = [];
const read = await observe(async () => { reads = await readGitHubResponseRuns(db, inputs); });
// The latest runs, their requester provenance, and the earlier runs: each one statement for the page.
expect(read.statements).toBeLessThanOrEqual(4);
expect(reads.every(state => !("forbidden" in state) && !state.ownsLatestRequest && state.finishedRequestRun)).toBe(true);
// One earlier run is still publishing its reply: that request waits.
const publishing = f.stale[0]!;
const [publishingRun] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, f.companyId), sql`${heartbeatRuns.contextSnapshot}->>'wakeCommentId' = ${publishing.commentId}`));
const [conversation] = await db.select({ conversationId: chatActions.conversationId }).from(chatActions)
.where(eq(chatActions.id, publishing.actionId));
await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpointId,
conversationId: conversation!.conversationId, kind: "github_review_publication",
providerActionId: `github_publication:${randomUUID()}`, status: "processing",
payload: { operation: "comment", session: { companyId: f.companyId, issueId: publishing.issueId,
runId: publishingRun!.id, agentId: f.agentId } } });
await start(); await advance(31_000);
const settled = f.stale.filter(request => request !== publishing);
expect(new Set(acknowledged)).toEqual(new Set(settled.map(request => request.deliveryId)));
expect(await finals(settled.map(request => request.actionId))).toBe(settled.length);
const [waiting] = await db.select().from(chatActions).where(eq(chatActions.id, publishing.actionId));
expect(waiting).toMatchObject({ status: "processed" });
expect(waiting!.result?.final).not.toBe(true);
}, 300_000);
it("acknowledges every owed request of a page when one run's requester provenance changed", async () => {
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
const f = await seed("received");
@@ -0,0 +1,18 @@
import { describe, expect, it } from "vitest";
import { holdsPublishedResponse } from "./chat-github-response-comments.js";
const markers = "\n\n<!-- paperclip-pr-response:a -->\n<!-- paperclip-response:b -->\n<!-- paperclip-response-version:2026-11-23T00:00:00.000Z -->";
const final = "\n<!-- paperclip-response-state:final -->";
describe("holdsPublishedResponse", () => {
it("protects a final review, even one that starts with a status sentence", () => {
expect(holdsPublishedResponse(`## Review — 4/5\n\nLooks good.${markers}${final}`)).toBe(true);
expect(holdsPublishedResponse(`This turn ended without publishing a final response. The fix landed later.${markers}${final}`)).toBe(true);
});
it("treats placeholders and status notices as replaceable", () => {
expect(holdsPublishedResponse(`Working on this…${markers}`)).toBe(false);
expect(holdsPublishedResponse(`Anything${markers}\n<!-- paperclip-response-kind:status -->${final}`)).toBe(false);
expect(holdsPublishedResponse(`This turn ended without publishing a final response. See the Paperclip task for details.${markers}${final}`)).toBe(false);
expect(holdsPublishedResponse(`Work is paused. Your request is saved. See the Paperclip task for details.${markers}`)).toBe(false);
});
});
@@ -7,6 +7,7 @@ import {
} from "@paperclipai/db";
import { registerGitHubTerminalResponseWork } from "./chat-channels/github/terminal-response-work.js";
import { githubResponseExecution, githubResponseRunColumns as responseRunColumns } from "./chat-channels/github/response-execution.js";
import { FINISHED_RUN_STATUSES, finishedRunStatusSql, runBoundToIssue, runWokeForComment } from "./chat-channels/github/response-run-state.js";
import { notifyChatResponseAvailability } from "./chat-response-availability.js";
import { registerGitHubAcknowledgementWork } from "./chat-channels/github/acknowledgement-work.js";
import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
@@ -33,6 +34,15 @@ type Comment = { id: number; body?: string; html_url: string; user?: { login?: s
const generation = (endpoint: Source["endpoint"]) => (endpoint.setup as { runtimeGeneration?: number }).runtimeGeneration ?? 0;
const stoppedAcknowledgement = Symbol("stopped GitHub acknowledgement");
const actionKey = (deliveryId: string) => `github_response:${deliveryId}`;
const statusMarker = "<!-- paperclip-response-kind:status -->";
// The complete status notices posted before the kind marker existed.
const legacyStatusBodies = new Set(["Work is paused. Your request is saved. See the Paperclip task for details.",
"This turn ended without publishing a final response. See the Paperclip task for details.",
"This turn stopped before completing. See the Paperclip task for details.",
"This request has been handled. See the response in this conversation."]);
/** A reply or review the agent published, as opposed to a placeholder or a Paperclip status notice. */
export const holdsPublishedResponse = (body: string | undefined) => !!body?.includes("<!-- paperclip-response-state:final -->") &&
!body.includes(statusMarker) && !legacyStatusBodies.has(body.split("\n\n<!-- paperclip-")[0]!.trim());
const responseMarker = (source: Source) => isMainPullResponse(source) ? pullResponseMarker(source) : requestResponseMarker(source);
async function findResponseComment(source: Source, api: Api, legacyMarkers: string[] = []): Promise<Comment | null> {
@@ -79,7 +89,9 @@ async function stageResponse(db: Db, source: Source) {
export async function writeGitHubResponseComment(
db: Db, source: Source, api: Api, lease: Lease,
input: { body: string; final: boolean; versionAt?: Date; acknowledgement?: boolean; preserveFinal?: boolean; pausedVersion?: string },
input: { body: string; final: boolean; versionAt?: Date; acknowledgement?: boolean; preserveFinal?: boolean; pausedVersion?: string;
/** A Paperclip status notice (paused, stopped, no reply), not the agent's own words. */
status?: boolean },
assertCurrent: () => Promise<void>,
) {
await assertCurrent();
@@ -87,7 +99,20 @@ export async function writeGitHubResponseComment(
const shared = isMainPullResponse(source);
const target = shared ? await stagePullResponse(db, source) : response;
const versionAt = input.versionAt ?? source.delivery.createdAt;
// The main PR comment is shared by every request. A status notice for one
// request never replaces a newer response or a published review: it settles
// that request against the comment as it stands, so nothing retries it later.
const settleStatus = async (current: { id: string; url: string }, code: string) => {
if (shared) await retireLegacyResponsePlaceholder(source, response.result, current, api, assertCurrent);
await lease.commit(async tx => { await tx.update(chatActions).set({ status: "processed", result: {
...current, final: true, code, versionAt: versionAt.toISOString(),
}, updatedAt: new Date() }).where(and(eq(chatActions.id, response.id),
sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`)); });
return current;
};
if (target.result?.id && Date.parse(String(target.result.versionAt)) > versionAt.getTime()) {
if (shared && input.status)
return settleStatus({ id: String(target.result.id), url: String(target.result.url) }, "status_superseded");
if (!input.acknowledgement) throw conflict("A newer GitHub response has already been published");
if (shared) await retireLegacyResponsePlaceholder(source, response.result,
{ id: String(target.result.id), url: String(target.result.url) }, api, assertCurrent);
@@ -126,10 +151,13 @@ export async function writeGitHubResponseComment(
}
await assertCurrent();
const providerVersion = previous?.body?.match(/<!-- paperclip-response-version:([^ ]+) -->/)?.[1];
const keepsResponse = holdsPublishedResponse(previous?.body);
if (shared && input.status && previous && (keepsResponse || (providerVersion && Date.parse(providerVersion) > versionAt.getTime())))
return settleStatus({ id: String(previous.id), url: previous.html_url }, keepsResponse ? "published_response_kept" : "status_superseded");
if (providerVersion && Date.parse(providerVersion) > versionAt.getTime()) throw conflict("A newer GitHub response has already been published");
const sameRequest = !shared || previous?.body?.includes(requestResponseMarker(source)) === true;
const alreadyFinal = sameRequest && previous?.body?.includes("<!-- paperclip-response-state:final -->") === true;
const body = `${projectSafeChatPublicationText(input.body)}\n\n${marker}${shared ? `\n${requestResponseMarker(source)}` : ""}\n<!-- paperclip-response-version:${versionAt.toISOString()} -->${input.final ? "\n<!-- paperclip-response-state:final -->" : ""}`;
const body = `${projectSafeChatPublicationText(input.body)}\n\n${marker}${shared ? `\n${requestResponseMarker(source)}` : ""}\n<!-- paperclip-response-version:${versionAt.toISOString()} -->${input.status ? `\n${statusMarker}` : ""}${input.final ? "\n<!-- paperclip-response-state:final -->" : ""}`;
const preserved = previous && (previous.body === body || (input.acknowledgement && (sameRequest || (shared && previous.body?.includes("<!-- paperclip-response-state:final -->")))) || (alreadyFinal && !input.final) ||
(input.preserveFinal && previous.body?.includes("<!-- paperclip-response-state:final -->"))) ? previous : null;
const posted = preserved && (!shared || preserved.body?.includes(marker)) ? preserved : await api.request<Comment>(
@@ -220,7 +248,12 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
sourceMessageId: source.sourceMessageId, issueStatus: source.issueStatus,
deliveryCreatedAt: source.delivery.createdAt,
});
if (execution.reply === "unsettled") throw conflict("GitHub reply is still being resolved");
if (execution.reply === "unsettled") {
// An acknowledged request waits for its reply to settle without
// spending delivery retries; the terminal sweep reads it again.
if (existing.status === "processed" && existing.result?.id) return { id: String(existing.result.id), url: String(existing.result.url) };
throw conflict("GitHub reply is still being resolved");
}
if (execution.presentationPending) return;
if (isMainPullResponse(source) && execution.passiveResponseWait) {
// Preserve the shared assessment when this exact run intentionally waits
@@ -286,7 +319,7 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
}
return writeGitHubResponseComment(db, source, api, lease,
{ body: finalBody ?? (isMainPullResponse(source) && !requestRunning ? "Review queued…" : "Working on this…"), final: finalBody !== undefined && !requestPaused,
acknowledgement: finalBody === undefined, preserveFinal, pausedVersion,
acknowledgement: finalBody === undefined, status: finalBody !== undefined, preserveFinal, pausedVersion,
...(finalBody !== undefined ? { versionAt: finalVersionAt ?? new Date() } : {}) }, assertCurrent);
});
}
@@ -366,7 +399,7 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
const source = await context(link.deliveryId!);
const [current] = await db.select(responseRunColumns).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, input.companyId)));
if (!current || current.agentId !== source.endpoint.assignedAgentId ||
!["succeeded", "failed", "interrupted", "timed_out", "cancelled"].includes(current.status) ||
!(FINISHED_RUN_STATUSES as readonly string[]).includes(current.status) ||
source.endpoint.id !== input.endpointId || source.conversation.issueId !== input.issueId ||
boundRunIssueId(current) !== input.issueId)
throw forbidden("GitHub failure authority changed");
@@ -414,16 +447,19 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
sql`exists (select 1 from ${heartbeatRuns} r where r.company_id = ${chatActions.companyId}
and r.agent_id = ${chatEndpoints.assignedAgentId}
and coalesce(r.native_issue_id::text, r.context_snapshot->>'issueId') = ${chatConversations.issueId}::text
and r.status in ('succeeded', 'failed', 'interrupted', 'timed_out', 'cancelled')
and ${finishedRunStatusSql(sql`r.status`)}
and not exists (select 1 from ${heartbeatRuns} newer where newer.company_id = r.company_id
and newer.agent_id = r.agent_id
and coalesce(newer.native_issue_id::text, newer.context_snapshot->>'issueId') = ${chatConversations.issueId}::text
and (newer.created_at, newer.id) > (r.created_at, r.id))
and (${issues.status} = 'blocked' or r.active_identity_context_id is not null or exists (select 1 from ${chatMessageLinks} l
join ${heartbeatRuns} q on q.company_id = r.company_id and q.agent_id = r.agent_id
and ${runBoundToIssue(sql`q`, sql`${chatConversations.issueId}`)}
and ${finishedRunStatusSql(sql`q.status`)}
where l.company_id = ${chatActions.companyId} and l.endpoint_id = ${chatActions.endpointId}
and l.delivery_id = ${chatActions.deliveryId} and l.direction = 'inbound'
and (l.comment_id::text = r.context_snapshot->>'wakeCommentId'
or coalesce(r.context_snapshot->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))))`,
-- The run that woke for this request; a newer run may follow it.
and ${runWokeForComment(sql`q`, sql`l.comment_id`)})))`,
)).orderBy(asc(chatActions.updatedAt)).limit(limit);
for (const row of stopped) if (row.deliveryId) await tryAcknowledge(row.deliveryId);
return stopped.length;