Skip to content

Commit 28aa32e

Browse files
cryppadottaclaude
andauthored
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 18aa2b3. ## 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>
1 parent 7d26bda commit 28aa32e

13 files changed

Lines changed: 1188 additions & 32 deletions
Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
2+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
3+
import { and, eq } from "drizzle-orm";
4+
import {
5+
agents,
6+
agentWakeupRequests,
7+
companies,
8+
completionContracts,
9+
createDb,
10+
heartbeatRuns,
11+
issueThreadInteractions,
12+
issues,
13+
statusDecisions,
14+
workspaceOperations,
15+
} from "@paperclipai/db";
16+
import { CONTROL_PLANE_CONFORMANCE_OPEN } from "../vendor/paperclip-runner/testing.js";
17+
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
18+
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
19+
import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js";
20+
import { documentService } from "../services/documents.js";
21+
import { recoveryService } from "../services/recovery/service.js";
22+
23+
const cardFailure = vi.hoisted(() => ({ next: false }));
24+
vi.mock("../services/native-runtime/native-plan-review-card.js", async (importOriginal) => {
25+
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-review-card.js")>();
26+
return {
27+
...actual,
28+
ensureNativePlanReviewCard: async (...args: Parameters<typeof actual.ensureNativePlanReviewCard>) => {
29+
if (cardFailure.next) {
30+
cardFailure.next = false;
31+
throw new Error("connection reset while opening the card");
32+
}
33+
return actual.ensureNativePlanReviewCard(...args);
34+
},
35+
};
36+
});
37+
38+
const committedPlanWait = vi.hoisted(() => ({ runIds: new Set<string>() }));
39+
vi.mock("../services/native-runtime/native-plan-wait.js", async (importOriginal) => {
40+
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-wait.js")>();
41+
return {
42+
...actual,
43+
hasCommittedNativePlanWait: async (...args: Parameters<typeof actual.hasCommittedNativePlanWait>) =>
44+
committedPlanWait.runIds.has(args[1].runId) || actual.hasCommittedNativePlanWait(...args),
45+
};
46+
});
47+
48+
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_FINALIZER_TEST_DATABASE_URL");
49+
50+
// The live failure: the Antigravity process was killed mid Plan-mode run; the
51+
// automatic continuation wrote a new plan revision and yielded "waiting for
52+
// plan review" without opening the Approve / Request changes card. The task
53+
// sat in progress with nothing for the user to act on.
54+
describe("Plan-mode run settle opens the plan review", () => {
55+
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
56+
let db: ReturnType<typeof createDb>;
57+
const companyId = "72300000-0000-4000-8000-000000000001";
58+
const agentId = "72300000-0000-4000-8000-000000000002";
59+
let seq = 0;
60+
61+
beforeAll(async () => {
62+
if (!external) temporary = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-finalizer-");
63+
db = createDb(external ?? temporary.connectionString);
64+
await db.insert(companies).values({ id: companyId, name: "Plan review", issuePrefix: "PRF" });
65+
await db.insert(agents).values({ id: agentId, companyId, name: "Gemma Antigravity", adapterType: "antigravity_local", status: "running" });
66+
}, 30_000);
67+
68+
afterAll(async () => {
69+
await db?.$client.end({ timeout: 1 });
70+
await temporary?.cleanup();
71+
});
72+
73+
const yielded = {
74+
schema: "paperclip.run_result.v1" as const,
75+
reportedWorkDisposition: "yielded" as const,
76+
summary: "Saved the plan. Waiting for plan review before executing.",
77+
completionClaim: {
78+
contractRevision: "plan-v1", objectiveSatisfied: false,
79+
criteria: [{ criterionId: "objective", status: "unknown" as const, evidenceRefs: [] }],
80+
remainingWork: [],
81+
},
82+
evidence: [], verification: [], attentionRequests: [], artifacts: [],
83+
continuation: { kind: "response_wake" as const, summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
84+
};
85+
86+
async function settleRun(options: { workMode: "planning" | "standard"; writePlan: boolean }) {
87+
seq += 1;
88+
const id = (n: number) => `72300000-0000-4000-8${String(seq).padStart(3, "0")}-${String(n).padStart(12, "0")}`;
89+
const issueId = id(1), contractId = id(2), runId = id(3);
90+
await db.insert(issues).values({ id: issueId, companyId, title: `Plan ${seq}`, status: "in_progress",
91+
assigneeAgentId: agentId, workMode: options.workMode });
92+
await db.insert(completionContracts).values({
93+
id: contractId, companyId, issueId, revision: 1,
94+
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "phase6-v1", risk: "standard",
95+
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal",
96+
contractJson: { revision: "plan-v1", objective: "Plan the file",
97+
criteria: [{ id: "objective", requirement: "The plan is approved" }] },
98+
canonicalSha256: `plan-contract-${seq}`, createdByActorType: "system", createdByActorId: "test",
99+
});
100+
await db.insert(heartbeatRuns).values({
101+
id: runId, companyId, agentId, status: "running", runtimeMode: "native",
102+
runtimeModeReason: "persisted_before_kill_switch", nativeIssueId: issueId, nativeSessionId: runId,
103+
runnerInstanceId: contractId, completionContractId: contractId,
104+
completionContractSha256: `plan-contract-${seq}`, contextSnapshot: { issueId },
105+
});
106+
if (options.writePlan) {
107+
await documentService(db).upsertIssueDocument({ issueId, key: "plan", title: "Plan", format: "markdown",
108+
body: "# Create crash-proof.txt\n\n1. Write CRASH.", createdByAgentId: agentId, createdByRunId: runId });
109+
}
110+
const port = new PaperclipControlPlanePort(db, {
111+
companyId, issueId, runId, agentId, sessionId: runId, completionContractId: contractId,
112+
completionContractSha256: `plan-contract-${seq}`, sourceInstanceId: contractId,
113+
controlPlaneSourceInstanceId: `plan-control-${seq}`,
114+
});
115+
await port.openRun({ ...CONTROL_PLANE_CONFORMANCE_OPEN,
116+
identity: { companyId, issueId, runId, agentId, sessionId: runId }, sourceInstanceId: contractId });
117+
await port.completeRun({ result: yielded, terminal: { schema: "paperclip.prp.terminal.v1",
118+
turnTerminalState: "completed", runTerminalState: "succeeded", reportedWorkDisposition: "yielded" },
119+
callerResultId: `plan-result-${seq}` });
120+
await db.insert(workspaceOperations).values({ companyId, heartbeatRunId: runId, issueId,
121+
phase: "workspace_finalize", status: "succeeded" });
122+
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
123+
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
124+
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.id, issue!.lastStatusDecisionId!));
125+
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issueId));
126+
const wakes = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
127+
eq(agentWakeupRequests.agentId, agentId)));
128+
return { issueId, runId, issue: issue!, decision: decision!, cards,
129+
wakes: wakes.filter(wake => JSON.stringify(wake.payload ?? {}).includes(issueId)) };
130+
}
131+
132+
it("opens one review card for the new plan revision and waits on it", async () => {
133+
const settled = await settleRun({ workMode: "planning", writePlan: true });
134+
135+
expect(settled.cards).toHaveLength(1);
136+
expect(settled.cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending", sourceRunId: settled.runId });
137+
expect(settled.cards[0]!.payload).toMatchObject({ target: { type: "issue_document", key: "plan", revisionNumber: 1 } });
138+
expect(settled.issue.status).toBe("in_review");
139+
expect(settled.decision.reasonCode).toBe("governed_response_waiting");
140+
});
141+
142+
it("asks the agent for its plan when a Plan-mode run yields with none", async () => {
143+
const settled = await settleRun({ workMode: "planning", writePlan: false });
144+
145+
expect(settled.cards).toHaveLength(0);
146+
expect(settled.decision.reasonCode).toBe("plan_mode_plan_not_produced");
147+
expect(settled.wakes.some(wake => JSON.stringify(wake.payload).includes("Plan mode"))).toBe(true);
148+
});
149+
150+
it("gives a task left without its card by an older release one on the next recovery pass", async () => {
151+
const settled = await settleRun({ workMode: "planning", writePlan: true });
152+
// The state an older release left: settled, waiting, no card.
153+
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
154+
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
155+
const enqueueWakeup = vi.fn(async () => null);
156+
const recovery = recoveryService(db, { enqueueWakeup });
157+
158+
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
159+
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
160+
161+
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
162+
expect(cards).toHaveLength(1);
163+
expect(cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending" });
164+
expect(enqueueWakeup).not.toHaveBeenCalled();
165+
});
166+
167+
it("settles the run when opening the card fails, and the next recovery pass opens it", async () => {
168+
cardFailure.next = true;
169+
const settled = await settleRun({ workMode: "planning", writePlan: true });
170+
171+
expect(settled.cards).toHaveLength(0);
172+
expect(settled.issue.status).toBe("in_progress");
173+
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
174+
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
175+
expect(run).toMatchObject({ status: "succeeded" });
176+
177+
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
178+
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
179+
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
180+
expect(cards).toEqual([expect.objectContaining({ kind: "request_confirmation", status: "pending" })]);
181+
});
182+
183+
it.each(["finalization reason", "committed plan wait"])("never opens a second card for a plan the user already accepted (%s)", async (proof) => {
184+
const settled = await settleRun({ workMode: "planning", writePlan: true });
185+
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
186+
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
187+
if (proof === "finalization reason") {
188+
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
189+
await db.update(heartbeatRuns).set({ resultJson: { ...(run!.resultJson as Record<string, unknown>),
190+
finalizationReasonCode: "native_plan_accepted_waiting_for_continuation" } }).where(eq(heartbeatRuns.id, settled.runId));
191+
} else committedPlanWait.runIds.add(settled.runId);
192+
193+
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
194+
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
195+
196+
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId))).toHaveLength(0);
197+
});
198+
199+
it("leaves a Standard-mode response wait unchanged", async () => {
200+
const settled = await settleRun({ workMode: "standard", writePlan: true });
201+
202+
expect(settled.cards).toHaveLength(0);
203+
expect(settled.issue.status).toBe("in_progress");
204+
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
205+
});
206+
});

0 commit comments

Comments
 (0)