import { describe, expect, it, vi } from "vitest"; const { SEMANTIC_POLICY, EXTRACTION_FIELD_TYPES, chooseAction, extract, filter, find, semanticModel, verify, } = require("../../native/semantic-core.cjs"); type Question = { criteria: Record }; type Questions = Record; function responseFor( questions: Questions, selections: Record, selectedProbability = 0.9, ) { const answers = Object.fromEntries( Object.entries(questions).map(([name, question]) => { const labels = Object.keys(question.criteria); const selected = selections[name] || labels[0]; let probability = selectedProbability; if (labels.length === 1) { probability = 1; } else if ( selections[name] === undefined && (name === "prerequisites" || name === "prerequisite_evidence") ) { probability = 0.99; } const remainder = labels.length > 1 ? (1 - probability) / (labels.length - 1) : 0; return [ name, { type: "choice", choice: selected, confidence: 0.42, probabilities: Object.fromEntries( labels.map((label) => [label, label === selected ? probability : remainder]), ), }, ]; }), ); return { model: "jev-response-model", usage: { input_tokens: 10, output_tokens: 2 }, answers }; } const evaluateWith = (selections: Record, probability = 0.9) => vi.fn(async (_state: unknown, questions: Questions) => responseFor(questions, selections, probability), ); describe("semantic decision core", () => { it("publishes the approved v1 policy constants", () => { expect(SEMANTIC_POLICY).toMatchObject({ model: "jev-1.13.0", timeoutMs: 5000, probabilitySumTolerance: 0.01, limits: { stateBytes: 24 * 1024, candidates: 64, actionChoices: 70, chunks: 48, questions: 50, filterTop: 12, inputSlots: 16, inputValueBytes: 16 * 1024, defaultSteps: 5, maxSteps: 8, defaultWallMs: 30_000, maxWallMs: 60_000, providerCalls: 17, invalidActionDecisionRetries: 1, directActionRetryChoices: 18, invalidActionDecisionRegionTop: 2, staleRefreshes: 2, identicalObservationHashes: 2, }, }); }); it("registers only models with a complete measured threshold set", () => { const keys = [ "find", "filter", "verifyPositive", "verifyNegative", "prerequisiteSupported", "prerequisiteBlocked", "write", "exactRefWrite", ]; expect(Object.keys(SEMANTIC_POLICY.models)).toEqual(["jev-1.13.0", "clef", "clef-flash"]); expect(Object.isFrozen(SEMANTIC_POLICY.models)).toBe(true); for (const entry of Object.values(SEMANTIC_POLICY.models) as Array<{ provider: string; images: boolean; thresholds: Record; }>) { expect(["typesafe", "cloudflare"]).toContain(entry.provider); expect(entry.images).toBe(entry.provider === "cloudflare"); expect(Object.keys(entry.thresholds).sort()).toEqual([...keys].sort()); for (const value of Object.values(entry.thresholds)) { expect(Number.isFinite(value) && value > 0 && value <= 1).toBe(true); } expect(Object.isFrozen(entry) && Object.isFrozen(entry.thresholds)).toBe(true); } expect(semanticModel("clef-flash")).toBe(SEMANTIC_POLICY.models["clef-flash"]); }); it("rejects unknown models with the list of valid model ids", () => { expect(() => semanticModel("jev-9")).toThrow( expect.objectContaining({ code: "semantic_invalid_request", message: expect.stringContaining("jev-1.13.0, clef, clef-flash"), }), ); }); it("applies Clef measured thresholds through the model option", async () => { const click = { id: "click", kind: "click", ref: "ref.1" }; const exactRef = (probability: number) => chooseAction({ state: {}, goal: "save", actions: [click], origin: "https://example.test", allowWrite: true, allowRefs: ["ref.1"], model: "clef", evaluate: evaluateWith({ action: "click" }, probability), }); expect(await exactRef(0.78)).toMatchObject({ status: "uncertain", appliedThreshold: 0.79 }); expect(await exactRef(0.79)).toMatchObject({ status: "selected", appliedThreshold: 0.79 }); const broad = (probability: number) => chooseAction({ state: {}, goal: "save", actions: [click], origin: "https://example.test", allowWrite: true, allowRefs: [], model: "clef", evaluate: evaluateWith({ action: "click" }, probability), }); expect(await broad(0.84)).toMatchObject({ status: "uncertain", appliedThreshold: 0.85 }); expect(await broad(0.85)).toMatchObject({ status: "selected", appliedThreshold: 0.85 }); const supported = (probability: number) => chooseAction({ state: {}, goal: "save", actions: [click], origin: "https://example.test", allowWrite: true, model: "clef", evaluate: vi.fn(async (_state: unknown, questions: Questions) => { const response = responseFor( questions, { action: "click", prerequisites: "supported" }, 0.9, ); response.answers.prerequisites.probabilities = { supported: probability, blocked: 0, uncertain: 1 - probability, }; return response; }), }); expect(await supported(0.69)).toMatchObject({ status: "uncertain", prerequisiteStatus: "uncertain", prerequisiteThresholds: { supported: 0.7, blocked: 0.9 }, }); expect(await supported(0.7)).toMatchObject({ status: "selected", prerequisiteStatus: "supported", }); const negative = (probability: number) => verify({ state: {}, outcome: "saved", model: "clef-flash", evaluate: evaluateWith({ verdict: "not_satisfied" }, probability), }); expect(await negative(0.93)).toMatchObject({ status: "uncertain", appliedThreshold: 0.94 }); expect(await negative(0.94)).toMatchObject({ status: "not_satisfied", appliedThreshold: 0.94, }); }); it("find selects only a supplied candidate and gates on selected probability", async () => { const candidates = [{ id: "ref.1", role: "button", name: "Preferences" }]; const found = await find({ state: { title: "Settings" }, goal: "preferences", candidates, evaluate: evaluateWith({ target: "ref.1" }, 0.7), }); const uncertain = await find({ state: {}, goal: "preferences", candidates, evaluate: evaluateWith({ target: "ref.1" }, 0.69), }); const overridden = await find({ state: {}, goal: "preferences", candidates, thresholds: { find: 0.69 }, evaluate: evaluateWith({ target: "ref.1" }, 0.69), }); expect(found).toMatchObject({ status: "found", candidate: candidates[0], appliedThreshold: 0.7, model: "jev-response-model", decision: { confidence: 0.42 }, }); expect(uncertain).toMatchObject({ status: "uncertain", candidate: null }); expect(overridden).toMatchObject({ status: "found", appliedThreshold: 0.69 }); }); it("verify gates positive and negative labels independently and selects only verbatim evidence", async () => { const evidence = [{ id: "line.2", text: "Saved" }]; const result = await verify({ state: { chunks: evidence }, outcome: "preferences saved", evidence, evaluate: evaluateWith({ verdict: "satisfied", evidence: "line.2" }, 0.9), }); expect(result).toMatchObject({ status: "satisfied", appliedThreshold: 0.85, evidence: evidence[0], }); expect(result.evidence.text).toBe("Saved"); }); it("filter fans out one closed question per chunk and deterministically ranks passing chunks", async () => { const chunks = [ { id: "c1", text: "first" }, { id: "c2", text: "second" }, ]; const evaluate = vi.fn(async (_state: unknown, questions: Questions) => { const response = responseFor(questions, { chunk_0: "relevant", chunk_1: "relevant" }, 0.7); response.answers.chunk_1.probabilities = { relevant: 0.8, not_relevant: 0.2 }; return response; }); const result = await filter({ state: { origin: "https://example.test" }, goal: "settings", chunks, top: 1, evaluate, }); const overridden = await filter({ state: { origin: "https://example.test" }, goal: "settings", chunks, top: 1, thresholds: { filter: 0.81 }, evaluate, }); expect(Object.keys(evaluate.mock.calls[0][1])).toEqual(["chunk_0", "chunk_1"]); expect(result).toMatchObject({ status: "filtered", appliedThreshold: 0.65, omittedCount: 1, chunks: [{ id: "c2", text: "second" }], }); expect(overridden).toMatchObject({ status: "uncertain", appliedThreshold: 0.81, chunks: [] }); }); it("returns uncertain filtering instead of masquerading as an empty page", async () => { const result = await filter({ state: {}, goal: "missing", chunks: [{ id: "c1", text: "noise" }], evaluate: evaluateWith({ chunk_0: "not_relevant" }, 0.9), }); expect(result).toMatchObject({ status: "uncertain", chunks: [], omittedCount: 1 }); }); it("constructs a closed action choice and locally enforces write authorization", async () => { const actions = [ { id: "nav", kind: "navigate", url: "https://example.test/settings" }, { id: "click", kind: "click", ref: "ref.1" }, { id: "fill", kind: "fill", ref: "ref.2", slot: "email" }, { id: "wait", kind: "wait", durationMs: 500 }, ]; const evaluate = evaluateWith({ action: "nav" }, 0.99); const result = await chooseAction({ state: {}, goal: "open", actions, origin: "https://example.test", allowWrite: false, inputSlots: ["email"], evaluate, }); expect(Object.keys(evaluate.mock.calls[0][1].action.criteria)).toEqual(["nav", "wait", "stop"]); expect(result).toMatchObject({ status: "selected", action: actions[0] }); }); it("describes closed actions and blocks an incompatible write with bounded evidence", async () => { const state = { candidates: [{ id: "ref.1", role: "radio", name: "M", state: { checked: false } }], chunks: [{ id: "product", text: "Available colours: Larch, Dark Jade", refs: ["ref.1"] }], }; const evaluate = evaluateWith( { action: "click", prerequisites: "blocked", prerequisite_evidence: "product" }, 0.99, ); const result = await chooseAction({ state, goal: "Select Sea Salt and size M", actions: [{ id: "click", kind: "click", ref: "ref.1" }], origin: "https://example.test", allowWrite: true, thresholds: { write: 0.85 }, evaluate, }); expect(evaluate.mock.calls[0][1].action.criteria).toEqual({ click: "click | radio | M | unchecked", stop: "The goal is already satisfied, or no supplied action can safely make progress", }); expect(result).toMatchObject({ status: "blocked", action: null, prerequisiteStatus: "blocked", prerequisiteThresholds: { supported: 0.75, blocked: 0.9 }, prerequisiteEvidence: state.chunks[0], prerequisiteEvidenceThreshold: 0.65, }); }); it("does not present low-confidence prerequisite evidence as support", async () => { const state = { chunks: [ { id: "product", text: "Available colours: Larch" }, { id: "shipping", text: "Delivery information" }, ], }; const evaluate = vi.fn(async (_state: unknown, questions: Questions) => { const response = responseFor( questions, { action: "click", prerequisites: "blocked", prerequisite_evidence: "product" }, 0.99, ); response.answers.prerequisite_evidence.probabilities = { product: 0.37, shipping: 0.32, none: 0.31, }; return response; }); const result = await chooseAction({ state, goal: "Select Sea Salt", actions: [{ id: "click", kind: "click", ref: "ref.1" }], origin: "https://example.test", allowWrite: true, evaluate, }); expect(result).toMatchObject({ status: "blocked", prerequisiteEvidence: null, prerequisiteEvidenceThreshold: 0.65, prerequisiteEvidenceDecision: { label: "product", probability: 0.37 }, }); }); it("requires supported prerequisites for writes but not read-only navigation", async () => { const write = { id: "click", kind: "click", ref: "ref.1" }; const options = { state: {}, goal: "advance", actions: [write], origin: "https://example.test", allowWrite: true, thresholds: { write: 0.7 }, }; const uncertainWrite = await chooseAction({ ...options, evaluate: evaluateWith({ action: "click", prerequisites: "supported" }, 0.74), }); const acceptedWrite = await chooseAction({ ...options, evaluate: evaluateWith({ action: "click", prerequisites: "supported" }, 0.75), }); const navigation = { id: "nav", kind: "navigate", url: "https://example.test/product" }; const acceptedNavigation = await chooseAction({ ...options, actions: [navigation], allowWrite: false, evaluate: evaluateWith({ action: "nav", prerequisites: "blocked" }, 0.99), }); expect(uncertainWrite).toMatchObject({ status: "uncertain", prerequisiteStatus: "uncertain" }); expect(acceptedWrite).toMatchObject({ status: "selected", prerequisiteStatus: "supported" }); expect(acceptedNavigation).toMatchObject({ status: "selected", action: navigation, prerequisiteStatus: "not_applicable", }); const overridden = await chooseAction({ ...options, thresholds: { write: 0.7, prerequisiteSupported: 0.74 }, evaluate: evaluateWith({ action: "click", prerequisites: "supported" }, 0.74), }); expect(overridden).toMatchObject({ status: "selected", action: write }); }); it("applies the prerequisite block threshold without weakening write confidence", async () => { const options = { state: {}, goal: "change an unavailable variant", actions: [{ id: "click", kind: "click", ref: "ref.1" }], origin: "https://example.test", allowWrite: true, thresholds: { write: 0.8 }, }; const below = await chooseAction({ ...options, evaluate: evaluateWith({ action: "click", prerequisites: "blocked" }, 0.89), }); const blocked = await chooseAction({ ...options, evaluate: evaluateWith({ action: "click", prerequisites: "blocked" }, 0.9), }); const overridden = await chooseAction({ ...options, thresholds: { write: 0.8, prerequisiteBlocked: 0.89 }, evaluate: evaluateWith({ action: "click", prerequisites: "blocked" }, 0.89), }); expect(below).toMatchObject({ status: "uncertain", prerequisiteStatus: "uncertain" }); expect(blocked).toMatchObject({ status: "blocked", prerequisiteStatus: "blocked" }); expect(overridden).toMatchObject({ status: "blocked", prerequisiteStatus: "blocked" }); }); it("applies the exact-ref write threshold at its 0.64/0.65 boundary", async () => { const action = { id: "fill", kind: "fill", ref: "ref.2", slot: "email" }; const below = await chooseAction({ state: {}, goal: "fill", actions: [action], origin: "https://example.test", allowWrite: true, allowRefs: ["ref.2"], inputSlots: ["email"], evaluate: evaluateWith({ action: "fill" }, 0.64), }); const selected = await chooseAction({ state: {}, goal: "fill", actions: [action], origin: "https://example.test", allowWrite: true, allowRefs: ["ref.2"], inputSlots: ["email"], evaluate: evaluateWith({ action: "fill" }, 0.65), }); expect(below).toMatchObject({ status: "uncertain", appliedThreshold: 0.65 }); expect(selected).toMatchObject({ status: "selected", action, appliedThreshold: 0.65 }); }); it("applies per-call write thresholds without changing defaults or exact-ref thresholds", async () => { const broadAction = { id: "click", kind: "click", ref: "ref.1" }; const broadOptions = { state: {}, goal: "add to cart", actions: [broadAction], origin: "https://example.test", allowWrite: true, allowRefs: [], inputSlots: [], evaluate: evaluateWith({ action: "click" }, 0.85), }; const defaultResult = await chooseAction(broadOptions); const overridden = await chooseAction({ ...broadOptions, thresholds: { write: 0.85 } }); expect(defaultResult).toMatchObject({ status: "uncertain", appliedThreshold: 0.95 }); expect(overridden).toMatchObject({ status: "selected", action: broadAction, appliedThreshold: 0.85, }); expect(SEMANTIC_POLICY.models["jev-1.13.0"].thresholds.write).toBe(0.95); const exactOptions = { ...broadOptions, allowRefs: ["ref.1"], evaluate: evaluateWith({ action: "click" }, 0.6), }; const broadOnly = await chooseAction({ ...exactOptions, thresholds: { write: 0.5 } }); const exactOverride = await chooseAction({ ...exactOptions, thresholds: { exactRefWrite: 0.6 }, }); expect(broadOnly).toMatchObject({ status: "uncertain", appliedThreshold: 0.65 }); expect(exactOverride).toMatchObject({ status: "selected", appliedThreshold: 0.6 }); }); it("applies positive and negative verification overrides independently", async () => { const options = { state: {}, outcome: "saved", evidence: [] }; const positiveDefault = await verify({ ...options, evaluate: evaluateWith({ verdict: "satisfied" }, 0.8), }); const positiveOverride = await verify({ ...options, thresholds: { verifyPositive: 0.8 }, evaluate: evaluateWith({ verdict: "satisfied" }, 0.8), }); const negativeOverride = await verify({ ...options, thresholds: { verifyNegative: 0.8 }, evaluate: evaluateWith({ verdict: "not_satisfied" }, 0.8), }); expect(positiveDefault).toMatchObject({ status: "uncertain", appliedThreshold: 0.85 }); expect(positiveOverride).toMatchObject({ status: "satisfied", appliedThreshold: 0.8 }); expect(negativeOverride).toMatchObject({ status: "not_satisfied", appliedThreshold: 0.8 }); }); it.each([ { name: "broad authorization", actions: [{ id: "click", kind: "click", ref: "ref.1" }], allowRefs: [], inputSlots: [], selected: "click", }, { name: "multiple allowed refs", actions: [ { id: "click-1", kind: "click", ref: "ref.1" }, { id: "click-2", kind: "click", ref: "ref.2" }, ], allowRefs: ["ref.1", "ref.2"], inputSlots: [], selected: "click-1", }, { name: "multiple fill slots", actions: [ { id: "fill-email", kind: "fill", ref: "ref.1", slot: "email" }, { id: "fill-backup", kind: "fill", ref: "ref.1", slot: "backup" }, ], allowRefs: ["ref.1"], inputSlots: ["email", "backup"], selected: "fill-email", }, ])("retains the 0.95 write threshold for $name", async (testCase) => { const below = await chooseAction({ state: {}, goal: "write", actions: testCase.actions, origin: "https://example.test", allowWrite: true, allowRefs: testCase.allowRefs, inputSlots: testCase.inputSlots, evaluate: evaluateWith({ action: testCase.selected }, 0.94), }); const selected = await chooseAction({ state: {}, goal: "write", actions: testCase.actions, origin: "https://example.test", allowWrite: true, allowRefs: testCase.allowRefs, inputSlots: testCase.inputSlots, evaluate: evaluateWith({ action: testCase.selected }, 0.95), }); expect(below).toMatchObject({ status: "uncertain", appliedThreshold: 0.95 }); expect(selected).toMatchObject({ status: "selected", appliedThreshold: 0.95 }); }); it("rejects unsafe navigation and malformed provider output", async () => { await expect( chooseAction({ state: {}, goal: "leave", actions: [{ id: "nav", kind: "navigate", url: "https://other.test" }], origin: "https://example.test", evaluate: evaluateWith({ action: "nav" }), }), ).rejects.toMatchObject({ code: "semantic_invalid_request" }); await expect( find({ state: {}, goal: "target", candidates: [{ id: "r1" }], evaluate: async () => ({ model: "jev", usage: { input_tokens: 1, output_tokens: 1 }, answers: { target: { type: "choice", choice: "invented", confidence: 1, probabilities: { r1: 0, none: 1 }, }, }, }), }), ).rejects.toMatchObject({ code: "provider_invalid_response" }); }); it("enforces the UTF-8 state cap before invoking the provider", async () => { const evaluate = evaluateWith({ target: "none" }); await expect( find({ state: "x".repeat(SEMANTIC_POLICY.limits.stateBytes), goal: "target", candidates: [], evaluate, }), ).rejects.toMatchObject({ code: "semantic_invalid_request" }); expect(evaluate).not.toHaveBeenCalled(); }); }); describe("semantic extraction core", () => { const state = { origin: "https://shop.example", title: "Your order", readyState: "complete", modals: [], candidates: [ { id: "e5", role: "button", name: "Pay $42.10" }, { id: "e6", role: "link", name: "" }, ], chunks: [ { id: "c1", text: "šŸšššŸ“¦ Order A-88412", refs: ["e2"] }, { id: "c2", text: "Total $701.10", refs: [] }, ], }; const sentState = 'Your order\nšŸšššŸ“¦ Order A-88412\nTotal $701.10\nbutton "Pay $42.10"'; // Clairic reports spans as code-point offsets into the state it received. function spanOf(text: string, value: string) { const start = [...text.slice(0, text.indexOf(value))].length; return [start, start + [...value].length]; } function run( fields: Array<{ name: string; type: string; instructions?: string; spec?: Record; }>, answers: (text: string) => Record, options: { thresholds?: Record; response?: Record } = {}, ) { const evaluate = vi.fn(async (text: string, _fields: unknown, _options: unknown) => ({ model: "clairic", answers: answers(text), truncated: false, usage: { input_tokens: 504, output_tokens: 0 }, ...options.response, })); const result = extract({ state, fields: fields.map(({ name, type, instructions, spec }) => ({ name, type, spec: spec ?? { ...EXTRACTION_FIELD_TYPES[type], ...(instructions ? { instructions } : {}), }, })), referenceDate: "2026-10-23", thresholds: options.thresholds, evaluate, }); return { result, evaluate }; } it("sends one line per source and maps code-point spans back to chunks and refs", async () => { const { result, evaluate } = run( [ { name: "order_id", type: "text", instructions: "Order number" }, { name: "total", type: "number" }, { name: "pay", type: "text" }, { name: "heading", type: "text" }, { name: "tracking", type: "text" }, ], (text) => ({ order_id: { type: "text", value: "A-88412", span: spanOf(text, "A-88412"), confidence: 0.99, p_null: 0.001, }, total: { type: "number", value: 701.1, confidence: 0.99, mean: 701 }, pay: { type: "text", value: "$42.10", span: spanOf(text, "$42.10"), confidence: 0.95 }, heading: { type: "text", value: "order\nšŸšššŸ“¦", span: spanOf(text, "order\nšŸšššŸ“¦"), confidence: 0.9, }, tracking: { type: "text", value: null, guess: "A-88412", span: spanOf(text, "A-88412"), confidence: 0.84, p_null: 0.99, }, }), { response: { state_text: "ignored" } }, ); expect(await result).toEqual({ status: "partial", fields: { order_id: { type: "text", status: "extracted", value: "A-88412", confidence: 0.99, pNull: 0.001, source: { chunks: ["c1"], refs: ["e2"] }, }, total: { type: "number", status: "extracted", value: 701.1, confidence: 0.99, source: null, }, pay: { type: "text", status: "extracted", value: "$42.10", confidence: 0.95, source: { chunks: [], refs: ["e5"] }, }, heading: { type: "text", status: "extracted", value: "order\nšŸšššŸ“¦", confidence: 0.9, source: { chunks: ["title", "c1"], refs: ["e2"] }, }, tracking: { type: "text", status: "null", value: null, guess: "A-88412", confidence: 0.84, pNull: 0.99, source: null, }, }, appliedThresholds: { extract: 0.8, null: 0.5 }, referenceDate: "2026-10-23", truncated: false, usage: { input_tokens: 504, output_tokens: 0 }, }); expect(evaluate).toHaveBeenCalledWith( sentState, { order_id: { type: "text", instructions: "Order number", null_threshold: 0.5 }, total: { type: "number", null_threshold: 0.5 }, pay: { type: "text", null_threshold: 0.5 }, heading: { type: "text", null_threshold: 0.5 }, tracking: { type: "text", null_threshold: 0.5 }, }, { referenceDate: "2026-10-23" }, ); }); it("withholds values below the extract threshold and never invents a source", async () => { const fields = [ { name: "order_id", type: "text" }, { name: "misplaced", type: "text" }, ]; const answers = (text: string) => ({ order_id: { type: "text", value: "A-88412", span: spanOf(text, "A-88412"), confidence: 0.5 }, misplaced: { type: "text", value: "A-88412", span: spanOf(text, "Total"), confidence: 0.4 }, }); expect(await run(fields, answers).result).toMatchObject({ status: "uncertain", fields: { order_id: { status: "uncertain", value: null, guess: "A-88412", source: { chunks: ["c1"], refs: ["e2"] }, }, misplaced: { status: "uncertain", value: null, guess: "A-88412", source: null }, }, }); expect(await run(fields, answers, { thresholds: { extract: 0.45 } }).result).toMatchObject({ status: "partial", appliedThresholds: { extract: 0.45, null: 0.5 }, fields: { order_id: { status: "extracted", value: "A-88412" } }, }); }); it.each([ ["a missing answer", "date", {}], ["a different answer type", "date", { field: { type: "text", value: "2026-09-28" } }], ["a malformed date", "date", { field: { type: "date", value: "Sept 28" } }], ["a non-integer integer", "integer", { field: { type: "number", value: 2.5 } }], [ "an out-of-range confidence", "date", { field: { type: "date", value: null, confidence: 1.5 } }, ], ["a span past the state", "text", { field: { type: "text", value: "x", span: [0, 999] } }], [ "a list item of the wrong type", "list.date", { field: { type: "list", value: ["2026-09-28", "Sept 28"] } }, ], [ "spans that do not align with the items", "list", { field: { type: "list", value: ["a", "b"], spans: [[0, 1]] } }, ], [ "a response that does not report truncation", "number", { field: { type: "number", value: 1 } }, { truncated: undefined }, ], ])("rejects %s as provider_invalid_response", async (_label, type, answers, response?) => { const { result } = run([{ name: "field", type }], () => answers, { response }); await expect(result).rejects.toMatchObject({ code: "provider_invalid_response" }); }); it("passes field options through and fills the registry null threshold only when absent", async () => { const { result, evaluate } = run( [ { name: "total", type: "number", spec: { type: "number", unit: "USD", decimals: 2, null_threshold: 0.3 }, }, { name: "count", type: "integer", spec: { type: "number", integer: true } }, { name: "codes", type: "list", spec: { type: "list", items: "text" } }, ], () => ({ total: { type: "number", value: null }, count: { type: "number", value: null }, codes: { type: "list", value: [] }, }), ); expect((await result).fields.codes).toEqual({ type: "list", status: "null", value: null, sources: null, }); expect(evaluate.mock.calls[0][1]).toEqual({ total: { type: "number", unit: "USD", decimals: 2, null_threshold: 0.3 }, count: { type: "number", integer: true, null_threshold: 0.5 }, codes: { type: "list", items: "text" }, }); }); it("maps each list item to its own source and withholds an uncertain list", async () => { const fields = [ { name: "codes", type: "list" }, { name: "amounts", type: "list.number" }, ]; const answers = (confidence: number) => (text: string) => ({ codes: { type: "list", value: ["šŸ“¦", "A-88412"], spans: [spanOf(text, "šŸ“¦"), spanOf(text, "A-88412")], confidence, }, amounts: { type: "list", value: [701.1], spans: [spanOf(text, "701.10")], confidence }, }); expect((await run(fields, answers(0.9)).result).fields).toEqual({ codes: { type: "list", status: "extracted", value: ["šŸ“¦", "A-88412"], confidence: 0.9, sources: [ { chunks: ["c1"], refs: ["e2"] }, { chunks: ["c1"], refs: ["e2"] }, ], }, amounts: { type: "list.number", status: "extracted", value: [701.1], confidence: 0.9, sources: [null], }, }); expect((await run(fields, answers(0.44)).result).fields.codes).toEqual({ type: "list", status: "uncertain", value: null, guess: ["šŸ“¦", "A-88412"], confidence: 0.44, sources: [ { chunks: ["c1"], refs: ["e2"] }, { chunks: ["c1"], refs: ["e2"] }, ], }); }); });