@unblocklabs/unblock-memory 0.10.1 → 0.10.3

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 (79) hide show
  1. package/README.md +10 -7
  2. package/dist/src/abortable.d.ts +2 -0
  3. package/dist/src/abortable.js +4 -0
  4. package/dist/src/agent-paths.d.ts +5 -0
  5. package/dist/src/agent-paths.js +10 -0
  6. package/dist/src/analysis.js +13 -18
  7. package/dist/src/cluster-review.js +9 -7
  8. package/dist/src/config.js +2 -2
  9. package/dist/src/curation.js +3 -10
  10. package/dist/src/diagnostics.d.ts +6 -1
  11. package/dist/src/diagnostics.js +1 -1
  12. package/dist/src/emotion-baselines.d.ts +0 -2
  13. package/dist/src/emotion-baselines.js +18 -39
  14. package/dist/src/evidence-review.js +2 -1
  15. package/dist/src/extraction-chunk.js +3 -4
  16. package/dist/src/extraction-index.d.ts +2 -0
  17. package/dist/src/extraction-index.js +4 -2
  18. package/dist/src/extraction-runtime.js +3 -3
  19. package/dist/src/extraction-store.js +7 -19
  20. package/dist/src/extraction-worker.js +3 -2
  21. package/dist/src/guards.d.ts +6 -0
  22. package/dist/src/guards.js +12 -0
  23. package/dist/src/inside-out-runtime.js +4 -3
  24. package/dist/src/inside-out-store.js +4 -10
  25. package/dist/src/inside-out.js +5 -3
  26. package/dist/src/json-hash.d.ts +2 -0
  27. package/dist/src/json-hash.js +6 -0
  28. package/dist/src/manager.d.ts +6 -1
  29. package/dist/src/manager.js +62 -91
  30. package/dist/src/memory-database.d.ts +3 -0
  31. package/dist/src/memory-database.js +18 -1
  32. package/dist/src/memory-search.d.ts +8 -2
  33. package/dist/src/memory-search.js +18 -2
  34. package/dist/src/people-hooks.js +3 -6
  35. package/dist/src/people-primer-tool.js +0 -2
  36. package/dist/src/people-primer.js +3 -6
  37. package/dist/src/people-store.d.ts +2 -1
  38. package/dist/src/people-store.js +29 -82
  39. package/dist/src/people-tools.js +4 -5
  40. package/dist/src/plugin.js +36 -27
  41. package/dist/src/quality-audit.js +2 -2
  42. package/dist/src/query-generator.js +1 -1
  43. package/dist/src/response-audit.js +7 -8
  44. package/dist/src/response-episodes.js +5 -8
  45. package/dist/src/response-judge.js +2 -3
  46. package/dist/src/response-reviews.js +8 -18
  47. package/dist/src/response-runtime.js +4 -3
  48. package/dist/src/response-stages.js +4 -4
  49. package/dist/src/response-store.js +15 -44
  50. package/dist/src/response-text.d.ts +1 -0
  51. package/dist/src/response-text.js +6 -4
  52. package/dist/src/retrieval-telemetry.d.ts +7 -2
  53. package/dist/src/retrieval-telemetry.js +3 -2
  54. package/dist/src/runtime.js +9 -8
  55. package/dist/src/safety-whisperer.js +4 -12
  56. package/dist/src/session-projector.js +7 -14
  57. package/dist/src/session-sync.d.ts +1 -0
  58. package/dist/src/session-sync.js +13 -17
  59. package/dist/src/skill-whisperer.js +3 -9
  60. package/dist/src/slack-directory.js +1 -5
  61. package/dist/src/sources.js +17 -37
  62. package/dist/src/tool-context.d.ts +2 -0
  63. package/dist/src/tool-context.js +5 -1
  64. package/dist/src/training-input.d.ts +0 -1
  65. package/dist/src/training-input.js +3 -6
  66. package/dist/src/training-queries.d.ts +1 -1
  67. package/dist/src/training-queries.js +9 -8
  68. package/dist/src/training-retrieval.js +2 -2
  69. package/dist/src/training-runtime.js +3 -3
  70. package/dist/src/training-store.js +14 -25
  71. package/dist/src/typesafe-client.d.ts +8 -0
  72. package/dist/src/typesafe-client.js +7 -1
  73. package/dist/src/typesafe-review.d.ts +1 -1
  74. package/dist/src/typesafe-review.js +1 -3
  75. package/dist/src/typesafe.js +4 -7
  76. package/docs/configuration.md +1 -1
  77. package/docs/retrieval.md +34 -7
  78. package/openclaw.plugin.json +1 -1
  79. package/package.json +6 -2
@@ -44,7 +44,6 @@ export function registerPeoplePrimerTool(api, runtime, stores, config) {
44
44
  try {
45
45
  combined.throwIfAborted();
46
46
  const apiKey = await abortable(resolveTypeSafeApiKey(config.typesafe), combined);
47
- combined.throwIfAborted();
48
47
  if (!apiKey)
49
48
  return jsonResult({ status: "unavailable", reason: "TypeSafe API key not configured" });
50
49
  const store = stores.get(active.agentId);
@@ -55,7 +54,6 @@ export function registerPeoplePrimerTool(api, runtime, stores, config) {
55
54
  if (identities.length && identities.every(i => i.isBot === true || i.isDeactivated))
56
55
  return jsonResult({ status: "unavailable", reason: "No active human identity" });
57
56
  const { manager } = await abortable(runtime.getMemorySearchManager(active), combined);
58
- combined.throwIfAborted();
59
57
  if (!manager)
60
58
  return jsonResult({ status: "unavailable", reason: "Memory unavailable" });
61
59
  const agentName = resolveAgentIdentity(active.cfg, active.agentId)?.name?.trim() || suppliedName?.trim() || "the assistant";
@@ -1,12 +1,9 @@
1
- import { createHash } from "node:crypto";
2
- import { Type } from "typebox";
3
1
  import { Value } from "typebox/value";
4
- import { requestTypeSafe, TYPESAFE_NOUL_SCHEMA } from "./typesafe-client.js";
5
- import { TYPESAFE_REVIEW_MODEL } from "./typesafe-review.js";
2
+ import { requestTypeSafe, TYPESAFE_MODEL, TYPESAFE_NOUL_ANSWERS_SCHEMA as answerSchema } from "./typesafe-client.js";
6
3
  import { abortable } from "./abortable.js";
4
+ import { jsonHash } from "./json-hash.js";
7
5
  const VERSION = "people-primer-background-v4";
8
6
  const MAX_EXCERPT_CHARS = 6000;
9
- const answerSchema = Type.Object({ answers: Type.Record(Type.String(), TYPESAFE_NOUL_SCHEMA) });
10
7
  function questionsFor(name, agent) {
11
8
  return [
12
9
  { id: "role", question: `Who is ${name}? What is their explicitly stated role and organization?` },
@@ -102,7 +99,7 @@ export async function primePersonDossier(params) {
102
99
  false: "Only a topic/name match, activity summary, behavioral profile, ambiguous attribution or no explicit background answer." },
103
100
  }])),
104
101
  };
105
- const key = createHash("sha256").update(JSON.stringify([VERSION, TYPESAFE_REVIEW_MODEL, person.id, state, questions])).digest("hex");
102
+ const key = jsonHash([VERSION, TYPESAFE_MODEL, person.id, state, questions]);
106
103
  const expectedKeys = Object.keys(questions);
107
104
  const valid = (value) => Value.Check(answerSchema, value) &&
108
105
  Object.keys(value.answers).length === expectedKeys.length && expectedKeys.every(k => Object.hasOwn(value.answers, k));
@@ -153,7 +153,8 @@ export declare class PeopleStore {
153
153
  }[];
154
154
  };
155
155
  getDossierRevision(personId: string): string | null;
156
- replaceDossier(personId: string, reasonInput: string, input: unknown, expectedRevision?: string | null): PersonDossier;
156
+ /** Returns undefined when the person does not exist. */
157
+ replaceDossier(personId: string, reasonInput: string, input: unknown, expectedRevision?: string | null): PersonDossier | undefined;
157
158
  deleteDossier(personId: string, reasonInput: string): boolean;
158
159
  getWhisperReceipt(threadKey: string, personId: string): {
159
160
  runId: string;
@@ -1,12 +1,13 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { join } from "node:path";
4
- import { MEMORY_DATABASE, openMemoryDatabase } from "./memory-database.js";
4
+ import { immediateTransaction, MEMORY_DATABASE, openMemoryDatabase } from "./memory-database.js";
5
5
  import { resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
6
6
  import { normalizeAgentIdStrict } from "openclaw/plugin-sdk/routing";
7
7
  import { Type } from "typebox";
8
8
  import { Value } from "typebox/value";
9
9
  import { backgroundWordCount, PEOPLE_BACKGROUND_MAX_WORDS } from "./people-background.js";
10
+ import { agentStateDir } from "./agent-paths.js";
10
11
  const BASELINE_DOSSIER_CATEGORIES = [
11
12
  "role",
12
13
  "priorities",
@@ -154,8 +155,11 @@ export class PeopleStore {
154
155
  this.#maxBlurbChars = options.maxBlurbChars;
155
156
  try {
156
157
  this.#migrate();
158
+ // The second index serves cross-scope matches (inside-out-store PERSON_MATCH).
157
159
  this.#db.exec(`CREATE INDEX IF NOT EXISTS person_identities_person
158
- ON person_identities(person_id, provider, account_scope, external_id)`);
160
+ ON person_identities(person_id, provider, account_scope, external_id);
161
+ CREATE INDEX IF NOT EXISTS person_identities_provider_external
162
+ ON person_identities(provider, external_id)`);
159
163
  }
160
164
  catch (error) {
161
165
  this.#db.close();
@@ -207,8 +211,7 @@ export class PeopleStore {
207
211
  const externalId = required(input.externalId, "externalId");
208
212
  const directorySync = input.syncedAt !== undefined;
209
213
  const now = input.seenAt ?? input.syncedAt ?? new Date().toISOString();
210
- this.#db.exec("BEGIN IMMEDIATE");
211
- try {
214
+ return immediateTransaction(this.#db, () => {
212
215
  const existing = this.#identityRow(provider, accountScope, externalId);
213
216
  const personId = existing?.person_id ?? randomUUID();
214
217
  if (existing) {
@@ -216,7 +219,6 @@ export class PeopleStore {
216
219
  .prepare("SELECT * FROM people WHERE id = ?")
217
220
  .get(personId);
218
221
  if (existingPerson.status !== "active") {
219
- this.#db.exec("COMMIT");
220
222
  return { person: person(existingPerson), identity: identity(existing), created: false };
221
223
  }
222
224
  }
@@ -289,13 +291,8 @@ export class PeopleStore {
289
291
  .prepare("SELECT * FROM people WHERE id = ?")
290
292
  .get(personId);
291
293
  const identityRow = this.#identityRow(provider, accountScope, externalId);
292
- this.#db.exec("COMMIT");
293
294
  return { person: person(personRow), identity: identity(identityRow), created: !existing };
294
- }
295
- catch (error) {
296
- this.#db.exec("ROLLBACK");
297
- throw error;
298
- }
295
+ });
299
296
  }
300
297
  findPersonByIdentity(provider, accountScope, externalId) {
301
298
  const row = this.#db
@@ -330,11 +327,9 @@ export class PeopleStore {
330
327
  const name = required(input.name, "company name");
331
328
  const primaryDomain = optional(input.primaryDomain);
332
329
  const now = new Date().toISOString();
333
- this.#db.exec("BEGIN IMMEDIATE");
334
- try {
330
+ return immediateTransaction(this.#db, () => {
335
331
  const target = this.#db.prepare("SELECT id FROM people WHERE id = ?").get(personId);
336
332
  if (!target) {
337
- this.#db.exec("COMMIT");
338
333
  return undefined;
339
334
  }
340
335
  let row = this.#db
@@ -359,13 +354,8 @@ export class PeopleStore {
359
354
  this.#db
360
355
  .prepare("UPDATE people SET company_id = ?, updated_at = ? WHERE id = ?")
361
356
  .run(row.id, now, personId);
362
- this.#db.exec("COMMIT");
363
357
  return company(row);
364
- }
365
- catch (error) {
366
- this.#db.exec("ROLLBACK");
367
- throw error;
368
- }
358
+ });
369
359
  }
370
360
  listActivePeople(limit = 50, offset = 0) {
371
361
  return this.#db
@@ -387,8 +377,7 @@ export class PeopleStore {
387
377
  this.#db
388
378
  .prepare("UPDATE people SET injection_enabled = ?, updated_at = ? WHERE id = ?")
389
379
  .run(Number(enabled), now, personId);
390
- const row = this.#db.prepare("SELECT * FROM people WHERE id = ?").get(personId);
391
- return row ? person(row) : undefined;
380
+ return this.getPerson(personId);
392
381
  }
393
382
  validateDossier(input) {
394
383
  const dossier = Value.Parse(PERSON_DOSSIER_WRITE_SCHEMA, input);
@@ -401,16 +390,16 @@ export class PeopleStore {
401
390
  .get(personId);
402
391
  return row?.id ?? null;
403
392
  }
393
+ /** Returns undefined when the person does not exist. */
404
394
  replaceDossier(personId, reasonInput, input, expectedRevision) {
405
395
  const dossier = this.validateDossier(input);
406
396
  const dossierJson = serializeDossier(dossier);
407
397
  const reason = dossierReason(reasonInput);
408
398
  const reviewedAt = new Date().toISOString();
409
- this.#db.exec("BEGIN IMMEDIATE");
410
- try {
399
+ return immediateTransaction(this.#db, () => {
411
400
  const target = this.#db.prepare("SELECT id, status FROM people WHERE id = ?").get(personId);
412
401
  if (!target)
413
- throw new Error(`person not found: ${personId}`);
402
+ return undefined;
414
403
  if (expectedRevision !== undefined &&
415
404
  (target.status !== "active" || this.getDossierRevision(personId) !== expectedRevision)) {
416
405
  throw new DossierConflictError();
@@ -437,24 +426,17 @@ export class PeopleStore {
437
426
  VALUES (?, ?, 'replace', ?, ?, ?, ?)
438
427
  `)
439
428
  .run(randomUUID(), personId, existing?.dossier_json ?? null, dossierJson, reason, reviewedAt);
440
- this.#db.exec("COMMIT");
441
429
  return dossier;
442
- }
443
- catch (error) {
444
- this.#db.exec("ROLLBACK");
445
- throw error;
446
- }
430
+ });
447
431
  }
448
432
  deleteDossier(personId, reasonInput) {
449
433
  const reason = dossierReason(reasonInput);
450
434
  const changedAt = new Date().toISOString();
451
- this.#db.exec("BEGIN IMMEDIATE");
452
- try {
435
+ return immediateTransaction(this.#db, () => {
453
436
  const existing = this.#db
454
437
  .prepare("SELECT dossier_json FROM person_dossiers WHERE person_id = ?")
455
438
  .get(personId);
456
439
  if (!existing) {
457
- this.#db.exec("COMMIT");
458
440
  return false;
459
441
  }
460
442
  parseDossierJson(existing.dossier_json);
@@ -466,13 +448,8 @@ export class PeopleStore {
466
448
  VALUES (?, ?, 'delete', ?, NULL, ?, ?)
467
449
  `)
468
450
  .run(randomUUID(), personId, existing.dossier_json, reason, changedAt);
469
- this.#db.exec("COMMIT");
470
451
  return true;
471
- }
472
- catch (error) {
473
- this.#db.exec("ROLLBACK");
474
- throw error;
475
- }
452
+ });
476
453
  }
477
454
  getWhisperReceipt(threadKey, personId) {
478
455
  const row = this.#db
@@ -571,8 +548,7 @@ export class PeopleStore {
571
548
  }
572
549
  softDeletePerson(personId) {
573
550
  const now = new Date().toISOString();
574
- this.#db.exec("BEGIN IMMEDIATE");
575
- try {
551
+ return immediateTransaction(this.#db, () => {
576
552
  const changed = this.#db
577
553
  .prepare(`
578
554
  UPDATE people SET status = 'unavailable', injection_enabled = 0,
@@ -580,7 +556,6 @@ export class PeopleStore {
580
556
  `)
581
557
  .run(now, personId);
582
558
  if (changed.changes === 0) {
583
- this.#db.exec("COMMIT");
584
559
  return undefined;
585
560
  }
586
561
  this.#upsertTodoRow({
@@ -589,18 +564,12 @@ export class PeopleStore {
589
564
  context: { personId },
590
565
  }, now);
591
566
  const updated = this.getPerson(personId);
592
- this.#db.exec("COMMIT");
593
567
  return updated;
594
- }
595
- catch (error) {
596
- this.#db.exec("ROLLBACK");
597
- throw error;
598
- }
568
+ });
599
569
  }
600
570
  restorePerson(personId) {
601
571
  const now = new Date().toISOString();
602
- this.#db.exec("BEGIN IMMEDIATE");
603
- try {
572
+ return immediateTransaction(this.#db, () => {
604
573
  const changed = this.#db
605
574
  .prepare(`
606
575
  UPDATE people SET status = 'active', injection_enabled = 0, updated_at = ?
@@ -608,17 +577,11 @@ export class PeopleStore {
608
577
  `)
609
578
  .run(now, personId);
610
579
  if (changed.changes === 0) {
611
- this.#db.exec("COMMIT");
612
580
  return undefined;
613
581
  }
614
582
  const restored = this.getPerson(personId);
615
- this.#db.exec("COMMIT");
616
583
  return restored;
617
- }
618
- catch (error) {
619
- this.#db.exec("ROLLBACK");
620
- throw error;
621
- }
584
+ });
622
585
  }
623
586
  resolveTodoByKey(deduplicationKey, note) {
624
587
  const now = new Date().toISOString();
@@ -633,16 +596,10 @@ export class PeopleStore {
633
596
  const deduplicationKey = required(input.deduplicationKey, "deduplicationKey");
634
597
  const kind = required(input.kind, "kind");
635
598
  const now = new Date().toISOString();
636
- this.#db.exec("BEGIN IMMEDIATE");
637
- try {
599
+ return immediateTransaction(this.#db, () => {
638
600
  const row = this.#upsertTodoRow({ deduplicationKey, kind, context: input.context }, now);
639
- this.#db.exec("COMMIT");
640
601
  return todo(row);
641
- }
642
- catch (error) {
643
- this.#db.exec("ROLLBACK");
644
- throw error;
645
- }
602
+ });
646
603
  }
647
604
  listTodos(limit = 100) {
648
605
  const bounded = Math.max(1, Math.min(100, Math.floor(limit)));
@@ -661,12 +618,14 @@ export class PeopleStore {
661
618
  const row = this.#db
662
619
  .prepare("SELECT * FROM people_todos WHERE deduplication_key = ?")
663
620
  .get(input.deduplicationKey);
664
- if (row?.status === "resolved") {
621
+ if (!row || row.status === "resolved") {
665
622
  const count = this.#db
666
623
  .prepare("SELECT COUNT(*) AS count FROM people_todos WHERE status = 'open'")
667
624
  .get();
668
625
  if (count.count >= this.#maxOpenTodos)
669
626
  return this.#incrementOverflowTodo(now);
627
+ }
628
+ if (row?.status === "resolved") {
670
629
  this.#db
671
630
  .prepare(`
672
631
  UPDATE people_todos
@@ -687,11 +646,6 @@ export class PeopleStore {
687
646
  .run(contextJson, now, row.id);
688
647
  return this.#db.prepare("SELECT * FROM people_todos WHERE id = ?").get(row.id);
689
648
  }
690
- const count = this.#db
691
- .prepare("SELECT COUNT(*) AS count FROM people_todos WHERE status = 'open'")
692
- .get();
693
- if (count.count >= this.#maxOpenTodos)
694
- return this.#incrementOverflowTodo(now);
695
649
  const id = randomUUID();
696
650
  this.#db
697
651
  .prepare(`
@@ -758,8 +712,7 @@ export class PeopleStore {
758
712
  }
759
713
  }
760
714
  #migrate() {
761
- this.#db.exec("BEGIN IMMEDIATE");
762
- try {
715
+ return immediateTransaction(this.#db, () => {
763
716
  // Re-read under the write lock so concurrent first opens cannot both migrate.
764
717
  const version = this.#db.prepare("SELECT version FROM memory_schema WHERE component='people'").get()?.version
765
718
  ?? this.#db.prepare("PRAGMA user_version").get()?.user_version ?? 0;
@@ -767,7 +720,6 @@ export class PeopleStore {
767
720
  throw new Error(`unsupported PeopleSQL schema version: ${version}`);
768
721
  if (version === 4) {
769
722
  this.#db.prepare("INSERT OR IGNORE INTO memory_schema VALUES ('people',4)").run();
770
- this.#db.exec("COMMIT");
771
723
  return;
772
724
  }
773
725
  if (version === 2) {
@@ -881,12 +833,7 @@ export class PeopleStore {
881
833
  INSERT INTO memory_schema VALUES ('people',4)
882
834
  ON CONFLICT(component) DO UPDATE SET version=excluded.version;
883
835
  `);
884
- this.#db.exec("COMMIT");
885
- }
886
- catch (error) {
887
- this.#db.exec("ROLLBACK");
888
- throw error;
889
- }
836
+ });
890
837
  }
891
838
  }
892
839
  export class PeopleStores {
@@ -904,7 +851,7 @@ export class PeopleStores {
904
851
  const canonicalAgentId = normalized.value;
905
852
  let store = this.#stores.get(canonicalAgentId);
906
853
  if (!store) {
907
- store = new PeopleStore(join(this.#stateRoot, "agents", canonicalAgentId, "unblock-memory", MEMORY_DATABASE), this.#options);
854
+ store = new PeopleStore(join(agentStateDir(canonicalAgentId, this.#stateRoot), MEMORY_DATABASE), this.#options);
908
855
  this.#stores.set(canonicalAgentId, store);
909
856
  }
910
857
  return store;
@@ -3,7 +3,7 @@ import { Type } from "typebox";
3
3
  import { Value } from "typebox/value";
4
4
  import { renderPeopleWhisper } from "./people-hooks.js";
5
5
  import { DossierConflictError, PERSON_DOSSIER_WRITE_SCHEMA } from "./people-store.js";
6
- import { getContext } from "./tool-context.js";
6
+ import { getContext, runtimeConfig } from "./tool-context.js";
7
7
  import { reviewPersonDossier } from "./people-dossier-review.js";
8
8
  import { createOpenClawSlackDirectory, syncSlackDirectory, } from "./slack-directory.js";
9
9
  const nonEmpty = Type.String({ pattern: "\\S", maxLength: 1000 });
@@ -223,14 +223,13 @@ function createUpdateTool(stores, config, runtime, ctx) {
223
223
  : "TypeSafe background review passed (person-background-v2)";
224
224
  try {
225
225
  const dossier = store.replaceDossier(input.personId, `${input.reason}\n${audit}`, proposed, revision);
226
+ if (!dossier)
227
+ return jsonResult({ status: "not_found" });
226
228
  return jsonResult({ status: "ok", saved: true, verification: review.status === "manual" ? "manual" : "typesafe", dossier, review });
227
229
  }
228
230
  catch (error) {
229
231
  if (error instanceof DossierConflictError)
230
232
  return jsonResult({ status: "conflict", saved: false, reason: error.message });
231
- if (error instanceof Error && error.message.startsWith("person not found:")) {
232
- return jsonResult({ status: "not_found" });
233
- }
234
233
  throw error;
235
234
  }
236
235
  }
@@ -297,7 +296,7 @@ export function registerPeopleTools(api, stores, config, runtime, directoryReade
297
296
  });
298
297
  api.registerTool((ctx) => createSyncTool(stores, directoryReader ??
299
298
  createOpenClawSlackDirectory({
300
- getConfig: () => ctx.getRuntimeConfig?.() ?? ctx.runtimeConfig ?? ctx.config,
299
+ getConfig: () => runtimeConfig(ctx),
301
300
  }), ctx), {
302
301
  names: ["memory_people_sync"],
303
302
  optional: true,
@@ -21,7 +21,12 @@ import { resolveTimezone } from "./session-projector.js";
21
21
  import { searchMemory } from "./memory-search.js";
22
22
  import { prepareQueryConversation, QueryInputBudgetError } from "./query-contract.js";
23
23
  import { resolveTypeSafeApiKey } from "./typesafe-client.js";
24
+ import { abortedByTimeout } from "./abortable.js";
24
25
  import { registerExtraction } from "./extraction-runtime.js";
26
+ function managerUnavailable(error) {
27
+ return jsonResult({ status: "unavailable", error: error ?? "memory unavailable" });
28
+ }
29
+ const ISO_TIMESTAMP_PATTERN = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$";
25
30
  const searchParameters = Type.Object({
26
31
  bm25Query: Type.String({ pattern: "\\S", description: "Distinctive names, identifiers and keywords for BM25 retrieval." }),
27
32
  vectorQuery: Type.String({ pattern: "\\S", description: "Natural-language question describing the information needed; also the intent used to judge usefulness." }),
@@ -31,11 +36,11 @@ const searchParameters = Type.Object({
31
36
  sessionFilter: Type.Optional(Type.Object({
32
37
  startedFrom: Type.Optional(Type.String({
33
38
  description: "Inclusive lower bound on session start time, not message or claim dates (ISO 8601).",
34
- pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$",
39
+ pattern: ISO_TIMESTAMP_PATTERN,
35
40
  })),
36
41
  startedTo: Type.Optional(Type.String({
37
42
  description: "Inclusive upper bound on session start time, not message or claim dates (ISO 8601).",
38
- pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$",
43
+ pattern: ISO_TIMESTAMP_PATTERN,
39
44
  })),
40
45
  provider: Type.Optional(Type.String({ pattern: "\\S" })),
41
46
  chatType: Type.Optional(Type.Union([Type.Literal("channel"), Type.Literal("group"), Type.Literal("direct")])),
@@ -43,7 +48,7 @@ const searchParameters = Type.Object({
43
48
  conversationId: Type.Optional(Type.String({ pattern: "\\S" })),
44
49
  }, { additionalProperties: false, description: "Restricts session documents only; selected file corpora remain eligible. Not an audience access control." })),
45
50
  maxResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Maximum hits; default 5." })),
46
- minUsefulness: Type.Optional(Type.Number({ minimum: 0, maximum: 1, description: "Minimum TypeSafe usefulness probability; default 0.7. Not confidence in factual truth." })),
51
+ minUsefulness: Type.Optional(Type.Number({ minimum: 0, maximum: 1, description: "Minimum TypeSafe usefulness probability; default 0.7. Not confidence in factual truth. Not applied to unjudged retrieval fallback." })),
47
52
  }, { additionalProperties: false });
48
53
  const getParameters = Type.Object({
49
54
  path: Type.String({ pattern: "\\S" }),
@@ -61,7 +66,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
61
66
  return {
62
67
  name: "memory_search",
63
68
  label: "Memory Search",
64
- description: "Search this agent's configured memory corpora with BM25 and vector queries, then TypeSafe usefulness ranking. Supply keywords in bm25Query and the information needed in vectorQuery; no query generation or recall gate runs. Queries and candidate passages are sent to TypeSafe. Skills are excluded. Session snippets are message arrays; file snippets are strings. Inspect source context with memory_get. Empty results or errors do not prove absence of a fact.",
69
+ description: "Search this agent's configured memory corpora with BM25 and vector queries, then TypeSafe usefulness ranking. If TypeSafe is unavailable, returns retrieval-ranked leads with a warning; retrieval scores are not usefulness probabilities and minUsefulness is not applied. Supply keywords in bm25Query and the information needed in vectorQuery; no query generation or recall gate runs. Queries and candidate passages are sent to TypeSafe when available. Skills are excluded. Session snippets are message arrays; file snippets are strings. Inspect source context with memory_get. Empty results or errors do not prove absence of a fact.",
65
70
  parameters: searchParameters,
66
71
  async execute(_toolCallId, params, signal) {
67
72
  const started = performance.now();
@@ -73,11 +78,12 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
73
78
  // Reject oversized explicit inputs before credential resolution or any service call.
74
79
  prepareQueryConversation([], queries.lex);
75
80
  const { conversation } = prepareQueryConversation([], queries.vec);
76
- const apiKey = await resolveTypeSafeApiKey(typesafe);
77
- if (!apiKey) {
78
- measurement.outcome = "skipped";
79
- return jsonResult({ results: [], error: "TypeSafe API key not configured or TypeSafe disabled" });
81
+ let apiKey;
82
+ try {
83
+ apiKey = await resolveTypeSafeApiKey(typesafe);
80
84
  }
85
+ catch { /* Explicit search can still return local evidence; never expose credential errors. */ }
86
+ signal?.throwIfAborted();
81
87
  const { manager, error } = await runtime.getMemorySearchManager(active);
82
88
  measurement.setupMs = performance.now() - started;
83
89
  if (!manager)
@@ -87,27 +93,33 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
87
93
  sessionFilter,
88
94
  maxResults,
89
95
  minUsefulness,
90
- apiKey, timeoutMs: typesafe.timeoutMs, conversation,
96
+ apiKey, timeoutMs: typesafe.timeoutMs, conversation, allowRetrievalFallback: true,
91
97
  signal, timings: measurement,
92
98
  requestContext: active.requestContext,
93
99
  onCandidates: ({ retrievalMs, candidates, eligible }) => {
94
100
  Object.assign(measurement, { retrievalMs, candidates, eligible });
95
101
  },
96
102
  });
97
- measurement.judgeMs = search.judgeMs;
103
+ measurement.requestsSucceeded = search.requestsSucceeded;
104
+ measurement.requestsFailed = search.requestsFailed;
105
+ measurement.fallbackKeyUnavailable = Number(search.fallbackReason === "key_unavailable");
106
+ measurement.fallbackAllJudgmentsFailed = Number(search.fallbackReason === "all_judgments_failed");
98
107
  measurement.results = search.results.length;
99
108
  measurement.contextChars = search.results.reduce((sum, hit) => sum + hit.snippet.length, 0);
100
- if (search.eligible && !search.requestsSucceeded)
101
- return jsonResult({ results: [], error: "All memory usefulness judgments failed" });
102
- measurement.outcome = search.requestsFailed ? "partial" : search.results.length ? "ok" : "empty";
109
+ measurement.outcome = search.rankingMode === "retrieval" ? "degraded" : search.requestsFailed ? "partial" : search.results.length ? "ok" : "empty";
103
110
  // Compact only the public tool response; internal ranking and consumers keep
104
111
  // full-precision scores and the host's source/citation compatibility fields.
105
112
  const payload = {
106
- ...(search.requestsFailed ? { warning: `${search.requestsFailed} candidate usefulness judgments failed; results are partial` } : {}),
107
- results: search.results.map(({ source: _source, citation: _citation, session, sessionMessages, ...result }) => ({
113
+ rankingMode: search.rankingMode,
114
+ scoreMeaning: search.rankingMode === "retrieval" ? "retrieval_rank" : "usefulness_probability",
115
+ minUsefulnessApplied: search.rankingMode !== "retrieval",
116
+ ...(search.fallbackReason ? { fallbackReason: search.fallbackReason,
117
+ warning: "TypeSafe usefulness ranking unavailable; returning unjudged retrieval-ranked leads. Scores are retrieval ranks, not usefulness probabilities; minUsefulness was not applied. Verify evidence with memory_get." }
118
+ : search.requestsFailed ? { warning: `${search.requestsFailed} candidate usefulness judgments failed; results are partial` } : {}),
119
+ results: search.results.map(({ source: _source, citation: _citation, vectorScore: _vectorScore, textScore: _textScore, session, sessionMessages, ...result }) => ({
108
120
  ...result,
109
121
  snippet: result.corpus === "sessions" ? sessionMessages ?? [{ body: result.snippet, partial: true }] : result.snippet,
110
- score: Number(result.score.toFixed(2)),
122
+ score: search.rankingMode === "retrieval" ? result.score : Number(result.score.toFixed(2)),
111
123
  ...(session ? { session: { ...session, startedAt: new Date(session.startedAt).toISOString() } } : {}),
112
124
  })),
113
125
  };
@@ -128,8 +140,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
128
140
  measurement.otherMs = Math.max(0, measurement.elapsedMs - measurement.setupMs -
129
141
  (measurement.retrievalMs ?? 0) - (measurement.candidatePrepMs ?? 0) - (measurement.judgeMs ?? 0));
130
142
  if (signal?.aborted)
131
- measurement.outcome = signal.reason instanceof Error && signal.reason.name === "TimeoutError"
132
- ? "timed_out" : "cancelled";
143
+ measurement.outcome = abortedByTimeout(signal) ? "timed_out" : "cancelled";
133
144
  diagnostics.measureSearch(active.agentId, measurement);
134
145
  }
135
146
  },
@@ -149,7 +160,7 @@ function createGetTool(runtime, ctx) {
149
160
  const path = untrimmedPath.trim();
150
161
  const { manager, error } = await runtime.getMemorySearchManager(active);
151
162
  if (!manager)
152
- return jsonResult({ status: "unavailable", error: error ?? "memory unavailable" });
163
+ return managerUnavailable(error);
153
164
  return jsonResult(await manager.readFile({
154
165
  relPath: path,
155
166
  from,
@@ -218,7 +229,7 @@ function createReclusterTool(runtime, ctx) {
218
229
  const options = Value.Parse(reclusterParameters, params);
219
230
  const { manager, error } = await runtime.getMemorySearchManager(active);
220
231
  if (!manager)
221
- return jsonResult({ status: "unavailable", error: error ?? "memory unavailable" });
232
+ return managerUnavailable(error);
222
233
  try {
223
234
  return jsonResult(await manager.recluster(options, signal));
224
235
  }
@@ -247,7 +258,7 @@ function createListClustersTool(runtime, ctx) {
247
258
  const { limit } = Value.Parse(listClustersParameters, params);
248
259
  const { manager, error } = await runtime.getMemorySearchManager(active);
249
260
  if (!manager)
250
- return jsonResult({ status: "unavailable", error: error ?? "memory unavailable" });
261
+ return managerUnavailable(error);
251
262
  return jsonResult(await manager.listClusters(limit));
252
263
  },
253
264
  };
@@ -277,7 +288,7 @@ function createFetchClusterTool(runtime, ctx) {
277
288
  const { clusterId, topK, offset, sort } = Value.Parse(fetchClusterParameters, params);
278
289
  const { manager, error } = await runtime.getMemorySearchManager(active);
279
290
  if (!manager)
280
- return jsonResult({ status: "unavailable", error: error ?? "memory unavailable" });
291
+ return managerUnavailable(error);
281
292
  return jsonResult(await manager.fetchCluster({ clusterId, topK, offset, sort }));
282
293
  },
283
294
  };
@@ -338,14 +349,12 @@ function createListMaintenanceTool(runtime, ctx) {
338
349
  const options = Value.Parse(listMaintenanceParameters, params);
339
350
  const { manager, error } = await runtime.getMemorySearchManager(active);
340
351
  if (!manager)
341
- return jsonResult({ status: "unavailable", error: error ?? "memory unavailable" });
352
+ return managerUnavailable(error);
342
353
  return jsonResult({ status: "ok", tasks: await manager.listMaintenanceTasks(options) });
343
354
  },
344
355
  };
345
356
  }
346
- const isoTimestamp = Type.String({
347
- pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$",
348
- });
357
+ const isoTimestamp = Type.String({ pattern: ISO_TIMESTAMP_PATTERN });
349
358
  const updateMaintenanceParameters = Type.Object({
350
359
  taskId: Type.String({ pattern: "\\S" }),
351
360
  action: Type.Union([
@@ -379,7 +388,7 @@ function createUpdateMaintenanceTool(runtime, ctx) {
379
388
  const { taskId, action, note, annotation } = Value.Parse(updateMaintenanceParameters, params);
380
389
  const { manager, error } = await runtime.getMemorySearchManager(active);
381
390
  if (!manager)
382
- return jsonResult({ status: "unavailable", error: error ?? "memory unavailable" });
391
+ return managerUnavailable(error);
383
392
  const updated = manager.updateMaintenanceTask({
384
393
  id: taskId,
385
394
  status: action === "resolve" ? "resolved" : action === "defer" ? "deferred" : "irrelevant",
@@ -132,6 +132,7 @@ export async function auditQualityPage(params) {
132
132
  structure === "serialized_message" ? "possible_serialized_message" : "possible_ingestion_noise";
133
133
  const startLine = row.doc.slice(0, row.pos).split("\n").length;
134
134
  const endLine = startLine + text.split("\n").length - 1;
135
+ const triage = qualityTriage(judgment.noise, judgment.evidence, structure === "encoded_message");
135
136
  const task = curation.addTask({
136
137
  type: "quality_review", corpus: source.corpus, collection: source.collection,
137
138
  path: row.path, reason, contentFingerprint: fingerprint,
@@ -141,7 +142,7 @@ export async function auditQualityPage(params) {
141
142
  indicator: structure === "empty" ? "deterministic_empty" :
142
143
  structure === "encoded_message" ? "deterministic_encoding" : "typesafe",
143
144
  ...judgment, policy: QUALITY_JUDGE_VERSION,
144
- triage: qualityTriage(judgment.noise, judgment.evidence, structure === "encoded_message"),
145
+ triage,
145
146
  instruction: "Inspect original source and ingestion before acting. Verify source/index after any authorized repair. Never manually edit generated session projections.",
146
147
  }),
147
148
  });
@@ -149,7 +150,6 @@ export async function auditQualityPage(params) {
149
150
  advance();
150
151
  if (task.status !== "pending")
151
152
  continue;
152
- const triage = qualityTriage(judgment.noise, judgment.evidence, structure === "encoded_message");
153
153
  const key = JSON.stringify([source.collection, reason, triage]);
154
154
  const group = groups.get(key) ?? {
155
155
  corpus: source.corpus, source: source.configuredPath, reason, triage, pending: 0, examples: [],
@@ -4,7 +4,7 @@ import { abortable } from "./abortable.js";
4
4
  import { messageText } from "./whisperer-context.js";
5
5
  import { conversationUserText } from "./response-text.js";
6
6
  import { parseQueryPair, prepareQueryConversation } from "./query-contract.js";
7
- const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
7
+ import { record } from "./guards.js";
8
8
  /** Preserve whole visible messages and the complete current request, never tool/thinking text. */
9
9
  export function queryConversation(prompt, messages) {
10
10
  const currentRequest = conversationUserText(prompt)?.text ?? "";
@@ -1,20 +1,19 @@
1
- import { createHash } from "node:crypto";
2
1
  import { abortable } from "./abortable.js";
3
- import { resolveTypeSafeApiKey } from "./typesafe-client.js";
2
+ import { resolveTypeSafeApiKey, TYPESAFE_MODEL } from "./typesafe-client.js";
4
3
  import { RESPONSE_EXTRACTOR_VERSION, ResponseTranscriptReader } from "./response-episodes.js";
5
4
  import { RESPONSE_RUBRIC_VERSION, RESPONSE_STAGE_VERSIONS, judgeMemoryOpportunity } from "./response-judge.js";
6
5
  import { ResponseAuditStore } from "./response-store.js";
7
6
  import { responseMemoryCandidates } from "./response-memory.js";
8
7
  import { assessResponseStages } from "./response-stages.js";
9
8
  import { ResponsePeople } from "./response-identity.js";
10
- import { TYPESAFE_REVIEW_MODEL } from "./typesafe-review.js";
9
+ import { jsonHash } from "./json-hash.js";
11
10
  export function responseCohort(config) {
12
- return RESPONSE_RUBRIC_VERSION + ":" + createHash("sha256").update(JSON.stringify({
11
+ return RESPONSE_RUBRIC_VERSION + ":" + jsonHash({
13
12
  extractor: RESPONSE_EXTRACTOR_VERSION, historyMessages: config.historyMessages,
14
13
  stages: RESPONSE_STAGE_VERSIONS,
15
14
  sentimentEnabled: config.sentimentEnabled,
16
15
  senderIds: [...config.senderIds].sort(), chatTypes: [...config.chatTypes].sort(), memoryCorpora: [...config.memoryCorpora].sort(),
17
- })).digest("hex").slice(0, 16);
16
+ }).slice(0, 16);
18
17
  }
19
18
  /** All inference is outside memory's mutation queue and outside transcript DB transactions. */
20
19
  export async function auditResponses(options) {
@@ -96,7 +95,7 @@ export async function auditResponses(options) {
96
95
  coverage.reconciledSessions++;
97
96
  for (const key of Object.keys(snapshot.coverage))
98
97
  coverage[key] += snapshot.coverage[key];
99
- const episodes = snapshot.episodes.filter(e => e.timestamp >= now - config.responseAudit.lookbackDays * 86400_000);
98
+ const episodes = snapshot.episodes.filter(e => e.timestamp >= since);
100
99
  coverage.outsideLookback += snapshot.episodes.length - episodes.length;
101
100
  store?.observe(cohort, session, snapshot.episodes);
102
101
  store?.checkpointSave(cohort, session, snapshot.revision, snapshot.coverage);
@@ -123,9 +122,9 @@ export async function auditResponses(options) {
123
122
  try {
124
123
  const approved = options.sources.filter(s => config.responseAudit.memoryCorpora.includes(s.corpus));
125
124
  const candidates = responseMemoryCandidates(options.indexPath, approved, e);
126
- const memoryKey = createHash("sha256").update(JSON.stringify([TYPESAFE_REVIEW_MODEL, RESPONSE_STAGE_VERSIONS.memory,
125
+ const memoryKey = jsonHash([TYPESAFE_MODEL, RESPONSE_STAGE_VERSIONS.memory,
127
126
  e.id, e.session, e.senderId, e.request, e.answer, e.feedback, candidates,
128
- [...config.responseAudit.memoryCorpora].sort()])).digest("hex");
127
+ [...config.responseAudit.memoryCorpora].sort()]);
129
128
  let judged = store.stage(cohort, e, "memory", memoryKey);
130
129
  if (judged)
131
130
  coverage.stageCacheHits++;