toon-memory 3.5.0 → 3.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -11
- package/dist/cli/setup.js +42 -15
- package/mcp/server.js +264 -43
- package/package.json +3 -2
- package/src/cli/opencode-plugin.ts +38 -14
- package/src/lib/context.ts +43 -2
- package/src/lib/graph.ts +69 -2
- package/src/lib/quality.ts +21 -2
- package/src/mcp/tools.ts +182 -27
package/src/lib/context.ts
CHANGED
|
@@ -45,9 +45,18 @@ function formatOverview(data: string): string {
|
|
|
45
45
|
const cats = Object.entries(byCategory)
|
|
46
46
|
.map(([k, v]) => `${k}:${v}`)
|
|
47
47
|
.join(" ")
|
|
48
|
+
|
|
49
|
+
const originBreak = (): string => {
|
|
50
|
+
const o: Record<string, number> = {}
|
|
51
|
+
for (const e of entries) { o[e.origin] = (o[e.origin] || 0) + 1 }
|
|
52
|
+
return Object.entries(o).map(([k, v]) => `${k}:${v}`).join(" ")
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const obsoleteCount = entries.filter((e) => e.status === "obsolete").length
|
|
48
56
|
const ttlNote = expired > 0 ? ` | ${expired} expired` : ""
|
|
57
|
+
const obsoleteNote = obsoleteCount > 0 ? ` | ${obsoleteCount} obsolete` : ""
|
|
49
58
|
|
|
50
|
-
return `## Memory (${entries.length} entries)${ttlNote}\n${cats}`
|
|
59
|
+
return `## Memory (${entries.length} entries)${ttlNote}${obsoleteNote}\n${cats}\nOrigin: ${originBreak()}`
|
|
51
60
|
}
|
|
52
61
|
|
|
53
62
|
/**
|
|
@@ -569,7 +578,39 @@ export function generateContextHealth(data: string, root: string): { report: Hea
|
|
|
569
578
|
info.push(`${stale.length} stale sessions (will be pruned automatically)`)
|
|
570
579
|
}
|
|
571
580
|
|
|
572
|
-
// 8.
|
|
581
|
+
// 8. Missing evidence: entries with path_scope but no file
|
|
582
|
+
const missingEvidence = entries.filter((e) => e.path_scope && !e.file)
|
|
583
|
+
if (missingEvidence.length > 0) {
|
|
584
|
+
warnings.push(`${missingEvidence.length} entries with path_scope but no file (missing evidence): ${missingEvidence.slice(0, 3).map((e) => e.key).join(", ")}`)
|
|
585
|
+
score -= 3
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// 9. Stale claims: entries with overlapping content in the same category
|
|
589
|
+
// that may contain competing/outdated information
|
|
590
|
+
const staleClaims: string[] = []
|
|
591
|
+
for (let i = 0; i < entries.length; i++) {
|
|
592
|
+
for (let j = i + 1; j < entries.length; j++) {
|
|
593
|
+
const a = entries[i], b = entries[j]
|
|
594
|
+
if (a.category !== b.category) continue
|
|
595
|
+
if (a.key === b.key) continue
|
|
596
|
+
const aWords = new Set(normalize(a.content).split(/\s+/).filter((w) => w.length > 3))
|
|
597
|
+
const bWords = new Set(normalize(b.content).split(/\s+/).filter((w) => w.length > 3))
|
|
598
|
+
const intersection = new Set([...aWords].filter((w) => bWords.has(w)))
|
|
599
|
+
const union = new Set([...aWords, ...bWords])
|
|
600
|
+
const similarity = union.size > 0 ? intersection.size / union.size : 0
|
|
601
|
+
if (similarity > 0.4) {
|
|
602
|
+
staleClaims.push(`${a.key} ≈ ${b.key} (${(similarity * 100).toFixed(0)}% same category)`)
|
|
603
|
+
if (staleClaims.length >= 5) break
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
if (staleClaims.length >= 5) break
|
|
607
|
+
}
|
|
608
|
+
if (staleClaims.length > 0) {
|
|
609
|
+
warnings.push(`${staleClaims.length} potentially overlapping claims: ${staleClaims.slice(0, 3).join("; ")}`)
|
|
610
|
+
score -= 3
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// 10. Entry count
|
|
573
614
|
if (entries.length > 80) {
|
|
574
615
|
warnings.push(`${entries.length} entries (near limit of 100)`)
|
|
575
616
|
score -= 3
|
package/src/lib/graph.ts
CHANGED
|
@@ -34,6 +34,12 @@ export interface GraphEntry {
|
|
|
34
34
|
lastAccessed: string
|
|
35
35
|
/** Priority level 0-5. 0 = normal, 1-5 = pinned with priority (5 = highest). */
|
|
36
36
|
priority: number
|
|
37
|
+
/** Glob pattern scoping this entry to a file path (e.g. "src/**\/*.ts"). Empty = global. */
|
|
38
|
+
path_scope: string
|
|
39
|
+
/** Who created this entry. */
|
|
40
|
+
origin: "human" | "agent" | "inferred"
|
|
41
|
+
/** Lifecycle status. Obsolete entries are filtered from normal recalls. */
|
|
42
|
+
status: "active" | "obsolete" | "resolved"
|
|
37
43
|
}
|
|
38
44
|
|
|
39
45
|
export interface MemoryGraph {
|
|
@@ -81,6 +87,9 @@ export function parseEntries(data: string): GraphEntry[] {
|
|
|
81
87
|
.filter(Boolean),
|
|
82
88
|
lastAccessed: parts.length > 12 ? parts[12] || "" : "",
|
|
83
89
|
priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
|
|
90
|
+
path_scope: parts.length > 14 ? parts[14] || "" : "",
|
|
91
|
+
origin: parts.length > 15 && parts[15] ? parts[15] as "human" | "agent" | "inferred" : "agent",
|
|
92
|
+
status: parts.length > 16 && parts[16] ? parts[16] as "active" | "obsolete" | "resolved" : "active",
|
|
84
93
|
})
|
|
85
94
|
}
|
|
86
95
|
return out
|
|
@@ -145,6 +154,8 @@ export interface GraphRecallOpts {
|
|
|
145
154
|
limit?: number
|
|
146
155
|
/** Session bias: boost entries whose file matches current session files. */
|
|
147
156
|
sessionFiles?: string[]
|
|
157
|
+
/** Path scope glob filter: only return entries whose path_scope matches. */
|
|
158
|
+
path_scope?: string
|
|
148
159
|
}
|
|
149
160
|
|
|
150
161
|
/**
|
|
@@ -157,7 +168,7 @@ export function bm25Scores(entries: GraphEntry[], query: string): Map<string, nu
|
|
|
157
168
|
if (N === 0) return scores
|
|
158
169
|
|
|
159
170
|
const docs = entries.map((e) =>
|
|
160
|
-
tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`)
|
|
171
|
+
tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")} ${e.path_scope}`)
|
|
161
172
|
)
|
|
162
173
|
const df = new Map<string, number>()
|
|
163
174
|
for (const d of docs) {
|
|
@@ -243,11 +254,13 @@ export function graphRecallDetailed(
|
|
|
243
254
|
|
|
244
255
|
const seedKeys = new Set<string>()
|
|
245
256
|
for (const e of entries) {
|
|
257
|
+
if (e.status === "obsolete") continue
|
|
246
258
|
if (category && e.category !== category) continue
|
|
247
259
|
if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue
|
|
248
260
|
if (from_date && e.date < from_date) continue
|
|
249
261
|
if (to_date && e.date > to_date) continue
|
|
250
262
|
if (e.ttl && isExpiredLocal(e.ttl)) continue
|
|
263
|
+
if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue
|
|
251
264
|
const text = normalize(
|
|
252
265
|
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
253
266
|
)
|
|
@@ -263,6 +276,7 @@ export function graphRecallDetailed(
|
|
|
263
276
|
if (seedKeys.size === 0) {
|
|
264
277
|
scored.push(
|
|
265
278
|
...[...entries]
|
|
279
|
+
.filter((e) => e.status !== "obsolete")
|
|
266
280
|
.sort((a, b) => {
|
|
267
281
|
if (a.priority !== b.priority) return b.priority - a.priority
|
|
268
282
|
return importance(b) - importance(a)
|
|
@@ -313,7 +327,7 @@ export function graphRecallDetailed(
|
|
|
313
327
|
selected = scored.map((x) => x.e)
|
|
314
328
|
|
|
315
329
|
// Inject pinned entries that aren't already in the result set, sorted by priority desc.
|
|
316
|
-
const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key))
|
|
330
|
+
const pinnedKeys = new Set(entries.filter((e) => e.priority > 0 && e.status !== "obsolete").map((e) => e.key))
|
|
317
331
|
const inResult = new Set(selected.map((e) => e.key))
|
|
318
332
|
const toInject = [...pinnedKeys]
|
|
319
333
|
.filter((k) => !inResult.has(k) && byKey.has(k))
|
|
@@ -357,6 +371,31 @@ export interface RenderCompactOpts {
|
|
|
357
371
|
seeds?: Set<string>
|
|
358
372
|
/** Max chars before a neighbor (non-seed) is truncated with an ellipsis. */
|
|
359
373
|
snippetLen?: number
|
|
374
|
+
/** Budget level: "tiny" (key+1 line), "normal" (compact, default), "deep" (all fields). */
|
|
375
|
+
budget?: "tiny" | "normal" | "deep"
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Simple glob match: supports `*` (any chars except `/`), `**` (any chars),
|
|
380
|
+
* and `?` (single char). Used by path_scope filtering.
|
|
381
|
+
*/
|
|
382
|
+
export function globMatch(pattern: string, target: string): boolean {
|
|
383
|
+
if (!pattern) return true
|
|
384
|
+
if (pattern.startsWith("/")) pattern = pattern.slice(1)
|
|
385
|
+
if (target.startsWith("/")) target = target.slice(1)
|
|
386
|
+
const reStr = "^" + pattern
|
|
387
|
+
.replace(/\*\*/g, "___DOUBLESTAR___")
|
|
388
|
+
.replace(/\*/g, "[^/]*")
|
|
389
|
+
.replace(/___DOUBLESTAR___/g, ".*")
|
|
390
|
+
.replace(/\?/g, ".")
|
|
391
|
+
.replace(/\./g, "\\.")
|
|
392
|
+
.replace(/\\\.\*/g, ".*")
|
|
393
|
+
+ "$"
|
|
394
|
+
try {
|
|
395
|
+
return new RegExp(reStr).test(target)
|
|
396
|
+
} catch {
|
|
397
|
+
return false
|
|
398
|
+
}
|
|
360
399
|
}
|
|
361
400
|
|
|
362
401
|
/**
|
|
@@ -366,6 +405,11 @@ export interface RenderCompactOpts {
|
|
|
366
405
|
* - graph edges render as `->2, ->3` (numeric) when `adjacency` is given
|
|
367
406
|
* - neighbors reached via graph (non-seeds) are truncated to `snippetLen`
|
|
368
407
|
*
|
|
408
|
+
* Budget levels:
|
|
409
|
+
* "tiny" — key + category + 1 line of content (~50 tokens). For proactive recall.
|
|
410
|
+
* "normal" — current compact format with tags, edges, truncated neighbors.
|
|
411
|
+
* "deep" — full content with all fields (id, date, file, links, quality).
|
|
412
|
+
*
|
|
369
413
|
* The stored `.toon` file is never mutated — this only shapes the output.
|
|
370
414
|
*/
|
|
371
415
|
export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {}): string {
|
|
@@ -373,10 +417,33 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
|
|
|
373
417
|
entries.forEach((e, i) => index.set(e.key, i + 1))
|
|
374
418
|
const snippetLen = opts.snippetLen ?? 90
|
|
375
419
|
|
|
420
|
+
const budget = opts.budget ?? "normal"
|
|
421
|
+
|
|
376
422
|
return entries
|
|
377
423
|
.map((e) => {
|
|
378
424
|
const n = index.get(e.key)!
|
|
379
425
|
const isSeed = opts.seeds ? opts.seeds.has(e.key) : true
|
|
426
|
+
|
|
427
|
+
if (budget === "tiny") {
|
|
428
|
+
const firstLine = e.content.split("\n")[0] || ""
|
|
429
|
+
const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "…" : firstLine
|
|
430
|
+
const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
|
|
431
|
+
return `[${n}] ${e.category}/${e.key}${pin}\n ${snippet}`
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
if (budget === "deep") {
|
|
435
|
+
const ttlInfo = e.ttl ? ` · ttl: ${e.ttl}` : ""
|
|
436
|
+
const accessInfo = e.accessed > 0 ? ` · accessed: ${e.accessed}x` : ""
|
|
437
|
+
const lastAccess = e.lastAccessed ? ` · lastAccess: ${e.lastAccessed}` : ""
|
|
438
|
+
const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
|
|
439
|
+
const links = e.links.length ? `\n links: ${e.links.join(", ")}` : ""
|
|
440
|
+
const originInfo = e.origin !== "agent" ? ` · origin: ${e.origin}` : ""
|
|
441
|
+
const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
|
|
442
|
+
const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
|
|
443
|
+
return `[${n}] ${e.category}/${e.key}${pin} (${e.id})\n ${e.content}\n File: ${e.file} | Tags: ${e.tags.join(";")} | Date: ${e.date}${ttlInfo}${accessInfo}${lastAccess}${originInfo}${scopeInfo}${statusInfo}${links}`
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// "normal" budget (default)
|
|
380
447
|
let body = e.content
|
|
381
448
|
if (!isSeed && e.content.length > snippetLen) {
|
|
382
449
|
body = e.content.slice(0, snippetLen).trimEnd() + "…"
|
package/src/lib/quality.ts
CHANGED
|
@@ -32,7 +32,8 @@ export function qualityScore(
|
|
|
32
32
|
content: string,
|
|
33
33
|
date: string,
|
|
34
34
|
accessed: number = 0,
|
|
35
|
-
lastAccessed: string = ""
|
|
35
|
+
lastAccessed: string = "",
|
|
36
|
+
origin: string = ""
|
|
36
37
|
): number {
|
|
37
38
|
let score = 0
|
|
38
39
|
if (tags) {
|
|
@@ -70,6 +71,10 @@ export function qualityScore(
|
|
|
70
71
|
else if (daysSinceAccess < 30) score += 0.03
|
|
71
72
|
}
|
|
72
73
|
|
|
74
|
+
// Origin weighting: human > agent > inferred
|
|
75
|
+
if (origin === "human") score += 0.1
|
|
76
|
+
else if (origin === "inferred") score -= 0.05
|
|
77
|
+
|
|
73
78
|
// Staleness decay: penalize entries that haven't been accessed recently
|
|
74
79
|
// and were created more than 30 days ago. Decay ramps up over time.
|
|
75
80
|
if (date) {
|
|
@@ -146,7 +151,21 @@ export function mergeEntries(existingLine: string, newLine: string): string {
|
|
|
146
151
|
|
|
147
152
|
const quality = qualityScore(mergedTags, mergedLinks, content, date, accessed, lastAccessed)
|
|
148
153
|
|
|
149
|
-
|
|
154
|
+
// Merge new fields: path_scope (field 14), origin (field 15), status (field 16)
|
|
155
|
+
const existingScope = ep.length > 14 ? ep[14] || "" : ""
|
|
156
|
+
const newScope = np.length > 14 ? np[14] || "" : ""
|
|
157
|
+
const path_scope = newScope || existingScope
|
|
158
|
+
|
|
159
|
+
const existingOrigin = ep.length > 15 ? ep[15] || "" : ""
|
|
160
|
+
const newOrigin = np.length > 15 ? np[15] || "" : ""
|
|
161
|
+
const originRank: Record<string, number> = { human: 3, agent: 2, inferred: 1 }
|
|
162
|
+
const origin = (originRank[newOrigin] || 0) >= (originRank[existingOrigin] || 0) ? newOrigin : existingOrigin
|
|
163
|
+
|
|
164
|
+
const existingStatus = ep.length > 16 ? ep[16] || "" : ""
|
|
165
|
+
const newStatus = np.length > 16 ? np[16] || "" : ""
|
|
166
|
+
const status = newStatus === "active" || existingStatus === "active" ? "active" : newStatus || existingStatus || "active"
|
|
167
|
+
|
|
168
|
+
return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}|${path_scope}|${origin}|${status}`
|
|
150
169
|
}
|
|
151
170
|
|
|
152
171
|
/**
|
package/src/mcp/tools.ts
CHANGED
|
@@ -21,7 +21,7 @@ import { normalize, isExpiredLocal, tokenize, importance } from "../lib/utils"
|
|
|
21
21
|
import { expandSynonyms } from "../lib/synonyms"
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
|
-
* Register all
|
|
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,25 +144,29 @@ 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'."),
|
|
145
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')."),
|
|
146
150
|
},
|
|
147
151
|
},
|
|
148
|
-
async ({ query, category, from_date, to_date, mode, hops, compact, bias }) => {
|
|
152
|
+
async ({ query, category, from_date, to_date, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
|
|
149
153
|
const data = readMemory()
|
|
150
154
|
|
|
151
155
|
// Delegate to graphRecallDetailed for both flat and graph modes
|
|
152
156
|
// This avoids duplicating BM25 + ranking logic
|
|
153
157
|
const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
|
|
154
|
-
const
|
|
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 })
|
|
155
160
|
if (detail.entries.length === 0) {
|
|
156
161
|
return { content: [{ type: "text" as const, text: `No results found for "${query}"` }] }
|
|
157
162
|
}
|
|
158
163
|
bumpAccessed(detail.entries.map((e) => e.id))
|
|
159
|
-
if (
|
|
164
|
+
if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
|
|
160
165
|
const formatted = renderCompact(detail.entries, {
|
|
161
166
|
adjacency: detail.adjacency,
|
|
162
167
|
seeds: detail.seeds,
|
|
163
168
|
snippetLen: 90,
|
|
169
|
+
budget: resolvedBudget,
|
|
164
170
|
})
|
|
165
171
|
return { content: [{ type: "text" as const, text: formatted }] }
|
|
166
172
|
}
|
|
@@ -168,7 +174,10 @@ server.registerTool(
|
|
|
168
174
|
.map((r) => {
|
|
169
175
|
const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
|
|
170
176
|
const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
|
|
171
|
-
|
|
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}`
|
|
172
181
|
})
|
|
173
182
|
.join("\n\n")
|
|
174
183
|
return { content: [{ type: "text" as const, text: formatted }] }
|
|
@@ -184,9 +193,10 @@ server.registerTool(
|
|
|
184
193
|
description: "Delete a memory entry by its key or id.",
|
|
185
194
|
inputSchema: {
|
|
186
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."),
|
|
187
197
|
},
|
|
188
198
|
},
|
|
189
|
-
async ({ key }) => {
|
|
199
|
+
async ({ key, hard }) => {
|
|
190
200
|
const data = readMemory()
|
|
191
201
|
const lines = data.split("\n")
|
|
192
202
|
const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
|
|
@@ -195,28 +205,58 @@ server.registerTool(
|
|
|
195
205
|
return { content: [{ type: "text" as const, text: "No entries in memory" }] }
|
|
196
206
|
}
|
|
197
207
|
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
|
|
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
|
+
})
|
|
203
214
|
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
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
|
+
}
|
|
209
249
|
|
|
210
250
|
writeMemory(lines.join("\n"))
|
|
211
251
|
|
|
212
|
-
if (
|
|
252
|
+
if (!found) {
|
|
213
253
|
return {
|
|
214
254
|
content: [{ type: "text" as const, text: `"${key}" not found in memory.` }],
|
|
215
255
|
}
|
|
216
256
|
}
|
|
217
257
|
|
|
218
258
|
return {
|
|
219
|
-
content: [{ type: "text" as const, text: `"${key}"
|
|
259
|
+
content: [{ type: "text" as const, text: `"${key}" marked as obsolete. Use memory_resolve(key: "${key}") to restore.` }],
|
|
220
260
|
}
|
|
221
261
|
}
|
|
222
262
|
)
|
|
@@ -235,7 +275,7 @@ server.registerTool(
|
|
|
235
275
|
const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
|
|
236
276
|
const entries = lines.map((l) => {
|
|
237
277
|
const parts = l.trim().split("|")
|
|
238
|
-
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] || "" : "" }
|
|
239
279
|
})
|
|
240
280
|
|
|
241
281
|
const byCategory: Record<string, number> = {}
|
|
@@ -251,6 +291,13 @@ server.registerTool(
|
|
|
251
291
|
: "N/A"
|
|
252
292
|
|
|
253
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
|
+
|
|
254
301
|
const stats = [
|
|
255
302
|
`Total entries: ${entries.length}`,
|
|
256
303
|
`File summaries: ${summaryLines.length}`,
|
|
@@ -258,6 +305,12 @@ server.registerTool(
|
|
|
258
305
|
"By category:",
|
|
259
306
|
...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
|
|
260
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
|
+
"",
|
|
261
314
|
`TTL: ${withTtl} with expiration, ${expired} expired`,
|
|
262
315
|
`Average quality: ${avgQuality} (${withQuality} with score)`,
|
|
263
316
|
"",
|
|
@@ -267,7 +320,9 @@ server.registerTool(
|
|
|
267
320
|
const ttlInfo = parts[7] ? ` | TTL: ${parts[7]}` : ""
|
|
268
321
|
const qualityInfo = parts[10] ? ` | Q: ${parts[10]}` : ""
|
|
269
322
|
const accessInfo = parts[8] && parseInt(parts[8]) > 0 ? ` | accessed: ${parts[8]}x` : ""
|
|
270
|
-
|
|
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}`
|
|
271
326
|
}),
|
|
272
327
|
"",
|
|
273
328
|
`Most accessed:`,
|
|
@@ -1812,14 +1867,17 @@ server.registerTool(
|
|
|
1812
1867
|
mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = keyword search (default). 'graph' = graph-based recall."),
|
|
1813
1868
|
hops: z.number().optional().default(1).describe("Graph depth in 'graph' mode (1 or 2). Default 1."),
|
|
1814
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'."),
|
|
1815
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')."),
|
|
1816
1873
|
},
|
|
1817
1874
|
},
|
|
1818
|
-
async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias }) => {
|
|
1875
|
+
async ({ query, category, tags, from_date, to_date, limit, mode, hops, compact, bias, budget: budgetParam, path_scope }) => {
|
|
1819
1876
|
const data = readMemory()
|
|
1820
1877
|
|
|
1821
1878
|
const resolvedFrom = from_date ? parseRelativeDate(from_date) : ""
|
|
1822
1879
|
const sessionFiles = bias === "session" ? getCurrentSessionFiles() : undefined
|
|
1880
|
+
const resolvedBudget = budgetParam || (compact ? "normal" : "deep")
|
|
1823
1881
|
const detail = graphRecallDetailed(data, query, {
|
|
1824
1882
|
category: category || undefined,
|
|
1825
1883
|
tags: tags || undefined,
|
|
@@ -1828,6 +1886,7 @@ server.registerTool(
|
|
|
1828
1886
|
hops,
|
|
1829
1887
|
limit,
|
|
1830
1888
|
sessionFiles,
|
|
1889
|
+
path_scope: path_scope || undefined,
|
|
1831
1890
|
})
|
|
1832
1891
|
|
|
1833
1892
|
if (detail.entries.length === 0) {
|
|
@@ -1836,11 +1895,12 @@ server.registerTool(
|
|
|
1836
1895
|
|
|
1837
1896
|
bumpAccessed(detail.entries.map((e) => e.id))
|
|
1838
1897
|
|
|
1839
|
-
if (
|
|
1898
|
+
if (resolvedBudget === "tiny" || resolvedBudget === "normal") {
|
|
1840
1899
|
const formatted = renderCompact(detail.entries, {
|
|
1841
1900
|
adjacency: detail.adjacency,
|
|
1842
1901
|
seeds: detail.seeds,
|
|
1843
1902
|
snippetLen: 90,
|
|
1903
|
+
budget: resolvedBudget,
|
|
1844
1904
|
})
|
|
1845
1905
|
return { content: [{ type: "text" as const, text: `🔍 Search: "${query}"\n\n${formatted}` }] }
|
|
1846
1906
|
}
|
|
@@ -1849,7 +1909,10 @@ server.registerTool(
|
|
|
1849
1909
|
.map((r) => {
|
|
1850
1910
|
const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
|
|
1851
1911
|
const pin = r.priority > 0 ? (r.priority > 1 ? ` 📌${r.priority}` : " 📌") : ""
|
|
1852
|
-
|
|
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}`
|
|
1853
1916
|
})
|
|
1854
1917
|
.join("\n\n")
|
|
1855
1918
|
|
|
@@ -1941,6 +2004,98 @@ server.registerTool(
|
|
|
1941
2004
|
}
|
|
1942
2005
|
)
|
|
1943
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
|
+
|
|
1944
2099
|
// ── memory_visualize (MCP Apps) ──────────────────────────────────────────────
|
|
1945
2100
|
|
|
1946
2101
|
registerAppTool(
|