toon-memory 4.3.5 → 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.
@@ -0,0 +1,45 @@
1
+ import { loadConfig } from "../mcp/config"
2
+ import { readMemory, writeMemory } from "../mcp/memory-io"
3
+ import { readObservations, pruneObservations } from "../mcp/observations"
4
+ import { promoteSignals, type Signal } from "../lib/promoter"
5
+ import { readFeedback } from "../mcp/feedback"
6
+ import { rebuildEdges } from "../mcp/edges"
7
+ import { pruneExpiredEntries } from "../mcp/archive"
8
+ import { consolidateEntries } from "../mcp/consolidation"
9
+
10
+ export interface SleepResult {
11
+ ran: boolean
12
+ promoted: number
13
+ edges: number
14
+ pruned: number
15
+ duplicates: number
16
+ }
17
+
18
+ export function runSleep(): SleepResult {
19
+ const config = loadConfig()
20
+ if (!config.sleep?.enabled && process.env.TOON_MEMORY_SLEEP !== "1") {
21
+ return { ran: false, promoted: 0, edges: 0, pruned: 0, duplicates: 0 }
22
+ }
23
+
24
+ const signals: Signal[] = readObservations().map((o) => ({
25
+ type: o.tool,
26
+ summary: o.summary,
27
+ file: o.file,
28
+ session: o.session,
29
+ ts: o.ts,
30
+ }))
31
+ const promotedResult = promoteSignals(readMemory(), signals, {})
32
+ if (promotedResult.promoted.length > 0) writeMemory(promotedResult.data)
33
+
34
+ const edges = rebuildEdges(readMemory(), readFeedback())
35
+ const pruned = pruneExpiredEntries() + pruneObservations()
36
+ const duplicates = consolidateEntries().removed
37
+
38
+ return {
39
+ ran: true,
40
+ promoted: promotedResult.promoted.length,
41
+ edges,
42
+ pruned,
43
+ duplicates,
44
+ }
45
+ }
@@ -0,0 +1,32 @@
1
+ export interface ActivationEdge {
2
+ from: string
3
+ to: string
4
+ type: string
5
+ weight: number
6
+ }
7
+
8
+ export function activationScores(
9
+ edges: ActivationEdge[],
10
+ seeds: string[],
11
+ depth = 1
12
+ ): Map<string, number> {
13
+ const out = new Map<string, number>()
14
+ let frontier = [...new Set(seeds)]
15
+ for (let d = 0; d < Math.max(0, depth); d++) {
16
+ const next: string[] = []
17
+ for (const node of frontier) {
18
+ for (const edge of edges) {
19
+ let other = ""
20
+ if (edge.from === node) other = edge.to
21
+ else if (edge.to === node) other = edge.from
22
+ if (!other || other === node || seeds.includes(other)) continue
23
+ const kind = edge.type === "supports" || edge.type === "used_in" ? 1 : edge.type === "contradicts" ? 0.6 : 0.8
24
+ const gain = edge.weight * kind * Math.pow(0.5, d)
25
+ out.set(other, (out.get(other) || 0) + gain)
26
+ next.push(other)
27
+ }
28
+ }
29
+ frontier = [...new Set(next)]
30
+ }
31
+ return out
32
+ }
@@ -0,0 +1,178 @@
1
+ import { basename } from "path"
2
+ import { graphRecallDetailed, parseEntries, type GraphEntry } from "./graph"
3
+ import { estimateTokens, isExpiredLocal, isPrivate, tokenize } from "./utils"
4
+ import { entryAgeDays, projectSlug } from "./handoff"
5
+ import type { ActivationEdge } from "./activation"
6
+
7
+ export interface ContextSection {
8
+ title: string
9
+ lines: string[]
10
+ }
11
+
12
+ export interface ContextPackage {
13
+ task: string
14
+ asOf: string
15
+ freshness: string
16
+ project: string
17
+ slug: string
18
+ root: string
19
+ sections: ContextSection[]
20
+ queries: string[]
21
+ hydrate: string[]
22
+ usedTokens: number
23
+ }
24
+
25
+ export interface CompileOpts {
26
+ root?: string
27
+ today?: string
28
+ maxTokens?: number
29
+ utility?: Map<string, number>
30
+ edges?: ActivationEdge[]
31
+ activation?: boolean
32
+ dense?: Map<string, number>
33
+ sessions?: string[]
34
+ }
35
+
36
+ function claim(e: GraphEntry, maxChars = 120): string {
37
+ const text = e.content.replace(/\s+/g, " ").trim()
38
+ if (!text) return e.key
39
+ const sentence = text.match(/^[^.!?]+[.!?]?/)?.[0] || text
40
+ if (sentence.length <= maxChars) return sentence.trim()
41
+ return `${sentence.slice(0, maxChars).replace(/\s+\S*$/, "")} · ${e.key}`
42
+ }
43
+
44
+ function line(e: GraphEntry, today: string): string {
45
+ const age = entryAgeDays(e.date, today)
46
+ const stale = age > 30 ? ` [stale ${age}d]` : ""
47
+ const file = e.file ? ` @ ${e.file}` : ""
48
+ return `- [${e.category}] ${e.key}: ${claim(e)}${file}${stale}`
49
+ }
50
+
51
+ export function compileContext(data: string, task: string, opts: CompileOpts = {}): ContextPackage {
52
+ const today = opts.today || new Date().toISOString().split("T")[0]
53
+ const root = opts.root || process.cwd()
54
+ const maxTokens = opts.maxTokens ?? 900
55
+ const usable = parseEntries(data).filter(
56
+ (e) =>
57
+ e.status !== "obsolete" &&
58
+ e.status !== "draft" &&
59
+ !isPrivate(e) &&
60
+ !(e.ttl && isExpiredLocal(e.ttl, today))
61
+ )
62
+
63
+ const newest = usable.reduce((acc, e) => (e.date > acc ? e.date : acc), "")
64
+ const age = entryAgeDays(newest, today)
65
+ const freshness = !newest ? "empty" : age > 30 ? `stale-${age}d` : "fresh"
66
+
67
+ const graphRanked = graphRecallDetailed(data, task, {
68
+ limit: 12,
69
+ utility: opts.utility,
70
+ edges: opts.edges,
71
+ activation: opts.activation,
72
+ dense: opts.dense,
73
+ }).entries
74
+ const utilitySeeds = [...(opts.utility?.entries() || [])]
75
+ .filter(([, value]) => value > 0)
76
+ .sort((a, b) => b[1] - a[1])
77
+ .map(([key]) => key)
78
+ const utilityEntries = utilitySeeds
79
+ .map((key) => usable.find((e) => e.key === key))
80
+ .filter((e): e is GraphEntry => Boolean(e))
81
+ const ranked = [...utilityEntries, ...graphRanked.filter((e) => !utilitySeeds.includes(e.key))]
82
+ const seen = new Set<string>()
83
+ const take = (list: GraphEntry[]): GraphEntry[] => {
84
+ const out: GraphEntry[] = []
85
+ for (const e of list) {
86
+ if (seen.has(e.key)) continue
87
+ seen.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
+
94
+ const directives = take(
95
+ usable
96
+ .filter(
97
+ (e) =>
98
+ (e.origin === "human" || e.importance === "critical" || e.priority > 0) &&
99
+ e.category !== "warning" &&
100
+ e.evidence !== "conflict"
101
+ )
102
+ .sort((a, b) => b.priority - a.priority || byDate(a, b))
103
+ .slice(0, 3)
104
+ )
105
+ const constraints = take(
106
+ usable
107
+ .filter(
108
+ (e) =>
109
+ e.category === "warning" ||
110
+ e.evidence === "conflict" ||
111
+ e.tags.some((t) => ["trap", "gotcha", "risk", "warning", "outdated"].includes(t.toLowerCase()))
112
+ )
113
+ .sort(byDate)
114
+ .slice(0, 2)
115
+ )
116
+ const memory = take(ranked.slice(0, 5))
117
+ const decisions = take(ranked.filter((e) => e.category === "decision").slice(0, 2))
118
+
119
+ const tokens = tokenize(task).slice(0, 4)
120
+ const queries: string[] = []
121
+ if (task.trim()) queries.push(task.trim().slice(0, 140))
122
+ if (tokens.length >= 2) queries.push(`${tokens[0]} ${tokens[1]}`)
123
+ if (memory.length > 0 && tokens.length > 0) queries.push(`${memory[0].key} ${tokens[0]}`)
124
+ const queriesOut = [...new Set(queries)].slice(0, 3)
125
+
126
+ const hydrate = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.key))].slice(0, 8)
127
+ const files = [...new Set([...directives, ...constraints, ...memory, ...decisions].map((e) => e.file).filter(Boolean))].slice(0, 4)
128
+ const sessionLines = (opts.sessions || []).slice(0, 2).map((s) => `- ${s}`)
129
+
130
+ const sections: ContextSection[] = [
131
+ { title: "Directives", lines: directives.map((e) => line(e, today)) },
132
+ { title: "Constraints", lines: constraints.map((e) => line(e, today)) },
133
+ { title: "Memory", lines: memory.map((e) => line(e, today)) },
134
+ { title: "Decisions", lines: decisions.map((e) => line(e, today)) },
135
+ { title: "Retrieval", lines: queriesOut.map((q) => `- query: ${q}`) },
136
+ { title: "Hydrate", lines: hydrate.length ? hydrate.map((k) => `- ${k}`) : ["- (none)"] },
137
+ { title: "Files", lines: files.map((f) => `- ${f}`) },
138
+ { title: "Sessions", lines: sessionLines.length ? sessionLines : ["- (none)"] },
139
+ ].filter((s) => s.lines.length > 0)
140
+
141
+ const pkg: ContextPackage = {
142
+ task,
143
+ asOf: today,
144
+ freshness,
145
+ project: basename(root) || root,
146
+ slug: projectSlug(root),
147
+ root,
148
+ sections: [],
149
+ queries: queriesOut,
150
+ hydrate,
151
+ usedTokens: 0,
152
+ }
153
+
154
+ let used = estimateTokens(
155
+ `<memory project="${pkg.project}" as_of="${today}" freshness="${freshness}">\nidentity: mcp_project=${pkg.slug} | root=${root}\n</memory>`
156
+ )
157
+ for (const section of sections) {
158
+ const block = `${section.title}\n${section.lines.join("\n")}`
159
+ const cost = estimateTokens(`\n${block}`)
160
+ if (used + cost > maxTokens) continue
161
+ used += cost
162
+ pkg.sections.push(section)
163
+ }
164
+ pkg.usedTokens = used
165
+ return pkg
166
+ }
167
+
168
+ export function renderContextPackage(pkg: ContextPackage): string {
169
+ const task = pkg.task.replace(/"/g, "&quot;").slice(0, 140)
170
+ const out = [
171
+ `<memory project="${pkg.project}" as_of="${pkg.asOf}" freshness="${pkg.freshness}" task="${task}">`,
172
+ `identity: mcp_project=${pkg.slug} | root=${pkg.root}`,
173
+ ]
174
+ for (const section of pkg.sections) out.push(`${section.title}\n${section.lines.join("\n")}`)
175
+ if (pkg.sections.length === 0) out.push("(no stable memories yet)")
176
+ out.push("</memory>")
177
+ return out.join("\n")
178
+ }
@@ -0,0 +1,123 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"
2
+ import { dirname } from "path"
3
+ import { parseEntries } from "../lib/graph"
4
+ import { loadConfig, VECTORS_FILE } from "../mcp/config"
5
+ import { withLockSync } from "../lib/lock"
6
+
7
+ export interface DenseModule {
8
+ embed(texts: string[], model?: string): Promise<number[][]>
9
+ }
10
+
11
+ export interface StoredVectors {
12
+ dim: number
13
+ vectors: Map<string, number[]>
14
+ }
15
+
16
+ export async function loadDenseModule(): Promise<DenseModule | null> {
17
+ const spec = process.env.TOON_MEMORY_DENSE_MODULE || "toon-memory-dense"
18
+ try {
19
+ const mod: any = await import(spec)
20
+ const embed = mod?.embed || mod?.default?.embed || mod?.default
21
+ return typeof embed === "function" ? { embed } : null
22
+ } catch {
23
+ return null
24
+ }
25
+ }
26
+
27
+ export function cosine(a: number[], b: number[]): number {
28
+ const n = Math.min(a.length, b.length)
29
+ if (n === 0) return 0
30
+ let dot = 0
31
+ let na = 0
32
+ let nb = 0
33
+ for (let i = 0; i < n; i++) {
34
+ dot += a[i] * b[i]
35
+ na += a[i] * a[i]
36
+ nb += b[i] * b[i]
37
+ }
38
+ if (na === 0 || nb === 0) return 0
39
+ const value = dot / (Math.sqrt(na) * Math.sqrt(nb))
40
+ return Number.isFinite(value) ? value : 0
41
+ }
42
+
43
+ export function readVectors(): StoredVectors {
44
+ const empty = { dim: 0, vectors: new Map<string, number[]>() }
45
+ if (!existsSync(VECTORS_FILE)) return empty
46
+ try {
47
+ const buf = readFileSync(VECTORS_FILE)
48
+ const newline = buf.indexOf(0x0a)
49
+ if (newline === -1) return empty
50
+ const match = buf.subarray(0, newline).toString("utf-8").match(/^TMVEC1 (\d+)$/)
51
+ if (!match) return empty
52
+ const dim = Number(match[1])
53
+ if (!Number.isFinite(dim) || dim <= 0) return empty
54
+ let offset = newline + 1
55
+ const vectors = new Map<string, number[]>()
56
+ while (offset + 2 <= buf.length) {
57
+ const len = buf.readUInt16BE(offset)
58
+ offset += 2
59
+ if (offset + len + dim * 4 > buf.length) break
60
+ const key = buf.subarray(offset, offset + len).toString("utf-8")
61
+ offset += len
62
+ const vec: number[] = []
63
+ for (let i = 0; i < dim; i++) vec.push(buf.readFloatLE(offset + i * 4))
64
+ offset += dim * 4
65
+ vectors.set(key, vec)
66
+ }
67
+ return { dim, vectors }
68
+ } catch {
69
+ return empty
70
+ }
71
+ }
72
+
73
+ export function writeVectors(vectors: Map<string, number[]>, dim: number): number {
74
+ const dir = dirname(VECTORS_FILE)
75
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
76
+ const chunks: Buffer[] = [Buffer.from(`TMVEC1 ${dim}\n`, "utf-8")]
77
+ let written = 0
78
+ for (const [key, vec] of vectors) {
79
+ if (vec.length !== dim) continue
80
+ const keyBuf = Buffer.from(key, "utf-8")
81
+ const lenBuf = Buffer.alloc(2)
82
+ lenBuf.writeUInt16BE(keyBuf.length)
83
+ const vecBuf = Buffer.alloc(dim * 4)
84
+ for (let i = 0; i < dim; i++) vecBuf.writeFloatLE(vec[i], i * 4)
85
+ chunks.push(lenBuf, keyBuf, vecBuf)
86
+ written++
87
+ }
88
+ const out = Buffer.concat(chunks)
89
+ withLockSync(VECTORS_FILE, () => writeFileSync(VECTORS_FILE, out))
90
+ return written
91
+ }
92
+
93
+ export async function buildVectors(data: string, module: DenseModule, model?: string): Promise<number> {
94
+ const entries = parseEntries(data).filter((e) => e.status !== "obsolete" && e.status !== "draft")
95
+ if (entries.length === 0) return 0
96
+ const embedded = await module.embed(entries.map((e) => `${e.key} ${e.content}`), model)
97
+ const dim = embedded[0]?.length || loadConfig().dense?.dim || 0
98
+ if (!dim) return 0
99
+ const vectors = new Map<string, number[]>()
100
+ entries.forEach((e, i) => {
101
+ if (embedded[i]?.length === dim) vectors.set(e.key, embedded[i])
102
+ })
103
+ return writeVectors(vectors, dim)
104
+ }
105
+
106
+ export async function denseScores(query: string, data: string): Promise<Map<string, number>> {
107
+ const config = loadConfig()
108
+ if (!config.dense?.enabled || !query.trim()) return new Map()
109
+ try {
110
+ const module = await loadDenseModule()
111
+ if (!module) return new Map()
112
+ if (readVectors().vectors.size === 0) await buildVectors(data, module, config.dense.model)
113
+ const stored = readVectors()
114
+ if (stored.vectors.size === 0) return new Map()
115
+ const [queryVec] = await module.embed([query], config.dense.model)
116
+ if (!queryVec) return new Map()
117
+ const out = new Map<string, number>()
118
+ for (const [key, vec] of stored.vectors) out.set(key, cosine(queryVec, vec))
119
+ return out
120
+ } catch {
121
+ return new Map()
122
+ }
123
+ }
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