@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,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { join, relative, isAbsolute } from "node:path";
2
3
  import { existsSync, readFileSync, statSync, realpathSync } from "node:fs";
3
4
  import { Type } from "typebox";
@@ -6,9 +7,9 @@ import { listAgentIds, jsonResult } from "openclaw/plugin-sdk/agent-runtime";
6
7
  import { resolveAgentWorkspaceDir, resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
7
8
  import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
8
9
  import { resolveConfig } from "./config.js";
9
- import { PeopleStores as LocalPeopleStores } from "./people-store.js";
10
+ import { PeopleStores, recordDossierVerificationInTransaction } from "./people-store.js";
10
11
  import { inventoryPeople, dossierAssertions, privateJson } from "./people-learning-inventory.js";
11
- import { PeopleLearningStore, LEARNING_RECEIPT_SCHEMA } from "./people-learning-store.js";
12
+ import { PeopleLearningStore, LEARNING_RECEIPT_SCHEMA, manifestRevision } from "./people-learning-store.js";
12
13
  import { learningForAgent } from "./people-learning-config.js";
13
14
  import { resolveTimezone } from "./session-projector.js";
14
15
  import { reconcilePeopleLearning, learningSession, LEARNING_TOOLS } from "./people-learning-cron.js";
@@ -20,6 +21,48 @@ import { getContext } from "./tool-context.js";
20
21
  import { record } from "./guards.js";
21
22
  import { jsonHash } from "./json-hash.js";
22
23
  import { reviewWindow } from "./people-learning-time.js";
24
+ const LEARNING_PARAMETERS = Type.Union([
25
+ Type.Object({ action: Type.Literal("inventory"), kind: Type.Enum(["nightly", "weekly"]) }, { additionalProperties: false }),
26
+ Type.Object({ action: Type.Literal("inspect"), runId: Type.String() }, { additionalProperties: false }),
27
+ Type.Object({ action: Type.Literal("signals"), runId: Type.String() }, { additionalProperties: false }),
28
+ Type.Object({
29
+ action: Type.Literal("checkpoint"),
30
+ runId: Type.String(),
31
+ manifestRevision: Type.String({ pattern: "\\S" }),
32
+ receipt: LEARNING_RECEIPT_SCHEMA,
33
+ }, { additionalProperties: false }),
34
+ ]);
35
+ function withLearningStore(storePath, agentId, fn) {
36
+ const ledger = new PeopleLearningStore(storePath, agentId);
37
+ try {
38
+ return fn(ledger);
39
+ }
40
+ finally {
41
+ ledger.close();
42
+ }
43
+ }
44
+ function resolvePluginConfig(cfg, fallback) {
45
+ const entry = cfg.plugins?.entries?.["unblock-memory"];
46
+ return resolveConfig(entry ? entry.config : fallback);
47
+ }
48
+ function isLearningEnabled(config, agentId, kind) {
49
+ if (!config.people.enabled || !config.people.whisperer.enabled)
50
+ return false;
51
+ const agent = learningForAgent(config.people.learning, agentId);
52
+ return agent.enabled && (kind === undefined || agent[kind]);
53
+ }
54
+ function isLearningAuthorized(cfg, config, job) {
55
+ return listAgentIds(cfg).includes(job.agentId) && isLearningEnabled(config, job.agentId, job.kind);
56
+ }
57
+ function isAnalysisApproved(config) {
58
+ return config.responseAudit.enabled && config.decisionModel.enabled && config.responseAudit.intervalMinutes > 0;
59
+ }
60
+ function auditCohort(config) {
61
+ return responseCohort(config.responseAudit, config.decisionModel.model, config.decisionModel.endpoint);
62
+ }
63
+ function publishManifest(root, manifest) {
64
+ return privateJson(root, `${manifestRevision(manifest)}.manifest.json`, manifest);
65
+ }
23
66
  function reviewPaths(cfg, config, agentId, stateRoot) {
24
67
  if (!listAgentIds(cfg).includes(agentId))
25
68
  throw new Error("Unknown people-learning agent");
@@ -32,108 +75,288 @@ function reviewPaths(cfg, config, agentId, stateRoot) {
32
75
  if (path === "" || (!path.startsWith("..") && !isAbsolute(path)))
33
76
  throw new Error("People review state overlaps a configured corpus root");
34
77
  }
35
- return { state, root, storePath: join(state, MEMORY_DATABASE),
36
- databasePath: agentTranscriptDatabase(cfg, agentId), workspace, sources };
78
+ return {
79
+ state, root, storePath: join(state, MEMORY_DATABASE),
80
+ databasePath: agentTranscriptDatabase(cfg, agentId), workspace, sources,
81
+ };
82
+ }
83
+ function importLegacyBacklog(cfg, stores, ledger, agentId, paths, manifest) {
84
+ // Carry the original extension's queue forward without modifying its receipts
85
+ // or pretending its free-form entries have already been resolved.
86
+ const legacyPath = join(paths.workspace, "logs", "people-reflection", "backlog.json");
87
+ if (!existsSync(legacyPath))
88
+ return;
89
+ let legacy;
90
+ try {
91
+ if (statSync(legacyPath).size > 1024 * 1024)
92
+ throw new Error("Legacy backlog over read budget");
93
+ legacy = JSON.parse(readFileSync(legacyPath, "utf8"));
94
+ }
95
+ catch {
96
+ legacy = { source: legacyPath, unresolved: "Legacy backlog unreadable; inspect original locally" };
97
+ }
98
+ const canonical = (path) => existsSync(path) ? realpathSync(path) : path;
99
+ const canonicalWorkspace = canonical(paths.workspace);
100
+ const workspaceOwners = listAgentIds(cfg).filter(id => canonical(resolveAgentWorkspaceDir(cfg, id)) === canonicalWorkspace);
101
+ const declaredOwner = record(legacy)?.agentId;
102
+ const owner = declaredOwner === undefined ? (workspaceOwners.length === 1 ? workspaceOwners[0] : undefined)
103
+ : typeof declaredOwner === "string" && workspaceOwners.includes(declaredOwner) ? declaredOwner : undefined;
104
+ if (!owner) {
105
+ manifest.sourceGaps.push({
106
+ id: jsonHash(["legacy-owner", legacyPath]),
107
+ reason: "Legacy backlog in a shared workspace has no exact agentId; establish ownership before import",
108
+ });
109
+ return;
110
+ }
111
+ if (owner !== agentId)
112
+ return;
113
+ const hash = jsonHash(legacy), legacyId = `legacy:${hash}`;
114
+ const legacyFile = privateJson(paths.root, `${hash}.legacy.json`, legacy);
115
+ const previous = ledger.get(legacyId);
116
+ // An import has its own first-seen metadata. An unchanged source must not
117
+ // inherit a different day's window or switch kind on the next review.
118
+ if (!previous) {
119
+ ledger.begin({
120
+ ...manifest, id: legacyId, roster: [], assertions: [], sessions: [], fullValidation: true,
121
+ sourceGaps: [{ id: hash, reason: `Imported legacy review backlog; resume every unfinished entry before resolving: ${legacyFile}` }],
122
+ });
123
+ }
124
+ if (previous?.status !== "complete" && record(legacy)?.bootstrapRequired === true) {
125
+ const people = stores.get(agentId);
126
+ manifest.fullValidation = true;
127
+ manifest.assertions = manifest.roster.flatMap(person => {
128
+ const dossier = people.getDossier(person.personId)?.dossier;
129
+ return dossier ? dossierAssertions(person.personId, dossier) : [];
130
+ });
131
+ }
37
132
  }
38
133
  function beginReview(cfg, config, stores, agentId, kind, stateRoot, day, resumeTimezone) {
39
134
  const paths = reviewPaths(cfg, config, agentId, stateRoot);
40
135
  const settings = learningForAgent(config.people.learning, agentId);
41
- const ledger = new PeopleLearningStore(paths.storePath, agentId);
42
- try {
136
+ return withLearningStore(paths.storePath, agentId, ledger => {
43
137
  const requestedTimezone = resumeTimezone ?? settings.timezone ?? resolveTimezone(cfg.agents?.defaults?.userTimezone);
44
138
  const priorWindow = ledger.get(`${kind}:${reviewWindow(Date.now(), requestedTimezone, kind, day).localDay}`)?.manifest.window;
45
- const manifest = inventoryPeople({ agentId, kind, people: stores.get(agentId), databasePath: paths.databasePath,
139
+ const manifest = inventoryPeople({
140
+ agentId, kind, people: stores.get(agentId), databasePath: paths.databasePath,
46
141
  timezone: priorWindow?.timezone ?? requestedTimezone, day: priorWindow?.localDay ?? day,
47
- exportRoot: join(paths.root, "exports") });
48
- // Carry the original extension's queue forward without modifying its receipts
49
- // or pretending its free-form entries have already been resolved.
50
- const legacyPath = join(paths.workspace, "logs", "people-reflection", "backlog.json");
51
- if (existsSync(legacyPath)) {
52
- let legacy;
53
- try {
54
- if (statSync(legacyPath).size > 1024 * 1024)
55
- throw new Error("Legacy backlog over read budget");
56
- legacy = JSON.parse(readFileSync(legacyPath, "utf8"));
57
- }
58
- catch {
59
- legacy = { source: legacyPath, unresolved: "Legacy backlog unreadable; inspect original locally" };
60
- }
61
- const canonical = (path) => existsSync(path) ? realpathSync(path) : path;
62
- const workspaceOwners = listAgentIds(cfg).filter(id => canonical(resolveAgentWorkspaceDir(cfg, id)) === canonical(paths.workspace));
63
- const declaredOwner = record(legacy)?.agentId;
64
- const owner = declaredOwner === undefined ? (workspaceOwners.length === 1 ? workspaceOwners[0] : undefined)
65
- : typeof declaredOwner === "string" && workspaceOwners.includes(declaredOwner) ? declaredOwner : undefined;
66
- if (!owner) {
67
- manifest.sourceGaps.push({ id: jsonHash(["legacy-owner", legacyPath]), reason: "Legacy backlog in a shared workspace has no exact agentId; establish ownership before import" });
68
- }
69
- else if (owner === agentId) {
70
- const hash = jsonHash(legacy), legacyId = `legacy:${hash}`;
71
- const legacyFile = privateJson(paths.root, `${hash}.legacy.json`, legacy);
72
- const previous = ledger.get(legacyId);
73
- // An import has its own first-seen metadata. An unchanged source must not
74
- // inherit a different day's window or switch kind on the next review.
75
- if (!previous)
76
- ledger.begin({ ...manifest, id: legacyId, roster: [], assertions: [], sessions: [], fullValidation: true,
77
- sourceGaps: [{ id: hash, reason: `Imported legacy review backlog; resume every unfinished entry before resolving: ${legacyFile}` }] });
78
- if (previous?.status !== "complete" && record(legacy)?.bootstrapRequired === true) {
79
- manifest.fullValidation = true;
80
- manifest.assertions = manifest.roster.flatMap(person => {
81
- const dossier = stores.get(agentId).getDossier(person.personId)?.dossier;
82
- return dossier ? dossierAssertions(person.personId, dossier) : [];
83
- });
84
- }
85
- }
86
- }
142
+ exportRoot: join(paths.root, "exports"),
143
+ });
144
+ importLegacyBacklog(cfg, stores, ledger, agentId, paths, manifest);
87
145
  ledger.planMissedWindows(manifest);
88
- const run = ledger.begin(manifest);
89
- const file = privateJson(paths.root, `${jsonHash(run.manifest)}.manifest.json`, run.manifest);
90
- return { ...run, manifestFile: file, backlog: ledger.backlog() };
91
- }
92
- finally {
93
- ledger.close();
94
- }
146
+ let manifestFile = "";
147
+ const run = ledger.begin(manifest, published => {
148
+ manifestFile = publishManifest(paths.root, published);
149
+ });
150
+ return { ...run, manifestFile, backlog: ledger.backlog() };
151
+ });
95
152
  }
96
153
  function saveErrors(receipt, manifest, stores, agentId) {
97
154
  const people = stores.get(agentId), errors = [];
155
+ const manifestCreatedAt = Date.parse(manifest.createdAt);
156
+ const changesByPerson = new Map();
98
157
  for (const change of receipt.changes) {
99
158
  const saved = people.getDossierChange(change.personId, change.changeId);
100
- if (!saved || Date.parse(saved.changedAt) < Date.parse(manifest.createdAt))
159
+ if (!saved || Date.parse(saved.changedAt) < manifestCreatedAt)
101
160
  errors.push(`Unconfirmed save: ${change.changeId}`);
161
+ let ids = changesByPerson.get(change.personId);
162
+ if (!ids) {
163
+ ids = new Set();
164
+ changesByPerson.set(change.personId, ids);
165
+ }
166
+ ids.add(change.changeId);
102
167
  }
168
+ const reviewsById = new Map(receipt.assertionReviews.map(r => [r.assertionId, r]));
169
+ const manifestAssertionIds = new Set(manifest.assertions.map(a => a.id));
170
+ const personState = new Map();
171
+ const currentPersonState = (personId) => {
172
+ let state = personState.get(personId);
173
+ if (!state) {
174
+ const dossier = people.getDossier(personId)?.dossier;
175
+ const assertionIds = new Set(dossier ? dossierAssertions(personId, dossier).map(a => a.id) : []);
176
+ state = { assertionIds, revision: people.getDossierRevision(personId) };
177
+ personState.set(personId, state);
178
+ }
179
+ return state;
180
+ };
181
+ const hasCurrentChange = (personId, revision) => revision !== null && (changesByPerson.get(personId)?.has(revision) ?? false);
103
182
  for (const assertion of manifest.assertions) {
104
- const review = receipt.assertionReviews.find(r => r.assertionId === assertion.id);
183
+ const review = reviewsById.get(assertion.id);
105
184
  if (!review || review.disposition === "unresolved")
106
185
  continue;
107
- const dossier = people.getDossier(assertion.personId)?.dossier;
108
- const current = dossier ? dossierAssertions(assertion.personId, dossier) : [];
109
- const retained = current.find(a => a.id === assertion.id);
186
+ const { assertionIds, revision } = currentPersonState(assertion.personId);
187
+ const retained = assertionIds.has(assertion.id);
110
188
  if (review.disposition === "revalidated" && !retained)
111
189
  errors.push(`Revalidated statement no longer present: ${assertion.id}`);
112
190
  if (review.disposition !== "revalidated" && retained)
113
191
  errors.push(`Correction/retirement not saved: ${assertion.id}`);
114
192
  // The source-verified receipt records this revalidation's actual date.
115
193
  // Unchanged claims need not be rewritten or have their original dates renewed.
116
- if (review.disposition !== "revalidated" && !receipt.changes.some(c => c.personId === assertion.personId &&
117
- c.changeId === people.getDossierRevision(assertion.personId)))
194
+ if (review.disposition !== "revalidated" && !hasCurrentChange(assertion.personId, revision)) {
118
195
  errors.push(`Missing current change receipt: ${assertion.id}`);
196
+ }
119
197
  }
120
198
  // Concurrent additions must be reviewed, not silently excluded from a weekly/ bootstrap run.
121
199
  for (const personId of reviewCohort(manifest)) {
122
- const dossier = people.getDossier(personId)?.dossier;
123
- if (!dossier)
200
+ const { assertionIds, revision } = currentPersonState(personId);
201
+ if (!assertionIds.size)
124
202
  continue;
125
- if (dossierAssertions(personId, dossier).some(a => !manifest.assertions.some(old => old.id === a.id)) &&
126
- !receipt.changes.some(c => c.personId === personId && c.changeId === people.getDossierRevision(personId)))
203
+ let hasNewAssertion = false;
204
+ for (const id of assertionIds)
205
+ if (!manifestAssertionIds.has(id)) {
206
+ hasNewAssertion = true;
207
+ break;
208
+ }
209
+ if (hasNewAssertion && !hasCurrentChange(personId, revision)) {
127
210
  errors.push(`New assertions require current verified save receipts: ${personId}`);
211
+ }
128
212
  }
129
213
  return errors;
130
214
  }
131
215
  function reviewCohort(manifest) {
132
- return new Set([...manifest.assertions.map(a => a.personId),
133
- ...manifest.roster.filter(p => manifest.kind === "weekly" && p.sessionIds.length > 0).map(p => p.personId)]);
216
+ return new Set([
217
+ ...manifest.assertions.map(a => a.personId),
218
+ ...manifest.roster.filter(p => manifest.kind === "weekly" && p.sessionIds.length > 0).map(p => p.personId),
219
+ ]);
134
220
  }
135
221
  function analysisBasis(config, manifest) {
136
- return jsonHash([responseCohort(config.responseAudit), config.responseAudit.lookbackDays, manifest]);
222
+ return jsonHash([auditCohort(config), config.responseAudit.lookbackDays, manifest]);
223
+ }
224
+ async function handleSignalsAction(options) {
225
+ const { params, agentId, paths, analysisConfig, analysisGeneration, analysisSequence, instanceId, isCurrent, signal } = options;
226
+ if (!isAnalysisApproved(analysisConfig)) {
227
+ let report;
228
+ if (analysisConfig.responseAudit.enabled && hasMemoryTable(paths.storePath, "response_results")) {
229
+ const store = new ResponseAuditStore(paths.storePath);
230
+ try {
231
+ report = store.report(auditCohort(analysisConfig), Date.now() - 8 * 86400_000);
232
+ }
233
+ finally {
234
+ store.close();
235
+ }
236
+ }
237
+ return jsonResult({ status: "not_approved", report, reason: "Automatic external analysis is not enabled; cached leads only" });
238
+ }
239
+ const startedAt = Date.now();
240
+ const { since, until, basis, expectedManifestRevision } = withLearningStore(paths.storePath, agentId, ledger => {
241
+ const target = ledger.get(params.runId);
242
+ if (!target || target.manifest.inventoryPending)
243
+ throw new Error("Inventory this run before analysis");
244
+ return {
245
+ since: target.manifest.window.since,
246
+ until: target.manifest.window.until,
247
+ basis: analysisBasis(analysisConfig, target.manifest),
248
+ expectedManifestRevision: target.manifestRevision,
249
+ };
250
+ });
251
+ const audit = await auditResponses({
252
+ config: analysisConfig, agentId, ...paths,
253
+ indexPath: join(paths.state, "index.sqlite"), peoplePath: paths.storePath,
254
+ sources: paths.sources.filter(s => analysisConfig.responseAudit.memoryCorpora.includes(s.corpus)), signal,
255
+ });
256
+ const pending = "coverage" in audit ? audit.coverage : undefined;
257
+ let unresolved = 0;
258
+ let report;
259
+ if (hasMemoryTable(paths.storePath, "response_results")) {
260
+ const store = new ResponseAuditStore(paths.storePath);
261
+ try {
262
+ const cohort = auditCohort(analysisConfig);
263
+ unresolved = store.unresolvedWork(cohort, since, until);
264
+ report = store.report(cohort, since, undefined, { until, bucket: "day" });
265
+ }
266
+ finally {
267
+ store.close();
268
+ }
269
+ }
270
+ else
271
+ unresolved++;
272
+ const analysisStatus = !unresolved && since >= Date.now() - analysisConfig.responseAudit.lookbackDays * 86400_000 &&
273
+ audit.status === "ok" && pending && !pending.failed && !pending.deferredByLimit &&
274
+ !pending.sessionsOverBudget && !pending.reconciliationDeferred && !pending.sessionLimitReached && !pending.oversized && !pending.stale
275
+ ? "complete" : "unresolved";
276
+ if (!isCurrent()) {
277
+ return jsonResult({
278
+ status: "unresolved",
279
+ stale: true,
280
+ staleReason: "superseded",
281
+ audit,
282
+ report,
283
+ note: "Analysis configuration or service generation changed while in flight; newer analysis state preserved",
284
+ });
285
+ }
286
+ const recorded = withLearningStore(paths.storePath, agentId, ledger => ledger.recordAnalysis(params.runId, analysisStatus, audit, basis, {
287
+ expectedManifestRevision,
288
+ startedAt,
289
+ generation: analysisGeneration,
290
+ sequence: analysisSequence,
291
+ instanceId,
292
+ }));
293
+ if (!recorded.recorded) {
294
+ return jsonResult({
295
+ status: "unresolved",
296
+ stale: true,
297
+ staleReason: recorded.reason,
298
+ audit,
299
+ report,
300
+ note: "Older or stale in-flight analysis was fenced; newer analysis state preserved",
301
+ });
302
+ }
303
+ return jsonResult({
304
+ status: analysisStatus, audit, report,
305
+ note: "Signals cover only existing approvals and bounded audit work; preserve unassessed/failed analysis as unresolved",
306
+ });
307
+ }
308
+ function handleInspectAction(options) {
309
+ const { params, cfg, config, stores, agentId, stateRoot, paths } = options;
310
+ return withLearningStore(paths.storePath, agentId, ledger => {
311
+ const prior = ledger.get(params.runId);
312
+ if (prior && prior.status !== "complete" && !params.runId.startsWith("legacy:")) {
313
+ beginReview(cfg, config, stores, agentId, prior.manifest.kind, stateRoot, prior.manifest.window.localDay, prior.manifest.window.timezone);
314
+ }
315
+ const run = ledger.get(params.runId);
316
+ return jsonResult({ run, manifestRevision: run?.manifestRevision, backlog: ledger.backlog() });
317
+ });
318
+ }
319
+ function handleCheckpointAction(options) {
320
+ const { params, config, stores, agentId, paths } = options;
321
+ const people = stores.get(agentId);
322
+ return withLearningStore(paths.storePath, agentId, ledger => {
323
+ let verificationTargets = [];
324
+ // Validate revision, expand newly acquired dossier assertions (without ever calling
325
+ // ledger.begin() or mutating sessions/roster/sourceGaps), and merge the receipt inside
326
+ // one immediateTransaction; then commit dossier verifications + completion atomically.
327
+ const coverage = ledger.checkpoint(params.runId, params.receipt, Date.now(), (receipt, manifest) => {
328
+ verificationTargets = manifest.fullValidation
329
+ ? [...new Set(manifest.assertions.map(a => a.personId))]
330
+ .filter(personId => people.getDossier(personId))
331
+ .map(personId => ({ personId, revision: people.getDossierRevision(personId) }))
332
+ : [];
333
+ const errors = saveErrors(receipt, manifest, stores, agentId);
334
+ const approved = isAnalysisApproved(config);
335
+ const analysis = ledger.analysis(params.runId);
336
+ if (approved && receipt.analysis.status !== "unresolved" &&
337
+ (receipt.analysis.status !== "complete" || analysis?.status !== "complete" || analysis.basis !== analysisBasis(config, manifest))) {
338
+ errors.push("Approved analysis has not completed for this cohort and inventory; preserve unresolved analysis backlog");
339
+ }
340
+ if (!approved && receipt.analysis.status !== "not_approved") {
341
+ errors.push("External analysis is not approved; do not invent analysis results");
342
+ }
343
+ return errors;
344
+ }, (receiptId, db, manifest) => {
345
+ if (!manifest.fullValidation)
346
+ return;
347
+ for (const { personId, revision } of verificationTargets) {
348
+ recordDossierVerificationInTransaction(db, personId, revision, `Complete source validation receipt ${receiptId}`);
349
+ }
350
+ }, params.manifestRevision, {
351
+ collectAssertions: manifest => [...reviewCohort(manifest)].flatMap(personId => {
352
+ const dossier = people.getDossier(personId)?.dossier;
353
+ return dossier ? dossierAssertions(personId, dossier) : [];
354
+ }),
355
+ beforeManifestCommit: published => { publishManifest(paths.root, published); },
356
+ shouldFinalize: manifest => manifest.fullValidation,
357
+ });
358
+ return jsonResult(coverage);
359
+ });
137
360
  }
138
361
  const STARTUP_RETRY_DELAY_MS = 5_000;
139
362
  const RETRY_DELAY_MS = 60_000;
@@ -143,12 +366,24 @@ function isStartupPrepError(error) {
143
366
  }
144
367
  export function registerPeopleLearning(api, initial, stores) {
145
368
  let cfg = api.config, config = initial, stateRoot = resolveStateDir(), live = false;
146
- let jobs = [], reconciliation, followUp;
369
+ // Separate durable cron declaration recognition from current authorization:
370
+ // recognizedJobs persists across transient reconcile/reload failures so private-session
371
+ // hooks keep enforcing tool restrictions, while authorization is checked against live cfg/config.
372
+ let recognizedJobs = [];
373
+ let reconciliation, followUp;
147
374
  let rerun = false, startupRetries = 0;
148
375
  let getCron;
149
376
  let generation = 0;
377
+ let analysisSeq = 0;
378
+ const instanceId = randomUUID();
150
379
  let scheduler;
151
380
  let retryTask;
381
+ const mergeRecognized = (discovered, replace = false) => {
382
+ const next = new Map(replace ? [] : recognizedJobs.map(j => [`${j.agentId}:${j.id}`, j]));
383
+ for (const job of discovered)
384
+ next.set(`${job.agentId}:${job.id}`, job);
385
+ recognizedJobs = [...next.values()];
386
+ };
152
387
  const clearRetry = () => { retryTask?.cancel?.(); retryTask = undefined; };
153
388
  const scheduleRetry = (delayMs) => {
154
389
  clearRetry();
@@ -178,19 +413,30 @@ export function registerPeopleLearning(api, initial, stores) {
178
413
  }
179
414
  return followUp;
180
415
  }
181
- const cron = getCron?.();
182
- if (!cron) {
183
- api.logger.warn("unblock-memory people learning incomplete: this host does not expose service getCron; upgrade the host");
184
- return Promise.resolve();
185
- }
186
416
  rerun = false;
187
417
  const version = generation;
188
418
  const learning = config.people.enabled && config.people.whisperer.enabled ? config.people.learning
189
- : { ...config.people.learning, enabled: false, agents: {} };
190
- reconciliation = reconcilePeopleLearning(cron, cfg, learning, () => live && version === generation)
191
- .then(result => {
419
+ : {
420
+ ...config.people.learning,
421
+ enabled: false,
422
+ agents: Object.fromEntries(Object.entries(config.people.learning.agents ?? {}).map(([id, agent]) => [id, { ...agent, enabled: false }])),
423
+ };
424
+ reconciliation = Promise.resolve()
425
+ .then(async () => {
426
+ const cron = getCron?.();
427
+ if (!cron) {
428
+ if (live && version === generation) {
429
+ rerun = false;
430
+ api.logger.warn("unblock-memory people learning incomplete: this host does not expose service getCron; upgrade the host");
431
+ scheduleRetry(RETRY_DELAY_MS);
432
+ }
433
+ return;
434
+ }
435
+ await reconcilePeopleLearning(cron, cfg, learning, () => live && version === generation, (discovered, replace) => {
436
+ if (live && version === generation)
437
+ mergeRecognized(discovered, replace);
438
+ });
192
439
  if (live && version === generation) {
193
- jobs = result;
194
440
  startupRetries = 0;
195
441
  clearRetry();
196
442
  }
@@ -219,8 +465,7 @@ export function registerPeopleLearning(api, initial, stores) {
219
465
  start(context) {
220
466
  cfg = context.config;
221
467
  stateRoot = context.stateDir;
222
- const entry = cfg.plugins?.entries?.["unblock-memory"];
223
- config = resolveConfig(entry ? entry.config : api.pluginConfig);
468
+ config = resolvePluginConfig(cfg, api.pluginConfig);
224
469
  clearRetry();
225
470
  live = true;
226
471
  generation++;
@@ -232,21 +477,22 @@ export function registerPeopleLearning(api, initial, stores) {
232
477
  },
233
478
  async stop() {
234
479
  live = false;
235
- const stopVersion = ++generation;
480
+ generation++;
236
481
  rerun = false;
237
482
  startupRetries = 0;
238
483
  clearRetry();
239
484
  await reconciliation?.catch(() => { });
240
485
  await followUp?.catch(() => { });
241
- if (stopVersion === generation)
242
- jobs = [];
486
+ // Do NOT clear recognizedJobs here: on service reload (stop -> start),
487
+ // a transient reconcile failure in start() would otherwise leave
488
+ // before_tool_call failing open. recognizedJobs is only replaced on an
489
+ // authoritative full snapshot from reconcilePeopleLearning.
243
490
  },
244
491
  });
245
492
  api.on("gateway_start", () => reconcile());
246
493
  api.on("cron_reconciled", (_event, context) => {
247
494
  if (context.config) {
248
- const entry = context.config.plugins?.entries?.["unblock-memory"];
249
- const nextConfig = resolveConfig(entry ? entry.config : api.pluginConfig);
495
+ const nextConfig = resolvePluginConfig(context.config, api.pluginConfig);
250
496
  generation++;
251
497
  cfg = context.config;
252
498
  config = nextConfig;
@@ -256,10 +502,10 @@ export function registerPeopleLearning(api, initial, stores) {
256
502
  // Defense in depth: cron delivery is none AND these review sessions cannot send,
257
503
  // spawn another agent, exec, change configuration, or reactivate a person.
258
504
  api.on("before_tool_call", (event, context) => {
259
- const job = learningSession(context.sessionKey, jobs);
505
+ const job = learningSession(context.sessionKey, recognizedJobs);
260
506
  if (!job)
261
507
  return;
262
- if (!config.people.enabled || !config.people.whisperer.enabled || !learningForAgent(config.people.learning, job.agentId).enabled) {
508
+ if (!isLearningAuthorized(cfg, config, job)) {
263
509
  return { block: true, blockReason: "People learning is disabled for this agent" };
264
510
  }
265
511
  if (!LEARNING_TOOLS.includes(event.toolName) || (event.toolName === "memory_people_update" &&
@@ -269,136 +515,51 @@ export function registerPeopleLearning(api, initial, stores) {
269
515
  if (event.toolName === "memory_people_update") {
270
516
  try {
271
517
  const person = stores.get(job.agentId).getPerson(String(record(event.params)?.personId));
272
- if (!person || person.status !== "active" || !person.injectionEnabled)
518
+ if (!person || person.status !== "active" || !person.injectionEnabled) {
273
519
  return { block: true, blockReason: "Inactive/paused people are review-only" };
520
+ }
274
521
  }
275
522
  catch {
276
523
  return { block: true, blockReason: "People source unavailable; preserve unresolved work" };
277
524
  }
278
525
  }
279
526
  });
280
- const parameters = Type.Union([
281
- Type.Object({ action: Type.Literal("inventory"), kind: Type.Enum(["nightly", "weekly"]) }, { additionalProperties: false }),
282
- Type.Object({ action: Type.Literal("inspect"), runId: Type.String() }, { additionalProperties: false }),
283
- Type.Object({ action: Type.Literal("signals"), runId: Type.String() }, { additionalProperties: false }),
284
- Type.Object({ action: Type.Literal("checkpoint"), runId: Type.String(), receipt: LEARNING_RECEIPT_SCHEMA }, { additionalProperties: false }),
285
- ]);
286
527
  api.registerTool(ctx => {
287
- const active = getContext(ctx), job = learningSession(ctx.sessionKey, jobs);
288
- if (!active || !job || active.agentId !== job.agentId || !config.people.enabled || !config.people.whisperer.enabled ||
289
- !learningForAgent(config.people.learning, active.agentId).enabled)
528
+ const active = getContext(ctx), job = learningSession(ctx.sessionKey, recognizedJobs);
529
+ if (!active || !job || active.agentId !== job.agentId || !isLearningAuthorized(cfg, config, job))
290
530
  return null;
291
- return { name: "memory_people_learning", label: "Private People Learning", parameters,
531
+ return {
532
+ name: "memory_people_learning",
533
+ label: "Private People Learning",
534
+ parameters: LEARNING_PARAMETERS,
292
535
  description: "Inventory full local exchanges and assertion coverage, inspect resumable private backlog, get approved analysis leads, and checkpoint verified review receipts. Scheduled People Whisperer sessions only.",
293
536
  async execute(_id, input, signal) {
294
- const params = Value.Parse(parameters, input);
537
+ const params = Value.Parse(LEARNING_PARAMETERS, input);
295
538
  if (!live)
296
539
  return jsonResult({ status: "unavailable" });
297
- if (!config.people.enabled || !config.people.whisperer.enabled || !learningForAgent(config.people.learning, active.agentId).enabled)
540
+ if (!isLearningAuthorized(cfg, config, job))
298
541
  return jsonResult({ status: "disabled" });
299
542
  if (params.action === "inventory")
300
543
  return jsonResult(beginReview(cfg, config, stores, active.agentId, params.kind, stateRoot));
301
544
  const paths = reviewPaths(cfg, config, active.agentId, stateRoot);
302
545
  if (params.action === "signals") {
303
- const analysisConfig = config;
304
- if (!config.responseAudit.enabled || !config.typesafe.enabled || !config.responseAudit.intervalMinutes) {
305
- let report;
306
- if (config.responseAudit.enabled && hasMemoryTable(paths.storePath, "response_results")) {
307
- const store = new ResponseAuditStore(paths.storePath);
308
- try {
309
- report = store.report(responseCohort(config.responseAudit), Date.now() - 8 * 86400_000);
310
- }
311
- finally {
312
- store.close();
313
- }
314
- }
315
- return jsonResult({ status: "not_approved", report, reason: "Automatic external analysis is not enabled; cached leads only" });
316
- }
317
- const targetLedger = new PeopleLearningStore(paths.storePath, active.agentId);
318
- let since, until, basis;
319
- try {
320
- const target = targetLedger.get(params.runId);
321
- if (!target || target.manifest.inventoryPending)
322
- throw new Error("Inventory this run before analysis");
323
- since = target.manifest.window.since;
324
- until = target.manifest.window.until;
325
- basis = analysisBasis(analysisConfig, target.manifest);
326
- }
327
- finally {
328
- targetLedger.close();
329
- }
330
- const audit = await auditResponses({ config: analysisConfig, agentId: active.agentId, ...paths,
331
- indexPath: join(paths.state, "index.sqlite"), peoplePath: paths.storePath,
332
- sources: paths.sources.filter(s => analysisConfig.responseAudit.memoryCorpora.includes(s.corpus)), signal });
333
- const pending = "coverage" in audit ? audit.coverage : undefined;
334
- let unresolved = 0;
335
- let report;
336
- if (hasMemoryTable(paths.storePath, "response_results")) {
337
- const store = new ResponseAuditStore(paths.storePath);
338
- try {
339
- unresolved = store.unresolvedWork(responseCohort(analysisConfig.responseAudit), since, until);
340
- report = store.report(responseCohort(analysisConfig.responseAudit), since, undefined, { until, bucket: "day" });
341
- }
342
- finally {
343
- store.close();
344
- }
345
- }
346
- else
347
- unresolved++;
348
- const analysisStatus = !unresolved && since >= Date.now() - analysisConfig.responseAudit.lookbackDays * 86400_000 && audit.status === "ok" && pending && !pending.failed && !pending.deferredByLimit &&
349
- !pending.sessionsOverBudget && !pending.reconciliationDeferred && !pending.sessionLimitReached && !pending.oversized && !pending.stale
350
- ? "complete" : "unresolved";
351
- const ledger = new PeopleLearningStore(paths.storePath, active.agentId);
352
- try {
353
- ledger.recordAnalysis(params.runId, analysisStatus, audit, basis);
354
- }
355
- finally {
356
- ledger.close();
357
- }
358
- return jsonResult({ status: analysisStatus, audit, report, note: "Signals cover only existing approvals and bounded audit work; preserve unassessed/failed analysis as unresolved" });
359
- }
360
- const ledger = new PeopleLearningStore(paths.storePath, active.agentId);
361
- try {
362
- if (params.action === "inspect") {
363
- const prior = ledger.get(params.runId);
364
- if (prior && prior.status !== "complete" && !params.runId.startsWith("legacy:"))
365
- beginReview(cfg, config, stores, active.agentId, prior.manifest.kind, stateRoot, prior.manifest.window.localDay, prior.manifest.window.timezone);
366
- return jsonResult({ run: ledger.get(params.runId), backlog: ledger.backlog() });
367
- }
368
- let run = ledger.get(params.runId);
369
- if (!run)
370
- throw new Error("Unknown review run");
371
- // A participant may have acquired a dossier since the inventory.
372
- // Expand expectations before accepting a weekly checkpoint.
373
- const current = [...reviewCohort(run.manifest)].flatMap(personId => {
374
- const dossier = stores.get(active.agentId).getDossier(personId)?.dossier;
375
- return dossier ? dossierAssertions(personId, dossier) : [];
546
+ const analysisGeneration = generation;
547
+ return handleSignalsAction({
548
+ params,
549
+ agentId: active.agentId,
550
+ paths,
551
+ analysisConfig: config,
552
+ analysisGeneration,
553
+ analysisSequence: ++analysisSeq,
554
+ instanceId,
555
+ isCurrent: () => live && generation === analysisGeneration,
556
+ signal,
376
557
  });
377
- run = ledger.begin({ ...run.manifest, assertions: [...new Map([...run.manifest.assertions, ...current].map(a => [a.id, a])).values()] });
378
- const people = stores.get(active.agentId);
379
- const verificationTargets = [...new Set(run.manifest.assertions.map(a => a.personId))]
380
- .filter(personId => people.getDossier(personId))
381
- .map(personId => ({ personId, revision: people.getDossierRevision(personId) }));
382
- // Validate the merged checkpoint, including saved dispositions from earlier attempts.
383
- const coverage = ledger.checkpoint(params.runId, params.receipt, Date.now(), receipt => {
384
- const errors = saveErrors(receipt, run.manifest, stores, active.agentId);
385
- const approved = config.responseAudit.enabled && config.typesafe.enabled && config.responseAudit.intervalMinutes > 0;
386
- const analysis = ledger.analysis(params.runId);
387
- if (approved && receipt.analysis.status !== "unresolved" &&
388
- (receipt.analysis.status !== "complete" || analysis?.status !== "complete" || analysis.basis !== analysisBasis(config, run.manifest)))
389
- errors.push("Approved analysis has not completed for this cohort and inventory; preserve unresolved analysis backlog");
390
- if (!approved && receipt.analysis.status !== "not_approved")
391
- errors.push("External analysis is not approved; do not invent analysis results");
392
- return errors;
393
- }, run.manifest.fullValidation ? receiptId => {
394
- for (const { personId, revision } of verificationTargets)
395
- people.recordDossierVerification(personId, revision, `Complete source validation receipt ${receiptId}`);
396
- } : undefined);
397
- return jsonResult(coverage);
398
558
  }
399
- finally {
400
- ledger.close();
559
+ if (params.action === "inspect") {
560
+ return handleInspectAction({ params, cfg, config, stores, agentId: active.agentId, stateRoot, paths });
401
561
  }
562
+ return handleCheckpointAction({ params, config, stores, agentId: active.agentId, paths });
402
563
  },
403
564
  };
404
565
  }, { names: ["memory_people_learning"] });
@@ -412,7 +573,7 @@ export function registerPeopleLearningCli(api, config) {
412
573
  .action((opts) => {
413
574
  if (opts.kind !== "nightly" && opts.kind !== "weekly")
414
575
  throw new Error("Invalid review kind");
415
- const stores = new LocalPeopleStores({ maxOpenTodos: config.people.todos.maxOpen, maxBlurbChars: config.people.whisperer.maxChars });
576
+ const stores = new PeopleStores({ maxOpenTodos: config.people.todos.maxOpen, maxBlurbChars: config.people.whisperer.maxChars });
416
577
  try {
417
578
  console.log(JSON.stringify(beginReview(cfg, config, stores, opts.agent, opts.kind, resolveStateDir(), opts.date), null, 2));
418
579
  }
@@ -424,13 +585,9 @@ export function registerPeopleLearningCli(api, config) {
424
585
  .option("--run <id>", "Inspect one review and its latest receipt")
425
586
  .action((opts) => {
426
587
  const paths = reviewPaths(cfg, config, opts.agent, resolveStateDir());
427
- const ledger = new PeopleLearningStore(paths.storePath, opts.agent);
428
- try {
588
+ withLearningStore(paths.storePath, opts.agent, ledger => {
429
589
  console.log(JSON.stringify({ backlog: ledger.backlog(), ...(opts.run ? { run: ledger.get(opts.run) } : {}) }, null, 2));
430
- }
431
- finally {
432
- ledger.close();
433
- }
590
+ });
434
591
  });
435
592
  }, { descriptors: [{ name: "memory-people-learning", description: "Private people-learning coverage and inventories", hasSubcommands: true }] });
436
593
  }