mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 22:49:00 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native Runner starts each agent harness and owns its lifecycle, credentials and recovery > - Google Antigravity is Google's only first-party coding harness, and it is the harness for Gemini 4 Neon > - The Runner had an Antigravity integration, but only as a pending candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only, closed unless an operator opened it for one company and one model > - Cloud sandboxes run Linux and use API keys, so the candidate could not run there, and it had one attended test cell > - This pull request moves the integration to ACP server 1.5.2, makes it run on Linux and with a Gemini API key, adds the tests the other ACPX harnesses have, and removes the code paths that would block recovery after release > - The benefit is that the release of Antigravity becomes a small declaration change after the live suites pass. The profile stays `pending` in this pull request. ## Linked Issues or Issue Description Refs #98 Refs #6559 Refs #8523 Refs #21121 (a separate legacy-style `agy_local` adapter that uses the CLI print protocol; this pull request does not replace or include it) ## What Changed **Runtime** - Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is `1.5.2-paperclip.2`. - Verified patched closures for `darwin-arm64`, `linux-x64` and `linux-arm64`. `darwin-x64` stays inventory-only. - The patcher reads Mach-O and ELF builds. It signs macOS output only. One admission source serves all platforms. - Platform gates in TypeScript, Rust, the sidecar schema and the server admit each host that has a verified closure. **Auth and models** - Gemini API-key auth reaches an exact-model session receipt. Admission accepts a model only when the base model and the thinking level both match the requested ID. - API-key connections get a model list on local and cloud environments. The list is generated at build time from the pinned runtime. The server starts no process to read it. - Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker marks them "needs a paid Gemini API plan" for API-key connections. - One shared module maps model ID to family and thinking level. - `google/gemini-4-neon` is added to the OpenCode model list. A new model audit is in `doc/adapter-model-audit-2026-11-22.md`. **Lifecycle and failures** - A provider error no longer completes the turn. The driver classifies it: overloaded, rate limit, quota, auth rejected, model unavailable. - Overload retries are bounded (3 attempts, about 14 seconds). - A refused session reload maps to incompatible saved state, so the automatic replacement conversation applies. - Server gates that refused restart recovery, remote targets and shared state for Antigravity now apply only while the profile is pending. - A Google sign-in connection with a cloud environment is refused at save and at Test, with a plain message. - A released profile rejects candidate grants in TypeScript and in Rust. **Launch cost and integrity (all native ACPX providers)** - Each closure is verified one time into a sealed read-only store. Later launches check file identities and hash the exact executable they start. - Remote provider-pack verification is recorded per sandbox lease. Later runs check kernel identity and fall back to the full hash on any difference. - Superseded stores are removed in the background after a launch. **Provider pack and image** - The provider pack carries Antigravity for `linux-x64` as a candidate provider. It becomes an ordinary provider from the profile status alone. - The Daytona image build accepts the candidate. A credential-free smoke runs in the build. **Tests and CI** - New `antigravity-qualification` suite: 24 cells, local and Daytona. - New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each cell requires the exact model in the Runner receipt. - Antigravity can run the `chat-features` cases with `--profile runner-acpx-antigravity`. - `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new profile and derives candidate providers from the selected Daytona cells. **Docs** - `doc/plans/2026-11-22-antigravity-qualification.md` is the current release contract, acceptance ledger and operator recipe. ## Verification Commands that passed on the final revision: - `pnpm build` - Typecheck for all packages, including the runner-e2e test projects - `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped; 386 node tests passed - `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199 passed, 2 failed. The 2 failures are Codex transport timing tests that pass alone and on `master`. - `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`, `node scripts/check-maps.mjs` - Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64` - UI picker tests: 397 of 397 Known failures that also fail on `master`: - 11 runner package script tests (browser, Pi and package-boundary checks) - 6 `runtime-selection` tests that read an untracked local skill file Live evidence, without a prompt: - Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona sandbox. The closure digests reproduce. A changed or missing file is rejected. - `initialize` reports 1.5.2. An API-key session returns a receipt for exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both platforms. - All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt under an API key. - A session survives a process kill and resumes in a new process with exact receipts, on both platforms. - The server's remote path verifies the provider pack in a Daytona sandbox. - Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to 1.74 s on Linux x64, before the per-launch executable hash was restored (about 60 ms on macOS; not measured on Linux). - Remote pack verification on a reused sandbox lease: about 4.3 s to about 0.25 s. Live evidence, with a prompt, on an already-released harness: - Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on `darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both native runs succeeded (25.5 s and 25.7 s). The process started from the new launch store with no fallback warning. - The same cell and `native-pending-controller-restart` failed in the paid workflow on this branch and on `master` in the same way, before any native start. The workflow does not install the Pi runtime for local cells, so the agent setup check fails. That is a workflow gap, not part of this change. **Not run.** No Antigravity prompt completed on 1.5.2 on any platform. The only Gemini key available is on the free tier, and Google returned 503 or 429 for each attempt on two days. These gates are open: - All 24 `antigravity-qualification` cells - Both model lineup suites, including inference on Gemini 4 Neon - The attended Google sign-in journey on 1.5.2 - The chat cases under Antigravity - Image pull time and startup time on a published image - A native start on `linux-arm64` - A live provider-death cell for Kimi, Pi or Copilot on the new launch store (one ordinary Pi cell passed live; see above) ## Risks - **The launch store changes how every native ACPX provider starts** (Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two defects in the first version (an executable swap was possible, and Pi launches broke). Both are fixed with tests. One live Pi cell passed on this branch on macOS. No live provider-death cell and no Linux cell ran for those providers. - The profile digest changes. Saved Antigravity candidate sessions and existing candidate grants stop working. The new release refuses old state by name and starts a replacement conversation. - The Linux provider pack and the Daytona image grow by about 834 MB (about 274 MB compressed) when Antigravity is included. - The pack verification record is in server memory. The first run after a server restart pays the full hash again. - Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as user rules. This is deliberate and matches Codex. Any other rule file is refused. - Orchestrator mode is not available. ACP server 1.5.2 does not expose it. - Antigravity stays `pending`. Normal users cannot run it until a later change removes the pending status. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated the work, with tool use. - Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran the tests, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
327 lines
29 KiB
TypeScript
327 lines
29 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { canonicalJson } from "../../packages/shared/src/portability-hash.js";
|
|
import { hasAcpxNativeOrigin } from "./acpx-native-origin.js";
|
|
import { isValidNativePrpEnvelope } from "./native-event-envelope.js";
|
|
import { assertCopilotRemoteRetirement, copilotRemoteDeniedSample, type CopilotRemoteSnapshot } from "./copilot-protection-evidence.js";
|
|
import { readCopilotToolEvidence } from "./copilot-evidence.js";
|
|
import { readCursorToolEvidence } from "./cursor-native-evidence.js";
|
|
import { bootstrapReadExecutionId, withoutProvenBootstrapReads, type BootstrapReadProof } from "./native-bootstrap-read-proof.js";
|
|
|
|
type Row = Record<string, any>;
|
|
export interface ActiveStopCaller { type: "board"; userId: "local-board"; source: "local_implicit" }
|
|
export type ActiveStopProvider = "cursor" | "copilot" | "antigravity";
|
|
/** Providers without a native tool-evidence notice; their proof is the canonical PRP stream alone. */
|
|
const CANONICAL_PROVIDERS: ReadonlySet<ActiveStopProvider> = new Set(["antigravity"]);
|
|
export interface ActiveStopScope { provider: ActiveStopProvider; companyId: string; issueId: string; runId: string; target: string; commandSha256?: string }
|
|
export interface ActiveStopPending {
|
|
schema: "paperclip.e2e.native-active-stop-pending.v2";
|
|
caller: ActiveStopCaller; scope: ActiveStopScope; requestId: string; toolCallId: string; nativeSessionId: string; turnId: string;
|
|
normalizedSessionId: string; sourceInstanceId: string; requestSourceSeq: number; permissionSourceSeq: number;
|
|
requestRowSha256: string; permissionRowSha256: string; cancellationRequestId: string; observedMonotonicNs: string;
|
|
toolOriginSourceSeq: number; toolStartedSourceSeq: number; toolOriginRowSha256: string; toolStartedRowSha256: string;
|
|
}
|
|
const rec = (v: unknown): Row => v !== null && typeof v === "object" && !Array.isArray(v) ? v as Row : {};
|
|
const id = (v: unknown): v is string => typeof v === "string" && v.length > 0 && v.length <= 240 && !/[\u0000-\u001f\u007f]/u.test(v) && !v.includes("[REDACTED]");
|
|
const uuid = (v: unknown): v is string => typeof v === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/u.test(v);
|
|
const hash = (v: unknown) => `sha256:${createHash("sha256").update(canonicalJson(v)).digest("hex")}`;
|
|
function fail(condition: unknown, reason: string): asserts condition { if (!condition) throw new Error(`Native active Stop: ${reason}`); }
|
|
/** The isolated Product server uses local-trusted board authentication. Bind
|
|
* the same public session observed by the API client, never infer a null actor. */
|
|
export function readActiveStopCaller(health: unknown, authentication: unknown): ActiveStopCaller {
|
|
const session = rec(rec(authentication).session);
|
|
fail(rec(health).deploymentMode === "local_trusted" && session.userId === "local-board"
|
|
&& session.id === "paperclip:local_implicit:local-board", "expected isolated board caller missing");
|
|
return { type: "board", userId: "local-board", source: "local_implicit" };
|
|
}
|
|
function isActiveStopCaller(caller: unknown): caller is ActiveStopCaller {
|
|
const value = rec(caller);
|
|
return value.type === "board" && value.userId === "local-board" && value.source === "local_implicit";
|
|
}
|
|
function canonicalRows(events: readonly unknown[], scope: ActiveStopScope) {
|
|
fail(events.length <= 20_000 && events.length > 0, "bounded durable evidence required");
|
|
const rows = events.map(rec).filter(row => rec(row.payload).prpEvent !== undefined);
|
|
const seen = new Set<number>(), source = new Set<string>();
|
|
for (const row of rows) {
|
|
const e = rec(rec(row.payload).prpEvent);
|
|
fail(row.companyId === scope.companyId && row.runId === scope.runId && isValidNativePrpEnvelope(e, row.protocolSchemaVersion)
|
|
&& e.sourceKind === "runner" && e.runId === scope.runId
|
|
&& e.eventType === row.eventType && Number.isSafeInteger(row.seq) && row.seq > 0 && !seen.has(row.seq)
|
|
&& id(e.sourceInstanceId) && Number.isSafeInteger(e.sourceSeq) && e.sourceSeq > 0
|
|
&& e.sourceEventId === `${e.sourceInstanceId}:${e.runId}:${e.sourceSeq}` && !source.has(e.sourceEventId), "invalid/duplicate/foreign canonical row");
|
|
seen.add(row.seq); source.add(e.sourceEventId);
|
|
}
|
|
const ordered = [...rows].sort((a, b) => a.seq - b.seq);
|
|
const lastBySource = new Map<string, number>();
|
|
for (const row of ordered) {
|
|
const e = rec(rec(row.payload).prpEvent), previous = lastBySource.get(e.sourceInstanceId) ?? 0;
|
|
fail(e.sourceSeq > previous, "durable source sequence reordered");
|
|
lastBySource.set(e.sourceInstanceId, e.sourceSeq);
|
|
}
|
|
return ordered.map(row => ({ row, event: rec(rec(row.payload).prpEvent) }));
|
|
}
|
|
const terminals = new Set(["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]);
|
|
const closures = new Set(["runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired"]);
|
|
type CanonicalRow = ReturnType<typeof canonicalRows>[number];
|
|
const MUTATIONS = new Set(["edit", "write", "execute"]);
|
|
const READS = new Set(["read", "search"]);
|
|
/**
|
|
* No provider notice exists, so bind the one durable permission card to its
|
|
* exact native tool call through the canonical execution ID. Only completed
|
|
* read-only operations may precede it; the mutation may not complete.
|
|
*/
|
|
function canonicalOrigin(rows: CanonicalRow[], scope: ActiveStopScope) {
|
|
const created = rows.filter(x => x.event.eventType === "runtime_request.created");
|
|
fail(created.length === 1, "one durable native card required");
|
|
const card = created[0]!, request = rec(rec(card.event.payload).request), details = rec(request.details);
|
|
const choices = Array.isArray(request.choices) ? request.choices.map(rec) : [];
|
|
fail(request.schema === "paperclip.runtime_request.v2" && request.type === "permission" && request.requestKind === "permission_approval"
|
|
&& request.status === "pending" && id(request.requestId) && id(request.itemId) && id(details.toolCallId) && request.turnId === card.event.turnId
|
|
&& id(card.event.turnId) && id(card.event.normalizedSessionId) && hasAcpxNativeOrigin(request.origin, scope.provider, "session/request_permission")
|
|
&& choices.some(choice => choice.key === "decline") && choices.some(choice => choice.key === "accept"), "exact native permission identity missing");
|
|
const stream = (event: Row) => event.turnId === card.event.turnId && event.normalizedSessionId === card.event.normalizedSessionId && event.sourceInstanceId === card.event.sourceInstanceId;
|
|
fail(rows.filter(x => x.event.turnId != null).every(x => stream(x.event)), "foreign turn/session/source");
|
|
const executionId = bootstrapReadExecutionId(details.toolCallId);
|
|
const executions = rows.filter(x => x.event.eventType.startsWith("tool.execution."));
|
|
const own = executions.filter(x => rec(x.event.payload).executionId === executionId);
|
|
const started = own.filter(x => x.event.eventType === "tool.execution.started");
|
|
fail(started.length === 1 && own[0] === started[0] && own.filter(x => x.event.eventType === "tool.execution.completed").length <= 1
|
|
&& own.every(x => rec(x.event.payload).schema === "paperclip.tool.execution.v1"
|
|
&& ["tool.execution.started", "tool.execution.progressed", "tool.execution.completed"].includes(x.event.eventType)
|
|
&& rec(x.event.payload).status === (x.event.eventType === "tool.execution.completed" ? "failed" : "running")
|
|
&& (MUTATIONS.has(rec(x.event.payload).operation) || rec(x.event.payload).operation === "unknown")
|
|
&& (rec(x.event.payload).target === scope.target || rec(x.event.payload).target == null))
|
|
&& own.some(x => MUTATIONS.has(rec(x.event.payload).operation))
|
|
&& (own.some(x => rec(x.event.payload).target === scope.target) || String(request.prompt ?? "").includes(scope.target)),
|
|
"exact native mutation lifecycle missing or completed");
|
|
const boundary = Math.min(card.row.seq, started[0]!.row.seq), others = new Map<string, CanonicalRow[]>();
|
|
for (const x of executions.filter(x => rec(x.event.payload).executionId !== executionId)) {
|
|
const key = String(rec(x.event.payload).executionId); others.set(key, [...others.get(key) ?? [], x]);
|
|
}
|
|
for (const group of others.values()) {
|
|
fail(group[0]!.event.eventType === "tool.execution.started" && group.at(-1)!.event.eventType === "tool.execution.completed"
|
|
&& group.at(-1)!.row.seq < boundary && group.every(x => READS.has(rec(x.event.payload).operation) || rec(x.event.payload).operation === "unknown")
|
|
&& group.some(x => READS.has(rec(x.event.payload).operation)) && group.every(x => rec(x.event.payload).target !== scope.target),
|
|
"extra native operation before or beside the pending mutation");
|
|
}
|
|
const notice = { runId: scope.runId, sessionId: card.event.normalizedSessionId as string, turnId: card.event.turnId as string,
|
|
toolCallId: details.toolCallId as string, requestId: request.requestId as string, seq: card.row.seq, stage: "permission_requested" as const,
|
|
declineOffered: true, operation: "edit" };
|
|
return { rows, notice, permission: card, created: card, toolOrigin: started[0]!, toolStarted: started[0]!, request, stream };
|
|
}
|
|
function origin(events: readonly unknown[], scope: ActiveStopScope, bootstrap?: BootstrapReadProof) {
|
|
fail([scope.companyId, scope.issueId, scope.runId, scope.target].every(id) && ["cursor", "copilot", "antigravity"].includes(scope.provider), "exact scope required");
|
|
const rows = canonicalRows(events, scope);
|
|
if (CANONICAL_PROVIDERS.has(scope.provider)) return canonicalOrigin(rows, scope);
|
|
const notices = scope.provider === "cursor" ? readCursorToolEvidence(events, scope.runId) : readCopilotToolEvidence(events, scope.runId);
|
|
const requests = notices.filter(n => n.stage === "permission_requested");
|
|
fail(requests.length === 1, "one native permission required");
|
|
const notice = requests[0]!;
|
|
fail(id(notice.requestId) && notice.declineOffered === true && (scope.provider === "cursor"
|
|
? notice.operation === "execute" && /^sha256:[a-f0-9]{64}$/u.test(scope.commandSha256 ?? "") && notice.commandSha256 === scope.commandSha256
|
|
: notice.operation === "edit" && "target" in notice && notice.target === scope.target), "exact native operation required");
|
|
const permission = rows.find(x => x.row.seq === notice.seq);
|
|
const created = rows.filter(x => x.event.eventType === "runtime_request.created");
|
|
fail(permission && created.length === 1, "one durable native card required");
|
|
const request = rec(rec(created[0]!.event.payload).request), p = permission.event;
|
|
fail(request.schema === "paperclip.runtime_request.v2" && request.type === "permission" && request.requestKind === "permission_approval"
|
|
&& request.status === "pending" && request.requestId === notice.requestId && request.turnId === notice.turnId
|
|
&& rec(request.details).toolCallId === notice.toolCallId && hasAcpxNativeOrigin(request.origin, scope.provider, "session/request_permission")
|
|
&& id(p.normalizedSessionId) && p.turnId === notice.turnId && created[0]!.event.turnId === notice.turnId
|
|
&& created[0]!.event.normalizedSessionId === p.normalizedSessionId && created[0]!.event.sourceInstanceId === p.sourceInstanceId,
|
|
"native notice/card identity mismatch");
|
|
const stream = (event: Row) => event.turnId === notice.turnId && event.normalizedSessionId === p.normalizedSessionId && event.sourceInstanceId === p.sourceInstanceId;
|
|
fail(rows.filter(x => x.event.turnId != null).every(x => stream(x.event)), "foreign turn/session/source");
|
|
const tool = notices.find(n => n.stage === "tool" && n.toolCallId === notice.toolCallId);
|
|
fail(tool, "native operation origin missing");
|
|
const selected = withoutProvenBootstrapReads(notices, tool, bootstrap);
|
|
fail(selected.every(n => n.runId === notice.runId && n.sessionId === notice.sessionId && n.turnId === notice.turnId
|
|
&& n.toolCallId === notice.toolCallId && (n.requestId === undefined || n.requestId === notice.requestId)
|
|
&& (n.operation === undefined || n.operation === notice.operation)
|
|
&& (!("target" in n) || n.target === undefined || n.target === scope.target)
|
|
&& (n.commandSha256 === undefined || n.commandSha256 === scope.commandSha256)
|
|
&& n.status !== "completed" && (n.stage !== "permission_delivered" || n.outcome === "cancel")), "extra/replayed/answered native operation");
|
|
const tools = selected.filter(n => n.stage === "tool");
|
|
fail(tools.filter(n => n.status === "pending").length === 1
|
|
&& tools.filter(n => n.status === "failed").length <= 1
|
|
&& tools[0]!.status === "pending"
|
|
// Cursor queues permission evidence until its exact command origin exists.
|
|
// Copilot projects the request immediately, including permission-first ACP.
|
|
&& (scope.provider !== "cursor" || tools[0]!.seq < notice.seq)
|
|
&& selected.filter(n => n.stage === "permission_delivered").length <= 1, "duplicate native operation lifecycle");
|
|
const executions = rows.filter(x => x.event.eventType.startsWith("tool.execution.") && rec(x.event.payload).executionId === bootstrapReadExecutionId(notice.toolCallId));
|
|
fail(executions.filter(x => x.event.eventType === "tool.execution.started").length === 1
|
|
&& executions.filter(x => x.event.eventType === "tool.execution.completed").length <= 1
|
|
&& executions.every(x => rec(x.event.payload).schema === "paperclip.tool.execution.v1" && rec(x.event.payload).transport === "builtin"
|
|
&& ["tool.execution.started", "tool.execution.progressed", "tool.execution.completed"].includes(x.event.eventType)
|
|
&& rec(x.event.payload).status === (x.event.eventType === "tool.execution.completed" ? "failed" : "running")), "duplicate canonical operation lifecycle");
|
|
// ACP permits a permission request before its tool notification. Require
|
|
// both in the pre-Stop observation, without imposing a card/start order.
|
|
const toolOrigin = rows.find(x => x.row.seq === tools[0]!.seq);
|
|
const toolStarted = executions.find(x => x.event.eventType === "tool.execution.started");
|
|
fail(toolOrigin && toolStarted, "native operation origin missing");
|
|
const allowed = new Set(notices.filter(n => n.stage === "tool").map(n => bootstrapReadExecutionId(n.toolCallId)));
|
|
fail(rows.filter(x => x.event.eventType.startsWith("tool.execution.")).every(x => allowed.has(rec(x.event.payload).executionId)), "unattributed operation");
|
|
fail(rows.filter(x => x.event.eventType === "tool.execution.completed" && rec(x.event.payload).executionId === bootstrapReadExecutionId(notice.toolCallId))
|
|
.every(x => rec(x.event.payload).status !== "completed"), "target operation completed");
|
|
return { rows, notice, permission, created: created[0]!, toolOrigin, toolStarted, request, stream };
|
|
}
|
|
export function observeActiveStopPending(input: { events: readonly unknown[]; run: Row; issue: Row; scope: ActiveStopScope; caller: ActiveStopCaller; cancellationRequestId: string; bootstrap?: BootstrapReadProof }): ActiveStopPending {
|
|
const { run, issue, scope } = input, proof = origin(input.events, scope, input.bootstrap);
|
|
fail(isActiveStopCaller(input.caller) && uuid(input.cancellationRequestId) && run.id === scope.runId && run.companyId === scope.companyId && run.nativeIssueId === scope.issueId
|
|
&& run.status === "running" && run.runtimeMode === "native" && issue.id === scope.issueId && issue.companyId === scope.companyId && issue.status === "in_progress"
|
|
&& run.resultJson?.startupCancellation == null && run.resultJson?.nativeCancellation == null, "run is not fresh active work");
|
|
fail(CANONICAL_PROVIDERS.has(scope.provider) || !(scope.provider === "cursor" ? readCursorToolEvidence(input.events, scope.runId) : readCopilotToolEvidence(input.events, scope.runId)).some(n => n.stage === "permission_delivered"), "permission already answered");
|
|
fail(!proof.rows.some(x => terminals.has(x.event.eventType) || closures.has(x.event.eventType)), "request or provider already settled");
|
|
fail(!proof.rows.some(x => x.event.eventType === "tool.execution.completed" && rec(x.event.payload).executionId === bootstrapReadExecutionId(proof.notice.toolCallId)), "operation already ended");
|
|
return { schema: "paperclip.e2e.native-active-stop-pending.v2", scope, caller: input.caller, requestId: proof.notice.requestId!, toolCallId: proof.notice.toolCallId,
|
|
nativeSessionId: proof.notice.sessionId, turnId: proof.notice.turnId, normalizedSessionId: proof.permission.event.normalizedSessionId,
|
|
sourceInstanceId: proof.permission.event.sourceInstanceId, requestSourceSeq: proof.created.event.sourceSeq, permissionSourceSeq: proof.permission.event.sourceSeq,
|
|
requestRowSha256: hash(proof.created.row), permissionRowSha256: hash(proof.permission.row), cancellationRequestId: input.cancellationRequestId,
|
|
toolOriginSourceSeq: proof.toolOrigin.event.sourceSeq, toolStartedSourceSeq: proof.toolStarted.event.sourceSeq,
|
|
toolOriginRowSha256: hash(proof.toolOrigin.row), toolStartedRowSha256: hash(proof.toolStarted.row),
|
|
observedMonotonicNs: process.hrtime.bigint().toString() };
|
|
}
|
|
export function readActiveStopSettlement(input: { events: readonly unknown[]; run: Row; issue: Row; pending: ActiveStopPending; dispatchMonotonicNs: string; bootstrap?: BootstrapReadProof }) {
|
|
const before = input.pending, { run, issue } = input;
|
|
fail(before?.schema === "paperclip.e2e.native-active-stop-pending.v2" && isActiveStopCaller(before.caller) && uuid(before.cancellationRequestId)
|
|
&& /^[1-9][0-9]{0,29}$/u.test(before.observedMonotonicNs) && /^[1-9][0-9]{0,29}$/u.test(input.dispatchMonotonicNs)
|
|
&& BigInt(before.observedMonotonicNs) < BigInt(input.dispatchMonotonicNs), "pre-dispatch pending observation missing");
|
|
const proof = origin(input.events, before.scope, input.bootstrap);
|
|
fail(hash(proof.created.row) === before.requestRowSha256 && hash(proof.permission.row) === before.permissionRowSha256
|
|
&& hash(proof.toolOrigin.row) === before.toolOriginRowSha256 && hash(proof.toolStarted.row) === before.toolStartedRowSha256
|
|
&& proof.toolOrigin.event.sourceSeq === before.toolOriginSourceSeq && proof.toolStarted.event.sourceSeq === before.toolStartedSourceSeq
|
|
&& proof.notice.sessionId === before.nativeSessionId && proof.notice.turnId === before.turnId && proof.notice.toolCallId === before.toolCallId
|
|
&& proof.notice.requestId === before.requestId && proof.permission.event.normalizedSessionId === before.normalizedSessionId
|
|
&& proof.permission.event.sourceInstanceId === before.sourceInstanceId && proof.created.event.sourceSeq === before.requestSourceSeq
|
|
&& proof.permission.event.sourceSeq === before.permissionSourceSeq, "observed pending request changed");
|
|
const closed = proof.rows.filter(x => closures.has(x.event.eventType)), terminal = proof.rows.filter(x => terminals.has(x.event.eventType));
|
|
fail(closed.length === 1 && terminal.length === 1, "one closed request and one terminal required");
|
|
const c = closed[0]!, t = terminal[0]!, cp = rec(c.event.payload), tp = rec(t.event.payload);
|
|
// Product persists the harness projection, not the raw runnerd backend
|
|
// payload. The terminal mapper closes pending permissions with turn_terminal
|
|
// and emits {status,error}. Bind that exact boundary to the retained native
|
|
// request and caller-owned Stop below; a generic terminal is insufficient.
|
|
fail(proof.stream(c.event) && proof.stream(t.event) && c.event.eventType === "runtime_request.cancelled" && cp.requestId === before.requestId && cp.turnId === before.turnId
|
|
&& cp.requestKind === "permission_approval" && cp.reason === "turn_terminal"
|
|
&& cp.itemId === proof.request.itemId && cp.action === undefined && cp.response === undefined && cp.replayAllowed !== true
|
|
&& t.event.eventType === "turn.cancelled" && tp.status === "cancelled" && tp.error === null
|
|
&& c.event.sourceSeq > Math.max(before.requestSourceSeq, before.permissionSourceSeq, before.toolOriginSourceSeq, before.toolStartedSourceSeq)
|
|
&& t.event.sourceSeq > c.event.sourceSeq,
|
|
"pending callback did not close through cancellation");
|
|
fail(proof.rows.filter(x => x.event.eventType.startsWith("tool.execution.")
|
|
|| (x.event.eventType === "provider.notice.recorded" && ["cursor_tool_evidence_v1", "copilot_tool_evidence_v1"].includes(rec(x.event.payload).category)))
|
|
.every(x => x.event.sourceSeq < t.event.sourceSeq), "native operation after provider cancellation");
|
|
const stop = assertStopAcknowledged(run, issue, before);
|
|
return { schema: "paperclip.e2e.native-active-stop-settlement.v2", pending: before, dispatchMonotonicNs: input.dispatchMonotonicNs,
|
|
branch: "pending_permission_cancelled" as const, closedRequestSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq,
|
|
closedRequestRowSha256: hash(c.row), terminalRowSha256: hash(t.row), intentId: stop.intentId as string,
|
|
intentAuditId: stop.intentAuditId as string, acknowledgementAuditId: stop.acknowledgementAuditId as string,
|
|
taskStillInProgress: true, normalCompletionAccepted: false, replayAllowed: false };
|
|
}
|
|
/**
|
|
* Playbook section 13, "Permission denial": the operator denies the one real
|
|
* native permission in the browser, then stops the task. The denial must reach
|
|
* the provider as a `decline` resolution of that exact request before the
|
|
* turn ends; the mutation never completes; nothing runs after the terminal;
|
|
* and Stop is acknowledged for this run. If the provider already ended its
|
|
* turn after the denial, the run must not claim the task done.
|
|
*/
|
|
export function readDeniedPermissionSettlement(input: { events: readonly unknown[]; run: Row; issue: Row; pending: ActiveStopPending; stopDispatched: boolean }) {
|
|
const before = input.pending, { run, issue } = input;
|
|
fail(before?.schema === "paperclip.e2e.native-active-stop-pending.v2" && isActiveStopCaller(before.caller), "pre-denial pending observation missing");
|
|
const proof = origin(input.events, before.scope);
|
|
fail(hash(proof.created.row) === before.requestRowSha256 && proof.notice.requestId === before.requestId && proof.notice.turnId === before.turnId
|
|
&& proof.notice.toolCallId === before.toolCallId, "observed pending request changed");
|
|
const closed = proof.rows.filter(x => closures.has(x.event.eventType)), terminal = proof.rows.filter(x => terminals.has(x.event.eventType));
|
|
fail(closed.length === 1 && terminal.length === 1, "one closed request and one terminal required");
|
|
const c = closed[0]!, t = terminal[0]!, cp = rec(c.event.payload);
|
|
fail(proof.stream(c.event) && proof.stream(t.event) && c.event.eventType === "runtime_request.resolved" && cp.requestId === before.requestId
|
|
&& cp.turnId === before.turnId && cp.action === "decline" && c.event.sourceSeq > before.requestSourceSeq && t.event.sourceSeq > c.event.sourceSeq,
|
|
"denial was not delivered to the exact native request before the turn ended");
|
|
fail(proof.rows.filter(x => x.event.eventType.startsWith("tool.execution.")).every(x => x.event.sourceSeq < t.event.sourceSeq
|
|
&& !(x.event.eventType === "tool.execution.completed" && rec(x.event.payload).status === "completed" && MUTATIONS.has(rec(x.event.payload).operation))),
|
|
"native mutation completed or ran after the terminal");
|
|
fail(run.id === before.scope.runId && run.companyId === before.scope.companyId && run.nativeIssueId === before.scope.issueId && run.runtimeMode === "native",
|
|
"foreign run");
|
|
if (t.event.eventType === "turn.cancelled") {
|
|
fail(input.stopDispatched, "turn cancelled without the operator's Stop");
|
|
const stop = assertStopAcknowledged(run, issue, before);
|
|
return { schema: "paperclip.e2e.native-permission-denial.v1", branch: "denied_then_stopped" as const, requestId: before.requestId,
|
|
resolvedSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq, intentId: stop.intentId as string, replayAllowed: false };
|
|
}
|
|
fail(["succeeded", "failed"].includes(run.status) && issue.id === before.scope.issueId && issue.status !== "done",
|
|
"provider finished after the denial but the task claims completion");
|
|
return { schema: "paperclip.e2e.native-permission-denial.v1", branch: "denied_then_finished" as const, requestId: before.requestId,
|
|
resolvedSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq, replayAllowed: false };
|
|
}
|
|
function assertStopAcknowledged(run: Row, issue: Row, before: ActiveStopPending): Row {
|
|
const stop = rec(rec(run.resultJson).nativeCancellation), startup = rec(rec(run.resultJson).startupCancellation);
|
|
fail(run.id === before.scope.runId && run.companyId === before.scope.companyId && run.nativeIssueId === before.scope.issueId && run.runtimeMode === "native" && run.status === "cancelled"
|
|
&& issue.id === before.scope.issueId && issue.companyId === before.scope.companyId && issue.status === "in_progress"
|
|
&& rec(startup.requestedBy).type === before.caller.type && rec(startup.requestedBy).userId === before.caller.userId
|
|
&& startup.cancellationRequestId === before.cancellationRequestId && stop.intentId === `native-cancellation:${before.cancellationRequestId}`
|
|
&& stop.schema === "paperclip.native-cancellation.v1" && stop.companyId === before.scope.companyId && stop.runId === run.id && stop.issueId === issue.id
|
|
&& stop.scope === "run" && stop.dispatched === true && stop.dispatchState === "acknowledged" && stop.reasonCode === "cancellation_run_only"
|
|
&& Array.isArray(stop.effects) && stop.effects.length === 1 && stop.effects[0] === "release_run_resources"
|
|
&& id(stop.intentAuditId) && id(stop.acknowledgementAuditId) && stop.intentAuditId !== stop.acknowledgementAuditId,
|
|
"same-scope caller Stop acknowledgement missing");
|
|
return stop;
|
|
}
|
|
|
|
export interface ActiveStopRemoteObservation {
|
|
phase: "before-request" | "pending" | "owned-process-retirement";
|
|
source: "live-snapshot" | "retirement-seal";
|
|
snapshot: CopilotRemoteSnapshot;
|
|
}
|
|
|
|
/** A per-turn Daytona observer seals itself when the owned tree retires. The
|
|
* host may retrieve that receipt later; retrieval is not a fresh observation. */
|
|
export function readActiveStopRemoteRetirement(input: {
|
|
scope: Pick<ActiveStopScope, "companyId" | "runId" | "target">; observations: readonly ActiveStopRemoteObservation[];
|
|
}) {
|
|
const observations = input.observations;
|
|
fail(observations.length === 3
|
|
&& observations.map(o => `${o.phase}:${o.source}`).join(",") === "before-request:live-snapshot,pending:live-snapshot,owned-process-retirement:retirement-seal",
|
|
"remote seal cannot stand in for a fresh causal sample");
|
|
const [baseline, pending, terminal] = observations.map(o => o.snapshot) as [CopilotRemoteSnapshot, CopilotRemoteSnapshot, CopilotRemoteSnapshot];
|
|
fail(baseline.binding.companyId === input.scope.companyId && baseline.binding.runId === input.scope.runId, "remote observation belongs to another run");
|
|
for (const snapshot of [baseline, pending, terminal]) {
|
|
fail(!copilotRemoteDeniedSample(snapshot, baseline, input.scope.target, "pending").exists, "remote target changed");
|
|
}
|
|
fail(BigInt(baseline.observedMonotonicNs) < BigInt(pending.observedMonotonicNs)
|
|
&& BigInt(pending.observedMonotonicNs) < BigInt(terminal.observedMonotonicNs), "remote observation reused or out of order");
|
|
fail(!baseline.setup.published && pending.setup.published && pending.setup.sha256 === terminal.setup.sha256
|
|
&& baseline.processes.captured && pending.processes.captured
|
|
&& baseline.processes.live.includes(baseline.processes.root?.pid ?? -1)
|
|
&& pending.processes.live.includes(pending.processes.root?.pid ?? -1), "remote pending lifetime unproven");
|
|
assertCopilotRemoteRetirement(terminal, baseline);
|
|
assertCopilotRemoteRetirement(terminal, pending);
|
|
for (const snapshot of [baseline, pending]) {
|
|
fail(snapshot.processes.journal.every(p => terminal.processes.journal.some(q =>
|
|
p.pid === q.pid && p.startTicks === q.startTicks && p.bootId === q.bootId)), "remote descendant journal lost");
|
|
}
|
|
return { schema: "paperclip.e2e.native-active-stop-remote-retirement.v1" as const,
|
|
coverage: "continuous-through-owned-process-retirement" as const, filesystemAfterRetirementObserved: false as const,
|
|
binding: terminal.binding, target: input.scope.target,
|
|
observations: observations.map(o => ({ phase: o.phase, source: o.source,
|
|
observedMonotonicNs: o.snapshot.observedMonotonicNs, snapshotSha256: hash(o.snapshot) })) };
|
|
}
|
|
|
|
/** Local files remain accessible through teardown. Remote per-turn files do
|
|
* not: require the complete lifetime seal, never relabel it as a later sample. */
|
|
export function assertActiveStopRetirement(input: {
|
|
completed: boolean; identityChanged: boolean;
|
|
processes: { captured: boolean; live: readonly number[] };
|
|
watcher: { complete: boolean; targetMutationCount: number };
|
|
} & ({ environment: "local"; samples: ReadonlyArray<{ phase: string; absent: boolean }> }
|
|
| { environment: "daytona"; remote: Parameters<typeof readActiveStopRemoteRetirement>[0] })) {
|
|
fail(input.completed && !input.identityChanged && input.processes.captured
|
|
&& input.processes.live.length === 0 && input.watcher.complete && input.watcher.targetMutationCount === 0,
|
|
"retirement or continuous no-effect proof is incomplete");
|
|
if (input.environment === "daytona") return readActiveStopRemoteRetirement(input.remote);
|
|
fail(input.environment === "local" && input.samples.length === 4 && input.samples.every(s => s.absent === true)
|
|
&& input.samples.map(s => s.phase).join(",") === "before-request,pending,after-stop,after-cleanup",
|
|
"causal target observation missing or changed");
|
|
return { coverage: "local-through-cleanup" as const };
|
|
}
|