@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,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);
@@ -59,9 +59,10 @@ export async function runExtraction(params) {
59
59
  if (existing.length > 100 || JSON.stringify(existing.map(m => ({ id: m.id, text: m.text }))).length > 40_000) {
60
60
  throw new Error("Existing memories exceed review budget");
61
61
  }
62
+ const existingFacts = existing.map(m => ({ id: m.id, text: m.text, observedAt: m.observedAt }));
62
63
  const page = await readExtractionChunk({ agentId: params.agentId, agentName: params.agentName, session,
63
64
  cursor: checkpoint.cursor, context: extractionHistory(checkpoint.context, config.historyMessages),
64
- existing: existing.map(m => ({ id: m.id, text: m.text, observedAt: m.observedAt })), signal, readPage });
65
+ existing: existingFacts, signal, readPage });
65
66
  if (page.kind === "unavailable") {
66
67
  store.error(session.sessionId, "source_unavailable");
67
68
  failed++;
@@ -85,7 +86,7 @@ export async function runExtraction(params) {
85
86
  const messages = page.messages;
86
87
  const newIds = fresh.map(m => m.id);
87
88
  stage = "propose";
88
- const proposals = newIds.length ? await (params.extract ?? extractWithLuna)(params.runtime, params.agentId, messages, newIds, existing.map(m => ({ id: m.id, text: m.text, observedAt: m.observedAt })), signal) : [];
89
+ const proposals = newIds.length ? await (params.extract ?? extractWithLuna)(params.runtime, params.agentId, messages, newIds, existingFacts, signal) : [];
89
90
  const accepted = [];
90
91
  stage = "validate";
91
92
  for (let start = 0; start < proposals.length; start += 4) {
@@ -0,0 +1,6 @@
1
+ /** Narrowing for untrusted JSON-shaped input such as transcripts and API responses. */
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
3
+ /** A plain object, or undefined for null, arrays and primitives. */
4
+ export declare function record(value: unknown): Record<string, unknown> | undefined;
5
+ /** A trimmed non-empty string, or undefined. */
6
+ export declare function nonBlank(value: unknown): string | undefined;
@@ -0,0 +1,12 @@
1
+ /** Narrowing for untrusted JSON-shaped input such as transcripts and API responses. */
2
+ export function isRecord(value) {
3
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4
+ }
5
+ /** A plain object, or undefined for null, arrays and primitives. */
6
+ export function record(value) {
7
+ return isRecord(value) ? value : undefined;
8
+ }
9
+ /** A trimmed non-empty string, or undefined. */
10
+ export function nonBlank(value) {
11
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
12
+ }
@@ -1,16 +1,17 @@
1
1
  import { join, dirname } from "node:path";
2
- import { resolveAgentDir, resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
2
+ import { resolveAgentDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
3
3
  import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
4
4
  import { MEMORY_DATABASE } from "./memory-database.js";
5
5
  import { dateOption } from "./date-option.js";
6
6
  import { linkInsideOutPeople, purgeInsideOutPerson, repairInsideOutIdentities, reportInsideOut, runInsideOut, refreshInsideOutBaselinesAsync, reportInsideOutBaselines } from "./inside-out.js";
7
+ import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
7
8
  export function registerInsideOut(api, config) {
8
9
  const paths = (cfg, agentId) => {
9
10
  if (!listAgentIds(cfg).includes(agentId))
10
11
  throw new Error("Unknown Inside Out agent");
11
12
  const agentDir = resolveAgentDir(cfg, agentId);
12
- return { agentId, databasePath: join(agentDir, "openclaw-agent.sqlite"), sessionsDir: join(dirname(agentDir), "sessions"),
13
- storePath: join(resolveStateDir(), "agents", agentId, "unblock-memory", MEMORY_DATABASE) };
13
+ return { agentId, databasePath: agentTranscriptDatabase(cfg, agentId), sessionsDir: join(dirname(agentDir), "sessions"),
14
+ storePath: join(agentStateDir(agentId), MEMORY_DATABASE) };
14
15
  };
15
16
  api.registerCli(({ program, config: cfg }) => {
16
17
  const root = program.command("memory-emotions").description("Inside Out: review human replies and analyze emotion probabilities");
@@ -2,7 +2,10 @@ import type { DatabaseSync } from "node:sqlite";
2
2
  import { refreshEmotionBaselines } from "./emotion-baselines.js";
3
3
  export declare const PERSON_MATCH = "SELECT min(i.person_id) person_id FROM person_identities i\n WHERE i.provider=e.channel AND i.external_id=e.sender_id\n AND (i.account_scope=json_extract(e.human_key,'$[1]') OR substr(json_extract(e.human_key,'$[1]'),1,8)='session:')\n HAVING count(DISTINCT i.person_id)=1";
4
4
  export declare function openInsideOutStore(path: string): DatabaseSync;
5
- /** Refresh People links without loading transcripts or calling Jev. Known accounts stay exact. Purged grades stay unlinked. */
5
+ /**
6
+ * Refresh People links without loading transcripts or calling Jev. Known accounts stay exact.
7
+ * Purged grades stay unlinked. Matching is a read; only changed links are written, in short batches.
8
+ */
6
9
  export declare function linkInsideOutPeople(path: string): {
7
10
  updated: number;
8
11
  linked: number;
@@ -18,9 +21,30 @@ type BaselineResult = ReturnType<typeof refreshEmotionBaselines>;
18
21
  /** Rebuild local statistics from existing grades, refreshing exact People links first unless the caller just did. */
19
22
  export declare function refreshInsideOutBaselines(path: string, options?: BaselineOptions): BaselineResult;
20
23
  /**
21
- * Keep historical aggregation off the Gateway event loop; serialize refreshes per store.
22
- * Aborting skips queued work and terminates a running worker: SQLite rolls back its open
23
- * batch, committed batches are idempotent, and the next refresh resumes.
24
+ * Worker entry, also behind the synchronous API. `unless`: the fingerprint left by this store's
25
+ * previous refresh; unchanged inputs skip the pass.
26
+ * @public loaded by name from the worker thread
27
+ */
28
+ export declare function refreshWithFingerprint(path: string, options: BaselineOptions & {
29
+ unless?: string;
30
+ }): {
31
+ result: {
32
+ snapshots: number;
33
+ comparisons: number;
34
+ };
35
+ fingerprint?: undefined;
36
+ } | {
37
+ result: {
38
+ snapshots: number;
39
+ comparisons: number;
40
+ };
41
+ fingerprint: string;
42
+ };
43
+ /**
44
+ * Keep historical aggregation off the Gateway event loop; serialize refreshes per store, and skip
45
+ * one whose inputs have not changed since this process's previous refresh of that store.
46
+ * Aborting skips queued work and terminates a running worker. Its connection closes with the
47
+ * worker, so SQLite rolls back the open batch; committed batches are idempotent and the next refresh resumes.
24
48
  */
25
49
  export declare function refreshInsideOutBaselinesAsync(path: string, options?: BaselineOptions, signal?: AbortSignal): Promise<{
26
50
  snapshots: number;
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { Worker } from "node:worker_threads";
3
- import { openMemoryDatabase } from "./memory-database.js";
4
- import { PURGED_GRADE, purgeEmotionProfile, refreshEmotionBaselines } from "./emotion-baselines.js";
3
+ import { immediateTransaction, openMemoryDatabase, tableExists } from "./memory-database.js";
4
+ import { PURGED_GRADE, baselineFingerprint, purgeEmotionProfile, refreshEmotionBaselines } from "./emotion-baselines.js";
5
5
  // Imported by the baseline worker with plain Node resolution: host SDK aliases do not
6
6
  // reach worker threads, so this module and its imports must stay free of `openclaw`.
7
7
  const SCHEMA = `CREATE TABLE IF NOT EXISTS inside_out (
@@ -38,15 +38,25 @@ export function openInsideOutStore(path) {
38
38
  throw error;
39
39
  }
40
40
  }
41
- /** Refresh People links without loading transcripts or calling Jev. Known accounts stay exact. Purged grades stay unlinked. */
41
+ /**
42
+ * Refresh People links without loading transcripts or calling Jev. Known accounts stay exact.
43
+ * Purged grades stay unlinked. Matching is a read; only changed links are written, in short batches.
44
+ */
42
45
  export function linkInsideOutPeople(path) {
43
46
  const db = openInsideOutStore(path);
44
47
  try {
45
48
  let updated = 0;
46
- if (db.prepare("SELECT 1 FROM sqlite_schema WHERE name='person_identities'").get()) {
49
+ if (tableExists(db, "person_identities")) {
47
50
  const person = `(${PERSON_MATCH})`;
48
- updated = Number(db.prepare(`UPDATE inside_out AS e SET person_id=${person}
49
- WHERE person_id IS NOT ${person} AND error IS NOT ?`).run(PURGED_GRADE).changes);
51
+ const changes = db.prepare(`SELECT e.rowid id,${person} person_id FROM inside_out e
52
+ WHERE e.person_id IS NOT ${person} AND e.error IS NOT ?`).all(PURGED_GRADE);
53
+ const link = db.prepare("UPDATE inside_out SET person_id=? WHERE rowid=? AND error IS NOT ?");
54
+ for (let start = 0; start < changes.length; start += 500) {
55
+ immediateTransaction(db, () => {
56
+ for (const change of changes.slice(start, start + 500))
57
+ updated += Number(link.run(change.person_id, change.id, PURGED_GRADE).changes);
58
+ });
59
+ }
50
60
  }
51
61
  const counts = db.prepare(`SELECT count(person_id) linked,count(*)-count(person_id) unlinked FROM inside_out`).get();
52
62
  return { updated, linked: Number(counts.linked), unlinked: Number(counts.unlinked) };
@@ -57,52 +67,70 @@ export function linkInsideOutPeople(path) {
57
67
  }
58
68
  /** Rebuild local statistics from existing grades, refreshing exact People links first unless the caller just did. */
59
69
  export function refreshInsideOutBaselines(path, options = {}) {
70
+ return refreshWithFingerprint(path, options).result;
71
+ }
72
+ /**
73
+ * Worker entry, also behind the synchronous API. `unless`: the fingerprint left by this store's
74
+ * previous refresh; unchanged inputs skip the pass.
75
+ * @public loaded by name from the worker thread
76
+ */
77
+ export function refreshWithFingerprint(path, options) {
60
78
  if (!existsSync(path))
61
- return { snapshots: 0, comparisons: 0 };
79
+ return { result: { snapshots: 0, comparisons: 0 } };
62
80
  if (options.link !== false)
63
81
  linkInsideOutPeople(path);
64
82
  const db = openInsideOutStore(path);
65
83
  try {
66
- return refreshEmotionBaselines(db, { ...options, minInteractions: options.minInteractions ?? 20 });
84
+ const settings = { ...options, minInteractions: options.minInteractions ?? 20, now: options.now ?? Date.now() };
85
+ if (!options.recompare && options.unless && baselineFingerprint(db, settings) === options.unless) {
86
+ return { result: { snapshots: 0, comparisons: 0 }, fingerprint: options.unless };
87
+ }
88
+ const result = refreshEmotionBaselines(db, settings);
89
+ return { result, fingerprint: baselineFingerprint(db, settings) };
67
90
  }
68
91
  finally {
69
92
  db.close();
70
93
  }
71
94
  }
72
95
  const baselineJobs = new Map();
96
+ const fingerprints = new Map();
73
97
  /**
74
- * Keep historical aggregation off the Gateway event loop; serialize refreshes per store.
75
- * Aborting skips queued work and terminates a running worker: SQLite rolls back its open
76
- * batch, committed batches are idempotent, and the next refresh resumes.
98
+ * Keep historical aggregation off the Gateway event loop; serialize refreshes per store, and skip
99
+ * one whose inputs have not changed since this process's previous refresh of that store.
100
+ * Aborting skips queued work and terminates a running worker. Its connection closes with the
101
+ * worker, so SQLite rolls back the open batch; committed batches are idempotent and the next refresh resumes.
77
102
  */
78
103
  export function refreshInsideOutBaselinesAsync(path, options = {}, signal) {
79
- const settings = { ...options, now: options.now ?? Date.now() };
80
104
  const job = (baselineJobs.get(path) ?? Promise.resolve()).catch(() => { }).then(() => {
81
105
  signal?.throwIfAborted();
82
106
  if (!existsSync(path))
83
107
  return { snapshots: 0, comparisons: 0 };
108
+ const settings = { ...options, now: options.now ?? Date.now(), unless: fingerprints.get(path) };
84
109
  return new Promise((resolve, reject) => {
85
110
  const worker = new Worker(`
86
111
  const { parentPort, workerData } = require("node:worker_threads");
87
112
  // tsx's CLI preload only registers on the main thread. Source-mode
88
113
  // development needs explicit registration; compiled installs do not.
89
114
  if (workerData.module.endsWith(".ts")) require("node:module").createRequire(workerData.module)("tsx/esm/api").register();
90
- import(workerData.module).then(({ refreshInsideOutBaselines }) => {
91
- parentPort.postMessage(refreshInsideOutBaselines(workerData.path, workerData.options));
115
+ import(workerData.module).then(({ refreshWithFingerprint }) => {
116
+ parentPort.postMessage(refreshWithFingerprint(workerData.path, workerData.options));
92
117
  }).catch(error => { throw error; });
93
118
  `, { eval: true, workerData: { module: import.meta.url, path, options: settings } });
94
- let result, aborted = false;
119
+ let outcome, aborted = false;
95
120
  const abort = () => { aborted = true; void worker.terminate(); };
96
121
  signal?.addEventListener("abort", abort, { once: true });
97
- worker.once("message", (value) => { result = value; });
122
+ worker.once("message", (value) => { outcome = value; });
98
123
  worker.once("error", reject);
99
124
  // Settle only after the worker closes its database and exits.
100
125
  worker.once("exit", code => {
101
126
  signal?.removeEventListener("abort", abort);
102
127
  if (aborted)
103
128
  reject(signal.reason);
104
- else if (code === 0 && result)
105
- resolve(result);
129
+ else if (code === 0 && outcome) {
130
+ if (outcome.fingerprint)
131
+ fingerprints.set(path, outcome.fingerprint);
132
+ resolve(outcome.result);
133
+ }
106
134
  else
107
135
  reject(new Error(`Inside Out baseline worker exited without a result (code ${code})`));
108
136
  });
@@ -121,12 +149,15 @@ export function purgeInsideOutPerson(path, personId, options = {}) {
121
149
  // Never create Inside Out tables in a store that has none.
122
150
  const probe = openMemoryDatabase(path);
123
151
  try {
124
- if (!probe.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='inside_out'").get())
152
+ if (!tableExists(probe, "inside_out"))
125
153
  return { baselines: 0, assessments: 0, grades: 0 };
126
154
  }
127
155
  finally {
128
156
  probe.close();
129
157
  }
158
+ // Erasing grades must cover replies linked to this person since the last refresh.
159
+ if (options.grades)
160
+ linkInsideOutPeople(path);
130
161
  const db = openInsideOutStore(path);
131
162
  try {
132
163
  return purgeEmotionProfile(db, personId, options);
@@ -1,4 +1,3 @@
1
- import { createHash } from "node:crypto";
2
1
  import { existsSync } from "node:fs";
3
2
  import { DatabaseSync } from "node:sqlite";
4
3
  import { stripReasoningTagsFromText } from "openclaw/plugin-sdk/text-chunking";
@@ -8,6 +7,8 @@ import { estimateJevTokens, requestTypeSafe, resolveTypeSafeApiKey, TYPESAFE_MOD
8
7
  import { readInsideOutSources } from "./inside-out-sources.js";
9
8
  import { INSIDE_OUT_EMOTIONS, PURGED_GRADE, deviationReader, emotionBaselineHistory } from "./emotion-baselines.js";
10
9
  import { PERSON_MATCH, openInsideOutStore, refreshInsideOutBaselinesAsync } from "./inside-out-store.js";
10
+ import { jsonHash } from "./json-hash.js";
11
+ import { tableExists } from "./memory-database.js";
11
12
  export { linkInsideOutPeople, purgeInsideOutPerson, refreshInsideOutBaselines, refreshInsideOutBaselinesAsync } from "./inside-out-store.js";
12
13
  const RUBRIC = "emotion-presence-v2";
13
14
  const CONTEXT_ERROR = "Target reply and preceding assistant exceed context budget";
@@ -52,7 +53,6 @@ export function resolveInsideOut(value) {
52
53
  return { enabled, intervalMinutes: integer("intervalMinutes", 0, 10080), maxInteractions: integer("maxInteractions", 1, 10000),
53
54
  maxContextTokens: integer("maxContextTokens", 256, 30000), baselineMinInteractions: integer("baselineMinInteractions", 1, 10000) };
54
55
  }
55
- const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
56
56
  function humanIdentity(source, message) {
57
57
  const meta = message.__openclaw, identity = meta?.senderIdentity;
58
58
  const channel = meta?.transport?.channel ?? identity?.pluginId ?? message.sourceChannel ?? source.channel;
@@ -101,10 +101,10 @@ function* interactions(source, budget, cached, after) {
101
101
  if (!text)
102
102
  continue;
103
103
  const { channel, sender, human } = humanIdentity(source, m);
104
- const message = { id: event.id ?? hash(event), role: parsed.role, text,
104
+ const message = { id: event.id ?? jsonHash(event), role: parsed.role, text,
105
105
  ...(parsed.role === "user" ? { human } : {}) };
106
106
  const assistant = parsed.role === "user" && event.seq > after ? history.findLastIndex(item => item.role === "assistant") : -1;
107
- const id = assistant >= 0 ? hash([source.sessionId, message.id]) : "";
107
+ const id = assistant >= 0 ? jsonHash([source.sessionId, message.id]) : "";
108
108
  if (assistant >= 0 && !cached(id)) {
109
109
  const selected = [{ message: history[assistant], position: assistant }];
110
110
  let size = estimateJevTokens({ history: selected.map(s => s.message), target: message });
@@ -176,7 +176,7 @@ export async function runInsideOut(options) {
176
176
  const result = { reviewed: 0, cached: 0, failed: 0, sources: 0, skippedSources: 0, errors: [] };
177
177
  try {
178
178
  store = openInsideOutStore(storePath);
179
- const person = store.prepare("SELECT 1 FROM sqlite_schema WHERE name='person_identities'").get()
179
+ const person = tableExists(store, "person_identities")
180
180
  ? store.prepare(`SELECT (${PERSON_MATCH}) person_id FROM (SELECT ? channel,? human_key,? sender_id) e`)
181
181
  : undefined;
182
182
  const existing = store.prepare("SELECT 1 FROM inside_out WHERE interaction_id=? AND rubric=?");
@@ -315,7 +315,7 @@ export function reportInsideOut(path, options = {}) {
315
315
  return [];
316
316
  const db = new DatabaseSync(path, { readOnly: true });
317
317
  try {
318
- if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE name='inside_out'").get())
318
+ if (!tableExists(db, "inside_out"))
319
319
  return [];
320
320
  if (options.personId && !db.prepare("SELECT 1 FROM pragma_table_info('inside_out') WHERE name='person_id'").get())
321
321
  return [];
@@ -0,0 +1,2 @@
1
+ /** Hex SHA-256 of a value's JSON: the shared identity for cache, checkpoint and dedup keys. */
2
+ export declare function jsonHash(value: unknown): string;
@@ -0,0 +1,6 @@
1
+ import { createHash } from "node:crypto";
2
+ // Loaded by the Inside Out baseline worker (see inside-out-store.ts): keep this module free of `openclaw`.
3
+ /** Hex SHA-256 of a value's JSON: the shared identity for cache, checkpoint and dedup keys. */
4
+ export function jsonHash(value) {
5
+ return createHash("sha256").update(JSON.stringify(value)).digest("hex");
6
+ }