toon-memory 4.3.4 → 4.4.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
@@ -18,6 +18,8 @@ import { normalize, isExpiredLocal, tokenize, importance, importanceBoost, impor
18
18
  import { expandSynonyms } from "./synonyms"
19
19
  import { fuzzyMatch } from "./fuzzy"
20
20
  import { evidenceBoost } from "./evidence"
21
+ import { ngramScores } from "./ngrams"
22
+ import { activationScores, type ActivationEdge } from "./activation"
21
23
 
22
24
  export interface GraphEntry {
23
25
  id: string
@@ -301,6 +303,12 @@ export interface GraphRecallOpts {
301
303
  asOf?: string
302
304
  /** Reference date (YYYY-MM-DD) for recency/decay/TTL scoring. Defaults to the wall clock. */
303
305
  today?: string
306
+ utility?: Map<string, number>
307
+ edges?: ActivationEdge[]
308
+ activation?: boolean
309
+ activationDepth?: number
310
+ dense?: Map<string, number>
311
+ denseWeight?: number
304
312
  }
305
313
 
306
314
  /**
@@ -389,6 +397,30 @@ export function centrality(adjacency: Map<string, string[]>): Map<string, number
389
397
  return out
390
398
  }
391
399
 
400
+ /**
401
+ * Centrality restricted to a subset of keys, counting only edges whose
402
+ * neighbors are also inside the subset. On a small memory graph the global
403
+ * centrality of hubs dominates RRF fusion and buries relevant peripheral
404
+ * entries (a gold hit with bm25 rank 1 but global cent rank ~180 lands out of
405
+ * the top-5). Local centrality measures "hub of the candidate context" instead
406
+ * of "hub of the whole memory", which is what ranking against a query needs.
407
+ */
408
+ export function localCentrality(
409
+ adjacency: Map<string, string[]>,
410
+ keys: Iterable<string>
411
+ ): Map<string, number> {
412
+ let maxDeg = 1
413
+ const deg = new Map<string, number>()
414
+ for (const k of keys) {
415
+ const d = (adjacency.get(k) || []).length
416
+ deg.set(k, d)
417
+ if (d > maxDeg) maxDeg = d
418
+ }
419
+ const out = new Map<string, number>()
420
+ for (const [k, d] of deg) out.set(k, d / maxDeg)
421
+ return out
422
+ }
423
+
392
424
  export interface GraphRecallResult {
393
425
  /** Selected entries, ordered by final score (desc). */
394
426
  entries: GraphEntry[]
@@ -438,6 +470,9 @@ const W_IMP = 0.25
438
470
  const SEED_BONUS = 1.0
439
471
  /** Per-hop decay: a node 1 hop from a seed scores half of an equivalent seed. */
440
472
  const DECAY = 0.5
473
+ /** Minimum char n-gram cosine for an entry to seed without a lexical match.
474
+ * Tri-grams of "autotag" vs "auto tag" score ~0.7; unrelated entries < 0.3. */
475
+ export const NGRAM_SEED_MIN = 0.45
441
476
 
442
477
  /**
443
478
  * Graph-aware recall with BM25 + centrality re-ranking.
@@ -445,6 +480,31 @@ const DECAY = 0.5
445
480
  * expanded up to `hops` (1 or 2), with relevance propagated from the seeds.
446
481
  * Falls back to top-by-importance when the query matches nothing.
447
482
  */
483
+ /**
484
+ * Recompute a lightweight quality signal from the entry itself instead of
485
+ * trusting a stored number that may be months old. Pure fields only.
486
+ */
487
+ export function entryQuality(
488
+ e: GraphEntry,
489
+ today = new Date().toISOString().split("T")[0]
490
+ ): number {
491
+ let q = Math.min(0.3, e.tags.length * 0.1) + Math.min(0.2, e.links.length * 0.1)
492
+ const len = e.content.length
493
+ if (len > 20) q += 0.1
494
+ if (len > 60) q += 0.1
495
+ if (len > 150) q += 0.1
496
+ q += importance(e, today) * 0.1
497
+ q += Math.min(0.15, e.accessed * 0.03)
498
+ if (e.origin === "human") q += 0.1
499
+ else if (e.origin === "inferred") q -= 0.05
500
+ q += evidenceBoost(e.evidence)
501
+ if (e.date) {
502
+ const age = (Date.parse(`${today}T00:00:00`) - Date.parse(`${e.date}T00:00:00`)) / 86400000
503
+ if (age > 30) q -= Math.min(0.2, ((age - 30) / 90) * 0.2)
504
+ }
505
+ return Math.max(0, Math.min(1, Number(q.toFixed(3))))
506
+ }
507
+
448
508
  export function graphRecallDetailed(
449
509
  data: string,
450
510
  query: string,
@@ -462,6 +522,7 @@ export function graphRecallDetailed(
462
522
  const expandedTokens = expandSynonyms(qTokens)
463
523
  const bm25 = bm25Scores(entries, query)
464
524
  const cent = centrality(adjacency)
525
+ const ngram = ngramScores(entries, query)
465
526
 
466
527
  const seedKeys = new Set<string>()
467
528
  const asOf = opts.asOf || ""
@@ -483,7 +544,11 @@ export function graphRecallDetailed(
483
544
  const docTokens = text.split(" ")
484
545
  const exactMatch = expandedTokens.some((t) => text.includes(t))
485
546
  const fuzzy = !exactMatch && fuzzyMatch(qTokens, docTokens)
486
- if (qTokens.length > 0 && !exactMatch && !fuzzy) continue
547
+ // Morphological catch: "autotag" ≈ "auto tag", "plugin" ≈ "plugins".
548
+ // The n-gram cosine is only consulted when lexical gates miss, and a
549
+ // fraction of the BM25 max keeps weak surface matches out of the seeds.
550
+ const ngMatch = !exactMatch && !fuzzy && (ngram.get(e.key) || 0) >= NGRAM_SEED_MIN
551
+ if (qTokens.length > 0 && !exactMatch && !fuzzy && !ngMatch) continue
487
552
  seedKeys.add(e.key)
488
553
  }
489
554
 
@@ -504,10 +569,13 @@ export function graphRecallDetailed(
504
569
  const ia = importanceRank(a.importance)
505
570
  const ib = importanceRank(b.importance)
506
571
  if (ia !== ib) return ib - ia
507
- return importance(b, opts.today) - importance(a, opts.today)
572
+ return (
573
+ importance(b, opts.today) + entryQuality(b, opts.today) * 0.25 -
574
+ (importance(a, opts.today) + entryQuality(a, opts.today) * 0.25)
575
+ )
508
576
  })
509
577
  .slice(0, opts.limit ?? 6)
510
- .map((e) => ({ e, s: importance(e, opts.today) + importanceBoost(e.importance) }))
578
+ .map((e) => ({ e, s: importance(e, opts.today) + entryQuality(e, opts.today) * 0.25 + importanceBoost(e.importance) }))
511
579
  )
512
580
  } else {
513
581
  // BFS from all seeds, recording the shortest hop distance to each node.
@@ -526,42 +594,61 @@ export function graphRecallDetailed(
526
594
  }
527
595
 
528
596
  // RRF mode: fuse per-signal rankers instead of the weighted linear score.
529
- // BM25 (the only real retriever on a small memory graph) is fused three times;
530
- // centrality contributes once as the graph signal. Importance is dropped from
531
- // the fusion — on small graphs its rank is dominated by recency noise and
532
- // including it drags nDCG down (validated on scripts/bench-rrf.mjs). k is
533
- // adaptive: the textbook k=60 flattens rank differences on small graphs, so it
597
+ // Ranks are computed ONLY over the BFS candidate set (not the whole
598
+ // memory), and centrality is LOCAL to that same set — global hub
599
+ // centrality buries relevant peripheral entries (validated: a gold hit
600
+ // with bm25 rank 1 but global cent rank ~180 fell out of the top-5).
601
+ // Signals: BM25 (3×), char n-gram cosine (the morphological signal that
602
+ // catches "autotag" ≈ "auto tag"), local centrality (1×). k is adaptive:
603
+ // the textbook k=60 flattens rank differences on small graphs, so it
534
604
  // scales with sqrt(candidate count).
535
- const sub = (m: Map<string, number>) => new Map([...m].filter(([k]) => isVisible.has(k)))
605
+ const cand = new Set(best.keys())
606
+ const sub = (m: Map<string, number>) => new Map([...m].filter(([k]) => cand.has(k)))
607
+ const localCent = localCentrality(adjacency, cand)
536
608
  const bm25Rank = rankBy(sub(bm25))
537
- const centRank = rankBy(sub(cent))
538
- const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null
539
-
609
+ const ngRank = rankBy(sub(ngram))
610
+ const centRank = rankBy(sub(localCent))
611
+ const fused = opts.rrf
612
+ ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, ngRank, centRank], rrfK(bm25Rank.size))
613
+ : null
614
+
615
+ const base = [...best.keys()].map((k) => {
616
+ const e = byKey.get(k)!
617
+ const dist = best.get(k)!
618
+ const decay = Math.pow(DECAY, dist)
619
+ let s = fused
620
+ ? fused.get(k) || 0
621
+ : (bm25.get(k) || 0) + W_CENT * (cent.get(k) || 0) + W_IMP * importance(e, opts.today)
622
+ if (!fused && seedKeys.has(k)) s += SEED_BONUS
623
+ if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
624
+ const entryFile = e.file.split(":")[0]
625
+ if (opts.sessionFiles.some((f) => f === entryFile)) {
626
+ s *= 1.15
627
+ }
628
+ }
629
+ // Negative-memory boost: warnings surface first.
630
+ if (e.category === "warning") s += 0.2
631
+ // Explicit importance boost: critical/high entries surface first, low last.
632
+ s += importanceBoost(e.importance)
633
+ // Evidence bias: conflicts surface for review, verified is grounded, unverified sinks.
634
+ s += evidenceBoost(e.evidence)
635
+ // Recomputed quality keeps stale stored fields from dominating old entries.
636
+ s += entryQuality(e, opts.today) * 0.08
637
+ if (opts.utility) s += (opts.utility.get(k) || 0) * 0.25
638
+ if (opts.dense) s += (opts.dense.get(k) || 0) * (opts.denseWeight ?? 0.25)
639
+ s *= decay
640
+ return { e, s, priority: e.priority }
641
+ })
642
+ if (opts.activation && opts.edges && base.length > 0) {
643
+ const seeds = [...base]
644
+ .sort((a, b) => b.s - a.s)
645
+ .slice(0, 5)
646
+ .map((x) => x.e.key)
647
+ const activated = activationScores(opts.edges, seeds, opts.activationDepth ?? 1)
648
+ for (const x of base) x.s += (activated.get(x.e.key) || 0) * 0.1
649
+ }
540
650
  scored.push(
541
- ...[...best.keys()]
542
- .map((k) => {
543
- const e = byKey.get(k)!
544
- const dist = best.get(k)!
545
- const decay = Math.pow(DECAY, dist)
546
- let s = fused
547
- ? fused.get(k) || 0
548
- : (bm25.get(k) || 0) + W_CENT * (cent.get(k) || 0) + W_IMP * importance(e, opts.today)
549
- if (!fused && seedKeys.has(k)) s += SEED_BONUS
550
- if (opts.sessionFiles && opts.sessionFiles.length > 0 && e.file) {
551
- const entryFile = e.file.split(":")[0]
552
- if (opts.sessionFiles.some((f) => f === entryFile)) {
553
- s *= 1.15
554
- }
555
- }
556
- // Negative-memory boost: warnings surface first.
557
- if (e.category === "warning") s += 0.2
558
- // Explicit importance boost: critical/high entries surface first, low last.
559
- s += importanceBoost(e.importance)
560
- // Evidence bias: conflicts surface for review, verified is grounded, unverified sinks.
561
- s += evidenceBoost(e.evidence)
562
- s *= decay
563
- return { e, s, priority: e.priority }
564
- })
651
+ ...base
565
652
  .sort((a, b) => {
566
653
  if (a.priority !== b.priority) return b.priority - a.priority
567
654
  return b.s - a.s
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Compact handoff brief: the packet injected at session start instead of a
3
+ * full memory dump. Deterministic, zero-dep, no LLM.
4
+ *
5
+ * Unlike a search result, a handoff carries enough state to keep the agent
6
+ * from re-investigating: cross-tool identity, freshness, hard directives,
7
+ * known traps and file pointers.
8
+ */
9
+
10
+ import { basename } from "path"
11
+ import { parseEntries, type GraphEntry } from "./graph"
12
+ import { estimateTokens, isExpiredLocal, isPrivate } from "./utils"
13
+
14
+ export interface HandoffOpts {
15
+ /** Focus area; biases "recent" selection toward matching entries. */
16
+ task?: string
17
+ /** Hard token ceiling for the whole brief. Default 420. */
18
+ maxTokens?: number
19
+ /** Today, injectable for deterministic tests. */
20
+ today?: string
21
+ }
22
+
23
+ /** Slug used by codebase-memory-mcp and other path-derived project registries. */
24
+ export function projectSlug(root: string): string {
25
+ return root
26
+ .replace(/^[\\/]+/, "")
27
+ .replace(/[^a-z0-9]+/gi, "-")
28
+ .replace(/^-+|-+$/g, "")
29
+ .toLowerCase()
30
+ }
31
+
32
+ export function entryAgeDays(date: string, today: string): number {
33
+ if (!date) return 0
34
+ const then = Date.parse(`${date}T00:00:00`)
35
+ const now = Date.parse(`${today}T00:00:00`)
36
+ if (!Number.isFinite(then) || !Number.isFinite(now)) return 0
37
+ return Math.max(0, Math.round((now - then) / 86400000))
38
+ }
39
+
40
+ /** First sentence, clipped at a word boundary. Never ends in an ellipsis. */
41
+ function claim(e: GraphEntry, maxChars = 130): string {
42
+ const text = e.content.replace(/\s+/g, " ").trim()
43
+ if (!text) return e.key
44
+ const sentence = text.match(/^[^.!?]+[.!?]?/)?.[0] || text
45
+ if (sentence.length <= maxChars) return sentence.trim()
46
+ const cut = sentence.slice(0, maxChars).replace(/\s+\S*$/, "")
47
+ return `${cut} · ver ${e.key}`
48
+ }
49
+
50
+ function matches(e: GraphEntry, task: string): boolean {
51
+ const q = task.toLowerCase()
52
+ if (!q) return false
53
+ const text = `${e.key} ${e.content} ${e.tags.join(" ")} ${e.file}`.toLowerCase()
54
+ return q.split(/\s+/).filter((t) => t.length > 3).some((t) => text.includes(t))
55
+ }
56
+
57
+ /**
58
+ * Build the handoff brief from raw TOON memory data.
59
+ */
60
+ export function buildHandoffBrief(data: string, root: string, opts: HandoffOpts = {}): string {
61
+ const today = opts.today || new Date().toISOString().split("T")[0]
62
+ const maxTokens = opts.maxTokens ?? 420
63
+ const task = opts.task || ""
64
+
65
+ const usable = parseEntries(data).filter(
66
+ (e) =>
67
+ e.status !== "obsolete" &&
68
+ e.status !== "draft" &&
69
+ !isPrivate(e) &&
70
+ !(e.ttl && isExpiredLocal(e.ttl, today))
71
+ )
72
+
73
+ const newest = usable.reduce((acc, e) => (e.date > acc ? e.date : acc), "")
74
+ const age = entryAgeDays(newest, today)
75
+ const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh"
76
+
77
+ const head = [
78
+ `<memory project="${basename(root) || root}" as_of="${today}" freshness="${freshness}">`,
79
+ `identity: mcp_project=${projectSlug(root)} | root=${root}`,
80
+ ]
81
+
82
+ const used = new Set<string>()
83
+ const take = (list: GraphEntry[]): GraphEntry[] => {
84
+ const out: GraphEntry[] = []
85
+ for (const e of list) {
86
+ if (used.has(e.key)) continue
87
+ used.add(e.key)
88
+ out.push(e)
89
+ }
90
+ return out
91
+ }
92
+ const byDate = (a: GraphEntry, b: GraphEntry) => b.date.localeCompare(a.date)
93
+ const line = (section: string, e: GraphEntry): string => {
94
+ const stale = entryAgeDays(e.date, today) > 30 ? ` [stale ${entryAgeDays(e.date, today)}d]` : ""
95
+ const file = e.file ? ` @ ${e.file}` : ""
96
+ return `${section} [${e.category}] ${e.key}: ${claim(e)}${file}${stale}`
97
+ }
98
+
99
+ const traps = take(
100
+ usable
101
+ .filter(
102
+ (e) =>
103
+ e.category === "warning" ||
104
+ e.tags.some((t) => ["trap", "gotcha", "risk", "warning"].includes(t.toLowerCase()))
105
+ )
106
+ .sort(byDate)
107
+ .slice(0, 2)
108
+ )
109
+ const directives = take(
110
+ usable
111
+ .filter((e) => e.origin === "human" || e.importance === "critical")
112
+ .sort((a, b) => b.priority - a.priority || byDate(a, b))
113
+ .slice(0, 2)
114
+ )
115
+ const open = take(usable.filter((e) => e.category === "decision").sort(byDate).slice(0, 3))
116
+ const recent = take(
117
+ [...usable].sort((a, b) => {
118
+ const tm = Number(matches(b, task)) - Number(matches(a, task))
119
+ return tm || byDate(a, b)
120
+ }).slice(0, 3)
121
+ )
122
+ const files = usable.filter((e) => e.file).sort(byDate).slice(0, 3)
123
+
124
+ const sections: string[] = []
125
+ const push = (title: string, rows: string[]) => {
126
+ if (rows.length > 0) sections.push(`${title}\n${rows.join("\n")}`)
127
+ }
128
+ push("directives:", directives.map((e) => line("-", e)))
129
+ push("traps:", traps.map((e) => line("-", e)))
130
+ push("open:", open.map((e) => line("-", e)))
131
+ push("recent:", recent.map((e) => line("-", e)))
132
+ if (files.length > 0) {
133
+ push("files:", files.map((e) => `- ${e.file}${e.key ? ` ← ${e.key}` : ""}`))
134
+ }
135
+
136
+ const out = [...head]
137
+ for (const section of sections) {
138
+ if (estimateTokens(out.join("\n") + "\n" + section) > maxTokens) break
139
+ out.push(section)
140
+ }
141
+ if (out.length === 2) out.push("(no stable memories yet)")
142
+ out.push("</memory>")
143
+ return out.join("\n")
144
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Deterministic character n-gram "embedding-lite" for toon-memory.
3
+ *
4
+ * No model, no weights, no network: hashes character n-grams (tri-grams by
5
+ * default) of a text into a sparse 32-bit hash set, then measures overlap via
6
+ * cosine. Captures exactly the lexical variation that token-level BM25 misses:
7
+ * - morphology: "autotag" ≈ "auto tag" (shared tri-grams)
8
+ * - plurals: "plugin" ≈ "plugins"
9
+ * - derivations: "serialize" ≈ "serialization"
10
+ *
11
+ * Deterministic: FNV-1a is a fixed hash, so the same text always yields the
12
+ * same vector. Offline: zero deps, zero model files. The whole module is
13
+ * ~80 lines of pure JS.
14
+ */
15
+
16
+ /** FNV-1a 32-bit hash. Deterministic, single pass, no collisions in practice
17
+ * for the tens-to-hundreds of n-grams per text we hash. */
18
+ export function fnv1a32(s: string): number {
19
+ let h = 0x811c9dc5
20
+ for (let i = 0; i < s.length; i++) {
21
+ h ^= s.charCodeAt(i)
22
+ h = (h * 0x01000193) >>> 0
23
+ }
24
+ return h >>> 0
25
+ }
26
+
27
+ /**
28
+ * Hash set of the character n-grams of a text.
29
+ *
30
+ * The text is split on whitespace and every token is padded with `^`/`$`
31
+ * sentinels so boundary tri-grams (prefixes/suffixes) are captured:
32
+ * "auto" → ^au aut uto o$, which overlaps heavily with "autotag".
33
+ */
34
+ export function ngramHashes(text: string, n = 3): Set<number> {
35
+ const out = new Set<number>()
36
+ const tokens = text.split(/\s+/)
37
+ for (const token of tokens) {
38
+ if (!token) continue
39
+ const padded = "^" + token + "$"
40
+ for (let i = 0; i + n <= padded.length; i++) {
41
+ out.add(fnv1a32(padded.slice(i, i + n)))
42
+ }
43
+ }
44
+ return out
45
+ }
46
+
47
+ /** Cosine similarity between two n-gram hash sets. 0 when either is empty. */
48
+ export function ngramCosine(a: Set<number>, b: Set<number>): number {
49
+ if (a.size === 0 || b.size === 0) return 0
50
+ let inter = 0
51
+ const [small, large] = a.size <= b.size ? [a, b] : [b, a]
52
+ for (const h of small) if (large.has(h)) inter++
53
+ return inter / Math.sqrt(a.size * b.size)
54
+ }
55
+
56
+ /** Per-entry n-gram cosine vs the query. Returns key → 0..1. */
57
+ export function ngramScores(
58
+ entries: Array<{ key: string; id: string; category: string; content: string; file: string; tags: string[]; path_scope?: string }>,
59
+ query: string
60
+ ): Map<string, number> {
61
+ const qHashes = ngramHashes(query)
62
+ const out = new Map<string, number>()
63
+ for (const e of entries) {
64
+ const text = `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")} ${e.path_scope || ""}`
65
+ out.set(e.key, ngramCosine(qHashes, ngramHashes(text)))
66
+ }
67
+ return out
68
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Deterministic promoter: turns captured signals into durable memory entries.
3
+ * No LLM, no network. High bar on purpose — low-confidence signals stay in
4
+ * session.toon as a log instead of polluting data.toon.
5
+ */
6
+
7
+ import { parseEntries } from "./graph"
8
+ import { toToonLine, escField } from "./utils"
9
+
10
+ export type SignalType = "user_directive" | "error_fix" | "decision" | "diff_pattern" | "checkpoint"
11
+
12
+ export interface Signal {
13
+ type: string
14
+ summary: string
15
+ file: string
16
+ session: string
17
+ ts: string
18
+ }
19
+
20
+ export interface ScoredSignal {
21
+ signal: Signal
22
+ score: number
23
+ category: "decision" | "pattern" | "bug" | "knowledge" | "warning"
24
+ tags: string
25
+ origin: "human" | "agent" | "inferred"
26
+ importance: string
27
+ evidence: string
28
+ }
29
+
30
+ export const PROMOTE_THRESHOLD = 0.75
31
+
32
+ const DIRECTIVE = /recuerda|siempre|nunca|no hagas|importante|ten cuidado|decidimos|must not|always|never/i
33
+ const FIX = /fix|fixed|error|fallo|bug|verified|pas(o|ó|ed)|green/i
34
+ const DECISION = /decidimos|elegimos|optamos|rechazamos|commit|merge|pr\b/i
35
+
36
+ function slug(text: string): string {
37
+ return text
38
+ .toLowerCase()
39
+ .replace(/[^a-z0-9áéíóúñü]+/g, "-")
40
+ .replace(/^-+|-+$/g, "")
41
+ .slice(0, 48) || "signal"
42
+ }
43
+
44
+ export function scoreSignal(signal: Signal): ScoredSignal {
45
+ const text = `${signal.summary} ${signal.file}`
46
+ const type = signal.type.replace(/:$/, "")
47
+ const hasFile = Boolean(signal.file)
48
+ const lengthOk = signal.summary.length >= 40 && signal.summary.length <= 300
49
+ let score = 0.2
50
+ let category: ScoredSignal["category"] = "knowledge"
51
+ let tags = "auto-captured"
52
+ let origin: ScoredSignal["origin"] = "inferred"
53
+ let importance = ""
54
+ let evidence = "unverified"
55
+
56
+ if (type === "user_directive" || DIRECTIVE.test(text)) {
57
+ category = "warning"
58
+ origin = "human"
59
+ importance = "high"
60
+ tags = "auto-captured;directive"
61
+ score = 0.85
62
+ } else if (type === "error_fix" || FIX.test(text)) {
63
+ category = "bug"
64
+ tags = "auto-captured;error-fix"
65
+ score = 0.6
66
+ if (hasFile && FIX.test(text)) evidence = "verified"
67
+ } else if (type === "decision" || DECISION.test(text)) {
68
+ category = "decision"
69
+ tags = "auto-captured;decision"
70
+ score = 0.58
71
+ } else if (type === "diff_pattern") {
72
+ category = "pattern"
73
+ tags = "auto-captured;pattern"
74
+ score = 0.45
75
+ } else if (type === "checkpoint") {
76
+ tags = "auto-captured;checkpoint"
77
+ score = 0.4
78
+ }
79
+
80
+ if (lengthOk) score += 0.08
81
+ if (hasFile) score += 0.04
82
+ if (origin === "human") score += 0.04
83
+ if (evidence === "verified") score += 0.06
84
+
85
+ return { signal, score: Math.min(1, Number(score.toFixed(2))), category, tags, origin, importance, evidence }
86
+ }
87
+
88
+ export interface PromotionResult {
89
+ data: string
90
+ promoted: Array<{ key: string; category: string; score: number }>
91
+ kept: number
92
+ }
93
+
94
+ /**
95
+ * Append every signal at/above `threshold` to raw TOON memory data.
96
+ * Existing keys win (no overwrite); count in the header stays consistent.
97
+ */
98
+ export function promoteSignals(data: string, signals: Signal[], opts: { threshold?: number; today?: string } = {}): PromotionResult {
99
+ const threshold = opts.threshold ?? PROMOTE_THRESHOLD
100
+ const today = opts.today || new Date().toISOString().split("T")[0]
101
+ const lines = data.split("\n")
102
+ let headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
103
+ if (headerIdx === -1) {
104
+ lines.push("[0|]")
105
+ headerIdx = lines.length - 1
106
+ }
107
+
108
+ const known = new Set(parseEntries(data).map((e) => e.key))
109
+ const promoted: PromotionResult["promoted"] = []
110
+ let kept = 0
111
+
112
+ for (const raw of signals) {
113
+ const signal = { ...raw, summary: (raw.summary || "").replace(/\s+/g, " ").trim() }
114
+ const scored = scoreSignal(signal)
115
+ if (scored.score < threshold || !signal.summary) {
116
+ kept++
117
+ continue
118
+ }
119
+ const key = `${scored.category}-${slug(signal.summary)}`
120
+ if (known.has(key)) {
121
+ kept++
122
+ continue
123
+ }
124
+ known.add(key)
125
+ const id = `sig-${Date.now().toString(36)}-${promoted.length.toString(36)}`
126
+ const line = toToonLine([
127
+ id, scored.category, key, escField(signal.summary), escField(signal.file || ""),
128
+ scored.tags, today, "", "0", "", "0.85", "1.0", today, "0", "",
129
+ scored.origin, "active", "", scored.importance, scored.evidence,
130
+ ])
131
+ lines.splice(headerIdx + 1, 0, line)
132
+ promoted.push({ key, category: scored.category, score: scored.score })
133
+ }
134
+
135
+ const match = lines[headerIdx].match(/\[(\d+)\|/)
136
+ const count = match ? parseInt(match[1]) : 0
137
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + promoted.length}|`)
138
+
139
+ return { data: lines.join("\n"), promoted, kept }
140
+ }
@@ -12,18 +12,21 @@ import {
12
12
  buildGraph,
13
13
  bm25Scores,
14
14
  centrality,
15
+ localCentrality,
15
16
  renderCompact,
16
17
  rankBy,
17
18
  rrfFuse,
18
19
  rrfK,
19
20
  globMatch,
20
21
  buildReason,
22
+ NGRAM_SEED_MIN,
21
23
  type GraphEntry,
22
24
  } from "./graph"
23
25
  import { normalize, isExpiredLocal, tokenize, importance, importanceBoost, importanceRank, isPrivate, estimateTokens, languageFamily, parseToonLine, toToonLine } from "./utils"
24
26
  import { expandSynonyms } from "./synonyms"
25
27
  import { fuzzyMatch } from "./fuzzy"
26
28
  import { evidenceBoost } from "./evidence"
29
+ import { ngramScores } from "./ngrams"
27
30
 
28
31
  /**
29
32
  * Quality score for an entry (0..1). Pure heuristics, no LLM.
@@ -213,6 +216,7 @@ export function generateSmartRecall(
213
216
  today?: string
214
217
  explain?: boolean
215
218
  budgetTokens?: number
219
+ utility?: Map<string, number>
216
220
  } = {}
217
221
  ): string {
218
222
  const entries = parseEntries(data)
@@ -221,6 +225,7 @@ export function generateSmartRecall(
221
225
  const { adjacency } = buildGraph(entries)
222
226
  const bm25 = bm25Scores(entries, intent)
223
227
  const cent = centrality(adjacency)
228
+ const ngram = ngramScores(entries, intent)
224
229
  const limit = opts.limit ?? 8
225
230
  const category = opts.category || ""
226
231
  const mtimes = opts.fileMtimes
@@ -236,14 +241,19 @@ export function generateSmartRecall(
236
241
  })
237
242
 
238
243
  // RRF mode: fuse per-signal rankers instead of the weighted linear score.
239
- // BM25 (the only real retriever on a small memory graph) is fused three times;
240
- // centrality contributes once as the graph signal. Importance is dropped from the
241
- // fusion (recency-dominated noise on small graphs; validated on scripts/bench-rrf.mjs).
242
- // k is adaptive (sqrt of candidate count) — the textbook k=60 flattens rank
244
+ // Ranks are computed ONLY over the eligible set (not the whole memory), and
245
+ // centrality is LOCAL to that same set — global hub centrality buries
246
+ // relevant peripheral entries. Signals: BM25 (3×), char n-gram cosine
247
+ // (morphology: "autotag" ≈ "auto tag"), local centrality (1×). k is
248
+ // adaptive (sqrt of candidate count) — the textbook k=60 flattens rank
243
249
  // differences on small memory graphs.
244
- const bm25Rank = rankBy(new Map([...bm25].filter(([k]) => eligible.some((e) => e.key === k))))
245
- const centRank = rankBy(new Map([...cent].filter(([k]) => eligible.some((e) => e.key === k))))
246
- const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, centRank], rrfK(bm25Rank.size)) : null
250
+ const eligibleKeys = new Set(eligible.map((e) => e.key))
251
+ const sub = (m: Map<string, number>) => new Map([...m].filter(([k]) => eligibleKeys.has(k)))
252
+ const localCent = localCentrality(adjacency, eligibleKeys)
253
+ const bm25Rank = rankBy(sub(bm25))
254
+ const ngRank = rankBy(sub(ngram))
255
+ const centRank = rankBy(sub(localCent))
256
+ const fused = opts.rrf ? rrfFuse([bm25Rank, bm25Rank, bm25Rank, ngRank, centRank], rrfK(bm25Rank.size)) : null
247
257
 
248
258
  const scored = eligible
249
259
  .map((e) => {
@@ -253,7 +263,8 @@ export function generateSmartRecall(
253
263
  const docTokens = text.split(" ")
254
264
  const exactMatch = qTokens.length === 0 || expandedTokens.some((t) => text.includes(t))
255
265
  const fuzzy = !exactMatch && qTokens.length > 0 && fuzzyMatch(qTokens, docTokens)
256
- const matchesQuery = exactMatch || fuzzy
266
+ const ngMatch = !exactMatch && !fuzzy && (ngram.get(e.key) || 0) >= NGRAM_SEED_MIN
267
+ const matchesQuery = exactMatch || fuzzy || ngMatch
257
268
  const bm25Score = bm25.get(e.key) || 0
258
269
  const centScore = cent.get(e.key) || 0
259
270
  const impScore = importance(e, opts.today)
@@ -289,12 +300,16 @@ export function generateSmartRecall(
289
300
  const impBoost = importanceBoost(e.importance)
290
301
  // Evidence bias: conflicts surface for review, verified is grounded, unverified sinks.
291
302
  const evBoost = evidenceBoost(e.evidence)
303
+ // Morphological catch: "autotag" ≈ "auto tag", "plugin" ≈ "plugins".
304
+ const ngScore = ngram.get(e.key) || 0
305
+ const ngBoost = ngMatch ? ngScore * 0.15 : 0
292
306
  let combined: number
307
+ const utilityBoost = (opts.utility?.get(e.key) || 0) * 0.25
293
308
  if (opts.rrf) {
294
- combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost
309
+ combined = (fused?.get(e.key) ?? 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + ngBoost + utilityBoost
295
310
  } else {
296
311
  combined =
297
- bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost
312
+ bm25Score + 0.3 * centScore + 0.3 * impScore + (matchesQuery ? 0.5 : 0) - drift + sessionBias + langBoost + folderBoost + warningBoost + impBoost + evBoost + utilityBoost
298
313
  }
299
314
  return { entry: e, score: combined, matchesQuery, priority: e.priority, bm25Score }
300
315
  })