toon-memory 3.0.0 → 3.2.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.
package/src/mcp/tools.ts CHANGED
@@ -11,7 +11,7 @@ import { archiveOldEntries } from "./archive"
11
11
  import { consolidateEntries } from "./consolidation"
12
12
  import { readUnderLock } from "../lib/lock"
13
13
  import { encrypt, decrypt } from "./crypto"
14
- import { graphRecallDetailed, renderCompact, parseEntries } from "../lib/graph"
14
+ import { graphRecallDetailed, renderCompact, parseEntries, buildGraph } from "../lib/graph"
15
15
  import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
16
16
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
17
17
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
@@ -1374,6 +1374,182 @@ server.registerTool(
1374
1374
  }
1375
1375
  )
1376
1376
 
1377
+ // ── memory_merge_similar ─────────────────────────────────────────────
1378
+
1379
+ server.registerTool(
1380
+ "memory_merge_similar",
1381
+ {
1382
+ title: "Merge Similar Entries",
1383
+ description: "Find entries with overlapping content (>50% word similarity) and merge them. Deterministic, no LLM. Keeps the longer content and combines tags.",
1384
+ inputSchema: {
1385
+ dryRun: z.boolean().optional().default(false).describe("If true, show what would be merged without making changes."),
1386
+ },
1387
+ },
1388
+ async ({ dryRun }) => {
1389
+ const data = readMemory()
1390
+ const entries = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
1391
+
1392
+ if (entries.length < 2) {
1393
+ return { content: [{ type: "text" as const, text: "✅ Not enough entries to compress." }] }
1394
+ }
1395
+
1396
+ // Parse entries and compute similarity
1397
+ const parsed = entries.map((line) => {
1398
+ const parts = line.trim().split("|")
1399
+ if (parts.length < 7) return null
1400
+ const [id, cat, key, content, file, tags, date, ttl, accessedRaw] = parts
1401
+ const words = new Set(normalize(`${key} ${content} ${tags}`).split(" ").filter(Boolean))
1402
+ return { id, cat, key, content, file, tags, date, ttl, accessed: parseInt(accessedRaw) || 0, words, line }
1403
+ }).filter(Boolean) as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; ttl: string; accessed: number; words: Set<string>; line: string }>
1404
+
1405
+ // Find pairs with >50% word overlap (Jaccard similarity)
1406
+ const mergePairs: Array<{ a: number; b: number; similarity: number }> = []
1407
+ for (let i = 0; i < parsed.length; i++) {
1408
+ for (let j = i + 1; j < parsed.length; j++) {
1409
+ const a = parsed[i], b = parsed[j]
1410
+ const intersection = new Set([...a.words].filter((w) => b.words.has(w)))
1411
+ const union = new Set([...a.words, ...b.words])
1412
+ const similarity = union.size > 0 ? intersection.size / union.size : 0
1413
+ if (similarity > 0.5) {
1414
+ mergePairs.push({ a: i, b: j, similarity })
1415
+ }
1416
+ }
1417
+ }
1418
+
1419
+ if (mergePairs.length === 0) {
1420
+ return { content: [{ type: "text" as const, text: "✅ No similar entries found to merge." }] }
1421
+ }
1422
+
1423
+ // Sort by similarity (highest first) and merge greedily
1424
+ mergePairs.sort((x, y) => y.similarity - x.similarity)
1425
+ const merged = new Set<number>()
1426
+ const mergeActions: string[] = []
1427
+
1428
+ for (const pair of mergePairs) {
1429
+ if (merged.has(pair.a) || merged.has(pair.b)) continue
1430
+ const a = parsed[pair.a], b = parsed[pair.b]
1431
+
1432
+ // Merge: keep the entry with more content, combine tags
1433
+ const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
1434
+ const longer = a.content.length >= b.content.length ? a : b
1435
+ const shorter = a.content.length < b.content.length ? a : b
1436
+ const newContent = longer.content
1437
+ const newDate = a.date > b.date ? a.date : b.date
1438
+ const newAccessed = a.accessed + b.accessed
1439
+
1440
+ mergeActions.push(` [${longer.cat}] ${longer.key} ← ${shorter.key} (similarity: ${(pair.similarity * 100).toFixed(0)}%)`)
1441
+
1442
+ if (!dryRun) {
1443
+ // Update the longer entry with merged data
1444
+ const mergedLine = ` ${longer.id}|${longer.cat}|${longer.key}|${newContent}|${longer.file}|${mergedTags}|${newDate}|${longer.ttl}|${newAccessed}|${longer.line.split("|")[9] || ""}|${longer.line.split("|")[10] || ""}|${longer.line.split("|")[11] || ""}|${longer.line.split("|")[12] || ""}`
1445
+ // Replace in entries array
1446
+ entries[entries.indexOf(longer.line)] = mergedLine
1447
+ merged.add(pair.b)
1448
+ }
1449
+ }
1450
+
1451
+ if (dryRun) {
1452
+ return {
1453
+ content: [{
1454
+ type: "text" as const,
1455
+ text: `🔍 Dry run — would merge ${merged.size} entries:\n\n${mergeActions.join("\n")}\n\nRun with dryRun: false to apply.`
1456
+ }],
1457
+ }
1458
+ }
1459
+
1460
+ // Remove merged entries and write back
1461
+ const newLines = entries.filter((_, i) => !merged.has(i))
1462
+ const headerIdx = newLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1463
+ if (headerIdx !== -1) {
1464
+ const count = newLines.filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")).length
1465
+ newLines[headerIdx] = newLines[headerIdx].replace(/\[\d+\|/, `[${count}|`)
1466
+ }
1467
+ writeMemory(newLines.join("\n"))
1468
+
1469
+ return {
1470
+ content: [{
1471
+ type: "text" as const,
1472
+ text: `✅ Merged ${merged.size} entries into ${entries.length - merged.size} entries.\n\n${mergeActions.join("\n")}`
1473
+ }],
1474
+ }
1475
+ }
1476
+ )
1477
+
1478
+ // ── memory_graph_path ────────────────────────────────────────────────
1479
+
1480
+ server.registerTool(
1481
+ "memory_graph_path",
1482
+ {
1483
+ title: "Find Graph Path",
1484
+ description: "Find the shortest path between two memory entries in the knowledge graph. Shows how two concepts are connected through related entries.",
1485
+ inputSchema: {
1486
+ from: z.string().describe("Starting entry key"),
1487
+ to: z.string().describe("Target entry key"),
1488
+ },
1489
+ },
1490
+ async ({ from, to }) => {
1491
+ const data = readMemory()
1492
+ const entries = parseEntries(data)
1493
+ const graph = buildGraph(entries)
1494
+
1495
+ if (!graph.byKey.has(from)) {
1496
+ return { content: [{ type: "text" as const, text: `❌ Entry "${from}" not found in memory.` }] }
1497
+ }
1498
+ if (!graph.byKey.has(to)) {
1499
+ return { content: [{ type: "text" as const, text: `❌ Entry "${to}" not found in memory.` }] }
1500
+ }
1501
+
1502
+ // BFS shortest path
1503
+ const visited = new Set<string>()
1504
+ const parent = new Map<string, string>()
1505
+ const queue = [from]
1506
+ visited.add(from)
1507
+
1508
+ while (queue.length > 0) {
1509
+ const current = queue.shift()!
1510
+ if (current === to) break
1511
+
1512
+ for (const neighbor of graph.adjacency.get(current) || []) {
1513
+ if (!visited.has(neighbor)) {
1514
+ visited.add(neighbor)
1515
+ parent.set(neighbor, current)
1516
+ queue.push(neighbor)
1517
+ }
1518
+ }
1519
+ }
1520
+
1521
+ if (!visited.has(to)) {
1522
+ return {
1523
+ content: [{
1524
+ type: "text" as const,
1525
+ text: `🔗 No path found between "${from}" and "${to}". They may be in disconnected parts of the memory graph.`
1526
+ }],
1527
+ }
1528
+ }
1529
+
1530
+ // Reconstruct path
1531
+ const path: string[] = []
1532
+ let current: string | null = to
1533
+ while (current !== null) {
1534
+ path.unshift(current)
1535
+ current = parent.get(current) || null
1536
+ }
1537
+
1538
+ const pathStr = path.map((key, i) => {
1539
+ const entry = graph.byKey.get(key)!
1540
+ const arrow = i < path.length - 1 ? ` → ` : ""
1541
+ return `[${entry.category}] ${key}${arrow}`
1542
+ }).join("\n ")
1543
+
1544
+ return {
1545
+ content: [{
1546
+ type: "text" as const,
1547
+ text: `🔗 Path (${path.length} hops):\n\n ${pathStr}`
1548
+ }],
1549
+ }
1550
+ }
1551
+ )
1552
+
1377
1553
  } // end registerTools
1378
1554
 
1379
1555
  /** Parse relative time string to milliseconds. */
@@ -0,0 +1,49 @@
1
+ import { readMemory } from "../mcp/memory-io"
2
+ import { parseEntries, buildGraph } from "../lib/graph"
3
+ import type { ViewerData } from "./types"
4
+
5
+ export function buildViewerData(): ViewerData {
6
+ const data = readMemory()
7
+ const entries = parseEntries(data)
8
+ if (entries.length === 0) {
9
+ console.log("Memory is empty. Nothing to display.")
10
+ process.exit(0)
11
+ }
12
+
13
+ const graph = buildGraph(entries)
14
+
15
+ const nodes = entries.map((e) => ({
16
+ id: e.key,
17
+ category: e.category,
18
+ content: e.content.substring(0, 120),
19
+ tags: e.tags,
20
+ quality: e.accessed,
21
+ accessCount: e.accessed,
22
+ date: e.date,
23
+ file: e.file,
24
+ links: e.links,
25
+ ttl: e.ttl,
26
+ lastAccessed: e.lastAccessed,
27
+ }))
28
+
29
+ const edges: { source: string; target: string }[] = []
30
+ const seen = new Set<string>()
31
+ for (const [key, neighbors] of graph.adjacency) {
32
+ for (const n of neighbors) {
33
+ const pair = [key, n].sort().join("::")
34
+ if (!seen.has(pair)) {
35
+ seen.add(pair)
36
+ edges.push({ source: key, target: n })
37
+ }
38
+ }
39
+ }
40
+
41
+ const categories: Record<string, number> = {}
42
+ const tagCounts: Record<string, number> = {}
43
+ for (const e of entries) {
44
+ categories[e.category] = (categories[e.category] || 0) + 1
45
+ for (const t of e.tags) tagCounts[t] = (tagCounts[t] || 0) + 1
46
+ }
47
+
48
+ return { nodes, edges, categories, tagCounts, totalEntries: entries.length }
49
+ }