@remnic/core 9.7.8 → 9.7.10

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 (406) hide show
  1. package/dist/access-admin-ops-surface.d.ts +6 -6
  2. package/dist/access-admin-ops-surface.js +32 -30
  3. package/dist/access-audit.js +2 -2
  4. package/dist/access-boundary.d.ts +6 -6
  5. package/dist/access-boundary.js +33 -31
  6. package/dist/access-cli.js +92 -90
  7. package/dist/access-cli.js.map +1 -1
  8. package/dist/access-http.d.ts +6 -6
  9. package/dist/access-http.js +40 -38
  10. package/dist/access-identity-continuity-surface.d.ts +5 -5
  11. package/dist/access-identity-continuity-surface.js +32 -30
  12. package/dist/access-lcm-surface.d.ts +6 -6
  13. package/dist/access-lcm-surface.js +32 -30
  14. package/dist/access-mcp.d.ts +6 -6
  15. package/dist/access-mcp.js +37 -35
  16. package/dist/access-observe-write-surface.d.ts +6 -6
  17. package/dist/access-observe-write-surface.js +32 -30
  18. package/dist/access-operations-batch.js +35 -33
  19. package/dist/access-operations.d.ts +9 -9
  20. package/dist/access-operations.js +36 -34
  21. package/dist/access-recall-surface.d.ts +6 -6
  22. package/dist/access-recall-surface.js +32 -30
  23. package/dist/access-schema.d.ts +64 -64
  24. package/dist/{access-service-CxDZXTKt.d.ts → access-service-DSuzikHQ.d.ts} +4 -4
  25. package/dist/access-service.d.ts +6 -6
  26. package/dist/access-service.js +32 -30
  27. package/dist/access-surface-catalog.d.ts +6 -6
  28. package/dist/action-confidence.d.ts +1 -1
  29. package/dist/active-memory-bridge.d.ts +1 -1
  30. package/dist/active-recall.d.ts +1 -1
  31. package/dist/active-recall.js +1 -1
  32. package/dist/adapters/index.js +4 -4
  33. package/dist/adapters/registry.js +2 -2
  34. package/dist/{auto-sync-676N6N6Y.js → auto-sync-AAMTVZMK.js} +5 -5
  35. package/dist/behavior-learner.d.ts +1 -1
  36. package/dist/behavior-signals.d.ts +1 -1
  37. package/dist/bootstrap.d.ts +5 -5
  38. package/dist/briefing.d.ts +2 -2
  39. package/dist/briefing.js +15 -13
  40. package/dist/buffer-surprise-report.d.ts +1 -1
  41. package/dist/buffer.d.ts +2 -2
  42. package/dist/bulk-import/index.d.ts +3 -3
  43. package/dist/calibration.d.ts +1 -1
  44. package/dist/calibration.js +2 -2
  45. package/dist/capabilities.d.ts +1 -1
  46. package/dist/{capsule-merge-GK5E647P.js → capsule-merge-Z2HUO6IK.js} +10 -2
  47. package/dist/capsule-merge-Z2HUO6IK.js.map +1 -0
  48. package/dist/{catalog-DzU9HowE.d.ts → catalog-BNwjACa5.d.ts} +1 -1
  49. package/dist/causal-behavior.d.ts +1 -1
  50. package/dist/causal-consolidation.d.ts +1 -1
  51. package/dist/causal-consolidation.js +16 -14
  52. package/dist/causal-consolidation.js.map +1 -1
  53. package/dist/causal-trajectory-graph.d.ts +1 -1
  54. package/dist/{chunk-HHAA35A3.js → chunk-2VN4JAX7.js} +548 -161
  55. package/dist/chunk-2VN4JAX7.js.map +1 -0
  56. package/dist/{chunk-CNWC274T.js → chunk-3OQ4IZJN.js} +28 -28
  57. package/dist/{chunk-JO5AT6QT.js → chunk-3ZVFLMFQ.js} +1 -1
  58. package/dist/chunk-3ZVFLMFQ.js.map +1 -0
  59. package/dist/{chunk-7XH7VJN4.js → chunk-5S7Z5SHA.js} +2 -2
  60. package/dist/{chunk-WKE4VXSZ.js → chunk-673NPXE3.js} +2 -2
  61. package/dist/{chunk-Q6JPMCPO.js → chunk-7CKS4AXY.js} +63 -58
  62. package/dist/chunk-7CKS4AXY.js.map +1 -0
  63. package/dist/{chunk-UHGHTOR5.js → chunk-7EX4YOKH.js} +7 -7
  64. package/dist/{chunk-TVVEYCNW.js → chunk-7K5Q6COX.js} +4 -4
  65. package/dist/{chunk-EJCVMPIM.js → chunk-7LMEY5KZ.js} +15 -1
  66. package/dist/chunk-7LMEY5KZ.js.map +1 -0
  67. package/dist/{chunk-3F4N4WDH.js → chunk-AHLPZ2SF.js} +2 -2
  68. package/dist/{chunk-6C35R7P4.js → chunk-DJCKXI4M.js} +2 -2
  69. package/dist/{chunk-AD2KK5MT.js → chunk-DLWYAN6A.js} +9 -3
  70. package/dist/chunk-DLWYAN6A.js.map +1 -0
  71. package/dist/{chunk-TVRPRFUB.js → chunk-EQF5763Z.js} +9 -7
  72. package/dist/chunk-EQF5763Z.js.map +1 -0
  73. package/dist/{chunk-FYKIEOG6.js → chunk-FNJX2O6G.js} +3 -3
  74. package/dist/{chunk-DQPPRXFO.js → chunk-HQ7QZJM5.js} +2 -2
  75. package/dist/{chunk-RKNJBZ55.js → chunk-JBPKEARU.js} +4 -4
  76. package/dist/{chunk-KIPLG7S7.js → chunk-JKLJ6A7W.js} +2 -2
  77. package/dist/{chunk-O3BZ6PFY.js → chunk-JZM5QUTE.js} +2 -2
  78. package/dist/{chunk-KTOH7EJE.js → chunk-KXLRMM35.js} +312 -48
  79. package/dist/chunk-KXLRMM35.js.map +1 -0
  80. package/dist/{chunk-ZUFJ7ZTR.js → chunk-L4H6MQ7I.js} +6 -2
  81. package/dist/chunk-L4H6MQ7I.js.map +1 -0
  82. package/dist/{chunk-SYNYI4ZM.js → chunk-L5HJQC36.js} +2 -2
  83. package/dist/{chunk-VXMWDXIJ.js → chunk-LC7OODWZ.js} +2 -2
  84. package/dist/{chunk-ZW6OKHVX.js → chunk-LQKITFGB.js} +2 -2
  85. package/dist/{chunk-TZJVTH3F.js → chunk-MXRMNKSY.js} +14 -14
  86. package/dist/{chunk-GL3SMLMZ.js → chunk-N3LWQJ6Y.js} +150 -119
  87. package/dist/chunk-N3LWQJ6Y.js.map +1 -0
  88. package/dist/{chunk-M5QKGHCR.js → chunk-OC35KQIN.js} +6 -2
  89. package/dist/chunk-OC35KQIN.js.map +1 -0
  90. package/dist/chunk-OKUEZOGW.js +27 -0
  91. package/dist/chunk-OKUEZOGW.js.map +1 -0
  92. package/dist/{chunk-PKGWJFNR.js → chunk-OVMS3DCB.js} +2 -2
  93. package/dist/chunk-PDJTHRAW.js +36 -0
  94. package/dist/chunk-PDJTHRAW.js.map +1 -0
  95. package/dist/{chunk-LRGSLV7M.js → chunk-PYHOAXTI.js} +4 -4
  96. package/dist/{chunk-NMMKRVUF.js → chunk-QVALQE4P.js} +6 -6
  97. package/dist/{chunk-FXGC5UUH.js → chunk-RT7IP3D3.js} +2 -2
  98. package/dist/{chunk-AH3M6F4X.js → chunk-SBFDL2EQ.js} +2 -2
  99. package/dist/{chunk-UYZUJ4EB.js → chunk-SECMZACR.js} +2 -2
  100. package/dist/{chunk-HXDKC3BI.js → chunk-TGBJ2OMK.js} +2 -2
  101. package/dist/{chunk-DE6ENYLG.js → chunk-TXLGHDHS.js} +2 -2
  102. package/dist/{chunk-74MJH7I3.js → chunk-U4KHQTJ6.js} +12 -3
  103. package/dist/chunk-U4KHQTJ6.js.map +1 -0
  104. package/dist/{chunk-CRFTLUWT.js → chunk-UTDA43TB.js} +2 -2
  105. package/dist/{chunk-GKCCHHZK.js → chunk-UXKMMNJD.js} +4 -4
  106. package/dist/{chunk-57INMZ6F.js → chunk-UZRIKUFS.js} +2 -2
  107. package/dist/{chunk-2FSHROYK.js → chunk-V53GJUSL.js} +8 -8
  108. package/dist/{chunk-LKT755LP.js → chunk-VA4WSW54.js} +2 -2
  109. package/dist/{chunk-ZHKD4EZM.js → chunk-VCEH5UYS.js} +3 -3
  110. package/dist/{chunk-CHVU4RE5.js → chunk-VDLMAJXS.js} +3 -3
  111. package/dist/{chunk-XFTPUXCE.js → chunk-VRAD2FGO.js} +10 -10
  112. package/dist/{chunk-VF4XKTX3.js → chunk-VZ5OJE4X.js} +10 -2
  113. package/dist/chunk-VZ5OJE4X.js.map +1 -0
  114. package/dist/{chunk-UVIQHSS7.js → chunk-WUDBMLC6.js} +9 -3
  115. package/dist/chunk-WUDBMLC6.js.map +1 -0
  116. package/dist/{chunk-AWJ2FHCF.js → chunk-X47LWMKA.js} +49 -21
  117. package/dist/chunk-X47LWMKA.js.map +1 -0
  118. package/dist/{chunk-VMGMY2AI.js → chunk-XF4KOVDK.js} +8 -8
  119. package/dist/{chunk-VMGMY2AI.js.map → chunk-XF4KOVDK.js.map} +1 -1
  120. package/dist/{chunk-T7VNN3ZM.js → chunk-XVLEGMJI.js} +2 -2
  121. package/dist/{chunk-R2SJDIPO.js → chunk-YLTG6BO4.js} +9 -7
  122. package/dist/chunk-YLTG6BO4.js.map +1 -0
  123. package/dist/{chunk-QDCJNRKK.js → chunk-YXOAQAH2.js} +3 -3
  124. package/dist/{cli-BqyGVyOe.d.ts → cli-DACyuK8-.d.ts} +5 -5
  125. package/dist/cli.d.ts +8 -8
  126. package/dist/cli.js +66 -64
  127. package/dist/compounding/engine.d.ts +2 -2
  128. package/dist/compounding/engine.js +15 -13
  129. package/dist/compounding/preference-consolidator.d.ts +1 -1
  130. package/dist/compression-optimizer.d.ts +1 -1
  131. package/dist/config.d.ts +1 -1
  132. package/dist/config.js +1 -1
  133. package/dist/connectors/codex-materialize-runner.d.ts +1 -1
  134. package/dist/connectors/codex-materialize-runner.js +15 -13
  135. package/dist/connectors/codex-materialize.d.ts +1 -1
  136. package/dist/connectors/index.d.ts +1 -1
  137. package/dist/connectors/index.js +15 -13
  138. package/dist/consolidation-provenance-check.d.ts +2 -2
  139. package/dist/consolidation-provenance-check.js +6 -2
  140. package/dist/consolidation-undo.d.ts +2 -2
  141. package/dist/consolidation-undo.js +8 -1
  142. package/dist/consolidation-undo.js.map +1 -1
  143. package/dist/contradiction/index.d.ts +2 -2
  144. package/dist/conversation-index/backend.d.ts +1 -1
  145. package/dist/conversation-index/chunker.d.ts +1 -1
  146. package/dist/conversation-index/faiss-adapter.d.ts +1 -1
  147. package/dist/conversation-index/indexer.d.ts +1 -1
  148. package/dist/conversation-index/search.d.ts +1 -1
  149. package/dist/day-summary.d.ts +1 -1
  150. package/dist/delinearize.d.ts +1 -1
  151. package/dist/direct-answer-wiring.d.ts +1 -1
  152. package/dist/direct-answer.d.ts +1 -1
  153. package/dist/embedding-fallback.d.ts +1 -1
  154. package/dist/enrichment/index.d.ts +1 -1
  155. package/dist/entity-retrieval.d.ts +2 -2
  156. package/dist/entity-retrieval.js +15 -13
  157. package/dist/entity-schema.d.ts +1 -1
  158. package/dist/explicit-capture.d.ts +5 -5
  159. package/dist/extraction-faithfulness.d.ts +1 -1
  160. package/dist/extraction-faithfulness.js +3 -3
  161. package/dist/extraction-judge-telemetry.d.ts +1 -1
  162. package/dist/extraction-judge-training.d.ts +1 -1
  163. package/dist/extraction-judge.d.ts +1 -1
  164. package/dist/extraction-judge.js +3 -3
  165. package/dist/extraction.d.ts +1 -1
  166. package/dist/extraction.js +3 -3
  167. package/dist/fallback-llm.d.ts +1 -1
  168. package/dist/fallback-llm.js +2 -2
  169. package/dist/{forget-KHF7A44H.js → forget-CQCLB5LB.js} +2 -2
  170. package/dist/graph-dashboard-diff.d.ts +1 -1
  171. package/dist/graph-dashboard-key.d.ts +1 -1
  172. package/dist/graph-dashboard-parser.d.ts +1 -1
  173. package/dist/graph-edge-reinforcement.d.ts +1 -1
  174. package/dist/graph-snapshot.d.ts +1 -1
  175. package/dist/graph.d.ts +1 -1
  176. package/dist/identity-continuity.d.ts +1 -1
  177. package/dist/importance.d.ts +1 -1
  178. package/dist/importers/index.d.ts +1 -1
  179. package/dist/in-flight-reads.d.ts +19 -0
  180. package/dist/in-flight-reads.js +16 -0
  181. package/dist/in-flight-reads.js.map +1 -0
  182. package/dist/index.d.ts +13 -13
  183. package/dist/index.js +116 -114
  184. package/dist/intent.d.ts +1 -1
  185. package/dist/lcm/engine.d.ts +1 -1
  186. package/dist/lcm/engine.js +4 -4
  187. package/dist/lcm/index.d.ts +1 -1
  188. package/dist/lcm/index.js +13 -13
  189. package/dist/lcm/tools.d.ts +1 -1
  190. package/dist/lifecycle.d.ts +1 -1
  191. package/dist/live-connectors-runner.d.ts +1 -1
  192. package/dist/local-llm.d.ts +1 -1
  193. package/dist/local-model-endpoint.d.ts +1 -1
  194. package/dist/maintenance/memory-governance.d.ts +1 -1
  195. package/dist/maintenance/memory-governance.js +15 -13
  196. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +15 -13
  197. package/dist/maintenance/rebuild-memory-projection.js +16 -14
  198. package/dist/mcp-memory-inspector-app.d.ts +6 -6
  199. package/dist/memory-action-policy.d.ts +1 -1
  200. package/dist/memory-cache.d.ts +24 -13
  201. package/dist/memory-cache.js +3 -1
  202. package/dist/memory-corpus-version.d.ts +19 -0
  203. package/dist/memory-corpus-version.js +13 -0
  204. package/dist/memory-corpus-version.js.map +1 -0
  205. package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
  206. package/dist/memory-projection-store.d.ts +1 -1
  207. package/dist/memory-provenance.d.ts +1 -1
  208. package/dist/memory-worth-outcomes.d.ts +2 -2
  209. package/dist/models-json.d.ts +1 -1
  210. package/dist/namespaces/migrate.d.ts +3 -3
  211. package/dist/namespaces/migrate.js +22 -20
  212. package/dist/namespaces/principal.d.ts +1 -1
  213. package/dist/namespaces/search.d.ts +1 -1
  214. package/dist/namespaces/search.js +7 -7
  215. package/dist/namespaces/storage.d.ts +3 -3
  216. package/dist/namespaces/storage.js +15 -13
  217. package/dist/native-knowledge.d.ts +1 -1
  218. package/dist/operator-toolkit.d.ts +2 -2
  219. package/dist/operator-toolkit.js +27 -25
  220. package/dist/orchestration/compression-guideline-coordinator.d.ts +2 -2
  221. package/dist/orchestration/maintenance.d.ts +2 -2
  222. package/dist/orchestration/maintenance.js +17 -15
  223. package/dist/{orchestrator-37Cx7yyw.d.ts → orchestrator-D83AvrPf.d.ts} +4 -4
  224. package/dist/orchestrator.d.ts +5 -5
  225. package/dist/orchestrator.js +92 -90
  226. package/dist/page-versioning.js +5 -1
  227. package/dist/patterns-cli.d.ts +1 -1
  228. package/dist/{pipeline-C6onljHc.d.ts → pipeline-BSqGpYl1.d.ts} +1 -1
  229. package/dist/policy-runtime.d.ts +1 -1
  230. package/dist/provenance.d.ts +1 -1
  231. package/dist/{qmd-J08G7MEm.d.ts → qmd-CutnpRVe.d.ts} +1 -1
  232. package/dist/qmd-preflight.d.ts +2 -2
  233. package/dist/qmd-recall-cache.d.ts +1 -1
  234. package/dist/qmd.d.ts +2 -2
  235. package/dist/qmd.js +2 -2
  236. package/dist/recall-disclosure-escalation.d.ts +1 -1
  237. package/dist/recall-explain-renderer.d.ts +1 -1
  238. package/dist/recall-explain-renderer.js +3 -3
  239. package/dist/recall-planner-llm.d.ts +1 -1
  240. package/dist/recall-planner-llm.js +2 -2
  241. package/dist/recall-state.d.ts +1 -1
  242. package/dist/recall-tag-filter.d.ts +1 -1
  243. package/dist/recall-timings.d.ts +1 -1
  244. package/dist/recall-xray-cli.d.ts +1 -1
  245. package/dist/recall-xray-cli.js +4 -4
  246. package/dist/recall-xray-renderer.d.ts +1 -1
  247. package/dist/recall-xray-renderer.js +3 -3
  248. package/dist/recall-xray.d.ts +1 -1
  249. package/dist/recall-xray.js +2 -2
  250. package/dist/replay/normalizers/chatgpt.d.ts +1 -1
  251. package/dist/replay/normalizers/claude.d.ts +1 -1
  252. package/dist/replay/normalizers/openclaw.d.ts +1 -1
  253. package/dist/replay/normalizers/shared.d.ts +1 -1
  254. package/dist/replay/runner.d.ts +1 -1
  255. package/dist/replay/types.d.ts +1 -1
  256. package/dist/resolve-auth-token.d.ts +1 -1
  257. package/dist/resume-bundles.js +2 -2
  258. package/dist/retrieval-agents.d.ts +2 -2
  259. package/dist/retrieval-agents.js +2 -2
  260. package/dist/retrieval-tiers.d.ts +1 -1
  261. package/dist/routing/engine.d.ts +1 -1
  262. package/dist/routing/store.d.ts +1 -1
  263. package/dist/schemas.d.ts +52 -52
  264. package/dist/search/embed-helper.d.ts +1 -1
  265. package/dist/search/factory.d.ts +1 -1
  266. package/dist/search/factory.js +6 -6
  267. package/dist/search/index.d.ts +1 -1
  268. package/dist/search/index.js +12 -12
  269. package/dist/search/lancedb-backend.d.ts +1 -1
  270. package/dist/search/meilisearch-backend.d.ts +1 -1
  271. package/dist/search/noop-backend.d.ts +1 -1
  272. package/dist/search/orama-backend.d.ts +1 -1
  273. package/dist/search/port.d.ts +1 -1
  274. package/dist/search/remote-backend.d.ts +1 -1
  275. package/dist/{semantic-consolidation-BFtoVosl.d.ts → semantic-consolidation-btIVRC4l.d.ts} +1 -1
  276. package/dist/semantic-consolidation.d.ts +2 -2
  277. package/dist/semantic-consolidation.js +16 -14
  278. package/dist/semantic-rule-promotion.js +15 -13
  279. package/dist/semantic-rule-verifier.d.ts +5 -1
  280. package/dist/semantic-rule-verifier.js +15 -13
  281. package/dist/session-observer-bands.d.ts +1 -1
  282. package/dist/session-observer-state.d.ts +1 -1
  283. package/dist/shared-context/manager.d.ts +9 -9
  284. package/dist/signal.d.ts +1 -1
  285. package/dist/{storage-CXjwBr69.d.ts → storage-BVv_Mqa0.d.ts} +133 -3
  286. package/dist/storage.d.ts +2 -2
  287. package/dist/storage.js +14 -12
  288. package/dist/summarizer.d.ts +1 -1
  289. package/dist/summarizer.js +3 -3
  290. package/dist/summary-snapshot.d.ts +1 -1
  291. package/dist/temporal-index-compat.d.ts +1 -0
  292. package/dist/temporal-index-compat.js +16 -0
  293. package/dist/temporal-index-compat.js.map +1 -0
  294. package/dist/temporal-index.d.ts +58 -7
  295. package/dist/temporal-index.js +23 -3
  296. package/dist/temporal-supersession.d.ts +2 -2
  297. package/dist/temporal-timeline-recall.d.ts +1 -1
  298. package/dist/temporal-validity.d.ts +1 -1
  299. package/dist/threading.d.ts +1 -1
  300. package/dist/tier-migration.d.ts +2 -2
  301. package/dist/tier-routing.d.ts +1 -1
  302. package/dist/topics.d.ts +1 -1
  303. package/dist/transcript.d.ts +1 -1
  304. package/dist/transfer/capsule-import.js +6 -2
  305. package/dist/transfer/import-sqlite.js +2 -2
  306. package/dist/transfer/types.d.ts +66 -66
  307. package/dist/trust-score-stage.d.ts +1 -1
  308. package/dist/trust-score.d.ts +1 -1
  309. package/dist/{types-DpxqC8dI.d.ts → types-Cmkz7csa.d.ts} +27 -0
  310. package/dist/types.d.ts +1 -1
  311. package/dist/types.js +1 -1
  312. package/dist/utility-runtime.d.ts +1 -1
  313. package/dist/verified-recall.d.ts +4 -0
  314. package/dist/verified-recall.js +15 -13
  315. package/package.json +12 -2
  316. package/src/binary-lifecycle/pipeline.ts +22 -0
  317. package/src/cli.ts +8 -0
  318. package/src/compounding/engine.ts +9 -1
  319. package/src/config.ts +14 -0
  320. package/src/consolidation-undo.ts +8 -0
  321. package/src/curation/index.ts +9 -0
  322. package/src/in-flight-reads.ts +63 -0
  323. package/src/maintenance/memory-governance.ts +6 -0
  324. package/src/memory-cache-hot.test.ts +131 -0
  325. package/src/memory-cache.ts +146 -22
  326. package/src/memory-corpus-version.ts +45 -0
  327. package/src/namespaces/storage.ts +20 -1
  328. package/src/operator-toolkit.ts +7 -1
  329. package/src/orchestration/consolidation-run.ts +5 -5
  330. package/src/orchestration/contradiction-linking-coordinator.ts +2 -2
  331. package/src/orchestration/lifecycle-policy-coordinator.ts +2 -2
  332. package/src/orchestration/persistence-index.ts +6 -6
  333. package/src/orchestration/recall-internal.ts +6 -3
  334. package/src/orchestration/recall-search-pipeline.ts +36 -21
  335. package/src/orchestration/semantic-consolidation-coordinator.ts +2 -2
  336. package/src/orchestrator.ts +25 -5
  337. package/src/page-versioning.ts +14 -1
  338. package/src/provenance-frontmatter.test.ts +6 -0
  339. package/src/review/index.ts +16 -8
  340. package/src/semantic-rule-promotion.ts +9 -1
  341. package/src/semantic-rule-verifier.ts +19 -6
  342. package/src/spaces/index.ts +10 -0
  343. package/src/storage/memory-read-store.ts +9 -2
  344. package/src/storage-contract/cache-coherence.test.ts +242 -0
  345. package/src/storage-contract/namespace-routing.test.ts +26 -1
  346. package/src/storage.ts +513 -31
  347. package/src/temporal-index-compat.ts +311 -0
  348. package/src/temporal-index.test.ts +273 -22
  349. package/src/temporal-index.ts +427 -178
  350. package/src/transfer/capsule-cache-coherence.test.ts +107 -0
  351. package/src/transfer/capsule-import.ts +8 -0
  352. package/src/transfer/capsule-merge.ts +7 -0
  353. package/src/types.ts +27 -0
  354. package/src/verified-recall.ts +20 -6
  355. package/dist/capsule-merge-GK5E647P.js.map +0 -1
  356. package/dist/chunk-74MJH7I3.js.map +0 -1
  357. package/dist/chunk-AD2KK5MT.js.map +0 -1
  358. package/dist/chunk-AWJ2FHCF.js.map +0 -1
  359. package/dist/chunk-EJCVMPIM.js.map +0 -1
  360. package/dist/chunk-GL3SMLMZ.js.map +0 -1
  361. package/dist/chunk-HHAA35A3.js.map +0 -1
  362. package/dist/chunk-JO5AT6QT.js.map +0 -1
  363. package/dist/chunk-KTOH7EJE.js.map +0 -1
  364. package/dist/chunk-M5QKGHCR.js.map +0 -1
  365. package/dist/chunk-Q6JPMCPO.js.map +0 -1
  366. package/dist/chunk-R2SJDIPO.js.map +0 -1
  367. package/dist/chunk-TVRPRFUB.js.map +0 -1
  368. package/dist/chunk-UVIQHSS7.js.map +0 -1
  369. package/dist/chunk-VF4XKTX3.js.map +0 -1
  370. package/dist/chunk-ZUFJ7ZTR.js.map +0 -1
  371. /package/dist/{auto-sync-676N6N6Y.js.map → auto-sync-AAMTVZMK.js.map} +0 -0
  372. /package/dist/{chunk-CNWC274T.js.map → chunk-3OQ4IZJN.js.map} +0 -0
  373. /package/dist/{chunk-7XH7VJN4.js.map → chunk-5S7Z5SHA.js.map} +0 -0
  374. /package/dist/{chunk-WKE4VXSZ.js.map → chunk-673NPXE3.js.map} +0 -0
  375. /package/dist/{chunk-UHGHTOR5.js.map → chunk-7EX4YOKH.js.map} +0 -0
  376. /package/dist/{chunk-TVVEYCNW.js.map → chunk-7K5Q6COX.js.map} +0 -0
  377. /package/dist/{chunk-3F4N4WDH.js.map → chunk-AHLPZ2SF.js.map} +0 -0
  378. /package/dist/{chunk-6C35R7P4.js.map → chunk-DJCKXI4M.js.map} +0 -0
  379. /package/dist/{chunk-FYKIEOG6.js.map → chunk-FNJX2O6G.js.map} +0 -0
  380. /package/dist/{chunk-DQPPRXFO.js.map → chunk-HQ7QZJM5.js.map} +0 -0
  381. /package/dist/{chunk-RKNJBZ55.js.map → chunk-JBPKEARU.js.map} +0 -0
  382. /package/dist/{chunk-KIPLG7S7.js.map → chunk-JKLJ6A7W.js.map} +0 -0
  383. /package/dist/{chunk-O3BZ6PFY.js.map → chunk-JZM5QUTE.js.map} +0 -0
  384. /package/dist/{chunk-SYNYI4ZM.js.map → chunk-L5HJQC36.js.map} +0 -0
  385. /package/dist/{chunk-VXMWDXIJ.js.map → chunk-LC7OODWZ.js.map} +0 -0
  386. /package/dist/{chunk-ZW6OKHVX.js.map → chunk-LQKITFGB.js.map} +0 -0
  387. /package/dist/{chunk-TZJVTH3F.js.map → chunk-MXRMNKSY.js.map} +0 -0
  388. /package/dist/{chunk-PKGWJFNR.js.map → chunk-OVMS3DCB.js.map} +0 -0
  389. /package/dist/{chunk-LRGSLV7M.js.map → chunk-PYHOAXTI.js.map} +0 -0
  390. /package/dist/{chunk-NMMKRVUF.js.map → chunk-QVALQE4P.js.map} +0 -0
  391. /package/dist/{chunk-FXGC5UUH.js.map → chunk-RT7IP3D3.js.map} +0 -0
  392. /package/dist/{chunk-AH3M6F4X.js.map → chunk-SBFDL2EQ.js.map} +0 -0
  393. /package/dist/{chunk-UYZUJ4EB.js.map → chunk-SECMZACR.js.map} +0 -0
  394. /package/dist/{chunk-HXDKC3BI.js.map → chunk-TGBJ2OMK.js.map} +0 -0
  395. /package/dist/{chunk-DE6ENYLG.js.map → chunk-TXLGHDHS.js.map} +0 -0
  396. /package/dist/{chunk-CRFTLUWT.js.map → chunk-UTDA43TB.js.map} +0 -0
  397. /package/dist/{chunk-GKCCHHZK.js.map → chunk-UXKMMNJD.js.map} +0 -0
  398. /package/dist/{chunk-57INMZ6F.js.map → chunk-UZRIKUFS.js.map} +0 -0
  399. /package/dist/{chunk-2FSHROYK.js.map → chunk-V53GJUSL.js.map} +0 -0
  400. /package/dist/{chunk-LKT755LP.js.map → chunk-VA4WSW54.js.map} +0 -0
  401. /package/dist/{chunk-ZHKD4EZM.js.map → chunk-VCEH5UYS.js.map} +0 -0
  402. /package/dist/{chunk-CHVU4RE5.js.map → chunk-VDLMAJXS.js.map} +0 -0
  403. /package/dist/{chunk-XFTPUXCE.js.map → chunk-VRAD2FGO.js.map} +0 -0
  404. /package/dist/{chunk-T7VNN3ZM.js.map → chunk-XVLEGMJI.js.map} +0 -0
  405. /package/dist/{chunk-QDCJNRKK.js.map → chunk-YXOAQAH2.js.map} +0 -0
  406. /package/dist/{forget-KHF7A44H.js.map → forget-CQCLB5LB.js.map} +0 -0
@@ -1,6 +1,9 @@
1
1
  import {
2
2
  createVersion
3
- } from "./chunk-VF4XKTX3.js";
3
+ } from "./chunk-VZ5OJE4X.js";
4
+ import {
5
+ bumpMemoryCorpusVersionForDir
6
+ } from "./chunk-OKUEZOGW.js";
4
7
  import {
5
8
  parseExportBundle
6
9
  } from "./chunk-WEHSQBFR.js";
@@ -176,6 +179,7 @@ async function importCapsule(opts) {
176
179
  }
177
180
  await mkdir(path.dirname(targetAbs), { recursive: true });
178
181
  await writeFile(targetAbs, contentToWrite, "utf-8");
182
+ bumpMemoryCorpusVersionForDir(rootReal);
179
183
  imported.push({
180
184
  sourcePath: rec.path,
181
185
  targetPath: targetRel,
@@ -227,4 +231,4 @@ function mintForkId(capsuleId, originalId, now) {
227
231
  export {
228
232
  importCapsule
229
233
  };
230
- //# sourceMappingURL=chunk-M5QKGHCR.js.map
234
+ //# sourceMappingURL=chunk-OC35KQIN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transfer/capsule-import.ts"],"sourcesContent":["import { lstat, mkdir, readFile, realpath, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { gunzipSync } from \"node:zlib\";\nimport { bumpMemoryCorpusVersionForDir } from \"../memory-corpus-version.js\";\nimport {\n createVersion,\n type VersioningConfig,\n type VersioningLogger,\n} from \"../page-versioning.js\";\nimport {\n assertIsDirectoryNotSymlink,\n assertRealpathInsideRoot,\n fromPosixRelPath,\n isPathInsideRoot,\n sha256String,\n} from \"./fs-utils.js\";\nimport {\n parseExportBundle,\n type CapsuleBlock,\n type ExportManifestV2,\n type ExportMemoryRecordV1,\n} from \"./types.js\";\nimport { isEncryptedCapsuleFile, decryptCapsuleFileInMemory } from \"./capsule-crypto.js\";\n\n/**\n * Conflict-resolution mode for {@link importCapsule}. Inverse of the\n * `mode` selector in PR 4/6's CLI surface.\n *\n * - `\"skip\"` (default) — when a target file already exists at the same\n * relative path, leave it untouched. The corresponding record is reported\n * via {@link ImportCapsuleResult.skipped}.\n * - `\"overwrite\"` — when a target file exists, snapshot the prior content\n * via {@link createVersion} (gotcha #54: write-before-delete; gotcha #25:\n * don't destroy old state until new state is confirmed), then write the\n * incoming content. The snapshot's `note` includes the source capsule id.\n * - `\"fork\"` — never overwrite. Every record is rebased under\n * `forks/<capsule-id>/<original-path>` and any YAML-frontmatter `id:`\n * field is rewritten to a new fork-scoped value. The original tree is\n * not touched.\n *\n * The mode is selected once per call and applied uniformly to every record\n * in the bundle. Mixed-mode imports are not supported by design — that\n * would let a single corrupted manifest silently land partial state.\n */\nexport type ImportCapsuleMode = \"skip\" | \"overwrite\" | \"fork\";\n\n/**\n * Options accepted by {@link importCapsule}.\n *\n * `archivePath` — absolute or cwd-relative path to a `.capsule.json.gz`\n * archive produced by `exportCapsule`. The archive must contain a V2\n * bundle (`schemaVersion: 2`); V1 archives are rejected.\n *\n * `root` — absolute or cwd-relative path to the memory directory that\n * will receive the records. Must be an existing directory.\n *\n * `mode` — see {@link ImportCapsuleMode}. Defaults to `\"skip\"`.\n *\n * `versioning` — optional page-versioning config used by `mode: \"overwrite\"`\n * to snapshot prior content before replacing it. Snapshots are skipped when\n * not provided or when `enabled === false`. Tests pass an enabled config\n * to assert snapshot creation; production callers thread the\n * orchestrator's resolved versioning config.\n *\n * `log` — optional logger forwarded to {@link createVersion}.\n *\n * `now` — optional clock override (ms epoch) used to derive deterministic\n * fork ids in tests. Production callers omit this.\n */\nexport interface ImportCapsuleOptions {\n archivePath: string;\n root: string;\n mode?: ImportCapsuleMode;\n versioning?: VersioningConfig;\n log?: VersioningLogger;\n now?: number;\n /**\n * Memory directory whose secure-store keyring is used when the archive is\n * encrypted. Required when `archivePath` ends with `.enc` or when the file\n * starts with the REMNIC-ENC magic header. If `memoryDir` is omitted and the\n * archive turns out to be encrypted, `importCapsule` throws a clear error\n * rather than silently failing.\n *\n * When provided and the archive is NOT encrypted, the value is ignored.\n */\n memoryDir?: string;\n /**\n * Original secure-store passphrase for encrypted format-v2 archives. When\n * supplied, the importer derives the archive key from the embedded KDF\n * header, enabling restore without the source machine's unlocked keyring.\n */\n passphrase?: string;\n}\n\nexport interface ImportCapsuleSkippedRecord {\n /** Original record path (capsule-relative, posix). */\n path: string;\n /**\n * Why this record was not written.\n *\n * `\"exists\"` — the target path already existed and the mode was `\"skip\"`,\n * OR the computed fork path already existed in fork mode.\n *\n * `\"checksum_mismatch\"` is intentionally absent: a checksum failure aborts\n * the import entirely (fail-closed) rather than skipping the offending\n * record, so no `ImportCapsuleSkippedRecord` is ever produced for it.\n */\n reason: \"exists\";\n}\n\nexport interface ImportCapsuleImportedRecord {\n /** Capsule-relative posix path the record carried. */\n sourcePath: string;\n /** Memory-dir-relative posix path the file was written to. */\n targetPath: string;\n /** Whether a prior version snapshot was taken (overwrite-mode only). */\n snapshotted: boolean;\n /** Whether the frontmatter `id:` field was rewritten (fork-mode only). */\n rewroteId: boolean;\n}\n\nexport interface ImportCapsuleResult {\n /** Records that landed on disk. */\n imported: ImportCapsuleImportedRecord[];\n /** Records that were not written. */\n skipped: ImportCapsuleSkippedRecord[];\n /** The manifest decoded from the archive. */\n manifest: ExportManifestV2;\n}\n\n/**\n * Pure async function that imports a capsule archive into a memory\n * directory. Inverse of {@link import(\"./capsule-export.js\").exportCapsule}.\n *\n * Sequence:\n * 1. Read + gunzip + JSON.parse the archive.\n * 2. Validate the bundle through `parseExportBundle` (V1 rejected).\n * 3. Verify each record's content sha256 against the manifest entry.\n * Any mismatch aborts the import BEFORE any file is written —\n * partial-write recovery would require a full rollback we cannot\n * offer cheaply, so we fail closed (gotcha #25).\n * 4. Apply the selected {@link ImportCapsuleMode} to every record.\n *\n * Determinism guarantees:\n * - Imported records are returned sorted by `sourcePath`.\n * - Skipped records are returned sorted by `path`.\n * - Fork-mode rebases under a stable `forks/<capsule-id>/` prefix so\n * repeated fork imports of the same capsule shape land in predictable\n * locations (subsequent fork imports still skip-on-exist because the\n * target tree is computed from the source path).\n */\nexport async function importCapsule(\n opts: ImportCapsuleOptions,\n): Promise<ImportCapsuleResult> {\n const archiveAbs = path.resolve(opts.archivePath);\n const rootAbs = path.resolve(opts.root);\n await assertIsDirectoryNotSymlink(rootAbs, \"importCapsule\", \"root\");\n\n const mode: ImportCapsuleMode = opts.mode ?? \"skip\";\n // Reject unknown mode values up-front (rule 51). TypeScript callers get a\n // compile-time check via the union type; JS/CLI callers get a runtime error\n // here before any write begins — not a silent destructive fallback.\n if (mode !== \"skip\" && mode !== \"overwrite\" && mode !== \"fork\") {\n throw new Error(\n `importCapsule: unknown mode ${JSON.stringify(mode)}; expected \"skip\", \"overwrite\", or \"fork\"`,\n );\n }\n\n // Auto-detect encrypted archives. If the file ends with `.enc` or starts\n // with the REMNIC-ENC magic header, decrypt it first before gunzip+parse.\n // Rule 48: default is \"not encrypted\"; we only attempt decryption when the\n // header is definitively present, never on ambiguous content.\n const encrypted = await isEncryptedCapsuleFile(archiveAbs);\n let raw: Buffer;\n if (encrypted) {\n if (!opts.memoryDir && !opts.passphrase) {\n throw new Error(\n `importCapsule: archive is encrypted but 'memoryDir' was not provided. ` +\n `Pass the memory directory so the secure-store key can be retrieved, ` +\n `provide the original passphrase for a format-v2 archive restore, ` +\n `or run \\`remnic secure-store unlock\\` before importing.`,\n );\n }\n raw = await decryptCapsuleFileInMemory(archiveAbs, opts.memoryDir, {\n passphrase: opts.passphrase,\n });\n } else {\n raw = await readFile(archiveAbs);\n }\n const json = gunzipSync(raw).toString(\"utf-8\");\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(json);\n } catch (cause) {\n throw new Error(\n `importCapsule: archive is not valid JSON after gunzip: ${archiveAbs}`,\n { cause: cause as Error },\n );\n }\n\n const parsed = parseExportBundle(parsedJson);\n if (parsed.capsuleVersion !== 2) {\n // PR 1/6 ships a V1 reader; capsule import is V2-only by design. A V1\n // bundle does not carry a capsule block, so fork-mode (which depends on\n // `capsule.id` for the rebase prefix) cannot work. Reject up-front per\n // gotcha #51 instead of silently routing to a different code path.\n throw new Error(\n \"importCapsule: archive is V1; only V2 capsule archives are supported\",\n );\n }\n const bundle = parsed.bundle as { manifest: ExportManifestV2; records: ExportMemoryRecordV1[] };\n const manifest = bundle.manifest;\n const capsule = manifest.capsule;\n\n // Build a path → manifest-entry index for O(1) checksum lookup. The\n // manifest is the source of truth; records-without-manifest-entries and\n // manifest-entries-without-records are both treated as corruption.\n const manifestIndex = new Map<string, ExportManifestV2[\"files\"][number]>();\n for (const f of manifest.files) {\n manifestIndex.set(f.path, f);\n }\n if (manifestIndex.size !== manifest.files.length) {\n throw new Error(\n \"importCapsule: manifest contains duplicate file paths\",\n );\n }\n const recordPaths = new Set<string>();\n for (const rec of bundle.records) {\n if (recordPaths.has(rec.path)) {\n throw new Error(\n `importCapsule: bundle contains duplicate record path: ${rec.path}`,\n );\n }\n recordPaths.add(rec.path);\n }\n\n // Phase 1: verify every record matches its manifest entry AND validate all\n // target paths before any filesystem mutation. We do both in a single pass\n // so a corrupted or malicious archive cannot leave the memory dir partially\n // written (fail-closed per gotcha #25).\n //\n // The real root is resolved once via realpath so the subsequent per-record\n // inside-root checks are symlink-aware: a record path like `facts/a.md`\n // cannot write outside the intended sandbox via a symlinked subdirectory\n // (Codex P1 feedback). If realpath fails (root does not exist) the earlier\n // assertIsDirectoryNotSymlink call already threw, so this should always succeed.\n const rootReal = await realpath(rootAbs).catch(() => rootAbs);\n\n // Tracks normalized, case-folded target paths seen so far in phase 1. Maps\n // targetAbs.toLowerCase() → first source path so the collision error can name\n // both offending entries. Two manifest entries whose computed target paths\n // normalize to the same absolute path (e.g. `subdir/file.md` and\n // `subdir/./file.md`, or differing case on case-insensitive filesystems such\n // as macOS and Windows) would both try to write the same inode — the second\n // would silently overwrite the first. We reject the import up-front before\n // any write (Codex P2 thread on PR #741, line 283).\n const seenTargetPaths = new Map<string, string>();\n\n for (const rec of bundle.records) {\n // Checksum validation.\n const entry = manifestIndex.get(rec.path);\n if (!entry) {\n throw new Error(\n `importCapsule: archive checksum mismatch (record without manifest entry: ${rec.path})`,\n );\n }\n const { sha256, bytes } = sha256String(rec.content);\n if (sha256 !== entry.sha256 || bytes !== entry.bytes) {\n throw new Error(\n `importCapsule: archive checksum mismatch for ${rec.path}: ` +\n `expected sha256=${entry.sha256} bytes=${entry.bytes}, ` +\n `got sha256=${sha256} bytes=${bytes}`,\n );\n }\n\n // Source path validation: reject any record whose posix source path\n // contains a `..` segment, an absolute prefix, or any component that would\n // let fork-mode bypass its isolation invariant. This check runs before\n // `computeTargetPath` so that fork mode's `forks/<id>/` rebase cannot be\n // bypassed by a path like `../../profile.md` (which `path.join` would\n // silently collapse, landing the file inside root but outside the fork\n // prefix — Cursor medium thread #741). Rejecting `..` up-front is simpler\n // and more robust than normalising after the fact.\n //\n // Extended guard (Codex P1 #741 round 5): also reject paths containing\n // backslash separators (`\\`), which are Windows path separators. On Windows\n // a path like `..\\\\escape.md` or `subdir\\\\..\\\\..\\\\escape.md` would resolve\n // to a parent traversal but would bypass a purely posix-split check.\n // Additionally, after posix-normalizing the path we re-check for a leading\n // `..` or `/` — this catches edge-cases such as `subdir/../..` where the\n // individual split segments are not `..` but the normalized result is.\n if (rec.path.includes(\"\\\\\")) {\n throw new Error(\n `importCapsule: record path contains backslash separators (Windows-style paths are not allowed): ${rec.path}`,\n );\n }\n const posixNormalized = path.posix.normalize(rec.path);\n if (\n rec.path.startsWith(\"/\") ||\n rec.path.split(\"/\").some((seg) => seg === \"..\") ||\n posixNormalized.startsWith(\"..\") ||\n posixNormalized.startsWith(\"/\")\n ) {\n throw new Error(\n `importCapsule: record path escapes target root: ${rec.path}`,\n );\n }\n\n // Path-traversal validation (moved here from phase 2 per Cursor feedback:\n // the traversal check must run before ANY write so a malicious archive\n // with an escaping path that sorts last cannot land partial writes).\n //\n // We build targetAbs relative to the real-resolved root (rootReal) so\n // that the inside-root check is symlink-aware: if `rootReal !== rootAbs`\n // (the import root is itself behind a symlink), we still compare against\n // the canonical path (Codex P1).\n const targetRel = computeTargetPath(rec.path, mode, capsule.id);\n const targetAbs = path.join(rootReal, fromPosixRelPath(targetRel));\n if (!isPathInsideRoot(rootReal, targetAbs)) {\n throw new Error(\n `importCapsule: record path escapes target root: ${rec.path}`,\n );\n }\n\n // Symlink-aware containment check (Cursor thread #741 line 247/264).\n // The lexical check above handles `..`-traversal but cannot detect\n // symlinked subdirectories that point outside the root. We resolve the\n // nearest existing ancestor of the target via realpath to catch symlinks\n // anywhere in the path components. If any resolved prefix escapes rootReal,\n // the import is rejected before any write. This applies to ALL modes,\n // including fork mode whose rebase prefix may itself traverse a symlink.\n await assertRealpathInsideRoot(rootReal, targetAbs, rec.path, \"importCapsule\");\n\n // Target-file symlink check (Codex P1 #741 round 4, line 260).\n // `assertRealpathInsideRoot` resolves the nearest existing *ancestor* to\n // catch symlinked parent directories, but if the TARGET FILE itself already\n // exists and is a symlink, that check passes (the parent is real) while the\n // write would silently follow the symlink to a path outside root. We\n // therefore lstat the target directly: if it exists and is a symlink we\n // reject the record up-front. For new files the parent-canonicalization\n // performed above is sufficient; no realpath of a non-existent file is\n // needed.\n const targetLstat = await lstat(targetAbs).catch(() => null);\n if (targetLstat !== null && targetLstat.isSymbolicLink()) {\n throw new Error(\n `importCapsule: record target is a symlink and cannot be written to safely: ${rec.path}`,\n );\n }\n\n // Duplicate normalized target path detection (Codex P2 #741, line 283).\n // `path.join` already normalises `.` segments (e.g. `subdir/./file.md` →\n // `subdir/file.md`). On case-insensitive filesystems (macOS default,\n // Windows), two paths that differ only in case would resolve to the same\n // inode. We fold the dedup key to lowercase so that `subdir/File.md` and\n // `subdir/file.md` are detected as duplicates before any write occurs.\n // This is intentionally unconditional: the cost of an extra `.toLowerCase()`\n // on case-sensitive filesystems is negligible, and a defensive lowercase\n // is far simpler than probing filesystem case-sensitivity at runtime.\n const dedupKey = targetAbs.toLowerCase();\n const firstSourcePath = seenTargetPaths.get(dedupKey);\n if (firstSourcePath !== undefined) {\n throw new Error(\n `importCapsule: manifest contains two entries that resolve to the same target path: ` +\n `\"${firstSourcePath}\" and \"${rec.path}\" both map to \"${targetRel}\"`,\n );\n }\n seenTargetPaths.set(dedupKey, rec.path);\n }\n // Detect manifest-only entries (missing record). Treat as corruption.\n for (const f of manifest.files) {\n if (!recordPaths.has(f.path)) {\n throw new Error(\n `importCapsule: archive checksum mismatch (manifest entry without record: ${f.path})`,\n );\n }\n }\n\n // Phase 2: apply the mode. All records were validated in phase 1; we now\n // write to disk. Per-record errors propagate; each individual write is\n // atomic (mkdir + writeFile pair).\n const imported: ImportCapsuleImportedRecord[] = [];\n const skipped: ImportCapsuleSkippedRecord[] = [];\n\n // Sort by source path so the imported/skipped lists are deterministic\n // regardless of bundle order. (`exportCapsule` already sorts; we re-sort\n // defensively in case a hand-edited archive ships records in another order.)\n const sortedRecords = [...bundle.records].sort((a, b) =>\n a.path.localeCompare(b.path),\n );\n\n for (const rec of sortedRecords) {\n const targetRel = computeTargetPath(rec.path, mode, capsule.id);\n // Use rootReal (realpath-resolved) to stay consistent with phase 1's\n // traversal validation and avoid writing through stale symlinks.\n const targetAbs = path.join(rootReal, fromPosixRelPath(targetRel));\n\n const exists = await fileExistsAt(targetAbs);\n\n // Skip logic applies to both `skip` mode (explicit) and `fork` mode\n // (Cursor medium: fork mode must also be skip-on-exist for the computed\n // fork path, because production imports generate non-deterministic IDs —\n // so re-importing the same capsule should not overwrite user edits in the\n // fork tree or silently change file identities by generating new IDs).\n if ((mode === \"skip\" || mode === \"fork\") && exists) {\n skipped.push({ path: rec.path, reason: \"exists\" });\n continue;\n }\n\n let snapshotted = false;\n if (mode === \"overwrite\" && exists) {\n // Gotcha #54: snapshot BEFORE overwriting. If snapshot creation fails\n // we abort this record's import rather than silently destroying\n // history. The page-versioning module is responsible for atomic\n // sidecar writes; we just call it.\n if (opts.versioning && opts.versioning.enabled) {\n const prior = await readFile(targetAbs, \"utf-8\").catch(() => \"\");\n await createVersion(\n targetAbs,\n prior,\n \"manual\",\n opts.versioning,\n opts.log,\n `capsule-import: ${capsule.id}`,\n rootReal,\n );\n snapshotted = true;\n }\n }\n\n let contentToWrite = rec.content;\n let rewroteId = false;\n if (mode === \"fork\") {\n const forked = rewriteFrontmatterIdForFork(rec.content, capsule.id, opts.now);\n contentToWrite = forked.content;\n rewroteId = forked.rewrote;\n }\n\n await mkdir(path.dirname(targetAbs), { recursive: true });\n await writeFile(targetAbs, contentToWrite, \"utf-8\");\n // Bump the corpus sentinel per write (Cursor Medium, #1902): a concurrent\n // readAllMemories during the import must rescan and see records already on\n // disk, never the pre-import corpus, mid-batch.\n bumpMemoryCorpusVersionForDir(rootReal);\n imported.push({\n sourcePath: rec.path,\n targetPath: targetRel,\n snapshotted,\n rewroteId,\n });\n }\n\n // Sort skipped for stable output (see comment above).\n skipped.sort((a, b) => a.path.localeCompare(b.path));\n\n // Per-record corpus bumps happen inside the loop above (Cursor Medium,\n // #1902); no after-batch bump needed here.\n\n return { imported, skipped, manifest };\n}\n\n// ---------------------------------------------------------------------------\n// Path helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the destination relative path for a record under the chosen\n * mode.\n *\n * - `skip` / `overwrite` — identity: the record's posix path is used as-is.\n * - `fork` — rebased under `forks/<capsule-id>/<original-path>` so the\n * original tree is never modified.\n */\nfunction computeTargetPath(\n sourcePosix: string,\n mode: ImportCapsuleMode,\n capsuleId: string,\n): string {\n if (mode === \"fork\") return `forks/${capsuleId}/${sourcePosix}`;\n return sourcePosix;\n}\n\nasync function fileExistsAt(absPath: string): Promise<boolean> {\n const st = await stat(absPath).catch(() => null);\n return st !== null && st.isFile();\n}\n\n// ---------------------------------------------------------------------------\n// Fork-mode id rewriting\n// ---------------------------------------------------------------------------\n\n/**\n * Rewrite a YAML-frontmatter `id:` field to a fork-scoped value.\n *\n * Strategy: we deliberately do NOT parse the entire YAML — memory files\n * use a deterministic top-of-file frontmatter delimited by `---` lines,\n * and the orchestrator's `parseFrontmatter` reads `id` as a top-level\n * key with a single-line scalar value. We mirror that contract:\n *\n * - Detect a leading `---\\n` … `\\n---` block at the top of the file.\n * - Within that block, locate the first `id:` line that is not nested\n * under another key (cheap heuristic: line starts at column 0).\n * - Replace its value with a new fork-id derived from `capsuleId` and\n * a short random suffix (or {@link opts.now} when provided for tests).\n *\n * Files without a frontmatter block, or without an `id:` key inside one,\n * are returned unchanged with `rewrote: false`. This keeps non-memory\n * artifacts (READMEs, transcripts) byte-identical to the source.\n */\nfunction rewriteFrontmatterIdForFork(\n content: string,\n capsuleId: string,\n now: number | undefined,\n): { content: string; rewrote: boolean } {\n // Detect the dominant line ending in the file so we can preserve it when\n // rebuilding the frontmatter delimiters. Splitting/joining on `\\n` silently\n // drops `\\r` from CRLF files, changing the byte content (Cursor thread #741\n // line 467). We detect the ending of the very first line (the opening `---`)\n // and use that as the canonical separator for the reconstructed delimiters.\n // All three cases are covered: CRLF (\\r\\n), LF (\\n), and bare CR (\\r).\n const crlfMatch = /^---(\\r\\n|\\r|\\n)/.exec(content);\n // Fall back to LF if the file starts with `---` but has no newline (EOF).\n const eol = crlfMatch ? crlfMatch[1] : \"\\n\";\n\n // Frontmatter block detection: `---` on its own line at the very start,\n // followed by content, followed by `---` on its own line. The closing\n // delimiter must be at column 0. We capture the trailing terminator\n // (`\\r?\\n` or end-of-string) as a separate group so we can re-emit it\n // verbatim, preserving CRLF/LF/EOF shape from the original file.\n const fmMatch = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(\\r?\\n|$)/.exec(content);\n if (!fmMatch) return { content, rewrote: false };\n const fmBody = fmMatch[1];\n const fmTrailer = fmMatch[2];\n const fmStart = fmMatch.index;\n const fmEnd = fmStart + fmMatch[0].length;\n\n // Find a top-level `id:` line. Top-level means the line begins at\n // column 0 inside the frontmatter body (no leading whitespace) and the\n // key is exactly `id`. We deliberately accept `id:` and `id : ` shapes\n // but reject `nested_id:` to avoid touching unrelated keys.\n const idLineRe = /^id:[ \\t]*([^\\r\\n]*)$/m;\n const idMatch = idLineRe.exec(fmBody);\n if (!idMatch) return { content, rewrote: false };\n\n const newId = mintForkId(capsuleId, idMatch[1]?.trim() ?? \"\", now);\n const replacedBody = fmBody.replace(idLineRe, `id: ${newId}`);\n // Reconstruct the file: original prefix (always empty here, fmStart === 0\n // by the `^` anchor) + frontmatter delimiters around the rewritten body.\n // Use the detected `eol` for the opening/closing `---` lines so that CRLF\n // files remain CRLF and LF files remain LF, preserving byte-content fidelity\n // (Cursor thread #741 line 467). The captured `fmTrailer` (the newline\n // immediately after the closing `---`, or end-of-string) is re-emitted\n // verbatim so the byte immediately after the closing fence is unchanged.\n const prefix = content.slice(0, fmStart);\n const tail = content.slice(fmEnd);\n const rebuilt = `${prefix}---${eol}${replacedBody}${eol}---${fmTrailer}${tail}`;\n return { content: rebuilt, rewrote: true };\n}\n\n/**\n * Derive a deterministic-when-`now`-is-set fork id from the capsule id and\n * the original record id. Production callers omit `now` and get a UUID\n * suffix; tests pass `now` for byte-stable assertions.\n */\nfunction mintForkId(capsuleId: string, originalId: string, now: number | undefined): string {\n const base = originalId.length > 0 ? originalId : \"fork\";\n if (now === undefined) {\n const suffix = randomUUID().slice(0, 8);\n return `${base}-fork-${capsuleId}-${suffix}`;\n }\n // Deterministic suffix: short hash of (capsuleId, originalId, now). Using\n // sha256 over a sorted-key serialization (gotcha #38) so the suffix does\n // not depend on Object.entries order.\n const payload = JSON.stringify({ c: capsuleId, i: originalId, n: now });\n const suffix = createHash(\"sha256\").update(payload, \"utf-8\").digest(\"hex\").slice(0, 8);\n return `${base}-fork-${capsuleId}-${suffix}`;\n}\n\n// Note: `CapsuleBlock` is re-exported here purely so callers that want to\n// inspect the manifest block don't have to deep-import from `./types.js`.\nexport type { CapsuleBlock };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,OAAO,UAAU,UAAU,MAAM,iBAAiB;AAClE,OAAO,UAAU;AACjB,SAAS,YAAY,kBAAkB;AACvC,SAAS,kBAAkB;AAqJ3B,eAAsB,cACpB,MAC8B;AAC9B,QAAM,aAAa,KAAK,QAAQ,KAAK,WAAW;AAChD,QAAM,UAAU,KAAK,QAAQ,KAAK,IAAI;AACtC,QAAM,4BAA4B,SAAS,iBAAiB,MAAM;AAElE,QAAM,OAA0B,KAAK,QAAQ;AAI7C,MAAI,SAAS,UAAU,SAAS,eAAe,SAAS,QAAQ;AAC9D,UAAM,IAAI;AAAA,MACR,+BAA+B,KAAK,UAAU,IAAI,CAAC;AAAA,IACrD;AAAA,EACF;AAMA,QAAM,YAAY,MAAM,uBAAuB,UAAU;AACzD,MAAI;AACJ,MAAI,WAAW;AACb,QAAI,CAAC,KAAK,aAAa,CAAC,KAAK,YAAY;AACvC,YAAM,IAAI;AAAA,QACR;AAAA,MAIF;AAAA,IACF;AACA,UAAM,MAAM,2BAA2B,YAAY,KAAK,WAAW;AAAA,MACjE,YAAY,KAAK;AAAA,IACnB,CAAC;AAAA,EACH,OAAO;AACL,UAAM,MAAM,SAAS,UAAU;AAAA,EACjC;AACA,QAAM,OAAO,WAAW,GAAG,EAAE,SAAS,OAAO;AAC7C,MAAI;AACJ,MAAI;AACF,iBAAa,KAAK,MAAM,IAAI;AAAA,EAC9B,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,0DAA0D,UAAU;AAAA,MACpE,EAAE,MAAsB;AAAA,IAC1B;AAAA,EACF;AAEA,QAAM,SAAS,kBAAkB,UAAU;AAC3C,MAAI,OAAO,mBAAmB,GAAG;AAK/B,UAAM,IAAI;AAAA,MACR;AAA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QAAM,UAAU,KAAK,UAAU,EAAE,GAAG,WAAW,GAAG,YAAY,GAAG,IAAI,CAAC;AACtE,QAAM,SAAS,WAAW,QAAQ,EAAE,OAAO,SAAS,OAAO,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,CAAC;AACrF,SAAO,GAAG,IAAI,SAAS,SAAS,IAAI,MAAM;AAC5C;","names":["suffix"]}
@@ -0,0 +1,27 @@
1
+ import {
2
+ invalidateDerivedAndGlobalForDir
3
+ } from "./chunk-X47LWMKA.js";
4
+ import {
5
+ deleteInFlightReadsForDir
6
+ } from "./chunk-PDJTHRAW.js";
7
+
8
+ // src/memory-corpus-version.ts
9
+ import { appendFileSync, mkdirSync } from "fs";
10
+ import path from "path";
11
+ var MEMORY_CORPUS_VERSION_SENTINEL = ".memory-corpus-version.log";
12
+ function bumpMemoryCorpusVersionForDir(memoryDir) {
13
+ try {
14
+ const stateDir = path.join(memoryDir, "state");
15
+ mkdirSync(stateDir, { recursive: true });
16
+ appendFileSync(path.join(stateDir, MEMORY_CORPUS_VERSION_SENTINEL), "x");
17
+ } catch {
18
+ }
19
+ deleteInFlightReadsForDir(memoryDir);
20
+ invalidateDerivedAndGlobalForDir(memoryDir);
21
+ }
22
+
23
+ export {
24
+ MEMORY_CORPUS_VERSION_SENTINEL,
25
+ bumpMemoryCorpusVersionForDir
26
+ };
27
+ //# sourceMappingURL=chunk-OKUEZOGW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/memory-corpus-version.ts"],"sourcesContent":["import { appendFileSync, mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { deleteInFlightReadsForDir } from \"./in-flight-reads.js\";\nimport { invalidateDerivedAndGlobalForDir } from \"./memory-cache.js\";\n\n/**\n * Filename of the memory-corpus version sentinel (issue #1902). MUST stay in\n * sync with `StorageManager.versionFilePath(\"memory-corpus\")` in storage.ts —\n * the byte size of this append-only file IS the corpus version, and the\n * version-keyed hot-memories result cache keys on it.\n */\nexport const MEMORY_CORPUS_VERSION_SENTINEL = \".memory-corpus-version.log\";\n\n/**\n * Out-of-band corpus-version bump (issue #1902) for code paths that write or\n * modify memory files WITHOUT going through a StorageManager mutation method\n * — review approval, governance restore, migration. Appends one byte to the\n * on-disk sentinel so any process's version-keyed hot-memories cache rescans\n * on its next read (StorageManager.readSharedVersion reads the file size, so\n * the growth is observed immediately). Fail-open: a bump failure must never\n * crash the caller — a stale-cache window self-heals on the next real write.\n */\nexport function bumpMemoryCorpusVersionForDir(memoryDir: string): void {\n try {\n const stateDir = path.join(memoryDir, \"state\");\n mkdirSync(stateDir, { recursive: true });\n appendFileSync(path.join(stateDir, MEMORY_CORPUS_VERSION_SENTINEL), \"x\");\n } catch {\n /* fail-open: never let a cache-coherence bump crash the primary operation */\n }\n // Drop any in-flight readAllMemories scan for this dir (Cursor Medium, #1902):\n // after the sentinel advances, a concurrent read that missed the version-keyed\n // hot entry must not attach to a scan that began BEFORE this out-of-band write\n // and receive a pre-write corpus. Clearing forces a fresh scan of disk truth.\n deleteInFlightReadsForDir(memoryDir);\n // Also evict the TTL-keyed derived (episode/rule) and global (QMD search/recall)\n // caches for this dir (issue #1902, Codex Medium). The sentinel bump self-heals\n // the version-keyed hot cache, but the QMD caches are TTL-keyed, NOT\n // corpus-version-keyed — without this, an out-of-band writer (capsule\n // import/merge, review, spaces, governance restore, page revert, binary\n // redirect) would leave a warm process serving pre-write recall/search results\n // for the remainder of the QMD cache TTL. Route the bump through the same\n // invalidation chokepoint the in-process mutation paths use.\n invalidateDerivedAndGlobalForDir(memoryDir);\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,gBAAgB,iBAAiB;AAC1C,OAAO,UAAU;AAUV,IAAM,iCAAiC;AAWvC,SAAS,8BAA8B,WAAyB;AACrE,MAAI;AACF,UAAM,WAAW,KAAK,KAAK,WAAW,OAAO;AAC7C,cAAU,UAAU,EAAE,WAAW,KAAK,CAAC;AACvC,mBAAe,KAAK,KAAK,UAAU,8BAA8B,GAAG,GAAG;AAAA,EACzE,QAAQ;AAAA,EAER;AAKA,4BAA0B,SAAS;AASnC,mCAAiC,SAAS;AAC5C;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-SOBJ6NEY.js";
4
4
  import {
5
5
  summarizeDisclosureTokens
6
- } from "./chunk-DQPPRXFO.js";
6
+ } from "./chunk-HQ7QZJM5.js";
7
7
  import {
8
8
  summarizeRetrievedMemoryProvenance
9
9
  } from "./chunk-I4WBNM3M.js";
@@ -587,4 +587,4 @@ export {
587
587
  renderRecallExplain,
588
588
  parseRecallExplainFormat
589
589
  };
590
- //# sourceMappingURL=chunk-PKGWJFNR.js.map
590
+ //# sourceMappingURL=chunk-OVMS3DCB.js.map
@@ -0,0 +1,36 @@
1
+ // src/in-flight-reads.ts
2
+ var inFlightReadsByKey = /* @__PURE__ */ new Map();
3
+ var DIR_SEP = "\0";
4
+ function composeKey(baseDir, keyId) {
5
+ return `${baseDir}${DIR_SEP}${keyId}`;
6
+ }
7
+ function getInFlightRead(baseDir, keyId = "") {
8
+ return inFlightReadsByKey.get(composeKey(baseDir, keyId));
9
+ }
10
+ function setInFlightRead(baseDir, keyId, read) {
11
+ inFlightReadsByKey.set(composeKey(baseDir, keyId), read);
12
+ }
13
+ function deleteInFlightRead(baseDir, keyId = "", expected) {
14
+ const key = composeKey(baseDir, keyId);
15
+ if (expected === void 0 || inFlightReadsByKey.get(key) === expected) {
16
+ inFlightReadsByKey.delete(key);
17
+ }
18
+ }
19
+ function deleteInFlightReadsForDir(baseDir) {
20
+ const prefix = `${baseDir}${DIR_SEP}`;
21
+ for (const key of inFlightReadsByKey.keys()) {
22
+ if (key.startsWith(prefix)) inFlightReadsByKey.delete(key);
23
+ }
24
+ }
25
+ function clearInFlightReads() {
26
+ inFlightReadsByKey.clear();
27
+ }
28
+
29
+ export {
30
+ getInFlightRead,
31
+ setInFlightRead,
32
+ deleteInFlightRead,
33
+ deleteInFlightReadsForDir,
34
+ clearInFlightReads
35
+ };
36
+ //# sourceMappingURL=chunk-PDJTHRAW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/in-flight-reads.ts"],"sourcesContent":["import type { MemoryFile } from \"./types.js\";\n\n/**\n * In-flight readAllMemories() dedup registry (issue #1902).\n *\n * NOT a cache layer — it holds transient per-(directory, secure-store key) scan\n * promises so temporally-overlapping reads collapse onto ONE disk scan; the slot\n * is deleted when the promise settles. It lives in its own module (not\n * memory-cache.ts) so it is not swept by the ALL_CACHE_LAYERS invalidation\n * contract, yet remains importable by both StorageManager and the out-of-band\n * corpus-bump helper (memory-corpus-version.ts).\n *\n * Keyed by baseDir AND secure-store key identity (Codex P1 / Cursor Medium):\n * an unlocked manager's decrypted scan must NOT be handed to a locked or\n * differently-keyed manager for the same dir — that would bypass the keyId\n * isolation getCachedMemories enforces. Locked/plaintext stores use keyId \"\".\n */\nconst inFlightReadsByKey = new Map<string, Promise<MemoryFile[]>>();\n\nconst DIR_SEP = \"\\u0000\";\n\nfunction composeKey(baseDir: string, keyId: string): string {\n return `${baseDir}${DIR_SEP}${keyId}`;\n}\n\nexport function getInFlightRead(baseDir: string, keyId = \"\"): Promise<MemoryFile[]> | undefined {\n return inFlightReadsByKey.get(composeKey(baseDir, keyId));\n}\n\nexport function setInFlightRead(baseDir: string, keyId: string, read: Promise<MemoryFile[]>): void {\n inFlightReadsByKey.set(composeKey(baseDir, keyId), read);\n}\n\n/**\n * Delete the in-flight slot for one (baseDir, keyId). When `expected` is given,\n * only deletes if the slot still holds that exact promise (owner-only clear).\n */\nexport function deleteInFlightRead(\n baseDir: string,\n keyId = \"\",\n expected?: Promise<MemoryFile[]>,\n): void {\n const key = composeKey(baseDir, keyId);\n if (expected === undefined || inFlightReadsByKey.get(key) === expected) {\n inFlightReadsByKey.delete(key);\n }\n}\n\n/**\n * Drop EVERY in-flight slot for `baseDir` across all secure-store identities.\n * Used by mutations / invalidation / out-of-band corpus bumps: after the corpus\n * changes, no reader of any key identity may attach to a pre-mutation scan.\n */\nexport function deleteInFlightReadsForDir(baseDir: string): void {\n const prefix = `${baseDir}${DIR_SEP}`;\n for (const key of inFlightReadsByKey.keys()) {\n if (key.startsWith(prefix)) inFlightReadsByKey.delete(key);\n }\n}\n\nexport function clearInFlightReads(): void {\n inFlightReadsByKey.clear();\n}\n"],"mappings":";AAiBA,IAAM,qBAAqB,oBAAI,IAAmC;AAElE,IAAM,UAAU;AAEhB,SAAS,WAAW,SAAiB,OAAuB;AAC1D,SAAO,GAAG,OAAO,GAAG,OAAO,GAAG,KAAK;AACrC;AAEO,SAAS,gBAAgB,SAAiB,QAAQ,IAAuC;AAC9F,SAAO,mBAAmB,IAAI,WAAW,SAAS,KAAK,CAAC;AAC1D;AAEO,SAAS,gBAAgB,SAAiB,OAAe,MAAmC;AACjG,qBAAmB,IAAI,WAAW,SAAS,KAAK,GAAG,IAAI;AACzD;AAMO,SAAS,mBACd,SACA,QAAQ,IACR,UACM;AACN,QAAM,MAAM,WAAW,SAAS,KAAK;AACrC,MAAI,aAAa,UAAa,mBAAmB,IAAI,GAAG,MAAM,UAAU;AACtE,uBAAmB,OAAO,GAAG;AAAA,EAC/B;AACF;AAOO,SAAS,0BAA0B,SAAuB;AAC/D,QAAM,SAAS,GAAG,OAAO,GAAG,OAAO;AACnC,aAAW,OAAO,mBAAmB,KAAK,GAAG;AAC3C,QAAI,IAAI,WAAW,MAAM,EAAG,oBAAmB,OAAO,GAAG;AAAA,EAC3D;AACF;AAEO,SAAS,qBAA2B;AACzC,qBAAmB,MAAM;AAC3B;","names":[]}
@@ -1,10 +1,10 @@
1
+ import {
2
+ SQLITE_SCHEMA_VERSION
3
+ } from "./chunk-Z734BLO3.js";
1
4
  import {
2
5
  parseConflictPolicy,
3
6
  validateManifestRecords
4
7
  } from "./chunk-G4IAEX6D.js";
5
- import {
6
- SQLITE_SCHEMA_VERSION
7
- } from "./chunk-Z734BLO3.js";
8
8
  import {
9
9
  openBetterSqlite3
10
10
  } from "./chunk-RL6NEVXT.js";
@@ -84,4 +84,4 @@ async function importSqlite(opts) {
84
84
  export {
85
85
  importSqlite
86
86
  };
87
- //# sourceMappingURL=chunk-LRGSLV7M.js.map
87
+ //# sourceMappingURL=chunk-PYHOAXTI.js.map
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-V7IZKJI3.js";
4
4
  import {
5
5
  AdapterRegistry
6
- } from "./chunk-RKNJBZ55.js";
6
+ } from "./chunk-JBPKEARU.js";
7
7
  import {
8
8
  EngramMcpServer,
9
9
  MCP_SUPPORTED_PROTOCOL_VERSIONS,
@@ -13,7 +13,7 @@ import {
13
13
  processChatMessage,
14
14
  sessionBelongsToPrincipal,
15
15
  subscribeChatTranscript
16
- } from "./chunk-CHVU4RE5.js";
16
+ } from "./chunk-VDLMAJXS.js";
17
17
  import {
18
18
  validateRequest
19
19
  } from "./chunk-2MR3MFQB.js";
@@ -28,7 +28,7 @@ import {
28
28
  } from "./chunk-35NN3ZFA.js";
29
29
  import {
30
30
  getOperation
31
- } from "./chunk-57INMZ6F.js";
31
+ } from "./chunk-UZRIKUFS.js";
32
32
  import {
33
33
  assertOperationAllowed,
34
34
  enforceNamespaceAllowList,
@@ -38,7 +38,7 @@ import {
38
38
  import {
39
39
  CorrectionContractError,
40
40
  EngramAccessInputError
41
- } from "./chunk-CNWC274T.js";
41
+ } from "./chunk-3OQ4IZJN.js";
42
42
  import {
43
43
  isTrustZoneName
44
44
  } from "./chunk-JGSKJHF7.js";
@@ -50,7 +50,7 @@ import {
50
50
  } from "./chunk-DEUNUKTD.js";
51
51
  import {
52
52
  isRecallDisclosure
53
- } from "./chunk-JO5AT6QT.js";
53
+ } from "./chunk-3ZVFLMFQ.js";
54
54
  import {
55
55
  expandTildePath
56
56
  } from "./chunk-EYIEWJNI.js";
@@ -2972,4 +2972,4 @@ function positiveIntQueryParam(value, label) {
2972
2972
  export {
2973
2973
  EngramAccessHttpServer
2974
2974
  };
2975
- //# sourceMappingURL=chunk-NMMKRVUF.js.map
2975
+ //# sourceMappingURL=chunk-QVALQE4P.js.map
@@ -43,7 +43,7 @@ import {
43
43
  FallbackLlmClient,
44
44
  fallbackLlmRuntimeContextFromConfig,
45
45
  gatewayTaskChainOptions
46
- } from "./chunk-GKCCHHZK.js";
46
+ } from "./chunk-UXKMMNJD.js";
47
47
  import {
48
48
  buildChatCompletionTokenLimit,
49
49
  shouldAssumeOpenAiChatCompletions
@@ -2476,4 +2476,4 @@ export {
2476
2476
  classifyFallbackParseFailure,
2477
2477
  ExtractionEngine
2478
2478
  };
2479
- //# sourceMappingURL=chunk-FXGC5UUH.js.map
2479
+ //# sourceMappingURL=chunk-RT7IP3D3.js.map
@@ -6,7 +6,7 @@ import {
6
6
  } from "./chunk-SFQ6QNL7.js";
7
7
  import {
8
8
  StorageManager
9
- } from "./chunk-KTOH7EJE.js";
9
+ } from "./chunk-KXLRMM35.js";
10
10
  import {
11
11
  buildLifecycleEventsForMemory,
12
12
  sortMemoryLifecycleEvents
@@ -115,4 +115,4 @@ export {
115
115
  backupExistingLedger,
116
116
  rebuildMemoryLifecycleLedger
117
117
  };
118
- //# sourceMappingURL=chunk-AH3M6F4X.js.map
118
+ //# sourceMappingURL=chunk-SBFDL2EQ.js.map
@@ -10,7 +10,7 @@ import {
10
10
  import {
11
11
  planNamespaceMaintenance,
12
12
  runNamespaceMaintenanceBatchPlan
13
- } from "./chunk-O3BZ6PFY.js";
13
+ } from "./chunk-JZM5QUTE.js";
14
14
  import {
15
15
  resolveConsolidationCapabilities,
16
16
  resolveNamespaceCapabilities,
@@ -447,4 +447,4 @@ var MaintenanceScheduler = class {
447
447
  export {
448
448
  MaintenanceScheduler
449
449
  };
450
- //# sourceMappingURL=chunk-UYZUJ4EB.js.map
450
+ //# sourceMappingURL=chunk-SECMZACR.js.map
@@ -4,7 +4,7 @@ import {
4
4
  import {
5
5
  compareEntityTimestamps,
6
6
  normalizeEntityName
7
- } from "./chunk-KTOH7EJE.js";
7
+ } from "./chunk-KXLRMM35.js";
8
8
  import {
9
9
  resolveNamespaceCapabilities
10
10
  } from "./chunk-BFPETA3S.js";
@@ -682,4 +682,4 @@ export {
682
682
  entityIndexVersion,
683
683
  entityRecentTranscriptLookbackHours
684
684
  };
685
- //# sourceMappingURL=chunk-HXDKC3BI.js.map
685
+ //# sourceMappingURL=chunk-TGBJ2OMK.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  isTemporalQuery,
3
3
  recencyWindowBoundsFromPrompt
4
- } from "./chunk-HHAA35A3.js";
4
+ } from "./chunk-2VN4JAX7.js";
5
5
  import {
6
6
  log
7
7
  } from "./chunk-37CTGERM.js";
@@ -406,4 +406,4 @@ export {
406
406
  augmentWithDirectAndTemporal,
407
407
  parallelRetrieval
408
408
  };
409
- //# sourceMappingURL=chunk-DE6ENYLG.js.map
409
+ //# sourceMappingURL=chunk-TXLGHDHS.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-EGGE52UU.js";
5
5
  import {
6
6
  StorageManager
7
- } from "./chunk-KTOH7EJE.js";
7
+ } from "./chunk-KXLRMM35.js";
8
8
  import {
9
9
  MutationSerializer
10
10
  } from "./chunk-LTJAMRGI.js";
@@ -180,7 +180,16 @@ var NamespaceStorageRouter = class {
180
180
  return cached;
181
181
  }
182
182
  }
183
- const sm = new StorageManager(root, this.config.entitySchemas);
183
+ const sm = new StorageManager(
184
+ root,
185
+ this.config.entitySchemas,
186
+ this.config.hotMemoriesCacheEnabled
187
+ );
188
+ StorageManager.setHotMemoriesCacheDefault(
189
+ root,
190
+ this.config.hotMemoriesCacheEnabled,
191
+ this.config.hotMemoriesCacheTtlMs
192
+ );
184
193
  sm.citationTemplate = this.config.inlineSourceAttributionFormat;
185
194
  this.bindCatalogWriteHook(sm, ns);
186
195
  this.applyTombstonesConfig(sm, ns);
@@ -339,4 +348,4 @@ export {
339
348
  resolveNamespaceStorageRoot,
340
349
  NamespaceStorageRouter
341
350
  };
342
- //# sourceMappingURL=chunk-74MJH7I3.js.map
351
+ //# sourceMappingURL=chunk-U4KHQTJ6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespaces/storage.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"../capabilities.js\";\nimport path from \"node:path\";\nimport { access, lstat, readdir } from \"node:fs/promises\";\nimport { isSafeRouteNamespace } from \"../routing/engine.js\";\nimport { StorageManager } from \"../storage.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\nimport { namespaceIdentityToken, normalizeNamespaceIdentity } from \"./identity.js\";\nimport type { NamespaceCatalog } from \"./catalog.js\";\nimport { MutationSerializer } from \"../utils/serialize-mutations.js\";\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function hasStoredEntries(p: string): Promise<boolean> {\n try {\n const entry = await lstat(p);\n if (entry.isSymbolicLink()) return true;\n if (!entry.isDirectory()) return true;\n const children = await readdir(p, { withFileTypes: true });\n for (const child of children) {\n const childPath = path.join(p, child.name);\n if (child.isSymbolicLink() || child.isFile()) return true;\n if (child.isDirectory() && (await hasStoredEntries(childPath))) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n// Build a per-namespace directory under `<memoryDir>/namespaces` and assert the\n// resolved path stays inside that base. Namespace identifiers can originate from\n// operator config (config.defaultNamespace) and request-derived routing, so this\n// containment check prevents directory traversal (CodeQL js/path-injection).\n// For safe segments this returns exactly `path.join(base, segment)`, so there is\n// no behavioral change for valid namespaces.\nfunction resolveNamespaceDir(memoryDir: string, segment: string): string {\n // Mirror isSafeRouteNamespace's separator/parent-ref rejection (without its\n // 64-char cap, so identity tokens still pass). Rejecting separators and \"..\"\n // up front keeps the value a single contained child of <memoryDir>/namespaces.\n if (\n segment.length === 0 ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\") ||\n segment.includes(\"..\") ||\n path.isAbsolute(segment)\n ) {\n throw new Error(`unsafe namespace path segment: ${segment}`);\n }\n return path.join(memoryDir, \"namespaces\", segment);\n}\n\nconst LEGACY_NAMESPACE_CONTENT_CHILDREN = [\n ...ALL_CATEGORY_DIRS,\n \"entities\",\n \"artifacts\",\n \"identity\",\n \"config\",\n \"summaries\",\n \"profile.md\",\n] as const;\n\nconst LEGACY_NAMESPACE_RUNTIME_CHILDREN = [\"state\"] as const;\n\nasync function hasAnyLegacyData(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await hasStoredEntries(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\nasync function hasAnyNamespaceStorageMarker(\n rootDir: string,\n options: { includeRuntimeState?: boolean } = {},\n): Promise<boolean> {\n const children = options.includeRuntimeState === true\n ? [...LEGACY_NAMESPACE_CONTENT_CHILDREN, ...LEGACY_NAMESPACE_RUNTIME_CHILDREN]\n : LEGACY_NAMESPACE_CONTENT_CHILDREN;\n for (const child of children) {\n if (await exists(path.join(rootDir, child))) return true;\n }\n return false;\n}\n\n/**\n * Storage routing for namespaces.\n *\n * Compatibility note:\n * - When namespaces are enabled, existing raw namespace roots are preserved.\n * New namespace roots use tokenized names under `memoryDir/namespaces/<token>`.\n * - The default namespace continues to use the legacy `memoryDir` root unless the caller\n * has created `memoryDir/namespaces/<defaultNamespace>` (in which case we use that).\n *\n * This avoids surprising \"lost memories\" when an install flips namespaces on without\n * migrating existing data.\n */\n/**\n * Optional hooks for the storage router. `onResolve` fires whenever a namespace's\n * storage is resolved/created, so a downstream consumer (e.g. the namespace\n * catalog, issue #1499) can register the namespace. The hook MUST NOT throw into\n * the router; the router invokes it defensively and a hook failure never affects\n * storage resolution.\n *\n * The hook MAY return (or resolve to) a boolean indicating whether the\n * registration actually PERSISTED (round 6, codex P2 — NEFoX). When it resolves\n * to `false` (a dropped/no-op registration), the router does NOT mark the\n * (namespace, storageDir) pair as notified, so the next resolve RETRIES it\n * instead of suppressing it forever. A `void`/`undefined` result is treated as\n * success (legacy hooks).\n */\nexport interface NamespaceStorageRouterHooks {\n onResolve?: (\n namespace: string,\n storageDir: string,\n ) => void | boolean | Promise<void | boolean>;\n}\n\n/**\n * Resolve the runtime storage root for the configured DEFAULT namespace.\n *\n * Shared between the live router (`NamespaceStorageRouter.defaultNamespaceRoot`)\n * and the rebuildable catalog (`NamespaceCatalog.rebuildFromDisk`) so the two\n * can never diverge (CLAUDE.md rule #22/#42 — read & write paths resolve through\n * the same logic). The contract is: while legacy memory data still lives\n * directly under `memoryDir`, the default root stays `memoryDir`; only once the\n * legacy root is empty and a `namespaces/<default|token>` dir holds data does\n * the default migrate into that tokenized/legacy-named dir.\n */\nexport async function resolveDefaultNamespaceRoot(config: PluginConfig): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) {\n return config.memoryDir;\n }\n\n // Build the legacy default root from the NORMALIZED (trimmed) name so a\n // whitespace-padded `defaultNamespace` still finds the live `namespaces/default`\n // root (NIabe). `storageFor()` classifies the trimmed value as the default, and\n // the on-disk legacy dir is created under the trimmed name; using the raw spaced\n // name here would look for `namespaces/<spaced>` and miss the real root, falling\n // back to memoryDir/tokenized. `namespaceIdentityToken` already normalizes\n // internally, so the tokenized path is unaffected.\n const defaultIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);\n const tokenizedNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityToken(config.defaultNamespace),\n );\n const tokenizedHasData =\n (await exists(tokenizedNsDir)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));\n const nsDir = tokenizedHasData\n ? tokenizedNsDir\n : (await exists(legacyNsDir))\n ? legacyNsDir\n : tokenizedNsDir;\n return (await exists(nsDir)) && !(await hasAnyLegacyData(config.memoryDir))\n ? nsDir\n : config.memoryDir;\n}\n\n/**\n * Resolve the runtime storage root for ANY namespace exactly as the live router\n * would (`NamespaceStorageRouter.namespaceRoot`). Shared so the rebuildable\n * catalog records the SAME on-disk root the router routes to — a recall/read\n * touch must not guess `namespaces/<token>` when the router actually serves a\n * legacy raw-name dir or a migrated default root (CLAUDE.md rule #22/#42; round\n * 4, cursor Medium). The default namespace delegates to `resolveDefaultNamespaceRoot`;\n * every other namespace prefers the tokenized root when it has a storage marker,\n * else a legacy raw-name dir when present, else the tokenized root.\n */\nexport async function resolveNamespaceStorageRoot(\n config: PluginConfig,\n namespace: string,\n): Promise<string> {\n if (!resolveNamespaceCapabilities(config).namespaces) return config.memoryDir;\n // Compare on NORMALIZED identity so a whitespace-padded configured default name\n // still routes to the default root rather than a tokenized non-default dir\n // (NH-FH). The catalog keys records by the same normalized identity.\n if (normalizeNamespaceIdentity(namespace) === normalizeNamespaceIdentity(config.defaultNamespace)) {\n return resolveDefaultNamespaceRoot(config);\n }\n const legacyRoot = resolveNamespaceDir(config.memoryDir, namespace);\n const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(namespace));\n if (\n (await exists(tokenizedRoot)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedRoot, { includeRuntimeState: true }))\n ) {\n return tokenizedRoot;\n }\n return (await exists(legacyRoot)) ? legacyRoot : tokenizedRoot;\n}\n\nexport class NamespaceStorageRouter {\n private readonly cache = new Map<string, StorageManager>();\n private defaultNsRootResolved: string | null = null;\n // Dedup the resolve hook (round 6, cursor Medium — NCNL2). Recall/extraction\n // call `storageFor` repeatedly; firing `onResolve` (→ catalog loadCompacted +\n // append) on every cache hit grows `namespaces.jsonl` without bound between\n // rebuilds. We fire the hook only when the (namespace, storageDir) pair is new\n // or its dir changed, so a steady-state cache hit is a no-op for the catalog.\n private readonly notifiedResolved = new Map<string, string>();\n // Instance-scoped serializer for the resolve hook (issue #1524 adoption).\n // Replaces the bespoke `inFlightResolved` marker-then-clear pattern: the\n // serializer's per-key chain strictly orders concurrent notifications for the\n // SAME namespace, and the task re-checks `notifiedResolved` once it runs, so a\n // burst of cache hits before the first hook settles collapses to a single\n // hook invocation (the once-per-namespace intent). Recovery is preserved —\n // one rejected hook never poisons subsequent notifications for that key.\n private readonly resolveSerializer = new MutationSerializer();\n // (namespace, storageDir) pairs whose resolve hook is currently pending. Set SYNCHRONOUSLY in\n // notifyResolved (before queueing) so a burst of concurrent storageFor()\n // cache hits collapses onto the one in-flight hook instead of each enqueuing\n // its own task. Cleared when the queued hook settles. Without this, a dropped\n // hook (returns false on a rebuild-lock timeout) leaves notifiedResolved\n // unset, so every queued sibling task would re-run the hook — N serial lock\n // waits (cursor Medium 06f58a7c, codex P2).\n private readonly inFlightResolveHooks = new Set<string>();\n // Tracks every in-flight resolve-hook promise so callers can deterministically\n // await the fire-and-forget registrations that `storageFor()` kicks off (see\n // `whenResolveHooksSettled`). Entries are removed as each hook settles, so the\n // set holds at most one promise per concurrently-resolving namespace.\n private readonly pendingResolveHooks = new Set<Promise<unknown>>();\n // Pending post-write catalog touch promises (#1522). Like pendingResolveHooks,\n // lets tests await fire-and-forget write touches deterministically.\n private readonly pendingWriteTouches = new Set<Promise<unknown>>();\n\n // Normalized (trimmed) default namespace identity (NH-FH). `storageFor`\n // normalizes its input, so default-namespace branches must compare against the\n // normalized config default too — otherwise a whitespace-padded configured\n // default name routes the default namespace to a tokenized non-default root.\n private readonly defaultNamespaceIdentity: string;\n\n constructor(\n private readonly config: PluginConfig,\n private readonly hooks: NamespaceStorageRouterHooks = {},\n /** Catalog reference for post-write/read touches (issue #1522 chokepoint). */\n private readonly catalog?: NamespaceCatalog,\n ) {\n this.defaultNamespaceIdentity = normalizeNamespaceIdentity(config.defaultNamespace);\n }\n\n private async defaultNamespaceRoot(): Promise<string> {\n this.defaultNsRootResolved = await resolveDefaultNamespaceRoot(this.config);\n return this.defaultNsRootResolved;\n }\n\n private async namespaceRoot(namespace: string): Promise<string> {\n // NOTE: only used after defaultNamespaceRoot() resolution.\n if (!resolveNamespaceCapabilities(this.config).namespaces) return this.config.memoryDir;\n if (normalizeNamespaceIdentity(namespace) === this.defaultNamespaceIdentity) {\n return this.defaultNsRootResolved ?? this.config.memoryDir;\n }\n return resolveNamespaceStorageRoot(this.config, namespace);\n }\n\n async storageFor(namespace: string): Promise<StorageManager> {\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n if (ns !== this.defaultNamespaceIdentity && !isSafeRouteNamespace(ns)) {\n throw new Error(`unsafe namespace: ${ns}`);\n }\n // Even when the default namespace is exempt from the check above, every\n // on-disk path is built through resolveNamespaceDir(), which rejects\n // traversal segments — so an unsafe configured default still cannot escape\n // <memoryDir>/namespaces (CodeQL js/path-injection).\n\n let root: string;\n if (ns === this.defaultNamespaceIdentity) {\n root = await this.defaultNamespaceRoot();\n const cached = this.cache.get(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n } else {\n const cached = this.cache.get(ns);\n root = await this.namespaceRoot(ns);\n if (cached && cached.dir === root) {\n this.notifyResolved(ns, root);\n return cached;\n }\n }\n\n // Pass the hot-memories cache gate explicitly (issue #1902, Codex P2): a\n // per-namespace child root is never registered in the per-dir default map,\n // so without this it would fall back to the process-wide default and ignore\n // THIS daemon's hotMemoriesCacheEnabled config. Threading it from config\n // keeps every namespace storage aligned with its owning orchestrator.\n const sm = new StorageManager(\n root,\n this.config.entitySchemas,\n this.config.hotMemoriesCacheEnabled,\n );\n // Register this child root's gate AND TTL in the per-dir maps (issue #1902,\n // Codex P2). The constructor override above fixes the child's own gate, but\n // its TTL is resolved via the per-dir map (hotCacheTtlMs); an unregistered\n // child root would fall back to the last process-wide TTL and could inherit\n // another daemon's value. Registering keyed by root keeps both per-dir.\n StorageManager.setHotMemoriesCacheDefault(\n root,\n this.config.hotMemoriesCacheEnabled,\n this.config.hotMemoriesCacheTtlMs,\n );\n // Propagate the inline-attribution template so that router-created storages\n // (used by extraction and shared-promotion paths) strip citations consistently,\n // matching the behaviour of the primary this.storage instance in the orchestrator.\n sm.citationTemplate = this.config.inlineSourceAttributionFormat;\n // #1522: install the post-write catalog touch at the chokepoint — every\n // successful write on this StorageManager records the namespace touch.\n this.bindCatalogWriteHook(sm, ns);\n // #1579: apply the tombstone non-resurrection config so every namespace\n // storage enforces the invariant at its own writeMemory chokepoint.\n this.applyTombstonesConfig(sm, ns);\n this.cache.set(ns, sm);\n this.notifyResolved(ns, root);\n return sm;\n }\n\n /**\n * Fire the resolve hook defensively. A hook failure (e.g. a catalog write\n * error) MUST NOT crash storage resolution — see CLAUDE.md gotcha #13.\n *\n * Issue #1524 adoption: hook invocations for the SAME namespace are now\n * strictly ordered through the shared `MutationSerializer` rather than the\n * bespoke `inFlightResolved` marker-then-clear pattern. The serializer\n * guarantees one in-flight hook per namespace; a concurrent burst of\n * `storageFor()` cache hits collapses to a single hook invocation because\n * each queued task re-checks `notifiedResolved` before invoking the hook. A\n * dropped (`false`) or rejected hook leaves `notifiedResolved` unset so the\n * next `storageFor()` retries — the serializer recovers from the rejection,\n * so a failed hook never poisons later notifications.\n */\n private notifyResolved(namespace: string, storageDir: string): void {\n const hook = this.hooks.onResolve;\n if (!hook) return;\n // Permanent dedup: skip once we've SUCCESSFULLY notified this exact\n // (namespace, storageDir). A changed dir (rare: migration/realignment)\n // still re-fires once. The mark is set ONLY AFTER the hook succeeds, so a\n // dropped registration (e.g. rebuild-lock timeout) is RETRIED on the next\n // cache hit instead of being suppressed forever (round 6, cursor Medium —\n // ND3EJ).\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n // In-flight dedup (cursor Medium 06f58a7c, codex P2): if a hook for THIS\n // namespace is already pending, collapse this call onto it instead of\n // enqueueing another task. The serializer strictly orders queued tasks, but\n // ordering alone is not enough — when the first hook returns `false`\n // (dropped touch, e.g. rebuild-lock timeout), `notifiedResolved` stays\n // unset, so each queued sibling task would pass its re-check and re-run the\n // hook. With the real catalog hook each retry can spend the full lock wait,\n // so N cache hits during a rebuild leave N serial background lock attempts.\n // Collapsing here means at most ONE hook runs per in-flight registration;\n // its result (set `notifiedResolved` on success, leave unset on drop)\n // decides whether a LATER `storageFor()` retries — collapsing loses\n // nothing because the drop is already retried on the next cache hit.\n // Keyed by the composite (namespace, storageDir) so a CHANGED dir\n // (migration/realignment) for the same namespace still gets its own hook —\n // it is NOT collapsed onto the old dir's pending registration (cursor\n // Medium, codex P2).\n const inFlightKey = namespace + \"\\u0000\" + storageDir;\n if (this.inFlightResolveHooks.has(inFlightKey)) return;\n this.inFlightResolveHooks.add(inFlightKey);\n // Queue through the serializer. Concurrent calls for the same namespace\n // strictly order here; the 2nd call's task runs only after the 1st's hook\n // settles, by which point `notifiedResolved` is either set (no-op) or still\n // unset (retry). The returned promise is tracked for\n // `whenResolveHooksSettled()`. Rejections from the task body are caught so\n // they never reach the caller (best-effort hook contract); the serializer's\n // recovered tail still lets subsequent notifications run.\n const task = async (): Promise<void> => {\n // Re-check after queueing: a prior task in this same chain may have just\n // marked the pair as notified.\n if (this.notifiedResolved.get(namespace) === storageDir) return;\n try {\n // Hook may be sync or async; Promise.resolve normalizes both. A result\n // of `false` means the registration was dropped/no-op (e.g. rebuild-lock\n // timeout) — leave notifiedResolved UNSET so the next storageFor retries\n // (round 6, codex P2 — NEFoX). `void`/`undefined` is success for legacy\n // hooks. A rejection leaves notifiedResolved unset for the same reason.\n const persisted = await Promise.resolve(hook(namespace, storageDir));\n if (persisted !== false) {\n this.notifiedResolved.set(namespace, storageDir);\n }\n } catch {\n // Best-effort: a hook failure MUST NOT crash storage resolution. Leave\n // notifiedResolved unset so a later storageFor retries the registration.\n }\n };\n const queued = this.resolveSerializer.serialize(namespace, task);\n this.pendingResolveHooks.add(queued);\n // Clear the in-flight marker when the hook settles so a subsequent\n // storageFor() can retry after a drop, or short-circuit via notifiedResolved\n // after a success.\n const cleanup = (): void => {\n this.inFlightResolveHooks.delete(inFlightKey);\n this.pendingResolveHooks.delete(queued);\n };\n void queued.then(cleanup, cleanup);\n }\n\n /**\n * Install the post-write catalog touch hook on an externally-constructed\n * StorageManager (issue #1522). Used by the orchestrator for the legacy\n * default-namespace storage (`this.storage`) that bypasses the router.\n */\n bindCatalogWriteHook(sm: StorageManager, namespace: string): void {\n sm.onCatalogWrite = () => this.touchCatalogWrite(namespace, sm.dir);\n }\n\n /**\n * Install the tombstone config on an externally-constructed StorageManager\n * (issue #1579). Mirrors `bindCatalogWriteHook` — used for the legacy\n * default-namespace storage that bypasses the router. Router-created\n * storages are wired inline in `storageFor()` via `applyTombstonesConfig`.\n */\n bindTombstonesConfig(\n sm: StorageManager,\n namespace: string,\n config: { enabled: boolean; semanticMatch: boolean; semanticThreshold: number },\n ): void {\n this.tombstonesGlobalConfig = { ...config };\n sm.setTombstonesConfig({ ...config, namespace });\n }\n\n private tombstonesGlobalConfig: {\n enabled: boolean;\n semanticMatch: boolean;\n semanticThreshold: number;\n } = { enabled: false, semanticMatch: false, semanticThreshold: 0.9 };\n\n /**\n * Apply the tombstone config to a router-created StorageManager. Called\n * inline in `storageFor()` so every namespace storage enforces the\n * non-resurrection invariant, namespace-scoped (rule 42).\n */\n private applyTombstonesConfig(sm: StorageManager, namespace: string): void {\n sm.setTombstonesConfig({ ...this.tombstonesGlobalConfig, namespace });\n }\n\n /**\n * Post-write catalog touch (issue #1522 chokepoint). Called by every\n * StorageManager's post-write hook AFTER a successful write. Best-effort\n * and failure-tolerant — a catalog error MUST NOT affect the primary write\n * (gotcha #13, rule #40). Fire-and-forget by design.\n */\n private touchCatalogWrite(namespace: string, storageDir: string): void {\n if (!this.catalog) return;\n const touch = this.catalog\n .markWrite(namespace, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Record a namespace read in the catalog (issue #1522 chokepoint move).\n * Best-effort and failure-tolerant. Used by recall paths so the read touch\n * lives in the storage layer, not at the caller.\n */\n recordRead(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n void this.catalog\n .markRead(ns, { discoveredBy: \"read\", storageDir })\n .catch(() => undefined);\n }\n /**\n * Record a namespace write touch in the catalog (issue #1522). Best-effort\n * and failure-tolerant. Used by consolidation/cleanup passes that may mutate\n * the store via delete-only paths (e.g. entity-file merges, TTL cleanup) so\n * the namespace's lastWriteAt stays fresh even when no explicit write went\n * through the storage chokepoint. This is NOT a substitute for the chokepoint\n * — it's a belt-and-suspenders for paths the chokepoint doesn't cover.\n */\n recordWrite(namespace: string, storageDir?: string): void {\n if (!this.catalog) return;\n const ns = normalizeNamespaceIdentity(namespace || this.config.defaultNamespace);\n const touch = this.catalog\n .markWrite(ns, { discoveredBy: \"write\", storageDir })\n .catch(() => undefined);\n this.pendingWriteTouches.add(touch);\n void touch.then(\n () => { this.pendingWriteTouches.delete(touch); },\n () => { this.pendingWriteTouches.delete(touch); },\n );\n }\n\n /**\n * Resolve once every in-flight post-write catalog touch has settled (#1522).\n * Mirrors `whenResolveHooksSettled()`: the StorageManager's post-write hook\n * fires the catalog touch fire-and-forget, so tests asserting lastWriteAt\n * moved should await this instead of racing a timer.\n */\n async whenWriteTouchesSettled(): Promise<void> {\n while (this.pendingWriteTouches.size > 0) {\n await Promise.allSettled([...this.pendingWriteTouches]);\n }\n }\n\n /**\n * Resolve once every in-flight `onResolve` registration has settled.\n *\n * `storageFor()` fires the resolve hook fire-and-forget, so its catalog side\n * effect (e.g. `registerResolved(...)`) is not observable the moment\n * `storageFor()` returns. Callers that must act on that side effect — notably\n * tests asserting the catalog was updated — should await this instead of\n * racing a timer. Resolves immediately when no hook is registered or nothing\n * is in flight. The loop re-checks because a settling hook could, in\n * principle, trigger a follow-on resolution.\n */\n async whenResolveHooksSettled(): Promise<void> {\n while (this.pendingResolveHooks.size > 0) {\n await Promise.allSettled([...this.pendingResolveHooks]);\n }\n }\n}\n"],"mapp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3
3
  normalizeEntityName
4
- } from "./chunk-KTOH7EJE.js";
4
+ } from "./chunk-KXLRMM35.js";
5
5
  import {
6
6
  serializeMutations
7
7
  } from "./chunk-LTJAMRGI.js";
@@ -956,4 +956,4 @@ export {
956
956
  resolveBriefingSaveDir,
957
957
  briefingFilename
958
958
  };
959
- //# sourceMappingURL=chunk-CRFTLUWT.js.map
959
+ //# sourceMappingURL=chunk-UTDA43TB.js.map
@@ -2,14 +2,14 @@ import {
2
2
  getGatewayRuntimeAuthForModel,
3
3
  resolveProviderApiKey
4
4
  } from "./chunk-K2ZLHESQ.js";
5
+ import {
6
+ loadModelsJsonProviders
7
+ } from "./chunk-VFSP73LP.js";
5
8
  import {
6
9
  buildChatCompletionTemperature,
7
10
  buildChatCompletionTokenLimit,
8
11
  shouldAssumeOpenAiChatCompletions
9
12
  } from "./chunk-L2EXJQJP.js";
10
- import {
11
- loadModelsJsonProviders
12
- } from "./chunk-VFSP73LP.js";
13
13
  import {
14
14
  extractJsonCandidates
15
15
  } from "./chunk-RGMVMVMF.js";
@@ -708,4 +708,4 @@ export {
708
708
  fallbackLlmRuntimeContextFromConfig,
709
709
  FallbackLlmClient
710
710
  };
711
- //# sourceMappingURL=chunk-GKCCHHZK.js.map
711
+ //# sourceMappingURL=chunk-UXKMMNJD.js.map
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-D7FOKIY5.js";
6
6
  import {
7
7
  EngramAccessInputError
8
- } from "./chunk-CNWC274T.js";
8
+ } from "./chunk-3OQ4IZJN.js";
9
9
  import {
10
10
  expandTildePath
11
11
  } from "./chunk-EYIEWJNI.js";
@@ -274,4 +274,4 @@ export {
274
274
  listRegisteredOperations,
275
275
  __resetRegistryForTest
276
276
  };
277
- //# sourceMappingURL=chunk-57INMZ6F.js.map
277
+ //# sourceMappingURL=chunk-UZRIKUFS.js.map
@@ -1,3 +1,9 @@
1
+ import {
2
+ LanceDbBackend
3
+ } from "./chunk-N3JDIRBW.js";
4
+ import {
5
+ MeilisearchBackend
6
+ } from "./chunk-UTRJFDP2.js";
1
7
  import {
2
8
  NoopSearchBackend
3
9
  } from "./chunk-CYEPCZN5.js";
@@ -10,12 +16,6 @@ import {
10
16
  import {
11
17
  EmbedHelper
12
18
  } from "./chunk-FNMFJWBY.js";
13
- import {
14
- LanceDbBackend
15
- } from "./chunk-N3JDIRBW.js";
16
- import {
17
- MeilisearchBackend
18
- } from "./chunk-UTRJFDP2.js";
19
19
  import {
20
20
  createConversationIndexBackend
21
21
  } from "./chunk-JI5AVXYO.js";
@@ -24,7 +24,7 @@ import {
24
24
  } from "./chunk-TN7THW5U.js";
25
25
  import {
26
26
  QmdClient
27
- } from "./chunk-3F4N4WDH.js";
27
+ } from "./chunk-AHLPZ2SF.js";
28
28
  import {
29
29
  resolveIndexingCapabilities,
30
30
  resolvePipelineProcessingCapabilities,
@@ -175,4 +175,4 @@ export {
175
175
  createConversationSearchBackend,
176
176
  createConversationIndexRuntime
177
177
  };
178
- //# sourceMappingURL=chunk-2FSHROYK.js.map
178
+ //# sourceMappingURL=chunk-V53GJUSL.js.map
@@ -4,7 +4,7 @@ import {
4
4
  } from "./chunk-AAD2ZS6P.js";
5
5
  import {
6
6
  gatewayTaskChainOptions
7
- } from "./chunk-GKCCHHZK.js";
7
+ } from "./chunk-UXKMMNJD.js";
8
8
  import {
9
9
  extractJsonCandidates
10
10
  } from "./chunk-RGMVMVMF.js";
@@ -685,4 +685,4 @@ export {
685
685
  serializeFaithfulnessFields,
686
686
  parseFaithfulnessField
687
687
  };
688
- //# sourceMappingURL=chunk-LKT755LP.js.map
688
+ //# sourceMappingURL=chunk-VA4WSW54.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  NamespaceStorageRouter
3
- } from "./chunk-74MJH7I3.js";
3
+ } from "./chunk-U4KHQTJ6.js";
4
4
  import {
5
5
  namespaceCollectionName
6
- } from "./chunk-T7VNN3ZM.js";
6
+ } from "./chunk-XVLEGMJI.js";
7
7
  import {
8
8
  namespaceIdentityFromToken,
9
9
  namespaceIdentityToken
@@ -207,4 +207,4 @@ export {
207
207
  verifyNamespaces,
208
208
  runNamespaceMigration
209
209
  };
210
- //# sourceMappingURL=chunk-ZHKD4EZM.js.map
210
+ //# sourceMappingURL=chunk-VCEH5UYS.js.map
@@ -18,7 +18,7 @@ import {
18
18
  } from "./chunk-T4WDJPEZ.js";
19
19
  import {
20
20
  getOperation
21
- } from "./chunk-57INMZ6F.js";
21
+ } from "./chunk-UZRIKUFS.js";
22
22
  import {
23
23
  assertOperationAllowed,
24
24
  capabilityAllowsOp,
@@ -27,7 +27,7 @@ import {
27
27
  } from "./chunk-D7FOKIY5.js";
28
28
  import {
29
29
  EngramAccessInputError
30
- } from "./chunk-CNWC274T.js";
30
+ } from "./chunk-3OQ4IZJN.js";
31
31
  import {
32
32
  readEnvVar
33
33
  } from "./chunk-JUC24CTX.js";
@@ -3789,4 +3789,4 @@ export {
3789
3789
  MCP_SUPPORTED_PROTOCOL_VERSIONS,
3790
3790
  EngramMcpServer
3791
3791
  };
3792
- //# sourceMappingURL=chunk-CHVU4RE5.js.map
3792
+ //# sourceMappingURL=chunk-VDLMAJXS.js.map