fix(server): bound accepted-interaction continuation recovery (#9656)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Heartbeat recovery keeps assigned issues moving when a run or
continuation path disappears
> - Accepted issue-thread interactions can create a continuation wake
after an agent previously parked for review
> - The recovery sweep could requeue that accepted-interaction wake
while the queued-run gate cancelled it using the older pre-acceptance
park summary
> - That cancellation path had no bound, so recovery could repeat the
same wake and cancellation indefinitely
> - This pull request makes accepted-interaction evidence supersede the
older park and caps repeated recovery cancellations at three attempts
> - The benefit is that accepted work resumes normally, while genuine
repeated failures become a visible dependency wait or escalation instead
of a cancel loop

## Linked Issues or Issue Description

Refs #9331

The accepted-interaction continuation recovery added by #9331 can
encounter a stale continuation summary written before approval. The
sweep requeues a continuation carrying the accepted interaction
timestamp, but queued-run invalidation cancels it because the older
summary says to wait for review. Recovery then sees the accepted
interaction without a successful run and requeues again. This PR
prevents that stale-summary cancellation and adds a bounded fallback if
three equivalent cancellations have already occurred.

## What Changed

- Let queued continuation wakes with a parseable `interactionResolvedAt`
bypass a pre-acceptance waiting-for-review park summary.
- Count consecutive unsuccessful continuation runs for the same issue
and agent since interaction acceptance; after three review-park
cancellations, convert a real dependency wait or use the existing
visible escalation path.
- Add focused regression coverage for the park bypass, unchanged
non-interaction park behavior, below-cap requeue, cap escalation, and
successful-run skip.
- Document the accepted-interaction precedence and bounded requeue
contract in execution semantics §9.2.

## Verification

- `pnpm vitest run
server/src/__tests__/heartbeat-process-recovery.test.ts -t "accepted
interaction continuation recovery|accepted interaction recovery after
its continuation succeeds|requeues accepted interaction continuations
stranded"`
- `pnpm vitest run
server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts -t
"pre-acceptance review park|continuation summary parks executor work"`
- `pnpm --filter @paperclipai/server typecheck`

## Risks

- Low risk: the park bypass only applies when the queued context
contains a parseable interaction resolution timestamp.
- The retry bound is scoped to unsuccessful `issue_continuation_needed`
runs for the same company, issue, agent, error code, and post-acceptance
time window.
- No schema, migration, API, or UI changes.

> 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

- OpenAI Codex, exact model ID `gpt-5.5`, high-reasoning coding mode
with repository tool use and command execution; context-window size was
not exposed by the runtime.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-07-16 02:34:20 -05:00
1 parent 3124dd0f1e
commit 4f9894df44
5 files changed
+295 -1

No files matched your search

+3
View File
@@ -10505,10 +10505,13 @@ export function heartbeatService(db: Db, options: HeartbeatServiceOptions = {})
const resumeIntent = context.resumeIntent === true || context.followUpRequested === true;
const wakeReason = readNonEmptyString(context.wakeReason);
const retryReason = readNonEmptyString(context.retryReason) ?? run.scheduledRetryReason ?? null;
const interactionResolvedAt = readNonEmptyString(context.interactionResolvedAt);
const hasResolvedInteractionEvidence = interactionResolvedAt !== null && !Number.isNaN(Date.parse(interactionResolvedAt));
if (
issue.status === "in_progress" &&
!wakeCommentId &&
!hasResolvedInteractionEvidence &&
(wakeReason === "issue_continuation_needed" || retryReason === "issue_continuation_needed")
) {
const queuedWake = parseObject(context.paperclipWake);
+39
View File
@@ -289,6 +289,7 @@ const NON_RETRYABLE_CONTINUATION_ERROR_CODES = new Set<string>([
// issue has a real waiting target we convert it into a normal dependency wait rather
// than escalating it as stranded.
const CONTINUATION_WAITING_ON_REVIEW_ERROR_CODE = "issue_continuation_waiting_on_review";
const INTERACTION_CONTINUATION_REQUEUE_MAX_ATTEMPTS = 3;
const CONTINUATION_RECOVERY_TRANSIENT_MAX_ATTEMPTS = 3;
const CONTINUATION_RECOVERY_DEFAULT_MAX_ATTEMPTS = 1;
@@ -635,7 +636,9 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
async function summarizeRecentContinuationRetries(
companyId: string,
issueId: string,
agentId: string,
errorCodeToMatch: string | null,
since: Date | null = null,
) {
const rows = await db
.select({
@@ -649,7 +652,9 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
.where(
and(
eq(heartbeatRuns.companyId, companyId),
eq(heartbeatRuns.agentId, agentId),
sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = ${issueId}`,
...(since ? [or(gte(heartbeatRuns.createdAt, since), gte(heartbeatRuns.finishedAt, since))] : []),
),
)
.orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id))
@@ -3336,6 +3341,39 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
agentId,
acceptedInteractionResolvedAt,
);
const { consecutive } = await summarizeRecentContinuationRetries(
issue.companyId,
issue.id,
agentId,
CONTINUATION_WAITING_ON_REVIEW_ERROR_CODE,
acceptedInteractionResolvedAt,
);
if (consecutive >= INTERACTION_CONTINUATION_REQUEUE_MAX_ATTEMPTS && latestPostResolutionRun) {
const resolved = await resolveContinuationWaitingOnReview(issue);
if (resolved) {
result.waitingOnReviewResolved += 1;
result.issueIds.push(issue.id);
continue;
}
const updated = await escalateStrandedAssignedIssue({
issue,
previousStatus: issue.status as StrandedPreviousStatus,
latestRun: latestPostResolutionRun,
comment:
`Paperclip stopped requeueing accepted interaction \`${acceptedContinuationInteraction.id}\` after ` +
`${consecutive} consecutive continuation wakes were cancelled while waiting on review. ` +
"Moving the issue to `blocked` so the missing execution path is visible for intervention.",
});
if (updated) {
result.escalated += 1;
result.issueIds.push(issue.id);
} else {
result.skipped += 1;
}
continue;
}
const queued = await enqueueStrandedIssueRecovery({
issueId: issue.id,
agentId,
@@ -3656,6 +3694,7 @@ export function recoveryService(db: Db, deps: { enqueueWakeup: RecoveryWakeup })
const { consecutive, latestFinishedAt } = await summarizeRecentContinuationRetries(
issue.companyId,
issue.id,
agentId,
classification.errorCode,
);
if (consecutive >= classification.maxAttempts) {