fix(recovery): report an unrunnable recovery continuation once instead of every sweep (#21288)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Execution recovery delivers a recorded continuation to the task's
agent through a sweep that runs about every 15 seconds.
> - The sweep keeps a continuation `pending` until a wake for it is
admitted. A skipped wake leaves it pending, and the next pass tries
again.
> - The workspace preflight refuses a wake for an isolated git-worktree
task that has no project and no reusable workspace
(`workspace_worktree_requires_project`). Each refusal blocks the task
again, writes an activity row and posts a system comment.
> - Thus one refused continuation produced a new "blocked before
dispatch" comment about every 15 seconds, without end. A person's chat
collected hundreds of them in a few hours.
> - This pull request closes the continuation that the preflight
refuses, in the same transaction as the refusal.
> - The benefit is that the task is reported once and then waits for a
person, instead of a tight retry loop that floods its thread.

## Linked Issues or Issue Description

Refs #21250 (merged; fixes one way to reach this state: admission
refused a fresh isolated continuation of a projectless task. This PR
bounds the loop for any continuation that the preflight refuses.)

**What happened?**
A conversation task had `executionWorkspaceSettings.mode =
isolated_workspace`, no project, and a bound adapter-managed workspace.
A run failed at bootstrap. The fresh-continuation fallback could not
prove that the old writer had stopped, so it chose
`fresh_isolated_workspace`, cleared the task's `executionWorkspaceId`,
and recorded a continuation with `continuationDelivery: "pending"`. The
recovery wake sets `forceFreshSession`, so the preflight found no prior
session workspace. With no project and no binding, the preflight refused
the wake as `workspace_worktree_requires_project`. The continuation
stayed `pending`, so `deliverReconciledExecutions` woke it again on
every pass. Each pass posted the same system comment and activity row
(about every 15 s, for hours).

**Expected behavior**
A continuation that cannot start is reported once. The task stays
blocked with one clear comment until a person changes its workspace
settings. The sweep does not retry it in a tight loop.

**Steps to reproduce**
1. Enable isolated workspaces. Give a task `mode: isolated_workspace`,
`git_worktree` strategy, no project and no execution workspace.
2. Record a resolved recovery action for it with `continuationDelivery:
"pending"` and a valid `executionReconciliation`.
3. Run `deliverReconciledExecutions` three times.
4. See three "blocked before dispatch" comments and three
`issue.workspace_preflight_blocked` rows. The continuation stays
`pending`.

## What Changed

- `server/src/services/heartbeat/queue.ts`: when the workspace preflight
refuses a validated execution-reconciliation wake
(`reconciledRecoveryActionId`), it now sets the action's
`continuationDelivery` to `invalidated` with
`continuationInvalidatedReason: "workspace_worktree_requires_project"`,
and settles its coalesced holds in the same transaction as the block,
the comment, and the activity row. The sweep only reads `pending`
continuations, so it stops. (`queue.ts` already exceeded 1,000 lines;
this adds 10 lines inside the existing preflight refusal transaction
rather than splitting the transactional refusal path.)
- `server/src/__tests__/issue-recovery-actions.test.ts`: new regression
`"reports a reconciled continuation with an unrunnable workspace once
instead of retrying every sweep"` verifying across 3
`deliverReconciledExecutions` sweeps that only 1 comment, 1
`issue.workspace_preflight_blocked` activity row, and 1 skipped wakeup
request are recorded, the task is blocked, the primary continuation is
`invalidated` with `workspace_worktree_requires_project`, and a
coalesced sibling hold is also settled to `invalidated`.

## Verification

- Red, on unfixed `origin/master` (`2d06567795`): `cd server && npx
vitest run src/__tests__/issue-recovery-actions.test.ts -t "unrunnable
workspace once"` failed with `AssertionError: expected [ …(3) ] to have
a length of 1 but got 3` (three sweeps, three duplicate comments).
- Green, on rebased head (`7b2c4cdbda`):
- `cd server && npx vitest run
src/__tests__/issue-recovery-actions.test.ts -t "unrunnable workspace
once"`: 1 passed (120 skipped).
- `cd server && npx vitest run
src/__tests__/issue-recovery-actions.test.ts
src/__tests__/completed-turn-cleanup-hold-settle.test.ts`: 2 files, 131
passed (121 + 10).
  - `pnpm --filter @paperclipai/server typecheck`: passed.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-recovery-actions.test.ts`: passed (110
nightly suites validated, 1 test file checked).
- `pnpm verify --explain` selected 1,944/2,301 Vitest files because
`queue.ts` is a shared server hub; focused recovery suites passed
locally and PR CI supplies full typecheck, build, and sharded suite
coverage.

## Risks

- Low risk. The change only runs on the preflight's refusal path, and
only for a validated execution-reconciliation wake.
- After this change, the refused continuation does not run by itself
when a person later fixes the workspace settings. The person's next
message or Retry starts the task through normal admission. This is the
same contract as the existing `in_review` invalidation.
- No migration. No schema change. No new query on the normal admission
path.

## Model Used

- Original PR: Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used
through Claude Code with tool use.
- Rebase onto `master`, conflict resolution, strengthened regression
test, and verification: Claude Opus 4.6 (`claude-opus-4-6`), Anthropic,
used through Antigravity with tool use (shell, file edits, git/gh).

## 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: lucktastic <13757243+lucktastic@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-25 15:31:34 -06:00
1 parent 68e92bcd5d
commit 7b446b4504
2 files changed
+67

No files matched your search

@@ -2758,6 +2758,63 @@ describeEmbeddedPostgres("issue recovery actions", () => {
},
);
it("reports a reconciled continuation with an unrunnable workspace once instead of retrying every sweep", async () => {
const { action, companyId, coderId, heartbeat, sourceIssueId } = await seedReconciledDelivery();
const [coalesced] = await db.insert(issueRecoveryActions).values({
companyId,
sourceIssueId,
kind: "active_run_watchdog",
status: "resolved",
outcome: "restored",
ownerType: "board",
returnOwnerAgentId: coderId,
cause: "uncertain_external_action",
fingerprint: `coalesced:${action.id}`,
nextAction: "Follow primary continuation.",
evidence: {
continuationDelivery: "coalesced",
coalescedIntoRecoveryActionId: action.id,
},
}).returning();
await db.update(issues).set({
projectId: null,
executionWorkspaceId: null,
executionWorkspacePreference: "reuse_existing",
executionWorkspaceSettings: { mode: "isolated_workspace", workspaceStrategy: { type: "git_worktree" } },
}).where(eq(issues.id, sourceIssueId));
const settings = instanceSettingsService(db);
const prior = (await settings.getExperimental()).enableIsolatedWorkspaces;
await settings.updateExperimental({ enableIsolatedWorkspaces: true });
try {
for (let sweep = 0; sweep < 3; sweep += 1)
await deliverReconciledExecutions(db, heartbeat.wakeup);
} finally {
await settings.updateExperimental({ enableIsolatedWorkspaces: prior });
}
const comments = await db.select({ body: issueComments.body }).from(issueComments)
.where(eq(issueComments.issueId, sourceIssueId));
expect(comments).toHaveLength(1);
expect(comments[0]!.body).toContain("before dispatch because its workspace settings are not runnable");
expect(await db.select().from(activityLog).where(and(
eq(activityLog.entityId, sourceIssueId),
eq(activityLog.action, "issue.workspace_preflight_blocked"),
))).toHaveLength(1);
expect(await db.select().from(agentWakeupRequests).where(
eq(agentWakeupRequests.idempotencyKey, `execution-reconciliation:${action.id}`),
)).toHaveLength(1);
const [task] = await db.select({ status: issues.status }).from(issues).where(eq(issues.id, sourceIssueId));
expect(task!.status).toBe("blocked");
const [receipt] = await db.select().from(issueRecoveryActions)
.where(eq(issueRecoveryActions.id, action.id));
expect(receipt!.evidence).toMatchObject({
continuationDelivery: "invalidated",
continuationInvalidatedReason: "workspace_worktree_requires_project",
});
const [settledCoalesced] = await db.select().from(issueRecoveryActions)
.where(eq(issueRecoveryActions.id, coalesced!.id));
expect(settledCoalesced!.evidence.continuationDelivery).toBe("invalidated");
});
it("keeps reconciliation pending behind unrelated issue work without creating a second deferred outbox", async () => {
const { action, heartbeat, sourceIssueId, companyId, coderId } =
await seedReconciledDelivery();
+10
View File
@@ -4608,6 +4608,16 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
.returning();
if (blocked) await emitSystemTaskBlockedAfterCommit(tx, blocked, issue.status);
}
// A recovery continuation cannot run until a person changes the
// task's workspace settings. Close it here so the delivery sweep
// does not retry it (and repost this comment) on every pass.
if (reconciledRecoveryActionId) {
await tx.update(issueRecoveryActions).set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify(
{ continuationDelivery: "invalidated", continuationInvalidatedReason: WORKSPACE_WORKTREE_REQUIRES_PROJECT_CODE })}::jsonb` })
.where(and(eq(issueRecoveryActions.companyId, issue.companyId), eq(issueRecoveryActions.id, reconciledRecoveryActionId)));
await settleCoalescedFreshContinuationHolds(tx as unknown as Db, { companyId: issue.companyId,
primaryId: reconciledRecoveryActionId, delivery: "invalidated" });
}
await insertIssueComment(tx, {
companyId: issue.companyId,
issueId: issue.id,