@gamaze/hicortex 0.27.3 → 0.28.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.
Files changed (92) hide show
  1. package/assets/dashboard.html +361 -100
  2. package/dist/backfill-privacy.d.ts +68 -45
  3. package/dist/backfill-privacy.js +236 -145
  4. package/dist/calibration.d.ts +67 -68
  5. package/dist/calibration.js +75 -78
  6. package/dist/capture-health.d.ts +2 -2
  7. package/dist/capture-health.js +2 -2
  8. package/dist/classification.d.ts +141 -12
  9. package/dist/classification.js +214 -27
  10. package/dist/classify-domains.d.ts +1 -1
  11. package/dist/classify-domains.js +2 -2
  12. package/dist/cli-args.d.ts +5 -3
  13. package/dist/cli-args.js +7 -3
  14. package/dist/cli.d.ts +2 -0
  15. package/dist/cli.js +64 -16
  16. package/dist/cluster.d.ts +12 -9
  17. package/dist/cluster.js +9 -6
  18. package/dist/consolidate.d.ts +93 -43
  19. package/dist/consolidate.js +255 -119
  20. package/dist/dashboard.d.ts +48 -5
  21. package/dist/dashboard.js +55 -3
  22. package/dist/db.js +27 -6
  23. package/dist/dedup.d.ts +2 -3
  24. package/dist/dedup.js +2 -3
  25. package/dist/distill-queue.d.ts +36 -4
  26. package/dist/distill-queue.js +80 -18
  27. package/dist/distiller.d.ts +1 -1
  28. package/dist/distiller.js +13 -12
  29. package/dist/domain-classify.d.ts +8 -9
  30. package/dist/domain-classify.js +6 -7
  31. package/dist/graph.d.ts +15 -5
  32. package/dist/graph.js +46 -13
  33. package/dist/hermes-transcript-reader.d.ts +1 -1
  34. package/dist/hermes-transcript-reader.js +1 -1
  35. package/dist/init.d.ts +2 -2
  36. package/dist/init.js +3 -3
  37. package/dist/llm.d.ts +1 -1
  38. package/dist/llm.js +5 -5
  39. package/dist/mcp-server.js +323 -59
  40. package/dist/memory-instructions.d.ts +2 -2
  41. package/dist/memory-instructions.js +2 -2
  42. package/dist/nightly.d.ts +1 -1
  43. package/dist/nightly.js +64 -5
  44. package/dist/nofit.d.ts +2 -2
  45. package/dist/nofit.js +2 -2
  46. package/dist/observed-agents.d.ts +54 -0
  47. package/dist/observed-agents.js +78 -0
  48. package/dist/project-canonicalize.d.ts +6 -5
  49. package/dist/project-canonicalize.js +6 -5
  50. package/dist/prompts.d.ts +30 -9
  51. package/dist/prompts.js +40 -17
  52. package/dist/quality-scoreboard.d.ts +1 -1
  53. package/dist/recall-hook-cli.d.ts +1 -1
  54. package/dist/recall-hook-cli.js +2 -2
  55. package/dist/recall-index.d.ts +28 -14
  56. package/dist/recall-index.js +22 -10
  57. package/dist/recall-precision.d.ts +3 -3
  58. package/dist/recall-precision.js +5 -4
  59. package/dist/reconcile-projects.d.ts +2 -2
  60. package/dist/reconcile-projects.js +2 -2
  61. package/dist/reconsolidation.d.ts +9 -2
  62. package/dist/reconsolidation.js +48 -31
  63. package/dist/relink.d.ts +2 -2
  64. package/dist/relink.js +4 -4
  65. package/dist/rescore-importance.d.ts +2 -2
  66. package/dist/rescore-importance.js +22 -3
  67. package/dist/retrieval.d.ts +14 -0
  68. package/dist/retrieval.js +11 -11
  69. package/dist/schema-prototypes.d.ts +1 -1
  70. package/dist/schema-prototypes.js +1 -1
  71. package/dist/seed-lesson.js +4 -2
  72. package/dist/spaces-api.d.ts +104 -0
  73. package/dist/spaces-api.js +193 -0
  74. package/dist/spaces-cli.d.ts +90 -0
  75. package/dist/spaces-cli.js +245 -0
  76. package/dist/spaces.d.ts +187 -0
  77. package/dist/spaces.js +360 -0
  78. package/dist/storage.d.ts +47 -10
  79. package/dist/storage.js +74 -17
  80. package/dist/sweep-volatile.d.ts +2 -2
  81. package/dist/sweep-volatile.js +2 -2
  82. package/dist/telemetry-cli.d.ts +1 -1
  83. package/dist/telemetry-cli.js +1 -1
  84. package/dist/type-classify.d.ts +1 -1
  85. package/dist/type-classify.js +1 -1
  86. package/dist/type-labels.d.ts +1 -1
  87. package/dist/type-labels.js +1 -1
  88. package/dist/types.d.ts +43 -20
  89. package/dist/wrapper-prompt.d.ts +2 -2
  90. package/dist/wrapper-prompt.js +2 -2
  91. package/package.json +3 -2
  92. package/server.json +2 -2
@@ -57,29 +57,29 @@ export interface RecallIndexOptions {
57
57
  * since #408 — calibration.ts RECALL_MIN_SIMILARITY; this field is the
58
58
  * eval/test seam). FTS-matched candidates pass regardless — a BM25
59
59
  * text match is direct evidence of relevance. 0.62 (raised from 0.55
60
- * on 2026-08-03 per a 0.01-step floor sweep on the rewritten corpus): steady
61
- * ~3:1 noise:signal removal with no knee; 0.62 = +2.2pts precision, 10/98
62
- * prompts silent, sits below the 0.63 local pessimum. The floor is a noise
60
+ * after a 0.01-step floor sweep): steady
61
+ * ~3:1 noise:signal removal with no knee; sits below the 0.63 local
62
+ * pessimum. The floor is a noise
63
63
  * dial, NOT a silence mechanism — at 0.62 each correctly-silenced empty prompt
64
64
  * comes with ~1.5 wrongly-silenced (real signal); a non-cosine gate is the
65
65
  * real silence fix (eval #3 §4). */
66
66
  minSimilarity?: number;
67
67
  /** Max index lines per response (release-managed — calibration.ts
68
- * RECALL_MAX_ITEMS; seam only). 5 (lowered from 6 on 2026-08-03). Per-slot
68
+ * RECALL_MAX_ITEMS; seam only). 5 (lowered from 6). Per-slot
69
69
  * decomposition at floor 0.62: slot 6 gives NO prompt its first relevant
70
70
  * memory — "6 is wrong" is the robust, prompt-set-independent finding, and
71
- * 5 captures it. The K-sweep is monotone (precision@4 33.7% > @6 30.6% >
72
- * @8 28.3%), so 4 is lower-noise — but the 4-vs-5 distinction rests on 5
73
- * of 98 prompts and is overfitting-fragile (K and the floor were tuned on
71
+ * 5 captures it. The K-sweep is monotone toward 4 (lower K, lower noise),
72
+ * so 4 is lower-noise — but the 4-vs-5 distinction is
73
+ * overfitting-fragile (K and the floor were tuned on
74
74
  * the same set); 5 hedges with coverage at modest cost. */
75
75
  maxItems?: number;
76
76
  /** Prompts shorter than this are skipped (continuations, "yes", "do it"). */
77
77
  minPromptLength?: number;
78
78
  /** Max chars of the memory's first line shown in an index entry
79
79
  * (release-managed — calibration.ts RECALL_TITLE_CHARS; seam only).
80
- * 100 (reverted from 150 on 2026-08-03): the full-corpus relevance eval
81
- * (#3, §5) found 100 vs 150 statistically identical (0.6pts apart, N=40,
82
- * full CI overlap); 100 saves ~13% tokens per block. */
80
+ * 100 (reverted from 150): the relevance eval
81
+ * (#3, §5) found 100 vs 150 statistically identical (full CI overlap);
82
+ * 100 saves ~13% tokens per block. */
83
83
  titleChars?: number;
84
84
  /** Slots of `maxItems` guaranteed to the pure-prompt (unblended) search's
85
85
  * top passing hit(s) — the #324 novelty floor. Release-managed
@@ -95,7 +95,7 @@ export interface RecallIndexOptions {
95
95
  * the firstRunLookbackDays precedent) — production sets it from the
96
96
  * boot-resolved config value; eval/tests inject through this field.
97
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. */
98
+ * absent — #566 ruling); 0 or ≤ the recall floor = fence off. */
99
99
  crossProjectMinSimilarity?: number;
100
100
  /** #567: the project-identity alias map — `filters.project` is folded at
101
101
  * its build site so a raw client-pushed label (cwd-derived, unnormalized)
@@ -135,7 +135,7 @@ export declare const MAX_SESSION_ID_CHARS = 128;
135
135
  /** First content line, de-markdowned and truncated — the index line title. */
136
136
  export declare function memoryTitle(content: string, maxLen?: number): string;
137
137
  /**
138
- * Render one production index line. Exported (2026-08-02, relevance eval #v2)
138
+ * Render one production index line. Exported (relevance eval #v2)
139
139
  * so the eval can measure the REAL rendered surface instead of reimplementing
140
140
  * it — `maxLen` threads through to `memoryTitle` unchanged (default
141
141
  * DEFAULT_TITLE_CHARS = 100, release-managed since #408) so the eval's snippet-length
@@ -165,8 +165,8 @@ export interface RelevanceScope {
165
165
  * 0.62 is off on EVERY surface, not just sites that happen to carry a floor;
166
166
  * floor-less surfaces [/search no-param, the MCP tool] must not arm at
167
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
168
+ * scope's (case-insensitive — measured events sat on case-split project
169
+ * labels; a null/absent candidate project counts as foreign) must clear
170
170
  * max(bar, the site floor) on a MEASURED cosine — the fence only RAISES a
171
171
  * site's existing floor, never weakens it. No source branching is needed:
172
172
  * FTS-only and graph-only hits carry similarity null → they naturally do not
@@ -288,6 +288,14 @@ export declare function createRecallRetrieveFn(deps: {
288
288
  * rows inside retrieve().
289
289
  */
290
290
  includeConfidential?: boolean;
291
+ /**
292
+ * #642 AC-5: the generalized gate — the request's visible SPACE set
293
+ * (spacesForMember over the boot-resolved spaces; the route adapter
294
+ * computes it per request from the body `agent`). Threaded into retrieve()
295
+ * and unioned with the boolean there (resolveVisibleSet): rows of spaces
296
+ * outside the set are hard-omitted at candidate-build time.
297
+ */
298
+ visibleSpaces?: Set<string>;
291
299
  }): RecallRetrieveFactory;
292
300
  /** Normalize a request-supplied string-list param: array of strings or a CSV
293
301
  * string → string[] | undefined. Anything else (or an empty result) means
@@ -320,11 +328,17 @@ export interface MemoryGetDeps {
320
328
  * — a confidential memory fetched by a non-member answers 404 BEFORE any
321
329
  * side effect (no strengthen, no precision event: existence is not revealed).
322
330
  * Members (the adapter passes true) fetch both pools normally.
331
+ *
332
+ * #642 AC-5: `opts.visibleSpaces` is the generalized form — the predicate is
333
+ * isVisiblePrivacy over resolveVisibleSet(boolean, set): shared rows for
334
+ * everyone, the viewer's spaces yes, everything else (including unknown/
335
+ * retired space ids, AC-7) 404 before any side effect.
323
336
  */
324
337
  export declare function handleMemoryGet(db: Database.Database, query: {
325
338
  id?: unknown;
326
339
  }, deps?: MemoryGetDeps, opts?: {
327
340
  includeConfidential?: boolean;
341
+ visibleSpaces?: Set<string>;
328
342
  }): RecallIndexResult;
329
343
  /**
330
344
  * MCP `hicortex_get` presentation: handleMemoryGet's result framed as the
@@ -96,18 +96,19 @@ const storage = __importStar(require("./storage.js"));
96
96
  const wrapper_prompt_js_1 = require("./wrapper-prompt.js");
97
97
  const project_canonicalize_js_1 = require("./project-canonicalize.js");
98
98
  const type_labels_js_1 = require("./type-labels.js");
99
+ const spaces_js_1 = require("./spaces.js");
99
100
  const retrieval_js_1 = require("./retrieval.js");
100
101
  const CALIBRATION = __importStar(require("./calibration.js"));
101
102
  /** Relevance-gate floor for vector-only candidates (release-managed —
102
- * calibration.ts RECALL_MIN_SIMILARITY). 0.62 (was 0.55; raised 2026-08-03
103
+ * calibration.ts RECALL_MIN_SIMILARITY). 0.62 (was 0.55; raised
103
104
  * on the fine-grain floor sweep — see the minSimilarity doc above). */
104
105
  const DEFAULT_MIN_SIMILARITY = CALIBRATION.RECALL_MIN_SIMILARITY;
105
106
  /** Max index lines per pushed recall block (release-managed — calibration.ts
106
- * RECALL_MAX_ITEMS). 5 (was 6; lowered 2026-08-03 — slot 6 is pure padding
107
+ * RECALL_MAX_ITEMS). 5 (was 6; slot 6 is pure padding
107
108
  * at floor 0.62). */
108
109
  const DEFAULT_MAX_ITEMS = CALIBRATION.RECALL_MAX_ITEMS;
109
110
  const DEFAULT_MIN_PROMPT_LENGTH = CALIBRATION.RECALL_MIN_PROMPT_CHARS;
110
- /** Default index-line title length. 100 (reverted from 150 on 2026-08-03:
111
+ /** Default index-line title length. 100 (reverted from 150:
111
112
  * eval #3 §5 showed 100 vs 150 statistically identical; 100 saves ~13% tokens). */
112
113
  const DEFAULT_TITLE_CHARS = CALIBRATION.RECALL_TITLE_CHARS;
113
114
  /** Default #324 novelty-floor slots (release-managed — calibration.ts
@@ -167,7 +168,7 @@ function formatDate(iso) {
167
168
  return `${dd}.${mm}.${d.getFullYear()}`;
168
169
  }
169
170
  /**
170
- * Render one production index line. Exported (2026-08-02, relevance eval #v2)
171
+ * Render one production index line. Exported (relevance eval #v2)
171
172
  * so the eval can measure the REAL rendered surface instead of reimplementing
172
173
  * it — `maxLen` threads through to `memoryTitle` unchanged (default
173
174
  * DEFAULT_TITLE_CHARS = 100, release-managed since #408) so the eval's snippet-length
@@ -198,8 +199,8 @@ function formatIndexLine(r, maxLen = DEFAULT_TITLE_CHARS) {
198
199
  * 0.62 is off on EVERY surface, not just sites that happen to carry a floor;
199
200
  * floor-less surfaces [/search no-param, the MCP tool] must not arm at
200
201
  * 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
202
+ * scope's (case-insensitive — measured events sat on case-split project
203
+ * labels; a null/absent candidate project counts as foreign) must clear
203
204
  * max(bar, the site floor) on a MEASURED cosine — the fence only RAISES a
204
205
  * site's existing floor, never weakens it. No source branching is needed:
205
206
  * FTS-only and graph-only hits carry similarity null → they naturally do not
@@ -304,6 +305,10 @@ function createRecallRetrieveFn(deps) {
304
305
  // #332: the classification gate — hard omit unless the requesting
305
306
  // agent is a circle member (the factory was built with membership).
306
307
  includeConfidential: deps.includeConfidential === true,
308
+ // #642 AC-5: the generalized gate — the requesting agent's visible
309
+ // space set, threaded through the factory (unioned with the boolean
310
+ // inside retrieve via resolveVisibleSet).
311
+ visibleSpaces: deps.visibleSpaces,
307
312
  // #329: shared per-request FTS list. The recall path never passes
308
313
  // sourceAgent, so the memo is keyed on (query, fetchLimit) only —
309
314
  // exactly the two things retrieve() would pass to searchFts.
@@ -365,7 +370,7 @@ async function handleRecallIndex(deps, body) {
365
370
  // exposure never writes last_accessed anyway). The SAME shared
366
371
  // classifier the hook client guards with (wrapper-prompt.ts) — defense in
367
372
  // depth. A wrapper carrying real payload prose falls through and recalls on
368
- // the full text, exactly today's behavior (owner decision 4).
373
+ // the full text, exactly today's behavior (decision 4).
369
374
  if ((0, wrapper_prompt_js_1.isPureWrapperPrompt)(prompt)) {
370
375
  return { status: 200, body: { block: null, skipped: "wrapper-prompt" } };
371
376
  }
@@ -544,7 +549,7 @@ async function handleRecallIndex(deps, body) {
544
549
  const lines = picked.map((r) => formatIndexLine(r, titleChars));
545
550
  const block = [
546
551
  "## Memory recall (auto)",
547
- // Provenance is BUILT IN (owner decision 27.07, option D; extended #202/#204):
552
+ // Provenance is BUILT IN (option D; extended #202/#204):
548
553
  // - #202: origin agent in each one-liner (formatIndexLine) — trust calibration.
549
554
  // - #204: confidence levels — FETCHED (read in full) vs SNIPPET (one-line entry only),
550
555
  // so "the agent cited a memory" can no longer pass as "the agent read it".
@@ -570,6 +575,11 @@ async function handleRecallIndex(deps, body) {
570
575
  * — a confidential memory fetched by a non-member answers 404 BEFORE any
571
576
  * side effect (no strengthen, no precision event: existence is not revealed).
572
577
  * Members (the adapter passes true) fetch both pools normally.
578
+ *
579
+ * #642 AC-5: `opts.visibleSpaces` is the generalized form — the predicate is
580
+ * isVisiblePrivacy over resolveVisibleSet(boolean, set): shared rows for
581
+ * everyone, the viewer's spaces yes, everything else (including unknown/
582
+ * retired space ids, AC-7) 404 before any side effect.
573
583
  */
574
584
  function handleMemoryGet(db, query, deps, opts) {
575
585
  const id = typeof query.id === "string" ? query.id : "";
@@ -588,7 +598,9 @@ function handleMemoryGet(db, query, deps, opts) {
588
598
  // #332: the gate fires BEFORE strengthenMemory + the fetch recorder — a
589
599
  // refused fetch must leave no trace on the row and record no event (the
590
600
  // same 404 shape an unknown id produces).
591
- if (mem.privacy === "confidential" && opts?.includeConfidential !== true) {
601
+ // #642: the generalized predicate (shared always; the viewer's spaces;
602
+ // nothing else — unknown space ids included, AC-7).
603
+ if (!(0, spaces_js_1.isVisiblePrivacy)(mem.privacy, (0, spaces_js_1.resolveVisibleSet)(opts?.includeConfidential, opts?.visibleSpaces))) {
592
604
  return notFound;
593
605
  }
594
606
  storage.strengthenMemory(db, fullId, new Date().toISOString());
@@ -605,7 +617,7 @@ function handleMemoryGet(db, query, deps, opts) {
605
617
  }
606
618
  }
607
619
  // `citation` is server-rendered so every plugin surfaces the same built-in
608
- // provenance norm (owner directive 27.07) — see #193.
620
+ // provenance norm — see #193.
609
621
  const date = (mem.created_at ?? "").slice(0, 10);
610
622
  // Shallow-copy and apply the human-term label to memory_type so the REST
611
623
  // response surfaces the user-facing vocabulary, not the raw DB enum. The
@@ -96,8 +96,8 @@ export declare function recordRecallFetch(db: Database.Database, memoryId: strin
96
96
  *
97
97
  * #578 retention split — recall_verdicts rides the SAME horizon with ONE
98
98
  * carve-out: grader='owner' rows are NEVER dropped (they are the
99
- * manual-verdict calibration reference, tiny volume by construction — about
100
- * five thumbs a week). Machine rows ('auto', 'revealed') prune with the events
99
+ * manual-verdict calibration reference, tiny volume by construction).
100
+ * Machine rows ('auto', 'revealed') prune with the events
101
101
  * they were derived from — a revealed verdict outliving its own event rows
102
102
  * would claim a window the store no longer holds.
103
103
  */
@@ -197,7 +197,7 @@ export interface MemoryPrecision {
197
197
  /** Top-3 by window showings DESC, lines rendered through the SHARED
198
198
  * formatIndexLine (≤ RECALL_TITLE_CHARS — the card cannot drift from
199
199
  * what agents see). Hover-only on the card face (no memory lists on
200
- * the main page — owner ruling 2026-09-12). */
200
+ * the main page — #578 ruling). */
201
201
  top: Array<{
202
202
  id: string;
203
203
  line: string;
@@ -162,8 +162,8 @@ function recordRecallFetch(db, memoryId, ts) {
162
162
  *
163
163
  * #578 retention split — recall_verdicts rides the SAME horizon with ONE
164
164
  * carve-out: grader='owner' rows are NEVER dropped (they are the
165
- * manual-verdict calibration reference, tiny volume by construction — about
166
- * five thumbs a week). Machine rows ('auto', 'revealed') prune with the events
165
+ * manual-verdict calibration reference, tiny volume by construction).
166
+ * Machine rows ('auto', 'revealed') prune with the events
167
167
  * they were derived from — a revealed verdict outliving its own event rows
168
168
  * would claim a window the store no longer holds.
169
169
  */
@@ -217,8 +217,9 @@ function createStandingContextBasis(config) {
217
217
  // not a ledger.
218
218
  try {
219
219
  // #332: the basis is a server-internal redundancy reference over the
220
- // whole lesson store (no agent sees it) — ungated by design.
221
- for (const lesson of storage.getLessons(db, 30, null, { includeConfidential: true }))
220
+ // whole lesson store (no agent sees it) — ungated by design. #642:
221
+ // allSpaces is the explicit whole-store form (every pool).
222
+ for (const lesson of storage.getLessons(db, 30, null, { allSpaces: true }))
222
223
  texts.push(lesson.content);
223
224
  }
224
225
  catch (err) {
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * The server canonicalizes every project string at entry (project-
6
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
7
+ * that predates it: the `hicortex`/`Hicortex` case split and the
8
+ * junk-label share measured in #565 WS1. Dry run by default (report
9
9
  * only, zero writes); `--apply` renames along the dedup rails.
10
10
  *
11
11
  * What a rename is: a pure function of the config alias map + the current
@@ -5,8 +5,8 @@
5
5
  *
6
6
  * The server canonicalizes every project string at entry (project-
7
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
8
+ * that predates it: the `hicortex`/`Hicortex` case split and the
9
+ * junk-label share measured in #565 WS1. Dry run by default (report
10
10
  * only, zero writes); `--apply` renames along the dedup rails.
11
11
  *
12
12
  * What a rename is: a pure function of the config alias map + the current
@@ -98,7 +98,7 @@ export declare const RECONSOLIDATION_STAGE_LABEL = "reconsolidation";
98
98
  * provenance there). Deliberately wide: a retraction often rides inside an
99
99
  * otherwise unrelated memory (the field failure that opened this issue), so
100
100
  * the neighborhood gate must be a touch wider while the LLM verdict +
101
- * confidence gate carry the precision load. Since #206-B (owner decision 6)
101
+ * confidence gate carry the precision load. Since #206-B (decision 6)
102
102
  * this floor also subsumes the retired Stage 3.7 supersession scan's 0.80:
103
103
  * 3.8 is the ONLY true-update detector, scanning every new memory — no
104
104
  * shape gate, wider floor — with `corrects`/`supersedes` partitioning what
@@ -164,10 +164,17 @@ export interface ReconsolidationOptions {
164
164
  * selects the client matching the memories it reads; when the confidential
165
165
  * side is needed and absent, that pair/group holds (skipped_infra counts,
166
166
  * retried next run), never judged on the main model. The deterministic
167
- * merge zone needs no client but is class-pure via the classification rail
167
+ * merge zone needs no client but is space-pure via the classification rail
168
168
  * (clusterMetadataMismatch).
169
169
  */
170
170
  confidentialLlm?: LlmClient | null;
171
+ /**
172
+ * #642: per-space clients (every configured space except 'confidential',
173
+ * which keeps the field above). Same hold-not-fallback law per space: a
174
+ * candidate/pair/group whose space has no client holds (skipped_infra),
175
+ * never judged on the standard client.
176
+ */
177
+ spaceClients?: Map<string, LlmClient | null>;
171
178
  }
172
179
  /** The stage report (typed once, in ConsolidationReport — field list there). */
173
180
  export type ReconsolidationStageResult = NonNullable<ConsolidationReport["stages"]["reconsolidation"]>;
@@ -140,6 +140,7 @@ exports.stageReconsolidation = stageReconsolidation;
140
140
  exports.rollbackHistoryRow = rollbackHistoryRow;
141
141
  exports.runHistoryCommand = runHistoryCommand;
142
142
  const classification_js_1 = require("./classification.js");
143
+ const spaces_js_1 = require("./spaces.js");
143
144
  const retrieval_js_1 = require("./retrieval.js");
144
145
  const storage = __importStar(require("./storage.js"));
145
146
  const state_js_1 = require("./state.js");
@@ -159,7 +160,7 @@ exports.RECONSOLIDATION_STAGE_LABEL = "reconsolidation";
159
160
  * provenance there). Deliberately wide: a retraction often rides inside an
160
161
  * otherwise unrelated memory (the field failure that opened this issue), so
161
162
  * the neighborhood gate must be a touch wider while the LLM verdict +
162
- * confidence gate carry the precision load. Since #206-B (owner decision 6)
163
+ * confidence gate carry the precision load. Since #206-B (decision 6)
163
164
  * this floor also subsumes the retired Stage 3.7 supersession scan's 0.80:
164
165
  * 3.8 is the ONLY true-update detector, scanning every new memory — no
165
166
  * shape gate, wider floor — with `corrects`/`supersedes` partitioning what
@@ -578,13 +579,13 @@ function accumulateBandStat(cumulative, run) {
578
579
  */
579
580
  async function findOlderCorrectionNeighbors(db, candidate, embedFn, minSimilarity) {
580
581
  const embedding = storage.getStoredEmbedding(db, candidate.id) ?? (await embedFn(candidate.content));
581
- // #332: pairing is class-pure — the KNN pool is unscoped, the filter
582
- // narrows it to the candidate's own class (no reconsolidation pair ever
583
- // mixes classes; NULL privacy reads standard).
584
- const candidateConfidential = candidate.privacy === "confidential";
582
+ // #332/#642: pairing is space-pure — the KNN pool is unscoped, the filter
583
+ // narrows it to the candidate's own space (no reconsolidation pair ever
584
+ // mixes spaces; NULL privacy reads standard via spaceOf).
585
+ const candidateSpace = (0, spaces_js_1.spaceOf)(candidate.privacy);
585
586
  return storage
586
587
  .vectorSearch(db, embedding, CORRECTION_NEIGHBOR_POOL, [candidate.id])
587
- .filter((n) => (n.privacy === "confidential") === candidateConfidential &&
588
+ .filter((n) => (0, spaces_js_1.spaceOf)(n.privacy) === candidateSpace &&
588
589
  n.created_at < candidate.created_at &&
589
590
  (0, retrieval_js_1.l2ToCosine)(n.distance) >= minSimilarity)
590
591
  .sort((a, b) => (0, retrieval_js_1.l2ToCosine)(b.distance) - (0, retrieval_js_1.l2ToCosine)(a.distance))
@@ -607,11 +608,11 @@ function findScoutNeighbors(db, candidate, references, candidateEmbedding) {
607
608
  return [];
608
609
  try {
609
610
  const hits = storage.searchFts(db, references, CORRECTION_NEIGHBOR_POOL);
610
- // #332: the scout source is class-pure too — same filter as the KNN
611
+ // #332/#642: the scout source is space-pure too — same filter as the KNN
611
612
  // source (the FTS pool is unscoped; the filter narrows it).
612
- const candidateConfidential = candidate.privacy === "confidential";
613
+ const candidateSpace = (0, spaces_js_1.spaceOf)(candidate.privacy);
613
614
  return hits
614
- .filter((m) => (m.privacy === "confidential") === candidateConfidential &&
615
+ .filter((m) => (0, spaces_js_1.spaceOf)(m.privacy) === candidateSpace &&
615
616
  m.id !== candidate.id &&
616
617
  m.created_at < candidate.created_at &&
617
618
  m.status !== "absorbed")
@@ -710,15 +711,27 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
710
711
  // hit() logs event=deadline_deferred once per stage name.
711
712
  const deadline = options.deadline;
712
713
  const deadlineHit = (stageLabel = exports.RECONSOLIDATION_STAGE_LABEL) => deadline?.hit(stageLabel) ?? false;
713
- // ---- #332 per-pool client selection. Every LLM call below goes through
714
- // clientFor(...); a null answer means "confidential text, no confidential
715
- // model" — the pair/group HOLDS (skippedInfra, retried next run), never
716
- // judged on the standard client. (Named llmPair — the merge-batch loop
717
- // below has its own local `pair` per queued merge.)
718
- const llmPair = { standard: llm, confidential: options.confidentialLlm ?? null };
714
+ // ---- #332/#642 per-space client selection. Every LLM call below goes
715
+ // through clientFor(...); a null answer means "non-shared text, no client
716
+ // for its space" — the pair/group HOLDS (skippedInfra, retried next run),
717
+ // never judged on the standard client. #642 rule: standard rows may ride
718
+ // any private pool's client (the pre-#642 confidential posture — a private
719
+ // model is trusted with shared text), but TWO different spaces' text never
720
+ // shares one client — such a pair/group holds instead. (Named llmPair —
721
+ // the merge-batch loop below has its own local `pair` per queued merge.)
722
+ const llmPair = {
723
+ standard: llm,
724
+ confidential: options.confidentialLlm ?? null,
725
+ spaces: options.spaceClients,
726
+ };
719
727
  const clientFor = (...mems) => {
720
- const confidential = mems.some((m) => m.privacy === "confidential");
721
- return (0, classification_js_1.clientForPool)(llmPair, confidential ? "confidential" : "standard");
728
+ const spaces = new Set(mems.map((m) => (0, spaces_js_1.spaceOf)(m.privacy ?? null)));
729
+ spaces.delete("standard");
730
+ if (spaces.size === 0)
731
+ return llmPair.standard;
732
+ if (spaces.size > 1)
733
+ return null; // cross-space call — hold, never one client for two spaces
734
+ return (0, classification_js_1.clientForPool)(llmPair, [...spaces][0]);
722
735
  };
723
736
  // Per-run verdict statistics by cosine band (#392) — report snapshot here,
724
737
  // cumulative series in state.json at stage end (never on dry-run).
@@ -954,11 +967,13 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
954
967
  explicitDivergent++; // mark's target is gone/invisible — retain link, nothing to upgrade
955
968
  continue;
956
969
  }
957
- // #332: an explicit mark may legally cross classes (an agent marked
958
- // across pools) — the verdict call selects its client by BOTH sides.
970
+ // #332/#642: an explicit mark may legally cross pools (an agent
971
+ // marked across spaces) — the verdict call selects its client by BOTH
972
+ // sides; two DIFFERENT spaces on one pair hold (no single client may
973
+ // read both).
959
974
  const markClient = clientFor(target, candidate);
960
975
  if (!markClient) {
961
- skippedInfra++; // held — no confidential model for a confidential side
976
+ skippedInfra++; // held — no client for a private side (or a cross-space pair)
962
977
  continue;
963
978
  }
964
979
  const { verdict, usage } = await classifyPair(markClient, target.content, candidate.content);
@@ -978,8 +993,8 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
978
993
  }
979
994
  else {
980
995
  // Divergent: the nightly verdict did not confirm a rewrite. The mark
981
- // is RETAINED untouched — explicit input is deliberate (owner
982
- // decision 1), and marks are cheap to reverse via CLI.
996
+ // is RETAINED untouched — explicit input is a deliberate design
997
+ // decision, and marks are cheap to reverse via CLI.
983
998
  explicitDivergent++;
984
999
  console.log(`[hicortex] Reconsolidation: explicit mark on ${candidate.id.slice(0, 8)} diverged ` +
985
1000
  `(verdict ${verdict.action}, confidence ${verdict.confidence.toFixed(2)}) — mark retained`);
@@ -1012,9 +1027,10 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
1012
1027
  }
1013
1028
  else {
1014
1029
  scoutScanned++;
1015
- // #332: the shape call reads the candidate's content — pool-matched
1016
- // client; held (skip the scout source for this memory, fail-soft like
1017
- // a parse failure) when the confidential side is unconfigured.
1030
+ // #332/#642: the shape call reads the candidate's content —
1031
+ // pool-matched client; held (skip the scout source for this memory,
1032
+ // fail-soft like a parse failure) when the candidate's space has no
1033
+ // client.
1018
1034
  const scoutClient = clientFor(candidate);
1019
1035
  if (!scoutClient) {
1020
1036
  skippedInfra++;
@@ -1114,8 +1130,8 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
1114
1130
  stopScan = true; // the boundary below still applies what this candidate already confirmed
1115
1131
  break;
1116
1132
  }
1117
- // #332: the verdict call reads BOTH memories — pool-matched client
1118
- // (detection pairs are class-pure by construction, so the pool is one
1133
+ // #332/#642: the verdict call reads BOTH memories — pool-matched client
1134
+ // (detection pairs are space-pure by construction, so the pool is one
1119
1135
  // value; a held pair counts skippedInfra and re-detects next run).
1120
1136
  const verdictClient = clientFor(entry.mem, candidate);
1121
1137
  if (!verdictClient) {
@@ -1337,10 +1353,11 @@ async function stageReconsolidation(db, llm, budget, embedFn, dryRun, stateDir,
1337
1353
  const triggersArg = group.triggers.map((t) => ({ id: t.id, content: t.memory.content }));
1338
1354
  let contract = null;
1339
1355
  let infraError = false;
1340
- // #332: the rewrite prompt reads the target AND every trigger —
1341
- // pool-matched client (groups are class-pure by construction: their
1342
- // pairs came from the class-pure detection sources). Held when the
1343
- // confidential side is unconfigured: the group defers untouched.
1356
+ // #332/#642: the rewrite prompt reads the target AND every
1357
+ // trigger — pool-matched client (groups are space-pure by
1358
+ // construction: their pairs came from the space-pure detection
1359
+ // sources). Held when the pool's space has no client: the group
1360
+ // defers untouched.
1344
1361
  const rewriteClient = clientFor(group.target, ...group.triggers.map((t) => t.memory));
1345
1362
  if (!rewriteClient) {
1346
1363
  skippedInfra++;
package/dist/relink.d.ts CHANGED
@@ -9,8 +9,8 @@
9
9
  * classification machinery (discoverLinkCandidates / classifyLinkCandidates
10
10
  * from consolidate.ts) — no new linking logic.
11
11
  *
12
- * Classification is HEURISTIC-ONLY (2026-07). LLM edge classification was
13
- * retired after the 672-link audit (see consolidate.ts Stage 3 header) found
12
+ * Classification is HEURISTIC-ONLY. LLM edge classification was
13
+ * retired after a comprehensive link audit (see consolidate.ts Stage 3 header) found
14
14
  * the LLM-classified UPPERCASE types near-useless. relink therefore never needs
15
15
  * an LLM; the old `--no-llm`, `--max-llm-calls`, and `--llm-base-url/--llm-model`
16
16
  * flags are gone. The classifyLinkCandidates call is retained (shared with the
package/dist/relink.js CHANGED
@@ -10,8 +10,8 @@
10
10
  * classification machinery (discoverLinkCandidates / classifyLinkCandidates
11
11
  * from consolidate.ts) — no new linking logic.
12
12
  *
13
- * Classification is HEURISTIC-ONLY (2026-07). LLM edge classification was
14
- * retired after the 672-link audit (see consolidate.ts Stage 3 header) found
13
+ * Classification is HEURISTIC-ONLY. LLM edge classification was
14
+ * retired after a comprehensive link audit (see consolidate.ts Stage 3 header) found
15
15
  * the LLM-classified UPPERCASE types near-useless. relink therefore never needs
16
16
  * an LLM; the old `--no-llm`, `--max-llm-calls`, and `--llm-base-url/--llm-model`
17
17
  * flags are gone. The classifyLinkCandidates call is retained (shared with the
@@ -157,8 +157,8 @@ async function runRelink(options = {}) {
157
157
  report.cursor = cursor;
158
158
  console.log(`[hicortex] relink starting (${dryRun ? "dry-run" : "heuristic"}): ${totalMemories} memories, ` +
159
159
  `batch ${batchSize}, cursor ${cursor}${options.reset ? " (reset)" : ""}`);
160
- // Load all existing links once as an unordered pair set (471 rows on the
161
- // live corpus — trivial). `seenPairs` additionally accumulates pairs
160
+ // Load all existing links once as an unordered pair set (a few hundred
161
+ // rows on the live corpus — trivial). `seenPairs` additionally accumulates pairs
162
162
  // handled during this run so re-runs AND within-run reverse candidates
163
163
  // never create duplicate edges.
164
164
  const preExistingPairs = loadExistingPairs(db);
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `hicortex rescore-importance` (#425) — the one-shot LLM backfill that
3
3
  * re-judges the EXISTING corpus under the re-anchored importance rubric
4
- * (owner decision D1, 2026-09-13: rescore via LLM, resumable, local
4
+ * (decision D1: rescore via LLM, resumable, local
5
5
  * gateway).
6
6
  *
7
7
  * Precedents, deliberately mixed per the issue's attribution:
@@ -18,7 +18,7 @@
18
18
  *
19
19
  * Scope: every LIVE (non-absorbed) memory, rowid-ascending. A row's
20
20
  * corroboration_count survives untouched; base_strength is re-judged (that
21
- * is D1's explicit trade: one rubric for all rows, the 2026-08-21-validated
21
+ * is D1's explicit trade: one rubric for all rows, the previously-validated
22
22
  * ORDERING is re-derived rather than mapped).
23
23
  */
24
24
  import { LlmClient } from "./llm.js";
@@ -2,7 +2,7 @@
2
2
  /**
3
3
  * `hicortex rescore-importance` (#425) — the one-shot LLM backfill that
4
4
  * re-judges the EXISTING corpus under the re-anchored importance rubric
5
- * (owner decision D1, 2026-09-13: rescore via LLM, resumable, local
5
+ * (decision D1: rescore via LLM, resumable, local
6
6
  * gateway).
7
7
  *
8
8
  * Precedents, deliberately mixed per the issue's attribution:
@@ -19,7 +19,7 @@
19
19
  *
20
20
  * Scope: every LIVE (non-absorbed) memory, rowid-ascending. A row's
21
21
  * corroboration_count survives untouched; base_strength is re-judged (that
22
- * is D1's explicit trade: one rubric for all rows, the 2026-08-21-validated
22
+ * is D1's explicit trade: one rubric for all rows, the previously-validated
23
23
  * ORDERING is re-derived rather than mapped).
24
24
  */
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -123,8 +123,11 @@ async function runRescoreImportance(options = {}) {
123
123
  let llm;
124
124
  // #332: the confidential client — confidential rows in a slice score on it;
125
125
  // without one they hold (the slice's cursor holds below them, retried when
126
- // the model is configured).
126
+ // the model is configured). #642: per-space clients ride the same pair —
127
+ // a space row scores on ITS model or holds, exactly like the confidential
128
+ // pool (never the main model).
127
129
  let confidentialLlm = null;
130
+ let spaceClients;
128
131
  if (options.llm) {
129
132
  llm = options.llm;
130
133
  }
@@ -135,6 +138,7 @@ async function runRescoreImportance(options = {}) {
135
138
  }
136
139
  llm = resolved.pair.standard;
137
140
  confidentialLlm = resolved.pair.confidential;
141
+ spaceClients = resolved.pair.spaces;
138
142
  }
139
143
  const dbPath = (0, db_js_1.resolveDbPath)(options.dbPath);
140
144
  const db = (0, db_js_1.initDb)(dbPath);
@@ -184,6 +188,7 @@ async function runRescoreImportance(options = {}) {
184
188
  const memories = memoriesForIds(db, sliceRows);
185
189
  const r = await (0, consolidate_js_1.scoreMemoriesImportance)(db, memories, llm, {
186
190
  confidentialLlm,
191
+ spaceClients,
187
192
  onBatch: (written, batchFailed) => {
188
193
  calls++;
189
194
  },
@@ -199,6 +204,20 @@ async function runRescoreImportance(options = {}) {
199
204
  `(llmConfidentialBaseUrl/ApiKey). Cursor held — re-run after configuring.`);
200
205
  break;
201
206
  }
207
+ if (r.skipped_spaces && Object.keys(r.skipped_spaces).length > 0) {
208
+ // #642: same posture for spaces — rows of a space with no model HELD,
209
+ // never scored on the main model and never advanced past. They retry
210
+ // once a per-space llm or the llmConfidential* endpoint exists (the
211
+ // nightly's unscored pool also re-finds them).
212
+ aborted = true;
213
+ const heldList = Object.entries(r.skipped_spaces)
214
+ .map(([id, n]) => `${n} ${id}`)
215
+ .join(", ");
216
+ console.warn(`[hicortex] rescore-importance ABORTED: row(s) of space(s) with no model ` +
217
+ `in the slice at rowid ${sliceRows[0].__rowid} are held (${heldList}). ` +
218
+ `Cursor held — configure spaces.<id>.llm* or llmConfidential* and re-run.`);
219
+ break;
220
+ }
202
221
  if (r.failed > 0) {
203
222
  // The slice's call threw (endpoint down) or a write failed — nothing
204
223
  // usable came out of it. Stop; the cursor stays at the last
@@ -339,6 +339,17 @@ export declare function retrieve(db: Database.Database, embedFn: EmbedFn, query:
339
339
  * rows the predicate is a no-op — byte-identical behavior.
340
340
  */
341
341
  includeConfidential?: boolean;
342
+ /**
343
+ * #642 AC-5: the generalized gate — the requester's visible SPACE set
344
+ * (spacesForMember over the boot-resolved spaces, computed by the adapter
345
+ * from `?agent=`; the wire never carries a space list). Unioned with
346
+ * includeConfidential by resolveVisibleSet: a row is visible iff
347
+ * isVisiblePrivacy(privacy, that union) — shared always, the viewer's
348
+ * spaces yes, everything else (INCLUDING unknown/retired space ids, AC-7)
349
+ * hard-omitted on every channel. Boolean-only callers are byte-identical
350
+ * on standard/confidential data.
351
+ */
352
+ visibleSpaces?: Set<string>;
342
353
  }): Promise<MemorySearchResult[]>;
343
354
  /**
344
355
  * Get recent context, optionally filtered by project.
@@ -352,4 +363,7 @@ export declare function searchRecent(db: Database.Database, options?: {
352
363
  * belief-walk terminals; TRUE only for circle-member requests.
353
364
  */
354
365
  includeConfidential?: boolean;
366
+ /** #642 AC-5: the generalized gate — same contract as retrieve()'s
367
+ * (resolveVisibleSet union; unknown space ids hard-omitted, AC-7). */
368
+ visibleSpaces?: Set<string>;
355
369
  }): MemorySearchResult[];