toon-memory 4.3.2 → 4.3.3

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/mcp/tools.ts CHANGED
@@ -2,26 +2,28 @@ import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
2
2
  import { registerAppTool } from "@modelcontextprotocol/ext-apps/server"
3
3
  import { z } from "zod"
4
4
  import { readFileSync, writeFileSync, existsSync, copyFileSync, mkdirSync, readdirSync } from "fs"
5
- import { join, basename } from "path"
5
+ import { join, basename, dirname } from "path"
6
6
  import { readMemory, writeMemory, safeWrite } from "./memory-io"
7
- import { loadConfig, saveConfig, getKey, MEMORY_FILE, OBSERVATIONS_FILE, MEMORY_DIR, MAX_ENTRIES, getMaxEntries, ARCHIVE_FILE } from "./config"
7
+ import { loadConfig, saveConfig, getKey, MEMORY_FILE, OBSERVATIONS_FILE, MEMORY_DIR, MAX_ENTRIES, getMaxEntries, ARCHIVE_FILE, GLOBAL_FILE } from "./config"
8
8
  import { generateId, parseTTL, isExpired, inferTags, parseRelativeDate } from "./entries"
9
9
  import { findRelatedEntries, bumpAccessed } from "./scoring"
10
10
  import { readObservations } from "./observations"
11
11
  import { archiveOldEntries } from "./archive"
12
- import { consolidateEntries, consolidateVersions } from "./consolidation"
12
+ import { consolidateEntries, consolidateVersions, mergeMemoryFiles } from "./consolidation"
13
13
  import { readUnderLock } from "../lib/lock"
14
14
  import { encrypt, decrypt } from "./crypto"
15
+ import { storeSecret, getSecret, listSecrets, forgetSecret } from "./vault"
15
16
  import { graphRecallDetailed, renderCompact, renderIndex, fetchEntriesByIds, parseEntries, buildGraph, parseLinkToken, formatLink, typedLinks } from "../lib/graph"
16
17
  import { qualityScore, mergeEntries, generateSmartRecall } from "../lib/quality"
17
18
  import { generateContextBrief, generateContextGenerate, generateContextDiff, generateContextFocus, generateContextHealth, generateContextExport } from "../lib/context"
18
19
  import { coordinationView, resolveSessionId, currentBranch, SESSION_TTL_MS, getCurrentSessionFiles } from "../lib/sessions"
19
20
  import { fileMtimes } from "../lib/git"
20
21
  import { normalize, isExpiredLocal, tokenize, importance, estimateTokens, parseToonLine, toToonLine, escField, unescField } from "../lib/utils"
22
+ import { evidenceFor, detectContradictions } from "../lib/evidence"
21
23
  import { expandSynonyms } from "../lib/synonyms"
22
24
 
23
25
  /**
24
- * Register all 22 memory tools.
26
+ * Register all MCP memory tools (38 total across tools.ts).
25
27
  */
26
28
  export function registerTools(server: McpServer): void {
27
29
 
@@ -505,7 +507,21 @@ server.registerTool(
505
507
  const resolvedLinks = links
506
508
  ? links.split(/[\s;]+/).filter(Boolean).join(" ")
507
509
  : existingParts[9] || ""
508
- let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", "0", path_scope || "", origin, "", "", importance])
510
+
511
+ // Write-path intelligence (deterministic, no LLM): detect contradictions
512
+ // against warnings / critical decisions and annotate the entry with its
513
+ // evidence level (verified when the referenced file exists on disk).
514
+ const tagList = resolvedTags.split(";").map((t) => t.trim()).filter(Boolean)
515
+ const candidate = { key, content, category, tags: tagList }
516
+ const existingEntries = parseEntries(data)
517
+ const conflicts = detectContradictions(existingEntries, candidate)
518
+ const evidence = evidenceFor(
519
+ existingEntries,
520
+ candidate,
521
+ file || ""
522
+ )
523
+
524
+ let newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, "0", resolvedLinks, "", "", "", "0", path_scope || "", origin, "", "", importance, evidence])
509
525
  let action = "Saved"
510
526
  let mergeInfo = ""
511
527
  const tagsInferred = !tags && resolvedTags ? true : false
@@ -520,7 +536,7 @@ server.registerTool(
520
536
  const lastAccessed = ""
521
537
  const quality = verbatim ? 0.5 : qualityScore(resolvedTags, resolvedLinks, content, date, accessed, lastAccessed, origin)
522
538
  const confidence = 1.0
523
- newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active", "", importance])
539
+ newEntry = toToonLine([entryId, category, key, content, file || "", resolvedTags, date, resolvedTtl, String(accessed), resolvedLinks, quality.toFixed(2), String(confidence), lastAccessed, "0", path_scope || "", origin, "active", "", importance, evidence])
524
540
  const match = lines[headerIdx].match(/\[(\d+)\|/)
525
541
  const count = match ? parseInt(match[1]) : 0
526
542
  lines.splice(headerIdx + 1, 0, newEntry)
@@ -541,6 +557,12 @@ server.registerTool(
541
557
 
542
558
  const ttlMsg = resolvedTtl ? `\nā° TTL: ${resolvedTtl}` : ""
543
559
  const inferredMsg = tagsInferred ? `\nšŸ·ļø Inferred tags: ${resolvedTags}` : ""
560
+ const evidenceMsg = evidence ? `\nšŸ”Ž Evidence: ${evidence}` : ""
561
+ let conflictMsg = ""
562
+ if (conflicts.length > 0) {
563
+ const items = conflicts.map((c) => ` āš ļø [${c.category}] ${c.key} (${c.similarity}% overlap) — ${c.note}`).join("\n")
564
+ conflictMsg = `\n\nāš ļø Potential CONTRADICTION with existing memory:\n${items}\n → The new claim was saved but flagged (evidence: conflict). Re-check before trusting it over the existing entry.`
565
+ }
544
566
 
545
567
  const related = findRelatedEntries(`${key} ${content} ${resolvedTags}`, key, 3)
546
568
  let relatedMsg = ""
@@ -550,7 +572,7 @@ server.registerTool(
550
572
  }
551
573
 
552
574
  return {
553
- content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${relatedMsg}` }],
575
+ content: [{ type: "text" as const, text: `🧠 ${action}: ${category}/${key} (${entryId})\n${content}${ttlMsg}${inferredMsg}${archiveMsg}${mergeInfo}${evidenceMsg}${conflictMsg}${relatedMsg}` }],
554
576
  }
555
577
  }
556
578
  )
@@ -1130,6 +1152,76 @@ server.registerTool(
1130
1152
  }
1131
1153
  )
1132
1154
 
1155
+ // ── memory_secret ────────────────────────────────────────────────────────────
1156
+
1157
+ server.registerTool(
1158
+ "memory_secret",
1159
+ {
1160
+ title: "Encrypted Secrets Vault",
1161
+ description: "Store/retrieve secrets in the encrypted sidecar vault (secrets.toon, AES-256-GCM). Keeps data.toon readable and open while sensitive values stay encrypted at rest. Requires TOON_MEMORY_KEY. 'store' encrypts, 'get' decrypts, 'list' shows metadata only (no values), 'forget' removes.",
1162
+ inputSchema: {
1163
+ action: z.enum(["store", "get", "list", "forget"]).describe("store = encrypt + save; get = decrypt + return; list = metadata only; forget = remove."),
1164
+ key: z.string().optional().describe("Secret identifier (kebab-case). Required for store/get/forget."),
1165
+ value: z.string().optional().describe("The secret value to encrypt (store only)."),
1166
+ file: z.string().optional().default("").describe("Optional related file/line (e.g. .env, src/api.ts:40)."),
1167
+ tags: z.string().optional().default("").describe("Semicolon-separated metadata tags (e.g. api;token)."),
1168
+ ttl: z.string().optional().default("").describe("Time to live (e.g. 7d, 2026-07-17). Empty = no expiration."),
1169
+ },
1170
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
1171
+ },
1172
+ async ({ action, key, value, file, tags, ttl }) => {
1173
+ try {
1174
+ if (action === "store") {
1175
+ if (!key || !value) {
1176
+ return { content: [{ type: "text" as const, text: "āŒ 'store' needs both key and value." }] }
1177
+ }
1178
+ const { id, date } = storeSecret(key, value, { file: file || "", tags: tags || "", ttl: ttl || "" })
1179
+ const ref = ` Reference it from memory with: memory_remember(category: "knowledge", key: "${key}", content: "Stored in secrets vault", file: "${file || "secrets.toon"}", tags: "secret;vault")`
1180
+ return {
1181
+ content: [{ type: "text" as const, text: `šŸ” Stored secret "${key}" (${id}) on ${date}\n Value is AES-256-GCM encrypted at rest in secrets.toon.\n${ref}` }],
1182
+ }
1183
+ }
1184
+
1185
+ if (action === "get") {
1186
+ if (!key) return { content: [{ type: "text" as const, text: "āŒ 'get' needs a key." }] }
1187
+ const hit = getSecret(key)
1188
+ if (!hit) {
1189
+ return { content: [{ type: "text" as const, text: `āŒ No secret "${key}" in the vault. Run memory_secret(action: "list") to see stored keys.` }] }
1190
+ }
1191
+ const meta = `Secret: ${key} Ā· file: ${hit.file || "—"} Ā· tags: ${hit.tags.join(";") || "—"} Ā· date: ${hit.date}${hit.ttl ? ` Ā· ttl: ${hit.ttl}` : ""}`
1192
+ return {
1193
+ content: [{ type: "text" as const, text: `${meta}\n\n${hit.value}` }],
1194
+ }
1195
+ }
1196
+
1197
+ if (action === "list") {
1198
+ const list = listSecrets()
1199
+ if (list.length === 0) {
1200
+ return { content: [{ type: "text" as const, text: "šŸ” Vault is empty." }] }
1201
+ }
1202
+ const rows = list
1203
+ .map((s) => ` Ā· ${s.key}${s.file ? ` (${s.file})` : ""} — saved ${s.date}${s.ttl ? ` Ā· ttl ${s.ttl}` : ""} [${s.id}]`)
1204
+ .join("\n")
1205
+ return {
1206
+ content: [{ type: "text" as const, text: `šŸ” ${list.length} secret(s) in vault (values stay encrypted):\n${rows}\n\nGet a value with memory_secret(action: "get", key: "<key>")` }],
1207
+ }
1208
+ }
1209
+
1210
+ if (action === "forget") {
1211
+ if (!key) return { content: [{ type: "text" as const, text: "āŒ 'forget' needs a key." }] }
1212
+ const removed = forgetSecret(key)
1213
+ return {
1214
+ content: [{ type: "text" as const, text: removed ? `šŸ—‘ļø Removed secret "${key}" from the vault.` : `āŒ No secret "${key}" in the vault.` }],
1215
+ }
1216
+ }
1217
+
1218
+ return { content: [{ type: "text" as const, text: "āŒ Unknown action." }] }
1219
+ } catch (err) {
1220
+ return { content: [{ type: "text" as const, text: `āŒ ${err instanceof Error ? err.message : String(err)}` }] }
1221
+ }
1222
+ }
1223
+ )
1224
+
1133
1225
  // ── memory_captured ──────────────────────────────────────────────────────────
1134
1226
 
1135
1227
  server.registerTool(
@@ -1732,6 +1824,71 @@ server.registerTool(
1732
1824
  }
1733
1825
  )
1734
1826
 
1827
+ // ── memory_export_global / memory_import_global ──────────────────────────
1828
+ // Cross-project conventions live in ~/.toon-memory/memory/global.toon. They
1829
+ // are pulled into a project with a one-shot merge (offline, deterministic) —
1830
+ // never a live dual-source recall, so the ranking pipeline stays untouched.
1831
+
1832
+ server.registerTool(
1833
+ "memory_export_global",
1834
+ {
1835
+ title: "Export to Global Memory",
1836
+ description: "Write the current project memory to the global memory file (~/.toon-memory/memory/global.toon, or TOON_MEMORY_GLOBAL_FILE). One-shot: the global file is a plain TOON document you curate and import into other projects with memory_import_global.",
1837
+ inputSchema: {
1838
+ target: z.string().optional().describe("Override the global file path (defaults to TOON_MEMORY_GLOBAL_FILE or ~/.toon-memory/memory/global.toon)."),
1839
+ },
1840
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
1841
+ },
1842
+ async ({ target }) => {
1843
+ const dest = target || GLOBAL_FILE
1844
+ const data = readMemory()
1845
+ mkdirSync(dirname(dest), { recursive: true })
1846
+ safeWrite(dest, data)
1847
+ const count = parseEntries(data).length
1848
+ return {
1849
+ content: [{ type: "text" as const, text: `šŸ“¤ Exported ${count} entries to global memory:\n ${dest}\n\nImport them elsewhere with memory_import_global.` }],
1850
+ }
1851
+ }
1852
+ )
1853
+
1854
+ server.registerTool(
1855
+ "memory_import_global",
1856
+ {
1857
+ title: "Import Global Memory",
1858
+ description: "Merge cross-project conventions from the global memory file (~/.toon-memory/memory/global.toon, or TOON_MEMORY_GLOBAL_FILE) into this project. One-shot merge by key: keeps newer dates, unions tags/links, preserves all fields. Deterministic and offline.",
1859
+ inputSchema: {
1860
+ merge: z.boolean().optional().default(true).describe("If true, merge with existing memory (default). If false, replace entirely."),
1861
+ source: z.string().optional().describe("Override the global file path (defaults to TOON_MEMORY_GLOBAL_FILE or ~/.toon-memory/memory/global.toon)."),
1862
+ },
1863
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },
1864
+ },
1865
+ async ({ merge, source }) => {
1866
+ const src = source || GLOBAL_FILE
1867
+ if (!existsSync(src)) {
1868
+ return {
1869
+ content: [{ type: "text" as const, text: `āŒ No global memory at:\n ${src}\n\nExport from another project with memory_export_global, or create the file with a few memory entries first.` }],
1870
+ }
1871
+ }
1872
+ const globalData = readFileSync(src, "utf-8")
1873
+
1874
+ if (!merge) {
1875
+ safeWrite(MEMORY_FILE, globalData)
1876
+ const count = parseEntries(globalData).length
1877
+ return {
1878
+ content: [{ type: "text" as const, text: `šŸ“„ Memory replaced from global (${count} entries).` }],
1879
+ }
1880
+ }
1881
+
1882
+ const localData = readMemory()
1883
+ const { data, added, updated } = mergeMemoryFiles(localData, globalData)
1884
+ writeMemory(data)
1885
+ const total = parseEntries(data).length
1886
+ return {
1887
+ content: [{ type: "text" as const, text: `šŸ“„ Global memory merged\n Added: ${added} new entries\n Updated: ${updated} existing entries\n Total: ${total} entries` }],
1888
+ }
1889
+ }
1890
+ )
1891
+
1735
1892
  // ── memory_merge_sessions ──────────────────────────────────────────────
1736
1893
 
1737
1894
  server.registerTool(
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Encrypted sidecar vault for secrets.
3
+ *
4
+ * The main memory file (data.toon) stays a readable, open TOON format — that
5
+ * is the product's philosophy. But that means credentials and API keys cannot
6
+ * live there. `secrets.toon` is a whole-file AES-256-GCM vault (reusing the
7
+ * main crypto) that keeps secret values out of plaintext while the rest of the
8
+ * memory remains open.
9
+ *
10
+ * Internal layout is the same TOON line format, one entry per secret:
11
+ * `id|secret|key|iv:authTag:ciphertext|file|tags|date|ttl|0|links|...`
12
+ * Only the `content` field carries the encrypted value; the whole file is then
13
+ * encrypted again at rest, so no metadata leaks either. Requires
14
+ * TOON_MEMORY_KEY (same key as memory_encrypt). Deterministic, offline.
15
+ */
16
+
17
+ import { existsSync } from "fs"
18
+ import { generateId, parseTTL } from "./entries"
19
+ import { SECRETS_FILE, getKey } from "./config"
20
+ import { encrypt, decrypt } from "./crypto"
21
+ import { safeWrite } from "./memory-io"
22
+ import { readUnderLock } from "../lib/lock"
23
+ import { parseToonLine, toToonLine } from "../lib/utils"
24
+
25
+ const VAULT_HEADER = "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links}:\n"
26
+
27
+ /** Resolve the vault key or throw a friendly error telling the user how to fix it. */
28
+ export function vaultKey(): string {
29
+ const key = getKey()
30
+ if (!key) {
31
+ throw new Error(
32
+ "TOON_MEMORY_KEY is not set — the secrets vault needs it.\n export TOON_MEMORY_KEY=<64-hex-char-key>\n (generate one with: node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\")"
33
+ )
34
+ }
35
+ return key
36
+ }
37
+
38
+ /** Read the vault and return its decrypted TOON content ("" when the vault doesn't exist yet). */
39
+ export function readVault(): string {
40
+ if (!existsSync(SECRETS_FILE)) return ""
41
+ const key = vaultKey()
42
+ const raw = readUnderLock(SECRETS_FILE)
43
+ try {
44
+ return decrypt(raw, key)
45
+ } catch {
46
+ throw new Error("Failed to decrypt secrets.toon — wrong TOON_MEMORY_KEY or corrupted vault.")
47
+ }
48
+ }
49
+
50
+ /** Encrypt the given TOON content and persist it to secrets.toon (atomic + locked). */
51
+ export function writeVault(content: string): void {
52
+ const key = vaultKey()
53
+ safeWrite(SECRETS_FILE, encrypt(content, key))
54
+ }
55
+
56
+ /** Parse vault content into a map of key -> { id, file, tags, date, ttl } plus the ciphertext. */
57
+ function vaultEntries(content: string): Array<{ id: string; key: string; value: string; file: string; tags: string; date: string; ttl: string }> {
58
+ const out: Array<{ id: string; key: string; value: string; file: string; tags: string; date: string; ttl: string }> = []
59
+ for (const line of content.split("\n")) {
60
+ if (!line.startsWith(" ") || !line.includes("|")) continue
61
+ const parts = parseToonLine(line)
62
+ if (parts.length < 7) continue
63
+ out.push({ id: parts[0], key: parts[2], value: parts[3] || "", file: parts[4] || "", tags: parts[5] || "", date: parts[6] || "", ttl: parts[7] || "" })
64
+ }
65
+ return out
66
+ }
67
+
68
+ /** Rebuild the vault TOON content from a list of parsed secrets. */
69
+ function rebuildVault(list: Array<{ id: string; key: string; value: string; file: string; tags: string; date: string; ttl: string }>): string {
70
+ const lines = [
71
+ "version: 1",
72
+ `[${list.length}|]{id|category|key|content|file|tags|date|ttl|accessed|links}:`,
73
+ ...list.map((s) =>
74
+ toToonLine([s.id, "secret", s.key, s.value, s.file, s.tags, s.date, s.ttl, "0", ""])
75
+ ),
76
+ ]
77
+ return lines.join("\n")
78
+ }
79
+
80
+ export interface StoredSecret {
81
+ key: string
82
+ value: string
83
+ file: string
84
+ tags: string[]
85
+ date: string
86
+ ttl: string
87
+ }
88
+
89
+ export interface SecretMeta {
90
+ id: string
91
+ key: string
92
+ file: string
93
+ tags: string[]
94
+ date: string
95
+ ttl: string
96
+ }
97
+
98
+ /** Store (or overwrite) a secret. The value is AES-256-GCM encrypted at rest. */
99
+ export function storeSecret(
100
+ key: string,
101
+ value: string,
102
+ opts: { file?: string; tags?: string; ttl?: string } = {}
103
+ ): { id: string; date: string } {
104
+ if (!value) throw new Error("A secret needs a non-empty value.")
105
+ const vk = vaultKey()
106
+ const encrypted = encrypt(value, vk)
107
+ const content = readVault()
108
+ const list = vaultEntries(content)
109
+ const date = new Date().toISOString().split("T")[0]
110
+ const resolvedTtl = parseTTL(opts.ttl || "")
111
+
112
+ const existing = list.find((s) => s.key === key)
113
+ const id = existing ? existing.id : generateId()
114
+ const merged: Array<{ id: string; key: string; value: string; file: string; tags: string; date: string; ttl: string }> = []
115
+ for (const s of list) {
116
+ if (s.key === key) {
117
+ merged.push({ id, key, value: encrypted, file: opts.file || s.file, tags: opts.tags || s.tags, date, ttl: resolvedTtl || s.ttl })
118
+ } else {
119
+ merged.push(s)
120
+ }
121
+ }
122
+ if (!existing) {
123
+ merged.push({ id, key, value: encrypted, file: opts.file || "", tags: opts.tags || "", date, ttl: resolvedTtl })
124
+ }
125
+
126
+ writeVault(rebuildVault(merged))
127
+ return { id, date }
128
+ }
129
+
130
+ /** Retrieve a secret's decrypted value plus metadata. Returns null when not found. */
131
+ export function getSecret(key: string): StoredSecret | null {
132
+ const content = readVault()
133
+ if (!content) return null
134
+ const hit = vaultEntries(content).find((s) => s.key === key)
135
+ if (!hit) return null
136
+ const vk = vaultKey()
137
+ let value: string
138
+ try {
139
+ value = decrypt(hit.value, vk)
140
+ } catch {
141
+ throw new Error(`Failed to decrypt secret "${key}" — wrong TOON_MEMORY_KEY or corrupted value.`)
142
+ }
143
+ return {
144
+ key,
145
+ value,
146
+ file: hit.file,
147
+ tags: hit.tags.split(";").map((t) => t.trim()).filter(Boolean),
148
+ date: hit.date,
149
+ ttl: hit.ttl,
150
+ }
151
+ }
152
+
153
+ /** List vault metadata (keys, files, dates) without decrypting any value. */
154
+ export function listSecrets(): SecretMeta[] {
155
+ const content = readVault()
156
+ if (!content) return []
157
+ return vaultEntries(content).map((s) => ({
158
+ id: s.id,
159
+ key: s.key,
160
+ file: s.file,
161
+ tags: s.tags.split(";").map((t) => t.trim()).filter(Boolean),
162
+ date: s.date,
163
+ ttl: s.ttl,
164
+ }))
165
+ }
166
+
167
+ /** Remove a secret by key. Returns false when the key did not exist. */
168
+ export function forgetSecret(key: string): boolean {
169
+ const content = readVault()
170
+ if (!content) return false
171
+ const list = vaultEntries(content)
172
+ const next = list.filter((s) => s.key !== key)
173
+ if (next.length === list.length) return false
174
+ writeVault(rebuildVault(next))
175
+ return true
176
+ }