@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
package/README.md CHANGED
@@ -8,8 +8,9 @@ keyword or vector similarity.
8
8
 
9
9
  ## Quick start
10
10
 
11
- **Requirements:** Node.js 22+, OpenClaw 2026.8.1-beta.3 or later, and a
12
- [TypeSafe](https://docs.typesafe.ai) API key. Search uses TypeSafe to rank results.
11
+ **Requirements:** Node.js 22+ and OpenClaw 2026.8.1-beta.3 or later.
12
+ A [TypeSafe](https://docs.typesafe.ai) API key enables usefulness ranking; without
13
+ it, explicit search returns labeled local search leads.
13
14
 
14
15
  1. Install once per OpenClaw host, not once per agent:
15
16
 
@@ -17,7 +18,7 @@ keyword or vector similarity.
17
18
  openclaw plugins install npm:@unblocklabs/unblock-memory
18
19
  ```
19
20
 
20
- 2. Save your TypeSafe key in a private file (`chmod 600`), for example
21
+ 2. For usefulness ranking, save your TypeSafe key in a private file (`chmod 600`), for example
21
22
  `~/.openclaw/secrets/unblock-memory-typesafe.env`:
22
23
 
23
24
  ```dotenv
@@ -88,13 +89,15 @@ come back with their source location.
88
89
 
89
90
  The agent then calls `memory_get` with that `path` to read the surrounding
90
91
  context, attribution and dates. Search defaults to 5 results with a usefulness
91
- score of at least 0.7. See [search and read](docs/retrieval.md#search-and-read)
92
- for every parameter.
92
+ score of at least 0.7 when TypeSafe is available. If ranking is unavailable,
93
+ search returns unjudged local leads with a warning; the usefulness threshold
94
+ is not applied. Automatic Memory Whisperer hints still require TypeSafe.
95
+ See [search and read](docs/retrieval.md#search-and-read) for every parameter.
93
96
 
94
97
  **What leaves your machine:** indexing, embeddings, storage and `memory_get` run
95
98
  locally. `memory_search` sends the search question and candidate passages, with
96
- their paths and dates, to TypeSafe for scoring. Optional TypeSafe features send
97
- only what their own settings approve; see
99
+ their paths and dates, to TypeSafe for scoring when available. Optional TypeSafe
100
+ features send only what their own settings approve; see
98
101
  [TypeSafe data scope](docs/configuration.md#typesafe-data-scope).
99
102
 
100
103
  **On by default:** search and read over the `memory` corpus, and a
@@ -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(`
@@ -102,9 +102,10 @@ export declare class WhispererDiagnostics {
102
102
  failed?: number | undefined;
103
103
  empty?: number | undefined;
104
104
  timed_out?: number | undefined;
105
+ degraded?: number | undefined;
105
106
  };
106
107
  slowestRecent: {
107
- outcome: "cancelled" | "ok" | "partial" | "skipped" | "failed" | "empty" | "timed_out";
108
+ outcome: "cancelled" | "ok" | "partial" | "skipped" | "failed" | "empty" | "timed_out" | "degraded";
108
109
  setupMs?: number | undefined;
109
110
  queueWaitMs?: number | undefined;
110
111
  metadataMs?: number | undefined;
@@ -133,6 +134,10 @@ export declare class WhispererDiagnostics {
133
134
  eligible?: number | undefined;
134
135
  results?: number | undefined;
135
136
  contextChars?: number | undefined;
137
+ requestsSucceeded?: number | undefined;
138
+ requestsFailed?: number | undefined;
139
+ fallbackKeyUnavailable?: number | undefined;
140
+ fallbackAllJudgmentsFailed?: number | undefined;
136
141
  }[];
137
142
  measurements: {
138
143
  [k: string]: {
@@ -4,7 +4,7 @@ export class WhispererDiagnostics {
4
4
  static shared() {
5
5
  const scope = globalThis;
6
6
  // Bump the version whenever the shape changes so an older loaded copy is never reused.
7
- const symbol = Symbol.for("unblock-memory.whisperer-diagnostics.v2");
7
+ const symbol = Symbol.for("unblock-memory.whisperer-diagnostics.v3");
8
8
  return (scope[symbol] ??= new WhispererDiagnostics());
9
9
  }
10
10
  #agents = new Map();
@@ -4,8 +4,6 @@ export declare const INSIDE_OUT_EMOTIONS: readonly ["joy", "sadness", "fear", "a
4
4
  export declare const PURGED_GRADE = "Purged by operator";
5
5
  type Emotion = typeof INSIDE_OUT_EMOTIONS[number];
6
6
  type Row = Record<string, SQLOutputValue>;
7
- export declare const hash: (value: unknown) => string;
8
- export declare const tableExists: (db: DatabaseSync, name: string) => boolean;
9
7
  type Statistics = {
10
8
  count: number;
11
9
  mean: number | null;
@@ -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,8 @@ 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
- export 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
- export const tableExists = (db, name) => Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?").get(name));
17
19
  const GRADE = `interaction_id,rubric,model,person_id,target_at,reviewed_at,error,${INSIDE_OUT_EMOTIONS.join(",")}`;
18
20
  const VALID = INSIDE_OUT_EMOTIONS.map(e => `e.${e} BETWEEN 0 AND 1`).join(" AND ");
19
21
  // Comparable grades: successful, timed, not after `now`. Callers add the People join.
@@ -28,8 +30,7 @@ function schemaVersion(db) {
28
30
  function initializeEmotionBaselines(db) {
29
31
  if (schemaVersion(db) === 2)
30
32
  return;
31
- db.exec("BEGIN IMMEDIATE");
32
- try {
33
+ immediateTransaction(db, () => {
33
34
  const version = schemaVersion(db);
34
35
  if (version !== undefined && version !== 1 && version !== 2)
35
36
  throw new Error("Unsupported Inside Out baseline storage version");
@@ -48,20 +49,15 @@ function initializeEmotionBaselines(db) {
48
49
  CREATE INDEX IF NOT EXISTS inside_out_deviations_interaction ON inside_out_deviations(interaction_id,rubric);
49
50
  CREATE INDEX IF NOT EXISTS inside_out_deviations_person ON inside_out_deviations(person_id);
50
51
  INSERT OR REPLACE INTO memory_schema VALUES ('emotion-baselines',2);`);
51
- db.exec("COMMIT");
52
- }
53
- catch (error) {
54
- db.exec("ROLLBACK");
55
- throw error;
56
- }
52
+ });
57
53
  }
58
54
  function gradeSignature(row) {
59
- 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,
60
56
  row.reviewed_at, row.error, ...INSIDE_OUT_EMOTIONS.map(e => row[e])]);
61
57
  }
62
58
  function histograms() {
63
59
  const empty = () => ({ count: 0, sum: 0, carry: 0, min: Infinity, max: -Infinity, bins: new Array(STEPS + 1).fill(0) });
64
- return { joy: empty(), sadness: empty(), fear: empty(), anger: empty(), disgust: empty(), surprise: empty() };
60
+ return perEmotion(empty);
65
61
  }
66
62
  // Neumaier summation keeps means exact for repeated values: twenty 0.8s average to 0.8.
67
63
  function accumulate(target, value, count, min, max) {
@@ -127,8 +123,7 @@ function summarize(week) {
127
123
  return { count: h.count, mean: h.count ? (h.sum + h.carry) / h.count : null, min: h.count ? h.min : null,
128
124
  p10: quantile(0.1), median: quantile(0.5), p90: quantile(0.9), max: h.count ? h.max : null, distribution: values };
129
125
  };
130
- return { joy: statistics(week.joy), sadness: statistics(week.sadness), fear: statistics(week.fear),
131
- anger: statistics(week.anger), disgust: statistics(week.disgust), surprise: statistics(week.surprise) };
126
+ return perEmotion(emotion => statistics(week[emotion]));
132
127
  }
133
128
  /** Freeze a population's rank prefixes before later grades join it. */
134
129
  function ranks(population) {
@@ -138,8 +133,7 @@ function ranks(population) {
138
133
  prefix.push(prefix.at(-1) + n);
139
134
  return { count: h.count, mean: (h.sum + h.carry) / h.count, prefix };
140
135
  };
141
- return { joy: freeze(population.joy), sadness: freeze(population.sadness), fear: freeze(population.fear),
142
- anger: freeze(population.anger), disgust: freeze(population.disgust), surprise: freeze(population.surprise) };
136
+ return perEmotion(emotion => freeze(population[emotion]));
143
137
  }
144
138
  function compare(row, population, minimum) {
145
139
  const count = population.joy.count;
@@ -151,8 +145,7 @@ function compare(row, population, minimum) {
151
145
  const percentile = (prefix[b] + (prefix[b + 1] - prefix[b]) / 2) / count;
152
146
  return { delta: score - mean, percentile, unusualness: Math.abs(2 * percentile - 1) };
153
147
  };
154
- return { status: "ok", count, emotions: { joy: deviation("joy"), sadness: deviation("sadness"), fear: deviation("fear"),
155
- anger: deviation("anger"), disgust: deviation("disgust"), surprise: deviation("surprise") } };
148
+ return { status: "ok", count, emotions: perEmotion(deviation) };
156
149
  }
157
150
  /** Queue writes and commit them in short IMMEDIATE transactions. Only call between completed reads. */
158
151
  function batches(db) {
@@ -160,16 +153,8 @@ function batches(db) {
160
153
  const flush = () => {
161
154
  if (!pending.length)
162
155
  return;
163
- db.exec("BEGIN IMMEDIATE");
164
- try {
165
- for (const write of pending)
166
- write();
167
- db.exec("COMMIT");
168
- }
169
- catch (error) {
170
- db.exec("ROLLBACK");
171
- throw error;
172
- }
156
+ immediateTransaction(db, () => { for (const write of pending)
157
+ write(); });
173
158
  pending.length = 0;
174
159
  };
175
160
  return { write(change) { pending.push(change); if (pending.length >= BATCH)
@@ -199,12 +184,12 @@ export function refreshEmotionBaselines(db, options) {
199
184
  const result = { version: VERSION, status: "insufficient_history", personId: row.person_id === null ? null : String(row.person_id),
200
185
  baselineId: null, baselineEnd: null, assessedAt: now, minInteractions: minimum, cumulative: null, weekly: null };
201
186
  decide(result);
202
- 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]);
203
188
  if (previous && key(JSON.parse(String(previous.result_json))) === key(result))
204
189
  return;
205
190
  // Chaining records permits an explicit return to an earlier baseline without
206
191
  // selecting an obsolete intervening assessment or losing either observation.
207
- const id = hash([key(result), previous?.id ?? null]);
192
+ const id = jsonHash([key(result), previous?.id ?? null]);
208
193
  queue.write(() => {
209
194
  // Rechecked under the write lock: a purge, regrade or relink committed since the read wins.
210
195
  const current = grade.get(row.interaction_id, row.rubric);
@@ -269,7 +254,7 @@ export function refreshEmotionBaselines(db, options) {
269
254
  merge(cumulative, weekly);
270
255
  // Chained ids address the whole cumulative population without rehashing earlier weeks.
271
256
  // Empty weeks are kept: a weekly comparison always means the preceding calendar week.
272
- 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);
273
258
  current.add(start);
274
259
  if (existing.get(start) !== id)
275
260
  queue.write(() => {
@@ -408,8 +393,7 @@ export function purgeEmotionProfile(db, personId, options = {}) {
408
393
  if (!tableExists(db, "inside_out"))
409
394
  return counts;
410
395
  initializeEmotionBaselines(db);
411
- db.exec("BEGIN IMMEDIATE");
412
- try {
396
+ return immediateTransaction(db, () => {
413
397
  if (options.grades) {
414
398
  counts.assessments += Number(db.prepare(`DELETE FROM inside_out_deviations WHERE (interaction_id,rubric) IN
415
399
  (SELECT interaction_id,rubric FROM inside_out WHERE person_id=?)`).run(personId).changes);
@@ -418,11 +402,6 @@ export function purgeEmotionProfile(db, personId, options = {}) {
418
402
  }
419
403
  counts.assessments += Number(db.prepare("DELETE FROM inside_out_deviations WHERE person_id=?").run(personId).changes);
420
404
  counts.baselines = Number(db.prepare("DELETE FROM person_emotion_baselines WHERE person_id=?").run(personId).changes);
421
- db.exec("COMMIT");
422
405
  return counts;
423
- }
424
- catch (error) {
425
- db.exec("ROLLBACK");
426
- throw error;
427
- }
406
+ });
428
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);
@@ -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
  function memoryDigest(text) {
4
4
  return createHash("sha256").update(text.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.!]+$/, "")).digest("hex");
5
5
  }
@@ -60,7 +60,7 @@ export class ExtractionStore {
60
60
  release(owner) { this.db.prepare("UPDATE extraction_worker SET owner=NULL,lease_until=0 WHERE id=1 AND owner=?").run(owner); }
61
61
  checkpoint(session, since) {
62
62
  this.db.prepare(`INSERT INTO extraction_sessions(session_id,metadata,updated_at,extract_since) VALUES(?,?,?,?)
63
- ON CONFLICT(session_id) DO UPDATE SET metadata=excluded.metadata`).run(session.sessionId, JSON.stringify(session), Date.now(), since ?? this.liveSince());
63
+ ON CONFLICT(session_id) DO UPDATE SET metadata=excluded.metadata WHERE metadata IS NOT excluded.metadata`).run(session.sessionId, JSON.stringify(session), Date.now(), since ?? this.liveSince());
64
64
  const row = this.db.prepare("SELECT cursor,context,extract_since,complete_revision FROM extraction_sessions WHERE session_id=?").get(session.sessionId);
65
65
  if (since !== undefined && since < Number(row.extract_since)) {
66
66
  // A broader explicitly approved backfill replays this session. Existing facts are
@@ -83,22 +83,15 @@ export class ExtractionStore {
83
83
  observedAt: Number(r.observed_at), evidence: JSON.parse(String(r.evidence)), metadata: JSON.parse(String(r.metadata)), judgment: JSON.parse(String(r.judgment)) }));
84
84
  }
85
85
  reset(sessionId, cursor, owner) {
86
- this.db.exec("BEGIN IMMEDIATE");
87
- try {
86
+ immediateTransaction(this.db, () => {
88
87
  this.renew(owner);
89
88
  this.db.prepare("UPDATE extracted_memories SET status='withdrawn' WHERE session_id=? AND status='active'").run(sessionId);
90
89
  this.db.prepare("UPDATE extraction_sessions SET cursor=?,context='[]',complete_revision=NULL,error=NULL WHERE session_id=?").run(cursor, sessionId);
91
- this.db.exec("COMMIT");
92
- }
93
- catch (error) {
94
- this.db.exec("ROLLBACK");
95
- throw error;
96
- }
90
+ });
97
91
  }
98
92
  commit(params) {
99
- this.db.exec("BEGIN IMMEDIATE");
100
- let written = 0;
101
- try {
93
+ return immediateTransaction(this.db, () => {
94
+ let written = 0;
102
95
  this.renew(params.owner);
103
96
  const current = this.db.prepare("SELECT cursor FROM extraction_sessions WHERE session_id=?").get(params.session.sessionId);
104
97
  if (current?.cursor !== params.expected)
@@ -125,13 +118,8 @@ export class ExtractionStore {
125
118
  }
126
119
  this.db.prepare("UPDATE extraction_sessions SET cursor=?,context=?,updated_at=?,complete_revision=?,error=NULL WHERE session_id=?")
127
120
  .run(params.cursor, JSON.stringify(params.context), Date.now(), params.completeRevision ?? null, params.session.sessionId);
128
- this.db.exec("COMMIT");
129
121
  return written;
130
- }
131
- catch (error) {
132
- this.db.exec("ROLLBACK");
133
- throw error;
134
- }
122
+ });
135
123
  }
136
124
  error(sessionId, code) {
137
125
  this.db.prepare("UPDATE extraction_sessions SET error=?,updated_at=? WHERE session_id=?").run(code, Date.now(), sessionId);