@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
@@ -1,14 +1,11 @@
1
- import { createHash } from "node:crypto";
2
1
  import { DatabaseSync } from "node:sqlite";
3
2
  import { AgentTranscriptReader } from "./agent-transcript.js";
4
3
  import { messageText } from "./whisperer-context.js";
5
4
  import { responseUserText } from "./response-text.js";
5
+ import { jsonHash } from "./json-hash.js";
6
+ import { record } from "./guards.js";
6
7
  export const RESPONSE_EXTRACTOR_VERSION = 6;
7
8
  const MAX_EVENTS = 2000, MAX_SESSION_BYTES = 2_000_000, MAX_EPISODE_CHARS = 24_000;
8
- function record(v) {
9
- return v !== null && typeof v === "object" && !Array.isArray(v) ? v : undefined;
10
- }
11
- const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
12
9
  /** Never deduce human identity from text or the user role alone. */
13
10
  export function responseEpisodes(session, rows, config) {
14
11
  const coverage = { completedResponses: 0, eligible: 0, noFeedback: 0,
@@ -44,7 +41,7 @@ export function responseEpisodes(session, rows, config) {
44
41
  coverage.oversized++;
45
42
  else {
46
43
  const { final: _final, ...content } = current;
47
- const id = hash([session.sessionId, current.answer.at(-1).seq]);
44
+ const id = jsonHash([session.sessionId, current.answer.at(-1).seq]);
48
45
  const episode = { id, inputHash: "", session, ...content, followup: { status: "pending", messages: [] } };
49
46
  episodes.push(episode);
50
47
  followupTarget = episode;
@@ -172,7 +169,7 @@ export function responseEpisodes(session, rows, config) {
172
169
  finish(false); // No next assistant turn: the feedback block may still grow.
173
170
  for (const episode of episodes) {
174
171
  const { inputHash: _hash, session: s, ...content } = episode;
175
- episode.inputHash = hash([RESPONSE_EXTRACTOR_VERSION, s.sessionId, s.accountId, s.chatType, s.conversationId, content]);
172
+ episode.inputHash = jsonHash([RESPONSE_EXTRACTOR_VERSION, s.sessionId, s.accountId, s.chatType, s.conversationId, content]);
176
173
  }
177
174
  return { episodes, coverage };
178
175
  }
@@ -261,7 +258,7 @@ export class ResponseTranscriptReader {
261
258
  const rows = snapshot.rows;
262
259
  // Exact active content catches in-place edits and branch changes even when writer
263
260
  // watermarks are absent. Raw text is never retained in the checkpoint database.
264
- const revision = hash([RESPONSE_EXTRACTOR_VERSION, session, config.historyMessages, [...config.senderIds].sort(), rows]);
261
+ const revision = jsonHash([RESPONSE_EXTRACTOR_VERSION, session, config.historyMessages, [...config.senderIds].sort(), rows]);
265
262
  if (revision === previousRevision)
266
263
  return { unchanged: true, revision };
267
264
  return { ...responseEpisodes(session, rows, config), revision };
@@ -1,8 +1,7 @@
1
1
  import { Type } from "typebox";
2
2
  import { Value } from "typebox/value";
3
- import { requestTypeSafe, TYPESAFE_NOUL_SCHEMA as noul } from "./typesafe-client.js";
4
- import { TYPESAFE_REVIEW_MODEL } from "./typesafe-review.js";
5
- export const RESPONSE_RUBRIC_VERSION = `${TYPESAFE_REVIEW_MODEL}:response-v10`;
3
+ import { requestTypeSafe, TYPESAFE_MODEL, TYPESAFE_NOUL_SCHEMA as noul } from "./typesafe-client.js";
4
+ export const RESPONSE_RUBRIC_VERSION = `${TYPESAFE_MODEL}:response-v10`;
6
5
  export const RESPONSE_STAGE_VERSIONS = { quality: "quality-v9", feedback: "feedback-v9", sentiment: "sentiment-v10", retrospective: "retrospective-v9", memory: "memory-v2-isolated" };
7
6
  const probability = Type.Number({ minimum: 0, maximum: 1 });
8
7
  const score = Type.Object({ type: Type.Literal("score"), score: Type.Number({ minimum: 0, maximum: 3 }),
@@ -1,5 +1,7 @@
1
- import { createHash, randomUUID } from "node:crypto";
1
+ import { randomUUID } from "node:crypto";
2
2
  import { responseOutcome } from "./response-outcome.js";
3
+ import { immediateTransaction } from "./memory-database.js";
4
+ import { jsonHash } from "./json-hash.js";
3
5
  export const RESPONSE_REVIEW_POLICY = "response-review-v2";
4
6
  /** Operator-only tasks, intentionally not exposed as memory-curation agent tools. */
5
7
  export class ResponseReviews {
@@ -40,7 +42,7 @@ export class ResponseReviews {
40
42
  ];
41
43
  for (const s of signals) {
42
44
  const humanKey = result.human?.key ?? "unknown";
43
- const id = createHash("sha256").update(JSON.stringify([episodeId, s.family, humanKey])).digest("hex");
45
+ const id = jsonHash([episodeId, s.family, humanKey]);
44
46
  this.db.prepare(`INSERT INTO response_review_tasks(id,episode_id,family,human_key,created_at,updated_at) VALUES(?,?,?,?,?,?)
45
47
  ON CONFLICT(id) DO UPDATE SET updated_at=excluded.updated_at`).run(id, episodeId, s.family, humanKey, now, now);
46
48
  this.db.prepare(`INSERT INTO response_review_evidence VALUES(?,?,?,1,?) ON CONFLICT(task_id,cohort)
@@ -51,8 +53,7 @@ export class ResponseReviews {
51
53
  DO UPDATE SET input_hash=excluded.input_hash,policy=excluded.policy`).run(cohort, episodeId, inputHash, RESPONSE_REVIEW_POLICY);
52
54
  }
53
55
  refresh(cohort, since) {
54
- this.db.exec("BEGIN IMMEDIATE");
55
- try {
56
+ return immediateTransaction(this.db, () => {
56
57
  const rows = this.db.prepare(`SELECT r.id,r.input_hash,r.result FROM response_results r
57
58
  LEFT JOIN response_review_versions v ON v.cohort=r.cohort AND v.episode_id=r.id
58
59
  WHERE r.cohort=? AND r.active=1 AND r.status='ok' AND r.episode_at>=?
@@ -60,13 +61,8 @@ export class ResponseReviews {
60
61
  .all(cohort, since, RESPONSE_REVIEW_POLICY);
61
62
  for (const row of rows)
62
63
  this.sync(cohort, String(row.id), String(row.input_hash), JSON.parse(String(row.result)), Date.now());
63
- this.db.exec("COMMIT");
64
64
  return rows.length;
65
- }
66
- catch (error) {
67
- this.db.exec("ROLLBACK");
68
- throw error;
69
- }
65
+ });
70
66
  }
71
67
  reconcile(cohort, sessionId) {
72
68
  this.db.prepare(`UPDATE response_review_evidence AS e SET active=CASE WHEN EXISTS (
@@ -92,18 +88,12 @@ export class ResponseReviews {
92
88
  throw new Error("Invalid response review decision");
93
89
  if (!this.list(cohort, id).length)
94
90
  throw new Error("Unknown response review task in current cohort");
95
- this.db.exec("BEGIN IMMEDIATE");
96
- try {
91
+ immediateTransaction(this.db, () => {
97
92
  this.db.prepare("UPDATE response_review_tasks SET status=?,reviewer_kind=?,resolution_note=?,updated_at=? WHERE id=?")
98
93
  .run(status, reviewer, note.trim(), now, id);
99
94
  this.db.prepare("INSERT INTO response_review_decisions(task_id,status,reviewer_kind,note,decided_at) VALUES(?,?,?,?,?)")
100
95
  .run(id, status, reviewer, note.trim(), now);
101
- this.db.exec("COMMIT");
102
- }
103
- catch (error) {
104
- this.db.exec("ROLLBACK");
105
- throw error;
106
- }
96
+ });
107
97
  }
108
98
  annotate(occurredAt, kind, note) {
109
99
  if (!Number.isFinite(occurredAt) || !["model", "prompt", "deployment", "other"].includes(kind) || !note.trim() || note.length > 4000)
@@ -1,20 +1,21 @@
1
1
  import { hasMemoryTable, MEMORY_DATABASE } from "./memory-database.js";
2
2
  import { join } from "node:path";
3
- import { resolveAgentDir, resolveAgentWorkspaceDir, resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
3
+ import { resolveAgentWorkspaceDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
4
4
  import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
5
5
  import { normalizeAgentIdStrict } from "openclaw/plugin-sdk/routing";
6
6
  import { resolveSources } from "./sources.js";
7
7
  import { auditResponses, responseCohort } from "./response-audit.js";
8
8
  import { ResponseAuditStore } from "./response-store.js";
9
9
  import { dateOption } from "./date-option.js";
10
+ import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
10
11
  export function registerResponseAudit(api, config) {
11
12
  const options = (cfg, id) => {
12
13
  const normalized = normalizeAgentIdStrict(id);
13
14
  if (!normalized.ok || !listAgentIds(cfg).includes(normalized.value))
14
15
  throw new Error("Unknown response-audit agent");
15
16
  const agentId = normalized.value;
16
- const state = join(resolveStateDir(), "agents", agentId, "unblock-memory");
17
- return { agentId, config, databasePath: join(resolveAgentDir(cfg, agentId), "openclaw-agent.sqlite"),
17
+ const state = agentStateDir(agentId);
18
+ return { agentId, config, databasePath: agentTranscriptDatabase(cfg, agentId),
18
19
  storePath: join(state, MEMORY_DATABASE), indexPath: join(state, "index.sqlite"),
19
20
  peoplePath: join(state, MEMORY_DATABASE),
20
21
  sources: resolveSources(resolveAgentWorkspaceDir(cfg, agentId), config.corpora.filter(c => c.kind === "files")
@@ -1,14 +1,14 @@
1
- import { createHash } from "node:crypto";
2
1
  import { RESPONSE_EXTRACTOR_VERSION } from "./response-episodes.js";
3
2
  import { judgeResponse, judgeResponseFollowup, RESPONSE_STAGE_VERSIONS } from "./response-judge.js";
4
- import { TYPESAFE_REVIEW_MODEL } from "./typesafe-review.js";
3
+ import { TYPESAFE_MODEL } from "./typesafe-client.js";
4
+ import { jsonHash } from "./json-hash.js";
5
5
  export async function assessResponseStages(store, cohort, e, params, sentimentEnabled, usage) {
6
6
  const original = { before: e.before, request: e.request, answer: e.answer, contextLimited: e.contextLimited };
7
7
  const feedback = { ...original, feedback: e.feedback };
8
8
  const evidence = { quality: original, feedback, sentiment: feedback, retrospective: { ...feedback, followup: e.followup } };
9
9
  const keys = Object.fromEntries(Object.keys(evidence).map(stage => [stage,
10
- createHash("sha256").update(JSON.stringify([RESPONSE_EXTRACTOR_VERSION, TYPESAFE_REVIEW_MODEL, RESPONSE_STAGE_VERSIONS[stage],
11
- e.id, e.session, e.senderId, e.thread, evidence[stage]])).digest("hex"),
10
+ jsonHash([RESPONSE_EXTRACTOR_VERSION, TYPESAFE_MODEL, RESPONSE_STAGE_VERSIONS[stage],
11
+ e.id, e.session, e.senderId, e.thread, evidence[stage]]),
12
12
  ]));
13
13
  const cache = {
14
14
  quality: store.stage(cohort, e, "quality", keys.quality),
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { openMemoryDatabase } from "./memory-database.js";
2
+ import { immediateTransaction, openMemoryDatabase } from "./memory-database.js";
3
3
  import { responseOutcome, RESPONSE_REPORT_VERSION } from "./response-outcome.js";
4
4
  import { ResponsePeople } from "./response-identity.js";
5
5
  import { ResponseReviews, RESPONSE_REVIEW_POLICY } from "./response-reviews.js";
@@ -46,20 +46,14 @@ export class ResponseAuditStore {
46
46
  }
47
47
  /** Claim one bounded scheduled attempt, never replay every missed interval. */
48
48
  claimScheduled(now, intervalMs) {
49
- this.#db.exec("BEGIN IMMEDIATE");
50
- try {
49
+ return immediateTransaction(this.#db, () => {
51
50
  this.#db.prepare(`INSERT INTO response_schedule VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET
52
51
  next_due=next_due + excluded.interval_ms - interval_ms, interval_ms=excluded.interval_ms`)
53
52
  .run(intervalMs, now + intervalMs);
54
53
  const claimed = this.#db.prepare("UPDATE response_schedule SET next_due=? WHERE id=1 AND next_due<=?")
55
54
  .run(now + intervalMs, now).changes > 0;
56
- this.#db.exec("COMMIT");
57
55
  return claimed;
58
- }
59
- catch (error) {
60
- this.#db.exec("ROLLBACK");
61
- throw error;
62
- }
56
+ });
63
57
  }
64
58
  acquire(now) {
65
59
  const token = randomUUID();
@@ -74,8 +68,7 @@ export class ResponseAuditStore {
74
68
  WHERE cohort=? AND active=1 AND episode_at>=? ORDER BY session_id`).all(cohort, since).map(row => String(row.session_id));
75
69
  }
76
70
  observe(cohort, sessionId, episodes) {
77
- this.#db.exec("BEGIN IMMEDIATE");
78
- try {
71
+ immediateTransaction(this.#db, () => {
79
72
  this.#db.prepare("UPDATE response_results SET active=0 WHERE cohort=? AND session_id=?").run(cohort, sessionId);
80
73
  const insert = this.#db.prepare(`INSERT INTO response_results(cohort,id,session_id,input_hash,episode_at,active,status)
81
74
  VALUES(?,?,?,?,?,1,'pending') ON CONFLICT(cohort,id) DO UPDATE SET active=1,
@@ -88,12 +81,7 @@ export class ResponseAuditStore {
88
81
  for (const e of episodes)
89
82
  insert.run(cohort, e.id, sessionId, e.inputHash, e.timestamp);
90
83
  this.reviews.reconcile(cohort, sessionId);
91
- this.#db.exec("COMMIT");
92
- }
93
- catch (error) {
94
- this.#db.exec("ROLLBACK");
95
- throw error;
96
- }
84
+ });
97
85
  }
98
86
  needsJudgment(cohort, e, now) {
99
87
  const row = this.#db.prepare("SELECT status,attempts,attempted_at FROM response_results WHERE cohort=? AND id=? AND input_hash=? AND active=1")
@@ -111,18 +99,12 @@ export class ResponseAuditStore {
111
99
  }
112
100
  save(cohort, e, result, now) {
113
101
  result = { ...result, human: result.human ?? new ResponsePeople().resolve(e) };
114
- this.#db.exec("BEGIN IMMEDIATE");
115
- try {
102
+ immediateTransaction(this.#db, () => {
116
103
  const changed = this.#db.prepare("UPDATE response_results SET status='ok',assessed_at=?,result=? WHERE cohort=? AND id=? AND input_hash=? AND active=1")
117
104
  .run(now, JSON.stringify(result), cohort, e.id, e.inputHash).changes;
118
105
  if (changed)
119
106
  this.reviews.sync(cohort, e.id, e.inputHash, result, now);
120
- this.#db.exec("COMMIT");
121
- }
122
- catch (error) {
123
- this.#db.exec("ROLLBACK");
124
- throw error;
125
- }
107
+ });
126
108
  }
127
109
  cursor(cohort) { return String(this.#db.prepare("SELECT cursor FROM response_cursors WHERE cohort=?").get(cohort)?.cursor ?? ""); }
128
110
  advance(cohort, cursor) {
@@ -157,27 +139,20 @@ export class ResponseAuditStore {
157
139
  return row ? JSON.parse(String(row.result)) : undefined;
158
140
  }
159
141
  stageBegin(keys, now) {
160
- this.#db.exec("BEGIN IMMEDIATE");
161
- try {
142
+ immediateTransaction(this.#db, () => {
162
143
  for (const key of keys) {
163
144
  const changed = this.#db.prepare(`UPDATE response_stages SET attempts=attempts+1,attempted_at=?,status='failed'
164
145
  WHERE key=? AND status!='ok' AND attempts<3 AND (attempted_at IS NULL OR attempted_at<=?)`).run(now, key, now - 600_000).changes;
165
146
  if (!changed)
166
147
  throw new Error("Response stage in backoff or retry exhausted");
167
148
  }
168
- this.#db.exec("COMMIT");
169
- }
170
- catch (error) {
171
- this.#db.exec("ROLLBACK");
172
- throw error;
173
- }
149
+ });
174
150
  }
175
151
  stageSave(key, result, now) {
176
152
  this.#db.prepare("UPDATE response_stages SET status='ok',result=?,assessed_at=? WHERE key=?").run(JSON.stringify(result), now, key);
177
153
  }
178
154
  retryFailed(cohort) {
179
- this.#db.exec("BEGIN IMMEDIATE");
180
- try {
155
+ return immediateTransaction(this.#db, () => {
181
156
  const episodes = this.#db.prepare(`UPDATE response_results AS r SET attempts=0,attempted_at=NULL,status='pending'
182
157
  WHERE cohort=? AND active=1 AND (status!='ok' OR json_extract(result,'$.memory.status')='unavailable' OR EXISTS (
183
158
  SELECT 1 FROM response_stage_links l JOIN response_stages s ON s.key=l.key
@@ -186,13 +161,8 @@ export class ResponseAuditStore {
186
161
  WHERE status!='ok' AND key IN (SELECT l.key FROM response_stage_links l JOIN response_results r
187
162
  ON r.cohort=l.cohort AND r.id=l.episode_id AND r.input_hash=l.input_hash WHERE r.cohort=? AND r.active=1)`)
188
163
  .run(cohort).changes;
189
- this.#db.exec("COMMIT");
190
164
  return { stages, episodes };
191
- }
192
- catch (error) {
193
- this.#db.exec("ROLLBACK");
194
- throw error;
195
- }
165
+ });
196
166
  }
197
167
  scan(cohort, coverage, now) {
198
168
  this.#db.prepare("INSERT INTO response_scans VALUES(?,?,?) ON CONFLICT(cohort) DO UPDATE SET observed_at=excluded.observed_at,coverage=excluded.coverage")
@@ -364,16 +334,17 @@ export class ResponseAuditStore {
364
334
  const scoreDimension = dimension === "fulfillment" || dimension === "deliverableFit" || dimension === "dissatisfactionIntensity" ? dimension : null;
365
335
  const sentimentDimension = dimension === "dissatisfactionRate" || dimension === "sentimentUnknownRate";
366
336
  const emotionDimension = dimension === "annoyanceRate" || dimension === "frustrationRate";
337
+ const assessedSubset = scoreDimension || sentimentDimension || emotionDimension;
367
338
  const beforeN = scoreDimension ? previous[`${scoreDimension}Scored`] : sentimentDimension ? previous.sentimentAssessed : emotionDimension ? previous.emotionAssessed : previous.evaluated;
368
339
  const afterN = scoreDimension ? current[`${scoreDimension}Scored`] : sentimentDimension ? current.sentimentAssessed : emotionDimension ? current.emotionAssessed : current.evaluated;
369
340
  const before = dimension === "fulfillment" || dimension === "deliverableFit" || dimension === "dissatisfactionIntensity" ? previous[`${dimension}Mean`] : previous[dimension];
370
341
  const after = dimension === "fulfillment" || dimension === "deliverableFit" || dimension === "dissatisfactionIntensity" ? current[`${dimension}Mean`] : current[dimension];
371
- const beforeCoverage = scoreDimension || sentimentDimension || emotionDimension ? beforeN / previous.evaluated : previous.outcomeCoverage;
372
- const afterCoverage = scoreDimension || sentimentDimension || emotionDimension ? afterN / current.evaluated : current.outcomeCoverage;
342
+ const beforeCoverage = assessedSubset ? beforeN / previous.evaluated : previous.outcomeCoverage;
343
+ const afterCoverage = assessedSubset ? afterN / current.evaluated : current.outcomeCoverage;
373
344
  const coverageChanged = beforeCoverage !== afterCoverage;
374
345
  const enough = beforeN >= 20 && afterN >= 20 && current.taskType !== "uncertain" && current.agentModel !== "unknown";
375
346
  const status = !current.human || !current.human.accountScope || current.taskType === "uncertain" || current.agentModel === "unknown" ? "unknown_stratum" :
376
- !enough ? "insufficient_samples" : (scoreDimension || sentimentDimension || emotionDimension) && coverageChanged ? "coverage_changed" : "descriptive_comparison";
347
+ !enough ? "insufficient_samples" : assessedSubset && coverageChanged ? "coverage_changed" : "descriptive_comparison";
377
348
  return { fromWeek: previous.week, toWeek: current.week, taskType: current.taskType, agentModel: current.agentModel,
378
349
  fromPeriod: previous.week, toPeriod: current.week, human: current.human,
379
350
  dimension, beforeN, afterN, status,
@@ -1,3 +1,4 @@
1
+ export declare const CONVERSATION_INFO: RegExp;
1
2
  /** Infer legacy transport sender metadata only to unwrap visible conversation text. */
2
3
  export declare function conversationUserText(raw: string, sender?: unknown): {
3
4
  text: string;
@@ -1,3 +1,5 @@
1
+ export const CONVERSATION_INFO = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n([^]*?)\r?\n```\r?\n/;
2
+ const FROM_HEADER = /^From: [^\r\n]+ \(([^()\r\n]+)\)\r?\n/;
1
3
  /** Infer legacy transport sender metadata only to unwrap visible conversation text. */
2
4
  export function conversationUserText(raw, sender) {
3
5
  const parsed = conversationEnvelope(raw, sender);
@@ -8,7 +10,7 @@ export function conversationUserText(raw, sender) {
8
10
  export function conversationEnvelope(raw, sender) {
9
11
  let senderId = typeof sender === "string" ? sender : undefined;
10
12
  if (senderId === undefined) {
11
- const header = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n([^]*?)\r?\n```\r?\n/.exec(raw.trim());
13
+ const header = CONVERSATION_INFO.exec(raw.trim());
12
14
  if (header) {
13
15
  let metadata;
14
16
  try {
@@ -22,7 +24,7 @@ export function conversationEnvelope(raw, sender) {
22
24
  senderId = metadata.sender.id;
23
25
  }
24
26
  }
25
- senderId ??= /^From: [^\r\n]+ \(([^()\r\n]+)\)\r?\n/.exec(raw.trim())?.[1];
27
+ senderId ??= FROM_HEADER.exec(raw.trim())?.[1];
26
28
  }
27
29
  return userEnvelope(raw, senderId ?? "");
28
30
  }
@@ -36,7 +38,7 @@ function userEnvelope(input, senderId) {
36
38
  let text = input.trim();
37
39
  let contextLimited = false;
38
40
  let context;
39
- const header = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n([^]*?)\r?\n```\r?\n/.exec(text);
41
+ const header = CONVERSATION_INFO.exec(text);
40
42
  if (header) {
41
43
  let meta;
42
44
  try {
@@ -70,7 +72,7 @@ function userEnvelope(input, senderId) {
70
72
  }
71
73
  }
72
74
  else {
73
- const from = /^From: [^\r\n]+ \(([^()\r\n]+)\)\r?\n/.exec(text);
75
+ const from = FROM_HEADER.exec(text);
74
76
  if (from) {
75
77
  if (from[1] !== senderId)
76
78
  return undefined;
@@ -1,7 +1,7 @@
1
1
  import { type RetrievalTimings } from "./retrieval-timing.js";
2
2
  type RetrievalOperation = "vector" | "memoryWhisperer" | "memorySearch";
3
- type RetrievalOutcome = "ok" | "partial" | "empty" | "failed" | "cancelled" | "timed_out" | "skipped";
4
- declare const fields: readonly ["elapsedMs", "retrievalMs", "judgeMs", "gateMs", "generationMs", "setupMs", "queueWaitMs", "metadataMs", "storeSetupMs", "bm25Ms", "vectorMs", "vectorIndexCheckMs", "vectorScopeMs", "embeddingMs", "vectorScanMs", "hydrationMs", "vectorMappingMs", "vectorOtherMs", "passageMs", "candidatePrepMs", "retrievalOtherMs", "otherMs", "metadataReloads", "vectorScanAttempts", "candidates", "eligible", "results", "contextChars"];
3
+ type RetrievalOutcome = "ok" | "partial" | "empty" | "failed" | "cancelled" | "timed_out" | "skipped" | "degraded";
4
+ declare const fields: readonly ["elapsedMs", "retrievalMs", "judgeMs", "gateMs", "generationMs", "setupMs", "queueWaitMs", "metadataMs", "storeSetupMs", "bm25Ms", "vectorMs", "vectorIndexCheckMs", "vectorScopeMs", "embeddingMs", "vectorScanMs", "hydrationMs", "vectorMappingMs", "vectorOtherMs", "passageMs", "candidatePrepMs", "retrievalOtherMs", "otherMs", "metadataReloads", "vectorScanAttempts", "candidates", "eligible", "results", "contextChars", "requestsSucceeded", "requestsFailed", "fallbackKeyUnavailable", "fallbackAllJudgmentsFailed"];
5
5
  type Field = typeof fields[number];
6
6
  export type RetrievalObservation = {
7
7
  outcome: RetrievalOutcome;
@@ -24,6 +24,7 @@ export declare class RetrievalTelemetry {
24
24
  failed?: number | undefined;
25
25
  empty?: number | undefined;
26
26
  timed_out?: number | undefined;
27
+ degraded?: number | undefined;
27
28
  };
28
29
  slowestRecent: {
29
30
  outcome: RetrievalOutcome;
@@ -55,6 +56,10 @@ export declare class RetrievalTelemetry {
55
56
  eligible?: number | undefined;
56
57
  results?: number | undefined;
57
58
  contextChars?: number | undefined;
59
+ requestsSucceeded?: number | undefined;
60
+ requestsFailed?: number | undefined;
61
+ fallbackKeyUnavailable?: number | undefined;
62
+ fallbackAllJudgmentsFailed?: number | undefined;
58
63
  }[];
59
64
  measurements: {
60
65
  [k: string]: {
@@ -1,8 +1,9 @@
1
1
  import { timingFields } from "./retrieval-timing.js";
2
2
  const fields = ["elapsedMs", "retrievalMs", "judgeMs", "gateMs", "generationMs", ...timingFields,
3
- "metadataReloads", "vectorScanAttempts", "candidates", "eligible", "results", "contextChars"];
3
+ "metadataReloads", "vectorScanAttempts", "candidates", "eligible", "results", "contextChars",
4
+ "requestsSucceeded", "requestsFailed", "fallbackKeyUnavailable", "fallbackAllJudgmentsFailed"];
4
5
  const recentLimit = 256;
5
- const outcomes = ["ok", "partial", "empty", "failed", "cancelled", "timed_out", "skipped"];
6
+ const outcomes = ["ok", "partial", "empty", "failed", "cancelled", "timed_out", "skipped", "degraded"];
6
7
  const boundedAdd = (left, right) => Math.min(Number.MAX_SAFE_INTEGER, left + right);
7
8
  /** Only fixed operation/outcome names and nonnegative numbers enter this store. */
8
9
  export class RetrievalTelemetry {
@@ -2,13 +2,14 @@ import { randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
3
  import { MEMORY_DATABASE } from "./memory-database.js";
4
4
  import { join } from "node:path";
5
- import { resolveAgentDir, resolveAgentWorkspaceDir, resolveStateDir, } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
5
+ import { resolveAgentWorkspaceDir, resolveStateDir, } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
6
6
  import { listAgentIds, resolveAgentIdentity } from "openclaw/plugin-sdk/agent-runtime";
7
7
  import { QmdMemoryManager } from "./manager.js";
8
8
  import { resolveTimezone } from "./session-projector.js";
9
9
  import { unchangedSessionSync } from "./session-sync.js";
10
10
  import { resolveConfiguredSkillPath, resolveSessionSource, resolveSources } from "./sources.js";
11
11
  import { classifyWorkspaceMemoryPaths } from "./workspace-path-classifier.js";
12
+ import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
12
13
  const activeSessionSyncs = new Map();
13
14
  async function readJson(path) {
14
15
  try {
@@ -122,7 +123,7 @@ export class QmdMemoryRuntime {
122
123
  error: 'memory session sync requires a configured "sessions" corpus',
123
124
  };
124
125
  }
125
- const directory = this.#sessionSyncDirectory(params.agentId);
126
+ const directory = this.#stateDir(params.agentId);
126
127
  const statusPath = join(directory, "session-sync-status.json");
127
128
  const running = activeSessionSyncs.get(directory);
128
129
  if (running)
@@ -193,7 +194,7 @@ export class QmdMemoryRuntime {
193
194
  return { status: "started", startedAt };
194
195
  }
195
196
  async sessionSyncStatus(agentId) {
196
- const directory = this.#sessionSyncDirectory(agentId);
197
+ const directory = this.#stateDir(agentId);
197
198
  const statusPath = join(directory, "session-sync-status.json");
198
199
  const status = await readJson(statusPath);
199
200
  const running = activeSessionSyncs.get(directory);
@@ -232,7 +233,7 @@ export class QmdMemoryRuntime {
232
233
  }
233
234
  async #createManager(cfg, agentId) {
234
235
  const workspaceDir = resolveAgentWorkspaceDir(cfg, agentId);
235
- const stateDir = join(this.#stateRoot, "agents", agentId, "unblock-memory");
236
+ const stateDir = this.#stateDir(agentId);
236
237
  const fileCorpora = this.#corpora.filter((corpus) => corpus.kind === "files" || corpus.kind === "skills");
237
238
  const sessions = this.#sessionConfig(cfg, agentId);
238
239
  const sources = resolveSources(workspaceDir, fileCorpora);
@@ -265,18 +266,18 @@ export class QmdMemoryRuntime {
265
266
  const corpus = this.#corpora.find(corpus => corpus.kind === "sessions");
266
267
  if (!corpus)
267
268
  return;
268
- const stateDir = this.#sessionSyncDirectory(agentId);
269
+ const stateDir = this.#stateDir(agentId);
269
270
  const source = resolveSessionSource(join(stateDir, "sessions"), corpus.chatTypes);
270
271
  return {
271
272
  agentId, agentName: resolveAgentIdentity(cfg, agentId)?.name?.trim() || agentId,
272
273
  chatTypes: corpus.chatTypes, maxExpandedTokens: corpus.maxExpandedTokens,
273
274
  collection: source.collection, outputDir: source.root,
274
- databasePath: join(resolveAgentDir(cfg, agentId), "openclaw-agent.sqlite"),
275
+ databasePath: agentTranscriptDatabase(cfg, agentId),
275
276
  manifestPath: join(stateDir, "sessions-manifest.json"),
276
277
  timezone: resolveTimezone(cfg.agents?.defaults?.userTimezone?.trim()),
277
278
  };
278
279
  }
279
- #sessionSyncDirectory(agentId) {
280
- return join(this.#stateRoot, "agents", agentId, "unblock-memory");
280
+ #stateDir(agentId) {
281
+ return agentStateDir(agentId, this.#stateRoot);
281
282
  }
282
283
  }
@@ -1,22 +1,16 @@
1
1
  import { Value } from "typebox/value";
2
- import { estimateJevTokens, requestTypeSafe, resolveTypeSafeApiKey, TYPESAFE_NOUL_SCHEMA, TypeSafeRequestError } from "./typesafe-client.js";
2
+ import { estimateJevTokens, isTypeSafeTimeout, requestTypeSafe, resolveTypeSafeApiKey, TYPESAFE_NOUL_SCHEMA, TypeSafeRequestError } from "./typesafe-client.js";
3
3
  import { messageText } from "./whisperer-context.js";
4
- import { conversationEnvelope, conversationUserText } from "./response-text.js";
4
+ import { CONVERSATION_INFO, conversationEnvelope, conversationUserText } from "./response-text.js";
5
5
  import { SKILL_WHISPERER_TIMEOUT_MS } from "./skill-whisperer.js";
6
6
  import { abortable } from "./abortable.js";
7
+ import { isRecord, nonBlank } from "./guards.js";
7
8
  // Leaves room for the longest scenario question under Jev's 32k state-plus-question limit.
8
9
  const MAX_STATE_TOKENS = 24_000;
9
10
  const MAX_SESSIONS = 1000;
10
11
  const RUNS_PER_SESSION = 4;
11
- const CONVERSATION_INFO = /^Conversation info: ⟦openclaw:ctx⟧\r?\n```json\r?\n[^]*?\r?\n```\r?\n/;
12
12
  class SafetyInputError extends Error {
13
13
  }
14
- function isRecord(value) {
15
- return value !== null && typeof value === "object" && !Array.isArray(value);
16
- }
17
- function nonBlank(value) {
18
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
19
- }
20
14
  /** Thread replies and forum topics belong to their parent conversation (`C1:thread:1712.01`, `-100:topic:5`). */
21
15
  function conversationId(value) {
22
16
  const lower = value?.toLowerCase();
@@ -241,9 +235,7 @@ export function registerSafetyWhisperer(api, plugin, diagnostics) {
241
235
  }
242
236
  catch (error) {
243
237
  // Fail open by design, but never silently: "could not check" is recorded separately from "no match".
244
- const timedOut = (error instanceof TypeSafeRequestError && error.code === "timeout") ||
245
- (signal.aborted && signal.reason instanceof Error && signal.reason.name === "TimeoutError");
246
- const outcome = error instanceof SafetyInputError ? "input_too_large" : timedOut ? "timed_out" : signal.aborted ? "cancelled" : "failed";
238
+ const outcome = error instanceof SafetyInputError ? "input_too_large" : isTypeSafeTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed";
247
239
  record(outcome);
248
240
  if (outcome !== "cancelled") {
249
241
  warn({ event: "check_failed", agentId, runId: context.runId, outcome, eligibleScenarios: scenarios.length,
@@ -1,15 +1,8 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { projectLoggieMessage } from "./loggie-projection.js";
3
3
  import { applyProposal, parseAttachments, parseInternalMessage } from "./session-noise.js";
4
+ import { nonBlank, record } from "./guards.js";
4
5
  const MESSAGE_HEADING = /^## (User|Assistant) — (.+) — (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} \S.*)$/u;
5
- function record(value) {
6
- return value !== null && typeof value === "object" && !Array.isArray(value)
7
- ? value
8
- : undefined;
9
- }
10
- function nonEmptyString(value) {
11
- return typeof value === "string" && value.trim() ? value.trim() : undefined;
12
- }
13
6
  function timestamp(value) {
14
7
  if (typeof value === "number" && Number.isFinite(value))
15
8
  return value;
@@ -72,12 +65,12 @@ export function projectMessage(row, input) {
72
65
  const metadata = record(message.__openclaw);
73
66
  const speaker = role === "assistant"
74
67
  ? input.agentName
75
- : nonEmptyString(metadata?.senderName) ??
76
- nonEmptyString(metadata?.senderUsername) ??
77
- nonEmptyString(metadata?.senderId) ??
78
- nonEmptyString(message.senderName) ??
79
- nonEmptyString(message.senderLabel) ??
80
- nonEmptyString(message.senderId) ??
68
+ : nonBlank(metadata?.senderName) ??
69
+ nonBlank(metadata?.senderUsername) ??
70
+ nonBlank(metadata?.senderId) ??
71
+ nonBlank(message.senderName) ??
72
+ nonBlank(message.senderLabel) ??
73
+ nonBlank(message.senderId) ??
81
74
  "User";
82
75
  if (role === "user" && speaker !== "User") {
83
76
  text = text.replace(/^From:[^\n]*\n/u, "").trim();
@@ -46,6 +46,7 @@ type ProjectionOptions = {
46
46
  };
47
47
  export declare function unchangedSessionSync(params: ProjectionOptions, indexPath: string): Promise<SessionSyncResult | undefined>;
48
48
  export declare function readSessionManifest(path: string): Promise<SessionManifest>;
49
+ export declare function projectionHash(content: string): string;
49
50
  export declare function sessionMetadataByPath(manifest: SessionManifest): Map<string, SessionMetadata>;
50
51
  export declare function syncSessionProjections(params: ProjectionOptions & {
51
52
  force?: boolean;
@@ -27,6 +27,16 @@ const REQUIRED_COLUMNS = {
27
27
  session_transcript_active_events: ["session_id", "active_position", "event_seq", "message_position"],
28
28
  transcript_rewrite_watermarks: ["session_id", "generation"],
29
29
  };
30
+ function windowMetadata(window) {
31
+ return {
32
+ sessionId: window.sessionId,
33
+ provider: window.provider ?? undefined,
34
+ chatType: window.chatType,
35
+ accountId: window.accountId ?? undefined,
36
+ conversationId: window.conversationId ?? undefined,
37
+ startedAt: window.startedAt,
38
+ };
39
+ }
30
40
  function projectionKey(params) {
31
41
  return JSON.stringify([PROJECTOR_VERSION, params.databasePath, params.agentId,
32
42
  params.agentName, params.timezone, [...params.chatTypes].sort()]);
@@ -122,14 +132,7 @@ function readSnapshot(params) {
122
132
  const changed = new Set();
123
133
  const unavailable = new Set();
124
134
  for (const window of windows) {
125
- const metadata = {
126
- sessionId: window.sessionId,
127
- provider: window.provider ?? undefined,
128
- chatType: window.chatType,
129
- accountId: window.accountId ?? undefined,
130
- conversationId: window.conversationId ?? undefined,
131
- startedAt: window.startedAt,
132
- };
135
+ const metadata = windowMetadata(window);
133
136
  const previous = params.previousManifest.sessions[window.sessionId];
134
137
  const documentPath = sessionDocumentPath(metadata);
135
138
  const sourceFingerprint = JSON.stringify(window);
@@ -230,7 +233,7 @@ async function remove(path) {
230
233
  throw error;
231
234
  }
232
235
  }
233
- function projectionHash(content) {
236
+ export function projectionHash(content) {
234
237
  return createHash("sha256").update(content).digest("hex");
235
238
  }
236
239
  export function sessionMetadataByPath(manifest) {
@@ -259,14 +262,7 @@ export async function syncSessionProjections(params) {
259
262
  for (const window of snapshot.windows) {
260
263
  const previous = previousManifest.sessions[window.sessionId];
261
264
  const events = snapshot.events.get(window.sessionId);
262
- const metadata = {
263
- sessionId: window.sessionId,
264
- provider: window.provider ?? undefined,
265
- chatType: window.chatType,
266
- accountId: window.accountId ?? undefined,
267
- conversationId: window.conversationId ?? undefined,
268
- startedAt: window.startedAt,
269
- };
265
+ const metadata = windowMetadata(window);
270
266
  const documentPath = sessionDocumentPath(metadata);
271
267
  if (snapshot.unavailable.has(window.sessionId)) {
272
268
  counts.failed += 1;