@exulu/backend 5.1.1 → 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 (56) hide show
  1. package/dist/{chunk-UXHMHM4E.js → chunk-ASF74XFZ.js} +271 -33
  2. package/dist/{convert-exulu-tools-to-ai-sdk-tools-FHFMJSD2.js → convert-exulu-tools-to-ai-sdk-tools-MFLZQONB.js} +3 -1
  3. package/dist/index.cjs +2761 -355
  4. package/dist/index.js +2425 -305
  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/ee/workers.ts +16 -0
  56. package/package.json +1 -1
@@ -0,0 +1,710 @@
1
+ // ee/claim-check/run.ts
2
+ //
3
+ // Orchestration. Everything about cost and provider fragility lives here:
4
+ // batching (spec §2.3), bounded fan-out, one bisect per failed batch, a stage
5
+ // circuit breaker, and the caps that turn a huge answer into a partial result
6
+ // instead of a failure.
7
+ import type { LanguageModel } from "ai";
8
+ import {
9
+ CLAIM_CHECK_DEFAULTS,
10
+ type Claim,
11
+ type ClaimCheckOptions,
12
+ type ClaimCheckResult,
13
+ type ClaimCheckSource,
14
+ type DisambiguationOutcome,
15
+ type EvidenceSnippet,
16
+ type SelectionOutcome,
17
+ type Sentence,
18
+ type SentenceState,
19
+ type SentenceWindow,
20
+ } from "./types";
21
+ import { buildWindows, localeFromText, splitIntoSentences } from "./split";
22
+ import {
23
+ indexSourcesWithLimits,
24
+ MAX_CHARS_PER_SOURCE,
25
+ selectEvidence,
26
+ type PassageIndex,
27
+ type SourceTruncation,
28
+ } from "./evidence";
29
+ import { runSelectAndDisambiguate } from "./stages/select-disambiguate";
30
+ import { runSelection } from "./stages/select";
31
+ import { runDisambiguation } from "./stages/disambiguate";
32
+ import { runDecomposition } from "./stages/decompose";
33
+ import { runVerification } from "./stages/verify";
34
+ import { scoreClaims, buildSentenceResults } from "./score";
35
+ import { addUsage, EMPTY_USAGE, type StageUsage } from "./stages/usage";
36
+ import { mapWithConcurrency } from "./concurrency";
37
+
38
+ /**
39
+ * A typical 30-sentence NEWLIFT answer cost 19 provider calls at
40
+ * {10, 5, 3} — 3 extraction + 6 decomposition + 10 verification — and a
41
+ * 44,000-character answer is ~568 sentences. These sizes bring that to 8
42
+ * (2 + 2 + 4); see CLAIM_CHECK_MAX_OUTPUT_TOKENS for the measured output-token
43
+ * headroom each one leaves, and BISECT_FLOOR for what a failed batch now costs.
44
+ */
45
+ export const BATCH = { selectDisambiguate: 25, decompose: 15, verifySentences: 8 };
46
+ /**
47
+ * A failed batch is split in half and each half retried, recursively, until
48
+ * the pieces are small enough that splitting them again costs more calls than
49
+ * the sentences it would save. At BATCH.selectDisambiguate = 25 that is
50
+ * 25 -> 13 + 12 -> 7 + 6 + 6 + 6: a batch that fails for its SIZE (an
51
+ * output-token overflow is the deterministic case, and the reason bisecting
52
+ * exists at all) gets two further chances at a size that fits.
53
+ *
54
+ * Why a floor rather than splitting down to single sentences: the blast radius
55
+ * of a failure is the size of the smallest piece that still failed, and the
56
+ * call cost of reaching size 1 from 25 is 1+2+4+8+16 = 31. Eight sentences of
57
+ * a 120-sentence cap reported not_checked, with a note, is a degradation the
58
+ * response states plainly; 31 calls for one unlucky batch is a bill the caller
59
+ * never agreed to. The floor is what bounds a CONTENT-triggered failure (a
60
+ * batch that would fail at any size) to at most 7 calls instead.
61
+ *
62
+ * The floor applies to the RETRY rounds only. Round 0 always bisects a failed
63
+ * batch of more than one sentence, whatever its size: the brief's guarantee
64
+ * that "a lone failing batch still gets its bisect" has to hold for a short
65
+ * answer too, and applying the floor to the original batch quietly took it
66
+ * away — a lone failing batch of 2 to 8 sentences got ZERO retries and lost
67
+ * every sentence to not_checked, where {10, 5, 3} bisected and usually
68
+ * recovered half. What the floor is for is bounding the DEPTH of the
69
+ * recursion, not refusing the first retry.
70
+ */
71
+ export const BISECT_FLOOR = 8;
72
+ /**
73
+ * Hard ceiling on bisect ROUNDS, independent of the floor. At the floor above
74
+ * no batch this engine produces needs more than two rounds (25 -> 13 -> 7), so
75
+ * it never binds today; it exists so that raising BATCH later cannot turn one
76
+ * failing batch into an unbounded series of retries without someone revisiting
77
+ * this number.
78
+ */
79
+ export const MAX_BISECT_ROUNDS = 3;
80
+ /**
81
+ * Evidence selection is a PER-CLAIM job (spec §2.2): score the passages for
82
+ * one claim and take its best few. Pooling a whole verification group's claim
83
+ * texts into one query starved the weaker-scoring claims — six to ten claims
84
+ * shared four snippets — and the failure mode is a false "unsupported".
85
+ */
86
+ export const EVIDENCE_PER_CLAIM = 3;
87
+ /** Ceiling on the union, so a group of ten claims cannot blow up one prompt. */
88
+ export const MAX_EVIDENCE_PER_CALL = 12;
89
+ export const MAX_IN_FLIGHT = 6;
90
+ export const STAGE_FAILURE_ABORT = 0.4;
91
+ /** Paper §D: 3 completions, 2 successes required, for Selection and Disambiguation. */
92
+ const MIN_SUCCESS_RATIO = 2 / 3;
93
+
94
+ /**
95
+ * How many truncated source names the note spells out before it says "and N
96
+ * more", and how long one name may be. Module scope, named, like every other
97
+ * tuning number in this file — they were inline literals inside the note
98
+ * builder.
99
+ */
100
+ const TRUNCATION_NAMES_LISTED = 3;
101
+ const TRUNCATION_NAME_MAX_CHARS = 80;
102
+
103
+ /**
104
+ * The truncated sources, formatted for the note a reader sees: whitespace
105
+ * collapsed, capped at `TRUNCATION_NAME_MAX_CHARS`, quoted so a comma in a
106
+ * filename cannot read as a separator, and at most
107
+ * `TRUNCATION_NAMES_LISTED` of them before "and N more".
108
+ *
109
+ * The collapse matters because a `name` is arbitrary caller-supplied text:
110
+ * a newline in one made a single-line note read as two.
111
+ */
112
+ const formatSourceNames = (names: string[]): string => {
113
+ const quoted = names.map((name) => {
114
+ const flat = name.replace(/\s+/g, " ").trim();
115
+ return `"${flat.length > TRUNCATION_NAME_MAX_CHARS ? flat.slice(0, TRUNCATION_NAME_MAX_CHARS) + "…" : flat}"`;
116
+ });
117
+ if (quoted.length <= TRUNCATION_NAMES_LISTED) return quoted.join(", ");
118
+ return (
119
+ quoted.slice(0, TRUNCATION_NAMES_LISTED).join(", ") +
120
+ `, and ${quoted.length - TRUNCATION_NAMES_LISTED} more`
121
+ );
122
+ };
123
+
124
+ const chunk = <T,>(items: T[], size: number): T[][] => {
125
+ const out: T[][] = [];
126
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
127
+ return out;
128
+ };
129
+
130
+ type StageState = {
131
+ usage: StageUsage;
132
+ notes: string[];
133
+ states: Map<number, { state: SentenceState; reason?: string }>;
134
+ partial: boolean;
135
+ };
136
+
137
+ /**
138
+ * Run one batched stage over all batches with bounded concurrency. A rejected
139
+ * batch is split in half and each half retried, recursively, down to
140
+ * BISECT_FLOOR — so one bad call costs at most 8 sentences instead of 25, for
141
+ * at most 7 calls instead of 31. Above STAGE_FAILURE_ABORT the stage stops
142
+ * reporting and the caller degrades to a partial result.
143
+ */
144
+ async function runBatched<R>(
145
+ batches: SentenceWindow[][],
146
+ label: string,
147
+ state: StageState,
148
+ call: (windows: SentenceWindow[]) => Promise<{ result: R; usage: StageUsage }>,
149
+ ): Promise<R[]> {
150
+ const good: R[] = [];
151
+ let pending = batches;
152
+
153
+ for (let round = 0; pending.length > 0; round += 1) {
154
+ const settled = await mapWithConcurrency(pending, MAX_IN_FLIGHT, async (windows) => call(windows));
155
+ const failed: SentenceWindow[][] = [];
156
+
157
+ settled.forEach((outcome, i) => {
158
+ if (outcome.status === "fulfilled") {
159
+ good.push(outcome.value.result);
160
+ state.usage = addUsage(state.usage, outcome.value.usage);
161
+ return;
162
+ }
163
+ failed.push(pending[i]!);
164
+ });
165
+
166
+ if (failed.length === 0) return good;
167
+
168
+ // The breaker judges the stage's FIRST round only, exactly as before.
169
+ // A single failure is never systemic: it must get its bisect (that is the
170
+ // point of bisecting at all), and the breaker exists for a provider
171
+ // failing broadly, which takes at least two observed failures to
172
+ // establish. It deliberately does not re-run on the retry rounds: the
173
+ // failure the recursion exists for — an output-token overflow — is
174
+ // deterministic in batch SIZE, so every sibling of a round failing is the
175
+ // signal to split further, not the signal to give up. Re-running it here
176
+ // would cap the depth at one bisect for exactly the case 25 -> 13 -> 7 was
177
+ // widened for.
178
+ if (round === 0 && failed.length >= 2 && failed.length / pending.length > STAGE_FAILURE_ABORT) {
179
+ state.partial = true;
180
+ state.notes.push(
181
+ `${label}: aborted after ${failed.length} of ${pending.length} calls failed; remaining sentences are not_checked`,
182
+ );
183
+ for (const batch of failed) markNotChecked(state, batch, `${label} aborted`);
184
+ return good;
185
+ }
186
+
187
+ const next: SentenceWindow[][] = [];
188
+ for (const batch of failed) {
189
+ // Round 0 always bisects (the first retry is never refused); the floor
190
+ // only stops the recursion going deeper. See BISECT_FLOOR.
191
+ if (batch.length > 1 && round < MAX_BISECT_ROUNDS && (round === 0 || batch.length > BISECT_FLOOR)) {
192
+ const mid = Math.ceil(batch.length / 2);
193
+ next.push(batch.slice(0, mid), batch.slice(mid));
194
+ continue;
195
+ }
196
+ markNotChecked(
197
+ state,
198
+ batch,
199
+ batch.length === 1
200
+ ? `${label} failed for this sentence`
201
+ : round === 0
202
+ ? `${label} failed for this batch of ${batch.length} sentences`
203
+ : `${label} failed after bisect`,
204
+ );
205
+ }
206
+ pending = next;
207
+ }
208
+
209
+ return good;
210
+ }
211
+
212
+ /**
213
+ * Per-claim selection, unioned and deduplicated by passage identity
214
+ * (sourceId + text, which is what makes a passage the same passage; a source
215
+ * id alone is not unique — a document is many passages).
216
+ *
217
+ * Filled by RANK, not by claim: every claim's best snippet lands before any
218
+ * claim's second, so the ceiling cuts extra context rather than cutting a
219
+ * claim's only supporting passage.
220
+ */
221
+ export function selectGroupEvidence(claimTexts: string[], index: PassageIndex): EvidenceSnippet[] {
222
+ const perClaim = claimTexts.map((text) => selectEvidence([text], index, EVIDENCE_PER_CLAIM));
223
+ const union: EvidenceSnippet[] = [];
224
+ const seen = new Set<string>();
225
+
226
+ for (let rank = 0; rank < EVIDENCE_PER_CLAIM; rank += 1) {
227
+ for (const snippets of perClaim) {
228
+ const snippet = snippets[rank];
229
+ if (!snippet) continue;
230
+ const key = `${snippet.sourceId}\u0000${snippet.text}`;
231
+ if (seen.has(key)) continue;
232
+ seen.add(key);
233
+ union.push(snippet);
234
+ if (union.length >= MAX_EVIDENCE_PER_CALL) return union;
235
+ }
236
+ }
237
+
238
+ return union;
239
+ }
240
+
241
+ function markNotChecked(state: StageState, windows: SentenceWindow[], reason: string): void {
242
+ state.partial = true;
243
+ state.notes.push(`${windows.length} sentence(s) marked not_checked: ${reason}`);
244
+ for (const w of windows) {
245
+ if (!state.states.has(w.sentence.index)) {
246
+ state.states.set(w.sentence.index, { state: "not_checked", reason });
247
+ }
248
+ }
249
+ }
250
+
251
+ /** Majority voting for paper fidelity: a sentence advances when at least 2 of 3 runs agree. */
252
+ function vote<T extends { index: number }>(
253
+ runs: T[][],
254
+ passes: (outcome: T) => boolean,
255
+ completions: number,
256
+ ): Map<number, { passed: boolean; sample: T }> {
257
+ const byIndex = new Map<number, T[]>();
258
+ for (const run of runs) {
259
+ for (const outcome of run) {
260
+ const list = byIndex.get(outcome.index) ?? [];
261
+ list.push(outcome);
262
+ byIndex.set(outcome.index, list);
263
+ }
264
+ }
265
+ const required = Math.max(1, Math.ceil(completions * MIN_SUCCESS_RATIO));
266
+ const voted = new Map<number, { passed: boolean; sample: T }>();
267
+ for (const [index, outcomes] of byIndex) {
268
+ const successes = outcomes.filter(passes);
269
+ voted.set(index, {
270
+ passed: successes.length >= required,
271
+ sample: successes[0] ?? outcomes[0]!,
272
+ });
273
+ }
274
+ return voted;
275
+ }
276
+
277
+ export async function runClaimCheck(args: {
278
+ question: string;
279
+ answer: string;
280
+ sources: ClaimCheckSource[];
281
+ model: LanguageModel;
282
+ options?: ClaimCheckOptions;
283
+ locale?: string;
284
+ /** Supplied only for IMP callers with an agent scope (Task 13). */
285
+ secondChance?: (claimText: string) => Promise<EvidenceSnippet[]>;
286
+ /**
287
+ * The HTTP handler's 60 s deadline (spec §4). Threaded to every provider
288
+ * call so a hung provider is cancelled instead of holding one of the twenty
289
+ * global in-flight slots until the transport gives up.
290
+ */
291
+ signal?: AbortSignal;
292
+ }): Promise<ClaimCheckResult> {
293
+ const options = args.options ?? CLAIM_CHECK_DEFAULTS;
294
+ const startedAt = Date.now();
295
+ const timings: Record<string, number> = {};
296
+ const lap = (name: string, from: number) => {
297
+ timings[name] = Date.now() - from;
298
+ };
299
+
300
+ const state: StageState = { usage: { ...EMPTY_USAGE }, notes: [], states: new Map(), partial: false };
301
+ // Hoisted so a failure anywhere past the split stage can still report
302
+ // whatever was already determined, instead of losing it to the catch below.
303
+ let allSentences: Sentence[] = [];
304
+ let skipped: Sentence[] = [];
305
+ // Finding 5: evidence past MAX_CHARS_PER_SOURCE is never searched, so what
306
+ // was dropped has to reach `limits` and `notes` on every return path,
307
+ // including the catch below.
308
+ let truncation: SourceTruncation = { sources: 0, droppedChars: 0, names: [] };
309
+
310
+ try {
311
+ const locale = args.locale ?? localeFromText(args.answer);
312
+
313
+ // ── Split ──────────────────────────────────────────────────────────────
314
+ let tStage = Date.now();
315
+ allSentences = splitIntoSentences(args.answer, locale);
316
+ const sentences = allSentences.slice(0, options.caps.maxSentences);
317
+ skipped = allSentences.slice(options.caps.maxSentences);
318
+ for (const s of skipped) state.states.set(s.index, { state: "not_checked", reason: "cap_exceeded" });
319
+ if (skipped.length > 0) {
320
+ state.partial = true;
321
+ state.notes.push(`maxSentences (${options.caps.maxSentences}) reached; ${skipped.length} sentence(s) not checked`);
322
+ }
323
+ lap("splitMs", tStage);
324
+
325
+ // ── Selection + Disambiguation ─────────────────────────────────────────
326
+ tStage = Date.now();
327
+ const selectWindows = buildWindows(sentences, 5, 5);
328
+ const laterWindows = new Map(buildWindows(sentences, 5, 0).map((w) => [w.sentence.index, w]));
329
+ // Spec §2.3: paper fidelity "restores one sentence per call". Batching it
330
+ // the same way as the fast path made §8's fast-vs-paper comparison — the
331
+ // thing that is supposed to SET the final batch sizes — unable to answer
332
+ // that question, because both arms batched identically.
333
+ const paper = options.fidelity === "paper";
334
+ // Only paper votes, so `completions` outside it bought nothing except a
335
+ // raised temperature (0.2) — strictly less determinism for the same single
336
+ // call per batch.
337
+ const completions = paper ? options.completions : 1;
338
+ const temperature = completions > 1 ? 0.2 : 0;
339
+ const selectBatchSize = paper ? 1 : BATCH.selectDisambiguate;
340
+ const decomposeBatchSize = paper ? 1 : BATCH.decompose;
341
+ const batches = chunk(selectWindows, selectBatchSize);
342
+
343
+ const selection: SelectionOutcome[] = [];
344
+ const disambiguation: DisambiguationOutcome[] = [];
345
+
346
+ if (paper) {
347
+ const selectionRuns: SelectionOutcome[][] = [];
348
+ for (let run = 0; run < completions; run += 1) {
349
+ const results = await runBatched(batches, "selection", state, async (windows) => {
350
+ const { outcomes, usage } = await runSelection({
351
+ windows, question: args.question, model: args.model, temperature, ...(args.signal ? { signal: args.signal } : {}),
352
+ });
353
+ return { result: outcomes, usage };
354
+ });
355
+ selectionRuns.push(results.flat());
356
+ }
357
+ const selectionVote = vote(selectionRuns, (o) => o.verifiable, completions);
358
+ for (const [index, { passed, sample }] of selectionVote) {
359
+ selection.push({ ...sample, index, verifiable: passed });
360
+ }
361
+
362
+ const survivors = selection.filter((s) => s.verifiable).map((s) => laterWindows.get(s.index)!).filter(Boolean);
363
+ // Correction 1: this map is built from the GLOBAL selection array above
364
+ // (every sentence that has a rewrite), not from one batch's slice of it —
365
+ // a window's preceding/following sentences routinely belong to other
366
+ // batches, and excerptFor substitutes by index across the whole window.
367
+ const texts = new Map(selection.filter((s) => s.rewritten).map((s) => [s.index, s.rewritten!]));
368
+ const disambiguationRuns: DisambiguationOutcome[][] = [];
369
+ for (let run = 0; run < completions; run += 1) {
370
+ const results = await runBatched(chunk(survivors, selectBatchSize), "disambiguation", state, async (windows) => {
371
+ const { outcomes, usage } = await runDisambiguation({
372
+ windows, question: args.question, sentenceTexts: texts, model: args.model, temperature,
373
+ ...(args.signal ? { signal: args.signal } : {}),
374
+ });
375
+ return { result: outcomes, usage };
376
+ });
377
+ disambiguationRuns.push(results.flat());
378
+ }
379
+ const disambiguationVote = vote(disambiguationRuns, (o) => o.resolvable, completions);
380
+ for (const [index, { passed, sample }] of disambiguationVote) {
381
+ disambiguation.push({ ...sample, index, resolvable: passed });
382
+ }
383
+ } else {
384
+ const merged = await runBatched(batches, "selection+disambiguation", state, async (windows) => {
385
+ const out = await runSelectAndDisambiguate({
386
+ windows, question: args.question, model: args.model, temperature, ...(args.signal ? { signal: args.signal } : {}),
387
+ });
388
+ return { result: { selection: out.selection, disambiguation: out.disambiguation }, usage: out.usage };
389
+ });
390
+ for (const part of merged) {
391
+ selection.push(...part.selection);
392
+ disambiguation.push(...part.disambiguation);
393
+ }
394
+ }
395
+ lap("selectDisambiguateMs", tStage);
396
+
397
+ // Record the states these two stages decided.
398
+ const selectionByIndex = new Map(selection.map((s) => [s.index, s]));
399
+ const disambiguationByIndex = new Map(disambiguation.map((d) => [d.index, d]));
400
+ const survivingIndexes: number[] = [];
401
+ // Finding 4: a sentence the model never answered for is NOT the finding
402
+ // "this sentence asserts nothing checkable" (no_verifiable_content) — that
403
+ // would tell the user something about their text that nobody judged. The
404
+ // stages set `answered: false` for exactly this case, so the two are
405
+ // distinguishable here without matching on reason strings.
406
+ const unanswered: number[] = [];
407
+ for (const sentence of sentences) {
408
+ const sel = selectionByIndex.get(sentence.index);
409
+ const dis = disambiguationByIndex.get(sentence.index);
410
+ if (!sel) continue; // not_checked was already recorded by runBatched
411
+ if (sel.answered === false) {
412
+ state.states.set(sentence.index, { state: "not_checked", reason: sel.reason });
413
+ unanswered.push(sentence.index);
414
+ continue;
415
+ }
416
+ if (!sel.verifiable) {
417
+ state.states.set(sentence.index, { state: "no_verifiable_content", reason: sel.reason });
418
+ continue;
419
+ }
420
+ if (dis?.answered === false) {
421
+ state.states.set(sentence.index, { state: "not_checked", reason: dis.reason });
422
+ unanswered.push(sentence.index);
423
+ continue;
424
+ }
425
+ if (!dis?.resolvable) {
426
+ state.states.set(sentence.index, {
427
+ state: "cannot_disambiguate",
428
+ reason: dis?.reason ?? "disambiguation did not report an outcome",
429
+ });
430
+ continue;
431
+ }
432
+ state.states.set(sentence.index, { state: "checked" });
433
+ survivingIndexes.push(sentence.index);
434
+ }
435
+ if (unanswered.length > 0) {
436
+ state.partial = true;
437
+ state.notes.push(
438
+ `selection/disambiguation returned no outcome for ${unanswered.length} sentence(s); they are not_checked`,
439
+ );
440
+ }
441
+
442
+ // ── Decomposition ────────────────────────────────────────────────────────
443
+ tStage = Date.now();
444
+ const claims: Claim[] = [];
445
+ if (survivingIndexes.length > 0) {
446
+ // Correction 1: built from every surviving sentence, globally — same
447
+ // reasoning as the `texts` map above.
448
+ const decomposeTexts = new Map<number, string>();
449
+ for (const index of survivingIndexes) {
450
+ const clarified = disambiguationByIndex.get(index)?.clarified;
451
+ const rewritten = selectionByIndex.get(index)?.rewritten;
452
+ const text = clarified ?? rewritten;
453
+ if (text) decomposeTexts.set(index, text);
454
+ }
455
+ const survivorWindows = survivingIndexes.map((i) => laterWindows.get(i)!).filter(Boolean);
456
+ const decomposed = await runBatched(chunk(survivorWindows, decomposeBatchSize), "decomposition", state, async (windows) => {
457
+ const { outcomes, usage } = await runDecomposition({
458
+ windows, question: args.question, sentenceTexts: decomposeTexts, model: args.model, temperature: 0,
459
+ ...(args.signal ? { signal: args.signal } : {}),
460
+ });
461
+ return { result: outcomes, usage };
462
+ });
463
+
464
+ const allowed = new Set(survivingIndexes);
465
+ const flat = decomposed.flat().filter((o) => allowed.has(o.index)).sort((a, b) => a.index - b.index);
466
+ // Finding 4: a sentence whose decomposition DID produce claims, but every
467
+ // one of them landed past the maxClaims cap, must read as a resource cap
468
+ // (cap_exceeded) — not as "decomposition found nothing to verify here",
469
+ // which is what no_verifiable_content means.
470
+ const capCutSentences = new Set<number>();
471
+ for (const outcome of flat) {
472
+ let pushedForThisOutcome = 0;
473
+ for (const c of outcome.claims) {
474
+ if (claims.length >= options.caps.maxClaims) break;
475
+ claims.push({
476
+ id: `c${claims.length + 1}`,
477
+ sentenceIndex: outcome.index,
478
+ text: c.text,
479
+ inferred: c.inferred,
480
+ verdict: "unsupported",
481
+ evidence: [],
482
+ rationale: "",
483
+ rechecked: false,
484
+ });
485
+ pushedForThisOutcome += 1;
486
+ }
487
+ if (outcome.claims.length > 0 && pushedForThisOutcome === 0) {
488
+ capCutSentences.add(outcome.index);
489
+ }
490
+ }
491
+ const produced = flat.reduce((n, o) => n + o.claims.length, 0);
492
+ if (produced > claims.length) {
493
+ state.partial = true;
494
+ state.notes.push(`maxClaims (${options.caps.maxClaims}) reached; ${produced - claims.length} claim(s) dropped`);
495
+ }
496
+
497
+ // Correction 2: a sentence decomposition REPORTED ON but found no claim in
498
+ // ("no_verifiable_content") is a different fact from a sentence it never
499
+ // answered for at all ("not_checked") — runDecomposition omits an entry
500
+ // entirely in the latter case, so the two are distinguishable here, and a
501
+ // reader deserves to know which one happened.
502
+ const outcomeIndexes = new Set(flat.map((o) => o.index));
503
+ const withClaims = new Set(claims.map((c) => c.sentenceIndex));
504
+ const missingOutcome: number[] = [];
505
+ for (const index of survivingIndexes) {
506
+ if (withClaims.has(index)) continue;
507
+ if (capCutSentences.has(index)) {
508
+ state.states.set(index, { state: "not_checked", reason: "cap_exceeded" });
509
+ } else if (outcomeIndexes.has(index)) {
510
+ state.states.set(index, { state: "no_verifiable_content", reason: "decomposition extracted no claim" });
511
+ } else {
512
+ state.states.set(index, { state: "not_checked", reason: "decomposition did not report an outcome" });
513
+ missingOutcome.push(index);
514
+ }
515
+ }
516
+ if (missingOutcome.length > 0) {
517
+ state.partial = true;
518
+ state.notes.push(`decomposition did not report an outcome for ${missingOutcome.length} sentence(s)`);
519
+ }
520
+ }
521
+ lap("decomposeMs", tStage);
522
+
523
+ // ── Evidence + Verification ──────────────────────────────────────────────
524
+ tStage = Date.now();
525
+ // One index per check: the token sets and the document-frequency map are
526
+ // built here, not inside the 200-odd per-claim selections below.
527
+ const indexed = indexSourcesWithLimits(args.sources);
528
+ const passages = indexed.passages;
529
+ truncation = indexed.truncation;
530
+ if (truncation.sources > 0) {
531
+ // R35: a check that read three quarters of the evidence is not "ok".
532
+ // `unsupportedShare` over a partly-read source set is a number the
533
+ // engine did not measure, and the zero-evidence case below already
534
+ // reports exactly that degree-of-coverage fact as `partial` — leaving
535
+ // this one `ok` made `partial` disagree with itself, and a client
536
+ // branching on `status` (as the docs instruct) read a quarter-blind
537
+ // check as clean.
538
+ state.partial = true;
539
+
540
+ state.notes.push(
541
+ `${truncation.sources} source(s) were truncated at ${MAX_CHARS_PER_SOURCE} characters ` +
542
+ `(${formatSourceNames(truncation.names)}); ` +
543
+ `${truncation.droppedChars} character(s) of evidence were not searched, so a claim supported only there reads as unsupported`,
544
+ );
545
+ }
546
+ lap("evidenceMs", tStage);
547
+
548
+ tStage = Date.now();
549
+ // Correction 3: a verification group whose CALL FAILED must not leave its
550
+ // claims standing as "unsupported" — that reports a provider outage as a
551
+ // coverage gap in the customer's sources. Those claims are dropped from the
552
+ // result entirely (never reaching scoreClaims), and their sentences become
553
+ // not_checked instead.
554
+ let finalClaims: Claim[] = claims;
555
+ if (claims.length > 0) {
556
+ const bySentence = new Map<number, Claim[]>();
557
+ for (const claim of claims) {
558
+ const list = bySentence.get(claim.sentenceIndex) ?? [];
559
+ list.push(claim);
560
+ bySentence.set(claim.sentenceIndex, list);
561
+ }
562
+ const groups = chunk([...bySentence.values()], BATCH.verifySentences).map((g) => g.flat());
563
+
564
+ const verified = await mapWithConcurrency(groups, MAX_IN_FLIGHT, async (group) => {
565
+ const evidence = selectGroupEvidence(group.map((c) => c.text), indexed);
566
+ return runVerification({
567
+ claims: group.map((c) => ({ id: c.id, text: c.text })),
568
+ evidence,
569
+ model: args.model,
570
+ ...(args.signal ? { signal: args.signal } : {}),
571
+ });
572
+ });
573
+
574
+ const droppedClaimIds = new Set<string>();
575
+ const byId = new Map(claims.map((c) => [c.id, c]));
576
+ verified.forEach((outcome, i) => {
577
+ const group = groups[i]!;
578
+ if (outcome.status !== "fulfilled") {
579
+ state.partial = true;
580
+ state.notes.push(`verification failed for ${group.length} claim(s); they were dropped from the result`);
581
+ const sentenceIndexes = new Set(group.map((c) => c.sentenceIndex));
582
+ for (const c of group) droppedClaimIds.add(c.id);
583
+ for (const index of sentenceIndexes) {
584
+ state.states.set(index, { state: "not_checked", reason: "verification failed for this sentence" });
585
+ }
586
+ return;
587
+ }
588
+ state.usage = addUsage(state.usage, outcome.value.usage);
589
+ for (const verdict of outcome.value.outcomes) {
590
+ const claim = byId.get(verdict.claimId);
591
+ if (!claim) continue;
592
+ claim.verdict = verdict.verdict;
593
+ claim.evidence = verdict.evidence;
594
+ claim.rationale = verdict.rationale;
595
+ }
596
+
597
+ // Finding 4: the call succeeded but the model left claims out of its
598
+ // array. Those claims carry no verdict anybody produced, so they are
599
+ // dropped like the claims of a failed call — never reported
600
+ // "unsupported", which would inflate the share with the model's
601
+ // silence. A sentence whose every claim was dropped was not checked.
602
+ const answered = new Set(outcome.value.outcomes.map((o) => o.claimId));
603
+ const missing = group.filter((c) => !answered.has(c.id));
604
+ if (missing.length === 0) return;
605
+ state.partial = true;
606
+ state.notes.push(
607
+ `verification returned no verdict for ${missing.length} claim(s); they were dropped from the result`,
608
+ );
609
+ for (const c of missing) droppedClaimIds.add(c.id);
610
+ const groupSentences = new Map<number, Claim[]>();
611
+ for (const c of group) {
612
+ const list = groupSentences.get(c.sentenceIndex) ?? [];
613
+ list.push(c);
614
+ groupSentences.set(c.sentenceIndex, list);
615
+ }
616
+ for (const [index, list] of groupSentences) {
617
+ if (list.every((c) => droppedClaimIds.has(c.id))) {
618
+ state.states.set(index, {
619
+ state: "not_checked",
620
+ reason: "verification returned no verdict for this sentence",
621
+ });
622
+ }
623
+ }
624
+ });
625
+
626
+ finalClaims = droppedClaimIds.size > 0 ? claims.filter((c) => !droppedClaimIds.has(c.id)) : claims;
627
+
628
+ // ── Second chance for unsupported claims (IMP callers only) ────────────
629
+ if (options.reRetrieve && args.secondChance && options.caps.maxReRetrievals > 0) {
630
+ const candidates = finalClaims.filter((c) => c.verdict === "unsupported");
631
+ const budget = candidates.slice(0, options.caps.maxReRetrievals);
632
+ if (candidates.length > budget.length) {
633
+ state.notes.push(
634
+ `maxReRetrievals (${options.caps.maxReRetrievals}) reached; ${candidates.length - budget.length} unsupported claim(s) were not re-retrieved`,
635
+ );
636
+ }
637
+ await mapWithConcurrency(budget, MAX_IN_FLIGHT, async (claim) => {
638
+ try {
639
+ const extra = await args.secondChance!(claim.text);
640
+ if (extra.length === 0) return;
641
+ const { outcomes, usage } = await runVerification({
642
+ claims: [{ id: claim.id, text: claim.text }],
643
+ evidence: extra,
644
+ model: args.model,
645
+ ...(args.signal ? { signal: args.signal } : {}),
646
+ });
647
+ state.usage = addUsage(state.usage, usage);
648
+ const verdict = outcomes[0];
649
+ if (!verdict) return;
650
+ claim.rechecked = true;
651
+ claim.verdict = verdict.verdict;
652
+ claim.evidence = verdict.evidence;
653
+ claim.rationale = verdict.rationale;
654
+ } catch {
655
+ // A failed second chance leaves the first verdict standing.
656
+ state.notes.push(`second-chance retrieval failed for ${claim.id}`);
657
+ }
658
+ });
659
+ }
660
+ }
661
+ lap("verifyMs", tStage);
662
+
663
+ // Finding 3 (spec §2.4 rule 3): with no usable passage at all, every claim
664
+ // lands in verification's no-evidence branch and the result would read
665
+ // "100% unsupported, status ok" — a confident hallucination verdict
666
+ // produced without a byte of evidence having been read. Only claims that
667
+ // WERE judged against evidence can carry a score; when a second-chance
668
+ // retrieval supplied passages for some of them, those still count, and
669
+ // when nothing was read at all this is scoreClaims([]) → label "n/a".
670
+ const scorable = passages.length === 0 ? finalClaims.filter((c) => c.rechecked) : finalClaims;
671
+ const unread = finalClaims.length - scorable.length;
672
+ if (unread > 0) {
673
+ state.partial = true;
674
+ state.notes.push(
675
+ `no usable evidence was supplied: ${unread} claim(s) are reported unsupported without any source having been read, and are excluded from the score`,
676
+ );
677
+ }
678
+
679
+ timings.totalMs = Date.now() - startedAt;
680
+
681
+ return {
682
+ status: state.partial ? "partial" : "ok",
683
+ score: scoreClaims(scorable, options.thresholds),
684
+ sentences: buildSentenceResults(allSentences, state.states, finalClaims),
685
+ claims: finalClaims,
686
+ usage: state.usage,
687
+ timings,
688
+ limits: { truncated: skipped.length > 0 || truncation.sources > 0, sentencesSkipped: skipped.length },
689
+ notes: state.notes,
690
+ };
691
+ } catch (err) {
692
+ // "Partial beats failing": an uncaught error anywhere in the pipeline
693
+ // (provider calls are already isolated per-call by mapWithConcurrency, so
694
+ // this is for something like a bug in split/evidence/score) degrades to a
695
+ // partial result instead of rejecting the caller's promise. The note
696
+ // carries the error forward rather than swallowing it.
697
+ timings.totalMs = Date.now() - startedAt;
698
+ const message = err instanceof Error ? err.message : String(err);
699
+ return {
700
+ status: "partial",
701
+ score: scoreClaims([], options.thresholds),
702
+ sentences: buildSentenceResults(allSentences, state.states, []),
703
+ claims: [],
704
+ usage: state.usage,
705
+ timings,
706
+ limits: { truncated: skipped.length > 0 || truncation.sources > 0, sentencesSkipped: skipped.length },
707
+ notes: [...state.notes, `claim check failed internally: ${message}`],
708
+ };
709
+ }
710
+ }