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.
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Project-vocabulary discovery for toon-memory (Hito 7).
3
+ *
4
+ * On `toon-memory init` we scan the project's dependency manifests and turn
5
+ * each dependency into a tag keyword. Those keywords are written to
6
+ * `config.json` as `vocab`, and `memory_remember`'s tag inference matches
7
+ * against them — so a project that depends on `redis` auto-tags entries that
8
+ * mention "redis" with `redis`, without a hand-maintained glossary.
9
+ *
10
+ * Deterministic and offline: we only read manifest files, never hit the network.
11
+ */
12
+
13
+ import { existsSync, readFileSync } from "fs"
14
+ import { join } from "path"
15
+
16
+ /** tag -> keywords that should attach that tag. */
17
+ export type Vocab = Record<string, string[]>
18
+
19
+ /** Cargo-style manifest names we understand. */
20
+ const MANIFESTS = ["package.json", "Cargo.toml", "requirements.txt", "pyproject.toml", "go.mod"]
21
+
22
+ /**
23
+ * Scan `root` for dependency manifests and return a vocabulary derived from
24
+ * the declared dependencies. Missing manifests are silently skipped.
25
+ */
26
+ export function extractProjectDeps(root: string): Vocab {
27
+ const vocab: Vocab = {}
28
+
29
+ const pkgPath = join(root, "package.json")
30
+ if (existsSync(pkgPath)) {
31
+ try {
32
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"))
33
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }
34
+ for (const name of Object.keys(deps)) {
35
+ const tag = name.replace(/^@[^/]+\//, "").toLowerCase()
36
+ vocab[tag] = name.includes("/") ? [name.toLowerCase(), tag] : [name.toLowerCase()]
37
+ }
38
+ } catch {
39
+ // ignore malformed manifest
40
+ }
41
+ }
42
+
43
+ const cargoPath = join(root, "Cargo.toml")
44
+ if (existsSync(cargoPath)) {
45
+ try {
46
+ const txt = readFileSync(cargoPath, "utf-8")
47
+ const block = txt.match(/\[dependencies\][\s\S]*?(?:\n\[|$)/)?.[0] || ""
48
+ for (const line of block.split("\n")) {
49
+ const m = line.match(/^\s*([A-Za-z0-9_-]+)\s*=/)
50
+ if (m) {
51
+ const tag = m[1].toLowerCase()
52
+ vocab[tag] = [tag]
53
+ }
54
+ }
55
+ } catch {
56
+ // ignore
57
+ }
58
+ }
59
+
60
+ for (const file of ["requirements.txt", "pyproject.toml"]) {
61
+ const p = join(root, file)
62
+ if (!existsSync(p)) continue
63
+ try {
64
+ const txt = readFileSync(p, "utf-8")
65
+ for (const raw of txt.split("\n")) {
66
+ const name = raw.trim().split(/[<>=!~ \[\]]/)[0].toLowerCase()
67
+ if (!name || name.startsWith("#") || name.includes("[") ) continue
68
+ vocab[name] = [name]
69
+ }
70
+ } catch {
71
+ // ignore
72
+ }
73
+ }
74
+
75
+ const goPath = join(root, "go.mod")
76
+ if (existsSync(goPath)) {
77
+ try {
78
+ const txt = readFileSync(goPath, "utf-8")
79
+ for (const raw of txt.split("\n")) {
80
+ const m = raw.match(/^\s*([A-Za-z0-9_./-]+)\s+v[0-9]/)
81
+ if (m) {
82
+ const full = m[1]
83
+ const tag = full.split("/").pop()!.toLowerCase()
84
+ vocab[tag] = [tag, full.toLowerCase()]
85
+ }
86
+ }
87
+ } catch {
88
+ // ignore
89
+ }
90
+ }
91
+
92
+ return vocab
93
+ }
94
+
95
+ /** Merge two vocabularies; `extra` wins on key collisions. */
96
+ export function mergeVocab(base: Vocab, extra: Vocab): Vocab {
97
+ return { ...base, ...extra }
98
+ }
99
+
100
+ export { MANIFESTS }
package/src/mcp/server.ts CHANGED
@@ -7,7 +7,7 @@ import { fileURLToPath } from "url"
7
7
  import { randomBytes, createCipheriv, createDecipheriv } from "crypto"
8
8
  import { withLockSync, atomicWrite, readUnderLock } from "../lib/lock"
9
9
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS } from "../lib/sessions"
10
- import { graphRecall } from "../lib/graph"
10
+ import { graphRecallDetailed, renderCompact } from "../lib/graph"
11
11
 
12
12
  const __dirname = dirname(fileURLToPath(import.meta.url))
13
13
 
@@ -48,6 +48,8 @@ const ALGORITHM = "aes-256-gcm"
48
48
  interface MemoryConfig {
49
49
  /** Whether encryption is enabled */
50
50
  encrypted: boolean
51
+ /** Project-specific tag vocabulary discovered from dependencies (Hito 7). */
52
+ vocab?: Record<string, string[]>
51
53
  }
52
54
 
53
55
  /**
@@ -81,7 +83,16 @@ function loadConfig(): MemoryConfig {
81
83
  */
82
84
  function saveConfig(config: MemoryConfig): void {
83
85
  ensureMemoryDir()
84
- writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2))
86
+ // Merge so we never clobber a `vocab` written by `toon-memory init`.
87
+ let existing: Partial<MemoryConfig> = {}
88
+ if (existsSync(CONFIG_FILE)) {
89
+ try {
90
+ existing = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
91
+ } catch {
92
+ existing = {}
93
+ }
94
+ }
95
+ writeFileSync(CONFIG_FILE, JSON.stringify({ ...existing, ...config }, null, 2))
85
96
  }
86
97
 
87
98
  /**
@@ -272,9 +283,11 @@ const TAG_VOCABULARY: Record<string, string[]> = {
272
283
 
273
284
  /**
274
285
  * Infer tags from content and key by matching against vocabulary.
286
+ * The built-in vocabulary is always used; a project-specific `vocab`
287
+ * (discovered from dependencies at `init`) is matched on top of it.
275
288
  * Returns semicolon-separated tags.
276
289
  */
277
- function inferTags(content: string, key: string): string {
290
+ function inferTags(content: string, key: string, vocab?: Record<string, string[]>): string {
278
291
  const text = `${key} ${content}`.toLowerCase()
279
292
  const matched: string[] = []
280
293
  for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
@@ -282,6 +295,13 @@ function inferTags(content: string, key: string): string {
282
295
  matched.push(tag)
283
296
  }
284
297
  }
298
+ if (vocab) {
299
+ for (const [tag, keywords] of Object.entries(vocab)) {
300
+ if (keywords.some((kw) => text.includes(kw))) {
301
+ matched.push(tag)
302
+ }
303
+ }
304
+ }
285
305
  return matched.join(";")
286
306
  }
287
307
 
@@ -579,7 +599,7 @@ function consolidateEntries(): { removed: number; kept: number; duplicates: stri
579
599
  }
580
600
 
581
601
  const server = new McpServer(
582
- { name: "toon-memory", version: "2.2.0" },
602
+ { name: "toon-memory", version: "2.3.0" },
583
603
  { capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
584
604
  )
585
605
 
@@ -704,7 +724,7 @@ server.registerTool(
704
724
 
705
725
  const entryId = existingIdx !== -1 ? existingId : newId
706
726
  const resolvedTtl = parseTTL(ttl)
707
- const resolvedTags = tags ? tags : inferTags(content, key)
727
+ const resolvedTags = tags ? tags : inferTags(content, key, loadConfig().vocab)
708
728
  // Preserve existing links on upsert unless new ones are provided.
709
729
  const existingParts = existingIdx !== -1 ? lines[existingIdx].trim().split("|") : []
710
730
  const resolvedLinks = links
@@ -778,9 +798,10 @@ server.registerTool(
778
798
  to_date: z.string().optional().default("").describe("Fecha fin filtro (YYYY-MM-DD)"),
779
799
  mode: z.enum(["flat", "graph"]).optional().default("flat").describe("'flat' = búsqueda por palabra clave (default). 'graph' = recall basado en grafo: expande el subgrafo de entradas relacionadas desde las coincidencias (más preciso, menos tokens)."),
780
800
  hops: z.number().optional().default(1).describe("Profundidad del grafo en modo 'graph' (1 o 2). Default 1."),
801
+ compact: z.boolean().optional().default(false).describe("Salida token-efficient: índices numéricos (1, 2), omite id/fecha/archivo (conserva tags), aristas como '->2', y trunca vecinos del grafo a un snippet. No muta el archivo .toon."),
781
802
  },
782
803
  },
783
- async ({ query, category, from_date, to_date, mode, hops }) => {
804
+ async ({ query, category, from_date, to_date, mode, hops, compact }) => {
784
805
  const data = readMemory()
785
806
  const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
786
807
 
@@ -813,12 +834,20 @@ server.registerTool(
813
834
  // Graph mode: expand the ego-subgraph from keyword matches and return the
814
835
  // focused, relationship-aware result set (fewer tokens, higher precision).
815
836
  if (mode === "graph") {
816
- const subgraph = graphRecall(data, query, { category, from_date, to_date, hops })
817
- if (subgraph.length === 0) {
837
+ const detail = graphRecallDetailed(data, query, { category, from_date, to_date, hops })
838
+ if (detail.entries.length === 0) {
818
839
  return { content: [{ type: "text" as const, text: `No se encontraron resultados para "${query}"` }] }
819
840
  }
820
- bumpAccessed(subgraph.map((e) => e.id))
821
- const formatted = subgraph
841
+ bumpAccessed(detail.entries.map((e) => e.id))
842
+ if (compact) {
843
+ const formatted = renderCompact(detail.entries, {
844
+ adjacency: detail.adjacency,
845
+ seeds: detail.seeds,
846
+ snippetLen: 90,
847
+ })
848
+ return { content: [{ type: "text" as const, text: formatted }] }
849
+ }
850
+ const formatted = detail.entries
822
851
  .map((r) => {
823
852
  const links = r.links.length ? `\n links: ${r.links.join(", ")}` : ""
824
853
  return `[${r.category}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags.join(";")} | Date: ${r.date}${links}`
@@ -834,6 +863,23 @@ server.registerTool(
834
863
 
835
864
  bumpAccessed(ranked.map((r) => r.id))
836
865
 
866
+ if (compact) {
867
+ const entries = ranked.map((r) => ({
868
+ id: r.id,
869
+ category: r.cat,
870
+ key: r.key,
871
+ content: r.content,
872
+ file: r.file,
873
+ tags: r.tags ? r.tags.split(";").filter(Boolean) : [],
874
+ date: r.date,
875
+ ttl: "",
876
+ accessed: r.accessed,
877
+ links: [] as string[],
878
+ }))
879
+ const formatted = renderCompact(entries)
880
+ return { content: [{ type: "text" as const, text: formatted }] }
881
+ }
882
+
837
883
  const formatted = ranked
838
884
  .map((r) => `[${r.cat}] ${r.key} (${r.id})\n ${r.content}\n File: ${r.file} | Tags: ${r.tags} | Date: ${r.date}`)
839
885
  .join("\n\n")