toon-memory 4.2.0 → 4.3.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/lib/graph.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * without mutating the stored `.toon` file.
15
15
  */
16
16
 
17
- import { normalize, isExpiredLocal, tokenize, importance, estimateTokens, parseToonLine } from "./utils"
17
+ import { normalize, isExpiredLocal, tokenize, importance, importanceBoost, importanceRank, estimateTokens, parseToonLine } from "./utils"
18
18
  import { expandSynonyms } from "./synonyms"
19
19
  import { fuzzyMatch } from "./fuzzy"
20
20
 
@@ -42,6 +42,8 @@ export interface GraphEntry {
42
42
  status: "active" | "obsolete" | "resolved" | "draft"
43
43
  /** ISO date when this entry was superseded (set by memory_forget action=supersede). Empty if never superseded. */
44
44
  supersededOn: string
45
+ /** Explicit importance level: "critical" | "high" | "medium" | "low". Empty = auto (recency+frequency). */
46
+ importance: string
45
47
  }
46
48
 
47
49
  /** Edge type labels used in typed links (`type:key`). */
@@ -128,6 +130,7 @@ export function parseEntries(data: string): GraphEntry[] {
128
130
  origin: parts.length > 15 && parts[15] ? parts[15] as "human" | "agent" | "inferred" : "agent",
129
131
  status: parts.length > 16 && parts[16] ? parts[16] as "active" | "obsolete" | "resolved" | "draft" : "active",
130
132
  supersededOn: parts.length > 17 ? parts[17] || "" : "",
133
+ importance: parts.length > 18 ? parts[18] || "" : "",
131
134
  })
132
135
  }
133
136
  return out
@@ -419,6 +422,7 @@ export function buildReason(
419
422
  parts.push("never used")
420
423
  }
421
424
  parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW")
425
+ if (e.importance) parts.push(`explicit ${e.importance}`)
422
426
  return parts.join(" · ")
423
427
  }
424
428
 
@@ -490,10 +494,13 @@ export function graphRecallDetailed(
490
494
  ...visibleEntries
491
495
  .sort((a, b) => {
492
496
  if (a.priority !== b.priority) return b.priority - a.priority
497
+ const ia = importanceRank(a.importance)
498
+ const ib = importanceRank(b.importance)
499
+ if (ia !== ib) return ib - ia
493
500
  return importance(b, opts.today) - importance(a, opts.today)
494
501
  })
495
502
  .slice(0, opts.limit ?? 6)
496
- .map((e) => ({ e, s: importance(e, opts.today) }))
503
+ .map((e) => ({ e, s: importance(e, opts.today) + importanceBoost(e.importance) }))
497
504
  )
498
505
  } else {
499
506
  // BFS from all seeds, recording the shortest hop distance to each node.
@@ -541,6 +548,8 @@ export function graphRecallDetailed(
541
548
  }
542
549
  // Negative-memory boost: warnings surface first.
543
550
  if (e.category === "warning") s += 0.2
551
+ // Explicit importance boost: critical/high entries surface first, low last.
552
+ s += importanceBoost(e.importance)
544
553
  s *= decay
545
554
  return { e, s, priority: e.priority }
546
555
  })
@@ -685,7 +694,8 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
685
694
  const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
686
695
  const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
687
696
  const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
688
- block = `[${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}${supersededInfo}${links}`
697
+ const impInfo = e.importance ? ` · importance: ${e.importance}` : ""
698
+ block = `[${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}${supersededInfo}${impInfo}${links}`
689
699
  } else {
690
700
  // "normal" budget (default)
691
701
  let body = e.content
@@ -20,7 +20,7 @@ import {
20
20
  buildReason,
21
21
  type GraphEntry,
22
22
  } from "./graph"
23
- import { normalize, isExpiredLocal, tokenize, importance, isPrivate, estimateTokens, languageFamily, parseToonLine, toToonLine } from "./utils"
23
+ import { normalize, isExpiredLocal, tokenize, importance, importanceBoost, importanceRank, isPrivate, estimateTokens, languageFamily, parseToonLine, toToonLine } from "./utils"
24
24
  import { expandSynonyms } from "./synonyms"
25
25
  import { fuzzyMatch } from "./fuzzy"
26
26
 
@@ -180,7 +180,12 @@ export function mergeEntries(existingLine: string, newLine: string): string {
180
180
  // Preserve superseded_on (field 17) from the existing entry.
181
181
  const existingSupersededOn = ep.length > 17 ? ep[17] || "" : ""
182
182
 
183
- return toToonLine([id, category, key, content, file, mergedTags, date, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn])
183
+ // Take the more important explicit level (field 18). Empty (auto) counts as medium.
184
+ const existingImportance = ep.length > 18 ? ep[18] || "" : ""
185
+ const newImportance = np.length > 18 ? np[18] || "" : ""
186
+ const importance = importanceRank(newImportance) >= importanceRank(existingImportance) ? newImportance : existingImportance
187
+
188
+ return toToonLine([id, category, key, content, file, mergedTags, date, ttl, String(accessed), mergedLinks, quality.toFixed(2), String(confidence), lastAccessed, String(priority), path_scope, origin, status, existingSupersededOn, importance])
184
189
  }
185
190
 
186
191
  /**
@@ -272,12 +277,14 @@ export function generateSmartRecall(
272
277
  if (e.path_scope && globMatch(e.path_scope, ".")) folderBoost = 0.05
273
278
  // Negative-memory boost: warnings are cheap to ignore and expensive to repeat.
274
279
  const warningBoost = e.category === "warning" ? 0.2 : 0
280
+ // Explicit importance boost: critical/high entries surface first, low last.
281
+ const impBoost = importanceBoost(e.importance)
275
282
  let combined: number
276
283
  if (opts.rrf) {
277
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost
284
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost
278
285
  } else {
279
286
  combined =
280
- bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost
287
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost
281
288
  }
282
289
  return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score }
283
290
  })
@@ -304,6 +311,9 @@ export function generateSmartRecall(
304
311
  const top = eligible
305
312
  .sort((a, b) => {
306
313
  if (a.priority !== b.priority) return b.priority - a.priority
314
+ const ia = importanceRank(a.importance)
315
+ const ib = importanceRank(b.importance)
316
+ if (ia !== ib) return ib - ia
307
317
  return importance(b, opts.today) - importance(a, opts.today)
308
318
  })
309
319
  .slice(0, limit)
package/src/lib/utils.ts CHANGED
@@ -23,6 +23,30 @@ export function importance(
23
23
  return recency * 0.6 + freq * 0.4
24
24
  }
25
25
 
26
+ /** Explicit importance levels, highest to lowest. Empty string = auto (no boost). */
27
+ export const IMPORTANCE_LEVELS = ["critical", "high", "medium", "low"] as const
28
+ export type ImportanceLevel = (typeof IMPORTANCE_LEVELS)[number]
29
+
30
+ /** Ranking boost for an explicit importance level. Auto (empty) = 0. */
31
+ export const IMPORTANCE_BOOST: Record<ImportanceLevel, number> = {
32
+ critical: 0.3,
33
+ high: 0.15,
34
+ medium: 0,
35
+ low: -0.1,
36
+ }
37
+
38
+ /** Map an explicit importance level to its ranking boost (empty/unknown = 0). */
39
+ export const importanceBoost = (level: string): number =>
40
+ IMPORTANCE_BOOST[level as ImportanceLevel] ?? 0
41
+
42
+ /** Rank order for merging: higher value wins. Empty (auto) counts as medium. */
43
+ export const importanceRank = (level: string): number => {
44
+ if (level === "critical") return 4
45
+ if (level === "high") return 3
46
+ if (level === "low") return 1
47
+ return 2 // medium or auto
48
+ }
49
+
26
50
  export const tokenize = (s: string): string[] =>
27
51
  s
28
52
  .replace(/([a-z])([A-Z])/g, "$1 $2")
package/src/mcp/tools.ts CHANGED
@@ -466,10 +466,11 @@ server.registerTool(
466
466
  links: z.string().optional().default("").describe("Related entry keys, separated by space or ';' (e.g. risk-spec engine-arch). Builds graph edges."),
467
467
  path_scope: z.string().optional().default("").describe("Glob pattern to scope this entry (e.g. src/**.ts). Empty = global."),
468
468
  origin: z.enum(["human", "agent", "inferred"]).optional().default("agent").describe("Who created this entry."),
469
+ importance: z.enum(["critical", "high", "medium", "low"]).optional().describe("Explicit importance level — critical/high entries surface first in recall, low last. Omit for auto (recency + frequency)."),
469
470
  },
470
471
  annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
471
472
  },
472
- async ({ category, key, content, file, tags, ttl, links, path_scope, origin }) => {
473
+ async ({ category, key, content, file, tags, ttl, links, path_scope, origin, importance = "" }) => {
473
474
  const data = readMemory()
474
475
  const newId = generateId()
475
476
  const date = new Date().toISOString().split("T")[0]
@@ -504,7 +505,7 @@ server.registerTool(
504
505
  const resolvedLinks = links
505
506
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
506
507
  : existingParts[9] || ""
507
- let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", path_scope || "", origin])
508
+ let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", "0", path_scope || "", origin, "", "", importance])
508
509
  let action = "Saved"
509
510
  let mergeInfo = ""
510
511
  const tagsInferred = !tags && resolvedTags ? true : false
@@ -519,7 +520,7 @@ server.registerTool(
519
520
  const lastAccessed = ""
520
521
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed, origin)
521
522
  const confidence = 1.0
522
- newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active"])
523
+ newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active", "", importance])
523
524
  const match = lines[headerIdx].match(/\[(\d+)\|/)
524
525
  const count = match ? parseInt(match[1]) : 0
525
526
  lines.splice(headerIdx + 1, 0, newEntry)