@unblocklabs/unblock-memory 0.10.0 → 0.10.2

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 (72) hide show
  1. package/dist/src/abortable.d.ts +2 -0
  2. package/dist/src/abortable.js +4 -0
  3. package/dist/src/agent-paths.d.ts +5 -0
  4. package/dist/src/agent-paths.js +10 -0
  5. package/dist/src/analysis.js +13 -18
  6. package/dist/src/cluster-review.js +9 -7
  7. package/dist/src/config.js +2 -2
  8. package/dist/src/curation.js +3 -10
  9. package/dist/src/emotion-baselines.d.ts +12 -1
  10. package/dist/src/emotion-baselines.js +67 -47
  11. package/dist/src/evidence-review.js +2 -1
  12. package/dist/src/extraction-chunk.js +3 -4
  13. package/dist/src/extraction-index.d.ts +2 -0
  14. package/dist/src/extraction-index.js +4 -2
  15. package/dist/src/extraction-runtime.js +3 -3
  16. package/dist/src/extraction-store.js +7 -19
  17. package/dist/src/extraction-worker.js +3 -2
  18. package/dist/src/guards.d.ts +6 -0
  19. package/dist/src/guards.js +12 -0
  20. package/dist/src/inside-out-runtime.js +4 -3
  21. package/dist/src/inside-out-store.d.ts +28 -4
  22. package/dist/src/inside-out-store.js +50 -19
  23. package/dist/src/inside-out.js +6 -6
  24. package/dist/src/json-hash.d.ts +2 -0
  25. package/dist/src/json-hash.js +6 -0
  26. package/dist/src/manager.js +62 -91
  27. package/dist/src/memory-database.d.ts +3 -0
  28. package/dist/src/memory-database.js +18 -1
  29. package/dist/src/people-hooks.js +3 -6
  30. package/dist/src/people-primer-tool.js +0 -2
  31. package/dist/src/people-primer.js +3 -6
  32. package/dist/src/people-store.d.ts +2 -1
  33. package/dist/src/people-store.js +29 -82
  34. package/dist/src/people-tools.js +4 -5
  35. package/dist/src/plugin.js +20 -13
  36. package/dist/src/quality-audit.js +2 -2
  37. package/dist/src/query-generator.js +1 -1
  38. package/dist/src/response-audit.js +7 -8
  39. package/dist/src/response-episodes.js +5 -8
  40. package/dist/src/response-judge.js +2 -3
  41. package/dist/src/response-reviews.js +8 -18
  42. package/dist/src/response-runtime.js +4 -3
  43. package/dist/src/response-stages.js +4 -4
  44. package/dist/src/response-store.js +15 -44
  45. package/dist/src/response-text.d.ts +1 -0
  46. package/dist/src/response-text.js +6 -4
  47. package/dist/src/runtime.js +9 -8
  48. package/dist/src/safety-whisperer.js +4 -12
  49. package/dist/src/session-projector.js +7 -14
  50. package/dist/src/session-sync.d.ts +1 -0
  51. package/dist/src/session-sync.js +13 -17
  52. package/dist/src/skill-whisperer.js +3 -9
  53. package/dist/src/slack-directory.js +1 -5
  54. package/dist/src/sources.js +17 -37
  55. package/dist/src/tool-context.d.ts +2 -0
  56. package/dist/src/tool-context.js +5 -1
  57. package/dist/src/training-input.d.ts +0 -1
  58. package/dist/src/training-input.js +3 -6
  59. package/dist/src/training-queries.d.ts +1 -1
  60. package/dist/src/training-queries.js +9 -8
  61. package/dist/src/training-retrieval.js +2 -2
  62. package/dist/src/training-runtime.js +3 -3
  63. package/dist/src/training-store.js +14 -25
  64. package/dist/src/typesafe-client.d.ts +8 -0
  65. package/dist/src/typesafe-client.js +7 -1
  66. package/dist/src/typesafe-review.d.ts +1 -1
  67. package/dist/src/typesafe-review.js +1 -3
  68. package/dist/src/typesafe.js +4 -7
  69. package/docs/configuration.md +17 -7
  70. package/docs/retrieval.md +2 -1
  71. package/openclaw.plugin.json +2 -3
  72. package/package.json +1 -1
@@ -1,2 +1,4 @@
1
1
  /** Stop waiting without cancelling shared work that other callers still need. */
2
2
  export declare function abortable<T>(pending: Promise<T>, signal?: AbortSignal): Promise<T>;
3
+ /** Whether the signal fired because an `AbortSignal.timeout` deadline elapsed. */
4
+ export declare function abortedByTimeout(signal: AbortSignal | undefined): boolean;
@@ -19,3 +19,7 @@ export async function abortable(pending, signal) {
19
19
  signal.removeEventListener("abort", onAbort);
20
20
  }
21
21
  }
22
+ /** Whether the signal fired because an `AbortSignal.timeout` deadline elapsed. */
23
+ export function abortedByTimeout(signal) {
24
+ return Boolean(signal?.aborted && signal.reason instanceof Error && signal.reason.name === "TimeoutError");
25
+ }
@@ -0,0 +1,5 @@
1
+ import type { OpenClawConfig } from "openclaw/plugin-sdk/plugin-entry";
2
+ /** This plugin's per-agent state: QMD index, durable stores and session projections. */
3
+ export declare function agentStateDir(agentId: string, stateRoot?: string): string;
4
+ /** The host's per-agent transcript database. */
5
+ export declare function agentTranscriptDatabase(cfg: OpenClawConfig, agentId: string): string;
@@ -0,0 +1,10 @@
1
+ import { join } from "node:path";
2
+ import { resolveAgentDir, resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
3
+ /** This plugin's per-agent state: QMD index, durable stores and session projections. */
4
+ export function agentStateDir(agentId, stateRoot = resolveStateDir()) {
5
+ return join(stateRoot, "agents", agentId, "unblock-memory");
6
+ }
7
+ /** The host's per-agent transcript database. */
8
+ export function agentTranscriptDatabase(cfg, agentId) {
9
+ return join(resolveAgentDir(cfg, agentId), "openclaw-agent.sqlite");
10
+ }
@@ -1,5 +1,6 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
+ import { chunkFingerprint } from "./curation.js";
3
4
  const DEFAULT_CLUSTER_LIMIT = 20;
4
5
  const MAX_CLUSTER_LIMIT = 50;
5
6
  const DEFAULT_MEMBER_LIMIT = 20;
@@ -170,7 +171,7 @@ export function runAnalysisWorker(params) {
170
171
  }
171
172
  function latestRun(db) {
172
173
  return db.prepare(`
173
- SELECT id, created_at, completed_at, input_digest, model, embedding_fingerprint, dimensions, stale_at
174
+ SELECT id, created_at, completed_at, input_digest, model, embedding_fingerprint, dimensions, stale_at, params_json
174
175
  FROM memory_analysis_runs
175
176
  WHERE completed_at IS NOT NULL
176
177
  ORDER BY completed_at DESC, created_at DESC, id DESC
@@ -181,13 +182,7 @@ export function latestAnalysisRunId(db) {
181
182
  return latestRun(db)?.id;
182
183
  }
183
184
  export function latestAnalysisCollections(db) {
184
- const row = db.prepare(`
185
- SELECT params_json
186
- FROM memory_analysis_runs
187
- WHERE completed_at IS NOT NULL
188
- ORDER BY completed_at DESC, created_at DESC, id DESC
189
- LIMIT 1
190
- `).get();
185
+ const row = latestRun(db);
191
186
  if (!row)
192
187
  return undefined;
193
188
  try {
@@ -270,7 +265,7 @@ function representativeOrder(clusterId) {
270
265
  m.hash,
271
266
  m.seq`;
272
267
  }
273
- function members(db, runId, clusterId, limit, offset = 0, sort = "representative", maxExcerptBytes = MAX_EXCERPT_BYTES, maxTotalBytes = MAX_TOTAL_EXCERPT_BYTES, maxTotalAliases = MAX_TOTAL_ALIASES, temporal = {}) {
268
+ function members(db, runId, clusterId, limit, offset, sort, temporal) {
274
269
  const score = clusterId === -1 ? "m.outlier_score" : "m.probability";
275
270
  const order = {
276
271
  representative: representativeOrder(clusterId),
@@ -342,11 +337,11 @@ function members(db, runId, clusterId, limit, offset = 0, sort = "representative
342
337
  ORDER BY ${order}
343
338
  LIMIT ? OFFSET ?
344
339
  `).all(temporal.sessionCollection ?? "", temporal.sessionCollection ?? "", temporal.sessionCollection ?? "", runId, clusterId, runId, clusterId, limit, offset);
345
- let remaining = maxTotalBytes;
346
- let remainingAliases = maxTotalAliases;
340
+ let remaining = MAX_TOTAL_EXCERPT_BYTES;
341
+ let remainingAliases = MAX_TOTAL_ALIASES;
347
342
  return rows.map((row, index) => {
348
343
  const remainingRows = rows.length - index;
349
- const excerptBudget = Math.min(maxExcerptBytes, Math.floor(remaining / remainingRows));
344
+ const excerptBudget = Math.min(MAX_EXCERPT_BYTES, Math.floor(remaining / remainingRows));
350
345
  const fullText = row.doc.slice(row.pos, row.pos + row.chunk_len);
351
346
  const text = byteSlice(fullText, excerptBudget);
352
347
  remaining -= Buffer.byteLength(text);
@@ -365,7 +360,7 @@ function members(db, runId, clusterId, limit, offset = 0, sort = "representative
365
360
  eventTime: row.event_time,
366
361
  eventTimeBasis: row.event_time_basis,
367
362
  eventTimeSource: `qmd://${row.event_collection}/${row.event_path}`,
368
- contentFingerprint: createHash("sha256").update(fullText).digest("hex"),
363
+ contentFingerprint: chunkFingerprint(fullText),
369
364
  text,
370
365
  sourcePaths: aliases,
371
366
  };
@@ -415,8 +410,8 @@ function clusterPreview(db, runId, clusterId, maxBytes, aliasLimit) {
415
410
  sourcePaths: sourcePaths(db, row.hash, Math.min(MAX_ALIASES_PER_MEMBER, aliasLimit)),
416
411
  };
417
412
  }
418
- function toSummary(db, run, row, includePreview, previewBytes = 600, aliasLimit = MAX_TOTAL_ALIASES) {
419
- const preview = includePreview
413
+ function toSummary(db, run, row, previewBytes = 0, aliasLimit = MAX_TOTAL_ALIASES) {
414
+ const preview = previewBytes > 0
420
415
  ? clusterPreview(db, run.id, row.cluster_id, previewBytes, aliasLimit)
421
416
  : undefined;
422
417
  return {
@@ -468,7 +463,7 @@ export function readClusters(db, requestedLimit = DEFAULT_CLUSTER_LIMIT) {
468
463
  let remainingAliases = MAX_TOTAL_ALIASES;
469
464
  const clusters = rows.map((row) => {
470
465
  const previewBytes = Math.min(600, remainingBytes);
471
- const summary = toSummary(db, run, row, previewBytes > 0, previewBytes, remainingAliases);
466
+ const summary = toSummary(db, run, row, previewBytes, remainingAliases);
472
467
  remainingBytes -= Buffer.byteLength(summary.preview?.text ?? "");
473
468
  remainingAliases -= summary.preview?.sourcePaths.length ?? 0;
474
469
  return summary;
@@ -479,7 +474,7 @@ export function readClusters(db, requestedLimit = DEFAULT_CLUSTER_LIMIT) {
479
474
  runId: run.id,
480
475
  ...readMetadata(run),
481
476
  clusters,
482
- noise: noise ? toSummary(db, run, noise, false) : null,
477
+ noise: noise ? toSummary(db, run, noise) : null,
483
478
  };
484
479
  }
485
480
  function resolveClusterId(db, runId, reference) {
@@ -523,7 +518,7 @@ export function readCluster(db, clusterReferenceId, requestedLimit = DEFAULT_MEM
523
518
  const limit = Math.max(1, Math.min(MAX_MEMBER_LIMIT, Math.floor(requestedLimit)));
524
519
  const offset = Math.max(0, Math.floor(requestedOffset));
525
520
  const total = availableSize(db, run.id, clusterId);
526
- const pageMembers = members(db, run.id, clusterId, limit, offset, sort, MAX_EXCERPT_BYTES, MAX_TOTAL_EXCERPT_BYTES, MAX_TOTAL_ALIASES, temporal);
521
+ const pageMembers = members(db, run.id, clusterId, limit, offset, sort, temporal);
527
522
  const nextOffset = offset + pageMembers.length;
528
523
  const hasMore = nextOffset < total;
529
524
  return {
@@ -1,7 +1,13 @@
1
1
  import { readAnalysisSummary, readCluster } from "./analysis.js";
2
2
  import { parseSafeVirtualPath } from "./sources.js";
3
+ import { TYPESAFE_MODEL } from "./typesafe-client.js";
3
4
  import { reviewClusterDefects } from "./typesafe-review.js";
4
5
  import { chunkFingerprint } from "./curation.js";
6
+ function indexedChunk(db, safe, member) {
7
+ return db.prepare(`SELECT c.doc, v.pos, v.chunk_len FROM documents d JOIN content c ON c.hash = d.hash
8
+ JOIN content_vectors v ON v.hash = d.hash WHERE d.active = 1 AND d.collection = ? AND d.path = ? AND d.hash = ? AND v.seq = ?`)
9
+ .get(safe.source.collection, safe.relativePath, member.hash, member.seq);
10
+ }
5
11
  /** Inspect center and edge samples; never extrapolate their labels to the rest of a cluster. */
6
12
  export async function reviewClusterIngestion(params) {
7
13
  params.signal.throwIfAborted();
@@ -19,9 +25,7 @@ export async function reviewClusterIngestion(params) {
19
25
  return [];
20
26
  const safe = parseSafeVirtualPath(path, sources);
21
27
  // Reload the full chunk; analysis previews may be truncated. Never judge a silently cut prefix.
22
- const row = params.db.prepare(`SELECT c.doc, v.pos, v.chunk_len FROM documents d JOIN content c ON c.hash = d.hash
23
- JOIN content_vectors v ON v.hash = d.hash WHERE d.active = 1 AND d.collection = ? AND d.path = ? AND d.hash = ? AND v.seq = ?`)
24
- .get(safe.source.collection, safe.relativePath, member.hash, member.seq);
28
+ const row = indexedChunk(params.db, safe, member);
25
29
  if (!row || row.pos < 0 || row.chunk_len < 1 || row.pos + row.chunk_len > row.doc.length || row.chunk_len > 2000)
26
30
  return [];
27
31
  const text = row.doc.slice(row.pos, row.pos + row.chunk_len);
@@ -45,9 +49,7 @@ export async function reviewClusterIngestion(params) {
45
49
  const safe = parseSafeVirtualPath(member.path, sources);
46
50
  if (!safe)
47
51
  return { status: "unavailable", reason: "Source scope changed; retry" };
48
- const row = params.db.prepare(`SELECT c.doc, v.pos, v.chunk_len FROM documents d JOIN content c ON c.hash = d.hash
49
- JOIN content_vectors v ON v.hash = d.hash WHERE d.active = 1 AND d.collection = ? AND d.path = ? AND d.hash = ? AND v.seq = ?`)
50
- .get(safe.source.collection, safe.relativePath, member.hash, member.seq);
52
+ const row = indexedChunk(params.db, safe, member);
51
53
  if (!row || chunkFingerprint(row.doc.slice(row.pos, row.pos + row.chunk_len)) !== member.fingerprint)
52
54
  return { status: "unavailable", reason: "Sample changed during review; retry" };
53
55
  }
@@ -59,6 +61,6 @@ export async function reviewClusterIngestion(params) {
59
61
  });
60
62
  return { status: "ok", runId: snapshot.runId, clusterId: params.clusterId, members, recurring,
61
63
  sampled: sample.length, considered: snapshot.considered, clusterSize: snapshot.clusterSize,
62
- policy: "jev-1.13.0:cluster-defects-v2-isolated", scope: "Center/edge sample of approved complete chunks only. Recurring labels are hypotheses, not proof of a shared cause or permission to change any member. Unreviewed members remain unknown." };
64
+ policy: `${TYPESAFE_MODEL}:cluster-defects-v2-isolated`, scope: "Center/edge sample of approved complete chunks only. Recurring labels are hypotheses, not proof of a shared cause or permission to change any member. Unreviewed members remain unknown." };
63
65
  });
64
66
  }
@@ -370,8 +370,8 @@ export function resolveConfig(value) {
370
370
  skillWhisperer = { enabled, historyMessages, minScore, cooldownTurns };
371
371
  }
372
372
  // Default-on means "on once skills exist": without a skills corpus it could never
373
- // hint, so it registers no prompt hook and reports inactive. Host-applied schema
374
- // defaults are indistinguishable from an explicit true, so this never throws.
373
+ // hint, so it registers no prompt hook and reports inactive. An explicit true is
374
+ // overridden too, never thrown; plugin registration warns about that case.
375
375
  if (skillWhisperer.enabled && !corpora.some((corpus) => corpus.kind === "skills")) {
376
376
  skillWhisperer = { ...skillWhisperer, enabled: false };
377
377
  }
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { openMemoryDatabase } from "./memory-database.js";
2
+ import { immediateTransaction, openMemoryDatabase } from "./memory-database.js";
3
3
  const TEMPORAL_BASES = ["path", "frontmatter", "session", "agent_verified"];
4
4
  const MAINTENANCE_TASK_TYPES = ["ambiguous_event_time", "exact_duplicate", "quality_review"];
5
5
  const MAINTENANCE_STATUSES = ["pending", "resolved", "deferred", "irrelevant"];
@@ -159,12 +159,10 @@ export class CurationStore {
159
159
  `).all(status, limit).map((row) => task(row));
160
160
  }
161
161
  updateTask(params) {
162
- this.#db.exec("BEGIN IMMEDIATE");
163
- try {
162
+ return immediateTransaction(this.#db, () => {
164
163
  const row = this.#db.prepare("SELECT * FROM maintenance_tasks WHERE id = ?")
165
164
  .get(params.id);
166
165
  if (!row) {
167
- this.#db.exec("COMMIT");
168
166
  return undefined;
169
167
  }
170
168
  const now = new Date().toISOString();
@@ -208,13 +206,8 @@ export class CurationStore {
208
206
  WHERE id = ?
209
207
  `).run(params.status, params.note ?? null, now, params.id);
210
208
  const updated = task(this.#db.prepare("SELECT * FROM maintenance_tasks WHERE id = ?").get(params.id));
211
- this.#db.exec("COMMIT");
212
209
  return updated;
213
- }
214
- catch (error) {
215
- this.#db.exec("ROLLBACK");
216
- throw error;
217
- }
210
+ });
218
211
  }
219
212
  updateAnnotationLocation(params) {
220
213
  this.#db.prepare(`
@@ -89,7 +89,10 @@ export declare function deviationReader(db: DatabaseSync): (row: Row, history?:
89
89
  }[];
90
90
  status: "not_compared";
91
91
  };
92
- /** Weekly snapshots, newest first; cumulative statistics are prefix sums of each population's stored weeks. */
92
+ /**
93
+ * Weekly snapshots, newest first; cumulative statistics are prefix sums of each population's stored weeks.
94
+ * `since` keeps weeks whose last day is on or after that UTC date (`week_end` is the exclusive next Monday).
95
+ */
93
96
  export declare function emotionBaselineHistory(db: DatabaseSync, options?: {
94
97
  personId?: string;
95
98
  since?: number;
@@ -106,6 +109,14 @@ export declare function emotionBaselineHistory(db: DatabaseSync, options?: {
106
109
  weekly: Summary;
107
110
  cumulative: Summary;
108
111
  }[];
112
+ /**
113
+ * Changes whenever a refresh input could: grades, links, people, stored results, the current week,
114
+ * grades crossing `now`, or settings. Equal fingerprints mean a refresh would write nothing.
115
+ */
116
+ export declare function baselineFingerprint(db: DatabaseSync, options: {
117
+ minInteractions: number;
118
+ now: number;
119
+ }): string;
109
120
  /**
110
121
  * Delete one person's baselines and assessment history. With `grades`, also erase their six
111
122
  * probabilities and person link, keeping a tombstone so the reply is never sent to Jev again.
@@ -1,7 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { immediateTransaction, tableExists } from "./memory-database.js";
3
+ import { jsonHash } from "./json-hash.js";
2
4
  export const INSIDE_OUT_EMOTIONS = ["joy", "sadness", "fear", "anger", "disgust", "surprise"];
3
5
  /** Erased by an operator purge: never retried, linked, aggregated or compared. */
4
6
  export const PURGED_GRADE = "Purged by operator";
7
+ /** Builds a per-emotion record in canonical emotion order, so serialized key order is stable. */
8
+ const perEmotion = (f) => Object.fromEntries(INSIDE_OUT_EMOTIONS.map(emotion => [emotion, f(emotion)]));
5
9
  const WEEK = 7 * 86400_000;
6
10
  const MONDAY = Date.UTC(1970, 0, 5);
7
11
  const VERSION = "personal-deviation-v2";
@@ -10,10 +14,9 @@ const STEPS = 100;
10
14
  // Writers on the shared store wait for at most one short batch, never a whole refresh.
11
15
  const BATCH = 500;
12
16
  const PAGE = 2000;
13
- const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
14
17
  const weekStart = (time) => MONDAY + Math.floor((time - MONDAY) / WEEK) * WEEK;
15
18
  const bin = (value) => Math.round(value * STEPS);
16
- const tableExists = (db, name) => Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?").get(name));
19
+ const GRADE = `interaction_id,rubric,model,person_id,target_at,reviewed_at,error,${INSIDE_OUT_EMOTIONS.join(",")}`;
17
20
  const VALID = INSIDE_OUT_EMOTIONS.map(e => `e.${e} BETWEEN 0 AND 1`).join(" AND ");
18
21
  // Comparable grades: successful, timed, not after `now`. Callers add the People join.
19
22
  const COMPARABLE = `e.reviewed_at<=? AND e.error IS NULL AND e.target_at IS NOT NULL AND e.target_at<=? AND ${VALID}`;
@@ -27,8 +30,7 @@ function schemaVersion(db) {
27
30
  function initializeEmotionBaselines(db) {
28
31
  if (schemaVersion(db) === 2)
29
32
  return;
30
- db.exec("BEGIN IMMEDIATE");
31
- try {
33
+ immediateTransaction(db, () => {
32
34
  const version = schemaVersion(db);
33
35
  if (version !== undefined && version !== 1 && version !== 2)
34
36
  throw new Error("Unsupported Inside Out baseline storage version");
@@ -47,20 +49,15 @@ function initializeEmotionBaselines(db) {
47
49
  CREATE INDEX IF NOT EXISTS inside_out_deviations_interaction ON inside_out_deviations(interaction_id,rubric);
48
50
  CREATE INDEX IF NOT EXISTS inside_out_deviations_person ON inside_out_deviations(person_id);
49
51
  INSERT OR REPLACE INTO memory_schema VALUES ('emotion-baselines',2);`);
50
- db.exec("COMMIT");
51
- }
52
- catch (error) {
53
- db.exec("ROLLBACK");
54
- throw error;
55
- }
52
+ });
56
53
  }
57
54
  function gradeSignature(row) {
58
- return hash([row.interaction_id, row.rubric, row.model, row.person_id ?? null, row.target_at,
55
+ return jsonHash([row.interaction_id, row.rubric, row.model, row.person_id ?? null, row.target_at,
59
56
  row.reviewed_at, row.error, ...INSIDE_OUT_EMOTIONS.map(e => row[e])]);
60
57
  }
61
58
  function histograms() {
62
59
  const empty = () => ({ count: 0, sum: 0, carry: 0, min: Infinity, max: -Infinity, bins: new Array(STEPS + 1).fill(0) });
63
- return { joy: empty(), sadness: empty(), fear: empty(), anger: empty(), disgust: empty(), surprise: empty() };
60
+ return perEmotion(empty);
64
61
  }
65
62
  // Neumaier summation keeps means exact for repeated values: twenty 0.8s average to 0.8.
66
63
  function accumulate(target, value, count, min, max) {
@@ -126,8 +123,7 @@ function summarize(week) {
126
123
  return { count: h.count, mean: h.count ? (h.sum + h.carry) / h.count : null, min: h.count ? h.min : null,
127
124
  p10: quantile(0.1), median: quantile(0.5), p90: quantile(0.9), max: h.count ? h.max : null, distribution: values };
128
125
  };
129
- return { joy: statistics(week.joy), sadness: statistics(week.sadness), fear: statistics(week.fear),
130
- anger: statistics(week.anger), disgust: statistics(week.disgust), surprise: statistics(week.surprise) };
126
+ return perEmotion(emotion => statistics(week[emotion]));
131
127
  }
132
128
  /** Freeze a population's rank prefixes before later grades join it. */
133
129
  function ranks(population) {
@@ -137,8 +133,7 @@ function ranks(population) {
137
133
  prefix.push(prefix.at(-1) + n);
138
134
  return { count: h.count, mean: (h.sum + h.carry) / h.count, prefix };
139
135
  };
140
- return { joy: freeze(population.joy), sadness: freeze(population.sadness), fear: freeze(population.fear),
141
- anger: freeze(population.anger), disgust: freeze(population.disgust), surprise: freeze(population.surprise) };
136
+ return perEmotion(emotion => freeze(population[emotion]));
142
137
  }
143
138
  function compare(row, population, minimum) {
144
139
  const count = population.joy.count;
@@ -150,8 +145,7 @@ function compare(row, population, minimum) {
150
145
  const percentile = (prefix[b] + (prefix[b + 1] - prefix[b]) / 2) / count;
151
146
  return { delta: score - mean, percentile, unusualness: Math.abs(2 * percentile - 1) };
152
147
  };
153
- return { status: "ok", count, emotions: { joy: deviation("joy"), sadness: deviation("sadness"), fear: deviation("fear"),
154
- anger: deviation("anger"), disgust: deviation("disgust"), surprise: deviation("surprise") } };
148
+ return { status: "ok", count, emotions: perEmotion(deviation) };
155
149
  }
156
150
  /** Queue writes and commit them in short IMMEDIATE transactions. Only call between completed reads. */
157
151
  function batches(db) {
@@ -159,16 +153,8 @@ function batches(db) {
159
153
  const flush = () => {
160
154
  if (!pending.length)
161
155
  return;
162
- db.exec("BEGIN IMMEDIATE");
163
- try {
164
- for (const write of pending)
165
- write();
166
- db.exec("COMMIT");
167
- }
168
- catch (error) {
169
- db.exec("ROLLBACK");
170
- throw error;
171
- }
156
+ immediateTransaction(db, () => { for (const write of pending)
157
+ write(); });
172
158
  pending.length = 0;
173
159
  };
174
160
  return { write(change) { pending.push(change); if (pending.length >= BATCH)
@@ -186,23 +172,29 @@ export function refreshEmotionBaselines(db, options) {
186
172
  initializeEmotionBaselines(db);
187
173
  let snapshots = 0, comparisons = 0;
188
174
  const queue = batches(db), people = tableExists(db, "people");
189
- const prior = db.prepare(`SELECT id,result_json FROM inside_out_deviations WHERE interaction_id=? AND rubric=? AND grade_signature=?
190
- ORDER BY assessed_at DESC,rowid DESC LIMIT 1`);
175
+ const prior = db.prepare(`SELECT id,result_json,json_extract(result_json,'$.status') status FROM inside_out_deviations
176
+ WHERE interaction_id=? AND rubric=? AND grade_signature=? ORDER BY assessed_at DESC,rowid DESC LIMIT 1`);
191
177
  const save = db.prepare("INSERT OR IGNORE INTO inside_out_deviations VALUES (?,?,?,?,?,?,?,?)");
178
+ const grade = db.prepare(`SELECT ${GRADE} FROM inside_out WHERE interaction_id=? AND rubric=?`);
192
179
  const assess = (row, signature, decide) => {
193
180
  const previous = prior.get(row.interaction_id, row.rubric, signature);
194
- if (!options.recompare && previous)
181
+ // An existing assessment stands for its grade, except future_time: that only described the clock.
182
+ if (!options.recompare && previous && previous.status !== "future_time")
195
183
  return;
196
184
  const result = { version: VERSION, status: "insufficient_history", personId: row.person_id === null ? null : String(row.person_id),
197
185
  baselineId: null, baselineEnd: null, assessedAt: now, minInteractions: minimum, cumulative: null, weekly: null };
198
186
  decide(result);
199
- const key = (assessment) => hash([assessment.version, signature, assessment.baselineId, assessment.status, assessment.minInteractions]);
187
+ const key = (assessment) => jsonHash([assessment.version, signature, assessment.baselineId, assessment.status, assessment.minInteractions]);
200
188
  if (previous && key(JSON.parse(String(previous.result_json))) === key(result))
201
189
  return;
202
190
  // Chaining records permits an explicit return to an earlier baseline without
203
191
  // selecting an obsolete intervening assessment or losing either observation.
204
- const id = hash([key(result), previous?.id ?? null]);
192
+ const id = jsonHash([key(result), previous?.id ?? null]);
205
193
  queue.write(() => {
194
+ // Rechecked under the write lock: a purge, regrade or relink committed since the read wins.
195
+ const current = grade.get(row.interaction_id, row.rubric);
196
+ if (!current || gradeSignature(current) !== signature)
197
+ return;
206
198
  comparisons += Number(save.run(id, row.interaction_id, row.rubric, signature, now, result.baselineId, result.personId, JSON.stringify(result)).changes);
207
199
  });
208
200
  };
@@ -213,8 +205,8 @@ export function refreshEmotionBaselines(db, options) {
213
205
  ON CONFLICT(person_id,rubric,model,week_start) DO UPDATE SET id=excluded.id,version=excluded.version,
214
206
  week_end=excluded.week_end,computed_at=excluded.computed_at,weekly_json=excluded.weekly_json`);
215
207
  const remove = db.prepare("DELETE FROM person_emotion_baselines WHERE person_id=? AND rubric=? AND model=? AND week_start=? AND id=?");
216
- const page = db.prepare(`SELECT interaction_id,rubric,model,person_id,target_at,reviewed_at,error,${INSIDE_OUT_EMOTIONS.join(",")}
217
- FROM inside_out e WHERE e.person_id=? AND e.rubric=? AND e.model=? AND ${COMPARABLE}
208
+ const populated = db.prepare("SELECT 1 FROM inside_out WHERE person_id=? AND rubric=? AND model=? LIMIT 1");
209
+ const page = db.prepare(`SELECT ${GRADE} FROM inside_out e WHERE e.person_id=? AND e.rubric=? AND e.model=? AND ${COMPARABLE}
218
210
  AND (? IS NULL OR e.target_at>? OR (e.target_at=? AND e.interaction_id>?)) ORDER BY e.target_at,e.interaction_id LIMIT ?`);
219
211
  const groups = db.prepare(`SELECT DISTINCT e.person_id,e.rubric,e.model FROM inside_out e JOIN people p ON p.id=e.person_id
220
212
  WHERE ${COMPARABLE}`).all(now, now);
@@ -262,11 +254,13 @@ export function refreshEmotionBaselines(db, options) {
262
254
  merge(cumulative, weekly);
263
255
  // Chained ids address the whole cumulative population without rehashing earlier weeks.
264
256
  // Empty weeks are kept: a weekly comparison always means the preceding calendar week.
265
- const id = hash([VERSION, person, rubric, model, start, previous?.id ?? null, signatures]), json = encode(weekly);
257
+ const id = jsonHash([VERSION, person, rubric, model, start, previous?.id ?? null, signatures]), json = encode(weekly);
266
258
  current.add(start);
267
259
  if (existing.get(start) !== id)
268
260
  queue.write(() => {
269
- snapshots += Number(upsert.run(person, rubric, model, start, id, VERSION, end, now, json).changes);
261
+ // A purge of this person since the read leaves no linked grades: never restore their distribution.
262
+ if (populated.get(person, rubric, model))
263
+ snapshots += Number(upsert.run(person, rubric, model, start, id, VERSION, end, now, json).changes);
270
264
  });
271
265
  previous = { id, end, weekly };
272
266
  }
@@ -325,15 +319,28 @@ export function deviationReader(db) {
325
319
  }) } : current;
326
320
  };
327
321
  }
328
- /** Weekly snapshots, newest first; cumulative statistics are prefix sums of each population's stored weeks. */
322
+ /**
323
+ * Weekly snapshots, newest first; cumulative statistics are prefix sums of each population's stored weeks.
324
+ * `since` keeps weeks whose last day is on or after that UTC date (`week_end` is the exclusive next Monday).
325
+ */
329
326
  export function emotionBaselineHistory(db, options = {}) {
330
327
  const limit = options.limit ?? 100;
331
328
  if (!Number.isInteger(limit) || limit < 1 || limit > 1000)
332
329
  throw new Error("Baseline limit must be between 1 and 1000");
333
330
  if (schemaVersion(db) !== 2)
334
331
  return [];
332
+ // One read snapshot: a concurrent refresh may replace or drop weeks between the two queries.
333
+ db.exec("BEGIN");
334
+ try {
335
+ return readBaselineHistory(db, options, limit);
336
+ }
337
+ finally {
338
+ db.exec("COMMIT");
339
+ }
340
+ }
341
+ function readBaselineHistory(db, options, limit) {
335
342
  const selected = db.prepare(`SELECT person_id,rubric,model,week_start FROM person_emotion_baselines
336
- WHERE (? IS NULL OR person_id=?) AND (? IS NULL OR week_end>=?) ORDER BY week_end DESC,person_id,rubric,model LIMIT ?`)
343
+ WHERE (? IS NULL OR person_id=?) AND (? IS NULL OR week_end>?) ORDER BY week_end DESC,person_id,rubric,model LIMIT ?`)
337
344
  .all(options.personId ?? null, options.personId ?? null, options.since ?? null, options.since ?? null, limit);
338
345
  const wanted = new Map();
339
346
  for (const row of selected) {
@@ -358,6 +365,25 @@ export function emotionBaselineHistory(db, options = {}) {
358
365
  }
359
366
  return selected.map(row => snapshots.get(JSON.stringify([JSON.stringify([row.person_id, row.rubric, row.model]), row.week_start])));
360
367
  }
368
+ /**
369
+ * Changes whenever a refresh input could: grades, links, people, stored results, the current week,
370
+ * grades crossing `now`, or settings. Equal fingerprints mean a refresh would write nothing.
371
+ */
372
+ export function baselineFingerprint(db, options) {
373
+ const digest = createHash("sha256").update(JSON.stringify([VERSION, schemaVersion(db) ?? null, weekStart(options.now), options.minInteractions]));
374
+ for (const table of ["people", "person_emotion_baselines", "inside_out_deviations"]) {
375
+ digest.update(`|${tableExists(db, table) ? Number(db.prepare(`SELECT count(*) n FROM ${table}`).get().n) : -1}`);
376
+ }
377
+ if (tableExists(db, "inside_out")) {
378
+ const timing = db.prepare("SELECT count(*) n,sum(target_at<=?) due,sum(reviewed_at<=?) reviewed FROM inside_out").get(options.now, options.now);
379
+ digest.update(`|${timing.n},${timing.due},${timing.reviewed}`);
380
+ // Regrades rewrite reviewed_at; links and purges rewrite person_id and error.
381
+ for (const row of db.prepare("SELECT rowid,person_id,reviewed_at,error IS NULL ok FROM inside_out ORDER BY rowid").iterate()) {
382
+ digest.update(`|${row.rowid},${row.person_id},${row.reviewed_at},${row.ok}`);
383
+ }
384
+ }
385
+ return digest.digest("hex");
386
+ }
361
387
  /**
362
388
  * Delete one person's baselines and assessment history. With `grades`, also erase their six
363
389
  * probabilities and person link, keeping a tombstone so the reply is never sent to Jev again.
@@ -367,8 +393,7 @@ export function purgeEmotionProfile(db, personId, options = {}) {
367
393
  if (!tableExists(db, "inside_out"))
368
394
  return counts;
369
395
  initializeEmotionBaselines(db);
370
- db.exec("BEGIN IMMEDIATE");
371
- try {
396
+ return immediateTransaction(db, () => {
372
397
  if (options.grades) {
373
398
  counts.assessments += Number(db.prepare(`DELETE FROM inside_out_deviations WHERE (interaction_id,rubric) IN
374
399
  (SELECT interaction_id,rubric FROM inside_out WHERE person_id=?)`).run(personId).changes);
@@ -377,11 +402,6 @@ export function purgeEmotionProfile(db, personId, options = {}) {
377
402
  }
378
403
  counts.assessments += Number(db.prepare("DELETE FROM inside_out_deviations WHERE person_id=?").run(personId).changes);
379
404
  counts.baselines = Number(db.prepare("DELETE FROM person_emotion_baselines WHERE person_id=?").run(personId).changes);
380
- db.exec("COMMIT");
381
405
  return counts;
382
- }
383
- catch (error) {
384
- db.exec("ROLLBACK");
385
- throw error;
386
- }
406
+ });
387
407
  }
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { parseSafeVirtualPath } from "./sources.js";
3
+ import { TYPESAFE_MODEL } from "./typesafe-client.js";
3
4
  import { reviewTypeSafeClaim } from "./typesafe-review.js";
4
5
  export async function reviewIndexedClaim(params) {
5
6
  const unavailable = (reason) => ({ status: "unavailable", verdict: "insufficient_evidence", needsReview: true, reason });
@@ -45,7 +46,7 @@ export async function reviewIndexedClaim(params) {
45
46
  }
46
47
  return { status: "ok", ...judgment,
47
48
  evidence: evidence.map(({ text: _text, ...citation }) => citation),
48
- policy: params.personBackground ? "jev-1.13.0:person-background-v2" : "jev-1.13.0:claim-v1",
49
+ policy: `${TYPESAFE_MODEL}:${params.personBackground ? "person-background-v2" : "claim-v1"}`,
49
50
  scope: "Advisory support check against cited indexed excerpts only, not current truth or authorization to write. Verify original sources and identity before promotion." };
50
51
  });
51
52
  }
@@ -1,12 +1,11 @@
1
- import { createHash } from "node:crypto";
2
1
  import { Type } from "typebox";
3
2
  import { Value } from "typebox/value";
4
3
  import { EXTRACTION_INPUT_LIMIT, EXTRACTION_INPUT_TARGET, extractionMessageTokens, extractionOverhead } from "./extraction-model.js";
5
4
  import { readExtractionPage } from "./extraction-source.js";
5
+ import { jsonHash } from "./json-hash.js";
6
6
  const PREFIX = "unblock-extraction:v1:";
7
7
  const bookmarkSchema = Type.Object({ before: Type.Union([Type.Null(), Type.String()]), fence: Type.String(),
8
8
  index: Type.Integer({ minimum: 0 }), offset: Type.Integer({ minimum: 0 }), id: Type.String(), hash: Type.String() });
9
- function digest(message) { return createHash("sha256").update(JSON.stringify(message)).digest("hex"); }
10
9
  function fragment(message, start, end) {
11
10
  const sourceMessageId = message.sourceMessageId ?? message.id, offset = (message.textOffset ?? 0) + start;
12
11
  return { ...message, sourceMessageId, textOffset: offset,
@@ -91,7 +90,7 @@ export async function readExtractionChunk(params) {
91
90
  return page;
92
91
  if ((page.entryCount && page.cursor === before) || (!page.entryCount && page.hasMore))
93
92
  throw new Error("Transcript reader made no progress");
94
- if (resume && (!page.messages[resume.index] || page.messages[resume.index].id !== resume.id || digest(page.messages[resume.index]) !== resume.hash)) {
93
+ if (resume && (!page.messages[resume.index] || page.messages[resume.index].id !== resume.id || jsonHash(page.messages[resume.index]) !== resume.hash)) {
95
94
  throw new Error("Partial extraction source changed");
96
95
  }
97
96
  entryCount += page.entryCount;
@@ -99,7 +98,7 @@ export async function readExtractionChunk(params) {
99
98
  const next = page.messages[index];
100
99
  return { kind: "page", messages, newIds, entryCount, fence: startingFence ?? page.cursor,
101
100
  exhausted: !next && !page.hasMore,
102
- cursor: next ? PREFIX + JSON.stringify({ before, fence: page.cursor, index, offset, id: next.id, hash: digest(next) }) : page.cursor };
101
+ cursor: next ? PREFIX + JSON.stringify({ before, fence: page.cursor, index, offset, id: next.id, hash: jsonHash(next) }) : page.cursor };
103
102
  };
104
103
  for (let i = resume?.index ?? 0; i < page.messages.length; i++) {
105
104
  const message = page.messages[i];
@@ -2,7 +2,9 @@ import type { QMDStore } from "@unblocklabs/qmd";
2
2
  import type { CorpusMemorySearchResult } from "./contracts.js";
3
3
  import { type ExtractedRecord } from "./extraction-store.js";
4
4
  export declare const EXTRACTED_COLLECTION = "unblock-extracted";
5
+ export declare const EXTRACTED_PREFIX = "qmd://unblock-extracted/";
5
6
  export declare function extractedPath(record: ExtractedRecord): string;
7
+ export declare function extractedUri(record: ExtractedRecord): string;
6
8
  export declare function extractedRecords(storePath: string, paths?: readonly string[]): ExtractedRecord[];
7
9
  export declare function extractedHit(record: ExtractedRecord, score: number): CorpusMemorySearchResult;
8
10
  /** Single adapter for QMD's documented advanced store API; no Markdown and no private SQL writes. */
@@ -2,9 +2,11 @@ import { createHash } from "node:crypto";
2
2
  import { hasMemoryTable } from "./memory-database.js";
3
3
  import { ExtractionStore } from "./extraction-store.js";
4
4
  export const EXTRACTED_COLLECTION = "unblock-extracted";
5
+ export const EXTRACTED_PREFIX = `qmd://${EXTRACTED_COLLECTION}/`;
5
6
  export function extractedPath(record) { return `${record.id}/${record.revision}`; }
7
+ export function extractedUri(record) { return `${EXTRACTED_PREFIX}${extractedPath(record)}`; }
6
8
  export function extractedRecords(storePath, paths) {
7
- if (!hasMemoryTable(storePath, "extracted_memories"))
9
+ if (paths?.length === 0 || !hasMemoryTable(storePath, "extracted_memories"))
8
10
  return [];
9
11
  const store = new ExtractionStore(storePath);
10
12
  try {
@@ -15,7 +17,7 @@ export function extractedRecords(storePath, paths) {
15
17
  }
16
18
  }
17
19
  export function extractedHit(record, score) {
18
- return { path: `qmd://${EXTRACTED_COLLECTION}/${extractedPath(record)}`, startLine: 1, endLine: 1, score,
20
+ return { path: extractedUri(record), startLine: 1, endLine: 1, score,
19
21
  snippet: record.text, corpus: "extracted", source: "memory", session: record.metadata,
20
22
  extracted: { id: record.id, revision: record.revision, observedAt: new Date(record.observedAt).toISOString() },
21
23
  citation: `session:${record.sessionId}#${record.evidence.map(e => e.messageId).join(",")}` };
@@ -3,11 +3,11 @@ import { Type } from "typebox";
3
3
  import { Value } from "typebox/value";
4
4
  import { callGatewayFromCli, errorShape, ErrorCodes } from "openclaw/plugin-sdk/gateway-runtime";
5
5
  import { listAgentIds, resolveAgentIdentity } from "openclaw/plugin-sdk/agent-runtime";
6
- import { resolveAgentDir, resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
7
6
  import { MEMORY_DATABASE, hasMemoryTable } from "./memory-database.js";
8
7
  import { ExtractionStore } from "./extraction-store.js";
9
8
  import { extractionSessions } from "./extraction-source.js";
10
9
  import { dateOption } from "./date-option.js";
10
+ import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
11
11
  export function registerExtraction(api, config, runtime) {
12
12
  let lifetime = new AbortController();
13
13
  let timer, running;
@@ -15,8 +15,8 @@ export function registerExtraction(api, config, runtime) {
15
15
  if (!listAgentIds(cfg).includes(agentId))
16
16
  throw new Error("Unknown extraction agent");
17
17
  return { agentId, agentName: resolveAgentIdentity(cfg, agentId)?.name?.trim() || agentId,
18
- config, runtime: api.runtime, storePath: join(resolveStateDir(), "agents", agentId, "unblock-memory", MEMORY_DATABASE),
19
- sessions: () => extractionSessions(join(resolveAgentDir(cfg, agentId), "openclaw-agent.sqlite"), agentId, config.extraction.chatTypes) };
18
+ config, runtime: api.runtime, storePath: join(agentStateDir(agentId), MEMORY_DATABASE),
19
+ sessions: () => extractionSessions(agentTranscriptDatabase(cfg, agentId), agentId, config.extraction.chatTypes) };
20
20
  };
21
21
  const run = async (cfg, agentId, signal, since, sessionId, scheduled = false) => {
22
22
  const opts = options(cfg, agentId);