toon-memory 3.3.1 → 3.5.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
@@ -15,7 +15,7 @@ import { encrypt, decrypt } from "./crypto"
15
15
  import { graphRecallDetailed, renderCompact, parseEntries, buildGraph } from "../lib/graph"
16
16
  import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
17
17
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
18
- import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
18
+ import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS, getCurrentSessionFiles } from "../lib/sessions"
19
19
  import { fileMtimes } from "../lib/git"
20
20
  import { normalize, isExpiredLocal, tokenize, importance } from "../lib/utils"
21
21
  import { expandSynonyms } from "../lib/synonyms"
@@ -142,14 +142,16 @@ server.registerTool(
142
142
  mode: z.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)."),
143
143
  hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
144
144
  compact: z.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."),
145
+ bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
145
146
  },
146
147
  },
147
- async ({ query, category, from_date, to_date, mode, hops, compact }) => {
148
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias }) => {
148
149
  const data = readMemory()
149
150
 
150
151
  // Delegate to graphRecallDetailed for both flat and graph modes
151
152
  // This avoids duplicating BM25 + ranking logic
152
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
153
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
154
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles })
153
155
  if (detail.entries.length === 0) {
154
156
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
155
157
  }
@@ -165,7 +167,8 @@ server.registerTool(
165
167
  const formatted = detail.entries
166
168
  .map((r) => {
167
169
  const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
168
- return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
170
+ const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
171
+ return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
169
172
  })
170
173
  .join("\n\n")
171
174
  return { content: [{ type: "text" as const, text: formatted }] }
@@ -280,6 +283,44 @@ server.registerTool(
280
283
  .map((e) => ` ${e.key}: ${e.accessed}x (Q: ${e.quality})`),
281
284
  ]
282
285
 
286
+ // Cold memories: high quality but rarely accessed
287
+ const coldEntries = lines
288
+ .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
289
+ .map((l) => {
290
+ const p = l.trim().split("|")
291
+ return {
292
+ key: p[2],
293
+ cat: p[1],
294
+ quality: parseFloat(p[10]) || 0,
295
+ accessed: p.length > 8 ? parseInt(p[8]) || 0 : 0,
296
+ lastAccessed: p.length > 12 ? p[12] || "" : "",
297
+ date: p[6] || "",
298
+ }
299
+ })
300
+ .filter((e) => {
301
+ if (e.accessed >= 2) return false
302
+ if (e.quality < 0.7) return false
303
+ const lastDate = e.lastAccessed || e.date
304
+ if (!lastDate) return false
305
+ const daysSinceLastAccess = (Date.now() - new Date(lastDate).getTime()) / 86400000
306
+ return daysSinceLastAccess > 30
307
+ })
308
+ .sort((a, b) => b.quality - a.quality)
309
+
310
+ if (coldEntries.length > 0) {
311
+ stats.push(
312
+ "",
313
+ `Cold memories (${coldEntries.length}):`,
314
+ ...coldEntries.slice(0, 5).map((e) => {
315
+ const lastDate = e.lastAccessed || e.date
316
+ const daysSince = Math.round((Date.now() - new Date(lastDate).getTime()) / 86400000)
317
+ return ` ${e.key} (Q: ${e.quality.toFixed(2)}) — ${daysSince}d since last access`
318
+ }),
319
+ "",
320
+ "💡 Run memory_archive() to archive cold entries."
321
+ )
322
+ }
323
+
283
324
  return { content: [{ type: "text" as const, text: stats.join("\n") }] }
284
325
  }
285
326
  )
@@ -382,12 +423,14 @@ server.registerTool(
382
423
  intent: z.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
383
424
  limit: z.number().optional().default(8).describe("Maximum entries to return"),
384
425
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
426
+ bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
385
427
  },
386
428
  },
387
- async ({ intent, limit, category }) => {
429
+ async ({ intent, limit, category, bias }) => {
388
430
  const data = readMemory()
389
431
  const mtimes = fileMtimes()
390
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes })
432
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
433
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles })
391
434
  return { content: [{ type: "text" as const, text: result }] }
392
435
  }
393
436
  )
@@ -1450,10 +1493,31 @@ server.registerTool(
1450
1493
  }
1451
1494
 
1452
1495
  if (dryRun) {
1496
+ // Detailed preview: show what each merge produces
1497
+ const previewLines: string[] = [
1498
+ `🔍 Dry run — ${mergePairs.length} merge candidate(s) found:`,
1499
+ "",
1500
+ ]
1501
+ for (const pair of mergePairs) {
1502
+ const a = parsed[pair.a], b = parsed[pair.b]
1503
+ const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
1504
+ const longer = a.content.length >= b.content.length ? a : b
1505
+ const shorter = a.content.length < b.content.length ? a : b
1506
+ previewLines.push(` ── Pair: [${a.cat}] ${a.key} ↔ [${b.cat}] ${b.key}`)
1507
+ previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`)
1508
+ previewLines.push(` A tags: ${a.tags || "(none)"}`)
1509
+ previewLines.push(` B tags: ${b.tags || "(none)"}`)
1510
+ previewLines.push(` → Merged tags: ${mergedTags || "(none)"}`)
1511
+ previewLines.push(` → Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`)
1512
+ previewLines.push(` → Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "…" : ""}`)
1513
+ previewLines.push("")
1514
+ }
1515
+ previewLines.push(`Would merge ${merged.size} entries into ${entries.length - merged.size} entries.`)
1516
+ previewLines.push("Run with dryRun: false to apply.")
1453
1517
  return {
1454
1518
  content: [{
1455
1519
  type: "text" as const,
1456
- text: `🔍 Dry run — would merge ${merged.size} entries:\n\n${mergeActions.join("\n")}\n\nRun with dryRun: false to apply.`
1520
+ text: previewLines.join("\n"),
1457
1521
  }],
1458
1522
  }
1459
1523
  }
@@ -1551,6 +1615,332 @@ server.registerTool(
1551
1615
  }
1552
1616
  )
1553
1617
 
1618
+ // ── memory_checkpoint ─────────────────────────────────────────────────────────
1619
+
1620
+ server.registerTool(
1621
+ "memory_checkpoint",
1622
+ {
1623
+ title: "Session Checkpoint",
1624
+ description: "Save or update a session checkpoint with 7-day TTL. Creates a knowledge entry snapshot of the current session state. Same session = upsert (single checkpoint per session). Auto-expires.",
1625
+ inputSchema: {
1626
+ note: z.string().optional().default("").describe("Optional summary of what was accomplished in this session."),
1627
+ },
1628
+ },
1629
+ async ({ note }) => {
1630
+ const data = readMemory()
1631
+ const lines = data.split("\n")
1632
+
1633
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1634
+ if (headerIdx === -1) {
1635
+ lines.push(`[0|]`)
1636
+ headerIdx = lines.length - 1
1637
+ }
1638
+
1639
+ const sessionId = resolveSessionId({})
1640
+ const shortId = sessionId.replace(/^proc-/, "").slice(0, 8)
1641
+ const key = `checkpoint-${shortId}`
1642
+ const now = new Date()
1643
+ const date = now.toISOString().split("T")[0]
1644
+ const ttl7d = new Date(now.getTime() + 7 * 86400000).toISOString().split("T")[0]
1645
+
1646
+ // Gather session context: branch, files touched, agent
1647
+ const sessions = await import("../lib/sessions")
1648
+ const allSessions = sessions.listSessions()
1649
+ const mySession = allSessions.find((s) => s.id === sessionId)
1650
+ const branch = mySession?.branch || currentBranch()
1651
+ const files = mySession ? Object.keys(mySession.files) : []
1652
+ const fileList = files.length > 0 ? `\nFiles touched: ${files.slice(0, 10).join(", ")}${files.length > 10 ? ` (+${files.length - 10} more)` : ""}` : ""
1653
+
1654
+ const content = `Session checkpoint (${date})${note ? `\nNote: ${note}` : ""}\nBranch: ${branch}${fileList}`
1655
+
1656
+ // Check for existing checkpoint with same key
1657
+ let existingIdx = -1
1658
+ let existingId = ""
1659
+ for (let i = headerIdx + 1; i < lines.length; i++) {
1660
+ const line = lines[i]
1661
+ if (!line.startsWith(" ") || !line.includes("|")) continue
1662
+ if (line.startsWith(" summaries:")) break
1663
+ const parts = line.trim().split("|")
1664
+ if (parts[2] === key) {
1665
+ existingIdx = i
1666
+ existingId = parts[0]
1667
+ break
1668
+ }
1669
+ }
1670
+
1671
+ if (existingIdx !== -1) {
1672
+ // Update existing checkpoint
1673
+ const parts = lines[existingIdx].trim().split("|")
1674
+ parts[3] = content
1675
+ parts[6] = date
1676
+ parts[7] = ttl7d
1677
+ while (parts.length < 14) parts.push("")
1678
+ parts[13] = "0"
1679
+ lines[existingIdx] = ` ${parts.join("|")}`
1680
+ writeMemory(lines.join("\n"))
1681
+ return {
1682
+ content: [{ type: "text" as const, text: `📝 Checkpoint updated: ${key}\n⏰ TTL: ${ttl7d} (7d)\n${note ? `\n${note}` : ""}` }],
1683
+ }
1684
+ }
1685
+
1686
+ // Create new checkpoint entry
1687
+ const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
1688
+ const quality = qualityScore("checkpoint", "", content, date)
1689
+ const newEntry = `${newId}|knowledge|${key}|${content}||checkpoint|${date}|${ttl7d}|0||${quality.toFixed(2)}|1|${now.toISOString()}|0`
1690
+
1691
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
1692
+ const count = match ? parseInt(match[1]) : 0
1693
+ lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
1694
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
1695
+ writeMemory(lines.join("\n"))
1696
+
1697
+ return {
1698
+ content: [{
1699
+ type: "text" as const,
1700
+ text: `📝 Checkpoint saved: ${key} (${newId})\n⏰ TTL: ${ttl7d} (7d)${note ? `\n\n${note}` : ""}`,
1701
+ }],
1702
+ }
1703
+ }
1704
+ )
1705
+
1706
+ // ── memory_pin ───────────────────────────────────────────────────────────────
1707
+
1708
+ server.registerTool(
1709
+ "memory_pin",
1710
+ {
1711
+ title: "Pin Entry",
1712
+ description: "Pin a memory entry with priority level (1-5). Higher priority entries appear first in recalls. Default: 1. Useful for critical decisions, project rules, or frequently-needed context.",
1713
+ inputSchema: {
1714
+ key: z.string().describe("Key or id of the entry to pin"),
1715
+ priority: z.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1."),
1716
+ },
1717
+ },
1718
+ async ({ key, priority }) => {
1719
+ const data = readMemory()
1720
+ const lines = data.split("\n")
1721
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1722
+
1723
+ if (headerIdx === -1) {
1724
+ return { content: [{ type: "text" as const, text: "No entries in memory" }] }
1725
+ }
1726
+
1727
+ const clampedPriority = Math.max(1, Math.min(5, Math.round(priority)))
1728
+
1729
+ let found = false
1730
+ for (let i = headerIdx + 1; i < lines.length; i++) {
1731
+ const line = lines[i]
1732
+ if (!line.startsWith(" ") || !line.includes("|")) continue
1733
+ if (line.startsWith(" summaries:")) break
1734
+ const parts = line.trim().split("|")
1735
+ if (parts[0] === key || parts[2] === key) {
1736
+ while (parts.length < 14) parts.push("")
1737
+ parts[13] = String(clampedPriority)
1738
+ lines[i] = ` ${parts.join("|")}`
1739
+ found = true
1740
+ break
1741
+ }
1742
+ }
1743
+
1744
+ if (!found) {
1745
+ return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
1746
+ }
1747
+
1748
+ writeMemory(lines.join("\n"))
1749
+ return { content: [{ type: "text" as const, text: `📌${clampedPriority > 1 ? clampedPriority : ""} Pinned "${key}" at priority ${clampedPriority}. It will now appear first in recalls.` }] }
1750
+ }
1751
+ )
1752
+
1753
+ // ── memory_unpin ─────────────────────────────────────────────────────────────
1754
+
1755
+ server.registerTool(
1756
+ "memory_unpin",
1757
+ {
1758
+ title: "Unpin Entry",
1759
+ description: "Remove the pin from a memory entry so it returns to normal ranking.",
1760
+ inputSchema: {
1761
+ key: z.string().describe("Key or id of the entry to unpin"),
1762
+ },
1763
+ },
1764
+ async ({ key }) => {
1765
+ const data = readMemory()
1766
+ const lines = data.split("\n")
1767
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1768
+
1769
+ if (headerIdx === -1) {
1770
+ return { content: [{ type: "text" as const, text: "No entries in memory" }] }
1771
+ }
1772
+
1773
+ let found = false
1774
+ for (let i = headerIdx + 1; i < lines.length; i++) {
1775
+ const line = lines[i]
1776
+ if (!line.startsWith(" ") || !line.includes("|")) continue
1777
+ if (line.startsWith(" summaries:")) break
1778
+ const parts = line.trim().split("|")
1779
+ if (parts[0] === key || parts[2] === key) {
1780
+ if (parts.length > 13) {
1781
+ parts[13] = "0"
1782
+ lines[i] = ` ${parts.join("|")}`
1783
+ }
1784
+ found = true
1785
+ break
1786
+ }
1787
+ }
1788
+
1789
+ if (!found) {
1790
+ return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
1791
+ }
1792
+
1793
+ writeMemory(lines.join("\n"))
1794
+ return { content: [{ type: "text" as const, text: `Unpinned "${key}". It will now use normal ranking.` }] }
1795
+ }
1796
+ )
1797
+
1798
+ // ── memory_search ────────────────────────────────────────────────────────────
1799
+
1800
+ server.registerTool(
1801
+ "memory_search",
1802
+ {
1803
+ title: "Unified Search",
1804
+ description: "Search memory with combined filters: text query, category, tags, and date range. Returns ranked results.",
1805
+ inputSchema: {
1806
+ query: z.string().describe("Text to search for"),
1807
+ category: z.string().optional().default("").describe("Filter by category (empty = all)"),
1808
+ tags: z.string().optional().default("").describe("Semicolon-separated tags; entry must have ALL specified tags"),
1809
+ from_date: z.string().optional().default("").describe("Start date filter (YYYY-MM-DD or relative like 7d)"),
1810
+ to_date: z.string().optional().default("").describe("End date filter (YYYY-MM-DD)"),
1811
+ limit: z.number().optional().default(6).describe("Maximum entries to return"),
1812
+ mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
1813
+ hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
1814
+ compact: z.boolean().optional().default(false).describe("Token-efficient output"),
1815
+ bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
1816
+ },
1817
+ },
1818
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias }) => {
1819
+ const data = readMemory()
1820
+
1821
+ const resolvedFrom = from_date ? parseRelativeDate(from_date) : ""
1822
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
1823
+ const detail = graphRecallDetailed(data, query, {
1824
+ category: category || undefined,
1825
+ tags: tags || undefined,
1826
+ from_date: resolvedFrom || undefined,
1827
+ to_date: to_date || undefined,
1828
+ hops,
1829
+ limit,
1830
+ sessionFiles,
1831
+ })
1832
+
1833
+ if (detail.entries.length === 0) {
1834
+ return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
1835
+ }
1836
+
1837
+ bumpAccessed(detail.entries.map((e) => e.id))
1838
+
1839
+ if (compact) {
1840
+ const formatted = renderCompact(detail.entries, {
1841
+ adjacency: detail.adjacency,
1842
+ seeds: detail.seeds,
1843
+ snippetLen: 90,
1844
+ })
1845
+ return { content: [{ type: "text" as const, text: `🔍 Search: "${query}"\n\n${formatted}` }] }
1846
+ }
1847
+
1848
+ const formatted = detail.entries
1849
+ .map((r) => {
1850
+ const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
1851
+ const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
1852
+ return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
1853
+ })
1854
+ .join("\n\n")
1855
+
1856
+ let filterInfo = ""
1857
+ if (category) filterInfo += ` category: ${category}`
1858
+ if (tags) filterInfo += ` tags: ${tags}`
1859
+ if (from_date) filterInfo += ` from: ${from_date}`
1860
+ if (to_date) filterInfo += ` to: ${to_date}`
1861
+
1862
+ return {
1863
+ content: [{ type: "text" as const, text: `🔍 Search results${filterInfo}:\n\n${formatted}` }],
1864
+ }
1865
+ }
1866
+ )
1867
+
1868
+ // ── memory_tag ───────────────────────────────────────────────────────────────
1869
+
1870
+ server.registerTool(
1871
+ "memory_tag",
1872
+ {
1873
+ title: "Batch Tag Operations",
1874
+ description: "Batch add, remove, or set tags on one or more memory entries by key or id.",
1875
+ inputSchema: {
1876
+ action: z.enum(["add", "remove", "set"]).describe("'add': merge tags (union). 'remove': remove specified tags. 'set': replace all tags."),
1877
+ tags: z.string().describe("Semicolon-separated tags to apply"),
1878
+ ids: z.string().describe("Comma or space-separated entry keys or IDs to modify"),
1879
+ },
1880
+ },
1881
+ async ({ action, tags, ids }) => {
1882
+ const data = readMemory()
1883
+ const lines = data.split("\n")
1884
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1885
+
1886
+ if (headerIdx === -1) {
1887
+ return { content: [{ type: "text" as const, text: "No entries in memory." }] }
1888
+ }
1889
+
1890
+ const targetIds = ids.split(/[\s,]+/).filter(Boolean)
1891
+ const targetSet = new Set(targetIds)
1892
+ const tagsToApply = tags.split(";").map((t) => t.trim()).filter(Boolean)
1893
+
1894
+ if (tagsToApply.length === 0) {
1895
+ return { content: [{ type: "text" as const, text: "No tags provided." }] }
1896
+ }
1897
+
1898
+ let modified = 0
1899
+ const modifiedKeys: string[] = []
1900
+
1901
+ for (let i = headerIdx + 1; i < lines.length; i++) {
1902
+ const line = lines[i]
1903
+ if (!line.startsWith(" ") || !line.includes("|")) continue
1904
+ if (line.startsWith(" summaries:")) break
1905
+ const parts = line.trim().split("|")
1906
+ const entryId = parts[0]
1907
+ const entryKey = parts[2]
1908
+
1909
+ if (!targetSet.has(entryId) && !targetSet.has(entryKey)) continue
1910
+
1911
+ const currentTags = (parts[5] || "").split(";").map((t) => t.trim()).filter(Boolean)
1912
+ let newTags: string[]
1913
+
1914
+ if (action === "add") {
1915
+ newTags = [...new Set([...currentTags, ...tagsToApply])]
1916
+ } else if (action === "remove") {
1917
+ newTags = currentTags.filter((t) => !tagsToApply.includes(t))
1918
+ } else {
1919
+ newTags = [...tagsToApply]
1920
+ }
1921
+
1922
+ parts[5] = newTags.join(";")
1923
+ lines[i] = ` ${parts.join("|")}`
1924
+ modified++
1925
+ modifiedKeys.push(entryKey)
1926
+ }
1927
+
1928
+ if (modified === 0) {
1929
+ return { content: [{ type: "text" as const, text: `No entries found matching: ${targetIds.join(", ")}` }] }
1930
+ }
1931
+
1932
+ writeMemory(lines.join("\n"))
1933
+
1934
+ const actionLabel = action === "add" ? "Added" : action === "remove" ? "Removed" : "Set"
1935
+ return {
1936
+ content: [{
1937
+ type: "text" as const,
1938
+ text: `🏷️ ${actionLabel} tags on ${modified} entries:\n Tags: ${tagsToApply.join(";")}\n Entries: ${modifiedKeys.join(", ")}`,
1939
+ }],
1940
+ }
1941
+ }
1942
+ )
1943
+
1554
1944
  // ── memory_visualize (MCP Apps) ──────────────────────────────────────────────
1555
1945
 
1556
1946
  registerAppTool(