mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
fix(evals): attribute native saved-skill library reads
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
24e095c160
commit
552fd03bbc
5 files changed
+201
-6
No files matched your search
@@ -6,7 +6,7 @@ import { savedSkillDocumentAttributed, savedSkillFixture, savedSkillReadAssignme
|
||||
type Row = Record<string, any>;
|
||||
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,
|
||||
|
||||
@@ -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,6 +97,55 @@ function assignedSkillReadText(output: string, binding: NativePrpRunBinding, fix
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
/** 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 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()
|
||||
|| typeof assignment.skillId !== "string" || !assignment.skillId.trim()
|
||||
|| skills.length !== 1 || skills[0].versionId !== assignment.versionId
|
||||
|| run.contextSnapshot?.skillSelectionSnapshot !== true
|
||||
|| run.contextSnapshot?.skillVersions?.[assignment.key] !== assignment.versionId
|
||||
|| payload.name !== "paperclip_load_skill" || payload.operation !== "unknown"
|
||||
|| payload.readOnly !== false || payload.target != null) 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;
|
||||
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 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.
|
||||
@@ -251,9 +301,10 @@ 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 output = (libraryText ?? assignedText ?? (wrappedRead ? wrapped![2]! : payload.output)).split("\n").map((line: string) => line.replace(/^\s*\d+(?:[:|]|→)\s?/, "")).join("\n");
|
||||
if (!output.includes(fixture.procedure.trim())) return false;
|
||||
return bound.some(start => {
|
||||
const initial = start.payload.prpEvent, p = initial.payload;
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { savedSkillFixture, savedSkillReadAssignment, savedSkillReadReceipts } from "./saved-skill-use-evidence.js";
|
||||
|
||||
type Row = Record<string, any>;
|
||||
const fixture = savedSkillFixture("library-loader", "62ff548dfec748da8fef6d5fbf6cc23d");
|
||||
const binding = { companyId: "company", agentId: "agent", runId: "run" };
|
||||
const key = `company/${binding.companyId}/${fixture.slug}`;
|
||||
|
||||
function observations() {
|
||||
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: fixture.name, slug: fixture.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: fixture.markdown, byteSize: Buffer.byteLength(fixture.markdown),
|
||||
sha256: createHash("sha256").update(fixture.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 = ["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<typeof observations>;
|
||||
const completed = (v: Observations) => v.events.find(row => row.eventType === "tool.execution.completed")!.payload.prpEvent.payload;
|
||||
const read = (v: Observations) => savedSkillReadReceipts(v.events, binding, fixture, 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([
|
||||
["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([]);
|
||||
});
|
||||
});
|
||||
@@ -80,6 +80,16 @@ 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.
|
||||
|
||||
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`
|
||||
|
||||
Reference in new issue
Block a user