@unblocklabs/unblock-memory 0.12.2 → 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 (123) 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 +189 -127
  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 +423 -204
  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/query-generator.d.ts +1 -1
  68. package/dist/src/query-generator.js +15 -8
  69. package/dist/src/response-audit.d.ts +1 -1
  70. package/dist/src/response-audit.js +76 -43
  71. package/dist/src/response-episodes.d.ts +1 -1
  72. package/dist/src/response-episodes.js +12 -17
  73. package/dist/src/response-judge.d.ts +151 -145
  74. package/dist/src/response-judge.js +535 -204
  75. package/dist/src/response-reviews.d.ts +29 -1
  76. package/dist/src/response-reviews.js +110 -13
  77. package/dist/src/response-runtime.js +8 -8
  78. package/dist/src/response-stages.d.ts +50 -53
  79. package/dist/src/response-stages.js +10 -4
  80. package/dist/src/response-store.d.ts +7 -6
  81. package/dist/src/response-store.js +332 -210
  82. package/dist/src/response-text.d.ts +2 -0
  83. package/dist/src/response-text.js +182 -36
  84. package/dist/src/review-tools.d.ts +8 -2
  85. package/dist/src/review-tools.js +18 -18
  86. package/dist/src/runtime.d.ts +7 -4
  87. package/dist/src/runtime.js +624 -98
  88. package/dist/src/safety-whisperer.d.ts +2 -2
  89. package/dist/src/safety-whisperer.js +88 -71
  90. package/dist/src/session-sync.d.ts +3 -1
  91. package/dist/src/session-sync.js +200 -95
  92. package/dist/src/skill-whisperer.d.ts +1 -1
  93. package/dist/src/skill-whisperer.js +52 -30
  94. package/dist/src/training-gate.d.ts +8 -21
  95. package/dist/src/training-gate.js +32 -35
  96. package/dist/src/training-judge.d.ts +9 -16
  97. package/dist/src/training-judge.js +5 -5
  98. package/dist/src/training-queries.d.ts +13 -8
  99. package/dist/src/training-queries.js +370 -228
  100. package/dist/src/training-retrieval.d.ts +14 -24
  101. package/dist/src/training-retrieval.js +182 -136
  102. package/dist/src/training-runtime.d.ts +3 -0
  103. package/dist/src/training-runtime.js +76 -18
  104. package/dist/src/training-store.d.ts +18 -3
  105. package/dist/src/training-store.js +138 -50
  106. package/dist/src/training.js +8 -11
  107. package/dist/src/whisperer-context.d.ts +14 -0
  108. package/dist/src/whisperer-context.js +22 -1
  109. package/docs/configuration.md +76 -63
  110. package/docs/extraction.md +9 -7
  111. package/docs/memory-training.md +7 -6
  112. package/docs/people-learning.md +2 -2
  113. package/docs/peoplesql.md +6 -6
  114. package/docs/response-audit.md +10 -8
  115. package/docs/retrieval.md +40 -37
  116. package/openclaw.plugin.json +40 -26
  117. package/package.json +3 -2
  118. package/skills/memory-curator/SKILL.md +1 -1
  119. package/skills/people-whisperer/SKILL.md +1 -1
  120. package/dist/src/typesafe-client.d.ts +0 -30
  121. package/dist/src/typesafe-client.js +0 -92
  122. package/dist/src/typesafe-review.js +0 -154
  123. package/dist/src/typesafe.js +0 -147
@@ -128,6 +128,7 @@ function readSnapshot(params) {
128
128
  GROUP BY window.session_id
129
129
  ORDER BY window.created_at, window.session_id
130
130
  `).all(...params.chatTypes);
131
+ const fingerprints = new Map();
131
132
  const events = new Map();
132
133
  const changed = new Set();
133
134
  const unavailable = new Set();
@@ -136,19 +137,25 @@ function readSnapshot(params) {
136
137
  const previous = params.previousManifest.sessions[window.sessionId];
137
138
  const documentPath = sessionDocumentPath(metadata);
138
139
  const sourceFingerprint = JSON.stringify(window);
139
- const unchanged = !window.cold && !params.force &&
140
- (previous ? previous.sourceFingerprint === sourceFingerprint &&
141
- previous.projectorVersion === PROJECTOR_VERSION &&
142
- previous.documentPath === documentPath &&
143
- existsSync(projectionPath(params.outputDir, documentPath)) :
144
- params.previousManifest.ignoredSessions?.[window.sessionId] === sourceFingerprint);
140
+ fingerprints.set(window.sessionId, sourceFingerprint);
141
+ const entryProjectionKey = previous?.projectionKey ?? params.previousManifest.projectionKey;
142
+ const previouslyFailed = params.previousManifest.failedSessions?.[window.sessionId] !== undefined;
143
+ const unchanged = !window.cold && !params.force && !previouslyFailed &&
144
+ (previous
145
+ ? entryProjectionKey === params.currentProjectionKey &&
146
+ previous.sourceFingerprint === sourceFingerprint &&
147
+ previous.projectorVersion === PROJECTOR_VERSION &&
148
+ previous.documentPath === documentPath &&
149
+ existsSync(projectionPath(params.outputDir, documentPath))
150
+ : params.previousManifest.projectionKey === params.currentProjectionKey &&
151
+ params.previousManifest.ignoredSessions?.[window.sessionId] === sourceFingerprint);
145
152
  if (!unchanged) {
146
153
  changed.add(window.sessionId);
147
154
  if (!params.metadataOnly) {
148
155
  try {
149
156
  const snapshot = transcripts.read(window.sessionId);
150
157
  if (snapshot.kind === "ready")
151
- events.set(window.sessionId, snapshot.rows.map(row => ({ ...row, sessionId: window.sessionId })));
158
+ events.set(window.sessionId, snapshot.rows);
152
159
  else
153
160
  unavailable.add(window.sessionId);
154
161
  }
@@ -159,7 +166,7 @@ function readSnapshot(params) {
159
166
  }
160
167
  }
161
168
  db.exec("COMMIT");
162
- return { windows, events, changed, unavailable };
169
+ return { windows, fingerprints, events, changed, unavailable };
163
170
  }
164
171
  catch (error) {
165
172
  try {
@@ -174,10 +181,18 @@ function readSnapshot(params) {
174
181
  }
175
182
  export async function unchangedSessionSync(params, indexPath) {
176
183
  const manifest = await readSessionManifest(params.manifestPath);
177
- if (!manifest.lastSuccessfulSyncAt || manifest.projectionKey !== projectionKey(params) ||
178
- !manifest.indexSignature || manifest.indexSignature !== sessionIndexSignature(indexPath))
184
+ const currentProjectionKey = projectionKey(params);
185
+ if (!manifest.lastSuccessfulSyncAt || manifest.projectionKey !== currentProjectionKey ||
186
+ !manifest.indexSignature || manifest.indexSignature !== sessionIndexSignature(indexPath) ||
187
+ Object.keys(manifest.failedSessions ?? {}).length > 0)
179
188
  return;
180
- const snapshot = readSnapshot({ ...params, previousManifest: manifest, force: false, metadataOnly: true });
189
+ const snapshot = readSnapshot({
190
+ ...params,
191
+ previousManifest: manifest,
192
+ currentProjectionKey,
193
+ force: false,
194
+ metadataOnly: true,
195
+ });
181
196
  const ids = new Set(snapshot.windows.map(window => window.sessionId));
182
197
  if (snapshot.changed.size || Object.keys(manifest.sessions).some(id => !ids.has(id)) ||
183
198
  Object.keys(manifest.ignoredSessions ?? {}).some(id => !ids.has(id)))
@@ -207,7 +222,27 @@ export async function readSessionManifest(path) {
207
222
  typeof manifest.sessions !== "object" || Array.isArray(manifest.sessions)) {
208
223
  throw new Error(`unsupported unblock-memory session manifest: ${path}`);
209
224
  }
210
- return manifest;
225
+ const parsed = { ...manifest };
226
+ if (manifest.failedSessions !== undefined) {
227
+ if (!manifest.failedSessions || typeof manifest.failedSessions !== "object" || Array.isArray(manifest.failedSessions)) {
228
+ delete parsed.failedSessions;
229
+ }
230
+ else {
231
+ const validFailed = {};
232
+ for (const [sessionId, fingerprint] of Object.entries(manifest.failedSessions)) {
233
+ if (sessionId.length > 0 && typeof fingerprint === "string") {
234
+ validFailed[sessionId] = fingerprint;
235
+ }
236
+ }
237
+ if (Object.keys(validFailed).length > 0) {
238
+ parsed.failedSessions = validFailed;
239
+ }
240
+ else {
241
+ delete parsed.failedSessions;
242
+ }
243
+ }
244
+ }
245
+ return parsed;
211
246
  }
212
247
  async function atomicWrite(path, content, mode) {
213
248
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
@@ -246,99 +281,159 @@ export function sessionMetadataByPath(manifest) {
246
281
  startedAt: session.startedAt,
247
282
  }]));
248
283
  }
284
+ function retainPreviousSession(previous, previousManifestProjectionKey) {
285
+ if (!previous)
286
+ return undefined;
287
+ if (previous.projectionKey !== undefined || previousManifestProjectionKey === undefined) {
288
+ return previous;
289
+ }
290
+ return { ...previous, projectionKey: previousManifestProjectionKey };
291
+ }
292
+ async function syncWindow(params) {
293
+ const { window, sourceFingerprint, previous, events } = params;
294
+ const metadata = windowMetadata(window);
295
+ const documentPath = sessionDocumentPath(metadata);
296
+ const fail = () => ({
297
+ kind: "failed",
298
+ session: retainPreviousSession(previous, params.previousManifestProjectionKey),
299
+ });
300
+ if (params.unavailable)
301
+ return fail();
302
+ if (events === undefined) {
303
+ return previous
304
+ ? { kind: "unchanged", session: previous }
305
+ : { kind: "unchanged", ignoredFingerprint: sourceFingerprint };
306
+ }
307
+ if (events.length > 0 && (!window.sourceGeneration || window.maxSeq === null)) {
308
+ return fail();
309
+ }
310
+ let projection;
311
+ try {
312
+ const input = {
313
+ ...metadata,
314
+ label: window.label ?? undefined,
315
+ agentName: params.agentName,
316
+ timezone: params.timezone,
317
+ events,
318
+ diagnostics: params.diagnostics,
319
+ };
320
+ projection = projectSessionDocument(input);
321
+ }
322
+ catch {
323
+ return fail();
324
+ }
325
+ if (!projection) {
326
+ if (previous) {
327
+ await remove(projectionPath(params.outputDir, previous.documentPath));
328
+ }
329
+ return {
330
+ kind: "skipped",
331
+ ignoredFingerprint: sourceFingerprint,
332
+ removedPrevious: Boolean(previous),
333
+ };
334
+ }
335
+ const { content, messages } = projection;
336
+ const target = projectionPath(params.outputDir, documentPath);
337
+ const hash = projectionHash(content);
338
+ const contentChanged = params.force || previous?.projectorVersion !== PROJECTOR_VERSION ||
339
+ previous.projectionHash !== hash || previous.documentPath !== documentPath || !existsSync(target);
340
+ if (contentChanged) {
341
+ await atomicWrite(target, content, 0o600);
342
+ await utimes(target, new Date(), new Date(metadata.startedAt));
343
+ }
344
+ if (previous?.documentPath && previous.documentPath !== documentPath) {
345
+ await remove(projectionPath(params.outputDir, previous.documentPath));
346
+ }
347
+ const session = {
348
+ ...metadata,
349
+ sourceGeneration: window.sourceGeneration,
350
+ maxSeq: window.maxSeq,
351
+ activeEventCount: window.activeEventCount,
352
+ sizeBytes: Buffer.byteLength(content),
353
+ projectionHash: hash,
354
+ documentPath,
355
+ projectorVersion: PROJECTOR_VERSION,
356
+ projectionKey: params.currentProjectionKey,
357
+ sourceFingerprint,
358
+ messages,
359
+ };
360
+ return contentChanged ? { kind: "updated", session } : { kind: "unchanged", session };
361
+ }
362
+ async function resolveIndexSignature(params) {
363
+ // Never certify an index mutation that happened during a failed, skipped, or readiness check.
364
+ if (params.failed > 0)
365
+ return undefined;
366
+ if (!params.needsIndex)
367
+ return params.previousIndexSignature;
368
+ if (!params.indexed || !params.indexPath)
369
+ return undefined;
370
+ // Timing point 2: capture index signature after indexing, before readiness check.
371
+ const signatureBeforeReadiness = sessionIndexSignature(params.indexPath);
372
+ if (!signatureBeforeReadiness)
373
+ return undefined;
374
+ const ready = await params.indexReady?.() ?? false;
375
+ if (!ready)
376
+ return undefined;
377
+ // Timing point 3: verify index did not mutate during readiness validation.
378
+ if (signatureBeforeReadiness !== sessionIndexSignature(params.indexPath))
379
+ return undefined;
380
+ return signatureBeforeReadiness;
381
+ }
249
382
  export async function syncSessionProjections(params) {
250
383
  const previousManifest = await readSessionManifest(params.manifestPath);
384
+ const currentProjectionKey = projectionKey(params);
251
385
  const snapshot = readSnapshot({
252
386
  ...params,
253
- force: params.force === true || previousManifest.projectionKey !== projectionKey(params),
387
+ force: params.force === true,
254
388
  previousManifest,
389
+ currentProjectionKey,
255
390
  });
256
391
  const sessions = {};
257
392
  const ignoredSessions = {};
393
+ const failedSessions = {};
258
394
  const counts = { unchanged: 0, updated: 0, removed: 0, skipped: 0, failed: 0 };
259
395
  const diagnostics = { internalMessagesCleaned: 0, attachmentsCleaned: 0, attachmentBudgetSkipped: 0 };
260
396
  await mkdir(params.outputDir, { recursive: true, mode: 0o700 });
261
397
  await chmod(params.outputDir, 0o700);
262
398
  for (const window of snapshot.windows) {
263
- const previous = previousManifest.sessions[window.sessionId];
264
- const events = snapshot.events.get(window.sessionId);
265
- const metadata = windowMetadata(window);
266
- const documentPath = sessionDocumentPath(metadata);
267
- if (snapshot.unavailable.has(window.sessionId)) {
399
+ const outcome = await syncWindow({
400
+ window,
401
+ sourceFingerprint: snapshot.fingerprints.get(window.sessionId),
402
+ previous: previousManifest.sessions[window.sessionId],
403
+ events: snapshot.events.get(window.sessionId),
404
+ unavailable: snapshot.unavailable.has(window.sessionId),
405
+ force: params.force === true,
406
+ outputDir: params.outputDir,
407
+ agentName: params.agentName,
408
+ timezone: params.timezone,
409
+ currentProjectionKey,
410
+ previousManifestProjectionKey: previousManifest.projectionKey,
411
+ diagnostics,
412
+ });
413
+ if (outcome.kind === "failed") {
268
414
  counts.failed += 1;
269
- if (previous)
270
- sessions[window.sessionId] = previous;
271
- continue;
415
+ failedSessions[window.sessionId] = snapshot.fingerprints.get(window.sessionId);
416
+ if (outcome.session)
417
+ sessions[window.sessionId] = outcome.session;
272
418
  }
273
- if (events === undefined) {
274
- if (previous)
275
- sessions[window.sessionId] = previous;
276
- else
277
- ignoredSessions[window.sessionId] = JSON.stringify(window);
419
+ else if (outcome.kind === "unchanged") {
278
420
  counts.unchanged += 1;
279
- continue;
280
- }
281
- if (events.length > 0 && (!window.sourceGeneration || window.maxSeq === null)) {
282
- counts.failed += 1;
283
- if (previous)
284
- sessions[window.sessionId] = previous;
285
- continue;
286
- }
287
- let projection;
288
- try {
289
- const input = {
290
- ...metadata,
291
- label: window.label ?? undefined,
292
- agentName: params.agentName,
293
- timezone: params.timezone,
294
- events,
295
- diagnostics,
296
- };
297
- projection = projectSessionDocument(input);
298
- }
299
- catch {
300
- counts.failed += 1;
301
- if (previous)
302
- sessions[window.sessionId] = previous;
303
- continue;
421
+ if (outcome.session)
422
+ sessions[window.sessionId] = outcome.session;
423
+ else if (outcome.ignoredFingerprint !== undefined) {
424
+ ignoredSessions[window.sessionId] = outcome.ignoredFingerprint;
425
+ }
304
426
  }
305
- if (!projection) {
306
- ignoredSessions[window.sessionId] = JSON.stringify(window);
427
+ else if (outcome.kind === "skipped") {
307
428
  counts.skipped += 1;
308
- if (previous) {
309
- await remove(projectionPath(params.outputDir, previous.documentPath));
429
+ ignoredSessions[window.sessionId] = outcome.ignoredFingerprint;
430
+ if (outcome.removedPrevious)
310
431
  counts.removed += 1;
311
- }
312
- continue;
313
- }
314
- const { content, messages } = projection;
315
- const target = projectionPath(params.outputDir, documentPath);
316
- const hash = projectionHash(content);
317
- const contentChanged = params.force === true || previous?.projectorVersion !== PROJECTOR_VERSION ||
318
- previous.projectionHash !== hash || previous.documentPath !== documentPath || !existsSync(target);
319
- if (contentChanged) {
320
- await atomicWrite(target, content, 0o600);
321
- await utimes(target, new Date(), new Date(metadata.startedAt));
322
432
  }
323
- if (previous?.documentPath && previous.documentPath !== documentPath) {
324
- await remove(projectionPath(params.outputDir, previous.documentPath));
325
- }
326
- sessions[window.sessionId] = {
327
- ...metadata,
328
- sourceGeneration: window.sourceGeneration,
329
- maxSeq: window.maxSeq,
330
- activeEventCount: window.activeEventCount,
331
- sizeBytes: Buffer.byteLength(content),
332
- projectionHash: hash,
333
- documentPath,
334
- projectorVersion: PROJECTOR_VERSION,
335
- sourceFingerprint: JSON.stringify(window),
336
- messages,
337
- };
338
- if (contentChanged)
433
+ else {
339
434
  counts.updated += 1;
340
- else
341
- counts.unchanged += 1;
435
+ sessions[window.sessionId] = outcome.session;
436
+ }
342
437
  }
343
438
  const liveIds = new Set(snapshot.windows.map(window => window.sessionId));
344
439
  for (const [sessionId, session] of Object.entries(previousManifest.sessions)) {
@@ -347,25 +442,35 @@ export async function syncSessionProjections(params) {
347
442
  await remove(projectionPath(params.outputDir, session.documentPath));
348
443
  counts.removed += 1;
349
444
  }
445
+ // Timing point 1: verify index signature before running QMD index/embed.
350
446
  const needsIndex = params.force === true || counts.updated > 0 || counts.removed > 0 ||
351
- previousManifest.projectionKey !== projectionKey(params) ||
447
+ previousManifest.projectionKey !== currentProjectionKey ||
352
448
  !previousManifest.indexSignature || !params.indexPath ||
353
449
  previousManifest.indexSignature !== sessionIndexSignature(params.indexPath);
354
450
  const embedded = needsIndex ? await params.index?.() ?? 0 : 0;
355
- const lastSuccessfulSyncAt = Date.now();
451
+ const checkedAt = Date.now();
356
452
  const indexed = needsIndex && params.index !== undefined;
357
- const signature = params.indexPath ? sessionIndexSignature(params.indexPath) : undefined;
358
- const indexReady = indexed && (await params.indexReady?.() ?? false);
359
- const lastIndexedAt = indexed ? lastSuccessfulSyncAt : previousManifest.lastIndexedAt;
453
+ const indexSignature = await resolveIndexSignature({
454
+ failed: counts.failed,
455
+ needsIndex,
456
+ indexed,
457
+ indexPath: params.indexPath,
458
+ previousIndexSignature: previousManifest.indexSignature,
459
+ indexReady: params.indexReady,
460
+ });
461
+ const lastSuccessfulSyncAt = counts.failed === 0 ? checkedAt : previousManifest.lastSuccessfulSyncAt;
462
+ const lastIndexedAt = indexed ? checkedAt : previousManifest.lastIndexedAt;
463
+ const manifestProjectionKey = counts.failed === 0
464
+ ? currentProjectionKey
465
+ : previousManifest.projectionKey;
360
466
  const manifest = {
361
467
  version: MANIFEST_VERSION,
362
468
  lastSuccessfulSyncAt,
363
469
  lastIndexedAt,
364
- projectionKey: projectionKey(params),
365
- // Never certify an index mutation that happened during a skipped run or readiness check.
366
- indexSignature: counts.failed > 0 ? undefined : !needsIndex ? previousManifest.indexSignature :
367
- indexReady && params.indexPath && signature === sessionIndexSignature(params.indexPath) ? signature : undefined,
470
+ projectionKey: manifestProjectionKey,
471
+ indexSignature,
368
472
  ignoredSessions,
473
+ ...(Object.keys(failedSessions).length ? { failedSessions } : {}),
369
474
  sessions,
370
475
  };
371
476
  await atomicWrite(params.manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 0o600);
@@ -374,8 +479,8 @@ export async function syncSessionProjections(params) {
374
479
  scanned: snapshot.windows.length,
375
480
  ...counts,
376
481
  embedded,
377
- lastSuccessfulSyncAt,
378
- lastCheckedAt: lastSuccessfulSyncAt,
482
+ ...(lastSuccessfulSyncAt !== undefined ? { lastSuccessfulSyncAt } : {}),
483
+ lastCheckedAt: checkedAt,
379
484
  lastIndexedAt,
380
485
  ...(!needsIndex ? { skipReason: "no_indexable_changes" } : {}),
381
486
  diagnostics,
@@ -13,5 +13,5 @@ type SkillWhispererRuntime = {
13
13
  agentId: string;
14
14
  }, path: string): string | undefined;
15
15
  };
16
- export declare function registerSkillWhisperer(api: OpenClawPluginApi, runtime: SkillWhispererRuntime, config: UnblockMemoryConfig["skillWhisperer"], typesafe: UnblockMemoryConfig["typesafe"], diagnostics?: WhispererDiagnostics): Parameters<typeof api.on<"before_prompt_build">>[1] | undefined;
16
+ export declare function registerSkillWhisperer(api: OpenClawPluginApi, runtime: SkillWhispererRuntime, config: UnblockMemoryConfig["skillWhisperer"], decisionModel: UnblockMemoryConfig["decisionModel"], diagnostics?: WhispererDiagnostics): Parameters<typeof api.on<"before_prompt_build">>[1] | undefined;
17
17
  export {};
@@ -1,16 +1,17 @@
1
1
  import { basename } from "node:path";
2
- import { selectTypeSafeSkill } from "./typesafe.js";
3
- import { isTypeSafeTimeout, resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
4
- import { buildSkillWhispererQuery, recentSkillMessages } from "./whisperer-context.js";
2
+ import { selectSkill } from "./decision-ranking.js";
3
+ import { isDecisionTimeout, resolveDecisionCredential, DecisionRequestError } from "./decision-client.js";
4
+ import { buildSkillWhispererQuery, MAX_SKILL_QUERY_CHARS, recentSkillMessages } from "./whisperer-context.js";
5
5
  import { abortable } from "./abortable.js";
6
6
  import { isRecord } from "./guards.js";
7
7
  const CANDIDATE_LIMIT = 10;
8
- const MAX_QUERY_CHARS = 12_000;
9
- const TYPESAFE_CANDIDATE_LIMIT = 3;
8
+ const JUDGE_CANDIDATE_LIMIT = 3;
9
+ const MAX_SESSIONS = 1_000;
10
+ const MAX_SEEN_RUNS = 64;
10
11
  export const SKILL_WHISPERER_TIMEOUT_MS = 3000;
11
- function typeSafeConversation(prompt, messages) {
12
- const currentRequest = prompt.trim().slice(-MAX_QUERY_CHARS);
13
- let remaining = MAX_QUERY_CHARS - currentRequest.length;
12
+ function decisionConversation(prompt, messages) {
13
+ const currentRequest = prompt.trim().slice(-MAX_SKILL_QUERY_CHARS);
14
+ let remaining = MAX_SKILL_QUERY_CHARS - currentRequest.length;
14
15
  const history = [];
15
16
  for (let i = messages.length - 1; i >= 0; i--) {
16
17
  if (remaining <= 0)
@@ -32,16 +33,25 @@ function readPath(params) {
32
33
  function sessionScope(context) {
33
34
  return context.sessionId || context.sessionKey;
34
35
  }
35
- export function registerSkillWhisperer(api, runtime, config, typesafe, diagnostics) {
36
+ export function registerSkillWhisperer(api, runtime, config, decisionModel, diagnostics) {
36
37
  if (!config.enabled)
37
38
  return;
38
39
  const sessions = new Map();
40
+ const touchSession = (scope, state) => {
41
+ sessions.delete(scope);
42
+ sessions.set(scope, state);
43
+ };
39
44
  const stateFor = (scope) => {
40
45
  let state = sessions.get(scope);
41
46
  if (!state) {
42
- state = { turn: 0, skills: new Map() };
43
- sessions.set(scope, state);
47
+ if (sessions.size >= MAX_SESSIONS) {
48
+ const oldest = sessions.keys().next().value;
49
+ sessions.get(oldest)?.controller?.abort();
50
+ sessions.delete(oldest);
51
+ }
52
+ state = { turn: 0, seenRuns: new Set(), skills: new Map() };
44
53
  }
54
+ touchSession(scope, state);
45
55
  return state;
46
56
  };
47
57
  const active = (agentId) => ({ cfg: api.config, agentId });
@@ -53,7 +63,15 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
53
63
  const state = stateFor(scope);
54
64
  if (state.lastRunId === runId)
55
65
  return state.result;
66
+ // Ignore delayed prompt rebuilds for already-superseded runs so they never abort or advance the latest run.
67
+ if (state.seenRuns.has(runId))
68
+ return undefined;
56
69
  state.controller?.abort();
70
+ if (state.lastRunId) {
71
+ state.seenRuns.add(state.lastRunId);
72
+ if (state.seenRuns.size > MAX_SEEN_RUNS)
73
+ state.seenRuns.delete(state.seenRuns.values().next().value);
74
+ }
57
75
  const controller = new AbortController();
58
76
  state.controller = controller;
59
77
  const { signal } = controller;
@@ -64,17 +82,16 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
64
82
  const run = async () => {
65
83
  try {
66
84
  const runtimeParams = active(agentId);
67
- const apiKey = await abortable(resolveTypeSafeApiKey(typesafe), signal);
85
+ const apiKey = await abortable(resolveDecisionCredential(decisionModel), signal);
68
86
  if (!apiKey)
69
- diagnostics?.record(agentId, "skill", typesafe.enabled ? "missing_key" : "typesafe_disabled");
87
+ diagnostics?.record(agentId, "skill", decisionModel.enabled ? "missing_key" : "decision_disabled");
70
88
  const recentMessages = recentSkillMessages(event.messages, config.historyMessages);
71
89
  const candidates = await abortable(runtime.searchSkills(runtimeParams, buildSkillWhispererQuery(event.prompt, recentMessages), apiKey ? -1 : config.minScore, CANDIDATE_LIMIT), signal);
72
90
  const resolvedCandidates = candidates.flatMap((candidate) => {
73
91
  const canonicalPath = runtime.resolveSkillPath(runtimeParams, candidate.path);
74
92
  return canonicalPath ? [{ candidate, canonicalPath }] : [];
75
93
  });
76
- let resolved = resolvedCandidates[0];
77
- if (!resolved) {
94
+ if (!resolvedCandidates.length) {
78
95
  diagnostics?.record(agentId, "skill", "no_candidates");
79
96
  return;
80
97
  }
@@ -82,23 +99,26 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
82
99
  const previous = state.skills.get(path);
83
100
  return state.turn - Math.max(previous?.suggested ?? -Infinity, previous?.opened ?? -Infinity) <= config.cooldownTurns;
84
101
  };
102
+ // Exclude cooling skills before choosing a winner so a cooling top hit never suppresses an eligible alternative.
103
+ const eligibleCandidates = resolvedCandidates.filter(({ canonicalPath }) => !cooling(canonicalPath));
104
+ if (!eligibleCandidates.length) {
105
+ diagnostics?.record(agentId, "skill", "cooldown");
106
+ return;
107
+ }
108
+ let resolved = eligibleCandidates[0];
85
109
  if (apiKey) {
86
- const shortlist = resolvedCandidates.slice(0, TYPESAFE_CANDIDATE_LIMIT);
87
- if (shortlist.every(({ canonicalPath }) => cooling(canonicalPath))) {
88
- diagnostics?.record(agentId, "skill", "cooldown");
89
- return;
90
- }
91
- const selectedIndex = await abortable(selectTypeSafeSkill({
92
- apiKey, timeoutMs: typesafe.timeoutMs, signal,
93
- ...typeSafeConversation(event.prompt, recentMessages),
110
+ const shortlist = eligibleCandidates.slice(0, JUDGE_CANDIDATE_LIMIT);
111
+ const selectedIndex = await abortable(selectSkill({
112
+ apiKey, endpoint: decisionModel.endpoint, model: decisionModel.model, timeoutMs: decisionModel.timeoutMs, signal,
113
+ ...decisionConversation(event.prompt, recentMessages),
94
114
  candidates: shortlist.map(({ candidate }) => candidate),
95
115
  onCandidateFailure: (candidateIndex, error) => {
96
116
  if (signal.aborted)
97
117
  return;
98
118
  diagnostics?.record(agentId, "skill", "judge_candidate_failed");
99
119
  api.logger.warn("unblock-memory skill_whisperer " + JSON.stringify({ event: "candidate_failed",
100
- agentId, runId, candidateIndex, errorCode: error instanceof TypeSafeRequestError ? error.code : "unexpected",
101
- httpStatus: error instanceof TypeSafeRequestError ? error.status : undefined }));
120
+ agentId, runId, candidateIndex, errorCode: error instanceof DecisionRequestError ? error.code : "unexpected",
121
+ httpStatus: error instanceof DecisionRequestError ? error.status : undefined }));
102
122
  },
103
123
  }), signal);
104
124
  if (selectedIndex === undefined) {
@@ -107,12 +127,10 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
107
127
  }
108
128
  resolved = shortlist[selectedIndex];
109
129
  }
110
- else if (resolved && resolved.candidate.score < config.minScore) {
130
+ else if (resolved.candidate.score < config.minScore) {
111
131
  diagnostics?.record(agentId, "skill", "rejected");
112
132
  return;
113
133
  }
114
- if (!resolved)
115
- return;
116
134
  // A selection completing after session teardown must not resurrect its hint.
117
135
  if (sessions.get(scope) !== state || state.lastRunId !== runId) {
118
136
  diagnostics?.record(agentId, "skill", "cancelled");
@@ -134,7 +152,7 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
134
152
  };
135
153
  }
136
154
  catch (error) {
137
- diagnostics?.record(agentId, "skill", isTypeSafeTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed");
155
+ diagnostics?.record(agentId, "skill", isDecisionTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed");
138
156
  if (!signal.aborted)
139
157
  api.logger.warn("unblock-memory skill whisperer failed; no hint emitted");
140
158
  return;
@@ -154,11 +172,15 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
154
172
  const path = scope ? readPath(event.params) : undefined;
155
173
  if (!scope || !path)
156
174
  return;
175
+ // Ignore late callbacks for cleared, closed, or unknown sessions rather than recreating stale state.
176
+ const state = sessions.get(scope);
177
+ if (!state)
178
+ return;
157
179
  try {
158
180
  const canonicalPath = runtime.resolveSkillPath(active(context.agentId), path);
159
181
  if (!canonicalPath)
160
182
  return;
161
- const state = stateFor(scope);
183
+ touchSession(scope, state);
162
184
  const history = state.skills.get(canonicalPath) ?? {};
163
185
  history.opened = state.turn;
164
186
  state.skills.set(canonicalPath, history);
@@ -1,28 +1,15 @@
1
1
  import type { TrainingInput } from "./training-input.js";
2
2
  export declare const TRAINING_GATE_VERSION = "historical-recall-v2";
3
- export declare const TRAINING_GATE_MODEL = "jev-1.13.0";
3
+ export declare const TRAINING_GATE_MODEL = "liquid/d1.2-ultra";
4
4
  export declare const TRAINING_GATE_THRESHOLD = 0.7;
5
5
  export declare const TRAINING_GATE_QUESTIONS: {
6
- recall_needed: {
7
- type: string;
8
- instructions: {
9
- question: string;
10
- history: string;
11
- scope: string;
12
- timeWindow: string;
13
- trust: string;
14
- };
15
- criteria: {
16
- true: string;
17
- false: string;
18
- };
19
- };
6
+ readonly recall_needed: import("@unblocklabs/decisions").NoulQuestion;
20
7
  };
21
- export declare function judgeTrainingInput(input: TrainingInput, apiKey: string, signal: AbortSignal): Promise<{
8
+ export declare function judgeTrainingInput(input: TrainingInput, apiKey: string, signal: AbortSignal, options?: {
9
+ endpoint?: string;
10
+ model?: string;
11
+ }): Promise<{
22
12
  probability: number;
23
- model: "jev-1.13.0";
24
- usage: {
25
- input_tokens: number;
26
- output_tokens: number;
27
- };
13
+ model: string;
14
+ usage: import("@unblocklabs/decisions").DecisionUsage;
28
15
  }>;