@gamaze/hicortex 0.27.4 → 0.29.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 (94) hide show
  1. package/assets/dashboard.html +1898 -3211
  2. package/assets/viz.html +229 -2
  3. package/dist/backfill-privacy.d.ts +68 -45
  4. package/dist/backfill-privacy.js +236 -145
  5. package/dist/calibration.d.ts +67 -68
  6. package/dist/calibration.js +75 -78
  7. package/dist/capture-health.d.ts +2 -2
  8. package/dist/capture-health.js +2 -2
  9. package/dist/classification.d.ts +141 -12
  10. package/dist/classification.js +214 -27
  11. package/dist/classify-domains.d.ts +1 -1
  12. package/dist/classify-domains.js +2 -2
  13. package/dist/cli-args.d.ts +5 -3
  14. package/dist/cli-args.js +7 -3
  15. package/dist/cli.d.ts +2 -0
  16. package/dist/cli.js +64 -16
  17. package/dist/cluster.d.ts +12 -9
  18. package/dist/cluster.js +9 -6
  19. package/dist/consolidate.d.ts +93 -43
  20. package/dist/consolidate.js +255 -119
  21. package/dist/dashboard.d.ts +48 -5
  22. package/dist/dashboard.js +55 -3
  23. package/dist/db.js +27 -6
  24. package/dist/dedup.d.ts +2 -3
  25. package/dist/dedup.js +2 -3
  26. package/dist/distill-queue.d.ts +36 -4
  27. package/dist/distill-queue.js +80 -18
  28. package/dist/distiller.d.ts +1 -1
  29. package/dist/distiller.js +13 -12
  30. package/dist/domain-classify.d.ts +8 -9
  31. package/dist/domain-classify.js +6 -7
  32. package/dist/graph.d.ts +15 -5
  33. package/dist/graph.js +46 -13
  34. package/dist/hermes-transcript-reader.d.ts +1 -1
  35. package/dist/hermes-transcript-reader.js +1 -1
  36. package/dist/init.d.ts +30 -2
  37. package/dist/init.js +48 -3
  38. package/dist/llm.d.ts +1 -1
  39. package/dist/llm.js +5 -5
  40. package/dist/mcp-server.js +323 -59
  41. package/dist/memory-instructions.d.ts +2 -2
  42. package/dist/memory-instructions.js +2 -2
  43. package/dist/nightly.d.ts +1 -1
  44. package/dist/nightly.js +64 -5
  45. package/dist/nofit.d.ts +2 -2
  46. package/dist/nofit.js +2 -2
  47. package/dist/observed-agents.d.ts +54 -0
  48. package/dist/observed-agents.js +78 -0
  49. package/dist/project-canonicalize.d.ts +6 -5
  50. package/dist/project-canonicalize.js +6 -5
  51. package/dist/prompts.d.ts +29 -8
  52. package/dist/prompts.js +39 -16
  53. package/dist/quality-scoreboard.d.ts +1 -1
  54. package/dist/recall-hook-cli.d.ts +1 -1
  55. package/dist/recall-hook-cli.js +2 -2
  56. package/dist/recall-index.d.ts +28 -14
  57. package/dist/recall-index.js +22 -10
  58. package/dist/recall-precision.d.ts +3 -3
  59. package/dist/recall-precision.js +5 -4
  60. package/dist/reconcile-projects.d.ts +2 -2
  61. package/dist/reconcile-projects.js +2 -2
  62. package/dist/reconsolidation.d.ts +9 -2
  63. package/dist/reconsolidation.js +48 -31
  64. package/dist/relink.d.ts +2 -2
  65. package/dist/relink.js +4 -4
  66. package/dist/rescore-importance.d.ts +2 -2
  67. package/dist/rescore-importance.js +22 -3
  68. package/dist/retrieval.d.ts +14 -0
  69. package/dist/retrieval.js +11 -11
  70. package/dist/schema-prototypes.d.ts +1 -1
  71. package/dist/schema-prototypes.js +1 -1
  72. package/dist/seed-lesson.js +4 -2
  73. package/dist/spaces-api.d.ts +104 -0
  74. package/dist/spaces-api.js +193 -0
  75. package/dist/spaces-cli.d.ts +90 -0
  76. package/dist/spaces-cli.js +245 -0
  77. package/dist/spaces.d.ts +187 -0
  78. package/dist/spaces.js +360 -0
  79. package/dist/storage.d.ts +47 -10
  80. package/dist/storage.js +74 -17
  81. package/dist/sweep-volatile.d.ts +2 -2
  82. package/dist/sweep-volatile.js +2 -2
  83. package/dist/telemetry-cli.d.ts +1 -1
  84. package/dist/telemetry-cli.js +1 -1
  85. package/dist/type-classify.d.ts +1 -1
  86. package/dist/type-classify.js +1 -1
  87. package/dist/type-labels.d.ts +1 -1
  88. package/dist/type-labels.js +1 -1
  89. package/dist/types.d.ts +43 -20
  90. package/dist/wrapper-prompt.d.ts +2 -2
  91. package/dist/wrapper-prompt.js +2 -2
  92. package/opencode-plugin/hicortex/index.ts +562 -364
  93. package/package.json +2 -2
  94. package/server.json +2 -2
@@ -58,6 +58,7 @@ exports.resolveMemorySoftCap = resolveMemorySoftCap;
58
58
  exports.stageMemoryCapEviction = stageMemoryCapEviction;
59
59
  exports.runConsolidation = runConsolidation;
60
60
  const classification_js_1 = require("./classification.js");
61
+ const spaces_js_1 = require("./spaces.js");
61
62
  const retrieval_js_1 = require("./retrieval.js");
62
63
  const storage = __importStar(require("./storage.js"));
63
64
  const config_read_js_1 = require("./config-read.js");
@@ -78,10 +79,10 @@ const CALIBRATION = __importStar(require("./calibration.js"));
78
79
  * #241 consolidateMaxLlmCalls mechanism, renamed and widened). A runaway
79
80
  * BACKSTOP that bounds money/load INDEPENDENT OF LATENCY — a fast metered or
80
81
  * capacity-limited endpoint permits thousands of calls inside the wall-clock
81
- * budget, so time alone cannot protect it (owner ruling 2026-09-12). Consumed
82
+ * budget, so time alone cannot protect it. Consumed
82
83
  * in run order: a stage that exhausts it defers its remainder via its cursor.
83
- * 5000 clears a one-time classification backlog (a ~2000-memory batch drains
84
- * in ~1-2 runs) with margin. Config: `nightlyLlmCallBudget` (#405); the old
84
+ * 5000 clears a one-time classification backlog in a couple of runs with
85
+ * margin. Config: `nightlyLlmCallBudget` (#405); the old
85
86
  * `consolidateMaxLlmCalls` key is a deprecated alias honored one release.
86
87
  */
87
88
  exports.DEFAULT_NIGHTLY_LLM_CALL_BUDGET = 5000;
@@ -110,12 +111,12 @@ const CONSOLIDATE_PRUNE_MIN_AGE_DAYS = 90;
110
111
  /**
111
112
  * Minimum COSINE similarity for a link candidate.
112
113
  *
113
- * Calibration (2026-07): measured top-10 neighbor cosine histogram on the
114
- * ~3000-memory production corpus. Typical top-1 neighbor cosine:
115
- * median 0.823, p10 0.743, p90 0.902. Threshold 0.75 combined with the
116
- * top-3 cap yields ≈ 2.2 candidate links/memory. The previous value (0.55)
114
+ * Calibration: measured top-10 neighbor cosine histogram on a
115
+ * several-thousand-memory production corpus — typical top-1 neighbor cosine
116
+ * sits in the mid-0.8s. Threshold 0.75 combined with the
117
+ * top-3 cap yields ≈ 2 candidate links/memory. The previous value (0.55)
117
118
  * lived on an accidental 1−L2 scale where it required cosine > 0.90 — a
118
- * near-duplicate detector that linked only 12% of memories.
119
+ * near-duplicate detector that linked only a small fraction of memories.
119
120
  */
120
121
  exports.CONSOLIDATE_LINK_THRESHOLD = 0.75;
121
122
  /** Max link candidates kept per memory (highest-cosine neighbors first). */
@@ -134,9 +135,10 @@ exports.CONSOLIDATE_LINK_FETCH_MAX_K = 200;
134
135
  /**
135
136
  * Minimum COSINE similarity for a CROSS-PROJECT link candidate.
136
137
  *
137
- * A 672-link audit (17 LLM judges, 2026-07) found cross-project links were 65%
138
- * wrong-link vs 6% for same-project, and that strength (cosine) predicts quality
139
- * (wrong-link 42% → 6% across strength quartiles). Cross-project pairs must clear
138
+ * A many-judge link audit found cross-project links were overwhelmingly
139
+ * wrong-link while same-project links were mostly right, and that strength
140
+ * (cosine) predicts quality (the wrong-link share fell steadily across
141
+ * strength quartiles). Cross-project pairs must clear
140
142
  * a much higher bar than the same-project 0.75 to survive discovery. Same-project
141
143
  * links keep CONSOLIDATE_LINK_THRESHOLD (0.75).
142
144
  */
@@ -407,9 +409,14 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
407
409
  let failed = 0;
408
410
  let skippedBudget = 0;
409
411
  let skippedConfidential = 0;
412
+ const skippedSpaces = {};
410
413
  let remaining = memories.length;
411
- const pair = { standard: llm, confidential: opts.confidentialLlm ?? null };
412
- for (const batch of buildImportanceBatches(memories, 10)) {
414
+ const pair = {
415
+ standard: llm,
416
+ confidential: opts.confidentialLlm ?? null,
417
+ spaces: opts.spaceClients,
418
+ };
419
+ for (const batch of buildImportanceBatches(memories, 10, opts.spaceOrder)) {
413
420
  if (budget?.exhausted) {
414
421
  skippedBudget += remaining;
415
422
  break;
@@ -426,11 +433,16 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
426
433
  remaining -= batch.memories.length;
427
434
  continue;
428
435
  }
429
- // #332 per-pool selection: the confidential pool needs its client —
430
- // absent ⇒ skip-and-hold (rows stay unscored; retried next run).
436
+ // #332/#642 per-space selection: every non-shared pool needs its own
437
+ // client — absent ⇒ skip-and-hold (rows stay unscored; retried next run).
431
438
  const batchLlm = (0, classification_js_1.clientForPool)(pair, batch.pool);
432
439
  if (!batchLlm) {
433
- skippedConfidential += batch.memories.length;
440
+ if (batch.pool === "confidential") {
441
+ skippedConfidential += batch.memories.length;
442
+ }
443
+ else {
444
+ skippedSpaces[batch.pool] = (skippedSpaces[batch.pool] ?? 0) + batch.memories.length;
445
+ }
434
446
  remaining -= batch.memories.length;
435
447
  continue;
436
448
  }
@@ -496,33 +508,57 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
496
508
  console.warn(`[hicortex] importance: ${skippedConfidential} confidential memories held — ` +
497
509
  `no confidential model configured (llmConfidentialBaseUrl/ApiKey). Retried next run.`);
498
510
  }
511
+ // #642: same visibility for held SPACES — one line naming every space id
512
+ // and its held count (a silently-unscored space is the same failure mode).
513
+ const heldSpaceIds = Object.keys(skippedSpaces);
514
+ if (heldSpaceIds.length > 0) {
515
+ console.warn(`[hicortex] importance: held memories by space — ` +
516
+ heldSpaceIds.map((id) => `${skippedSpaces[id]} ${id}`).join(", ") +
517
+ `. No model configured for those spaces (spaces.<id>.llm* or the ` +
518
+ `llmConfidential* endpoint); retried next run, never the main model.`);
519
+ }
499
520
  return {
500
521
  scored,
501
522
  failed,
502
523
  skipped_budget: skippedBudget,
503
524
  ...(skippedConfidential > 0 ? { skipped_confidential: skippedConfidential } : {}),
525
+ ...(heldSpaceIds.length > 0 ? { skipped_spaces: skippedSpaces } : {}),
504
526
  };
505
527
  }
506
528
  /**
507
- * #332 — the importance batch builder: partition by classification, then
508
- * slice into batches. Every batch is SINGLE-CLASS by construction (AC-10),
509
- * so the scoring call site can route each batch to the client matching its
510
- * pool with no per-item checks. Exported for the unit test.
529
+ * #332/#642 — the importance batch builder: partition by SPACE (spaceOf —
530
+ * 'standard' is the shared pool, every other stamp its own space), then
531
+ * slice into batches. Every batch is SINGLE-SPACE by construction (AC-10
532
+ * widened to N pools), so the scoring call site can route each batch to the
533
+ * client matching its space with no per-item checks. Exported for the unit
534
+ * test.
535
+ *
536
+ * Emission order (#642, deterministic): the shared pool first (arrival
537
+ * order), then the `spaceOrder` sequence (the CONFIG key order —
538
+ * resolveSpaces preserves it), then any residual stored ids no configured
539
+ * space claims, in first-appearance order. A residual (stored-but-retired)
540
+ * id has no client by construction, so its batches HOLD at the call site —
541
+ * retired rows are reported as held, never scored, never lost.
511
542
  */
512
- function buildImportanceBatches(memories, batchSize = 10) {
543
+ function buildImportanceBatches(memories, batchSize = 10,
544
+ /** #642: the configured space ids in config order. The default keeps the
545
+ * pre-#642 two-pool output (standard then confidential) for every
546
+ * existing caller. */
547
+ spaceOrder = ["confidential"]) {
513
548
  const byPool = new Map();
514
549
  for (const mem of memories) {
515
- const pool = mem.privacy === "confidential" ? "confidential" : "standard";
550
+ const pool = (0, spaces_js_1.spaceOf)(mem.privacy);
516
551
  const list = byPool.get(pool);
517
552
  if (list)
518
553
  list.push(mem);
519
554
  else
520
555
  byPool.set(pool, [mem]);
521
556
  }
522
- // Standard pool first (arrival order), then confidential — a stable,
523
- // greppable order.
557
+ const order = new Set(["standard", ...spaceOrder]);
558
+ for (const id of byPool.keys())
559
+ order.add(id);
524
560
  const out = [];
525
- for (const pool of ["standard", "confidential"]) {
561
+ for (const pool of order) {
526
562
  const list = byPool.get(pool);
527
563
  if (!list)
528
564
  continue;
@@ -538,22 +574,36 @@ async function stageImportance(db, memories, llm, budget, dryRun, deadline,
538
574
  * promotion/enrichment gains that survived the nightly. */
539
575
  guardSkipped = 0,
540
576
  /** #332: the confidential-pool client (see scoreMemoriesImportance). */
541
- confidentialLlm) {
542
- const r = await scoreMemoriesImportance(db, memories, llm, { budget, deadline, dryRun, confidentialLlm });
577
+ confidentialLlm,
578
+ /** #642: per-space clients + the configured batch order (see
579
+ * scoreMemoriesImportance). */
580
+ spaceClients, spaceOrder) {
581
+ const r = await scoreMemoriesImportance(db, memories, llm, {
582
+ budget,
583
+ deadline,
584
+ dryRun,
585
+ confidentialLlm,
586
+ spaceClients,
587
+ spaceOrder,
588
+ });
543
589
  return { ...r, guard_skipped: guardSkipped };
544
590
  }
545
591
  // ---------------------------------------------------------------------------
546
592
  // Stage 2.5: Reflection
547
593
  // ---------------------------------------------------------------------------
548
594
  /**
549
- * One reflection run over ONE class-pure cohort (#332). The cohort never
550
- * mixes classes (the caller splits), the recent-lessons dedup block is
551
- * class-scoped, the contradiction check only sees same-class lessons, and
552
- * every generated lesson inherits the pool's stamp at insert. `client` is the
553
- * client matching `pool` — the caller guarantees it (a confidential cohort
554
- * without a client never reaches here; it holds instead).
595
+ * One reflection run over ONE space-pure cohort (#332, widened to spaces by
596
+ * #642). The cohort never mixes spaces (the caller splits), the
597
+ * recent-lessons dedup block is space-scoped, the contradiction check only
598
+ * sees same-space lessons, and every generated lesson inherits the pool's
599
+ * stamp at insert. `client` is the client matching `pool` — the caller
600
+ * guarantees it (a cohort whose space has no client never reaches here; it
601
+ * holds instead). `privacyLine` is the RESOLVED space line threaded from the
602
+ * caller (SpaceDef.privacyLine); undefined for 'standard' and for a
603
+ * 'confidential' pool with no resolved SpaceDef — both fall back to the
604
+ * shipped constants inside reflection(), byte-identical to #602.
555
605
  */
556
- async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
606
+ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun, privacyLine) {
557
607
  if (cohort.length === 0) {
558
608
  return { generated: 0, skipped: true, reason: "no memories" };
559
609
  }
@@ -566,19 +616,22 @@ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
566
616
  });
567
617
  const memoriesBlock = lines.join("\n\n");
568
618
  // Feed recent lessons to prevent duplicates and enable escalation.
569
- // #332: the dedup block is CLASS-SCOPED — a confidential run's prompt must
570
- // not quote standard lessons (and vice versa); the pool's own lessons are
571
- // the coherent reference set.
619
+ // #332/#642: the dedup block is SPACE-SCOPED — a private pool's prompt must
620
+ // not quote another pool's lessons (and vice versa); the pool's own lessons
621
+ // are the coherent reference set. visibleSpaces {pool} is the same read the
622
+ // legacy boolean produced for both pre-#642 pools ('standard' reads
623
+ // shared-only, 'confidential' reads shared+confidential).
572
624
  const recentLessons = storage
573
- .getLessons(db, 7, null, { includeConfidential: pool === "confidential" })
625
+ .getLessons(db, 7, null, { visibleSpaces: new Set([pool]) })
574
626
  .slice(0, 10);
575
627
  const recentBlock = recentLessons.length > 0
576
628
  ? recentLessons.map(l => `- ${l.content.slice(0, 150)}`).join("\n")
577
629
  : undefined;
578
- // #602: pool-aware prompt — the confidential pool's reflection prompt swaps
579
- // ONLY the privacy line (personal domains allowed at the process level;
580
- // secrets still never), so the pool can actually generate its lessons.
581
- const prompt = (0, prompts_js_1.reflection)(memoriesBlock, recentBlock, pool);
630
+ // #602/#642: pool-aware prompt — each pool's reflection prompt swaps ONLY
631
+ // the privacy line (the RESOLVED space line here; personal domains allowed
632
+ // at the process level for private pools; secrets still never), so the pool
633
+ // can actually generate its lessons.
634
+ const prompt = (0, prompts_js_1.reflection)(memoriesBlock, recentBlock, pool, privacyLine);
582
635
  if (dryRun) {
583
636
  return { generated: 0, skipped: false };
584
637
  }
@@ -633,12 +686,12 @@ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
633
686
  // TRUE cosine > 0.80 (#145): the old `1 − n.distance > 0.80` sat on
634
687
  // the accidental 1−L2 scale and required cosine > 0.98 — the check
635
688
  // effectively never fired. See isContradictionCandidate.
636
- // #332: class-scoped — only SAME-POOL lessons enter the check (the
637
- // vector search is unscoped; the filter narrows it).
689
+ // #332/#642: space-scoped — only SAME-SPACE lessons enter the check
690
+ // (the vector search is unscoped; the filter narrows it).
638
691
  const similarLessons = storage.vectorSearch(db, embedding, 3)
639
692
  .filter((n) => isContradictionCandidate(n.distance) &&
640
693
  n.memory_type === "learnings" &&
641
- (n.privacy === "confidential") === (pool === "confidential"));
694
+ (0, spaces_js_1.spaceOf)(n.privacy) === pool);
642
695
  let contradicted = false;
643
696
  if (similarLessons.length > 0 && budget.use("contradiction_check")) {
644
697
  const existingText = similarLessons[0].content.slice(0, 300);
@@ -667,8 +720,8 @@ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
667
720
  project,
668
721
  memoryType: "learnings",
669
722
  baseStrength: baseStrength[severity] ?? 0.8,
670
- // #332: lessons inherit their pool's stamp — the class is born
671
- // with the cohort, never judged from content.
723
+ // #332/#642: lessons inherit their pool's (space's) stamp — the
724
+ // class is born with the cohort, never judged from content.
672
725
  privacy: pool,
673
726
  });
674
727
  generated++;
@@ -696,43 +749,78 @@ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
696
749
  }
697
750
  async function stageReflection(db, memories, llm, budget, embedFn, dryRun,
698
751
  /** #332: the confidential-pool client; absent ⇒ the confidential cohort
699
- * holds (skipped, no fallback to the main model). */
700
- confidentialLlm) {
752
+ * holds (skipped, no fallback to the main model). #642: the confidential
753
+ * SPACE keeps this exact role — it is never routed through spaceClients. */
754
+ confidentialLlm,
755
+ /** #642: per-space clients (every configured space except 'confidential'). */
756
+ spaceClients,
757
+ /** #642: the resolved SpaceDef list (config order) — cohort order + each
758
+ * space's privacyLine. Absent = the pre-#642 two-pool split. */
759
+ spaces) {
701
760
  if (memories.length === 0) {
702
761
  return { lessons_generated: 0, skipped: true, reason: "no memories" };
703
762
  }
704
- // #332: split the watermark cohort by class — the pools NEVER mix in a
705
- // reflection prompt (a mixed cohort would distill cross-class lessons with
706
- // no honest stamp). Standard run unchanged on the main client.
707
- const standardCohort = memories.filter((m) => m.privacy !== "confidential");
708
- const confidentialCohort = memories.filter((m) => m.privacy === "confidential");
763
+ // #332/#642: split the watermark cohort by SPACE — the pools NEVER mix in
764
+ // a reflection prompt (a mixed cohort would distill cross-space lessons
765
+ // with no honest stamp). Standard run unchanged on the main client; every
766
+ // other space runs its own cohort on its own client, config order.
767
+ const spaceById = new Map((spaces ?? []).map((s) => [s.id, s]));
768
+ const cohorts = new Map();
769
+ for (const mem of memories) {
770
+ const space = (0, spaces_js_1.spaceOf)(mem.privacy);
771
+ const list = cohorts.get(space);
772
+ if (list)
773
+ list.push(mem);
774
+ else
775
+ cohorts.set(space, [mem]);
776
+ }
777
+ // Deterministic order: shared first, then the configured spaces in CONFIG
778
+ // order (a legacy-materialized confidential space sits last — the pre-#642
779
+ // standard→confidential order), then residual stored ids (first-seen).
780
+ const order = new Set(["standard", ...(spaces ?? []).map((s) => s.id)]);
781
+ for (const id of cohorts.keys())
782
+ order.add(id);
783
+ // The confidential pool's client is ALWAYS the confidential field — never
784
+ // the space map (one endpoint, one role; buildSpaceLlms skips the id).
785
+ const clientForSpace = (id) => id === "confidential" ? (confidentialLlm ?? null) : (spaceClients?.get(id) ?? null);
709
786
  let generated = 0;
710
787
  let anyFailed = false;
711
788
  let anySkipped = false;
712
789
  let reason;
713
790
  let confidentialSkipped = false;
714
- if (standardCohort.length > 0) {
715
- const r = await reflectPool(db, standardCohort, "standard", llm, budget, embedFn, dryRun);
716
- generated += r.generated;
717
- anyFailed = anyFailed || r.failed === true;
718
- anySkipped = anySkipped || r.skipped === true;
719
- reason = reason ?? r.reason;
720
- }
721
- if (confidentialCohort.length > 0) {
722
- if (!confidentialLlm) {
723
- // Hold: the cohort is retried next run (it is the lastConsolidated
724
- // watermark cohort — a held watermark re-finds it). Never the main model.
725
- confidentialSkipped = true;
726
- console.warn(`[hicortex] reflection: ${confidentialCohort.length} confidential memorie(s) held — ` +
727
- `no confidential model configured (llmConfidentialBaseUrl/ApiKey). No lessons generated for the pool.`);
728
- }
729
- else {
730
- const r = await reflectPool(db, confidentialCohort, "confidential", confidentialLlm, budget, embedFn, dryRun);
791
+ const heldSpaces = [];
792
+ for (const pool of order) {
793
+ const cohort = cohorts.get(pool);
794
+ if (!cohort || cohort.length === 0)
795
+ continue;
796
+ if (pool === "standard") {
797
+ const r = await reflectPool(db, cohort, "standard", llm, budget, embedFn, dryRun);
731
798
  generated += r.generated;
732
799
  anyFailed = anyFailed || r.failed === true;
733
800
  anySkipped = anySkipped || r.skipped === true;
734
801
  reason = reason ?? r.reason;
802
+ continue;
803
+ }
804
+ const client = clientForSpace(pool);
805
+ if (!client) {
806
+ // Hold: the cohort is retried next run (it is the lastConsolidated
807
+ // watermark cohort — a held watermark re-finds it). Never the main model.
808
+ if (pool === "confidential")
809
+ confidentialSkipped = true;
810
+ heldSpaces.push(pool);
811
+ console.warn(pool === "confidential"
812
+ ? `[hicortex] reflection: ${cohort.length} confidential memorie(s) held — ` +
813
+ `no confidential model configured (llmConfidentialBaseUrl/ApiKey). No lessons generated for the pool.`
814
+ : `[hicortex] reflection: ${cohort.length} memorie(s) of space '${pool}' held — ` +
815
+ `no model configured for that space (spaces.${pool}.llm* or the llmConfidential* ` +
816
+ `endpoint). No lessons generated for the pool; never the main model.`);
817
+ continue;
735
818
  }
819
+ const r = await reflectPool(db, cohort, pool, client, budget, embedFn, dryRun, spaceById.get(pool)?.privacyLine);
820
+ generated += r.generated;
821
+ anyFailed = anyFailed || r.failed === true;
822
+ anySkipped = anySkipped || r.skipped === true;
823
+ reason = reason ?? r.reason;
736
824
  }
737
825
  return {
738
826
  lessons_generated: generated,
@@ -740,6 +828,7 @@ confidentialLlm) {
740
828
  ...(anySkipped ? { skipped: true } : {}),
741
829
  ...(reason ? { reason } : {}),
742
830
  ...(confidentialSkipped ? { confidential_skipped: true } : {}),
831
+ ...(heldSpaces.length > 0 ? { held_spaces: heldSpaces } : {}),
743
832
  };
744
833
  }
745
834
  // ---------------------------------------------------------------------------
@@ -793,7 +882,11 @@ function rebuildContentModuleIndex(db, domains, stateDir) {
793
882
  async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, stateDir, weakPrimaryFloor = nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline,
794
883
  /** #332: the confidential-pool client — classification calls pick the
795
884
  * client matching EACH memory's stamp (AC-10 second half). */
796
- confidentialLlm) {
885
+ confidentialLlm,
886
+ /** #642: per-space clients (every configured space except 'confidential') —
887
+ * per-row selection is spaceOf(row.privacy), one row's content to one
888
+ * client; a space without a client HOLDS its rows. */
889
+ spaceClients) {
797
890
  // Rows needing (re)classification:
798
891
  // - domain IS NULL (never classified), OR
799
892
  // - domain NOT IN the current vocabulary (a rename/removal re-files), OR
@@ -820,7 +913,12 @@ confidentialLlm) {
820
913
  let weakPrimary = 0;
821
914
  let noAssociationDecayed = 0;
822
915
  let heldConfidential = 0;
823
- const pair = { standard: llm, confidential: confidentialLlm ?? null };
916
+ const heldSpaces = {};
917
+ const pair = {
918
+ standard: llm,
919
+ confidential: confidentialLlm ?? null,
920
+ spaces: spaceClients,
921
+ };
824
922
  if (rows.length > 0) {
825
923
  // Prototypes at run start — newly classified memories get their weights
826
924
  // from the CURRENT prototypes (the post-classification recompute below
@@ -836,13 +934,18 @@ confidentialLlm) {
836
934
  console.warn(`[hicortex] content-domain: budget exhausted after ${classified} classified`);
837
935
  break;
838
936
  }
839
- // #332 per-row client selection: the classify call carries this row's
840
- // CONTENT — a confidential row goes to the confidential client, and
841
- // without one it is HELD (tags untouched, retried next run), never
842
- // classified on the main model.
843
- const rowLlm = (0, classification_js_1.clientForPool)(pair, row.privacy === "confidential" ? "confidential" : "standard");
937
+ // #332/#642 per-row client selection: the classify call carries this
938
+ // row's CONTENT — a private-pool row goes to ITS space's client
939
+ // (confidential via the confidential field), and without one it is
940
+ // HELD (tags untouched, retried next run), never classified on the
941
+ // main model.
942
+ const rowSpace = (0, spaces_js_1.spaceOf)(row.privacy);
943
+ const rowLlm = (0, classification_js_1.clientForPool)(pair, rowSpace);
844
944
  if (!rowLlm) {
845
- heldConfidential++;
945
+ if (rowSpace === "confidential")
946
+ heldConfidential++;
947
+ else
948
+ heldSpaces[rowSpace] = (heldSpaces[rowSpace] ?? 0) + 1;
846
949
  continue;
847
950
  }
848
951
  // classifyMemoryTags returns null ONLY on infra error (throws after retry) —
@@ -857,7 +960,7 @@ confidentialLlm) {
857
960
  continue;
858
961
  }
859
962
  if (result.tags.length === 0) {
860
- // Genuine no-fit (owner amendment 07.07): weak primary from the
963
+ // Genuine no-fit (spec 2026-07-07 amendment): weak primary from the
861
964
  // prototype argmax when it clears the floor, else accelerated decay.
862
965
  // Each row appears exactly once in `rows`, so a run never
863
966
  // double-halves.
@@ -892,6 +995,13 @@ confidentialLlm) {
892
995
  console.warn(`[hicortex] content-domain: ${heldConfidential} confidential row(s) held — ` +
893
996
  `no confidential model configured; they retry next run`);
894
997
  }
998
+ // #642: name every held SPACE (same visibility as the confidential line).
999
+ const heldSpaceIds = Object.keys(heldSpaces);
1000
+ if (heldSpaceIds.length > 0) {
1001
+ console.warn(`[hicortex] content-domain: rows held by space — ` +
1002
+ heldSpaceIds.map((id) => `${heldSpaces[id]} ${id}`).join(", ") +
1003
+ `. No model configured for those spaces; they retry next run, never the main model.`);
1004
+ }
895
1005
  console.log(`[hicortex] Graded tags: ${classified} classified, ${weakPrimary} weak-primary, ` +
896
1006
  `${noAssociationDecayed} no-association decayed, ${prototypes.size} prototypes ` +
897
1007
  `(${seeded} description-seeded), ${weightsRecomputed} weights recomputed, ` +
@@ -906,6 +1016,7 @@ confidentialLlm) {
906
1016
  weak_primary: weakPrimary,
907
1017
  no_association_decayed: noAssociationDecayed,
908
1018
  ...(heldConfidential > 0 ? { held_confidential: heldConfidential } : {}),
1019
+ ...(heldSpaceIds.length > 0 ? { held_spaces: heldSpaces } : {}),
909
1020
  ...(rows.length === 0 ? { reason: "nothing_stale" } : {}),
910
1021
  };
911
1022
  }
@@ -1078,40 +1189,42 @@ async function stageDomainCuration(db, llm, budget, dryRun, stateDir) {
1078
1189
  /**
1079
1190
  * Discovery: find link candidates for one memory given its embedding.
1080
1191
  * Vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
1081
- * highest-cosine SAME-CLASS neighbors above CONSOLIDATE_LINK_THRESHOLD,
1192
+ * highest-cosine SAME-SPACE neighbors above CONSOLIDATE_LINK_THRESHOLD,
1082
1193
  * pre-compute the heuristic relationship type.
1083
1194
  *
1084
- * #602 — ADAPTIVE CLASS-SCOPED FETCH. The pre-#602 code fetched a fixed
1085
- * top-10 UNFILTERED window and then dropped cross-class neighbors in the
1195
+ * #602 — ADAPTIVE SPACE-SCOPED FETCH (class-scoped at birth, space-scoped
1196
+ * since #642). The pre-#602 code fetched a fixed
1197
+ * top-10 UNFILTERED window and then dropped cross-space neighbors in the
1086
1198
  * loop — the #192 filtered-over-fetch defect class. Starvation math: when
1087
- * the standard pool heavily outnumbers the confidential pool, a confidential
1088
- * memory's 10 nearest neighbors are usually ALL standard (the classes are
1089
- * topically distinct but the majority class is much larger), so the
1090
- * confidential pool systematically under-linked — its same-class neighbors
1199
+ * the shared pool heavily outnumbers a private space, a private
1200
+ * memory's 10 nearest neighbors are usually ALL shared (the spaces are
1201
+ * topically distinct but the majority pool is much larger), so the
1202
+ * private pool systematically under-linked — its same-space neighbors
1091
1203
  * never made the window. The fix
1092
1204
  * escalates the window (k × 4 per step, capped at CONSOLIDATE_LINK_FETCH_MAX_K
1093
1205
  * = the #192 over-fetch cap) until the window holds CONSOLIDATE_LINK_TOP_K
1094
- * same-class neighbors, comes back short (no more rows may exist), or hits
1206
+ * same-space neighbors, comes back short (no more rows may exist), or hits
1095
1207
  * the cap. Balanced corpora do ZERO extra queries (the first window already
1096
- * holds 3+ same-class neighbors).
1208
+ * holds 3+ same-space neighbors).
1097
1209
  *
1098
- * WHY the class is not denormalized into the vec0 table (a WHERE clause
1210
+ * WHY the space is not denormalized into the vec0 table (a WHERE clause
1099
1211
  * would make this a one-fetch query): memory_vectors carries only id +
1100
1212
  * embedding, and privacy is MUTABLE post-insert (`hicortex backfill-privacy`
1101
- * and REST /update can reclassify a row) — a vec0-side class column would go
1102
- * stale the moment a row's class changed without a re-embed. The class is
1213
+ * and REST /update can reclassify a row) — a vec0-side space column would go
1214
+ * stale the moment a row's stamp changed without a re-embed. The space is
1103
1215
  * read live from memories, so it can never disagree with the row.
1104
1216
  *
1105
1217
  * Shared between the nightly `stageLinks` (which embeds via embedFn) and
1106
1218
  * `hicortex relink` (which reuses stored embeddings from memory_vectors).
1107
1219
  */
1108
1220
  function discoverLinkCandidates(db, mem, embedding) {
1109
- // #332: class-pure link discovery — a candidate NEVER crosses the circle
1110
- // (no memory_links row joins the two classes; a pre-#332 cross-class link
1111
- // stays as historical data, but the stage creates none). NULL privacy (a
1112
- // pre-v27 row) reads standard, the same normalization everywhere else uses.
1113
- const memClass = mem.privacy === "confidential" ? "confidential" : "standard";
1114
- const isSameClass = (m) => (m.privacy === "confidential" ? "confidential" : "standard") === memClass;
1221
+ // #332/#642: space-pure link discovery — a candidate NEVER crosses a space
1222
+ // boundary (no memory_links row joins two spaces; a pre-existing
1223
+ // cross-space link stays as historical data, but the stage creates none).
1224
+ // NULL privacy (a pre-v27 row) reads standard via spaceOf — the same
1225
+ // normalization every read gate uses.
1226
+ const memSpace = (0, spaces_js_1.spaceOf)(mem.privacy);
1227
+ const isSameSpace = (m) => (0, spaces_js_1.spaceOf)(m.privacy) === memSpace;
1115
1228
  // The excluded self (distance 0 — always the nearest stored row) occupies
1116
1229
  // one seat of the raw window, so each fetch asks for k + 1: a FULL window
1117
1230
  // then yields exactly k non-self neighbors and `neighbors.length === k`
@@ -1121,7 +1234,7 @@ function discoverLinkCandidates(db, mem, embedding) {
1121
1234
  // own class AND the corpus may hold more rows beyond it.
1122
1235
  let k = exports.CONSOLIDATE_LINK_FETCH_K;
1123
1236
  let neighbors = fetchWindow(k);
1124
- while (neighbors.filter(isSameClass).length < exports.CONSOLIDATE_LINK_TOP_K &&
1237
+ while (neighbors.filter(isSameSpace).length < exports.CONSOLIDATE_LINK_TOP_K &&
1125
1238
  neighbors.length === k &&
1126
1239
  k < exports.CONSOLIDATE_LINK_FETCH_MAX_K) {
1127
1240
  k = Math.min(k * 4, exports.CONSOLIDATE_LINK_FETCH_MAX_K);
@@ -1135,16 +1248,17 @@ function discoverLinkCandidates(db, mem, embedding) {
1135
1248
  for (const neighbor of neighbors) {
1136
1249
  if (candidates.length >= exports.CONSOLIDATE_LINK_TOP_K)
1137
1250
  break;
1138
- // The in-loop class filter stays: it enforces purity (#332) and top-K
1139
- // cosine order regardless of how wide the escalated window got (#602).
1140
- if (!isSameClass(neighbor))
1251
+ // The in-loop space filter stays: it enforces purity (#332/#642) and
1252
+ // top-K cosine order regardless of how wide the escalated window got
1253
+ // (#602).
1254
+ if (!isSameSpace(neighbor))
1141
1255
  continue;
1142
1256
  // sqlite-vec vec0 `distance` is L2, not a similarity. Embeddings are
1143
1257
  // L2-normalized (embedder.ts, normalize: true), so cos = 1 − d²/2.
1144
1258
  // The old `1 − distance` formula silently required cosine > 0.90.
1145
1259
  const similarity = (0, retrieval_js_1.l2ToCosine)(neighbor.distance);
1146
- // Cross-project guard (2026-07 audit): cross-project links were 65%
1147
- // wrong-link vs 6% same-project. A candidate whose source/target belong to
1260
+ // Cross-project guard (link audit): cross-project links were overwhelmingly
1261
+ // wrong-link while same-project links were mostly right. A candidate whose source/target belong to
1148
1262
  // DIFFERENT projects must clear the higher CROSS_PROJECT_LINK_THRESHOLD;
1149
1263
  // same-project keeps CONSOLIDATE_LINK_THRESHOLD. A memory with no project
1150
1264
  // (null) is treated as same-project — the guard only fires on two distinct
@@ -1165,9 +1279,9 @@ function discoverLinkCandidates(db, mem, embedding) {
1165
1279
  /**
1166
1280
  * Classification: assign a relationship type to each candidate link.
1167
1281
  *
1168
- * HEURISTIC-ONLY (2026-07). LLM edge classification was retired after the
1169
- * 672-link audit (see the Stage 3 header) found the LLM-classified UPPERCASE
1170
- * types near-useless (CONTRADICTS 4% acceptable). Every candidate now takes its
1282
+ * HEURISTIC-ONLY. LLM edge classification was retired after a comprehensive
1283
+ * link audit (see the Stage 3 header) found the LLM-classified UPPERCASE
1284
+ * types near-useless (every one below half acceptable). Every candidate now takes its
1171
1285
  * pre-computed `heuristicType` (only `extends` or `relates_to` — see
1172
1286
  * classifyRelationship). No LLM call is made. #405: the ignored `llm`/`budget`
1173
1287
  * params are deleted — the signature now tells the truth.
@@ -1224,10 +1338,10 @@ async function stageLinks(db, memories, embedFn, dryRun, llm, budget) {
1224
1338
  /**
1225
1339
  * Classify the relationship between two memories.
1226
1340
  *
1227
- * TWO-LABEL heuristic (2026-07). The 672-link audit (see the Stage 3 header)
1228
- * showed only `extends` (57% acceptable) and `relates_to` (53%) held up; the
1341
+ * TWO-LABEL heuristic. The link audit (see the Stage 3 header)
1342
+ * showed only `extends` and `relates_to` held up; the
1229
1343
  * emitted vocabulary is collapsed to exactly those two. The retired labels
1230
- * `updates` and `derives` (~31% acceptable) and all UPPERCASE LLM types are no
1344
+ * `updates` and `derives` (weak in the audit) and all UPPERCASE LLM types are no
1231
1345
  * longer produced. They remain in VALID_RELATIONSHIP_TYPES so pre-existing rows
1232
1346
  * still validate.
1233
1347
  *
@@ -1309,8 +1423,8 @@ function stageDecayPrune(db, dryRun) {
1309
1423
  * iterated once per new use — iteration is what makes the ceiling asymptotic
1310
1424
  * (a count-sized single shot would overshoot it).
1311
1425
  *
1312
- * The formula's S input is floored at PROMOTION_STRENGTH_FLOOR (#453 review,
1313
- * owner decision 2026-09-16): S^(−0.3) has a zero-singularity, and a writable
1426
+ * The formula's S input is floored at PROMOTION_STRENGTH_FLOOR (#453 review):
1427
+ * S^(−0.3) has a zero-singularity, and a writable
1314
1428
  * base_strength of 0.0 would otherwise leap to the ceiling via Infinity→clamp
1315
1429
  * on a single access. The floor bounds the first boost at ≈+0.13; it clamps
1316
1430
  * the INPUT only — the stored 0.0 row is not rewritten, and the promoted
@@ -1622,9 +1736,31 @@ deadline,
1622
1736
  * reconsolidation verdicts/rewrites) selects per-pool — confidential work
1623
1737
  * goes here; when null, that work HOLDS/skips, never falls back to `llm`.
1624
1738
  * Optional so every pre-#332 caller (and corpora with no confidential
1625
- * rows) is byte-identical.
1739
+ * rows) is byte-identical. #642: the confidential SPACE keeps this exact
1740
+ * role — it is never routed through spaceClients.
1741
+ */
1742
+ confidentialLlm,
1743
+ /**
1744
+ * #642 AC-9: per-space clients — every configured space except
1745
+ * 'confidential' (resolveLlmPair/buildSpaceLlms). Every pool-aware stage
1746
+ * above selects per space; a space with a null entry HOLDS its work
1747
+ * (skipped_spaces / held_spaces report fields), never falls back to `llm`.
1748
+ * Default empty = the pre-#642 two-pool run.
1749
+ */
1750
+ spaceClients,
1751
+ /**
1752
+ * #642: their per-space endpoint configs. No consolidation stage reads a
1753
+ * config today (the drain's per-endpoint chunk-size cache is the consumer);
1754
+ * the field rides here so the nightly threads ONE resolved bundle through
1755
+ * both calls.
1756
+ */
1757
+ spaceConfigs,
1758
+ /**
1759
+ * #642: the resolved SpaceDef list (config order) — reflection cohort
1760
+ * order, each space's privacyLine, and the importance batch order. Default
1761
+ * [] = the pre-#642 two-pool shape.
1626
1762
  */
1627
- confidentialLlm) {
1763
+ spaces) {
1628
1764
  const start = new Date();
1629
1765
  const report = {
1630
1766
  started_at: start.toISOString(),
@@ -1742,7 +1878,7 @@ confidentialLlm) {
1742
1878
  .map((r) => r.id))
1743
1879
  : new Set();
1744
1880
  const settleCandidates = scoreMemories.filter((m) => !paidGainIds.has(m.id));
1745
- report.stages.importance = await stageImportance(db, settleCandidates, llm, budget, dryRun, deadline, scoreMemories.length - settleCandidates.length, confidentialLlm);
1881
+ report.stages.importance = await stageImportance(db, settleCandidates, llm, budget, dryRun, deadline, scoreMemories.length - settleCandidates.length, confidentialLlm, spaceClients, spaces && spaces.length > 0 ? spaces.map((s) => s.id) : undefined);
1746
1882
  }
1747
1883
  // Stage 2.5: Reflection
1748
1884
  if (deadline?.hit("reflection")) {
@@ -1756,7 +1892,7 @@ confidentialLlm) {
1756
1892
  };
1757
1893
  }
1758
1894
  else {
1759
- report.stages.reflection = await stageReflection(db, precheck.newMemories, llm, budget, embedFn, dryRun, confidentialLlm);
1895
+ report.stages.reflection = await stageReflection(db, precheck.newMemories, llm, budget, embedFn, dryRun, confidentialLlm, spaceClients, spaces);
1760
1896
  }
1761
1897
  // Stage 2.7: Domain assignment.
1762
1898
  // Content-based (config-owned domains) REPLACES project grouping when a
@@ -1773,7 +1909,7 @@ confidentialLlm) {
1773
1909
  };
1774
1910
  }
1775
1911
  else {
1776
- report.stages.domain_curation = await stageContentDomains(db, cfgDomains, llm, budget, embedFn, dryRun, stateDir, domainOptions?.weakPrimaryFloor ?? nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline, confidentialLlm);
1912
+ report.stages.domain_curation = await stageContentDomains(db, cfgDomains, llm, budget, embedFn, dryRun, stateDir, domainOptions?.weakPrimaryFloor ?? nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline, confidentialLlm, spaceClients);
1777
1913
  }
1778
1914
  }
1779
1915
  else {
@@ -1788,12 +1924,12 @@ confidentialLlm) {
1788
1924
  // Stage 3.8: Reconsolidation (#384) — resolve corrections: rewrite
1789
1925
  // fact-shaped targets in place (absorbing transition-only triggers),
1790
1926
  // mark everything else. THE unified resolution stage since #392, and
1791
- // since #206-B (owner decision 6) also the ONLY true-update detector:
1927
+ // since #206-B (decision 6) also the ONLY true-update detector:
1792
1928
  // the standalone supersession stage (3.7) is retired into its
1793
1929
  // `supersedes` verdict action. Rides the same shared budget under its
1794
1930
  // own stage label + cursor.
1795
1931
  if (!deadline?.hit("reconsolidation")) {
1796
- report.stages.reconsolidation = await (0, reconsolidation_js_1.stageReconsolidation)(db, llm, budget, embedFn, dryRun, stateDir, { ...reconsolidationOptions, deadline, confidentialLlm });
1932
+ report.stages.reconsolidation = await (0, reconsolidation_js_1.stageReconsolidation)(db, llm, budget, embedFn, dryRun, stateDir, { ...reconsolidationOptions, deadline, confidentialLlm, spaceClients });
1797
1933
  }
1798
1934
  // Stage 4: Decay & Prune
1799
1935
  if (!deadline?.hit("decay_prune")) {