@nxuss/lemma 1.12.0 → 1.15.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 (50) hide show
  1. package/README.md +15 -8
  2. package/dist/cjs/mcp/index.js +3 -0
  3. package/dist/cjs/mcp/index.js.map +1 -1
  4. package/dist/cjs/mcp/tasks.d.ts +20 -0
  5. package/dist/cjs/mcp/tasks.d.ts.map +1 -0
  6. package/dist/cjs/mcp/tasks.js +71 -0
  7. package/dist/cjs/mcp/tasks.js.map +1 -0
  8. package/dist/cjs/mcp/tool-profiles.d.ts.map +1 -1
  9. package/dist/cjs/mcp/tool-profiles.js +1 -0
  10. package/dist/cjs/mcp/tool-profiles.js.map +1 -1
  11. package/dist/cjs/mcp/tools.d.ts.map +1 -1
  12. package/dist/cjs/mcp/tools.js +360 -42
  13. package/dist/cjs/mcp/tools.js.map +1 -1
  14. package/dist/cjs/subconscious/TheBrainV2.d.ts +149 -1
  15. package/dist/cjs/subconscious/TheBrainV2.d.ts.map +1 -1
  16. package/dist/cjs/subconscious/TheBrainV2.js +314 -33
  17. package/dist/cjs/subconscious/TheBrainV2.js.map +1 -1
  18. package/dist/cjs/utils/PatchMatcher.d.ts +1 -0
  19. package/dist/cjs/utils/PatchMatcher.d.ts.map +1 -1
  20. package/dist/cjs/utils/PatchMatcher.js +4 -4
  21. package/dist/cjs/utils/PatchMatcher.js.map +1 -1
  22. package/dist/cjs/utils/SymbolSurgicalContext.d.ts +9 -0
  23. package/dist/cjs/utils/SymbolSurgicalContext.d.ts.map +1 -1
  24. package/dist/cjs/utils/SymbolSurgicalContext.js +19 -0
  25. package/dist/cjs/utils/SymbolSurgicalContext.js.map +1 -1
  26. package/dist/esm/mcp/index.js +3 -0
  27. package/dist/esm/mcp/index.js.map +1 -1
  28. package/dist/esm/mcp/tasks.d.ts +20 -0
  29. package/dist/esm/mcp/tasks.d.ts.map +1 -0
  30. package/dist/esm/mcp/tasks.js +66 -0
  31. package/dist/esm/mcp/tasks.js.map +1 -0
  32. package/dist/esm/mcp/tool-profiles.d.ts.map +1 -1
  33. package/dist/esm/mcp/tool-profiles.js +1 -0
  34. package/dist/esm/mcp/tool-profiles.js.map +1 -1
  35. package/dist/esm/mcp/tools.d.ts.map +1 -1
  36. package/dist/esm/mcp/tools.js +362 -44
  37. package/dist/esm/mcp/tools.js.map +1 -1
  38. package/dist/esm/subconscious/TheBrainV2.d.ts +149 -1
  39. package/dist/esm/subconscious/TheBrainV2.d.ts.map +1 -1
  40. package/dist/esm/subconscious/TheBrainV2.js +310 -33
  41. package/dist/esm/subconscious/TheBrainV2.js.map +1 -1
  42. package/dist/esm/utils/PatchMatcher.d.ts +1 -0
  43. package/dist/esm/utils/PatchMatcher.d.ts.map +1 -1
  44. package/dist/esm/utils/PatchMatcher.js +4 -4
  45. package/dist/esm/utils/PatchMatcher.js.map +1 -1
  46. package/dist/esm/utils/SymbolSurgicalContext.d.ts +9 -0
  47. package/dist/esm/utils/SymbolSurgicalContext.d.ts.map +1 -1
  48. package/dist/esm/utils/SymbolSurgicalContext.js +18 -0
  49. package/dist/esm/utils/SymbolSurgicalContext.js.map +1 -1
  50. package/package.json +1 -1
@@ -79,6 +79,7 @@ const StateHashCache_1 = require("../utils/StateHashCache");
79
79
  const TokenReceipt_1 = require("../utils/TokenReceipt");
80
80
  const CommandOutputDistiller_1 = require("../utils/CommandOutputDistiller");
81
81
  const PatchMatcher_1 = require("../utils/PatchMatcher");
82
+ const tasks_1 = require("./tasks");
82
83
  const WorkspaceSearch_1 = require("../utils/WorkspaceSearch");
83
84
  const LocalPrefilter_1 = require("../utils/LocalPrefilter");
84
85
  const ReadWorkspaceCache_1 = require("../utils/ReadWorkspaceCache");
@@ -110,7 +111,7 @@ function isProUser() {
110
111
  }
111
112
  const FREE_TOOLS = new Set([
112
113
  // Cache & Memory — the hook that shows instant value
113
- "smarter_cache", "state_hash_cache", "token_receipt", "search_memory", "store_memory", "get_project_history",
114
+ "smarter_cache", "state_hash_cache", "token_receipt", "search_memory", "store_memory", "downvote_memory", "verify_memory", "get_project_history",
114
115
  // Token optimization — shows what they're saving
115
116
  "token_budget", "squeeze_prompt", "turbosqueeze",
116
117
  // Utility — just enough to function
@@ -180,6 +181,45 @@ async function tryElicitConfirmation(summary) {
180
181
  return { supported: false, confirmed: true };
181
182
  }
182
183
  }
184
+ /**
185
+ * Ask the client to pick one of several candidates via a typed (oneOf) elicitation form,
186
+ * instead of the plain confirm/deny shape tryElicitConfirmation uses. Same defensive
187
+ * contract: no support, a decline, or a malformed response all just mean "couldn't
188
+ * resolve it this way" — the caller falls back to its own error/default behavior, never
189
+ * blocks or throws.
190
+ */
191
+ async function tryElicitChoice(message, options) {
192
+ if (!mcpServerRef || options.length === 0)
193
+ return { supported: false, index: null };
194
+ try {
195
+ const result = await mcpServerRef.elicitInput({
196
+ message,
197
+ requestedSchema: {
198
+ type: "object",
199
+ properties: {
200
+ choice: {
201
+ type: "string",
202
+ title: "Which one?",
203
+ oneOf: options.map((opt, i) => ({ const: String(i), title: opt.title })),
204
+ },
205
+ },
206
+ required: ["choice"],
207
+ },
208
+ });
209
+ if (result.action !== "accept" || !result.content) {
210
+ return { supported: true, index: null };
211
+ }
212
+ const idx = Number(result.content.choice);
213
+ if (!Number.isInteger(idx) || idx < 0 || idx >= options.length) {
214
+ return { supported: true, index: null };
215
+ }
216
+ return { supported: true, index: idx };
217
+ }
218
+ catch (err) {
219
+ (0, utils_1.logWarn)("elicitation", "Client does not support elicitation (or the request failed) — no choice made");
220
+ return { supported: false, index: null };
221
+ }
222
+ }
183
223
  const toolDefinitions = [
184
224
  {
185
225
  name: "scrub_privacy",
@@ -196,7 +236,7 @@ const toolDefinitions = [
196
236
  {
197
237
  name: "search_memory",
198
238
  annotations: { readOnlyHint: true, openWorldHint: false },
199
- description: "Search Lemma's semantic memory (The Brain) before investigating something from scratch — retrieves past solutions, fixes, and context from ALL your projects globally. Results are split into 'fresh' (safe to reuse — either untracked general knowledge, or every file it depended on still hashes the same) and 'stale' (a similar question was answered before, but a tracked file changed since — re-verify against current state before reusing). Never treat a stale result as current.",
239
+ description: "Search Lemma's semantic memory (The Brain) before investigating something from scratch — retrieves past solutions, fixes, and context from ALL your projects globally. Results split into 'fresh' (safe to reuse) and 'stale' (a tracked file changed since — re-verify before reusing). Never treat a stale result as current. If a returned memory turns out wrong once acted on, call downvote_memory with its id.",
200
240
  inputSchema: {
201
241
  type: "object",
202
242
  properties: {
@@ -207,6 +247,15 @@ const toolDefinitions = [
207
247
  description: "Similarity floor (0.0-1.0) a memory must clear to be returned. Lowering this surfaces loosely related memories that are usually noise — leave it alone unless a known-relevant memory is being filtered out.",
208
248
  default: 0.75,
209
249
  },
250
+ domain: {
251
+ type: "string",
252
+ description: "Prefer memories tagged with this domain (e.g. 'auth', 'billing' — matches cognitive_map domains). Soft preference, not a filter: an untagged or cross-domain memory can still be the best match.",
253
+ },
254
+ semanticDiff: {
255
+ type: "boolean",
256
+ description: "Don't count a comment/whitespace-only change as stale.",
257
+ default: false,
258
+ },
210
259
  },
211
260
  required: ["query"],
212
261
  },
@@ -214,7 +263,7 @@ const toolDefinitions = [
214
263
  {
215
264
  name: "store_memory",
216
265
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
217
- description: "Persist a technical solution, bug fix, architecture decision, or key fact into Lemma's Brain — so future questions on the same topic (even phrased differently) don't require re-investigating the repo. Pass filePaths for anything derived from specific files (e.g. 'where is X implemented', 'how does Y work') so the memory auto-invalidates the moment those files change, instead of risking a stale answer being reused. If the answer is really about one function/class rather than the whole file, pass `symbols` instead (or in addition) so an unrelated edit elsewhere in that file doesn't stale it out. Pass outcome='failed' for an approach that was tried and did NOT work — that's just as worth remembering as a fix, so the Brain can warn 'already tried, didn't work' instead of only ever suggesting reuse.",
266
+ description: "Persist a technical solution, bug fix, architecture decision, or key fact into Lemma's Brain — so future questions on the same topic (even phrased differently) don't require re-investigating the repo. Pass filePaths for anything derived from specific files so the memory auto-invalidates the moment those files change. If the answer is really about one function/class, pass `symbols` instead (or in addition) so an unrelated edit elsewhere in that file doesn't stale it out. Pass outcome='failed' for an approach that was tried and did NOT work.",
218
267
  inputSchema: {
219
268
  type: "object",
220
269
  properties: {
@@ -259,10 +308,48 @@ const toolDefinitions = [
259
308
  },
260
309
  description: "Split `response` into independently-verifiable sub-claims when it makes more than one assertion about different parts of the code. Each claim tracks its own filePaths/symbols, so one claim going stale (e.g. one function changed) doesn't discard the others that are still true. Skip this for a single-fact response — plain filePaths/symbols above already covers that case.",
261
310
  },
311
+ domain: {
312
+ type: "string",
313
+ description: "Tag this memory with a domain (e.g. 'auth', 'billing' — matches cognitive_map domains) so domain-scoped searches prefer it. Optional: when omitted and filePaths is set, Lemma auto-derives a domain from the first file via cognitive_map (or a lightweight path heuristic if the map was never built).",
314
+ },
315
+ derivedFrom: {
316
+ type: "array",
317
+ items: { type: "string" },
318
+ description: "Ids of memories this one depends on; stale if they go stale.",
319
+ },
262
320
  },
263
321
  required: ["query", "response"],
264
322
  },
265
323
  },
324
+ {
325
+ name: "verify_memory",
326
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
327
+ description: "Cheaply revalidate ids from a prior search_memory/store_memory result — batch hash-compare, no BM25/re-search. Each id comes back 'fresh', 'stale', or 'unknown' (purged/renamed, never reported as fresh). Accepts entry ids and claim ids together.",
328
+ inputSchema: {
329
+ type: "object",
330
+ properties: {
331
+ ids: { type: "array", items: { type: "string" }, description: "Entry and/or claim ids to revalidate, from a prior search_memory/store_memory result." },
332
+ semanticDiff: {
333
+ type: "boolean",
334
+ description: "Don't count a comment/whitespace-only change as stale.",
335
+ default: false,
336
+ },
337
+ },
338
+ required: ["ids"],
339
+ },
340
+ },
341
+ {
342
+ name: "downvote_memory",
343
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
344
+ description: "Tell the Brain a specific memory from a prior search_memory result was wrong or misleading in practice — not just irrelevant to skip, but actually acted on and it didn't hold up. Lowers that memory's future ranking and moves it toward eviction sooner, without deleting it (it may still be right for a different query later). Use the `id` from the search_memory result you're downvoting.",
345
+ inputSchema: {
346
+ type: "object",
347
+ properties: {
348
+ id: { type: "string", description: "The memory's id, from a prior search_memory result." },
349
+ },
350
+ required: ["id"],
351
+ },
352
+ },
266
353
  {
267
354
  name: "get_routing_advice",
268
355
  annotations: { readOnlyHint: true, openWorldHint: false },
@@ -357,6 +444,7 @@ const toolDefinitions = [
357
444
  {
358
445
  name: "run_workspace_command",
359
446
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
447
+ execution: { taskSupport: "optional" },
360
448
  description: "Execute a bash command in the workspace root. Default timeout 120s — raise it with timeoutMs for a full test or build run (max 600s). Captures both stdout and stderr, and returns whatever was produced even if the command times out. Long test/build/lint output is distilled deterministically — for jest, vitest and tsc it returns the failing tests or diagnostics with their locations and reasons, dropping code frames and node_modules stack frames; anything else falls back to head/tail plus error-matching lines. The complete output is always stored first and the reply carries a handle: nothing is lost, use output_region to retrieve any part verbatim. Pass raw:true to skip distillation.",
361
449
  inputSchema: {
362
450
  type: "object",
@@ -1390,6 +1478,8 @@ const toolHandlers = {
1390
1478
  scrub_privacy: handleScrubPrivacy,
1391
1479
  search_memory: handleSearchMemory,
1392
1480
  store_memory: handleStoreMemory,
1481
+ downvote_memory: handleDownvoteMemory,
1482
+ verify_memory: handleVerifyMemory,
1393
1483
  get_routing_advice: handleGetRoutingAdvice,
1394
1484
  auto_heal: handleAutoHeal,
1395
1485
  read_workspace_file: handleReadWorkspaceFile,
@@ -1539,7 +1629,7 @@ function setupToolsHandlers(server, onToolCall) {
1539
1629
  server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
1540
1630
  tools: toolDefinitionsArray,
1541
1631
  }));
1542
- server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
1632
+ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => {
1543
1633
  const { name, arguments: args } = request.params;
1544
1634
  const startTime = Date.now();
1545
1635
  // ── Pro License Gate (granular: free tools work without license) ────────
@@ -1568,6 +1658,39 @@ function setupToolsHandlers(server, onToolCall) {
1568
1658
  });
1569
1659
  throw new Error(`Unknown tool: ${name}`);
1570
1660
  }
1661
+ // ── Task-augmented call: hand off to tasks.ts instead of awaiting inline ────
1662
+ // A task-unaware client never sends `request.params.task`, so this only triggers when
1663
+ // the caller actually asked for it — today's synchronous behavior is unchanged otherwise.
1664
+ if (request.params.task && tasks_1.TASK_CAPABLE_TOOLS.has(name)) {
1665
+ const ledgerBefore = (0, TokenReceipt_1.getLedgerLength)();
1666
+ return (0, tasks_1.runAsTask)(name, (args || {}), request, extra.requestId, handler, (result, error) => {
1667
+ if (error) {
1668
+ onToolCall?.({
1669
+ tool: name,
1670
+ args: args || {},
1671
+ result: "ERROR",
1672
+ latency: Date.now() - startTime,
1673
+ error: error instanceof Error ? error.message.substring(0, 100) : String(error).substring(0, 100),
1674
+ });
1675
+ return;
1676
+ }
1677
+ if ((0, TokenReceipt_1.getLedgerLength)() === ledgerBefore) {
1678
+ (0, TokenReceipt_1.recordReceiptEvent)(receiptTypeForTool(name), name, {
1679
+ tool: name,
1680
+ ...receiptLabelMeta(name, args),
1681
+ });
1682
+ }
1683
+ const tokensImpact = (0, utils_1.estimateTokensFromResult)(result);
1684
+ onToolCall?.({
1685
+ tool: name,
1686
+ args: args || {},
1687
+ result: "OK",
1688
+ latency: Date.now() - startTime,
1689
+ tokensImpact,
1690
+ });
1691
+ (0, reportSavings_1.reportCost)({ source: "toolResult", tokens: tokensImpact, toolName: name });
1692
+ });
1693
+ }
1571
1694
  try {
1572
1695
  // Sampled around the handler so a tool that logs its own, more specific event
1573
1696
  // (a cache hit, a miss) isn't double-counted by the generic entry below.
@@ -1603,6 +1726,9 @@ function setupToolsHandlers(server, onToolCall) {
1603
1726
  throw error;
1604
1727
  }
1605
1728
  });
1729
+ // Registered after ListTools/CallTool: tests and other callers that assume "ListTools is
1730
+ // first, CallTool is second" (see tests/unit/tool-regressions.test.ts) key off that order.
1731
+ (0, tasks_1.registerTaskHandlers)(server);
1606
1732
  }
1607
1733
  // ── Tool Implementations ────────────────────────────────────────────
1608
1734
  async function handleScrubPrivacy(args) {
@@ -1626,11 +1752,13 @@ async function handleSearchMemory(args) {
1626
1752
  // formatting below then presents it as a reusable memory. Match smarter_cache's
1627
1753
  // threshold so both paths agree on what counts as a hit.
1628
1754
  const minSimilarity = typeof args?.minSimilarity === "number" ? args.minSimilarity : DEFAULT_MEMORY_SIMILARITY_FLOOR;
1755
+ const domain = typeof args?.domain === "string" && args.domain.trim() ? args.domain.trim() : undefined;
1756
+ const semanticDiff = args?.semanticDiff === true;
1629
1757
  if (!query)
1630
1758
  throw new Error("Query is required");
1631
1759
  try {
1632
1760
  const brain = (0, TheBrainV2_1.getBrain)();
1633
- const results = brain.search(query, limit, minSimilarity, { projectId: (0, TheBrainV2_1.deriveProjectId)() });
1761
+ const results = brain.search(query, limit, minSimilarity, { projectId: (0, TheBrainV2_1.deriveProjectId)(), domain, semanticDiff });
1634
1762
  if (results.length === 0) {
1635
1763
  (0, TokenReceipt_1.recordReceiptEvent)("reasoning", query.substring(0, 100), {
1636
1764
  tool: "search_memory",
@@ -1654,7 +1782,9 @@ async function handleSearchMemory(args) {
1654
1782
  const staleCount = r.claims.filter((c) => !c.fresh).length;
1655
1783
  return `\nClaims (${r.claims.length - staleCount}/${r.claims.length} still fresh — trust only the ✓ ones):\n${lines.join("\n")}`;
1656
1784
  };
1657
- const formatResult = (r, i) => `Result ${i + 1} (Similarity: ${(r.similarity * 100).toFixed(1)}%)${r.outcome === "failed" ? "\n⚠️ TAGGED AS A FAILED ATTEMPT — this was tried before and did NOT work. Do not repeat it; treat this as a warning, not a suggestion." : ""}\nPrompt: ${r.query.substring(0, 300)}...\nResponse: ${typeof r.response === "string" ? r.response : JSON.stringify(r.response, null, 2)}${formatClaims(r)}`;
1785
+ const formatResult = (r, i) => `Result ${i + 1} (id: ${r.id}, Similarity: ${(r.similarity * 100).toFixed(1)}%)${r.outcome === "failed" ? "\n⚠️ TAGGED AS A FAILED ATTEMPT — this was tried before and did NOT work. Do not repeat it; treat this as a warning, not a suggestion." : ""}\nPrompt: ${r.query.substring(0, 300)}...\nResponse: ${typeof r.response === "string" ? r.response : JSON.stringify(r.response, null, 2)}${formatClaims(r)}${Array.isArray(r.cosmeticChanges) && r.cosmeticChanges.length > 0
1786
+ ? `\n(comment/whitespace-only change, ignored under semanticDiff: ${r.cosmeticChanges.join(", ")})`
1787
+ : ""}`;
1658
1788
  if (fresh.length > 0) {
1659
1789
  // Only a fresh hit (or an untracked, purely conceptual entry) counts as a real
1660
1790
  // avoided re-investigation — this is the only case worth crediting as savings.
@@ -1702,11 +1832,18 @@ async function handleStoreMemory(args) {
1702
1832
  const claims = Array.isArray(args?.claims)
1703
1833
  ? args.claims.filter((c) => c?.text)
1704
1834
  : undefined;
1835
+ const explicitDomain = typeof args?.domain === "string" && args.domain.trim() ? args.domain.trim() : undefined;
1836
+ // Auto-derive from the first tracked file when the caller didn't say — see
1837
+ // deriveDomainForFile for why this is a best-effort tag, not a hard classification.
1838
+ const domain = explicitDomain || (filePaths && filePaths.length > 0 ? deriveDomainForFile(filePaths[0]) : undefined);
1839
+ const derivedFrom = Array.isArray(args?.derivedFrom)
1840
+ ? args.derivedFrom.filter((id) => typeof id === "string" && id)
1841
+ : undefined;
1705
1842
  if (!query || !responseText)
1706
1843
  throw new Error("Query and response are required");
1707
1844
  try {
1708
1845
  const brain = (0, TheBrainV2_1.getBrain)();
1709
- const storeRes = brain.store(query, responseText, provider, 0.92, filePaths, undefined, outcome, symbols, claims);
1846
+ const storeRes = brain.store(query, responseText, provider, 0.92, filePaths, undefined, outcome, symbols, claims, domain, derivedFrom);
1710
1847
  // Storing a memory saves nothing — it only creates the chance of a saving later.
1711
1848
  // Crediting tokens here inflated the ledger on write and then credited the same
1712
1849
  // answer again on every read. The saving is booked by search_memory on a fresh hit.
@@ -1719,13 +1856,63 @@ async function handleStoreMemory(args) {
1719
1856
  const symbolNote = symbols && symbols.length > 0 ? ` Tracking freshness against ${symbols.length} symbol(s) specifically — unrelated edits elsewhere in those files won't stale this out.` : "";
1720
1857
  const outcomeNote = outcome === "failed" ? " Tagged as a FAILED attempt — future searches will surface it as a warning, not a suggestion." : "";
1721
1858
  const claimsNote = claims && claims.length > 0 ? ` Split into ${claims.length} independently-verifiable claim(s) — a future search can trust the ones still fresh even if another goes stale.` : "";
1722
- return { content: [{ type: "text", text: `Success: Memory stored. ${storeRes.reason}${trackingNote}${symbolNote}${outcomeNote}${claimsNote}` }] };
1859
+ const domainNote = domain
1860
+ ? ` Tagged with domain '${domain}'${explicitDomain ? "" : " (auto-derived from filePaths)"} — domain-scoped searches will prefer it.`
1861
+ : "";
1862
+ const derivedFromNote = derivedFrom && derivedFrom.length > 0
1863
+ ? ` Derived from ${derivedFrom.length} prior memor${derivedFrom.length === 1 ? "y" : "ies"} — this one goes stale too if any of those do.`
1864
+ : "";
1865
+ const conflictsNote = storeRes.conflicts && storeRes.conflicts.length > 0
1866
+ ? `\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` +
1867
+ storeRes.conflicts.map((c) => ` - [${c.outcome}] ${c.id}: ${c.query.substring(0, 120)}`).join("\n")
1868
+ : "";
1869
+ return { content: [{ type: "text", text: `Success: Memory stored. ${storeRes.reason}${trackingNote}${symbolNote}${outcomeNote}${claimsNote}${domainNote}${derivedFromNote}${conflictsNote}` }] };
1723
1870
  }
1724
1871
  catch (e) {
1725
1872
  (0, utils_1.logError)("store_memory", e);
1726
1873
  return { content: [{ type: "text", text: `Failed to store memory in local Brain: ${e.message}` }] };
1727
1874
  }
1728
1875
  }
1876
+ async function handleDownvoteMemory(args) {
1877
+ const id = args?.id;
1878
+ if (!id)
1879
+ throw new Error("id is required");
1880
+ try {
1881
+ const result = (0, TheBrainV2_1.getBrain)().downvote(id);
1882
+ return { content: [{ type: "text", text: result.message }] };
1883
+ }
1884
+ catch (e) {
1885
+ (0, utils_1.logError)("downvote_memory", e);
1886
+ return { content: [{ type: "text", text: `Failed to downvote memory: ${e.message}` }] };
1887
+ }
1888
+ }
1889
+ async function handleVerifyMemory(args) {
1890
+ const ids = Array.isArray(args?.ids) ? args.ids.filter((id) => typeof id === "string" && id) : [];
1891
+ const semanticDiff = args?.semanticDiff === true;
1892
+ if (ids.length === 0)
1893
+ throw new Error("ids is required and must be a non-empty array");
1894
+ try {
1895
+ const results = (0, TheBrainV2_1.getBrain)().verifyByIds(ids, { semanticDiff });
1896
+ const fresh = results.filter((r) => r.status === "fresh");
1897
+ const stale = results.filter((r) => r.status === "stale");
1898
+ const unknown = results.filter((r) => r.status === "unknown");
1899
+ const formatOne = (r) => {
1900
+ const staleNote = r.staleFiles && r.staleFiles.length > 0 ? ` (changed: ${r.staleFiles.join(", ")})` : "";
1901
+ const cosmeticNote = r.cosmeticChanges && r.cosmeticChanges.length > 0 ? ` (cosmetic only, ignored: ${r.cosmeticChanges.join(", ")})` : "";
1902
+ const claimsNote = r.claimBreakdown && r.claimBreakdown.length > 0
1903
+ ? `\n Claims: ${r.claimBreakdown.map((c) => `${c.fresh ? "✓" : "✗"} ${c.text}`).join(" | ")}`
1904
+ : "";
1905
+ return `${r.id}: ${r.status}${staleNote}${cosmeticNote}${claimsNote}`;
1906
+ };
1907
+ const summary = `${fresh.length} fresh, ${stale.length} stale, ${unknown.length} unknown (of ${results.length} checked).`;
1908
+ const lines = results.map(formatOne).join("\n");
1909
+ return { content: [{ type: "text", text: `${summary}\n${lines}` }] };
1910
+ }
1911
+ catch (e) {
1912
+ (0, utils_1.logError)("verify_memory", e);
1913
+ return { content: [{ type: "text", text: `Failed to verify memory: ${e.message}` }] };
1914
+ }
1915
+ }
1729
1916
  async function handleGetRoutingAdvice(args) {
1730
1917
  const prompt = args?.prompt;
1731
1918
  const intendedModel = args?.intended_model;
@@ -1964,6 +2151,30 @@ function stripLineNumberGutter(text) {
1964
2151
  return text;
1965
2152
  return lines.map((l) => l.replace(GUTTER, "")).join("\n");
1966
2153
  }
2154
+ // Splices one resolved match into the file and writes it. Shared by the normal
2155
+ // single-match path and the ambiguous-match-resolved-via-elicitation path below.
2156
+ async function applyMatch(match, filePath, resolved, originalContent, searchContent, replaceContent) {
2157
+ let updatedContent;
2158
+ if (match.strategy === "exact" && match.charStart !== undefined && match.charEnd !== undefined) {
2159
+ // Splice by character offset — the search block may be a mid-line fragment, and
2160
+ // a whole-line splice would discard everything else sharing that line.
2161
+ updatedContent = originalContent.slice(0, match.charStart) + replaceContent + originalContent.slice(match.charEnd);
2162
+ }
2163
+ else {
2164
+ const contentLines = originalContent.split("\n");
2165
+ const finalReplace = (0, PatchMatcher_1.reindentReplacement)(replaceContent, searchContent, contentLines[match.startLine]);
2166
+ const updatedLines = [...contentLines.slice(0, match.startLine), ...finalReplace.split("\n"), ...contentLines.slice(match.endLine + 1)];
2167
+ updatedContent = updatedLines.join("\n");
2168
+ }
2169
+ const elicited = await tryElicitConfirmation(`Apply a patch to ${filePath}? This replaces ${searchContent.length} char(s) with ${replaceContent.length} char(s) ` +
2170
+ `starting at line ${match.startLine + 1}.`);
2171
+ if (elicited.supported && !elicited.confirmed) {
2172
+ return { content: [{ type: "text", text: `Patch to ${filePath} was not applied: declined during confirmation.` }] };
2173
+ }
2174
+ fs_1.default.writeFileSync(resolved, updatedContent, "utf8");
2175
+ const note = match.strategy === "exact" ? "" : ` (matched via ${match.strategy}, score ${match.score.toFixed(2)})`;
2176
+ return { content: [{ type: "text", text: `Success: Patch successfully applied to ${filePath}${note}` }] };
2177
+ }
1967
2178
  async function handleApplyWorkspacePatch(args) {
1968
2179
  const filePath = args?.filePath;
1969
2180
  const rawSearch = args?.searchContent;
@@ -1986,6 +2197,15 @@ async function handleApplyWorkspacePatch(args) {
1986
2197
  const matchResult = (0, PatchMatcher_1.findMatch)(originalContent, searchContent);
1987
2198
  if (!Array.isArray(matchResult)) {
1988
2199
  if (matchResult.reason === "ambiguous") {
2200
+ const candidates = matchResult.candidates ?? [];
2201
+ if (candidates.length > 0) {
2202
+ const chosen = await tryElicitChoice(`${candidates.length} equally good matches found for the search content in ${filePath}. Which one should be patched?`, candidates.map((c) => ({
2203
+ title: `line ${c.startLine + 1}: ${c.matchedText.split("\n")[0].slice(0, 80)}`,
2204
+ })));
2205
+ if (chosen.index !== null) {
2206
+ return applyMatch(candidates[chosen.index], filePath, resolved, originalContent, searchContent, replaceContent);
2207
+ }
2208
+ }
1989
2209
  return {
1990
2210
  content: [
1991
2211
  {
@@ -2014,33 +2234,71 @@ async function handleApplyWorkspacePatch(args) {
2014
2234
  ],
2015
2235
  };
2016
2236
  }
2017
- const match = matchResult[0];
2018
- let updatedContent;
2019
- if (match.strategy === "exact" && match.charStart !== undefined && match.charEnd !== undefined) {
2020
- // Splice by character offset — the search block may be a mid-line fragment, and
2021
- // a whole-line splice would discard everything else sharing that line.
2022
- updatedContent = originalContent.slice(0, match.charStart) + replaceContent + originalContent.slice(match.charEnd);
2023
- }
2024
- else {
2025
- const contentLines = originalContent.split("\n");
2026
- const finalReplace = (0, PatchMatcher_1.reindentReplacement)(replaceContent, searchContent, contentLines[match.startLine]);
2027
- const updatedLines = [...contentLines.slice(0, match.startLine), ...finalReplace.split("\n"), ...contentLines.slice(match.endLine + 1)];
2028
- updatedContent = updatedLines.join("\n");
2029
- }
2030
- const elicited = await tryElicitConfirmation(`Apply a patch to ${filePath}? This replaces ${searchContent.length} char(s) with ${replaceContent.length} char(s) ` +
2031
- `starting at line ${match.startLine + 1}.`);
2032
- if (elicited.supported && !elicited.confirmed) {
2033
- return { content: [{ type: "text", text: `Patch to ${filePath} was not applied: declined during confirmation.` }] };
2034
- }
2035
- fs_1.default.writeFileSync(resolved, updatedContent, "utf8");
2036
- const note = match.strategy === "exact" ? "" : ` (matched via ${match.strategy}, score ${match.score.toFixed(2)})`;
2037
- return { content: [{ type: "text", text: `Success: Patch successfully applied to ${filePath}${note}` }] };
2237
+ return applyMatch(matchResult[0], filePath, resolved, originalContent, searchContent, replaceContent);
2038
2238
  }
2039
2239
  catch (err) {
2040
2240
  (0, utils_1.logError)("apply_workspace_patch", err);
2041
2241
  return { content: [{ type: "text", text: `Error applying patch: ${err.message}` }] };
2042
2242
  }
2043
2243
  }
2244
+ // Async replacement for spawnSync: a blocking syscall inside a `tools/call` handler
2245
+ // freezes the whole (single-threaded) MCP server for the run's entire duration — including
2246
+ // task-status polls for THIS run once it's task-augmented (see runAsTask in tasks.ts), which
2247
+ // would otherwise defeat the point of making the tool pollable. `spawn` keeps the event loop
2248
+ // free while the command runs. Shape of the resolved value mirrors spawnSync's return value
2249
+ // on the fields the caller actually reads, so the rest of handleRunWorkspaceCommand is unchanged.
2250
+ function spawnCollect(command, cwd, timeoutMs) {
2251
+ return new Promise((resolve) => {
2252
+ const child = (0, child_process_1.spawn)(command, {
2253
+ cwd,
2254
+ shell: true,
2255
+ env: { ...process.env },
2256
+ // spawnSync closed stdin immediately (no `input` option given), so a command reading
2257
+ // from stdin (e.g. `sed` with no file argument) saw EOF right away. Plain `spawn`
2258
+ // leaves stdin as an open pipe by default — nothing ever writes to or closes it — so
2259
+ // the same command hangs until the timeout kills it. "ignore" reproduces the old,
2260
+ // immediate-EOF behavior.
2261
+ stdio: ["ignore", "pipe", "pipe"],
2262
+ });
2263
+ let stdout = "";
2264
+ let stderr = "";
2265
+ let stdoutBytes = 0;
2266
+ let stderrBytes = 0;
2267
+ const MAX_BUFFER = 20 * 1024 * 1024;
2268
+ let timedOut = false;
2269
+ let settled = false;
2270
+ const timer = setTimeout(() => {
2271
+ timedOut = true;
2272
+ child.kill("SIGTERM");
2273
+ }, timeoutMs);
2274
+ child.stdout?.on("data", (chunk) => {
2275
+ if (stdoutBytes >= MAX_BUFFER)
2276
+ return;
2277
+ stdoutBytes += chunk.length;
2278
+ stdout += chunk.toString("utf8");
2279
+ });
2280
+ child.stderr?.on("data", (chunk) => {
2281
+ if (stderrBytes >= MAX_BUFFER)
2282
+ return;
2283
+ stderrBytes += chunk.length;
2284
+ stderr += chunk.toString("utf8");
2285
+ });
2286
+ child.on("error", (err) => {
2287
+ if (settled)
2288
+ return;
2289
+ settled = true;
2290
+ clearTimeout(timer);
2291
+ resolve({ stdout, stderr, status: null, timedOut, error: err });
2292
+ });
2293
+ child.on("close", (code) => {
2294
+ if (settled)
2295
+ return;
2296
+ settled = true;
2297
+ clearTimeout(timer);
2298
+ resolve({ stdout, stderr, status: code, timedOut });
2299
+ });
2300
+ });
2301
+ }
2044
2302
  async function handleRunWorkspaceCommand(args) {
2045
2303
  const command = args?.command;
2046
2304
  if (!command)
@@ -2070,10 +2328,10 @@ async function handleRunWorkspaceCommand(args) {
2070
2328
  // ── End allowlist check ────────────────────────────────────────────────
2071
2329
  const workspaceRoot = process.cwd();
2072
2330
  try {
2073
- // spawnSync rather than execSync: execSync leaves stderr attached to the parent unless
2074
- // stdio is overridden, which silently dropped the output of every tool that reports on
2075
- // stderr (jest and tsc both do) on a successful run. It also gives us stdout, stderr and
2076
- // the exit code through one code path instead of a throw-on-failure split.
2331
+ // spawn (via spawnCollect above) rather than execSync: execSync leaves stderr attached to
2332
+ // the parent unless stdio is overridden, which silently dropped the output of every tool
2333
+ // that reports on stderr (jest and tsc both do) on a successful run. It also gives us
2334
+ // stdout, stderr and the exit code through one code path instead of a throw-on-failure split.
2077
2335
  // 15s was below the runtime of the commands this tool exists for: a real `npm test` or
2078
2336
  // `tsc --noEmit` always tripped it, so the distillation pipeline never ran on the output
2079
2337
  // it was built for and the call was pure overhead before falling back to a plain shell.
@@ -2085,15 +2343,8 @@ async function handleRunWorkspaceCommand(args) {
2085
2343
  if (elicited.supported && !elicited.confirmed) {
2086
2344
  return { content: [{ type: "text", text: `Command was not run: declined during confirmation.\n\nCommand: ${command}` }] };
2087
2345
  }
2088
- const result = (0, child_process_1.spawnSync)(command, {
2089
- cwd: workspaceRoot,
2090
- shell: true,
2091
- encoding: "utf8",
2092
- timeout: timeoutMs,
2093
- maxBuffer: 20 * 1024 * 1024,
2094
- env: { ...process.env },
2095
- });
2096
- const timedOut = !!result.error && result.error.code === "ETIMEDOUT";
2346
+ const result = await spawnCollect(command, workspaceRoot, timeoutMs);
2347
+ const timedOut = result.timedOut;
2097
2348
  if (result.error && !timedOut) {
2098
2349
  return {
2099
2350
  content: [{ type: "text", text: `Command could not be executed: ${result.error.message}` }],
@@ -5006,6 +5257,37 @@ async function handleSmartFileSlice(args) {
5006
5257
  }
5007
5258
  }
5008
5259
  // ── Test Oracle ──────────────────────────────────────────────────────
5260
+ /**
5261
+ * Auto-capture a green test run into the Brain, tagged `outcome: 'confirmed'` and tracked
5262
+ * against the files actually changed. This is the auto-store hook: today store_memory only
5263
+ * fires when the agent remembers to call it, so working fixes routinely go uncaptured. A
5264
+ * passing suite over an uncommitted diff is real, cheap evidence something worked — reusing
5265
+ * it costs nothing store_memory wouldn't have cost anyway, and store()'s own dedup guard
5266
+ * means re-running the same green suite repeatedly just no-ops instead of piling up entries.
5267
+ *
5268
+ * Silent on a clean tree (nothing changed, nothing to attribute the pass to) or when the
5269
+ * repo isn't git-tracked. Returns a short suffix for resultText — this must never happen
5270
+ * invisibly, or a future search_memory hit would look reasoned-from-scratch instead of
5271
+ * traced back to an automated test run.
5272
+ */
5273
+ function autoStoreGreenTests(command, workspaceRoot) {
5274
+ try {
5275
+ const changed = (0, AffectedTests_1.changedFilesFromGit)(workspaceRoot);
5276
+ if (changed.length === 0)
5277
+ return "";
5278
+ const domain = deriveDomainForFile(changed[0]);
5279
+ const query = `tests passing after changes to ${changed.slice(0, 5).join(", ")}${changed.length > 5 ? ` and ${changed.length - 5} more file(s)` : ""}`;
5280
+ const response = `\`${command}\` passed with these files changed (uncommitted at capture time):\n${changed.join("\n")}`;
5281
+ const storeRes = (0, TheBrainV2_1.getBrain)().store(query, response, "test_oracle_auto", 0.92, changed, undefined, "confirmed", undefined, undefined, domain);
5282
+ if (!storeRes.stored)
5283
+ return "";
5284
+ 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.`;
5285
+ }
5286
+ catch {
5287
+ // Never let auto-capture break the actual test result the caller asked for.
5288
+ return "";
5289
+ }
5290
+ }
5009
5291
  async function handleTestOracle(args) {
5010
5292
  const command = args.command || "npm test";
5011
5293
  const workspaceRoot = process.cwd();
@@ -5016,6 +5298,7 @@ async function handleTestOracle(args) {
5016
5298
  try {
5017
5299
  const out = (0, child_process_1.execSync)(command, { cwd: workspaceRoot, encoding: "utf8", timeout: 30000 });
5018
5300
  resultText = `All tests passed!\n\nOutput:\n${out.substring(0, 1000)}`;
5301
+ resultText += autoStoreGreenTests(command, workspaceRoot);
5019
5302
  }
5020
5303
  catch (e) {
5021
5304
  const stdout = e.stdout || "";
@@ -5331,6 +5614,41 @@ async function handleFileIntentIndex(args) {
5331
5614
  }
5332
5615
  }
5333
5616
  const COG_MAP_FILE = path_1.default.join(os_1.default.homedir(), ".lemma-cache", "cog_map.json");
5617
+ /**
5618
+ * Best-effort domain for a repo-relative file path, so store_memory and the test-oracle
5619
+ * auto-store below don't require a human to type `domain` by hand every time.
5620
+ *
5621
+ * Prefers the persisted Cognitive Map (built via `cognitive_map` action "build") when it
5622
+ * has this exact file listed — that reflects an actual workspace scan. Falls back to the
5623
+ * same lightweight substring heuristic "build" uses, so a project that never ran "build"
5624
+ * still gets a reasonable tag instead of none at all. Returns undefined rather than
5625
+ * "general" when nothing matches — an absent domain stays visible to every domain-scoped
5626
+ * search (see BrainEntry.domain), while a wrong guess would actively mislead one.
5627
+ */
5628
+ function deriveDomainForFile(relPath) {
5629
+ const norm = relPath.replace(/^\//, "");
5630
+ if (fs_1.default.existsSync(COG_MAP_FILE)) {
5631
+ try {
5632
+ const map = JSON.parse(fs_1.default.readFileSync(COG_MAP_FILE, "utf8"));
5633
+ for (const node of Object.values(map.nodes || {})) {
5634
+ if (node.files.includes(norm))
5635
+ return node.domain;
5636
+ }
5637
+ }
5638
+ catch { /* fall through to heuristic */ }
5639
+ }
5640
+ if (norm.includes("mcp"))
5641
+ return "mcp";
5642
+ if (norm.includes("subconscious") || norm.includes("brain"))
5643
+ return "memory";
5644
+ if (norm.includes("security") || norm.includes("scrubber"))
5645
+ return "security";
5646
+ if (norm.includes("pr-review"))
5647
+ return "pr-review";
5648
+ if (norm.includes("utils"))
5649
+ return "utils";
5650
+ return undefined;
5651
+ }
5334
5652
  async function handleCognitiveMap(args) {
5335
5653
  const action = args.action;
5336
5654
  const domain = args.domain;