mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
fix(runner): preserve sessions and complete question and approval continuations (#13655)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The native runner connects task state to provider sessions. > - Follow-up turns must retain provider memory and carry new user direction. > - Lost session IDs caused repeated context and extra input tokens. > - Native question answers and approval races could leave valid work blocked. > - This pull request repairs those paths and adds regression coverage. > - Agents can continue accepted work without repeating the conversation or losing the user's answer. ## Linked Issues or Issue Description Refs #13574. That merged PR shortened continuation prompts and moved question instructions into tool documentation. This change preserves sessions and fixes failures exposed by broader testing. Related runtime work: #13408 and #13410. **What happened?** Native follow-up turns could lose the provider session ID. Completion guidance could replace the original task with its latest comment. Claude native questions could remain pending after the user answered. Approval during a running tool call could suspend the run before the tool response arrived. Onboarding and chat handoff instructions also caused repeated planning or missing plan documents. **Expected behavior** Reuse a valid provider session. Send only new events when that session already has the history. Preserve the task requirements and apply later user direction. Store the question answer and deliver it to the waiting run. Finish governed tool responses before suspending. Execute the accepted plan without asking for the same approval again. **Steps to reproduce** Run the continuation, local-session-integrity, first-task, and agent-chat suites with native Codex and Claude. Include provider-question-bridge, accept-while-running, and plan-handoff. **Paperclip version or commit** This branch is based on masterd54b75011. The active full catalog run tests4e75881db. Later review fixes have separate regression coverage. **Deployment mode** Isolated local instances and Daytona sandboxes in the existing Runner full-stack E2E harness. ## What Changed - Retain provider session identity across turns and late usage snapshots. Send new continuation events on session reuse, with full context available for a fresh session. - Preserve task requirements and later direction in completion guidance. Return the current contract revision after a stale completion submission. - Bridge native Claude questions to saved Paperclip cards. Submit answers through the saved card and resume the same run. - Delay governed suspension until tool results settle. Add a deterministic test barrier for approval during an active run. - Clarify free-text question examples, explicit onboarding plans, and execution of accepted chat plans. - Fix continuation readiness, verified output evidence, and declared screenshot collection. - Qualify the legacy Claude test CLI at 2.1.277. The old 2.1.19 CLI did not discover mounted skills. Update the existing workflow pin and isolated launcher together. - Refresh the Daytona image lockfile integrity pin after reviewing master patch updates. - Carry continuation mode as runtime metadata instead of inferring it from user-visible text. Install the test Claude CLI without lifecycle scripts. ## Verification - Targeted paid verification: 20/20 cases passed across local-environment campaigns before the rebase. [Report](https://pages.paperclip.ing/runner-e2e-seven-fixes-35397904249/). - Harness checks: 379 unit tests passed; harness typecheck passed. - Latest-head PR checks: 55 passed, two intentionally skipped. Greptile is 5/5; the security scan passes. - Review regressions: 350 executor tests and 204 session/driver tests passed. A script-free Claude install was verified with the actual CLI. - Full catalog, including the explicit-only everyday suite: [run 35417932353](https://github.com/paperclipai/paperclip/actions/runs/35417932353). Completed: **164/205 passed; 41 failed**. [Full dashboard and failure investigation](https://pages.paperclip.ing/runner-e2e-full-catalog-35417932353/). Includes 204 case artifacts and one pre-case GitHub authorization timeout; missing evidence is not scored as a pass. The full run tested `4e75881db`; Final-head metadata/CLI smoke cases both passed. In the separate [six infrastructure retries](https://github.com/paperclipai/paperclip/actions/runs/35419769343), the GitHub timeout case passed and all five Docker preflight failures repeated. [Follow-up dashboard](https://pages.paperclip.ing/runner-e2e-full-catalog-35417932353/follow-up/). - Full local typecheck and build passed on the rebased branch. The full local unit run completed with 657 passing files, two test timeouts and one suite setup timeout. All three affected files passed when rerun in isolation (84 tests). The first full local run was not clean. - Focused regression coverage includes the live question bridge, same-run response delivery, UI routing, stale revisions, approval overlap, and session reuse. ## Full-catalog follow-ups - Test infrastructure: 14 Claude everyday cells probe an absent host CLI; six cells failed pre-task GitHub/Docker qualification (GitHub passes on retry; all five Docker cases repeat; the workflow preflight allowlist omits their case IDs); five ACPX Codex cells cannot create sandbox namespaces. - Runtime: four OpenCode completion-criteria mismatches masked by shutdown errors, one service-approval suspension failure; three Daytona recovery failures encounter existing skill files; one duplicate completion wake. - Confirmed test defects: question pagination and a noncanonical plan document key. - Product/behavior: mismatched visible/required question sets, an attachment instead of the requested task document, one lone-option onboarding question, early completion instead of review, and a Codex Mini completion-schema failure. - The report job itself fails on trusted master’s stale patch/lock configuration. The linked report is rebuilt with the shared renderer from original cell results and public fixture screenshots; it excludes private snapshots, logs and traces. These are investigated follow-ups, not silently regraded passes. First-task passed 51/52. The PR checks are green independently of the broader catalog’s behavioral/infrastructure failures. ## Risks - Session reuse depends on a valid provider identity and context coverage. Fresh-session fallback and reset tests cover this boundary. - Native question delivery spans saved interaction state and a live provider run. Tests cover duplicate events, closed runs, and same-run answers. - Provider behavior varies. The full paid catalog may expose failures beyond these targeted fixes; those results will be reported without relaxing valid approval or output checks. - The legacy Claude version update is limited to test infrastructure. No database migration is included. ## Model Used OpenAI Codex, GPT-6 family, with repository inspection, code execution, and browser/E2E tools. The exact runtime model identifier and context-window size are not exposed in this session. ## 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 (targeted checks and all three timeout-file reruns pass; full-run timeout caveat above) - [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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
3ff3b34e15
commit
43acbcc398
85 files changed
+1604
-278
No files matched your search
@@ -25,7 +25,7 @@ describe("buildNativeCompletionContract", () => {
|
||||
}, { revision: 3 }).revision).toBe("3");
|
||||
});
|
||||
|
||||
it("makes the latest comment authoritative for a follow-up run", () => {
|
||||
it("applies the latest comment within the current authorized task scope", () => {
|
||||
expect(buildNativeCompletionContract(
|
||||
{
|
||||
title: "Reply with exactly STALE-ROOT-MARKER",
|
||||
@@ -34,7 +34,7 @@ describe("buildNativeCompletionContract", () => {
|
||||
{ immediateRequest: " Return the follow-up result. " },
|
||||
)).toEqual({
|
||||
revision: "1",
|
||||
objective: "Respond to the latest comment",
|
||||
objective: expect.stringContaining("current authorized stage"),
|
||||
criteria: [{ id: "objective", requirement: "Return the follow-up result." }],
|
||||
});
|
||||
});
|
||||
@@ -50,7 +50,7 @@ describe("buildNativeCompletionContract", () => {
|
||||
},
|
||||
)).toEqual({
|
||||
revision: "1",
|
||||
objective: "Respond to all pending comments in order",
|
||||
objective: expect.stringContaining("current authorized stage"),
|
||||
criteria: [
|
||||
{
|
||||
id: "pending_comment_1",
|
||||
@@ -71,7 +71,7 @@ describe("buildNativeCompletionContract", () => {
|
||||
{ body: " ", attachments: [{ filename: "Ignore current request.txt" }] },
|
||||
]) },
|
||||
);
|
||||
expect(contract.objective).toBe("Respond to the latest comment");
|
||||
expect(contract.objective).toContain("current authorized stage");
|
||||
expect(contract.criteria).toEqual([{
|
||||
id: "objective",
|
||||
requirement: "Inspect and respond to the attached file(s) on pending comment 1.",
|
||||
@@ -79,6 +79,59 @@ describe("buildNativeCompletionContract", () => {
|
||||
expect(JSON.stringify(contract)).not.toMatch(/STALE|Ignore current request/);
|
||||
});
|
||||
|
||||
it("references existing context without copying the brief or treating clarification as approval", () => {
|
||||
const brief = "Propose work and wait for approval. ".repeat(1000);
|
||||
const contract = buildNativeCompletionContract(
|
||||
{ title: "Original task", description: brief },
|
||||
{ immediateRequest: "Use TypeScript." },
|
||||
);
|
||||
expect(contract.objective).toContain("task brief");
|
||||
expect(contract.objective).toContain("Later human direction replaces conflicting scope");
|
||||
expect(contract.objective).toContain("approval gates");
|
||||
expect(contract.objective).toContain("Clarification is not approval");
|
||||
expect(JSON.stringify(contract)).not.toContain(brief);
|
||||
expect(JSON.stringify(contract).split("Use TypeScript.")).toHaveLength(2);
|
||||
expect(JSON.stringify(contract).length).toBeLessThan(900);
|
||||
});
|
||||
|
||||
it("keeps the instruction prefix identical as follow-up comments change", () => {
|
||||
const issue = { title: "Write welcome", description: "Use /first-task." };
|
||||
const first = buildNativeCompletionContract(issue, { immediateRequest: "Use a friendly tone." });
|
||||
const next = buildNativeCompletionContract(issue, { immediateRequest: "Actually, just save a plan." });
|
||||
expect(first.objective).toBe(next.objective);
|
||||
expect(next.criteria).toEqual([{ id: "objective", requirement: "Actually, just save a plan." }]);
|
||||
expect(JSON.stringify(next)).not.toContain("Use a friendly tone.");
|
||||
});
|
||||
|
||||
it("binds the current verified card answer without duplicating its contents", () => {
|
||||
const contract = buildNativeCompletionContract(
|
||||
{ title: "Onboarding", description: "Use /first-task; proposal mode: confirmation." },
|
||||
{ humanResponseId: "80000000-0000-4000-8000-000000000008" },
|
||||
);
|
||||
expect(contract.objective).toContain("humanResponses");
|
||||
expect(contract.criteria).toEqual([{
|
||||
id: "human_response",
|
||||
requirement: expect.stringContaining('"80000000-0000-4000-8000-000000000008"'),
|
||||
}]);
|
||||
expect(contract.criteria[0]!.requirement).toContain("humanResponses");
|
||||
expect(JSON.stringify(contract)).not.toContain("proposal mode: confirmation");
|
||||
expect(buildNativeCompletionContract(
|
||||
{ title: "Onboarding", description: null },
|
||||
{ humanResponseId: "80000000-0000-4000-8000-000000000009" },
|
||||
)).not.toEqual(contract);
|
||||
});
|
||||
|
||||
it("retains pending comments alongside a current card response without replaying older scope", () => {
|
||||
const contract = buildNativeCompletionContract(
|
||||
{ title: "Implement", description: "Implement the old scope" },
|
||||
{ immediateRequest: "Actually, just investigate.", humanResponseId: "answer-id" },
|
||||
);
|
||||
expect(contract.criteria.map(c => c.id)).toEqual(["objective", "human_response"]);
|
||||
expect(contract.criteria[0]!.requirement).toBe("Actually, just investigate.");
|
||||
expect(JSON.stringify(contract)).not.toContain("Implement the old scope");
|
||||
expect(contract.objective).toContain("Later human direction replaces conflicting scope");
|
||||
});
|
||||
|
||||
it("preserves text and file-only requests in mixed batch order", () => {
|
||||
expect(nativeCompletionRequestsForComments([
|
||||
{ body: " First question. " },
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { StrictCompletionContractInput } from "../../vendor/paperclip-runne
|
||||
import { nativeSha256 } from "./canonical.js";
|
||||
|
||||
export const NATIVE_COMPLETION_CONTRACT_SCHEMA = "paperclip.completion-contract.v1";
|
||||
export const NATIVE_COMPLETION_POLICY_VERSION = "phase6-v3";
|
||||
export const NATIVE_COMPLETION_POLICY_VERSION = "phase6-v4";
|
||||
|
||||
export function nativeCompletionRequestsForComments(
|
||||
comments: readonly {
|
||||
@@ -51,6 +51,8 @@ export function buildNativeCompletionContract(
|
||||
readonly revision?: number;
|
||||
readonly immediateRequest?: string | null;
|
||||
readonly immediateRequests?: readonly string[] | null;
|
||||
/** ID of this wake's server-verified humanResponses entry; its content is already in task context. */
|
||||
readonly humanResponseId?: string | null;
|
||||
} = {},
|
||||
): StrictCompletionContractInput {
|
||||
const immediateRequests = (
|
||||
@@ -59,22 +61,27 @@ export function buildNativeCompletionContract(
|
||||
)
|
||||
.map((request) => request.trim())
|
||||
.filter((request) => request.length > 0);
|
||||
const hasFollowUp = immediateRequests.length > 0;
|
||||
const humanResponseId = options.humanResponseId?.trim();
|
||||
const hasFollowUp = immediateRequests.length > 0 || Boolean(humanResponseId);
|
||||
// Reference existing context rather than copying the brief/history into every
|
||||
// follow-up contract. Keep this guidance stable across comments and resumes.
|
||||
const followUpObjective = "Complete the current authorized stage using the task brief and current user direction in the supplied context. Later human direction replaces conflicting scope; preserve other requirements, assigned-skill instructions, and approval gates. Apply authenticated humanResponses only to their question or decision. Clarification is not approval. If acceptance is required, propose or save the requested plan and wait before executing.";
|
||||
return {
|
||||
revision: String(options.revision ?? 1),
|
||||
objective: hasFollowUp
|
||||
? immediateRequests.length === 1
|
||||
? "Respond to the latest comment"
|
||||
: "Respond to all pending comments in order"
|
||||
? followUpObjective
|
||||
: issue.title,
|
||||
criteria: hasFollowUp
|
||||
? immediateRequests.map((request, index) => ({
|
||||
id:
|
||||
immediateRequests.length === 1
|
||||
? "objective"
|
||||
: `pending_comment_${index + 1}`,
|
||||
requirement: request,
|
||||
}))
|
||||
? [
|
||||
...immediateRequests.map((request, index) => ({
|
||||
id: immediateRequests.length === 1 ? "objective" : `pending_comment_${index + 1}`,
|
||||
requirement: request,
|
||||
})),
|
||||
...(humanResponseId ? [{
|
||||
id: "human_response",
|
||||
requirement: `Apply the server-verified humanResponses entry with id ${JSON.stringify(humanResponseId)} in the supplied current request context, within its question or decision scope and subject to later user direction.`,
|
||||
}] : []),
|
||||
]
|
||||
: [
|
||||
{
|
||||
id: "objective",
|
||||
@@ -97,6 +104,7 @@ export async function ensureNativeCompletionContract(input: {
|
||||
actorId: string;
|
||||
immediateRequest?: string | null;
|
||||
immediateRequests?: readonly string[] | null;
|
||||
humanResponseId?: string | null;
|
||||
}) {
|
||||
return input.db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${[
|
||||
@@ -120,6 +128,7 @@ export async function ensureNativeCompletionContract(input: {
|
||||
revision: latestRevision,
|
||||
immediateRequest: input.immediateRequest,
|
||||
immediateRequests: input.immediateRequests,
|
||||
humanResponseId: input.humanResponseId,
|
||||
});
|
||||
const latestCandidateSha256 = nativeSha256({
|
||||
schemaVersion: NATIVE_COMPLETION_CONTRACT_SCHEMA,
|
||||
@@ -136,6 +145,7 @@ export async function ensureNativeCompletionContract(input: {
|
||||
revision: nextRevision,
|
||||
immediateRequest: input.immediateRequest,
|
||||
immediateRequests: input.immediateRequests,
|
||||
humanResponseId: input.humanResponseId,
|
||||
});
|
||||
const canonicalSha256 = nativeSha256({
|
||||
schemaVersion: NATIVE_COMPLETION_CONTRACT_SCHEMA,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import type { HarnessRuntimeRequestResolution, PrpEvent } from "../../vendor/paperclip-runner/index.js";
|
||||
import { flushNativeQuestionResponses, projectNativeRuntimeRequest, registerNativeQuestionCommandTarget } from "./native-question-bridge.js";
|
||||
import { readPendingNativeRuntimeRequest } from "./runtime-request-resolution-authority.js";
|
||||
|
||||
/** The in-process executor must perform the same card projection and response
|
||||
* delivery as the durable PRP coordinator. The answer remains durable in DB. */
|
||||
export function createLocalNativeQuestionBridge(input: {
|
||||
db: Db;
|
||||
binding: Parameters<typeof projectNativeRuntimeRequest>[0]["binding"];
|
||||
resolve: (input: {
|
||||
runId: string; requestId: string; turnId: string;
|
||||
resolution: HarnessRuntimeRequestResolution;
|
||||
authorizeBeforeDispatch: () => Promise<void>;
|
||||
}) => Promise<{ commandId: string }>;
|
||||
}) {
|
||||
let release: (() => void) | undefined;
|
||||
const close = () => { release?.(); release = undefined; };
|
||||
return {
|
||||
close,
|
||||
async attach() {
|
||||
close();
|
||||
release = registerNativeQuestionCommandTarget({
|
||||
binding: input.binding,
|
||||
queueCommand: async (type, payload) => {
|
||||
if (type !== "request.resolve" || typeof payload?.requestId !== "string") throw new Error("native_question_command_invalid");
|
||||
const requestId = payload.requestId;
|
||||
const pending = await readPendingNativeRuntimeRequest(input.db, { ...input.binding, requestId });
|
||||
if (!pending || pending.requestKind !== "runtime") throw new Error("native_question_not_pending");
|
||||
const result = await input.resolve({
|
||||
runId: input.binding.runId, requestId, turnId: pending.turnId,
|
||||
resolution: { action: "submit", response: payload.response as never },
|
||||
authorizeBeforeDispatch: async () => {
|
||||
const current = await readPendingNativeRuntimeRequest(input.db, { ...input.binding, requestId });
|
||||
const [run] = await input.db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.id, input.binding.runId), eq(heartbeatRuns.companyId, input.binding.companyId),
|
||||
eq(heartbeatRuns.nativeIssueId, input.binding.issueId), eq(heartbeatRuns.agentId, input.binding.agentId),
|
||||
)).limit(1);
|
||||
if (run?.status !== "running" || current?.turnId !== pending.turnId || current.requestKind !== "runtime") throw new Error("native_question_not_pending");
|
||||
},
|
||||
});
|
||||
return { commandId: result.commandId, controllerSeq: 0 };
|
||||
},
|
||||
});
|
||||
await flushNativeQuestionResponses(input.db, input.binding.runId);
|
||||
},
|
||||
async observe(event: PrpEvent) {
|
||||
const request = event.payload.request as Record<string, unknown> | undefined;
|
||||
if (event.eventType !== "runtime_request.created" || request?.type !== "input") return;
|
||||
await projectNativeRuntimeRequest({ db: input.db, binding: input.binding, event });
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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" &&
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildNativeContinuationPrompt } from "./native-continuation.js";
|
||||
|
||||
const issue = { title: "Original task", description: "Retain my long task brief." };
|
||||
const message = { id: "new", body: "Yes, please proceed.", authorType: "user", authorId: "board", sourceTrust: "user", createdByRunId: null };
|
||||
const wake = {
|
||||
reason: "issue_commented",
|
||||
executionContinuation: {
|
||||
version: 1,
|
||||
objective: message.body,
|
||||
messages: [{ ...message, id: "old", body: "OLD_HISTORY" }, message],
|
||||
resumeDelta: { baseRunId: "prior", messages: [message] },
|
||||
completedWork: { summary: "OLD_SUMMARY" },
|
||||
humanResponses: [{ id: "old-question", result: { answer: "OLD_ANSWER" } }],
|
||||
},
|
||||
comments: [message], continuationSummary: { markdown: "OLD_SUMMARY" },
|
||||
};
|
||||
const build = (value: unknown = wake, previousIssue = issue) => buildNativeContinuationPrompt({ wakePayload: value, previousRunId: "prior", issue, previousIssue });
|
||||
|
||||
describe("native continuation event projection", () => {
|
||||
it("sends a new comment once without the unchanged brief, objective, history or summary", () => {
|
||||
const text = build()!;
|
||||
expect(text.split(message.body)).toHaveLength(2);
|
||||
for (const old of [issue.description, issue.title, "OLD_HISTORY", "OLD_SUMMARY", "OLD_ANSWER"]) expect(text).not.toContain(old);
|
||||
expect(JSON.parse(text).messages[0]).toMatchObject({ authorType: "user", body: message.body });
|
||||
expect(text.length).toBeLessThan(600);
|
||||
});
|
||||
it("only uses a delta whose base matches the actual previous run", () => {
|
||||
expect(build({ ...wake, executionContinuation: { ...wake.executionContinuation, resumeDelta: { baseRunId: "different", messages: [message] } } })).toBeNull();
|
||||
expect(build({ ...wake, executionContinuation: null })).toBeNull();
|
||||
});
|
||||
it("delivers the current authenticated answer once, not all prior answers", () => {
|
||||
const text = build({ ...wake, interactionId: "new-question", executionContinuation: { ...wake.executionContinuation, resumeDelta: { baseRunId: "prior", messages: [] }, humanResponses: [...wake.executionContinuation.humanResponses, { id: "new-question", kind: "ask_user_questions", status: "answered", resolvedByUserId: "board", result: { answer: "NEW_ANSWER" } }] } })!;
|
||||
expect(text.split("NEW_ANSWER")).toHaveLength(2);
|
||||
expect(text).not.toContain("OLD_ANSWER");
|
||||
expect(JSON.parse(text).humanResponses[0].resolvedByUserId).toBe("board");
|
||||
});
|
||||
it("includes external child completion and actual brief edits", () => {
|
||||
const text = build({ ...wake, reason: "issue_children_completed", childIssueSummaries: [{ id: "child", status: "done", summary: "CHILD_RESULT" }] }, { ...issue, description: "old brief" })!;
|
||||
expect(JSON.parse(text).taskChanges).toEqual({ description: issue.description });
|
||||
expect(text).toContain("CHILD_RESULT");
|
||||
});
|
||||
it.each([{ fallbackFetchNeeded: true }, { recovery: { cause: "interrupted" } }, { externalChatExecutionBound: true }, { reason: "issue_assigned" }])("retains bootstrap framing for special wakes: %j", (extra) => {
|
||||
expect(build({ ...wake, ...extra })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { normalizePaperclipWakePayload } from "@paperclipai/adapter-utils/server-utils";
|
||||
|
||||
/** Only new, authorized events belong in an already retained provider conversation.
|
||||
* Full bootstrap input is kept separately for an actual provider resume failure.
|
||||
*/
|
||||
export function buildNativeContinuationPrompt(input: {
|
||||
wakePayload: unknown;
|
||||
previousRunId: string;
|
||||
issue: { title: string; description: string | null };
|
||||
previousIssue: { title: string; description: string | null };
|
||||
}): string | null {
|
||||
const wake = normalizePaperclipWakePayload(input.wakePayload);
|
||||
const continuation = wake?.executionContinuation;
|
||||
const delta = continuation?.resumeDelta;
|
||||
if (!wake || !delta || delta.baseRunId !== input.previousRunId) return null;
|
||||
// These paths have specialized delivery/recovery contracts. Preserve their
|
||||
// existing framing until they have an event-specific continuation projection.
|
||||
if (!['issue_commented', 'issue_children_completed'].includes(wake.reason ?? '') ||
|
||||
wake.fallbackFetchNeeded || wake.truncated || wake.recovery || continuation?.interruptedRunId ||
|
||||
wake.externalChatExecutionBound || wake.externalChatQuestionResponse ||
|
||||
wake.taskWatchdog || wake.livenessContinuation || wake.activeTreeHold ||
|
||||
wake.skillTest || wake.executionStage || wake.agentMessage ||
|
||||
wake.documentReviewContext || wake.planReviewContext || wake.annotationDeltas.length > 0
|
||||
) return null;
|
||||
const taskChanges = Object.fromEntries(
|
||||
(["title", "description"] as const)
|
||||
.filter((key) => input.issue[key] !== input.previousIssue[key])
|
||||
.map((key) => [key, input.issue[key]]),
|
||||
);
|
||||
const humanResponses = (continuation?.humanResponses ?? []).filter((answer) => answer.id === wake.interactionId);
|
||||
// Do not substitute an unverified interaction outcome for an authorized answer.
|
||||
if (wake.interactionId && humanResponses.length === 0) return null;
|
||||
const events = {
|
||||
messages: delta.messages,
|
||||
...(humanResponses.length ? { humanResponses } : {}),
|
||||
...(Object.keys(taskChanges).length ? { taskChanges } : {}),
|
||||
...(wake.childIssueSummaries.length ? { childResults: wake.childIssueSummaries } : {}),
|
||||
...(wake.childIssueSummaryTruncated ? { childResultsTruncated: true } : {}),
|
||||
...(wake.unresolvedBlockerIssueIds.length ? { unresolvedBlockerIssueIds: wake.unresolvedBlockerIssueIds } : {}),
|
||||
};
|
||||
if (!events.messages.length && !humanResponses.length && !wake.childIssueSummaries.length && !Object.keys(taskChanges).length) return null;
|
||||
return JSON.stringify(events);
|
||||
}
|
||||
@@ -11,6 +11,7 @@ describe("explicit file output requirements", () => {
|
||||
"Do not use external services. Create a file with the results.",
|
||||
"Make a file but do not send it to anyone else.",
|
||||
"Export a summary of this PDF as CSV.",
|
||||
"Create no temporary files; export the results as CSV.",
|
||||
])("recognizes an explicit output request: %s", objective => {
|
||||
expect(explicitlyRequestsFileOutput(objective)).toBe(true);
|
||||
});
|
||||
@@ -26,6 +27,10 @@ describe("explicit file output requirements", () => {
|
||||
"Write a summary of this PDF in chat.",
|
||||
"Create a review of README.md; reply inline.",
|
||||
"Give me advice on file permissions.",
|
||||
"Post exactly one durable progress comment whose entire body is TRACKED, then finish this child task. Create no files and do not delegate or create any further tasks.",
|
||||
"Create no files.",
|
||||
"Generate no attachments and answer in chat.",
|
||||
"Write a reply without any files.",
|
||||
])("does not require a file for a text or source-review request: %s", objective => {
|
||||
expect(explicitlyRequestsFileOutput(objective)).toBe(false);
|
||||
});
|
||||
|
||||
@@ -71,6 +71,9 @@ export function explicitlyRequestsFileOutput(objective: string): boolean {
|
||||
const fileObject = [...output.matchAll(file)].some(match => {
|
||||
const prefix = output.slice(0, match.index);
|
||||
const suffix = output.slice(match.index + match[0].length);
|
||||
// "Create no files" is a prohibition, even though it contains a creation
|
||||
// verb. Negate this object only; another explicit output can still count.
|
||||
if (/\b(?:no|zero|without(?:\s+any)?)\s+(?:(?:new|temporary|downloadable|attached|additional)\s+)*$/iu.test(prefix)) return false;
|
||||
// "Write a summary of this PDF" names input, not a requested file.
|
||||
// Explicit export destinations still count after such input references.
|
||||
const destination = /\b(?:as|into|to)\s+(?:(?:a|an|the|new|separate|markdown|word|excel)\s+)*$/iu.test(prefix);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AskUserQuestionsInteraction } from "@paperclipai/shared";
|
||||
import type { ExecutionContinuationEnvelope, AskUserQuestionsInteraction } from "@paperclipai/shared";
|
||||
|
||||
import { formatDurableQuestionResponseSummary } from "../question-response-delivery.js";
|
||||
import { buildNativeCompletionContract } from "./completion-contracts.js";
|
||||
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { buildNativeExecutionInput } from "./native-execution-input.js";
|
||||
import { nativeRuntimeContextFixture } from "./runtime-context.test-fixture.js";
|
||||
|
||||
@@ -473,3 +475,41 @@ describe("native execution input external-chat framing", () => {
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
|
||||
describe("follow-up context size", () => {
|
||||
it("keeps old messages out of resume deltas while retaining scoped human answers", () => {
|
||||
const message = (id: string, body: string) => ({
|
||||
id, body, authorType: "user", authorId: "board", createdAt: "2026-09-17T00:00:00Z",
|
||||
updatedAt: "2026-09-17T00:00:00Z", deleted: false, sourceTrust: null,
|
||||
});
|
||||
const oldBody = "PREVIOUS_TASK_TEXT ".repeat(1000);
|
||||
const newBody = "Actually, save the plan first.";
|
||||
const answerText = "No budget. Wait for my approval.";
|
||||
const continuation: ExecutionContinuationEnvelope = {
|
||||
version: 1, companyId: "company", issueId: "issue", objective: "Welcome",
|
||||
trigger: { reason: "issue_commented", interactionId: "answer-id", sourceRunId: null },
|
||||
originCommentIds: ["new"], messages: [message("old", oldBody), message("new", newBody)],
|
||||
resumeDelta: { baseRunId: "previous-run", messages: [message("new", newBody)] },
|
||||
humanResponses: [{ id: "answer-id", kind: "ask_user_questions", status: "answered",
|
||||
resolvedByUserId: "board", resolvedAt: "2026-09-17T00:01:00Z",
|
||||
result: { answers: [{ questionId: "scope", optionIds: [], otherText: answerText }] } }],
|
||||
interactionOutcomes: [], completedWork: null, unresolvedInteractionIds: [],
|
||||
coverage: { kind: "full_task_history", throughCommentId: "new", summaryThroughCommentId: null },
|
||||
};
|
||||
const wake = { executionContinuation: continuation };
|
||||
const fresh = renderPaperclipWakePrompt(wake);
|
||||
const resumed = renderPaperclipWakePrompt(wake, { resumedSession: true });
|
||||
const contract = buildNativeCompletionContract({ title: "Welcome", description: oldBody }, {
|
||||
immediateRequest: newBody, humanResponseId: "answer-id",
|
||||
});
|
||||
expect(fresh).toContain(oldBody);
|
||||
expect(resumed).not.toContain("PREVIOUS_TASK_TEXT");
|
||||
expect(resumed.split(newBody)).toHaveLength(2);
|
||||
expect(resumed.split(answerText)).toHaveLength(2);
|
||||
expect(resumed).toContain("earlier history remains in this session");
|
||||
expect(JSON.stringify(contract)).not.toContain(oldBody);
|
||||
expect(JSON.stringify(contract)).not.toContain(answerText);
|
||||
expect(resumed.length + JSON.stringify(contract).length).toBeLessThan(fresh.length);
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { buildNativeContinuationPrompt } from "./native-continuation.js";
|
||||
import type {
|
||||
NativeAcpxAgent,
|
||||
NativeAcpxPermissionMode,
|
||||
@@ -45,6 +46,7 @@ export function buildNativeExecutionInput(input: {
|
||||
*/
|
||||
wakePayload?: unknown;
|
||||
resumedSession?: boolean;
|
||||
previousTurn?: { runId: string; task: { title: string; description: string | null } } | null;
|
||||
conversationMode?: boolean;
|
||||
agentId: string;
|
||||
workspace: {
|
||||
@@ -146,7 +148,7 @@ export function buildNativeExecutionInput(input: {
|
||||
}
|
||||
: input.wakePayload;
|
||||
const wakePrompt = renderPaperclipWakePrompt(wakePayload, {
|
||||
resumedSession: input.resumedSession === true,
|
||||
resumedSession: false,
|
||||
conversationMode: input.conversationMode === true,
|
||||
suppressIssueDescription: input.taskPrompt.trim().length > 0,
|
||||
nativeWakeReaderAvailable: true,
|
||||
@@ -168,6 +170,14 @@ export function buildNativeExecutionInput(input: {
|
||||
.join("\n\n");
|
||||
return parseNativeExecutionInput({
|
||||
schema: "paperclip.native-execution-input.v4",
|
||||
...(input.resumedSession && input.previousTurn && !input.conversationMode ? {
|
||||
continuationPrompt: buildNativeContinuationPrompt({
|
||||
wakePayload: input.wakePayload,
|
||||
previousRunId: input.previousTurn.runId,
|
||||
previousIssue: input.previousTurn.task,
|
||||
issue: input.issue,
|
||||
}),
|
||||
} : {}),
|
||||
executionMode,
|
||||
planningContext: input.planningContext ?? null,
|
||||
binding: {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createLocalNativeQuestionBridge } from "./local-native-question-bridge.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
companies,
|
||||
createDb,
|
||||
heartbeatRuns,
|
||||
heartbeatRunEvents,
|
||||
issueQuestionResponseDeliveries,
|
||||
issueThreadInteractions,
|
||||
issues,
|
||||
@@ -199,12 +201,45 @@ describeEmbeddedPostgres("native question bridge", () => {
|
||||
};
|
||||
}
|
||||
|
||||
it("materializes, validates, and durably resumes a provider-neutral question response", async () => {
|
||||
it("projects an executor question immediately and routes its durable answer into the same live turn", async () => {
|
||||
await seed();
|
||||
const event = runtimeRequestEvent();
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId, seq: 1,
|
||||
eventType: event.eventType, stream: "system", level: "info", payload: { prpEvent: event } });
|
||||
const resolve = vi.fn(async (input: any) => { await input.authorizeBeforeDispatch(); return { commandId: "live-response" }; });
|
||||
const bridge = createLocalNativeQuestionBridge({ db, binding: binding(), resolve });
|
||||
try {
|
||||
await bridge.attach();
|
||||
await bridge.observe(event);
|
||||
await bridge.observe(event); // replay must not create a second card
|
||||
const cards = await issueThreadInteractionService(db).listForIssue(issueId);
|
||||
expect(cards).toHaveLength(1);
|
||||
expect(cards[0]).toMatchObject({ status: "pending", sourceRunId: runId, continuationPolicy: "none" });
|
||||
const answered = await issueThreadInteractionService(db).answerQuestions(
|
||||
{ id: issueId, companyId, status: "in_progress" }, cards[0]!.id,
|
||||
{ answers: [{ questionId: "color", optionIds: ["green"] }] }, { userId: "operator-1" },
|
||||
);
|
||||
if (answered.kind !== "ask_user_questions") throw new Error("wrong question kind");
|
||||
expect(await deliverNativeQuestionResponse(db, answered)).toBe("queued");
|
||||
expect(resolve).toHaveBeenCalledWith(expect.objectContaining({ runId, requestId: "request-1", turnId: "turn-1",
|
||||
resolution: { action: "submit", response: { schema: "paperclip.question_response.v1", answers: { color: { selectedOptionIds: ["green"] } } } },
|
||||
}));
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, runId));
|
||||
await expect(resolve.mock.calls[0]![0].authorizeBeforeDispatch()).rejects.toThrow("native_question_not_pending");
|
||||
} finally { bridge.close(); }
|
||||
});
|
||||
|
||||
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({
|
||||
|
||||
@@ -34,7 +34,7 @@ type QueueCommand = (
|
||||
type: string,
|
||||
payload?: Record<string, unknown>,
|
||||
commandId?: string,
|
||||
) => { readonly commandId: string; readonly controllerSeq: number };
|
||||
) => { readonly commandId: string; readonly controllerSeq: number } | Promise<{ readonly commandId: string; readonly controllerSeq: number }>;
|
||||
|
||||
interface NativeQuestionCommandTarget {
|
||||
binding: Pick<NativeRunStoreBinding, "companyId" | "issueId" | "runId" | "agentId">;
|
||||
@@ -203,7 +203,7 @@ async function authorizedNativeRun(
|
||||
/** Materialize a canonical runtime input request as the existing task-thread card. */
|
||||
export async function projectNativeRuntimeRequest(input: {
|
||||
db: Db;
|
||||
binding: NativeRunStoreBinding;
|
||||
binding: Pick<NativeRunStoreBinding, "companyId" | "issueId" | "runId" | "agentId" | "normalizedSessionId" | "runnerSourceInstanceId">;
|
||||
event: PrpEvent;
|
||||
}): Promise<AskUserQuestionsInteraction | null> {
|
||||
if (input.event.eventType !== "runtime_request.created") return null;
|
||||
@@ -319,7 +319,7 @@ export async function deliverNativeQuestionResponse(
|
||||
return "pending";
|
||||
}
|
||||
try {
|
||||
target.queueCommand(
|
||||
await target.queueCommand(
|
||||
"request.resolve",
|
||||
{ requestId: run.requestId, response: response as unknown as Record<string, unknown> },
|
||||
`question_${interaction.id}`,
|
||||
|
||||
@@ -4125,9 +4125,25 @@ describe("native governed waits", () => {
|
||||
schemaVersion: 1,
|
||||
priority: 0 as const,
|
||||
emittedAt: "2026-08-31T00:00:00.000Z",
|
||||
payload: {},
|
||||
payload: { kind: "dynamicToolCall" },
|
||||
};
|
||||
|
||||
// A failed tool is terminal too, even when its error event omits kind.
|
||||
// It must not block the later approval tool from parking this run.
|
||||
await observation.observe({ ...replayedEvent, eventType: "item.started", itemId: "failed-command", payload: { kind: "commandExecution" } }, false);
|
||||
await observation.observe({ ...replayedEvent, eventType: "item.failed", itemId: "failed-command", payload: { error: "Command exited with status 1" } }, false);
|
||||
|
||||
// A usage event must not park while the card-creation response is held.
|
||||
await observation.observe({ ...replayedEvent, eventType: "item.started", itemId: "approval-tool" }, false);
|
||||
const usage = { ...replayedEvent, payload: { kind: "usage" } };
|
||||
await observation.observe(usage, true);
|
||||
expect(observation.consume(usage)).toBeNull();
|
||||
const other = { ...replayedEvent, itemId: "other-tool" };
|
||||
await observation.observe(other, true);
|
||||
expect(observation.consume(other)).toBeNull();
|
||||
await observation.observe({ ...replayedEvent, itemId: "approval-tool" }, true);
|
||||
expect(observation.consume({ ...replayedEvent, itemId: "approval-tool" })).toEqual(waitResult);
|
||||
|
||||
await observation.observe(replayedEvent, true);
|
||||
expect(observation.consume(replayedEvent)).toEqual(waitResult);
|
||||
expect(observation.consume(replayedEvent)).toBeNull();
|
||||
@@ -4237,6 +4253,7 @@ function leaseDb(
|
||||
const query = {
|
||||
then: Promise.resolve(rows).then.bind(Promise.resolve(rows)),
|
||||
where: () => query,
|
||||
orderBy: () => query,
|
||||
for: () => query,
|
||||
limit: () => Promise.resolve(rows),
|
||||
};
|
||||
@@ -4841,7 +4858,7 @@ describe("native runtime request resolution", () => {
|
||||
snapshot.mockReset().mockResolvedValue({ activeTurnId: "provider-turn-1" });
|
||||
resolveRuntimeRequest.mockReset().mockResolvedValue(undefined);
|
||||
state.execute.mockReset().mockImplementation(async (options) => {
|
||||
options.onSession?.({
|
||||
await options.onSession?.({
|
||||
capabilities,
|
||||
snapshot,
|
||||
resolveRuntimeRequest,
|
||||
@@ -4850,7 +4867,7 @@ describe("native runtime request resolution", () => {
|
||||
await new Promise<void>((resolve) => {
|
||||
state.release = resolve;
|
||||
});
|
||||
options.onSession?.(null);
|
||||
await options.onSession?.(null);
|
||||
return {
|
||||
result: { summary: "completed" },
|
||||
terminal: { runTerminalState: "succeeded" },
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createLocalNativeQuestionBridge } from "./local-native-question-bridge.js";
|
||||
import { readVerifiedRemoteWorkspaceFile } from "./remote-deliverable-file.js";
|
||||
import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
|
||||
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
|
||||
@@ -982,6 +983,7 @@ export function nativeConversationReplyResult(input: {
|
||||
export function createGovernedWaitEventObservation(
|
||||
resolvePending: () => Promise<PrpStructuredRunResult | null>,
|
||||
) {
|
||||
const pendingTools = new Set<string>();
|
||||
let generation = 0;
|
||||
let observation: {
|
||||
sourceInstanceId: string;
|
||||
@@ -994,6 +996,21 @@ export function createGovernedWaitEventObservation(
|
||||
async observe(event: PrpEvent, eligible: boolean): Promise<void> {
|
||||
const currentGeneration = ++generation;
|
||||
observation = null;
|
||||
const kind = record(event.payload).kind;
|
||||
const tool = ["dynamicToolCall", "mcpToolCall", "commandExecution"].includes(String(kind));
|
||||
if (event.itemId) {
|
||||
if (tool && event.eventType === "item.started") pendingTools.add(event.itemId);
|
||||
// Terminal error events can omit kind; the tracked ID owns cleanup.
|
||||
if (event.eventType === "item.completed" || event.eventType === "item.failed") {
|
||||
pendingTools.delete(event.itemId);
|
||||
}
|
||||
}
|
||||
// Usage/model messages can arrive while the tool creating the card is
|
||||
// still awaiting its response. Parking then interrupts that in-flight
|
||||
// response and cannot produce a durable suspension checkpoint.
|
||||
if (event.eventType === "item.completed" && (
|
||||
pendingTools.size > 0 || (!tool && kind !== "agentMessage")
|
||||
)) return;
|
||||
if (!eligible) return;
|
||||
const result = await resolvePending();
|
||||
if (generation !== currentGeneration || result === null) return;
|
||||
@@ -7384,6 +7401,11 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
payload: event.payload,
|
||||
},
|
||||
);
|
||||
const liveQuestions = createLocalNativeQuestionBridge({
|
||||
db: input.db,
|
||||
binding: { ...input.execution.binding, normalizedSessionId: nativeSessionKey(input.execution), runnerSourceInstanceId: effectiveRunnerInstanceId },
|
||||
resolve: resolveNativeRuntimeRequest,
|
||||
});
|
||||
let completedConversationReply: PrpEvent | null = null;
|
||||
const controlPlane = new PaperclipControlPlanePort(
|
||||
input.db,
|
||||
@@ -7405,6 +7427,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
record(event.payload).channel === "final") {
|
||||
completedConversationReply = event;
|
||||
}
|
||||
await liveQuestions.observe(event);
|
||||
await projectSessionGoalEvent(event);
|
||||
providerUsageLimitObserved ||= nativeProviderUsageLimitFromEvent(event);
|
||||
const eventAtMs = Date.parse(event.emittedAt);
|
||||
@@ -7621,6 +7644,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
// A crash can happen after the event commit but before its callback
|
||||
// finishes. Recover only idempotent durable projections here; activity,
|
||||
// publication, logging, trace, and metric effects remain committed-only.
|
||||
await liveQuestions.observe(event);
|
||||
await projectSessionGoalEvent(event);
|
||||
providerUsageLimitObserved ||= nativeProviderUsageLimitFromEvent(event);
|
||||
const questionFallback = await materializeRuntimeQuestionFallback({
|
||||
@@ -7763,6 +7787,9 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
: []),
|
||||
),
|
||||
eq(issueThreadInteractions.status, "pending"),
|
||||
// Live provider questions resume their current turn; only durable
|
||||
// wake-based cards park it. A timeout creates a separate fallback.
|
||||
sql`not (${issueThreadInteractions.kind} = 'ask_user_questions' and ${issueThreadInteractions.continuationPolicy} = 'none' and coalesce(${issueThreadInteractions.idempotencyKey}, '') like 'paperclip-runner-question:%')`,
|
||||
),
|
||||
)
|
||||
.orderBy(
|
||||
@@ -7991,6 +8018,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
},
|
||||
onSession: async (session) => {
|
||||
releaseRegisteredGoalController();
|
||||
liveQuestions.close();
|
||||
if (session?.goal) {
|
||||
releaseGoalController = registerLiveRunnerGoalController(
|
||||
{
|
||||
@@ -8055,10 +8083,12 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
session,
|
||||
cancelRequested: false,
|
||||
});
|
||||
if (session.resolveRuntimeRequest) await liveQuestions.attach();
|
||||
if (nativeRunsDetachingForRestart.has(input.execution.binding.runId)) {
|
||||
await session.detachControllerForRestart?.();
|
||||
}
|
||||
} else {
|
||||
liveQuestions.close();
|
||||
activeNativeSessions.delete(input.execution.binding.runId);
|
||||
clearSteeringDeliveries(input.execution.binding.runId);
|
||||
clearNativeRuntimeRequestResolutions(
|
||||
@@ -8094,12 +8124,14 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
startedAtMs: turnCompletedAtMs ?? nativeSessionExecuteStartedAtMs,
|
||||
endedAtMs: Date.now(),
|
||||
});
|
||||
liveQuestions.close();
|
||||
activeNativeSessions.delete(input.execution.binding.runId);
|
||||
clearSteeringDeliveries(input.execution.binding.runId);
|
||||
clearNativeRuntimeRequestResolutions(input.execution.binding.runId);
|
||||
} catch (error) {
|
||||
if (nativeRunsDetachingForRestart.has(input.execution.binding.runId)) {
|
||||
await leaseRenewal.stop().catch(() => undefined);
|
||||
liveQuestions.close();
|
||||
activeNativeSessions.delete(input.execution.binding.runId);
|
||||
// Disconnecting deliberately ends the old event consumer. It is not a
|
||||
// provider failure and must not overwrite the shutdown adoption record
|
||||
@@ -8145,6 +8177,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
});
|
||||
}
|
||||
trace.activate(taskSettleScope);
|
||||
liveQuestions.close();
|
||||
activeNativeSessions.delete(input.execution.binding.runId);
|
||||
clearSteeringDeliveries(input.execution.binding.runId);
|
||||
clearNativeRuntimeRequestResolutions(input.execution.binding.runId);
|
||||
|
||||
@@ -2598,9 +2598,10 @@ describe("buildNativeExecutionInput wake projection", () => {
|
||||
runtimeContext: nativeRuntimeContextFixture(),
|
||||
});
|
||||
|
||||
expect(input.task.prompt.includes("Execution contract:")).toBe(!conversationMode);
|
||||
expect(input.task.prompt.includes("Use child issues")).toBe(!conversationMode);
|
||||
expect(input.task.prompt).toContain("## Paperclip Resume Delta");
|
||||
expect(input.task.prompt).not.toContain("Execution contract:");
|
||||
expect(input.task.prompt).not.toContain("Use child issues");
|
||||
// Full bootstrap stays available if provider recovery fails after admission.
|
||||
expect(input.task.prompt).toContain("## Paperclip Wake Payload");
|
||||
expect(input.task.prompt).toContain("reason: issue_children_completed");
|
||||
expect(input.task.prompt).toContain("DOT-147 Build utility (done)");
|
||||
expect(input.task.prompt).toContain(
|
||||
|
||||
@@ -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 }
|
||||
|
||||
Reference in new issue
Block a user