@unblocklabs/unblock-memory 0.12.3 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +19 -18
  2. package/dist/src/analysis.js +1 -1
  3. package/dist/src/cluster-review.d.ts +2 -0
  4. package/dist/src/cluster-review.js +3 -3
  5. package/dist/src/config.d.ts +9 -6
  6. package/dist/src/config.js +31 -20
  7. package/dist/src/curation.d.ts +1 -1
  8. package/dist/src/decision-client.d.ts +39 -0
  9. package/dist/src/decision-client.js +74 -0
  10. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  11. package/dist/src/decision-ranking.js +154 -0
  12. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  13. package/dist/src/decision-review.js +192 -0
  14. package/dist/src/diagnostics.d.ts +5 -5
  15. package/dist/src/emotion-baselines.d.ts +28 -3
  16. package/dist/src/emotion-baselines.js +309 -113
  17. package/dist/src/evidence-review.d.ts +22 -8
  18. package/dist/src/evidence-review.js +4 -4
  19. package/dist/src/extraction-chunk.d.ts +3 -0
  20. package/dist/src/extraction-chunk.js +23 -5
  21. package/dist/src/extraction-model.d.ts +2 -0
  22. package/dist/src/extraction-model.js +73 -48
  23. package/dist/src/extraction-runtime.d.ts +3 -1
  24. package/dist/src/extraction-runtime.js +43 -16
  25. package/dist/src/extraction-source.d.ts +1 -1
  26. package/dist/src/extraction-source.js +19 -11
  27. package/dist/src/extraction-store.d.ts +28 -3
  28. package/dist/src/extraction-store.js +145 -23
  29. package/dist/src/extraction-worker.d.ts +1 -0
  30. package/dist/src/extraction-worker.js +246 -93
  31. package/dist/src/inside-out-runtime.js +41 -29
  32. package/dist/src/inside-out-store.d.ts +2 -2
  33. package/dist/src/inside-out-store.js +110 -69
  34. package/dist/src/inside-out.d.ts +10 -9
  35. package/dist/src/inside-out.js +190 -105
  36. package/dist/src/manager.d.ts +22 -9
  37. package/dist/src/manager.js +275 -169
  38. package/dist/src/memory-search.d.ts +4 -2
  39. package/dist/src/memory-search.js +5 -5
  40. package/dist/src/memory-whisperer.d.ts +1 -1
  41. package/dist/src/memory-whisperer.js +183 -125
  42. package/dist/src/my-turn.d.ts +1 -1
  43. package/dist/src/my-turn.js +87 -68
  44. package/dist/src/people-background.d.ts +4 -0
  45. package/dist/src/people-background.js +29 -6
  46. package/dist/src/people-dossier-review.d.ts +20 -8
  47. package/dist/src/people-dossier-review.js +11 -8
  48. package/dist/src/people-hooks.js +127 -22
  49. package/dist/src/people-learning-cron.d.ts +1 -1
  50. package/dist/src/people-learning-cron.js +106 -57
  51. package/dist/src/people-learning-inventory.d.ts +1 -0
  52. package/dist/src/people-learning-inventory.js +281 -171
  53. package/dist/src/people-learning-prompt.js +1 -1
  54. package/dist/src/people-learning-runtime.d.ts +1 -1
  55. package/dist/src/people-learning-runtime.js +360 -203
  56. package/dist/src/people-learning-store.d.ts +27 -4
  57. package/dist/src/people-learning-store.js +312 -96
  58. package/dist/src/people-primer-tool.js +8 -6
  59. package/dist/src/people-primer.d.ts +3 -1
  60. package/dist/src/people-primer.js +61 -44
  61. package/dist/src/people-store.d.ts +18 -21
  62. package/dist/src/people-store.js +186 -63
  63. package/dist/src/people-tools.js +136 -92
  64. package/dist/src/plugin.js +16 -16
  65. package/dist/src/quality-audit.d.ts +2 -0
  66. package/dist/src/quality-audit.js +8 -7
  67. package/dist/src/response-audit.d.ts +1 -1
  68. package/dist/src/response-audit.js +76 -43
  69. package/dist/src/response-episodes.d.ts +1 -1
  70. package/dist/src/response-episodes.js +12 -17
  71. package/dist/src/response-judge.d.ts +151 -145
  72. package/dist/src/response-judge.js +535 -204
  73. package/dist/src/response-reviews.d.ts +29 -1
  74. package/dist/src/response-reviews.js +110 -13
  75. package/dist/src/response-runtime.js +8 -8
  76. package/dist/src/response-stages.d.ts +50 -53
  77. package/dist/src/response-stages.js +10 -4
  78. package/dist/src/response-store.d.ts +7 -6
  79. package/dist/src/response-store.js +332 -210
  80. package/dist/src/review-tools.d.ts +8 -2
  81. package/dist/src/review-tools.js +18 -18
  82. package/dist/src/runtime.d.ts +7 -4
  83. package/dist/src/runtime.js +624 -98
  84. package/dist/src/safety-whisperer.d.ts +2 -2
  85. package/dist/src/safety-whisperer.js +88 -71
  86. package/dist/src/session-sync.d.ts +3 -1
  87. package/dist/src/session-sync.js +200 -95
  88. package/dist/src/skill-whisperer.d.ts +1 -1
  89. package/dist/src/skill-whisperer.js +52 -30
  90. package/dist/src/training-gate.d.ts +8 -21
  91. package/dist/src/training-gate.js +32 -35
  92. package/dist/src/training-judge.d.ts +9 -16
  93. package/dist/src/training-judge.js +5 -5
  94. package/dist/src/training-queries.d.ts +13 -8
  95. package/dist/src/training-queries.js +370 -228
  96. package/dist/src/training-retrieval.d.ts +14 -24
  97. package/dist/src/training-retrieval.js +182 -136
  98. package/dist/src/training-runtime.d.ts +3 -0
  99. package/dist/src/training-runtime.js +76 -18
  100. package/dist/src/training-store.d.ts +18 -3
  101. package/dist/src/training-store.js +138 -50
  102. package/dist/src/training.js +8 -11
  103. package/dist/src/whisperer-context.d.ts +14 -0
  104. package/dist/src/whisperer-context.js +22 -1
  105. package/docs/configuration.md +76 -63
  106. package/docs/extraction.md +9 -7
  107. package/docs/memory-training.md +7 -6
  108. package/docs/people-learning.md +2 -2
  109. package/docs/peoplesql.md +6 -6
  110. package/docs/response-audit.md +10 -8
  111. package/docs/retrieval.md +40 -37
  112. package/openclaw.plugin.json +40 -26
  113. package/package.json +3 -2
  114. package/skills/memory-curator/SKILL.md +1 -1
  115. package/skills/people-whisperer/SKILL.md +1 -1
  116. package/dist/src/typesafe-client.d.ts +0 -30
  117. package/dist/src/typesafe-client.js +0 -92
  118. package/dist/src/typesafe-review.js +0 -154
  119. package/dist/src/typesafe.js +0 -147
@@ -15,7 +15,7 @@ export function registerInsideOut(api, config) {
15
15
  };
16
16
  api.registerCli(({ program, config: cfg }) => {
17
17
  const root = program.command("memory-emotions").description("Inside Out: review human replies and analyze emotion probabilities");
18
- root.command("link-people").description("Backfill or refresh People identity links without Jev")
18
+ root.command("link-people").description("Backfill or refresh People identity links without the decision model")
19
19
  .option("--agent <id>", "Agent id", "main")
20
20
  .option("--repair-identities", "Recover legacy sender/channel metadata for unlinked reviews")
21
21
  .action(async (opts) => {
@@ -34,7 +34,7 @@ export function registerInsideOut(api, config) {
34
34
  if ("failed" in result && (result.failed || result.errors.length || result.baselineError))
35
35
  process.exitCode = 1;
36
36
  });
37
- root.command("baseline-refresh").description("Update local weekly baselines and missing comparisons; no Jev calls")
37
+ root.command("baseline-refresh").description("Update local weekly baselines and missing comparisons; no inference")
38
38
  .option("--agent <id>", "Agent id", "main")
39
39
  .option("--recompare", "Append revised comparisons using newly available historical grades; preserve earlier results")
40
40
  .action(async (opts) => {
@@ -46,7 +46,7 @@ export function registerInsideOut(api, config) {
46
46
  .action((opts) => {
47
47
  console.log(JSON.stringify(reportInsideOutBaselines(paths(cfg, opts.agent).storePath, { personId: opts.person, since: opts.since ? dateOption(opts.since, 0) : undefined, limit: Number(opts.limit) }), null, 2));
48
48
  });
49
- root.command("purge").description("Delete one person's emotion baselines and assessment history; no Jev calls")
49
+ root.command("purge").description("Delete one person's emotion baselines and assessment history; no inference")
50
50
  .requiredOption("--person <id>", "Exact PeopleSQL person ID").option("--agent <id>", "Agent id", "main")
51
51
  .option("--grades", "Also erase this person's raw emotion grades; tombstones keep those replies from being regraded")
52
52
  .action((opts) => {
@@ -71,58 +71,70 @@ export function registerInsideOut(api, config) {
71
71
  let timer, baselineTimer, running;
72
72
  let refreshing;
73
73
  let lifetime = new AbortController();
74
+ const clearTimers = () => {
75
+ if (timer) {
76
+ clearInterval(timer);
77
+ timer = undefined;
78
+ }
79
+ if (baselineTimer) {
80
+ clearInterval(baselineTimer);
81
+ baselineTimer = undefined;
82
+ }
83
+ };
74
84
  const tick = () => {
75
- if (running)
85
+ if (running || lifetime.signal.aborted)
76
86
  return;
87
+ const { signal } = lifetime;
77
88
  running = (async () => {
78
89
  for (const agentId of listAgentIds(api.config)) {
79
- if (lifetime.signal.aborted)
90
+ if (signal.aborted)
80
91
  break;
81
92
  try {
82
- const result = await runInsideOut({ ...paths(api.config, agentId), config, signal: lifetime.signal });
93
+ const result = await runInsideOut({ ...paths(api.config, agentId), config, signal });
83
94
  if ("failed" in result && (result.failed || result.errors.length))
84
95
  api.logger.warn("Inside Out: some reviews or sources failed; inspect memory-emotions export");
85
96
  if ("baselineError" in result && result.baselineError)
86
97
  api.logger.warn(`Inside Out baselines: ${result.baselineError}`);
87
98
  }
88
99
  catch (error) {
89
- if (!lifetime.signal.aborted)
100
+ if (!signal.aborted)
90
101
  api.logger.warn(`Inside Out: ${String(error)}`);
91
102
  }
92
103
  }
93
104
  })().finally(() => { running = undefined; });
94
105
  };
95
- api.on("gateway_start", () => {
96
- lifetime = new AbortController();
97
- const refresh = () => {
98
- if (refreshing)
99
- return;
100
- refreshing = (async () => {
101
- for (const agentId of listAgentIds(api.config)) {
102
- if (lifetime.signal.aborted)
103
- break;
104
- try {
105
- await refreshInsideOutBaselinesAsync(paths(api.config, agentId).storePath, { minInteractions: config.insideOut.baselineMinInteractions }, lifetime.signal);
106
- }
107
- catch (error) {
108
- if (!lifetime.signal.aborted)
109
- api.logger.warn(`Inside Out baselines: ${String(error)}`);
110
- }
106
+ const refresh = () => {
107
+ if (refreshing || lifetime.signal.aborted)
108
+ return;
109
+ const { signal } = lifetime;
110
+ refreshing = (async () => {
111
+ for (const agentId of listAgentIds(api.config)) {
112
+ if (signal.aborted)
113
+ break;
114
+ try {
115
+ await refreshInsideOutBaselinesAsync(paths(api.config, agentId).storePath, { minInteractions: config.insideOut.baselineMinInteractions }, signal);
116
+ }
117
+ catch (error) {
118
+ if (!signal.aborted)
119
+ api.logger.warn(`Inside Out baselines: ${String(error)}`);
111
120
  }
112
- })().finally(() => { refreshing = undefined; });
113
- };
121
+ }
122
+ })().finally(() => { refreshing = undefined; });
123
+ };
124
+ api.on("gateway_start", () => {
125
+ clearTimers();
126
+ if (lifetime.signal.aborted)
127
+ lifetime = new AbortController();
114
128
  // Local statistics remain available when inference is manual-only or lacks a key.
115
129
  baselineTimer = setInterval(refresh, 86400_000);
116
130
  baselineTimer.unref();
117
131
  refresh();
118
- if (config.typesafe.enabled && config.insideOut.intervalMinutes) {
132
+ if (config.decisionModel.enabled && config.insideOut.intervalMinutes) {
119
133
  timer = setInterval(tick, config.insideOut.intervalMinutes * 60_000);
120
134
  timer.unref();
121
135
  tick();
122
136
  }
123
137
  });
124
138
  // Aborting cancels active baseline workers rather than waiting for a full historical pass.
125
- api.on("gateway_stop", async () => { if (timer)
126
- clearInterval(timer); if (baselineTimer)
127
- clearInterval(baselineTimer); lifetime.abort(); await Promise.all([running, refreshing]); });
139
+ api.on("gateway_stop", async () => { clearTimers(); lifetime.abort(); await Promise.all([running, refreshing]); });
128
140
  }
@@ -3,7 +3,7 @@ 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
5
  /**
6
- * Refresh People links without loading transcripts or calling Jev. Known accounts stay exact.
6
+ * Refresh People links without loading transcripts or calling the decision model. Known accounts stay exact.
7
7
  * Purged grades stay unlinked. Matching is a read; only changed links are written, in short batches.
8
8
  */
9
9
  export declare function linkInsideOutPeople(path: string): {
@@ -38,7 +38,7 @@ export declare function refreshWithFingerprint(path: string, options: BaselineOp
38
38
  snapshots: number;
39
39
  comparisons: number;
40
40
  };
41
- fingerprint: string;
41
+ fingerprint: string | undefined;
42
42
  };
43
43
  /**
44
44
  * Keep historical aggregation off the Gateway event loop; serialize refreshes per store, and skip
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { Worker } from "node:worker_threads";
3
3
  import { immediateTransaction, openMemoryDatabase, tableExists } from "./memory-database.js";
4
- import { PURGED_GRADE, baselineFingerprint, purgeEmotionProfile, refreshEmotionBaselines } from "./emotion-baselines.js";
4
+ import { PURGED_GRADE, baselineFingerprints, baselineInputSnapshot, 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 (
@@ -17,20 +17,26 @@ CREATE TABLE IF NOT EXISTS inside_out_checkpoints (
17
17
  source TEXT NOT NULL, rubric TEXT NOT NULL, session_id TEXT NOT NULL, signature TEXT NOT NULL,
18
18
  revision TEXT NOT NULL, last_seq INTEGER NOT NULL,
19
19
  PRIMARY KEY(source,rubric)
20
+ ) STRICT;
21
+ CREATE TABLE IF NOT EXISTS inside_out_person_generations (
22
+ person_id TEXT PRIMARY KEY, generation INTEGER NOT NULL
20
23
  ) STRICT;`;
21
24
  // A missing account may match across scopes only when every candidate names the same person.
22
25
  export const PERSON_MATCH = `SELECT min(i.person_id) person_id FROM person_identities i
23
26
  WHERE i.provider=e.channel AND i.external_id=e.sender_id
24
27
  AND (i.account_scope=json_extract(e.human_key,'$[1]') OR substr(json_extract(e.human_key,'$[1]'),1,8)='session:')
25
28
  HAVING count(DISTINCT i.person_id)=1`;
29
+ function ensureInsideOutSchema(db) {
30
+ db.exec(SCHEMA);
31
+ if (!db.prepare("SELECT 1 FROM pragma_table_info('inside_out') WHERE name='person_id'").get()) {
32
+ db.exec("ALTER TABLE inside_out ADD COLUMN person_id TEXT");
33
+ }
34
+ db.exec("CREATE INDEX IF NOT EXISTS inside_out_person_time ON inside_out(person_id,target_at)");
35
+ }
26
36
  export function openInsideOutStore(path) {
27
37
  const db = openMemoryDatabase(path);
28
38
  try {
29
- db.exec(SCHEMA);
30
- if (!db.prepare("SELECT 1 FROM pragma_table_info('inside_out') WHERE name='person_id'").get()) {
31
- db.exec("ALTER TABLE inside_out ADD COLUMN person_id TEXT");
32
- }
33
- db.exec("CREATE INDEX IF NOT EXISTS inside_out_person_time ON inside_out(person_id,target_at)");
39
+ ensureInsideOutSchema(db);
34
40
  return db;
35
41
  }
36
42
  catch (error) {
@@ -38,28 +44,31 @@ export function openInsideOutStore(path) {
38
44
  throw error;
39
45
  }
40
46
  }
47
+ function linkInsideOutPeopleInDb(db) {
48
+ let updated = 0;
49
+ if (tableExists(db, "person_identities")) {
50
+ const person = `(${PERSON_MATCH})`;
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
+ }
60
+ }
61
+ const counts = db.prepare(`SELECT count(person_id) linked,count(*)-count(person_id) unlinked FROM inside_out`).get();
62
+ return { updated, linked: Number(counts.linked), unlinked: Number(counts.unlinked) };
63
+ }
41
64
  /**
42
- * Refresh People links without loading transcripts or calling Jev. Known accounts stay exact.
65
+ * Refresh People links without loading transcripts or calling the decision model. Known accounts stay exact.
43
66
  * Purged grades stay unlinked. Matching is a read; only changed links are written, in short batches.
44
67
  */
45
68
  export function linkInsideOutPeople(path) {
46
69
  const db = openInsideOutStore(path);
47
70
  try {
48
- let updated = 0;
49
- if (tableExists(db, "person_identities")) {
50
- const person = `(${PERSON_MATCH})`;
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
- }
60
- }
61
- const counts = db.prepare(`SELECT count(person_id) linked,count(*)-count(person_id) unlinked FROM inside_out`).get();
62
- return { updated, linked: Number(counts.linked), unlinked: Number(counts.unlinked) };
71
+ return linkInsideOutPeopleInDb(db);
63
72
  }
64
73
  finally {
65
74
  db.close();
@@ -77,21 +86,75 @@ export function refreshInsideOutBaselines(path, options = {}) {
77
86
  export function refreshWithFingerprint(path, options) {
78
87
  if (!existsSync(path))
79
88
  return { result: { snapshots: 0, comparisons: 0 } };
80
- if (options.link !== false)
81
- linkInsideOutPeople(path);
82
89
  const db = openInsideOutStore(path);
83
90
  try {
91
+ if (options.link !== false)
92
+ linkInsideOutPeopleInDb(db);
84
93
  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 };
94
+ let beforeInputs;
95
+ let expectedGenerations;
96
+ if (!options.recompare && options.unless) {
97
+ const before = baselineFingerprints(db, settings);
98
+ if (before.fullFingerprint === options.unless) {
99
+ return { result: { snapshots: 0, comparisons: 0 }, fingerprint: options.unless };
100
+ }
101
+ beforeInputs = before.inputFingerprint;
102
+ expectedGenerations = before.personGenerations;
103
+ }
104
+ else {
105
+ const before = baselineInputSnapshot(db, settings);
106
+ beforeInputs = before.inputFingerprint;
107
+ expectedGenerations = before.personGenerations;
87
108
  }
88
- const result = refreshEmotionBaselines(db, settings);
89
- return { result, fingerprint: baselineFingerprint(db, settings) };
109
+ const result = refreshEmotionBaselines(db, { ...settings, expectedGenerations });
110
+ const after = baselineFingerprints(db, settings);
111
+ // Only certify the post-pass fingerprint if grades, People inputs, and purge generations stayed unchanged mid-pass.
112
+ const fingerprint = after.inputFingerprint === beforeInputs ? after.fullFingerprint : undefined;
113
+ return { result, fingerprint };
90
114
  }
91
115
  finally {
92
116
  db.close();
93
117
  }
94
118
  }
119
+ function runBaselineWorker(path, options, signal) {
120
+ return new Promise((resolve, reject) => {
121
+ const worker = new Worker(`
122
+ const { parentPort, workerData } = require("node:worker_threads");
123
+ // tsx's CLI preload only registers on the main thread. Source-mode
124
+ // development needs explicit registration; compiled installs do not.
125
+ if (workerData.module.endsWith(".ts")) require("node:module").createRequire(workerData.module)("tsx/esm/api").register();
126
+ import(workerData.module).then(({ refreshWithFingerprint }) => {
127
+ parentPort.postMessage(refreshWithFingerprint(workerData.path, workerData.options));
128
+ }).catch(error => { throw error; });
129
+ `, { eval: true, workerData: { module: import.meta.url, path, options } });
130
+ let outcome;
131
+ let workerError;
132
+ let hasError = false;
133
+ let aborted = false;
134
+ const abort = () => { aborted = true; void worker.terminate(); };
135
+ signal?.addEventListener("abort", abort, { once: true });
136
+ worker.once("message", (value) => { outcome = value; });
137
+ // Record worker errors and settle only on "exit" so the next queued job cannot open SQLite early.
138
+ worker.on("error", error => {
139
+ if (!hasError) {
140
+ hasError = true;
141
+ workerError = error;
142
+ }
143
+ });
144
+ // Settle only after the worker closes its database and exits.
145
+ worker.once("exit", code => {
146
+ signal?.removeEventListener("abort", abort);
147
+ if (aborted)
148
+ reject(signal.reason);
149
+ else if (hasError)
150
+ reject(workerError);
151
+ else if (code === 0 && outcome)
152
+ resolve(outcome);
153
+ else
154
+ reject(new Error(`Inside Out baseline worker exited without a result (code ${code})`));
155
+ });
156
+ });
157
+ }
95
158
  const baselineJobs = new Map();
96
159
  const fingerprints = new Map();
97
160
  /**
@@ -101,40 +164,23 @@ const fingerprints = new Map();
101
164
  * worker, so SQLite rolls back the open batch; committed batches are idempotent and the next refresh resumes.
102
165
  */
103
166
  export function refreshInsideOutBaselinesAsync(path, options = {}, signal) {
104
- const job = (baselineJobs.get(path) ?? Promise.resolve()).catch(() => { }).then(() => {
167
+ const job = (baselineJobs.get(path) ?? Promise.resolve()).catch(() => { }).then(async () => {
105
168
  signal?.throwIfAborted();
106
169
  if (!existsSync(path))
107
170
  return { snapshots: 0, comparisons: 0 };
108
171
  const settings = { ...options, now: options.now ?? Date.now(), unless: fingerprints.get(path) };
109
- return new Promise((resolve, reject) => {
110
- const worker = new Worker(`
111
- const { parentPort, workerData } = require("node:worker_threads");
112
- // tsx's CLI preload only registers on the main thread. Source-mode
113
- // development needs explicit registration; compiled installs do not.
114
- if (workerData.module.endsWith(".ts")) require("node:module").createRequire(workerData.module)("tsx/esm/api").register();
115
- import(workerData.module).then(({ refreshWithFingerprint }) => {
116
- parentPort.postMessage(refreshWithFingerprint(workerData.path, workerData.options));
117
- }).catch(error => { throw error; });
118
- `, { eval: true, workerData: { module: import.meta.url, path, options: settings } });
119
- let outcome, aborted = false;
120
- const abort = () => { aborted = true; void worker.terminate(); };
121
- signal?.addEventListener("abort", abort, { once: true });
122
- worker.once("message", (value) => { outcome = value; });
123
- worker.once("error", reject);
124
- // Settle only after the worker closes its database and exits.
125
- worker.once("exit", code => {
126
- signal?.removeEventListener("abort", abort);
127
- if (aborted)
128
- reject(signal.reason);
129
- else if (code === 0 && outcome) {
130
- if (outcome.fingerprint)
131
- fingerprints.set(path, outcome.fingerprint);
132
- resolve(outcome.result);
133
- }
134
- else
135
- reject(new Error(`Inside Out baseline worker exited without a result (code ${code})`));
136
- });
137
- });
172
+ try {
173
+ const outcome = await runBaselineWorker(path, settings, signal);
174
+ if (outcome.fingerprint)
175
+ fingerprints.set(path, outcome.fingerprint);
176
+ else
177
+ fingerprints.delete(path);
178
+ return outcome.result;
179
+ }
180
+ catch (error) {
181
+ fingerprints.delete(path);
182
+ throw error;
183
+ }
138
184
  }).finally(() => { if (baselineJobs.get(path) === job)
139
185
  baselineJobs.delete(path); });
140
186
  baselineJobs.set(path, job);
@@ -147,19 +193,14 @@ export function purgeInsideOutPerson(path, personId, options = {}) {
147
193
  if (!existsSync(path))
148
194
  return { baselines: 0, assessments: 0, grades: 0 };
149
195
  // Never create Inside Out tables in a store that has none.
150
- const probe = openMemoryDatabase(path);
196
+ const db = openMemoryDatabase(path);
151
197
  try {
152
- if (!tableExists(probe, "inside_out"))
198
+ if (!tableExists(db, "inside_out"))
153
199
  return { baselines: 0, assessments: 0, grades: 0 };
154
- }
155
- finally {
156
- probe.close();
157
- }
158
- // Erasing grades must cover replies linked to this person since the last refresh.
159
- if (options.grades)
160
- linkInsideOutPeople(path);
161
- const db = openInsideOutStore(path);
162
- try {
200
+ ensureInsideOutSchema(db);
201
+ // Erasing grades must cover replies linked to this person since the last refresh.
202
+ if (options.grades)
203
+ linkInsideOutPeopleInDb(db);
163
204
  return purgeEmotionProfile(db, personId, options);
164
205
  }
165
206
  finally {
@@ -17,6 +17,15 @@ export declare function repairInsideOutIdentities(options: Parameters<typeof rea
17
17
  repaired: number;
18
18
  errors: string[];
19
19
  }>;
20
+ type InsideOutRunResult = {
21
+ reviewed: number;
22
+ cached: number;
23
+ failed: number;
24
+ sources: number;
25
+ skippedSources: number;
26
+ errors: string[];
27
+ baselineError?: string;
28
+ };
20
29
  export declare function runInsideOut(options: {
21
30
  agentId: string;
22
31
  databasePath: string;
@@ -26,15 +35,7 @@ export declare function runInsideOut(options: {
26
35
  signal?: AbortSignal;
27
36
  retry?: boolean;
28
37
  sessionId?: string;
29
- }): Promise<{
30
- reviewed: number;
31
- cached: number;
32
- failed: number;
33
- sources: number;
34
- skippedSources: number;
35
- errors: string[];
36
- baselineError?: string;
37
- } | {
38
+ }): Promise<InsideOutRunResult | {
38
39
  status: string;
39
40
  }>;
40
41
  export declare function reportInsideOutBaselines(path: string, options?: Parameters<typeof emotionBaselineHistory>[1]): {