@exulu/backend 5.1.0 → 5.1.1

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.
@@ -1723,7 +1723,7 @@ var ExuluTool = class _ExuluTool {
1723
1723
  if (!agent) {
1724
1724
  throw new Error("Agent not found.");
1725
1725
  }
1726
- const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-IFENSB7J.js");
1726
+ const { convertExuluToolsToAiSdkTools: convertExuluToolsToAiSdkTools2 } = await import("./convert-exulu-tools-to-ai-sdk-tools-FHFMJSD2.js");
1727
1727
  const tools = await convertExuluToolsToAiSdkTools2(
1728
1728
  [this],
1729
1729
  [],
@@ -2375,6 +2375,7 @@ function itemMatchesIdentifierToken(itemName, tokens) {
2375
2375
  const normName = normalizeFileName(itemName).toLowerCase().replace(/[^a-z0-9]/g, "");
2376
2376
  return tokens.some((t) => normName.includes(t));
2377
2377
  }
2378
+ var stripSeparators = (s) => s.toLowerCase().replace(/[-_\.\s]/g, "");
2378
2379
  function applyRewrites(question, rewrites) {
2379
2380
  const out = /* @__PURE__ */ new Set();
2380
2381
  for (const rule of rewrites) {
@@ -2387,6 +2388,8 @@ function applyRewrites(question, rewrites) {
2387
2388
  }
2388
2389
 
2389
2390
  // ee/agentic-retrieval/pipeline/prefilter.ts
2391
+ var SUPPLEMENT_MIN_TOKEN_LENGTH = 4;
2392
+ var SUPPLEMENT_BUDGET = 15;
2390
2393
  var itemCaches = {};
2391
2394
  var ensureItemsCache = async ({
2392
2395
  cacheKey,
@@ -2396,12 +2399,21 @@ var ensureItemsCache = async ({
2396
2399
  }) => {
2397
2400
  if (!itemCaches[cacheKey] || Date.now() - itemCaches[cacheKey].tsp.getTime() > 5 * 60 * 1e3 || itemCaches[cacheKey].items.length === 0) {
2398
2401
  const result = await context.getItems({ fields, filters: [] });
2399
- const normalizedItems = result.map((item) => ({
2400
- name: item.name,
2401
- id: item.id,
2402
- external_id: item.external_id,
2403
- normalized: normalize(item)
2404
- }));
2402
+ const normalizedItems = result.map((item) => {
2403
+ const normalized = normalize(item);
2404
+ return {
2405
+ name: item.name,
2406
+ id: item.id,
2407
+ external_id: item.external_id,
2408
+ normalized,
2409
+ // Separator-free form used only by the supplementary pass in
2410
+ // fuzzyPrefilter. Deliberately NOT added to the Fuse index or keys:
2411
+ // changing what Fuse scores reshuffles which items win the result cap,
2412
+ // which cost 22 regressions against 6 improvements when measured over
2413
+ // positively-rated production cases.
2414
+ stripped: stripSeparators(normalized ?? item.name ?? "")
2415
+ };
2416
+ });
2405
2417
  itemCaches[cacheKey] = {
2406
2418
  cacheKey,
2407
2419
  items: normalizedItems,
@@ -2445,7 +2457,8 @@ async function fuzzyPrefilter({
2445
2457
  fields,
2446
2458
  normalize,
2447
2459
  cutoff = DEFAULT_PREFILTER_CUTOFF,
2448
- limit
2460
+ limit,
2461
+ supplementSeparatorVariants = false
2449
2462
  }) {
2450
2463
  const cache2 = await ensureItemsCache({ cacheKey, context, fields, normalize });
2451
2464
  if (!relevantKeywords?.length) {
@@ -2536,6 +2549,44 @@ async function fuzzyPrefilter({
2536
2549
  name: result2.item.name,
2537
2550
  id: result2.item.id
2538
2551
  }));
2552
+ const supplementTokens = !supplementSeparatorVariants ? [] : [
2553
+ ...new Set(
2554
+ uniqueKeywords.filter((k) => /[-_.]/.test(k)).map((k) => stripSeparators(k)).filter((t) => t.length >= SUPPLEMENT_MIN_TOKEN_LENGTH)
2555
+ )
2556
+ ].sort((a, b) => b.length - a.length);
2557
+ if (supplementTokens.length > 0) {
2558
+ const seen = new Set(prefiltered.map((p) => p.id));
2559
+ const candidates = cache2.items.filter(
2560
+ (item) => item.id && !seen.has(item.id) && supplementTokens.some((t) => (item.stripped ?? "").includes(t))
2561
+ ).map((item, idx) => {
2562
+ const nameStripped = stripSeparators(item.name ?? "");
2563
+ return {
2564
+ item,
2565
+ idx,
2566
+ nameMatch: supplementTokens.some((t) => nameStripped.includes(t)) ? 0 : 1,
2567
+ nameLength: (item.name ?? "").length
2568
+ };
2569
+ }).sort(
2570
+ (a, b) => a.nameMatch - b.nameMatch || a.nameLength - b.nameLength || a.idx - b.idx
2571
+ );
2572
+ const supplement = [];
2573
+ for (const { item } of candidates) {
2574
+ if (supplement.length >= SUPPLEMENT_BUDGET) break;
2575
+ if (!item.id || seen.has(item.id)) continue;
2576
+ seen.add(item.id);
2577
+ supplement.push({
2578
+ key: item.external_id ?? item.id,
2579
+ name: item.name ?? item.external_id ?? item.id,
2580
+ id: item.id
2581
+ });
2582
+ }
2583
+ if (supplement.length > 0) {
2584
+ console.log(
2585
+ `[EXULU pipeline] fuzzyPrefilter: +${supplement.length} separator-insensitive supplement(s) for [${supplementTokens.join(", ")}]`
2586
+ );
2587
+ prefiltered.push(...supplement);
2588
+ }
2589
+ }
2539
2590
  console.log(
2540
2591
  `[EXULU pipeline] fuzzyPrefilter: ${prefiltered.length} result(s) for [${uniqueKeywords.join(", ")}]`
2541
2592
  );
@@ -2594,7 +2645,10 @@ async function resolveIdentifierPins({
2594
2645
  const matched = set.strategy === "exact" ? await exactTokenPrefilter({ ...common, tokens: output.matches }) : await fuzzyPrefilter({
2595
2646
  ...common,
2596
2647
  relevantKeywords: output.matches,
2597
- cutoff: DEFAULT_PREFILTER_CUTOFF
2648
+ cutoff: DEFAULT_PREFILTER_CUTOFF,
2649
+ // Identifier pins are a hard id-whitelist over filenames,
2650
+ // which is exactly the case the supplement exists for.
2651
+ supplementSeparatorVariants: true
2598
2652
  });
2599
2653
  if (!matched.length) return;
2600
2654
  const target = pinsByContext.get(ctxId) ?? /* @__PURE__ */ new Set();
@@ -2,7 +2,7 @@ import "dotenv/config";
2
2
  import {
3
3
  convertExuluToolsToAiSdkTools,
4
4
  hydrateVariables
5
- } from "./chunk-MUR4WZLA.js";
5
+ } from "./chunk-UXHMHM4E.js";
6
6
  import "./chunk-4PDWNVNT.js";
7
7
  export {
8
8
  convertExuluToolsToAiSdkTools,
package/dist/index.cjs CHANGED
@@ -14048,7 +14048,7 @@ function applyRewrites(question, rewrites) {
14048
14048
  }
14049
14049
  return [...out];
14050
14050
  }
14051
- var normalizeFileName;
14051
+ var normalizeFileName, stripSeparators;
14052
14052
  var init_text_utils = __esm({
14053
14053
  "ee/agentic-retrieval/pipeline/text-utils.ts"() {
14054
14054
  "use strict";
@@ -14064,6 +14064,7 @@ var init_text_utils = __esm({
14064
14064
  normalized = normalized.replace(/ +/g, " ").trim();
14065
14065
  return normalized;
14066
14066
  };
14067
+ stripSeparators = (s) => s.toLowerCase().replace(/[-_\.\s]/g, "");
14067
14068
  }
14068
14069
  });
14069
14070
 
@@ -14102,7 +14103,8 @@ async function fuzzyPrefilter({
14102
14103
  fields,
14103
14104
  normalize,
14104
14105
  cutoff = DEFAULT_PREFILTER_CUTOFF,
14105
- limit
14106
+ limit,
14107
+ supplementSeparatorVariants = false
14106
14108
  }) {
14107
14109
  const cache2 = await ensureItemsCache({ cacheKey, context, fields, normalize });
14108
14110
  if (!relevantKeywords?.length) {
@@ -14193,6 +14195,44 @@ async function fuzzyPrefilter({
14193
14195
  name: result2.item.name,
14194
14196
  id: result2.item.id
14195
14197
  }));
14198
+ const supplementTokens = !supplementSeparatorVariants ? [] : [
14199
+ ...new Set(
14200
+ uniqueKeywords.filter((k) => /[-_.]/.test(k)).map((k) => stripSeparators(k)).filter((t) => t.length >= SUPPLEMENT_MIN_TOKEN_LENGTH)
14201
+ )
14202
+ ].sort((a, b) => b.length - a.length);
14203
+ if (supplementTokens.length > 0) {
14204
+ const seen = new Set(prefiltered.map((p) => p.id));
14205
+ const candidates = cache2.items.filter(
14206
+ (item) => item.id && !seen.has(item.id) && supplementTokens.some((t) => (item.stripped ?? "").includes(t))
14207
+ ).map((item, idx) => {
14208
+ const nameStripped = stripSeparators(item.name ?? "");
14209
+ return {
14210
+ item,
14211
+ idx,
14212
+ nameMatch: supplementTokens.some((t) => nameStripped.includes(t)) ? 0 : 1,
14213
+ nameLength: (item.name ?? "").length
14214
+ };
14215
+ }).sort(
14216
+ (a, b) => a.nameMatch - b.nameMatch || a.nameLength - b.nameLength || a.idx - b.idx
14217
+ );
14218
+ const supplement = [];
14219
+ for (const { item } of candidates) {
14220
+ if (supplement.length >= SUPPLEMENT_BUDGET) break;
14221
+ if (!item.id || seen.has(item.id)) continue;
14222
+ seen.add(item.id);
14223
+ supplement.push({
14224
+ key: item.external_id ?? item.id,
14225
+ name: item.name ?? item.external_id ?? item.id,
14226
+ id: item.id
14227
+ });
14228
+ }
14229
+ if (supplement.length > 0) {
14230
+ console.log(
14231
+ `[EXULU pipeline] fuzzyPrefilter: +${supplement.length} separator-insensitive supplement(s) for [${supplementTokens.join(", ")}]`
14232
+ );
14233
+ prefiltered.push(...supplement);
14234
+ }
14235
+ }
14196
14236
  console.log(
14197
14237
  `[EXULU pipeline] fuzzyPrefilter: ${prefiltered.length} result(s) for [${uniqueKeywords.join(", ")}]`
14198
14238
  );
@@ -14236,7 +14276,10 @@ async function resolveIdentifierPins({
14236
14276
  const matched = set.strategy === "exact" ? await exactTokenPrefilter({ ...common, tokens: output.matches }) : await fuzzyPrefilter({
14237
14277
  ...common,
14238
14278
  relevantKeywords: output.matches,
14239
- cutoff: DEFAULT_PREFILTER_CUTOFF
14279
+ cutoff: DEFAULT_PREFILTER_CUTOFF,
14280
+ // Identifier pins are a hard id-whitelist over filenames,
14281
+ // which is exactly the case the supplement exists for.
14282
+ supplementSeparatorVariants: true
14240
14283
  });
14241
14284
  if (!matched.length) return;
14242
14285
  const target = pinsByContext.get(ctxId) ?? /* @__PURE__ */ new Set();
@@ -14262,7 +14305,7 @@ async function resolveIdentifierPins({
14262
14305
  );
14263
14306
  return { pinsByContext, exactPinsByContext, steps };
14264
14307
  }
14265
- var import_fuse, import_zod12, itemCaches, ensureItemsCache, FUZZY_EXTRACTION_PROMPT, EXACT_EXTRACTION_PROMPT;
14308
+ var import_fuse, import_zod12, SUPPLEMENT_MIN_TOKEN_LENGTH, SUPPLEMENT_BUDGET, itemCaches, ensureItemsCache, FUZZY_EXTRACTION_PROMPT, EXACT_EXTRACTION_PROMPT;
14266
14309
  var init_prefilter = __esm({
14267
14310
  "ee/agentic-retrieval/pipeline/prefilter.ts"() {
14268
14311
  "use strict";
@@ -14272,6 +14315,8 @@ var init_prefilter = __esm({
14272
14315
  init_micro_call();
14273
14316
  init_text_utils();
14274
14317
  init_config3();
14318
+ SUPPLEMENT_MIN_TOKEN_LENGTH = 4;
14319
+ SUPPLEMENT_BUDGET = 15;
14275
14320
  itemCaches = {};
14276
14321
  ensureItemsCache = async ({
14277
14322
  cacheKey,
@@ -14281,12 +14326,21 @@ var init_prefilter = __esm({
14281
14326
  }) => {
14282
14327
  if (!itemCaches[cacheKey] || Date.now() - itemCaches[cacheKey].tsp.getTime() > 5 * 60 * 1e3 || itemCaches[cacheKey].items.length === 0) {
14283
14328
  const result = await context.getItems({ fields, filters: [] });
14284
- const normalizedItems = result.map((item) => ({
14285
- name: item.name,
14286
- id: item.id,
14287
- external_id: item.external_id,
14288
- normalized: normalize(item)
14289
- }));
14329
+ const normalizedItems = result.map((item) => {
14330
+ const normalized = normalize(item);
14331
+ return {
14332
+ name: item.name,
14333
+ id: item.id,
14334
+ external_id: item.external_id,
14335
+ normalized,
14336
+ // Separator-free form used only by the supplementary pass in
14337
+ // fuzzyPrefilter. Deliberately NOT added to the Fuse index or keys:
14338
+ // changing what Fuse scores reshuffles which items win the result cap,
14339
+ // which cost 22 regressions against 6 improvements when measured over
14340
+ // positively-rated production cases.
14341
+ stripped: stripSeparators(normalized ?? item.name ?? "")
14342
+ };
14343
+ });
14290
14344
  itemCaches[cacheKey] = {
14291
14345
  cacheKey,
14292
14346
  items: normalizedItems,
@@ -20148,6 +20202,18 @@ async function recallMemories({ agent, contexts, query, user, db: db2, previousU
20148
20202
  return { collector, memoryItems: chunks, promptBlock: buildMemoryPromptBlock(collector.list()) };
20149
20203
  }
20150
20204
 
20205
+ // src/exulu/public-surface.ts
20206
+ init_cjs_shims();
20207
+ var PUBLIC_SURFACE_HEADER = "x-public-surface";
20208
+ function isPublicSurface(req) {
20209
+ const raw = req?.headers?.[PUBLIC_SURFACE_HEADER];
20210
+ const value = Array.isArray(raw) ? raw[0] : raw;
20211
+ return value === "1" || value === "true";
20212
+ }
20213
+ function treatAsGuest(req, user) {
20214
+ return isPublicSurface(req) || !user?.id;
20215
+ }
20216
+
20151
20217
  // src/exulu/generate-stream.ts
20152
20218
  init_decisions();
20153
20219
 
@@ -20384,7 +20450,8 @@ var generateSync = async ({
20384
20450
  }
20385
20451
  const { db: memoryDb } = await postgresClient();
20386
20452
  const currentAsUiMessage = { id: "current", role: "user", parts: query ? [{ type: "text", text: query }] : [] };
20387
- const memoryRecall = await recallMemories({ agent, contexts, query, user, db: memoryDb, previousUserTurns: previousUserTexts([...messages, currentAsUiMessage]) });
20453
+ const recallUser = isPublicSurface(req) ? void 0 : user;
20454
+ const memoryRecall = await recallMemories({ agent, contexts, query, user: recallUser, db: memoryDb, previousUserTurns: previousUserTexts([...messages, currentAsUiMessage]) });
20388
20455
  const memoryContext = memoryRecall.promptBlock;
20389
20456
  const memoryItems = memoryRecall.memoryItems;
20390
20457
  const personalizationInformation = exuluConfig?.privacy?.systemPromptPersonalization !== false ? `
@@ -20723,7 +20790,8 @@ var generateStream = async ({
20723
20790
  });
20724
20791
  }
20725
20792
  const { db: memoryDb } = await postgresClient();
20726
- const memoryRecall = await recallMemories({ agent, contexts, query, user, db: memoryDb, previousUserTurns: previousUserTexts(messages) });
20793
+ const recallUser = isPublicSurface(req) ? void 0 : user;
20794
+ const memoryRecall = await recallMemories({ agent, contexts, query, user: recallUser, db: memoryDb, previousUserTurns: previousUserTexts(messages) });
20727
20795
  const memoryContext = memoryRecall.promptBlock;
20728
20796
  const memoryItems = memoryRecall.memoryItems;
20729
20797
  messages = messages.filter(
@@ -31063,7 +31131,9 @@ ${customInstructions}` : agent.instructions,
31063
31131
  if (part.type === "finish") {
31064
31132
  return {
31065
31133
  ...finishTurnMetadata({ totalUsage: part.totalUsage, startedAt: turnStartedAt }),
31066
- ...recalledMemoriesMetadata({ recall: result.recall, agent, isGuest: !user?.id })
31134
+ // The public surface is a guest surface even for a signed-in visitor:
31135
+ // the page renders in guest mode, so the data has to follow.
31136
+ ...recalledMemoriesMetadata({ recall: result.recall, agent, isGuest: treatAsGuest(req, user) })
31067
31137
  };
31068
31138
  }
31069
31139
  return void 0;
package/dist/index.js CHANGED
@@ -180,7 +180,7 @@ import {
180
180
  willEmbedOnQueue,
181
181
  withRetry,
182
182
  workflowTemplatesSchema
183
- } from "./chunk-MUR4WZLA.js";
183
+ } from "./chunk-UXHMHM4E.js";
184
184
  import {
185
185
  LiteLLMAdminError,
186
186
  findLiteLLMModel,
@@ -3878,6 +3878,17 @@ async function recallMemories({ agent, contexts, query, user, db, previousUserTu
3878
3878
  return { collector, memoryItems: chunks, promptBlock: buildMemoryPromptBlock(collector.list()) };
3879
3879
  }
3880
3880
 
3881
+ // src/exulu/public-surface.ts
3882
+ var PUBLIC_SURFACE_HEADER = "x-public-surface";
3883
+ function isPublicSurface(req) {
3884
+ const raw = req?.headers?.[PUBLIC_SURFACE_HEADER];
3885
+ const value = Array.isArray(raw) ? raw[0] : raw;
3886
+ return value === "1" || value === "true";
3887
+ }
3888
+ function treatAsGuest(req, user) {
3889
+ return isPublicSurface(req) || !user?.id;
3890
+ }
3891
+
3881
3892
  // src/exulu/memory/usage.ts
3882
3893
  function usageRows(input) {
3883
3894
  const memories = input.recall?.list() ?? [];
@@ -4110,7 +4121,8 @@ var generateSync = async ({
4110
4121
  }
4111
4122
  const { db: memoryDb } = await postgresClient();
4112
4123
  const currentAsUiMessage = { id: "current", role: "user", parts: query ? [{ type: "text", text: query }] : [] };
4113
- const memoryRecall = await recallMemories({ agent, contexts, query, user, db: memoryDb, previousUserTurns: previousUserTexts([...messages, currentAsUiMessage]) });
4124
+ const recallUser = isPublicSurface(req) ? void 0 : user;
4125
+ const memoryRecall = await recallMemories({ agent, contexts, query, user: recallUser, db: memoryDb, previousUserTurns: previousUserTexts([...messages, currentAsUiMessage]) });
4114
4126
  const memoryContext = memoryRecall.promptBlock;
4115
4127
  const memoryItems = memoryRecall.memoryItems;
4116
4128
  const personalizationInformation = exuluConfig?.privacy?.systemPromptPersonalization !== false ? `
@@ -4449,7 +4461,8 @@ var generateStream = async ({
4449
4461
  });
4450
4462
  }
4451
4463
  const { db: memoryDb } = await postgresClient();
4452
- const memoryRecall = await recallMemories({ agent, contexts, query, user, db: memoryDb, previousUserTurns: previousUserTexts(messages) });
4464
+ const recallUser = isPublicSurface(req) ? void 0 : user;
4465
+ const memoryRecall = await recallMemories({ agent, contexts, query, user: recallUser, db: memoryDb, previousUserTurns: previousUserTexts(messages) });
4453
4466
  const memoryContext = memoryRecall.promptBlock;
4454
4467
  const memoryItems = memoryRecall.memoryItems;
4455
4468
  messages = messages.filter(
@@ -14590,7 +14603,9 @@ ${customInstructions}` : agent.instructions,
14590
14603
  if (part.type === "finish") {
14591
14604
  return {
14592
14605
  ...finishTurnMetadata({ totalUsage: part.totalUsage, startedAt: turnStartedAt }),
14593
- ...recalledMemoriesMetadata({ recall: result.recall, agent, isGuest: !user?.id })
14606
+ // The public surface is a guest surface even for a signed-in visitor:
14607
+ // the page renders in guest mode, so the data has to follow.
14608
+ ...recalledMemoriesMetadata({ recall: result.recall, agent, isGuest: treatAsGuest(req, user) })
14594
14609
  };
14595
14610
  }
14596
14611
  return void 0;
@@ -46,6 +46,129 @@ describe("fuzzyPrefilter", () => {
46
46
  });
47
47
  });
48
48
 
49
+ describe("fuzzyPrefilter separator handling", () => {
50
+ // Real NEWLIFT shape: the FST-2XT *handbooks* spell the product without a
51
+ // hyphen (hb_FST2XT-XTs_...), while brochures and certificates spell it with
52
+ // one. A question says "FST-2XT", so that is what the extractor emits. With
53
+ // more hyphenated files than the 30-result cap, an unhyphenated handbook has
54
+ // to survive the rescorer's match-ratio penalty to be pinned at all.
55
+ const decoys = Array.from({ length: 34 }, (_, i) => ({
56
+ id: `br${i}`,
57
+ name: `br_FST-2XT_brochure_${i}.pdf`,
58
+ external_id: `/b/br_FST-2XT_brochure_${i}.pdf`,
59
+ }));
60
+ const handbook = {
61
+ id: "hb",
62
+ name: "hb_FST2XT-XTs_2017-11_de.pdf",
63
+ external_id: "/b/hb_FST2XT-XTs_2017-11_de.pdf",
64
+ };
65
+ const newliftCtx = { id: "tech", getItems: jest.fn(async () => [...decoys, handbook]) };
66
+
67
+ it("pins an unhyphenated handbook despite a hyphenated identifier and a full result cap", async () => {
68
+ const r = await fuzzyPrefilter({
69
+ cacheKey: "sep1", relevantKeywords: ["FST-2XT"], context: newliftCtx,
70
+ fields: ["name", "id", "external_id"], normalize: (i) => i.external_id,
71
+ supplementSeparatorVariants: true,
72
+ });
73
+ expect(r.map((x) => x.id)).toContain("hb");
74
+ });
75
+ });
76
+
77
+ describe("fuzzyPrefilter supplement ordering", () => {
78
+ // `normalized` carries the whole storage path, and NEWLIFT files the product's
79
+ // documents under a `/FST/FST-2XT/` folder — so every unrelated file in that
80
+ // folder matches the identifier just as well as the handbook does. Taking the
81
+ // supplement in corpus order therefore fills the budget with incidental files
82
+ // (observed in production: Bosch-FWMaterialfahrt.pdf, spsrules.txt) and drops
83
+ // the handbook. A filename match has to outrank a path-only match.
84
+ const brochures = Array.from({ length: 34 }, (_, i) => ({
85
+ id: `br${i}`,
86
+ name: `br_FST-2XT_brochure_${i}.pdf`,
87
+ external_id: `/Techdoc/FST/FST-2XT/br_FST-2XT_brochure_${i}.pdf`,
88
+ }));
89
+ const pathOnly = Array.from({ length: 25 }, (_, i) => ({
90
+ id: `path${i}`,
91
+ name: `unrelated_doc_${i}.pdf`,
92
+ external_id: `/Techdoc/FST/FST-2XT/unrelated_doc_${i}.pdf`,
93
+ }));
94
+ const handbook = {
95
+ id: "hb",
96
+ name: "hb_FST2XT-XTs_2017-11_de.pdf",
97
+ external_id: "/Techdoc/FST/FST-2XT/hb_FST2XT-XTs_2017-11_de.pdf",
98
+ };
99
+ // handbook last, so only relevance ordering can keep it within the budget
100
+ const ctxRel = {
101
+ id: "tech",
102
+ getItems: jest.fn(async () => [...brochures, ...pathOnly, handbook]),
103
+ };
104
+
105
+ it("prefers a filename match over path-only matches when the budget is tight", async () => {
106
+ const r = await fuzzyPrefilter({
107
+ cacheKey: "ord1", relevantKeywords: ["FST-2XT"], context: ctxRel,
108
+ fields: ["name", "id", "external_id"], normalize: (i) => i.external_id,
109
+ supplementSeparatorVariants: true,
110
+ });
111
+ expect(r.map((x) => x.id)).toContain("hb");
112
+ });
113
+ });
114
+
115
+ describe("fuzzyPrefilter supplement scope and degenerate corpora", () => {
116
+ const brochures = Array.from({ length: 34 }, (_, i) => ({
117
+ id: `br${i}`,
118
+ name: `br_FST-2XT_brochure_${i}.pdf`,
119
+ external_id: `/Techdoc/FST/FST-2XT/br_FST-2XT_brochure_${i}.pdf`,
120
+ }));
121
+ const handbook = {
122
+ id: "hb",
123
+ name: "hb_FST2XT-XTs_2017-11_de.pdf",
124
+ external_id: "/Techdoc/FST/FST-2XT/hb_FST2XT-XTs_2017-11_de.pdf",
125
+ };
126
+
127
+ it("leaves the result untouched unless the caller opts in", async () => {
128
+ // The conversations keyword prefilter (search.ts) matches ticket text, not
129
+ // filenames, so it must not inherit filename-shaped supplementing.
130
+ const ctxNoOptIn = { id: "tech", getItems: jest.fn(async () => [...brochures, handbook]) };
131
+ const r = await fuzzyPrefilter({
132
+ cacheKey: "noopt", relevantKeywords: ["FST-2XT"], context: ctxNoOptIn,
133
+ fields: ["name", "id", "external_id"], normalize: (i) => i.external_id,
134
+ });
135
+ expect(r).toHaveLength(30);
136
+ expect(r.map((x) => x.id)).not.toContain("hb");
137
+ });
138
+
139
+ it("adds nothing when external_id carries no filename text", async () => {
140
+ // Other tenants store an opaque id (uuid / int / "9998-31938") instead of a
141
+ // path, so there is nothing for a separator-free token to match.
142
+ const opaque = [
143
+ ...brochures.map((b, i) => ({ ...b, external_id: `550e8400-e29b-41d4-a716-${String(i).padStart(12, "0")}` })),
144
+ { ...handbook, external_id: "550e8400-e29b-41d4-a716-446655449999" },
145
+ ];
146
+ const ctxOpaque = { id: "tickets", getItems: jest.fn(async () => opaque) };
147
+ const r = await fuzzyPrefilter({
148
+ cacheKey: "opaque", relevantKeywords: ["FST-2XT"], context: ctxOpaque,
149
+ fields: ["name", "id", "external_id"], normalize: (i) => i.external_id,
150
+ supplementSeparatorVariants: true,
151
+ });
152
+ // no crash, and the opaque corpus yields no separator-variant candidates
153
+ expect(r.length).toBeLessThanOrEqual(30);
154
+ });
155
+
156
+ it("survives items with no name at all", async () => {
157
+ const nameless = [
158
+ ...brochures,
159
+ { id: "nameless", name: undefined as any, external_id: "/Techdoc/FST/FST-2XT/x.pdf" },
160
+ ];
161
+ const ctxNameless = { id: "tech", getItems: jest.fn(async () => nameless) };
162
+ await expect(
163
+ fuzzyPrefilter({
164
+ cacheKey: "nameless", relevantKeywords: ["FST-2XT"], context: ctxNameless,
165
+ fields: ["name", "id", "external_id"], normalize: (i) => i.external_id,
166
+ supplementSeparatorVariants: true,
167
+ }),
168
+ ).resolves.toBeDefined();
169
+ });
170
+ });
171
+
49
172
  describe("resolveIdentifierPins", () => {
50
173
  it("runs one extraction call per identifier set and routes pins to the set's contexts", async () => {
51
174
  (generateText as jest.Mock).mockResolvedValue({
@@ -1,7 +1,7 @@
1
1
  import Fuse from "fuse.js";
2
2
  import { z } from "zod";
3
3
  import { microCall } from "./micro-call";
4
- import { normalizeFileName } from "./text-utils";
4
+ import { normalizeFileName, stripSeparators } from "./text-utils";
5
5
  import { DEFAULT_PREFILTER_CUTOFF, type IdentifierSet, type KbKind } from "./config";
6
6
  import type { PhaseStep } from "./types";
7
7
 
@@ -17,11 +17,17 @@ export type PrefilteredResult = {
17
17
 
18
18
  type ItemsCache = {
19
19
  fuseIndex: any;
20
- items: { name?: string; id?: string; external_id?: string; normalized?: string }[];
20
+ items: { name?: string; id?: string; external_id?: string; normalized?: string; stripped?: string }[];
21
21
  tsp: Date;
22
22
  cacheKey: string;
23
23
  };
24
24
 
25
+ /** Shortest separator-free token eligible for the supplementary pass. Below
26
+ * this, a token matches too much of the corpus to be a useful pin. */
27
+ const SUPPLEMENT_MIN_TOKEN_LENGTH = 4;
28
+ /** Most items the supplementary pass may add on top of the primary result. */
29
+ const SUPPLEMENT_BUDGET = 15;
30
+
25
31
  // ---------------------------------------------------------------------------
26
32
  // Cache
27
33
  // ---------------------------------------------------------------------------
@@ -50,12 +56,21 @@ const ensureItemsCache = async ({
50
56
  ) {
51
57
  const result = await context.getItems({ fields, filters: [] });
52
58
 
53
- const normalizedItems = result.map((item: any) => ({
54
- name: item.name,
55
- id: item.id,
56
- external_id: item.external_id,
57
- normalized: normalize(item),
58
- }));
59
+ const normalizedItems = result.map((item: any) => {
60
+ const normalized = normalize(item);
61
+ return {
62
+ name: item.name,
63
+ id: item.id,
64
+ external_id: item.external_id,
65
+ normalized,
66
+ // Separator-free form used only by the supplementary pass in
67
+ // fuzzyPrefilter. Deliberately NOT added to the Fuse index or keys:
68
+ // changing what Fuse scores reshuffles which items win the result cap,
69
+ // which cost 22 regressions against 6 improvements when measured over
70
+ // positively-rated production cases.
71
+ stripped: stripSeparators(normalized ?? item.name ?? ""),
72
+ };
73
+ });
59
74
 
60
75
  itemCaches[cacheKey] = {
61
76
  cacheKey,
@@ -137,6 +152,7 @@ export async function fuzzyPrefilter({
137
152
  normalize,
138
153
  cutoff = DEFAULT_PREFILTER_CUTOFF,
139
154
  limit,
155
+ supplementSeparatorVariants = false,
140
156
  }: {
141
157
  cacheKey: string;
142
158
  relevantKeywords: string[];
@@ -146,6 +162,15 @@ export async function fuzzyPrefilter({
146
162
  normalize: (item: any) => string | undefined;
147
163
  cutoff?: number;
148
164
  limit?: number;
165
+ /**
166
+ * Opt in to the separator-insensitive supplement below. Only meaningful when
167
+ * `normalize` yields FILENAME-ish text: it exists because a hyphenated
168
+ * identifier scores badly against an unhyphenated filename. Callers that
169
+ * normalize to prose — the conversations keyword prefilter joins a ticket's
170
+ * name and description — get nothing useful from it, so it stays off by
171
+ * default rather than silently widening every prefilter in the pipeline.
172
+ */
173
+ supplementSeparatorVariants?: boolean;
149
174
  }): Promise<PrefilteredResult[]> {
150
175
  const cache = await ensureItemsCache({ cacheKey, context, fields, normalize });
151
176
 
@@ -264,6 +289,82 @@ export async function fuzzyPrefilter({
264
289
  id: result.item.id,
265
290
  }));
266
291
 
292
+ // ---------------------------------------------------------------------
293
+ // Supplementary separator-insensitive pass
294
+ // ---------------------------------------------------------------------
295
+ // Fuse scores an identifier's punctuation, not just its letters: "FST-2XT"
296
+ // scores ~0.0001 against `br_FST-2XT_2019-10_de.pdf` but ~0.02 against
297
+ // `hb_FST2XT-XTs_2017-11_de.pdf`. NEWLIFT's brochures carry the hyphen and
298
+ // its handbooks do not, so the brochures filled the cap above and the
299
+ // handbooks — which hold the error-code tables — were dropped entirely.
300
+ // Because identifier pins are a hard id-whitelist rather than a boost, that
301
+ // made their content unreachable no matter how the model phrased the query.
302
+ //
303
+ // This pass is strictly ADDITIVE: it never reorders or displaces a primary
304
+ // hit, so no pin that resolved before can be lost. Only tokens that actually
305
+ // CONTAIN a separator can be mismatched this way, so only those are
306
+ // supplemented — a plain token like "FST" is already scored correctly and
307
+ // supplementing it would match most of the corpus.
308
+ const supplementTokens = !supplementSeparatorVariants
309
+ ? []
310
+ : [
311
+ ...new Set(
312
+ uniqueKeywords
313
+ .filter((k) => /[-_.]/.test(k))
314
+ .map((k) => stripSeparators(k))
315
+ .filter((t) => t.length >= SUPPLEMENT_MIN_TOKEN_LENGTH),
316
+ ),
317
+ ].sort((a, b) => b.length - a.length); // most specific first
318
+
319
+ if (supplementTokens.length > 0) {
320
+ const seen = new Set(prefiltered.map((p) => p.id));
321
+ // `normalized` is the full storage path, and NEWLIFT files a product's
322
+ // documents under a folder named after it (`/FST/FST-2XT/...`), so every
323
+ // incidental file in that folder matches the identifier as well as the
324
+ // handbook does. Rank a match in the FILENAME above a path-only match, then
325
+ // prefer the shorter name (the more specific document), before falling back
326
+ // to corpus order — otherwise the budget fills with whatever happens to be
327
+ // stored alongside.
328
+ const candidates = cache.items
329
+ .filter(
330
+ (item) =>
331
+ item.id &&
332
+ !seen.has(item.id) &&
333
+ supplementTokens.some((t) => (item.stripped ?? "").includes(t)),
334
+ )
335
+ .map((item, idx) => {
336
+ const nameStripped = stripSeparators(item.name ?? "");
337
+ return {
338
+ item,
339
+ idx,
340
+ nameMatch: supplementTokens.some((t) => nameStripped.includes(t)) ? 0 : 1,
341
+ nameLength: (item.name ?? "").length,
342
+ };
343
+ })
344
+ .sort(
345
+ (a, b) =>
346
+ a.nameMatch - b.nameMatch || a.nameLength - b.nameLength || a.idx - b.idx,
347
+ );
348
+
349
+ const supplement: PrefilteredResult[] = [];
350
+ for (const { item } of candidates) {
351
+ if (supplement.length >= SUPPLEMENT_BUDGET) break;
352
+ if (!item.id || seen.has(item.id)) continue;
353
+ seen.add(item.id);
354
+ supplement.push({
355
+ key: item.external_id ?? item.id,
356
+ name: item.name ?? item.external_id ?? item.id,
357
+ id: item.id,
358
+ });
359
+ }
360
+ if (supplement.length > 0) {
361
+ console.log(
362
+ `[EXULU pipeline] fuzzyPrefilter: +${supplement.length} separator-insensitive supplement(s) for [${supplementTokens.join(", ")}]`,
363
+ );
364
+ prefiltered.push(...supplement);
365
+ }
366
+ }
367
+
267
368
  console.log(
268
369
  `[EXULU pipeline] fuzzyPrefilter: ${prefiltered.length} result(s) for [${uniqueKeywords.join(", ")}]`,
269
370
  );
@@ -352,6 +453,9 @@ export async function resolveIdentifierPins({
352
453
  ...common,
353
454
  relevantKeywords: output.matches!,
354
455
  cutoff: DEFAULT_PREFILTER_CUTOFF,
456
+ // Identifier pins are a hard id-whitelist over filenames,
457
+ // which is exactly the case the supplement exists for.
458
+ supplementSeparatorVariants: true,
355
459
  });
356
460
  if (!matched.length) return;
357
461
  const target = pinsByContext.get(ctxId) ?? new Set<string>();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "5.1.0",
4
+ "version": "5.1.1",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {