@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.
@@ -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
@@ -94,6 +94,7 @@ exports.handleMemoryGet = handleMemoryGet;
94
94
  exports.formatMemoryGetText = formatMemoryGetText;
95
95
  const storage = __importStar(require("./storage.js"));
96
96
  const wrapper_prompt_js_1 = require("./wrapper-prompt.js");
97
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
97
98
  const type_labels_js_1 = require("./type-labels.js");
98
99
  const retrieval_js_1 = require("./retrieval.js");
99
100
  const CALIBRATION = __importStar(require("./calibration.js"));
@@ -191,16 +192,47 @@ function formatIndexLine(r, maxLen = DEFAULT_TITLE_CHARS) {
191
192
  * Relevance gate: a real BM25 text match (FTS) passes unconditionally; a
192
193
  * vector-only candidate must clear `minSimilarity`.
193
194
  *
194
- * NOTE: FTS hits BYPASS the similarity floor, so raising the floor shifts
195
- * weight toward FTS-sourced entries. In practice FTS is currently inert on
196
- * real prompts — eval #3 had 0 FTS rows / 2,208 (2,203 vector + 5 graph), and
197
- * a relevance sample returned 96/96 vector — so the floor change is safe as
198
- * measured. But FTS quality is unmeasured; if FTS starts firing
199
- * (e.g. as #205's fielded-BM25 retune beds in), give it its own eval.
195
+ * #566 cross-project fence (optional `scope`): when a project scope is
196
+ * present and the bar is ARMED — strictly above the RECALL floor
197
+ * (RECALL_MIN_SIMILARITY, the documented OFF threshold: 0 or any value ≤
198
+ * 0.62 is off on EVERY surface, not just sites that happen to carry a floor;
199
+ * floor-less surfaces [/search no-param, the MCP tool] must not arm at
200
+ * values the docs call off) — a candidate whose project DIFFERS from the
201
+ * scope's (case-insensitive — 161 measured events sat on Hicortex/hicortex
202
+ * case splits; a null/absent candidate project counts as foreign) must clear
203
+ * max(bar, the site floor) on a MEASURED cosine — the fence only RAISES a
204
+ * site's existing floor, never weakens it. No source branching is needed:
205
+ * FTS-only and graph-only hits carry similarity null → they naturally do not
206
+ * admit cross-project (that IS the scoped FTS bypass — same-project token
207
+ * matches still pass unconditionally below); `both` and `vector` carry a
208
+ * measured cosine → gated like a vector hit. Same-project candidates fall
209
+ * through to the legacy branch with the site floor unchanged (the fence
210
+ * never floors same-project). Every pre-#566 two-arg caller (incl. the eval
211
+ * harness) passes no scope and gets exactly the old behavior.
200
212
  */
201
- function passesRelevanceGate(r, minSimilarity) {
213
+ function passesRelevanceGate(r, minSimilarity, scope) {
214
+ // #566 fence branch — armed against the RECALL floor (the knob's
215
+ // documented off threshold, the same constant everywhere), NOT this site's
216
+ // floor; same-project candidates skip to the legacy branch untouched.
217
+ if (scope && scope.crossProjectMinSimilarity > CALIBRATION.RECALL_MIN_SIMILARITY) {
218
+ const sameProject = r.project !== null &&
219
+ r.project.toLowerCase() === scope.project.toLowerCase();
220
+ if (!sameProject) {
221
+ // max(bar, site floor): the fence may only raise the bar — a /search
222
+ // caller at minSimilarity 0.9 with the knob at 0.72 must not see a
223
+ // cross 0.75 row re-admitted by this branch. At /recall-index the site
224
+ // floor IS the recall floor, so max() reduces to the bar there.
225
+ return (typeof r.similarity === "number" &&
226
+ r.similarity >= Math.max(scope.crossProjectMinSimilarity, minSimilarity ?? 0));
227
+ }
228
+ }
229
+ // Legacy branch — byte-identical to pre-#566 (same-project, no scope, or a
230
+ // disarmed bar). `minSimilarity === undefined` = this site has no base
231
+ // floor (the /search no-param contract) → only the FTS bypass applies.
202
232
  if (r.source === "fts" || r.source === "both")
203
233
  return true;
234
+ if (minSimilarity === undefined)
235
+ return true;
204
236
  return typeof r.similarity === "number" && r.similarity >= minSimilarity;
205
237
  }
206
238
  /**
@@ -340,6 +372,10 @@ async function handleRecallIndex(deps, body) {
340
372
  const maxItems = clampInt(deps.options?.maxItems, DEFAULT_MAX_ITEMS, 1, 20);
341
373
  const titleChars = clampInt(deps.options?.titleChars, DEFAULT_TITLE_CHARS, 40, 400);
342
374
  const minSimilarity = clampNumber(deps.options?.minSimilarity, DEFAULT_MIN_SIMILARITY, 0, 1);
375
+ // #566: the cross-project fence bar — resolved once per request from the
376
+ // options seam (production threads the boot-resolved config value; the
377
+ // default IS the calibration constant, so the fence is ON out of the box).
378
+ const crossMinSimilarity = clampNumber(deps.options?.crossProjectMinSimilarity, CALIBRATION.CROSS_PROJECT_MIN_SIMILARITY, 0, 1);
343
379
  // #324: clamped to [0, maxItems] — the floor is a reservation inside the
344
380
  // item cap, never an expansion of it.
345
381
  const noveltySlots = resolveNoveltyFloorSlots(deps.options?.noveltyFloorSlots, maxItems);
@@ -350,10 +386,25 @@ async function handleRecallIndex(deps, body) {
350
386
  // (plugin config). Neither excludes anything — both are zero-boost-neutral
351
387
  // score terms in computeScore. (0.16.x: `privacy` is no longer threaded —
352
388
  // vestigial column, never filtered; a plugin's privacy_filter is a no-op.)
389
+ // #567: project folds through the canonicalizer (the stored corpus is
390
+ // canonical; a raw pushed label would silently lose its own affinity boost
391
+ // and arm the #566 fence against its own project on a case variant).
353
392
  const filters = {
354
- project: typeof req.project === "string" && req.project ? req.project : undefined,
393
+ project: typeof req.project === "string" && req.project
394
+ ? (0, project_canonicalize_js_1.canonicalizeProject)(req.project, deps.options?.projectAliases) ?? undefined
395
+ : undefined,
355
396
  mission_domains: parseStringListParam(req.mission_domains),
356
397
  };
398
+ // #566: the gate scope exists ONLY when the request carries a project — a
399
+ // no-project request is byte-identical with the fence on or off. One scope,
400
+ // threaded into BOTH gate call sites below (blended picks + pureFiltered);
401
+ // the pure list feeds the #324 novelty floor AND the #329 backfill, so both
402
+ // inherit the fence through it. No second gate anywhere else (retrieve()
403
+ // stays fence-free — cold-exposure slots live inside it and their output
404
+ // flows through the gate here).
405
+ const gateScope = filters.project !== undefined
406
+ ? { project: filters.project, crossProjectMinSimilarity: crossMinSimilarity }
407
+ : undefined;
357
408
  // #324 + #329 item 3: when the floor is armed AND would differ from the
358
409
  // blended search, TWO searches run per recall — the blended (session-intent)
359
410
  // query that has always run, and a PURE-prompt query with no centroid blend.
@@ -391,7 +442,7 @@ async function handleRecallIndex(deps, body) {
391
442
  // Blended (session-intent) picks: relevance gate + turn-based suppression,
392
443
  // top maxItems — exactly what the index would show with no novelty floor.
393
444
  const blendedPicks = results
394
- .filter((r) => passesRelevanceGate(r, minSimilarity))
445
+ .filter((r) => passesRelevanceGate(r, minSimilarity, gateScope))
395
446
  .filter((r) => deps.registry.isShowable(sessionId, r.id))
396
447
  .slice(0, maxItems);
397
448
  // #324 novelty floor: the best match(es) for the CURRENT PROMPT ALONE are
@@ -408,7 +459,7 @@ async function handleRecallIndex(deps, body) {
408
459
  // The gate + suppression are applied ONCE to the pure list: the head feeds
409
460
  // the novelty floor, the tail feeds the #329 backfill below.
410
461
  const pureFiltered = pureResults
411
- .filter((r) => passesRelevanceGate(r, minSimilarity))
462
+ .filter((r) => passesRelevanceGate(r, minSimilarity, gateScope))
412
463
  .filter((r) => deps.registry.isShowable(sessionId, r.id));
413
464
  const blendedIds = new Set(blendedPicks.map((r) => r.id));
414
465
  const noveltyPicks = pureFiltered
@@ -0,0 +1,99 @@
1
+ /**
2
+ * `hicortex reconcile-projects` (#567) — one-shot project-label
3
+ * reconciliation for EXISTING rows.
4
+ *
5
+ * The server canonicalizes every project string at entry (project-
6
+ * canonicalize.ts, wired in mcp-server.ts); this command heals the corpus
7
+ * that predates it: the 5,544-row `hicortex`/`Hicortex` case split and the
8
+ * 14% junk-label share measured in #565 WS1. Dry run by default (report
9
+ * only, zero writes); `--apply` renames along the dedup rails.
10
+ *
11
+ * What a rename is: a pure function of the config alias map + the current
12
+ * labels — canonicalize(label) ≠ label. Same single-hop semantics as the
13
+ * entry-point fold, computed from the ORIGINAL labels BEFORE any write (the
14
+ * per-group `WHERE project = ?` updates are then order-independent). Touches
15
+ * `memories.project` and `distill_queue.project` (the inbox must not
16
+ * re-distill old labels post-rename) and NOTHING else:
17
+ * - no `memories.domain`, no `memory_tags` — tag-derived, recomputed
18
+ * nightly; a rename is not a re-classification;
19
+ * - no `dedup_log`, no new audit table — relabels are not destructive
20
+ * (dedup needed its log because merges absorb rows; the pre-apply
21
+ * backup IS the safety net here).
22
+ *
23
+ * Safety rails (the #100 `hicortex dedup` pattern): pre-apply DB backup via
24
+ * takePreDedupBackup (abort all writes on failure) → single-flight capture
25
+ * lock (waitMs 0 — a busy lock aborts, never waits) → ONE transaction per
26
+ * rename group, fail-soft per group. The FTS row syncs automatically: the
27
+ * `memories_fts_update` trigger (db.ts) fires `AFTER UPDATE OF … project`.
28
+ * SQLite's BINARY collation on `memories.project` makes the `WHERE
29
+ * project = ?` match case-sensitive — exactly what a case-split rename
30
+ * needs (`Hicortex` → `hicortex` rewrites only the variant rows).
31
+ *
32
+ * Idempotent by construction: a second run finds every label already
33
+ * canonical and reports zero groups.
34
+ */
35
+ import { acquireCaptureLock } from "./capture.js";
36
+ /** One planned rename: every row labeled `from` becomes `to`. */
37
+ export interface ReconcileGroup {
38
+ from: string;
39
+ to: string;
40
+ /** Rows in `memories` carrying the old label. */
41
+ memoryRows: number;
42
+ /** Rows in `distill_queue` carrying the old label (re-distilled canonical). */
43
+ queuedRows: number;
44
+ }
45
+ /**
46
+ * One SURVIVING label after canonicalization, with its post-rename row
47
+ * count (memories) — the junk-curation evidence: every label the alias map
48
+ * does NOT fold is listed so the operator can curate from data, and
49
+ * pure-numeric labels (the version-suffix class, e.g. `3` from
50
+ * `CAB-v0-0-3`) are flagged explicitly.
51
+ */
52
+ export interface ReconcileLabel {
53
+ label: string;
54
+ rows: number;
55
+ numeric: boolean;
56
+ }
57
+ /** --apply outcome counts. */
58
+ export interface ReconcileApplied {
59
+ groups: number;
60
+ memories: number;
61
+ queued: number;
62
+ /** Groups whose transaction failed (rolled back; retried on a re-run). */
63
+ failed: number;
64
+ }
65
+ export interface ReconcileReport {
66
+ dryRun: boolean;
67
+ /** Planned (dry run) or executed (apply) rename groups. */
68
+ groups: ReconcileGroup[];
69
+ /** Post-canonical surviving labels with row counts, numeric ones flagged. */
70
+ labels: ReconcileLabel[];
71
+ /** The pure-numeric surviving labels (the flagged subset of `labels`). */
72
+ numericLabels: string[];
73
+ /** --apply only. */
74
+ applied?: ReconcileApplied;
75
+ /** --apply only: path to the pre-apply backup. */
76
+ backupPath?: string;
77
+ /** --apply only: the capture lock was busy — zero writes, retried later. */
78
+ lockBusy?: boolean;
79
+ }
80
+ export interface ReconcileOptions {
81
+ /** Execute the renames. Default false = dry run (report only, zero writes). */
82
+ apply?: boolean;
83
+ /** DB path override (tests / snapshot verification). Defaults to resolveDbPath(). */
84
+ dbPath?: string;
85
+ /** State dir override (tests). Defaults to ~/.hicortex. Backups land under <stateDir>/backups/. */
86
+ stateDir?: string;
87
+ /** Config override (tests). Defaults to reading stateDir/config.json. */
88
+ config?: Record<string, unknown> | null;
89
+ /** Capture-lock acquirer override (tests). Defaults to the real capture.ts lock. */
90
+ acquireLock?: typeof acquireCaptureLock;
91
+ }
92
+ /**
93
+ * Run `hicortex reconcile-projects`. Dry run by default (options.apply
94
+ * falsy) — plan + report only, zero writes. `options.apply` executes:
95
+ * backup, then one transaction per rename group. A busy capture lock is an
96
+ * abort with the dedup wording (reported as `lockBusy: true`, never a
97
+ * wait); a failed backup aborts all writes (throw, like dedup).
98
+ */
99
+ export declare function runReconcileProjects(options?: ReconcileOptions): Promise<ReconcileReport>;
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ /**
3
+ * `hicortex reconcile-projects` (#567) — one-shot project-label
4
+ * reconciliation for EXISTING rows.
5
+ *
6
+ * The server canonicalizes every project string at entry (project-
7
+ * canonicalize.ts, wired in mcp-server.ts); this command heals the corpus
8
+ * that predates it: the 5,544-row `hicortex`/`Hicortex` case split and the
9
+ * 14% junk-label share measured in #565 WS1. Dry run by default (report
10
+ * only, zero writes); `--apply` renames along the dedup rails.
11
+ *
12
+ * What a rename is: a pure function of the config alias map + the current
13
+ * labels — canonicalize(label) ≠ label. Same single-hop semantics as the
14
+ * entry-point fold, computed from the ORIGINAL labels BEFORE any write (the
15
+ * per-group `WHERE project = ?` updates are then order-independent). Touches
16
+ * `memories.project` and `distill_queue.project` (the inbox must not
17
+ * re-distill old labels post-rename) and NOTHING else:
18
+ * - no `memories.domain`, no `memory_tags` — tag-derived, recomputed
19
+ * nightly; a rename is not a re-classification;
20
+ * - no `dedup_log`, no new audit table — relabels are not destructive
21
+ * (dedup needed its log because merges absorb rows; the pre-apply
22
+ * backup IS the safety net here).
23
+ *
24
+ * Safety rails (the #100 `hicortex dedup` pattern): pre-apply DB backup via
25
+ * takePreDedupBackup (abort all writes on failure) → single-flight capture
26
+ * lock (waitMs 0 — a busy lock aborts, never waits) → ONE transaction per
27
+ * rename group, fail-soft per group. The FTS row syncs automatically: the
28
+ * `memories_fts_update` trigger (db.ts) fires `AFTER UPDATE OF … project`.
29
+ * SQLite's BINARY collation on `memories.project` makes the `WHERE
30
+ * project = ?` match case-sensitive — exactly what a case-split rename
31
+ * needs (`Hicortex` → `hicortex` rewrites only the variant rows).
32
+ *
33
+ * Idempotent by construction: a second run finds every label already
34
+ * canonical and reports zero groups.
35
+ */
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.runReconcileProjects = runReconcileProjects;
38
+ const paths_js_1 = require("./paths.js");
39
+ const node_fs_1 = require("node:fs");
40
+ const node_path_1 = require("node:path");
41
+ const db_js_1 = require("./db.js");
42
+ const capture_js_1 = require("./capture.js");
43
+ const dedup_js_1 = require("./dedup.js");
44
+ const project_canonicalize_js_1 = require("./project-canonicalize.js");
45
+ const HICORTEX_HOME = (0, paths_js_1.hicortexHome)();
46
+ function readConfig(stateDir) {
47
+ try {
48
+ return JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(stateDir, "config.json"), "utf-8"));
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ /** Distinct non-blank labels + row counts from one table's project column. */
55
+ function readLabels(db, table) {
56
+ const rows = db
57
+ .prepare(`SELECT project, COUNT(*) AS c FROM ${table} WHERE project IS NOT NULL AND project != '' GROUP BY project`)
58
+ .all();
59
+ const out = new Map();
60
+ for (const r of rows)
61
+ out.set(r.project, r.c);
62
+ return out;
63
+ }
64
+ /**
65
+ * Compute the FULL plan from the ORIGINAL labels, before any write:
66
+ * rename groups (canonical ≠ label) + the post-canonical surviving-label
67
+ * report. A blank/whitespace label canonicalizes to null — not a rename
68
+ * target (blank rows are excluded by the read; they predate this command
69
+ * and carry no identity either way).
70
+ */
71
+ function planReconcile(db, aliases) {
72
+ const memoryLabels = readLabels(db, "memories");
73
+ const queuedLabels = readLabels(db, "distill_queue");
74
+ const groups = [];
75
+ const canonicalRows = new Map();
76
+ for (const [label, rows] of memoryLabels) {
77
+ const canon = (0, project_canonicalize_js_1.canonicalizeProject)(label, aliases);
78
+ if (canon !== null)
79
+ canonicalRows.set(canon, (canonicalRows.get(canon) ?? 0) + rows);
80
+ if (canon !== null && canon !== label) {
81
+ groups.push({ from: label, to: canon, memoryRows: rows, queuedRows: queuedLabels.get(label) ?? 0 });
82
+ }
83
+ }
84
+ // Queue-only labels (memories row already renamed, inbox holds the old
85
+ // label — e.g. a reconcile run between delivery and drain) group too.
86
+ for (const [label, rows] of queuedLabels) {
87
+ const canon = (0, project_canonicalize_js_1.canonicalizeProject)(label, aliases);
88
+ if (canon !== null && canon !== label && !memoryLabels.has(label)) {
89
+ groups.push({ from: label, to: canon, memoryRows: 0, queuedRows: rows });
90
+ }
91
+ }
92
+ groups.sort((a, b) => b.memoryRows - a.memoryRows || a.from.localeCompare(b.from));
93
+ const labels = [...canonicalRows.entries()]
94
+ .map(([label, rows]) => ({ label, rows, numeric: /^\d+$/.test(label) }))
95
+ .sort((a, b) => b.rows - a.rows || a.label.localeCompare(b.label));
96
+ return { groups, labels };
97
+ }
98
+ /**
99
+ * Run `hicortex reconcile-projects`. Dry run by default (options.apply
100
+ * falsy) — plan + report only, zero writes. `options.apply` executes:
101
+ * backup, then one transaction per rename group. A busy capture lock is an
102
+ * abort with the dedup wording (reported as `lockBusy: true`, never a
103
+ * wait); a failed backup aborts all writes (throw, like dedup).
104
+ */
105
+ async function runReconcileProjects(options = {}) {
106
+ const stateDir = options.stateDir ?? HICORTEX_HOME;
107
+ const config = options.config !== undefined ? options.config : readConfig(stateDir);
108
+ const aliases = (0, project_canonicalize_js_1.parseProjectAliases)(config);
109
+ // Server-mode only — client installs have no local DB.
110
+ if (config?.mode === "client") {
111
+ throw new Error("[hicortex] reconcile-projects is server-mode only (it needs the local DB). " +
112
+ `This machine is a client of ${config.serverUrl ?? "a remote server"} — run reconcile-projects on the server.`);
113
+ }
114
+ const apply = options.apply ?? false;
115
+ const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
116
+ const db = (0, db_js_1.initDb)(dbPath);
117
+ try {
118
+ console.log(`[hicortex] reconcile-projects starting (${apply ? "APPLY" : "dry-run"}): db ${dbPath}` +
119
+ (aliases ? `, ${Object.keys(aliases).length} alias(es)` : ", no aliases (mechanical fold only)"));
120
+ const { groups, labels } = planReconcile(db, aliases);
121
+ const numericLabels = labels.filter((l) => l.numeric).map((l) => l.label);
122
+ const report = { dryRun: !apply, groups, labels, numericLabels };
123
+ const totalMemories = groups.reduce((s, g) => s + g.memoryRows, 0);
124
+ const totalQueued = groups.reduce((s, g) => s + g.queuedRows, 0);
125
+ console.log(`[hicortex] reconcile-projects: ${groups.length} rename group(s), ` +
126
+ `${totalMemories} memory row(s)${totalQueued > 0 ? `, ${totalQueued} queued row(s)` : ""} ` +
127
+ `(${apply ? "applying" : "dry run — zero writes"})`);
128
+ for (const g of groups) {
129
+ console.log(`[hicortex] ${g.from} → ${g.to} (${g.memoryRows} row(s)${g.queuedRows > 0 ? `, ${g.queuedRows} queued` : ""})`);
130
+ }
131
+ // The unmapped-labels report: every SURVIVING post-canonical label with
132
+ // its row count, numerics flagged — the junk-curation evidence.
133
+ console.log(`[hicortex] surviving project labels (post-canonicalization): ${labels.length}`);
134
+ for (const l of labels) {
135
+ console.log(`[hicortex] ${l.label}: ${l.rows} row(s)${l.numeric ? " [NUMERIC — likely a junk label; consider an alias]" : ""}`);
136
+ }
137
+ if (!apply)
138
+ return report;
139
+ // --apply: single-flight capture lock (waitMs 0) so a concurrent
140
+ // nightly/capture run cannot race the renames. Busy → abort (reported,
141
+ // never a silent wait — a deliberate manual command is retried by the
142
+ // operator, like dedup).
143
+ const acquireLock = options.acquireLock ?? capture_js_1.acquireCaptureLock;
144
+ const releaseLock = await acquireLock(stateDir, 0);
145
+ if (!releaseLock) {
146
+ console.error("[hicortex] reconcile-projects --apply aborted: another capture/nightly run holds the lock. Retry when it finishes.");
147
+ report.lockBusy = true;
148
+ return report;
149
+ }
150
+ try {
151
+ // Backup FIRST — abort entirely (no renames attempted) if it fails.
152
+ let backupPath;
153
+ try {
154
+ backupPath = await (0, dedup_js_1.takePreDedupBackup)(db, stateDir, config);
155
+ }
156
+ catch (err) {
157
+ throw new Error(`[hicortex] reconcile-projects --apply aborted: backup failed (${err instanceof Error ? err.message : String(err)}). No renames attempted.`);
158
+ }
159
+ console.log(`[hicortex] Backup written: ${backupPath}`);
160
+ report.backupPath = backupPath;
161
+ const applied = { groups: 0, memories: 0, queued: 0, failed: 0 };
162
+ // ONE transaction per group: both table updates commit together, and a
163
+ // failed group rolls back whole (fail-soft — the rest proceed, the
164
+ // failed group is retried on a re-run; idempotency makes that safe).
165
+ for (const g of groups) {
166
+ try {
167
+ const renamed = db.transaction(() => {
168
+ const m = db
169
+ .prepare("UPDATE memories SET project = ? WHERE project = ?")
170
+ .run(g.to, g.from);
171
+ const q = db
172
+ .prepare("UPDATE distill_queue SET project = ? WHERE project = ?")
173
+ .run(g.to, g.from);
174
+ return { memories: m.changes, queued: q.changes };
175
+ })();
176
+ applied.groups++;
177
+ applied.memories += renamed.memories;
178
+ applied.queued += renamed.queued;
179
+ console.log(`[hicortex] renamed ${g.from} → ${g.to}: ${renamed.memories} memory row(s)${renamed.queued > 0 ? `, ${renamed.queued} queued` : ""}`);
180
+ }
181
+ catch (err) {
182
+ applied.failed++;
183
+ console.error(`[hicortex] rename FAILED (${g.from} → ${g.to}): ` +
184
+ `${err instanceof Error ? err.message : String(err)} — rolled back, left for a re-run`);
185
+ }
186
+ }
187
+ report.applied = applied;
188
+ console.log(`[hicortex] reconcile-projects complete: ${applied.groups} group(s) renamed, ` +
189
+ `${applied.memories} memory row(s), ${applied.queued} queued row(s)` +
190
+ (applied.failed > 0 ? `, ${applied.failed} group(s) FAILED (see errors above)` : ""));
191
+ return report;
192
+ }
193
+ finally {
194
+ releaseLock();
195
+ }
196
+ }
197
+ finally {
198
+ db.close();
199
+ }
200
+ }
package/dist/types.d.ts CHANGED
@@ -501,6 +501,14 @@ export interface HicortexConfig {
501
501
  llmApiKey?: string;
502
502
  /** @deprecated Use the Hicortex server for distillation and consolidation. */
503
503
  llmModel?: string;
504
+ /**
505
+ * Explicit request-dialect key for the openai-compat path (#562). The only
506
+ * recognized dialect value today is "azure" — the request sends
507
+ * max_completion_tokens instead of max_tokens and never chat_template_kwargs
508
+ * (Azure 400s on both). Absent/empty → the provider is URL-detected
509
+ * (detectProvider); the dialect is NEVER inferred from the URL.
510
+ */
511
+ llmProvider?: string;
504
512
  /** @deprecated Consolidation is owned by the server nightly. */
505
513
  consolidateHour?: number;
506
514
  /** @deprecated The OC plugin no longer opens its own database. */
@@ -705,6 +713,18 @@ export interface HicortexConfig {
705
713
  * so these were not surfacing in the top-k anyway).
706
714
  */
707
715
  memorySoftCap?: number;
716
+ /**
717
+ * The cross-project recall fence bar (#566; default 0.72 — fence ON when
718
+ * the key is absent, owner ruling 2026-10-28). A memory from a different
719
+ * project than the request's must clear this bar on a measured cosine to be
720
+ * admitted into recall/search results; same-project and unscoped recall are
721
+ * unchanged. `0` or any value ≤ the recall floor (0.62) = fence off
722
+ * (today's scope-blind behavior). Clamped to [0,1]; a wrong type warns and
723
+ * keeps the default (readUnitIntervalConfig). The one #408 config-key
724
+ * exception (firstRunLookbackDays precedent) — a per-install posture dial,
725
+ * not corpus calibration. Resolved once at server boot (restart to apply).
726
+ */
727
+ recallCrossProjectMinSimilarity?: number;
708
728
  /**
709
729
  * Hosted-service mode (issue #110, #271 — spec 2026-07-27 §1-§2). When true,
710
730
  * the server enforces hosted-tenant constraints at boot: it refuses to start