toon-memory 4.1.2 → 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, 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
@@ -389,6 +392,38 @@ export interface GraphRecallResult {
389
392
  adjacency: Map<string, string[]>
390
393
  /** Final combined score per key (bm25 + centrality + importance + seed bonus). */
391
394
  scores: Map<string, number>
395
+ /** Optional per-key "why selected" reason strings (Explaining WHY). */
396
+ reasons?: Map<string, string>
397
+ }
398
+
399
+ /**
400
+ * Build a short, deterministic "why was this selected" string per entry.
401
+ * Pure heuristics — no LLM. Used to explain recall results so the agent can
402
+ * trust the ranking instead of trusting a black box.
403
+ */
404
+ export function buildReason(
405
+ e: GraphEntry,
406
+ bm25Score: number,
407
+ bm25Max: number,
408
+ impScore: number,
409
+ today = new Date().toISOString().split("T")[0]
410
+ ): string {
411
+ const parts: string[] = []
412
+ if (bm25Max > 0) {
413
+ parts.push(`${Math.round((bm25Score / bm25Max) * 100)}% relevance`)
414
+ }
415
+ if (e.accessed > 0) {
416
+ parts.push(`used ${e.accessed}×`)
417
+ }
418
+ if (e.lastAccessed) {
419
+ const days = Math.floor((Date.parse(`${today}T00:00:00`) - Date.parse(e.lastAccessed)) / 86400000)
420
+ parts.push(days <= 0 ? "used today" : days === 1 ? "used yesterday" : `used ${days}d ago`)
421
+ } else if (e.accessed === 0) {
422
+ parts.push("never used")
423
+ }
424
+ parts.push(impScore >= 0.7 ? "importance HIGH" : impScore >= 0.4 ? "importance MED" : "importance LOW")
425
+ if (e.importance) parts.push(`explicit ${e.importance}`)
426
+ return parts.join(" · ")
392
427
  }
393
428
 
394
429
  const W_CENT = 0.4
@@ -459,10 +494,13 @@ export function graphRecallDetailed(
459
494
  ...visibleEntries
460
495
  .sort((a, b) => {
461
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
462
500
  return importance(b, opts.today) - importance(a, opts.today)
463
501
  })
464
502
  .slice(0, opts.limit ?? 6)
465
- .map((e) => ({ e, s: importance(e, opts.today) }))
503
+ .map((e) => ({ e, s: importance(e, opts.today) + importanceBoost(e.importance) }))
466
504
  )
467
505
  } else {
468
506
  // BFS from all seeds, recording the shortest hop distance to each node.
@@ -508,6 +546,10 @@ export function graphRecallDetailed(
508
546
  s *= 1.15
509
547
  }
510
548
  }
549
+ // Negative-memory boost: warnings surface first.
550
+ if (e.category === "warning") s += 0.2
551
+ // Explicit importance boost: critical/high entries surface first, low last.
552
+ s += importanceBoost(e.importance)
511
553
  s *= decay
512
554
  return { e, s, priority: e.priority }
513
555
  })
@@ -545,7 +587,18 @@ export function graphRecallDetailed(
545
587
  const scores = new Map<string, number>()
546
588
  selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key)!.s))
547
589
 
548
- return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores }
590
+ // Explain WHY: normalize bm25 by its max over the visible candidates.
591
+ let bm25Max = 0
592
+ for (const v of bm25.values()) if (v > bm25Max) bm25Max = v
593
+ const reasons = new Map<string, string>()
594
+ for (const e of selected) {
595
+ reasons.set(
596
+ e.key,
597
+ buildReason(e, bm25.get(e.key) || 0, bm25Max, importance(e, opts.today), opts.today)
598
+ )
599
+ }
600
+
601
+ return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores, reasons }
549
602
  }
550
603
 
551
604
  /**
@@ -568,6 +621,10 @@ export interface RenderCompactOpts {
568
621
  snippetLen?: number
569
622
  /** Budget level: "tiny" (key+1 line), "normal" (compact, default), "deep" (all fields). */
570
623
  budget?: "tiny" | "normal" | "deep"
624
+ /** Optional per-key reason strings appended after each entry ("why it was selected"). */
625
+ reasons?: Map<string, string>
626
+ /** Deterministic token budget: stop after entries consume ~N estimated tokens. */
627
+ budgetTokens?: number
571
628
  }
572
629
 
573
630
  /**
@@ -614,31 +671,32 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
614
671
 
615
672
  const budget = opts.budget ?? "normal"
616
673
 
617
- return entries
618
- .map((e) => {
619
- const n = index.get(e.key)!
620
- const isSeed = opts.seeds ? opts.seeds.has(e.key) : true
621
-
622
- if (budget === "tiny") {
623
- const firstLine = e.content.split("\n")[0] || ""
624
- const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "…" : firstLine
625
- const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
626
- return `[${n}] ${e.category}/${e.key}${pin}\n ${snippet}`
627
- }
628
-
629
- if (budget === "deep") {
630
- const ttlInfo = e.ttl ? ` · ttl: ${e.ttl}` : ""
631
- const accessInfo = e.accessed > 0 ? ` · accessed: ${e.accessed}x` : ""
632
- const lastAccess = e.lastAccessed ? ` · lastAccess: ${e.lastAccessed}` : ""
633
- const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
634
- const links = e.links.length ? `\n links: ${e.links.join(", ")}` : ""
635
- const originInfo = e.origin !== "agent" ? ` · origin: ${e.origin}` : ""
636
- const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
637
- const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
638
- const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
639
- 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}${supersededInfo}${links}`
640
- }
641
-
674
+ const rendered: string[] = []
675
+ let tokens = 0
676
+ for (const e of entries) {
677
+ const n = index.get(e.key)!
678
+ const isSeed = opts.seeds ? opts.seeds.has(e.key) : true
679
+ const reason = opts.reasons?.get(e.key)
680
+ let block: string
681
+
682
+ if (budget === "tiny") {
683
+ const firstLine = e.content.split("\n")[0] || ""
684
+ const snippet = firstLine.length > 80 ? firstLine.slice(0, 80).trimEnd() + "…" : firstLine
685
+ const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
686
+ block = `[${n}] ${e.category}/${e.key}${pin}\n ${snippet}`
687
+ } else if (budget === "deep") {
688
+ const ttlInfo = e.ttl ? ` · ttl: ${e.ttl}` : ""
689
+ const accessInfo = e.accessed > 0 ? ` · accessed: ${e.accessed}x` : ""
690
+ const lastAccess = e.lastAccessed ? ` · lastAccess: ${e.lastAccessed}` : ""
691
+ const pin = e.priority > 0 ? (e.priority > 1 ? ` 📌${e.priority}` : " 📌") : ""
692
+ const links = e.links.length ? `\n links: ${e.links.join(", ")}` : ""
693
+ const originInfo = e.origin !== "agent" ? ` · origin: ${e.origin}` : ""
694
+ const scopeInfo = e.path_scope ? ` · scope: ${e.path_scope}` : ""
695
+ const statusInfo = e.status !== "active" ? ` · status: ${e.status}` : ""
696
+ const supersededInfo = e.supersededOn ? ` · superseded: ${e.supersededOn}` : ""
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}`
699
+ } else {
642
700
  // "normal" budget (default)
643
701
  let body = e.content
644
702
  if (!isSeed && e.content.length > snippetLen) {
@@ -653,7 +711,21 @@ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {
653
711
  .filter((x): x is number => typeof x === "number")
654
712
  if (nb.length) edges = ` · edges: ->${nb.join(", ->")}`
655
713
  }
656
- return `[${n}] ${e.category}/${e.key}${tag}\n ${body}${tags}${edges}`
657
- })
658
- .join("\n\n")
714
+ block = `[${n}] ${e.category}/${e.key}${tag}\n ${body}${tags}${edges}`
715
+ }
716
+
717
+ if (reason) block += `\n ↳ ${reason}`
718
+ rendered.push(block)
719
+
720
+ // Deterministic token budget: stop before the accumulated estimate exceeds it.
721
+ if (opts.budgetTokens && opts.budgetTokens > 0) {
722
+ tokens += estimateTokens(block)
723
+ if (rendered.length > 1 && tokens > opts.budgetTokens) {
724
+ rendered.pop()
725
+ break
726
+ }
727
+ }
728
+ }
729
+
730
+ return rendered.join("\n\n")
659
731
  }
@@ -16,9 +16,11 @@ import {
16
16
  rankBy,
17
17
  rrfFuse,
18
18
  rrfK,
19
+ globMatch,
20
+ buildReason,
19
21
  type GraphEntry,
20
22
  } from "./graph"
21
- import { normalize, isExpiredLocal, tokenize, importance, isPrivate, parseToonLine, toToonLine } from "./utils"
23
+ import { normalize, isExpiredLocal, tokenize, importance, importanceBoost, importanceRank, isPrivate, estimateTokens, languageFamily, parseToonLine, toToonLine } from "./utils"
22
24
  import { expandSynonyms } from "./synonyms"
23
25
  import { fuzzyMatch } from "./fuzzy"
24
26
 
@@ -178,7 +180,12 @@ export function mergeEntries(existingLine: string, newLine: string): string {
178
180
  // Preserve superseded_on (field 17) from the existing entry.
179
181
  const existingSupersededOn = ep.length > 17 ? ep[17] || "" : ""
180
182
 
181
- 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])
182
189
  }
183
190
 
184
191
  /**
@@ -188,7 +195,17 @@ export function mergeEntries(existingLine: string, newLine: string): string {
188
195
  export function generateSmartRecall(
189
196
  data: string,
190
197
  intent: string,
191
- opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void; fileMtimes?: Map<string, string>; sessionFiles?: string[]; rrf?: boolean; today?: string } = {}
198
+ opts: {
199
+ limit?: number
200
+ category?: string
201
+ bumpAccess?: (ids: string[]) => void
202
+ fileMtimes?: Map<string, string>
203
+ sessionFiles?: string[]
204
+ rrf?: boolean
205
+ today?: string
206
+ explain?: boolean
207
+ budgetTokens?: number
208
+ } = {}
192
209
  ): string {
193
210
  const entries = parseEntries(data)
194
211
  if (entries.length === 0) return "Empty memory."
@@ -247,14 +264,29 @@ export function generateSmartRecall(
247
264
  sessionBias = 0.15
248
265
  }
249
266
  }
267
+ // Language match: same script family as the query gets a small boost
268
+ // (a Spanish query should prefer Spanish entries over English ones).
269
+ let langBoost = 0
270
+ const qFamily = languageFamily(intent)
271
+ if (qFamily !== "none") {
272
+ const eFamily = languageFamily(`${e.content} ${e.key} ${e.tags.join(" ")}`)
273
+ if (qFamily === eFamily) langBoost = 0.1
274
+ }
275
+ // Folder match: entries scoped to the current working directory get a boost.
276
+ let folderBoost = 0
277
+ if (e.path_scope && globMatch(e.path_scope, ".")) folderBoost = 0.05
278
+ // Negative-memory boost: warnings are cheap to ignore and expensive to repeat.
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)
250
282
  let combined: number
251
283
  if (opts.rrf) {
252
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias
284
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost
253
285
  } else {
254
286
  combined =
255
- bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias
287
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost
256
288
  }
257
- return { entry: e, score: combined, matchesQuery, priority: e.priority }
289
+ return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score }
258
290
  })
259
291
  .filter((x) => x.score > 0 || x.matchesQuery)
260
292
  .sort((a, b) => {
@@ -272,22 +304,38 @@ export function generateSmartRecall(
272
304
  .filter(Boolean)
273
305
  .sort((a, b) => b.priority - a.priority)
274
306
  for (const e of toInject) {
275
- scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority })
307
+ scored.unshift({ entry: e, score: 999, matchesQuery: false, priority: e.priority, bm25Score: 0 })
276
308
  }
277
309
 
278
310
  if (scored.length === 0) {
279
311
  const top = eligible
280
312
  .sort((a, b) => {
281
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
282
317
  return importance(b, opts.today) - importance(a, opts.today)
283
318
  })
284
319
  .slice(0, limit)
285
320
  if (top.length === 0) return "No entries in memory."
286
- return renderCompact(top)
321
+ return renderCompact(top, { budgetTokens: opts.budgetTokens })
287
322
  }
288
323
 
289
324
  if (opts.bumpAccess) opts.bumpAccess(scored.map((x) => x.entry.id))
290
- return renderCompact(scored.map((x) => x.entry))
325
+
326
+ // Explain WHY: build per-key reasons with the same determinism as graph recall.
327
+ let bm25Max = 0
328
+ for (const s of scored) if (s.bm25Score > bm25Max) bm25Max = s.bm25Score
329
+ const reasons = new Map<string, string>()
330
+ if (opts.explain) {
331
+ for (const s of scored) {
332
+ reasons.set(
333
+ s.entry.key,
334
+ buildReason(s.entry, s.bm25Score, bm25Max, importance(s.entry, opts.today), opts.today)
335
+ )
336
+ }
337
+ }
338
+ return renderCompact(scored.map((x) => x.entry), { reasons: opts.explain ? reasons : undefined, budgetTokens: opts.budgetTokens })
291
339
  }
292
340
 
293
341
  /**
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")
@@ -31,6 +55,46 @@ export const tokenize = (s: string): string[] =>
31
55
  .split(/\s+/)
32
56
  .filter(Boolean)
33
57
 
58
+ /**
59
+ * Deterministic token estimate for a text: roughly one token per 4 chars,
60
+ * plus one per whitespace run. No LLM — good enough to budget recall output.
61
+ */
62
+ export const estimateTokens = (s: string): number => {
63
+ if (!s) return 0
64
+ const chars = Math.ceil(s.length / 4)
65
+ const words = (s.match(/\S+/g) || []).length
66
+ return Math.max(1, chars + words)
67
+ }
68
+
69
+ /**
70
+ * Language-family detection via character ranges. Deterministic, no libraries.
71
+ * Returns "latin" for ASCII/EU languages, "cjk" for CJK, "cyrillic", "arabic",
72
+ * "greek", "hebrew", "devanagari", or "other".
73
+ */
74
+ export const languageFamily = (s: string): string => {
75
+ let cjk = 0, cyr = 0, arab = 0, greek = 0, hebrew = 0, deva = 0, latin = 0, total = 0
76
+ for (const ch of s) {
77
+ const c = ch.codePointAt(0)!
78
+ if (!/[\p{L}]/u.test(ch)) continue
79
+ total++
80
+ if (c >= 0x4e00 && c <= 0x9fff || c >= 0x3040 && c <= 0x30ff || c >= 0xac00 && c <= 0xd7af) cjk++
81
+ else if (c >= 0x0400 && c <= 0x04ff) cyr++
82
+ else if (c >= 0x0600 && c <= 0x06ff) arab++
83
+ else if (c >= 0x0370 && c <= 0x03ff) greek++
84
+ else if (c >= 0x0590 && c <= 0x05ff) hebrew++
85
+ else if (c >= 0x0900 && c <= 0x097f) deva++
86
+ else latin++
87
+ }
88
+ if (total === 0) return "none"
89
+ if (cjk / total > 0.3) return "cjk"
90
+ if (cyr / total > 0.3) return "cyrillic"
91
+ if (arab / total > 0.3) return "arabic"
92
+ if (greek / total > 0.3) return "greek"
93
+ if (hebrew / total > 0.3) return "hebrew"
94
+ if (deva / total > 0.3) return "devanagari"
95
+ return "latin"
96
+ }
97
+
34
98
  /**
35
99
  * Escape a field for the pipe-delimited TOON format. Literal newlines, pipes and
36
100
  * backslashes would otherwise break line-based parsing (a multi-line content turns
@@ -1,6 +1,6 @@
1
1
  import { readMemory, writeMemory } from "./memory-io"
2
2
  import { mergeEntries } from "../lib/quality"
3
- import { parseToonLine } from "../lib/utils"
3
+ import { parseToonLine, toToonLine } from "../lib/utils"
4
4
 
5
5
  /**
6
6
  * Jaccard similarity between two content strings (0..1).
@@ -114,3 +114,96 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
114
114
 
115
115
  return { removed: totalRemoved, kept: order.length, duplicates }
116
116
  }
117
+
118
+ /**
119
+ * Extract a (base, version) pair from a versioned key or content line.
120
+ * Matches "Use React 18", "React 18.2", "next 13.5.1", "vite ^5.0.0", etc.
121
+ * Returns null when no version number is present.
122
+ */
123
+ export function extractVersion(text: string): { base: string; version: [number, number, number] } | null {
124
+ const m = text.match(/([A-Za-z][A-Za-z0-9._-]*?)\s*(?:v)?(\d+)\.(\d+)(?:\.(\d+))?/)
125
+ if (!m) return null
126
+ const base = m[1].replace(/[-_.]+$/g, "").toLowerCase()
127
+ return { base, version: [parseInt(m[2]), parseInt(m[3]), m[4] ? parseInt(m[4]) : 0] }
128
+ }
129
+
130
+ /** Compare two [major, minor, patch] version tuples: >0, <0, or 0. */
131
+ function compareVersions(a: [number, number, number], b: [number, number, number]): number {
132
+ for (let i = 0; i < 3; i++) {
133
+ if (a[i] !== b[i]) return a[i] - b[i]
134
+ }
135
+ return 0
136
+ }
137
+
138
+ /**
139
+ * Version-supersession compaction: detect entries that describe the same
140
+ * subject with different versions (e.g. "Use React 18" vs "Use React 19")
141
+ * and mark the older ones obsolete in favor of the newest. Deterministic,
142
+ * no LLM — uses a version regex + base-name grouping.
143
+ *
144
+ * Returns the actions taken (or proposed when `dryRun`).
145
+ */
146
+ export function consolidateVersions(dryRun: boolean): { removed: number; proposals: string[]; groups: Array<{ base: string; winner: string; losers: string[] }> } {
147
+ const data = readMemory()
148
+ const lines = data.split("\n")
149
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
150
+ if (headerIdx === -1) return { removed: 0, proposals: [], groups: [] }
151
+
152
+ interface Candidate { lineIdx: number; id: string; key: string; content: string; category: string; base: string; version: [number, number, number] }
153
+ const candidates: Candidate[] = []
154
+ for (let i = headerIdx + 1; i < lines.length; i++) {
155
+ const line = lines[i]
156
+ if (!line.startsWith(" ") || !line.includes("|")) continue
157
+ if (line.startsWith(" summaries:")) break
158
+ const parts = parseToonLine(line)
159
+ if (parts.length < 7) continue
160
+ const [id, category, key, content] = parts
161
+ const hit = extractVersion(`${key} ${content}`.toLowerCase())
162
+ if (hit && key.toLowerCase().includes(hit.base)) {
163
+ candidates.push({ lineIdx: i, id, key, content, category, base: hit.base, version: hit.version })
164
+ }
165
+ }
166
+ if (candidates.length < 2) return { removed: 0, proposals: [], groups: [] }
167
+
168
+ // Group by base name.
169
+ const byBase = new Map<string, Candidate[]>()
170
+ for (const c of candidates) {
171
+ const list = byBase.get(c.base) || []
172
+ list.push(c)
173
+ byBase.set(c.base, list)
174
+ }
175
+
176
+ const groups: Array<{ base: string; winner: string; losers: string[] }> = []
177
+ for (const [base, list] of byBase) {
178
+ if (list.length < 2) continue
179
+ const sorted = [...list].sort((a, b) => compareVersions(b.version, a.version))
180
+ const winner = sorted[0]
181
+ const losers = sorted.slice(1)
182
+ if (losers.length === 0) continue
183
+ groups.push({ base, winner: winner.key, losers: losers.map((l) => l.key) })
184
+ }
185
+
186
+ if (groups.length === 0) return { removed: 0, proposals: [], groups }
187
+ if (dryRun) return { removed: 0, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups }
188
+
189
+ // Apply: mark losers obsolete with a superseded note.
190
+ const today = new Date().toISOString().split("T")[0]
191
+ let changed = 0
192
+ for (const g of groups) {
193
+ for (const loser of g.losers) {
194
+ const hit = candidates.find((c) => c.key === loser)
195
+ if (!hit) continue
196
+ const parts = parseToonLine(lines[hit.lineIdx])
197
+ while (parts.length < 18) parts.push("")
198
+ parts[9] = parts[9] ? `${parts[9]} ${g.winner}` : g.winner
199
+ parts[16] = "obsolete"
200
+ parts[17] = today
201
+ lines[hit.lineIdx] = toToonLine(parts)
202
+ changed++
203
+ }
204
+ }
205
+ if (changed === 0) return { removed: 0, proposals: [], groups }
206
+
207
+ writeMemory(lines.join("\n"))
208
+ return { removed: changed, proposals: groups.map((g) => `Replace ${g.losers.join(", ")} by ${g.winner}`), groups }
209
+ }
@@ -94,7 +94,7 @@ export function writeSessionEntry(entry: Omit<SessionEntry, "accessed" | "lastAc
94
94
  */
95
95
  export function promoteSessionEntries(
96
96
  entriesToPromote: SessionEntry[],
97
- category: "decision" | "pattern" | "bug" | "knowledge" | "architecture" = "knowledge"
97
+ category: "decision" | "pattern" | "bug" | "knowledge" | "architecture" | "warning" = "knowledge"
98
98
  ): number {
99
99
  if (entriesToPromote.length === 0) return 0
100
100