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

@@ -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;