@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
@@ -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 { renderPeopleDossier } from "./people-background.js";
6
- import { DossierConflictError, PERSON_DOSSIER_WRITE_SCHEMA } from "./people-store.js";
6
+ import { DossierConflictError, PERSON_DOSSIER_WRITE_SCHEMA, } from "./people-store.js";
7
7
  import { getContext, runtimeConfig } from "./tool-context.js";
8
8
  import { reviewPersonDossier } from "./people-dossier-review.js";
9
9
  import { createOpenClawSlackDirectory, syncSlackDirectory, } from "./slack-directory.js";
@@ -83,12 +83,13 @@ const updateParameters = Type.Union([
83
83
  reason: Type.String({ pattern: "\\S", maxLength: 500 }),
84
84
  agentName: Type.Optional(Type.String({ pattern: "\\S", maxLength: 100 })),
85
85
  manualVerification: Type.Optional(Type.String({ pattern: "\\S", maxLength: 400,
86
- description: "Source-specific attestation that you checked every saved claim, its scope and any newer corrections. Distinguish explicit preferences from provisional agent lessons. Skips TypeSafe; recorded as manual. Never use as a blind retry switch." })),
86
+ description: "Source-specific attestation that you checked every saved claim, its scope and any newer corrections. Distinguish explicit preferences from provisional agent lessons. Skips automated review; recorded as manual. Never use as a blind retry switch." })),
87
87
  }, { additionalProperties: false }),
88
88
  Type.Object({
89
89
  action: Type.Literal("delete_dossier"),
90
90
  personId: nonEmpty,
91
91
  reason: nonEmpty,
92
+ expectedRevision: Type.Optional(Type.Union([nonEmpty, Type.Null()])),
92
93
  }, { additionalProperties: false }),
93
94
  Type.Object({
94
95
  action: Type.Literal("set_company"),
@@ -135,6 +136,65 @@ function personView(stores, agentId, selector, maxChars) {
135
136
  contribution,
136
137
  };
137
138
  }
139
+ function nextPageOffset(offset, count, limit) {
140
+ return count === limit ? offset + count : null;
141
+ }
142
+ async function handleReplaceDossier(params) {
143
+ const { store, config, runtime, active, input, signal } = params;
144
+ const person = store.getPerson(input.personId);
145
+ if (!person || person.status !== "active")
146
+ return jsonResult({ status: "not_found" });
147
+ const proposed = store.validateDossier(input.dossier);
148
+ const revision = store.getDossierRevision(input.personId);
149
+ if (signal?.aborted) {
150
+ return jsonResult({
151
+ status: "review_unavailable",
152
+ needsReview: true,
153
+ reason: "Cancelled; no dossier written",
154
+ });
155
+ }
156
+ const review = input.manualVerification
157
+ ? { status: "manual", needsReview: false, note: input.manualVerification }
158
+ : await reviewPersonDossier({
159
+ config,
160
+ runtime,
161
+ active,
162
+ person,
163
+ dossier: proposed,
164
+ agentName: input.agentName,
165
+ signal,
166
+ });
167
+ if (review.needsReview || signal?.aborted) {
168
+ return jsonResult({
169
+ status: review.status === "ok" && !signal?.aborted ? "needs_review" : "review_unavailable",
170
+ needsReview: true,
171
+ saved: false,
172
+ review,
173
+ });
174
+ }
175
+ const audit = review.status === "manual"
176
+ ? `Manual verification: ${review.note}`
177
+ : "Decision model review passed for every dossier assertion (person-interaction-v1)";
178
+ try {
179
+ const saved = store.replaceVerifiedDossier(input.personId, `${input.reason}\n${audit}`, proposed, audit, revision);
180
+ if (!saved)
181
+ return jsonResult({ status: "not_found" });
182
+ return jsonResult({
183
+ status: "ok",
184
+ saved: true,
185
+ changeId: saved.changeId,
186
+ verification: review.status === "manual" ? "manual" : "decision",
187
+ dossier: saved.dossier,
188
+ review,
189
+ });
190
+ }
191
+ catch (error) {
192
+ if (error instanceof DossierConflictError) {
193
+ return jsonResult({ status: "conflict", saved: false, reason: error.message });
194
+ }
195
+ throw error;
196
+ }
197
+ }
138
198
  function createInspectTool(stores, config, ctx) {
139
199
  const active = getContext(ctx);
140
200
  if (!active)
@@ -150,42 +210,45 @@ function createInspectTool(stores, config, ctx) {
150
210
  return jsonResult(personView(stores, active.agentId, input, config.whisperer.maxChars));
151
211
  }
152
212
  const store = stores.get(active.agentId);
153
- if (input.view === "people") {
154
- const limit = input.limit ?? 50;
155
- const offset = input.offset ?? 0;
156
- const people = store.listActivePeople(limit, offset, input.includeInactive ?? false).map((person) => {
157
- const dossierReviewedAt = store.getDossierReviewedAt(person.id);
158
- return {
159
- person,
160
- identities: store.listIdentities(person.id),
161
- hasDossier: dossierReviewedAt !== undefined,
162
- dossierReviewedAt: dossierReviewedAt ?? null,
163
- };
164
- });
165
- return jsonResult({
166
- status: "ok",
167
- people,
168
- nextOffset: people.length === limit ? offset + people.length : null,
169
- });
170
- }
171
- if (input.view === "dossier_changes") {
172
- const limit = input.limit ?? 20;
173
- const offset = input.offset ?? 0;
174
- const changes = store.listDossierChanges(input.personId, limit, offset);
175
- return jsonResult({
176
- status: "ok",
177
- changes,
178
- nextOffset: changes.length === limit ? offset + changes.length : null,
179
- });
180
- }
181
- if (input.view === "dossier_change") {
182
- const change = store.getDossierChange(input.personId, input.changeId);
183
- return jsonResult(change ? { status: "ok", change } : { status: "not_found" });
213
+ switch (input.view) {
214
+ case "people": {
215
+ const limit = input.limit ?? 50;
216
+ const offset = input.offset ?? 0;
217
+ const people = store.listActivePeople(limit, offset, input.includeInactive ?? false).map((person) => {
218
+ const dossierReviewedAt = store.getDossierReviewedAt(person.id);
219
+ return {
220
+ person,
221
+ identities: store.listIdentities(person.id),
222
+ hasDossier: dossierReviewedAt !== undefined,
223
+ dossierReviewedAt: dossierReviewedAt ?? null,
224
+ };
225
+ });
226
+ return jsonResult({
227
+ status: "ok",
228
+ people,
229
+ nextOffset: nextPageOffset(offset, people.length, limit),
230
+ });
231
+ }
232
+ case "dossier_changes": {
233
+ const limit = input.limit ?? 20;
234
+ const offset = input.offset ?? 0;
235
+ const changes = store.listDossierChanges(input.personId, limit, offset);
236
+ return jsonResult({
237
+ status: "ok",
238
+ changes,
239
+ nextOffset: nextPageOffset(offset, changes.length, limit),
240
+ });
241
+ }
242
+ case "dossier_change": {
243
+ const change = store.getDossierChange(input.personId, input.changeId);
244
+ return jsonResult(change ? { status: "ok", change } : { status: "not_found" });
245
+ }
246
+ case "todos":
247
+ return jsonResult({
248
+ status: "ok",
249
+ todos: store.listTodos(input.limit ?? 20),
250
+ });
184
251
  }
185
- return jsonResult({
186
- status: "ok",
187
- todos: store.listTodos(input.limit ?? 20),
188
- });
189
252
  },
190
253
  };
191
254
  }
@@ -201,65 +264,46 @@ function createUpdateTool(stores, config, runtime, ctx) {
201
264
  async execute(_toolCallId, raw, signal) {
202
265
  const input = Value.Parse(updateParameters, raw);
203
266
  const store = stores.get(active.agentId);
204
- if (input.action === "set_injection") {
205
- const person = store.setInjection(input.personId, input.enabled);
206
- return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
207
- }
208
- if (input.action === "replace_dossier") {
209
- const person = store.getPerson(input.personId);
210
- if (!person || person.status !== "active")
211
- return jsonResult({ status: "not_found" });
212
- const proposed = store.validateDossier(input.dossier);
213
- const revision = store.getDossierRevision(input.personId);
214
- if (signal?.aborted)
215
- return jsonResult({ status: "review_unavailable", needsReview: true, reason: "Cancelled; no dossier written" });
216
- const review = input.manualVerification
217
- ? { status: "manual", needsReview: false, note: input.manualVerification }
218
- : await reviewPersonDossier({ config, runtime, active, person, dossier: proposed, agentName: input.agentName, signal });
219
- if (review.needsReview || signal?.aborted) {
220
- return jsonResult({ status: review.status === "ok" && !signal?.aborted ? "needs_review" : "review_unavailable",
221
- needsReview: true, saved: false, review });
267
+ switch (input.action) {
268
+ case "set_injection": {
269
+ const person = store.setInjection(input.personId, input.enabled);
270
+ return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
222
271
  }
223
- const audit = review.status === "manual"
224
- ? `Manual verification: ${review.note}`
225
- : "TypeSafe review passed for every dossier assertion (person-interaction-v1)";
226
- try {
227
- const dossier = store.replaceDossier(input.personId, `${input.reason}\n${audit}`, proposed, revision);
228
- if (!dossier)
229
- return jsonResult({ status: "not_found" });
230
- const changeId = store.getDossierRevision(input.personId);
231
- store.recordDossierVerification(input.personId, changeId, audit);
232
- return jsonResult({ status: "ok", saved: true, changeId, verification: review.status === "manual" ? "manual" : "typesafe", dossier, review });
272
+ case "replace_dossier":
273
+ return handleReplaceDossier({ store, config, runtime, active, input, signal });
274
+ case "delete_dossier":
275
+ try {
276
+ return jsonResult(store.deleteDossier(input.personId, input.reason, input.expectedRevision)
277
+ ? { status: "ok" }
278
+ : { status: "not_found" });
279
+ }
280
+ catch (error) {
281
+ if (error instanceof DossierConflictError) {
282
+ return jsonResult({ status: "conflict", saved: false, reason: error.message });
283
+ }
284
+ throw error;
285
+ }
286
+ case "set_company": {
287
+ const company = store.setCompany(input.personId, {
288
+ name: input.companyName,
289
+ primaryDomain: input.primaryDomain,
290
+ });
291
+ const person = store.getPerson(input.personId);
292
+ return jsonResult(company && person ? { status: "ok", company, person } : { status: "not_found" });
233
293
  }
234
- catch (error) {
235
- if (error instanceof DossierConflictError)
236
- return jsonResult({ status: "conflict", saved: false, reason: error.message });
237
- throw error;
294
+ case "resolve_todo": {
295
+ const todo = store.resolveTodoByKey(input.deduplicationKey, input.note);
296
+ return jsonResult(todo ? { status: "ok", todo } : { status: "not_found" });
297
+ }
298
+ case "restore_person": {
299
+ const person = store.restorePerson(input.personId);
300
+ return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
301
+ }
302
+ case "soft_delete_person": {
303
+ const person = store.softDeletePerson(input.personId);
304
+ return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
238
305
  }
239
306
  }
240
- if (input.action === "delete_dossier") {
241
- return jsonResult(store.deleteDossier(input.personId, input.reason)
242
- ? { status: "ok" }
243
- : { status: "not_found" });
244
- }
245
- if (input.action === "set_company") {
246
- const company = store.setCompany(input.personId, {
247
- name: input.companyName,
248
- primaryDomain: input.primaryDomain,
249
- });
250
- const person = store.getPerson(input.personId);
251
- return jsonResult(company && person ? { status: "ok", company, person } : { status: "not_found" });
252
- }
253
- if (input.action === "resolve_todo") {
254
- const todo = store.resolveTodoByKey(input.deduplicationKey, input.note);
255
- return jsonResult(todo ? { status: "ok", todo } : { status: "not_found" });
256
- }
257
- if (input.action === "restore_person") {
258
- const person = store.restorePerson(input.personId);
259
- return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
260
- }
261
- const person = store.softDeletePerson(input.personId);
262
- return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
263
307
  },
264
308
  };
265
309
  }
@@ -21,7 +21,7 @@ import { registerMemoryTraining } from "./training-runtime.js";
21
21
  import { resolveTimezone } from "./session-projector.js";
22
22
  import { searchMemory } from "./memory-search.js";
23
23
  import { prepareQueryConversation, QueryInputBudgetError } from "./query-contract.js";
24
- import { resolveTypeSafeApiKey } from "./typesafe-client.js";
24
+ import { resolveDecisionCredential } from "./decision-client.js";
25
25
  import { abortedByTimeout } from "./abortable.js";
26
26
  import { registerExtraction } from "./extraction-runtime.js";
27
27
  import { registerPeopleLearning, registerPeopleLearningCli } from "./people-learning-runtime.js";
@@ -50,7 +50,7 @@ const searchParameters = Type.Object({
50
50
  conversationId: Type.Optional(Type.String({ pattern: "\\S" })),
51
51
  }, { additionalProperties: false, description: "Restricts session documents only; selected file corpora remain eligible. Not an audience access control." })),
52
52
  maxResults: Type.Optional(Type.Integer({ minimum: 1, maximum: 20, description: "Maximum hits; default 5." })),
53
- 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." })),
53
+ minUsefulness: Type.Optional(Type.Number({ minimum: 0, maximum: 1, description: "Minimum decision model usefulness probability; default 0.7. Not confidence in factual truth. Not applied to unjudged retrieval fallback." })),
54
54
  }, { additionalProperties: false });
55
55
  const getParameters = Type.Object({
56
56
  path: Type.String({ pattern: "\\S" }),
@@ -61,14 +61,14 @@ const syncSessionsParameters = Type.Object({
61
61
  force: Type.Optional(Type.Boolean()),
62
62
  }, { additionalProperties: false });
63
63
  const syncStatusParameters = Type.Object({}, { additionalProperties: false });
64
- function createSearchTool(runtime, ctx, typesafe, diagnostics) {
64
+ function createSearchTool(runtime, ctx, decisionModel, diagnostics) {
65
65
  const active = getContext(ctx);
66
66
  if (!active)
67
67
  return null;
68
68
  return {
69
69
  name: "memory_search",
70
70
  label: "Memory Search",
71
- 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.",
71
+ description: "Search this agent's memory corpora with BM25 and vector queries. The configured decision endpoint (Codex LB by default) receives the semantic query and candidate passages to rank usefulness. If judging is unavailable, returns unjudged retrieval leads without applying minUsefulness. Supply keywords in bm25Query and the information needed in vectorQuery. Skills are excluded. Inspect source context with memory_get. Empty results or errors do not prove absence of a fact.",
72
72
  parameters: searchParameters,
73
73
  async execute(_toolCallId, params, signal) {
74
74
  const started = performance.now();
@@ -82,7 +82,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
82
82
  const { conversation } = prepareQueryConversation([], queries.vec);
83
83
  let apiKey;
84
84
  try {
85
- apiKey = await resolveTypeSafeApiKey(typesafe);
85
+ apiKey = await resolveDecisionCredential(decisionModel);
86
86
  }
87
87
  catch { /* Explicit search can still return local evidence; never expose credential errors. */ }
88
88
  signal?.throwIfAborted();
@@ -95,7 +95,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
95
95
  sessionFilter,
96
96
  maxResults,
97
97
  minUsefulness,
98
- apiKey, timeoutMs: typesafe.timeoutMs, conversation, allowRetrievalFallback: true,
98
+ apiKey, endpoint: decisionModel.endpoint, model: decisionModel.model, timeoutMs: decisionModel.timeoutMs, conversation, allowRetrievalFallback: true,
99
99
  signal, timings: measurement,
100
100
  requestContext: active.requestContext,
101
101
  onCandidates: ({ retrievalMs, candidates, eligible }) => {
@@ -116,7 +116,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
116
116
  scoreMeaning: search.rankingMode === "retrieval" ? "retrieval_rank" : "usefulness_probability",
117
117
  minUsefulnessApplied: search.rankingMode !== "retrieval",
118
118
  ...(search.fallbackReason ? { fallbackReason: search.fallbackReason,
119
- 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." }
119
+ warning: "decision model usefulness ranking unavailable; returning unjudged retrieval-ranked leads. Scores are retrieval ranks, not usefulness probabilities; minUsefulness was not applied. Verify evidence with memory_get." }
120
120
  : search.requestsFailed ? { warning: `${search.requestsFailed} candidate usefulness judgments failed; results are partial` } : {}),
121
121
  results: search.results.map(({ source: _source, citation: _citation, vectorScore: _vectorScore, textScore: _textScore, session, sessionMessages, ...result }) => ({
122
122
  ...result,
@@ -313,19 +313,19 @@ function createAuditQualityTool(runtime, ctx, config) {
313
313
  return null;
314
314
  return {
315
315
  name: "memory_audit_quality", label: "Audit Memory Quality",
316
- description: "Audit a bounded page of approved indexed chunks using TypeSafe. Records review indicators in the maintenance inbox; never edits, deletes or suppresses source data. Continue with the returned next cursor; restart without after for a cached rescan.",
316
+ description: "Audit a bounded page of approved indexed chunks using decision model. Records review indicators in the maintenance inbox; never edits, deletes or suppresses source data. Continue with the returned next cursor; restart without after for a cached rescan.",
317
317
  parameters: auditQualityParameters,
318
318
  async execute(_toolCallId, params, signal) {
319
319
  const options = Value.Parse(auditQualityParameters, params);
320
- if (!config.qualityAudit.enabled || !config.typesafe.enabled)
320
+ if (!config.qualityAudit.enabled || !config.decisionModel.enabled)
321
321
  return jsonResult({ status: "disabled" });
322
322
  try {
323
- const context = await reviewRequestContext(runtime, active, config.typesafe, signal);
323
+ const context = await reviewRequestContext(runtime, active, config.decisionModel, signal);
324
324
  if (context.status !== "ready")
325
325
  return jsonResult(context);
326
326
  return jsonResult(await context.manager.auditQuality({
327
327
  ...options, corpora: config.qualityAudit.corpora, minNoise: config.qualityAudit.minNoise,
328
- apiKey: context.apiKey, timeoutMs: context.timeoutMs, signal: context.signal,
328
+ apiKey: context.apiKey, endpoint: context.endpoint, model: context.model, timeoutMs: context.timeoutMs, signal: context.signal,
329
329
  }));
330
330
  }
331
331
  catch {
@@ -495,8 +495,8 @@ export function registerUnblockMemory(api) {
495
495
  api.on("gateway_start", () => runtime.startSessionSyncSchedule(api.config, (error) => {
496
496
  api.logger.warn(`unblock-memory scheduled session sync could not start: ${String(error)}`);
497
497
  }));
498
- api.on("gateway_stop", () => runtime.stopSessionSyncSchedule());
499
498
  }
499
+ api.on("gateway_stop", () => runtime.close());
500
500
  let peopleWhisperer;
501
501
  const peopleStores = new PeopleStores({
502
502
  maxOpenTodos: config.people.todos.maxOpen,
@@ -517,13 +517,13 @@ export function registerUnblockMemory(api) {
517
517
  api.logger.warn('unblock-memory skillWhisperer.enabled is true but no corpus has kind "skills"; Skill Whisperer is inactive');
518
518
  }
519
519
  registerWhispererPrompt(api, {
520
- memory: registerMemoryWhisperer(api, runtime, config.memoryWhisperer, config.typesafe, diagnostics),
521
- skill: registerSkillWhisperer(api, runtime, config.skillWhisperer, config.typesafe, diagnostics),
520
+ memory: registerMemoryWhisperer(api, runtime, config.memoryWhisperer, config.decisionModel, diagnostics),
521
+ skill: registerSkillWhisperer(api, runtime, config.skillWhisperer, config.decisionModel, diagnostics),
522
522
  people: peopleWhisperer,
523
- myTurn: registerMyTurn(api, config.myTurn, config.typesafe, diagnostics),
523
+ myTurn: registerMyTurn(api, config.myTurn, config.decisionModel, diagnostics),
524
524
  safety: registerSafetyWhisperer(api, config, diagnostics),
525
525
  });
526
- api.registerTool((ctx) => createSearchTool(runtime, ctx, config.typesafe, diagnostics), { names: ["memory_search"] });
526
+ api.registerTool((ctx) => createSearchTool(runtime, ctx, config.decisionModel, diagnostics), { names: ["memory_search"] });
527
527
  api.registerTool((ctx) => createGetTool(runtime, ctx), { names: ["memory_get"] });
528
528
  api.registerTool((ctx) => createSyncSessionsTool(runtime, ctx), {
529
529
  names: ["memory_sync_sessions"],
@@ -13,6 +13,8 @@ export declare function auditQualityPage(params: {
13
13
  curation: CurationStore;
14
14
  sources: readonly ResolvedSource[];
15
15
  apiKey: string;
16
+ endpoint?: string;
17
+ model?: string;
16
18
  timeoutMs: number;
17
19
  minNoise: number;
18
20
  limit?: number;
@@ -1,6 +1,6 @@
1
1
  import { chunkFingerprint } from "./curation.js";
2
2
  import { parseSafeVirtualPath } from "./sources.js";
3
- import { judgeTypeSafeQuality, QUALITY_JUDGE_VERSION } from "./typesafe.js";
3
+ import { judgeQuality, qualityJudgeVersion } from "./decision-ranking.js";
4
4
  import { qualityTriage } from "./quality-triage.js";
5
5
  const MAX_CHUNK_CHARS = 6000;
6
6
  /** A formatting clue, never proof that JSON or structured data is worthless. */
@@ -29,6 +29,7 @@ export function qualityStructure(text) {
29
29
  }
30
30
  export async function auditQualityPage(params) {
31
31
  const { db, curation, signal } = params;
32
+ const policy = qualityJudgeVersion(params.model, params.endpoint);
32
33
  const sources = new Map(params.sources.filter(source => source.kind !== "skills")
33
34
  .map(source => [source.collection, source]));
34
35
  const groups = new Map();
@@ -37,7 +38,7 @@ export async function auditQualityPage(params) {
37
38
  const result = (status, done) => ({
38
39
  status, done, next, scanned, judged, cached, skippedOversized, skippedStale, flagged,
39
40
  groups: [...groups.values()].sort((a, b) => Number(b.triage === "preserve_evidence_repair") - Number(a.triage === "preserve_evidence_repair")),
40
- policy: QUALITY_JUDGE_VERSION,
41
+ policy,
41
42
  scope: "Indexed chunks only; not a whole-source audit. Findings are indicators, not permission to modify data.",
42
43
  });
43
44
  const check = () => {
@@ -74,7 +75,7 @@ export async function auditQualityPage(params) {
74
75
  const source = sources.get(row.collection);
75
76
  const text = row.doc.slice(row.pos, row.pos + row.chunk_len);
76
77
  const fingerprint = chunkFingerprint(text);
77
- const cacheKey = chunkFingerprint(JSON.stringify([QUALITY_JUDGE_VERSION, source.kind, fingerprint]));
78
+ const cacheKey = chunkFingerprint(JSON.stringify([policy, source.kind, fingerprint]));
78
79
  const eligible = Boolean(parseSafeVirtualPath(`qmd://${source.collection}/${row.path}`, sources)) && row.pos >= 0 && row.chunk_len > 0 &&
79
80
  row.pos + row.chunk_len <= row.doc.length;
80
81
  const structure = qualityStructure(text);
@@ -84,8 +85,8 @@ export async function auditQualityPage(params) {
84
85
  });
85
86
  const missing = [...new Map(batch.filter(item => item.eligible && item.text.length <= MAX_CHUNK_CHARS &&
86
87
  item.structure !== "empty" && !item.judgment).map(item => [item.cacheKey, item])).values()];
87
- const answers = await Promise.allSettled(missing.map(async (item) => (await judgeTypeSafeQuality({
88
- apiKey: params.apiKey, timeoutMs: params.timeoutMs, signal,
88
+ const answers = await Promise.allSettled(missing.map(async (item) => (await judgeQuality({
89
+ apiKey: params.apiKey, endpoint: params.endpoint, model: params.model, timeoutMs: params.timeoutMs, signal,
89
90
  chunks: [{ text: item.text, sourceKind: item.source.kind === "sessions" ? "sessions" : "files" }],
90
91
  }))[0]));
91
92
  check();
@@ -140,8 +141,8 @@ export async function auditQualityPage(params) {
140
141
  path: `qmd://${source.collection}/${row.path}`, from: startLine, to: endLine,
141
142
  excerpt: text.slice(0, 400), excerptTruncated: text.length > 400,
142
143
  indicator: structure === "empty" ? "deterministic_empty" :
143
- structure === "encoded_message" ? "deterministic_encoding" : "typesafe",
144
- ...judgment, policy: QUALITY_JUDGE_VERSION,
144
+ structure === "encoded_message" ? "deterministic_encoding" : "decision",
145
+ ...judgment, policy,
145
146
  triage,
146
147
  instruction: "Inspect original source and ingestion before acting. Verify source/index after any authorized repair. Never manually edit generated session projections.",
147
148
  }),
@@ -1,7 +1,7 @@
1
1
  import type { UnblockMemoryConfig } from "./config.js";
2
2
  import { type QueryConversation, type QueryPair } from "./query-contract.js";
3
3
  /** Preserve whole visible messages and the complete current request, never tool/thinking text. */
4
- export declare function queryConversation(prompt: string, messages: readonly unknown[]): QueryConversation;
4
+ export declare function queryConversation(prompt: string, messages: readonly unknown[], currentUserMessage?: string): QueryConversation;
5
5
  /** Deterministic query pair used when the resident query API fails or times out. */
6
6
  export declare function fallbackQueries(conversation: QueryConversation): QueryPair;
7
7
  /** Bound conversation context repeated across automatic passage usefulness judgments. */
@@ -2,12 +2,12 @@ import { randomUUID } from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { abortable, abortedByTimeout } from "./abortable.js";
4
4
  import { messageText } from "./whisperer-context.js";
5
- import { conversationUserText } from "./response-text.js";
5
+ import { CONVERSATION_INFO, queryUserText } from "./response-text.js";
6
6
  import { parseQueryPair, prepareQueryConversation } from "./query-contract.js";
7
- import { record } from "./guards.js";
7
+ import { nonBlank, record } from "./guards.js";
8
8
  /** Preserve whole visible messages and the complete current request, never tool/thinking text. */
9
- export function queryConversation(prompt, messages) {
10
- const currentRequest = conversationUserText(prompt)?.text ?? "";
9
+ export function queryConversation(prompt, messages, currentUserMessage) {
10
+ const currentRequest = queryUserText(currentUserMessage !== undefined ? currentUserMessage : prompt) ?? "";
11
11
  const visible = [];
12
12
  const assistantTexts = new Map();
13
13
  for (const item of messages) {
@@ -31,11 +31,17 @@ export function queryConversation(prompt, messages) {
31
31
  (mirror && record(message.openclawDeliveryMirror)?.kind === "channel-final-suppressed")))
32
32
  continue;
33
33
  const text = messageText(message);
34
- const raw = text?.role === "user" && typeof meta?.upstreamUserText === "string" ? meta.upstreamUserText : text?.text;
35
- const content = text?.role === "user" && raw ? conversationUserText(raw, meta?.senderId ?? message.senderId)?.text : raw;
34
+ const sender = nonBlank(meta?.senderId) ?? nonBlank(message.senderId);
35
+ const upstream = typeof meta?.upstreamUserText === "string" ? meta.upstreamUserText : undefined;
36
+ const content = text?.role === "user"
37
+ ? (upstream ? queryUserText(upstream, sender) : undefined) ??
38
+ // Fall back to canonical message.content only when upstreamUserText is absent or has a decorated non-envelope prefix,
39
+ // never to bypass a rejected Conversation info envelope.
40
+ (upstream && CONVERSATION_INFO.test(upstream.trim()) ? undefined : (text.text ? queryUserText(text.text, sender) : undefined))
41
+ : text?.text;
36
42
  if (message.role === "user") {
37
43
  assistantTexts.clear();
38
- if (!content || /^(?:\[OpenClaw heartbeat poll\]|\[Queued messages while agent was busy\]|\[Subagent Context\]|<relevant-memories>)/.test(content)) {
44
+ if (!content || /^(?:\[cron:|\[OpenClaw heartbeat poll\]|\[Inter-session message\]|\[Queued messages while agent was busy\]|\[Subagent Context\]|<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>|<relevant-memories>|<unblock_memory>|<conversation_context>)/.test(content)) {
39
45
  visible.length = 0;
40
46
  continue;
41
47
  }
@@ -50,7 +56,8 @@ export function queryConversation(prompt, messages) {
50
56
  }
51
57
  visible.push({ role: text.role, content });
52
58
  }
53
- if (visible.at(-1)?.role === "user" && visible.at(-1)?.content === currentRequest)
59
+ const last = visible.at(-1);
60
+ if (last?.role === "user" && last.content.replaceAll("\r\n", "\n") === currentRequest.replaceAll("\r\n", "\n"))
54
61
  visible.pop();
55
62
  return prepareQueryConversation(visible, currentRequest).conversation;
56
63
  }
@@ -1,6 +1,6 @@
1
1
  import type { UnblockMemoryConfig } from "./config.js";
2
2
  import type { ResolvedSource } from "./sources.js";
3
- export declare function responseCohort(config: UnblockMemoryConfig["responseAudit"]): string;
3
+ export declare function responseCohort(config: UnblockMemoryConfig["responseAudit"], model?: string, endpoint?: string): string;
4
4
  export type ResponseAuditOptions = {
5
5
  agentId: string;
6
6
  databasePath: string;