toon-memory 3.7.0 → 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/setup.js CHANGED
@@ -288,6 +288,57 @@ function detectAgents() {
288
288
  // src/cli/memory.ts
289
289
  import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
290
290
  import { join as join4 } from "path";
291
+
292
+ // src/lib/utils.ts
293
+ var tokenize = (s) => s.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/[-_]/g, " ").toLowerCase().split(/\s+/).filter(Boolean);
294
+ var unescField = (s) => {
295
+ let out = "";
296
+ for (let i = 0; i < s.length; i++) {
297
+ const c = s[i];
298
+ if (c === "\\" && i + 1 < s.length) {
299
+ const n = s[i + 1];
300
+ if (n === "n") {
301
+ out += "\n";
302
+ i++;
303
+ } else if (n === "|") {
304
+ out += "|";
305
+ i++;
306
+ } else if (n === "\\") {
307
+ out += "\\";
308
+ i++;
309
+ } else out += c;
310
+ } else out += c;
311
+ }
312
+ return out;
313
+ };
314
+ var parseToonLine = (line) => {
315
+ const parts = [];
316
+ let cur = "";
317
+ let escaped = false;
318
+ for (const c of line.trim()) {
319
+ if (escaped) {
320
+ cur += c;
321
+ escaped = false;
322
+ continue;
323
+ }
324
+ if (c === "\\") {
325
+ cur += c;
326
+ escaped = true;
327
+ continue;
328
+ }
329
+ if (c === "|") {
330
+ parts.push(unescField(cur));
331
+ cur = "";
332
+ continue;
333
+ }
334
+ cur += c;
335
+ }
336
+ if (escaped) cur += "\\";
337
+ parts.push(unescField(cur));
338
+ return parts;
339
+ };
340
+
341
+ // src/cli/memory.ts
291
342
  function installMemoryDir() {
292
343
  const memoryFile = join4(MEMORY_DIR, "data.toon");
293
344
  if (!existsSync4(MEMORY_DIR)) mkdirSync2(MEMORY_DIR, { recursive: true });
@@ -322,7 +373,7 @@ function dumpMemoryMarkdown() {
322
373
  const data = readFileSync4(memoryFile, "utf-8");
323
374
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|"));
324
375
  const entries = lines.map((line) => {
325
- const parts = line.trim().split("|");
376
+ const parts = parseToonLine(line);
326
377
  return {
327
378
  id: parts[0] ?? "",
328
379
  category: parts[1] ?? "",
@@ -341,7 +392,7 @@ function dumpMemoryMarkdown() {
341
392
  if (!sl.includes(":") || !sl.startsWith(" ")) continue;
342
393
  const idx = sl.indexOf(":");
343
394
  const file = sl.slice(0, idx).trim();
344
- const summary = sl.slice(idx + 1).trim();
395
+ const summary = unescField(sl.slice(idx + 1).trim());
345
396
  if (file && summary) summaries.push({ file, summary });
346
397
  }
347
398
  }
@@ -1128,7 +1179,7 @@ function stats() {
1128
1179
  const categories = {};
1129
1180
  let latestDate = "";
1130
1181
  for (const line of lines) {
1131
- const parts = line.trim().split("|");
1182
+ const parts = parseToonLine(line);
1132
1183
  if (parts.length >= 7) {
1133
1184
  const category = parts[1];
1134
1185
  const date = parts[6];
@@ -1157,7 +1208,7 @@ function exportMemory() {
1157
1208
  const data = readFileSync9(memoryFile, "utf-8");
1158
1209
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|"));
1159
1210
  const entries = lines.map((line) => {
1160
- const parts = line.trim().split("|");
1211
+ const parts = parseToonLine(line);
1161
1212
  return {
1162
1213
  id: parts[0],
1163
1214
  category: parts[1],
@@ -1209,7 +1260,7 @@ function importMemory() {
1209
1260
  let existingKeys = [];
1210
1261
  if (existsSync9(memoryFile)) {
1211
1262
  const existing = readFileSync9(memoryFile, "utf-8");
1212
- existingKeys = existing.split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => l.trim().split("|")[2]);
1263
+ existingKeys = existing.split("\n").filter((l) => l.startsWith(" ") && l.includes("|")).map((l) => parseToonLine(l)[2]);
1213
1264
  }
1214
1265
  const newEntries = importData.entries.filter((e) => !existingKeys.includes(e.key));
1215
1266
  if (newEntries.length === 0) {
@@ -1599,7 +1650,7 @@ var entryLines = (data) => data.split("\n").filter(
1599
1650
  function parseEntries(data) {
1600
1651
  const out = [];
1601
1652
  for (const line of entryLines(data)) {
1602
- const parts = line.trim().split("|");
1653
+ const parts = parseToonLine(line);
1603
1654
  if (parts.length < 7) continue;
1604
1655
  const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] = parts;
1605
1656
  out.push({
@@ -1623,6 +1674,19 @@ function parseEntries(data) {
1623
1674
  }
1624
1675
  return out;
1625
1676
  }
1677
+ function orphanScore(a, b) {
1678
+ const aTags = new Set(a.tags);
1679
+ let sharedTags = 0;
1680
+ for (const t of b.tags) if (aTags.has(t)) sharedTags++;
1681
+ const aKey = new Set(tokenize(a.key));
1682
+ const bKey = new Set(tokenize(b.key));
1683
+ let sharedKey = 0;
1684
+ for (const t of bKey) if (aKey.has(t)) sharedKey++;
1685
+ const aTok = new Set(tokenize(a.content));
1686
+ let sharedContent = 0;
1687
+ for (const t of tokenize(b.content)) if (aTok.has(t)) sharedContent++;
1688
+ return sharedTags * 4 + sharedKey * 2 + sharedContent;
1689
+ }
1626
1690
  function buildGraph(entries) {
1627
1691
  const byKey = /* @__PURE__ */ new Map();
1628
1692
  for (const e of entries) {
@@ -1658,8 +1722,71 @@ function buildGraph(entries) {
1658
1722
  }
1659
1723
  const adjacency = /* @__PURE__ */ new Map();
1660
1724
  for (const [k, v] of adj) adjacency.set(k, [...v]);
1725
+ const allKeys = [...byKey.keys()];
1726
+ for (const key of allKeys) {
1727
+ if (adj.has(key)) continue;
1728
+ let best = "";
1729
+ let bestScore = -1;
1730
+ for (const other of allKeys) {
1731
+ if (other === key) continue;
1732
+ const score = orphanScore(byKey.get(key), byKey.get(other));
1733
+ if (best === "" || score > bestScore || score === bestScore && other < best) {
1734
+ bestScore = score;
1735
+ best = other;
1736
+ }
1737
+ }
1738
+ if (best) link(key, best);
1739
+ }
1740
+ for (const [k, v] of adj) adjacency.set(k, [...v]);
1741
+ const comps = connectedComponents(adjacency);
1742
+ if (comps.length > 1) {
1743
+ let largest = comps[0];
1744
+ for (const c of comps) if (c.length > largest.length) largest = c;
1745
+ const largestSet = new Set(largest);
1746
+ for (const comp of comps) {
1747
+ if (comp.length === largest.length && comp[0] === largest[0]) continue;
1748
+ let bestA = "";
1749
+ let bestB = "";
1750
+ let bestScore = -1;
1751
+ for (const a of comp) {
1752
+ const ea = byKey.get(a);
1753
+ for (const b of largest) {
1754
+ const score = orphanScore(ea, byKey.get(b));
1755
+ if (bestA === "" || score > bestScore || score === bestScore && a + b < bestA + bestB) {
1756
+ bestScore = score;
1757
+ bestA = a;
1758
+ bestB = b;
1759
+ }
1760
+ }
1761
+ }
1762
+ if (bestA) link(bestA, bestB);
1763
+ }
1764
+ for (const [k, v] of adj) adjacency.set(k, [...v]);
1765
+ }
1661
1766
  return { adjacency, byKey };
1662
1767
  }
1768
+ function connectedComponents(adjacency) {
1769
+ const comps = [];
1770
+ const seen = /* @__PURE__ */ new Set();
1771
+ for (const [start] of adjacency) {
1772
+ if (seen.has(start)) continue;
1773
+ const comp = [];
1774
+ const stack = [start];
1775
+ seen.add(start);
1776
+ while (stack.length) {
1777
+ const cur = stack.pop();
1778
+ comp.push(cur);
1779
+ for (const next of adjacency.get(cur) || []) {
1780
+ if (!seen.has(next)) {
1781
+ seen.add(next);
1782
+ stack.push(next);
1783
+ }
1784
+ }
1785
+ }
1786
+ comps.push(comp);
1787
+ }
1788
+ return comps;
1789
+ }
1663
1790
 
1664
1791
  // src/viewer/data.ts
1665
1792
  function buildViewerData() {
@@ -2632,15 +2759,40 @@ function openBrowser(url) {
2632
2759
  console.log(`Open in browser: ${url}`);
2633
2760
  }
2634
2761
  }
2762
+ function resolvePort(portArg) {
2763
+ const raw = portArg ?? process.env.PORT;
2764
+ if (raw === void 0 || raw === "") return 3e3;
2765
+ const port = Number(raw);
2766
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
2767
+ console.error(`Invalid port: '${raw}'. Expected an integer between 1 and 65535.`);
2768
+ process.exit(1);
2769
+ }
2770
+ return port;
2771
+ }
2772
+ var MAX_PORT_ATTEMPTS = 20;
2635
2773
  function viewer(portArg) {
2636
- const PORT = parseInt(portArg || process.env.PORT || "3000", 10);
2774
+ const startPort = resolvePort(portArg);
2775
+ let port = startPort;
2637
2776
  let currentHtml = generateHtml(buildViewerData());
2638
2777
  const server = createServer((_req, res) => {
2639
2778
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2640
2779
  res.end(currentHtml);
2641
2780
  });
2642
- server.listen(PORT, "127.0.0.1", () => {
2643
- const url = `http://127.0.0.1:${PORT}`;
2781
+ server.on("error", (err) => {
2782
+ if (err.code === "EADDRINUSE" && port < startPort + MAX_PORT_ATTEMPTS) {
2783
+ port += 1;
2784
+ console.log(`Port ${port - 1} in use, trying ${port}...`);
2785
+ server.listen(port, "127.0.0.1", onListen);
2786
+ } else if (err.code === "EADDRINUSE") {
2787
+ console.error(`Port ${port} already in use. Try: toon-memory viewer --port ${port + 1} (or PORT=${port + 1} toon-memory viewer)`);
2788
+ process.exit(1);
2789
+ } else {
2790
+ console.error(`Server error: ${err.message}`);
2791
+ process.exit(1);
2792
+ }
2793
+ });
2794
+ function onListen() {
2795
+ const url = `http://127.0.0.1:${port}`;
2644
2796
  const data = buildViewerData();
2645
2797
  console.log(`
2646
2798
  toon-memory viewer`);
@@ -2649,7 +2801,8 @@ toon-memory viewer`);
2649
2801
  console.log(` Press 'r' in terminal to reload | Ctrl+C to stop
2650
2802
  `);
2651
2803
  openBrowser(url);
2652
- });
2804
+ }
2805
+ server.listen(startPort, "127.0.0.1", onListen);
2653
2806
  if (process.stdin.isTTY) {
2654
2807
  process.stdin.setRawMode?.(true);
2655
2808
  process.stdin.resume();
@@ -2663,14 +2816,6 @@ toon-memory viewer`);
2663
2816
  if (key === "") process.exit(0);
2664
2817
  });
2665
2818
  }
2666
- server.on("error", (err) => {
2667
- if (err.code === "EADDRINUSE") {
2668
- console.error(`Port ${PORT} already in use. Try: PORT=3001 toon-memory viewer`);
2669
- } else {
2670
- console.error(`Server error: ${err.message}`);
2671
- }
2672
- process.exit(1);
2673
- });
2674
2819
  }
2675
2820
  function viewerExport() {
2676
2821
  const viewerData = buildViewerData();
@@ -2696,6 +2841,10 @@ if (args[0] === "uninstall") {
2696
2841
  process.exit(0);
2697
2842
  }
2698
2843
  if (args[0] === "init") {
2844
+ if (args.includes("-h") || args.includes("--help")) {
2845
+ printUsage();
2846
+ process.exit(0);
2847
+ }
2699
2848
  const rest = args.slice(1);
2700
2849
  const agentNames = [];
2701
2850
  let scope;
@@ -2746,9 +2895,19 @@ if (args[0] === "watch") {
2746
2895
  process.exit(0);
2747
2896
  }
2748
2897
  if (args[0] === "viewer") {
2898
+ if (args.includes("-h") || args.includes("--help")) {
2899
+ printViewerUsage();
2900
+ process.exit(0);
2901
+ }
2749
2902
  const portIdx = args.indexOf("--port");
2750
- const port = portIdx !== -1 && args[portIdx + 1] ? args[portIdx + 1] : void 0;
2903
+ if (portIdx !== -1 && !args[portIdx + 1]) {
2904
+ console.error("Missing value for --port\n");
2905
+ printViewerUsage();
2906
+ process.exit(1);
2907
+ }
2908
+ const port = portIdx !== -1 ? args[portIdx + 1] : void 0;
2751
2909
  if (args.includes("--export")) {
2910
+ if (port) console.log("Note: --port is ignored with --export");
2752
2911
  viewerExport();
2753
2912
  } else {
2754
2913
  viewer(port);
@@ -2762,6 +2921,15 @@ if (args[0] === "viewer") {
2762
2921
  printUsage();
2763
2922
  process.exit(1);
2764
2923
  }
2924
+ function printViewerUsage() {
2925
+ console.log(`Usage: toon-memory viewer [options]
2926
+ Options:
2927
+ --export Save a static HTML viewer to .toon-memory/viewer/index.html
2928
+ --port <n> Port to serve on (default: 3000, or $PORT)
2929
+ -h, --help Show this help
2930
+
2931
+ Press 'r' in the terminal while serving to reload the graph.`);
2932
+ }
2765
2933
  function printUsage() {
2766
2934
  console.log(`Usage: toon-memory <command> [options]
2767
2935
  Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, mcp