@unblocklabs/unblock-memory 0.12.3 → 0.14.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 (138) hide show
  1. package/README.md +19 -18
  2. package/defaults.json +162 -0
  3. package/dist/src/analysis.js +1 -1
  4. package/dist/src/cluster-review.d.ts +2 -0
  5. package/dist/src/cluster-review.js +9 -8
  6. package/dist/src/config.d.ts +9 -6
  7. package/dist/src/config.js +59 -45
  8. package/dist/src/curation.d.ts +1 -1
  9. package/dist/src/decision-client.d.ts +45 -0
  10. package/dist/src/decision-client.js +87 -0
  11. package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
  12. package/dist/src/decision-ranking.js +155 -0
  13. package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
  14. package/dist/src/decision-review.js +193 -0
  15. package/dist/src/defaults.d.ts +8 -0
  16. package/dist/src/defaults.js +128 -0
  17. package/dist/src/diagnostics.d.ts +5 -5
  18. package/dist/src/emotion-baselines.d.ts +28 -3
  19. package/dist/src/emotion-baselines.js +312 -115
  20. package/dist/src/evidence-review.d.ts +22 -8
  21. package/dist/src/evidence-review.js +11 -8
  22. package/dist/src/extraction-chunk.d.ts +3 -0
  23. package/dist/src/extraction-chunk.js +25 -6
  24. package/dist/src/extraction-config.js +4 -2
  25. package/dist/src/extraction-model.d.ts +25 -17
  26. package/dist/src/extraction-model.js +232 -104
  27. package/dist/src/extraction-runtime.d.ts +3 -1
  28. package/dist/src/extraction-runtime.js +48 -20
  29. package/dist/src/extraction-source.d.ts +1 -1
  30. package/dist/src/extraction-source.js +21 -12
  31. package/dist/src/extraction-store.d.ts +29 -3
  32. package/dist/src/extraction-store.js +149 -25
  33. package/dist/src/extraction-worker.d.ts +3 -3
  34. package/dist/src/extraction-worker.js +250 -95
  35. package/dist/src/inside-out-runtime.js +43 -30
  36. package/dist/src/inside-out-sources.js +2 -1
  37. package/dist/src/inside-out-store.d.ts +2 -2
  38. package/dist/src/inside-out-store.js +111 -69
  39. package/dist/src/inside-out.d.ts +10 -9
  40. package/dist/src/inside-out.js +194 -106
  41. package/dist/src/manager.d.ts +22 -9
  42. package/dist/src/manager.js +279 -172
  43. package/dist/src/memory-database.js +3 -2
  44. package/dist/src/memory-passage.d.ts +2 -2
  45. package/dist/src/memory-passage.js +3 -2
  46. package/dist/src/memory-search.d.ts +4 -2
  47. package/dist/src/memory-search.js +5 -5
  48. package/dist/src/memory-whisperer.d.ts +1 -1
  49. package/dist/src/memory-whisperer.js +195 -129
  50. package/dist/src/my-turn.d.ts +1 -1
  51. package/dist/src/my-turn.js +90 -70
  52. package/dist/src/people-background.d.ts +5 -1
  53. package/dist/src/people-background.js +31 -7
  54. package/dist/src/people-dossier-review.d.ts +20 -8
  55. package/dist/src/people-dossier-review.js +15 -11
  56. package/dist/src/people-hooks.js +127 -22
  57. package/dist/src/people-learning-cron.d.ts +1 -1
  58. package/dist/src/people-learning-cron.js +107 -57
  59. package/dist/src/people-learning-inventory.d.ts +1 -0
  60. package/dist/src/people-learning-inventory.js +283 -172
  61. package/dist/src/people-learning-prompt.js +1 -1
  62. package/dist/src/people-learning-runtime.d.ts +1 -1
  63. package/dist/src/people-learning-runtime.js +360 -203
  64. package/dist/src/people-learning-store.d.ts +27 -4
  65. package/dist/src/people-learning-store.js +312 -96
  66. package/dist/src/people-primer-tool.js +13 -10
  67. package/dist/src/people-primer.d.ts +3 -1
  68. package/dist/src/people-primer.js +66 -48
  69. package/dist/src/people-store.d.ts +18 -21
  70. package/dist/src/people-store.js +188 -64
  71. package/dist/src/people-tools.js +138 -93
  72. package/dist/src/plugin.js +19 -18
  73. package/dist/src/quality-audit.d.ts +2 -0
  74. package/dist/src/quality-audit.js +11 -9
  75. package/dist/src/quality-triage.js +4 -3
  76. package/dist/src/query-generator.js +5 -2
  77. package/dist/src/response-audit.d.ts +1 -1
  78. package/dist/src/response-audit.js +78 -44
  79. package/dist/src/response-config.js +3 -1
  80. package/dist/src/response-episodes.d.ts +1 -1
  81. package/dist/src/response-episodes.js +15 -19
  82. package/dist/src/response-identity.js +2 -1
  83. package/dist/src/response-judge.d.ts +151 -145
  84. package/dist/src/response-judge.js +535 -204
  85. package/dist/src/response-memory.js +2 -1
  86. package/dist/src/response-outcome.js +9 -8
  87. package/dist/src/response-reviews.d.ts +29 -1
  88. package/dist/src/response-reviews.js +113 -15
  89. package/dist/src/response-runtime.js +10 -9
  90. package/dist/src/response-stages.d.ts +50 -53
  91. package/dist/src/response-stages.js +10 -4
  92. package/dist/src/response-store.d.ts +7 -6
  93. package/dist/src/response-store.js +335 -212
  94. package/dist/src/review-tools.d.ts +8 -2
  95. package/dist/src/review-tools.js +22 -21
  96. package/dist/src/runtime.d.ts +7 -4
  97. package/dist/src/runtime.js +625 -98
  98. package/dist/src/safety-config.js +3 -2
  99. package/dist/src/safety-whisperer.d.ts +2 -2
  100. package/dist/src/safety-whisperer.js +90 -73
  101. package/dist/src/session-sync.d.ts +3 -1
  102. package/dist/src/session-sync.js +202 -96
  103. package/dist/src/skill-whisperer.d.ts +2 -2
  104. package/dist/src/skill-whisperer.js +55 -32
  105. package/dist/src/slack-directory.js +3 -2
  106. package/dist/src/training-gate.d.ts +9 -22
  107. package/dist/src/training-gate.js +34 -36
  108. package/dist/src/training-input.js +4 -3
  109. package/dist/src/training-judge.d.ts +9 -16
  110. package/dist/src/training-judge.js +6 -5
  111. package/dist/src/training-models.d.ts +1 -1
  112. package/dist/src/training-models.js +9 -7
  113. package/dist/src/training-queries.d.ts +14 -9
  114. package/dist/src/training-queries.js +374 -231
  115. package/dist/src/training-retrieval.d.ts +17 -27
  116. package/dist/src/training-retrieval.js +186 -139
  117. package/dist/src/training-runtime.d.ts +3 -0
  118. package/dist/src/training-runtime.js +76 -18
  119. package/dist/src/training-store.d.ts +18 -3
  120. package/dist/src/training-store.js +141 -52
  121. package/dist/src/training.js +9 -11
  122. package/dist/src/whisperer-context.d.ts +13 -0
  123. package/dist/src/whisperer-context.js +22 -1
  124. package/docs/configuration.md +83 -64
  125. package/docs/extraction.md +26 -35
  126. package/docs/memory-training.md +7 -6
  127. package/docs/people-learning.md +2 -2
  128. package/docs/peoplesql.md +6 -6
  129. package/docs/response-audit.md +10 -8
  130. package/docs/retrieval.md +43 -47
  131. package/openclaw.plugin.json +76 -75
  132. package/package.json +5 -2
  133. package/skills/memory-curator/SKILL.md +1 -1
  134. package/skills/people-whisperer/SKILL.md +1 -1
  135. package/dist/src/typesafe-client.d.ts +0 -30
  136. package/dist/src/typesafe-client.js +0 -92
  137. package/dist/src/typesafe-review.js +0 -154
  138. package/dist/src/typesafe.js +0 -147
@@ -1,15 +1,222 @@
1
- import { resolveTypeSafeApiKey } from "./typesafe-client.js";
2
- import { extractWithLuna, validateExtractedMemory, EXTRACTION_VERSION } from "./extraction-model.js";
3
- import { ExtractionStore } from "./extraction-store.js";
1
+ import { DEFAULTS } from "./defaults.js";
2
+ import { abortable } from "./abortable.js";
3
+ import { extractWithDecisionModel, validateExtractedMemory, EXTRACTION_VERSION, } from "./extraction-model.js";
4
+ import { buildCompleteRevision, ExtractionLeaseLostError, extractionPolicyFingerprint, ExtractionStore, } from "./extraction-store.js";
4
5
  import { readExtractionPage } from "./extraction-source.js";
5
6
  import { extractionHistory, readExtractionChunk } from "./extraction-chunk.js";
7
+ import { resolveDecisionCredential } from "./decision-client.js";
8
+ function handleResetOrMissing(store, sessionId, page, owner, policyFingerprint) {
9
+ if (page.kind !== "reset" && page.kind !== "missing")
10
+ return false;
11
+ store.reset(sessionId, page.kind === "reset" ? (page.cursor ?? null) : null, owner, policyFingerprint);
12
+ return true;
13
+ }
14
+ function scoreField(judgment, key) {
15
+ return "scores" in judgment && judgment.scores ? judgment.scores[key] : 0;
16
+ }
17
+ function isBetterReplacement(candidate, incumbent) {
18
+ if (candidate.observedAt !== incumbent.observedAt)
19
+ return candidate.observedAt > incumbent.observedAt;
20
+ for (const key of ["replacement", "supported", "useful"]) {
21
+ const diff = scoreField(candidate.judgment, key) - scoreField(incumbent.judgment, key);
22
+ if (diff !== 0)
23
+ return diff > 0;
24
+ }
25
+ return candidate.order < incumbent.order;
26
+ }
27
+ async function validateProposals(params) {
28
+ const { proposals, messages, newIds, existing, apiKey, config, signal, validate } = params;
29
+ const messageById = new Map(messages.map(m => [m.id, m]));
30
+ const existingById = new Map(existing.map(m => [m.id, m]));
31
+ const standalone = [];
32
+ const winnerByPredecessor = new Map();
33
+ let rejected = 0;
34
+ for (let start = 0; start < proposals.length; start += DEFAULTS.extraction.validatorBatchSize) {
35
+ signal.throwIfAborted();
36
+ // Isolated judgments overlap, but failed chunks drain before their lease is released.
37
+ const judgments = await Promise.allSettled(proposals.slice(start, start + DEFAULTS.extraction.validatorBatchSize).map(async (proposal, offset) => ({
38
+ proposal,
39
+ order: start + offset,
40
+ judgment: await validate({
41
+ proposal,
42
+ messages,
43
+ newIds,
44
+ existing,
45
+ apiKey,
46
+ endpoint: config.decisionModel.endpoint,
47
+ model: config.decisionModel.model,
48
+ signal,
49
+ thresholds: config.extraction,
50
+ }),
51
+ })));
52
+ const failure = judgments.find(result => result.status === "rejected");
53
+ if (failure)
54
+ throw failure.reason;
55
+ for (const result of judgments) {
56
+ if (result.status !== "fulfilled")
57
+ continue;
58
+ const { proposal, judgment, order } = result.value;
59
+ if (!judgment.accepted) {
60
+ rejected++;
61
+ continue;
62
+ }
63
+ let observedAt = -Infinity;
64
+ let missingEvidence = false;
65
+ const mappedEvidence = [];
66
+ for (const item of proposal.evidence) {
67
+ const message = messageById.get(item.messageId);
68
+ if (!message) {
69
+ missingEvidence = true;
70
+ break;
71
+ }
72
+ if (message.timestamp > observedAt)
73
+ observedAt = message.timestamp;
74
+ mappedEvidence.push({ ...item, messageId: message.sourceMessageId ?? item.messageId });
75
+ }
76
+ if (missingEvidence || !Number.isFinite(observedAt)) {
77
+ rejected++;
78
+ continue;
79
+ }
80
+ const prior = proposal.replaces ? existingById.get(proposal.replaces) : undefined;
81
+ if (proposal.replaces && (!prior || prior.observedAt > observedAt)) {
82
+ rejected++;
83
+ continue;
84
+ }
85
+ const candidate = {
86
+ proposal: { ...proposal, evidence: mappedEvidence },
87
+ judgment,
88
+ observedAt,
89
+ order,
90
+ };
91
+ if (proposal.replaces) {
92
+ const incumbent = winnerByPredecessor.get(proposal.replaces);
93
+ if (!incumbent) {
94
+ winnerByPredecessor.set(proposal.replaces, candidate);
95
+ }
96
+ else {
97
+ if (isBetterReplacement(candidate, incumbent)) {
98
+ winnerByPredecessor.set(proposal.replaces, candidate);
99
+ }
100
+ rejected++;
101
+ }
102
+ }
103
+ else {
104
+ standalone.push(candidate);
105
+ }
106
+ }
107
+ }
108
+ const accepted = [...standalone, ...winnerByPredecessor.values()]
109
+ .sort((a, b) => a.order - b.order)
110
+ .map(({ proposal, observedAt, judgment }) => ({ proposal, observedAt, judgment }));
111
+ return { accepted, rejected };
112
+ }
113
+ async function processSession(params) {
114
+ const { session, store, owner, config, agentId, agentName, since, version, policyFingerprint, apiKey, signal, leaseAbort, readPage, extract, validate, } = params;
115
+ const extractionConfig = config.extraction;
116
+ const checkpoint = store.checkpoint(session, owner, since, policyFingerprint);
117
+ const expectedCompleteRevision = session.sourceRevision === undefined
118
+ ? undefined
119
+ : buildCompleteRevision(session.sourceRevision, policyFingerprint);
120
+ if (expectedCompleteRevision !== undefined && checkpoint.completeRevision === expectedCompleteRevision) {
121
+ return { processed: 0, accepted: 0, rejected: 0, unchanged: 1, failed: 0 };
122
+ }
123
+ let stage = "read";
124
+ try {
125
+ const existing = store.records(session.sessionId);
126
+ if (existing.length > DEFAULTS.extraction.maxExistingFacts || JSON.stringify(existing.map(m => ({ id: m.id, text: m.text }))).length > DEFAULTS.extraction.maxExistingChars) {
127
+ throw new Error("Existing memories exceed review budget");
128
+ }
129
+ const existingFacts = existing.map(m => ({ id: m.id, text: m.text, observedAt: m.observedAt }));
130
+ const page = await readExtractionChunk({
131
+ agentId,
132
+ agentName,
133
+ session,
134
+ cursor: checkpoint.cursor,
135
+ context: extractionHistory(checkpoint.context, extractionConfig.historyMessages),
136
+ existing: existingFacts,
137
+ signal,
138
+ readPage,
139
+ });
140
+ signal.throwIfAborted();
141
+ if (page.kind === "unavailable") {
142
+ store.error(session.sessionId, "source_unavailable", owner);
143
+ return { processed: 1, accepted: 0, rejected: 0, unchanged: 0, failed: 1 };
144
+ }
145
+ if (handleResetOrMissing(store, session.sessionId, page, owner, policyFingerprint)) {
146
+ return { processed: 1, accepted: 0, rejected: 0, unchanged: 0, failed: 0 };
147
+ }
148
+ if (!page.entryCount) {
149
+ store.completeEmpty({
150
+ sessionId: session.sessionId,
151
+ expected: checkpoint.cursor,
152
+ owner,
153
+ completeRevision: page.exhausted ? expectedCompleteRevision : undefined,
154
+ policyFingerprint,
155
+ });
156
+ return { processed: 0, accepted: 0, rejected: 0, unchanged: 1, failed: 0 };
157
+ }
158
+ const freshIds = new Set(page.newIds);
159
+ const messages = page.messages;
160
+ const newIds = messages.filter(m => freshIds.has(m.id) && m.timestamp >= checkpoint.since).map(m => m.id);
161
+ stage = "propose";
162
+ const proposals = newIds.length ? await extract({ messages, newIds, existing: existingFacts, apiKey, signal,
163
+ endpoint: config.decisionModel.endpoint, model: config.decisionModel.model, minReplacement: extractionConfig.minReplacement }) : [];
164
+ stage = "validate";
165
+ const { accepted, rejected } = await validateProposals({
166
+ proposals,
167
+ messages,
168
+ newIds,
169
+ existing,
170
+ apiKey,
171
+ config,
172
+ signal,
173
+ validate,
174
+ });
175
+ // A branch rewrite during inference invalidates its proposals. Appends are safe and processed next time.
176
+ signal.throwIfAborted();
177
+ const checkPending = readPage(agentId, agentName, session, page.fence, undefined, signal);
178
+ void checkPending.catch(() => { });
179
+ const check = await abortable(checkPending, signal);
180
+ signal.throwIfAborted();
181
+ if (handleResetOrMissing(store, session.sessionId, check, owner, policyFingerprint)) {
182
+ return { processed: 1, accepted: 0, rejected, unchanged: 0, failed: 0 };
183
+ }
184
+ if (check.kind === "unavailable")
185
+ throw new Error("Source changed during extraction");
186
+ const context = extractionHistory(messages, extractionConfig.historyMessages);
187
+ stage = "commit";
188
+ const written = store.commit({
189
+ session,
190
+ expected: checkpoint.cursor,
191
+ cursor: page.cursor,
192
+ context,
193
+ accepted,
194
+ owner,
195
+ version,
196
+ completeRevision: page.exhausted ? expectedCompleteRevision : undefined,
197
+ policyFingerprint,
198
+ });
199
+ return { processed: 1, accepted: written, rejected, unchanged: 0, failed: 0 };
200
+ }
201
+ catch (error) {
202
+ if (error instanceof ExtractionLeaseLostError) {
203
+ leaseAbort.abort(error);
204
+ throw error;
205
+ }
206
+ signal.throwIfAborted();
207
+ store.error(session.sessionId, `${stage}_failed`, owner);
208
+ return { processed: 1, accepted: 0, rejected: 0, unchanged: 0, failed: 1 };
209
+ }
210
+ }
6
211
  export async function runExtraction(params) {
7
212
  const config = params.config.extraction;
8
213
  if (!config.enabled)
9
214
  return { status: "disabled" };
10
- const apiKey = await resolveTypeSafeApiKey(params.config.typesafe);
215
+ params.signal.throwIfAborted();
216
+ const apiKey = await abortable(resolveDecisionCredential(params.config.decisionModel), params.signal);
217
+ params.signal.throwIfAborted();
11
218
  if (!apiKey)
12
- return { status: "unavailable", reason: "TypeSafe API key not configured" };
219
+ return { status: "unavailable", reason: "Decision model API key not configured" };
13
220
  const store = new ExtractionStore(params.storePath);
14
221
  const owner = store.claim(params.scheduled ?? false, config.intervalMinutes * 60_000);
15
222
  if (!owner) {
@@ -17,16 +224,28 @@ export async function runExtraction(params) {
17
224
  return { status: "not_due_or_busy" };
18
225
  }
19
226
  const leaseAbort = new AbortController();
20
- const signal = AbortSignal.any([params.signal, leaseAbort.signal, AbortSignal.timeout(600_000)]);
227
+ const signal = AbortSignal.any([params.signal, leaseAbort.signal, AbortSignal.timeout(DEFAULTS.extraction.runTimeoutMs)]);
21
228
  const heartbeat = setInterval(() => { try {
22
229
  store.renew(owner);
23
230
  }
24
- catch {
25
- leaseAbort.abort();
26
- } }, 30_000);
231
+ catch (error) {
232
+ leaseAbort.abort(error);
233
+ } }, DEFAULTS.extraction.heartbeatMs);
27
234
  heartbeat.unref();
28
235
  let processed = 0, acceptedCount = 0, rejectedCount = 0, unchanged = 0, failed = 0;
29
236
  const readPage = params.readPage ?? readExtractionPage;
237
+ const extract = params.extract ?? extractWithDecisionModel;
238
+ const validate = params.validate ?? validateExtractedMemory;
239
+ const version = params.version ?? EXTRACTION_VERSION;
240
+ const policyFingerprint = extractionPolicyFingerprint({
241
+ version,
242
+ historyMessages: config.historyMessages,
243
+ minSupport: config.minSupport,
244
+ minRetention: config.minRetention,
245
+ minReplacement: config.minReplacement,
246
+ extractorModel: params.config.decisionModel.model,
247
+ validatorModel: params.config.decisionModel.model,
248
+ });
30
249
  try {
31
250
  const sessions = params.sessions();
32
251
  const visible = new Set(sessions.map(s => s.sessionId));
@@ -48,92 +267,28 @@ export async function runExtraction(params) {
48
267
  continue;
49
268
  if (processed >= config.maxBatches)
50
269
  break;
51
- const checkpoint = store.checkpoint(session, params.since);
52
- if (session.sourceRevision !== undefined && checkpoint.completeRevision === session.sourceRevision) {
53
- unchanged++;
54
- continue;
55
- }
56
- let stage = "read";
57
- try {
58
- const existing = store.records(session.sessionId);
59
- if (existing.length > 100 || JSON.stringify(existing.map(m => ({ id: m.id, text: m.text }))).length > 40_000) {
60
- throw new Error("Existing memories exceed review budget");
61
- }
62
- const existingFacts = existing.map(m => ({ id: m.id, text: m.text, observedAt: m.observedAt }));
63
- const page = await readExtractionChunk({ agentId: params.agentId, agentName: params.agentName, session,
64
- cursor: checkpoint.cursor, context: extractionHistory(checkpoint.context, config.historyMessages),
65
- existing: existingFacts, signal, readPage });
66
- if (page.kind === "unavailable") {
67
- store.error(session.sessionId, "source_unavailable");
68
- failed++;
69
- processed++;
70
- continue;
71
- }
72
- if (page.kind === "reset" || page.kind === "missing") {
73
- store.reset(session.sessionId, page.kind === "reset" ? page.cursor : null, owner);
74
- processed++;
75
- continue;
76
- }
77
- if (!page.entryCount) {
78
- store.db.prepare("UPDATE extraction_sessions SET updated_at=?,complete_revision=? WHERE session_id=?")
79
- .run(Date.now(), page.exhausted ? session.sourceRevision ?? null : null, session.sessionId);
80
- unchanged++;
81
- continue;
82
- }
83
- const since = checkpoint.since;
84
- const freshIds = new Set(page.newIds);
85
- const fresh = page.messages.filter(m => freshIds.has(m.id) && m.timestamp >= since);
86
- const messages = page.messages;
87
- const newIds = fresh.map(m => m.id);
88
- stage = "propose";
89
- const proposals = newIds.length ? await (params.extract ?? extractWithLuna)(params.runtime, params.agentId, messages, newIds, existingFacts, signal) : [];
90
- const accepted = [];
91
- stage = "validate";
92
- for (let start = 0; start < proposals.length; start += 4) {
93
- signal.throwIfAborted();
94
- // Isolated judgments overlap, but failed chunks drain before their lease is released.
95
- const judgments = await Promise.allSettled(proposals.slice(start, start + 4).map(async (proposal) => ({ proposal,
96
- judgment: await (params.validate ?? validateExtractedMemory)({ proposal, messages, newIds, existing, apiKey, signal, thresholds: config }) })));
97
- const failure = judgments.find(result => result.status === "rejected");
98
- if (failure)
99
- throw failure.reason;
100
- for (const result of judgments) {
101
- if (result.status !== "fulfilled")
102
- continue;
103
- const { proposal, judgment } = result.value;
104
- const observedAt = judgment.accepted ? Math.max(...proposal.evidence.map(e => messages.find(m => m.id === e.messageId).timestamp)) : 0;
105
- const prior = existing.find(m => m.id === proposal.replaces);
106
- if (judgment.accepted && (!prior || prior.observedAt <= observedAt))
107
- accepted.push({ proposal: { ...proposal,
108
- evidence: proposal.evidence.map(e => ({ ...e, messageId: messages.find(m => m.id === e.messageId).sourceMessageId ?? e.messageId })) }, judgment, observedAt });
109
- else
110
- rejectedCount++;
111
- }
112
- }
113
- // A branch rewrite during inference invalidates its proposals. Appends are safe and processed next time.
114
- const check = await readPage(params.agentId, params.agentName, session, page.fence);
115
- if (check.kind === "reset" || check.kind === "missing") {
116
- store.reset(session.sessionId, check.kind === "reset" ? check.cursor : null, owner);
117
- processed++;
118
- continue;
119
- }
120
- if (check.kind === "unavailable")
121
- throw new Error("Source changed during extraction");
122
- signal.throwIfAborted();
123
- const context = extractionHistory(messages, config.historyMessages);
124
- stage = "commit";
125
- const written = store.commit({ session, expected: checkpoint.cursor, cursor: page.cursor,
126
- context, accepted, owner, version: EXTRACTION_VERSION,
127
- completeRevision: page.exhausted ? session.sourceRevision : undefined });
128
- processed++;
129
- acceptedCount += written;
130
- }
131
- catch {
132
- signal.throwIfAborted();
133
- failed++;
134
- processed++;
135
- store.error(session.sessionId, `${stage}_failed`);
136
- }
270
+ const outcome = await processSession({
271
+ session,
272
+ store,
273
+ owner,
274
+ config: params.config,
275
+ agentId: params.agentId,
276
+ agentName: params.agentName,
277
+ since: params.since,
278
+ version,
279
+ policyFingerprint,
280
+ apiKey,
281
+ signal,
282
+ leaseAbort,
283
+ readPage,
284
+ extract,
285
+ validate,
286
+ });
287
+ processed += outcome.processed;
288
+ acceptedCount += outcome.accepted;
289
+ rejectedCount += outcome.rejected;
290
+ unchanged += outcome.unchanged;
291
+ failed += outcome.failed;
137
292
  }
138
293
  return { status: "completed", processed, accepted: acceptedCount, rejected: rejectedCount, unchanged, failed };
139
294
  }
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { join, dirname } from "node:path";
2
3
  import { resolveAgentDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
3
4
  import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
@@ -15,7 +16,7 @@ export function registerInsideOut(api, config) {
15
16
  };
16
17
  api.registerCli(({ program, config: cfg }) => {
17
18
  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")
19
+ root.command("link-people").description("Backfill or refresh People identity links without the decision model")
19
20
  .option("--agent <id>", "Agent id", "main")
20
21
  .option("--repair-identities", "Recover legacy sender/channel metadata for unlinked reviews")
21
22
  .action(async (opts) => {
@@ -34,7 +35,7 @@ export function registerInsideOut(api, config) {
34
35
  if ("failed" in result && (result.failed || result.errors.length || result.baselineError))
35
36
  process.exitCode = 1;
36
37
  });
37
- root.command("baseline-refresh").description("Update local weekly baselines and missing comparisons; no Jev calls")
38
+ root.command("baseline-refresh").description("Update local weekly baselines and missing comparisons; no inference")
38
39
  .option("--agent <id>", "Agent id", "main")
39
40
  .option("--recompare", "Append revised comparisons using newly available historical grades; preserve earlier results")
40
41
  .action(async (opts) => {
@@ -46,7 +47,7 @@ export function registerInsideOut(api, config) {
46
47
  .action((opts) => {
47
48
  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
49
  });
49
- root.command("purge").description("Delete one person's emotion baselines and assessment history; no Jev calls")
50
+ root.command("purge").description("Delete one person's emotion baselines and assessment history; no inference")
50
51
  .requiredOption("--person <id>", "Exact PeopleSQL person ID").option("--agent <id>", "Agent id", "main")
51
52
  .option("--grades", "Also erase this person's raw emotion grades; tombstones keep those replies from being regraded")
52
53
  .action((opts) => {
@@ -71,58 +72,70 @@ export function registerInsideOut(api, config) {
71
72
  let timer, baselineTimer, running;
72
73
  let refreshing;
73
74
  let lifetime = new AbortController();
75
+ const clearTimers = () => {
76
+ if (timer) {
77
+ clearInterval(timer);
78
+ timer = undefined;
79
+ }
80
+ if (baselineTimer) {
81
+ clearInterval(baselineTimer);
82
+ baselineTimer = undefined;
83
+ }
84
+ };
74
85
  const tick = () => {
75
- if (running)
86
+ if (running || lifetime.signal.aborted)
76
87
  return;
88
+ const { signal } = lifetime;
77
89
  running = (async () => {
78
90
  for (const agentId of listAgentIds(api.config)) {
79
- if (lifetime.signal.aborted)
91
+ if (signal.aborted)
80
92
  break;
81
93
  try {
82
- const result = await runInsideOut({ ...paths(api.config, agentId), config, signal: lifetime.signal });
94
+ const result = await runInsideOut({ ...paths(api.config, agentId), config, signal });
83
95
  if ("failed" in result && (result.failed || result.errors.length))
84
96
  api.logger.warn("Inside Out: some reviews or sources failed; inspect memory-emotions export");
85
97
  if ("baselineError" in result && result.baselineError)
86
98
  api.logger.warn(`Inside Out baselines: ${result.baselineError}`);
87
99
  }
88
100
  catch (error) {
89
- if (!lifetime.signal.aborted)
101
+ if (!signal.aborted)
90
102
  api.logger.warn(`Inside Out: ${String(error)}`);
91
103
  }
92
104
  }
93
105
  })().finally(() => { running = undefined; });
94
106
  };
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
- }
107
+ const refresh = () => {
108
+ if (refreshing || lifetime.signal.aborted)
109
+ return;
110
+ const { signal } = lifetime;
111
+ refreshing = (async () => {
112
+ for (const agentId of listAgentIds(api.config)) {
113
+ if (signal.aborted)
114
+ break;
115
+ try {
116
+ await refreshInsideOutBaselinesAsync(paths(api.config, agentId).storePath, { minInteractions: config.insideOut.baselineMinInteractions }, signal);
117
+ }
118
+ catch (error) {
119
+ if (!signal.aborted)
120
+ api.logger.warn(`Inside Out baselines: ${String(error)}`);
111
121
  }
112
- })().finally(() => { refreshing = undefined; });
113
- };
122
+ }
123
+ })().finally(() => { refreshing = undefined; });
124
+ };
125
+ api.on("gateway_start", () => {
126
+ clearTimers();
127
+ if (lifetime.signal.aborted)
128
+ lifetime = new AbortController();
114
129
  // Local statistics remain available when inference is manual-only or lacks a key.
115
- baselineTimer = setInterval(refresh, 86400_000);
130
+ baselineTimer = setInterval(refresh, DEFAULTS.insideOut.baselineRefreshMs);
116
131
  baselineTimer.unref();
117
132
  refresh();
118
- if (config.typesafe.enabled && config.insideOut.intervalMinutes) {
133
+ if (config.decisionModel.enabled && config.insideOut.intervalMinutes) {
119
134
  timer = setInterval(tick, config.insideOut.intervalMinutes * 60_000);
120
135
  timer.unref();
121
136
  tick();
122
137
  }
123
138
  });
124
139
  // 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]); });
140
+ api.on("gateway_stop", async () => { clearTimers(); lifetime.abort(); await Promise.all([running, refreshing]); });
128
141
  }
@@ -1,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { createReadStream, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { DatabaseSync } from "node:sqlite";
@@ -56,7 +57,7 @@ export async function* readInsideOutSources(paths, errors) {
56
57
  if (existsSync(paths.databasePath)) {
57
58
  const db = new DatabaseSync(paths.databasePath, { readOnly: true });
58
59
  try {
59
- db.exec("PRAGMA busy_timeout=1000");
60
+ db.exec(`PRAGMA busy_timeout=${DEFAULTS.sqlite.readerBusyTimeoutMs}`);
60
61
  const transcripts = new AgentTranscriptReader(db, paths.agentId);
61
62
  const sessions = db.prepare(`SELECT w.session_id sessionId, COALESCE(w.channel,c.channel,'local') channel,
62
63
  COALESCE(w.account_id,c.account_id,'') account, COALESCE(r.generation,'') revision,
@@ -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