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,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
  })
package/src/lib/utils.ts CHANGED
@@ -4,7 +4,20 @@
4
4
  */
5
5
 
6
6
  export const normalize = (s: string): string =>
7
- s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
7
+ s
8
+ .toLowerCase()
9
+ .normalize("NFD")
10
+ .replace(/[\u0300-\u036f]/g, "")
11
+ .replace(/[-_]/g, " ")
12
+ .replace(/\s+/g, " ")
13
+ .trim()
14
+
15
+ const STOPWORDS = new Set([
16
+ "a", "de", "del", "la", "el", "los", "las", "un", "una", "unos", "unas", "y", "o", "en", "al",
17
+ "por", "para", "con", "sin", "sobre", "como", "que", "cual", "cuando", "donde", "es", "son",
18
+ "fue", "era", "se", "su", "sus", "lo", "le", "les", "me", "te", "nos", "os", "mi", "tu",
19
+ "the", "and", "or", "for", "with", "from", "this", "that", "into", "was", "were", "been", "being",
20
+ ])
8
21
 
9
22
  export const isExpiredLocal = (ttl: string, today = new Date().toISOString().split("T")[0]): boolean => {
10
23
  if (!ttl) return false
@@ -48,12 +61,9 @@ export const importanceRank = (level: string): number => {
48
61
  }
49
62
 
50
63
  export const tokenize = (s: string): string[] =>
51
- s
52
- .replace(/([a-z])([A-Z])/g, "$1 $2")
53
- .replace(/[-_]/g, " ")
54
- .toLowerCase()
55
- .split(/\s+/)
56
- .filter(Boolean)
64
+ normalize(s.replace(/([a-z])([A-Z])/g, "$1 $2"))
65
+ .split(" ")
66
+ .filter((t) => t.length >= 2 && !STOPWORDS.has(t))
57
67
 
58
68
  /**
59
69
  * Deterministic token estimate for a text: roughly one token per 4 chars,
@@ -0,0 +1,46 @@
1
+ /** Tolerant argument helpers: LLMs routinely send "6" instead of 6. */
2
+
3
+ import { z } from "zod"
4
+
5
+ const toNumber = (v: unknown): unknown => {
6
+ if (typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v))) return Number(v)
7
+ return v
8
+ }
9
+
10
+ /** Positive integer, optional with a fallback. Rejects 0, negatives and junk. */
11
+ export function positiveInt(fallback: number, max = 500) {
12
+ return z.preprocess(toNumber, z.number().int().min(1).max(max).optional().default(fallback))
13
+ }
14
+
15
+ /** Positive integer, optional with no default (0 = absent). */
16
+ export function optionalPositiveInt(max = 500) {
17
+ return z.preprocess(toNumber, z.number().int().min(1).max(max).optional())
18
+ }
19
+
20
+ /** String that must carry content — prevents silent empty-key entries. */
21
+ export function requiredText(label: string, max = 4000) {
22
+ return z.string().trim().min(1, `${label} must not be empty`).max(max)
23
+ }
24
+
25
+ /** Normalize id lists regardless of separator, including JSON arrays. */
26
+ export function splitIds(value: string): string[] {
27
+ if (!value) return []
28
+ let raw = value
29
+ if (value.trim().startsWith("[")) {
30
+ try {
31
+ const parsed = JSON.parse(value)
32
+ if (Array.isArray(parsed)) raw = parsed.map(String).join(" ")
33
+ } catch {
34
+ /* keep the raw string */
35
+ }
36
+ }
37
+ return raw.split(/[\s,;]+/).map((t) => t.trim()).filter(Boolean)
38
+ }
39
+
40
+ /** Empty results are data, not errors. Actionable text + machine-readable payload. */
41
+ export function noMatches(query: string): { content: Array<{ type: "text"; text: string }>; structuredContent: { found: false; count: 0 } } {
42
+ return {
43
+ content: [{ type: "text", text: `No matching memories for "${query}". Try a shorter query, or save one first with memory_remember. A transient empty result is not an error.` }],
44
+ structuredContent: { found: false, count: 0 },
45
+ }
46
+ }
package/src/mcp/config.ts CHANGED
@@ -14,6 +14,12 @@ export const ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon")
14
14
  /** Observations log written by capture hooks (opt-in, separate from memory) */
15
15
  export const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
16
16
 
17
+ export const FEEDBACK_FILE = join(MEMORY_DIR, "feedback.toon")
18
+
19
+ export const EDGES_FILE = join(MEMORY_DIR, "edges.toon")
20
+
21
+ export const VECTORS_FILE = join(MEMORY_DIR, "vectors.bin")
22
+
17
23
  /** Encrypted sidecar vault for secrets. Whole-file AES-256-GCM when TOON_MEMORY_KEY is set.
18
24
  * Kept separate from data.toon so the main memory stays a readable, open format. */
19
25
  export const SECRETS_FILE = join(MEMORY_DIR, "secrets.toon")
@@ -56,6 +62,20 @@ export interface MemoryConfig {
56
62
  enabled?: boolean
57
63
  interval?: number
58
64
  }
65
+ feedback?: {
66
+ implicit?: boolean
67
+ }
68
+ graph?: {
69
+ activation?: boolean
70
+ }
71
+ sleep?: {
72
+ enabled?: boolean
73
+ }
74
+ dense?: {
75
+ enabled?: boolean
76
+ model?: string
77
+ dim?: number
78
+ }
59
79
  }
60
80
 
61
81
  /**
@@ -0,0 +1,99 @@
1
+ import { existsSync, mkdirSync, readFileSync } from "fs"
2
+ import { dirname } from "path"
3
+ import { EDGES_FILE } from "./config"
4
+ import { atomicWrite, withLockSync } from "../lib/lock"
5
+ import { parseEntries, parseLinkToken } from "../lib/graph"
6
+ import { parseToonLine, toToonLine } from "../lib/utils"
7
+ import type { FeedbackEvent } from "./feedback"
8
+
9
+ export const EDGE_TYPES = ["related", "supports", "contradicts", "supersedes", "depends_on", "derived_from", "used_in"] as const
10
+ export type EdgeType = (typeof EDGE_TYPES)[number]
11
+
12
+ export interface Edge {
13
+ from: string
14
+ to: string
15
+ type: EdgeType
16
+ weight: number
17
+ ts: string
18
+ }
19
+
20
+ const HEADER = "version: 1\nedges[0|]{from|to|type|weight|ts}:"
21
+ const MAX_EDGES = 2000
22
+
23
+ function normalizeType(type: string): EdgeType {
24
+ const t = type.toLowerCase()
25
+ return (EDGE_TYPES as readonly string[]).includes(t) ? (t as EdgeType) : "related"
26
+ }
27
+
28
+ export function readEdges(): Edge[] {
29
+ if (!existsSync(EDGES_FILE)) return []
30
+ try {
31
+ const lines = readFileSync(EDGES_FILE, "utf-8").split("\n")
32
+ const start = lines.findIndex((l) => l.startsWith("edges[") || /^\[\d+\|]/.test(l))
33
+ if (start === -1) return []
34
+ const out: Edge[] = []
35
+ for (const line of lines.slice(start + 1)) {
36
+ if (!line.startsWith(" ") || !line.includes("|")) continue
37
+ const p = parseToonLine(line)
38
+ if (p.length < 5) continue
39
+ const weight = Number(p[3])
40
+ if (!p[0] || !p[1] || !Number.isFinite(weight)) continue
41
+ out.push({ from: p[0], to: p[1], type: normalizeType(p[2]), weight, ts: p[4] || "" })
42
+ }
43
+ return out
44
+ } catch {
45
+ return []
46
+ }
47
+ }
48
+
49
+ export function writeEdges(edges: Edge[]): void {
50
+ const dir = dirname(EDGES_FILE)
51
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
52
+ const sorted = [...edges]
53
+ .filter((e) => e.from && e.to && e.from !== e.to)
54
+ .sort((a, b) => a.from.localeCompare(b.from) || a.to.localeCompare(b.to) || a.type.localeCompare(b.type))
55
+ .slice(0, MAX_EDGES)
56
+ const header = `version: 1\nedges[${sorted.length}|]{from|to|type|weight|ts}:`
57
+ const lines = [header, ...sorted.map((e) => toToonLine([e.from, e.to, e.type, String(e.weight), e.ts]))]
58
+ withLockSync(EDGES_FILE, () => atomicWrite(EDGES_FILE, lines.join("\n")))
59
+ }
60
+
61
+ export function deriveEdges(data: string, feedback: FeedbackEvent[] = []): Edge[] {
62
+ const entries = parseEntries(data)
63
+ const keys = new Set(entries.map((e) => e.key))
64
+ const map = new Map<string, Edge>()
65
+ const add = (from: string, to: string, type: EdgeType, weight: number, ts: string) => {
66
+ if (!keys.has(from) || !keys.has(to) || from === to) return
67
+ const id = `${from}|${to}|${type}`
68
+ const prev = map.get(id)
69
+ if (prev) prev.weight = Math.max(prev.weight, weight)
70
+ else map.set(id, { from, to, type, weight, ts })
71
+ }
72
+
73
+ for (const e of entries) {
74
+ for (const link of e.links) {
75
+ const { type, key } = parseLinkToken(link)
76
+ add(e.key, key, normalizeType(type), 1, e.date)
77
+ }
78
+ }
79
+
80
+ for (const event of feedback) {
81
+ if (!event.task) continue
82
+ const haystack = event.task.toLowerCase()
83
+ const type: EdgeType = event.signal === "wrong" || event.signal === "outdated" ? "contradicts" : "used_in"
84
+ const weight = event.signal === "useful" ? 1 : 0.5
85
+ for (const key of keys) {
86
+ if (key === event.key) continue
87
+ if (!haystack.includes(key.toLowerCase())) continue
88
+ add(event.key, key, type, weight, event.ts.slice(0, 10))
89
+ }
90
+ }
91
+
92
+ return [...map.values()]
93
+ }
94
+
95
+ export function rebuildEdges(data: string, feedback: FeedbackEvent[] = []): number {
96
+ const edges = deriveEdges(data, feedback)
97
+ writeEdges(edges)
98
+ return edges.length
99
+ }