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/README.de.md +9 -4
- package/README.es.md +9 -4
- package/README.fr.md +9 -4
- package/README.ja.md +9 -4
- package/README.ko.md +9 -4
- package/README.md +24 -15
- package/README.pt-br.md +9 -4
- package/README.zh.md +9 -4
- package/dist/cli/setup.js +42 -15
- package/mcp/server.js +459 -81
- package/package.json +3 -2
- package/skills/toon-memory.md +20 -0
- package/src/cli/opencode-plugin.ts +38 -14
- package/src/lib/context.ts +43 -2
- package/src/lib/graph.ts +92 -16
- package/src/lib/quality.ts +50 -16
- package/src/lib/sessions.ts +8 -0
- package/src/mcp/tools.ts +350 -38
package/package.json
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
3
|
+
"mcpName": "io.github.LuiggiVal08/toon-memory",
|
|
4
|
+
"version": "3.6.0",
|
|
5
|
+
"description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 37 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
|
|
5
6
|
"type": "module",
|
|
6
7
|
"bin": {
|
|
7
8
|
"toon-memory": "./bin/toon-memory.js"
|
package/skills/toon-memory.md
CHANGED
|
@@ -43,6 +43,26 @@ A persistent memory system for AI coding agents. It remembers decisions, pattern
|
|
|
43
43
|
| `context_brief` | One-call context briefing: memory + sessions + health in compact markdown |
|
|
44
44
|
| `memory_encrypt` | Enable AES-256-GCM encryption |
|
|
45
45
|
| `memory_decrypt` | Disable encryption and decode memory |
|
|
46
|
+
| `memory_backup` | Create timestamped backup of memory file |
|
|
47
|
+
| `context_generate` | Full project briefing: project + git + memory + sessions |
|
|
48
|
+
| `context_diff` | Incremental briefing since last session |
|
|
49
|
+
| `context_focus` | Hyper-focused briefing for a specific task |
|
|
50
|
+
| `context_health` | Memory health audit with score 0-100 |
|
|
51
|
+
| `context_export` | Export memory as markdown for system prompts |
|
|
52
|
+
| `memory_compress` | LLM-powered compression of selected entries |
|
|
53
|
+
| `memory_compress_all` | Batch compression of low-quality entries |
|
|
54
|
+
| `memory_primer` | Auto-generated knowledge map for session start |
|
|
55
|
+
| `memory_merge_sessions` | Merge observations across parallel sessions |
|
|
56
|
+
| `memory_export_gist` | Export memory to a private GitHub Gist |
|
|
57
|
+
| `memory_import_gist` | Import memory from a GitHub Gist |
|
|
58
|
+
| `memory_merge_similar` | Find and merge near-duplicates by Jaccard similarity |
|
|
59
|
+
| `memory_graph_path` | BFS shortest path between two entries |
|
|
60
|
+
| `memory_visualize` | Open interactive memory graph viewer |
|
|
61
|
+
| `memory_pin` | Pin entry with priority 1-5 for top recall placement |
|
|
62
|
+
| `memory_unpin` | Remove the priority flag from an entry |
|
|
63
|
+
| `memory_search` | Search with category, tags, and date range filters |
|
|
64
|
+
| `memory_tag` | Batch tag operations (add, remove, set) |
|
|
65
|
+
| `memory_checkpoint` | Create session snapshot with 7d TTL |
|
|
46
66
|
|
|
47
67
|
## MCP Resources
|
|
48
68
|
|
|
@@ -26,14 +26,15 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
26
26
|
return await $\`npx -y toon-memory dump\`.cwd(root).text()
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
-
const recall = async (query) => {
|
|
29
|
+
const recall = async (query, opts = {}) => {
|
|
30
30
|
try {
|
|
31
|
+
const args = { query, mode: "flat", budget: opts.budget || "tiny", path_scope: opts.path_scope || "" }
|
|
31
32
|
const result = await $\`npx -y toon-memory mcp\`.cwd(root)
|
|
32
33
|
.stdin(JSON.stringify({
|
|
33
34
|
jsonrpc: "2.0",
|
|
34
35
|
id: 1,
|
|
35
36
|
method: "tools/call",
|
|
36
|
-
params: { name: "memory_recall", arguments:
|
|
37
|
+
params: { name: "memory_recall", arguments: args }
|
|
37
38
|
}))
|
|
38
39
|
.text()
|
|
39
40
|
const parsed = JSON.parse(result)
|
|
@@ -62,6 +63,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
62
63
|
"tool.execute.after": async (input) => {
|
|
63
64
|
// Intelligent auto-loading: extract file path from tool result,
|
|
64
65
|
// recall only memory relevant to that file, inject as context.
|
|
66
|
+
// Also proactively recalls entries scoped to the matched paths.
|
|
65
67
|
try {
|
|
66
68
|
const toolName = input?.tool || ""
|
|
67
69
|
const args = input?.args || {}
|
|
@@ -71,6 +73,7 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
71
73
|
if (args.file) filePath = args.file
|
|
72
74
|
else if (args.path) filePath = args.path
|
|
73
75
|
else if (args.filePath) filePath = args.filePath
|
|
76
|
+
else if (args.target) filePath = args.target
|
|
74
77
|
|
|
75
78
|
// Also try to extract from tool output text
|
|
76
79
|
if (!filePath && input?.output) {
|
|
@@ -79,19 +82,40 @@ export const ToonMemory = async ({ $, directory, worktree }) => {
|
|
|
79
82
|
if (fileMatch) filePath = fileMatch[1]
|
|
80
83
|
}
|
|
81
84
|
|
|
82
|
-
if (
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
85
|
+
if (filePath) {
|
|
86
|
+
// Build recall query from file path components
|
|
87
|
+
const basename = path.basename(filePath, path.extname(filePath))
|
|
88
|
+
const dirParts = path.dirname(filePath).split(path.sep).filter(Boolean)
|
|
89
|
+
const query = [basename, ...dirParts.slice(-2)].join(" ")
|
|
90
|
+
|
|
91
|
+
const text = await recall(query, { budget: "tiny", path_scope: filePath })
|
|
92
|
+
if (text && !text.includes("(empty)") && !text.includes("No results")) {
|
|
93
|
+
if (typeof input?.setContext === "function") {
|
|
94
|
+
input.setContext("toon-memory:" + filePath, text)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
91
98
|
|
|
92
|
-
//
|
|
93
|
-
|
|
94
|
-
|
|
99
|
+
// Proactive recall: if no file was found, try tool-name-based recall
|
|
100
|
+
// for common tool patterns that may have relevant memory entries
|
|
101
|
+
if (!filePath && toolName) {
|
|
102
|
+
const toolKeywords = toolName
|
|
103
|
+
.replace(/^memory_/, "")
|
|
104
|
+
.replace(/^context_/, "")
|
|
105
|
+
.replace(/^file_/, "")
|
|
106
|
+
.replace(/^text_document_/, "")
|
|
107
|
+
.split("_")
|
|
108
|
+
.filter(Boolean)
|
|
109
|
+
.join(" ")
|
|
110
|
+
|
|
111
|
+
if (toolKeywords.length > 3) {
|
|
112
|
+
const text = await recall(toolKeywords, { budget: "tiny" })
|
|
113
|
+
if (text && !text.includes("(empty)") && !text.includes("No results")) {
|
|
114
|
+
if (typeof input?.setContext === "function") {
|
|
115
|
+
input.setContext("toon-memory:" + toolName, text)
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
95
119
|
}
|
|
96
120
|
} catch {}
|
|
97
121
|
},
|
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
|
@@ -32,8 +32,14 @@ export interface GraphEntry {
|
|
|
32
32
|
links: string[]
|
|
33
33
|
/** ISO timestamp of last recall/access. Empty if never accessed. */
|
|
34
34
|
lastAccessed: string
|
|
35
|
-
/**
|
|
36
|
-
|
|
35
|
+
/** Priority level 0-5. 0 = normal, 1-5 = pinned with priority (5 = highest). */
|
|
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 {
|
|
@@ -80,7 +86,10 @@ export function parseEntries(data: string): GraphEntry[] {
|
|
|
80
86
|
.map((t) => t.trim())
|
|
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
|
|
@@ -143,6 +152,10 @@ export interface GraphRecallOpts {
|
|
|
143
152
|
hops?: number
|
|
144
153
|
/** Max entries returned (keeps token cost low). Default 6. */
|
|
145
154
|
limit?: number
|
|
155
|
+
/** Session bias: boost entries whose file matches current session files. */
|
|
156
|
+
sessionFiles?: string[]
|
|
157
|
+
/** Path scope glob filter: only return entries whose path_scope matches. */
|
|
158
|
+
path_scope?: string
|
|
146
159
|
}
|
|
147
160
|
|
|
148
161
|
/**
|
|
@@ -155,7 +168,7 @@ export function bm25Scores(entries: GraphEntry[], query: string): Map<string, nu
|
|
|
155
168
|
if (N === 0) return scores
|
|
156
169
|
|
|
157
170
|
const docs = entries.map((e) =>
|
|
158
|
-
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}`)
|
|
159
172
|
)
|
|
160
173
|
const df = new Map<string, number>()
|
|
161
174
|
for (const d of docs) {
|
|
@@ -241,11 +254,13 @@ export function graphRecallDetailed(
|
|
|
241
254
|
|
|
242
255
|
const seedKeys = new Set<string>()
|
|
243
256
|
for (const e of entries) {
|
|
257
|
+
if (e.status === "obsolete") continue
|
|
244
258
|
if (category && e.category !== category) continue
|
|
245
259
|
if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue
|
|
246
260
|
if (from_date && e.date < from_date) continue
|
|
247
261
|
if (to_date && e.date > to_date) continue
|
|
248
262
|
if (e.ttl && isExpiredLocal(e.ttl)) continue
|
|
263
|
+
if (opts.path_scope && e.path_scope && !globMatch(opts.path_scope, e.path_scope)) continue
|
|
249
264
|
const text = normalize(
|
|
250
265
|
`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
|
|
251
266
|
)
|
|
@@ -261,8 +276,9 @@ export function graphRecallDetailed(
|
|
|
261
276
|
if (seedKeys.size === 0) {
|
|
262
277
|
scored.push(
|
|
263
278
|
...[...entries]
|
|
279
|
+
.filter((e) => e.status !== "obsolete")
|
|
264
280
|
.sort((a, b) => {
|
|
265
|
-
if (a.
|
|
281
|
+
if (a.priority !== b.priority) return b.priority - a.priority
|
|
266
282
|
return importance(b) - importance(a)
|
|
267
283
|
})
|
|
268
284
|
.slice(0, opts.limit ?? 6)
|
|
@@ -291,11 +307,17 @@ export function graphRecallDetailed(
|
|
|
291
307
|
const decay = Math.pow(DECAY, dist)
|
|
292
308
|
let s = (bm25.get(k) || 0) + W_CENT * cent.get(k)! + W_IMP * importance(e)
|
|
293
309
|
if (seedKeys.has(k)) s += SEED_BONUS
|
|
310
|
+
if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
|
|
311
|
+
const entryFile = e.file.split(":")[0]
|
|
312
|
+
if (opts.sessionFiles.some((f) => f === entryFile)) {
|
|
313
|
+
s *= 1.15
|
|
314
|
+
}
|
|
315
|
+
}
|
|
294
316
|
s *= decay
|
|
295
|
-
return { e, s,
|
|
317
|
+
return { e, s, priority: e.priority }
|
|
296
318
|
})
|
|
297
319
|
.sort((a, b) => {
|
|
298
|
-
if (a.
|
|
320
|
+
if (a.priority !== b.priority) return b.priority - a.priority
|
|
299
321
|
return b.s - a.s
|
|
300
322
|
})
|
|
301
323
|
.slice(0, opts.limit ?? 6)
|
|
@@ -304,15 +326,16 @@ export function graphRecallDetailed(
|
|
|
304
326
|
|
|
305
327
|
selected = scored.map((x) => x.e)
|
|
306
328
|
|
|
307
|
-
// Inject pinned entries that aren't already in the result set,
|
|
308
|
-
const pinnedKeys = new Set(entries.filter((e) => e.
|
|
329
|
+
// Inject pinned entries that aren't already in the result set, sorted by priority desc.
|
|
330
|
+
const pinnedKeys = new Set(entries.filter((e) => e.priority > 0 && e.status !== "obsolete").map((e) => e.key))
|
|
309
331
|
const inResult = new Set(selected.map((e) => e.key))
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
332
|
+
const toInject = [...pinnedKeys]
|
|
333
|
+
.filter((k) => !inResult.has(k) && byKey.has(k))
|
|
334
|
+
.map((k) => byKey.get(k)!)
|
|
335
|
+
.sort((a, b) => b.priority - a.priority)
|
|
336
|
+
for (const e of toInject) {
|
|
337
|
+
selected.unshift(e)
|
|
338
|
+
scored.unshift({ e, s: 999 })
|
|
316
339
|
}
|
|
317
340
|
|
|
318
341
|
// Restrict adjacency to the selected entries for compact edge rendering.
|
|
@@ -348,6 +371,31 @@ export interface RenderCompactOpts {
|
|
|
348
371
|
seeds?: Set<string>
|
|
349
372
|
/** Max chars before a neighbor (non-seed) is truncated with an ellipsis. */
|
|
350
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
|
+
}
|
|
351
399
|
}
|
|
352
400
|
|
|
353
401
|
/**
|
|
@@ -357,6 +405,11 @@ export interface RenderCompactOpts {
|
|
|
357
405
|
* - graph edges render as `->2, ->3` (numeric) when `adjacency` is given
|
|
358
406
|
* - neighbors reached via graph (non-seeds) are truncated to `snippetLen`
|
|
359
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
|
+
*
|
|
360
413
|
* The stored `.toon` file is never mutated — this only shapes the output.
|
|
361
414
|
*/
|
|
362
415
|
export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {}): string {
|
|
@@ -364,15 +417,38 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
|
|
|
364
417
|
entries.forEach((e, i) => index.set(e.key, i + 1))
|
|
365
418
|
const snippetLen = opts.snippetLen ?? 90
|
|
366
419
|
|
|
420
|
+
const budget = opts.budget ?? "normal"
|
|
421
|
+
|
|
367
422
|
return entries
|
|
368
423
|
.map((e) => {
|
|
369
424
|
const n = index.get(e.key)!
|
|
370
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)
|
|
371
447
|
let body = e.content
|
|
372
448
|
if (!isSeed && e.content.length > snippetLen) {
|
|
373
449
|
body = e.content.slice(0, snippetLen).trimEnd() + "…"
|
|
374
450
|
}
|
|
375
|
-
const tag = e.
|
|
451
|
+
const tag = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
|
|
376
452
|
const tags = e.tags.length ? ` · tags: ${e.tags.join(";")}` : ""
|
|
377
453
|
let edges = ""
|
|
378
454
|
if (opts.adjacency) {
|
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) {
|
|
@@ -139,9 +144,28 @@ export function mergeEntries(existingLine: string, newLine: string): string {
|
|
|
139
144
|
const newLastAccessed = np.length > 12 ? np[12] || "" : ""
|
|
140
145
|
const lastAccessed = newLastAccessed > existingLastAccessed ? newLastAccessed : existingLastAccessed
|
|
141
146
|
|
|
147
|
+
// Take max priority (field 13)
|
|
148
|
+
const existingPriority = ep.length > 13 ? parseInt(ep[13]) || 0 : 0
|
|
149
|
+
const newPriority = np.length > 13 ? parseInt(np[13]) || 0 : 0
|
|
150
|
+
const priority = Math.max(existingPriority, newPriority)
|
|
151
|
+
|
|
142
152
|
const quality = qualityScore(mergedTags, mergedLinks, content, date, accessed, lastAccessed)
|
|
143
153
|
|
|
144
|
-
|
|
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}`
|
|
145
169
|
}
|
|
146
170
|
|
|
147
171
|
/**
|
|
@@ -151,7 +175,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
|
|
|
151
175
|
export function generateSmartRecall(
|
|
152
176
|
data: string,
|
|
153
177
|
intent: string,
|
|
154
|
-
opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string
|
|
178
|
+
opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[] } = {}
|
|
155
179
|
): string {
|
|
156
180
|
const entries = parseEntries(data)
|
|
157
181
|
if (entries.length === 0) return "Empty memory."
|
|
@@ -190,32 +214,42 @@ export function generateSmartRecall(
|
|
|
190
214
|
const fileDate = mtimes.get(filePath)
|
|
191
215
|
if (fileDate && e.date && fileDate > e.date) drift = 0.3
|
|
192
216
|
}
|
|
217
|
+
// Session bias: boost entries matching current session files
|
|
218
|
+
let sessionBias = 0
|
|
219
|
+
if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
|
|
220
|
+
const entryFile = e.file.split(":")[0]
|
|
221
|
+
if (opts.sessionFiles.some((f) => f === entryFile)) {
|
|
222
|
+
sessionBias = 0.15
|
|
223
|
+
}
|
|
224
|
+
}
|
|
193
225
|
const combined =
|
|
194
|
-
bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift
|
|
195
|
-
return { entry: e, score: combined, matchesQuery,
|
|
226
|
+
bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias
|
|
227
|
+
return { entry: e, score: combined, matchesQuery, priority: e.priority }
|
|
196
228
|
})
|
|
197
229
|
.filter((x) => x.score > 0 || x.matchesQuery)
|
|
198
230
|
.sort((a, b) => {
|
|
199
|
-
if (a.
|
|
231
|
+
if (a.priority !== b.priority) return b.priority - a.priority
|
|
200
232
|
return b.score - a.score
|
|
201
233
|
})
|
|
202
234
|
.slice(0, limit)
|
|
203
235
|
|
|
204
|
-
// Inject pinned entries not already in the result set.
|
|
205
|
-
const pinnedKeys = new Set(entries.filter((e) => e.
|
|
236
|
+
// Inject pinned entries not already in the result set, sorted by priority desc.
|
|
237
|
+
const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key))
|
|
206
238
|
const inResult = new Set(scored.map((x) => x.entry.key))
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
239
|
+
const toInject = [...pinnedKeys]
|
|
240
|
+
.filter((k) => !inResult.has(k))
|
|
241
|
+
.map((k) => entries.find((en) => en.key === k)!)
|
|
242
|
+
.filter(Boolean)
|
|
243
|
+
.sort((a, b) => b.priority - a.priority)
|
|
244
|
+
for (const e of toInject) {
|
|
245
|
+
scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority })
|
|
212
246
|
}
|
|
213
247
|
|
|
214
248
|
if (scored.length === 0) {
|
|
215
249
|
const top = entries
|
|
216
250
|
.filter((e) => !category || e.category === category)
|
|
217
251
|
.sort((a, b) => {
|
|
218
|
-
if (a.
|
|
252
|
+
if (a.priority !== b.priority) return b.priority - a.priority
|
|
219
253
|
return importance(b) - importance(a)
|
|
220
254
|
})
|
|
221
255
|
.slice(0, limit)
|
|
@@ -252,7 +286,7 @@ export function generateSystemPrimer(data: string): string {
|
|
|
252
286
|
const top = [...entries]
|
|
253
287
|
.filter((e) => !isPrivate(e))
|
|
254
288
|
.sort((a, b) => {
|
|
255
|
-
if (a.
|
|
289
|
+
if (a.priority !== b.priority) return b.priority - a.priority
|
|
256
290
|
return importance(b) - importance(a)
|
|
257
291
|
})
|
|
258
292
|
.slice(0, 5)
|
|
@@ -267,7 +301,7 @@ export function generateSystemPrimer(data: string): string {
|
|
|
267
301
|
e.lastAccessed
|
|
268
302
|
)
|
|
269
303
|
const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low"
|
|
270
|
-
const pin = e.
|
|
304
|
+
const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
|
|
271
305
|
lines.push(
|
|
272
306
|
` [${e.category}] ${e.key}${pin} — ${e.content.slice(0, 80)} (quality: ${conf})`
|
|
273
307
|
)
|
package/src/lib/sessions.ts
CHANGED
|
@@ -226,6 +226,14 @@ export function detectConflicts(active: ActiveSessionView[] = listSessions().fil
|
|
|
226
226
|
return conflicts
|
|
227
227
|
}
|
|
228
228
|
|
|
229
|
+
/** Get files touched by the current session. Returns empty array if no heartbeat record. */
|
|
230
|
+
export function getCurrentSessionFiles(): string[] {
|
|
231
|
+
const id = resolveSessionId({})
|
|
232
|
+
const all = listSessions()
|
|
233
|
+
const mine = all.find((s) => s.id === id)
|
|
234
|
+
return mine ? Object.keys(mine.files) : []
|
|
235
|
+
}
|
|
236
|
+
|
|
229
237
|
/** Convenience: list active sessions + conflicts in one call. */
|
|
230
238
|
export function coordinationView(selfId?: string) {
|
|
231
239
|
const all = listSessions()
|