@unblocklabs/unblock-memory 0.12.2 → 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.
- package/README.md +19 -18
- package/dist/src/analysis.js +1 -1
- package/dist/src/cluster-review.d.ts +2 -0
- package/dist/src/cluster-review.js +3 -3
- package/dist/src/config.d.ts +9 -6
- package/dist/src/config.js +31 -20
- package/dist/src/curation.d.ts +1 -1
- package/dist/src/decision-client.d.ts +39 -0
- package/dist/src/decision-client.js +74 -0
- package/dist/src/{typesafe.d.ts → decision-ranking.d.ts} +15 -18
- package/dist/src/decision-ranking.js +154 -0
- package/dist/src/{typesafe-review.d.ts → decision-review.d.ts} +13 -9
- package/dist/src/decision-review.js +192 -0
- package/dist/src/diagnostics.d.ts +5 -5
- package/dist/src/emotion-baselines.d.ts +28 -3
- package/dist/src/emotion-baselines.js +309 -113
- package/dist/src/evidence-review.d.ts +22 -8
- package/dist/src/evidence-review.js +4 -4
- package/dist/src/extraction-chunk.d.ts +3 -0
- package/dist/src/extraction-chunk.js +23 -5
- package/dist/src/extraction-model.d.ts +2 -0
- package/dist/src/extraction-model.js +73 -48
- package/dist/src/extraction-runtime.d.ts +3 -1
- package/dist/src/extraction-runtime.js +43 -16
- package/dist/src/extraction-source.d.ts +1 -1
- package/dist/src/extraction-source.js +19 -11
- package/dist/src/extraction-store.d.ts +28 -3
- package/dist/src/extraction-store.js +145 -23
- package/dist/src/extraction-worker.d.ts +1 -0
- package/dist/src/extraction-worker.js +246 -93
- package/dist/src/inside-out-runtime.js +41 -29
- package/dist/src/inside-out-store.d.ts +2 -2
- package/dist/src/inside-out-store.js +110 -69
- package/dist/src/inside-out.d.ts +10 -9
- package/dist/src/inside-out.js +190 -105
- package/dist/src/manager.d.ts +22 -9
- package/dist/src/manager.js +275 -169
- package/dist/src/memory-search.d.ts +4 -2
- package/dist/src/memory-search.js +5 -5
- package/dist/src/memory-whisperer.d.ts +1 -1
- package/dist/src/memory-whisperer.js +189 -127
- package/dist/src/my-turn.d.ts +1 -1
- package/dist/src/my-turn.js +87 -68
- package/dist/src/people-background.d.ts +4 -0
- package/dist/src/people-background.js +29 -6
- package/dist/src/people-dossier-review.d.ts +20 -8
- package/dist/src/people-dossier-review.js +11 -8
- package/dist/src/people-hooks.js +127 -22
- package/dist/src/people-learning-cron.d.ts +1 -1
- package/dist/src/people-learning-cron.js +106 -57
- package/dist/src/people-learning-inventory.d.ts +1 -0
- package/dist/src/people-learning-inventory.js +281 -171
- package/dist/src/people-learning-prompt.js +1 -1
- package/dist/src/people-learning-runtime.d.ts +1 -1
- package/dist/src/people-learning-runtime.js +423 -204
- package/dist/src/people-learning-store.d.ts +27 -4
- package/dist/src/people-learning-store.js +312 -96
- package/dist/src/people-primer-tool.js +8 -6
- package/dist/src/people-primer.d.ts +3 -1
- package/dist/src/people-primer.js +61 -44
- package/dist/src/people-store.d.ts +18 -21
- package/dist/src/people-store.js +186 -63
- package/dist/src/people-tools.js +136 -92
- package/dist/src/plugin.js +16 -16
- package/dist/src/quality-audit.d.ts +2 -0
- package/dist/src/quality-audit.js +8 -7
- package/dist/src/query-generator.d.ts +1 -1
- package/dist/src/query-generator.js +15 -8
- package/dist/src/response-audit.d.ts +1 -1
- package/dist/src/response-audit.js +76 -43
- package/dist/src/response-episodes.d.ts +1 -1
- package/dist/src/response-episodes.js +12 -17
- package/dist/src/response-judge.d.ts +151 -145
- package/dist/src/response-judge.js +535 -204
- package/dist/src/response-reviews.d.ts +29 -1
- package/dist/src/response-reviews.js +110 -13
- package/dist/src/response-runtime.js +8 -8
- package/dist/src/response-stages.d.ts +50 -53
- package/dist/src/response-stages.js +10 -4
- package/dist/src/response-store.d.ts +7 -6
- package/dist/src/response-store.js +332 -210
- package/dist/src/response-text.d.ts +2 -0
- package/dist/src/response-text.js +182 -36
- package/dist/src/review-tools.d.ts +8 -2
- package/dist/src/review-tools.js +18 -18
- package/dist/src/runtime.d.ts +7 -4
- package/dist/src/runtime.js +624 -98
- package/dist/src/safety-whisperer.d.ts +2 -2
- package/dist/src/safety-whisperer.js +88 -71
- package/dist/src/session-sync.d.ts +3 -1
- package/dist/src/session-sync.js +200 -95
- package/dist/src/skill-whisperer.d.ts +1 -1
- package/dist/src/skill-whisperer.js +52 -30
- package/dist/src/training-gate.d.ts +8 -21
- package/dist/src/training-gate.js +32 -35
- package/dist/src/training-judge.d.ts +9 -16
- package/dist/src/training-judge.js +5 -5
- package/dist/src/training-queries.d.ts +13 -8
- package/dist/src/training-queries.js +370 -228
- package/dist/src/training-retrieval.d.ts +14 -24
- package/dist/src/training-retrieval.js +182 -136
- package/dist/src/training-runtime.d.ts +3 -0
- package/dist/src/training-runtime.js +76 -18
- package/dist/src/training-store.d.ts +18 -3
- package/dist/src/training-store.js +138 -50
- package/dist/src/training.js +8 -11
- package/dist/src/whisperer-context.d.ts +14 -0
- package/dist/src/whisperer-context.js +22 -1
- package/docs/configuration.md +76 -63
- package/docs/extraction.md +9 -7
- package/docs/memory-training.md +7 -6
- package/docs/people-learning.md +2 -2
- package/docs/peoplesql.md +6 -6
- package/docs/response-audit.md +10 -8
- package/docs/retrieval.md +40 -37
- package/openclaw.plugin.json +40 -26
- package/package.json +3 -2
- package/skills/memory-curator/SKILL.md +1 -1
- package/skills/people-whisperer/SKILL.md +1 -1
- package/dist/src/typesafe-client.d.ts +0 -30
- package/dist/src/typesafe-client.js +0 -92
- package/dist/src/typesafe-review.js +0 -154
- 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
|
|
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,135 +75,386 @@ 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 {
|
|
36
|
-
|
|
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
|
-
|
|
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({
|
|
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
|
-
|
|
49
|
-
|
|
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
|
-
|
|
89
|
-
const
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
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) <
|
|
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 =
|
|
183
|
+
const review = reviewsById.get(assertion.id);
|
|
105
184
|
if (!review || review.disposition === "unresolved")
|
|
106
185
|
continue;
|
|
107
|
-
const
|
|
108
|
-
const
|
|
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" && !
|
|
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
|
|
123
|
-
if (!
|
|
200
|
+
const { assertionIds, revision } = currentPersonState(personId);
|
|
201
|
+
if (!assertionIds.size)
|
|
124
202
|
continue;
|
|
125
|
-
|
|
126
|
-
|
|
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([
|
|
133
|
-
...manifest.
|
|
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([
|
|
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
|
+
});
|
|
360
|
+
}
|
|
361
|
+
const STARTUP_RETRY_DELAY_MS = 5_000;
|
|
362
|
+
const RETRY_DELAY_MS = 60_000;
|
|
363
|
+
const MAX_QUIET_STARTUP_RETRIES = 8;
|
|
364
|
+
function isStartupPrepError(error) {
|
|
365
|
+
return /not completed startup inspection and preparation/i.test(String(error));
|
|
137
366
|
}
|
|
138
367
|
export function registerPeopleLearning(api, initial, stores) {
|
|
139
368
|
let cfg = api.config, config = initial, stateRoot = resolveStateDir(), live = false;
|
|
140
|
-
|
|
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;
|
|
374
|
+
let rerun = false, startupRetries = 0;
|
|
141
375
|
let getCron;
|
|
142
376
|
let generation = 0;
|
|
377
|
+
let analysisSeq = 0;
|
|
378
|
+
const instanceId = randomUUID();
|
|
143
379
|
let scheduler;
|
|
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
|
+
};
|
|
387
|
+
const clearRetry = () => { retryTask?.cancel?.(); retryTask = undefined; };
|
|
388
|
+
const scheduleRetry = (delayMs) => {
|
|
389
|
+
clearRetry();
|
|
390
|
+
if (!live || !scheduler || scheduler.signal?.aborted)
|
|
391
|
+
return;
|
|
392
|
+
try {
|
|
393
|
+
retryTask = scheduler.schedule({ id: "people-learning-reconcile", delayMs, run: reconcile });
|
|
394
|
+
}
|
|
395
|
+
catch {
|
|
396
|
+
// Host scheduler can close concurrently during gateway shutdown or reload.
|
|
397
|
+
}
|
|
398
|
+
};
|
|
144
399
|
const reconcile = () => {
|
|
145
400
|
if (!live)
|
|
146
401
|
return Promise.resolve();
|
|
147
|
-
if (reconciliation)
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
402
|
+
if (reconciliation) {
|
|
403
|
+
rerun = true;
|
|
404
|
+
if (!followUp) {
|
|
405
|
+
const next = () => {
|
|
406
|
+
followUp = undefined;
|
|
407
|
+
if (!live || !rerun)
|
|
408
|
+
return;
|
|
409
|
+
rerun = false;
|
|
410
|
+
return reconcile();
|
|
411
|
+
};
|
|
412
|
+
followUp = reconciliation.then(next, next);
|
|
413
|
+
}
|
|
414
|
+
return followUp;
|
|
153
415
|
}
|
|
416
|
+
rerun = false;
|
|
154
417
|
const version = generation;
|
|
155
418
|
const learning = config.people.enabled && config.people.whisperer.enabled ? config.people.learning
|
|
156
|
-
: {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
+
});
|
|
439
|
+
if (live && version === generation) {
|
|
440
|
+
startupRetries = 0;
|
|
441
|
+
clearRetry();
|
|
442
|
+
}
|
|
443
|
+
})
|
|
160
444
|
.catch(error => {
|
|
445
|
+
if (!live || version !== generation)
|
|
446
|
+
return;
|
|
447
|
+
rerun = false;
|
|
448
|
+
if (isStartupPrepError(error) && scheduler && !scheduler.signal?.aborted && startupRetries < MAX_QUIET_STARTUP_RETRIES) {
|
|
449
|
+
startupRetries++;
|
|
450
|
+
if (startupRetries === 1) {
|
|
451
|
+
api.logger.info?.("unblock-memory people learning scheduling deferred until agent startup preparation completes");
|
|
452
|
+
}
|
|
453
|
+
scheduleRetry(STARTUP_RETRY_DELAY_MS);
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
161
456
|
api.logger.warn(`unblock-memory people learning scheduling incomplete: ${String(error)}`);
|
|
162
|
-
|
|
163
|
-
scheduler?.schedule({ id: "people-learning-reconcile", delayMs: 60_000, run: reconcile });
|
|
457
|
+
scheduleRetry(RETRY_DELAY_MS);
|
|
164
458
|
})
|
|
165
459
|
.finally(() => { reconciliation = undefined; });
|
|
166
460
|
return reconciliation;
|
|
@@ -171,33 +465,47 @@ export function registerPeopleLearning(api, initial, stores) {
|
|
|
171
465
|
start(context) {
|
|
172
466
|
cfg = context.config;
|
|
173
467
|
stateRoot = context.stateDir;
|
|
174
|
-
|
|
175
|
-
|
|
468
|
+
config = resolvePluginConfig(cfg, api.pluginConfig);
|
|
469
|
+
clearRetry();
|
|
176
470
|
live = true;
|
|
177
471
|
generation++;
|
|
472
|
+
startupRetries = 0;
|
|
473
|
+
rerun = false;
|
|
178
474
|
getCron = context.getCron?.bind(context);
|
|
179
475
|
scheduler = context.scheduler;
|
|
180
476
|
void reconcile();
|
|
181
477
|
},
|
|
182
|
-
async stop() {
|
|
478
|
+
async stop() {
|
|
479
|
+
live = false;
|
|
480
|
+
generation++;
|
|
481
|
+
rerun = false;
|
|
482
|
+
startupRetries = 0;
|
|
483
|
+
clearRetry();
|
|
484
|
+
await reconciliation?.catch(() => { });
|
|
485
|
+
await followUp?.catch(() => { });
|
|
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.
|
|
490
|
+
},
|
|
183
491
|
});
|
|
184
492
|
api.on("gateway_start", () => reconcile());
|
|
185
493
|
api.on("cron_reconciled", (_event, context) => {
|
|
186
494
|
if (context.config) {
|
|
495
|
+
const nextConfig = resolvePluginConfig(context.config, api.pluginConfig);
|
|
187
496
|
generation++;
|
|
188
497
|
cfg = context.config;
|
|
189
|
-
|
|
190
|
-
config = resolveConfig(entry ? entry.config : api.pluginConfig);
|
|
498
|
+
config = nextConfig;
|
|
191
499
|
}
|
|
192
500
|
return reconcile();
|
|
193
501
|
});
|
|
194
502
|
// Defense in depth: cron delivery is none AND these review sessions cannot send,
|
|
195
503
|
// spawn another agent, exec, change configuration, or reactivate a person.
|
|
196
504
|
api.on("before_tool_call", (event, context) => {
|
|
197
|
-
const job = learningSession(context.sessionKey,
|
|
505
|
+
const job = learningSession(context.sessionKey, recognizedJobs);
|
|
198
506
|
if (!job)
|
|
199
507
|
return;
|
|
200
|
-
if (!
|
|
508
|
+
if (!isLearningAuthorized(cfg, config, job)) {
|
|
201
509
|
return { block: true, blockReason: "People learning is disabled for this agent" };
|
|
202
510
|
}
|
|
203
511
|
if (!LEARNING_TOOLS.includes(event.toolName) || (event.toolName === "memory_people_update" &&
|
|
@@ -207,136 +515,51 @@ export function registerPeopleLearning(api, initial, stores) {
|
|
|
207
515
|
if (event.toolName === "memory_people_update") {
|
|
208
516
|
try {
|
|
209
517
|
const person = stores.get(job.agentId).getPerson(String(record(event.params)?.personId));
|
|
210
|
-
if (!person || person.status !== "active" || !person.injectionEnabled)
|
|
518
|
+
if (!person || person.status !== "active" || !person.injectionEnabled) {
|
|
211
519
|
return { block: true, blockReason: "Inactive/paused people are review-only" };
|
|
520
|
+
}
|
|
212
521
|
}
|
|
213
522
|
catch {
|
|
214
523
|
return { block: true, blockReason: "People source unavailable; preserve unresolved work" };
|
|
215
524
|
}
|
|
216
525
|
}
|
|
217
526
|
});
|
|
218
|
-
const parameters = Type.Union([
|
|
219
|
-
Type.Object({ action: Type.Literal("inventory"), kind: Type.Enum(["nightly", "weekly"]) }, { additionalProperties: false }),
|
|
220
|
-
Type.Object({ action: Type.Literal("inspect"), runId: Type.String() }, { additionalProperties: false }),
|
|
221
|
-
Type.Object({ action: Type.Literal("signals"), runId: Type.String() }, { additionalProperties: false }),
|
|
222
|
-
Type.Object({ action: Type.Literal("checkpoint"), runId: Type.String(), receipt: LEARNING_RECEIPT_SCHEMA }, { additionalProperties: false }),
|
|
223
|
-
]);
|
|
224
527
|
api.registerTool(ctx => {
|
|
225
|
-
const active = getContext(ctx), job = learningSession(ctx.sessionKey,
|
|
226
|
-
if (!active || !job || active.agentId !== job.agentId || !
|
|
227
|
-
!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))
|
|
228
530
|
return null;
|
|
229
|
-
return {
|
|
531
|
+
return {
|
|
532
|
+
name: "memory_people_learning",
|
|
533
|
+
label: "Private People Learning",
|
|
534
|
+
parameters: LEARNING_PARAMETERS,
|
|
230
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.",
|
|
231
536
|
async execute(_id, input, signal) {
|
|
232
|
-
const params = Value.Parse(
|
|
537
|
+
const params = Value.Parse(LEARNING_PARAMETERS, input);
|
|
233
538
|
if (!live)
|
|
234
539
|
return jsonResult({ status: "unavailable" });
|
|
235
|
-
if (!
|
|
540
|
+
if (!isLearningAuthorized(cfg, config, job))
|
|
236
541
|
return jsonResult({ status: "disabled" });
|
|
237
542
|
if (params.action === "inventory")
|
|
238
543
|
return jsonResult(beginReview(cfg, config, stores, active.agentId, params.kind, stateRoot));
|
|
239
544
|
const paths = reviewPaths(cfg, config, active.agentId, stateRoot);
|
|
240
545
|
if (params.action === "signals") {
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
}
|
|
253
|
-
return jsonResult({ status: "not_approved", report, reason: "Automatic external analysis is not enabled; cached leads only" });
|
|
254
|
-
}
|
|
255
|
-
const targetLedger = new PeopleLearningStore(paths.storePath, active.agentId);
|
|
256
|
-
let since, until, basis;
|
|
257
|
-
try {
|
|
258
|
-
const target = targetLedger.get(params.runId);
|
|
259
|
-
if (!target || target.manifest.inventoryPending)
|
|
260
|
-
throw new Error("Inventory this run before analysis");
|
|
261
|
-
since = target.manifest.window.since;
|
|
262
|
-
until = target.manifest.window.until;
|
|
263
|
-
basis = analysisBasis(analysisConfig, target.manifest);
|
|
264
|
-
}
|
|
265
|
-
finally {
|
|
266
|
-
targetLedger.close();
|
|
267
|
-
}
|
|
268
|
-
const audit = await auditResponses({ config: analysisConfig, agentId: active.agentId, ...paths,
|
|
269
|
-
indexPath: join(paths.state, "index.sqlite"), peoplePath: paths.storePath,
|
|
270
|
-
sources: paths.sources.filter(s => analysisConfig.responseAudit.memoryCorpora.includes(s.corpus)), signal });
|
|
271
|
-
const pending = "coverage" in audit ? audit.coverage : undefined;
|
|
272
|
-
let unresolved = 0;
|
|
273
|
-
let report;
|
|
274
|
-
if (hasMemoryTable(paths.storePath, "response_results")) {
|
|
275
|
-
const store = new ResponseAuditStore(paths.storePath);
|
|
276
|
-
try {
|
|
277
|
-
unresolved = store.unresolvedWork(responseCohort(analysisConfig.responseAudit), since, until);
|
|
278
|
-
report = store.report(responseCohort(analysisConfig.responseAudit), since, undefined, { until, bucket: "day" });
|
|
279
|
-
}
|
|
280
|
-
finally {
|
|
281
|
-
store.close();
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
else
|
|
285
|
-
unresolved++;
|
|
286
|
-
const analysisStatus = !unresolved && since >= Date.now() - analysisConfig.responseAudit.lookbackDays * 86400_000 && audit.status === "ok" && pending && !pending.failed && !pending.deferredByLimit &&
|
|
287
|
-
!pending.sessionsOverBudget && !pending.reconciliationDeferred && !pending.sessionLimitReached && !pending.oversized && !pending.stale
|
|
288
|
-
? "complete" : "unresolved";
|
|
289
|
-
const ledger = new PeopleLearningStore(paths.storePath, active.agentId);
|
|
290
|
-
try {
|
|
291
|
-
ledger.recordAnalysis(params.runId, analysisStatus, audit, basis);
|
|
292
|
-
}
|
|
293
|
-
finally {
|
|
294
|
-
ledger.close();
|
|
295
|
-
}
|
|
296
|
-
return jsonResult({ status: analysisStatus, audit, report, note: "Signals cover only existing approvals and bounded audit work; preserve unassessed/failed analysis as unresolved" });
|
|
297
|
-
}
|
|
298
|
-
const ledger = new PeopleLearningStore(paths.storePath, active.agentId);
|
|
299
|
-
try {
|
|
300
|
-
if (params.action === "inspect") {
|
|
301
|
-
const prior = ledger.get(params.runId);
|
|
302
|
-
if (prior && prior.status !== "complete" && !params.runId.startsWith("legacy:"))
|
|
303
|
-
beginReview(cfg, config, stores, active.agentId, prior.manifest.kind, stateRoot, prior.manifest.window.localDay, prior.manifest.window.timezone);
|
|
304
|
-
return jsonResult({ run: ledger.get(params.runId), backlog: ledger.backlog() });
|
|
305
|
-
}
|
|
306
|
-
let run = ledger.get(params.runId);
|
|
307
|
-
if (!run)
|
|
308
|
-
throw new Error("Unknown review run");
|
|
309
|
-
// A participant may have acquired a dossier since the inventory.
|
|
310
|
-
// Expand expectations before accepting a weekly checkpoint.
|
|
311
|
-
const current = [...reviewCohort(run.manifest)].flatMap(personId => {
|
|
312
|
-
const dossier = stores.get(active.agentId).getDossier(personId)?.dossier;
|
|
313
|
-
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,
|
|
314
557
|
});
|
|
315
|
-
run = ledger.begin({ ...run.manifest, assertions: [...new Map([...run.manifest.assertions, ...current].map(a => [a.id, a])).values()] });
|
|
316
|
-
const people = stores.get(active.agentId);
|
|
317
|
-
const verificationTargets = [...new Set(run.manifest.assertions.map(a => a.personId))]
|
|
318
|
-
.filter(personId => people.getDossier(personId))
|
|
319
|
-
.map(personId => ({ personId, revision: people.getDossierRevision(personId) }));
|
|
320
|
-
// Validate the merged checkpoint, including saved dispositions from earlier attempts.
|
|
321
|
-
const coverage = ledger.checkpoint(params.runId, params.receipt, Date.now(), receipt => {
|
|
322
|
-
const errors = saveErrors(receipt, run.manifest, stores, active.agentId);
|
|
323
|
-
const approved = config.responseAudit.enabled && config.typesafe.enabled && config.responseAudit.intervalMinutes > 0;
|
|
324
|
-
const analysis = ledger.analysis(params.runId);
|
|
325
|
-
if (approved && receipt.analysis.status !== "unresolved" &&
|
|
326
|
-
(receipt.analysis.status !== "complete" || analysis?.status !== "complete" || analysis.basis !== analysisBasis(config, run.manifest)))
|
|
327
|
-
errors.push("Approved analysis has not completed for this cohort and inventory; preserve unresolved analysis backlog");
|
|
328
|
-
if (!approved && receipt.analysis.status !== "not_approved")
|
|
329
|
-
errors.push("External analysis is not approved; do not invent analysis results");
|
|
330
|
-
return errors;
|
|
331
|
-
}, run.manifest.fullValidation ? receiptId => {
|
|
332
|
-
for (const { personId, revision } of verificationTargets)
|
|
333
|
-
people.recordDossierVerification(personId, revision, `Complete source validation receipt ${receiptId}`);
|
|
334
|
-
} : undefined);
|
|
335
|
-
return jsonResult(coverage);
|
|
336
558
|
}
|
|
337
|
-
|
|
338
|
-
|
|
559
|
+
if (params.action === "inspect") {
|
|
560
|
+
return handleInspectAction({ params, cfg, config, stores, agentId: active.agentId, stateRoot, paths });
|
|
339
561
|
}
|
|
562
|
+
return handleCheckpointAction({ params, config, stores, agentId: active.agentId, paths });
|
|
340
563
|
},
|
|
341
564
|
};
|
|
342
565
|
}, { names: ["memory_people_learning"] });
|
|
@@ -350,7 +573,7 @@ export function registerPeopleLearningCli(api, config) {
|
|
|
350
573
|
.action((opts) => {
|
|
351
574
|
if (opts.kind !== "nightly" && opts.kind !== "weekly")
|
|
352
575
|
throw new Error("Invalid review kind");
|
|
353
|
-
const stores = new
|
|
576
|
+
const stores = new PeopleStores({ maxOpenTodos: config.people.todos.maxOpen, maxBlurbChars: config.people.whisperer.maxChars });
|
|
354
577
|
try {
|
|
355
578
|
console.log(JSON.stringify(beginReview(cfg, config, stores, opts.agent, opts.kind, resolveStateDir(), opts.date), null, 2));
|
|
356
579
|
}
|
|
@@ -362,13 +585,9 @@ export function registerPeopleLearningCli(api, config) {
|
|
|
362
585
|
.option("--run <id>", "Inspect one review and its latest receipt")
|
|
363
586
|
.action((opts) => {
|
|
364
587
|
const paths = reviewPaths(cfg, config, opts.agent, resolveStateDir());
|
|
365
|
-
|
|
366
|
-
try {
|
|
588
|
+
withLearningStore(paths.storePath, opts.agent, ledger => {
|
|
367
589
|
console.log(JSON.stringify({ backlog: ledger.backlog(), ...(opts.run ? { run: ledger.get(opts.run) } : {}) }, null, 2));
|
|
368
|
-
}
|
|
369
|
-
finally {
|
|
370
|
-
ledger.close();
|
|
371
|
-
}
|
|
590
|
+
});
|
|
372
591
|
});
|
|
373
592
|
}, { descriptors: [{ name: "memory-people-learning", description: "Private people-learning coverage and inventories", hasSubcommands: true }] });
|
|
374
593
|
}
|