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,206 @@
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import {
|
||||
agents,
|
||||
agentWakeupRequests,
|
||||
companies,
|
||||
completionContracts,
|
||||
createDb,
|
||||
heartbeatRuns,
|
||||
issueThreadInteractions,
|
||||
issues,
|
||||
statusDecisions,
|
||||
workspaceOperations,
|
||||
} from "@paperclipai/db";
|
||||
import { CONTROL_PLANE_CONFORMANCE_OPEN } from "../vendor/paperclip-runner/testing.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
|
||||
import { PaperclipControlPlanePort } from "../services/native-runtime/paperclip-control-plane-port.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { recoveryService } from "../services/recovery/service.js";
|
||||
|
||||
const cardFailure = vi.hoisted(() => ({ next: false }));
|
||||
vi.mock("../services/native-runtime/native-plan-review-card.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-review-card.js")>();
|
||||
return {
|
||||
...actual,
|
||||
ensureNativePlanReviewCard: async (...args: Parameters<typeof actual.ensureNativePlanReviewCard>) => {
|
||||
if (cardFailure.next) {
|
||||
cardFailure.next = false;
|
||||
throw new Error("connection reset while opening the card");
|
||||
}
|
||||
return actual.ensureNativePlanReviewCard(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const committedPlanWait = vi.hoisted(() => ({ runIds: new Set<string>() }));
|
||||
vi.mock("../services/native-runtime/native-plan-wait.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/native-runtime/native-plan-wait.js")>();
|
||||
return {
|
||||
...actual,
|
||||
hasCommittedNativePlanWait: async (...args: Parameters<typeof actual.hasCommittedNativePlanWait>) =>
|
||||
committedPlanWait.runIds.has(args[1].runId) || actual.hasCommittedNativePlanWait(...args),
|
||||
};
|
||||
});
|
||||
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_FINALIZER_TEST_DATABASE_URL");
|
||||
|
||||
// The live failure: the Antigravity process was killed mid Plan-mode run; the
|
||||
// automatic continuation wrote a new plan revision and yielded "waiting for
|
||||
// plan review" without opening the Approve / Request changes card. The task
|
||||
// sat in progress with nothing for the user to act on.
|
||||
describe("Plan-mode run settle opens the plan review", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const companyId = "72300000-0000-4000-8000-000000000001";
|
||||
const agentId = "72300000-0000-4000-8000-000000000002";
|
||||
let seq = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!external) temporary = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-finalizer-");
|
||||
db = createDb(external ?? temporary.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Plan review", issuePrefix: "PRF" });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Gemma Antigravity", adapterType: "antigravity_local", status: "running" });
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end({ timeout: 1 });
|
||||
await temporary?.cleanup();
|
||||
});
|
||||
|
||||
const yielded = {
|
||||
schema: "paperclip.run_result.v1" as const,
|
||||
reportedWorkDisposition: "yielded" as const,
|
||||
summary: "Saved the plan. Waiting for plan review before executing.",
|
||||
completionClaim: {
|
||||
contractRevision: "plan-v1", objectiveSatisfied: false,
|
||||
criteria: [{ criterionId: "objective", status: "unknown" as const, evidenceRefs: [] }],
|
||||
remainingWork: [],
|
||||
},
|
||||
evidence: [], verification: [], attentionRequests: [], artifacts: [],
|
||||
continuation: { kind: "response_wake" as const, summary: "Waiting for plan review", idempotencyKey: "plan-review-wake-v1" },
|
||||
};
|
||||
|
||||
async function settleRun(options: { workMode: "planning" | "standard"; writePlan: boolean }) {
|
||||
seq += 1;
|
||||
const id = (n: number) => `72300000-0000-4000-8${String(seq).padStart(3, "0")}-${String(n).padStart(12, "0")}`;
|
||||
const issueId = id(1), contractId = id(2), runId = id(3);
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: `Plan ${seq}`, status: "in_progress",
|
||||
assigneeAgentId: agentId, workMode: options.workMode });
|
||||
await db.insert(completionContracts).values({
|
||||
id: contractId, companyId, issueId, revision: 1,
|
||||
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "phase6-v1", risk: "standard",
|
||||
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal",
|
||||
contractJson: { revision: "plan-v1", objective: "Plan the file",
|
||||
criteria: [{ id: "objective", requirement: "The plan is approved" }] },
|
||||
canonicalSha256: `plan-contract-${seq}`, createdByActorType: "system", createdByActorId: "test",
|
||||
});
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: runId, companyId, agentId, status: "running", runtimeMode: "native",
|
||||
runtimeModeReason: "persisted_before_kill_switch", nativeIssueId: issueId, nativeSessionId: runId,
|
||||
runnerInstanceId: contractId, completionContractId: contractId,
|
||||
completionContractSha256: `plan-contract-${seq}`, contextSnapshot: { issueId },
|
||||
});
|
||||
if (options.writePlan) {
|
||||
await documentService(db).upsertIssueDocument({ issueId, key: "plan", title: "Plan", format: "markdown",
|
||||
body: "# Create crash-proof.txt\n\n1. Write CRASH.", createdByAgentId: agentId, createdByRunId: runId });
|
||||
}
|
||||
const port = new PaperclipControlPlanePort(db, {
|
||||
companyId, issueId, runId, agentId, sessionId: runId, completionContractId: contractId,
|
||||
completionContractSha256: `plan-contract-${seq}`, sourceInstanceId: contractId,
|
||||
controlPlaneSourceInstanceId: `plan-control-${seq}`,
|
||||
});
|
||||
await port.openRun({ ...CONTROL_PLANE_CONFORMANCE_OPEN,
|
||||
identity: { companyId, issueId, runId, agentId, sessionId: runId }, sourceInstanceId: contractId });
|
||||
await port.completeRun({ result: yielded, terminal: { schema: "paperclip.prp.terminal.v1",
|
||||
turnTerminalState: "completed", runTerminalState: "succeeded", reportedWorkDisposition: "yielded" },
|
||||
callerResultId: `plan-result-${seq}` });
|
||||
await db.insert(workspaceOperations).values({ companyId, heartbeatRunId: runId, issueId,
|
||||
phase: "workspace_finalize", status: "succeeded" });
|
||||
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.id, issue!.lastStatusDecisionId!));
|
||||
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issueId));
|
||||
const wakes = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
|
||||
eq(agentWakeupRequests.agentId, agentId)));
|
||||
return { issueId, runId, issue: issue!, decision: decision!, cards,
|
||||
wakes: wakes.filter(wake => JSON.stringify(wake.payload ?? {}).includes(issueId)) };
|
||||
}
|
||||
|
||||
it("opens one review card for the new plan revision and waits on it", async () => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
|
||||
expect(settled.cards).toHaveLength(1);
|
||||
expect(settled.cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending", sourceRunId: settled.runId });
|
||||
expect(settled.cards[0]!.payload).toMatchObject({ target: { type: "issue_document", key: "plan", revisionNumber: 1 } });
|
||||
expect(settled.issue.status).toBe("in_review");
|
||||
expect(settled.decision.reasonCode).toBe("governed_response_waiting");
|
||||
});
|
||||
|
||||
it("asks the agent for its plan when a Plan-mode run yields with none", async () => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: false });
|
||||
|
||||
expect(settled.cards).toHaveLength(0);
|
||||
expect(settled.decision.reasonCode).toBe("plan_mode_plan_not_produced");
|
||||
expect(settled.wakes.some(wake => JSON.stringify(wake.payload).includes("Plan mode"))).toBe(true);
|
||||
});
|
||||
|
||||
it("gives a task left without its card by an older release one on the next recovery pass", async () => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
// The state an older release left: settled, waiting, no card.
|
||||
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
|
||||
const enqueueWakeup = vi.fn(async () => null);
|
||||
const recovery = recoveryService(db, { enqueueWakeup });
|
||||
|
||||
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
await recovery.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
|
||||
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]).toMatchObject({ kind: "request_confirmation", status: "pending" });
|
||||
expect(enqueueWakeup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("settles the run when opening the card fails, and the next recovery pass opens it", async () => {
|
||||
cardFailure.next = true;
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
|
||||
expect(settled.cards).toHaveLength(0);
|
||||
expect(settled.issue.status).toBe("in_progress");
|
||||
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
|
||||
expect(run).toMatchObject({ status: "succeeded" });
|
||||
|
||||
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
|
||||
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
const cards = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
expect(cards).toEqual([expect.objectContaining({ kind: "request_confirmation", status: "pending" })]);
|
||||
});
|
||||
|
||||
it.each(["finalization reason", "committed plan wait"])("never opens a second card for a plan the user already accepted (%s)", async (proof) => {
|
||||
const settled = await settleRun({ workMode: "planning", writePlan: true });
|
||||
await db.delete(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId));
|
||||
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, settled.issueId));
|
||||
if (proof === "finalization reason") {
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, settled.runId));
|
||||
await db.update(heartbeatRuns).set({ resultJson: { ...(run!.resultJson as Record<string, unknown>),
|
||||
finalizationReasonCode: "native_plan_accepted_waiting_for_continuation" } }).where(eq(heartbeatRuns.id, settled.runId));
|
||||
} else committedPlanWait.runIds.add(settled.runId);
|
||||
|
||||
await recoveryService(db, { enqueueWakeup: vi.fn(async () => null) })
|
||||
.reconcileStrandedAssignedIssues({ companyId, issueId: settled.issueId });
|
||||
|
||||
expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, settled.issueId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("leaves a Standard-mode response wait unchanged", async () => {
|
||||
const settled = await settleRun({ workMode: "standard", writePlan: true });
|
||||
|
||||
expect(settled.cards).toHaveLength(0);
|
||||
expect(settled.issue.status).toBe("in_progress");
|
||||
expect(settled.decision.reasonCode).toBe("response_wake_waiting_for_input");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,543 @@
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
agents,
|
||||
companies,
|
||||
createDb,
|
||||
documentRevisions,
|
||||
documents,
|
||||
goals,
|
||||
heartbeatRuns,
|
||||
issueComments,
|
||||
issueDocuments,
|
||||
issueThreadInteractions,
|
||||
issues,
|
||||
} from "@paperclipai/db";
|
||||
import { ensureNativePlanReviewCard, planReviewCardIdempotencyKey } from "../services/native-runtime/native-plan-review-card.js";
|
||||
import { synchronizeCompletedProviderPlan } from "../services/native-runtime/native-session-executor.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
|
||||
// Lets a test hand the card function the document as it was read before a
|
||||
// newer revision landed: the window a delayed settle runs in.
|
||||
const staleRead = vi.hoisted(() => ({ next: null as unknown }));
|
||||
vi.mock("../services/documents.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/documents.js")>();
|
||||
return {
|
||||
...actual,
|
||||
documentService: (db: Parameters<typeof actual.documentService>[0]) => {
|
||||
const service = actual.documentService(db);
|
||||
return {
|
||||
...service,
|
||||
getIssueDocumentByKey: async (...args: Parameters<typeof service.getIssueDocumentByKey>) => {
|
||||
if (staleRead.next) {
|
||||
const snapshot = staleRead.next;
|
||||
staleRead.next = null;
|
||||
return snapshot as Awaited<ReturnType<typeof service.getIssueDocumentByKey>>;
|
||||
}
|
||||
return service.getIssueDocumentByKey(...args);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_PLAN_REVIEW_CARD_TEST_DATABASE_URL");
|
||||
const embeddedPostgresSupport = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
const PLAN = "# Create crash-proof.txt\n\n1. Write the file.\n2. Verify it.";
|
||||
|
||||
// Harnesses without a provider plan event (Antigravity and other ACPX agents)
|
||||
// write the Plan document with a tool. A Plan-mode run that settles without
|
||||
// opening the review card — for example a run recovered after its process was
|
||||
// killed — must not leave the task waiting on a review nobody can give.
|
||||
describeEmbeddedPostgres("Plan-mode review card on settle", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!external) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plan-review-card-");
|
||||
db = createDb(external ?? tempDb!.connectionString, { maxConnections: 6 });
|
||||
}, 20_000);
|
||||
|
||||
afterEach(async () => {
|
||||
await db.delete(activityLog);
|
||||
await db.delete(issueComments);
|
||||
await db.delete(issueThreadInteractions);
|
||||
await db.delete(issueDocuments);
|
||||
await db.delete(documentRevisions);
|
||||
await db.delete(documents);
|
||||
await db.delete(heartbeatRuns);
|
||||
await db.delete(issues);
|
||||
await db.delete(goals);
|
||||
await db.delete(agents);
|
||||
await db.delete(companies);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end({ timeout: 1 });
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
let prefix = 0;
|
||||
async function seed(workMode: "standard" | "planning" = "planning", options: { conversation?: boolean } = {}) {
|
||||
const companyId = randomUUID();
|
||||
const goalId = randomUUID();
|
||||
const issueId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Paperclip", issuePrefix: `PRC${++prefix}`, requireBoardApprovalForNewAgents: false });
|
||||
await db.insert(goals).values({ id: goalId, companyId, title: "Ship", level: "task", status: "active" });
|
||||
await db.insert(agents).values({
|
||||
id: agentId, companyId, name: "Gemma", role: "engineer", status: "active",
|
||||
adapterType: "antigravity_local", adapterConfig: {}, runtimeConfig: {}, permissions: {},
|
||||
});
|
||||
await db.insert(issues).values({
|
||||
id: issueId, companyId, goalId, title: "Create crash-proof.txt", status: "in_progress",
|
||||
priority: "medium", assigneeAgentId: agentId, workMode,
|
||||
...(options.conversation ? { conversationAgentId: agentId, conversationUserId: "local-board", conversationState: "active" } : {}),
|
||||
});
|
||||
const newRun = async () => {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "succeeded", contextSnapshot: { issueId } });
|
||||
return runId;
|
||||
};
|
||||
const binding = (runId: string) => ({ companyId, issueId, agentId, runId });
|
||||
const writePlan = async (runId: string, body = PLAN) => documentService(db).upsertIssueDocument({
|
||||
issueId, key: "plan", title: "Plan", format: "markdown", body,
|
||||
baseRevisionId: (await documentService(db).getIssueDocumentByKey(issueId, "plan"))?.latestRevisionId ?? undefined,
|
||||
createdByAgentId: agentId, createdByRunId: runId,
|
||||
} as never);
|
||||
const cards = () => db.select().from(issueThreadInteractions)
|
||||
.where(and(eq(issueThreadInteractions.issueId, issueId), eq(issueThreadInteractions.kind, "request_confirmation")));
|
||||
return { companyId, issueId, agentId, newRun, binding, writePlan, cards };
|
||||
}
|
||||
|
||||
it("opens exactly one review card for a recovered run's new plan revision", async () => {
|
||||
const t = await seed();
|
||||
await t.newRun(); // the killed run
|
||||
const recovered = await t.newRun();
|
||||
await t.writePlan(recovered);
|
||||
|
||||
const outcome = await ensureNativePlanReviewCard(db, t.binding(recovered));
|
||||
|
||||
expect(outcome.kind).toBe("created");
|
||||
const cards = await t.cards();
|
||||
expect(cards).toHaveLength(1);
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
expect(cards[0]).toMatchObject({ status: "pending", sourceRunId: recovered, createdByAgentId: t.agentId });
|
||||
expect(cards[0]!.payload).toMatchObject({
|
||||
acceptLabel: "Approve plan", rejectLabel: "Request changes",
|
||||
target: { type: "issue_document", key: "plan", revisionId: plan!.latestRevisionId, revisionNumber: 1 },
|
||||
});
|
||||
const activity = await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId));
|
||||
expect(activity).toEqual([expect.objectContaining({ action: "issue.thread_interaction_created", actorType: "system" })]);
|
||||
});
|
||||
|
||||
// The agent's plan card opened as instructed: bound to the saved plan revision.
|
||||
async function agentPlanCard(t: Awaited<ReturnType<typeof seed>>, runId: string, key: string) {
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
return issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
|
||||
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee",
|
||||
payload: { version: 1, prompt: "Approve the plan?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
|
||||
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
|
||||
revisionId: plan!.latestRevisionId, revisionNumber: plan!.latestRevisionNumber } },
|
||||
} as never, { agentId: t.agentId, runId });
|
||||
}
|
||||
const plainCard = (t: Awaited<ReturnType<typeof seed>>, runId: string, key: string, prompt: string) =>
|
||||
issueThreadInteractionService(db).create({ id: t.issueId, companyId: t.companyId }, {
|
||||
kind: "request_confirmation", idempotencyKey: key, sourceRunId: runId, continuationPolicy: "wake_assignee_on_accept",
|
||||
payload: { version: 1, prompt, acceptLabel: "Confirm", rejectLabel: "Request changes" },
|
||||
} as never, { agentId: t.agentId, runId });
|
||||
|
||||
it("does nothing when the agent already opened its plan card for the revision", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
await agentPlanCard(t, runId, "confirm-plan-v1");
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending" });
|
||||
expect(await t.cards()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps one card across repeated and concurrent settles of the same and later runs", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
const reconcileRun = await t.newRun();
|
||||
|
||||
const outcomes = await Promise.all([
|
||||
ensureNativePlanReviewCard(db, t.binding(runId)),
|
||||
ensureNativePlanReviewCard(db, t.binding(runId)),
|
||||
ensureNativePlanReviewCard(db, t.binding(reconcileRun)),
|
||||
]);
|
||||
await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
await ensureNativePlanReviewCard(db, t.binding(reconcileRun));
|
||||
|
||||
expect(outcomes.filter(outcome => outcome.kind === "created")).toHaveLength(1);
|
||||
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, t.issueId))).toHaveLength(1);
|
||||
const cards = await t.cards();
|
||||
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
|
||||
expect(cards).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("opens a new card for the revision written after Request changes and leaves the old one unanswerable", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
const created = await ensureNativePlanReviewCard(db, t.binding(first));
|
||||
if (created.kind !== "created") throw new Error("expected a card");
|
||||
const interactions = issueThreadInteractionService(db);
|
||||
const [oldCard] = await t.cards();
|
||||
await interactions.rejectInteraction(
|
||||
{ id: t.issueId, companyId: t.companyId }, oldCard!.id,
|
||||
{ reason: "Name the file crash-proof-2.txt" } as never, { userId: "local-board" } as never,
|
||||
);
|
||||
|
||||
// Request changes answered this revision: nothing new until the agent revises.
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "reviewed" });
|
||||
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Use crash-proof-2.txt.`);
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const cards = await t.cards();
|
||||
expect(cards).toHaveLength(2);
|
||||
const pending = cards.filter(card => card.status === "pending");
|
||||
expect(pending).toHaveLength(1);
|
||||
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
|
||||
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("rejected");
|
||||
});
|
||||
|
||||
it("replaces a still-pending card for an older revision", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
await ensureNativePlanReviewCard(db, t.binding(first));
|
||||
const [oldCard] = await t.cards();
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Revised.`);
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const cards = await t.cards();
|
||||
expect(cards.find(card => card.id === oldCard!.id)?.status).toBe("expired");
|
||||
expect(cards.filter(card => card.status === "pending")).toHaveLength(1);
|
||||
await expect(interactionsAccept(t, oldCard!.id)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("never withdraws a newer revision's card from a delayed settle of an older one", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
const revisionOne = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Revised.`);
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
// The first run's settle read revision 1 before revision 2 landed.
|
||||
staleRead.next = revisionOne;
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "not_applicable" });
|
||||
|
||||
const cards = await t.cards();
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]).toMatchObject({ status: "pending" });
|
||||
expect(cards[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
|
||||
});
|
||||
|
||||
it("withdraws the agent's plan card for v1 when a recovered run writes v2, leaving one answerable card", async () => {
|
||||
const t = await seed();
|
||||
const crashed = await t.newRun();
|
||||
await t.writePlan(crashed);
|
||||
const v1 = await agentPlanCard(t, crashed, "own-v1");
|
||||
const recovered = await t.newRun();
|
||||
await t.writePlan(recovered, `${PLAN}\n3. Revised after recovery.`);
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(recovered))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const pending = (await t.cards()).filter(card => card.status === "pending");
|
||||
expect(pending).toHaveLength(1);
|
||||
expect(pending[0]!.payload).toMatchObject({ target: { revisionNumber: 2 } });
|
||||
await expect(interactionsAccept(t, v1.id)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("keeps an unrelated confirmation opened after the plan ordinary: answering it never approves the plan", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
const unrelated = await plainCard(t, runId, "rename-repo", "May I rename the repository?");
|
||||
expect((unrelated.payload as { target?: unknown }).target).toBeUndefined();
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "created" });
|
||||
await interactionsAccept(t, unrelated.id);
|
||||
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
|
||||
expect(issue!.workMode).toBe("planning");
|
||||
const planCards = (await t.cards()).filter(card => (card.payload as { target?: { key?: string } }).target?.key === "plan");
|
||||
expect(planCards).toEqual([expect.objectContaining({ status: "pending" })]);
|
||||
});
|
||||
|
||||
it("leaves a card opened before plan binding existed answerable, and still opens the current plan's card", async () => {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
// A row an older release saved: the agent's plan card with no target.
|
||||
const [legacy] = await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "pending",
|
||||
continuationPolicy: "wake_assignee_on_accept", sourceRunId: first, createdByAgentId: t.agentId,
|
||||
payload: { version: 1, prompt: "Proceed with plan v1?", acceptLabel: "Confirm", rejectLabel: "Request changes" },
|
||||
}).returning();
|
||||
const second = await t.newRun();
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
await t.writePlan(second, `${PLAN}\n3. Revised.`);
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "created" });
|
||||
|
||||
const cards = await t.cards();
|
||||
// Not withdrawn by guess; its answer reaches the agent as an ordinary confirmation.
|
||||
expect(cards.find(card => card.id === legacy!.id)?.status).toBe("pending");
|
||||
expect(cards.filter(card => card.status === "pending" &&
|
||||
(card.payload as { target?: { revisionNumber?: number } }).target?.revisionNumber === 2)).toHaveLength(1);
|
||||
// Accepting the old card does not approve the newer revision.
|
||||
await interactionsAccept(t, legacy!.id);
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, t.issueId));
|
||||
expect(issue!.workMode).toBe("planning");
|
||||
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["server", "agent"])("keeps run A's pending %s plan card as the gate when run B settles a Plan-mode conversation", async (opener) => {
|
||||
const t = await seed("planning", { conversation: true });
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
if (opener === "server") await expect(ensureNativePlanReviewCard(db, t.binding(first))).resolves.toMatchObject({ kind: "created" });
|
||||
else await agentPlanCard(t, first, "conversation-plan");
|
||||
const second = await t.newRun();
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(second))).resolves.toMatchObject({ kind: "pending" });
|
||||
expect((await t.cards()).filter(card => card.status === "pending")).toHaveLength(1);
|
||||
});
|
||||
|
||||
async function interactionsAccept(t: Awaited<ReturnType<typeof seed>>, id: string) {
|
||||
return issueThreadInteractionService(db).acceptInteraction(
|
||||
{ id: t.issueId, companyId: t.companyId, projectId: null, goalId: null }, id, {} as never, { userId: "local-board" } as never,
|
||||
);
|
||||
}
|
||||
|
||||
it("returns the original card for an identical retry after a plan revision landed", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
const first = await plainCard(t, runId, "retry-key", "May I proceed?");
|
||||
// The response was lost; meanwhile the agent saved its plan.
|
||||
await t.writePlan(runId);
|
||||
|
||||
const retried = await plainCard(t, runId, "retry-key", "May I proceed?");
|
||||
expect(retried.id).toBe(first.id);
|
||||
});
|
||||
|
||||
it("reports a Plan-mode run with no plan, and leaves Standard tasks untouched", async () => {
|
||||
const planning = await seed();
|
||||
const runId = await planning.newRun();
|
||||
await expect(ensureNativePlanReviewCard(db, planning.binding(runId))).resolves.toEqual({ kind: "no_plan" });
|
||||
expect(await planning.cards()).toHaveLength(0);
|
||||
|
||||
const standard = await seed("standard");
|
||||
const standardRun = await standard.newRun();
|
||||
await standard.writePlan(standardRun);
|
||||
await expect(ensureNativePlanReviewCard(db, standard.binding(standardRun))).resolves.toEqual({ kind: "not_applicable" });
|
||||
expect(await standard.cards()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("leaves the card Codex and Claude open from their plan event as the only card", async () => {
|
||||
const t = await seed();
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: t.companyId, agentId: t.agentId, status: "running", contextSnapshot: { issueId: t.issueId } });
|
||||
const synced = await synchronizeCompletedProviderPlan({
|
||||
db,
|
||||
execution: {
|
||||
binding: t.binding(runId), provider: { kind: "codex" }, task: { workMode: "planning" }, executionMode: "plan",
|
||||
planningContext: { documentId: null, baseRevisionId: null, baseRevisionNumber: 0, markdown: "", sha256: "none", reviewContext: {} },
|
||||
} as never,
|
||||
event: { sourceEventId: "event-1", turnId: "turn-1", eventType: "plan.proposed",
|
||||
payload: { schema: "paperclip.plan.proposed.v1", proposalId: "plan-1", status: "completed", markdown: PLAN, source: "codex" } },
|
||||
});
|
||||
expect(synced).toMatchObject({ status: "synchronized" });
|
||||
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({ kind: "pending", interactionId: synced!.confirmationId });
|
||||
expect(await t.cards()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not put a person's own plan edit up for review", async () => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await documentService(db).upsertIssueDocument({
|
||||
issueId: t.issueId, key: "plan", title: "Plan", format: "markdown", body: "# My plan", createdByUserId: "local-board",
|
||||
});
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toEqual({ kind: "not_applicable" });
|
||||
expect(await t.cards()).toHaveLength(0);
|
||||
});
|
||||
// Each way a Plan-mode run can leave the task, and the one current action
|
||||
// the user gets: a review card for the revision, or (no plan / already
|
||||
// answered) the arbiter's "save your plan" continuation.
|
||||
type Scenario = { name: string; setup: (t: Awaited<ReturnType<typeof seed>>, runId: string) => Promise<void>;
|
||||
kind: "created" | "pending" | "reviewed" | "no_plan" };
|
||||
const question = async (t: Awaited<ReturnType<typeof seed>>, runId: string) => {
|
||||
const [row] = await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "ask_user_questions", status: "pending",
|
||||
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
|
||||
payload: { version: 1, questions: [{ id: "q1", prompt: "Which name?", selectionMode: "single",
|
||||
options: [{ id: "a", label: "A" }] }] },
|
||||
}).returning();
|
||||
return row!;
|
||||
};
|
||||
const scenarios: Scenario[] = [
|
||||
{ name: "no plan saved", setup: async () => {}, kind: "no_plan" },
|
||||
{ name: "plan saved, agent opened no card (first run or recovered run)", setup: async (t, runId) => { await t.writePlan(runId); }, kind: "created" },
|
||||
{ name: "plan saved, agent opened its plan card bound to the revision", setup: async (t, runId) => {
|
||||
await t.writePlan(runId); await agentPlanCard(t, runId, `own-${runId}`);
|
||||
}, kind: "pending" },
|
||||
{ name: "plan saved, agent opened an unbound confirmation (ordinary, not a plan review)", setup: async (t, runId) => {
|
||||
await t.writePlan(runId); await plainCard(t, runId, `plain-${runId}`, "Proceed?");
|
||||
}, kind: "created" },
|
||||
{ name: "plan saved, agent asked a current question", setup: async (t, runId) => {
|
||||
await t.writePlan(runId); await question(t, runId);
|
||||
}, kind: "pending" },
|
||||
{ name: "plan saved, an older question a later comment made historical", setup: async (t, runId) => {
|
||||
await question(t, runId);
|
||||
await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
|
||||
authorUserId: "local-board", body: "Use A.", createdAt: new Date(Date.now() + 1_000) });
|
||||
await t.writePlan(runId);
|
||||
}, kind: "created" },
|
||||
{ name: "plan saved, an older question the user dismissed", setup: async (t, runId) => {
|
||||
const row = await question(t, runId);
|
||||
await db.update(issueThreadInteractions).set({ dismissedAt: new Date(), dismissedByUserId: "local-board" })
|
||||
.where(eq(issueThreadInteractions.id, row.id));
|
||||
await t.writePlan(runId);
|
||||
}, kind: "created" },
|
||||
...(["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"] as const).flatMap(key =>
|
||||
(["pending", "accepted", "rejected"] as const).map((status): Scenario => ({
|
||||
name: `plan saved, an unrelated ${key} card (${status}) opened after it`,
|
||||
setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status,
|
||||
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
|
||||
payload: { version: 1, prompt: "Allow this?", [key]: { id: "governed" } },
|
||||
});
|
||||
},
|
||||
kind: "created",
|
||||
}))),
|
||||
{ name: "plan saved, a confirmation someone else opened after it", setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: "rejected",
|
||||
continuationPolicy: "none", createdByUserId: "local-board",
|
||||
payload: { version: 1, prompt: "Unrelated?" },
|
||||
});
|
||||
}, kind: "created" },
|
||||
{ name: "revision already answered with Request changes, no new revision", setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
const [card] = await t.cards();
|
||||
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
|
||||
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
|
||||
}, kind: "reviewed" },
|
||||
{ name: "new revision after Request changes", setup: async (t, runId) => {
|
||||
await t.writePlan(runId);
|
||||
await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
const [card] = await t.cards();
|
||||
await issueThreadInteractionService(db).rejectInteraction({ id: t.issueId, companyId: t.companyId }, card!.id,
|
||||
{ reason: "Rename it" } as never, { userId: "local-board" } as never);
|
||||
await t.writePlan(runId, `${PLAN}\n3. Renamed.`);
|
||||
}, kind: "created" },
|
||||
];
|
||||
|
||||
it.each(scenarios)("$name", async ({ setup, kind }) => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await setup(t, runId);
|
||||
|
||||
const outcome = await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
expect(outcome.kind).toBe(kind);
|
||||
// A repeat settle changes nothing, and at most one review card is pending.
|
||||
await expect(ensureNativePlanReviewCard(db, t.binding(runId))).resolves.toMatchObject({
|
||||
kind: kind === "created" ? "pending" : kind });
|
||||
const planReviews = (await t.cards()).filter(card => card.status === "pending" &&
|
||||
(card.payload as { target?: { key?: string } }).target?.key === "plan");
|
||||
expect(planReviews.length).toBeLessThanOrEqual(1);
|
||||
if (kind === "created") expect(planReviews).toHaveLength(1);
|
||||
});
|
||||
// Every state the current revision's own plan card can reach, and what the
|
||||
// user is left with: a current card, or (they decided) the agent's bounded
|
||||
// "revise your plan" continuation. Never a silent wait, never a second card
|
||||
// for a plan the user already accepted.
|
||||
type CardState = { status: string; by?: "user" | "agent" | "system"; dismissed?: boolean; laterComment?: boolean;
|
||||
outcome: "pending" | "reviewed" | "created" };
|
||||
const cardStates: CardState[] = [
|
||||
{ status: "pending", outcome: "pending" },
|
||||
{ status: "pending", dismissed: true, outcome: "pending" },
|
||||
{ status: "pending", laterComment: true, outcome: "pending" },
|
||||
{ status: "accepted", by: "user", outcome: "reviewed" },
|
||||
{ status: "rejected", by: "user", outcome: "reviewed" },
|
||||
{ status: "cancelled", by: "user", outcome: "reviewed" },
|
||||
{ status: "cancelled", by: "agent", outcome: "created" },
|
||||
{ status: "expired", by: "system", outcome: "created" },
|
||||
{ status: "expired", by: "agent", outcome: "created" },
|
||||
{ status: "failed", by: "system", outcome: "created" },
|
||||
];
|
||||
it.each(cardStates)("current revision's card $status (by $by, dismissed $dismissed, later comment $laterComment) -> $outcome",
|
||||
async ({ status, by, dismissed, laterComment, outcome }) => {
|
||||
const t = await seed();
|
||||
const runId = await t.newRun();
|
||||
await t.writePlan(runId);
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
const resolved = status !== "pending";
|
||||
const [card] = await db.insert(issueThreadInteractions).values(<typeof issueThreadInteractions.$inferInsert>{
|
||||
companyId: t.companyId, issueId: t.issueId, kind: "request_confirmation", status: status as never,
|
||||
continuationPolicy: "wake_assignee", sourceRunId: runId, createdByAgentId: t.agentId,
|
||||
idempotencyKey: planReviewCardIdempotencyKey(plan!.latestRevisionId!),
|
||||
payload: { version: 1, prompt: "Approve plan revision 1?", acceptLabel: "Approve plan", rejectLabel: "Request changes",
|
||||
target: { type: "issue_document", issueId: t.issueId, documentId: plan!.id, key: "plan",
|
||||
revisionId: plan!.latestRevisionId, revisionNumber: 1 } },
|
||||
...(resolved ? { resolvedAt: new Date(),
|
||||
resolvedByUserId: by === "user" ? "local-board" : null,
|
||||
resolvedByAgentId: by === "agent" ? t.agentId : null } : {}),
|
||||
...(dismissed ? { dismissedAt: new Date(), dismissedByUserId: "local-board" } : {}),
|
||||
}).returning();
|
||||
if (laterComment) await db.insert(issueComments).values({ companyId: t.companyId, issueId: t.issueId, authorType: "user",
|
||||
authorUserId: "local-board", body: "Looking now.", createdAt: new Date(Date.now() + 1_000) });
|
||||
|
||||
const first = await ensureNativePlanReviewCard(db, t.binding(runId));
|
||||
expect(first.kind).toBe(outcome);
|
||||
const again = await ensureNativePlanReviewCard(db, t.binding(await t.newRun()));
|
||||
expect(again.kind).toBe(outcome === "created" ? "pending" : outcome);
|
||||
const pending = (await t.cards()).filter(row => row.status === "pending");
|
||||
if (outcome === "reviewed") expect(pending).toHaveLength(0);
|
||||
else expect(pending).toHaveLength(1);
|
||||
if (outcome === "created") expect(pending[0]!.id).not.toBe(card!.id);
|
||||
});
|
||||
it("opens exactly one card for the current revision when settles race across a revision change", async () => {
|
||||
for (let round = 0; round < 15; round += 1) {
|
||||
const t = await seed();
|
||||
const first = await t.newRun();
|
||||
await t.writePlan(first);
|
||||
await ensureNativePlanReviewCard(db, t.binding(first));
|
||||
const second = await t.newRun();
|
||||
await t.writePlan(second, `${PLAN}\n3. Round ${round}.`);
|
||||
const runs = await Promise.all([t.newRun(), t.newRun(), t.newRun()]);
|
||||
|
||||
await Promise.all([second, ...runs].map(runId => ensureNativePlanReviewCard(db, t.binding(runId))));
|
||||
|
||||
const plan = await documentService(db).getIssueDocumentByKey(t.issueId, "plan");
|
||||
const pending = (await t.cards()).filter(card => card.status === "pending");
|
||||
expect(pending).toHaveLength(1);
|
||||
expect(pending[0]!.payload).toMatchObject({ target: { revisionId: plan!.latestRevisionId } });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
|
||||
import { NATIVE_PLAN_REVIEW_DIRECTIVE, buildPaperclipTaskMarkdown } from "./task-markdown.js";
|
||||
|
||||
const issue = {
|
||||
id: "task-1",
|
||||
@@ -66,6 +66,15 @@ describe("heartbeat task markdown rendering", () => {
|
||||
expect(markdown).toContain("Do not invent material user intent or success criteria");
|
||||
});
|
||||
|
||||
it("tells a native Plan-mode run that Paperclip opens the one plan review card", () => {
|
||||
const planning = { issue: { ...issue, workMode: "planning" } };
|
||||
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true })).toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
|
||||
// Adapters keep their own approval flow, and an accepted plan is executed.
|
||||
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: false })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
|
||||
expect(buildPaperclipTaskMarkdown({ ...planning, nativeRunner: true, acceptedPlanContinuation: true,
|
||||
taskPlan: { documentId: "plan", revisionId: "revision", revisionNumber: 1, body: "Do it." } })).not.toContain(NATIVE_PLAN_REVIEW_DIRECTIVE);
|
||||
});
|
||||
|
||||
it("preserves execution of a clear accepted plan without imposing clarification", () => {
|
||||
const markdown = buildPaperclipTaskMarkdown({
|
||||
issue: { ...issue, workMode: "planning" },
|
||||
|
||||
@@ -7,6 +7,9 @@ import { TASK_QUESTION_GUIDANCE } from "../issue-question-context.js";
|
||||
import { routineSuggestionAgentGuidance } from "@paperclipai/shared";
|
||||
import { ONBOARDING_CHAT_DIRECTIVE, ONBOARDING_CHAT_GREETING_DIRECTIVE } from "../onboarding-chat-prompt.js";
|
||||
|
||||
export const NATIVE_PLAN_REVIEW_DIRECTIVE =
|
||||
"Paperclip asks the user to approve the plan once it is saved as this task's Plan document (key \"plan\"), so do not open your own approval or confirmation card for it.";
|
||||
|
||||
export function buildPaperclipTaskMarkdown(input: {
|
||||
companyPrefix?: string | null;
|
||||
onboardingChat?: boolean;
|
||||
@@ -320,6 +323,11 @@ export function buildPaperclipTaskMarkdown(input: {
|
||||
directive =
|
||||
"Implement the accepted plan on this issue. Follow any task assignments explicitly included in the approved plan. Plan acceptance alone does not require subtasks.";
|
||||
}
|
||||
if (!acceptedPlanContinuation && input.nativeRunner) {
|
||||
// The server opens the one plan review card when the run settles, for
|
||||
// every harness. An agent-opened card would be a second card.
|
||||
directive += ` ${NATIVE_PLAN_REVIEW_DIRECTIVE}`;
|
||||
}
|
||||
lines.push(
|
||||
`- Work mode: ${quoteTaskScalar("planning")}`,
|
||||
"",
|
||||
|
||||
@@ -3,10 +3,24 @@ import { heartbeatRuns, issueComments, issueThreadInteractions, type Db } from "
|
||||
|
||||
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 (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))`;
|
||||
and not (${governedActionPayloadSql()}))`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -17,7 +31,7 @@ export function ordinaryQuestionCondition() {
|
||||
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 not (${governedActionPayloadSql()})
|
||||
and coalesce(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'issue_document')`;
|
||||
}
|
||||
|
||||
@@ -89,7 +103,7 @@ export function activeIssueInteractionCondition(input: {
|
||||
${ordinaryQuestionCondition()}
|
||||
or (${issueThreadInteractions.kind} in ('request_confirmation', 'request_checkbox_confirmation')
|
||||
and ${issueThreadInteractions.effectiveResolverPolicy} = 'anyone'
|
||||
and not (${issueThreadInteractions.payload} ?| array['toolAction', 'secretProposal', 'connectionAuthorization']))
|
||||
and not (${governedActionPayloadSql()}))
|
||||
)
|
||||
)` : undefined,
|
||||
)!;
|
||||
|
||||
@@ -14,7 +14,7 @@ import { notifyToolReviewChange } from "./tool-review-work-notifications.js";
|
||||
import { projectGitHubInteractionErrors } from "./tool-access/github-action-error-projection.js";
|
||||
import { normalizeEscapedLineBreaks } from "@paperclipai/shared/validators/text";
|
||||
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
|
||||
import { historicalQuestionCondition } from "./issue-question-context.js";
|
||||
import { hasGovernedPayload, historicalQuestionCondition } from "./issue-question-context.js";
|
||||
import {
|
||||
currentContinuationOrigins,
|
||||
deliveredContinuationCommentIds,
|
||||
@@ -228,6 +228,8 @@ type CreateInteractionOptions = {
|
||||
supersedePendingSiblingInteractions?: boolean;
|
||||
replayAcceptedInteractionIds?: readonly string[];
|
||||
requireAcceptedReplay?: boolean;
|
||||
/** Runs once, in the insert transaction, only when this call created the card (never on an idempotent replay). */
|
||||
afterInsertInTransaction?: (tx: Db, row: IssueThreadInteractionRow) => Promise<void>;
|
||||
};
|
||||
|
||||
type InteractionWakeup = (
|
||||
@@ -693,7 +695,7 @@ async function isEquivalentAcceptedReplay(
|
||||
if (
|
||||
!replayAcceptedInteractionIds.includes(row.id)
|
||||
|| !isRequestConfirmationLikeKind(row.kind)
|
||||
|| ["toolAction", "secretProposal", "connectionAuthorization", "qualityReview"].some(key => Object.hasOwn(row.payload, key))
|
||||
|| hasGovernedPayload(row.payload)
|
||||
|| row.status !== "accepted"
|
||||
|| row.result?.outcome !== "accepted"
|
||||
|| !row.resolvedAt
|
||||
@@ -5324,6 +5326,7 @@ export function issueThreadInteractionService(
|
||||
})
|
||||
.returning();
|
||||
|
||||
await options.afterInsertInTransaction?.(tx as unknown as Db, row);
|
||||
if (row.addresseeAgentId || row.addresseeUserId) {
|
||||
const [privacyIssue] = await tx.select().from(issues).where(and(eq(issues.id, issue.id), eq(issues.companyId, issue.companyId)));
|
||||
await ensureAssignmentIssueAccessGrant(tx, { ...privacyIssue!,
|
||||
|
||||
@@ -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" &&
|
||||
|
||||
@@ -27,6 +27,7 @@ import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
|
||||
import { RESTRICTED_WORKSPACE_SOURCE_REASON } from "../workspace-source-restriction.js";
|
||||
import { PROJECT_STORAGE_ENVIRONMENT_INCOMPATIBLE } from "../project-storage-environment-reason.js";
|
||||
import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.js";
|
||||
import { ensureNativePlanReviewCard } from "../native-runtime/native-plan-review-card.js";
|
||||
import { hasCommittedNativeConversationTurnWait, hasCommittedNativeResponseWakeWait } from "../native-runtime/native-response-wake-wait.js";
|
||||
import { listExternalReviewWaits } from "../native-runtime/external-review-wait.js";
|
||||
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
|
||||
@@ -5096,6 +5097,28 @@ export function recoveryService(
|
||||
continue;
|
||||
}
|
||||
|
||||
// A Plan-mode task whose run settled before the server opened plan
|
||||
// review cards on settle (or whose card opening was interrupted) gets
|
||||
// its card here; the card is then its next action.
|
||||
if (
|
||||
issue.workMode === "planning" &&
|
||||
issue.status === "in_progress" &&
|
||||
latestRun?.status === "succeeded" &&
|
||||
latestRun.agentId === agentId &&
|
||||
// An accepted native plan waits for the user's next message; its
|
||||
// answered plan question is the review. Never ask for it again.
|
||||
parseObject(latestRun.resultJson).finalizationReasonCode !== "native_plan_accepted_waiting_for_continuation" &&
|
||||
!(await hasCommittedNativePlanWait(db, {
|
||||
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
|
||||
})) &&
|
||||
(await ensureNativePlanReviewCard(db, {
|
||||
companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId,
|
||||
})).kind === "created"
|
||||
) {
|
||||
result.skipped += 1;
|
||||
result.issueIds.push(issue.id);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
await hasActiveExecutionPath(
|
||||
issue.companyId,
|
||||
|
||||
Reference in new issue
Block a user