@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 { Type } from "typebox";
2
3
  import { Value } from "typebox/value";
3
4
  import { jsonResult } from "openclaw/plugin-sdk/agent-runtime";
@@ -21,7 +22,7 @@ import { registerMemoryTraining } from "./training-runtime.js";
21
22
  import { resolveTimezone } from "./session-projector.js";
22
23
  import { searchMemory } from "./memory-search.js";
23
24
  import { prepareQueryConversation, QueryInputBudgetError } from "./query-contract.js";
24
- import { resolveTypeSafeApiKey } from "./typesafe-client.js";
25
+ import { resolveDecisionCredential } from "./decision-client.js";
25
26
  import { abortedByTimeout } from "./abortable.js";
26
27
  import { registerExtraction } from "./extraction-runtime.js";
27
28
  import { registerPeopleLearning, registerPeopleLearningCli } from "./people-learning-runtime.js";
@@ -50,25 +51,25 @@ const searchParameters = Type.Object({
50
51
  conversationId: Type.Optional(Type.String({ pattern: "\\S" })),
51
52
  }, { additionalProperties: false, description: "Restricts session documents only; selected file corpora remain eligible. Not an audience access control." })),
52
53
  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." })),
54
+ 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
55
  }, { additionalProperties: false });
55
56
  const getParameters = Type.Object({
56
57
  path: Type.String({ pattern: "\\S" }),
57
58
  from: Type.Optional(Type.Integer({ minimum: 1, description: "First source line, 1-based; default 1. Use nextFrom from a truncated read to continue." })),
58
- lines: Type.Optional(Type.Integer({ minimum: 1, maximum: 1000, description: "Requested lines; default 120, also bounded by 12,000 content characters." })),
59
+ lines: Type.Optional(Type.Integer({ minimum: 1, maximum: DEFAULTS.memoryWhisperer.memoryGetMaxLines, description: `Requested lines; default 120, also bounded by ${DEFAULTS.memoryWhisperer.memoryGetMaxChars} content characters.` })),
59
60
  }, { additionalProperties: false });
60
61
  const syncSessionsParameters = Type.Object({
61
62
  force: Type.Optional(Type.Boolean()),
62
63
  }, { additionalProperties: false });
63
64
  const syncStatusParameters = Type.Object({}, { additionalProperties: false });
64
- function createSearchTool(runtime, ctx, typesafe, diagnostics) {
65
+ function createSearchTool(runtime, ctx, decisionModel, diagnostics) {
65
66
  const active = getContext(ctx);
66
67
  if (!active)
67
68
  return null;
68
69
  return {
69
70
  name: "memory_search",
70
71
  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.",
72
+ 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
73
  parameters: searchParameters,
73
74
  async execute(_toolCallId, params, signal) {
74
75
  const started = performance.now();
@@ -82,7 +83,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
82
83
  const { conversation } = prepareQueryConversation([], queries.vec);
83
84
  let apiKey;
84
85
  try {
85
- apiKey = await resolveTypeSafeApiKey(typesafe);
86
+ apiKey = await resolveDecisionCredential(decisionModel);
86
87
  }
87
88
  catch { /* Explicit search can still return local evidence; never expose credential errors. */ }
88
89
  signal?.throwIfAborted();
@@ -95,7 +96,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
95
96
  sessionFilter,
96
97
  maxResults,
97
98
  minUsefulness,
98
- apiKey, timeoutMs: typesafe.timeoutMs, conversation, allowRetrievalFallback: true,
99
+ apiKey, endpoint: decisionModel.endpoint, model: decisionModel.model, timeoutMs: decisionModel.timeoutMs, conversation, allowRetrievalFallback: true,
99
100
  signal, timings: measurement,
100
101
  requestContext: active.requestContext,
101
102
  onCandidates: ({ retrievalMs, candidates, eligible }) => {
@@ -116,7 +117,7 @@ function createSearchTool(runtime, ctx, typesafe, diagnostics) {
116
117
  scoreMeaning: search.rankingMode === "retrieval" ? "retrieval_rank" : "usefulness_probability",
117
118
  minUsefulnessApplied: search.rankingMode !== "retrieval",
118
119
  ...(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." }
120
+ 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
121
  : search.requestsFailed ? { warning: `${search.requestsFailed} candidate usefulness judgments failed; results are partial` } : {}),
121
122
  results: search.results.map(({ source: _source, citation: _citation, vectorScore: _vectorScore, textScore: _textScore, session, sessionMessages, ...result }) => ({
122
123
  ...result,
@@ -313,19 +314,19 @@ function createAuditQualityTool(runtime, ctx, config) {
313
314
  return null;
314
315
  return {
315
316
  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.",
317
+ 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
318
  parameters: auditQualityParameters,
318
319
  async execute(_toolCallId, params, signal) {
319
320
  const options = Value.Parse(auditQualityParameters, params);
320
- if (!config.qualityAudit.enabled || !config.typesafe.enabled)
321
+ if (!config.qualityAudit.enabled || !config.decisionModel.enabled)
321
322
  return jsonResult({ status: "disabled" });
322
323
  try {
323
- const context = await reviewRequestContext(runtime, active, config.typesafe, signal);
324
+ const context = await reviewRequestContext(runtime, active, config.decisionModel, signal);
324
325
  if (context.status !== "ready")
325
326
  return jsonResult(context);
326
327
  return jsonResult(await context.manager.auditQuality({
327
328
  ...options, corpora: config.qualityAudit.corpora, minNoise: config.qualityAudit.minNoise,
328
- apiKey: context.apiKey, timeoutMs: context.timeoutMs, signal: context.signal,
329
+ apiKey: context.apiKey, endpoint: context.endpoint, model: context.model, timeoutMs: context.timeoutMs, signal: context.signal,
329
330
  }));
330
331
  }
331
332
  catch {
@@ -456,7 +457,7 @@ export function resolveFlushPlan(params = {}) {
456
457
  return {
457
458
  softThresholdTokens: nonNegativeInteger(configured?.softThresholdTokens, 4000),
458
459
  forceFlushTranscriptBytes: parseByteSize(configured?.forceFlushTranscriptBytes) ?? 2 * 1024 * 1024,
459
- reserveTokensFloor: 20_000,
460
+ reserveTokensFloor: DEFAULTS.sqlite.flushReserveTokensFloor,
460
461
  ...(legacyModel ? { model: legacyModel } : {}),
461
462
  prompt: `Pre-compaction memory flush. Store durable memories only in ${target}. If it exists, append; never overwrite it or bootstrap files. Do not create timestamped variants. If nothing is durable, reply NO_REPLY.`,
462
463
  systemPrompt: `Capture durable memories in ${target}; append only and do not overwrite bootstrap files. Usually NO_REPLY is correct.`,
@@ -495,8 +496,8 @@ export function registerUnblockMemory(api) {
495
496
  api.on("gateway_start", () => runtime.startSessionSyncSchedule(api.config, (error) => {
496
497
  api.logger.warn(`unblock-memory scheduled session sync could not start: ${String(error)}`);
497
498
  }));
498
- api.on("gateway_stop", () => runtime.stopSessionSyncSchedule());
499
499
  }
500
+ api.on("gateway_stop", () => runtime.close());
500
501
  let peopleWhisperer;
501
502
  const peopleStores = new PeopleStores({
502
503
  maxOpenTodos: config.people.todos.maxOpen,
@@ -517,13 +518,13 @@ export function registerUnblockMemory(api) {
517
518
  api.logger.warn('unblock-memory skillWhisperer.enabled is true but no corpus has kind "skills"; Skill Whisperer is inactive');
518
519
  }
519
520
  registerWhispererPrompt(api, {
520
- memory: registerMemoryWhisperer(api, runtime, config.memoryWhisperer, config.typesafe, diagnostics),
521
- skill: registerSkillWhisperer(api, runtime, config.skillWhisperer, config.typesafe, diagnostics),
521
+ memory: registerMemoryWhisperer(api, runtime, config.memoryWhisperer, config.decisionModel, diagnostics),
522
+ skill: registerSkillWhisperer(api, runtime, config.skillWhisperer, config.decisionModel, diagnostics),
522
523
  people: peopleWhisperer,
523
- myTurn: registerMyTurn(api, config.myTurn, config.typesafe, diagnostics),
524
+ myTurn: registerMyTurn(api, config.myTurn, config.decisionModel, diagnostics),
524
525
  safety: registerSafetyWhisperer(api, config, diagnostics),
525
526
  });
526
- api.registerTool((ctx) => createSearchTool(runtime, ctx, config.typesafe, diagnostics), { names: ["memory_search"] });
527
+ api.registerTool((ctx) => createSearchTool(runtime, ctx, config.decisionModel, diagnostics), { names: ["memory_search"] });
527
528
  api.registerTool((ctx) => createGetTool(runtime, ctx), { names: ["memory_get"] });
528
529
  api.registerTool((ctx) => createSyncSessionsTool(runtime, ctx), {
529
530
  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,8 +1,9 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { chunkFingerprint } from "./curation.js";
2
3
  import { parseSafeVirtualPath } from "./sources.js";
3
- import { judgeTypeSafeQuality, QUALITY_JUDGE_VERSION } from "./typesafe.js";
4
+ import { judgeQuality, qualityJudgeVersion } from "./decision-ranking.js";
4
5
  import { qualityTriage } from "./quality-triage.js";
5
- const MAX_CHUNK_CHARS = 6000;
6
+ const MAX_CHUNK_CHARS = DEFAULTS.quality.gradeMaxChars;
6
7
  /** A formatting clue, never proof that JSON or structured data is worthless. */
7
8
  export function qualityStructure(text) {
8
9
  if (!text.trim())
@@ -29,6 +30,7 @@ export function qualityStructure(text) {
29
30
  }
30
31
  export async function auditQualityPage(params) {
31
32
  const { db, curation, signal } = params;
33
+ const policy = qualityJudgeVersion(params.model, params.endpoint);
32
34
  const sources = new Map(params.sources.filter(source => source.kind !== "skills")
33
35
  .map(source => [source.collection, source]));
34
36
  const groups = new Map();
@@ -37,7 +39,7 @@ export async function auditQualityPage(params) {
37
39
  const result = (status, done) => ({
38
40
  status, done, next, scanned, judged, cached, skippedOversized, skippedStale, flagged,
39
41
  groups: [...groups.values()].sort((a, b) => Number(b.triage === "preserve_evidence_repair") - Number(a.triage === "preserve_evidence_repair")),
40
- policy: QUALITY_JUDGE_VERSION,
42
+ policy,
41
43
  scope: "Indexed chunks only; not a whole-source audit. Findings are indicators, not permission to modify data.",
42
44
  });
43
45
  const check = () => {
@@ -74,7 +76,7 @@ export async function auditQualityPage(params) {
74
76
  const source = sources.get(row.collection);
75
77
  const text = row.doc.slice(row.pos, row.pos + row.chunk_len);
76
78
  const fingerprint = chunkFingerprint(text);
77
- const cacheKey = chunkFingerprint(JSON.stringify([QUALITY_JUDGE_VERSION, source.kind, fingerprint]));
79
+ const cacheKey = chunkFingerprint(JSON.stringify([policy, source.kind, fingerprint]));
78
80
  const eligible = Boolean(parseSafeVirtualPath(`qmd://${source.collection}/${row.path}`, sources)) && row.pos >= 0 && row.chunk_len > 0 &&
79
81
  row.pos + row.chunk_len <= row.doc.length;
80
82
  const structure = qualityStructure(text);
@@ -84,8 +86,8 @@ export async function auditQualityPage(params) {
84
86
  });
85
87
  const missing = [...new Map(batch.filter(item => item.eligible && item.text.length <= MAX_CHUNK_CHARS &&
86
88
  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,
89
+ const answers = await Promise.allSettled(missing.map(async (item) => (await judgeQuality({
90
+ apiKey: params.apiKey, endpoint: params.endpoint, model: params.model, timeoutMs: params.timeoutMs, signal,
89
91
  chunks: [{ text: item.text, sourceKind: item.source.kind === "sessions" ? "sessions" : "files" }],
90
92
  }))[0]));
91
93
  check();
@@ -138,10 +140,10 @@ export async function auditQualityPage(params) {
138
140
  path: row.path, reason, contentFingerprint: fingerprint,
139
141
  detail: JSON.stringify({
140
142
  path: `qmd://${source.collection}/${row.path}`, from: startLine, to: endLine,
141
- excerpt: text.slice(0, 400), excerptTruncated: text.length > 400,
143
+ excerpt: text.slice(0, DEFAULTS.quality.previewChars), excerptTruncated: text.length > DEFAULTS.quality.previewChars,
142
144
  indicator: structure === "empty" ? "deterministic_empty" :
143
- structure === "encoded_message" ? "deterministic_encoding" : "typesafe",
144
- ...judgment, policy: QUALITY_JUDGE_VERSION,
145
+ structure === "encoded_message" ? "deterministic_encoding" : "decision",
146
+ ...judgment, policy,
145
147
  triage,
146
148
  instruction: "Inspect original source and ingestion before acting. Verify source/index after any authorized repair. Never manually edit generated session projections.",
147
149
  }),
@@ -1,11 +1,12 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { chunkFingerprint } from "./curation.js";
2
3
  /** Routing hints only: low evidence is not permission to delete. */
3
4
  export function qualityTriage(noise, evidence, encodingDefect = false) {
4
- if (noise < 0.8 && !encodingDefect)
5
+ if (noise < DEFAULTS.quality.triageNoiseThreshold && !encodingDefect)
5
6
  return "context_review";
6
- if (evidence >= 0.8)
7
+ if (evidence >= DEFAULTS.quality.triageEvidenceHigh)
7
8
  return "preserve_evidence_repair";
8
- if (evidence <= 0.2)
9
+ if (evidence <= DEFAULTS.quality.triageEvidenceLow)
9
10
  return "inspect_scaffolding";
10
11
  return "context_review";
11
12
  }
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  import { readFile } from "node:fs/promises";
3
4
  import { abortable, abortedByTimeout } from "./abortable.js";
@@ -211,8 +212,10 @@ export class ApiQueryGenerator {
211
212
  this.config = config;
212
213
  }
213
214
  async generate(conversation, signal) {
214
- const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(10_000)]);
215
+ const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(DEFAULTS.memoryWhisperer.queryClientTimeoutMs)]);
215
216
  throwIfQueryAborted(requestSignal);
217
+ if (!this.config.endpoint)
218
+ throw new QueryApiError("unavailable");
216
219
  if (!this.config.apiKeyFile)
217
220
  throw new QueryApiError("credentials");
218
221
  let token;
@@ -257,7 +260,7 @@ export class ApiQueryGenerator {
257
260
  if (done)
258
261
  break;
259
262
  size += value.byteLength;
260
- if (size > 16_384)
263
+ if (size > DEFAULTS.memoryWhisperer.queryResponseMaxBytes)
261
264
  throw new QueryApiError("invalid_response");
262
265
  chunks.push(value);
263
266
  }
@@ -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;
@@ -1,14 +1,16 @@
1
+ import { DEFAULTS } from "./defaults.js";
2
+ import { setImmediate } from "node:timers/promises";
1
3
  import { abortable } from "./abortable.js";
2
- import { resolveTypeSafeApiKey, TYPESAFE_MODEL } from "./typesafe-client.js";
4
+ import { decisionModelScope, resolveDecisionCredential, DEFAULT_DECISION_MODEL } from "./decision-client.js";
3
5
  import { RESPONSE_EXTRACTOR_VERSION, ResponseTranscriptReader } from "./response-episodes.js";
4
- import { RESPONSE_RUBRIC_VERSION, RESPONSE_STAGE_VERSIONS, judgeMemoryOpportunity } from "./response-judge.js";
6
+ import { responseRubricVersion, RESPONSE_STAGE_VERSIONS, judgeMemoryOpportunity, } from "./response-judge.js";
5
7
  import { ResponseAuditStore } from "./response-store.js";
6
8
  import { responseMemoryCandidates } from "./response-memory.js";
7
9
  import { assessResponseStages } from "./response-stages.js";
8
10
  import { ResponsePeople } from "./response-identity.js";
9
11
  import { jsonHash } from "./json-hash.js";
10
- export function responseCohort(config) {
11
- return RESPONSE_RUBRIC_VERSION + ":" + jsonHash({
12
+ export function responseCohort(config, model = DEFAULT_DECISION_MODEL, endpoint) {
13
+ return responseRubricVersion(model, endpoint) + ":" + jsonHash({
12
14
  extractor: RESPONSE_EXTRACTOR_VERSION, historyMessages: config.historyMessages,
13
15
  stages: RESPONSE_STAGE_VERSIONS,
14
16
  sentimentEnabled: config.sentimentEnabled,
@@ -18,20 +20,20 @@ export function responseCohort(config) {
18
20
  /** All inference is outside memory's mutation queue and outside transcript DB transactions. */
19
21
  export async function auditResponses(options) {
20
22
  const { config, agentId } = options;
21
- if (!config.responseAudit.enabled || !config.typesafe.enabled)
23
+ if (!config.responseAudit.enabled || !config.decisionModel.enabled)
22
24
  return { status: "disabled" };
23
- const signal = AbortSignal.any([AbortSignal.timeout(120_000), ...(options.signal ? [options.signal] : [])]);
24
- const cohort = responseCohort(config.responseAudit);
25
+ const signal = AbortSignal.any([AbortSignal.timeout(DEFAULTS.responseAudit.deadlineMs), ...(options.signal ? [options.signal] : [])]);
26
+ const cohort = responseCohort(config.responseAudit, config.decisionModel.model, config.decisionModel.endpoint);
25
27
  let key;
26
28
  if (!options.dryRun) {
27
29
  try {
28
- key = await abortable(resolveTypeSafeApiKey(config.typesafe), signal);
30
+ key = await abortable(resolveDecisionCredential(config.decisionModel), signal);
29
31
  }
30
32
  catch {
31
33
  return { status: "unavailable", reason: "Credentials unavailable or audit cancelled" };
32
34
  }
33
35
  if (!key)
34
- return { status: "unavailable", reason: "TypeSafe API key not configured" };
36
+ return { status: "unavailable", reason: "Decision model API key not configured" };
35
37
  }
36
38
  let reader, store, lease;
37
39
  let people;
@@ -62,7 +64,7 @@ export async function auditResponses(options) {
62
64
  coverage.sessionLimitReached = sessions.length > 100;
63
65
  let stoppedForBudget = false;
64
66
  for (const session of sessions.slice(0, 100)) {
65
- await new Promise(resolve => setImmediate(resolve));
67
+ await setImmediate();
66
68
  signal.throwIfAborted();
67
69
  coverage.sessions++;
68
70
  const checkpoint = store?.checkpoint(cohort, session);
@@ -85,16 +87,14 @@ export async function auditResponses(options) {
85
87
  coverage.unchangedSessions++;
86
88
  coverage.cachedOrBackoff += work?.total ?? 0;
87
89
  if (checkpoint)
88
- for (const key of Object.keys(checkpoint.coverage))
89
- coverage[key] += checkpoint.coverage[key];
90
+ addCoverage(coverage, checkpoint.coverage);
90
91
  store?.advance(cohort, session);
91
92
  continue;
92
93
  }
93
94
  coverage.extractedSessions++;
94
95
  if (tracked.has(session))
95
96
  coverage.reconciledSessions++;
96
- for (const key of Object.keys(snapshot.coverage))
97
- coverage[key] += snapshot.coverage[key];
97
+ addCoverage(coverage, snapshot.coverage);
98
98
  const episodes = snapshot.episodes.filter(e => e.timestamp >= since);
99
99
  coverage.outsideLookback += snapshot.episodes.length - episodes.length;
100
100
  store?.observe(cohort, session, snapshot.episodes);
@@ -113,47 +113,47 @@ export async function auditResponses(options) {
113
113
  continue;
114
114
  }
115
115
  coverage.attempted++;
116
+ const existing = store.memoryRetryResult(cohort, e);
116
117
  store.attempted(cohort, e, Date.now());
117
118
  try {
118
- const params = { apiKey: key, timeoutMs: config.typesafe.timeoutMs, signal };
119
- const judgment = await abortable(assessResponseStages(store, cohort, e, params, config.responseAudit.sentimentEnabled, coverage), signal);
120
- let memory = { status: "not_requested", candidates: [] };
121
- if (judgment.feedback.memoryGap.noul >= 0.8 && config.responseAudit.memoryCorpora.length) {
122
- try {
123
- const approved = options.sources.filter(s => config.responseAudit.memoryCorpora.includes(s.corpus));
124
- const candidates = responseMemoryCandidates(options.indexPath, approved, e);
125
- const memoryKey = jsonHash([TYPESAFE_MODEL, RESPONSE_STAGE_VERSIONS.memory,
126
- e.id, e.session, e.senderId, e.request, e.answer, e.feedback, candidates,
127
- [...config.responseAudit.memoryCorpora].sort()]);
128
- let judged = store.stage(cohort, e, "memory", memoryKey);
129
- if (judged)
130
- coverage.stageCacheHits++;
131
- else {
132
- store.stageBegin([memoryKey], Date.now());
133
- coverage.stageAttempts++;
134
- judged = await abortable(judgeMemoryOpportunity(e, candidates, params), signal);
135
- store.stageSave(memoryKey, judged, Date.now());
136
- }
137
- memory = { status: "checked", candidates: judged };
119
+ const params = {
120
+ apiKey: key, endpoint: config.decisionModel.endpoint, model: config.decisionModel.model,
121
+ timeoutMs: config.decisionModel.timeoutMs, signal,
122
+ };
123
+ const result = existing
124
+ ? {
125
+ ...existing,
126
+ memory: await assessMemoryOpportunity(store, cohort, e, existing.feedback, options, params, coverage),
138
127
  }
139
- catch {
140
- memory = { status: "unavailable", candidates: [] };
141
- }
142
- }
128
+ : await (async () => {
129
+ const judgment = await abortable(assessResponseStages(store, cohort, e, params, config.responseAudit.sentimentEnabled, coverage), signal);
130
+ const memory = await assessMemoryOpportunity(store, cohort, e, judgment.feedback, options, params, coverage);
131
+ return {
132
+ ...judgment,
133
+ human: people.resolve(e),
134
+ references: references(e),
135
+ agentModel: e.model,
136
+ contextLimited: e.contextLimited,
137
+ memorySearchCalls: e.memorySearchCalls,
138
+ memory,
139
+ };
140
+ })();
143
141
  signal.throwIfAborted();
144
142
  const fresh = reader.read(session, config.responseAudit, snapshot.revision);
145
- if (!fresh || !("unchanged" in fresh) && !fresh.episodes.some(candidate => candidate.id === e.id && candidate.inputHash === e.inputHash)) {
143
+ if (!fresh || (!("unchanged" in fresh) && !fresh.episodes.some(candidate => candidate.id === e.id && candidate.inputHash === e.inputHash))) {
146
144
  coverage.stale++;
147
145
  store.stale(cohort, e);
148
- if (fresh !== undefined && (!fresh || !("unchanged" in fresh))) {
146
+ if (fresh !== undefined) {
149
147
  store.observe(cohort, session, fresh?.episodes ?? []);
150
148
  store.checkpointForget(cohort, session);
151
149
  }
152
150
  break;
153
151
  }
154
- store.save(cohort, e, { ...judgment, human: people.resolve(e), references: references(e), agentModel: e.model,
155
- contextLimited: e.contextLimited, memorySearchCalls: e.memorySearchCalls, memory }, Date.now());
156
- coverage.evaluated++;
152
+ store.save(cohort, e, result, Date.now());
153
+ if (existing && result.memory.status === "unavailable")
154
+ coverage.failed++;
155
+ else
156
+ coverage.evaluated++;
157
157
  }
158
158
  catch {
159
159
  coverage.failed++;
@@ -162,7 +162,7 @@ export async function auditResponses(options) {
162
162
  }
163
163
  }
164
164
  // Let stop/cancellation handlers run between bounded synchronous session reads.
165
- await new Promise(resolve => setImmediate(resolve));
165
+ await setImmediate();
166
166
  store?.advance(cohort, session);
167
167
  if (coverage.attempted >= config.responseAudit.maxEpisodes && session !== sessions.at(-1)) {
168
168
  stoppedForBudget = true;
@@ -188,6 +188,40 @@ export async function auditResponses(options) {
188
188
  people?.close();
189
189
  }
190
190
  }
191
+ function addCoverage(target, delta) {
192
+ for (const key of Object.keys(delta))
193
+ target[key] += delta[key];
194
+ }
195
+ async function assessMemoryOpportunity(store, cohort, e, feedback, options, params, usage) {
196
+ if (feedback.memoryGap.noul < DEFAULTS.responseAudit.scoreHigh || !options.config.responseAudit.memoryCorpora.length) {
197
+ return { status: "not_requested", candidates: [] };
198
+ }
199
+ try {
200
+ const approved = options.sources.filter(s => options.config.responseAudit.memoryCorpora.includes(s.corpus));
201
+ const candidates = responseMemoryCandidates(options.indexPath, approved, e);
202
+ const memoryKey = jsonHash([
203
+ decisionModelScope(options.config.decisionModel.model, options.config.decisionModel.endpoint),
204
+ RESPONSE_STAGE_VERSIONS.memory,
205
+ e.id, e.session, e.senderId, e.request, e.answer, e.feedback, candidates,
206
+ [...options.config.responseAudit.memoryCorpora].sort(),
207
+ ]);
208
+ let judged = store.stage(cohort, e, "memory", memoryKey, candidates);
209
+ if (judged)
210
+ usage.stageCacheHits++;
211
+ else {
212
+ store.stageBegin([memoryKey], Date.now());
213
+ usage.stageAttempts++;
214
+ judged = await abortable(judgeMemoryOpportunity(e, candidates, params), params.signal);
215
+ store.stageSave(memoryKey, judged, Date.now());
216
+ }
217
+ return { status: "checked", candidates: judged };
218
+ }
219
+ catch {
220
+ if (params.signal.aborted)
221
+ throw new Error("Audit cancelled");
222
+ return { status: "unavailable", candidates: [] };
223
+ }
224
+ }
191
225
  function references(e) {
192
226
  return { sessionId: e.session.sessionId, request: e.request.map(m => m.seq), answer: e.answer.map(m => m.seq),
193
227
  feedback: e.feedback.map(m => m.seq), followup: e.followup.messages.map(m => m.seq), inputHash: e.inputHash };
@@ -1,6 +1,8 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  export function resolveResponseAudit(value, corpora) {
2
3
  const defaults = { enabled: false, sentimentEnabled: true, senderIds: [], chatTypes: ["direct"],
3
- historyMessages: 6, lookbackDays: 30, maxEpisodes: 20, intervalMinutes: 60, memoryCorpora: [] };
4
+ historyMessages: DEFAULTS.responseAudit.defaultHistoryMessages, lookbackDays: DEFAULTS.responseAudit.defaultLookbackDays,
5
+ maxEpisodes: DEFAULTS.responseAudit.defaultMaxEpisodes, intervalMinutes: DEFAULTS.responseAudit.defaultIntervalMinutes, memoryCorpora: [] };
4
6
  if (value === undefined)
5
7
  return defaults;
6
8
  if (!value || typeof value !== "object" || Array.isArray(value))
@@ -1,5 +1,5 @@
1
1
  import type { ResponseAuditConfig } from "./response-config.js";
2
- export declare const RESPONSE_EXTRACTOR_VERSION = 6;
2
+ export declare const RESPONSE_EXTRACTOR_VERSION = 7;
3
3
  type Row = {
4
4
  seq: number;
5
5
  eventJson: string;
@@ -1,11 +1,12 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { DatabaseSync } from "node:sqlite";
2
3
  import { AgentTranscriptReader } from "./agent-transcript.js";
3
4
  import { messageText } from "./whisperer-context.js";
4
5
  import { responseUserText } from "./response-text.js";
5
6
  import { jsonHash } from "./json-hash.js";
6
7
  import { record } from "./guards.js";
7
- export const RESPONSE_EXTRACTOR_VERSION = 6;
8
- const MAX_EVENTS = 2000, MAX_SESSION_BYTES = 2_000_000, MAX_EPISODE_CHARS = 24_000;
8
+ export const RESPONSE_EXTRACTOR_VERSION = 7;
9
+ const { maxSessionEvents: MAX_EVENTS, maxSessionBytes: MAX_SESSION_BYTES, maxEpisodeChars: MAX_EPISODE_CHARS } = DEFAULTS.responseAudit;
9
10
  /** Never deduce human identity from text or the user role alone. */
10
11
  export function responseEpisodes(session, rows, config) {
11
12
  const coverage = { completedResponses: 0, eligible: 0, noFeedback: 0,
@@ -50,6 +51,7 @@ export function responseEpisodes(session, rows, config) {
50
51
  current = undefined;
51
52
  };
52
53
  const boundary = () => { closeFollowup(false); finish(false); history = []; historyDropped = false; pending = []; };
54
+ const filterOut = () => { coverage.filteredEvents++; boundary(); };
53
55
  const remember = (text) => {
54
56
  history.push(text);
55
57
  if (history.length > config.historyMessages) {
@@ -63,8 +65,7 @@ export function responseEpisodes(session, rows, config) {
63
65
  e = record(JSON.parse(row.eventJson));
64
66
  }
65
67
  catch {
66
- coverage.filteredEvents++;
67
- boundary();
68
+ filterOut();
68
69
  continue;
69
70
  }
70
71
  if (e?.type !== "message") {
@@ -87,15 +88,13 @@ export function responseEpisodes(session, rows, config) {
87
88
  if (m.provenance !== undefined || !human ||
88
89
  typeof senderId !== "string" || !config.senderIds.includes(senderId) ||
89
90
  transport?.channel !== "slack" || transport.conversationRef !== session.conversationId) {
90
- coverage.filteredEvents++;
91
- boundary();
91
+ filterOut();
92
92
  continue;
93
93
  }
94
94
  const raw = typeof meta?.upstreamUserText === "string" ? meta.upstreamUserText : messageText(m)?.text;
95
95
  const visible = raw ? responseUserText(raw, senderId) : undefined;
96
96
  if (!visible) {
97
- coverage.filteredEvents++;
98
- boundary();
97
+ filterOut();
99
98
  continue;
100
99
  }
101
100
  const thread = typeof transport.threadId === "string" ? transport.threadId : "";
@@ -116,20 +115,21 @@ export function responseEpisodes(session, rows, config) {
116
115
  continue;
117
116
  }
118
117
  if (m.role !== "assistant") {
119
- coverage.filteredEvents++;
120
- boundary();
118
+ filterOut();
121
119
  continue;
122
120
  }
123
121
  if (m.provenance !== undefined || meta?.turnTainted === true) {
124
- coverage.filteredEvents++;
125
- boundary();
122
+ filterOut();
126
123
  continue;
127
124
  }
128
125
  if (m.provider === "openclaw" && (m.model === "delivery-mirror" || m.model === "gateway-injected")) {
129
126
  // Preserve only preceding clean assistant evidence, never the synthetic notice.
130
127
  // This is not a completed response and cannot enter the original quality grade.
131
128
  closeFollowup(true, true);
132
- coverage.filteredEvents++;
129
+ filterOut();
130
+ continue;
131
+ }
132
+ if (m.stopReason === "error" || m.stopReason === "aborted") {
133
133
  boundary();
134
134
  continue;
135
135
  }
@@ -144,10 +144,6 @@ export function responseEpisodes(session, rows, config) {
144
144
  }
145
145
  if (!current)
146
146
  continue;
147
- if (meta?.turnTainted === true || m.stopReason === "error" || m.stopReason === "aborted") {
148
- boundary();
149
- continue;
150
- }
151
147
  if (Array.isArray(m.content)) {
152
148
  current.memorySearchCalls += m.content.filter(p => {
153
149
  const block = record(p);
@@ -162,7 +158,7 @@ export function responseEpisodes(session, rows, config) {
162
158
  remember(item);
163
159
  current.model = typeof m.model === "string" ? m.model : "unknown";
164
160
  current.timestamp = row.createdAt;
165
- current.final = meta?.runTerminal === true || (m.stopReason === "stop" && m.channel !== "commentary");
161
+ current.final ||= meta?.runTerminal === true || (m.stopReason === "stop" && m.channel !== "commentary");
166
162
  }
167
163
  if (current?.final)
168
164
  closeFollowup(true);
@@ -180,7 +176,7 @@ export class ResponseTranscriptReader {
180
176
  constructor(path, agentId) {
181
177
  this.#db = new DatabaseSync(path, { readOnly: true });
182
178
  try {
183
- this.#db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000");
179
+ this.#db.exec(`PRAGMA query_only=ON; PRAGMA busy_timeout=${DEFAULTS.sqlite.readerBusyTimeoutMs}`);
184
180
  this.#transcripts = new AgentTranscriptReader(this.#db, agentId, "Unsupported response-audit transcript schema or agent");
185
181
  }
186
182
  catch (error) {
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { existsSync } from "node:fs";
2
3
  import { basename, dirname, join } from "node:path";
3
4
  import { DatabaseSync } from "node:sqlite";
@@ -13,7 +14,7 @@ export class ResponsePeople {
13
14
  return;
14
15
  try {
15
16
  this.#db = new DatabaseSync(path, { readOnly: true });
16
- this.#db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=1000");
17
+ this.#db.exec(`PRAGMA query_only=ON; PRAGMA busy_timeout=${DEFAULTS.sqlite.readerBusyTimeoutMs}`);
17
18
  }
18
19
  catch {
19
20
  this.#db?.close();