toon-memory 4.3.1 → 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/README.md +17 -11
- package/dist/cli/capture.js +3 -0
- package/dist/cli/setup.js +335 -141
- package/mcp/server.js +558 -131
- package/package.json +2 -2
- package/skills/toon-memory.md +3 -0
- package/src/cli/agents.ts +67 -0
- package/src/cli/commands.ts +59 -18
- package/src/cli/config-writer.ts +75 -10
- package/src/cli/constants.ts +7 -4
- package/src/cli/hooks.ts +1 -1
- package/src/cli/types.ts +2 -2
- package/src/lib/evidence.ts +118 -0
- package/src/lib/graph.ts +12 -2
- package/src/lib/quality.ts +13 -3
- package/src/mcp/archive.ts +16 -6
- package/src/mcp/config.ts +10 -0
- package/src/mcp/consolidation.ts +65 -0
- package/src/mcp/tools.ts +164 -7
- package/src/mcp/vault.ts +176 -0
- package/src/viewer/html.ts +126 -80
- package/src/viewer/index.ts +27 -27
- package/src/viewer/logo-isologo.svg +16 -0
- package/src/viewer/logo.svg +49 -0
- package/src/viewer/types.ts +5 -5
package/src/mcp/archive.ts
CHANGED
|
@@ -6,6 +6,16 @@ import { isExpired } from "./entries"
|
|
|
6
6
|
import { entryScoreForLine } from "./scoring"
|
|
7
7
|
import { parseToonLine } from "../lib/utils"
|
|
8
8
|
|
|
9
|
+
/** Match both header conventions: `entries[N|]` (MCP writers) and `[N|]` (CLI init). */
|
|
10
|
+
function findHeaderIdx(lines: string[]): number {
|
|
11
|
+
return lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Bump the entry count in a header line, preserving its `entries`/`archived` prefix if present. */
|
|
15
|
+
function bumpHeaderCount(line: string, count: number): string {
|
|
16
|
+
return line.replace(/^([a-z]+)?\[(\d+)\|/, (_m, pre: string) => `${pre || ""}[${count}|`)
|
|
17
|
+
}
|
|
18
|
+
|
|
9
19
|
/**
|
|
10
20
|
* Archive entries older than ARCHIVE_DAYS or with expired TTL.
|
|
11
21
|
* When `trimToMax` is set, also archive the lowest-importance entries
|
|
@@ -14,7 +24,7 @@ import { parseToonLine } from "../lib/utils"
|
|
|
14
24
|
export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archived: number; kept: number } {
|
|
15
25
|
const data = readMemory()
|
|
16
26
|
const lines = data.split("\n")
|
|
17
|
-
const headerIdx = lines
|
|
27
|
+
const headerIdx = findHeaderIdx(lines)
|
|
18
28
|
|
|
19
29
|
if (headerIdx === -1) return { archived: 0, kept: 0 }
|
|
20
30
|
|
|
@@ -67,18 +77,18 @@ export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archive
|
|
|
67
77
|
archiveHeaderIdx = archiveLines.length - 1
|
|
68
78
|
}
|
|
69
79
|
|
|
70
|
-
const archiveMatch = archiveLines[archiveHeaderIdx].match(
|
|
80
|
+
const archiveMatch = archiveLines[archiveHeaderIdx].match(/\[(\d+)\|/)
|
|
71
81
|
const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0
|
|
72
82
|
|
|
73
83
|
for (const entry of toArchiveLines) {
|
|
74
84
|
archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`)
|
|
75
85
|
}
|
|
76
|
-
archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx]
|
|
86
|
+
archiveLines[archiveHeaderIdx] = bumpHeaderCount(archiveLines[archiveHeaderIdx], archiveCount + toArchiveLines.length)
|
|
77
87
|
|
|
78
88
|
safeWrite(ARCHIVE_FILE, archiveLines.join("\n"))
|
|
79
89
|
|
|
80
90
|
// Update main file
|
|
81
|
-
lines[headerIdx] = lines[headerIdx]
|
|
91
|
+
lines[headerIdx] = bumpHeaderCount(lines[headerIdx], toKeepLines.length)
|
|
82
92
|
const keepSet = new Set(toKeepLines)
|
|
83
93
|
const allEntryLines = lines.slice(headerIdx + 1)
|
|
84
94
|
const newEntryLines = allEntryLines.filter((l) => {
|
|
@@ -104,7 +114,7 @@ export function pruneExpiredEntries(): number {
|
|
|
104
114
|
withLockSync(MEMORY_FILE, () => {
|
|
105
115
|
const data = readMemory()
|
|
106
116
|
const lines = data.split("\n")
|
|
107
|
-
const headerIdx = lines
|
|
117
|
+
const headerIdx = findHeaderIdx(lines)
|
|
108
118
|
if (headerIdx === -1) return
|
|
109
119
|
|
|
110
120
|
const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
|
|
@@ -120,7 +130,7 @@ export function pruneExpiredEntries(): number {
|
|
|
120
130
|
})
|
|
121
131
|
if (pruned === 0) return
|
|
122
132
|
|
|
123
|
-
lines[headerIdx] = lines[headerIdx]
|
|
133
|
+
lines[headerIdx] = bumpHeaderCount(lines[headerIdx], kept.length)
|
|
124
134
|
const keepSet = new Set(kept.map((l) => l.trim()))
|
|
125
135
|
const allEntryLines = lines.slice(headerIdx + 1)
|
|
126
136
|
const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()))
|
package/src/mcp/config.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"
|
|
2
2
|
import { join } from "path"
|
|
3
|
+
import { homedir } from "os"
|
|
3
4
|
|
|
4
5
|
/** Base directory for memory storage */
|
|
5
6
|
export const MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory")
|
|
@@ -13,6 +14,15 @@ export const ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon")
|
|
|
13
14
|
/** Observations log written by capture hooks (opt-in, separate from memory) */
|
|
14
15
|
export const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
|
|
15
16
|
|
|
17
|
+
/** Encrypted sidecar vault for secrets. Whole-file AES-256-GCM when TOON_MEMORY_KEY is set.
|
|
18
|
+
* Kept separate from data.toon so the main memory stays a readable, open format. */
|
|
19
|
+
export const SECRETS_FILE = join(MEMORY_DIR, "secrets.toon")
|
|
20
|
+
|
|
21
|
+
/** Optional global memory (cross-project conventions), merged on demand via memory_import_global.
|
|
22
|
+
* Overridable with TOON_MEMORY_GLOBAL_FILE for tests or custom locations. */
|
|
23
|
+
export const GLOBAL_FILE =
|
|
24
|
+
process.env.TOON_MEMORY_GLOBAL_FILE || join(homedir(), ".toon-memory", "memory", "global.toon")
|
|
25
|
+
|
|
16
26
|
/** Configuration file for encryption settings */
|
|
17
27
|
export const CONFIG_FILE = join(MEMORY_DIR, "config.json")
|
|
18
28
|
|
package/src/mcp/consolidation.ts
CHANGED
|
@@ -115,6 +115,71 @@ export function consolidateEntries(): { removed: number; kept: number; duplicate
|
|
|
115
115
|
return { removed: totalRemoved, kept: order.length, duplicates }
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Merge two TOON memory documents by key, preserving every field.
|
|
120
|
+
*
|
|
121
|
+
* Pure (no file I/O): local wins on ids; incoming entries merge into existing
|
|
122
|
+
* ones via mergeEntries (tags/links union, max confidence/priority, newest
|
|
123
|
+
* date/content). Used by memory_import_global — a one-shot, offline pull of
|
|
124
|
+
* cross-project conventions. Never a live dual-source recall, so the ranking
|
|
125
|
+
* pipeline is untouched.
|
|
126
|
+
*/
|
|
127
|
+
export function mergeMemoryFiles(
|
|
128
|
+
localData: string,
|
|
129
|
+
incomingData: string
|
|
130
|
+
): { data: string; added: number; updated: number } {
|
|
131
|
+
const isEntry = (l: string): boolean =>
|
|
132
|
+
l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
|
|
133
|
+
|
|
134
|
+
const localLines = localData.split("\n")
|
|
135
|
+
const headerIdx = localLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
|
|
136
|
+
|
|
137
|
+
let prefix: string[]
|
|
138
|
+
let summaries: string[]
|
|
139
|
+
let localEntryLines: string[]
|
|
140
|
+
|
|
141
|
+
if (headerIdx === -1) {
|
|
142
|
+
prefix = ["version: 1"]
|
|
143
|
+
summaries = []
|
|
144
|
+
localEntryLines = []
|
|
145
|
+
} else {
|
|
146
|
+
prefix = localLines.slice(0, headerIdx)
|
|
147
|
+
const body = localLines.slice(headerIdx + 1)
|
|
148
|
+
localEntryLines = body.filter(isEntry)
|
|
149
|
+
summaries = body.filter((l) => !isEntry(l))
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const merged = new Map<string, string>()
|
|
153
|
+
for (const line of localEntryLines) {
|
|
154
|
+
const parts = parseToonLine(line)
|
|
155
|
+
if (parts.length >= 3) merged.set(parts[2], line.trim())
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
let added = 0
|
|
159
|
+
let updated = 0
|
|
160
|
+
for (const line of incomingData.split("\n").filter(isEntry)) {
|
|
161
|
+
const parts = parseToonLine(line)
|
|
162
|
+
// Minimal legacy lines (id|category|key|content) are valid entries too.
|
|
163
|
+
if (parts.length < 3) continue
|
|
164
|
+
const key = parts[2]
|
|
165
|
+
const existing = merged.get(key)
|
|
166
|
+
if (existing === undefined) {
|
|
167
|
+
merged.set(key, line.trim())
|
|
168
|
+
added++
|
|
169
|
+
} else {
|
|
170
|
+
merged.set(key, mergeEntries(existing, line.trim()))
|
|
171
|
+
updated++
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const header = `[${merged.size}|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence|lastAccessed}:`
|
|
176
|
+
// Entries must keep the two-space TOON indent — parseEntries only reads
|
|
177
|
+
// lines starting with two spaces, so re-indent anything that lost it.
|
|
178
|
+
const indented = [...merged.values()].map((l) => (l.startsWith(" ") ? l : ` ${l}`))
|
|
179
|
+
const data = [...prefix, header, ...indented, ...summaries].join("\n")
|
|
180
|
+
return { data, added, updated }
|
|
181
|
+
}
|
|
182
|
+
|
|
118
183
|
/**
|
|
119
184
|
* Extract a (base, version) pair from a versioned key or content line.
|
|
120
185
|
* Matches "Use React 18", "React 18.2", "next 13.5.1", "vite ^5.0.0", etc.
|
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
|
|
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
|
-
|
|
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(
|
package/src/mcp/vault.ts
ADDED
|
@@ -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
|
+
}
|