Fix native Claude question bridging and runner behavioral regressions

Validate completion revisions in-turn, clarify text questions and approved handoffs, and make continuation and approval-overlap fixtures deterministic. Add native Claude question round-trip coverage.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-09-18 22:05:48 -05:00
1 parent 86d1992ac4
commit cd34aaee0c
40 files changed
+563 -206

No files matched your search

@@ -23,7 +23,7 @@ Work in this order.
1. Take the path the user picked.
- `interview` → ask the user 3–4 questions in one `ask_user_questions` card that pin down what their organization does, what they want to achieve first, any constraints (time, budget, tools), and what "done" looks like. Don't guess; ask. Don't post anything else before the card. The answers lead to the plan-and-team path in step 2.
- `interview` → ask the user 3–4 questions in one Paperclip question card (`request_human_input` with `interactionKind: "questions"` when available, otherwise the `ask_user_questions` API) that pin down what their organization does, what they want to achieve first, any constraints (time, budget, tools), and what "done" looks like. Don't guess; ask. Don't post anything else before the card. The answers lead to the plan-and-team path in step 2.
- `task` → the text they typed is the task. If it is clear enough to propose on, go straight to step 2. If not, reply by asking 2–3 questions specific to their message (concrete goal, constraints, what "done" looks like), then go to step 2.
@@ -31,6 +31,7 @@ Work in this order.
2. Propose, then wait for acceptance.
- Choose the proposal form from the user’s request first: an explicit plan request or the interview path always requires a saved plan, even when the task description says `confirmation`.
- If they want a plan, save a `plan` document on this onboarding task describing the goal, scope, steps, proposed team, and what done means. Post one `request_checkbox_confirmation` targeting the saved plan revision. A card or thread message alone is not a saved plan. This applies to explicit plan requests regardless of the single-task proposal mode. Proposing a team does not authorize hiring it.
- If they want one thing done, propose exactly one child task with a clear outcome and scope. Ask them to accept it before creating the child. Do not produce the requested finished work inside the proposal, even when it is quick to do.
- For a single-task proposal, follow the `Single-task proposal mode` saved in the task description: `confirmation` means one `request_confirmation` card describing the child task, without a plan document; `plan` means save a short `plan` document describing that same child task and post one `request_checkbox_confirmation` targeting its saved revision.
+1 -1
View File
@@ -85,7 +85,7 @@ When the user asks to approve a plan before handoff, publish the plan and create
Before handing off work, inspect available projects and repositories. Every task you create from this chat must belong to a suitable project. Reuse an appropriate existing project; otherwise use create_project. Consider all relevant available repositories and pass repositoryIds for one or multiple repositories when the work spans them. For existing GitHub repositories you can access that are absent from the catalog, pass their HTTPS repositoryUrls; this registers them with the project without creating remote GitHub repositories. You may combine known IDs and URLs and attach multiple repositories. The direct HTTP equivalent is POST /api/companies/{companyId}/projects with name, repositoryIds and/or repositoryUrls arrays, and an idempotencyKey. Include all selected repositories in that creation; do not combine these arrays with workspace. Never invent repository IDs or substitute inaccessible repositories. Ask when the choice is materially ambiguous or required access is missing. Non-code projects may need no repository.
Create ordinary assigned tasks, never subtasks of this conversation. Give each task a clear outcome, context, acceptance criteria, project, and appropriate assignee. Use create_task with initialPlan to copy the relevant plan into the new task before execution starts. If using the HTTP API directly, POST /api/companies/{companyId}/issues with projectId, assigneeAgentId, status: "todo", initialPlan containing the relevant plan Markdown, and an idempotencyKey; omit parentId. Putting a plan in description does not create the task's plan document. Verify the new task's plan document before claiming the handoff is complete. Preserve the original plan here. When splitting work, include the relevant part of the plan in each task. Create and link each task before claiming it exists.
Create ordinary assigned tasks, never subtasks of this conversation. Give each task a clear outcome, context, acceptance criteria, project, and appropriate assignee. Use create_task with initialPlan to copy the relevant plan into the new task before execution starts. If using the HTTP API directly, POST /api/companies/{companyId}/issues with projectId, assigneeAgentId, status: "todo", initialPlan containing the relevant plan Markdown, and an idempotencyKey; omit parentId. Putting a plan in description does not create the task's plan document. Verify the new task's plan document before claiming the handoff is complete. Preserve the original plan here. Carry forward only the remaining execution steps, not completed planning, approval, project creation, or task creation steps. Include the source conversation ID, approved plan revision ID, and accepted interaction ID so the worker can verify the recorded approval. State the approved scope and what is already done; do not claim the new plan document has its own approval. The worker should execute that authorized scope, and ask again only if scope changes or another applicable gate requires it. When splitting work, include the relevant part of the plan in each task. Create and link each task before claiming it exists.
Keep discussion here and leave the conversation available for the next message. Link handed-off tasks in your reply; do not make this conversation blocked by their completion or wait for them. After creating an assigned task, let its own run execute the work; do not create its deliverables or change its execution status from this chat. Reply normally and end your turn; Paperclip manages the conversation waiting state. Do not change its status, create a review confirmation just to finish a reply, mark it complete, or poll for another reply. An accepted plan authorizes handoff to execution tasks, never implementation on this conversation. Honor normal approvals. Ask mode is non-mutating. Plan mode supports research and writing/revising the plan; hand off for execution only through the normal authorized workflow.`;
@@ -0,0 +1,45 @@
import { randomUUID } from "node:crypto";
import { beforeAll, afterAll, describe, expect, it } from "vitest";
import { eq } from "drizzle-orm";
import { createDb, companies, agents, issues, heartbeatRuns, documents, documentRevisions, issueDocuments, issueThreadInteractions } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { handoffPlanContext } from "./handoff-plan-context.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("handoff approval evidence", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
beforeAll(async () => { temporary = await startEmbeddedPostgresTestDatabase("handoff-plan-"); db = createDb(temporary.connectionString); }, 20_000);
afterAll(async () => { await temporary?.cleanup(); });
async function seed() {
const companyId = randomUUID(), agentId = randomUUID(), sourceId = randomUUID(), runId = randomUUID();
const documentId = randomUUID(), revisionId = randomUUID(), interactionId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Handoff", issuePrefix: companyId.slice(0, 8) });
await db.insert(agents).values({ id: agentId, companyId, name: "Planner", adapterType: "paperclip_runner" });
await db.insert(issues).values({ id: sourceId, companyId, title: "Source chat", conversationAgentId: agentId, assigneeAgentId: agentId, conversationUserId: "operator", conversationState: "active" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: sourceId, status: "succeeded" });
await db.insert(documents).values({ id: documentId, companyId, latestBody: "A newer unapproved plan" });
await db.insert(documentRevisions).values({ id: revisionId, documentId, companyId, revisionNumber: 1, body: "Write the approved note." });
await db.insert(issueDocuments).values({ companyId, issueId: sourceId, documentId, key: "plan" });
await db.insert(issueThreadInteractions).values({ id: interactionId, companyId, issueId: sourceId, kind: "request_confirmation", status: "accepted", resolvedAt: new Date("2026-09-01"), payload: { version: 1, prompt: "Approve the plan", target: { type: "issue_document", key: "plan", revisionId } } });
const [task] = await db.insert(issues).values({ companyId, title: "Execute", originRunId: runId, createdAt: new Date("2026-09-02") }).returning();
return { task, companyId, sourceId, runId, revisionId, interactionId, documentId };
}
it("returns the exact accepted source revision, never a newer unapproved body or new-document approval", async () => {
const f = await seed();
const result = await handoffPlanContext(db, f.task);
expect(result).toMatchObject({ sourceIssueId: f.sourceId, revisionId: f.revisionId, interactionId: f.interactionId, markdown: "Write the approved note." });
expect(result?.guidance).toContain("not approval of changes");
expect(result?.guidance).toContain("Preserve other applicable gates");
});
it.each(["pending", "later", "other-company", "other-task", "unrelated-document", "no-origin"])("does not infer authority from %s evidence", async (kind) => {
const f = await seed();
if (kind === "pending") await db.update(issueThreadInteractions).set({ status: "pending" }).where(eq(issueThreadInteractions.id, f.interactionId));
if (kind === "later") await db.update(issueThreadInteractions).set({ resolvedAt: new Date("2026-09-03") }).where(eq(issueThreadInteractions.id, f.interactionId));
if (kind === "other-company") f.task.companyId = randomUUID();
if (kind === "other-task") await db.update(issues).set({ conversationAgentId: null, conversationUserId: null, conversationState: null }).where(eq(issues.id, f.sourceId));
if (kind === "unrelated-document") await db.update(issueDocuments).set({ key: "unrelated" }).where(eq(issueDocuments.documentId, f.documentId));
if (kind === "no-origin") f.task.originRunId = null;
expect(await handoffPlanContext(db, f.task)).toBeNull();
});
});
@@ -0,0 +1,33 @@
import { and, desc, eq, lte } from "drizzle-orm";
import { documentRevisions, heartbeatRuns, issueDocuments, issues, issueThreadInteractions, type Db } from "@paperclipai/db";
/** Approval evidence belongs to the source conversation and exact revision.
* It informs scope; it does not approve the new task's document or waive gates. */
export async function handoffPlanContext(db: Db, task: typeof issues.$inferSelect) {
if (!task.originRunId || task.conversationAgentId) return null;
const [sourceRun] = await db.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, task.originRunId), eq(heartbeatRuns.companyId, task.companyId),
));
const sourceId = sourceRun?.nativeIssueId ?? sourceRun?.contextSnapshot?.issueId;
if (typeof sourceId !== "string" || sourceId === task.id) return null;
const [source] = await db.select().from(issues).where(and(eq(issues.id, sourceId), eq(issues.companyId, task.companyId)));
if (!source?.conversationAgentId) return null;
const accepted = await db.select().from(issueThreadInteractions).where(and(
eq(issueThreadInteractions.companyId, task.companyId), eq(issueThreadInteractions.issueId, source.id),
eq(issueThreadInteractions.kind, "request_confirmation"), eq(issueThreadInteractions.status, "accepted"),
lte(issueThreadInteractions.resolvedAt, task.createdAt),
)).orderBy(desc(issueThreadInteractions.resolvedAt));
for (const interaction of accepted) {
const target = (interaction.payload as { target?: { type?: string; key?: string; revisionId?: string; issueId?: string } }).target;
if (target?.type !== "issue_document" || target.key !== "plan" || !target.revisionId ||
(target.issueId && target.issueId !== source.id)) continue;
const [revision] = await db.select({ markdown: documentRevisions.body, revisionId: documentRevisions.id })
.from(documentRevisions).innerJoin(issueDocuments, and(
eq(issueDocuments.documentId, documentRevisions.documentId), eq(issueDocuments.companyId, task.companyId),
eq(issueDocuments.issueId, source.id), eq(issueDocuments.key, "plan"),
)).where(and(eq(documentRevisions.id, target.revisionId), eq(documentRevisions.companyId, task.companyId)));
if (revision) return { sourceIssueId: source.id, interactionId: interaction.id, ...revision,
guidance: "This source plan was accepted before this task was created. Execute the assigned scope within that plan; planning and handoff steps already completed in the source are not new work. This is not approval of changes to scope or of a new task document. Preserve other applicable gates." };
}
return null;
}
@@ -8,6 +8,7 @@ import {
approvals,
agents,
heartbeatRuns,
completionContracts,
issueApprovals,
issueThreadInteractions,
issues,
@@ -55,6 +56,21 @@ export async function nativeCompletionFeedback(
? "Review blocker recorded. Paperclip will preserve the task and record the reviewer recovery action."
: "Review report accepted. The recorded review decision controls task completion; this report cannot override it.";
}
// Bind feedback to this run, not the first contract from a reused session or
// an unrelated newer run. Reject before admitting the result so the provider
// can correct the report in the same turn.
if (run.completionContractId) {
const contract = await db.select().from(completionContracts).where(and(
eq(completionContracts.id, run.completionContractId),
eq(completionContracts.companyId, run.companyId),
eq(completionContracts.issueId, issue.id),
)).then((rows) => rows[0]);
if (!contract) throw new Error("Completion report's bound contract no longer exists.");
const current = contract.contractJson as { revision?: string; criteria?: Array<{ id: string }> };
if (result.completionClaim.contractRevision !== current.revision) {
throw new Error(`Stale completionClaim.contractRevision. This turn requires ${JSON.stringify(current.revision)} with criterion IDs ${JSON.stringify(current.criteria?.map((c) => c.id) ?? [])}. Reassess the current request and resubmit your report with that revision; do not repeat completed work.`);
}
}
const signals = normalizePrpResultSignals(result);
if (
result.reportedWorkDisposition === "done" &&
@@ -199,12 +199,17 @@ describeEmbeddedPostgres("native question bridge", () => {
};
}
it("materializes, validates, and durably resumes a provider-neutral question response", async () => {
it.each(["codex", "claude"])("materializes, validates, and durably resumes a %s question response", async (provider) => {
await seed();
const interaction = await projectNativeRuntimeRequest({
db,
binding: binding(),
event: runtimeRequestEvent(),
event: { ...runtimeRequestEvent(), payload: {
request: { ...(runtimeRequestEvent().payload.request as Record<string, unknown>),
origin: { adapter: provider === "claude" ? "acpx-runtime-sidecar" : "codex-app-server", provider,
method: provider === "claude" ? "elicitation/create" : "item/tool/requestUserInput" },
},
} },
});
expect(interaction).toMatchObject({
@@ -1053,7 +1053,7 @@ describe("PaperclipControlPlanePort conformance", () => {
backendKind: "mock",
sourceInstanceId: runnerInstanceId,
});
const result = { ...structuredClone(CONTROL_PLANE_CONFORMANCE_RESULT), reportedWorkDisposition: "needs_review" as const, attentionRequests: [{ kind: "approval" as const, summary: "Approve publication", ownerClass: "human" as const }, { kind: "review" as const, summary: "Review release notes", ownerClass: "agent" as const, targetAgentId: reviewerAgentId }] };
const result = { ...structuredClone(CONTROL_PLANE_CONFORMANCE_RESULT), completionClaim: { ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, contractRevision: "phase6-v1" }, reportedWorkDisposition: "needs_review" as const, attentionRequests: [{ kind: "approval" as const, summary: "Approve publication", ownerClass: "human" as const }, { kind: "review" as const, summary: "Review release notes", ownerClass: "agent" as const, targetAgentId: reviewerAgentId }] };
await expect(nativeCompletionFeedback(db, runId, { ...result, attentionRequests: [] }))
.rejects.toThrow("needs_review requires");
await expect(nativeCompletionFeedback(db, runId, {
@@ -1062,6 +1062,10 @@ describe("PaperclipControlPlanePort conformance", () => {
await expect(nativeCompletionFeedback(db, runId, {
...result, attentionRequests: [{ kind: "review", summary: "Review work", ownerClass: "agent", targetAgentId: "99999999-9999-4999-8999-999999999999" }],
})).rejects.toThrow("not available in this company");
await expect(nativeCompletionFeedback(db, runId, {
...result,
completionClaim: { ...result.completionClaim, contractRevision: "stale-first-turn" },
})).rejects.toThrow(/contractRevision.*phase6-v1/);
await expect(nativeCompletionFeedback(db, runId, result)).resolves.toContain("Completion report accepted");
await port.completeRun({
result,
@@ -1,3 +1,4 @@
import { handoffPlanContext } from "./handoff-plan-context.js";
import { callCreateSkillTool } from "../skill-tools.js";
import { callProjectTool } from "../project-tools.js";
import { isConnectorTool, executeConnectorTool, type ConnectorAssignment } from "../connector-runtime.js";
@@ -378,6 +379,7 @@ export class PaperclipRunnerToolAuthority {
},
connectionGuidance: CONNECTION_INTENT_AGENT_GUIDANCE,
acceptedPlan: await this.#acceptedPlan(context.run.contextSnapshot),
sourcePlanApproval: await handoffPlanContext(this.db, context.issue),
childReviewOutcomes: await childReviewOutcomes(this.db, this.binding.companyId, this.binding.issueId),
...(this.binding.nativeReview ? {
assignedReview: (await getNativeReviewAssignment(this.db, {
@@ -1349,7 +1351,7 @@ export class PaperclipRunnerToolAuthority {
}
: null;
if (targetRevisionId !== null && suppliedPayload.target === undefined && inferredPlanningTarget === null) {
throw new Error("paperclip_runner_interaction_target_incomplete");
throw new Error('paperclip_runner_interaction_target_incomplete: targetRevisionId also requires payload.target = { type: "issue_document", key: "plan", revisionId: targetRevisionId }. Use the actual document key. If the source plan already authorized this scope, do not request approval again merely because the execution task has a new plan document.');
}
const normalizedPayload = inferredPlanningTarget !== null
? { ...suppliedPayload, target: inferredPlanningTarget }