@remnic/core 9.3.655 → 9.3.656

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 (247) hide show
  1. package/dist/access-cli.js +22 -22
  2. package/dist/access-http.d.ts +4 -4
  3. package/dist/access-http.js +10 -10
  4. package/dist/access-mcp.d.ts +4 -4
  5. package/dist/access-mcp.js +9 -9
  6. package/dist/access-schema.d.ts +10 -10
  7. package/dist/{access-service-BEJvriUt.d.ts → access-service-D_nbpexW.d.ts} +33 -2
  8. package/dist/access-service.d.ts +4 -4
  9. package/dist/access-service.js +8 -8
  10. package/dist/action-confidence.d.ts +1 -1
  11. package/dist/active-memory-bridge.d.ts +1 -1
  12. package/dist/active-recall.d.ts +1 -1
  13. package/dist/active-recall.js +1 -1
  14. package/dist/behavior-learner.d.ts +1 -1
  15. package/dist/behavior-signals.d.ts +1 -1
  16. package/dist/bootstrap.d.ts +3 -3
  17. package/dist/briefing.d.ts +1 -1
  18. package/dist/briefing.js +3 -3
  19. package/dist/buffer-surprise-report.d.ts +1 -1
  20. package/dist/buffer.d.ts +1 -1
  21. package/dist/calibration.d.ts +1 -1
  22. package/dist/causal-behavior.d.ts +1 -1
  23. package/dist/causal-consolidation.d.ts +1 -1
  24. package/dist/causal-consolidation.js +4 -4
  25. package/dist/{chunk-PVE7KSQP.js → chunk-2BD7DG37.js} +2 -2
  26. package/dist/{chunk-54LOUIBE.js → chunk-2MXEVL75.js} +2 -2
  27. package/dist/{chunk-55ZMNKMQ.js → chunk-4UL7VPTD.js} +276 -57
  28. package/dist/chunk-4UL7VPTD.js.map +1 -0
  29. package/dist/{chunk-COVZLGMR.js → chunk-54XF2FY7.js} +17 -17
  30. package/dist/{chunk-UYNFWZWG.js → chunk-AGJKWOKV.js} +2 -2
  31. package/dist/{chunk-TDZSSJV4.js → chunk-AZBV4RRY.js} +1 -1
  32. package/dist/chunk-AZBV4RRY.js.map +1 -0
  33. package/dist/{chunk-KOI765XP.js → chunk-CTAV55JM.js} +241 -1
  34. package/dist/chunk-CTAV55JM.js.map +1 -0
  35. package/dist/{chunk-A3Y37UWI.js → chunk-DIBWFCLA.js} +3 -3
  36. package/dist/{chunk-QDVQ4AN2.js → chunk-DR67OK4E.js} +5 -5
  37. package/dist/{chunk-XBIACVCO.js → chunk-EC2AYKRX.js} +2 -2
  38. package/dist/{chunk-IQ53ZSXV.js → chunk-GCYFUTUC.js} +2 -2
  39. package/dist/{chunk-YYN3LIYA.js → chunk-GSHW5VVD.js} +5 -5
  40. package/dist/chunk-GYSYLGNE.js +650 -0
  41. package/dist/chunk-GYSYLGNE.js.map +1 -0
  42. package/dist/{chunk-NRBGRZW4.js → chunk-IOZ5WBWD.js} +2 -2
  43. package/dist/{chunk-NCSJKK23.js → chunk-JSVFEHLL.js} +7 -5
  44. package/dist/chunk-JSVFEHLL.js.map +1 -0
  45. package/dist/{chunk-7LWRCOP7.js → chunk-LZTFCAKE.js} +2 -2
  46. package/dist/{chunk-TEO46GMM.js → chunk-NXCK7DO7.js} +2 -2
  47. package/dist/{chunk-XOFXKASO.js → chunk-PEPHBH2W.js} +2 -2
  48. package/dist/{chunk-WDTUYOLS.js → chunk-QZRKNA5F.js} +2 -2
  49. package/dist/{chunk-PS3SYNHP.js → chunk-R5DB26G6.js} +2 -2
  50. package/dist/{chunk-5QD3QD76.js → chunk-RDW5G6DO.js} +659 -123
  51. package/dist/chunk-RDW5G6DO.js.map +1 -0
  52. package/dist/{chunk-BGKXTVNG.js → chunk-SWDHVH2P.js} +2 -2
  53. package/dist/{chunk-67G4T7KI.js → chunk-SXYCVRLK.js} +3 -3
  54. package/dist/{chunk-UCEABZZN.js → chunk-TFFZUFEP.js} +7 -5
  55. package/dist/chunk-TFFZUFEP.js.map +1 -0
  56. package/dist/{chunk-UCEDY5M7.js → chunk-TIJYQXDI.js} +2 -2
  57. package/dist/{chunk-2RCGZ67B.js → chunk-VAEAGTEQ.js} +3 -3
  58. package/dist/{chunk-XRKQOQLY.js → chunk-WIKMCJUR.js} +2 -2
  59. package/dist/{chunk-KZZ4YAEC.js → chunk-WWMHAMAY.js} +2 -2
  60. package/dist/{chunk-OKW6F5S5.js → chunk-YEZHZCUO.js} +4 -4
  61. package/dist/{chunk-5FOCXX5E.js → chunk-YVVQUAOO.js} +3 -3
  62. package/dist/{chunk-5FOCXX5E.js.map → chunk-YVVQUAOO.js.map} +1 -1
  63. package/dist/{chunk-3XGWCZ63.js → chunk-YXLT4EMM.js} +2 -2
  64. package/dist/{chunk-PTMJ2FH2.js → chunk-Z6UDTNY6.js} +2 -2
  65. package/dist/{cli-BGahB_d3.d.ts → cli-aYxSuPvP.d.ts} +3 -3
  66. package/dist/cli.d.ts +5 -5
  67. package/dist/cli.js +22 -22
  68. package/dist/compounding/engine.d.ts +1 -1
  69. package/dist/compounding/engine.js +3 -3
  70. package/dist/compounding/preference-consolidator.d.ts +1 -1
  71. package/dist/compression-optimizer.d.ts +1 -1
  72. package/dist/config.d.ts +1 -1
  73. package/dist/config.js +1 -1
  74. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  75. package/dist/connectors/codex-materialize-runner.js +3 -3
  76. package/dist/connectors/codex-materialize.d.ts +1 -1
  77. package/dist/connectors/index.d.ts +1 -1
  78. package/dist/connectors/index.js +3 -3
  79. package/dist/consolidation-provenance-check.d.ts +1 -1
  80. package/dist/consolidation-undo.d.ts +1 -1
  81. package/dist/contradiction/index.d.ts +1 -1
  82. package/dist/conversation-index/backend.d.ts +1 -1
  83. package/dist/conversation-index/chunker.d.ts +1 -1
  84. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  85. package/dist/conversation-index/indexer.d.ts +1 -1
  86. package/dist/conversation-index/search.d.ts +1 -1
  87. package/dist/day-summary.d.ts +1 -1
  88. package/dist/delinearize.d.ts +1 -1
  89. package/dist/direct-answer-wiring.d.ts +1 -1
  90. package/dist/direct-answer.d.ts +1 -1
  91. package/dist/embedding-fallback.d.ts +1 -1
  92. package/dist/enrichment/index.d.ts +1 -1
  93. package/dist/entity-retrieval.d.ts +1 -1
  94. package/dist/entity-retrieval.js +3 -3
  95. package/dist/entity-schema.d.ts +1 -1
  96. package/dist/explicit-capture.d.ts +3 -3
  97. package/dist/explicit-cue-recall.js +2 -2
  98. package/dist/extraction-judge-telemetry.d.ts +1 -1
  99. package/dist/extraction-judge-training.d.ts +1 -1
  100. package/dist/extraction-judge.d.ts +1 -1
  101. package/dist/extraction.d.ts +1 -1
  102. package/dist/fallback-llm.d.ts +1 -1
  103. package/dist/focused-list-recall.js +2 -2
  104. package/dist/identity-continuity.d.ts +1 -1
  105. package/dist/importance.d.ts +1 -1
  106. package/dist/index.d.ts +121 -121
  107. package/dist/index.js +32 -32
  108. package/dist/intent.d.ts +1 -1
  109. package/dist/lcm/engine.d.ts +1 -1
  110. package/dist/lcm/index.d.ts +1 -1
  111. package/dist/lcm/tools.d.ts +1 -1
  112. package/dist/lcm-fallback-read.js +1 -1
  113. package/dist/lifecycle.d.ts +1 -1
  114. package/dist/live-connectors-runner.d.ts +1 -1
  115. package/dist/local-llm.d.ts +1 -1
  116. package/dist/maintenance/memory-governance.d.ts +1 -1
  117. package/dist/maintenance/memory-governance.js +3 -3
  118. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +3 -3
  119. package/dist/maintenance/rebuild-memory-projection.js +4 -4
  120. package/dist/mcp-memory-inspector-app.d.ts +4 -4
  121. package/dist/memory-action-policy.d.ts +1 -1
  122. package/dist/memory-cache.d.ts +1 -1
  123. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  124. package/dist/memory-projection-store.d.ts +1 -1
  125. package/dist/memory-provenance.d.ts +1 -1
  126. package/dist/memory-worth-outcomes.d.ts +1 -1
  127. package/dist/models-json.d.ts +1 -1
  128. package/dist/namespaces/migrate.d.ts +1 -1
  129. package/dist/namespaces/migrate.js +4 -4
  130. package/dist/namespaces/principal.d.ts +1 -1
  131. package/dist/namespaces/search.d.ts +1 -1
  132. package/dist/namespaces/storage.d.ts +1 -1
  133. package/dist/namespaces/storage.js +3 -3
  134. package/dist/native-knowledge.d.ts +1 -1
  135. package/dist/operator-toolkit.d.ts +1 -1
  136. package/dist/operator-toolkit.js +7 -7
  137. package/dist/{orchestrator-BgzZlWxH.d.ts → orchestrator-D1wcmPNj.d.ts} +8 -2
  138. package/dist/orchestrator.d.ts +3 -3
  139. package/dist/orchestrator.js +18 -18
  140. package/dist/patterns-cli.d.ts +1 -1
  141. package/dist/policy-runtime.d.ts +1 -1
  142. package/dist/qmd-recall-cache.d.ts +1 -1
  143. package/dist/qmd.d.ts +1 -1
  144. package/dist/recall-disclosure-escalation.d.ts +1 -1
  145. package/dist/recall-explain-renderer.d.ts +1 -1
  146. package/dist/recall-explain-renderer.js +3 -3
  147. package/dist/recall-planner-llm.d.ts +1 -1
  148. package/dist/recall-state.d.ts +1 -1
  149. package/dist/recall-tag-filter.d.ts +1 -1
  150. package/dist/recall-xray-cli.d.ts +1 -1
  151. package/dist/recall-xray-cli.js +4 -4
  152. package/dist/recall-xray-renderer.d.ts +1 -1
  153. package/dist/recall-xray-renderer.js +3 -3
  154. package/dist/recall-xray.d.ts +1 -1
  155. package/dist/recall-xray.js +2 -2
  156. package/dist/resolve-auth-token.d.ts +1 -1
  157. package/dist/response-guidance-recall.js +2 -2
  158. package/dist/resume-bundles.js +2 -2
  159. package/dist/retrieval-agents.d.ts +1 -1
  160. package/dist/retrieval-tiers.d.ts +1 -1
  161. package/dist/routing/engine.d.ts +1 -1
  162. package/dist/routing/store.d.ts +1 -1
  163. package/dist/search/embed-helper.d.ts +1 -1
  164. package/dist/search/factory.d.ts +1 -1
  165. package/dist/search/index.d.ts +1 -1
  166. package/dist/search/lancedb-backend.d.ts +1 -1
  167. package/dist/search/meilisearch-backend.d.ts +1 -1
  168. package/dist/search/noop-backend.d.ts +1 -1
  169. package/dist/search/orama-backend.d.ts +1 -1
  170. package/dist/search/port.d.ts +1 -1
  171. package/dist/search/remote-backend.d.ts +1 -1
  172. package/dist/{semantic-consolidation-Z8d_uMq8.d.ts → semantic-consolidation-MWOdNtSE.d.ts} +1 -1
  173. package/dist/semantic-consolidation.d.ts +2 -2
  174. package/dist/semantic-consolidation.js +4 -4
  175. package/dist/semantic-rule-promotion.js +3 -3
  176. package/dist/semantic-rule-verifier.d.ts +3 -2
  177. package/dist/semantic-rule-verifier.js +5 -3
  178. package/dist/session-observer-bands.d.ts +1 -1
  179. package/dist/session-observer-state.d.ts +1 -1
  180. package/dist/shared-context/manager.d.ts +1 -1
  181. package/dist/signal.d.ts +1 -1
  182. package/dist/storage.d.ts +1 -1
  183. package/dist/storage.js +2 -2
  184. package/dist/summarizer.d.ts +1 -1
  185. package/dist/summary-snapshot.d.ts +1 -1
  186. package/dist/targeted-fact-recall.js +2 -2
  187. package/dist/temporal-supersession.d.ts +1 -1
  188. package/dist/temporal-validity.d.ts +1 -1
  189. package/dist/threading.d.ts +1 -1
  190. package/dist/tier-migration.d.ts +1 -1
  191. package/dist/tier-routing.d.ts +1 -1
  192. package/dist/topics.d.ts +1 -1
  193. package/dist/transcript.d.ts +1 -1
  194. package/dist/{types-2OPlQWJG.d.ts → types-CgcCpUrf.d.ts} +39 -1
  195. package/dist/types.d.ts +1 -1
  196. package/dist/types.js +1 -1
  197. package/dist/utility-runtime.d.ts +1 -1
  198. package/dist/verified-recall.d.ts +2 -1
  199. package/dist/verified-recall.js +5 -3
  200. package/package.json +1 -1
  201. package/src/access-service-observe-lcm-parity.test.ts +86 -1
  202. package/src/access-service-observe-scope.test.ts +283 -1
  203. package/src/access-service-raw-excerpt-read-gate.test.ts +53 -0
  204. package/src/access-service.ts +391 -93
  205. package/src/coding/coding-namespace.ts +0 -3
  206. package/src/config.ts +282 -0
  207. package/src/lcm-fallback-read.ts +2 -6
  208. package/src/namespaces/scope-profiles.test.ts +1074 -0
  209. package/src/namespaces/scope-profiles.ts +456 -0
  210. package/src/orchestrator-flush.test.ts +142 -0
  211. package/src/orchestrator-source-attribution.test.ts +73 -0
  212. package/src/orchestrator.ts +835 -163
  213. package/src/semantic-rule-verifier.ts +13 -6
  214. package/src/types.ts +52 -0
  215. package/src/verified-recall.ts +10 -6
  216. package/dist/chunk-55ZMNKMQ.js.map +0 -1
  217. package/dist/chunk-5QD3QD76.js.map +0 -1
  218. package/dist/chunk-KOI765XP.js.map +0 -1
  219. package/dist/chunk-MMJANTJX.js +0 -339
  220. package/dist/chunk-MMJANTJX.js.map +0 -1
  221. package/dist/chunk-NCSJKK23.js.map +0 -1
  222. package/dist/chunk-TDZSSJV4.js.map +0 -1
  223. package/dist/chunk-UCEABZZN.js.map +0 -1
  224. /package/dist/{chunk-PVE7KSQP.js.map → chunk-2BD7DG37.js.map} +0 -0
  225. /package/dist/{chunk-54LOUIBE.js.map → chunk-2MXEVL75.js.map} +0 -0
  226. /package/dist/{chunk-COVZLGMR.js.map → chunk-54XF2FY7.js.map} +0 -0
  227. /package/dist/{chunk-UYNFWZWG.js.map → chunk-AGJKWOKV.js.map} +0 -0
  228. /package/dist/{chunk-A3Y37UWI.js.map → chunk-DIBWFCLA.js.map} +0 -0
  229. /package/dist/{chunk-QDVQ4AN2.js.map → chunk-DR67OK4E.js.map} +0 -0
  230. /package/dist/{chunk-XBIACVCO.js.map → chunk-EC2AYKRX.js.map} +0 -0
  231. /package/dist/{chunk-IQ53ZSXV.js.map → chunk-GCYFUTUC.js.map} +0 -0
  232. /package/dist/{chunk-YYN3LIYA.js.map → chunk-GSHW5VVD.js.map} +0 -0
  233. /package/dist/{chunk-NRBGRZW4.js.map → chunk-IOZ5WBWD.js.map} +0 -0
  234. /package/dist/{chunk-7LWRCOP7.js.map → chunk-LZTFCAKE.js.map} +0 -0
  235. /package/dist/{chunk-TEO46GMM.js.map → chunk-NXCK7DO7.js.map} +0 -0
  236. /package/dist/{chunk-XOFXKASO.js.map → chunk-PEPHBH2W.js.map} +0 -0
  237. /package/dist/{chunk-WDTUYOLS.js.map → chunk-QZRKNA5F.js.map} +0 -0
  238. /package/dist/{chunk-PS3SYNHP.js.map → chunk-R5DB26G6.js.map} +0 -0
  239. /package/dist/{chunk-BGKXTVNG.js.map → chunk-SWDHVH2P.js.map} +0 -0
  240. /package/dist/{chunk-67G4T7KI.js.map → chunk-SXYCVRLK.js.map} +0 -0
  241. /package/dist/{chunk-UCEDY5M7.js.map → chunk-TIJYQXDI.js.map} +0 -0
  242. /package/dist/{chunk-2RCGZ67B.js.map → chunk-VAEAGTEQ.js.map} +0 -0
  243. /package/dist/{chunk-XRKQOQLY.js.map → chunk-WIKMCJUR.js.map} +0 -0
  244. /package/dist/{chunk-KZZ4YAEC.js.map → chunk-WWMHAMAY.js.map} +0 -0
  245. /package/dist/{chunk-OKW6F5S5.js.map → chunk-YEZHZCUO.js.map} +0 -0
  246. /package/dist/{chunk-3XGWCZ63.js.map → chunk-YXLT4EMM.js.map} +0 -0
  247. /package/dist/{chunk-PTMJ2FH2.js.map → chunk-Z6UDTNY6.js.map} +0 -0
@@ -29,7 +29,7 @@ import {
29
29
  import {
30
30
  CompoundingEngine,
31
31
  defaultTierMigrationCycleBudget
32
- } from "./chunk-UYNFWZWG.js";
32
+ } from "./chunk-AGJKWOKV.js";
33
33
  import {
34
34
  SharedContextManager
35
35
  } from "./chunk-DRD2Q7HQ.js";
@@ -56,7 +56,7 @@ import {
56
56
  import {
57
57
  buildTargetedFactRecallSection,
58
58
  shouldRecallTargetedFactEvidence
59
- } from "./chunk-PS3SYNHP.js";
59
+ } from "./chunk-R5DB26G6.js";
60
60
  import {
61
61
  applyTemporalSupersession,
62
62
  normalizeSupersessionKey,
@@ -71,7 +71,7 @@ import {
71
71
  import {
72
72
  buildResponseGuidanceRecallSection,
73
73
  shouldRecallResponseGuidance
74
- } from "./chunk-XBIACVCO.js";
74
+ } from "./chunk-EC2AYKRX.js";
75
75
  import {
76
76
  mergeWithAgentResults,
77
77
  runDirectAgent,
@@ -170,19 +170,19 @@ import {
170
170
  import {
171
171
  buildFocusedListRecallSection,
172
172
  shouldRecallFocusedListEvidence
173
- } from "./chunk-7LWRCOP7.js";
173
+ } from "./chunk-LZTFCAKE.js";
174
174
  import {
175
175
  buildEntityRecallSection,
176
176
  entityRecentTranscriptLookbackHours,
177
177
  readRecentEntityTranscriptEntries
178
- } from "./chunk-NRBGRZW4.js";
178
+ } from "./chunk-IOZ5WBWD.js";
179
179
  import {
180
180
  buildEventOrderRecallSection,
181
181
  shouldRecallEventOrderEvidence
182
182
  } from "./chunk-UU6MVCJ6.js";
183
183
  import {
184
184
  buildExplicitCueRecallSection
185
- } from "./chunk-3XGWCZ63.js";
185
+ } from "./chunk-YXLT4EMM.js";
186
186
  import {
187
187
  formatDaySummaryMemories
188
188
  } from "./chunk-WLEB7WCG.js";
@@ -210,7 +210,7 @@ import {
210
210
  materializeAfterSemanticConsolidation,
211
211
  parseConsolidationResponse,
212
212
  parseOperatorAwareConsolidationResponse
213
- } from "./chunk-BGKXTVNG.js";
213
+ } from "./chunk-SWDHVH2P.js";
214
214
  import {
215
215
  normalizeReplaySessionKey
216
216
  } from "./chunk-2PRQG7PV.js";
@@ -218,14 +218,16 @@ import {
218
218
  RoutingRulesStore
219
219
  } from "./chunk-X6IRLNOO.js";
220
220
  import {
221
+ compareVerifiedEpisodeResults,
221
222
  searchVerifiedEpisodes
222
- } from "./chunk-NCSJKK23.js";
223
+ } from "./chunk-JSVFEHLL.js";
223
224
  import {
224
225
  ThreadingManager
225
226
  } from "./chunk-W4RVMTHR.js";
226
227
  import {
228
+ compareVerifiedSemanticRuleResults,
227
229
  searchVerifiedSemanticRules
228
- } from "./chunk-UCEABZZN.js";
230
+ } from "./chunk-TFFZUFEP.js";
229
231
  import {
230
232
  searchWorkProductLedgerEntries
231
233
  } from "./chunk-ZRWB5D4H.js";
@@ -239,7 +241,7 @@ import {
239
241
  NamespaceStorageRouter,
240
242
  resolveDefaultNamespaceRoot,
241
243
  resolveNamespaceStorageRoot
242
- } from "./chunk-XRKQOQLY.js";
244
+ } from "./chunk-WIKMCJUR.js";
243
245
  import {
244
246
  isAboveImportanceThreshold,
245
247
  scoreImportance
@@ -305,9 +307,11 @@ import {
305
307
  import {
306
308
  clusterByKey,
307
309
  combineNamespaces,
310
+ expandScopeProfileReadNamespaces,
308
311
  lcmReadSessionIdsForNamespaces,
309
- resolveCodingNamespaceOverlay
310
- } from "./chunk-MMJANTJX.js";
312
+ resolveCodingNamespaceOverlay,
313
+ resolveScopeProfilePlan
314
+ } from "./chunk-GYSYLGNE.js";
311
315
  import {
312
316
  listTrustZoneRecords,
313
317
  searchTrustZoneRecords
@@ -317,7 +321,7 @@ import {
317
321
  } from "./chunk-FF4KLI5W.js";
318
322
  import {
319
323
  buildXraySnapshot
320
- } from "./chunk-54LOUIBE.js";
324
+ } from "./chunk-2MXEVL75.js";
321
325
  import {
322
326
  NamespaceSearchRouter
323
327
  } from "./chunk-EKQMQQ3U.js";
@@ -357,7 +361,7 @@ import {
357
361
  } from "./chunk-Y56J7CXW.js";
358
362
  import {
359
363
  buildChainFollowupGenerator
360
- } from "./chunk-PTMJ2FH2.js";
364
+ } from "./chunk-Z6UDTNY6.js";
361
365
  import {
362
366
  ALL_CATEGORY_DIRS,
363
367
  ContentHashIndex,
@@ -368,7 +372,7 @@ import {
368
372
  normalizeEntityName,
369
373
  parseEntityFile,
370
374
  stripAttributesSuffix
371
- } from "./chunk-TEO46GMM.js";
375
+ } from "./chunk-NXCK7DO7.js";
372
376
  import {
373
377
  isValidTranscriptDate,
374
378
  loadSpeakerRegistry,
@@ -383,7 +387,7 @@ import {
383
387
  } from "./chunk-J6A3CX5N.js";
384
388
  import {
385
389
  confidenceTier
386
- } from "./chunk-TDZSSJV4.js";
390
+ } from "./chunk-AZBV4RRY.js";
387
391
  import {
388
392
  inferMemoryStatus,
389
393
  isActiveMemoryStatus
@@ -4328,6 +4332,7 @@ var Orchestrator = class _Orchestrator {
4328
4332
  _peerIdBySession = /* @__PURE__ */ new Map();
4329
4333
  routingRulesStore = null;
4330
4334
  contentHashIndex = null;
4335
+ contentHashIndexesByStorageDir = /* @__PURE__ */ new Map();
4331
4336
  artifactSourceStatusCache = /* @__PURE__ */ new WeakMap();
4332
4337
  static ARTIFACT_STATUS_CACHE_TTL_MS = 6e4;
4333
4338
  // Access tracking buffer (Phase 1A)
@@ -4793,6 +4798,9 @@ var Orchestrator = class _Orchestrator {
4793
4798
  return Object.keys(searchOptions).length > 0 ? searchOptions : void 0;
4794
4799
  }
4795
4800
  async searchAcrossNamespaces(options) {
4801
+ if (this.config.namespacesEnabled && options.namespaces !== void 0 && options.namespaces.length === 0) {
4802
+ return [];
4803
+ }
4796
4804
  const namespaces = this.config.namespacesEnabled ? Array.from(
4797
4805
  new Set(
4798
4806
  (options.namespaces?.length ? options.namespaces : this.configuredNamespaces()).map((value) => value.trim()).filter(Boolean)
@@ -4849,6 +4857,57 @@ var Orchestrator = class _Orchestrator {
4849
4857
  }
4850
4858
  invalidateLiveContentHashIndex() {
4851
4859
  this.contentHashIndex = null;
4860
+ this.contentHashIndexesByStorageDir.clear();
4861
+ }
4862
+ async contentHashIndexForStorage(targetStorage) {
4863
+ if (!this.config.factDeduplicationEnabled) return null;
4864
+ if (targetStorage.dir === this.storage.dir) {
4865
+ if (!this.contentHashIndex) {
4866
+ this.contentHashIndex = this.storage.createContentHashIndex();
4867
+ await this.contentHashIndex.load();
4868
+ }
4869
+ return this.contentHashIndex;
4870
+ }
4871
+ const cached = this.contentHashIndexesByStorageDir.get(targetStorage.dir);
4872
+ if (cached) return cached;
4873
+ const index = targetStorage.createContentHashIndex();
4874
+ await index.load();
4875
+ this.contentHashIndexesByStorageDir.set(targetStorage.dir, index);
4876
+ log.info(
4877
+ `content-hash dedup: loaded ${index.size} hashes for storage ${targetStorage.dir}`
4878
+ );
4879
+ return index;
4880
+ }
4881
+ async hasContentHashDedup(targetStorage, content) {
4882
+ const index = await this.contentHashIndexForStorage(targetStorage);
4883
+ return index ? index.has(content) : false;
4884
+ }
4885
+ async addContentHashDedup(targetStorage, content) {
4886
+ const index = await this.contentHashIndexForStorage(targetStorage);
4887
+ if (!index) return;
4888
+ index.add(content);
4889
+ }
4890
+ async removeContentHashForMemory(targetStorage, memory, context) {
4891
+ const index = await this.contentHashIndexForStorage(targetStorage);
4892
+ if (!index) return;
4893
+ if (memory.frontmatter.contentHash) {
4894
+ index.removeByHash(memory.frontmatter.contentHash);
4895
+ return;
4896
+ }
4897
+ log.warn(
4898
+ `[${context}] removing hash for legacy memory ${memory.frontmatter.id ?? "(unknown)"} via content fallback - no contentHash in frontmatter`
4899
+ );
4900
+ index.remove(memory.content);
4901
+ }
4902
+ async saveContentHashIndexes() {
4903
+ const indexes = /* @__PURE__ */ new Set();
4904
+ if (this.contentHashIndex) indexes.add(this.contentHashIndex);
4905
+ for (const index of this.contentHashIndexesByStorageDir.values()) {
4906
+ indexes.add(index);
4907
+ }
4908
+ for (const index of indexes) {
4909
+ await index.save();
4910
+ }
4852
4911
  }
4853
4912
  constructor(config) {
4854
4913
  this.config = config;
@@ -6128,16 +6187,11 @@ ${doc.content}` : doc.content,
6128
6187
  relatedMemoryIds: [canonicalId]
6129
6188
  });
6130
6189
  if (archiveResult) {
6131
- if (this.contentHashIndex) {
6132
- if (m.frontmatter.contentHash) {
6133
- this.contentHashIndex.removeByHash(m.frontmatter.contentHash);
6134
- } else {
6135
- log.warn(
6136
- `[semantic-consolidation] removing hash for legacy memory ${m.frontmatter.id ?? "(unknown)"} via content fallback \u2014 no contentHash in frontmatter`
6137
- );
6138
- this.contentHashIndex.remove(m.content);
6139
- }
6140
- }
6190
+ await this.removeContentHashForMemory(
6191
+ targetStorage,
6192
+ m,
6193
+ "semantic-consolidation"
6194
+ );
6141
6195
  try {
6142
6196
  await this.embeddingFallback.removeFromIndex(m.frontmatter.id);
6143
6197
  if (this.config.queryAwareIndexingEnabled && m.path && m.frontmatter?.created) {
@@ -6173,8 +6227,8 @@ ${doc.content}` : doc.content,
6173
6227
  }
6174
6228
  }
6175
6229
  }
6176
- if (result.memoriesArchived > 0 && this.contentHashIndex) {
6177
- await this.contentHashIndex.save().catch(
6230
+ if (result.memoriesArchived > 0) {
6231
+ await this.saveContentHashIndexes().catch(
6178
6232
  (err) => log.warn(
6179
6233
  `[semantic-consolidation] content-hash index save failed: ${err}`
6180
6234
  )
@@ -7082,7 +7136,8 @@ ${r.snippet.trim()}
7082
7136
  this.enqueueDirectAnswerObservation(
7083
7137
  prompt,
7084
7138
  sessionKey,
7085
- options.namespace?.trim() || void 0
7139
+ options.namespace?.trim() || void 0,
7140
+ options.principalOverride
7086
7141
  );
7087
7142
  } catch (err) {
7088
7143
  log.debug(`direct-answer observation setup failed: ${err}`);
@@ -7137,17 +7192,32 @@ ${r.snippet.trim()}
7137
7192
  if (timeoutHandle) clearTimeout(timeoutHandle);
7138
7193
  }
7139
7194
  }
7140
- enqueueDirectAnswerObservation(prompt, sessionKey, namespaceOverride) {
7195
+ enqueueDirectAnswerObservation(prompt, sessionKey, namespaceOverride, principalOverride) {
7141
7196
  const expectedSnapshot = this.lastRecall.get(sessionKey);
7142
7197
  if (expectedSnapshot === null) return;
7143
7198
  if (expectedSnapshot.plannerMode === "no_recall") return;
7144
- const principal = resolvePrincipal(sessionKey, this.config);
7199
+ const principal = principalOverride ?? resolvePrincipal(sessionKey, this.config);
7145
7200
  const observationCodingOverlay = namespaceOverride && canReadNamespace(principal, namespaceOverride, this.config) ? null : this.applyCodingRecallOverlay(sessionKey);
7146
7201
  const observationPrincipalSelf = defaultNamespaceForPrincipal(principal, this.config);
7147
7202
  const observationCodingSelf = observationCodingOverlay ? combineNamespaces(observationPrincipalSelf, observationCodingOverlay.namespace) : null;
7203
+ const observationScopeProfilePlan = namespaceOverride && canReadNamespace(principal, namespaceOverride, this.config) ? null : resolveScopeProfilePlan({
7204
+ config: this.config,
7205
+ principal,
7206
+ codingContext: sessionKey ? this.getCodingContextForSession(sessionKey) : null,
7207
+ codingOverlay: observationCodingOverlay
7208
+ });
7148
7209
  let observationNamespaces;
7149
7210
  if (namespaceOverride && canReadNamespace(principal, namespaceOverride, this.config)) {
7150
7211
  observationNamespaces = [namespaceOverride];
7212
+ } else if (observationScopeProfilePlan) {
7213
+ observationNamespaces = expandScopeProfileReadNamespaces({
7214
+ profilePlan: observationScopeProfilePlan,
7215
+ principalSelfNamespace: observationScopeProfilePlan.baseNamespace,
7216
+ config: this.config,
7217
+ principal,
7218
+ codingOverlay: observationCodingOverlay,
7219
+ legacyRecallNamespaces: recallNamespacesForPrincipal(principal, this.config)
7220
+ });
7151
7221
  } else if (observationCodingOverlay && observationCodingSelf) {
7152
7222
  const base = recallNamespacesForPrincipal(principal, this.config);
7153
7223
  const mapped = base.map(
@@ -8280,10 +8350,26 @@ ${r.snippet.trim()}
8280
8350
  const codingOverlay = namespaceOverride ? null : this.applyCodingRecallOverlay(sessionKey);
8281
8351
  const principalSelfNamespace = defaultNamespaceForPrincipal(principal, this.config);
8282
8352
  const codingSelfNamespace = codingOverlay ? combineNamespaces(principalSelfNamespace, codingOverlay.namespace) : null;
8283
- const selfNamespace = namespaceOverride ?? codingSelfNamespace ?? principalSelfNamespace;
8353
+ const scopeProfilePlan = namespaceOverride ? null : resolveScopeProfilePlan({
8354
+ config: this.config,
8355
+ principal,
8356
+ codingContext: sessionKey ? this.getCodingContextForSession(sessionKey) : null,
8357
+ codingOverlay
8358
+ });
8359
+ const profileEffectiveNamespace = scopeProfilePlan?.writeNamespace || scopeProfilePlan?.readNamespaces[0];
8360
+ const selfNamespace = namespaceOverride ?? profileEffectiveNamespace ?? codingSelfNamespace ?? principalSelfNamespace;
8284
8361
  let recallNamespaces;
8285
8362
  if (namespaceOverride) {
8286
8363
  recallNamespaces = [namespaceOverride];
8364
+ } else if (scopeProfilePlan) {
8365
+ recallNamespaces = expandScopeProfileReadNamespaces({
8366
+ profilePlan: scopeProfilePlan,
8367
+ principalSelfNamespace: scopeProfilePlan.baseNamespace,
8368
+ config: this.config,
8369
+ principal,
8370
+ codingOverlay,
8371
+ legacyRecallNamespaces: readableRecallNamespaces
8372
+ });
8287
8373
  } else if (codingOverlay && codingSelfNamespace) {
8288
8374
  const mapped = readableRecallNamespaces.map(
8289
8375
  (ns) => ns === principalSelfNamespace ? codingSelfNamespace : ns
@@ -8295,10 +8381,12 @@ ${r.snippet.trim()}
8295
8381
  } else {
8296
8382
  recallNamespaces = readableRecallNamespaces;
8297
8383
  }
8298
- const codingOverlaySelfReadable = codingOverlay !== null && readableRecallNamespaces.includes(principalSelfNamespace);
8384
+ const codingOverlaySelfReadable = codingOverlay !== null && (scopeProfilePlan ? scopeProfilePlan.layers.some((layer) => layer.id === "userProject" && layer.readable) : readableRecallNamespaces.includes(principalSelfNamespace));
8299
8385
  let lcmReadNamespaces;
8300
8386
  if (namespaceOverride) {
8301
8387
  lcmReadNamespaces = [namespaceOverride];
8388
+ } else if (scopeProfilePlan) {
8389
+ lcmReadNamespaces = recallNamespaces;
8302
8390
  } else if (codingOverlay && codingSelfNamespace && codingOverlaySelfReadable) {
8303
8391
  const fallbackNs = codingOverlay.readFallbacks.map(
8304
8392
  (fallback) => combineNamespaces(principalSelfNamespace, fallback)
@@ -8307,7 +8395,7 @@ ${r.snippet.trim()}
8307
8395
  } else {
8308
8396
  lcmReadNamespaces = [this.config.defaultNamespace];
8309
8397
  }
8310
- const lcmReadSessionIds = lcmReadSessionIdsForNamespaces(
8398
+ const lcmReadSessionIds = scopeProfilePlan && !sessionKey ? [] : lcmReadSessionIdsForNamespaces(
8311
8399
  lcmReadNamespaces,
8312
8400
  sessionKey,
8313
8401
  this.config.defaultNamespace
@@ -8480,7 +8568,144 @@ ${r.snippet.trim()}
8480
8568
  });
8481
8569
  return "";
8482
8570
  }
8483
- const profileStorage = await this.storageRouter.storageFor(selfNamespace);
8571
+ const profileStorageNamespaces = scopeProfilePlan ? recallNamespaces : [selfNamespace];
8572
+ const profileStorages = await Promise.all(
8573
+ profileStorageNamespaces.map((namespace) => this.storageRouter.storageFor(namespace))
8574
+ );
8575
+ const emptyProfileStorage = new Proxy(
8576
+ { dir: path4.join(this.config.memoryDir, ".empty-scope-profile") },
8577
+ {
8578
+ get(target, prop) {
8579
+ if (prop in target) return target[prop];
8580
+ if (prop === "readProfile") return async () => "";
8581
+ if (prop === "readQuestions" || prop === "listEntityNames" || prop === "readContinuityIncidents")
8582
+ return async () => [];
8583
+ if (prop === "readIdentityAnchor" || prop === "readIdentityImprovementLoops")
8584
+ return async () => "";
8585
+ if (prop === "readEntity" || prop === "readMemoryByPath")
8586
+ return async () => null;
8587
+ return async () => [];
8588
+ }
8589
+ }
8590
+ );
8591
+ const profileStorage = profileStorages.length <= 1 ? profileStorages[0] ?? emptyProfileStorage : new Proxy(profileStorages[0], {
8592
+ get(target, prop) {
8593
+ if (prop === "readProfile") {
8594
+ return async () => {
8595
+ for (const storage of profileStorages) {
8596
+ const profile2 = await storage.readProfile();
8597
+ if (profile2.trim().length > 0) return profile2;
8598
+ }
8599
+ return "";
8600
+ };
8601
+ }
8602
+ if (prop === "readQuestions") {
8603
+ return async (...args) => {
8604
+ const merged = [];
8605
+ const seen = /* @__PURE__ */ new Set();
8606
+ const priorityOf = (question) => {
8607
+ const priority = Number(question?.priority ?? 0);
8608
+ return Number.isFinite(priority) ? priority : 0;
8609
+ };
8610
+ for (const storage of profileStorages) {
8611
+ const questions = await storage.readQuestions(...args);
8612
+ for (const question of questions) {
8613
+ const key = typeof question === "string" ? question : JSON.stringify(question);
8614
+ if (seen.has(key)) continue;
8615
+ seen.add(key);
8616
+ merged.push(question);
8617
+ }
8618
+ }
8619
+ return merged.sort(
8620
+ (left, right) => priorityOf(right) - priorityOf(left) || String(left?.id ?? "").localeCompare(String(right?.id ?? ""))
8621
+ );
8622
+ };
8623
+ }
8624
+ if (prop === "readIdentityAnchor") {
8625
+ return async () => {
8626
+ for (const storage of profileStorages) {
8627
+ const anchor = await storage.readIdentityAnchor() ?? "";
8628
+ if (anchor.trim().length > 0) return anchor;
8629
+ }
8630
+ return "";
8631
+ };
8632
+ }
8633
+ if (prop === "readIdentityImprovementLoops") {
8634
+ return async () => {
8635
+ const sections = [];
8636
+ const seen = /* @__PURE__ */ new Set();
8637
+ for (const storage of profileStorages) {
8638
+ const loops = (await storage.readIdentityImprovementLoops() ?? "").trim();
8639
+ if (!loops || seen.has(loops)) continue;
8640
+ seen.add(loops);
8641
+ sections.push(loops);
8642
+ }
8643
+ return sections.join("\n\n");
8644
+ };
8645
+ }
8646
+ if (prop === "readContinuityIncidents") {
8647
+ return async (...args) => {
8648
+ const limit = typeof args[0] === "number" && Number.isFinite(args[0]) ? Math.max(0, args[0]) : void 0;
8649
+ const incidents = [];
8650
+ const seen = /* @__PURE__ */ new Set();
8651
+ const incidentTime = (incident) => {
8652
+ const raw = incident?.updatedAt ?? incident?.openedAt ?? incident?.createdAt;
8653
+ const parsed = typeof raw === "string" ? Date.parse(raw) : Number.NaN;
8654
+ return Number.isFinite(parsed) ? parsed : 0;
8655
+ };
8656
+ for (const storage of profileStorages) {
8657
+ for (const incident of await storage.readContinuityIncidents(...args)) {
8658
+ const key = JSON.stringify(incident);
8659
+ if (seen.has(key)) continue;
8660
+ seen.add(key);
8661
+ incidents.push(incident);
8662
+ }
8663
+ }
8664
+ incidents.sort(
8665
+ (left, right) => incidentTime(right) - incidentTime(left) || String(left?.id ?? "").localeCompare(String(right?.id ?? ""))
8666
+ );
8667
+ return limit === void 0 ? incidents : incidents.slice(0, limit);
8668
+ };
8669
+ }
8670
+ if (prop === "listEntityNames") {
8671
+ return async (...args) => {
8672
+ const names = /* @__PURE__ */ new Set();
8673
+ for (const storage of profileStorages) {
8674
+ for (const name of await storage.listEntityNames(...args)) names.add(name);
8675
+ }
8676
+ return [...names];
8677
+ };
8678
+ }
8679
+ if (prop === "readEntity" || prop === "readMemoryByPath") {
8680
+ return async (...args) => {
8681
+ for (const storage of profileStorages) {
8682
+ const value = await storage[prop](...args);
8683
+ if (value) return value;
8684
+ }
8685
+ return null;
8686
+ };
8687
+ }
8688
+ if (prop === "readAllMemories") {
8689
+ return async (...args) => {
8690
+ const memories = [];
8691
+ const seen = /* @__PURE__ */ new Set();
8692
+ for (const storage of profileStorages) {
8693
+ for (const memory of await storage.readAllMemories(...args)) {
8694
+ const key = String(memory?.path ?? memory?.frontmatter?.id ?? JSON.stringify(memory));
8695
+ if (seen.has(key)) continue;
8696
+ seen.add(key);
8697
+ memories.push(memory);
8698
+ }
8699
+ }
8700
+ return memories;
8701
+ };
8702
+ }
8703
+ return target[prop];
8704
+ }
8705
+ });
8706
+ const profileStorageDirs = Array.from(
8707
+ new Set(profileStorages.map((storage) => storage.dir).filter((dir) => typeof dir === "string" && dir.length > 0))
8708
+ );
8484
8709
  throwIfRecallAborted(options.abortSignal);
8485
8710
  if (this.namespaceCatalog.enabled && recallResultLimit > 0 && !options.abortSignal?.aborted) {
8486
8711
  for (const ns of recallNamespaces) this.markCatalogRead(ns);
@@ -8492,6 +8717,8 @@ ${r.snippet.trim()}
8492
8717
  ))
8493
8718
  return null;
8494
8719
  if (!this.sharedContext) return null;
8720
+ if (scopeProfilePlan && !(scopeProfilePlan.profile.readOrder.includes("serverShared") && scopeProfilePlan.readNamespaces.includes(this.config.sharedNamespace)))
8721
+ return null;
8495
8722
  const t0 = Date.now();
8496
8723
  const [priorities, roundtable, crossSignals] = await Promise.all([
8497
8724
  this.sharedContext.readPriorities(),
@@ -8716,13 +8943,52 @@ ${lines.join("\n\n")}`;
8716
8943
  if (!this.config.knowledgeIndexEnabled) return null;
8717
8944
  const t0 = Date.now();
8718
8945
  try {
8719
- const ki = await this.storage.buildKnowledgeIndex(this.config, {
8720
- maxEntities: this.getRecallSectionNumber(
8721
- "knowledge-index",
8722
- "maxEntities"
8723
- ),
8724
- maxChars: this.getRecallSectionNumber("knowledge-index", "maxChars")
8725
- });
8946
+ const knowledgeIndexMaxChars = this.getRecallSectionNumber("knowledge-index", "maxChars") ?? this.config.knowledgeIndexMaxChars;
8947
+ const knowledgeIndexMaxEntities = this.getRecallSectionNumber("knowledge-index", "maxEntities") ?? this.config.knowledgeIndexMaxEntities;
8948
+ const knowledgeIndexOptions = {
8949
+ maxEntities: knowledgeIndexMaxEntities,
8950
+ maxChars: knowledgeIndexMaxChars
8951
+ };
8952
+ const ki = scopeProfilePlan ? await (async () => {
8953
+ const perLayerOptions = {
8954
+ ...knowledgeIndexOptions,
8955
+ maxEntities: Number.MAX_SAFE_INTEGER,
8956
+ maxChars: Number.MAX_SAFE_INTEGER
8957
+ };
8958
+ const results = await Promise.all(
8959
+ profileStorages.map(
8960
+ (storage) => storage.buildKnowledgeIndex(this.config, perLayerOptions)
8961
+ )
8962
+ );
8963
+ const sections = results.map((result) => result.result.trim()).filter((section) => section.length > 0);
8964
+ const maxRows = Math.max(0, Math.floor(knowledgeIndexMaxEntities));
8965
+ const rows = [];
8966
+ let header = null;
8967
+ for (const section of sections) {
8968
+ const lines = section.split("\n").map((line) => line.trimEnd()).filter((line) => line.length > 0);
8969
+ const tableHeaderIndex = lines.findIndex(
8970
+ (line) => line.startsWith("| Entity |")
8971
+ );
8972
+ if (tableHeaderIndex === -1) continue;
8973
+ header ??= lines.slice(0, tableHeaderIndex + 2);
8974
+ for (const row of lines.slice(tableHeaderIndex + 2)) {
8975
+ if (!row.startsWith("|")) continue;
8976
+ if (rows.length >= maxRows) break;
8977
+ rows.push(row);
8978
+ }
8979
+ if (rows.length >= maxRows) break;
8980
+ }
8981
+ const merged = header && rows.length > 0 ? `${header.join("\n")}
8982
+ ${rows.join("\n")}
8983
+ ` : "";
8984
+ return {
8985
+ result: this.truncateRecallSectionToBudget(
8986
+ merged,
8987
+ knowledgeIndexMaxChars
8988
+ ),
8989
+ cached: results.every((result) => result.cached)
8990
+ };
8991
+ })() : await this.storage.buildKnowledgeIndex(this.config, knowledgeIndexOptions);
8726
8992
  recordRecallSectionMetric({
8727
8993
  section: "ki",
8728
8994
  priority: "core",
@@ -9089,15 +9355,30 @@ ${lines.join("\n\n")}`;
9089
9355
  });
9090
9356
  return null;
9091
9357
  }
9092
- const results = await searchHarmonicRetrieval({
9093
- memoryDir: this.config.memoryDir,
9094
- abstractionNodeStoreDir: this.config.abstractionNodeStoreDir,
9095
- query: retrievalQuery,
9096
- maxResults,
9097
- sessionKey,
9098
- anchorsEnabled: this.config.abstractionAnchorsEnabled,
9099
- abortSignal: harmonicRetrievalAbort.signal
9100
- });
9358
+ const harmonicSearchDirs = scopeProfilePlan ? profileStorageDirs : [this.config.memoryDir];
9359
+ const harmonicResultsByDir = await Promise.all(
9360
+ harmonicSearchDirs.map(
9361
+ (memoryDir) => searchHarmonicRetrieval({
9362
+ memoryDir,
9363
+ abstractionNodeStoreDir: scopeProfilePlan ? void 0 : this.config.abstractionNodeStoreDir,
9364
+ query: retrievalQuery,
9365
+ maxResults,
9366
+ sessionKey,
9367
+ anchorsEnabled: this.config.abstractionAnchorsEnabled,
9368
+ abortSignal: harmonicRetrievalAbort.signal
9369
+ })
9370
+ )
9371
+ );
9372
+ const harmonicByNodeId = /* @__PURE__ */ new Map();
9373
+ for (const result of harmonicResultsByDir.flat()) {
9374
+ const existing = harmonicByNodeId.get(result.node.nodeId);
9375
+ if (!existing || result.score > existing.score) {
9376
+ harmonicByNodeId.set(result.node.nodeId, result);
9377
+ }
9378
+ }
9379
+ const results = [...harmonicByNodeId.values()].sort(
9380
+ (left, right) => right.score - left.score || right.anchorScore - left.anchorScore || right.node.recordedAt.localeCompare(left.node.recordedAt) || left.node.nodeId.localeCompare(right.node.nodeId)
9381
+ ).slice(0, maxResults);
9101
9382
  recordRecallSectionMetric({
9102
9383
  section: "harmonicRetrieval",
9103
9384
  priority: "enrichment",
@@ -9143,11 +9424,28 @@ ${lines.join("\n\n")}`;
9143
9424
  const VERIFIED_RECALL_TIMEOUT_MS = 15e3;
9144
9425
  let timeoutHandle;
9145
9426
  const results = await Promise.race([
9146
- searchVerifiedEpisodes({
9147
- memoryDir: profileStorage.dir,
9148
- query: retrievalQuery,
9149
- maxResults,
9150
- boxRecallDays: this.config.boxRecallDays
9427
+ Promise.all(
9428
+ profileStorageDirs.map(
9429
+ (memoryDir) => searchVerifiedEpisodes({
9430
+ memoryDir,
9431
+ query: retrievalQuery,
9432
+ maxResults,
9433
+ boxRecallDays: this.config.boxRecallDays
9434
+ }).catch((err) => {
9435
+ log.debug(`verified recall directory scan failed: ${err}`);
9436
+ return [];
9437
+ })
9438
+ )
9439
+ ).then((groups) => {
9440
+ const merged = [];
9441
+ const seen = /* @__PURE__ */ new Set();
9442
+ for (const result of groups.flat()) {
9443
+ const key = result.box.id || JSON.stringify(result);
9444
+ if (seen.has(key)) continue;
9445
+ seen.add(key);
9446
+ merged.push(result);
9447
+ }
9448
+ return merged.sort(compareVerifiedEpisodeResults).slice(0, maxResults);
9151
9449
  }),
9152
9450
  new Promise((resolve) => {
9153
9451
  timeoutHandle = setTimeout(
@@ -9206,10 +9504,27 @@ ${lines.join("\n\n")}`;
9206
9504
  const VERIFIED_RULES_TIMEOUT_MS = 15e3;
9207
9505
  let rulesTimeoutHandle;
9208
9506
  const results = await Promise.race([
9209
- searchVerifiedSemanticRules({
9210
- memoryDir: this.config.memoryDir,
9211
- query: retrievalQuery,
9212
- maxResults
9507
+ Promise.all(
9508
+ profileStorageDirs.map(
9509
+ (memoryDir) => searchVerifiedSemanticRules({
9510
+ memoryDir,
9511
+ query: retrievalQuery,
9512
+ maxResults
9513
+ }).catch((err) => {
9514
+ log.debug(`verified rules directory scan failed: ${err}`);
9515
+ return [];
9516
+ })
9517
+ )
9518
+ ).then((groups) => {
9519
+ const merged = [];
9520
+ const seen = /* @__PURE__ */ new Set();
9521
+ for (const result of groups.flat()) {
9522
+ const key = result.rule.frontmatter.id || result.rule.path || JSON.stringify(result);
9523
+ if (seen.has(key)) continue;
9524
+ seen.add(key);
9525
+ merged.push(result);
9526
+ }
9527
+ return merged.sort(compareVerifiedSemanticRuleResults).slice(0, maxResults);
9213
9528
  }),
9214
9529
  new Promise((resolve) => {
9215
9530
  rulesTimeoutHandle = setTimeout(
@@ -9265,13 +9580,28 @@ ${lines.join("\n\n")}`;
9265
9580
  });
9266
9581
  return null;
9267
9582
  }
9268
- const results = await searchWorkProductLedgerEntries({
9269
- memoryDir: this.config.memoryDir,
9270
- workProductLedgerDir: this.config.workProductLedgerDir,
9271
- query: retrievalQuery,
9272
- maxResults,
9273
- sessionKey
9274
- });
9583
+ const workProductSearchDirs = scopeProfilePlan ? profileStorageDirs : [this.config.memoryDir];
9584
+ const workProductResultsByDir = await Promise.all(
9585
+ workProductSearchDirs.map(
9586
+ (memoryDir) => searchWorkProductLedgerEntries({
9587
+ memoryDir,
9588
+ workProductLedgerDir: scopeProfilePlan ? void 0 : this.config.workProductLedgerDir,
9589
+ query: retrievalQuery,
9590
+ maxResults,
9591
+ sessionKey
9592
+ })
9593
+ )
9594
+ );
9595
+ const workProductByEntryId = /* @__PURE__ */ new Map();
9596
+ for (const result of workProductResultsByDir.flat()) {
9597
+ const existing = workProductByEntryId.get(result.entry.entryId);
9598
+ if (!existing || result.score > existing.score) {
9599
+ workProductByEntryId.set(result.entry.entryId, result);
9600
+ }
9601
+ }
9602
+ const results = [...workProductByEntryId.values()].sort(
9603
+ (left, right) => right.score - left.score || right.entry.recordedAt.localeCompare(left.entry.recordedAt) || left.entry.entryId.localeCompare(right.entry.entryId)
9604
+ ).slice(0, maxResults);
9275
9605
  recordRecallSectionMetric({
9276
9606
  section: "workProducts",
9277
9607
  priority: "core",
@@ -9445,22 +9775,50 @@ ${lines.join("\n\n")}`;
9445
9775
  }
9446
9776
  const maxPerAgent = this.config.parallelMaxResultsPerAgent;
9447
9777
  const specializedAgentPromise = !queryAwarePrefilterIsEmpty && this.config.parallelRetrievalEnabled && maxPerAgent > 0 ? Promise.all([
9448
- shouldRunAgent("direct", retrievalQuery, 0) ? runDirectAgent(
9449
- retrievalQuery,
9450
- profileStorage.dir,
9451
- maxPerAgent
9452
- ).catch((err) => {
9453
- log.debug(`DirectAgent pre-start failed: ${err}`);
9454
- return [];
9778
+ shouldRunAgent("direct", retrievalQuery, 0) ? Promise.all(
9779
+ profileStorageDirs.map(
9780
+ (memoryDir) => runDirectAgent(
9781
+ retrievalQuery,
9782
+ memoryDir,
9783
+ maxPerAgent
9784
+ ).catch((err) => {
9785
+ log.debug(`DirectAgent pre-start failed: ${err}`);
9786
+ return [];
9787
+ })
9788
+ )
9789
+ ).then((groups) => {
9790
+ const merged = [];
9791
+ const seen = /* @__PURE__ */ new Set();
9792
+ for (const result of groups.flat()) {
9793
+ const key = result.path ?? JSON.stringify(result);
9794
+ if (seen.has(key)) continue;
9795
+ seen.add(key);
9796
+ merged.push(result);
9797
+ }
9798
+ return merged.sort((a, b) => b.score - a.score).slice(0, maxPerAgent);
9455
9799
  }) : Promise.resolve([]),
9456
- shouldRunAgent("temporal", retrievalQuery, 0) ? runTemporalAgent(
9457
- retrievalQuery,
9458
- this.config.memoryDir,
9459
- maxPerAgent,
9460
- queryAwarePrefilter.candidatePaths
9461
- ).catch((err) => {
9462
- log.debug(`TemporalAgent pre-start failed: ${err}`);
9463
- return [];
9800
+ shouldRunAgent("temporal", retrievalQuery, 0) ? Promise.all(
9801
+ profileStorageDirs.map(
9802
+ (memoryDir) => runTemporalAgent(
9803
+ retrievalQuery,
9804
+ memoryDir,
9805
+ maxPerAgent,
9806
+ queryAwarePrefilter.candidatePaths
9807
+ ).catch((err) => {
9808
+ log.debug(`TemporalAgent pre-start failed for ${memoryDir}: ${err}`);
9809
+ return [];
9810
+ })
9811
+ )
9812
+ ).then((groups) => {
9813
+ const merged = [];
9814
+ const seen = /* @__PURE__ */ new Set();
9815
+ for (const result of groups.flat()) {
9816
+ const key = result.path ?? JSON.stringify(result);
9817
+ if (seen.has(key)) continue;
9818
+ seen.add(key);
9819
+ merged.push(result);
9820
+ }
9821
+ return merged.sort((a, b) => b.score - a.score).slice(0, maxPerAgent);
9464
9822
  }) : Promise.resolve([])
9465
9823
  ]) : null;
9466
9824
  try {
@@ -9935,7 +10293,27 @@ ${formatted}`;
9935
10293
  this.isRecallSectionEnabled(
9936
10294
  "memory-boxes",
9937
10295
  this.config.memoryBoxesEnabled === true
9938
- ) && this.config.memoryBoxesEnabled && this.config.boxRecallDays > 0 ? this.boxBuilderFor(profileStorage).readRecentBoxes(this.config.boxRecallDays).catch(() => []) : Promise.resolve([])
10296
+ ) && this.config.memoryBoxesEnabled && this.config.boxRecallDays > 0 ? Promise.all(
10297
+ profileStorages.map(
10298
+ (storage) => this.boxBuilderFor(storage).readRecentBoxes(this.config.boxRecallDays).catch(() => [])
10299
+ )
10300
+ ).then((groups) => {
10301
+ const boxes = [];
10302
+ const seen = /* @__PURE__ */ new Set();
10303
+ for (const box of groups.flat()) {
10304
+ const key = JSON.stringify(box);
10305
+ if (seen.has(key)) continue;
10306
+ seen.add(key);
10307
+ boxes.push(box);
10308
+ }
10309
+ return boxes.sort((a, b) => {
10310
+ const aTime = Date.parse(a.sealedAt ?? "");
10311
+ const bTime = Date.parse(b.sealedAt ?? "");
10312
+ const aRank = Number.isFinite(aTime) ? aTime : 0;
10313
+ const bRank = Number.isFinite(bTime) ? bTime : 0;
10314
+ return bRank - aRank;
10315
+ });
10316
+ }) : Promise.resolve([])
9939
10317
  );
9940
10318
  this.profiler.startSpan("phase-1-parallel", profileTraceId);
9941
10319
  const phase1Start = Date.now();
@@ -12192,7 +12570,41 @@ ${normalized}`).digest("hex");
12192
12570
  };
12193
12571
  }
12194
12572
  const principal = typeof options.principalOverride === "string" && options.principalOverride.length > 0 ? options.principalOverride : resolvePrincipal(sessionKey, this.config);
12195
- const selfNamespace = typeof options.writeNamespaceOverride === "string" && options.writeNamespaceOverride.length > 0 ? options.writeNamespaceOverride : this.applyCodingNamespaceOverlay(
12573
+ const explicitWriteNamespace = typeof options.writeNamespaceOverride === "string" && options.writeNamespaceOverride.length > 0 ? options.writeNamespaceOverride : void 0;
12574
+ const codingContextForWrite = sessionKey ? this.getCodingContextForSession(sessionKey) : null;
12575
+ const codingOverlayForWrite = resolveCodingNamespaceOverlay(
12576
+ codingContextForWrite,
12577
+ this.config.codingMode,
12578
+ this.config.defaultNamespace
12579
+ );
12580
+ const scopeProfileGatePlan = resolveScopeProfilePlan({
12581
+ config: this.config,
12582
+ principal,
12583
+ codingContext: codingContextForWrite,
12584
+ codingOverlay: codingOverlayForWrite
12585
+ });
12586
+ const scopeProfileWritePlan = explicitWriteNamespace ? null : scopeProfileGatePlan;
12587
+ if (scopeProfileWritePlan) {
12588
+ const selectedLayer = scopeProfileWritePlan.layers.find(
12589
+ (layer) => layer.id === scopeProfileWritePlan.writeLayer
12590
+ );
12591
+ const writeNamespaceReadable = scopeProfileWritePlan.readNamespaces.includes(
12592
+ scopeProfileWritePlan.writeNamespace
12593
+ );
12594
+ if (!selectedLayer?.writable || !writeNamespaceReadable) {
12595
+ log.warn(
12596
+ `runExtraction: skipping scope profile ${scopeProfileWritePlan.profileId} because write layer ${scopeProfileWritePlan.writeLayer} is not writable inside the profile read stack`
12597
+ );
12598
+ await clearBuffer();
12599
+ return {
12600
+ status: "skipped",
12601
+ reason: "scope_profile_no_writable_layer",
12602
+ persistedCount: 0,
12603
+ durableOutputCount: 0
12604
+ };
12605
+ }
12606
+ }
12607
+ const selfNamespace = explicitWriteNamespace ?? scopeProfileWritePlan?.writeNamespace ?? this.applyCodingNamespaceOverlay(
12196
12608
  sessionKey,
12197
12609
  defaultNamespaceForPrincipal(principal, this.config)
12198
12610
  );
@@ -12320,7 +12732,8 @@ ${normalized}`).digest("hex");
12320
12732
  { sessionKey, principal, validAt: sourceValidAt },
12321
12733
  // Pass the KNOWN base namespace (NHIdx) so the catalog write touch records the
12322
12734
  // real namespace rather than a guess decoded from the storage dir.
12323
- selfNamespace
12735
+ selfNamespace,
12736
+ scopeProfileGatePlan
12324
12737
  );
12325
12738
  let postPersistMetadataFailed = false;
12326
12739
  meta ??= await storage.loadMeta();
@@ -12748,7 +13161,7 @@ ${normalized}`).digest("hex");
12748
13161
  }
12749
13162
  }
12750
13163
  }
12751
- async persistExtraction(result, storage, threadIdForExtraction, sourceContext, baseNamespace) {
13164
+ async persistExtraction(result, storage, threadIdForExtraction, sourceContext, baseNamespace, scopeProfileWritePlan) {
12752
13165
  const citationEnabled = this.config.inlineSourceAttributionEnabled === true;
12753
13166
  const citationTemplate = this.config.inlineSourceAttributionFormat;
12754
13167
  const citationContextBase = citationEnabled ? {
@@ -12802,22 +13215,128 @@ ${normalized}`).digest("hex");
12802
13215
  "inferred",
12803
13216
  "speculative"
12804
13217
  ];
13218
+ const sharedProfileLayer = scopeProfileWritePlan?.layers.find(
13219
+ (layer) => layer.id === "serverShared" && layer.namespace === this.config.sharedNamespace
13220
+ );
13221
+ const sharedPromotionTarget = scopeProfileWritePlan?.promotionTargets.find(
13222
+ (target) => target.target === "serverShared" && target.namespace === this.config.sharedNamespace
13223
+ );
13224
+ const profileAllowsSharedWrites = !scopeProfileWritePlan || Boolean(
13225
+ scopeProfileWritePlan.profile.readOrder.includes("serverShared") && scopeProfileWritePlan.readNamespaces.includes(this.config.sharedNamespace) && sharedProfileLayer?.readable && sharedProfileLayer.writable && sharedPromotionTarget?.authorized
13226
+ );
13227
+ const profileAutoPromotionAllows = (category, confidence) => {
13228
+ if (!scopeProfileWritePlan) return false;
13229
+ const actualTier = confidenceTier(confidence);
13230
+ const actualRank = confidenceTierOrder.indexOf(actualTier);
13231
+ if (actualRank === -1) return false;
13232
+ const autoPromote = scopeProfileWritePlan.profile.autoPromote;
13233
+ if (!autoPromote.enabled) return false;
13234
+ if (!autoPromote.categories.includes(category)) return false;
13235
+ const minimumRank = confidenceTierOrder.indexOf(autoPromote.minConfidenceTier);
13236
+ return minimumRank !== -1 && actualRank <= minimumRank;
13237
+ };
13238
+ const sharedAutoPromotionAllows = (category, confidence) => {
13239
+ if (!scopeProfileWritePlan) {
13240
+ const actualTier = confidenceTier(confidence);
13241
+ const actualRank = confidenceTierOrder.indexOf(actualTier);
13242
+ if (actualRank === -1) return false;
13243
+ if (!this.config.autoPromoteToSharedEnabled) return false;
13244
+ if (!this.config.autoPromoteToSharedCategories.includes(category))
13245
+ return false;
13246
+ const minimumRank = confidenceTierOrder.indexOf(
13247
+ this.config.autoPromoteMinConfidenceTier
13248
+ );
13249
+ return minimumRank !== -1 && actualRank <= minimumRank;
13250
+ }
13251
+ return scopeProfileWritePlan.profile.autoPromote.targets.includes("serverShared") && profileAutoPromotionAllows(category, confidence);
13252
+ };
12805
13253
  const shouldPromoteToShared = (targetStorage, category, confidence) => {
12806
- if (!this.config.namespacesEnabled || !this.config.autoPromoteToSharedEnabled)
13254
+ if (!this.config.namespacesEnabled || !profileAllowsSharedWrites || !sharedAutoPromotionAllows(category, confidence))
12807
13255
  return false;
12808
13256
  if (this.namespaceFromStorageDir(targetStorage.dir) === this.config.sharedNamespace)
12809
13257
  return false;
12810
- if (!this.config.autoPromoteToSharedCategories.includes(category))
12811
- return false;
12812
- const actualTier = confidenceTier(confidence);
12813
- const actualRank = confidenceTierOrder.indexOf(actualTier);
12814
- const minimumRank = confidenceTierOrder.indexOf(
12815
- this.config.autoPromoteMinConfidenceTier
13258
+ return true;
13259
+ };
13260
+ const promoteMemoryToProfileTargets = async (options) => {
13261
+ if (!scopeProfileWritePlan || !profileAutoPromotionAllows(options.category, options.confidence))
13262
+ return;
13263
+ const autoTargets = new Set(scopeProfileWritePlan.profile.autoPromote.targets);
13264
+ const targets = scopeProfileWritePlan.promotionTargets.filter(
13265
+ (target) => target.target !== "serverShared" && autoTargets.has(target.target) && target.authorized && target.namespace
12816
13266
  );
12817
- if (actualRank === -1 || minimumRank === -1) return false;
12818
- return actualRank <= minimumRank;
13267
+ if (targets.length === 0) return;
13268
+ const rawContent = citationEnabled && hasCitationForTemplate(options.content, citationTemplate) ? stripCitationForTemplate(options.content, citationTemplate) : options.content;
13269
+ const citedContent = applyInlineCitation(rawContent);
13270
+ const sanitizedBase = sanitizeMemoryContent(rawContent);
13271
+ const dedupContent = options.category === "fact" && options.structuredAttributes && Object.keys(options.structuredAttributes).length > 0 ? `${sanitizedBase.text}
13272
+ [Attributes: ${normalizeAttributePairs(options.structuredAttributes)}]` : sanitizedBase.text;
13273
+ for (const target of targets) {
13274
+ if (!target.namespace) continue;
13275
+ try {
13276
+ const targetStorage = await this.storageRouter.storageFor(target.namespace);
13277
+ if (targetStorage.dir === options.sourceStorage.dir) continue;
13278
+ if (options.category === "fact" && await targetStorage.hasFactContentHash(dedupContent)) {
13279
+ continue;
13280
+ }
13281
+ const promotedId = await targetStorage.writeMemory(
13282
+ options.category,
13283
+ citedContent,
13284
+ {
13285
+ confidence: options.confidence,
13286
+ tags: [...options.tags, `${target.target}-promotion`],
13287
+ entityRef: options.entityRef,
13288
+ structuredAttributes: options.structuredAttributes,
13289
+ source: `${options.source}-${target.target}-promotion`,
13290
+ importance: options.importance,
13291
+ lineage: [options.sourceMemoryId],
13292
+ sourceMemoryId: options.sourceMemoryId,
13293
+ intentGoal: options.intentGoal,
13294
+ intentActionType: options.intentActionType,
13295
+ intentEntityTypes: options.intentEntityTypes,
13296
+ memoryKind: options.memoryKind,
13297
+ validAt: options.validAt,
13298
+ contentHashSource: options.category === "fact" ? dedupContent : rawContent
13299
+ }
13300
+ );
13301
+ if (this.config.temporalSupersessionEnabled && options.category === "fact" && options.entityRef && options.structuredAttributes && Object.keys(options.structuredAttributes).length > 0) {
13302
+ try {
13303
+ await applyTemporalSupersession({
13304
+ storage: targetStorage,
13305
+ newMemoryId: promotedId,
13306
+ entityRef: options.entityRef,
13307
+ structuredAttributes: options.structuredAttributes,
13308
+ createdAt: supersessionOrderingAt(options.validAt),
13309
+ enabled: true
13310
+ });
13311
+ } catch (profileSupersessionErr) {
13312
+ log.warn(
13313
+ `persistExtraction: ${target.target} promotion temporal supersession failed open for promoted ${promotedId}: ${profileSupersessionErr}`
13314
+ );
13315
+ }
13316
+ }
13317
+ this.markCatalogWrite(target.namespace, targetStorage.dir);
13318
+ trackPersistedId(targetStorage, promotedId, { includeReturnedIds: false });
13319
+ await this.indexPersistedMemory(targetStorage, promotedId);
13320
+ trackBehaviorSignals(
13321
+ targetStorage,
13322
+ buildBehaviorSignalsForMemory({
13323
+ memoryId: promotedId,
13324
+ category: options.category,
13325
+ content: options.content,
13326
+ namespace: target.namespace,
13327
+ confidence: options.confidence,
13328
+ source: "extraction"
13329
+ })
13330
+ );
13331
+ } catch (err) {
13332
+ log.warn(
13333
+ `persistExtraction: ${target.target} promotion failed open for ${options.sourceMemoryId}: ${err}`
13334
+ );
13335
+ }
13336
+ }
12819
13337
  };
12820
13338
  const promoteMemoryToShared = async (options) => {
13339
+ await promoteMemoryToProfileTargets(options);
12821
13340
  if (!shouldPromoteToShared(
12822
13341
  options.sourceStorage,
12823
13342
  options.category,
@@ -12904,11 +13423,10 @@ ${normalized}`).digest("hex");
12904
13423
  intentEntityTypes: options.intentEntityTypes,
12905
13424
  memoryKind: options.memoryKind,
12906
13425
  validAt: options.validAt,
12907
- // Index the RAW content hash so hasFactContentHash(rawContent)
12908
- // returns true on subsequent extractions. Without this, the index
12909
- // would record the hash of citedContent (which changes every call
12910
- // due to an updated timestamp), causing duplicate promotions.
12911
- contentHashSource: rawContent
13426
+ // Index the same canonical body used by hasFactContentHash above.
13427
+ // For structured facts this includes the normalized Attributes
13428
+ // suffix, matching StorageManager.writeMemory enrichment.
13429
+ contentHashSource: options.category === "fact" ? dedupContent : rawContent
12912
13430
  }
12913
13431
  );
12914
13432
  if (this.config.temporalSupersessionEnabled && options.entityRef && options.structuredAttributes && Object.keys(options.structuredAttributes).length > 0) {
@@ -13182,7 +13700,7 @@ ${normalized}`).digest("hex");
13182
13700
  }
13183
13701
  if (this.config.extractionScopeClassificationEnabled && this.config.namespacesEnabled && fact.scope === "global" && !routedNamespaceExplicit) {
13184
13702
  const currentNs = this.namespaceFromStorageDir(targetStorage.dir);
13185
- if (currentNs !== this.config.sharedNamespace) {
13703
+ if (currentNs !== this.config.sharedNamespace && profileAllowsSharedWrites) {
13186
13704
  try {
13187
13705
  targetStorage = await this.storageRouter.storageFor(
13188
13706
  this.config.sharedNamespace
@@ -13196,13 +13714,28 @@ ${normalized}`).digest("hex");
13196
13714
  `scope-routing: failed to resolve shared namespace storage; writing to session namespace (fail-open): ${scopeRouteErr}`
13197
13715
  );
13198
13716
  }
13717
+ } else if (currentNs !== this.config.sharedNamespace) {
13718
+ log.debug(
13719
+ `scope-routing: skipped shared namespace for global fact because active scope profile ${scopeProfileWritePlan?.profileId ?? "none"} does not authorize serverShared writes`
13720
+ );
13199
13721
  }
13200
13722
  }
13201
13723
  const canonicalContentForHash = citationEnabled && hasCitationForTemplate(fact.content, citationTemplate) ? stripCitationForTemplate(fact.content, citationTemplate) : fact.content;
13202
13724
  const contentHashDedupKey = writeCategory === "procedure" ? buildProcedurePersistBody(fact.content, fact.procedureSteps) : canonicalContentForHash;
13203
- if (this.contentHashIndex && this.contentHashIndex.has(contentHashDedupKey)) {
13725
+ let exactDuplicate = false;
13726
+ try {
13727
+ exactDuplicate = await this.hasContentHashDedup(
13728
+ targetStorage,
13729
+ contentHashDedupKey
13730
+ );
13731
+ } catch (err) {
13732
+ log.warn(
13733
+ `content-hash dedup lookup failed for storage ${targetStorage.dir}; writing fact fail-open: ${err}`
13734
+ );
13735
+ }
13736
+ if (exactDuplicate) {
13204
13737
  log.debug(
13205
- `dedup: skipping duplicate fact "${fact.content.slice(0, 60)}\u2026"`
13738
+ `dedup: skipping duplicate fact "${fact.content.slice(0, 60)}\u2026" in storage ${targetStorage.dir}`
13206
13739
  );
13207
13740
  dedupedCount++;
13208
13741
  continue;
@@ -13465,9 +13998,13 @@ ${normalized}`).digest("hex");
13465
13998
  validAt: sourceContext?.validAt,
13466
13999
  source: extractionWriteSource
13467
14000
  });
13468
- if (this.contentHashIndex) {
14001
+ try {
13469
14002
  const canonicalChunkedContent = citationEnabled && hasCitationForTemplate(fact.content, citationTemplate) ? stripCitationForTemplate(fact.content, citationTemplate) : fact.content;
13470
- this.contentHashIndex.add(canonicalChunkedContent);
14003
+ await this.addContentHashDedup(targetStorage, canonicalChunkedContent);
14004
+ } catch (err) {
14005
+ log.warn(
14006
+ `content-hash dedup registration failed for chunked memory ${parentId}: ${err}`
14007
+ );
13471
14008
  }
13472
14009
  for (const chunk of chunkResult.chunks) {
13473
14010
  const chunkId = `${parentId}-chunk-${chunk.index}`;
@@ -13669,10 +14206,14 @@ ${normalized}`).digest("hex");
13669
14206
  intentEntityTypes: inferredIntent?.entityTypes
13670
14207
  });
13671
14208
  }
13672
- if (this.contentHashIndex) {
14209
+ try {
13673
14210
  const canonicalFactContent = citationEnabled && hasCitationForTemplate(fact.content, citationTemplate) ? stripCitationForTemplate(fact.content, citationTemplate) : fact.content;
13674
14211
  const hashRegisterKey = writeCategory === "procedure" ? buildProcedurePersistBody(fact.content, fact.procedureSteps) : canonicalFactContent;
13675
- this.contentHashIndex.add(hashRegisterKey);
14212
+ await this.addContentHashDedup(targetStorage, hashRegisterKey);
14213
+ } catch (err) {
14214
+ log.warn(
14215
+ `content-hash dedup registration failed for memory ${memoryId}: ${err}`
14216
+ );
13676
14217
  }
13677
14218
  } finally {
13678
14219
  this.markCatalogWrite(targetNamespaceName, targetStorage.dir);
@@ -13772,9 +14313,9 @@ ${normalized}`).digest("hex");
13772
14313
  if (durableNonFactWritten) {
13773
14314
  touchBaseNonFactNamespace();
13774
14315
  }
13775
- if (this.contentHashIndex) {
13776
- await this.contentHashIndex.save().catch((err) => log.warn(`content-hash index save failed: ${err}`));
13777
- }
14316
+ await this.saveContentHashIndexes().catch(
14317
+ (err) => log.warn(`content-hash index save failed: ${err}`)
14318
+ );
13778
14319
  for (const {
13779
14320
  storage: targetStorage,
13780
14321
  events
@@ -14729,16 +15270,11 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
14729
15270
  if (accessCount > this.config.factArchivalMaxAccessCount) continue;
14730
15271
  const result = await this.storage.archiveMemory(memory);
14731
15272
  if (result) {
14732
- if (this.contentHashIndex) {
14733
- if (memory.frontmatter.contentHash) {
14734
- this.contentHashIndex.removeByHash(memory.frontmatter.contentHash);
14735
- } else {
14736
- log.warn(
14737
- `[fact-archival] removing hash for legacy memory ${memory.frontmatter.id ?? "(unknown)"} via content fallback \u2014 no contentHash in frontmatter`
14738
- );
14739
- this.contentHashIndex.remove(memory.content);
14740
- }
14741
- }
15273
+ await this.removeContentHashForMemory(
15274
+ this.storage,
15275
+ memory,
15276
+ "fact-archival"
15277
+ );
14742
15278
  await this.embeddingFallback.removeFromIndex(memory.frontmatter.id);
14743
15279
  if (this.config.queryAwareIndexingEnabled && memory.path && memory.frontmatter?.created) {
14744
15280
  deindexMemory(
@@ -14751,8 +15287,8 @@ ${texts.map((t, i) => `[${i + 1}] ${t}`).join("\n\n")}`;
14751
15287
  archivedCount++;
14752
15288
  }
14753
15289
  }
14754
- if (archivedCount > 0 && this.contentHashIndex) {
14755
- await this.contentHashIndex.save().catch(
15290
+ if (archivedCount > 0) {
15291
+ await this.saveContentHashIndexes().catch(
14756
15292
  (err) => log.warn(`content-hash index save failed during archival: ${err}`)
14757
15293
  );
14758
15294
  }
@@ -16707,4 +17243,4 @@ export {
16707
17243
  resolvePersistedMemoryRelativePath,
16708
17244
  Orchestrator
16709
17245
  };
16710
- //# sourceMappingURL=chunk-5QD3QD76.js.map
17246
+ //# sourceMappingURL=chunk-RDW5G6DO.js.map