dsh-cross-memory 0.0.0-stage → 0.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.
Files changed (152) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -2
  3. package/cordis.patch.yml +27 -0
  4. package/docs/DETAIL.md +13 -0
  5. package/docs/DETAIL.zh.md +17 -0
  6. package/icon.svg +1 -0
  7. package/lib/backfill.js +273 -0
  8. package/lib/citations.js +305 -0
  9. package/lib/client.js +1550 -0
  10. package/lib/config.js +736 -0
  11. package/lib/consolidate.js +1119 -0
  12. package/lib/extract.js +570 -0
  13. package/lib/gate.js +137 -0
  14. package/lib/git-origin.js +224 -0
  15. package/lib/index.js +4475 -0
  16. package/lib/log.js +260 -0
  17. package/lib/loops.js +186 -0
  18. package/lib/notices.js +195 -0
  19. package/lib/notify.js +33 -0
  20. package/lib/persona.js +112 -0
  21. package/lib/query.js +93 -0
  22. package/lib/raw-recall.js +286 -0
  23. package/lib/reflection.js +291 -0
  24. package/lib/remote.js +455 -0
  25. package/lib/render.js +678 -0
  26. package/lib/retention.js +64 -0
  27. package/lib/schedule.js +245 -0
  28. package/lib/search.js +1068 -0
  29. package/lib/skills.js +220 -0
  30. package/lib/state.js +701 -0
  31. package/lib/storage.js +1424 -0
  32. package/lib/sync-runtime.js +268 -0
  33. package/lib/sync.js +620 -0
  34. package/lib/test/activity.test.js +74 -0
  35. package/lib/test/archive.test.js +182 -0
  36. package/lib/test/backfill.test.js +144 -0
  37. package/lib/test/citations.test.js +91 -0
  38. package/lib/test/client-wiring.test.js +134 -0
  39. package/lib/test/consolidate-job.test.js +95 -0
  40. package/lib/test/consolidate.test.js +430 -0
  41. package/lib/test/consolidation-selection.test.js +152 -0
  42. package/lib/test/dedupe-keys.test.js +230 -0
  43. package/lib/test/delta.test.js +93 -0
  44. package/lib/test/derived.test.js +110 -0
  45. package/lib/test/disputes-panel.test.js +314 -0
  46. package/lib/test/eval.test.js +171 -0
  47. package/lib/test/expand.test.js +164 -0
  48. package/lib/test/extract.test.js +1020 -0
  49. package/lib/test/git-origin.test.js +189 -0
  50. package/lib/test/injection.test.js +440 -0
  51. package/lib/test/kind-filter.test.js +49 -0
  52. package/lib/test/legacy-state.test.js +69 -0
  53. package/lib/test/log.test.js +156 -0
  54. package/lib/test/loops.test.js +86 -0
  55. package/lib/test/memory.test.js +855 -0
  56. package/lib/test/notices.test.js +140 -0
  57. package/lib/test/persona.test.js +73 -0
  58. package/lib/test/prefilter.test.js +73 -0
  59. package/lib/test/preset.test.js +77 -0
  60. package/lib/test/raw-recall.test.js +186 -0
  61. package/lib/test/recall.test.js +433 -0
  62. package/lib/test/reflection.test.js +64 -0
  63. package/lib/test/remote.test.js +227 -0
  64. package/lib/test/retention.test.js +117 -0
  65. package/lib/test/retrieval.test.js +142 -0
  66. package/lib/test/rotation.test.js +228 -0
  67. package/lib/test/schedule.test.js +112 -0
  68. package/lib/test/settings-card.test.js +58 -0
  69. package/lib/test/skills.test.js +129 -0
  70. package/lib/test/state.test.js +212 -0
  71. package/lib/test/subagent-contract.test.js +139 -0
  72. package/lib/test/sweep.test.js +159 -0
  73. package/lib/test/sync.test.js +314 -0
  74. package/lib/test/time.test.js +171 -0
  75. package/lib/time.js +303 -0
  76. package/lib/tool.js +330 -0
  77. package/lib/types/backfill.d.ts +96 -0
  78. package/lib/types/citations.d.ts +105 -0
  79. package/lib/types/config.d.ts +811 -0
  80. package/lib/types/consolidate.d.ts +742 -0
  81. package/lib/types/extract.d.ts +352 -0
  82. package/lib/types/gate.d.ts +83 -0
  83. package/lib/types/git-origin.d.ts +23 -0
  84. package/lib/types/index.d.ts +1316 -0
  85. package/lib/types/log.d.ts +144 -0
  86. package/lib/types/loops.d.ts +82 -0
  87. package/lib/types/notices.d.ts +117 -0
  88. package/lib/types/notify.d.ts +12 -0
  89. package/lib/types/persona.d.ts +43 -0
  90. package/lib/types/query.d.ts +45 -0
  91. package/lib/types/raw-recall.d.ts +84 -0
  92. package/lib/types/reflection.d.ts +122 -0
  93. package/lib/types/remote.d.ts +233 -0
  94. package/lib/types/render.d.ts +286 -0
  95. package/lib/types/retention.d.ts +66 -0
  96. package/lib/types/schedule.d.ts +116 -0
  97. package/lib/types/search.d.ts +583 -0
  98. package/lib/types/skills.d.ts +71 -0
  99. package/lib/types/state.d.ts +294 -0
  100. package/lib/types/storage.d.ts +458 -0
  101. package/lib/types/sync-runtime.d.ts +103 -0
  102. package/lib/types/sync.d.ts +222 -0
  103. package/lib/types/test/activity.test.d.ts +1 -0
  104. package/lib/types/test/archive.test.d.ts +1 -0
  105. package/lib/types/test/backfill.test.d.ts +1 -0
  106. package/lib/types/test/citations.test.d.ts +1 -0
  107. package/lib/types/test/client-wiring.test.d.ts +1 -0
  108. package/lib/types/test/consolidate-job.test.d.ts +1 -0
  109. package/lib/types/test/consolidate.test.d.ts +1 -0
  110. package/lib/types/test/consolidation-selection.test.d.ts +1 -0
  111. package/lib/types/test/dedupe-keys.test.d.ts +1 -0
  112. package/lib/types/test/delta.test.d.ts +1 -0
  113. package/lib/types/test/derived.test.d.ts +1 -0
  114. package/lib/types/test/disputes-panel.test.d.ts +1 -0
  115. package/lib/types/test/eval.test.d.ts +1 -0
  116. package/lib/types/test/expand.test.d.ts +1 -0
  117. package/lib/types/test/extract.test.d.ts +1 -0
  118. package/lib/types/test/git-origin.test.d.ts +1 -0
  119. package/lib/types/test/injection.test.d.ts +1 -0
  120. package/lib/types/test/kind-filter.test.d.ts +1 -0
  121. package/lib/types/test/legacy-state.test.d.ts +1 -0
  122. package/lib/types/test/log.test.d.ts +1 -0
  123. package/lib/types/test/loops.test.d.ts +1 -0
  124. package/lib/types/test/memory.test.d.ts +1 -0
  125. package/lib/types/test/notices.test.d.ts +1 -0
  126. package/lib/types/test/persona.test.d.ts +1 -0
  127. package/lib/types/test/prefilter.test.d.ts +1 -0
  128. package/lib/types/test/preset.test.d.ts +1 -0
  129. package/lib/types/test/raw-recall.test.d.ts +1 -0
  130. package/lib/types/test/recall.test.d.ts +1 -0
  131. package/lib/types/test/reflection.test.d.ts +1 -0
  132. package/lib/types/test/remote.test.d.ts +1 -0
  133. package/lib/types/test/retention.test.d.ts +1 -0
  134. package/lib/types/test/retrieval.test.d.ts +1 -0
  135. package/lib/types/test/rotation.test.d.ts +1 -0
  136. package/lib/types/test/schedule.test.d.ts +1 -0
  137. package/lib/types/test/settings-card.test.d.ts +1 -0
  138. package/lib/types/test/skills.test.d.ts +1 -0
  139. package/lib/types/test/state.test.d.ts +1 -0
  140. package/lib/types/test/subagent-contract.test.d.ts +1 -0
  141. package/lib/types/test/sweep.test.d.ts +1 -0
  142. package/lib/types/test/sync.test.d.ts +1 -0
  143. package/lib/types/test/time.test.d.ts +1 -0
  144. package/lib/types/time.d.ts +67 -0
  145. package/lib/types/tool.d.ts +9 -0
  146. package/lib/types/types.d.ts +374 -0
  147. package/lib/types/workspace.d.ts +20 -0
  148. package/lib/types.js +47 -0
  149. package/lib/workspace.js +65 -0
  150. package/locale/en.json +7 -0
  151. package/locale/zh.json +7 -0
  152. package/package.json +126 -4
package/lib/state.js ADDED
@@ -0,0 +1,701 @@
1
+ /**
2
+ * Operational state: extraction watermarks, job leases, and usage counters.
3
+ *
4
+ * These are NOT the memories. Entries stay human-readable markdown files (see
5
+ * `storage.ts`), because those are the thing a person greps, edits, and commits.
6
+ * State is the opposite: it is small, hot, and written concurrently by every
7
+ * session in the process, which is exactly what a JSON read-modify-write file
8
+ * gets wrong — two sessions mining at once would each write back a whole
9
+ * document and silently drop the other's watermark.
10
+ *
11
+ * So state lives in SQLite, through Node's built-in `node:sqlite` (no
12
+ * dependency). The module is loaded lazily and every failure degrades to an
13
+ * in-memory map: a deployment on an older Node, or one where the driver is
14
+ * unavailable, keeps working — it just loses cross-restart watermarks instead
15
+ * of refusing to boot.
16
+ *
17
+ * @module dsh-cross-memory/state
18
+ */
19
+ import { mkdirSync } from 'node:fs';
20
+ import { readFile, rm } from 'node:fs/promises';
21
+ import { createRequire } from 'node:module';
22
+ import { dirname, join } from 'node:path';
23
+ /**
24
+ * Module-level require, used only for the optional `node:sqlite` import.
25
+ * `createRequire` keeps the load lazy and lets an unavailable driver be caught
26
+ * instead of failing the whole plugin at import time.
27
+ */
28
+ const requireOptional = createRequire(import.meta.url);
29
+ /** Whether a filesystem error means "absent". */
30
+ function isMissing(error) {
31
+ return typeof error === 'object' && error !== null && 'code' in error
32
+ && (error.code === 'ENOENT' || error.code === 'ENOTDIR');
33
+ }
34
+ /** The single background-pass pause a store records today. */
35
+ export const BACKGROUND_LIMIT = 'background';
36
+ /**
37
+ * Durable state store.
38
+ *
39
+ * Every method is synchronous and internally consistent: SQLite serializes the
40
+ * writes, and the fallback map is single-process. Callers do not need locking.
41
+ */
42
+ export class StateStore {
43
+ path;
44
+ db;
45
+ /** Fallback when `node:sqlite` is unavailable: watermarks survive only in-process. */
46
+ sessions = new Map();
47
+ jobs = new Map();
48
+ usage = new Map();
49
+ /** Bookkeeping scalars: when the last sweep ran, and anything else a pass must remember. */
50
+ meta = new Map();
51
+ /** Per-session memory switches, when the SQL driver is unavailable. */
52
+ sessionModes = new Map();
53
+ /** Last injection per conversation, when the SQL driver is unavailable. */
54
+ injections = new Map();
55
+ limits = new Map();
56
+ /** Why the SQL driver is absent, for one diagnostic line. */
57
+ degradedReason;
58
+ constructor(path) {
59
+ this.path = path;
60
+ let driver;
61
+ try {
62
+ // Required lazily so a deployment on an older Node never pays for (or
63
+ // fails on) the import.
64
+ const { DatabaseSync } = requireOptional('node:sqlite');
65
+ mkdirSync(dirname(path), { recursive: true });
66
+ this.db = new DatabaseSync(path);
67
+ this.db.exec(`
68
+ PRAGMA journal_mode = WAL;
69
+ PRAGMA synchronous = NORMAL;
70
+ -- The default autocheckpoint is 1000 pages (4 MB at the default page
71
+ -- size), which for this store means the write-ahead log is allowed to
72
+ -- grow to thirty times the size of the database: measured on a real
73
+ -- store, 143 KB of tables beside a 4.12 MB WAL sitting exactly at the
74
+ -- threshold. Checkpointing every 64 pages keeps the WAL proportional to
75
+ -- what actually changed, and this database sees a few writes per pass.
76
+ PRAGMA wal_autocheckpoint = 64;
77
+ CREATE TABLE IF NOT EXISTS sessions (
78
+ id TEXT PRIMARY KEY,
79
+ last_seq INTEGER NOT NULL DEFAULT 0,
80
+ at INTEGER NOT NULL DEFAULT 0,
81
+ root TEXT,
82
+ contributed INTEGER NOT NULL DEFAULT 0,
83
+ activity_at INTEGER NOT NULL DEFAULT 0,
84
+ memory_mode TEXT
85
+ );
86
+ CREATE TABLE IF NOT EXISTS jobs (
87
+ key TEXT PRIMARY KEY,
88
+ enqueued_at INTEGER NOT NULL,
89
+ root TEXT,
90
+ not_before INTEGER NOT NULL DEFAULT 0,
91
+ lease TEXT,
92
+ lease_until INTEGER NOT NULL DEFAULT 0,
93
+ retries INTEGER NOT NULL DEFAULT 0,
94
+ last_error TEXT
95
+ );
96
+ CREATE TABLE IF NOT EXISTS usage (
97
+ scope TEXT NOT NULL,
98
+ id TEXT NOT NULL,
99
+ uses INTEGER NOT NULL DEFAULT 0,
100
+ last_used_at INTEGER NOT NULL DEFAULT 0,
101
+ surfaced_at INTEGER NOT NULL DEFAULT 0,
102
+ consolidated_at INTEGER NOT NULL DEFAULT 0,
103
+ PRIMARY KEY (scope, id)
104
+ );
105
+ CREATE TABLE IF NOT EXISTS limits (
106
+ id TEXT PRIMARY KEY,
107
+ failures INTEGER NOT NULL DEFAULT 0,
108
+ until INTEGER NOT NULL DEFAULT 0,
109
+ at INTEGER NOT NULL DEFAULT 0,
110
+ reason TEXT
111
+ );
112
+ CREATE TABLE IF NOT EXISTS meta (
113
+ key TEXT PRIMARY KEY,
114
+ value TEXT NOT NULL
115
+ );
116
+ -- What each conversation was already shown, so a later delta injection
117
+ -- can name only what is new. Durable because the conversation (and the
118
+ -- block it carries) survives a restart: an in-memory marker would
119
+ -- re-inject the whole delta on the first step after every restart.
120
+ CREATE TABLE IF NOT EXISTS injections (
121
+ session TEXT PRIMARY KEY,
122
+ at INTEGER NOT NULL,
123
+ ids TEXT NOT NULL
124
+ );
125
+ `);
126
+ this.migrate();
127
+ }
128
+ catch (error) {
129
+ driver = error instanceof Error ? error.message : String(error);
130
+ this.db = undefined;
131
+ }
132
+ this.degradedReason = driver;
133
+ }
134
+ /**
135
+ * Add columns a newer version introduced.
136
+ *
137
+ * `CREATE TABLE IF NOT EXISTS` is a no-op on an existing table, so a column
138
+ * added to the schema above would silently never appear on an upgraded store
139
+ * and every query naming it would fail. Each column is checked and added
140
+ * individually, which is safe to run on every open.
141
+ */
142
+ migrate() {
143
+ const db = this.db;
144
+ if (db === undefined)
145
+ return;
146
+ const columns = (table) => {
147
+ const rows = db.prepare(`PRAGMA table_info(${table})`).all();
148
+ return new Set(rows.map((row) => row.name));
149
+ };
150
+ // jobs.root: which workspace a consolidation pass covers (added after v1).
151
+ if (!columns('jobs').has('root'))
152
+ db.exec('ALTER TABLE jobs ADD COLUMN root TEXT');
153
+ // usage.surfaced_at / usage.consolidated_at: retention and review bookkeeping.
154
+ if (!columns('usage').has('surfaced_at'))
155
+ db.exec('ALTER TABLE usage ADD COLUMN surfaced_at INTEGER NOT NULL DEFAULT 0');
156
+ if (!columns('usage').has('consolidated_at'))
157
+ db.exec('ALTER TABLE usage ADD COLUMN consolidated_at INTEGER NOT NULL DEFAULT 0');
158
+ // sessions.memory_mode: per-session memory switch (`off` suspends it).
159
+ if (!columns('sessions').has('memory_mode'))
160
+ db.exec('ALTER TABLE sessions ADD COLUMN memory_mode TEXT');
161
+ }
162
+ /** Whether SQLite is backing this store. */
163
+ get durable() {
164
+ return this.db !== undefined;
165
+ }
166
+ /**
167
+ * The write-ahead-log checkpoint threshold in pages, as this connection sees it.
168
+ *
169
+ * Exposed because the value is per-connection and therefore invisible to any
170
+ * other handle: a fresh connection reports the compiled-in default and would
171
+ * happily "confirm" a policy this store does not use.
172
+ */
173
+ get walAutocheckpoint() {
174
+ const db = this.db;
175
+ if (db === undefined)
176
+ return 0;
177
+ try {
178
+ const row = db.prepare('PRAGMA wal_autocheckpoint').get();
179
+ return Number(row?.wal_autocheckpoint ?? 0);
180
+ }
181
+ catch {
182
+ return 0;
183
+ }
184
+ }
185
+ /** Close the database handle; safe to call twice. */
186
+ close() {
187
+ try {
188
+ this.db?.close();
189
+ }
190
+ catch {
191
+ // Closing a store that is already gone is not a caller error.
192
+ }
193
+ this.db = undefined;
194
+ }
195
+ /** Read one session's watermark. */
196
+ getSession(id) {
197
+ if (this.db === undefined)
198
+ return this.sessions.get(id);
199
+ const row = this.db.prepare('SELECT last_seq, at, root, contributed, activity_at FROM sessions WHERE id = ?').get(id);
200
+ if (row === undefined)
201
+ return undefined;
202
+ return {
203
+ lastSeq: Number(row.last_seq),
204
+ at: Number(row.at),
205
+ ...row.root === null ? {} : { root: row.root },
206
+ contributed: row.contributed === 1,
207
+ activityAt: Number(row.activity_at),
208
+ };
209
+ }
210
+ /** Write one session's watermark. */
211
+ putSession(id, state) {
212
+ if (this.db === undefined) {
213
+ this.sessions.set(id, state);
214
+ return;
215
+ }
216
+ this.db.prepare(`
217
+ INSERT INTO sessions (id, last_seq, at, root, contributed, activity_at)
218
+ VALUES (?, ?, ?, ?, ?, ?)
219
+ ON CONFLICT(id) DO UPDATE SET
220
+ last_seq = excluded.last_seq, at = excluded.at, root = excluded.root,
221
+ contributed = excluded.contributed, activity_at = excluded.activity_at
222
+ `).run(id, state.lastSeq, state.at, state.root ?? null, state.contributed === true ? 1 : 0, state.activityAt ?? 0);
223
+ }
224
+ /** Record activity for a session without touching its watermark. */
225
+ touchSession(id, at = Date.now()) {
226
+ if (this.db === undefined) {
227
+ const existing = this.sessions.get(id);
228
+ this.sessions.set(id, existing === undefined
229
+ ? { lastSeq: 0, at: 0, activityAt: at }
230
+ : { ...existing, activityAt: at });
231
+ return;
232
+ }
233
+ this.db.prepare(`
234
+ INSERT INTO sessions (id, last_seq, at, activity_at) VALUES (?, 0, 0, ?)
235
+ ON CONFLICT(id) DO UPDATE SET activity_at = excluded.activity_at
236
+ `).run(id, at);
237
+ }
238
+ /** Every session that has a watermark, newest activity first. */
239
+ listSessions() {
240
+ if (this.db === undefined)
241
+ return [...this.sessions.entries()].map(([id, state]) => ({ id, state }));
242
+ const rows = this.db.prepare('SELECT id, last_seq, at, root, contributed, activity_at FROM sessions ORDER BY activity_at DESC').all();
243
+ return rows.map((row) => ({
244
+ id: row.id,
245
+ state: {
246
+ lastSeq: Number(row.last_seq),
247
+ at: Number(row.at),
248
+ ...row.root === null ? {} : { root: row.root },
249
+ contributed: row.contributed === 1,
250
+ activityAt: Number(row.activity_at),
251
+ },
252
+ }));
253
+ }
254
+ /**
255
+ * What one conversation was already shown, and when.
256
+ *
257
+ * The ids are the entries the model has already seen in this conversation;
258
+ * `at` is the moment of the last injection. A delta pass compares entry
259
+ * `updated` stamps against `at`, so both are needed.
260
+ *
261
+ * @param id - session id.
262
+ * @returns the record, or `undefined` when the conversation was never injected.
263
+ */
264
+ getInjection(id) {
265
+ if (this.db === undefined)
266
+ return this.injections.get(id);
267
+ const row = this.db.prepare('SELECT at, ids FROM injections WHERE session = ?').get(id);
268
+ if (row === undefined)
269
+ return undefined;
270
+ try {
271
+ const parsed = JSON.parse(row.ids);
272
+ return {
273
+ at: Number(row.at),
274
+ ids: Array.isArray(parsed) ? parsed.filter((value) => typeof value === 'string') : [],
275
+ };
276
+ }
277
+ catch {
278
+ // A corrupt id list is not a reason to re-inject everything: keep the
279
+ // timestamp and treat the conversation as having been shown nothing.
280
+ return { at: Number(row.at), ids: [] };
281
+ }
282
+ }
283
+ /** Record that a conversation was shown these entries at `at`. */
284
+ putInjection(id, record) {
285
+ if (this.db === undefined) {
286
+ this.injections.set(id, { at: record.at, ids: [...record.ids] });
287
+ return;
288
+ }
289
+ this.db.prepare(`
290
+ INSERT INTO injections (session, at, ids) VALUES (?, ?, ?)
291
+ ON CONFLICT(session) DO UPDATE SET at = excluded.at, ids = excluded.ids
292
+ `).run(id, Math.trunc(record.at), JSON.stringify(record.ids));
293
+ }
294
+ /**
295
+ * Number of sessions this store knows about.
296
+ *
297
+ * Every row counts, including ones that only ever recorded activity or a
298
+ * memory switch, so this answers "has this store seen the session" — which is
299
+ * what the legacy-import guard needs. {@link minedCount} answers "was it
300
+ * mined", which is what a diagnostic wants.
301
+ */
302
+ sessionCount() {
303
+ if (this.db === undefined)
304
+ return this.sessions.size;
305
+ const row = this.db.prepare('SELECT COUNT(*) AS n FROM sessions').get();
306
+ return Number(row.n);
307
+ }
308
+ /**
309
+ * Number of sessions that were actually mined.
310
+ *
311
+ * The distinction is not cosmetic: a store can accumulate dozens of activity
312
+ * rows while extraction has never once completed, and a single "sessions"
313
+ * number reports that as a busy, healthy plugin.
314
+ */
315
+ minedCount() {
316
+ if (this.db === undefined) {
317
+ return [...this.sessions.values()].filter((state) => state.lastSeq > 0 || state.contributed === true).length;
318
+ }
319
+ const row = this.db.prepare('SELECT COUNT(*) AS n FROM sessions WHERE last_seq > 0 OR contributed = 1').get();
320
+ return Number(row.n);
321
+ }
322
+ /** Read one job. */
323
+ getJob(key) {
324
+ if (this.db === undefined)
325
+ return this.jobs.get(key);
326
+ const row = this.db.prepare('SELECT key, enqueued_at, not_before, root, lease, lease_until, retries, last_error FROM jobs WHERE key = ?').get(key);
327
+ if (row === undefined)
328
+ return undefined;
329
+ return {
330
+ key: row.key,
331
+ enqueuedAt: Number(row.enqueued_at),
332
+ notBefore: Number(row.not_before),
333
+ ...row.root === null ? {} : { root: row.root },
334
+ ...row.lease === null ? {} : { lease: row.lease },
335
+ leaseUntil: Number(row.lease_until),
336
+ retries: Number(row.retries),
337
+ ...row.last_error === null ? {} : { lastError: row.last_error },
338
+ };
339
+ }
340
+ /** Insert or replace one job. */
341
+ putJob(job) {
342
+ if (this.db === undefined) {
343
+ this.jobs.set(job.key, job);
344
+ return;
345
+ }
346
+ this.db.prepare(`
347
+ INSERT INTO jobs (key, enqueued_at, not_before, root, lease, lease_until, retries, last_error)
348
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
349
+ ON CONFLICT(key) DO UPDATE SET
350
+ enqueued_at = excluded.enqueued_at, not_before = excluded.not_before, root = excluded.root, lease = excluded.lease,
351
+ lease_until = excluded.lease_until, retries = excluded.retries, last_error = excluded.last_error
352
+ `).run(job.key, job.enqueuedAt, job.notBefore, job.root ?? null, job.lease ?? null, job.leaseUntil ?? 0, job.retries, job.lastError ?? null);
353
+ }
354
+ /** Delete one job. */
355
+ deleteJob(key) {
356
+ if (this.db === undefined) {
357
+ this.jobs.delete(key);
358
+ return;
359
+ }
360
+ this.db.prepare('DELETE FROM jobs WHERE key = ?').run(key);
361
+ }
362
+ /**
363
+ * Claim one job for `leaseMs`, or return `undefined` when another holder owns
364
+ * a live lease or the job's backoff has not elapsed. The current holder may
365
+ * renew its own lease.
366
+ * @param key - job key.
367
+ * @param token - this worker's opaque lease token.
368
+ * @param leaseMs - how long the lease is valid.
369
+ * @param now - injected clock.
370
+ * @returns the claimed job, or `undefined` when it is not available.
371
+ */
372
+ claimJob(key, token, leaseMs, now = Date.now()) {
373
+ const job = this.getJob(key);
374
+ if (job === undefined)
375
+ return undefined;
376
+ if (job.notBefore > now)
377
+ return undefined;
378
+ // `notBefore` is the BACKOFF, and it exists to stop a broken pass spinning.
379
+ // A person typing the command is not a broken pass: `consolidateNow` clears
380
+ // the backoff before claiming when it was forced, so a stale row from an era
381
+ // when the pass always failed cannot block a command the user asked for.
382
+ const heldByOther = job.lease !== undefined && job.lease !== token && (job.leaseUntil ?? 0) > now;
383
+ if (heldByOther)
384
+ return undefined;
385
+ const claimed = { ...job, lease: token, leaseUntil: now + leaseMs };
386
+ this.putJob(claimed);
387
+ return claimed;
388
+ }
389
+ /**
390
+ * Drop one job's backoff and last failure, leaving the job queued.
391
+ *
392
+ * Called when a person forces a pass. Without it a manual `/memories
393
+ * consolidate` returned "nothing to consolidate" for hours after a failure had
394
+ * already been fixed — the command was refused by a backoff meant for the
395
+ * background retry, and the message named three causes none of which was the
396
+ * real one.
397
+ *
398
+ * @param key - job key.
399
+ */
400
+ clearJobBackoff(key) {
401
+ const job = this.getJob(key);
402
+ if (job === undefined)
403
+ return;
404
+ const { lastError: _lastError, lease: _lease, leaseUntil: _leaseUntil, ...rest } = job;
405
+ this.putJob({ ...rest, notBefore: 0, retries: 0 });
406
+ }
407
+ /** Record one usage hit for a memory entry. */
408
+ bumpUsage(scope, id, now = Date.now()) {
409
+ if (this.db === undefined) {
410
+ const key = `${scope}\u0000${id}`;
411
+ const previous = this.usage.get(key);
412
+ this.usage.set(key, {
413
+ uses: (previous?.uses ?? 0) + 1,
414
+ lastUsedAt: now,
415
+ surfacedAt: previous?.surfacedAt ?? 0,
416
+ consolidatedAt: previous?.consolidatedAt ?? 0,
417
+ });
418
+ return { uses: (previous?.uses ?? 0) + 1, lastUsedAt: now };
419
+ }
420
+ this.db.prepare(`
421
+ INSERT INTO usage (scope, id, uses, last_used_at) VALUES (?, ?, 1, ?)
422
+ ON CONFLICT(scope, id) DO UPDATE SET uses = uses + 1, last_used_at = excluded.last_used_at
423
+ `).run(scope, id, now);
424
+ const row = this.db.prepare('SELECT uses, last_used_at FROM usage WHERE scope = ? AND id = ?').get(scope, id);
425
+ return { uses: Number(row.uses), lastUsedAt: Number(row.last_used_at) };
426
+ }
427
+ /** Read one entry's usage counters. */
428
+ getUsage(scope, id) {
429
+ if (this.db === undefined) {
430
+ const row = this.usage.get(`${scope}\u0000${id}`);
431
+ return row === undefined ? { uses: 0, lastUsedAt: 0 } : { uses: row.uses, lastUsedAt: row.lastUsedAt };
432
+ }
433
+ const row = this.db.prepare('SELECT uses, last_used_at FROM usage WHERE scope = ? AND id = ?').get(scope, id);
434
+ return row === undefined ? { uses: 0, lastUsedAt: 0 } : { uses: Number(row.uses), lastUsedAt: Number(row.last_used_at) };
435
+ }
436
+ /**
437
+ * Every usage row, for the summary ranking pass.
438
+ *
439
+ * `surfacedAt` is the authoritative "was this ever listed in an injected
440
+ * block" clock. The entry file mirrors it for human readers, but the mirror
441
+ * can be stale (it is refreshed at most hourly, and entries written before
442
+ * this table existed never got a row): selection decisions read THIS.
443
+ */
444
+ listUsage() {
445
+ if (this.db === undefined) {
446
+ return [...this.usage.entries()].map(([key, value]) => {
447
+ const [scope, id] = key.split('\u0000');
448
+ return { scope: scope ?? '', id: id ?? '', uses: value.uses, lastUsedAt: value.lastUsedAt, surfacedAt: value.surfacedAt };
449
+ });
450
+ }
451
+ const rows = this.db.prepare('SELECT scope, id, uses, last_used_at, surfaced_at FROM usage').all();
452
+ return rows.map((row) => ({
453
+ scope: row.scope,
454
+ id: row.id,
455
+ uses: Number(row.uses),
456
+ lastUsedAt: Number(row.last_used_at),
457
+ surfacedAt: Number(row.surfaced_at),
458
+ }));
459
+ }
460
+ /**
461
+ * Record that an entry was listed in an injected block.
462
+ *
463
+ * Surfacing is a weaker signal than a read — the model saw the memory but did
464
+ * not open it — so it deliberately does not inflate `uses`. It exists because
465
+ * retention would otherwise evict the memories that work too well to need a
466
+ * search: an entry the model read straight out of the summary would look
467
+ * unused, and the better it is, the faster it would expire.
468
+ *
469
+ * @param scope - the entry's scope.
470
+ * @param id - the entry's id.
471
+ * @param now - injected clock.
472
+ * @returns the recorded timestamp.
473
+ */
474
+ bumpSurfaced(scope, id, now = Date.now()) {
475
+ if (this.db === undefined) {
476
+ const key = `${scope}\u0000${id}`;
477
+ const previous = this.usage.get(key);
478
+ this.usage.set(key, {
479
+ uses: previous?.uses ?? 0,
480
+ lastUsedAt: previous?.lastUsedAt ?? 0,
481
+ surfacedAt: now,
482
+ consolidatedAt: previous?.consolidatedAt ?? 0,
483
+ });
484
+ return now;
485
+ }
486
+ this.db.prepare(`
487
+ INSERT INTO usage (scope, id, uses, last_used_at, surfaced_at) VALUES (?, ?, 0, 0, ?)
488
+ ON CONFLICT(scope, id) DO UPDATE SET surfaced_at = excluded.surfaced_at
489
+ `).run(scope, id, now);
490
+ return now;
491
+ }
492
+ /**
493
+ * Record that a consolidation pass reviewed these entries.
494
+ *
495
+ * The mark is what stops a review from starving: selection prefers entries it
496
+ * has never reviewed, then the ones reviewed longest ago, so a memory cannot
497
+ * sit unseen forever behind a permanently-newest first page.
498
+ *
499
+ * @param refs - the scope/id pairs the pass considered.
500
+ * @param now - clock to record.
501
+ */
502
+ markConsolidated(refs, now = Date.now()) {
503
+ for (const ref of refs) {
504
+ if (this.db === undefined) {
505
+ const key = `${ref.scope}\u0000${ref.id}`;
506
+ const previous = this.usage.get(key);
507
+ this.usage.set(key, {
508
+ uses: previous?.uses ?? 0,
509
+ lastUsedAt: previous?.lastUsedAt ?? 0,
510
+ surfacedAt: previous?.surfacedAt ?? 0,
511
+ consolidatedAt: now,
512
+ });
513
+ continue;
514
+ }
515
+ this.db.prepare(`
516
+ INSERT INTO usage (scope, id, uses, last_used_at, consolidated_at) VALUES (?, ?, 0, 0, ?)
517
+ ON CONFLICT(scope, id) DO UPDATE SET consolidated_at = excluded.consolidated_at
518
+ `).run(ref.scope, ref.id, now);
519
+ }
520
+ }
521
+ /** Every usage row with all four timestamps, for the retention pass. */
522
+ retentionRows() {
523
+ if (this.db === undefined) {
524
+ return [...this.usage.entries()].map(([key, value]) => {
525
+ const [scope, id] = key.split('\u0000');
526
+ return { scope: scope ?? '', id: id ?? '', ...value };
527
+ });
528
+ }
529
+ const rows = this.db.prepare('SELECT scope, id, uses, last_used_at, surfaced_at, consolidated_at FROM usage').all();
530
+ return rows.map((row) => ({
531
+ scope: row.scope,
532
+ id: row.id,
533
+ uses: Number(row.uses),
534
+ lastUsedAt: Number(row.last_used_at),
535
+ surfacedAt: Number(row.surfaced_at),
536
+ consolidatedAt: Number(row.consolidated_at),
537
+ }));
538
+ }
539
+ /** Read one bookkeeping value, if it was ever written. */
540
+ getMeta(key) {
541
+ if (this.db === undefined)
542
+ return this.meta.get(key);
543
+ const row = this.db.prepare('SELECT value FROM meta WHERE key = ?').get(key);
544
+ return row?.value;
545
+ }
546
+ /** Write one bookkeeping value. */
547
+ putMeta(key, value) {
548
+ if (this.db === undefined) {
549
+ this.meta.set(key, value);
550
+ return;
551
+ }
552
+ this.db.prepare(`
553
+ INSERT INTO meta (key, value) VALUES (?, ?)
554
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
555
+ `).run(key, value);
556
+ }
557
+ /** One session's memory switch; `on` unless it was turned off. */
558
+ getSessionMode(id) {
559
+ if (this.db === undefined)
560
+ return this.sessionModes.get(id) ?? 'on';
561
+ const row = this.db.prepare('SELECT memory_mode FROM sessions WHERE id = ?').get(id);
562
+ return row?.memory_mode === 'off' ? 'off' : 'on';
563
+ }
564
+ /** Turn one session's memory off, or back on. */
565
+ setSessionMode(id, mode, at = Date.now()) {
566
+ if (this.db === undefined) {
567
+ if (!this.sessions.has(id))
568
+ this.sessions.set(id, { lastSeq: 0, at: 0, activityAt: at });
569
+ this.sessionModes.set(id, mode);
570
+ return;
571
+ }
572
+ this.db.prepare(`
573
+ INSERT INTO sessions (id, last_seq, at, memory_mode) VALUES (?, 0, 0, ?)
574
+ ON CONFLICT(id) DO UPDATE SET memory_mode = excluded.memory_mode
575
+ `).run(id, mode);
576
+ }
577
+ /** The recorded background pause, if any. */
578
+ getLimit(id = BACKGROUND_LIMIT) {
579
+ if (this.db === undefined)
580
+ return this.limits.get(id);
581
+ const row = this.db.prepare('SELECT id, failures, until, at, reason FROM limits WHERE id = ?').get(id);
582
+ if (row === undefined)
583
+ return undefined;
584
+ return {
585
+ failures: Number(row.failures),
586
+ until: Number(row.until),
587
+ at: Number(row.at),
588
+ ...row.reason === null ? {} : { reason: row.reason },
589
+ };
590
+ }
591
+ /**
592
+ * Whether background passes are paused right now.
593
+ * @param now - injected clock.
594
+ * @param id - which pause to read.
595
+ * @returns true while the recorded wait has not elapsed.
596
+ */
597
+ isLimited(now = Date.now(), id = BACKGROUND_LIMIT) {
598
+ const limit = this.getLimit(id);
599
+ return limit !== undefined && limit.until > now;
600
+ }
601
+ /**
602
+ * Record one provider refusal and extend the wait.
603
+ *
604
+ * The wait doubles per consecutive refusal, capped, so a provider that keeps
605
+ * refusing costs one failed call per interval instead of one per idle timer.
606
+ *
607
+ * @param reason - provider wording, for diagnostics.
608
+ * @param baseMs - wait after the first refusal.
609
+ * @param maxMs - ceiling for the doubling.
610
+ * @param now - injected clock.
611
+ * @param id - which pause to write.
612
+ * @returns the state after this refusal.
613
+ */
614
+ noteLimitFailure(reason, baseMs, maxMs, now = Date.now(), id = BACKGROUND_LIMIT) {
615
+ const previous = this.getLimit(id);
616
+ const failures = (previous?.failures ?? 0) + 1;
617
+ const wait = Math.min(maxMs, baseMs * 2 ** (failures - 1));
618
+ const state = { failures, until: now + wait, at: now, reason };
619
+ if (this.db === undefined) {
620
+ this.limits.set(id, state);
621
+ return state;
622
+ }
623
+ this.db.prepare(`
624
+ INSERT INTO limits (id, failures, until, at, reason) VALUES (?, ?, ?, ?, ?)
625
+ ON CONFLICT(id) DO UPDATE SET
626
+ failures = excluded.failures, until = excluded.until, at = excluded.at, reason = excluded.reason
627
+ `).run(id, state.failures, state.until, state.at, state.reason ?? null);
628
+ return state;
629
+ }
630
+ /** Forget the pause after a pass succeeds. */
631
+ clearLimit(id = BACKGROUND_LIMIT) {
632
+ if (this.db === undefined) {
633
+ this.limits.delete(id);
634
+ return;
635
+ }
636
+ this.db.prepare('DELETE FROM limits WHERE id = ?').run(id);
637
+ }
638
+ }
639
+ /**
640
+ * Resolve the state database path inside one memory store. */
641
+ export function statePath(memoriesDir) {
642
+ return join(memoriesDir, 'state.db');
643
+ }
644
+ /** The pre-SQLite watermark file, imported once and then removed. */
645
+ export const LEGACY_STATE_FILE = 'extract-state.json';
646
+ /**
647
+ * Import and remove a pre-SQLite `extract-state.json`.
648
+ *
649
+ * The file only ever held extraction watermarks. Importing them matters: a
650
+ * session with no watermark is re-mined, which spends quota re-reading a
651
+ * conversation that was already processed. The import is skipped when the
652
+ * database already holds sessions, so it can never overwrite newer state.
653
+ *
654
+ * @param store - the state store to import into.
655
+ * @param memoriesDir - directory the legacy file lives in.
656
+ * @returns how many watermarks were imported, or `undefined` when there was nothing to do.
657
+ */
658
+ export async function importLegacyState(store, memoriesDir) {
659
+ const path = join(memoriesDir, LEGACY_STATE_FILE);
660
+ let text;
661
+ try {
662
+ text = await readFile(path, 'utf8');
663
+ }
664
+ catch (error) {
665
+ if (isMissing(error))
666
+ return undefined;
667
+ throw error;
668
+ }
669
+ let parsed;
670
+ try {
671
+ parsed = JSON.parse(text);
672
+ }
673
+ catch {
674
+ // A corrupt legacy file is not worth failing the plugin over; remove it so
675
+ // it stops looking like live state.
676
+ await rm(path, { force: true });
677
+ return 0;
678
+ }
679
+ let imported = 0;
680
+ if (store.sessionCount() === 0 && typeof parsed.sessions === 'object' && parsed.sessions !== null) {
681
+ for (const [id, value] of Object.entries(parsed.sessions)) {
682
+ if (typeof value !== 'object' || value === null)
683
+ continue;
684
+ const lastSeq = Number(value.lastSeq);
685
+ if (!Number.isFinite(lastSeq) || lastSeq <= 0)
686
+ continue;
687
+ store.putSession(id, {
688
+ lastSeq: Math.trunc(lastSeq),
689
+ at: Number.isFinite(Number(value.at)) ? Number(value.at) : 0,
690
+ ...typeof value.root === 'string' ? { root: value.root } : {},
691
+ ...value.contributed === true ? { contributed: true } : {},
692
+ // The legacy file never recorded activity; the watermark time is the
693
+ // closest honest proxy for "when this session was last touched".
694
+ activityAt: Number.isFinite(Number(value.at)) ? Number(value.at) : 0,
695
+ });
696
+ imported += 1;
697
+ }
698
+ }
699
+ await rm(path, { force: true });
700
+ return imported;
701
+ }