@remnic/core 10.0.149 → 10.0.151

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 (161) hide show
  1. package/dist/access-admin-ops-surface.js +56 -55
  2. package/dist/access-cli.js +56 -55
  3. package/dist/access-cli.js.map +1 -1
  4. package/dist/access-extraction-force-flush-preempt.js +56 -55
  5. package/dist/access-extraction-force-flush.js +56 -55
  6. package/dist/access-http-briefing.js +56 -55
  7. package/dist/access-http-query.js +56 -55
  8. package/dist/access-http.js +56 -55
  9. package/dist/access-identity-continuity-surface.js +56 -55
  10. package/dist/access-lcm-surface.js +56 -55
  11. package/dist/access-mcp.js +56 -55
  12. package/dist/access-observe-write-surface.js +56 -55
  13. package/dist/access-operations-batch.js +56 -55
  14. package/dist/access-operations.js +56 -55
  15. package/dist/access-recall-concurrency.js +56 -55
  16. package/dist/access-recall-response.js +56 -55
  17. package/dist/access-recall-surface.js +56 -55
  18. package/dist/access-service.js +56 -55
  19. package/dist/active-recall.js +9 -9
  20. package/dist/adapters/index.js +4 -4
  21. package/dist/adapters/registry.js +2 -2
  22. package/dist/briefing.js +10 -10
  23. package/dist/causal-consolidation.js +11 -11
  24. package/dist/{chunk-XCJDDXJX.js → chunk-272GJCTZ.js} +2 -2
  25. package/dist/{chunk-E6VI7POW.js → chunk-2ZYU76CG.js} +66 -66
  26. package/dist/{chunk-EIEANUBO.js → chunk-3YZYD5XJ.js} +7 -7
  27. package/dist/{chunk-66DUCUOC.js → chunk-4LF5E2LM.js} +4 -4
  28. package/dist/{chunk-5UYP5IQB.js → chunk-5N767BMB.js} +2 -2
  29. package/dist/{chunk-EYES6ALH.js → chunk-5Y3UVK6S.js} +81 -40
  30. package/dist/chunk-5Y3UVK6S.js.map +1 -0
  31. package/dist/{chunk-DOFLNJZD.js → chunk-6ENFCUYH.js} +3 -3
  32. package/dist/{chunk-RSPPAPFI.js → chunk-6M3VJJON.js} +2 -2
  33. package/dist/{chunk-ORPYIVT3.js → chunk-ALNINIUB.js} +2 -2
  34. package/dist/{chunk-RQ6HMDA5.js → chunk-AMPTUYKS.js} +2 -2
  35. package/dist/{chunk-UMC6F3Y4.js → chunk-CAFF45W4.js} +3 -3
  36. package/dist/{chunk-AHNGWFNG.js → chunk-DPF7TX3D.js} +2 -2
  37. package/dist/{chunk-TVRUUT7U.js → chunk-EK3GC76D.js} +2 -2
  38. package/dist/{chunk-YCASWFI6.js → chunk-EUIWWY2F.js} +3 -3
  39. package/dist/{chunk-HUDPXTXW.js → chunk-GXL52YZA.js} +23 -14
  40. package/dist/chunk-GXL52YZA.js.map +1 -0
  41. package/dist/{chunk-7OWV3GVD.js → chunk-HAEMXLHX.js} +2 -2
  42. package/dist/{chunk-JPVUBL4L.js → chunk-HOENUZJ7.js} +2 -2
  43. package/dist/{chunk-Z3GZRG5Z.js → chunk-J2NQZJRG.js} +2 -2
  44. package/dist/chunk-JA2GJCOS.js +16 -0
  45. package/dist/chunk-JA2GJCOS.js.map +1 -0
  46. package/dist/{chunk-NQJAF2Q4.js → chunk-KZBUOWKB.js} +2 -2
  47. package/dist/{chunk-SLZJ7HQX.js → chunk-M7BJEWPQ.js} +2 -2
  48. package/dist/{chunk-3DJ6R4CC.js → chunk-MX5VGD6C.js} +4 -4
  49. package/dist/{chunk-AWZ5CWSR.js → chunk-MXMFRU45.js} +7 -7
  50. package/dist/{chunk-5ZSN2OFB.js → chunk-NQ2WFFPQ.js} +6 -6
  51. package/dist/{chunk-MBQVWTCS.js → chunk-O2677F2E.js} +2 -2
  52. package/dist/{chunk-ZG4GNPRE.js → chunk-PBE7NFB5.js} +5 -5
  53. package/dist/{chunk-DLR3SBOM.js → chunk-RJ5L6LRD.js} +4 -4
  54. package/dist/{chunk-HADCITEA.js → chunk-SENCYTQ2.js} +10 -10
  55. package/dist/{chunk-7QKZOZF4.js → chunk-T266H3RJ.js} +2 -2
  56. package/dist/{chunk-QGV6JVQ7.js → chunk-T2IKH7XD.js} +2 -2
  57. package/dist/{chunk-TQU2RB4B.js → chunk-UUY7OEO7.js} +2 -2
  58. package/dist/{chunk-CA56BOUE.js → chunk-VI5ECVDF.js} +3 -3
  59. package/dist/{chunk-B5MB2G3H.js → chunk-VZCX3DOD.js} +2 -2
  60. package/dist/{chunk-GCHM5BYL.js → chunk-WWQMZBDI.js} +4 -4
  61. package/dist/{chunk-4JKIOAOF.js → chunk-XSG2S43P.js} +3 -3
  62. package/dist/{chunk-5BKH4XG5.js → chunk-XTJUE2ON.js} +2 -2
  63. package/dist/{chunk-6S37C5UK.js → chunk-Z5QZHDG2.js} +2 -2
  64. package/dist/{chunk-K6RKNQRD.js → chunk-ZFGXIEQU.js} +2 -2
  65. package/dist/cli.js +56 -55
  66. package/dist/coding/export-okf-codegraph.js +9 -9
  67. package/dist/compounding/engine.js +11 -11
  68. package/dist/config.js +9 -9
  69. package/dist/connectors/codex-materialize-runner.js +10 -10
  70. package/dist/connectors/index.js +10 -10
  71. package/dist/convergence-refresh.js +12 -12
  72. package/dist/corpus-watermark.js +12 -12
  73. package/dist/entity-retrieval.js +10 -10
  74. package/dist/explicit-capture.js +56 -55
  75. package/dist/extraction.js +10 -10
  76. package/dist/harmonic-retrieval.d.ts +3 -0
  77. package/dist/harmonic-retrieval.d.ts.map +1 -1
  78. package/dist/harmonic-retrieval.js +14 -11
  79. package/dist/harmonic-source-lookup.d.ts.map +1 -1
  80. package/dist/harmonic-source-lookup.js +2 -1
  81. package/dist/index.js +94 -93
  82. package/dist/lcm/engine.js +2 -2
  83. package/dist/lcm/index.js +5 -5
  84. package/dist/location/index.js +11 -11
  85. package/dist/maintenance/memory-governance.js +10 -10
  86. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +10 -10
  87. package/dist/maintenance/rebuild-memory-projection-runner.js +12 -12
  88. package/dist/maintenance/rebuild-memory-projection.js +11 -11
  89. package/dist/map-in-batches.d.ts +10 -0
  90. package/dist/map-in-batches.d.ts.map +1 -0
  91. package/dist/map-in-batches.js +10 -0
  92. package/dist/map-in-batches.js.map +1 -0
  93. package/dist/namespaces/migrate.js +11 -11
  94. package/dist/namespaces/search.js +7 -7
  95. package/dist/namespaces/storage.js +10 -10
  96. package/dist/operator-doctor-corpus.js +13 -13
  97. package/dist/operator-toolkit.js +16 -16
  98. package/dist/orchestration/backlog-scheduler.js +57 -56
  99. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  100. package/dist/orchestration/buffer-drain-runner.js +57 -56
  101. package/dist/orchestration/maintenance.js +18 -18
  102. package/dist/orchestrator.js +56 -55
  103. package/dist/recall-navigation.js +56 -55
  104. package/dist/resume-bundles.js +9 -9
  105. package/dist/search/factory.js +6 -6
  106. package/dist/search/index.js +11 -11
  107. package/dist/search/lancedb-backend.js +2 -2
  108. package/dist/search/meilisearch-backend.js +2 -2
  109. package/dist/search/orama-backend.js +2 -2
  110. package/dist/semantic-consolidation.js +11 -11
  111. package/dist/semantic-rule-promotion.js +10 -10
  112. package/dist/semantic-rule-verifier.js +10 -10
  113. package/dist/source-agent-qualifier.js +10 -10
  114. package/dist/standup/build.js +10 -10
  115. package/dist/storage.js +9 -9
  116. package/dist/transfer/export-okf.js +10 -10
  117. package/dist/verified-recall.js +10 -10
  118. package/dist/who-knows-cli.js +11 -11
  119. package/dist/who-knows.js +10 -10
  120. package/package.json +2 -2
  121. package/src/harmonic-retrieval-index.test.ts +238 -1
  122. package/src/harmonic-retrieval.ts +114 -41
  123. package/src/harmonic-source-lookup.ts +21 -15
  124. package/src/map-in-batches.ts +17 -0
  125. package/dist/chunk-EYES6ALH.js.map +0 -1
  126. package/dist/chunk-HUDPXTXW.js.map +0 -1
  127. /package/dist/{chunk-XCJDDXJX.js.map → chunk-272GJCTZ.js.map} +0 -0
  128. /package/dist/{chunk-E6VI7POW.js.map → chunk-2ZYU76CG.js.map} +0 -0
  129. /package/dist/{chunk-EIEANUBO.js.map → chunk-3YZYD5XJ.js.map} +0 -0
  130. /package/dist/{chunk-66DUCUOC.js.map → chunk-4LF5E2LM.js.map} +0 -0
  131. /package/dist/{chunk-5UYP5IQB.js.map → chunk-5N767BMB.js.map} +0 -0
  132. /package/dist/{chunk-DOFLNJZD.js.map → chunk-6ENFCUYH.js.map} +0 -0
  133. /package/dist/{chunk-RSPPAPFI.js.map → chunk-6M3VJJON.js.map} +0 -0
  134. /package/dist/{chunk-ORPYIVT3.js.map → chunk-ALNINIUB.js.map} +0 -0
  135. /package/dist/{chunk-RQ6HMDA5.js.map → chunk-AMPTUYKS.js.map} +0 -0
  136. /package/dist/{chunk-UMC6F3Y4.js.map → chunk-CAFF45W4.js.map} +0 -0
  137. /package/dist/{chunk-AHNGWFNG.js.map → chunk-DPF7TX3D.js.map} +0 -0
  138. /package/dist/{chunk-TVRUUT7U.js.map → chunk-EK3GC76D.js.map} +0 -0
  139. /package/dist/{chunk-YCASWFI6.js.map → chunk-EUIWWY2F.js.map} +0 -0
  140. /package/dist/{chunk-7OWV3GVD.js.map → chunk-HAEMXLHX.js.map} +0 -0
  141. /package/dist/{chunk-JPVUBL4L.js.map → chunk-HOENUZJ7.js.map} +0 -0
  142. /package/dist/{chunk-Z3GZRG5Z.js.map → chunk-J2NQZJRG.js.map} +0 -0
  143. /package/dist/{chunk-NQJAF2Q4.js.map → chunk-KZBUOWKB.js.map} +0 -0
  144. /package/dist/{chunk-SLZJ7HQX.js.map → chunk-M7BJEWPQ.js.map} +0 -0
  145. /package/dist/{chunk-3DJ6R4CC.js.map → chunk-MX5VGD6C.js.map} +0 -0
  146. /package/dist/{chunk-AWZ5CWSR.js.map → chunk-MXMFRU45.js.map} +0 -0
  147. /package/dist/{chunk-5ZSN2OFB.js.map → chunk-NQ2WFFPQ.js.map} +0 -0
  148. /package/dist/{chunk-MBQVWTCS.js.map → chunk-O2677F2E.js.map} +0 -0
  149. /package/dist/{chunk-ZG4GNPRE.js.map → chunk-PBE7NFB5.js.map} +0 -0
  150. /package/dist/{chunk-DLR3SBOM.js.map → chunk-RJ5L6LRD.js.map} +0 -0
  151. /package/dist/{chunk-HADCITEA.js.map → chunk-SENCYTQ2.js.map} +0 -0
  152. /package/dist/{chunk-7QKZOZF4.js.map → chunk-T266H3RJ.js.map} +0 -0
  153. /package/dist/{chunk-QGV6JVQ7.js.map → chunk-T2IKH7XD.js.map} +0 -0
  154. /package/dist/{chunk-TQU2RB4B.js.map → chunk-UUY7OEO7.js.map} +0 -0
  155. /package/dist/{chunk-CA56BOUE.js.map → chunk-VI5ECVDF.js.map} +0 -0
  156. /package/dist/{chunk-B5MB2G3H.js.map → chunk-VZCX3DOD.js.map} +0 -0
  157. /package/dist/{chunk-GCHM5BYL.js.map → chunk-WWQMZBDI.js.map} +0 -0
  158. /package/dist/{chunk-4JKIOAOF.js.map → chunk-XSG2S43P.js.map} +0 -0
  159. /package/dist/{chunk-5BKH4XG5.js.map → chunk-XTJUE2ON.js.map} +0 -0
  160. /package/dist/{chunk-6S37C5UK.js.map → chunk-Z5QZHDG2.js.map} +0 -0
  161. /package/dist/{chunk-K6RKNQRD.js.map → chunk-ZFGXIEQU.js.map} +0 -0
@@ -6,7 +6,8 @@ import test from "node:test";
6
6
  import { getMemoryProjectionPath } from "./memory-projection-store.js";
7
7
  import { openBetterSqlite3 } from "./runtime/better-sqlite.js";
8
8
  import { recordAbstractionNode } from "./abstraction-nodes.js";
9
- import { searchHarmonicRetrieval, type HarmonicRetrievalResult } from "./harmonic-retrieval.js";
9
+ import { recordCueAnchor } from "./cue-anchors.js";
10
+ import { harmonicSearchIndexStats, readProjectedHarmonicGraph, searchHarmonicRetrieval, type HarmonicRetrievalResult } from "./harmonic-retrieval.js";
10
11
  import { rebuildMemoryProjection } from "./maintenance/rebuild-memory-projection.js";
11
12
  import { StorageManager } from "./storage.js";
12
13
 
@@ -385,3 +386,239 @@ test("the cold path walk honors an aborted signal", async () => {
385
386
  await rm(memoryDir, { recursive: true, force: true });
386
387
  }
387
388
  });
389
+
390
+ test("indexed source resolution overlaps per-source file reads (#3450)", async (t) => {
391
+ const memoryDir = await mkdtemp(path.join(tmpdir(), "remnic-harmonic-concurrency-"));
392
+ try {
393
+ const storage = new StorageManager(memoryDir);
394
+ await storage.ensureDirectories();
395
+ const sourceMemoryIds: string[] = [];
396
+ for (let i = 0; i < 40; i++) {
397
+ const { id } = await storage.writeMemory("fact", `concurrent source payload ${i}`, { source: "test" });
398
+ sourceMemoryIds.push(id);
399
+ }
400
+ await recordAbstractionNode({
401
+ memoryDir,
402
+ node: {
403
+ schemaVersion: 1,
404
+ nodeId: "many-sources",
405
+ recordedAt: "2026-11-19T00:00:00.000Z",
406
+ sessionKey: "agent:index",
407
+ kind: "topic",
408
+ abstractionLevel: "meso",
409
+ title: "stored title",
410
+ summary: "stored summary",
411
+ sourceMemoryIds,
412
+ },
413
+ });
414
+ await rebuildMemoryProjection({ memoryDir, storage, dryRun: false });
415
+
416
+ // Every recalled build resolves thousands of sources; when each read is
417
+ // awaited in turn the build takes seconds on real disks (w91: ~19 s inside
418
+ // harmonicRetrieval). With a small per-read delay, serial code keeps
419
+ // maxInFlight at 1 while batched reads overlap.
420
+ const originalRead = StorageManager.prototype.readMemoryByPath;
421
+ let inFlight = 0;
422
+ let maxInFlight = 0;
423
+ t.mock.method(StorageManager.prototype, "readMemoryByPath", async function (
424
+ this: StorageManager,
425
+ ...args: Parameters<StorageManager["readMemoryByPath"]>
426
+ ) {
427
+ inFlight += 1;
428
+ maxInFlight = Math.max(maxInFlight, inFlight);
429
+ await new Promise((resolve) => setTimeout(resolve, 5));
430
+ try {
431
+ return await originalRead.call(this, ...args);
432
+ } finally {
433
+ inFlight -= 1;
434
+ }
435
+ });
436
+ const graph = await readProjectedHarmonicGraph({ memoryDir, anchorsEnabled: false });
437
+ assert.equal(maxInFlight > 1, true, `source reads ran one at a time (max in-flight ${maxInFlight})`);
438
+ assert.deepEqual(graph.nodes[0]?.sourceMemoryIds?.slice().sort(), sourceMemoryIds.slice().sort());
439
+ } finally {
440
+ t.mock.restoreAll();
441
+ await rm(memoryDir, { recursive: true, force: true });
442
+ }
443
+ });
444
+
445
+ test("cached graph searches share one scoring index across recalls (#3450)", async (t) => {
446
+ const memoryDir = await mkdtemp(path.join(tmpdir(), "remnic-harmonic-index-reuse-"));
447
+ try {
448
+ const storage = new StorageManager(memoryDir);
449
+ await storage.ensureDirectories();
450
+ const a = await storage.writeMemory("fact", "shared index source payload", { source: "test" });
451
+ await recordAbstractionNode({
452
+ memoryDir,
453
+ node: {
454
+ schemaVersion: 1,
455
+ nodeId: "shared-index-node",
456
+ recordedAt: "2026-11-19T00:00:00.000Z",
457
+ sessionKey: "agent:index",
458
+ kind: "topic",
459
+ abstractionLevel: "meso",
460
+ title: "shared index source payload",
461
+ summary: "shared index summary",
462
+ sourceMemoryIds: [a.id],
463
+ },
464
+ });
465
+ await rebuildMemoryProjection({ memoryDir, storage, dryRun: false });
466
+
467
+ const run = () =>
468
+ searchHarmonicRetrieval({
469
+ memoryDir,
470
+ query: "shared index source payload",
471
+ maxResults: 5,
472
+ anchorsEnabled: false,
473
+ useGraphCache: true,
474
+ });
475
+ const first = await run();
476
+ const buildsBefore = harmonicSearchIndexStats.builds;
477
+ const second = await run();
478
+ const third = await run();
479
+ assert.equal(
480
+ harmonicSearchIndexStats.builds,
481
+ buildsBefore,
482
+ "repeat searches over a cached graph must reuse the same scoring index (re-tokenizing every recall costs ~750 ms on a real corpus)",
483
+ );
484
+ assert.deepEqual(third, second);
485
+ assert.deepEqual(second.map((r) => r.node.nodeId), first.map((r) => r.node.nodeId));
486
+ } finally {
487
+ t.mock.restoreAll();
488
+ await rm(memoryDir, { recursive: true, force: true });
489
+ }
490
+ });
491
+
492
+ test("anchors sharing an anchorId across types keep their own cues (#3450)", async (t) => {
493
+ const memoryDir = await mkdtemp(path.join(tmpdir(), "remnic-harmonic-dup-anchor-"));
494
+ try {
495
+ const storage = new StorageManager(memoryDir);
496
+ await storage.ensureDirectories();
497
+ const alpha = await storage.writeMemory("fact", "alpha source body", { source: "test" });
498
+ const beta = await storage.writeMemory("fact", "beta source body", { source: "test" });
499
+ await recordAbstractionNode({
500
+ memoryDir,
501
+ node: {
502
+ schemaVersion: 1,
503
+ nodeId: "dup-anchor-alpha",
504
+ recordedAt: "2026-11-19T00:00:00.000Z",
505
+ sessionKey: "agent:index",
506
+ kind: "topic",
507
+ abstractionLevel: "meso",
508
+ title: "unmatched alpha title",
509
+ summary: "unmatched alpha summary",
510
+ sourceMemoryIds: [alpha.id],
511
+ },
512
+ });
513
+ await recordAbstractionNode({
514
+ memoryDir,
515
+ node: {
516
+ schemaVersion: 1,
517
+ nodeId: "dup-anchor-beta",
518
+ recordedAt: "2026-11-19T00:00:00.000Z",
519
+ sessionKey: "agent:index",
520
+ kind: "topic",
521
+ abstractionLevel: "meso",
522
+ title: "unmatched beta title",
523
+ summary: "unmatched beta summary",
524
+ sourceMemoryIds: [beta.id],
525
+ },
526
+ });
527
+ // The anchor store dedups by (anchorType, anchorId), so one anchorId can
528
+ // legitimately recur under a second type — each keeps its own cue.
529
+ await recordCueAnchor({
530
+ memoryDir,
531
+ anchor: {
532
+ schemaVersion: 1,
533
+ anchorId: "shared-anchor-id",
534
+ anchorType: "entity",
535
+ anchorValue: "zebra wobble",
536
+ normalizedCue: "zebra wobble",
537
+ recordedAt: "2026-11-19T00:00:00.000Z",
538
+ sessionKey: "agent:index",
539
+ nodeRefs: ["dup-anchor-alpha"],
540
+ sourceMemoryIdsByNodeRef: { "dup-anchor-alpha": [alpha.id] },
541
+ },
542
+ });
543
+ await recordCueAnchor({
544
+ memoryDir,
545
+ anchor: {
546
+ schemaVersion: 1,
547
+ anchorId: "shared-anchor-id",
548
+ anchorType: "file",
549
+ anchorValue: "quartz tumble",
550
+ normalizedCue: "quartz tumble",
551
+ recordedAt: "2026-11-19T00:00:00.000Z",
552
+ sessionKey: "agent:index",
553
+ nodeRefs: ["dup-anchor-beta"],
554
+ sourceMemoryIdsByNodeRef: { "dup-anchor-beta": [beta.id] },
555
+ },
556
+ });
557
+ await rebuildMemoryProjection({ memoryDir, storage, dryRun: false });
558
+
559
+ const zebra = await searchHarmonicRetrieval({
560
+ memoryDir,
561
+ query: "zebra wobble",
562
+ maxResults: 5,
563
+ anchorsEnabled: true,
564
+ useGraphCache: true,
565
+ });
566
+ assert.deepEqual(zebra.map((r) => r.node.nodeId), ["dup-anchor-alpha"]);
567
+ const quartz = await searchHarmonicRetrieval({
568
+ memoryDir,
569
+ query: "quartz tumble",
570
+ maxResults: 5,
571
+ anchorsEnabled: true,
572
+ useGraphCache: true,
573
+ });
574
+ assert.deepEqual(quartz.map((r) => r.node.nodeId), ["dup-anchor-beta"]);
575
+ } finally {
576
+ t.mock.restoreAll();
577
+ await rm(memoryDir, { recursive: true, force: true });
578
+ }
579
+ });
580
+
581
+ test("nodes sharing a nodeId across record days keep their own tokens (#3450)", async (t) => {
582
+ const memoryDir = await mkdtemp(path.join(tmpdir(), "remnic-harmonic-dup-node-"));
583
+ try {
584
+ const storage = new StorageManager(memoryDir);
585
+ await storage.ensureDirectories();
586
+ const a = await storage.writeMemory("fact", "zebra wobble retained source", { source: "test" });
587
+ const b = await storage.writeMemory("fact", "quartz tumble retained source", { source: "test" });
588
+ // Node records live under nodes/<day>/<nodeId>.json, so one nodeId can
589
+ // legitimately recur on a second day as a distinct projected node.
590
+ for (const [recordedAt, title, id] of [
591
+ ["2026-11-17T00:00:00.000Z", "zebra wobble", a.id],
592
+ ["2026-11-18T00:00:00.000Z", "quartz tumble", b.id],
593
+ ] as const) {
594
+ await recordAbstractionNode({
595
+ memoryDir,
596
+ node: {
597
+ schemaVersion: 1,
598
+ nodeId: "shared-id",
599
+ recordedAt,
600
+ sessionKey: "agent:index",
601
+ kind: "topic",
602
+ abstractionLevel: "meso",
603
+ title,
604
+ summary: title,
605
+ sourceMemoryIds: [id],
606
+ },
607
+ });
608
+ }
609
+ await rebuildMemoryProjection({ memoryDir, storage, dryRun: false });
610
+
611
+ const got = await searchHarmonicRetrieval({
612
+ memoryDir,
613
+ query: "zebra wobble",
614
+ maxResults: 5,
615
+ anchorsEnabled: false,
616
+ useGraphCache: true,
617
+ });
618
+ assert.equal(got.length, 1);
619
+ assert.equal(got[0].node.sourceMemoryIds?.[0], a.id);
620
+ } finally {
621
+ t.mock.restoreAll();
622
+ await rm(memoryDir, { recursive: true, force: true });
623
+ }
624
+ });
@@ -13,7 +13,7 @@ import { inferMemoryStatus, toMemoryPathRel } from "./memory-lifecycle-ledger-ut
13
13
  } from "./abstraction-nodes.js";
14
14
  import { resolveCueAnchorStoreDir, validateCueAnchor, type CueAnchor, type CueAnchorType } from "./cue-anchors.js";
15
15
  import { compareDeterministicStrings } from "./deterministic-order.js";
16
- import { countRecallTokenOverlap, normalizeRecallTokens } from "./recall-tokenization.js";
16
+ import { normalizeRecallTokenSet, normalizeRecallTokens } from "./recall-tokenization.js";
17
17
  import { stripAttributesSuffix } from "./structured-attributes.js";
18
18
  import { isValidityExpiredNow } from "./temporal-validity.js";
19
19
  import { assertSafePathSegment, isRecord } from "./store-contract.js";
@@ -24,6 +24,7 @@ import { SecureStoreLockedError } from "./secure-store/secure-fs.js";
24
24
  import { StorageManager } from "./storage.js";
25
25
  import { RECALL_FALLBACK_DIRS } from "./utils/category-dir.js";
26
26
  import { readHarmonicSourceMemory, readUnresolvedHarmonicSources } from "./harmonic-source-lookup.js";
27
+ import { mapInBatches } from "./map-in-batches.js";
27
28
 
28
29
 
29
30
  type SourceMemoryMap = Map<string, MemoryFile>;
@@ -76,7 +77,7 @@ async function readIndexedSourceMemories(options: {
76
77
  const days = utcDaysSince(rebuiltMs, options.nowMs);
77
78
  const sourceMemories: SourceMemoryMap = new Map();
78
79
  const pending: string[] = [];
79
- for (const id of options.sourceMemoryIds) {
80
+ const resolved = await mapInBatches(options.sourceMemoryIds, async (id) => {
80
81
  const state = batch.states.get(id);
81
82
  // An id is only ever joined into a path when it is a single safe segment.
82
83
  let safeId = true;
@@ -89,15 +90,16 @@ async function readIndexedSourceMemories(options: {
89
90
  const candidates = state
90
91
  ? [state.path, path.join(options.memoryDir, "cold", state.pathRel)]
91
92
  : safeId ? unprojectedCandidatePaths(options.memoryDir, id, days) : [];
92
- let found = false;
93
93
  for (const candidate of candidates) {
94
94
  const memory = await readHarmonicSourceMemory(storage, rootReal, candidate, options.abortSignal);
95
95
  if (memory?.frontmatter.id !== id) continue;
96
- sourceMemories.set(id, memory);
97
- found = true;
98
- break;
96
+ return { id, memory };
99
97
  }
100
- if (!found) pending.push(id);
98
+ return { id, memory: undefined };
99
+ });
100
+ for (const { id, memory } of resolved) {
101
+ if (memory) sourceMemories.set(id, memory);
102
+ else pending.push(id);
101
103
  }
102
104
  if (pending.length === 0) return sourceMemories;
103
105
 
@@ -289,35 +291,109 @@ interface HarmonicCandidate {
289
291
  matchedAnchors: Map<string, HarmonicMatchedAnchor>;
290
292
  }
291
293
 
292
- function scoreNode(node: AbstractionNode, queryTokens: Set<string>): { score: number; matchedFields: string[] } {
294
+ function tokenOverlap(queryTokens: Set<string>, fieldTokens: ReadonlySet<string>): number {
295
+ let matches = 0;
296
+ for (const token of queryTokens) {
297
+ if (fieldTokens.has(token)) matches += 1;
298
+ }
299
+ return matches;
300
+ }
301
+
302
+ interface HarmonicNodeTokens {
303
+ title: ReadonlySet<string>;
304
+ summary: ReadonlySet<string>;
305
+ tags: ReadonlySet<string>;
306
+ entities: ReadonlySet<string>;
307
+ kind: ReadonlySet<string>;
308
+ }
309
+
310
+ interface HarmonicAnchorTokens {
311
+ value: ReadonlySet<string>;
312
+ normalized: ReadonlySet<string>;
313
+ type: ReadonlySet<string>;
314
+ eligibleTags: ReadonlySet<string>;
315
+ }
316
+
317
+ interface HarmonicSearchIndex {
318
+ nodesById: Map<string, AbstractionNode>;
319
+ nodeTokens: HarmonicNodeTokens[];
320
+ anchorTokens: HarmonicAnchorTokens[];
321
+ }
322
+
323
+ export const harmonicSearchIndexStats = { builds: 0 };
324
+
325
+ /**
326
+ * Per-graph scoring index, keyed on the frozen graph object itself. Scoring a
327
+ * recall tokenizes every node's title/summary/tags/entities/kind and every
328
+ * anchor's value/cue/type/eligible tags; on a cache hit that repeated the
329
+ * whole normalization for each recall (~0.75 s on a ~2.5k node, ~10k anchor
330
+ * corpus, issue #3450). The sets are identical to what `countRecallTokenOverlap`
331
+ * computed from the raw fields, so scores and matchedFields are unchanged.
332
+ * For an uncached graph the index is built per call — the same work the old
333
+ * code did inline.
334
+ */
335
+ const harmonicSearchIndexes = new WeakMap<ProjectedHarmonicGraph, HarmonicSearchIndex>();
336
+
337
+ function getHarmonicSearchIndex(graph: ProjectedHarmonicGraph): HarmonicSearchIndex {
338
+ const cached = harmonicSearchIndexes.get(graph);
339
+ if (cached) return cached;
340
+ harmonicSearchIndexStats.builds += 1;
341
+ const nodesById = new Map(graph.nodes.map((node) => [node.nodeId, node]));
342
+ // Node ids are only unique per record day (nodes/<day>/<nodeId>.json), so
343
+ // tokens are indexed by position in graph.nodes.
344
+ const nodeTokens = graph.nodes.map((node) => ({
345
+ title: normalizeRecallTokenSet(node.title ?? ""),
346
+ summary: normalizeRecallTokenSet(node.summary ?? ""),
347
+ tags: normalizeRecallTokenSet(node.tags?.join(" ") ?? ""),
348
+ entities: normalizeRecallTokenSet(node.entityRefs?.join(" ") ?? ""),
349
+ kind: normalizeRecallTokenSet(`${node.kind} ${node.abstractionLevel}`),
350
+ }));
351
+ // Anchor ids are only unique per anchorType (cue-anchors dedups by
352
+ // type+id), so tokens are indexed by position in graph.anchors.
353
+ const anchorTokens = graph.anchors.map((anchor) => {
354
+ const eligibleNodeTags = new Set(anchor.nodeRefs.flatMap((nodeRef) => nodesById.get(nodeRef)?.tags ?? []));
355
+ const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];
356
+ return {
357
+ value: normalizeRecallTokenSet(anchor.anchorValue ?? ""),
358
+ normalized: normalizeRecallTokenSet(anchor.normalizedCue ?? ""),
359
+ type: normalizeRecallTokenSet(anchor.anchorType),
360
+ eligibleTags: normalizeRecallTokenSet(eligibleAnchorTags.join(" ")),
361
+ };
362
+ });
363
+ const index: HarmonicSearchIndex = { nodesById, nodeTokens, anchorTokens };
364
+ harmonicSearchIndexes.set(graph, index);
365
+ return index;
366
+ }
367
+
368
+ function scoreNode(tokens: HarmonicNodeTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {
293
369
  const matchedFields: string[] = [];
294
370
  let score = 0;
295
371
 
296
- const titleMatches = countRecallTokenOverlap(queryTokens, node.title);
372
+ const titleMatches = tokenOverlap(queryTokens, tokens.title);
297
373
  if (titleMatches > 0) {
298
374
  score += titleMatches * 3;
299
375
  matchedFields.push("title");
300
376
  }
301
377
 
302
- const summaryMatches = countRecallTokenOverlap(queryTokens, node.summary);
378
+ const summaryMatches = tokenOverlap(queryTokens, tokens.summary);
303
379
  if (summaryMatches > 0) {
304
380
  score += summaryMatches * 3;
305
381
  matchedFields.push("summary");
306
382
  }
307
383
 
308
- const tagMatches = countRecallTokenOverlap(queryTokens, node.tags?.join(" "));
384
+ const tagMatches = tokenOverlap(queryTokens, tokens.tags);
309
385
  if (tagMatches > 0) {
310
386
  score += tagMatches * 2;
311
387
  matchedFields.push("tags");
312
388
  }
313
389
 
314
- const entityMatches = countRecallTokenOverlap(queryTokens, node.entityRefs?.join(" "));
390
+ const entityMatches = tokenOverlap(queryTokens, tokens.entities);
315
391
  if (entityMatches > 0) {
316
392
  score += entityMatches * 2;
317
393
  matchedFields.push("entityRefs");
318
394
  }
319
395
 
320
- const kindMatches = countRecallTokenOverlap(queryTokens, `${node.kind} ${node.abstractionLevel}`);
396
+ const kindMatches = tokenOverlap(queryTokens, tokens.kind);
321
397
  if (kindMatches > 0) {
322
398
  score += kindMatches;
323
399
  matchedFields.push("kind");
@@ -326,16 +402,12 @@ function scoreNode(node: AbstractionNode, queryTokens: Set<string>): { score: nu
326
402
  return { score, matchedFields };
327
403
  }
328
404
 
329
- function scoreAnchor(
330
- anchor: CueAnchor,
331
- queryTokens: Set<string>,
332
- eligibleNodeTags: readonly string[]
333
- ): { score: number; matchedFields: string[] } {
405
+ function scoreAnchor(tokens: HarmonicAnchorTokens, queryTokens: Set<string>): { score: number; matchedFields: string[] } {
334
406
  const matchedFields: string[] = [];
335
407
  let score = 0;
336
408
 
337
- const valueMatches = countRecallTokenOverlap(queryTokens, anchor.anchorValue);
338
- const normalizedMatches = countRecallTokenOverlap(queryTokens, anchor.normalizedCue);
409
+ const valueMatches = tokenOverlap(queryTokens, tokens.value);
410
+ const normalizedMatches = tokenOverlap(queryTokens, tokens.normalized);
339
411
  const cueMatches = Math.max(valueMatches, normalizedMatches);
340
412
  if (cueMatches > 0) {
341
413
  score += cueMatches * 4;
@@ -343,13 +415,13 @@ function scoreAnchor(
343
415
  if (normalizedMatches > 0) matchedFields.push("anchor");
344
416
  }
345
417
 
346
- const typeMatches = countRecallTokenOverlap(queryTokens, anchor.anchorType);
418
+ const typeMatches = tokenOverlap(queryTokens, tokens.type);
347
419
  if (typeMatches > 0) {
348
420
  score += typeMatches;
349
421
  matchedFields.push("anchorType");
350
422
  }
351
423
 
352
- const tagMatches = countRecallTokenOverlap(queryTokens, eligibleNodeTags.join(" "));
424
+ const tagMatches = tokenOverlap(queryTokens, tokens.eligibleTags);
353
425
  if (tagMatches > 0) {
354
426
  score += tagMatches * 2;
355
427
  matchedFields.push("anchorTags");
@@ -364,15 +436,15 @@ export async function readAbstractionNodes(options: {
364
436
  }): Promise<AbstractionNode[]> {
365
437
  const rootDir = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);
366
438
  const files = await listJsonFilesStrict(path.join(rootDir, "nodes"), { allowMissingDirectory: true });
367
- const nodes: AbstractionNode[] = [];
368
- for (const filePath of files) {
439
+ const parsed = await mapInBatches(files, async (filePath) => {
369
440
  try {
370
- nodes.push(validateAbstractionNode(await readJsonFile(filePath)));
441
+ return validateAbstractionNode(await readJsonFile(filePath));
371
442
  } catch {
372
443
  // fail-open: invalid artifacts stay visible via status tooling instead of recall
444
+ return null;
373
445
  }
374
- }
375
- return nodes;
446
+ });
447
+ return parsed.filter((node): node is AbstractionNode => node !== null);
376
448
  }
377
449
 
378
450
  export async function readCueAnchors(options: {
@@ -382,15 +454,15 @@ export async function readCueAnchors(options: {
382
454
  const abstractionRoot = resolveAbstractionNodeStoreDir(options.memoryDir, options.abstractionNodeStoreDir);
383
455
  const rootDir = resolveCueAnchorStoreDir(abstractionRoot);
384
456
  const files = await listJsonFilesStrict(rootDir, { allowMissingDirectory: true });
385
- const anchors: CueAnchor[] = [];
386
- for (const filePath of files) {
457
+ const parsed = await mapInBatches(files, async (filePath) => {
387
458
  try {
388
- anchors.push(validateCueAnchor(await readJsonFile(filePath)));
459
+ return validateCueAnchor(await readJsonFile(filePath));
389
460
  } catch {
390
461
  // fail-open: invalid artifacts stay visible via status tooling instead of recall
462
+ return null;
391
463
  }
392
- }
393
- return anchors;
464
+ });
465
+ return parsed.filter((anchor): anchor is CueAnchor => anchor !== null);
394
466
  }
395
467
 
396
468
  export interface ProjectedHarmonicGraph {
@@ -778,17 +850,20 @@ export async function searchHarmonicRetrieval(options: {
778
850
 
779
851
  // One projection for every graph reader: nodes and anchors both arrive
780
852
  // already narrowed to the namespace's current active memories.
781
- const { nodes: eligibleNodes, anchors } = await readProjectedHarmonicGraph({
853
+ const graph = await readProjectedHarmonicGraph({
782
854
  ...options,
783
855
  useCache: options.useGraphCache === true,
784
856
  waitBudgetMs:
785
857
  options.waitBudgetMs === undefined ? HARMONIC_GRAPH_WAIT_BUDGET_MS : options.waitBudgetMs,
786
858
  });
859
+ const { nodes: eligibleNodes, anchors } = graph;
860
+ const searchIndex = getHarmonicSearchIndex(graph);
787
861
  const candidates = new Map<string, HarmonicCandidate>();
788
862
 
789
- for (const node of eligibleNodes) {
863
+ for (const [nodeIndexPos, node] of eligibleNodes.entries()) {
790
864
  throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
791
- const { score, matchedFields } = scoreNode(node, queryTokens);
865
+ const tokens = searchIndex.nodeTokens[nodeIndexPos];
866
+ const { score, matchedFields } = scoreNode(tokens, queryTokens);
792
867
  if (score <= 0) continue;
793
868
  candidates.set(node.nodeId, {
794
869
  node,
@@ -801,17 +876,15 @@ export async function searchHarmonicRetrieval(options: {
801
876
 
802
877
  if (options.anchorsEnabled) {
803
878
  throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
804
- const nodeIndex = new Map(eligibleNodes.map((node) => [node.nodeId, node]));
805
- for (const anchor of anchors) {
879
+ for (const [anchorIndex, anchor] of anchors.entries()) {
806
880
  throwIfAborted(options.abortSignal, "harmonic retrieval aborted");
807
881
  // `nodeRefs` are the projection's surviving references already.
808
882
  const eligibleNodeRefs = anchor.nodeRefs;
809
- const eligibleNodeTags = new Set(eligibleNodeRefs.flatMap((nodeRef) => nodeIndex.get(nodeRef)?.tags ?? []));
810
- const eligibleAnchorTags = anchor.tags?.filter((tag) => eligibleNodeTags.has(tag)) ?? [];
811
- const { score, matchedFields } = scoreAnchor(anchor, queryTokens, eligibleAnchorTags);
883
+ const anchorTokens = searchIndex.anchorTokens[anchorIndex];
884
+ const { score, matchedFields } = scoreAnchor(anchorTokens, queryTokens);
812
885
  if (score <= 0) continue;
813
886
  for (const nodeRef of eligibleNodeRefs) {
814
- const node = nodeIndex.get(nodeRef);
887
+ const node = searchIndex.nodesById.get(nodeRef);
815
888
  if (!node) continue;
816
889
  const existing = candidates.get(nodeRef) ?? {
817
890
  node,
@@ -3,6 +3,7 @@ import { existsSync } from "node:fs";
3
3
  import { mkdir, realpath } from "node:fs/promises";
4
4
  import { throwIfAborted } from "./abort-error.js";
5
5
  import { readJsonFile, writeJsonFileAtomic } from "./json-store.js";
6
+ import { mapInBatches } from "./map-in-batches.js";
6
7
  import { readProjectedMemoryPaths } from "./memory-projection-batch.js";
7
8
  import { SecureStoreLockedError } from "./secure-store/secure-fs.js";
8
9
  import { isPathInsideStorageRoot, isSafeLegacyPathSegment } from "./storage-paths.js";
@@ -80,20 +81,19 @@ export async function readUnresolvedHarmonicSources(options: {
80
81
  const cache = safeCache ? await readPathCache(cachePath, rebuiltAt, corpusVersion, nowMs) : new Map<string, PathEntry>();
81
82
  const found = new Map<string, MemoryFile>();
82
83
  const pending = new Set<string>();
83
- for (const id of options.sourceMemoryIds) {
84
+ const probed = await mapInBatches(options.sourceMemoryIds, async (id) => {
84
85
  throwIfAborted(abortSignal, "harmonic retrieval aborted");
85
86
  const entry = cache.get(id);
86
- if (entry?.path === null) continue;
87
- if (entry?.path) {
88
- const candidate = path.resolve(storage.dir, entry.path);
89
- const memory = isCorpusPath(storage.dir, candidate)
90
- ? await readHarmonicSourceMemory(storage, rootReal, candidate, abortSignal) : null;
91
- if (memory?.frontmatter.id === id) {
92
- found.set(id, memory);
93
- continue;
94
- }
95
- }
96
- pending.add(id);
87
+ if (entry?.path === null || !entry?.path) return { id, memory: null, skip: entry?.path === null };
88
+ const candidate = path.resolve(storage.dir, entry.path);
89
+ const memory = isCorpusPath(storage.dir, candidate)
90
+ ? await readHarmonicSourceMemory(storage, rootReal, candidate, abortSignal) : null;
91
+ return { id, memory: memory?.frontmatter.id === id ? memory : null, skip: false };
92
+ });
93
+ for (const { id, memory, skip } of probed) {
94
+ if (skip) continue;
95
+ if (memory) found.set(id, memory);
96
+ else pending.add(id);
97
97
  }
98
98
  if (pending.size === 0) return found;
99
99
 
@@ -104,12 +104,18 @@ export async function readUnresolvedHarmonicSources(options: {
104
104
  ...(await storage.collectActiveMemoryPaths({ abortSignal, propagateReadErrors: true })),
105
105
  ...(await storage.collectColdMemoryPaths({ abortSignal, propagateReadErrors: true })),
106
106
  ];
107
- for (const filePath of walked) {
108
- throwIfAborted(abortSignal, "harmonic retrieval aborted");
107
+ const toRead = walked.filter((filePath) =>
109
108
  // Existing projected files need no parse unless their filename names a wanted id.
110
109
  // New/imported files must be keyed by frontmatter id, not their basename (#3188).
111
- if (!inspectProjected && !pending.has(path.basename(filePath, ".md")) && projectedPaths?.has(filePath)) continue;
110
+ inspectProjected || pending.has(path.basename(filePath, ".md")) || !projectedPaths?.has(filePath));
111
+ const read = await mapInBatches(toRead, async (filePath) => {
112
+ throwIfAborted(abortSignal, "harmonic retrieval aborted");
112
113
  const memory = await readHarmonicSourceMemory(storage, rootReal, filePath, abortSignal);
114
+ // Drop non-matching parses inside the batch so a full-corpus walk does not
115
+ // hold every MemoryFile until the last batch resolves.
116
+ return { filePath, memory: memory !== null && pending.has(memory.frontmatter.id) ? memory : null };
117
+ });
118
+ for (const { filePath, memory } of read) {
113
119
  if (!memory) continue;
114
120
  const id = memory.frontmatter.id;
115
121
  if (pending.has(id)) {
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Run `fn` over `items` in `size`-wide parallel batches. A harmonic graph build
3
+ * resolves thousands of per-file reads (nodes, anchors, sources); awaiting
4
+ * each in turn made builds take ~10-20 s on a real corpus, so every recall
5
+ * that missed the cache paid the whole wait (issue #3450). The batch size
6
+ * matches the corpus read path's (readParsedMemoriesFromPaths uses 50, #2307).
7
+ */
8
+ export const HARMONIC_READ_BATCH_SIZE = 50;
9
+
10
+ export async function mapInBatches<T, R>(items: readonly T[], fn: (item: T) => Promise<R>): Promise<R[]> {
11
+ const results: R[] = new Array(items.length);
12
+ for (let i = 0; i < items.length; i += HARMONIC_READ_BATCH_SIZE) {
13
+ const settled = await Promise.all(items.slice(i, i + HARMONIC_READ_BATCH_SIZE).map(fn));
14
+ for (let j = 0; j < settled.length; j++) results[i + j] = settled[j];
15
+ }
16
+ return results;
17
+ }