@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
@@ -22,6 +22,8 @@ export { expandSessionSearchHit } from "./memory-passage.js";
22
22
  const DEFAULT_READ_LINES = 120;
23
23
  const MAX_READ_CHARS = 12_000;
24
24
  const WATCH_DEBOUNCE_MS = 250;
25
+ const WATCH_RETRY_MS = 1_000;
26
+ const MANAGER_CLOSED_ERROR = "QmdMemoryManager is closed";
25
27
  function readSkillDocuments(source) {
26
28
  const documents = [];
27
29
  const visitedDirectories = new Set();
@@ -126,13 +128,7 @@ export function cleanupRemovedDocuments(store, changedDocuments = 0) {
126
128
  }
127
129
  return cleaned;
128
130
  }
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);
131
+ function pruneStaleCollections(store, staleCollections) {
136
132
  const deleteDocuments = store.internal.db.prepare("DELETE FROM documents WHERE collection = ?");
137
133
  const removed = store.internal.db.transaction(() => {
138
134
  let count = 0;
@@ -150,18 +146,23 @@ export function buildReadResult(params) {
150
146
  const from = Math.max(1, Math.floor(params.from ?? 1));
151
147
  const requestedLines = Math.max(1, Math.floor(params.lines ?? DEFAULT_READ_LINES));
152
148
  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");
149
+ let includedLines = 0;
150
+ let length = 0;
151
+ for (const line of selected) {
152
+ const nextLength = length + line.length + (includedLines > 0 ? 1 : 0);
153
+ if (includedLines > 0 && nextLength > MAX_READ_CHARS)
154
+ break;
155
+ length = nextLength;
156
+ includedLines += 1;
158
157
  }
159
- const hardTruncated = text.length > MAX_READ_CHARS;
160
- if (hardTruncated)
161
- text = text.slice(0, MAX_READ_CHARS);
158
+ const hardTruncated = length > MAX_READ_CHARS;
162
159
  const moreLinesRemain = from - 1 + includedLines < fileLines.length;
163
160
  const truncated = hardTruncated || moreLinesRemain || includedLines < selected.length;
164
161
  const nextFrom = hardTruncated ? undefined : truncated ? from + includedLines : undefined;
162
+ selected.length = includedLines;
163
+ let text = selected.join("\n");
164
+ if (hardTruncated)
165
+ text = text.slice(0, MAX_READ_CHARS);
165
166
  if (truncated) {
166
167
  text += `\n\n[More content available.${nextFrom ? ` Use from=${nextFrom} to continue.` : ""}]`;
167
168
  }
@@ -223,9 +224,12 @@ export class QmdMemoryManager {
223
224
  #analysisRunner;
224
225
  #sessions;
225
226
  #store;
227
+ #storePromise;
226
228
  #curation;
227
229
  #cleanupRemovedDocuments;
228
230
  #operationChain;
231
+ #inFlight = new Set();
232
+ #closePromise;
229
233
  #watcher;
230
234
  #watchReady;
231
235
  #watchTimer;
@@ -250,20 +254,22 @@ export class QmdMemoryManager {
250
254
  }
251
255
  }
252
256
  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
- };
257
+ return this.#runFenced(async () => {
258
+ await this.#operationChain;
259
+ const store = await this.#getStore();
260
+ const status = await store.getStatus();
261
+ const manifest = this.#sessions ? await readSessionManifest(this.#sessions.manifestPath) : undefined;
262
+ return {
263
+ projectorVersion: PROJECTOR_VERSION,
264
+ semanticChunkingVersion: "semanticChunkingVersion" in status ? status.semanticChunkingVersion : null,
265
+ sessionsNeedingProjection: manifest ? Object.values(manifest.sessions).filter(session => session.projectorVersion !== PROJECTOR_VERSION).length : 0,
266
+ needsEmbedding: status.needsEmbedding,
267
+ embeddingReady: status.needsEmbedding === 0 && status.hasVectorIndex,
268
+ structuralChunksOmitted: this.#structuralDiagnosticsAvailable ? this.#structuralChunksOmitted : null,
269
+ retrieval: this.#retrievalTelemetry.snapshot(),
270
+ scope: "Projection count covers previously indexed sessions; omissions count this manager lifetime; null means dependency has not reported counts.",
271
+ };
272
+ });
267
273
  }
268
274
  constructor(params) {
269
275
  this.#dbPath = params.dbPath;
@@ -281,9 +287,11 @@ export class QmdMemoryManager {
281
287
  this.#sessions = params.sessions;
282
288
  }
283
289
  async start() {
290
+ this.#assertOpen();
284
291
  if (this.#sessions) {
285
292
  await this.#reloadSessionMetadata();
286
293
  }
294
+ this.#assertOpen();
287
295
  this.#startWatcher();
288
296
  await this.sync({ reason: "first-use" });
289
297
  await this.#watchReady;
@@ -348,30 +356,79 @@ export class QmdMemoryManager {
348
356
  if (source.kind !== "skills")
349
357
  this.#watchCollections.add(source.collection);
350
358
  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);
359
+ this.#scheduleWatchSync();
360
+ });
361
+ }
362
+ #scheduleWatchSync(retry = false) {
363
+ if (this.#watchTimer)
364
+ clearTimeout(this.#watchTimer);
365
+ this.#watchTimer = setTimeout(() => {
366
+ this.#watchTimer = undefined;
367
+ if (this.#closed)
368
+ return;
369
+ void this.#sync({ watchOnly: true }).catch(() => {
370
+ if (!retry && !this.#closed && !this.#watchTimer)
371
+ this.#scheduleWatchSync(true);
372
+ });
373
+ }, retry ? WATCH_RETRY_MS : WATCH_DEBOUNCE_MS);
374
+ }
375
+ #assertOpen() {
376
+ if (this.#closed)
377
+ throw new Error(MANAGER_CLOSED_ERROR);
378
+ }
379
+ #runFenced(run) {
380
+ if (this.#closed)
381
+ return Promise.reject(new Error(MANAGER_CLOSED_ERROR));
382
+ const promise = Promise.resolve().then(run);
383
+ const tracked = promise.then(() => undefined, () => undefined);
384
+ this.#inFlight.add(tracked);
385
+ void tracked.finally(() => {
386
+ this.#inFlight.delete(tracked);
359
387
  });
388
+ return promise;
360
389
  }
361
390
  async #getStore() {
391
+ this.#assertOpen();
362
392
  if (this.#store)
363
393
  return this.#store;
394
+ if (!this.#storePromise) {
395
+ const pending = this.#openStore();
396
+ this.#storePromise = pending;
397
+ void pending.finally(() => {
398
+ if (this.#storePromise === pending)
399
+ this.#storePromise = undefined;
400
+ }).catch(() => undefined);
401
+ }
402
+ const store = await this.#storePromise;
403
+ this.#assertOpen();
404
+ return store;
405
+ }
406
+ async #openStore() {
407
+ this.#assertOpen();
364
408
  await mkdir(dirname(this.#dbPath), { recursive: true });
409
+ this.#assertOpen();
365
410
  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);
411
+ const created = await this.#storeFactory();
412
+ if (this.#closed) {
413
+ await created.close().catch(() => undefined);
414
+ throw new Error(MANAGER_CLOSED_ERROR);
371
415
  }
372
- return this.#store;
416
+ try {
417
+ const store = created;
418
+ if (store.internal) {
419
+ ensureMemoryAnalysisSchema(store.internal.db);
420
+ markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
421
+ }
422
+ }
423
+ catch (error) {
424
+ await created.close().catch(() => undefined);
425
+ throw error;
426
+ }
427
+ this.#store = created;
428
+ return created;
373
429
  }
374
430
  const { createStore } = await import("@unblocklabs/qmd");
431
+ this.#assertOpen();
375
432
  const store = await createStore({
376
433
  dbPath: this.#dbPath,
377
434
  keepModelsWarm: this.#keepModelsWarm,
@@ -384,6 +441,7 @@ export class QmdMemoryManager {
384
441
  },
385
442
  });
386
443
  try {
444
+ this.#assertOpen();
387
445
  enableSecureDelete(store);
388
446
  ensureMemoryAnalysisSchema(store.internal.db);
389
447
  markStaleForAnalysisCollectionChange(store.internal.db, this.#indexCollections, this.#hasSkills);
@@ -391,20 +449,25 @@ export class QmdMemoryManager {
391
449
  const staleCollections = (await store.getStatus()).collections
392
450
  .map((collection) => collection.name)
393
451
  .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);
452
+ if (staleCollections.length > 0) {
453
+ const latestRunId = latestAnalysisRunId(store.internal.db);
454
+ let prunedAnalysisInput = false;
455
+ if (latestRunId !== undefined) {
456
+ const appearsInAnalysis = store.internal.db.prepare(`
457
+ SELECT 1
458
+ FROM memory_analysis_memberships membership
459
+ JOIN documents document ON document.hash = membership.hash
460
+ WHERE membership.run_id = ? AND document.collection = ?
461
+ LIMIT 1
462
+ `);
463
+ prunedAnalysisInput = staleCollections.some((collection) => appearsInAnalysis.get(latestRunId, collection));
464
+ }
465
+ const prunedDocuments = pruneStaleCollections(store, staleCollections);
466
+ if (prunedDocuments > 0 && prunedAnalysisInput)
467
+ markMemoryAnalysisStale(store.internal.db);
468
+ }
407
469
  await ensureSemanticChunking(store);
470
+ this.#assertOpen();
408
471
  }
409
472
  catch (error) {
410
473
  await store.close().catch(() => undefined);
@@ -505,20 +568,31 @@ export class QmdMemoryManager {
505
568
  const status = await store.getStatus();
506
569
  const collections = await store.listCollections();
507
570
  this.#files = collections.reduce((total, collection) => total + collection.active_count, 0);
508
- this.#dirty = status.needsEmbedding > 0;
571
+ this.#dirty = status.needsEmbedding > 0 || this.#watchCollections.size > 0;
509
572
  }
510
573
  sync(params) {
511
- return this.#sync(params);
574
+ return this.#sync({ force: params?.force });
512
575
  }
513
- #sync(params, affectedCollections) {
514
- const run = async () => {
515
- const store = await this.#getStore();
576
+ #sync({ force, watchOnly }) {
577
+ return this.#enqueue(async () => {
578
+ const watched = [...this.#watchCollections];
579
+ if (watchOnly && watched.length === 0)
580
+ return;
581
+ this.#watchCollections.clear();
516
582
  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);
583
+ try {
584
+ const store = await this.#getStore();
585
+ const collections = watchOnly ? watched : this.#indexSources.filter((source) => source.kind !== "sessions").map(source => source.collection);
586
+ await this.#updateAndEmbed(store, collections.length ? collections : undefined, force);
587
+ await this.#refreshIndexStatus(store);
588
+ }
589
+ catch (error) {
590
+ if (!this.#closed)
591
+ for (const collection of watched)
592
+ this.#watchCollections.add(collection);
593
+ throw error;
594
+ }
595
+ });
522
596
  }
523
597
  syncSessions(force = false, onPhase) {
524
598
  return this.#enqueue(async () => {
@@ -539,6 +613,7 @@ export class QmdMemoryManager {
539
613
  });
540
614
  this.#sessionMetadata = sessionMetadataByPath(synced.manifest);
541
615
  this.#sessionManifest = synced.manifest;
616
+ this.#sessionManifestMtimeNs = await this.#manifestMtimeNs(sessions.manifestPath);
542
617
  if (synced.result.skipReason)
543
618
  return synced.result;
544
619
  const store = await this.#getStore();
@@ -637,13 +712,15 @@ export class QmdMemoryManager {
637
712
  });
638
713
  }
639
714
  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) }));
715
+ return this.#runFenced(async () => {
716
+ await this.#operationChain;
717
+ const tasks = this.#getCuration().listTasks(params);
718
+ if (!tasks.some(task => task.type === "quality_review"))
719
+ return tasks;
720
+ const store = await this.#getAnalysisStore();
721
+ const fingerprints = new Map();
722
+ return tasks.map(task => ({ ...task, indexPresence: qualityTaskPresence(store.internal.db, task, fingerprints) }));
723
+ });
647
724
  }
648
725
  async auditQuality(params) {
649
726
  if (this.#qualityAuditRunning)
@@ -670,6 +747,7 @@ export class QmdMemoryManager {
670
747
  return this.#getCuration().updateTask(params);
671
748
  }
672
749
  #getCuration() {
750
+ this.#assertOpen();
673
751
  this.#curation ??= new CurationStore(this.#curationPath);
674
752
  return this.#curation;
675
753
  }
@@ -773,7 +851,13 @@ export class QmdMemoryManager {
773
851
  return store;
774
852
  }
775
853
  #enqueue(run) {
776
- const result = (this.#operationChain ?? Promise.resolve()).then(run, run);
854
+ if (this.#closed)
855
+ return Promise.reject(new Error(MANAGER_CLOSED_ERROR));
856
+ const guardedRun = () => {
857
+ this.#assertOpen();
858
+ return run();
859
+ };
860
+ const result = (this.#operationChain ?? Promise.resolve()).then(guardedRun, guardedRun);
777
861
  this.#operationChain = result.then(() => undefined, () => undefined);
778
862
  return result;
779
863
  }
@@ -795,30 +879,32 @@ export class QmdMemoryManager {
795
879
  return results;
796
880
  }
797
881
  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,
882
+ return this.#runFenced(async () => {
883
+ if (opts?.sources && !opts.sources.includes("memory"))
884
+ return [];
885
+ if (this.#sources.size === 0)
886
+ return [];
887
+ const collections = this.#collectionNames(opts?.corpora);
888
+ opts?.signal?.throwIfAborted();
889
+ await this.#operationChain;
890
+ const sessions = this.#sessions;
891
+ opts?.signal?.throwIfAborted();
892
+ if (sessions && collections.includes(sessions.collection)) {
893
+ await this.#refreshSessionMetadata();
894
+ }
895
+ const store = await this.#getStore();
896
+ opts?.signal?.throwIfAborted();
897
+ const allowedPaths = this.#allowedPaths(collections, opts?.sessionFilter);
898
+ const hits = await store.vsearch(query, {
899
+ collection: collections,
900
+ limit: opts?.maxResults ?? 5,
901
+ minScore: opts?.minScore ?? 0.3,
902
+ allowedPaths,
903
+ expand: false,
904
+ });
905
+ opts?.signal?.throwIfAborted();
906
+ return this.#renderSearchHits(hits, store, opts);
819
907
  });
820
- opts?.signal?.throwIfAborted();
821
- return this.#renderSearchHits(hits, store, opts);
822
908
  }
823
909
  /** Shared discovery: exact trained recipe, scoped before either retrieval lane. */
824
910
  async searchCandidates(queries, opts) {
@@ -949,78 +1035,83 @@ export class QmdMemoryManager {
949
1035
  return results.filter(hit => !hit.path.startsWith(EXTRACTED_PREFIX) || finalPaths.has(hit.path));
950
1036
  }
951
1037
  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))
1038
+ return this.#runFenced(async () => {
1039
+ if (!this.#hasSkills)
1040
+ return [];
1041
+ await this.#operationChain;
1042
+ const store = await this.#getStore();
1043
+ if (!store.internal?.llm)
1044
+ throw new Error("Skill Whisperer requires the QMD embedding model");
1045
+ const llm = store.internal.llm;
1046
+ const { formatDocForEmbedding, formatQueryForEmbedding } = await import("@unblocklabs/qmd");
1047
+ this.#assertOpen();
1048
+ let skillIndex = this.#skillIndex;
1049
+ if (!skillIndex) {
1050
+ const pending = (async () => {
1051
+ // Sources iterate in configuration order, so the first skill of a name wins.
1052
+ const byName = new Map();
1053
+ for (const source of this.#sources.values()) {
1054
+ if (source.kind !== "skills")
972
1055
  continue;
973
- byName.set(key, { name, description: frontmatterValue(document.body, "description") ?? "", path: document.path });
1056
+ for (const document of readSkillDocuments(source)) {
1057
+ const name = frontmatterValue(document.body, "name") || basename(dirname(document.path));
1058
+ const key = name.toLowerCase();
1059
+ if (byName.has(key))
1060
+ continue;
1061
+ byName.set(key, { name, description: frontmatterValue(document.body, "description") ?? "", path: document.path });
1062
+ }
974
1063
  }
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 }] : [];
1064
+ const skills = [...byName.values()];
1065
+ const embeddings = await llm.embedBatch(skills.map((candidate) => formatDocForEmbedding(candidate.description, candidate.name, llm.embedModelName)));
1066
+ return skills.flatMap((candidate, index) => {
1067
+ const embedding = embeddings[index]?.embedding;
1068
+ return embedding ? [{ ...candidate, score: 0, embedding }] : [];
1069
+ });
1070
+ })();
1071
+ skillIndex = pending.catch((error) => {
1072
+ if (this.#skillIndex === skillIndex)
1073
+ this.#skillIndex = undefined;
1074
+ throw error;
981
1075
  });
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);
1076
+ this.#skillIndex = skillIndex;
1077
+ }
1078
+ const queryEmbedding = await llm.embed(formatQueryForEmbedding(query, llm.embedModelName), { isQuery: true });
1079
+ if (!queryEmbedding)
1080
+ return [];
1081
+ const candidates = await skillIndex;
1082
+ return candidates
1083
+ .map(({ embedding, ...candidate }) => ({
1084
+ ...candidate,
1085
+ score: cosineSimilarity(queryEmbedding.embedding, embedding),
1086
+ }))
1087
+ .filter((candidate) => candidate.score >= minScore)
1088
+ .sort((left, right) => right.score - left.score)
1089
+ .slice(0, limit);
1090
+ });
1002
1091
  }
1003
1092
  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,
1093
+ return this.#runFenced(async () => {
1094
+ if (params.relPath.startsWith(EXTRACTED_PREFIX)) {
1095
+ const record = this.#currentExtracted([params.relPath]).find(r => params.relPath === extractedUri(r));
1096
+ return record ? buildReadResult({ content: `${record.text}\nObserved: ${new Date(record.observedAt).toISOString()}\nSource: ${extractedHit(record, 1).citation}`,
1097
+ path: params.relPath, from: params.from, lines: params.lines }) : { status: "not_found", text: "", path: params.relPath };
1098
+ }
1099
+ const safe = parseSafeVirtualPath(params.relPath, this.#sources);
1100
+ if (!safe || safe.source.kind === "skills") {
1101
+ return { status: "not_found", text: "", path: params.relPath };
1102
+ }
1103
+ await this.#operationChain;
1104
+ const store = await this.#getStore();
1105
+ const doc = await store.get(safe.normalized, { includeBody: true });
1106
+ if ("error" in doc || doc.filepath !== safe.normalized || doc.body === undefined) {
1107
+ return { status: "not_found", text: "", path: params.relPath };
1108
+ }
1109
+ return buildReadResult({
1110
+ content: doc.body,
1111
+ path: safe.normalized,
1112
+ from: params.from,
1113
+ lines: params.lines,
1114
+ });
1024
1115
  });
1025
1116
  }
1026
1117
  status() {
@@ -1052,16 +1143,26 @@ export class QmdMemoryManager {
1052
1143
  };
1053
1144
  }
1054
1145
  async probeEmbeddingAvailability() {
1055
- await this.#getStore();
1056
- return { ok: true, checked: true, checkedAtMs: Date.now() };
1146
+ return this.#runFenced(async () => {
1147
+ await this.#getStore();
1148
+ return { ok: true, checked: true, checkedAtMs: Date.now() };
1149
+ });
1057
1150
  }
1058
1151
  async probeVectorAvailability() {
1059
- const status = await (await this.#getStore()).getStatus();
1060
- return status.hasVectorIndex;
1152
+ return this.#runFenced(async () => {
1153
+ const status = await (await this.#getStore()).getStatus();
1154
+ return status.hasVectorIndex;
1155
+ });
1061
1156
  }
1062
- async close() {
1157
+ close() {
1063
1158
  this.#closed = true;
1064
1159
  this.#reviewLifetime.abort();
1160
+ if (!this.#closePromise) {
1161
+ this.#closePromise = this.#close();
1162
+ }
1163
+ return this.#closePromise;
1164
+ }
1165
+ async #close() {
1065
1166
  if (this.#watchTimer)
1066
1167
  clearTimeout(this.#watchTimer);
1067
1168
  this.#watchTimer = undefined;
@@ -1070,8 +1171,13 @@ export class QmdMemoryManager {
1070
1171
  this.#watcher = undefined;
1071
1172
  this.#watchReady = undefined;
1072
1173
  await this.#operationChain?.catch(() => undefined);
1174
+ while (this.#inFlight.size > 0) {
1175
+ await Promise.all([...this.#inFlight]);
1176
+ }
1177
+ await this.#storePromise?.catch(() => undefined);
1073
1178
  await this.#store?.close();
1074
1179
  this.#store = undefined;
1180
+ this.#storePromise = undefined;
1075
1181
  this.#curation?.close();
1076
1182
  this.#curation = undefined;
1077
1183
  }
@@ -14,18 +14,20 @@ export type MemorySearchObservation = RetrievalTimings & {
14
14
  requestsFailed: number;
15
15
  };
16
16
  export type MemoryRanking = {
17
- rankingMode: "typesafe_usefulness" | "retrieval";
17
+ rankingMode: "decision" | "retrieval";
18
18
  fallbackReason?: "key_unavailable" | "all_judgments_failed";
19
19
  };
20
20
  /** Both entry points use the same complete passages and independent usefulness judgments. */
21
21
  export declare function searchMemory(manager: MemoryCandidateManager, queries: QueryPair, options: CorpusSearchOptions & {
22
22
  apiKey?: string;
23
+ endpoint?: string;
24
+ model?: string;
23
25
  timeoutMs: number;
24
26
  conversation: QueryConversation;
25
27
  asOf?: string;
26
28
  /** Only explicit, agent-requested search opts in. Automatic injection stays strict. */
27
29
  allowRetrievalFallback?: boolean;
28
- /** Cap top retrieval-ranked candidates sent to TypeSafe (after dedup and cooldown filtering). */
30
+ /** Cap top retrieval-ranked candidates sent to the decision endpoint (after dedup and cooldown filtering). */
29
31
  maxJudgeCandidates?: number;
30
32
  minUsefulness?: number;
31
33
  excludedPassages?: ReadonlyMap<string, number>;