@gamaze/hicortex 0.25.0 → 0.26.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.
@@ -0,0 +1,826 @@
1
+ "use strict";
2
+ /**
3
+ * Quality scoreboard (#578) — the Memory Precision card as a standing quality
4
+ * instrument. Everything here is OFF the request path by construction:
5
+ *
6
+ * - Tier-1 deterministic metrics (block size, cross-project share +
7
+ * attribution coverage, sub-bar share, distinct-memory recycling) are
8
+ * computed from the #476 event store at RENDER time (handleDashboardData)
9
+ * and stamped into the nightly snapshot by the snapshot writer.
10
+ * - The corpus-health trio (near-duplicate cluster count, scope-anchor
11
+ * rate, canonical-label integrity) is computed by the NIGHTLY snapshot
12
+ * writer ONLY — the dup-cluster count re-runs the dedup clustering over
13
+ * every vector, far too heavy per dashboard load — and renders from the
14
+ * snapshot series, never per-request.
15
+ * - The weekly auto-grading pass runs inside the nightly, gated by a
16
+ * state.json week cursor, on its own call lane. NO grading code is
17
+ * reachable from any HTTP handler.
18
+ *
19
+ * Layering (the recall-precision.ts law): pure functions over the db handle
20
+ * + injectable seams (fetch, clock, cap, logger) so tests exercise every
21
+ * failure mode without HTTP, keys, or live calls; dashboard.ts holds only the
22
+ * express adapters; mcp-server.ts only the routes.
23
+ *
24
+ * Threshold-free storage (the #476 law): verdict rows carry RAW score +
25
+ * confidence; "useful" and "contested" derive at render from
26
+ * QUALITY_USEFUL_SCORE / QUALITY_CONTESTED_CONFIDENCE, so recalibration never
27
+ * rewrites history.
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.OPENROUTER_KEY_NAME = exports.GradeEmptyAnswersError = exports.QUALITY_GRADE_DECISIONS_URL = void 0;
31
+ exports.windowStartDay = windowStartDay;
32
+ exports.computeTier1Metrics = computeTier1Metrics;
33
+ exports.readQualityTier1 = readQualityTier1;
34
+ exports.readQualityChanges = readQualityChanges;
35
+ exports.computeCorpusHealth = computeCorpusHealth;
36
+ exports.readGradedAggregate = readGradedAggregate;
37
+ exports.buildQualitySnapshotBlock = buildQualitySnapshotBlock;
38
+ exports.createGradeClient = createGradeClient;
39
+ exports.readOpenRouterKey = readOpenRouterKey;
40
+ exports.insertVerdictRow = insertVerdictRow;
41
+ exports.isoWeekKey = isoWeekKey;
42
+ exports.runQualityGradeStage = runQualityGradeStage;
43
+ exports.listContestedVerdicts = listContestedVerdicts;
44
+ exports.recordOwnerVerdict = recordOwnerVerdict;
45
+ const node_fs_1 = require("node:fs");
46
+ const node_path_1 = require("node:path");
47
+ const calibration_js_1 = require("./calibration.js");
48
+ const config_read_js_1 = require("./config-read.js");
49
+ const dedup_js_1 = require("./dedup.js");
50
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
51
+ const redact_js_1 = require("./redact.js");
52
+ const recall_index_js_1 = require("./recall-index.js");
53
+ const DAY_MS = 86_400_000;
54
+ const round4 = (v) => Math.round(v * 10000) / 10000;
55
+ /** Inclusive window start (UTC YYYY-MM-DD) for an N-day window: today counts
56
+ * as day 1 — the readMemoryPrecision day-bucket convention. */
57
+ function windowStartDay(now, windowDays) {
58
+ return new Date(now.getTime() - (windowDays - 1) * DAY_MS).toISOString().slice(0, 10);
59
+ }
60
+ /** The day BEFORE `day` (UTC) — the before/after split edge for a change
61
+ * date: before = window up to this day, after = `day` onward. */
62
+ function dayBefore(day) {
63
+ return new Date(new Date(`${day}T00:00:00.000Z`).getTime() - DAY_MS)
64
+ .toISOString()
65
+ .slice(0, 10);
66
+ }
67
+ /** The #-prefix attribution map: push id → the request's project, from the
68
+ * stored canonicalized label (v26+) when present, ELSE the dominant project
69
+ * of memories distilled from the push's session. `memories.source_session`
70
+ * is segment-scoped (`<sessionId>#<segment>`), so the join is the documented
71
+ * `source_session LIKE sessionId || '#%'` — a BARE equality join matches 0
72
+ * rows on real data (measured, #578; pinned by test). Multi-project sessions
73
+ * resolve to the DOMINANT project (max row count, project ASC tiebreak) —
74
+ * a small minority of joinable sessions in practice, negligible
75
+ * ambiguity. */
76
+ function resolveRequestProjects(db, fromDay, toDay) {
77
+ const pushRows = (toDay
78
+ ? db
79
+ .prepare("SELECT id, session_id, project FROM recall_pushes WHERE day >= ? AND day <= ?")
80
+ .all(fromDay, toDay)
81
+ : db.prepare("SELECT id, session_id, project FROM recall_pushes WHERE day >= ?").all(fromDay));
82
+ const resolved = new Map();
83
+ const needJoin = [];
84
+ for (const p of pushRows) {
85
+ if (typeof p.project === "string" && p.project)
86
+ resolved.set(p.id, p.project);
87
+ else if (p.session_id)
88
+ needJoin.push({ id: p.id, session_id: p.session_id });
89
+ }
90
+ if (needJoin.length > 0) {
91
+ // Dominant project per session over segment-scoped rows: substr before
92
+ // the FIRST '#' IS the LIKE '<sid>#%' prefix — identical join semantics.
93
+ const rows = db
94
+ .prepare(`SELECT substr(source_session, 1, instr(source_session, '#') - 1) AS sid,
95
+ project, COUNT(*) AS c
96
+ FROM memories
97
+ WHERE source_session LIKE '%#%'
98
+ GROUP BY sid, project`)
99
+ .all();
100
+ const dominant = new Map();
101
+ for (const r of rows) {
102
+ const cur = dominant.get(r.sid);
103
+ if (!cur ||
104
+ r.c > cur.c ||
105
+ (r.c === cur.c && (r.project ?? "") < (cur.project ?? ""))) {
106
+ dominant.set(r.sid, { project: r.project, c: r.c });
107
+ }
108
+ }
109
+ for (const p of needJoin) {
110
+ const d = dominant.get(p.session_id);
111
+ // A session whose rows are all project-NULL does not attribute — the
112
+ // coverage % carries that honestly.
113
+ if (d && d.project !== null)
114
+ resolved.set(p.id, d.project);
115
+ }
116
+ }
117
+ return resolved;
118
+ }
119
+ /**
120
+ * The Tier-1 metric set over one inclusive day range [fromDay, toDay]
121
+ * (toDay null = open-ended, the rolling-window shape). Pure SQL-shaped math
122
+ * over raw event rows — every value equals the hand-computed query of its
123
+ * formula; the tests pin exactly that (the readMemoryPrecision Level-1
124
+ * convention). Cross determination matches the #566 fence's own comparison:
125
+ * case-insensitive, a NULL memory project counts as foreign; a memory row
126
+ * that no longer exists reads as a NULL project (the LEFT JOIN's honest
127
+ * output — the fence could not have matched it either).
128
+ */
129
+ function computeTier1Metrics(db, fromDay, toDay, opts) {
130
+ const bar = opts?.crossBar ?? calibration_js_1.CROSS_PROJECT_MIN_SIMILARITY;
131
+ const requestProject = resolveRequestProjects(db, fromDay, toDay);
132
+ const lineRows = (toDay
133
+ ? db
134
+ .prepare(`SELECT e.push_id AS push_id, e.memory_id AS memory_id, e.similarity AS similarity,
135
+ m.project AS mem_project
136
+ FROM recall_events e LEFT JOIN memories m ON m.id = e.memory_id
137
+ WHERE e.day >= ? AND e.day <= ? AND e.kind = 'shown'`)
138
+ .all(fromDay, toDay)
139
+ : db
140
+ .prepare(`SELECT e.push_id AS push_id, e.memory_id AS memory_id, e.similarity AS similarity,
141
+ m.project AS mem_project
142
+ FROM recall_events e LEFT JOIN memories m ON m.id = e.memory_id
143
+ WHERE e.day >= ? AND e.kind = 'shown'`)
144
+ .all(fromDay));
145
+ let attributed = 0;
146
+ let cross = 0;
147
+ let subBar = 0;
148
+ for (const l of lineRows) {
149
+ if (l.push_id === null)
150
+ continue;
151
+ const req = requestProject.get(l.push_id);
152
+ if (req === undefined)
153
+ continue;
154
+ attributed++;
155
+ const isCross = l.mem_project === null || l.mem_project.toLowerCase() !== req.toLowerCase();
156
+ if (!isCross)
157
+ continue;
158
+ cross++;
159
+ if (typeof l.similarity === "number" && l.similarity < bar)
160
+ subBar++;
161
+ }
162
+ const perDay = (toDay
163
+ ? db
164
+ .prepare(`SELECT day, COUNT(DISTINCT memory_id) AS d
165
+ FROM recall_events
166
+ WHERE day >= ? AND day <= ? AND kind = 'shown'
167
+ GROUP BY day`)
168
+ .all(fromDay, toDay)
169
+ : db
170
+ .prepare(`SELECT day, COUNT(DISTINCT memory_id) AS d
171
+ FROM recall_events
172
+ WHERE day >= ? AND kind = 'shown'
173
+ GROUP BY day`)
174
+ .all(fromDay));
175
+ const recycling = perDay.length > 0
176
+ ? round4(perDay.reduce((sum, r) => sum + r.d, 0) / perDay.length)
177
+ : null;
178
+ const pushes = (toDay
179
+ ? db
180
+ .prepare("SELECT COUNT(*) AS c FROM recall_pushes WHERE day >= ? AND day <= ?")
181
+ .get(fromDay, toDay)
182
+ : db.prepare("SELECT COUNT(*) AS c FROM recall_pushes WHERE day >= ?").get(fromDay));
183
+ return {
184
+ pushes: pushes.c,
185
+ lines: lineRows.length,
186
+ block_size: pushes.c > 0 ? round4(lineRows.length / pushes.c) : null,
187
+ cross_share: attributed > 0 ? round4(cross / attributed) : null,
188
+ attribution_coverage: lineRows.length > 0 ? round4(attributed / lineRows.length) : null,
189
+ sub_bar_share: cross > 0 ? round4(subBar / cross) : null,
190
+ recycling,
191
+ cross_project_bar: bar,
192
+ };
193
+ }
194
+ /**
195
+ * The Tier-1 set over the rolling N-day window (inclusive day buckets, the
196
+ * readMemoryPrecision convention) — what handleDashboardData spreads into
197
+ * the memory_precision block and the snapshot writer stamps.
198
+ */
199
+ function readQualityTier1(db, windowDays, opts) {
200
+ const now = opts?.now ?? new Date();
201
+ return computeTier1Metrics(db, windowStartDay(now, windowDays), null, opts);
202
+ }
203
+ /** The compact four-metric projection of a full Tier-1 set. */
204
+ function compactTier1(t) {
205
+ return {
206
+ block_size: t.block_size,
207
+ cross_share: t.cross_share,
208
+ sub_bar_share: t.sub_bar_share,
209
+ recycling: t.recycling,
210
+ };
211
+ }
212
+ /**
213
+ * Every QUALITY_CHANGES entry the raw event window still covers, each with
214
+ * its before/after computed from raw events: before = window start up to the
215
+ * day BEFORE the change date, after = the change date onward. Entries older
216
+ * than the window are omitted (their trend lives on in the snapshot series);
217
+ * future-dated entries carry honest nulls on the after side until they
218
+ * deploy. Numbers are never pinned in code — moving a metric definition
219
+ * re-derives every baseline.
220
+ */
221
+ function readQualityChanges(db, windowDays, opts) {
222
+ const now = opts?.now ?? new Date();
223
+ const fromDay = windowStartDay(now, windowDays);
224
+ const out = [];
225
+ for (const change of calibration_js_1.QUALITY_CHANGES) {
226
+ // Aged out of the raw window — the entry's before/after is no longer
227
+ // computable from events; omit (the snapshot series carries the trend).
228
+ if (change.date < fromDay)
229
+ continue;
230
+ const before = dayBefore(change.date) >= fromDay
231
+ ? compactTier1(computeTier1Metrics(db, fromDay, dayBefore(change.date), opts))
232
+ : null; // the change predates the window start — no before data
233
+ const after = change.date <= now.toISOString().slice(0, 10)
234
+ ? compactTier1(computeTier1Metrics(db, change.date, null, opts))
235
+ : null; // future-dated entry (e.g. a pinned next deploy) — no data yet
236
+ out.push({ id: change.id, label: change.label, date: change.date, before, after });
237
+ }
238
+ return out;
239
+ }
240
+ /** The trio. The dup-cluster count re-runs planDedup (read-only) — nightly
241
+ * cost only, exactly like the merge zone that already runs beside it. The
242
+ * canonical check uses the MECHANICAL fold (trim + lowercase, no alias
243
+ * hop): aliases are config-owned and the snapshot writer has no config —
244
+ * the mechanical fold is the stable definition that still catches every
245
+ * case/whitespace drift. */
246
+ function computeCorpusHealth(db) {
247
+ const dupClusters = (0, dedup_js_1.planDedup)(db, calibration_js_1.DEDUP_AUTO_MERGE_THRESHOLD).clusterCount;
248
+ const live = db
249
+ .prepare(`SELECT COUNT(*) AS total,
250
+ SUM(CASE WHEN domain IS NOT NULL THEN 1 ELSE 0 END) AS anchored
251
+ FROM memories
252
+ WHERE COALESCE(status, '') != 'absorbed'`)
253
+ .get();
254
+ const projectRows = db
255
+ .prepare(`SELECT project, COUNT(*) AS c
256
+ FROM memories
257
+ WHERE COALESCE(status, '') != 'absorbed' AND project IS NOT NULL
258
+ GROUP BY project`)
259
+ .all();
260
+ let drift = 0;
261
+ for (const r of projectRows) {
262
+ if ((0, project_canonicalize_js_1.canonicalizeProject)(r.project) !== r.project)
263
+ drift += r.c;
264
+ }
265
+ return {
266
+ dup_clusters: dupClusters,
267
+ scope_anchor_rate: live.total > 0 && live.anchored !== null ? round4(live.anchored / live.total) : null,
268
+ canonical_drift: drift,
269
+ };
270
+ }
271
+ /** Graded aggregates over the retention window (verdicts older than the
272
+ * event horizon are pruned, except owner verdicts, which stay
273
+ * countable forever... but for TREND comparability the window matches the
274
+ * event store). */
275
+ function readGradedAggregate(db, opts) {
276
+ const now = opts?.now ?? new Date();
277
+ const fromDay = windowStartDay(now, calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS);
278
+ const usefulScore = opts?.usefulScore ?? calibration_js_1.QUALITY_USEFUL_SCORE;
279
+ const contestedBelow = opts?.contestedBelow ?? calibration_js_1.QUALITY_CONTESTED_CONFIDENCE;
280
+ const rows = db
281
+ .prepare(`SELECT grader, score, confidence, verdict, push_id, memory_id
282
+ FROM recall_verdicts
283
+ WHERE day >= ? AND grader IN ('auto', 'owner')`)
284
+ .all(fromDay);
285
+ const answered = new Set(db
286
+ .prepare("SELECT push_id, memory_id FROM recall_verdicts WHERE grader = 'owner'")
287
+ .all().map((r) => `${r.push_id ?? ""}|${r.memory_id}`));
288
+ let useful = 0;
289
+ let contested = 0;
290
+ for (const r of rows) {
291
+ if ((r.grader === "owner" && r.verdict === 1) ||
292
+ (r.grader === "auto" && typeof r.score === "number" && r.score >= usefulScore)) {
293
+ useful++;
294
+ }
295
+ if (r.grader === "auto" &&
296
+ (r.confidence === null || r.confidence < contestedBelow) &&
297
+ !answered.has(`${r.push_id ?? ""}|${r.memory_id}`)) {
298
+ contested++;
299
+ }
300
+ }
301
+ return {
302
+ graded: rows.length,
303
+ useful,
304
+ useful_share: rows.length > 0 ? round4(useful / rows.length) : null,
305
+ contested,
306
+ };
307
+ }
308
+ /** Build the nightly quality block. Nightly-only by construction (only
309
+ * writeSnapshot calls it — the per-request dashboard path never does; the
310
+ * dup-cluster KNN alone forbids that). */
311
+ function buildQualitySnapshotBlock(db, opts) {
312
+ const now = opts?.now ?? new Date();
313
+ return {
314
+ tier1_7d: readQualityTier1(db, 7, { now }),
315
+ tier1_30d: readQualityTier1(db, 30, { now }),
316
+ graded: readGradedAggregate(db, { now }),
317
+ corpus: computeCorpusHealth(db),
318
+ };
319
+ }
320
+ // ---------------------------------------------------------------------------
321
+ // The grading decisions client — one grader, an injectable-fetch seam (the
322
+ // codebase's standard test pattern; NO grader abstraction, #578 non-goal)
323
+ // ---------------------------------------------------------------------------
324
+ /** The decisions API endpoint: a typed-decisions API (POST typed questions,
325
+ * NOT /v1/chat/completions), sub-second per call at a negligible per-call
326
+ * cost. The model id is operator config (#582 — `qualityGradeModel`, no
327
+ * default). Documented failure mode: silent degradation on credit
328
+ * exhaustion — HTTP 200 with EMPTY answers; the client asserts the
329
+ * answer is non-null so that mode writes nothing and surfaces as a greppable
330
+ * health line instead of a silent zero. */
331
+ exports.QUALITY_GRADE_DECISIONS_URL = "https://openrouter.ai/api/alpha/decisions";
332
+ /** Thrown when the endpoint answers HTTP 200 but the answer is null/absent —
333
+ * the documented credit-exhaustion silent-degradation mode. The stage
334
+ * catches it, writes nothing, logs `event=quality_grade_failed`, and the
335
+ * items retry next run (dup-over-loss). */
336
+ class GradeEmptyAnswersError extends Error {
337
+ constructor() {
338
+ super("The grading decisions endpoint returned HTTP 200 with no answer (documented credit-exhaustion mode)");
339
+ this.name = "GradeEmptyAnswersError";
340
+ }
341
+ }
342
+ exports.GradeEmptyAnswersError = GradeEmptyAnswersError;
343
+ /**
344
+ * The grading prompt — the grade target is the index line AS PUSHED (what
345
+ * the consuming agent actually saw, not the memory behind it), rendered
346
+ * through the shared formatIndexLine, with the stored prompt excerpt for
347
+ * context. A typed `score` question (0..1) — the decisions API takes
348
+ * structured questions, not free chat.
349
+ */
350
+ function gradingQuestion(line, promptExcerpt) {
351
+ const excerpt = promptExcerpt && promptExcerpt.trim() ? promptExcerpt.trim() : "(no prompt excerpt recorded)";
352
+ return (`An AI agent received this pushed memory-index line alongside a prompt:\n\n` +
353
+ `Prompt excerpt: ${excerpt}\n\n` +
354
+ `Index line: ${line}\n\n` +
355
+ `Score how useful this one line was for that prompt, 0 (noise) to 1 (directly useful).`);
356
+ }
357
+ /**
358
+ * Build the grading client. `model` is the operator-configured model id
359
+ * (#582 — no default; the stage skips without one). `fetchFn` is the
360
+ * INJECTABLE FETCH SEAM — tests inject a fake and count calls / force both
361
+ * documented failure modes; production uses global fetch. No key material
362
+ * is ever logged. EGRESS REDACTION (#582) lives HERE, at the boundary where
363
+ * the request body is built: both payload parts (the line and the prompt
364
+ * excerpt) run through the deterministic redaction pass BEFORE the question
365
+ * is composed, so no caller can ship raw text to the endpoint.
366
+ */
367
+ function createGradeClient(opts) {
368
+ const doFetch = opts.fetchFn ?? fetch;
369
+ return {
370
+ async gradeLine(line, promptExcerpt, signal) {
371
+ // redact("") is "" — the no-excerpt fallback in gradingQuestion keeps
372
+ // working unchanged.
373
+ const safeLine = (0, redact_js_1.redact)(line).text;
374
+ const safeExcerpt = (0, redact_js_1.redact)(promptExcerpt).text;
375
+ const resp = await doFetch(exports.QUALITY_GRADE_DECISIONS_URL, {
376
+ method: "POST",
377
+ headers: {
378
+ "Content-Type": "application/json",
379
+ Authorization: `Bearer ${opts.apiKey}`,
380
+ },
381
+ body: JSON.stringify({
382
+ model: opts.model,
383
+ questions: [
384
+ {
385
+ type: "score",
386
+ id: "usefulness",
387
+ question: gradingQuestion(safeLine, safeExcerpt),
388
+ min: 0,
389
+ max: 1,
390
+ },
391
+ ],
392
+ }),
393
+ signal,
394
+ });
395
+ if (!resp.ok) {
396
+ throw new Error(`grading decisions endpoint HTTP ${resp.status}`);
397
+ }
398
+ const data = (await resp.json());
399
+ // THE empty-answers assertion — the documented silent-degradation mode
400
+ // must never read as a graded zero.
401
+ const answer = data?.answers?.[0];
402
+ if (answer === null || answer === undefined)
403
+ throw new GradeEmptyAnswersError();
404
+ const score = Number(answer.score);
405
+ const confidence = Number(answer.confidence ?? 1);
406
+ if (!Number.isFinite(score) || !Number.isFinite(confidence)) {
407
+ throw new Error("grading decisions answer is not numeric (score/confidence)");
408
+ }
409
+ return { score, confidence };
410
+ },
411
+ };
412
+ }
413
+ // ---------------------------------------------------------------------------
414
+ // The API key — repo-root .env (gitignored), never printed. Tiny reader, no
415
+ // dotenv dependency.
416
+ // ---------------------------------------------------------------------------
417
+ exports.OPENROUTER_KEY_NAME = "OPENROUTER_HICORTEX_KEY";
418
+ /** Resolve the key: process env wins (the systemd Environment= deployment
419
+ * path), then the repo-root .env (the development convenience path), then
420
+ * ./.env. Returns null when absent — the stage skips (fail-soft), never
421
+ * errors. NEVER logs the value. The repo root is three levels above this
422
+ * module's directory both compiled (dist/) and under vitest (src/) — the
423
+ * __dirname convention init.ts uses. */
424
+ function readOpenRouterKey(envPath) {
425
+ const fromEnv = process.env[exports.OPENROUTER_KEY_NAME];
426
+ if (typeof fromEnv === "string" && fromEnv.trim())
427
+ return fromEnv.trim();
428
+ const candidates = envPath
429
+ ? [envPath]
430
+ : [
431
+ (0, node_path_1.join)(__dirname, "..", "..", "..", ".env"), // repo root
432
+ (0, node_path_1.join)(process.cwd(), ".env"),
433
+ ];
434
+ for (const path of candidates) {
435
+ let raw;
436
+ try {
437
+ raw = (0, node_fs_1.readFileSync)(path, "utf-8");
438
+ }
439
+ catch {
440
+ continue; // absent — the next candidate
441
+ }
442
+ for (const line of raw.split("\n")) {
443
+ const m = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/);
444
+ if (!m || m[1] !== exports.OPENROUTER_KEY_NAME)
445
+ continue;
446
+ const value = m[2].trim().replace(/^["']|["']$/g, "");
447
+ return value || null;
448
+ }
449
+ }
450
+ return null;
451
+ }
452
+ // ---------------------------------------------------------------------------
453
+ // Verdict writes (shared by the stage and the owner PUT)
454
+ // ---------------------------------------------------------------------------
455
+ /** One verdict row insert (the single write shape). */
456
+ function insertVerdictRow(db, row) {
457
+ const info = db
458
+ .prepare(`INSERT INTO recall_verdicts (ts, day, push_id, memory_id, grader, score, confidence, verdict)
459
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
460
+ .run(row.ts, row.day, row.push_id, row.memory_id, row.grader, row.score, row.confidence, row.verdict);
461
+ return Number(info.lastInsertRowid);
462
+ }
463
+ // ---------------------------------------------------------------------------
464
+ // The weekly grading stage — offline, own call lane, deadline-aware,
465
+ // fail-soft (nightly-only wiring; never on any request path)
466
+ // ---------------------------------------------------------------------------
467
+ /** ISO-8601 week key "YYYY-Www" (UTC) — the stage's cadence gate. */
468
+ function isoWeekKey(d) {
469
+ const date = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
470
+ const dayNum = (date.getUTCDay() + 6) % 7; // Mon = 0
471
+ date.setUTCDate(date.getUTCDate() - dayNum + 3); // this week's Thursday
472
+ const isoYear = date.getUTCFullYear();
473
+ const jan4 = new Date(Date.UTC(isoYear, 0, 4));
474
+ const jan4Day = (jan4.getUTCDay() + 6) % 7;
475
+ const week1Mon = Date.UTC(isoYear, 0, 4 - jan4Day);
476
+ const week = 1 + Math.round((date.getTime() - week1Mon) / (7 * DAY_MS));
477
+ return `${isoYear}-W${String(week).padStart(2, "0")}`;
478
+ }
479
+ /**
480
+ * The weekly grading pass (#578): mark revealed-useful lines (shown then
481
+ * fetched in-window) useful with ZERO grading calls, then grade a sample of
482
+ * shown-never-fetched index lines stratified by request project, each graded
483
+ * AS PUSHED (the shared formatIndexLine render + the stored prompt excerpt).
484
+ *
485
+ * OWN LANE: bounded by `callCap` (default 60/week) — deliberately separate
486
+ * from nightlyLlmCallBudget (different provider, independent
487
+ * starvation risk); the consolidation budget is untouched. Deadline-aware
488
+ * between items (createRunDeadline). Dup-over-loss: the week cursor
489
+ * (state.qualityGradeWeek, the supersessionCursor convention) advances only
490
+ * on `complete`; an item with an existing auto-grade verdict is never
491
+ * re-graded (the sample filter), so a retried pass grades exactly the
492
+ * remainder.
493
+ *
494
+ * GATED + FAIL-SOFT (#582): the pass runs ONLY on explicit opt-in —
495
+ * `qualityGrading: true` + `qualityGradeModel` in config, plus the endpoint
496
+ * key; a missing flag, key, or model → skip with
497
+ * `event=quality_grade_skipped`; a client
498
+ * failure (incl. the documented HTTP-200-empty-answers credit-exhaustion
499
+ * mode, guarded by the non-null answer assertion) stops the pass with
500
+ * `event=quality_grade_failed`, writes nothing further, holds the cursor —
501
+ * neither ever throws to the caller (the nightly wraps its own try/catch
502
+ * anyway, mirroring pruneRecallPrecision).
503
+ */
504
+ function runQualityGradeStage(db, gradedWeek, opts) {
505
+ return runQualityGradeStageInner(db, gradedWeek, opts).catch((err) => {
506
+ // Fail-soft at the boundary: an unexpected throw (db, fs) must never
507
+ // fail the nightly run. The week is held; the next run retries.
508
+ (opts?.log ?? console.warn)(`[hicortex] event=quality_grade_failed error=` +
509
+ `${err instanceof Error ? err.message : String(err)}`);
510
+ return {
511
+ week: isoWeekKey(opts?.now ? opts.now() : new Date()),
512
+ complete: false,
513
+ revealedMarked: 0,
514
+ sampled: 0,
515
+ graded: 0,
516
+ deferred: 0,
517
+ };
518
+ });
519
+ }
520
+ async function runQualityGradeStageInner(db, gradedWeek, opts) {
521
+ const now = opts?.now ? opts.now() : new Date();
522
+ const log = opts?.log ?? console.log;
523
+ const week = isoWeekKey(now);
524
+ const base = {
525
+ week,
526
+ revealedMarked: 0,
527
+ sampled: 0,
528
+ graded: 0,
529
+ deferred: 0,
530
+ };
531
+ if (gradedWeek === week) {
532
+ return { ...base, complete: true, skipped: "already-graded" };
533
+ }
534
+ // #582 — explicit operator opt-in, FAIL-CLOSED. The grading lane sends
535
+ // prompt-derived text to a third-party endpoint, so it runs ONLY when the
536
+ // config turns it on (`qualityGrading: true`, readStrictBoolean — absent
537
+ // or wrong-typed ≠ on). Gate order: week cursor → config gate → api key →
538
+ // model. Greppable skip line, never an error.
539
+ const cfg = opts?.config ?? {};
540
+ if ((0, config_read_js_1.readStrictBoolean)(cfg, "qualityGrading") !== true) {
541
+ log(`[hicortex] event=quality_grade_skipped reason=disabled week=${week}`);
542
+ return { ...base, complete: false, skipped: "disabled" };
543
+ }
544
+ const readKey = opts?.readKey ?? readOpenRouterKey;
545
+ const apiKey = readKey();
546
+ if (!apiKey) {
547
+ // No key on this install — the whole stage (revealed marking included)
548
+ // skips: grading is the stage's purpose, and revealed rows are only
549
+ // useful beside graded ones. Greppable, never an error.
550
+ log(`[hicortex] event=quality_grade_skipped reason=no_api_key week=${week}`);
551
+ return { ...base, complete: false, skipped: "no-api-key" };
552
+ }
553
+ const model = (0, config_read_js_1.readStringConfig)(cfg, "qualityGradeModel");
554
+ if (!model) {
555
+ // #582 — the model id is operator config, no default: an egress path
556
+ // never gets an implicit model choice. Skip + health line.
557
+ log(`[hicortex] event=quality_grade_skipped reason=no_model week=${week}`);
558
+ return { ...base, complete: false, skipped: "no-model" };
559
+ }
560
+ const client = opts?.client ?? createGradeClient({ apiKey, model });
561
+ const cap = opts?.callCap ?? calibration_js_1.QUALITY_GRADE_WEEKLY_CALL_CAP;
562
+ const fromDay = windowStartDay(now, calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS);
563
+ const nowIso = now.toISOString();
564
+ // --- Population: every shown (push, memory) pair in the retention window,
565
+ // with the push's prompt excerpt + the memory row for the line render. ---
566
+ const shownRows = db
567
+ .prepare(`SELECT e.push_id AS push_id, e.memory_id AS memory_id, p.prompt_excerpt AS prompt_excerpt
568
+ FROM recall_events e JOIN recall_pushes p ON p.id = e.push_id
569
+ WHERE e.day >= ? AND e.kind = 'shown'`)
570
+ .all(fromDay);
571
+ const fetchedInWindow = new Set(db
572
+ .prepare("SELECT DISTINCT memory_id FROM recall_events WHERE day >= ? AND kind = 'fetch'")
573
+ .all(fromDay).map((r) => r.memory_id));
574
+ const autoGraded = new Set(db
575
+ .prepare("SELECT push_id, memory_id FROM recall_verdicts WHERE grader = 'auto'")
576
+ .all().map((r) => `${r.push_id ?? ""}|${r.memory_id}`));
577
+ const revealedMarkedKeys = new Set(db
578
+ .prepare("SELECT push_id, memory_id FROM recall_verdicts WHERE grader = 'revealed'")
579
+ .all().map((r) => `${r.push_id ?? ""}|${r.memory_id}`));
580
+ const requestProject = resolveRequestProjects(db, fromDay, null);
581
+ const memStmt = db.prepare(`SELECT id, content, created_at, domain, project, source_agent, memory_type
582
+ FROM memories WHERE id = ?`);
583
+ const renderLine = (memoryId) => {
584
+ const row = memStmt.get(memoryId);
585
+ if (!row)
586
+ return null; // memory gone (deleted) — not gradable, skipped
587
+ return (0, recall_index_js_1.formatIndexLine)({
588
+ id: row.id,
589
+ content: row.content,
590
+ score: 0,
591
+ effective_strength: 0,
592
+ access_count: 0,
593
+ memory_type: row.memory_type,
594
+ project: row.project,
595
+ domain: row.domain,
596
+ source_agent: row.source_agent,
597
+ created_at: row.created_at,
598
+ connections: 0,
599
+ }, calibration_js_1.RECALL_TITLE_CHARS);
600
+ };
601
+ // --- (a) Revealed-useful: shown then fetched in-window → useful, ZERO
602
+ // grading calls. Idempotent per (push, memory): a pair marked once is
603
+ // never re-marked. ---
604
+ let revealedMarked = 0;
605
+ const candidates = [];
606
+ for (const s of shownRows) {
607
+ const key = `${s.push_id}|${s.memory_id}`;
608
+ if (fetchedInWindow.has(s.memory_id)) {
609
+ if (!revealedMarkedKeys.has(key)) {
610
+ insertVerdictRow(db, {
611
+ ts: nowIso,
612
+ day: nowIso.slice(0, 10),
613
+ push_id: s.push_id,
614
+ memory_id: s.memory_id,
615
+ grader: "revealed",
616
+ score: 1,
617
+ confidence: 1,
618
+ verdict: 1,
619
+ });
620
+ revealedMarkedKeys.add(key);
621
+ revealedMarked++;
622
+ }
623
+ continue;
624
+ }
625
+ // (b) the grading middle: shown-never-fetched, not already auto-graded,
626
+ // with a renderable line (the grade target is the line AS PUSHED).
627
+ if (autoGraded.has(key))
628
+ continue;
629
+ const line = renderLine(s.memory_id);
630
+ if (line === null)
631
+ continue;
632
+ candidates.push({
633
+ push_id: s.push_id,
634
+ memory_id: s.memory_id,
635
+ prompt_excerpt: s.prompt_excerpt,
636
+ line,
637
+ request_project: requestProject.get(s.push_id) ?? null,
638
+ });
639
+ }
640
+ // --- Stratify by request project, round-robin across the project groups
641
+ // (deterministic: groups by project name) so no single project's volume
642
+ // starves the others. Unattributed lines group under null and still get
643
+ // their turn. The FULL order is built (the cap bounds CALLS in the loop
644
+ // below, not the sample — the remainder must count as DEFERRED so the
645
+ // week cursor holds and next week retries it). ---
646
+ const groups = new Map();
647
+ for (const c of candidates) {
648
+ const g = groups.get(c.request_project) ?? [];
649
+ g.push(c);
650
+ groups.set(c.request_project, g);
651
+ }
652
+ const order = [...groups.keys()].sort((a, b) => (a ?? "￿").localeCompare(b ?? "￿"));
653
+ const sample = [];
654
+ let exhausted = false;
655
+ while (!exhausted) {
656
+ exhausted = true;
657
+ for (const g of order) {
658
+ const item = groups.get(g).shift();
659
+ if (item) {
660
+ sample.push(item);
661
+ exhausted = false;
662
+ }
663
+ }
664
+ }
665
+ // --- The grading pass: deadline + own-cap checked BETWEEN items. ---
666
+ let graded = 0;
667
+ let deferred = 0;
668
+ let failure = null;
669
+ for (const item of sample) {
670
+ if (graded >= cap) {
671
+ deferred = sample.length - graded;
672
+ log(`[hicortex] event=quality_grade_deferred reason=cap graded=${graded} deferred=${deferred} week=${week}`);
673
+ break;
674
+ }
675
+ if (opts?.deadline?.hit("quality_grade")) {
676
+ deferred = sample.length - graded;
677
+ log(`[hicortex] event=quality_grade_deferred reason=deadline graded=${graded} deferred=${deferred} week=${week}`);
678
+ break;
679
+ }
680
+ try {
681
+ const answer = await client.gradeLine(item.line, item.prompt_excerpt ?? "");
682
+ insertVerdictRow(db, {
683
+ ts: nowIso,
684
+ day: nowIso.slice(0, 10),
685
+ push_id: item.push_id,
686
+ memory_id: item.memory_id,
687
+ grader: "auto",
688
+ score: answer.score, // RAW — threshold-free (the #476 law)
689
+ confidence: answer.confidence,
690
+ verdict: null, // derived at render, never stored for the 'auto' grader
691
+ });
692
+ graded++;
693
+ }
694
+ catch (err) {
695
+ // Includes the documented HTTP-200-empty-answers mode: NOTHING from
696
+ // this call was written; already-written items stay (dup-over-loss);
697
+ // the remainder defers to the next run (cursor held).
698
+ deferred = sample.length - graded;
699
+ failure = err instanceof Error ? err.message : String(err);
700
+ log(`[hicortex] event=quality_grade_failed error=${failure} graded=${graded} deferred=${deferred} week=${week}`);
701
+ break;
702
+ }
703
+ }
704
+ const complete = deferred === 0 && graded === sample.length;
705
+ if (complete) {
706
+ log(`[hicortex] event=quality_grade_done week=${week} graded=${graded} revealed=${revealedMarked}`);
707
+ }
708
+ return { week, complete, revealedMarked, sampled: sample.length, graded, deferred };
709
+ }
710
+ /**
711
+ * GET /dashboard/quality/contested's pure handler: the contested slice —
712
+ * auto-graded rows with confidence below QUALITY_CONTESTED_CONFIDENCE
713
+ * (render edge, echoed in the payload) that the owner has not yet answered
714
+ * — newest first... no: LEAST confident first (they need the thumbs most),
715
+ * then newest. Paginated (`limit` default 20, cap 100; `offset` default 0).
716
+ */
717
+ function listContestedVerdicts(db, query, opts) {
718
+ const contestedBelow = opts?.contestedBelow ?? calibration_js_1.QUALITY_CONTESTED_CONFIDENCE;
719
+ let limit = 20;
720
+ if (typeof query.limit !== "undefined") {
721
+ const n = Math.floor(Number(query.limit));
722
+ limit = Number.isFinite(n) && n > 0 ? Math.min(n, 100) : 20;
723
+ }
724
+ let offset = 0;
725
+ if (typeof query.offset !== "undefined") {
726
+ const n = Math.floor(Number(query.offset));
727
+ offset = Number.isFinite(n) && n > 0 ? n : 0;
728
+ }
729
+ // The answered filter: once the owner thumbs a (push, memory), it leaves
730
+ // the contested list — the drawer clears as the owner grades. NULL push_id
731
+ // pairs match on IS (the verdict rows carry them verbatim).
732
+ const answeredExists = `EXISTS (
733
+ SELECT 1 FROM recall_verdicts o
734
+ WHERE o.grader = 'owner'
735
+ AND o.memory_id = v.memory_id
736
+ AND (o.push_id = v.push_id OR (o.push_id IS NULL AND v.push_id IS NULL)))`;
737
+ const total = db
738
+ .prepare(`SELECT COUNT(*) AS c FROM recall_verdicts v
739
+ WHERE v.grader = 'auto'
740
+ AND COALESCE(v.confidence, 0) < ?
741
+ AND NOT ${answeredExists}`)
742
+ .get(contestedBelow).c;
743
+ const rows = db
744
+ .prepare(`SELECT v.id, v.ts, v.push_id, v.memory_id, v.score, v.confidence, p.prompt_excerpt
745
+ FROM recall_verdicts v
746
+ LEFT JOIN recall_pushes p ON p.id = v.push_id
747
+ WHERE v.grader = 'auto'
748
+ AND COALESCE(v.confidence, 0) < ?
749
+ AND NOT ${answeredExists}
750
+ ORDER BY v.confidence ASC, v.ts DESC
751
+ LIMIT ? OFFSET ?`)
752
+ .all(contestedBelow, limit, offset);
753
+ const memStmt = db.prepare(`SELECT id, content, created_at, domain, project, source_agent, memory_type
754
+ FROM memories WHERE id = ?`);
755
+ const items = rows.map((r) => {
756
+ const mem = memStmt.get(r.memory_id);
757
+ return {
758
+ id: r.id,
759
+ ts: r.ts,
760
+ push_id: r.push_id,
761
+ memory_id: r.memory_id,
762
+ score: r.score,
763
+ confidence: r.confidence,
764
+ line: mem
765
+ ? (0, recall_index_js_1.formatIndexLine)({
766
+ id: mem.id,
767
+ content: mem.content,
768
+ score: 0,
769
+ effective_strength: 0,
770
+ access_count: 0,
771
+ memory_type: mem.memory_type,
772
+ project: mem.project,
773
+ domain: mem.domain,
774
+ source_agent: mem.source_agent,
775
+ created_at: mem.created_at,
776
+ connections: 0,
777
+ }, calibration_js_1.RECALL_TITLE_CHARS)
778
+ : null,
779
+ prompt_excerpt: r.prompt_excerpt,
780
+ };
781
+ });
782
+ return { total, limit, offset, items };
783
+ }
784
+ /**
785
+ * PUT /dashboard/quality/verdict's pure handler — the dashboard's THIRD
786
+ * scoped writer (after /dashboard/model and /dashboard/capture-pause; same
787
+ * convention: strict validation, injected effect, 404 on unknown id).
788
+ *
789
+ * Body: `{id: number, verdict: 1 | -1}` — numeric thumbs (1 = useful, -1 =
790
+ * not); no string aliases to mis-parse. `id` is a recall_verdicts row id
791
+ * (the contested item's). The verdict persists as a NEW `grader='owner'`
792
+ * row against the same (push_id, memory_id) — history is append-only, the
793
+ * owner verdicts accumulate, and the auto-graded row it answers stays
794
+ * untouched.
795
+ */
796
+ function recordOwnerVerdict(db, body, opts) {
797
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
798
+ return { status: 400, body: { error: "Body must be a JSON object {id, verdict}" } };
799
+ }
800
+ const { id, verdict } = body;
801
+ if (typeof id !== "number" || !Number.isInteger(id) || id < 1) {
802
+ return { status: 400, body: { error: "Invalid 'id' — expected an integer verdict-row id" } };
803
+ }
804
+ if (verdict !== 1 && verdict !== -1) {
805
+ return { status: 400, body: { error: "Invalid 'verdict' — expected 1 (useful) or -1 (not useful)" } };
806
+ }
807
+ const target = db
808
+ .prepare("SELECT id, push_id, memory_id FROM recall_verdicts WHERE id = ?")
809
+ .get(id);
810
+ if (!target) {
811
+ return { status: 404, body: { error: `No verdict row with id ${id}` } };
812
+ }
813
+ const now = opts?.now ? opts.now() : new Date();
814
+ const nowIso = now.toISOString();
815
+ const newId = insertVerdictRow(db, {
816
+ ts: nowIso,
817
+ day: nowIso.slice(0, 10),
818
+ push_id: target.push_id,
819
+ memory_id: target.memory_id,
820
+ grader: "owner",
821
+ score: verdict, // the thumb IS the score for owner rows
822
+ confidence: 1, // owner verdicts are certain by definition
823
+ verdict,
824
+ });
825
+ return { status: 200, body: { ok: true, id: newId, verdict, memory_id: target.memory_id } };
826
+ }