@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.
@@ -52,6 +52,7 @@ exports.resolveDistillProbeGate = resolveDistillProbeGate;
52
52
  exports.createMcpServer = createMcpServer;
53
53
  exports.resolveBodyLimitMb = resolveBodyLimitMb;
54
54
  exports.resolveSearchSimilarityFloor = resolveSearchSimilarityFloor;
55
+ exports.applySearchRelevanceGate = applySearchRelevanceGate;
55
56
  exports.makeBodyLimitErrorHandler = makeBodyLimitErrorHandler;
56
57
  exports.makeContentLengthGate = makeContentLengthGate;
57
58
  exports.startServer = startServer;
@@ -93,6 +94,7 @@ const redact_js_1 = require("./redact.js");
93
94
  const capture_health_js_1 = require("./capture-health.js");
94
95
  const recall_precision_js_1 = require("./recall-precision.js");
95
96
  const capture_pause_js_1 = require("./capture-pause.js");
97
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
96
98
  const init_js_1 = require("./init.js");
97
99
  // ---------------------------------------------------------------------------
98
100
  // Server state
@@ -129,9 +131,30 @@ let identityClients = ["cc"];
129
131
  let identityAgents = {};
130
132
  // Pushed-recall dedup registry (#192) + options; configured at boot.
131
133
  let recallRegistry = new recall_registry_js_1.SessionRecallRegistry();
134
+ // #566: the cross-project recall fence bar — the ONE config-resolved recall
135
+ // knob (deliberate #408 exception on the firstRunLookbackDays precedent).
136
+ // Resolved once at boot below; consumed by the two search sites directly and
137
+ // threaded into recallIndexOptions for /recall-index.
138
+ let recallCrossProjectBar = CALIBRATION.CROSS_PROJECT_MIN_SIMILARITY;
132
139
  let recallIndexOptions = {};
140
+ // #567: the project-identity alias map (config `projectAliases`, folded at
141
+ // read — never scaffolded by init). Resolved once at boot; every
142
+ // project-string entry point below folds through it (canonProject) so the
143
+ // same project never lands as two labels regardless of which client sent it.
144
+ let projectAliases = null;
133
145
  // Product-owned memory instructions (#192): on unless config says false.
134
146
  let memoryInstructionsEnabled = true;
147
+ /**
148
+ * #567: fold ONE project string through the boot-resolved alias map — the
149
+ * shared normalization for every project-string entry point in this file
150
+ * (MCP tools + REST routes). Absent/blank/non-string → undefined (no filter
151
+ * / SQL NULL via the callers' `?? null` paths — a whitespace label is junk);
152
+ * otherwise trim + lowercase + one explicit alias hop. insertMemory/
153
+ * updateMemory themselves stay dumb (no fold inside storage.ts) — this is
154
+ * the ONE place labels canonicalize, so every comparison downstream (recall
155
+ * affinity, lesson selection, the dedup project rail) sees the same value.
156
+ */
157
+ const canonProject = (v) => (0, project_canonicalize_js_1.canonicalizeProject)(typeof v === "string" ? v : null, projectAliases) ?? undefined;
135
158
  // Cache detectChunkSize results keyed by "<provider>/<model>@<baseUrl>" so we
136
159
  // probe each endpoint once per server boot rather than once per /distill request.
137
160
  const chunkSizeCache = new Map();
@@ -192,8 +215,17 @@ function createMcpServer() {
192
215
  if (!db)
193
216
  return { content: [{ type: "text", text: "Hicortex not initialized" }], isError: true };
194
217
  try {
195
- const results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project });
196
- return { content: [{ type: "text", text: formatResults(results) }] };
218
+ // #567: fold the project scope ONCE so retrieve, the fence scope, and
219
+ // the gate below all see the same canonical value.
220
+ const canon = canonProject(project);
221
+ const results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project: canon });
222
+ // #566: gate with the same composed search gate as REST /search —
223
+ // this site had NO gate at all before (a scope-blind asymmetry).
224
+ // Same-project and no-project results are unchanged (the helper is
225
+ // identity for them absent a minSimilarity); cross-project rows below
226
+ // the fence bar drop only when a project scope is present.
227
+ const gated = applySearchRelevanceGate(results, { project: canon, crossProjectMinSimilarity: recallCrossProjectBar });
228
+ return { content: [{ type: "text", text: formatResults(gated) }] };
197
229
  }
198
230
  catch (err) {
199
231
  return { content: [{ type: "text", text: `Search failed: ${err instanceof Error ? err.message : String(err)}` }], isError: true };
@@ -227,7 +259,8 @@ function createMcpServer() {
227
259
  if (!db)
228
260
  return { content: [{ type: "text", text: "Hicortex not initialized" }], isError: true };
229
261
  try {
230
- const results = retrieval.searchRecent(db, { project, limit });
262
+ // #567: fold the filter so a raw client label matches the canonical corpus.
263
+ const results = retrieval.searchRecent(db, { project: canonProject(project), limit });
231
264
  return { content: [{ type: "text", text: formatResults(results) }] };
232
265
  }
233
266
  catch (err) {
@@ -262,7 +295,8 @@ function createMcpServer() {
262
295
  const embedding = await (0, embedder_js_1.embed)(content);
263
296
  const id = storage.insertMemory(db, content, embedding, {
264
297
  sourceAgent: "claude-code/manual",
265
- project,
298
+ // #567: store canonical (fold + alias hop at the entry point).
299
+ project: canonProject(project),
266
300
  // Normalize legacy raw enum to the canonical term the DB stores.
267
301
  memoryType: memory_type ? (0, type_labels_js_1.normalizeMemoryType)(memory_type) : "experience",
268
302
  });
@@ -297,8 +331,10 @@ function createMcpServer() {
297
331
  const fields = {};
298
332
  if (content !== undefined)
299
333
  fields.content = content;
334
+ // #567: fold — a blank-after-fold label becomes SQL NULL (a
335
+ // whitespace label is junk), never a stored variant.
300
336
  if (project !== undefined)
301
- fields.project = project;
337
+ fields.project = (0, project_canonicalize_js_1.canonicalizeProject)(project, projectAliases);
302
338
  // Normalize legacy raw enum to canonical human terms before DB write.
303
339
  if (memory_type !== undefined)
304
340
  fields.memory_type = (0, type_labels_js_1.normalizeMemoryType)(memory_type);
@@ -344,7 +380,8 @@ function createMcpServer() {
344
380
  if (!db)
345
381
  return { content: [{ type: "text", text: "Hicortex not initialized" }], isError: true };
346
382
  try {
347
- const lessons = storage.getLessons(db, days ?? 7, project);
383
+ // #567: fold the filter — lessons come back canonical, the query must ask canonically.
384
+ const lessons = storage.getLessons(db, days ?? 7, canonProject(project));
348
385
  if (lessons.length === 0) {
349
386
  return { content: [{ type: "text", text: "No Learnings found for the specified period." }] };
350
387
  }
@@ -524,6 +561,40 @@ function resolveSearchSimilarityFloor(raw) {
524
561
  return undefined;
525
562
  return Math.min(1, Math.max(0, v));
526
563
  }
564
+ /**
565
+ * The ONE composed search gate shared by REST /search and the MCP
566
+ * `hicortex_search` tool (#566). Pure — exported for tests (the
567
+ * resolveSearchSimilarityFloor precedent).
568
+ *
569
+ * - `minSimilarity` (the #409 optional query floor): applied post-hoc with
570
+ * the exported recall gate — FTS/`both` hits pass regardless, vector-only
571
+ * hits must clear the floor.
572
+ * - `project` + `crossProjectMinSimilarity` (the #566 fence): when a
573
+ * NON-EMPTY project scope is present and the bar is > 0, cross-project
574
+ * candidates must clear the raised bar on a measured cosine. An
575
+ * empty-string project is NO scope (REST /search normalizes "" away with
576
+ * its truthiness check; the MCP tool's zod schema lets "" through — the
577
+ * normalization lives here so both surfaces agree). A bar of 0 = fence
578
+ * off → never scopes → identity. Whether the bar is ARMED (strictly
579
+ * above the RECALL floor — the documented OFF threshold, on every
580
+ * surface) is decided INSIDE the gate — one decision site, not
581
+ * duplicated here.
582
+ *
583
+ * Identity when there is nothing to gate (`minSimilarity` undefined AND no
584
+ * scope) — the pre-#566 no-param / no-project contracts are untouched,
585
+ * including previously-ungated same-project rows (graph-only hits survive).
586
+ */
587
+ function applySearchRelevanceGate(results, opts) {
588
+ const scope = typeof opts.project === "string" &&
589
+ opts.project !== "" &&
590
+ typeof opts.crossProjectMinSimilarity === "number" &&
591
+ opts.crossProjectMinSimilarity > 0
592
+ ? { project: opts.project, crossProjectMinSimilarity: opts.crossProjectMinSimilarity }
593
+ : undefined;
594
+ if (opts.minSimilarity === undefined && scope === undefined)
595
+ return results;
596
+ return results.filter((r) => (0, recall_index_js_1.passesRelevanceGate)(r, opts.minSimilarity, scope));
597
+ }
527
598
  /**
528
599
  * Express error middleware (#7): translate express.json's default HTML 413
529
600
  * (entity.too.large) into a consistent JSON response. Catches body-parser
@@ -788,13 +859,27 @@ async function startServer(options = {}) {
788
859
  // process to the shipped constants (they remain the eval/test seam; see
789
860
  // retrieval.ts). The boot log still prints the active values — now sourced
790
861
  // from the calibration constants via the configure*() returns.
862
+ //
863
+ // #566: the ONE exception — the cross-project fence bar IS config-resolved
864
+ // (`recallCrossProjectMinSimilarity`, the deliberate #408 exception on the
865
+ // firstRunLookbackDays precedent: a per-install posture dial, not corpus
866
+ // calibration). Boot-time; restart to apply.
867
+ recallCrossProjectBar = (0, config_read_js_1.readUnitIntervalConfig)(savedConfig ?? {}, "recallCrossProjectMinSimilarity", CALIBRATION.CROSS_PROJECT_MIN_SIMILARITY);
868
+ // #567: project-identity alias map, resolved once at boot like the fence
869
+ // bar above (restart to apply). A rejected/cycle map is null — the fold
870
+ // degrades to mechanical trim+lowercase, and the reader has already warned
871
+ // why. No boot log line beyond that: an absent map is the default state.
872
+ projectAliases = (0, project_canonicalize_js_1.parseProjectAliases)(savedConfig);
791
873
  retrieval.configureDecay();
792
874
  const recallCfg = retrieval.configureRecall();
793
875
  const scoringCfg = retrieval.configureScoring();
794
876
  const sessionIntentCfg = retrieval.configureSessionIntent();
795
- console.log(`[hicortex] Recall (release-managed calibration): k=${recallCfg.searchLimit}/recent=${recallCfg.recentLimit}` +
877
+ console.log(
878
+ // Everything on this line is release-managed EXCEPT /cross= (config-sourced, #566).
879
+ `[hicortex] Recall (release-managed calibration): k=${recallCfg.searchLimit}/recent=${recallCfg.recentLimit}` +
796
880
  `/window=${recallCfg.recentWindowDays}d/cold=${recallCfg.coldExposureSlots}` +
797
881
  `/novelty=${CALIBRATION.NOVELTY_FLOOR_SLOTS}` +
882
+ `/cross=${recallCrossProjectBar}` +
798
883
  ` · ` +
799
884
  `score sim=${scoringCfg.similarity}/str=${scoringCfg.strength}/conn=${scoringCfg.connections}` +
800
885
  `/K=${scoringCfg.connectionsSaturation}` +
@@ -803,10 +888,10 @@ async function startServer(options = {}) {
803
888
  `, intent w=${sessionIntentCfg.weight}` +
804
889
  (sessionIntentCfg.weight === 0 ? " (disabled)" : ""));
805
890
  // Defaults resolve inside recall-index.ts / recall-registry.ts from the
806
- // calibration constants (#408) — the options objects stay as the seams the
807
- // eval injects through.
891
+ // calibration constants (#408) — the options object stays the eval/test
892
+ // seam for the rest, now carrying the one config-resolved recall knob.
808
893
  recallRegistry = new recall_registry_js_1.SessionRecallRegistry();
809
- recallIndexOptions = {};
894
+ recallIndexOptions = { crossProjectMinSimilarity: recallCrossProjectBar, projectAliases };
810
895
  memoryInstructionsEnabled = savedConfig?.memoryInstructions !== false;
811
896
  if (resolvedAgents.dropped.length > 0) {
812
897
  console.warn(`[hicortex] Ignoring invalid identityAgents entries: ${resolvedAgents.dropped.join(", ")} ` +
@@ -1007,7 +1092,9 @@ async function startServer(options = {}) {
1007
1092
  sourceDomain: typeof source_domain === "string" ? source_domain : null,
1008
1093
  sourceMachine: storage.sanitizeSourceMachine(source_machine),
1009
1094
  sourceSession: source_session ?? undefined,
1010
- project: project ?? undefined,
1095
+ // #567: store canonical — legacy pre-distilled ingest from an
1096
+ // un-upgraded client folds here too.
1097
+ project: canonProject(project),
1011
1098
  memoryType: normalizedType ?? "experience",
1012
1099
  // 0.16.x: privacy defaults to null (vestigial column). A legacy client
1013
1100
  // that sends an explicit value is honored; absent → null.
@@ -1042,7 +1129,9 @@ async function startServer(options = {}) {
1042
1129
  // No hardcoded default: absent limit → the release-managed calibration
1043
1130
  // default (#408 — was the searchLimit config key).
1044
1131
  const limit = req.query.limit ? Number(req.query.limit) : undefined;
1045
- const project = typeof req.query.project === "string" && req.query.project ? req.query.project : undefined;
1132
+ // #567: fold ONCE (blank/non-string → undefined, the old truthiness
1133
+ // normalization) — retrieve and the gate below share the canonical value.
1134
+ const project = canonProject(req.query.project);
1046
1135
  // 0.16.x: `privacy` query param is ACCEPTED for backward compat (old
1047
1136
  // clients/plugins still send it) but no longer read — retrieval ignores
1048
1137
  // privacy entirely (the column is vestigial, never filtered).
@@ -1051,12 +1140,14 @@ async function startServer(options = {}) {
1051
1140
  // caller) = ungated, byte-identical behavior. The console sends the
1052
1141
  // recall floor (RECALL_MIN_SIMILARITY, via the /dashboard/field echo) so
1053
1142
  // vector nearest-neighbor junk below it never renders as "results".
1143
+ // #566: the same composed call now also carries the cross-project fence —
1144
+ // the #409 floor is unchanged in effect; the fence applies only when the
1145
+ // request carries a project (applySearchRelevanceGate is identity
1146
+ // otherwise).
1054
1147
  const minSimilarity = resolveSearchSimilarityFloor(req.query.minSimilarity);
1055
1148
  try {
1056
1149
  let results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project });
1057
- if (minSimilarity !== undefined) {
1058
- results = results.filter((r) => (0, recall_index_js_1.passesRelevanceGate)(r, minSimilarity));
1059
- }
1150
+ results = applySearchRelevanceGate(results, { minSimilarity, project, crossProjectMinSimilarity: recallCrossProjectBar });
1060
1151
  res.json({ results });
1061
1152
  }
1062
1153
  catch (err) {
@@ -1065,8 +1156,9 @@ async function startServer(options = {}) {
1065
1156
  });
1066
1157
  // REST /recall-index — pushed recall index (#192). One recall logic for all
1067
1158
  // harnesses: CC UserPromptSubmit hook, Hermes/OC per-turn plugins. Returns a
1068
- // compact index block (or null); exposure is recorded as shown_count +
1069
- // 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 /
1070
1162
  // GET /memory — real use). {reset: true} clears the session's dedup state
1071
1163
  // (SessionStart/compaction).
1072
1164
  //
@@ -1143,7 +1235,9 @@ async function startServer(options = {}) {
1143
1235
  res.status(503).json({ error: "Server not initialized" });
1144
1236
  return;
1145
1237
  }
1146
- const project = typeof req.query.project === "string" && req.query.project ? req.query.project : undefined;
1238
+ // #567: fold once (blank/non-string → undefined, the old truthiness
1239
+ // normalization folded in).
1240
+ const project = canonProject(req.query.project);
1147
1241
  // No hardcoded default: absent limit → the release-managed calibration
1148
1242
  // default (#408 — was the recentLimit config key).
1149
1243
  // 0.16.x: `privacy` query param accepted but ignored (vestigial column).
@@ -1290,6 +1384,12 @@ async function startServer(options = {}) {
1290
1384
  // accounting records held posts there too. Nothing else reads them before
1291
1385
  // the guard, so semantics are unchanged.
1292
1386
  const { text, messages, source_agent, source_agent_id, source_domain, source_machine, project, session_id, segment_id, session_date, privacy } = req.body ?? {};
1387
+ // #567: fold the wire project ONCE, right after the destructure — the
1388
+ // queue enqueue, the sync distill prompt, and the insert opts below all
1389
+ // carry the canonical value, so an un-upgraded client's raw label never
1390
+ // lands as a stored variant (old npx clients, frozen plugin copies, and
1391
+ // un-refreshed extensions all canonicalize for free at the server).
1392
+ const canonProjectVal = canonProject(project);
1293
1393
  // #422 capture health: normalize the wire fields ONCE so every exit below
1294
1394
  // records with a one-liner (recordDistillActivity re-sanitizes machine/
1295
1395
  // agent — the builder only forwards + picks the byte count). bytes = the
@@ -1427,7 +1527,7 @@ async function startServer(options = {}) {
1427
1527
  source_agent_id,
1428
1528
  source_domain,
1429
1529
  source_machine,
1430
- project,
1530
+ project: canonProjectVal,
1431
1531
  session_id,
1432
1532
  segment_id,
1433
1533
  session_date,
@@ -1497,7 +1597,7 @@ async function startServer(options = {}) {
1497
1597
  // land in the caller's file-persisted nightly log (#156 audit trail); the
1498
1598
  // server-side per-entry console.log in distillChunk stays as well.
1499
1599
  const dropped = [];
1500
- const entries = await (0, distiller_js_1.distillSession)(llm, conversationText, project ?? "unknown", date, chunkSize, dropped, (u) => {
1600
+ const entries = await (0, distiller_js_1.distillSession)(llm, conversationText, canonProjectVal ?? "unknown", date, chunkSize, dropped, (u) => {
1501
1601
  distillUsage.prompt += u.prompt_tokens ?? 0;
1502
1602
  distillUsage.completion += u.completion_tokens ?? 0;
1503
1603
  distillUsage.total += u.total_tokens ?? 0;
@@ -1542,7 +1642,8 @@ async function startServer(options = {}) {
1542
1642
  // Per-chunk key: "<session_id>[#<segment_id>]#<i>". The prefix
1543
1643
  // matches the dedup checks above, so a re-run is idempotent.
1544
1644
  sourceSession: sourcePrefix ? `${sourcePrefix}#${i}` : undefined,
1545
- project: project ?? undefined,
1645
+ // #567: canonical (folded once above the queue/sync branch).
1646
+ project: canonProjectVal,
1546
1647
  // #216: the distiller now classifies each entry as
1547
1648
  // experience/knowledge/decisions via the [E]/[K]/[D] tag parsed in
1548
1649
  // distiller.ts. Pre-#216 distiller output (no tag) defaults to
@@ -1618,8 +1719,10 @@ async function startServer(options = {}) {
1618
1719
  const fields = {};
1619
1720
  if (content !== undefined)
1620
1721
  fields.content = content;
1722
+ // #567: fold — a blank-after-fold label becomes SQL NULL (a whitespace
1723
+ // label is junk), never a stored variant.
1621
1724
  if (project !== undefined)
1622
- fields.project = project;
1725
+ fields.project = (0, project_canonicalize_js_1.canonicalizeProject)(project, projectAliases);
1623
1726
  if (privacy !== undefined)
1624
1727
  fields.privacy = privacy;
1625
1728
  // Validate + normalize memory_type BEFORE adding to `fields` so the
@@ -1913,8 +2016,10 @@ async function startServer(options = {}) {
1913
2016
  // GET /dashboard/data — the metric payload (series, composition, digest).
1914
2017
  // Bearer-only (the auth middleware is installed at app boot); no separate
1915
2018
  // exemption. The handler lives in src/dashboard.ts (pure); this is the thin
1916
- // express adapter that injects the live db + config. STRICTLY view-only —
1917
- // 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).
1918
2023
  app.get("/dashboard/data", (0, dashboard_js_1.dashboardDataHandler)(() => db, () => readConfigFile(stateDir)));
1919
2024
  // GET /dashboard/field — the console flight-field payload (#409/#421
1920
2025
  // Phase 1): the whole live store as minimal fields (titles ≤100 via the
@@ -1957,6 +2062,26 @@ async function startServer(options = {}) {
1957
2062
  // (auth middleware, no shell exemption — it mutates operator state);
1958
2063
  // localhost bypass applies. Handler + adapter live in src/dashboard.ts.
1959
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));
1960
2085
  // GET /account — account identity for the console nav (name/org/plan from
1961
2086
  // config). The LIGHTWEIGHT twin of the account block inside /dashboard/data:
1962
2087
  // the /viz and /identity/ui pages need only this, not the metric payload;
package/dist/nightly.js CHANGED
@@ -78,10 +78,12 @@ const identity_store_js_1 = require("./identity-store.js");
78
78
  const capture_cursors_js_1 = require("./capture-cursors.js");
79
79
  const capture_js_1 = require("./capture.js");
80
80
  const distill_queue_js_1 = require("./distill-queue.js");
81
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
81
82
  const token_budget_js_1 = require("./token-budget.js");
82
83
  const run_deadline_js_1 = require("./run-deadline.js");
83
84
  const dashboard_js_1 = require("./dashboard.js");
84
85
  const recall_precision_js_1 = require("./recall-precision.js");
86
+ const quality_scoreboard_js_1 = require("./quality-scoreboard.js");
85
87
  const telemetry_js_1 = require("./telemetry.js");
86
88
  const init_js_1 = require("./init.js");
87
89
  const backup_js_1 = require("./backup.js");
@@ -728,6 +730,10 @@ async function runNightly(options = {}) {
728
730
  deadline,
729
731
  yieldUrl: (0, config_read_js_1.readStringConfig)(savedConfig ?? {}, "drainYieldUrl") ?? undefined,
730
732
  probeBusy: makeDrainYieldProbe(),
733
+ // #567: the drain folds queued rows' projects through the same
734
+ // boot-time alias map the daemon resolved (rows queued pre-deploy
735
+ // still hold raw wire labels).
736
+ projectAliases: (0, project_canonicalize_js_1.parseProjectAliases)(savedConfig),
731
737
  });
732
738
  // #5 metering, same as the daemon's sync path: record tokens against
733
739
  // the monthly budget (incl. a failed item's partial usage) and fold
@@ -1170,6 +1176,31 @@ async function runNightly(options = {}) {
1170
1176
  console.warn(`[hicortex] Recall-precision retention prune failed: ` +
1171
1177
  `${pruneErr instanceof Error ? pruneErr.message : String(pruneErr)}`);
1172
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
+ }
1173
1204
  }
1174
1205
  // Anonymous telemetry (fire-and-forget, full nightly only).
1175
1206
  // Capture-only runs are excluded to avoid inflating install pings.
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Project-identity canonicalization (#567).
3
+ *
4
+ * The SAME project arrives under different labels: `hicortex` vs `Hicortex`
5
+ * (case comes from the session-root dir name) split one project across two,
6
+ * and junk labels (`default`, version-suffix numerics like `3`) carry no
7
+ * project identity at all. Measured on the 22,691-memory corpus audit (#565
8
+ * WS1): 5,544 rows split on case alone, 14% of the corpus under junk labels,
9
+ * and project mismatch blocking 59 of 69 near-duplicate clusters in
10
+ * `hicortex dedup` (423 excess rows). Every comparison that keys on project
11
+ * (recall affinity, lesson selection, the dedup project rail) is exact
12
+ * `===` — so variants break affinity that should exist.
13
+ *
14
+ * The fix is ONE pure normalization applied at every project-string entry
15
+ * point (server) plus the client-side comparison site (the CC SessionStart
16
+ * hook): trim → lowercase → ONE explicit alias hop. Nothing else:
17
+ *
18
+ * - NO separator folding, NO edit distance, NO embedding similarity — two
19
+ * genuinely different labels never collapse without an explicit
20
+ * `projectAliases` entry (the #567 anti-goal: a rename must never merge
21
+ * two real projects).
22
+ * - The alias map is owner-curated config (`projectAliases` in
23
+ * config.json), folded at read, never scaffolded by init (an alias map
24
+ * has no sane generic default — the telemetry-key precedent).
25
+ *
26
+ * `hicortex reconcile-projects` (reconcile-projects.ts) applies the same
27
+ * function to EXISTING rows so the corpus heals without silent rewrites.
28
+ */
29
+ /**
30
+ * The mechanical fold: trim + lowercase. Labels are dir-name derived and
31
+ * display-lowercase was accepted by the owner (no case-preservation
32
+ * machinery — Option 3 stayed rejected), so this is the whole canonical
33
+ * alphabet.
34
+ */
35
+ export declare function foldProjectLabel(raw: string): string;
36
+ /**
37
+ * Canonicalize one project label: fold, then ONE alias hop
38
+ * (`aliases[folded] ?? folded`). Absent/blank input (or a non-string) →
39
+ * null — callers store/compare SQL NULL, never a whitespace label.
40
+ *
41
+ * Exactly ONE hop: an alias-of-alias (`a → b`, `b → c`) is NOT followed —
42
+ * canonicalize(a) is `b`, not `c`. The map is a flat renaming table, not a
43
+ * chain; parseProjectAliases rejects hop CYCLES loudly at load, but chains
44
+ * are legal (and single-hop by design) — curate the map to point every
45
+ * synonym directly at its canonical label.
46
+ *
47
+ * Prototype-safe: the hop uses an own-property lookup, so a label like
48
+ * `"constructor"` can never resolve through the Object prototype chain.
49
+ */
50
+ export declare function canonicalizeProject(raw: string | null | undefined, aliases?: Readonly<Record<string, string>> | null): string | null;
51
+ /**
52
+ * Read + validate the `projectAliases` config key (`{ "raw": "canonical" }`).
53
+ * Boundary posture per config-read.ts (the parseHours whole-list precedent):
54
+ *
55
+ * - key absent → null (no aliases — mechanical fold only);
56
+ * - not a plain object → warn + null;
57
+ * - every key AND target folded through foldProjectLabel, so
58
+ * `{"Hicortex ": " Work "}` behaves as `{"hicortex": "work"}`;
59
+ * - a non-string target, or a key/target that folds to an empty label →
60
+ * warn naming the key, drop just that entry (an alias to/from nothing
61
+ * is a config slip);
62
+ * - a NON-TRIVIAL cycle (following hops from a key returns to it in ≥2
63
+ * hops — e.g. `a→b, b→a`) → warn naming the cycle and reject the WHOLE
64
+ * map (→ null). A cyclic map contradicts itself under the one-hop
65
+ * lookup (fold(a)=b while fold(b)=a — the labels can never converge),
66
+ * so it is an operator error to notice, not half-apply. A self-map
67
+ * `a→a` returns to its key in 1 hop — a harmless no-op, kept folded.
68
+ *
69
+ * A map whose every entry was dropped resolves to null (nothing to alias).
70
+ */
71
+ export declare function parseProjectAliases(config: Record<string, unknown> | null | undefined): Readonly<Record<string, string>> | null;
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ /**
3
+ * Project-identity canonicalization (#567).
4
+ *
5
+ * The SAME project arrives under different labels: `hicortex` vs `Hicortex`
6
+ * (case comes from the session-root dir name) split one project across two,
7
+ * and junk labels (`default`, version-suffix numerics like `3`) carry no
8
+ * project identity at all. Measured on the 22,691-memory corpus audit (#565
9
+ * WS1): 5,544 rows split on case alone, 14% of the corpus under junk labels,
10
+ * and project mismatch blocking 59 of 69 near-duplicate clusters in
11
+ * `hicortex dedup` (423 excess rows). Every comparison that keys on project
12
+ * (recall affinity, lesson selection, the dedup project rail) is exact
13
+ * `===` — so variants break affinity that should exist.
14
+ *
15
+ * The fix is ONE pure normalization applied at every project-string entry
16
+ * point (server) plus the client-side comparison site (the CC SessionStart
17
+ * hook): trim → lowercase → ONE explicit alias hop. Nothing else:
18
+ *
19
+ * - NO separator folding, NO edit distance, NO embedding similarity — two
20
+ * genuinely different labels never collapse without an explicit
21
+ * `projectAliases` entry (the #567 anti-goal: a rename must never merge
22
+ * two real projects).
23
+ * - The alias map is owner-curated config (`projectAliases` in
24
+ * config.json), folded at read, never scaffolded by init (an alias map
25
+ * has no sane generic default — the telemetry-key precedent).
26
+ *
27
+ * `hicortex reconcile-projects` (reconcile-projects.ts) applies the same
28
+ * function to EXISTING rows so the corpus heals without silent rewrites.
29
+ */
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.foldProjectLabel = foldProjectLabel;
32
+ exports.canonicalizeProject = canonicalizeProject;
33
+ exports.parseProjectAliases = parseProjectAliases;
34
+ /**
35
+ * The mechanical fold: trim + lowercase. Labels are dir-name derived and
36
+ * display-lowercase was accepted by the owner (no case-preservation
37
+ * machinery — Option 3 stayed rejected), so this is the whole canonical
38
+ * alphabet.
39
+ */
40
+ function foldProjectLabel(raw) {
41
+ return raw.trim().toLowerCase();
42
+ }
43
+ /**
44
+ * Canonicalize one project label: fold, then ONE alias hop
45
+ * (`aliases[folded] ?? folded`). Absent/blank input (or a non-string) →
46
+ * null — callers store/compare SQL NULL, never a whitespace label.
47
+ *
48
+ * Exactly ONE hop: an alias-of-alias (`a → b`, `b → c`) is NOT followed —
49
+ * canonicalize(a) is `b`, not `c`. The map is a flat renaming table, not a
50
+ * chain; parseProjectAliases rejects hop CYCLES loudly at load, but chains
51
+ * are legal (and single-hop by design) — curate the map to point every
52
+ * synonym directly at its canonical label.
53
+ *
54
+ * Prototype-safe: the hop uses an own-property lookup, so a label like
55
+ * `"constructor"` can never resolve through the Object prototype chain.
56
+ */
57
+ function canonicalizeProject(raw, aliases) {
58
+ if (typeof raw !== "string")
59
+ return null;
60
+ const folded = foldProjectLabel(raw);
61
+ if (folded === "")
62
+ return null;
63
+ if (aliases && Object.hasOwn(aliases, folded))
64
+ return aliases[folded];
65
+ return folded;
66
+ }
67
+ /**
68
+ * Read + validate the `projectAliases` config key (`{ "raw": "canonical" }`).
69
+ * Boundary posture per config-read.ts (the parseHours whole-list precedent):
70
+ *
71
+ * - key absent → null (no aliases — mechanical fold only);
72
+ * - not a plain object → warn + null;
73
+ * - every key AND target folded through foldProjectLabel, so
74
+ * `{"Hicortex ": " Work "}` behaves as `{"hicortex": "work"}`;
75
+ * - a non-string target, or a key/target that folds to an empty label →
76
+ * warn naming the key, drop just that entry (an alias to/from nothing
77
+ * is a config slip);
78
+ * - a NON-TRIVIAL cycle (following hops from a key returns to it in ≥2
79
+ * hops — e.g. `a→b, b→a`) → warn naming the cycle and reject the WHOLE
80
+ * map (→ null). A cyclic map contradicts itself under the one-hop
81
+ * lookup (fold(a)=b while fold(b)=a — the labels can never converge),
82
+ * so it is an operator error to notice, not half-apply. A self-map
83
+ * `a→a` returns to its key in 1 hop — a harmless no-op, kept folded.
84
+ *
85
+ * A map whose every entry was dropped resolves to null (nothing to alias).
86
+ */
87
+ function parseProjectAliases(config) {
88
+ if (!config)
89
+ return null;
90
+ const v = config.projectAliases;
91
+ if (v === undefined)
92
+ return null;
93
+ if (typeof v !== "object" || v === null || Array.isArray(v)) {
94
+ console.warn('[hicortex] config "projectAliases" is not an object — ignored.');
95
+ return null;
96
+ }
97
+ const out = {};
98
+ for (const [rawKey, rawTarget] of Object.entries(v)) {
99
+ if (typeof rawTarget !== "string") {
100
+ console.warn(`[hicortex] config "projectAliases"."${rawKey}" target is not a string — entry dropped.`);
101
+ continue;
102
+ }
103
+ const key = foldProjectLabel(rawKey);
104
+ const target = foldProjectLabel(rawTarget);
105
+ if (key === "" || target === "") {
106
+ console.warn(`[hicortex] config "projectAliases"."${rawKey}" folds to an empty label — entry dropped.`);
107
+ continue;
108
+ }
109
+ out[key] = target;
110
+ }
111
+ const keys = Object.keys(out);
112
+ // Cycle rejection: walk hops from every key, bounded by the map size (a
113
+ // longer walk must revisit a node — either the start, found here, or a
114
+ // member of a cycle the walk from THAT member will find).
115
+ for (const key of keys) {
116
+ let cur = key;
117
+ for (let hops = 0; hops < keys.length; hops++) {
118
+ cur = Object.hasOwn(out, cur) ? out[cur] : undefined;
119
+ if (cur === undefined)
120
+ break;
121
+ if (cur === key) {
122
+ if (hops + 1 >= 2) {
123
+ console.warn(`[hicortex] config "projectAliases" contains a cycle through "${key}" ` +
124
+ `(single-hop lookup: "${key}" → "${out[key]}" but they can never converge) — ` +
125
+ `the whole alias map is ignored. Point every synonym directly at its canonical label.`);
126
+ return null;
127
+ }
128
+ break; // self-map at hop 1 — harmless no-op
129
+ }
130
+ }
131
+ }
132
+ return keys.length > 0 ? out : null;
133
+ }