import { performance } from "node:perf_hooks"; import { describe, expect, it } from "vitest"; import type { Db } from "@paperclipai/db"; import { HttpError } from "../../errors.js"; import { admitToolInputSchema, providerToolSchemaShapeIssues, runnerCodexDynamicToolsFit, } from "../../vendor/paperclip-runner/index.js"; import { boundedReadSchemaBlocks, createSchemaBlocksResponseBudget, deduplicateSchemaBlocks, MAX_CANDIDATE_SCHEMA_FENCES, MAX_KV_LABELS_ENTRIES, MAX_RESPONSE_SCHEMA_BLOCKS_BYTES, MAX_SCANNED_SCHEMA_MARKDOWN_CHARS, MAX_SCHEMA_FENCE_BODY_CHARS, normalizeRunnerKvLabelsInput, projectBoundedSchemaBlocks, scanFencedSchemaBlocks, } from "./native-task-metadata.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; describe("scanFencedSchemaBlocks", () => { it("extracts backtick and tilde json schema fences with quotes, extra attributes, and nested fences", () => { const markdown = [ "Progress summary before fence:", "```json schema=test-report@1", '{"passed":true,"total":4,"failed":0}', "```", "", ' ~~~json extra=true schema="finding@1" ', '{"severity":"high","title":"Missing lock","line":18}', " ~~~ ", "", "````JSON schema='git-commit@1'", "{", ' "sha": "abc1234",', ' "message": "Includes ``` inner backticks safely"', "}", "````", ].join("\n"); expect(scanFencedSchemaBlocks(markdown)).toEqual([ { rawSchemaRef: "test-report@1", rawJson: '{"passed":true,"total":4,"failed":0}', oversized: false, }, { rawSchemaRef: "finding@1", rawJson: '{"severity":"high","title":"Missing lock","line":18}', oversized: false, }, { rawSchemaRef: "git-commit@1", rawJson: '{\n "sha": "abc1234",\n "message": "Includes ``` inner backticks safely"\n}', oversized: false, }, ]); }); it("ignores ordinary code blocks, invalid backtick info strings, and unclosed fences", () => { const markdown = [ "```json", '{"ordinary":true}', "```", "```json schema=test-report@1 `disallowed-backtick`", '{"passed":true}', "```", "```ts schema=test-report@1", '{"passed":true}', "```", "```json schema=test-report@1", '{"unclosed":true}', ].join("\n"); expect(scanFencedSchemaBlocks(markdown)).toEqual([]); }); it("marks oversized fence bodies without buffering unbounded lines and caps candidate count and input length", () => { const hugeBody = "x".repeat(MAX_SCHEMA_FENCE_BODY_CHARS + 128); const oversizedDoc = `\`\`\`json schema=test-report@1\n${hugeBody}\n\`\`\``; expect(scanFencedSchemaBlocks(oversizedDoc)).toEqual([ { rawSchemaRef: "test-report@1", rawJson: "", oversized: true, }, ]); const manyFences = Array.from( { length: MAX_CANDIDATE_SCHEMA_FENCES + 10 }, (_, idx) => `\`\`\`json schema=test-report@1\n{"passed":true,"total":${idx}}\n\`\`\``, ).join("\n"); const capped = scanFencedSchemaBlocks(manyFences); expect(capped).toHaveLength(MAX_CANDIDATE_SCHEMA_FENCES); expect(capped[0]?.rawJson).toBe('{"passed":true,"total":0}'); expect(capped[MAX_CANDIDATE_SCHEMA_FENCES - 1]?.rawJson).toBe( `{"passed":true,"total":${MAX_CANDIDATE_SCHEMA_FENCES - 1}}`, ); const beyondPrefix = "a".repeat(MAX_SCANNED_SCHEMA_MARKDOWN_CHARS + 32) + "\n```json schema=test-report@1\n{\"passed\":true}\n```"; expect(scanFencedSchemaBlocks(beyondPrefix)).toEqual([]); }); it("scans 5,000 repeated unterminated ```json lines in strictly linear time (< 50ms)", () => { // Warm up V8 bytecode before measuring linear scan wall time. scanFencedSchemaBlocks("```json schema=test-report@1\n{\"passed\":true}\n```"); const repeatedPlain = "```json\n".repeat(5_000); const startPlain = performance.now(); const outPlain = scanFencedSchemaBlocks(repeatedPlain); const elapsedPlainMs = performance.now() - startPlain; expect(outPlain).toEqual([]); expect(elapsedPlainMs).toBeLessThan(50); const repeatedSchema = "```json schema=test-report@1\n".repeat(5_000); const startSchema = performance.now(); const outSchema = scanFencedSchemaBlocks(repeatedSchema); const elapsedSchemaMs = performance.now() - startSchema; expect(outSchema).toEqual([]); expect(elapsedSchemaMs).toBeLessThan(50); }); }); describe("normalizeRunnerKvLabelsInput & deduplicateSchemaBlocks", () => { it("normalizes both { key, value } arrays and string maps while enforcing key/value rules", () => { expect(normalizeRunnerKvLabelsInput(undefined)).toEqual({}); expect(normalizeRunnerKvLabelsInput(null)).toEqual({}); expect( normalizeRunnerKvLabelsInput([ { key: "env", value: "staging" }, { key: "role", value: "scanner" }, ]), ).toEqual({ env: "staging", role: "scanner" }); expect( normalizeRunnerKvLabelsInput({ env: "production", "team.owner": "platform", }), ).toEqual({ env: "production", "team.owner": "platform" }); expect(() => normalizeRunnerKvLabelsInput([ { key: "env", value: "a" }, { key: "env", value: "b" }, ]), ).toThrow(HttpError); expect(() => normalizeRunnerKvLabelsInput([{ key: "paperclip.internal", value: "1" }]), ).toThrow(/paperclip\./); const tooMany = Array.from({ length: MAX_KV_LABELS_ENTRIES + 1 }, (_, i) => ({ key: `k${i}`, value: "v", })); expect(() => normalizeRunnerKvLabelsInput(tooMany)).toThrow( `kvLabels cannot exceed ${MAX_KV_LABELS_ENTRIES} entries`, ); }); it("deduplicates schema blocks with canonically equivalent JSON payloads", () => { const blocks = deduplicateSchemaBlocks([ { schema: "test-report", version: 1, data: { passed: true, total: 5 } }, { schema: "test-report", version: 1, data: { total: 5, passed: true } }, { schema: "test-report", version: 1, data: { passed: false, total: 5 } }, { schema: "finding", version: 1, data: { severity: "low", title: "Note" } }, ]); expect(blocks).toEqual([ { schema: "test-report", version: 1, data: { passed: true, total: 5 } }, { schema: "test-report", version: 1, data: { passed: false, total: 5 } }, { schema: "finding", version: 1, data: { severity: "low", title: "Note" } }, ]); const singleFortyKiB = [ { schema: "finding", version: 1, data: { severity: "low", title: "40k", notes: "x".repeat(40 * 1024) } }, ]; expect(projectBoundedSchemaBlocks(singleFortyKiB)).toEqual({ schemaBlocks: singleFortyKiB }); const largeBlocks = Array.from({ length: 24 }, (_, idx) => ({ schema: "finding", version: 1, data: { severity: "low", title: `item-${idx}`, notes: "x".repeat(4_096) }, })); const projected = projectBoundedSchemaBlocks(largeBlocks, { maxBlocks: 16, maxTotalChars: 12_000 }); expect(projected.schemaBlocks.length).toBeGreaterThan(0); expect(projected.schemaBlocks.length).toBeLessThan(largeBlocks.length); expect(projected.schemaBlocksTruncated).toBe(true); expect(projected.schemaBlocksOmittedCount).toBe(largeBlocks.length - projected.schemaBlocks.length); expect(projected.schemaBlocksFullReadHint).toContain("call_api"); expect(boundedReadSchemaBlocks(largeBlocks, { maxBlocks: 16, maxTotalChars: 12_000 })).toEqual( projected.schemaBlocks, ); // Aggregate response budget across 9 comments x ~60 KiB stays <= 128 KiB (well below 500 KB PRP command limit) const sharedBudget = createSchemaBlocksResponseBudget(); const nineComments = Array.from({ length: 9 }, (_, idx) => [ { schema: "finding", version: 1, data: { severity: "low", title: `c-${idx}`, notes: "y".repeat(60 * 1024) } }, ]); const historyProjections = nineComments.map((blocks) => projectBoundedSchemaBlocks(blocks, { responseBudget: sharedBudget }), ); expect(historyProjections[0]?.schemaBlocks).toHaveLength(1); expect(historyProjections[1]?.schemaBlocks).toHaveLength(1); expect(historyProjections.slice(2).every((p) => p.schemaBlocks.length === 0 && p.schemaBlocksTruncated === true && p.schemaBlocksOmittedCount === 1)).toBe(true); expect(Buffer.byteLength(JSON.stringify(historyProjections), "utf8")).toBeLessThan( MAX_RESPONSE_SCHEMA_BLOCKS_BYTES + 4_096, ); }); }); describe("parity runner tool schema provider admission", () => { it("admits create_task, report_progress, and search_tasks across strict provider schema checks", () => { const dummyDb = new Proxy({} as Db, { get() { throw new Error("definitions() must not query the database"); }, }); const id = "00000000-0000-4000-8000-000000000101"; const authority = new PaperclipRunnerToolAuthority(dummyDb, { companyId: id, agentId: id, issueId: id, runId: id, }); const definitions = authority.definitions(); for (const toolName of ["create_task", "report_progress", "search_tasks"] as const) { const tool = definitions.find((entry) => entry.name === toolName); expect(tool, `expected ${toolName} to be advertised`).toBeDefined(); expect(providerToolSchemaShapeIssues(tool!.inputSchema)).toEqual([]); expect(admitToolInputSchema(tool!.inputSchema as Record).ok).toBe(true); } expect(runnerCodexDynamicToolsFit(definitions)).toBe(true); }); });