@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,3 +1,4 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { Buffer } from "node:buffer";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { join } from "node:path";
@@ -6,7 +7,7 @@ import { resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-fou
6
7
  import { normalizeAgentIdStrict } from "openclaw/plugin-sdk/routing";
7
8
  import { Type } from "typebox";
8
9
  import { Value } from "typebox/value";
9
- import { backgroundWordCount, PEOPLE_BACKGROUND_MAX_WORDS, renderPeopleDossier } from "./people-background.js";
10
+ import { AGENT_LESSON_MAX_TTL_MS, backgroundWordCount, INTERACTION_DOSSIER_CATEGORIES, isInteractionCategory, PEOPLE_BACKGROUND_MAX_WORDS, renderPeopleDossier, } from "./people-background.js";
10
11
  import { agentStateDir } from "./agent-paths.js";
11
12
  const BASELINE_DOSSIER_CATEGORIES = [
12
13
  "role",
@@ -17,6 +18,9 @@ const BASELINE_DOSSIER_CATEGORIES = [
17
18
  "relationship",
18
19
  "openLoops",
19
20
  ];
21
+ const isoTimestampSchema = Type.String({
22
+ pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$",
23
+ });
20
24
  const evidenceRefSchema = Type.Object({
21
25
  source: Type.Union([
22
26
  Type.Literal("session"),
@@ -25,9 +29,7 @@ const evidenceRefSchema = Type.Object({
25
29
  Type.Literal("manual"),
26
30
  ]),
27
31
  locator: Type.String({ minLength: 1, maxLength: 1000 }),
28
- observedAt: Type.Optional(Type.String({
29
- pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$",
30
- })),
32
+ observedAt: Type.Optional(isoTimestampSchema),
31
33
  }, { additionalProperties: false });
32
34
  const claimSchema = Type.Object({
33
35
  statement: Type.String({ minLength: 1, maxLength: 2000 }),
@@ -40,8 +42,8 @@ const claimSchema = Type.Object({
40
42
  ]),
41
43
  confidence: Type.Optional(Type.Union([Type.Literal("low"), Type.Literal("medium"), Type.Literal("high")])),
42
44
  scope: Type.Optional(Type.String({ pattern: "\\S", maxLength: 200 })),
43
- reviewedAt: Type.Optional(Type.String({ pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$" })),
44
- expiresAt: Type.Optional(Type.String({ pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{1,9})?(?:Z|[+-]\\d{2}:\\d{2})$" })),
45
+ reviewedAt: Type.Optional(isoTimestampSchema),
46
+ expiresAt: Type.Optional(isoTimestampSchema),
45
47
  }, { additionalProperties: false });
46
48
  // Keep the broad schema for legacy dossier and history reads only.
47
49
  const PERSON_DOSSIER_SCHEMA = Type.Object({
@@ -55,7 +57,7 @@ const PERSON_DOSSIER_SCHEMA = Type.Object({
55
57
  export const PERSON_DOSSIER_WRITE_SCHEMA = Type.Object({
56
58
  ...PERSON_DOSSIER_SCHEMA.properties,
57
59
  sections: Type.Array(Type.Object({
58
- category: Type.Enum(["role", "relationship", "preferences", "workingStyle"]),
60
+ category: Type.Enum(["role", "relationship", ...INTERACTION_DOSSIER_CATEGORIES]),
59
61
  claims: Type.Array(Type.Object({
60
62
  ...claimSchema.properties,
61
63
  epistemicType: Type.Enum(["observed", "reported", "agent_assessment"]),
@@ -65,7 +67,7 @@ export const PERSON_DOSSIER_WRITE_SCHEMA = Type.Object({
65
67
  export class DossierConflictError extends Error {
66
68
  constructor() { super("Dossier or person changed during review; inspect again before retrying"); }
67
69
  }
68
- const MAX_DOSSIER_JSON_BYTES = 64 * 1024;
70
+ const MAX_DOSSIER_JSON_BYTES = DEFAULTS.people.dossierMaxBytes;
69
71
  function serializeDossier(dossier) {
70
72
  const json = JSON.stringify(dossier);
71
73
  if (Buffer.byteLength(json, "utf8") > MAX_DOSSIER_JSON_BYTES) {
@@ -147,6 +149,71 @@ function company(row) {
147
149
  updatedAt: row.updated_at,
148
150
  };
149
151
  }
152
+ function ensureDossierVerificationTable(db) {
153
+ db.exec(`CREATE TABLE IF NOT EXISTS person_dossier_verification (
154
+ person_id TEXT PRIMARY KEY REFERENCES people(id) ON DELETE CASCADE,
155
+ revision TEXT NOT NULL, verification TEXT NOT NULL, verified_at TEXT NOT NULL
156
+ ) STRICT`);
157
+ }
158
+ function insertDossierChangeRow(db, params) {
159
+ const id = randomUUID();
160
+ db.prepare(`
161
+ INSERT INTO person_dossier_changes
162
+ (id, person_id, action, before_dossier_json, after_dossier_json, reason, changed_at)
163
+ VALUES (?, ?, ?, ?, ?, ?, ?)
164
+ `)
165
+ .run(id, params.personId, params.action, params.beforeDossierJson, params.afterDossierJson, params.reason, params.changedAt);
166
+ return id;
167
+ }
168
+ function upsertDossierVerificationRow(db, personId, revision, verification, verifiedAt) {
169
+ db.prepare(`
170
+ INSERT INTO person_dossier_verification (person_id, revision, verification, verified_at)
171
+ VALUES (?, ?, ?, ?)
172
+ ON CONFLICT(person_id) DO UPDATE SET
173
+ revision = excluded.revision,
174
+ verification = excluded.verification,
175
+ verified_at = excluded.verified_at
176
+ `)
177
+ .run(personId, revision, verification, verifiedAt);
178
+ }
179
+ /**
180
+ * Records a dossier verification inside the caller's existing SQLite write transaction.
181
+ * Callers sharing `unblock-memory.sqlite` use this to commit dossier verifications
182
+ * atomically with learning-receipt completion without nesting BEGIN IMMEDIATE.
183
+ */
184
+ export function recordDossierVerificationInTransaction(db, personId, revision, verification, now = new Date().toISOString()) {
185
+ const normalizedVerification = required(verification, "verification");
186
+ ensureDossierVerificationTable(db);
187
+ const latestChange = db
188
+ .prepare("SELECT id, action, after_dossier_json FROM person_dossier_changes WHERE person_id = ? ORDER BY rowid DESC LIMIT 1")
189
+ .get(personId);
190
+ if ((latestChange?.id ?? null) !== revision)
191
+ throw new DossierConflictError();
192
+ const existing = db
193
+ .prepare("SELECT dossier_json FROM person_dossiers WHERE person_id = ?")
194
+ .get(personId);
195
+ if (!existing)
196
+ throw new DossierConflictError();
197
+ let verifiedRevision = revision;
198
+ if (verifiedRevision === null) {
199
+ // Pre-v4 dossiers have no change revision. Establish a baseline snapshot
200
+ // without rewriting their data or pretending the old write happened now.
201
+ verifiedRevision = insertDossierChangeRow(db, {
202
+ personId,
203
+ action: "replace",
204
+ beforeDossierJson: existing.dossier_json,
205
+ afterDossierJson: existing.dossier_json,
206
+ reason: "Legacy baseline after complete source validation",
207
+ changedAt: now,
208
+ });
209
+ }
210
+ else if (!latestChange ||
211
+ latestChange.action !== "replace" ||
212
+ latestChange.after_dossier_json !== existing.dossier_json) {
213
+ throw new DossierConflictError();
214
+ }
215
+ upsertDossierVerificationRow(db, personId, verifiedRevision, normalizedVerification, now);
216
+ }
150
217
  export class PeopleStore {
151
218
  #db;
152
219
  #maxOpenTodos;
@@ -384,56 +451,87 @@ export class PeopleStore {
384
451
  return this.getPerson(personId);
385
452
  }
386
453
  validateDossier(input) {
387
- const dossier = Value.Parse(PERSON_DOSSIER_WRITE_SCHEMA, input);
388
- this.#validateDossier(dossier);
389
- serializeDossier(dossier);
390
- return dossier;
454
+ return this.#parseAndSerializeDossier(input).dossier;
391
455
  }
392
456
  getDossierRevision(personId) {
393
- const row = this.#db.prepare("SELECT id FROM person_dossier_changes WHERE person_id = ? ORDER BY rowid DESC LIMIT 1")
457
+ const row = this.#db
458
+ .prepare("SELECT id FROM person_dossier_changes WHERE person_id = ? ORDER BY rowid DESC LIMIT 1")
394
459
  .get(personId);
395
460
  return row?.id ?? null;
396
461
  }
397
462
  isDossierVerified(personId) {
398
463
  this.#ensureDossierVerification();
399
- const row = this.#db.prepare("SELECT revision FROM person_dossier_verification WHERE person_id=?").get(personId);
400
- return !!row && row.revision === this.getDossierRevision(personId);
464
+ const row = this.#db
465
+ .prepare(`
466
+ SELECT 1
467
+ FROM person_dossiers d
468
+ JOIN person_dossier_verification v ON v.person_id = d.person_id
469
+ JOIN person_dossier_changes c ON c.person_id = d.person_id AND c.id = v.revision
470
+ WHERE d.person_id = ?
471
+ AND c.action = 'replace'
472
+ AND c.after_dossier_json = d.dossier_json
473
+ AND c.id = (
474
+ SELECT latest.id FROM person_dossier_changes latest
475
+ WHERE latest.person_id = d.person_id
476
+ ORDER BY latest.rowid DESC
477
+ LIMIT 1
478
+ )
479
+ `)
480
+ .get(personId);
481
+ return row !== undefined;
482
+ }
483
+ getVerifiedDossier(personId) {
484
+ this.#ensureDossierVerification();
485
+ const row = this.#db
486
+ .prepare(`
487
+ SELECT d.dossier_json, d.reviewed_at
488
+ FROM person_dossiers d
489
+ JOIN person_dossier_verification v ON v.person_id = d.person_id
490
+ JOIN person_dossier_changes c ON c.person_id = d.person_id AND c.id = v.revision
491
+ WHERE d.person_id = ?
492
+ AND c.action = 'replace'
493
+ AND c.after_dossier_json = d.dossier_json
494
+ AND c.id = (
495
+ SELECT latest.id FROM person_dossier_changes latest
496
+ WHERE latest.person_id = d.person_id
497
+ ORDER BY latest.rowid DESC
498
+ LIMIT 1
499
+ )
500
+ `)
501
+ .get(personId);
502
+ return row
503
+ ? {
504
+ dossier: parseDossierJson(row.dossier_json),
505
+ reviewedAt: row.reviewed_at,
506
+ }
507
+ : undefined;
401
508
  }
402
509
  recordDossierVerification(personId, revision, verification) {
510
+ const normalizedVerification = required(verification, "verification");
403
511
  this.#ensureDossierVerification();
512
+ const now = new Date().toISOString();
404
513
  immediateTransaction(this.#db, () => {
405
- if (this.getDossierRevision(personId) !== revision)
406
- throw new DossierConflictError();
407
- if (revision === null) {
408
- const existing = this.#db.prepare("SELECT dossier_json FROM person_dossiers WHERE person_id=?").get(personId);
409
- if (!existing)
410
- throw new DossierConflictError();
411
- // Pre-v4 dossiers have no change revision. Establish a baseline snapshot
412
- // without rewriting their data or pretending the old write happened now.
413
- revision = randomUUID();
414
- this.#db.prepare(`INSERT INTO person_dossier_changes
415
- (id,person_id,action,before_dossier_json,after_dossier_json,reason,changed_at)
416
- VALUES (?,?,'replace',?,?,?,?)`).run(revision, personId, existing.dossier_json, existing.dossier_json, "Legacy baseline after complete source validation", new Date().toISOString());
417
- }
418
- this.#db.prepare(`INSERT INTO person_dossier_verification VALUES (?,?,?,?) ON CONFLICT(person_id) DO UPDATE SET
419
- revision=excluded.revision,verification=excluded.verification,verified_at=excluded.verified_at`)
420
- .run(personId, revision, verification, new Date().toISOString());
514
+ recordDossierVerificationInTransaction(this.#db, personId, revision, normalizedVerification, now);
421
515
  });
422
516
  }
423
517
  #ensureDossierVerification() {
424
518
  if (this.#dossierVerificationReady)
425
519
  return;
426
- this.#db.exec(`CREATE TABLE IF NOT EXISTS person_dossier_verification (
427
- person_id TEXT PRIMARY KEY REFERENCES people(id) ON DELETE CASCADE,
428
- revision TEXT NOT NULL, verification TEXT NOT NULL, verified_at TEXT NOT NULL
429
- ) STRICT`);
520
+ ensureDossierVerificationTable(this.#db);
430
521
  this.#dossierVerificationReady = true;
431
522
  }
432
- /** Returns undefined when the person does not exist. */
433
- replaceDossier(personId, reasonInput, input, expectedRevision) {
434
- const dossier = this.validateDossier(input);
435
- const dossierJson = serializeDossier(dossier);
523
+ #insertDossierChange(params) {
524
+ return insertDossierChangeRow(this.#db, params);
525
+ }
526
+ #upsertDossierVerification(personId, revision, verification, verifiedAt) {
527
+ upsertDossierVerificationRow(this.#db, personId, revision, verification, verifiedAt);
528
+ }
529
+ #writeDossier(personId, reasonInput, input, expectedRevision, verificationInput) {
530
+ const { dossier, dossierJson } = this.#parseAndSerializeDossier(input);
436
531
  const reason = dossierReason(reasonInput);
532
+ const verification = verificationInput === undefined ? undefined : required(verificationInput, "verification");
533
+ if (verification !== undefined)
534
+ this.#ensureDossierVerification();
437
535
  const reviewedAt = new Date().toISOString();
438
536
  return immediateTransaction(this.#db, () => {
439
537
  const target = this.#db.prepare("SELECT id, status FROM people WHERE id = ?").get(personId);
@@ -458,20 +556,35 @@ export class PeopleStore {
458
556
  reviewed_at = excluded.reviewed_at
459
557
  `)
460
558
  .run(personId, dossierJson, dossier.blurb, reviewedAt);
461
- this.#db
462
- .prepare(`
463
- INSERT INTO person_dossier_changes
464
- (id, person_id, action, before_dossier_json, after_dossier_json, reason, changed_at)
465
- VALUES (?, ?, 'replace', ?, ?, ?, ?)
466
- `)
467
- .run(randomUUID(), personId, existing?.dossier_json ?? null, dossierJson, reason, reviewedAt);
468
- return dossier;
559
+ const changeId = this.#insertDossierChange({
560
+ personId,
561
+ action: "replace",
562
+ beforeDossierJson: existing?.dossier_json ?? null,
563
+ afterDossierJson: dossierJson,
564
+ reason,
565
+ changedAt: reviewedAt,
566
+ });
567
+ if (verification !== undefined) {
568
+ this.#upsertDossierVerification(personId, changeId, verification, reviewedAt);
569
+ }
570
+ return { dossier, changeId };
469
571
  });
470
572
  }
471
- deleteDossier(personId, reasonInput) {
573
+ /** Returns undefined when the person does not exist. */
574
+ replaceDossier(personId, reasonInput, input, expectedRevision) {
575
+ return this.#writeDossier(personId, reasonInput, input, expectedRevision)?.dossier;
576
+ }
577
+ /** Atomically replaces a dossier, records its history revision, and binds verification to that revision. */
578
+ replaceVerifiedDossier(personId, reasonInput, input, verificationInput, expectedRevision) {
579
+ return this.#writeDossier(personId, reasonInput, input, expectedRevision, verificationInput);
580
+ }
581
+ deleteDossier(personId, reasonInput, expectedRevision) {
472
582
  const reason = dossierReason(reasonInput);
473
583
  const changedAt = new Date().toISOString();
474
584
  return immediateTransaction(this.#db, () => {
585
+ if (expectedRevision !== undefined && this.getDossierRevision(personId) !== expectedRevision) {
586
+ throw new DossierConflictError();
587
+ }
475
588
  const existing = this.#db
476
589
  .prepare("SELECT dossier_json FROM person_dossiers WHERE person_id = ?")
477
590
  .get(personId);
@@ -480,13 +593,14 @@ export class PeopleStore {
480
593
  }
481
594
  parseDossierJson(existing.dossier_json);
482
595
  this.#db.prepare("DELETE FROM person_dossiers WHERE person_id = ?").run(personId);
483
- this.#db
484
- .prepare(`
485
- INSERT INTO person_dossier_changes
486
- (id, person_id, action, before_dossier_json, after_dossier_json, reason, changed_at)
487
- VALUES (?, ?, 'delete', ?, NULL, ?, ?)
488
- `)
489
- .run(randomUUID(), personId, existing.dossier_json, reason, changedAt);
596
+ this.#insertDossierChange({
597
+ personId,
598
+ action: "delete",
599
+ beforeDossierJson: existing.dossier_json,
600
+ afterDossierJson: null,
601
+ reason,
602
+ changedAt,
603
+ });
490
604
  return true;
491
605
  });
492
606
  }
@@ -738,7 +852,12 @@ export class PeopleStore {
738
852
  `)
739
853
  .get(provider, accountScope, externalId);
740
854
  }
741
- #validateDossier(dossier) {
855
+ #parseAndSerializeDossier(input) {
856
+ const dossier = Value.Parse(PERSON_DOSSIER_WRITE_SCHEMA, input);
857
+ this.#checkDossierRules(dossier);
858
+ return { dossier, dossierJson: serializeDossier(dossier) };
859
+ }
860
+ #checkDossierRules(dossier) {
742
861
  if (dossier.blurb.length > this.#maxBlurbChars) {
743
862
  throw new Error(`dossier blurb must not exceed ${this.#maxBlurbChars} characters`);
744
863
  }
@@ -749,24 +868,29 @@ export class PeopleStore {
749
868
  if (backgroundWordCount(dossier.blurb) > PEOPLE_BACKGROUND_MAX_WORDS) {
750
869
  throw new Error(`dossier blurb must not exceed ${PEOPLE_BACKGROUND_MAX_WORDS} words`);
751
870
  }
752
- for (const section of dossier.sections)
871
+ for (const section of dossier.sections) {
872
+ const interaction = isInteractionCategory(section.category);
753
873
  for (const claim of section.claims) {
754
- if (["preferences", "workingStyle"].includes(section.category) && (!claim.reviewedAt || !claim.scope)) {
874
+ if (interaction && (!claim.reviewedAt || !claim.scope)) {
755
875
  throw new Error("Interaction claims require explicit scope and reviewedAt after source verification");
756
876
  }
757
- for (const date of [claim.reviewedAt, claim.expiresAt]) {
758
- if (date !== undefined && !Number.isFinite(Date.parse(date)))
759
- throw new Error("Invalid claim review/expiry date");
877
+ const reviewedAtMs = claim.reviewedAt === undefined ? undefined : Date.parse(claim.reviewedAt);
878
+ const expiresAtMs = claim.expiresAt === undefined ? undefined : Date.parse(claim.expiresAt);
879
+ if ((reviewedAtMs !== undefined && !Number.isFinite(reviewedAtMs)) ||
880
+ (expiresAtMs !== undefined && !Number.isFinite(expiresAtMs))) {
881
+ throw new Error("Invalid claim review/expiry date");
760
882
  }
761
883
  if (claim.epistemicType === "agent_assessment") {
762
- if (!["preferences", "workingStyle"].includes(section.category) || !claim.reviewedAt || !claim.expiresAt) {
884
+ if (!interaction || reviewedAtMs === undefined || expiresAtMs === undefined) {
763
885
  throw new Error("Agent lessons require a preference/workingStyle section, reviewedAt and expiresAt");
764
886
  }
765
- const lifetime = Date.parse(claim.expiresAt) - Date.parse(claim.reviewedAt);
766
- if (lifetime <= 0 || lifetime > 30 * 86400000)
887
+ const lifetime = expiresAtMs - reviewedAtMs;
888
+ if (lifetime <= 0 || lifetime > AGENT_LESSON_MAX_TTL_MS) {
767
889
  throw new Error("Agent lessons must expire within 30 days of review");
890
+ }
768
891
  }
769
892
  }
893
+ }
770
894
  if (renderPeopleDossier(dossier).length > this.#maxBlurbChars) {
771
895
  throw new Error(`Combined people context must not exceed ${this.#maxBlurbChars} characters`);
772
896
  }
@@ -1,9 +1,10 @@
1
+ import { DEFAULTS } from "./defaults.js";
1
2
  import { jsonResult } from "openclaw/plugin-sdk/agent-runtime";
2
3
  import { Type } from "typebox";
3
4
  import { Value } from "typebox/value";
4
5
  import { renderPeopleWhisper } from "./people-hooks.js";
5
6
  import { renderPeopleDossier } from "./people-background.js";
6
- import { DossierConflictError, PERSON_DOSSIER_WRITE_SCHEMA } from "./people-store.js";
7
+ import { DossierConflictError, PERSON_DOSSIER_WRITE_SCHEMA, } from "./people-store.js";
7
8
  import { getContext, runtimeConfig } from "./tool-context.js";
8
9
  import { reviewPersonDossier } from "./people-dossier-review.js";
9
10
  import { createOpenClawSlackDirectory, syncSlackDirectory, } from "./slack-directory.js";
@@ -83,12 +84,13 @@ const updateParameters = Type.Union([
83
84
  reason: Type.String({ pattern: "\\S", maxLength: 500 }),
84
85
  agentName: Type.Optional(Type.String({ pattern: "\\S", maxLength: 100 })),
85
86
  manualVerification: Type.Optional(Type.String({ pattern: "\\S", maxLength: 400,
86
- description: "Source-specific attestation that you checked every saved claim, its scope and any newer corrections. Distinguish explicit preferences from provisional agent lessons. Skips TypeSafe; recorded as manual. Never use as a blind retry switch." })),
87
+ description: "Source-specific attestation that you checked every saved claim, its scope and any newer corrections. Distinguish explicit preferences from provisional agent lessons. Skips automated review; recorded as manual. Never use as a blind retry switch." })),
87
88
  }, { additionalProperties: false }),
88
89
  Type.Object({
89
90
  action: Type.Literal("delete_dossier"),
90
91
  personId: nonEmpty,
91
92
  reason: nonEmpty,
93
+ expectedRevision: Type.Optional(Type.Union([nonEmpty, Type.Null()])),
92
94
  }, { additionalProperties: false }),
93
95
  Type.Object({
94
96
  action: Type.Literal("set_company"),
@@ -135,6 +137,65 @@ function personView(stores, agentId, selector, maxChars) {
135
137
  contribution,
136
138
  };
137
139
  }
140
+ function nextPageOffset(offset, count, limit) {
141
+ return count === limit ? offset + count : null;
142
+ }
143
+ async function handleReplaceDossier(params) {
144
+ const { store, config, runtime, active, input, signal } = params;
145
+ const person = store.getPerson(input.personId);
146
+ if (!person || person.status !== "active")
147
+ return jsonResult({ status: "not_found" });
148
+ const proposed = store.validateDossier(input.dossier);
149
+ const revision = store.getDossierRevision(input.personId);
150
+ if (signal?.aborted) {
151
+ return jsonResult({
152
+ status: "review_unavailable",
153
+ needsReview: true,
154
+ reason: "Cancelled; no dossier written",
155
+ });
156
+ }
157
+ const review = input.manualVerification
158
+ ? { status: "manual", needsReview: false, note: input.manualVerification }
159
+ : await reviewPersonDossier({
160
+ config,
161
+ runtime,
162
+ active,
163
+ person,
164
+ dossier: proposed,
165
+ agentName: input.agentName,
166
+ signal,
167
+ });
168
+ if (review.needsReview || signal?.aborted) {
169
+ return jsonResult({
170
+ status: review.status === "ok" && !signal?.aborted ? "needs_review" : "review_unavailable",
171
+ needsReview: true,
172
+ saved: false,
173
+ review,
174
+ });
175
+ }
176
+ const audit = review.status === "manual"
177
+ ? `Manual verification: ${review.note}`
178
+ : "Decision model review passed for every dossier assertion (person-interaction-v1)";
179
+ try {
180
+ const saved = store.replaceVerifiedDossier(input.personId, `${input.reason}\n${audit}`, proposed, audit, revision);
181
+ if (!saved)
182
+ return jsonResult({ status: "not_found" });
183
+ return jsonResult({
184
+ status: "ok",
185
+ saved: true,
186
+ changeId: saved.changeId,
187
+ verification: review.status === "manual" ? "manual" : "decision",
188
+ dossier: saved.dossier,
189
+ review,
190
+ });
191
+ }
192
+ catch (error) {
193
+ if (error instanceof DossierConflictError) {
194
+ return jsonResult({ status: "conflict", saved: false, reason: error.message });
195
+ }
196
+ throw error;
197
+ }
198
+ }
138
199
  function createInspectTool(stores, config, ctx) {
139
200
  const active = getContext(ctx);
140
201
  if (!active)
@@ -150,42 +211,45 @@ function createInspectTool(stores, config, ctx) {
150
211
  return jsonResult(personView(stores, active.agentId, input, config.whisperer.maxChars));
151
212
  }
152
213
  const store = stores.get(active.agentId);
153
- if (input.view === "people") {
154
- const limit = input.limit ?? 50;
155
- const offset = input.offset ?? 0;
156
- const people = store.listActivePeople(limit, offset, input.includeInactive ?? false).map((person) => {
157
- const dossierReviewedAt = store.getDossierReviewedAt(person.id);
158
- return {
159
- person,
160
- identities: store.listIdentities(person.id),
161
- hasDossier: dossierReviewedAt !== undefined,
162
- dossierReviewedAt: dossierReviewedAt ?? null,
163
- };
164
- });
165
- return jsonResult({
166
- status: "ok",
167
- people,
168
- nextOffset: people.length === limit ? offset + people.length : null,
169
- });
170
- }
171
- if (input.view === "dossier_changes") {
172
- const limit = input.limit ?? 20;
173
- const offset = input.offset ?? 0;
174
- const changes = store.listDossierChanges(input.personId, limit, offset);
175
- return jsonResult({
176
- status: "ok",
177
- changes,
178
- nextOffset: changes.length === limit ? offset + changes.length : null,
179
- });
180
- }
181
- if (input.view === "dossier_change") {
182
- const change = store.getDossierChange(input.personId, input.changeId);
183
- return jsonResult(change ? { status: "ok", change } : { status: "not_found" });
214
+ switch (input.view) {
215
+ case "people": {
216
+ const limit = input.limit ?? 50;
217
+ const offset = input.offset ?? 0;
218
+ const people = store.listActivePeople(limit, offset, input.includeInactive ?? false).map((person) => {
219
+ const dossierReviewedAt = store.getDossierReviewedAt(person.id);
220
+ return {
221
+ person,
222
+ identities: store.listIdentities(person.id),
223
+ hasDossier: dossierReviewedAt !== undefined,
224
+ dossierReviewedAt: dossierReviewedAt ?? null,
225
+ };
226
+ });
227
+ return jsonResult({
228
+ status: "ok",
229
+ people,
230
+ nextOffset: nextPageOffset(offset, people.length, limit),
231
+ });
232
+ }
233
+ case "dossier_changes": {
234
+ const limit = input.limit ?? 20;
235
+ const offset = input.offset ?? 0;
236
+ const changes = store.listDossierChanges(input.personId, limit, offset);
237
+ return jsonResult({
238
+ status: "ok",
239
+ changes,
240
+ nextOffset: nextPageOffset(offset, changes.length, limit),
241
+ });
242
+ }
243
+ case "dossier_change": {
244
+ const change = store.getDossierChange(input.personId, input.changeId);
245
+ return jsonResult(change ? { status: "ok", change } : { status: "not_found" });
246
+ }
247
+ case "todos":
248
+ return jsonResult({
249
+ status: "ok",
250
+ todos: store.listTodos(input.limit ?? 20),
251
+ });
184
252
  }
185
- return jsonResult({
186
- status: "ok",
187
- todos: store.listTodos(input.limit ?? 20),
188
- });
189
253
  },
190
254
  };
191
255
  }
@@ -196,70 +260,51 @@ function createUpdateTool(stores, config, runtime, ctx) {
196
260
  return {
197
261
  name: "memory_people_update",
198
262
  label: "Update People Memory",
199
- description: "Curate ongoing interaction feedback during nightly dreaming for the exact person. Replace a complete dossier: identity blurb <=70 words; role/relationship, preferences and workingStyle sections. Cite original evidence for every claim; preserve verified existing claims and their scope. Agent-assessed lessons require reviewedAt and expiresAt within 30 days. Automatic review checks every statement; use source-specific manualVerification only after checking original sources yourself. Delete contradicted/stale claims with a reason. Context refreshes on the next user turn.",
263
+ description: `Curate ongoing interaction feedback during nightly dreaming for the exact person. Replace a complete dossier: identity blurb <=${DEFAULTS.people.backgroundMaxWords} words; role/relationship, preferences and workingStyle sections. Cite original evidence for every claim; preserve verified existing claims and their scope. Agent-assessed lessons require reviewedAt and expiresAt within 30 days. Automatic review checks every statement; use source-specific manualVerification only after checking original sources yourself. Delete contradicted/stale claims with a reason. Context refreshes on the next user turn.`,
200
264
  parameters: updateParameters,
201
265
  async execute(_toolCallId, raw, signal) {
202
266
  const input = Value.Parse(updateParameters, raw);
203
267
  const store = stores.get(active.agentId);
204
- if (input.action === "set_injection") {
205
- const person = store.setInjection(input.personId, input.enabled);
206
- return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
207
- }
208
- if (input.action === "replace_dossier") {
209
- const person = store.getPerson(input.personId);
210
- if (!person || person.status !== "active")
211
- return jsonResult({ status: "not_found" });
212
- const proposed = store.validateDossier(input.dossier);
213
- const revision = store.getDossierRevision(input.personId);
214
- if (signal?.aborted)
215
- return jsonResult({ status: "review_unavailable", needsReview: true, reason: "Cancelled; no dossier written" });
216
- const review = input.manualVerification
217
- ? { status: "manual", needsReview: false, note: input.manualVerification }
218
- : await reviewPersonDossier({ config, runtime, active, person, dossier: proposed, agentName: input.agentName, signal });
219
- if (review.needsReview || signal?.aborted) {
220
- return jsonResult({ status: review.status === "ok" && !signal?.aborted ? "needs_review" : "review_unavailable",
221
- needsReview: true, saved: false, review });
268
+ switch (input.action) {
269
+ case "set_injection": {
270
+ const person = store.setInjection(input.personId, input.enabled);
271
+ return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
222
272
  }
223
- const audit = review.status === "manual"
224
- ? `Manual verification: ${review.note}`
225
- : "TypeSafe review passed for every dossier assertion (person-interaction-v1)";
226
- try {
227
- const dossier = store.replaceDossier(input.personId, `${input.reason}\n${audit}`, proposed, revision);
228
- if (!dossier)
229
- return jsonResult({ status: "not_found" });
230
- const changeId = store.getDossierRevision(input.personId);
231
- store.recordDossierVerification(input.personId, changeId, audit);
232
- return jsonResult({ status: "ok", saved: true, changeId, verification: review.status === "manual" ? "manual" : "typesafe", dossier, review });
273
+ case "replace_dossier":
274
+ return handleReplaceDossier({ store, config, runtime, active, input, signal });
275
+ case "delete_dossier":
276
+ try {
277
+ return jsonResult(store.deleteDossier(input.personId, input.reason, input.expectedRevision)
278
+ ? { status: "ok" }
279
+ : { status: "not_found" });
280
+ }
281
+ catch (error) {
282
+ if (error instanceof DossierConflictError) {
283
+ return jsonResult({ status: "conflict", saved: false, reason: error.message });
284
+ }
285
+ throw error;
286
+ }
287
+ case "set_company": {
288
+ const company = store.setCompany(input.personId, {
289
+ name: input.companyName,
290
+ primaryDomain: input.primaryDomain,
291
+ });
292
+ const person = store.getPerson(input.personId);
293
+ return jsonResult(company && person ? { status: "ok", company, person } : { status: "not_found" });
233
294
  }
234
- catch (error) {
235
- if (error instanceof DossierConflictError)
236
- return jsonResult({ status: "conflict", saved: false, reason: error.message });
237
- throw error;
295
+ case "resolve_todo": {
296
+ const todo = store.resolveTodoByKey(input.deduplicationKey, input.note);
297
+ return jsonResult(todo ? { status: "ok", todo } : { status: "not_found" });
298
+ }
299
+ case "restore_person": {
300
+ const person = store.restorePerson(input.personId);
301
+ return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
302
+ }
303
+ case "soft_delete_person": {
304
+ const person = store.softDeletePerson(input.personId);
305
+ return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
238
306
  }
239
307
  }
240
- if (input.action === "delete_dossier") {
241
- return jsonResult(store.deleteDossier(input.personId, input.reason)
242
- ? { status: "ok" }
243
- : { status: "not_found" });
244
- }
245
- if (input.action === "set_company") {
246
- const company = store.setCompany(input.personId, {
247
- name: input.companyName,
248
- primaryDomain: input.primaryDomain,
249
- });
250
- const person = store.getPerson(input.personId);
251
- return jsonResult(company && person ? { status: "ok", company, person } : { status: "not_found" });
252
- }
253
- if (input.action === "resolve_todo") {
254
- const todo = store.resolveTodoByKey(input.deduplicationKey, input.note);
255
- return jsonResult(todo ? { status: "ok", todo } : { status: "not_found" });
256
- }
257
- if (input.action === "restore_person") {
258
- const person = store.restorePerson(input.personId);
259
- return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
260
- }
261
- const person = store.softDeletePerson(input.personId);
262
- return jsonResult(person ? { status: "ok", person } : { status: "not_found" });
263
308
  },
264
309
  };
265
310
  }