toon-memory 4.2.0 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/setup.js CHANGED
@@ -421,6 +421,14 @@ function dumpMemoryMarkdown() {
421
421
  // src/cli/config-writer.ts
422
422
  import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
423
423
  import { dirname as dirname3 } from "path";
424
+ function loadJSON(file) {
425
+ if (!existsSync5(file)) return {};
426
+ try {
427
+ return JSON.parse(readFileSync5(file, "utf-8"));
428
+ } catch {
429
+ return null;
430
+ }
431
+ }
424
432
  function installJSONConfig(agent, scope) {
425
433
  const configPath = scope === "global" ? agent.global : agent.local;
426
434
  if (!configPath) {
@@ -429,13 +437,10 @@ function installJSONConfig(agent, scope) {
429
437
  }
430
438
  const configDir = dirname3(configPath);
431
439
  if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
432
- let config = {};
433
- if (existsSync5(configPath)) {
434
- try {
435
- config = JSON.parse(readFileSync5(configPath, "utf-8"));
436
- } catch {
437
- config = {};
438
- }
440
+ const config = loadJSON(configPath);
441
+ if (config === null) {
442
+ console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
443
+ return;
439
444
  }
440
445
  const mcpKey = agent.mcpKey || "mcpServers";
441
446
  if (!config[mcpKey]) config[mcpKey] = {};
@@ -483,9 +488,13 @@ function installZedConfig(agent) {
483
488
  const stripped = raw.replace(/\/\/.*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
484
489
  config = JSON.parse(stripped);
485
490
  } catch {
486
- config = {};
491
+ config = null;
487
492
  }
488
493
  }
494
+ if (config === null) {
495
+ console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
496
+ return;
497
+ }
489
498
  if (!config.context_servers) config.context_servers = {};
490
499
  config.context_servers["toon-memory"] = {
491
500
  command: "npx",
@@ -500,13 +509,10 @@ function installContinueConfig(agent) {
500
509
  if (!configPath) return;
501
510
  const configDir = dirname3(configPath);
502
511
  if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
503
- let config = {};
504
- if (existsSync5(configPath)) {
505
- try {
506
- config = JSON.parse(readFileSync5(configPath, "utf-8"));
507
- } catch {
508
- config = {};
509
- }
512
+ const config = loadJSON(configPath);
513
+ if (config === null) {
514
+ console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
515
+ return;
510
516
  }
511
517
  if (!config.experimental) config.experimental = {};
512
518
  if (!config.experimental.modelContextProtocolServers) {
@@ -534,13 +540,10 @@ function installOpenClawConfig(agent) {
534
540
  if (!configPath) return;
535
541
  const configDir = dirname3(configPath);
536
542
  if (!existsSync5(configDir)) mkdirSync3(configDir, { recursive: true });
537
- let config = {};
538
- if (existsSync5(configPath)) {
539
- try {
540
- config = JSON.parse(readFileSync5(configPath, "utf-8"));
541
- } catch {
542
- config = {};
543
- }
543
+ const config = loadJSON(configPath);
544
+ if (config === null) {
545
+ console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
546
+ return;
544
547
  }
545
548
  if (!config.mcp) config.mcp = {};
546
549
  if (!config.mcp.servers) config.mcp.servers = {};
@@ -611,6 +614,14 @@ ${content}`);
611
614
  // src/cli/hooks.ts
612
615
  import { existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync7, writeFileSync as writeFileSync5, chmodSync } from "fs";
613
616
  import { dirname as dirname5, join as join5 } from "path";
617
+ function readJSON(file) {
618
+ if (!existsSync7(file)) return {};
619
+ try {
620
+ return JSON.parse(readFileSync7(file, "utf-8"));
621
+ } catch {
622
+ return null;
623
+ }
624
+ }
614
625
  function sessionStartHookContent(agentName) {
615
626
  return `#!/bin/bash
616
627
  # toon-memory session-start hook for ${agentName}
@@ -665,13 +676,10 @@ function registerCaptureHookJSON(agent, scriptPath) {
665
676
  if (!configPath) return;
666
677
  const configDir = dirname5(configPath);
667
678
  if (!existsSync7(configDir)) mkdirSync5(configDir, { recursive: true });
668
- let config = {};
669
- if (existsSync7(configPath)) {
670
- try {
671
- config = JSON.parse(readFileSync7(configPath, "utf-8"));
672
- } catch {
673
- config = {};
674
- }
679
+ const config = readJSON(configPath);
680
+ if (config === null) {
681
+ console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
682
+ return;
675
683
  }
676
684
  if (!config.hooks) config.hooks = {};
677
685
  for (const event of agent.captureJson || []) {
@@ -730,9 +738,13 @@ function registerHookJSON(agent, hookPath) {
730
738
  config = JSON.parse(readFileSync7(configPath, "utf-8"));
731
739
  }
732
740
  } catch {
733
- config = {};
741
+ config = null;
734
742
  }
735
743
  }
744
+ if (config === null) {
745
+ console.log(` \u26A0\uFE0F Skipping ${configPath}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
746
+ return;
747
+ }
736
748
  if (agent.name === "claude" || agent.name === "gemini") {
737
749
  if (!config.hooks) config.hooks = {};
738
750
  if (!config.hooks.SessionStart) config.hooks.SessionStart = [];
@@ -763,9 +775,13 @@ function registerAntigravityHooks(agent) {
763
775
  try {
764
776
  cfg = JSON.parse(readFileSync7(hooksFile, "utf-8"));
765
777
  } catch {
766
- cfg = {};
778
+ cfg = null;
767
779
  }
768
780
  }
781
+ if (cfg === null) {
782
+ console.log(` \u26A0\uFE0F Skipping ${hooksFile}: existing file is not valid JSON \u2014 fix it manually, then re-run.`);
783
+ return;
784
+ }
769
785
  cfg[ANTIGRAVITY_HOOK_NAME] = {
770
786
  PreInvocation: [{ type: "command", command: sessionPath }],
771
787
  PostToolUse: [{ matcher: "*", hooks: [{ type: "command", command: capPath }] }],
@@ -794,6 +810,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
794
810
  const recall = async (query, opts = {}) => {
795
811
  try {
796
812
  const args = { query, mode: "flat", budget: opts.budget || "tiny", path_scope: opts.path_scope || "" }
813
+ if (opts.category) args.category = opts.category
797
814
  const result = await $\`npx -y toon-memory mcp\`.cwd(root)
798
815
  .stdin(JSON.stringify({
799
816
  jsonrpc: "2.0",
@@ -807,11 +824,44 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
807
824
  } catch { return "" }
808
825
  }
809
826
 
827
+ // Pre-edit risk surfacing: warning-category entries scoped to a file path.
828
+ // Injected as a distinct block so the agent sees known risks before it edits.
829
+ const risks = async (filePath) => {
830
+ return await recall(filePath, { budget: "tiny", path_scope: filePath, category: "warning" })
831
+ }
832
+
810
833
  const write = (text) => {
811
834
  fs.mkdirSync(INS, { recursive: true })
812
835
  fs.writeFileSync(OUT, text)
813
836
  }
814
837
 
838
+ const pickPath = (args) => {
839
+ if (!args) return ""
840
+ if (args.file) return args.file
841
+ if (args.path) return args.path
842
+ if (args.filePath) return args.filePath
843
+ if (args.target) return args.target
844
+ return ""
845
+ }
846
+
847
+ const buildQuery = (filePath) => {
848
+ const basename = path.basename(filePath, path.extname(filePath))
849
+ const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
850
+ return [basename, ...dirParts.slice(-2)].join(" ")
851
+ }
852
+
853
+ const inject = (ctx, key, text) => {
854
+ if (!text || text.includes("(empty)") || text.includes("No results")) return
855
+ if (typeof ctx?.setContext === "function") ctx.setContext(key, text)
856
+ }
857
+
858
+ // Edit/write-ish tools are where known risks matter most.
859
+ const isEditTool = (name) => {
860
+ if (!name) return false
861
+ return name === "edit" || name === "write" || name === "apply-patch" ||
862
+ name.includes("edit") || name.includes("write") || name.includes("patch")
863
+ }
864
+
815
865
  return {
816
866
  "session.created": async () => {
817
867
  try {
@@ -825,6 +875,19 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
825
875
  if (Array.isArray(output?.context)) output.context.push(out)
826
876
  } catch {}
827
877
  },
878
+ "tool.execute.before": async (input, output) => {
879
+ // Pre-edit risk surfacing: for edit/write tools, surface known
880
+ // warning entries for the target file BEFORE the tool runs.
881
+ try {
882
+ const toolName = input?.tool || ""
883
+ if (!isEditTool(toolName)) return
884
+ const args = output?.args || input?.args || {}
885
+ const filePath = pickPath(args)
886
+ if (!filePath) return
887
+ const text = await risks(filePath)
888
+ inject(input, "toon-memory:risks:" + filePath, "\u26A0 KNOWN RISKS for " + filePath + ":\\n" + text)
889
+ } catch {}
890
+ },
828
891
  "tool.execute.after": async (input) => {
829
892
  // Intelligent auto-loading: extract file path from tool result,
830
893
  // recall only memory relevant to that file, inject as context.
@@ -834,11 +897,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
834
897
  const args = input?.args || {}
835
898
 
836
899
  // Extract file path from tool arguments or output
837
- let filePath = ""
838
- if (args.file) filePath = args.file
839
- else if (args.path) filePath = args.path
840
- else if (args.filePath) filePath = args.filePath
841
- else if (args.target) filePath = args.target
900
+ let filePath = pickPath(args)
842
901
 
843
902
  // Also try to extract from tool output text
844
903
  if (!filePath && input?.output) {
@@ -849,15 +908,15 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
849
908
 
850
909
  if (filePath) {
851
910
  // Build recall query from file path components
852
- const basename = path.basename(filePath, path.extname(filePath))
853
- const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
854
- const query = [basename, ...dirParts.slice(-2)].join(" ")
855
-
911
+ const query = buildQuery(filePath)
856
912
  const text = await recall(query, { budget: "tiny", path_scope: filePath })
857
- if (text && !text.includes("(empty)") && !text.includes("No results")) {
858
- if (typeof input?.setContext === "function") {
859
- input.setContext("toon-memory:" + filePath, text)
860
- }
913
+ inject(input, "toon-memory:" + filePath, text)
914
+
915
+ // Pre-edit risk block for edit/write tools (same key as the before
916
+ // hook \u2014 setContext overwrites, so no duplication when both fire).
917
+ if (isEditTool(toolName)) {
918
+ const riskText = await risks(filePath)
919
+ inject(input, "toon-memory:risks:" + filePath, "\u26A0 KNOWN RISKS for " + filePath + ":\\n" + riskText)
861
920
  }
862
921
  }
863
922
 
@@ -875,11 +934,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
875
934
 
876
935
  if (toolKeywords.length > 3) {
877
936
  const text = await recall(toolKeywords, { budget: "tiny" })
878
- if (text && !text.includes("(empty)") && !text.includes("No results")) {
879
- if (typeof input?.setContext === "function") {
880
- input.setContext("toon-memory:" + toolName, text)
881
- }
882
- }
937
+ inject(input, "toon-memory:" + toolName, text)
883
938
  }
884
939
  }
885
940
  } catch {}
@@ -1669,7 +1724,8 @@ function parseEntries(data) {
1669
1724
  path_scope: parts.length > 14 ? parts[14] || "" : "",
1670
1725
  origin: parts.length > 15 && parts[15] ? parts[15] : "agent",
1671
1726
  status: parts.length > 16 && parts[16] ? parts[16] : "active",
1672
- supersededOn: parts.length > 17 ? parts[17] || "" : ""
1727
+ supersededOn: parts.length > 17 ? parts[17] || "" : "",
1728
+ importance: parts.length > 18 ? parts[18] || "" : ""
1673
1729
  });
1674
1730
  }
1675
1731
  return out;
@@ -1,11 +1,20 @@
1
1
  // src/cli/toon-memory.ts
2
- import { dirname, join } from "path";
2
+ import { dirname } from "path";
3
3
  import { fileURLToPath } from "url";
4
+
5
+ // src/cli/entry.ts
6
+ import { join } from "path";
7
+ import { pathToFileURL } from "url";
8
+ function fileImportURL(dirname2, ...parts) {
9
+ return pathToFileURL(join(dirname2, ...parts)).href;
10
+ }
11
+
12
+ // src/cli/toon-memory.ts
4
13
  var __dirname = dirname(fileURLToPath(import.meta.url));
5
14
  var args = process.argv.slice(2);
6
15
  if (args[0] === "mcp") {
7
- await import(join(__dirname, "..", "mcp", "server.js"));
16
+ await import(fileImportURL(__dirname, "..", "mcp", "server.js"));
8
17
  } else {
9
18
  process.argv = ["node", "toon-memory", ...args];
10
- await import(join(__dirname, "..", "dist", "cli", "setup.js"));
19
+ await import(fileImportURL(__dirname, "..", "dist", "cli", "setup.js"));
11
20
  }
package/install.ps1 CHANGED
@@ -1,18 +1,24 @@
1
1
  # toon-memory installer for Windows (PowerShell)
2
2
  # Usage: irm https://raw.githubusercontent.com/LuiggiVal08/toon-memory/main/install.ps1 | iex
3
3
 
4
- $TOON_VERSION = "1.0.9"
5
- # SHA-256 checksum of the tarball. Update on each release.
6
- # Generate with: certutil -hashfile toon-memory-$TOON_VERSION.tgz SHA256
7
- $TOON_CHECKSUM = "d5b2a8cbe0f3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9"
8
-
9
4
  Write-Host "🧠 toon-memory installer" -ForegroundColor Cyan
10
5
  Write-Host ""
11
6
 
7
+ # Resolve the latest version + integrity from the npm registry (mirrors install.sh)
8
+ try {
9
+ $meta = Invoke-RestMethod -Uri "https://registry.npmjs.org/toon-memory/latest" -ErrorAction Stop
10
+ $TOON_VERSION = $meta.version
11
+ $integrity = $meta.dist.integrity
12
+ } catch {
13
+ Write-Host "Error: Could not determine latest toon-memory version." -ForegroundColor Red
14
+ Write-Host "You can install manually: npm install -g toon-memory"
15
+ exit 1
16
+ }
17
+
12
18
  # Check if npm is available
13
19
  if (Get-Command npm -ErrorAction SilentlyContinue) {
14
- Write-Host "Installing toon-memory via npm..."
15
- npm install -g toon-memory@$TOON_VERSION
20
+ Write-Host "Installing toon-memory v$TOON_VERSION via npm..."
21
+ npm install -g "toon-memory@$TOON_VERSION"
16
22
  Write-Host ""
17
23
  Write-Host "✅ toon-memory installed!" -ForegroundColor Green
18
24
  Write-Host ""
@@ -35,15 +41,19 @@ if (Get-Command npm -ErrorAction SilentlyContinue) {
35
41
  $tgzPath = "$INSTALL_DIR\toon-memory.tgz"
36
42
  Invoke-WebRequest -Uri $url -OutFile $tgzPath
37
43
 
38
- # Verify integrity
39
- $actualHash = (Get-FileHash -Path $tgzPath -Algorithm SHA256).Hash.ToLower()
40
- if ($actualHash -ne $TOON_CHECKSUM) {
41
- Write-Host "❌ Checksum mismatch! Expected $TOON_CHECKSUM, got $actualHash" -ForegroundColor Red
42
- Write-Host "The downloaded file may be corrupted or tampered with." -ForegroundColor Red
43
- Remove-Item -Path $tgzPath -Force
44
- exit 1
44
+ # Verify integrity (npm dist.integrity is "sha512-<base64>"; compare against SHA512 hex)
45
+ if ($integrity -and $integrity.StartsWith("sha512-")) {
46
+ $expectedHex = -join ([Convert]::FromBase64String($integrity.Substring(7)) | ForEach-Object { $_.ToString("x2") })
47
+ $actualHash = (Get-FileHash -Path $tgzPath -Algorithm SHA512).Hash.ToLower()
48
+ if ($actualHash -ne $expectedHex.ToLower()) {
49
+ Write-Host "❌ Integrity check failed! The downloaded file may be corrupted or tampered with." -ForegroundColor Red
50
+ Remove-Item -Path $tgzPath -Force
51
+ exit 1
52
+ }
53
+ Write-Host "✅ Integrity verified" -ForegroundColor Green
54
+ } else {
55
+ Write-Host "⚠️ No sha512 integrity available from the registry; skipping verification" -ForegroundColor Yellow
45
56
  }
46
- Write-Host "✅ Integrity verified" -ForegroundColor Green
47
57
 
48
58
  # Extract
49
59
  cd $INSTALL_DIR
package/mcp/server.js CHANGED
@@ -21994,7 +21994,7 @@ function importance(e, today = (/* @__PURE__ */ new Date()).toISOString().split(
21994
21994
  const freq = Math.min(1, e.accessed / 5);
21995
21995
  return recency * 0.6 + freq * 0.4;
21996
21996
  }
21997
- var normalize, isExpiredLocal, tokenize, estimateTokens, languageFamily, escField, unescField, parseToonLine, toToonLine, isPrivate;
21997
+ var normalize, isExpiredLocal, IMPORTANCE_BOOST, importanceBoost, importanceRank, tokenize, estimateTokens, languageFamily, escField, unescField, parseToonLine, toToonLine, isPrivate;
21998
21998
  var init_utils = __esm({
21999
21999
  "src/lib/utils.ts"() {
22000
22000
  "use strict";
@@ -22003,6 +22003,19 @@ var init_utils = __esm({
22003
22003
  if (!ttl) return false;
22004
22004
  return ttl <= today;
22005
22005
  };
22006
+ IMPORTANCE_BOOST = {
22007
+ critical: 0.3,
22008
+ high: 0.15,
22009
+ medium: 0,
22010
+ low: -0.1
22011
+ };
22012
+ importanceBoost = (level) => IMPORTANCE_BOOST[level] ?? 0;
22013
+ importanceRank = (level) => {
22014
+ if (level === "critical") return 4;
22015
+ if (level === "high") return 3;
22016
+ if (level === "low") return 1;
22017
+ return 2;
22018
+ };
22006
22019
  tokenize = (s2) => s2.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
22007
22020
  estimateTokens = (s2) => {
22008
22021
  if (!s2) return 0;
@@ -22284,7 +22297,8 @@ function parseEntries(data) {
22284
22297
  path_scope: parts.length > 14 ? parts[14] || "" : "",
22285
22298
  origin: parts.length > 15 && parts[15] ? parts[15] : "agent",
22286
22299
  status: parts.length > 16 && parts[16] ? parts[16] : "active",
22287
- supersededOn: parts.length > 17 ? parts[17] || "" : ""
22300
+ supersededOn: parts.length > 17 ? parts[17] || "" : "",
22301
+ importance: parts.length > 18 ? parts[18] || "" : ""
22288
22302
  });
22289
22303
  }
22290
22304
  return out;
@@ -22475,6 +22489,7 @@ function buildReason(e, bm25Score, bm25Max, impScore, today = (/* @__PURE__ */ n
22475
22489
  parts.push("never used");
22476
22490
  }
22477
22491
  parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW");
22492
+ if (e.importance) parts.push(`explicit ${e.importance}`);
22478
22493
  return parts.join(" \xB7 ");
22479
22494
  }
22480
22495
  function graphRecallDetailed(data, query, opts = {}) {
@@ -22524,8 +22539,11 @@ function graphRecallDetailed(data, query, opts = {}) {
22524
22539
  scored.push(
22525
22540
  ...visibleEntries.sort((a, b2) => {
22526
22541
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22542
+ const ia2 = importanceRank(a.importance);
22543
+ const ib2 = importanceRank(b2.importance);
22544
+ if (ia2 !== ib2) return ib2 - ia2;
22527
22545
  return importance(b2, opts.today) - importance(a, opts.today);
22528
- }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) }))
22546
+ }).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e, opts.today) + importanceBoost(e.importance) }))
22529
22547
  );
22530
22548
  } else {
22531
22549
  const best = /* @__PURE__ */ new Map();
@@ -22559,6 +22577,7 @@ function graphRecallDetailed(data, query, opts = {}) {
22559
22577
  }
22560
22578
  }
22561
22579
  if (e.category === "warning") s2 += 0.2;
22580
+ s2 += importanceBoost(e.importance);
22562
22581
  s2 *= decay;
22563
22582
  return { e, s: s2, priority: e.priority };
22564
22583
  }).sort((a, b2) => {
@@ -22595,6 +22614,25 @@ function graphRecallDetailed(data, query, opts = {}) {
22595
22614
  }
22596
22615
  return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons };
22597
22616
  }
22617
+ function fetchEntriesByIds(data, tokens, opts = {}) {
22618
+ const byId = /* @__PURE__ */ new Map();
22619
+ const byKey = /* @__PURE__ */ new Map();
22620
+ const asOf = opts.asOf || "";
22621
+ for (const e of parseEntries(data)) {
22622
+ const visible = e.status === "active" || e.status === "resolved" || asOf && e.status === "obsolete" && e.supersededOn && e.supersededOn > asOf;
22623
+ if (!visible) continue;
22624
+ if (asOf && e.date && e.date > asOf) continue;
22625
+ if (e.ttl && isExpiredLocal(e.ttl, opts.today)) continue;
22626
+ if (!byId.has(e.id)) byId.set(e.id, e);
22627
+ if (!byKey.has(e.key)) byKey.set(e.key, e);
22628
+ }
22629
+ const out = [];
22630
+ for (const t of tokens) {
22631
+ const e = byKey.get(t) || byId.get(t);
22632
+ if (e && !out.includes(e)) out.push(e);
22633
+ }
22634
+ return out;
22635
+ }
22598
22636
  function globMatch(pattern, target) {
22599
22637
  if (!pattern) return true;
22600
22638
  if (pattern.startsWith("/")) pattern = pattern.slice(1);
@@ -22635,9 +22673,10 @@ function renderCompact(entries, opts = {}) {
22635
22673
  const scopeInfo = e.path_scope ? ` \xB7 scope: ${e.path_scope}` : "";
22636
22674
  const statusInfo = e.status !== "active" ? ` \xB7 status: ${e.status}` : "";
22637
22675
  const supersededInfo = e.supersededOn ? ` \xB7 superseded: ${e.supersededOn}` : "";
22676
+ const impInfo = e.importance ? ` \xB7 importance: ${e.importance}` : "";
22638
22677
  block = `[${n}] ${e.category}/${e.key}${pin} (${e.id})
22639
22678
  ${e.content}
22640
- File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${links}`;
22679
+ File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}${impInfo}${links}`;
22641
22680
  } else {
22642
22681
  let body = e.content;
22643
22682
  if (!isSeed && e.content.length > snippetLen) {
@@ -22666,6 +22705,24 @@ function renderCompact(entries, opts = {}) {
22666
22705
  }
22667
22706
  return rendered.join("\n\n");
22668
22707
  }
22708
+ function renderIndex(entries, opts = {}) {
22709
+ let max = 0;
22710
+ if (opts.scores) {
22711
+ for (const v3 of opts.scores.values()) if (v3 > max) max = v3;
22712
+ }
22713
+ const lines = [];
22714
+ for (let i = 0; i < entries.length; i++) {
22715
+ const e = entries[i];
22716
+ const pin = e.priority > 0 ? e.priority > 1 ? ` \u{1F4CC}${e.priority}` : " \u{1F4CC}" : "";
22717
+ let score = "";
22718
+ if (opts.scores && max > 0) {
22719
+ const s2 = opts.scores.get(e.key);
22720
+ if (s2 !== void 0) score = ` \xB7 ${Math.round(s2 / max * 100)}%`;
22721
+ }
22722
+ lines.push(`[${i + 1}] ${e.key} (${e.id})${pin} \xB7 ${e.category} \xB7 ${e.date}${score}`);
22723
+ }
22724
+ return lines.join("\n");
22725
+ }
22669
22726
  var DEFAULT_EDGE_TYPE, entryLines, W_CENT, W_IMP, SEED_BONUS, DECAY;
22670
22727
  var init_graph = __esm({
22671
22728
  "src/lib/graph.ts"() {
@@ -22781,7 +22838,10 @@ function mergeEntries(existingLine, newLine) {
22781
22838
  const newStatus = np2.length > 16 ? np2[16] || "" : "";
22782
22839
  const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active";
22783
22840
  const existingSupersededOn = ep2.length > 17 ? ep2[17] || "" : "";
22784
- return toToonLine([id2, category, key, content, file2, mergedTags, date5, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn]);
22841
+ const existingImportance = ep2.length > 18 ? ep2[18] || "" : "";
22842
+ const newImportance = np2.length > 18 ? np2[18] || "" : "";
22843
+ const importance2 = importanceRank(newImportance) >= importanceRank(existingImportance) ? newImportance : existingImportance;
22844
+ return toToonLine([id2, category, key, content, file2, mergedTags, date5, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn, importance2]);
22785
22845
  }
22786
22846
  function generateSmartRecall(data, intent, opts = {}) {
22787
22847
  const entries = parseEntries(data);
@@ -22836,11 +22896,12 @@ function generateSmartRecall(data, intent, opts = {}) {
22836
22896
  let folderBoost = 0;
22837
22897
  if (e.path_scope && globMatch(e.path_scope, ".")) folderBoost = 0.05;
22838
22898
  const warningBoost = e.category === "warning" ? 0.2 : 0;
22899
+ const impBoost = importanceBoost(e.importance);
22839
22900
  let combined;
22840
22901
  if (opts.rrf) {
22841
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost;
22902
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost;
22842
22903
  } else {
22843
- combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost;
22904
+ combined = bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost;
22844
22905
  }
22845
22906
  return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score };
22846
22907
  }).filter((x) => x.score > 0 || x.matchesQuery).sort((a, b2) => {
@@ -22856,6 +22917,9 @@ function generateSmartRecall(data, intent, opts = {}) {
22856
22917
  if (scored.length === 0) {
22857
22918
  const top = eligible.sort((a, b2) => {
22858
22919
  if (a.priority !== b2.priority) return b2.priority - a.priority;
22920
+ const ia2 = importanceRank(a.importance);
22921
+ const ib2 = importanceRank(b2.importance);
22922
+ if (ia2 !== ib2) return ib2 - ia2;
22859
22923
  return importance(b2, opts.today) - importance(a, opts.today);
22860
22924
  }).slice(0, limit);
22861
22925
  if (top.length === 0) return "No entries in memory.";
@@ -34748,11 +34812,12 @@ ${mergeActions.join("\n")}`
34748
34812
  ttl: external_exports.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
34749
34813
  links: external_exports.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
34750
34814
  path_scope: external_exports.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
34751
- origin: external_exports.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry.")
34815
+ origin: external_exports.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
34816
+ importance: external_exports.enum(["critical", "high", "medium", "low"]).optional().describe("Explicit importance level \u2014 critical/high entries surface first in recall, low last. Omit for auto (recency + frequency).")
34752
34817
  },
34753
34818
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34754
34819
  },
34755
- async ({ category, key, content, file: file2, tags, ttl, links, path_scope, origin }) => {
34820
+ async ({ category, key, content, file: file2, tags, ttl, links, path_scope, origin, importance: importance2 = "" }) => {
34756
34821
  const data = readMemory();
34757
34822
  const newId = generateId();
34758
34823
  const date5 = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -34782,7 +34847,7 @@ ${mergeActions.join("\n")}`
34782
34847
  const resolvedTags = tags ? tags : verbatim ? "" : inferTags(content, key, config2.vocab);
34783
34848
  const existingParts = existingIdx !== -1 ? parseToonLine(lines[existingIdx]) : [];
34784
34849
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
34785
- let newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, "0", resolvedLinks, "", "", "", path_scope || "", origin]);
34850
+ let newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, "0", resolvedLinks, "", "", "", "0", path_scope || "", origin, "", "", importance2]);
34786
34851
  let action = "Saved";
34787
34852
  let mergeInfo = "";
34788
34853
  const tagsInferred = !tags && resolvedTags ? true : false;
@@ -34796,7 +34861,7 @@ ${mergeActions.join("\n")}`
34796
34861
  const lastAccessed = "";
34797
34862
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date5, accessed, lastAccessed, origin);
34798
34863
  const confidence = 1;
34799
- newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active"]);
34864
+ newEntry = toToonLine([entryId, category, key, content, file2 || "", resolvedTags, date5, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active", "", importance2]);
34800
34865
  const match = lines[headerIdx].match(/\[(\d+)\|/);
34801
34866
  const count = match ? parseInt(match[1]) : 0;
34802
34867
  lines.splice(headerIdx + 1, 0, newEntry);
@@ -34838,12 +34903,14 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34838
34903
  title: "Search Memory",
34839
34904
  description: "Search the project's persistent memory. Returns relevant entries. Use BEFORE reading files. Pattern: recall \u2192 context_diff for recent changes \u2192 capture to save observations.",
34840
34905
  inputSchema: {
34841
- query: external_exports.string().describe("Text to search for"),
34906
+ query: external_exports.string().optional().default("").describe("Text to search for (optional when mode:'index' or ids is given)"),
34842
34907
  category: external_exports.string().optional().default("").describe("Filter by category (empty = all)"),
34843
34908
  from_date: external_exports.string().optional().default("").describe("Start date filter (YYYY-MM-DD)"),
34844
34909
  to_date: external_exports.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
34845
- mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens)."),
34910
+ mode: external_exports.enum(["flat", "graph", "index"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall: expands the related-entry subgraph from matches (more precise, fewer tokens). 'index' = one line per entry (key, id, category, date, relevance %) with no content \u2014 browse then fetch full entries with `ids`."),
34911
+ ids: external_exports.string().optional().default("").describe("Batch fetch: comma/space/;-separated entry ids or keys, rendered in the given order (unknown entries skipped). Complements mode:'index' \u2014 layer 2 of progressive disclosure. Overrides mode."),
34846
34912
  hops: external_exports.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
34913
+ limit: external_exports.number().optional().describe("Maximum entries returned. Default 6 (15 in 'index' mode). Keeps token cost low."),
34847
34914
  compact: external_exports.boolean().optional().default(false).describe("Token-efficient output: numeric indices (1, 2), omits id/date/file (keeps tags), edges as '->2', truncates graph neighbors to a snippet. Does not mutate .toon file."),
34848
34915
  budget: external_exports.enum(["tiny", "normal", "deep"]).optional().default("deep").describe("'tiny': key+1 line (~50 tokens). 'normal': compact with tags/edges. 'deep': all fields (default). Overrides 'compact'."),
34849
34916
  budget_tokens: external_exports.number().optional().default(0).describe("Deterministic token budget: include entries until the estimated output reaches ~N tokens (overrides limit). 0 = no budget."),
@@ -34855,11 +34922,62 @@ ${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }]
34855
34922
  },
34856
34923
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true }
34857
34924
  },
34858
- async ({ query, category, from_date, to_date, mode, hops, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
34925
+ async ({ query, category, from_date, to_date, mode, ids, hops, limit: limitParam, compact, budget: budgetParam, budget_tokens, explain, bias, path_scope, rrf, as_of }) => {
34859
34926
  const data = readMemory();
34860
- const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34861
34927
  const resolvedBudget = budgetParam || (compact ? "normal" : "deep");
34862
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: as_of || void 0 });
34928
+ const resolvedAsOf = as_of || void 0;
34929
+ if (ids && ids.trim()) {
34930
+ const tokens = ids.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean);
34931
+ const entries = fetchEntriesByIds(data, tokens, { asOf: resolvedAsOf });
34932
+ if (entries.length === 0) {
34933
+ return { content: [{ type: "text", text: `No entries found for ids: ${ids}` }] };
34934
+ }
34935
+ bumpAccessed(entries.map((e) => e.id));
34936
+ const label = entries.length === 1 ? "entry" : "entries";
34937
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
34938
+ const formatted3 = renderCompact(entries, {
34939
+ budget: resolvedBudget,
34940
+ budgetTokens: budget_tokens || void 0
34941
+ });
34942
+ return { content: [{ type: "text", text: `Fetched ${entries.length} ${label}:
34943
+
34944
+ ${formatted3}` }] };
34945
+ }
34946
+ const formatted2 = entries.map((r2) => {
34947
+ const links = r2.links.length ? `
34948
+ links: ${r2.links.join(", ")}` : "";
34949
+ const pin = r2.priority > 0 ? r2.priority > 1 ? ` \u{1F4CC}${r2.priority}` : " \u{1F4CC}" : "";
34950
+ const originInfo = r2.origin !== "agent" ? ` | origin: ${r2.origin}` : "";
34951
+ const scopeInfo = r2.path_scope ? ` | scope: ${r2.path_scope}` : "";
34952
+ const statusInfo = r2.status !== "active" ? ` | status: ${r2.status}` : "";
34953
+ const supersededInfo = r2.supersededOn ? ` | superseded: ${r2.supersededOn}` : "";
34954
+ return `[${r2.category}] ${r2.key}${pin} (${r2.id})
34955
+ ${r2.content}
34956
+ File: ${r2.file} | Tags: ${r2.tags.join(";")} | Date: ${r2.date}${links}${originInfo}${scopeInfo}${statusInfo}${supersededInfo}`;
34957
+ }).join("\n\n");
34958
+ return { content: [{ type: "text", text: `Fetched ${entries.length} ${label}:
34959
+
34960
+ ${formatted2}` }] };
34961
+ }
34962
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : void 0;
34963
+ const limit = limitParam ?? (mode === "index" ? 15 : 6);
34964
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, limit, sessionFiles, path_scope: path_scope || void 0, rrf, asOf: resolvedAsOf });
34965
+ if (mode === "index") {
34966
+ if (detail.entries.length === 0) {
34967
+ return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34968
+ }
34969
+ const formatted2 = renderIndex(detail.entries, { scores: detail.scores });
34970
+ return {
34971
+ content: [{
34972
+ type: "text",
34973
+ text: `\u{1F4C7} Memory index (${detail.entries.length} entries):
34974
+
34975
+ ${formatted2}
34976
+
34977
+ Fetch full entries with memory_recall ids="<id1>,<id2>" or search with mode:"flat".`
34978
+ }]
34979
+ };
34980
+ }
34863
34981
  if (detail.entries.length === 0) {
34864
34982
  return { content: [{ type: "text", text: `No results found for "${query}"` }] };
34865
34983
  }
@@ -48182,7 +48300,7 @@ function registerResources(server2) {
48182
48300
 
48183
48301
  // src/mcp/server.ts
48184
48302
  var server = new McpServer(
48185
- { name: "toon-memory", version: "4.2.0" },
48303
+ { name: "toon-memory", version: "4.3.1" },
48186
48304
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
48187
48305
  );
48188
48306
  var s = server.server;
@@ -48194,7 +48312,7 @@ s.setRequestHandler(InitializeRequestSchema, async (request) => {
48194
48312
  return {
48195
48313
  protocolVersion,
48196
48314
  capabilities: s.getCapabilities(),
48197
- serverInfo: { name: "toon-memory", version: "4.2.0" },
48315
+ serverInfo: { name: "toon-memory", version: "4.3.1" },
48198
48316
  ...s._instructions && { instructions: s._instructions }
48199
48317
  };
48200
48318
  });