toon-memory 3.4.0 → 3.6.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,13 +15,13 @@ 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"
22
22
 
23
23
  /**
24
- * Register all 20 memory tools.
24
+ * Register all 22 memory tools.
25
25
  */
26
26
  export function registerTools(server: McpServer): void {
27
27
 
@@ -40,9 +40,11 @@ server.registerTool(
40
40
  tags: z.string().optional().default("").describe("Semicolon-separated tags (e.g. risk;spec)"),
41
41
  ttl: z.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration"),
42
42
  links: z.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
43
+ path_scope: z.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
44
+ origin: z.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
43
45
  },
44
46
  },
45
- async ({ category, key, content, file, tags, ttl, links }) => {
47
+ async ({ category, key, content, file, tags, ttl, links, path_scope, origin }) => {
46
48
  const data = readMemory()
47
49
  const newId = generateId()
48
50
  const date = new Date().toISOString().split("T")[0]
@@ -77,7 +79,7 @@ server.registerTool(
77
79
  const resolvedLinks = links
78
80
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
79
81
  : existingParts[9] || ""
80
- let newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}`
82
+ let newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|0|${resolvedLinks}|||||${path_scope || ""}|${origin}`
81
83
  let action = "Saved"
82
84
  let mergeInfo = ""
83
85
  const tagsInferred = !tags && resolvedTags ? true : false
@@ -90,9 +92,9 @@ server.registerTool(
90
92
  } else {
91
93
  const accessed = 0
92
94
  const lastAccessed = ""
93
- const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed)
95
+ const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed, origin)
94
96
  const confidence = 1.0
95
- newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`
97
+ newEntry = `${entryId}|${category}|${key}|${content}|${file || ""}|${resolvedTags}|${date}|${resolvedTtl}|${accessed}|${resolvedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|0|${path_scope || ""}|${origin}|active`
96
98
  const match = lines[headerIdx].match(/\[(\d+)\|/)
97
99
  const count = match ? parseInt(match[1]) : 0
98
100
  lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
@@ -142,30 +144,40 @@ server.registerTool(
142
144
  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
145
  hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
144
146
  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."),
147
+ budget: z.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'."),
148
+ bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
149
+ path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
145
150
  },
146
151
  },
147
- async ({ query, category, from_date, to_date, mode, hops, compact }) => {
152
+ async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
148
153
  const data = readMemory()
149
154
 
150
155
  // Delegate to graphRecallDetailed for both flat and graph modes
151
156
  // This avoids duplicating BM25 + ranking logic
152
- const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
157
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
158
+ const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
159
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops, sessionFiles, path_scope: path_scope || undefined })
153
160
  if (detail.entries.length === 0) {
154
161
  return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
155
162
  }
156
163
  bumpAccessed(detail.entries.map((e) => e.id))
157
- if (compact) {
164
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
158
165
  const formatted = renderCompact(detail.entries, {
159
166
  adjacency: detail.adjacency,
160
167
  seeds: detail.seeds,
161
168
  snippetLen: 90,
169
+ budget: resolvedBudget,
162
170
  })
163
171
  return { content: [{ type: "text" as const, text: formatted }] }
164
172
  }
165
173
  const formatted = detail.entries
166
174
  .map((r) => {
167
175
  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}`
176
+ const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
177
+ const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
178
+ const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
179
+ const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
180
+ return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}`
169
181
  })
170
182
  .join("\n\n")
171
183
  return { content: [{ type: "text" as const, text: formatted }] }
@@ -181,9 +193,10 @@ server.registerTool(
181
193
  description: "Delete a memory entry by its key or id.",
182
194
  inputSchema: {
183
195
  key: z.string().describe("Key or id of the entry to delete"),
196
+ hard: z.boolean().optional().default(false).describe("If true, permanently remove the entry. If false (default), softly marks as obsolete (status=obsolete) so it can be resolved or restored later."),
184
197
  },
185
198
  },
186
- async ({ key }) => {
199
+ async ({ key, hard }) => {
187
200
  const data = readMemory()
188
201
  const lines = data.split("\n")
189
202
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
@@ -192,28 +205,58 @@ server.registerTool(
192
205
  return { content: [{ type: "text" as const, text: "No entries in memory" }] }
193
206
  }
194
207
 
195
- const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
196
- const filtered = entryLines.filter((l) => {
197
- const parts = l.trim().split("|")
198
- return parts[0] !== key && parts[2] !== key
199
- })
208
+ if (hard) {
209
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
210
+ const filtered = entryLines.filter((l) => {
211
+ const parts = l.trim().split("|")
212
+ return parts[0] !== key && parts[2] !== key
213
+ })
200
214
 
201
- const removed = entryLines.length - filtered.length
202
- const match = lines[headerIdx].match(/\[(\d+)\|/)
203
- const count = match ? parseInt(match[1]) : 0
204
- lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`)
205
- lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
215
+ const removed = entryLines.length - filtered.length
216
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
217
+ const count = match ? parseInt(match[1]) : 0
218
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count - removed}|`)
219
+ lines.splice(headerIdx + 1, entryLines.length, ...filtered.map((l) => ` ${l.trim()}`))
220
+
221
+ writeMemory(lines.join("\n"))
222
+
223
+ if (removed === 0) {
224
+ return {
225
+ content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
226
+ }
227
+ }
228
+
229
+ return {
230
+ content: [{ type: "text" as const, text: `"${key}" permanently deleted. ${count - removed} entries remaining.` }],
231
+ }
232
+ }
233
+
234
+ // Soft-delete: mark status as "obsolete"
235
+ let found = false
236
+ for (let i = headerIdx + 1; i < lines.length; i++) {
237
+ const line = lines[i]
238
+ if (!line.startsWith(" ") || !line.includes("|")) continue
239
+ if (line.startsWith(" summaries:")) break
240
+ const parts = line.trim().split("|")
241
+ if (parts[0] === key || parts[2] === key) {
242
+ while (parts.length < 17) parts.push("")
243
+ parts[16] = "obsolete"
244
+ lines[i] = ` ${parts.join("|")}`
245
+ found = true
246
+ break
247
+ }
248
+ }
206
249
 
207
250
  writeMemory(lines.join("\n"))
208
251
 
209
- if (removed === 0) {
252
+ if (!found) {
210
253
  return {
211
254
  content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
212
255
  }
213
256
  }
214
257
 
215
258
  return {
216
- content: [{ type: "text" as const, text: `"${key}" deleted. ${count - removed} entries remaining.` }],
259
+ content: [{ type: "text" as const, text: `"${key}" marked as obsolete. Use memory_resolve(key: "${key}") to restore.` }],
217
260
  }
218
261
  }
219
262
  )
@@ -232,7 +275,7 @@ server.registerTool(
232
275
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
233
276
  const entries = lines.map((l) => {
234
277
  const parts = l.trim().split("|")
235
- return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "" }
278
+ return { category: parts[1] || "unknown", ttl: parts[7] || "", quality: parts[10] || "", origin: parts.length > 15 ? parts[15] || "" : "", status: parts.length > 16 ? parts[16] || "" : "" }
236
279
  })
237
280
 
238
281
  const byCategory: Record<string, number> = {}
@@ -248,6 +291,13 @@ server.registerTool(
248
291
  : "N/A"
249
292
 
250
293
  const summaryLines = data.split("\n").filter((l) => l.includes(":") && !l.startsWith(" ") && !l.startsWith("version") && !l.startsWith("entries") && !/^\[\d+\|]/.test(l))
294
+ const byOrigin: Record<string, number> = {}
295
+ const byStatus: Record<string, number> = {}
296
+ for (const e of entries) {
297
+ byOrigin[e.origin || "agent"] = (byOrigin[e.origin || "agent"] || 0) + 1
298
+ byStatus[e.status || "active"] = (byStatus[e.status || "active"] || 0) + 1
299
+ }
300
+
251
301
  const stats = [
252
302
  `Total entries: ${entries.length}`,
253
303
  `File summaries: ${summaryLines.length}`,
@@ -255,6 +305,12 @@ server.registerTool(
255
305
  "By category:",
256
306
  ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
257
307
  "",
308
+ "By origin:",
309
+ ...Object.entries(byOrigin).map(([k, v]) => ` ${k}: ${v}`),
310
+ "",
311
+ "By status:",
312
+ ...Object.entries(byStatus).map(([k, v]) => ` ${k}: ${v}`),
313
+ "",
258
314
  `TTL: ${withTtl} with expiration, ${expired} expired`,
259
315
  `Average quality: ${avgQuality} (${withQuality} with score)`,
260
316
  "",
@@ -264,7 +320,9 @@ server.registerTool(
264
320
  const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
265
321
  const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
266
322
  const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : ""
267
- return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}`
323
+ const originInfo = parts.length > 15 && parts[15] && parts[15] !== "agent" ? ` | origin: ${parts[15]}` : ""
324
+ const statusInfo = parts.length > 16 && parts[16] && parts[16] !== "active" ? ` | status: ${parts[16]}` : ""
325
+ return ` [${parts[1]}] ${parts[2]} (${parts[0]})${ttlInfo}${qualityInfo}${accessInfo}${originInfo}${statusInfo}`
268
326
  }),
269
327
  "",
270
328
  `Most accessed:`,
@@ -280,6 +338,44 @@ server.registerTool(
280
338
  .map((e) => ` ${e.key}: ${e.accessed}x (Q: ${e.quality})`),
281
339
  ]
282
340
 
341
+ // Cold memories: high quality but rarely accessed
342
+ const coldEntries = lines
343
+ .filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
344
+ .map((l) => {
345
+ const p = l.trim().split("|")
346
+ return {
347
+ key: p[2],
348
+ cat: p[1],
349
+ quality: parseFloat(p[10]) || 0,
350
+ accessed: p.length > 8 ? parseInt(p[8]) || 0 : 0,
351
+ lastAccessed: p.length > 12 ? p[12] || "" : "",
352
+ date: p[6] || "",
353
+ }
354
+ })
355
+ .filter((e) => {
356
+ if (e.accessed >= 2) return false
357
+ if (e.quality < 0.7) return false
358
+ const lastDate = e.lastAccessed || e.date
359
+ if (!lastDate) return false
360
+ const daysSinceLastAccess = (Date.now() - new Date(lastDate).getTime()) / 86400000
361
+ return daysSinceLastAccess > 30
362
+ })
363
+ .sort((a, b) => b.quality - a.quality)
364
+
365
+ if (coldEntries.length > 0) {
366
+ stats.push(
367
+ "",
368
+ `Cold memories (${coldEntries.length}):`,
369
+ ...coldEntries.slice(0, 5).map((e) => {
370
+ const lastDate = e.lastAccessed || e.date
371
+ const daysSince = Math.round((Date.now() - new Date(lastDate).getTime()) / 86400000)
372
+ return ` ${e.key} (Q: ${e.quality.toFixed(2)}) — ${daysSince}d since last access`
373
+ }),
374
+ "",
375
+ "💡 Run memory_archive() to archive cold entries."
376
+ )
377
+ }
378
+
283
379
  return { content: [{ type: "text" as const, text: stats.join("\n") }] }
284
380
  }
285
381
  )
@@ -382,12 +478,14 @@ server.registerTool(
382
478
  intent: z.string().describe("Describe what you need to know (e.g. 'database schema for backend')"),
383
479
  limit: z.number().optional().default(8).describe("Maximum entries to return"),
384
480
  category: z.string().optional().default("").describe("Filter by category (empty = all)"),
481
+ bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
385
482
  },
386
483
  },
387
- async ({ intent, limit, category }) => {
484
+ async ({ intent, limit, category, bias }) => {
388
485
  const data = readMemory()
389
486
  const mtimes = fileMtimes()
390
- const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes })
487
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
488
+ const result = generateSmartRecall(data, intent, { limit, category, fileMtimes: mtimes, sessionFiles })
391
489
  return { content: [{ type: "text" as const, text: result }] }
392
490
  }
393
491
  )
@@ -1450,10 +1548,31 @@ server.registerTool(
1450
1548
  }
1451
1549
 
1452
1550
  if (dryRun) {
1551
+ // Detailed preview: show what each merge produces
1552
+ const previewLines: string[] = [
1553
+ `🔍 Dry run — ${mergePairs.length} merge candidate(s) found:`,
1554
+ "",
1555
+ ]
1556
+ for (const pair of mergePairs) {
1557
+ const a = parsed[pair.a], b = parsed[pair.b]
1558
+ const mergedTags = [...new Set([...a.tags.split(";"), ...b.tags.split(";")])].filter(Boolean).join(";")
1559
+ const longer = a.content.length >= b.content.length ? a : b
1560
+ const shorter = a.content.length < b.content.length ? a : b
1561
+ previewLines.push(` ── Pair: [${a.cat}] ${a.key} ↔ [${b.cat}] ${b.key}`)
1562
+ previewLines.push(` Similarity: ${(pair.similarity * 100).toFixed(0)}%`)
1563
+ previewLines.push(` A tags: ${a.tags || "(none)"}`)
1564
+ previewLines.push(` B tags: ${b.tags || "(none)"}`)
1565
+ previewLines.push(` → Merged tags: ${mergedTags || "(none)"}`)
1566
+ previewLines.push(` → Content winner: "${longer.key}" (${longer.content.length} chars vs ${shorter.content.length})`)
1567
+ previewLines.push(` → Result content: ${longer.content.slice(0, 120)}${longer.content.length > 120 ? "…" : ""}`)
1568
+ previewLines.push("")
1569
+ }
1570
+ previewLines.push(`Would merge ${merged.size} entries into ${entries.length - merged.size} entries.`)
1571
+ previewLines.push("Run with dryRun: false to apply.")
1453
1572
  return {
1454
1573
  content: [{
1455
1574
  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.`
1575
+ text: previewLines.join("\n"),
1457
1576
  }],
1458
1577
  }
1459
1578
  }
@@ -1551,18 +1670,107 @@ server.registerTool(
1551
1670
  }
1552
1671
  )
1553
1672
 
1673
+ // ── memory_checkpoint ─────────────────────────────────────────────────────────
1674
+
1675
+ server.registerTool(
1676
+ "memory_checkpoint",
1677
+ {
1678
+ title: "Session Checkpoint",
1679
+ 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.",
1680
+ inputSchema: {
1681
+ note: z.string().optional().default("").describe("Optional summary of what was accomplished in this session."),
1682
+ },
1683
+ },
1684
+ async ({ note }) => {
1685
+ const data = readMemory()
1686
+ const lines = data.split("\n")
1687
+
1688
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
1689
+ if (headerIdx === -1) {
1690
+ lines.push(`[0|]`)
1691
+ headerIdx = lines.length - 1
1692
+ }
1693
+
1694
+ const sessionId = resolveSessionId({})
1695
+ const shortId = sessionId.replace(/^proc-/, "").slice(0, 8)
1696
+ const key = `checkpoint-${shortId}`
1697
+ const now = new Date()
1698
+ const date = now.toISOString().split("T")[0]
1699
+ const ttl7d = new Date(now.getTime() + 7 * 86400000).toISOString().split("T")[0]
1700
+
1701
+ // Gather session context: branch, files touched, agent
1702
+ const sessions = await import("../lib/sessions")
1703
+ const allSessions = sessions.listSessions()
1704
+ const mySession = allSessions.find((s) => s.id === sessionId)
1705
+ const branch = mySession?.branch || currentBranch()
1706
+ const files = mySession ? Object.keys(mySession.files) : []
1707
+ const fileList = files.length > 0 ? `\nFiles touched: ${files.slice(0, 10).join(", ")}${files.length > 10 ? ` (+${files.length - 10} more)` : ""}` : ""
1708
+
1709
+ const content = `Session checkpoint (${date})${note ? `\nNote: ${note}` : ""}\nBranch: ${branch}${fileList}`
1710
+
1711
+ // Check for existing checkpoint with same key
1712
+ let existingIdx = -1
1713
+ let existingId = ""
1714
+ for (let i = headerIdx + 1; i < lines.length; i++) {
1715
+ const line = lines[i]
1716
+ if (!line.startsWith(" ") || !line.includes("|")) continue
1717
+ if (line.startsWith(" summaries:")) break
1718
+ const parts = line.trim().split("|")
1719
+ if (parts[2] === key) {
1720
+ existingIdx = i
1721
+ existingId = parts[0]
1722
+ break
1723
+ }
1724
+ }
1725
+
1726
+ if (existingIdx !== -1) {
1727
+ // Update existing checkpoint
1728
+ const parts = lines[existingIdx].trim().split("|")
1729
+ parts[3] = content
1730
+ parts[6] = date
1731
+ parts[7] = ttl7d
1732
+ while (parts.length < 14) parts.push("")
1733
+ parts[13] = "0"
1734
+ lines[existingIdx] = ` ${parts.join("|")}`
1735
+ writeMemory(lines.join("\n"))
1736
+ return {
1737
+ content: [{ type: "text" as const, text: `📝 Checkpoint updated: ${key}\n⏰ TTL: ${ttl7d} (7d)\n${note ? `\n${note}` : ""}` }],
1738
+ }
1739
+ }
1740
+
1741
+ // Create new checkpoint entry
1742
+ const newId = `cp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
1743
+ const quality = qualityScore("checkpoint", "", content, date)
1744
+ const newEntry = `${newId}|knowledge|${key}|${content}||checkpoint|${date}|${ttl7d}|0||${quality.toFixed(2)}|1|${now.toISOString()}|0`
1745
+
1746
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
1747
+ const count = match ? parseInt(match[1]) : 0
1748
+ lines.splice(headerIdx + 1, 0, ` ${newEntry}`)
1749
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
1750
+ writeMemory(lines.join("\n"))
1751
+
1752
+ return {
1753
+ content: [{
1754
+ type: "text" as const,
1755
+ text: `📝 Checkpoint saved: ${key} (${newId})\n⏰ TTL: ${ttl7d} (7d)${note ? `\n\n${note}` : ""}`,
1756
+ }],
1757
+ }
1758
+ }
1759
+ )
1760
+
1554
1761
  // ── memory_pin ───────────────────────────────────────────────────────────────
1555
1762
 
1556
1763
  server.registerTool(
1557
1764
  "memory_pin",
1558
1765
  {
1559
1766
  title: "Pin Entry",
1560
- description: "Pin a memory entry so it always appears first in recalls. Useful for critical decisions, project rules, or frequently-needed context.",
1767
+ 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.",
1561
1768
  inputSchema: {
1562
1769
  key: z.string().describe("Key or id of the entry to pin"),
1770
+ priority: z.number().optional().default(1).describe("Priority level 1-5 (5 = highest). Default: 1."),
1563
1771
  },
1564
1772
  },
1565
- async ({ key }) => {
1773
+ async ({ key, priority }) => {
1566
1774
  const data = readMemory()
1567
1775
  const lines = data.split("\n")
1568
1776
  const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
@@ -1571,6 +1779,8 @@ server.registerTool(
1571
1779
  return { content: [{ type: "text" as const, text: "No entries in memory" }] }
1572
1780
  }
1573
1781
 
1782
+ const clampedPriority = Math.max(1, Math.min(5, Math.round(priority)))
1783
+
1574
1784
  let found = false
1575
1785
  for (let i = headerIdx + 1; i < lines.length; i++) {
1576
1786
  const line = lines[i]
@@ -1578,9 +1788,8 @@ server.registerTool(
1578
1788
  if (line.startsWith(" summaries:")) break
1579
1789
  const parts = line.trim().split("|")
1580
1790
  if (parts[0] === key || parts[2] === key) {
1581
- // Set pinned field at position 13
1582
1791
  while (parts.length < 14) parts.push("")
1583
- parts[13] = "1"
1792
+ parts[13] = String(clampedPriority)
1584
1793
  lines[i] = ` ${parts.join("|")}`
1585
1794
  found = true
1586
1795
  break
@@ -1592,7 +1801,7 @@ server.registerTool(
1592
1801
  }
1593
1802
 
1594
1803
  writeMemory(lines.join("\n"))
1595
- return { content: [{ type: "text" as const, text: `📌 Pinned "${key}". It will now appear first in recalls.` }] }
1804
+ return { content: [{ type: "text" as const, text: `📌${clampedPriority > 1 ? clampedPriority : ""} Pinned "${key}" at priority ${clampedPriority}. It will now appear first in recalls.` }] }
1596
1805
  }
1597
1806
  )
1598
1807
 
@@ -1637,7 +1846,7 @@ server.registerTool(
1637
1846
  }
1638
1847
 
1639
1848
  writeMemory(lines.join("\n"))
1640
- return { content: [{ type: "text" as const, text: `📌 Unpinned "${key}". It will now use normal ranking.` }] }
1849
+ return { content: [{ type: "text" as const, text: `Unpinned "${key}". It will now use normal ranking.` }] }
1641
1850
  }
1642
1851
  )
1643
1852
 
@@ -1658,12 +1867,17 @@ server.registerTool(
1658
1867
  mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
1659
1868
  hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
1660
1869
  compact: z.boolean().optional().default(false).describe("Token-efficient output"),
1870
+ budget: z.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'."),
1871
+ bias: z.enum(["none", "session"]).optional().default("none").describe("'session': boost entries whose file matches current session files. 'none': no bias (default)."),
1872
+ path_scope: z.string().optional().default("").describe("Glob pattern to filter entries by path scope (e.g. 'src/**.ts')."),
1661
1873
  },
1662
1874
  },
1663
- async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact }) => {
1875
+ async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
1664
1876
  const data = readMemory()
1665
1877
 
1666
1878
  const resolvedFrom = from_date ? parseRelativeDate(from_date) : ""
1879
+ const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
1880
+ const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
1667
1881
  const detail = graphRecallDetailed(data, query, {
1668
1882
  category: category || undefined,
1669
1883
  tags: tags || undefined,
@@ -1671,6 +1885,8 @@ server.registerTool(
1671
1885
  to_date: to_date || undefined,
1672
1886
  hops,
1673
1887
  limit,
1888
+ sessionFiles,
1889
+ path_scope: path_scope || undefined,
1674
1890
  })
1675
1891
 
1676
1892
  if (detail.entries.length === 0) {
@@ -1679,11 +1895,12 @@ server.registerTool(
1679
1895
 
1680
1896
  bumpAccessed(detail.entries.map((e) => e.id))
1681
1897
 
1682
- if (compact) {
1898
+ if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
1683
1899
  const formatted = renderCompact(detail.entries, {
1684
1900
  adjacency: detail.adjacency,
1685
1901
  seeds: detail.seeds,
1686
1902
  snippetLen: 90,
1903
+ budget: resolvedBudget,
1687
1904
  })
1688
1905
  return { content: [{ type: "text" as const, text: `🔍 Search: "${query}"\n\n${formatted}` }] }
1689
1906
  }
@@ -1691,8 +1908,11 @@ server.registerTool(
1691
1908
  const formatted = detail.entries
1692
1909
  .map((r) => {
1693
1910
  const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
1694
- const pin = r.pinned ? " 📌" : ""
1695
- return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
1911
+ const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
1912
+ const originInfo = r.origin !== "agent" ? ` | origin: ${r.origin}` : ""
1913
+ const scopeInfo = r.path_scope ? ` | scope: ${r.path_scope}` : ""
1914
+ const statusInfo = r.status !== "active" ? ` | status: ${r.status}` : ""
1915
+ return `[${r.category}] ${r.key}${pin} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}${originInfo}${scopeInfo}${statusInfo}`
1696
1916
  })
1697
1917
  .join("\n\n")
1698
1918
 
@@ -1784,6 +2004,98 @@ server.registerTool(
1784
2004
  }
1785
2005
  )
1786
2006
 
2007
+ // ── memory_resolve ───────────────────────────────────────────────────────────
2008
+
2009
+ server.registerTool(
2010
+ "memory_resolve",
2011
+ {
2012
+ title: "Resolve Entry",
2013
+ description: "Restore an obsolete entry back to active status, or mark an entry as resolved. Reverses soft-delete.",
2014
+ inputSchema: {
2015
+ key: z.string().describe("Key or id of the entry to resolve/restore"),
2016
+ },
2017
+ },
2018
+ async ({ key }) => {
2019
+ const data = readMemory()
2020
+ const lines = data.split("\n")
2021
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2022
+
2023
+ if (headerIdx === -1) {
2024
+ return { content: [{ type: "text" as const, text: "No entries in memory" }] }
2025
+ }
2026
+
2027
+ let found = false
2028
+ let wasObsolete = false
2029
+ for (let i = headerIdx + 1; i < lines.length; i++) {
2030
+ const line = lines[i]
2031
+ if (!line.startsWith(" ") || !line.includes("|")) continue
2032
+ if (line.startsWith(" summaries:")) break
2033
+ const parts = line.trim().split("|")
2034
+ if (parts[0] === key || parts[2] === key) {
2035
+ while (parts.length < 17) parts.push("")
2036
+ wasObsolete = parts[16] === "obsolete"
2037
+ parts[16] = "active"
2038
+ lines[i] = ` ${parts.join("|")}`
2039
+ found = true
2040
+ break
2041
+ }
2042
+ }
2043
+
2044
+ if (!found) {
2045
+ return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
2046
+ }
2047
+
2048
+ writeMemory(lines.join("\n"))
2049
+
2050
+ const msg = wasObsolete ? `"${key}" restored to active status.` : `"${key}" marked as resolved.`
2051
+ return { content: [{ type: "text" as const, text: `✅ ${msg}` }] }
2052
+ }
2053
+ )
2054
+
2055
+ // ── memory_suppress ──────────────────────────────────────────────────────────
2056
+
2057
+ server.registerTool(
2058
+ "memory_suppress",
2059
+ {
2060
+ title: "Suppress Entry",
2061
+ description: "Suppress a memory entry so it's hidden from normal recalls. Sets status to 'obsolete'. Use memory_resolve to restore.",
2062
+ inputSchema: {
2063
+ key: z.string().describe("Key or id of the entry to suppress"),
2064
+ },
2065
+ },
2066
+ async ({ key }) => {
2067
+ const data = readMemory()
2068
+ const lines = data.split("\n")
2069
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
2070
+
2071
+ if (headerIdx === -1) {
2072
+ return { content: [{ type: "text" as const, text: "No entries in memory" }] }
2073
+ }
2074
+
2075
+ let found = false
2076
+ for (let i = headerIdx + 1; i < lines.length; i++) {
2077
+ const line = lines[i]
2078
+ if (!line.startsWith(" ") || !line.includes("|")) continue
2079
+ if (line.startsWith(" summaries:")) break
2080
+ const parts = line.trim().split("|")
2081
+ if (parts[0] === key || parts[2] === key) {
2082
+ while (parts.length < 17) parts.push("")
2083
+ parts[16] = "obsolete"
2084
+ lines[i] = ` ${parts.join("|")}`
2085
+ found = true
2086
+ break
2087
+ }
2088
+ }
2089
+
2090
+ if (!found) {
2091
+ return { content: [{ type: "text" as const, text: `"${key}" not found in memory.` }] }
2092
+ }
2093
+
2094
+ writeMemory(lines.join("\n"))
2095
+ return { content: [{ type: "text" as const, text: `"${key}" suppressed. Use memory_resolve(key: "${key}") to restore.` }] }
2096
+ }
2097
+ )
2098
+
1787
2099
  // ── memory_visualize (MCP Apps) ──────────────────────────────────────────────
1788
2100
 
1789
2101
  registerAppTool(