@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.
- package/README.md +2 -0
- package/assets/dashboard.html +227 -64
- package/dist/calibration.d.ts +59 -0
- package/dist/calibration.js +53 -2
- package/dist/dashboard.d.ts +38 -9
- package/dist/dashboard.js +84 -13
- package/dist/db.js +72 -0
- package/dist/mcp-server.js +27 -4
- package/dist/nightly.js +26 -0
- package/dist/quality-scoreboard.d.ts +351 -0
- package/dist/quality-scoreboard.js +826 -0
- package/dist/recall-index.d.ts +7 -7
- package/dist/recall-index.js +19 -14
- package/dist/recall-precision.d.ts +41 -7
- package/dist/recall-precision.js +32 -12
- package/dist/retrieval.js +3 -2
- package/dist/state.d.ts +9 -0
- package/dist/storage.d.ts +11 -6
- package/dist/storage.js +16 -10
- package/dist/types.d.ts +17 -0
- package/package.json +1 -1
- package/server.json +2 -2
package/dist/dashboard.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
/**
|
|
3
|
-
* /dashboard —
|
|
4
|
-
*
|
|
3
|
+
* /dashboard — memory analytics (#224) + the console's live-data endpoints
|
|
4
|
+
* (#409/#421 Phase 1: /dashboard/field, /dashboard/events).
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
* ONE snapshot row per full nightly run (the writer is
|
|
8
|
-
* metric SQL lives next to its definition, not in
|
|
9
|
-
* the pure data handlers mounted at GET
|
|
10
|
-
* GET /dashboard/field and GET /dashboard/events.
|
|
11
|
-
*
|
|
12
|
-
*
|
|
6
|
+
* View-only-leaning with SCOPED writers: this module computes metrics, reads
|
|
7
|
+
* snapshots, writes ONE snapshot row per full nightly run (the writer is
|
|
8
|
+
* here because the metric SQL lives next to its definition, not in
|
|
9
|
+
* nightly.ts), and exposes the pure data handlers mounted at GET
|
|
10
|
+
* /dashboard/data, GET /dashboard/field and GET /dashboard/events. The
|
|
11
|
+
* mutation surface is deliberately narrow: PUT /dashboard/model (#422),
|
|
12
|
+
* PUT /dashboard/capture-pause (#423), and PUT /dashboard/quality/verdict
|
|
13
|
+
* (#578 — the contested thumbs) — each an owner-ruled scoped writer, never
|
|
14
|
+
* a general write path.
|
|
13
15
|
*
|
|
14
16
|
* Layering (mirrors how recall-index.ts holds pure logic and viz.ts holds
|
|
15
17
|
* thin express adapters): all metric SQL + snapshot shape lives HERE so it
|
|
@@ -40,12 +42,15 @@ exports.dashboardModelGetHandler = dashboardModelGetHandler;
|
|
|
40
42
|
exports.dashboardModelPutHandler = dashboardModelPutHandler;
|
|
41
43
|
exports.handleDashboardCapturePausePut = handleDashboardCapturePausePut;
|
|
42
44
|
exports.dashboardCapturePausePutHandler = dashboardCapturePausePutHandler;
|
|
45
|
+
exports.dashboardQualityContestedHandler = dashboardQualityContestedHandler;
|
|
46
|
+
exports.dashboardQualityVerdictPutHandler = dashboardQualityVerdictPutHandler;
|
|
43
47
|
const node_zlib_1 = require("node:zlib");
|
|
44
48
|
const recall_index_js_1 = require("./recall-index.js");
|
|
45
49
|
const config_read_js_1 = require("./config-read.js");
|
|
46
50
|
const consolidate_js_1 = require("./consolidate.js");
|
|
47
51
|
const capture_health_js_1 = require("./capture-health.js");
|
|
48
52
|
const recall_precision_js_1 = require("./recall-precision.js");
|
|
53
|
+
const quality_scoreboard_js_1 = require("./quality-scoreboard.js");
|
|
49
54
|
const distill_queue_js_1 = require("./distill-queue.js");
|
|
50
55
|
const capture_pause_js_1 = require("./capture-pause.js");
|
|
51
56
|
const state_js_1 = require("./state.js");
|
|
@@ -237,6 +242,20 @@ function writeSnapshot(db, runAt, delta, memorySoftCap) {
|
|
|
237
242
|
if (memorySoftCap !== undefined) {
|
|
238
243
|
metrics.capacity = { memory_soft_cap: memorySoftCap };
|
|
239
244
|
}
|
|
245
|
+
// #578 — the quality block: Tier-1 (7d + 30d) + graded aggregates + the
|
|
246
|
+
// corpus trio, computed HERE (nightly writer only — the per-request
|
|
247
|
+
// dashboard path never runs the dup-cluster KNN; the card renders the trio
|
|
248
|
+
// from this snapshot series). `runAt` is the caller-chosen instant, so the
|
|
249
|
+
// block's windows are deterministic for tests. Fail-soft like every
|
|
250
|
+
// snapshot extra: a quality computation error must not lose the whole
|
|
251
|
+
// snapshot row — surface and write the base metrics.
|
|
252
|
+
try {
|
|
253
|
+
metrics.quality = (0, quality_scoreboard_js_1.buildQualitySnapshotBlock)(db, { now: new Date(runAt) });
|
|
254
|
+
}
|
|
255
|
+
catch (qErr) {
|
|
256
|
+
console.warn(`[hicortex] Dashboard snapshot quality block failed: ` +
|
|
257
|
+
`${qErr instanceof Error ? qErr.message : String(qErr)}`);
|
|
258
|
+
}
|
|
240
259
|
db.prepare("INSERT OR REPLACE INTO dashboard_snapshots (run_at, metrics) VALUES (?, ?)").run(runAt, JSON.stringify(metrics));
|
|
241
260
|
return { run_at: runAt, metrics };
|
|
242
261
|
}
|
|
@@ -582,10 +601,18 @@ function handleDashboardData(db, query, config) {
|
|
|
582
601
|
// event tables + snapshot deltas. Level 2's "latest" is the SAME live
|
|
583
602
|
// adoption this handler already computed (one definition of corpus
|
|
584
603
|
// shape — computeDashboardMetrics); readMemoryPrecision owns the rest.
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
604
|
+
// #578 spreads the Tier-1 quality metrics + the change-registry
|
|
605
|
+
// before/after deltas into the SAME block over the SAME effective
|
|
606
|
+
// window (≤ 2 KB budget still asserted by test; verdict/contested data
|
|
607
|
+
// stays OUT — behind the lazy paginated /dashboard/quality/contested).
|
|
608
|
+
memory_precision: {
|
|
609
|
+
...(0, recall_precision_js_1.readMemoryPrecision)(db, rangeParam, {
|
|
610
|
+
shown_sum: live.adoption?.shown_sum ?? 0,
|
|
611
|
+
used_sum: live.adoption?.used_sum ?? 0,
|
|
612
|
+
}),
|
|
613
|
+
tier1: (0, quality_scoreboard_js_1.readQualityTier1)(db, (0, recall_precision_js_1.effectivePrecisionWindowDays)(rangeParam)),
|
|
614
|
+
changes: (0, quality_scoreboard_js_1.readQualityChanges)(db, (0, recall_precision_js_1.effectivePrecisionWindowDays)(rangeParam)),
|
|
615
|
+
},
|
|
589
616
|
// #529: live inbox state — depth + oldest age + the echoed warn
|
|
590
617
|
// threshold. Live only (no series): depth at snapshot time is ~0 by
|
|
591
618
|
// construction, so history would be a flat line.
|
|
@@ -1261,3 +1288,47 @@ function dashboardCapturePausePutHandler(getDb) {
|
|
|
1261
1288
|
}
|
|
1262
1289
|
};
|
|
1263
1290
|
}
|
|
1291
|
+
// ---------------------------------------------------------------------------
|
|
1292
|
+
// GET /dashboard/quality/contested + PUT /dashboard/quality/verdict — the
|
|
1293
|
+
// #578 quality drawer's endpoints. Pure handlers live in quality-scoreboard.ts
|
|
1294
|
+
// (the recall-precision layering law); these are the thin express adapters
|
|
1295
|
+
// (the dashboardDataHandler convention). The GET is lazy + paginated so the
|
|
1296
|
+
// graded data stays out of the ≤ 2 KB memory_precision block; the PUT is the
|
|
1297
|
+
// dashboard's THIRD scoped writer (owner thumbs — the calibration
|
|
1298
|
+
// reference), after /dashboard/model and /dashboard/capture-pause.
|
|
1299
|
+
// ---------------------------------------------------------------------------
|
|
1300
|
+
/**
|
|
1301
|
+
* Express adapter for GET /dashboard/quality/contested. Bearer-only (auth
|
|
1302
|
+
* middleware, no shell exemption — it carries grading data); localhost
|
|
1303
|
+
* bypass applies. Query: `limit` (default 20, cap 100), `offset` (default 0).
|
|
1304
|
+
*/
|
|
1305
|
+
function dashboardQualityContestedHandler(getDb) {
|
|
1306
|
+
return (req, res) => {
|
|
1307
|
+
try {
|
|
1308
|
+
res.status(200).json((0, quality_scoreboard_js_1.listContestedVerdicts)(getDb(), req.query));
|
|
1309
|
+
}
|
|
1310
|
+
catch (err) {
|
|
1311
|
+
res.status(500).json({ error: err instanceof Error ? err.message : String(err) });
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* Express adapter for PUT /dashboard/quality/verdict — the contested
|
|
1317
|
+
* drawer's thumbs. Body `{id: number, verdict: 1 | -1}` (numeric thumbs: 1 =
|
|
1318
|
+
* useful, -1 = not). Persists grader='owner' (retained forever — the
|
|
1319
|
+
* calibration reference; the nightly verdict prune never drops owner
|
|
1320
|
+
* rows). Bearer-only like every dashboard writer; localhost bypass
|
|
1321
|
+
* applies. 404 on an unknown id,
|
|
1322
|
+
* 400 on a malformed body — strict validation, the model-PUT convention.
|
|
1323
|
+
*/
|
|
1324
|
+
function dashboardQualityVerdictPutHandler(getDb) {
|
|
1325
|
+
return (req, res) => {
|
|
1326
|
+
try {
|
|
1327
|
+
const { status, body } = (0, quality_scoreboard_js_1.recordOwnerVerdict)(getDb(), req.body ?? null);
|
|
1328
|
+
res.status(status).json(body);
|
|
1329
|
+
}
|
|
1330
|
+
catch (err) {
|
|
1331
|
+
res.status(500).json({ error: err instanceof Error ? err.message : String(err) });
|
|
1332
|
+
}
|
|
1333
|
+
};
|
|
1334
|
+
}
|
package/dist/db.js
CHANGED
|
@@ -808,6 +808,78 @@ const MIGRATIONS = [
|
|
|
808
808
|
db.exec("CREATE INDEX IF NOT EXISTS idx_distill_queue_arrived ON distill_queue(arrived_at)");
|
|
809
809
|
},
|
|
810
810
|
},
|
|
811
|
+
{
|
|
812
|
+
version: 25,
|
|
813
|
+
name: "use_clock_correction",
|
|
814
|
+
up: (db) => {
|
|
815
|
+
// #569 — close the exposure-refresh loop. Since v8 (#192) every
|
|
816
|
+
// recall-index showing stamped last_accessed = now, and that column is
|
|
817
|
+
// the clock effectiveStrength decays on (the strength term of
|
|
818
|
+
// computeScore, the stageDecayPrune predicate, the cap-eviction
|
|
819
|
+
// ordering) — so shown-but-never-fetched noise stayed young forever.
|
|
820
|
+
// touchMemoriesShown now bumps shown_count only, superseding the v8
|
|
821
|
+
// refresh semantics, and this one-time correction re-anchors the
|
|
822
|
+
// accumulated false youth: for rows never fetched AND never
|
|
823
|
+
// owner-corroborated, no use ever happened, so creation age is the
|
|
824
|
+
// honest decay clock. Used and enriched rows keep their stamps — the
|
|
825
|
+
// classes that earned them. The v20 promotion-baseline backfill is the
|
|
826
|
+
// precedent for correcting a signal's history when its semantics
|
|
827
|
+
// change. Idempotent: re-running rewrites the same creation value onto
|
|
828
|
+
// the same rows (the fixed writer produces no new exposure stamps).
|
|
829
|
+
db.exec(`UPDATE memories SET last_accessed = created_at
|
|
830
|
+
WHERE access_count = 0 AND COALESCE(corroboration_count, 0) = 0`);
|
|
831
|
+
},
|
|
832
|
+
},
|
|
833
|
+
{
|
|
834
|
+
version: 26,
|
|
835
|
+
name: "quality_verdicts",
|
|
836
|
+
up: (db) => {
|
|
837
|
+
// #578 — the quality scoreboard's store half. Two additions:
|
|
838
|
+
//
|
|
839
|
+
// (1) recall_pushes.project — the CANONICALIZED wire label the #566
|
|
840
|
+
// fence gated with (handleRecallIndex already computes
|
|
841
|
+
// canonicalizeProject(req.project) before the recorder runs; the label
|
|
842
|
+
// was simply dropped on the floor). Nullable, NO backfill — the v15
|
|
843
|
+
// source_machine precedent: pre-v26 rows stay NULL and attribute via
|
|
844
|
+
// the `#`-prefix join on memories.source_session (which is
|
|
845
|
+
// segment-scoped `<sessionId>#<segment>` — bare equality matches 0
|
|
846
|
+
// rows, measured #578); the join covers 96%+ of pushes, and the
|
|
847
|
+
// attribution COVERAGE % renders beside the cross-project share so the
|
|
848
|
+
// gap is explicit, never silent.
|
|
849
|
+
//
|
|
850
|
+
// (2) recall_verdicts — the judgment sidecar (the v16/v22 sidecar law:
|
|
851
|
+
// OPERATIONS/judgment telemetry, no memories FK — a verdict row
|
|
852
|
+
// outliving its memory, or grading a memory later absorbed, is valid;
|
|
853
|
+
// memory_id is DATA). One row per (grader × push × memory × time):
|
|
854
|
+
// grader 'auto' (weekly grade stage), 'owner' (dashboard thumbs — the
|
|
855
|
+
// calibration reference, NEVER pruned), or 'revealed'
|
|
856
|
+
// (shown-then-fetched, marked useful with zero grading calls). score +
|
|
857
|
+
// confidence are stored RAW and THRESHOLD-FREE (the #476 law —
|
|
858
|
+
// "useful" and "contested" are derived at render), verdict carries the
|
|
859
|
+
// owner's ±1 thumb (NULL for the 'auto' grader, derived at render). Pruned with
|
|
860
|
+
// the 90-day horizon EXCEPT grader='owner' rows.
|
|
861
|
+
//
|
|
862
|
+
// Idempotent: hasColumn-guarded ALTER (v15 pattern) + IF NOT EXISTS.
|
|
863
|
+
if (!hasColumn(db, "recall_pushes", "project")) {
|
|
864
|
+
db.exec("ALTER TABLE recall_pushes ADD COLUMN project TEXT");
|
|
865
|
+
}
|
|
866
|
+
db.exec(`
|
|
867
|
+
CREATE TABLE IF NOT EXISTS recall_verdicts (
|
|
868
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
869
|
+
ts TEXT NOT NULL,
|
|
870
|
+
day TEXT NOT NULL,
|
|
871
|
+
push_id INTEGER,
|
|
872
|
+
memory_id TEXT NOT NULL,
|
|
873
|
+
grader TEXT NOT NULL,
|
|
874
|
+
score REAL,
|
|
875
|
+
confidence REAL,
|
|
876
|
+
verdict INTEGER
|
|
877
|
+
)
|
|
878
|
+
`);
|
|
879
|
+
db.exec("CREATE INDEX IF NOT EXISTS idx_recall_verdicts_day ON recall_verdicts(day)");
|
|
880
|
+
db.exec("CREATE INDEX IF NOT EXISTS idx_recall_verdicts_push_memory ON recall_verdicts(push_id, memory_id)");
|
|
881
|
+
},
|
|
882
|
+
},
|
|
811
883
|
];
|
|
812
884
|
/**
|
|
813
885
|
* Run all pending migrations against the database.
|
package/dist/mcp-server.js
CHANGED
|
@@ -1156,8 +1156,9 @@ async function startServer(options = {}) {
|
|
|
1156
1156
|
});
|
|
1157
1157
|
// REST /recall-index — pushed recall index (#192). One recall logic for all
|
|
1158
1158
|
// harnesses: CC UserPromptSubmit hook, Hermes/OC per-turn plugins. Returns a
|
|
1159
|
-
// compact index block (or null); exposure is recorded as shown_count
|
|
1160
|
-
// last_accessed
|
|
1159
|
+
// compact index block (or null); exposure is recorded as shown_count ONLY
|
|
1160
|
+
// (#569: last_accessed is the use clock — fetches/enrich — never refreshed
|
|
1161
|
+
// by listing) and NOT access_count (that stays reserved for hicortex_get /
|
|
1161
1162
|
// GET /memory — real use). {reset: true} clears the session's dedup state
|
|
1162
1163
|
// (SessionStart/compaction).
|
|
1163
1164
|
//
|
|
@@ -2015,8 +2016,10 @@ async function startServer(options = {}) {
|
|
|
2015
2016
|
// GET /dashboard/data — the metric payload (series, composition, digest).
|
|
2016
2017
|
// Bearer-only (the auth middleware is installed at app boot); no separate
|
|
2017
2018
|
// exemption. The handler lives in src/dashboard.ts (pure); this is the thin
|
|
2018
|
-
// express adapter that injects the live db + config.
|
|
2019
|
-
//
|
|
2019
|
+
// express adapter that injects the live db + config. Read-only like every
|
|
2020
|
+
// /dashboard/data GET; the dashboard surface's deliberately narrow
|
|
2021
|
+
// mutation set lives in the scoped PUTs below (model settings #422,
|
|
2022
|
+
// capture-pause #423, quality verdict #578).
|
|
2020
2023
|
app.get("/dashboard/data", (0, dashboard_js_1.dashboardDataHandler)(() => db, () => readConfigFile(stateDir)));
|
|
2021
2024
|
// GET /dashboard/field — the console flight-field payload (#409/#421
|
|
2022
2025
|
// Phase 1): the whole live store as minimal fields (titles ≤100 via the
|
|
@@ -2059,6 +2062,26 @@ async function startServer(options = {}) {
|
|
|
2059
2062
|
// (auth middleware, no shell exemption — it mutates operator state);
|
|
2060
2063
|
// localhost bypass applies. Handler + adapter live in src/dashboard.ts.
|
|
2061
2064
|
app.put("/dashboard/capture-pause", (0, dashboard_js_1.dashboardCapturePausePutHandler)(() => db));
|
|
2065
|
+
// GET /dashboard/quality/contested — the #578 quality drawer's contested
|
|
2066
|
+
// slice: auto-graded verdict rows below the (render-edge) confidence threshold,
|
|
2067
|
+
// least-confident first, with the index line AS PUSHED re-rendered through
|
|
2068
|
+
// the shared formatIndexLine + the stored prompt excerpt. LAZY + paginated
|
|
2069
|
+
// (?limit= default 20 cap 100, ?offset=) so grading data stays out of the
|
|
2070
|
+
// ≤ 2 KB memory_precision block. Items the owner has answered (thumbs
|
|
2071
|
+
// recorded) leave the list. Bearer-only (auth middleware, no shell
|
|
2072
|
+
// exemption — it carries grading data); localhost bypass applies. Handler
|
|
2073
|
+
// lives in src/quality-scoreboard.ts (pure) via a thin adapter in
|
|
2074
|
+
// src/dashboard.ts.
|
|
2075
|
+
app.get("/dashboard/quality/contested", (0, dashboard_js_1.dashboardQualityContestedHandler)(() => db));
|
|
2076
|
+
// PUT /dashboard/quality/verdict — the dashboard's THIRD scoped writer
|
|
2077
|
+
// (after /dashboard/model and /dashboard/capture-pause): the owner's thumbs
|
|
2078
|
+
// on a contested line. Body {id, verdict: 1|-1} (numeric: 1 useful, -1
|
|
2079
|
+
// not) — persisted as grader='owner', a NEW verdict row against the same
|
|
2080
|
+
// (push, memory) so history is append-only; these rows are the
|
|
2081
|
+
// owner calibration reference and are NEVER pruned by the nightly verdict
|
|
2082
|
+
// retention. 404 on an unknown id, 400 on a malformed body. Bearer-only
|
|
2083
|
+
// like every dashboard writer; localhost bypass applies.
|
|
2084
|
+
app.put("/dashboard/quality/verdict", (0, dashboard_js_1.dashboardQualityVerdictPutHandler)(() => db));
|
|
2062
2085
|
// GET /account — account identity for the console nav (name/org/plan from
|
|
2063
2086
|
// config). The LIGHTWEIGHT twin of the account block inside /dashboard/data:
|
|
2064
2087
|
// the /viz and /identity/ui pages need only this, not the metric payload;
|
package/dist/nightly.js
CHANGED
|
@@ -83,6 +83,7 @@ const token_budget_js_1 = require("./token-budget.js");
|
|
|
83
83
|
const run_deadline_js_1 = require("./run-deadline.js");
|
|
84
84
|
const dashboard_js_1 = require("./dashboard.js");
|
|
85
85
|
const recall_precision_js_1 = require("./recall-precision.js");
|
|
86
|
+
const quality_scoreboard_js_1 = require("./quality-scoreboard.js");
|
|
86
87
|
const telemetry_js_1 = require("./telemetry.js");
|
|
87
88
|
const init_js_1 = require("./init.js");
|
|
88
89
|
const backup_js_1 = require("./backup.js");
|
|
@@ -1175,6 +1176,31 @@ async function runNightly(options = {}) {
|
|
|
1175
1176
|
console.warn(`[hicortex] Recall-precision retention prune failed: ` +
|
|
1176
1177
|
`${pruneErr instanceof Error ? pruneErr.message : String(pruneErr)}`);
|
|
1177
1178
|
}
|
|
1179
|
+
// #578 — the weekly quality-grade stage (third-party decisions
|
|
1180
|
+
// endpoint); explicit operator opt-in (#582: `qualityGrading` +
|
|
1181
|
+
// `qualityGradeModel` config) — absent → skip.
|
|
1182
|
+
// Gated by the state.json ISO-week cursor: one pass per week, on its
|
|
1183
|
+
// OWN call lane (cap 60/week — deliberately separate from
|
|
1184
|
+
// nightlyLlmCallBudget, different provider), deadline-aware between
|
|
1185
|
+
// items, fail-soft against every documented failure mode (absent key →
|
|
1186
|
+
// skip; HTTP-200-empty-answers → nothing written, retried). The cursor
|
|
1187
|
+
// advances ONLY on a completed pass (dup-over-loss). Own try/catch —
|
|
1188
|
+
// telemetry housekeeping must never fail the run (the prune above is
|
|
1189
|
+
// the precedent). Snapshot ordering: this run's fresh verdicts land in
|
|
1190
|
+
// tomorrow's snapshot block — the trend lags a day by construction.
|
|
1191
|
+
try {
|
|
1192
|
+
const gradedWeek = (0, state_js_1.loadState)(stateDir).qualityGradeWeek;
|
|
1193
|
+
const report = await (0, quality_scoreboard_js_1.runQualityGradeStage)(db, gradedWeek, { deadline, config: savedConfig });
|
|
1194
|
+
if (report.complete && !report.skipped) {
|
|
1195
|
+
(0, state_js_1.updateState)((s) => {
|
|
1196
|
+
s.qualityGradeWeek = report.week;
|
|
1197
|
+
}, stateDir);
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
catch (gradeErr) {
|
|
1201
|
+
console.warn(`[hicortex] Quality-grade stage failed: ` +
|
|
1202
|
+
`${gradeErr instanceof Error ? gradeErr.message : String(gradeErr)}`);
|
|
1203
|
+
}
|
|
1178
1204
|
}
|
|
1179
1205
|
// Anonymous telemetry (fire-and-forget, full nightly only).
|
|
1180
1206
|
// Capture-only runs are excluded to avoid inflating install pings.
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quality scoreboard (#578) — the Memory Precision card as a standing quality
|
|
3
|
+
* instrument. Everything here is OFF the request path by construction:
|
|
4
|
+
*
|
|
5
|
+
* - Tier-1 deterministic metrics (block size, cross-project share +
|
|
6
|
+
* attribution coverage, sub-bar share, distinct-memory recycling) are
|
|
7
|
+
* computed from the #476 event store at RENDER time (handleDashboardData)
|
|
8
|
+
* and stamped into the nightly snapshot by the snapshot writer.
|
|
9
|
+
* - The corpus-health trio (near-duplicate cluster count, scope-anchor
|
|
10
|
+
* rate, canonical-label integrity) is computed by the NIGHTLY snapshot
|
|
11
|
+
* writer ONLY — the dup-cluster count re-runs the dedup clustering over
|
|
12
|
+
* every vector, far too heavy per dashboard load — and renders from the
|
|
13
|
+
* snapshot series, never per-request.
|
|
14
|
+
* - The weekly auto-grading pass runs inside the nightly, gated by a
|
|
15
|
+
* state.json week cursor, on its own call lane. NO grading code is
|
|
16
|
+
* reachable from any HTTP handler.
|
|
17
|
+
*
|
|
18
|
+
* Layering (the recall-precision.ts law): pure functions over the db handle
|
|
19
|
+
* + injectable seams (fetch, clock, cap, logger) so tests exercise every
|
|
20
|
+
* failure mode without HTTP, keys, or live calls; dashboard.ts holds only the
|
|
21
|
+
* express adapters; mcp-server.ts only the routes.
|
|
22
|
+
*
|
|
23
|
+
* Threshold-free storage (the #476 law): verdict rows carry RAW score +
|
|
24
|
+
* confidence; "useful" and "contested" derive at render from
|
|
25
|
+
* QUALITY_USEFUL_SCORE / QUALITY_CONTESTED_CONFIDENCE, so recalibration never
|
|
26
|
+
* rewrites history.
|
|
27
|
+
*/
|
|
28
|
+
import type Database from "better-sqlite3";
|
|
29
|
+
import type { RunDeadline } from "./run-deadline.js";
|
|
30
|
+
/** Inclusive window start (UTC YYYY-MM-DD) for an N-day window: today counts
|
|
31
|
+
* as day 1 — the readMemoryPrecision day-bucket convention. */
|
|
32
|
+
export declare function windowStartDay(now: Date, windowDays: number): string;
|
|
33
|
+
/** The Tier-1 metric set over one day range. Every share is null when its
|
|
34
|
+
* denominator is empty (undefined, never a guessed 0 — the readMemoryPrecision
|
|
35
|
+
* honesty convention); the cross-project bar is ECHOED (the page never
|
|
36
|
+
* hardcodes an edge). */
|
|
37
|
+
export interface QualityTier1 {
|
|
38
|
+
/** Non-skipped /recall-index calls in the range (silent turns included). */
|
|
39
|
+
pushes: number;
|
|
40
|
+
/** Pushed index lines (kind='shown' events) in the range. */
|
|
41
|
+
lines: number;
|
|
42
|
+
/** lines ÷ pushes — the pushed-block size the fence was measured with;
|
|
43
|
+
* null when there were no pushes. */
|
|
44
|
+
block_size: number | null;
|
|
45
|
+
/** Attributed lines whose memory's project differs from the request's ÷
|
|
46
|
+
* attributed lines; null when nothing attributed. */
|
|
47
|
+
cross_share: number | null;
|
|
48
|
+
/** Attributed lines ÷ all lines — the explicit attribution bound rendered
|
|
49
|
+
* beside the share (the ~4% gap is visible, never silent); null when no
|
|
50
|
+
* lines. */
|
|
51
|
+
attribution_coverage: number | null;
|
|
52
|
+
/** Attributed cross lines with a measured similarity below the effective
|
|
53
|
+
* bar ÷ attributed cross lines; null when no attributed cross lines. */
|
|
54
|
+
sub_bar_share: number | null;
|
|
55
|
+
/** Average daily COUNT(DISTINCT memory_id) of shown events over the days
|
|
56
|
+
* that have any shown events; null when none. */
|
|
57
|
+
recycling: number | null;
|
|
58
|
+
/** The effective cross-project bar the sub-bar share is measured against
|
|
59
|
+
* (calibration CROSS_PROJECT_MIN_SIMILARITY — the fence's own knob). */
|
|
60
|
+
cross_project_bar: number;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The Tier-1 metric set over one inclusive day range [fromDay, toDay]
|
|
64
|
+
* (toDay null = open-ended, the rolling-window shape). Pure SQL-shaped math
|
|
65
|
+
* over raw event rows — every value equals the hand-computed query of its
|
|
66
|
+
* formula; the tests pin exactly that (the readMemoryPrecision Level-1
|
|
67
|
+
* convention). Cross determination matches the #566 fence's own comparison:
|
|
68
|
+
* case-insensitive, a NULL memory project counts as foreign; a memory row
|
|
69
|
+
* that no longer exists reads as a NULL project (the LEFT JOIN's honest
|
|
70
|
+
* output — the fence could not have matched it either).
|
|
71
|
+
*/
|
|
72
|
+
export declare function computeTier1Metrics(db: Database.Database, fromDay: string, toDay: string | null, opts?: {
|
|
73
|
+
crossBar?: number;
|
|
74
|
+
}): QualityTier1;
|
|
75
|
+
/**
|
|
76
|
+
* The Tier-1 set over the rolling N-day window (inclusive day buckets, the
|
|
77
|
+
* readMemoryPrecision convention) — what handleDashboardData spreads into
|
|
78
|
+
* the memory_precision block and the snapshot writer stamps.
|
|
79
|
+
*/
|
|
80
|
+
export declare function readQualityTier1(db: Database.Database, windowDays: number, opts?: {
|
|
81
|
+
now?: Date;
|
|
82
|
+
crossBar?: number;
|
|
83
|
+
}): QualityTier1;
|
|
84
|
+
/** One registry entry's before/after over the raw event window — the FOUR
|
|
85
|
+
* metrics the card renders per change (block size, cross share, sub-bar
|
|
86
|
+
* share, recycling). Nulls when a side has no data (honest undefined, never
|
|
87
|
+
* zero). Deliberately compact: the memory_precision block's ≤ 2 KB budget
|
|
88
|
+
* is the gate, and the full bar/coverage echoes ride the tier1 side. */
|
|
89
|
+
export interface QualityChangeDelta {
|
|
90
|
+
id: string;
|
|
91
|
+
label: string;
|
|
92
|
+
date: string;
|
|
93
|
+
before: {
|
|
94
|
+
block_size: number | null;
|
|
95
|
+
cross_share: number | null;
|
|
96
|
+
sub_bar_share: number | null;
|
|
97
|
+
recycling: number | null;
|
|
98
|
+
} | null;
|
|
99
|
+
after: {
|
|
100
|
+
block_size: number | null;
|
|
101
|
+
cross_share: number | null;
|
|
102
|
+
sub_bar_share: number | null;
|
|
103
|
+
recycling: number | null;
|
|
104
|
+
} | null;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Every QUALITY_CHANGES entry the raw event window still covers, each with
|
|
108
|
+
* its before/after computed from raw events: before = window start up to the
|
|
109
|
+
* day BEFORE the change date, after = the change date onward. Entries older
|
|
110
|
+
* than the window are omitted (their trend lives on in the snapshot series);
|
|
111
|
+
* future-dated entries carry honest nulls on the after side until they
|
|
112
|
+
* deploy. Numbers are never pinned in code — moving a metric definition
|
|
113
|
+
* re-derives every baseline.
|
|
114
|
+
*/
|
|
115
|
+
export declare function readQualityChanges(db: Database.Database, windowDays: number, opts?: {
|
|
116
|
+
now?: Date;
|
|
117
|
+
crossBar?: number;
|
|
118
|
+
}): QualityChangeDelta[];
|
|
119
|
+
export interface CorpusHealth {
|
|
120
|
+
/** Near-duplicate clusters (size > 1) at the dedup merge threshold — the
|
|
121
|
+
* SHARED clustering core (planDedup, the same KNN + union-find the
|
|
122
|
+
* nightly merge zone and `hicortex dedup` run), so the scoreboard's count
|
|
123
|
+
* can never disagree with what a dedup pass would merge. */
|
|
124
|
+
dup_clusters: number;
|
|
125
|
+
/** Share of live (non-absorbed) memories with a non-null domain — how much
|
|
126
|
+
* of the corpus is anchored to a knowledge scope. Null on an empty
|
|
127
|
+
* corpus. */
|
|
128
|
+
scope_anchor_rate: number | null;
|
|
129
|
+
/** Count of live memories whose stored project differs from its
|
|
130
|
+
* canonicalized form — the #567 drift signal: post-reconcile drift is
|
|
131
|
+
* NEW non-canonical rows arriving through some un-normalized path. */
|
|
132
|
+
canonical_drift: number;
|
|
133
|
+
}
|
|
134
|
+
/** The trio. The dup-cluster count re-runs planDedup (read-only) — nightly
|
|
135
|
+
* cost only, exactly like the merge zone that already runs beside it. The
|
|
136
|
+
* canonical check uses the MECHANICAL fold (trim + lowercase, no alias
|
|
137
|
+
* hop): aliases are config-owned and the snapshot writer has no config —
|
|
138
|
+
* the mechanical fold is the stable definition that still catches every
|
|
139
|
+
* case/whitespace drift. */
|
|
140
|
+
export declare function computeCorpusHealth(db: Database.Database): CorpusHealth;
|
|
141
|
+
export interface GradedAggregate {
|
|
142
|
+
/** Auto-grader + owner verdict rows in the retention window. */
|
|
143
|
+
graded: number;
|
|
144
|
+
/** Rows judged useful at render (owner verdict +1, or auto-grader
|
|
145
|
+
* score ≥ QUALITY_USEFUL_SCORE). */
|
|
146
|
+
useful: number;
|
|
147
|
+
/** useful ÷ graded; null when nothing graded. */
|
|
148
|
+
useful_share: number | null;
|
|
149
|
+
/** Auto-graded rows below QUALITY_CONTESTED_CONFIDENCE that the owner
|
|
150
|
+
* has not answered — exactly the contested drawer's population. */
|
|
151
|
+
contested: number;
|
|
152
|
+
}
|
|
153
|
+
/** Graded aggregates over the retention window (verdicts older than the
|
|
154
|
+
* event horizon are pruned, except owner verdicts, which stay
|
|
155
|
+
* countable forever... but for TREND comparability the window matches the
|
|
156
|
+
* event store). */
|
|
157
|
+
export declare function readGradedAggregate(db: Database.Database, opts?: {
|
|
158
|
+
now?: Date;
|
|
159
|
+
usefulScore?: number;
|
|
160
|
+
contestedBelow?: number;
|
|
161
|
+
}): GradedAggregate;
|
|
162
|
+
export interface QualitySnapshotBlock {
|
|
163
|
+
/** Tier-1 over the trailing 7-day window. */
|
|
164
|
+
tier1_7d: QualityTier1;
|
|
165
|
+
/** Tier-1 over the trailing 30-day window. */
|
|
166
|
+
tier1_30d: QualityTier1;
|
|
167
|
+
/** Graded aggregates over the retention window. */
|
|
168
|
+
graded: GradedAggregate;
|
|
169
|
+
/** The corpus-health trio at snapshot time. */
|
|
170
|
+
corpus: CorpusHealth;
|
|
171
|
+
}
|
|
172
|
+
/** Build the nightly quality block. Nightly-only by construction (only
|
|
173
|
+
* writeSnapshot calls it — the per-request dashboard path never does; the
|
|
174
|
+
* dup-cluster KNN alone forbids that). */
|
|
175
|
+
export declare function buildQualitySnapshotBlock(db: Database.Database, opts?: {
|
|
176
|
+
now?: Date;
|
|
177
|
+
}): QualitySnapshotBlock;
|
|
178
|
+
/** The decisions API endpoint: a typed-decisions API (POST typed questions,
|
|
179
|
+
* NOT /v1/chat/completions), sub-second per call at a negligible per-call
|
|
180
|
+
* cost. The model id is operator config (#582 — `qualityGradeModel`, no
|
|
181
|
+
* default). Documented failure mode: silent degradation on credit
|
|
182
|
+
* exhaustion — HTTP 200 with EMPTY answers; the client asserts the
|
|
183
|
+
* answer is non-null so that mode writes nothing and surfaces as a greppable
|
|
184
|
+
* health line instead of a silent zero. */
|
|
185
|
+
export declare const QUALITY_GRADE_DECISIONS_URL = "https://openrouter.ai/api/alpha/decisions";
|
|
186
|
+
/** One graded answer: RAW score + confidence, no thresholds applied (the
|
|
187
|
+
* #476 law — the contested slice derives at render). */
|
|
188
|
+
export interface GradeAnswer {
|
|
189
|
+
score: number;
|
|
190
|
+
confidence: number;
|
|
191
|
+
}
|
|
192
|
+
export interface GradeClient {
|
|
193
|
+
gradeLine(line: string, promptExcerpt: string, signal?: AbortSignal): Promise<GradeAnswer>;
|
|
194
|
+
}
|
|
195
|
+
/** Thrown when the endpoint answers HTTP 200 but the answer is null/absent —
|
|
196
|
+
* the documented credit-exhaustion silent-degradation mode. The stage
|
|
197
|
+
* catches it, writes nothing, logs `event=quality_grade_failed`, and the
|
|
198
|
+
* items retry next run (dup-over-loss). */
|
|
199
|
+
export declare class GradeEmptyAnswersError extends Error {
|
|
200
|
+
constructor();
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Build the grading client. `model` is the operator-configured model id
|
|
204
|
+
* (#582 — no default; the stage skips without one). `fetchFn` is the
|
|
205
|
+
* INJECTABLE FETCH SEAM — tests inject a fake and count calls / force both
|
|
206
|
+
* documented failure modes; production uses global fetch. No key material
|
|
207
|
+
* is ever logged. EGRESS REDACTION (#582) lives HERE, at the boundary where
|
|
208
|
+
* the request body is built: both payload parts (the line and the prompt
|
|
209
|
+
* excerpt) run through the deterministic redaction pass BEFORE the question
|
|
210
|
+
* is composed, so no caller can ship raw text to the endpoint.
|
|
211
|
+
*/
|
|
212
|
+
export declare function createGradeClient(opts: {
|
|
213
|
+
apiKey: string;
|
|
214
|
+
model: string;
|
|
215
|
+
fetchFn?: typeof fetch;
|
|
216
|
+
}): GradeClient;
|
|
217
|
+
export declare const OPENROUTER_KEY_NAME = "OPENROUTER_HICORTEX_KEY";
|
|
218
|
+
/** Resolve the key: process env wins (the systemd Environment= deployment
|
|
219
|
+
* path), then the repo-root .env (the development convenience path), then
|
|
220
|
+
* ./.env. Returns null when absent — the stage skips (fail-soft), never
|
|
221
|
+
* errors. NEVER logs the value. The repo root is three levels above this
|
|
222
|
+
* module's directory both compiled (dist/) and under vitest (src/) — the
|
|
223
|
+
* __dirname convention init.ts uses. */
|
|
224
|
+
export declare function readOpenRouterKey(envPath?: string): string | null;
|
|
225
|
+
/** One verdict row insert (the single write shape). */
|
|
226
|
+
export declare function insertVerdictRow(db: Database.Database, row: {
|
|
227
|
+
ts: string;
|
|
228
|
+
day: string;
|
|
229
|
+
push_id: number | null;
|
|
230
|
+
memory_id: string;
|
|
231
|
+
grader: string;
|
|
232
|
+
score: number | null;
|
|
233
|
+
confidence: number | null;
|
|
234
|
+
verdict: number | null;
|
|
235
|
+
}): number;
|
|
236
|
+
/** ISO-8601 week key "YYYY-Www" (UTC) — the stage's cadence gate. */
|
|
237
|
+
export declare function isoWeekKey(d: Date): string;
|
|
238
|
+
export interface QualityGradeReport {
|
|
239
|
+
/** The week the pass ran for (the caller persists it as the cursor only
|
|
240
|
+
* when `complete`). */
|
|
241
|
+
week: string;
|
|
242
|
+
/** True when the whole sample was processed — the ONLY condition that
|
|
243
|
+
* advances the week cursor (dup-over-loss: capped/deadlined/failed passes
|
|
244
|
+
* hold the cursor and retry the ungraded remainder next nightly). */
|
|
245
|
+
complete: boolean;
|
|
246
|
+
skipped?: "already-graded" | "no-api-key" | "disabled" | "no-model";
|
|
247
|
+
/** Revealed-useful lines marked useful (ZERO grading calls). */
|
|
248
|
+
revealedMarked: number;
|
|
249
|
+
/** Shown-never-fetched lines selected for grading this pass. */
|
|
250
|
+
sampled: number;
|
|
251
|
+
graded: number;
|
|
252
|
+
deferred: number;
|
|
253
|
+
}
|
|
254
|
+
export interface QualityGradeOptions {
|
|
255
|
+
now?: () => Date;
|
|
256
|
+
/** Injectable client (tests). Default: built from the resolved key + the
|
|
257
|
+
* config-read model id. */
|
|
258
|
+
client?: GradeClient;
|
|
259
|
+
/** Saved config (#582): the stage is opt-in via `qualityGrading` +
|
|
260
|
+
* `qualityGradeModel` (readStrictBoolean / readStringConfig — fail-closed:
|
|
261
|
+
* absent or wrong-typed → skip). */
|
|
262
|
+
config?: Record<string, unknown> | null;
|
|
263
|
+
/** Key resolution seam (tests). Default readOpenRouterKey. */
|
|
264
|
+
readKey?: () => string | null;
|
|
265
|
+
/** The run deadline (#405) — checked between items; a hit defers the
|
|
266
|
+
* remainder. */
|
|
267
|
+
deadline?: RunDeadline;
|
|
268
|
+
/** Weekly call cap override (tests); default QUALITY_GRADE_WEEKLY_CALL_CAP. */
|
|
269
|
+
callCap?: number;
|
|
270
|
+
/** Log seam (tests); default console.log — the `event=quality_grade_*`
|
|
271
|
+
* health lines are journald-greppable. */
|
|
272
|
+
log?: (msg: string) => void;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The weekly grading pass (#578): mark revealed-useful lines (shown then
|
|
276
|
+
* fetched in-window) useful with ZERO grading calls, then grade a sample of
|
|
277
|
+
* shown-never-fetched index lines stratified by request project, each graded
|
|
278
|
+
* AS PUSHED (the shared formatIndexLine render + the stored prompt excerpt).
|
|
279
|
+
*
|
|
280
|
+
* OWN LANE: bounded by `callCap` (default 60/week) — deliberately separate
|
|
281
|
+
* from nightlyLlmCallBudget (different provider, independent
|
|
282
|
+
* starvation risk); the consolidation budget is untouched. Deadline-aware
|
|
283
|
+
* between items (createRunDeadline). Dup-over-loss: the week cursor
|
|
284
|
+
* (state.qualityGradeWeek, the supersessionCursor convention) advances only
|
|
285
|
+
* on `complete`; an item with an existing auto-grade verdict is never
|
|
286
|
+
* re-graded (the sample filter), so a retried pass grades exactly the
|
|
287
|
+
* remainder.
|
|
288
|
+
*
|
|
289
|
+
* GATED + FAIL-SOFT (#582): the pass runs ONLY on explicit opt-in —
|
|
290
|
+
* `qualityGrading: true` + `qualityGradeModel` in config, plus the endpoint
|
|
291
|
+
* key; a missing flag, key, or model → skip with
|
|
292
|
+
* `event=quality_grade_skipped`; a client
|
|
293
|
+
* failure (incl. the documented HTTP-200-empty-answers credit-exhaustion
|
|
294
|
+
* mode, guarded by the non-null answer assertion) stops the pass with
|
|
295
|
+
* `event=quality_grade_failed`, writes nothing further, holds the cursor —
|
|
296
|
+
* neither ever throws to the caller (the nightly wraps its own try/catch
|
|
297
|
+
* anyway, mirroring pruneRecallPrecision).
|
|
298
|
+
*/
|
|
299
|
+
export declare function runQualityGradeStage(db: Database.Database, gradedWeek: string | undefined, opts?: QualityGradeOptions): Promise<QualityGradeReport>;
|
|
300
|
+
/** One contested item — an auto-graded verdict row below the confidence
|
|
301
|
+
* threshold, with the index line re-rendered through the shared
|
|
302
|
+
* formatIndexLine (the same render the grading pass graded). */
|
|
303
|
+
export interface ContestedItem {
|
|
304
|
+
id: number;
|
|
305
|
+
ts: string;
|
|
306
|
+
push_id: number | null;
|
|
307
|
+
memory_id: string;
|
|
308
|
+
score: number | null;
|
|
309
|
+
confidence: number | null;
|
|
310
|
+
/** The line as pushed; null when the memory row no longer exists (honest,
|
|
311
|
+
* never a fabricated title). */
|
|
312
|
+
line: string | null;
|
|
313
|
+
prompt_excerpt: string | null;
|
|
314
|
+
}
|
|
315
|
+
export interface ContestedList {
|
|
316
|
+
total: number;
|
|
317
|
+
limit: number;
|
|
318
|
+
offset: number;
|
|
319
|
+
items: ContestedItem[];
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* GET /dashboard/quality/contested's pure handler: the contested slice —
|
|
323
|
+
* auto-graded rows with confidence below QUALITY_CONTESTED_CONFIDENCE
|
|
324
|
+
* (render edge, echoed in the payload) that the owner has not yet answered
|
|
325
|
+
* — newest first... no: LEAST confident first (they need the thumbs most),
|
|
326
|
+
* then newest. Paginated (`limit` default 20, cap 100; `offset` default 0).
|
|
327
|
+
*/
|
|
328
|
+
export declare function listContestedVerdicts(db: Database.Database, query: {
|
|
329
|
+
limit?: unknown;
|
|
330
|
+
offset?: unknown;
|
|
331
|
+
}, opts?: {
|
|
332
|
+
contestedBelow?: number;
|
|
333
|
+
}): ContestedList;
|
|
334
|
+
/**
|
|
335
|
+
* PUT /dashboard/quality/verdict's pure handler — the dashboard's THIRD
|
|
336
|
+
* scoped writer (after /dashboard/model and /dashboard/capture-pause; same
|
|
337
|
+
* convention: strict validation, injected effect, 404 on unknown id).
|
|
338
|
+
*
|
|
339
|
+
* Body: `{id: number, verdict: 1 | -1}` — numeric thumbs (1 = useful, -1 =
|
|
340
|
+
* not); no string aliases to mis-parse. `id` is a recall_verdicts row id
|
|
341
|
+
* (the contested item's). The verdict persists as a NEW `grader='owner'`
|
|
342
|
+
* row against the same (push_id, memory_id) — history is append-only, the
|
|
343
|
+
* owner verdicts accumulate, and the auto-graded row it answers stays
|
|
344
|
+
* untouched.
|
|
345
|
+
*/
|
|
346
|
+
export declare function recordOwnerVerdict(db: Database.Database, body: unknown, opts?: {
|
|
347
|
+
now?: () => Date;
|
|
348
|
+
}): {
|
|
349
|
+
status: number;
|
|
350
|
+
body: Record<string, unknown>;
|
|
351
|
+
};
|