@gamaze/hicortex 0.25.0 → 0.26.1

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,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
+ };