@unblocklabs/unblock-memory 0.12.3 → 0.13.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 (119) hide show
  1. package/README.md +19 -18
  2. package/dist/src/analysis.js +1 -1
  3. package/dist/src/cluster-review.d.ts +2 -0
  4. package/dist/src/cluster-review.js +3 -3
  5. package/dist/src/config.d.ts +9 -6
  6. package/dist/src/config.js +31 -20
  7. package/dist/src/curation.d.ts +1 -1
  8. package/dist/src/decision-client.d.ts +39 -0
  9. package/dist/src/decision-client.js +74 -0
  10. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  11. package/dist/src/decision-ranking.js +154 -0
  12. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  13. package/dist/src/decision-review.js +192 -0
  14. package/dist/src/diagnostics.d.ts +5 -5
  15. package/dist/src/emotion-baselines.d.ts +28 -3
  16. package/dist/src/emotion-baselines.js +309 -113
  17. package/dist/src/evidence-review.d.ts +22 -8
  18. package/dist/src/evidence-review.js +4 -4
  19. package/dist/src/extraction-chunk.d.ts +3 -0
  20. package/dist/src/extraction-chunk.js +23 -5
  21. package/dist/src/extraction-model.d.ts +2 -0
  22. package/dist/src/extraction-model.js +73 -48
  23. package/dist/src/extraction-runtime.d.ts +3 -1
  24. package/dist/src/extraction-runtime.js +43 -16
  25. package/dist/src/extraction-source.d.ts +1 -1
  26. package/dist/src/extraction-source.js +19 -11
  27. package/dist/src/extraction-store.d.ts +28 -3
  28. package/dist/src/extraction-store.js +145 -23
  29. package/dist/src/extraction-worker.d.ts +1 -0
  30. package/dist/src/extraction-worker.js +246 -93
  31. package/dist/src/inside-out-runtime.js +41 -29
  32. package/dist/src/inside-out-store.d.ts +2 -2
  33. package/dist/src/inside-out-store.js +110 -69
  34. package/dist/src/inside-out.d.ts +10 -9
  35. package/dist/src/inside-out.js +190 -105
  36. package/dist/src/manager.d.ts +22 -9
  37. package/dist/src/manager.js +275 -169
  38. package/dist/src/memory-search.d.ts +4 -2
  39. package/dist/src/memory-search.js +5 -5
  40. package/dist/src/memory-whisperer.d.ts +1 -1
  41. package/dist/src/memory-whisperer.js +183 -125
  42. package/dist/src/my-turn.d.ts +1 -1
  43. package/dist/src/my-turn.js +87 -68
  44. package/dist/src/people-background.d.ts +4 -0
  45. package/dist/src/people-background.js +29 -6
  46. package/dist/src/people-dossier-review.d.ts +20 -8
  47. package/dist/src/people-dossier-review.js +11 -8
  48. package/dist/src/people-hooks.js +127 -22
  49. package/dist/src/people-learning-cron.d.ts +1 -1
  50. package/dist/src/people-learning-cron.js +106 -57
  51. package/dist/src/people-learning-inventory.d.ts +1 -0
  52. package/dist/src/people-learning-inventory.js +281 -171
  53. package/dist/src/people-learning-prompt.js +1 -1
  54. package/dist/src/people-learning-runtime.d.ts +1 -1
  55. package/dist/src/people-learning-runtime.js +360 -203
  56. package/dist/src/people-learning-store.d.ts +27 -4
  57. package/dist/src/people-learning-store.js +312 -96
  58. package/dist/src/people-primer-tool.js +8 -6
  59. package/dist/src/people-primer.d.ts +3 -1
  60. package/dist/src/people-primer.js +61 -44
  61. package/dist/src/people-store.d.ts +18 -21
  62. package/dist/src/people-store.js +186 -63
  63. package/dist/src/people-tools.js +136 -92
  64. package/dist/src/plugin.js +16 -16
  65. package/dist/src/quality-audit.d.ts +2 -0
  66. package/dist/src/quality-audit.js +8 -7
  67. package/dist/src/response-audit.d.ts +1 -1
  68. package/dist/src/response-audit.js +76 -43
  69. package/dist/src/response-episodes.d.ts +1 -1
  70. package/dist/src/response-episodes.js +12 -17
  71. package/dist/src/response-judge.d.ts +151 -145
  72. package/dist/src/response-judge.js +535 -204
  73. package/dist/src/response-reviews.d.ts +29 -1
  74. package/dist/src/response-reviews.js +110 -13
  75. package/dist/src/response-runtime.js +8 -8
  76. package/dist/src/response-stages.d.ts +50 -53
  77. package/dist/src/response-stages.js +10 -4
  78. package/dist/src/response-store.d.ts +7 -6
  79. package/dist/src/response-store.js +332 -210
  80. package/dist/src/review-tools.d.ts +8 -2
  81. package/dist/src/review-tools.js +18 -18
  82. package/dist/src/runtime.d.ts +7 -4
  83. package/dist/src/runtime.js +624 -98
  84. package/dist/src/safety-whisperer.d.ts +2 -2
  85. package/dist/src/safety-whisperer.js +88 -71
  86. package/dist/src/session-sync.d.ts +3 -1
  87. package/dist/src/session-sync.js +200 -95
  88. package/dist/src/skill-whisperer.d.ts +1 -1
  89. package/dist/src/skill-whisperer.js +52 -30
  90. package/dist/src/training-gate.d.ts +8 -21
  91. package/dist/src/training-gate.js +32 -35
  92. package/dist/src/training-judge.d.ts +9 -16
  93. package/dist/src/training-judge.js +5 -5
  94. package/dist/src/training-queries.d.ts +13 -8
  95. package/dist/src/training-queries.js +370 -228
  96. package/dist/src/training-retrieval.d.ts +14 -24
  97. package/dist/src/training-retrieval.js +182 -136
  98. package/dist/src/training-runtime.d.ts +3 -0
  99. package/dist/src/training-runtime.js +76 -18
  100. package/dist/src/training-store.d.ts +18 -3
  101. package/dist/src/training-store.js +138 -50
  102. package/dist/src/training.js +8 -11
  103. package/dist/src/whisperer-context.d.ts +14 -0
  104. package/dist/src/whisperer-context.js +22 -1
  105. package/docs/configuration.md +76 -63
  106. package/docs/extraction.md +9 -7
  107. package/docs/memory-training.md +7 -6
  108. package/docs/people-learning.md +2 -2
  109. package/docs/peoplesql.md +6 -6
  110. package/docs/response-audit.md +10 -8
  111. package/docs/retrieval.md +40 -37
  112. package/openclaw.plugin.json +40 -26
  113. package/package.json +3 -2
  114. package/skills/memory-curator/SKILL.md +1 -1
  115. package/skills/people-whisperer/SKILL.md +1 -1
  116. package/dist/src/typesafe-client.d.ts +0 -30
  117. package/dist/src/typesafe-client.js +0 -92
  118. package/dist/src/typesafe-review.js +0 -154
  119. package/dist/src/typesafe.js +0 -147
@@ -1,7 +1,9 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { closeSync, constants, fchmodSync, lstatSync, openSync, readFileSync } from "node:fs";
3
+ import fs from "node:fs/promises";
3
4
  import { MEMORY_DATABASE } from "./memory-database.js";
4
5
  import { join } from "node:path";
6
+ import { DatabaseSync } from "node:sqlite";
5
7
  import { resolveAgentWorkspaceDir, resolveStateDir, } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
6
8
  import { listAgentIds, resolveAgentIdentity } from "openclaw/plugin-sdk/agent-runtime";
7
9
  import { QmdMemoryManager } from "./manager.js";
@@ -10,10 +12,64 @@ import { unchangedSessionSync } from "./session-sync.js";
10
12
  import { resolveConfiguredSkillPath, resolveSessionSource, resolveSources } from "./sources.js";
11
13
  import { classifyWorkspaceMemoryPaths } from "./workspace-path-classifier.js";
12
14
  import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
13
- const activeSessionSyncs = new Map();
15
+ const SESSION_SYNC_LOCK_FILE = "session-sync.lock.sqlite";
16
+ const LEGACY_SESSION_SYNC_LOCK_FILE = "session-sync.lock";
17
+ const SESSION_SYNC_STATUS_FILE = "session-sync-status.json";
18
+ const LEASE_BUSY_TIMEOUT_MS = 5000;
19
+ const MAX_LEASE_BUSY_RETRIES = 6;
20
+ const heldSessionSyncLeaseTokens = new Set();
21
+ const LEASE_SCHEMA_SQL = `
22
+ CREATE TABLE IF NOT EXISTS session_sync_lease (
23
+ id INTEGER PRIMARY KEY CHECK(id = 1),
24
+ pid INTEGER NOT NULL,
25
+ token TEXT NOT NULL,
26
+ started_at TEXT NOT NULL
27
+ )
28
+ `;
29
+ function heldLeaseKey(lockPath, token) {
30
+ return `${lockPath}\0${token}`;
31
+ }
32
+ function isLeaseHeldInProcess(lockPath, token) {
33
+ return heldSessionSyncLeaseTokens.has(heldLeaseKey(lockPath, token));
34
+ }
35
+ function isLeaseActive(lockPath, lease) {
36
+ if (!isProcessAlive(lease.pid))
37
+ return false;
38
+ if (lease.pid === process.pid && !isLeaseHeldInProcess(lockPath, lease.token)) {
39
+ return false;
40
+ }
41
+ return true;
42
+ }
43
+ function parseLegacySessionSyncLock(value) {
44
+ if (!value || typeof value !== "object" || Array.isArray(value))
45
+ return undefined;
46
+ const { pid, token, startedAt } = value;
47
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 ||
48
+ typeof token !== "string" || token.length === 0 ||
49
+ typeof startedAt !== "string" || startedAt.length === 0) {
50
+ return undefined;
51
+ }
52
+ return { pid, token, startedAt };
53
+ }
54
+ function readLiveLegacySessionSyncLock(directory) {
55
+ const legacyPath = join(directory, LEGACY_SESSION_SYNC_LOCK_FILE);
56
+ try {
57
+ const stat = lstatSync(legacyPath, { throwIfNoEntry: false });
58
+ if (!stat || !stat.isFile())
59
+ return undefined;
60
+ const parsed = parseLegacySessionSyncLock(JSON.parse(readFileSync(legacyPath, "utf8")));
61
+ if (!parsed || !isProcessAlive(parsed.pid))
62
+ return undefined;
63
+ return parsed;
64
+ }
65
+ catch {
66
+ // Missing, unreadable, or invalid legacy lock file does not block SQLite lease acquisition.
67
+ return undefined;
68
+ }
69
+ }
14
70
  async function readJson(path) {
15
71
  try {
16
- return JSON.parse(await readFile(path, "utf8"));
72
+ return JSON.parse(await fs.readFile(path, "utf8"));
17
73
  }
18
74
  catch (error) {
19
75
  if (error.code === "ENOENT")
@@ -23,7 +79,7 @@ async function readJson(path) {
23
79
  }
24
80
  async function removeIfPresent(path) {
25
81
  try {
26
- await unlink(path);
82
+ await fs.unlink(path);
27
83
  }
28
84
  catch (error) {
29
85
  if (error.code !== "ENOENT")
@@ -33,27 +89,219 @@ async function removeIfPresent(path) {
33
89
  async function atomicWriteJson(path, value) {
34
90
  const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
35
91
  try {
36
- await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
37
- await rename(temporary, path);
92
+ await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
93
+ await fs.chmod(temporary, 0o600);
94
+ await fs.rename(temporary, path);
38
95
  }
39
96
  finally {
40
97
  await removeIfPresent(temporary);
41
98
  }
42
99
  }
43
- export async function recoverInterruptedSessionSync(directory, statusPath, stale) {
44
- activeSessionSyncs.set(directory, stale.startedAt);
100
+ function isProcessAlive(pid) {
101
+ if (!Number.isInteger(pid) || pid <= 0)
102
+ return false;
103
+ try {
104
+ process.kill(pid, 0);
105
+ return true;
106
+ }
107
+ catch (error) {
108
+ const code = error.code;
109
+ if (code === "EPERM")
110
+ return true;
111
+ if (code === "ESRCH")
112
+ return false;
113
+ throw error;
114
+ }
115
+ }
116
+ function parseLeaseRow(value) {
117
+ if (!value || typeof value !== "object" || Array.isArray(value))
118
+ return undefined;
119
+ const { pid, token, started_at: startedAt } = value;
120
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 ||
121
+ typeof token !== "string" || token.length === 0 ||
122
+ typeof startedAt !== "string" || startedAt.length === 0) {
123
+ return undefined;
124
+ }
125
+ return { pid, token, startedAt };
126
+ }
127
+ function isSqliteBusy(error) {
128
+ if (!(error instanceof Error))
129
+ return false;
130
+ const errcode = "errcode" in error && typeof error.errcode === "number" ? error.errcode : undefined;
131
+ return errcode !== undefined && (errcode & 0xff) === 5;
132
+ }
133
+ async function withLeaseBusyRetry(operation) {
134
+ for (let attempt = 0;; attempt += 1) {
135
+ try {
136
+ return operation();
137
+ }
138
+ catch (error) {
139
+ if (!isSqliteBusy(error) || attempt >= MAX_LEASE_BUSY_RETRIES)
140
+ throw error;
141
+ const backoffMs = Math.min(200, 20 * (attempt + 1));
142
+ await new Promise((resolve) => setTimeout(resolve, backoffMs));
143
+ }
144
+ }
145
+ }
146
+ function ensurePrivateLeaseFile(lockPath) {
147
+ const existing = lstatSync(lockPath, { throwIfNoEntry: false });
148
+ if (existing && !existing.isFile()) {
149
+ throw new Error("Session sync lock database must be a regular file, not a symlink");
150
+ }
151
+ const descriptor = openSync(lockPath, constants.O_CREAT | constants.O_APPEND | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
152
+ try {
153
+ fchmodSync(descriptor, 0o600);
154
+ }
155
+ finally {
156
+ closeSync(descriptor);
157
+ }
158
+ }
159
+ async function withImmediateLeaseTransaction(lockPath, fn) {
160
+ return await withLeaseBusyRetry(() => {
161
+ ensurePrivateLeaseFile(lockPath);
162
+ const db = new DatabaseSync(lockPath);
163
+ let inTransaction = false;
164
+ try {
165
+ db.exec(`PRAGMA busy_timeout = ${LEASE_BUSY_TIMEOUT_MS}; PRAGMA trusted_schema = OFF;`);
166
+ db.exec("BEGIN IMMEDIATE");
167
+ inTransaction = true;
168
+ db.exec(LEASE_SCHEMA_SQL);
169
+ const { commit, value, onCommit } = fn(db);
170
+ db.exec(commit ? "COMMIT" : "ROLLBACK");
171
+ inTransaction = false;
172
+ if (commit)
173
+ onCommit?.();
174
+ return value;
175
+ }
176
+ catch (error) {
177
+ if (inTransaction) {
178
+ try {
179
+ db.exec("ROLLBACK");
180
+ }
181
+ catch {
182
+ // Transaction may already be rolled back by SQLite.
183
+ }
184
+ }
185
+ throw error;
186
+ }
187
+ finally {
188
+ db.close();
189
+ }
190
+ });
191
+ }
192
+ async function readSessionSyncLock(lockPath) {
193
+ const stat = lstatSync(lockPath, { throwIfNoEntry: false });
194
+ if (!stat)
195
+ return { exists: false };
196
+ if (!stat.isFile()) {
197
+ throw new Error("Session sync lock database must be a regular file, not a symlink");
198
+ }
199
+ return await withLeaseBusyRetry(() => {
200
+ const db = new DatabaseSync(lockPath, { readOnly: true });
201
+ try {
202
+ db.exec(`PRAGMA busy_timeout = ${LEASE_BUSY_TIMEOUT_MS}; PRAGMA query_only = ON; PRAGMA trusted_schema = OFF;`);
203
+ const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'session_sync_lease'").get();
204
+ if (!table)
205
+ return { exists: false };
206
+ const row = db.prepare("SELECT pid, token, started_at FROM session_sync_lease WHERE id = 1").get();
207
+ if (!row)
208
+ return { exists: false };
209
+ return { exists: true, lock: parseLeaseRow(row) };
210
+ }
211
+ finally {
212
+ db.close();
213
+ }
214
+ });
215
+ }
216
+ async function releaseSessionSyncLock(lockPath, token) {
217
+ heldSessionSyncLeaseTokens.delete(heldLeaseKey(lockPath, token));
218
+ const existing = lstatSync(lockPath, { throwIfNoEntry: false });
219
+ if (!existing)
220
+ return;
221
+ await withImmediateLeaseTransaction(lockPath, (db) => {
222
+ db.prepare("DELETE FROM session_sync_lease WHERE id = 1 AND token = ?").run(token);
223
+ return { commit: true, value: undefined };
224
+ });
225
+ }
226
+ async function releaseSessionSyncLockSafely(lockPath, token, onError) {
227
+ try {
228
+ await releaseSessionSyncLock(lockPath, token);
229
+ }
230
+ catch (error) {
231
+ if (onError)
232
+ onError(error);
233
+ else
234
+ console.warn(`unblock-memory failed to release session sync lease (${lockPath}): ${String(error)}`);
235
+ }
236
+ }
237
+ async function clearStaleSessionSyncLease(lockPath) {
238
+ const existing = lstatSync(lockPath, { throwIfNoEntry: false });
239
+ if (!existing)
240
+ return undefined;
241
+ return await withImmediateLeaseTransaction(lockPath, (db) => {
242
+ const row = db.prepare("SELECT pid, token, started_at FROM session_sync_lease WHERE id = 1").get();
243
+ if (!row)
244
+ return { commit: false, value: undefined };
245
+ const current = parseLeaseRow(row);
246
+ if (current && isLeaseActive(lockPath, current)) {
247
+ return { commit: false, value: current };
248
+ }
249
+ db.prepare("DELETE FROM session_sync_lease WHERE id = 1").run();
250
+ return { commit: true, value: undefined };
251
+ });
252
+ }
253
+ async function acquireSessionSyncLock(directory, startedAt) {
254
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
255
+ const liveLegacyBefore = readLiveLegacySessionSyncLock(directory);
256
+ if (liveLegacyBefore) {
257
+ return { acquired: false, owner: liveLegacyBefore };
258
+ }
259
+ const lockPath = join(directory, SESSION_SYNC_LOCK_FILE);
260
+ const candidate = {
261
+ pid: process.pid,
262
+ token: randomUUID(),
263
+ startedAt,
264
+ };
265
+ return await withImmediateLeaseTransaction(lockPath, (db) => {
266
+ const row = db.prepare("SELECT pid, token, started_at FROM session_sync_lease WHERE id = 1").get();
267
+ const existing = parseLeaseRow(row);
268
+ if (existing && isLeaseActive(lockPath, existing)) {
269
+ return { commit: false, value: { acquired: false, owner: existing } };
270
+ }
271
+ const liveLegacy = readLiveLegacySessionSyncLock(directory);
272
+ if (liveLegacy) {
273
+ return { commit: false, value: { acquired: false, owner: liveLegacy } };
274
+ }
275
+ db.prepare("INSERT OR REPLACE INTO session_sync_lease (id, pid, token, started_at) VALUES (1, ?, ?, ?)").run(candidate.pid, candidate.token, candidate.startedAt);
276
+ return {
277
+ commit: true,
278
+ value: { acquired: true, lock: candidate, lockPath },
279
+ onCommit: () => {
280
+ heldSessionSyncLeaseTokens.add(heldLeaseKey(lockPath, candidate.token));
281
+ },
282
+ };
283
+ });
284
+ }
285
+ function runningStatusFromReceipt(status, startedAt) {
286
+ return status?.status === "running" && status.startedAt === startedAt
287
+ ? { status: "running", phase: status.phase, startedAt }
288
+ : { status: "running", phase: "queued", startedAt };
289
+ }
290
+ export async function recoverInterruptedSessionSync(directory, statusPath, stale, onError) {
291
+ const acquired = await acquireSessionSyncLock(directory, stale.startedAt);
292
+ if (!acquired.acquired) {
293
+ const current = await readJson(statusPath);
294
+ return runningStatusFromReceipt(current, acquired.owner.startedAt);
295
+ }
45
296
  try {
46
297
  const current = await readJson(statusPath);
47
298
  if (!current)
48
299
  return { status: "idle" };
49
300
  if (current.status !== "running")
50
301
  return current;
51
- if (current.startedAt !== stale.startedAt) {
52
- return { status: "running", phase: current.phase, startedAt: current.startedAt };
53
- }
54
302
  const failed = {
55
303
  status: "failed",
56
- startedAt: stale.startedAt,
304
+ startedAt: current.startedAt,
57
305
  completedAt: new Date().toISOString(),
58
306
  error: "session sync interrupted by Gateway restart",
59
307
  };
@@ -61,8 +309,7 @@ export async function recoverInterruptedSessionSync(directory, statusPath, stale
61
309
  return failed;
62
310
  }
63
311
  finally {
64
- if (activeSessionSyncs.get(directory) === stale.startedAt)
65
- activeSessionSyncs.delete(directory);
312
+ await releaseSessionSyncLockSafely(acquired.lockPath, acquired.lock.token, onError);
66
313
  }
67
314
  }
68
315
  export class QmdMemoryRuntime {
@@ -71,24 +318,72 @@ export class QmdMemoryRuntime {
71
318
  #analysisExecutable;
72
319
  #keepEmbeddingModelWarm;
73
320
  #stateRoot;
321
+ #onError;
74
322
  #managers = new Map();
323
+ #closingManagers = new Map();
324
+ #activeSessionSyncs = new Map();
325
+ #pendingSessionSyncStarts = new Set();
326
+ #closing = false;
327
+ #closed = false;
328
+ #reloadFences = 0;
329
+ #closeAllFences = 0;
330
+ #closePromise;
75
331
  #sessionSyncTimer;
332
+ #schedule;
76
333
  startSessionSyncSchedule(cfg, onError) {
77
334
  this.stopSessionSyncSchedule();
335
+ if (this.#closing || this.#closed)
336
+ return;
337
+ const sessions = this.#corpora.find((corpus) => corpus.kind === "sessions");
338
+ if (!sessions?.syncIntervalMinutes)
339
+ return;
340
+ this.#schedule = { cfg, onError };
341
+ if (this.#reloadFences === 0 && this.#closeAllFences === 0) {
342
+ this.#startSessionSyncTimer(sessions.syncIntervalMinutes, cfg, onError);
343
+ }
344
+ }
345
+ stopSessionSyncSchedule() {
346
+ this.#schedule = undefined;
347
+ this.#pauseSessionSyncSchedule();
348
+ }
349
+ #pauseSessionSyncSchedule() {
350
+ if (this.#sessionSyncTimer)
351
+ clearInterval(this.#sessionSyncTimer);
352
+ this.#sessionSyncTimer = undefined;
353
+ }
354
+ #maybeResumeSessionSyncSchedule() {
355
+ if (this.#closing ||
356
+ this.#closed ||
357
+ this.#reloadFences > 0 ||
358
+ this.#closeAllFences > 0 ||
359
+ this.#sessionSyncTimer ||
360
+ !this.#schedule) {
361
+ return;
362
+ }
78
363
  const sessions = this.#corpora.find((corpus) => corpus.kind === "sessions");
79
364
  if (!sessions?.syncIntervalMinutes)
80
365
  return;
366
+ this.#startSessionSyncTimer(sessions.syncIntervalMinutes, this.#schedule.cfg, this.#schedule.onError);
367
+ }
368
+ #startSessionSyncTimer(syncIntervalMinutes, cfg, onError) {
81
369
  this.#sessionSyncTimer = setInterval(() => {
82
370
  for (const agentId of listAgentIds(cfg)) {
83
371
  void this.startSessionSync({ cfg, agentId }).catch(onError);
84
372
  }
85
- }, sessions.syncIntervalMinutes * 60_000);
373
+ }, syncIntervalMinutes * 60_000);
86
374
  this.#sessionSyncTimer.unref();
87
375
  }
88
- stopSessionSyncSchedule() {
89
- if (this.#sessionSyncTimer)
90
- clearInterval(this.#sessionSyncTimer);
91
- this.#sessionSyncTimer = undefined;
376
+ #admissionBlockedReason() {
377
+ if (this.#closing || this.#closed)
378
+ return "memory runtime is closing";
379
+ if (this.#reloadFences > 0)
380
+ return "memory runtime is reloading";
381
+ if (this.#closeAllFences > 0)
382
+ return "memory runtime is closing";
383
+ return undefined;
384
+ }
385
+ async #releaseLease(lockPath, token) {
386
+ await releaseSessionSyncLockSafely(lockPath, token, this.#onError ?? this.#schedule?.onError);
92
387
  }
93
388
  constructor(corpora, options = {}) {
94
389
  this.#corpora = corpora;
@@ -96,42 +391,82 @@ export class QmdMemoryRuntime {
96
391
  this.#analysisExecutable = options.analysisExecutable;
97
392
  this.#keepEmbeddingModelWarm = options.keepEmbeddingModelWarm ?? true;
98
393
  this.#stateRoot = options.stateRoot ?? resolveStateDir();
394
+ this.#onError = options.onError;
99
395
  }
100
396
  async getMemorySearchManager(params) {
101
- let pending = this.#managers.get(params.agentId);
102
- if (!pending) {
103
- pending = this.#createManager(params.cfg, params.agentId);
104
- this.#managers.set(params.agentId, pending);
105
- }
106
- try {
107
- return { manager: await pending };
108
- }
109
- catch (error) {
110
- if (this.#managers.get(params.agentId) === pending)
111
- this.#managers.delete(params.agentId);
112
- return { manager: null, error: error instanceof Error ? error.message : String(error) };
397
+ while (true) {
398
+ const blocked = this.#admissionBlockedReason();
399
+ if (blocked) {
400
+ return { manager: null, error: blocked };
401
+ }
402
+ const closing = this.#closingManagers.get(params.agentId);
403
+ if (closing) {
404
+ await closing.catch(() => undefined);
405
+ continue;
406
+ }
407
+ let pending = this.#managers.get(params.agentId);
408
+ if (!pending) {
409
+ pending = this.#createManager(params.cfg, params.agentId);
410
+ this.#managers.set(params.agentId, pending);
411
+ }
412
+ try {
413
+ const manager = await pending;
414
+ const blockedAfter = this.#admissionBlockedReason();
415
+ if (blockedAfter) {
416
+ return { manager: null, error: blockedAfter };
417
+ }
418
+ if (this.#managers.get(params.agentId) !== pending) {
419
+ continue;
420
+ }
421
+ return { manager };
422
+ }
423
+ catch (error) {
424
+ if (this.#managers.get(params.agentId) === pending)
425
+ this.#managers.delete(params.agentId);
426
+ return { manager: null, error: error instanceof Error ? error.message : String(error) };
427
+ }
113
428
  }
114
429
  }
115
430
  resolveMemoryBackendConfig() {
116
431
  return { backend: "builtin" };
117
432
  }
118
433
  classifyWorkspaceMemoryPaths = classifyWorkspaceMemoryPaths;
119
- async startSessionSync(params, force = false) {
434
+ startSessionSync(params, force = false) {
435
+ const blocked = this.#admissionBlockedReason();
436
+ if (blocked) {
437
+ return Promise.resolve({
438
+ status: "unavailable",
439
+ error: blocked,
440
+ });
441
+ }
120
442
  if (!this.#corpora.some((corpus) => corpus.kind === "sessions")) {
121
- return {
443
+ return Promise.resolve({
122
444
  status: "unavailable",
123
445
  error: 'memory session sync requires a configured "sessions" corpus',
124
- };
446
+ });
125
447
  }
448
+ const pending = this.#startSessionSync(params, force);
449
+ this.#pendingSessionSyncStarts.add(pending);
450
+ const cleanup = () => {
451
+ this.#pendingSessionSyncStarts.delete(pending);
452
+ };
453
+ pending.then(cleanup, cleanup);
454
+ return pending;
455
+ }
456
+ async #startSessionSync(params, force) {
126
457
  const directory = this.#stateDir(params.agentId);
127
- const statusPath = join(directory, "session-sync-status.json");
128
- const running = activeSessionSyncs.get(directory);
129
- if (running)
130
- return { status: "already_running", startedAt: running };
458
+ const statusPath = join(directory, SESSION_SYNC_STATUS_FILE);
131
459
  const startedAt = new Date().toISOString();
132
- activeSessionSyncs.set(directory, startedAt);
460
+ const acquired = await acquireSessionSyncLock(directory, startedAt);
461
+ if (!acquired.acquired) {
462
+ return { status: "already_running", startedAt: acquired.owner.startedAt };
463
+ }
464
+ const blockedAfterAcquire = this.#admissionBlockedReason();
465
+ if (blockedAfterAcquire) {
466
+ await this.#releaseLease(acquired.lockPath, acquired.lock.token);
467
+ return { status: "unavailable", error: blockedAfterAcquire };
468
+ }
133
469
  try {
134
- await mkdir(directory, { recursive: true, mode: 0o700 });
135
470
  await atomicWriteJson(statusPath, {
136
471
  status: "running",
137
472
  phase: "queued",
@@ -140,85 +475,276 @@ export class QmdMemoryRuntime {
140
475
  });
141
476
  }
142
477
  catch (error) {
143
- if (activeSessionSyncs.get(directory) === startedAt)
144
- activeSessionSyncs.delete(directory);
478
+ await this.#releaseLease(acquired.lockPath, acquired.lock.token);
145
479
  throw error;
146
480
  }
147
- void (async () => {
148
- let statusWrites = Promise.resolve();
149
- const writePhase = (phase) => {
150
- statusWrites = statusWrites.then(() => atomicWriteJson(statusPath, {
151
- status: "running",
152
- phase,
153
- pid: process.pid,
154
- startedAt,
155
- }));
156
- };
481
+ const blockedAfterWrite = this.#admissionBlockedReason();
482
+ if (blockedAfterWrite) {
157
483
  try {
158
- const sessions = this.#sessionConfig(params.cfg, params.agentId);
159
- let result = !force && sessions
160
- ? await unchangedSessionSync(sessions, join(directory, "index.sqlite")) : undefined;
161
- if (!result) {
162
- const { manager, error } = await this.getMemorySearchManager(params);
163
- if (!manager)
164
- throw new Error(error ?? "memory unavailable");
165
- result = await manager.syncSessions(force, writePhase);
166
- }
167
- await statusWrites;
168
484
  await atomicWriteJson(statusPath, {
169
- status: "completed",
485
+ status: "failed",
170
486
  startedAt,
171
487
  completedAt: new Date().toISOString(),
172
- ...result,
488
+ error: blockedAfterWrite,
173
489
  });
174
490
  }
175
- catch (error) {
176
- await statusWrites.catch(() => { });
177
- try {
178
- await atomicWriteJson(statusPath, {
179
- status: "failed",
180
- startedAt,
181
- completedAt: new Date().toISOString(),
182
- error: error instanceof Error ? error.message : String(error),
183
- });
184
- }
185
- catch {
186
- // The next status read converts the persisted running state to interrupted.
187
- }
491
+ catch {
492
+ // Best effort: the next status read recovers any remaining running receipt.
188
493
  }
189
- finally {
190
- if (activeSessionSyncs.get(directory) === startedAt)
191
- activeSessionSyncs.delete(directory);
494
+ await this.#releaseLease(acquired.lockPath, acquired.lock.token);
495
+ return { status: "unavailable", error: blockedAfterWrite };
496
+ }
497
+ const run = this.#runSessionSync(params, force, {
498
+ directory,
499
+ statusPath,
500
+ lockPath: acquired.lockPath,
501
+ token: acquired.lock.token,
502
+ startedAt,
503
+ });
504
+ this.#activeSessionSyncs.set(directory, run);
505
+ const cleanupRun = () => {
506
+ if (this.#activeSessionSyncs.get(directory) === run) {
507
+ this.#activeSessionSyncs.delete(directory);
192
508
  }
193
- })().catch(() => { });
509
+ };
510
+ run.then(cleanupRun, cleanupRun);
194
511
  return { status: "started", startedAt };
195
512
  }
513
+ async #runSessionSync(params, force, run) {
514
+ let statusWrites = Promise.resolve();
515
+ const writePhase = (phase) => {
516
+ statusWrites = statusWrites.then(() => atomicWriteJson(run.statusPath, {
517
+ status: "running",
518
+ phase,
519
+ pid: process.pid,
520
+ startedAt: run.startedAt,
521
+ }));
522
+ };
523
+ try {
524
+ const sessions = this.#sessionConfig(params.cfg, params.agentId);
525
+ let result = !force && sessions
526
+ ? await unchangedSessionSync(sessions, join(run.directory, "index.sqlite"))
527
+ : undefined;
528
+ if (!result) {
529
+ const { manager, error } = await this.getMemorySearchManager(params);
530
+ if (!manager)
531
+ throw new Error(error ?? "memory unavailable");
532
+ result = await manager.syncSessions(force, writePhase);
533
+ }
534
+ await statusWrites;
535
+ await atomicWriteJson(run.statusPath, {
536
+ status: "completed",
537
+ startedAt: run.startedAt,
538
+ completedAt: new Date().toISOString(),
539
+ ...result,
540
+ });
541
+ }
542
+ catch (error) {
543
+ await statusWrites.catch(() => { });
544
+ try {
545
+ await atomicWriteJson(run.statusPath, {
546
+ status: "failed",
547
+ startedAt: run.startedAt,
548
+ completedAt: new Date().toISOString(),
549
+ error: error instanceof Error ? error.message : String(error),
550
+ });
551
+ }
552
+ catch {
553
+ // The next status read converts the persisted running state to interrupted.
554
+ }
555
+ }
556
+ finally {
557
+ await this.#releaseLease(run.lockPath, run.token);
558
+ }
559
+ }
196
560
  async sessionSyncStatus(agentId) {
197
561
  const directory = this.#stateDir(agentId);
198
- const statusPath = join(directory, "session-sync-status.json");
562
+ const lockPath = join(directory, SESSION_SYNC_LOCK_FILE);
563
+ const statusPath = join(directory, SESSION_SYNC_STATUS_FILE);
564
+ const onError = this.#onError ?? this.#schedule?.onError;
565
+ const lockState = await readSessionSyncLock(lockPath);
566
+ if (lockState.exists && lockState.lock && isLeaseActive(lockPath, lockState.lock)) {
567
+ const status = await readJson(statusPath);
568
+ return runningStatusFromReceipt(status, lockState.lock.startedAt);
569
+ }
570
+ const legacyOwner = readLiveLegacySessionSyncLock(directory);
571
+ if (legacyOwner) {
572
+ const status = await readJson(statusPath);
573
+ return runningStatusFromReceipt(status, legacyOwner.startedAt);
574
+ }
199
575
  const status = await readJson(statusPath);
200
- const running = activeSessionSyncs.get(directory);
201
- if (running) {
202
- return status?.status === "running" && status.startedAt === running
203
- ? { status: "running", phase: status.phase, startedAt: running }
204
- : { status: "running", phase: "queued", startedAt: running };
576
+ if (status?.status === "running") {
577
+ return await recoverInterruptedSessionSync(directory, statusPath, status, onError);
578
+ }
579
+ if (lockState.exists) {
580
+ const liveOwner = await clearStaleSessionSyncLease(lockPath);
581
+ if (liveOwner) {
582
+ const refreshedStatus = await readJson(statusPath);
583
+ return runningStatusFromReceipt(refreshedStatus, liveOwner.startedAt);
584
+ }
585
+ const refreshedStatus = await readJson(statusPath);
586
+ if (refreshedStatus?.status === "running") {
587
+ return await recoverInterruptedSessionSync(directory, statusPath, refreshedStatus, onError);
588
+ }
589
+ return refreshedStatus ?? { status: "idle" };
590
+ }
591
+ return status ?? { status: "idle" };
592
+ }
593
+ async #drainSessionSyncs() {
594
+ while (this.#pendingSessionSyncStarts.size > 0 || this.#activeSessionSyncs.size > 0) {
595
+ await Promise.allSettled([
596
+ ...this.#pendingSessionSyncStarts,
597
+ ...this.#activeSessionSyncs.values(),
598
+ ]);
205
599
  }
206
- if (!status)
207
- return { status: "idle" };
208
- if (status.status !== "running")
209
- return status;
210
- return await recoverInterruptedSessionSync(directory, statusPath, status);
600
+ }
601
+ prepareReload(change) {
602
+ // QMD embeds locally rather than via host MemoryEmbeddingProviderAdapter instances,
603
+ // so only retiring this runtime affects its managers and session syncs.
604
+ if (!change.retireRuntime) {
605
+ return {
606
+ drain: async () => ({ errors: [] }),
607
+ resume() { },
608
+ };
609
+ }
610
+ this.#reloadFences += 1;
611
+ this.#pauseSessionSyncSchedule();
612
+ let resumed = false;
613
+ let drainPromise;
614
+ return {
615
+ drain: () => {
616
+ if (!drainPromise) {
617
+ drainPromise = (async () => {
618
+ const errors = [];
619
+ if (resumed)
620
+ return { errors };
621
+ let ranOnce = false;
622
+ while (!ranOnce ||
623
+ (!resumed && (this.#pendingSessionSyncStarts.size > 0 ||
624
+ this.#activeSessionSyncs.size > 0 ||
625
+ this.#managers.size > 0 ||
626
+ this.#closingManagers.size > 0))) {
627
+ ranOnce = true;
628
+ await this.#drainSessionSyncs();
629
+ if (resumed)
630
+ break;
631
+ const agentIds = new Set([...this.#managers.keys(), ...this.#closingManagers.keys()]);
632
+ if (agentIds.size > 0) {
633
+ const settled = await Promise.allSettled([...agentIds].map((agentId) => this.closeMemorySearchManager({ agentId })));
634
+ for (const outcome of settled) {
635
+ if (outcome.status === "rejected")
636
+ errors.push(outcome.reason);
637
+ }
638
+ }
639
+ }
640
+ return { errors };
641
+ })();
642
+ }
643
+ return drainPromise;
644
+ },
645
+ resume: () => {
646
+ if (resumed)
647
+ return;
648
+ resumed = true;
649
+ this.#reloadFences = Math.max(0, this.#reloadFences - 1);
650
+ this.#maybeResumeSessionSyncSchedule();
651
+ },
652
+ };
211
653
  }
212
654
  async closeMemorySearchManager(params) {
213
- const pending = this.#managers.get(params.agentId);
214
- this.#managers.delete(params.agentId);
215
- await (await pending)?.close();
655
+ const { agentId } = params;
656
+ const activeSync = this.#activeSessionSyncs.get(this.#stateDir(agentId));
657
+ if (activeSync)
658
+ await activeSync.catch(() => undefined);
659
+ const previousClose = this.#closingManagers.get(agentId);
660
+ const pending = this.#managers.get(agentId);
661
+ this.#managers.delete(agentId);
662
+ if (!previousClose && !pending)
663
+ return;
664
+ const closing = (async () => {
665
+ let closeError;
666
+ if (previousClose) {
667
+ try {
668
+ await previousClose;
669
+ }
670
+ catch (error) {
671
+ closeError = error;
672
+ }
673
+ }
674
+ if (pending) {
675
+ let manager;
676
+ try {
677
+ manager = await pending;
678
+ }
679
+ catch {
680
+ // Failed startup already cleaned up its own manager inside #createManager.
681
+ }
682
+ if (manager) {
683
+ try {
684
+ await manager.close();
685
+ }
686
+ catch (error) {
687
+ closeError ??= error;
688
+ }
689
+ }
690
+ }
691
+ if (closeError !== undefined)
692
+ throw closeError;
693
+ })();
694
+ this.#closingManagers.set(agentId, closing);
695
+ try {
696
+ await closing;
697
+ }
698
+ finally {
699
+ if (this.#closingManagers.get(agentId) === closing) {
700
+ this.#closingManagers.delete(agentId);
701
+ }
702
+ }
216
703
  }
217
704
  async closeAllMemorySearchManagers() {
705
+ this.#closeAllFences += 1;
218
706
  this.stopSessionSyncSchedule();
219
- const managers = [...this.#managers.values()];
220
- this.#managers.clear();
221
- await Promise.all(managers.map(async (pending) => (await pending).close()));
707
+ let firstError;
708
+ let hasError = false;
709
+ try {
710
+ while (this.#pendingSessionSyncStarts.size > 0 ||
711
+ this.#activeSessionSyncs.size > 0 ||
712
+ this.#managers.size > 0 ||
713
+ this.#closingManagers.size > 0) {
714
+ await this.#drainSessionSyncs();
715
+ const agentIds = new Set([...this.#managers.keys(), ...this.#closingManagers.keys()]);
716
+ if (agentIds.size > 0) {
717
+ const settled = await Promise.allSettled([...agentIds].map((agentId) => this.closeMemorySearchManager({ agentId })));
718
+ for (const outcome of settled) {
719
+ if (outcome.status === "rejected" && !hasError) {
720
+ hasError = true;
721
+ firstError = outcome.reason;
722
+ }
723
+ }
724
+ }
725
+ }
726
+ }
727
+ finally {
728
+ this.#closeAllFences = Math.max(0, this.#closeAllFences - 1);
729
+ }
730
+ if (hasError)
731
+ throw firstError;
732
+ }
733
+ async close() {
734
+ if (this.#closePromise)
735
+ return this.#closePromise;
736
+ this.#closing = true;
737
+ const closing = (async () => {
738
+ try {
739
+ await this.closeAllMemorySearchManagers();
740
+ }
741
+ finally {
742
+ this.#closed = true;
743
+ this.#closing = false;
744
+ }
745
+ })();
746
+ this.#closePromise = closing;
747
+ return closing;
222
748
  }
223
749
  async searchSkills(params, query, minScore, limit) {
224
750
  const { manager, error } = await this.getMemorySearchManager(params);