mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
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>
This commit is contained in:
1 parent
7d26bdaa42
commit
28aa32e7d7
13 files changed
+1188
-32
No files matched your search
@@ -0,0 +1,252 @@
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { documentRevisions, documents, issueThreadInteractions, issues, type Db } from "@paperclipai/db";
|
||||
import { logActivity, publishActivity } from "../activity-log.js";
|
||||
import { documentService } from "../documents.js";
|
||||
import { HttpError } from "../../errors.js";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import { issueThreadInteractionService } from "../issue-thread-interactions.js";
|
||||
import { activeIssueInteractionCondition, hasGovernedPayload } from "../issue-question-context.js";
|
||||
import { isConversation } from "../../lib/conversation-wake-policy.js";
|
||||
|
||||
/**
|
||||
* The Plan-mode review card for the current plan revision.
|
||||
*
|
||||
* Codex and Claude report their plan as a provider event, and the session
|
||||
* opens the Approve / Request changes card for it. Harnesses without such an
|
||||
* event (Antigravity and other ACPX agents) write the Plan document with a
|
||||
* tool and must open the card themselves. A run that forgets, or a recovered
|
||||
* run that resumes after the original process died, would otherwise leave a
|
||||
* Plan-mode task waiting on a review nobody can give. When a Plan-mode run
|
||||
* settles, the server opens the card for the current revision unless one
|
||||
* already covers it.
|
||||
*/
|
||||
export type NativePlanReviewCardOutcome =
|
||||
/** The server opened the card for this revision. */
|
||||
| { kind: "created"; interactionId: string; revisionId: string }
|
||||
/** A pending card (or question) already gives the user the next action. */
|
||||
| { kind: "pending"; interactionId: string }
|
||||
/** The current revision was already answered; the agent owes a new revision. */
|
||||
| { kind: "reviewed"; revisionId: string }
|
||||
/** Plan mode produced no plan to review. */
|
||||
| { kind: "no_plan" }
|
||||
/** Not a Plan-mode task this agent owns, or the revision is not the agent's. */
|
||||
| { kind: "not_applicable" };
|
||||
|
||||
type Binding = { companyId: string; issueId: string; runId: string; agentId: string };
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> =>
|
||||
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
|
||||
export function planReviewCardIdempotencyKey(revisionId: string): string {
|
||||
return `plan-review:v1:${revisionId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one Plan-review card shape, for the card Paperclip opens from a
|
||||
* provider's plan event (Codex, Claude) and the one it opens on settle.
|
||||
*/
|
||||
export function planReviewConfirmationInput(input: {
|
||||
issueId: string;
|
||||
documentId: string;
|
||||
revisionId: string;
|
||||
revisionNumber: number;
|
||||
sourceRunId: string;
|
||||
idempotencyKey: string;
|
||||
source: "provider_plan" | "plan_document";
|
||||
}) {
|
||||
return {
|
||||
kind: "request_confirmation" as const,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
sourceRunId: input.sourceRunId,
|
||||
title: `Review plan revision ${input.revisionNumber}`,
|
||||
summary: input.source === "provider_plan"
|
||||
? "Review the synchronized Paperclip plan."
|
||||
: "Review the plan before the agent starts the work.",
|
||||
continuationPolicy: "wake_assignee" as const,
|
||||
payload: {
|
||||
version: 1 as const,
|
||||
prompt: `Approve plan revision ${input.revisionNumber}?`,
|
||||
...(input.source === "provider_plan"
|
||||
? { detailsMarkdown: "The completed provider plan has been synchronized to the canonical Plan document." }
|
||||
: {}),
|
||||
acceptLabel: "Approve plan",
|
||||
rejectLabel: "Request changes",
|
||||
rejectRequiresReason: true,
|
||||
supersedeOnUserComment: false,
|
||||
target: {
|
||||
type: "issue_document" as const,
|
||||
issueId: input.issueId,
|
||||
documentId: input.documentId,
|
||||
key: "plan",
|
||||
revisionId: input.revisionId,
|
||||
revisionNumber: input.revisionNumber,
|
||||
label: `Plan v${input.revisionNumber}`,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function coveringCard(db: Db, binding: Binding, revision: { id: string }, conversationMode: boolean) {
|
||||
// A historical or deferred card cannot give the user the next action; the
|
||||
// same rule decides the run's governance gate.
|
||||
const active = new Set((await db.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, binding.companyId),
|
||||
eq(issueThreadInteractions.issueId, binding.issueId),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
activeIssueInteractionCondition({ runId: binding.runId, conversationMode }),
|
||||
))).map(row => row.id));
|
||||
const cards = await db.select({
|
||||
id: issueThreadInteractions.id,
|
||||
kind: issueThreadInteractions.kind,
|
||||
status: issueThreadInteractions.status,
|
||||
payload: issueThreadInteractions.payload,
|
||||
createdAt: issueThreadInteractions.createdAt,
|
||||
resolvedByUserId: issueThreadInteractions.resolvedByUserId,
|
||||
resolvedByAgentId: issueThreadInteractions.resolvedByAgentId,
|
||||
result: issueThreadInteractions.result,
|
||||
}).from(issueThreadInteractions).where(and(
|
||||
eq(issueThreadInteractions.companyId, binding.companyId),
|
||||
eq(issueThreadInteractions.issueId, binding.issueId),
|
||||
inArray(issueThreadInteractions.kind, ["request_confirmation", "ask_user_questions"]),
|
||||
));
|
||||
const targetRevision = (payload: unknown) => {
|
||||
const target = record(record(payload).target);
|
||||
return target.type === "issue_document" && typeof target.revisionId === "string" ? target.revisionId : null;
|
||||
};
|
||||
// Only an explicit plan review covers a revision: a card bound to this
|
||||
// revision (the server's, Codex/Claude's, or an agent's card opened with the
|
||||
// plan target). An unbound confirmation is an ordinary request: it never
|
||||
// covers a plan, never starts execution and is never withdrawn here. A
|
||||
// pending question also gives the user the next action. A card bound to an
|
||||
// older revision does not cover this one.
|
||||
const covers = (card: (typeof cards)[number]) => {
|
||||
if (card.kind === "ask_user_questions") return card.status === "pending";
|
||||
if (hasGovernedPayload(card.payload)) return false;
|
||||
return targetRevision(card.payload) === revision.id;
|
||||
};
|
||||
// A pending card bound to this revision always gates it, also when the
|
||||
// conversation prior-turn rule would leave it out of the active set.
|
||||
const pending = cards.find(card => card.status === "pending" && covers(card) &&
|
||||
(active.has(card.id) || targetRevision(card.payload) === revision.id));
|
||||
if (pending) return { kind: "pending" as const, interactionId: pending.id };
|
||||
// How each terminal state of a card bound to this revision counts:
|
||||
// - accepted or rejected: the user decided this revision;
|
||||
// - cancelled by the user (withdrawn from the thread): the user declined to
|
||||
// review this revision. Do not reopen it; the agent is asked to revise.
|
||||
// - cancelled by an agent or the system, expired (superseded, stale, task
|
||||
// closed) or failed: no one reviewed it. The revision gets a fresh card.
|
||||
// A card withdrawn as a stale target was for an older revision, even though
|
||||
// the withdrawal records the current revision on it.
|
||||
const bound = cards.filter(card => card.kind === "request_confirmation" && covers(card) &&
|
||||
record(card.result).outcome !== "stale_target");
|
||||
const decided = bound.find(card => ["accepted", "rejected"].includes(card.status) ||
|
||||
(card.status === "cancelled" && card.resolvedByUserId && !card.resolvedByAgentId));
|
||||
if (decided) return { kind: "reviewed" as const, revisionId: revision.id };
|
||||
const unreviewed = bound.filter(card => card.status !== "pending")
|
||||
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];
|
||||
return unreviewed ? { kind: "reopen" as const, afterInteractionId: unreviewed.id } : null;
|
||||
}
|
||||
|
||||
export async function ensureNativePlanReviewCard(db: Db, binding: Binding): Promise<NativePlanReviewCardOutcome> {
|
||||
const publications: Parameters<typeof publishActivity>[0][] = [];
|
||||
// One decision per task at a time: reading the current revision and its
|
||||
// cards, withdrawing older cards, choosing the key and inserting all happen
|
||||
// under the task row lock, so two settles can never both open a card for
|
||||
// one plan. Card creation takes the same lock first, so the order matches.
|
||||
const outcome = await db.transaction(async (transaction) => {
|
||||
const tx = transaction as unknown as Db;
|
||||
const [issue] = await tx.select({
|
||||
workMode: issues.workMode, status: issues.status, assigneeAgentId: issues.assigneeAgentId,
|
||||
assigneeUserId: issues.assigneeUserId, hiddenAt: issues.hiddenAt,
|
||||
conversationAgentId: issues.conversationAgentId, conversationUserId: issues.conversationUserId,
|
||||
}).from(issues).where(and(eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId))).limit(1).for("update");
|
||||
if (!issue || issue.workMode !== "planning" || issue.hiddenAt || issue.assigneeUserId ||
|
||||
issue.assigneeAgentId !== binding.agentId || ["done", "cancelled"].includes(issue.status)) {
|
||||
return { kind: "not_applicable" } as const;
|
||||
}
|
||||
const plan = await documentService(tx).getIssueDocumentByKey(binding.issueId, "plan");
|
||||
if (!plan?.latestRevisionId) return { kind: "no_plan" } as const;
|
||||
const [revision] = await tx.select({
|
||||
id: documentRevisions.id, revisionNumber: documentRevisions.revisionNumber,
|
||||
createdByAgentId: documentRevisions.createdByAgentId,
|
||||
}).from(documentRevisions).where(and(
|
||||
eq(documentRevisions.id, plan.latestRevisionId), eq(documentRevisions.companyId, binding.companyId),
|
||||
)).limit(1);
|
||||
if (!revision) return { kind: "no_plan" } as const;
|
||||
// A delayed settle that read an older revision must not act on it.
|
||||
const [current] = await tx.select({ latestRevisionId: documents.latestRevisionId, latestRevisionNumber: documents.latestRevisionNumber })
|
||||
.from(documents).where(and(eq(documents.id, plan.id), eq(documents.companyId, binding.companyId))).for("update");
|
||||
if (current?.latestRevisionId !== revision.id) return { kind: "not_applicable" } as const;
|
||||
const conversationMode = isConversation(issue);
|
||||
const existing = await coveringCard(tx, binding, revision, conversationMode);
|
||||
if (existing && existing.kind !== "reopen") return existing;
|
||||
// Only the assigned agent's own proposal is put up for review. A revision
|
||||
// a person wrote is theirs already.
|
||||
if (revision.createdByAgentId !== binding.agentId) return { kind: "not_applicable" } as const;
|
||||
// A card for this revision that no one reviewed keeps its key; the fresh
|
||||
// card's key names the one it follows.
|
||||
const idempotencyKey = existing?.kind === "reopen"
|
||||
? `${planReviewCardIdempotencyKey(revision.id)}:after:${existing.afterInteractionId}`
|
||||
: planReviewCardIdempotencyKey(revision.id);
|
||||
// Withdraw cards bound to an older revision. Answering one is already
|
||||
// refused as a stale target, so this only tidies the thread: a row it
|
||||
// cannot read must not stop the current card from opening.
|
||||
await tx.transaction(async (savepoint) => {
|
||||
await issueThreadInteractionService(savepoint as unknown as Db).expireStaleRequestConfirmationsForIssueDocument(
|
||||
{ id: binding.issueId, companyId: binding.companyId },
|
||||
{ id: plan.id, key: "plan", latestRevisionId: current.latestRevisionId, latestRevisionNumber: current.latestRevisionNumber },
|
||||
{ agentId: binding.agentId, runId: binding.runId });
|
||||
}).catch((error: unknown) => logger.warn({ issueId: binding.issueId, error }, "Could not withdraw stale plan review cards"));
|
||||
let inserted = false;
|
||||
try {
|
||||
const interaction = await issueThreadInteractionService(tx).create(
|
||||
{ id: binding.issueId, companyId: binding.companyId },
|
||||
planReviewConfirmationInput({
|
||||
issueId: binding.issueId, documentId: plan.id, revisionId: revision.id, revisionNumber: revision.revisionNumber,
|
||||
sourceRunId: binding.runId, source: "plan_document", idempotencyKey,
|
||||
}) as never,
|
||||
{ agentId: binding.agentId, runId: binding.runId },
|
||||
{
|
||||
// Leave the agent's other pending cards answerable. Only cards bound
|
||||
// to an older plan revision were withdrawn above; an unbound card is
|
||||
// never withdrawn by guess.
|
||||
supersedePendingSiblingInteractions: false,
|
||||
// Only the call that inserted the card records it.
|
||||
afterInsertInTransaction: async (insertTx, row) => {
|
||||
inserted = true;
|
||||
await logActivity(insertTx, {
|
||||
companyId: binding.companyId,
|
||||
actorType: "system",
|
||||
actorId: "native-plan-review",
|
||||
agentId: binding.agentId,
|
||||
runId: binding.runId,
|
||||
issueId: binding.issueId,
|
||||
action: "issue.thread_interaction_created",
|
||||
entityType: "issue",
|
||||
entityId: binding.issueId,
|
||||
details: {
|
||||
interactionId: row.id,
|
||||
interactionKind: "request_confirmation",
|
||||
source: "plan_mode_settle",
|
||||
planRevisionId: revision.id,
|
||||
planRevisionNumber: revision.revisionNumber,
|
||||
},
|
||||
}, publications);
|
||||
},
|
||||
},
|
||||
);
|
||||
return inserted
|
||||
? { kind: "created", interactionId: interaction.id, revisionId: revision.id } as const
|
||||
: { kind: "pending", interactionId: interaction.id } as const;
|
||||
} catch (error) {
|
||||
// The task closed or the agent may no longer write here. A refused card
|
||||
// must not fail the run's settlement; database errors still surface so
|
||||
// finalization (or the recovery pass) retries.
|
||||
if (!(error instanceof HttpError) || error.status >= 500) throw error;
|
||||
const covered = await coveringCard(tx, binding, revision, conversationMode);
|
||||
return covered && covered.kind !== "reopen" ? covered : { kind: "not_applicable" } as const;
|
||||
}
|
||||
});
|
||||
for (const publication of publications) publishActivity(publication);
|
||||
return outcome;
|
||||
}
|
||||
@@ -114,6 +114,7 @@ import {
|
||||
} from "../heartbeat-run-summary.js";
|
||||
import { resolveChatRunPresentationAuthorizationReason } from "../chat-run-publications.js";
|
||||
import { settledResponsePublicationSql } from "./native-response-publication-receipt.js";
|
||||
import { ensureNativePlanReviewCard } from "./native-plan-review-card.js";
|
||||
import { hasChatRunOwnedProviderInteraction } from "../chat-interaction-arbitration.js";
|
||||
import {
|
||||
authorizeCommittedChatResponse,
|
||||
@@ -1677,6 +1678,23 @@ export async function finalizeNativeRun(input: {
|
||||
? await findSupersededExternalReviewRequests(input.db, {
|
||||
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
|
||||
}) : [];
|
||||
// A Plan-mode run that settles with a plan revision nobody was asked to
|
||||
// review gets its review card here, whichever harness ran it and whether
|
||||
// or not the agent remembered to open it. The card is the review gate below.
|
||||
const planReview = terminalState === "succeeded" && input.workspaceFinalizeStatus === "succeeded" &&
|
||||
authoritativeIssue.workMode === "planning" && result.reportedWorkDisposition !== "done" &&
|
||||
!isNativePlanWaitResult(result) &&
|
||||
!readNativeReviewAssignmentContext(run.contextSnapshot)
|
||||
? await ensureNativePlanReviewCard(input.db, {
|
||||
companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId,
|
||||
}).catch((error: unknown) => {
|
||||
// The run already succeeded; a card that could not be opened must
|
||||
// not fail its settlement. The task settles in its response wait and
|
||||
// the stranded-task pass opens the card (idempotently) later.
|
||||
logger.warn({ runId: run.id, issueId: authoritativeIssue.id, error }, "Plan review card could not be opened at settle; recovery will retry");
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
const governanceGate = await pendingNativeGovernance({
|
||||
db: input.db,
|
||||
companyId: run.companyId,
|
||||
@@ -1778,6 +1796,7 @@ export async function finalizeNativeRun(input: {
|
||||
monitorWaitSuperseded: supersededMonitorWait !== null,
|
||||
monitorWaitAuthorized: authoritativeIssue.workMode === "standard" && authoritativeIssue.executionRunId === run.id && monitorWaitAt !== null,
|
||||
planWaitAuthorized: planWait !== null,
|
||||
planNotProduced: planReview?.kind === "no_plan" || planReview?.kind === "reviewed",
|
||||
hasPendingChildCompletion,
|
||||
providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision,
|
||||
providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision,
|
||||
|
||||
@@ -335,6 +335,7 @@ import {
|
||||
type NativeStatusDecision,
|
||||
} from "./status-arbiter.js";
|
||||
import { conflict, HttpError } from "../../errors.js";
|
||||
import { planReviewConfirmationInput } from "./native-plan-review-card.js";
|
||||
import { redactSensitiveText } from "../../redaction.js";
|
||||
import { classifyRemoteConnectionError } from "../remote-connection-failure.js";
|
||||
import { resolvePaperclipRunnerBinary, resolvePaperclipRunnerBinaryAsync, resolveRemotePaperclipRunnerBinary, verifiedBundledRemoteRunnerBinary } from "./native-codex-runner.js";
|
||||
@@ -2322,33 +2323,15 @@ export async function synchronizeCompletedProviderPlan(input: {
|
||||
id: input.execution.binding.issueId,
|
||||
companyId: input.execution.binding.companyId,
|
||||
},
|
||||
{
|
||||
kind: "request_confirmation",
|
||||
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
|
||||
planReviewConfirmationInput({
|
||||
issueId: input.execution.binding.issueId,
|
||||
documentId: current.id,
|
||||
revisionId: revision.id,
|
||||
revisionNumber: revision.revisionNumber,
|
||||
sourceRunId: input.execution.binding.runId,
|
||||
title: `Review plan revision ${revision.revisionNumber}`,
|
||||
summary: "Review the synchronized Paperclip plan.",
|
||||
continuationPolicy: "wake_assignee",
|
||||
payload: {
|
||||
version: 1,
|
||||
prompt: `Approve plan revision ${revision.revisionNumber}?`,
|
||||
detailsMarkdown:
|
||||
"The completed provider plan has been synchronized to the canonical Plan document.",
|
||||
acceptLabel: "Approve plan",
|
||||
rejectLabel: "Request changes",
|
||||
rejectRequiresReason: true,
|
||||
supersedeOnUserComment: false,
|
||||
target: {
|
||||
type: "issue_document",
|
||||
issueId: input.execution.binding.issueId,
|
||||
documentId: current.id,
|
||||
key: "plan",
|
||||
revisionId: revision.id,
|
||||
revisionNumber: revision.revisionNumber,
|
||||
label: `Plan v${revision.revisionNumber}`,
|
||||
},
|
||||
},
|
||||
} as never,
|
||||
source: "provider_plan",
|
||||
idempotencyKey: `runner-plan-approval:v1:${input.execution.binding.runId}:${planId}:${providerRevision}:${digest}`,
|
||||
}) as never,
|
||||
{
|
||||
agentId: input.execution.binding.agentId,
|
||||
runId: input.execution.binding.runId,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { NativeEvidenceAssessment } from "./evidence-classifier.js";
|
||||
import { arbitrateNativeStatus } from "./status-arbiter.js";
|
||||
import { PLAN_NOT_PRODUCED_REASON } from "./plan-mode-status.js";
|
||||
|
||||
const yieldedWait: NativeEvidenceAssessment = {
|
||||
objectiveClaimSatisfied: false, objectiveSatisfied: false, allCriteriaSatisfied: false, verificationPassed: false,
|
||||
hasFailedVerification: false, hasBlockingRemainingWork: false, reportedDisposition: "yielded",
|
||||
summary: "Waiting for plan review", contractRevisionMatches: true, criterionAssessments: [],
|
||||
verificationAssessments: [], verificationCaveats: [], acceptedEvidenceRefs: [], missingRequirements: [],
|
||||
rejectedEvidence: [], unverifiableEvidence: [], blocker: null,
|
||||
continuation: { kind: "response_wake", summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
|
||||
attentionRequests: [], ignoredAttentionRequests: [],
|
||||
} as NativeEvidenceAssessment;
|
||||
|
||||
const arbitrate = (overrides: Partial<Parameters<typeof arbitrateNativeStatus>[0]>) => arbitrateNativeStatus({
|
||||
assessment: yieldedWait, terminalState: "succeeded", workspaceFinalizeStatus: "succeeded",
|
||||
agentId: "agent", priorIssueStatus: "in_progress", ...overrides,
|
||||
});
|
||||
|
||||
// Every way a Plan-mode response wait can settle leaves the user one current
|
||||
// action (the review card is the gate) or schedules the agent to produce one.
|
||||
describe("Plan-mode response wait settlement", () => {
|
||||
it.each([
|
||||
{ name: "assigned run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" } },
|
||||
reasonCode: "governed_response_waiting", next: "card" },
|
||||
{ name: "comment-started run, plan card open", input: { governanceGate: { kind: "interaction" as const, id: "card" }, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
|
||||
reasonCode: "governed_response_waiting", next: "card" },
|
||||
{ name: "assigned run, no plan", input: { planNotProduced: true },
|
||||
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
|
||||
{ name: "comment-started run, no plan", input: { planNotProduced: true, boardResponseWaitAuthorized: true, boardResponseWaitOrigin: true },
|
||||
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
|
||||
{ name: "comment-started run whose comment was superseded, no plan", input: { planNotProduced: true, boardResponseWaitOrigin: true },
|
||||
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "continuation" },
|
||||
{ name: "second miss after the continuation", input: { planNotProduced: true, allowIncompleteContinuation: false },
|
||||
reasonCode: PLAN_NOT_PRODUCED_REASON, next: "recovery" },
|
||||
])("$name", ({ input, reasonCode, next }) => {
|
||||
const decision = arbitrate(input);
|
||||
expect(decision.reasonCode).toBe(reasonCode);
|
||||
const kinds = decision.effects.map(effect => effect.kind);
|
||||
if (next === "card") expect(kinds).toContain("create_interaction");
|
||||
if (next === "continuation") expect(kinds).toContain("enqueue_continuation");
|
||||
if (next === "recovery") expect(kinds).toContain("record_finalization_error");
|
||||
});
|
||||
|
||||
it("leaves Standard-mode and conversation waits unchanged", () => {
|
||||
expect(arbitrate({}).reasonCode).toBe("response_wake_waiting_for_input");
|
||||
expect(arbitrate({ boardResponseWaitAuthorized: true }).reasonCode).toBe("board_response_waiting");
|
||||
expect(arbitrate({ planNotProduced: true, isConversation: true }).reasonCode).not.toBe(PLAN_NOT_PRODUCED_REASON);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { NativeAuthoritativeIssueStatus, NativeStatusDecision } from "./status-arbiter.js";
|
||||
|
||||
export const PLAN_NOT_PRODUCED_REASON = "plan_mode_plan_not_produced";
|
||||
|
||||
/**
|
||||
* Plan mode waits only on a plan review. A Plan-mode run that yields a
|
||||
* response wait with no plan to review (none saved, or the current revision
|
||||
* already answered) must not rest as a silent wait. The agent is asked once to
|
||||
* save its plan (its review card then opens); after that, the task keeps its
|
||||
* status and shows a recovery step.
|
||||
*/
|
||||
export function planNotProducedDecision(input: {
|
||||
priorIssueStatus: NativeAuthoritativeIssueStatus;
|
||||
agentId: string;
|
||||
allowIncompleteContinuation?: boolean;
|
||||
}): Omit<NativeStatusDecision, "policyVersion"> {
|
||||
if (input.allowIncompleteContinuation === false) {
|
||||
return {
|
||||
statusAction: "preserve", toStatus: input.priorIssueStatus,
|
||||
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
|
||||
effects: [{ kind: "record_finalization_error", cause: PLAN_NOT_PRODUCED_REASON,
|
||||
nextAction: "The agent finished in Plan mode without a new plan to review. Ask it to write the plan, or switch the task out of Plan mode.",
|
||||
agentId: input.agentId }],
|
||||
};
|
||||
}
|
||||
return {
|
||||
statusAction: "in_progress", toStatus: "in_progress",
|
||||
reasonCode: PLAN_NOT_PRODUCED_REASON, unblockDescriptor: null,
|
||||
effects: [{
|
||||
kind: "enqueue_continuation", continuationKind: "same_agent",
|
||||
summary: "This task is in Plan mode and there is no new plan to review. Save your plan (or the revised plan) to this task's Plan document; Paperclip then asks the user to approve it. If you need an answer first, ask a question instead of waiting.",
|
||||
// The bounded incomplete-report key: a second miss gets the recovery step.
|
||||
idempotencyKey: "native-completion-incomplete", agentId: input.agentId,
|
||||
}],
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, N
|
||||
import { NATIVE_TOOL_RECEIPT_LIMIT_CODE, NATIVE_TOOL_RECEIPT_LIMIT_MAX_CONTINUATIONS } from "./native-tool-receipt-limit.js";
|
||||
import { NATIVE_ENVIRONMENT_BLOCKER_CODE, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_ACTION, NATIVE_ENVIRONMENT_BLOCKER_EXHAUSTED_CODE,
|
||||
NATIVE_ENVIRONMENT_BLOCKER_MAX_RETRIES } from "./native-environment-blocker.js";
|
||||
import { planNotProducedDecision } from "./plan-mode-status.js";
|
||||
import { NATIVE_AGENT_BLOCKER_CONTINUATION_CODE, NATIVE_AGENT_BLOCKER_HANDOFF_CODE,
|
||||
NATIVE_AGENT_BLOCKER_MAX_CONTINUATIONS } from "./native-agent-blocker.js";
|
||||
|
||||
@@ -236,6 +237,8 @@ export function arbitrateNativeStatus(input: {
|
||||
publishedExternalReview?: boolean;
|
||||
/** Server-verified accepted plan request and normal provider terminal. */
|
||||
planWaitAuthorized?: boolean;
|
||||
/** A Plan-mode run settled with no unanswered plan revision to review. */
|
||||
planNotProduced?: boolean;
|
||||
monitorWaitAuthorized?: boolean;
|
||||
caseHandoffAuthorized?: boolean;
|
||||
/** The saved timer already admitted another run and this run no longer owns checkout. */
|
||||
@@ -854,6 +857,12 @@ export function arbitrateNativeStatus(input: {
|
||||
effects: [],
|
||||
};
|
||||
}
|
||||
// Before the passive board/response waits: a Plan-mode run, assigned or
|
||||
// comment-started, with no plan to review must not rest as a silent wait.
|
||||
if (input.planNotProduced === true && !input.isConversation && input.assessment.reportedDisposition === "yielded" &&
|
||||
input.assessment.continuation?.kind === "response_wake") {
|
||||
return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, ...planNotProducedDecision(input) };
|
||||
}
|
||||
if (
|
||||
input.assessment.reportedDisposition === "yielded" &&
|
||||
input.assessment.continuation?.kind === "response_wake" &&
|
||||
|
||||
Reference in new issue
Block a user