toon-memory 2.2.0 → 2.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/mcp/server.js CHANGED
@@ -27907,50 +27907,137 @@ var importance = (e) => {
27907
27907
  const freq = Math.min(1, e.accessed / 5);
27908
27908
  return recency * 0.6 + freq * 0.4;
27909
27909
  };
27910
- function graphRecall(data, query, opts = {}) {
27910
+ var tokenize = (s) => normalize(s).split(" ").filter(Boolean);
27911
+ function bm25Scores(entries, query) {
27912
+ const N = entries.length;
27913
+ const scores = /* @__PURE__ */ new Map();
27914
+ if (N === 0) return scores;
27915
+ const docs = entries.map(
27916
+ (e) => tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`)
27917
+ );
27918
+ const df = /* @__PURE__ */ new Map();
27919
+ for (const d of docs) {
27920
+ for (const t of new Set(d)) df.set(t, (df.get(t) || 0) + 1);
27921
+ }
27922
+ const avgdl = docs.reduce((a, b2) => a + b2.length, 0) / N;
27923
+ const k1 = 1.5;
27924
+ const b = 0.75;
27925
+ const qTokens = tokenize(query);
27926
+ entries.forEach((e, i) => {
27927
+ const d = docs[i];
27928
+ const dl = d.length || 1;
27929
+ let score = 0;
27930
+ for (const t of qTokens) {
27931
+ const dfT = df.get(t);
27932
+ if (!dfT) continue;
27933
+ const f = d.filter((x) => x === t).length;
27934
+ const idf = Math.log((N - dfT + 0.5) / (dfT + 0.5) + 1);
27935
+ score += idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avgdl));
27936
+ }
27937
+ scores.set(e.key, score);
27938
+ });
27939
+ return scores;
27940
+ }
27941
+ function centrality(adjacency) {
27942
+ let maxDeg = 1;
27943
+ const deg = /* @__PURE__ */ new Map();
27944
+ for (const [k, v] of adjacency) {
27945
+ deg.set(k, v.length);
27946
+ if (v.length > maxDeg) maxDeg = v.length;
27947
+ }
27948
+ const out = /* @__PURE__ */ new Map();
27949
+ for (const [k, d] of deg) out.set(k, d / maxDeg);
27950
+ return out;
27951
+ }
27952
+ var W_CENT = 0.4;
27953
+ var W_IMP = 0.25;
27954
+ var SEED_BONUS = 1;
27955
+ var DECAY = 0.5;
27956
+ function graphRecallDetailed(data, query, opts = {}) {
27911
27957
  const entries = parseEntries(data);
27912
27958
  const { adjacency, byKey } = buildGraph(entries);
27913
27959
  const hops = Math.max(1, Math.min(2, opts.hops ?? 1));
27914
27960
  const category = opts.category || "";
27915
27961
  const from_date = opts.from_date || "";
27916
27962
  const to_date = opts.to_date || "";
27917
- const queryTokens = normalize(query).split(" ").filter(Boolean);
27918
- const seedScore = /* @__PURE__ */ new Map();
27963
+ const qTokens = tokenize(query);
27964
+ const bm25 = bm25Scores(entries, query);
27965
+ const cent = centrality(adjacency);
27966
+ const seedKeys = /* @__PURE__ */ new Set();
27919
27967
  for (const e of entries) {
27920
27968
  if (category && e.category !== category) continue;
27921
27969
  if (from_date && e.date < from_date) continue;
27922
27970
  if (to_date && e.date > to_date) continue;
27923
27971
  if (e.ttl && isExpiredLocal(e.ttl)) continue;
27924
- const searchStr = normalize(
27972
+ const text = normalize(
27925
27973
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
27926
27974
  );
27927
- if (queryTokens.length > 0 && !queryTokens.every((t) => searchStr.includes(t)))
27928
- continue;
27929
- seedScore.set(e.key, importance(e) + 1);
27930
- }
27931
- if (seedScore.size === 0) {
27932
- return [...entries].sort((a, b) => importance(b) - importance(a)).slice(0, opts.limit ?? 6);
27933
- }
27934
- const best = /* @__PURE__ */ new Map();
27935
- const queue = [];
27936
- for (const k of seedScore.keys()) queue.push({ key: k, dist: 0 });
27937
- while (queue.length) {
27938
- const { key, dist } = queue.shift();
27939
- if (best.has(key) && best.get(key) <= dist) continue;
27940
- best.set(key, dist);
27941
- if (dist >= hops) continue;
27942
- for (const nb of adjacency.get(key) || []) {
27943
- queue.push({ key: nb, dist: dist + 1 });
27944
- }
27945
- }
27946
- const scored = [...best.keys()].map((k) => {
27947
- const e = byKey.get(k);
27948
- let s = importance(e);
27949
- if (seedScore.has(k)) s += 1;
27950
- else s += 0.6 / best.get(k);
27951
- return { e, s };
27952
- }).sort((a, b) => b.s - a.s);
27953
- return scored.slice(0, opts.limit ?? 6).map((x) => x.e);
27975
+ if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue;
27976
+ seedKeys.add(e.key);
27977
+ }
27978
+ let selected;
27979
+ const scored = [];
27980
+ if (seedKeys.size === 0) {
27981
+ scored.push(
27982
+ ...[...entries].sort((a, b) => importance(b) - importance(a)).slice(0, opts.limit ?? 6).map((e) => ({ e, s: importance(e) }))
27983
+ );
27984
+ } else {
27985
+ const best = /* @__PURE__ */ new Map();
27986
+ const queue = [];
27987
+ for (const k of seedKeys) queue.push({ key: k, dist: 0 });
27988
+ while (queue.length) {
27989
+ const { key, dist } = queue.shift();
27990
+ if (best.has(key) && best.get(key) <= dist) continue;
27991
+ best.set(key, dist);
27992
+ if (dist >= hops) continue;
27993
+ for (const nb of adjacency.get(key) || []) {
27994
+ queue.push({ key: nb, dist: dist + 1 });
27995
+ }
27996
+ }
27997
+ scored.push(
27998
+ ...[...best.keys()].map((k) => {
27999
+ const e = byKey.get(k);
28000
+ const dist = best.get(k);
28001
+ const decay = Math.pow(DECAY, dist);
28002
+ let s = (bm25.get(k) || 0) + W_CENT * cent.get(k) + W_IMP * importance(e);
28003
+ if (seedKeys.has(k)) s += SEED_BONUS;
28004
+ s *= decay;
28005
+ return { e, s };
28006
+ }).sort((a, b) => b.s - a.s).slice(0, opts.limit ?? 6)
28007
+ );
28008
+ }
28009
+ selected = scored.map((x) => x.e);
28010
+ const subAdj = /* @__PURE__ */ new Map();
28011
+ for (const e of selected) {
28012
+ subAdj.set(
28013
+ e.key,
28014
+ (adjacency.get(e.key) || []).filter((k) => selected.some((s) => s.key === k))
28015
+ );
28016
+ }
28017
+ const scores = /* @__PURE__ */ new Map();
28018
+ selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key).s));
28019
+ return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores };
28020
+ }
28021
+ function renderCompact(entries, opts = {}) {
28022
+ const index = /* @__PURE__ */ new Map();
28023
+ entries.forEach((e, i) => index.set(e.key, i + 1));
28024
+ const snippetLen = opts.snippetLen ?? 90;
28025
+ return entries.map((e) => {
28026
+ const n = index.get(e.key);
28027
+ const isSeed = opts.seeds ? opts.seeds.has(e.key) : true;
28028
+ let body = e.content;
28029
+ if (!isSeed && e.content.length > snippetLen) {
28030
+ body = e.content.slice(0, snippetLen).trimEnd() + "\u2026";
28031
+ }
28032
+ const tags = e.tags.length ? ` \xB7 tags: ${e.tags.join(";")}` : "";
28033
+ let edges = "";
28034
+ if (opts.adjacency) {
28035
+ const nb = (opts.adjacency.get(e.key) || []).map((k) => index.get(k)).filter((x) => typeof x === "number");
28036
+ if (nb.length) edges = ` \xB7 edges: ->${nb.join(", ->")}`;
28037
+ }
28038
+ return `[${n}] ${e.category}/${e.key}
28039
+ ${body}${tags}${edges}`;
28040
+ }).join("\n\n");
27954
28041
  }
27955
28042
 
27956
28043
  // src/mcp/server.ts
@@ -27978,7 +28065,15 @@ function loadConfig() {
27978
28065
  }
27979
28066
  function saveConfig(config2) {
27980
28067
  ensureMemoryDir();
27981
- writeFileSync3(CONFIG_FILE, JSON.stringify(config2, null, 2));
28068
+ let existing = {};
28069
+ if (existsSync3(CONFIG_FILE)) {
28070
+ try {
28071
+ existing = JSON.parse(readFileSync3(CONFIG_FILE, "utf-8"));
28072
+ } catch {
28073
+ existing = {};
28074
+ }
28075
+ }
28076
+ writeFileSync3(CONFIG_FILE, JSON.stringify({ ...existing, ...config2 }, null, 2));
27982
28077
  }
27983
28078
  function getKey() {
27984
28079
  return process.env.TOON_MEMORY_KEY;
@@ -28087,7 +28182,7 @@ var TAG_VOCABULARY = {
28087
28182
  "payment": ["payment", "stripe", "billing", "invoice", "checkout", "subscription"],
28088
28183
  "webhook": ["webhook", "callback", "event", "listener", "hook"]
28089
28184
  };
28090
- function inferTags(content, key) {
28185
+ function inferTags(content, key, vocab) {
28091
28186
  const text = `${key} ${content}`.toLowerCase();
28092
28187
  const matched = [];
28093
28188
  for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
@@ -28095,6 +28190,13 @@ function inferTags(content, key) {
28095
28190
  matched.push(tag);
28096
28191
  }
28097
28192
  }
28193
+ if (vocab) {
28194
+ for (const [tag, keywords] of Object.entries(vocab)) {
28195
+ if (keywords.some((kw) => text.includes(kw))) {
28196
+ matched.push(tag);
28197
+ }
28198
+ }
28199
+ }
28098
28200
  return matched.join(";");
28099
28201
  }
28100
28202
  function parseRelativeDate(since) {
@@ -28296,7 +28398,7 @@ function consolidateEntries() {
28296
28398
  return { removed: duplicates.length, kept: order.length, duplicates };
28297
28399
  }
28298
28400
  var server = new McpServer(
28299
- { name: "toon-memory", version: "2.2.0" },
28401
+ { name: "toon-memory", version: "2.3.0" },
28300
28402
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
28301
28403
  );
28302
28404
  server.registerResource(
@@ -28389,7 +28491,7 @@ server.registerTool(
28389
28491
  }
28390
28492
  const entryId = existingIdx !== -1 ? existingId : newId;
28391
28493
  const resolvedTtl = parseTTL(ttl);
28392
- const resolvedTags = tags ? tags : inferTags(content, key);
28494
+ const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab);
28393
28495
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : [];
28394
28496
  const resolvedLinks = links ? links.split(/[\s;]+/).filter(Boolean).join(" ") : existingParts[9] || "";
28395
28497
  const newEntry = `${entryId}|${category}|${key}|${content}|${file2 || ""}|${resolvedTags}|${date5}|${resolvedTtl}|0|${resolvedLinks}`;
@@ -28445,10 +28547,11 @@ server.registerTool(
28445
28547
  from_date: external_exports.string().optional().default("").describe("Fecha inicio filtro (YYYY-MM-DD)"),
28446
28548
  to_date: external_exports.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
28447
28549
  mode: external_exports.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = b\xFAsqueda por palabra clave (default). 'graph' = recall basado en grafo: expande el subgrafo de entradas relacionadas desde las coincidencias (m\xE1s preciso, menos tokens)."),
28448
- hops: external_exports.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1.")
28550
+ hops: external_exports.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
28551
+ compact: external_exports.boolean().optional().default(false).describe("Salida token-efficient: \xEDndices num\xE9ricos (1, 2), omite id/fecha/archivo (conserva tags), aristas como '->2', y trunca vecinos del grafo a un snippet. No muta el archivo .toon.")
28449
28552
  }
28450
28553
  },
28451
- async ({ query, category, from_date, to_date, mode, hops }) => {
28554
+ async ({ query, category, from_date, to_date, mode, hops, compact }) => {
28452
28555
  const data = readMemory();
28453
28556
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"));
28454
28557
  const normalize3 = (s) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim();
@@ -28471,12 +28574,20 @@ server.registerTool(
28471
28574
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28472
28575
  }
28473
28576
  if (mode === "graph") {
28474
- const subgraph = graphRecall(data, query, { category, from_date, to_date, hops });
28475
- if (subgraph.length === 0) {
28577
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops });
28578
+ if (detail.entries.length === 0) {
28476
28579
  return { content: [{ type: "text", text: `No se encontraron resultados para "${query}"` }] };
28477
28580
  }
28478
- bumpAccessed(subgraph.map((e) => e.id));
28479
- const formatted2 = subgraph.map((r) => {
28581
+ bumpAccessed(detail.entries.map((e) => e.id));
28582
+ if (compact) {
28583
+ const formatted3 = renderCompact(detail.entries, {
28584
+ adjacency: detail.adjacency,
28585
+ seeds: detail.seeds,
28586
+ snippetLen: 90
28587
+ });
28588
+ return { content: [{ type: "text", text: formatted3 }] };
28589
+ }
28590
+ const formatted2 = detail.entries.map((r) => {
28480
28591
  const links = r.links.length ? `
28481
28592
  links: ${r.links.join(", ")}` : "";
28482
28593
  return `[${r.category}] ${r.key} (${r.id})
@@ -28487,6 +28598,22 @@ server.registerTool(
28487
28598
  }
28488
28599
  const ranked = results.map((r) => ({ ...r, score: entryScore(r.date, r.accessed) })).sort((a, b) => b.score - a.score);
28489
28600
  bumpAccessed(ranked.map((r) => r.id));
28601
+ if (compact) {
28602
+ const entries = ranked.map((r) => ({
28603
+ id: r.id,
28604
+ category: r.cat,
28605
+ key: r.key,
28606
+ content: r.content,
28607
+ file: r.file,
28608
+ tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
28609
+ date: r.date,
28610
+ ttl: "",
28611
+ accessed: r.accessed,
28612
+ links: []
28613
+ }));
28614
+ const formatted2 = renderCompact(entries);
28615
+ return { content: [{ type: "text", text: formatted2 }] };
28616
+ }
28490
28617
  const formatted = ranked.map((r) => `[${r.cat}] ${r.key} (${r.id})
28491
28618
  ${r.content}
28492
28619
  File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`).join("\n\n");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "toon-memory",
3
- "version": "2.2.0",
3
+ "version": "2.3.0",
4
4
  "description": "Persistent memory system for AI coding agents using TOON format (22% fewer tokens than JSON, measured)",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli/setup.ts CHANGED
@@ -3,6 +3,7 @@ import { basename, dirname, join } from "path"
3
3
  import { fileURLToPath } from "url"
4
4
  import { createInterface } from "readline"
5
5
  import { gzipSync, gunzipSync } from "zlib"
6
+ import { extractProjectDeps } from "../lib/vocab"
6
7
 
7
8
  const __dirname = dirname(fileURLToPath(import.meta.url))
8
9
  const projectRoot = process.cwd()
@@ -601,17 +602,43 @@ function installForAgent(agent: Agent, scope: string): void {
601
602
  installHooks(agent)
602
603
  }
603
604
 
605
+ /**
606
+ * Read/write the shared memory config.json, preserving unknown keys
607
+ * (e.g. `encrypted`, `capture`) so we never clobber sibling settings.
608
+ */
609
+ function updateMemoryConfig(patch: Record<string, any>): void {
610
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
611
+ let cfg: Record<string, any> = {}
612
+ if (existsSync(CAPTURE_CONFIG)) {
613
+ try {
614
+ cfg = JSON.parse(readFileSync(CAPTURE_CONFIG, "utf-8"))
615
+ } catch {
616
+ cfg = {}
617
+ }
618
+ }
619
+ Object.assign(cfg, patch)
620
+ writeFileSync(CAPTURE_CONFIG, JSON.stringify(cfg, null, 2))
621
+ }
622
+
604
623
  /**
605
624
  * Initialize toon-memory for all detected agents (non-interactive).
606
625
  *
607
- * Installs MCP server configs, creates memory directory, and
608
- * updates `.gitignore`.
626
+ * Installs MCP server configs, creates memory directory, discovers project
627
+ * dependencies for tag inference, and updates `.gitignore`.
609
628
  */
610
629
  function init(scope: string = "local"): void {
611
630
  console.log("\n🧠 toon-memory init\n")
612
631
 
613
632
  installMemoryDir()
614
633
 
634
+ // Hito 7 (B): derive a project-specific tag vocabulary from dependencies.
635
+ const deps = extractProjectDeps(projectRoot)
636
+ const depCount = Object.keys(deps).length
637
+ if (depCount > 0) {
638
+ updateMemoryConfig({ vocab: deps })
639
+ console.log(` Detected ${depCount} dependencies → auto-tag vocabulary written to config.json`)
640
+ }
641
+
615
642
  const agents = detectAgents()
616
643
  for (const agent of agents) {
617
644
  installForAgent(agent, scope)
package/src/lib/graph.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  * Everything is deterministic and offline: no embeddings, no LLM, no network.
9
9
  * The graph's value is precision (relational context) and smaller result sets
10
10
  * (an ego-subgraph instead of dumping every keyword match).
11
+ *
12
+ * Hito 7 adds BM25 relevance scoring + graph centrality re-ranking, plus a
13
+ * `detailed` result so the MCP server can render compact / numeric-edge output
14
+ * without mutating the stored `.toon` file.
11
15
  */
12
16
 
13
17
  export interface GraphEntry {
@@ -130,16 +134,89 @@ const importance = (e: GraphEntry): number => {
130
134
  return recency * 0.6 + freq * 0.4
131
135
  }
132
136
 
137
+ const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
138
+
139
+ /**
140
+ * BM25 relevance of each entry for the query. Deterministic and offline.
141
+ * Returns a map key -> score (0 when the entry shares no query token).
142
+ */
143
+ export function bm25Scores(entries: GraphEntry[], query: string): Map<string, number> {
144
+ const N = entries.length
145
+ const scores = new Map<string, number>()
146
+ if (N === 0) return scores
147
+
148
+ const docs = entries.map((e) =>
149
+ tokenize(`${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`)
150
+ )
151
+ const df = new Map<string, number>()
152
+ for (const d of docs) {
153
+ for (const t of new Set(d)) df.set(t, (df.get(t) || 0) + 1)
154
+ }
155
+ const avgdl = docs.reduce((a, b) => a + b.length, 0) / N
156
+ const k1 = 1.5
157
+ const b = 0.75
158
+ const qTokens = tokenize(query)
159
+
160
+ entries.forEach((e, i) => {
161
+ const d = docs[i]
162
+ const dl = d.length || 1
163
+ let score = 0
164
+ for (const t of qTokens) {
165
+ const dfT = df.get(t)
166
+ if (!dfT) continue
167
+ const f = d.filter((x) => x === t).length
168
+ const idf = Math.log((N - dfT + 0.5) / (dfT + 0.5) + 1)
169
+ score += (idf * (f * (k1 + 1))) / (f + k1 * (1 - b + (b * dl) / avgdl))
170
+ }
171
+ scores.set(e.key, score)
172
+ })
173
+ return scores
174
+ }
175
+
176
+ /**
177
+ * Degree-normalized centrality (0..1). A hub connected to many entries scores
178
+ * near 1, so it surfaces even when it lacks the exact query word.
179
+ */
180
+ export function centrality(adjacency: Map<string, string[]>): Map<string, number> {
181
+ let maxDeg = 1
182
+ const deg = new Map<string, number>()
183
+ for (const [k, v] of adjacency) {
184
+ deg.set(k, v.length)
185
+ if (v.length > maxDeg) maxDeg = v.length
186
+ }
187
+ const out = new Map<string, number>()
188
+ for (const [k, d] of deg) out.set(k, d / maxDeg)
189
+ return out
190
+ }
191
+
192
+ export interface GraphRecallResult {
193
+ /** Selected entries, ordered by final score (desc). */
194
+ entries: GraphEntry[]
195
+ /** Keys that directly matched the query (seeds, distance 0). */
196
+ seeds: Set<string>
197
+ /** Adjacency restricted to the selected entries (for numeric-edge rendering). */
198
+ adjacency: Map<string, string[]>
199
+ /** Final combined score per key (bm25 + centrality + importance + seed bonus). */
200
+ scores: Map<string, number>
201
+ }
202
+
203
+ const W_CENT = 0.4
204
+ const W_IMP = 0.25
205
+ const SEED_BONUS = 1.0
206
+ /** Per-hop decay: a node 1 hop from a seed scores half of an equivalent seed. */
207
+ const DECAY = 0.5
208
+
133
209
  /**
134
- * Graph-aware recall. Seeds are keyword matches (AND logic); the result is the
135
- * ego-subgraph expanded up to `hops` with relevance propagated from seeds.
210
+ * Graph-aware recall with BM25 + centrality re-ranking.
211
+ * Seeds are keyword matches (AND logic); the result is the ego-subgraph
212
+ * expanded up to `hops` (1 or 2), with relevance propagated from the seeds.
136
213
  * Falls back to top-by-importance when the query matches nothing.
137
214
  */
138
- export function graphRecall(
215
+ export function graphRecallDetailed(
139
216
  data: string,
140
217
  query: string,
141
218
  opts: GraphRecallOpts = {}
142
- ): GraphEntry[] {
219
+ ): GraphRecallResult {
143
220
  const entries = parseEntries(data)
144
221
  const { adjacency, byKey } = buildGraph(entries)
145
222
  const hops = Math.max(1, Math.min(2, opts.hops ?? 1))
@@ -147,54 +224,131 @@ export function graphRecall(
147
224
  const from_date = opts.from_date || ""
148
225
  const to_date = opts.to_date || ""
149
226
 
150
- const queryTokens = normalize(query)
151
- .split(" ")
152
- .filter(Boolean)
227
+ const qTokens = tokenize(query)
228
+ const bm25 = bm25Scores(entries, query)
229
+ const cent = centrality(adjacency)
153
230
 
154
- const seedScore = new Map<string, number>()
231
+ const seedKeys = new Set<string>()
155
232
  for (const e of entries) {
156
233
  if (category && e.category !== category) continue
157
234
  if (from_date && e.date < from_date) continue
158
235
  if (to_date && e.date > to_date) continue
159
236
  if (e.ttl && isExpiredLocal(e.ttl)) continue
160
- const searchStr = normalize(
237
+ const text = normalize(
161
238
  `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
162
239
  )
163
- if (queryTokens.length > 0 && !queryTokens.every((t) => searchStr.includes(t)))
164
- continue
165
- seedScore.set(e.key, importance(e) + 1.0)
240
+ if (qTokens.length > 0 && !qTokens.every((t) => text.includes(t))) continue
241
+ seedKeys.add(e.key)
166
242
  }
167
243
 
168
- // No matches: return the most important entries as a sane fallback.
169
- if (seedScore.size === 0) {
170
- return [...entries]
171
- .sort((a, b) => importance(b) - importance(a))
172
- .slice(0, opts.limit ?? 6)
244
+ let selected: GraphEntry[]
245
+ const scored: Array<{ e: GraphEntry; s: number }> = []
246
+ if (seedKeys.size === 0) {
247
+ scored.push(
248
+ ...[...entries]
249
+ .sort((a, b) => importance(b) - importance(a))
250
+ .slice(0, opts.limit ?? 6)
251
+ .map((e) => ({ e, s: importance(e) }))
252
+ )
253
+ } else {
254
+ // BFS from all seeds, recording the shortest hop distance to each node.
255
+ const best = new Map<string, number>()
256
+ const queue: Array<{ key: string; dist: number }> = []
257
+ for (const k of seedKeys) queue.push({ key: k, dist: 0 })
258
+ while (queue.length) {
259
+ const { key, dist } = queue.shift()!
260
+ if (best.has(key) && best.get(key)! <= dist) continue
261
+ best.set(key, dist)
262
+ if (dist >= hops) continue
263
+ for (const nb of adjacency.get(key) || []) {
264
+ queue.push({ key: nb, dist: dist + 1 })
265
+ }
266
+ }
267
+
268
+ scored.push(
269
+ ...[...best.keys()]
270
+ .map((k) => {
271
+ const e = byKey.get(k)!
272
+ const dist = best.get(k)!
273
+ const decay = Math.pow(DECAY, dist)
274
+ let s = (bm25.get(k) || 0) + W_CENT * cent.get(k)! + W_IMP * importance(e)
275
+ if (seedKeys.has(k)) s += SEED_BONUS
276
+ s *= decay
277
+ return { e, s }
278
+ })
279
+ .sort((a, b) => b.s - a.s)
280
+ .slice(0, opts.limit ?? 6)
281
+ )
173
282
  }
174
283
 
175
- // BFS from all seeds, recording the shortest hop distance to each node.
176
- const best = new Map<string, number>()
177
- const queue: Array<{ key: string; dist: number }> = []
178
- for (const k of seedScore.keys()) queue.push({ key: k, dist: 0 })
179
- while (queue.length) {
180
- const { key, dist } = queue.shift()!
181
- if (best.has(key) && best.get(key)! <= dist) continue
182
- best.set(key, dist)
183
- if (dist >= hops) continue
184
- for (const nb of adjacency.get(key) || []) {
185
- queue.push({ key: nb, dist: dist + 1 })
186
- }
284
+ selected = scored.map((x) => x.e)
285
+
286
+ // Restrict adjacency to the selected entries for compact edge rendering.
287
+ const subAdj = new Map<string, string[]>()
288
+ for (const e of selected) {
289
+ subAdj.set(
290
+ e.key,
291
+ (adjacency.get(e.key) || []).filter((k) => selected.some((s) => s.key === k))
292
+ )
187
293
  }
188
294
 
189
- const scored = [...best.keys()]
190
- .map((k) => {
191
- const e = byKey.get(k)!
192
- let s = importance(e)
193
- if (seedScore.has(k)) s += 1.0
194
- else s += 0.6 / best.get(k)!
195
- return { e, s }
196
- })
197
- .sort((a, b) => b.s - a.s)
295
+ const scores = new Map<string, number>()
296
+ selected.forEach((e) => scores.set(e.key, scored.find((x) => x.e.key === e.key)!.s))
297
+
298
+ return { entries: selected, seeds: seedKeys, adjacency: subAdj, scores }
299
+ }
300
+
301
+ /**
302
+ * Convenience wrapper returning just the ordered entries (backward compatible).
303
+ */
304
+ export function graphRecall(
305
+ data: string,
306
+ query: string,
307
+ opts: GraphRecallOpts = {}
308
+ ): GraphEntry[] {
309
+ return graphRecallDetailed(data, query, opts).entries
310
+ }
311
+
312
+ export interface RenderCompactOpts {
313
+ /** Restricted adjacency for numeric edge rendering (graph mode). */
314
+ adjacency?: Map<string, string[]>
315
+ /** Keys that directly matched the query (seeds = full content). */
316
+ seeds?: Set<string>
317
+ /** Max chars before a neighbor (non-seed) is truncated with an ellipsis. */
318
+ snippetLen?: number
319
+ }
320
+
321
+ /**
322
+ * Token-efficient rendering of recall results.
323
+ * - each entry gets a stable numeric index `1`, `2`, ...
324
+ * - `id` / `date` / `file` are dropped (only `tags` is kept)
325
+ * - graph edges render as `->2, ->3` (numeric) when `adjacency` is given
326
+ * - neighbors reached via graph (non-seeds) are truncated to `snippetLen`
327
+ *
328
+ * The stored `.toon` file is never mutated — this only shapes the output.
329
+ */
330
+ export function renderCompact(entries: GraphEntry[], opts: RenderCompactOpts = {}): string {
331
+ const index = new Map<string, number>()
332
+ entries.forEach((e, i) => index.set(e.key, i + 1))
333
+ const snippetLen = opts.snippetLen ?? 90
198
334
 
199
- return scored.slice(0, opts.limit ?? 6).map((x) => x.e)
335
+ return entries
336
+ .map((e) => {
337
+ const n = index.get(e.key)!
338
+ const isSeed = opts.seeds ? opts.seeds.has(e.key) : true
339
+ let body = e.content
340
+ if (!isSeed && e.content.length > snippetLen) {
341
+ body = e.content.slice(0, snippetLen).trimEnd() + "…"
342
+ }
343
+ const tags = e.tags.length ? ` · tags: ${e.tags.join(";")}` : ""
344
+ let edges = ""
345
+ if (opts.adjacency) {
346
+ const nb = (opts.adjacency.get(e.key) || [])
347
+ .map((k) => index.get(k))
348
+ .filter((x): x is number => typeof x === "number")
349
+ if (nb.length) edges = ` · edges: ->${nb.join(", ->")}`
350
+ }
351
+ return `[${n}] ${e.category}/${e.key}\n ${body}${tags}${edges}`
352
+ })
353
+ .join("\n\n")
200
354
  }