toon-memory 3.0.0 → 3.2.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.de.md +7 -5
- package/README.es.md +7 -5
- package/README.fr.md +7 -5
- package/README.ja.md +7 -5
- package/README.ko.md +7 -5
- package/README.md +140 -9
- package/README.pt-br.md +7 -5
- package/README.zh.md +7 -5
- package/dist/cli/setup.js +1356 -28
- package/mcp/server.js +173 -2
- package/package.json +6 -2
- package/src/cli/agents.ts +10 -9
- package/src/cli/commands.ts +1 -1
- package/src/cli/config-writer.ts +90 -3
- package/src/cli/hooks.ts +2 -2
- package/src/cli/opencode-plugin.ts +58 -11
- package/src/cli/setup.ts +16 -7
- package/src/cli/types.ts +4 -2
- package/src/lib/checkpoint.ts +132 -0
- package/src/lib/graph.ts +16 -0
- package/src/lib/quality.ts +18 -1
- package/src/mcp/config.ts +5 -0
- package/src/mcp/prompts.ts +55 -0
- package/src/mcp/session-store.ts +276 -0
- package/src/mcp/tools.ts +177 -1
- package/src/viewer/data.ts +49 -0
- package/src/viewer/html.ts +880 -0
- package/src/viewer/index.ts +76 -0
- package/src/viewer/server.ts +1 -0
- package/src/viewer/types.ts +29 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-checkpoint system for toon-memory.
|
|
3
|
+
*
|
|
4
|
+
* Inspired by MiMo Code's checkpoint-writer subagent, but deterministic:
|
|
5
|
+
* - Detects when agent is working on complex tasks (many tool calls without recall)
|
|
6
|
+
* - Auto-generates checkpoint entries to preserve working state
|
|
7
|
+
* - Uses pattern detection, not LLM
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readSessionEntries, writeSessionEntry } from "../mcp/session-store"
|
|
11
|
+
import { loadConfig } from "../mcp/config"
|
|
12
|
+
|
|
13
|
+
/** Minimum tool calls between auto-checkpoints */
|
|
14
|
+
const DEFAULT_INTERVAL = 5
|
|
15
|
+
|
|
16
|
+
/** Minimum time (ms) between auto-checkpoints */
|
|
17
|
+
const MIN_TIME_BETWEEN_MS = 2 * 60 * 1000 // 2 minutes
|
|
18
|
+
|
|
19
|
+
/** Last checkpoint timestamp (in-memory, per process) */
|
|
20
|
+
let lastCheckpointTime = 0
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Analyze session history to determine if auto-checkpoint should trigger.
|
|
24
|
+
*
|
|
25
|
+
* Triggers when:
|
|
26
|
+
* 1. Interval of tool calls reached (default: 5 calls since last checkpoint)
|
|
27
|
+
* 2. Enough time has passed (2+ minutes)
|
|
28
|
+
* 3. Agent is working without recalling memory (potential "blind" work)
|
|
29
|
+
*/
|
|
30
|
+
export function shouldCheckpoint(sessionId?: string): boolean {
|
|
31
|
+
const config = loadConfig()
|
|
32
|
+
const checkpointConfig = config.checkpoint
|
|
33
|
+
|
|
34
|
+
// Check if auto-checkpoint is disabled
|
|
35
|
+
if (checkpointConfig?.enabled === false) return false
|
|
36
|
+
|
|
37
|
+
const interval = checkpointConfig?.interval || DEFAULT_INTERVAL
|
|
38
|
+
|
|
39
|
+
// Time check
|
|
40
|
+
const now = Date.now()
|
|
41
|
+
if (now - lastCheckpointTime < MIN_TIME_BETWEEN_MS) return false
|
|
42
|
+
|
|
43
|
+
// Get session entries
|
|
44
|
+
const entries = readSessionEntries(sessionId)
|
|
45
|
+
if (entries.length < interval) return false
|
|
46
|
+
|
|
47
|
+
// Count tool calls since last checkpoint
|
|
48
|
+
// Simple heuristic: if we have N+ entries without a checkpoint summary, trigger
|
|
49
|
+
const recentEntries = entries.slice(-interval)
|
|
50
|
+
const hasCheckpoint = recentEntries.some((e) =>
|
|
51
|
+
e.summary.toLowerCase().includes("checkpoint") ||
|
|
52
|
+
e.summary.toLowerCase().includes("auto-saved")
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
if (hasCheckpoint) return false
|
|
56
|
+
|
|
57
|
+
// Check for "blind work" pattern: many tool calls without memory recall
|
|
58
|
+
const recentTools = recentEntries.map((e) => e.tool)
|
|
59
|
+
const recallCount = recentTools.filter((t) =>
|
|
60
|
+
t.includes("recall") || t.includes("smart_recall") || t.includes("context")
|
|
61
|
+
).length
|
|
62
|
+
|
|
63
|
+
// If less than 20% of recent calls are recalls, agent might be working blind
|
|
64
|
+
const recallRatio = recallCount / recentTools.length
|
|
65
|
+
if (recallRatio > 0.2) return false
|
|
66
|
+
|
|
67
|
+
// All checks passed
|
|
68
|
+
return true
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Generate a checkpoint entry from current session state.
|
|
73
|
+
* Called after shouldCheckpoint returns true.
|
|
74
|
+
*/
|
|
75
|
+
export function generateCheckpoint(sessionId: string): { summary: string; file: string } {
|
|
76
|
+
const entries = readSessionEntries(sessionId)
|
|
77
|
+
|
|
78
|
+
// Extract key information from recent entries
|
|
79
|
+
const recentFiles = [...new Set(entries.slice(-10).map((e) => e.file).filter(Boolean))]
|
|
80
|
+
const recentTools = entries.slice(-10).map((e) => e.tool)
|
|
81
|
+
const toolCounts = recentTools.reduce((acc, t) => {
|
|
82
|
+
acc[t] = (acc[t] || 0) + 1
|
|
83
|
+
return acc
|
|
84
|
+
}, {} as Record<string, number>)
|
|
85
|
+
|
|
86
|
+
const topTools = Object.entries(toolCounts)
|
|
87
|
+
.sort((a, b) => b[1] - a[1])
|
|
88
|
+
.slice(0, 3)
|
|
89
|
+
.map(([t, c]) => `${t}(${c})`)
|
|
90
|
+
.join(", ")
|
|
91
|
+
|
|
92
|
+
const filesSummary = recentFiles.length > 0
|
|
93
|
+
? `Files: ${recentFiles.slice(0, 5).join(", ")}${recentFiles.length > 5 ? ` +${recentFiles.length - 5}` : ""}`
|
|
94
|
+
: ""
|
|
95
|
+
|
|
96
|
+
const summary = `Auto-checkpoint: ${topTools}${filesSummary ? ` | ${filesSummary}` : ""}`
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
summary,
|
|
100
|
+
file: recentFiles[0] || "",
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Maybe auto-checkpoint: check if we should checkpoint, and if so, do it.
|
|
106
|
+
* Returns true if a checkpoint was created.
|
|
107
|
+
*/
|
|
108
|
+
export function maybeAutoCheckpoint(sessionId: string): boolean {
|
|
109
|
+
if (!shouldCheckpoint(sessionId)) return false
|
|
110
|
+
|
|
111
|
+
const checkpoint = generateCheckpoint(sessionId)
|
|
112
|
+
|
|
113
|
+
writeSessionEntry({
|
|
114
|
+
ts: new Date().toISOString(),
|
|
115
|
+
session: sessionId,
|
|
116
|
+
agent: "system",
|
|
117
|
+
branch: "",
|
|
118
|
+
tool: "auto-checkpoint",
|
|
119
|
+
file: checkpoint.file,
|
|
120
|
+
summary: checkpoint.summary,
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
lastCheckpointTime = Date.now()
|
|
124
|
+
return true
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Reset checkpoint timer (called on session start).
|
|
129
|
+
*/
|
|
130
|
+
export function resetCheckpointTimer(): void {
|
|
131
|
+
lastCheckpointTime = 0
|
|
132
|
+
}
|
package/src/lib/graph.ts
CHANGED
|
@@ -109,6 +109,22 @@ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
|
|
|
109
109
|
for (const r of refs) link(e.key, r.slice(2, -2))
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
+
// Connect entries sharing 2+ tags
|
|
113
|
+
if (entries.some((e) => e.tags.length > 0)) {
|
|
114
|
+
for (let i = 0; i < entries.length; i++) {
|
|
115
|
+
const ei = entries[i]
|
|
116
|
+
if (ei.tags.length === 0) continue
|
|
117
|
+
const eTags = new Set(ei.tags)
|
|
118
|
+
for (let j = i + 1; j < entries.length; j++) {
|
|
119
|
+
const ej = entries[j]
|
|
120
|
+
if (ej.tags.length === 0) continue
|
|
121
|
+
let shared = 0
|
|
122
|
+
for (const t of ej.tags) if (eTags.has(t)) shared++
|
|
123
|
+
if (shared >= 2) link(ei.key, ej.key)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
112
128
|
const adjacency = new Map<string, string[]>()
|
|
113
129
|
for (const [k, v] of adj) adjacency.set(k, [...v])
|
|
114
130
|
return { adjacency, byKey }
|
package/src/lib/quality.ts
CHANGED
|
@@ -24,6 +24,7 @@ import { fuzzyMatch } from "./fuzzy"
|
|
|
24
24
|
* - Specificity (0.1 max): unique word ratio
|
|
25
25
|
* - Access frequency (0.15 max): how often recalled
|
|
26
26
|
* - Access recency (0.1 max): how recently accessed
|
|
27
|
+
* - Staleness decay: entries not accessed in 30+ days lose up to 0.2
|
|
27
28
|
*/
|
|
28
29
|
export function qualityScore(
|
|
29
30
|
tags: string,
|
|
@@ -68,7 +69,23 @@ export function qualityScore(
|
|
|
68
69
|
else if (daysSinceAccess < 7) score += 0.07
|
|
69
70
|
else if (daysSinceAccess < 30) score += 0.03
|
|
70
71
|
}
|
|
71
|
-
|
|
72
|
+
|
|
73
|
+
// Staleness decay: penalize entries that haven't been accessed recently
|
|
74
|
+
// and were created more than 30 days ago. Decay ramps up over time.
|
|
75
|
+
if (date) {
|
|
76
|
+
const daysSinceCreation = (Date.now() - new Date(`${date}T00:00:00`).getTime()) / 86400000
|
|
77
|
+
const daysSinceLastAccess = lastAccessed
|
|
78
|
+
? (Date.now() - new Date(lastAccessed).getTime()) / 86400000
|
|
79
|
+
: daysSinceCreation
|
|
80
|
+
|
|
81
|
+
// Only decay if entry is old AND hasn't been accessed recently
|
|
82
|
+
if (daysSinceCreation > 30 && daysSinceLastAccess > 30) {
|
|
83
|
+
const staleness = Math.min(1, (daysSinceLastAccess - 30) / 90) // 0→1 over 30-120 days
|
|
84
|
+
score -= staleness * 0.2 // Max penalty: -0.2
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return Math.max(0, Math.min(1, score))
|
|
72
89
|
}
|
|
73
90
|
|
|
74
91
|
/**
|
package/src/mcp/config.ts
CHANGED
|
@@ -41,6 +41,11 @@ export interface MemoryConfig {
|
|
|
41
41
|
maxEntries?: number
|
|
42
42
|
/** Verbatim mode: skip tag inference and quality scoring at write time. */
|
|
43
43
|
verbatim?: boolean
|
|
44
|
+
/** Auto-checkpoint configuration */
|
|
45
|
+
checkpoint?: {
|
|
46
|
+
enabled?: boolean
|
|
47
|
+
interval?: number
|
|
48
|
+
}
|
|
44
49
|
}
|
|
45
50
|
|
|
46
51
|
/**
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/server"
|
|
2
|
+
import { z } from "zod"
|
|
3
|
+
import { readMemory } from "./memory-io"
|
|
4
|
+
import { parseEntries } from "../lib/graph"
|
|
5
|
+
|
|
6
|
+
export function registerPrompts(server: McpServer): void {
|
|
7
|
+
server.registerPrompt(
|
|
8
|
+
"summarize_project_context",
|
|
9
|
+
{
|
|
10
|
+
title: "Summarize Project Context",
|
|
11
|
+
description: "Analyze the current TOON memory state and generate a compact summary of project knowledge.",
|
|
12
|
+
argsSchema: { intent: z.string().optional().describe("Optional focus area (e.g. 'auth', 'database')") },
|
|
13
|
+
},
|
|
14
|
+
({ intent }: { intent?: string }) => {
|
|
15
|
+
const data = readMemory()
|
|
16
|
+
const entries = parseEntries(data)
|
|
17
|
+
const byCategory: Record<string, number> = {}
|
|
18
|
+
for (const e of entries) {
|
|
19
|
+
byCategory[e.category] = (byCategory[e.category] || 0) + 1
|
|
20
|
+
}
|
|
21
|
+
const total = entries.length
|
|
22
|
+
let summary = `This project has ${total} memory entr${total === 1 ? "y" : "ies"}`
|
|
23
|
+
if (byCategory.decision) summary += `, ${byCategory.decision} decision${byCategory.decision === 1 ? "" : "s"}`
|
|
24
|
+
if (byCategory.pattern) summary += `, ${byCategory.pattern} pattern${byCategory.pattern === 1 ? "" : "s"}`
|
|
25
|
+
if (byCategory.bug) summary += `, ${byCategory.bug} bug${byCategory.bug === 1 ? "" : "s"}`
|
|
26
|
+
if (byCategory.knowledge) summary += `, ${byCategory.knowledge} knowledge entr${byCategory.knowledge === 1 ? "y" : "ies"}`
|
|
27
|
+
if (byCategory.architecture) summary += `, ${byCategory.architecture} architecture note${byCategory.architecture === 1 ? "" : "s"}`
|
|
28
|
+
summary += "."
|
|
29
|
+
|
|
30
|
+
let filtered = entries
|
|
31
|
+
if (intent) {
|
|
32
|
+
const q = intent.toLowerCase()
|
|
33
|
+
filtered = entries.filter((e) =>
|
|
34
|
+
e.key.toLowerCase().includes(q) ||
|
|
35
|
+
e.content.toLowerCase().includes(q) ||
|
|
36
|
+
e.tags.some((t) => t.toLowerCase().includes(q))
|
|
37
|
+
)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const recent = [...filtered].sort((a, b) => b.date.localeCompare(a.date)).slice(0, 5)
|
|
41
|
+
let detail = recent.length > 0
|
|
42
|
+
? "\n\nMost relevant entries:\n" + recent.map((e) =>
|
|
43
|
+
` [${e.category}] ${e.key}: ${e.content.slice(0, 100)}`
|
|
44
|
+
).join("\n")
|
|
45
|
+
: ""
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
messages: [{
|
|
49
|
+
role: "user" as const,
|
|
50
|
+
content: { type: "text" as const, text: summary + detail },
|
|
51
|
+
}],
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
)
|
|
55
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { readFileSync, existsSync, writeFileSync, renameSync } from "fs"
|
|
2
|
+
import { join } from "path"
|
|
3
|
+
import { OBSERVATIONS_FILE, MEMORY_FILE, MEMORY_DIR } from "./config"
|
|
4
|
+
import { withLockSync, atomicWrite, readUnderLock } from "../lib/lock"
|
|
5
|
+
import { loadConfig, getKey } from "./config"
|
|
6
|
+
import { encrypt, decrypt } from "./crypto"
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Session-aware memory store.
|
|
10
|
+
*
|
|
11
|
+
* Replaces observations.toon with session.toon — adds session lifecycle:
|
|
12
|
+
* - Entries are tagged with session_id
|
|
13
|
+
* - On session end, entries with accessed > 0 are auto-promoted to memory.toon
|
|
14
|
+
* - Entries without access are discarded
|
|
15
|
+
* - Manual promotion via memory_promote tool
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
/** Maximum session entries to keep */
|
|
19
|
+
const MAX_SESSION_ENTRIES = 500
|
|
20
|
+
|
|
21
|
+
export interface SessionEntry {
|
|
22
|
+
ts: string
|
|
23
|
+
session: string
|
|
24
|
+
agent: string
|
|
25
|
+
branch: string
|
|
26
|
+
tool: string
|
|
27
|
+
file: string
|
|
28
|
+
summary: string
|
|
29
|
+
accessed: number
|
|
30
|
+
lastAccessed: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Read captured activity from session.toon (or observations.toon for compat).
|
|
35
|
+
*/
|
|
36
|
+
export function readSessionEntries(sessionId?: string): SessionEntry[] {
|
|
37
|
+
const filePath = getSessionFile()
|
|
38
|
+
if (!existsSync(filePath)) return []
|
|
39
|
+
|
|
40
|
+
const entries = readFileSync(filePath, "utf-8")
|
|
41
|
+
.split("\n")
|
|
42
|
+
.filter((l) => l.startsWith(" ") && l.includes("|"))
|
|
43
|
+
.map((l) => {
|
|
44
|
+
const p = l.trim().split("|")
|
|
45
|
+
return {
|
|
46
|
+
ts: p[0] || "",
|
|
47
|
+
session: p[1] || "",
|
|
48
|
+
agent: p[2] || "",
|
|
49
|
+
branch: p[3] || "",
|
|
50
|
+
tool: p[4] || "",
|
|
51
|
+
file: p[6] || "",
|
|
52
|
+
summary: p[7] || "",
|
|
53
|
+
accessed: p.length > 8 ? parseInt(p[8]) || 0 : 0,
|
|
54
|
+
lastAccessed: p.length > 9 ? p[9] || "" : "",
|
|
55
|
+
}
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
if (sessionId) {
|
|
59
|
+
return entries.filter((e) => e.session === sessionId)
|
|
60
|
+
}
|
|
61
|
+
return entries
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Write a session entry. Appends to session.toon.
|
|
66
|
+
*/
|
|
67
|
+
export function writeSessionEntry(entry: Omit<SessionEntry, "accessed" | "lastAccessed">): void {
|
|
68
|
+
const filePath = getSessionFile()
|
|
69
|
+
ensureSessionFile()
|
|
70
|
+
|
|
71
|
+
const data = readUnderLock(filePath)
|
|
72
|
+
const lines = data.split("\n")
|
|
73
|
+
let headerIdx = lines.findIndex((l) => l.startsWith("session[") || l.startsWith("observations["))
|
|
74
|
+
if (headerIdx === -1) {
|
|
75
|
+
lines.push("session[0|]")
|
|
76
|
+
headerIdx = lines.length - 1
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const entryLine = `${entry.ts}|${entry.session}|${entry.agent}|${entry.branch}|${entry.tool}||${entry.file}|${entry.summary}|0|`
|
|
80
|
+
|
|
81
|
+
const match = lines[headerIdx].match(/\[(\d+)\|/)
|
|
82
|
+
const count = match ? parseInt(match[1]) : 0
|
|
83
|
+
lines.splice(headerIdx + 1, 0, ` ${entryLine}`)
|
|
84
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${count + 1}|`)
|
|
85
|
+
|
|
86
|
+
atomicWrite(filePath, lines.join("\n"))
|
|
87
|
+
pruneSessionEntries()
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Promote session entries to permanent memory.toon.
|
|
92
|
+
* Moves selected entries (by index or tool filter) to memory.
|
|
93
|
+
*/
|
|
94
|
+
export function promoteSessionEntries(
|
|
95
|
+
entriesToPromote: SessionEntry[],
|
|
96
|
+
category: "decision" | "pattern" | "bug" | "knowledge" | "architecture" = "knowledge"
|
|
97
|
+
): number {
|
|
98
|
+
if (entriesToPromote.length === 0) return 0
|
|
99
|
+
|
|
100
|
+
const memoryData = readMemoryFile()
|
|
101
|
+
const memoryLines = memoryData.split("\n")
|
|
102
|
+
let memoryHeaderIdx = memoryLines.findIndex((l) => l.startsWith("entries[") || /^\[\d+\|]/.test(l))
|
|
103
|
+
if (memoryHeaderIdx === -1) {
|
|
104
|
+
memoryLines.push("[0|]")
|
|
105
|
+
memoryHeaderIdx = memoryLines.length - 1
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
let promoted = 0
|
|
109
|
+
for (const entry of entriesToPromote) {
|
|
110
|
+
if (!entry.summary) continue
|
|
111
|
+
|
|
112
|
+
const id = `sp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
|
113
|
+
const date = entry.ts.split("T")[0] || new Date().toISOString().split("T")[0]
|
|
114
|
+
const key = entry.summary.slice(0, 50).replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `session-${id}`
|
|
115
|
+
|
|
116
|
+
const memoryEntry = `${id}|${category}|${key}|${entry.summary}|${entry.file}|session-promoted|${date}||0||0.5|1.0|`
|
|
117
|
+
|
|
118
|
+
const match = memoryLines[memoryHeaderIdx].match(/\[(\d+)\|/)
|
|
119
|
+
const count = match ? parseInt(match[1]) : 0
|
|
120
|
+
memoryLines.splice(memoryHeaderIdx + 1, 0, ` ${memoryEntry}`)
|
|
121
|
+
memoryLines[memoryHeaderIdx] = memoryLines[memoryHeaderIdx].replace(/\[\d+\|/, `[${count + 1}|`)
|
|
122
|
+
promoted++
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (promoted > 0) {
|
|
126
|
+
atomicWrite(MEMORY_FILE, memoryLines.join("\n"))
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return promoted
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Clear session entries (called on session end).
|
|
134
|
+
* Auto-promotes entries with accessed > 0, discards the rest.
|
|
135
|
+
*/
|
|
136
|
+
export function clearSession(sessionId: string): { promoted: number; discarded: number } {
|
|
137
|
+
const allEntries = readSessionEntries()
|
|
138
|
+
const sessionEntries = allEntries.filter((e) => e.session === sessionId)
|
|
139
|
+
const otherEntries = allEntries.filter((e) => e.session !== sessionId)
|
|
140
|
+
|
|
141
|
+
const toPromote = sessionEntries.filter((e) => e.accessed > 0)
|
|
142
|
+
const toDiscard = sessionEntries.filter((e) => e.accessed === 0)
|
|
143
|
+
|
|
144
|
+
const promoted = promoteSessionEntries(toPromote, "knowledge")
|
|
145
|
+
|
|
146
|
+
// Rewrite file with only other sessions' entries
|
|
147
|
+
const filePath = getSessionFile()
|
|
148
|
+
if (otherEntries.length === 0) {
|
|
149
|
+
atomicWrite(filePath, "session[0|]{ts|session|agent|branch|tool||file|summary|accessed|lastAccessed}:\n")
|
|
150
|
+
} else {
|
|
151
|
+
const lines = [`session[${otherEntries.length}|]{ts|session|agent|branch|tool||file|summary|accessed|lastAccessed}:`]
|
|
152
|
+
for (const e of otherEntries) {
|
|
153
|
+
lines.push(` ${e.ts}|${e.session}|${e.agent}|${e.branch}|${e.tool}||${e.file}|${e.summary}|${e.accessed}|${e.lastAccessed}`)
|
|
154
|
+
}
|
|
155
|
+
atomicWrite(filePath, lines.join("\n"))
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return { promoted, discarded: toDiscard.length }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Mark session entries as accessed (bump counter).
|
|
163
|
+
*/
|
|
164
|
+
export function bumpSessionAccess(summaries: string[]): void {
|
|
165
|
+
if (summaries.length === 0) return
|
|
166
|
+
const summarySet = new Set(summaries)
|
|
167
|
+
const filePath = getSessionFile()
|
|
168
|
+
if (!existsSync(filePath)) return
|
|
169
|
+
|
|
170
|
+
const data = readUnderLock(filePath)
|
|
171
|
+
const lines = data.split("\n")
|
|
172
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("session[") || l.startsWith("observations["))
|
|
173
|
+
if (headerIdx === -1) return
|
|
174
|
+
|
|
175
|
+
const now = new Date().toISOString()
|
|
176
|
+
for (let i = headerIdx + 1; i < lines.length; i++) {
|
|
177
|
+
const line = lines[i]
|
|
178
|
+
if (!line.startsWith(" ") || !line.includes("|")) continue
|
|
179
|
+
const parts = line.trim().split("|")
|
|
180
|
+
const summary = parts[7] || ""
|
|
181
|
+
if (summarySet.has(summary)) {
|
|
182
|
+
const accessed = parts.length > 8 ? (parseInt(parts[8]) || 0) + 1 : 1
|
|
183
|
+
parts[8] = String(accessed)
|
|
184
|
+
while (parts.length < 10) parts.push("")
|
|
185
|
+
parts[9] = now
|
|
186
|
+
lines[i] = ` ${parts.join("|")}`
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
atomicWrite(filePath, lines.join("\n"))
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Get the session file path, migrating from observations.toon if needed.
|
|
195
|
+
*/
|
|
196
|
+
function getSessionFile(): string {
|
|
197
|
+
const sessionFile = join(MEMORY_DIR, "session.toon")
|
|
198
|
+
if (existsSync(sessionFile)) return sessionFile
|
|
199
|
+
|
|
200
|
+
// Migrate from observations.toon
|
|
201
|
+
if (existsSync(OBSERVATIONS_FILE)) {
|
|
202
|
+
migrateObservationsToSession()
|
|
203
|
+
return sessionFile
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return sessionFile
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Migrate observations.toon to session.toon format.
|
|
211
|
+
*/
|
|
212
|
+
function migrateObservationsToSession(): void {
|
|
213
|
+
const data = readFileSync(OBSERVATIONS_FILE, "utf-8")
|
|
214
|
+
const lines = data.split("\n")
|
|
215
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("observations["))
|
|
216
|
+
if (headerIdx === -1) return
|
|
217
|
+
|
|
218
|
+
// Convert old format to new format (add accessed/lastAccessed fields)
|
|
219
|
+
const newLines = [`session[0|]{ts|session|agent|branch|tool||file|summary|accessed|lastAccessed}:`]
|
|
220
|
+
for (const line of lines.slice(headerIdx + 1)) {
|
|
221
|
+
if (!line.startsWith(" ") || !line.includes("|")) continue
|
|
222
|
+
const parts = line.trim().split("|")
|
|
223
|
+
// Old format: ts|session|agent|branch|tool||file|summary
|
|
224
|
+
// New format: ts|session|agent|branch|tool||file|summary|accessed|lastAccessed
|
|
225
|
+
while (parts.length < 8) parts.push("")
|
|
226
|
+
parts.push("0", "") // Add accessed=0 and lastAccessed=""
|
|
227
|
+
newLines.push(` ${parts.join("|")}`)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const sessionFile = join(MEMORY_DIR, "session.toon")
|
|
231
|
+
atomicWrite(sessionFile, newLines.join("\n"))
|
|
232
|
+
|
|
233
|
+
// Keep observations.toon as backup (don't delete - user might want it)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function ensureSessionFile(): void {
|
|
237
|
+
const filePath = getSessionFile()
|
|
238
|
+
if (!existsSync(filePath)) {
|
|
239
|
+
atomicWrite(filePath, "session[0|]{ts|session|agent|branch|tool||file|summary|accessed|lastAccessed}:\n")
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function pruneSessionEntries(): void {
|
|
244
|
+
const filePath = getSessionFile()
|
|
245
|
+
if (!existsSync(filePath)) return
|
|
246
|
+
|
|
247
|
+
const data = readUnderLock(filePath)
|
|
248
|
+
const lines = data.split("\n")
|
|
249
|
+
const headerIdx = lines.findIndex((l) => l.startsWith("session[") || l.startsWith("observations["))
|
|
250
|
+
if (headerIdx === -1) return
|
|
251
|
+
|
|
252
|
+
const entryLines = lines.slice(headerIdx + 1).filter((l) => l.trim().length > 0)
|
|
253
|
+
if (entryLines.length <= MAX_SESSION_ENTRIES) return
|
|
254
|
+
|
|
255
|
+
const toRemove = entryLines.length - MAX_SESSION_ENTRIES
|
|
256
|
+
const kept = entryLines.slice(toRemove)
|
|
257
|
+
|
|
258
|
+
lines[headerIdx] = lines[headerIdx].replace(/\[\d+\|/, `[${kept.length}|`)
|
|
259
|
+
lines.splice(headerIdx + 1, lines.length - headerIdx - 1, ...kept.map((l) => ` ${l.trim()}`))
|
|
260
|
+
atomicWrite(filePath, lines.join("\n"))
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function readMemoryFile(): string {
|
|
264
|
+
const config = loadConfig()
|
|
265
|
+
const data = readUnderLock(MEMORY_FILE)
|
|
266
|
+
if (config.encrypted) {
|
|
267
|
+
const key = getKey()
|
|
268
|
+
if (!key) return "version: 1\nentries[0|]:\n"
|
|
269
|
+
return decrypt(data, key)
|
|
270
|
+
}
|
|
271
|
+
return data
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Re-export for backward compatibility
|
|
275
|
+
export const readObservations = readSessionEntries
|
|
276
|
+
export const pruneObservations = pruneSessionEntries
|