toon-memory 2.11.0 → 3.1.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,11 +11,13 @@ 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"
18
18
  import { fileMtimes } from "../lib/git"
19
+ import { normalize, isExpiredLocal, tokenize, importance } from "../lib/utils"
20
+ import { expandSynonyms } from "../lib/synonyms"
19
21
 
20
22
  /**
21
23
  * Register all 20 memory tools.
@@ -67,7 +69,9 @@ server.registerTool(
67
69
 
68
70
  const entryId = existingIdx !== -1 ? existingId : newId
69
71
  const resolvedTtl = parseTTL(ttl)
70
- const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab)
72
+ const config = loadConfig()
73
+ const verbatim = config.verbatim === true
74
+ const resolvedTags = tags ? tags : (verbatim ? "" : inferTags(content, key, config.vocab))
71
75
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
72
76
  const resolvedLinks = links
73
77
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
@@ -83,9 +87,11 @@ server.registerTool(
83
87
  action = "Updated"
84
88
  mergeInfo = "\nMerge: tags combined, date and links updated"
85
89
  } else {
86
- const quality = qualityScore(resolvedTags, resolvedLinks, content, date)
90
+ const accessed = 0
91
+ const lastAccessed = ""
92
+ const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed)
87
93
  const confidence = 1.0
88
- newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}|${quality.toFixed(2)}|${confidence}`
94
+ newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`
89
95
  const match = lines[headerIdx].match(/\[(\d+)\|/)
90
96
  const count = match ? parseInt(match[1]) : 0
91
97
  lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
@@ -256,8 +262,21 @@ server.registerTool(
256
262
  const parts = l.trim().split("|")
257
263
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
258
264
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
259
- return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}`
265
+ const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : ""
266
+ return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}`
260
267
  }),
268
+ "",
269
+ `Most accessed:`,
270
+ ...lines
271
+ .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
272
+ .map((l) => {
273
+ const parts = l.trim().split("|")
274
+ return { key: parts[2], accessed: parts.length > 8 ? parseInt(parts[8]) || 0 : 0, quality: parts[10] || "" }
275
+ })
276
+ .filter((e) => e.accessed > 0)
277
+ .sort((a, b) => b.accessed - a.accessed)
278
+ .slice(0, 5)
279
+ .map((e) => ` ${e.key}: ${e.accessed}x (Q: ${e.quality})`),
261
280
  ]
262
281
 
263
282
  return { content: [{ type: "text" as const, text: stats.join("\n") }] }
@@ -826,4 +845,727 @@ server.registerTool(
826
845
  }
827
846
  )
828
847
 
848
+ // ── memory_primer ─────────────────────────────────────────────────────
849
+
850
+ server.registerTool(
851
+ "memory_primer",
852
+ {
853
+ title: "System Primer",
854
+ description: "Generate a compact system primer: always-current knowledge map for auto-injection into agent context. Excludes private entries, shows top memories by importance, categories, and patterns. Use at session start or when context feels stale.",
855
+ inputSchema: {},
856
+ },
857
+ async () => {
858
+ const data = readMemory()
859
+ const { generateSystemPrimer } = await import("../lib/quality")
860
+ const primer = generateSystemPrimer(data)
861
+ return { content: [{ type: "text" as const, text: primer }] }
862
+ }
863
+ )
864
+
865
+ // ── memory_compress ────────────────────────────────────────────────────
866
+
867
+ server.registerTool(
868
+ "memory_compress",
869
+ {
870
+ title: "Compress Memory Entries",
871
+ description: "LLM-powered compression: select entries to compress into one concise entry. The agent (YOU) reads the entries, writes a compressed summary, then calls memory_remember to save it. Two-step dance: this tool provides context, you provide intelligence.",
872
+ inputSchema: {
873
+ query: z.string().optional().default("").describe("Search query to find entries to compress (e.g. 'auth bug fixes'). Empty = show lowest-quality entries."),
874
+ count: z.number().optional().default(3).describe("Number of entries to compress (2-10). Default: 3."),
875
+ category: z.string().optional().default("").describe("Filter by category (empty = all)."),
876
+ },
877
+ },
878
+ async ({ query, count, category }) => {
879
+ const data = readMemory()
880
+ const entries = parseEntries(data)
881
+ const clampedCount = Math.max(2, Math.min(10, count))
882
+
883
+ let candidates: typeof entries
884
+
885
+ if (query) {
886
+ // Find entries matching the query
887
+ const qTokens = tokenize(query)
888
+ const expandedTokens = expandSynonyms(qTokens)
889
+ candidates = entries
890
+ .filter((e) => {
891
+ if (category && e.category !== category) return false
892
+ if (e.ttl && isExpiredLocal(e.ttl)) return false
893
+ const text = normalize(`${e.key} ${e.content} ${e.tags.join(" ")}`)
894
+ return expandedTokens.some((t) => text.includes(t)) || qTokens.some((t) => text.includes(t))
895
+ })
896
+ .sort((a, b) => importance(b) - importance(a))
897
+ } else {
898
+ // Find lowest-quality entries (candidates for compression)
899
+ candidates = entries
900
+ .filter((e) => {
901
+ if (category && e.category !== category) return false
902
+ if (e.ttl && isExpiredLocal(e.ttl)) return false
903
+ return true
904
+ })
905
+ .sort((a, b) => importance(a) - importance(b))
906
+ }
907
+
908
+ const toCompress = candidates.slice(0, clampedCount)
909
+
910
+ if (toCompress.length < 2) {
911
+ return {
912
+ content: [{
913
+ type: "text" as const,
914
+ text: `Need at least 2 entries to compress. Found ${toCompress.length} matching entries.`
915
+ }],
916
+ }
917
+ }
918
+
919
+ // Build the compression prompt for the agent
920
+ const entryList = toCompress.map((e, i) =>
921
+ `${i + 1}. [${e.category}] ${e.key} (${e.id})\n ${e.content}\n Tags: ${e.tags.join(";")} | File: ${e.file} | Date: ${e.date}`
922
+ ).join("\n\n")
923
+
924
+ const prompt = [
925
+ `📦 Compress ${toCompress.length} entries into 1 concise entry.`,
926
+ "",
927
+ "Entries to compress:",
928
+ entryList,
929
+ "",
930
+ "Instructions:",
931
+ "1. Read the entries above",
932
+ "2. Write a single concise summary that captures the essential information",
933
+ "3. Call memory_remember with:",
934
+ ` - category: "${toCompress[0].category}" (or most appropriate)`,
935
+ " - key: a short kebab-case title (e.g. 'auth-bug-patterns')",
936
+ " - content: your compressed summary (1-3 sentences)",
937
+ " - tags: combine the most relevant tags from all entries",
938
+ ` - file: "${toCompress.find((e) => e.file)?.file || ""}" (if applicable)`,
939
+ " - links: combine relevant links",
940
+ "",
941
+ "4. After saving, call memory_forget for each original entry ID:",
942
+ toCompress.map((e) => ` memory_forget(key: "${e.id}")`).join("\n"),
943
+ "",
944
+ "The compressed entry should be strictly better than the sum of its parts.",
945
+ ].join("\n")
946
+
947
+ return { content: [{ type: "text" as const, text: prompt }] }
948
+ }
949
+ )
950
+
951
+ // ── memory_compress_all ────────────────────────────────────────────────
952
+
953
+ server.registerTool(
954
+ "memory_compress_all",
955
+ {
956
+ title: "Lazy Batch Compression",
957
+ description: "Compress all low-quality entries (no tags, low quality score) in one pass. Deterministic, no LLM — merges entries with similar content and removes empty/stale ones. Inspired by MemPalace's lazy compression.",
958
+ inputSchema: {
959
+ minQuality: z.number().optional().default(0.3).describe("Entries below this quality score are compression candidates (0-1). Default: 0.3."),
960
+ dryRun: z.boolean().optional().default(false).describe("If true, show what would be compressed without making changes."),
961
+ },
962
+ },
963
+ async ({ minQuality, dryRun }) => {
964
+ const data = readMemory()
965
+ const lines = data.split("\n")
966
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
967
+ if (headerIdx === -1) {
968
+ return { content: [{ type: "text" as const, text: "No entries in memory." }] }
969
+ }
970
+
971
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
972
+
973
+ // Find compression candidates: low quality, no tags, or stale
974
+ const candidates: { idx: number; line: string; quality: number; key: string }[] = []
975
+ for (let i = 0; i < entryLines.length; i++) {
976
+ const line = entryLines[i].trim()
977
+ const parts = line.split("|")
978
+ if (parts.length < 11) continue
979
+ const quality = parseFloat(parts[10]) || 0
980
+ const tags = parts[5] || ""
981
+ const key = parts[2]
982
+ const content = parts[3] || ""
983
+
984
+ // Candidates: low quality OR no tags OR very short content
985
+ const isCandidate = quality < minQuality || !tags || content.length < 20
986
+ if (isCandidate) {
987
+ candidates.push({ idx: i, line, quality, key })
988
+ }
989
+ }
990
+
991
+ if (candidates.length === 0) {
992
+ return {
993
+ content: [{
994
+ type: "text" as const,
995
+ text: `✅ No compression candidates found. All entries have quality >= ${minQuality} or have tags.`
996
+ }],
997
+ }
998
+ }
999
+
1000
+ // Group candidates by category for potential merging
1001
+ const byCategory = new Map<string, typeof candidates>()
1002
+ for (const c of candidates) {
1003
+ const parts = c.line.split("|")
1004
+ const cat = parts[1] || "unknown"
1005
+ if (!byCategory.has(cat)) byCategory.set(cat, [])
1006
+ byCategory.get(cat)!.push(c)
1007
+ }
1008
+
1009
+ const sections: string[] = [
1010
+ `📦 Compression candidates: ${candidates.length} entries below quality ${minQuality}`,
1011
+ "",
1012
+ "By category:",
1013
+ ]
1014
+
1015
+ for (const [cat, items] of byCategory) {
1016
+ sections.push(` ${cat}: ${items.length} entries`)
1017
+ for (const item of items.slice(0, 3)) {
1018
+ const parts = item.line.split("|")
1019
+ sections.push(` - ${item.key} (Q: ${item.quality.toFixed(2)}) — ${(parts[3] || "").slice(0, 60)}`)
1020
+ }
1021
+ if (items.length > 3) {
1022
+ sections.push(` ... and ${items.length - 3} more`)
1023
+ }
1024
+ }
1025
+
1026
+ if (dryRun) {
1027
+ sections.push("", "🔍 Dry run — no changes made. Use dryRun: false to compress.")
1028
+ return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1029
+ }
1030
+
1031
+ // Remove candidates (conservative: just remove the lowest quality ones)
1032
+ // Don't auto-merge — let the agent decide via memory_compress
1033
+ const removeKeys = new Set(candidates.map((c) => c.key))
1034
+ const kept = entryLines.filter((l) => {
1035
+ const parts = l.trim().split("|")
1036
+ return !removeKeys.has(parts[2])
1037
+ })
1038
+
1039
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
1040
+ const count = match ? parseInt(match[1]) : 0
1041
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
1042
+ lines.splice(headerIdx + 1, entryLines.length, ...kept.map((l) => ` ${l.trim()}`))
1043
+ writeMemory(lines.join("\n"))
1044
+
1045
+ sections.push("", `🗑️ Removed ${candidates.length} low-quality entries. ${kept.length} entries remaining.`)
1046
+ sections.push("💡 Use memory_compress to merge related entries before removing them.")
1047
+
1048
+ return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1049
+ }
1050
+ )
1051
+
1052
+ // ── memory_export_gist ─────────────────────────────────────────────────
1053
+
1054
+ server.registerTool(
1055
+ "memory_export_gist",
1056
+ {
1057
+ title: "Export to GitHub Gist",
1058
+ description: "Export memory to a private GitHub Gist for cloud sync. Requires GITHUB_TOKEN env var. Zero deps — uses Node's built-in fetch().",
1059
+ inputSchema: {
1060
+ description: z.string().optional().default("").describe("Optional description for the Gist."),
1061
+ },
1062
+ },
1063
+ async ({ description }) => {
1064
+ const token = process.env.GITHUB_TOKEN
1065
+ if (!token) {
1066
+ return {
1067
+ content: [{
1068
+ type: "text" as const,
1069
+ text: "❌ GITHUB_TOKEN not set. Add it to your environment:\n export GITHUB_TOKEN=ghp_your_token_here"
1070
+ }],
1071
+ }
1072
+ }
1073
+
1074
+ if (!existsSync(MEMORY_FILE)) {
1075
+ return { content: [{ type: "text" as const, text: "No memory file to export." }] }
1076
+ }
1077
+
1078
+ const data = readFileSync(MEMORY_FILE, "utf-8")
1079
+ const desc = description || `toon-memory backup ${new Date().toISOString().split("T")[0]}`
1080
+
1081
+ try {
1082
+ const resp = await fetch("https://api.github.com/gists", {
1083
+ method: "POST",
1084
+ headers: {
1085
+ Authorization: `Bearer ${token}`,
1086
+ "Content-Type": "application/json",
1087
+ Accept: "application/vnd.github.v3+json",
1088
+ },
1089
+ body: JSON.stringify({
1090
+ description: desc,
1091
+ public: false,
1092
+ files: {
1093
+ "data.toon": { content: data },
1094
+ },
1095
+ }),
1096
+ })
1097
+
1098
+ if (!resp.ok) {
1099
+ const err = await resp.text()
1100
+ return { content: [{ type: "text" as const, text: `❌ GitHub API error (${resp.status}): ${err}` }] }
1101
+ }
1102
+
1103
+ const gist = await resp.json() as { id: string; html_url: string; created_at: string }
1104
+ return {
1105
+ content: [{
1106
+ type: "text" as const,
1107
+ text: `📤 Memory exported to Gist\nID: ${gist.id}\nURL: ${gist.html_url}\n\nTo import later: memory_import_gist(gist_id: "${gist.id}")`
1108
+ }],
1109
+ }
1110
+ } catch (err) {
1111
+ return { content: [{ type: "text" as const, text: `❌ Failed to export: ${err}` }] }
1112
+ }
1113
+ }
1114
+ )
1115
+
1116
+ // ── memory_import_gist ─────────────────────────────────────────────────
1117
+
1118
+ server.registerTool(
1119
+ "memory_import_gist",
1120
+ {
1121
+ title: "Import from GitHub Gist",
1122
+ description: "Import memory from a GitHub Gist. Merges entries (keeps newer dates, combines tags). Requires GITHUB_TOKEN env var.",
1123
+ inputSchema: {
1124
+ gist_id: z.string().describe("GitHub Gist ID or full URL (https://gist.github.com/user/id)."),
1125
+ merge: z.boolean().optional().default(true).describe("If true, merge with existing memory. If false, replace entirely."),
1126
+ },
1127
+ },
1128
+ async ({ gist_id, merge }) => {
1129
+ const token = process.env.GITHUB_TOKEN
1130
+ if (!token) {
1131
+ return {
1132
+ content: [{
1133
+ type: "text" as const,
1134
+ text: "❌ GITHUB_TOKEN not set. Add it to your environment:\n export GITHUB_TOKEN=ghp_your_token_here"
1135
+ }],
1136
+ }
1137
+ }
1138
+
1139
+ // Extract gist ID from URL if needed
1140
+ const idMatch = gist_id.match(/\/([a-f0-9]+)$/i) || [null, gist_id]
1141
+ const id = idMatch[1] || gist_id
1142
+
1143
+ try {
1144
+ const resp = await fetch(`https://api.github.com/gists/${id}`, {
1145
+ headers: {
1146
+ Authorization: `Bearer ${token}`,
1147
+ Accept: "application/vnd.github.v3+json",
1148
+ },
1149
+ })
1150
+
1151
+ if (!resp.ok) {
1152
+ const err = await resp.text()
1153
+ return { content: [{ type: "text" as const, text: `❌ GitHub API error (${resp.status}): ${err}` }] }
1154
+ }
1155
+
1156
+ const gist = await resp.json() as { files: Record<string, { content: string }> }
1157
+ const file = gist.files["data.toon"]
1158
+ if (!file) {
1159
+ return { content: [{ type: "text" as const, text: "❌ Gist does not contain data.toon file." }] }
1160
+ }
1161
+
1162
+ const remoteData = file.content
1163
+
1164
+ if (!merge) {
1165
+ // Replace entirely
1166
+ safeWrite(MEMORY_FILE, remoteData)
1167
+ const entries = parseEntries(remoteData)
1168
+ return {
1169
+ content: [{
1170
+ type: "text" as const,
1171
+ text: `📥 Memory replaced from Gist (${entries.length} entries).`
1172
+ }],
1173
+ }
1174
+ }
1175
+
1176
+ // Merge mode: combine entries from both sources
1177
+ const localData = existsSync(MEMORY_FILE) ? readFileSync(MEMORY_FILE, "utf-8") : "version: 1\nentries[0|]\n"
1178
+ const localEntries = parseEntries(localData)
1179
+ const remoteEntries = parseEntries(remoteData)
1180
+
1181
+ const localByKey = new Map(localEntries.map((e) => [e.key, e]))
1182
+ let added = 0
1183
+ let updated = 0
1184
+
1185
+ for (const remote of remoteEntries) {
1186
+ const existing = localByKey.get(remote.key)
1187
+ if (!existing) {
1188
+ // New entry from remote
1189
+ localByKey.set(remote.key, remote)
1190
+ added++
1191
+ } else {
1192
+ // Merge: keep newer date, combine tags, take max quality
1193
+ const mergedTags = [...new Set([...existing.tags, ...remote.tags])].join(";")
1194
+ const mergedLinks = [...new Set([...existing.links, ...remote.links])].join(" ")
1195
+ const newerDate = remote.date > existing.date ? remote.date : existing.date
1196
+ const merged = {
1197
+ ...existing,
1198
+ tags: mergedTags.split(";").filter(Boolean),
1199
+ links: mergedLinks.split(/[\s;]+/).filter(Boolean),
1200
+ date: newerDate,
1201
+ content: remote.content.length > existing.content.length ? remote.content : existing.content,
1202
+ }
1203
+ localByKey.set(remote.key, merged)
1204
+ updated++
1205
+ }
1206
+ }
1207
+
1208
+ // Rebuild the file
1209
+ const entries = [...localByKey.values()]
1210
+ const lines = [
1211
+ "version: 1",
1212
+ `[${entries.length}|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence|lastAccessed}:`,
1213
+ ...entries.map((e) => {
1214
+ const tags = e.tags.join(";")
1215
+ const links = e.links.join(" ")
1216
+ const q = qualityScore(tags, links, e.content, e.date, e.accessed, e.lastAccessed)
1217
+ return ` ${e.id}|${e.category}|${e.key}|${e.content}|${e.file}|${tags}|${e.date}|${e.ttl}|${e.accessed}|${links}|${q.toFixed(2)}|1|${e.lastAccessed}`
1218
+ }),
1219
+ ]
1220
+ safeWrite(MEMORY_FILE, lines.join("\n"))
1221
+
1222
+ return {
1223
+ content: [{
1224
+ type: "text" as const,
1225
+ text: `📥 Memory merged from Gist\n Added: ${added} new entries\n Updated: ${updated} existing entries\n Total: ${entries.length} entries`
1226
+ }],
1227
+ }
1228
+ } catch (err) {
1229
+ return { content: [{ type: "text" as const, text: `❌ Failed to import: ${err}` }] }
1230
+ }
1231
+ }
1232
+ )
1233
+
1234
+ // ── memory_merge_sessions ──────────────────────────────────────────────
1235
+
1236
+ server.registerTool(
1237
+ "memory_merge_sessions",
1238
+ {
1239
+ title: "Merge Session Observations",
1240
+ description: "Merge observations from multiple sessions/branches into a consolidated view. Deduplicates and suggests entries to promote to memory. Inspired by Hindsight's multi-agent session merging.",
1241
+ inputSchema: {
1242
+ since: z.string().optional().default("24h").describe("Time window to merge (e.g. '24h', '7d', '2026-07-20'). Default: 24h."),
1243
+ promote: z.boolean().optional().default(false).describe("If true, auto-promote unique observations to memory entries."),
1244
+ },
1245
+ },
1246
+ async ({ since, promote }) => {
1247
+ const { listSessions, pruneSessions } = await import("../lib/sessions")
1248
+ pruneSessions()
1249
+ const sessions = listSessions()
1250
+
1251
+ // Filter sessions by time window
1252
+ const sinceMs = parseRelativeMs(since)
1253
+ const cutoff = Date.now() - sinceMs
1254
+ const recentSessions = sessions.filter((s) => new Date(s.lastSeen).getTime() >= cutoff)
1255
+
1256
+ if (recentSessions.length === 0) {
1257
+ return { content: [{ type: "text" as const, text: `No sessions found in the last ${since}.` }] }
1258
+ }
1259
+
1260
+ // Collect all files touched across sessions
1261
+ const allFiles = new Map<string, Array<{ session: string; agent: string; branch: string; touched: string }>>()
1262
+ for (const s of recentSessions) {
1263
+ for (const [file, touched] of Object.entries(s.files)) {
1264
+ if (!allFiles.has(file)) allFiles.set(file, [])
1265
+ allFiles.get(file)!.push({ session: s.id, agent: s.agent, branch: s.branch, touched })
1266
+ }
1267
+ }
1268
+
1269
+ // Find files touched by multiple sessions (potential merge points)
1270
+ const sharedFiles = [...allFiles.entries()]
1271
+ .filter(([_, sessions]) => sessions.length >= 2)
1272
+ .sort((a, b) => b[1].length - a[1].length)
1273
+
1274
+ // Read observations for these sessions
1275
+ let observations: Array<{ ts: string; session: string; agent: string; branch: string; tool: string; file: string; summary: string }> = []
1276
+ if (existsSync(OBSERVATIONS_FILE)) {
1277
+ const data = readFileSync(OBSERVATIONS_FILE, "utf-8")
1278
+ const sessionIds = new Set(recentSessions.map((s) => s.id))
1279
+ observations = data.split("\n")
1280
+ .filter((l) => l.startsWith(" ") && l.includes("|"))
1281
+ .map((l) => {
1282
+ const p = l.trim().split("|")
1283
+ return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
1284
+ })
1285
+ .filter((o) => sessionIds.has(o.session))
1286
+ }
1287
+
1288
+ // Deduplicate observations by tool+summary hash
1289
+ const seen = new Set<string>()
1290
+ const uniqueObs = observations.filter((o) => {
1291
+ const key = `${o.tool}|${o.summary}`
1292
+ if (seen.has(key)) return false
1293
+ seen.add(key)
1294
+ return true
1295
+ })
1296
+
1297
+ // Build output
1298
+ const sections: string[] = [
1299
+ `🔀 Session Merge Report (${recentSessions.length} sessions, last ${since})`,
1300
+ "",
1301
+ `Sessions:`,
1302
+ ...recentSessions.map((s) => {
1303
+ const mins = Math.max(0, Math.round((Date.now() - new Date(s.lastSeen).getTime()) / 60000))
1304
+ const files = Object.keys(s.files).length
1305
+ return ` ${s.agent}@${s.branch} (${s.id}) — ${mins}min ago, ${files} files`
1306
+ }),
1307
+ ]
1308
+
1309
+ if (sharedFiles.length > 0) {
1310
+ sections.push("", `Shared files (${sharedFiles.length}):`)
1311
+ for (const [file, sess] of sharedFiles.slice(0, 10)) {
1312
+ const who = sess.map((s) => `${s.agent}@${s.branch}`).join(", ")
1313
+ sections.push(` ${file} ↔ ${who}`)
1314
+ }
1315
+ }
1316
+
1317
+ if (uniqueObs.length > 0) {
1318
+ sections.push("", `Unique observations (${uniqueObs.length} of ${observations.length} total):`)
1319
+ for (const o of uniqueObs.slice(0, 15)) {
1320
+ sections.push(` [${o.tool}] ${o.agent}@${o.branch}: ${o.summary.slice(0, 100)}`)
1321
+ }
1322
+ }
1323
+
1324
+ // Auto-promote mode
1325
+ if (promote && uniqueObs.length > 0) {
1326
+ const data = readMemory()
1327
+ const entries = parseEntries(data)
1328
+ const existingKeys = new Set(entries.map((e) => e.key))
1329
+ let promoted = 0
1330
+
1331
+ for (const obs of uniqueObs.slice(0, 5)) {
1332
+ // Generate a key from the observation summary
1333
+ const key = obs.summary
1334
+ .toLowerCase()
1335
+ .replace(/[^a-z0-9\s]/g, "")
1336
+ .split(/\s+/)
1337
+ .slice(0, 4)
1338
+ .join("-")
1339
+ .slice(0, 40)
1340
+
1341
+ if (!key || existingKeys.has(key)) continue
1342
+
1343
+ // Use memory_remember logic inline
1344
+ const newId = generateId()
1345
+ const date = new Date().toISOString().split("T")[0]
1346
+ const content = obs.summary.slice(0, 500)
1347
+ const file = obs.file || ""
1348
+ const tags = `session-merge;${obs.agent};${obs.branch}`
1349
+ const quality = qualityScore(tags, "", content, date)
1350
+ const entry = `${newId}|knowledge|${key}|${content}|${file}|${tags}|${date}||0||${quality.toFixed(2)}|1|`
1351
+
1352
+ // Append to memory
1353
+ const lines = data.split("\n")
1354
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1355
+ if (headerIdx === -1) {
1356
+ lines.push(`[0|]`)
1357
+ headerIdx = lines.length - 1
1358
+ }
1359
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
1360
+ const count = match ? parseInt(match[1]) : 0
1361
+ lines.splice(headerIdx + 1, 0, ` ${entry}`)
1362
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
1363
+ writeMemory(lines.join("\n"))
1364
+ existingKeys.add(key)
1365
+ promoted++
1366
+ }
1367
+
1368
+ sections.push("", `📤 Promoted ${promoted} observations to memory.`)
1369
+ } else if (uniqueObs.length > 0) {
1370
+ sections.push("", `💡 Use 'promote: true' to auto-save unique observations as memory entries.`)
1371
+ }
1372
+
1373
+ return { content: [{ type: "text" as const, text: sections.join("\n") }] }
1374
+ }
1375
+ )
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
+
829
1553
  } // end registerTools
1554
+
1555
+ /** Parse relative time string to milliseconds. */
1556
+ function parseRelativeMs(s: string): number {
1557
+ const match = s.match(/^(\d+)(h|d|m)$/i)
1558
+ if (!match) {
1559
+ // Try parsing as date
1560
+ const d = new Date(s)
1561
+ if (!isNaN(d.getTime())) return Date.now() - d.getTime()
1562
+ return 24 * 60 * 60 * 1000 // default 24h
1563
+ }
1564
+ const n = parseInt(match[1])
1565
+ switch (match[2].toLowerCase()) {
1566
+ case "m": return n * 60 * 1000
1567
+ case "h": return n * 60 * 60 * 1000
1568
+ case "d": return n * 24 * 60 * 60 * 1000
1569
+ default: return 24 * 60 * 60 * 1000
1570
+ }
1571
+ }