@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.
@@ -1,14 +1,16 @@
1
1
  /**
2
- * /dashboard — view-only memory analytics (#224) + the console's live-data
3
- * endpoints (#409/#421 Phase 1: /dashboard/field, /dashboard/events).
2
+ * /dashboard — memory analytics (#224) + the console's live-data endpoints
3
+ * (#409/#421 Phase 1: /dashboard/field, /dashboard/events).
4
4
  *
5
- * STRICTLY view-only: this module computes metrics, reads snapshots, writes
6
- * ONE snapshot row per full nightly run (the writer is here because the
7
- * metric SQL lives next to its definition, not in nightly.ts), and exposes
8
- * the pure data handlers mounted at GET /dashboard/data,
9
- * GET /dashboard/field and GET /dashboard/events. There are NO mutation
10
- * endpoints on the dashboard surface — the only write path is the nightly
11
- * snapshot writer + the one-time backfill, both internal.
5
+ * View-only-leaning with SCOPED writers: this module computes metrics, reads
6
+ * snapshots, writes ONE snapshot row per full nightly run (the writer is
7
+ * here because the metric SQL lives next to its definition, not in
8
+ * nightly.ts), and exposes the pure data handlers mounted at GET
9
+ * /dashboard/data, GET /dashboard/field and GET /dashboard/events. The
10
+ * mutation surface is deliberately narrow: PUT /dashboard/model (#422),
11
+ * PUT /dashboard/capture-pause (#423), and PUT /dashboard/quality/verdict
12
+ * (#578 — the contested thumbs) — each an owner-ruled scoped writer, never
13
+ * a general write path.
12
14
  *
13
15
  * Layering (mirrors how recall-index.ts holds pure logic and viz.ts holds
14
16
  * thin express adapters): all metric SQL + snapshot shape lives HERE so it
@@ -24,6 +26,7 @@ import type express from "express";
24
26
  import type Database from "better-sqlite3";
25
27
  import { type CaptureHealthRow } from "./capture-health.js";
26
28
  import { type MemoryPrecision } from "./recall-precision.js";
29
+ import { type QualitySnapshotBlock } from "./quality-scoreboard.js";
27
30
  import { type Stage } from "./stages.js";
28
31
  /** Corpus-shape snapshot. `adoption` is null in backfilled rows (point-in-time,
29
32
  * can't be reconstructed from created_at). */
@@ -158,6 +161,16 @@ export interface DashboardMetrics {
158
161
  cold_count: number;
159
162
  uses_per_showing: number | null;
160
163
  };
164
+ /**
165
+ * #578 — the quality scoreboard block: Tier-1 aggregates (7d + 30d), the
166
+ * graded aggregates, and the corpus-health trio. Stamped by the NIGHTLY
167
+ * snapshot writer ONLY (the dup-cluster KNN is far too heavy per dashboard
168
+ * load — the card renders the trio from this series, never live); the
169
+ * live dashboard path computes tier1/changes from raw events at render
170
+ * instead (handleDashboardData). Undefined on backfilled rows. New keys
171
+ * only — the metrics blob is a stable contract, existing keys untouched.
172
+ */
173
+ quality?: QualitySnapshotBlock;
161
174
  }
162
175
  /** One row of the snapshot series (run_at + parsed metrics). */
163
176
  export interface DashboardSnapshot {
@@ -749,3 +762,19 @@ export declare function handleDashboardCapturePausePut(body: unknown, setPause:
749
762
  * is skipped (200) or captured as before.
750
763
  */
751
764
  export declare function dashboardCapturePausePutHandler(getDb: () => Database.Database): express.RequestHandler;
765
+ /**
766
+ * Express adapter for GET /dashboard/quality/contested. Bearer-only (auth
767
+ * middleware, no shell exemption — it carries grading data); localhost
768
+ * bypass applies. Query: `limit` (default 20, cap 100), `offset` (default 0).
769
+ */
770
+ export declare function dashboardQualityContestedHandler(getDb: () => Database.Database): express.RequestHandler;
771
+ /**
772
+ * Express adapter for PUT /dashboard/quality/verdict — the contested
773
+ * drawer's thumbs. Body `{id: number, verdict: 1 | -1}` (numeric thumbs: 1 =
774
+ * useful, -1 = not). Persists grader='owner' (retained forever — the
775
+ * calibration reference; the nightly verdict prune never drops owner
776
+ * rows). Bearer-only like every dashboard writer; localhost bypass
777
+ * applies. 404 on an unknown id,
778
+ * 400 on a malformed body — strict validation, the model-PUT convention.
779
+ */
780
+ export declare function dashboardQualityVerdictPutHandler(getDb: () => Database.Database): express.RequestHandler;
package/dist/dashboard.js CHANGED
@@ -1,15 +1,17 @@
1
1
  "use strict";
2
2
  /**
3
- * /dashboard — view-only memory analytics (#224) + the console's live-data
4
- * endpoints (#409/#421 Phase 1: /dashboard/field, /dashboard/events).
3
+ * /dashboard — memory analytics (#224) + the console's live-data endpoints
4
+ * (#409/#421 Phase 1: /dashboard/field, /dashboard/events).
5
5
  *
6
- * STRICTLY view-only: this module computes metrics, reads snapshots, writes
7
- * ONE snapshot row per full nightly run (the writer is here because the
8
- * metric SQL lives next to its definition, not in nightly.ts), and exposes
9
- * the pure data handlers mounted at GET /dashboard/data,
10
- * GET /dashboard/field and GET /dashboard/events. There are NO mutation
11
- * endpoints on the dashboard surface — the only write path is the nightly
12
- * snapshot writer + the one-time backfill, both internal.
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
- memory_precision: (0, recall_precision_js_1.readMemoryPrecision)(db, rangeParam, {
586
- shown_sum: live.adoption?.shown_sum ?? 0,
587
- used_sum: live.adoption?.used_sum ?? 0,
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.
@@ -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, NOT access_count (that stays reserved for hicortex_get /
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. STRICTLY view-only —
2019
- // no mutation endpoints on the dashboard surface.
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.