Files
PaperClipAI/packages/paperclip-runner/src/contracts/native-execution.test.ts
T
170e1b0c07 feat(runner): pin Codex 0.170.0 and Agent SDK 0.3.328 so Fable 5.2 and GPT-6.2 run (#22278)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner runs Claude and Codex agents from one shared
provider pack. The pack pins an exact Claude Agent SDK (which bundles
Claude Code) and an exact Codex CLI.
> - #22222 added Claude Fable 5.2 (minimum Claude Code 2.1.321) and
GPT-6.2 Sol and Astra (minimum Codex 0.169.1). The pack still bundles
Claude Code 2.1.286 and Codex 0.160.0.
> - Because of this, Paperclip Runner stops these models with a named
version error, and native remote Codex accepts only `>=0.149.0
<0.161.0`.
> - This pull request moves the provider pack to Agent SDK 0.3.328
(Claude Code 2.1.328) and Codex 0.170.0. It moves every constant that
depends on these pins, and the remote Codex window to `<0.171.0`.
> - The benefit is that Fable 5.2 and GPT-6.2 run on Paperclip Runner
after a sandbox image with this pack is promoted.

## Linked Issues or Issue Description

Refs #22222 (adds the models and the version floors; this pull request
makes them runnable on Paperclip Runner).
Refs #18488 (moves only the Codex pin to 0.166.0 and the window to
`<0.167.0`; it is not updated since November 1 and has conflicts with
`master`).
Refs #18486 (GPT-6.1 Terra needs Codex 0.165.0; Codex 0.170.0 satisfies
it).

**Overlap with #18488.** #18488 changes the same Codex pin locations.
This pull request uses a newer pin (0.170.0) and also moves the Claude
runtime. If this pull request merges first, #18488 has no remaining
change. I did not change the #18488 branch.

## What Changed

- Claude runtime: `@anthropic-ai/claude-agent-sdk` 0.3.286 → 0.3.328
(Claude Code 2.1.286 → 2.1.328). This changes the root `pnpm.overrides`,
`pnpm-workspace.yaml`, the ACPX `claude` profile, and the qualified
Claude runtime in `installation-integrity.ts`, with new executable
digests for Linux x64, Linux ARM64, macOS ARM64, and macOS x64.
- Codex runtime: `@openai/codex` 0.160.0 → 0.170.0. This changes the
runner dependency, the `codex-acp@1.6.2>@openai/codex` override, the
`codex-acp` patch dependency line, the ACPX `codex` profile, and the
qualified Linux x64 runtime with its new executable digest.
- The ACP bridges do not change: `claude-agent-acp` 0.73.0 and the
patched `codex-acp` 1.6.2. Their `commandDigest` values and profile
versions do not change.
- Generated declarations: `generated-profiles.ts` and
`generated_acpx_profiles.rs` are regenerated with
`generate:acpx-profiles`.
- Remote native Codex window: `REMOTE_CODEX_MAXIMUM_VERSION_EXCLUSIVE`
0.161.0 → 0.171.0. The minimum stays at 0.149.0. Images with Codex
0.149.0 through 0.170.x are accepted.
- Codex company observability: the qualified-version check moves to
`codex-cli 0.170.0`. The `otel` configuration keys that Paperclip writes
(`exporter`, `trace_exporter`, `metrics_exporter`) are present in the
0.170.0 configuration schema. The `OtelExporterKind`,
`OtelHttpProtocol`, and `OtelTlsConfig` definitions are identical to
0.160.0.
- Daytona runner image probes (`Dockerfile`, `Dockerfile.release`)
expect `codex-cli 0.170.0` and `2.1.328 (Claude Code)`. The remote npm
install spec in `server/src/adapters/registry.ts` is
`@openai/codex@0.170.0`.
- Tests: fixtures and assertions that mirror the pins use the new
versions. The window tests accept 0.161.0 through 0.170.99 and reject
0.171.0. The ACPX gate tests now show that Fable 5.2 and GPT-6.2 are
admitted. A new test mocks an older bundled runtime and keeps the named
version-gap errors covered. The fallback test shows that GPT-6.2 stays
on 0.170.0 and still falls back on 0.160.0.
- Opt-in qualification scripts
(`scripts/tests/native-cleanup-paginated-codex.mjs`,
`native-provider-startup-codex.mjs`) require Codex 0.170.0.
- Documentation: `docker/daytona-runner/README.md`,
`doc/architecture/paperclip-runner-compatibility.md`,
`doc/agent-observability.md`, `docs/deploy/environment-variables.md`,
and the deferred item in `doc/adapter-model-audit-2026-11-18.md`.
- `pnpm-lock.yaml` is not part of this pull request. The refresh bot
regenerates it on `master`, as for the previous pin refreshes (#14942,
#14993).

## Verification

Sources, checked on 2026-11-19:

- npm registry: `@openai/codex@0.170.0` (published 2026-11-18T03:45Z)
and `@anthropic-ai/claude-agent-sdk@0.3.328` (published
2026-11-18T23:13Z, `claudeCodeVersion` 2.1.328). Both are the `latest`
tags.
- [Codex releases](https://github.com/openai/codex/releases) 0.161.0
through 0.170.0. The notes record no app-server protocol break. 0.169.0
keeps project configuration disabled for `codex exec` in untrusted
directories; Paperclip's CLI path already uses `--skip-git-repo-check`,
and the native path uses `app-server`.
- [Claude Code
changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md)
2.1.287 through 2.1.328. See "Risks" for the headless changes that I
reviewed.

Digests and package shape:

- I downloaded each platform archive with `npm pack`, which verifies
registry integrity, and computed the SHA-256 of the executable. As a
method check, the same command on the 0.3.286 Linux x64 archive gives
the digest that is on `master` (`fe503f65…`). The Codex 0.160.0 archive
also gives the `master` digest (`12eb3e81…`).
- The extracted executables report `codex-cli 0.170.0` and `2.1.328
(Claude Code)`.
- The Codex 0.170.0 Linux x64 archive no longer contains
`codex-resources/zsh/bin/zsh`. Paperclip does not reference that path.
- The Agent SDK 0.3.328 `optionalDependencies` have the same platform
set as 0.3.286. The Codex 0.170.0 `optionalDependencies` use the same
`npm:@openai/codex@<version>-<platform>` aliases.
- Bridge link check: I installed
`@agentclientprotocol/claude-agent-acp@0.73.0` with an override to Agent
SDK 0.3.328 and imported its entry module. Node linked all of the named
SDK imports, and the import completed.

Real Codex qualification (no model turn, no credentials):

- `PAPERCLIP_TEST_CODEX_BINARY=<installed 0.170.0 Linux x64 binary> node
--import ./server/node_modules/tsx/dist/loader.mjs
scripts/tests/native-cleanup-paginated-codex.mjs` passed: `green: true`,
with the expected red control and paginated `thread/resume` through the
real 0.170.0 `app-server`. The installed binary digest matches the
pinned digest.

Focused suites (Linux x64, Node 25.9.0, local `pnpm install
--no-frozen-lockfile`):

- `cd packages/paperclip-runner && pnpm run typecheck:typescript`
passed, including `check:acpx-profiles`.
- `npx tsc --noEmit` passed in `packages/adapters/codex-local` and
`packages/adapters/claude-local`.
- `packages/adapters/codex-local`: 625 passed.
`packages/adapters/claude-local`: 419 passed, 1 skipped.
- `node --test`: `acpx-codex-package-contract` 9 passed,
`controlled-evals/controller` 77 passed, `scripts/acpx-patch-packaging`
26 passed, `scripts/__tests__/grok-public-install-sandbox` 27 passed.
- `server`: `acpx-qualification`, `codex-runtime-compatibility`, and
`codex-model-fallback` 110 passed. `native-session-executor` 1541
passed, 1 failed. The failure (`compares export process compatibility …
db.transaction is not a function`) also fails on unchanged `master` on
this host.
- `packages/paperclip-runner` vitest (`installation-integrity`,
`qualified-profiles`, `codex-security-config`, `native-execution`,
`native-backend-factory`): 283 passed, 25 failed. All 25 failures are in
`installation-integrity.test.ts` with "ACPX provider lifetime guardian
failed to start". The same 25 tests fail on unchanged `master` on this
host (master fails 30 here).

Rust (toolchain 1.97.1 from `rust-toolchain.toml`, Linux x64):

- `cargo test -p paperclip-runner-core --lib`: 658 passed, 2 failed, 4
ignored. `warm_run_attachment_reuses_the_provider_ingress_listener` also
fails on unchanged `master` on this host.
`reaping_stops_a_dead_runners_provider_and_its_escaped_tool_job` is
flaky here: on this branch it passed 2 of 3 reruns.
- `cargo test -p paperclip-runner-core --test acpx_warm_attachment
--test native_provider_backend`: 7 and 45 passed.
- The new and changed saved-session tests pass:
`a_session_saved_by_the_previous_agent_runtime_is_refused_by_name`,
`unrestorable_saved_sessions_keep_strict_bindings_and_name_their_class`,
and `a_settled_session_saved_by_the_previous_acpx_release_continues`.
`rustfmt --check` passes.
- `server`: `native-session-resume.test.ts` and
`acpx-qualification.test.ts` 110 passed, 2 skipped. Both new resume
cases run and pass.

Not run here:

- `native-provider-startup-codex.mjs`, because it needs a compiled
`paperclip-runnerd`. The trusted CI runner workflow covers startup and
session-resume probes.
- The Docker image build and any live model turn. A live Fable 5.2 and
GPT-6.2 test follows the staging image rollout.

## Saved sessions from the previous release

This change keeps the ACPX bridge command digests and profile versions.
It changes `agentRuntimeVersion` in the `claude` and `codex` ACPX
profiles. That field is part of the saved session identity. The previous
release saved sessions with Agent SDK 0.3.286 or Codex 0.160.0. This
build refuses those saved sessions. It does not migrate them.

- **Next run (the usual case):** the saved provider descriptor names the
old runtime. `rebindNativeSessionCheckpoint` does not match it, so the
next run starts a fresh provider session in the same workspace with the
complete handoff prompt. No run fails. The earlier provider conversation
does not carry over.
- **A run in flight at the deploy (settled or mid-turn):** the runner
restore refuses the saved descriptor with the permanent class
`provider_state_incompatible`. The server reports it as
`native_provider_state_incompatible` and stops automatic retries. The
runner opens no provider and keeps the saved state bytes and the
workspace. The next run on the task starts a fresh provider session.
- **Native Codex (`codex_app_server`) and OpenCode** sessions do not
record this field, so their resume decision does not change. After a new
image is promoted, native Codex resumes a saved thread with Codex
0.170.0 instead of 0.160.0. This pull request does not test that
cross-version thread resume.

New tests:
- `acpx_provider_backend.rs`:
`a_session_saved_by_the_previous_agent_runtime_is_refused_by_name`
covers settled Claude and Codex sessions and a Claude turn interrupted
mid-run by the deploy.
`unrestorable_saved_sessions_keep_strict_bindings_and_name_their_class`
has a new `agent_runtime_release` case. Each case checks the named
class, that no provider session opens, and that the saved bytes do not
change.
- `native-session-resume.test.ts`: "a session saved by the previous
Claude or Codex ACPX runtime" checks that a same-release session
resumes, and that a session saved with Agent SDK 0.3.286 or Codex
0.160.0 starts fresh in the same workspace.

## Risks

- Medium. Every Paperclip Runner Claude and Codex run uses the new
executables. The digests, generated profiles, image probes, and window
must agree. They agree locally, and CI runs the Rust and runner suites
again.
- Claude Code 2.1.287 through 2.1.328 change some headless defaults. I
checked each one against Paperclip:
- 2.1.302: `-p` and Agent SDK sessions with no permission mode start in
`default` mode on third-party providers. Paperclip always sets a mode
(`bypassPermissions` or `default`), so this does not apply.
- 2.1.299: MCP allow rules now match only the whole server name.
Paperclip already writes `mcp__<server>__*` and exact
`mcp__paperclip__<tool>` rules.
- 2.1.302: fork subagents are on by default in `-p` and the Agent SDK,
as in the terminal. This pull request keeps the upstream default and
does not set `CLAUDE_CODE_FORK_SUBAGENT=0`. Reviewers can ask to keep
them off.
- 2.1.299 and later: stdio MCP connections negotiate MCP protocol
2026-07-28 first and fall back to the older protocol for servers that do
not answer.
- Agent SDK 0.3.328 is less than one day old. If a regression appears,
revert this pull request to return to 0.3.286 and Codex 0.160.0.
- Sandbox images built before this change still carry Codex 0.160.0 and
Claude Code 2.1.286. They stay accepted. On those images, Fable 5.2 and
GPT-6.2 keep the existing named errors and fallbacks until a new image
is promoted.
- Until the refresh bot updates `pnpm-lock.yaml` on `master`, a local
`--frozen-lockfile` install fails, as with the previous pin refreshes.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude, model ID `claude-opus-5-5`, through Claude Code with
tool use (shell, file edit, `gh`) and code execution. The context window
and reasoning mode are not reported in this session.
- The registry archives, digests, release notes, configuration schemas,
and changelog were read directly. No model output was used as a source
for those facts.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [ ] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:45:18 -08:00

940 lines
50 KiB
TypeScript

import { nativeTaskConstraints } from "../backends/runtime-context.js";
import { createHash } from "node:crypto";
import { QUALIFIED_ACPX_PROFILES } from "../drivers/acpx/qualified-profiles.js";
import { QUALIFIED_ACPX_VERSION } from "../drivers/acpx/generated-profiles.js";
import { describe, expect, it } from "vitest";
import { buildNativeModelEnvelope, parseNativeExecutionInput, NATIVE_EXECUTION_INPUT_SCHEMA, NATIVE_EXECUTION_INPUT_SCHEMA_V6, NATIVE_EXECUTION_INPUT_SCHEMA_V7, NATIVE_EXECUTION_INPUT_SCHEMA_V9, NATIVE_EXECUTION_INPUT_SCHEMA_V10, type NativeExecutionInputV1 } from "./native-execution.js";
import {
NATIVE_RUNTIME_ASSET_SCHEMA,
PAPERCLIP_EXECUTION_PROMPT,
PAPERCLIP_EXECUTION_PROMPT_REVISION,
canonicalNativeRuntimeContextDigest,
composeNativeSystemInstructions,
nativeRuntimePromptDigest,
type NativeRuntimeContextSnapshot,
} from "./runtime-context.js";
const input: NativeExecutionInputV1 = {
schema: "paperclip.native-execution-input.v1",
binding: {
companyId: "company-1",
runId: "run-1",
issueId: "issue-1",
agentId: "agent-1",
executionWorkspaceId: "workspace-1",
},
task: {
identifier: "PAP-1",
title: "Safe task",
description: null,
prompt: "# PAP-1: Safe task\n\nPlease address the latest comment.",
workMode: "standard",
},
workspace: { cwd: "/safe/workspace", repoUrl: null, repoRef: null, branchName: null },
session: {
normalizedSessionId: null,
driverKind: "codex_app_server",
protocolVersion: 1,
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
},
provider: { kind: "codex", model: null },
completionContract: {
id: "contract-1",
sha256: "abc123",
schemaVersion: "paperclip.completion-contract.v1",
contract: {
revision: "1",
objective: "Complete the safe task.",
criteria: [{ id: "objective", requirement: "The task is complete." }],
},
},
interactionResponses: [],
credentialBindings: [{
bindingId: "opaque-binding",
service: "github",
destination: "github.com",
expiresAt: null,
displayName: "GitHub",
}],
};
describe("NativeExecutionInputV1", () => {
it.each(["paperclip.native-execution-input.v3", "paperclip.native-execution-input.v4", NATIVE_EXECUTION_INPUT_SCHEMA])(
"preserves a saved %s execution through recovery parsing",
(schema) => {
const digest = "0".repeat(64);
const text = "Saved system instructions absent from the current release.";
const context = {
prompt: { revision: "saved-prompt-before-upgrade", text, digest: createHash("sha256").update(text).digest("hex") },
instructions: {
entryPath: "AGENTS.md",
bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 1, totalBytes: 42 },
},
skills: [],
mcp: { assignmentSetId: "none", digest, bindingId: null },
};
const persisted = JSON.parse(JSON.stringify({
...input,
schema,
provider: schema === "paperclip.native-execution-input.v3" ? input.provider : { ...input.provider, approvalPolicy: "never" },
executionMode: "default",
planningContext: null,
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
}));
const recovered = parseNativeExecutionInput(persisted);
if (!("runtimeContext" in recovered)) throw new Error("Expected a runtime context");
expect(recovered.runtimeContext).toEqual(persisted.runtimeContext);
expect(parseNativeExecutionInput(recovered)).toEqual(recovered);
},
);
it("parses v3 immutable runtime context without changing the model task envelope", () => {
const digest = "0".repeat(64);
const context: Omit<NativeRuntimeContextSnapshot, "aggregateDigest"> = {
prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: {
entryPath: "AGENTS.md",
bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 2, totalBytes: 42 },
},
skills: [{
key: "company/research",
runtimeName: "research",
versionId: "version-1",
bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/skills/research", fileCount: 2, totalBytes: 42 },
}],
mcp: { assignmentSetId: "sha256:test", digest, bindingId: "native-mcp:run-1" },
};
const preconfigured = {
...input, schema: "paperclip.native-execution-input.v7", homeMode: "preconfigured",
provider: { kind: "codex", model: null, approvalPolicy: "never" },
executionMode: "default", planningContext: null,
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
};
expect(parseNativeExecutionInput(preconfigured)).toMatchObject({ homeMode: "preconfigured" });
for (const agent of ["claude", "codex"]) {
expect(() => parseNativeExecutionInput({ ...preconfigured, executionMode: "plan",
provider: { kind: "acpx", agent, permissionMode: "approve-all" } })).toThrow("preconfigured ACPX read-only execution is not supported");
}
for (const permissionMode of ["approve-reads", "approve-paperclip", "deny-all"]) {
expect(() => parseNativeExecutionInput({ ...preconfigured, provider: { kind: "acpx", agent: "codex", permissionMode } })).toThrow("requires ACPX approve-all");
}
expect(() => parseNativeExecutionInput({ ...preconfigured, provider: { kind: "acpx", agent: "codex", permissionMode: "approve-all" } })).toThrow("cannot protect Runner state");
expect(buildNativeModelEnvelope(parseNativeExecutionInput(preconfigured)).schema).toBe("paperclip.native-model-envelope.v3");
expect(() => parseNativeExecutionInput({ ...preconfigured, homeMode: "other" })).toThrow("homeMode");
expect(() => parseNativeExecutionInput({ ...preconfigured, provider: { kind: "opencode", model: "provider/model", permissionMode: "allow" } })).toThrow("supports native Codex");
expect(() => parseNativeExecutionInput({ ...preconfigured, schema: "paperclip.native-execution-input.v5" })).toThrow("homeMode");
const parsed = parseNativeExecutionInput({
...input,
schema: "paperclip.native-execution-input.v3",
executionMode: "default",
planningContext: null,
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
});
expect(parsed.schema).toBe("paperclip.native-execution-input.v3");
if (!("runtimeContext" in parsed)) throw new Error("Expected a runtime context");
const envelope = buildNativeModelEnvelope(parsed);
expect(envelope.task).toEqual(buildNativeModelEnvelope(input).task);
expect(envelope.completionContract).toEqual(buildNativeModelEnvelope(input).completionContract);
expect(JSON.stringify(envelope)).not.toContain("runtimeContext");
expect(JSON.stringify(envelope)).not.toContain(PAPERCLIP_EXECUTION_PROMPT);
expect(composeNativeSystemInstructions(parsed.runtimeContext, "Follow sibling.md")).toBe(
`${PAPERCLIP_EXECUTION_PROMPT}\n\nFollow sibling.md\n\nRead-only instruction sibling root: /runtime/instructions`,
);
const agentFilesContext = {
...parsed.runtimeContext,
instructions: {
...parsed.runtimeContext.instructions,
workingCopy: { kind: "agent_files" as const, rootPath: "/runtime/current-agent-copy", entryPath: "AGENTS.md" },
},
};
const agentFilesInstructions = composeNativeSystemInstructions(agentFilesContext, "Preserve my personal notes.");
expect(agentFilesInstructions).toContain("AGENT_HOME) is /runtime/current-agent-copy.");
expect(agentFilesInstructions).toContain("its absolute path may change between turns");
expect(agentFilesInstructions).toContain("use the current $AGENT_HOME environment variable instead of an absolute agent-directory path from an earlier turn");
expect(agentFilesInstructions).toContain("All supported files and subfolders there are restored across tasks and sessions");
expect(agentFilesInstructions).toContain("Write task deliverables in the task working directory");
expect(agentFilesInstructions).toContain("Preserve my personal notes.");
expect(agentFilesInstructions).toMatch(/Read-only instruction sibling root: \/runtime\/instructions$/);
expect(composeNativeSystemInstructions(parsed.runtimeContext, "Follow sibling.md")).not.toContain("$AGENT_HOME");
expect(canonicalNativeRuntimeContextDigest({
...context,
mcp: { ...context.mcp, bindingId: "native-mcp:run-2" },
})).toBe(parsed.runtimeContext.aggregateDigest);
const current = parseNativeExecutionInput({
...parsed,
schema: "paperclip.native-execution-input.v4",
provider: { kind: "codex", model: null, approvalPolicy: "on-request" },
});
const withDelta = parseNativeExecutionInput({ ...current, continuationPrompt: '{"messages":[{"authorType":"user","body":"Just this new comment"}]}' });
// No checkpoint / failed provider recovery must retain full bootstrap input.
expect(buildNativeModelEnvelope(withDelta)).toEqual(buildNativeModelEnvelope(current));
const delta = buildNativeModelEnvelope(withDelta, { resumedSession: true });
expect(delta).toEqual({
schema: "paperclip.native-continuation.v1",
events: '{"messages":[{"authorType":"user","body":"Just this new comment"}]}',
completion: { revision: "1", criterionIds: ["objective"],
instruction: "Before ending this turn, obtain one accepted paperclip_finish or paperclip_block result. Earlier reports belong to earlier turns; a final message alone does not complete this turn." },
});
expect(JSON.stringify(delta)).not.toContain(input.task.title);
expect(JSON.stringify(delta)).not.toContain(input.completionContract.contract.objective);
expect(JSON.stringify(delta)).not.toContain("opaque-binding");
const withGuidance = parseNativeExecutionInput({ ...current, initialCommunicationGuidance: "Saved Slack instructions" });
expect(buildNativeModelEnvelope(withGuidance).task.prompt).toBe(`Saved Slack instructions\n\n${current.task.prompt}`);
// Structured question/approval resumes may use a full envelope rather than
// a delta. They still must not repeat initial communication instructions.
expect(buildNativeModelEnvelope(withGuidance, { resumedSession: true })).toEqual(buildNativeModelEnvelope(current));
expect(buildNativeModelEnvelope(parseNativeExecutionInput({ ...withGuidance, continuationPrompt: "new message" }), { resumedSession: true })).not.toHaveProperty("task");
expect(buildNativeModelEnvelope(withGuidance).task.prompt.match(/Saved Slack instructions/g)).toHaveLength(1);
expect(current).toMatchObject({
schema: "paperclip.native-execution-input.v4",
provider: { kind: "codex", approvalPolicy: "on-request" },
});
const withEffort = parseNativeExecutionInput({
...current,
schema: NATIVE_EXECUTION_INPUT_SCHEMA,
provider: { kind: "codex", model: "gpt-6-astra", approvalPolicy: "on-request", reasoningEffort: "ultra" },
});
expect(withEffort.provider).toMatchObject({ kind: "codex", reasoningEffort: "ultra" });
expect(parseNativeExecutionInput(withEffort)).toEqual(withEffort);
const disabledSearch = parseNativeExecutionInput({ ...withEffort, provider: { ...withEffort.provider, webSearch: "disabled" } });
expect(disabledSearch.provider).toHaveProperty("webSearch", "disabled");
expect(parseNativeExecutionInput(JSON.parse(JSON.stringify(disabledSearch)))).toEqual(disabledSearch);
for (const webSearch of [true, false, "live", "cached", null]) {
expect(() => parseNativeExecutionInput({ ...withEffort, provider: { ...withEffort.provider, webSearch } })).toThrow("webSearch");
}
expect(() => parseNativeExecutionInput({
...withEffort,
provider: { kind: "codex", model: "gpt-6-astra", approvalPolicy: "on-request", reasoningEffort: "impossible" },
})).toThrow("reasoningEffort");
expect(() => parseNativeExecutionInput({
...current,
provider: { kind: "codex", model: null, approvalPolicy: "on-request", reasoningEffort: "ultra" },
})).toThrow("input.provider");
expect(() => parseNativeExecutionInput({
...parsed,
schema: "paperclip.native-execution-input.v4",
provider: { kind: "codex", model: null, approvalPolicy: "sometimes" },
})).toThrow("approvalPolicy");
});
it("rejects runtime-context traversal and aggregate digest drift", () => {
const digest = "0".repeat(64);
const context = {
prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: {
entryPath: "../AGENTS.md",
bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 1, totalBytes: 1 },
},
skills: [],
mcp: { assignmentSetId: "none", digest, bindingId: null },
aggregateDigest: digest,
} as const;
expect(() => parseNativeExecutionInput({ ...input, schema: "paperclip.native-execution-input.v3", executionMode: "default", planningContext: null, runtimeContext: context })).toThrow("bundle root");
expect(() => parseNativeExecutionInput({
...input,
schema: "paperclip.native-execution-input.v3",
executionMode: "default",
planningContext: null,
runtimeContext: { ...context, instructions: { ...context.instructions, entryPath: "AGENTS.md" } },
})).toThrow("aggregateDigest");
});
it("builds a model envelope without authority or credential bindings", () => {
const parsed = parseNativeExecutionInput(input);
const model = buildNativeModelEnvelope(parsed);
const serialized = JSON.stringify(model);
expect(serialized).not.toContain("company-1");
expect(serialized).not.toContain("run-1");
expect(serialized).not.toContain("opaque-binding");
expect(model.task.title).toBe("Safe task");
expect(model.task.prompt).toContain("latest comment");
});
it("rejects unknown context or environment escape hatches", () => {
expect(() => parseNativeExecutionInput({ ...input, context: { secret: "canary" } })).toThrow(
"unknown field context",
);
expect(() => parseNativeExecutionInput({
...input,
workspace: { ...input.workspace, env: { PAPERCLIP_API_KEY: "canary" } },
})).toThrow("unknown field env");
});
it("accepts a persisted OpenCode driver/model pair and rejects mismatches", () => {
const opencode = parseNativeExecutionInput({
...input,
session: { ...input.session, driverKind: "opencode_server" },
provider: { kind: "opencode", model: "openrouter/deepseek/deepseek-v4-flash-0731" },
});
expect(opencode.provider).toEqual({
kind: "opencode",
model: "openrouter/deepseek/deepseek-v4-flash-0731",
});
expect(parseNativeExecutionInput(opencode)).toEqual(opencode);
expect(() => parseNativeExecutionInput({
...input,
session: { ...input.session, driverKind: "opencode_server" },
provider: { kind: "codex", model: null },
})).toThrow("does not match");
});
it("deserializes pre-provider Codex state as Codex", () => {
const legacy: Record<string, unknown> = { ...structuredClone(input) };
delete legacy.provider;
expect(parseNativeExecutionInput(legacy).provider).toEqual({
kind: "codex",
model: null,
});
expect(parseNativeExecutionInput(parseNativeExecutionInput(legacy))).toEqual(
parseNativeExecutionInput(legacy),
);
});
it("accepts an immutable Claude Managed Agent profile and rejects driver or beta drift", () => {
const claudeManaged = {
...input,
session: { ...input.session, driverKind: "claude_managed_agents_api" },
provider: {
kind: "claude_managed",
model: "claude-sonnet-5",
managedProfile: {
profileId: "managed-profile-1",
anthropicAgentId: "agent_01",
agentVersion: "3",
environmentId: "environment_01",
betaVersion: "managed-agents-2026-04-01",
},
maxSessionListCostUsd: 1,
},
} as const;
const parsed = parseNativeExecutionInput(claudeManaged);
expect(parsed.provider).toEqual(claudeManaged.provider);
expect(buildNativeModelEnvelope(parsed).workspace).toBeNull();
expect(() => parseNativeExecutionInput({
...claudeManaged,
session: { ...claudeManaged.session, driverKind: "codex_app_server" },
})).toThrow("does not match");
expect(() => parseNativeExecutionInput({
...claudeManaged,
provider: {
...claudeManaged.provider,
managedProfile: { ...claudeManaged.provider.managedProfile, betaVersion: "future-beta" },
},
})).toThrow("betaVersion");
});
it("accepts a closed AWS AgentCore Harness snapshot and rejects drift or unsafe limits", () => {
const awsAgentCore = {
...input,
session: { ...input.session, driverKind: "aws_agentcore_harness_api" },
provider: {
kind: "aws_agentcore",
model: "global.anthropic.claude-sonnet-4-6",
agentCoreProfile: {
profileId: "agentcore-development",
region: "us-east-1",
accountId: "123456789012",
harnessArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:harness/harness-1",
harnessVersion: "3",
endpointArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:harness-endpoint/harness-1/paperclip",
endpointQualifier: "paperclip",
agentRuntimeArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/runtime-1",
memoryArn: "arn:aws:bedrock-agentcore:us-east-1:123456789012:memory/memory-1",
memoryId: "memory-1",
invocationRoleArn: "arn:aws:iam::123456789012:role/paperclip-agentcore-runner",
contextBucket: "paperclip-agentcore-context",
contextPrefix: "paperclip/runtime",
contextKmsKeyArn: "arn:aws:kms:us-east-1:123456789012:key/test",
qualificationRevision: "aws-agentcore-harness-context-v2",
eventExpiryDays: 90,
},
maxEstimatedSessionCostUsd: 1,
invocationLimits: { maxIterations: 8, maxOutputTokens: 4096, timeoutSeconds: 300 },
},
} as const;
const parsed = parseNativeExecutionInput(awsAgentCore);
expect(parsed.provider).toEqual(awsAgentCore.provider);
expect(buildNativeModelEnvelope(parsed).workspace).toBeNull();
expect(JSON.stringify(parsed)).not.toContain("AWS_SECRET_ACCESS_KEY");
expect(() => parseNativeExecutionInput({
...awsAgentCore,
session: { ...awsAgentCore.session, driverKind: "codex_app_server" },
})).toThrow("does not match");
expect(() => parseNativeExecutionInput({
...awsAgentCore,
provider: { ...awsAgentCore.provider, invocationLimits: { ...awsAgentCore.provider.invocationLimits, maxIterations: 9 } },
})).toThrow("maxIterations");
expect(() => parseNativeExecutionInput({
...awsAgentCore,
provider: { ...awsAgentCore.provider, agentCoreProfile: { ...awsAgentCore.provider.agentCoreProfile, eventExpiryDays: 30 } },
})).toThrow("eventExpiryDays");
});
it.each([
[17, "sha256:a1d976c437cb736c9cce8ebe8b8baf59e571761a8d00e8b1885e72dd906d8f21"],
[18, "sha256:9d3e7d8269f1a0af94616552dfc69671932688b81dbbd5bab9ef356b3a9cbccb"],
] as const)("decodes a persisted Pi profile-%s run without rewriting its identity", (agentProfileVersion, commandDigest) => {
const { permissionPolicy: _permissionPolicy, ...nativeProfile } = QUALIFIED_ACPX_PROFILES.pi;
const profile = { ...nativeProfile, agentProfileVersion, commandDigest };
const persisted = { ...input, session: { ...input.session, driverKind: "acpx_runtime" },
provider: { kind: "acpx", agent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731",
piThinkingLevel: "low", permissionPolicy: "interactive", profile } };
const parsed = parseNativeExecutionInput(persisted);
expect(parsed.provider).toEqual(persisted.provider);
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
});
it.each([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] as const)("accepts only a closed ACPX profile matching the driver and agent at profile version %s", (agentProfileVersion) => {
const provider = {
kind: "acpx",
agent: "pi",
model: "openrouter/deepseek/deepseek-v4-flash-0731",
permissionPolicy: "interactive",
profile: {
driverKind: "acpx_runtime",
protocolVersion: 1,
acpxVersion: "0.22.0",
agent: "pi",
agentProfileVersion,
agentServerPackage: "pi-acp",
agentServerVersion: "0.0.33",
agentRuntimePackage: "@earendil-works/pi-coding-agent",
agentRuntimeVersion: "1.0.0",
commandDigest: "sha256:24ff73fda6e3c76ddce2d359a79f5c4b8f292eb290e4d2ab85aac94676b2c2dc",
},
} as const;
const parsed = parseNativeExecutionInput({
...input,
session: { ...input.session, driverKind: "acpx_runtime" },
provider,
});
expect(parsed.provider).toEqual({
kind: "acpx",
agent: "pi",
model: "openrouter/deepseek/deepseek-v4-flash-0731",
permissionPolicy: "interactive",
profile: provider.profile,
});
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
for (const unsupportedVersion of [0, Math.max(16, QUALIFIED_ACPX_PROFILES.pi.agentProfileVersion) + 1, 1.5, "14", null]) {
expect(() => parseNativeExecutionInput({
...input,
session: { ...input.session, driverKind: "acpx_runtime" },
provider: { ...provider, piThinkingLevel: "low", profile: { ...provider.profile, agentProfileVersion: unsupportedVersion } },
})).toThrow("qualified ACPX v1 profile");
}
expect(buildNativeModelEnvelope(parsed).workspace).toEqual({ cwd: "/safe/workspace" });
expect(() => parseNativeExecutionInput({
...input,
session: { ...input.session, driverKind: "acpx_runtime" },
provider: { ...provider, profile: { ...provider.profile, agent: "claude" } },
})).toThrow("qualified ACPX v1 profile");
expect(() => parseNativeExecutionInput({
...input,
session: { ...input.session, driverKind: "opencode_server" },
provider,
})).toThrow("does not match");
});
// Old saved inputs decode with their own digest; admission refuses them later.
it.each([
[17, `sha256:${"1".repeat(64)}`],
[91, "sha256:e4383c48ad21898dfe38609fdc8c0fa9a76dfcb8582a64b5415f107846904aa9"],
] as const)("decodes saved Copilot v%s input after the current profile advances", (version, commandDigest) => {
const { permissionPolicy, qualificationStatus: _status, ...currentProfile } = QUALIFIED_ACPX_PROFILES.copilot;
const provider = { kind: "acpx", agent: "copilot", model: "explicit-provider-model", permissionPolicy,
profile: { ...currentProfile, agentProfileVersion: version, commandDigest } };
const parsed = parseNativeExecutionInput({ ...input, session: { ...input.session, driverKind: "acpx_runtime" }, provider });
expect(parsed.provider).toEqual(provider);
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
});
it("decodes a Claude input saved under ACPX 0.13.1 as the current qualified profile", () => {
const savedProfile = {
agent: "claude",
driverKind: "acpx_runtime",
acpxVersion: "0.13.1",
commandDigest: "sha256:9d73d1f0f121fb96cc8badb28c22d5bff02d8582eb2e40360a81c189e1b9422a",
protocolVersion: 1,
agentServerPackage: "@agentclientprotocol/claude-agent-acp",
agentServerVersion: "0.73.0",
agentProfileVersion: 1,
agentRuntimePackage: "@anthropic-ai/claude-agent-sdk",
agentRuntimeVersion: "0.3.328",
};
const saved = {
...input,
session: { ...input.session, driverKind: "acpx_runtime" },
provider: {
kind: "acpx", agent: "claude", model: "claude-opus-5-5",
permissionPolicy: "interactive", profile: savedProfile,
},
};
const parsed = parseNativeExecutionInput(saved);
expect(parsed.provider).toEqual({ ...saved.provider, profile: { ...savedProfile, acpxVersion: QUALIFIED_ACPX_VERSION } });
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
for (const acpxVersion of ["0.13.0", "0.21.9", "0.23.0", "", null, 13]) {
expect(() => parseNativeExecutionInput({
...saved, provider: { ...saved.provider, profile: { ...savedProfile, acpxVersion } },
})).toThrow("qualified ACPX v1 profile");
}
});
it.each([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] as const)("decodes closed Copilot profile history at version %s without admitting a future version", (agentProfileVersion) => {
const { permissionPolicy, qualificationStatus: _qualificationStatus, ...snapshot } = QUALIFIED_ACPX_PROFILES.copilot;
const provider = {
kind: "acpx", agent: "copilot", model: "gpt-5.6-luna", permissionPolicy,
profile: { ...snapshot, agentProfileVersion },
} as const;
const value = { ...input, session: { ...input.session, driverKind: "acpx_runtime" }, provider };
const parsed = parseNativeExecutionInput(value);
expect(parsed.provider).toEqual(provider);
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
for (const unsupportedVersion of [0, QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion + 1, 1.5, "34", null]) {
expect(() => parseNativeExecutionInput({
...value, provider: { ...provider, profile: { ...provider.profile, agentProfileVersion: unsupportedVersion } },
})).toThrow("qualified ACPX v1 profile");
}
expect(() => parseNativeExecutionInput({
...value, provider: { ...provider, profile: { ...provider.profile, agent: "pi" } },
})).toThrow("qualified ACPX v1 profile");
expect(() => parseNativeExecutionInput({
...value, session: { ...value.session, driverKind: "opencode_server" },
})).toThrow("does not match");
});
it.each(Object.values(QUALIFIED_ACPX_PROFILES))(
"admits the current $agent profile through the native execution boundary",
(declaration) => {
const { permissionPolicy, qualificationStatus: _status, ...profile } = declaration;
const provider = {
kind: "acpx", agent: declaration.agent,
model: "explicit-provider-model",
permissionPolicy, profile,
...(declaration.agent === "pi" ? { piThinkingLevel: "low" } : {}),
};
const parsed = parseNativeExecutionInput({
...input,
session: { ...input.session, driverKind: "acpx_runtime" },
provider,
});
expect(parsed.provider).toEqual(provider);
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
},
);
it("defaults legacy lifecycle state to per-turn and validates warm timeouts", () => {
const legacy: Record<string, unknown> = { ...structuredClone(input) };
delete (legacy.session as Record<string, unknown>).lifecyclePolicy;
expect(parseNativeExecutionInput(legacy).session.lifecyclePolicy).toEqual({
mode: "per_turn",
idleTimeoutMs: null,
});
expect(parseNativeExecutionInput({
...input,
session: {
...input.session,
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 },
},
}).session.lifecyclePolicy).toEqual({ mode: "warm", idleTimeoutMs: 300_000 });
expect(() => parseNativeExecutionInput({
...input,
session: {
...input.session,
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 0 },
},
})).toThrow("positive integer");
expect(() => parseNativeExecutionInput({
...input,
session: {
...input.session,
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 86_400_001 },
},
})).toThrow("no greater than 86400000");
});
});
describe("NativeExecutionInputV2 planning", () => {
const planning = {
...input,
schema: "paperclip.native-execution-input.v2",
executionMode: "plan",
task: { ...input.task, workMode: "planning" },
planningContext: {
documentId: "document-1",
baseRevisionId: "revision-3",
baseRevisionNumber: 3,
markdown: "# Existing plan",
sha256: "plan-digest",
reviewContext: { threads: [{ id: "annotation-1" }] },
},
} as const;
it("round-trips native plan mode and its pinned canonical revision into model context", () => {
const parsed = parseNativeExecutionInput(planning);
expect(parsed).toMatchObject({ schema: "paperclip.native-execution-input.v2", executionMode: "plan" });
expect(buildNativeModelEnvelope(parsed)).toMatchObject({
schema: "paperclip.native-model-envelope.v2",
executionMode: "plan",
planningContext: { baseRevisionId: "revision-3", baseRevisionNumber: 3 },
});
});
it("fails closed when plan mode omits its pinned Paperclip context", () => {
expect(() => parseNativeExecutionInput({ ...planning, planningContext: null }))
.toThrow("planningContext is required");
expect(() => parseNativeExecutionInput({
...planning,
task: { ...planning.task, workMode: "standard" },
})).toThrow("requires planning work mode");
});
it("allows an accepted planning issue to continue in fresh default execution mode", () => {
expect(parseNativeExecutionInput({
...planning,
executionMode: "default",
planningContext: null,
})).toMatchObject({ task: { workMode: "planning" }, executionMode: "default" });
});
const cloudContext: Omit<NativeRuntimeContextSnapshot, "aggregateDigest"> = {
prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest: "0".repeat(64), manifestDigest: "0".repeat(64), rootPath: "/runtime/instructions", fileCount: 1, totalBytes: 1 } },
skills: [], mcp: { assignmentSetId: "none", digest: "0".repeat(64), bindingId: null },
};
const cloudPlanning = {
...planning, schema: "paperclip.native-execution-input.v5",
provider: { kind: "cursor_cloud", model: "explicit-cloud-model", cursorCloud: { schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/example/fixture" }] } },
session: { ...planning.session, driverKind: "cursor_cloud_api" },
runtimeContext: { ...cloudContext, aggregateDigest: canonicalNativeRuntimeContextDigest(cloudContext) },
} as const;
it("preserves Cursor Cloud semantic planning and its pinned revision in the model envelope", () => {
const parsed = parseNativeExecutionInput(cloudPlanning);
expect(parsed).toMatchObject({ provider: { kind: "cursor_cloud" }, task: { workMode: "planning" }, executionMode: "plan", planningContext: planning.planningContext });
expect(buildNativeModelEnvelope(parsed)).toMatchObject({ executionMode: "plan", task: { workMode: "planning" }, planningContext: planning.planningContext });
expect(parseNativeExecutionInput(JSON.parse(JSON.stringify(parsed)))).toEqual(parsed);
});
it.each([
["missing context", { planningContext: null }, "planningContext is required"],
["standard task", { task: { ...cloudPlanning.task, workMode: "standard" } }, "requires planning work mode"],
["default with context", { executionMode: "default" }, "only valid in plan execution mode"],
["warm session", { session: { ...cloudPlanning.session, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 1000 } } }, "Cursor Cloud requires"],
])("keeps Cursor Cloud planning validation closed for %s", (_name, change, error) => {
expect(() => parseNativeExecutionInput({ ...cloudPlanning, ...change })).toThrow(error as string);
});
});
describe.each(["ask", "skill_test"])("NativeExecutionInputV2 %s mode", (workMode) => {
it("round-trips the restricted mode as a default execution without planning context", () => {
const parsed = parseNativeExecutionInput({
...input,
schema: "paperclip.native-execution-input.v2",
executionMode: "default",
task: { ...input.task, workMode },
planningContext: null,
});
expect(parsed).toMatchObject({
schema: "paperclip.native-execution-input.v2",
executionMode: "default",
task: { workMode },
});
expect(buildNativeModelEnvelope(parsed)).toMatchObject({
schema: "paperclip.native-model-envelope.v2",
task: { workMode },
executionMode: "default",
planningContext: null,
});
});
it("rejects plan execution for the restricted mode", () => {
expect(() => parseNativeExecutionInput({
...input,
schema: "paperclip.native-execution-input.v2",
executionMode: "plan",
task: { ...input.task, workMode },
planningContext: {
documentId: null,
baseRevisionId: null,
baseRevisionNumber: 0,
markdown: "",
sha256: "digest",
reviewContext: {},
},
})).toThrow("plan execution mode requires planning work mode");
});
});
describe("native task context ownership", () => {
function currentInput() {
const digest = "0".repeat(64);
const context: Omit<NativeRuntimeContextSnapshot, "aggregateDigest"> = {
prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 1, totalBytes: 1 } },
skills: [],
mcp: { assignmentSetId: "none", digest, bindingId: null },
};
return parseNativeExecutionInput({
...input,
schema: NATIVE_EXECUTION_INPUT_SCHEMA,
task: { ...input.task, description: "Use $assigned-skill. Repeat this. Repeat this.", prompt: "# PAP-1\n\nIssue description:\nUse $assigned-skill. Repeat this. Repeat this." },
provider: { kind: "codex", model: null, approvalPolicy: "never" },
executionMode: "default",
planningContext: null,
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
});
}
const { permissionPolicy: _copilotPermissionPolicy, qualificationStatus: _copilotQualificationStatus,
...copilotSnapshot } = QUALIFIED_ACPX_PROFILES.copilot;
it.each([
{ driverKind: "acpx_runtime", provider: { kind: "acpx", agent: "copilot", model: "gpt-5.6-luna", permissionMode: "deny-all", profile: copilotSnapshot } },
{ driverKind: "opencode_server", provider: { kind: "opencode", model: "openrouter/deepseek/deepseek-v4-flash-0731", permissionMode: "deny" } },
{ driverKind: "acpx_runtime", provider: {
kind: "acpx", agent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731", permissionMode: "deny-all",
profile: { driverKind: "acpx_runtime", protocolVersion: 1, acpxVersion: "0.22.0", agent: "pi", agentProfileVersion: 1,
agentServerPackage: "pi-acp", agentServerVersion: "0.0.33", agentRuntimePackage: "@earendil-works/pi-coding-agent",
agentRuntimeVersion: "0.84.2", commandDigest: `sha256:${"a".repeat(64)}` },
} },
{ driverKind: "openai_dot_mcp", provider: {
kind: "openai_dot", model: null,
binding: { bindingId: "dot-binding", bindingGeneration: 1, companyId: input.binding.companyId, agentId: input.binding.agentId,
acceptByUnixMs: 1_000, expiresAtUnixMs: 2_000 },
} },
])("preserves an unregistered saved prompt for $provider.kind", ({ driverKind, provider }) => {
const current = currentInput();
if (!("runtimeContext" in current)) throw new Error("Expected a runtime context");
const text = "Saved instructions absent from the current release.";
const context = { ...current.runtimeContext,
prompt: { revision: "saved-prompt-before-upgrade", text, digest: createHash("sha256").update(text).digest("hex") } };
context.aggregateDigest = canonicalNativeRuntimeContextDigest(context);
const persisted = JSON.parse(JSON.stringify({
...current, provider, session: { ...current.session, driverKind }, runtimeContext: context,
...(provider.kind === "openai_dot" ? {
schema: NATIVE_EXECUTION_INPUT_SCHEMA_V6,
workspace: { access: "none", cwd: null, repoUrl: null, repoRef: null, branchName: null },
credentialBindings: [],
} : {}),
}));
const recovered = parseNativeExecutionInput(persisted);
if (!("runtimeContext" in recovered)) throw new Error("Expected a runtime context");
expect(recovered.runtimeContext).toEqual(context);
expect(recovered.provider).toEqual(provider);
expect(recovered.session.driverKind).toBe(driverKind);
expect(parseNativeExecutionInput(recovered)).toEqual(recovered);
});
it("carries an opaque provider mode without a vendor restriction and fences obsolete field names", () => {
const current = currentInput();
const provider = {
kind: "acpx", agent: "codex", model: "gpt-5.6-sol", permissionMode: "approve-all", mode: "architect",
profile: { driverKind: "acpx_runtime", protocolVersion: 1, acpxVersion: "0.22.0", agent: "codex", agentProfileVersion: 3,
agentServerPackage: "@agentclientprotocol/codex-acp", agentServerVersion: "1.6.2",
agentRuntimePackage: "@openai/codex", agentRuntimeVersion: "0.170.0", commandDigest: `sha256:${"a".repeat(64)}` },
};
const value = { ...current, session: { ...current.session, driverKind: "acpx_runtime" }, provider };
const parsed = parseNativeExecutionInput(value);
expect(parsed.provider).toMatchObject({ agent: "codex", mode: "architect" });
expect(parseNativeExecutionInput(parsed)).toEqual(parsed);
expect(JSON.stringify(buildNativeModelEnvelope(parsed))).not.toContain("architect");
for (const mode of [null, 1, "", " ", "x".repeat(241), "plan\0", "plan\n"]) {
expect(() => parseNativeExecutionInput({ ...value, provider: { ...provider, mode } })).toThrow(/provider.mode/);
}
const { mode: _mode, ...withoutMode } = provider;
expect(() => parseNativeExecutionInput({ ...value, provider: { ...withoutMode, cursorMode: "plan" } })).toThrow(/input.provider/);
});
it.each([
["v4", "paperclip.native-execution-input.v4", "paperclip.native-model-envelope.v2"],
["v5", NATIVE_EXECUTION_INPUT_SCHEMA, "paperclip.native-model-envelope.v3"],
] as const)("applies communication guidance once for fresh %s input and never on resume", (_label, schema, envelopeSchema) => {
const guidance = "Saved Slack instructions";
const v5 = currentInput();
const source = {
kind: "description" as const,
id: v5.binding.issueId,
revision: createHash("sha256").update(v5.task.description!).digest("hex"),
};
const contract = {
...v5.completionContract.contract,
criteria: [{ id: "objective", requirement: v5.task.description! }],
};
const parsed = parseNativeExecutionInput({
...v5,
schema,
initialCommunicationGuidance: guidance,
...(schema === NATIVE_EXECUTION_INPUT_SCHEMA ? {
completionContract: { ...v5.completionContract, contract },
completionSources: {
promptSha256: createHash("sha256").update(v5.task.prompt).digest("hex"),
contractRevision: contract.revision,
criteria: [{ id: "objective", source }],
},
} : {}),
});
const fresh = buildNativeModelEnvelope(parsed);
expect(fresh.schema).toBe(envelopeSchema);
expect(fresh.task.prompt).toBe(`${guidance}\n\n${parsed.task.prompt}`);
expect(fresh.task.prompt.match(/Saved Slack instructions/g)).toHaveLength(1);
if (schema === NATIVE_EXECUTION_INPUT_SCHEMA) {
expect(fresh.task).not.toHaveProperty("description");
expect(fresh.completionContract.criteria).toEqual([
{ id: "objective", source: { ...source, location: "task.prompt" } },
]);
} else {
expect(fresh.task).toHaveProperty("description", parsed.task.description);
}
const fullResume = buildNativeModelEnvelope(parsed, { resumedSession: true });
expect(fullResume.schema).toBe(envelopeSchema);
if (!("task" in fullResume)) throw new Error("Expected a full resume envelope");
expect(fullResume.task.prompt).toBe(parsed.task.prompt);
expect(fullResume.task.prompt).not.toContain(guidance);
const compactResume = buildNativeModelEnvelope(
parseNativeExecutionInput({ ...parsed, continuationPrompt: "new message" }),
{ resumedSession: true },
);
expect(compactResume).toMatchObject({ schema: "paperclip.native-continuation.v1" });
expect(JSON.stringify(compactResume)).not.toContain(guidance);
});
it("selects model fields without losing the internal skill-selection description", () => {
const execution = currentInput();
const envelope = buildNativeModelEnvelope(execution);
expect(envelope.task).toEqual({
identifier: execution.task.identifier,
title: execution.task.title,
prompt: execution.task.prompt,
workMode: execution.task.workMode,
});
expect(execution.task.description).toBe("Use $assigned-skill. Repeat this. Repeat this.");
expect(envelope.task.prompt).toContain("Repeat this. Repeat this.");
expect(envelope.completionContract).toEqual(execution.completionContract.contract);
});
it("references only verified criterion sources and preserves independent requirements", () => {
const execution = currentInput();
const source = { kind: "description", id: execution.binding.issueId, revision: createHash("sha256").update(execution.task.description!).digest("hex") };
const contract = { ...execution.completionContract.contract, criteria: [
{ id: "objective", requirement: execution.task.description! },
{ id: "independent", requirement: "Also report a measured result." },
] };
const completeInput = parseNativeExecutionInput({
...execution,
completionContract: { ...execution.completionContract, contract },
completionSources: { promptSha256: createHash("sha256").update(execution.task.prompt).digest("hex"), contractRevision: contract.revision, criteria: [{ id: "objective", source }] },
});
if (completeInput.schema !== NATIVE_EXECUTION_INPUT_SCHEMA) throw new Error("Expected a v5 execution input");
const before = structuredClone(completeInput.completionContract);
const envelope = buildNativeModelEnvelope(completeInput);
expect(envelope.completionContract.criteria).toEqual([
{ id: "objective", source: { ...source, location: "task.prompt" } },
{ id: "independent", requirement: "Also report a measured result." },
]);
expect(completeInput.completionContract).toEqual(before);
// A different prompt or contract revision invalidates the projection, never the saved contract.
for (const stale of [
{ ...completeInput, task: { ...completeInput.task, prompt: "Recovery without the original brief" } },
{ ...completeInput, completionContract: { ...completeInput.completionContract, contract: { ...contract, revision: "new" } } },
]) {
expect(buildNativeModelEnvelope(stale).completionContract).toEqual(stale.completionContract.contract);
}
});
});
describe("Claude effort input v9", () => {
const { permissionPolicy: _permission, ...profile } = QUALIFIED_ACPX_PROFILES.claude;
const digest = "0".repeat(64);
const context = { prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 1, totalBytes: 1 } },
skills: [], mcp: { assignmentSetId: "none", digest, bindingId: null } };
const current = { ...input, schema: NATIVE_EXECUTION_INPUT_SCHEMA_V9, homeMode: "isolated", executionMode: "default", planningContext: null,
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
session: { ...input.session, driverKind: "acpx_runtime" },
provider: { kind: "acpx", agent: "claude", model: "claude-opus-5-5", permissionMode: "approve-all", profile } };
it.each(["low", "medium", "high", "xhigh", "max"])("round trips explicit %s and retains the compact model envelope", claudeEffort => {
const parsed = parseNativeExecutionInput({ ...current, provider: { ...current.provider, claudeEffort } });
expect(parsed).toMatchObject({ schema: NATIVE_EXECUTION_INPUT_SCHEMA_V9, provider: { claudeEffort } });
expect(buildNativeModelEnvelope(parsed).schema).toBe("paperclip.native-model-envelope.v3");
expect(JSON.stringify(buildNativeModelEnvelope(parsed))).not.toContain("claudeEffort");
});
it("directs answered Claude v9 questions to the actual compact envelope on fresh and resumed turns", () => {
const response = { interactionId: "answer-1", kind: "ask_user_questions", response: {
status: "answered", result: { version: 1, answers: [{ questionId: "destination", optionIds: ["workspace"], otherText: "Use the task workspace." }] },
} };
const parsed = parseNativeExecutionInput({ ...current, provider: { ...current.provider, claudeEffort: "high" }, interactionResponses: [response] });
const constraint = nativeTaskConstraints(parsed).find(value => value.includes("already authoritatively answered"));
expect(constraint).toContain("interactionResponses[0].response.result.answers");
expect(constraint).not.toContain("message.interactionResponses");
expect(constraint).not.toContain("Use the task workspace.");
for (const envelope of [buildNativeModelEnvelope(parsed), buildNativeModelEnvelope(parsed, { resumedSession: true })]) {
expect(envelope).toHaveProperty("interactionResponses.0.response.result.answers", response.response.result.answers);
expect(envelope).not.toHaveProperty("message");
}
});
it("keeps historical readers closed and rejects aliases and foreign effort", () => {
const { homeMode: _homeMode, ...historical } = current;
for (const schema of ["paperclip.native-execution-input.v4", NATIVE_EXECUTION_INPUT_SCHEMA]) {
expect(() => parseNativeExecutionInput({ ...historical, schema, provider: { ...current.provider, claudeEffort: "high" } })).toThrow("claudeEffort");
expect(parseNativeExecutionInput({ ...historical, schema }).schema).toBe(schema);
}
expect(() => parseNativeExecutionInput({ ...current, provider: { ...current.provider, claudeEffort: "ultra" } })).toThrow("Claude effort");
expect(() => parseNativeExecutionInput({ ...current, provider: { ...current.provider, agent: "codex", profile: QUALIFIED_ACPX_PROFILES.codex, claudeEffort: "high" } })).toThrow("Claude effort");
});
});
describe("Grok effort input v10", () => {
const { permissionPolicy: _permission, ...profile } = QUALIFIED_ACPX_PROFILES.grok;
const digest = "0".repeat(64);
const context = { prompt: { revision: PAPERCLIP_EXECUTION_PROMPT_REVISION, text: PAPERCLIP_EXECUTION_PROMPT, digest: nativeRuntimePromptDigest() },
instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA, digest, manifestDigest: digest, rootPath: "/runtime/instructions", fileCount: 1, totalBytes: 1 } },
skills: [], mcp: { assignmentSetId: "none", digest, bindingId: null } };
const current = { ...input, schema: NATIVE_EXECUTION_INPUT_SCHEMA_V10, homeMode: "isolated", executionMode: "default", planningContext: null,
runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) },
session: { ...input.session, driverKind: "acpx_runtime" },
provider: { kind: "acpx", agent: "grok", model: "grok-4.7", permissionMode: "approve-all", profile } };
it.each([undefined, true, false])("round trips Grok search policy %s and rejects it on other providers", grokDisableWebSearch => {
expect(parseNativeExecutionInput({ ...current, provider: { ...current.provider, grokDisableWebSearch } }).provider)
.toMatchObject(grokDisableWebSearch === undefined ? {} : { grokDisableWebSearch });
if (grokDisableWebSearch !== undefined) {
expect(() => parseNativeExecutionInput({ ...current, schema: NATIVE_EXECUTION_INPUT_SCHEMA_V9, provider: { ...current.provider, grokDisableWebSearch } })).toThrow("grokDisableWebSearch");
expect(() => parseNativeExecutionInput({ ...current, provider: { ...current.provider, agent: "codex", profile: QUALIFIED_ACPX_PROFILES.codex, grokDisableWebSearch } })).toThrow("Grok web search");
}
});
it.each(["minimal", "low", "medium", "high", "xhigh"])("round trips explicit %s and retains the compact model envelope", grokEffort => {
const parsed = parseNativeExecutionInput({ ...current, provider: { ...current.provider, grokEffort } });
expect(parsed).toMatchObject({ schema: NATIVE_EXECUTION_INPUT_SCHEMA_V10, provider: { grokEffort } });
expect(buildNativeModelEnvelope(parsed).schema).toBe("paperclip.native-model-envelope.v3");
expect(JSON.stringify(buildNativeModelEnvelope(parsed))).not.toContain("grokEffort");
});
it("directs answered Grok v10 questions to the actual compact envelope on fresh and resumed turns", () => {
const response = { interactionId: "answer-1", kind: "ask_user_questions", response: {
status: "answered", result: { version: 1, answers: [{ questionId: "destination", optionIds: ["workspace"], otherText: "Use the task workspace." }] },
} };
const parsed = parseNativeExecutionInput({ ...current, provider: { ...current.provider, grokEffort: "high" }, interactionResponses: [response] });
const constraint = nativeTaskConstraints(parsed).find(value => value.includes("already authoritatively answered"));
expect(constraint).toContain("interactionResponses[0].response.result.answers");
expect(constraint).not.toContain("message.interactionResponses");
expect(constraint).not.toContain("Use the task workspace.");
for (const envelope of [buildNativeModelEnvelope(parsed), buildNativeModelEnvelope(parsed, { resumedSession: true })]) {
expect(envelope).toHaveProperty("interactionResponses.0.response.result.answers", response.response.result.answers);
expect(envelope).not.toHaveProperty("message");
}
});
it("keeps historical readers closed and rejects aliases and foreign effort", () => {
const { homeMode: _homeMode, ...historical } = current;
for (const schema of ["paperclip.native-execution-input.v4", NATIVE_EXECUTION_INPUT_SCHEMA]) {
expect(() => parseNativeExecutionInput({ ...historical, schema, provider: { ...current.provider, grokEffort: "high" } })).toThrow("grokEffort");
expect(parseNativeExecutionInput({ ...historical, schema }).schema).toBe(schema);
}
expect(() => parseNativeExecutionInput({ ...current, provider: { ...current.provider, grokEffort: "ultra" } })).toThrow("Grok effort");
expect(() => parseNativeExecutionInput({ ...current, provider: { ...current.provider, agent: "codex", profile: QUALIFIED_ACPX_PROFILES.codex, grokEffort: "high" } })).toThrow("Grok effort");
});
});