toon-memory 2.7.0 → 2.9.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 +4 -3
- package/dist/cli/capture.js +41 -10
- package/dist/cli/session-start.js +6 -6
- package/dist/cli/setup.js +36 -33
- package/mcp/server.js +324 -325
- package/package.json +2 -6
- package/src/cli/agents.ts +8 -5
- package/src/cli/capture-toggle.ts +4 -4
- package/src/cli/capture.ts +5 -0
- package/src/cli/commands.ts +15 -15
- package/src/cli/constants.ts +1 -1
- package/src/cli/session-start.ts +6 -6
- package/src/cli/setup.ts +8 -8
- package/src/lib/context.ts +83 -83
- package/src/lib/git.ts +10 -11
- package/src/lib/graph.ts +2 -20
- package/src/lib/quality.ts +17 -31
- package/src/lib/utils.ts +25 -0
- package/src/mcp/archive.ts +5 -4
- package/src/mcp/config.ts +9 -1
- package/src/mcp/entries.ts +1 -1
- package/src/mcp/observations.ts +28 -1
- package/src/mcp/resources.ts +3 -3
- package/src/mcp/scoring.ts +3 -6
- package/src/mcp/tools.ts +191 -190
package/src/lib/git.ts
CHANGED
|
@@ -89,26 +89,25 @@ function parseIndex(dir: string): IndexEntry[] {
|
|
|
89
89
|
const sha = buf.slice(offset + 32, offset + 52).toString("hex")
|
|
90
90
|
const flags = buf.readUInt16BE(offset + 52)
|
|
91
91
|
|
|
92
|
-
//
|
|
92
|
+
// v3/v4 entries have an extra 4-byte extended entry field after the standard 62 bytes
|
|
93
|
+
let nameOffset = 62
|
|
94
|
+
if (version >= 3) {
|
|
95
|
+
nameOffset += 4
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Name starts at entryStart + nameOffset, null-terminated, padded to 8-byte alignment
|
|
93
99
|
const nameLen = flags & 0x0fff
|
|
94
|
-
const nameStart = entryStart +
|
|
100
|
+
const nameStart = entryStart + nameOffset
|
|
95
101
|
let name: string
|
|
96
102
|
if (nameLen > 0 && nameStart + nameLen <= buf.length) {
|
|
97
103
|
name = buf.toString("utf-8", nameStart, nameStart + nameLen)
|
|
98
104
|
} else {
|
|
99
|
-
// Read until null byte
|
|
100
105
|
const end = buf.indexOf(0, nameStart)
|
|
101
106
|
name = end >= 0 ? buf.toString("utf-8", nameStart, end) : buf.toString("utf-8", nameStart)
|
|
102
107
|
}
|
|
103
108
|
|
|
104
|
-
//
|
|
105
|
-
|
|
106
|
-
// In v3, there's an extra 4-byte field (padding/extended)
|
|
107
|
-
// The name starts at entryStart + 62 regardless in v2-v4
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// Compute total entry size: 62 bytes + name length, padded to 8-byte boundary
|
|
111
|
-
const rawLen = 62 + name.length
|
|
109
|
+
// Compute total entry size: base bytes + name length, padded to 8-byte boundary
|
|
110
|
+
const rawLen = nameOffset + name.length
|
|
112
111
|
const paddedLen = Math.ceil(rawLen / 8) * 8
|
|
113
112
|
offset = entryStart + paddedLen
|
|
114
113
|
|
package/src/lib/graph.ts
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
* without mutating the stored `.toon` file.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
|
|
18
|
+
|
|
17
19
|
export interface GraphEntry {
|
|
18
20
|
id: string
|
|
19
21
|
category: string
|
|
@@ -35,15 +37,6 @@ export interface MemoryGraph {
|
|
|
35
37
|
byKey: Map<string, GraphEntry>
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
const isExpiredLocal = (ttl: string): boolean => {
|
|
39
|
-
if (!ttl) return false
|
|
40
|
-
const today = new Date().toISOString().split("T")[0]
|
|
41
|
-
return ttl <= today
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const normalize = (s: string): string =>
|
|
45
|
-
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
46
|
-
|
|
47
40
|
const entryLines = (data: string): string[] =>
|
|
48
41
|
data
|
|
49
42
|
.split("\n")
|
|
@@ -125,17 +118,6 @@ export interface GraphRecallOpts {
|
|
|
125
118
|
limit?: number
|
|
126
119
|
}
|
|
127
120
|
|
|
128
|
-
const importance = (e: GraphEntry): number => {
|
|
129
|
-
const today = new Date().toISOString().split("T")[0]
|
|
130
|
-
const days =
|
|
131
|
-
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
132
|
-
const recency = Math.max(0, 30 - days) / 30
|
|
133
|
-
const freq = Math.min(1, e.accessed / 5)
|
|
134
|
-
return recency * 0.6 + freq * 0.4
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
|
138
|
-
|
|
139
121
|
/**
|
|
140
122
|
* BM25 relevance of each entry for the query. Deterministic and offline.
|
|
141
123
|
* Returns a map key -> score (0 when the entry shares no query token).
|
package/src/lib/quality.ts
CHANGED
|
@@ -8,26 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { parseEntries, buildGraph, bm25Scores, centrality, renderCompact, type GraphEntry } from "./graph"
|
|
11
|
-
|
|
12
|
-
const normalize = (s: string): string =>
|
|
13
|
-
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
14
|
-
|
|
15
|
-
const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
|
16
|
-
|
|
17
|
-
const isExpiredLocal = (ttl: string): boolean => {
|
|
18
|
-
if (!ttl) return false
|
|
19
|
-
const today = new Date().toISOString().split("T")[0]
|
|
20
|
-
return ttl <= today
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const importance = (e: GraphEntry): number => {
|
|
24
|
-
const today = new Date().toISOString().split("T")[0]
|
|
25
|
-
const days =
|
|
26
|
-
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
27
|
-
const recency = Math.max(0, 30 - days) / 30
|
|
28
|
-
const freq = Math.min(1, e.accessed / 5)
|
|
29
|
-
return recency * 0.6 + freq * 0.4
|
|
30
|
-
}
|
|
11
|
+
import { normalize, isExpiredLocal, tokenize, importance } from "./utils"
|
|
31
12
|
|
|
32
13
|
/**
|
|
33
14
|
* Quality score for an entry (0..1). Pure heuristics, no LLM.
|
|
@@ -92,7 +73,12 @@ export function mergeEntries(existingLine: string, newLine: string): string {
|
|
|
92
73
|
const newTtl = np[7] || ""
|
|
93
74
|
const ttl = newTtl || existingTtl
|
|
94
75
|
|
|
95
|
-
//
|
|
76
|
+
// Preserve existing accessed count (field 8)
|
|
77
|
+
const existingAccessed = ep.length > 8 ? parseInt(ep[8]) || 0 : 0
|
|
78
|
+
const newAccessed = np.length > 8 ? parseInt(np[8]) || 0 : 0
|
|
79
|
+
const accessed = Math.max(existingAccessed, newAccessed)
|
|
80
|
+
|
|
81
|
+
// Take max confidence — handle entries with <12 fields gracefully
|
|
96
82
|
const existingConf = ep.length > 11 ? parseFloat(ep[11]) || 0 : 0
|
|
97
83
|
const newConf = np.length > 11 ? parseFloat(np[11]) || 0 : 0
|
|
98
84
|
const confidence = Math.max(existingConf, newConf)
|
|
@@ -104,7 +90,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
|
|
|
104
90
|
|
|
105
91
|
const quality = qualityScore(mergedTags, mergedLinks, content, date)
|
|
106
92
|
|
|
107
|
-
return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}
|
|
93
|
+
return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}`
|
|
108
94
|
}
|
|
109
95
|
|
|
110
96
|
/**
|
|
@@ -117,7 +103,7 @@ export function generateSmartRecall(
|
|
|
117
103
|
opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void } = {}
|
|
118
104
|
): string {
|
|
119
105
|
const entries = parseEntries(data)
|
|
120
|
-
if (entries.length === 0) return "
|
|
106
|
+
if (entries.length === 0) return "Empty memory."
|
|
121
107
|
|
|
122
108
|
const { adjacency } = buildGraph(entries)
|
|
123
109
|
const bm25 = bm25Scores(entries, intent)
|
|
@@ -154,7 +140,7 @@ export function generateSmartRecall(
|
|
|
154
140
|
.filter((e) => !category || e.category === category)
|
|
155
141
|
.sort((a, b) => importance(b) - importance(a))
|
|
156
142
|
.slice(0, limit)
|
|
157
|
-
if (top.length === 0) return "No
|
|
143
|
+
if (top.length === 0) return "No entries in memory."
|
|
158
144
|
return renderCompact(top)
|
|
159
145
|
}
|
|
160
146
|
|
|
@@ -168,7 +154,7 @@ export function generateSmartRecall(
|
|
|
168
154
|
*/
|
|
169
155
|
export function generateSystemPrimer(data: string): string {
|
|
170
156
|
const entries = parseEntries(data)
|
|
171
|
-
if (entries.length === 0) return "
|
|
157
|
+
if (entries.length === 0) return "Empty memory. No entries saved."
|
|
172
158
|
|
|
173
159
|
const byCategory: Record<string, GraphEntry[]> = {}
|
|
174
160
|
for (const e of entries) {
|
|
@@ -178,7 +164,7 @@ export function generateSystemPrimer(data: string): string {
|
|
|
178
164
|
|
|
179
165
|
const lines: string[] = [
|
|
180
166
|
"=== System Primer ===",
|
|
181
|
-
`
|
|
167
|
+
`Entries: ${entries.length}`,
|
|
182
168
|
"",
|
|
183
169
|
]
|
|
184
170
|
|
|
@@ -186,7 +172,7 @@ export function generateSystemPrimer(data: string): string {
|
|
|
186
172
|
const top = [...entries]
|
|
187
173
|
.sort((a, b) => importance(b) - importance(a))
|
|
188
174
|
.slice(0, 5)
|
|
189
|
-
lines.push("Top
|
|
175
|
+
lines.push("Top memories:")
|
|
190
176
|
for (const e of top) {
|
|
191
177
|
const quality = qualityScore(
|
|
192
178
|
e.tags.join(";"),
|
|
@@ -194,15 +180,15 @@ export function generateSystemPrimer(data: string): string {
|
|
|
194
180
|
e.content,
|
|
195
181
|
e.date
|
|
196
182
|
)
|
|
197
|
-
const conf = quality >= 0.5 ? "
|
|
183
|
+
const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low"
|
|
198
184
|
lines.push(
|
|
199
|
-
` [${e.category}] ${e.key} — ${e.content.slice(0, 80)} (
|
|
185
|
+
` [${e.category}] ${e.key} — ${e.content.slice(0, 80)} (quality: ${conf})`
|
|
200
186
|
)
|
|
201
187
|
}
|
|
202
188
|
lines.push("")
|
|
203
189
|
|
|
204
190
|
// Categories
|
|
205
|
-
lines.push("
|
|
191
|
+
lines.push("Categories:")
|
|
206
192
|
for (const [cat, items] of Object.entries(byCategory)) {
|
|
207
193
|
lines.push(` ${cat}: ${items.length}`)
|
|
208
194
|
}
|
|
@@ -211,7 +197,7 @@ export function generateSystemPrimer(data: string): string {
|
|
|
211
197
|
// Rules (mandatory patterns)
|
|
212
198
|
const patterns = entries.filter((e) => e.category === "pattern")
|
|
213
199
|
if (patterns.length > 0) {
|
|
214
|
-
lines.push("
|
|
200
|
+
lines.push("Established patterns:")
|
|
215
201
|
for (const p of patterns.slice(0, 5)) {
|
|
216
202
|
lines.push(` • ${p.key}: ${p.content.slice(0, 100)}`)
|
|
217
203
|
}
|
package/src/lib/utils.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared helper functions used across lib/ modules.
|
|
3
|
+
* Eliminates copy-paste duplication of normalize, isExpiredLocal, importance, tokenize.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export const normalize = (s: string): string =>
|
|
7
|
+
s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
|
|
8
|
+
|
|
9
|
+
export const isExpiredLocal = (ttl: string): boolean => {
|
|
10
|
+
if (!ttl) return false
|
|
11
|
+
const today = new Date().toISOString().split("T")[0]
|
|
12
|
+
return ttl <= today
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Lightweight importance score: recency (60%) + frequency (40%). */
|
|
16
|
+
export function importance(e: { date: string; accessed: number }): number {
|
|
17
|
+
const today = new Date().toISOString().split("T")[0]
|
|
18
|
+
const days =
|
|
19
|
+
(Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
|
|
20
|
+
const recency = Math.max(0, 30 - days) / 30
|
|
21
|
+
const freq = Math.min(1, e.accessed / 5)
|
|
22
|
+
return recency * 0.6 + freq * 0.4
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const tokenize = (s: string): string[] => normalize(s).split(" ").filter(Boolean)
|
package/src/mcp/archive.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readFileSync, existsSync } from "fs"
|
|
2
2
|
import { withLockSync } from "../lib/lock"
|
|
3
3
|
import { readMemory, writeMemory, safeWrite } from "./memory-io"
|
|
4
|
-
import { ensureMemoryFile, MEMORY_FILE, MEMORY_DIR,
|
|
4
|
+
import { ensureMemoryFile, MEMORY_FILE, MEMORY_DIR, getMaxEntries, ARCHIVE_DAYS, ARCHIVE_FILE } from "./config"
|
|
5
5
|
import { isExpired } from "./entries"
|
|
6
6
|
import { entryScoreForLine } from "./scoring"
|
|
7
7
|
|
|
@@ -35,8 +35,9 @@ export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archive
|
|
|
35
35
|
|
|
36
36
|
if (opts.trimToMax) {
|
|
37
37
|
const remaining = entryLines.length - toArchive.size
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
const maxEntries = getMaxEntries()
|
|
39
|
+
if (remaining > maxEntries) {
|
|
40
|
+
const need = remaining - maxEntries
|
|
40
41
|
const candidates = entryLines
|
|
41
42
|
.map((line, idx) => ({ idx, score: entryScoreForLine(line) }))
|
|
42
43
|
.filter((c) => !toArchive.has(c.idx))
|
|
@@ -61,7 +62,7 @@ export function archiveOldEntries(opts: { trimToMax?: boolean } = {}): { archive
|
|
|
61
62
|
const archiveLines = archiveContent.split("\n")
|
|
62
63
|
let archiveHeaderIdx = archiveLines.findIndex((l) => l.startsWith("archived["))
|
|
63
64
|
if (archiveHeaderIdx === -1) {
|
|
64
|
-
archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date}:`)
|
|
65
|
+
archiveLines.push(`archived[0|]{id|category|key|content|file|tags|date|ttl|accessed|links|quality|confidence}:`)
|
|
65
66
|
archiveHeaderIdx = archiveLines.length - 1
|
|
66
67
|
}
|
|
67
68
|
|
package/src/mcp/config.ts
CHANGED
|
@@ -16,7 +16,13 @@ export const OBSERVATIONS_FILE = join(MEMORY_DIR, "observations.toon")
|
|
|
16
16
|
/** Configuration file for encryption settings */
|
|
17
17
|
export const CONFIG_FILE = join(MEMORY_DIR, "config.json")
|
|
18
18
|
|
|
19
|
-
/** Maximum active entries before auto-archive */
|
|
19
|
+
/** Maximum active entries before auto-archive (default 100, configurable via config.json) */
|
|
20
|
+
export function getMaxEntries(): number {
|
|
21
|
+
const config = loadConfig()
|
|
22
|
+
return config.maxEntries || 100
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Legacy constant for backward compatibility */
|
|
20
26
|
export const MAX_ENTRIES = 100
|
|
21
27
|
|
|
22
28
|
/** Days before entries are archived */
|
|
@@ -31,6 +37,8 @@ export interface MemoryConfig {
|
|
|
31
37
|
encrypted: boolean
|
|
32
38
|
/** Project-specific tag vocabulary discovered from dependencies (Hito 7). */
|
|
33
39
|
vocab?: Record<string, string[]>
|
|
40
|
+
/** Maximum active entries before auto-archive (default 100). */
|
|
41
|
+
maxEntries?: number
|
|
34
42
|
}
|
|
35
43
|
|
|
36
44
|
/**
|
package/src/mcp/entries.ts
CHANGED
package/src/mcp/observations.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import { readFileSync, existsSync } from "fs"
|
|
1
|
+
import { readFileSync, existsSync, writeFileSync } from "fs"
|
|
2
2
|
import { OBSERVATIONS_FILE } from "./config"
|
|
3
3
|
|
|
4
|
+
/** Maximum observations to keep in the log file */
|
|
5
|
+
const MAX_OBSERVATIONS = 500
|
|
6
|
+
|
|
4
7
|
/**
|
|
5
8
|
* Read captured activity from observations.toon (written by hooks).
|
|
6
9
|
*/
|
|
@@ -14,3 +17,27 @@ export function readObservations(): Array<{ ts: string; session: string; agent:
|
|
|
14
17
|
return { ts: p[0] || "", session: p[1] || "", agent: p[2] || "", branch: p[3] || "", tool: p[4] || "", file: p[6] || "", summary: p[7] || "" }
|
|
15
18
|
})
|
|
16
19
|
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Prune observations.toon to MAX_OBSERVATIONS entries.
|
|
23
|
+
* Keeps the most recent entries. Called on each capture append.
|
|
24
|
+
*/
|
|
25
|
+
export function pruneObservations(): number {
|
|
26
|
+
if (!existsSync(OBSERVATIONS_FILE)) return 0
|
|
27
|
+
const data = readFileSync(OBSERVATIONS_FILE, "utf-8")
|
|
28
|
+
const lines = data.split("\n")
|
|
29
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("observations["))
|
|
30
|
+
if (headerIdx === -1) return 0
|
|
31
|
+
|
|
32
|
+
const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0)
|
|
33
|
+
if (entryLines.length <= MAX_OBSERVATIONS) return 0
|
|
34
|
+
|
|
35
|
+
const toRemove = entryLines.length - MAX_OBSERVATIONS
|
|
36
|
+
const pruned = entryLines.slice(toRemove)
|
|
37
|
+
const kept = entryLines.slice(0, MAX_OBSERVATIONS)
|
|
38
|
+
|
|
39
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
|
|
40
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...kept.map((l) => ` ${l.trim()}`))
|
|
41
|
+
writeFileSync(OBSERVATIONS_FILE, lines.join("\n"))
|
|
42
|
+
return toRemove
|
|
43
|
+
}
|
package/src/mcp/resources.ts
CHANGED
|
@@ -35,9 +35,9 @@ export function registerResources(server: McpServer): void {
|
|
|
35
35
|
const withTtl = entries.filter((e) => e.ttl).length
|
|
36
36
|
const expired = entries.filter((e) => e.ttl && isExpired(e.ttl)).length
|
|
37
37
|
const text = [
|
|
38
|
-
`
|
|
39
|
-
`TTL: ${withTtl}
|
|
40
|
-
"
|
|
38
|
+
`Total entries: ${entries.length}`,
|
|
39
|
+
`TTL: ${withTtl} with expiration, ${expired} expired`,
|
|
40
|
+
"By category:",
|
|
41
41
|
...Object.entries(byCategory).map(([k, v]) => ` ${k}: ${v}`),
|
|
42
42
|
].join("\n")
|
|
43
43
|
return { contents: [{ uri: uri.href, text }] }
|
package/src/mcp/scoring.ts
CHANGED
|
@@ -1,15 +1,12 @@
|
|
|
1
1
|
import { readMemory, writeMemory } from "./memory-io"
|
|
2
|
-
import { normalize } from "
|
|
2
|
+
import { normalize, importance } from "../lib/utils"
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* Importance score for an entry: blends recency and access frequency.
|
|
6
|
-
*
|
|
6
|
+
* Delegates to shared importance() in lib/utils.
|
|
7
7
|
*/
|
|
8
8
|
export function entryScore(dateStr: string, accessed: number): number {
|
|
9
|
-
|
|
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
|
|
9
|
+
return importance({ date: dateStr, accessed })
|
|
13
10
|
}
|
|
14
11
|
|
|
15
12
|
export function entryScoreForLine(line: string): number {
|