Integrate pinned Cursor ACP runtime and explicit public setup

Consolidate Cursor v10 onto current controller behavior, retain admission gates, and prepare native interaction and cleanup qualification. Add the public provisioner and ordinary provider-pack assets.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-03 13:33:15 -05:00
1 parent 2a8a99e4a5
commit e2b89b6302
199 files changed
+20293 -851

No files matched your search

@@ -0,0 +1,163 @@
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { and, eq, inArray, sql } from "drizzle-orm";
import { agents, companies, createDb, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { rethrowNativeCancellationLockConflict, nativeRetryCancellationCommitCondition, cancellationIntentId, claimCancellationRequest, startupCancellationFence } from "../services/native-runtime/native-cancellation-request.js";
describe("atomic caller cancellation request ownership", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let cancelNativeSession: typeof import("../services/native-runtime/native-session-executor.js").cancelNativeSession;
beforeAll(async () => {
({ cancelNativeSession } = await import("../services/native-runtime/native-session-executor.js"));
database = await startEmbeddedPostgresTestDatabase("caller-stop-");
db = createDb(database.connectionString);
}, 90_000);
afterAll(async () => { await database?.cleanup(); });
async function fixture() {
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Stop claims", issuePrefix: randomUUID().slice(0, 8) });
await db.insert(agents).values({ id: agentId, companyId, name: "Stop target" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", status: "running", runtimeMode: "native" });
return { companyId, runId, agentId };
}
const defaultFence = (runId: string) => db.update(heartbeatRuns).set({ resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || jsonb_build_object('startupCancellation', ${startupCancellationFence(new Date().toISOString())})` }).where(eq(heartbeatRuns.id, runId));
it("allows exactly one of two concurrent identities and idempotent same-ID retries", async () => {
const { companyId, runId } = await fixture(), a = randomUUID(), b = randomUUID();
const results = await Promise.allSettled([claimCancellationRequest(db, runId, companyId, a, "board-user"), claimCancellationRequest(db, runId, companyId, b, "board-user")]);
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
const winner = results[0].status === "fulfilled" ? a : b;
await expect(claimCancellationRequest(db, runId, companyId, winner, "other-board-user")).rejects.toMatchObject({ status: 409 });
const copies = await Promise.all([claimCancellationRequest(db, runId, companyId, winner, "board-user"), claimCancellationRequest(db, runId, companyId, winner, "board-user")]);
expect(copies[0].resultJson).toEqual(copies[1].resultJson);
await expect(claimCancellationRequest(db, runId, randomUUID(), winner, "board-user")).rejects.toMatchObject({ status: 409 });
});
it("does not overwrite a caller claim when default Stop races after it", async () => {
const { companyId, runId } = await fixture(), id = randomUUID();
const claimed = await claimCancellationRequest(db, runId, companyId, id, "board-user");
await Promise.all([defaultFence(runId), claimCancellationRequest(db, runId, companyId, id, "board-user")]);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(run.resultJson).toEqual(claimed.resultJson);
});
it("rejects a default Stop that won first, without replacing its marker", async () => {
const { companyId, runId } = await fixture(); await defaultFence(runId);
const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
await expect(claimCancellationRequest(db, runId, companyId, randomUUID(), "board-user")).rejects.toMatchObject({ status: 409 });
const [after] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(after.resultJson).toEqual(before.resultJson);
});
it("accepts only the original acknowledged identity on a terminal run", async () => {
const { companyId, runId } = await fixture(), id = randomUUID();
const run = await claimCancellationRequest(db, runId, companyId, id, "board-user");
await db.update(heartbeatRuns).set({ status: "cancelled", resultJson: { ...run.resultJson, nativeCancellation: { schema: "paperclip.native-cancellation.v1", intentId: cancellationIntentId(id), runId, companyId, scope: "run", dispatched: true, dispatchState: "acknowledged", intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID() } } }).where(eq(heartbeatRuns.id, runId));
await expect(claimCancellationRequest(db, runId, companyId, id, "board-user")).resolves.toMatchObject({ status: "cancelled" });
await expect(claimCancellationRequest(db, runId, companyId, randomUUID(), "board-user")).rejects.toMatchObject({ status: 409 });
await db.update(heartbeatRuns).set({ resultJson: { ...run.resultJson, nativeCancellation: { intentId: cancellationIntentId(id) } } }).where(eq(heartbeatRuns.id, runId));
await expect(claimCancellationRequest(db, runId, companyId, id, "board-user")).rejects.toMatchObject({ status: 409 });
});
async function retryFixture(phase = "retryable_failure") {
const f = await fixture(), issueId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Native retry", status: "in_progress", assigneeAgentId: f.agentId });
await db.update(heartbeatRuns).set({ nativeIssueId: issueId, status: "failed" }).where(eq(heartbeatRuns.id, f.runId));
await db.insert(nativeRunFinalizations).values({ runId: f.runId, companyId: f.companyId, issueId, phase, nextAttemptAt: new Date(Date.now() + 30_000) });
return { ...f, issueId };
}
it("admits a failed retry and recovers the same caller after audited native cancellation disables it", async () => {
const f = await retryFixture(), id = randomUUID();
await claimCancellationRequest(db, f.runId, f.companyId, id, "board-user");
// No provider is attached: exercise the actual durable cancellation path.
const outcome = await cancelNativeSession(f.runId, "Stop", { db, scope: "run", cancellationRequestId: id });
expect(outcome.auditId).toBeTruthy();
const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId));
expect(coordinator).toMatchObject({ phase: "terminal_failure", failureCode: "native_retry_cancelled", nextAttemptAt: null });
const retried = await claimCancellationRequest(db, f.runId, f.companyId, id, "board-user");
expect(retried.resultJson?.nativeCancellation).toMatchObject({ intentId: cancellationIntentId(id), dispatchState: "acknowledged" });
await expect(claimCancellationRequest(db, f.runId, f.companyId, randomUUID(), "board-user")).rejects.toMatchObject({ status: 409 });
await expect(claimCancellationRequest(db, f.runId, f.companyId, id, "other-actor")).rejects.toMatchObject({ status: 409 });
await expect(cancelNativeSession(f.runId, "Stop", { db, scope: "run", cancellationRequestId: id })).resolves.toMatchObject({ auditId: outcome.auditId });
});
it.each(["observed", "terminal_failure", "committed"])("does not claim a failed run whose coordinator advanced to %s", async phase => {
const f = await retryFixture(phase);
await expect(claimCancellationRequest(db, f.runId, f.companyId, randomUUID(), "board-user")).rejects.toMatchObject({ status: 409 });
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run.resultJson?.startupCancellation).toBeUndefined();
});
it("rejects a coordinator-only concurrent claim, then observes its committed phase without installing a Stop fence", async () => {
const f = await retryFixture(), id = randomUUID();
let release!: () => void, locked!: () => void;
const acquired = new Promise<void>(resolve => { locked = resolve; });
const hold = new Promise<void>(resolve => { release = resolve; });
const advance = db.transaction(async tx => {
await tx.update(nativeRunFinalizations).set({ phase: "observed", nextAttemptAt: null }).where(eq(nativeRunFinalizations.runId, f.runId));
locked(); await hold;
});
try {
await acquired;
await expect(claimCancellationRequest(db, f.runId, f.companyId, id, "board-user")).rejects.toMatchObject({ status: 409, message: "Native retry cancellation is busy; retry the same request" });
} finally { release(); await advance; }
await expect(claimCancellationRequest(db, f.runId, f.companyId, id, "board-user")).rejects.toMatchObject({ status: 409 });
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run.resultJson?.startupCancellation).toBeUndefined();
});
it.each(["failed", "running"])("preserves a %s terminal/recovery outcome that wins after reservation", async status => {
const f = await retryFixture(), id = randomUUID();
await claimCancellationRequest(db, f.runId, f.companyId, id, "board-user");
await db.update(nativeRunFinalizations).set({ phase: status === "failed" ? "terminal_failure" : "observed",
failureCode: "board_recovery", nextAttemptAt: null }).where(eq(nativeRunFinalizations.runId, f.runId));
await db.update(heartbeatRuns).set({ status, errorCode: "board_recovery" }).where(eq(heartbeatRuns.id, f.runId));
await expect(cancelNativeSession(f.runId, "Stop", { db, scope: "run", cancellationRequestId: id })).rejects.toMatchObject({ status: 409 });
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(run).toMatchObject({ status, errorCode: "board_recovery" });
expect(run.resultJson?.nativeCancellation).toBeUndefined();
});
it("does not overwrite a coordinator-only terminal change after acknowledgement", async () => {
const f = await retryFixture(), id = randomUUID();
await claimCancellationRequest(db, f.runId, f.companyId, id, "board-user");
await cancelNativeSession(f.runId, "Stop", { db, scope: "run", cancellationRequestId: id });
const [acknowledged] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
const commit = () => db.update(heartbeatRuns).set({ status: "cancelled" }).where(and(eq(heartbeatRuns.id, f.runId),
inArray(heartbeatRuns.status, ["queued", "running", "scheduled_retry", "failed"]), nativeRetryCancellationCommitCondition(acknowledged.resultJson))).returning();
let release!: () => void, locked!: () => void;
const acquired = new Promise<void>(resolve => { locked = resolve; });
const hold = new Promise<void>(resolve => { release = resolve; });
const advance = db.transaction(async tx => {
await tx.update(nativeRunFinalizations).set({ failureCode: "board_recovery" }).where(eq(nativeRunFinalizations.runId, f.runId));
locked(); await hold;
});
try { await acquired; await expect(commit().catch(rethrowNativeCancellationLockConflict)).rejects.toMatchObject({ status: 409, message: "Native retry cancellation is busy; retry the same request" }); }
finally { release(); await advance; }
expect(await commit()).toEqual([]);
const [preserved] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(preserved).toMatchObject({ status: "failed", resultJson: acknowledged.resultJson });
});
it.each(["running", "queued", "scheduled_retry"])("preserves a status-only advance to %s after acknowledgement", async status => {
const f = await retryFixture(), id = randomUUID();
await claimCancellationRequest(db, f.runId, f.companyId, id, "board-user");
await cancelNativeSession(f.runId, "Stop", { db, scope: "run", cancellationRequestId: id });
const [acknowledged] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, f.runId));
// Match heartbeat's broader candidate list: the production retry predicate,
// not a test-only failed-status filter, must preserve the newer state.
const committed = await db.update(heartbeatRuns).set({ status: "cancelled" }).where(and(eq(heartbeatRuns.id, f.runId),
inArray(heartbeatRuns.status, ["queued", "running", "scheduled_retry", "failed"]),
nativeRetryCancellationCommitCondition(acknowledged.resultJson))).returning();
expect(committed).toEqual([]);
const [preserved] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
expect(preserved).toMatchObject({ status, resultJson: acknowledged.resultJson });
});
it("commits an unchanged acknowledged retry but preserves a newer run result", async () => {
const f = await retryFixture(), id = randomUUID();
await claimCancellationRequest(db, f.runId, f.companyId, id, "board-user");
await cancelNativeSession(f.runId, "Stop", { db, scope: "run", cancellationRequestId: id });
const [acknowledged] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
const commit = () => db.update(heartbeatRuns).set({ status: "cancelled" }).where(and(eq(heartbeatRuns.id, f.runId),
inArray(heartbeatRuns.status, ["queued", "running", "scheduled_retry", "failed"]), nativeRetryCancellationCommitCondition(acknowledged.resultJson))).returning();
await db.update(heartbeatRuns).set({ resultJson: { ...acknowledged.resultJson, boardRecovery: "new-outcome" } }).where(eq(heartbeatRuns.id, f.runId));
expect(await commit()).toEqual([]);
await db.update(heartbeatRuns).set({ resultJson: acknowledged.resultJson }).where(eq(heartbeatRuns.id, f.runId));
expect(await commit()).toMatchObject([{ status: "cancelled" }]);
});
});
+3
View File
@@ -1,5 +1,6 @@
import { connectionIntentService } from "../services/connection-intents.js";
import { completeConnectionIntentSchema } from "@paperclipai/shared";
import { cancellationRequestId } from "../services/native-runtime/native-cancellation-request.js";
import { agentFileStore, agentFileTokenFromHash } from "../services/agent-file-store.js";
import { pipeline } from "node:stream/promises";
import { resolveAgentAppearance, agentAvatarUrl } from "@paperclipai/shared";
@@ -7022,10 +7023,12 @@ export function agentRoutes(
const runId = readHeartbeatRunId(req);
const existing = await getAccessibleResource(req, res, heartbeat.getRun(runId), "Heartbeat run not found");
if (!existing) return;
const requestId = cancellationRequestId(req.body?.cancellationRequestId);
// Stamp the cancellation as operator-initiated (this route is board-only).
// Recovery reads this to stand down instead of classifying the cancelled
// run as agent stranding and re-waking the agent the operator just stopped.
const run = await heartbeat.cancelRun(runId, "Cancelled by a board operator", {
...(requestId ? { cancellationRequestId: requestId, cancellationRequestedByUserId: req.actor.userId ?? null } : {}),
resultJson: {
cancelledByActorType: "user",
cancelledByUserId: req.actor.userId ?? null,
+46 -17
View File
@@ -1,5 +1,6 @@
import { externalObjectService } from "./external-objects.js";
import { isAiAuthenticationBlocked } from "./ai-auth-failure.js";
import { nativeRetryCancellationCommitCondition, rethrowNativeCancellationLockConflict, claimCancellationRequest, startupCancellationFence } from "./native-runtime/native-cancellation-request.js";
import { CHAT_COMPLETION_WAKE_REASON, prepareChatCompletionTurn, chatCompletionInstruction, isCompletedOnboardingHandoffWake } from "./chat-completion-delivery.js";
import { AgentDirectoryReuseInvalidatedError, isAgentDirectoryCopy } from "./agent-directory-working-copies.js";
@@ -9442,10 +9443,11 @@ export async function cancelHeartbeatNativeRun(input: {
runId: string;
reason: string;
runtimeMode: string | null;
cancellationRequestId?: string;
cancel?: (
runId: string,
reason: string,
options: { db: Db; scope: "run" },
options: { db: Db; scope: "run"; cancellationRequestId?: string },
) => Promise<{ decision: unknown | null; auditId: string | null }>;
}) {
if (input.runtimeMode !== "native") {
@@ -9455,10 +9457,12 @@ export async function cancelHeartbeatNativeRun(input: {
? await input.cancel(input.runId, input.reason, {
db: input.db,
scope: "run",
...(input.cancellationRequestId ? { cancellationRequestId: input.cancellationRequestId } : {}),
})
: await cancelNativeSession(input.runId, input.reason, {
db: input.db,
scope: "run",
...(input.cancellationRequestId ? { cancellationRequestId: input.cancellationRequestId } : {}),
});
if (!cancellation.decision || !cancellation.auditId) {
throw new Error("native_cancellation_outcome_not_audited");
@@ -12988,6 +12992,7 @@ export function heartbeatService(
fromStatuses: string[],
patch?: Partial<typeof heartbeatRuns.$inferInsert>,
failureReport?: RunFailureReportOptions,
cancellationCondition?: ReturnType<typeof nativeRetryCancellationCommitCondition>,
) {
// fromStatuses can name a terminal status as its own source (for example,
// an idempotent "still failed" patch), so the write below is not always a
@@ -13046,13 +13051,18 @@ export function heartbeatService(
and(
eq(heartbeatRuns.id, runId),
inArray(heartbeatRuns.status, fromStatuses),
...(cancellationCondition ? [cancellationCondition] : []),
...(isHeartbeatRunTerminalStatus(status)
? [nativeRunnerOwnershipNotHeldCondition()]
: []),
),
)
.returning()
.then((rows) => rows[0] ?? null);
.then((rows) => rows[0] ?? null)
.catch((error: unknown) => {
if (cancellationCondition) rethrowNativeCancellationLockConflict(error);
throw error;
});
if (updated) {
publishLiveEvent({
@@ -23552,7 +23562,8 @@ export function heartbeatService(
const savedFileInput = parseObject(parseObject(run.runnerProfileJson).nativeExecutionInput);
const priorFileInput = Object.keys(savedFileInput).length ? savedFileInput : parseObject(parseObject(priorFileRun?.profile).nativeExecutionInput);
const priorWorkingCopy = parseObject(parseObject(parseObject(priorFileInput.runtimeContext).instructions).workingCopy);
const warmFiles = nativeRuntimeResolution.kind === "native" && nativeRuntimeResolution.profile.backend === "codex_app_server" &&
const warmFiles = nativeRuntimeResolution.kind === "native" && (nativeRuntimeResolution.profile.backend === "codex_app_server" ||
(nativeRuntimeResolution.profile.backend === "acpx_runtime" && parseObject(agent.adapterConfig).acpxAgent === "cursor")) &&
(executionTarget?.kind === "remote" && executionTarget.transport === "sandbox"
? executionTarget.runnerLifecyclePolicy?.mode === "warm"
: parseObject(agent.adapterConfig).lifecycleMode === "warm");
@@ -25097,6 +25108,11 @@ export function heartbeatService(
await completeWorkspace();
}
} catch (adapterErr) {
if (adapterErr instanceof NativeCancellationPendingRecoveryError) {
// Durable cancellation is settled by the outer recovery handler;
// it does not imply a failed workspace or a persisted run result.
throw adapterErr;
}
if (adapterErr instanceof NativeWorkspaceFinalizationBusyError
|| adapterErr instanceof NativeWorkspaceFinalizationOwnershipLostError) {
nativeWorkspaceFinalizeScheduled = true;
@@ -29453,6 +29469,9 @@ export function heartbeatService(
}
type CancelRunOptions = {
/** Optional board request identity, atomically reserved for native Stop. */
cancellationRequestId?: string;
cancellationRequestedByUserId?: string | null;
errorCode?: string;
resultJson?: Record<string, unknown>;
eventMessage?: string;
@@ -29481,20 +29500,27 @@ export function heartbeatService(
) {
let run = await getRun(runId);
if (!run) throw notFound("Heartbeat run not found");
if (options.cancellationRequestId) {
run = await claimCancellationRequest(db, runId, run.companyId, options.cancellationRequestId, options.cancellationRequestedByUserId ?? null);
}
// The caller claim checked retry eligibility under both durable row locks.
// This is only a cancellation candidate: dispatch rechecks the coordinator
// under lock, and the final CAS requires its own unchanged acknowledged
// retry fence. Re-reading only retryable_failure here would strand replay.
const pendingNativeRetry =
run.runtimeMode === "native" && run.status === "failed"
? await db
.select({ runId: nativeRunFinalizations.runId })
.from(nativeRunFinalizations)
.where(
and(
eq(nativeRunFinalizations.runId, run.id),
eq(nativeRunFinalizations.companyId, run.companyId),
eq(nativeRunFinalizations.phase, "retryable_failure"),
),
)
.then((rows) => rows.length > 0)
: false;
run.runtimeMode === "native" && run.status === "failed" && (
Boolean(options.cancellationRequestId) || await db
.select({ runId: nativeRunFinalizations.runId })
.from(nativeRunFinalizations)
.where(
and(
eq(nativeRunFinalizations.runId, run.id),
eq(nativeRunFinalizations.companyId, run.companyId),
eq(nativeRunFinalizations.phase, "retryable_failure"),
),
)
.then((rows) => rows.length > 0)
);
if (
!pendingNativeRetry &&
!CANCELLABLE_HEARTBEAT_RUN_STATUSES.includes(
@@ -29527,7 +29553,7 @@ export function heartbeatService(
// Established legacy processes must still be stopped if the database is
// unavailable. Only native or not-yet-dispatched preparation needs this
// additional durable fence before its existing cancellation path.
if (run.runtimeMode === "native" || (!run.runtimeModeResolvedAt && !running && !control)) {
if (!options.cancellationRequestId && (run.runtimeMode === "native" || (!run.runtimeModeResolvedAt && !running && !control))) {
const [fenced] = await db.update(heartbeatRuns).set({
// Record handoff intent before native cancellation can finalize and release
// the run. Only its audited stop acknowledgement suppresses recovery.
@@ -29617,6 +29643,7 @@ export function heartbeatService(
runId: run.id,
reason,
runtimeMode: run.runtimeMode,
...(options.cancellationRequestId ? { cancellationRequestId: options.cancellationRequestId } : {}),
});
if (running) {
await terminateHeartbeatRunProcess({
@@ -29719,6 +29746,8 @@ export function heartbeatService(
}
: {}),
},
undefined,
pendingNativeRetry ? nativeRetryCancellationCommitCondition(persistedCancellationResult) : undefined,
);
} catch (error) {
if (processCancellationSettlement) {
@@ -10,6 +10,18 @@ import { nativeSha256 } from "./canonical.js";
export const NATIVE_COMPLETION_CONTRACT_SCHEMA = "paperclip.completion-contract.v1";
export const NATIVE_COMPLETION_POLICY_VERSION = "phase6-v4";
/** Canonical persisted receipt includes the policy that governs the contract. */
export function nativeCompletionContractSha256(row: Pick<typeof completionContracts.$inferSelect,
"schemaVersion" | "policyVersion" | "risk" | "completionAuthority" | "contractJson">): string {
return nativeSha256({
schemaVersion: row.schemaVersion,
policyVersion: row.policyVersion,
risk: row.risk,
completionAuthority: row.completionAuthority,
contract: row.contractJson,
});
}
type CompletionComment = {
id?: string;
body: string;
@@ -162,11 +174,11 @@ export async function ensureNativeCompletionContract(input: {
immediateRequests: input.immediateRequests,
humanResponseId: input.humanResponseId,
});
const latestCandidateSha256 = nativeSha256({
const latestCandidateSha256 = nativeCompletionContractSha256({
schemaVersion: NATIVE_COMPLETION_CONTRACT_SCHEMA,
policyVersion: NATIVE_COMPLETION_POLICY_VERSION,
...policy,
contract: latestCandidate,
contractJson: latestCandidate as unknown as Record<string, unknown>,
});
if (latest?.canonicalSha256 === latestCandidateSha256) {
return { row: latest, contract: latestCandidate, sources: buildNativeCompletionContractSources(input) };
@@ -179,11 +191,11 @@ export async function ensureNativeCompletionContract(input: {
immediateRequests: input.immediateRequests,
humanResponseId: input.humanResponseId,
});
const canonicalSha256 = nativeSha256({
const canonicalSha256 = nativeCompletionContractSha256({
schemaVersion: NATIVE_COMPLETION_CONTRACT_SCHEMA,
policyVersion: NATIVE_COMPLETION_POLICY_VERSION,
...policy,
contract,
contractJson: contract as unknown as Record<string, unknown>,
});
const [row] = await tx.insert(completionContracts).values({
companyId: input.companyId,
@@ -12,6 +12,7 @@ export const INHERITABLE_NATIVE_RUNNER_CONFIG_KEYS = [
"codexPermissionMode",
"opencodePermissionMode",
"acpxPermissionMode",
"acpxSessionMode",
"lifecycleMode",
"modelReasoningEffort",
"maxIterations",
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from "vitest";
import { assertCancellationRequest, cancellationIntentId, cancellationRequestId, claimCancellationRequest } from "./native-cancellation-request.js";
import { heartbeatRuns, type Db } from "@paperclipai/db";
const id = "11111111-1111-4111-8111-111111111111";
describe("caller-bound native cancellation", () => {
it.each([null, "", " x", {}, [], 1, `${id} `, "not-a-uuid"])("rejects malformed request %j", value => {
expect(() => cancellationRequestId(value)).toThrow("Invalid cancellationRequestId");
});
it("preserves the absent option and normalizes a valid UUID", () => {
expect(cancellationRequestId(undefined)).toBeUndefined();
expect(cancellationRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")).toBe("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa");
});
it.each([{ startupCancellation: {} }, { startupCancellation: { requestedAt: "earlier" } },
{ startupCancellation: { cancellationRequestId: "other" } }, { nativeCancellation: { intentId: "other" } }])("rejects prior or racing intent %j", result => {
expect(() => assertCancellationRequest(result, id, true)).toThrow("earlier Stop");
});
it("requires a reservation at the native locked dispatch gate", () => {
expect(() => assertCancellationRequest({}, id)).toThrow("earlier Stop");
expect(() => assertCancellationRequest({}, id, true)).not.toThrow();
const startupCancellation = { cancellationRequestId: id };
expect(() => assertCancellationRequest({ startupCancellation }, id)).not.toThrow();
expect(() => assertCancellationRequest({ startupCancellation, nativeCancellation: { intentId: cancellationIntentId(id) } }, id)).not.toThrow();
});
});
describe("failed native retry caller admission", () => {
const companyId = "company", runId = "run", issueId = "issue";
const claimed = { cancellationRequestId: id, requestedBy: { type: "board", userId: "board-user" } };
const native = { schema: "paperclip.native-cancellation.v1", intentId: cancellationIntentId(id),
companyId, runId, issueId, scope: "run", dispatchState: "pending", dispatched: false, intentAuditId: "intent-audit" };
function fixture(phase: string | null, resultJson: Record<string, unknown> = {}, status = "failed", failureCode: string | null = null) {
const run = { id: runId, companyId, nativeIssueId: issueId, runtimeMode: "native", status, resultJson };
const locks: unknown[][] = [];
const update = vi.fn((values: { resultJson: Record<string, unknown> }) => { run.resultJson = values.resultJson;
return { where: () => ({ returning: async () => [run] }) }; });
const tx = { select: () => ({ from: (table: unknown) => ({ where: () => ({
for: (...args: unknown[]) => { locks.push(args); return { limit: async () => table === heartbeatRuns ? [run]
: phase ? [{ phase, failureCode }] : [] }; },
}) }) }), update: () => ({ set: update }) };
const db = { transaction: async (fn: (value: typeof tx) => Promise<unknown>) => fn(tx) } as unknown as Db;
return { db, run, locks, update };
}
it("admits a pending retry under the coordinator lock and preserves the exact caller on retry", async () => {
const f = fixture("retryable_failure");
await claimCancellationRequest(f.db, runId, companyId, id, "board-user");
const first = structuredClone(f.run.resultJson);
await claimCancellationRequest(f.db, runId, companyId, id, "board-user");
expect(f.run.resultJson).toEqual(first);
expect(f.update).toHaveBeenCalledTimes(1);
expect(f.locks).toContainEqual(["update", { noWait: true }]);
});
it.each([null, "observed", "executing", "terminal_failure", "committed"])("rejects missing or advanced retry phase %s without writing", async phase => {
const f = fixture(phase);
await expect(claimCancellationRequest(f.db, runId, companyId, id, "board-user")).rejects.toMatchObject({ status: 409 });
expect(f.update).not.toHaveBeenCalled();
});
it.each(["pending", "acknowledged"])("recovers its own %s intent after native retry cancellation", async dispatchState => {
const f = fixture("terminal_failure", { startupCancellation: claimed,
nativeCancellation: { ...native, dispatchState, ...(dispatchState === "acknowledged" ? { acknowledgementAuditId: "ack-audit" } : {}) } }, "failed", "native_retry_cancelled");
await expect(claimCancellationRequest(f.db, runId, companyId, id, "board-user")).resolves.toMatchObject({ status: "failed" });
expect(f.update).not.toHaveBeenCalled();
await expect(claimCancellationRequest(f.db, runId, companyId, id, "another-actor")).rejects.toMatchObject({ status: 409 });
});
it.each([{}, { ...native, intentId: "foreign" }, { ...native, issueId: "foreign" },
{ ...native, intentAuditId: null }, { ...native, dispatchState: "acknowledged" }])("rejects unproven or foreign cancellation recovery %j", nativeCancellation => {
const f = fixture("terminal_failure", { startupCancellation: claimed, nativeCancellation }, "failed", "native_retry_cancelled");
return expect(claimCancellationRequest(f.db, runId, companyId, id, "board-user")).rejects.toMatchObject({ status: 409 });
});
it.each(["succeeded", "cancelled", "timed_out"])("does not admit terminal %s merely because a retry row exists", status => {
const f = fixture("retryable_failure", {}, status);
return expect(claimCancellationRequest(f.db, runId, companyId, id, "board-user")).rejects.toMatchObject({ status: 409 });
});
it.each([{ code: "55P03" }, { cause: { code: "55P03" } }])("fails closed on coordinator contention without database details", async error => {
const db = { transaction: async () => { throw error; } } as unknown as Db;
await expect(claimCancellationRequest(db, runId, companyId, id, "board-user")).rejects.toMatchObject({ status: 409, message: "Native retry cancellation is busy; retry the same request" });
});
});
@@ -0,0 +1,133 @@
import { and, eq, sql } from "drizzle-orm";
import { heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
import { badRequest, conflict } from "../../errors.js";
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
export function cancellationRequestId(value: unknown): string | undefined {
if (value === undefined) return undefined;
if (typeof value !== "string" || !UUID.test(value)) throw badRequest("Invalid cancellationRequestId");
return value.toLowerCase();
}
export const cancellationIntentId = (requestId: string) => `native-cancellation:${requestId}`;
/** Run only while holding this company's run row lock. An earlier uncorrelated
* startup fence is also a conflicting Stop, even before native intent exists. */
export function assertCancellationRequest(result: unknown, requestId: string, allowUnclaimed = false) {
const value = record(result), startup = record(value.startupCancellation), native = record(value.nativeCancellation);
if ((Object.hasOwn(value, "startupCancellation") && startup.cancellationRequestId !== requestId)
|| (Object.hasOwn(value, "nativeCancellation") && native.intentId !== cancellationIntentId(requestId))
|| (!allowUnclaimed && startup.cancellationRequestId !== requestId)) {
throw conflict("Cancellation request conflicts with an earlier Stop");
}
}
/** Evaluate only while both the run and coordinator are locked. A UUID alone
* is not retry authority; a resumed Stop needs its exact durable native intent. */
export function nativeRetryCancellationEligible(input: {
runId: string; companyId: string; issueId: string; resultJson: unknown; requestId?: string; scope?: string;
}, coordinator: { phase?: string; failureCode?: string | null } | null | undefined) {
if (coordinator?.phase === "retryable_failure") return true;
if (coordinator?.phase !== "terminal_failure" || coordinator.failureCode !== "native_retry_cancelled") return false;
const result = record(input.resultJson), native = record(result.nativeCancellation);
return (!input.requestId || (record(result.startupCancellation).cancellationRequestId === input.requestId
&& native.intentId === cancellationIntentId(input.requestId)))
&& native.schema === "paperclip.native-cancellation.v1" && typeof native.intentId === "string" && !!native.intentId
&& native.runId === input.runId && native.companyId === input.companyId && native.issueId === input.issueId
&& native.scope === (input.scope ?? "run") && ["pending", "acknowledged"].includes(String(native.dispatchState))
&& typeof native.dispatched === "boolean" && typeof native.intentAuditId === "string" && !!native.intentAuditId
&& (native.dispatchState === "pending" || (typeof native.acknowledgementAuditId === "string"
&& !!native.acknowledgementAuditId && native.acknowledgementAuditId !== native.intentAuditId));
}
/** Final failed -> cancelled CAS: a later board/recovery outcome must win.
* The row-locking subquery prevents a coordinator-only writer from changing
* the retry disposition between this check and the status update. */
export function nativeRetryCancellationCommitCondition(expectedResult: unknown) {
const native = record(record(expectedResult).nativeCancellation);
if (native.dispatchState !== "acknowledged" || typeof native.runId !== "string"
|| typeof native.companyId !== "string" || typeof native.issueId !== "string"
|| !nativeRetryCancellationEligible({ runId: native.runId, companyId: native.companyId,
issueId: native.issueId, resultJson: expectedResult }, { phase: "terminal_failure", failureCode: "native_retry_cancelled" })) {
return sql`false`;
}
return sql`${heartbeatRuns.status} = 'failed' and ${heartbeatRuns.runtimeMode} = 'native'
and ${heartbeatRuns.id} = ${native.runId} and ${heartbeatRuns.companyId} = ${native.companyId}
and ${heartbeatRuns.nativeIssueId} = ${native.issueId}
and ${heartbeatRuns.resultJson} = ${JSON.stringify(expectedResult)}::jsonb
and exists (select 1 from ${nativeRunFinalizations}
where ${nativeRunFinalizations.runId} = ${heartbeatRuns.id}
and ${nativeRunFinalizations.companyId} = ${heartbeatRuns.companyId}
and ${nativeRunFinalizations.issueId} = ${heartbeatRuns.nativeIssueId}
and ${nativeRunFinalizations.phase} = 'terminal_failure'
and ${nativeRunFinalizations.failureCode} = 'native_retry_cancelled'
for update nowait)`;
}
export function rethrowNativeCancellationLockConflict(error: unknown): never {
const value = record(error);
if (value.code === "55P03" || record(value.cause).code === "55P03") {
throw conflict("Native retry cancellation is busy; retry the same request");
}
throw error;
}
/** Reserve the caller's identity before handoff or dispatch. No schema change:
* the existing startup fence and native intent carry the correlation. */
export async function claimCancellationRequest(db: Db, runId: string, companyId: string, requestId: string, userId: string | null) {
if (cancellationRequestId(requestId) !== requestId) throw badRequest("Invalid cancellationRequestId");
if (userId !== null && (typeof userId !== "string" || !userId)) throw badRequest("Invalid cancellation request actor");
return db.transaction(async tx => {
const run = await tx.select().from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)))
.for("update").limit(1).then(rows => rows[0]);
if (!run || run.runtimeMode !== "native") throw conflict("Correlated Stop requires a native run");
assertCancellationRequest(run.resultJson, requestId, true);
const result = record(run.resultJson);
let pendingRetry = false;
if (run.status === "failed" && run.nativeIssueId) {
// Eligibility and the caller fence must share a transaction. Coordinator
// writers need not lock the run. NOWAIT avoids a lock-order deadlock with
// execution's coordinator -> run claim; a busy claim can be retried.
const coordinator = await tx.select().from(nativeRunFinalizations)
.where(and(eq(nativeRunFinalizations.runId, runId), eq(nativeRunFinalizations.companyId, companyId),
eq(nativeRunFinalizations.issueId, run.nativeIssueId)))
.for("update", { noWait: true }).limit(1).then(rows => rows[0]);
pendingRetry = nativeRetryCancellationEligible({ runId, companyId, issueId: run.nativeIssueId,
resultJson: result, requestId }, coordinator);
}
if (record(result.startupCancellation).cancellationRequestId === requestId) {
const actor = record(record(result.startupCancellation).requestedBy);
if (actor.type !== "board" || actor.userId !== userId) throw conflict("Cancellation request belongs to another actor");
if (!pendingRetry && !["queued", "running", "scheduled_retry"].includes(run.status)) {
const native = record(result.nativeCancellation);
if (run.status !== "cancelled" || native.schema !== "paperclip.native-cancellation.v1"
|| native.intentId !== cancellationIntentId(requestId) || native.runId !== runId || native.companyId !== companyId
|| native.scope !== "run" || native.dispatchState !== "acknowledged" || typeof native.dispatched !== "boolean"
|| typeof native.intentAuditId !== "string" || !native.intentAuditId
|| typeof native.acknowledgementAuditId !== "string" || !native.acknowledgementAuditId
|| native.intentAuditId === native.acknowledgementAuditId) throw conflict("Correlated Stop run is already terminal without acknowledgement");
}
return run;
}
if (!pendingRetry && !["queued", "running", "scheduled_retry"].includes(run.status)) throw conflict("Correlated Stop run is already terminal");
const [claimed] = await tx.update(heartbeatRuns).set({ resultJson: { ...result,
startupCancellation: { requestedAt: new Date().toISOString(), beforeNativeSelection: false, cancellationRequestId: requestId, requestedBy: { type: "board", userId }, ...(run.status === "failed" ? { retryCancellation: true } : {}) },
} }).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))).returning();
if (!claimed) throw conflict("Correlated Stop run changed");
return claimed;
}).catch(rethrowNativeCancellationLockConflict);
}
/** Used by the default Stop path too: never erase a correlated reservation. */
export function startupCancellationFence(requestedAt: string) {
return sql`CASE
WHEN ${heartbeatRuns.resultJson}->'startupCancellation'->>'cancellationRequestId' IS NOT NULL
THEN ${heartbeatRuns.resultJson}->'startupCancellation'
ELSE jsonb_build_object('requestedAt', ${requestedAt}::text,
'beforeNativeSelection', ${heartbeatRuns.runtimeMode} = 'legacy'
and ${heartbeatRuns.runtimeModeResolvedAt} is null
and ${heartbeatRuns.executionStage} = 'preparing'
and coalesce(${heartbeatRuns.runnerProfileJson}->'adapterDispatch'->>'adapterType' = 'paperclip_runner', false))
END`;
}
@@ -0,0 +1,41 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { heartbeatRuns, issues, issueThreadInteractions, issueApprovals, type Db } from "@paperclipai/db";
import type { PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js";
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
const state = vi.hoisted(() => ({ blockers: 0 }));
vi.mock("./native-deliverable-feedback.js", () => ({ validateNativeDeliverableEvidence: vi.fn(async () => undefined) }));
vi.mock("./automatic-completion-reviews.js", () => ({ findAutomaticCompletionReviews: vi.fn(async () => []) }));
vi.mock("../agent-invokability.js", () => ({ evaluateAgentInvokabilityFromDb: vi.fn() }));
vi.mock("../issues.js", () => ({ issueService: () => ({ getDependencyReadiness: async () => ({ unresolvedBlockerCount: state.blockers }) }) }));
vi.mock("./native-review-participant.js", () => ({ readNativeReviewAssignmentContext: () => null, getNativeReviewAssignment: vi.fn() }));
vi.mock("../../vendor/paperclip-runner/index.js", () => ({ normalizePrpResultSignals: () => ({ verification: [], actionableAttentionRequests: [] }) }));
const result = { reportedWorkDisposition: "done", summary: "EXACT_PRIVATE_MARKER", completionClaim: { objectiveSatisfied: true, criteria: [], remainingWork: [] } } as unknown as PrpStructuredRunResult;
function database(options: { interaction?: boolean; approval?: boolean; review?: boolean } = {}): Db {
// Pure query double: no client, PostgreSQL process, or network is created.
return { select: () => ({ from: (table: unknown) => {
const rows = table === heartbeatRuns ? [{ id: "run", companyId: "company", nativeIssueId: "issue", contextSnapshot: {} }]
: table === issues ? [{ id: "issue", companyId: "company", status: "in_progress", ...(options.review ? { executionState: { status: "pending" } } : {}) }]
: table === issueThreadInteractions && options.interaction ? [{ id: "request", kind: "request_confirmation", title: "Decision" }]
: table === issueApprovals && options.approval ? [{ id: "approval" }] : [];
const query = { where: () => query, limit: () => query, innerJoin: () => query, then: (resolve: (value: unknown[]) => unknown) => Promise.resolve(rows).then(resolve) };
return query;
} }) } as unknown as Db;
}
beforeEach(() => { state.blockers = 0; });
describe("native completion feedback format precedence", () => {
it("honors requested final format only after normal completion acceptance without echoing the summary", async () => {
const feedback = await nativeCompletionFeedback(database(), "run", result);
expect(feedback).toContain("Follow the user's explicitly requested final-response format, including an exact response when requested.");
expect(feedback).toContain("Task status will be committed after this turn and workspace finalization finish.");
expect(feedback).toContain("Do not claim an approval is needed unless one was requested.");
expect(feedback).not.toContain(result.summary);
});
it.each(["interaction", "approval", "review", "dependency"] as const)("preserves %s governance feedback instead of granting format precedence", async mode => {
state.blockers = mode === "dependency" ? 1 : 0;
const feedback = await nativeCompletionFeedback(database({ interaction: mode === "interaction", approval: mode === "approval", review: mode === "review" }), "run", result);
expect(feedback).not.toContain("final-response format");
expect(feedback).toMatch(/still waiting|still pending|unresolved dependencies/);
});
});
@@ -210,5 +210,5 @@ export async function nativeCompletionFeedback(
throw new Error("The named reviewer is not available in this company. Choose an available reviewer or report the concrete blocker.");
}
}
return "Completion report accepted. Task status will be committed after this turn and workspace finalization finish. Describe the completed work and any explicitly requested reviewer action; do not claim an approval is needed unless one was requested.";
return "Completion report accepted. Task status will be committed after this turn and workspace finalization finish. Follow the user's explicitly requested final-response format, including an exact response when requested. Otherwise describe the completed work and any explicitly requested reviewer action. Do not claim an approval is needed unless one was requested.";
}
@@ -0,0 +1,159 @@
import { describe, expect, it, vi } from "vitest";
import * as runner from "../../vendor/paperclip-runner/index.js";
import { resolveQualifiedAcpxProfile, validatePrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js";
import { buildQuestionResponseDeliveryEnvelope } from "../question-response-delivery.js";
import { NATIVE_COMPLETION_CONTRACT_SCHEMA, NATIVE_COMPLETION_POLICY_VERSION } from "./completion-contracts.js";
import { nativeSha256 } from "./canonical.js";
import { nativeCursorPlanWaitFromFacts, type CursorPlanWaitFacts } from "./native-cursor-plan-wait.js";
function fixture(): CursorPlanWaitFacts {
const b = { companyId: "company", issueId: "issue", agentId: "agent", runId: "run" };
const contract = { revision: "revision", criteria: [{ id: "criterion" }] };
const contractMetadata = { schemaVersion: NATIVE_COMPLETION_CONTRACT_SCHEMA, policyVersion: NATIVE_COMPLETION_POLICY_VERSION, risk: "low", completionAuthority: "agent_claim_policy" };
const contractSha = nativeSha256({ ...contractMetadata, contract });
const planId = `plan-${"a".repeat(64)}`;
const input = { schema: "paperclip.question_set.v1", title: "Plan", description: "Exact revised plan text", questions: [{ id: planId, prompt: "Proceed?", required: true, answerMode: "single_select", options: [{ id: "accept", label: "Accept" }, { id: "reject", label: "Reject" }, { id: "cancel", label: "Cancel" }] }] };
const i = { id: "interaction", ...b, sourceRunId: b.runId, createdByAgentId: b.agentId, resolvedByUserId: "board", resolvedByAgentId: null, resolvedAt: new Date(0),
kind: "ask_user_questions", status: "answered", continuationPolicy: "none", idempotencyKey: "paperclip-runner-question:run:request",
payload: { runtimeRequestId: "request", questionSet: input }, result: { version: 1, answers: [{ questionId: planId, optionIds: ["accept"] }] } };
const envelope = buildQuestionResponseDeliveryEnvelope(i as never);
const d = { id: "delivery", ...b, interactionId: i.id, sourceRunId: b.runId, targetRunId: b.runId, targetTurnId: null, status: "delivered", deliveryMode: "steered", acknowledgedAt: new Date(1), payloadSha256: nativeSha256(envelope) };
const event = (sourceSeq: number, eventType: string, payload: Record<string, unknown>) => {
const e = { schema: "paperclip.prp.event.v1", runId: b.runId, normalizedSessionId: "session", turnId: "turn", sourceInstanceId: "instance", sourceEventId: `instance:${sourceSeq}`, sourceSeq, sourceKind: "runner", schemaVersion: 1, eventType, payload };
return { ...b, seq: sourceSeq, eventType, payload: { prpEvent: e }, sourceInstanceId: e.sourceInstanceId, sourceEventId: e.sourceEventId, sourceSeq, sourcePayloadSha256: nativeSha256(e), protocolSchemaVersion: 1 };
};
return {
binding: b,
run: { id: b.runId, companyId: b.companyId, agentId: b.agentId, nativeIssueId: b.issueId, runtimeMode: "native", runnerInstanceId: "instance", status: "running", completionContractId: "contract", completionContractSha256: contractSha, runnerProfileJson: { nativeExecutionInput: { binding: b, provider: { kind: "acpx", agent: "cursor", cursorMode: "plan", model: "gpt-5.6-luna[context=272k,reasoning=medium,fast=false]", profile: resolveQualifiedAcpxProfile("cursor", "gpt-5.6-luna[context=272k,reasoning=medium,fast=false]") }, session: { normalizedSessionId: "session" }, completionContract: { id: "contract", sha256: contractSha, contract } } } },
contract: { id: "contract", ...contractMetadata, canonicalSha256: contractSha, contractJson: contract },
events: [
event(275, "runtime_request.created", { request: { schema: "paperclip.runtime_request.v2", status: "pending", type: "input", requestKind: "runtime", requestId: "request", turnId: "turn", itemId: "native-plan-tool", origin: { provider: "cursor", method: "cursor/create_plan", adapter: "acpx-runtime-sidecar" }, input } }),
event(294, "tool.execution.started", { schema: "paperclip.tool.execution.v1", executionId: "native-plan-tool", transport: "builtin", operation: "execute", status: "running", name: "arbitrary display name" }),
event(300, "runtime_request.resolved", { requestId: "request", turnId: "turn", action: "submit", response: envelope.response }),
event(303, "tool.execution.completed", { schema: "paperclip.tool.execution.v1", executionId: "native-plan-tool", transport: "builtin", operation: "execute", status: "completed" }),
event(304, "turn.completed", { status: "completed", error: null }),
],
interactions: [{ interaction: i, delivery: d }],
} as unknown as CursorPlanWaitFacts;
}
function editEvent(f: CursorPlanWaitFacts, index: number, edit: (e: any) => void) {
const row = f.events.filter(row => !row.eventType.startsWith("tool.execution."))[index]!;
const e = (row.payload as any).prpEvent;
edit(e); row.sourcePayloadSha256 = nativeSha256(e);
}
describe("accepted Cursor plan passive-wait authority", () => {
it("records the accepted revision and explicitly unfinished Plan-mode continuation", () => {
const value = nativeCursorPlanWaitFromFacts(fixture());
expect(value?.source).toMatchObject({ requestId: "request", planRevision: `plan-${"a".repeat(64)}`, terminalEventId: "instance:304", toolExecutionId: "native-plan-tool" });
expect(value?.result).toMatchObject({ reportedWorkDisposition: "yielded", completionClaim: { objectiveSatisfied: false, remainingWork: [{ blocksCompletion: true }] }, continuation: { kind: "response_wake" } });
expect(value?.result.summary).toContain("next message");
const validated = validatePrpStructuredRunResult(value!.result);
expect(validated.ok).toBe(true);
if (validated.ok) expect(validated.result).toEqual(value!.result);
});
it.each(["unrelated same-title tool", "cross turn", "cross session", "duplicate start", "duplicate completion", "missing start", "missing completion", "failed completion", "changed request tool", "uncommitted tool row"])("rejects correlated lifecycle corruption: %s", kind => {
const f = fixture();
const start = f.events.find(row => row.eventType === "tool.execution.started")!;
const end = f.events.find(row => row.eventType === "tool.execution.completed")!;
const event = (start.payload as any).prpEvent;
if (kind === "unrelated same-title tool") event.payload.executionId = "unrelated-tool";
if (kind === "cross turn") event.turnId = "other";
if (kind === "cross session") event.normalizedSessionId = "other";
if (kind === "duplicate start") f.events.splice(2, 0, structuredClone(start));
if (kind === "duplicate completion") f.events.splice(4, 0, structuredClone(end));
if (kind === "missing start") f.events = f.events.filter(row => row !== start);
if (kind === "missing completion") f.events = f.events.filter(row => row !== end);
if (kind === "failed completion") { (end.payload as any).prpEvent.payload.status = "failed"; end.sourcePayloadSha256 = nativeSha256((end.payload as any).prpEvent); }
if (kind === "changed request tool") editEvent(f, 0, e => { e.payload.request.itemId = "unrelated-tool"; });
start.sourcePayloadSha256 = kind === "uncommitted tool row" ? null : nativeSha256(event);
expect(nativeCursorPlanWaitFromFacts(f)).toBeNull();
});
it("rejects an additional same-title tool while the real plan tool remains correlated", () => {
const f = fixture();
const extra = structuredClone(f.events.find(row => row.eventType === "tool.execution.started")!);
extra.seq = 295; extra.sourceSeq = 295; extra.sourceEventId = "instance:295";
const e = (extra.payload as any).prpEvent;
Object.assign(e, { sourceSeq: 295, sourceEventId: extra.sourceEventId });
Object.assign(e.payload, { executionId: "unrelated", name: "Create Plan" });
extra.sourcePayloadSha256 = nativeSha256(e); f.events.splice(2, 0, extra);
expect(nativeCursorPlanWaitFromFacts(f)).toBeNull();
});
it("binds actual callback-before-tool-start order without trusting display names", () => {
const f = fixture(); const original = nativeCursorPlanWaitFromFacts(f)!;
expect(original.source.toolLifecycleSha256).toMatch(/^[a-f0-9]{64}$/);
const start = f.events.find(row => row.eventType === "tool.execution.started")!;
(start.payload as any).prpEvent.payload.name = "changed display text";
start.sourcePayloadSha256 = nativeSha256((start.payload as any).prpEvent);
const changed = nativeCursorPlanWaitFromFacts(f)!;
expect(changed).not.toBeNull();
expect(changed.source.authoritySha256).not.toBe(original.source.authoritySha256);
expect(changed.source.toolLifecycleSha256).not.toBe(original.source.toolLifecycleSha256);
});
it("does not create a new wait from an earlier profile after the catalog advances", () => {
const facts = fixture();
expect(nativeCursorPlanWaitFromFacts(facts)).not.toBeNull();
const current = resolveQualifiedAcpxProfile("cursor", "gpt-5.6-luna[context=272k,reasoning=medium,fast=false]");
// Model a future catalog revision without tying this test to today's version.
const next = { ...current, agentProfileVersion: (current.agentProfileVersion + 1) as typeof current.agentProfileVersion, commandDigest: `sha256:${"b".repeat(64)}` } satisfies typeof current;
expect(next.agentProfileVersion).toBeGreaterThan(current.agentProfileVersion);
const resolver = vi.spyOn(runner, "resolveQualifiedAcpxProfile").mockReturnValue(next);
try { expect(nativeCursorPlanWaitFromFacts(facts)).toBeNull(); }
finally { resolver.mockRestore(); }
});
it("projects only declared scope keys from a wider typed caller binding", () => {
const f = fixture(); Object.assign(f.binding, { wakeupRequestId: "unrelated-caller-metadata" });
const proof = nativeCursorPlanWaitFromFacts(f);
expect(proof).not.toBeNull();
expect(proof!.source).not.toHaveProperty("wakeupRequestId");
});
it.each([
["foreign runner", (f: CursorPlanWaitFacts) => { f.run.runnerInstanceId = "other"; }],
["changed admission binding", (f: CursorPlanWaitFacts) => { (f.run.runnerProfileJson as any).nativeExecutionInput.binding = { ...f.binding, runId: "other" }; }],
["wrong company", (f: CursorPlanWaitFacts) => { f.run.companyId = "other"; }],
["wrong task", (f: CursorPlanWaitFacts) => { f.run.nativeIssueId = "other"; }],
["failed run", (f: CursorPlanWaitFacts) => { f.run.status = "failed"; }],
["cancelled run", (f: CursorPlanWaitFacts) => { f.run.status = "cancelled"; }],
["Agent mode", (f: CursorPlanWaitFacts) => { (f.run.runnerProfileJson as any).nativeExecutionInput.provider.cursorMode = "agent"; }],
["stale profile", (f: CursorPlanWaitFacts) => { (f.run.runnerProfileJson as any).nativeExecutionInput.provider.profile = { ...resolveQualifiedAcpxProfile("cursor", "gpt-5.6-luna[context=272k,reasoning=medium,fast=false]"), commandDigest: "old" }; }],
["changed contract policy", (f: CursorPlanWaitFacts) => { f.contract.policyVersion = "tampered-policy"; }],
["changed completion authority", (f: CursorPlanWaitFacts) => { f.contract.completionAuthority = "server_arbiter"; }],
["changed contract hash", (f: CursorPlanWaitFacts) => { f.contract.canonicalSha256 = "f".repeat(64); }],
["changed contract", (f: CursorPlanWaitFacts) => { f.contract.contractJson.revision = "new"; }],
["unknown origin", (f: CursorPlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.origin.provider = "acpx"; })],
["wrong method", (f: CursorPlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.origin.method = "cursor/ask_question"; })],
["untrusted adapter", (f: CursorPlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.origin.adapter = "other"; })],
["cross turn", (f: CursorPlanWaitFacts) => editEvent(f, 1, e => { e.turnId = "other"; })],
["cross session", (f: CursorPlanWaitFacts) => editEvent(f, 1, e => { e.normalizedSessionId = "other"; })],
["native error", (f: CursorPlanWaitFacts) => editEvent(f, 2, e => { e.payload.error = { message: "failure" }; })],
["changed plan", (f: CursorPlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.input.description = "other"; })],
["rejection", (f: CursorPlanWaitFacts) => editEvent(f, 1, e => { e.payload.response.answers[`plan-${"a".repeat(64)}`].selectedOptionIds = ["reject"]; })],
["cancellation", (f: CursorPlanWaitFacts) => editEvent(f, 1, e => { e.payload.response.answers[`plan-${"a".repeat(64)}`].selectedOptionIds = ["cancel"]; })],
["missing delivery", (f: CursorPlanWaitFacts) => { f.interactions = []; }],
["unacknowledged delivery", (f: CursorPlanWaitFacts) => { f.interactions[0]!.delivery.acknowledgedAt = null; }],
["fallback wake", (f: CursorPlanWaitFacts) => { f.interactions[0]!.delivery.deliveryMode = "wake_fallback"; }],
["wrong target", (f: CursorPlanWaitFacts) => { f.interactions[0]!.delivery.targetRunId = "other"; }],
["changed answer digest", (f: CursorPlanWaitFacts) => { f.interactions[0]!.delivery.payloadSha256 = "other"; }],
["missing resolution time", (f: CursorPlanWaitFacts) => { f.interactions[0]!.interaction.resolvedAt = null; }],
["agent resolved", (f: CursorPlanWaitFacts) => { f.interactions[0]!.interaction.resolvedByAgentId = "agent"; }],
["duplicate receipt", (f: CursorPlanWaitFacts) => { f.events.splice(1, 0, structuredClone(f.events[0]!)); }],
["duplicate delivery", (f: CursorPlanWaitFacts) => { f.interactions.push(structuredClone(f.interactions[0]!)); }],
["uncommitted event", (f: CursorPlanWaitFacts) => { f.events[1]!.sourcePayloadSha256 = null; }],
["changed row identity", (f: CursorPlanWaitFacts) => { f.events[1]!.sourceEventId = "other"; }],
["terminal before answer", (f: CursorPlanWaitFacts) => { f.events.reverse(); }],
] as const)("rejects %s", (_name, mutate) => {
const f = fixture(); mutate(f); expect(nativeCursorPlanWaitFromFacts(f)).toBeNull();
});
it("does not reuse an older acceptance after a new request, later work, or conflicting terminal", () => {
for (const kind of ["runtime_request.created", "tool.execution.started", "turn.failed", "turn.cancelled", "turn.completed"]) {
const f = fixture(); const row = structuredClone(f.events[0]!);
row.seq = 2.5; row.sourceSeq = 3; row.sourceEventId = "instance:later"; row.eventType = kind;
const e = (row.payload as any).prpEvent; Object.assign(e, { sourceSeq: 3, sourceEventId: row.sourceEventId, eventType: kind });
if (kind === "runtime_request.created") e.payload.request.requestId = "new-plan";
row.sourcePayloadSha256 = nativeSha256(e);
editEvent(f, 2, e => { e.sourceSeq = 4; }); f.events[2]!.sourceSeq = 4;
f.events.splice(2, 0, row);
expect(nativeCursorPlanWaitFromFacts(f)).toBeNull();
}
});
});
@@ -0,0 +1,243 @@
import { and, asc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm";
import {
completionContracts, heartbeatRunEvents, heartbeatRuns, issues, issueComments,
nativeRunFinalizations, nativeRunResults, statusDecisions,
issueQuestionResponseDeliveries, issueThreadInteractions, type Db,
} from "@paperclipai/db";
import type { AskUserQuestionsInteraction } from "@paperclipai/shared";
import {
parsePaperclipQuestionResponse, parsePaperclipQuestionSet, resolveQualifiedAcpxProfile,
type PrpStructuredRunResult,
} from "../../vendor/paperclip-runner/index.js";
import { buildQuestionResponseDeliveryEnvelope } from "../question-response-delivery.js";
import { nativeCompletionContractSha256 } from "./completion-contracts.js";
import { nativeSha256 } from "./canonical.js";
type Binding = { companyId: string; issueId: string; runId: string; agentId: string };
const record = (v: unknown): Record<string, any> => v && typeof v === "object" && !Array.isArray(v) ? v as Record<string, any> : {};
const same = (a: unknown, b: unknown) => nativeSha256(a) === nativeSha256(b);
const PREFIX = "cursor-plan-wait:";
// Preserve the exact Cursor6 proof query: progress rows were never part of its
// 1,000-row budget. Completed tools were included and must stay included.
const LEGACY_EVENT_TYPES = ["runtime_request.created", "runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired", "turn.started", "turn.completed", "turn.failed", "turn.cancelled", "tool.execution.started", "tool.execution.completed"];
const EVENT_TYPES = [...LEGACY_EVENT_TYPES, "tool.execution.progressed"];
const SUMMARY = "Plan accepted. This task is waiting for your next message. This run used Plan mode; no implementation or task completion is claimed.";
export interface NativeCursorPlanWaitSource extends Binding {
schema: "paperclip.native_cursor_plan_wait.v1";
contractId: string;
contractSha256: string;
interactionId: string;
requestId: string;
planRevision: string;
turnId: string;
normalizedSessionId: string;
sourceInstanceId: string;
requestEventId: string;
resolvedEventId: string;
terminalEventId: string;
deliveryId: string;
authoritySha256: string;
toolExecutionId?: string;
toolLifecycleSha256?: string;
}
export interface CursorPlanWaitFacts {
binding: Binding;
run: Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "agentId" | "nativeIssueId" | "runtimeMode" | "status" | "runnerProfileJson" | "runnerInstanceId" | "completionContractId" | "completionContractSha256">;
contract: Pick<typeof completionContracts.$inferSelect, "id" | "canonicalSha256" | "contractJson" | "schemaVersion" | "policyVersion" | "risk" | "completionAuthority">;
events: Array<Pick<typeof heartbeatRunEvents.$inferSelect, "companyId" | "agentId" | "runId" | "seq" | "eventType" | "payload" | "sourceInstanceId" | "sourceEventId" | "sourceSeq" | "sourcePayloadSha256" | "protocolSchemaVersion">>;
interactions: Array<{ interaction: typeof issueThreadInteractions.$inferSelect; delivery: typeof issueQuestionResponseDeliveries.$inferSelect }>;
}
function isHistoricalUnboundWait(source?: NativeCursorPlanWaitSource): boolean {
return source !== undefined && source.toolExecutionId === undefined && source.toolLifecycleSha256 === undefined;
}
/** Only committed native request/answer/normal-terminal facts can create this passive wait. */
export function nativeCursorPlanWaitFromFacts(facts: CursorPlanWaitFacts) {
return cursorPlanWaitFromFacts(facts);
}
function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: NativeCursorPlanWaitSource): { source: NativeCursorPlanWaitSource; result: PrpStructuredRunResult } | null {
try {
const { run, contract } = facts;
const b: Binding = { companyId: facts.binding.companyId, issueId: facts.binding.issueId, runId: facts.binding.runId, agentId: facts.binding.agentId };
const admission = record(record(run.runnerProfileJson).nativeExecutionInput);
const provider = record(admission.provider), profile = record(provider.profile);
// First admission must match today's qualified runtime. Recovery may retain
// a previously committed wait only if the entire original proof is unchanged.
if (!committedSource) {
const expected = resolveQualifiedAcpxProfile("cursor", typeof provider.model === "string" ? provider.model : "");
if (!["agent", "driverKind", "protocolVersion", "acpxVersion", "commandDigest", "agentProfileVersion", "agentServerPackage", "agentServerVersion", "agentRuntimePackage", "agentRuntimeVersion"].every(key => profile[key] === record(expected)[key])) return null;
}
if (run.id !== b.runId || run.companyId !== b.companyId || run.agentId !== b.agentId || run.nativeIssueId !== b.issueId || run.runtimeMode !== "native" || !["running", "succeeded"].includes(run.status) ||
!Object.entries(b).every(([key, value]) => record(admission.binding)[key] === value) || provider.kind !== "acpx" || provider.agent !== "cursor" || provider.cursorMode !== "plan" || typeof provider.model !== "string" || !provider.model.trim() ||
record(admission.completionContract).id !== contract.id || record(admission.completionContract).sha256 !== contract.canonicalSha256 || nativeCompletionContractSha256(contract) !== contract.canonicalSha256 || run.completionContractId !== contract.id || run.completionContractSha256 !== contract.canonicalSha256 || !same(contract.contractJson, record(admission.completionContract).contract)) return null;
const sessionId = record(admission.session).normalizedSessionId;
if (typeof sessionId !== "string" || !sessionId || facts.events.length === 0 || facts.events.length > 1000) return null;
const events: Array<Record<string, any>> = [];
const ids = new Set<string>(), seqs = new Set<string>();
let lastRowSeq = -1;
const lastSourceSeq = new Map<string, number>();
for (const row of facts.events) {
const event = record(record(row.payload).prpEvent);
if (!event.schema) continue; // Non-PRP aggregate rows are not native evidence.
if (row.companyId !== b.companyId || row.runId !== b.runId || row.agentId !== b.agentId || row.seq <= lastRowSeq ||
event.schema !== "paperclip.prp.event.v1" || event.schemaVersion !== 1 || event.sourceInstanceId !== run.runnerInstanceId || event.sourceKind !== "runner" || event.runId !== b.runId || event.normalizedSessionId !== sessionId ||
row.eventType !== event.eventType || row.sourceEventId !== event.sourceEventId || row.sourceInstanceId !== event.sourceInstanceId || row.sourceSeq !== event.sourceSeq || row.protocolSchemaVersion !== event.schemaVersion ||
typeof event.sourceInstanceId !== "string" || !event.sourceInstanceId || typeof event.sourceEventId !== "string" || !event.sourceEventId || !Number.isSafeInteger(event.sourceSeq) || event.sourceSeq < 1 || row.sourcePayloadSha256 !== nativeSha256(event) ||
(lastSourceSeq.get(event.sourceInstanceId) ?? 0) >= event.sourceSeq || ids.has(event.sourceEventId) || seqs.has(`${event.sourceInstanceId}:${event.sourceSeq}`)) return null;
lastSourceSeq.set(event.sourceInstanceId, event.sourceSeq);
lastRowSeq = row.seq; ids.add(event.sourceEventId); seqs.add(`${event.sourceInstanceId}:${event.sourceSeq}`); events.push(event);
}
const terminal = events.at(-1);
if (!terminal || terminal.eventType !== "turn.completed" || record(terminal.payload).status !== "completed" || record(terminal.payload).error != null || typeof terminal.turnId !== "string") return null;
const turn = events.filter(e => e.turnId === terminal.turnId);
if (turn.some(e => e.sourceInstanceId !== terminal.sourceInstanceId) || turn.filter(e => ["turn.completed", "turn.failed", "turn.cancelled"].includes(e.eventType)).length !== 1) return null;
const requests = turn.filter(e => e.eventType === "runtime_request.created");
const created = requests.at(-1), request = record(record(created?.payload).request), origin = record(request.origin);
if (!created || request.schema !== "paperclip.runtime_request.v2" || request.type !== "input" || request.requestKind !== "runtime" || request.status !== "pending" || request.turnId !== terminal.turnId ||
origin.provider !== "cursor" || origin.method !== "cursor/create_plan" || !["acpx-runtime", "acpx-runtime-sidecar"].includes(origin.adapter) || typeof request.requestId !== "string") return null;
if (new Set(requests.map(e => record(record(e.payload).request).requestId)).size !== requests.length) return null;
// No unresolved earlier input or later work is disguised as an accepted plan boundary.
for (const start of requests) {
const id = record(record(start.payload).request).requestId;
const ends = turn.filter(e => ["runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired"].includes(e.eventType) && record(e.payload).requestId === id);
if (ends.length !== 1 || ends[0]!.sourceSeq <= start.sourceSeq || ends[0]!.eventType !== "runtime_request.resolved") return null;
}
const resolved = turn.find(e => e.eventType === "runtime_request.resolved" && record(e.payload).requestId === request.requestId)!;
const resolution = record(resolved.payload);
if (resolved.sourceSeq >= terminal.sourceSeq || resolution.action !== "submit" || resolution.turnId !== terminal.turnId) return null;
const historicalUnboundWait = isHistoricalUnboundWait(committedSource);
let toolBinding: { toolExecutionId: string; toolLifecycleSha256: string } | undefined;
if (historicalUnboundWait) {
if (profile.agentProfileVersion !== 6 || profile.commandDigest !== "sha256:377dcea64a727ce799cc112458d4b40ba4bc6574cd6c6f7233b6efd5917a6c4b") return null;
// Reconstruct only the previously committed contract; never create a new
// unbound wait or let a catalog upgrade authorize additional work.
if (turn.some(e => e.sourceSeq > created.sourceSeq && e.eventType === "tool.execution.started")) return null;
} else {
const id = request.itemId;
if (typeof id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/.test(id)) return null;
const tools = turn.filter(e => e.eventType.startsWith("tool.execution."));
const lifecycle = tools.filter(e => record(e.payload).executionId === id);
const starts = lifecycle.filter(e => e.eventType === "tool.execution.started");
const ends = lifecycle.filter(e => e.eventType === "tool.execution.completed");
if (starts.length !== 1 || ends.length !== 1 || starts[0]!.sourceSeq >= resolved.sourceSeq || ends[0]!.sourceSeq <= resolved.sourceSeq || ends[0]!.sourceSeq >= terminal.sourceSeq ||
lifecycle[0] !== starts[0] || lifecycle.at(-1) !== ends[0] ||
lifecycle.some(e => record(e.payload).schema !== "paperclip.tool.execution.v1" || record(e.payload).transport !== "builtin" || record(e.payload).operation !== "execute" || record(e.payload).status !== (e.eventType === "tool.execution.completed" ? "completed" : "running")) ||
tools.some(e => e.sourceSeq > created.sourceSeq && record(e.payload).executionId !== id)) return null;
toolBinding = { toolExecutionId: id, toolLifecycleSha256: nativeSha256(lifecycle) };
}
const questionSet = parsePaperclipQuestionSet(request.input);
const plan = questionSet.questions.filter(q => /^plan-[a-f0-9]{64}$/.test(q.id));
if (plan.length !== 1 || plan[0]!.answerMode !== "single_select" || !plan[0]!.required || !same(plan[0]!.options?.map(o => o.id), ["accept", "reject", "cancel"])) return null;
const response = parsePaperclipQuestionResponse(questionSet, resolution.response);
if (!same(response.answers[plan[0]!.id]?.selectedOptionIds, ["accept"])) return null;
const matches = facts.interactions.filter(({ interaction: i }) => record(i.payload).runtimeRequestId === request.requestId);
if (matches.length !== 1) return null;
const { interaction: i, delivery: d } = matches[0]!;
if (i.companyId !== b.companyId || i.issueId !== b.issueId || i.sourceRunId !== b.runId || i.createdByAgentId !== b.agentId || i.kind !== "ask_user_questions" || i.status !== "answered" || i.continuationPolicy !== "none" || !i.resolvedByUserId || !i.resolvedAt || i.resolvedByAgentId ||
i.idempotencyKey !== `paperclip-runner-question:${b.runId}:${request.requestId}` || !same(record(i.payload).questionSet, questionSet) ||
d.companyId !== b.companyId || d.issueId !== b.issueId || d.interactionId !== i.id || d.sourceRunId !== b.runId || d.targetRunId !== b.runId || d.status !== "delivered" || d.deliveryMode !== "steered" || !d.acknowledgedAt || (d.targetTurnId !== null && d.targetTurnId !== terminal.turnId)) return null;
const envelope = buildQuestionResponseDeliveryEnvelope(i as unknown as AskUserQuestionsInteraction);
if (d.payloadSha256 !== nativeSha256(envelope) || !same(parsePaperclipQuestionResponse(questionSet, envelope.response), response)) return null;
const source: NativeCursorPlanWaitSource = {
...b, schema: "paperclip.native_cursor_plan_wait.v1", contractId: contract.id, contractSha256: contract.canonicalSha256, interactionId: i.id, requestId: request.requestId, planRevision: plan[0]!.id,
turnId: terminal.turnId, normalizedSessionId: sessionId, sourceInstanceId: terminal.sourceInstanceId,
requestEventId: created.sourceEventId, resolvedEventId: resolved.sourceEventId, terminalEventId: terminal.sourceEventId, deliveryId: d.id,
...(toolBinding ?? {}),
authoritySha256: nativeSha256({ admission, contract, created, resolved, terminal, interaction: i, delivery: d, resolvedAt: i.resolvedAt?.toISOString(), acknowledgedAt: d.acknowledgedAt.toISOString(), ...(toolBinding ? { toolBinding } : {}) }),
};
if (committedSource && !same(source, committedSource)) return null;
const ref = `interaction:${i.id}`;
const result: PrpStructuredRunResult = {
schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", summary: SUMMARY,
completionClaim: { contractRevision: String(contract.contractJson.revision), objectiveSatisfied: false,
criteria: (contract.contractJson.criteria as Array<{id: string}>).map(c => ({ criterionId: c.id, status: "unknown", evidenceRefs: [ref] })),
remainingWork: [{ description: "Continue or finalize the accepted plan only after explicit direction; remain in the selected mode.", blocksCompletion: true }] },
evidence: [{ ref }, { ref: `run-event:${resolved.sourceEventId}` }], verification: [], attentionRequests: [],
artifacts: [{ kind: "issue_thread_interaction", ref }],
continuation: { kind: "response_wake", summary: SUMMARY, idempotencyKey: `${PREFIX}${created.sourceEventId}` },
};
return { source, result };
} catch { return null; }
}
export function isNativeCursorPlanWaitResult(value: unknown): boolean {
const result = record(value);
return result.reportedWorkDisposition === "yielded" && typeof record(result.continuation).idempotencyKey === "string" && record(result.continuation).idempotencyKey.startsWith(PREFIX);
}
/** The committer calls this again under its issue lock; rows are share-locked then. */
export async function readNativeCursorPlanWait(db: Db, binding: Binding, locked = false) {
return readCursorPlanWaitProof(db, binding, locked);
}
// Historical profile validation is available only after the committed-receipt
// query below establishes its scoped authority. New wait callers cannot select it.
async function readCursorPlanWaitProof(db: Db, binding: Binding, locked: boolean, committedSource?: NativeCursorPlanWaitSource) {
const q = db.select({ run: heartbeatRuns, contract: completionContracts }).from(heartbeatRuns)
.innerJoin(completionContracts, and(eq(completionContracts.id, heartbeatRuns.completionContractId), eq(completionContracts.companyId, binding.companyId), eq(completionContracts.issueId, binding.issueId)))
.innerJoin(issues, and(eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId), eq(issues.assigneeAgentId, binding.agentId)))
.where(and(eq(heartbeatRuns.id, binding.runId), eq(heartbeatRuns.companyId, binding.companyId), eq(heartbeatRuns.agentId, binding.agentId), eq(heartbeatRuns.nativeIssueId, binding.issueId))).limit(1);
const [row] = await (locked ? q.for("share", { noWait: true }) : q);
if (!row || record(record(row.run.runnerProfileJson).nativeExecutionInput).provider?.agent !== "cursor" || record(record(row.run.runnerProfileJson).nativeExecutionInput).provider?.cursorMode !== "plan") return null;
const eventTypes = isHistoricalUnboundWait(committedSource) ? LEGACY_EVENT_TYPES : EVENT_TYPES;
const eqs = db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.companyId, binding.companyId), eq(heartbeatRunEvents.runId, binding.runId), inArray(heartbeatRunEvents.eventType, eventTypes))).orderBy(asc(heartbeatRunEvents.seq)).limit(1001);
const events = await (locked ? eqs.for("share", { noWait: true }) : eqs);
const iq = db.select({ interaction: issueThreadInteractions, delivery: issueQuestionResponseDeliveries }).from(issueThreadInteractions)
.innerJoin(issueQuestionResponseDeliveries, eq(issueQuestionResponseDeliveries.interactionId, issueThreadInteractions.id))
.where(and(eq(issueThreadInteractions.companyId, binding.companyId), eq(issueThreadInteractions.issueId, binding.issueId), eq(issueThreadInteractions.sourceRunId, binding.runId))).limit(101);
const interactions = await (locked ? iq.for("share", { noWait: true }) : iq);
if (interactions.length > 100) return null;
return cursorPlanWaitFromFacts({ binding, ...row, events, interactions }, committedSource);
}
/** An exact applied wait suppresses recovery, not a later independently admitted user wake. */
export async function hasCommittedNativeCursorPlanWait(db: Db, binding: Binding): Promise<boolean> {
const [receipt] = await db.select({ decision: statusDecisions, result: nativeRunResults })
.from(nativeRunFinalizations)
.innerJoin(statusDecisions, and(
eq(statusDecisions.id, nativeRunFinalizations.decisionId),
eq(statusDecisions.assessmentId, nativeRunFinalizations.assessmentId),
eq(statusDecisions.companyId, binding.companyId), eq(statusDecisions.issueId, binding.issueId),
eq(statusDecisions.runId, binding.runId), eq(statusDecisions.applicationState, "applied"),
eq(statusDecisions.toStatus, "in_progress"), eq(statusDecisions.reasonCode, "native_plan_accepted_waiting_for_continuation"),
))
.innerJoin(nativeRunResults, and(
eq(nativeRunResults.id, nativeRunFinalizations.resultId), eq(nativeRunResults.companyId, binding.companyId),
eq(nativeRunResults.issueId, binding.issueId), eq(nativeRunResults.runId, binding.runId), eq(nativeRunResults.schemaStatus, "accepted"),
))
.innerJoin(issues, and(
eq(issues.id, binding.issueId), eq(issues.companyId, binding.companyId), eq(issues.assigneeAgentId, binding.agentId),
eq(issues.status, "in_progress"), eq(issues.lastStatusDecisionId, statusDecisions.id), isNull(issues.hiddenAt),
sql`coalesce(${issues.executionState}->>'status', '') <> 'pending'`,
))
.where(and(eq(nativeRunFinalizations.companyId, binding.companyId), eq(nativeRunFinalizations.issueId, binding.issueId),
eq(nativeRunFinalizations.runId, binding.runId), eq(nativeRunFinalizations.phase, "committed"))).limit(1);
if (!receipt) return false;
const committedSource = record(receipt.decision.decisionJson).cursorPlanWait as NativeCursorPlanWaitSource | undefined;
if (!committedSource) return false;
const proof = await readCursorPlanWaitProof(db, binding, false, committedSource);
const envelope = record(receipt.result.resultJson), terminal = record(envelope.terminal);
const acceptedIdentity = record(record(receipt.decision.decisionJson).cursorPlanWaitResult);
if (!proof || receipt.result.completionContractId !== proof.source.contractId || receipt.result.turnId !== proof.source.turnId || acceptedIdentity.resultId !== receipt.result.id || acceptedIdentity.resultSha256 !== receipt.result.canonicalSha256 || !same(record(receipt.decision.decisionJson).cursorPlanWait, proof.source) || !same(envelope.result, proof.result) ||
terminal.schema !== "paperclip.prp.terminal.v1" || terminal.runTerminalState !== "succeeded" || terminal.turnTerminalState !== "completed" || terminal.reportedWorkDisposition !== "yielded") return false;
const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, binding.runId), eq(heartbeatRuns.companyId, binding.companyId))).limit(1);
if (!run || run.status !== "succeeded") return false;
// Settings for future runs cannot authorize work on this accepted plan.
// The original admission is checked above; only task-specific continuation
// or a superseding decision/run can release this committed passive wait.
const [interaction] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, proof.source.interactionId)).limit(1);
if (!interaction?.resolvedAt) return false;
const [newRequest, newerRun] = await Promise.all([
db.select({ id: issueComments.id }).from(issueComments).where(and(
eq(issueComments.companyId, binding.companyId), eq(issueComments.issueId, binding.issueId),
eq(issueComments.authorType, "user"), gt(issueComments.createdAt, interaction.resolvedAt),
)).limit(1),
db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, binding.companyId), eq(heartbeatRuns.nativeIssueId, binding.issueId), ne(heartbeatRuns.id, binding.runId), gt(heartbeatRuns.createdAt, run.createdAt),
)).limit(1),
]);
return newRequest.length === 0 && newerRun.length === 0;
}
@@ -1,4 +1,5 @@
import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
import { resolvePaperclipRunnerCursorMode } from "@paperclipai/adapter-utils";
import { createHash } from "node:crypto";
import { buildNativeContinuationPrompt } from "./native-continuation.js";
import type {
@@ -71,6 +72,7 @@ export function buildNativeExecutionInput(input: {
codexReasoningEffort?: string;
opencodePermissionMode?: NativeOpenCodePermissionMode;
acpxPermissionMode?: NativeAcpxPermissionMode;
acpxSessionMode?: "agent" | "plan" | "ask";
model?: string | null;
managedProfile?: Extract<
NativeExecutionInputV5["provider"],
@@ -102,6 +104,7 @@ export function buildNativeExecutionInput(input: {
if (input.issue.workMode !== "standard" && input.issue.workMode !== "planning" && input.issue.workMode !== "ask") {
throw new Error("native_execution_input_invalid: issue work mode must be standard, planning, or ask");
}
const cursorMode = resolvePaperclipRunnerCursorMode(input.provider, input.acpxAgent, input.acpxSessionMode);
const executionMode = input.executionMode
?? (input.issue.workMode === "planning" ? "plan" : "default");
const acpxProfile = input.provider === "acpx"
@@ -263,6 +266,7 @@ export function buildNativeExecutionInput(input: {
agent: acpxProfile!.agent,
model: input.model,
permissionMode: input.acpxPermissionMode ?? "approve-all",
...(cursorMode === undefined ? {} : { cursorMode }),
profile: {
driverKind: acpxProfile!.driverKind,
protocolVersion: acpxProfile!.protocolVersion,
@@ -1,3 +1,4 @@
import { isNativeCursorPlanWaitResult, readNativeCursorPlanWait } from "./native-cursor-plan-wait.js";
import { settleSlackConversation } from "../slack-conversation-lifecycle.js";
import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js";
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js";
@@ -1274,7 +1275,17 @@ export async function finalizeNativeRun(input: {
companyId: run.companyId, issueId: authoritativeIssue.id, agentId: run.agentId,
contextSnapshot: reviewContext, allowResolvedByRunId: run.id,
}) : null;
const cursorPlanWait = isNativeCursorPlanWaitResult(result)
? await readNativeCursorPlanWait(input.db, { companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId })
: null;
// Loss of the authority behind this server-issued wait must never fall
// through to the generic response_wake auto-continuation branch.
if (isNativeCursorPlanWaitResult(result) &&
(!cursorPlanWait || nativeSha256(cursorPlanWait.result) !== nativeSha256(result))) {
throw new Error("native_cursor_plan_wait_authority_lost");
}
const proposedDecision = resolveNativeFinalizerStatus({
cursorPlanWaitAuthorized: cursorPlanWait !== null,
...(reviewContext ? { nativeReviewOutcome: nativeReview
? nativeReview.interaction.status === "pending" ? "pending" as const : "resolved" as const
: "stale" as const } : {}),
@@ -1351,6 +1362,9 @@ export async function finalizeNativeRun(input: {
priorStatusVersion: Number(authoritativeIssue.statusVersion),
priorDecisionId: authoritativeIssue.lastStatusDecisionId,
decision,
requireCursorPlanWaitSource:
decision.reasonCode === "native_plan_accepted_waiting_for_continuation"
? cursorPlanWait?.source : undefined,
requireBoardResponseWaitSource:
decision.reasonCode === "board_response_waiting" || repairBoardResponseWait
? boardResponseWait?.source
@@ -883,10 +883,10 @@ export async function stageNativeRunnerWakeAttachments(input: {
if (workspaceRoot) {
const processDirectoryName = await currentStagingProcessDirectoryName();
await withStagingRegistryLock(workspaceRoot, async () => {
const stagingDirectory = await ensurePrivateStagingDirectory(
workspaceRoot,
processDirectoryName,
);
// Empty wakes still scrub abandoned bytes, but need no new staging paths.
const stagingDirectory = selections.length > 0
? await ensurePrivateStagingDirectory(workspaceRoot, processDirectoryName)
: null;
const activePaths =
activeStagingPathsByWorkspace.get(workspaceRoot) ?? new Set<string>();
const reusablePaths = await scrubNativeRunnerStagingResidue(
@@ -894,7 +894,7 @@ export async function stageNativeRunnerWakeAttachments(input: {
activePaths,
processDirectoryName,
);
if (selections.length > 0) {
if (stagingDirectory !== null) {
stagingDestinations = reusablePaths.slice(0, selections.length);
while (stagingDestinations.length < selections.length) {
const candidate = path.join(stagingDirectory, randomUUID());
@@ -1150,6 +1150,17 @@ describe("remote provider pack manifest", () => {
expect(readRemoteProviderPackManifest(root).payload.pins.opencode).toBe(
"1.18.32",
);
const cursorPath = "provider-assets/cursor/linux-x64";
await mkdir(join(root, cursorPath), { recursive: true });
await writeFile(join(root, cursorPath, "runtime"), "pinned Cursor runtime");
Object.assign(payload, { providers: { cursor: { version: "2026.09.26-dd393fe", profileDigest: digest("cursor-profile"),
closureDigest: digest("cursor-closure"), qualification: "pending", path: cursorPath,
sha256: sha256DirectoryTree(join(root, cursorPath)) } } });
await writeManifest();
expect(readRemoteProviderPackManifest(root).payload.providers?.cursor?.version).toBe("2026.09.26-dd393fe");
await writeFile(join(root, cursorPath, "runtime"), "substitute Cursor runtime");
expect(() => readRemoteProviderPackManifest(root)).toThrow("asset tree digest mismatch");
await writeFile(join(root, cursorPath, "runtime"), "pinned Cursor runtime");
const candidatePath = "provider-assets/pi/linux-x64";
await mkdir(join(root, candidatePath), { recursive: true });
await writeFile(join(root, candidatePath, "runtime"), "pinned runtime");
@@ -1,3 +1,5 @@
import { nativeRetryCancellationEligible, rethrowNativeCancellationLockConflict, assertCancellationRequest, cancellationIntentId as callerCancellationIntentId, cancellationRequestId } from "./native-cancellation-request.js";
import { readNativeCursorPlanWait } from "./native-cursor-plan-wait.js";
import { resolveAcpxQualification } from "./acpx-qualification.js";
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js";
@@ -138,7 +140,7 @@ import {
renderNativeRunnerStagedAttachmentPrompt,
stageNativeRunnerWakeAttachments,
} from "./native-runner-file-handoff.js";
import { nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
import { nativeRuntimeContractForProvider, nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
import { verifyRetainedMaintenanceNoLaunch } from "./native-maintenance-no-launch.js";
import { registerRunnerPrpAuthority } from "../../realtime/runner-prp-ws.js";
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
@@ -155,7 +157,7 @@ import {
type NativeAuthoritativeIssueStatus,
type NativeStatusDecision,
} from "./status-arbiter.js";
import { HttpError } from "../../errors.js";
import { conflict, HttpError } from "../../errors.js";
import { redactSensitiveText } from "../../redaction.js";
import { resolvePaperclipRunnerBinary } from "./native-codex-runner.js";
import {
@@ -5272,6 +5274,7 @@ function nativeSessionConfigDigest(
// without newly required tools.
nativeToolContractFingerprint:
nativeToolContractFingerprintForTarget(executionTargetKind),
runtimeContract: nativeRuntimeContractForProvider(execution.provider),
}),
)
.digest("hex")}`;
@@ -5491,6 +5494,7 @@ export function providerSessionIdentityFromDurableProviderState(input: {
identity.requestedModel !== expectedModel ||
identity.effectiveModel !== expectedModel ||
identity.permissionMode !== input.execution.provider.permissionMode ||
!acpxRecoveryCursorModeMatches(input.execution.provider, descriptor.cursorMode, identity.cursorMode) ||
!["approve-all", "approve-paperclip", "approve-reads", "deny-all"].includes(
String(identity.permissionMode),
) ||
@@ -5575,11 +5579,30 @@ function providerSessionIdentityIsPresent(value: unknown): boolean {
);
}
// Recovery consumes observed identities; it must never apply the fresh-config
// default to a missing persisted mode or allow another provider to carry it.
function acpxRecoveryCursorModeMatches(
provider: NativeExecutionInput["provider"],
...observedModes: unknown[]
): boolean {
const expected = record(provider).cursorMode;
if (provider.kind === "acpx" && provider.agent === "cursor") {
return (expected === "agent" || expected === "plan" || expected === "ask")
&& observedModes.every(mode => mode === expected);
}
return expected === undefined && observedModes.every(mode => mode === undefined);
}
export function providerSessionIdentityTransitionIsAllowed(input: {
execution: NativeExecutionInput;
previous: unknown;
current: unknown;
}): boolean {
if (input.execution.provider.kind === "acpx" && !acpxRecoveryCursorModeMatches(
input.execution.provider,
record(record(input.previous).providerSessionIdentity).cursorMode,
record(record(input.current).providerSessionIdentity).cursorMode,
)) return false;
if (canonicalJson(input.previous) === canonicalJson(input.current)) {
return true;
}
@@ -6568,6 +6591,7 @@ export function cancelNativeSession(
db: Db;
scope?: "turn" | "run" | "issue";
replacementAccepted?: boolean;
cancellationRequestId?: string;
},
): Promise<{
dispatched: boolean;
@@ -6582,6 +6606,7 @@ export async function cancelNativeSession(
db: Db;
scope?: "turn" | "run" | "issue";
replacementAccepted?: boolean;
cancellationRequestId?: string;
},
): Promise<
| boolean
@@ -6708,8 +6733,10 @@ export async function cancelNativeSession(
}
if (isNativeRunnerOwnershipHeld(lockedRun))
throw new NativeRunnerOwnershipUnverifiedError();
const coordinator = await tx
.select({ runId: nativeRunFinalizations.runId })
const retryCancellation = lockedRun.status === "failed"
|| record(record(lockedRun.resultJson).startupCancellation).retryCancellation === true;
const coordinatorQuery = tx
.select({ runId: nativeRunFinalizations.runId, phase: nativeRunFinalizations.phase, failureCode: nativeRunFinalizations.failureCode })
.from(nativeRunFinalizations)
.where(
and(
@@ -6717,13 +6744,25 @@ export async function cancelNativeSession(
eq(nativeRunFinalizations.companyId, cancellationContext.companyId),
eq(nativeRunFinalizations.issueId, cancellationContext.issueId),
),
)
.limit(1)
.then((rows) => rows[0] ?? null);
);
// Recheck after reservation, at the same transaction that records intent
// and disables the retry. NOWAIT avoids coordinator -> run lock inversion.
const coordinator = await (retryCancellation
? coordinatorQuery.for("update", { noWait: true }) : coordinatorQuery)
.limit(1).then((rows) => rows[0] ?? null);
if (!coordinator)
throw new Error("native_cancellation_coordinator_missing");
const resultJson = record(lockedRun.resultJson);
// A default Stop joins an already reserved caller intent; it cannot
// replace that intent while the originating request is still dispatching.
const requestedId = options.cancellationRequestId
?? cancellationRequestId(record(resultJson.startupCancellation).cancellationRequestId);
if (requestedId) assertCancellationRequest(resultJson, requestedId);
if (retryCancellation && !nativeRetryCancellationEligible({
runId, companyId: cancellationContext.companyId, issueId: cancellationContext.issueId,
resultJson, requestId: requestedId, scope: options.scope ?? "run",
}, coordinator)) throw conflict("Native retry is no longer cancellable");
const existing = record(resultJson.nativeCancellation);
const existingIntentId =
typeof existing.intentId === "string" && existing.intentId.length > 0
@@ -6764,7 +6803,9 @@ export async function cancelNativeSession(
};
}
const intentId = `native-cancellation:${randomUUID()}`;
const intentId = requestedId
? callerCancellationIntentId(requestedId)
: `native-cancellation:${randomUUID()}`;
const activity = await persistActivity(tx as unknown as Db, {
companyId: cancellationContext.companyId,
actorType: "system",
@@ -6851,7 +6892,7 @@ export async function cancelNativeSession(
priorCoordinatorDecisionId: cancellationContext.coordinatorDecisionId,
existing: false,
};
});
}).catch(rethrowNativeCancellationLockConflict);
if (intentPublication) publishActivity(intentPublication);
cancellationIntentId = intent.intentId;
auditId = intent.auditId;
@@ -8382,6 +8423,10 @@ async function executePaperclipNativeSessionWithinScope(
if (terminalEvent.eventType !== "turn.completed") return null;
const governedWait = await resolvePendingGovernedWait();
if (governedWait) return governedWait;
if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "cursor" && input.execution.provider.cursorMode === "plan") {
const planWait = await readNativeCursorPlanWait(input.db, input.execution.binding);
if (planWait?.source.terminalEventId === terminalEvent.sourceEventId) return planWait.result;
}
const [conversation] = await input.db
.select({ agentId: issues.conversationAgentId })
.from(issues)
@@ -9441,6 +9486,10 @@ type RemoteProviderPackManifest = {
distDigest: string;
bridgeDigest: string;
acpxProfileDigests: typeof REMOTE_PROVIDER_PACK_PROFILE_DIGESTS;
providers?: Partial<Record<"cursor", {
version: string; profileDigest: string; closureDigest: string; qualification: "pending";
path: string; sha256: string;
}>>;
candidateProviders?: Partial<Record<"cursor" | "copilot" | "pi", {
version: string; profileDigest: string; closureDigest: string; qualification: "pending";
path: string; sha256: string;
@@ -9609,14 +9658,14 @@ export function readRemoteProviderPackManifest(
"runner_remote_provider_artifact_incompatible: provider dist tree digest mismatch",
);
}
if (payload.candidateProviders !== undefined) {
const candidates = payload.candidateProviders;
for (const [inventory, candidates] of [["providers", payload.providers], ["candidateProviders", payload.candidateProviders]] as const) {
if (candidates === undefined) continue;
if (!candidates || typeof candidates !== "object" || Array.isArray(candidates) || Object.keys(candidates).length > 3) {
throw new Error("runner_remote_provider_artifact_incompatible: invalid candidate inventory");
}
for (const [provider, candidate] of Object.entries(candidates)) {
const expectedPath = `provider-assets/${provider}/${payload.target.platform}-${payload.target.architecture}`;
if (!["cursor", "copilot", "pi"].includes(provider) || !candidate
if (!(inventory === "providers" ? ["cursor"] : ["cursor", "copilot", "pi"]).includes(provider) || !candidate
|| Object.keys(candidate).some(key => !["version", "profileDigest", "closureDigest", "qualification", "path", "sha256"].includes(key))
|| candidate.qualification !== "pending" || candidate.path !== expectedPath
|| typeof candidate.version !== "string" || !candidate.version || candidate.version.length > 120
@@ -11039,7 +11088,7 @@ async function createRunnerdBackendWithinSessionClaim(
"const tree=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}",
"for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)throw new Error(name+' digest mismatch')}",
"if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)throw new Error('dist tree digest mismatch')",
"for(const candidate of Object.values(manifest.payload.candidateProviders||{})){if(tree(path.join(root,candidate.path))!==candidate.sha256)throw new Error('candidate asset tree digest mismatch')}",
"for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)throw new Error('candidate asset tree digest mismatch')}",
"const version=process.versions.node.split('.').map(Number)",
"const minimum=manifest.payload.pins.nodeMinimum.split('.').map(Number)",
"if(version[0]<minimum[0]||(version[0]===minimum[0]&&(version[1]<minimum[1]||(version[1]===minimum[1]&&version[2]<minimum[2]))))throw new Error('Node version incompatible')",
@@ -12498,6 +12547,7 @@ async function createRunnerdBackendWithinSessionClaim(
// Read only the server operator environment, never agent/runtime env.
acpxCandidateProfile: resolveAcpxQualification(input.execution.provider, process.env),
acpxPermissionMode: input.execution.provider.permissionMode,
acpxCursorMode: input.execution.provider.cursorMode,
acpxPermissionModePinned:
input.execution.schema === "paperclip.native-execution-input.v4" ||
input.execution.schema === "paperclip.native-execution-input.v5",
@@ -12610,6 +12660,7 @@ async function createRunnerdBackendWithinSessionClaim(
? input.execution.runtimeContext
: null,
runnerRuntimeContext: remoteRuntimeContext,
baseInstructions: recoveryContext?.baseInstructions,
runnerFilesystemRoot: remoteRunnerFilesystemRoot ?? undefined,
resumeWorkingDirectory: runnerExecution.workspace.cwd,
externallySandboxed: remoteTarget?.transport === "sandbox",
@@ -10,6 +10,16 @@ import { canonicalNativeRuntimeContextDigest, parseNativeExecutionInput } from "
export type NativeToolExecutionTargetKind = "local" | "remote";
/** Fence live ACPX owners when shared runtime semantics change, even if the
* underlying native executable/profile did not change. Undefined preserves
* the existing configuration digest for other provider transports.
*/
export function nativeRuntimeContractForProvider(
provider: NativeExecutionInput["provider"],
): string | undefined {
return provider.kind === "acpx" ? "paperclip.acpx-runtime-contract.v1" : undefined;
}
/**
* Persisted provider threads retain their dynamic-tool declarations. This
* fingerprint is part of checkpoint compatibility and must change whenever
@@ -3,6 +3,7 @@ import {
PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES,
PAPERCLIP_RUNNER_ACPX_PROFILES,
resolvePaperclipRunnerPermissionMode,
resolvePaperclipRunnerCursorMode,
type PaperclipRunnerProvider,
} from "@paperclipai/adapter-utils";
import {
@@ -119,6 +120,7 @@ export type PaperclipRunnerNativeProviderInput =
model: string;
acpxAgent: AdmittedPaperclipRunnerAcpxAgent;
acpxPermissionMode: "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
acpxSessionMode?: "agent" | "plan" | "ask";
};
export class PaperclipRunnerProviderProfileError extends Error {
@@ -346,6 +348,14 @@ export function resolvePaperclipRunnerProviderProfile(
}
assertPermissionMode(candidate, config);
try {
resolvePaperclipRunnerCursorMode(candidate, config.acpxAgent, config.acpxSessionMode);
} catch (error) {
throw new PaperclipRunnerProviderProfileError(
"paperclip_runner_cursor_mode_invalid",
error instanceof Error ? error.message : "Invalid Cursor session mode",
);
}
const model = optionalString(config.model);
if (candidate === "codex") {
return {
@@ -521,6 +531,9 @@ export function resolvePaperclipRunnerNativeProviderInput(input: {
provider: "acpx",
model: profile.model,
acpxAgent: profile.acpxAgent,
...(profile.acpxAgent === "cursor" ? {
acpxSessionMode: resolvePaperclipRunnerCursorMode("acpx", "cursor", config.acpxSessionMode),
} : {}),
acpxPermissionMode: resolvePaperclipRunnerPermissionMode(
"acpx",
config.acpxPermissionMode,
@@ -108,6 +108,8 @@ export function arbitrateNativeStatus(input: {
governanceResolvedForRun?: boolean;
externalChatResponseWaitAuthorization?:
"authorized" | "revoked" | "not_applicable";
/** Server-verified accepted Cursor Plan request and normal provider terminal. */
cursorPlanWaitAuthorized?: boolean;
boardResponseWaitAuthorized?: boolean;
boardResponseWaitOrigin?: boolean;
isConversation?: boolean;
@@ -454,6 +456,21 @@ export function arbitrateNativeStatus(input: {
effects: [],
};
}
if (
input.cursorPlanWaitAuthorized === true &&
input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation?.kind === "response_wake"
) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "in_progress", toStatus: "in_progress",
reasonCode: "native_plan_accepted_waiting_for_continuation",
unblockDescriptor: null,
// An answered native plan is not task completion or permission to
// change modes. Only a new explicit user cause may continue the work.
effects: [],
};
}
if (
input.assessment.reportedDisposition === "yielded" &&
input.assessment.continuation &&
@@ -1,3 +1,4 @@
import { readNativeCursorPlanWait, type NativeCursorPlanWaitSource } from "./native-cursor-plan-wait.js";
import { and, asc, desc, eq, inArray, notInArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import type { CreateIssueThreadInteraction } from "@paperclipai/shared";
@@ -1535,6 +1536,7 @@ export async function commitNativeStatusDecision(input: {
preMaterializedEffects?: NativeMaterializedStatusEffect[];
supersedesCommittedDecisionId?: string;
requireExternalChatResponseWaitAuthorization?: { agentId: string };
requireCursorPlanWaitSource?: NativeCursorPlanWaitSource;
requireBoardResponseWaitSource?: NativeBoardResponseWaitSource;
requireBoardResponseWaitOrigin?: NativeBoardResponseWaitOrigin;
reviewResponsePresentation?: {
@@ -1644,6 +1646,32 @@ export async function commitNativeStatusDecision(input: {
const passiveBoardResponseWait =
reasonCode === "board_response_waiting" ||
reasonCode === "board_response_wait_superseded";
let cursorPlanWait: Awaited<ReturnType<typeof readNativeCursorPlanWait>> = null;
let cursorPlanWaitResult: { resultId: string; resultSha256: string } | null = null;
if (reasonCode === "native_plan_accepted_waiting_for_continuation") {
const expected = input.requireCursorPlanWaitSource;
if (!expected || expected.companyId !== input.companyId || expected.issueId !== input.issueId || expected.runId !== input.runId || input.decision.effects.length !== 0 || input.decision.statusAction !== "in_progress" || input.decision.toStatus !== "in_progress") throw new NativeStatusRaceError();
try {
cursorPlanWait = await readNativeCursorPlanWait(tx as unknown as Db, expected, true);
if (!cursorPlanWait || nativeSha256(cursorPlanWait.source) !== nativeSha256(expected)) throw new NativeStatusRaceError();
// Recheck the committed semantic result too: an arbitrary caller cannot
// use a genuine plan receipt to authorize a different finalization.
const [accepted] = await tx.select().from(nativeRunResults).where(and(
eq(nativeRunResults.id, coordinator!.resultId!), eq(nativeRunResults.companyId, input.companyId),
eq(nativeRunResults.issueId, input.issueId), eq(nativeRunResults.runId, input.runId), eq(nativeRunResults.schemaStatus, "accepted"),
)).for("share", { noWait: true });
const envelope = record(accepted?.resultJson), terminal = record(envelope.terminal);
if (!accepted || accepted.completionContractId !== cursorPlanWait.source.contractId || accepted.turnId !== cursorPlanWait.source.turnId ||
nativeSha256(envelope.result) !== nativeSha256(cursorPlanWait.result) ||
terminal.schema !== "paperclip.prp.terminal.v1" || terminal.runTerminalState !== "succeeded" || terminal.turnTerminalState !== "completed" || terminal.reportedWorkDisposition !== "yielded") throw new NativeStatusRaceError();
// completeRun hashes its full private binding, not the stored resultJson.
// Preserve that accepted identity instead of inventing a new digest.
cursorPlanWaitResult = { resultId: accepted.id, resultSha256: accepted.canonicalSha256 };
} catch (error) {
if (isExternalChatWaitAuthorizationContention(error)) throw new NativeStatusRaceError();
throw error;
}
}
let boardResponseWaitOrigin: NativeBoardResponseWaitOrigin | null = null;
if (
passiveBoardResponseWait ||
@@ -1759,6 +1787,7 @@ export async function commitNativeStatusDecision(input: {
? { boardResponseWait: boardResponseWait.source }
: {}),
...(boardResponseWaitOrigin ? { boardResponseWaitOrigin } : {}),
...(cursorPlanWait ? { cursorPlanWait: cursorPlanWait.source, cursorPlanWaitResult } : {}),
priorStatusVersion: input.priorStatusVersion,
projectedStatusVersion:
input.decision.statusAction === "preserve"
@@ -1827,6 +1856,12 @@ export async function commitNativeStatusDecision(input: {
}
if (!decisionRow) throw new Error("native_status_decision_not_persisted");
if (cursorPlanWait) {
await issueService(tx as unknown as Db).addComment(
input.issueId, cursorPlanWait.result.summary,
{ agentId: cursorPlanWait.source.agentId, runId: input.runId }, undefined, tx,
);
}
if (boardResponseWait && reasonCode === "board_response_waiting") {
// The answer and passive-wait receipt commit together. In particular,
// no chat presentation authorization is supplied: this is Board-only.
+4
View File
@@ -1,4 +1,5 @@
import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
import { hasCommittedNativeCursorPlanWait } from "../native-runtime/native-cursor-plan-wait.js";
import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared";
import { settleSlackConversation } from "../slack-conversation-lifecycle.js";
import { externalConversationStateSql } from "../slack-conversation-state.js";
@@ -1171,6 +1172,7 @@ export function recoveryService(
runId: latestRun.id,
agentId: latestRun.agentId,
};
if (await hasCommittedNativeCursorPlanWait(db, binding)) return true;
const [receipt] = await db
.select({
run: heartbeatRuns,
@@ -1369,6 +1371,8 @@ export function recoveryService(
latestRun: LatestIssueRun,
) {
if (issue.monitorNextCheckAt) return true;
if (issue.status === "in_progress" && latestRun?.status === "succeeded" && latestRun.agentId === issue.assigneeAgentId &&
await hasCommittedNativeCursorPlanWait(db, { companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId: latestRun.agentId })) return true;
if (
issue.status === "in_progress" &&
latestRun?.status === "succeeded" &&