toon-memory 3.3.1 โ†’ 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli/hooks.ts CHANGED
@@ -6,6 +6,8 @@ import { projectRoot, CAPTURE_JS, SESSION_START_JS, CAPTURE_CONFIG, ANTIGRAVITY_
6
6
  /** Hook script content for SessionStart reminder */
7
7
  export function sessionStartHookContent(agentName: string): string {
8
8
  return `#!/bin/bash
9
+ # toon-memory session-start hook for ${agentName}
10
+ # Registers this session so memory_sessions and context_* tools work.
9
11
  node "${SESSION_START_JS}" ${agentName}
10
12
  exit 0
11
13
  `
@@ -17,6 +19,8 @@ exit 0
17
19
  */
18
20
  export function captureHookContent(agentName: string): string {
19
21
  return `#!/bin/bash
22
+ # toon-memory capture hook for ${agentName}
23
+ # Logs tool calls to observations.toon (opt-in via TOON_MEMORY_CAPTURE env or config).
20
24
  CFG="${CAPTURE_CONFIG}"
21
25
  if [ -z "$TOON_MEMORY_CAPTURE" ]; then
22
26
  if [ ! -f "$CFG" ]; then exit 0; fi
package/src/cli/memory.ts CHANGED
@@ -12,7 +12,7 @@ export function installMemoryDir(): void {
12
12
  if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
13
13
 
14
14
  if (!existsSync(memoryFile)) {
15
- writeFileSync(memoryFile, "version: 1\n[0|]\n")
15
+ writeFileSync(memoryFile, "version: 1\n[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence|lastAccessed|pinned}:\n")
16
16
  console.log(" Created .toon-memory/memory/data.toon")
17
17
  }
18
18
  }
package/src/lib/graph.ts CHANGED
@@ -32,6 +32,8 @@ export interface GraphEntry {
32
32
  links: string[]
33
33
  /** ISO timestamp of last recall/access. Empty if never accessed. */
34
34
  lastAccessed: string
35
+ /** Priority level 0-5. 0 = normal, 1-5 = pinned with priority (5 = highest). */
36
+ priority: number
35
37
  }
36
38
 
37
39
  export interface MemoryGraph {
@@ -78,6 +80,7 @@ export function parseEntries(data: string): GraphEntry[] {
78
80
  .map((t) => t.trim())
79
81
  .filter(Boolean),
80
82
  lastAccessed: parts.length > 12 ? parts[12] || "" : "",
83
+ priority: parts.length > 13 ? parseInt(parts[13]) || 0 : 0,
81
84
  })
82
85
  }
83
86
  return out
@@ -132,12 +135,16 @@ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
132
135
 
133
136
  export interface GraphRecallOpts {
134
137
  category?: string
138
+ /** Semicolon-separated; entry must have ALL specified tags to match. */
139
+ tags?: string
135
140
  from_date?: string
136
141
  to_date?: string
137
142
  /** Graph traversal depth from matched seeds (1 or 2). Default 1. */
138
143
  hops?: number
139
144
  /** Max entries returned (keeps token cost low). Default 6. */
140
145
  limit?: number
146
+ /** Session bias: boost entries whose file matches current session files. */
147
+ sessionFiles?: string[]
141
148
  }
142
149
 
143
150
  /**
@@ -225,6 +232,7 @@ export function graphRecallDetailed(
225
232
  const { adjacency, byKey } = buildGraph(entries)
226
233
  const hops = Math.max(1, Math.min(2, opts.hops ?? 1))
227
234
  const category = opts.category || ""
235
+ const tagsFilter = opts.tags ? opts.tags.split(";").map((t) => t.trim()).filter(Boolean) : []
228
236
  const from_date = opts.from_date || ""
229
237
  const to_date = opts.to_date || ""
230
238
 
@@ -236,6 +244,7 @@ export function graphRecallDetailed(
236
244
  const seedKeys = new Set<string>()
237
245
  for (const e of entries) {
238
246
  if (category && e.category !== category) continue
247
+ if (tagsFilter.length > 0 && !tagsFilter.every((t) => e.tags.includes(t))) continue
239
248
  if (from_date && e.date < from_date) continue
240
249
  if (to_date && e.date > to_date) continue
241
250
  if (e.ttl && isExpiredLocal(e.ttl)) continue
@@ -254,7 +263,10 @@ export function graphRecallDetailed(
254
263
  if (seedKeys.size === 0) {
255
264
  scored.push(
256
265
  ...[...entries]
257
- .sort((a, b) => importance(b) - importance(a))
266
+ .sort((a, b) => {
267
+ if (a.priority !== b.priority) return b.priority - a.priority
268
+ return importance(b) - importance(a)
269
+ })
258
270
  .slice(0, opts.limit ?? 6)
259
271
  .map((e) => ({ e, s: importance(e) }))
260
272
  )
@@ -281,16 +293,37 @@ export function graphRecallDetailed(
281
293
  const decay = Math.pow(DECAY, dist)
282
294
  let s = (bm25.get(k) || 0) + W_CENT * cent.get(k)! + W_IMP * importance(e)
283
295
  if (seedKeys.has(k)) s += SEED_BONUS
296
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
297
+ const entryFile = e.file.split(":")[0]
298
+ if (opts.sessionFiles.some((f) => f === entryFile)) {
299
+ s *= 1.15
300
+ }
301
+ }
284
302
  s *= decay
285
- return { e, s }
303
+ return { e, s, priority: e.priority }
304
+ })
305
+ .sort((a, b) => {
306
+ if (a.priority !== b.priority) return b.priority - a.priority
307
+ return b.s - a.s
286
308
  })
287
- .sort((a, b) => b.s - a.s)
288
309
  .slice(0, opts.limit ?? 6)
289
310
  )
290
311
  }
291
312
 
292
313
  selected = scored.map((x) => x.e)
293
314
 
315
+ // 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))
317
+ const inResult = new Set(selected.map((e) => e.key))
318
+ const toInject = [...pinnedKeys]
319
+ .filter((k) => !inResult.has(k) && byKey.has(k))
320
+ .map((k) => byKey.get(k)!)
321
+ .sort((a, b) => b.priority - a.priority)
322
+ for (const e of toInject) {
323
+ selected.unshift(e)
324
+ scored.unshift({ e, s: 999 })
325
+ }
326
+
294
327
  // Restrict adjacency to the selected entries for compact edge rendering.
295
328
  const subAdj = new Map<string, string[]>()
296
329
  for (const e of selected) {
@@ -348,6 +381,7 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
348
381
  if (!isSeed && e.content.length > snippetLen) {
349
382
  body = e.content.slice(0, snippetLen).trimEnd() + "โ€ฆ"
350
383
  }
384
+ const tag = e.priority > 0 ? (e.priority > 1 ? ` ๐Ÿ“Œ${e.priority}` : " ๐Ÿ“Œ") : ""
351
385
  const tags = e.tags.length ? ` ยท tags: ${e.tags.join(";")}` : ""
352
386
  let edges = ""
353
387
  if (opts.adjacency) {
@@ -356,7 +390,7 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
356
390
  .filter((x): x is number => typeof x === "number")
357
391
  if (nb.length) edges = ` ยท edges: ->${nb.join(", ->")}`
358
392
  }
359
- return `[${n}] ${e.category}/${e.key}\n ${body}${tags}${edges}`
393
+ return `[${n}] ${e.category}/${e.key}${tag}\n ${body}${tags}${edges}`
360
394
  })
361
395
  .join("\n\n")
362
396
  }
@@ -139,9 +139,14 @@ export function mergeEntries(existingLine: string, newLine: string): string {
139
139
  const newLastAccessed = np.length > 12 ? np[12] || "" : ""
140
140
  const lastAccessed = newLastAccessed > existingLastAccessed ? newLastAccessed : existingLastAccessed
141
141
 
142
+ // Take max priority (field 13)
143
+ const existingPriority = ep.length > 13 ? parseInt(ep[13]) || 0 : 0
144
+ const newPriority = np.length > 13 ? parseInt(np[13]) || 0 : 0
145
+ const priority = Math.max(existingPriority, newPriority)
146
+
142
147
  const quality = qualityScore(mergedTags, mergedLinks, content, date, accessed, lastAccessed)
143
148
 
144
- return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}`
149
+ return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}|${lastAccessed}|${priority}`
145
150
  }
146
151
 
147
152
  /**
@@ -151,7 +156,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
151
156
  export function generateSmartRecall(
152
157
  data: string,
153
158
  intent: string,
154
- opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string> } = {}
159
+ opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[] } = {}
155
160
  ): string {
156
161
  const entries = parseEntries(data)
157
162
  if (entries.length === 0) return "Empty memory."
@@ -190,18 +195,44 @@ export function generateSmartRecall(
190
195
  const fileDate = mtimes.get(filePath)
191
196
  if (fileDate && e.date && fileDate > e.date) drift = 0.3
192
197
  }
198
+ // Session bias: boost entries matching current session files
199
+ let sessionBias = 0
200
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
201
+ const entryFile = e.file.split(":")[0]
202
+ if (opts.sessionFiles.some((f) => f === entryFile)) {
203
+ sessionBias = 0.15
204
+ }
205
+ }
193
206
  const combined =
194
- bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift
195
- return { entry: e, score: combined, matchesQuery }
207
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias
208
+ return { entry: e, score: combined, matchesQuery, priority: e.priority }
196
209
  })
197
210
  .filter((x) => x.score > 0 || x.matchesQuery)
198
- .sort((a, b) => b.score - a.score)
211
+ .sort((a, b) => {
212
+ if (a.priority !== b.priority) return b.priority - a.priority
213
+ return b.score - a.score
214
+ })
199
215
  .slice(0, limit)
200
216
 
217
+ // Inject pinned entries not already in the result set, sorted by priority desc.
218
+ const pinnedKeys = new Set(entries.filter((e) => e.priority > 0).map((e) => e.key))
219
+ const inResult = new Set(scored.map((x) => x.entry.key))
220
+ const toInject = [...pinnedKeys]
221
+ .filter((k) => !inResult.has(k))
222
+ .map((k) => entries.find((en) => en.key === k)!)
223
+ .filter(Boolean)
224
+ .sort((a, b) => b.priority - a.priority)
225
+ for (const e of toInject) {
226
+ scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority })
227
+ }
228
+
201
229
  if (scored.length === 0) {
202
230
  const top = entries
203
231
  .filter((e) => !category || e.category === category)
204
- .sort((a, b) => importance(b) - importance(a))
232
+ .sort((a, b) => {
233
+ if (a.priority !== b.priority) return b.priority - a.priority
234
+ return importance(b) - importance(a)
235
+ })
205
236
  .slice(0, limit)
206
237
  if (top.length === 0) return "No entries in memory."
207
238
  return renderCompact(top)
@@ -232,10 +263,13 @@ export function generateSystemPrimer(data: string): string {
232
263
  "",
233
264
  ]
234
265
 
235
- // Top entries by importance (global)
266
+ // Pinned entries first, then top by importance
236
267
  const top = [...entries]
237
268
  .filter((e) => !isPrivate(e))
238
- .sort((a, b) => importance(b) - importance(a))
269
+ .sort((a, b) => {
270
+ if (a.priority !== b.priority) return b.priority - a.priority
271
+ return importance(b) - importance(a)
272
+ })
239
273
  .slice(0, 5)
240
274
  lines.push("Top memories:")
241
275
  for (const e of top) {
@@ -248,8 +282,9 @@ export function generateSystemPrimer(data: string): string {
248
282
  e.lastAccessed
249
283
  )
250
284
  const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low"
285
+ const pin = e.priority > 0 ? (e.priority > 1 ? ` ๐Ÿ“Œ${e.priority}` : " ๐Ÿ“Œ") : ""
251
286
  lines.push(
252
- ` [${e.category}] ${e.key} โ€” ${e.content.slice(0, 80)} (quality: ${conf})`
287
+ ` [${e.category}] ${e.key}${pin} โ€” ${e.content.slice(0, 80)} (quality: ${conf})`
253
288
  )
254
289
  }
255
290
  lines.push("")
@@ -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()
package/src/mcp/config.ts CHANGED
@@ -98,6 +98,6 @@ export function ensureMemoryDir(): void {
98
98
  export function ensureMemoryFile(): void {
99
99
  ensureMemoryDir()
100
100
  if (!existsSync(MEMORY_FILE)) {
101
- writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n")
101
+ writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence|lastAccessed|pinned}:\n")
102
102
  }
103
103
  }