@exulu/backend 5.1.2 → 5.3.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 (58) hide show
  1. package/dist/{chunk-37MKZIH2.js → chunk-PU3LGCBR.js} +281 -33
  2. package/dist/{convert-exulu-tools-to-ai-sdk-tools-BNDHJH7B.js → convert-exulu-tools-to-ai-sdk-tools-77FLVHEA.js} +3 -1
  3. package/dist/index.cjs +2800 -376
  4. package/dist/index.js +2412 -285
  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/invoke-skills/create-sandbox.ts +18 -1
  55. package/ee/python/requirements.txt +3 -0
  56. package/ee/schemas.ts +71 -0
  57. package/ee/workers.ts +13 -0
  58. package/package.json +1 -1
@@ -126,3 +126,82 @@ describe("rerankResults", () => {
126
126
  expect(passedItems[0].chunk_content).toBe("hello\nworld");
127
127
  });
128
128
  });
129
+
130
+ describe("duplicate suppression", () => {
131
+ const reranker = { model: "m", rerank: jest.fn(async (_q: string, items: any[]) =>
132
+ items.map((it, i) => ({ ...it, rerank_score: 0.9 - i * 0.01 }))) } as any;
133
+
134
+ it("keeps the best-scoring copy and backfills the freed slot", async () => {
135
+ const chunks = Array.from({ length: 6 }, (_, i) => chunk("c" + i, "I" + i, 1));
136
+ const r = await rerankResults({
137
+ chunks, query: "q", state: state(), reranker, tuning: { ...tuning, topK: 3 },
138
+ findNearDuplicates: async () => [["c0", "c1"]],
139
+ });
140
+ const ids = r.limited_results.map((c: any) => c.chunk_id);
141
+ expect(ids).toHaveLength(3);
142
+ expect(ids).toContain("c0"); // better score survives
143
+ expect(ids).not.toContain("c1"); // its near-duplicate is dropped
144
+ expect(ids).toContain("c3"); // slot backfilled past c2
145
+ });
146
+
147
+ it("still returns topK when every candidate is a near-duplicate", async () => {
148
+ const chunks = Array.from({ length: 5 }, (_, i) => chunk("d" + i, "I" + i, 1));
149
+ const all: Array<[string, string]> = [];
150
+ for (let i = 0; i < 5; i++) for (let j = i + 1; j < 5; j++) all.push(["d" + i, "d" + j]);
151
+ const r = await rerankResults({
152
+ chunks, query: "q", state: state(), reranker, tuning: { ...tuning, topK: 3 },
153
+ findNearDuplicates: async () => all,
154
+ });
155
+ expect(r.limited_results).toHaveLength(3);
156
+ expect(r.limited_results[0].chunk_id).toBe("d0");
157
+ });
158
+
159
+ it("keeps a chunk with no chunk_id and never suppresses by it", async () => {
160
+ // 4 candidates, topK 3: e2 is a duplicate of e0 and must lose its slot to e3,
161
+ // while the id-less chunk is kept and never used as a suppression key.
162
+ const chunks = [
163
+ chunk("e0", "I0", 1),
164
+ chunk("e2", "I2", 1),
165
+ { ...chunk("x", "I1", 1), chunk_id: undefined },
166
+ chunk("e3", "I3", 1),
167
+ ];
168
+ const r = await rerankResults({
169
+ chunks: chunks as any, query: "q", state: state(), reranker, tuning: { ...tuning, topK: 3 },
170
+ findNearDuplicates: async () => [["e0", "e2"]],
171
+ });
172
+ const ids = r.limited_results.map((c: any) => c.chunk_id);
173
+ expect(r.limited_results).toHaveLength(3);
174
+ expect(ids).toContain("e0");
175
+ expect(ids).not.toContain("e2"); // duplicate dropped
176
+ expect(ids).toContain(undefined); // id-less chunk kept
177
+ expect(ids).toContain("e3"); // freed slot backfilled
178
+ });
179
+
180
+ it("behaves exactly as before when no callback is supplied", async () => {
181
+ const chunks = Array.from({ length: 6 }, (_, i) => chunk("f" + i, "I" + i, 1));
182
+ const base = { chunks, query: "q", state: state(), reranker, tuning: { ...tuning, topK: 3 } };
183
+ const without = await rerankResults(base);
184
+ expect(without.limited_results.map((c: any) => c.chunk_id)).toEqual(["f0", "f1", "f2"]);
185
+ });
186
+
187
+ it("suppresses duplicates on the page-filter path too (three copies of page 127)", async () => {
188
+ // The motivating case from the design spec: an explicit page lookup where the page
189
+ // exists three times under different filenames. The page filter used to overwrite
190
+ // limited_results with a plain slice, which bypassed suppression entirely.
191
+ const chunks = Array.from({ length: 5 }, (_, i) =>
192
+ chunk("p" + i, "I" + i, 1, { chunk_metadata: { page: 127 } }),
193
+ );
194
+ const r = await rerankResults({
195
+ chunks, query: "q", state: state({ userRequestedPage: 127 }), reranker,
196
+ tuning: { ...tuning, topK: 3 },
197
+ findNearDuplicates: async () => [["p0", "p1"], ["p0", "p2"], ["p1", "p2"]],
198
+ });
199
+ const ids = r.limited_results.map((c: any) => c.chunk_id);
200
+ expect(ids).toHaveLength(3);
201
+ expect(ids).toContain("p0"); // best-scoring copy survives
202
+ expect(ids).not.toContain("p1"); // its near-duplicates lose their slots
203
+ expect(ids).not.toContain("p2");
204
+ expect(ids).toContain("p3"); // freed slots carry different content
205
+ expect(ids).toContain("p4");
206
+ });
207
+ });
@@ -63,8 +63,14 @@ export async function rerankResults(opts: {
63
63
  state: RerankState;
64
64
  reranker?: ResolvedReranker;
65
65
  tuning: { topK: number; pinBoost: number; identifierBoost: number; pageWindow: number };
66
+ /**
67
+ * Optional near-duplicate lookup. Receives the sorted candidate slice and returns unordered
68
+ * id pairs whose content is near-identical. Suppression happens DURING top-K selection so a
69
+ * dropped candidate's slot is backfilled. Absent or failing = no suppression.
70
+ */
71
+ findNearDuplicates?: (candidates: ChunkWithScore[]) => Promise<Array<[string, string]>>;
66
72
  }): Promise<RerankResult> {
67
- const { chunks, query, state, reranker, tuning } = opts;
73
+ const { chunks, query, state, reranker, tuning, findNearDuplicates } = opts;
68
74
 
69
75
  // Empty input fast path
70
76
  if (chunks.length === 0) {
@@ -151,16 +157,59 @@ export async function rerankResults(opts: {
151
157
 
152
158
  // Top-K selection with pinned-item force-inclusion
153
159
  const { topK } = tuning;
160
+
161
+ // Ask only about the window selection can reach: topK plus the backfill reserve.
162
+ const candidateWindow = sorted.slice(0, Math.max(topK * 3, topK + 20));
163
+ let duplicateOf = new Map<string, string[]>();
164
+ if (findNearDuplicates && candidateWindow.length > 1) {
165
+ try {
166
+ const pairs = await findNearDuplicates(candidateWindow);
167
+ for (const [a, b] of pairs) {
168
+ if (!a || !b) continue;
169
+ duplicateOf.set(a, [...(duplicateOf.get(a) ?? []), b]);
170
+ duplicateOf.set(b, [...(duplicateOf.get(b) ?? []), a]);
171
+ }
172
+ } catch (err) {
173
+ console.warn("[EXULU pipeline] near-duplicate lookup failed — selecting without suppression:", err);
174
+ duplicateOf = new Map();
175
+ }
176
+ }
177
+
178
+ const selectDistinct = (pool: ChunkWithScore[], n: number): ChunkWithScore[] => {
179
+ if (duplicateOf.size === 0) return pool.slice(0, n);
180
+ const picked: ChunkWithScore[] = [];
181
+ const pickedIds = new Set<string>();
182
+ const deferred: ChunkWithScore[] = [];
183
+ for (const c of pool) {
184
+ if (picked.length >= n) break;
185
+ const id = c.chunk_id;
186
+ // A chunk without an id can never be matched by a pair; always keep it.
187
+ if (id && (duplicateOf.get(id) ?? []).some((other) => pickedIds.has(other))) {
188
+ deferred.push(c);
189
+ continue;
190
+ }
191
+ picked.push(c);
192
+ if (id) pickedIds.add(id);
193
+ }
194
+ // Never return fewer than asked: refill from what was deferred, best score first.
195
+ for (const c of deferred) {
196
+ if (picked.length >= n) break;
197
+ picked.push(c);
198
+ }
199
+ return picked;
200
+ };
201
+
154
202
  let limited_results: ChunkWithScore[] = (() => {
155
- const top = sorted.slice(0, topK);
203
+ const top = selectDistinct(sorted, topK);
156
204
  if (pinnedGroups.length === 0) return top;
157
205
  const byId = new Map<string, ChunkWithScore>();
158
206
  for (const r of [...pinnedGroups, ...top]) {
159
207
  if (r.chunk_id && !byId.has(r.chunk_id)) byId.set(r.chunk_id, r);
160
208
  }
161
- return Array.from(byId.values())
162
- .sort((a, b) => (b.rerank_score || 0) - (a.rerank_score || 0))
163
- .slice(0, Math.max(topK, pinnedGroups.length + topK));
209
+ return selectDistinct(
210
+ Array.from(byId.values()).sort((a, b) => (b.rerank_score || 0) - (a.rerank_score || 0)),
211
+ Math.max(topK, pinnedGroups.length + topK),
212
+ );
164
213
  })();
165
214
 
166
215
  // Page filter — applies to all paths; scoped to userPinnedItemIds when non-empty
@@ -171,7 +220,13 @@ export async function rerankResults(opts: {
171
220
  const p = (r.chunk_metadata as { page?: unknown } | undefined)?.page;
172
221
  return typeof p === 'number' && Math.abs(p - state.userRequestedPage!) <= tuning.pageWindow;
173
222
  });
174
- if (pageMatched.length > 0) limited_results = pageMatched.slice(0, topK);
223
+ // Suppression applies on this path too — an explicit page lookup is the motivating case
224
+ // for it (several copies of the same page under different filenames). Pair coverage here
225
+ // is partial by design: the pair window was computed over the head of `sorted`, so a page
226
+ // match below it contributes no pairs. Partial suppression beats none, and `selectDistinct`
227
+ // refills from what it deferred, so this can never return fewer results than the plain
228
+ // slice did. With no pairs found it IS the plain slice.
229
+ if (pageMatched.length > 0) limited_results = selectDistinct(pageMatched, topK);
175
230
  }
176
231
 
177
232
  return { limited_results, sorted_reranked_results: sorted, rerank_score_max_genuine };
@@ -0,0 +1,26 @@
1
+ // ee/claim-check/agent-config.ts
2
+ //
3
+ // One place to read a claim-check caller's agent configuration. Both the HTTP
4
+ // handler and the second-chance retrieval need the same two steps — flatten the
5
+ // agentic_context_search tool's config entries, then parse them with the
6
+ // retrieval pipeline's own schema — so neither owns a private copy.
7
+ import { parsePipelineConfig, type PipelineConfig } from "@EE/agentic-retrieval/pipeline/config";
8
+
9
+ /** The agent's agentic_context_search tool config as a plain record. */
10
+ export function toolConfigOf(agent: unknown): Record<string, unknown> {
11
+ const tools = (agent as { tools?: { id?: string; config?: { name?: string; variable?: unknown }[] }[] } | undefined)?.tools ?? [];
12
+ const tool = tools.find((t) => t?.id === "agentic_context_search");
13
+ const out: Record<string, unknown> = {};
14
+ for (const entry of tool?.config ?? []) if (entry?.name) out[entry.name] = entry.variable;
15
+ return out;
16
+ }
17
+
18
+ /** True when the agent has no agentic_context_search tool configured at all. */
19
+ export function hasNoToolConfig(raw: Record<string, unknown>): boolean {
20
+ return Object.keys(raw).length === 0;
21
+ }
22
+
23
+ /** The parsed pipeline config for an agent; defaults throughout, never throws. */
24
+ export function pipelineConfigFor(agent: unknown): PipelineConfig {
25
+ return parsePipelineConfig(toolConfigOf(agent));
26
+ }
@@ -0,0 +1,33 @@
1
+ // ee/claim-check/concurrency.test.ts
2
+ import { mapWithConcurrency } from "./concurrency";
3
+
4
+ describe("mapWithConcurrency", () => {
5
+ it("never exceeds the limit and preserves input order in the results", async () => {
6
+ let inFlight = 0;
7
+ let peak = 0;
8
+ const items = [1, 2, 3, 4, 5, 6, 7, 8];
9
+ const results = await mapWithConcurrency(items, 3, async (n) => {
10
+ inFlight += 1;
11
+ peak = Math.max(peak, inFlight);
12
+ await new Promise((r) => setTimeout(r, 5));
13
+ inFlight -= 1;
14
+ return n * 2;
15
+ });
16
+ expect(peak).toBeLessThanOrEqual(3);
17
+ expect(results.map((r) => (r.status === "fulfilled" ? r.value : null))).toEqual([2, 4, 6, 8, 10, 12, 14, 16]);
18
+ });
19
+
20
+ it("reports a rejection per item instead of failing the whole batch", async () => {
21
+ const results = await mapWithConcurrency([1, 2, 3], 2, async (n) => {
22
+ if (n === 2) throw new Error("boom");
23
+ return n;
24
+ });
25
+ expect(results.map((r) => r.status)).toEqual(["fulfilled", "rejected", "fulfilled"]);
26
+ });
27
+
28
+ it("returns an empty array for no items and treats a limit below 1 as 1", async () => {
29
+ expect(await mapWithConcurrency([], 4, async (n) => n)).toEqual([]);
30
+ const results = await mapWithConcurrency([1, 2], 0, async (n) => n);
31
+ expect(results).toHaveLength(2);
32
+ });
33
+ });
@@ -0,0 +1,30 @@
1
+ // ee/claim-check/concurrency.ts
2
+ //
3
+ // Bounded fan-out. A check is a few dozen provider calls; letting them all go
4
+ // at once manufactures the 429s the retry logic then has to absorb.
5
+
6
+ export async function mapWithConcurrency<T, R>(
7
+ items: T[],
8
+ limit: number,
9
+ fn: (item: T, index: number) => Promise<R>,
10
+ ): Promise<PromiseSettledResult<R>[]> {
11
+ const results: PromiseSettledResult<R>[] = new Array(items.length);
12
+ const bound = Math.max(1, Math.floor(limit));
13
+ let next = 0;
14
+
15
+ const worker = async (): Promise<void> => {
16
+ while (true) {
17
+ const index = next;
18
+ next += 1;
19
+ if (index >= items.length) return;
20
+ try {
21
+ results[index] = { status: "fulfilled", value: await fn(items[index]!, index) };
22
+ } catch (reason) {
23
+ results[index] = { status: "rejected", reason };
24
+ }
25
+ }
26
+ };
27
+
28
+ await Promise.all(Array.from({ length: Math.min(bound, items.length) }, () => worker()));
29
+ return results;
30
+ }
@@ -0,0 +1,198 @@
1
+ import { preprocessQuery } from "@SRC/utils/query-preprocessing";
2
+ import { indexSources, indexSourcesWithLimits, MAX_CHARS_PER_SOURCE, selectEvidence } from "./evidence";
3
+
4
+ const SOURCES = [
5
+ {
6
+ id: "s1",
7
+ name: "handbuch.pdf",
8
+ content:
9
+ "Der Kabinenlichtschalter im Schaltschrank kann eine Fernabschaltung auslösen. " +
10
+ "Die Spannung beträgt 230 Volt.",
11
+ },
12
+ {
13
+ id: "s2",
14
+ name: "ticket-1735.txt",
15
+ content: "Der Kunde meldet eine defekte Tür. Die Tür wurde am 3. März getauscht.",
16
+ },
17
+ ];
18
+
19
+ describe("indexSources", () => {
20
+ it("produces passages tagged with their source id and name", () => {
21
+ const { passages } = indexSources(SOURCES);
22
+ expect(passages.length).toBeGreaterThanOrEqual(2);
23
+ expect(new Set(passages.map((p) => p.sourceId))).toEqual(new Set(["s1", "s2"]));
24
+ expect(passages[0]!.tokens.size).toBeGreaterThan(0);
25
+ });
26
+
27
+ it("slices long content into overlapping passages and truncates per source", () => {
28
+ const long = { id: "big", content: "Satz eins. ".repeat(500) };
29
+ const { passages } = indexSources([long], { passageChars: 400, overlapChars: 50, maxCharsPerSource: 2000 });
30
+ expect(passages.length).toBeGreaterThan(1);
31
+ expect(passages.reduce((n, p) => n + p.text.length, 0)).toBeLessThanOrEqual(2000 + 400);
32
+ });
33
+
34
+ // Finding 5: 28.4% of a 601,392-char evidence set used to be dropped
35
+ // silently — limits.truncated stayed false and no note was emitted, so
36
+ // claims supported only in a dropped tail came back "unsupported".
37
+ it("reports how many sources were truncated and how many characters were dropped", () => {
38
+ const { passages, truncation } = indexSourcesWithLimits(
39
+ [
40
+ { id: "big", content: "a".repeat(2500) },
41
+ { id: "bigger", content: "b".repeat(3000) },
42
+ { id: "small", content: "Kurzer Satz." },
43
+ ],
44
+ { passageChars: 400, overlapChars: 50, maxCharsPerSource: 1000 },
45
+ );
46
+ expect(truncation).toEqual({ sources: 2, droppedChars: 1500 + 2000, names: ["big", "bigger"] });
47
+ expect(passages.every((p) => p.text.length <= 400)).toBe(true);
48
+ });
49
+
50
+ it("reports no truncation when every source fits", () => {
51
+ expect(indexSourcesWithLimits(SOURCES).truncation).toEqual({ sources: 0, droppedChars: 0, names: [] });
52
+ });
53
+
54
+ it("defaults the per-source limit to the documented 60,000 characters", () => {
55
+ expect(MAX_CHARS_PER_SOURCE).toBe(60_000);
56
+ const { truncation } = indexSourcesWithLimits([{ id: "huge", content: "x".repeat(60_010) }]);
57
+ expect(truncation).toEqual({ sources: 1, droppedChars: 10, names: ["huge"] });
58
+ });
59
+
60
+ // Review Focus 3
61
+ it("ignores empty and whitespace-only sources without crashing", () => {
62
+ expect(indexSources([{ id: "e1", content: "" }, { id: "e2", content: " \n " }]).passages).toEqual([]);
63
+ });
64
+
65
+ // R36: selectEvidence is called once per claim (200 of them at production
66
+ // scale), and it used to rebuild a Set per passage AND the whole
67
+ // document-frequency map on every one of those calls — 1,377 ms of
68
+ // synchronous event-loop blocking per check, measured over 541k chars of
69
+ // evidence, in a process that also streams chat for everyone else.
70
+ it("builds each passage's token set and the set's document frequencies once, at index time", () => {
71
+ const { passages, documentFrequency } = indexSources(SOURCES);
72
+
73
+ expect(passages.every((p) => p.tokens instanceof Set)).toBe(true);
74
+ // "der", "die" and "ein" are in both passages; the distinguishing terms
75
+ // are in one each. This map is the IDF denominator.
76
+ expect(documentFrequency.get("der")).toBe(2);
77
+ expect(documentFrequency.get("die")).toBe(2);
78
+ expect(documentFrequency.get("ein")).toBe(2);
79
+ expect(documentFrequency.get("fernabschalt")).toBe(1);
80
+ expect(documentFrequency.get("getauscht")).toBe(1);
81
+ expect(documentFrequency.size).toBe(new Set(passages.flatMap((p) => [...p.tokens])).size);
82
+ });
83
+
84
+ // Review Focus 3
85
+ it("keeps duplicate source ids distinguishable by passage, never merging them", () => {
86
+ const { passages } = indexSources([
87
+ { id: "dup", name: "a.pdf", content: "Inhalt A über Schalter." },
88
+ { id: "dup", name: "b.pdf", content: "Inhalt B über Türen." },
89
+ ]);
90
+ expect(passages.map((p) => p.sourceName).sort()).toEqual(["a.pdf", "b.pdf"]);
91
+ expect(passages.every((p) => p.sourceId === "dup")).toBe(true);
92
+ });
93
+ });
94
+
95
+ describe("selectEvidence", () => {
96
+ it("ranks the passage that shares the claim's terms first", () => {
97
+ const index = indexSources(SOURCES);
98
+ const [top] = selectEvidence(["Der Kabinenlichtschalter löst eine Fernabschaltung aus"], index, 2);
99
+ expect(top!.sourceId).toBe("s1");
100
+ expect(top!.text).toContain("Fernabschaltung");
101
+ expect(top!.score).toBeGreaterThan(0);
102
+ });
103
+
104
+ it("returns at most topK snippets and none for an empty passage set", () => {
105
+ const index = indexSources(SOURCES);
106
+ expect(selectEvidence(["Spannung"], index, 1)).toHaveLength(1);
107
+ expect(selectEvidence(["Spannung"], indexSources([]), 3)).toEqual([]);
108
+ });
109
+
110
+ it("scores a claim with no lexical overlap at zero but still returns a fallback snippet", () => {
111
+ const index = indexSources(SOURCES);
112
+ const picked = selectEvidence(["Völlig unverwandtes Thema Zebrastreifen"], index, 2);
113
+ expect(picked).toHaveLength(2);
114
+ expect(picked.every((p) => p.score === 0)).toBe(true);
115
+ });
116
+
117
+ it("pools the terms of several claims, surfacing a passage one claim alone would not rank", () => {
118
+ const sources = [
119
+ { id: "p1", content: "Steuerung meldet Fernabschaltung im Schaltschrank." },
120
+ { id: "p2", content: "Kabinentuer wurde getauscht und Dienstag geprueft." },
121
+ { id: "p3", content: "Steuerung ist montiert." },
122
+ ];
123
+ const index = indexSources(sources);
124
+ const claimA = "Steuerung meldet Fernabschaltung";
125
+ const claimB = "Kabinentuer wurde getauscht Dienstag";
126
+
127
+ // Claim A alone: p3 shares "Steuerung" and so outranks p2, which shares nothing.
128
+ const aOnly = selectEvidence([claimA], index, 2).map((p) => p.sourceId);
129
+ expect(aOnly).toContain("p1");
130
+ expect(aOnly).toContain("p3");
131
+ expect(aOnly).not.toContain("p2");
132
+
133
+ // Both claims pooled: p2 now carries three of claim B's rare terms and must
134
+ // displace p3, which carries only one of claim A's. This assertion is the
135
+ // discriminator — it fails if the second claim's tokens are not pooled in.
136
+ const pooled = selectEvidence([claimA, claimB], index, 2).map((p) => p.sourceId);
137
+ expect(pooled).toContain("p1");
138
+ expect(pooled).toContain("p2");
139
+ expect(pooled).not.toContain("p3");
140
+ });
141
+
142
+ it("zeroes ubiquitous terms and avoids their ranking inversion", () => {
143
+ const sources = [
144
+ { id: "s1", name: "a.txt", content: "Die Anlage wurde installiert und getestet." },
145
+ { id: "s2", name: "b.txt", content: "Die Prüfung wurde durchgeführt und bestanden." },
146
+ { id: "s3", name: "c.txt", content: "Die Wartung wurde geplant und dokumentiert." },
147
+ { id: "s4", name: "d.txt", content: "Die Spule wurde ersetzt und kalibriert." },
148
+ ];
149
+ const index = indexSources(sources);
150
+ // "Die" and "wurde" appear in all four passages (filler); "Spule" only in s4
151
+ const claimMixed = ["Die Spule wurde ersetzt"];
152
+ const picked = selectEvidence(claimMixed, index, 4);
153
+ // The passage with "Spule" must rank first despite "Die" and "wurde" being ubiquitous
154
+ expect(picked[0]!.sourceId).toBe("s4");
155
+ // A claim built only from ubiquitous terms scores every passage 0
156
+ const claimFiller = ["Die wurde"];
157
+ const fillerPicked = selectEvidence(claimFiller, index, 4);
158
+ expect(fillerPicked.every((p) => p.score === 0)).toBe(true);
159
+ });
160
+
161
+ // R36, the discriminator: scoring reads the document frequencies off the
162
+ // index. Were they still rebuilt inside this call, mangling the index's map
163
+ // could not change a score, and this test would pass under the regression
164
+ // it exists to catch.
165
+ it("takes the IDF weight from the index's map instead of recomputing one per call", () => {
166
+ const index = indexSources(SOURCES);
167
+ const before = selectEvidence(["Fernabschaltung im Schaltschrank"], index, 1)[0]!.score;
168
+ expect(before).toBeGreaterThan(0);
169
+
170
+ // Claim the two distinguishing terms appear in every passage: log(N/N) = 0.
171
+ index.documentFrequency.set("fernabschalt", index.passages.length);
172
+ index.documentFrequency.set("schaltschrank", index.passages.length);
173
+ const after = selectEvidence(["Fernabschaltung im Schaltschrank"], index, 1)[0]!.score;
174
+
175
+ expect(after).toBe(0);
176
+ });
177
+
178
+ it("silences preprocessing logs when requested", () => {
179
+ const logSpy = jest.spyOn(console, "log").mockImplementation();
180
+ try {
181
+ // Calling indexSources should not emit preprocessing logs
182
+ indexSources([{ id: "s1", content: "Test content für eine Überprüfung." }]);
183
+ expect(logSpy).not.toHaveBeenCalledWith(expect.stringContaining("[EXULU] Query preprocessing"));
184
+ } finally {
185
+ logSpy.mockRestore();
186
+ }
187
+ });
188
+
189
+ it("still logs when silent is not requested", () => {
190
+ const spy = jest.spyOn(console, "log").mockImplementation(() => {});
191
+ try {
192
+ preprocessQuery("Die Steuerung meldet eine Fernabschaltung.", { enableStemming: false });
193
+ expect(spy).toHaveBeenCalled();
194
+ } finally {
195
+ spy.mockRestore();
196
+ }
197
+ });
198
+ });
@@ -0,0 +1,162 @@
1
+ //
2
+ // Why this exists: measured on NEWLIFT's live data, one turn's evidence
3
+ // averages ~89k chars (max ~600k). Sending all of it into every verification
4
+ // call would cost more than every extraction stage combined. So sources are
5
+ // sliced into overlapping passages and scored per claim with a lexical
6
+ // IDF-weighted overlap — deliberately no embedder, so a client that brings its
7
+ // own sources gets identical behaviour with no embedding spend.
8
+ import { preprocessQuery } from "@SRC/utils/query-preprocessing";
9
+ import type { ClaimCheckSource, EvidenceSnippet } from "./types";
10
+
11
+ export type IndexedPassage = {
12
+ sourceId: string;
13
+ sourceName?: string;
14
+ text: string;
15
+ /**
16
+ * The passage's distinct tokens, built ONCE at index time. Scoring only ever
17
+ * asks "does this passage contain this token", so the set is the useful
18
+ * shape; rebuilding it per claim is what made selection the most expensive
19
+ * synchronous thing in a check (see PassageIndex).
20
+ */
21
+ tokens: Set<string>;
22
+ };
23
+
24
+ /**
25
+ * Passages plus the one thing scoring needs that belongs to the SET rather
26
+ * than to any passage: how many passages each token appears in, the IDF
27
+ * denominator.
28
+ *
29
+ * Why this type exists: `selectEvidence` is called once per claim (spec §2.2),
30
+ * and it used to rebuild this map — and a Set per passage — on every call.
31
+ * Measured at production scale (541k chars of evidence → 540 passages, 200
32
+ * claims, 14 verification groups) that was 1,330 ms of synchronous
33
+ * event-loop blocking per check, against 167 ms for the per-group call it
34
+ * replaced. The process serves chat streaming for every other user and the
35
+ * global in-flight cap permits 20 concurrent checks, so the cost is not local
36
+ * to the check that pays it. Both are now computed once, with the passages.
37
+ */
38
+ export type PassageIndex = {
39
+ passages: IndexedPassage[];
40
+ /** token → number of passages containing it. */
41
+ documentFrequency: Map<string, number>;
42
+ };
43
+
44
+ /**
45
+ * Per-source hard limit. A 600k-char evidence set is never indexed whole (spec
46
+ * §4), so anything past this is NOT searched — which is only honest if the
47
+ * result says so, hence the truncation report below. Without it, a claim
48
+ * supported only in a dropped tail comes back "unsupported" and the feature
49
+ * invents a hallucination on the largest real turns.
50
+ */
51
+ export const MAX_CHARS_PER_SOURCE = 60_000;
52
+
53
+ const DEFAULTS = { passageChars: 1200, overlapChars: 200, maxCharsPerSource: MAX_CHARS_PER_SOURCE };
54
+
55
+ /** What indexing had to leave unsearched. */
56
+ export type SourceTruncation = {
57
+ /** Number of sources whose content was cut. */
58
+ sources: number;
59
+ /** Characters of source content that were never indexed. */
60
+ droppedChars: number;
61
+ /** Names (or ids) of the sources that were truncated. */
62
+ names: string[];
63
+ };
64
+
65
+ /** Stemmed content tokens (the caller dedupes into a Set). Language is detected per text. */
66
+ function tokenize(text: string): string[] {
67
+ if (!text.trim()) return [];
68
+ const { processed } = preprocessQuery(text, { enableStemming: true, detectLanguage: true, silent: true });
69
+ return processed
70
+ .toLowerCase()
71
+ .split(/[^\p{L}\p{N}]+/u)
72
+ .filter((t) => t.length >= 3);
73
+ }
74
+
75
+ export type IndexOptions = { passageChars?: number; overlapChars?: number; maxCharsPerSource?: number };
76
+
77
+ /**
78
+ * Index the sources AND report what had to be dropped, so the caller can set
79
+ * `limits.truncated` and note it. The truncation-free `indexSources` below is
80
+ * the same function for callers that cannot truncate anything (second-chance
81
+ * retrieval, which feeds it chunks, not whole documents).
82
+ */
83
+ export function indexSourcesWithLimits(
84
+ sources: ClaimCheckSource[],
85
+ opts: IndexOptions = {},
86
+ ): PassageIndex & { truncation: SourceTruncation } {
87
+ const { passageChars, overlapChars, maxCharsPerSource } = { ...DEFAULTS, ...opts };
88
+ const passages: IndexedPassage[] = [];
89
+ // IDF over passages, so a term that appears everywhere ("aufzug" in a lift
90
+ // manual) cannot outvote the one distinguishing term in the claim. Counted
91
+ // here, with the tokens in hand, rather than per scoring call.
92
+ const documentFrequency = new Map<string, number>();
93
+ const truncation: SourceTruncation = { sources: 0, droppedChars: 0, names: [] };
94
+
95
+ for (const source of sources) {
96
+ const full = source.content ?? "";
97
+ const content = full.slice(0, maxCharsPerSource);
98
+ if (full.length > content.length) {
99
+ truncation.sources += 1;
100
+ truncation.droppedChars += full.length - content.length;
101
+ // Which document, not just how many: a reader cannot act on a count.
102
+ // Using || instead of ?? to handle empty string names.
103
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
104
+ truncation.names.push(source.name || source.id);
105
+ }
106
+ if (!content.trim()) continue;
107
+
108
+ const step = Math.max(1, passageChars - overlapChars);
109
+ for (let start = 0; start < content.length; start += step) {
110
+ const text = content.slice(start, start + passageChars).trim();
111
+ if (!text) continue;
112
+ const tokens = new Set(tokenize(text));
113
+ for (const token of tokens) documentFrequency.set(token, (documentFrequency.get(token) ?? 0) + 1);
114
+ passages.push({
115
+ sourceId: source.id,
116
+ sourceName: source.name,
117
+ text,
118
+ tokens,
119
+ });
120
+ if (start + passageChars >= content.length) break;
121
+ }
122
+ }
123
+
124
+ return { passages, documentFrequency, truncation };
125
+ }
126
+
127
+ export function indexSources(sources: ClaimCheckSource[], opts: IndexOptions = {}): PassageIndex {
128
+ const { passages, documentFrequency } = indexSourcesWithLimits(sources, opts);
129
+ return { passages, documentFrequency };
130
+ }
131
+
132
+ /**
133
+ * Best `topK` passages for one claim (or a pooled set of claims). Nothing
134
+ * about the index is recomputed here — see PassageIndex for what that cost.
135
+ */
136
+ export function selectEvidence(claimTexts: string[], index: PassageIndex, topK = 4): EvidenceSnippet[] {
137
+ const { passages, documentFrequency } = index;
138
+ if (passages.length === 0) return [];
139
+
140
+ const queryTokens = new Set(claimTexts.flatMap((t) => tokenize(t)));
141
+
142
+ const scored = passages.map((passage, position) => {
143
+ let score = 0;
144
+ for (const token of queryTokens) {
145
+ if (!passage.tokens.has(token)) continue;
146
+ const df = documentFrequency.get(token) ?? passages.length;
147
+ score += Math.max(0, Math.log(passages.length / df));
148
+ }
149
+ return { passage, score, position };
150
+ });
151
+
152
+ // Stable: score desc, then original order, so an all-zero set still returns
153
+ // a deterministic fallback rather than nothing to check against.
154
+ scored.sort((a, b) => (b.score - a.score) || (a.position - b.position));
155
+
156
+ return scored.slice(0, topK).map(({ passage, score }) => ({
157
+ sourceId: passage.sourceId,
158
+ sourceName: passage.sourceName,
159
+ text: passage.text,
160
+ score: Number(score.toFixed(4)),
161
+ }));
162
+ }