Files
PaperClipAI/tests/runner-e2e/copilot-semantic-evidence.test.ts
T
DottaandPaperclip 7c247243e5 Qualify and package Copilot for ordinary installations (#15706)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A provider must work through normal installed packages on local and
Daytona environments.
> - Candidate-only success does not prove that the shipped package
contains the manifest and native runtime needed for Daytona.
> - The release must preserve saved-token access and task lifecycle
guarantees.
> - This pull request will qualify Copilot and include the exact-source
remote manifest in normal release archives.
> - The benefit is a reviewable part of the Copilot production release.

## Linked Issues or Issue Description

Refs #15701, #15703 and #15705. Supersedes qualification work in #15563
and the original candidate in #14434. Base: #15705.

## What Changed

- Keep Copilot discovery passive during reconnect reconciliation;
refresh on explicit opening, account/environment changes and reconnect.

- Retain the selected Product cases, permission/continuity evidence and
cleanup checks.
- Build the Linux provider manifest from the existing pinned Docker
stage in the cloud.
- Join all four native daemon receipts with that manifest before server
packing.
- Reject missing or incompatible remote authority during normal release
assembly; retain historical workflow compatibility.
- Promote the completed profile47 qualification marker, publish the
current qualification record and preserve every failed attempt.
- Keep one current release checklist and the shipped-canary gates
explicit.

## Verification

Runtime #15701 is merged at `d855e550ad8d2a267312983f26457aabf5393c3a`.
History #15703 is merged at `df80616d98119cbf5abd40549794d9980a5fabf6`.
Remaining source
[`42bcbd61299655f7e37aabe6bb5f19bba770ad1d`](https://github.com/paperclipai/paperclip/commit/42bcbd61299655f7e37aabe6bb5f19bba770ad1d)
contains the four-file authorization repair. The remaining PR trees
preserve six nonoverlapping files from the newer public mainline
managed-settings fix and the CI-owned lockfile. No unrelated provider is
enabled.

The security finding is repaired: existing-agent discovery requires
`agent_config:update` before connection selection or token resolution.
The saved environment is the default. Authorized editors can select a
prospective environment. Both denied board-viewer and agent-reader
regressions fail on the original source. All49 route tests and server
typecheck pass with the fix. Denied requests perform no connection
selection, credential resolution or probe. Current-head security scans
pass on both remaining PRs; the repaired thread is resolved.

Copilot CLI1.0.88 and profile47 retain digest
`sha256:55044aa235e88b3fe36ec8a556ee1e3382590870aab907e4462ef7d64af49cea`.
The [qualification
record](https://github.com/paperclipai/paperclip/blob/42bcbd61299655f7e37aabe6bb5f19bba770ad1d/doc/plans/2026-10-20-copilot-qualification-v47.json)
reports20/20 Product cells,154 assertions and7/7 protocol cases,46
assertions against frozen normal installed source
`c2616370800f5f6df45246b0890ba35a7cd2faab`. The exact qualification
model is `gpt-5.6-luna`. Every passing Product case confirms cleanup.
Original failures remain recorded; automatic behavior retries are
disabled. The route-only authorization repair changes no bound
runtime/profile bytes and does not relabel the frozen campaign.

The ordinary installed remote journey passed saved-token selection,
model discovery, normal UI save/reopen, metadata-only Test, completed
task, accepted receipt and exact19-byte browser download. An open model
catalog caused no additional discovery requests during117seconds. Actual
installed runtime smokes passed on macOS ARM64, macOS x64 under Rosetta
and native Linux x64 on Daytona. Raw token browser entry was not
exercised; encrypted connection creation used the normal API.

The first Daytona file attempt timed out during delayed semantic
dispatch; its precise stalled layer remains unresolved. Independent
ordinary remote delivery and the other19 Product cells passed before one
instrumented recheck passed8/8 with unchanged source,prompt,assertions
and deadlines. No causal latency repair is claimed.

Before the authorization repair, all four final PR heads passed required
verify/E2E and fresh Greptile5/5 reviews with zero unresolved threads.
Current-head CI/review is running for the two repaired heads. Local
focused checks retain129 connection,59 runner,72 shared-eval and88
recovery/workspace passes, plus migration safety and token gates. The
additive Copilot migration is361; released master history is preserved.

[Cloud normal-package
run39414239704](https://github.com/paperclipai/paperclip/actions/runs/39414239704)
builds the pre-security source4f3f. All four native producers and Linux
package assembly pass; the final clean installed consumers are
finishing. All18 retained archives match their hashes;37,863 regular
files contain zero selected credentials. That package does not contain
the later route repair. The actual final published package must include
it and pass the local/Daytona live canaries. The frozen Daytona image
remains published and independently verified. No separate full-image
scan is claimed. Docker builds run in the cloud.

**Remaining:** current-head CI/review, setup and qualification merges,
final publication, and ordinary local/Daytona canaries against the
actual shipped package. The user explicitly authorizes the maintainer
review override; CI remains a merge gate. No production deployment is
claimed. Provider USD remains unknown and GitHub-attributed.

## Risks

An omitted or mismatched image manifest prevents ordinary Daytona
startup. Final normal archives must contain the matching image authority
and platform daemons. The completed runtime campaign remains bound to
its original source; the final UI-only repair needs its own
normal-install setup proof. Credit notices are not measured USD
receipts. Native steering, native plan mode and detached work remain
outside this release.

## Model Used

OpenAI Codex, based on GPT-6. The exact serving model ID and context
window are not exposed in this task. Used for code changes, review and
tool-assisted verification.

## 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
- [ ] 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-20 07:33:14 -05:00

259 lines
25 KiB
TypeScript

import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import { copilotAttachedFinishReady, copilotFinishAttemptBeforeCommandExit, onlyCopilotAttachedOperations, readCopilotSemanticCompletion } from "./copilot-semantic-evidence.js";
import { readCopilotToolEvidence } from "./copilot-evidence.js";
import { copilotActionNotices, findCopilotFixtureCommand } from "./copilot-protection-evidence.js";
import { validatePrpStructuredRunResult } from "../../packages/paperclip-runner/src/protocol/replay-contract.js";
import { runnerSuites, suiteDefinitionHash } from "./catalog.js";
const hash = (v: string) => createHash("sha256").update(v).digest("hex");
const canonical = (v: any): string => Array.isArray(v) ? `[${v.map(canonical).join(",")}]` : v !== null && typeof v === "object" ? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}` : JSON.stringify(v);
const rawInput = { summary: "EXACT-MARKER", reportedWorkDisposition: "done", completionClaim: { contractRevision: "1", objectiveSatisfied: true, criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }], remainingWork: [] }, evidence: [], verification: [] };
const validation = validatePrpStructuredRunResult(rawInput);
if (!validation.ok) throw new Error("Semantic fixture input must pass the production validator");
const result = validation.result;
const receipt = { schema: "paperclip.semantic_tool_receipt.v2", operationId: "paperclip_finish", callIdentitySha256: hash("3"), inputSha256: hash(canonical(rawInput)), normalizedInputSha256: hash(canonical(result)), resultSha256: hash("opaque original returned encoding"), outcome: "returned" };
function row(seq: number, eventType: string, payload: any, overrides: any = {}) {
const e = { schema: "paperclip.prp.event.v1", eventType, runId: "run", turnId: "turn", normalizedSessionId: "normalized", sourceInstanceId: "source", sourceKind: "runner", sourceSeq: seq, emittedAt: "2026-09-30T12:00:00Z", payload, ...overrides };
return { companyId: "company", runId: "run", seq, eventType, sourceInstanceId: e.sourceInstanceId, sourceSeq: e.sourceSeq, payload: { prpEvent: e } };
}
function notice(seq: number, toolCallId: string, status: string, fields: any = {}) {
return row(seq, "provider.notice.recorded", { schema: "paperclip.provider.notice.v1", category: "copilot_tool_evidence_v1", scope: "turn", provenance: { method: "session/update", eventType: "tool", sessionId: "native", turnId: "turn" }, details: Object.entries({ stage: "tool", toolCallId, status, ...fields }).map(([name, value]) => ({ name, value: String(value) })) });
}
function fixture() {
const rows = [notice(1, "command", "pending", { operation: "execute" }), notice(2, "finish-native", "pending"), row(3, "run.result.proposed", structuredClone(result), { itemId: "item-run" }),
row(4, "provider.notice.recorded", { schema: "paperclip.provider.notice.v1", category: "paperclip_semantic_tool_receipt_v2", scope: "turn", provenance: { method: "paperclip/semantic_tool_result", eventType: "semantic_result", sessionId: "native", turnId: "turn" }, details: Object.entries({ stage: "semantic_result", ...receipt }).map(([name, value]) => ({ name, value })) }),
notice(5, "finish-native", "completed", { semanticOperationId: receipt.operationId, semanticCallIdentitySha256: receipt.callIdentitySha256, semanticInputSha256: receipt.inputSha256, semanticNormalizedInputSha256: receipt.normalizedInputSha256, semanticResultSha256: receipt.resultSha256, semanticOutcome: receipt.outcome }),
row(6, "turn.completed", {}), row(7, "run.result.accepted", { result: structuredClone(result) }, { sourceKind: "control_plane", sourceInstanceId: "source:control", sourceSeq: 1 })];
const expected = { companyId: "company", runId: "run", turnId: "turn", nativeSessionId: "native", command: readCopilotToolEvidence(rows, "run")[0]!, summary: "EXACT-MARKER" };
return { rows, expected };
}
const frame = (r: any) => r.payload.prpEvent;
function setField(r: any, key: string, value: string) { frame(r).payload.details.find((d: any) => d.name === key).value = value; }
describe("Copilot semantic completion public-event oracle", () => {
it("attests the retained v15 context read before independently accepting its exact finish", async () => {
const retained = JSON.parse(await readFile(new URL("./fixtures/copilot-context-attached-completion-v15.json", import.meta.url), "utf8"));
const notices = readCopilotToolEvidence(retained.rows, retained.rows[0].runId);
const command = notices.find(n => n.operation === "execute" && n.status === "pending")!;
const proof = readCopilotSemanticCompletion(retained.rows, { companyId: retained.rows[0].companyId,
runId: command.runId, turnId: command.turnId, nativeSessionId: command.sessionId, command,
summary: retained.summary, requireContextRead: true });
expect(proof).toMatchObject({ schema: "paperclip.e2e.copilot-semantic-completion.v4", contextRead: { canonicalSeqs: expect.any(Array) } });
expect(proof.contextRead!.completedSeq).toBeLessThan(command.seq);
expect(onlyCopilotAttachedOperations(copilotActionNotices(notices, command, undefined, retained.rows), command, proof)).toBe(true);
for (const invalid of ["missing", "duplicate", "error", "foreign", "late", "mutating", "wrong-input", "missing-canonical", "failed-canonical", "native-mutation", "canonical-mutation", "not-read-only", "source-sequence-drift", "extra-context-call"]) {
const rows = structuredClone(retained.rows);
const receipt = rows.find((r: any) => r.seq === proof.contextRead!.receiptSeq)!;
if (invalid === "missing") rows.splice(rows.indexOf(receipt), 1);
if (invalid === "duplicate") rows.push(structuredClone(receipt));
if (invalid === "error") setField(receipt, "outcome", "error");
if (invalid === "foreign") frame(receipt).sourceInstanceId = "foreign";
if (invalid === "late") receipt.seq = command.seq + 1;
if (invalid === "mutating") setField(receipt, "operationId", "report_progress");
if (invalid === "wrong-input") setField(receipt, "inputSha256", hash("foreign"));
const canonical = rows.find((r: any) => r.seq === proof.contextRead!.canonicalSeqs.at(-1))!;
if (invalid === "missing-canonical") rows.splice(rows.indexOf(canonical), 1);
if (invalid === "failed-canonical") frame(canonical).payload.status = "failed";
if (invalid === "native-mutation") setField(rows.find((r: any) => r.seq === proof.contextRead!.pendingSeq), "operation", "edit");
if (invalid === "canonical-mutation") frame(canonical).payload.operation = "edit";
if (invalid === "not-read-only") frame(canonical).payload.readOnly = false;
if (invalid === "source-sequence-drift") { frame(canonical).sourceSeq = command.seq + 1; canonical.sourceSeq = command.seq + 1; }
if (invalid === "extra-context-call") rows.push(structuredClone(rows.find((r: any) => r.seq === proof.contextRead!.completedSeq)));
expect(() => readCopilotSemanticCompletion(rows, { companyId: rows[0].companyId,
runId: command.runId, turnId: command.turnId, nativeSessionId: command.sessionId, command,
summary: retained.summary, requireContextRead: true }), invalid).toThrow();
}
});
it("cannot qualify a historical finish without the now-required context read", () => {
const f = fixture();
expect(() => readCopilotSemanticCompletion(f.rows, { ...f.expected, requireContextRead: true })).toThrow("context read");
});
it("versions semantic completion and current-mainline denial settlement independently", () => {
const suite = runnerSuites.find(s => s.id === "copilot-protection")!;
expect(suite.definitionMetadata).toMatchObject({ version: 24, titleCreation: "explicit-search-composer", taskBinding: "browser-creation-response-id", remoteBootstrapContext: "already-exposed-dedicated-tool-no-http-substitution", semanticCompletionEvidence: "paperclip.e2e.copilot-semantic-completion.v4", denialSettlementEvidence: "paperclip.e2e.copilot-denial-settlement.v4" });
expect(suiteDefinitionHash(suite)).not.toBe(suiteDefinitionHash({ ...suite, definitionMetadata: { ...suite.definitionMetadata, version: 8 } }));
});
it("joins exact native lifecycle, authoritative callback, proposed content and accepted control-plane result", () => {
const { rows, expected } = fixture(); const proof = readCopilotSemanticCompletion(rows, expected);
expect(proof.nativeToolCallId).toBe("finish-native"); expect(proof.acceptedSeq).toBe(7); expect(proof.summarySha256).toBe(hash("EXACT-MARKER"));
expect(JSON.stringify(proof)).not.toContain("EXACT-MARKER");
});
it("binds distinct raw and production-normalized input digests without filling defaults in the oracle", () => {
const { rows, expected } = fixture();
expect(rawInput).not.toHaveProperty("schema");
expect(rawInput).not.toHaveProperty("artifacts");
expect(rawInput).not.toHaveProperty("attentionRequests");
expect(result).toMatchObject({ schema: "paperclip.run_result.v1", artifacts: [], attentionRequests: [] });
expect(receipt.inputSha256).not.toBe(receipt.normalizedInputSha256);
expect(readCopilotSemanticCompletion(rows, expected)).toMatchObject({
schema: "paperclip.e2e.copilot-semantic-completion.v2",
inputSha256: receipt.inputSha256, normalizedInputSha256: receipt.normalizedInputSha256,
});
// Same authenticated raw/native join is necessary but cannot substitute for
// the invocation-captured normalized body digest.
setField(rows[3], "normalizedInputSha256", receipt.inputSha256);
setField(rows[4], "semanticNormalizedInputSha256", receipt.inputSha256);
expect(() => readCopilotSemanticCompletion(rows, expected)).toThrow("canonical accepted result");
});
it.each(["missing", "null", "wrong", "uppercase", "malformed"])("rejects %s normalized finish digest", value => {
const f = fixture();
if (value === "missing") {
frame(f.rows[3]!).payload.details = frame(f.rows[3]!).payload.details.filter((d: any) => d.name !== "normalizedInputSha256");
frame(f.rows[4]!).payload.details = frame(f.rows[4]!).payload.details.filter((d: any) => d.name !== "semanticNormalizedInputSha256");
} else {
const digest = value === "null" ? "null" : value === "wrong" ? hash("foreign-normalized-input") : value === "uppercase" ? "A".repeat(64) : "not-a-digest";
setField(f.rows[3], "normalizedInputSha256", digest); setField(f.rows[4], "semanticNormalizedInputSha256", digest);
}
expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow();
});
it("allows an explicit null native digest as diagnostic data, never as successful finish authority", () => {
const f = fixture(); setField(f.rows[4], "semanticNormalizedInputSha256", "null");
expect(readCopilotToolEvidence(f.rows, "run").at(-1)?.semanticNormalizedInputSha256).toBeNull();
expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow("native receipt mismatch");
});
it.each(["only", "alongside-v2"])("rejects legacy v1 authority %s as fresh qualification", mode => {
const f = fixture(), old = structuredClone(f.rows[3]!);
frame(old).payload.category = "paperclip_semantic_tool_receipt_v1";
setField(old, "schema", "paperclip.semantic_tool_receipt.v1");
frame(old).payload.details = frame(old).payload.details.filter((d: any) => d.name !== "normalizedInputSha256");
if (mode === "only") f.rows[3] = old; else f.rows.push(old);
expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow();
});
it("does not repair an unnormalized proposed and accepted body by adding defaults", () => {
const f = fixture(); frame(f.rows[2]!).payload = structuredClone(rawInput); frame(f.rows[6]!).payload.result = structuredClone(rawInput);
expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow("canonical accepted result");
});
it.each([0, 1, 2, 3, 4, 5, 6])("rejects missing required row %s", index => { const f = fixture(); f.rows.splice(index, 1); expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); });
it.each([1, 2, 3, 4, 5, 6])("rejects duplicate required row %s", index => { const f = fixture(); f.rows.push(structuredClone(f.rows[index]!)); expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); });
it.each(["companyId", "runId"])("rejects foreign durable %s", key => { const f = fixture(); (f.rows[3] as any)[key] = "foreign"; expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); });
it.each(["turnId", "normalizedSessionId", "sourceInstanceId", "sourceKind", "eventType", "schema"])("rejects foreign or malformed envelope %s", key => {
for (const index of [1, 2, 3, 4, 5, 6]) { const f = fixture(); (frame(f.rows[index]!))[key] = "foreign"; expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); }
});
it.each([null, undefined])("rejects missing envelope turn %s even with native provenance intact", turn => { const f = fixture(); frame(f.rows[4]!).turnId = turn; expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); });
it.each(["sessionId", "turnId", "method", "eventType"])("rejects authoritative provenance %s mismatch", key => { const f = fixture(); frame(f.rows[3]!).payload.provenance[key] = "foreign"; expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); });
it.each(["callIdentitySha256", "inputSha256", "normalizedInputSha256", "resultSha256", "operationId", "outcome"])("rejects native %s disagreement", key => { const f = fixture(); setField(f.rows[4], `semantic${key[0]!.toUpperCase()}${key.slice(1)}`, key.endsWith("Sha256") ? "a".repeat(64) : "wrong"); expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); });
it("does not infer acceptance from returned receipt or a tool named paperclip_finish", () => {
const f = fixture(); frame(f.rows[6]!).payload.result = { accepted: false, summary: "EXACT-MARKER" }; expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow();
const g = fixture(); frame(g.rows[4]!).payload.title = "paperclip_finish"; frame(g.rows[4]!).payload.details = frame(g.rows[4]!).payload.details.filter((d: any) => !d.name.startsWith("semantic")); expect(() => readCopilotSemanticCompletion(g.rows, g.expected)).toThrow();
});
it.each(["failed", "cancelled", "interrupted"])("rejects %s terminal", status => { const f = fixture(); f.rows[5]!.eventType = `turn.${status}`; frame(f.rows[5]!).eventType = `turn.${status}`; expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); });
it("rejects changed accepted body, forged call ID, wrong summary and rejected result", () => {
for (const mutate of [(f: ReturnType<typeof fixture>) => { frame(f.rows[6]!).payload.result.completionClaim.remainingWork.push("unfinished"); }, (f: ReturnType<typeof fixture>) => { setField(f.rows[3], "callIdentitySha256", hash("foreign-call")); }, (f: ReturnType<typeof fixture>) => { f.expected.summary = "other"; }, (f: ReturnType<typeof fixture>) => { f.rows.push(row(8, "run.result.rejected", {})); }]) { const f = fixture(); mutate(f); expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); }
});
it("rejects duplicate/unknown/oversized receipt details and partial native fields", () => {
for (const mutate of [(r: any) => frame(r).payload.details.push({ name: "secret", value: "untrusted" }), (r: any) => frame(r).payload.details.push(frame(r).payload.details[0]), (r: any) => setField(r, "operationId", "x".repeat(300))]) { const f = fixture(); mutate(f.rows[3]); expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); }
const f = fixture(); frame(f.rows[4]!).payload.details.pop(); expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow();
});
it("rejects mutation metadata, extra lifecycle, reordered receipt and source sequence drift", () => {
for (const mutate of [(f: ReturnType<typeof fixture>) => frame(f.rows[1]!).payload.details.push({ name: "operation", value: "edit" }), (f: ReturnType<typeof fixture>) => f.rows.push(notice(8, "finish-native", "pending")), (f: ReturnType<typeof fixture>) => { f.rows[3]!.seq = 8; }, (f: ReturnType<typeof fixture>) => { frame(f.rows[3]!).sourceSeq = 20; f.rows[3]!.sourceSeq = 20; }, (f: ReturnType<typeof fixture>) => { frame(f.rows[1]!).sourceSeq = 20; f.rows[1]!.sourceSeq = 20; }]) { const f = fixture(); mutate(f); expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow(); }
});
it("does not treat canonical run-level itemId as semantic call identity", () => {
for (const itemId of ["item-run", "3", "unrelated-item", null]) {
const f = fixture(); frame(f.rows[2]!).itemId = itemId;
expect(readCopilotSemanticCompletion(f.rows, f.expected).callIdentitySha256).toBe(receipt.callIdentitySha256);
}
});
it("rejects a different finish input even when proposal and acceptance agree", () => {
const f = fixture(); frame(f.rows[2]!).payload.completionClaim.criteria[0].evidenceRefs.push("different");
frame(f.rows[6]!).payload.result = structuredClone(frame(f.rows[2]!).payload);
expect(() => readCopilotSemanticCompletion(f.rows, f.expected)).toThrow();
});
it("accepts the retained shell-read ordering: pending has shellId only, completion gains command identity after finish", () => {
const f = attachedFixture();
expect(f.notices.find(n => n.toolCallId === "shell-read" && n.status === "pending")?.commandToolCallId).toBeUndefined();
expect(onlyCopilotAttachedOperations(f.notices, f.command, f.proof)).toBe(true);
});
it("rejects waiting on read_bash before attempting finish", () => {
const f = attachedFixture();
f.notices.find(n => n.toolCallId === "shell-read" && n.status === "pending")!.seq = 16;
expect(onlyCopilotAttachedOperations(f.notices, f.command, f.proof)).toBe(false);
});
it("requires an independently observed exit strictly after the finish attempt", () => {
const f = attachedFixture(), at = f.proof.nativePendingObservedAtMs;
expect(copilotFinishAttemptBeforeCommandExit(f.proof, at + 1)).toBe(true);
for (const exitAt of [at - 1, at, NaN, Infinity]) expect(copilotFinishAttemptBeforeCommandExit(f.proof, exitAt)).toBe(false);
});
it("releases the fixture only after a matching native finish receipt", () => {
const f = attachedFixture();
expect(copilotAttachedFinishReady(f.notices, f.command)).toMatchObject({ toolCallId: f.proof.nativeToolCallId, status: "pending" });
for (const changed of [{ turnId: "foreign" }, { sessionId: "foreign" }, { semanticOutcome: "error" }]) {
const partial = f.notices.map(n => n.semanticOperationId === "paperclip_finish" ? { ...n, ...changed } : n);
expect(copilotAttachedFinishReady(partial as any, f.command)).toBeUndefined();
}
const incomplete = f.notices.filter(n => !(n.toolCallId === f.proof.nativeToolCallId && n.status === "pending"));
expect(() => copilotAttachedFinishReady(incomplete, f.command)).toThrow("matching finish origin");
});
it.each(["", " ", "\t ", " "])("releases an accepted whitespace-prefixed command through the same finish gate: %j", prefix => {
const f = attachedFixture(), command = "printf fixture";
const nativeDigest = `sha256:${hash(prefix + command)}`;
for (const n of f.notices.filter(n => n.toolCallId === f.command.toolCallId)) n.commandSha256 = nativeDigest;
const matched = findCopilotFixtureCommand(f.notices, command);
expect(matched?.match.leadingWhitespace).toBe(prefix);
expect(copilotAttachedFinishReady(f.notices, matched!.call)?.toolCallId).toBe(f.proof.nativeToolCallId);
expect(findCopilotFixtureCommand(f.notices, command + " changed")).toBeNull();
});
it("accepts bounded in-progress shell updates without inventing terminal command identity", () => {
const f = attachedFixture(), pending = f.notices.find(n => n.toolCallId === "shell-read" && n.status === "pending")!;
f.notices.push({ ...pending, status: "in_progress", seq: 53 });
expect(onlyCopilotAttachedOperations(f.notices, f.command, f.proof)).toBe(true);
});
it("rejects shell-read evidence from a different durable stream despite matching native identity", () => {
const f = attachedFixture(), r = f.rows.find(r => r.seq === 52)!;
frame(r).sourceInstanceId = "foreign"; r.sourceInstanceId = "foreign";
expect(() => readCopilotSemanticCompletion(f.rows, { companyId: "company", runId: "run", turnId: "turn", nativeSessionId: "native", command: f.command, summary: "EXACT-MARKER" })).toThrow();
});
it.each(["missing-pending", "missing-terminal", "duplicate-pending", "duplicate-terminal", "extra-completed-only", "extra-complete-read", "wrong-shell", "wrong-command", "failed", "nonzero", "reordered", "late", "wrong-operation", "mutation", "read-path", "foreign-session", "foreign-turn", "foreign-run", "permission", "semantic-fields", "normalized-semantic-field"])("rejects invalid shell-read lifecycle: %s", failure => {
const f = attachedFixture(), start = f.notices.find(n => n.toolCallId === "shell-read" && n.status === "pending")!, end = f.notices.find(n => n.toolCallId === "shell-read" && n.status === "completed")!;
if (failure === "missing-pending") f.notices.splice(f.notices.indexOf(start), 1);
if (failure === "missing-terminal") f.notices.splice(f.notices.indexOf(end), 1);
if (failure === "duplicate-pending") f.notices.push({ ...start, seq: 53 });
if (failure === "duplicate-terminal") f.notices.push({ ...end, seq: 56 });
if (failure === "extra-completed-only") f.notices.push({ ...end, toolCallId: "extra", seq: 57 });
if (failure === "extra-complete-read") f.notices.push({ ...start, toolCallId: "extra", seq: 56 }, { ...end, toolCallId: "extra", seq: 57 });
if (failure === "wrong-shell") start.shellId = "foreign";
if (failure === "wrong-command") end.commandToolCallId = "foreign";
if (failure === "failed") end.status = "failed";
if (failure === "nonzero") end.exitCode = 1;
if (failure === "reordered") start.seq = 14;
if (failure === "late") end.seq = 61;
if (failure === "wrong-operation") start.operation = "execute";
if (failure === "mutation") end.target = "file.txt";
if (failure === "read-path") start.readTargetSha256 = `sha256:${"a".repeat(64)}`;
if (failure === "foreign-session") start.sessionId = "foreign";
if (failure === "foreign-turn") start.turnId = "foreign";
if (failure === "foreign-run") start.runId = "foreign";
if (failure === "permission") start.stage = "permission_requested";
if (failure === "semantic-fields") end.semanticCallIdentitySha256 = receipt.callIdentitySha256;
if (failure === "normalized-semantic-field") end.semanticNormalizedInputSha256 = receipt.normalizedInputSha256;
expect(onlyCopilotAttachedOperations(f.notices, f.command, f.proof)).toBe(false);
});
it("rejects duplicate shell origins and arbitrary extra operations", () => {
const f = attachedFixture();
const started = f.notices.find(n => n.shellState === "started")!;
expect(onlyCopilotAttachedOperations([...f.notices, { ...started, seq: 16 }], f.command, f.proof)).toBe(false);
for (const operation of [undefined, "read", "edit", "execute"] as const) expect(onlyCopilotAttachedOperations([...f.notices, { ...f.command, toolCallId: "extra", operation, seq: 17 }], f.command, f.proof)).toBe(false);
});
it("keeps actual flow correlation before no-extra-operation gate and keeps visible marker independent", async () => {
const source = await readFile(new URL("./copilot-protection-flow.ts", import.meta.url), "utf8");
expect(source.indexOf("readCopilotSemanticCompletion(runEvents")).toBeLessThan(source.indexOf('check("no-extra-native-operation", onlyCopilotAttachedOperations('));
expect(source).toContain("undefined, runEvents), call!, semantic)");
expect(source).toContain('check("exact-completion-marker", comments.filter');
expect(source).not.toContain('if (remote) check("no-extra-native-operation"');
});
});
// Mirrors retained native order: command pending→shell started; finish; then
// read_bash pending(shellId only)→completed(commandToolCallId), before turn end.
function attachedFixture() {
const f = fixture(); frame(f.rows[2]!).itemId = "3";
for (const r of f.rows) { r.seq *= 10; if (frame(r).sourceKind === "runner") { r.sourceSeq *= 10; frame(r).sourceSeq *= 10; } }
const fields = { operation: "execute", commandSha256: `sha256:${"a".repeat(64)}`, mode: "async", detach: false };
f.rows[0] = notice(10, "command", "pending", fields);
f.rows.push(notice(15, "command", "completed", { ...fields, shellId: "0", commandToolCallId: "command", shellState: "started" }),
notice(52, "shell-read", "pending", { operation: "read", shellId: "0" }),
notice(55, "shell-read", "completed", { operation: "read", shellId: "0", commandToolCallId: "command", shellState: "completed", exitCode: 0 }));
const notices = readCopilotToolEvidence(f.rows, "run"), command = notices.find(n => n.seq === 10)!;
const proof = readCopilotSemanticCompletion(f.rows, { ...f.expected, command });
return { rows: f.rows, notices, command, proof };
}