From 477323e4e8ca5d2209202bc90b980d6423183509 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:39:05 -0600 Subject: [PATCH] fix(evals): attribute native saved-skill library reads (#23611) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Product E2E tests check that agents use saved skills and save the correct result. > - The saved-skill test binds a native source read to an exact skill version and run. > - The native library tool can return the complete source through `paperclip_load_skill`. > - The test did not recognize this tool result, so it rejected a successful read. > - This pull request adds a closed check for that result and preserves the independent output checks. ## Linked Issues or Issue Description **What happened?** The saved-skill journey rejected a successful native OpenCode library read. Its receipt list was empty. The proxy reports `operation: unknown` and `readOnly: false` for this tool. Retained event payloads can also omit null targets. **Expected behavior** A complete source read must qualify when the saved skill, immutable version, source bytes, admitted assignment and native call all agree. Failed, partial, copied or foreign results must fail. **Steps to reproduce** Run the new library-loader test against the old parser. The valid start/progress/completion case returns no receipt. The test expects one receipt. The new retained-event case also fails before support for omitted null targets. Related public repairs: #22813 fixes assigned-skill name resolution. [Cloud #1135](https://github.com/paperclipai/paperclip-cloud/pull/1135) reports ordinary saved-skill assignment. Neither adds this evidence path. ## What Changed - Carry the saved skill ID with the selected key and version. - Accept the native OpenCode library result only with matching IDs, key, version, full source, SHA-256, byte count and complete single-file inventory. - Require the actual run, runner, native session, turn, item and one ordered start/completion pair. Allow progress events between them. Allow absent or null targets. Reject a supplied path. - Share native run admission across the library, OpenCode loader and Codex paths. Share the two OpenCode loaders' ordered call checks. - Preserve literal numeric prefixes in verified source text. Remove display line numbers only from file-reader output. - Add negative cases and full-flow cases for the source read and independent output checks. Document the accepted evidence. ## Verification - Red: the valid library read returned an empty receipt list against the old parser. - Red: the retained event shape with omitted null targets failed before that case was supported. - Red: six new library and assigned-source cases with literal `1: `, `2|` and `3→` prefixes fail before the review fix. Native and provider skill-loader cases also cover these prefixes. - Green: five focused saved-skill test files pass, with 279 tests. - Replay of retained private events: the old receipt list is empty; the fixed parser returns one receipt for the original completed event. Private data stays out of this PR. - `pnpm test:e2e:runner:typecheck` passed for the final files. The test fixture uses mutable row types for its negative cases. - `pnpm verify` could not select tests because the managed Git storage guard rejected `git ls-files`. The focused tests ran directly. - [Required CI](https://github.com/paperclipai/paperclip/actions/runs/47113067897) passes on c34ad477. The typecheck, all four runner-support shards, static checks and all six runner package shards pass. The path selector skips Build and unrelated suites for this test-only change. - Greptile, Feynman and Ponytail each give the current head 5/5. All four prior review threads are resolved. - After merge, run only `saved-skill-use` in the QA staging workflow. The original failed run remains failed. ## Risks The main risk is a false positive from copied or incomplete tool output. The new path requires a specific built-in tool, exact source identity and bytes, the admitted version and a unique paired native call. Existing file-read and Codex checks remain unchanged. Independent document content, revision author, reload and source-preservation checks still apply. No runtime behavior, schema, migration or selected test plan changes. ## Model Used OpenAI Codex, GPT-6, with reasoning, 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 --------- Co-authored-by: Paperclip --- .../saved-skill-use-evidence.test.ts | 23 +++- .../saved-skill-use-evidence.ts | 123 ++++++++++++------ .../saved-skill-use-flow.test.ts | 30 ++++- .../saved-skill-use-library-loader.test.ts | 111 ++++++++++++++++ .../saved-skill-use-native-loader.test.ts | 14 +- .../product-journeys/saved-skill-use.md | 14 ++ 6 files changed, 273 insertions(+), 42 deletions(-) create mode 100644 tests/runner-e2e/product-journeys/saved-skill-use-library-loader.test.ts diff --git a/tests/runner-e2e/product-journeys/saved-skill-use-evidence.test.ts b/tests/runner-e2e/product-journeys/saved-skill-use-evidence.test.ts index 3841766ef97..ed6009dde54 100644 --- a/tests/runner-e2e/product-journeys/saved-skill-use-evidence.test.ts +++ b/tests/runner-e2e/product-journeys/saved-skill-use-evidence.test.ts @@ -6,7 +6,7 @@ import { savedSkillDocumentAttributed, savedSkillFixture, savedSkillReadAssignme type Row = Record; const fixture = savedSkillFixture("campaign-id", "62ff548dfec748da8fef6d5fbf6cc23d"); const binding = { companyId: "company", agentId: "agent", issueId: "issue", runId: "run" }; -const assignment = { key: `company/${binding.companyId}/${fixture.slug}`, versionId: "version" }; +const assignment = { skillId: "skill", key: `company/${binding.companyId}/${fixture.slug}`, versionId: "version" }; function native(seq: number, eventType: string, payload: Row): Row { return { ...binding, seq, eventType, protocolSchemaVersion: 1, sourceSeq: seq, sourceInstanceId: "runner-instance", sourceEventId: `event-${seq}`, payload: { prpEvent: { schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: binding.runId, @@ -136,6 +136,17 @@ describe("saved skill use evidence", () => { expect(savedSkillReadReceipts(assignedReadEvents(), binding, fixture, runtimeName, { ...assignment, key: "foreign" })).toEqual([]); expect(savedSkillReadReceipts(assignedReadEvents(), binding, fixture, runtimeName, { ...assignment, versionId: "foreign" })).toEqual([]); }); + it.each(["1: ", "2|", "3→"])("preserves literal assigned-source prefixes %s", prefix => { + const procedure = `${prefix}${fixture.procedure}`; + const sourceFixture = { ...fixture, procedure, markdown: fixture.markdown.replace(fixture.procedure, procedure) }; + const events = assignedReadEvents(); + changeAssignedResult(events, r => { + r.text = sourceFixture.markdown; r.byteSize = Buffer.byteLength(r.text); + r.sha256 = createHash("sha256").update(r.text).digest("hex"); + }); + const payload = events[1]!.payload.prpEvent.payload; payload.outputBytes = Buffer.byteLength(payload.output); + expect(savedSkillReadReceipts(events, binding, sourceFixture, runtimeName, assignment)).toHaveLength(1); + }); it.each([{ kind: "codex" }, { kind: "acpx", agent: "cursor" }, { kind: "cursor_cloud" }])( "binds the semantic source to common native skill entries for %j while preserving the OpenCode file guard", provider => { const { skill } = source(); @@ -271,6 +282,16 @@ describe("saved skill use evidence", () => { expect(savedSkillReadReceipts(wrong, binding, fixture)).toEqual([]); } }); + it.each(["1: ", "2|", "3→"])("preserves literal provider skill procedure prefixes %s", prefix => { + const procedure = `${prefix}${fixture.procedure}`; + const sourceFixture = { ...fixture, procedure, markdown: fixture.markdown.replace(fixture.procedure, procedure) }; + const events = ["pending", "completed"].map((status, index) => { + const event = canonicalProviderEventsFromOpenCodePart({ id: "load-skill", type: "tool", tool: "skill", + state: { status, output: `\n${procedure}\n` } })[0]!; + return native(index + 1, event.eventType, event.payload); + }); + expect(savedSkillReadReceipts(events, binding, sourceFixture)).toHaveLength(1); + }); it("allows known file-reader line prefixes without treating partial output as a complete read", () => { const events = readEvents(); events[1]!.payload.prpEvent.payload.output = fixture.markdown.split("\n").map((line, i) => `${i + 1}: ${line}`).join("\n"); diff --git a/tests/runner-e2e/product-journeys/saved-skill-use-evidence.ts b/tests/runner-e2e/product-journeys/saved-skill-use-evidence.ts index ed8df09cd5f..1075c0bb3a8 100644 --- a/tests/runner-e2e/product-journeys/saved-skill-use-evidence.ts +++ b/tests/runner-e2e/product-journeys/saved-skill-use-evidence.ts @@ -51,7 +51,7 @@ export function savedSkillResultMatches(body: unknown, expected: SavedSkillFixtu } catch { return false; } } -export interface SavedSkillReadAssignment { key: string; versionId: string } +export interface SavedSkillReadAssignment { key: string; versionId: string; skillId?: string } /** All native providers share the canonical skill/version selection contract. */ export function savedSkillReadAssignment(skill: Row, assignments: Row, run: Row): SavedSkillReadAssignment | undefined { @@ -66,7 +66,8 @@ export function savedSkillReadAssignment(skill: Row, assignments: Row, run: Row) || !versions || typeof versions !== "object" || Array.isArray(versions) || !Object.hasOwn(versions, skill.key) || versions[skill.key] !== skill.currentVersionId || assigned[0].versionId !== skill.currentVersionId || native[0].versionId !== skill.currentVersionId) return undefined; - return { key: skill.key, versionId: skill.currentVersionId }; + return { key: skill.key, versionId: skill.currentVersionId, + ...(typeof skill.id === "string" && skill.id.trim() ? { skillId: skill.id } : {}) }; } /** OpenCode's file wrapper also needs the exact materialized directory identity. */ @@ -96,28 +97,83 @@ function assignedSkillReadText(output: string, binding: NativePrpRunBinding, fix } catch { return undefined; } } +/** Shared run admission; provider-specific receipts validate their own payloads. */ +function admittedNativeSkill(binding: NativePrpRunBinding, fixture: SavedSkillFixture, + assignment: SavedSkillReadAssignment | undefined, run: Row | undefined): Row | undefined { + const input = run?.runnerProfileJson?.nativeExecutionInput; + const skills = Array.isArray(input?.runtimeContext?.skills) + ? input.runtimeContext.skills.filter((skill: Row) => skill.key === assignment?.key) : []; + if (!run || run.runtimeMode !== "native" + || run.id !== binding.runId || run.companyId !== binding.companyId || run.agentId !== binding.agentId + || typeof run.runnerInstanceId !== "string" || !run.runnerInstanceId.trim() + || typeof run.nativeSessionId !== "string" || !run.nativeSessionId.trim() + || !assignment || assignment.key !== `company/${binding.companyId}/${fixture.slug}` + || typeof assignment.versionId !== "string" || !assignment.versionId.trim() + || skills.length !== 1 || skills[0].versionId !== assignment.versionId + || run.contextSnapshot?.skillSelectionSnapshot !== true + || run.contextSnapshot?.skillVersions?.[assignment.key] !== assignment.versionId) return undefined; + return skills[0]; +} + +/** Unknown-operation OpenCode loaders require one complete, ordered native call. */ +function nativeOpenCodeSkillCall(row: Row, bound: Row[], binding: NativePrpRunBinding, fixture: SavedSkillFixture, + assignment: SavedSkillReadAssignment | undefined, run: Row | undefined): Row | undefined { + const skill = admittedNativeSkill(binding, fixture, assignment, run); + const event = row.payload.prpEvent, payload = event.payload; + if (!skill || run?.runnerProfileJson?.nativeExecutionInput?.provider?.kind !== "opencode" + || event.sourceInstanceId !== run.runnerInstanceId || event.normalizedSessionId !== run.nativeSessionId + || typeof event.itemId !== "string" || !event.itemId.trim() || !Number.isSafeInteger(row.seq) + || payload.operation !== "unknown" || payload.readOnly !== false || payload.target != null) return undefined; + const pair = bound.filter(candidate => ["tool.execution.started", "tool.execution.completed"].includes(candidate.payload.prpEvent.eventType) + && candidate.payload.prpEvent.payload?.executionId === payload.executionId); + const start = pair.find(candidate => candidate.payload.prpEvent.eventType === "tool.execution.started"); + const initial = start?.payload.prpEvent, p = initial?.payload; + if (pair.length !== 2 || !start || !Number.isSafeInteger(start.seq) || start.seq >= row.seq + || initial.sourceSeq >= event.sourceSeq || initial.sourceInstanceId !== event.sourceInstanceId + || initial.normalizedSessionId !== event.normalizedSessionId || initial.turnId !== event.turnId || initial.itemId !== event.itemId + || p?.schema !== payload.schema || p.name !== payload.name || p.transport !== payload.transport + || p.operation !== payload.operation || p.status !== "running" || p.readOnly !== false || p.target != null) return undefined; + return skill; +} + +/** The native library loader returns the immutable source through Core's read API. + * OpenCode's proxy reports unknown/false for this tool too. Those hints alone + * prove nothing: require the admitted version, exact saved source and paired call. + */ +function nativeLibrarySkillLoad(row: Row, bound: Row[], binding: NativePrpRunBinding, fixture: SavedSkillFixture, + assignment: SavedSkillReadAssignment | undefined, run: Row | undefined): string | undefined { + const payload = row.payload.prpEvent.payload; + if (!assignment || typeof assignment.skillId !== "string" || !assignment.skillId.trim() + || payload.name !== "paperclip_load_skill" + || !nativeOpenCodeSkillCall(row, bound, binding, fixture, assignment, run)) return undefined; + try { + const wrapper = JSON.parse(payload.output); + if (wrapper?.type !== "inputText" || typeof wrapper.text !== "string" + || Object.keys(wrapper).sort().join(",") !== "text,type") return undefined; + const result = JSON.parse(wrapper.text); + if (result?.id !== assignment.skillId || result.skillId !== assignment.skillId || result.key !== assignment.key + || result.versionId !== assignment.versionId || result.name !== fixture.name || result.slug !== fixture.slug + || result.sourceType !== "managed" || result.path !== "SKILL.md" || result.nextOffset !== null + || result.text !== fixture.markdown || result.byteSize !== Buffer.byteLength(fixture.markdown) + || result.sha256 !== createHash("sha256").update(fixture.markdown).digest("hex") + || result.outcome !== undefined || result.fileCount !== 1 || result.nextFileOffset !== null + || !Array.isArray(result.files) || result.files.length !== 1 + || result.files[0]?.path !== "SKILL.md" || result.files[0]?.kind !== "skill") return undefined; + return result.text; + } catch { return undefined; } +} + /** OpenCode's proxy forwards the builtin skill loader without an operation. * Core091 therefore records unknown/false even though the loader exposes its saved body. * Only this complete, immutable-version-bound native loader may use that shape. */ function nativeOpenCodeSkillLoad(row: Row, bound: Row[], binding: NativePrpRunBinding, fixture: SavedSkillFixture, runtimeName: string | undefined, assignment: SavedSkillReadAssignment | undefined, run: Row | undefined): boolean { - const event = row.payload.prpEvent, payload = event.payload, input = run?.runnerProfileJson?.nativeExecutionInput; - const skills = Array.isArray(input?.runtimeContext?.skills) - ? input.runtimeContext.skills.filter((skill: Row) => skill.key === assignment?.key) : []; - if (!run || run.runtimeMode !== "native" || input?.provider?.kind !== "opencode" - || run.id !== binding.runId || run.companyId !== binding.companyId || run.agentId !== binding.agentId - || typeof run.runnerInstanceId !== "string" || !run.runnerInstanceId.trim() - || typeof run.nativeSessionId !== "string" || !run.nativeSessionId.trim() - || event.sourceInstanceId !== run.runnerInstanceId || event.normalizedSessionId !== run.nativeSessionId - || typeof event.itemId !== "string" || !event.itemId.trim() || !Number.isSafeInteger(row.seq) - || !assignment || assignment.key !== `company/${binding.companyId}/${fixture.slug}` - || typeof assignment.versionId !== "string" || !assignment.versionId.trim() - || skills.length !== 1 || skills[0].versionId !== assignment.versionId || skills[0].runtimeName !== runtimeName - || run.contextSnapshot?.skillSelectionSnapshot !== true - || run.contextSnapshot?.skillVersions?.[assignment.key] !== assignment.versionId + const payload = row.payload.prpEvent.payload; + const skill = nativeOpenCodeSkillCall(row, bound, binding, fixture, assignment, run); + if (!skill || skill.runtimeName !== runtimeName || typeof runtimeName !== "string" || !/^[a-z0-9][a-z0-9_-]*$/i.test(runtimeName) - || payload.name !== "skill" || payload.operation !== "unknown" || payload.readOnly !== false || payload.target !== null) return false; + || payload.name !== "skill") return false; const wrapper = /^\r\n]+)">\n# Skill: ([^\r\n]+)\n\n([\s\S]*?)\n\nBase directory for this skill: ([^\r\n]+)\n([\s\S]*)\n<\/skill_content>\s*$/.exec(payload.output); if (!wrapper || wrapper[1] !== fixture.slug || wrapper[2] !== fixture.slug || wrapper[3] !== fixture.procedure.trim() || !/\s*<\/skill_files>/.test(wrapper[5]!) @@ -130,13 +186,7 @@ function nativeOpenCodeSkillLoad(row: Row, bound: Row[], binding: NativePrpRunBi if (!path.startsWith("/") || /[\\\u0000-\u001f\u007f?#]/.test(path) || /%[a-f0-9]{2}/i.test(path) || path.split("/").some(part => part === "." || part === "..") || !path.replace(/\/$/, "").endsWith(`/.claude/skills/${runtimeName}`)) return false; - const pair = bound.filter(candidate => ["tool.execution.started", "tool.execution.completed"].includes(candidate.payload.prpEvent.eventType) - && candidate.payload.prpEvent.payload?.executionId === payload.executionId); - const start = pair.find(candidate => candidate.payload.prpEvent.eventType === "tool.execution.started"); - const initial = start?.payload.prpEvent, initialPayload = initial?.payload; - return Boolean(pair.length === 2 && start && Number.isSafeInteger(start.seq) && start.seq < row.seq - && initial.sourceSeq < event.sourceSeq && initial.normalizedSessionId === event.normalizedSessionId && initial.itemId === event.itemId - && initialPayload?.readOnly === false && initialPayload.target === null); + return true; } // Core091 provider_bridge.rs hashes UTF-8 JSON with object keys ordered by UTF-16. @@ -154,17 +204,8 @@ function semanticDigest(value: unknown): string { */ function codexAssignedSkillReceipts(bound: Row[], binding: NativePrpRunBinding, fixture: SavedSkillFixture, assignment: SavedSkillReadAssignment | undefined, run: Row | undefined) { - const input = run?.runnerProfileJson?.nativeExecutionInput; - const skills = Array.isArray(input?.runtimeContext?.skills) - ? input.runtimeContext.skills.filter((skill: Row) => skill.key === assignment?.key) : []; - if (!run || run.runtimeMode !== "native" || input?.provider?.kind !== "codex" - || run.id !== binding.runId || run.companyId !== binding.companyId || run.agentId !== binding.agentId - || typeof run.runnerInstanceId !== "string" || !run.runnerInstanceId.trim() - || typeof run.nativeSessionId !== "string" || !run.nativeSessionId.trim() - || !assignment || assignment.key !== `company/${binding.companyId}/${fixture.slug}` || !assignment.versionId - || skills.length !== 1 || skills[0].versionId !== assignment.versionId - || run.contextSnapshot?.skillSelectionSnapshot !== true - || run.contextSnapshot?.skillVersions?.[assignment.key] !== assignment.versionId + const skill = admittedNativeSkill(binding, fixture, assignment, run); + if (!skill || !run || !assignment || run.runnerProfileJson?.nativeExecutionInput?.provider?.kind !== "codex" || !fixture.markdown.includes(fixture.procedure.trim()) || !fixture.markdown.includes(fixture.expected.reference)) return []; const expected = { skill: assignment.key, versionId: assignment.versionId, path: "SKILL.md", text: fixture.markdown, sha256: createHash("sha256").update(fixture.markdown, "utf8").digest("hex"), @@ -194,8 +235,8 @@ function codexAssignedSkillReceipts(bound: Row[], binding: NativePrpRunBinding, const initial = semantic(start)!, args = initial.input; if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some(key => !["skill", "path", "offset"].includes(key)) - || !(args.skill === assignment.key || typeof skills[0].runtimeName === "string" - && skills[0].runtimeName.trim() && args.skill === skills[0].runtimeName) + || !(args.skill === assignment.key || typeof skill.runtimeName === "string" + && skill.runtimeName.trim() && args.skill === skill.runtimeName) || Object.hasOwn(args, "path") && args.path !== "SKILL.md" || Object.hasOwn(args, "offset") && args.offset !== 0 || !content(initial, semanticDigest(args))) return []; // Duplicates, reconciled alternatives and foreign same-call carriers cannot supply a second interpretation. @@ -251,9 +292,13 @@ export function savedSkillReadReceipts(events: Row[], binding: NativePrpRunBindi && assignment?.key === `company/${binding.companyId}/${fixture.slug}` && typeof assignment.versionId === "string" && assignment.versionId.trim() ? assignedSkillReadText(payload.output, binding, fixture, assignment.versionId) : undefined; - if (!reading && !loading && !nativeLoading && !wrappedRead && assignedText === undefined) return false; + const libraryText = nativeLibrarySkillLoad(row, bound, binding, fixture, assignment, run); + if (!reading && !loading && !nativeLoading && !wrappedRead && assignedText === undefined && libraryText === undefined) return false; // File readers may prefix each source line with its line number. - const output = (assignedText ?? (wrappedRead ? wrapped![2]! : payload.output)).split("\n").map((line: string) => line.replace(/^\s*\d+(?:[:|]|→)\s?/, "")).join("\n"); + const readerOutput = wrappedRead ? wrapped![2]! : payload.output; + const output = libraryText ?? assignedText ?? ((reading || wrappedRead) + ? readerOutput.split("\n").map((line: string) => line.replace(/^\s*\d+(?:[:|]|→)\s?/, "")).join("\n") + : payload.output); if (!output.includes(fixture.procedure.trim())) return false; return bound.some(start => { const initial = start.payload.prpEvent, p = initial.payload; diff --git a/tests/runner-e2e/product-journeys/saved-skill-use-flow.test.ts b/tests/runner-e2e/product-journeys/saved-skill-use-flow.test.ts index 266d07514f5..a37c57d6af2 100644 --- a/tests/runner-e2e/product-journeys/saved-skill-use-flow.test.ts +++ b/tests/runner-e2e/product-journeys/saved-skill-use-flow.test.ts @@ -22,7 +22,7 @@ const directories: string[] = []; afterEach(async () => { vi.clearAllMocks(); await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true }))); }); async function setup(change: (kind: string, row: any) => any = (_kind, row) => row, campaignId = "campaign", betaSkillsEnabled = false, - wrappedRead: boolean | "assigned" | "codex" = false) { + wrappedRead: boolean | "assigned" | "codex" | "library" = false) { const directory = await mkdtemp(path.join(os.tmpdir(), "saved-skill-flow-")); directories.push(directory); let fixture: SavedSkillFixture; let skill: Row, assigned = false, issueCreated = false, reloaded = false; @@ -110,9 +110,19 @@ async function setup(change: (kind: string, row: any) => any = (_kind, row) => r Object.assign(p.payload, { name: "paperclip_read_assigned_skill", operation: "unknown", readOnly: true, target: null, output: status === "completed" ? output : "", outputBytes: status === "completed" ? Buffer.byteLength(output) : 0 }); } + if (wrappedRead === "library") { + const result = { id: skill.id, skillId: skill.id, key: skill.key, name: fixture.name, slug: fixture.slug, + sourceType: "managed", versionId: skill.currentVersionId, path: "SKILL.md", text: fixture.markdown, + sha256: createHash("sha256").update(fixture.markdown).digest("hex"), byteSize: Buffer.byteLength(fixture.markdown), + nextOffset: null, fileCount: 1, files: [{ kind: "skill", path: "SKILL.md" }], nextFileOffset: null }; + const output = JSON.stringify({ type: "inputText", text: JSON.stringify(change("library-read", result)) }); + Object.assign(p.payload, { name: "paperclip_load_skill", operation: "unknown", readOnly: false, target: null, + output: status === "completed" ? output : "", outputBytes: status === "completed" ? Buffer.byteLength(output) : 0 }); + } return change("event", { runId: "run", companyId: "company", agentId: "agent", seq: i + 1, eventType: p.eventType, sourceEventId: `event-${i}`, sourceInstanceId: "instance", sourceSeq: i + 1, protocolSchemaVersion: 1, payload: { prpEvent: { schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: "run", turnId: "turn", + ...(wrappedRead === "library" ? { normalizedSessionId: "session", itemId: "item" } : {}), eventType: p.eventType, sourceEventId: `event-${i}`, sourceInstanceId: "instance", sourceSeq: i + 1, payload: p.payload } } }); }); } @@ -142,6 +152,24 @@ async function setup(change: (kind: string, row: any) => any = (_kind, row) => r } describe("saved skill journey orchestration", () => { + it("verifies all seven checks after a native library load", async () => { + const f = await setup(undefined, "campaign", false, "library"); await f.run(); + expect(f.evidence.checks).toHaveLength(7); + expect(f.evidence.checks.every(check => check.passed)).toBe(true); + expect(f.page.reload).toHaveBeenCalledOnce(); + const receipt = JSON.parse(await readFile(path.join(f.directory, "saved-skill-use-checks.json"), "utf8")); + expect(receipt.receipts).toEqual([{ runId: "run", executionId: "load", seq: 2 }]); + expect(receipt.reopened).toEqual(receipt.document); + }); + it.each([ + ["incorrect result", "revision", (r: Row) => { r.body = "{}"; }, "saved_skill_result_authored_by_run"], + ["foreign output author", "revision", (r: Row) => { r.createdByRunId = "foreign"; }, "saved_skill_result_authored_by_run"], + ["changed source", "retained-skill", (r: Row) => { r.markdown += "changed"; }, "saved_skill_source_preserved"], + ["wrong loaded version", "library-read", (r: Row) => { r.versionId = "foreign"; }, "saved_skill_native_read_attributed"], + ] as const)("still rejects %s after a native library load", async (_label, target, mutate, code) => { + const f = await setup((kind, row) => { if (kind === target) mutate(row); return row; }, "campaign", false, "library"); + await expect(f.run()).rejects.toMatchObject({ outcome: "failed", code }); + }); it.each([{ kind: "codex" }, { kind: "acpx", agent: "cursor" }, { kind: "cursor_cloud" }])( "binds a common semantic read for provider %j without an OpenCode directory", async provider => { const f = await setup((kind, row) => { diff --git a/tests/runner-e2e/product-journeys/saved-skill-use-library-loader.test.ts b/tests/runner-e2e/product-journeys/saved-skill-use-library-loader.test.ts new file mode 100644 index 00000000000..a27eea60eed --- /dev/null +++ b/tests/runner-e2e/product-journeys/saved-skill-use-library-loader.test.ts @@ -0,0 +1,111 @@ +import { createHash } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { savedSkillFixture, savedSkillReadAssignment, savedSkillReadReceipts } from "./saved-skill-use-evidence.js"; + +type Row = Record; +const fixture = savedSkillFixture("library-loader", "62ff548dfec748da8fef6d5fbf6cc23d"); +const binding = { companyId: "company", agentId: "agent", runId: "run" }; +const key = `company/${binding.companyId}/${fixture.slug}`; + +function observations(sourceFixture = fixture) { + const skill = { id: "skill", key, currentVersionId: "version" }; + const assignments = { entries: [{ key, versionId: "version" }] }; + const run: Row = { ...binding, id: binding.runId, runtimeMode: "native", runnerInstanceId: "runner", nativeSessionId: "session", + contextSnapshot: { skillSelectionSnapshot: true, skillVersions: { [key]: "version" } }, + runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode" }, runtimeContext: { skills: assignments.entries } } } }; + // Shape of a retained native library load. All identities and source bytes are synthetic. + const result: Row = { id: skill.id, skillId: skill.id, key, name: sourceFixture.name, slug: sourceFixture.slug, + versionId: "version", sourceType: "managed", trustLevel: "markdown_only", compatibility: "compatible", + description: "Make a receipt using this saved procedure.", instruction: "Use this versionId for further pages and referenced files.", + path: "SKILL.md", text: sourceFixture.markdown, byteSize: Buffer.byteLength(sourceFixture.markdown), + sha256: createHash("sha256").update(sourceFixture.markdown).digest("hex"), nextOffset: null, + files: [{ kind: "skill", path: "SKILL.md" }], fileCount: 1, nextFileOffset: null }; + const output = JSON.stringify({ type: "inputText", text: JSON.stringify(result) }); + const events: Row[] = ["started", "progressed", "completed"].map((phase, index) => { + const eventType = `tool.execution.${phase}`; + return { ...binding, seq: index + 1, eventType, protocolSchemaVersion: 1, + sourceInstanceId: "runner", sourceSeq: index + 1, sourceEventId: `event-${index}`, + payload: { prpEvent: { schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", + ...binding, sourceInstanceId: "runner", sourceSeq: index + 1, sourceEventId: `event-${index}`, + normalizedSessionId: "session", turnId: "turn", itemId: "item", eventType, + payload: { schema: "paperclip.tool.execution.v1", executionId: "load", name: "paperclip_load_skill", + transport: "builtin", operation: "unknown", readOnly: false, target: null, + status: phase === "completed" ? "completed" : "running", output: phase === "completed" ? output : "", + outputBytes: phase === "completed" ? Buffer.byteLength(output) : 0, outputTruncated: false } } } }; + }); + return { skill, assignments, run, events }; +} +type Observations = ReturnType; +const completed = (v: Observations) => v.events.find(row => row.eventType === "tool.execution.completed")!.payload.prpEvent.payload; +const read = (v: Observations, sourceFixture = fixture) => savedSkillReadReceipts(v.events, binding, sourceFixture, undefined, + savedSkillReadAssignment(v.skill, v.assignments, v.run), v.run); +function result(v: Observations, change: (r: Row) => void) { + const p = completed(v), wrapper = JSON.parse(p.output), value = JSON.parse(wrapper.text); + change(value); wrapper.text = JSON.stringify(value); p.output = JSON.stringify(wrapper); +} + +describe("saved-skill native library load", () => { + it("accepts the complete library source read despite the proxy's unknown operation and false read-only hint", () => { + expect(read(observations())).toEqual([{ runId: "run", executionId: "load", seq: 3 }]); + }); + it("accepts retained event payloads that omit null targets", () => { + const v = observations(); + for (const row of v.events) delete row.payload.prpEvent.payload.target; + expect(read(v)).toHaveLength(1); + }); + it.each(["1: ", "2|", "3→"])("preserves literal source prefixes %s", prefix => { + const procedure = `${prefix}${fixture.procedure}`; + const sourceFixture = { ...fixture, procedure, markdown: fixture.markdown.replace(fixture.procedure, procedure) }; + expect(read(observations(sourceFixture), sourceFixture)).toHaveLength(1); + }); + it.each([ + ["skill id", (v: Observations) => result(v, r => { r.skillId = "foreign"; })], + ["id alias", (v: Observations) => result(v, r => { r.id = "foreign"; })], + ["key", (v: Observations) => result(v, r => { r.key = "foreign"; })], + ["version", (v: Observations) => result(v, r => { r.versionId = "foreign"; })], + ["path", (v: Observations) => result(v, r => { r.path = "other.md"; })], + ["partial page", (v: Observations) => result(v, r => { r.nextOffset = 6000; })], + ["missing pagination", (v: Observations) => result(v, r => { delete r.nextOffset; })], + ["checksum", (v: Observations) => result(v, r => { r.sha256 = "0".repeat(64); })], + ["source bytes", (v: Observations) => result(v, r => { r.byteSize++; })], + ["partial content", (v: Observations) => result(v, r => { r.text = fixture.procedure; })], + ["extra content", (v: Observations) => result(v, r => { r.text += "extra"; })], + ["failed result", (v: Observations) => result(v, r => { r.outcome = "failed"; })], + ["wrong source", (v: Observations) => result(v, r => { r.sourceType = "local_path"; })], + ["wrong inventory", (v: Observations) => result(v, r => { r.files[0].path = "other.md"; })], + ["incomplete inventory", (v: Observations) => result(v, r => { r.nextFileOffset = 50; })], + ["missing start", (v: Observations) => { v.events.shift(); }], + ["duplicate start", (v: Observations) => { v.events.push(structuredClone(v.events[0]!)); }], + ["duplicate completion", (v: Observations) => { v.events.push(structuredClone(v.events[2]!)); }], + ["foreign company", (v: Observations) => { v.events[2]!.companyId = "foreign"; }], + ["foreign agent", (v: Observations) => { v.events[2]!.agentId = "foreign"; }], + ["foreign run", (v: Observations) => { v.events[2]!.runId = "foreign"; }], + ["foreign envelope run", (v: Observations) => { v.events[2]!.payload.prpEvent.runId = "foreign"; }], + ["foreign runner", (v: Observations) => { v.run.runnerInstanceId = "foreign"; }], + ["foreign session", (v: Observations) => { v.run.nativeSessionId = "foreign"; }], + ["foreign turn", (v: Observations) => { v.events[0]!.payload.prpEvent.turnId = "foreign"; }], + ["foreign item", (v: Observations) => { v.events[0]!.payload.prpEvent.itemId = "foreign"; }], + ["foreign call", (v: Observations) => { v.events[0]!.payload.prpEvent.payload.executionId = "foreign"; }], + ["unordered source", (v: Observations) => { v.events[0]!.sourceSeq = v.events[0]!.payload.prpEvent.sourceSeq = 4; }], + ["failed completion", (v: Observations) => { completed(v).status = "failed"; }], + ["truncated completion", (v: Observations) => { completed(v).outputTruncated = true; }], + ["shell copy", (v: Observations) => { for (const row of v.events) row.payload.prpEvent.payload.name = "bash"; }], + ["other tool", (v: Observations) => { for (const row of v.events) row.payload.prpEvent.payload.name = "paperclip_read_document"; }], + ["wrong transport", (v: Observations) => { completed(v).transport = "process"; }], + ["unexpected target", (v: Observations) => { completed(v).target = "/other/SKILL.md"; }], + ["mutating operation", (v: Observations) => { completed(v).operation = "edit"; }], + ["unselected version", (v: Observations) => { v.run.contextSnapshot.skillVersions[key] = "foreign"; }], + ["missing selection", (v: Observations) => { v.run.contextSnapshot.skillSelectionSnapshot = false; }], + ["API version mismatch", (v: Observations) => { v.assignments.entries[0]!.versionId = "foreign"; }], + ["missing skill id", (v: Observations) => { v.skill.id = ""; }], + ["wrong run owner", (v: Observations) => { v.run.agentId = "foreign"; }], + ["invalid wrapper", (v: Observations) => { completed(v).output = fixture.markdown; }], + ] as const)("rejects %s", (_label, change) => { + const v = observations(); change(v); + const p = completed(v); p.outputBytes = Buffer.byteLength(p.output); + expect(read(v)).toEqual([]); + }); + it("rejects a completion with an incorrect output byte count", () => { + const v = observations(); completed(v).outputBytes++; expect(read(v)).toEqual([]); + }); +}); diff --git a/tests/runner-e2e/product-journeys/saved-skill-use-native-loader.test.ts b/tests/runner-e2e/product-journeys/saved-skill-use-native-loader.test.ts index 925ad58b5d9..fc1f4700a42 100644 --- a/tests/runner-e2e/product-journeys/saved-skill-use-native-loader.test.ts +++ b/tests/runner-e2e/product-journeys/saved-skill-use-native-loader.test.ts @@ -42,7 +42,7 @@ function observations() { return { skill, assignments, run, events, notifications }; } type Observations = ReturnType; -const read = (value: Observations) => savedSkillReadReceipts(value.events, binding, fixture, +const read = (value: Observations, sourceFixture = fixture) => savedSkillReadReceipts(value.events, binding, sourceFixture, savedSkillReadRuntimeName(value.skill, value.assignments, value.run), savedSkillReadAssignment(value.skill, value.assignments, value.run), value.run); const completed = (v: Observations) => v.events[1]!.payload.prpEvent.payload; @@ -63,6 +63,18 @@ describe("saved-skill native OpenCode builtin loader", () => { const value = observations(); output(value, text => text.replace("/workspace/", "/work space/") .replace(`${runtimeName}\n`, `${runtimeName}/\n`)); expect(read(value)).toHaveLength(1); }); + it.each(["1: ", "2|", "3→"])("preserves literal native skill procedure prefixes %s", prefix => { + const procedure = `${prefix}${fixture.procedure}`; + const sourceFixture = { ...fixture, procedure, markdown: fixture.markdown.replace(fixture.procedure, procedure) }; + const value = observations(); + output(value, text => text.replace(fixture.procedure.trim(), procedure.trim())); + expect(read(value, sourceFixture)).toHaveLength(1); + }); + it("accepts omitted null targets in retained native loader events", () => { + const value = observations(); + for (const row of value.events) delete row.payload.prpEvent.payload.target; + expect(read(value)).toHaveLength(1); + }); it.each([ ["missing start", (v: Observations) => { v.events.shift(); }], ["missing completion", (v: Observations) => { v.events.pop(); }], diff --git a/tests/runner-e2e/product-journeys/saved-skill-use.md b/tests/runner-e2e/product-journeys/saved-skill-use.md index c0b8df87244..8c8ac48dd03 100644 --- a/tests/runner-e2e/product-journeys/saved-skill-use.md +++ b/tests/runner-e2e/product-journeys/saved-skill-use.md @@ -80,6 +80,20 @@ A semantic read failure can have a completed tool status; it does not qualify. A partial page, copied tool result, foreign version, missing start or unbound native event also fails closed. +Core's native OpenCode library tool `paperclip_load_skill` can also supply the +read with an unknown operation and a false read-only hint. Its complete +`inputText` result must bind both skill IDs, the canonical key and the immutable +created version to the saved fixture. The original Markdown, byte size, SHA-256, +`SKILL.md` path and complete single-file inventory must match. Both page offsets +must be null. The actual run's admitted assignment, runner, session, turn, item +and one ordered start/completion pair must agree. Progress events can occur +between the pair. Duplicate start/completion events fail. This path does not +change the independent saved-output, revision authorship, reload or source checks. +Verified library and assigned-skill text retains literal numeric line prefixes. +Only file-reader output has presentation line numbers removed. Native loaders +share run admission and ordered call checks; Codex uses the same run admission +with its own semantic receipt checks. + Codex's dynamic tool display is not first-party authority. Its raw name, optional namespace or read-only hint cannot qualify a read. For Codex, the grader also accepts Core's retained `semantic_tool.input` and `semantic_tool.result`