fix(github): recover response requests that ran out of retries; restore lost regression tests (#22906)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Review agents answer GitHub pull request threads, and each request's
comment must end in a real reply or an honest final notice
> - After #22672, #22710, #22798 and #22807, new review-bot comments on
staging settle: 0 of 85 comments since the deploy are stuck
> - Two older "Working on this…" comments (PRs #22649 and #22676) still
did not settle. Before those fixes, their requests spent all
acknowledgement retries and were left `failed`, a state no recovery path
reads again
> - Separately, the chat-channels split (#22838) was built from an older
copy of the monolith and dropped the regression tests those fixes added
> - This pull request adds a one-time recovery migration for exhausted
requests and restores the lost regression tests
> - The benefit is that the last stuck comments settle, and the settle
rules stay covered by tests that run on every PR

## Linked Issues or Issue Description

Refs #22672, #22710, #22798, #22807, #22838

**Describe the bug**
Two GitHub request comments from 2026-11-23 still read "Working on
this…" on staging after the settle fixes deployed. Before #22798, an
unsettled reply made each acknowledgement attempt fail with "GitHub
reply is still being resolved", so these requests spent all 8 retries
and stayed `failed` with `retryable: false`. Neither the acknowledgement
sweep (retryable only) nor the terminal sweep (processed only) reads
them again.

**Steps to reproduce**
1. A request's acknowledgement fails 8 times and is left `failed`,
`retryable: false`, with its comment still "Working on this…".
2. Deploy the settle fixes. Nothing reads the request again.

**Expected behavior**
Such a request settles with the current decision once.

## What Changed

- Migration `0509_recover_exhausted_github_responses.sql`: one UPDATE
that returns failed, non-final `github_response_comment` rows that
already hold a posted comment to `processed` (code
`recovered_after_exhausted_retries`, wait key and retry time cleared),
so the terminal sweep settles them. Marked `online_compatible`.
- Restored regression tests dropped by the split, in
`server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts`:
published review kept in the main comment (ended / paused), older status
settles against a newer placeholder, back-to-back runs settle, waited
thread links a later response (including a different-PR guard),
inline-only review link, waited thread settles when the task finishes,
refused reply settles.
- New tests: a failed run whose automatic retry finished the task
(inline and issue threads), and the exhausted-retries recovery.

## Verification

- `github-review-workflow.integration.test.ts` restored + new tests: 11
passed locally. The recovery test shows the comment stuck before the
migration and settled after it.
- Test tree typecheck (`src/__tests__/tsconfig.json`) is clean.
- After deploy: the two remaining placeholders on #22649 and #22676
should settle within a sweep pass; I will check them on staging.

## Risks

- The migration updates only failed, non-final GitHub request rows that
have a posted comment; on staging that is a handful of rows. Each is
read once by the terminal sweep and then settles or waits under the
current rules.
- Restored tests add a few seconds to the GitHub review workflow suite.

## 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-25 05:42:24 -06:00
1 parent 4aaa77e6fc
commit 4622965a25
5 files changed
+5919 -5415

No files matched your search

@@ -43,6 +43,11 @@ const legacyStatusBodies = new Set(["Work is paused. Your request is saved. See
/** 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());
/** A 404 when reading the request's own posted comment: it was deleted on GitHub. */
const responseCommentDeleted = (error: unknown) => {
const details = error instanceof HttpError ? error.details as { code?: string; providerStatus?: number } | undefined : undefined;
return details?.code === "github_response_deleted";
};
const responseMarker = (source: Source) => isMainPullResponse(source) ? pullResponseMarker(source) : requestResponseMarker(source);
async function findResponseComment(source: Source, api: Api, legacyMarkers: string[] = []): Promise<Comment | null> {
@@ -143,7 +148,15 @@ export async function writeGitHubResponseComment(
if (target.result?.id) {
// Never recreate a deleted comment or edit an arbitrary caller-selected ID.
if (!/^[1-9][0-9]*$/.test(String(target.result.id))) throw forbidden("Invalid GitHub response receipt");
previous = await api.request<Comment>(`${item}/${target.result.id}`);
try {
previous = await api.request<Comment>(`${item}/${target.result.id}`);
} catch (error) {
const details = error instanceof HttpError ? error.details as { providerStatus?: number } | undefined : undefined;
// Only a 404 for this exact comment proves it was deleted; a token or
// repository-access failure is not.
if (details?.providerStatus === 404) throw conflict("GitHub response comment was deleted", { code: "github_response_deleted" });
throw error;
}
if (!previous.body?.includes(marker) || previous.user?.login !== source.endpoint.botUsername)
throw forbidden("GitHub response is no longer owned by this App");
} else {
@@ -372,7 +385,8 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
}, async () => { await assertCurrent(); await context(link.deliveryId!); });
} catch (error) {
const details = error instanceof HttpError ? error.details as { code?: string; providerStatus?: number } | undefined : undefined;
if (!response.result?.id || details?.code !== "github_bot_operation_failed" || details.providerStatus !== 404) throw error;
const deleted = responseCommentDeleted(error) || (details?.code === "github_bot_operation_failed" && details.providerStatus === 404);
if (!response.result?.id || !deleted) throw error;
// A human can delete an earlier working comment while the coalesced
// review runs. Settle that exact receipt without recreating the comment
// or blocking the current response and check publication.
@@ -472,11 +486,25 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
if (!row || row.result?.final === true) return;
const attempts = Number(row.result?.attempts ?? 0) + 1;
const denied = error instanceof Error && "status" in error && error.status === 403;
const details = error instanceof HttpError ? error.details as { code?: string; retryable?: boolean } | undefined : undefined;
if (row.result?.id && responseCommentDeleted(error)) {
// Someone deleted the posted comment. Settle the request without
// recreating it, as finishRun does for coalesced requests.
await db.transaction(async tx => {
await notifyChatResponseAvailability(tx, { companyId: row.companyId, deliveryId });
await tx.update(chatActions).set({ status: "cancelled", result: { ...row.result, final: true, code: "response_deleted" },
updatedAt: new Date() }).where(and(eq(chatActions.id, row.id), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
});
return;
}
await db.transaction(async tx => {
await notifyChatResponseAvailability(tx, { companyId: row.companyId, deliveryId });
await tx.update(chatActions).set({ status: denied ? "cancelled" : "failed", result: {
...row.result, attempts, retryable: !denied && attempts < 8,
retryAt: new Date(Date.now() + Math.min(300000, 1000 * 2 ** attempts)).toISOString(),
// Temporary failures (network, rate limit, 5xx) keep retrying with
// backoff up to 5 minutes, then hourly. An error GitHub calls
// permanent stops after 8 attempts, since retrying cannot fix it.
...row.result, attempts, retryable: !denied && (details?.retryable !== false || attempts < 8),
retryAt: new Date(Date.now() + (attempts < 8 ? Math.min(300000, 1000 * 2 ** attempts) : 3_600_000)).toISOString(),
code: denied ? "authorization_changed" : "acknowledgement_unconfirmed",
}, updatedAt: new Date() }).where(and(eq(chatActions.id, row.id), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
});