toon-memory 2.5.2 → 2.7.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.
- package/README.md +124 -3
- package/dist/cli/setup.js +463 -425
- package/mcp/server.js +2058 -1084
- package/package.json +4 -2
- package/skills/toon-memory.md +1 -0
- package/src/cli/agents.ts +184 -0
- package/src/cli/capture-toggle.ts +29 -0
- package/src/cli/commands.ts +532 -0
- package/src/cli/config-writer.ts +133 -0
- package/src/cli/constants.ts +56 -0
- package/src/cli/hooks.ts +202 -0
- package/src/cli/instructions.ts +35 -0
- package/src/cli/memory.ts +104 -0
- package/src/cli/opencode-plugin.ts +84 -0
- package/src/cli/setup.ts +5 -1596
- package/src/cli/types.ts +29 -0
- package/src/cli/watch.ts +169 -0
- package/src/lib/code-search.ts +192 -0
- package/src/lib/context.ts +658 -0
- package/src/lib/git.ts +263 -0
- package/src/lib/project-scan.ts +224 -0
- package/src/mcp/archive.ts +129 -0
- package/src/mcp/config.ts +88 -0
- package/src/mcp/consolidation.ts +70 -0
- package/src/mcp/crypto.ts +41 -0
- package/src/mcp/entries.ts +110 -0
- package/src/mcp/memory-io.ts +53 -0
- package/src/mcp/observations.ts +16 -0
- package/src/mcp/resources.ts +57 -0
- package/src/mcp/scoring.ts +77 -0
- package/src/mcp/server.ts +5 -1482
- package/src/mcp/tools.ts +826 -0
|
@@ -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 const normalize = (s: string) => s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
@@ -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
|
+
}
|