@nxuss/lemma 1.16.1 → 1.17.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 (36) hide show
  1. package/bin/init.js +4 -0
  2. package/dist/cjs/mcp/tools.d.ts.map +1 -1
  3. package/dist/cjs/mcp/tools.js +279 -9
  4. package/dist/cjs/mcp/tools.js.map +1 -1
  5. package/dist/cjs/pr-review/bridge/BrainBridge.js +1 -1
  6. package/dist/cjs/pr-review/bridge/BrainBridge.js.map +1 -1
  7. package/dist/cjs/subconscious/BrainEmbeddings.d.ts +59 -0
  8. package/dist/cjs/subconscious/BrainEmbeddings.d.ts.map +1 -0
  9. package/dist/cjs/subconscious/BrainEmbeddings.js +222 -0
  10. package/dist/cjs/subconscious/BrainEmbeddings.js.map +1 -0
  11. package/dist/cjs/subconscious/GitIngest.js +2 -2
  12. package/dist/cjs/subconscious/GitIngest.js.map +1 -1
  13. package/dist/cjs/subconscious/TheBrainV2.d.ts +284 -2
  14. package/dist/cjs/subconscious/TheBrainV2.d.ts.map +1 -1
  15. package/dist/cjs/subconscious/TheBrainV2.js +871 -46
  16. package/dist/cjs/subconscious/TheBrainV2.js.map +1 -1
  17. package/dist/cjs/utils/ConversationCheckpoint.js +1 -1
  18. package/dist/cjs/utils/ConversationCheckpoint.js.map +1 -1
  19. package/dist/esm/mcp/tools.d.ts.map +1 -1
  20. package/dist/esm/mcp/tools.js +280 -10
  21. package/dist/esm/mcp/tools.js.map +1 -1
  22. package/dist/esm/pr-review/bridge/BrainBridge.js +1 -1
  23. package/dist/esm/pr-review/bridge/BrainBridge.js.map +1 -1
  24. package/dist/esm/subconscious/BrainEmbeddings.d.ts +59 -0
  25. package/dist/esm/subconscious/BrainEmbeddings.d.ts.map +1 -0
  26. package/dist/esm/subconscious/BrainEmbeddings.js +211 -0
  27. package/dist/esm/subconscious/BrainEmbeddings.js.map +1 -0
  28. package/dist/esm/subconscious/GitIngest.js +2 -2
  29. package/dist/esm/subconscious/GitIngest.js.map +1 -1
  30. package/dist/esm/subconscious/TheBrainV2.d.ts +284 -2
  31. package/dist/esm/subconscious/TheBrainV2.d.ts.map +1 -1
  32. package/dist/esm/subconscious/TheBrainV2.js +866 -46
  33. package/dist/esm/subconscious/TheBrainV2.js.map +1 -1
  34. package/dist/esm/utils/ConversationCheckpoint.js +1 -1
  35. package/dist/esm/utils/ConversationCheckpoint.js.map +1 -1
  36. package/package.json +1 -1
@@ -24,7 +24,7 @@ import { findPattern, storePattern, getPatternStats } from "../utils/PromptPatte
24
24
  import { runAnalysis, parseDiff } from "../pr-review/PRReviewEngine.js";
25
25
  import { ReviewStore } from "../pr-review/ReviewStore.js";
26
26
  import { runPRReview } from "../pr-review/reviewRunner.js";
27
- import { getBrain, deriveProjectId } from "../subconscious/TheBrainV2.js";
27
+ import { getBrain, deriveProjectId, currentGitContext } from "../subconscious/TheBrainV2.js";
28
28
  import { collapseContext } from "../utils/ContextCollapser.js";
29
29
  import { getSymbolSurgicalContext } from "../utils/SymbolSurgicalContext.js";
30
30
  import { compressWormhole } from "../utils/WormholeCompressor.js";
@@ -69,6 +69,10 @@ function isProUser() {
69
69
  const FREE_TOOLS = new Set([
70
70
  // Cache & Memory — the hook that shows instant value
71
71
  "smarter_cache", "state_hash_cache", "token_receipt", "search_memory", "store_memory", "downvote_memory", "verify_memory", "get_project_history",
72
+ // Memory upkeep. Deleting your own memories, re-verifying them, and getting them back out
73
+ // of the tool must never be behind a paywall — a user who cannot export or forget what a
74
+ // free tier collected does not really own it.
75
+ "forget_memory", "refresh_memory", "brain_stats", "brain_export", "brain_import",
72
76
  // Token optimization — shows what they're saving
73
77
  "token_budget", "squeeze_prompt", "turbosqueeze",
74
78
  // Utility — just enough to function
@@ -307,6 +311,81 @@ const toolDefinitions = [
307
311
  required: ["id"],
308
312
  },
309
313
  },
314
+ {
315
+ name: "forget_memory",
316
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
317
+ description: "Permanently delete one memory from the Brain by id. Use when a memory is flat wrong, was captured by mistake, or should never have been stored — not when it is merely a poor match for one query (that is downvote_memory, which keeps it around for a different question later). Deletion is irreversible and the id will not come back from another session's copy.",
318
+ inputSchema: {
319
+ type: "object",
320
+ properties: {
321
+ id: { type: "string", description: "The memory's id, from a search_memory or store_memory result." },
322
+ },
323
+ required: ["id"],
324
+ },
325
+ },
326
+ {
327
+ name: "refresh_memory",
328
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
329
+ description: "Re-anchor a STALE memory to the code as it stands now, keeping its id, hit count and derivedFrom links (storing a near-duplicate instead loses all three, and dedup often refuses it anyway). Call with just the id after you have verified the memory is still correct; pass filePaths/symbols instead when the code moved and it should track something new. Only call this once you have actually checked — it records your assertion that the memory is true today, it cannot verify that itself.",
330
+ inputSchema: {
331
+ type: "object",
332
+ properties: {
333
+ id: { type: "string", description: "The memory's id, from a search_memory or verify_memory result." },
334
+ filePaths: { type: "array", items: { type: "string" }, description: "New files to track instead of the current ones. Omit to re-hash whatever it already tracks." },
335
+ symbols: {
336
+ type: "array",
337
+ items: {
338
+ type: "object",
339
+ properties: {
340
+ filePath: { type: "string" },
341
+ symbolName: { type: "string" },
342
+ },
343
+ required: ["filePath", "symbolName"],
344
+ },
345
+ description: "New symbols to track instead of the current ones (e.g. the function was renamed or moved).",
346
+ },
347
+ },
348
+ required: ["id"],
349
+ },
350
+ },
351
+ {
352
+ name: "brain_stats",
353
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
354
+ description: "Health report for the Brain itself: entry count, how many memories no search has ever reused, how many were downvoted, what wrote them (manual vs. each auto-capture path), projects covered, and corpus size. Pass deep:true to also re-hash every tracked file and report the stale ratio — accurate but thousands of file reads on a large Brain.",
355
+ inputSchema: {
356
+ type: "object",
357
+ properties: {
358
+ deep: { type: "boolean", description: "Also compute the stale ratio by re-hashing all tracked evidence. Slow.", default: false },
359
+ },
360
+ },
361
+ },
362
+ {
363
+ name: "brain_export",
364
+ annotations: { readOnlyHint: true, idempotentHint: false, openWorldHint: false },
365
+ description: "Write memories to a portable NDJSON bundle for backup, moving to another machine, or sharing with a teammate. Defaults to this project's memories only, and to fresh ones only (a stale memory exported and imported elsewhere is just a wrong answer with a passport).",
366
+ inputSchema: {
367
+ type: "object",
368
+ properties: {
369
+ outPath: { type: "string", description: "Where to write the bundle (relative to the workspace root)." },
370
+ allProjects: { type: "boolean", description: "Export every project's memories, not just this one.", default: false },
371
+ domain: { type: "string", description: "Only export memories tagged with this domain." },
372
+ includeStale: { type: "boolean", description: "Include memories whose tracked evidence no longer matches.", default: false },
373
+ },
374
+ required: ["outPath"],
375
+ },
376
+ },
377
+ {
378
+ name: "brain_import",
379
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
380
+ description: "Merge a bundle written by brain_export into this Brain. Additive and non-destructive: an id already present keeps the newer version, and anything previously deleted with forget_memory stays deleted. Imported memories track the paths of the machine they came from, so most will read as stale here until refresh_memory re-anchors them.",
381
+ inputSchema: {
382
+ type: "object",
383
+ properties: {
384
+ path: { type: "string", description: "Path to the bundle file (relative to the workspace root)." },
385
+ },
386
+ required: ["path"],
387
+ },
388
+ },
310
389
  {
311
390
  name: "get_routing_advice",
312
391
  annotations: { readOnlyHint: true, openWorldHint: false },
@@ -1437,6 +1516,11 @@ const toolHandlers = {
1437
1516
  store_memory: handleStoreMemory,
1438
1517
  downvote_memory: handleDownvoteMemory,
1439
1518
  verify_memory: handleVerifyMemory,
1519
+ forget_memory: handleForgetMemory,
1520
+ refresh_memory: handleRefreshMemory,
1521
+ brain_stats: handleBrainStats,
1522
+ brain_export: handleBrainExport,
1523
+ brain_import: handleBrainImport,
1440
1524
  get_routing_advice: handleGetRoutingAdvice,
1441
1525
  auto_heal: handleAutoHeal,
1442
1526
  read_workspace_file: handleReadWorkspaceFile,
@@ -1715,7 +1799,9 @@ async function handleSearchMemory(args) {
1715
1799
  throw new Error("Query is required");
1716
1800
  try {
1717
1801
  const brain = getBrain();
1718
- const results = brain.search(query, limit, minSimilarity, { projectId: deriveProjectId(), domain, semanticDiff });
1802
+ // searchHybrid is search() plus one boolean check unless LEMMA_BRAIN_EMBEDDINGS is set,
1803
+ // so this costs nothing by default and picks up the semantic re-rank when it is enabled.
1804
+ const results = await brain.searchHybrid(query, limit, minSimilarity, { projectId: deriveProjectId(), domain, semanticDiff });
1719
1805
  if (results.length === 0) {
1720
1806
  recordReceiptEvent("reasoning", query.substring(0, 100), {
1721
1807
  tool: "search_memory",
@@ -1766,7 +1852,15 @@ async function handleSearchMemory(args) {
1766
1852
  }
1767
1853
  if (stale.length > 0) {
1768
1854
  const staleText = stale
1769
- .map((r, i) => `${formatResult(r, i)}\nSTALE — changed since stored: ${r.staleFiles.join(", ")}`)
1855
+ .map((r, i) => {
1856
+ // "You are on a different branch" and "someone rewrote this function" are the same
1857
+ // hash mismatch and completely different situations for the reader: the first is
1858
+ // usually not a reason to distrust the memory at all.
1859
+ const cause = r.staleCause === "branch-changed"
1860
+ ? `\nNOTE: stored on branch \`${r.storedOnBranch}\`, you are on \`${currentGitContext().branch || "an unknown branch"}\`. The difference may be the branch switch rather than an edit — check before discarding this.`
1861
+ : "";
1862
+ return `${formatResult(r, i)}\nSTALE — changed since stored: ${r.staleFiles.join(", ")}${cause}`;
1863
+ })
1770
1864
  .join("\n\n---\n\n");
1771
1865
  parts.push(`${stale.length} more ${stale.length === 1 ? "memory is" : "memories are"} similar but STALE (underlying file(s) changed) — do not reuse verbatim, re-verify against current file state:\n\n${staleText}`);
1772
1866
  }
@@ -1800,7 +1894,7 @@ async function handleStoreMemory(args) {
1800
1894
  throw new Error("Query and response are required");
1801
1895
  try {
1802
1896
  const brain = getBrain();
1803
- const storeRes = brain.store(query, responseText, provider, 0.92, filePaths, undefined, outcome, symbols, claims, domain, derivedFrom);
1897
+ const storeRes = brain.store(query, responseText, provider, 0.92, filePaths, undefined, outcome, symbols, claims, domain, derivedFrom, { source: "manual" });
1804
1898
  // Storing a memory saves nothing — it only creates the chance of a saving later.
1805
1899
  // Crediting tokens here inflated the ledger on write and then credited the same
1806
1900
  // answer again on every read. The saving is booked by search_memory on a fresh hit.
@@ -1823,7 +1917,11 @@ async function handleStoreMemory(args) {
1823
1917
  ? `\n\n⚠️ ${storeRes.conflicts.length} existing ${storeRes.conflicts.length === 1 ? "memory shares" : "memories share"} a symbol with this one but disagree on outcome — review before trusting either:\n` +
1824
1918
  storeRes.conflicts.map((c) => ` - [${c.outcome}] ${c.id}: ${c.query.substring(0, 120)}`).join("\n")
1825
1919
  : "";
1826
- return { content: [{ type: "text", text: `Success: Memory stored. ${storeRes.reason}${trackingNote}${symbolNote}${outcomeNote}${claimsNote}${domainNote}${derivedFromNote}${conflictsNote}` }] };
1920
+ // The id is the handle for every follow-up action on this memory — derivedFrom on a
1921
+ // later store, verify_memory, refresh_memory, forget_memory. Without it the caller had
1922
+ // to search for the memory it had just written to do anything with it.
1923
+ const idNote = storeRes.id ? ` (id: ${storeRes.id})` : "";
1924
+ return { content: [{ type: "text", text: `Success: Memory stored${idNote}. ${storeRes.reason}${trackingNote}${symbolNote}${outcomeNote}${claimsNote}${domainNote}${derivedFromNote}${conflictsNote}` }] };
1827
1925
  }
1828
1926
  catch (e) {
1829
1927
  logError("store_memory", e);
@@ -1843,6 +1941,138 @@ async function handleDownvoteMemory(args) {
1843
1941
  return { content: [{ type: "text", text: `Failed to downvote memory: ${e.message}` }] };
1844
1942
  }
1845
1943
  }
1944
+ /**
1945
+ * Deleting a memory is the one Brain operation with no undo, so it asks the client to
1946
+ * confirm where the client supports it, and echoes back what was destroyed where it doesn't
1947
+ * — an irreversible action must at minimum leave a record of what it removed.
1948
+ */
1949
+ async function handleForgetMemory(args) {
1950
+ const id = args?.id;
1951
+ if (!id)
1952
+ throw new Error("id is required");
1953
+ try {
1954
+ const brain = getBrain();
1955
+ const preview = brain.verifyByIds([id])[0];
1956
+ if (preview?.status === "unknown") {
1957
+ return { content: [{ type: "text", text: `No memory with id "${id}" in the Brain — nothing to delete.` }] };
1958
+ }
1959
+ const elicited = await tryElicitConfirmation(`Permanently delete Brain memory "${id}"? This cannot be undone.`);
1960
+ if (elicited.supported && !elicited.confirmed) {
1961
+ return { content: [{ type: "text", text: `Memory "${id}" was not deleted: declined during confirmation.` }] };
1962
+ }
1963
+ const result = brain.forget(id);
1964
+ if (!result.ok || !result.forgotten) {
1965
+ return { content: [{ type: "text", text: result.message }] };
1966
+ }
1967
+ return {
1968
+ content: [{
1969
+ type: "text",
1970
+ text: `${result.message}\n\nDeleted content, for the record (nothing else can recover it):\n stored: ${result.forgotten.timestamp}\n reused: ${result.forgotten.hits} time(s)\n query: ${result.forgotten.query.substring(0, 300)}`,
1971
+ }],
1972
+ };
1973
+ }
1974
+ catch (e) {
1975
+ logError("forget_memory", e);
1976
+ return { content: [{ type: "text", text: `Failed to delete memory: ${e.message}` }] };
1977
+ }
1978
+ }
1979
+ async function handleRefreshMemory(args) {
1980
+ const id = args?.id;
1981
+ if (!id)
1982
+ throw new Error("id is required");
1983
+ const filePaths = Array.isArray(args?.filePaths) ? args.filePaths.filter((p) => typeof p === "string" && p) : undefined;
1984
+ const symbols = Array.isArray(args?.symbols)
1985
+ ? args.symbols.filter((sym) => sym?.filePath && sym?.symbolName)
1986
+ : undefined;
1987
+ try {
1988
+ const result = getBrain().refresh(id, { filePaths, symbols });
1989
+ if (!result.ok)
1990
+ return { content: [{ type: "text", text: result.message }] };
1991
+ const retrackedNote = result.retracked && result.retracked.length > 0
1992
+ ? `\nNow tracking: ${result.retracked.join(", ")}`
1993
+ : "\nThis memory tracks no files or symbols, so there was nothing to re-anchor — its age clock was reset.";
1994
+ return { content: [{ type: "text", text: `${result.message}${retrackedNote}` }] };
1995
+ }
1996
+ catch (e) {
1997
+ logError("refresh_memory", e);
1998
+ return { content: [{ type: "text", text: `Failed to refresh memory: ${e.message}` }] };
1999
+ }
2000
+ }
2001
+ async function handleBrainStats(args) {
2002
+ try {
2003
+ const stats = getBrain().getStats({ deep: args?.deep === true });
2004
+ const lines = [];
2005
+ lines.push(`# Brain health`);
2006
+ lines.push(`Entries: ${stats.totalEntries} (${stats.totalTerms} indexed terms, ${((stats.corpusBytes || 0) / 1024).toFixed(0)} KB on disk)`);
2007
+ lines.push(`This session: ${stats.cacheHits} hit(s), ${stats.cacheMisses} miss(es)`);
2008
+ if (stats.totalEntries > 0) {
2009
+ const neverHitPct = ((stats.neverHit || 0) / stats.totalEntries) * 100;
2010
+ lines.push(`Never reused: ${stats.neverHit} (${neverHitPct.toFixed(0)}% — these are evicted first)`);
2011
+ lines.push(`Downvoted: ${stats.downvoted}`);
2012
+ lines.push(`Projects: ${stats.projects}${stats.unscopedEntries ? ` (+${stats.unscopedEntries} entries predating project scoping)` : ""}`);
2013
+ if (stats.oldestEntry)
2014
+ lines.push(`Oldest entry: ${stats.oldestEntry}`);
2015
+ if (stats.tombstones)
2016
+ lines.push(`Deleted ids still suppressed: ${stats.tombstones}`);
2017
+ const sources = Object.entries(stats.bySource || {}).sort((a, b) => b[1] - a[1]);
2018
+ if (sources.length > 0) {
2019
+ lines.push(`Written by: ${sources.map(([k, v]) => `${k}=${v}`).join(", ")}`);
2020
+ }
2021
+ }
2022
+ if (stats.staleEntries !== undefined) {
2023
+ lines.push(`Stale: ${stats.staleEntries} of the entries that track evidence (${((stats.staleRatio || 0) * 100).toFixed(0)}%) — refresh_memory re-anchors one, forget_memory drops it.`);
2024
+ }
2025
+ else {
2026
+ lines.push(`(stale ratio not computed — pass deep:true)`);
2027
+ }
2028
+ return { content: [{ type: "text", text: lines.join("\n") }] };
2029
+ }
2030
+ catch (e) {
2031
+ logError("brain_stats", e);
2032
+ return { content: [{ type: "text", text: `Failed to read Brain stats: ${e.message}` }] };
2033
+ }
2034
+ }
2035
+ async function handleBrainExport(args) {
2036
+ const outPath = args?.outPath;
2037
+ if (!outPath)
2038
+ throw new Error("outPath is required");
2039
+ try {
2040
+ const bundle = getBrain().exportBundle({
2041
+ // Scoped to this project unless asked otherwise: exporting every project's memories
2042
+ // by default is how a bundle meant for one teammate ends up carrying another client's
2043
+ // codebase notes with it.
2044
+ projectId: args?.allProjects === true ? undefined : deriveProjectId(),
2045
+ domain: typeof args?.domain === "string" && args.domain.trim() ? args.domain.trim() : undefined,
2046
+ includeStale: args?.includeStale === true,
2047
+ });
2048
+ const { resolved } = safeResolvePath(process.cwd(), outPath);
2049
+ fs.mkdirSync(path.dirname(resolved), { recursive: true });
2050
+ fs.writeFileSync(resolved, bundle.text, "utf8");
2051
+ const staleNote = bundle.skippedStale > 0
2052
+ ? ` Skipped ${bundle.skippedStale} stale memor${bundle.skippedStale === 1 ? "y" : "ies"} (pass includeStale:true to export those too).`
2053
+ : "";
2054
+ return { content: [{ type: "text", text: `Exported ${bundle.count} memor${bundle.count === 1 ? "y" : "ies"} to ${outPath}.${staleNote}` }] };
2055
+ }
2056
+ catch (e) {
2057
+ logError("brain_export", e);
2058
+ return { content: [{ type: "text", text: `Failed to export Brain: ${e.message}` }] };
2059
+ }
2060
+ }
2061
+ async function handleBrainImport(args) {
2062
+ const bundlePath = args?.path;
2063
+ if (!bundlePath)
2064
+ throw new Error("path is required");
2065
+ try {
2066
+ const { resolved } = safeResolvePath(process.cwd(), bundlePath);
2067
+ const text = fs.readFileSync(resolved, "utf8");
2068
+ const result = getBrain().importBundle(text);
2069
+ return { content: [{ type: "text", text: result.message }] };
2070
+ }
2071
+ catch (e) {
2072
+ logError("brain_import", e);
2073
+ return { content: [{ type: "text", text: `Failed to import Brain bundle: ${e.message}` }] };
2074
+ }
2075
+ }
1846
2076
  async function handleVerifyMemory(args) {
1847
2077
  const ids = Array.isArray(args?.ids) ? args.ids.filter((id) => typeof id === "string" && id) : [];
1848
2078
  const semanticDiff = args?.semanticDiff === true;
@@ -2030,7 +2260,7 @@ async function handleReadWorkspaceFile(args) {
2030
2260
  `If you no longer hold that copy, re-fetch with force:true.`,
2031
2261
  ``,
2032
2262
  delta.body,
2033
- ].join("\n"),
2263
+ ].join("\n") + formatRecallNote(filePath),
2034
2264
  },
2035
2265
  ],
2036
2266
  };
@@ -2039,7 +2269,7 @@ async function handleReadWorkspaceFile(args) {
2039
2269
  }
2040
2270
  recordSent(resolved, view, dedup.hash, content);
2041
2271
  warmNeighbors(workspaceRoot, resolved);
2042
- return { content: [{ type: "text", text: rangeHeader + content }] };
2272
+ return { content: [{ type: "text", text: rangeHeader + content + formatRecallNote(filePath) }] };
2043
2273
  }
2044
2274
  catch (err) {
2045
2275
  logError("read_workspace_file", err);
@@ -2129,6 +2359,46 @@ function formatBlastRadiusNote(result) {
2129
2359
  const failedIds = result.failedHits.map((h) => h.id).join(", ");
2130
2360
  return `${base}\n⚠️ ${result.failedHits.length} of those document a PRIOR ATTEMPT THAT FAILED on related code: ${failedIds}. Review before continuing down this path.`;
2131
2361
  }
2362
+ /**
2363
+ * The read-side counterpart to formatBlastRadiusNote.
2364
+ *
2365
+ * Fase E made the write path proactive: a tool that stales memories says so on the spot.
2366
+ * The read path stayed entirely opt-in — the Brain only spoke when the agent remembered to
2367
+ * call search_memory, which is exactly the moment an agent that doesn't know a memory exists
2368
+ * has no reason to. This closes that asymmetry: reading code the Brain already has notes on
2369
+ * surfaces them, including any documented dead end, before the investigation restarts from
2370
+ * scratch.
2371
+ *
2372
+ * Same rules as the write-side note: advisory only, never blocks, never mutates, and adds no
2373
+ * tool schema (it enriches an existing response), so it costs nothing per turn. It reports
2374
+ * ids rather than content — pulling whole memories into every file read would spend far more
2375
+ * context than it saves; search_memory or verify_memory fetches the ones that matter.
2376
+ */
2377
+ const _recallNoted = new Set();
2378
+ function formatRecallNote(filePath, symbolName) {
2379
+ try {
2380
+ const result = getBrain().findBlastRadius(filePath, symbolName);
2381
+ if (result.hits.length === 0)
2382
+ return "";
2383
+ // Repeating the identical note on every read of the same file is nagging, not signal.
2384
+ // Keyed by the memory set, so a note reappears when the set genuinely changes.
2385
+ const ids = result.hits.map((h) => h.id).sort();
2386
+ const key = `${path.resolve(filePath)}::${symbolName || ""}::${ids.join(",")}`;
2387
+ if (_recallNoted.has(key))
2388
+ return "";
2389
+ _recallNoted.add(key);
2390
+ const subject = symbolName ? `\`${symbolName}\`` : "this file";
2391
+ const base = `\n\n🧠 The Brain already has ${result.hits.length} memor${result.hits.length === 1 ? "y" : "ies"} about ${subject}: ${ids.join(", ")}. Call verify_memory on them before investigating from scratch.`;
2392
+ if (result.failedHits.length === 0)
2393
+ return base;
2394
+ const failedIds = result.failedHits.map((h) => h.id).join(", ");
2395
+ return `${base}\n⚠️ ${result.failedHits.length} of those document an approach that was tried here and FAILED: ${failedIds}. Read those first so you don't repeat it.`;
2396
+ }
2397
+ catch {
2398
+ // A recall note must never be the reason a file read fails.
2399
+ return "";
2400
+ }
2401
+ }
2132
2402
  async function applyMatch(match, filePath, resolved, originalContent, searchContent, replaceContent) {
2133
2403
  let updatedContent;
2134
2404
  if (match.strategy === "exact" && match.charStart !== undefined && match.charEnd !== undefined) {
@@ -5047,7 +5317,7 @@ async function handleGetSymbolSurgicalContext(args) {
5047
5317
  filePath
5048
5318
  });
5049
5319
  return {
5050
- content: [{ type: "text", text: output }]
5320
+ content: [{ type: "text", text: output + formatRecallNote(filePath, symbolName) }]
5051
5321
  };
5052
5322
  }
5053
5323
  catch (err) {
@@ -5228,7 +5498,7 @@ async function handleSmartFileSlice(args) {
5228
5498
  resultText += `${i + 1}: ${lines[i]}\n`;
5229
5499
  }
5230
5500
  });
5231
- return { content: [{ type: "text", text: resultText }] };
5501
+ return { content: [{ type: "text", text: resultText + formatRecallNote(filePath) }] };
5232
5502
  }
5233
5503
  catch (e) {
5234
5504
  return { content: [{ type: "text", text: `Error slicing file: ${e.message}` }] };
@@ -5256,7 +5526,7 @@ function autoStoreGreenTests(command, workspaceRoot) {
5256
5526
  const domain = deriveDomainForFile(changed[0]);
5257
5527
  const query = `tests passing after changes to ${changed.slice(0, 5).join(", ")}${changed.length > 5 ? ` and ${changed.length - 5} more file(s)` : ""}`;
5258
5528
  const response = `\`${command}\` passed with these files changed (uncommitted at capture time):\n${changed.join("\n")}`;
5259
- const storeRes = getBrain().store(query, response, "test_oracle_auto", 0.92, changed, undefined, "confirmed", undefined, undefined, domain);
5529
+ const storeRes = getBrain().store(query, response, "test_oracle_auto", 0.92, changed, undefined, "confirmed", undefined, undefined, domain, undefined, { source: "auto-test" });
5260
5530
  if (!storeRes.stored)
5261
5531
  return "";
5262
5532
  return `\n\n[Lemma] Auto-captured this green state in Brain (${changed.length} file(s), tagged confirmed) — search_memory will surface it, and will flag it stale the moment any of these files change again.`;