@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.
- 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 +183 -125
- 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 +360 -203
- 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/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/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,5 +1,42 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import { immediateTransaction, openMemoryDatabase } from "./memory-database.js";
|
|
3
|
+
import { jsonHash } from "./json-hash.js";
|
|
4
|
+
export class ExtractionLeaseLostError extends Error {
|
|
5
|
+
constructor() {
|
|
6
|
+
super("Extraction lease lost");
|
|
7
|
+
this.name = "ExtractionLeaseLostError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export function extractionPolicyFingerprint(params) {
|
|
11
|
+
return jsonHash({
|
|
12
|
+
version: params.version,
|
|
13
|
+
historyMessages: params.historyMessages,
|
|
14
|
+
minSupport: params.minSupport,
|
|
15
|
+
minRetention: params.minRetention,
|
|
16
|
+
minReplacement: params.minReplacement,
|
|
17
|
+
validatorModel: params.validatorModel ?? null,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
export function buildCompleteRevision(sourceRevision, policyFingerprint) {
|
|
21
|
+
return JSON.stringify({ sourceRevision, policy: policyFingerprint });
|
|
22
|
+
}
|
|
23
|
+
function parseCompleteRevision(value) {
|
|
24
|
+
if (value === null)
|
|
25
|
+
return null;
|
|
26
|
+
try {
|
|
27
|
+
const parsed = JSON.parse(value);
|
|
28
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed) &&
|
|
29
|
+
typeof parsed.sourceRevision === "string" &&
|
|
30
|
+
typeof parsed.policy === "string") {
|
|
31
|
+
return {
|
|
32
|
+
sourceRevision: parsed.sourceRevision,
|
|
33
|
+
policy: parsed.policy,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch { /* Legacy plain-string complete_revision without policy binding. */ }
|
|
38
|
+
return { sourceRevision: value, policy: null };
|
|
39
|
+
}
|
|
3
40
|
function memoryDigest(text) {
|
|
4
41
|
return createHash("sha256").update(text.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.!]+$/, "")).digest("hex");
|
|
5
42
|
}
|
|
@@ -20,7 +57,7 @@ export class ExtractionStore {
|
|
|
20
57
|
session_id TEXT PRIMARY KEY, metadata TEXT NOT NULL CHECK(json_valid(metadata)), cursor TEXT,
|
|
21
58
|
extract_since INTEGER NOT NULL,
|
|
22
59
|
context TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(context)), updated_at INTEGER NOT NULL,
|
|
23
|
-
error TEXT, complete_revision TEXT
|
|
60
|
+
error TEXT, complete_revision TEXT, policy_fingerprint TEXT
|
|
24
61
|
) STRICT;
|
|
25
62
|
CREATE TABLE IF NOT EXISTS extracted_memories (
|
|
26
63
|
id TEXT NOT NULL, revision INTEGER NOT NULL, session_id TEXT NOT NULL REFERENCES extraction_sessions(session_id),
|
|
@@ -36,6 +73,9 @@ export class ExtractionStore {
|
|
|
36
73
|
if (!this.db.prepare("SELECT 1 FROM pragma_table_info('extraction_sessions') WHERE name='complete_revision'").get()) {
|
|
37
74
|
this.db.exec("ALTER TABLE extraction_sessions ADD COLUMN complete_revision TEXT");
|
|
38
75
|
}
|
|
76
|
+
if (!this.db.prepare("SELECT 1 FROM pragma_table_info('extraction_sessions') WHERE name='policy_fingerprint'").get()) {
|
|
77
|
+
this.db.exec("ALTER TABLE extraction_sessions ADD COLUMN policy_fingerprint TEXT");
|
|
78
|
+
}
|
|
39
79
|
this.db.prepare("INSERT OR IGNORE INTO extraction_worker(id,live_since) VALUES(1,?)").run(Date.now());
|
|
40
80
|
}
|
|
41
81
|
catch (error) {
|
|
@@ -55,21 +95,69 @@ export class ExtractionStore {
|
|
|
55
95
|
const now = Date.now();
|
|
56
96
|
if (!this.db.prepare("UPDATE extraction_worker SET lease_until=? WHERE id=1 AND owner=? AND lease_until>=?")
|
|
57
97
|
.run(now + 180_000, owner, now).changes)
|
|
58
|
-
throw new
|
|
98
|
+
throw new ExtractionLeaseLostError();
|
|
59
99
|
}
|
|
60
100
|
release(owner) { this.db.prepare("UPDATE extraction_worker SET owner=NULL,lease_until=0 WHERE id=1 AND owner=?").run(owner); }
|
|
61
|
-
|
|
62
|
-
this.db.prepare(
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
101
|
+
readCheckpoint(sessionId) {
|
|
102
|
+
const row = this.db.prepare("SELECT cursor,context,extract_since,complete_revision,policy_fingerprint,error FROM extraction_sessions WHERE session_id=?").get(sessionId);
|
|
103
|
+
if (!row)
|
|
104
|
+
return undefined;
|
|
105
|
+
return {
|
|
106
|
+
cursor: row.cursor,
|
|
107
|
+
context: JSON.parse(String(row.context)),
|
|
108
|
+
since: Number(row.extract_since),
|
|
109
|
+
completeRevision: row.complete_revision,
|
|
110
|
+
policyFingerprint: row.policy_fingerprint,
|
|
111
|
+
error: row.error,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
checkpoint(session, owner, since, policyFingerprint) {
|
|
115
|
+
return immediateTransaction(this.db, () => {
|
|
116
|
+
this.renew(owner);
|
|
117
|
+
this.db.prepare(`INSERT INTO extraction_sessions(session_id,metadata,updated_at,extract_since,policy_fingerprint) VALUES(?,?,?,?,?)
|
|
118
|
+
ON CONFLICT(session_id) DO UPDATE SET metadata=excluded.metadata WHERE metadata IS NOT excluded.metadata`)
|
|
119
|
+
.run(session.sessionId, JSON.stringify(session), Date.now(), since ?? this.liveSince(), policyFingerprint ?? null);
|
|
120
|
+
const row = this.db.prepare("SELECT cursor,context,extract_since,complete_revision,policy_fingerprint FROM extraction_sessions WHERE session_id=?").get(session.sessionId);
|
|
121
|
+
const storedCursor = row.cursor;
|
|
122
|
+
const storedCompleteRevision = row.complete_revision;
|
|
123
|
+
const storedPolicy = row.policy_fingerprint;
|
|
124
|
+
if (since !== undefined && since < Number(row.extract_since)) {
|
|
125
|
+
// A broader explicitly approved backfill replays this session. Existing facts are
|
|
126
|
+
// supplied to Luna and exact duplicates are ignored; history is never deleted.
|
|
127
|
+
const nextPolicy = policyFingerprint ?? storedPolicy;
|
|
128
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=NULL,context='[]',complete_revision=NULL,extract_since=?,policy_fingerprint=? WHERE session_id=?")
|
|
129
|
+
.run(since, nextPolicy, session.sessionId);
|
|
130
|
+
return { cursor: null, context: [], since, completeRevision: null, policyFingerprint: nextPolicy };
|
|
131
|
+
}
|
|
132
|
+
if (policyFingerprint !== undefined) {
|
|
133
|
+
const completeRevisionPolicyMismatch = storedCompleteRevision !== null && parseCompleteRevision(storedCompleteRevision)?.policy !== policyFingerprint;
|
|
134
|
+
if ((storedCursor !== null || storedCompleteRevision !== null) && (storedPolicy !== policyFingerprint || completeRevisionPolicyMismatch)) {
|
|
135
|
+
// A prompt or retention-policy change (or unversioned legacy cursor) replays the
|
|
136
|
+
// session from the start with existing facts retained so completion covers the full scan.
|
|
137
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=NULL,context='[]',complete_revision=NULL,policy_fingerprint=? WHERE session_id=?")
|
|
138
|
+
.run(policyFingerprint, session.sessionId);
|
|
139
|
+
return { cursor: null, context: [], since: Number(row.extract_since), completeRevision: null, policyFingerprint };
|
|
140
|
+
}
|
|
141
|
+
if (storedPolicy !== policyFingerprint) {
|
|
142
|
+
this.db.prepare("UPDATE extraction_sessions SET policy_fingerprint=? WHERE session_id=?")
|
|
143
|
+
.run(policyFingerprint, session.sessionId);
|
|
144
|
+
return {
|
|
145
|
+
cursor: storedCursor,
|
|
146
|
+
context: JSON.parse(String(row.context)),
|
|
147
|
+
since: Number(row.extract_since),
|
|
148
|
+
completeRevision: storedCompleteRevision,
|
|
149
|
+
policyFingerprint,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
cursor: storedCursor,
|
|
155
|
+
context: JSON.parse(String(row.context)),
|
|
156
|
+
since: Number(row.extract_since),
|
|
157
|
+
completeRevision: storedCompleteRevision,
|
|
158
|
+
policyFingerprint: storedPolicy,
|
|
159
|
+
};
|
|
160
|
+
});
|
|
73
161
|
}
|
|
74
162
|
records(sessionId, paths) {
|
|
75
163
|
const keys = paths?.filter(path => /^[a-f0-9-]+\/[1-9]\d*$/.test(path)).map(path => path.split("/"));
|
|
@@ -82,20 +170,48 @@ export class ExtractionStore {
|
|
|
82
170
|
.map(r => ({ id: String(r.id), revision: Number(r.revision), text: String(r.text), sessionId: String(r.session_id),
|
|
83
171
|
observedAt: Number(r.observed_at), evidence: JSON.parse(String(r.evidence)), metadata: JSON.parse(String(r.metadata)), judgment: JSON.parse(String(r.judgment)) }));
|
|
84
172
|
}
|
|
85
|
-
reset(sessionId, cursor, owner) {
|
|
173
|
+
reset(sessionId, cursor, owner, policyFingerprint) {
|
|
86
174
|
immediateTransaction(this.db, () => {
|
|
87
175
|
this.renew(owner);
|
|
88
176
|
this.db.prepare("UPDATE extracted_memories SET status='withdrawn' WHERE session_id=? AND status='active'").run(sessionId);
|
|
89
|
-
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context='[]',complete_revision=NULL,error=NULL WHERE session_id=?")
|
|
177
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context='[]',complete_revision=NULL,policy_fingerprint=?,error=NULL,updated_at=? WHERE session_id=?")
|
|
178
|
+
.run(cursor, policyFingerprint ?? null, Date.now(), sessionId);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
assertCheckpointFenced(current, expected, policyFingerprint, completeRevision) {
|
|
182
|
+
if (!current || current.cursor !== expected)
|
|
183
|
+
throw new Error("Extraction checkpoint changed");
|
|
184
|
+
const storedPolicy = current.policy_fingerprint;
|
|
185
|
+
if (policyFingerprint !== undefined) {
|
|
186
|
+
if (expected !== null ? storedPolicy !== policyFingerprint : storedPolicy !== null && storedPolicy !== policyFingerprint) {
|
|
187
|
+
throw new Error("Extraction checkpoint changed");
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const nextPolicy = policyFingerprint ?? storedPolicy;
|
|
191
|
+
if (completeRevision !== undefined) {
|
|
192
|
+
const parsed = parseCompleteRevision(completeRevision);
|
|
193
|
+
if (parsed && parsed.policy !== null && nextPolicy !== parsed.policy) {
|
|
194
|
+
throw new Error("Extraction checkpoint changed");
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return nextPolicy;
|
|
198
|
+
}
|
|
199
|
+
completeEmpty(params) {
|
|
200
|
+
immediateTransaction(this.db, () => {
|
|
201
|
+
this.renew(params.owner);
|
|
202
|
+
const current = this.db.prepare("SELECT cursor,policy_fingerprint FROM extraction_sessions WHERE session_id=?").get(params.sessionId);
|
|
203
|
+
const nextPolicy = this.assertCheckpointFenced(current, params.expected, params.policyFingerprint, params.completeRevision);
|
|
204
|
+
this.db.prepare("UPDATE extraction_sessions SET updated_at=?,complete_revision=?,policy_fingerprint=?,error=NULL WHERE session_id=?")
|
|
205
|
+
.run(Date.now(), params.completeRevision ?? null, nextPolicy, params.sessionId);
|
|
90
206
|
});
|
|
91
207
|
}
|
|
92
208
|
commit(params) {
|
|
93
209
|
return immediateTransaction(this.db, () => {
|
|
94
210
|
let written = 0;
|
|
211
|
+
const replaced = new Set();
|
|
95
212
|
this.renew(params.owner);
|
|
96
|
-
const current = this.db.prepare("SELECT cursor FROM extraction_sessions WHERE session_id=?").get(params.session.sessionId);
|
|
97
|
-
|
|
98
|
-
throw new Error("Extraction checkpoint changed");
|
|
213
|
+
const current = this.db.prepare("SELECT cursor,policy_fingerprint FROM extraction_sessions WHERE session_id=?").get(params.session.sessionId);
|
|
214
|
+
const nextPolicy = this.assertCheckpointFenced(current, params.expected, params.policyFingerprint, params.completeRevision);
|
|
99
215
|
for (const { proposal, observedAt, judgment } of params.accepted) {
|
|
100
216
|
const digest = memoryDigest(proposal.text);
|
|
101
217
|
const duplicate = this.db.prepare("SELECT id FROM extracted_memories WHERE session_id=? AND digest=? AND status='active'")
|
|
@@ -104,10 +220,13 @@ export class ExtractionStore {
|
|
|
104
220
|
continue;
|
|
105
221
|
let id = randomUUID(), revision = 1;
|
|
106
222
|
if (proposal.replaces) {
|
|
223
|
+
if (replaced.has(proposal.replaces))
|
|
224
|
+
throw new Error("Conflicting memory replacement in batch");
|
|
107
225
|
const previous = this.db.prepare("SELECT revision,observed_at FROM extracted_memories WHERE id=? AND session_id=? AND status='active'")
|
|
108
226
|
.get(proposal.replaces, params.session.sessionId);
|
|
109
227
|
if (!previous || Number(previous.observed_at) > observedAt)
|
|
110
228
|
throw new Error("Invalid or stale memory replacement");
|
|
229
|
+
replaced.add(proposal.replaces);
|
|
111
230
|
id = proposal.replaces;
|
|
112
231
|
revision = Number(previous.revision) + 1;
|
|
113
232
|
this.db.prepare("UPDATE extracted_memories SET status='superseded' WHERE id=? AND status='active'").run(id);
|
|
@@ -116,13 +235,16 @@ export class ExtractionStore {
|
|
|
116
235
|
.run(id, revision, params.session.sessionId, proposal.text.trim(), digest, JSON.stringify(proposal.evidence), observedAt, JSON.stringify(judgment), params.version, Date.now());
|
|
117
236
|
written++;
|
|
118
237
|
}
|
|
119
|
-
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context=?,updated_at=?,complete_revision=?,error=NULL WHERE session_id=?")
|
|
120
|
-
.run(params.cursor, JSON.stringify(params.context), Date.now(), params.completeRevision ?? null, params.session.sessionId);
|
|
238
|
+
this.db.prepare("UPDATE extraction_sessions SET cursor=?,context=?,updated_at=?,complete_revision=?,policy_fingerprint=?,error=NULL WHERE session_id=?")
|
|
239
|
+
.run(params.cursor, JSON.stringify(params.context), Date.now(), params.completeRevision ?? null, nextPolicy, params.session.sessionId);
|
|
121
240
|
return written;
|
|
122
241
|
});
|
|
123
242
|
}
|
|
124
|
-
error(sessionId, code) {
|
|
125
|
-
this.db
|
|
243
|
+
error(sessionId, code, owner) {
|
|
244
|
+
immediateTransaction(this.db, () => {
|
|
245
|
+
this.renew(owner);
|
|
246
|
+
this.db.prepare("UPDATE extraction_sessions SET error=?,updated_at=? WHERE session_id=?").run(code, Date.now(), sessionId);
|
|
247
|
+
});
|
|
126
248
|
}
|
|
127
249
|
report() {
|
|
128
250
|
return { memories: this.records(), sessions: this.db.prepare("SELECT session_id,updated_at,error,cursor IS NOT NULL AS checkpointed FROM extraction_sessions").all() };
|
|
@@ -1,15 +1,220 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { extractWithLuna, validateExtractedMemory, EXTRACTION_VERSION } from "./extraction-model.js";
|
|
3
|
-
import { ExtractionStore } from "./extraction-store.js";
|
|
1
|
+
import { abortable } from "./abortable.js";
|
|
2
|
+
import { extractWithLuna, validateExtractedMemory, EXTRACTION_VERSION, } from "./extraction-model.js";
|
|
3
|
+
import { buildCompleteRevision, ExtractionLeaseLostError, extractionPolicyFingerprint, ExtractionStore, } from "./extraction-store.js";
|
|
4
4
|
import { readExtractionPage } from "./extraction-source.js";
|
|
5
5
|
import { extractionHistory, readExtractionChunk } from "./extraction-chunk.js";
|
|
6
|
+
import { resolveDecisionCredential } from "./decision-client.js";
|
|
7
|
+
function handleResetOrMissing(store, sessionId, page, owner, policyFingerprint) {
|
|
8
|
+
if (page.kind !== "reset" && page.kind !== "missing")
|
|
9
|
+
return false;
|
|
10
|
+
store.reset(sessionId, page.kind === "reset" ? (page.cursor ?? null) : null, owner, policyFingerprint);
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
function scoreField(judgment, key) {
|
|
14
|
+
return "scores" in judgment && judgment.scores ? judgment.scores[key] : 0;
|
|
15
|
+
}
|
|
16
|
+
function isBetterReplacement(candidate, incumbent) {
|
|
17
|
+
if (candidate.observedAt !== incumbent.observedAt)
|
|
18
|
+
return candidate.observedAt > incumbent.observedAt;
|
|
19
|
+
for (const key of ["replacement", "supported", "useful"]) {
|
|
20
|
+
const diff = scoreField(candidate.judgment, key) - scoreField(incumbent.judgment, key);
|
|
21
|
+
if (diff !== 0)
|
|
22
|
+
return diff > 0;
|
|
23
|
+
}
|
|
24
|
+
return candidate.order < incumbent.order;
|
|
25
|
+
}
|
|
26
|
+
async function validateProposals(params) {
|
|
27
|
+
const { proposals, messages, newIds, existing, apiKey, config, signal, validate } = params;
|
|
28
|
+
const messageById = new Map(messages.map(m => [m.id, m]));
|
|
29
|
+
const existingById = new Map(existing.map(m => [m.id, m]));
|
|
30
|
+
const standalone = [];
|
|
31
|
+
const winnerByPredecessor = new Map();
|
|
32
|
+
let rejected = 0;
|
|
33
|
+
for (let start = 0; start < proposals.length; start += 4) {
|
|
34
|
+
signal.throwIfAborted();
|
|
35
|
+
// Isolated judgments overlap, but failed chunks drain before their lease is released.
|
|
36
|
+
const judgments = await Promise.allSettled(proposals.slice(start, start + 4).map(async (proposal, offset) => ({
|
|
37
|
+
proposal,
|
|
38
|
+
order: start + offset,
|
|
39
|
+
judgment: await validate({
|
|
40
|
+
proposal,
|
|
41
|
+
messages,
|
|
42
|
+
newIds,
|
|
43
|
+
existing,
|
|
44
|
+
apiKey,
|
|
45
|
+
endpoint: config.decisionModel.endpoint,
|
|
46
|
+
model: config.decisionModel.model,
|
|
47
|
+
signal,
|
|
48
|
+
thresholds: config.extraction,
|
|
49
|
+
}),
|
|
50
|
+
})));
|
|
51
|
+
const failure = judgments.find(result => result.status === "rejected");
|
|
52
|
+
if (failure)
|
|
53
|
+
throw failure.reason;
|
|
54
|
+
for (const result of judgments) {
|
|
55
|
+
if (result.status !== "fulfilled")
|
|
56
|
+
continue;
|
|
57
|
+
const { proposal, judgment, order } = result.value;
|
|
58
|
+
if (!judgment.accepted) {
|
|
59
|
+
rejected++;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
let observedAt = -Infinity;
|
|
63
|
+
let missingEvidence = false;
|
|
64
|
+
const mappedEvidence = [];
|
|
65
|
+
for (const item of proposal.evidence) {
|
|
66
|
+
const message = messageById.get(item.messageId);
|
|
67
|
+
if (!message) {
|
|
68
|
+
missingEvidence = true;
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
if (message.timestamp > observedAt)
|
|
72
|
+
observedAt = message.timestamp;
|
|
73
|
+
mappedEvidence.push({ ...item, messageId: message.sourceMessageId ?? item.messageId });
|
|
74
|
+
}
|
|
75
|
+
if (missingEvidence || !Number.isFinite(observedAt)) {
|
|
76
|
+
rejected++;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const prior = proposal.replaces ? existingById.get(proposal.replaces) : undefined;
|
|
80
|
+
if (proposal.replaces && (!prior || prior.observedAt > observedAt)) {
|
|
81
|
+
rejected++;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const candidate = {
|
|
85
|
+
proposal: { ...proposal, evidence: mappedEvidence },
|
|
86
|
+
judgment,
|
|
87
|
+
observedAt,
|
|
88
|
+
order,
|
|
89
|
+
};
|
|
90
|
+
if (proposal.replaces) {
|
|
91
|
+
const incumbent = winnerByPredecessor.get(proposal.replaces);
|
|
92
|
+
if (!incumbent) {
|
|
93
|
+
winnerByPredecessor.set(proposal.replaces, candidate);
|
|
94
|
+
}
|
|
95
|
+
else {
|
|
96
|
+
if (isBetterReplacement(candidate, incumbent)) {
|
|
97
|
+
winnerByPredecessor.set(proposal.replaces, candidate);
|
|
98
|
+
}
|
|
99
|
+
rejected++;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
else {
|
|
103
|
+
standalone.push(candidate);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const accepted = [...standalone, ...winnerByPredecessor.values()]
|
|
108
|
+
.sort((a, b) => a.order - b.order)
|
|
109
|
+
.map(({ proposal, observedAt, judgment }) => ({ proposal, observedAt, judgment }));
|
|
110
|
+
return { accepted, rejected };
|
|
111
|
+
}
|
|
112
|
+
async function processSession(params) {
|
|
113
|
+
const { session, store, owner, config, agentId, agentName, runtime, since, version, policyFingerprint, apiKey, signal, leaseAbort, readPage, extract, validate, } = params;
|
|
114
|
+
const extractionConfig = config.extraction;
|
|
115
|
+
const checkpoint = store.checkpoint(session, owner, since, policyFingerprint);
|
|
116
|
+
const expectedCompleteRevision = session.sourceRevision === undefined
|
|
117
|
+
? undefined
|
|
118
|
+
: buildCompleteRevision(session.sourceRevision, policyFingerprint);
|
|
119
|
+
if (expectedCompleteRevision !== undefined && checkpoint.completeRevision === expectedCompleteRevision) {
|
|
120
|
+
return { processed: 0, accepted: 0, rejected: 0, unchanged: 1, failed: 0 };
|
|
121
|
+
}
|
|
122
|
+
let stage = "read";
|
|
123
|
+
try {
|
|
124
|
+
const existing = store.records(session.sessionId);
|
|
125
|
+
if (existing.length > 100 || JSON.stringify(existing.map(m => ({ id: m.id, text: m.text }))).length > 40_000) {
|
|
126
|
+
throw new Error("Existing memories exceed review budget");
|
|
127
|
+
}
|
|
128
|
+
const existingFacts = existing.map(m => ({ id: m.id, text: m.text, observedAt: m.observedAt }));
|
|
129
|
+
const page = await readExtractionChunk({
|
|
130
|
+
agentId,
|
|
131
|
+
agentName,
|
|
132
|
+
session,
|
|
133
|
+
cursor: checkpoint.cursor,
|
|
134
|
+
context: extractionHistory(checkpoint.context, extractionConfig.historyMessages),
|
|
135
|
+
existing: existingFacts,
|
|
136
|
+
signal,
|
|
137
|
+
readPage,
|
|
138
|
+
});
|
|
139
|
+
signal.throwIfAborted();
|
|
140
|
+
if (page.kind === "unavailable") {
|
|
141
|
+
store.error(session.sessionId, "source_unavailable", owner);
|
|
142
|
+
return { processed: 1, accepted: 0, rejected: 0, unchanged: 0, failed: 1 };
|
|
143
|
+
}
|
|
144
|
+
if (handleResetOrMissing(store, session.sessionId, page, owner, policyFingerprint)) {
|
|
145
|
+
return { processed: 1, accepted: 0, rejected: 0, unchanged: 0, failed: 0 };
|
|
146
|
+
}
|
|
147
|
+
if (!page.entryCount) {
|
|
148
|
+
store.completeEmpty({
|
|
149
|
+
sessionId: session.sessionId,
|
|
150
|
+
expected: checkpoint.cursor,
|
|
151
|
+
owner,
|
|
152
|
+
completeRevision: page.exhausted ? expectedCompleteRevision : undefined,
|
|
153
|
+
policyFingerprint,
|
|
154
|
+
});
|
|
155
|
+
return { processed: 0, accepted: 0, rejected: 0, unchanged: 1, failed: 0 };
|
|
156
|
+
}
|
|
157
|
+
const freshIds = new Set(page.newIds);
|
|
158
|
+
const messages = page.messages;
|
|
159
|
+
const newIds = messages.filter(m => freshIds.has(m.id) && m.timestamp >= checkpoint.since).map(m => m.id);
|
|
160
|
+
stage = "propose";
|
|
161
|
+
const proposals = newIds.length ? await extract(runtime, agentId, messages, newIds, existingFacts, signal) : [];
|
|
162
|
+
stage = "validate";
|
|
163
|
+
const { accepted, rejected } = await validateProposals({
|
|
164
|
+
proposals,
|
|
165
|
+
messages,
|
|
166
|
+
newIds,
|
|
167
|
+
existing,
|
|
168
|
+
apiKey,
|
|
169
|
+
config,
|
|
170
|
+
signal,
|
|
171
|
+
validate,
|
|
172
|
+
});
|
|
173
|
+
// A branch rewrite during inference invalidates its proposals. Appends are safe and processed next time.
|
|
174
|
+
signal.throwIfAborted();
|
|
175
|
+
const checkPending = readPage(agentId, agentName, session, page.fence, undefined, signal);
|
|
176
|
+
void checkPending.catch(() => { });
|
|
177
|
+
const check = await abortable(checkPending, signal);
|
|
178
|
+
signal.throwIfAborted();
|
|
179
|
+
if (handleResetOrMissing(store, session.sessionId, check, owner, policyFingerprint)) {
|
|
180
|
+
return { processed: 1, accepted: 0, rejected, unchanged: 0, failed: 0 };
|
|
181
|
+
}
|
|
182
|
+
if (check.kind === "unavailable")
|
|
183
|
+
throw new Error("Source changed during extraction");
|
|
184
|
+
const context = extractionHistory(messages, extractionConfig.historyMessages);
|
|
185
|
+
stage = "commit";
|
|
186
|
+
const written = store.commit({
|
|
187
|
+
session,
|
|
188
|
+
expected: checkpoint.cursor,
|
|
189
|
+
cursor: page.cursor,
|
|
190
|
+
context,
|
|
191
|
+
accepted,
|
|
192
|
+
owner,
|
|
193
|
+
version,
|
|
194
|
+
completeRevision: page.exhausted ? expectedCompleteRevision : undefined,
|
|
195
|
+
policyFingerprint,
|
|
196
|
+
});
|
|
197
|
+
return { processed: 1, accepted: written, rejected, unchanged: 0, failed: 0 };
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
if (error instanceof ExtractionLeaseLostError) {
|
|
201
|
+
leaseAbort.abort(error);
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
signal.throwIfAborted();
|
|
205
|
+
store.error(session.sessionId, `${stage}_failed`, owner);
|
|
206
|
+
return { processed: 1, accepted: 0, rejected: 0, unchanged: 0, failed: 1 };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
6
209
|
export async function runExtraction(params) {
|
|
7
210
|
const config = params.config.extraction;
|
|
8
211
|
if (!config.enabled)
|
|
9
212
|
return { status: "disabled" };
|
|
10
|
-
|
|
213
|
+
params.signal.throwIfAborted();
|
|
214
|
+
const apiKey = await abortable(resolveDecisionCredential(params.config.decisionModel), params.signal);
|
|
215
|
+
params.signal.throwIfAborted();
|
|
11
216
|
if (!apiKey)
|
|
12
|
-
return { status: "unavailable", reason: "
|
|
217
|
+
return { status: "unavailable", reason: "Decision model API key not configured" };
|
|
13
218
|
const store = new ExtractionStore(params.storePath);
|
|
14
219
|
const owner = store.claim(params.scheduled ?? false, config.intervalMinutes * 60_000);
|
|
15
220
|
if (!owner) {
|
|
@@ -21,12 +226,23 @@ export async function runExtraction(params) {
|
|
|
21
226
|
const heartbeat = setInterval(() => { try {
|
|
22
227
|
store.renew(owner);
|
|
23
228
|
}
|
|
24
|
-
catch {
|
|
25
|
-
leaseAbort.abort();
|
|
229
|
+
catch (error) {
|
|
230
|
+
leaseAbort.abort(error);
|
|
26
231
|
} }, 30_000);
|
|
27
232
|
heartbeat.unref();
|
|
28
233
|
let processed = 0, acceptedCount = 0, rejectedCount = 0, unchanged = 0, failed = 0;
|
|
29
234
|
const readPage = params.readPage ?? readExtractionPage;
|
|
235
|
+
const extract = params.extract ?? extractWithLuna;
|
|
236
|
+
const validate = params.validate ?? validateExtractedMemory;
|
|
237
|
+
const version = params.version ?? EXTRACTION_VERSION;
|
|
238
|
+
const policyFingerprint = extractionPolicyFingerprint({
|
|
239
|
+
version,
|
|
240
|
+
historyMessages: config.historyMessages,
|
|
241
|
+
minSupport: config.minSupport,
|
|
242
|
+
minRetention: config.minRetention,
|
|
243
|
+
minReplacement: config.minReplacement,
|
|
244
|
+
validatorModel: params.config.decisionModel.model,
|
|
245
|
+
});
|
|
30
246
|
try {
|
|
31
247
|
const sessions = params.sessions();
|
|
32
248
|
const visible = new Set(sessions.map(s => s.sessionId));
|
|
@@ -48,92 +264,29 @@ export async function runExtraction(params) {
|
|
|
48
264
|
continue;
|
|
49
265
|
if (processed >= config.maxBatches)
|
|
50
266
|
break;
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
processed++;
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
if (!page.entryCount) {
|
|
78
|
-
store.db.prepare("UPDATE extraction_sessions SET updated_at=?,complete_revision=? WHERE session_id=?")
|
|
79
|
-
.run(Date.now(), page.exhausted ? session.sourceRevision ?? null : null, session.sessionId);
|
|
80
|
-
unchanged++;
|
|
81
|
-
continue;
|
|
82
|
-
}
|
|
83
|
-
const since = checkpoint.since;
|
|
84
|
-
const freshIds = new Set(page.newIds);
|
|
85
|
-
const fresh = page.messages.filter(m => freshIds.has(m.id) && m.timestamp >= since);
|
|
86
|
-
const messages = page.messages;
|
|
87
|
-
const newIds = fresh.map(m => m.id);
|
|
88
|
-
stage = "propose";
|
|
89
|
-
const proposals = newIds.length ? await (params.extract ?? extractWithLuna)(params.runtime, params.agentId, messages, newIds, existingFacts, signal) : [];
|
|
90
|
-
const accepted = [];
|
|
91
|
-
stage = "validate";
|
|
92
|
-
for (let start = 0; start < proposals.length; start += 4) {
|
|
93
|
-
signal.throwIfAborted();
|
|
94
|
-
// Isolated judgments overlap, but failed chunks drain before their lease is released.
|
|
95
|
-
const judgments = await Promise.allSettled(proposals.slice(start, start + 4).map(async (proposal) => ({ proposal,
|
|
96
|
-
judgment: await (params.validate ?? validateExtractedMemory)({ proposal, messages, newIds, existing, apiKey, signal, thresholds: config }) })));
|
|
97
|
-
const failure = judgments.find(result => result.status === "rejected");
|
|
98
|
-
if (failure)
|
|
99
|
-
throw failure.reason;
|
|
100
|
-
for (const result of judgments) {
|
|
101
|
-
if (result.status !== "fulfilled")
|
|
102
|
-
continue;
|
|
103
|
-
const { proposal, judgment } = result.value;
|
|
104
|
-
const observedAt = judgment.accepted ? Math.max(...proposal.evidence.map(e => messages.find(m => m.id === e.messageId).timestamp)) : 0;
|
|
105
|
-
const prior = existing.find(m => m.id === proposal.replaces);
|
|
106
|
-
if (judgment.accepted && (!prior || prior.observedAt <= observedAt))
|
|
107
|
-
accepted.push({ proposal: { ...proposal,
|
|
108
|
-
evidence: proposal.evidence.map(e => ({ ...e, messageId: messages.find(m => m.id === e.messageId).sourceMessageId ?? e.messageId })) }, judgment, observedAt });
|
|
109
|
-
else
|
|
110
|
-
rejectedCount++;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
// A branch rewrite during inference invalidates its proposals. Appends are safe and processed next time.
|
|
114
|
-
const check = await readPage(params.agentId, params.agentName, session, page.fence);
|
|
115
|
-
if (check.kind === "reset" || check.kind === "missing") {
|
|
116
|
-
store.reset(session.sessionId, check.kind === "reset" ? check.cursor : null, owner);
|
|
117
|
-
processed++;
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
if (check.kind === "unavailable")
|
|
121
|
-
throw new Error("Source changed during extraction");
|
|
122
|
-
signal.throwIfAborted();
|
|
123
|
-
const context = extractionHistory(messages, config.historyMessages);
|
|
124
|
-
stage = "commit";
|
|
125
|
-
const written = store.commit({ session, expected: checkpoint.cursor, cursor: page.cursor,
|
|
126
|
-
context, accepted, owner, version: EXTRACTION_VERSION,
|
|
127
|
-
completeRevision: page.exhausted ? session.sourceRevision : undefined });
|
|
128
|
-
processed++;
|
|
129
|
-
acceptedCount += written;
|
|
130
|
-
}
|
|
131
|
-
catch {
|
|
132
|
-
signal.throwIfAborted();
|
|
133
|
-
failed++;
|
|
134
|
-
processed++;
|
|
135
|
-
store.error(session.sessionId, `${stage}_failed`);
|
|
136
|
-
}
|
|
267
|
+
const outcome = await processSession({
|
|
268
|
+
session,
|
|
269
|
+
store,
|
|
270
|
+
owner,
|
|
271
|
+
config: params.config,
|
|
272
|
+
agentId: params.agentId,
|
|
273
|
+
agentName: params.agentName,
|
|
274
|
+
runtime: params.runtime,
|
|
275
|
+
since: params.since,
|
|
276
|
+
version,
|
|
277
|
+
policyFingerprint,
|
|
278
|
+
apiKey,
|
|
279
|
+
signal,
|
|
280
|
+
leaseAbort,
|
|
281
|
+
readPage,
|
|
282
|
+
extract,
|
|
283
|
+
validate,
|
|
284
|
+
});
|
|
285
|
+
processed += outcome.processed;
|
|
286
|
+
acceptedCount += outcome.accepted;
|
|
287
|
+
rejectedCount += outcome.rejected;
|
|
288
|
+
unchanged += outcome.unchanged;
|
|
289
|
+
failed += outcome.failed;
|
|
137
290
|
}
|
|
138
291
|
return { status: "completed", processed, accepted: acceptedCount, rejected: rejectedCount, unchanged, failed };
|
|
139
292
|
}
|