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