@gamaze/hicortex 0.24.1 → 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/dist/cli.js CHANGED
@@ -17,6 +17,10 @@
17
17
  * dedup --apply Execute the merge (default: dry run);
18
18
  * losers are absorbed (kept as evidence,
19
19
  * hidden from recall), not deleted
20
+ * reconcile-projects One-shot project-label reconciliation (issue #567)
21
+ * reconcile-projects --apply Execute the renames (default: dry
22
+ * run); canonicalizes existing rows via
23
+ * the case fold + the projectAliases map
20
24
  * sweep-volatile One-shot sweep of volatile GH-status/version rows (#489)
21
25
  * sweep-volatile --apply Demote matches via absorb (default:
22
26
  * dry run; backup first, audit trail)
@@ -309,6 +313,30 @@ switch (command) {
309
313
  });
310
314
  break;
311
315
  }
316
+ case "reconcile-projects": {
317
+ // One-shot project-label reconciliation (#567): canonicalize EXISTING
318
+ // rows under the case fold + the projectAliases map. Mirrors `dedup`:
319
+ // dry-run default, --apply explicit (backup first, one transaction per
320
+ // rename group); flags parsed here, the runner lives in
321
+ // reconcile-projects.ts so this switch stays thin.
322
+ const args = process.argv.slice(3);
323
+ let dbPath;
324
+ try {
325
+ dbPath = (0, cli_args_js_1.readValueFlag)(args, "--db");
326
+ }
327
+ catch {
328
+ console.error("[hicortex] reconcile-projects: --db requires a path value");
329
+ process.exit(1);
330
+ }
331
+ const reconcileOptions = { apply: args.includes("--apply"), dbPath };
332
+ import("./reconcile-projects.js").then(({ runReconcileProjects }) => {
333
+ runReconcileProjects(reconcileOptions).catch((err) => {
334
+ console.error(err instanceof Error ? err.message : `[hicortex] reconcile-projects failed: ${err}`);
335
+ process.exit(1);
336
+ });
337
+ });
338
+ break;
339
+ }
312
340
  case "sweep-volatile": {
313
341
  // One-shot store sweep of volatile GH-status/version rows (#489,
314
342
  // deliverable iii): reuses the distill path's deterministic gate over the
@@ -471,6 +499,7 @@ Commands:
471
499
  nightly Run nightly denoise + capture + consolidate
472
500
  relink Resumable link-discovery pass over the ENTIRE corpus (server mode)
473
501
  dedup Cluster + merge near-duplicate memories (server mode; dry run by default)
502
+ reconcile-projects Canonicalize existing project labels (server mode; dry run by default)
474
503
  history Show a memory's rewrite history, or roll one back (server mode)
475
504
  history <id> List rewrite events (read-only)
476
505
  history --rollback <row> Undo one rewrite + un-absorb its triggers
@@ -506,6 +535,9 @@ Options:
506
535
  dedup --threshold <t> Override the threshold for one run (default: the
507
536
  release-managed calibration ceiling, 0.92)
508
537
  dedup --db <path> DB path override (defaults to the configured DB)
538
+ reconcile-projects --apply Execute the project renames (default: dry run, report only)
539
+ Backup first; renames memories + distill_queue only
540
+ reconcile-projects --db <path> DB path override (defaults to the configured DB)
509
541
  history --rollback <row> Roll back history row <row>: restores prior content/status, un-absorbs triggers
510
542
  history --db <path> DB path override (defaults to the configured DB)
511
543
  backup --out <dir> Write the artifact into <dir> as hicortex-<ISO>.tar.gz (default: <home>/backups)
@@ -30,6 +30,17 @@ export declare function readStrictBoolean(config: Record<string, unknown>, key:
30
30
  * value (e.g. memorySoftCap's eviction opt-out, timerJitterSeconds).
31
31
  */
32
32
  export declare function readNonNegativeConfig(config: Record<string, unknown>, key: string, def: number): number;
33
+ /**
34
+ * Read a finite number clamped into the unit interval [0, 1] (#566 — the
35
+ * similarity-bar keys). 0 is a VALID value here (the deliberate "off"
36
+ * setting — unlike readPositiveConfig, which rejects it), and out-of-range
37
+ * numbers CLAMP rather than warn: the caller's contract is a similarity bar,
38
+ * and 1.5 / -0.2 carry the same intent as 1 / 0 (full fence / off), not a
39
+ * typo class the operator must notice. Only a wrong TYPE (string, null,
40
+ * NaN, …) warns and keeps `def` — the readPositiveConfig boundary posture
41
+ * against silent coercion.
42
+ */
43
+ export declare function readUnitIntervalConfig(config: Record<string, unknown>, key: string, def: number): number;
33
44
  /**
34
45
  * Read + validate an array of scheduling hours (integers 0–23, local time) for
35
46
  * the capture/consolidation timers (0.17). Returns the validated, de-duped,
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.readPositiveConfig = readPositiveConfig;
18
18
  exports.readStrictBoolean = readStrictBoolean;
19
19
  exports.readNonNegativeConfig = readNonNegativeConfig;
20
+ exports.readUnitIntervalConfig = readUnitIntervalConfig;
20
21
  exports.parseHours = parseHours;
21
22
  exports.readStringConfig = readStringConfig;
22
23
  exports.readAccount = readAccount;
@@ -63,6 +64,26 @@ function readNonNegativeConfig(config, key, def) {
63
64
  console.warn(`[hicortex] config "${key}" = ${String(v)} is not a non-negative finite number — using default ${def}.`);
64
65
  return def;
65
66
  }
67
+ /**
68
+ * Read a finite number clamped into the unit interval [0, 1] (#566 — the
69
+ * similarity-bar keys). 0 is a VALID value here (the deliberate "off"
70
+ * setting — unlike readPositiveConfig, which rejects it), and out-of-range
71
+ * numbers CLAMP rather than warn: the caller's contract is a similarity bar,
72
+ * and 1.5 / -0.2 carry the same intent as 1 / 0 (full fence / off), not a
73
+ * typo class the operator must notice. Only a wrong TYPE (string, null,
74
+ * NaN, …) warns and keeps `def` — the readPositiveConfig boundary posture
75
+ * against silent coercion.
76
+ */
77
+ function readUnitIntervalConfig(config, key, def) {
78
+ const v = config[key];
79
+ if (v === undefined)
80
+ return def;
81
+ if (typeof v === "number" && Number.isFinite(v)) {
82
+ return Math.min(1, Math.max(0, v));
83
+ }
84
+ console.warn(`[hicortex] config "${key}" = ${String(v)} is not a finite number — using default ${def}.`);
85
+ return def;
86
+ }
66
87
  /**
67
88
  * Read + validate an array of scheduling hours (integers 0–23, local time) for
68
89
  * the capture/consolidation timers (0.17). Returns the validated, de-duped,
@@ -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.
@@ -168,6 +168,14 @@ export interface DrainOptions {
168
168
  * real detectChunkSize, cached per endpoint like the /distill handler).
169
169
  */
170
170
  detectChunkSize?: typeof detectChunkSize;
171
+ /**
172
+ * #567: the project-identity alias map — the drain folds `item.project`
173
+ * once per item (the queue kept the wire project verbatim, so rows queued
174
+ * before the canonicalization deploy still distill + store canonical;
175
+ * defense-in-depth beside the /distill handler's own fold). null/absent →
176
+ * mechanical fold only. The nightly passes the boot-resolved config value.
177
+ */
178
+ projectAliases?: Readonly<Record<string, string>> | null;
171
179
  }
172
180
  export interface DrainReport {
173
181
  /**
@@ -79,6 +79,7 @@ const distiller_js_1 = require("./distiller.js");
79
79
  const calibration_js_1 = require("./calibration.js");
80
80
  const storage = __importStar(require("./storage.js"));
81
81
  const dedup_js_1 = require("./dedup.js");
82
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
82
83
  /** Normalize an unknown wire value into a nullable string column. */
83
84
  function str(v) {
84
85
  return typeof v === "string" && v.length > 0 ? v : null;
@@ -360,10 +361,14 @@ async function drainDistillQueue(db, opts) {
360
361
  // BEFORE distillation — see resolveDrainCreatedAt: a throwing date
361
362
  // computation after the LLM calls is the poison row.
362
363
  const createdAt = resolveDrainCreatedAt(item);
364
+ // #567: fold the queued project ONCE per item — both the distill
365
+ // prompt and the insert opts below carry the canonical value (the
366
+ // queue row keeps the raw wire label verbatim by design).
367
+ const canonProject = (0, project_canonicalize_js_1.canonicalizeProject)(item.project, opts.projectAliases);
363
368
  try {
364
369
  // Cast: DrainLlm is the structural surface distillSession uses.
365
370
  const llm = opts.llm;
366
- const entries = await (0, distiller_js_1.distillSession)(llm, item.text, item.project ?? "unknown", item.session_date ?? new Date().toISOString().slice(0, 10), chunkSize, [], (u) => {
371
+ const entries = await (0, distiller_js_1.distillSession)(llm, item.text, canonProject ?? "unknown", item.session_date ?? new Date().toISOString().slice(0, 10), chunkSize, [], (u) => {
367
372
  usage.prompt += u.prompt_tokens ?? 0;
368
373
  usage.completion += u.completion_tokens ?? 0;
369
374
  usage.total += u.total_tokens ?? 0;
@@ -398,7 +403,7 @@ async function drainDistillQueue(db, opts) {
398
403
  sourceDomain: item.source_domain,
399
404
  sourceMachine: storage.sanitizeSourceMachine(item.source_machine),
400
405
  sourceSession: sourcePrefix ? `${sourcePrefix}#${i}` : undefined,
401
- project: item.project ?? undefined,
406
+ project: canonProject ?? undefined,
402
407
  memoryType,
403
408
  privacy: item.privacy,
404
409
  createdAt,
@@ -47,6 +47,11 @@ export interface ResolvedConfig {
47
47
  agentName: string | null;
48
48
  /** Max lessons to inject (config.lessonsLimit, default 10). */
49
49
  lessonsLimit?: number;
50
+ /** #567: the project-identity alias map (config `projectAliases`, folded
51
+ * at read) — the client-side fold of the cwd-derived project uses it so
52
+ * the lesson-selection comparison converges with the canonical server
53
+ * corpus. null when the key is absent (mechanical fold only). */
54
+ projectAliases?: Readonly<Record<string, string>> | null;
50
55
  }
51
56
  /**
52
57
  * Read ~/.hicortex/config.json and resolve the server URL + auth token, or
@@ -55,6 +60,17 @@ export interface ResolvedConfig {
55
60
  * never resolve the server differently.
56
61
  */
57
62
  export declare function resolveConfig(): ResolvedConfig | null;
63
+ /**
64
+ * #567: the client-side project fold for lesson selection. The SessionStart
65
+ * hook derives its comparison project LOCALLY (basename of the session's
66
+ * cwd — the capture-side convention), while the server stores canonical
67
+ * labels; without folding the local label through the SAME function the
68
+ * `lesson.project === targetProject` affinity would silently miss on every
69
+ * case variant. Pure — exported so the fold is testable without stubbing
70
+ * fetchLessonsBlock's HTTP path (the resolveConfig/parseProjectAliases pair
71
+ * plus this function are the whole client-side seam).
72
+ */
73
+ export declare function deriveHookProject(cwd: string, aliases?: Readonly<Record<string, string>> | null): string | null;
58
74
  /**
59
75
  * Title-case a section name for its heading: split on `-`/`_`, capitalize each
60
76
  * word ("user" → "User", "my_notes" → "My Notes").
@@ -30,6 +30,7 @@
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
31
  exports.gateAndRenderContext = exports.renderContextBlock = exports.fetchLessonsContext = void 0;
32
32
  exports.resolveConfig = resolveConfig;
33
+ exports.deriveHookProject = deriveHookProject;
33
34
  exports.titleCaseSection = titleCaseSection;
34
35
  exports.orderSectionNames = orderSectionNames;
35
36
  exports.renderIdentityBlock = renderIdentityBlock;
@@ -43,6 +44,7 @@ const features_js_1 = require("./features.js");
43
44
  const extensions_js_1 = require("./extensions.js");
44
45
  const state_js_1 = require("./state.js");
45
46
  const paths_js_1 = require("./paths.js");
47
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
46
48
  const DEFAULT_PORT = 8787;
47
49
  /** Harness name this hook injects for — used to self-gate on GET /identity `clients`. */
48
50
  const THIS_HARNESS = "cc";
@@ -77,11 +79,25 @@ function resolveConfig() {
77
79
  home,
78
80
  agentName,
79
81
  lessonsLimit: typeof config.lessonsLimit === "number" ? config.lessonsLimit : undefined,
82
+ projectAliases: (0, project_canonicalize_js_1.parseProjectAliases)(config),
80
83
  };
81
84
  }
82
85
  function authHeaders(authToken) {
83
86
  return authToken ? { "Authorization": `Bearer ${authToken}` } : {};
84
87
  }
88
+ /**
89
+ * #567: the client-side project fold for lesson selection. The SessionStart
90
+ * hook derives its comparison project LOCALLY (basename of the session's
91
+ * cwd — the capture-side convention), while the server stores canonical
92
+ * labels; without folding the local label through the SAME function the
93
+ * `lesson.project === targetProject` affinity would silently miss on every
94
+ * case variant. Pure — exported so the fold is testable without stubbing
95
+ * fetchLessonsBlock's HTTP path (the resolveConfig/parseProjectAliases pair
96
+ * plus this function are the whole client-side seam).
97
+ */
98
+ function deriveHookProject(cwd, aliases) {
99
+ return (0, project_canonicalize_js_1.canonicalizeProject)((0, node_path_1.basename)(cwd), aliases);
100
+ }
85
101
  /**
86
102
  * Trust framing + provenance for the injected lessons block (#516). The
87
103
  * fence + two lines are byte-identical on every client surface (CC hook,
@@ -111,7 +127,9 @@ async function fetchLessonsBlock(cfg) {
111
127
  // path component matches the capture-side CC project name convention
112
128
  // (transcript-reader's decodeProjectDirName also takes the last component).
113
129
  // This enables in-project + same-domain lesson boosting on the CC path.
114
- const project = (0, node_path_1.basename)(process.cwd()) || null;
130
+ // #567: folded through the shared canonicalizer so the local label
131
+ // compares equal to the canonical server corpus (see deriveHookProject).
132
+ const project = deriveHookProject(process.cwd(), cfg.projectAliases);
115
133
  const selected = await (0, extensions_js_1.getLessonSelector)().select(data.lessons, { maxLessons, moduleIndex, project });
116
134
  const lessonLines = selected.map((l) => {
117
135
  const typeMatch = l.content.match(/\*\*Type:\*\* (\w+)/);
@@ -54,6 +54,34 @@ export declare function resolveBodyLimitMb(configVal: unknown, hostedMode: boole
54
54
  * shape /recall-index uses, so the two recall surfaces gate identically.
55
55
  */
56
56
  export declare function resolveSearchSimilarityFloor(raw: unknown): number | undefined;
57
+ /**
58
+ * The ONE composed search gate shared by REST /search and the MCP
59
+ * `hicortex_search` tool (#566). Pure — exported for tests (the
60
+ * resolveSearchSimilarityFloor precedent).
61
+ *
62
+ * - `minSimilarity` (the #409 optional query floor): applied post-hoc with
63
+ * the exported recall gate — FTS/`both` hits pass regardless, vector-only
64
+ * hits must clear the floor.
65
+ * - `project` + `crossProjectMinSimilarity` (the #566 fence): when a
66
+ * NON-EMPTY project scope is present and the bar is > 0, cross-project
67
+ * candidates must clear the raised bar on a measured cosine. An
68
+ * empty-string project is NO scope (REST /search normalizes "" away with
69
+ * its truthiness check; the MCP tool's zod schema lets "" through — the
70
+ * normalization lives here so both surfaces agree). A bar of 0 = fence
71
+ * off → never scopes → identity. Whether the bar is ARMED (strictly
72
+ * above the RECALL floor — the documented OFF threshold, on every
73
+ * surface) is decided INSIDE the gate — one decision site, not
74
+ * duplicated here.
75
+ *
76
+ * Identity when there is nothing to gate (`minSimilarity` undefined AND no
77
+ * scope) — the pre-#566 no-param / no-project contracts are untouched,
78
+ * including previously-ungated same-project rows (graph-only hits survive).
79
+ */
80
+ export declare function applySearchRelevanceGate(results: MemorySearchResult[], opts: {
81
+ minSimilarity?: number;
82
+ project?: string;
83
+ crossProjectMinSimilarity?: number;
84
+ }): MemorySearchResult[];
57
85
  /**
58
86
  * Express error middleware (#7): translate express.json's default HTML 413
59
87
  * (entity.too.large) into a consistent JSON response. Catches body-parser