@unblocklabs/unblock-memory 0.12.3 → 0.14.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 (138) hide show
  1. package/README.md +19 -18
  2. package/defaults.json +162 -0
  3. package/dist/src/analysis.js +1 -1
  4. package/dist/src/cluster-review.d.ts +2 -0
  5. package/dist/src/cluster-review.js +9 -8
  6. package/dist/src/config.d.ts +9 -6
  7. package/dist/src/config.js +59 -45
  8. package/dist/src/curation.d.ts +1 -1
  9. package/dist/src/decision-client.d.ts +45 -0
  10. package/dist/src/decision-client.js +87 -0
  11. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  12. package/dist/src/decision-ranking.js +155 -0
  13. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  14. package/dist/src/decision-review.js +193 -0
  15. package/dist/src/defaults.d.ts +8 -0
  16. package/dist/src/defaults.js +128 -0
  17. package/dist/src/diagnostics.d.ts +5 -5
  18. package/dist/src/emotion-baselines.d.ts +28 -3
  19. package/dist/src/emotion-baselines.js +312 -115
  20. package/dist/src/evidence-review.d.ts +22 -8
  21. package/dist/src/evidence-review.js +11 -8
  22. package/dist/src/extraction-chunk.d.ts +3 -0
  23. package/dist/src/extraction-chunk.js +25 -6
  24. package/dist/src/extraction-config.js +4 -2
  25. package/dist/src/extraction-model.d.ts +25 -17
  26. package/dist/src/extraction-model.js +232 -104
  27. package/dist/src/extraction-runtime.d.ts +3 -1
  28. package/dist/src/extraction-runtime.js +48 -20
  29. package/dist/src/extraction-source.d.ts +1 -1
  30. package/dist/src/extraction-source.js +21 -12
  31. package/dist/src/extraction-store.d.ts +29 -3
  32. package/dist/src/extraction-store.js +149 -25
  33. package/dist/src/extraction-worker.d.ts +3 -3
  34. package/dist/src/extraction-worker.js +250 -95
  35. package/dist/src/inside-out-runtime.js +43 -30
  36. package/dist/src/inside-out-sources.js +2 -1
  37. package/dist/src/inside-out-store.d.ts +2 -2
  38. package/dist/src/inside-out-store.js +111 -69
  39. package/dist/src/inside-out.d.ts +10 -9
  40. package/dist/src/inside-out.js +194 -106
  41. package/dist/src/manager.d.ts +22 -9
  42. package/dist/src/manager.js +279 -172
  43. package/dist/src/memory-database.js +3 -2
  44. package/dist/src/memory-passage.d.ts +2 -2
  45. package/dist/src/memory-passage.js +3 -2
  46. package/dist/src/memory-search.d.ts +4 -2
  47. package/dist/src/memory-search.js +5 -5
  48. package/dist/src/memory-whisperer.d.ts +1 -1
  49. package/dist/src/memory-whisperer.js +195 -129
  50. package/dist/src/my-turn.d.ts +1 -1
  51. package/dist/src/my-turn.js +90 -70
  52. package/dist/src/people-background.d.ts +5 -1
  53. package/dist/src/people-background.js +31 -7
  54. package/dist/src/people-dossier-review.d.ts +20 -8
  55. package/dist/src/people-dossier-review.js +15 -11
  56. package/dist/src/people-hooks.js +127 -22
  57. package/dist/src/people-learning-cron.d.ts +1 -1
  58. package/dist/src/people-learning-cron.js +107 -57
  59. package/dist/src/people-learning-inventory.d.ts +1 -0
  60. package/dist/src/people-learning-inventory.js +283 -172
  61. package/dist/src/people-learning-prompt.js +1 -1
  62. package/dist/src/people-learning-runtime.d.ts +1 -1
  63. package/dist/src/people-learning-runtime.js +360 -203
  64. package/dist/src/people-learning-store.d.ts +27 -4
  65. package/dist/src/people-learning-store.js +312 -96
  66. package/dist/src/people-primer-tool.js +13 -10
  67. package/dist/src/people-primer.d.ts +3 -1
  68. package/dist/src/people-primer.js +66 -48
  69. package/dist/src/people-store.d.ts +18 -21
  70. package/dist/src/people-store.js +188 -64
  71. package/dist/src/people-tools.js +138 -93
  72. package/dist/src/plugin.js +19 -18
  73. package/dist/src/quality-audit.d.ts +2 -0
  74. package/dist/src/quality-audit.js +11 -9
  75. package/dist/src/quality-triage.js +4 -3
  76. package/dist/src/query-generator.js +5 -2
  77. package/dist/src/response-audit.d.ts +1 -1
  78. package/dist/src/response-audit.js +78 -44
  79. package/dist/src/response-config.js +3 -1
  80. package/dist/src/response-episodes.d.ts +1 -1
  81. package/dist/src/response-episodes.js +15 -19
  82. package/dist/src/response-identity.js +2 -1
  83. package/dist/src/response-judge.d.ts +151 -145
  84. package/dist/src/response-judge.js +535 -204
  85. package/dist/src/response-memory.js +2 -1
  86. package/dist/src/response-outcome.js +9 -8
  87. package/dist/src/response-reviews.d.ts +29 -1
  88. package/dist/src/response-reviews.js +113 -15
  89. package/dist/src/response-runtime.js +10 -9
  90. package/dist/src/response-stages.d.ts +50 -53
  91. package/dist/src/response-stages.js +10 -4
  92. package/dist/src/response-store.d.ts +7 -6
  93. package/dist/src/response-store.js +335 -212
  94. package/dist/src/review-tools.d.ts +8 -2
  95. package/dist/src/review-tools.js +22 -21
  96. package/dist/src/runtime.d.ts +7 -4
  97. package/dist/src/runtime.js +625 -98
  98. package/dist/src/safety-config.js +3 -2
  99. package/dist/src/safety-whisperer.d.ts +2 -2
  100. package/dist/src/safety-whisperer.js +90 -73
  101. package/dist/src/session-sync.d.ts +3 -1
  102. package/dist/src/session-sync.js +202 -96
  103. package/dist/src/skill-whisperer.d.ts +2 -2
  104. package/dist/src/skill-whisperer.js +55 -32
  105. package/dist/src/slack-directory.js +3 -2
  106. package/dist/src/training-gate.d.ts +9 -22
  107. package/dist/src/training-gate.js +34 -36
  108. package/dist/src/training-input.js +4 -3
  109. package/dist/src/training-judge.d.ts +9 -16
  110. package/dist/src/training-judge.js +6 -5
  111. package/dist/src/training-models.d.ts +1 -1
  112. package/dist/src/training-models.js +9 -7
  113. package/dist/src/training-queries.d.ts +14 -9
  114. package/dist/src/training-queries.js +374 -231
  115. package/dist/src/training-retrieval.d.ts +17 -27
  116. package/dist/src/training-retrieval.js +186 -139
  117. package/dist/src/training-runtime.d.ts +3 -0
  118. package/dist/src/training-runtime.js +76 -18
  119. package/dist/src/training-store.d.ts +18 -3
  120. package/dist/src/training-store.js +141 -52
  121. package/dist/src/training.js +9 -11
  122. package/dist/src/whisperer-context.d.ts +13 -0
  123. package/dist/src/whisperer-context.js +22 -1
  124. package/docs/configuration.md +83 -64
  125. package/docs/extraction.md +26 -35
  126. package/docs/memory-training.md +7 -6
  127. package/docs/people-learning.md +2 -2
  128. package/docs/peoplesql.md +6 -6
  129. package/docs/response-audit.md +10 -8
  130. package/docs/retrieval.md +43 -47
  131. package/openclaw.plugin.json +76 -75
  132. package/package.json +5 -2
  133. package/skills/memory-curator/SKILL.md +1 -1
  134. package/skills/people-whisperer/SKILL.md +1 -1
  135. package/dist/src/typesafe-client.d.ts +0 -30
  136. package/dist/src/typesafe-client.js +0 -92
  137. package/dist/src/typesafe-review.js +0 -154
  138. package/dist/src/typesafe.js +0 -147
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
2
3
  import { mkdir, stat } from "node:fs/promises";
3
4
  import { basename, dirname, relative, resolve, sep } from "node:path";
@@ -20,8 +21,10 @@ import { expandSessionSearchHit, renderMemoryPassage } from "./memory-passage.js
20
21
  import { startTiming, timeStage, vectorTrace, vectorParts, unaccounted } from "./retrieval-timing.js";
21
22
  export { expandSessionSearchHit } from "./memory-passage.js";
22
23
  const DEFAULT_READ_LINES = 120;
23
- const MAX_READ_CHARS = 12_000;
24
- const WATCH_DEBOUNCE_MS = 250;
24
+ const MAX_READ_CHARS = DEFAULTS.memoryWhisperer.memoryGetMaxChars;
25
+ const WATCH_DEBOUNCE_MS = DEFAULTS.sqlite.watchDebounceMs;
26
+ const WATCH_RETRY_MS = DEFAULTS.sqlite.watchRetryMs;
27
+ const MANAGER_CLOSED_ERROR = "QmdMemoryManager is closed";
25
28
  function readSkillDocuments(source) {
26
29
  const documents = [];
27
30
  const visitedDirectories = new Set();
@@ -126,13 +129,7 @@ export function cleanupRemovedDocuments(store, changedDocuments = 0) {
126
129
  }
127
130
  return cleaned;
128
131
  }
129
- export async function pruneStaleCollections(store, configuredCollections) {
130
- const staleCollections = (await store.getStatus()).collections
131
- .map((collection) => collection.name)
132
- .filter((name) => !configuredCollections.has(name));
133
- if (staleCollections.length === 0)
134
- return 0;
135
- enableSecureDelete(store);
132
+ function pruneStaleCollections(store, staleCollections) {
136
133
  const deleteDocuments = store.internal.db.prepare("DELETE FROM documents WHERE collection = ?");
137
134
  const removed = store.internal.db.transaction(() => {
138
135
  let count = 0;
@@ -148,20 +145,25 @@ export function buildReadResult(params) {
148
145
  if (fileLines.at(-1) === "")
149
146
  fileLines.pop();
150
147
  const from = Math.max(1, Math.floor(params.from ?? 1));
151
- const requestedLines = Math.max(1, Math.floor(params.lines ?? DEFAULT_READ_LINES));
148
+ const requestedLines = Math.min(DEFAULTS.memoryWhisperer.memoryGetMaxLines, Math.max(1, Math.floor(params.lines ?? DEFAULT_READ_LINES)));
152
149
  const selected = fileLines.slice(from - 1, from - 1 + requestedLines);
153
- let includedLines = selected.length;
154
- let text = selected.join("\n");
155
- while (includedLines > 1 && text.length > MAX_READ_CHARS) {
156
- includedLines -= 1;
157
- text = selected.slice(0, includedLines).join("\n");
150
+ let includedLines = 0;
151
+ let length = 0;
152
+ for (const line of selected) {
153
+ const nextLength = length + line.length + (includedLines > 0 ? 1 : 0);
154
+ if (includedLines > 0 && nextLength > MAX_READ_CHARS)
155
+ break;
156
+ length = nextLength;
157
+ includedLines += 1;
158
158
  }
159
- const hardTruncated = text.length > MAX_READ_CHARS;
160
- if (hardTruncated)
161
- text = text.slice(0, MAX_READ_CHARS);
159
+ const hardTruncated = length > MAX_READ_CHARS;
162
160
  const moreLinesRemain = from - 1 + includedLines < fileLines.length;
163
161
  const truncated = hardTruncated || moreLinesRemain || includedLines < selected.length;
164
162
  const nextFrom = hardTruncated ? undefined : truncated ? from + includedLines : undefined;
163
+ selected.length = includedLines;
164
+ let text = selected.join("\n");
165
+ if (hardTruncated)
166
+ text = text.slice(0, MAX_READ_CHARS);
165
167
  if (truncated) {
166
168
  text += `\n\n[More content available.${nextFrom ? ` Use from=${nextFrom} to continue.` : ""}]`;
167
169
  }
@@ -223,9 +225,12 @@ export class QmdMemoryManager {
223
225
  #analysisRunner;
224
226
  #sessions;
225
227
  #store;
228
+ #storePromise;
226
229
  #curation;
227
230
  #cleanupRemovedDocuments;
228
231
  #operationChain;
232
+ #inFlight = new Set();
233
+ #closePromise;
229
234
  #watcher;
230
235
  #watchReady;
231
236
  #watchTimer;
@@ -250,20 +255,22 @@ export class QmdMemoryManager {
250
255
  }
251
256
  }
252
257
  async diagnostics() {
253
- await this.#operationChain;
254
- const store = await this.#getStore();
255
- const status = await store.getStatus();
256
- const manifest = this.#sessions ? await readSessionManifest(this.#sessions.manifestPath) : undefined;
257
- return {
258
- projectorVersion: PROJECTOR_VERSION,
259
- semanticChunkingVersion: "semanticChunkingVersion" in status ? status.semanticChunkingVersion : null,
260
- sessionsNeedingProjection: manifest ? Object.values(manifest.sessions).filter(session => session.projectorVersion !== PROJECTOR_VERSION).length : 0,
261
- needsEmbedding: status.needsEmbedding,
262
- embeddingReady: status.needsEmbedding === 0 && status.hasVectorIndex,
263
- structuralChunksOmitted: this.#structuralDiagnosticsAvailable ? this.#structuralChunksOmitted : null,
264
- retrieval: this.#retrievalTelemetry.snapshot(),
265
- scope: "Projection count covers previously indexed sessions; omissions count this manager lifetime; null means dependency has not reported counts.",
266
- };
258
+ return this.#runFenced(async () => {
259
+ await this.#operationChain;
260
+ const store = await this.#getStore();
261
+ const status = await store.getStatus();
262
+ const manifest = this.#sessions ? await readSessionManifest(this.#sessions.manifestPath) : undefined;
263
+ return {
264
+ projectorVersion: PROJECTOR_VERSION,
265
+ semanticChunkingVersion: "semanticChunkingVersion" in status ? status.semanticChunkingVersion : null,
266
+ sessionsNeedingProjection: manifest ? Object.values(manifest.sessions).filter(session => session.projectorVersion !== PROJECTOR_VERSION).length : 0,
267
+ needsEmbedding: status.needsEmbedding,
268
+ embeddingReady: status.needsEmbedding === 0 && status.hasVectorIndex,
269
+ structuralChunksOmitted: this.#structuralDiagnosticsAvailable ? this.#structuralChunksOmitted : null,
270
+ retrieval: this.#retrievalTelemetry.snapshot(),
271
+ scope: "Projection count covers previously indexed sessions; omissions count this manager lifetime; null means dependency has not reported counts.",
272
+ };
273
+ });
267
274
  }
268
275
  constructor(params) {
269
276
  this.#dbPath = params.dbPath;
@@ -281,9 +288,11 @@ export class QmdMemoryManager {
281
288
  this.#sessions = params.sessions;
282
289
  }
283
290
  async start() {
291
+ this.#assertOpen();
284
292
  if (this.#sessions) {
285
293
  await this.#reloadSessionMetadata();
286
294
  }
295
+ this.#assertOpen();
287
296
  this.#startWatcher();
288
297
  await this.sync({ reason: "first-use" });
289
298
  await this.#watchReady;
@@ -348,30 +357,79 @@ export class QmdMemoryManager {
348
357
  if (source.kind !== "skills")
349
358
  this.#watchCollections.add(source.collection);
350
359
  this.#dirty = true;
351
- if (this.#watchTimer)
352
- clearTimeout(this.#watchTimer);
353
- this.#watchTimer = setTimeout(() => {
354
- this.#watchTimer = undefined;
355
- const collections = [...this.#watchCollections];
356
- this.#watchCollections.clear();
357
- void this.#sync({ reason: "watch" }, collections).catch(() => undefined);
358
- }, WATCH_DEBOUNCE_MS);
360
+ this.#scheduleWatchSync();
361
+ });
362
+ }
363
+ #scheduleWatchSync(retry = false) {
364
+ if (this.#watchTimer)
365
+ clearTimeout(this.#watchTimer);
366
+ this.#watchTimer = setTimeout(() => {
367
+ this.#watchTimer = undefined;
368
+ if (this.#closed)
369
+ return;
370
+ void this.#sync({ watchOnly: true }).catch(() => {
371
+ if (!retry && !this.#closed && !this.#watchTimer)
372
+ this.#scheduleWatchSync(true);
373
+ });
374
+ }, retry ? WATCH_RETRY_MS : WATCH_DEBOUNCE_MS);
375
+ }
376
+ #assertOpen() {
377
+ if (this.#closed)
378
+ throw new Error(MANAGER_CLOSED_ERROR);
379
+ }
380
+ #runFenced(run) {
381
+ if (this.#closed)
382
+ return Promise.reject(new Error(MANAGER_CLOSED_ERROR));
383
+ const promise = Promise.resolve().then(run);
384
+ const tracked = promise.then(() => undefined, () => undefined);
385
+ this.#inFlight.add(tracked);
386
+ void tracked.finally(() => {
387
+ this.#inFlight.delete(tracked);
359
388
  });
389
+ return promise;
360
390
  }
361
391
  async #getStore() {
392
+ this.#assertOpen();
362
393
  if (this.#store)
363
394
  return this.#store;
395
+ if (!this.#storePromise) {
396
+ const pending = this.#openStore();
397
+ this.#storePromise = pending;
398
+ void pending.finally(() => {
399
+ if (this.#storePromise === pending)
400
+ this.#storePromise = undefined;
401
+ }).catch(() => undefined);
402
+ }
403
+ const store = await this.#storePromise;
404
+ this.#assertOpen();
405
+ return store;
406
+ }
407
+ async #openStore() {
408
+ this.#assertOpen();
364
409
  await mkdir(dirname(this.#dbPath), { recursive: true });
410
+ this.#assertOpen();
365
411
  if (this.#storeFactory) {
366
- this.#store = await this.#storeFactory();
367
- const store = this.#store;
368
- if (store.internal) {
369
- ensureMemoryAnalysisSchema(store.internal.db);
370
- markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
412
+ const created = await this.#storeFactory();
413
+ if (this.#closed) {
414
+ await created.close().catch(() => undefined);
415
+ throw new Error(MANAGER_CLOSED_ERROR);
371
416
  }
372
- return this.#store;
417
+ try {
418
+ const store = created;
419
+ if (store.internal) {
420
+ ensureMemoryAnalysisSchema(store.internal.db);
421
+ markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
422
+ }
423
+ }
424
+ catch (error) {
425
+ await created.close().catch(() => undefined);
426
+ throw error;
427
+ }
428
+ this.#store = created;
429
+ return created;
373
430
  }
374
431
  const { createStore } = await import("@unblocklabs/qmd");
432
+ this.#assertOpen();
375
433
  const store = await createStore({
376
434
  dbPath: this.#dbPath,
377
435
  keepModelsWarm: this.#keepModelsWarm,
@@ -384,6 +442,7 @@ export class QmdMemoryManager {
384
442
  },
385
443
  });
386
444
  try {
445
+ this.#assertOpen();
387
446
  enableSecureDelete(store);
388
447
  ensureMemoryAnalysisSchema(store.internal.db);
389
448
  markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
@@ -391,20 +450,25 @@ export class QmdMemoryManager {
391
450
  const staleCollections = (await store.getStatus()).collections
392
451
  .map((collection) => collection.name)
393
452
  .filter((collection) => !configuredCollections.has(collection));
394
- const latestRunId = latestAnalysisRunId(store.internal.db);
395
- const appearsInAnalysis = store.internal.db.prepare(`
396
- SELECT 1
397
- FROM memory_analysis_memberships membership
398
- JOIN documents document ON document.hash = membership.hash
399
- WHERE membership.run_id = ? AND document.collection = ?
400
- LIMIT 1
401
- `);
402
- const prunedAnalysisInput = latestRunId !== undefined &&
403
- staleCollections.some((collection) => appearsInAnalysis.get(latestRunId, collection));
404
- const prunedDocuments = await pruneStaleCollections(store, configuredCollections);
405
- if (prunedDocuments > 0 && prunedAnalysisInput)
406
- markMemoryAnalysisStale(store.internal.db);
453
+ if (staleCollections.length > 0) {
454
+ const latestRunId = latestAnalysisRunId(store.internal.db);
455
+ let prunedAnalysisInput = false;
456
+ if (latestRunId !== undefined) {
457
+ const appearsInAnalysis = store.internal.db.prepare(`
458
+ SELECT 1
459
+ FROM memory_analysis_memberships membership
460
+ JOIN documents document ON document.hash = membership.hash
461
+ WHERE membership.run_id = ? AND document.collection = ?
462
+ LIMIT 1
463
+ `);
464
+ prunedAnalysisInput = staleCollections.some((collection) => appearsInAnalysis.get(latestRunId, collection));
465
+ }
466
+ const prunedDocuments = pruneStaleCollections(store, staleCollections);
467
+ if (prunedDocuments > 0 && prunedAnalysisInput)
468
+ markMemoryAnalysisStale(store.internal.db);
469
+ }
407
470
  await ensureSemanticChunking(store);
471
+ this.#assertOpen();
408
472
  }
409
473
  catch (error) {
410
474
  await store.close().catch(() => undefined);
@@ -505,20 +569,31 @@ export class QmdMemoryManager {
505
569
  const status = await store.getStatus();
506
570
  const collections = await store.listCollections();
507
571
  this.#files = collections.reduce((total, collection) => total + collection.active_count, 0);
508
- this.#dirty = status.needsEmbedding > 0;
572
+ this.#dirty = status.needsEmbedding > 0 || this.#watchCollections.size > 0;
509
573
  }
510
574
  sync(params) {
511
- return this.#sync(params);
575
+ return this.#sync({ force: params?.force });
512
576
  }
513
- #sync(params, affectedCollections) {
514
- const run = async () => {
515
- const store = await this.#getStore();
577
+ #sync({ force, watchOnly }) {
578
+ return this.#enqueue(async () => {
579
+ const watched = [...this.#watchCollections];
580
+ if (watchOnly && watched.length === 0)
581
+ return;
582
+ this.#watchCollections.clear();
516
583
  this.#dirty = true;
517
- const collections = affectedCollections ?? this.#indexSources.filter((source) => source.kind !== "sessions").map(source => source.collection);
518
- await this.#updateAndEmbed(store, collections.length ? collections : undefined, params?.force);
519
- await this.#refreshIndexStatus(store);
520
- };
521
- return this.#enqueue(run);
584
+ try {
585
+ const store = await this.#getStore();
586
+ const collections = watchOnly ? watched : this.#indexSources.filter((source) => source.kind !== "sessions").map(source => source.collection);
587
+ await this.#updateAndEmbed(store, collections.length ? collections : undefined, force);
588
+ await this.#refreshIndexStatus(store);
589
+ }
590
+ catch (error) {
591
+ if (!this.#closed)
592
+ for (const collection of watched)
593
+ this.#watchCollections.add(collection);
594
+ throw error;
595
+ }
596
+ });
522
597
  }
523
598
  syncSessions(force = false, onPhase) {
524
599
  return this.#enqueue(async () => {
@@ -539,6 +614,7 @@ export class QmdMemoryManager {
539
614
  });
540
615
  this.#sessionMetadata = sessionMetadataByPath(synced.manifest);
541
616
  this.#sessionManifest = synced.manifest;
617
+ this.#sessionManifestMtimeNs = await this.#manifestMtimeNs(sessions.manifestPath);
542
618
  if (synced.result.skipReason)
543
619
  return synced.result;
544
620
  const store = await this.#getStore();
@@ -637,13 +713,15 @@ export class QmdMemoryManager {
637
713
  });
638
714
  }
639
715
  async listMaintenanceTasks(params = {}) {
640
- await this.#operationChain;
641
- const tasks = this.#getCuration().listTasks(params);
642
- if (!tasks.some(task => task.type === "quality_review"))
643
- return tasks;
644
- const store = await this.#getAnalysisStore();
645
- const fingerprints = new Map();
646
- return tasks.map(task => ({ ...task, indexPresence: qualityTaskPresence(store.internal.db, task, fingerprints) }));
716
+ return this.#runFenced(async () => {
717
+ await this.#operationChain;
718
+ const tasks = this.#getCuration().listTasks(params);
719
+ if (!tasks.some(task => task.type === "quality_review"))
720
+ return tasks;
721
+ const store = await this.#getAnalysisStore();
722
+ const fingerprints = new Map();
723
+ return tasks.map(task => ({ ...task, indexPresence: qualityTaskPresence(store.internal.db, task, fingerprints) }));
724
+ });
647
725
  }
648
726
  async auditQuality(params) {
649
727
  if (this.#qualityAuditRunning)
@@ -670,6 +748,7 @@ export class QmdMemoryManager {
670
748
  return this.#getCuration().updateTask(params);
671
749
  }
672
750
  #getCuration() {
751
+ this.#assertOpen();
673
752
  this.#curation ??= new CurationStore(this.#curationPath);
674
753
  return this.#curation;
675
754
  }
@@ -773,7 +852,13 @@ export class QmdMemoryManager {
773
852
  return store;
774
853
  }
775
854
  #enqueue(run) {
776
- const result = (this.#operationChain ?? Promise.resolve()).then(run, run);
855
+ if (this.#closed)
856
+ return Promise.reject(new Error(MANAGER_CLOSED_ERROR));
857
+ const guardedRun = () => {
858
+ this.#assertOpen();
859
+ return run();
860
+ };
861
+ const result = (this.#operationChain ?? Promise.resolve()).then(guardedRun, guardedRun);
777
862
  this.#operationChain = result.then(() => undefined, () => undefined);
778
863
  return result;
779
864
  }
@@ -795,30 +880,32 @@ export class QmdMemoryManager {
795
880
  return results;
796
881
  }
797
882
  async #search(query, opts) {
798
- if (opts?.sources && !opts.sources.includes("memory"))
799
- return [];
800
- if (this.#sources.size === 0)
801
- return [];
802
- const collections = this.#collectionNames(opts?.corpora);
803
- opts?.signal?.throwIfAborted();
804
- await this.#operationChain;
805
- const sessions = this.#sessions;
806
- opts?.signal?.throwIfAborted();
807
- if (sessions && collections.includes(sessions.collection)) {
808
- await this.#refreshSessionMetadata();
809
- }
810
- const store = await this.#getStore();
811
- opts?.signal?.throwIfAborted();
812
- const allowedPaths = this.#allowedPaths(collections, opts?.sessionFilter);
813
- const hits = await store.vsearch(query, {
814
- collection: collections,
815
- limit: opts?.maxResults ?? 5,
816
- minScore: opts?.minScore ?? 0.3,
817
- allowedPaths,
818
- expand: false,
883
+ return this.#runFenced(async () => {
884
+ if (opts?.sources && !opts.sources.includes("memory"))
885
+ return [];
886
+ if (this.#sources.size === 0)
887
+ return [];
888
+ const collections = this.#collectionNames(opts?.corpora);
889
+ opts?.signal?.throwIfAborted();
890
+ await this.#operationChain;
891
+ const sessions = this.#sessions;
892
+ opts?.signal?.throwIfAborted();
893
+ if (sessions && collections.includes(sessions.collection)) {
894
+ await this.#refreshSessionMetadata();
895
+ }
896
+ const store = await this.#getStore();
897
+ opts?.signal?.throwIfAborted();
898
+ const allowedPaths = this.#allowedPaths(collections, opts?.sessionFilter);
899
+ const hits = await store.vsearch(query, {
900
+ collection: collections,
901
+ limit: opts?.maxResults ?? 5,
902
+ minScore: opts?.minScore ?? 0.3,
903
+ allowedPaths,
904
+ expand: false,
905
+ });
906
+ opts?.signal?.throwIfAborted();
907
+ return this.#renderSearchHits(hits, store, opts);
819
908
  });
820
- opts?.signal?.throwIfAborted();
821
- return this.#renderSearchHits(hits, store, opts);
822
909
  }
823
910
  /** Shared discovery: exact trained recipe, scoped before either retrieval lane. */
824
911
  async searchCandidates(queries, opts) {
@@ -949,78 +1036,83 @@ export class QmdMemoryManager {
949
1036
  return results.filter(hit => !hit.path.startsWith(EXTRACTED_PREFIX) || finalPaths.has(hit.path));
950
1037
  }
951
1038
  async searchSkills(query, minScore, limit) {
952
- if (!this.#hasSkills)
953
- return [];
954
- await this.#operationChain;
955
- const store = await this.#getStore();
956
- if (!store.internal?.llm)
957
- throw new Error("Skill Whisperer requires the QMD embedding model");
958
- const llm = store.internal.llm;
959
- const { formatDocForEmbedding, formatQueryForEmbedding } = await import("@unblocklabs/qmd");
960
- let skillIndex = this.#skillIndex;
961
- if (!skillIndex) {
962
- const pending = (async () => {
963
- // Sources iterate in configuration order, so the first skill of a name wins.
964
- const byName = new Map();
965
- for (const source of this.#sources.values()) {
966
- if (source.kind !== "skills")
967
- continue;
968
- for (const document of readSkillDocuments(source)) {
969
- const name = frontmatterValue(document.body, "name") || basename(dirname(document.path));
970
- const key = name.toLowerCase();
971
- if (byName.has(key))
1039
+ return this.#runFenced(async () => {
1040
+ if (!this.#hasSkills)
1041
+ return [];
1042
+ await this.#operationChain;
1043
+ const store = await this.#getStore();
1044
+ if (!store.internal?.llm)
1045
+ throw new Error("Skill Whisperer requires the QMD embedding model");
1046
+ const llm = store.internal.llm;
1047
+ const { formatDocForEmbedding, formatQueryForEmbedding } = await import("@unblocklabs/qmd");
1048
+ this.#assertOpen();
1049
+ let skillIndex = this.#skillIndex;
1050
+ if (!skillIndex) {
1051
+ const pending = (async () => {
1052
+ // Sources iterate in configuration order, so the first skill of a name wins.
1053
+ const byName = new Map();
1054
+ for (const source of this.#sources.values()) {
1055
+ if (source.kind !== "skills")
972
1056
  continue;
973
- byName.set(key, { name, description: frontmatterValue(document.body, "description") ?? "", path: document.path });
1057
+ for (const document of readSkillDocuments(source)) {
1058
+ const name = frontmatterValue(document.body, "name") || basename(dirname(document.path));
1059
+ const key = name.toLowerCase();
1060
+ if (byName.has(key))
1061
+ continue;
1062
+ byName.set(key, { name, description: frontmatterValue(document.body, "description") ?? "", path: document.path });
1063
+ }
974
1064
  }
975
- }
976
- const skills = [...byName.values()];
977
- const embeddings = await llm.embedBatch(skills.map((candidate) => formatDocForEmbedding(candidate.description, candidate.name, llm.embedModelName)));
978
- return skills.flatMap((candidate, index) => {
979
- const embedding = embeddings[index]?.embedding;
980
- return embedding ? [{ ...candidate, score: 0, embedding }] : [];
1065
+ const skills = [...byName.values()];
1066
+ const embeddings = await llm.embedBatch(skills.map((candidate) => formatDocForEmbedding(candidate.description, candidate.name, llm.embedModelName)));
1067
+ return skills.flatMap((candidate, index) => {
1068
+ const embedding = embeddings[index]?.embedding;
1069
+ return embedding ? [{ ...candidate, score: 0, embedding }] : [];
1070
+ });
1071
+ })();
1072
+ skillIndex = pending.catch((error) => {
1073
+ if (this.#skillIndex === skillIndex)
1074
+ this.#skillIndex = undefined;
1075
+ throw error;
981
1076
  });
982
- })();
983
- skillIndex = pending.catch((error) => {
984
- if (this.#skillIndex === skillIndex)
985
- this.#skillIndex = undefined;
986
- throw error;
987
- });
988
- this.#skillIndex = skillIndex;
989
- }
990
- const queryEmbedding = await llm.embed(formatQueryForEmbedding(query, llm.embedModelName), { isQuery: true });
991
- if (!queryEmbedding)
992
- return [];
993
- const candidates = await skillIndex;
994
- return candidates
995
- .map(({ embedding, ...candidate }) => ({
996
- ...candidate,
997
- score: cosineSimilarity(queryEmbedding.embedding, embedding),
998
- }))
999
- .filter((candidate) => candidate.score >= minScore)
1000
- .sort((left, right) => right.score - left.score)
1001
- .slice(0, limit);
1077
+ this.#skillIndex = skillIndex;
1078
+ }
1079
+ const queryEmbedding = await llm.embed(formatQueryForEmbedding(query, llm.embedModelName), { isQuery: true });
1080
+ if (!queryEmbedding)
1081
+ return [];
1082
+ const candidates = await skillIndex;
1083
+ return candidates
1084
+ .map(({ embedding, ...candidate }) => ({
1085
+ ...candidate,
1086
+ score: cosineSimilarity(queryEmbedding.embedding, embedding),
1087
+ }))
1088
+ .filter((candidate) => candidate.score >= minScore)
1089
+ .sort((left, right) => right.score - left.score)
1090
+ .slice(0, limit);
1091
+ });
1002
1092
  }
1003
1093
  async readFile(params) {
1004
- if (params.relPath.startsWith(EXTRACTED_PREFIX)) {
1005
- const record = this.#currentExtracted([params.relPath]).find(r => params.relPath === extractedUri(r));
1006
- return record ? buildReadResult({ content: `${record.text}\nObserved: ${new Date(record.observedAt).toISOString()}\nSource: ${extractedHit(record, 1).citation}`,
1007
- path: params.relPath, from: params.from, lines: params.lines }) : { status: "not_found", text: "", path: params.relPath };
1008
- }
1009
- const safe = parseSafeVirtualPath(params.relPath, this.#sources);
1010
- if (!safe || safe.source.kind === "skills") {
1011
- return { status: "not_found", text: "", path: params.relPath };
1012
- }
1013
- await this.#operationChain;
1014
- const store = await this.#getStore();
1015
- const doc = await store.get(safe.normalized, { includeBody: true });
1016
- if ("error" in doc || doc.filepath !== safe.normalized || doc.body === undefined) {
1017
- return { status: "not_found", text: "", path: params.relPath };
1018
- }
1019
- return buildReadResult({
1020
- content: doc.body,
1021
- path: safe.normalized,
1022
- from: params.from,
1023
- lines: params.lines,
1094
+ return this.#runFenced(async () => {
1095
+ if (params.relPath.startsWith(EXTRACTED_PREFIX)) {
1096
+ const record = this.#currentExtracted([params.relPath]).find(r => params.relPath === extractedUri(r));
1097
+ return record ? buildReadResult({ content: `${record.text}\nObserved: ${new Date(record.observedAt).toISOString()}\nSource: ${extractedHit(record, 1).citation}`,
1098
+ path: params.relPath, from: params.from, lines: params.lines }) : { status: "not_found", text: "", path: params.relPath };
1099
+ }
1100
+ const safe = parseSafeVirtualPath(params.relPath, this.#sources);
1101
+ if (!safe || safe.source.kind === "skills") {
1102
+ return { status: "not_found", text: "", path: params.relPath };
1103
+ }
1104
+ await this.#operationChain;
1105
+ const store = await this.#getStore();
1106
+ const doc = await store.get(safe.normalized, { includeBody: true });
1107
+ if ("error" in doc || doc.filepath !== safe.normalized || doc.body === undefined) {
1108
+ return { status: "not_found", text: "", path: params.relPath };
1109
+ }
1110
+ return buildReadResult({
1111
+ content: doc.body,
1112
+ path: safe.normalized,
1113
+ from: params.from,
1114
+ lines: params.lines,
1115
+ });
1024
1116
  });
1025
1117
  }
1026
1118
  status() {
@@ -1052,16 +1144,26 @@ export class QmdMemoryManager {
1052
1144
  };
1053
1145
  }
1054
1146
  async probeEmbeddingAvailability() {
1055
- await this.#getStore();
1056
- return { ok: true, checked: true, checkedAtMs: Date.now() };
1147
+ return this.#runFenced(async () => {
1148
+ await this.#getStore();
1149
+ return { ok: true, checked: true, checkedAtMs: Date.now() };
1150
+ });
1057
1151
  }
1058
1152
  async probeVectorAvailability() {
1059
- const status = await (await this.#getStore()).getStatus();
1060
- return status.hasVectorIndex;
1153
+ return this.#runFenced(async () => {
1154
+ const status = await (await this.#getStore()).getStatus();
1155
+ return status.hasVectorIndex;
1156
+ });
1061
1157
  }
1062
- async close() {
1158
+ close() {
1063
1159
  this.#closed = true;
1064
1160
  this.#reviewLifetime.abort();
1161
+ if (!this.#closePromise) {
1162
+ this.#closePromise = this.#close();
1163
+ }
1164
+ return this.#closePromise;
1165
+ }
1166
+ async #close() {
1065
1167
  if (this.#watchTimer)
1066
1168
  clearTimeout(this.#watchTimer);
1067
1169
  this.#watchTimer = undefined;
@@ -1070,8 +1172,13 @@ export class QmdMemoryManager {
1070
1172
  this.#watcher = undefined;
1071
1173
  this.#watchReady = undefined;
1072
1174
  await this.#operationChain?.catch(() => undefined);
1175
+ while (this.#inFlight.size > 0) {
1176
+ await Promise.all([...this.#inFlight]);
1177
+ }
1178
+ await this.#storePromise?.catch(() => undefined);
1073
1179
  await this.#store?.close();
1074
1180
  this.#store = undefined;
1181
+ this.#storePromise = undefined;
1075
1182
  this.#curation?.close();
1076
1183
  this.#curation = undefined;
1077
1184
  }
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { closeSync, constants, existsSync, fchmodSync, lstatSync, mkdirSync, openSync } from "node:fs";
2
3
  import { basename, dirname, join } from "node:path";
3
4
  import { DatabaseSync } from "node:sqlite";
@@ -25,7 +26,7 @@ function requireRegularFile(path) {
25
26
  }
26
27
  function enableWal(db) {
27
28
  // Switching journal modes can return SQLITE_BUSY without invoking busy_timeout.
28
- const deadline = Date.now() + 5000;
29
+ const deadline = Date.now() + DEFAULTS.sqlite.mainBusyTimeoutMs;
29
30
  for (;;) {
30
31
  try {
31
32
  db.exec("PRAGMA journal_mode=WAL");
@@ -51,7 +52,7 @@ export function openMemoryDatabase(path) {
51
52
  }
52
53
  const db = new DatabaseSync(path);
53
54
  try {
54
- db.exec("PRAGMA busy_timeout=5000");
55
+ db.exec(`PRAGMA busy_timeout=${DEFAULTS.sqlite.mainBusyTimeoutMs}`);
55
56
  enableWal(db);
56
57
  db.exec(`PRAGMA foreign_keys=ON;
57
58
  PRAGMA trusted_schema=OFF;