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