@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,6 +1,8 @@
1
+ import type { DatabaseSync } from "node:sqlite";
1
2
  import { Type, type Static } from "typebox";
2
3
  import type { ReviewManifest } from "./people-learning-inventory.js";
3
4
  export declare const LEARNING_RECEIPT_SCHEMA: Type.TObject<{
5
+ manifestRevision: Type.TOptional<Type.TString>;
4
6
  peopleReviews: Type.TArray<Type.TObject<{
5
7
  reason: Type.TString;
6
8
  sourceRefs: Type.TArray<Type.TString>;
@@ -35,6 +37,15 @@ export declare const LEARNING_RECEIPT_SCHEMA: Type.TObject<{
35
37
  executionFollowups: Type.TArray<Type.TString>;
36
38
  }>;
37
39
  export type LearningReceipt = Static<typeof LEARNING_RECEIPT_SCHEMA>;
40
+ export type RecordAnalysisOptions = {
41
+ expectedManifestRevision?: string;
42
+ startedAt?: number;
43
+ recordedAt?: number;
44
+ generation?: number;
45
+ sequence?: number;
46
+ instanceId?: string;
47
+ };
48
+ export declare function manifestRevision(manifest: ReviewManifest): string;
38
49
  export declare function verifyLearningCoverage(manifest: ReviewManifest, receipt: LearningReceipt, now?: number): {
39
50
  status: "partial" | "complete" | "invalid";
40
51
  expectedPeople: number;
@@ -49,11 +60,16 @@ export declare class PeopleLearningStore {
49
60
  readonly agentId: string;
50
61
  constructor(path: string, agentId: string);
51
62
  close(): void;
52
- recordAnalysis(id: string, status: "complete" | "unresolved", result: unknown, basis: string): void;
63
+ recordAnalysis(id: string, status: "complete" | "unresolved", result: unknown, basis: string, options?: RecordAnalysisOptions): {
64
+ recorded: boolean;
65
+ reason?: "manifest_changed" | "superseded";
66
+ };
53
67
  analysis(id: string): Record<string, import("node:sqlite").SQLOutputValue> | undefined;
54
- begin(manifest: ReviewManifest): {
68
+ begin(manifest: ReviewManifest, beforeCommit?: (manifest: ReviewManifest) => void): {
55
69
  manifest: ReviewManifest;
70
+ manifestRevision: string;
56
71
  receipt: {
72
+ manifestRevision?: string | undefined;
57
73
  analysis: {
58
74
  status: "complete" | "unresolved" | "not_approved";
59
75
  reason: string;
@@ -93,7 +109,9 @@ export declare class PeopleLearningStore {
93
109
  planMissedWindows(manifest: ReviewManifest): void;
94
110
  get(id: string): {
95
111
  manifest: ReviewManifest;
112
+ manifestRevision: string;
96
113
  receipt: {
114
+ manifestRevision?: string | undefined;
97
115
  analysis: {
98
116
  status: "complete" | "unresolved" | "not_approved";
99
117
  reason: string;
@@ -135,12 +153,18 @@ export declare class PeopleLearningStore {
135
153
  status: string;
136
154
  coverage: unknown;
137
155
  }[];
138
- checkpoint(id: string, input: unknown, now?: number, checkSaves?: (receipt: LearningReceipt) => string[], finalize?: (receiptId: string) => void): {
156
+ checkpoint(id: string, input: unknown, now?: number, checkSaves?: (receipt: LearningReceipt, manifest: ReviewManifest) => string[], finalize?: (receiptId: string, db: DatabaseSync, manifest: ReviewManifest) => void, expectedManifestRevision?: string, options?: {
157
+ collectAssertions?: (manifest: ReviewManifest) => ReviewManifest["assertions"];
158
+ beforeManifestCommit?: (manifest: ReviewManifest) => void;
159
+ shouldFinalize?: (manifest: ReviewManifest) => boolean;
160
+ }): {
139
161
  backlog: {
140
162
  id: string;
141
163
  status: string;
142
164
  coverage: unknown;
143
165
  }[];
166
+ receiptId: string;
167
+ manifestRevision: string;
144
168
  status: "partial" | "complete" | "invalid";
145
169
  expectedPeople: number;
146
170
  expectedSessions: number;
@@ -148,6 +172,5 @@ export declare class PeopleLearningStore {
148
172
  missing: string[];
149
173
  errors: string[];
150
174
  unresolved: string[];
151
- receiptId: string;
152
175
  };
153
176
  }
@@ -6,6 +6,7 @@ import { reviewWindow, shiftDate } from "./people-learning-time.js";
6
6
  const text = Type.String({ pattern: "\\S" });
7
7
  const verification = { reason: text, sourceRefs: Type.Array(text), reviewedAt: text };
8
8
  export const LEARNING_RECEIPT_SCHEMA = Type.Object({
9
+ manifestRevision: Type.Optional(text),
9
10
  peopleReviews: Type.Array(Type.Object({ personId: text, status: Type.Enum(["reviewed", "no_interactions", "unresolved"]),
10
11
  sessionIds: Type.Array(text), ...verification }, { additionalProperties: false })),
11
12
  assertionReviews: Type.Array(Type.Object({ assertionId: text,
@@ -17,12 +18,19 @@ export const LEARNING_RECEIPT_SCHEMA = Type.Object({
17
18
  changes: Type.Array(Type.Object({ personId: text, changeId: text }, { additionalProperties: false })),
18
19
  executionFollowups: Type.Array(text),
19
20
  }, { additionalProperties: false });
21
+ export function manifestRevision(manifest) {
22
+ return jsonHash(manifest);
23
+ }
20
24
  export function verifyLearningCoverage(manifest, receipt, now = Date.now()) {
21
25
  const missing = [], errors = [], unresolved = [];
22
- const unresolvedGaps = manifest.sourceGaps.filter(g => !receipt.sourceGapReviews.some(r => r.sourceGapId === g.id && r.status === "resolved"));
26
+ const manifestCreatedAt = Date.parse(manifest.createdAt);
27
+ const currentRevision = manifestRevision(manifest);
28
+ if (receipt.manifestRevision !== undefined && receipt.manifestRevision !== currentRevision) {
29
+ errors.push(`Stale manifest revision: expected ${currentRevision}, got ${receipt.manifestRevision}`);
30
+ }
23
31
  if (manifest.inventoryPending)
24
32
  missing.push("inventory");
25
- const map = (items, key, known) => {
33
+ const indexBy = (items, key, known) => {
26
34
  const result = new Map();
27
35
  for (const item of items) {
28
36
  const id = key(item);
@@ -37,10 +45,22 @@ export function verifyLearningCoverage(manifest, receipt, now = Date.now()) {
37
45
  const verified = (value, id) => {
38
46
  const date = Date.parse(value.reviewedAt);
39
47
  if (!value.reason.trim() || !value.sourceRefs.length || value.sourceRefs.some(s => !s.trim()) ||
40
- !Number.isFinite(date) || date < Date.parse(manifest.createdAt) || date > now)
48
+ !Number.isFinite(date) || date < manifestCreatedAt || date > now) {
41
49
  errors.push(`Missing actual source verification: ${id}`);
50
+ }
42
51
  };
43
- const people = map(receipt.peopleReviews, r => r.personId, new Set(manifest.roster.map(p => p.personId)));
52
+ const gaps = indexBy(receipt.sourceGapReviews, r => r.sourceGapId, new Set(manifest.sourceGaps.map(g => g.id)));
53
+ let hasUnresolvedGaps = false;
54
+ for (const gap of manifest.sourceGaps) {
55
+ const review = gaps.get(gap.id);
56
+ if (review?.status === "resolved")
57
+ verified(review, gap.id);
58
+ else {
59
+ hasUnresolvedGaps = true;
60
+ unresolved.push(`source:${gap.id}`);
61
+ }
62
+ }
63
+ const people = indexBy(receipt.peopleReviews, r => r.personId, new Set(manifest.roster.map(p => p.personId)));
44
64
  if (manifest.kind === "nightly")
45
65
  for (const person of manifest.roster) {
46
66
  const review = people.get(person.personId);
@@ -55,19 +75,21 @@ export function verifyLearningCoverage(manifest, receipt, now = Date.now()) {
55
75
  if (review.status === "no_interactions") {
56
76
  if (person.sessionIds.length)
57
77
  errors.push(`Skipped interactions: ${person.personId}`);
58
- if (unresolvedGaps.length)
78
+ if (hasUnresolvedGaps)
59
79
  unresolved.push(`activity-unknown:${person.personId}`);
60
80
  }
61
81
  else {
62
82
  verified(review, person.personId);
83
+ const reviewedSessions = new Set(review.sessionIds);
84
+ const expectedSessions = new Set(person.sessionIds);
63
85
  for (const id of person.sessionIds)
64
- if (!review.sessionIds.includes(id))
86
+ if (!reviewedSessions.has(id))
65
87
  missing.push(`session:${person.personId}:${id}`);
66
- if (review.sessionIds.some(id => !person.sessionIds.includes(id)))
88
+ if (review.sessionIds.some(id => !expectedSessions.has(id)))
67
89
  errors.push(`Wrong session attribution: ${person.personId}`);
68
90
  }
69
91
  }
70
- const assertions = map(receipt.assertionReviews, r => r.assertionId, new Set(manifest.assertions.map(a => a.id)));
92
+ const assertions = indexBy(receipt.assertionReviews, r => r.assertionId, new Set(manifest.assertions.map(a => a.id)));
71
93
  for (const assertion of manifest.assertions) {
72
94
  const review = assertions.get(assertion.id);
73
95
  if (!review) {
@@ -80,22 +102,21 @@ export function verifyLearningCoverage(manifest, receipt, now = Date.now()) {
80
102
  }
81
103
  verified(review, assertion.id);
82
104
  const corrected = Date.parse(review.correctionsCheckedAt ?? "");
83
- if (!Number.isFinite(corrected) || corrected < Date.parse(manifest.createdAt) || corrected > now)
105
+ if (!Number.isFinite(corrected) || corrected < manifestCreatedAt || corrected > now) {
84
106
  errors.push(`Missing newer-correction research: ${assertion.id}`);
85
- }
86
- const gaps = map(receipt.sourceGapReviews, r => r.sourceGapId, new Set(manifest.sourceGaps.map(g => g.id)));
87
- for (const gap of manifest.sourceGaps) {
88
- const review = gaps.get(gap.id);
89
- if (review?.status === "resolved")
90
- verified(review, gap.id);
91
- else
92
- unresolved.push(`source:${gap.id}`);
107
+ }
93
108
  }
94
109
  if (receipt.analysis.status === "unresolved")
95
110
  unresolved.push("analysis");
96
- return { status: errors.length ? "invalid" : missing.length || unresolved.length ? "partial" : "complete",
111
+ return {
112
+ status: errors.length ? "invalid" : missing.length || unresolved.length ? "partial" : "complete",
97
113
  expectedPeople: manifest.kind === "nightly" ? manifest.roster.length : 0,
98
- expectedSessions: manifest.sessions.length, expectedAssertions: manifest.assertions.length, missing, errors, unresolved };
114
+ expectedSessions: manifest.sessions.length,
115
+ expectedAssertions: manifest.assertions.length,
116
+ missing,
117
+ errors,
118
+ unresolved,
119
+ };
99
120
  }
100
121
  export class PeopleLearningStore {
101
122
  agentId;
@@ -107,7 +128,8 @@ export class PeopleLearningStore {
107
128
  singleton INTEGER PRIMARY KEY CHECK(singleton=1), agent_id TEXT NOT NULL
108
129
  ) STRICT;
109
130
  CREATE TABLE IF NOT EXISTS people_learning_runs (
110
- id TEXT PRIMARY KEY, manifest TEXT NOT NULL, receipt TEXT, status TEXT NOT NULL, coverage TEXT NOT NULL
131
+ id TEXT PRIMARY KEY, manifest TEXT NOT NULL, receipt TEXT, status TEXT NOT NULL, coverage TEXT NOT NULL,
132
+ reopened_revision TEXT
111
133
  ) STRICT;
112
134
  CREATE TABLE IF NOT EXISTS people_learning_receipts (
113
135
  id TEXT PRIMARY KEY, run_id TEXT NOT NULL, receipt TEXT NOT NULL, coverage TEXT NOT NULL, created_at TEXT NOT NULL
@@ -118,6 +140,10 @@ export class PeopleLearningStore {
118
140
  CREATE TABLE IF NOT EXISTS people_learning_analysis (
119
141
  run_id TEXT PRIMARY KEY, status TEXT NOT NULL, result TEXT NOT NULL, checked_at TEXT NOT NULL
120
142
  ) STRICT;`);
143
+ const columns = this.#db.prepare("PRAGMA table_info(people_learning_runs)").all();
144
+ if (!columns.some(col => col.name === "reopened_revision")) {
145
+ this.#db.exec("ALTER TABLE people_learning_runs ADD COLUMN reopened_revision TEXT");
146
+ }
121
147
  this.#db.prepare("INSERT OR IGNORE INTO people_learning_owner VALUES (1,?)").run(agentId);
122
148
  const owner = this.#db.prepare("SELECT agent_id FROM people_learning_owner").get();
123
149
  if (owner && owner.agent_id !== agentId) {
@@ -126,62 +152,147 @@ export class PeopleLearningStore {
126
152
  }
127
153
  }
128
154
  close() { this.#db.close(); }
129
- recordAnalysis(id, status, result, basis) {
130
- if (!this.get(id))
131
- throw new Error("Unknown review run");
132
- this.#db.prepare(`INSERT INTO people_learning_analysis VALUES (?,?,?,?) ON CONFLICT(run_id) DO UPDATE SET
133
- status=excluded.status,result=excluded.result,checked_at=excluded.checked_at`)
134
- .run(id, status, JSON.stringify({ basis, result }), new Date().toISOString());
155
+ recordAnalysis(id, status, result, basis, options = {}) {
156
+ return immediateTransaction(this.#db, () => {
157
+ const run = this.#getRunRow(id);
158
+ if (!run)
159
+ throw new Error("Unknown review run");
160
+ if (options.expectedManifestRevision !== undefined && run.manifestRevision !== options.expectedManifestRevision) {
161
+ return { recorded: false, reason: "manifest_changed" };
162
+ }
163
+ const recordedAt = options.recordedAt ?? Date.now();
164
+ const startedAt = options.startedAt ?? recordedAt;
165
+ const existing = this.#db.prepare(`SELECT status, checked_at,
166
+ json_extract(result,'$.basis') basis,
167
+ json_extract(result,'$.manifestRevision') manifestRevision,
168
+ json_extract(result,'$.startedAt') startedAt,
169
+ json_extract(result,'$.generation') generation,
170
+ json_extract(result,'$.sequence') sequence,
171
+ json_extract(result,'$.instanceId') instanceId
172
+ FROM people_learning_analysis WHERE run_id=?`).get(id);
173
+ if (existing) {
174
+ const existingManifestRevision = typeof existing.manifestRevision === "string" ? existing.manifestRevision : undefined;
175
+ const existingStillCurrent = existingManifestRevision === undefined || existingManifestRevision === run.manifestRevision;
176
+ if (existingStillCurrent) {
177
+ const sameInstance = typeof options.instanceId === "string" && options.instanceId === existing.instanceId;
178
+ const existingGen = typeof existing.generation === "number" ? existing.generation : undefined;
179
+ const existingSeq = typeof existing.sequence === "number" ? existing.sequence : undefined;
180
+ const existingStartedAt = typeof existing.startedAt === "number"
181
+ ? existing.startedAt
182
+ : Date.parse(String(existing.checked_at));
183
+ if (sameInstance && options.generation !== undefined && existingGen !== undefined && options.generation !== existingGen) {
184
+ if (options.generation < existingGen)
185
+ return { recorded: false, reason: "superseded" };
186
+ }
187
+ else if (Number.isFinite(existingStartedAt) && startedAt !== existingStartedAt) {
188
+ if (startedAt < existingStartedAt)
189
+ return { recorded: false, reason: "superseded" };
190
+ }
191
+ else if (sameInstance && options.sequence !== undefined && existingSeq !== undefined && options.sequence < existingSeq) {
192
+ return { recorded: false, reason: "superseded" };
193
+ }
194
+ else if (existing.basis === basis && existing.status === "complete" && status !== "complete") {
195
+ return { recorded: false, reason: "superseded" };
196
+ }
197
+ }
198
+ }
199
+ this.#db.prepare(`INSERT INTO people_learning_analysis VALUES (?,?,?,?) ON CONFLICT(run_id) DO UPDATE SET
200
+ status=excluded.status,result=excluded.result,checked_at=excluded.checked_at`)
201
+ .run(id, status, JSON.stringify({
202
+ basis,
203
+ manifestRevision: run.manifestRevision,
204
+ startedAt,
205
+ ...(options.generation !== undefined ? { generation: options.generation } : {}),
206
+ ...(options.sequence !== undefined ? { sequence: options.sequence } : {}),
207
+ ...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),
208
+ result,
209
+ }), new Date(recordedAt).toISOString());
210
+ return { recorded: true };
211
+ });
212
+ }
213
+ analysis(id) {
214
+ return this.#db.prepare("SELECT status,checked_at,json_extract(result,'$.basis') basis FROM people_learning_analysis WHERE run_id=?").get(id);
135
215
  }
136
- analysis(id) { return this.#db.prepare("SELECT status,checked_at,json_extract(result,'$.basis') basis FROM people_learning_analysis WHERE run_id=?").get(id); }
137
- begin(manifest) {
216
+ #rememberInventory(snapshot) {
217
+ this.#db.prepare("INSERT OR IGNORE INTO people_learning_inventories VALUES (?,?,?,?)")
218
+ .run(jsonHash(snapshot), snapshot.id, JSON.stringify(snapshot), snapshot.refreshedAt ?? snapshot.createdAt);
219
+ }
220
+ begin(manifest, beforeCommit) {
138
221
  if (manifest.agentId !== this.agentId)
139
222
  throw new Error("Cross-agent review manifest");
140
223
  return immediateTransaction(this.#db, () => {
141
- const previous = this.get(manifest.id);
142
- const remember = (snapshot) => this.#db.prepare("INSERT OR IGNORE INTO people_learning_inventories VALUES (?,?,?,?)")
143
- .run(jsonHash(snapshot), snapshot.id, JSON.stringify(snapshot), snapshot.refreshedAt ?? snapshot.createdAt);
144
- if (previous)
145
- remember(previous.manifest);
224
+ const previous = this.#getRunRow(manifest.id);
146
225
  if (previous && !manifest.inventoryPending) {
147
226
  const prior = previous.manifest;
148
227
  if (prior.kind !== manifest.kind || JSON.stringify(prior.window) !== JSON.stringify(manifest.window))
149
228
  throw new Error("Review window changed");
150
- const missingSessions = prior.sessions.filter(s => !manifest.sessions.some(next => next.sessionId === s.sessionId));
229
+ const incomingSessionIds = new Set(manifest.sessions.map(s => s.sessionId));
230
+ const missingSessions = prior.sessions.filter(s => !incomingSessionIds.has(s.sessionId));
151
231
  const sessions = [...manifest.sessions, ...missingSessions];
152
232
  const sourceGaps = [...manifest.sourceGaps, ...missingSessions.map(s => ({
153
233
  id: jsonHash(["missing-session", s.sessionId]), sessionId: s.sessionId,
154
234
  reason: "Previously inventoried session is no longer readable; preserve original export and verify source",
155
235
  }))];
236
+ const priorRosterById = new Map(prior.roster.map(p => [p.personId, p]));
156
237
  const roster = [...new Map([...prior.roster, ...manifest.roster].map(person => {
157
- const old = prior.roster.find(p => p.personId === person.personId);
238
+ const old = priorRosterById.get(person.personId);
158
239
  return [person.personId, { ...person, sessionIds: [...new Set([...(old?.sessionIds ?? []), ...person.sessionIds])] }];
159
240
  })).values()];
160
241
  const assertions = [...new Map([...prior.assertions, ...manifest.assertions].map(a => [a.id, a])).values()];
161
242
  const { refreshedAt: _incomingRefresh, ...incoming } = manifest;
162
- const next = { ...incoming, createdAt: prior.createdAt, fullValidation: prior.fullValidation || manifest.fullValidation,
163
- roster, sessions, sourceGaps, assertions };
243
+ const next = {
244
+ ...incoming,
245
+ createdAt: prior.createdAt,
246
+ fullValidation: prior.fullValidation || manifest.fullValidation,
247
+ roster,
248
+ sessions,
249
+ sourceGaps,
250
+ assertions,
251
+ };
164
252
  const { refreshedAt: _oldRefresh, ...oldComparable } = prior;
165
- if (jsonHash(next) === jsonHash(oldComparable))
166
- return previous;
253
+ if (jsonHash(next) === jsonHash(oldComparable)) {
254
+ beforeCommit?.(previous.manifest);
255
+ this.#rememberInventory(previous.manifest);
256
+ return this.#toPublicRun(previous);
257
+ }
167
258
  const sourcesChanged = jsonHash([prior.sessions, prior.sourceGaps, prior.roster]) !== jsonHash([sessions, sourceGaps, roster]);
168
- manifest = { ...next, refreshedAt: new Date(Date.now()).toISOString() };
169
- const receipt = previous.receipt ? { ...previous.receipt,
259
+ const nextManifest = { ...next, refreshedAt: new Date(Date.now()).toISOString() };
260
+ const nextRevision = manifestRevision(nextManifest);
261
+ // Publish the manifest artifact BEFORE committing the ledger/run row pointing to it.
262
+ beforeCommit?.(nextManifest);
263
+ this.#rememberInventory(previous.manifest);
264
+ const gapIds = new Set(sourceGaps.map(g => g.id));
265
+ const receipt = previous.receipt ? {
266
+ ...previous.receipt,
267
+ manifestRevision: sourcesChanged
268
+ ? undefined
269
+ : previous.receipt.manifestRevision !== undefined ? nextRevision : undefined,
170
270
  peopleReviews: sourcesChanged ? [] : previous.receipt.peopleReviews,
171
271
  assertionReviews: sourcesChanged ? [] : previous.receipt.assertionReviews,
172
- sourceGapReviews: sourcesChanged ? [] : previous.receipt.sourceGapReviews.filter(r => sourceGaps.some(g => g.id === r.sourceGapId)),
272
+ sourceGapReviews: sourcesChanged ? [] : previous.receipt.sourceGapReviews.filter(r => gapIds.has(r.sourceGapId)),
173
273
  analysis: sourcesChanged ? { status: "unresolved", reason: "Source inventory changed; recheck analysis" } : previous.receipt.analysis,
174
274
  } : undefined;
275
+ // Record reopened_revision whenever a run's manifest refreshes (even before
276
+ // any receipt was saved) so an unversioned receipt for an earlier export
277
+ // can never mark the refreshed manifest complete.
278
+ const reopenedRevision = nextRevision;
175
279
  if (sourcesChanged)
176
- this.#db.prepare("DELETE FROM people_learning_analysis WHERE run_id=?").run(manifest.id);
177
- this.#db.prepare("UPDATE people_learning_runs SET manifest=?,receipt=?,status='partial',coverage=? WHERE id=?")
178
- .run(JSON.stringify(manifest), receipt ? JSON.stringify(receipt) : null, JSON.stringify(receipt ? verifyLearningCoverage(manifest, receipt) : { missing: ["receipt"] }), manifest.id);
280
+ this.#db.prepare("DELETE FROM people_learning_analysis WHERE run_id=?").run(nextManifest.id);
281
+ this.#db.prepare("UPDATE people_learning_runs SET manifest=?,receipt=?,status='partial',coverage=?,reopened_revision=? WHERE id=?")
282
+ .run(JSON.stringify(nextManifest), receipt ? JSON.stringify(receipt) : null, JSON.stringify(receipt ? verifyLearningCoverage(nextManifest, receipt) : { missing: ["receipt"] }), reopenedRevision, nextManifest.id);
283
+ this.#rememberInventory(nextManifest);
179
284
  }
180
285
  else if (!previous) {
181
- this.#db.prepare(`INSERT INTO people_learning_runs VALUES (?,?,NULL,'partial',?)`)
286
+ // Publish the manifest artifact BEFORE committing the ledger/run row pointing to it.
287
+ beforeCommit?.(manifest);
288
+ this.#db.prepare("INSERT INTO people_learning_runs (id,manifest,receipt,status,coverage,reopened_revision) VALUES (?,?,NULL,'partial',?,NULL)")
182
289
  .run(manifest.id, JSON.stringify(manifest), JSON.stringify({ missing: ["receipt"], unresolved: manifest.sourceGaps.map(g => g.id) }));
290
+ this.#rememberInventory(manifest);
291
+ }
292
+ else {
293
+ this.#rememberInventory(previous.manifest);
294
+ this.#rememberInventory(manifest);
183
295
  }
184
- remember(manifest);
185
296
  return this.get(manifest.id);
186
297
  });
187
298
  }
@@ -190,52 +301,177 @@ export class PeopleLearningStore {
190
301
  if (!last)
191
302
  return;
192
303
  const step = manifest.kind === "nightly" ? 1 : 7;
304
+ const createdAt = Date.parse(manifest.createdAt);
193
305
  let day = shiftDate(String(last.id).slice(manifest.kind.length + 1), step);
194
306
  while (day < manifest.window.localDay) {
195
- this.begin({ ...manifest, id: `${manifest.kind}:${day}`, inventoryPending: true,
196
- window: reviewWindow(Date.parse(manifest.createdAt), manifest.window.timezone, manifest.kind, day),
197
- roster: [], assertions: [], sessions: [], sourceGaps: [{ id: `inventory:${day}`, reason: "Missed scheduled window; inventory and review still required" }] });
307
+ this.begin({
308
+ ...manifest, id: `${manifest.kind}:${day}`, inventoryPending: true,
309
+ window: reviewWindow(createdAt, manifest.window.timezone, manifest.kind, day),
310
+ roster: [], assertions: [], sessions: [],
311
+ sourceGaps: [{ id: `inventory:${day}`, reason: "Missed scheduled window; inventory and review still required" }],
312
+ });
198
313
  day = shiftDate(day, step);
199
314
  }
200
315
  }
201
- get(id) {
202
- const row = this.#db.prepare("SELECT * FROM people_learning_runs WHERE id=?").get(id);
316
+ #getRunRow(id) {
317
+ const row = this.#db.prepare("SELECT id,manifest,receipt,status,coverage,reopened_revision FROM people_learning_runs WHERE id=?").get(id);
203
318
  if (!row)
204
319
  return undefined;
205
- return { manifest: JSON.parse(String(row.manifest)),
320
+ const manifest = JSON.parse(String(row.manifest));
321
+ return {
322
+ manifest,
323
+ manifestRevision: manifestRevision(manifest),
206
324
  receipt: row.receipt ? Value.Parse(LEARNING_RECEIPT_SCHEMA, JSON.parse(String(row.receipt))) : undefined,
207
- status: String(row.status), coverage: JSON.parse(String(row.coverage)) };
325
+ status: String(row.status),
326
+ coverage: JSON.parse(String(row.coverage)),
327
+ reopenedRevision: typeof row.reopened_revision === "string" ? row.reopened_revision : null,
328
+ };
329
+ }
330
+ #toPublicRun(row) {
331
+ return {
332
+ manifest: row.manifest,
333
+ manifestRevision: row.manifestRevision,
334
+ receipt: row.receipt,
335
+ status: row.status,
336
+ coverage: row.coverage,
337
+ };
338
+ }
339
+ get(id) {
340
+ const row = this.#getRunRow(id);
341
+ return row ? this.#toPublicRun(row) : undefined;
208
342
  }
209
343
  backlog() {
210
344
  return this.#db.prepare("SELECT id,status,coverage FROM people_learning_runs WHERE status!='complete' ORDER BY id").all()
211
345
  .map(row => ({ id: String(row.id), status: String(row.status), coverage: JSON.parse(String(row.coverage)) }));
212
346
  }
213
- checkpoint(id, input, now = Date.now(), checkSaves, finalize) {
347
+ #mergeReceipt(prior, patch, expectedManifestRevision) {
348
+ const merge = (previous, next, key) => {
349
+ if (new Set(next.map(key)).size !== next.length)
350
+ throw new Error("Duplicate review disposition");
351
+ return [...new Map([...previous, ...next].map(row => [key(row), row])).values()];
352
+ };
353
+ const mergedRevision = patch.manifestRevision ?? expectedManifestRevision ?? prior?.manifestRevision;
354
+ return {
355
+ ...patch,
356
+ ...(mergedRevision !== undefined ? { manifestRevision: mergedRevision } : {}),
357
+ peopleReviews: merge(prior?.peopleReviews ?? [], patch.peopleReviews, r => r.personId),
358
+ assertionReviews: merge(prior?.assertionReviews ?? [], patch.assertionReviews, r => r.assertionId),
359
+ sourceGapReviews: merge(prior?.sourceGapReviews ?? [], patch.sourceGapReviews, r => r.sourceGapId),
360
+ changes: merge(prior?.changes ?? [], patch.changes, r => r.changeId),
361
+ executionFollowups: [...new Set([...(prior?.executionFollowups ?? []), ...patch.executionFollowups])],
362
+ };
363
+ }
364
+ #publishFinalized(id, pending, manifest, result, finalize) {
365
+ // Run staged-revision freshness check, ALL dossier verification writes (on this.#db),
366
+ // and final completion UPDATE inside ONE atomic SQLite transaction. If the staged
367
+ // revision changed or any person's verification fails, the entire transaction rolls
368
+ // back and zero newly verified dossiers become visible.
369
+ const { receiptId: _pendingId, manifestRevision: revision, backlog: _backlog, ...pendingCoverage } = result;
370
+ const coverage = { ...pendingCoverage, status: "complete", unresolved: result.unresolved.filter(r => r !== "dossier-verification") };
371
+ const receiptId = jsonHash([result.receiptId, "verified"]);
372
+ let published = false;
373
+ try {
374
+ published = immediateTransaction(this.#db, () => {
375
+ const current = this.#db.prepare("SELECT 1 FROM people_learning_runs WHERE id=? AND manifest=? AND receipt=? AND coverage=? AND status='partial'").get(id, pending.manifest, pending.receipt, pending.coverage);
376
+ if (!current)
377
+ return false;
378
+ finalize(result.receiptId, this.#db, manifest);
379
+ const updated = this.#db.prepare("UPDATE people_learning_runs SET status='complete',coverage=? WHERE id=? AND manifest=? AND receipt=? AND coverage=? AND status='partial'").run(JSON.stringify(coverage), id, pending.manifest, pending.receipt, pending.coverage);
380
+ if (!updated.changes)
381
+ throw new Error("Staged checkpoint changed during finalization");
382
+ this.#db.prepare("INSERT INTO people_learning_receipts VALUES (?,?,?,?,?)")
383
+ .run(receiptId, id, pending.receipt, JSON.stringify(coverage), new Date(Date.now()).toISOString());
384
+ return true;
385
+ });
386
+ }
387
+ catch {
388
+ return { ...result, backlog: this.backlog() };
389
+ }
390
+ return published ? { ...coverage, receiptId, manifestRevision: revision, backlog: this.backlog() } : { ...result, backlog: this.backlog() };
391
+ }
392
+ checkpoint(id, input, now = Date.now(), checkSaves, finalize, expectedManifestRevision, options) {
214
393
  const patch = Value.Parse(LEARNING_RECEIPT_SCHEMA, input);
215
394
  let staged;
395
+ let stagedManifest;
216
396
  const result = immediateTransaction(this.#db, () => {
217
- const run = this.get(id);
397
+ let run = this.#getRunRow(id);
218
398
  if (!run)
219
399
  throw new Error("Unknown review run");
220
400
  if (run.manifest.inventoryPending)
221
401
  throw new Error("Inventory the missed window before checkpointing it");
222
- const merge = (previous, next, key) => {
223
- if (new Set(next.map(key)).size !== next.length)
224
- throw new Error("Duplicate review disposition");
225
- return [...new Map([...previous, ...next].map(row => [key(row), row])).values()];
226
- };
227
- const prior = run.receipt;
228
- const receipt = { ...patch,
229
- peopleReviews: merge(prior?.peopleReviews ?? [], patch.peopleReviews, r => r.personId),
230
- assertionReviews: merge(prior?.assertionReviews ?? [], patch.assertionReviews, r => r.assertionId),
231
- sourceGapReviews: merge(prior?.sourceGapReviews ?? [], patch.sourceGapReviews, r => r.sourceGapId),
232
- changes: merge(prior?.changes ?? [], patch.changes, r => r.changeId),
233
- executionFollowups: [...new Set([...(prior?.executionFollowups ?? []), ...patch.executionFollowups])] };
402
+ const revisionErrors = [];
403
+ if (expectedManifestRevision !== undefined && patch.manifestRevision !== undefined &&
404
+ expectedManifestRevision !== patch.manifestRevision) {
405
+ revisionErrors.push(`Conflicting manifest revision: ${expectedManifestRevision} vs ${patch.manifestRevision}`);
406
+ }
407
+ const suppliedRevision = expectedManifestRevision ?? patch.manifestRevision;
408
+ if (suppliedRevision !== undefined && suppliedRevision !== run.manifestRevision) {
409
+ revisionErrors.push(`Stale manifest revision: expected ${run.manifestRevision}, got ${suppliedRevision}`);
410
+ }
411
+ else if (suppliedRevision === undefined && run.reopenedRevision !== null) {
412
+ revisionErrors.push(`Manifest was refreshed; provide current manifestRevision ${run.manifestRevision}`);
413
+ }
414
+ if (revisionErrors.length) {
415
+ const coverage = {
416
+ status: "invalid",
417
+ expectedPeople: run.manifest.kind === "nightly" ? run.manifest.roster.length : 0,
418
+ expectedSessions: run.manifest.sessions.length,
419
+ expectedAssertions: run.manifest.assertions.length,
420
+ missing: [],
421
+ errors: revisionErrors,
422
+ unresolved: [],
423
+ };
424
+ const receiptId = jsonHash([id, patch, now]);
425
+ this.#db.prepare("INSERT INTO people_learning_receipts VALUES (?,?,?,?,?)")
426
+ .run(receiptId, id, JSON.stringify(patch), JSON.stringify(coverage), new Date(now).toISOString());
427
+ return { receiptId, manifestRevision: run.manifestRevision, ...coverage, backlog: this.backlog() };
428
+ }
429
+ // Revision is CAS-verified inside BEGIN IMMEDIATE. Only now expand newly
430
+ // acquired dossier assertions — never touching sessions, roster, or sourceGaps.
431
+ let assertionsExpanded = false;
432
+ if (options?.collectAssertions) {
433
+ const discovered = options.collectAssertions(run.manifest);
434
+ const mergedAssertions = [...new Map([...run.manifest.assertions, ...discovered].map(a => [a.id, a])).values()];
435
+ if (jsonHash(mergedAssertions) !== jsonHash(run.manifest.assertions)) {
436
+ assertionsExpanded = true;
437
+ const nextManifest = {
438
+ ...run.manifest,
439
+ assertions: mergedAssertions,
440
+ refreshedAt: new Date(now).toISOString(),
441
+ };
442
+ const nextRevision = manifestRevision(nextManifest);
443
+ options.beforeManifestCommit?.(nextManifest);
444
+ this.#rememberInventory(run.manifest);
445
+ const updatedPriorReceipt = run.receipt ? {
446
+ ...run.receipt,
447
+ manifestRevision: run.receipt.manifestRevision !== undefined ? nextRevision : undefined,
448
+ } : undefined;
449
+ this.#db.prepare("UPDATE people_learning_runs SET manifest=?,receipt=?,status='partial',coverage=?,reopened_revision=? WHERE id=?")
450
+ .run(JSON.stringify(nextManifest), updatedPriorReceipt ? JSON.stringify(updatedPriorReceipt) : null, JSON.stringify(updatedPriorReceipt ? verifyLearningCoverage(nextManifest, updatedPriorReceipt, now) : { missing: ["receipt"] }), nextRevision, id);
451
+ this.#rememberInventory(nextManifest);
452
+ run = {
453
+ ...run,
454
+ manifest: nextManifest,
455
+ manifestRevision: nextRevision,
456
+ receipt: updatedPriorReceipt,
457
+ status: "partial",
458
+ reopenedRevision: nextRevision,
459
+ };
460
+ }
461
+ }
462
+ const patchForMerge = assertionsExpanded && patch.manifestRevision !== undefined
463
+ ? { ...patch, manifestRevision: run.manifestRevision }
464
+ : patch;
465
+ const mergedExpectedRevision = assertionsExpanded
466
+ ? (expectedManifestRevision !== undefined ? run.manifestRevision : undefined)
467
+ : expectedManifestRevision;
468
+ const receipt = this.#mergeReceipt(run.receipt, patchForMerge, mergedExpectedRevision);
234
469
  const coverage = verifyLearningCoverage(run.manifest, receipt, now);
235
- coverage.errors.push(...checkSaves?.(receipt) ?? []);
470
+ coverage.errors.push(...checkSaves?.(receipt, run.manifest) ?? []);
236
471
  if (coverage.errors.length)
237
472
  coverage.status = "invalid";
238
- if (coverage.status === "complete" && finalize) {
473
+ const needsFinalize = Boolean(finalize && (options?.shouldFinalize ? options.shouldFinalize(run.manifest) : true));
474
+ if (coverage.status === "complete" && needsFinalize) {
239
475
  coverage.status = "partial";
240
476
  coverage.unresolved.push("dossier-verification");
241
477
  }
@@ -246,36 +482,16 @@ export class PeopleLearningStore {
246
482
  this.#db.prepare("UPDATE people_learning_runs SET receipt=?,status=?,coverage=? WHERE id=?")
247
483
  .run(JSON.stringify(receipt), coverage.status, JSON.stringify(coverage), id);
248
484
  }
249
- if (coverage.unresolved.includes("dossier-verification"))
485
+ if (coverage.unresolved.includes("dossier-verification")) {
250
486
  staged = {
251
487
  manifest: JSON.stringify(run.manifest), receipt: JSON.stringify(receipt), coverage: JSON.stringify(coverage),
252
488
  };
253
- return { receiptId, ...coverage, backlog: this.backlog() };
489
+ stagedManifest = run.manifest;
490
+ }
491
+ return { receiptId, manifestRevision: run.manifestRevision, ...coverage, backlog: this.backlog() };
254
492
  });
255
- if (!finalize || !result.unresolved.includes("dossier-verification"))
256
- return result;
257
- // PeopleStore uses a separate connection to this database. Persist pending
258
- // work before releasing our transaction; publish complete only after its
259
- // verification writes succeed. A crash/failure leaves resumable backlog.
260
- const pending = staged;
261
- try {
262
- finalize(result.receiptId);
263
- }
264
- catch {
493
+ if (!finalize || !staged || !stagedManifest || !result.unresolved.includes("dossier-verification"))
265
494
  return result;
266
- }
267
- const { receiptId: _pendingId, backlog: _backlog, ...pendingCoverage } = result;
268
- const coverage = { ...pendingCoverage, status: "complete", unresolved: result.unresolved.filter(r => r !== "dossier-verification") };
269
- const receiptId = jsonHash([result.receiptId, "verified"]);
270
- const published = immediateTransaction(this.#db, () => {
271
- const updated = this.#db.prepare("UPDATE people_learning_runs SET status='complete',coverage=? WHERE id=? AND manifest=? AND receipt=? AND coverage=? AND status='partial'")
272
- .run(JSON.stringify(coverage), id, pending.manifest, pending.receipt, pending.coverage);
273
- if (!updated.changes)
274
- return false;
275
- this.#db.prepare("INSERT INTO people_learning_receipts VALUES (?,?,?,?,?)")
276
- .run(receiptId, id, pending.receipt, JSON.stringify(coverage), new Date(Date.now()).toISOString());
277
- return true;
278
- });
279
- return published ? { ...coverage, receiptId, backlog: this.backlog() } : { ...result, backlog: this.backlog() };
495
+ return this.#publishFinalized(id, staged, stagedManifest, result, finalize);
280
496
  }
281
497
  }