toon-memory 2.8.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.
@@ -73,7 +73,12 @@ export function mergeEntries(existingLine: string, newLine: string): string {
73
73
  const newTtl = np[7] || ""
74
74
  const ttl = newTtl || existingTtl
75
75
 
76
- // Take max confidence
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
77
82
  const existingConf = ep.length > 11 ? parseFloat(ep[11]) || 0 : 0
78
83
  const newConf = np.length > 11 ? parseFloat(np[11]) || 0 : 0
79
84
  const confidence = Math.max(existingConf, newConf)
@@ -85,7 +90,7 @@ export function mergeEntries(existingLine: string, newLine: string): string {
85
90
 
86
91
  const quality = qualityScore(mergedTags, mergedLinks, content, date)
87
92
 
88
- return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|0|${mergedLinks}|${quality.toFixed(2)}|${confidence}`
93
+ return `${id}|${category}|${key}|${content}|${file}|${mergedTags}|${date}|${ttl}|${accessed}|${mergedLinks}|${quality.toFixed(2)}|${confidence}`
89
94
  }
90
95
 
91
96
  /**
@@ -98,7 +103,7 @@ export function generateSmartRecall(
98
103
  opts: { limit?: number; category?: string; bumpAccess?: (ids: string[]) => void } = {}
99
104
  ): string {
100
105
  const entries = parseEntries(data)
101
- if (entries.length === 0) return "Memoria vacía."
106
+ if (entries.length === 0) return "Empty memory."
102
107
 
103
108
  const { adjacency } = buildGraph(entries)
104
109
  const bm25 = bm25Scores(entries, intent)
@@ -135,7 +140,7 @@ export function generateSmartRecall(
135
140
  .filter((e) => !category || e.category === category)
136
141
  .sort((a, b) => importance(b) - importance(a))
137
142
  .slice(0, limit)
138
- if (top.length === 0) return "No hay entradas en memoria."
143
+ if (top.length === 0) return "No entries in memory."
139
144
  return renderCompact(top)
140
145
  }
141
146
 
@@ -149,7 +154,7 @@ export function generateSmartRecall(
149
154
  */
150
155
  export function generateSystemPrimer(data: string): string {
151
156
  const entries = parseEntries(data)
152
- if (entries.length === 0) return "Memoria vacía. No hay entradas guardadas."
157
+ if (entries.length === 0) return "Empty memory. No entries saved."
153
158
 
154
159
  const byCategory: Record<string, GraphEntry[]> = {}
155
160
  for (const e of entries) {
@@ -159,7 +164,7 @@ export function generateSystemPrimer(data: string): string {
159
164
 
160
165
  const lines: string[] = [
161
166
  "=== System Primer ===",
162
- `Entradas: ${entries.length}`,
167
+ `Entries: ${entries.length}`,
163
168
  "",
164
169
  ]
165
170
 
@@ -167,7 +172,7 @@ export function generateSystemPrimer(data: string): string {
167
172
  const top = [...entries]
168
173
  .sort((a, b) => importance(b) - importance(a))
169
174
  .slice(0, 5)
170
- lines.push("Top memorias:")
175
+ lines.push("Top memories:")
171
176
  for (const e of top) {
172
177
  const quality = qualityScore(
173
178
  e.tags.join(";"),
@@ -175,15 +180,15 @@ export function generateSystemPrimer(data: string): string {
175
180
  e.content,
176
181
  e.date
177
182
  )
178
- const conf = quality >= 0.5 ? "alta" : quality >= 0.3 ? "media" : "baja"
183
+ const conf = quality >= 0.5 ? "high" : quality >= 0.3 ? "medium" : "low"
179
184
  lines.push(
180
- ` [${e.category}] ${e.key} — ${e.content.slice(0, 80)} (calidad: ${conf})`
185
+ ` [${e.category}] ${e.key} — ${e.content.slice(0, 80)} (quality: ${conf})`
181
186
  )
182
187
  }
183
188
  lines.push("")
184
189
 
185
190
  // Categories
186
- lines.push("Categorías:")
191
+ lines.push("Categories:")
187
192
  for (const [cat, items] of Object.entries(byCategory)) {
188
193
  lines.push(` ${cat}: ${items.length}`)
189
194
  }
@@ -192,7 +197,7 @@ export function generateSystemPrimer(data: string): string {
192
197
  // Rules (mandatory patterns)
193
198
  const patterns = entries.filter((e) => e.category === "pattern")
194
199
  if (patterns.length > 0) {
195
- lines.push("Patrones establecidos:")
200
+ lines.push("Established patterns:")
196
201
  for (const p of patterns.slice(0, 5)) {
197
202
  lines.push(` • ${p.key}: ${p.content.slice(0, 100)}`)
198
203
  }
@@ -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, MAX_ENTRIES, ARCHIVE_DAYS, ARCHIVE_FILE } from "./config"
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
- if (remaining > MAX_ENTRIES) {
39
- const need = remaining - MAX_ENTRIES
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
  /**
@@ -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
+ }
@@ -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
- `Entradas totales: ${entries.length}`,
39
- `TTL: ${withTtl} con expiración, ${expired} expiradas`,
40
- "Por categoría:",
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 }] }
@@ -1,15 +1,12 @@
1
1
  import { readMemory, writeMemory } from "./memory-io"
2
- import { normalize } from "./entries"
2
+ import { normalize, importance } from "../lib/utils"
3
3
 
4
4
  /**
5
5
  * Importance score for an entry: blends recency and access frequency.
6
- * Deterministic — no LLM. Higher = more worth keeping.
6
+ * Delegates to shared importance() in lib/utils.
7
7
  */
8
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
9
+ return importance({ date: dateStr, accessed })
13
10
  }
14
11
 
15
12
  export function entryScoreForLine(line: string): number {