diff --git a/doc/plans/2026-10-03-cursor-production-readiness.md b/doc/plans/2026-10-03-cursor-production-readiness.md index 09ed3a8073e..89fe939029f 100644 --- a/doc/plans/2026-10-03-cursor-production-readiness.md +++ b/doc/plans/2026-10-03-cursor-production-readiness.md @@ -630,3 +630,33 @@ Historical live qualification, image, package and review identities above remain historical evidence and are not relabeled as certification of this new source. Release assembly must build matching daemon, sidecar and controller artifacts. Auto-merge is disabled while the updated boundary receives review. + +## Bounded provider-boundary cleanup (2026-10-06) + +The shared ACPX event decoder validates bounded parent-tool identities and the +event's run/turn scope. Native RPC recognition stays in the Cursor adapter before +sidecar emission. The runner's authenticated-run-grant attachment policy is now +an explicit, runner-owned provider capability selected after pinned-profile +validation. Cursor remains the only provider opted into that policy. Its identity, +authority, pending-work and unknown-context-field checks are unchanged. + +The controller settles accepted plans and permission declines through a provider +lifecycle adapter. Cursor owns the native method names, mode interpretation, +accepted revision interpretation and qualified-profile recognition. Shared code +owns committed event correlation, delivery acknowledgement, tool lifecycle, +status arbitration, receipt hashes and recovery suppression. No other provider +gains these settlement capabilities. New receipts use `native_plan_wait` and +`planWait`; a separate read-only decoder retains exact committed Cursor receipts, +including the earlier unbound-tool profile. Mixed or relabeled receipt formats +are rejected. Legacy receipts cannot authorize new waits or implementation work. + +Historical profile-version compatibility now lives in provider metadata. The +generic live-session handler delegates optional notice validation to a provider +adapter. Cursor's partial counters retain their closed diagnostic format and +never become measured usage or spend. + +Focused checks cover normal and historical plan-wait replay, tampering, foreign +scope, unsupported adapters, permission declines, optional diagnostics and Rust +event projection. No new paid provider cells are part of this bounded cleanup. +Historical live results keep their original build identities; new release +artifacts still require matching source and qualification. diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_event_payload.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_event_payload.rs index b4c834fbee7..b40c18aafad 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_event_payload.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_event_payload.rs @@ -125,22 +125,12 @@ pub fn decode_acpx_event( validate_question_set(&question_set)?; let question_set = sanitize_question_set(question_set)?; let origin = optional_object(&event.payload, "origin", "input request origin")?; + // Native methods are interpreted by the provider adapter. This + // transport validates the opaque reference under the event scope. let tool_call_id = if event.payload.get("toolCallId").is_some() { let id = required_id_with_limit(&event.payload, "toolCallId", "input parent tool", 240)?; - if id.len() > 240 - || sanitize_value(&json!(id)) != json!(id) - || origin - .as_ref() - .and_then(|v| v.get("provider")) - .and_then(Value::as_str) - != Some("cursor") - || origin - .as_ref() - .and_then(|v| v.get("method")) - .and_then(Value::as_str) - != Some("cursor/create_plan") - { + if id.len() > 240 || sanitize_value(&json!(id)) != json!(id) { return Err(LocalRunnerError::invalid( "ACPX input parent tool identity is invalid", )); diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs index 041e0dea439..70f20f92f58 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs @@ -12,6 +12,7 @@ use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; +use crate::acpx_provider_capabilities::{run_attachment_policy, RunAttachmentPolicy}; use crate::acpx_provider_session::{ AcpxPermissionMode, AcpxProviderRuntimePolicy, AcpxProviderSession, AcpxProviderSessionConfig, AcpxProviderSessionIdentity, AcpxTurnControlCapabilities, @@ -1105,7 +1106,7 @@ impl AcpxCommandExecutor { object.remove("aggregateDigest"); } } - if descriptor.agent == "cursor" { + if run_attachment_policy(&descriptor.agent) == RunAttachmentPolicy::AuthenticatedRunGrants { // New runs rotate authenticated instruction text and registered // file-copy grants. Preserve mainline MCP refresh while comparing // every remaining context identity, including unknown policy fields. @@ -1118,7 +1119,7 @@ impl AcpxCommandExecutor { || descriptor.runtime_context != state.descriptor.runtime_context; if !compatible || (grants_changed && descriptor.run_id == state.descriptor.run_id) { return Err(DurableRunnerError::invalid( - "Cursor run.attach changed runtime context outside a new authenticated run", + "ACPX run.attach changed runtime context outside a new authenticated run", )); } durable_descriptor.instructions = previous_descriptor.instructions.clone(); diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_capabilities.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_capabilities.rs new file mode 100644 index 00000000000..2be3ee802e0 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_capabilities.rs @@ -0,0 +1,35 @@ +//! Runner-owned provider admission metadata. These capabilities are selected +//! only after the descriptor's pinned profile and launch authority validate; +//! they cannot be enabled by a sidecar event or a caller-supplied flag. + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RunAttachmentPolicy { + ImmutableInstructions, + AuthenticatedRunGrants, +} + +pub(crate) fn run_attachment_policy(agent: &str) -> RunAttachmentPolicy { + match agent { + "cursor" => RunAttachmentPolicy::AuthenticatedRunGrants, + _ => RunAttachmentPolicy::ImmutableInstructions, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_qualified_providers_opt_into_run_grant_rotation() { + assert_eq!( + run_attachment_policy("cursor"), + RunAttachmentPolicy::AuthenticatedRunGrants + ); + for agent in ["claude", "codex", "grok", "pi", "copilot", "unknown"] { + assert_eq!( + run_attachment_policy(agent), + RunAttachmentPolicy::ImmutableInstructions + ); + } + } +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs index c81cd7a5eb9..1015939ce2c 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/lib.rs @@ -3,6 +3,7 @@ pub mod acpx_event_payload; pub mod acpx_event_scope; pub mod acpx_provider_backend; +mod acpx_provider_capabilities; pub mod acpx_provider_checkpoint; pub mod acpx_provider_session; pub mod acpx_provider_state; diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_event_payload.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_event_payload.rs index fc84238d5fe..f14a6244c95 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_event_payload.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_event_payload.rs @@ -403,7 +403,7 @@ fn rejects_payloads_before_decoding_when_scope_or_size_is_invalid() { } #[test] -fn native_plan_parent_tool_is_bounded_origin_scoped_and_not_redacted() { +fn input_parent_tool_is_bounded_scope_checked_and_provider_neutral() { let input = json!({"requestId":"input-1","toolCallId":"tool with spaces", "questionSet":{"schema":"paperclip.question_set.v1","questions":[{"id":"q","prompt":"Proceed?","required":true,"answerMode":"text"}]}, "origin":{"adapter":"acpx-runtime-sidecar","provider":"cursor","method":"cursor/create_plan"}}); @@ -432,10 +432,21 @@ fn native_plan_parent_tool_is_bounded_origin_scoped_and_not_redacted() { changed["toolCallId"] = bad; assert!(decode(changed).is_err()); } - for (field, value) in [("provider", "copilot"), ("method", "cursor/ask_question")] { + // Vendor method recognition belongs to the adapter. Neither a provider name + // nor an RPC spelling changes how this scoped opaque reference is decoded. + for (field, value) in [("provider", "other-provider"), ("method", "other/plan")] { let mut changed = input.clone(); changed["origin"][field] = json!(value); - assert!(decode(changed).is_err()); + assert!(decode(changed).is_ok()); + } + for (run, turn) in [("foreign-run", "turn-1"), ("run-1", "foreign-turn")] { + let mut scoped = event( + GeneratedAcpxSidecarEventType::RuntimeInputRequested, + input.clone(), + ); + scoped.run_id = Some(run.to_owned()); + scoped.turn_id = Some(turn.to_owned()); + assert!(decode_acpx_event(&active_scope(), &scoped).is_err()); } let mut legacy = input; legacy.as_object_mut().unwrap().remove("toolCallId"); diff --git a/packages/paperclip-runner/src/contracts/native-execution.ts b/packages/paperclip-runner/src/contracts/native-execution.ts index 1504f1c311b..fc1f1e4b0a5 100644 --- a/packages/paperclip-runner/src/contracts/native-execution.ts +++ b/packages/paperclip-runner/src/contracts/native-execution.ts @@ -1,3 +1,4 @@ +import { isSupportedAcpxProfileVersion, type AcpxProfileVersion } from "../drivers/acpx/profile-compatibility.js"; import { isProviderMode } from "./provider-mode.js"; import { createHash } from "node:crypto"; import type { PrpStructuredRunResult, PrpTerminalState } from "../protocol/replay-contract.js"; @@ -91,7 +92,7 @@ export interface NativeAcpxProfileSnapshot { protocolVersion: 1; acpxVersion: "0.13.1"; agent: NativeAcpxAgent; - agentProfileVersion: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; + agentProfileVersion: AcpxProfileVersion; agentServerPackage: string; agentServerVersion: string; agentRuntimePackage: string | null; @@ -607,8 +608,7 @@ export function parseNativeExecutionInput(value: unknown): NativeExecutionInput || profile.protocolVersion !== 1 || profile.acpxVersion !== "0.13.1" || profile.agent !== provider.agent - || (profile.agentProfileVersion !== 1 && profile.agentProfileVersion !== 2 && profile.agentProfileVersion !== 3 && profile.agentProfileVersion !== 4 && profile.agentProfileVersion !== 5 && profile.agentProfileVersion !== 6 && profile.agentProfileVersion !== 7 && profile.agentProfileVersion !== 8 && profile.agentProfileVersion !== 9 && profile.agentProfileVersion !== 10 && profile.agentProfileVersion !== 11 && profile.agentProfileVersion !== 12) - || (provider.agent !== "cursor" && (profile.agentProfileVersion as number) > 5) + || !isSupportedAcpxProfileVersion(provider.agent, profile.agentProfileVersion) ) { throw new NativeExecutionInputError("input.provider.profile does not match the qualified ACPX v1 profile"); } diff --git a/packages/paperclip-runner/src/live/cursor-usage-notice.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-usage-notice.ts similarity index 98% rename from packages/paperclip-runner/src/live/cursor-usage-notice.ts rename to packages/paperclip-runner/src/drivers/acpx/cursor-usage-notice.ts index f31b0c301f4..a1c2e9daf63 100644 --- a/packages/paperclip-runner/src/live/cursor-usage-notice.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-usage-notice.ts @@ -1,4 +1,4 @@ -import type { CanonicalProviderEvent } from "../provider-events.js"; +import type { CanonicalProviderEvent } from "../../provider-events.js"; const SUMMARY = "Cursor reported partial native counters. These observations are not authoritative token usage or billing cost."; const PROVENANCE = "Cursor native turnEnded observations; partial, unsummed, unverified counter semantics"; diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts new file mode 100644 index 00000000000..ef5aadb6f72 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vitest"; +import { isSupportedAcpxProfileVersion } from "./profile-compatibility.js"; + +describe("historical ACPX profile decoding", () => { + it("retains each provider's existing revision boundary", () => { + expect(isSupportedAcpxProfileVersion("cursor", 12)).toBe(true); + for (const agent of ["pi", "claude", "codex", "grok", "copilot"]) { + expect(isSupportedAcpxProfileVersion(agent, 5)).toBe(true); + expect(isSupportedAcpxProfileVersion(agent, 6)).toBe(false); + } + }); + it.each([0, 13, 1.5, "11", null, undefined, NaN])("rejects invalid revisions: %s", version => { + expect(isSupportedAcpxProfileVersion("cursor", version)).toBe(false); + }); + it.each(["unknown", "toString", "__proto__"])("rejects unregistered providers: %s", agent => { + expect(isSupportedAcpxProfileVersion(agent, 1)).toBe(false); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts new file mode 100644 index 00000000000..1947960c387 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts @@ -0,0 +1,13 @@ +/** Decodable historical profile revisions, not permission to launch them. + * Exact current profile/package/digest admission is checked separately. */ +export type AcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12; +const historicalVersions: Readonly> = { + pi: [1, 2, 3, 4, 5], claude: [1, 2, 3, 4, 5], codex: [1, 2, 3, 4, 5], + grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5], + cursor: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], +}; + +export function isSupportedAcpxProfileVersion(agent: string, value: unknown): value is AcpxProfileVersion { + return Object.hasOwn(historicalVersions, agent) + && historicalVersions[agent]!.includes(value as AcpxProfileVersion); +} diff --git a/packages/paperclip-runner/src/drivers/provider-notices.test.ts b/packages/paperclip-runner/src/drivers/provider-notices.test.ts new file mode 100644 index 00000000000..db6169cd54e --- /dev/null +++ b/packages/paperclip-runner/src/drivers/provider-notices.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { normalizeProviderNotice } from "./provider-notices.js"; + +const owner = { provider: "acpx", agent: "cursor", threadId: "thread", turnId: "turn" }; +function notice() { + return { + threadId: "thread", turnId: "turn", eventType: "provider.notice.recorded", itemId: "item", + payload: { schema: "paperclip.provider.notice.v1", noticeId: "notice", severity: "info", + category: "cursor_native_usage_observed", scope: "turn", recoverable: true, userActionable: false, + summary: "Cursor reported partial native counters. These observations are not authoritative token usage or billing cost.", + details: [ + { name: "Provenance", value: "Cursor native turnEnded observations; partial, unsummed, unverified counter semantics" }, + { name: "Partial reasons", value: "native_counter_semantics_unverified" }, + { name: "Collector truncated", value: "false" }, + { name: "Native observations 1-1", value: JSON.stringify([{ invocationId: "invocation-1", role: "parent", nativeRun: 1, sequence: 1, counters: { inputTokens: 20 } }]) }, + ] }, + }; +} + +describe("provider-owned optional notice normalization", () => { + it("retains partial counters as diagnostics without promoting them into accounting", () => { + const raw = notice(), result = normalizeProviderNotice(raw, owner); + expect(result).toEqual({ eventType: raw.eventType, itemId: raw.itemId, payload: raw.payload }); + expect(result).not.toHaveProperty("costUsd"); + expect(result).not.toHaveProperty("inputTokens"); + }); + it.each([ + { ...owner, provider: "codex" }, { ...owner, agent: "claude" }, { ...owner, agent: "toString" }, + { ...owner, threadId: "other" }, { ...owner, turnId: "other" }, { ...owner, turnId: null }, + ])("rejects another owner or an unqualified adapter: %j", other => { + expect(normalizeProviderNotice(notice(), other)).toBeNull(); + }); + it("does not admit arbitrary canonical events or malformed optional diagnostics", () => { + const raw = notice(); raw.payload.category = "some_other_notice"; + expect(normalizeProviderNotice(raw, owner)).toBeNull(); + const malformed = notice(); malformed.payload.details[3]!.value = "not JSON"; + expect(normalizeProviderNotice(malformed, owner)).toBeNull(); + expect(normalizeProviderNotice({ ...notice(), eventType: "turn.completed" }, owner)).toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/provider-notices.ts b/packages/paperclip-runner/src/drivers/provider-notices.ts new file mode 100644 index 00000000000..59fd9c60e9d --- /dev/null +++ b/packages/paperclip-runner/src/drivers/provider-notices.ts @@ -0,0 +1,19 @@ +import type { CanonicalProviderEvent } from "../provider-events.js"; +import { cursorUsageNotice } from "./acpx/cursor-usage-notice.js"; + +export interface ProviderNoticeOwner { + provider?: string; + agent?: string; + threadId: string; + turnId: string | null; +} + +type NoticeAdapter = (raw: unknown, owner: ProviderNoticeOwner) => CanonicalProviderEvent | null; +const acpxNotices: Readonly> = { cursor: cursorUsageNotice }; + +/** Accept only diagnostics understood by the admitted provider adapter. + * A canonical-looking envelope is not authority to inject arbitrary events. */ +export function normalizeProviderNotice(raw: unknown, owner: ProviderNoticeOwner): CanonicalProviderEvent | null { + if (owner.provider !== "acpx" || !owner.agent || !Object.hasOwn(acpxNotices, owner.agent)) return null; + return acpxNotices[owner.agent]?.(raw, owner) ?? null; +} diff --git a/packages/paperclip-runner/src/live/live-session.ts b/packages/paperclip-runner/src/live/live-session.ts index ac5a4fb6de5..78071fd47f4 100644 --- a/packages/paperclip-runner/src/live/live-session.ts +++ b/packages/paperclip-runner/src/live/live-session.ts @@ -1,4 +1,4 @@ -import { cursorUsageNotice } from "./cursor-usage-notice.js"; +import { normalizeProviderNotice } from "../drivers/provider-notices.js"; import { liveRunResultFeedback } from "./run-result-feedback.js"; import { createHash, randomUUID } from "node:crypto"; import { resolve } from "node:path"; @@ -2759,15 +2759,14 @@ export class CapabilityLiveSession { async #handleNotification(notification: CodexRpcNotification): Promise { const params = notification.params; if (notification.method === "paperclip/canonicalProviderEvent" - && params.eventType === "provider.notice.recorded" - && record(params.payload).category === "cursor_native_usage_observed") { - const notice = cursorUsageNotice(params, { + && params.eventType === "provider.notice.recorded") { + const notice = normalizeProviderNotice(params, { provider: this.#config.provider, agent: this.#config.acpxAgent, threadId: this.#providerThreadId, turnId: this.#activeTurnId, }); if (notice && !this.#evidence.some(entry => entry.turnId === this.#activeTurnId && entry.kind === "provider_event" && entry.data.canonical === true - && record(entry.data.payload).category === "cursor_native_usage_observed")) { + && record(entry.data.payload).category === record(notice.payload).category)) { this.#appendEvidence("provider_event", this.#activeTurnId, { canonicalEventType: notice.eventType, itemId: notice.itemId, payload: notice.payload, }); diff --git a/server/src/services/native-runtime/native-cursor-permission-decline.test.ts b/server/src/services/native-runtime/native-permission-decline.test.ts similarity index 80% rename from server/src/services/native-runtime/native-cursor-permission-decline.test.ts rename to server/src/services/native-runtime/native-permission-decline.test.ts index 71113520ce7..a0161db81cf 100644 --- a/server/src/services/native-runtime/native-cursor-permission-decline.test.ts +++ b/server/src/services/native-runtime/native-permission-decline.test.ts @@ -2,8 +2,9 @@ import { describe, expect, it, vi } from "vitest"; import { PgDialect } from "drizzle-orm/pg-core"; import type { Db } from "@paperclipai/db"; import type { PrpEvent } from "../../vendor/paperclip-runner/index.js"; -import { hasCompletedCursorPermissionDecline, readCompletedCursorPermissionDecline } from "./native-cursor-permission-decline.js"; +import { hasCompletedNativePermissionDecline, readCompletedNativePermissionDecline } from "./native-permission-decline.js"; +const provider = { kind: "acpx", agent: "cursor" }; const binding = { companyId: "company", runId: "run", agentId: "agent" }; function row(seq: number, eventType: string, payload: unknown): any { const event = { schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: "run", turnId: "turn", @@ -18,8 +19,15 @@ function facts() { return { rows: [created, resolved, completed], terminal: structuredClone(completed.payload.prpEvent) as PrpEvent }; } describe("completed Cursor permission decline", () => { + it.each([ + { kind: "codex" }, { kind: "acpx", agent: "claude" }, + { kind: "acpx", agent: "unknown" }, { kind: "acpx", agent: "toString" }, + ])("does not apply an unqualified provider's recovery policy: %j", otherProvider => { + const f = facts(); + expect(hasCompletedNativePermissionDecline(f.rows, binding, f.terminal, otherProvider)).toBe(false); + }); it("fences a committed denial without treating it as semantic success or requiring provider billing", () => { - const f = facts(); expect(hasCompletedCursorPermissionDecline(f.rows, binding, f.terminal)).toBe(true); + const f = facts(); expect(hasCompletedNativePermissionDecline(f.rows, binding, f.terminal, provider)).toBe(true); }); it.each(["company", "agent", "run", "turn", "session", "source", "provider", "method", "accept", "expired", "duplicate", "order", "terminal"])("rejects %s mismatches and ambiguous proof", mutation => { const f = facts(), created = f.rows[0], resolved = f.rows[1]; @@ -36,7 +44,7 @@ describe("completed Cursor permission decline", () => { if (mutation === "duplicate") f.rows.push(structuredClone(resolved)); if (mutation === "order") resolved.seq = 4; if (mutation === "terminal") f.terminal.sourceEventId = "foreign"; - expect(hasCompletedCursorPermissionDecline(f.rows, binding, f.terminal)).toBe(false); + expect(hasCompletedNativePermissionDecline(f.rows, binding, f.terminal, provider)).toBe(false); }); }); @@ -51,7 +59,7 @@ function readerDb(rows: unknown[]) { describe("permission decline reader event budget", () => { it("scopes the database read to the terminal turn and runner before limiting events", async () => { const f = facts(), { db, query } = readerDb(f.rows); - expect(await readCompletedCursorPermissionDecline(db, binding, f.terminal)).toBe(true); + expect(await readCompletedNativePermissionDecline(db, binding, f.terminal, provider)).toBe(true); const predicate = new PgDialect().sqlToQuery(query.where.mock.calls[0]![0]); expect(predicate.sql).toContain("->'prpEvent'->>'turnId'"); expect(predicate.sql).toContain("->'prpEvent'->>'normalizedSessionId'"); @@ -62,6 +70,6 @@ describe("permission decline reader event budget", () => { }); it("fails closed if this same turn exceeds its control-event budget", async () => { const f = facts(), { db } = readerDb(Array.from({ length: 1001 }, () => f.rows[0])); - await expect(readCompletedCursorPermissionDecline(db, binding, f.terminal)).rejects.toThrow("exceeds control-event budget"); + await expect(readCompletedNativePermissionDecline(db, binding, f.terminal, provider)).rejects.toThrow("exceeds control-event budget"); }); }); diff --git a/server/src/services/native-runtime/native-cursor-permission-decline.ts b/server/src/services/native-runtime/native-permission-decline.ts similarity index 82% rename from server/src/services/native-runtime/native-cursor-permission-decline.ts rename to server/src/services/native-runtime/native-permission-decline.ts index c9036255cc5..4d279dd3d78 100644 --- a/server/src/services/native-runtime/native-cursor-permission-decline.ts +++ b/server/src/services/native-runtime/native-permission-decline.ts @@ -1,21 +1,24 @@ import { and, asc, eq, inArray, sql } from "drizzle-orm"; import { heartbeatRunEvents, type Db } from "@paperclipai/db"; import type { PrpEvent } from "../../vendor/paperclip-runner/index.js"; +import { nativeProviderLifecycle, type LifecycleRecord } from "./provider-lifecycle.js"; const record = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; type Binding = { companyId: string; runId: string; agentId: string }; const TYPES = ["runtime_request.created", "runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired", "turn.completed"]; -export class NativeCursorPermissionDeclinedError extends Error { +export class NativePermissionDeclinedError extends Error { constructor() { - super("native_finalization_missing: session returned no semantic result; Cursor permission was declined; explicit direction is required"); - this.name = "NativeCursorPermissionDeclinedError"; + super("native_finalization_missing: session returned no semantic result; provider permission was declined; explicit direction is required"); + this.name = "NativePermissionDeclinedError"; } } /** A committed user denial fences automatic disposition recovery. It does not * claim the provider received the response or prove absence of file effects. */ -export function hasCompletedCursorPermissionDecline(rows: readonly unknown[], binding: Binding, terminal: PrpEvent): boolean { +export function hasCompletedNativePermissionDecline(rows: readonly unknown[], binding: Binding, terminal: PrpEvent, provider: LifecycleRecord): boolean { + const adapter = nativeProviderLifecycle(provider); + if (!adapter) return false; if (terminal.eventType !== "turn.completed" || !terminal.turnId || !terminal.normalizedSessionId || !terminal.sourceInstanceId) return false; const selected = rows.map(record).map(row => ({ row, event: record(record(row.payload).prpEvent) })).filter(({ row, event }) => row.companyId === binding.companyId && row.agentId === binding.agentId && row.runId === binding.runId @@ -29,10 +32,9 @@ export function hasCompletedCursorPermissionDecline(rows: readonly unknown[], bi const end = terminals[0]!; return selected.some(created => { if (created.event.eventType !== "runtime_request.created") return false; - const request = record(record(created.event.payload).request), origin = record(request.origin); + const request = record(record(created.event.payload).request); if (request.type !== "permission" || request.status !== "pending" || !request.requestId || request.turnId !== terminal.turnId - || origin.provider !== "cursor" || origin.method !== "session/request_permission" - || !["acpx-runtime", "acpx-runtime-sidecar"].includes(origin.adapter)) return false; + || !adapter.isPermissionRequest(request)) return false; if (selected.filter(({ event }) => event.eventType === "runtime_request.created" && record(record(event.payload).request).requestId === request.requestId).length !== 1) return false; const outcomes = selected.filter(({ event }) => ["runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired"].includes(event.eventType) && record(event.payload).requestId === request.requestId); @@ -45,7 +47,8 @@ export function hasCompletedCursorPermissionDecline(rows: readonly unknown[], bi }); } -export async function readCompletedCursorPermissionDecline(db: Db, binding: Binding, terminal: PrpEvent) { +export async function readCompletedNativePermissionDecline(db: Db, binding: Binding, terminal: PrpEvent, provider: LifecycleRecord) { + if (!nativeProviderLifecycle(provider)) return false; const rows = await db.select().from(heartbeatRunEvents).where(and( eq(heartbeatRunEvents.companyId, binding.companyId), eq(heartbeatRunEvents.runId, binding.runId), eq(heartbeatRunEvents.agentId, binding.agentId), sql`${heartbeatRunEvents.payload}->'prpEvent'->>'turnId' = ${terminal.turnId}`, @@ -54,5 +57,5 @@ export async function readCompletedCursorPermissionDecline(db: Db, binding: Bind inArray(heartbeatRunEvents.eventType, TYPES), )).orderBy(asc(heartbeatRunEvents.seq)).limit(1001); if (rows.length > 1000) throw new Error("native_event_replay_conflict: permission recovery proof exceeds control-event budget"); - return hasCompletedCursorPermissionDecline(rows, binding, terminal); + return hasCompletedNativePermissionDecline(rows, binding, terminal, provider); } diff --git a/server/src/services/native-runtime/native-plan-wait-receipts.test.ts b/server/src/services/native-runtime/native-plan-wait-receipts.test.ts new file mode 100644 index 00000000000..2ed668603a2 --- /dev/null +++ b/server/src/services/native-runtime/native-plan-wait-receipts.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { readCommittedPlanWaitReceipt } from "./native-plan-wait-receipts.js"; + +describe("committed plan-wait receipt formats", () => { + const modern = { planWait: { schema: "paperclip.native_plan_wait.v1" }, planWaitResult: { resultId: "new" } }; + const legacy = { cursorPlanWait: { schema: "paperclip.native_cursor_plan_wait.v1" }, cursorPlanWaitResult: { resultId: "old" } }; + + it("reads each format without rewriting its source or accepted result identity", () => { + expect(readCommittedPlanWaitReceipt(modern)).toMatchObject({ source: modern.planWait, identity: modern.planWaitResult, format: { legacy: false } }); + expect(readCommittedPlanWaitReceipt(legacy)).toMatchObject({ source: legacy.cursorPlanWait, identity: legacy.cursorPlanWaitResult, format: { legacy: true } }); + expect(legacy.cursorPlanWait.schema).toBe("paperclip.native_cursor_plan_wait.v1"); + }); + + it.each([ + { ...modern, ...legacy }, { ...modern, cursorPlanWaitResult: legacy.cursorPlanWaitResult }, + { ...legacy, planWaitResult: modern.planWaitResult }, + { planWait: legacy.cursorPlanWait }, { cursorPlanWait: modern.planWait }, + { planWait: { schema: "future" } }, {}, null, + ])("rejects mixed, relabeled or unknown authority formats: %j", value => { + expect(readCommittedPlanWaitReceipt(value)).toBeNull(); + }); +}); diff --git a/server/src/services/native-runtime/native-plan-wait-receipts.ts b/server/src/services/native-runtime/native-plan-wait-receipts.ts new file mode 100644 index 00000000000..6a765adebf1 --- /dev/null +++ b/server/src/services/native-runtime/native-plan-wait-receipts.ts @@ -0,0 +1,26 @@ +/** Private persisted receipt codecs. Legacy fields are read only after the + * caller establishes an applied, company-scoped finalization; never rewritten. */ +const record = (v: unknown): Record => v && typeof v === "object" && !Array.isArray(v) ? v as Record : {}; +export const PLAN_WAIT_RECEIPT = { + schema: "paperclip.native_plan_wait.v1", prefix: "native-plan-wait:", legacy: false, +} as const; +const LEGACY_PLAN_WAIT_RECEIPT = { + schema: "paperclip.native_cursor_plan_wait.v1", prefix: "cursor-plan-wait:", legacy: true, +} as const; +export type PlanWaitReceiptFormat = typeof PLAN_WAIT_RECEIPT | typeof LEGACY_PLAN_WAIT_RECEIPT; + +export function readCommittedPlanWaitReceipt(value: unknown) { + const decision = record(value); + // Reject mixed formats rather than silently choosing an authority. + if (decision.planWait !== undefined || decision.planWaitResult !== undefined) { + if (decision.cursorPlanWait !== undefined || decision.cursorPlanWaitResult !== undefined + || record(decision.planWait).schema !== PLAN_WAIT_RECEIPT.schema) return null; + return { source: record(decision.planWait), identity: record(decision.planWaitResult), format: PLAN_WAIT_RECEIPT }; + } + if (record(decision.cursorPlanWait).schema !== LEGACY_PLAN_WAIT_RECEIPT.schema) return null; + return { source: record(decision.cursorPlanWait), identity: record(decision.cursorPlanWaitResult), format: LEGACY_PLAN_WAIT_RECEIPT }; +} + +export function isPlanWaitContinuation(value: unknown): boolean { + return typeof value === "string" && [PLAN_WAIT_RECEIPT, LEGACY_PLAN_WAIT_RECEIPT].some(format => value.startsWith(format.prefix)); +} diff --git a/server/src/services/native-runtime/native-cursor-plan-wait.test.ts b/server/src/services/native-runtime/native-plan-wait.test.ts similarity index 58% rename from server/src/services/native-runtime/native-cursor-plan-wait.test.ts rename to server/src/services/native-runtime/native-plan-wait.test.ts index d02ca7f82cd..bbb6a384891 100644 --- a/server/src/services/native-runtime/native-cursor-plan-wait.test.ts +++ b/server/src/services/native-runtime/native-plan-wait.test.ts @@ -1,12 +1,31 @@ import { describe, expect, it, vi } from "vitest"; import * as runner from "../../vendor/paperclip-runner/index.js"; +import * as lifecycle from "./provider-lifecycle.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 { hasCommittedNativeCursorPlanWait, nativeCursorPlanWaitFromFacts, type CursorPlanWaitFacts } from "./native-cursor-plan-wait.js"; +import { hasCommittedNativePlanWait, nativePlanWaitFromFacts, type PlanWaitFacts } from "./native-plan-wait.js"; -function fixture(): CursorPlanWaitFacts { +function committedDb(f: PlanWaitFacts, source: unknown, result: unknown, legacy = false) { + const sourceRecord = source as any; + const resultJson = { result, terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed", reportedWorkDisposition: "yielded" } }; + const canonicalSha256 = nativeSha256(resultJson); + const identity = { resultId: "result", resultSha256: canonicalSha256 }; + const decisionJson = legacy ? { cursorPlanWait: source, cursorPlanWaitResult: identity } : { planWait: source, planWaitResult: identity }; + const rows = [ + [{ decision: { decisionJson }, result: { id: "result", canonicalSha256, completionContractId: sourceRecord.contractId, turnId: sourceRecord.turnId, resultJson } }], + [{ run: f.run, contract: f.contract }], f.events, f.interactions, + [{ ...f.run, createdAt: new Date(0) }], [f.interactions[0]!.interaction], [], [], + ]; + return { select: () => { + const result = rows.shift(); + const query: any = { from: () => query, innerJoin: () => query, where: () => query, orderBy: () => query, limit: () => Promise.resolve(result) }; + return query; + } } as never; +} + +function fixture(): PlanWaitFacts { 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" }; @@ -34,15 +53,15 @@ function fixture(): CursorPlanWaitFacts { event(304, "turn.completed", { status: "completed", error: null }), ], interactions: [{ interaction: i, delivery: d }], - } as unknown as CursorPlanWaitFacts; + } as unknown as PlanWaitFacts; } -function editEvent(f: CursorPlanWaitFacts, index: number, edit: (e: any) => void) { +function editEvent(f: PlanWaitFacts, 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); } -function resequence(f: CursorPlanWaitFacts) { +function resequence(f: PlanWaitFacts) { f.events.forEach((row, index) => { const sourceSeq = index + 1; Object.assign(row, { seq: sourceSeq, sourceSeq, sourceEventId: `instance:${sourceSeq}` }); @@ -66,14 +85,69 @@ function withProgress(count: number) { } describe("accepted Cursor plan passive-wait authority", () => { + it("writes and replays a provider-neutral receipt while preserving its exact authority", async () => { + const f = fixture(); f.run.status = "succeeded"; + const proof = nativePlanWaitFromFacts(f)!; + expect(proof.source.schema).toBe("paperclip.native_plan_wait.v1"); + expect(proof.result.continuation!.idempotencyKey).toMatch(/^native-plan-wait:/); + expect(await hasCommittedNativePlanWait(committedDb(f, proof.source, proof.result), f.binding)).toBe(true); + const changed = structuredClone(proof.result); changed.summary = "different result"; + expect(await hasCommittedNativePlanWait(committedDb(f, proof.source, changed), f.binding)).toBe(false); + // A new receipt cannot opt into a historical admission by renaming a field. + const provider = (f.run.runnerProfileJson as any).nativeExecutionInput.provider; + provider.cursorMode = provider.mode; delete provider.mode; + expect(await hasCommittedNativePlanWait(committedDb(f, proof.source, proof.result), f.binding)).toBe(false); + }); + it("keeps lifecycle proof generic when an adapter supplies different native semantics", () => { + const f = fixture(); + const provider = (f.run.runnerProfileJson as any).nativeExecutionInput.provider; + Object.assign(provider, { kind: "test-provider", agent: "test", mode: "outline" }); + editEvent(f, 0, e => { e.payload.request.origin = { provider: "test", method: "outline/confirm" }; }); + // Unknown providers stay disabled unless the registry supplies an adapter. + expect(nativePlanWaitFromFacts(f)).toBeNull(); + const adapter: lifecycle.NativeProviderLifecycleAdapter = { + planWait: { + admits: p => p.kind === "test-provider" && p.mode === "outline", + isRequest: r => r.origin.method === "outline/confirm", + acceptedRevision: () => "outline-revision-7", + allowsLegacyUnboundTool: () => false, + }, + isPermissionRequest: () => false, + }; + const resolver = vi.spyOn(lifecycle, "nativeProviderLifecycle").mockReturnValue(adapter); + try { + expect(nativePlanWaitFromFacts(f)?.source.planRevision).toBe("outline-revision-7"); + f.interactions[0]!.delivery.acknowledgedAt = null; + expect(nativePlanWaitFromFacts(f)).toBeNull(); + } finally { resolver.mockRestore(); } + }); + it("replays only committed historical unbound-tool receipts from the exact legacy profile", async () => { + const f = fixture(); f.run.status = "succeeded"; + const proof = nativePlanWaitFromFacts(f)!; + const admission = (f.run.runnerProfileJson as any).nativeExecutionInput; + Object.assign(admission.provider.profile, { agentProfileVersion: 6, commandDigest: "sha256:377dcea64a727ce799cc112458d4b40ba4bc6574cd6c6f7233b6efd5917a6c4b" }); + admission.provider.cursorMode = "plan"; delete admission.provider.mode; + f.events = f.events.filter(e => !e.eventType.startsWith("tool.execution.")); + const payload = (type: string) => (f.events.find(e => e.eventType === type)!.payload as any).prpEvent; + const { interaction, delivery } = f.interactions[0]!; + const source = { ...proof.source, schema: "paperclip.native_cursor_plan_wait.v1", authoritySha256: nativeSha256({ admission, contract: f.contract, + created: payload("runtime_request.created"), resolved: payload("runtime_request.resolved"), terminal: payload("turn.completed"), + interaction, delivery, resolvedAt: interaction.resolvedAt!.toISOString(), acknowledgedAt: delivery.acknowledgedAt!.toISOString() }) }; + delete source.toolExecutionId; delete source.toolLifecycleSha256; + proof.result.continuation!.idempotencyKey = proof.result.continuation!.idempotencyKey.replace("native-plan-wait:", "cursor-plan-wait:"); + expect(nativePlanWaitFromFacts(f)).toBeNull(); + expect(await hasCommittedNativePlanWait(committedDb(f, source, proof.result, true), f.binding)).toBe(true); + admission.provider.profile.agentProfileVersion = 7; + expect(await hasCommittedNativePlanWait(committedDb(f, source, proof.result, true), f.binding)).toBe(false); + }); it("settles a long plan while binding every progress event into its proof", () => { const f = withProgress(2_000); - const proof = nativeCursorPlanWaitFromFacts(f); + const proof = nativePlanWaitFromFacts(f); expect(proof).not.toBeNull(); const progress = f.events[1_200]!; (progress.payload as any).prpEvent.payload.name = "updated diagnostic text"; progress.sourcePayloadSha256 = nativeSha256((progress.payload as any).prpEvent); - const changed = nativeCursorPlanWaitFromFacts(f); + const changed = nativePlanWaitFromFacts(f); expect(changed).not.toBeNull(); expect(changed!.source.toolLifecycleSha256).not.toBe(proof!.source.toolLifecycleSha256); expect(changed!.source.authoritySha256).not.toBe(proof!.source.authoritySha256); @@ -85,35 +159,36 @@ describe("accepted Cursor plan passive-wait authority", () => { if (kind === "foreign session") event.normalizedSessionId = "other"; if (kind === "late progress") { f.events.splice(1_200, 1); f.events.push(row); resequence(f); } row.sourcePayloadSha256 = kind === "tampered digest" ? "tampered" : nativeSha256(event); - expect(nativeCursorPlanWaitFromFacts(f)).toBeNull(); + expect(nativePlanWaitFromFacts(f)).toBeNull(); }); it("fails closed only at the separate progress and control-event budgets", () => { - expect(nativeCursorPlanWaitFromFacts(withProgress(20_000))).not.toBeNull(); - expect(nativeCursorPlanWaitFromFacts(withProgress(20_001))).toBeNull(); + expect(nativePlanWaitFromFacts(withProgress(20_000))).not.toBeNull(); + expect(nativePlanWaitFromFacts(withProgress(20_001))).toBeNull(); const f = withProgress(1_200); const turnStart = structuredClone(f.events[0]!); turnStart.eventType = "turn.started"; Object.assign((turnStart.payload as any).prpEvent, { eventType: "turn.started", payload: {} }); f.events.unshift(...Array.from({ length: 995 }, () => structuredClone(turnStart))); resequence(f); - expect(nativeCursorPlanWaitFromFacts(f)).not.toBeNull(); + expect(nativePlanWaitFromFacts(f)).not.toBeNull(); f.events.unshift(structuredClone(turnStart)); resequence(f); - expect(nativeCursorPlanWaitFromFacts(f)).toBeNull(); + expect(nativePlanWaitFromFacts(f)).toBeNull(); }); it("preserves an exact committed wait using the pre-release field without admitting new legacy waits", async () => { const f = fixture(); f.run.status = "succeeded"; - const proof = nativeCursorPlanWaitFromFacts(f)!; + const proof = nativePlanWaitFromFacts(f)!; const admission = (f.run.runnerProfileJson as any).nativeExecutionInput; admission.provider.cursorMode = admission.provider.mode; delete admission.provider.mode; - expect(nativeCursorPlanWaitFromFacts(f)).toBeNull(); + expect(nativePlanWaitFromFacts(f)).toBeNull(); const payload = (type: string) => (f.events.find(e => e.eventType === type)!.payload as any).prpEvent; const { interaction, delivery } = f.interactions[0]!; const toolBinding = { toolExecutionId: proof.source.toolExecutionId, toolLifecycleSha256: proof.source.toolLifecycleSha256 }; - const source = { ...proof.source, authoritySha256: nativeSha256({ admission, contract: f.contract, + const source = { ...proof.source, schema: "paperclip.native_cursor_plan_wait.v1", authoritySha256: nativeSha256({ admission, contract: f.contract, created: payload("runtime_request.created"), resolved: payload("runtime_request.resolved"), terminal: payload("turn.completed"), interaction, delivery, resolvedAt: interaction.resolvedAt!.toISOString(), acknowledgedAt: delivery.acknowledgedAt!.toISOString(), toolBinding }) }; + proof.result.continuation!.idempotencyKey = proof.result.continuation!.idempotencyKey.replace("native-plan-wait:", "cursor-plan-wait:"); const resultJson = { result: proof.result, terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed", reportedWorkDisposition: "yielded" } }; const canonicalSha256 = nativeSha256(resultJson); const db = () => { @@ -129,18 +204,18 @@ describe("accepted Cursor plan passive-wait authority", () => { return query; } } as never; }; - expect(await hasCommittedNativeCursorPlanWait(db(), f.binding)).toBe(true); + expect(await hasCommittedNativePlanWait(db(), f.binding)).toBe(true); // History is immutable: neither changing the old mode nor rewriting its // field name may preserve the original acceptance authority. admission.provider.cursorMode = "agent"; - expect(await hasCommittedNativeCursorPlanWait(db(), f.binding)).toBe(false); + expect(await hasCommittedNativePlanWait(db(), f.binding)).toBe(false); delete admission.provider.cursorMode; admission.provider.mode = "plan"; - expect(await hasCommittedNativeCursorPlanWait(db(), f.binding)).toBe(false); + expect(await hasCommittedNativePlanWait(db(), f.binding)).toBe(false); }); it("records the accepted revision and explicitly unfinished Plan-mode continuation", () => { - const value = nativeCursorPlanWaitFromFacts(fixture()); + const value = nativePlanWaitFromFacts(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"); @@ -163,7 +238,7 @@ describe("accepted Cursor plan passive-wait authority", () => { 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(); + expect(nativePlanWaitFromFacts(f)).toBeNull(); }); it("rejects an additional same-title tool while the real plan tool remains correlated", () => { const f = fixture(); @@ -173,15 +248,15 @@ describe("accepted Cursor plan passive-wait authority", () => { 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(); + expect(nativePlanWaitFromFacts(f)).toBeNull(); }); it("binds actual callback-before-tool-start order without trusting display names", () => { - const f = fixture(); const original = nativeCursorPlanWaitFromFacts(f)!; + const f = fixture(); const original = nativePlanWaitFromFacts(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)!; + const changed = nativePlanWaitFromFacts(f)!; expect(changed).not.toBeNull(); expect(changed.source.authoritySha256).not.toBe(original.source.authoritySha256); expect(changed.source.toolLifecycleSha256).not.toBe(original.source.toolLifecycleSha256); @@ -189,64 +264,64 @@ describe("accepted Cursor plan passive-wait authority", () => { it("preserves a valid v11 plan wait saved before production promotion", () => { const facts = fixture(); (facts.run.runnerProfileJson as any).nativeExecutionInput.provider.profile.qualificationStatus = "pending"; - const saved = nativeCursorPlanWaitFromFacts(facts); + const saved = nativePlanWaitFromFacts(facts); expect(saved).not.toBeNull(); expect(saved!.result.reportedWorkDisposition).toBe("yielded"); expect(saved!.result.completionClaim.objectiveSatisfied).toBe(false); }); it("does not create a new wait from an earlier profile after the catalog advances", () => { const facts = fixture(); - expect(nativeCursorPlanWaitFromFacts(facts)).not.toBeNull(); + expect(nativePlanWaitFromFacts(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(); } + try { expect(nativePlanWaitFromFacts(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); + const proof = nativePlanWaitFromFacts(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.mode = "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(); }], + ["foreign runner", (f: PlanWaitFacts) => { f.run.runnerInstanceId = "other"; }], + ["changed admission binding", (f: PlanWaitFacts) => { (f.run.runnerProfileJson as any).nativeExecutionInput.binding = { ...f.binding, runId: "other" }; }], + ["wrong company", (f: PlanWaitFacts) => { f.run.companyId = "other"; }], + ["wrong task", (f: PlanWaitFacts) => { f.run.nativeIssueId = "other"; }], + ["failed run", (f: PlanWaitFacts) => { f.run.status = "failed"; }], + ["cancelled run", (f: PlanWaitFacts) => { f.run.status = "cancelled"; }], + ["Agent mode", (f: PlanWaitFacts) => { (f.run.runnerProfileJson as any).nativeExecutionInput.provider.mode = "agent"; }], + ["stale profile", (f: PlanWaitFacts) => { (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: PlanWaitFacts) => { f.contract.policyVersion = "tampered-policy"; }], + ["changed completion authority", (f: PlanWaitFacts) => { f.contract.completionAuthority = "server_arbiter"; }], + ["changed contract hash", (f: PlanWaitFacts) => { f.contract.canonicalSha256 = "f".repeat(64); }], + ["changed contract", (f: PlanWaitFacts) => { f.contract.contractJson.revision = "new"; }], + ["unknown origin", (f: PlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.origin.provider = "acpx"; })], + ["wrong method", (f: PlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.origin.method = "cursor/ask_question"; })], + ["untrusted adapter", (f: PlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.origin.adapter = "other"; })], + ["cross turn", (f: PlanWaitFacts) => editEvent(f, 1, e => { e.turnId = "other"; })], + ["cross session", (f: PlanWaitFacts) => editEvent(f, 1, e => { e.normalizedSessionId = "other"; })], + ["native error", (f: PlanWaitFacts) => editEvent(f, 2, e => { e.payload.error = { message: "failure" }; })], + ["changed plan", (f: PlanWaitFacts) => editEvent(f, 0, e => { e.payload.request.input.description = "other"; })], + ["rejection", (f: PlanWaitFacts) => editEvent(f, 1, e => { e.payload.response.answers[`plan-${"a".repeat(64)}`].selectedOptionIds = ["reject"]; })], + ["cancellation", (f: PlanWaitFacts) => editEvent(f, 1, e => { e.payload.response.answers[`plan-${"a".repeat(64)}`].selectedOptionIds = ["cancel"]; })], + ["missing delivery", (f: PlanWaitFacts) => { f.interactions = []; }], + ["unacknowledged delivery", (f: PlanWaitFacts) => { f.interactions[0]!.delivery.acknowledgedAt = null; }], + ["fallback wake", (f: PlanWaitFacts) => { f.interactions[0]!.delivery.deliveryMode = "wake_fallback"; }], + ["wrong target", (f: PlanWaitFacts) => { f.interactions[0]!.delivery.targetRunId = "other"; }], + ["changed answer digest", (f: PlanWaitFacts) => { f.interactions[0]!.delivery.payloadSha256 = "other"; }], + ["missing resolution time", (f: PlanWaitFacts) => { f.interactions[0]!.interaction.resolvedAt = null; }], + ["agent resolved", (f: PlanWaitFacts) => { f.interactions[0]!.interaction.resolvedByAgentId = "agent"; }], + ["duplicate receipt", (f: PlanWaitFacts) => { f.events.splice(1, 0, structuredClone(f.events[0]!)); }], + ["duplicate delivery", (f: PlanWaitFacts) => { f.interactions.push(structuredClone(f.interactions[0]!)); }], + ["uncommitted event", (f: PlanWaitFacts) => { f.events[1]!.sourcePayloadSha256 = null; }], + ["changed row identity", (f: PlanWaitFacts) => { f.events[1]!.sourceEventId = "other"; }], + ["terminal before answer", (f: PlanWaitFacts) => { f.events.reverse(); }], ] as const)("rejects %s", (_name, mutate) => { - const f = fixture(); mutate(f); expect(nativeCursorPlanWaitFromFacts(f)).toBeNull(); + const f = fixture(); mutate(f); expect(nativePlanWaitFromFacts(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"]) { @@ -257,7 +332,7 @@ describe("accepted Cursor plan passive-wait authority", () => { 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(); + expect(nativePlanWaitFromFacts(f)).toBeNull(); } }); }); diff --git a/server/src/services/native-runtime/native-cursor-plan-wait.ts b/server/src/services/native-runtime/native-plan-wait.ts similarity index 79% rename from server/src/services/native-runtime/native-cursor-plan-wait.ts rename to server/src/services/native-runtime/native-plan-wait.ts index 0da1d726239..0a4e83ee5aa 100644 --- a/server/src/services/native-runtime/native-cursor-plan-wait.ts +++ b/server/src/services/native-runtime/native-plan-wait.ts @@ -6,18 +6,19 @@ import { } from "@paperclipai/db"; import type { AskUserQuestionsInteraction } from "@paperclipai/shared"; import { - parsePaperclipQuestionResponse, parsePaperclipQuestionSet, resolveQualifiedAcpxProfile, + parsePaperclipQuestionResponse, parsePaperclipQuestionSet, 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"; +import { nativeProviderLifecycle } from "./provider-lifecycle.js"; +import { PLAN_WAIT_RECEIPT, isPlanWaitContinuation, readCommittedPlanWaitReceipt, type PlanWaitReceiptFormat } from "./native-plan-wait-receipts.js"; type Binding = { companyId: string; issueId: string; runId: string; agentId: string }; const record = (v: unknown): Record => v && typeof v === "object" && !Array.isArray(v) ? v as Record : {}; 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 +// Preserve the exact historical 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"]; @@ -27,8 +28,8 @@ const MAX_CONTROL_EVENTS = 1000; const MAX_PROGRESS_EVENTS = 20_000; 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"; +export interface NativePlanWaitSource extends Binding { + schema: string; contractId: string; contractSha256: string; interactionId: string; @@ -45,7 +46,7 @@ export interface NativeCursorPlanWaitSource extends Binding { toolExecutionId?: string; toolLifecycleSha256?: string; } -export interface CursorPlanWaitFacts { +export interface PlanWaitFacts { binding: Binding; run: Pick; contract: Pick; @@ -53,36 +54,25 @@ export interface CursorPlanWaitFacts { interactions: Array<{ interaction: typeof issueThreadInteractions.$inferSelect; delivery: typeof issueQuestionResponseDeliveries.$inferSelect }>; } -function isHistoricalUnboundWait(source?: NativeCursorPlanWaitSource): boolean { - return source !== undefined && source.toolExecutionId === undefined && source.toolLifecycleSha256 === undefined; -} - -// Pre-release records used a vendor-specific field. Only a previously committed -// wait may read it; the unmodified admission remains bound to its original hash. -function isPlanMode(provider: Record, committed: boolean): boolean { - if (provider.mode !== undefined) return provider.mode === "plan" && provider.cursorMode === undefined; - return committed && provider.cursorMode === "plan"; +function isHistoricalUnboundWait(source: NativePlanWaitSource | undefined, format: PlanWaitReceiptFormat): boolean { + return format.legacy && 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); +export function nativePlanWaitFromFacts(facts: PlanWaitFacts) { + return planWaitFromFacts(facts); } -function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: NativeCursorPlanWaitSource): { source: NativeCursorPlanWaitSource; result: PrpStructuredRunResult } | null { +function planWaitFromFacts(facts: PlanWaitFacts, committedSource?: NativePlanWaitSource, format: PlanWaitReceiptFormat = PLAN_WAIT_RECEIPT): { source: NativePlanWaitSource; 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; - } + const provider = record(admission.provider); + const adapter = nativeProviderLifecycle(provider)?.planWait; + if (!adapter?.admits(provider, { committed: committedSource !== undefined, legacy: format.legacy })) 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" || !isPlanMode(provider, committedSource !== undefined) || typeof provider.model !== "string" || !provider.model.trim() || + !Object.entries(b).every(([key, value]) => record(admission.binding)[key] === value) || 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 > MAX_CONTROL_EVENTS + MAX_PROGRESS_EVENTS) return null; @@ -108,9 +98,9 @@ function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: N 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); + const created = requests.at(-1), request = record(record(created?.payload).request); 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; + !adapter.isRequest(request) || 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) { @@ -121,10 +111,10 @@ function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: N 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); + const historicalUnboundWait = isHistoricalUnboundWait(committedSource, format); let toolBinding: { toolExecutionId: string; toolLifecycleSha256: string } | undefined; if (historicalUnboundWait) { - if (profile.agentProfileVersion !== 6 || profile.commandDigest !== "sha256:377dcea64a727ce799cc112458d4b40ba4bc6574cd6c6f7233b6efd5917a6c4b") return null; + if (!adapter.allowsLegacyUnboundTool(provider)) 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; @@ -142,10 +132,9 @@ function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: N 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 planRevision = adapter.acceptedRevision(questionSet, response); + if (planRevision === null) 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]!; @@ -154,8 +143,8 @@ function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: N 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, + const source: NativePlanWaitSource = { + ...b, schema: format.schema, contractId: contract.id, contractSha256: contract.canonicalSha256, interactionId: i.id, requestId: request.requestId, planRevision, turnId: terminal.turnId, normalizedSessionId: sessionId, sourceInstanceId: terminal.sourceInstanceId, requestEventId: created.sourceEventId, resolvedEventId: resolved.sourceEventId, terminalEventId: terminal.sourceEventId, deliveryId: d.id, ...(toolBinding ?? {}), @@ -170,25 +159,25 @@ function cursorPlanWaitFromFacts(facts: CursorPlanWaitFacts, committedSource?: N 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}` }, + continuation: { kind: "response_wake", summary: SUMMARY, idempotencyKey: `${format.prefix}${created.sourceEventId}` }, }; return { source, result }; } catch { return null; } } -export function isNativeCursorPlanWaitResult(value: unknown): boolean { +export function isNativePlanWaitResult(value: unknown): boolean { const result = record(value); - return result.reportedWorkDisposition === "yielded" && typeof record(result.continuation).idempotencyKey === "string" && record(result.continuation).idempotencyKey.startsWith(PREFIX); + return result.reportedWorkDisposition === "yielded" && isPlanWaitContinuation(record(result.continuation).idempotencyKey); } /** 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); +export async function readNativePlanWait(db: Db, binding: Binding, locked = false) { + return readPlanWaitProof(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) { +async function readPlanWaitProof(db: Db, binding: Binding, locked: boolean, committedSource?: NativePlanWaitSource, format: PlanWaitReceiptFormat = PLAN_WAIT_RECEIPT) { 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))) @@ -196,9 +185,9 @@ async function readCursorPlanWaitProof(db: Db, binding: Binding, locked: boolean const [row] = await (locked ? q.for("share", { noWait: true }) : q); if (!row) return null; const provider = record(record(record(row.run.runnerProfileJson).nativeExecutionInput).provider); - if (provider.agent !== "cursor" || !isPlanMode(provider, committedSource !== undefined)) return null; - const eventTypes = isHistoricalUnboundWait(committedSource) ? LEGACY_EVENT_TYPES : EVENT_TYPES; - const eventLimit = MAX_CONTROL_EVENTS + (isHistoricalUnboundWait(committedSource) ? 0 : MAX_PROGRESS_EVENTS) + 1; + if (!nativeProviderLifecycle(provider)?.planWait.admits(provider, { committed: committedSource !== undefined, legacy: format.legacy })) return null; + const eventTypes = isHistoricalUnboundWait(committedSource, format) ? LEGACY_EVENT_TYPES : EVENT_TYPES; + const eventLimit = MAX_CONTROL_EVENTS + (isHistoricalUnboundWait(committedSource, format) ? 0 : MAX_PROGRESS_EVENTS) + 1; 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(eventLimit); const events = await (locked ? eqs.for("share", { noWait: true }) : eqs); const iq = db.select({ interaction: issueThreadInteractions, delivery: issueQuestionResponseDeliveries }).from(issueThreadInteractions) @@ -206,11 +195,11 @@ async function readCursorPlanWaitProof(db: Db, binding: Binding, locked: boolean .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); + return planWaitFromFacts({ binding, ...row, events, interactions }, committedSource, format); } /** An exact applied wait suppresses recovery, not a later independently admitted user wake. */ -export async function hasCommittedNativeCursorPlanWait(db: Db, binding: Binding): Promise { +export async function hasCommittedNativePlanWait(db: Db, binding: Binding): Promise { const [receipt] = await db.select({ decision: statusDecisions, result: nativeRunResults }) .from(nativeRunFinalizations) .innerJoin(statusDecisions, and( @@ -232,12 +221,13 @@ export async function hasCommittedNativeCursorPlanWait(db: Db, binding: Binding) .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 committed = readCommittedPlanWaitReceipt(receipt.decision.decisionJson); + if (!committed) return false; + const committedSource = committed.source as NativePlanWaitSource; + const proof = await readPlanWaitProof(db, binding, false, committedSource, committed.format); 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) || + const acceptedIdentity = committed.identity; + 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(committedSource, 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; diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 82b06d7a5ca..a98dd9ddcf6 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -1,4 +1,4 @@ -import { isNativeCursorPlanWaitResult, readNativeCursorPlanWait } from "./native-cursor-plan-wait.js"; +import { isNativePlanWaitResult, readNativePlanWait } from "./native-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"; @@ -1276,17 +1276,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 }) + const planWait = isNativePlanWaitResult(result) + ? await readNativePlanWait(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"); + if (isNativePlanWaitResult(result) && + (!planWait || nativeSha256(planWait.result) !== nativeSha256(result))) { + throw new Error("native_plan_wait_authority_lost"); } const proposedDecision = resolveNativeFinalizerStatus({ - cursorPlanWaitAuthorized: cursorPlanWait !== null, + planWaitAuthorized: planWait !== null, ...(reviewContext ? { nativeReviewOutcome: nativeReview ? nativeReview.interaction.status === "pending" ? "pending" as const : "resolved" as const : "stale" as const } : {}), @@ -1369,9 +1369,9 @@ export async function finalizeNativeRun(input: { priorStatusVersion: Number(authoritativeIssue.statusVersion), priorDecisionId: authoritativeIssue.lastStatusDecisionId, decision, - requireCursorPlanWaitSource: + requirePlanWaitSource: decision.reasonCode === "native_plan_accepted_waiting_for_continuation" - ? cursorPlanWait?.source : undefined, + ? planWait?.source : undefined, requireBoardResponseWaitSource: decision.reasonCode === "board_response_waiting" || repairBoardResponseWait ? boardResponseWait?.source diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 2fd5e2bc2d1..d410c4a6352 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -49,7 +49,7 @@ import { NativeSessionProtocolIntegrityError, } from "../../vendor/paperclip-runner/index.js"; import * as issueServiceModule from "../issues.js"; -import { NativeCursorPermissionDeclinedError } from "./native-cursor-permission-decline.js"; +import { NativePermissionDeclinedError } from "./native-permission-decline.js"; import { createNativeHarnessBackupStamp, verifyNativeHarnessBackupStamp, @@ -7424,7 +7424,7 @@ describe("native warm session supervision", () => { describe("native session bounded recovery", () => { it("blocks a denied Cursor task and gives recovery to the operator without another provider attempt", async () => { const updates: Array<{ table: unknown; values: Record }> = []; - const failure = new NativeCursorPermissionDeclinedError(); + const failure = new NativePermissionDeclinedError(); state.execute.mockReset().mockRejectedValueOnce(failure); state.upsertRecoveryAction.mockReset().mockResolvedValue({}); const updateIssue = vi.fn(async () => ({ status: "blocked", statusVersion: 7 })); @@ -7450,7 +7450,7 @@ describe("native session bounded recovery", () => { schema: "paperclip.native-cancellation.v1", ...execution.binding, scope: "run", reasonCode: "cancellation_run_only", dispatched: true, dispatchState: "acknowledged", intentAuditId: "intent", acknowledgementAuditId: "ack", } }); - throw failureKind === "permission-declined" ? new NativeCursorPermissionDeclinedError() : new Error("native_finalization_missing: session returned no semantic result"); + throw failureKind === "permission-declined" ? new NativePermissionDeclinedError() : new Error("native_finalization_missing: session returned no semantic result"); }); state.upsertRecoveryAction.mockClear(); await expect(executePaperclipNativeSession({ diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 5473f0cb12e..8a06c48645b 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -1,8 +1,9 @@ import { isProviderMode } from "../../vendor/paperclip-runner/index.js"; import { bundledRemoteProviderPackManifestPath, bundledRemoteRunnerBinary } from "../../vendor/paperclip-runner/index.js"; import { nativeRetryCancellationEligible, rethrowNativeCancellationLockConflict, assertCancellationRequest, cancellationIntentId as callerCancellationIntentId, cancellationRequestId } from "./native-cancellation-request.js"; -import { readNativeCursorPlanWait } from "./native-cursor-plan-wait.js"; -import { NativeCursorPermissionDeclinedError, readCompletedCursorPermissionDecline } from "./native-cursor-permission-decline.js"; +import { readNativePlanWait } from "./native-plan-wait.js"; +import { nativeProviderLifecycle } from "./provider-lifecycle.js"; +import { NativePermissionDeclinedError, readCompletedNativePermissionDecline } from "./native-permission-decline.js"; import { resolveAcpxQualification } from "./acpx-qualification.js"; import { readLocalAiCredentialFile } from "../local-ai-credential-file.js"; import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js"; @@ -6127,7 +6128,7 @@ export function nativeSessionFailureSourceCode( | "native_current_wake_comments_unread" | "native_current_wake_comments_changed_after_read" | "native_session_interrupted" { - if (error instanceof NativeCursorPermissionDeclinedError) return "native_permission_declined"; + if (error instanceof NativePermissionDeclinedError) return "native_permission_declined"; if (error instanceof NativeProviderTerminalFailure) { if (error.providerCode === "approval_required") return "native_provider_approval_required"; // Failed terminals retain their security meaning across the provider facade. @@ -8438,13 +8439,12 @@ 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.mode === "plan") { - const planWait = await readNativeCursorPlanWait(input.db, input.execution.binding); + if (nativeProviderLifecycle(input.execution.provider)?.planWait) { + const planWait = await readNativePlanWait(input.db, input.execution.binding); if (planWait?.source.terminalEventId === terminalEvent.sourceEventId) return planWait.result; } - if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "cursor" - && await readCompletedCursorPermissionDecline(input.db, input.execution.binding, terminalEvent)) { - throw new NativeCursorPermissionDeclinedError(); + if (await readCompletedNativePermissionDecline(input.db, input.execution.binding, terminalEvent, input.execution.provider)) { + throw new NativePermissionDeclinedError(); } const [conversation] = await input.db .select({ agentId: issues.conversationAgentId }) @@ -8752,7 +8752,7 @@ async function executePaperclipNativeSessionWithinScope( // another turn to perform completion bookkeeping. const stoppedBeforeFirstTurn = error instanceof Error && error.message === "native_session_cancelled"; if (protocolIntegrityFailure === null && error instanceof Error && - (stoppedBeforeFirstTurn || error instanceof NativeCursorPermissionDeclinedError || error.message === "native_finalization_missing: session returned no semantic result")) { + (stoppedBeforeFirstTurn || error instanceof NativePermissionDeclinedError || error.message === "native_finalization_missing: session returned no semantic result")) { const [stoppedRun] = await input.db.select().from(heartbeatRuns).where(and( eq(heartbeatRuns.id, input.execution.binding.runId), eq(heartbeatRuns.companyId, input.execution.binding.companyId), @@ -8897,7 +8897,7 @@ async function executePaperclipNativeSessionWithinScope( recoveryOwner: recoveryProjection.recoveryOwner, nextAction: sourceFailureCode === "native_permission_declined" - ? "Cursor permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." + ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." : sourceFailureCode === "native_session_cleanup_quarantined" @@ -9074,7 +9074,7 @@ async function executePaperclipNativeSessionWithinScope( }, nextAction: sourceFailureCode === "native_permission_declined" - ? "Cursor permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." + ? "Provider permission was declined. Inspect the task and give explicit direction before starting further provider work. Automatic recovery is stopped." : sourceFailureCode === "native_provider_approval_required" ? "Approval required. Review the operation and update the agent's permission setting before retrying. This runner has no interactive approval handler." : sourceFailureCode === "native_session_cleanup_quarantined" diff --git a/server/src/services/native-runtime/provider-lifecycle.ts b/server/src/services/native-runtime/provider-lifecycle.ts new file mode 100644 index 00000000000..9a25d30a749 --- /dev/null +++ b/server/src/services/native-runtime/provider-lifecycle.ts @@ -0,0 +1,24 @@ +import { cursorLifecycleAdapter } from "./providers/cursor-lifecycle.js"; + +export type LifecycleRecord = Record; + +/** Provider interpretation only. The controller independently verifies the + * committed event order, scope, delivery, tool lifecycle and receipt hashes. */ +export interface NativeProviderLifecycleAdapter { + planWait: { + admits(provider: LifecycleRecord, history: { committed: boolean; legacy: boolean }): boolean; + isRequest(request: LifecycleRecord): boolean; + acceptedRevision(questionSet: LifecycleRecord, response: LifecycleRecord): string | null; + allowsLegacyUnboundTool(provider: LifecycleRecord): boolean; + }; + isPermissionRequest(request: LifecycleRecord): boolean; +} + +const acpxAdapters: Readonly> = { + cursor: cursorLifecycleAdapter, +}; + +export function nativeProviderLifecycle(provider: LifecycleRecord): NativeProviderLifecycleAdapter | undefined { + if (provider.kind !== "acpx" || typeof provider.agent !== "string") return undefined; + return Object.hasOwn(acpxAdapters, provider.agent) ? acpxAdapters[provider.agent] : undefined; +} diff --git a/server/src/services/native-runtime/providers/cursor-lifecycle.ts b/server/src/services/native-runtime/providers/cursor-lifecycle.ts new file mode 100644 index 00000000000..29b610ae178 --- /dev/null +++ b/server/src/services/native-runtime/providers/cursor-lifecycle.ts @@ -0,0 +1,44 @@ +import { resolveQualifiedAcpxProfile } from "../../../vendor/paperclip-runner/index.js"; +import type { LifecycleRecord, NativeProviderLifecycleAdapter } from "../provider-lifecycle.js"; + +const record = (value: unknown): LifecycleRecord => value && typeof value === "object" && !Array.isArray(value) ? value : {}; +const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b); +function isOrigin(request: LifecycleRecord, method: string): boolean { + const origin = record(request.origin); + return origin.provider === "cursor" && origin.method === method + && ["acpx-runtime", "acpx-runtime-sidecar"].includes(origin.adapter); +} + +export const cursorLifecycleAdapter: NativeProviderLifecycleAdapter = { + planWait: { + admits(provider, history) { + if (provider.kind !== "acpx" || provider.agent !== "cursor" + || typeof provider.model !== "string" || !provider.model.trim()) return false; + if (provider.mode !== undefined) { + if (provider.mode !== "plan" || provider.cursorMode !== undefined) return false; + } else if (!history.committed || !history.legacy || provider.cursorMode !== "plan") return false; + // A committed receipt is replayed against its original, hashed admission. + // New waits must use the currently qualified provider profile. + if (history.committed) return true; + const profile = record(provider.profile), expected = resolveQualifiedAcpxProfile("cursor", provider.model); + return ["agent", "driverKind", "protocolVersion", "acpxVersion", "commandDigest", "agentProfileVersion", "agentServerPackage", "agentServerVersion", "agentRuntimePackage", "agentRuntimeVersion"] + .every(key => profile[key] === record(expected)[key]); + }, + isRequest: request => isOrigin(request, "cursor/create_plan"), + acceptedRevision(questionSet, response) { + const plans = questionSet.questions.filter((q: LifecycleRecord) => /^plan-[a-f0-9]{64}$/.test(q.id)); + if (plans.length !== 1) return null; + const plan = plans[0]; + if (plan.answerMode !== "single_select" || !plan.required + || !same(plan.options?.map((o: LifecycleRecord) => o.id), ["accept", "reject", "cancel"]) + || !same(response.answers[plan.id]?.selectedOptionIds, ["accept"])) return null; + return plan.id; + }, + allowsLegacyUnboundTool(provider) { + const profile = record(provider.profile); + return profile.agentProfileVersion === 6 + && profile.commandDigest === "sha256:377dcea64a727ce799cc112458d4b40ba4bc6574cd6c6f7233b6efd5917a6c4b"; + }, + }, + isPermissionRequest: request => isOrigin(request, "session/request_permission"), +}; diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 0e651f19191..f6e8f308a8d 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -108,8 +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; + /** Server-verified accepted plan request and normal provider terminal. */ + planWaitAuthorized?: boolean; boardResponseWaitAuthorized?: boolean; boardResponseWaitOrigin?: boolean; isConversation?: boolean; @@ -457,7 +457,7 @@ export function arbitrateNativeStatus(input: { }; } if ( - input.cursorPlanWaitAuthorized === true && + input.planWaitAuthorized === true && input.assessment.reportedDisposition === "yielded" && input.assessment.continuation?.kind === "response_wake" ) { diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index cf85369606f..54d3a6d0708 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -1,4 +1,4 @@ -import { readNativeCursorPlanWait, type NativeCursorPlanWaitSource } from "./native-cursor-plan-wait.js"; +import { readNativePlanWait, type NativePlanWaitSource } from "./native-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"; @@ -1536,7 +1536,7 @@ export async function commitNativeStatusDecision(input: { preMaterializedEffects?: NativeMaterializedStatusEffect[]; supersedesCommittedDecisionId?: string; requireExternalChatResponseWaitAuthorization?: { agentId: string }; - requireCursorPlanWaitSource?: NativeCursorPlanWaitSource; + requirePlanWaitSource?: NativePlanWaitSource; requireBoardResponseWaitSource?: NativeBoardResponseWaitSource; requireBoardResponseWaitOrigin?: NativeBoardResponseWaitOrigin; reviewResponsePresentation?: { @@ -1646,14 +1646,14 @@ export async function commitNativeStatusDecision(input: { const passiveBoardResponseWait = reasonCode === "board_response_waiting" || reasonCode === "board_response_wait_superseded"; - let cursorPlanWait: Awaited> = null; - let cursorPlanWaitResult: { resultId: string; resultSha256: string } | null = null; + let planWait: Awaited> = null; + let planWaitResult: { resultId: string; resultSha256: string } | null = null; if (reasonCode === "native_plan_accepted_waiting_for_continuation") { - const expected = input.requireCursorPlanWaitSource; + const expected = input.requirePlanWaitSource; 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(); + planWait = await readNativePlanWait(tx as unknown as Db, expected, true); + if (!planWait || nativeSha256(planWait.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( @@ -1661,12 +1661,12 @@ export async function commitNativeStatusDecision(input: { 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) || + if (!accepted || accepted.completionContractId !== planWait.source.contractId || accepted.turnId !== planWait.source.turnId || + nativeSha256(envelope.result) !== nativeSha256(planWait.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 }; + planWaitResult = { resultId: accepted.id, resultSha256: accepted.canonicalSha256 }; } catch (error) { if (isExternalChatWaitAuthorizationContention(error)) throw new NativeStatusRaceError(); throw error; @@ -1815,7 +1815,7 @@ export async function commitNativeStatusDecision(input: { ? { boardResponseWait: boardResponseWait.source } : {}), ...(boardResponseWaitOrigin ? { boardResponseWaitOrigin } : {}), - ...(cursorPlanWait ? { cursorPlanWait: cursorPlanWait.source, cursorPlanWaitResult } : {}), + ...(planWait ? { planWait: planWait.source, planWaitResult } : {}), priorStatusVersion: input.priorStatusVersion, projectedStatusVersion: input.decision.statusAction === "preserve" @@ -1887,10 +1887,10 @@ export async function commitNativeStatusDecision(input: { } if (!decisionRow) throw new Error("native_status_decision_not_persisted"); - if (cursorPlanWait) { + if (planWait) { await issueService(tx as unknown as Db).addComment( - input.issueId, cursorPlanWait.result.summary, - { agentId: cursorPlanWait.source.agentId, runId: input.runId }, undefined, tx, + input.issueId, planWait.result.summary, + { agentId: planWait.source.agentId, runId: input.runId }, undefined, tx, ); } if (boardResponseWait && reasonCode === "board_response_waiting") { diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 2d7f09472d2..6452529ff81 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -1,5 +1,5 @@ import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; -import { hasCommittedNativeCursorPlanWait } from "../native-runtime/native-cursor-plan-wait.js"; +import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.js"; import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared"; import { settleSlackConversation } from "../slack-conversation-lifecycle.js"; import { externalConversationStateSql } from "../slack-conversation-state.js"; @@ -1175,7 +1175,7 @@ export function recoveryService( runId: latestRun.id, agentId: latestRun.agentId, }; - if (await hasCommittedNativeCursorPlanWait(db, binding)) return true; + if (await hasCommittedNativePlanWait(db, binding)) return true; const [receipt] = await db .select({ run: heartbeatRuns, @@ -1375,7 +1375,7 @@ export function recoveryService( ) { 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; + await hasCommittedNativePlanWait(db, { companyId: issue.companyId, issueId: issue.id, runId: latestRun.id, agentId: latestRun.agentId })) return true; if ( issue.status === "in_progress" && latestRun?.status === "succeeded" &&