@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
|
@@ -28,7 +28,7 @@ function schemaVersion(db) {
|
|
|
28
28
|
}
|
|
29
29
|
/** Separate analytics tables: never dossier fields or prompt-injection state. */
|
|
30
30
|
function initializeEmotionBaselines(db) {
|
|
31
|
-
if (schemaVersion(db) === 2)
|
|
31
|
+
if (schemaVersion(db) === 2 && tableExists(db, "inside_out_person_generations"))
|
|
32
32
|
return;
|
|
33
33
|
immediateTransaction(db, () => {
|
|
34
34
|
const version = schemaVersion(db);
|
|
@@ -46,6 +46,9 @@ function initializeEmotionBaselines(db) {
|
|
|
46
46
|
id TEXT PRIMARY KEY, interaction_id TEXT NOT NULL, rubric TEXT NOT NULL, grade_signature TEXT NOT NULL,
|
|
47
47
|
assessed_at INTEGER NOT NULL, baseline_id TEXT, person_id TEXT, result_json TEXT NOT NULL
|
|
48
48
|
) STRICT;
|
|
49
|
+
CREATE TABLE IF NOT EXISTS inside_out_person_generations (
|
|
50
|
+
person_id TEXT PRIMARY KEY, generation INTEGER NOT NULL
|
|
51
|
+
) STRICT;
|
|
49
52
|
CREATE INDEX IF NOT EXISTS inside_out_deviations_interaction ON inside_out_deviations(interaction_id,rubric);
|
|
50
53
|
CREATE INDEX IF NOT EXISTS inside_out_deviations_person ON inside_out_deviations(person_id);
|
|
51
54
|
INSERT OR REPLACE INTO memory_schema VALUES ('emotion-baselines',2);`);
|
|
@@ -147,41 +150,108 @@ function compare(row, population, minimum) {
|
|
|
147
150
|
};
|
|
148
151
|
return { status: "ok", count, emotions: perEmotion(deviation) };
|
|
149
152
|
}
|
|
153
|
+
const EMPTY_POPULATION_DIGEST = createHash("sha256").digest("hex");
|
|
154
|
+
function readSnapshot(db, fn) {
|
|
155
|
+
db.exec("BEGIN");
|
|
156
|
+
try {
|
|
157
|
+
const result = fn();
|
|
158
|
+
db.exec("COMMIT");
|
|
159
|
+
return result;
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
db.exec("ROLLBACK");
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
150
166
|
/** Queue writes and commit them in short IMMEDIATE transactions. Only call between completed reads. */
|
|
151
167
|
function batches(db) {
|
|
152
168
|
const pending = [];
|
|
153
169
|
const flush = () => {
|
|
154
170
|
if (!pending.length)
|
|
155
171
|
return;
|
|
172
|
+
const tx = { populationDigests: new Map(), personGenerations: new Map() };
|
|
156
173
|
immediateTransaction(db, () => { for (const write of pending)
|
|
157
|
-
write(); });
|
|
174
|
+
write(tx); });
|
|
158
175
|
pending.length = 0;
|
|
159
176
|
};
|
|
160
177
|
return { write(change) { pending.push(change); if (pending.length >= BATCH)
|
|
161
178
|
flush(); }, flush };
|
|
162
179
|
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
180
|
+
function loadPersonGenerations(db) {
|
|
181
|
+
const generations = new Map();
|
|
182
|
+
for (const row of db.prepare("SELECT person_id,generation FROM inside_out_person_generations").iterate()) {
|
|
183
|
+
generations.set(String(row.person_id), Number(row.generation));
|
|
184
|
+
}
|
|
185
|
+
return generations;
|
|
186
|
+
}
|
|
187
|
+
function getPersonGeneration(tx, readGeneration, personId) {
|
|
188
|
+
let cached = tx.personGenerations.get(personId);
|
|
189
|
+
if (cached === undefined) {
|
|
190
|
+
const row = readGeneration.get(personId);
|
|
191
|
+
cached = row === undefined ? 0 : Number(row.generation);
|
|
192
|
+
tx.personGenerations.set(personId, cached);
|
|
193
|
+
}
|
|
194
|
+
return cached;
|
|
195
|
+
}
|
|
196
|
+
function loadPopulationDigests(db, person, rubric, model, now) {
|
|
197
|
+
if (!tableExists(db, "people"))
|
|
198
|
+
return { totalRows: 0, checkpoints: [] };
|
|
199
|
+
const rows = db.prepare(`SELECT ${GRADE} FROM inside_out e JOIN people p ON p.id=e.person_id
|
|
200
|
+
WHERE e.person_id=? AND e.rubric=? AND e.model=? AND ${COMPARABLE}
|
|
201
|
+
ORDER BY e.target_at,e.interaction_id`).iterate(person, rubric, model, now, now);
|
|
202
|
+
const digest = createHash("sha256");
|
|
203
|
+
const checkpoints = [];
|
|
204
|
+
let totalRows = 0;
|
|
205
|
+
let currentEnd;
|
|
206
|
+
for (const row of rows) {
|
|
207
|
+
const rowEnd = weekStart(Number(row.target_at)) + WEEK;
|
|
208
|
+
if (currentEnd !== undefined && rowEnd !== currentEnd) {
|
|
209
|
+
checkpoints.push({ end: currentEnd, digest: digest.copy().digest("hex") });
|
|
210
|
+
}
|
|
211
|
+
currentEnd = rowEnd;
|
|
212
|
+
digest.update(`|${gradeSignature(row)}`);
|
|
213
|
+
totalRows++;
|
|
214
|
+
}
|
|
215
|
+
if (currentEnd !== undefined) {
|
|
216
|
+
checkpoints.push({ end: currentEnd, digest: digest.digest("hex") });
|
|
217
|
+
}
|
|
218
|
+
return { totalRows, checkpoints };
|
|
219
|
+
}
|
|
220
|
+
function getPopulationDigests(tx, db, person, rubric, model, now) {
|
|
221
|
+
const key = JSON.stringify([person, rubric, model]);
|
|
222
|
+
let cached = tx.populationDigests.get(key);
|
|
223
|
+
if (!cached) {
|
|
224
|
+
cached = loadPopulationDigests(db, person, rubric, model, now);
|
|
225
|
+
tx.populationDigests.set(key, cached);
|
|
226
|
+
}
|
|
227
|
+
return cached;
|
|
228
|
+
}
|
|
229
|
+
function populationPrefixDigest(tx, db, person, rubric, model, now, end) {
|
|
230
|
+
const cached = getPopulationDigests(tx, db, person, rubric, model, now);
|
|
231
|
+
if (cached.totalRows === 0)
|
|
232
|
+
return end === Infinity ? EMPTY_POPULATION_DIGEST : null;
|
|
233
|
+
let match = null;
|
|
234
|
+
for (const checkpoint of cached.checkpoints) {
|
|
235
|
+
if (checkpoint.end <= end)
|
|
236
|
+
match = checkpoint.digest;
|
|
237
|
+
else
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
return match;
|
|
241
|
+
}
|
|
242
|
+
function createGradeAssessor(db, queue, options, personGenerationMatches, onComparison) {
|
|
243
|
+
const { now, minimum, recompare } = options;
|
|
175
244
|
const prior = db.prepare(`SELECT id,result_json,json_extract(result_json,'$.status') status FROM inside_out_deviations
|
|
176
245
|
WHERE interaction_id=? AND rubric=? AND grade_signature=? ORDER BY assessed_at DESC,rowid DESC LIMIT 1`);
|
|
177
246
|
const save = db.prepare("INSERT OR IGNORE INTO inside_out_deviations VALUES (?,?,?,?,?,?,?,?)");
|
|
178
247
|
const grade = db.prepare(`SELECT ${GRADE} FROM inside_out WHERE interaction_id=? AND rubric=?`);
|
|
179
|
-
|
|
248
|
+
return (row, signature, decide, fence) => {
|
|
180
249
|
const previous = prior.get(row.interaction_id, row.rubric, signature);
|
|
181
250
|
// An existing assessment stands for its grade, except future_time: that only described the clock.
|
|
182
|
-
if (!
|
|
251
|
+
if (!recompare && previous && previous.status !== "future_time")
|
|
183
252
|
return;
|
|
184
|
-
const
|
|
253
|
+
const personId = row.person_id === null ? null : String(row.person_id);
|
|
254
|
+
const result = { version: VERSION, status: "insufficient_history", personId,
|
|
185
255
|
baselineId: null, baselineEnd: null, assessedAt: now, minInteractions: minimum, cumulative: null, weekly: null };
|
|
186
256
|
decide(result);
|
|
187
257
|
const key = (assessment) => jsonHash([assessment.version, signature, assessment.baselineId, assessment.status, assessment.minInteractions]);
|
|
@@ -190,92 +260,102 @@ export function refreshEmotionBaselines(db, options) {
|
|
|
190
260
|
// Chaining records permits an explicit return to an earlier baseline without
|
|
191
261
|
// selecting an obsolete intervening assessment or losing either observation.
|
|
192
262
|
const id = jsonHash([key(result), previous?.id ?? null]);
|
|
193
|
-
queue.write(
|
|
194
|
-
// Rechecked under the write lock: a purge, regrade
|
|
263
|
+
queue.write(tx => {
|
|
264
|
+
// Rechecked under the write lock: a purge, regrade, relink, or population-prefix change wins.
|
|
265
|
+
if (personId !== null && !personGenerationMatches(tx, personId))
|
|
266
|
+
return;
|
|
267
|
+
if (fence && !fence(tx))
|
|
268
|
+
return;
|
|
195
269
|
const current = grade.get(row.interaction_id, row.rubric);
|
|
196
270
|
if (!current || gradeSignature(current) !== signature)
|
|
197
271
|
return;
|
|
198
|
-
|
|
272
|
+
onComparison(Number(save.run(id, row.interaction_id, row.rubric, signature, now, result.baselineId, result.personId, JSON.stringify(result)).changes));
|
|
199
273
|
});
|
|
200
274
|
};
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
275
|
+
}
|
|
276
|
+
function* iterateComparableGrades(page, person, rubric, model, now) {
|
|
277
|
+
let last;
|
|
278
|
+
for (;;) {
|
|
279
|
+
const batch = page.all(person, rubric, model, now, now, last?.target_at ?? null, last?.target_at ?? null, last?.target_at ?? null, last?.interaction_id ?? null, PAGE);
|
|
280
|
+
yield* batch;
|
|
281
|
+
if (batch.length < PAGE)
|
|
282
|
+
return;
|
|
283
|
+
last = batch.at(-1);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function refreshPopulation(db, queue, assess, statements, group, options, personGenerationMatches, onSnapshot) {
|
|
287
|
+
const { person, rubric, model } = group;
|
|
288
|
+
const personId = String(person);
|
|
289
|
+
const { now, cutoff, minimum } = options;
|
|
290
|
+
const existing = new Map(statements.stored.all(person, rubric, model).map(row => [Number(row.week_start), String(row.id)]));
|
|
291
|
+
const source = iterateComparableGrades(statements.page, person, rubric, model, now);
|
|
292
|
+
let next = source.next(), previous;
|
|
293
|
+
const cumulative = histograms(), current = new Set();
|
|
294
|
+
const seenDigest = createHash("sha256");
|
|
295
|
+
let seenCount = 0;
|
|
296
|
+
for (let start = next.done ? cutoff : weekStart(Number(next.value.target_at)); !next.done || start < cutoff; start += WEEK) {
|
|
297
|
+
const end = start + WEEK, weekly = histograms(), signatures = [];
|
|
298
|
+
const previousEnd = previous ? previous.end : start;
|
|
299
|
+
const previousExpectedPrefix = previous ? previous.expectedPrefix : null;
|
|
300
|
+
const prefixFence = tx => populationPrefixDigest(tx, db, person, rubric, model, now, previousEnd) === previousExpectedPrefix;
|
|
301
|
+
// Grades compare only with completed weeks before their own; this week joins afterwards.
|
|
302
|
+
let frozen;
|
|
303
|
+
while (!next.done && Number(next.value.target_at) < end) {
|
|
304
|
+
const row = next.value, signature = gradeSignature(row);
|
|
305
|
+
seenDigest.update(`|${signature}`);
|
|
306
|
+
seenCount++;
|
|
307
|
+
assess(row, signature, result => {
|
|
308
|
+
if (!previous)
|
|
309
|
+
return;
|
|
310
|
+
frozen ??= { cumulative: ranks(cumulative), weekly: ranks(previous.weekly) };
|
|
311
|
+
result.baselineId = previous.id;
|
|
312
|
+
result.baselineEnd = previous.end;
|
|
313
|
+
result.cumulative = compare(row, frozen.cumulative, minimum);
|
|
314
|
+
result.weekly = compare(row, frozen.weekly, minimum);
|
|
315
|
+
result.status = result.cumulative.status;
|
|
316
|
+
}, prefixFence);
|
|
317
|
+
if (start < cutoff) {
|
|
318
|
+
signatures.push(signature);
|
|
319
|
+
add(weekly, row);
|
|
226
320
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
});
|
|
246
|
-
if (start < cutoff) {
|
|
247
|
-
signatures.push(signature);
|
|
248
|
-
add(weekly, row);
|
|
249
|
-
}
|
|
250
|
-
next = source.next();
|
|
321
|
+
next = source.next();
|
|
322
|
+
}
|
|
323
|
+
if (start >= cutoff)
|
|
324
|
+
continue;
|
|
325
|
+
merge(cumulative, weekly);
|
|
326
|
+
// Chained ids address the whole cumulative population without rehashing earlier weeks.
|
|
327
|
+
// Empty weeks are kept: a weekly comparison always means the preceding calendar week.
|
|
328
|
+
const id = jsonHash([VERSION, person, rubric, model, start, previous?.id ?? null, signatures]), json = encode(weekly);
|
|
329
|
+
const expectedPrefix = seenDigest.copy().digest("hex");
|
|
330
|
+
current.add(start);
|
|
331
|
+
if (existing.get(start) !== id) {
|
|
332
|
+
const hasSeenGrades = seenCount > 0;
|
|
333
|
+
queue.write(tx => {
|
|
334
|
+
// Fence against concurrent purges, relinks, regrades, or new grades affecting this week's prefix.
|
|
335
|
+
if (hasSeenGrades &&
|
|
336
|
+
personGenerationMatches(tx, personId) &&
|
|
337
|
+
populationPrefixDigest(tx, db, person, rubric, model, now, end) === expectedPrefix) {
|
|
338
|
+
onSnapshot(Number(statements.upsert.run(person, rubric, model, start, id, VERSION, end, now, json).changes));
|
|
251
339
|
}
|
|
252
|
-
|
|
253
|
-
continue;
|
|
254
|
-
merge(cumulative, weekly);
|
|
255
|
-
// Chained ids address the whole cumulative population without rehashing earlier weeks.
|
|
256
|
-
// Empty weeks are kept: a weekly comparison always means the preceding calendar week.
|
|
257
|
-
const id = jsonHash([VERSION, person, rubric, model, start, previous?.id ?? null, signatures]), json = encode(weekly);
|
|
258
|
-
current.add(start);
|
|
259
|
-
if (existing.get(start) !== id)
|
|
260
|
-
queue.write(() => {
|
|
261
|
-
// A purge of this person since the read leaves no linked grades: never restore their distribution.
|
|
262
|
-
if (populated.get(person, rubric, model))
|
|
263
|
-
snapshots += Number(upsert.run(person, rubric, model, start, id, VERSION, end, now, json).changes);
|
|
264
|
-
});
|
|
265
|
-
previous = { id, end, weekly };
|
|
266
|
-
}
|
|
267
|
-
// Weeks no longer backed by linked grades are replaced, not retained as revisions.
|
|
268
|
-
for (const [start, id] of existing)
|
|
269
|
-
if (!current.has(start))
|
|
270
|
-
queue.write(() => { remove.run(person, rubric, model, start, id); });
|
|
340
|
+
});
|
|
271
341
|
}
|
|
342
|
+
previous = { id, end, weekly, expectedPrefix };
|
|
272
343
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
for (const
|
|
276
|
-
if (!
|
|
277
|
-
queue.write(
|
|
344
|
+
const expectedFull = seenDigest.digest("hex");
|
|
345
|
+
// Weeks no longer backed by linked grades are replaced, not retained as revisions.
|
|
346
|
+
for (const [start, id] of existing) {
|
|
347
|
+
if (!current.has(start)) {
|
|
348
|
+
queue.write(tx => {
|
|
349
|
+
if (personGenerationMatches(tx, personId) &&
|
|
350
|
+
populationPrefixDigest(tx, db, person, rubric, model, now, Infinity) === expectedFull) {
|
|
351
|
+
statements.remove.run(person, rubric, model, start, id);
|
|
352
|
+
}
|
|
353
|
+
});
|
|
354
|
+
}
|
|
278
355
|
}
|
|
356
|
+
}
|
|
357
|
+
function assessNonComparableGrades(db, queue, assess, options) {
|
|
358
|
+
const { people, now } = options;
|
|
279
359
|
// Everything not comparable records an explicit status, never a neutral score.
|
|
280
360
|
const comparable = people ? `coalesce(${COMPARABLE} AND EXISTS (SELECT 1 FROM people p WHERE p.id=e.person_id),0)` : "0";
|
|
281
361
|
const linked = people ? db.prepare("SELECT 1 FROM people WHERE id=?") : undefined;
|
|
@@ -300,6 +380,57 @@ export function refreshEmotionBaselines(db, options) {
|
|
|
300
380
|
last = Number(batch.at(-1)._rowid);
|
|
301
381
|
queue.flush();
|
|
302
382
|
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* One current, content-addressed snapshot per person, rubric, model and completed week.
|
|
386
|
+
* Reads finish before each batch commits, so the shared store is never held for a whole pass.
|
|
387
|
+
* No inference and no changes to raw grades.
|
|
388
|
+
*/
|
|
389
|
+
export function refreshEmotionBaselines(db, options) {
|
|
390
|
+
const now = options.now ?? Date.now(), cutoff = weekStart(now), minimum = options.minInteractions;
|
|
391
|
+
if (!Number.isFinite(now) || !Number.isInteger(minimum) || minimum < 1)
|
|
392
|
+
throw new Error("Invalid baseline settings");
|
|
393
|
+
initializeEmotionBaselines(db);
|
|
394
|
+
const expectedGenerations = options.expectedGenerations ?? loadPersonGenerations(db);
|
|
395
|
+
const readGeneration = db.prepare("SELECT generation FROM inside_out_person_generations WHERE person_id=?");
|
|
396
|
+
const personGenerationMatches = (tx, personId) => getPersonGeneration(tx, readGeneration, personId) === (expectedGenerations.get(personId) ?? 0);
|
|
397
|
+
let snapshots = 0, comparisons = 0;
|
|
398
|
+
const queue = batches(db), people = tableExists(db, "people");
|
|
399
|
+
const assess = createGradeAssessor(db, queue, { now, minimum, recompare: options.recompare }, personGenerationMatches, changes => { comparisons += changes; });
|
|
400
|
+
const populations = new Set();
|
|
401
|
+
if (people) {
|
|
402
|
+
const statements = {
|
|
403
|
+
stored: db.prepare("SELECT week_start,id FROM person_emotion_baselines WHERE person_id=? AND rubric=? AND model=?"),
|
|
404
|
+
upsert: db.prepare(`INSERT INTO person_emotion_baselines VALUES (?,?,?,?,?,?,?,?,?)
|
|
405
|
+
ON CONFLICT(person_id,rubric,model,week_start) DO UPDATE SET id=excluded.id,version=excluded.version,
|
|
406
|
+
week_end=excluded.week_end,computed_at=excluded.computed_at,weekly_json=excluded.weekly_json`),
|
|
407
|
+
remove: db.prepare("DELETE FROM person_emotion_baselines WHERE person_id=? AND rubric=? AND model=? AND week_start=? AND id=?"),
|
|
408
|
+
page: db.prepare(`SELECT ${GRADE} FROM inside_out e WHERE e.person_id=? AND e.rubric=? AND e.model=? AND ${COMPARABLE}
|
|
409
|
+
AND (? IS NULL OR e.target_at>? OR (e.target_at=? AND e.interaction_id>?)) ORDER BY e.target_at,e.interaction_id LIMIT ?`),
|
|
410
|
+
};
|
|
411
|
+
const groups = db.prepare(`SELECT DISTINCT e.person_id,e.rubric,e.model FROM inside_out e JOIN people p ON p.id=e.person_id
|
|
412
|
+
WHERE ${COMPARABLE}`).all(now, now);
|
|
413
|
+
for (const group of groups) {
|
|
414
|
+
const { person_id: person, rubric, model } = group;
|
|
415
|
+
populations.add(JSON.stringify([person, rubric, model]));
|
|
416
|
+
refreshPopulation(db, queue, assess, statements, { person, rubric, model }, { now, cutoff, minimum }, personGenerationMatches, changes => { snapshots += changes; });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
// Populations without linked grades (removed identity or person) lose their snapshots.
|
|
420
|
+
const drop = db.prepare("DELETE FROM person_emotion_baselines WHERE person_id=? AND rubric=? AND model=?");
|
|
421
|
+
for (const row of db.prepare("SELECT DISTINCT person_id,rubric,model FROM person_emotion_baselines").all()) {
|
|
422
|
+
if (!populations.has(JSON.stringify([row.person_id, row.rubric, row.model]))) {
|
|
423
|
+
const personId = String(row.person_id);
|
|
424
|
+
queue.write(tx => {
|
|
425
|
+
// Fence against concurrent purges, links, or new grades populating this person since the scan.
|
|
426
|
+
if (personGenerationMatches(tx, personId) &&
|
|
427
|
+
getPopulationDigests(tx, db, row.person_id, row.rubric, row.model, now).totalRows === 0) {
|
|
428
|
+
drop.run(row.person_id, row.rubric, row.model);
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
assessNonComparableGrades(db, queue, assess, { people, now });
|
|
303
434
|
queue.flush();
|
|
304
435
|
return { snapshots, comparisons };
|
|
305
436
|
}
|
|
@@ -330,13 +461,7 @@ export function emotionBaselineHistory(db, options = {}) {
|
|
|
330
461
|
if (schemaVersion(db) !== 2)
|
|
331
462
|
return [];
|
|
332
463
|
// One read snapshot: a concurrent refresh may replace or drop weeks between the two queries.
|
|
333
|
-
db
|
|
334
|
-
try {
|
|
335
|
-
return readBaselineHistory(db, options, limit);
|
|
336
|
-
}
|
|
337
|
-
finally {
|
|
338
|
-
db.exec("COMMIT");
|
|
339
|
-
}
|
|
464
|
+
return readSnapshot(db, () => readBaselineHistory(db, options, limit));
|
|
340
465
|
}
|
|
341
466
|
function readBaselineHistory(db, options, limit) {
|
|
342
467
|
const selected = db.prepare(`SELECT person_id,rubric,model,week_start FROM person_emotion_baselines
|
|
@@ -365,28 +490,97 @@ function readBaselineHistory(db, options, limit) {
|
|
|
365
490
|
}
|
|
366
491
|
return selected.map(row => snapshots.get(JSON.stringify([JSON.stringify([row.person_id, row.rubric, row.model]), row.week_start])));
|
|
367
492
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
493
|
+
function computeBaselineInputSnapshot(db, options) {
|
|
494
|
+
const digest = createHash("sha256").update(JSON.stringify([VERSION, weekStart(options.now), options.minInteractions]));
|
|
495
|
+
if (tableExists(db, "people")) {
|
|
496
|
+
let count = 0;
|
|
497
|
+
digest.update("|people:");
|
|
498
|
+
for (const row of db.prepare("SELECT id FROM people ORDER BY id").iterate()) {
|
|
499
|
+
digest.update(`${JSON.stringify(row.id)},`);
|
|
500
|
+
count++;
|
|
501
|
+
}
|
|
502
|
+
digest.update(`#${count}`);
|
|
503
|
+
}
|
|
504
|
+
else {
|
|
505
|
+
digest.update("|people:-1");
|
|
506
|
+
}
|
|
507
|
+
if (tableExists(db, "person_identities")) {
|
|
508
|
+
let count = 0;
|
|
509
|
+
digest.update("|identities:");
|
|
510
|
+
for (const row of db.prepare("SELECT rowid,person_id,provider,account_scope,external_id FROM person_identities ORDER BY rowid").iterate()) {
|
|
511
|
+
digest.update(`${JSON.stringify([row.rowid, row.person_id, row.provider, row.account_scope, row.external_id])},`);
|
|
512
|
+
count++;
|
|
513
|
+
}
|
|
514
|
+
digest.update(`#${count}`);
|
|
515
|
+
}
|
|
516
|
+
else {
|
|
517
|
+
digest.update("|identities:-1");
|
|
376
518
|
}
|
|
377
519
|
if (tableExists(db, "inside_out")) {
|
|
378
520
|
const timing = db.prepare("SELECT count(*) n,sum(target_at<=?) due,sum(reviewed_at<=?) reviewed FROM inside_out").get(options.now, options.now);
|
|
379
|
-
digest.update(
|
|
380
|
-
// Regrades rewrite reviewed_at; links and purges rewrite person_id and error.
|
|
381
|
-
for (const row of db.prepare("SELECT rowid,person_id,reviewed_at,error
|
|
382
|
-
digest.update(`|${row.rowid
|
|
521
|
+
digest.update(`|grades:${timing.n},${timing.due},${timing.reviewed}`);
|
|
522
|
+
// Regrades rewrite reviewed_at; links, time edits and purges rewrite person_id, target_at and error.
|
|
523
|
+
for (const row of db.prepare("SELECT rowid,person_id,target_at,reviewed_at,error FROM inside_out ORDER BY rowid").iterate()) {
|
|
524
|
+
digest.update(`|${JSON.stringify([row.rowid, row.person_id, row.target_at, row.reviewed_at, row.error])}`);
|
|
383
525
|
}
|
|
384
526
|
}
|
|
527
|
+
else {
|
|
528
|
+
digest.update("|grades:-1");
|
|
529
|
+
}
|
|
530
|
+
const personGenerations = new Map();
|
|
531
|
+
digest.update("|generations:");
|
|
532
|
+
let generationCount = 0;
|
|
533
|
+
if (tableExists(db, "inside_out_person_generations")) {
|
|
534
|
+
for (const row of db.prepare("SELECT person_id,generation FROM inside_out_person_generations ORDER BY person_id").iterate()) {
|
|
535
|
+
const personId = String(row.person_id);
|
|
536
|
+
const generation = Number(row.generation);
|
|
537
|
+
personGenerations.set(personId, generation);
|
|
538
|
+
digest.update(`${JSON.stringify([personId, generation])},`);
|
|
539
|
+
generationCount++;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
digest.update(`#${generationCount}`);
|
|
543
|
+
return { inputFingerprint: digest.digest("hex"), personGenerations };
|
|
544
|
+
}
|
|
545
|
+
function computeBaselineFingerprintFromInput(db, inputFingerprint) {
|
|
546
|
+
const digest = createHash("sha256").update(JSON.stringify([inputFingerprint, schemaVersion(db) ?? null]));
|
|
547
|
+
for (const table of ["person_emotion_baselines", "inside_out_deviations"]) {
|
|
548
|
+
digest.update(`|${tableExists(db, table) ? Number(db.prepare(`SELECT count(*) n FROM ${table}`).get().n) : -1}`);
|
|
549
|
+
}
|
|
385
550
|
return digest.digest("hex");
|
|
386
551
|
}
|
|
552
|
+
/**
|
|
553
|
+
* Snapshot of refresh inputs only (settings, current week, People tables, grades, and purge generations).
|
|
554
|
+
* Captures input fingerprint and per-person purge generations in one read snapshot so purges committing
|
|
555
|
+
* after the pre-pass snapshot are fenced out before refreshEmotionBaselines runs.
|
|
556
|
+
*/
|
|
557
|
+
export function baselineInputSnapshot(db, options) {
|
|
558
|
+
return readSnapshot(db, () => computeBaselineInputSnapshot(db, options));
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Computes input fingerprint, full fingerprint, and purge generations inside one consistent SQLite
|
|
562
|
+
* read snapshot so pre-pass fencing and post-pass certification never mix pre- and post-commit state.
|
|
563
|
+
*/
|
|
564
|
+
export function baselineFingerprints(db, options) {
|
|
565
|
+
return readSnapshot(db, () => {
|
|
566
|
+
const { inputFingerprint, personGenerations } = computeBaselineInputSnapshot(db, options);
|
|
567
|
+
return {
|
|
568
|
+
inputFingerprint,
|
|
569
|
+
fullFingerprint: computeBaselineFingerprintFromInput(db, inputFingerprint),
|
|
570
|
+
personGenerations,
|
|
571
|
+
};
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Changes whenever a refresh input could: grades, links, people, purge generations, stored results,
|
|
576
|
+
* the current week, grades crossing `now`, or settings. Equal fingerprints mean a refresh would write nothing.
|
|
577
|
+
*/
|
|
578
|
+
export function baselineFingerprint(db, options) {
|
|
579
|
+
return baselineFingerprints(db, options).fullFingerprint;
|
|
580
|
+
}
|
|
387
581
|
/**
|
|
388
582
|
* Delete one person's baselines and assessment history. With `grades`, also erase their six
|
|
389
|
-
* probabilities and person link, keeping a tombstone so the reply is never sent to
|
|
583
|
+
* probabilities and person link, keeping a tombstone so the reply is never sent to the decision model again.
|
|
390
584
|
*/
|
|
391
585
|
export function purgeEmotionProfile(db, personId, options = {}) {
|
|
392
586
|
const counts = { baselines: 0, assessments: 0, grades: 0 };
|
|
@@ -394,6 +588,8 @@ export function purgeEmotionProfile(db, personId, options = {}) {
|
|
|
394
588
|
return counts;
|
|
395
589
|
initializeEmotionBaselines(db);
|
|
396
590
|
return immediateTransaction(db, () => {
|
|
591
|
+
db.prepare(`INSERT INTO inside_out_person_generations (person_id, generation) VALUES (?, 1)
|
|
592
|
+
ON CONFLICT(person_id) DO UPDATE SET generation = generation + 1`).run(personId);
|
|
397
593
|
if (options.grades) {
|
|
398
594
|
counts.assessments += Number(db.prepare(`DELETE FROM inside_out_deviations WHERE (interaction_id,rubric) IN
|
|
399
595
|
(SELECT interaction_id,rubric FROM inside_out WHERE person_id=?)`).run(personId).changes);
|
|
@@ -11,6 +11,8 @@ export declare function reviewIndexedClaim(params: {
|
|
|
11
11
|
claim: string;
|
|
12
12
|
citations: readonly EvidenceCitation[];
|
|
13
13
|
apiKey: string;
|
|
14
|
+
endpoint?: string;
|
|
15
|
+
model?: string;
|
|
14
16
|
timeoutMs: number;
|
|
15
17
|
signal: AbortSignal;
|
|
16
18
|
personBackground?: {
|
|
@@ -35,17 +37,29 @@ export declare function reviewIndexedClaim(params: {
|
|
|
35
37
|
}[];
|
|
36
38
|
policy: string;
|
|
37
39
|
scope: string;
|
|
38
|
-
|
|
39
|
-
|
|
40
|
+
verdict: "supports" | "contradicts" | "insufficient_evidence";
|
|
41
|
+
confidence: number;
|
|
42
|
+
probabilities: Record<"supports" | "contradicts" | "insufficient_evidence", number>;
|
|
43
|
+
background: {
|
|
40
44
|
backgroundOnly: number;
|
|
41
45
|
explicitSupport: number;
|
|
42
|
-
}
|
|
46
|
+
};
|
|
47
|
+
needsReview: boolean;
|
|
48
|
+
status: "ok";
|
|
49
|
+
} | {
|
|
50
|
+
evidence: {
|
|
51
|
+
path: string;
|
|
52
|
+
from: number;
|
|
53
|
+
lines: number;
|
|
54
|
+
documentHash: string;
|
|
55
|
+
excerptHash: string;
|
|
56
|
+
}[];
|
|
57
|
+
policy: string;
|
|
58
|
+
scope: string;
|
|
43
59
|
verdict: "supports" | "contradicts" | "insufficient_evidence";
|
|
44
60
|
confidence: number;
|
|
45
|
-
probabilities:
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
insufficient_evidence: number;
|
|
49
|
-
};
|
|
61
|
+
probabilities: Record<"supports" | "contradicts" | "insufficient_evidence", number>;
|
|
62
|
+
needsReview: boolean;
|
|
63
|
+
background?: undefined;
|
|
50
64
|
status: "ok";
|
|
51
65
|
}>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { parseSafeVirtualPath } from "./sources.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { decisionModelScope, DEFAULT_DECISION_MODEL } from "./decision-client.js";
|
|
4
|
+
import { reviewClaim } from "./decision-review.js";
|
|
5
5
|
export async function reviewIndexedClaim(params) {
|
|
6
6
|
const unavailable = (reason) => ({ status: "unavailable", verdict: "insufficient_evidence", needsReview: true, reason });
|
|
7
7
|
if (!params.claim.trim() || params.claim.length > 2000 || !params.citations.length || params.citations.length > 3)
|
|
@@ -35,7 +35,7 @@ export async function reviewIndexedClaim(params) {
|
|
|
35
35
|
const { evidence } = snapshot;
|
|
36
36
|
if (evidence.reduce((sum, item) => sum + item.text.length, 0) > 6000)
|
|
37
37
|
return unavailable("Evidence exceeds 6000 characters; choose a narrower complete passage");
|
|
38
|
-
const judgment = await
|
|
38
|
+
const judgment = await reviewClaim({ ...params, evidence: evidence.map(item => item.text) });
|
|
39
39
|
params.signal.throwIfAborted();
|
|
40
40
|
return read(() => {
|
|
41
41
|
for (const item of evidence) {
|
|
@@ -46,7 +46,7 @@ export async function reviewIndexedClaim(params) {
|
|
|
46
46
|
}
|
|
47
47
|
return { status: "ok", ...judgment,
|
|
48
48
|
evidence: evidence.map(({ text: _text, ...citation }) => citation),
|
|
49
|
-
policy: `${
|
|
49
|
+
policy: `${decisionModelScope(params.model ?? DEFAULT_DECISION_MODEL, params.endpoint)}:${params.personBackground?.kind === "interaction" ? "person-interaction-v1" : params.personBackground ? "person-background-v2" : "claim-v1"}`,
|
|
50
50
|
scope: "Advisory support check against cited indexed excerpts only, not current truth or authorization to write. Verify original sources and identity before promotion." };
|
|
51
51
|
});
|
|
52
52
|
}
|