@zhangfeiyue/dsh-long-term-memory 0.0.0-stage → 1.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.
package/lib/store.js ADDED
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Durable memory store: an append-only JSON-lines log plus in-memory fold.
3
+ *
4
+ * Why a log instead of one JSON document:
5
+ * - An append is a single small write, so a crash loses at most the record being
6
+ * written, never the whole store.
7
+ * - Folding the log at load time is trivially recoverable, and a corrupt trailing
8
+ * line is skipped rather than failing the plugin.
9
+ * - Compaction rewrites only live records, so deleted and superseded history
10
+ * cannot grow without bound.
11
+ *
12
+ * The store lives outside every workspace (`~/.dsh/long-term-memory` by default)
13
+ * so memory survives workspace deletion and is shared by all sessions.
14
+ *
15
+ * @module dsh-long-term-memory/store
16
+ */
17
+
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import { newId, now } from './util.js'
21
+
22
+ const LOG_VERSION = 1
23
+ const BACKUP_KEEP = 5
24
+
25
+ /**
26
+ * Stamp one record with its lifetime fields.
27
+ *
28
+ * An explicit `updatedAt` is preserved rather than overwritten: `update()` relies
29
+ * on that to allow back-dating during import, repair or a migration.
30
+ *
31
+ * Otherwise the timestamp is nudged forward to stay strictly greater than the
32
+ * previous version. Two writes inside one millisecond would otherwise produce an
33
+ * identical `updatedAt`, and the board's optimistic-concurrency check compares
34
+ * exactly that value — a stale tab would be able to overwrite a newer memory.
35
+ */
36
+ function stamp(record, previous) {
37
+ const timestamp = now()
38
+ const previousUpdatedAt = Number(previous?.updatedAt)
39
+ const explicit = Number.isFinite(record.updatedAt) ? record.updatedAt : undefined
40
+ let updatedAt = explicit ?? timestamp
41
+ if (explicit === undefined && Number.isFinite(previousUpdatedAt) && updatedAt <= previousUpdatedAt) {
42
+ updatedAt = previousUpdatedAt + 1
43
+ }
44
+ return {
45
+ ...record,
46
+ createdAt: previous?.createdAt ?? record.createdAt ?? timestamp,
47
+ updatedAt,
48
+ }
49
+ }
50
+
51
+ /**
52
+ * A crash-safe, append-only record store.
53
+ *
54
+ * All mutating methods are synchronous and serialized by the JavaScript event
55
+ * loop, which is enough for the single Desktop host process. Multi-process
56
+ * safety comes from append-only lines: concurrent appenders never rewrite the
57
+ * file, and a torn final line is discarded at the next load.
58
+ */
59
+ export class MemoryStore {
60
+ /**
61
+ * @param {object} settings - resolved plugin settings (see `config.js`).
62
+ */
63
+ constructor(settings) {
64
+ this.settings = settings
65
+ this.dir = settings.storeDir
66
+ this.logPath = path.join(this.dir, 'records.jsonl')
67
+ this.backupDir = path.join(this.dir, 'backup')
68
+ this.logDir = path.join(this.dir, 'logs')
69
+ /** @type {Map<string, object>} id -> record */
70
+ this.records = new Map()
71
+ /** @type {Set<() => void>} change subscribers, e.g. the SSE board */
72
+ this.listeners = new Set()
73
+ this.lineCount = 0
74
+ this.corruptLines = 0
75
+ this.lastConsolidatedAt = 0
76
+ this.lastCompactedAt = 0
77
+ this.loadedAt = 0
78
+ this.error = null
79
+ }
80
+
81
+ /** Create the store directories when they are missing. */
82
+ ensureDirs() {
83
+ fs.mkdirSync(this.dir, { recursive: true })
84
+ fs.mkdirSync(this.backupDir, { recursive: true })
85
+ fs.mkdirSync(this.logDir, { recursive: true })
86
+ }
87
+
88
+ /**
89
+ * Load and fold the log. Never throws: a read failure is recorded on
90
+ * {@link MemoryStore.error} and leaves an empty store, so a damaged memory
91
+ * directory cannot stop a session from starting.
92
+ */
93
+ load() {
94
+ this.records.clear()
95
+ this.lineCount = 0
96
+ this.corruptLines = 0
97
+ this.error = null
98
+ try {
99
+ this.ensureDirs()
100
+ } catch (error) {
101
+ this.error = `cannot create store directory: ${error?.message ?? error}`
102
+ this.loadedAt = now()
103
+ return this
104
+ }
105
+ let raw = ''
106
+ try {
107
+ raw = fs.readFileSync(this.logPath, 'utf8')
108
+ } catch (error) {
109
+ if (error?.code !== 'ENOENT') this.error = `cannot read log: ${error?.message ?? error}`
110
+ this.loadedAt = now()
111
+ return this
112
+ }
113
+ for (const line of raw.split('\n')) {
114
+ if (line.trim().length === 0) continue
115
+ this.lineCount += 1
116
+ let op
117
+ try {
118
+ op = JSON.parse(line)
119
+ } catch {
120
+ this.corruptLines += 1
121
+ continue
122
+ }
123
+ this.applyOp(op)
124
+ }
125
+ this.loadedAt = now()
126
+ return this
127
+ }
128
+
129
+ /** Fold one log operation into memory. Unknown shapes are ignored. */
130
+ applyOp(op) {
131
+ if (op === null || typeof op !== 'object') return
132
+ if (op.op === 'u' && op.rec !== null && typeof op.rec === 'object' && typeof op.rec.id === 'string') {
133
+ this.records.set(op.rec.id, op.rec)
134
+ return
135
+ }
136
+ if (op.op === 'd' && typeof op.id === 'string') {
137
+ this.records.delete(op.id)
138
+ }
139
+ }
140
+
141
+ /** Append one operation to the durable log. */
142
+ appendOp(op) {
143
+ const payload = `${JSON.stringify({ v: LOG_VERSION, ...op })}\n`
144
+ try {
145
+ this.ensureDirs()
146
+ fs.appendFileSync(this.logPath, payload, 'utf8')
147
+ this.lineCount += 1
148
+ } catch (error) {
149
+ this.error = `cannot append to log: ${error?.message ?? error}`
150
+ this.writeLogLine('error', this.error)
151
+ }
152
+ }
153
+
154
+ /** Subscribe to store mutations. The callback must not throw. */
155
+ subscribe(listener) {
156
+ this.listeners.add(listener)
157
+ return () => { this.listeners.delete(listener) }
158
+ }
159
+
160
+ /**
161
+ * Tell subscribers that something changed.
162
+ *
163
+ * Notifications are deliberately coarse: subscribers re-render from the store
164
+ * rather than applying a diff, so a missed or duplicated notification cannot
165
+ * desynchronize a client.
166
+ */
167
+ notify() {
168
+ for (const listener of this.listeners) {
169
+ try {
170
+ listener()
171
+ } catch {
172
+ // A broken subscriber must not break a write.
173
+ }
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Insert or replace one record.
179
+ * @param {object} record - record body; `id` is minted when absent.
180
+ * @returns {object} the stored record.
181
+ */
182
+ put(record) {
183
+ const existing = typeof record.id === 'string' ? this.records.get(record.id) : undefined
184
+ const stored = stamp({ ...record, id: record.id ?? newId() }, existing)
185
+ this.records.set(stored.id, stored)
186
+ this.appendOp({ op: 'u', rec: stored })
187
+ this.notify()
188
+ return stored
189
+ }
190
+
191
+ /** Merge a patch into an existing record and persist it. */
192
+ update(id, patch) {
193
+ const existing = this.records.get(id)
194
+ if (existing === undefined) return undefined
195
+ // `createdAt` is immutable. `updatedAt` advances to now unless the patch
196
+ // states one explicitly, so an ordinary correction cannot leave a stale
197
+ // timestamp while a deliberate back-date still works.
198
+ const { createdAt: _createdAt, updatedAt: explicitUpdatedAt, ...rest } = patch
199
+ const stored = stamp({
200
+ ...existing,
201
+ ...rest,
202
+ id,
203
+ // `undefined` means "advance the clock"; an explicit value is a back-date.
204
+ ...explicitUpdatedAt === undefined ? { updatedAt: undefined } : { updatedAt: explicitUpdatedAt },
205
+ }, existing)
206
+ this.records.set(id, stored)
207
+ this.appendOp({ op: 'u', rec: stored })
208
+ this.notify()
209
+ return stored
210
+ }
211
+
212
+ /** Remove one record from the store. */
213
+ remove(id) {
214
+ if (!this.records.has(id)) return false
215
+ this.records.delete(id)
216
+ this.appendOp({ op: 'd', id })
217
+ this.notify()
218
+ return true
219
+ }
220
+
221
+ /** The record with this id, when present. */
222
+ get(id) {
223
+ return this.records.get(id)
224
+ }
225
+
226
+ /** Every record, live and archived. */
227
+ all() {
228
+ return [...this.records.values()]
229
+ }
230
+
231
+ /** Counts by status, kind and scope, for the admin tool and diagnostics. */
232
+ stats() {
233
+ const byStatus = {}
234
+ const byKind = {}
235
+ const byScope = {}
236
+ let bytes = 0
237
+ for (const record of this.records.values()) {
238
+ byStatus[record.status ?? 'active'] = (byStatus[record.status ?? 'active'] ?? 0) + 1
239
+ byKind[record.kind ?? 'note'] = (byKind[record.kind ?? 'note'] ?? 0) + 1
240
+ byScope[record.scope ?? 'global'] = (byScope[record.scope ?? 'global'] ?? 0) + 1
241
+ bytes += JSON.stringify(record).length
242
+ }
243
+ return {
244
+ storeDir: this.dir,
245
+ logPath: this.logPath,
246
+ records: this.records.size,
247
+ logLines: this.lineCount,
248
+ corruptLines: this.corruptLines,
249
+ approxBytes: bytes,
250
+ byStatus,
251
+ byKind,
252
+ byScope,
253
+ lastCompactedAt: this.lastCompactedAt || null,
254
+ lastConsolidatedAt: this.lastConsolidatedAt || null,
255
+ error: this.error,
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Rewrite the log with only live records, keeping a dated backup first.
261
+ * @param {boolean} keepBackup - whether to copy the previous log to `backup/`.
262
+ * @returns {{compacted: boolean, records: number, backup?: string, error?: string}}
263
+ */
264
+ compact(keepBackup = true) {
265
+ this.ensureDirs()
266
+ let backup
267
+ try {
268
+ if (keepBackup && fs.existsSync(this.logPath)) {
269
+ backup = path.join(this.backupDir, `records-${new Date().toISOString().replace(/[:.]/g, '-')}.jsonl`)
270
+ fs.copyFileSync(this.logPath, backup)
271
+ this.pruneBackups()
272
+ }
273
+ const lines = []
274
+ for (const record of this.records.values()) {
275
+ lines.push(JSON.stringify({ v: LOG_VERSION, op: 'u', rec: record }))
276
+ }
277
+ const target = `${this.logPath}.tmp`
278
+ const fd = fs.openSync(target, 'w')
279
+ try {
280
+ fs.writeSync(fd, lines.length === 0 ? '' : `${lines.join('\n')}\n`, null, 'utf8')
281
+ fs.fsyncSync(fd)
282
+ } finally {
283
+ fs.closeSync(fd)
284
+ }
285
+ fs.renameSync(target, this.logPath)
286
+ this.lineCount = lines.length
287
+ this.corruptLines = 0
288
+ this.lastCompactedAt = now()
289
+ return { compacted: true, records: this.records.size, ...backup === undefined ? {} : { backup } }
290
+ } catch (error) {
291
+ const message = `compaction failed: ${error?.message ?? error}`
292
+ this.error = message
293
+ this.writeLogLine('error', message)
294
+ return { compacted: false, records: this.records.size, error: message }
295
+ }
296
+ }
297
+
298
+ /** Keep only the most recent {@link BACKUP_KEEP} backups. */
299
+ pruneBackups() {
300
+ try {
301
+ const files = fs.readdirSync(this.backupDir)
302
+ .filter(name => name.startsWith('records-') && name.endsWith('.jsonl'))
303
+ .sort()
304
+ for (const name of files.slice(0, Math.max(0, files.length - BACKUP_KEEP))) {
305
+ fs.rmSync(path.join(this.backupDir, name), { force: true })
306
+ }
307
+ } catch {
308
+ // Backups are best-effort.
309
+ }
310
+ }
311
+
312
+ /** Whether the log has grown enough that compaction is worthwhile. */
313
+ shouldCompact() {
314
+ return this.lineCount > Math.max(500, this.records.size * 4)
315
+ }
316
+
317
+ /**
318
+ * Append one line to the plugin log, rotating at 1 MiB. Diagnostics are
319
+ * best-effort and never throw into a session.
320
+ */
321
+ writeLogLine(level, message) {
322
+ try {
323
+ this.ensureDirs()
324
+ const file = path.join(this.logDir, 'plugin.log')
325
+ const stampText = new Date().toISOString()
326
+ const line = `${stampText} [${level}] ${String(message)}\n`
327
+ try {
328
+ const stat = fs.statSync(file)
329
+ if (stat.size > 1_048_576) fs.renameSync(file, `${file}.1`)
330
+ } catch {
331
+ // No previous log.
332
+ }
333
+ fs.appendFileSync(file, line, 'utf8')
334
+ } catch {
335
+ // Never let logging break a session.
336
+ }
337
+ }
338
+ }