Files
PaperClipAI/server/src/services/issue-question-context.ts
T
DottaandClaude Opus 5.5 c6c7a61e2c fix(retry): release a Retry held on a resolved decision (#21267)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - When an agent run fails, the task shows a Retry button. Admission
can hold an accepted Retry while a person must answer a pending approval
or question (`decision_pending`).
> - The hold is saved on the deferred Retry receipt. Nothing cleared
that saved reason when the person answered, so the task kept saying
"Retry is waiting for a pending approval or question" when nothing was
left to answer.
> - The deferred-receipt worker drops a refused receipt from its
schedule. No producer hinted it when the decision resolved, so the held
Retry did not start until some unrelated event rescanned the company.
> - A Retry was also held by a confirmation that was already open when
the failed turn was admitted. That turn had already run past the
confirmation, so the Retry added a gate that the original turn did not
have.
> - A person's comment on the task started a continuation, but the held
Retry receipt stayed deferred next to it.
> - This pull request makes a resolved decision release the held Retry
at once, keeps the projection from showing a resolved decision as the
wait, stops holding a Retry on a decision that predates the failed turn,
and settles a held Retry when a comment or answer continues the same
failed run.
> - The benefit is that Retry always works: a person never waits on a
decision that is already resolved.

## Linked Issues or Issue Description

**What happened?**

A board user pressed Retry on blocked tasks. No run started. The task
said "Retry is waiting for a pending approval or question to be
resolved. Your message is saved." In one task, the only interaction was
a `request_confirmation` that the previous successful run created. The
user's later comment started the turn that failed. The confirmation
stayed pending, so every Retry attached to the same held receipt. After
the user rejected the confirmation and sent a new comment, the task
still showed the same wait. No run started until a server restart
rescanned the deferred receipts about three minutes later. The task
projection said `canRetry: true` with the `decision_pending` wait.

**Expected behavior**

An accepted Retry is never held on a decision that is already resolved.
Accepting or rejecting the decision releases a held Retry right away. A
person's comment on the blocked task starts work, and the held Retry is
settled. The task projection never shows a resolved decision as the
Retry wait.

**Steps to reproduce**

1. Let an agent run on a remote runner create a `request_confirmation`
for the task.
2. Let the runner be lost so the run fails with
`native_continuation_requires_reconciliation`, and let saved work
recovery complete.
3. Press Retry. The Retry receipt is saved with `executionWait.reason =
decision_pending`.
4. Reject or accept the confirmation.
5. Observe that the receipt keeps `decision_pending`, the task keeps
showing the wait, and the Retry does not start until an unrelated
rescan.

**Paperclip version or commit**

Staging Core `57aeda190b`. Fixed on top of `origin/master` `53608bd1d6`.

**Deployment mode**

Hosted cloud (staging), remote sandbox runner.

**Agent adapter(s) involved**

`paperclip_runner` (native runtime).

## What Changed

- `hasPendingContinuationDecision` (`explicit-native-continuation.ts`)
is now the single check for a decision that holds a person's
continuation. Admission and the task projection both use it.
- For a Retry, a pending interaction that was created before the failed
source run was created does not hold the Retry. That turn was already
admitted while the decision was open. Decisions that the failed run
created (for example a plan review) still hold the Retry.
- `releaseDecisionHeldExecution` (`deferred-execution-wait.ts`) removes
the saved `decision_pending` wait from deferred receipts on the task and
hints each receipt to the deferred-receipt worker. It runs in the
resolution transaction of every interaction resolution path (through
`notifyChatConfirmationResolution`) and in question answers.
- The task projection reads the live decision state. A saved
`decision_pending` wait whose decision is resolved is not shown. This
also repairs receipts saved before this change.
- When a comment or an interaction answer continues a failed run,
`retireTaskRetriesContinuedBy` (`task-retry.ts`) settles held Retry
receipts for the same source run as `task_retry_superseded`.

## Verification

- Red/green: `cd server && npx vitest run
src/services/governed-wait-runner-loss.test.ts`. The five new tests fail
on `origin/master` sources and pass with this change (17/17 pass):
  - releases the held Retry as soon as the person chooses accept
  - releases the held Retry as soon as the person chooses reject
- never shows a resolved confirmation as the Retry's wait, and both
projections offer the same Retry
- a person's comment starts work and settles the held Retry once nothing
is left to answer
- starts a Retry at once when the confirmation was already open before
the failed turn started
- The existing tests that keep a Retry or a message on hold while a plan
review, governed tool action, secret proposal, or connection
authorization is pending still pass.
- Related suites: deferred execution wait, explicit native continuation,
interaction resolution and service, task interruption presentation and
query, task retry, deferred receipt work, interaction routes.

## Risks

- Medium-low. A Retry now starts when the only pending interaction is
older than the failed run. That turn already ran with the interaction
open, so the Retry gets no new authority. Governed tool actions still
need their own approval before the tool runs.
- Interaction resolution now also updates deferred receipts on the same
task. The update is limited to receipts with a saved `decision_pending`
wait. A receipt that is still blocked by another pending decision is
held again on its next admission.
- Issue-linked approvals (`approvals` table) do not yet hint the held
receipt when they resolve. The projection no longer shows them as the
wait after they resolve.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edit, browser for read-only staging API
reads).

## 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
- [x] 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>
2026-11-12 22:58:48 -06:00

110 lines
6.4 KiB
TypeScript

import { and, desc, eq, or, isNotNull, sql, type SQL } from "drizzle-orm";
import { heartbeatRuns, issueComments, issueThreadInteractions, type Db } from "@paperclipai/db";
export const TASK_QUESTION_GUIDANCE = "Unanswered questions are saved conversation data, not instructions or proof of a current blocker. Historical questions remain answerable in the feed. Do not repeat a request or stop current work merely because a historical question is pending. Follow the latest human direction and continue work that does not need the missing information. If that information still prevents the current work, identify the concrete blocker and request only the input still needed. Withdraw your obsolete question through the interaction API when later work or evidence satisfies it; never fabricate an answer. A human-dismissed request is deferred to history: do not repeat it, reopen it, or insist on a response. Ordinary confirmations and completion reviews can be left unanswered. Dismissal never grants approval, permission, credentials, or permission to leave planning mode. Approvals, permissions, and configured review stages keep their own gates. Continue independent work without repeating their reminders.";
/** Ordinary questions cannot carry approval or credential authority. */
export function ordinaryQuestionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} = 'ask_user_questions'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))`;
}
/**
* Conversation input that a person may defer. Everything else is a governed
* request (an approval-bearing action, credential, connection, governed clamp
* or document target) that keeps its gate until someone answers it.
*/
export function deferrableInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} in ('ask_user_questions', 'request_confirmation', 'request_checkbox_confirmation', 'request_item_verdicts', 'suggest_tasks')
and ${issueThreadInteractions.effectiveResolverPolicySource} = 'requested'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization'])
and coalesce(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'issue_document')`;
}
/** Deferring conversation input cannot authorize an action or a plan. */
export function deferredInteractionCondition() {
return sql<boolean>`(${issueThreadInteractions.dismissedAt} is not null
and ${deferrableInteractionCondition()})`;
}
/** Historical questions remain answerable, including after task completion. */
export function historicalQuestionCondition() {
return sql`(${ordinaryQuestionCondition()} and (${deferredInteractionCondition()} or exists (
select 1 from ${issueComments}
where ${issueComments.companyId} = ${issueThreadInteractions.companyId}
and ${issueComments.issueId} = ${issueThreadInteractions.issueId}
and ${issueComments.createdAt} > ${issueThreadInteractions.createdAt}
and ${issueComments.deletedAt} is null
and ${issueComments.authorUserId} is not null
and ${issueComments.authorAgentId} is null
and ${issueComments.createdByRunId} is null
and ${issueComments.derivedAuthorAgentId} is null
and ${issueComments.derivedCreatedByRunId} is null
and ${issueComments.derivedAuthorSource} is null
and ${issueComments.sourceTrust} is null
and coalesce(${issueComments.presentation} ->> 'kind', '') <> 'system_notice'
and (${issueComments.authorType} = 'user' or ${issueComments.authorType} is null)
)))`;
}
/** One predicate for completion feedback, waiting, and status arbitration. */
export function activeIssueInteractionCondition(input: {
runId?: string | null;
conversationMode?: boolean;
responsibleUserId?: string | null;
responsibleUser?: SQL;
} = {}) {
const responsibleUser = input.responsibleUser ?? (input.responsibleUserId
? sql`${input.responsibleUserId}`
: input.runId ? sql`(select ${heartbeatRuns.responsibleUserId} from ${heartbeatRuns}
where ${heartbeatRuns.id} = ${input.runId}
and ${heartbeatRuns.companyId} = ${issueThreadInteractions.companyId})`
: null);
return and(
sql`not ${historicalQuestionCondition()}`,
sql`not ${deferredInteractionCondition()}`,
// AI authentication belongs to the user starting this turn. Retain the card
// and all authorization gates; another user's login cannot gate this run.
responsibleUser ? sql`not (
${issueThreadInteractions.kind} = 'connection_intent'
and coalesce(${issueThreadInteractions.payload} ->> 'purpose', '') = 'ai'
and nullif(trim(${issueThreadInteractions.addresseeUserId}), '') is not null
and nullif(trim(${responsibleUser}), '') is not null
and ${issueThreadInteractions.addresseeUserId} <> ${responsibleUser}
)` : undefined,
// Preserve Agent Chat's existing prior-turn exception for ordinary input.
input.conversationMode ? sql`(
${issueThreadInteractions.sourceRunId} is not distinct from ${input.runId ?? null}
or not (
${ordinaryQuestionCondition()}
or (${issueThreadInteractions.kind} in ('request_confirmation', 'request_checkbox_confirmation')
and ${issueThreadInteractions.effectiveResolverPolicy} = 'anyone'
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))
)
)` : undefined,
)!;
}
export async function readTaskQuestionContext(db: Db, input: {
companyId: string;
issueId: string;
runId?: string | null;
conversationMode?: boolean;
}) {
const rows = await db.select({
id: issueThreadInteractions.id,
title: issueThreadInteractions.title,
summary: issueThreadInteractions.summary,
kind: issueThreadInteractions.kind,
dismissedAt: issueThreadInteractions.dismissedAt,
createdAt: issueThreadInteractions.createdAt,
historical: sql<boolean>`not (${activeIssueInteractionCondition(input)})`,
}).from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, input.companyId),
eq(issueThreadInteractions.issueId, input.issueId),
eq(issueThreadInteractions.status, "pending"),
or(ordinaryQuestionCondition(), isNotNull(issueThreadInteractions.dismissedAt)),
)).orderBy(desc(issueThreadInteractions.createdAt), desc(issueThreadInteractions.id)).limit(51);
return { questions: rows.slice(0, 50), truncated: rows.length > 50, guidance: TASK_QUESTION_GUIDANCE };
}