@remnic/core 10.0.168 → 10.0.169

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 (376) hide show
  1. package/dist/access-admin-ops-surface.js +138 -137
  2. package/dist/access-cli.js +138 -137
  3. package/dist/access-cli.js.map +1 -1
  4. package/dist/access-coding-context-resolution.js +11 -11
  5. package/dist/access-extraction-force-flush-preempt.js +138 -137
  6. package/dist/access-extraction-force-flush.js +138 -137
  7. package/dist/access-http-briefing.js +138 -137
  8. package/dist/access-http-query.js +138 -137
  9. package/dist/access-http.js +138 -137
  10. package/dist/access-identity-continuity-surface.js +138 -137
  11. package/dist/access-lcm-surface.js +138 -137
  12. package/dist/access-mcp.js +138 -137
  13. package/dist/access-observe-write-category.js +11 -11
  14. package/dist/access-observe-write-surface.js +138 -137
  15. package/dist/access-offline-manifest.js +9 -9
  16. package/dist/access-operations-batch.js +138 -137
  17. package/dist/access-operations.js +138 -137
  18. package/dist/access-recall-concurrency.js +138 -137
  19. package/dist/access-recall-excerpt-attribution.d.ts +19 -0
  20. package/dist/access-recall-excerpt-attribution.d.ts.map +1 -0
  21. package/dist/access-recall-excerpt-attribution.js +8 -0
  22. package/dist/access-recall-response.js +138 -137
  23. package/dist/access-recall-surface.d.ts.map +1 -1
  24. package/dist/access-recall-surface.js +138 -137
  25. package/dist/access-schema.js +10 -10
  26. package/dist/access-service.js +138 -137
  27. package/dist/active-recall.js +24 -24
  28. package/dist/adapters/index.js +4 -4
  29. package/dist/adapters/registry.js +2 -2
  30. package/dist/{auto-sync-L3M4RKJD.js → auto-sync-ACP5U5A3.js} +3 -3
  31. package/dist/binary-lifecycle/scanner.d.ts +2 -4
  32. package/dist/binary-lifecycle/scanner.d.ts.map +1 -1
  33. package/dist/briefing.js +13 -13
  34. package/dist/buffer-add-turns-bounded.d.ts +11 -1
  35. package/dist/buffer-add-turns-bounded.d.ts.map +1 -1
  36. package/dist/buffer-add-turns-bounded.js +3 -3
  37. package/dist/buffer-session-cap.d.ts +2 -2
  38. package/dist/buffer-session-cap.d.ts.map +1 -1
  39. package/dist/buffer-session-cap.js +1 -1
  40. package/dist/buffer.d.ts +3 -2
  41. package/dist/buffer.d.ts.map +1 -1
  42. package/dist/buffer.js +12 -12
  43. package/dist/calibration.d.ts +19 -2
  44. package/dist/calibration.d.ts.map +1 -1
  45. package/dist/calibration.js +28 -5
  46. package/dist/calibration.js.map +1 -1
  47. package/dist/{capsule-crypto-GWVG7LGC.js → capsule-crypto-7FJQINUR.js} +2 -2
  48. package/dist/{capsule-merge-VHBRF65A.js → capsule-merge-BADOICNP.js} +2 -2
  49. package/dist/causal-behavior.js +2 -2
  50. package/dist/causal-chain.js +2 -2
  51. package/dist/causal-consolidation.js +17 -17
  52. package/dist/causal-retrieval.js +2 -2
  53. package/dist/causal-trajectory-graph.js +3 -3
  54. package/dist/causal-trajectory.js +1 -1
  55. package/dist/{chunk-OWHERGF2.js → chunk-2NLLXCJG.js} +2 -2
  56. package/dist/{chunk-D6BOOYNJ.js → chunk-32OTLNAU.js} +271 -237
  57. package/dist/chunk-32OTLNAU.js.map +1 -0
  58. package/dist/{chunk-L7SEYUHS.js → chunk-3I3NXB6X.js} +3 -3
  59. package/dist/{chunk-4NBUHYUV.js → chunk-3LADDLAF.js} +5 -5
  60. package/dist/{chunk-2DL3OFLD.js → chunk-45GEJRIG.js} +2 -2
  61. package/dist/{chunk-5BE3FLKL.js → chunk-5KDDAQ6K.js} +8 -8
  62. package/dist/{chunk-BPCR5DZP.js → chunk-62YZOQFR.js} +5 -5
  63. package/dist/chunk-62YZOQFR.js.map +1 -0
  64. package/dist/{chunk-HLWXCDUQ.js → chunk-63A2BU2B.js} +5 -5
  65. package/dist/{chunk-MOUSHJAR.js → chunk-7FPI5MFB.js} +5 -5
  66. package/dist/{chunk-ZX546Y3Y.js → chunk-7OYDFIL4.js} +2 -2
  67. package/dist/{chunk-CKZWLAHN.js → chunk-ACPFBVUD.js} +2 -2
  68. package/dist/{chunk-BKTCVXMK.js → chunk-AHOYKJ5X.js} +3 -3
  69. package/dist/{chunk-WEHSQBFR.js → chunk-AIF6V2OX.js} +9 -4
  70. package/dist/chunk-AIF6V2OX.js.map +1 -0
  71. package/dist/{chunk-FGT7CUYZ.js → chunk-ALTLOHO7.js} +2 -2
  72. package/dist/{chunk-FMFCQRDM.js → chunk-AUFPPBC3.js} +3 -3
  73. package/dist/{chunk-OAQRZ4SV.js → chunk-B5KTTWC7.js} +2 -2
  74. package/dist/{chunk-73TPOGS4.js → chunk-BFBS7OFQ.js} +9 -9
  75. package/dist/{chunk-QFTK6EDM.js → chunk-BFZFNXOC.js} +13 -13
  76. package/dist/{chunk-ZQUOUPP3.js → chunk-BHRPZBAH.js} +4 -4
  77. package/dist/{chunk-4L25GAYL.js → chunk-CX24SVLK.js} +2 -2
  78. package/dist/{chunk-YY57TRKN.js → chunk-D5ZLTLHF.js} +2 -2
  79. package/dist/{chunk-WEFFO2MJ.js → chunk-D6YCETHG.js} +2 -2
  80. package/dist/{chunk-ZDZJNXL6.js → chunk-DK2VBJ6Q.js} +4 -4
  81. package/dist/{chunk-VRHY7Y5A.js → chunk-DPL5VO5V.js} +3 -3
  82. package/dist/{chunk-LVGTH6IQ.js → chunk-E7ATID4Z.js} +11 -11
  83. package/dist/{chunk-CKELO7Q6.js → chunk-FHWX2REL.js} +2 -2
  84. package/dist/{chunk-CUPILBIP.js → chunk-FMIM36I4.js} +2 -2
  85. package/dist/{chunk-OWM2VWNX.js → chunk-FSXYBIEZ.js} +25 -24
  86. package/dist/chunk-FSXYBIEZ.js.map +1 -0
  87. package/dist/{chunk-A5UOREWD.js → chunk-FWTGO4NE.js} +2 -2
  88. package/dist/{chunk-3SL52JKD.js → chunk-FZVROZKC.js} +5 -5
  89. package/dist/{chunk-U3BCW7GX.js → chunk-G3RLCVJC.js} +3 -3
  90. package/dist/{chunk-UYIBNDQE.js → chunk-GF5NN3LE.js} +2 -2
  91. package/dist/{chunk-7OCKK5M5.js → chunk-GWY5ZFHP.js} +6 -6
  92. package/dist/{chunk-AL3TCNSJ.js → chunk-H3MLOQ7F.js} +24 -53
  93. package/dist/chunk-H3MLOQ7F.js.map +1 -0
  94. package/dist/{chunk-TNRGWJYT.js → chunk-H4IU24V5.js} +2 -2
  95. package/dist/{chunk-T4BT4FQN.js → chunk-HH6PXQ2B.js} +3 -3
  96. package/dist/{chunk-FEUWI5QH.js → chunk-HHPY5SSE.js} +2 -2
  97. package/dist/{chunk-OM5ESBES.js → chunk-HQPFACXO.js} +2 -2
  98. package/dist/{chunk-QLQUAVVP.js → chunk-I7WPLMUX.js} +16 -16
  99. package/dist/chunk-I7WPLMUX.js.map +1 -0
  100. package/dist/{chunk-IMULTENA.js → chunk-ID65XTF3.js} +2 -2
  101. package/dist/{chunk-WWQMZBDI.js → chunk-IJVU4ILJ.js} +4 -4
  102. package/dist/{chunk-GBSXTTLP.js → chunk-ITGAGNX5.js} +2 -2
  103. package/dist/chunk-IUGOGDCP.js +39 -0
  104. package/dist/chunk-IUGOGDCP.js.map +1 -0
  105. package/dist/{chunk-3PNJZTDV.js → chunk-JGGNUEVD.js} +2 -2
  106. package/dist/{chunk-YYXYZM2I.js → chunk-JN7OSQJR.js} +2 -2
  107. package/dist/{chunk-4D2EY4WM.js → chunk-K2DTHNDY.js} +6 -6
  108. package/dist/{chunk-TH6OYP6I.js → chunk-K36RMINQ.js} +3 -3
  109. package/dist/{chunk-OZKVVUJB.js → chunk-KIM5VNZN.js} +2 -2
  110. package/dist/{chunk-BFPQJNFZ.js → chunk-LXSDEPEK.js} +60 -11
  111. package/dist/{chunk-BFPQJNFZ.js.map → chunk-LXSDEPEK.js.map} +1 -1
  112. package/dist/{chunk-ZWDDY4WF.js → chunk-M7CFCRWJ.js} +2 -2
  113. package/dist/{chunk-QPFM6DHY.js → chunk-MTJFK42O.js} +2 -2
  114. package/dist/{chunk-RO5EGRAI.js → chunk-N3FRR6II.js} +2 -2
  115. package/dist/{chunk-UMEUU66X.js → chunk-O3OEVYUR.js} +2 -2
  116. package/dist/{chunk-J74YOBB3.js → chunk-PFR6ZKQI.js} +8 -8
  117. package/dist/{chunk-TAD6QMMD.js → chunk-PRC7SZYM.js} +2 -2
  118. package/dist/{chunk-LWZNSQN3.js → chunk-PUQQPLVV.js} +3 -3
  119. package/dist/{chunk-LWZNSQN3.js.map → chunk-PUQQPLVV.js.map} +1 -1
  120. package/dist/{chunk-GMO3BGOF.js → chunk-QC2MHZDD.js} +1 -1
  121. package/dist/{chunk-FOTFLHBN.js → chunk-QPLI7LUU.js} +3 -2
  122. package/dist/chunk-QPLI7LUU.js.map +1 -0
  123. package/dist/{chunk-2MWKUVHT.js → chunk-RK7SE3BL.js} +5 -5
  124. package/dist/{chunk-HDWISXFH.js → chunk-RVAPK2S7.js} +2 -2
  125. package/dist/{chunk-5PUZV73Z.js → chunk-SEIGLG62.js} +11 -11
  126. package/dist/{chunk-AVWOULJH.js → chunk-SH3GOZWK.js} +2 -2
  127. package/dist/{chunk-PFLN6TTW.js → chunk-T3MCVSUC.js} +2 -2
  128. package/dist/{chunk-WQUGCOKF.js → chunk-TFA6HPOA.js} +4 -4
  129. package/dist/{chunk-CLVILSBR.js → chunk-TGQW3AMK.js} +22 -22
  130. package/dist/{chunk-YZYAYUJQ.js → chunk-TLRIRISJ.js} +4 -4
  131. package/dist/{chunk-7VIJUZYW.js → chunk-TQ4CELUR.js} +3 -3
  132. package/dist/{chunk-5QDTZIGH.js → chunk-U7KP6QFU.js} +2 -2
  133. package/dist/{chunk-BUKK5SWA.js → chunk-UPD5XDJX.js} +5 -5
  134. package/dist/{chunk-BUKK5SWA.js.map → chunk-UPD5XDJX.js.map} +1 -1
  135. package/dist/{chunk-QVXEXGIM.js → chunk-VF6SC4OD.js} +2 -2
  136. package/dist/{chunk-EZG54YDS.js → chunk-VKXJQF5C.js} +2 -2
  137. package/dist/{chunk-RFLC6PKQ.js → chunk-VMRPLHEU.js} +2 -2
  138. package/dist/{chunk-U2PSE7MB.js → chunk-VPEIWMUT.js} +2 -2
  139. package/dist/{chunk-X67XNZ64.js → chunk-W4EJMMPP.js} +10 -10
  140. package/dist/{chunk-RB7NXZ2E.js → chunk-W4Q65VJL.js} +2 -2
  141. package/dist/{chunk-HDDRVXX4.js → chunk-W5LJ3SJ7.js} +2 -2
  142. package/dist/{chunk-W7N7NWG5.js → chunk-WCJQ3OUP.js} +2 -2
  143. package/dist/{chunk-JIF22AXI.js → chunk-WGKIXNLY.js} +5 -2
  144. package/dist/{chunk-JIF22AXI.js.map → chunk-WGKIXNLY.js.map} +1 -1
  145. package/dist/{chunk-FFWFFAP3.js → chunk-WI2WTIMY.js} +14 -8
  146. package/dist/chunk-WI2WTIMY.js.map +1 -0
  147. package/dist/{chunk-UVYI6VIX.js → chunk-X7Y7WX73.js} +1 -1
  148. package/dist/{chunk-22V3CMIW.js → chunk-XJTRIHTH.js} +8 -8
  149. package/dist/{chunk-SIONKXLU.js → chunk-XTRC6SSS.js} +14 -14
  150. package/dist/{chunk-SBRUTD5O.js → chunk-YSATDEBY.js} +5 -5
  151. package/dist/{chunk-3YOX2BQD.js → chunk-YWMCV5HL.js} +3 -3
  152. package/dist/{chunk-L272A5QW.js → chunk-YYDUBGUF.js} +30 -22
  153. package/dist/chunk-YYDUBGUF.js.map +1 -0
  154. package/dist/{chunk-6QWFZ3X5.js → chunk-ZA6CYFAK.js} +2 -2
  155. package/dist/cli.js +138 -137
  156. package/dist/coding/export-okf-codegraph.js +24 -24
  157. package/dist/coding/pre-action-gate.js +2 -2
  158. package/dist/compounding/engine.js +14 -14
  159. package/dist/config.js +24 -24
  160. package/dist/connectors/codex-marketplace.d.ts.map +1 -1
  161. package/dist/connectors/codex-materialize-runner.js +14 -14
  162. package/dist/connectors/codex-materialize.d.ts.map +1 -1
  163. package/dist/connectors/codex-materialize.js +1 -1
  164. package/dist/connectors/index.js +15 -15
  165. package/dist/consolidation-provenance-check.js +2 -2
  166. package/dist/convergence-refresh.js +15 -15
  167. package/dist/conversation-index/backend.js +2 -2
  168. package/dist/corpus-watermark.js +15 -15
  169. package/dist/deep-recall-http-glue.js +11 -11
  170. package/dist/embedding-fallback.js +2 -2
  171. package/dist/entity-retrieval.js +14 -14
  172. package/dist/event-order-recall.js +3 -3
  173. package/dist/explicit-capture.js +138 -137
  174. package/dist/extraction-judge.js +1 -1
  175. package/dist/extraction-normalization.js +1 -1
  176. package/dist/extraction-span-materialize.js +2 -2
  177. package/dist/extraction.js +27 -27
  178. package/dist/{graph-edge-decay-BC3IO2J4.js → graph-edge-decay-CXTNJ7IQ.js} +6 -6
  179. package/dist/graph-edge-decay-CXTNJ7IQ.js.map +1 -0
  180. package/dist/graph-jsonl.js +4 -4
  181. package/dist/graph-snapshot.js +4 -4
  182. package/dist/graph.js +5 -5
  183. package/dist/harmonic-retrieval.js +13 -13
  184. package/dist/index.js +197 -196
  185. package/dist/lcm/index.js +3 -3
  186. package/dist/local-llm.js +2 -2
  187. package/dist/location/index.js +14 -14
  188. package/dist/maintenance/memory-governance.js +13 -13
  189. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +13 -13
  190. package/dist/maintenance/rebuild-memory-projection-runner.js +15 -15
  191. package/dist/maintenance/rebuild-memory-projection.js +14 -14
  192. package/dist/memory-browse.js +5 -5
  193. package/dist/memory-controller.d.ts.map +1 -1
  194. package/dist/memory-controller.js +1 -1
  195. package/dist/namespaces/migrate.js +14 -14
  196. package/dist/namespaces/search.js +7 -7
  197. package/dist/namespaces/storage.d.ts.map +1 -1
  198. package/dist/namespaces/storage.js +13 -13
  199. package/dist/offline-sync-changeset-generations.js +4 -4
  200. package/dist/offline-sync-embedding-generation.js +3 -3
  201. package/dist/offline-sync-snapshot-stream.js +7 -7
  202. package/dist/offline-sync.js +6 -6
  203. package/dist/operator-doctor-corpus.js +16 -16
  204. package/dist/operator-toolkit.js +35 -35
  205. package/dist/orchestration/backlog-scheduler.d.ts +4 -0
  206. package/dist/orchestration/backlog-scheduler.d.ts.map +1 -1
  207. package/dist/orchestration/backlog-scheduler.js +149 -142
  208. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  209. package/dist/orchestration/buffer-drain-runner.js +139 -138
  210. package/dist/orchestration/extraction-persist-citation.d.ts +2 -2
  211. package/dist/orchestration/extraction-persist-citation.d.ts.map +1 -1
  212. package/dist/orchestration/extraction-persist.d.ts.map +1 -1
  213. package/dist/orchestration/maintenance.js +23 -23
  214. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  215. package/dist/orchestration/turn-ingestion-buffered.d.ts.map +1 -1
  216. package/dist/orchestrator.d.ts.map +1 -1
  217. package/dist/orchestrator.js +140 -139
  218. package/dist/qmd.js +4 -4
  219. package/dist/recall-navigation.js +138 -137
  220. package/dist/recall-state-view-admission.js +5 -5
  221. package/dist/recall-state-view-packet.d.ts.map +1 -1
  222. package/dist/recall-state-view-packet.js +30 -8
  223. package/dist/recall-state-view-packet.js.map +1 -1
  224. package/dist/recall-why-service.js +5 -5
  225. package/dist/reconcile/manifest.js +2 -2
  226. package/dist/resume-bundles.js +25 -25
  227. package/dist/search/factory.js +6 -6
  228. package/dist/search/index.js +8 -8
  229. package/dist/semantic-consolidation.js +18 -18
  230. package/dist/semantic-rule-promotion.js +13 -13
  231. package/dist/semantic-rule-verifier.js +13 -13
  232. package/dist/source-agent-qualifier.js +18 -18
  233. package/dist/source-attribution.d.ts +3 -3
  234. package/dist/source-attribution.d.ts.map +1 -1
  235. package/dist/source-attribution.js +1 -1
  236. package/dist/standup/build.js +13 -13
  237. package/dist/storage.d.ts +1 -0
  238. package/dist/storage.d.ts.map +1 -1
  239. package/dist/storage.js +12 -12
  240. package/dist/summarizer.d.ts +7 -1
  241. package/dist/summarizer.d.ts.map +1 -1
  242. package/dist/summarizer.js +3 -3
  243. package/dist/support-passport/index.js +16 -16
  244. package/dist/transfer/autodetect.js +3 -3
  245. package/dist/transfer/backup.js +2 -2
  246. package/dist/transfer/capsule-export.js +3 -3
  247. package/dist/transfer/capsule-import.js +3 -3
  248. package/dist/transfer/export-okf.js +13 -13
  249. package/dist/transfer/import-json.js +2 -2
  250. package/dist/transfer/import-md.js +2 -2
  251. package/dist/transfer/types.d.ts +15 -3
  252. package/dist/transfer/types.d.ts.map +1 -1
  253. package/dist/transfer/types.js +3 -1
  254. package/dist/verified-recall.js +13 -13
  255. package/dist/who-knows-cli.js +14 -14
  256. package/dist/who-knows.js +13 -13
  257. package/package.json +2 -2
  258. package/src/access-cli.test.ts +9 -9
  259. package/src/access-recall-excerpt-attribution.ts +69 -0
  260. package/src/access-recall-surface.ts +23 -21
  261. package/src/access-service-raw-excerpt-read-gate.test.ts +192 -11
  262. package/src/backlog-scheduler.test.ts +31 -0
  263. package/src/binary-lifecycle/scanner.ts +35 -14
  264. package/src/buffer-add-turns-bounded.ts +16 -2
  265. package/src/buffer-session-cap.ts +4 -4
  266. package/src/buffer.ts +5 -5
  267. package/src/calibration.ts +56 -4
  268. package/src/connectors/codex-marketplace-git.test.ts +267 -0
  269. package/src/connectors/codex-marketplace.ts +76 -13
  270. package/src/connectors/codex-materialize.ts +29 -55
  271. package/src/memory-controller.test.ts +11 -0
  272. package/src/memory-controller.ts +5 -1
  273. package/src/namespaces/storage.ts +1 -0
  274. package/src/orchestration/backlog-scheduler.ts +12 -3
  275. package/src/orchestration/extraction-persist-citation.ts +5 -3
  276. package/src/orchestration/extraction-persist.ts +15 -14
  277. package/src/orchestration/recall-internal.ts +2 -3
  278. package/src/orchestration/turn-ingestion-buffered.test.ts +52 -1
  279. package/src/orchestration/turn-ingestion-buffered.ts +26 -8
  280. package/src/orchestrator.ts +1 -0
  281. package/src/recall-state-view-packet.test.ts +40 -0
  282. package/src/recall-state-view-packet.ts +46 -9
  283. package/src/source-attribution.test.ts +57 -0
  284. package/src/source-attribution.ts +46 -43
  285. package/src/storage.ts +4 -3
  286. package/src/summarizer-shutdown.test.ts +49 -16
  287. package/src/summarizer.ts +13 -5
  288. package/src/testing/subjects/memory-maintenance.test.ts +293 -0
  289. package/src/transfer/capsule-export.ts +2 -1
  290. package/src/transfer/capsule-taxonomy-version.test.ts +70 -0
  291. package/src/transfer/types.ts +13 -3
  292. package/dist/chunk-AL3TCNSJ.js.map +0 -1
  293. package/dist/chunk-BPCR5DZP.js.map +0 -1
  294. package/dist/chunk-D6BOOYNJ.js.map +0 -1
  295. package/dist/chunk-FFWFFAP3.js.map +0 -1
  296. package/dist/chunk-FOTFLHBN.js.map +0 -1
  297. package/dist/chunk-L272A5QW.js.map +0 -1
  298. package/dist/chunk-OWM2VWNX.js.map +0 -1
  299. package/dist/chunk-QLQUAVVP.js.map +0 -1
  300. package/dist/chunk-WEHSQBFR.js.map +0 -1
  301. /package/dist/{capsule-crypto-GWVG7LGC.js.map → access-recall-excerpt-attribution.js.map} +0 -0
  302. /package/dist/{auto-sync-L3M4RKJD.js.map → auto-sync-ACP5U5A3.js.map} +0 -0
  303. /package/dist/{graph-edge-decay-BC3IO2J4.js.map → capsule-crypto-7FJQINUR.js.map} +0 -0
  304. /package/dist/{capsule-merge-VHBRF65A.js.map → capsule-merge-BADOICNP.js.map} +0 -0
  305. /package/dist/{chunk-OWHERGF2.js.map → chunk-2NLLXCJG.js.map} +0 -0
  306. /package/dist/{chunk-L7SEYUHS.js.map → chunk-3I3NXB6X.js.map} +0 -0
  307. /package/dist/{chunk-4NBUHYUV.js.map → chunk-3LADDLAF.js.map} +0 -0
  308. /package/dist/{chunk-2DL3OFLD.js.map → chunk-45GEJRIG.js.map} +0 -0
  309. /package/dist/{chunk-5BE3FLKL.js.map → chunk-5KDDAQ6K.js.map} +0 -0
  310. /package/dist/{chunk-HLWXCDUQ.js.map → chunk-63A2BU2B.js.map} +0 -0
  311. /package/dist/{chunk-MOUSHJAR.js.map → chunk-7FPI5MFB.js.map} +0 -0
  312. /package/dist/{chunk-ZX546Y3Y.js.map → chunk-7OYDFIL4.js.map} +0 -0
  313. /package/dist/{chunk-CKZWLAHN.js.map → chunk-ACPFBVUD.js.map} +0 -0
  314. /package/dist/{chunk-BKTCVXMK.js.map → chunk-AHOYKJ5X.js.map} +0 -0
  315. /package/dist/{chunk-FGT7CUYZ.js.map → chunk-ALTLOHO7.js.map} +0 -0
  316. /package/dist/{chunk-FMFCQRDM.js.map → chunk-AUFPPBC3.js.map} +0 -0
  317. /package/dist/{chunk-OAQRZ4SV.js.map → chunk-B5KTTWC7.js.map} +0 -0
  318. /package/dist/{chunk-73TPOGS4.js.map → chunk-BFBS7OFQ.js.map} +0 -0
  319. /package/dist/{chunk-QFTK6EDM.js.map → chunk-BFZFNXOC.js.map} +0 -0
  320. /package/dist/{chunk-ZQUOUPP3.js.map → chunk-BHRPZBAH.js.map} +0 -0
  321. /package/dist/{chunk-4L25GAYL.js.map → chunk-CX24SVLK.js.map} +0 -0
  322. /package/dist/{chunk-YY57TRKN.js.map → chunk-D5ZLTLHF.js.map} +0 -0
  323. /package/dist/{chunk-WEFFO2MJ.js.map → chunk-D6YCETHG.js.map} +0 -0
  324. /package/dist/{chunk-ZDZJNXL6.js.map → chunk-DK2VBJ6Q.js.map} +0 -0
  325. /package/dist/{chunk-VRHY7Y5A.js.map → chunk-DPL5VO5V.js.map} +0 -0
  326. /package/dist/{chunk-LVGTH6IQ.js.map → chunk-E7ATID4Z.js.map} +0 -0
  327. /package/dist/{chunk-CKELO7Q6.js.map → chunk-FHWX2REL.js.map} +0 -0
  328. /package/dist/{chunk-CUPILBIP.js.map → chunk-FMIM36I4.js.map} +0 -0
  329. /package/dist/{chunk-A5UOREWD.js.map → chunk-FWTGO4NE.js.map} +0 -0
  330. /package/dist/{chunk-3SL52JKD.js.map → chunk-FZVROZKC.js.map} +0 -0
  331. /package/dist/{chunk-U3BCW7GX.js.map → chunk-G3RLCVJC.js.map} +0 -0
  332. /package/dist/{chunk-UYIBNDQE.js.map → chunk-GF5NN3LE.js.map} +0 -0
  333. /package/dist/{chunk-7OCKK5M5.js.map → chunk-GWY5ZFHP.js.map} +0 -0
  334. /package/dist/{chunk-TNRGWJYT.js.map → chunk-H4IU24V5.js.map} +0 -0
  335. /package/dist/{chunk-T4BT4FQN.js.map → chunk-HH6PXQ2B.js.map} +0 -0
  336. /package/dist/{chunk-FEUWI5QH.js.map → chunk-HHPY5SSE.js.map} +0 -0
  337. /package/dist/{chunk-OM5ESBES.js.map → chunk-HQPFACXO.js.map} +0 -0
  338. /package/dist/{chunk-IMULTENA.js.map → chunk-ID65XTF3.js.map} +0 -0
  339. /package/dist/{chunk-WWQMZBDI.js.map → chunk-IJVU4ILJ.js.map} +0 -0
  340. /package/dist/{chunk-GBSXTTLP.js.map → chunk-ITGAGNX5.js.map} +0 -0
  341. /package/dist/{chunk-3PNJZTDV.js.map → chunk-JGGNUEVD.js.map} +0 -0
  342. /package/dist/{chunk-YYXYZM2I.js.map → chunk-JN7OSQJR.js.map} +0 -0
  343. /package/dist/{chunk-4D2EY4WM.js.map → chunk-K2DTHNDY.js.map} +0 -0
  344. /package/dist/{chunk-TH6OYP6I.js.map → chunk-K36RMINQ.js.map} +0 -0
  345. /package/dist/{chunk-OZKVVUJB.js.map → chunk-KIM5VNZN.js.map} +0 -0
  346. /package/dist/{chunk-ZWDDY4WF.js.map → chunk-M7CFCRWJ.js.map} +0 -0
  347. /package/dist/{chunk-QPFM6DHY.js.map → chunk-MTJFK42O.js.map} +0 -0
  348. /package/dist/{chunk-RO5EGRAI.js.map → chunk-N3FRR6II.js.map} +0 -0
  349. /package/dist/{chunk-UMEUU66X.js.map → chunk-O3OEVYUR.js.map} +0 -0
  350. /package/dist/{chunk-J74YOBB3.js.map → chunk-PFR6ZKQI.js.map} +0 -0
  351. /package/dist/{chunk-TAD6QMMD.js.map → chunk-PRC7SZYM.js.map} +0 -0
  352. /package/dist/{chunk-GMO3BGOF.js.map → chunk-QC2MHZDD.js.map} +0 -0
  353. /package/dist/{chunk-2MWKUVHT.js.map → chunk-RK7SE3BL.js.map} +0 -0
  354. /package/dist/{chunk-HDWISXFH.js.map → chunk-RVAPK2S7.js.map} +0 -0
  355. /package/dist/{chunk-5PUZV73Z.js.map → chunk-SEIGLG62.js.map} +0 -0
  356. /package/dist/{chunk-AVWOULJH.js.map → chunk-SH3GOZWK.js.map} +0 -0
  357. /package/dist/{chunk-PFLN6TTW.js.map → chunk-T3MCVSUC.js.map} +0 -0
  358. /package/dist/{chunk-WQUGCOKF.js.map → chunk-TFA6HPOA.js.map} +0 -0
  359. /package/dist/{chunk-CLVILSBR.js.map → chunk-TGQW3AMK.js.map} +0 -0
  360. /package/dist/{chunk-YZYAYUJQ.js.map → chunk-TLRIRISJ.js.map} +0 -0
  361. /package/dist/{chunk-7VIJUZYW.js.map → chunk-TQ4CELUR.js.map} +0 -0
  362. /package/dist/{chunk-5QDTZIGH.js.map → chunk-U7KP6QFU.js.map} +0 -0
  363. /package/dist/{chunk-QVXEXGIM.js.map → chunk-VF6SC4OD.js.map} +0 -0
  364. /package/dist/{chunk-EZG54YDS.js.map → chunk-VKXJQF5C.js.map} +0 -0
  365. /package/dist/{chunk-RFLC6PKQ.js.map → chunk-VMRPLHEU.js.map} +0 -0
  366. /package/dist/{chunk-U2PSE7MB.js.map → chunk-VPEIWMUT.js.map} +0 -0
  367. /package/dist/{chunk-X67XNZ64.js.map → chunk-W4EJMMPP.js.map} +0 -0
  368. /package/dist/{chunk-RB7NXZ2E.js.map → chunk-W4Q65VJL.js.map} +0 -0
  369. /package/dist/{chunk-HDDRVXX4.js.map → chunk-W5LJ3SJ7.js.map} +0 -0
  370. /package/dist/{chunk-W7N7NWG5.js.map → chunk-WCJQ3OUP.js.map} +0 -0
  371. /package/dist/{chunk-UVYI6VIX.js.map → chunk-X7Y7WX73.js.map} +0 -0
  372. /package/dist/{chunk-22V3CMIW.js.map → chunk-XJTRIHTH.js.map} +0 -0
  373. /package/dist/{chunk-SIONKXLU.js.map → chunk-XTRC6SSS.js.map} +0 -0
  374. /package/dist/{chunk-SBRUTD5O.js.map → chunk-YSATDEBY.js.map} +0 -0
  375. /package/dist/{chunk-3YOX2BQD.js.map → chunk-YWMCV5HL.js.map} +0 -0
  376. /package/dist/{chunk-6QWFZ3X5.js.map → chunk-ZA6CYFAK.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/buffer-add-turns-bounded.ts"],"sourcesContent":["/** Bounded multi-session turn admission (#3368 split from buffer.ts). */\n\nimport { selectEvictedBufferKeys } from \"./buffer-eviction.js\";\nimport {\n hasBufferedAdmissionIdempotencyKey,\n recordBufferedAdmissionIdempotencyKey,\n} from \"./buffer-admission-idempotency.js\";\nimport { refuseOverCapBatch, resolveMaxTurnsPerSession } from \"./buffer-session-cap.js\";\nimport type { BufferSessionPersistence } from \"./buffer-persistence.js\";\nimport type { BufferIngressCounters } from \"./buffer-ingress-counters.js\";\nimport type { AddTurnMutationResult, AddTurnOutcome } from \"./buffer-types.js\";\nimport { EVICTION_HOOKS } from \"./buffer-turn-helpers.js\";\nimport type { BufferEntryState, BufferState, BufferTurn, PluginConfig } from \"./types.js\";\n\nexport type AddTurnsBoundedOutcome =\n | Array<{ bufferKey: string; turn: BufferTurn; outcome: AddTurnOutcome }>\n | null\n | \"duplicate\";\n\nexport interface AddTurnsBoundedHost {\n readonly config: PluginConfig;\n readonly maxSessionEntries: number;\n get state(): BufferState;\n readonly persistence: BufferSessionPersistence;\n readonly ingress: BufferIngressCounters;\n enqueueMutation<T>(work: () => Promise<T>): Promise<T>;\n loadUnlocked(): Promise<void>;\n peekEntry(bufferKey: string): BufferEntryState | null;\n recordTurnUnlocked(bufferKey: string, turn: BufferTurn): Promise<AddTurnMutationResult>;\n completeAddTurnOutcome(\n bufferKey: string,\n turn: BufferTurn,\n mutation: AddTurnMutationResult,\n ): Promise<AddTurnOutcome>;\n}\n\nexport async function addTurnsBoundedWithAdmissionKey(\n host: AddTurnsBoundedHost,\n batches: readonly { bufferKey: string; turns: readonly BufferTurn[] }[],\n admissionKey?: string,\n): Promise<AddTurnsBoundedOutcome> {\n const pending = await host.enqueueMutation(async () => {\n await host.loadUnlocked();\n if (admissionKey && hasBufferedAdmissionIdempotencyKey(host.state, admissionKey)) {\n return \"duplicate\" as const;\n }\n const additions: Array<{ bufferKey: string; turn: BufferTurn }> = [];\n for (const batch of batches) {\n for (const turn of batch.turns) {\n additions.push({ bufferKey: batch.bufferKey, turn });\n }\n }\n\n if (refuseOverCapBatch((key) => host.peekEntry(key) ?? null, batches, resolveMaxTurnsPerSession(host.config.bufferMaxTurnsPerSession))) {\n return host.ingress.refuseAll(additions);\n }\n const entries = host.state.entries ?? {};\n const newKeys = [\n ...new Set(\n additions\n .map(({ bufferKey }) => bufferKey)\n .filter((bufferKey) => host.peekEntry(bufferKey) === null),\n ),\n ];\n const count = Object.keys(entries).length;\n const requiredEvictions = Math.max(0, count + newKeys.length - host.maxSessionEntries);\n if (requiredEvictions > 0) {\n const target = Math.max(0, host.maxSessionEntries - newKeys.length);\n const evicted = selectEvictedBufferKeys(entries, newKeys, target, EVICTION_HOOKS);\n if (newKeys.length > 0 && evicted.length < requiredEvictions) return host.ingress.refuseAll(additions);\n for (const key of evicted) delete entries[key];\n host.persistence.markEvicted(evicted);\n }\n\n const recorded: Array<{ bufferKey: string; turn: BufferTurn; mutation: AddTurnMutationResult }> = [];\n for (const { bufferKey, turn } of additions) {\n recorded.push({ bufferKey, turn, mutation: await host.recordTurnUnlocked(bufferKey, turn) });\n }\n if (admissionKey) {\n recordBufferedAdmissionIdempotencyKey(host.state, admissionKey, recorded.length);\n host.persistence.markAdmissionIdempotencyDirty();\n }\n return recorded;\n });\n if (pending === \"duplicate\") return \"duplicate\";\n if (pending === null) return null;\n\n const outcomes: Array<{ bufferKey: string; turn: BufferTurn; outcome: AddTurnOutcome }> = [];\n for (const item of pending) {\n outcomes.push({\n bufferKey: item.bufferKey,\n turn: item.turn,\n outcome: await host.completeAddTurnOutcome(item.bufferKey, item.turn, item.mutation),\n });\n }\n return outcomes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,eAAsB,gCACpB,MACA,SACA,cACiC;AACjC,QAAM,UAAU,MAAM,KAAK,gBAAgB,YA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F;AACA,QAAI,cAAc;AAChB,4CAAsC,KAAK,OAAO,cAAc,SAAS,MAAM;AAC/E,WAAK,YAAY,8BAA8B;AAAA,IACjD;AACA,WAAO;AAAA,EACT,CAAC;AACD,MAAI,YAAY,YAAa,QAAO;AACpC,MAAI,YAAY,KAAM,QAAO;AAE7B,QAAM,WAAoF,CAAC;AAC3F,aAAW,QAAQ,SAAS;AAC1B,aAAS,KAAK;AAAA,MACZ,WAAW,KAAK;AAAA,MAChB,MAAM,KAAK;AAAA,MACX,SAAS,MAAM,KAAK,uBAAuB,KAAK,WAAW,KAAK,MAAM,KAAK,QAAQ;AAAA,IACrF,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/namespaces/storage.ts"],"sourcesContent":["import { resolveNamespaceCapabilities, resolveRecallAuxiliaryCapabilities } 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 { keyring, secureStoreDir } from \"../secure-store/index.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { ALL_CATEGORY_DIRS } from \"../utils/category-dir.js\";\nimport { isMacOsReplicationJunkBasename } from \"../utils/macos-replication-junk.js\";\nimport {\n namespaceIdentityLegacyToken,\n namespaceIdentityToken,\n normalizeNamespaceIdentity,\n} 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 if (isMacOsReplicationJunkBasename(child.name)) continue;\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 defaultNfdIdentity = defaultIdentity.normalize(\"NFD\");\n const legacyNsDir = resolveNamespaceDir(config.memoryDir, defaultIdentity);\n const legacyNfdNsDir = resolveNamespaceDir(config.memoryDir, defaultNfdIdentity);\n const tokenizedNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityToken(defaultIdentity),\n );\n const legacyTokenNsDir = resolveNamespaceDir(\n config.memoryDir,\n namespaceIdentityLegacyToken(defaultNfdIdentity),\n );\n const tokenizedHasData =\n (await exists(tokenizedNsDir)) &&\n (await hasAnyNamespaceStorageMarker(tokenizedNsDir, { includeRuntimeState: true }));\n const legacyTokenHasData =\n (await exists(legacyTokenNsDir)) &&\n (await hasAnyNamespaceStorageMarker(legacyTokenNsDir, { includeRuntimeState: true }));\n const legacyHasData =\n (await exists(legacyNsDir)) &&\n (await hasAnyNamespaceStorageMarker(legacyNsDir, { includeRuntimeState: true }));\n const legacyNfdHasData =\n legacyNfdNsDir !== legacyNsDir &&\n (await exists(legacyNfdNsDir)) &&\n (await hasAnyNamespaceStorageMarker(legacyNfdNsDir, { includeRuntimeState: true }));\n const nsDir = tokenizedHasData\n ? tokenizedNsDir\n : legacyTokenHasData\n ? legacyTokenNsDir\n : legacyHasData\n ? legacyNsDir\n : legacyNfdHasData\n ? legacyNfdNsDir\n : (await exists(legacyNsDir))\n ? legacyNsDir\n : legacyNfdNsDir !== legacyNsDir && (await exists(legacyNfdNsDir))\n ? legacyNfdNsDir\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 normalized = normalizeNamespaceIdentity(namespace);\n const legacyExactNamespace = namespace.trim();\n const legacyNfdNamespace = normalized.normalize(\"NFD\");\n const legacyRoot = resolveNamespaceDir(config.memoryDir, normalized);\n const legacyExactRoot =\n legacyExactNamespace !== normalized && isSafeRouteNamespace(legacyExactNamespace)\n ? resolveNamespaceDir(config.memoryDir, legacyExactNamespace)\n : null;\n const legacyNfdRoot =\n legacyNfdNamespace !== normalized\n ? resolveNamespaceDir(config.memoryDir, legacyNfdNamespace)\n : null;\n const tokenizedRoot = resolveNamespaceDir(config.memoryDir, namespaceIdentityToken(normalized));\n const legacyTokenRoots = [\n namespaceIdentityLegacyToken(legacyExactNamespace),\n namespaceIdentityLegacyToken(legacyNfdNamespace),\n ]\n .filter((token, index, tokens) => tokens.indexOf(token) === index)\n .map((token) => resolveNamespaceDir(config.memoryDir, token));\n for (const candidate of [tokenizedRoot, ...legacyTokenRoots]) {\n if (\n (await exists(candidate)) &&\n (await hasAnyNamespaceStorageMarker(candidate, { includeRuntimeState: true }))\n ) {\n return candidate;\n }\n }\n for (const candidate of [legacyRoot, legacyExactRoot, legacyNfdRoot]) {\n if (candidate && (await exists(candidate))) return candidate;\n }\n return 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 /** #2019: hook fired when a new namespace storage is created via storageFor. */\n onStorageCreated?: (storage: StorageManager, namespace: string) => void;\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 await this.applySecureStoreConfig(cached);\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 await this.applySecureStoreConfig(cached);\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 const { scopedCacheInvalidationEnabled } = this.config;\n StorageManager.setScopedCacheInvalidationDefault(root, scopedCacheInvalidationEnabled);\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 // #2033: install the secure-store context on router-created stores. The\n // orchestrator keys ONLY its primary default-namespace storage; without\n // this, a store resolved through the router reads isSecureStoreUnlocked()\n // === false even after the operator unlocked the keyring, so secure-store\n // recovery paths (e.g. the CLI lifecycle-ledger rebuild) refuse an encrypted\n // ledger they could actually rewrite, and namespace writes could silently\n // fall back to plaintext. Mirror the orchestrator's setup exactly.\n await this.applySecureStoreConfig(sm);\n this.cache.set(ns, sm);\n // #2019: let the orchestrator wire write-triggered prioritized embedding on\n // every router-created namespace storage, not just the primary default store.\n this.onStorageCreated?.(sm, ns);\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 // Issue #1903: pure state-file writes only touch the catalog when explicitly\n // opted in. Router-created storages (storageFor) and the legacy default\n // storage both flow through here, so this is the single wiring point.\n sm.touchStateWrites = this.config.namespacesCatalogTouchStateWrites === true;\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 * Install the at-rest secure-store context on a router-created StorageManager\n * (#2033). Mirrors the orchestrator's primary-storage setup: mark the store\n * required so a locked store throws instead of silently writing plaintext, and\n * install the master key when the process-local keyring already holds it (the\n * operator unlocked). The secure store is one key per memory ROOT (single\n * header + per-file path-bound AAD), so every namespace store keys off the\n * root keyring id — exactly the id the orchestrator and `secure-store unlock`\n * register under. No-op when secure-store is disabled.\n */\n private async applySecureStoreConfig(sm: StorageManager): Promise<void> {\n if (!resolveRecallAuxiliaryCapabilities(this.config).secureStore) return;\n sm.setSecureStoreRequired(true);\n const existingKey = keyring.getKey(secureStoreDir(this.config.memoryDir));\n if (existingKey) {\n await sm.setSecureStoreKeyAndWait(existingKey, this.config.secureStoreEncryptOnWrite);\n }\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 // Flush any coalesced (buffered) touches first so their appends join the\n // pending set below — otherwise this could resolve while a buffered touch's\n // lastWriteAt is still unwritten on disk (#1903, Cursor). No-op when\n // coalescing is disabled (window 0) or the catalog is inert.\n await this.catalog?.flushPendingTouches().catch(() => undefined);\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 /**\n * #2019: iterate the currently cached router storages with their namespace so\n * callers can wire hooks on stores resolved before the hook was installed.\n */\n forEachCachedStorage(fn: (storage: StorageManager, namespace: string) => void): void {\n for (const [namespace, storage] of this.cache) fn(storage, namespace);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,QAAQ,OAAO,eAAe;AAevC,eAAe,OAAO,GAA6B;AACjD,MAAI;AACF,UAAM,OAAO,CAAC;AACd,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,eAAe,iBAAiB,GAA6B;AAC3D,MAAI;AACF,UAAM,QAAQ,MAAM,MAAM,CAAC;AAC3B,QAAI,MAAM,eAAe,EAAG,QAAO;AACnC,QAAI,CAAC,MAAM,YAAY,EAAG,QAAO;AACjC,UAAM,WAAW,MAAM,QAAQ,GAAG,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,SAAS,UAAU;AAC5B,UAAI,+BAA+B,MAAM,IAAI,EAAG;AAChD,YAAM,YAAY,KA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Q,WAAW,CAAC,GAAG,KAAK,mBAAmB,CAAC;AAAA,IACxD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,qBAAqB,IAAgE;AACnF,eAAW,CAAC,WAAW,OAAO,KAAK,KAAK,MAAO,IAAG,SAAS,SAAS;AAAA,EACtE;AACF;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/source-attribution.ts"],"sourcesContent":["/**\n * Inline Source Attribution Protocol (issue #369)\n *\n * Extracted facts carry provenance inline inside the fact body, so the\n * citation survives hostile memory text, copy/paste, and LLM quoting. This\n * complements — never replaces — the YAML frontmatter provenance stored on\n * disk.\n *\n * Default format (matches issue #369 proposal):\n *\n * The foo service uses Redis for rate limiting. [Source: agent=planner, session=abc123, ts=2026-04-10T14:25:07Z]\n *\n * Key properties:\n * - Inline (part of the body, not metadata).\n * - Compact (typically <80 chars of overhead per fact).\n * - Machine-parseable by a single regex.\n * - Opt-in via `inlineSourceAttributionEnabled` config flag (default off\n * for backwards compatibility with existing downstream consumers).\n * - Legacy facts without a citation remain fully readable.\n *\n * The format template is configurable via `inlineSourceAttributionFormat`\n * with supported placeholders:\n *\n * {agent} — principal / agent identifier\n * {session} — full session key (colon-delimited)\n * {sessionId} — short stable session id (trailing component)\n * {ts} — extraction timestamp (ISO 8601)\n * {date} — extraction date (YYYY-MM-DD)\n *\n * Any privacy-sensitive identifiers should be normalized before being passed\n * to `formatCitation` — the helper treats them as opaque strings.\n */\n\n/** Default citation format template (matches issue #369). */\nexport const DEFAULT_CITATION_FORMAT =\n \"[Source: agent={agent}, session={sessionId}, ts={ts}]\";\n\n/** Sentinel value used when a provenance field is missing. */\nexport const CITATION_UNKNOWN = \"unknown\";\n\nexport interface CitationContext {\n /** Principal / agent identifier (e.g. resolved via resolvePrincipal). */\n agent?: string;\n /** Full session key (e.g. \"agent:planner:main\"). */\n session?: string;\n /**\n * Opaque short session id. Derived from the trailing component of the\n * session key when not provided explicitly. Use this for compact formats\n * that do not need the full colon-delimited session key.\n */\n sessionId?: string;\n /** Extraction timestamp as an ISO 8601 string. */\n ts?: string;\n}\n\nexport interface ParsedCitation {\n /** Agent identifier parsed from the citation (never crashes on malformed input). */\n agent?: string;\n /** Session identifier parsed from the citation. */\n session?: string;\n /** Extraction timestamp parsed from the citation. */\n ts?: string;\n /** The full matched citation substring. */\n raw: string;\n}\n\n/**\n * Regex that matches the default `[Source: agent=X, session=Y, ts=Z]` shape\n * as well as human-edited variants (extra whitespace, reordered fields,\n * subset of fields). Matches non-greedily so it can be anchored anywhere in\n * the text. Kept as a getter factory so callers do not share regex state.\n */\nfunction defaultCitationMatcher(): RegExp {\n // Bounded repetition {1,1024} instead of + so the match cannot backtrack\n // polynomially over hostile memory text (CodeQL js/polynomial-redos). A real\n // citation is far shorter than 1024 chars, so this is behavior-preserving for\n // any genuine [Source: …] block; only pathological/oversized input is excluded.\n return /\\[Source:([^\\]\\n]{1,1024})\\]/gi;\n}\n\n// Linear trailing-whitespace trim. Replaces text.replace(/\\s+$/u, \"\"), whose\n// anchored quantifier backtracks polynomially on long inputs (CodeQL\n// js/polynomial-redos). Matches the exact \\s (with u flag) semantics one char\n// at a time, so the trailing-content preservation logic in attachCitation is\n// unaffected.\nfunction trimTrailingWhitespace(text: string): string {\n let end = text.length;\n while (end > 0 && /\\s/u.test(text[end - 1]!)) end--;\n return text.slice(0, end);\n}\n\n/**\n * Derive a short session id from a full session key.\n * Falls back to the raw session string if no colon is present.\n */\nexport function deriveSessionId(session: string | undefined): string | undefined {\n if (!session) return undefined;\n const trimmed = session.trim();\n if (trimmed.length === 0) return undefined;\n const parts = trimmed.split(\":\").filter((p) => p.length > 0);\n if (parts.length === 0) return trimmed;\n return parts[parts.length - 1];\n}\n\n/**\n * Format an inline citation tag using the provided template.\n *\n * Missing context fields fall back to {@link CITATION_UNKNOWN} — the caller\n * should always get a non-empty, parseable tag.\n *\n * Uses a single-pass substitution so that values which themselves contain\n * placeholder syntax (e.g. an agent literally named `\"{ts}\"`) cannot be\n * re-interpreted by subsequent replacement steps. Each placeholder slot\n * receives exactly one lookup and the substituted value is treated as\n * terminal text, not template source.\n */\nexport function formatCitation(\n ctx: CitationContext,\n template: string = DEFAULT_CITATION_FORMAT,\n): string {\n const session = ctx.session ?? \"\";\n const sessionId = ctx.sessionId ?? deriveSessionId(session) ?? CITATION_UNKNOWN;\n const ts = ctx.ts ?? CITATION_UNKNOWN;\n const agent = ctx.agent && ctx.agent.trim().length > 0 ? ctx.agent : CITATION_UNKNOWN;\n const date = ts && ts !== CITATION_UNKNOWN ? ts.slice(0, 10) : CITATION_UNKNOWN;\n const sessionForTemplate = session.trim().length > 0 ? session : CITATION_UNKNOWN;\n\n // Map from recognised placeholder names to their resolved value. Unknown\n // placeholder names are left intact (returning the original `{name}`).\n const values: Record<string, string> = {\n agent,\n session: sessionForTemplate,\n sessionId,\n ts,\n date,\n };\n\n // Single-pass scan: replace every recognised `{name}` in one sweep so that\n // substituted values cannot themselves be treated as template source on a\n // subsequent pass. The replacer-function form also guarantees that `$` /\n // `$&` / `$1` sequences inside values are emitted literally.\n return template.replace(/\\{([a-zA-Z_][\\w]*)\\}/g, (match, name: string) => {\n return Object.prototype.hasOwnProperty.call(values, name)\n ? values[name]!\n : match;\n });\n}\n\n/**\n * Returns true if the text already carries at least one citation marker.\n * Safe to call on any string — never throws.\n */\nexport function hasCitation(text: string): boolean {\n if (typeof text !== \"string\" || text.length === 0) return false;\n return defaultCitationMatcher().test(text);\n}\n\n/**\n * Escape a string for use as a regex literal.\n */\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Escape a single character for use INSIDE a character class `[...]`.\n * Special chars inside character classes: `]`, `\\`, `^`, `-`.\n */\nfunction escapeRegExpCharClass(ch: string): string {\n if (ch === \"]\") return \"\\\\]\";\n if (ch === \"\\\\\") return \"\\\\\\\\\";\n if (ch === \"^\") return \"\\\\^\";\n if (ch === \"-\") return \"\\\\-\";\n // Other regex meta chars are NOT special inside [...] but escaping them is safe.\n return escapeRegExp(ch);\n}\n\n/**\n * Build a per-placeholder token pattern that excludes newlines, whitespace,\n * and any punctuation characters used as inner separators in the template.\n *\n * This prevents a placeholder span from consuming separator bytes and\n * matching strings that cross separator boundaries in user-supplied content.\n *\n * @param nonWordSepChars - Set of non-word (non-alphanumeric, non-`_`) chars\n * extracted from the inner separator literals of the template.\n */\nfunction buildTokenPattern(nonWordSepChars: Set<string>): string {\n // Always exclude newlines and whitespace.\n const base = \"\\\\n\\\\s\";\n if (nonWordSepChars.size === 0) {\n // No inner separator punctuation — the placeholder spans the full space\n // between prefix and suffix. Fall back to a generous no-newline match.\n return `[^\\\\n]+?`;\n }\n const escaped = [...nonWordSepChars].map(escapeRegExpCharClass).join(\"\");\n return `[^${base}${escaped}]+?`;\n}\n\n/** Regex that matches a `{placeholder}` token inside a template string. */\nconst PLACEHOLDER_REGEX = /\\{[a-zA-Z_][\\w]*\\}/g;\n\n/**\n * Build a regex that matches a citation produced by the given template.\n *\n * The approach depends on the shape of the template:\n *\n * - **Normal case (non-empty literal prefix or suffix).** Anchor the match\n * on the outer literal frame and reconstruct the interior as\n * `interToken + sep + interToken + sep + ... + sep + lastToken`.\n * All **intermediate** per-placeholder tokens exclude the combined set of\n * non-word separator characters used between any two adjacent placeholders,\n * preventing a value from consuming a separator and crossing placeholder\n * boundaries. The **last** token is only required to avoid newlines because\n * it is terminated by the literal suffix anchor — this lets placeholder\n * values that legitimately contain a separator character be recognised (e.g.\n * an ISO-8601 timestamp `2026-04-10T14:25:07Z` in `[src:{agent}:{ts}]`\n * where `:` is the inter-placeholder separator). A template like\n * `[src:{agent}/{sessionId}@{date}]` emits\n * `\\[src:[^\\n\\s/@]+?\\/[^\\n\\s/@]+?@[^\\n]+?\\]` so that `[src:foo/bar]`\n * is NOT matched (wrong separator count), `[src:foo/bar/extra@2026]`\n * is NOT matched (intermediate token crosses a `/` boundary), and\n * `[src:planner/main@2026-04-10]` IS matched correctly.\n *\n * - **Placeholder-bounded with whitespace separator.** Both prefix and\n * suffix are empty and the separator literal(s) between placeholders\n * contain at least one whitespace character (e.g. `{source}: {content}`,\n * `{agent} {sessionId}`). A whitespace-containing separator produces\n * output that is visually indistinguishable from ordinary prose, so the\n * safe strategy is to require a **hard bracket/paren/angle delimiter** on\n * both sides of the reconstructed match. Prose almost never places\n * `[...]` / `(...)` / `<...>` around a phrase, so this yields clean\n * false-positive rejection.\n *\n * - **Placeholder-bounded with compact (non-whitespace) separator.** Both\n * prefix and suffix are empty and the separator literal(s) contain NO\n * whitespace (e.g. `{agent}:{sessionId}`, `{agent}/{sessionId}`).\n * `formatCitation` emits a compact token like `planner:main` with no\n * surrounding delimiters, so the bracket strategy cannot detect it.\n * Instead, the pattern requires that the entire token is bordered by\n * whitespace or a bracket/paren/angle on each side:\n *\n * `(?:(?<=[\\[\\(\\<])|(?<!\\S))[\\w.-]+<sep>[\\w.-]+(?:(?=[\\]\\)\\>])|(?!\\S))`\n *\n * This accepts `planner:main` when it appears standalone or inside a\n * bracket-wrapped token, and rejects `host:80` embedded inside a URL like\n * `http://host:80` because `host` is immediately preceded by `/`\n * (non-whitespace, non-bracket).\n *\n * - **All-placeholder case (no literals between placeholders either).** No\n * reliable regex can be built — a template like `{agent}{sessionId}`\n * contains no anchor characters. Returns `null`; {@link\n * hasCitationForTemplate} treats this as \"cannot detect\" and returns\n * false, falling back on explicit sentinel/format detection only for the\n * default `[Source: ...]` shape.\n *\n * Returns `null` when the template has no placeholders (fully-literal\n * citation, handled by the string-equality fast path in {@link\n * hasCitationForTemplate}) **or** when the template is entirely placeholder-\n * only with no literal content whatsoever.\n */\nfunction templateMatcher(template: string): RegExp | null {\n // Split around all {placeholder} tokens.\n const parts = template.split(PLACEHOLDER_REGEX);\n if (parts.length <= 1) return null;\n\n const prefix = parts[0] ?? \"\";\n const suffix = parts[parts.length - 1] ?? \"\";\n\n // Normal case: at least one literal frame on the outside.\n // Tighten the per-placeholder token so it cannot consume separator\n // characters and match strings that cross separator boundaries\n // (Finding 3 — Uru3).\n if (prefix.length > 0 || suffix.length > 0) {\n const escapedPrefix = escapeRegExp(prefix);\n const escapedSuffix = escapeRegExp(suffix);\n\n // Inner parts: literal separators that sit between adjacent placeholders.\n // For `[src:{agent}/{sessionId}@{date}]`, parts = [\"[src:\", \"/\", \"@\", \"]\"]\n // so innerParts = [\"/\", \"@\"].\n const innerParts = parts.slice(1, -1);\n\n // Collect only the non-word (punctuation/symbol) characters from each\n // inner separator so alphabetic separator text (unlikely but valid) does\n // not exclude letters from the per-placeholder token pattern.\n const nonWordSepChars = new Set<string>();\n for (const sep of innerParts) {\n for (const ch of sep) {\n if (!/\\w/.test(ch)) {\n nonWordSepChars.add(ch);\n }\n }\n }\n\n // All intermediate tokens (every placeholder except the last) use the\n // combined exclusion so they cannot cross placeholder boundaries.\n //\n // The LAST token is different: it is terminated by the literal suffix anchor\n // (e.g. `\\]`), so it does not need to exclude inner-separator characters.\n // Dropping that restriction lets placeholder values that legitimately contain\n // a separator character (e.g. an ISO-8601 timestamp `2026-04-10T14:25:07Z`\n // in template `[src:{agent}:{ts}]`) be recognised correctly instead of\n // producing false-negative misses that trigger duplicate citation injection.\n //\n // Only the LAST token is relaxed. Intermediate tokens keep the combined\n // exclusion so that cross-boundary false positives are still rejected\n // (e.g. `[src:foo/bar/extra@2026-04-11]` for `[src:{a}/{b}@{c}]`).\n const interToken = buildTokenPattern(nonWordSepChars);\n // Last token: terminated by suffix anchor — exclude only newlines.\n const lastToken = buildTokenPattern(new Set<string>());\n\n // Reconstruct the interior: interToken sep interToken sep ... sep lastToken\n // (or just lastToken when there are no inner separators at all).\n const middle =\n innerParts.length === 0\n ? lastToken\n : interToken +\n innerParts\n .slice(0, -1)\n .map((sep) => escapeRegExp(sep) + interToken)\n .join(\"\") +\n escapeRegExp(innerParts[innerParts.length - 1]!) +\n lastToken;\n\n const pattern = escapedPrefix + middle + escapedSuffix;\n return new RegExp(pattern, \"i\");\n }\n\n // Placeholder-bounded case: prefix and suffix are both empty.\n const middleLiterals = parts.slice(1, -1);\n const hasNonEmptyMiddle = middleLiterals.some((p) => p.length > 0);\n if (!hasNonEmptyMiddle) {\n // All-placeholder template with no literal content. Impossible to anchor\n // reliably without sentinel markers; signal the caller.\n return null;\n }\n\n // Identifier token: one or more word chars, dots, dashes, or colons.\n // Colons are included to allow timestamp values like \"10:30\" or session\n // keys like \"agent:planner:main\" inside compact placeholder-bounded\n // templates. URL-like fragments (`http://host:80`) are still rejected\n // because the lead anchor requires whitespace or a bracket immediately\n // before the first id-token group (`http` is preceded by `/`).\n const idToken = \"[\\\\w.:-]+\";\n const body =\n idToken +\n middleLiterals.map((lit) => escapeRegExp(lit) + idToken).join(\"\");\n\n const separatorText = middleLiterals.join(\"\");\n if (/\\s/.test(separatorText)) {\n // Separator contains whitespace: the emitted citation looks like ordinary\n // prose (e.g. `planner main`). Require a hard bracket/paren/angle\n // delimiter on both sides to prevent false matches on English text.\n const opener = \"[\\\\[\\\\(\\\\<]\";\n const closer = \"[\\\\]\\\\)\\\\>]\";\n return new RegExp(opener + body + closer, \"i\");\n }\n\n // Separator is compact (no whitespace): `formatCitation` emits a token like\n // `planner:main` without surrounding delimiters. The challenge is that the\n // same token shape also matches ordinary hyphenated or slashed prose words\n // (e.g. `long-term`, `docs/setup`), causing `hasCitationForTemplate` to\n // return true on uncited fact bodies and silently suppress citation injection\n // from `attachCitation`.\n //\n // Fix (Finding 1): tighten the trail anchor so a bare compact token is only\n // accepted when it sits at the very end of the string (possibly followed by\n // optional trailing whitespace or a newline). Since `attachCitation` always\n // appends the citation at the trimmed end of the fact body, a real citation\n // token will always appear at the tail. Prose like `\"long-term solution\"`\n // has `long-term` in the middle of the string (followed by ` solution`), so\n // the end-of-string anchor rejects it — no false positive, no silent drop.\n //\n // The lead anchor still accepts either a bracket opener or a whitespace\n // boundary (or start of string), so `\"Fact. planner:main\"` and standalone\n // `\"planner:main\"` are both detected after the first attachment pass.\n //\n // Bracket-wrapped form (e.g. `[planner:main]`) is also accepted via the\n // opener/closer pair — bracket still takes precedence over end-of-string.\n //\n // Example — why `http://host:80` does NOT match:\n // Trying to match `host:80`: the char before `h` is `/` (non-whitespace,\n // non-bracket), so `(?<=[\\[\\(\\<])` and `(?<!\\S)` both fail ⟹ no match.\n // Trying to match `http:...`: after `http:` the next chars are `//` which\n // are not `[\\w.-]+`, so the second id-token group fails ⟹ no match.\n const leadAnchor = \"(?:(?<=[\\\\[\\\\(\\\\<])|(?<!\\\\S))\";\n // Trail: either a bracket closer (for `[token]` shape) or end-of-string\n // optionally preceded by whitespace. The `(?!\\S)` is deliberately removed\n // so that a compact token in the MIDDLE of a sentence does not match.\n const trailAnchor = \"(?:(?=[\\\\]\\\\)\\\\>])|(?=\\\\s*$))\";\n return new RegExp(leadAnchor + body + trailAnchor, \"i\");\n}\n\n/**\n * Returns true if `text` already carries a citation produced by `template`\n * **or** by the default `[Source: ...]` format (for facts that were tagged\n * before a config change).\n *\n * Use this instead of {@link hasCitation} whenever the caller has access to\n * the configured `inlineSourceAttributionFormat`.\n *\n * All-placeholder templates such as `{agent}{sessionId}` have no literal\n * content to anchor on and therefore cannot be reliably detected without\n * dedicated sentinel markers. In that case the function returns `false` —\n * callers that need idempotent dedup for such templates should either adopt\n * a template with literal delimiters (recommended) or rely on the default\n * `[Source: ...]` marker detection which is always available via\n * {@link hasCitation}.\n */\nexport function hasCitationForTemplate(text: string, template: string): boolean {\n if (typeof text !== \"string\" || text.length === 0) return false;\n // Always accept the default format as a fallback so facts tagged before a\n // configuration change are not double-tagged on reprocessing.\n if (hasCitation(text)) return true;\n // If the configured template matches the default, we're done.\n //\n // Known limitation (Thread 2 — Codex P2): this fast path exits without\n // checking whether the content carries a citation from a DIFFERENT custom\n // template that was active before the config was changed back to the default.\n // Such a fact would be detected by `hasCitation` above only if the prior\n // custom template happened to match the default `[Source: ...]` pattern.\n // In practice, template changes mid-stream are rare, and the false-negative\n // (missing an old custom citation) produces a benign duplicate citation rather\n // than data loss. A full fix would require storing the citation template used\n // at write time in the frontmatter and checking that here.\n if (template === DEFAULT_CITATION_FORMAT) return false;\n\n // Fully-literal template (no placeholders): exact inclusion check.\n if (!PLACEHOLDER_REGEX.test(template)) {\n // Reset lastIndex because PLACEHOLDER_REGEX is declared with /g.\n PLACEHOLDER_REGEX.lastIndex = 0;\n return text.includes(template);\n }\n // Reset lastIndex after the .test() probe above.\n PLACEHOLDER_REGEX.lastIndex = 0;\n\n const matcher = templateMatcher(template);\n if (!matcher) {\n // All-placeholder template: cannot build a reliable matcher. See the\n // docstring — callers should not rely on dedup for this shape.\n return false;\n }\n return matcher.test(text);\n}\n\n/**\n * Return the LAST citation marker in `text` for the given template (or the\n * default `[Source: ...]` shape). `attachCitation` always appends at the\n * trimmed end, so the last occurrence is the most recently attached marker —\n * callers use this to lift a just-attached citation off a cited body and\n * re-attach it to a derived body (the merged-target commit path). Returns\n * null when the text carries no marker of this template (including\n * all-placeholder templates that cannot be matched reliably).\n */\nexport function lastCitationMarkerForTemplate(\n text: string,\n template: string = DEFAULT_CITATION_FORMAT,\n): string | null {\n if (typeof text !== \"string\" || text.length === 0) return null;\n let matcher: RegExp | null;\n if (template === DEFAULT_CITATION_FORMAT) {\n matcher = defaultCitationMatcher();\n } else if (!PLACEHOLDER_REGEX.test(template)) {\n // Fully-literal template: presence is exact inclusion (no placeholders\n // to widen the match).\n PLACEHOLDER_REGEX.lastIndex = 0;\n return text.includes(template) ? template : null;\n } else {\n PLACEHOLDER_REGEX.lastIndex = 0;\n matcher = templateMatcher(template);\n }\n if (!matcher) return null;\n const global = new RegExp(\n matcher.source,\n matcher.flags.includes(\"g\") ? matcher.flags : matcher.flags + \"g\",\n );\n let last: string | null = null;\n for (let match = global.exec(text); match !== null; match = global.exec(text)) {\n last = match[0];\n if (match[0].length === 0) global.lastIndex++;\n }\n return last;\n}\n\n/**\n * True when a template can be matched and stripped later. All-placeholder\n * templates such as `{agent}{sessionId}` have no literal anchors.\n */\nexport function citationTemplateIsDetectable(template: string): boolean {\n if (typeof template !== \"string\" || template.length === 0) return false;\n if (template === DEFAULT_CITATION_FORMAT) return true;\n PLACEHOLDER_REGEX.lastIndex = 0;\n if (!PLACEHOLDER_REGEX.test(template)) {\n PLACEHOLDER_REGEX.lastIndex = 0;\n return true;\n }\n PLACEHOLDER_REGEX.lastIndex = 0;\n return templateMatcher(template) !== null;\n}\n\n/**\n * Templates the merge path may lift, preserve, or strip. Longest\n * templates first so an overlapping custom marker beats an inner default\n * match; the current template wins equal-length ties. Undetectable\n * shapes are dropped so we never hash or attach a marker we cannot re-match.\n */\nexport function citationTemplatesToRecognize(\n primary: string | undefined,\n extra: readonly string[] = [],\n): string[] {\n const out: string[] = [];\n const add = (template: string | undefined): void => {\n if (typeof template !== \"string\" || template.length === 0) return;\n if (!citationTemplateIsDetectable(template)) return;\n if (!out.includes(template)) out.push(template);\n };\n add(primary);\n for (const template of extra) add(template);\n add(DEFAULT_CITATION_FORMAT);\n out.sort((a, b) => {\n if (b.length !== a.length) return b.length - a.length;\n if (a === primary && b !== primary) return -1;\n if (b === primary && a !== primary) return 1;\n return 0;\n });\n return out;\n}\n\n/**\n * Prior formats the caller still holds, if any. Absent or malformed\n * history is ignored — fail safe, do not invent templates.\n */\nexport function citationTemplatesForMerge(config: {\n inlineSourceAttributionFormat?: string;\n inlineSourceAttributionFormatHistory?: unknown;\n}): string[] {\n const raw = config.inlineSourceAttributionFormatHistory;\n const extra = Array.isArray(raw)\n ? raw.filter((value): value is string => typeof value === \"string\" && value.length > 0)\n : [];\n return citationTemplatesToRecognize(config.inlineSourceAttributionFormat, extra);\n}\n\nexport function lastRecognizedCitationMarker(\n text: string,\n templates: readonly string[],\n): string | null {\n for (const template of templates) {\n const marker = lastCitationMarkerForTemplate(text, template);\n if (marker) return marker;\n }\n return null;\n}\n\nexport function stripRecognizedCitations(text: string, templates: readonly string[]): string {\n let out = text;\n for (const template of templates) {\n out = stripCitationForTemplate(out, template);\n }\n return out;\n}\n\n/**\n * Attach an inline citation to fact text.\n *\n * If the text already has a citation — either the default `[Source: ...]`\n * marker or one produced by the configured template — it is returned unchanged.\n * Existing provenance is respected and never overwritten. Otherwise the\n * citation is appended to the trimmed text with a single space separator,\n * which keeps the marker visually adjacent to the fact body.\n */\nexport function attachCitation(\n text: string,\n ctx: CitationContext,\n template: string = DEFAULT_CITATION_FORMAT,\n): string {\n if (typeof text !== \"string\") return text as unknown as string;\n if (hasCitationForTemplate(text, template)) return text;\n const trimmedEnd = trimTrailingWhitespace(text);\n if (trimmedEnd.length === 0) return text;\n const citation = formatCitation(ctx, template);\n // Preserve any trailing newline that callers rely on for markdown rendering.\n const trailing = text.slice(trimmedEnd.length);\n return `${trimmedEnd} ${citation}${trailing}`;\n}\n\n/**\n * Parse a single inline citation from a piece of text. Returns the first\n * citation encountered or `null` when none is present. Malformed citations\n * do not throw — fields that cannot be parsed simply remain `undefined`.\n */\nexport function parseCitation(text: string): ParsedCitation | null {\n if (typeof text !== \"string\" || text.length === 0) return null;\n const matcher = defaultCitationMatcher();\n const match = matcher.exec(text);\n if (!match) return null;\n\n const body = match[1] ?? \"\";\n const raw = match[0] ?? \"\";\n const parsed: ParsedCitation = { raw };\n\n const fields = body\n .split(\",\")\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n\n for (const field of fields) {\n const eqIdx = field.indexOf(\"=\");\n if (eqIdx <= 0) continue;\n const key = field.slice(0, eqIdx).trim().toLowerCase();\n const value = field.slice(eqIdx + 1).trim();\n if (value.length === 0) continue;\n switch (key) {\n case \"agent\":\n parsed.agent = value;\n break;\n case \"session\":\n case \"sessionid\":\n parsed.session = value;\n break;\n case \"ts\":\n case \"timestamp\":\n parsed.ts = value;\n break;\n default:\n // Unknown fields are ignored defensively so human edits never crash.\n break;\n }\n }\n\n return parsed;\n}\n\n/**\n * Parse every citation embedded in the text. Always returns an array; empty\n * when none are present.\n */\nexport function parseAllCitations(text: string): ParsedCitation[] {\n if (typeof text !== \"string\" || text.length === 0) return [];\n const matcher = defaultCitationMatcher();\n const results: ParsedCitation[] = [];\n let match: RegExpExecArray | null;\n while ((match = matcher.exec(text)) !== null) {\n const parsed = parseCitation(match[0]);\n if (parsed) results.push(parsed);\n }\n return results;\n}\n\n/**\n * Remove all inline citations from a piece of text.\n *\n * Callers that want the raw fact body (for dedup hashing, display, or\n * comparison) should use this helper instead of hand-rolled regexes so the\n * whole codebase agrees on the citation syntax.\n *\n * Finding 2 fix: when the input contains no citation marker, the input is\n * returned byte-for-byte unchanged. When a citation IS removed, whitespace\n * normalization is applied only at each join seam (the single space between\n * the preceding text and where the citation was), rather than across the\n * entire string. This preserves markdown hard-break spacing, aligned text,\n * and code-like snippets in fact bodies that happen to carry a citation.\n *\n * Implementation: each citation match is replaced by its \"seam fix\" — the\n * content before the match has its trailing whitespace trimmed and then a\n * single space is appended if any text remains, collapsing only the gap\n * left by the removed marker. Whitespace elsewhere in the body is untouched.\n */\nexport function stripCitation(text: string): string {\n if (typeof text !== \"string\" || text.length === 0) return text;\n // Early exit: no citation marker present — return the input unchanged so\n // that callers never lose formatting fidelity on uncited strings.\n if (!hasCitation(text)) return text;\n\n // Walk through all citations and slice them out one by one so that we can\n // normalise ONLY the whitespace at each seam rather than the entire string.\n const matcher = defaultCitationMatcher();\n let result = \"\";\n let lastIndex = 0;\n\n let match: RegExpExecArray | null;\n while ((match = matcher.exec(text)) !== null) {\n // Text before this citation. Trim trailing spaces/tabs at the seam only.\n const before = text.slice(lastIndex, match.index).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = match.index + match[0].length;\n }\n\n // Append any trailing text after the last citation. Trim leading\n // spaces/tabs and trailing whitespace at the join seam.\n const after = text.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n\n return result.trimEnd();\n}\n\n/**\n * Strip an inline citation from text using a specific template regex.\n *\n * This is the template-aware counterpart to {@link stripCitation}. When the\n * caller holds the configured `inlineSourceAttributionFormat`, use this\n * function to strip citations produced by that template — including custom\n * templates that differ from the default `[Source: ...]` pattern.\n *\n * Behaviour:\n * - If the text has a **default-format** citation, strips it first\n * (always safe).\n * - Then, if the result has a **custom-template** citation detected by\n * `hasCitationForTemplate`, builds the template regex and removes every\n * occurrence. BOTH passes run when a body carries both forms — a target\n * written under the default format can carry the default marker plus a\n * custom marker appended after a config change; returning after the\n * default pass alone left the custom marker inside hash inputs (#2330).\n * - Fully-literal templates (no placeholders) are stripped by exact match\n * of the template text, the same inclusion check `hasCitationForTemplate`\n * uses.\n * - All-placeholder templates (no literal prefix/suffix/separator) cannot\n * produce a reliable matcher. `hasCitationForTemplate` already returns\n * `false` for such templates, so this function never attempts to strip an\n * undetectable citation. The text is returned unchanged when no citation\n * is detected.\n * - If no citation is detected for the given template, returns the text\n * unchanged.\n *\n * @returns The stripped text (or the original text when no citation is found).\n */\nexport function stripCitationForTemplate(\n text: string,\n template: string,\n): string {\n if (typeof text !== \"string\" || text.length === 0) return text;\n\n // First pass: the default-format marker, if any. A second pass below still\n // runs — a body can carry the default marker AND the custom template's\n // marker, and canonicalization must remove every recognized form.\n const afterDefault = hasCitation(text) ? stripCitation(text) : text;\n\n if (!hasCitationForTemplate(afterDefault, template)) return afterDefault;\n\n PLACEHOLDER_REGEX.lastIndex = 0;\n if (!PLACEHOLDER_REGEX.test(template)) {\n PLACEHOLDER_REGEX.lastIndex = 0;\n return stripExactLiteralCitation(afterDefault, template);\n }\n PLACEHOLDER_REGEX.lastIndex = 0;\n\n // Build the template matcher. hasCitationForTemplate already returned true,\n // which means templateMatcher produced a non-null result. The null branch\n // here is a defensive fallback only — the default pass already ran.\n const matcher = templateMatcher(template);\n if (!matcher) return afterDefault;\n\n // The matcher regex was built without the global flag; add it for exec loop.\n const globalMatcher = new RegExp(\n matcher.source,\n matcher.flags.includes(\"g\") ? matcher.flags : matcher.flags + \"g\",\n );\n let result = \"\";\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n while ((match = globalMatcher.exec(afterDefault)) !== null) {\n const matchEnd = match.index + match[0].length;\n const enclosure = enclosingDelimiterRange(afterDefault, match.index, matchEnd);\n const removalStart = enclosure?.start ?? match.index;\n const removalEnd = enclosure?.end ?? matchEnd;\n const before = afterDefault.slice(lastIndex, removalStart).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = removalEnd;\n // Guard against zero-width matches causing an infinite loop.\n if (match[0].length === 0) {\n globalMatcher.lastIndex++;\n }\n }\n\n const after = afterDefault.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n\n return result.trimEnd();\n}\n\nfunction stripExactLiteralCitation(text: string, marker: string): string {\n if (marker.length === 0) return text;\n let result = \"\";\n let lastIndex = 0;\n let idx = text.indexOf(marker);\n if (idx === -1) return text;\n while (idx !== -1) {\n const before = text.slice(lastIndex, idx).replace(/[ \\t]+$/, \"\");\n result += before;\n lastIndex = idx + marker.length;\n idx = text.indexOf(marker, lastIndex);\n }\n const after = text.slice(lastIndex).replace(/^[ \\t]+/, \"\");\n if (after.length > 0) {\n if (result.length > 0) result += \" \";\n result += after;\n }\n return result.trimEnd();\n}\n\nfunction enclosingDelimiterRange(\n text: string,\n start: number,\n end: number,\n): { start: number; end: number } | undefined {\n if (start <= 0 || end >= text.length) return undefined;\n const opener = text[start - 1];\n const closer = text[end];\n if (\n (opener === \"[\" && closer === \"]\") ||\n (opener === \"(\" && closer === \")\") ||\n (opener === \"<\" && closer === \">\")\n ) {\n return { start: start - 1, end: end + 1 };\n }\n return undefined;\n}\n"],"mappings":";AAkCO,IAAM,0BACX;AAGK,IAAM,mBAAmB;AAkChC,SAAS,yBAAiC;AAKxC,SAAO;AACT;AAOA,SAAS,uBAAuB,MAAsB;AACpD,MAAI,MAAM,KAAK;AACf,SAAO,MAAM,KAAK,MAAM,KAAK,KAAK,MAAM,CAAC,CAAE,EAAG;AAC9C,SAAO,KAAK,MAAM,GAAG,GAAG;AA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