@gamaze/hicortex 0.24.1 → 0.25.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) {
@@ -1143,7 +1234,9 @@ async function startServer(options = {}) {
1143
1234
  res.status(503).json({ error: "Server not initialized" });
1144
1235
  return;
1145
1236
  }
1146
- const project = typeof req.query.project === "string" && req.query.project ? req.query.project : undefined;
1237
+ // #567: fold once (blank/non-string → undefined, the old truthiness
1238
+ // normalization folded in).
1239
+ const project = canonProject(req.query.project);
1147
1240
  // No hardcoded default: absent limit → the release-managed calibration
1148
1241
  // default (#408 — was the recentLimit config key).
1149
1242
  // 0.16.x: `privacy` query param accepted but ignored (vestigial column).
@@ -1290,6 +1383,12 @@ async function startServer(options = {}) {
1290
1383
  // accounting records held posts there too. Nothing else reads them before
1291
1384
  // the guard, so semantics are unchanged.
1292
1385
  const { text, messages, source_agent, source_agent_id, source_domain, source_machine, project, session_id, segment_id, session_date, privacy } = req.body ?? {};
1386
+ // #567: fold the wire project ONCE, right after the destructure — the
1387
+ // queue enqueue, the sync distill prompt, and the insert opts below all
1388
+ // carry the canonical value, so an un-upgraded client's raw label never
1389
+ // lands as a stored variant (old npx clients, frozen plugin copies, and
1390
+ // un-refreshed extensions all canonicalize for free at the server).
1391
+ const canonProjectVal = canonProject(project);
1293
1392
  // #422 capture health: normalize the wire fields ONCE so every exit below
1294
1393
  // records with a one-liner (recordDistillActivity re-sanitizes machine/
1295
1394
  // agent — the builder only forwards + picks the byte count). bytes = the
@@ -1427,7 +1526,7 @@ async function startServer(options = {}) {
1427
1526
  source_agent_id,
1428
1527
  source_domain,
1429
1528
  source_machine,
1430
- project,
1529
+ project: canonProjectVal,
1431
1530
  session_id,
1432
1531
  segment_id,
1433
1532
  session_date,
@@ -1497,7 +1596,7 @@ async function startServer(options = {}) {
1497
1596
  // land in the caller's file-persisted nightly log (#156 audit trail); the
1498
1597
  // server-side per-entry console.log in distillChunk stays as well.
1499
1598
  const dropped = [];
1500
- const entries = await (0, distiller_js_1.distillSession)(llm, conversationText, project ?? "unknown", date, chunkSize, dropped, (u) => {
1599
+ const entries = await (0, distiller_js_1.distillSession)(llm, conversationText, canonProjectVal ?? "unknown", date, chunkSize, dropped, (u) => {
1501
1600
  distillUsage.prompt += u.prompt_tokens ?? 0;
1502
1601
  distillUsage.completion += u.completion_tokens ?? 0;
1503
1602
  distillUsage.total += u.total_tokens ?? 0;
@@ -1542,7 +1641,8 @@ async function startServer(options = {}) {
1542
1641
  // Per-chunk key: "<session_id>[#<segment_id>]#<i>". The prefix
1543
1642
  // matches the dedup checks above, so a re-run is idempotent.
1544
1643
  sourceSession: sourcePrefix ? `${sourcePrefix}#${i}` : undefined,
1545
- project: project ?? undefined,
1644
+ // #567: canonical (folded once above the queue/sync branch).
1645
+ project: canonProjectVal,
1546
1646
  // #216: the distiller now classifies each entry as
1547
1647
  // experience/knowledge/decisions via the [E]/[K]/[D] tag parsed in
1548
1648
  // distiller.ts. Pre-#216 distiller output (no tag) defaults to
@@ -1618,8 +1718,10 @@ async function startServer(options = {}) {
1618
1718
  const fields = {};
1619
1719
  if (content !== undefined)
1620
1720
  fields.content = content;
1721
+ // #567: fold — a blank-after-fold label becomes SQL NULL (a whitespace
1722
+ // label is junk), never a stored variant.
1621
1723
  if (project !== undefined)
1622
- fields.project = project;
1724
+ fields.project = (0, project_canonicalize_js_1.canonicalizeProject)(project, projectAliases);
1623
1725
  if (privacy !== undefined)
1624
1726
  fields.privacy = privacy;
1625
1727
  // Validate + normalize memory_type BEFORE adding to `fields` so the
package/dist/nightly.js CHANGED
@@ -78,6 +78,7 @@ 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");
@@ -728,6 +729,10 @@ async function runNightly(options = {}) {
728
729
  deadline,
729
730
  yieldUrl: (0, config_read_js_1.readStringConfig)(savedConfig ?? {}, "drainYieldUrl") ?? undefined,
730
731
  probeBusy: makeDrainYieldProbe(),
732
+ // #567: the drain folds queued rows' projects through the same
733
+ // boot-time alias map the daemon resolved (rows queued pre-deploy
734
+ // still hold raw wire labels).
735
+ projectAliases: (0, project_canonicalize_js_1.parseProjectAliases)(savedConfig),
731
736
  });
732
737
  // #5 metering, same as the daemon's sync path: record tokens against
733
738
  // the monthly budget (incl. a failed item's partial usage) and fold
@@ -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
+ }
@@ -87,6 +87,22 @@ export interface RecallIndexOptions {
87
87
  * coldExposureSlots sizing: small, a floor not a takeover. 0 disables the
88
88
  * pure-prompt search entirely (the kill-switch). Clamped to [0, maxItems]. */
89
89
  noveltyFloorSlots?: number;
90
+ /** #566 cross-project recall fence bar — a candidate from a DIFFERENT
91
+ * project than the request's must clear this on a measured cosine
92
+ * (scope-conditional; same-project keeps the 0.62 floor, no-scope
93
+ * requests are untouched). The one recall knob that is CONFIG-RESOLVED
94
+ * (`recallCrossProjectMinSimilarity`, the deliberate #408 exception on
95
+ * the firstRunLookbackDays precedent) — production sets it from the
96
+ * boot-resolved config value; eval/tests inject through this field.
97
+ * Default = calibration CROSS_PROJECT_MIN_SIMILARITY (0.72, fence ON when
98
+ * absent — owner ruling 2026-10-28); 0 or ≤ the recall floor = fence off. */
99
+ crossProjectMinSimilarity?: number;
100
+ /** #567: the project-identity alias map — `filters.project` is folded at
101
+ * its build site so a raw client-pushed label (cwd-derived, unnormalized)
102
+ * compares equal to the canonical corpus. null/absent → mechanical fold
103
+ * only. Production threads the boot-resolved config value (mcp-server);
104
+ * tests inject through this field, like every other option here. */
105
+ projectAliases?: Readonly<Record<string, string>> | null;
90
106
  }
91
107
  /** Default #324 novelty-floor slots (release-managed — calibration.ts
92
108
  * NOVELTY_FLOOR_SLOTS). 2 mirrors coldExposureSlots sizing — enough to
@@ -129,18 +145,39 @@ export declare function memoryTitle(content: string, maxLen?: number): string;
129
145
  export declare function formatIndexLine(r: MemorySearchResult & {
130
146
  domain?: string | null;
131
147
  }, maxLen?: number): string;
148
+ /**
149
+ * #566 cross-project recall fence — the request's project scope plus the
150
+ * resolved fence bar (see RecallIndexOptions.crossProjectMinSimilarity).
151
+ * Built by handleRecallIndex when the request carries a `project`; consumed
152
+ * by passesRelevanceGate's optional third argument.
153
+ */
154
+ export interface RelevanceScope {
155
+ project: string;
156
+ crossProjectMinSimilarity: number;
157
+ }
132
158
  /**
133
159
  * Relevance gate: a real BM25 text match (FTS) passes unconditionally; a
134
160
  * vector-only candidate must clear `minSimilarity`.
135
161
  *
136
- * NOTE: FTS hits BYPASS the similarity floor, so raising the floor shifts
137
- * weight toward FTS-sourced entries. In practice FTS is currently inert on
138
- * real prompts — eval #3 had 0 FTS rows / 2,208 (2,203 vector + 5 graph), and
139
- * a relevance sample returned 96/96 vector — so the floor change is safe as
140
- * measured. But FTS quality is unmeasured; if FTS starts firing
141
- * (e.g. as #205's fielded-BM25 retune beds in), give it its own eval.
162
+ * #566 cross-project fence (optional `scope`): when a project scope is
163
+ * present and the bar is ARMED — strictly above the RECALL floor
164
+ * (RECALL_MIN_SIMILARITY, the documented OFF threshold: 0 or any value ≤
165
+ * 0.62 is off on EVERY surface, not just sites that happen to carry a floor;
166
+ * floor-less surfaces [/search no-param, the MCP tool] must not arm at
167
+ * values the docs call off) — a candidate whose project DIFFERS from the
168
+ * scope's (case-insensitive — 161 measured events sat on Hicortex/hicortex
169
+ * case splits; a null/absent candidate project counts as foreign) must clear
170
+ * max(bar, the site floor) on a MEASURED cosine — the fence only RAISES a
171
+ * site's existing floor, never weakens it. No source branching is needed:
172
+ * FTS-only and graph-only hits carry similarity null → they naturally do not
173
+ * admit cross-project (that IS the scoped FTS bypass — same-project token
174
+ * matches still pass unconditionally below); `both` and `vector` carry a
175
+ * measured cosine → gated like a vector hit. Same-project candidates fall
176
+ * through to the legacy branch with the site floor unchanged (the fence
177
+ * never floors same-project). Every pre-#566 two-arg caller (incl. the eval
178
+ * harness) passes no scope and gets exactly the old behavior.
142
179
  */
143
- export declare function passesRelevanceGate(r: MemorySearchResult, minSimilarity: number): boolean;
180
+ export declare function passesRelevanceGate(r: MemorySearchResult, minSimilarity: number | undefined, scope?: RelevanceScope): boolean;
144
181
  /** Recall filters a client may push per request (#193 review F1): a scoped
145
182
  * plugin (Hermes default_project / mission_domains) must be able to narrow
146
183
  * recall exactly like the legacy /search prefetch did — dropping them