toon-memory 3.1.0 → 3.3.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 +140 -5
- package/dist/cli/setup.js +1265 -6
- package/mcp/server.js +44861 -29662
- package/package.json +7 -2
- package/src/cli/constants.ts +4 -0
- package/src/cli/setup.ts +16 -7
- package/src/lib/checkpoint.ts +132 -0
- package/src/lib/graph.ts +16 -0
- package/src/mcp/config.ts +5 -0
- package/src/mcp/prompts.ts +55 -0
- package/src/mcp/resources.ts +21 -2
- package/src/mcp/server.ts +22 -3
- package/src/mcp/session-store.ts +276 -0
- package/src/mcp/tools.ts +31 -1
- package/src/viewer/d3.v7.min.js +2 -0
- package/src/viewer/data.ts +48 -0
- package/src/viewer/html.ts +922 -0
- package/src/viewer/index.ts +76 -0
- package/src/viewer/server.ts +1 -0
- package/src/viewer/types.ts +29 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "toon-memory",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "MCP server giving AI coding agents offline, token-efficient persistent memory — 29 tools, 80% fewer tool calls, recall decisions, patterns, and bugs across sessions. No LLM, no server; works with 15+ agents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -29,19 +29,24 @@
|
|
|
29
29
|
"bench:full": "node scripts/bench-full-impact.mjs",
|
|
30
30
|
"bench:compress-all": "node scripts/bench-compress-all.mjs",
|
|
31
31
|
"bench:primer": "node scripts/bench-primer.mjs",
|
|
32
|
+
"capture:viewer": "node scripts/capture-viewer.mjs",
|
|
32
33
|
"inspect": "npm run build && npx @modelcontextprotocol/inspector node bin/toon-memory.js mcp",
|
|
33
34
|
"prepublishOnly": "npm run build && npm test"
|
|
34
35
|
},
|
|
35
36
|
"dependencies": {
|
|
36
37
|
"@inquirer/prompts": "^8.5.2",
|
|
37
|
-
"@modelcontextprotocol/
|
|
38
|
+
"@modelcontextprotocol/ext-apps": "^1.7.5",
|
|
39
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
38
40
|
"@toon-format/toon": "^2.3.0",
|
|
39
41
|
"zod": "^4.4.3"
|
|
40
42
|
},
|
|
41
43
|
"devDependencies": {
|
|
44
|
+
"@mcp-ui/server": "^6.1.0",
|
|
45
|
+
"@modelcontextprotocol/inspector": "^2.0.0",
|
|
42
46
|
"@types/node": "^26.1.1",
|
|
43
47
|
"esbuild": "^0.25.0",
|
|
44
48
|
"gpt-tokenizer": "^3.4.0",
|
|
49
|
+
"playwright": "^1.62.0",
|
|
45
50
|
"typescript": "^7.0.2",
|
|
46
51
|
"vitest": "^4.1.10"
|
|
47
52
|
},
|
package/src/cli/constants.ts
CHANGED
|
@@ -34,6 +34,9 @@ Persistent memory for this project. Use it to avoid re-investigating things.
|
|
|
34
34
|
1. Run memory_stats to see what's in memory.
|
|
35
35
|
2. If the user asks something that might be in memory, run memory_recall BEFORE reading files.
|
|
36
36
|
|
|
37
|
+
## When asked to see the memory graph
|
|
38
|
+
- Call memory_visualize() to open the interactive graph viewer inline.
|
|
39
|
+
|
|
37
40
|
## When making decisions
|
|
38
41
|
- Before implementing a non-trivial change: memory_remember(category='decision')
|
|
39
42
|
- When you resolve a complex bug: memory_remember(category='bug')
|
|
@@ -53,4 +56,5 @@ Persistent memory for this project. Use it to avoid re-investigating things.
|
|
|
53
56
|
export const OPENCODE_PASSIVE_INSTRUCTION = `# toon-memory
|
|
54
57
|
|
|
55
58
|
Memory auto-injects via .opencode/instructions/memory-autoload.md; use memory_recall only as fallback.
|
|
59
|
+
When the user asks to see the memory graph, call memory_visualize().
|
|
56
60
|
`
|
package/src/cli/setup.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { captureToggle } from "./capture-toggle"
|
|
2
2
|
import { init, uninstall, status, upgrade, stats, exportMemory, importMemory, dumpMemory, interactiveInstall } from "./commands"
|
|
3
3
|
import { watch } from "./watch"
|
|
4
|
+
import { viewer, viewerExport } from "../viewer"
|
|
4
5
|
|
|
5
6
|
const args = process.argv.slice(2)
|
|
6
7
|
|
|
@@ -72,20 +73,28 @@ if (args[0] === "watch") {
|
|
|
72
73
|
process.exit(0)
|
|
73
74
|
}
|
|
74
75
|
|
|
75
|
-
|
|
76
|
-
|
|
76
|
+
if (args[0] === "viewer") {
|
|
77
|
+
const portIdx = args.indexOf("--port")
|
|
78
|
+
const port = portIdx !== -1 && args[portIdx + 1] ? args[portIdx + 1] : undefined
|
|
79
|
+
if (args.includes("--export")) {
|
|
80
|
+
viewerExport()
|
|
81
|
+
} else {
|
|
82
|
+
viewer(port)
|
|
83
|
+
}
|
|
84
|
+
} else if (args.length === 0) {
|
|
77
85
|
await interactiveInstall()
|
|
78
86
|
process.exit(0)
|
|
87
|
+
} else {
|
|
88
|
+
console.log(`Unknown command: '${args[0]}'\n`)
|
|
89
|
+
printUsage()
|
|
90
|
+
process.exit(1)
|
|
79
91
|
}
|
|
80
92
|
|
|
81
|
-
console.log(`Unknown command: '${args[0]}'\n`)
|
|
82
|
-
printUsage()
|
|
83
|
-
process.exit(1)
|
|
84
|
-
|
|
85
93
|
/** Minimal usage string for unknown commands. */
|
|
86
94
|
function printUsage(): void {
|
|
87
95
|
console.log(`Usage: toon-memory <command> [options]
|
|
88
|
-
Commands: init, status, stats, export, import, watch, uninstall, capture, upgrade, mcp
|
|
96
|
+
Commands: init, status, stats, export, import, watch, viewer, uninstall, capture, upgrade, mcp
|
|
97
|
+
viewer [--export] [--port <n>] — Start an HTTP server with the graph viewer (press 'r' to reload). --export saves static HTML.
|
|
89
98
|
Init: toon-memory init [--agent <name> --agent <name>...] [--scope local|global]
|
|
90
99
|
Without --agent: interactive agent and scope selector.
|
|
91
100
|
With --agent: non-interactive installation (default: scope local).
|
|
@@ -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/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/sdk/server/mcp.js"
|
|
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
|
+
}
|
package/src/mcp/resources.ts
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
|
-
import type { McpServer } from "@modelcontextprotocol/server"
|
|
1
|
+
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
|
|
2
|
+
import { registerAppResource } from "@modelcontextprotocol/ext-apps/server"
|
|
3
|
+
import { createUIResource } from "@mcp-ui/server"
|
|
2
4
|
import { readMemory } from "./memory-io"
|
|
3
5
|
import { isExpired } from "./entries"
|
|
4
6
|
import { generateSystemPrimer } from "../lib/quality"
|
|
7
|
+
import { buildViewerData } from "../viewer/data"
|
|
8
|
+
import { generateHtml } from "../viewer/html"
|
|
5
9
|
|
|
6
10
|
/**
|
|
7
|
-
* Register memory MCP resources (entries, stats, summaries).
|
|
11
|
+
* Register memory MCP resources (entries, stats, summaries, viewer).
|
|
8
12
|
*/
|
|
9
13
|
export function registerResources(server: McpServer): void {
|
|
10
14
|
server.registerResource(
|
|
@@ -54,4 +58,19 @@ export function registerResources(server: McpServer): void {
|
|
|
54
58
|
return { contents: [{ uri: uri.href, text: primer }] }
|
|
55
59
|
}
|
|
56
60
|
)
|
|
61
|
+
|
|
62
|
+
// MCP Apps: interactive graph viewer rendered inline in MCP hosts
|
|
63
|
+
const viewerResource = createUIResource({
|
|
64
|
+
uri: "ui://viewer",
|
|
65
|
+
content: { type: "rawHtml", htmlString: generateHtml(buildViewerData()) },
|
|
66
|
+
encoding: "text",
|
|
67
|
+
adapters: { mcpApps: { enabled: true } },
|
|
68
|
+
})
|
|
69
|
+
registerAppResource(
|
|
70
|
+
server as unknown as Parameters<typeof registerAppResource>[0],
|
|
71
|
+
"Memory Graph Viewer",
|
|
72
|
+
viewerResource.resource.uri,
|
|
73
|
+
{ description: "Interactive memory graph viewer (D3.js force-directed graph with stats, timeline, detail panel)" },
|
|
74
|
+
async () => ({ contents: [viewerResource.resource] }),
|
|
75
|
+
)
|
|
57
76
|
}
|
package/src/mcp/server.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { McpServer } from "@modelcontextprotocol/server"
|
|
2
|
-
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
|
|
2
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
|
3
|
+
import { InitializeRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/sdk/types.js"
|
|
3
4
|
import { registerTools } from "./tools"
|
|
4
5
|
import { registerResources } from "./resources"
|
|
5
6
|
import { pruneExpiredEntries } from "./archive"
|
|
@@ -8,9 +9,27 @@ declare const TOON_VERSION: string
|
|
|
8
9
|
|
|
9
10
|
const server = new McpServer(
|
|
10
11
|
{ name: "toon-memory", version: TOON_VERSION },
|
|
11
|
-
{ capabilities: { tools: { listChanged: true }, resources: { listChanged: true } } }
|
|
12
|
+
{ capabilities: { tools: { listChanged: true }, resources: { listChanged: true }, experimental: { "io.modelcontextprotocol/ui": {} } } }
|
|
12
13
|
)
|
|
13
14
|
|
|
15
|
+
// MCP Apps support is advertised via capabilities.experimental.
|
|
16
|
+
// We DO NOT set top-level extensions here — for STDIO transport that
|
|
17
|
+
// triggers OAuth in some hosts (e.g. Inspector v2). The experimental
|
|
18
|
+
// field is sufficient for MCP Apps–compatible clients.
|
|
19
|
+
const s = server.server as any
|
|
20
|
+
s.setRequestHandler(InitializeRequestSchema, async (request: any) => {
|
|
21
|
+
const requestedVersion = request.params.protocolVersion
|
|
22
|
+
s._clientCapabilities = request.params.capabilities
|
|
23
|
+
s._clientVersion = request.params.clientInfo
|
|
24
|
+
const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION
|
|
25
|
+
return {
|
|
26
|
+
protocolVersion,
|
|
27
|
+
capabilities: s.getCapabilities(),
|
|
28
|
+
serverInfo: { name: "toon-memory", version: TOON_VERSION },
|
|
29
|
+
...(s._instructions && { instructions: s._instructions }),
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
|
|
14
33
|
registerResources(server)
|
|
15
34
|
registerTools(server)
|
|
16
35
|
|
|
@@ -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
|