@exulu/backend 4.3.3 → 5.1.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.
@@ -96,6 +96,21 @@ describe("project_search option", () => {
96
96
  });
97
97
  });
98
98
 
99
+ describe("show_sources_to_external_users option", () => {
100
+ it("defaults to true when absent or empty (empty string = backend default)", () => {
101
+ expect(parsePipelineConfig({}).showSourcesToExternalUsers).toBe(true);
102
+ expect(parsePipelineConfig(undefined).showSourcesToExternalUsers).toBe(true);
103
+ expect(parsePipelineConfig({ show_sources_to_external_users: "" }).showSourcesToExternalUsers).toBe(true);
104
+ });
105
+
106
+ it("parses explicit values", () => {
107
+ expect(parsePipelineConfig({ show_sources_to_external_users: "false" }).showSourcesToExternalUsers).toBe(false);
108
+ expect(parsePipelineConfig({ show_sources_to_external_users: false }).showSourcesToExternalUsers).toBe(false);
109
+ expect(parsePipelineConfig({ show_sources_to_external_users: "true" }).showSourcesToExternalUsers).toBe(true);
110
+ expect(parsePipelineConfig({ show_sources_to_external_users: true }).showSourcesToExternalUsers).toBe(true);
111
+ });
112
+ });
113
+
99
114
  describe("tuning.engine — the per-agent switch between the v1 flow and the parallel v2 flow", () => {
100
115
  it("defaults to v1 so existing agents keep today's behaviour", () => {
101
116
  expect(parsePipelineConfig({ tuning: '{"topK": 8}' }).tuning.engine).toBe("v1");
@@ -86,6 +86,8 @@ export type PipelineConfig = {
86
86
  logging: boolean;
87
87
  /** Search items attached to the chat's project as an additional source. Default true. */
88
88
  projectSearch: boolean;
89
+ /** Show source references (item names, IDs, chunk info) to external users and guests. When false, sources are hidden. Default true. */
90
+ showSourcesToExternalUsers: boolean;
89
91
  utilityModel: string;
90
92
  knowledgeBases: Record<string, KbProfile>;
91
93
  routing: z.infer<typeof routingSchema>;
@@ -153,6 +155,10 @@ export function parsePipelineConfig(raw?: Record<string, unknown>): PipelineConf
153
155
  r["project_search"] === undefined || r["project_search"] === ""
154
156
  ? true
155
157
  : boolVal(r["project_search"]),
158
+ showSourcesToExternalUsers:
159
+ r["show_sources_to_external_users"] === undefined || r["show_sources_to_external_users"] === ""
160
+ ? true
161
+ : boolVal(r["show_sources_to_external_users"]),
156
162
  utilityModel: strVal(r["utility_model"], ""),
157
163
  knowledgeBases: jsonVal("knowledge_bases", knowledgeBasesSchema, r["knowledge_bases"]),
158
164
  routing: jsonVal("routing", routingSchema, r["routing"]),
@@ -37,7 +37,8 @@ describe("createAgenticRetrievalTool", () => {
37
37
  const names = tool.config.map((c) => c.name).sort();
38
38
  expect(names).toEqual([
39
39
  "instructions", "knowledge_bases", "logging", "managed_context", "memory",
40
- "max_steps", "project_search", "require_preselected_contexts", "reranker", "routing", "tuning", "utility_model", "vocabulary",
40
+ "max_steps", "project_search", "require_preselected_contexts", "reranker",
41
+ "routing", "show_sources_to_external_users", "tuning", "utility_model", "vocabulary",
41
42
  ].sort());
42
43
  expect(tool.config.filter((c) => c.type === "json").map((c) => c.name).sort())
43
44
  .toEqual(["knowledge_bases", "memory", "routing", "tuning", "vocabulary"].sort());
@@ -109,7 +110,13 @@ describe("createAgenticRetrievalTool", () => {
109
110
 
110
111
  describe("payload deduplication", () => {
111
112
  it("strips chunk_content from step chunks in the serialized payload; top-level keeps it", async () => {
113
+ // Memory chunks are no longer copied into the top-level `chunks` (spec §3.1,
114
+ // "recall once" — the model already holds them via the system prompt), so the
115
+ // memory step here only exercises the per-step content-stripping half of
116
+ // dedup; the top-level-keeps-content half is exercised via a main search
117
+ // chunk, whose path into result.chunks is unchanged.
112
118
  const { runMemoryPhase } = jest.requireMock("./memory");
119
+ const { rerankResults } = jest.requireMock("./rerank");
113
120
  const memChunk = { chunk_id: "m1", chunk_content: "FULL MEMORY CONTENT", item_id: "i1", item_name: "Mem" };
114
121
  runMemoryPhase.mockResolvedValueOnce({
115
122
  memoryChunksForAnswer: [memChunk],
@@ -118,6 +125,12 @@ describe("payload deduplication", () => {
118
125
  updatedImportantKeyword: "k",
119
126
  steps: [{ text: "memory step", chunks: [memChunk] }],
120
127
  });
128
+ const mainChunk = { chunk_id: "r1", chunk_content: "FULL MAIN CONTENT", item_id: "i2", item_name: "Doc" };
129
+ rerankResults.mockResolvedValueOnce({
130
+ limited_results: [mainChunk],
131
+ sorted_reranked_results: [],
132
+ rerank_score_max_genuine: 1,
133
+ });
121
134
  const run = makeTool({});
122
135
  const out = await drain(run(inputs));
123
136
  const last = JSON.parse(out[out.length - 1].result);
@@ -125,9 +138,92 @@ describe("payload deduplication", () => {
125
138
  expect(stepWithChunks).toBeDefined();
126
139
  expect(stepWithChunks.chunks[0].chunk_content).toBeUndefined();
127
140
  expect(stepWithChunks.chunks[0].item_name).toBe("Mem");
128
- const topLevel = last.chunks.find((c: any) => c.chunk_id === "m1");
141
+ const topLevel = last.chunks.find((c: any) => c.chunk_id === "r1");
129
142
  expect(topLevel).toBeDefined();
130
- expect(topLevel.chunk_content).toBe("FULL MEMORY CONTENT");
143
+ expect(topLevel.chunk_content).toBe("FULL MAIN CONTENT");
144
+ // Memory chunks no longer reach the top-level chunk list on their own.
145
+ expect(last.chunks.find((c: any) => c.chunk_id === "m1")).toBeUndefined();
146
+ });
147
+ });
148
+
149
+ describe("source visibility for external / anonymous users", () => {
150
+ const SOURCE_FIELDS = ["item_id", "item_name", "item_external_id", "context", "chunk_id", "chunk_index"];
151
+ const richChunk = {
152
+ chunk_id: "c1", chunk_index: 3, chunk_content: "SECRET PASSAGE",
153
+ item_id: "i1", item_name: "Handbook.pdf", item_external_id: "ext-1", context: "docs",
154
+ };
155
+ const internalUser = { id: "u1", role: { name: "admin" } } as any;
156
+ const externalUser = { id: "u2", role: { name: "external" } } as any;
157
+
158
+ /**
159
+ * Seed both phases so a fully-populated chunk reaches the top-level list AND
160
+ * a step.
161
+ *
162
+ * The main search is what puts a chunk in `result.chunks`. Seeding only the
163
+ * memory phase used to be enough, because memory chunks were copied into
164
+ * that list — they no longer are ("recall once", asserted by the payload
165
+ * deduplication suite above), so a memory-only fixture leaves the top-level
166
+ * list empty and every assertion on `last.chunks[0]` reads undefined.
167
+ * Stripping itself is indifferent to where a chunk came from.
168
+ */
169
+ const seedRichChunk = () => {
170
+ jest.requireMock("./memory").runMemoryPhase.mockResolvedValueOnce({
171
+ memoryChunksForAnswer: [richChunk],
172
+ memoryOverride: { active: false, chunks: [], reason: "" },
173
+ memoryPinnedItemIdsByContext: new Map(), updatedQuestion: "q", updatedKeywords: ["k"],
174
+ updatedImportantKeyword: "k",
175
+ steps: [{ text: "memory step", chunks: [richChunk] }],
176
+ });
177
+ jest.requireMock("./rerank").rerankResults.mockResolvedValueOnce({
178
+ limited_results: [richChunk],
179
+ sorted_reranked_results: [],
180
+ rerank_score_max_genuine: 1,
181
+ });
182
+ };
183
+
184
+ const lastPayload = async (config: Record<string, unknown>, user: any) => {
185
+ seedRichChunk();
186
+ const out = await drain(makeTool(config, { user })(inputs));
187
+ return JSON.parse(out[out.length - 1].result);
188
+ };
189
+
190
+ it("strips source references for an external user when the flag is off", async () => {
191
+ const last = await lastPayload({ show_sources_to_external_users: false }, externalUser);
192
+ const topLevel = last.chunks[0];
193
+ expect(topLevel).toBeDefined();
194
+ for (const f of SOURCE_FIELDS) expect(topLevel[f]).toBeUndefined();
195
+ // the passage text itself still reaches the model — only the attribution is removed
196
+ expect(topLevel.chunk_content).toBe("SECRET PASSAGE");
197
+ const stepChunk = last.steps.find((s: any) => s.chunks?.length > 0).chunks[0];
198
+ for (const f of SOURCE_FIELDS) expect(stepChunk[f]).toBeUndefined();
199
+ });
200
+
201
+ it("strips source references for an anonymous guest when the flag is off", async () => {
202
+ const last = await lastPayload({ show_sources_to_external_users: false }, undefined);
203
+ for (const f of SOURCE_FIELDS) expect(last.chunks[0][f]).toBeUndefined();
204
+ });
205
+
206
+ it("keeps source references for an internal user even when the flag is off", async () => {
207
+ const last = await lastPayload({ show_sources_to_external_users: false }, internalUser);
208
+ expect(last.chunks[0].item_name).toBe("Handbook.pdf");
209
+ expect(last.chunks[0].chunk_id).toBe("c1");
210
+ });
211
+
212
+ it("keeps source references for external users when the flag is on", async () => {
213
+ const last = await lastPayload({ show_sources_to_external_users: true }, externalUser);
214
+ expect(last.chunks[0].item_name).toBe("Handbook.pdf");
215
+ });
216
+
217
+ it("defaults to showing sources when the flag is unset (backward compatible)", async () => {
218
+ const last = await lastPayload({}, externalUser);
219
+ expect(last.chunks[0].item_name).toBe("Handbook.pdf");
220
+ expect(last.chunks[0].chunk_id).toBe("c1");
221
+ });
222
+
223
+ it("still strips chunk_content from step chunks when sources are hidden", async () => {
224
+ const last = await lastPayload({ show_sources_to_external_users: false }, externalUser);
225
+ const stepChunk = last.steps.find((s: any) => s.chunks?.length > 0).chunks[0];
226
+ expect(stepChunk.chunk_content).toBeUndefined();
131
227
  });
132
228
  });
133
229
 
@@ -19,6 +19,7 @@ import { withTiming } from "./timing";
19
19
  import { needsPinRerun } from "./pin-rerun";
20
20
  import type { VectorSearchChunkResult } from "@SRC/graphql/resolvers/vector-search";
21
21
  import { parsePreselectedItems } from "./global-ids";
22
+ import { isExternalOrAnonymousUser } from "@SRC/exulu/resolve-max-steps";
22
23
  export { parsePreselectedItems } from "./global-ids";
23
24
 
24
25
  // ---------------------------------------------------------------------------
@@ -38,22 +39,46 @@ function addChunks(result: AgenticRetrievalOutput, chunks: ChunkWithScore[]): vo
38
39
  }
39
40
  }
40
41
 
42
+ /**
43
+ * Strip source reference fields from a chunk when sources should not be shown.
44
+ * Removes: item_id, item_name, item_external_id, context, chunk_id, chunk_index.
45
+ */
46
+ function stripSourceReferences(chunk: ChunkWithScore): Partial<ChunkWithScore> {
47
+ return {
48
+ ...chunk,
49
+ item_id: undefined,
50
+ item_name: undefined,
51
+ item_external_id: undefined,
52
+ context: undefined,
53
+ chunk_id: undefined,
54
+ chunk_index: undefined,
55
+ };
56
+ }
57
+
41
58
  /**
42
59
  * Serialize the cumulative output for yielding. Full chunk content lives ONLY in the
43
60
  * top-level `chunks` (what the chat UI cites and the calling agent reads); the per-step
44
61
  * chunk copies keep ids/names/metadata for counts and traceability but drop
45
62
  * `chunk_content` — serializing the same content twice roughly doubled the tool payload
46
63
  * and, across a few calls, overflowed the calling agent's context window.
64
+ *
65
+ * When hideSources is true, also strips source reference fields (item_id, item_name, etc.)
66
+ * from all chunks at both the top-level and per-step level.
47
67
  */
48
- function serializeOutput(result: AgenticRetrievalOutput): string {
68
+ function serializeOutput(result: AgenticRetrievalOutput, hideSources: boolean = false): string {
49
69
  return JSON.stringify({
50
70
  ...result,
71
+ chunks: hideSources ? result.chunks.map(stripSourceReferences) : result.chunks,
51
72
  steps: result.steps.map((step) =>
52
73
  step.chunks.length === 0
53
74
  ? step
54
75
  : {
55
76
  ...step,
56
- chunks: step.chunks.map((c) => ({ ...c, chunk_content: undefined })),
77
+ chunks: step.chunks.map((c) =>
78
+ hideSources
79
+ ? { ...stripSourceReferences(c), chunk_content: undefined }
80
+ : { ...c, chunk_content: undefined },
81
+ ),
57
82
  },
58
83
  ),
59
84
  });
@@ -183,6 +208,12 @@ export function createAgenticRetrievalTool(opts: {
183
208
  type: "json",
184
209
  default: '{"topK":5,"fallbackThreshold":0.95,"pinBoost":0.15,"identifierBoost":0.15,"pageWindow":1,"maxQueriesPerContext":5}',
185
210
  },
211
+ {
212
+ name: "show_sources_to_external_users",
213
+ description: "When disabled, hides source references (item names, IDs, chunk info) from external users and anonymous guests. Sources are stripped from the tool output and the system prompt guidance for citation is omitted.",
214
+ type: "boolean",
215
+ default: true,
216
+ },
186
217
  ],
187
218
  inputSchema: z.object({
188
219
  userQuery: z.string().describe("The original unaltered question from the user"),
@@ -217,6 +248,12 @@ export function createAgenticRetrievalTool(opts: {
217
248
 
218
249
  const cfg = parsePipelineConfig(toolVariablesConfig);
219
250
 
251
+ // ── Source visibility: strip references for external/anonymous users ──
252
+ // Only when the admin explicitly turned the flag off; the default (true)
253
+ // preserves the previous behaviour for every caller.
254
+ const hideSources =
255
+ !cfg.showSourcesToExternalUsers && isExternalOrAnonymousUser(user);
256
+
220
257
  // ── Gate: managed context requires preselected items ──────────────────
221
258
  if (cfg.managedContext && !preselected?.length) {
222
259
  if (cfg.logging) console.log("[EXULU] Managed context was enabled for the agentic retrieval tool. This means that the user must preselect items that the agentic retrieval tool will search in, please notify the user to preselect items before executing the tool.");
@@ -368,7 +405,6 @@ export function createAgenticRetrievalTool(opts: {
368
405
  timings,
369
406
  mergedCall: engineV2 && v2.mergedMemoryCall,
370
407
  memoryChunks: memoryItems ?? [],
371
- memoryContext,
372
408
  question: userQuery,
373
409
  keywords: relevantKeywords,
374
410
  importantKeyword,
@@ -412,9 +448,7 @@ export function createAgenticRetrievalTool(opts: {
412
448
  });
413
449
  result.reasoning.push({ text: step.text, tools: [] });
414
450
  }
415
- // Memory citable chunks go first (insertion-order dedup)
416
- addChunks(result, memResult.memoryChunksForAnswer);
417
- yield { result: serializeOutput(result) };
451
+ yield { result: serializeOutput(result, hideSources) };
418
452
 
419
453
  // ── Preselection-subset guard (yield, not throw) ──────────────────────
420
454
  const { mainContexts, fallbackContexts, userPinnedItemIdsByContext, userRequestedPage, hasExplicitDocAndPage } = routResult;
@@ -571,7 +605,7 @@ export function createAgenticRetrievalTool(opts: {
571
605
  tokens: 0,
572
606
  });
573
607
  result.reasoning.push({ text: `Reranking ${mainSearch.chunks.length} chunks`, tools: [] });
574
- yield { result: serializeOutput(result) };
608
+ yield { result: serializeOutput(result, hideSources) };
575
609
 
576
610
  const mainRerank = await rerankResults({
577
611
  chunks: mainSearch.chunks,
@@ -603,9 +637,9 @@ export function createAgenticRetrievalTool(opts: {
603
637
  });
604
638
 
605
639
  lap("rerankMs");
606
- // Accumulate main results (dedup by chunk_id, memory chunks already first)
640
+ // Accumulate main results (dedup by chunk_id)
607
641
  addChunks(result, mainRerank.limited_results);
608
- yield { result: serializeOutput(result) };
642
+ yield { result: serializeOutput(result, hideSources) };
609
643
 
610
644
  // ── Literal-lookup short-circuit ──────────────────────────────────────
611
645
  const literalLookupSatisfied =
@@ -629,7 +663,7 @@ export function createAgenticRetrievalTool(opts: {
629
663
  tokens: 0,
630
664
  });
631
665
  result.reasoning.push({ text: "Literal lookup satisfied; skipping fallback.", tools: [] });
632
- yield { result: serializeOutput(result) };
666
+ yield { result: serializeOutput(result, hideSources) };
633
667
  }
634
668
 
635
669
  // ── Fallback gate ─────────────────────────────────────────────────────
@@ -648,7 +682,7 @@ export function createAgenticRetrievalTool(opts: {
648
682
  tokens: 0,
649
683
  });
650
684
  result.reasoning.push({ text: `Fallback search in ${fallbackContextsToSearch.join(", ")}`, tools: [] });
651
- yield { result: serializeOutput(result) };
685
+ yield { result: serializeOutput(result, hideSources) };
652
686
 
653
687
  const fallbackRerank = await rerankResults({
654
688
  chunks: speculativeFallbackSearch.chunks,
@@ -673,7 +707,7 @@ export function createAgenticRetrievalTool(opts: {
673
707
  result.reasoning.push({ text: "Fallback results reranked", tools: [] });
674
708
  addChunks(result, fallbackRerank.limited_results);
675
709
  lap("fallbackRerankMs");
676
- yield { result: serializeOutput(result) };
710
+ yield { result: serializeOutput(result, hideSources) };
677
711
  }
678
712
 
679
713
  // ── Phase 4: memory override directive ────────────────────────────────
@@ -701,7 +735,7 @@ export function createAgenticRetrievalTool(opts: {
701
735
  tools: [],
702
736
  });
703
737
  addChunks(result, memoryOverride.chunks);
704
- yield { result: serializeOutput(result) };
738
+ yield { result: serializeOutput(result, hideSources) };
705
739
  }
706
740
 
707
741
  timings.totalMs = Date.now() - t0;
@@ -724,8 +758,8 @@ export function createAgenticRetrievalTool(opts: {
724
758
 
725
759
  // The generator's return value is not consumed by the tool wrapper (for-await only sees
726
760
  // yields), so the final payload — including the timing step — must be yielded.
727
- yield { result: serializeOutput(result) };
728
- return { result: serializeOutput(result) };
761
+ yield { result: serializeOutput(result, hideSources) };
762
+ return { result: serializeOutput(result, hideSources) };
729
763
  } catch (err) {
730
764
  console.warn("[EXULU pipeline] retrieval pipeline failed:", err);
731
765
  result.steps.push({
@@ -735,7 +769,7 @@ export function createAgenticRetrievalTool(opts: {
735
769
  chunks: [],
736
770
  tokens: 0,
737
771
  });
738
- yield { result: serializeOutput(result) };
772
+ yield { result: serializeOutput(result, hideSources) };
739
773
  return;
740
774
  }
741
775
  },
@@ -1,5 +1,5 @@
1
1
  // ee/agentic-retrieval/pipeline/memory.test.ts
2
- import { runMemoryPhase, clearMemoryItemCache } from "./memory";
2
+ import { runMemoryPhase } from "./memory";
3
3
 
4
4
  jest.mock("ai", () => ({
5
5
  ...jest.requireActual("ai"),
@@ -22,11 +22,11 @@ const baseOpts = {
22
22
  };
23
23
  const allOn = { enabled: true, override: true, filePrioritization: true, queryAugmentation: true };
24
24
 
25
- beforeEach(() => { clearMemoryItemCache(); (generateText as jest.Mock).mockReset(); });
25
+ beforeEach(() => { (generateText as jest.Mock).mockReset(); });
26
26
 
27
27
  describe("runMemoryPhase", () => {
28
28
  it("returns a neutral result when memory is disabled", async () => {
29
- const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")], memoryContext: undefined,
29
+ const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")],
30
30
  memoryConfig: { ...allOn, enabled: false } });
31
31
  expect(r.memoryChunksForAnswer).toEqual([]);
32
32
  expect(r.updatedQuestion).toBe(baseOpts.question);
@@ -40,24 +40,42 @@ describe("runMemoryPhase", () => {
40
40
  .mockResolvedValueOnce({ output: { shouldPrioritizeFiles: false, fileNameHints: [] } })
41
41
  .mockResolvedValueOnce({ output: { updatedUserQuestion: baseOpts.question, updatedRelevantKeywords: [], updatedImportantKeyword: "FST-2XT" } });
42
42
  const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "hint"), memChunk("2", "other")],
43
- memoryContext: undefined, memoryConfig: allOn });
43
+ memoryConfig: allOn });
44
44
  expect(r.memoryChunksForAnswer).toHaveLength(1);
45
45
  expect(r.memoryChunksForAnswer[0]).toMatchObject({ chunk_id: "1", rerank_score: 1, context: { id: "memory" } });
46
46
  });
47
47
 
48
+ it("keeps the relevance step's text to item names/ids and a count, never the raw chunk_content (no second copy of the memory in the serialized tool result)", async () => {
49
+ (generateText as jest.Mock)
50
+ .mockResolvedValueOnce({ output: { relevantChunkIds: ["1", "2"] } })
51
+ .mockResolvedValueOnce({ output: { overrides: false, confidence: "low", authoritativeChunkIds: [], reason: "" } })
52
+ .mockResolvedValueOnce({ output: { shouldPrioritizeFiles: false, fileNameHints: [] } })
53
+ .mockResolvedValueOnce({ output: { updatedUserQuestion: baseOpts.question, updatedRelevantKeywords: [], updatedImportantKeyword: "FST-2XT" } });
54
+ const r = await runMemoryPhase({
55
+ ...baseOpts,
56
+ memoryChunks: [memChunk("1", "SECRET-CHUNK-CONTENT-ONE"), memChunk("2", "SECRET-CHUNK-CONTENT-TWO")],
57
+ memoryConfig: allOn,
58
+ });
59
+ const relevanceStep = r.steps.find((s) => s.text.includes("Retrieved"));
60
+ expect(relevanceStep?.text).toContain("2 potentially relevant memories");
61
+ expect(relevanceStep?.text).toContain("Memory 1 (m1)");
62
+ expect(relevanceStep?.text).toContain("Memory 2 (m2)");
63
+ expect(relevanceStep?.text).not.toContain("SECRET-CHUNK-CONTENT");
64
+ });
65
+
48
66
  it("activates the override only with overrides=true AND high confidence AND chunks", async () => {
49
67
  (generateText as jest.Mock)
50
68
  .mockResolvedValueOnce({ output: { relevantChunkIds: ["1"] } })
51
69
  .mockResolvedValueOnce({ output: { overrides: true, confidence: "medium", authoritativeChunkIds: ["1"], reason: "r" } })
52
70
  .mockResolvedValueOnce({ output: { shouldPrioritizeFiles: false } })
53
71
  .mockResolvedValueOnce({ output: { updatedUserQuestion: baseOpts.question, updatedRelevantKeywords: [], updatedImportantKeyword: "FST-2XT" } });
54
- const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")], memoryContext: undefined, memoryConfig: allOn });
72
+ const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")], memoryConfig: allOn });
55
73
  expect(r.memoryOverride.active).toBe(false); // medium confidence blocks it
56
74
  });
57
75
 
58
76
  it("skips override/file/augmentation LLM calls when those features are off", async () => {
59
77
  (generateText as jest.Mock).mockResolvedValueOnce({ output: { relevantChunkIds: ["1"] } });
60
- const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")], memoryContext: undefined,
78
+ const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")],
61
79
  memoryConfig: { enabled: true, override: false, filePrioritization: false, queryAugmentation: false } });
62
80
  expect(generateText).toHaveBeenCalledTimes(1); // relevance only
63
81
  expect(r.memoryOverride.active).toBe(false);
@@ -67,7 +85,7 @@ describe("runMemoryPhase", () => {
67
85
  (generateText as jest.Mock)
68
86
  .mockResolvedValueOnce({ output: { relevantChunkIds: ["1"] } })
69
87
  .mockResolvedValueOnce({ output: { updatedUserQuestion: "expanded q", updatedRelevantKeywords: ["Feldbussteuerung"], updatedImportantKeyword: "SOMETHING-ELSE" } });
70
- const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")], memoryContext: undefined,
88
+ const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "x")],
71
89
  memoryConfig: { enabled: true, override: false, filePrioritization: false, queryAugmentation: true } });
72
90
  expect(r.updatedQuestion).toBe("expanded q");
73
91
  expect(r.updatedKeywords).toEqual(expect.arrayContaining(["door", "feldbussteuerung"]));
@@ -80,7 +98,7 @@ describe("runMemoryPhase", () => {
80
98
  .mockResolvedValueOnce({ output: { shouldPrioritizeFiles: true, fileNameHints: ["PROJECT_NOTES"] } });
81
99
  (fuzzyPrefilter as jest.Mock).mockResolvedValue([{ id: "d1", name: "Project Notes", key: "k" }]);
82
100
  const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "always check PROJECT_NOTES")],
83
- memoryContext: undefined, documentContexts: [{ id: "docs" }],
101
+ documentContexts: [{ id: "docs" }],
84
102
  memoryConfig: { enabled: true, override: false, filePrioritization: true, queryAugmentation: false } });
85
103
  // Pins are keyed by the context they were resolved in, so a consumer can apply them
86
104
  // only to that context (no cross-context leak). See search.ts rule 2b.
@@ -98,29 +116,23 @@ describe("runMemoryPhase", () => {
98
116
  .mockResolvedValueOnce({ output: { updatedUserQuestion: baseOpts.question, updatedRelevantKeywords: [{ bad: "object" } as any], updatedImportantKeyword: "FST-2XT" } });
99
117
 
100
118
  // This should resolve without throwing, returning a neutral result despite the runtime error in keyword merge
101
- const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "test")], memoryContext: undefined, memoryConfig: allOn });
119
+ const r = await runMemoryPhase({ ...baseOpts, memoryChunks: [memChunk("1", "test")], memoryConfig: allOn });
102
120
 
103
121
  // Verify it returns a neutral result (original question preserved, no crash)
104
122
  expect(r).toBeDefined();
105
123
  expect(r.updatedQuestion).toBe(baseOpts.question);
106
124
  });
107
- });
108
125
 
109
- describe("recallMemoryByKeywords — fetching the chunks of keyword-matched memory items", () => {
110
- const { singleSearch } = jest.requireMock("./multi-query") as { singleSearch: jest.Mock };
111
- const { recallMemoryByKeywords, clearMemoryItemCache } = jest.requireActual("./memory") as typeof import("./memory");
112
-
113
- it("uses the full-text method, not the hybrid one: the items are already chosen by keyword, so an embedding call would only add latency", async () => {
114
- clearMemoryItemCache();
115
- singleSearch.mockClear();
116
- const memoryContext = {
117
- id: "memory-ctx",
118
- getItems: async () => [{ id: "item-1", name: "CBM2 Version", description: "Hinweis zur CBM2 Firmware", information: "" }],
119
- };
120
- await recallMemoryByKeywords({ keywords: ["CBM2"], importantKeyword: "CBM2", user: {}, role: {}, memoryContext });
121
- expect(singleSearch).toHaveBeenCalledTimes(1);
122
- expect(singleSearch.mock.calls[0][0].config.method).toBe("tsvector");
123
- expect(singleSearch.mock.calls[0][0].pinnedItemIds).toEqual(["item-1"]);
126
+ it("runMemoryPhase judges only the chunks it is given and never searches", async () => {
127
+ const search = jest.fn();
128
+ const r = await runMemoryPhase({
129
+ memoryChunks: [], question: "q", keywords: ["k"], importantKeyword: "k", user: { id: 1 }, role: "r",
130
+ model: {} as never, memoryConfig: { enabled: true, override: true, filePrioritization: true, queryAugmentation: true },
131
+ glossary: [], documentContexts: [{ id: "docs", search } as never],
132
+ });
133
+ expect(search).not.toHaveBeenCalled();
134
+ expect(r.memoryChunksForAnswer).toEqual([]);
135
+ expect(r.memoryOverride.active).toBe(false);
124
136
  });
125
137
  });
126
138
 
@@ -136,7 +148,7 @@ describe("runMemoryPhase with mergedCall (engine v2)", () => {
136
148
  it("asks the model once and produces the same result shape as the four v1 hops", async () => {
137
149
  (generateText as jest.Mock).mockResolvedValueOnce(merged());
138
150
  const r = await runMemoryPhase({ ...baseOpts, mergedCall: true, memoryChunks: [memChunk("1", "hint"), memChunk("2", "other")],
139
- memoryContext: undefined, memoryConfig: allOn });
151
+ memoryConfig: allOn });
140
152
  expect(generateText).toHaveBeenCalledTimes(1);
141
153
  expect(r.memoryChunksForAnswer.map((c) => c.chunk_id)).toEqual(["1"]);
142
154
  expect(r.memoryOverride).toMatchObject({ active: true, reason: "direct answer" });
@@ -148,7 +160,7 @@ describe("runMemoryPhase with mergedCall (engine v2)", () => {
148
160
 
149
161
  it("ignores override/file/augmentation parts of the answer when those features are off", async () => {
150
162
  (generateText as jest.Mock).mockResolvedValueOnce(merged());
151
- const r = await runMemoryPhase({ ...baseOpts, mergedCall: true, memoryChunks: [memChunk("1", "hint")], memoryContext: undefined,
163
+ const r = await runMemoryPhase({ ...baseOpts, mergedCall: true, memoryChunks: [memChunk("1", "hint")],
152
164
  memoryConfig: { enabled: true, override: false, filePrioritization: false, queryAugmentation: false } });
153
165
  expect(generateText).toHaveBeenCalledTimes(1);
154
166
  expect(r.memoryOverride.active).toBe(false);
@@ -158,7 +170,7 @@ describe("runMemoryPhase with mergedCall (engine v2)", () => {
158
170
 
159
171
  it("treats no relevant chunks as a neutral result even if the model filled the other parts", async () => {
160
172
  (generateText as jest.Mock).mockResolvedValueOnce(merged({ relevantChunkIds: [] }));
161
- const r = await runMemoryPhase({ ...baseOpts, mergedCall: true, memoryChunks: [memChunk("1", "hint")], memoryContext: undefined, memoryConfig: allOn });
173
+ const r = await runMemoryPhase({ ...baseOpts, mergedCall: true, memoryChunks: [memChunk("1", "hint")], memoryConfig: allOn });
162
174
  expect(r.memoryChunksForAnswer).toEqual([]);
163
175
  expect(r.memoryOverride.active).toBe(false);
164
176
  expect(r.updatedQuestion).toBe(baseOpts.question);