Files
PaperClipAI/server/src/services/issue-question-context.ts
T
DottaandClaude Opus 5.5 28aa32e7d7 fix(plan-mode): open the plan review card when a Plan-mode run settles without one (#22732)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Plan mode makes an agent write a plan document. The user then
approves the plan or requests changes on a review card. After approval,
the agent does the work on the same task.
> - For Codex and Claude, the agent session reports the plan as a
provider event. Paperclip opens the review card from that event.
> - Google Antigravity and other ACPX agents have no such event. They
write the plan with a tool, and they must open the review card with
another tool.
> - When the agent does not open the card, the run settles as "waiting
for a response" and the task shows no action. This happened in a live
run: the Antigravity process was stopped during a Plan-mode run, and the
automatic continuation wrote a new plan revision but did not open the
card.
> - This pull request makes the server open the review card when a
Plan-mode run settles with a plan revision that has no review card. It
does this for every harness.
> - The benefit is that a Plan-mode task always shows the user the next
action, also after a crash or restart.

## Linked Issues or Issue Description

Refs #22727

**What happened?**

A Google Antigravity agent ran a task in Plan mode. The agent process
was stopped during the run. Paperclip continued the run automatically.
The new run wrote a new plan revision and finished with "waiting for
plan review". It did not open the Approve / Request changes card. The
task stayed in progress with no action for the user.

**Expected behavior**

When a Plan-mode run settles with a new plan revision, the user sees
exactly one review card for that revision. Retries, restarts and
duplicate settles do not add more cards. A Plan-mode run that produces
no plan does not leave the task waiting with no action.

**Steps to reproduce**

1. Assign a task to an Antigravity agent in Plan mode.
2. Stop the agent process while the run is in progress.
3. Let Paperclip continue the run automatically.
4. See that the continuation writes the plan but no review card opens.

**Paperclip version or commit**

master at 18aa2b353d.

## What Changed

- New `server/src/services/native-runtime/native-plan-review-card.ts`.
It opens the Plan-mode review card for the current plan revision, unless
an explicit plan review already covers it. Only a card bound to the plan
revision is a plan review: the server card, the Codex/Claude card, or an
agent card opened with the plan target. A confirmation without a plan
target is an ordinary request: it never covers a revision, never starts
execution and is never withdrawn by this logic. Per state of the
revision's card: pending is the gate; accepted, rejected, or withdrawn
by the user count as the user's decision (the agent is asked once to
revise); withdrawn by an agent or the system, expired or failed get a
fresh card. The idempotency key is bound to the revision (and to the
card it replaces), so concurrent settles open one card. Cards bound to
an older revision are withdrawn after re-reading the plan under a lock.
One card builder serves this and the Codex/Claude plan cards. A revision
that a person wrote is not put up for review. The call that inserts the
card logs it in the activity log.
- `heartbeat/task-markdown.ts`: the native Plan-mode directive says
Paperclip asks the user to approve the saved plan, so the agent does not
open its own card. This keeps the common case at one card.
- `native-run-finalizer.ts`: when a Plan-mode run settles successfully
and does not report done, the finalizer calls the new function before it
reads the governance gate. If the card cannot be opened, the run still
settles (the error is logged) and the recovery pass opens the card
later. The new card then becomes the gate, and the task waits in review
on it (`governed_response_waiting`), as for Codex and Claude.
- `plan-mode-status.ts` + `status-arbiter.ts`: a Plan-mode run (assigned
or started by a comment) that yields a response wait with no plan to
review (no plan, or the current revision already answered) no longer
settles as a silent wait. The agent gets one continuation that asks it
to save its plan. If that also fails, the task keeps its status and gets
a recovery action with a plain-language next step
(`plan_mode_plan_not_produced`). This uses the existing bounded
incomplete-report path.
- `issue-thread-interactions.ts`: a new `afterInsertInTransaction`
create option runs only when the call inserted the card (not on an
idempotent replay).
- `recovery/service.ts`: the existing stranded-task pass opens the card
for a Plan-mode task that an older release left in this state. No new
background worker.

## Verification

- `pnpm vitest run server/src/__tests__/native-plan-review-card.test.ts
server/src/__tests__/native-plan-review-card-finalizer.test.ts`
- Red on master, green on this branch:
- Finalizer: a recovered Plan-mode run with a new revision and no card
now gets exactly one card and waits in review (master: no card,
`response_wake_waiting_for_input`).
- Finalizer: a Plan-mode run with no plan gets the bounded "save your
plan" continuation (master: silent wait).
- Recovery pass: a task an older release left without a card gets one
card, also on a second pass, with no agent wake (master: no card).
- Table-driven tests: every way a Plan-mode run can settle (no plan;
plan with no card; agent card; current, historical and dismissed
questions; each governed card kind and status; a card by someone else;
Request changes with and without a new revision) leaves at most one plan
review card, or the "save your plan" continuation, and a repeat settle
changes nothing. Arbiter table: assigned and comment-started runs, with
and without a card, and the second miss.
- Also covered: an agent-opened card means no second card; concurrent
and repeated settles from several runs give one card; after Request
changes, the next revision gets a new card and the rejected card stays
rejected; a pending card for an older revision is expired and cannot be
accepted; Standard-mode response waits are unchanged; the card that
Codex and Claude open from their plan event stays the only card; a
person's own plan edit is not put up for review.
- `pnpm verify` passed for the selected suites.
- Not run live. The local Antigravity instance runs older code and was
not restarted for this change.

## Risks

- Low to medium. The change only acts on tasks in Plan mode. Standard,
Ask and conversation turns are not changed, except that the card
function can also run for a Plan-mode conversation run that has an
unreviewed plan.
- A Plan-mode run that reports done is not changed.
- An agent card without a document target is treated as covering the
revision when it was created after the revision. A plan card from Codex
or Claude has a target and is matched on that.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use
(shell, file edits, test runs).

## 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-24 00:32:12 -06:00

134 lines
7.8 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.";
/** Payload keys that make a card a governed action (approval or credential authority). */
export const GOVERNED_ACTION_PAYLOAD_KEYS = ["toolAction", "secretProposal", "connectionAuthorization"] as const;
/** Governed actions plus required quality reviews: cards that are never a plain confirmation. */
export const GOVERNED_REVIEW_PAYLOAD_KEYS = [...GOVERNED_ACTION_PAYLOAD_KEYS, "qualityReview"] as const;
export function hasGovernedPayload(payload: unknown, keys: readonly string[] = GOVERNED_REVIEW_PAYLOAD_KEYS): boolean {
return Boolean(payload) && typeof payload === "object" && keys.some(key => Object.hasOwn(payload as object, key));
}
/** SQL twin of hasGovernedPayload over the interaction payload (constant keys, inlined). */
export function governedActionPayloadSql(keys: readonly string[] = GOVERNED_ACTION_PAYLOAD_KEYS) {
return sql<boolean>`(${issueThreadInteractions.payload} ?| ${sql.raw(`array[${keys.map(key => `'${key}'`).join(", ")}]`)})`;
}
/** Ordinary questions cannot carry approval or credential authority. */
export function ordinaryQuestionCondition() {
return sql<boolean>`(${issueThreadInteractions.kind} = 'ask_user_questions'
and not (${governedActionPayloadSql()}))`;
}
/**
* 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 (${governedActionPayloadSql()})
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()}`,
// A routine offer is an optional follow-up on finished work; it never
// holds a task in a waiting posture or gates its completion.
sql`${issueThreadInteractions.kind} <> 'suggest_routine'`,
// A bar proposal is likewise optional: it never holds its bar
// conversation open, and it stays acceptable after the conversation ends.
sql`${issueThreadInteractions.kind} <> 'propose_responsibility_bar'`,
// So is an automation proposal in its automation conversation.
sql`${issueThreadInteractions.kind} <> 'propose_automation'`,
// And proposed dashboard changes in a dashboard conversation.
sql`${issueThreadInteractions.kind} <> 'propose_dashboard_changes'`,
// 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 (${governedActionPayloadSql()}))
)
)` : 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 };
}