toon-memory 2.0.0 → 2.1.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,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
+ }