fix(cursor): retain mode identity and ship verified platform daemons

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-03 17:19:49 -05:00
1 parent 2be4dacc5e
commit d0b90756e3
16 files changed
+249 -10

No files matched your search

@@ -286,3 +286,40 @@ Remote Stop reached the exact pending-callback cancellation and stale-answer ref
The affected remote Stop repeat passed. Remote warm three-turn continuation and normal completion also passed with cleanup. The first remote file case verified exact bytes, successful validation, an accessible registered deliverable and final task/run success. Its overall result remains failed because the automatically generated artifact-preparation comment used the provider-selected file title, which duplicated the completion marker. The fixture now requests the actual filename as its deliverable title and reserves the marker for completion. Exact byte, validation, accessible-output and single-completion checks remain intact; only the file case is repeated before continuing.
A provider-free normal-install probe also exposed a packaging blocker: the earlier npm consumer had a macOS ARM64 daemon in the universal server package and could not launch it on Linux (exec-format exit 126). Explicit Cursor provisioning itself passed, but that does not certify the installed product. Release packaging must include verified platform-specific daemons for all three promised targets and select the correct bundled daemon without an override. This release fix and the final installed product smoke remain required.
The remote file repeat and semantic question/restart case passed with cleanup. The
next semantic-plan approval case remains failed. The controller admitted its
completion report, but returning feedback to the provider's pending semantic
tool call was rejected. Shutdown did not prove a settled provider checkpoint;
the identity fence correctly prevented recovery. The failure is retained and is
not counted as a successful planning continuation.
Evaluation also found that the shared app-server checkpoint parser discarded
Cursor's observed mode. It now preserves Agent/Plan/Ask, with round-trip and
mismatched-mode recovery tests. Missing historical mode bindings remain fenced.
Retired provider tool callbacks have a closed diagnostic category; private
provider text is never copied into error identity. Remote checkpoint failures
now distinguish unconfirmed exit, unsettled turns and mode binding through
closed categories without weakening admission.
Public release packaging now selects the daemon beside its own compiled module,
including the server's vendored layout, and verifies its actual executable
architecture. Release assembly requires one source revision and all three
independently built daemons. Run
`pnpm --filter @paperclipai/paperclip-runner stage:release-binaries /path/to/manifest.json`
with a JSON manifest containing `sourceRevision` and `platforms`, whose exact
keys are `darwin-arm64`, `darwin-x64`, and `linux-x64`; each entry contains an
absolute artifact `path` and `sha256:<64 hex digits>` digest. Assembly verifies
all inputs before staging and records source and packaged hashes in
`dist/bin/release-manifest.json`. Rebuild the server after assembly so its
vendored distribution contains the entire verified platform set. The ordinary
public-install verifier requires this manifest at the current source and checks
all three packaged identities before launching the normally resolved Linux
daemon. The actual installed task smoke remains a separate required gate.
Focused repair verification: 42 checkpoint/binary-selection tests, nine durable
provider-state tests, 43 sidecar tests, and three closed Rust diagnostic tests
passed. The first sidecar invocation timed out in the sandbox; the unrestricted
local IPC repeat passed. Runtime source changed, so the next affected live
attempt requires refreshed platform packs and Linux image identities. Existing
results retain their original runtime/controller identities.
+1
View File
@@ -61,6 +61,7 @@
"build:typescript": "pnpm run ensure:eval-build-deps && pnpm run check:protocol-types && node ./node_modules/typescript/bin/tsc --version && node ./node_modules/typescript/bin/tsc -p tsconfig.json && node ./node_modules/typescript/bin/tsc -p tsconfig.surfaces.json && node scripts/build-verified-provider-entrypoints.mjs",
"build:rust": "cargo build --manifest-path runner/Cargo.toml --locked --workspace --bins",
"build:binary": "cargo build --release --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --bin paperclip-runnerd && node scripts/stage-runner-binary.mjs",
"stage:release-binaries": "node scripts/stage-release-runner-binaries.mjs",
"build:provider-pack": "pnpm run build:typescript && node scripts/build-provider-pack.mjs",
"build:runner-binaries": "cargo build --manifest-path runner/Cargo.toml --locked --workspace --bins",
"build:browser": "vite build --config vite.config.ts",
@@ -695,6 +695,7 @@ fn response_error_classification(error: &ResponseError) -> &'static str {
"AGENT_STARTUP_FAILED.EXIT_NONZERO" => return "agent_startup_exit_nonzero",
"AGENT_STARTUP_FAILED.OTHER" => return "agent_startup_other",
"AGENT_DISCONNECTED" => return "agent_disconnected",
"ACPX_TOOL_CALL_STALE" => return "provider_tool_call_retired",
"AUTH_REQUIRED" => return "authentication_required",
"COPILOT_AUTH_REQUIRED" => return "authentication_required",
"COPILOT_POLICY_VIOLATION" => return "copilot_policy_violation",
@@ -814,6 +815,8 @@ mod tests {
#[test]
fn candidate_auth_diagnostics_use_only_closed_codes_and_never_provider_text() {
for (code, expected) in [
("ACPX_TOOL_CALL_STALE", "provider_tool_call_retired"),
("ACPX_TOOL_CALL_STALE_EXTRA", "unclassified"),
("COPILOT_AUTH_REQUIRED", "authentication_required"),
("COPILOT_ENTITLEMENT_DENIED", "provider_entitlement_denied"),
("COPILOT_MODEL_UNAVAILABLE", "requested_model_unsupported"),
@@ -0,0 +1,35 @@
// Assemble the three independently built release daemons before npm packing.
// Usage: node packages/paperclip-runner/scripts/stage-release-runner-binaries.mjs MANIFEST.json
// Manifest: {sourceRevision, platforms: {"darwin-arm64": {path, sha256}, ...}}.
import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process";
import { chmodSync, copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { runnerBinaryTarget } from "../src/live/runner-binary.ts";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const required = ["darwin-arm64", "darwin-x64", "linux-x64"];
if (process.argv.length !== 3) throw Error("Usage: stage-release-runner-binaries.mjs MANIFEST.json");
const manifest = JSON.parse(readFileSync(process.argv[2], "utf8"));
if (!/^[a-f0-9]{40}$/.test(manifest.sourceRevision) || !manifest.platforms || Object.keys(manifest.platforms).sort().join() !== [...required].sort().join()) throw Error("Release daemon manifest must bind one source and all three supported targets");
const verified = required.map(target => {
const artifact = manifest.platforms[target];
if (!artifact || !isAbsolute(artifact.path) || !/^sha256:[a-f0-9]{64}$/.test(artifact.sha256)) throw Error(`Invalid ${target} release artifact`);
const bytes = readFileSync(artifact.path), sha256 = "sha256:" + createHash("sha256").update(bytes).digest("hex");
if (sha256 !== artifact.sha256 || runnerBinaryTarget(bytes) !== target) throw Error(`Release daemon ${target} digest or architecture mismatch`);
return { target, source: artifact.path, sha256 };
});
const platforms = {};
for (const artifact of verified) {
const relative = `${artifact.target}/paperclip-runnerd`, destination = join(root, "dist", "bin", relative);
mkdirSync(dirname(destination), { recursive: true }); copyFileSync(artifact.source, destination); chmodSync(destination, 0o755);
// Copied Mach-O inodes need a fresh ad-hoc signature on macOS. Record the
// resulting packaged bytes, as well as the verified build artifact identity.
if (process.platform === "darwin" && artifact.target.startsWith("darwin-")) {
execFileSync("codesign", ["--force", "--sign", "-", destination], { stdio: "pipe" });
}
const sha256 = "sha256:" + createHash("sha256").update(readFileSync(destination)).digest("hex");
platforms[artifact.target] = { path: relative, sha256, sourceSha256: artifact.sha256 };
}
writeFileSync(join(root, "dist", "bin", "release-manifest.json"), JSON.stringify({schema:"paperclip.runner.release-binaries.v1",sourceRevision:manifest.sourceRevision,platforms},null,2)+"\n");
console.log("Staged verified release daemons for " + required.join(", "));
@@ -477,7 +477,9 @@ async function dispatch(
pending.turnId !== expectedTurnId ||
turnId !== expectedTurnId
) {
throw new Error("tool call is stale or unknown");
throw Object.assign(new Error("tool call is stale or unknown"), {
code: "ACPX_TOOL_CALL_STALE",
});
}
if (!tools.delete(callId))
throw new Error("tool call lost its settlement race");
@@ -8,6 +8,12 @@ import {
} from "./acpx-sidecar-input.js";
describe("ACPX sidecar input sequencing", () => {
it("classifies a retired tool callback without copying provider text into its identity", () => {
const error = Object.assign(new Error("private-token-canary"), { code: "ACPX_TOOL_CALL_STALE" });
expect(acpxSidecarErrorCode(error)).toBe("ACPX_TOOL_CALL_STALE");
error.code = "ACPX_TOOL_CALL_STALE_EXTRA";
expect(acpxSidecarErrorCode(error)).toBe("acpx_sidecar_command_failed");
});
it("drains initialize, session.open, and suspend in input order", async () => {
const events: string[] = [];
let pending = Promise.resolve();
@@ -163,5 +163,6 @@ const STABLE_ACPX_SIDECAR_CODES = new Set([
"ACPX_SESSION_ENSURE_TYPE_ERROR",
"ACPX_SESSION_HANDSHAKE_TIMEOUT",
"ACPX_SIDECAR_STATUS_READ_TIMEOUT",
"ACPX_TOOL_CALL_STALE",
...GENERIC_ACPX_OUTPUT_CODES,
]);
@@ -194,10 +194,11 @@ describe("Codex app-server Codex driver", () => {
},
);
it("persists and verifies the tagged runnerd provider identity on recovery", async () => {
it.each([undefined, "agent", "plan", "ask"] as const)("persists and verifies the tagged runnerd provider identity including mode %s on recovery", async (cursorMode) => {
const providerIdentity = {
kind: "acpx",
normalizedSessionId: "normalized-tagged-recovery",
...(cursorMode === undefined ? {} : { cursorMode }),
acpxRecordId: "acpx-record-1",
backendSessionId: "backend-session-1",
agentSessionId: "agent-session-1",
@@ -78,6 +78,10 @@ export function parseProviderIdentity(
"ACPX provider identity contains an invalid permission mode",
);
}
const cursorMode = identity.cursorMode;
if (cursorMode !== undefined && cursorMode !== "agent" && cursorMode !== "plan" && cursorMode !== "ask") {
throw new Error("ACPX provider identity contains an invalid Cursor mode");
}
const fenceCandidates = identity.providerLifetimeFenceCandidates;
if (
!Array.isArray(fenceCandidates) ||
@@ -103,6 +107,7 @@ export function parseProviderIdentity(
requestedModel: identity.requestedModel as string,
effectiveModel: identity.effectiveModel as string,
...(permissionMode === undefined ? {} : { permissionMode }),
...(cursorMode === undefined ? {} : { cursorMode }),
providerLifetimeFenceCandidates: fenceCandidates as [
number,
number,
@@ -0,0 +1,42 @@
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { resolvePackagedRunnerBinary, runnerBinaryTarget } from "./runner-binary.js";
const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
function header(target: string) {
const bytes = Buffer.alloc(64);
if (target.startsWith("darwin")) { bytes.writeUInt32LE(0xfeedfacf); bytes.writeUInt32LE(target.endsWith("arm64") ? 0x0100000c : 0x01000007, 4); }
else { bytes.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); bytes.writeUInt16LE(target.endsWith("arm64") ? 183 : 62, 18); }
return bytes;
}
function fixture() { const root = mkdtempSync(join(tmpdir(), "runner-platform-")); roots.push(root); return root; }
function binary(root: string, target: string | null, bytes: Buffer) {
const folder = join(root, "dist", "bin", ...(target ? [target] : [])); mkdirSync(folder, { recursive: true });
const file = join(folder, "paperclip-runnerd"); writeFileSync(file, bytes); return file;
}
describe("packaged native daemon target", () => {
it.each(["darwin-arm64", "darwin-x64", "linux-x64"])("selects %s from a universal package rather than the build-host legacy binary", target => {
const root = fixture(); binary(root, null, header("darwin-arm64"));
for (const t of ["darwin-arm64", "darwin-x64", "linux-x64"]) binary(root, t, header(t));
const [platform, architecture] = target.split("-");
expect(runnerBinaryTarget(header(target))).toBe(target);
expect(resolvePackagedRunnerBinary(join(root, "dist"), platform as NodeJS.Platform, architecture as typeof process.arch)).toBe(join(root, "dist", "bin", target, "paperclip-runnerd"));
});
it("fails an installed Linux product with a Darwin daemon instead of silently selecting it", () => {
const root = fixture(); binary(root, null, header("darwin-arm64"));
expect(() => resolvePackagedRunnerBinary(join(root, "dist"), "linux", "x64")).toThrow("runner_runtime_incompatible");
});
it("rejects a mislabeled target even when a compatible legacy executable exists", () => {
const root = fixture(); binary(root, null, header("linux-x64")); binary(root, "linux-x64", header("darwin-arm64"));
expect(() => resolvePackagedRunnerBinary(join(root, "dist"), "linux", "x64")).toThrow("runner_runtime_incompatible");
});
it("retains a matching local legacy build and permits the source-only debug fallback", () => {
const root = fixture(); expect(resolvePackagedRunnerBinary(join(root, "dist"), "linux", "x64")).toBeNull();
const legacy = binary(root, null, header("linux-x64")); expect(resolvePackagedRunnerBinary(join(root, "dist"), "linux", "x64")).toBe(legacy);
});
it("rejects malformed, truncated and unknown binary formats", () => {
for (const bytes of [Buffer.alloc(0), Buffer.alloc(64), header("linux-x64").subarray(0, 19)]) expect(runnerBinaryTarget(bytes)).toBeNull();
});
});
@@ -0,0 +1,35 @@
import { existsSync, readFileSync } from "node:fs";
import { resolve } from "node:path";
/** Native binary headers bind the packaged executable to its actual target. */
export function runnerBinaryTarget(bytes: Buffer): string | null {
if (bytes.length < 20) return null;
if (bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) && bytes[4] === 2 && bytes[5] === 1) {
const machine = bytes.readUInt16LE(18);
return machine === 62 ? "linux-x64" : machine === 183 ? "linux-arm64" : null;
}
if (bytes.readUInt32LE(0) === 0xfeedfacf) {
const cpu = bytes.readUInt32LE(4);
return cpu === 0x01000007 ? "darwin-x64" : cpu === 0x0100000c ? "darwin-arm64" : null;
}
if (bytes.length >= 64 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
const offset = bytes.readUInt32LE(60);
if (offset <= bytes.length - 6 && bytes.readUInt32LE(offset) === 0x00004550) {
const machine = bytes.readUInt16LE(offset + 4);
return machine === 0x8664 ? "win32-x64" : machine === 0xaa64 ? "win32-arm64" : null;
}
}
return null;
}
export function resolvePackagedRunnerBinary(outputRoot: string, platform = process.platform, architecture = process.arch): string | null {
const target = `${platform}-${architecture}`, executable = platform === "win32" ? "paperclip-runnerd.exe" : "paperclip-runnerd";
for (const binary of [resolve(outputRoot, "bin", target, executable), resolve(outputRoot, "bin", executable)]) {
if (!existsSync(binary)) continue;
if (runnerBinaryTarget(readFileSync(binary)) !== target) {
throw new Error(`runner_runtime_incompatible: packaged daemon does not match ${target}; install the matching Paperclip release`);
}
return binary;
}
return null;
}
@@ -77,6 +77,7 @@ import {
prepareIsolatedCodexHome,
releaseMaterializedNativeRuntimeSkills,
} from "../drivers/runtime-context-materializer.js";
import { resolvePackagedRunnerBinary } from "./runner-binary.js";
import { RUNNERD_CANONICAL_ITEM } from "../drivers/codex/codex-driver-values.js";
// URL directory conversion preserves a trailing separator while path-derived
@@ -6808,11 +6809,12 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
}
export function defaultCapabilityRunnerdBinary(): string {
const staged = resolve(
packageRoot,
`dist/bin/paperclip-runnerd${executableSuffix}`,
);
if (existsSync(staged)) return staged;
// Standalone builds use dist/live; the server vendors that compiled tree
// directly under vendor/paperclip-runner. Resolve beside our own live module.
const outputRoot = resolve(fileURLToPath(new URL("../", import.meta.url)));
const staged = resolvePackagedRunnerBinary(outputRoot)
?? resolvePackagedRunnerBinary(resolve(packageRoot, "dist"));
if (staged) return staged;
return resolve(
packageRoot,
`runner/target/debug/paperclip-runnerd${executableSuffix}`,
@@ -50,7 +50,7 @@ if (args.length === 0 || (args.length === 1 && args[0] === "--help")) {
// Never silently qualify a debug fallback or a caller-selected alternate runner.
assert.match(
runnerBinary,
/\/dist\/bin\/paperclip-runnerd$/u,
/\/dist\/bin\/(?:darwin-(?:arm64|x64)\/|linux-x64\/)?paperclip-runnerd$/u,
"normal_staged_runner_required",
);
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
+26 -1
View File
@@ -16,6 +16,10 @@ const env = { ...process.env, NODE_PATH: '', PAPERCLIP_RELEASE_REUSE_UI_DIST: '1
for (const key of Object.keys(env)) if (/^(OPENAI|ANTHROPIC|OPENROUTER|DAYTONA|XAI|GROK|CURSOR|COPILOT|GITHUB|GH)(_|$)/.test(key) || /CANDIDATE/.test(key)) delete env[key];
const run = (command, args, cwd = root) => execFileSync(command, args, { cwd, env, stdio: 'pipe', maxBuffer: 64 * 1024 * 1024 });
const sourceRevision = run('git', ['rev-parse', 'HEAD'], repo).toString().trim();
const releaseBinaries = JSON.parse(readFileSync(join(repo, 'server/dist/vendor/paperclip-runner/bin/release-manifest.json'), 'utf8'));
assert.equal(releaseBinaries.schema, 'paperclip.runner.release-binaries.v1');
assert.equal(releaseBinaries.sourceRevision, sourceRevision, 'Stage all three release daemons and rebuild the server at this source before verification');
assert.deepEqual(Object.keys(releaseBinaries.platforms).sort(), ['darwin-arm64', 'darwin-x64', 'linux-x64']);
const releaseVersion = `0.0.0-cursor-verify.${sourceRevision.slice(0, 12)}`;
const listing = run(process.execPath, [join(repo, 'scripts/release-package-map.mjs'), 'list'], repo).toString().trim().split('\n').map(line => line.split('\t'));
const packages = new Map(listing.map(([dir, name]) => [name, {dir, manifest: JSON.parse(readFileSync(join(repo, dir, 'package.json')))}]));
@@ -72,6 +76,11 @@ const setupOutput = isolated(['node','node_modules/paperclipai/dist/index.js','r
console.log(setupOutput.trim());
assert.match(setupOutput,/Verified Cursor 2026\.09\.26-dd393fe \(linux-x64\), paperclip-cursor-usage-v4/);
const probe = `import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import { defaultCapabilityRunnerdBinary } from '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/live/runnerd-codex-transport.js';
import { runnerBinaryTarget } from '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/live/runner-binary.js';
import { verifyAcpxProfileInstallation } from '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/drivers/acpx/profile-installation.js';
import { resolveQualifiedAcpxProfile } from '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/drivers/acpx/qualified-profiles.js';
const profile = resolveQualifiedAcpxProfile('cursor', 'gpt-5.6-luna[context=272k,reasoning=medium,fast=false]');
@@ -80,9 +89,25 @@ assert.equal(installation.agentServerPackageJsonPath,'/consumer/node_modules/@pa
assert.equal(installation.agentRuntimePackageJsonPath,null);
assert.equal(installation.commandDigest,profile.commandDigest);
await (await installation.openCommand()).close();
const binaryRoot = '/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/bin';
const manifest = JSON.parse(readFileSync(binaryRoot + '/release-manifest.json', 'utf8'));
assert.equal(manifest.schema, 'paperclip.runner.release-binaries.v1');
assert.deepEqual(Object.keys(manifest.platforms).sort(), ['darwin-arm64', 'darwin-x64', 'linux-x64']);
for (const [target, artifact] of Object.entries(manifest.platforms)) {
assert.equal(artifact.path, target + '/paperclip-runnerd');
const bytes = readFileSync(binaryRoot + '/' + artifact.path);
assert.equal(runnerBinaryTarget(bytes), target);
assert.equal('sha256:' + createHash('sha256').update(bytes).digest('hex'), artifact.sha256);
}
const binary = defaultCapabilityRunnerdBinary();
assert.equal(binary, binaryRoot + '/linux-x64/paperclip-runnerd');
const metadata = JSON.parse(execFileSync(binary, ['--build-metadata'], { encoding: 'utf8' }));
assert.equal(metadata.schema, 'paperclip-runner/runnerd-build-metadata/v1');
assert.equal(metadata.binaryContractVersion, 2);
console.log('All three packaged daemon identities verified; the ordinary installed resolver launched Linux x64');
console.log('Installed Cursor closure and command lease verified without credentials or candidate overrides');`;
writeFileSync(join(assets,'probe.mjs'),probe,{mode:0o644});
console.log(isolated(['node','/packages/probe.mjs']).toString().trim());
for (const name of needed) assert.equal(JSON.parse(readFileSync(join(consumer,'node_modules',name,'package.json'))).version,releaseVersion);
const report = {schema:'paperclip.cursor.public-npm-install.v1',sourceRevision,releaseVersion,consumerImage:GROK_PUBLIC_INSTALL_IMAGE,packageCount:needed.size,sourceCliManifestPreserved:readFileSync(cliManifestPath).equals(original),lifecycleScriptsEnabled:true,lifecycleSentinelVerified:true,lifecycleNetwork:'bridge',consumerLockPreserved:true,npmProvisionedCursor:false,publicSetupCommand:true,pinnedClosureVerified:true,providerCalls:0};
const report = {schema:'paperclip.cursor.public-npm-install.v1',sourceRevision,releaseVersion,consumerImage:GROK_PUBLIC_INSTALL_IMAGE,packageCount:needed.size,sourceCliManifestPreserved:readFileSync(cliManifestPath).equals(original),lifecycleScriptsEnabled:true,lifecycleSentinelVerified:true,lifecycleNetwork:'bridge',consumerLockPreserved:true,npmProvisionedCursor:false,publicSetupCommand:true,pinnedClosureVerified:true,packagedDaemonTargetsVerified:['darwin-arm64','darwin-x64','linux-x64'],releaseBinaries,ordinaryInstalledDaemonLaunched:true,providerCalls:0};
writeFileSync(join(root,'report.json'),JSON.stringify(report,null,2)+'\n'); console.log(JSON.stringify(report));
@@ -311,6 +311,7 @@ import {
verifyRemoteRunnerReattachment,
readRemoteProviderPackManifest,
providerSessionIdentityFromDurableProviderState,
durableProviderCheckpointFailureReason,
providerSessionIdentityTransitionIsAllowed,
providerPlanMarkdown,
remoteCheckpointIncompleteFailure,
@@ -1731,6 +1732,37 @@ describe("split durable provider checkpoint identity", () => {
},
}) as unknown as NativeExecutionInputV1;
it.each(["agent", "plan", "ask"] as const)("requires both persisted Cursor mode bindings for %s recovery", mode => {
const profileDigest = `sha256:${"a".repeat(64)}`;
const input = execution({ kind: "acpx", agent: "cursor", model: "explicit-model", permissionMode: "approve-all", cursorMode: mode }, "acpx_runtime");
const identity = {
kind: "acpx", normalizedSessionId: "native-session", acpxRecordId: "record",
backendSessionId: "backend", agentSessionId: "agent-session", profileDigest,
workspaceDigest: `sha256:${"b".repeat(64)}`, requestedModel: "explicit-model",
effectiveModel: "explicit-model", permissionMode: "approve-all", cursorMode: mode,
providerLifetimeFenceCandidates: [53001, 53002, 53003],
};
const state = {
schema: "paperclip.runner.acpx-provider-state.v3", lifecycle: "suspended",
activeTurnId: null, providerExitUnconfirmed: false,
descriptor: { kind: "acpx", provider: "acpx", driver: "acpx_runtime", agent: "cursor",
model: "explicit-model", commandDigest: profileDigest, normalizedSessionId: "native-session", cursorMode: mode },
identity,
};
expect(providerSessionIdentityFromDurableProviderState({ execution: input, providerState: state })).toMatchObject({ providerSessionIdentity: identity });
for (const field of ["descriptor", "identity"] as const) {
for (const wrong of [undefined, mode === "agent" ? "plan" : "agent"]) {
const changed = structuredClone(state);
(changed[field] as Record<string, unknown>).cursorMode = wrong;
expect(providerSessionIdentityFromDurableProviderState({ execution: input, providerState: changed })).toEqual({ providerSessionId: null, providerBackendSessionId: null, providerSessionIdentity: null });
expect(durableProviderCheckpointFailureReason(input, changed)).toBe("cursor_mode_binding");
}
}
const unsettled = { ...state, providerExitUnconfirmed: true, privateProviderData: "secret-canary" };
expect(providerSessionIdentityFromDurableProviderState({ execution: input, providerState: unsettled }).providerSessionIdentity).toBeNull();
expect(durableProviderCheckpointFailureReason(input, unsettled)).toBe("provider_exit_unconfirmed");
});
it("reads ACPX identity from its provider-owned state after suspension", () => {
const profileDigest = `sha256:${"a".repeat(64)}`;
const identity = {
@@ -5580,6 +5580,18 @@ function providerSessionIdentityIsPresent(value: unknown): boolean {
);
}
/** Closed diagnostic categories; durable state may contain private provider data. */
export function durableProviderCheckpointFailureReason(execution: NativeExecutionInput, providerState: unknown): string {
if (execution.provider.kind !== "acpx") return "identity_binding";
const state = record(providerState);
if (state.schema !== ACPX_PROVIDER_STATE_SCHEMA) return "state_schema";
if (state.lifecycle !== "suspended") return "provider_not_suspended";
if (state.providerExitUnconfirmed !== false) return "provider_exit_unconfirmed";
if (state.activeTurnId !== null) return "provider_turn_unsettled";
if (!acpxRecoveryCursorModeMatches(execution.provider, record(state.descriptor).cursorMode, record(state.identity).cursorMode)) return "cursor_mode_binding";
return "identity_binding";
}
// Recovery consumes observed identities; it must never apply the fresh-config
// default to a missing persisted mode or allow another provider to carry it.
function acpxRecoveryCursorModeMatches(
@@ -11646,7 +11658,7 @@ async function createRunnerdBackendWithinSessionClaim(
providerState,
});
if (!providerSessionIdentityIsPresent(providerSessionIdentity)) {
throw new Error("runner_harness_state_mismatch: provider_identity_incomplete");
throw new Error(`runner_harness_state_mismatch: provider_identity_incomplete (${durableProviderCheckpointFailureReason(input.execution, providerState)})`);
}
const previousManifest = compatibleNativeHarnessBackupManifests({
root,