@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,9 +1,12 @@
1
+ import { DEFAULTS } from "./defaults.js";
2
+ import { randomUUID } from "node:crypto";
1
3
  import { DatabaseSync } from "node:sqlite";
2
- import { chmodSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
4
+ import { chmodSync, closeSync, constants, fchmodSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync, } from "node:fs";
3
5
  import { join } from "node:path";
4
6
  import { AgentTranscriptReader } from "./agent-transcript.js";
5
7
  import { record, nonBlank } from "./guards.js";
6
8
  import { jsonHash } from "./json-hash.js";
9
+ import { isInteractionCategory } from "./people-background.js";
7
10
  import { messageText } from "./whisperer-context.js";
8
11
  import { responseUserText } from "./response-text.js";
9
12
  import { reviewWindow } from "./people-learning-time.js";
@@ -11,10 +14,12 @@ export function dossierAssertions(personId, dossier) {
11
14
  // The blurb is prose, not necessarily one statement. Enumerate sentences as well as section claims.
12
15
  const sentences = [...new Intl.Segmenter("en", { granularity: "sentence" }).segment(dossier.blurb)]
13
16
  .map(s => s.segment.trim()).filter(Boolean);
14
- const assertions = [...sentences.map(statement => ({ personId, category: "blurb", statement })),
17
+ const assertions = [
18
+ ...sentences.map(statement => ({ personId, category: "blurb", statement })),
15
19
  ...dossier.sections.flatMap(section => section.claims.map(claim => ({
16
20
  personId, category: section.category, statement: claim.statement, claim,
17
- })))];
21
+ }))),
22
+ ];
18
23
  const occurrences = new Map();
19
24
  return assertions.map(assertion => {
20
25
  const { reviewedAt: _reviewed, ...claim } = assertion.claim ?? {};
@@ -24,34 +29,105 @@ export function dossierAssertions(personId, dossier) {
24
29
  return { ...assertion, id: jsonHash([fingerprint, occurrence]) };
25
30
  });
26
31
  }
32
+ function existingArtifactMatches(file, payload) {
33
+ const stat = lstatSync(file, { throwIfNoEntry: false });
34
+ if (!stat)
35
+ return false;
36
+ if (!stat.isFile())
37
+ throw new Error("Private review artifact must be a regular file, not a symlink");
38
+ return stat.size === payload.length && readFileSync(file).equals(payload);
39
+ }
40
+ /** Atomically publishes a flushed 0o600 private JSON artifact; never accepts a truncated partial file. */
27
41
  export function privateJson(root, name, value) {
28
42
  mkdirSync(root, { recursive: true, mode: 0o700 });
29
43
  chmodSync(root, 0o700);
30
44
  const file = join(root, name);
31
- // Content-addressed exports are immutable. Never follow an existing file/symlink for writes.
32
- if (!existsSync(file))
33
- writeFileSync(file, JSON.stringify(value, null, 2) + "\n", { mode: 0o600, flag: "wx" });
34
- return file;
45
+ const payload = Buffer.from(JSON.stringify(value, null, 2) + "\n", "utf8");
46
+ const existing = lstatSync(file, { throwIfNoEntry: false });
47
+ if (existing) {
48
+ if (!existing.isFile())
49
+ throw new Error("Private review artifact must be a regular file, not a symlink");
50
+ if (existing.size === payload.length && readFileSync(file).equals(payload)) {
51
+ chmodSync(file, 0o600);
52
+ return file;
53
+ }
54
+ }
55
+ const temp = join(root, `.${name}.${process.pid}.${randomUUID()}.tmp`);
56
+ let fd;
57
+ try {
58
+ fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
59
+ fchmodSync(fd, 0o600);
60
+ let offset = 0;
61
+ while (offset < payload.length) {
62
+ offset += writeSync(fd, payload, offset, payload.length - offset);
63
+ }
64
+ fsyncSync(fd);
65
+ closeSync(fd);
66
+ fd = undefined;
67
+ if (!existing) {
68
+ try {
69
+ linkSync(temp, file);
70
+ unlinkSync(temp);
71
+ return file;
72
+ }
73
+ catch (error) {
74
+ const code = error?.code;
75
+ if (code === "EPERM" || code === "ENOTSUP" || code === "EXDEV") {
76
+ renameSync(temp, file);
77
+ return file;
78
+ }
79
+ if (code !== "EEXIST")
80
+ throw error;
81
+ if (existingArtifactMatches(file, payload)) {
82
+ unlinkSync(temp);
83
+ return file;
84
+ }
85
+ renameSync(temp, file);
86
+ return file;
87
+ }
88
+ }
89
+ renameSync(temp, file);
90
+ return file;
91
+ }
92
+ catch (error) {
93
+ if (fd !== undefined) {
94
+ try {
95
+ closeSync(fd);
96
+ }
97
+ catch { }
98
+ }
99
+ try {
100
+ unlinkSync(temp);
101
+ }
102
+ catch { }
103
+ throw error;
104
+ }
35
105
  }
36
- export function inventoryPeople(options) {
37
- const now = options.now ?? Date.now(), { people, agentId, kind } = options;
38
- const window = reviewWindow(now, options.timezone, kind, options.day);
39
- const id = `${kind}:${window.localDay}`;
40
- const manifest = { id, agentId, kind, createdAt: new Date(now).toISOString(), window,
41
- fullValidation: kind === "weekly", roster: [], assertions: [], sourceGaps: [], sessions: [] };
42
- const gap = (reason, sessionId) => {
43
- const value = { reason, ...(sessionId ? { sessionId } : {}) };
44
- manifest.sourceGaps.push({ ...value, id: jsonHash(value) });
45
- };
106
+ function loadRosterAndDossiers(people) {
107
+ const roster = [];
46
108
  const dossiers = new Map();
109
+ const byIdentity = new Map();
47
110
  // Page through every record; inactive people remain visible without being reactivated.
48
111
  for (let offset = 0;; offset += 100) {
49
112
  const page = people.listActivePeople(100, offset, true);
50
113
  for (const person of page) {
51
- const identities = people.listIdentities(person.id).filter(i => !i.isDeactivated && i.isBot !== true)
52
- .map(({ provider, accountScope, externalId }) => ({ provider, accountScope, externalId }));
53
- manifest.roster.push({ personId: person.id, name: person.displayName, status: person.status,
54
- injectionEnabled: person.injectionEnabled, identities, sessionIds: [] });
114
+ const activeIdentities = people.listIdentities(person.id).filter(i => !i.isDeactivated && i.isBot !== true);
115
+ const identities = activeIdentities.map(({ provider, accountScope, externalId }) => ({ provider, accountScope, externalId }));
116
+ const reviewPerson = {
117
+ personId: person.id,
118
+ name: person.displayName,
119
+ status: person.status,
120
+ injectionEnabled: person.injectionEnabled,
121
+ identities,
122
+ sessionIds: [],
123
+ };
124
+ roster.push(reviewPerson);
125
+ for (const identity of activeIdentities) {
126
+ byIdentity.set(JSON.stringify([identity.provider, identity.accountScope, identity.externalId]), {
127
+ person: reviewPerson,
128
+ confirmedHuman: identity.isBot === false,
129
+ });
130
+ }
55
131
  const dossier = people.getDossier(person.id)?.dossier;
56
132
  if (dossier)
57
133
  dossiers.set(person.id, dossier);
@@ -59,14 +135,192 @@ export function inventoryPeople(options) {
59
135
  if (page.length < 100)
60
136
  break;
61
137
  }
62
- const byIdentity = new Map(manifest.roster.flatMap(person => people.listIdentities(person.personId)
63
- .filter(i => !i.isDeactivated && i.isBot !== true).map(identity => [JSON.stringify([identity.provider, identity.accountScope, identity.externalId]), { person, confirmedHuman: identity.isBot === false }])));
138
+ return { roster, dossiers, byIdentity };
139
+ }
140
+ function inventorySessionTranscript(session, snapshot, window, byIdentity, exportRoot, gap) {
141
+ const sessionId = String(session.sessionId);
142
+ const participants = new Set();
143
+ const messages = [];
144
+ let currentPerson;
145
+ let excludedExchange = false;
146
+ for (const row of snapshot.rows) {
147
+ const inWindow = row.createdAt >= window.since && row.createdAt < window.until;
148
+ let event;
149
+ try {
150
+ event = record(JSON.parse(row.eventJson));
151
+ }
152
+ catch {
153
+ gap(`Invalid event JSON at ${row.seq}`, sessionId);
154
+ currentPerson = undefined;
155
+ excludedExchange = false;
156
+ continue;
157
+ }
158
+ if (event?.type !== "message")
159
+ continue;
160
+ const message = record(event.message), meta = record(message?.__openclaw);
161
+ if (!message || (message.provenance !== undefined && record(message.provenance)?.kind !== "external_user")) {
162
+ currentPerson = undefined;
163
+ excludedExchange = true;
164
+ continue;
165
+ }
166
+ if (message.role === "user") {
167
+ const transport = record(meta?.transport), sender = nonBlank(meta?.senderId);
168
+ const identity = record(meta?.senderIdentity);
169
+ const provider = nonBlank(transport?.channel), account = nonBlank(transport?.accountId) ?? nonBlank(session.accountId);
170
+ currentPerson = undefined;
171
+ excludedExchange = false;
172
+ if (identity?.senderKind === "bot") {
173
+ excludedExchange = true;
174
+ continue;
175
+ }
176
+ const resolved = sender && provider && account ? byIdentity.get(JSON.stringify([provider, account, sender])) : undefined;
177
+ const person = resolved?.person;
178
+ if (!person || (!resolved.confirmedHuman && identity?.senderKind !== "human") || provider !== session.provider || account !== session.accountId ||
179
+ transport?.conversationRef !== session.conversationId || meta?.turnTainted === true) {
180
+ excludedExchange = !!provider && !!account && (provider !== session.provider || account !== session.accountId);
181
+ if (inWindow)
182
+ gap(`Unmapped or ambiguous exact identity at event ${row.seq}`, sessionId);
183
+ messages.push({ seq: row.seq, role: "boundary", timestamp: row.createdAt });
184
+ continue;
185
+ }
186
+ const raw = nonBlank(meta?.upstreamUserText) ?? messageText(message)?.text;
187
+ const nonText = Array.isArray(message.content) ? message.content.map(record)
188
+ .filter(part => part && part.type !== "text").map(part => ({ type: part.type, mimeType: part.mimeType })) : [];
189
+ const media = Array.isArray(meta?.media) ? meta.media.map(record).map(part => ({
190
+ path: part?.path, url: part?.url, kind: part?.kind, contentType: part?.contentType, fileName: part?.fileName,
191
+ })) : [];
192
+ if (nonText.length || media.length || (Array.isArray(message.attachments) && message.attachments.length)) {
193
+ gap(`Non-text human content requires original-source review at event ${row.seq}`, sessionId);
194
+ }
195
+ const extracted = raw ? responseUserText(raw, sender) : undefined;
196
+ currentPerson = person;
197
+ if (inWindow)
198
+ participants.add(person.personId);
199
+ if (!extracted)
200
+ gap(`Unreadable human request at event ${row.seq}`, sessionId);
201
+ messages.push({
202
+ seq: row.seq, timestamp: row.createdAt, role: "user", personId: person.personId,
203
+ provider, accountScope: account, senderId: sender, threadId: transport?.threadId ?? null,
204
+ text: extracted?.text ?? "Unreadable request; inspect the native original", nonText, media,
205
+ });
206
+ }
207
+ else if (!currentPerson) {
208
+ // A rejected user identity fences its entire exchange, not just the
209
+ // request. Never export another account's replies or tool results.
210
+ if (inWindow && !excludedExchange && ["assistant", "toolResult", "tool"].includes(String(message.role))) {
211
+ gap(`Unattributed output at event ${row.seq}; relevant activity unknown`, sessionId);
212
+ }
213
+ continue;
214
+ }
215
+ else if (meta?.turnTainted === true || meta?.resultContentSource === "network") {
216
+ if (inWindow)
217
+ participants.add(currentPerson.personId);
218
+ gap(`Untrusted ${String(message.role)} output requires original-source review at event ${row.seq}`, sessionId);
219
+ if (message.role === "assistant" && ["error", "aborted", "cancelled"].includes(String(message.stopReason))) {
220
+ messages.push({ seq: row.seq, role: "assistant_outcome", timestamp: row.createdAt, stopReason: message.stopReason, detailsWithheld: true });
221
+ }
222
+ }
223
+ else if (message.role === "assistant") {
224
+ if (message.provider === "openclaw" && ["delivery-mirror", "gateway-injected"].includes(String(message.model)))
225
+ continue;
226
+ const calls = Array.isArray(message.content) ? message.content.map(record).filter(part => part?.type === "toolCall") : [];
227
+ if (calls.length) {
228
+ if (inWindow)
229
+ participants.add(currentPerson.personId);
230
+ messages.push({ seq: row.seq, role: "tool_calls", timestamp: row.createdAt, calls });
231
+ }
232
+ if (message.channel === "analysis")
233
+ continue; // Never export hidden reasoning.
234
+ const visibleContent = Array.isArray(message.openclawDisplayContent) ? message.openclawDisplayContent : message.content;
235
+ const text = messageText({ ...message, content: visibleContent })?.text;
236
+ if (message.errorMessage || ["error", "aborted", "cancelled"].includes(String(message.stopReason))) {
237
+ if (inWindow)
238
+ participants.add(currentPerson.personId);
239
+ messages.push({
240
+ seq: row.seq, role: "assistant_outcome", timestamp: row.createdAt,
241
+ stopReason: message.stopReason, errorMessage: message.errorMessage,
242
+ });
243
+ }
244
+ const mediaUrls = record(message.openclawDelivery)?.mediaUrls;
245
+ if ((Array.isArray(visibleContent) && visibleContent.map(record).some(part => !["text", "toolCall", "thinking"].includes(String(part?.type)))) ||
246
+ (Array.isArray(mediaUrls) && mediaUrls.length > 0)) {
247
+ gap(`Non-text assistant output requires original-source review at event ${row.seq}`, sessionId);
248
+ if (inWindow)
249
+ participants.add(currentPerson.personId);
250
+ messages.push({
251
+ seq: row.seq, role: "assistant_media", timestamp: row.createdAt,
252
+ mediaUrls: Array.isArray(mediaUrls) ? mediaUrls.filter(url => typeof url === "string") : [],
253
+ });
254
+ }
255
+ if (!text || ["NO_REPLY", "HEARTBEAT_OK"].includes(text.trim()))
256
+ continue;
257
+ if (inWindow)
258
+ participants.add(currentPerson.personId);
259
+ messages.push({ seq: row.seq, role: "assistant", timestamp: row.createdAt, text });
260
+ }
261
+ else if (message.role === "toolResult" || message.role === "tool") {
262
+ if (inWindow)
263
+ participants.add(currentPerson.personId);
264
+ const parts = Array.isArray(message.content) ? message.content.map(record) : undefined;
265
+ const text = nonBlank(message.content) ?? (parts
266
+ ? parts.flatMap(part => part?.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n").trim()
267
+ : undefined);
268
+ if (!text || (parts && parts.some(part => part?.type !== "text"))) {
269
+ gap(`Non-text tool result requires original-source review at event ${row.seq}`, sessionId);
270
+ }
271
+ messages.push({
272
+ seq: row.seq, role: "tool_result", timestamp: row.createdAt,
273
+ toolName: message.toolName, toolCallId: message.toolCallId, isError: message.isError,
274
+ text: text || "Non-text tool result; inspect the native original",
275
+ });
276
+ }
277
+ }
278
+ // Export the complete relevant session, including context and later repair.
279
+ if (!participants.size)
280
+ return undefined;
281
+ const value = { ...session, window, messages, sourceRevision: jsonHash(snapshot.rows) };
282
+ const revision = jsonHash(value);
283
+ const file = privateJson(exportRoot, `${revision}.json`, value);
284
+ return { exported: { sessionId, revision, file }, participants };
285
+ }
286
+ function collectManifestAssertions(manifest, dossiers, people, kind) {
287
+ for (const person of manifest.roster) {
288
+ const dossier = dossiers.get(person.personId);
289
+ if (!dossier)
290
+ continue;
291
+ const unverified = !people.isDossierVerified(person.personId) || dossier.sections.some(s => isInteractionCategory(s.category) &&
292
+ s.claims.some(c => !c.reviewedAt || !c.scope || c.epistemicType === "inferred" ||
293
+ (c.epistemicType === "agent_assessment" && !c.expiresAt)));
294
+ if (unverified)
295
+ manifest.fullValidation = true;
296
+ if (kind === "nightly" ? unverified : person.sessionIds.length > 0 || unverified) {
297
+ manifest.assertions.push(...dossierAssertions(person.personId, dossier));
298
+ }
299
+ }
300
+ // A source outage may hide weekly activity. Validate all dossiers conservatively.
301
+ if (kind === "weekly" && manifest.sourceGaps.length) {
302
+ manifest.assertions = [...dossiers].flatMap(([personId, dossier]) => dossierAssertions(personId, dossier));
303
+ }
304
+ }
305
+ export function inventoryPeople(options) {
306
+ const now = options.now ?? Date.now(), { people, agentId, kind } = options;
307
+ const window = reviewWindow(now, options.timezone, kind, options.day);
308
+ const id = `${kind}:${window.localDay}`;
309
+ const { roster, dossiers, byIdentity } = loadRosterAndDossiers(people);
310
+ const manifest = {
311
+ id, agentId, kind, createdAt: new Date(now).toISOString(), window,
312
+ fullValidation: kind === "weekly", roster, assertions: [], sourceGaps: [], sessions: [],
313
+ };
314
+ const gap = (reason, sessionId) => {
315
+ const value = { reason, ...(sessionId ? { sessionId } : {}) };
316
+ manifest.sourceGaps.push({ ...value, id: jsonHash(value) });
317
+ };
64
318
  if (!byIdentity.size)
65
319
  gap("No authoritative local people identities; synchronize the host directory before claiming roster coverage");
66
320
  let db;
67
321
  try {
68
322
  db = new DatabaseSync(options.databasePath, { readOnly: true });
69
- db.exec("PRAGMA query_only=ON; PRAGMA busy_timeout=2000; BEGIN");
323
+ db.exec(`PRAGMA query_only=ON; PRAGMA busy_timeout=${DEFAULTS.sqlite.peopleInventoryBusyTimeoutMs}; BEGIN`);
70
324
  const reader = new AgentTranscriptReader(db, agentId);
71
325
  // Scan the catalog, not session start dates or audit's capped candidate window.
72
326
  // Cold/inaccessible history cannot be proven irrelevant and remains explicit work.
@@ -95,139 +349,12 @@ export function inventoryPeople(options) {
95
349
  gap("Missing or unsupported conversation type; relevance unknown", sessionId);
96
350
  continue;
97
351
  }
98
- const participants = new Set();
99
- const messages = [];
100
- let currentPerson;
101
- let excludedExchange = false;
102
- for (const row of snapshot.rows) {
103
- const inWindow = row.createdAt >= window.since && row.createdAt < window.until;
104
- let event;
105
- try {
106
- event = record(JSON.parse(row.eventJson));
107
- }
108
- catch {
109
- gap(`Invalid event JSON at ${row.seq}`, sessionId);
110
- currentPerson = undefined;
111
- excludedExchange = false;
112
- continue;
113
- }
114
- if (event?.type !== "message")
115
- continue;
116
- const message = record(event.message), meta = record(message?.__openclaw);
117
- if (!message || (message.provenance !== undefined && record(message.provenance)?.kind !== "external_user")) {
118
- currentPerson = undefined;
119
- excludedExchange = true;
120
- continue;
121
- }
122
- if (message.role === "user") {
123
- const transport = record(meta?.transport), sender = nonBlank(meta?.senderId);
124
- const identity = record(meta?.senderIdentity);
125
- const provider = nonBlank(transport?.channel), account = nonBlank(transport?.accountId) ?? nonBlank(session.accountId);
126
- currentPerson = undefined;
127
- excludedExchange = false;
128
- if (identity?.senderKind === "bot") {
129
- excludedExchange = true;
130
- continue;
131
- }
132
- const resolved = sender && provider && account ? byIdentity.get(JSON.stringify([provider, account, sender])) : undefined;
133
- const person = resolved?.person;
134
- if (!person || (!resolved.confirmedHuman && identity?.senderKind !== "human") || provider !== session.provider || account !== session.accountId ||
135
- transport?.conversationRef !== session.conversationId || meta?.turnTainted === true) {
136
- excludedExchange = !!provider && !!account && (provider !== session.provider || account !== session.accountId);
137
- if (inWindow)
138
- gap(`Unmapped or ambiguous exact identity at event ${row.seq}`, sessionId);
139
- messages.push({ seq: row.seq, role: "boundary", timestamp: row.createdAt });
140
- continue;
141
- }
142
- const raw = nonBlank(meta?.upstreamUserText) ?? messageText(message)?.text;
143
- const nonText = Array.isArray(message.content) ? message.content.map(record)
144
- .filter(part => part && part.type !== "text").map(part => ({ type: part.type, mimeType: part.mimeType })) : [];
145
- const media = Array.isArray(meta?.media) ? meta.media.map(record).map(part => ({
146
- path: part?.path, url: part?.url, kind: part?.kind, contentType: part?.contentType, fileName: part?.fileName,
147
- })) : [];
148
- if (nonText.length || media.length || (Array.isArray(message.attachments) && message.attachments.length)) {
149
- gap(`Non-text human content requires original-source review at event ${row.seq}`, sessionId);
150
- }
151
- const extracted = raw ? responseUserText(raw, sender) : undefined;
152
- currentPerson = person;
153
- if (inWindow)
154
- participants.add(person.personId);
155
- if (!extracted)
156
- gap(`Unreadable human request at event ${row.seq}`, sessionId);
157
- messages.push({ seq: row.seq, timestamp: row.createdAt, role: "user", personId: person.personId,
158
- provider, accountScope: account, senderId: sender, threadId: transport?.threadId ?? null,
159
- text: extracted?.text ?? "Unreadable request; inspect the native original", nonText, media });
160
- }
161
- else if (!currentPerson) {
162
- // A rejected user identity fences its entire exchange, not just the
163
- // request. Never export another account's replies or tool results.
164
- if (inWindow && !excludedExchange && ["assistant", "toolResult", "tool"].includes(String(message.role))) {
165
- gap(`Unattributed output at event ${row.seq}; relevant activity unknown`, sessionId);
166
- }
167
- continue;
168
- }
169
- else if (meta?.turnTainted === true || meta?.resultContentSource === "network") {
170
- if (inWindow)
171
- participants.add(currentPerson.personId);
172
- gap(`Untrusted ${String(message.role)} output requires original-source review at event ${row.seq}`, sessionId);
173
- if (message.role === "assistant" && ["error", "aborted", "cancelled"].includes(String(message.stopReason))) {
174
- messages.push({ seq: row.seq, role: "assistant_outcome", timestamp: row.createdAt, stopReason: message.stopReason, detailsWithheld: true });
175
- }
176
- }
177
- else if (message.role === "assistant") {
178
- if (message.provider === "openclaw" && ["delivery-mirror", "gateway-injected"].includes(String(message.model)))
179
- continue;
180
- const calls = Array.isArray(message.content) ? message.content.map(record).filter(part => part?.type === "toolCall") : [];
181
- if (calls.length) {
182
- if (inWindow && currentPerson)
183
- participants.add(currentPerson.personId);
184
- messages.push({ seq: row.seq, role: "tool_calls", timestamp: row.createdAt, calls });
185
- }
186
- if (message.channel === "analysis")
187
- continue; // Never export hidden reasoning.
188
- const visibleContent = Array.isArray(message.openclawDisplayContent) ? message.openclawDisplayContent : message.content;
189
- const text = messageText({ ...message, content: visibleContent })?.text;
190
- if (message.errorMessage || ["error", "aborted", "cancelled"].includes(String(message.stopReason))) {
191
- if (inWindow)
192
- participants.add(currentPerson.personId);
193
- messages.push({ seq: row.seq, role: "assistant_outcome", timestamp: row.createdAt,
194
- stopReason: message.stopReason, errorMessage: message.errorMessage });
195
- }
196
- const mediaUrls = record(message.openclawDelivery)?.mediaUrls;
197
- if ((Array.isArray(visibleContent) && visibleContent.map(record).some(part => !["text", "toolCall", "thinking"].includes(String(part?.type)))) ||
198
- (Array.isArray(mediaUrls) && mediaUrls.length > 0)) {
199
- gap(`Non-text assistant output requires original-source review at event ${row.seq}`, sessionId);
200
- if (inWindow)
201
- participants.add(currentPerson.personId);
202
- messages.push({ seq: row.seq, role: "assistant_media", timestamp: row.createdAt,
203
- mediaUrls: Array.isArray(mediaUrls) ? mediaUrls.filter(url => typeof url === "string") : [] });
204
- }
205
- if (!text || ["NO_REPLY", "HEARTBEAT_OK"].includes(text.trim()))
206
- continue;
207
- if (inWindow && currentPerson)
208
- participants.add(currentPerson.personId);
209
- messages.push({ seq: row.seq, role: "assistant", timestamp: row.createdAt, text });
210
- }
211
- else if (message.role === "toolResult" || message.role === "tool") {
212
- if (inWindow && currentPerson)
213
- participants.add(currentPerson.personId);
214
- const text = nonBlank(message.content) ?? (Array.isArray(message.content) ? message.content.map(record)
215
- .flatMap(part => part?.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n").trim() : undefined);
216
- if (!text || (Array.isArray(message.content) && message.content.map(record).some(part => part?.type !== "text")))
217
- gap(`Non-text tool result requires original-source review at event ${row.seq}`, sessionId);
218
- messages.push({ seq: row.seq, role: "tool_result", timestamp: row.createdAt,
219
- toolName: message.toolName, toolCallId: message.toolCallId, isError: message.isError,
220
- text: text || "Non-text tool result; inspect the native original" });
221
- }
222
- }
223
- // Export the complete relevant session, including context and later repair.
224
- if (!participants.size)
352
+ const result = inventorySessionTranscript(session, snapshot, window, byIdentity, options.exportRoot, gap);
353
+ if (!result)
225
354
  continue;
226
- const value = { ...session, window, messages, sourceRevision: jsonHash(snapshot.rows) }, revision = jsonHash(value);
227
- const file = privateJson(options.exportRoot, `${revision}.json`, value);
228
- manifest.sessions.push({ sessionId, revision, file });
355
+ manifest.sessions.push(result.exported);
229
356
  for (const person of manifest.roster)
230
- if (participants.has(person.personId))
357
+ if (result.participants.has(person.personId))
231
358
  person.sessionIds.push(sessionId);
232
359
  }
233
360
  }
@@ -239,22 +366,6 @@ export function inventoryPeople(options) {
239
366
  db.exec("ROLLBACK");
240
367
  db?.close();
241
368
  }
242
- for (const person of manifest.roster) {
243
- const dossier = dossiers.get(person.personId);
244
- if (!dossier)
245
- continue;
246
- const unverified = !people.isDossierVerified(person.personId) || dossier.sections.some(s => ["preferences", "workingStyle"].includes(s.category) &&
247
- s.claims.some(c => !c.reviewedAt || !c.scope || c.epistemicType === "inferred" ||
248
- (c.epistemicType === "agent_assessment" && !c.expiresAt)));
249
- if (unverified)
250
- manifest.fullValidation = true;
251
- if (kind === "nightly" ? unverified : person.sessionIds.length > 0 || unverified) {
252
- manifest.assertions.push(...dossierAssertions(person.personId, dossier));
253
- }
254
- }
255
- // A source outage may hide weekly activity. Validate all dossiers conservatively.
256
- if (kind === "weekly" && manifest.sourceGaps.length) {
257
- manifest.assertions = [...dossiers].flatMap(([personId, dossier]) => dossierAssertions(personId, dossier));
258
- }
369
+ collectManifestAssertions(manifest, dossiers, people, kind);
259
370
  return manifest;
260
371
  }
@@ -6,6 +6,6 @@ Use action signals with runId for approved response-quality and sentiment leads.
6
6
  You decide what is useful. Curate preferences during nightly dreaming. Keep useful explicit preferences and working-style feedback with exact sources and scope. Inferred lessons must be actionable, person-specific, labelled agent_assessment, sourced, reviewedAt the actual verification time, and expiresAt seven days later by default (maximum thirty days). Never renew a lesson merely because it exists. Keep general execution fixes in receipt.executionFollowups, not person dossiers. Avoid unnecessary or irrelevant caveats; keep saved lessons concise.
7
7
  For every manifest assertion (each blurb sentence and every section claim), inspect original evidence AND search newer corrections. Revalidate, correct, retire, or mark unresolved. Preserve history, scope, uncertainty, original source dates, and actual verification dates. An outage is unresolved work, never falsity or successful validation. Respect inactive/paused records; inspect/report but never restore or enable them. Legacy unverified preferences must pass complete source validation before reuse.
8
8
  Use memory_people_inspect and memory_people_update replace_dossier/delete_dossier only after source verification. Preserve independently valid claims; never drop unresolved claims to make a write pass. For source-specific manualVerification, attest only to evidence actually read. Verify actual save results and capture change IDs from dossier history. Read the packaged people-whisperer skill for evidence/save constraints.
9
- Checkpoint progress frequently with memory_people_learning action checkpoint and runId. Receipt fields: peopleReviews [{personId,status:reviewed|no_interactions|unresolved,sessionIds,reason,sourceRefs,reviewedAt}], assertionReviews [{assertionId,disposition:revalidated|corrected|retired|unresolved,reason,sourceRefs,reviewedAt,correctionsCheckedAt}], sourceGapReviews [{sourceGapId,status:resolved|unresolved,reason,sourceRefs,reviewedAt}], analysis {status:complete|not_approved|unresolved,reason}, changes [{personId,changeId}], executionFollowups [string]. Empty arrays are valid incremental checkpoints, never proof of complete coverage. Use actual ISO dates. Only resolve a gap after checking original sources and recording exact references. Read every assertion within a sentence/claim even if it contains several clauses. Omitted work remains backlog automatically.
9
+ Checkpoint progress frequently with memory_people_learning action checkpoint, runId, and the required latest manifestRevision from inventory/inspect/checkpoint. Receipt fields: peopleReviews [{personId,status:reviewed|no_interactions|unresolved,sessionIds,reason,sourceRefs,reviewedAt}], assertionReviews [{assertionId,disposition:revalidated|corrected|retired|unresolved,reason,sourceRefs,reviewedAt,correctionsCheckedAt}], sourceGapReviews [{sourceGapId,status:resolved|unresolved,reason,sourceRefs,reviewedAt}], analysis {status:complete|not_approved|unresolved,reason}, changes [{personId,changeId}], executionFollowups [string]. Empty arrays are valid incremental checkpoints, never proof of complete coverage. Use actual ISO dates. Only resolve a gap after checking original sources and recording exact references. Read every assertion within a sentence/claim even if it contains several clauses. Omitted work remains backlog automatically.
10
10
  No outbound messages, no exec/shell, no schedule/config/permission changes, no canonical registry edits. Exports and receipts stay private outside indexed corpora. End with a short private summary using the plugin's coverage status; never claim success if coverage is partial/invalid or backlog remains.`;
11
11
  }
@@ -1,6 +1,6 @@
1
1
  import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry";
2
2
  import { type UnblockMemoryConfig } from "./config.js";
3
- import type { PeopleStores } from "./people-store.js";
3
+ import { PeopleStores } from "./people-store.js";
4
4
  export declare function registerPeopleLearning(api: OpenClawPluginApi, initial: UnblockMemoryConfig, stores: PeopleStores): void;
5
5
  /** Operator CLI keeps raw review output private; no main-agent default. */
6
6
  export declare function registerPeopleLearningCli(api: OpenClawPluginApi, config: UnblockMemoryConfig): void;