@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
@@ -1,9 +1,11 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { DatabaseSync } from "node:sqlite";
2
- import { chmodSync, mkdirSync, writeFileSync, existsSync } from "node:fs";
3
+ import { chmodSync, closeSync, constants, fchmodSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync, } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { AgentTranscriptReader } from "./agent-transcript.js";
5
6
  import { record, nonBlank } from "./guards.js";
6
7
  import { jsonHash } from "./json-hash.js";
8
+ import { isInteractionCategory } from "./people-background.js";
7
9
  import { messageText } from "./whisperer-context.js";
8
10
  import { responseUserText } from "./response-text.js";
9
11
  import { reviewWindow } from "./people-learning-time.js";
@@ -11,10 +13,12 @@ export function dossierAssertions(personId, dossier) {
11
13
  // The blurb is prose, not necessarily one statement. Enumerate sentences as well as section claims.
12
14
  const sentences = [...new Intl.Segmenter("en", { granularity: "sentence" }).segment(dossier.blurb)]
13
15
  .map(s => s.segment.trim()).filter(Boolean);
14
- const assertions = [...sentences.map(statement => ({ personId, category: "blurb", statement })),
16
+ const assertions = [
17
+ ...sentences.map(statement => ({ personId, category: "blurb", statement })),
15
18
  ...dossier.sections.flatMap(section => section.claims.map(claim => ({
16
19
  personId, category: section.category, statement: claim.statement, claim,
17
- })))];
20
+ }))),
21
+ ];
18
22
  const occurrences = new Map();
19
23
  return assertions.map(assertion => {
20
24
  const { reviewedAt: _reviewed, ...claim } = assertion.claim ?? {};
@@ -24,34 +28,105 @@ export function dossierAssertions(personId, dossier) {
24
28
  return { ...assertion, id: jsonHash([fingerprint, occurrence]) };
25
29
  });
26
30
  }
31
+ function existingArtifactMatches(file, payload) {
32
+ const stat = lstatSync(file, { throwIfNoEntry: false });
33
+ if (!stat)
34
+ return false;
35
+ if (!stat.isFile())
36
+ throw new Error("Private review artifact must be a regular file, not a symlink");
37
+ return stat.size === payload.length && readFileSync(file).equals(payload);
38
+ }
39
+ /** Atomically publishes a flushed 0o600 private JSON artifact; never accepts a truncated partial file. */
27
40
  export function privateJson(root, name, value) {
28
41
  mkdirSync(root, { recursive: true, mode: 0o700 });
29
42
  chmodSync(root, 0o700);
30
43
  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;
44
+ const payload = Buffer.from(JSON.stringify(value, null, 2) + "\n", "utf8");
45
+ const existing = lstatSync(file, { throwIfNoEntry: false });
46
+ if (existing) {
47
+ if (!existing.isFile())
48
+ throw new Error("Private review artifact must be a regular file, not a symlink");
49
+ if (existing.size === payload.length && readFileSync(file).equals(payload)) {
50
+ chmodSync(file, 0o600);
51
+ return file;
52
+ }
53
+ }
54
+ const temp = join(root, `.${name}.${process.pid}.${randomUUID()}.tmp`);
55
+ let fd;
56
+ try {
57
+ fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
58
+ fchmodSync(fd, 0o600);
59
+ let offset = 0;
60
+ while (offset < payload.length) {
61
+ offset += writeSync(fd, payload, offset, payload.length - offset);
62
+ }
63
+ fsyncSync(fd);
64
+ closeSync(fd);
65
+ fd = undefined;
66
+ if (!existing) {
67
+ try {
68
+ linkSync(temp, file);
69
+ unlinkSync(temp);
70
+ return file;
71
+ }
72
+ catch (error) {
73
+ const code = error?.code;
74
+ if (code === "EPERM" || code === "ENOTSUP" || code === "EXDEV") {
75
+ renameSync(temp, file);
76
+ return file;
77
+ }
78
+ if (code !== "EEXIST")
79
+ throw error;
80
+ if (existingArtifactMatches(file, payload)) {
81
+ unlinkSync(temp);
82
+ return file;
83
+ }
84
+ renameSync(temp, file);
85
+ return file;
86
+ }
87
+ }
88
+ renameSync(temp, file);
89
+ return file;
90
+ }
91
+ catch (error) {
92
+ if (fd !== undefined) {
93
+ try {
94
+ closeSync(fd);
95
+ }
96
+ catch { }
97
+ }
98
+ try {
99
+ unlinkSync(temp);
100
+ }
101
+ catch { }
102
+ throw error;
103
+ }
35
104
  }
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
- };
105
+ function loadRosterAndDossiers(people) {
106
+ const roster = [];
46
107
  const dossiers = new Map();
108
+ const byIdentity = new Map();
47
109
  // Page through every record; inactive people remain visible without being reactivated.
48
110
  for (let offset = 0;; offset += 100) {
49
111
  const page = people.listActivePeople(100, offset, true);
50
112
  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: [] });
113
+ const activeIdentities = people.listIdentities(person.id).filter(i => !i.isDeactivated && i.isBot !== true);
114
+ const identities = activeIdentities.map(({ provider, accountScope, externalId }) => ({ provider, accountScope, externalId }));
115
+ const reviewPerson = {
116
+ personId: person.id,
117
+ name: person.displayName,
118
+ status: person.status,
119
+ injectionEnabled: person.injectionEnabled,
120
+ identities,
121
+ sessionIds: [],
122
+ };
123
+ roster.push(reviewPerson);
124
+ for (const identity of activeIdentities) {
125
+ byIdentity.set(JSON.stringify([identity.provider, identity.accountScope, identity.externalId]), {
126
+ person: reviewPerson,
127
+ confirmedHuman: identity.isBot === false,
128
+ });
129
+ }
55
130
  const dossier = people.getDossier(person.id)?.dossier;
56
131
  if (dossier)
57
132
  dossiers.set(person.id, dossier);
@@ -59,8 +134,186 @@ export function inventoryPeople(options) {
59
134
  if (page.length < 100)
60
135
  break;
61
136
  }
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 }])));
137
+ return { roster, dossiers, byIdentity };
138
+ }
139
+ function inventorySessionTranscript(session, snapshot, window, byIdentity, exportRoot, gap) {
140
+ const sessionId = String(session.sessionId);
141
+ const participants = new Set();
142
+ const messages = [];
143
+ let currentPerson;
144
+ let excludedExchange = false;
145
+ for (const row of snapshot.rows) {
146
+ const inWindow = row.createdAt >= window.since && row.createdAt < window.until;
147
+ let event;
148
+ try {
149
+ event = record(JSON.parse(row.eventJson));
150
+ }
151
+ catch {
152
+ gap(`Invalid event JSON at ${row.seq}`, sessionId);
153
+ currentPerson = undefined;
154
+ excludedExchange = false;
155
+ continue;
156
+ }
157
+ if (event?.type !== "message")
158
+ continue;
159
+ const message = record(event.message), meta = record(message?.__openclaw);
160
+ if (!message || (message.provenance !== undefined && record(message.provenance)?.kind !== "external_user")) {
161
+ currentPerson = undefined;
162
+ excludedExchange = true;
163
+ continue;
164
+ }
165
+ if (message.role === "user") {
166
+ const transport = record(meta?.transport), sender = nonBlank(meta?.senderId);
167
+ const identity = record(meta?.senderIdentity);
168
+ const provider = nonBlank(transport?.channel), account = nonBlank(transport?.accountId) ?? nonBlank(session.accountId);
169
+ currentPerson = undefined;
170
+ excludedExchange = false;
171
+ if (identity?.senderKind === "bot") {
172
+ excludedExchange = true;
173
+ continue;
174
+ }
175
+ const resolved = sender && provider && account ? byIdentity.get(JSON.stringify([provider, account, sender])) : undefined;
176
+ const person = resolved?.person;
177
+ if (!person || (!resolved.confirmedHuman && identity?.senderKind !== "human") || provider !== session.provider || account !== session.accountId ||
178
+ transport?.conversationRef !== session.conversationId || meta?.turnTainted === true) {
179
+ excludedExchange = !!provider && !!account && (provider !== session.provider || account !== session.accountId);
180
+ if (inWindow)
181
+ gap(`Unmapped or ambiguous exact identity at event ${row.seq}`, sessionId);
182
+ messages.push({ seq: row.seq, role: "boundary", timestamp: row.createdAt });
183
+ continue;
184
+ }
185
+ const raw = nonBlank(meta?.upstreamUserText) ?? messageText(message)?.text;
186
+ const nonText = Array.isArray(message.content) ? message.content.map(record)
187
+ .filter(part => part && part.type !== "text").map(part => ({ type: part.type, mimeType: part.mimeType })) : [];
188
+ const media = Array.isArray(meta?.media) ? meta.media.map(record).map(part => ({
189
+ path: part?.path, url: part?.url, kind: part?.kind, contentType: part?.contentType, fileName: part?.fileName,
190
+ })) : [];
191
+ if (nonText.length || media.length || (Array.isArray(message.attachments) && message.attachments.length)) {
192
+ gap(`Non-text human content requires original-source review at event ${row.seq}`, sessionId);
193
+ }
194
+ const extracted = raw ? responseUserText(raw, sender) : undefined;
195
+ currentPerson = person;
196
+ if (inWindow)
197
+ participants.add(person.personId);
198
+ if (!extracted)
199
+ gap(`Unreadable human request at event ${row.seq}`, sessionId);
200
+ messages.push({
201
+ seq: row.seq, timestamp: row.createdAt, role: "user", personId: person.personId,
202
+ provider, accountScope: account, senderId: sender, threadId: transport?.threadId ?? null,
203
+ text: extracted?.text ?? "Unreadable request; inspect the native original", nonText, media,
204
+ });
205
+ }
206
+ else if (!currentPerson) {
207
+ // A rejected user identity fences its entire exchange, not just the
208
+ // request. Never export another account's replies or tool results.
209
+ if (inWindow && !excludedExchange && ["assistant", "toolResult", "tool"].includes(String(message.role))) {
210
+ gap(`Unattributed output at event ${row.seq}; relevant activity unknown`, sessionId);
211
+ }
212
+ continue;
213
+ }
214
+ else if (meta?.turnTainted === true || meta?.resultContentSource === "network") {
215
+ if (inWindow)
216
+ participants.add(currentPerson.personId);
217
+ gap(`Untrusted ${String(message.role)} output requires original-source review at event ${row.seq}`, sessionId);
218
+ if (message.role === "assistant" && ["error", "aborted", "cancelled"].includes(String(message.stopReason))) {
219
+ messages.push({ seq: row.seq, role: "assistant_outcome", timestamp: row.createdAt, stopReason: message.stopReason, detailsWithheld: true });
220
+ }
221
+ }
222
+ else if (message.role === "assistant") {
223
+ if (message.provider === "openclaw" && ["delivery-mirror", "gateway-injected"].includes(String(message.model)))
224
+ continue;
225
+ const calls = Array.isArray(message.content) ? message.content.map(record).filter(part => part?.type === "toolCall") : [];
226
+ if (calls.length) {
227
+ if (inWindow)
228
+ participants.add(currentPerson.personId);
229
+ messages.push({ seq: row.seq, role: "tool_calls", timestamp: row.createdAt, calls });
230
+ }
231
+ if (message.channel === "analysis")
232
+ continue; // Never export hidden reasoning.
233
+ const visibleContent = Array.isArray(message.openclawDisplayContent) ? message.openclawDisplayContent : message.content;
234
+ const text = messageText({ ...message, content: visibleContent })?.text;
235
+ if (message.errorMessage || ["error", "aborted", "cancelled"].includes(String(message.stopReason))) {
236
+ if (inWindow)
237
+ participants.add(currentPerson.personId);
238
+ messages.push({
239
+ seq: row.seq, role: "assistant_outcome", timestamp: row.createdAt,
240
+ stopReason: message.stopReason, errorMessage: message.errorMessage,
241
+ });
242
+ }
243
+ const mediaUrls = record(message.openclawDelivery)?.mediaUrls;
244
+ if ((Array.isArray(visibleContent) && visibleContent.map(record).some(part => !["text", "toolCall", "thinking"].includes(String(part?.type)))) ||
245
+ (Array.isArray(mediaUrls) && mediaUrls.length > 0)) {
246
+ gap(`Non-text assistant output requires original-source review at event ${row.seq}`, sessionId);
247
+ if (inWindow)
248
+ participants.add(currentPerson.personId);
249
+ messages.push({
250
+ seq: row.seq, role: "assistant_media", timestamp: row.createdAt,
251
+ mediaUrls: Array.isArray(mediaUrls) ? mediaUrls.filter(url => typeof url === "string") : [],
252
+ });
253
+ }
254
+ if (!text || ["NO_REPLY", "HEARTBEAT_OK"].includes(text.trim()))
255
+ continue;
256
+ if (inWindow)
257
+ participants.add(currentPerson.personId);
258
+ messages.push({ seq: row.seq, role: "assistant", timestamp: row.createdAt, text });
259
+ }
260
+ else if (message.role === "toolResult" || message.role === "tool") {
261
+ if (inWindow)
262
+ participants.add(currentPerson.personId);
263
+ const parts = Array.isArray(message.content) ? message.content.map(record) : undefined;
264
+ const text = nonBlank(message.content) ?? (parts
265
+ ? parts.flatMap(part => part?.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n").trim()
266
+ : undefined);
267
+ if (!text || (parts && parts.some(part => part?.type !== "text"))) {
268
+ gap(`Non-text tool result requires original-source review at event ${row.seq}`, sessionId);
269
+ }
270
+ messages.push({
271
+ seq: row.seq, role: "tool_result", timestamp: row.createdAt,
272
+ toolName: message.toolName, toolCallId: message.toolCallId, isError: message.isError,
273
+ text: text || "Non-text tool result; inspect the native original",
274
+ });
275
+ }
276
+ }
277
+ // Export the complete relevant session, including context and later repair.
278
+ if (!participants.size)
279
+ return undefined;
280
+ const value = { ...session, window, messages, sourceRevision: jsonHash(snapshot.rows) };
281
+ const revision = jsonHash(value);
282
+ const file = privateJson(exportRoot, `${revision}.json`, value);
283
+ return { exported: { sessionId, revision, file }, participants };
284
+ }
285
+ function collectManifestAssertions(manifest, dossiers, people, kind) {
286
+ for (const person of manifest.roster) {
287
+ const dossier = dossiers.get(person.personId);
288
+ if (!dossier)
289
+ continue;
290
+ const unverified = !people.isDossierVerified(person.personId) || dossier.sections.some(s => isInteractionCategory(s.category) &&
291
+ s.claims.some(c => !c.reviewedAt || !c.scope || c.epistemicType === "inferred" ||
292
+ (c.epistemicType === "agent_assessment" && !c.expiresAt)));
293
+ if (unverified)
294
+ manifest.fullValidation = true;
295
+ if (kind === "nightly" ? unverified : person.sessionIds.length > 0 || unverified) {
296
+ manifest.assertions.push(...dossierAssertions(person.personId, dossier));
297
+ }
298
+ }
299
+ // A source outage may hide weekly activity. Validate all dossiers conservatively.
300
+ if (kind === "weekly" && manifest.sourceGaps.length) {
301
+ manifest.assertions = [...dossiers].flatMap(([personId, dossier]) => dossierAssertions(personId, dossier));
302
+ }
303
+ }
304
+ export function inventoryPeople(options) {
305
+ const now = options.now ?? Date.now(), { people, agentId, kind } = options;
306
+ const window = reviewWindow(now, options.timezone, kind, options.day);
307
+ const id = `${kind}:${window.localDay}`;
308
+ const { roster, dossiers, byIdentity } = loadRosterAndDossiers(people);
309
+ const manifest = {
310
+ id, agentId, kind, createdAt: new Date(now).toISOString(), window,
311
+ fullValidation: kind === "weekly", roster, assertions: [], sourceGaps: [], sessions: [],
312
+ };
313
+ const gap = (reason, sessionId) => {
314
+ const value = { reason, ...(sessionId ? { sessionId } : {}) };
315
+ manifest.sourceGaps.push({ ...value, id: jsonHash(value) });
316
+ };
64
317
  if (!byIdentity.size)
65
318
  gap("No authoritative local people identities; synchronize the host directory before claiming roster coverage");
66
319
  let db;
@@ -95,139 +348,12 @@ export function inventoryPeople(options) {
95
348
  gap("Missing or unsupported conversation type; relevance unknown", sessionId);
96
349
  continue;
97
350
  }
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)
351
+ const result = inventorySessionTranscript(session, snapshot, window, byIdentity, options.exportRoot, gap);
352
+ if (!result)
225
353
  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 });
354
+ manifest.sessions.push(result.exported);
229
355
  for (const person of manifest.roster)
230
- if (participants.has(person.personId))
356
+ if (result.participants.has(person.personId))
231
357
  person.sessionIds.push(sessionId);
232
358
  }
233
359
  }
@@ -239,22 +365,6 @@ export function inventoryPeople(options) {
239
365
  db.exec("ROLLBACK");
240
366
  db?.close();
241
367
  }
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
- }
368
+ collectManifestAssertions(manifest, dossiers, people, kind);
259
369
  return manifest;
260
370
  }
@@ -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;