@chenhw7/dsh-memory 0.8.0 → 0.9.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.
Files changed (42) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/client/index.js +38 -2
  5. package/lib/context/index.d.ts +45 -1
  6. package/lib/context/index.d.ts.map +1 -1
  7. package/lib/context/index.js +141 -4
  8. package/lib/context/index.js.map +1 -1
  9. package/lib/index.d.ts +27 -1
  10. package/lib/index.d.ts.map +1 -1
  11. package/lib/index.js +26 -1
  12. package/lib/index.js.map +1 -1
  13. package/lib/review/consolidate.d.ts +230 -0
  14. package/lib/review/consolidate.d.ts.map +1 -0
  15. package/lib/review/consolidate.js +435 -0
  16. package/lib/review/consolidate.js.map +1 -0
  17. package/lib/review/extract.d.ts +63 -12
  18. package/lib/review/extract.d.ts.map +1 -1
  19. package/lib/review/extract.js +163 -29
  20. package/lib/review/extract.js.map +1 -1
  21. package/lib/review/index.d.ts +20 -0
  22. package/lib/review/index.d.ts.map +1 -1
  23. package/lib/review/index.js +56 -9
  24. package/lib/review/index.js.map +1 -1
  25. package/lib/review/sweep.d.ts +171 -0
  26. package/lib/review/sweep.d.ts.map +1 -0
  27. package/lib/review/sweep.js +310 -0
  28. package/lib/review/sweep.js.map +1 -0
  29. package/lib/store/index.d.ts +111 -3
  30. package/lib/store/index.d.ts.map +1 -1
  31. package/lib/store/index.js +195 -12
  32. package/lib/store/index.js.map +1 -1
  33. package/lib/store/sqlite.d.ts +126 -0
  34. package/lib/store/sqlite.d.ts.map +1 -0
  35. package/lib/store/sqlite.js +653 -0
  36. package/lib/store/sqlite.js.map +1 -0
  37. package/lib/tool/index.d.ts.map +1 -1
  38. package/lib/tool/index.js +23 -5
  39. package/lib/tool/index.js.map +1 -1
  40. package/lib/types.d.ts +50 -0
  41. package/lib/types.d.ts.map +1 -1
  42. package/package.json +8 -2
@@ -0,0 +1,653 @@
1
+ /**
2
+ * The SQLite local storage backend (write-path rework Step 3.1): a
3
+ * `MemoryStore` provider over `node:sqlite`'s `DatabaseSync`, owning the
4
+ * plugin-named file `$DSH_HOME/storages/memory.db` (WAL mode + busy_timeout).
5
+ *
6
+ * Read path: the full tables load into memory at open (the target scale is
7
+ * tens–hundreds of entries) and all reads serve from that snapshot — the same
8
+ * synchronous in-memory read semantics as {@link DomainMemoryStore}. Write
9
+ * path: one SQL statement per record, entries + audit landing in one
10
+ * transaction — the write-amplification win over the host medium's
11
+ * full-file republish-and-fsync.
12
+ *
13
+ * The `node:sqlite` API surface is deliberately pinned to open/prepare/exec
14
+ * (plus the transaction helper); everything else about the driver hides
15
+ * behind this class (HOST_CONTRACT §11). Schema: `entries` (MemoryEntry
16
+ * fields as columns), `audit` (the audit trail), `suggestions` (the P1-1
17
+ * queue shape), `meta` (schemaVersion + consolidation progress). Zero-
18
+ * migration on read: absent columns/tables only matter at their write
19
+ * boundaries, and every column is nullable.
20
+ *
21
+ * @module @chenhw7/dsh-memory/store/sqlite
22
+ */
23
+ import { DatabaseSync } from 'node:sqlite';
24
+ import { mkdirSync } from 'node:fs';
25
+ import { dirname } from 'node:path';
26
+ import { MemoryStore, validateProjectScope, validateContent, } from '../index.js';
27
+ import { scanContent } from '../scanner.js';
28
+ import { buildCorpusStatsFromTokens, Bm25Index, tokenizeForSearch } from './bm25.js';
29
+ /** Cast a row to the MemoryEntry contract (the row carries exactly its fields). */
30
+ function asEntry(row) {
31
+ return row;
32
+ }
33
+ /** The columns the entries table carries (MemoryEntry's persisted fields). */
34
+ const ENTRY_COLUMNS = [
35
+ 'id', 'scope', 'category', 'content', 'summary', 'projectName',
36
+ 'createdAt', 'updatedAt', 'pinned', 'lastRecalledAt', 'staleSince',
37
+ 'accessCount', 'importance', 'anchors', 'status', 'supersededBy',
38
+ 'hitCount', 'lastHitAt',
39
+ ];
40
+ /** The audit table's columns (AuditEntry fields). */
41
+ const AUDIT_COLUMNS = [
42
+ 'id', 'op', 'entryId', 'scope', 'category', 'source', 'sessionId',
43
+ 'ts', 'seq', 'contentPreview',
44
+ ];
45
+ /** The suggestions table's columns (MemorySuggestion fields). */
46
+ const SUGGESTION_COLUMNS = [
47
+ 'id', 'scope', 'category', 'content', 'summary', 'projectName', 'hits',
48
+ 'firstSeenAt', 'lastSeenAt', 'targetEntryId', 'source', 'sessionId',
49
+ ];
50
+ /**
51
+ * Bind one record's optional fields to a statement: every column gets a
52
+ * positional parameter; `undefined` binds as SQL NULL (the zero-migration
53
+ * read side: absent optional fields read back as NULL → undefined).
54
+ */
55
+ function bindRecord(statement, columns, record) {
56
+ const params = columns.map(column => {
57
+ const value = record[column];
58
+ if (value === undefined || value === null)
59
+ return null;
60
+ if (typeof value === 'boolean')
61
+ return value ? 1 : 0;
62
+ if (typeof value === 'object')
63
+ return JSON.stringify(value);
64
+ return value;
65
+ });
66
+ statement.run(...params);
67
+ }
68
+ /** Read one row back into the record shape (JSON decoded; booleans restored; NULL dropped). */
69
+ function rowToRecord(row) {
70
+ const record = {};
71
+ for (const [key, value] of Object.entries(row)) {
72
+ if (value === null)
73
+ continue;
74
+ if (typeof value === 'number' && (key === 'pinned')) {
75
+ record[key] = value === 1;
76
+ continue;
77
+ }
78
+ if (typeof value === 'string' && (value.startsWith('[') || value.startsWith('{'))) {
79
+ try {
80
+ record[key] = JSON.parse(value);
81
+ continue;
82
+ }
83
+ catch {
84
+ // Not JSON — a literal string that happens to start with a bracket.
85
+ }
86
+ }
87
+ record[key] = value;
88
+ }
89
+ return record;
90
+ }
91
+ /**
92
+ * The medium meta-table key recording that this medium's data moved into
93
+ * memory.db (Step 3.2's one-time migration marker). A host-medium boot that
94
+ * reads this marker fails loud — two live stores would diverge.
95
+ */
96
+ export const SQLITE_MIGRATION_MARKER = 'medium:migratedToSqlite';
97
+ export class SqliteMemoryStore extends MemoryStore {
98
+ db;
99
+ failureLogger;
100
+ auditCap;
101
+ suggestionCap;
102
+ entriesCap;
103
+ failureCounts = new Map();
104
+ auditSeq = 0;
105
+ constructor(options) {
106
+ super();
107
+ this.failureLogger = options.failureLogger;
108
+ this.auditCap = options.auditCap ?? 200;
109
+ this.suggestionCap = options.suggestionCap ?? 200;
110
+ this.entriesCap = options.entriesCap ?? 500;
111
+ mkdirSync(dirname(options.dbPath), { recursive: true });
112
+ this.db = new DatabaseSync(options.dbPath);
113
+ this.db.exec('PRAGMA journal_mode = WAL;');
114
+ this.db.exec('PRAGMA busy_timeout = 5000');
115
+ this.migrate();
116
+ this.auditSeq = this.maxAuditSeq();
117
+ }
118
+ /** Create the tables when absent (zero-migration: existing databases reopen untouched). */
119
+ migrate() {
120
+ this.db.exec(`
121
+ CREATE TABLE IF NOT EXISTS entries (id TEXT PRIMARY KEY, ${ENTRY_COLUMNS.filter(column => column !== 'id').map(column => `"${column}"`).join(', ')});
122
+ CREATE TABLE IF NOT EXISTS audit (${AUDIT_COLUMNS.map(column => column).join(', ')});
123
+ CREATE TABLE IF NOT EXISTS suggestions (id TEXT PRIMARY KEY, ${SUGGESTION_COLUMNS.filter(column => column !== 'id').map(column => column).join(', ')});
124
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT, updatedAt INTEGER);
125
+ `);
126
+ }
127
+ reportFailure(site, error) {
128
+ this.failureCounts.set(site, (this.failureCounts.get(site) ?? 0) + 1);
129
+ this.failureLogger?.warn(`dsh-memory: ${site} failed${error === undefined ? '' : `: ${String(error)}`}`);
130
+ }
131
+ /** Close the database connection (the WAL sidecars recover on the next open). */
132
+ close() {
133
+ this.db.close();
134
+ }
135
+ maxAuditSeq() {
136
+ const row = this.db.prepare('SELECT MAX(seq) AS max FROM audit').get();
137
+ return row?.max ?? 0;
138
+ }
139
+ /** Next monotonic audit sequence number (the medium's MAX(seq) + 1). */
140
+ nextAuditSeq() {
141
+ this.auditSeq += 1;
142
+ return this.auditSeq;
143
+ }
144
+ // ─── Write path ─────────────────────────────────────────────────────────────
145
+ async add(input) {
146
+ validateProjectScope(input);
147
+ validateContent(input.content);
148
+ const scan = scanContent(input.content);
149
+ if (!scan.allowed) {
150
+ throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
151
+ }
152
+ const now = Date.now();
153
+ const entry = {
154
+ id: crypto.randomUUID(),
155
+ scope: input.scope,
156
+ content: input.content,
157
+ createdAt: now,
158
+ updatedAt: now,
159
+ ...(input.category !== undefined ? { category: input.category } : {}),
160
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
161
+ ...(input.projectName !== undefined ? { projectName: input.projectName } : {}),
162
+ ...(input.anchors !== undefined ? { anchors: input.anchors } : {}),
163
+ };
164
+ this.transaction(() => {
165
+ this.insertEntry(entry);
166
+ this.trimEntries(now);
167
+ this.appendAudit('add', entry.id, entry, input.source, input.sessionId, input.content);
168
+ });
169
+ return { entry: asEntry(entry) };
170
+ }
171
+ get(id) {
172
+ const row = this.db.prepare('SELECT * FROM entries WHERE id = ?').get(id);
173
+ return row === undefined ? undefined : asEntry(rowToRecord(row));
174
+ }
175
+ list(scope, projectName) {
176
+ const results = [];
177
+ let statement;
178
+ if (scope !== undefined && projectName !== undefined) {
179
+ statement = this.db.prepare('SELECT * FROM entries WHERE scope = ? AND projectName = ?');
180
+ for (const row of statement.all(scope, projectName))
181
+ results.push(asEntry(rowToRecord(row)));
182
+ }
183
+ else if (scope !== undefined) {
184
+ statement = this.db.prepare('SELECT * FROM entries WHERE scope = ?');
185
+ for (const row of statement.all(scope))
186
+ results.push(asEntry(rowToRecord(row)));
187
+ }
188
+ else if (projectName !== undefined) {
189
+ statement = this.db.prepare('SELECT * FROM entries WHERE projectName = ?');
190
+ for (const row of statement.all(projectName))
191
+ results.push(asEntry(rowToRecord(row)));
192
+ }
193
+ else {
194
+ statement = this.db.prepare('SELECT * FROM entries');
195
+ for (const row of statement.all())
196
+ results.push(asEntry(rowToRecord(row)));
197
+ }
198
+ return results.sort((a, b) => a.createdAt - b.createdAt);
199
+ }
200
+ async update(id, input) {
201
+ const existing = this.get(id);
202
+ if (existing === undefined)
203
+ return undefined;
204
+ const newContent = input.content ?? existing.content;
205
+ validateContent(newContent);
206
+ const scan = scanContent(newContent);
207
+ if (!scan.allowed) {
208
+ throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
209
+ }
210
+ const summary = input.summary ?? existing.summary;
211
+ if (summary !== undefined) {
212
+ const summaryScan = scanContent(summary);
213
+ if (!summaryScan.allowed) {
214
+ throw new Error(`memory summary rejected by scanner: ${summaryScan.reasons.join('; ')}`);
215
+ }
216
+ }
217
+ const updated = {
218
+ ...existing,
219
+ content: newContent,
220
+ updatedAt: Date.now(),
221
+ ...(input.category !== undefined ? { category: input.category } : {}),
222
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
223
+ };
224
+ this.transaction(() => {
225
+ this.insertEntry(updated);
226
+ this.appendAudit('update', id, updated, input.source, input.sessionId, newContent);
227
+ });
228
+ return asEntry(updated);
229
+ }
230
+ async remove(id) {
231
+ const existing = this.get(id);
232
+ if (existing === undefined)
233
+ return false;
234
+ this.transaction(() => {
235
+ this.db.prepare('DELETE FROM entries WHERE id = ?').run(id);
236
+ this.appendAudit('remove', id, existing, undefined, undefined, existing.content);
237
+ });
238
+ return true;
239
+ }
240
+ search(query) {
241
+ const limit = query.limit ?? 50;
242
+ const candidates = [];
243
+ for (const [, entry] of this.allEntries()) {
244
+ if (entry.status === 'superseded')
245
+ continue;
246
+ if (query.scope !== undefined && entry.scope !== query.scope)
247
+ continue;
248
+ if (query.category !== undefined && entry.category !== query.category)
249
+ continue;
250
+ if (query.projectName !== undefined && entry.projectName !== query.projectName)
251
+ continue;
252
+ candidates.push(entry);
253
+ }
254
+ const queryTokens = query.query !== undefined && query.query.length > 0 ? tokenizeForSearch(query.query) : [];
255
+ let ranked;
256
+ if (queryTokens.length > 0) {
257
+ // Same full-corpus df discipline as DomainMemoryStore.search (a per-pool
258
+ // df table would inflate function-word weights in small candidate pools).
259
+ const corpus = buildCorpusStatsFromTokens([...this.allEntries().values()].map(entry => entryIndexTokens(entry)));
260
+ const index = new Bm25Index(candidates.map(entry => entryIndexTokens(entry)), corpus);
261
+ const scores = index.scores(queryTokens);
262
+ ranked = [];
263
+ candidates.forEach((entry, i) => {
264
+ const score = scores[i] ?? 0;
265
+ if (score > 0)
266
+ ranked.push({ entry, score });
267
+ });
268
+ }
269
+ else {
270
+ ranked = candidates.map(entry => ({ entry, score: 0 }));
271
+ }
272
+ const pinOf = (entry) => entry.pinned === true ? 1 : 0;
273
+ const importanceOf = (entry) => entry.importance ?? 0;
274
+ ranked.sort((a, b) => b.score - a.score
275
+ || pinOf(b.entry) - pinOf(a.entry)
276
+ || importanceOf(b.entry) - importanceOf(a.entry)
277
+ || b.entry.updatedAt - a.entry.updatedAt);
278
+ let all = ranked.map(r => r.entry);
279
+ const total = all.length;
280
+ all = limit > 0 ? all.slice(0, limit) : all;
281
+ if (query.recordRecall !== false)
282
+ void this.stampRecalled(all.map(entry => entry.id));
283
+ return { entries: all, total };
284
+ }
285
+ async pin(id) {
286
+ return this.setPinned(id, true);
287
+ }
288
+ async unpin(id) {
289
+ return this.setPinned(id, false);
290
+ }
291
+ async setPinned(id, pinned) {
292
+ const existing = this.get(id);
293
+ if (existing === undefined)
294
+ return undefined;
295
+ const updated = { ...existing, pinned };
296
+ this.transaction(() => { this.insertEntry(updated); });
297
+ return asEntry(updated);
298
+ }
299
+ // ─── Recall / hit stamping (the RMW contract on the SQL row) ────────────────
300
+ /**
301
+ * Stamp entries with a recall timestamp (fire-and-forget): one UPDATE per
302
+ * changed entry, reading the row current at write time — a concurrent
303
+ * edit landing first is never rolled back by the stamp. `updatedAt` is
304
+ * intentionally left untouched.
305
+ */
306
+ async stampRecalled(ids) {
307
+ const now = Date.now();
308
+ for (const id of ids) {
309
+ try {
310
+ this.transaction(() => {
311
+ const current = this.get(id);
312
+ if (current === undefined)
313
+ return;
314
+ if (current.lastRecalledAt === now && current.staleSince === undefined)
315
+ return;
316
+ const { staleSince: _cleared, ...rest } = current;
317
+ this.insertEntry({ ...rest, lastRecalledAt: now, accessCount: (rest.accessCount ?? 0) + 1 });
318
+ });
319
+ }
320
+ catch (error) {
321
+ if (error instanceof Error && !error.message.includes('no record')) {
322
+ this.reportFailure('recall-stamp', error);
323
+ }
324
+ }
325
+ }
326
+ }
327
+ markRecalled(ids) {
328
+ if (ids.length === 0)
329
+ return;
330
+ void this.stampRecalled(ids.filter(id => this.get(id) !== undefined));
331
+ }
332
+ async markHits(ids) {
333
+ const now = Date.now();
334
+ for (const id of [...new Set(ids)]) {
335
+ try {
336
+ this.transaction(() => {
337
+ const current = this.get(id);
338
+ if (current === undefined)
339
+ return;
340
+ this.insertEntry({ ...current, hitCount: (current.hitCount ?? 0) + 1, lastHitAt: now });
341
+ this.appendAudit('update', id, this.get(id), 'review', undefined, current.content);
342
+ });
343
+ }
344
+ catch (error) {
345
+ if (error instanceof Error && !error.message.includes('no record')) {
346
+ this.reportFailure('mark-hits', error);
347
+ }
348
+ }
349
+ }
350
+ }
351
+ async supersedeEntry(id, supersededBy, annotate) {
352
+ const existing = this.get(id);
353
+ if (existing === undefined)
354
+ return undefined;
355
+ if (existing.status === 'superseded')
356
+ return existing;
357
+ const annotated = annotate === undefined ? existing.content : annotate(existing);
358
+ const updated = { ...existing, content: annotated, status: 'superseded', supersededBy };
359
+ this.transaction(() => {
360
+ this.insertEntry(updated);
361
+ this.appendAudit('update', id, updated, 'janitor', undefined, annotated);
362
+ });
363
+ return asEntry(updated);
364
+ }
365
+ // ─── Janitor (the two-tier lifecycle policy, same semantics) ────────────────
366
+ async janitor(decayDays, now = Date.now()) {
367
+ if (decayDays <= 0)
368
+ return 0;
369
+ const decayMs = decayDays * 24 * 60 * 60 * 1000;
370
+ let removed = 0;
371
+ for (const entry of this.list()) {
372
+ if (entry.pinned === true)
373
+ continue;
374
+ const lastActive = entry.lastRecalledAt ?? entry.createdAt;
375
+ if (now - lastActive < decayMs)
376
+ continue;
377
+ if (entry.scope === 'project') {
378
+ // Hard decay: the pin re-check reads the row current at write time.
379
+ const current = this.get(entry.id);
380
+ if (current === undefined || current.pinned === true)
381
+ continue;
382
+ this.transaction(() => {
383
+ this.db.prepare('DELETE FROM entries WHERE id = ?').run(entry.id);
384
+ this.appendAudit('remove', entry.id, current, 'janitor', undefined, current.content);
385
+ });
386
+ removed++;
387
+ continue;
388
+ }
389
+ // Soft decay only — stamp once, never auto-delete (importance grace, pin
390
+ // exemption, and decay idempotence all re-checked on the current row).
391
+ const current = this.get(entry.id);
392
+ if (current === undefined)
393
+ continue;
394
+ const lastActiveNow = current.lastRecalledAt ?? current.createdAt;
395
+ const graceFactor = current.importance !== undefined && current.importance >= 4 ? 1.5 : 1;
396
+ if (now - lastActiveNow < decayMs * graceFactor)
397
+ continue;
398
+ if (current.staleSince !== undefined)
399
+ continue;
400
+ this.transaction(() => {
401
+ this.insertEntry({ ...current, staleSince: now });
402
+ this.appendAudit('update', entry.id, { ...current, staleSince: now }, 'janitor', undefined, current.content);
403
+ });
404
+ }
405
+ return removed;
406
+ }
407
+ // ─── Suggestions (P1-1 queue shape) ─────────────────────────────────────────
408
+ async observeSuggestion(input) {
409
+ const scan = scanContent(input.content);
410
+ if (!scan.allowed) {
411
+ throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
412
+ }
413
+ const now = Date.now();
414
+ const existing = this.listSuggestions().find(suggestion => suggestion.scope === input.scope
415
+ && (input.targetEntryId !== undefined
416
+ ? suggestion.targetEntryId === input.targetEntryId
417
+ : jaccardish(suggestion.content, input.content) > 0.6));
418
+ if (existing !== undefined) {
419
+ const updated = {
420
+ ...existing,
421
+ hits: existing.hits + 1,
422
+ lastSeenAt: now,
423
+ ...(existing.category === undefined && input.category !== undefined ? { category: input.category } : {}),
424
+ ...(input.content.length > existing.content.length ? { content: input.content } : {}),
425
+ };
426
+ this.transaction(() => { this.insertSuggestion(updated); });
427
+ return asEntry(updated);
428
+ }
429
+ const row = {
430
+ id: crypto.randomUUID(),
431
+ scope: input.scope,
432
+ content: input.content,
433
+ hits: 1,
434
+ firstSeenAt: now,
435
+ lastSeenAt: now,
436
+ ...(input.category !== undefined ? { category: input.category } : {}),
437
+ ...(input.summary !== undefined ? { summary: input.summary } : {}),
438
+ ...(input.projectName !== undefined ? { projectName: input.projectName } : {}),
439
+ ...(input.targetEntryId !== undefined ? { targetEntryId: input.targetEntryId } : {}),
440
+ ...(input.source !== undefined ? { source: input.source } : {}),
441
+ ...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
442
+ };
443
+ this.transaction(() => {
444
+ this.insertSuggestion(row);
445
+ this.trimSuggestions();
446
+ });
447
+ return asEntry(row);
448
+ }
449
+ /** Trim the suggestion queue back to its cap (highest-hits exempt first). */
450
+ trimSuggestions() {
451
+ const count = this.db.prepare('SELECT COUNT(*) AS n FROM suggestions').get().n;
452
+ if (count <= this.suggestionCap)
453
+ return;
454
+ this.db.prepare(`DELETE FROM suggestions WHERE id IN (SELECT id FROM suggestions ORDER BY hits ASC, lastSeenAt ASC LIMIT ?)`)
455
+ .run(count - this.suggestionCap);
456
+ }
457
+ listSuggestions() {
458
+ const rows = this.db.prepare('SELECT * FROM suggestions ORDER BY hits DESC, lastSeenAt DESC').all();
459
+ return rows.map(row => asEntry(rowToRecord(row)));
460
+ }
461
+ getSuggestion(id) {
462
+ const row = this.db.prepare('SELECT * FROM suggestions WHERE id = ?').get(id);
463
+ return row === undefined ? undefined : asEntry(rowToRecord(row));
464
+ }
465
+ // ─── Health / audit / raw / meta ────────────────────────────────────────────
466
+ health() {
467
+ let global = 0, project = 0, user = 0, pinned = 0, stale = 0;
468
+ let lastActivity;
469
+ for (const entry of this.list()) {
470
+ if (entry.scope === 'global')
471
+ global++;
472
+ else if (entry.scope === 'project')
473
+ project++;
474
+ else
475
+ user++;
476
+ if (entry.pinned === true)
477
+ pinned++;
478
+ if (entry.staleSince !== undefined)
479
+ stale++;
480
+ lastActivity = Math.max(lastActivity ?? 0, entry.updatedAt);
481
+ }
482
+ const auditRecords = this.db.prepare('SELECT COUNT(*) AS n FROM audit').get().n;
483
+ return {
484
+ totalEntries: global + project + user,
485
+ byScope: { global, project, user },
486
+ pinned,
487
+ auditRecords,
488
+ ...(stale > 0 ? { stale } : {}),
489
+ ...(lastActivity !== undefined && auditRecords > 0 ? { lastActivityTs: lastActivity } : {}),
490
+ ...(this.failureCounts.size > 0 ? { backgroundFailures: Object.fromEntries(this.failureCounts) } : {}),
491
+ };
492
+ }
493
+ exportAuditLog() {
494
+ const rows = this.db.prepare('SELECT * FROM audit ORDER BY ts DESC').all();
495
+ return rows.map(row => rowToRecord(row));
496
+ }
497
+ async getRaw(id) {
498
+ const entry = this.get(id);
499
+ if (entry !== undefined) {
500
+ try {
501
+ this.appendAudit('readRaw', id, entry, 'ui', undefined, entry.content);
502
+ }
503
+ catch (error) {
504
+ // A failed raw-read audit never blocks the break-glass read.
505
+ this.reportFailure('audit-append', error);
506
+ }
507
+ }
508
+ return entry;
509
+ }
510
+ /** Read one meta record (synchronous; the meta table is tiny). */
511
+ getMeta(key) {
512
+ const row = this.db.prepare('SELECT * FROM meta WHERE key = ?').get(key);
513
+ if (row === undefined)
514
+ return undefined;
515
+ return { key: keyPrefix(key), ...(row.value !== null ? { value: row.value } : {}), ...(row.updatedAt !== null ? { updatedAt: row.updatedAt } : {}) };
516
+ }
517
+ /** Write one meta record (insert or replace; best-effort on failure). */
518
+ async setMeta(key, record) {
519
+ try {
520
+ this.db.prepare('INSERT INTO meta (key, value, updatedAt) VALUES (?, ?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value, updatedAt = excluded.updatedAt')
521
+ .run(key, record.value ?? null, record.updatedAt ?? Date.now());
522
+ }
523
+ catch (error) {
524
+ this.reportFailure('meta-write', error);
525
+ }
526
+ }
527
+ /**
528
+ * One-time bulk import from the host medium (Step 3.2's migration): every
529
+ * entry, audit record, and suggestion row lands verbatim in one
530
+ * transaction. Fidelity is row-for-row — ids, timestamps, and optional
531
+ * fields carry over; the caller owns the migration marker on the medium
532
+ * side.
533
+ */
534
+ importFromDomain(entries, audit, suggestions) {
535
+ this.transaction(() => {
536
+ for (const entry of entries)
537
+ this.insertEntry(entry);
538
+ for (const record of audit)
539
+ this.insertAudit(record);
540
+ for (const row of suggestions)
541
+ this.insertSuggestion(row);
542
+ });
543
+ this.auditSeq = this.maxAuditSeq();
544
+ }
545
+ // ─── Internals ──────────────────────────────────────────────────────────────
546
+ /** All entries keyed by id (the read snapshot; fresh per call). */
547
+ allEntries() {
548
+ const map = new Map();
549
+ for (const row of this.db.prepare('SELECT * FROM entries').all()) {
550
+ const record = rowToRecord(row);
551
+ map.set(record.id, asEntry(record));
552
+ }
553
+ return map;
554
+ }
555
+ /** Run `body` inside one transaction (entries + audit land atomically). */
556
+ transaction(body) {
557
+ this.db.exec('BEGIN');
558
+ try {
559
+ body();
560
+ this.db.exec('COMMIT');
561
+ }
562
+ catch (error) {
563
+ try {
564
+ this.db.exec('ROLLBACK');
565
+ }
566
+ catch { /* the transaction already ended; nothing to roll back */ }
567
+ throw error;
568
+ }
569
+ }
570
+ /** Insert or replace one entry row (the full-record put contract). */
571
+ insertEntry(entry) {
572
+ const columns = [...new Set([...ENTRY_COLUMNS.filter(column => entry[column] !== undefined), 'id', 'scope', 'content', 'createdAt', 'updatedAt'])];
573
+ const sql = `INSERT OR REPLACE INTO entries (${columns.map(c => `"${c}"`).join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;
574
+ bindRecord(this.db.prepare(sql), columns, entry);
575
+ }
576
+ /** Insert or replace one suggestion row. */
577
+ insertSuggestion(row) {
578
+ const columns = [...new Set([...SUGGESTION_COLUMNS.filter(column => row[column] !== undefined), 'id', 'scope', 'content', 'hits', 'firstSeenAt', 'lastSeenAt'])];
579
+ const sql = `INSERT OR REPLACE INTO suggestions (${columns.join(', ')}) VALUES (${columns.map(() => '?').join(', ')})`;
580
+ bindRecord(this.db.prepare(sql), columns, row);
581
+ }
582
+ /** Append one audit record (fire-and-forget semantics at the caller; best-effort here). */
583
+ appendAudit(op, entryId, entry, source, sessionId, content) {
584
+ const record = {
585
+ id: crypto.randomUUID(),
586
+ op,
587
+ entryId,
588
+ scope: entry.scope,
589
+ contentPreview: content.slice(0, 120),
590
+ ts: Date.now(),
591
+ seq: this.nextAuditSeq(),
592
+ ...(entry.category !== undefined ? { category: entry.category } : {}),
593
+ ...(source !== undefined ? { source } : {}),
594
+ ...(sessionId !== undefined ? { sessionId } : {}),
595
+ };
596
+ this.insertAudit(record);
597
+ // The audit trail caps: oldest records evict first.
598
+ const count = this.db.prepare('SELECT COUNT(*) AS n FROM audit').get().n;
599
+ if (count > this.auditCap) {
600
+ this.db.prepare(`DELETE FROM audit WHERE id IN (SELECT id FROM audit ORDER BY ts ASC LIMIT ?)`)
601
+ .run(count - this.auditCap);
602
+ }
603
+ }
604
+ /** Insert one audit record verbatim (the append's core; the import path reuses it). */
605
+ insertAudit(record) {
606
+ const sql = `INSERT OR REPLACE INTO audit (${AUDIT_COLUMNS.join(', ')}) VALUES (${AUDIT_COLUMNS.map(() => '?').join(', ')})`;
607
+ bindRecord(this.db.prepare(sql), AUDIT_COLUMNS, record);
608
+ // The audit trail caps: oldest records evict first.
609
+ const count = this.db.prepare('SELECT COUNT(*) AS n FROM audit').get().n;
610
+ if (count > this.auditCap) {
611
+ this.db.prepare(`DELETE FROM audit WHERE id IN (SELECT id FROM audit ORDER BY ts ASC LIMIT ?)`)
612
+ .run(count - this.auditCap);
613
+ }
614
+ }
615
+ /** Trim the entries table back to the cap (§ write-path governance). */
616
+ trimEntries(now) {
617
+ const count = this.db.prepare('SELECT COUNT(*) AS n FROM entries').get().n;
618
+ if (count <= this.entriesCap)
619
+ return;
620
+ const rows = this.db.prepare('SELECT * FROM entries').all();
621
+ const victims = rows
622
+ .map(row => rowToRecord(row))
623
+ .filter(entry => entry.pinned !== true)
624
+ .sort((a, b) => (a.accessCount ?? 0) - (b.accessCount ?? 0)
625
+ || (a.lastRecalledAt ?? a.createdAt) - (b.lastRecalledAt ?? b.createdAt))
626
+ .slice(0, count - this.entriesCap);
627
+ for (const victim of victims) {
628
+ this.db.prepare('DELETE FROM entries WHERE id = ?').run(victim.id);
629
+ this.appendAudit('remove', victim.id, victim, 'janitor', undefined, victim.content);
630
+ }
631
+ }
632
+ }
633
+ /** Quick content overlap for the suggestion dedup (same-shape rows). */
634
+ function jaccardish(a, b) {
635
+ const ta = new Set(tokenizeForSearch(a));
636
+ const tb = new Set(tokenizeForSearch(b));
637
+ if (ta.size === 0 && tb.size === 0)
638
+ return 1;
639
+ let shared = 0;
640
+ for (const token of ta)
641
+ if (tb.has(token))
642
+ shared++;
643
+ return shared / (ta.size + tb.size - shared);
644
+ }
645
+ /** The meta key's owning-subsystem prefix (before the first ':'). */
646
+ function keyPrefix(key) {
647
+ return key.slice(0, key.indexOf(':') > 0 ? key.indexOf(':') : undefined);
648
+ }
649
+ /** Merged content+summary token bag per entry (the search index's unit). */
650
+ function entryIndexTokens(entry) {
651
+ return [...tokenizeForSearch(`${entry.content}\n${entry.summary ?? ''}`)];
652
+ }
653
+ //# sourceMappingURL=sqlite.js.map