@gamaze/hicortex 0.24.0 → 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.
@@ -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+)/);
package/dist/llm.d.ts CHANGED
@@ -68,6 +68,7 @@ export declare function resolveExplicitLlmConfig(overrides?: {
68
68
  llmBaseUrl?: string;
69
69
  llmApiKey?: string;
70
70
  llmModel?: string;
71
+ llmProvider?: string;
71
72
  }): LlmConfig | null;
72
73
  /**
73
74
  * @deprecated Use resolveExplicitLlmConfig. This alias exists only to ease
@@ -290,6 +291,9 @@ export declare class LlmClient {
290
291
  /**
291
292
  * OpenAI-compatible /v1/chat/completions (works for OpenAI, OpenRouter, etc).
292
293
  * enableThinking is read from config here (one value, all phases — #231).
294
+ * #562: the azure dialect (provider "azure", selected ONLY via config
295
+ * llmProvider) swaps the token-cap parameter to max_completion_tokens and
296
+ * never sends chat_template_kwargs — Azure 400s on both (probed 2026-10-27).
293
297
  *
294
298
  * Token usage (#246): the OpenAI spec's `usage` object is always present on
295
299
  * a successful completion — `prompt_tokens` / `completion_tokens` /
package/dist/llm.js CHANGED
@@ -59,7 +59,11 @@ const undici_1 = require("undici");
59
59
  function resolveExplicitLlmConfig(overrides) {
60
60
  // 1. Explicit config-file overrides (both baseUrl and apiKey required)
61
61
  if (overrides?.llmBaseUrl && overrides?.llmApiKey) {
62
- const provider = detectProvider(overrides.llmBaseUrl);
62
+ // #562: a non-empty llmProvider selects an explicit request DIALECT
63
+ // (today: "azure") instead of URL detection. Absent/empty → detection
64
+ // unchanged. The dialect is NEVER inferred from the URL — Azure URLs
65
+ // detect as "openai" and stay that way without the explicit key.
66
+ const provider = overrides.llmProvider || detectProvider(overrides.llmBaseUrl);
63
67
  return {
64
68
  baseUrl: overrides.llmBaseUrl,
65
69
  apiKey: overrides.llmApiKey,
@@ -123,6 +127,12 @@ function applyTierTuningOverlay(llmConfig, savedConfig) {
123
127
  const thinking = (0, config_read_js_1.readStrictBoolean)(savedConfig, "enableThinking");
124
128
  if (thinking !== undefined) {
125
129
  llmConfig.enableThinking = thinking;
130
+ // #562: inert on the azure dialect — the cloud endpoint never receives
131
+ // chat_template_kwargs (see completeOpenAiCompat). One operator-facing
132
+ // line; removing the config key clears it.
133
+ if (llmConfig.provider === "azure") {
134
+ console.warn("[hicortex] enableThinking is ignored on the azure dialect (cloud endpoint — no chat_template_kwargs is sent); remove the key to clear this warning");
135
+ }
126
136
  }
127
137
  // #337 resilience knobs. Same boundary discipline as the keys above: absent =
128
138
  // call-site defaults (timeout 900 s, probe timeout 60 s, probe TTL 5 min),
@@ -185,6 +195,7 @@ function resolveSavedLlmConfig(savedConfig, findBinary = findClaudeBinary) {
185
195
  llmBaseUrl: savedConfig?.llmBaseUrl,
186
196
  llmApiKey: savedConfig?.llmApiKey,
187
197
  llmModel: savedConfig?.llmModel,
198
+ llmProvider: savedConfig?.llmProvider,
188
199
  });
189
200
  }
190
201
  // Tuning overlay (#220: maxTokens + enableThinking; #408: the diagnostic
@@ -768,6 +779,9 @@ class LlmClient {
768
779
  /**
769
780
  * OpenAI-compatible /v1/chat/completions (works for OpenAI, OpenRouter, etc).
770
781
  * enableThinking is read from config here (one value, all phases — #231).
782
+ * #562: the azure dialect (provider "azure", selected ONLY via config
783
+ * llmProvider) swaps the token-cap parameter to max_completion_tokens and
784
+ * never sends chat_template_kwargs — Azure 400s on both (probed 2026-10-27).
771
785
  *
772
786
  * Token usage (#246): the OpenAI spec's `usage` object is always present on
773
787
  * a successful completion — `prompt_tokens` / `completion_tokens` /
@@ -794,14 +808,19 @@ class LlmClient {
794
808
  // kwarg rides every call — so it is LOCAL-endpoint only (ollama, mlx-lm
795
809
  // gateway); a cloud OpenAI/OpenRouter/Groq endpoint would 400 on the unknown
796
810
  // field. provider cannot gate this (the MLX gateway is also provider:openai),
797
- // so the operator leaves enableThinking unset for cloud endpoints. See #220.
811
+ // so the operator leaves enableThinking unset for cloud endpoints — the ONE
812
+ // exception is the azure dialect (#562), which is explicitly selected via
813
+ // llmProvider and therefore IS gated off. See #220.
814
+ const azureDialect = this.config.provider === "azure";
798
815
  const thinking = this.config.enableThinking;
799
816
  const body = {
800
817
  model,
801
818
  messages: [{ role: "user", content: prompt }],
802
- max_tokens: maxTokens,
819
+ // #562: Azure 400s on max_tokens ("not supported with this model") and
820
+ // requires max_completion_tokens — the only request-shape difference.
821
+ ...(azureDialect ? { max_completion_tokens: maxTokens } : { max_tokens: maxTokens }),
803
822
  };
804
- if (thinking !== undefined) {
823
+ if (thinking !== undefined && !azureDialect) {
805
824
  body.chat_template_kwargs = { enable_thinking: thinking };
806
825
  }
807
826
  const resp = await (0, undici_1.fetch)(url, {
@@ -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
@@ -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
@@ -703,6 +774,7 @@ async function startServer(options = {}) {
703
774
  llmBaseUrl: savedConfig?.llmBaseUrl,
704
775
  llmApiKey: savedConfig?.llmApiKey,
705
776
  llmModel: savedConfig?.llmModel,
777
+ llmProvider: savedConfig?.llmProvider,
706
778
  });
707
779
  }
708
780
  if (llmConfig) {
@@ -787,13 +859,27 @@ async function startServer(options = {}) {
787
859
  // process to the shipped constants (they remain the eval/test seam; see
788
860
  // retrieval.ts). The boot log still prints the active values — now sourced
789
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);
790
873
  retrieval.configureDecay();
791
874
  const recallCfg = retrieval.configureRecall();
792
875
  const scoringCfg = retrieval.configureScoring();
793
876
  const sessionIntentCfg = retrieval.configureSessionIntent();
794
- 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}` +
795
880
  `/window=${recallCfg.recentWindowDays}d/cold=${recallCfg.coldExposureSlots}` +
796
881
  `/novelty=${CALIBRATION.NOVELTY_FLOOR_SLOTS}` +
882
+ `/cross=${recallCrossProjectBar}` +
797
883
  ` · ` +
798
884
  `score sim=${scoringCfg.similarity}/str=${scoringCfg.strength}/conn=${scoringCfg.connections}` +
799
885
  `/K=${scoringCfg.connectionsSaturation}` +
@@ -802,10 +888,10 @@ async function startServer(options = {}) {
802
888
  `, intent w=${sessionIntentCfg.weight}` +
803
889
  (sessionIntentCfg.weight === 0 ? " (disabled)" : ""));
804
890
  // Defaults resolve inside recall-index.ts / recall-registry.ts from the
805
- // calibration constants (#408) — the options objects stay as the seams the
806
- // 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.
807
893
  recallRegistry = new recall_registry_js_1.SessionRecallRegistry();
808
- recallIndexOptions = {};
894
+ recallIndexOptions = { crossProjectMinSimilarity: recallCrossProjectBar, projectAliases };
809
895
  memoryInstructionsEnabled = savedConfig?.memoryInstructions !== false;
810
896
  if (resolvedAgents.dropped.length > 0) {
811
897
  console.warn(`[hicortex] Ignoring invalid identityAgents entries: ${resolvedAgents.dropped.join(", ")} ` +
@@ -1006,7 +1092,9 @@ async function startServer(options = {}) {
1006
1092
  sourceDomain: typeof source_domain === "string" ? source_domain : null,
1007
1093
  sourceMachine: storage.sanitizeSourceMachine(source_machine),
1008
1094
  sourceSession: source_session ?? undefined,
1009
- project: project ?? undefined,
1095
+ // #567: store canonical — legacy pre-distilled ingest from an
1096
+ // un-upgraded client folds here too.
1097
+ project: canonProject(project),
1010
1098
  memoryType: normalizedType ?? "experience",
1011
1099
  // 0.16.x: privacy defaults to null (vestigial column). A legacy client
1012
1100
  // that sends an explicit value is honored; absent → null.
@@ -1041,7 +1129,9 @@ async function startServer(options = {}) {
1041
1129
  // No hardcoded default: absent limit → the release-managed calibration
1042
1130
  // default (#408 — was the searchLimit config key).
1043
1131
  const limit = req.query.limit ? Number(req.query.limit) : undefined;
1044
- 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);
1045
1135
  // 0.16.x: `privacy` query param is ACCEPTED for backward compat (old
1046
1136
  // clients/plugins still send it) but no longer read — retrieval ignores
1047
1137
  // privacy entirely (the column is vestigial, never filtered).
@@ -1050,12 +1140,14 @@ async function startServer(options = {}) {
1050
1140
  // caller) = ungated, byte-identical behavior. The console sends the
1051
1141
  // recall floor (RECALL_MIN_SIMILARITY, via the /dashboard/field echo) so
1052
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).
1053
1147
  const minSimilarity = resolveSearchSimilarityFloor(req.query.minSimilarity);
1054
1148
  try {
1055
1149
  let results = await retrieval.retrieve(db, embedder_js_1.embed, query, { limit, project });
1056
- if (minSimilarity !== undefined) {
1057
- results = results.filter((r) => (0, recall_index_js_1.passesRelevanceGate)(r, minSimilarity));
1058
- }
1150
+ results = applySearchRelevanceGate(results, { minSimilarity, project, crossProjectMinSimilarity: recallCrossProjectBar });
1059
1151
  res.json({ results });
1060
1152
  }
1061
1153
  catch (err) {
@@ -1142,7 +1234,9 @@ async function startServer(options = {}) {
1142
1234
  res.status(503).json({ error: "Server not initialized" });
1143
1235
  return;
1144
1236
  }
1145
- 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);
1146
1240
  // No hardcoded default: absent limit → the release-managed calibration
1147
1241
  // default (#408 — was the recentLimit config key).
1148
1242
  // 0.16.x: `privacy` query param accepted but ignored (vestigial column).
@@ -1289,6 +1383,12 @@ async function startServer(options = {}) {
1289
1383
  // accounting records held posts there too. Nothing else reads them before
1290
1384
  // the guard, so semantics are unchanged.
1291
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);
1292
1392
  // #422 capture health: normalize the wire fields ONCE so every exit below
1293
1393
  // records with a one-liner (recordDistillActivity re-sanitizes machine/
1294
1394
  // agent — the builder only forwards + picks the byte count). bytes = the
@@ -1426,7 +1526,7 @@ async function startServer(options = {}) {
1426
1526
  source_agent_id,
1427
1527
  source_domain,
1428
1528
  source_machine,
1429
- project,
1529
+ project: canonProjectVal,
1430
1530
  session_id,
1431
1531
  segment_id,
1432
1532
  session_date,
@@ -1496,7 +1596,7 @@ async function startServer(options = {}) {
1496
1596
  // land in the caller's file-persisted nightly log (#156 audit trail); the
1497
1597
  // server-side per-entry console.log in distillChunk stays as well.
1498
1598
  const dropped = [];
1499
- 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) => {
1500
1600
  distillUsage.prompt += u.prompt_tokens ?? 0;
1501
1601
  distillUsage.completion += u.completion_tokens ?? 0;
1502
1602
  distillUsage.total += u.total_tokens ?? 0;
@@ -1541,7 +1641,8 @@ async function startServer(options = {}) {
1541
1641
  // Per-chunk key: "<session_id>[#<segment_id>]#<i>". The prefix
1542
1642
  // matches the dedup checks above, so a re-run is idempotent.
1543
1643
  sourceSession: sourcePrefix ? `${sourcePrefix}#${i}` : undefined,
1544
- project: project ?? undefined,
1644
+ // #567: canonical (folded once above the queue/sync branch).
1645
+ project: canonProjectVal,
1545
1646
  // #216: the distiller now classifies each entry as
1546
1647
  // experience/knowledge/decisions via the [E]/[K]/[D] tag parsed in
1547
1648
  // distiller.ts. Pre-#216 distiller output (no tag) defaults to
@@ -1617,8 +1718,10 @@ async function startServer(options = {}) {
1617
1718
  const fields = {};
1618
1719
  if (content !== undefined)
1619
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.
1620
1723
  if (project !== undefined)
1621
- fields.project = project;
1724
+ fields.project = (0, project_canonicalize_js_1.canonicalizeProject)(project, projectAliases);
1622
1725
  if (privacy !== undefined)
1623
1726
  fields.privacy = privacy;
1624
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;