@exulu/backend 5.1.2 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/{chunk-37MKZIH2.js → chunk-ASF74XFZ.js} +265 -32
  2. package/dist/{convert-exulu-tools-to-ai-sdk-tools-BNDHJH7B.js → convert-exulu-tools-to-ai-sdk-tools-MFLZQONB.js} +3 -1
  3. package/dist/index.cjs +2748 -351
  4. package/dist/index.js +2419 -304
  5. package/ee/agentic-retrieval/pipeline/config.test.ts +42 -0
  6. package/ee/agentic-retrieval/pipeline/config.ts +36 -0
  7. package/ee/agentic-retrieval/pipeline/index.test.ts +3 -3
  8. package/ee/agentic-retrieval/pipeline/index.ts +43 -1
  9. package/ee/agentic-retrieval/pipeline/micro-call.test.ts +58 -0
  10. package/ee/agentic-retrieval/pipeline/micro-call.ts +20 -3
  11. package/ee/agentic-retrieval/pipeline/near-duplicates.test.ts +50 -0
  12. package/ee/agentic-retrieval/pipeline/near-duplicates.ts +74 -0
  13. package/ee/agentic-retrieval/pipeline/prefilter.test.ts +32 -0
  14. package/ee/agentic-retrieval/pipeline/prefilter.ts +13 -1
  15. package/ee/agentic-retrieval/pipeline/rerank.test.ts +79 -0
  16. package/ee/agentic-retrieval/pipeline/rerank.ts +61 -6
  17. package/ee/claim-check/agent-config.ts +26 -0
  18. package/ee/claim-check/concurrency.test.ts +33 -0
  19. package/ee/claim-check/concurrency.ts +30 -0
  20. package/ee/claim-check/evidence.test.ts +198 -0
  21. package/ee/claim-check/evidence.ts +162 -0
  22. package/ee/claim-check/prompts/decompose.ts +52 -0
  23. package/ee/claim-check/prompts/disambiguate.ts +58 -0
  24. package/ee/claim-check/prompts/select-disambiguate.ts +17 -0
  25. package/ee/claim-check/prompts/select.ts +55 -0
  26. package/ee/claim-check/prompts/shared.test.ts +193 -0
  27. package/ee/claim-check/prompts/shared.ts +89 -0
  28. package/ee/claim-check/prompts/verify.ts +56 -0
  29. package/ee/claim-check/rate-limit.test.ts +40 -0
  30. package/ee/claim-check/rate-limit.ts +82 -0
  31. package/ee/claim-check/routes.test.ts +1188 -0
  32. package/ee/claim-check/routes.ts +682 -0
  33. package/ee/claim-check/run.test.ts +1317 -0
  34. package/ee/claim-check/run.ts +710 -0
  35. package/ee/claim-check/score.test.ts +108 -0
  36. package/ee/claim-check/score.ts +75 -0
  37. package/ee/claim-check/second-chance.test.ts +89 -0
  38. package/ee/claim-check/second-chance.ts +80 -0
  39. package/ee/claim-check/split.test.ts +179 -0
  40. package/ee/claim-check/split.ts +220 -0
  41. package/ee/claim-check/stages/decompose.test.ts +129 -0
  42. package/ee/claim-check/stages/decompose.ts +64 -0
  43. package/ee/claim-check/stages/disambiguate.test.ts +130 -0
  44. package/ee/claim-check/stages/disambiguate.ts +74 -0
  45. package/ee/claim-check/stages/select-disambiguate.test.ts +137 -0
  46. package/ee/claim-check/stages/select-disambiguate.ts +90 -0
  47. package/ee/claim-check/stages/select.test.ts +155 -0
  48. package/ee/claim-check/stages/select.ts +94 -0
  49. package/ee/claim-check/stages/usage.ts +11 -0
  50. package/ee/claim-check/stages/verify.test.ts +154 -0
  51. package/ee/claim-check/stages/verify.ts +78 -0
  52. package/ee/claim-check/types.ts +178 -0
  53. package/ee/entitlements.ts +3 -0
  54. package/ee/schemas.ts +71 -0
  55. package/package.json +1 -1
@@ -0,0 +1,1317 @@
1
+ jest.mock("./stages/select-disambiguate", () => ({ runSelectAndDisambiguate: jest.fn() }));
2
+ jest.mock("./stages/select", () => ({ runSelection: jest.fn(), excerptFor: jest.fn(() => "excerpt") }));
3
+ jest.mock("./stages/disambiguate", () => ({ runDisambiguation: jest.fn() }));
4
+ jest.mock("./stages/decompose", () => ({ runDecomposition: jest.fn() }));
5
+ jest.mock("./stages/verify", () => ({ runVerification: jest.fn() }));
6
+
7
+ import { runSelectAndDisambiguate } from "./stages/select-disambiguate";
8
+ import { runSelection } from "./stages/select";
9
+ import { runDisambiguation } from "./stages/disambiguate";
10
+ import { runDecomposition } from "./stages/decompose";
11
+ import { runVerification } from "./stages/verify";
12
+ import { BISECT_FLOOR, MAX_EVIDENCE_PER_CALL, runClaimCheck, selectGroupEvidence } from "./run";
13
+ import { indexSources, selectEvidence, MAX_CHARS_PER_SOURCE } from "./evidence";
14
+ import { CLAIM_CHECK_DEFAULTS, type ClaimCheckOptions } from "./types";
15
+
16
+ const USAGE = { calls: 1, inputTokens: 100, outputTokens: 10 };
17
+ const options = (over: Partial<ClaimCheckOptions> = {}): ClaimCheckOptions => ({
18
+ ...CLAIM_CHECK_DEFAULTS,
19
+ ...over,
20
+ thresholds: { ...CLAIM_CHECK_DEFAULTS.thresholds, ...(over.thresholds ?? {}) },
21
+ caps: { ...CLAIM_CHECK_DEFAULTS.caps, ...(over.caps ?? {}) },
22
+ });
23
+
24
+ const SOURCES = [{ id: "s1", content: "Die FST-2XT arbeitet mit 230 Volt im Schaltschrank." }];
25
+ const ANSWER = "Die FST-2XT arbeitet mit 230 Volt. Das ist beeindruckend. Sie sitzt im Schaltschrank.";
26
+
27
+ /** All three sentences verifiable and resolvable. */
28
+ const allClear = (indexes: number[]) => ({
29
+ selection: indexes.map((index) => ({ index, verifiable: true, rewritten: null, reason: "fact", answered: true })),
30
+ disambiguation: indexes.map((index) => ({ index, resolvable: true, clarified: null, reason: "clear", answered: true })),
31
+ usage: USAGE,
32
+ });
33
+
34
+ beforeEach(() => {
35
+ [runSelectAndDisambiguate, runSelection, runDisambiguation, runDecomposition, runVerification].forEach((m) =>
36
+ (m as jest.Mock).mockReset(),
37
+ );
38
+ });
39
+
40
+ describe("runClaimCheck — fast path", () => {
41
+ it("uses the merged call, then decomposition, then verification, and assembles a scored result", async () => {
42
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
43
+ allClear(windows.map((w: any) => w.sentence.index)),
44
+ );
45
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
46
+ outcomes: windows.map((w: any) => ({
47
+ index: w.sentence.index,
48
+ claims: [{ text: `claim for ${w.sentence.index}`, inferred: false }],
49
+ })),
50
+ usage: USAGE,
51
+ }));
52
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
53
+ outcomes: claims.map((c: any, i: number) => ({
54
+ claimId: c.id,
55
+ verdict: i === 0 ? "supported" : "unsupported",
56
+ evidence: [],
57
+ rationale: "r",
58
+ })),
59
+ usage: USAGE,
60
+ }));
61
+
62
+ const result = await runClaimCheck({
63
+ question: "Womit arbeitet die FST-2XT?",
64
+ answer: ANSWER,
65
+ sources: SOURCES,
66
+ model: {} as any,
67
+ options: options(),
68
+ locale: "de",
69
+ });
70
+
71
+ expect(runSelection).not.toHaveBeenCalled();
72
+ expect(runDisambiguation).not.toHaveBeenCalled();
73
+ expect(result.status).toBe("ok");
74
+ expect(result.claims).toHaveLength(3);
75
+ expect(result.claims.map((c) => c.id)).toEqual(["c1", "c2", "c3"]);
76
+ expect(result.score.claims).toBe(3);
77
+ expect(result.sentences.every((s) => s.state === "checked")).toBe(true);
78
+ expect(result.usage.calls).toBeGreaterThanOrEqual(3);
79
+ expect(result.timings.totalMs).toBeGreaterThanOrEqual(0);
80
+ });
81
+
82
+ it("records dropped sentences with their reason and keeps them out of the score", async () => {
83
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) => ({
84
+ selection: windows.map((w: any) => ({
85
+ index: w.sentence.index,
86
+ verifiable: w.sentence.index !== 1,
87
+ rewritten: null,
88
+ reason: w.sentence.index === 1 ? "opinion" : "fact",
89
+ })),
90
+ disambiguation: windows.map((w: any) => ({
91
+ index: w.sentence.index,
92
+ resolvable: w.sentence.index === 0,
93
+ clarified: null,
94
+ reason: w.sentence.index === 2 ? "'Sie' unresolvable" : "clear",
95
+ })),
96
+ usage: USAGE,
97
+ }));
98
+ (runDecomposition as jest.Mock).mockResolvedValue({
99
+ outcomes: [{ index: 0, claims: [{ text: "c", inferred: false }] }],
100
+ usage: USAGE,
101
+ });
102
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
103
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
104
+ usage: USAGE,
105
+ }));
106
+
107
+ const result = await runClaimCheck({
108
+ question: "q", answer: ANSWER, sources: SOURCES, model: {} as any, options: options(), locale: "de",
109
+ });
110
+
111
+ expect(result.sentences.map((s) => s.state)).toEqual(["checked", "no_verifiable_content", "cannot_disambiguate"]);
112
+ expect(result.sentences[1]!.reason).toBe("opinion");
113
+ expect(result.score.claims).toBe(1);
114
+ // Decomposition only ever saw the surviving sentence.
115
+ expect((runDecomposition as jest.Mock).mock.calls[0][0].windows).toHaveLength(1);
116
+ });
117
+
118
+ // Review Focus 4
119
+ it("returns label n/a with no claims when every sentence is dropped, and never calls verification", async () => {
120
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) => ({
121
+ selection: windows.map((w: any) => ({ index: w.sentence.index, verifiable: false, rewritten: null, reason: "pleasantry" })),
122
+ disambiguation: windows.map((w: any) => ({ index: w.sentence.index, resolvable: false, clarified: null, reason: "pleasantry" })),
123
+ usage: USAGE,
124
+ }));
125
+
126
+ const result = await runClaimCheck({
127
+ question: "q", answer: "Gern! Immer wieder.", sources: SOURCES, model: {} as any, options: options(), locale: "de",
128
+ });
129
+
130
+ expect(runDecomposition).not.toHaveBeenCalled();
131
+ expect(runVerification).not.toHaveBeenCalled();
132
+ expect(result.claims).toEqual([]);
133
+ expect(result.score.label).toBe("n/a");
134
+ expect(result.status).toBe("ok");
135
+ });
136
+ });
137
+
138
+ // Finding 3 (spec §2.4 rule 3): sources: [] (or whitespace-only content) used
139
+ // to produce label "alert", unsupportedShare 1.0, status "ok" and no notes —
140
+ // a 100% hallucination verdict produced without reading a byte.
141
+ describe("runClaimCheck — no usable evidence", () => {
142
+ const allClaims = () => {
143
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
144
+ allClear(windows.map((w: any) => w.sentence.index)),
145
+ );
146
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
147
+ outcomes: windows.map((w: any) => ({
148
+ index: w.sentence.index,
149
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
150
+ })),
151
+ usage: USAGE,
152
+ }));
153
+ // What the real verify stage does with an empty evidence array.
154
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
155
+ outcomes: claims.map((c: any) => ({
156
+ claimId: c.id,
157
+ verdict: "unsupported",
158
+ evidence: [],
159
+ rationale: "no evidence was available for this claim",
160
+ })),
161
+ usage: USAGE,
162
+ }));
163
+ };
164
+
165
+ it("reports n/a and partial instead of a 100% unsupported share when no source has any content", async () => {
166
+ allClaims();
167
+ const result = await runClaimCheck({
168
+ question: "q", answer: ANSWER, sources: [], model: {} as any, options: options(), locale: "de",
169
+ });
170
+
171
+ expect(result.score.label).toBe("n/a");
172
+ expect(result.score.claims).toBe(0);
173
+ expect(result.score.unsupportedShare).toBe(0);
174
+ expect(result.status).toBe("partial");
175
+ // The claims themselves are kept, with their verdicts and rationales.
176
+ expect(result.claims).toHaveLength(3);
177
+ expect(result.claims.every((c) => c.verdict === "unsupported")).toBe(true);
178
+ expect(result.claims[0]!.rationale).toBe("no evidence was available for this claim");
179
+ expect(result.notes.some((n) => n.includes("no usable evidence was supplied"))).toBe(true);
180
+ });
181
+
182
+ it("treats whitespace-only source content as no evidence at all", async () => {
183
+ allClaims();
184
+ const result = await runClaimCheck({
185
+ question: "q",
186
+ answer: ANSWER,
187
+ sources: [{ id: "blank", content: " \n\t " }],
188
+ model: {} as any,
189
+ options: options(),
190
+ locale: "de",
191
+ });
192
+
193
+ expect(result.score.label).toBe("n/a");
194
+ expect(result.status).toBe("partial");
195
+ expect(result.notes.some((n) => n.includes("no usable evidence was supplied"))).toBe(true);
196
+ });
197
+
198
+ it("still scores the claims a second-chance retrieval did supply evidence for", async () => {
199
+ allClaims();
200
+ let verifyCall = 0;
201
+ (runVerification as jest.Mock).mockImplementation(async ({ claims, evidence }) => {
202
+ verifyCall += 1;
203
+ return {
204
+ outcomes: claims.map((c: any) => ({
205
+ claimId: c.id,
206
+ verdict: evidence.length > 0 ? "supported" : "unsupported",
207
+ evidence: [],
208
+ rationale: verifyCall === 1 ? "no evidence was available for this claim" : "found later",
209
+ })),
210
+ usage: USAGE,
211
+ };
212
+ });
213
+ const secondChance = jest
214
+ .fn()
215
+ .mockResolvedValue([{ sourceId: "deep", text: "Die FST-2XT arbeitet mit 230 Volt.", score: 2 }]);
216
+
217
+ const result = await runClaimCheck({
218
+ question: "q",
219
+ answer: ANSWER,
220
+ sources: [],
221
+ model: {} as any,
222
+ options: options({ caps: { maxReRetrievals: 3 } }),
223
+ locale: "de",
224
+ secondChance,
225
+ });
226
+
227
+ // All three claims were re-retrieved and judged against real passages, so
228
+ // the score is honest again and nothing is excluded.
229
+ expect(result.claims.every((c) => c.rechecked)).toBe(true);
230
+ expect(result.score.claims).toBe(3);
231
+ expect(result.score.label).toBe("ok");
232
+ expect(result.notes.some((n) => n.includes("no usable evidence was supplied"))).toBe(false);
233
+ });
234
+ });
235
+
236
+ describe("runClaimCheck — resilience", () => {
237
+ // Finding 3 (R19): "partial beats failing" is unconditional — an error
238
+ // thrown anywhere in the pipeline (not just a provider call) must degrade
239
+ // to a partial result rather than reject the caller's promise. An invalid
240
+ // Intl.Segmenter locale throws synchronously inside the split stage, before
241
+ // any stage mock is ever reached.
242
+ //
243
+ // Finding 14: the HTTP route now rejects an unusable locale with a 400
244
+ // (routes.test.ts), so this is no longer reachable through the API. It stays
245
+ // as the engine's own guarantee — runClaimCheck is called directly here, and
246
+ // every internal caller (the benchmark runner, a future chat path) depends
247
+ // on it degrading rather than throwing.
248
+ it("degrades to a partial result instead of throwing when the pipeline itself throws", async () => {
249
+ const result = await runClaimCheck({
250
+ question: "q",
251
+ answer: ANSWER,
252
+ sources: SOURCES,
253
+ model: {} as any,
254
+ options: options(),
255
+ locale: "💥not-a-locale💥",
256
+ });
257
+
258
+ expect(result.status).toBe("partial");
259
+ expect(result.claims).toEqual([]);
260
+ expect(result.sentences).toEqual([]);
261
+ expect(result.score.label).toBe("n/a");
262
+ expect(result.notes.some((n) => n.includes("claim check failed internally"))).toBe(true);
263
+ expect(runSelectAndDisambiguate).not.toHaveBeenCalled();
264
+ });
265
+
266
+
267
+ // Change B: BATCH.selectDisambiguate rose to 25, so a failed batch now
268
+ // bisects RECURSIVELY down to BISECT_FLOOR rather than once —
269
+ // 25 -> 13 + 12 -> 7 + 6 + 6 + 6 — and the sentences lost to a failure are
270
+ // the smallest still-failing piece, not half the batch. The fixture is 25
271
+ // sentences (one full batch) because the previous 3-sentence fixture is now
272
+ // below the floor and is never split at all.
273
+ it("bisects a failed batch recursively down to the floor and only loses the still-failing piece", async () => {
274
+ const answer = Array.from({ length: 25 }, (_, i) => `Satz Nummer ${i + 1} ist eindeutig wahr.`).join(" ");
275
+ const seen: number[][] = [];
276
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) => {
277
+ const indexes = windows.map((w: any) => w.sentence.index);
278
+ seen.push(indexes);
279
+ // Fails for its SIZE above the floor — the deterministic output-overflow
280
+ // shape the recursion exists for — and at or below the floor only for
281
+ // the one piece holding sentence 24.
282
+ if (indexes.length > BISECT_FLOOR) throw new Error("batch too big for the provider today");
283
+ if (indexes.includes(24)) throw new Error("still failing");
284
+ return allClear(indexes);
285
+ });
286
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
287
+ outcomes: windows.map((w: any) => ({
288
+ index: w.sentence.index,
289
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
290
+ })),
291
+ usage: USAGE,
292
+ }));
293
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
294
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
295
+ usage: USAGE,
296
+ }));
297
+
298
+ const result = await runClaimCheck({
299
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
300
+ });
301
+
302
+ // The whole batch, its halves, then THEIR halves — which are at or below
303
+ // the floor and are never split again.
304
+ expect(seen.map((b) => b.length)).toEqual([25, 13, 12, 7, 6, 6, 6]);
305
+ // Everything outside the single piece that kept failing survived the
306
+ // batch's collapse. A one-shot bisect loses all 25; no floor at all would
307
+ // keep splitting and lose only [22, 23, 24].
308
+ expect(result.sentences.filter((s) => s.state === "not_checked").map((s) => s.index)).toEqual([
309
+ 19, 20, 21, 22, 23, 24,
310
+ ]);
311
+ expect(result.sentences.filter((s) => s.state === "checked")).toHaveLength(19);
312
+ expect(result.sentences[19]!.reason).toBe("selection+disambiguation failed after bisect");
313
+ expect(result.status).toBe("partial");
314
+ expect(result.notes.join(" ")).toContain("not_checked");
315
+ });
316
+
317
+ // With only one batch the breaker's failures>=2 floor can never trip, so a
318
+ // lone failing batch always gets its bisect — and now gets it twice over,
319
+ // because the breaker deliberately does not re-run on the retry rounds (an
320
+ // output overflow is deterministic in batch size, so every sibling failing
321
+ // is the signal to split further, not to give up). The call count is the
322
+ // whole point of this test: it pins the recursion, the floor AND that
323
+ // non-re-running breaker at once.
324
+ it("recurses a lone failing batch to the floor without the breaker, for 1 + 2 + 4 calls", async () => {
325
+ const answer = Array.from({ length: 25 }, (_, i) => `Satz Nummer ${i + 1} ist eindeutig wahr.`).join(" ");
326
+ (runSelectAndDisambiguate as jest.Mock).mockRejectedValue(new Error("provider down"));
327
+
328
+ const result = await runClaimCheck({
329
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
330
+ });
331
+
332
+ // 7: a one-shot bisect would be 3, a breaker re-run at round 1 would be 3,
333
+ // and splitting past the floor would be 15.
334
+ expect((runSelectAndDisambiguate as jest.Mock).mock.calls.length).toBe(7);
335
+ expect(result.status).toBe("partial");
336
+ expect(result.claims).toEqual([]);
337
+ expect(result.sentences.every((s) => s.state === "not_checked")).toBe(true);
338
+ expect(result.sentences).toHaveLength(25);
339
+ expect(result.notes.some((n) => n.includes("selection+disambiguation"))).toBe(true);
340
+ expect(result.notes.some((n) => n.includes("aborted"))).toBe(false);
341
+ });
342
+
343
+ // The floor must bound the recursion's DEPTH, not refuse the first retry.
344
+ // Applying it to the original batch as well took the brief's lone-batch
345
+ // guarantee away below 8 sentences: a failing batch of 2-8 got ZERO retries
346
+ // (1 call) and lost every sentence, where {10, 5, 3} bisected and recovered
347
+ // half. Each row here is one batch that fails whole and succeeds in halves.
348
+ it.each([2, 3, 8])("bisects a lone failing batch of %i sentences at round 0, below the floor", async (n) => {
349
+ expect(n).toBeLessThanOrEqual(BISECT_FLOOR);
350
+ const answer = Array.from({ length: n }, (_, i) => `Satz Nummer ${i + 1} ist eindeutig wahr.`).join(" ");
351
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) => {
352
+ if (windows.length === n) throw new Error("batch too big for the provider today");
353
+ return allClear(windows.map((w: any) => w.sentence.index));
354
+ });
355
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
356
+ outcomes: windows.map((w: any) => ({
357
+ index: w.sentence.index,
358
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
359
+ })),
360
+ usage: USAGE,
361
+ }));
362
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
363
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
364
+ usage: USAGE,
365
+ }));
366
+
367
+ const result = await runClaimCheck({
368
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
369
+ });
370
+
371
+ // The whole batch, then its two halves. Applying the floor at round 0
372
+ // makes this 1 call and loses every sentence.
373
+ expect((runSelectAndDisambiguate as jest.Mock).mock.calls.length).toBe(3);
374
+ expect(result.sentences.every((s) => s.state === "checked")).toBe(true);
375
+ expect(result.status).toBe("ok");
376
+ });
377
+
378
+ // Finding 2 (R18): a genuine multi-batch circuit-breaker fixture. 60
379
+ // sentences batch into [25, 25, 10] for BATCH.selectDisambiguate = 25; the
380
+ // mock fails only the two full-size (un-bisected) batches outright — any
381
+ // bisected retry (always length < 25) would succeed — so disabling the
382
+ // breaker changes the outcome: the aborted batches' sentences would recover
383
+ // via their retries instead of staying not_checked, and the call count
384
+ // would rise from 3 to 7. That is the sensitivity check this test relies on.
385
+ it("trips the circuit breaker across multiple batches and never retries the aborted ones", async () => {
386
+ const answer = Array.from({ length: 60 }, (_, i) => `Satz Nummer ${i + 1} ist eindeutig wahr.`).join(" ");
387
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) => {
388
+ const indexes = windows.map((w: any) => w.sentence.index);
389
+ if (indexes.length === 25 && (indexes[0] === 0 || indexes[0] === 25)) {
390
+ throw new Error("provider down for this batch");
391
+ }
392
+ return allClear(indexes);
393
+ });
394
+ (runDecomposition as jest.Mock).mockResolvedValue({ outcomes: [], usage: USAGE });
395
+
396
+ const result = await runClaimCheck({
397
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
398
+ });
399
+
400
+ // Only the 3 initial batch calls — the breaker fired before any bisect
401
+ // retry was attempted for the two failing batches.
402
+ expect((runSelectAndDisambiguate as jest.Mock).mock.calls.length).toBe(3);
403
+ expect(result.status).toBe("partial");
404
+ expect(result.notes.some((n) => n.includes("selection+disambiguation") && n.includes("aborted"))).toBe(true);
405
+ expect(result.sentences[0]!.state).toBe("not_checked");
406
+ expect(result.sentences[30]!.state).toBe("not_checked");
407
+ });
408
+
409
+ // Review Focus 5
410
+ it("caps sentences and claims, flags the result partial, and keeps claim ids contiguous", async () => {
411
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
412
+ allClear(windows.map((w: any) => w.sentence.index)),
413
+ );
414
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
415
+ outcomes: windows.map((w: any) => ({
416
+ index: w.sentence.index,
417
+ claims: [
418
+ { text: `a${w.sentence.index}`, inferred: false },
419
+ { text: `b${w.sentence.index}`, inferred: false },
420
+ ],
421
+ })),
422
+ usage: USAGE,
423
+ }));
424
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
425
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
426
+ usage: USAGE,
427
+ }));
428
+
429
+ const result = await runClaimCheck({
430
+ question: "q",
431
+ answer: ANSWER,
432
+ sources: SOURCES,
433
+ model: {} as any,
434
+ options: options({ caps: { maxSentences: 2, maxClaims: 3, maxReRetrievals: 0 } }),
435
+ locale: "de",
436
+ });
437
+
438
+ expect(result.status).toBe("partial");
439
+ expect(result.limits.sentencesSkipped).toBe(1);
440
+ expect(result.sentences.find((s) => s.index === 2)!.reason).toBe("cap_exceeded");
441
+ expect(result.claims.map((c) => c.id)).toEqual(["c1", "c2", "c3"]);
442
+ expect(result.notes.some((n) => n.includes("maxClaims"))).toBe(true);
443
+ });
444
+
445
+ // Review Focus 5
446
+ it("drops a decomposition outcome whose sentence index was never in the batch", async () => {
447
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
448
+ allClear(windows.map((w: any) => w.sentence.index)),
449
+ );
450
+ (runDecomposition as jest.Mock).mockResolvedValue({
451
+ outcomes: [
452
+ { index: 0, claims: [{ text: "echt", inferred: false }] },
453
+ { index: 42, claims: [{ text: "erfunden", inferred: false }] },
454
+ ],
455
+ usage: USAGE,
456
+ });
457
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
458
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
459
+ usage: USAGE,
460
+ }));
461
+
462
+ const result = await runClaimCheck({
463
+ question: "q", answer: ANSWER, sources: SOURCES, model: {} as any, options: options(), locale: "de",
464
+ });
465
+
466
+ expect(result.claims).toHaveLength(1);
467
+ expect(result.claims[0]!.text).toBe("echt");
468
+ expect(result.claims[0]!.sentenceIndex).toBe(0);
469
+ });
470
+
471
+ // Finding 4 (R20): a surviving sentence whose decomposed claims were ALL cut
472
+ // by maxClaims must read as cap_exceeded, not no_verifiable_content — the
473
+ // cap is a resource limit, not a judgement that the sentence had nothing
474
+ // checkable in it.
475
+ it("marks a sentence cap_exceeded, not no_verifiable_content, when the cap cuts all of its claims", async () => {
476
+ const answer = "Erster Satz ist eindeutig. Zweiter Satz ist auch eindeutig.";
477
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
478
+ allClear(windows.map((w: any) => w.sentence.index)),
479
+ );
480
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
481
+ outcomes: windows.map((w: any) => ({
482
+ index: w.sentence.index,
483
+ claims: [
484
+ { text: `a${w.sentence.index}`, inferred: false },
485
+ { text: `b${w.sentence.index}`, inferred: false },
486
+ ],
487
+ })),
488
+ usage: USAGE,
489
+ }));
490
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
491
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
492
+ usage: USAGE,
493
+ }));
494
+
495
+ const result = await runClaimCheck({
496
+ question: "q",
497
+ answer,
498
+ sources: SOURCES,
499
+ model: {} as any,
500
+ // maxClaims = 2 exhausts entirely on sentence 0's two claims, so
501
+ // sentence 1's two claims are cut before either one is pushed.
502
+ options: options({ caps: { maxClaims: 2 } }),
503
+ locale: "de",
504
+ });
505
+
506
+ expect(result.claims).toHaveLength(2);
507
+ expect(result.sentences[0]!.state).toBe("checked");
508
+ expect(result.sentences[1]!.state).toBe("not_checked");
509
+ expect(result.sentences[1]!.reason).toBe("cap_exceeded");
510
+ expect(result.status).toBe("partial");
511
+ });
512
+
513
+ // Correction 2: runDecomposition OMITS an entry entirely for a sentence the
514
+ // model never answered, which must read as "the pipeline failed to process
515
+ // this sentence" (not_checked), not as "no factual claim here"
516
+ // (no_verifiable_content, which is reserved for a reported-but-empty claim list).
517
+ it("tells apart an empty claim list from a decomposition outcome that was never reported", async () => {
518
+ const answer = "Die Anlage läuft stabil. Das Blech ist blau.";
519
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
520
+ allClear(windows.map((w: any) => w.sentence.index)),
521
+ );
522
+ // Reports an (empty) outcome for sentence 0, says nothing at all about sentence 1.
523
+ (runDecomposition as jest.Mock).mockResolvedValue({
524
+ outcomes: [{ index: 0, claims: [] }],
525
+ usage: USAGE,
526
+ });
527
+
528
+ const result = await runClaimCheck({
529
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
530
+ });
531
+
532
+ expect(result.sentences[0]!.state).toBe("no_verifiable_content");
533
+ expect(result.sentences[0]!.reason).toBe("decomposition extracted no claim");
534
+ expect(result.sentences[1]!.state).toBe("not_checked");
535
+ expect(result.sentences[1]!.reason).toBe("decomposition did not report an outcome");
536
+ expect(result.status).toBe("partial");
537
+ expect(runVerification).not.toHaveBeenCalled();
538
+ });
539
+ });
540
+
541
+ // Finding 4: the model's silence is not a finding against the answer. Both
542
+ // places that used to turn an omitted outcome into a verdict about the text.
543
+ // Finding 5: per-source truncation has to be visible — the engine drops
544
+ // everything past 60,000 characters per source and never searches it.
545
+ // Finding 6: evidence selection is a per-claim job (spec §2.2). Pooling a
546
+ // group's claim texts into one query starved the weaker-scoring claims, and
547
+ // the failure mode is a false "unsupported".
548
+ describe("evidence selection per claim", () => {
549
+ // Four passages carry two rare terms of claim A each (score 3.58); the one
550
+ // passage that supports claim B carries three less-rare terms (3.30). The
551
+ // pooled top-4 is therefore exactly the four A passages, and claim B goes
552
+ // into verification with nothing that mentions it.
553
+ const SELECTION_SOURCES = [
554
+ { id: "a1", content: "Steuerung meldet." },
555
+ { id: "a2", content: "Fernabschaltung Sicherung." },
556
+ { id: "a3", content: "Defekt Schaltschrank." },
557
+ { id: "a4", content: "Verschlossen Kabinenlicht." },
558
+ { id: "b1", content: "Kabinentuer Dienstag getauscht." },
559
+ { id: "d1", content: "Kabinentuer Dienstag getauscht Protokoll." },
560
+ ];
561
+ const CLAIM_A =
562
+ "Die Steuerung meldet eine Fernabschaltung, die Sicherung ist defekt, der Schaltschrank ist verschlossen und das Kabinenlicht flackert.";
563
+ const CLAIM_B = "Die Kabinentuer wurde am Dienstag getauscht.";
564
+
565
+ it("is a fixture where pooling really does starve the second claim", () => {
566
+ const pooled = selectEvidence([CLAIM_A, CLAIM_B], indexSources(SELECTION_SOURCES), 4);
567
+ expect(pooled.map((p) => p.sourceId)).not.toContain("b1");
568
+ });
569
+
570
+ it("gives two claims with disjoint vocabularies each their own supporting passage", async () => {
571
+ const answer = "Die Steuerung meldet eine Fernabschaltung. Die Kabinentuer wurde getauscht.";
572
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
573
+ allClear(windows.map((w: any) => w.sentence.index)),
574
+ );
575
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
576
+ outcomes: windows.map((w: any) => ({
577
+ index: w.sentence.index,
578
+ claims: [{ text: w.sentence.index === 0 ? CLAIM_A : CLAIM_B, inferred: false }],
579
+ })),
580
+ usage: USAGE,
581
+ }));
582
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
583
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
584
+ usage: USAGE,
585
+ }));
586
+
587
+ await runClaimCheck({
588
+ question: "q",
589
+ answer,
590
+ sources: SELECTION_SOURCES,
591
+ model: {} as any,
592
+ options: options(),
593
+ locale: "de",
594
+ });
595
+
596
+ // Both claims are in ONE verification group (BATCH.verifySentences = 8).
597
+ expect((runVerification as jest.Mock).mock.calls).toHaveLength(1);
598
+ const evidence = (runVerification as jest.Mock).mock.calls[0][0].evidence as { sourceId: string }[];
599
+ const ids = evidence.map((e) => e.sourceId);
600
+ expect(ids).toContain("b1");
601
+ expect(ids.some((id) => id.startsWith("a"))).toBe(true);
602
+ });
603
+
604
+ it("deduplicates the union by passage identity and caps it per call", () => {
605
+ const sources = Array.from({ length: 20 }, (_, i) => ({
606
+ id: `s${i}`,
607
+ content: `Begriff${i} Begriff${i} dokumentiert.`,
608
+ }));
609
+ const index = indexSources(sources);
610
+ const claims = Array.from({ length: 20 }, (_, i) => `Begriff${i} ist dokumentiert.`);
611
+
612
+ const union = selectGroupEvidence(claims, index);
613
+ expect(union).toHaveLength(MAX_EVIDENCE_PER_CALL);
614
+ // Rank-first filling: every one of the first twelve claims contributed its
615
+ // OWN best passage, instead of the first four claims taking three each.
616
+ expect(new Set(union.map((e) => e.sourceId)).size).toBe(MAX_EVIDENCE_PER_CALL);
617
+ for (let i = 0; i < MAX_EVIDENCE_PER_CALL; i += 1) {
618
+ expect(union.map((e) => e.sourceId)).toContain(`s${i}`);
619
+ }
620
+ });
621
+
622
+ it("returns nothing when there are no passages at all", () => {
623
+ expect(selectGroupEvidence(["irgendein Claim"], indexSources([]))).toEqual([]);
624
+ });
625
+ });
626
+
627
+ // Finding 7: the HTTP handler's 60 s deadline has to reach the provider calls.
628
+ describe("runClaimCheck — abort signal", () => {
629
+ it("forwards the caller's signal to every stage", async () => {
630
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
631
+ allClear(windows.map((w: any) => w.sentence.index)),
632
+ );
633
+ (runDecomposition as jest.Mock).mockResolvedValue({
634
+ outcomes: [{ index: 0, claims: [{ text: "c", inferred: false }] }],
635
+ usage: USAGE,
636
+ });
637
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
638
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
639
+ usage: USAGE,
640
+ }));
641
+ const controller = new AbortController();
642
+
643
+ await runClaimCheck({
644
+ question: "q",
645
+ answer: ANSWER,
646
+ sources: SOURCES,
647
+ model: {} as any,
648
+ options: options(),
649
+ locale: "de",
650
+ signal: controller.signal,
651
+ });
652
+
653
+ expect((runSelectAndDisambiguate as jest.Mock).mock.calls[0][0].signal).toBe(controller.signal);
654
+ expect((runDecomposition as jest.Mock).mock.calls[0][0].signal).toBe(controller.signal);
655
+ expect((runVerification as jest.Mock).mock.calls[0][0].signal).toBe(controller.signal);
656
+ });
657
+ });
658
+
659
+ describe("runClaimCheck — source truncation", () => {
660
+ it("flags limits.truncated and notes the dropped characters when a source is cut", async () => {
661
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
662
+ allClear(windows.map((w: any) => w.sentence.index)),
663
+ );
664
+ // Every sentence gets an outcome, so truncation is the ONLY thing that can
665
+ // make these two results `partial`: a decomposition reporting on one of
666
+ // three sentences degrades the result by itself, and would have let the
667
+ // status assertions below pass under the very bug they pin.
668
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
669
+ outcomes: windows.map((w: any) => ({
670
+ index: w.sentence.index,
671
+ claims: [{ text: `c${w.sentence.index}`, inferred: false }],
672
+ })),
673
+ usage: USAGE,
674
+ }));
675
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
676
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
677
+ usage: USAGE,
678
+ }));
679
+
680
+ const result = await runClaimCheck({
681
+ question: "q",
682
+ answer: ANSWER,
683
+ sources: [{ id: "handbuch", content: `Die FST-2XT arbeitet mit 230 Volt. ${"x".repeat(60_000)}` }],
684
+ model: {} as any,
685
+ options: options(),
686
+ locale: "de",
687
+ });
688
+
689
+ expect(result.limits.truncated).toBe(true);
690
+ expect(result.limits.sentencesSkipped).toBe(0);
691
+ expect(result.notes.some((n) => n.includes("truncated at 60000 characters"))).toBe(true);
692
+ expect(result.notes.some((n) => n.includes("35 character(s) of evidence were not searched"))).toBe(true);
693
+ // R35: part of the evidence went unread, so the share of unsupported
694
+ // claims is not a number this check measured. Every other
695
+ // partly-measured outcome reports `partial`, including the zero-evidence
696
+ // case below, which is the same question of degree.
697
+ expect(result.status).toBe("partial");
698
+ });
699
+
700
+ it("leaves limits.truncated false when every source fits", async () => {
701
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
702
+ allClear(windows.map((w: any) => w.sentence.index)),
703
+ );
704
+ // Every sentence gets an outcome, so truncation is the ONLY thing that can
705
+ // make these two results `partial`: a decomposition reporting on one of
706
+ // three sentences degrades the result by itself, and would have let the
707
+ // status assertions below pass under the very bug they pin.
708
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
709
+ outcomes: windows.map((w: any) => ({
710
+ index: w.sentence.index,
711
+ claims: [{ text: `c${w.sentence.index}`, inferred: false }],
712
+ })),
713
+ usage: USAGE,
714
+ }));
715
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
716
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
717
+ usage: USAGE,
718
+ }));
719
+
720
+ const result = await runClaimCheck({
721
+ question: "q", answer: ANSWER, sources: SOURCES, model: {} as any, options: options(), locale: "de",
722
+ });
723
+
724
+ expect(result.limits.truncated).toBe(false);
725
+ expect(result.notes.some((n) => n.includes("truncated"))).toBe(false);
726
+ // The discriminator for the assertion above: truncation is what turns a
727
+ // check partial here, not the fixture.
728
+ expect(result.status).toBe("ok");
729
+ });
730
+
731
+ it("names the truncated source in the note it already emits", async () => {
732
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
733
+ allClear(windows.map((w: any) => w.sentence.index)),
734
+ );
735
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
736
+ outcomes: windows.map((w: any) => ({
737
+ index: w.sentence.index,
738
+ claims: [{ text: `c${w.sentence.index}`, inferred: false }],
739
+ })),
740
+ usage: USAGE,
741
+ }));
742
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
743
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
744
+ usage: USAGE,
745
+ }));
746
+
747
+ const result = await runClaimCheck({
748
+ question: "q",
749
+ answer: ANSWER,
750
+ sources: [
751
+ { id: "big", name: "handbuch.pdf", content: "x".repeat(MAX_CHARS_PER_SOURCE + 100) },
752
+ { id: "small", content: "fits" },
753
+ ],
754
+ model: {} as any,
755
+ options: options(),
756
+ locale: "de",
757
+ });
758
+ expect(result.status).toBe("partial"); // unchanged behaviour
759
+ expect(result.limits.truncated).toBe(true); // unchanged behaviour
760
+ const note = result.notes.find((n) => n.includes("truncated"));
761
+ expect(note).toContain("handbuch.pdf");
762
+ expect(note).not.toContain("small"); // an uncut source is not named
763
+ });
764
+
765
+ it("falls back to the id when a truncated source has no name", async () => {
766
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
767
+ allClear(windows.map((w: any) => w.sentence.index)),
768
+ );
769
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
770
+ outcomes: windows.map((w: any) => ({
771
+ index: w.sentence.index,
772
+ claims: [{ text: `c${w.sentence.index}`, inferred: false }],
773
+ })),
774
+ usage: USAGE,
775
+ }));
776
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
777
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
778
+ usage: USAGE,
779
+ }));
780
+
781
+ const result = await runClaimCheck({
782
+ question: "q",
783
+ answer: ANSWER,
784
+ sources: [{ id: "big", content: "x".repeat(MAX_CHARS_PER_SOURCE + 100) }],
785
+ model: {} as any,
786
+ options: options(),
787
+ locale: "de",
788
+ });
789
+ expect(result.notes.find((n) => n.includes("truncated"))).toContain("big");
790
+ });
791
+
792
+ it("caps the name list at three names and adds 'and N more' for the rest", async () => {
793
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
794
+ allClear(windows.map((w: any) => w.sentence.index)),
795
+ );
796
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
797
+ outcomes: windows.map((w: any) => ({
798
+ index: w.sentence.index,
799
+ claims: [{ text: `c${w.sentence.index}`, inferred: false }],
800
+ })),
801
+ usage: USAGE,
802
+ }));
803
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
804
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
805
+ usage: USAGE,
806
+ }));
807
+
808
+ // Create 5 sources, all truncated
809
+ const sources = Array.from({ length: 5 }, (_, i) => ({
810
+ id: `s${i}`,
811
+ name: `file${i}.pdf`,
812
+ content: "x".repeat(MAX_CHARS_PER_SOURCE + 100),
813
+ }));
814
+
815
+ const result = await runClaimCheck({
816
+ question: "q",
817
+ answer: ANSWER,
818
+ sources,
819
+ model: {} as any,
820
+ options: options(),
821
+ locale: "de",
822
+ });
823
+
824
+ const note = result.notes.find((n) => n.includes("truncated"));
825
+ // Should show exactly 3 names and "and 2 more"
826
+ expect(note).toContain('"file0.pdf"');
827
+ expect(note).toContain('"file1.pdf"');
828
+ expect(note).toContain('"file2.pdf"');
829
+ expect(note).toContain("and 2 more");
830
+ expect(note).not.toContain("file3.pdf");
831
+ expect(note).not.toContain("file4.pdf");
832
+ });
833
+
834
+ it("quotes source names to disambiguate commas in filenames", async () => {
835
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
836
+ allClear(windows.map((w: any) => w.sentence.index)),
837
+ );
838
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
839
+ outcomes: windows.map((w: any) => ({
840
+ index: w.sentence.index,
841
+ claims: [{ text: `c${w.sentence.index}`, inferred: false }],
842
+ })),
843
+ usage: USAGE,
844
+ }));
845
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
846
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
847
+ usage: USAGE,
848
+ }));
849
+
850
+ const result = await runClaimCheck({
851
+ question: "q",
852
+ answer: ANSWER,
853
+ sources: [
854
+ { id: "s1", name: "Report, Final.pdf", content: "x".repeat(MAX_CHARS_PER_SOURCE + 100) },
855
+ { id: "s2", name: "Draft.pdf", content: "x".repeat(MAX_CHARS_PER_SOURCE + 100) },
856
+ ],
857
+ model: {} as any,
858
+ options: options(),
859
+ locale: "de",
860
+ });
861
+
862
+ const note = result.notes.find((n) => n.includes("truncated"));
863
+ // Names should be quoted so commas don't cause misattribution
864
+ expect(note).toContain('"Report, Final.pdf"');
865
+ expect(note).toContain('"Draft.pdf"');
866
+ // Should read as 2 sources, not 3
867
+ expect(note).toMatch(/2 source\(s\)/);
868
+ });
869
+
870
+ // Fix round 3, minor: the cap and the quoting are in place, but a
871
+ // caller-supplied name is arbitrary text — a newline in one made a
872
+ // single-line note read as two, and the note is shown to a reader.
873
+ it("collapses whitespace in a caller-supplied name so one note stays one line", async () => {
874
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
875
+ allClear(windows.map((w: any) => w.sentence.index)),
876
+ );
877
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
878
+ outcomes: windows.map((w: any) => ({
879
+ index: w.sentence.index,
880
+ claims: [{ text: `c${w.sentence.index}`, inferred: false }],
881
+ })),
882
+ usage: USAGE,
883
+ }));
884
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
885
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
886
+ usage: USAGE,
887
+ }));
888
+
889
+ const result = await runClaimCheck({
890
+ question: "q",
891
+ answer: ANSWER,
892
+ sources: [{ id: "s1", name: "Wartung\n2026\tQ3.pdf", content: "x".repeat(MAX_CHARS_PER_SOURCE + 100) }],
893
+ model: {} as any,
894
+ options: options(),
895
+ locale: "de",
896
+ });
897
+
898
+ const note = result.notes.find((n) => n.includes("truncated"))!;
899
+ expect(note).toContain('"Wartung 2026 Q3.pdf"');
900
+ expect(note).not.toContain("\n");
901
+ expect(note).not.toContain("\t");
902
+ });
903
+ });
904
+
905
+ describe("runClaimCheck — omitted outcomes", () => {
906
+ it("drops a claim verification returned no verdict for, instead of scoring it unsupported", async () => {
907
+ const answer = "Satz eins ist wahr. Satz zwei ist auch wahr.";
908
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
909
+ allClear(windows.map((w: any) => w.sentence.index)),
910
+ );
911
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
912
+ outcomes: windows.map((w: any) => ({
913
+ index: w.sentence.index,
914
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
915
+ })),
916
+ usage: USAGE,
917
+ }));
918
+ // The call SUCCEEDS but answers for the first claim only — the likeliest
919
+ // failure of a long JSON array.
920
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
921
+ outcomes: claims
922
+ .slice(0, 1)
923
+ .map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
924
+ usage: USAGE,
925
+ }));
926
+
927
+ const result = await runClaimCheck({
928
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
929
+ });
930
+
931
+ // c2 is gone entirely rather than standing as an unsupported claim.
932
+ expect(result.claims.map((c) => c.id)).toEqual(["c1"]);
933
+ expect(result.score.claims).toBe(1);
934
+ expect(result.score.unsupported).toBe(0);
935
+ expect(result.score.label).toBe("ok");
936
+ expect(result.sentences[0]!.state).toBe("checked");
937
+ expect(result.sentences[1]!.state).toBe("not_checked");
938
+ expect(result.sentences[1]!.reason).toBe("verification returned no verdict for this sentence");
939
+ expect(result.status).toBe("partial");
940
+ expect(result.notes.some((n) => n.includes("verification returned no verdict"))).toBe(true);
941
+ });
942
+
943
+ it("marks a sentence selection never answered for not_checked, not no_verifiable_content", async () => {
944
+ const answer = "Satz eins ist wahr. Satz zwei ist auch wahr.";
945
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) => ({
946
+ selection: windows.map((w: any) => ({
947
+ index: w.sentence.index,
948
+ verifiable: w.sentence.index === 0,
949
+ rewritten: null,
950
+ reason: w.sentence.index === 0 ? "fact" : "no outcome returned for this sentence",
951
+ answered: w.sentence.index === 0,
952
+ })),
953
+ disambiguation: windows.map((w: any) => ({
954
+ index: w.sentence.index,
955
+ resolvable: w.sentence.index === 0,
956
+ clarified: null,
957
+ reason: w.sentence.index === 0 ? "clear" : "no outcome returned for this sentence",
958
+ answered: w.sentence.index === 0,
959
+ })),
960
+ usage: USAGE,
961
+ }));
962
+ (runDecomposition as jest.Mock).mockResolvedValue({
963
+ outcomes: [{ index: 0, claims: [{ text: "c", inferred: false }] }],
964
+ usage: USAGE,
965
+ });
966
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
967
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
968
+ usage: USAGE,
969
+ }));
970
+
971
+ const result = await runClaimCheck({
972
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
973
+ });
974
+
975
+ expect(result.sentences[1]!.state).toBe("not_checked");
976
+ expect(result.sentences[1]!.reason).toBe("no outcome returned for this sentence");
977
+ expect(result.status).toBe("partial");
978
+ expect(result.notes.some((n) => n.includes("returned no outcome for 1 sentence(s)"))).toBe(true);
979
+ });
980
+
981
+ it("marks a sentence disambiguation never answered for not_checked, not cannot_disambiguate", async () => {
982
+ const answer = "Satz eins ist wahr. Satz zwei ist auch wahr.";
983
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) => ({
984
+ selection: windows.map((w: any) => ({
985
+ index: w.sentence.index,
986
+ verifiable: true,
987
+ rewritten: null,
988
+ reason: "fact",
989
+ answered: true,
990
+ })),
991
+ disambiguation: windows.map((w: any) => ({
992
+ index: w.sentence.index,
993
+ resolvable: w.sentence.index === 0,
994
+ clarified: null,
995
+ reason: w.sentence.index === 0 ? "clear" : "no disambiguation returned for this sentence",
996
+ answered: w.sentence.index === 0,
997
+ })),
998
+ usage: USAGE,
999
+ }));
1000
+ (runDecomposition as jest.Mock).mockResolvedValue({
1001
+ outcomes: [{ index: 0, claims: [{ text: "c", inferred: false }] }],
1002
+ usage: USAGE,
1003
+ });
1004
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
1005
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
1006
+ usage: USAGE,
1007
+ }));
1008
+
1009
+ const result = await runClaimCheck({
1010
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
1011
+ });
1012
+
1013
+ expect(result.sentences[1]!.state).toBe("not_checked");
1014
+ expect(result.sentences[1]!.reason).toBe("no disambiguation returned for this sentence");
1015
+ expect(result.status).toBe("partial");
1016
+ });
1017
+ });
1018
+
1019
+ describe("runClaimCheck — paper fidelity and second chance", () => {
1020
+ it("runs selection and disambiguation as separate stages with majority voting", async () => {
1021
+ (runSelection as jest.Mock).mockImplementation(async ({ windows }) => ({
1022
+ outcomes: windows.map((w: any) => ({ index: w.sentence.index, verifiable: true, rewritten: null, reason: "fact" })),
1023
+ usage: USAGE,
1024
+ }));
1025
+ // Two of three completions say resolvable, so min_successes=2 passes.
1026
+ const resolvableSequence = [true, true, false];
1027
+ let call = 0;
1028
+ (runDisambiguation as jest.Mock).mockImplementation(async ({ windows }) => {
1029
+ const resolvable = resolvableSequence[call % resolvableSequence.length]!;
1030
+ call += 1;
1031
+ return {
1032
+ outcomes: windows.map((w: any) => ({ index: w.sentence.index, resolvable, clarified: null, reason: "r" })),
1033
+ usage: USAGE,
1034
+ };
1035
+ });
1036
+ (runDecomposition as jest.Mock).mockResolvedValue({
1037
+ outcomes: [{ index: 0, claims: [{ text: "c", inferred: false }] }],
1038
+ usage: USAGE,
1039
+ });
1040
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
1041
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
1042
+ usage: USAGE,
1043
+ }));
1044
+
1045
+ const result = await runClaimCheck({
1046
+ question: "q",
1047
+ answer: "Die FST-2XT arbeitet mit 230 Volt.",
1048
+ sources: SOURCES,
1049
+ model: {} as any,
1050
+ options: options({ fidelity: "paper", completions: 3 }),
1051
+ locale: "de",
1052
+ });
1053
+
1054
+ expect(runSelectAndDisambiguate).not.toHaveBeenCalled();
1055
+ expect((runSelection as jest.Mock).mock.calls.length).toBe(3);
1056
+ expect((runSelection as jest.Mock).mock.calls[0][0].temperature).toBe(0.2);
1057
+ expect(result.sentences[0]!.state).toBe("checked");
1058
+ });
1059
+
1060
+ // Finding 9: paper fidelity only unmerged the stages and added voting; both
1061
+ // fidelities batched 10 sentences per selection call and 5 per decomposition
1062
+ // call, so §8's fast-vs-paper comparison could not set the batch sizes.
1063
+ it("issues one call per sentence per completion in paper fidelity", async () => {
1064
+ const answer = "Satz eins ist wahr. Satz zwei ist wahr. Satz drei ist wahr.";
1065
+ (runSelection as jest.Mock).mockImplementation(async ({ windows }) => ({
1066
+ outcomes: windows.map((w: any) => ({
1067
+ index: w.sentence.index, verifiable: true, rewritten: null, reason: "fact", answered: true,
1068
+ })),
1069
+ usage: USAGE,
1070
+ }));
1071
+ (runDisambiguation as jest.Mock).mockImplementation(async ({ windows }) => ({
1072
+ outcomes: windows.map((w: any) => ({
1073
+ index: w.sentence.index, resolvable: true, clarified: null, reason: "clear", answered: true,
1074
+ })),
1075
+ usage: USAGE,
1076
+ }));
1077
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
1078
+ outcomes: windows.map((w: any) => ({
1079
+ index: w.sentence.index,
1080
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
1081
+ })),
1082
+ usage: USAGE,
1083
+ }));
1084
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
1085
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
1086
+ usage: USAGE,
1087
+ }));
1088
+
1089
+ const result = await runClaimCheck({
1090
+ question: "q",
1091
+ answer,
1092
+ sources: SOURCES,
1093
+ model: {} as any,
1094
+ options: options({ fidelity: "paper", completions: 2 }),
1095
+ locale: "de",
1096
+ });
1097
+
1098
+ const selectionCalls = (runSelection as jest.Mock).mock.calls;
1099
+ const disambiguationCalls = (runDisambiguation as jest.Mock).mock.calls;
1100
+ const decompositionCalls = (runDecomposition as jest.Mock).mock.calls;
1101
+ // 3 sentences x 2 completions, one sentence per call.
1102
+ expect(selectionCalls).toHaveLength(6);
1103
+ expect(disambiguationCalls).toHaveLength(6);
1104
+ expect(selectionCalls.every((c) => c[0].windows.length === 1)).toBe(true);
1105
+ expect(disambiguationCalls.every((c) => c[0].windows.length === 1)).toBe(true);
1106
+ // Decomposition is not voted, but it is one sentence per call too.
1107
+ expect(decompositionCalls).toHaveLength(3);
1108
+ expect(decompositionCalls.every((c) => c[0].windows.length === 1)).toBe(true);
1109
+ expect(result.claims).toHaveLength(3);
1110
+ });
1111
+
1112
+ // Finding 14: completions above 1 in fast fidelity only raised the
1113
+ // temperature to 0.2 — nothing votes in fast mode, so it bought strictly
1114
+ // less determinism for the same single call.
1115
+ it("ignores completions outside paper fidelity, keeping temperature at 0", async () => {
1116
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
1117
+ allClear(windows.map((w: any) => w.sentence.index)),
1118
+ );
1119
+ (runDecomposition as jest.Mock).mockResolvedValue({ outcomes: [], usage: USAGE });
1120
+
1121
+ await runClaimCheck({
1122
+ question: "q",
1123
+ answer: ANSWER,
1124
+ sources: SOURCES,
1125
+ model: {} as any,
1126
+ options: options({ fidelity: "fast", completions: 3 }),
1127
+ locale: "de",
1128
+ });
1129
+
1130
+ const calls = (runSelectAndDisambiguate as jest.Mock).mock.calls;
1131
+ expect(calls).toHaveLength(1);
1132
+ expect(calls[0][0].temperature).toBe(0);
1133
+ });
1134
+
1135
+ it("keeps the fast path batched: one merged call and one decomposition call for three sentences", async () => {
1136
+ const answer = "Satz eins ist wahr. Satz zwei ist wahr. Satz drei ist wahr.";
1137
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
1138
+ allClear(windows.map((w: any) => w.sentence.index)),
1139
+ );
1140
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
1141
+ outcomes: windows.map((w: any) => ({
1142
+ index: w.sentence.index,
1143
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
1144
+ })),
1145
+ usage: USAGE,
1146
+ }));
1147
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
1148
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
1149
+ usage: USAGE,
1150
+ }));
1151
+
1152
+ await runClaimCheck({
1153
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
1154
+ });
1155
+
1156
+ expect((runSelectAndDisambiguate as jest.Mock).mock.calls).toHaveLength(1);
1157
+ expect((runSelectAndDisambiguate as jest.Mock).mock.calls[0][0].windows).toHaveLength(3);
1158
+ expect((runDecomposition as jest.Mock).mock.calls).toHaveLength(1);
1159
+ expect((runDecomposition as jest.Mock).mock.calls[0][0].windows).toHaveLength(3);
1160
+ });
1161
+
1162
+ it("re-retrieves only unsupported claims, up to the cap, and marks the flipped ones rechecked", async () => {
1163
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
1164
+ allClear(windows.map((w: any) => w.sentence.index)),
1165
+ );
1166
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
1167
+ outcomes: windows.map((w: any) => ({ index: w.sentence.index, claims: [{ text: `claim ${w.sentence.index}`, inferred: false }] })),
1168
+ usage: USAGE,
1169
+ }));
1170
+ let verifyCall = 0;
1171
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => {
1172
+ verifyCall += 1;
1173
+ // First pass: everything unsupported. Second pass (second chance): supported.
1174
+ return {
1175
+ outcomes: claims.map((c: any) => ({
1176
+ claimId: c.id,
1177
+ verdict: verifyCall === 1 ? "unsupported" : "supported",
1178
+ evidence: [],
1179
+ rationale: "r",
1180
+ })),
1181
+ usage: USAGE,
1182
+ };
1183
+ });
1184
+
1185
+ const secondChance = jest
1186
+ .fn()
1187
+ .mockResolvedValue([{ sourceId: "deep", text: "Die FST-2XT arbeitet mit 230 Volt.", score: 2 }]);
1188
+
1189
+ const result = await runClaimCheck({
1190
+ question: "q",
1191
+ answer: ANSWER,
1192
+ sources: SOURCES,
1193
+ model: {} as any,
1194
+ options: options({ caps: { maxSentences: 120, maxClaims: 200, maxReRetrievals: 2 } }),
1195
+ locale: "de",
1196
+ secondChance,
1197
+ });
1198
+
1199
+ expect(secondChance).toHaveBeenCalledTimes(2);
1200
+ expect(result.claims.filter((c) => c.rechecked)).toHaveLength(2);
1201
+ expect(result.claims.filter((c) => c.verdict === "supported")).toHaveLength(2);
1202
+ expect(result.notes.some((n) => n.includes("maxReRetrievals"))).toBe(true);
1203
+ });
1204
+
1205
+ it("skips the second chance entirely when reRetrieve is off", async () => {
1206
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
1207
+ allClear(windows.map((w: any) => w.sentence.index)),
1208
+ );
1209
+ (runDecomposition as jest.Mock).mockResolvedValue({
1210
+ outcomes: [{ index: 0, claims: [{ text: "c", inferred: false }] }],
1211
+ usage: USAGE,
1212
+ });
1213
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
1214
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "unsupported", evidence: [], rationale: "r" })),
1215
+ usage: USAGE,
1216
+ }));
1217
+ const secondChance = jest.fn();
1218
+
1219
+ const result = await runClaimCheck({
1220
+ question: "q", answer: ANSWER, sources: SOURCES, model: {} as any,
1221
+ options: options({ reRetrieve: false }), locale: "de", secondChance,
1222
+ });
1223
+
1224
+ expect(secondChance).not.toHaveBeenCalled();
1225
+ expect(result.claims[0]!.rechecked).toBe(false);
1226
+ });
1227
+
1228
+ // Correction 3: a claim whose verification CALL FAILED (the group's promise
1229
+ // rejected) must not be reported as "unsupported" — that would misrepresent
1230
+ // a provider outage as "the sources don't support this." It must be dropped
1231
+ // from the result entirely, and its sentence marked not_checked.
1232
+ it("drops claims from a verification group that rejects, instead of reporting them unsupported", async () => {
1233
+ const answer = Array.from({ length: 9 }, (_, i) => `Satz Nummer ${i + 1} ist eindeutig wahr.`).join(" ");
1234
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
1235
+ allClear(windows.map((w: any) => w.sentence.index)),
1236
+ );
1237
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
1238
+ outcomes: windows.map((w: any) => ({
1239
+ index: w.sentence.index,
1240
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
1241
+ })),
1242
+ usage: USAGE,
1243
+ }));
1244
+ // BATCH.verifySentences = 8: sentences 0-7 land in one group (8 claims),
1245
+ // sentence 8 lands alone in a second group. Fail the first, pass the second.
1246
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => {
1247
+ if (claims.length === 8) throw new Error("provider down for this group");
1248
+ return {
1249
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
1250
+ usage: USAGE,
1251
+ };
1252
+ });
1253
+
1254
+ const result = await runClaimCheck({
1255
+ question: "q", answer, sources: SOURCES, model: {} as any, options: options(), locale: "de",
1256
+ });
1257
+
1258
+ expect(result.claims).toHaveLength(1);
1259
+ expect(result.claims[0]!.sentenceIndex).toBe(8);
1260
+ expect(result.score.claims).toBe(1);
1261
+ expect(result.sentences.slice(0, 8).every((s) => s.state === "not_checked")).toBe(true);
1262
+ expect(result.sentences[0]!.reason).toBe("verification failed for this sentence");
1263
+ expect(result.sentences[8]!.state).toBe("checked");
1264
+ expect(result.status).toBe("partial");
1265
+ expect(result.notes.some((n) => n.includes("verification"))).toBe(true);
1266
+ });
1267
+ });
1268
+
1269
+ // The product-owner objection this work answers: "running hundreds of checks
1270
+ // is going to be incredibly expensive and take a long time". These two tests
1271
+ // are the measurement — stage invocations counted, not estimated.
1272
+ describe("runClaimCheck — call budget", () => {
1273
+ /** 30 sentences. */
1274
+ const SENTENCES = Array.from(
1275
+ { length: 30 },
1276
+ (_, i) => `Satz Nummer ${i + 1} beschreibt eine eindeutig überprüfbare Tatsache.`,
1277
+ );
1278
+ const ANSWER_30 = SENTENCES.join(" ");
1279
+
1280
+ const runWith = async (sources: { id: string; content: string }[]) => {
1281
+ (runSelectAndDisambiguate as jest.Mock).mockImplementation(async ({ windows }) =>
1282
+ allClear(windows.map((w: any) => w.sentence.index)),
1283
+ );
1284
+ (runDecomposition as jest.Mock).mockImplementation(async ({ windows }) => ({
1285
+ outcomes: windows.map((w: any) => ({
1286
+ index: w.sentence.index,
1287
+ claims: [{ text: `claim ${w.sentence.index}`, inferred: false }],
1288
+ })),
1289
+ usage: USAGE,
1290
+ }));
1291
+ (runVerification as jest.Mock).mockImplementation(async ({ claims }) => ({
1292
+ outcomes: claims.map((c: any) => ({ claimId: c.id, verdict: "supported", evidence: [], rationale: "r" })),
1293
+ usage: USAGE,
1294
+ }));
1295
+ return runClaimCheck({
1296
+ question: "q", answer: ANSWER_30, sources, model: {} as any,
1297
+ options: options({ reRetrieve: false }), locale: "de",
1298
+ });
1299
+ };
1300
+
1301
+ it("costs 8 stage calls for a 30-sentence answer, down from 19", async () => {
1302
+ const result = await runWith(SOURCES);
1303
+ const counts = {
1304
+ selectDisambiguate: (runSelectAndDisambiguate as jest.Mock).mock.calls.length,
1305
+ decompose: (runDecomposition as jest.Mock).mock.calls.length,
1306
+ verify: (runVerification as jest.Mock).mock.calls.length,
1307
+ };
1308
+
1309
+ // ceil(30/25) + ceil(30/15) + ceil(30/8). At {10, 5, 3} this was 3 + 6 + 10.
1310
+ expect(counts).toEqual({ selectDisambiguate: 2, decompose: 2, verify: 4 });
1311
+ expect(counts.selectDisambiguate + counts.decompose + counts.verify).toBe(8);
1312
+ // What the response reports back agrees with what was spent.
1313
+ expect(result.usage.calls).toBe(8);
1314
+ expect(result.score.claims).toBe(30);
1315
+ expect(result.status).toBe("ok");
1316
+ });
1317
+ });