@gamaze/hicortex 0.26.2 → 0.27.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 (45) hide show
  1. package/README.md +7 -2
  2. package/assets/dashboard.html +1 -1
  3. package/dist/backfill-privacy.d.ts +82 -0
  4. package/dist/backfill-privacy.js +193 -0
  5. package/dist/classification.d.ts +153 -0
  6. package/dist/classification.js +265 -0
  7. package/dist/classify-domains.js +24 -7
  8. package/dist/cli.js +31 -0
  9. package/dist/cluster.d.ts +15 -8
  10. package/dist/cluster.js +10 -3
  11. package/dist/consolidate.d.ts +31 -2
  12. package/dist/consolidate.js +193 -40
  13. package/dist/db.js +26 -1
  14. package/dist/dedup.d.ts +5 -3
  15. package/dist/dedup.js +26 -12
  16. package/dist/distill-queue.d.ts +25 -1
  17. package/dist/distill-queue.js +47 -7
  18. package/dist/graph.d.ts +28 -3
  19. package/dist/graph.js +46 -4
  20. package/dist/init.d.ts +18 -9
  21. package/dist/init.js +111 -81
  22. package/dist/mcp-server.js +186 -32
  23. package/dist/nightly.js +33 -7
  24. package/dist/recall-index.d.ts +19 -9
  25. package/dist/recall-index.js +14 -4
  26. package/dist/recall-precision.js +3 -1
  27. package/dist/reconsolidation.d.ts +10 -0
  28. package/dist/reconsolidation.js +80 -17
  29. package/dist/redact.d.ts +9 -1
  30. package/dist/redact.js +32 -1
  31. package/dist/rescore-importance.js +21 -4
  32. package/dist/retrieval.d.ts +23 -6
  33. package/dist/retrieval.js +41 -15
  34. package/dist/seed-lesson.js +3 -1
  35. package/dist/storage.d.ts +23 -4
  36. package/dist/storage.js +38 -9
  37. package/dist/type-classify.js +22 -7
  38. package/dist/types.d.ts +81 -15
  39. package/dist/uninstall.js +6 -5
  40. package/hermes-plugin/hicortex/README.md +4 -0
  41. package/hermes-plugin/hicortex/client.py +36 -9
  42. package/hermes-plugin/hicortex/plugin.yaml +1 -1
  43. package/hermes-plugin/hicortex/provider.py +28 -6
  44. package/package.json +1 -1
  45. package/server.json +2 -2
@@ -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");
@@ -387,16 +389,18 @@ function stagePrecheck(db, stateDir) {
387
389
  * endpoint answered, the answer was unusable).
388
390
  */
389
391
  async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
390
- const batchSize = 10;
391
392
  const budget = opts.budget;
392
393
  const deadline = opts.deadline;
393
394
  const dryRun = opts.dryRun ?? false;
394
395
  let scored = 0;
395
396
  let failed = 0;
396
397
  let skippedBudget = 0;
397
- for (let i = 0; i < memories.length; i += batchSize) {
398
+ let skippedConfidential = 0;
399
+ let remaining = memories.length;
400
+ const pair = { standard: llm, confidential: opts.confidentialLlm ?? null };
401
+ for (const batch of buildImportanceBatches(memories, 10)) {
398
402
  if (budget?.exhausted) {
399
- skippedBudget += memories.length - i;
403
+ skippedBudget += remaining;
400
404
  break;
401
405
  }
402
406
  // #405: the run deadline bounds the batch loop too — a large unscored
@@ -404,29 +408,39 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
404
408
  // Same stage label as the boundary check, so the defer log fires once.
405
409
  if (deadline?.hit("importance"))
406
410
  break;
407
- const batch = memories.slice(i, i + batchSize);
408
- const lines = batch.map((mem, idx) => `[${idx}] ${mem.content.slice(0, 500)}`);
411
+ const lines = batch.memories.map((mem, idx) => `[${idx}] ${mem.content.slice(0, 500)}`);
409
412
  const memoriesBlock = lines.join("\n\n");
410
413
  const prompt = (0, prompts_js_1.importanceScoring)(memoriesBlock);
411
- if (dryRun)
414
+ if (dryRun) {
415
+ remaining -= batch.memories.length;
416
+ continue;
417
+ }
418
+ // #332 per-pool selection: the confidential pool needs its client —
419
+ // absent ⇒ skip-and-hold (rows stay unscored; retried next run).
420
+ const batchLlm = (0, classification_js_1.clientForPool)(pair, batch.pool);
421
+ if (!batchLlm) {
422
+ skippedConfidential += batch.memories.length;
423
+ remaining -= batch.memories.length;
412
424
  continue;
425
+ }
413
426
  if (budget && !budget.use("importance")) {
414
- skippedBudget += memories.length - i;
427
+ skippedBudget += remaining;
415
428
  break;
416
429
  }
417
430
  try {
418
- const r = await llm.complete(prompt);
431
+ const r = await batchLlm.complete(prompt);
419
432
  budget?.recordUsage("importance", r.usage);
420
433
  let scores = parseJsonLenient(r.text, null);
421
434
  if (!Array.isArray(scores)) {
422
- scores = new Array(batch.length).fill(0.5);
435
+ scores = new Array(batch.memories.length).fill(0.5);
423
436
  }
424
- while (scores.length < batch.length)
437
+ while (scores.length < batch.memories.length)
425
438
  scores.push(0.5);
426
- scores = scores.slice(0, batch.length);
439
+ scores = scores.slice(0, batch.memories.length);
440
+ remaining -= batch.memories.length;
427
441
  let batchWritten = 0;
428
442
  let batchFailed = 0;
429
- for (let j = 0; j < batch.length; j++) {
443
+ for (let j = 0; j < batch.memories.length; j++) {
430
444
  let scoreVal = 0.5;
431
445
  try {
432
446
  scoreVal = Math.max(0, Math.min(1, Number(scores[j])));
@@ -443,7 +457,7 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
443
457
  // re-rolled genuinely-0.5 rows every night).
444
458
  scoreVal = Math.min(scoreVal, CALIBRATION.IMPORTANCE_CEILING);
445
459
  try {
446
- storage.updateMemory(db, batch[j].id, {
460
+ storage.updateMemory(db, batch.memories[j].id, {
447
461
  base_strength: scoreVal,
448
462
  importance_scored_at: new Date().toISOString(),
449
463
  });
@@ -458,53 +472,102 @@ async function scoreMemoriesImportance(db, memories, llm, opts = {}) {
458
472
  opts.onBatch?.(batchWritten, batchFailed);
459
473
  }
460
474
  catch {
461
- failed += batch.length;
462
- opts.onBatch?.(0, batch.length);
475
+ failed += batch.memories.length;
476
+ opts.onBatch?.(0, batch.memories.length);
477
+ }
478
+ }
479
+ return {
480
+ scored,
481
+ failed,
482
+ skipped_budget: skippedBudget,
483
+ ...(skippedConfidential > 0 ? { skipped_confidential: skippedConfidential } : {}),
484
+ };
485
+ }
486
+ /**
487
+ * #332 — the importance batch builder: partition by classification, then
488
+ * slice into batches. Every batch is SINGLE-CLASS by construction (AC-10),
489
+ * so the scoring call site can route each batch to the client matching its
490
+ * pool with no per-item checks. Exported for the unit test.
491
+ */
492
+ function buildImportanceBatches(memories, batchSize = 10) {
493
+ const byPool = new Map();
494
+ for (const mem of memories) {
495
+ const pool = mem.privacy === "confidential" ? "confidential" : "standard";
496
+ const list = byPool.get(pool);
497
+ if (list)
498
+ list.push(mem);
499
+ else
500
+ byPool.set(pool, [mem]);
501
+ }
502
+ // Standard pool first (arrival order), then confidential — a stable,
503
+ // greppable order.
504
+ const out = [];
505
+ for (const pool of ["standard", "confidential"]) {
506
+ const list = byPool.get(pool);
507
+ if (!list)
508
+ continue;
509
+ for (let i = 0; i < list.length; i += batchSize) {
510
+ out.push({ pool, memories: list.slice(i, i + batchSize) });
463
511
  }
464
512
  }
465
- return { scored, failed, skipped_budget: skippedBudget };
513
+ return out;
466
514
  }
467
515
  async function stageImportance(db, memories, llm, budget, dryRun, deadline,
468
516
  /** #478: pool candidates the paid-gain guard dropped at the stage
469
517
  * boundary — reported, not scored, so the run's evidence shows the
470
518
  * promotion/enrichment gains that survived the nightly. */
471
- guardSkipped = 0) {
472
- const r = await scoreMemoriesImportance(db, memories, llm, { budget, deadline, dryRun });
519
+ guardSkipped = 0,
520
+ /** #332: the confidential-pool client (see scoreMemoriesImportance). */
521
+ confidentialLlm) {
522
+ const r = await scoreMemoriesImportance(db, memories, llm, { budget, deadline, dryRun, confidentialLlm });
473
523
  return { ...r, guard_skipped: guardSkipped };
474
524
  }
475
525
  // ---------------------------------------------------------------------------
476
526
  // Stage 2.5: Reflection
477
527
  // ---------------------------------------------------------------------------
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" };
528
+ /**
529
+ * One reflection run over ONE class-pure cohort (#332). The cohort never
530
+ * mixes classes (the caller splits), the recent-lessons dedup block is
531
+ * class-scoped, the contradiction check only sees same-class lessons, and
532
+ * every generated lesson inherits the pool's stamp at insert. `client` is the
533
+ * client matching `pool` — the caller guarantees it (a confidential cohort
534
+ * without a client never reaches here; it holds instead).
535
+ */
536
+ async function reflectPool(db, cohort, pool, client, budget, embedFn, dryRun) {
537
+ if (cohort.length === 0) {
538
+ return { generated: 0, skipped: true, reason: "no memories" };
481
539
  }
482
540
  // Build summary
483
- const lines = memories.slice(0, 50).map((mem) => {
541
+ const lines = cohort.slice(0, 50).map((mem) => {
484
542
  const project = mem.project ?? "unknown";
485
543
  const agent = mem.source_agent ?? "unknown";
486
544
  const content = mem.content.slice(0, 300);
487
545
  return `[${project}] [${agent}] ${content}`;
488
546
  });
489
547
  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);
548
+ // Feed recent lessons to prevent duplicates and enable escalation.
549
+ // #332: the dedup block is CLASS-SCOPED — a confidential run's prompt must
550
+ // not quote standard lessons (and vice versa); the pool's own lessons are
551
+ // the coherent reference set.
552
+ const recentLessons = storage
553
+ .getLessons(db, 7, null, { includeConfidential: pool === "confidential" })
554
+ .slice(0, 10);
492
555
  const recentBlock = recentLessons.length > 0
493
556
  ? recentLessons.map(l => `- ${l.content.slice(0, 150)}`).join("\n")
494
557
  : undefined;
495
558
  const prompt = (0, prompts_js_1.reflection)(memoriesBlock, recentBlock);
496
559
  if (dryRun) {
497
- return { lessons_generated: 0, skipped: false };
560
+ return { generated: 0, skipped: false };
498
561
  }
499
562
  if (!budget.use("reflection")) {
500
- return { lessons_generated: 0, skipped: true, reason: "budget_exhausted" };
563
+ return { generated: 0, skipped: true, reason: "budget_exhausted" };
501
564
  }
502
565
  try {
503
- const r = await llm.complete(prompt);
566
+ const r = await client.complete(prompt);
504
567
  budget.recordUsage("reflection", r.usage);
505
568
  const lessons = parseJsonLenient(r.text, []);
506
569
  if (!Array.isArray(lessons)) {
507
- return { lessons_generated: 0, failed: true };
570
+ return { generated: 0, failed: true };
508
571
  }
509
572
  let generated = 0;
510
573
  for (const lessonObj of lessons) {
@@ -543,14 +606,18 @@ async function stageReflection(db, memories, llm, budget, embedFn, dryRun) {
543
606
  // TRUE cosine > 0.80 (#145): the old `1 − n.distance > 0.80` sat on
544
607
  // the accidental 1−L2 scale and required cosine > 0.98 — the check
545
608
  // effectively never fired. See isContradictionCandidate.
609
+ // #332: class-scoped — only SAME-POOL lessons enter the check (the
610
+ // vector search is unscoped; the filter narrows it).
546
611
  const similarLessons = storage.vectorSearch(db, embedding, 3)
547
- .filter((n) => isContradictionCandidate(n.distance) && n.memory_type === "learnings");
612
+ .filter((n) => isContradictionCandidate(n.distance) &&
613
+ n.memory_type === "learnings" &&
614
+ (n.privacy === "confidential") === (pool === "confidential"));
548
615
  let contradicted = false;
549
616
  if (similarLessons.length > 0 && budget.use("contradiction_check")) {
550
617
  const existingText = similarLessons[0].content.slice(0, 300);
551
618
  const newText = content.slice(0, 300);
552
619
  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` +
620
+ 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
621
  `EXISTING: ${existingText}\n\nNEW: ${newText}\n\n` +
555
622
  `Answer ONLY "yes" or "no". If the new lesson updates/refines the existing one (not contradicts), answer "no".`);
556
623
  // Stage label "contradiction_check" matches the budget.use() call
@@ -573,6 +640,9 @@ async function stageReflection(db, memories, llm, budget, embedFn, dryRun) {
573
640
  project,
574
641
  memoryType: "learnings",
575
642
  baseStrength: baseStrength[severity] ?? 0.8,
643
+ // #332: lessons inherit their pool's stamp — the class is born
644
+ // with the cohort, never judged from content.
645
+ privacy: pool,
576
646
  });
577
647
  generated++;
578
648
  }
@@ -581,12 +651,60 @@ async function stageReflection(db, memories, llm, budget, embedFn, dryRun) {
581
651
  // Failed to store lesson
582
652
  }
583
653
  }
584
- return { lessons_generated: generated, failed: false };
654
+ return { generated, failed: false };
585
655
  }
586
656
  catch {
587
- return { lessons_generated: 0, failed: true };
657
+ return { generated: 0, failed: true };
588
658
  }
589
659
  }
660
+ async function stageReflection(db, memories, llm, budget, embedFn, dryRun,
661
+ /** #332: the confidential-pool client; absent ⇒ the confidential cohort
662
+ * holds (skipped, no fallback to the main model). */
663
+ confidentialLlm) {
664
+ if (memories.length === 0) {
665
+ return { lessons_generated: 0, skipped: true, reason: "no memories" };
666
+ }
667
+ // #332: split the watermark cohort by class — the pools NEVER mix in a
668
+ // reflection prompt (a mixed cohort would distill cross-class lessons with
669
+ // no honest stamp). Standard run unchanged on the main client.
670
+ const standardCohort = memories.filter((m) => m.privacy !== "confidential");
671
+ const confidentialCohort = memories.filter((m) => m.privacy === "confidential");
672
+ let generated = 0;
673
+ let anyFailed = false;
674
+ let anySkipped = false;
675
+ let reason;
676
+ let confidentialSkipped = false;
677
+ if (standardCohort.length > 0) {
678
+ const r = await reflectPool(db, standardCohort, "standard", llm, budget, embedFn, dryRun);
679
+ generated += r.generated;
680
+ anyFailed = anyFailed || r.failed === true;
681
+ anySkipped = anySkipped || r.skipped === true;
682
+ reason = reason ?? r.reason;
683
+ }
684
+ if (confidentialCohort.length > 0) {
685
+ if (!confidentialLlm) {
686
+ // Hold: the cohort is retried next run (it is the lastConsolidated
687
+ // watermark cohort — a held watermark re-finds it). Never the main model.
688
+ confidentialSkipped = true;
689
+ console.warn(`[hicortex] reflection: ${confidentialCohort.length} confidential memorie(s) held — ` +
690
+ `no confidential model configured (llmConfidentialBaseUrl/ApiKey). No lessons generated for the pool.`);
691
+ }
692
+ else {
693
+ const r = await reflectPool(db, confidentialCohort, "confidential", confidentialLlm, budget, embedFn, dryRun);
694
+ generated += r.generated;
695
+ anyFailed = anyFailed || r.failed === true;
696
+ anySkipped = anySkipped || r.skipped === true;
697
+ reason = reason ?? r.reason;
698
+ }
699
+ }
700
+ return {
701
+ lessons_generated: generated,
702
+ ...(anyFailed ? { failed: true } : {}),
703
+ ...(anySkipped ? { skipped: true } : {}),
704
+ ...(reason ? { reason } : {}),
705
+ ...(confidentialSkipped ? { confidential_skipped: true } : {}),
706
+ };
707
+ }
590
708
  // ---------------------------------------------------------------------------
591
709
  // Stage 2.7a: Content-based Domain Classification (config-owned domains)
592
710
  // ---------------------------------------------------------------------------
@@ -635,7 +753,10 @@ function rebuildContentModuleIndex(db, domains, stateDir) {
635
753
  (0, state_js_1.updateState)((s) => { s.moduleIndex = moduleIndex; }, stateDir);
636
754
  return { domains: moduleDomains.length };
637
755
  }
638
- async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, stateDir, weakPrimaryFloor = nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline) {
756
+ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, stateDir, weakPrimaryFloor = nofit_js_1.DEFAULT_WEAK_PRIMARY_FLOOR, deadline,
757
+ /** #332: the confidential-pool client — classification calls pick the
758
+ * client matching EACH memory's stamp (AC-10 second half). */
759
+ confidentialLlm) {
639
760
  // Rows needing (re)classification:
640
761
  // - domain IS NULL (never classified), OR
641
762
  // - domain NOT IN the current vocabulary (a rename/removal re-files), OR
@@ -648,7 +769,7 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
648
769
  // group so SQL precedence cannot let an OR arm absorb it.
649
770
  const placeholders = domains.map(() => "?").join(", ");
650
771
  const rows = db
651
- .prepare(`SELECT id, content, project FROM memories
772
+ .prepare(`SELECT id, content, project, privacy FROM memories
652
773
  WHERE COALESCE(status, '') != 'absorbed'
653
774
  AND (domain IS NULL
654
775
  OR domain NOT IN (${placeholders})
@@ -661,6 +782,8 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
661
782
  let classified = 0;
662
783
  let weakPrimary = 0;
663
784
  let noAssociationDecayed = 0;
785
+ let heldConfidential = 0;
786
+ const pair = { standard: llm, confidential: confidentialLlm ?? null };
664
787
  if (rows.length > 0) {
665
788
  // Prototypes at run start — newly classified memories get their weights
666
789
  // from the CURRENT prototypes (the post-classification recompute below
@@ -676,13 +799,22 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
676
799
  console.warn(`[hicortex] content-domain: budget exhausted after ${classified} classified`);
677
800
  break;
678
801
  }
802
+ // #332 per-row client selection: the classify call carries this row's
803
+ // CONTENT — a confidential row goes to the confidential client, and
804
+ // without one it is HELD (tags untouched, retried next run), never
805
+ // classified on the main model.
806
+ const rowLlm = (0, classification_js_1.clientForPool)(pair, row.privacy === "confidential" ? "confidential" : "standard");
807
+ if (!rowLlm) {
808
+ heldConfidential++;
809
+ continue;
810
+ }
679
811
  // classifyMemoryTags returns null ONLY on infra error (throws after retry) —
680
812
  // skip that memory, leaving domain/tags/strength untouched so a later
681
813
  // run retries it (issue #150: never file or decay on infra errors).
682
814
  // The onUsage callback (#246) wires the metered call's token accounting
683
815
  // into this stage's BudgetTracker slot — same stage label the budget.use
684
816
  // 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));
817
+ const result = await (0, domain_classify_js_1.classifyMemoryTags)(row.content, row.project, domains, rowLlm, (u) => budget.recordUsage("content_domain", u));
686
818
  if (result === null) {
687
819
  console.warn(`[hicortex] content-domain: infra error classifying ${row.id} — skipped (will retry)`);
688
820
  continue;
@@ -719,6 +851,10 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
719
851
  const { updated: primariesUpdated } = (0, schema_prototypes_js_1.refreshPrimaries)(db, domains);
720
852
  const seeded = stats.filter((s) => s.seeded).length;
721
853
  const { domains: domainCount } = rebuildContentModuleIndex(db, domains, stateDir);
854
+ if (heldConfidential > 0) {
855
+ console.warn(`[hicortex] content-domain: ${heldConfidential} confidential row(s) held — ` +
856
+ `no confidential model configured; they retry next run`);
857
+ }
722
858
  console.log(`[hicortex] Graded tags: ${classified} classified, ${weakPrimary} weak-primary, ` +
723
859
  `${noAssociationDecayed} no-association decayed, ${prototypes.size} prototypes ` +
724
860
  `(${seeded} description-seeded), ${weightsRecomputed} weights recomputed, ` +
@@ -732,6 +868,7 @@ async function stageContentDomains(db, domains, llm, budget, embedFn, dryRun, st
732
868
  primaries_updated: primariesUpdated,
733
869
  weak_primary: weakPrimary,
734
870
  no_association_decayed: noAssociationDecayed,
871
+ ...(heldConfidential > 0 ? { held_confidential: heldConfidential } : {}),
735
872
  ...(rows.length === 0 ? { reason: "nothing_stale" } : {}),
736
873
  };
737
874
  }
@@ -913,6 +1050,11 @@ async function stageDomainCuration(db, llm, budget, dryRun, stateDir) {
913
1050
  function discoverLinkCandidates(db, mem, embedding) {
914
1051
  const neighbors = storage.vectorSearch(db, embedding, 10, [mem.id]);
915
1052
  const candidates = [];
1053
+ // #332: class-pure link discovery — a candidate NEVER crosses the circle
1054
+ // (no memory_links row joins the two classes; a pre-#332 cross-class link
1055
+ // stays as historical data, but the stage creates none). NULL privacy (a
1056
+ // pre-v27 row) reads standard, the same normalization everywhere else uses.
1057
+ const memClass = mem.privacy === "confidential" ? "confidential" : "standard";
916
1058
  // vectorSearch orders by L2 distance ascending (`ORDER BY distance` in
917
1059
  // storage.ts), and cosine is monotonically decreasing in L2 distance for
918
1060
  // normalized vectors — so iterating in order and stopping at TOP_K keeps
@@ -920,6 +1062,8 @@ function discoverLinkCandidates(db, mem, embedding) {
920
1062
  for (const neighbor of neighbors) {
921
1063
  if (candidates.length >= exports.CONSOLIDATE_LINK_TOP_K)
922
1064
  break;
1065
+ if ((neighbor.privacy === "confidential" ? "confidential" : "standard") !== memClass)
1066
+ continue;
923
1067
  // sqlite-vec vec0 `distance` is L2, not a similarity. Embeddings are
924
1068
  // L2-normalized (embedder.ts, normalize: true), so cos = 1 − d²/2.
925
1069
  // The old `1 − distance` formula silently required cosine > 0.90.
@@ -1396,7 +1540,16 @@ reconsolidationOptions,
1396
1540
  * the report status becomes "deferred" — which keeps lastConsolidated
1397
1541
  * un-advanced so the next run re-finds the pending work.
1398
1542
  */
1399
- deadline) {
1543
+ deadline,
1544
+ /**
1545
+ * #332: the CONFIDENTIAL model client. Every stage that can touch
1546
+ * confidential text (importance batches, reflection, domain classification,
1547
+ * reconsolidation verdicts/rewrites) selects per-pool — confidential work
1548
+ * goes here; when null, that work HOLDS/skips, never falls back to `llm`.
1549
+ * Optional so every pre-#332 caller (and corpora with no confidential
1550
+ * rows) is byte-identical.
1551
+ */
1552
+ confidentialLlm) {
1400
1553
  const start = new Date();
1401
1554
  const report = {
1402
1555
  started_at: start.toISOString(),
@@ -1514,7 +1667,7 @@ deadline) {
1514
1667
  .map((r) => r.id))
1515
1668
  : new Set();
1516
1669
  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);
1670
+ report.stages.importance = await stageImportance(db, settleCandidates, llm, budget, dryRun, deadline, scoreMemories.length - settleCandidates.length, confidentialLlm);
1518
1671
  }
1519
1672
  // Stage 2.5: Reflection
1520
1673
  if (deadline?.hit("reflection")) {
@@ -1528,7 +1681,7 @@ deadline) {
1528
1681
  };
1529
1682
  }
1530
1683
  else {
1531
- report.stages.reflection = await stageReflection(db, precheck.newMemories, llm, budget, embedFn, dryRun);
1684
+ report.stages.reflection = await stageReflection(db, precheck.newMemories, llm, budget, embedFn, dryRun, confidentialLlm);
1532
1685
  }
1533
1686
  // Stage 2.7: Domain assignment.
1534
1687
  // Content-based (config-owned domains) REPLACES project grouping when a
@@ -1545,7 +1698,7 @@ deadline) {
1545
1698
  };
1546
1699
  }
1547
1700
  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);
1701
+ 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
1702
  }
1550
1703
  }
1551
1704
  else {
@@ -1565,7 +1718,7 @@ deadline) {
1565
1718
  // `supersedes` verdict action. Rides the same shared budget under its
1566
1719
  // own stage label + cursor.
1567
1720
  if (!deadline?.hit("reconsolidation")) {
1568
- report.stages.reconsolidation = await (0, reconsolidation_js_1.stageReconsolidation)(db, llm, budget, embedFn, dryRun, stateDir, { ...reconsolidationOptions, deadline });
1721
+ report.stages.reconsolidation = await (0, reconsolidation_js_1.stageReconsolidation)(db, llm, budget, embedFn, dryRun, stateDir, { ...reconsolidationOptions, deadline, confidentialLlm });
1569
1722
  }
1570
1723
  // Stage 4: Decay & Prune
1571
1724
  if (!deadline?.hit("decay_prune")) {
package/dist/db.js CHANGED
@@ -104,7 +104,11 @@ CREATE TABLE IF NOT EXISTS memories (
104
104
  source_agent TEXT DEFAULT 'default',
105
105
  source_session TEXT,
106
106
  project TEXT,
107
- privacy TEXT DEFAULT 'WORK',
107
+ -- #332: the two-level memory classification ('standard' | 'confidential').
108
+ -- Server-derived at intake from source_agent × the confidentialAgents
109
+ -- roster — never client-declared. The fresh-schema default flipped from the
110
+ -- pre-0.16 'WORK' (migration v27 maps every legacy value/NULL → standard).
111
+ privacy TEXT DEFAULT 'standard',
108
112
  memory_type TEXT DEFAULT 'experience',
109
113
  updated_at TIMESTAMP
110
114
  );
@@ -880,6 +884,27 @@ const MIGRATIONS = [
880
884
  db.exec("CREATE INDEX IF NOT EXISTS idx_recall_verdicts_push_memory ON recall_verdicts(push_id, memory_id)");
881
885
  },
882
886
  },
887
+ {
888
+ version: 27,
889
+ name: "privacy_standard",
890
+ up: (db) => {
891
+ // #332 — the privacy column becomes the two-level classification carrier
892
+ // ('standard' | 'confidential'). Production rows carry BOTH legacy
893
+ // populations: 'WORK' (the pre-0.16 schema default) and NULL (modern
894
+ // inserts, which passed `privacy ?? null`). Both map to 'standard' — the
895
+ // fail-closed default class; 'confidential' only ever exists once the
896
+ // server derives it at intake (source_agent × the confidentialAgents
897
+ // roster) or the operator backfills it. Any other legacy value ('',
898
+ // 'PERSONAL', …) maps the same way. The distill_queue rows are normalized
899
+ // with the SAME predicate so a pre-upgrade queued segment distills with
900
+ // the same stamp the migration just gave its already-stored siblings.
901
+ // Idempotent: re-running rewrites the same 'standard' onto the same rows.
902
+ db.exec(`UPDATE memories SET privacy = 'standard'
903
+ WHERE privacy IS NULL OR privacy NOT IN ('standard', 'confidential')`);
904
+ db.exec(`UPDATE distill_queue SET privacy = 'standard'
905
+ WHERE privacy IS NULL OR privacy NOT IN ('standard', 'confidential')`);
906
+ },
907
+ },
883
908
  ];
884
909
  /**
885
910
  * Run all pending migrations against the database.
package/dist/dedup.d.ts CHANGED
@@ -223,7 +223,7 @@ export type MergeMemoryIdsResult = {
223
223
  linksRepointed: number;
224
224
  } | {
225
225
  ok: false;
226
- reason: "project_mismatch" | "conflict_linked" | "no_members";
226
+ reason: "project_mismatch" | "classification_mismatch" | "conflict_linked" | "no_members";
227
227
  };
228
228
  /**
229
229
  * Merge an explicit set of memories (the judged-pair phase of #392: the
@@ -231,8 +231,10 @@ export type MergeMemoryIdsResult = {
231
231
  * through THIS function so the merge math stays single-definition). Loads the
232
232
  * LIVE rows at apply time — members that vanished or were absorbed between
233
233
  * verdict and apply are dropped defensively; a project disagreement refuses
234
- * the merge (both memories stay live — the only metadata rail left, #206
235
- * decision 2); a conflicts-linked pair refuses it exactly the same way
234
+ * the merge (both memories stay live — the #206 metadata rail); a
235
+ * CLASSIFICATION disagreement refuses it the same way (#332: the pools never
236
+ * cross — a confidential row never blends into a standard canonical or vice
237
+ * versa); a conflicts-linked pair refuses it exactly the same way
236
238
  * (#393 guard-C). One transaction for the whole set.
237
239
  */
238
240
  export declare function mergeMemoryIds(db: Database.Database, ids: string[]): MergeMemoryIdsResult;
package/dist/dedup.js CHANGED
@@ -287,9 +287,12 @@ function planDedup(db, threshold) {
287
287
  continue;
288
288
  }
289
289
  const mismatch = (0, cluster_js_1.clusterMetadataMismatch)(members);
290
- // #206 decision 2: project is the ONLY rail — the source_agent rail was
291
- // removed (cross-agent clusters merge; the skip reason is project_mismatch).
292
- if (mismatch.projectMismatch) {
290
+ // #206 decision 2: the source_agent rail was removed (cross-agent
291
+ // clusters merge). Project stayed the only METADATA rail until #332 added
292
+ // the classification rail — a cluster mixing standard and confidential
293
+ // rows is skipped, never blended (either skip reason keeps every member
294
+ // live; the pair re-detects structurally).
295
+ if (mismatch.projectMismatch || mismatch.classificationMismatch) {
293
296
  mismatchSkipped.push({ size: members.length, memberIds: members.map((m) => m.id), mismatch });
294
297
  continue;
295
298
  }
@@ -392,8 +395,10 @@ function mergeCluster(db, canonical, losers, injectFailure) {
392
395
  * through THIS function so the merge math stays single-definition). Loads the
393
396
  * LIVE rows at apply time — members that vanished or were absorbed between
394
397
  * verdict and apply are dropped defensively; a project disagreement refuses
395
- * the merge (both memories stay live — the only metadata rail left, #206
396
- * decision 2); a conflicts-linked pair refuses it exactly the same way
398
+ * the merge (both memories stay live — the #206 metadata rail); a
399
+ * CLASSIFICATION disagreement refuses it the same way (#332: the pools never
400
+ * cross — a confidential row never blends into a standard canonical or vice
401
+ * versa); a conflicts-linked pair refuses it exactly the same way
397
402
  * (#393 guard-C). One transaction for the whole set.
398
403
  */
399
404
  function mergeMemoryIds(db, ids) {
@@ -411,6 +416,9 @@ function mergeMemoryIds(db, ids) {
411
416
  if (mismatch.projectMismatch) {
412
417
  return { ok: false, reason: "project_mismatch" };
413
418
  }
419
+ if (mismatch.classificationMismatch) {
420
+ return { ok: false, reason: "classification_mismatch" };
421
+ }
414
422
  const { canonical, losers } = pickCanonical(members);
415
423
  const tx = db.transaction(() => mergeCluster(db, canonical, losers));
416
424
  const plan = tx();
@@ -471,7 +479,10 @@ async function runDeterministicMergeZone(db, opts = {}) {
471
479
  merged_clusters: 0,
472
480
  losers_merged: 0,
473
481
  links_repointed: 0,
474
- skipped_project_mismatch: plan.mismatchSkipped.length,
482
+ // #332: mismatch skips split by rail — project vs classification (a
483
+ // cluster can only trip one: either skip keeps every member live).
484
+ skipped_project_mismatch: plan.mismatchSkipped.filter((c) => c.mismatch.projectMismatch).length,
485
+ skipped_classification_mismatch: plan.mismatchSkipped.filter((c) => c.mismatch.classificationMismatch).length,
475
486
  skipped_conflict: plan.conflictSkipped.length,
476
487
  capped: 0,
477
488
  failed: 0,
@@ -576,6 +587,7 @@ async function runDeterministicMergeZone(db, opts = {}) {
576
587
  console.log(`[hicortex] deterministic-merge zone (>= ${threshold}): ${report.merged_clusters}/${plan.mergePlans.length} ` +
577
588
  `cluster(s) merged, ${report.losers_merged} loser(s) absorbed, ` +
578
589
  `${report.skipped_project_mismatch} skipped (project mismatch), ` +
590
+ `${report.skipped_classification_mismatch ?? 0} skipped (classification mismatch, #332), ` +
579
591
  `${report.skipped_conflict} skipped (conflict-flagged)` +
580
592
  (report.capped > 0 ? `, ${report.capped} deferred (run deadline)` : "") +
581
593
  (report.failed > 0 ? `, ${report.failed} FAILED` : ""));
@@ -594,7 +606,8 @@ async function runDeterministicMergeZone(db, opts = {}) {
594
606
  return {
595
607
  threshold, clusters_found: 0, mergeable_clusters: 0,
596
608
  merged_clusters: 0, losers_merged: 0, links_repointed: 0,
597
- skipped_project_mismatch: 0, skipped_conflict: 0, capped: 0, failed: 0,
609
+ skipped_project_mismatch: 0, skipped_classification_mismatch: 0,
610
+ skipped_conflict: 0, capped: 0, failed: 0,
598
611
  };
599
612
  }
600
613
  }
@@ -658,7 +671,7 @@ async function runDedup(options = {}) {
658
671
  linksSkippedExisting: linksSkippedExistingPreview,
659
672
  };
660
673
  console.log(`[hicortex] dedup: ${plan.clusterCount} cluster(s) found, ${mergeable.length} mergeable ` +
661
- `(${plannedMerges} row(s) would be absorbed), ${plan.mismatchSkipped.length} skipped (project mismatch), ` +
674
+ `(${plannedMerges} row(s) would be absorbed), ${plan.mismatchSkipped.length} skipped (project/classification mismatch), ` +
662
675
  `${plan.conflictSkipped.length} skipped (conflict-flagged), ` +
663
676
  `${linksSkippedExistingPreview} link(s) would be skipped (existing edge on the canonical)`);
664
677
  if (!apply) {
@@ -669,10 +682,11 @@ async function runDedup(options = {}) {
669
682
  `${c.linksSkippedSelfLink} skipped (self-link)`);
670
683
  }
671
684
  for (const c of plan.mismatchSkipped) {
672
- // #206 decision 2: project_mismatch is the only skip reason left on
673
- // this rail (the source_agent rail was removed) — the reference dry
674
- // run sizes the project rail alone off this line.
675
- console.log(`[hicortex] SKIPPED (project_mismatch): ${c.memberIds.map((id) => id.slice(0, 8)).join(", ")}`);
685
+ // The skip rail: project (#206 decision 2 — the source_agent rail was
686
+ // removed) or classification (#332 — the pools never cross). The dry
687
+ // run sizes each rail off these lines.
688
+ const reason = c.mismatch.classificationMismatch ? "classification_mismatch" : "project_mismatch";
689
+ console.log(`[hicortex] SKIPPED (${reason}): ${c.memberIds.map((id) => id.slice(0, 8)).join(", ")}`);
676
690
  }
677
691
  // #393 guard-C: listed for review like the mismatch clusters — a
678
692
  // conflicts-linked near-duplicate pair is deliberate, not an error.