@gamaze/hicortex 0.24.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,13 +7,13 @@
7
7
  * memory — a menu, not the meal); the agent lazy-loads full content with
8
8
  * `hicortex_get(id)` only when a line is actually relevant.
9
9
  *
10
- * Strengthening semantics (the recall/decay alignment):
11
- * - Appearing in the index = exposure: shown_count + last_accessed refresh
12
- * (mild, temporary strengthen — the decay clock resets) via
13
- * storage.touchMemoriesShown. NO access_count bump: the promotion signal
14
- * (#448), the prune shield, and the adoption metric stay driven by real
15
- * use.
16
- * - hicortex_get = use: full strengthen (access_count + 1).
10
+ * Strengthening semantics (the recall/decay alignment, refined #569):
11
+ * - Appearing in the index = exposure ONLY: shown_count via
12
+ * storage.touchMemoriesShown. NO last_accessed write (that is the use
13
+ * clock — #569 closed the exposure-refresh loop that kept never-fetched
14
+ * noise young forever) and NO access_count bump: the promotion signal
15
+ * (#448) and the adoption metric stay driven by real use.
16
+ * - hicortex_get = use: full strengthen (access_count + 1, clock refresh).
17
17
  *
18
18
  * Anti-bloat gates: relevance floor (measured cosine, or a real BM25 match),
19
19
  * per-session TURN-based dedup (SessionRecallRegistry), short-prompt skip,
@@ -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
@@ -8,13 +8,13 @@
8
8
  * memory — a menu, not the meal); the agent lazy-loads full content with
9
9
  * `hicortex_get(id)` only when a line is actually relevant.
10
10
  *
11
- * Strengthening semantics (the recall/decay alignment):
12
- * - Appearing in the index = exposure: shown_count + last_accessed refresh
13
- * (mild, temporary strengthen — the decay clock resets) via
14
- * storage.touchMemoriesShown. NO access_count bump: the promotion signal
15
- * (#448), the prune shield, and the adoption metric stay driven by real
16
- * use.
17
- * - hicortex_get = use: full strengthen (access_count + 1).
11
+ * Strengthening semantics (the recall/decay alignment, refined #569):
12
+ * - Appearing in the index = exposure ONLY: shown_count via
13
+ * storage.touchMemoriesShown. NO last_accessed write (that is the use
14
+ * clock — #569 closed the exposure-refresh loop that kept never-fetched
15
+ * noise young forever) and NO access_count bump: the promotion signal
16
+ * (#448) and the adoption metric stay driven by real use.
17
+ * - hicortex_get = use: full strengthen (access_count + 1, clock refresh).
18
18
  *
19
19
  * Anti-bloat gates: relevance floor (measured cosine, or a real BM25 match),
20
20
  * per-session TURN-based dedup (SessionRecallRegistry), short-prompt skip,
@@ -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
  /**
@@ -326,7 +358,8 @@ async function handleRecallIndex(deps, body) {
326
358
  // before any precision recording, so a pure plumbing payload (CC delivers
327
359
  // task-notifications/command envelopes as user-role messages; any client
328
360
  // could POST one) gets {block: null} with NO recall_pushes row, NO turn
329
- // burn, NO shown_count bump, NO last_accessed refresh. The SAME shared
361
+ // burn, NO shown_count bump — no exposure of any kind (and since #569
362
+ // exposure never writes last_accessed anyway). The SAME shared
330
363
  // classifier the hook client guards with (wrapper-prompt.ts) — defense in
331
364
  // depth. A wrapper carrying real payload prose falls through and recalls on
332
365
  // the full text, exactly today's behavior (owner decision 4).
@@ -340,6 +373,10 @@ async function handleRecallIndex(deps, body) {
340
373
  const maxItems = clampInt(deps.options?.maxItems, DEFAULT_MAX_ITEMS, 1, 20);
341
374
  const titleChars = clampInt(deps.options?.titleChars, DEFAULT_TITLE_CHARS, 40, 400);
342
375
  const minSimilarity = clampNumber(deps.options?.minSimilarity, DEFAULT_MIN_SIMILARITY, 0, 1);
376
+ // #566: the cross-project fence bar — resolved once per request from the
377
+ // options seam (production threads the boot-resolved config value; the
378
+ // default IS the calibration constant, so the fence is ON out of the box).
379
+ const crossMinSimilarity = clampNumber(deps.options?.crossProjectMinSimilarity, CALIBRATION.CROSS_PROJECT_MIN_SIMILARITY, 0, 1);
343
380
  // #324: clamped to [0, maxItems] — the floor is a reservation inside the
344
381
  // item cap, never an expansion of it.
345
382
  const noveltySlots = resolveNoveltyFloorSlots(deps.options?.noveltyFloorSlots, maxItems);
@@ -350,10 +387,25 @@ async function handleRecallIndex(deps, body) {
350
387
  // (plugin config). Neither excludes anything — both are zero-boost-neutral
351
388
  // score terms in computeScore. (0.16.x: `privacy` is no longer threaded —
352
389
  // vestigial column, never filtered; a plugin's privacy_filter is a no-op.)
390
+ // #567: project folds through the canonicalizer (the stored corpus is
391
+ // canonical; a raw pushed label would silently lose its own affinity boost
392
+ // and arm the #566 fence against its own project on a case variant).
353
393
  const filters = {
354
- project: typeof req.project === "string" && req.project ? req.project : undefined,
394
+ project: typeof req.project === "string" && req.project
395
+ ? (0, project_canonicalize_js_1.canonicalizeProject)(req.project, deps.options?.projectAliases) ?? undefined
396
+ : undefined,
355
397
  mission_domains: parseStringListParam(req.mission_domains),
356
398
  };
399
+ // #566: the gate scope exists ONLY when the request carries a project — a
400
+ // no-project request is byte-identical with the fence on or off. One scope,
401
+ // threaded into BOTH gate call sites below (blended picks + pureFiltered);
402
+ // the pure list feeds the #324 novelty floor AND the #329 backfill, so both
403
+ // inherit the fence through it. No second gate anywhere else (retrieve()
404
+ // stays fence-free — cold-exposure slots live inside it and their output
405
+ // flows through the gate here).
406
+ const gateScope = filters.project !== undefined
407
+ ? { project: filters.project, crossProjectMinSimilarity: crossMinSimilarity }
408
+ : undefined;
357
409
  // #324 + #329 item 3: when the floor is armed AND would differ from the
358
410
  // blended search, TWO searches run per recall — the blended (session-intent)
359
411
  // query that has always run, and a PURE-prompt query with no centroid blend.
@@ -391,7 +443,7 @@ async function handleRecallIndex(deps, body) {
391
443
  // Blended (session-intent) picks: relevance gate + turn-based suppression,
392
444
  // top maxItems — exactly what the index would show with no novelty floor.
393
445
  const blendedPicks = results
394
- .filter((r) => passesRelevanceGate(r, minSimilarity))
446
+ .filter((r) => passesRelevanceGate(r, minSimilarity, gateScope))
395
447
  .filter((r) => deps.registry.isShowable(sessionId, r.id))
396
448
  .slice(0, maxItems);
397
449
  // #324 novelty floor: the best match(es) for the CURRENT PROMPT ALONE are
@@ -408,7 +460,7 @@ async function handleRecallIndex(deps, body) {
408
460
  // The gate + suppression are applied ONCE to the pure list: the head feeds
409
461
  // the novelty floor, the tail feeds the #329 backfill below.
410
462
  const pureFiltered = pureResults
411
- .filter((r) => passesRelevanceGate(r, minSimilarity))
463
+ .filter((r) => passesRelevanceGate(r, minSimilarity, gateScope))
412
464
  .filter((r) => deps.registry.isShowable(sessionId, r.id));
413
465
  const blendedIds = new Set(blendedPicks.map((r) => r.id));
414
466
  const noveltyPicks = pureFiltered
@@ -446,7 +498,10 @@ async function handleRecallIndex(deps, body) {
446
498
  // Fail-soft like every recording site.
447
499
  if (deps.precision) {
448
500
  try {
449
- deps.precision.recorder(deps.db, { sessionId, prompt, ids: [] });
501
+ // #578: the canonicalized project label threads into the push row
502
+ // too (attribution) — filters.project is already computed above; a
503
+ // silent turn carries it like any other.
504
+ deps.precision.recorder(deps.db, { sessionId, prompt, ids: [], project: filters.project ?? null });
450
505
  }
451
506
  catch (err) {
452
507
  console.warn(`[hicortex] recall-precision push recording failed (fail-soft): ` +
@@ -459,8 +514,8 @@ async function handleRecallIndex(deps, body) {
459
514
  deps.registry.markShown(sessionId, ids);
460
515
  const nowIso = new Date().toISOString();
461
516
  // #476 Memory Precision: record the push + per-line events IN THE SAME
462
- // TRANSACTION as the exposure write (the recorder owns the unit — it calls
463
- // touchMemoriesShown inside its own transaction). FAIL-SOFT: on any error
517
+ // TRANSACTION as the exposure counter write (the recorder owns the unit —
518
+ // it calls touchMemoriesShown inside its own transaction). FAIL-SOFT: on any error
464
519
  // (or when the seams are absent — library callers, test doubles) the plain
465
520
  // exposure write runs instead, so shown_count NEVER depends on telemetry.
466
521
  let exposureWritten = false;
@@ -470,7 +525,7 @@ async function handleRecallIndex(deps, body) {
470
525
  deps.precision.promptEmbed(prompt),
471
526
  deps.precision.basis(deps.db),
472
527
  ]);
473
- deps.precision.recorder(deps.db, { ts: nowIso, sessionId, prompt, ids, promptEmbedding: promptEmb }, basis);
528
+ deps.precision.recorder(deps.db, { ts: nowIso, sessionId, prompt, ids, promptEmbedding: promptEmb, project: filters.project ?? null }, basis);
474
529
  exposureWritten = true;
475
530
  }
476
531
  catch (err) {
@@ -479,8 +534,9 @@ async function handleRecallIndex(deps, body) {
479
534
  }
480
535
  }
481
536
  if (!exposureWritten) {
482
- // Exposure signal: shown_count + last_accessed refresh, NOT access_count.
483
- storage.touchMemoriesShown(deps.db, ids, nowIso);
537
+ // Exposure signal: shown_count only — NOT last_accessed (the use clock,
538
+ // #569), NOT access_count.
539
+ storage.touchMemoriesShown(deps.db, ids);
484
540
  }
485
541
  const lines = picked.map((r) => formatIndexLine(r, titleChars));
486
542
  const block = [
@@ -21,8 +21,9 @@
21
21
  * FAIL-SOFT LAW: recording is telemetry. Any error here is caught by the
22
22
  * CALLER (handleRecallIndex / handleMemoryGet) and swallowed — the recall
23
23
  * response (status 200 + block) is never affected, and the exposure signal
24
- * (touchMemoriesShown) never depends on it (the handler falls back to the
25
- * plain exposure write when recording is absent or fails).
24
+ * (touchMemoriesShown — shown_count only, never the use clock #569) never
25
+ * depends on it (the handler falls back to the plain exposure write when
26
+ * recording is absent or fails).
26
27
  *
27
28
  * The perf law (bounded hot-path cost): the recorder computes cosines with
28
29
  * the request's ALREADY-MEMOIZED prompt embedding (createRecallRetrieveFn's
@@ -31,6 +32,7 @@
31
32
  * that already writes and spends ~100-300 ms embedding and searching.
32
33
  */
33
34
  import type Database from "better-sqlite3";
35
+ import type { QualityTier1, QualityChangeDelta } from "./quality-scoreboard.js";
34
36
  /** One non-skipped /recall-index call to record (recorder seam contract —
35
37
  * recall-index.ts types its precision deps against this). */
36
38
  export interface RecallPushEntry {
@@ -48,14 +50,21 @@ export interface RecallPushEntry {
48
50
  * memoized embed; unused on a silent turn, so no embed is ever spent on
49
51
  * recording). */
50
52
  promptEmbedding?: Float32Array;
53
+ /** #578: the request's CANONICALIZED project label — exactly the value the
54
+ * #566 fence gated with (handleRecallIndex's filters.project). Null when
55
+ * the request carried none. Stored on recall_pushes (migration v26) so the
56
+ * quality scoreboard attributes pushes from the row itself going forward;
57
+ * pre-v26 history attributes via the `#`-prefix join on
58
+ * memories.source_session (segment-scoped — bare equality matches 0). */
59
+ project?: string | null;
51
60
  }
52
61
  /**
53
62
  * Record one /recall-index push: the push row + (when lines were shown) the
54
63
  * per-line kind='shown' event rows, in ONE transaction WITH the existing
55
- * exposure write (storage.touchMemoriesShown — the spec's "same transaction";
56
- * better-sqlite3 nests the inner transaction as a savepoint, so a recording
57
- * failure rolls back the whole unit and the CALLER's fallback re-runs the
58
- * exposure touch alone — shown_count never depends on telemetry).
64
+ * exposure counter write (storage.touchMemoriesShown — the spec's "same
65
+ * transaction"; better-sqlite3 nests the inner transaction as a savepoint, so
66
+ * a recording failure rolls back the whole unit and the CALLER's fallback
67
+ * re-runs the exposure touch alone — shown_count never depends on telemetry).
59
68
  *
60
69
  * similarity = cosine(memory embedding, PURE prompt embedding), computed
61
70
  * UNIFORMLY via cosineBetweenVectors against the stored vector — FTS-sourced
@@ -84,6 +93,13 @@ export declare function recordRecallFetch(db: Database.Database, memoryId: strin
84
93
  * window the store no longer has rows for). Inclusive cutoff: the last N
85
94
  * calendar days with today counted stay (day >= today−(N−1)), the complement
86
95
  * is deleted — retained rows == window rows.
96
+ *
97
+ * #578 retention split — recall_verdicts rides the SAME horizon with ONE
98
+ * carve-out: grader='owner' rows are NEVER dropped (they are the owner's
99
+ * calibration reference, tiny volume by construction — about
100
+ * five thumbs a week). Machine rows ('auto', 'revealed') prune with the events
101
+ * they were derived from — a revealed verdict outliving its own event rows
102
+ * would claim a window the store no longer holds.
87
103
  */
88
104
  export declare function pruneRecallPrecision(db: Database.Database): void;
89
105
  /**
@@ -159,7 +175,15 @@ export interface MemoryPrecisionLevel2 {
159
175
  uses_per_showing: number | null;
160
176
  }
161
177
  /** The whole /dashboard/data memory_precision block (one card's payload,
162
- * budget ≤ 2 KB — the top-3 divergence lines are the only content). */
178
+ * budget ≤ 2 KB — the top-3 divergence lines are the only content).
179
+ *
180
+ * #578 adds the OPTIONAL `tier1` (deterministic quality metrics — block
181
+ * size, cross-project share + coverage, sub-bar share, recycling) and
182
+ * `changes` (per-registry-entry before/after deltas, computed from raw
183
+ * events at render) beside the original fields; both come from
184
+ * quality-scoreboard.ts and are spread in by handleDashboardData. Optional
185
+ * so older callers (and the ≤ 2 KB test's minimal shapes) keep the base
186
+ * contract; the card guards on their absence like every block before it. */
163
187
  export interface MemoryPrecision {
164
188
  /** The EFFECTIVE window (min(range, retention)); the page renders
165
189
  * "last N days" from this echo, never a hardcoded literal. */
@@ -180,6 +204,11 @@ export interface MemoryPrecision {
180
204
  shown: number;
181
205
  }>;
182
206
  };
207
+ /** #578: the Tier-1 quality metrics over the SAME effective window. */
208
+ tier1?: QualityTier1;
209
+ /** #578: before/after deltas for every change-registry entry the raw
210
+ * event window still covers (numbers computed at render, never frozen). */
211
+ changes?: QualityChangeDelta[];
183
212
  }
184
213
  /** Read-time seams (the #408 experiment pattern — the eval/tests sweep
185
214
  * values through them; production never passes anything). */
@@ -190,6 +219,11 @@ export interface MemoryPrecisionReadOptions {
190
219
  * only the share, never a stored row). */
191
220
  redundantAbove?: number;
192
221
  }
222
+ /** The EFFECTIVE memory-precision window for a range: min(range, retention)
223
+ * — the #578 quality metrics (quality-scoreboard.ts) ride the SAME window
224
+ * as the block they extend, so tier1/changes and level1 never disagree on
225
+ * which days they cover. Exported for handleDashboardData's spread. */
226
+ export declare function effectivePrecisionWindowDays(range: string): number;
193
227
  /**
194
228
  * The window aggregation behind /dashboard/data's memory_precision block
195
229
  * (the readCaptureHealthWindow pattern). Effective window = min(range,
@@ -22,8 +22,9 @@
22
22
  * FAIL-SOFT LAW: recording is telemetry. Any error here is caught by the
23
23
  * CALLER (handleRecallIndex / handleMemoryGet) and swallowed — the recall
24
24
  * response (status 200 + block) is never affected, and the exposure signal
25
- * (touchMemoriesShown) never depends on it (the handler falls back to the
26
- * plain exposure write when recording is absent or fails).
25
+ * (touchMemoriesShown — shown_count only, never the use clock #569) never
26
+ * depends on it (the handler falls back to the plain exposure write when
27
+ * recording is absent or fails).
27
28
  *
28
29
  * The perf law (bounded hot-path cost): the recorder computes cosines with
29
30
  * the request's ALREADY-MEMOIZED prompt embedding (createRecallRetrieveFn's
@@ -70,6 +71,7 @@ exports.recordRecallFetch = recordRecallFetch;
70
71
  exports.pruneRecallPrecision = pruneRecallPrecision;
71
72
  exports.identityServedToAllClients = identityServedToAllClients;
72
73
  exports.createStandingContextBasis = createStandingContextBasis;
74
+ exports.effectivePrecisionWindowDays = effectivePrecisionWindowDays;
73
75
  exports.readMemoryPrecision = readMemoryPrecision;
74
76
  const storage = __importStar(require("./storage.js"));
75
77
  const retrieval_js_1 = require("./retrieval.js");
@@ -80,10 +82,10 @@ const calibration_js_1 = require("./calibration.js");
80
82
  /**
81
83
  * Record one /recall-index push: the push row + (when lines were shown) the
82
84
  * per-line kind='shown' event rows, in ONE transaction WITH the existing
83
- * exposure write (storage.touchMemoriesShown — the spec's "same transaction";
84
- * better-sqlite3 nests the inner transaction as a savepoint, so a recording
85
- * failure rolls back the whole unit and the CALLER's fallback re-runs the
86
- * exposure touch alone — shown_count never depends on telemetry).
85
+ * exposure counter write (storage.touchMemoriesShown — the spec's "same
86
+ * transaction"; better-sqlite3 nests the inner transaction as a savepoint, so
87
+ * a recording failure rolls back the whole unit and the CALLER's fallback
88
+ * re-runs the exposure touch alone — shown_count never depends on telemetry).
87
89
  *
88
90
  * similarity = cosine(memory embedding, PURE prompt embedding), computed
89
91
  * UNIFORMLY via cosineBetweenVectors against the stored vector — FTS-sourced
@@ -103,13 +105,14 @@ function recordRecallPush(db, entry, basis = []) {
103
105
  VALUES (?, ?, ?, ?, ?, ?, 'shown')`);
104
106
  const tx = db.transaction(() => {
105
107
  if (entry.ids.length > 0) {
106
- // The exposure write rides INSIDE the recording transaction (spec: one
107
- // atomic unit). Nested db.transaction → savepoint.
108
- storage.touchMemoriesShown(db, entry.ids, ts);
108
+ // The exposure counter write rides INSIDE the recording transaction
109
+ // (spec: one atomic unit; shown_count only — never the use clock, #569).
110
+ // Nested db.transaction → savepoint.
111
+ storage.touchMemoriesShown(db, entry.ids);
109
112
  }
110
113
  const info = db
111
- .prepare("INSERT INTO recall_pushes (ts, day, session_id, prompt_excerpt) VALUES (?, ?, ?, ?)")
112
- .run(ts, day, entry.sessionId, excerpt);
114
+ .prepare("INSERT INTO recall_pushes (ts, day, session_id, prompt_excerpt, project) VALUES (?, ?, ?, ?, ?)")
115
+ .run(ts, day, entry.sessionId, excerpt, entry.project ?? null);
113
116
  const pushId = Number(info.lastInsertRowid);
114
117
  if (entry.ids.length === 0)
115
118
  return; // silent turn — push row only
@@ -156,10 +159,20 @@ function recordRecallFetch(db, memoryId, ts) {
156
159
  * window the store no longer has rows for). Inclusive cutoff: the last N
157
160
  * calendar days with today counted stay (day >= today−(N−1)), the complement
158
161
  * is deleted — retained rows == window rows.
162
+ *
163
+ * #578 retention split — recall_verdicts rides the SAME horizon with ONE
164
+ * carve-out: grader='owner' rows are NEVER dropped (they are the owner's
165
+ * calibration reference, tiny volume by construction — about
166
+ * five thumbs a week). Machine rows ('auto', 'revealed') prune with the events
167
+ * they were derived from — a revealed verdict outliving its own event rows
168
+ * would claim a window the store no longer holds.
159
169
  */
160
170
  function pruneRecallPrecision(db) {
161
171
  db.exec(`DELETE FROM recall_pushes WHERE day < date('now', '-${calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS - 1} days')`);
162
172
  db.exec(`DELETE FROM recall_events WHERE day < date('now', '-${calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS - 1} days')`);
173
+ db.exec(`DELETE FROM recall_verdicts
174
+ WHERE grader != 'owner'
175
+ AND day < date('now', '-${calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS - 1} days')`);
163
176
  }
164
177
  // ---------------------------------------------------------------------------
165
178
  // Standing-context basis — the redundancy reference (what every session
@@ -263,6 +276,13 @@ function rangeToDays(range) {
263
276
  const n = parseInt(range, 10);
264
277
  return Number.isFinite(n) && n > 0 ? n : null;
265
278
  }
279
+ /** The EFFECTIVE memory-precision window for a range: min(range, retention)
280
+ * — the #578 quality metrics (quality-scoreboard.ts) ride the SAME window
281
+ * as the block they extend, so tier1/changes and level1 never disagree on
282
+ * which days they cover. Exported for handleDashboardData's spread. */
283
+ function effectivePrecisionWindowDays(range) {
284
+ return Math.min(rangeToDays(range) ?? calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS, calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS);
285
+ }
266
286
  /**
267
287
  * The window aggregation behind /dashboard/data's memory_precision block
268
288
  * (the readCaptureHealthWindow pattern). Effective window = min(range,
@@ -282,7 +302,7 @@ function rangeToDays(range) {
282
302
  function readMemoryPrecision(db, range, liveAdoption, opts) {
283
303
  const now = opts?.now ?? new Date();
284
304
  const redundantAbove = opts?.redundantAbove ?? calibration_js_1.MEMORY_PRECISION_REDUNDANT_ABOVE;
285
- const windowDays = Math.min(rangeToDays(range) ?? calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS, calibration_js_1.MEMORY_PRECISION_WINDOW_DAYS);
305
+ const windowDays = effectivePrecisionWindowDays(range);
286
306
  // Inclusive window start (UTC YYYY-MM-DD): today counts as day 1.
287
307
  const cutoffDay = new Date(now.getTime() - (windowDays - 1) * DAY_MS).toISOString().slice(0, 10);
288
308
  // --- Level 1: group the window's shown events (raw values, no thresholds
@@ -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>;