toon-memory 2.0.0 → 2.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.
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Memory graph layer for toon-memory.
3
+ *
4
+ * Turns the flat TOON entry list into a lightweight knowledge graph:
5
+ * - nodes = memory entries (keyed by `key`)
6
+ * - edges = explicit `links` + implicit `[[key]]` references in content
7
+ *
8
+ * Everything is deterministic and offline: no embeddings, no LLM, no network.
9
+ * The graph's value is precision (relational context) and smaller result sets
10
+ * (an ego-subgraph instead of dumping every keyword match).
11
+ */
12
+
13
+ export interface GraphEntry {
14
+ id: string
15
+ category: string
16
+ key: string
17
+ content: string
18
+ file: string
19
+ tags: string[]
20
+ date: string
21
+ ttl: string
22
+ accessed: number
23
+ /** Explicit outgoing links declared on the entry. */
24
+ links: string[]
25
+ }
26
+
27
+ export interface MemoryGraph {
28
+ /** key -> connected keys (undirected, deduped, only keys that exist). */
29
+ adjacency: Map<string, string[]>
30
+ /** key -> entry (first occurrence wins on duplicate keys). */
31
+ byKey: Map<string, GraphEntry>
32
+ }
33
+
34
+ const isExpiredLocal = (ttl: string): boolean => {
35
+ if (!ttl) return false
36
+ const today = new Date().toISOString().split("T")[0]
37
+ return ttl <= today
38
+ }
39
+
40
+ const normalize = (s: string): string =>
41
+ s.toLowerCase().replace(/[-_]/g, " ").replace(/\s+/g, " ").trim()
42
+
43
+ const entryLines = (data: string): string[] =>
44
+ data
45
+ .split("\n")
46
+ .filter(
47
+ (l) => l.startsWith(" ") && l.includes("|") && !l.startsWith(" summaries:")
48
+ )
49
+
50
+ /**
51
+ * Parse TOON memory content into structured entries.
52
+ * Tolerant of the trailing `links` field (absent on older entries).
53
+ */
54
+ export function parseEntries(data: string): GraphEntry[] {
55
+ const out: GraphEntry[] = []
56
+ for (const line of entryLines(data)) {
57
+ const parts = line.trim().split("|")
58
+ if (parts.length < 7) continue
59
+ const [id, category, key, content, file, tags, date, ttl, accessedRaw, linksRaw] =
60
+ parts
61
+ out.push({
62
+ id,
63
+ category,
64
+ key,
65
+ content,
66
+ file: file || "",
67
+ tags: (tags || "")
68
+ .split(";")
69
+ .map((t) => t.trim())
70
+ .filter(Boolean),
71
+ date: date || "",
72
+ ttl: ttl || "",
73
+ accessed: accessedRaw ? parseInt(accessedRaw) || 0 : 0,
74
+ links: (linksRaw || "")
75
+ .split(/[\s;]+/)
76
+ .map((t) => t.trim())
77
+ .filter(Boolean),
78
+ })
79
+ }
80
+ return out
81
+ }
82
+
83
+ /**
84
+ * Build the adjacency graph from explicit links and implicit `[[key]]` refs.
85
+ * Edges are undirected and only connect keys that actually exist.
86
+ */
87
+ export function buildGraph(entries: GraphEntry[]): MemoryGraph {
88
+ const byKey = new Map<string, GraphEntry>()
89
+ for (const e of entries) {
90
+ if (!byKey.has(e.key)) byKey.set(e.key, e)
91
+ }
92
+
93
+ const adj = new Map<string, Set<string>>()
94
+ const link = (a: string, b: string): void => {
95
+ if (a === b) return
96
+ if (!byKey.has(a) || !byKey.has(b)) return
97
+ if (!adj.has(a)) adj.set(a, new Set())
98
+ adj.get(a)!.add(b)
99
+ if (!adj.has(b)) adj.set(b, new Set())
100
+ adj.get(b)!.add(a)
101
+ }
102
+
103
+ for (const e of entries) {
104
+ for (const l of e.links) link(e.key, l)
105
+ const refs = e.content.match(/\[\[([\w-]+)\]\]/g) || []
106
+ for (const r of refs) link(e.key, r.slice(2, -2))
107
+ }
108
+
109
+ const adjacency = new Map<string, string[]>()
110
+ for (const [k, v] of adj) adjacency.set(k, [...v])
111
+ return { adjacency, byKey }
112
+ }
113
+
114
+ export interface GraphRecallOpts {
115
+ category?: string
116
+ from_date?: string
117
+ to_date?: string
118
+ /** Graph traversal depth from matched seeds (1 or 2). Default 1. */
119
+ hops?: number
120
+ /** Max entries returned (keeps token cost low). Default 6. */
121
+ limit?: number
122
+ }
123
+
124
+ const importance = (e: GraphEntry): number => {
125
+ const today = new Date().toISOString().split("T")[0]
126
+ const days =
127
+ (Date.now() - new Date(`${e.date || today}T00:00:00`).getTime()) / 86400000
128
+ const recency = Math.max(0, 30 - days) / 30
129
+ const freq = Math.min(1, e.accessed / 5)
130
+ return recency * 0.6 + freq * 0.4
131
+ }
132
+
133
+ /**
134
+ * Graph-aware recall. Seeds are keyword matches (AND logic); the result is the
135
+ * ego-subgraph expanded up to `hops` with relevance propagated from seeds.
136
+ * Falls back to top-by-importance when the query matches nothing.
137
+ */
138
+ export function graphRecall(
139
+ data: string,
140
+ query: string,
141
+ opts: GraphRecallOpts = {}
142
+ ): GraphEntry[] {
143
+ const entries = parseEntries(data)
144
+ const { adjacency, byKey } = buildGraph(entries)
145
+ const hops = Math.max(1, Math.min(2, opts.hops ?? 1))
146
+ const category = opts.category || ""
147
+ const from_date = opts.from_date || ""
148
+ const to_date = opts.to_date || ""
149
+
150
+ const queryTokens = normalize(query)
151
+ .split(" ")
152
+ .filter(Boolean)
153
+
154
+ const seedScore = new Map<string, number>()
155
+ for (const e of entries) {
156
+ if (category && e.category !== category) continue
157
+ if (from_date && e.date < from_date) continue
158
+ if (to_date && e.date > to_date) continue
159
+ if (e.ttl && isExpiredLocal(e.ttl)) continue
160
+ const searchStr = normalize(
161
+ `${e.id} ${e.category} ${e.key} ${e.content} ${e.file} ${e.tags.join(" ")}`
162
+ )
163
+ if (queryTokens.length > 0 && !queryTokens.every((t) => searchStr.includes(t)))
164
+ continue
165
+ seedScore.set(e.key, importance(e) + 1.0)
166
+ }
167
+
168
+ // No matches: return the most important entries as a sane fallback.
169
+ if (seedScore.size === 0) {
170
+ return [...entries]
171
+ .sort((a, b) => importance(b) - importance(a))
172
+ .slice(0, opts.limit ?? 6)
173
+ }
174
+
175
+ // BFS from all seeds, recording the shortest hop distance to each node.
176
+ const best = new Map<string, number>()
177
+ const queue: Array<{ key: string; dist: number }> = []
178
+ for (const k of seedScore.keys()) queue.push({ key: k, dist: 0 })
179
+ while (queue.length) {
180
+ const { key, dist } = queue.shift()!
181
+ if (best.has(key) && best.get(key)! <= dist) continue
182
+ best.set(key, dist)
183
+ if (dist >= hops) continue
184
+ for (const nb of adjacency.get(key) || []) {
185
+ queue.push({ key: nb, dist: dist + 1 })
186
+ }
187
+ }
188
+
189
+ const scored = [...best.keys()]
190
+ .map((k) => {
191
+ const e = byKey.get(k)!
192
+ let s = importance(e)
193
+ if (seedScore.has(k)) s += 1.0
194
+ else s += 0.6 / best.get(k)!
195
+ return { e, s }
196
+ })
197
+ .sort((a, b) => b.s - a.s)
198
+
199
+ return scored.slice(0, opts.limit ?? 6).map((x) => x.e)
200
+ }
@@ -0,0 +1,120 @@
1
+ import { openSync, closeSync, writeFileSync, readFileSync, unlinkSync, existsSync, statSync, renameSync } from "fs"
2
+
3
+ /**
4
+ * Minimal, dependency-free, cross-process advisory locking + atomic writes.
5
+ *
6
+ * Used so multiple parallel agent sessions (e.g. several OpenCode sessions)
7
+ * can safely read/modify the same memory files without corrupting them and
8
+ * without a long-lived server. Lock is reentrant within the same process.
9
+ */
10
+
11
+ const STALE_MS = 15000
12
+ const LOCK_TIMEOUT_MS = 10000
13
+
14
+ function isAlive(pid: number): boolean {
15
+ if (!pid || pid <= 0) return false
16
+ try {
17
+ process.kill(pid, 0)
18
+ return true
19
+ } catch {
20
+ return false
21
+ }
22
+ }
23
+
24
+ function tryAcquire(lockFile: string): boolean {
25
+ if (existsSync(lockFile)) {
26
+ const age = Date.now() - statSync(lockFile).mtimeMs
27
+ let stale = age > STALE_MS
28
+ if (!stale) {
29
+ try {
30
+ const pid = parseInt(readFileSync(lockFile, "utf-8").trim(), 10)
31
+ if (!isAlive(pid)) stale = true
32
+ } catch {
33
+ stale = true
34
+ }
35
+ }
36
+ if (stale) {
37
+ try {
38
+ unlinkSync(lockFile)
39
+ } catch {
40
+ // ignore
41
+ }
42
+ } else {
43
+ return false
44
+ }
45
+ }
46
+ try {
47
+ const fd = openSync(lockFile, "wx")
48
+ writeFileSync(fd, String(process.pid))
49
+ closeSync(fd)
50
+ return true
51
+ } catch {
52
+ return false
53
+ }
54
+ }
55
+
56
+ const held = new Map<string, number>()
57
+
58
+ /** Run `fn` while holding an advisory lock on `file` (cross-process safe). */
59
+ export function withLockSync(file: string, fn: () => void): void {
60
+ const lockFile = `${file}.lock`
61
+ const depth = held.get(lockFile) ?? 0
62
+ if (depth > 0) {
63
+ held.set(lockFile, depth + 1)
64
+ try {
65
+ fn()
66
+ } finally {
67
+ const d = (held.get(lockFile) ?? 0) - 1
68
+ if (d <= 0) held.delete(lockFile)
69
+ else held.set(lockFile, d)
70
+ }
71
+ return
72
+ }
73
+
74
+ const deadline = Date.now() + LOCK_TIMEOUT_MS
75
+ while (!tryAcquire(lockFile)) {
76
+ if (Date.now() > deadline) throw new Error(`toon-memory lock timeout: ${file}`)
77
+ const t = Date.now() + 10
78
+ while (Date.now() < t) {
79
+ // busy-wait (short; tool writes are infrequent)
80
+ }
81
+ }
82
+
83
+ held.set(lockFile, 1)
84
+ try {
85
+ fn()
86
+ } finally {
87
+ const d = (held.get(lockFile) ?? 0) - 1
88
+ if (d <= 0) {
89
+ held.delete(lockFile)
90
+ try {
91
+ unlinkSync(lockFile)
92
+ } catch {
93
+ // ignore
94
+ }
95
+ } else {
96
+ held.set(lockFile, d)
97
+ }
98
+ }
99
+ }
100
+
101
+ /** Write `content` to `file` atomically via a temp file + rename (crash-safe). */
102
+ export function atomicWrite(file: string, content: string): void {
103
+ const tmp = `${file}.tmp`
104
+ writeFileSync(tmp, content)
105
+ renameSync(tmp, file)
106
+ }
107
+
108
+ /**
109
+ * Read `file` while holding its advisory lock (cross-process safe).
110
+ * Use for read-modify-write sequences (e.g. pruning expired entries) that
111
+ * must not race another process writing the same file. Reentrant with
112
+ * `withLockSync`, so it is safe to call from inside an outer lock.
113
+ */
114
+ export function readUnderLock(file: string, encoding: BufferEncoding = "utf-8"): string {
115
+ let content = ""
116
+ withLockSync(file, () => {
117
+ content = readFileSync(file, encoding)
118
+ })
119
+ return content
120
+ }
@@ -0,0 +1,225 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, unlinkSync, statSync } from "fs"
2
+ import { join } from "path"
3
+ import { execSync } from "child_process"
4
+
5
+ /**
6
+ * File-based multi-session coordination — no server, no network, no LLM.
7
+ *
8
+ * Each agent session owns exactly one heartbeat file under
9
+ * `.toon-memory/memory/sessions/<id>.json`. Every process only ever writes
10
+ * its OWN file (lock-free). Reads across files give other sessions a shared,
11
+ * eventually-consistent view so parallel sessions (e.g. several OpenCode
12
+ * windows) can see each other, their git branch, and which files they touch
13
+ * — and avoid stepping on each other.
14
+ *
15
+ * A session is "active" while its last heartbeat is within SESSION_TTL_MS.
16
+ * Dead sessions (pid no longer alive + stale heartbeat) are pruned lazily.
17
+ */
18
+
19
+ /** A session is considered active if it sent a heartbeat within this window. */
20
+ export const SESSION_TTL_MS = 10 * 60 * 1000
21
+
22
+ /** How stale a dead session must be before we delete its file. */
23
+ export const PRUNE_STALE_MS = 10 * 60 * 1000
24
+
25
+ export interface SessionRecord {
26
+ id: string
27
+ agent: string
28
+ pid: number
29
+ branch: string
30
+ startedAt: string
31
+ lastSeen: string
32
+ ended: boolean
33
+ files: Record<string, string> // path -> lastTouch ISO
34
+ }
35
+
36
+ function isAlive(pid: number): boolean {
37
+ if (!pid || pid <= 0) return false
38
+ try {
39
+ process.kill(pid, 0)
40
+ return true
41
+ } catch {
42
+ return false
43
+ }
44
+ }
45
+
46
+ function sessionDir(): string {
47
+ return join(process.cwd(), ".toon-memory", "memory", "sessions")
48
+ }
49
+
50
+ function sessionPath(id: string): string {
51
+ return join(sessionDir(), `${id}.json`)
52
+ }
53
+
54
+ function ensureSessionDir(): void {
55
+ const dir = sessionDir()
56
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
57
+ }
58
+
59
+ /** Resolve a stable session id: agent payload first, then env override. */
60
+ export function resolveSessionId(payload: Record<string, unknown> = {}): string {
61
+ const fromPayload =
62
+ (payload.session_id as string) ||
63
+ (payload.sessionId as string) ||
64
+ (payload.session_id_untruncated as string)
65
+ if (fromPayload && fromPayload.trim()) return fromPayload.trim()
66
+
67
+ if (process.env.TOON_MEMORY_SESSION_ID && process.env.TOON_MEMORY_SESSION_ID.trim()) {
68
+ return process.env.TOON_MEMORY_SESSION_ID.trim()
69
+ }
70
+
71
+ // Fallback: a per-process random id. Coordination is best-effort in this
72
+ // case (no stable session across hook invocations), but the file still
73
+ // records presence for the lifetime of the calling process.
74
+ return `proc-${process.pid}-${Math.random().toString(36).slice(2, 10)}`
75
+ }
76
+
77
+ /** Detect the current git branch; falls back to env or "unknown". */
78
+ export function currentBranch(): string {
79
+ if (process.env.TOON_MEMORY_BRANCH && process.env.TOON_MEMORY_BRANCH.trim()) {
80
+ return process.env.TOON_MEMORY_BRANCH.trim()
81
+ }
82
+ try {
83
+ const branch = execSync("git rev-parse --abbrev-ref HEAD", {
84
+ encoding: "utf-8",
85
+ timeout: 2000,
86
+ stdio: ["ignore", "pipe", "ignore"],
87
+ }).trim()
88
+ return branch || "unknown"
89
+ } catch {
90
+ return "unknown"
91
+ }
92
+ }
93
+
94
+ function readRecord(id: string): SessionRecord | null {
95
+ const p = sessionPath(id)
96
+ if (!existsSync(p)) return null
97
+ try {
98
+ return JSON.parse(readFileSync(p, "utf-8")) as SessionRecord
99
+ } catch {
100
+ return null
101
+ }
102
+ }
103
+
104
+ /** Create or refresh the calling session's heartbeat file. */
105
+ export function heartbeat(agent: string, sessionId: string, opts: { file?: string; ended?: boolean } = {}): void {
106
+ ensureSessionDir()
107
+ const now = new Date().toISOString()
108
+ const existing = readRecord(sessionId)
109
+ const record: SessionRecord = existing
110
+ ? { ...existing, agent, pid: process.pid, lastSeen: now, branch: currentBranch(), ended: opts.ended ?? existing.ended }
111
+ : {
112
+ id: sessionId,
113
+ agent,
114
+ pid: process.pid,
115
+ branch: currentBranch(),
116
+ startedAt: now,
117
+ lastSeen: now,
118
+ ended: opts.ended ?? false,
119
+ files: {},
120
+ }
121
+
122
+ if (opts.file && opts.file.trim()) {
123
+ record.files[opts.file.trim()] = now
124
+ }
125
+
126
+ writeFileSync(sessionPath(sessionId), JSON.stringify(record, null, 2))
127
+ }
128
+
129
+ /** Mark the calling session as ended (kept visible until TTL, then pruned). */
130
+ export function endSession(agent: string, sessionId: string): void {
131
+ heartbeat(agent, sessionId, { ended: true })
132
+ }
133
+
134
+ interface ActiveSessionView extends SessionRecord {
135
+ active: boolean
136
+ ageMs: number
137
+ }
138
+
139
+ function recentIso(iso: string): boolean {
140
+ const t = new Date(iso).getTime()
141
+ return !isNaN(t) && Date.now() - t <= SESSION_TTL_MS
142
+ }
143
+
144
+ /** Read all session records with an `active` flag. */
145
+ export function listSessions(): ActiveSessionView[] {
146
+ const dir = sessionDir()
147
+ if (!existsSync(dir)) return []
148
+ return readdirSync(dir)
149
+ .filter((f) => f.endsWith(".json"))
150
+ .map((f) => {
151
+ try {
152
+ return JSON.parse(readFileSync(join(dir, f), "utf-8")) as SessionRecord
153
+ } catch {
154
+ return null
155
+ }
156
+ })
157
+ .filter(Boolean)
158
+ .map((r) => {
159
+ const rec = r as SessionRecord
160
+ const active = recentIso(rec.lastSeen)
161
+ return { ...rec, active, ageMs: Date.now() - new Date(rec.lastSeen).getTime() }
162
+ })
163
+ .sort((a, b) => b.lastSeen.localeCompare(a.lastSeen))
164
+ }
165
+
166
+ /**
167
+ * Remove dead sessions: pid not alive AND heartbeat older than PRUNE_STALE_MS.
168
+ * Safe because we never delete a file whose owner process is still running.
169
+ * Returns the ids that were pruned.
170
+ */
171
+ export function pruneSessions(): string[] {
172
+ const pruned: string[] = []
173
+ const dir = sessionDir()
174
+ if (!existsSync(dir)) return pruned
175
+ for (const f of readdirSync(dir).filter((x) => x.endsWith(".json"))) {
176
+ const p = join(dir, f)
177
+ let rec: SessionRecord | null = null
178
+ try {
179
+ rec = JSON.parse(readFileSync(p, "utf-8"))
180
+ } catch {
181
+ continue
182
+ }
183
+ if (!rec) continue
184
+ const stale = Date.now() - new Date(rec.lastSeen).getTime() > PRUNE_STALE_MS
185
+ if (stale && !isAlive(rec.pid)) {
186
+ try {
187
+ unlinkSync(p)
188
+ pruned.push(rec.id)
189
+ } catch {
190
+ // ignore
191
+ }
192
+ }
193
+ }
194
+ return pruned
195
+ }
196
+
197
+ /** Detect soft conflicts: files touched by >=2 active sessions. */
198
+ export function detectConflicts(active: ActiveSessionView[] = listSessions().filter((s) => s.active)): {
199
+ file: string
200
+ sessions: Array<{ id: string; agent: string; branch: string }>
201
+ }[] {
202
+ const byFile = new Map<string, Array<{ id: string; agent: string; branch: string }>>()
203
+ for (const s of active) {
204
+ if (s.ended) continue
205
+ for (const file of Object.keys(s.files)) {
206
+ if (!byFile.has(file)) byFile.set(file, [])
207
+ byFile.get(file)!.push({ id: s.id, agent: s.agent, branch: s.branch })
208
+ }
209
+ }
210
+ const conflicts: { file: string; sessions: Array<{ id: string; agent: string; branch: string }> }[] = []
211
+ for (const [file, sessions] of byFile) {
212
+ if (sessions.length >= 2) conflicts.push({ file, sessions })
213
+ }
214
+ return conflicts
215
+ }
216
+
217
+ /** Convenience: list active sessions + conflicts in one call. */
218
+ export function coordinationView(selfId?: string) {
219
+ const all = listSessions()
220
+ const active = all.filter((s) => s.active)
221
+ const conflicts = detectConflicts(active)
222
+ const self = selfId ? all.find((s) => s.id === selfId) : undefined
223
+ pruneSessions()
224
+ return { active, conflicts, self }
225
+ }