@gamaze/hicortex 0.26.3 → 0.27.1

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 (60) hide show
  1. package/README.md +21 -13
  2. package/assets/dashboard.html +95 -3
  3. package/dist/backfill-privacy.d.ts +109 -0
  4. package/dist/backfill-privacy.js +304 -0
  5. package/dist/capture.d.ts +60 -0
  6. package/dist/capture.js +90 -1
  7. package/dist/classification.d.ts +315 -0
  8. package/dist/classification.js +525 -0
  9. package/dist/classify-domains.js +24 -7
  10. package/dist/cli.js +80 -0
  11. package/dist/cluster.d.ts +15 -8
  12. package/dist/cluster.js +10 -3
  13. package/dist/confidential-marker.d.ts +103 -0
  14. package/dist/confidential-marker.js +285 -0
  15. package/dist/consolidate.d.ts +65 -5
  16. package/dist/consolidate.js +275 -48
  17. package/dist/dashboard.d.ts +32 -0
  18. package/dist/dashboard.js +33 -0
  19. package/dist/db.js +49 -1
  20. package/dist/dedup.d.ts +5 -3
  21. package/dist/dedup.js +26 -12
  22. package/dist/distill-queue.d.ts +34 -1
  23. package/dist/distill-queue.js +57 -10
  24. package/dist/graph.d.ts +28 -3
  25. package/dist/graph.js +46 -4
  26. package/dist/hermes-transcript-reader.js +5 -0
  27. package/dist/init.d.ts +18 -9
  28. package/dist/init.js +111 -81
  29. package/dist/marker-key-api.d.ts +79 -0
  30. package/dist/marker-key-api.js +96 -0
  31. package/dist/mcp-server.js +317 -32
  32. package/dist/nightly.js +36 -7
  33. package/dist/opencode-transcript-reader.js +3 -0
  34. package/dist/pi-transcript-reader.js +3 -0
  35. package/dist/prompts.d.ts +33 -1
  36. package/dist/prompts.js +37 -2
  37. package/dist/recall-index.d.ts +19 -9
  38. package/dist/recall-index.js +14 -4
  39. package/dist/recall-precision.js +3 -1
  40. package/dist/reconsolidation.d.ts +10 -0
  41. package/dist/reconsolidation.js +80 -17
  42. package/dist/redact.d.ts +9 -1
  43. package/dist/redact.js +32 -1
  44. package/dist/rescore-importance.js +21 -4
  45. package/dist/retrieval.d.ts +23 -6
  46. package/dist/retrieval.js +41 -15
  47. package/dist/seed-lesson.js +3 -1
  48. package/dist/storage.d.ts +23 -4
  49. package/dist/storage.js +43 -11
  50. package/dist/transcript-reader.d.ts +10 -0
  51. package/dist/transcript-reader.js +13 -0
  52. package/dist/type-classify.js +22 -7
  53. package/dist/types.d.ts +117 -15
  54. package/dist/uninstall.js +6 -5
  55. package/hermes-plugin/hicortex/README.md +4 -0
  56. package/hermes-plugin/hicortex/client.py +36 -9
  57. package/hermes-plugin/hicortex/plugin.yaml +1 -1
  58. package/hermes-plugin/hicortex/provider.py +28 -6
  59. package/package.json +1 -1
  60. package/server.json +2 -2
@@ -38,7 +38,7 @@ var __importStar = (this && this.__importStar) || (function () {
38
38
  };
39
39
  })();
40
40
  Object.defineProperty(exports, "__esModule", { value: true });
41
- exports.DEFAULT_MEMORY_SOFT_CAP = exports.BudgetTracker = exports.REFLECTION_CONTRADICTION_MIN_COSINE = exports.l2ToCosine = exports.CROSS_PROJECT_LINK_THRESHOLD = exports.CONSOLIDATE_LINK_TOP_K = exports.CONSOLIDATE_LINK_THRESHOLD = exports.DEFAULT_NIGHTLY_LLM_CALL_BUDGET = void 0;
41
+ exports.DEFAULT_MEMORY_SOFT_CAP = exports.BudgetTracker = exports.REFLECTION_CONTRADICTION_MIN_COSINE = exports.l2ToCosine = exports.CROSS_PROJECT_LINK_THRESHOLD = exports.CONSOLIDATE_LINK_FETCH_MAX_K = exports.CONSOLIDATE_LINK_FETCH_K = exports.CONSOLIDATE_LINK_TOP_K = exports.CONSOLIDATE_LINK_THRESHOLD = exports.DEFAULT_NIGHTLY_LLM_CALL_BUDGET = void 0;
42
42
  exports.resolveNightlyLlmCallBudget = resolveNightlyLlmCallBudget;
43
43
  exports.isContradictionCandidate = isContradictionCandidate;
44
44
  exports.warnUnmeteredTokensRun = warnUnmeteredTokensRun;
@@ -46,6 +46,7 @@ exports.isStaleTokenPeriod = isStaleTokenPeriod;
46
46
  exports.shouldThrottleTokens = shouldThrottleTokens;
47
47
  exports.parseJsonLenient = parseJsonLenient;
48
48
  exports.scoreMemoriesImportance = scoreMemoriesImportance;
49
+ exports.buildImportanceBatches = buildImportanceBatches;
49
50
  exports.rebuildContentModuleIndex = rebuildContentModuleIndex;
50
51
  exports.discoverLinkCandidates = discoverLinkCandidates;
51
52
  exports.classifyLinkCandidates = classifyLinkCandidates;
@@ -56,6 +57,7 @@ exports.stagePromotion = stagePromotion;
56
57
  exports.resolveMemorySoftCap = resolveMemorySoftCap;
57
58
  exports.stageMemoryCapEviction = stageMemoryCapEviction;
58
59
  exports.runConsolidation = runConsolidation;
60
+ const classification_js_1 = require("./classification.js");
59
61
  const retrieval_js_1 = require("./retrieval.js");
60
62
  const storage = __importStar(require("./storage.js"));
61
63
  const config_read_js_1 = require("./config-read.js");
@@ -118,6 +120,17 @@ const CONSOLIDATE_PRUNE_MIN_AGE_DAYS = 90;
118
120
  exports.CONSOLIDATE_LINK_THRESHOLD = 0.75;
119
121
  /** Max link candidates kept per memory (highest-cosine neighbors first). */
120
122
  exports.CONSOLIDATE_LINK_TOP_K = 3;
123
+ /**
124
+ * Initial vector window for link-candidate discovery (#602). The fetch is
125
+ * UNFILTERED by class (see CONSOLIDATE_LINK_FETCH_MAX_K for why), so this is
126
+ * just the starting width of the adaptive escalation below.
127
+ */
128
+ exports.CONSOLIDATE_LINK_FETCH_K = 10;
129
+ /**
130
+ * Hard cap on the escalated vector window (#602) — the same over-fetch cap
131
+ * #192 established for filtered recall queries.
132
+ */
133
+ exports.CONSOLIDATE_LINK_FETCH_MAX_K = 200;
121
134
  /**
122
135
  * Minimum COSINE similarity for a CROSS-PROJECT link candidate.
123
136
  *
@@ -387,16 +400,18 @@ function stagePrecheck(db, stateDir) {
387
400
  * endpoint answered, the answer was unusable).
388
401
  */
389
402
  async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
390
- const batchSize = 10;
391
403
  const budget = opts.budget;
392
404
  const deadline = opts.deadline;
393
405
  const dryRun = opts.dryRun ?? false;
394
406
  let scored = 0;
395
407
  let failed = 0;
396
408
  let skippedBudget = 0;
397
- for (let i = 0; i < memories.length; i += batchSize) {
409
+ let skippedConfidential = 0;
410
+ let remaining = memories.length;
411
+ const pair = { standard: llm, confidential: opts.confidentialLlm ?? null };
412
+ for (const batch of buildImportanceBatches(memories, 10)) {
398
413
  if (budget?.exhausted) {
399
- skippedBudget += memories.length - i;
414
+ skippedBudget += remaining;
400
415
  break;
401
416
  }
402
417
  // #405: the run deadline bounds the batch loop too — a large unscored
@@ -404,29 +419,39 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
404
419
  // Same stage label as the boundary check, so the defer log fires once.
405
420
  if (deadline?.hit("importance"))
406
421
  break;
407
- const batch = memories.slice(i, i + batchSize);
408
- const lines = batch.map((mem, idx) => `[${idx}] ${mem.content.slice(0, 500)}`);
422
+ const lines = batch.memories.map((mem, idx) => `[${idx}] ${mem.content.slice(0, 500)}`);
409
423
  const memoriesBlock = lines.join("\n\n");
410
424
  const prompt = (0, prompts_js_1.importanceScoring)(memoriesBlock);
411
- if (dryRun)
425
+ if (dryRun) {
426
+ remaining -= batch.memories.length;
412
427
  continue;
428
+ }
429
+ // #332 per-pool selection: the confidential pool needs its client —
430
+ // absent ⇒ skip-and-hold (rows stay unscored; retried next run).
431
+ const batchLlm = (0, classification_js_1.clientForPool)(pair, batch.pool);
432
+ if (!batchLlm) {
433
+ skippedConfidential += batch.memories.length;
434
+ remaining -= batch.memories.length;
435
+ continue;
436
+ }
413
437
  if (budget && !budget.use("importance")) {
414
- skippedBudget += memories.length - i;
438
+ skippedBudget += remaining;
415
439
  break;
416
440
  }
417
441
  try {
418
- const r = await llm.complete(prompt);
442
+ const r = await batchLlm.complete(prompt);
419
443
  budget?.recordUsage("importance", r.usage);
420
444
  let scores = parseJsonLenient(r.text, null);
421
445
  if (!Array.isArray(scores)) {
422
- scores = new Array(batch.length).fill(0.5);
446
+ scores = new Array(batch.memories.length).fill(0.5);
423
447
  }
424
- while (scores.length < batch.length)
448
+ while (scores.length < batch.memories.length)
425
449
  scores.push(0.5);
426
- scores = scores.slice(0, batch.length);
450
+ scores = scores.slice(0, batch.memories.length);
451
+ remaining -= batch.memories.length;
427
452
  let batchWritten = 0;
428
453
  let batchFailed = 0;
429
- for (let j = 0; j < batch.length; j++) {
454
+ for (let j = 0; j < batch.memories.length; j++) {
430
455
  let scoreVal = 0.5;
431
456
  try {
432
457
  scoreVal = Math.max(0, Math.min(1, Number(scores[j])));
@@ -443,7 +468,7 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
443
468
  // re-rolled genuinely-0.5 rows every night).
444
469
  scoreVal = Math.min(scoreVal, CALIBRATION.IMPORTANCE_CEILING);
445
470
  try {
446
- storage.updateMemory(db, batch[j].id, {
471
+ storage.updateMemory(db, batch.memories[j].id, {
447
472
  base_strength: scoreVal,
448
473
  importance_scored_at: new Date().toISOString(),
449
474
  });
@@ -458,53 +483,118 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
458
483
  opts.onBatch?.(batchWritten, batchFailed);
459
484
  }
460
485
  catch {
461
- failed += batch.length;
462
- opts.onBatch?.(0, batch.length);
486
+ failed += batch.memories.length;
487
+ opts.onBatch?.(0, batch.memories.length);
488
+ }
489
+ }
490
+ // #602: the held count previously landed ONLY in the return value — a
491
+ // confidential pool silently unscored for weeks was invisible in
492
+ // nightly.log. ONE aggregate warn (not one per batch), mirroring
493
+ // stageReflection's held line below. Dry runs never reach the skip branch
494
+ // (they continue before client resolution), so no warn fires on dryRun.
495
+ if (skippedConfidential > 0) {
496
+ console.warn(`[hicortex] importance: ${skippedConfidential} confidential memories held — ` +
497
+ `no confidential model configured (llmConfidentialBaseUrl/ApiKey). Retried next run.`);
498
+ }
499
+ return {
500
+ scored,
501
+ failed,
502
+ skipped_budget: skippedBudget,
503
+ ...(skippedConfidential > 0 ? { skipped_confidential: skippedConfidential } : {}),
504
+ };
505
+ }
506
+ /**
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.
511
+ */
512
+ function buildImportanceBatches(memories, batchSize = 10) {
513
+ const byPool = new Map();
514
+ for (const mem of memories) {
515
+ const pool = mem.privacy === "confidential" ? "confidential" : "standard";
516
+ const list = byPool.get(pool);
517
+ if (list)
518
+ list.push(mem);
519
+ else
520
+ byPool.set(pool, [mem]);
521
+ }
522
+ // Standard pool first (arrival order), then confidential — a stable,
523
+ // greppable order.
524
+ const out = [];
525
+ for (const pool of ["standard", "confidential"]) {
526
+ const list = byPool.get(pool);
527
+ if (!list)
528
+ continue;
529
+ for (let i = 0; i < list.length; i += batchSize) {
530
+ out.push({ pool, memories: list.slice(i, i + batchSize) });
463
531
  }
464
532
  }
465
- return { scored, failed, skipped_budget: skippedBudget };
533
+ return out;
466
534
  }
467
535
  async function stageImportance(db, memories, llm, budget, dryRun, deadline,
468
536
  /** #478: pool candidates the paid-gain guard dropped at the stage
469
537
  * boundary — reported, not scored, so the run's evidence shows the
470
538
  * promotion/enrichment gains that survived the nightly. */
471
- guardSkipped = 0) {
472
- const r = await scoreMemoriesImportance(db, memories, llm, { budget, deadline, dryRun });
539
+ guardSkipped = 0,
540
+ /** #332: the confidential-pool client (see scoreMemoriesImportance). */
541
+ confidentialLlm) {
542
+ const r = await scoreMemoriesImportance(db, memories, llm, { budget, deadline, dryRun, confidentialLlm });
473
543
  return { ...r, guard_skipped: guardSkipped };
474
544
  }
475
545
  // ---------------------------------------------------------------------------
476
546
  // Stage 2.5: Reflection
477
547
  // ---------------------------------------------------------------------------
478
- async function stageReflection(db, memories, llm, budget, embedFn, dryRun) {
479
- if (memories.length === 0) {
480
- return { lessons_generated: 0, skipped: true, reason: "no memories" };
548
+ /**
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).
555
+ */
556
+ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
557
+ if (cohort.length === 0) {
558
+ return { generated: 0, skipped: true, reason: "no memories" };
481
559
  }
482
560
  // Build summary
483
- const lines = memories.slice(0, 50).map((mem) => {
561
+ const lines = cohort.slice(0, 50).map((mem) => {
484
562
  const project = mem.project ?? "unknown";
485
563
  const agent = mem.source_agent ?? "unknown";
486
564
  const content = mem.content.slice(0, 300);
487
565
  return `[${project}] [${agent}] ${content}`;
488
566
  });
489
567
  const memoriesBlock = lines.join("\n\n");
490
- // Feed recent lessons to prevent duplicates and enable escalation
491
- const recentLessons = storage.getLessons(db, 7).slice(0, 10);
568
+ // 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.
572
+ const recentLessons = storage
573
+ .getLessons(db, 7, null, { includeConfidential: pool === "confidential" })
574
+ .slice(0, 10);
492
575
  const recentBlock = recentLessons.length > 0
493
576
  ? recentLessons.map(l => `- ${l.content.slice(0, 150)}`).join("\n")
494
577
  : undefined;
495
- const prompt = (0, prompts_js_1.reflection)(memoriesBlock, recentBlock);
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);
496
582
  if (dryRun) {
497
- return { lessons_generated: 0, skipped: false };
583
+ return { generated: 0, skipped: false };
498
584
  }
499
585
  if (!budget.use("reflection")) {
500
- return { lessons_generated: 0, skipped: true, reason: "budget_exhausted" };
586
+ return { generated: 0, skipped: true, reason: "budget_exhausted" };
501
587
  }
502
588
  try {
503
- const r = await llm.complete(prompt);
589
+ const r = await client.complete(prompt);
504
590
  budget.recordUsage("reflection", r.usage);
505
591
  const lessons = parseJsonLenient(r.text, []);
506
592
  if (!Array.isArray(lessons)) {
507
- return { lessons_generated: 0, failed: true };
593
+ // #602: this branch was silent — a pool could fail every night with
594
+ // nothing in nightly.log. All logging below sits after the dryRun
595
+ // early-return, so a dry run logs nothing by construction.
596
+ console.warn(`[hicortex] reflection (${pool} pool): LLM reply was not a JSON array — no lessons stored (retried next run)`);
597
+ return { generated: 0, failed: true };
508
598
  }
509
599
  let generated = 0;
510
600
  for (const lessonObj of lessons) {
@@ -543,14 +633,18 @@ async function stageReflection(db, memories, llm, budget, embedFn, dryRun) {
543
633
  // TRUE cosine > 0.80 (#145): the old `1 − n.distance > 0.80` sat on
544
634
  // the accidental 1−L2 scale and required cosine > 0.98 — the check
545
635
  // 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).
546
638
  const similarLessons = storage.vectorSearch(db, embedding, 3)
547
- .filter((n) => isContradictionCandidate(n.distance) && n.memory_type === "learnings");
639
+ .filter((n) => isContradictionCandidate(n.distance) &&
640
+ n.memory_type === "learnings" &&
641
+ (n.privacy === "confidential") === (pool === "confidential"));
548
642
  let contradicted = false;
549
643
  if (similarLessons.length > 0 && budget.use("contradiction_check")) {
550
644
  const existingText = similarLessons[0].content.slice(0, 300);
551
645
  const newText = content.slice(0, 300);
552
646
  try {
553
- const verdictR = await llm.complete(`Two lessons from an AI memory system. Do they CONTRADICT each other (opposite advice on the same topic)?\n\n` +
647
+ const verdictR = await client.complete(`Two lessons from an AI memory system. Do they CONTRADICT each other (opposite advice on the same topic)?\n\n` +
554
648
  `EXISTING: ${existingText}\n\nNEW: ${newText}\n\n` +
555
649
  `Answer ONLY "yes" or "no". If the new lesson updates/refines the existing one (not contradicts), answer "no".`);
556
650
  // Stage label "contradiction_check" matches the budget.use() call
@@ -573,19 +667,80 @@ async function stageReflection(db, memories, llm, budget, embedFn, dryRun) {
573
667
  project,
574
668
  memoryType: "learnings",
575
669
  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.
672
+ privacy: pool,
576
673
  });
577
674
  generated++;
578
675
  }
579
676
  }
580
- catch {
581
- // Failed to store lesson
677
+ catch (err) {
678
+ // #602: was silent — an embed/insert failure dropped the lesson with
679
+ // no trace. Tagged with the pool so the nightly log shows WHICH pool
680
+ // is losing lessons.
681
+ console.warn(`[hicortex] reflection (${pool} pool): failed to store a lesson (embed/insert error): ` +
682
+ `${lessonText.slice(0, 80)} — ${err instanceof Error ? err.message : String(err)}`);
582
683
  }
583
684
  }
584
- return { lessons_generated: generated, failed: false };
685
+ // #602: ONE per-pool success line so a healthy-empty (0 lessons from a
686
+ // clean cohort) is distinguishable from a broken run in nightly.log.
687
+ console.log(`[hicortex] reflection (${pool} pool): generated ${generated} lessons`);
688
+ return { generated, failed: false };
585
689
  }
586
690
  catch {
587
- return { lessons_generated: 0, failed: true };
691
+ // #602: was silent — the pool's whole run could fail (endpoint down,
692
+ // timeout) and nightly.log showed nothing but the report's failed flag.
693
+ console.warn(`[hicortex] reflection (${pool} pool): LLM call failed — no lessons generated (retried next run)`);
694
+ return { generated: 0, failed: true };
695
+ }
696
+ }
697
+ async function stageReflection(db, memories, llm, budget, embedFn, dryRun,
698
+ /** #332: the confidential-pool client; absent ⇒ the confidential cohort
699
+ * holds (skipped, no fallback to the main model). */
700
+ confidentialLlm) {
701
+ if (memories.length === 0) {
702
+ return { lessons_generated: 0, skipped: true, reason: "no memories" };
703
+ }
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");
709
+ let generated = 0;
710
+ let anyFailed = false;
711
+ let anySkipped = false;
712
+ let reason;
713
+ 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);
731
+ generated += r.generated;
732
+ anyFailed = anyFailed || r.failed === true;
733
+ anySkipped = anySkipped || r.skipped === true;
734
+ reason = reason ?? r.reason;
735
+ }
588
736
  }
737
+ return {
738
+ lessons_generated: generated,
739
+ ...(anyFailed ? { failed: true } : {}),
740
+ ...(anySkipped ? { skipped: true } : {}),
741
+ ...(reason ? { reason } : {}),
742
+ ...(confidentialSkipped ? { confidential_skipped: true } : {}),
743
+ };
589
744
  }
590
745
  // ---------------------------------------------------------------------------
591
746
  // Stage 2.7a: Content-based Domain Classification (config-owned domains)
@@ -635,7 +790,10 @@ function rebuildContentModuleIndex(db, domains, stateDir) {
635
790
  (0, state_js_1.updateState)((s) => { s.moduleIndex = moduleIndex; }, stateDir);
636
791
  return { domains: moduleDomains.length };
637
792
  }
638
- async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, stateDir, weakPrimaryFloor = nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline) {
793
+ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, stateDir, weakPrimaryFloor = nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline,
794
+ /** #332: the confidential-pool client — classification calls pick the
795
+ * client matching EACH memory's stamp (AC-10 second half). */
796
+ confidentialLlm) {
639
797
  // Rows needing (re)classification:
640
798
  // - domain IS NULL (never classified), OR
641
799
  // - domain NOT IN the current vocabulary (a rename/removal re-files), OR
@@ -648,7 +806,7 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
648
806
  // group so SQL precedence cannot let an OR arm absorb it.
649
807
  const placeholders = domains.map(() => "?").join(", ");
650
808
  const rows = db
651
- .prepare(`SELECT id, content, project FROM memories
809
+ .prepare(`SELECT id, content, project, privacy FROM memories
652
810
  WHERE COALESCE(status, '') != 'absorbed'
653
811
  AND (domain IS NULL
654
812
  OR domain NOT IN (${placeholders})
@@ -661,6 +819,8 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
661
819
  let classified = 0;
662
820
  let weakPrimary = 0;
663
821
  let noAssociationDecayed = 0;
822
+ let heldConfidential = 0;
823
+ const pair = { standard: llm, confidential: confidentialLlm ?? null };
664
824
  if (rows.length > 0) {
665
825
  // Prototypes at run start — newly classified memories get their weights
666
826
  // from the CURRENT prototypes (the post-classification recompute below
@@ -676,13 +836,22 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
676
836
  console.warn(`[hicortex] content-domain: budget exhausted after ${classified} classified`);
677
837
  break;
678
838
  }
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");
844
+ if (!rowLlm) {
845
+ heldConfidential++;
846
+ continue;
847
+ }
679
848
  // classifyMemoryTags returns null ONLY on infra error (throws after retry) —
680
849
  // skip that memory, leaving domain/tags/strength untouched so a later
681
850
  // run retries it (issue #150: never file or decay on infra errors).
682
851
  // The onUsage callback (#246) wires the metered call's token accounting
683
852
  // into this stage's BudgetTracker slot — same stage label the budget.use
684
853
  // call above uses, so call count + tokens stay aligned.
685
- const result = await (0, domain_classify_js_1.classifyMemoryTags)(row.content, row.project, domains, llm, (u) => budget.recordUsage("content_domain", u));
854
+ const result = await (0, domain_classify_js_1.classifyMemoryTags)(row.content, row.project, domains, rowLlm, (u) => budget.recordUsage("content_domain", u));
686
855
  if (result === null) {
687
856
  console.warn(`[hicortex] content-domain: infra error classifying ${row.id} — skipped (will retry)`);
688
857
  continue;
@@ -719,6 +888,10 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
719
888
  const { updated: primariesUpdated } = (0, schema_prototypes_js_1.refreshPrimaries)(db, domains);
720
889
  const seeded = stats.filter((s) => s.seeded).length;
721
890
  const { domains: domainCount } = rebuildContentModuleIndex(db, domains, stateDir);
891
+ if (heldConfidential > 0) {
892
+ console.warn(`[hicortex] content-domain: ${heldConfidential} confidential row(s) held — ` +
893
+ `no confidential model configured; they retry next run`);
894
+ }
722
895
  console.log(`[hicortex] Graded tags: ${classified} classified, ${weakPrimary} weak-primary, ` +
723
896
  `${noAssociationDecayed} no-association decayed, ${prototypes.size} prototypes ` +
724
897
  `(${seeded} description-seeded), ${weightsRecomputed} weights recomputed, ` +
@@ -732,6 +905,7 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
732
905
  primaries_updated: primariesUpdated,
733
906
  weak_primary: weakPrimary,
734
907
  no_association_decayed: noAssociationDecayed,
908
+ ...(heldConfidential > 0 ? { held_confidential: heldConfidential } : {}),
735
909
  ...(rows.length === 0 ? { reason: "nothing_stale" } : {}),
736
910
  };
737
911
  }
@@ -903,15 +1077,55 @@ async function stageDomainCuration(db, llm, budget, dryRun, stateDir) {
903
1077
  }
904
1078
  /**
905
1079
  * Discovery: find link candidates for one memory given its embedding.
906
- * Top-10 vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
907
- * highest-cosine neighbors above CONSOLIDATE_LINK_THRESHOLD, pre-compute the
908
- * heuristic relationship type.
1080
+ * Vector neighbors (excluding self), keep the CONSOLIDATE_LINK_TOP_K
1081
+ * highest-cosine SAME-CLASS neighbors above CONSOLIDATE_LINK_THRESHOLD,
1082
+ * pre-compute the heuristic relationship type.
1083
+ *
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
1086
+ * loop — the #192 filtered-over-fetch defect class. Starvation math: in a
1087
+ * 22K-standard / 1K-confidential corpus a confidential memory's 10 nearest
1088
+ * neighbors are usually ALL standard (the classes are topically distinct but
1089
+ * the majority class is 22× larger), so the confidential pool systematically
1090
+ * under-linked — its same-class neighbors never made the window. The fix
1091
+ * escalates the window (k × 4 per step, capped at CONSOLIDATE_LINK_FETCH_MAX_K
1092
+ * = the #192 over-fetch cap) until the window holds CONSOLIDATE_LINK_TOP_K
1093
+ * same-class neighbors, comes back short (no more rows may exist), or hits
1094
+ * the cap. Balanced corpora do ZERO extra queries (the first window already
1095
+ * holds 3+ same-class neighbors).
1096
+ *
1097
+ * WHY the class is not denormalized into the vec0 table (a WHERE clause
1098
+ * would make this a one-fetch query): memory_vectors carries only id +
1099
+ * embedding, and privacy is MUTABLE post-insert (`hicortex backfill-privacy`
1100
+ * and REST /update can reclassify a row) — a vec0-side class column would go
1101
+ * stale the moment a row's class changed without a re-embed. The class is
1102
+ * read live from memories, so it can never disagree with the row.
909
1103
  *
910
1104
  * Shared between the nightly `stageLinks` (which embeds via embedFn) and
911
1105
  * `hicortex relink` (which reuses stored embeddings from memory_vectors).
912
1106
  */
913
1107
  function discoverLinkCandidates(db, mem, embedding) {
914
- const neighbors = storage.vectorSearch(db, embedding, 10, [mem.id]);
1108
+ // #332: class-pure link discovery — a candidate NEVER crosses the circle
1109
+ // (no memory_links row joins the two classes; a pre-#332 cross-class link
1110
+ // stays as historical data, but the stage creates none). NULL privacy (a
1111
+ // pre-v27 row) reads standard, the same normalization everywhere else uses.
1112
+ const memClass = mem.privacy === "confidential" ? "confidential" : "standard";
1113
+ const isSameClass = (m) => (m.privacy === "confidential" ? "confidential" : "standard") === memClass;
1114
+ // The excluded self (distance 0 — always the nearest stored row) occupies
1115
+ // one seat of the raw window, so each fetch asks for k + 1: a FULL window
1116
+ // then yields exactly k non-self neighbors and `neighbors.length === k`
1117
+ // means "more rows may exist beyond it".
1118
+ const fetchWindow = (k) => storage.vectorSearch(db, embedding, k + 1, [mem.id]);
1119
+ // #602 adaptive escalation: widen while the window starves the memory's
1120
+ // own class AND the corpus may hold more rows beyond it.
1121
+ let k = exports.CONSOLIDATE_LINK_FETCH_K;
1122
+ let neighbors = fetchWindow(k);
1123
+ while (neighbors.filter(isSameClass).length < exports.CONSOLIDATE_LINK_TOP_K &&
1124
+ neighbors.length === k &&
1125
+ k < exports.CONSOLIDATE_LINK_FETCH_MAX_K) {
1126
+ k = Math.min(k * 4, exports.CONSOLIDATE_LINK_FETCH_MAX_K);
1127
+ neighbors = fetchWindow(k);
1128
+ }
915
1129
  const candidates = [];
916
1130
  // vectorSearch orders by L2 distance ascending (`ORDER BY distance` in
917
1131
  // storage.ts), and cosine is monotonically decreasing in L2 distance for
@@ -920,6 +1134,10 @@ function discoverLinkCandidates(db, mem, embedding) {
920
1134
  for (const neighbor of neighbors) {
921
1135
  if (candidates.length >= exports.CONSOLIDATE_LINK_TOP_K)
922
1136
  break;
1137
+ // The in-loop class filter stays: it enforces purity (#332) and top-K
1138
+ // cosine order regardless of how wide the escalated window got (#602).
1139
+ if (!isSameClass(neighbor))
1140
+ continue;
923
1141
  // sqlite-vec vec0 `distance` is L2, not a similarity. Embeddings are
924
1142
  // L2-normalized (embedder.ts, normalize: true), so cos = 1 − d²/2.
925
1143
  // The old `1 − distance` formula silently required cosine > 0.90.
@@ -1396,7 +1614,16 @@ reconsolidationOptions,
1396
1614
  * the report status becomes "deferred" — which keeps lastConsolidated
1397
1615
  * un-advanced so the next run re-finds the pending work.
1398
1616
  */
1399
- deadline) {
1617
+ deadline,
1618
+ /**
1619
+ * #332: the CONFIDENTIAL model client. Every stage that can touch
1620
+ * confidential text (importance batches, reflection, domain classification,
1621
+ * reconsolidation verdicts/rewrites) selects per-pool — confidential work
1622
+ * goes here; when null, that work HOLDS/skips, never falls back to `llm`.
1623
+ * Optional so every pre-#332 caller (and corpora with no confidential
1624
+ * rows) is byte-identical.
1625
+ */
1626
+ confidentialLlm) {
1400
1627
  const start = new Date();
1401
1628
  const report = {
1402
1629
  started_at: start.toISOString(),
@@ -1514,7 +1741,7 @@ deadline) {
1514
1741
  .map((r) => r.id))
1515
1742
  : new Set();
1516
1743
  const settleCandidates = scoreMemories.filter((m) => !paidGainIds.has(m.id));
1517
- report.stages.importance = await stageImportance(db, settleCandidates, llm, budget, dryRun, deadline, scoreMemories.length - settleCandidates.length);
1744
+ report.stages.importance = await stageImportance(db, settleCandidates, llm, budget, dryRun, deadline, scoreMemories.length - settleCandidates.length, confidentialLlm);
1518
1745
  }
1519
1746
  // Stage 2.5: Reflection
1520
1747
  if (deadline?.hit("reflection")) {
@@ -1528,7 +1755,7 @@ deadline) {
1528
1755
  };
1529
1756
  }
1530
1757
  else {
1531
- report.stages.reflection = await stageReflection(db, precheck.newMemories, llm, budget, embedFn, dryRun);
1758
+ report.stages.reflection = await stageReflection(db, precheck.newMemories, llm, budget, embedFn, dryRun, confidentialLlm);
1532
1759
  }
1533
1760
  // Stage 2.7: Domain assignment.
1534
1761
  // Content-based (config-owned domains) REPLACES project grouping when a
@@ -1545,7 +1772,7 @@ deadline) {
1545
1772
  };
1546
1773
  }
1547
1774
  else {
1548
- report.stages.domain_curation = await stageContentDomains(db, cfgDomains, llm, budget, embedFn, dryRun, stateDir, domainOptions?.weakPrimaryFloor ?? nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline);
1775
+ report.stages.domain_curation = await stageContentDomains(db, cfgDomains, llm, budget, embedFn, dryRun, stateDir, domainOptions?.weakPrimaryFloor ?? nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline, confidentialLlm);
1549
1776
  }
1550
1777
  }
1551
1778
  else {
@@ -1565,7 +1792,7 @@ deadline) {
1565
1792
  // `supersedes` verdict action. Rides the same shared budget under its
1566
1793
  // own stage label + cursor.
1567
1794
  if (!deadline?.hit("reconsolidation")) {
1568
- report.stages.reconsolidation = await (0, reconsolidation_js_1.stageReconsolidation)(db, llm, budget, embedFn, dryRun, stateDir, { ...reconsolidationOptions, deadline });
1795
+ report.stages.reconsolidation = await (0, reconsolidation_js_1.stageReconsolidation)(db, llm, budget, embedFn, dryRun, stateDir, { ...reconsolidationOptions, deadline, confidentialLlm });
1569
1796
  }
1570
1797
  // Stage 4: Decay & Prune
1571
1798
  if (!deadline?.hit("decay_prune")) {
@@ -177,6 +177,23 @@ export interface DashboardSnapshot {
177
177
  run_at: string;
178
178
  metrics: DashboardMetrics;
179
179
  }
180
+ /**
181
+ * #601 — the confidential circle's VISIBILITY block: which agents are
182
+ * inner-circle and, for the observed ones, how many confidential memories
183
+ * they carry. Purely informational (the dashboard is NOT gated — confidential
184
+ * content stays visible on the console by the standing ruling); the page
185
+ * renders amber pills on circle agents, nothing on standard ones.
186
+ */
187
+ export interface AgentCircle {
188
+ /** The sanitized roster (resolveConfidentialAgents — the one agent-id
189
+ * namespace shared with `?agent=` and identityAgents). */
190
+ roster: string[];
191
+ /** OBSERVED source_agent values (e.g. "hermes/nano") that match the
192
+ * roster, each mapped to that agent's confidential memory count.
193
+ * Membership is KEY PRESENCE (a rostered agent observed with 0
194
+ * confidential rows is a member at 0); NULL source_agent never matches. */
195
+ members: Record<string, number>;
196
+ }
180
197
  /** The /dashboard/data response — the full payload the page renders. */
181
198
  export interface DashboardData {
182
199
  /**
@@ -257,6 +274,9 @@ export interface DashboardData {
257
274
  * module doc for why recall traffic can never attribute). ALWAYS present;
258
275
  * empty arrays when nothing is recorded (fresh install). The page degrades
259
276
  * to the phase-2 rendering when the block is absent (pre-phase-3 server).
277
+ * #601 adds `circle` — the confidential-circle visibility block (roster +
278
+ * observed members with counts), also always present; the page degrades to
279
+ * the exact prior rendering when the key is absent (pre-#601 server).
260
280
  */
261
281
  fleet: {
262
282
  pauses: Array<{
@@ -270,6 +290,7 @@ export interface DashboardData {
270
290
  last_seen: string;
271
291
  last_outcome: string;
272
292
  }>;
293
+ circle: AgentCircle;
273
294
  };
274
295
  /**
275
296
  * #476 — the Memory Precision card: Level 1 (pushed-index precision
@@ -476,6 +497,17 @@ export declare function writeSnapshot(db: Database.Database, runAt: string, delt
476
497
  * so backfilled rows OMIT it (the page treats undefined as "no data").
477
498
  */
478
499
  export declare function backfillSnapshots(db: Database.Database): number;
500
+ /**
501
+ * #601 — compute fleet.circle: the sanitized roster plus the OBSERVED
502
+ * source_agent values that match it, each with its confidential memory count.
503
+ * Reuses the intake path's own decision core (resolveConfidentialAgents +
504
+ * isConfidentialSourceAgent from classification.ts — one id namespace, one
505
+ * match rule; no second matcher to drift). One GROUP BY over memories:
506
+ * membership is observed-and-rostered (a rostered agent seen with only
507
+ * standard rows is a member at 0), the value is the confidential row count.
508
+ * Pure: takes a db + config, returns the block; no side effects.
509
+ */
510
+ export declare function readAgentCircle(db: Database.Database, config: Record<string, unknown> | null | undefined): AgentCircle;
479
511
  /**
480
512
  * The pure data handler for GET /dashboard/data. Reads query params
481
513
  * (`range`, `date`, `digestLimit`) off the request, returns the DashboardData