toon-memory 2.5.2 → 2.8.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,129 @@
1
+ import { readFileSync, existsSync } from "fs"
2
+ import { withLockSync } from "../lib/lock"
3
+ import { readMemory, writeMemory, safeWrite } from "./memory-io"
4
+ import { ensureMemoryFile, MEMORY_FILE, MEMORY_DIR, MAX_ENTRIES, ARCHIVE_DAYS, ARCHIVE_FILE } from "./config"
5
+ import { isExpired } from "./entries"
6
+ import { entryScoreForLine } from "./scoring"
7
+
8
+ /**
9
+ * Archive entries older than ARCHIVE_DAYS or with expired TTL.
10
+ * When `trimToMax` is set, also archive the lowest-importance entries
11
+ * until the active count is at or below MAX_ENTRIES.
12
+ */
13
+ export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archived: number; kept: number } {
14
+ const data = readMemory()
15
+ const lines = data.split("\n")
16
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
17
+
18
+ if (headerIdx === -1) return { archived: 0, kept: 0 }
19
+
20
+ const today = new Date()
21
+ const cutoff = new Date(today)
22
+ cutoff.setDate(cutoff.getDate() - ARCHIVE_DAYS)
23
+ const cutoffStr = cutoff.toISOString().split("T")[0]
24
+
25
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0)
26
+ const toArchive = new Set<number>()
27
+
28
+ entryLines.forEach((line, idx) => {
29
+ const parts = line.trim().split("|")
30
+ if (parts.length < 7) return
31
+ const date = parts[6]
32
+ const ttl = parts[7] || ""
33
+ if (date < cutoffStr || (ttl && isExpired(ttl))) toArchive.add(idx)
34
+ })
35
+
36
+ if (opts.trimToMax) {
37
+ const remaining = entryLines.length - toArchive.size
38
+ if (remaining > MAX_ENTRIES) {
39
+ const need = remaining - MAX_ENTRIES
40
+ const candidates = entryLines
41
+ .map((line, idx) => ({ idx, score: entryScoreForLine(line) }))
42
+ .filter((c) => !toArchive.has(c.idx))
43
+ .sort((a, b) => a.score - b.score)
44
+ for (let i = 0; i < need && i < candidates.length; i++) toArchive.add(candidates[i].idx)
45
+ }
46
+ }
47
+
48
+ if (toArchive.size === 0) return { archived: 0, kept: entryLines.length }
49
+
50
+ const toArchiveLines = entryLines.filter((_, idx) => toArchive.has(idx)).map((l) => l.trim())
51
+ const toKeepLines = entryLines.filter((_, idx) => !toArchive.has(idx)).map((l) => l.trim())
52
+
53
+ // Write archived entries
54
+ let archiveContent = ""
55
+ if (existsSync(ARCHIVE_FILE)) {
56
+ archiveContent = readFileSync(ARCHIVE_FILE, "utf-8")
57
+ } else {
58
+ archiveContent = `version: 1\narchived:\n`
59
+ }
60
+
61
+ const archiveLines = archiveContent.split("\n")
62
+ let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["))
63
+ if (archiveHeaderIdx === -1) {
64
+ archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`)
65
+ archiveHeaderIdx = archiveLines.length - 1
66
+ }
67
+
68
+ const archiveMatch = archiveLines[archiveHeaderIdx].match(/archived\[(\d+)\|/)
69
+ const archiveCount = archiveMatch ? parseInt(archiveMatch[1]) : 0
70
+
71
+ for (const entry of toArchiveLines) {
72
+ archiveLines.splice(archiveHeaderIdx + 1, 0, ` ${entry}`)
73
+ }
74
+ archiveLines[archiveHeaderIdx] = archiveLines[archiveHeaderIdx].replace(/archived\[\d+\|/, `[${archiveCount + toArchiveLines.length}|`)
75
+
76
+ safeWrite(ARCHIVE_FILE, archiveLines.join("\n"))
77
+
78
+ // Update main file
79
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${toKeepLines.length}|`)
80
+ const keepSet = new Set(toKeepLines)
81
+ const allEntryLines = lines.slice(headerIdx + 1)
82
+ const newEntryLines = allEntryLines.filter((l) => {
83
+ if (l.trim().length === 0) return false
84
+ return keepSet.has(l.trim())
85
+ })
86
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newEntryLines.map((l) => ` ${l.trim()}`))
87
+ writeMemory(lines.join("\n"))
88
+
89
+ return { archived: toArchiveLines.length, kept: toKeepLines.length }
90
+ }
91
+
92
+ /**
93
+ * Remove entries whose TTL has expired, run at server startup.
94
+ * Distinct from archiveOldEntries: pruning == hard delete of entries that
95
+ * have outlived their TTL. Runs entirely under the memory-file lock so parallel
96
+ * sessions can't corrupt the file mid-prune.
97
+ */
98
+ export function pruneExpiredEntries(): number {
99
+ ensureMemoryFile()
100
+ if (!existsSync(MEMORY_FILE)) return 0
101
+ let pruned = 0
102
+ withLockSync(MEMORY_FILE, () => {
103
+ const data = readMemory()
104
+ const lines = data.split("\n")
105
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries["))
106
+ if (headerIdx === -1) return
107
+
108
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
109
+ const kept = entryLines.filter((l) => {
110
+ const parts = l.trim().split("|")
111
+ if (parts.length < 8) return true
112
+ const ttl = parts[7] || ""
113
+ if (ttl && isExpired(ttl)) {
114
+ pruned++
115
+ return false
116
+ }
117
+ return true
118
+ })
119
+ if (pruned === 0) return
120
+
121
+ lines[headerIdx] = lines[headerIdx].replace(/entries\[\d+\|/, `[${kept.length}|`)
122
+ const keepSet = new Set(kept.map((l) => l.trim()))
123
+ const allEntryLines = lines.slice(headerIdx + 1)
124
+ const newLines = allEntryLines.filter((l) => l.trim().length === 0 || keepSet.has(l.trim()))
125
+ lines.splice(headerIdx + 1, allEntryLines.length, ...newLines.map((l) => (l.trim().length ? ` ${l.trim()}` : l)))
126
+ writeMemory(lines.join("\n"))
127
+ })
128
+ return pruned
129
+ }
@@ -0,0 +1,88 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs"
2
+ import { join } from "path"
3
+
4
+ /** Base directory for memory storage */
5
+ export const MEMORY_DIR = join(process.cwd(), ".toon-memory", "memory")
6
+
7
+ /** Main memory data file */
8
+ export const MEMORY_FILE = join(MEMORY_DIR, "data.toon")
9
+
10
+ /** Archive file for old entries */
11
+ export const ARCHIVE_FILE = join(MEMORY_DIR, "archive.toon")
12
+
13
+ /** Observations log written by capture hooks (opt-in, separate from memory) */
14
+ export const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
15
+
16
+ /** Configuration file for encryption settings */
17
+ export const CONFIG_FILE = join(MEMORY_DIR, "config.json")
18
+
19
+ /** Maximum active entries before auto-archive */
20
+ export const MAX_ENTRIES = 100
21
+
22
+ /** Days before entries are archived */
23
+ export const ARCHIVE_DAYS = 30
24
+
25
+ /** Encryption algorithm for AES-256-GCM */
26
+ export const ALGORITHM = "aes-256-gcm"
27
+
28
+ /** Memory configuration with encryption settings */
29
+ export interface MemoryConfig {
30
+ /** Whether encryption is enabled */
31
+ encrypted: boolean
32
+ /** Project-specific tag vocabulary discovered from dependencies (Hito 7). */
33
+ vocab?: Record<string, string[]>
34
+ }
35
+
36
+ /**
37
+ * Load memory configuration from config.json.
38
+ */
39
+ export function loadConfig(): MemoryConfig {
40
+ if (!existsSync(CONFIG_FILE)) {
41
+ return { encrypted: false }
42
+ }
43
+ try {
44
+ return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
45
+ } catch {
46
+ return { encrypted: false }
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Save memory configuration to config.json.
52
+ */
53
+ export function saveConfig(config: MemoryConfig): void {
54
+ ensureMemoryDir()
55
+ let existing: Partial<MemoryConfig> = {}
56
+ if (existsSync(CONFIG_FILE)) {
57
+ try {
58
+ existing = JSON.parse(readFileSync(CONFIG_FILE, "utf-8"))
59
+ } catch {
60
+ existing = {}
61
+ }
62
+ }
63
+ writeFileSync(CONFIG_FILE, JSON.stringify({ ...existing, ...config }, null, 2))
64
+ }
65
+
66
+ /**
67
+ * Get the encryption key from environment variable.
68
+ */
69
+ export function getKey(): string | undefined {
70
+ return process.env.TOON_MEMORY_KEY
71
+ }
72
+
73
+ /**
74
+ * Ensure memory directory exists, creating it if necessary.
75
+ */
76
+ export function ensureMemoryDir(): void {
77
+ if (!existsSync(MEMORY_DIR)) mkdirSync(MEMORY_DIR, { recursive: true })
78
+ }
79
+
80
+ /**
81
+ * Ensure memory file exists with default structure.
82
+ */
83
+ export function ensureMemoryFile(): void {
84
+ ensureMemoryDir()
85
+ if (!existsSync(MEMORY_FILE)) {
86
+ writeFileSync(MEMORY_FILE, "version: 1\nentries[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:\n")
87
+ }
88
+ }
@@ -0,0 +1,70 @@
1
+ import { readMemory, writeMemory } from "./memory-io"
2
+ import { mergeEntries } from "../lib/quality"
3
+
4
+ /**
5
+ * Deterministic consolidation: merge entries with the same key (combining
6
+ * tags, links, max confidence, latest date), then remove exact-content
7
+ * duplicates. No LLM involved.
8
+ */
9
+ export function consolidateEntries(): { removed: number; kept: number; duplicates: string[] } {
10
+ const data = readMemory()
11
+ const lines = data.split("\n")
12
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
13
+ if (headerIdx === -1) return { removed: 0, kept: 0, duplicates: [] }
14
+
15
+ const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0 && !l.startsWith(" summaries:"))
16
+
17
+ // Phase 1: Merge entries with the same key
18
+ const byKey = new Map<number, string>()
19
+ const keyOrder: number[] = []
20
+ const mergedAway: number[] = []
21
+
22
+ for (let i = 0; i < entryLines.length; i++) {
23
+ const line = entryLines[i].trim()
24
+ const parts = line.split("|")
25
+ if (parts.length < 3) continue
26
+ const key = parts[2]
27
+ const existingIdx = keyOrder.findIndex((idx) => {
28
+ const ep = entryLines[idx].trim().split("|")
29
+ return ep[2] === key
30
+ })
31
+ if (existingIdx !== -1) {
32
+ const mergedLine = mergeEntries(byKey.get(keyOrder[existingIdx])!, line)
33
+ byKey.set(keyOrder[existingIdx], mergedLine)
34
+ mergedAway.push(i)
35
+ } else {
36
+ byKey.set(i, line)
37
+ keyOrder.push(i)
38
+ }
39
+ }
40
+
41
+ // Phase 2: Remove exact-content duplicates (normalized)
42
+ const contentSeen = new Map<string, string>()
43
+ const order: string[] = []
44
+ const duplicates: string[] = []
45
+
46
+ for (const idx of keyOrder) {
47
+ const line = byKey.get(idx)!
48
+ const parts = line.split("|")
49
+ if (parts.length < 3) {
50
+ order.push(line)
51
+ continue
52
+ }
53
+ const content = (parts[3] || "").toLowerCase().replace(/\s+/g, " ").trim()
54
+ if (contentSeen.has(content)) {
55
+ duplicates.push(parts[2])
56
+ continue
57
+ }
58
+ contentSeen.set(content, line)
59
+ order.push(line)
60
+ }
61
+
62
+ const totalRemoved = mergedAway.length + duplicates.length
63
+ if (totalRemoved === 0) return { removed: 0, kept: order.length, duplicates: [] }
64
+
65
+ lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${order.length}|`)
66
+ lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...order.map((l) => ` ${l}`))
67
+ writeMemory(lines.join("\n"))
68
+
69
+ return { removed: totalRemoved, kept: order.length, duplicates }
70
+ }
@@ -0,0 +1,41 @@
1
+ import { randomBytes, createCipheriv, createDecipheriv } from "crypto"
2
+ import { ALGORITHM } from "./config"
3
+
4
+ /**
5
+ * Encrypt text using AES-256-GCM.
6
+ * @returns Encrypted string in format "iv:authTag:ciphertext"
7
+ */
8
+ export function encrypt(text: string, key: string): string {
9
+ const keyBuffer = Buffer.from(key, "hex")
10
+ const iv = randomBytes(16)
11
+ const cipher = createCipheriv(ALGORITHM, keyBuffer, iv)
12
+
13
+ let encrypted = cipher.update(text, "utf8", "hex")
14
+ encrypted += cipher.final("hex")
15
+
16
+ const authTag = cipher.getAuthTag()
17
+
18
+ return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`
19
+ }
20
+
21
+ /**
22
+ * Decrypt AES-256-GCM encrypted data.
23
+ */
24
+ export function decrypt(encryptedData: string, key: string): string {
25
+ const keyBuffer = Buffer.from(key, "hex")
26
+ const parts = encryptedData.split(":")
27
+ if (parts.length !== 3) {
28
+ throw new Error("Invalid encrypted data format: expected iv:authTag:ciphertext")
29
+ }
30
+ const [ivHex, authTagHex, encrypted] = parts
31
+
32
+ const iv = Buffer.from(ivHex, "hex")
33
+ const authTag = Buffer.from(authTagHex, "hex")
34
+ const decipher = createDecipheriv(ALGORITHM, keyBuffer, iv)
35
+ decipher.setAuthTag(authTag)
36
+
37
+ let decrypted = decipher.update(encrypted, "hex", "utf8")
38
+ decrypted += decipher.final("utf8")
39
+
40
+ return decrypted
41
+ }
@@ -0,0 +1,110 @@
1
+ import { randomBytes } from "crypto"
2
+
3
+ /**
4
+ * Generate a random 8-character hex ID for memory entries.
5
+ */
6
+ export function generateId(): string {
7
+ return randomBytes(4).toString("hex")
8
+ }
9
+
10
+ /**
11
+ * Parse a TTL value into an absolute date string (YYYY-MM-DD).
12
+ * Supports: exact dates (2026-07-17), relative days (7d, 30d).
13
+ * Returns empty string if no TTL.
14
+ */
15
+ export function parseTTL(ttl: string): string {
16
+ if (!ttl || !ttl.trim()) return ""
17
+ const trimmed = ttl.trim()
18
+ const dayMatch = trimmed.match(/^(\d+)d$/)
19
+ if (dayMatch) {
20
+ const days = parseInt(dayMatch[1])
21
+ const d = new Date()
22
+ d.setDate(d.getDate() + days)
23
+ return d.toISOString().split("T")[0]
24
+ }
25
+ if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed
26
+ return ""
27
+ }
28
+
29
+ /**
30
+ * Check if a TTL value has expired (date is in the past).
31
+ */
32
+ export function isExpired(ttl: string): boolean {
33
+ if (!ttl) return false
34
+ const ttlDate = parseTTL(ttl) || ttl
35
+ const today = new Date().toISOString().split("T")[0]
36
+ return ttlDate <= today
37
+ }
38
+
39
+ /** Built-in vocabulary for automatic tag inference */
40
+ export const TAG_VOCABULARY: Record<string, string[]> = {
41
+ "redis": ["redis", "cache", "caching", "memcached"],
42
+ "auth": ["auth", "authentication", "authorization", "login", "token", "jwt", "session", "oauth"],
43
+ "api": ["api", "endpoint", "rest", "graphql", "route", "router", "controller"],
44
+ "db": ["database", "db", "sql", "postgres", "mysql", "mongo", "query", "migration", "schema"],
45
+ "security": ["security", "encrypt", "decrypt", "vulnerability", "xss", "csrf", "cors", "sanitiz"],
46
+ "test": ["test", "testing", "vitest", "jest", "spec", "mock", "assert", "coverage"],
47
+ "deploy": ["deploy", "docker", "ci/cd", "github actions", "pipeline", "kubernetes", "k8s"],
48
+ "config": ["config", "configuration", "settings", "env", "environment", "dotenv"],
49
+ "performance": ["performance", "optimize", "benchmark", "latency", "throughput", "cache"],
50
+ "refactor": ["refactor", "cleanup", "restructure", "reorganize", "rework"],
51
+ "error": ["error", "exception", "throw", "catch", "handling", "retry", "fallback"],
52
+ "logging": ["log", "logging", "logger", "debug", "trace", "monitor", "observability"],
53
+ "types": ["typescript", "types", "type", "interface", "generic", "enum", "zod", "schema"],
54
+ "async": ["async", "await", "promise", "concurrent", "parallel", "worker", "queue"],
55
+ "state": ["state", "store", "redux", "context", "reducer", "action", "observable"],
56
+ "ui": ["ui", "component", "render", "dom", "css", "style", "layout", "responsive"],
57
+ "storage": ["storage", "file", "filesystem", "s3", "blob", "upload", "download"],
58
+ "email": ["email", "mail", "smtp", "sendgrid", "newsletter", "notification"],
59
+ "payment": ["payment", "stripe", "billing", "invoice", "checkout", "subscription"],
60
+ "webhook": ["webhook", "callback", "event", "listener", "hook"],
61
+ }
62
+
63
+ /**
64
+ * Infer tags from content and key by matching against vocabulary.
65
+ * The built-in vocabulary is always used; a project-specific `vocab`
66
+ * (discovered from dependencies at `init`) is matched on top of it.
67
+ * Returns semicolon-separated tags.
68
+ */
69
+ export function inferTags(content: string, key: string, vocab?: Record<string, string[]>): string {
70
+ const text = `${key} ${content}`.toLowerCase()
71
+ const matched: string[] = []
72
+ for (const [tag, keywords] of Object.entries(TAG_VOCABULARY)) {
73
+ if (keywords.some((kw) => text.includes(kw))) {
74
+ matched.push(tag)
75
+ }
76
+ }
77
+ if (vocab) {
78
+ for (const [tag, keywords] of Object.entries(vocab)) {
79
+ if (keywords.some((kw) => text.includes(kw))) {
80
+ matched.push(tag)
81
+ }
82
+ }
83
+ }
84
+ return matched.join(";")
85
+ }
86
+
87
+ /**
88
+ * Parse a relative date string into an absolute YYYY-MM-DD date.
89
+ * Supports: "24h", "7d", "30d", or an exact date "2026-07-10".
90
+ */
91
+ export function parseRelativeDate(since: string): string {
92
+ const trimmed = since.trim()
93
+ const hourMatch = trimmed.match(/^(\d+)h$/)
94
+ if (hourMatch) {
95
+ const d = new Date()
96
+ d.setHours(d.getHours() - parseInt(hourMatch[1]))
97
+ return d.toISOString().split("T")[0]
98
+ }
99
+ const dayMatch = trimmed.match(/^(\d+)d$/)
100
+ if (dayMatch) {
101
+ const d = new Date()
102
+ d.setDate(d.getDate() - parseInt(dayMatch[1]))
103
+ return d.toISOString().split("T")[0]
104
+ }
105
+ if (/^\d{4}-\d{2}-\d{2}$/.test(trimmed)) return trimmed
106
+ const today = new Date().toISOString().split("T")[0]
107
+ return today
108
+ }
109
+
110
+ export { normalize } from "../lib/utils"
@@ -0,0 +1,53 @@
1
+ import { withLockSync, atomicWrite, readUnderLock } from "../lib/lock"
2
+ import { loadConfig, ensureMemoryFile, MEMORY_FILE, getKey } from "./config"
3
+ import { encrypt, decrypt } from "./crypto"
4
+
5
+ /**
6
+ * Write `content` to a memory file atomically and safely across processes.
7
+ * Uses an advisory lock (temp+rename) so parallel sessions can't corrupt
8
+ * the same file. Encryption, if enabled, is applied by the caller.
9
+ */
10
+ export function safeWrite(file: string, content: string): void {
11
+ withLockSync(file, () => atomicWrite(file, content))
12
+ }
13
+
14
+ /**
15
+ * Read memory file, decrypting if encryption is enabled.
16
+ * Key is read from TOON_MEMORY_KEY env var.
17
+ */
18
+ export function readMemory(): string {
19
+ ensureMemoryFile()
20
+ const config = loadConfig()
21
+ const data = readUnderLock(MEMORY_FILE)
22
+
23
+ if (config.encrypted) {
24
+ const key = getKey()
25
+ if (!key) return ""
26
+ try {
27
+ return decrypt(data, key)
28
+ } catch {
29
+ return ""
30
+ }
31
+ }
32
+
33
+ return data
34
+ }
35
+
36
+ /**
37
+ * Write content to memory file, encrypting if encryption is enabled.
38
+ * Key is read from TOON_MEMORY_KEY env var.
39
+ */
40
+ export function writeMemory(content: string): void {
41
+ ensureMemoryFile()
42
+ const config = loadConfig()
43
+
44
+ if (config.encrypted) {
45
+ const key = getKey()
46
+ if (!key) return
47
+ const encrypted = encrypt(content, key)
48
+ safeWrite(MEMORY_FILE, encrypted)
49
+ return
50
+ }
51
+
52
+ safeWrite(MEMORY_FILE, content)
53
+ }
@@ -0,0 +1,16 @@
1
+ import { readFileSync, existsSync } from "fs"
2
+ import { OBSERVATIONS_FILE } from "./config"
3
+
4
+ /**
5
+ * Read captured activity from observations.toon (written by hooks).
6
+ */
7
+ export function readObservations(): Array<{ ts: string; session: string; agent: string; branch: string; tool: string; file: string; summary: string }> {
8
+ if (!existsSync(OBSERVATIONS_FILE)) return []
9
+ return readFileSync(OBSERVATIONS_FILE, "utf-8")
10
+ .split("\n")
11
+ .filter((l) => l.startsWith(" ") && l.includes("|"))
12
+ .map((l) => {
13
+ const p = l.trim().split("|")
14
+ return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
15
+ })
16
+ }
@@ -0,0 +1,57 @@
1
+ import type { McpServer } from "@modelcontextprotocol/server"
2
+ import { readMemory } from "./memory-io"
3
+ import { isExpired } from "./entries"
4
+ import { generateSystemPrimer } from "../lib/quality"
5
+
6
+ /**
7
+ * Register memory MCP resources (entries, stats, summaries).
8
+ */
9
+ export function registerResources(server: McpServer): void {
10
+ server.registerResource(
11
+ "memory-entries",
12
+ "toon://memory/entries",
13
+ { title: "Memory Entries", mimeType: "text/plain" },
14
+ async (uri) => {
15
+ const data = readMemory()
16
+ return { contents: [{ uri: uri.href, text: data }] }
17
+ }
18
+ )
19
+
20
+ server.registerResource(
21
+ "memory-stats",
22
+ "toon://memory/stats",
23
+ { title: "Memory Stats", mimeType: "text/plain" },
24
+ async (uri) => {
25
+ const data = readMemory()
26
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
27
+ const entries = lines.map((l) => {
28
+ const parts = l.trim().split("|")
29
+ return { category: parts[1] || "unknown", ttl: parts[7] || "" }
30
+ })
31
+ const byCategory: Record<string, number> = {}
32
+ for (const e of entries) {
33
+ byCategory[e.category] = (byCategory[e.category] || 0) + 1
34
+ }
35
+ const withTtl = entries.filter((e) => e.ttl).length
36
+ const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length
37
+ const text = [
38
+ `Entradas totales: ${entries.length}`,
39
+ `TTL: ${withTtl} con expiración, ${expired} expiradas`,
40
+ "Por categoría:",
41
+ ...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
42
+ ].join("\n")
43
+ return { contents: [{ uri: uri.href, text }] }
44
+ }
45
+ )
46
+
47
+ server.registerResource(
48
+ "memory-summaries",
49
+ "toon://memory/summaries",
50
+ { title: "Memory Summaries", mimeType: "text/plain" },
51
+ async (uri) => {
52
+ const data = readMemory()
53
+ const primer = generateSystemPrimer(data)
54
+ return { contents: [{ uri: uri.href, text: primer }] }
55
+ }
56
+ )
57
+ }
@@ -0,0 +1,77 @@
1
+ import { readMemory, writeMemory } from "./memory-io"
2
+ import { normalize } from "./entries"
3
+
4
+ /**
5
+ * Importance score for an entry: blends recency and access frequency.
6
+ * Deterministic — no LLM. Higher = more worth keeping.
7
+ */
8
+ export function entryScore(dateStr: string, accessed: number): number {
9
+ const days = (Date.now() - new Date(`${dateStr}T00:00:00`).getTime()) / 86400000
10
+ const recency = Math.max(0, 30 - days) / 30
11
+ const freq = Math.min(1, accessed / 5)
12
+ return recency * 0.6 + freq * 0.4
13
+ }
14
+
15
+ export function entryScoreForLine(line: string): number {
16
+ const parts = line.trim().split("|")
17
+ const date = parts[6] || new Date().toISOString().split("T")[0]
18
+ const accessed = parts.length > 8 ? parseInt(parts[8]) || 0 : 0
19
+ return entryScore(date, accessed)
20
+ }
21
+
22
+ /**
23
+ * Find entries related to the given text by fuzzy matching.
24
+ * Returns top N results ranked by match quality.
25
+ */
26
+ export function findRelatedEntries(text: string, excludeKey: string = "", limit: number = 3): Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; score: number }> {
27
+ const data = readMemory()
28
+ const lines = data.split("\n").filter((l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:"))
29
+ const queryTokens = normalize(text).split(" ").filter(Boolean)
30
+
31
+ const scored = lines
32
+ .map((line) => {
33
+ const trimmed = line.trim()
34
+ const parts = trimmed.split("|")
35
+ if (parts.length < 7) return null
36
+ const [id, cat, key, content, file, tags, date] = parts
37
+ if (key === excludeKey) return null
38
+ const searchStr = normalize(`${id} ${cat} ${key} ${content} ${file} ${tags}`)
39
+ let score = 0
40
+ for (const token of queryTokens) {
41
+ if (searchStr.includes(token)) score++
42
+ }
43
+ if (score === 0) return null
44
+ return { id, cat, key, content, file, tags, date, score }
45
+ })
46
+ .filter(Boolean)
47
+ .sort((a, b) => b!.score - a!.score)
48
+ .slice(0, limit)
49
+
50
+ return scored as Array<{ id: string; cat: string; key: string; content: string; file: string; tags: string; date: string; score: number }>
51
+ }
52
+
53
+ /**
54
+ * Increment the `accessed` counter for the given entry ids.
55
+ * Used by recall/suggest so frequently-used memories rank higher.
56
+ */
57
+ export function bumpAccessed(ids: string[]): void {
58
+ if (ids.length === 0) return
59
+ const idSet = new Set(ids)
60
+ const data = readMemory()
61
+ const lines = data.split("\n")
62
+ const headerIdx = lines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
63
+ if (headerIdx === -1) return
64
+
65
+ for (let i = headerIdx + 1; i < lines.length; i++) {
66
+ const line = lines[i]
67
+ if (!line.startsWith(" ") || !line.includes("|")) continue
68
+ if (line.startsWith(" summaries:")) break
69
+ const parts = line.trim().split("|")
70
+ if (idSet.has(parts[0])) {
71
+ const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1
72
+ parts[8] = String(accessed)
73
+ lines[i] = ` ${parts.join("|")}`
74
+ }
75
+ }
76
+ writeMemory(lines.join("\n"))
77
+ }