@remnic/core 10.0.167 → 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 (390) hide show
  1. package/dist/access-admin-ops-surface.js +139 -138
  2. package/dist/access-cli.js +139 -138
  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 +139 -138
  6. package/dist/access-extraction-force-flush.js +139 -138
  7. package/dist/access-http-briefing.js +139 -138
  8. package/dist/access-http-query.js +139 -138
  9. package/dist/access-http.js +139 -138
  10. package/dist/access-identity-continuity-surface.js +139 -138
  11. package/dist/access-lcm-surface.js +139 -138
  12. package/dist/access-mcp.js +139 -138
  13. package/dist/access-observe-write-category.js +11 -11
  14. package/dist/access-observe-write-surface.js +139 -138
  15. package/dist/access-offline-manifest.js +9 -9
  16. package/dist/access-operations-batch.js +139 -138
  17. package/dist/access-operations.js +139 -138
  18. package/dist/access-recall-concurrency.js +139 -138
  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 +139 -138
  23. package/dist/access-recall-surface.d.ts.map +1 -1
  24. package/dist/access-recall-surface.js +139 -138
  25. package/dist/access-schema.js +10 -10
  26. package/dist/access-service.js +139 -138
  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/bulk-import/index.d.ts +1 -1
  44. package/dist/bulk-import/index.d.ts.map +1 -1
  45. package/dist/bulk-import/index.js +3 -1
  46. package/dist/bulk-import/pipeline.d.ts +8 -0
  47. package/dist/bulk-import/pipeline.d.ts.map +1 -1
  48. package/dist/calibration.d.ts +19 -2
  49. package/dist/calibration.d.ts.map +1 -1
  50. package/dist/calibration.js +28 -5
  51. package/dist/calibration.js.map +1 -1
  52. package/dist/{capsule-crypto-GWVG7LGC.js → capsule-crypto-7FJQINUR.js} +2 -2
  53. package/dist/{capsule-merge-VHBRF65A.js → capsule-merge-BADOICNP.js} +2 -2
  54. package/dist/causal-behavior.js +2 -2
  55. package/dist/causal-chain.js +2 -2
  56. package/dist/causal-consolidation.js +17 -17
  57. package/dist/causal-retrieval.js +2 -2
  58. package/dist/causal-trajectory-graph.js +3 -3
  59. package/dist/causal-trajectory.js +1 -1
  60. package/dist/{chunk-OWHERGF2.js → chunk-2NLLXCJG.js} +2 -2
  61. package/dist/{chunk-IE2ZLO3R.js → chunk-32OTLNAU.js} +274 -248
  62. package/dist/chunk-32OTLNAU.js.map +1 -0
  63. package/dist/{chunk-L7SEYUHS.js → chunk-3I3NXB6X.js} +3 -3
  64. package/dist/{chunk-4NBUHYUV.js → chunk-3LADDLAF.js} +5 -5
  65. package/dist/{chunk-2DL3OFLD.js → chunk-45GEJRIG.js} +2 -2
  66. package/dist/{chunk-HSSERO3E.js → chunk-4P4GF76E.js} +8 -1
  67. package/dist/chunk-4P4GF76E.js.map +1 -0
  68. package/dist/{chunk-5BE3FLKL.js → chunk-5KDDAQ6K.js} +8 -8
  69. package/dist/{chunk-BPCR5DZP.js → chunk-62YZOQFR.js} +5 -5
  70. package/dist/chunk-62YZOQFR.js.map +1 -0
  71. package/dist/{chunk-HLWXCDUQ.js → chunk-63A2BU2B.js} +5 -5
  72. package/dist/{chunk-C5QYWM6F.js → chunk-7FPI5MFB.js} +5 -5
  73. package/dist/{chunk-ZX546Y3Y.js → chunk-7OYDFIL4.js} +2 -2
  74. package/dist/{chunk-CKZWLAHN.js → chunk-ACPFBVUD.js} +2 -2
  75. package/dist/{chunk-BKTCVXMK.js → chunk-AHOYKJ5X.js} +3 -3
  76. package/dist/{chunk-WEHSQBFR.js → chunk-AIF6V2OX.js} +9 -4
  77. package/dist/chunk-AIF6V2OX.js.map +1 -0
  78. package/dist/{chunk-FGT7CUYZ.js → chunk-ALTLOHO7.js} +2 -2
  79. package/dist/{chunk-FMFCQRDM.js → chunk-AUFPPBC3.js} +3 -3
  80. package/dist/{chunk-OAQRZ4SV.js → chunk-B5KTTWC7.js} +2 -2
  81. package/dist/{chunk-73TPOGS4.js → chunk-BFBS7OFQ.js} +9 -9
  82. package/dist/{chunk-QFTK6EDM.js → chunk-BFZFNXOC.js} +13 -13
  83. package/dist/{chunk-ZQUOUPP3.js → chunk-BHRPZBAH.js} +4 -4
  84. package/dist/{chunk-4L25GAYL.js → chunk-CX24SVLK.js} +2 -2
  85. package/dist/{chunk-YY57TRKN.js → chunk-D5ZLTLHF.js} +2 -2
  86. package/dist/{chunk-WEFFO2MJ.js → chunk-D6YCETHG.js} +2 -2
  87. package/dist/{chunk-ZDZJNXL6.js → chunk-DK2VBJ6Q.js} +4 -4
  88. package/dist/{chunk-VRHY7Y5A.js → chunk-DPL5VO5V.js} +3 -3
  89. package/dist/{chunk-LVGTH6IQ.js → chunk-E7ATID4Z.js} +11 -11
  90. package/dist/{chunk-CKELO7Q6.js → chunk-FHWX2REL.js} +2 -2
  91. package/dist/{chunk-CUPILBIP.js → chunk-FMIM36I4.js} +2 -2
  92. package/dist/{chunk-OWM2VWNX.js → chunk-FSXYBIEZ.js} +25 -24
  93. package/dist/chunk-FSXYBIEZ.js.map +1 -0
  94. package/dist/{chunk-A5UOREWD.js → chunk-FWTGO4NE.js} +2 -2
  95. package/dist/{chunk-3SL52JKD.js → chunk-FZVROZKC.js} +5 -5
  96. package/dist/{chunk-U3BCW7GX.js → chunk-G3RLCVJC.js} +3 -3
  97. package/dist/{chunk-UYIBNDQE.js → chunk-GF5NN3LE.js} +2 -2
  98. package/dist/{chunk-7OCKK5M5.js → chunk-GWY5ZFHP.js} +6 -6
  99. package/dist/{chunk-AL3TCNSJ.js → chunk-H3MLOQ7F.js} +24 -53
  100. package/dist/chunk-H3MLOQ7F.js.map +1 -0
  101. package/dist/{chunk-TNRGWJYT.js → chunk-H4IU24V5.js} +2 -2
  102. package/dist/{chunk-T4BT4FQN.js → chunk-HH6PXQ2B.js} +3 -3
  103. package/dist/{chunk-FEUWI5QH.js → chunk-HHPY5SSE.js} +2 -2
  104. package/dist/{chunk-OM5ESBES.js → chunk-HQPFACXO.js} +2 -2
  105. package/dist/{chunk-QLQUAVVP.js → chunk-I7WPLMUX.js} +16 -16
  106. package/dist/chunk-I7WPLMUX.js.map +1 -0
  107. package/dist/{chunk-IMULTENA.js → chunk-ID65XTF3.js} +2 -2
  108. package/dist/{chunk-WWQMZBDI.js → chunk-IJVU4ILJ.js} +4 -4
  109. package/dist/{chunk-GBSXTTLP.js → chunk-ITGAGNX5.js} +2 -2
  110. package/dist/chunk-IUGOGDCP.js +39 -0
  111. package/dist/chunk-IUGOGDCP.js.map +1 -0
  112. package/dist/{chunk-3PNJZTDV.js → chunk-JGGNUEVD.js} +2 -2
  113. package/dist/{chunk-YYXYZM2I.js → chunk-JN7OSQJR.js} +2 -2
  114. package/dist/{chunk-4D2EY4WM.js → chunk-K2DTHNDY.js} +6 -6
  115. package/dist/{chunk-TH6OYP6I.js → chunk-K36RMINQ.js} +3 -3
  116. package/dist/{chunk-OZKVVUJB.js → chunk-KIM5VNZN.js} +2 -2
  117. package/dist/{chunk-BFPQJNFZ.js → chunk-LXSDEPEK.js} +60 -11
  118. package/dist/{chunk-BFPQJNFZ.js.map → chunk-LXSDEPEK.js.map} +1 -1
  119. package/dist/{chunk-ZWDDY4WF.js → chunk-M7CFCRWJ.js} +2 -2
  120. package/dist/{chunk-QPFM6DHY.js → chunk-MTJFK42O.js} +2 -2
  121. package/dist/{chunk-RO5EGRAI.js → chunk-N3FRR6II.js} +2 -2
  122. package/dist/{chunk-UMEUU66X.js → chunk-O3OEVYUR.js} +2 -2
  123. package/dist/{chunk-J74YOBB3.js → chunk-PFR6ZKQI.js} +8 -8
  124. package/dist/{chunk-TAD6QMMD.js → chunk-PRC7SZYM.js} +2 -2
  125. package/dist/{chunk-LWZNSQN3.js → chunk-PUQQPLVV.js} +3 -3
  126. package/dist/{chunk-LWZNSQN3.js.map → chunk-PUQQPLVV.js.map} +1 -1
  127. package/dist/{chunk-GMO3BGOF.js → chunk-QC2MHZDD.js} +1 -1
  128. package/dist/{chunk-FOTFLHBN.js → chunk-QPLI7LUU.js} +3 -2
  129. package/dist/chunk-QPLI7LUU.js.map +1 -0
  130. package/dist/{chunk-2MWKUVHT.js → chunk-RK7SE3BL.js} +5 -5
  131. package/dist/{chunk-HDWISXFH.js → chunk-RVAPK2S7.js} +2 -2
  132. package/dist/{chunk-5PUZV73Z.js → chunk-SEIGLG62.js} +11 -11
  133. package/dist/{chunk-AVWOULJH.js → chunk-SH3GOZWK.js} +2 -2
  134. package/dist/{chunk-PFLN6TTW.js → chunk-T3MCVSUC.js} +2 -2
  135. package/dist/{chunk-WQUGCOKF.js → chunk-TFA6HPOA.js} +4 -4
  136. package/dist/{chunk-CLVILSBR.js → chunk-TGQW3AMK.js} +22 -22
  137. package/dist/{chunk-YZYAYUJQ.js → chunk-TLRIRISJ.js} +4 -4
  138. package/dist/{chunk-7VIJUZYW.js → chunk-TQ4CELUR.js} +3 -3
  139. package/dist/{chunk-5QDTZIGH.js → chunk-U7KP6QFU.js} +2 -2
  140. package/dist/{chunk-BUKK5SWA.js → chunk-UPD5XDJX.js} +5 -5
  141. package/dist/{chunk-BUKK5SWA.js.map → chunk-UPD5XDJX.js.map} +1 -1
  142. package/dist/{chunk-QVXEXGIM.js → chunk-VF6SC4OD.js} +2 -2
  143. package/dist/{chunk-EZG54YDS.js → chunk-VKXJQF5C.js} +2 -2
  144. package/dist/{chunk-RFLC6PKQ.js → chunk-VMRPLHEU.js} +2 -2
  145. package/dist/{chunk-U2PSE7MB.js → chunk-VPEIWMUT.js} +2 -2
  146. package/dist/{chunk-X67XNZ64.js → chunk-W4EJMMPP.js} +10 -10
  147. package/dist/{chunk-RB7NXZ2E.js → chunk-W4Q65VJL.js} +2 -2
  148. package/dist/{chunk-HDDRVXX4.js → chunk-W5LJ3SJ7.js} +2 -2
  149. package/dist/{chunk-W7N7NWG5.js → chunk-WCJQ3OUP.js} +2 -2
  150. package/dist/{chunk-JIF22AXI.js → chunk-WGKIXNLY.js} +5 -2
  151. package/dist/{chunk-JIF22AXI.js.map → chunk-WGKIXNLY.js.map} +1 -1
  152. package/dist/{chunk-FFWFFAP3.js → chunk-WI2WTIMY.js} +14 -8
  153. package/dist/chunk-WI2WTIMY.js.map +1 -0
  154. package/dist/{chunk-UVYI6VIX.js → chunk-X7Y7WX73.js} +1 -1
  155. package/dist/{chunk-22V3CMIW.js → chunk-XJTRIHTH.js} +8 -8
  156. package/dist/{chunk-SIONKXLU.js → chunk-XTRC6SSS.js} +14 -14
  157. package/dist/{chunk-SBRUTD5O.js → chunk-YSATDEBY.js} +5 -5
  158. package/dist/{chunk-3YOX2BQD.js → chunk-YWMCV5HL.js} +3 -3
  159. package/dist/{chunk-L272A5QW.js → chunk-YYDUBGUF.js} +30 -22
  160. package/dist/chunk-YYDUBGUF.js.map +1 -0
  161. package/dist/{chunk-6QWFZ3X5.js → chunk-ZA6CYFAK.js} +2 -2
  162. package/dist/cli.d.ts +1 -6
  163. package/dist/cli.d.ts.map +1 -1
  164. package/dist/cli.js +139 -138
  165. package/dist/coding/export-okf-codegraph.js +24 -24
  166. package/dist/coding/pre-action-gate.js +2 -2
  167. package/dist/compounding/engine.js +14 -14
  168. package/dist/config.js +24 -24
  169. package/dist/connectors/codex-marketplace.d.ts.map +1 -1
  170. package/dist/connectors/codex-materialize-runner.js +14 -14
  171. package/dist/connectors/codex-materialize.d.ts.map +1 -1
  172. package/dist/connectors/codex-materialize.js +1 -1
  173. package/dist/connectors/index.js +15 -15
  174. package/dist/consolidation-provenance-check.js +2 -2
  175. package/dist/convergence-refresh.js +15 -15
  176. package/dist/conversation-index/backend.js +2 -2
  177. package/dist/corpus-watermark.js +15 -15
  178. package/dist/deep-recall-http-glue.js +11 -11
  179. package/dist/embedding-fallback.js +2 -2
  180. package/dist/entity-retrieval.js +14 -14
  181. package/dist/event-order-recall.js +3 -3
  182. package/dist/explicit-capture.js +139 -138
  183. package/dist/extraction-judge.js +1 -1
  184. package/dist/extraction-normalization.js +1 -1
  185. package/dist/extraction-span-materialize.js +2 -2
  186. package/dist/extraction.js +27 -27
  187. package/dist/{graph-edge-decay-BC3IO2J4.js → graph-edge-decay-CXTNJ7IQ.js} +6 -6
  188. package/dist/graph-edge-decay-CXTNJ7IQ.js.map +1 -0
  189. package/dist/graph-jsonl.js +4 -4
  190. package/dist/graph-snapshot.js +4 -4
  191. package/dist/graph.js +5 -5
  192. package/dist/harmonic-retrieval.js +13 -13
  193. package/dist/index.js +198 -197
  194. package/dist/lcm/index.js +3 -3
  195. package/dist/local-llm.js +2 -2
  196. package/dist/location/index.js +14 -14
  197. package/dist/maintenance/memory-governance.js +13 -13
  198. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +13 -13
  199. package/dist/maintenance/rebuild-memory-projection-runner.js +15 -15
  200. package/dist/maintenance/rebuild-memory-projection.js +14 -14
  201. package/dist/memory-browse.js +5 -5
  202. package/dist/memory-controller.d.ts.map +1 -1
  203. package/dist/memory-controller.js +1 -1
  204. package/dist/namespaces/migrate.js +14 -14
  205. package/dist/namespaces/search.js +7 -7
  206. package/dist/namespaces/storage.d.ts.map +1 -1
  207. package/dist/namespaces/storage.js +13 -13
  208. package/dist/offline-sync-changeset-generations.js +4 -4
  209. package/dist/offline-sync-embedding-generation.js +3 -3
  210. package/dist/offline-sync-snapshot-stream.js +7 -7
  211. package/dist/offline-sync.js +6 -6
  212. package/dist/operator-doctor-corpus.js +16 -16
  213. package/dist/operator-toolkit.js +35 -35
  214. package/dist/orchestration/backlog-scheduler.d.ts +4 -0
  215. package/dist/orchestration/backlog-scheduler.d.ts.map +1 -1
  216. package/dist/orchestration/backlog-scheduler.js +150 -143
  217. package/dist/orchestration/backlog-scheduler.js.map +1 -1
  218. package/dist/orchestration/buffer-drain-runner.js +140 -139
  219. package/dist/orchestration/extraction-persist-citation.d.ts +2 -2
  220. package/dist/orchestration/extraction-persist-citation.d.ts.map +1 -1
  221. package/dist/orchestration/extraction-persist.d.ts.map +1 -1
  222. package/dist/orchestration/maintenance.js +23 -23
  223. package/dist/orchestration/recall-internal.d.ts.map +1 -1
  224. package/dist/orchestration/turn-ingestion-buffered.d.ts.map +1 -1
  225. package/dist/orchestrator.d.ts.map +1 -1
  226. package/dist/orchestrator.js +141 -140
  227. package/dist/qmd.js +4 -4
  228. package/dist/recall-navigation.js +139 -138
  229. package/dist/recall-state-view-admission.js +5 -5
  230. package/dist/recall-state-view-packet.d.ts.map +1 -1
  231. package/dist/recall-state-view-packet.js +30 -8
  232. package/dist/recall-state-view-packet.js.map +1 -1
  233. package/dist/recall-why-service.js +5 -5
  234. package/dist/reconcile/manifest.js +2 -2
  235. package/dist/resume-bundles.js +25 -25
  236. package/dist/search/factory.js +6 -6
  237. package/dist/search/index.js +8 -8
  238. package/dist/semantic-consolidation.js +18 -18
  239. package/dist/semantic-rule-promotion.js +13 -13
  240. package/dist/semantic-rule-verifier.js +13 -13
  241. package/dist/source-agent-qualifier.js +18 -18
  242. package/dist/source-attribution.d.ts +3 -3
  243. package/dist/source-attribution.d.ts.map +1 -1
  244. package/dist/source-attribution.js +1 -1
  245. package/dist/standup/build.js +13 -13
  246. package/dist/storage.d.ts +1 -0
  247. package/dist/storage.d.ts.map +1 -1
  248. package/dist/storage.js +12 -12
  249. package/dist/summarizer.d.ts +7 -1
  250. package/dist/summarizer.d.ts.map +1 -1
  251. package/dist/summarizer.js +3 -3
  252. package/dist/support-passport/index.js +16 -16
  253. package/dist/transfer/autodetect.js +3 -3
  254. package/dist/transfer/backup.js +2 -2
  255. package/dist/transfer/capsule-export.js +3 -3
  256. package/dist/transfer/capsule-import.js +3 -3
  257. package/dist/transfer/export-okf.js +13 -13
  258. package/dist/transfer/import-json.js +2 -2
  259. package/dist/transfer/import-md.js +2 -2
  260. package/dist/transfer/types.d.ts +15 -3
  261. package/dist/transfer/types.d.ts.map +1 -1
  262. package/dist/transfer/types.js +3 -1
  263. package/dist/verified-recall.js +13 -13
  264. package/dist/who-knows-cli.js +14 -14
  265. package/dist/who-knows.js +13 -13
  266. package/package.json +2 -2
  267. package/src/access-cli.test.ts +9 -9
  268. package/src/access-recall-excerpt-attribution.ts +69 -0
  269. package/src/access-recall-surface.ts +26 -31
  270. package/src/access-service-raw-excerpt-read-gate.test.ts +192 -11
  271. package/src/backlog-scheduler.test.ts +31 -0
  272. package/src/binary-lifecycle/scanner.ts +35 -14
  273. package/src/buffer-add-turns-bounded.ts +16 -2
  274. package/src/buffer-session-cap.ts +4 -4
  275. package/src/buffer.ts +5 -5
  276. package/src/bulk-import/index.ts +1 -0
  277. package/src/bulk-import/pipeline.test.ts +31 -0
  278. package/src/bulk-import/pipeline.ts +14 -0
  279. package/src/calibration.ts +56 -4
  280. package/src/cli.ts +3 -23
  281. package/src/connectors/codex-marketplace-git.test.ts +267 -0
  282. package/src/connectors/codex-marketplace.ts +76 -13
  283. package/src/connectors/codex-materialize.ts +29 -55
  284. package/src/memory-controller.test.ts +11 -0
  285. package/src/memory-controller.ts +5 -1
  286. package/src/namespaces/storage.ts +1 -0
  287. package/src/orchestration/backlog-scheduler.ts +12 -3
  288. package/src/orchestration/extraction-persist-citation.ts +5 -3
  289. package/src/orchestration/extraction-persist.ts +15 -14
  290. package/src/orchestration/recall-internal.ts +2 -3
  291. package/src/orchestration/turn-ingestion-buffered.test.ts +52 -1
  292. package/src/orchestration/turn-ingestion-buffered.ts +26 -8
  293. package/src/orchestrator.ts +1 -0
  294. package/src/recall-state-view-packet.test.ts +40 -0
  295. package/src/recall-state-view-packet.ts +46 -9
  296. package/src/source-attribution.test.ts +57 -0
  297. package/src/source-attribution.ts +46 -43
  298. package/src/storage.ts +4 -3
  299. package/src/summarizer-shutdown.test.ts +49 -16
  300. package/src/summarizer.ts +13 -5
  301. package/src/testing/subjects/memory-maintenance.test.ts +293 -0
  302. package/src/transfer/capsule-export.ts +2 -1
  303. package/src/transfer/capsule-taxonomy-version.test.ts +70 -0
  304. package/src/transfer/types.ts +13 -3
  305. package/dist/chunk-AL3TCNSJ.js.map +0 -1
  306. package/dist/chunk-BPCR5DZP.js.map +0 -1
  307. package/dist/chunk-FFWFFAP3.js.map +0 -1
  308. package/dist/chunk-FOTFLHBN.js.map +0 -1
  309. package/dist/chunk-HSSERO3E.js.map +0 -1
  310. package/dist/chunk-IE2ZLO3R.js.map +0 -1
  311. package/dist/chunk-L272A5QW.js.map +0 -1
  312. package/dist/chunk-OWM2VWNX.js.map +0 -1
  313. package/dist/chunk-QLQUAVVP.js.map +0 -1
  314. package/dist/chunk-WEHSQBFR.js.map +0 -1
  315. /package/dist/{capsule-crypto-GWVG7LGC.js.map → access-recall-excerpt-attribution.js.map} +0 -0
  316. /package/dist/{auto-sync-L3M4RKJD.js.map → auto-sync-ACP5U5A3.js.map} +0 -0
  317. /package/dist/{graph-edge-decay-BC3IO2J4.js.map → capsule-crypto-7FJQINUR.js.map} +0 -0
  318. /package/dist/{capsule-merge-VHBRF65A.js.map → capsule-merge-BADOICNP.js.map} +0 -0
  319. /package/dist/{chunk-OWHERGF2.js.map → chunk-2NLLXCJG.js.map} +0 -0
  320. /package/dist/{chunk-L7SEYUHS.js.map → chunk-3I3NXB6X.js.map} +0 -0
  321. /package/dist/{chunk-4NBUHYUV.js.map → chunk-3LADDLAF.js.map} +0 -0
  322. /package/dist/{chunk-2DL3OFLD.js.map → chunk-45GEJRIG.js.map} +0 -0
  323. /package/dist/{chunk-5BE3FLKL.js.map → chunk-5KDDAQ6K.js.map} +0 -0
  324. /package/dist/{chunk-HLWXCDUQ.js.map → chunk-63A2BU2B.js.map} +0 -0
  325. /package/dist/{chunk-C5QYWM6F.js.map → chunk-7FPI5MFB.js.map} +0 -0
  326. /package/dist/{chunk-ZX546Y3Y.js.map → chunk-7OYDFIL4.js.map} +0 -0
  327. /package/dist/{chunk-CKZWLAHN.js.map → chunk-ACPFBVUD.js.map} +0 -0
  328. /package/dist/{chunk-BKTCVXMK.js.map → chunk-AHOYKJ5X.js.map} +0 -0
  329. /package/dist/{chunk-FGT7CUYZ.js.map → chunk-ALTLOHO7.js.map} +0 -0
  330. /package/dist/{chunk-FMFCQRDM.js.map → chunk-AUFPPBC3.js.map} +0 -0
  331. /package/dist/{chunk-OAQRZ4SV.js.map → chunk-B5KTTWC7.js.map} +0 -0
  332. /package/dist/{chunk-73TPOGS4.js.map → chunk-BFBS7OFQ.js.map} +0 -0
  333. /package/dist/{chunk-QFTK6EDM.js.map → chunk-BFZFNXOC.js.map} +0 -0
  334. /package/dist/{chunk-ZQUOUPP3.js.map → chunk-BHRPZBAH.js.map} +0 -0
  335. /package/dist/{chunk-4L25GAYL.js.map → chunk-CX24SVLK.js.map} +0 -0
  336. /package/dist/{chunk-YY57TRKN.js.map → chunk-D5ZLTLHF.js.map} +0 -0
  337. /package/dist/{chunk-WEFFO2MJ.js.map → chunk-D6YCETHG.js.map} +0 -0
  338. /package/dist/{chunk-ZDZJNXL6.js.map → chunk-DK2VBJ6Q.js.map} +0 -0
  339. /package/dist/{chunk-VRHY7Y5A.js.map → chunk-DPL5VO5V.js.map} +0 -0
  340. /package/dist/{chunk-LVGTH6IQ.js.map → chunk-E7ATID4Z.js.map} +0 -0
  341. /package/dist/{chunk-CKELO7Q6.js.map → chunk-FHWX2REL.js.map} +0 -0
  342. /package/dist/{chunk-CUPILBIP.js.map → chunk-FMIM36I4.js.map} +0 -0
  343. /package/dist/{chunk-A5UOREWD.js.map → chunk-FWTGO4NE.js.map} +0 -0
  344. /package/dist/{chunk-3SL52JKD.js.map → chunk-FZVROZKC.js.map} +0 -0
  345. /package/dist/{chunk-U3BCW7GX.js.map → chunk-G3RLCVJC.js.map} +0 -0
  346. /package/dist/{chunk-UYIBNDQE.js.map → chunk-GF5NN3LE.js.map} +0 -0
  347. /package/dist/{chunk-7OCKK5M5.js.map → chunk-GWY5ZFHP.js.map} +0 -0
  348. /package/dist/{chunk-TNRGWJYT.js.map → chunk-H4IU24V5.js.map} +0 -0
  349. /package/dist/{chunk-T4BT4FQN.js.map → chunk-HH6PXQ2B.js.map} +0 -0
  350. /package/dist/{chunk-FEUWI5QH.js.map → chunk-HHPY5SSE.js.map} +0 -0
  351. /package/dist/{chunk-OM5ESBES.js.map → chunk-HQPFACXO.js.map} +0 -0
  352. /package/dist/{chunk-IMULTENA.js.map → chunk-ID65XTF3.js.map} +0 -0
  353. /package/dist/{chunk-WWQMZBDI.js.map → chunk-IJVU4ILJ.js.map} +0 -0
  354. /package/dist/{chunk-GBSXTTLP.js.map → chunk-ITGAGNX5.js.map} +0 -0
  355. /package/dist/{chunk-3PNJZTDV.js.map → chunk-JGGNUEVD.js.map} +0 -0
  356. /package/dist/{chunk-YYXYZM2I.js.map → chunk-JN7OSQJR.js.map} +0 -0
  357. /package/dist/{chunk-4D2EY4WM.js.map → chunk-K2DTHNDY.js.map} +0 -0
  358. /package/dist/{chunk-TH6OYP6I.js.map → chunk-K36RMINQ.js.map} +0 -0
  359. /package/dist/{chunk-OZKVVUJB.js.map → chunk-KIM5VNZN.js.map} +0 -0
  360. /package/dist/{chunk-ZWDDY4WF.js.map → chunk-M7CFCRWJ.js.map} +0 -0
  361. /package/dist/{chunk-QPFM6DHY.js.map → chunk-MTJFK42O.js.map} +0 -0
  362. /package/dist/{chunk-RO5EGRAI.js.map → chunk-N3FRR6II.js.map} +0 -0
  363. /package/dist/{chunk-UMEUU66X.js.map → chunk-O3OEVYUR.js.map} +0 -0
  364. /package/dist/{chunk-J74YOBB3.js.map → chunk-PFR6ZKQI.js.map} +0 -0
  365. /package/dist/{chunk-TAD6QMMD.js.map → chunk-PRC7SZYM.js.map} +0 -0
  366. /package/dist/{chunk-GMO3BGOF.js.map → chunk-QC2MHZDD.js.map} +0 -0
  367. /package/dist/{chunk-2MWKUVHT.js.map → chunk-RK7SE3BL.js.map} +0 -0
  368. /package/dist/{chunk-HDWISXFH.js.map → chunk-RVAPK2S7.js.map} +0 -0
  369. /package/dist/{chunk-5PUZV73Z.js.map → chunk-SEIGLG62.js.map} +0 -0
  370. /package/dist/{chunk-AVWOULJH.js.map → chunk-SH3GOZWK.js.map} +0 -0
  371. /package/dist/{chunk-PFLN6TTW.js.map → chunk-T3MCVSUC.js.map} +0 -0
  372. /package/dist/{chunk-WQUGCOKF.js.map → chunk-TFA6HPOA.js.map} +0 -0
  373. /package/dist/{chunk-CLVILSBR.js.map → chunk-TGQW3AMK.js.map} +0 -0
  374. /package/dist/{chunk-YZYAYUJQ.js.map → chunk-TLRIRISJ.js.map} +0 -0
  375. /package/dist/{chunk-7VIJUZYW.js.map → chunk-TQ4CELUR.js.map} +0 -0
  376. /package/dist/{chunk-5QDTZIGH.js.map → chunk-U7KP6QFU.js.map} +0 -0
  377. /package/dist/{chunk-QVXEXGIM.js.map → chunk-VF6SC4OD.js.map} +0 -0
  378. /package/dist/{chunk-EZG54YDS.js.map → chunk-VKXJQF5C.js.map} +0 -0
  379. /package/dist/{chunk-RFLC6PKQ.js.map → chunk-VMRPLHEU.js.map} +0 -0
  380. /package/dist/{chunk-U2PSE7MB.js.map → chunk-VPEIWMUT.js.map} +0 -0
  381. /package/dist/{chunk-X67XNZ64.js.map → chunk-W4EJMMPP.js.map} +0 -0
  382. /package/dist/{chunk-RB7NXZ2E.js.map → chunk-W4Q65VJL.js.map} +0 -0
  383. /package/dist/{chunk-HDDRVXX4.js.map → chunk-W5LJ3SJ7.js.map} +0 -0
  384. /package/dist/{chunk-W7N7NWG5.js.map → chunk-WCJQ3OUP.js.map} +0 -0
  385. /package/dist/{chunk-UVYI6VIX.js.map → chunk-X7Y7WX73.js.map} +0 -0
  386. /package/dist/{chunk-22V3CMIW.js.map → chunk-XJTRIHTH.js.map} +0 -0
  387. /package/dist/{chunk-SIONKXLU.js.map → chunk-XTRC6SSS.js.map} +0 -0
  388. /package/dist/{chunk-SBRUTD5O.js.map → chunk-YSATDEBY.js.map} +0 -0
  389. /package/dist/{chunk-3YOX2BQD.js.map → chunk-YWMCV5HL.js.map} +0 -0
  390. /package/dist/{chunk-6QWFZ3X5.js.map → chunk-ZA6CYFAK.js.map} +0 -0
@@ -0,0 +1,70 @@
1
+ /**
2
+ * CapsuleTaxonomySchema schemaVersion registry — issue 3572.
3
+ *
4
+ * CapsuleBlockSchema accepted any non-empty string as the capsule's taxonomy
5
+ * schemaVersion (the "free-form placeholder" hack). These tests pin the
6
+ * contract: only taxonomy versions in the known registry parse, unknown ones
7
+ * are refused with a message naming the known versions, and export with an
8
+ * unknown override fails the same way.
9
+ */
10
+
11
+ import assert from "node:assert/strict";
12
+ import test from "node:test";
13
+
14
+ import { makeTempDir } from "../testing/tmp-dir.js";
15
+ import { exportCapsule } from "./capsule-export.js";
16
+ import { CAPSULE_TAXONOMY_VERSIONS, CapsuleBlockSchema } from "./types.js";
17
+
18
+ function baseBlock() {
19
+ return {
20
+ id: "capsule-test",
21
+ version: "0.1.0",
22
+ schemaVersion: CAPSULE_TAXONOMY_VERSIONS[0],
23
+ parentCapsule: null,
24
+ parent: null,
25
+ description: "",
26
+ retrievalPolicy: { tierWeights: {}, directAnswerEnabled: false },
27
+ includes: {
28
+ taxonomy: false,
29
+ identityAnchors: false,
30
+ peerProfiles: false,
31
+ procedural: false,
32
+ },
33
+ };
34
+ }
35
+
36
+ test("known taxonomy versions parse", () => {
37
+ for (const v of CAPSULE_TAXONOMY_VERSIONS) {
38
+ const parsed = CapsuleBlockSchema.parse({ ...baseBlock(), schemaVersion: v });
39
+ assert.equal(parsed.schemaVersion, v);
40
+ }
41
+ });
42
+
43
+ test("unknown taxonomy versions are refused, naming the registry", () => {
44
+ const result = CapsuleBlockSchema.safeParse({ ...baseBlock(), schemaVersion: "taxonomy-v9" });
45
+ assert.equal(result.success, false);
46
+ if (!result.success) {
47
+ assert.match(result.error.issues[0].message, /taxonomy-v1/);
48
+ }
49
+ // Empty string stays refused too.
50
+ assert.equal(CapsuleBlockSchema.safeParse({ ...baseBlock(), schemaVersion: "" }).success, false);
51
+ });
52
+
53
+ test("export refuses an unknown schemaVersion override", async () => {
54
+ const root = await makeTempDir("cap-taxonomy-root-");
55
+ const outDir = await makeTempDir("cap-taxonomy-out-");
56
+ await assert.rejects(
57
+ exportCapsule({
58
+ name: "taxonomy-refusal-capsule",
59
+ root,
60
+ outDir,
61
+ pluginVersion: "0.0.0-test",
62
+ now: 1_700_000_000_000,
63
+ // SAFETY: the invalid literal is the point of this test; the cast
64
+ // defeats the enum's compile-time narrowing so safeParse can reject
65
+ // "taxonomy-v9" at runtime.
66
+ capsule: { schemaVersion: "taxonomy-v9" as "taxonomy-v1" },
67
+ }),
68
+ /taxonomy-v1/,
69
+ );
70
+ });
@@ -142,14 +142,24 @@ export const CapsuleParentSchema = z.object({
142
142
 
143
143
  export type CapsuleParent = z.infer<typeof CapsuleParentSchema>;
144
144
 
145
+ /**
146
+ * Known taxonomy schema versions a capsule may be authored against
147
+ * (issue 3572). Exporters must emit one of these; importers refuse anything
148
+ * else instead of silently accepting a version they cannot interpret.
149
+ */
150
+ export const CAPSULE_TAXONOMY_VERSIONS = ["taxonomy-v1"] as const;
151
+
145
152
  export const CapsuleBlockSchema = z.object({
146
153
  id: CapsuleIdSchema,
147
154
  version: SemverLikeSchema,
148
155
  /**
149
- * Taxonomy schema version the capsule was authored against. Free-form for
150
- * now; later PRs may tighten this to a known taxonomy registry.
156
+ * Taxonomy schema version the capsule was authored against. Must be a
157
+ * member of {@link CAPSULE_TAXONOMY_VERSIONS}; the error names the known
158
+ * versions so writers can pick one.
151
159
  */
152
- schemaVersion: z.string().min(1, "capsule.schemaVersion must not be empty"),
160
+ schemaVersion: z.enum(CAPSULE_TAXONOMY_VERSIONS, {
161
+ message: `capsule.schemaVersion must be one of: ${CAPSULE_TAXONOMY_VERSIONS.join(", ")}`,
162
+ }),
153
163
  /**
154
164
  * Optional reference to the parent capsule this one was forked or derived
155
165
  * from. `null` (not `undefined`) is the explicit "no parent" sentinel so
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/connectors/codex-materialize.ts","../src/connectors/materialize-paths.ts","../src/connectors/materialize-skills.ts"],"sourcesContent":["/**\n * codex-materialize.ts — Codex CLI native memory artifact materialization (#378)\n *\n * Periodically writes Remnic memories into the file layout that Codex CLI's\n * phase-2 consolidation reads directly under `<codex_home>/memories/`:\n *\n * memory_summary.md — always-loaded at session start (tight budget)\n * MEMORY.md — searchable handbook (task-group schema)\n * raw_memories.md — mechanical merge of raw memories, latest first\n * rollout_summaries/<slug>.md — per-session recaps\n *\n * Codex's own read path is agnostic to which producer wrote these files — it\n * tags reads by `memory_md` / `memory_summary` / `raw_memories` /\n * `rollout_summaries` / `skills`. By materializing Remnic content into this\n * exact layout we let Codex pick up Remnic memories without a single MCP call.\n *\n * Safety invariants\n * ─────────────────\n * - **Atomic writes.** Every file is rendered under `.remnic-tmp/` and then\n * `rename()`d into place so Codex never observes a half-written file.\n * - **Sentinel-based opt-in.** If `<codex_home>/memories/.remnic-managed` is\n * missing, we SKIP materialization entirely and log a warning. This honors\n * user hand-edits to the directory — a user who manually curated their\n * Codex memory layout will never have those edits overwritten.\n * - **Schema validation.** `MEMORY.md` content is validated against the\n * task-group schema before write. Invalid content throws and nothing is\n * written.\n * - **Idempotent no-ops.** A content hash is written into the sentinel. If\n * the re-rendered hash matches the previous run, we skip writes entirely.\n * - **Token budget.** `memory_summary.md` is truncated to fit under the\n * configured script-aware token estimate, leaving headroom under Codex's\n * 5000-token summary cap.\n *\n * Privacy\n * ───────\n * This module does not persist any user content outside `<codex_home>/memories`\n * — it only mirrors the memories that Remnic already wrote. It does not log\n * memory content to stdout; it logs file names, counts, and hashes.\n */\n\nimport {\n createHash,\n} from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { log } from \"../logger.js\";\nimport { readEnvVar, resolveHomeDir } from \"../runtime/env.js\";\nimport type { MemoryFile } from \"../types.js\";\nimport { estimateTokenCount } from \"../token-estimate.js\";\nimport type { SkillBundle } from \"../procedural/skill-projection.js\";\nimport { expandTildePath } from \"../utils/path.js\";\nimport { ensureSafeManagedSubdir } from \"./materialize-paths.js\";\nimport {\n commitSkillFiles,\n planSkillFiles,\n retiredSkillsAlreadyRemoved,\n skillFilePath,\n skillFileRelPath,\n stageSkillFiles,\n type SkillFile,\n} from \"./materialize-skills.js\";\n\n// ─── Types ─────────────────────────────────────────────────────────────────\n\n/**\n * Input for {@link materializeForNamespace}. Prefer passing pre-loaded\n * `memories` so this module stays I/O-agnostic and trivially testable.\n */\nexport interface MaterializeOptions {\n /** Pre-loaded Remnic memories for this namespace (required). */\n memories: MemoryFile[];\n /** Override `<codex_home>`. Defaults to `$CODEX_HOME` or `~/.codex`. */\n codexHome?: string;\n /** Maximum estimated token size of memory_summary.md. Default 4500. */\n maxSummaryTokens?: number;\n /** Maximum age of rollout_summaries/*.md in days. Default 30. */\n rolloutRetentionDays?: number;\n /** Per-session rollout summaries to render. */\n rolloutSummaries?: RolloutSummaryInput[];\n /**\n * Projected procedural skill bundles (issue #2369). `undefined` leaves\n * `skills/` untouched; an array — even an empty one — is authoritative for\n * the slugs Remnic projected, so retired procedures get their folder\n * removed. Folders this materializer never projected are never touched.\n */\n skills?: SkillBundle[];\n /** Current time, injected for deterministic tests. */\n now?: Date;\n /** Optional logger override for tests. */\n logger?: { info: (msg: string) => void; warn: (msg: string) => void; debug?: (msg: string) => void };\n}\n\n/** Input describing one Codex rollout summary file. */\nexport interface RolloutSummaryInput {\n /** Stable slug for the file (becomes `<slug>.md`). */\n slug: string;\n /** Working directory used during the rollout. */\n cwd?: string;\n /** Path to the raw Codex rollout log, if known. */\n rolloutPath?: string;\n /** ISO-8601 timestamp of the last update. */\n updatedAt?: string;\n /** Opaque thread / session id. */\n threadId?: string;\n /** Markdown body for the recap. */\n body: string;\n /** Freeform keywords / search hints. */\n keywords?: string[];\n}\n\n/** Result of a materialization run. */\nexport interface MaterializeResult {\n /** Namespace that was materialized. */\n namespace: string;\n /** `<codex_home>/memories` path this run targeted. */\n memoriesDir: string;\n /** Was anything actually written (vs. skipped / idempotent no-op)? */\n wrote: boolean;\n /** True if the sentinel was missing and we skipped with a warning. */\n skippedNoSentinel: boolean;\n /** True if the hash matched the previous run and we short-circuited. */\n skippedIdempotent: boolean;\n /** Files that were written this run (relative to `memoriesDir`). */\n filesWritten: string[];\n /** Content hash computed for this run. */\n contentHash: string;\n}\n\n/** On-disk shape of the `.remnic-managed` sentinel. */\ninterface SentinelFile {\n version: number;\n namespace: string;\n updated_at: string;\n content_hash: string;\n /**\n * Slugs under `skills/` that THIS materializer projected (issue #2369).\n * Absent on sentinels written before skill projection existed, which reads\n * as \"we have projected nothing\", so hand-created folders stay untouched.\n */\n projected_skills?: string[];\n}\n\n// ─── Constants ─────────────────────────────────────────────────────────────\n\n/** Bump when the on-disk layout or semantics change. */\nexport const MATERIALIZE_VERSION = 1;\n\n/** Sentinel file name at the root of the materialized memories dir. */\nexport const SENTINEL_FILE = \".remnic-managed\";\n\n/** Scratch directory used for atomic renames. */\nexport const TMP_DIR = \".remnic-tmp\";\n\n/** File names we own. Anything else in the directory is considered user-managed. */\nconst OWNED_FILES = new Set<string>([\n \"memory_summary.md\",\n \"MEMORY.md\",\n \"raw_memories.md\",\n]);\n\n/** Sub-directory for per-session rollout recaps. */\nconst ROLLOUT_SUBDIR = \"rollout_summaries\";\n\n// ─── Public entry points ───────────────────────────────────────────────────\n\n/**\n * Materialize a Remnic namespace into Codex's native memory layout.\n *\n * Returns a {@link MaterializeResult} describing what happened. Callers\n * should treat \"skipped\" as success — the sentinel / idempotent cases are\n * expected and intentional.\n *\n * @throws if `MEMORY.md` fails schema validation (we do not write garbage).\n */\nexport function materializeForNamespace(\n namespace: string,\n options: MaterializeOptions,\n): MaterializeResult {\n const logger = options.logger ?? {\n info: (msg) => log.info(`[codex-materialize] ${msg}`),\n warn: (msg) => log.warn(`[codex-materialize] ${msg}`),\n debug: (msg) => log.debug(`[codex-materialize] ${msg}`),\n };\n const memoriesDir = resolveCodexMemoriesDir(options.codexHome);\n const now = options.now ?? new Date();\n // Honor `0` as \"no summary budget\" — parseConfig already clamps to non-\n // negative integers, so any provided number is meaningful. Only fall back\n // to the default when the caller did not provide the option at all.\n const maxSummaryTokens =\n typeof options.maxSummaryTokens === \"number\" && options.maxSummaryTokens >= 0\n ? options.maxSummaryTokens\n : 4500;\n const rolloutRetentionDays =\n typeof options.rolloutRetentionDays === \"number\" && options.rolloutRetentionDays >= 0\n ? options.rolloutRetentionDays\n : 30;\n\n // ── Sentinel check ─────────────────────────────────────────────────────\n // We deliberately do NOT `mkdirSync(memoriesDir)` before reading the\n // sentinel: creating `~/.codex/memories/` for every user (including ones\n // who never use Codex) would make Remnic's post-consolidation hook leave\n // empty opt-in directories behind on disk. Instead we only check whether\n // the sentinel already exists — if the parent dir doesn't exist, the\n // sentinel can't exist either and we fall straight through to the skip\n // path without touching the filesystem. The `mkdirSync` for `memoriesDir`\n // happens later, only once we know we're actually going to write.\n const sentinelPath = path.join(memoriesDir, SENTINEL_FILE);\n const existingSentinel = readSentinel(sentinelPath);\n if (!existingSentinel) {\n // Log at `debug` when the entire memories dir doesn't exist — that's\n // the common \"user never opted in\" case and should not be noisy.\n // Keep the `warn` level only when the dir exists but lacks a sentinel,\n // which is the \"user hand-curated layout, don't overwrite\" case that\n // genuinely warrants attention.\n if (fs.existsSync(memoriesDir)) {\n logger.warn(\n `sentinel ${SENTINEL_FILE} missing in ${memoriesDir}; skipping materialization to preserve hand-edits`,\n );\n } else {\n logger.debug?.(\n `skipping materialization — ${memoriesDir} does not exist (user not opted in)`,\n );\n }\n return {\n namespace,\n memoriesDir,\n wrote: false,\n skippedNoSentinel: true,\n skippedIdempotent: false,\n filesWritten: [],\n contentHash: \"\",\n };\n }\n\n // Now that we know the user has opted in (sentinel exists), it's safe to\n // ensure the memories dir is present. In practice this is almost always a\n // no-op because the sentinel read above already succeeded, but a defensive\n // mkdirSync protects against a race where the dir was removed between the\n // sentinel read and the first write.\n fs.mkdirSync(memoriesDir, { recursive: true });\n\n // ── Render ─────────────────────────────────────────────────────────────\n const memories = [...options.memories];\n // Track whether the caller actually supplied a rollout set. `undefined`\n // means \"don't touch rollout_summaries/\"; an empty array is still\n // authoritative and means \"we own this dir and it should be empty\".\n const rolloutsSupplied = options.rolloutSummaries !== undefined;\n const rolloutSummaries = options.rolloutSummaries ?? [];\n\n // Prune-before-render: MEMORY.md and memory_summary.md both embed rollout\n // filenames in their body, so they must only ever see the *retained* set.\n // Running pruneRollouts after the renderers (as an earlier revision did)\n // caused MEMORY.md to list `rollout_summaries/<slug>.md` paths for rollouts\n // that were then pruned and never written — a broken link pointing at a\n // ghost file. See review feedback on PR #392.\n const retainedRollouts = pruneRollouts(rolloutSummaries, rolloutRetentionDays, now);\n\n // Deduplicate on sanitized filename. Two different slugs (\"Session 1\" and\n // \"session!!!1\") can sanitize to the same output (\"session-1\"), which would\n // otherwise make the first entry's tmp file get overwritten and cause the\n // later rename step to crash with ENOENT. For each collision slot we keep\n // the entry with the newest `updatedAt` so an unsorted input (or a caller\n // that accidentally appends older recaps after newer ones) can't have an\n // older recap clobber a newer one.\n // We do this at the retained-input level (not just at the written-file\n // level) so MEMORY.md's \"rollout_summary_files\" section lists each slot\n // exactly once and matches what actually gets written to disk.\n const dedupedRollouts: RolloutSummaryInput[] = [];\n const seenNames = new Map<string, number>();\n const parseTs = (value: string | undefined): number => {\n if (!value) return Number.NEGATIVE_INFINITY;\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : Number.NEGATIVE_INFINITY;\n };\n for (const r of retainedRollouts) {\n const name = `${sanitizeSlug(r.slug)}.md`;\n const existingIdx = seenNames.get(name);\n if (existingIdx === undefined) {\n seenNames.set(name, dedupedRollouts.length);\n dedupedRollouts.push(r);\n continue;\n }\n // Newest-wins: only replace the existing entry if the incoming one has a\n // strictly newer timestamp. Ties keep the earlier entry (stable for\n // unsorted inputs) because overwriting on ties would flip rendering output\n // for benign call-order changes.\n const existing = dedupedRollouts[existingIdx];\n if (parseTs(r.updatedAt) > parseTs(existing.updatedAt)) {\n dedupedRollouts[existingIdx] = r;\n }\n }\n\n const memorySummary = renderMemorySummary({\n namespace,\n memories,\n rolloutSummaries: dedupedRollouts,\n maxTokens: maxSummaryTokens,\n });\n\n const memoryMd = renderMemoryMd({\n namespace,\n memories,\n rolloutSummaries: dedupedRollouts,\n });\n\n // Fail fast on schema issues — do not write garbage.\n const validation = validateMemoryMd(memoryMd);\n if (!validation.valid) {\n const reason = validation.errors.join(\"; \");\n logger.warn(`MEMORY.md failed schema validation: ${reason}`);\n throw new Error(`codex-materialize: MEMORY.md schema validation failed: ${reason}`);\n }\n\n const rawMemories = renderRawMemories({ memories });\n\n const rolloutFiles = dedupedRollouts.map((r) => ({\n name: `${sanitizeSlug(r.slug)}.md`,\n body: renderRolloutSummary(r),\n }));\n const destRolloutsDir = path.join(memoriesDir, ROLLOUT_SUBDIR);\n const retainedRolloutNames = new Set(rolloutFiles.map((r) => r.name));\n\n // Skill bundles (issue #2369) — planning, ownership, and disk layout live in\n // materialize-skills.ts.\n const skillPlan = planSkillFiles(options.skills, existingSentinel.projected_skills ?? []);\n\n // ── Idempotence check ──────────────────────────────────────────────────\n const hash = computeContentHash({\n namespace,\n memorySummary,\n memoryMd,\n rawMemories,\n rolloutFiles,\n skillFiles: skillPlan.files,\n });\n\n if (existingSentinel.content_hash === hash) {\n // Idempotence early-return is only safe when the managed files we would\n // have written are still on disk. If a user or external process deleted\n // `MEMORY.md` / `memory_summary.md` / `raw_memories.md` (or any retained\n // rollout file) while the sentinel's hash stayed the same, we must fall\n // through and rewrite — otherwise Codex would be stuck with missing\n // artifacts until a memory-content change happens to flip the hash.\n const requiredFiles = [\n path.join(memoriesDir, \"memory_summary.md\"),\n path.join(memoriesDir, \"MEMORY.md\"),\n path.join(memoriesDir, \"raw_memories.md\"),\n ...rolloutFiles.map((r) => path.join(memoriesDir, ROLLOUT_SUBDIR, r.name)),\n ...skillPlan.files.map((s) => skillFilePath(memoriesDir, s.slug)),\n ];\n const allPresent = requiredFiles.every((f) => fs.existsSync(f));\n const rolloutsClean =\n !rolloutsSupplied ||\n rolloutDirectoryMatchesRetainedSet(\n ensureSafeManagedSubdir(memoriesDir, destRolloutsDir, ROLLOUT_SUBDIR),\n retainedRolloutNames,\n );\n const skillsClean = retiredSkillsAlreadyRemoved(memoriesDir, skillPlan.retiredSlugs);\n if (allPresent && rolloutsClean && skillsClean) {\n logger.debug?.(`no-op materialization for namespace=${namespace} (hash unchanged)`);\n return {\n namespace,\n memoriesDir,\n wrote: false,\n skippedNoSentinel: false,\n skippedIdempotent: true,\n filesWritten: [],\n contentHash: hash,\n };\n }\n logger.debug?.(\n `hash unchanged for namespace=${namespace} but managed files need refresh — forcing rewrite`,\n );\n }\n\n // ── Atomic writes ──────────────────────────────────────────────────────\n // Use a unique, per-run staging sub-directory so two overlapping runs\n // (e.g. a session-end trigger overlapping with a consolidation post-hook)\n // can't stomp each other's tmp files mid-rename. The old \"fixed TMP_DIR,\n // wipe-on-entry\" layout meant run B would delete run A's staging area out\n // from under it, causing ENOENT on A's rename loop. Per-run uniqueness\n // turns the shared dir into an insulated workspace. See review feedback on\n // PR #392.\n const runTag = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n const tmpDir = path.join(memoriesDir, `${TMP_DIR}-${runTag}`);\n // Opportunistic GC for stale scratch dirs left behind by a previous\n // crashed run. We only remove entries whose mtime is older than the\n // stale-threshold below — that way we never delete another in-flight\n // run's staging area out from under it. The threshold is deliberately\n // generous (1h) because a healthy materialize completes in milliseconds\n // and there's no legitimate reason for a live staging dir to be older.\n //\n // NB: we compare against `Date.now()` (wall-clock), not against the\n // injected `options.now`. Tests and deterministic replays commonly\n // inject a non-current timestamp, but file mtimes on disk are always\n // wall-clock, so mixing the two would either false-positive delete\n // fresh dirs (test-time in the past) or false-negative skip stale ones\n // (test-time in the future).\n const TMP_STALE_MS = 60 * 60 * 1000;\n const wallClockMs = Date.now();\n try {\n for (const entry of fs.readdirSync(memoriesDir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n if (!entry.name.startsWith(TMP_DIR)) continue;\n const stalePath = path.join(memoriesDir, entry.name);\n try {\n const stat = fs.statSync(stalePath);\n if (wallClockMs - stat.mtimeMs < TMP_STALE_MS) continue;\n fs.rmSync(stalePath, { recursive: true, force: true });\n } catch {\n // ignore — another concurrent run may own it, or we lack perms\n }\n }\n } catch {\n // ignore — dir may not exist yet\n }\n fs.mkdirSync(tmpDir, { recursive: true });\n fs.mkdirSync(path.join(tmpDir, ROLLOUT_SUBDIR), { recursive: true });\n\n const filesWritten: string[] = [];\n\n fs.writeFileSync(path.join(tmpDir, \"memory_summary.md\"), memorySummary);\n filesWritten.push(\"memory_summary.md\");\n\n fs.writeFileSync(path.join(tmpDir, \"MEMORY.md\"), memoryMd);\n filesWritten.push(\"MEMORY.md\");\n\n fs.writeFileSync(path.join(tmpDir, \"raw_memories.md\"), rawMemories);\n filesWritten.push(\"raw_memories.md\");\n\n for (const rollout of rolloutFiles) {\n fs.writeFileSync(path.join(tmpDir, ROLLOUT_SUBDIR, rollout.name), rollout.body);\n filesWritten.push(path.join(ROLLOUT_SUBDIR, rollout.name));\n }\n\n stageSkillFiles(tmpDir, skillPlan.files);\n for (const skill of skillPlan.files) {\n filesWritten.push(skillFileRelPath(skill.slug));\n }\n\n // Rename into place. Atomic per-file is sufficient — Codex reads each file\n // independently and tolerates an inconsistent in-between snapshot across\n // files for the duration of the rename loop (milliseconds).\n for (const rel of [\"memory_summary.md\", \"MEMORY.md\", \"raw_memories.md\"]) {\n const src = path.join(tmpDir, rel);\n const dest = path.join(memoriesDir, rel);\n fs.renameSync(src, dest);\n }\n\n const safeDestRolloutsDir = ensureSafeManagedSubdir(memoriesDir, destRolloutsDir, ROLLOUT_SUBDIR);\n // Only garbage-collect rollout files when the caller actually supplied a\n // `rolloutSummaries` array — otherwise we'd wipe legitimately\n // user/Codex-created recap files on every session-end run, since those\n // calls typically omit the rollout set entirely. When rollouts were\n // supplied (even as an empty array — meaning \"we own this dir and it\n // should be empty\"), we clear the stale files we previously owned.\n if (rolloutsSupplied) {\n let existingRollouts: fs.Dirent[];\n try {\n existingRollouts = fs.readdirSync(safeDestRolloutsDir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n existingRollouts = [];\n }\n for (const entry of existingRollouts) {\n if (!entry.isFile()) continue;\n if (!entry.name.endsWith(\".md\")) continue;\n if (retainedRolloutNames.has(entry.name)) continue;\n try {\n fs.unlinkSync(path.join(safeDestRolloutsDir, entry.name));\n } catch (err) {\n throw new Error(\n `codex-materialize: failed to prune stale rollout summary ${entry.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n }\n\n for (const rollout of rolloutFiles) {\n const src = path.join(tmpDir, ROLLOUT_SUBDIR, rollout.name);\n const dest = path.join(safeDestRolloutsDir, rollout.name);\n fs.renameSync(src, dest);\n }\n\n commitSkillFiles(memoriesDir, tmpDir, skillPlan);\n\n // Update sentinel last so a crash leaves hash mismatched → next run rewrites.\n const sentinel: SentinelFile = {\n version: MATERIALIZE_VERSION,\n namespace,\n updated_at: now.toISOString(),\n content_hash: hash,\n projected_skills: skillPlan.supplied\n ? skillPlan.files.map((s) => s.slug)\n : (existingSentinel.projected_skills ?? []),\n };\n writeSentinelAtomically(sentinelPath, sentinel);\n\n try {\n fs.rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // ignore\n }\n\n logger.info(\n `materialized namespace=${namespace} files=${filesWritten.length} hash=${hash.slice(0, 12)}`,\n );\n\n return {\n namespace,\n memoriesDir,\n wrote: true,\n skippedNoSentinel: false,\n skippedIdempotent: false,\n filesWritten,\n contentHash: hash,\n };\n}\n\n/**\n * Create (or refresh) the `.remnic-managed` sentinel. Callers must do this\n * explicitly the first time they want Remnic to start managing a directory —\n * we never write it implicitly, because its presence is the user's opt-in.\n */\nexport function ensureSentinel(memoriesDir: string, namespace: string, now: Date = new Date()): void {\n fs.mkdirSync(memoriesDir, { recursive: true });\n const sentinelPath = path.join(memoriesDir, SENTINEL_FILE);\n if (fs.existsSync(sentinelPath)) {\n readSentinel(sentinelPath);\n return;\n }\n const sentinel: SentinelFile = {\n version: MATERIALIZE_VERSION,\n namespace,\n updated_at: now.toISOString(),\n content_hash: \"\",\n };\n writeSentinelAtomically(sentinelPath, sentinel);\n}\n\n// ─── Rendering ─────────────────────────────────────────────────────────────\n\ninterface RenderContext {\n namespace: string;\n memories: MemoryFile[];\n rolloutSummaries: RolloutSummaryInput[];\n // Historically this interface exposed a `now: Date` field, but neither\n // `renderMemoryMd` nor `renderMemorySummary` ever read it (rendered output\n // is purely a function of `namespace`, `memories`, and `rolloutSummaries`).\n // The field was flagged as dead weight in PR #392 review and removed.\n // If a future renderer needs a timestamp, re-add it here and update both\n // call sites and the schema test.\n}\n\ninterface SummaryRenderContext extends RenderContext {\n maxTokens: number;\n}\n\n/**\n * Render `memory_summary.md` — the always-loaded file.\n * Budget-capped at `maxTokens` whitespace tokens.\n */\nexport function renderMemorySummary(ctx: SummaryRenderContext): string {\n const lines: string[] = [];\n lines.push(\"# Memory Summary\");\n lines.push(\"\");\n lines.push(`_namespace: ${ctx.namespace}_`);\n lines.push(`_source: remnic_`);\n lines.push(\"\");\n\n const highValue = selectSummaryMemories(ctx.memories, 12);\n if (highValue.length > 0) {\n lines.push(\"## Top memories\");\n lines.push(\"\");\n for (const mem of highValue) {\n lines.push(`- ${oneLineSummary(mem)}`);\n }\n lines.push(\"\");\n }\n\n if (ctx.rolloutSummaries.length > 0) {\n lines.push(\"## Recent rollouts\");\n lines.push(\"\");\n const sorted = [...ctx.rolloutSummaries]\n .sort((a, b) => (b.updatedAt ?? \"\").localeCompare(a.updatedAt ?? \"\"))\n .slice(0, 5);\n for (const r of sorted) {\n const when = r.updatedAt ? ` (${r.updatedAt})` : \"\";\n lines.push(`- ${r.slug}${when}`);\n }\n lines.push(\"\");\n }\n\n // Collapse trailing newlines to one without the anchored /\\n+$/ quantifier,\n // which backtracks polynomially (CodeQL js/polynomial-redos).\n const joined = lines.join(\"\\n\");\n let joinedEnd = joined.length;\n while (joinedEnd > 0 && joined[joinedEnd - 1] === \"\\n\") joinedEnd--;\n const full = joinedEnd === joined.length ? joined : `${joined.slice(0, joinedEnd)}\\n`;\n return truncateToTokenBudget(full, ctx.maxTokens);\n}\n\n/**\n * Render `MEMORY.md` — the searchable handbook in Codex's task-group schema.\n */\nexport function renderMemoryMd(ctx: RenderContext): string {\n const lines: string[] = [];\n lines.push(`# Task Group: ${ctx.namespace}`);\n lines.push(`scope: ${ctx.namespace}`);\n lines.push(`applies_to: cwd=*; reuse_rule=namespace-match`);\n lines.push(\"\");\n\n // One \"task\" per top-level topic cluster. For the first cut we group by\n // memory category so the schema validator always sees at least one task.\n const byCategory = groupMemoriesByCategory(ctx.memories);\n let taskIndex = 1;\n if (byCategory.size === 0) {\n lines.push(`## Task ${taskIndex}: baseline — no memories yet`);\n lines.push(\"\");\n lines.push(\"### rollout_summary_files\");\n for (const r of ctx.rolloutSummaries) {\n lines.push(\n `- rollout_summaries/${sanitizeSlug(r.slug)}.md (cwd=${r.cwd ?? \"*\"}, rollout_path=${r.rolloutPath ?? \"\"}, updated_at=${r.updatedAt ?? \"\"}, thread_id=${r.threadId ?? \"\"})`,\n );\n }\n if (ctx.rolloutSummaries.length === 0) {\n lines.push(\"- (none)\");\n }\n lines.push(\"\");\n lines.push(\"### keywords\");\n lines.push(`- ${ctx.namespace}`);\n lines.push(\"\");\n taskIndex += 1;\n } else {\n for (const [category, mems] of byCategory) {\n lines.push(`## Task ${taskIndex}: ${category} memories, outcome=surface-to-codex`);\n lines.push(\"\");\n lines.push(\"### rollout_summary_files\");\n const relevantRollouts = ctx.rolloutSummaries.slice(0, 5);\n if (relevantRollouts.length === 0) {\n lines.push(\"- (none)\");\n } else {\n for (const r of relevantRollouts) {\n lines.push(\n `- rollout_summaries/${sanitizeSlug(r.slug)}.md (cwd=${r.cwd ?? \"*\"}, rollout_path=${r.rolloutPath ?? \"\"}, updated_at=${r.updatedAt ?? \"\"}, thread_id=${r.threadId ?? \"\"})`,\n );\n }\n }\n lines.push(\"\");\n lines.push(\"### keywords\");\n const keywords = collectKeywords(mems, category, ctx.namespace);\n lines.push(`- ${keywords.join(\", \")}`);\n lines.push(\"\");\n taskIndex += 1;\n }\n }\n\n lines.push(\"## User preferences\");\n const prefs = pickCategory(ctx.memories, [\"preference\"]);\n if (prefs.length === 0) {\n lines.push(\"- (none recorded)\");\n } else {\n for (const pref of prefs.slice(0, 20)) {\n lines.push(`- ${oneLineSummary(pref)}`);\n }\n }\n lines.push(\"\");\n\n lines.push(\"## Reusable knowledge\");\n const knowledge = pickCategory(ctx.memories, [\"fact\", \"decision\", \"principle\", \"rule\", \"skill\"]);\n if (knowledge.length === 0) {\n lines.push(\"- (none recorded)\");\n } else {\n for (const mem of knowledge.slice(0, 30)) {\n lines.push(`- ${oneLineSummary(mem)}`);\n }\n }\n lines.push(\"\");\n\n lines.push(\"## Failures and how to do differently\");\n const corrections = pickCategory(ctx.memories, [\"correction\"]);\n if (corrections.length === 0) {\n lines.push(\"- (none recorded)\");\n } else {\n for (const mem of corrections.slice(0, 20)) {\n lines.push(`- ${oneLineSummary(mem)}`);\n }\n }\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n\n/** Render `raw_memories.md` — mechanical dump, latest first. */\nexport function renderRawMemories(ctx: { memories: MemoryFile[] }): string {\n const sorted = [...ctx.memories].sort((a, b) => {\n const aUpdated = a.frontmatter.updated ?? a.frontmatter.created ?? \"\";\n const bUpdated = b.frontmatter.updated ?? b.frontmatter.created ?? \"\";\n return bUpdated.localeCompare(aUpdated);\n });\n\n const lines: string[] = [\"# Raw Memories\", \"\", \"_source: remnic — latest first_\", \"\"];\n for (const mem of sorted) {\n const fm = mem.frontmatter;\n const id = fm.id ?? \"unknown\";\n const category = fm.category ?? \"unknown\";\n const updated = fm.updated ?? fm.created ?? \"\";\n lines.push(`## ${id} (${category}, updated=${updated})`);\n lines.push(\"\");\n lines.push(mem.content.trim());\n lines.push(\"\");\n }\n return lines.join(\"\\n\");\n}\n\n/** Render a single rollout summary file. */\nexport function renderRolloutSummary(input: RolloutSummaryInput): string {\n const lines: string[] = [];\n lines.push(`# Rollout Summary: ${input.slug}`);\n lines.push(\"\");\n const meta: string[] = [];\n if (input.cwd) meta.push(`cwd=${input.cwd}`);\n if (input.rolloutPath) meta.push(`rollout_path=${input.rolloutPath}`);\n if (input.updatedAt) meta.push(`updated_at=${input.updatedAt}`);\n if (input.threadId) meta.push(`thread_id=${input.threadId}`);\n if (meta.length > 0) {\n lines.push(`_${meta.join(\"; \")}_`);\n lines.push(\"\");\n }\n if (input.keywords && input.keywords.length > 0) {\n lines.push(`**keywords:** ${input.keywords.join(\", \")}`);\n lines.push(\"\");\n }\n lines.push(input.body.trim());\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ─── Schema validation ─────────────────────────────────────────────────────\n\nexport interface MemoryMdValidation {\n valid: boolean;\n errors: string[];\n}\n\n/**\n * Validate that a rendered `MEMORY.md` matches Codex's task-group schema.\n * We enforce the minimum set of structural requirements called out in #378:\n *\n * - one `# Task Group:` header\n * - `scope:` and `applies_to:` lines directly beneath it\n * - at least one `## Task N:` section\n * - each task section has `### rollout_summary_files` and `### keywords`\n * - `## User preferences`, `## Reusable knowledge`,\n * `## Failures and how to do differently` sections all present\n */\nexport function validateMemoryMd(content: string): MemoryMdValidation {\n const errors: string[] = [];\n const lines = content.split(/\\r?\\n/u);\n\n const taskGroupIndex = lines.findIndex((l) => /^#\\s+Task Group:\\s+\\S+/u.test(l));\n if (taskGroupIndex === -1) {\n errors.push(\"missing `# Task Group:` header\");\n } else {\n const tail = lines.slice(taskGroupIndex + 1, taskGroupIndex + 5);\n if (!tail.some((l) => /^scope:\\s*\\S+/u.test(l))) {\n errors.push(\"missing `scope:` line under Task Group header\");\n }\n if (!tail.some((l) => /^applies_to:\\s*\\S+/u.test(l))) {\n errors.push(\"missing `applies_to:` line under Task Group header\");\n }\n }\n\n const taskHeaders = lines.filter((l) => /^##\\s+Task\\s+\\d+:/u.test(l));\n if (taskHeaders.length === 0) {\n errors.push(\"at least one `## Task N:` section is required\");\n }\n\n // For every task section, make sure we have rollout_summary_files + keywords\n // before the next `##` header at the same level.\n const sectionRegex = /^##\\s+/u;\n for (let i = 0; i < lines.length; i++) {\n if (!/^##\\s+Task\\s+\\d+:/u.test(lines[i])) continue;\n let hasRollout = false;\n let hasKeywords = false;\n for (let j = i + 1; j < lines.length; j++) {\n if (sectionRegex.test(lines[j])) break;\n if (/^###\\s+rollout_summary_files\\s*$/u.test(lines[j])) hasRollout = true;\n if (/^###\\s+keywords\\s*$/u.test(lines[j])) hasKeywords = true;\n }\n if (!hasRollout) errors.push(`task block at line ${i + 1} missing \\`### rollout_summary_files\\``);\n if (!hasKeywords) errors.push(`task block at line ${i + 1} missing \\`### keywords\\``);\n }\n\n const requiredSections = [\n /^##\\s+User preferences\\s*$/u,\n /^##\\s+Reusable knowledge\\s*$/u,\n /^##\\s+Failures and how to do differently\\s*$/u,\n ];\n for (const re of requiredSections) {\n if (!lines.some((l) => re.test(l))) {\n errors.push(`missing required section: ${re.source}`);\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────────\n\nfunction resolveCodexHome(override?: string): string {\n if (override && override.trim().length > 0) {\n return path.resolve(expandTildePath(override.trim()));\n }\n const fromEnv = readEnvVar(\"CODEX_HOME\");\n if (fromEnv && fromEnv.trim().length > 0) {\n return path.resolve(expandTildePath(fromEnv.trim()));\n }\n return path.resolve(resolveHomeDir(), \".codex\");\n}\n\nexport function resolveCodexMemoriesDir(codexHome?: string): string {\n return path.join(resolveCodexHome(codexHome), \"memories\");\n}\n\nexport function hasCodexMaterializeSentinel(codexHome?: string): boolean {\n return readSentinel(path.join(resolveCodexMemoriesDir(codexHome), SENTINEL_FILE)) !== null;\n}\n\nfunction rolloutDirectoryMatchesRetainedSet(\n rolloutsDir: string,\n retainedNames: Set<string>,\n): boolean {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(rolloutsDir, { withFileTypes: true });\n } catch {\n return retainedNames.size === 0;\n }\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n if (!entry.name.endsWith(\".md\")) continue;\n if (!retainedNames.has(entry.name)) return false;\n }\n return true;\n}\n\nfunction readSentinel(sentinelPath: string): SentinelFile | null {\n if (!fs.existsSync(sentinelPath)) return null;\n try {\n const raw = fs.readFileSync(sentinelPath, \"utf-8\");\n const parsed = JSON.parse(raw) as Partial<SentinelFile>;\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n typeof parsed.version !== \"number\" ||\n typeof parsed.namespace !== \"string\" ||\n typeof parsed.updated_at !== \"string\" ||\n typeof parsed.content_hash !== \"string\"\n ) {\n throw new Error(\"invalid sentinel schema\");\n }\n // A sentinel written before issue #2369 has no `projected_skills`, which\n // reads as \"nothing projected\" — so an unrelated skills/ folder written by\n // a user or another tool is never treated as ours.\n const projected = Array.isArray(parsed.projected_skills)\n ? parsed.projected_skills.filter((slug): slug is string => typeof slug === \"string\")\n : [];\n return {\n version: parsed.version,\n namespace: parsed.namespace,\n updated_at: parsed.updated_at,\n content_hash: parsed.content_hash,\n projected_skills: projected,\n };\n } catch (err) {\n throw new Error(\n `codex-materialize: corrupt ${SENTINEL_FILE} sentinel at ${sentinelPath}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n}\n\nfunction writeSentinelAtomically(\n sentinelPath: string,\n sentinel: SentinelFile,\n): void {\n const tmpPath = `${sentinelPath}.${process.pid}.${Date.now()}.${Math.random()\n .toString(16)\n .slice(2)}.tmp`;\n try {\n fs.writeFileSync(tmpPath, `${JSON.stringify(sentinel, null, 2)}\\n`, {\n flag: \"wx\",\n });\n fs.renameSync(tmpPath, sentinelPath);\n } catch (err) {\n try {\n fs.rmSync(tmpPath, { force: true });\n } catch {\n // ignore cleanup failures; preserve the original write/rename error\n }\n throw err;\n }\n}\n\nfunction selectSummaryMemories(memories: MemoryFile[], limit: number): MemoryFile[] {\n const scored = memories\n .filter((m) => !m.frontmatter.status || m.frontmatter.status === \"active\")\n .map((m) => {\n const confidence = typeof m.frontmatter.confidence === \"number\" ? m.frontmatter.confidence : 0;\n const importance =\n typeof m.frontmatter.importance === \"object\" &&\n m.frontmatter.importance !== null &&\n typeof (m.frontmatter.importance as { score?: number }).score === \"number\"\n ? ((m.frontmatter.importance as { score: number }).score ?? 0)\n : 0;\n const updated = m.frontmatter.updated ?? m.frontmatter.created ?? \"\";\n return { memory: m, score: importance * 2 + confidence, updated };\n });\n\n scored.sort((a, b) => {\n if (b.score !== a.score) return b.score - a.score;\n return b.updated.localeCompare(a.updated);\n });\n\n return scored.slice(0, limit).map((s) => s.memory);\n}\n\nfunction oneLineSummary(memory: MemoryFile): string {\n const raw = memory.content.replace(/\\s+/gu, \" \").trim();\n if (raw.length <= 160) return raw;\n return `${raw.slice(0, 157)}...`;\n}\n\nfunction groupMemoriesByCategory(memories: MemoryFile[]): Map<string, MemoryFile[]> {\n const map = new Map<string, MemoryFile[]>();\n for (const memory of memories) {\n if (memory.frontmatter.status && memory.frontmatter.status !== \"active\") continue;\n const category = memory.frontmatter.category ?? \"unknown\";\n const list = map.get(category) ?? [];\n list.push(memory);\n map.set(category, list);\n }\n return map;\n}\n\nfunction pickCategory(memories: MemoryFile[], categories: string[]): MemoryFile[] {\n const allowed = new Set(categories);\n return memories.filter(\n (m) =>\n (!m.frontmatter.status || m.frontmatter.status === \"active\") &&\n allowed.has(m.frontmatter.category ?? \"\"),\n );\n}\n\nfunction collectKeywords(memories: MemoryFile[], category: string, namespace: string): string[] {\n const keywords = new Set<string>();\n keywords.add(category);\n keywords.add(namespace);\n for (const mem of memories.slice(0, 10)) {\n for (const tag of mem.frontmatter.tags ?? []) {\n if (typeof tag === \"string\" && tag.trim().length > 0) keywords.add(tag.trim());\n }\n }\n return [...keywords].slice(0, 16);\n}\n\nfunction pruneRollouts(\n rollouts: RolloutSummaryInput[],\n retentionDays: number,\n now: Date,\n): RolloutSummaryInput[] {\n // Negative retention → \"infinite retention\" escape hatch. `parseConfig`\n // clamps the knob to >= 0, so in practice only callers passing a negative\n // value intentionally get the all-pass behavior.\n if (retentionDays < 0) return rollouts;\n // retentionDays === 0 → cutoff is exactly `now`, which prunes every\n // rollout whose `updatedAt` is in the past (i.e. all of them in practice).\n // This matches the documented semantics of \"retain for 0 days\".\n const cutoffMs = now.getTime() - retentionDays * 24 * 60 * 60 * 1000;\n return rollouts.filter((r) => {\n if (!r.updatedAt) return true;\n const t = Date.parse(r.updatedAt);\n if (!Number.isFinite(t)) return true;\n return t >= cutoffMs;\n });\n}\n\nfunction sanitizeSlug(slug: string): string {\n const sanitized = slug\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/gu, \"-\")\n .slice(0, 96);\n const trimmed = trimHyphenEdges(sanitized);\n return trimmed || \"rollout\";\n}\n\nfunction trimHyphenEdges(value: string): string {\n let start = 0;\n let end = value.length;\n while (start < end && value[start] === \"-\") start += 1;\n while (end > start && value[end - 1] === \"-\") end -= 1;\n return value.slice(start, end);\n}\n/** Shared script-aware approximation used by the budget check. */\nexport function approximateTokenCount(text: string): number {\n return estimateTokenCount(text);\n}\n\n/**\n * Truncate `text` so it fits under `maxTokens`. We drop trailing lines until\n * under budget, then append a marker so readers can see that truncation occurred.\n */\nexport function truncateToTokenBudget(text: string, maxTokens: number): string {\n if (maxTokens <= 0) return \"\";\n if (approximateTokenCount(text) <= maxTokens) return text;\n\n const lineMarker = \"_[truncated for summary budget]_\";\n const tailMarker = \"[truncated]\";\n if (approximateTokenCount(tailMarker) > maxTokens) return \"\";\n const lineMarkerTokens = approximateTokenCount(lineMarker);\n\n const lines = text.split(/\\r?\\n/u);\n const lineBudget = Math.max(0, maxTokens - lineMarkerTokens);\n while (lines.length > 0 && approximateTokenCount(lines.join(\"\\n\")) > lineBudget) {\n lines.pop();\n }\n lines.push(lineMarker);\n let result = lines.join(\"\\n\");\n\n if (approximateTokenCount(result) > maxTokens) {\n const codePoints = [...result];\n let low = 0;\n let high = codePoints.length;\n while (low < high) {\n const mid = Math.ceil((low + high) / 2);\n const prefix = codePoints.slice(0, mid).join(\"\");\n const candidate = prefix.length > 0 ? `${prefix} ${tailMarker}` : tailMarker;\n if (approximateTokenCount(candidate) <= maxTokens) low = mid;\n else high = mid - 1;\n }\n const prefix = codePoints.slice(0, low).join(\"\");\n result = prefix.length > 0 ? `${prefix} ${tailMarker}` : tailMarker;\n }\n return result;\n}\n\nfunction computeContentHash(input: {\n namespace: string;\n memorySummary: string;\n memoryMd: string;\n rawMemories: string;\n rolloutFiles: Array<{ name: string; body: string }>;\n skillFiles: Array<{ slug: string; body: string }>;\n}): string {\n const hash = createHash(\"sha256\");\n hash.update(`v${MATERIALIZE_VERSION}\\n`);\n hash.update(`namespace=${input.namespace}\\n`);\n hash.update(\"---memory_summary---\\n\");\n hash.update(input.memorySummary);\n hash.update(\"\\n---memory_md---\\n\");\n hash.update(input.memoryMd);\n hash.update(\"\\n---raw_memories---\\n\");\n hash.update(input.rawMemories);\n const sortedRollouts = [...input.rolloutFiles].sort((a, b) => a.name.localeCompare(b.name));\n for (const r of sortedRollouts) {\n hash.update(`\\n---rollout:${r.name}---\\n`);\n hash.update(r.body);\n }\n // Sorted by slug so call order cannot flip the hash (§26).\n const sortedSkills = [...input.skillFiles].sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));\n for (const s of sortedSkills) {\n hash.update(`\\n---skill:${s.slug}---\\n`);\n hash.update(s.body);\n }\n return hash.digest(\"hex\");\n}\n\n// ─── Stat helper for tests / debugging ─────────────────────────────────────\n\n/**\n * Return basic stats about a materialized memories dir. Useful for tests and\n * debug CLI output. Returns `null` if the dir does not exist.\n */\nexport function describeMemoriesDir(memoriesDir: string): {\n exists: boolean;\n hasSentinel: boolean;\n files: string[];\n sentinel: SentinelFile | null;\n} | null {\n if (!fs.existsSync(memoriesDir)) return null;\n const sentinelPath = path.join(memoriesDir, SENTINEL_FILE);\n const sentinel = readSentinel(sentinelPath);\n const files: string[] = [];\n for (const entry of fs.readdirSync(memoriesDir, { withFileTypes: true })) {\n if (entry.isFile() && OWNED_FILES.has(entry.name)) files.push(entry.name);\n }\n const rolloutsDir = path.join(memoriesDir, ROLLOUT_SUBDIR);\n if (fs.existsSync(rolloutsDir)) {\n try {\n for (const entry of fs.readdirSync(rolloutsDir, { withFileTypes: true })) {\n if (entry.isFile() && entry.name.endsWith(\".md\")) {\n files.push(path.join(ROLLOUT_SUBDIR, entry.name));\n }\n }\n } catch {\n // ignore\n }\n }\n return {\n exists: true,\n hasSentinel: sentinel !== null,\n files: files.sort(),\n sentinel,\n };\n}\n","/**\n * materialize-paths.ts — containment guard for the materializer's managed\n * sub-directories (`rollout_summaries/`, `skills/`).\n *\n * Extracted from codex-materialize.ts so the skills section (issue #2369) and\n * the rollout section share ONE containment implementation instead of forking\n * the check (rule 22).\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { pathIsInside } from \"../utils/path-containment.js\";\n\n/**\n * Resolve a managed sub-directory of `memoriesDir`, creating it when absent,\n * and refuse a symlinked or escaping target. Returns the (unchanged) path so\n * callers can use it directly.\n */\nexport function ensureSafeManagedSubdir(memoriesDir: string, subdir: string, label: string): string {\n const memoriesReal = fs.realpathSync(memoriesDir);\n\n try {\n const stat = fs.lstatSync(subdir);\n if (stat.isSymbolicLink()) {\n throw new Error(\"is a symbolic link\");\n }\n if (!stat.isDirectory()) {\n throw new Error(\"is not a directory\");\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw new Error(\n `codex-materialize: unsafe ${label} directory at ${subdir}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n fs.mkdirSync(subdir, { recursive: true });\n }\n\n const subdirReal = fs.realpathSync(subdir);\n if (!pathIsInside(memoriesReal, subdirReal)) {\n throw new Error(\n `codex-materialize: unsafe ${label} directory at ${subdir}: resolves outside ${memoriesDir}`,\n );\n }\n\n return path.normalize(subdir);\n}\n","/**\n * materialize-skills.ts — the `skills/` section of the Codex materializer\n * (issue #2369).\n *\n * Extracted from codex-materialize.ts (which sits at its structural LOC cap)\n * so the skill staging / commit / prune rules live in one small module. Format\n * and slug rules stay in the host-agnostic `procedural/skill-projection.ts`;\n * this module only decides what lands on disk.\n *\n * Ownership rule: Remnic removes ONLY the slugs a previous run recorded in the\n * sentinel's `projected_skills`. A skill folder a user (or another tool)\n * created is never in that list, so it is never a removal candidate.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { renderSkillBundle, SKILL_FILE_NAME, type SkillBundle } from \"../procedural/skill-projection.js\";\nimport { isValidSkillSlug } from \"../skills-registry.js\";\nimport { ensureSafeManagedSubdir } from \"./materialize-paths.js\";\n\n/** Sub-directory for projected procedural skill bundles. */\nexport const SKILLS_SUBDIR = \"skills\";\n\nexport interface SkillFile {\n slug: string;\n body: string;\n}\n\nexport interface SkillPlan {\n /** False when the caller omitted `skills` — leave `skills/` untouched. */\n supplied: boolean;\n /** Bundles to write, deduplicated on slug. */\n files: SkillFile[];\n /** Previously projected slugs this run no longer projects. */\n retiredSlugs: string[];\n}\n\n/**\n * Decide what this run writes and removes. `undefined` bundles mean \"not our\n * business this run\"; an empty array is authoritative and retires everything\n * previously projected.\n */\nexport function planSkillFiles(\n bundles: SkillBundle[] | undefined,\n previouslyProjectedSlugs: readonly string[],\n): SkillPlan {\n const files: SkillFile[] = [];\n const seen = new Set<string>();\n for (const bundle of bundles ?? []) {\n // Invalid or duplicate slugs are dropped so two bundles can never target\n // one folder and leave the second rename with no source (§37).\n if (!isValidSkillSlug(bundle.slug) || seen.has(bundle.slug)) continue;\n seen.add(bundle.slug);\n files.push({ slug: bundle.slug, body: renderSkillBundle(bundle) });\n }\n const previous = previouslyProjectedSlugs.filter((slug) => isValidSkillSlug(slug));\n return {\n supplied: bundles !== undefined,\n files,\n retiredSlugs: bundles === undefined ? [] : previous.filter((slug) => !seen.has(slug)),\n };\n}\n\n/** Absolute path of a projected bundle's SKILL.md under `memoriesDir`. */\nexport function skillFilePath(memoriesDir: string, slug: string): string {\n return path.join(memoriesDir, SKILLS_SUBDIR, slug, SKILL_FILE_NAME);\n}\n\n/** Relative path recorded in `MaterializeResult.filesWritten`. */\nexport function skillFileRelPath(slug: string): string {\n return path.join(SKILLS_SUBDIR, slug, SKILL_FILE_NAME);\n}\n\n/**\n * True when no retired folder is still on disk. Guards the idempotent\n * early-return: a hash match is only a safe no-op if the removals also landed.\n */\nexport function retiredSkillsAlreadyRemoved(memoriesDir: string, retiredSlugs: readonly string[]): boolean {\n return retiredSlugs.every((slug) => !fs.existsSync(path.join(memoriesDir, SKILLS_SUBDIR, slug)));\n}\n\n/** Render bundles into the per-run staging directory. */\nexport function stageSkillFiles(tmpDir: string, files: readonly SkillFile[]): void {\n for (const file of files) {\n const stagedDir = path.join(tmpDir, SKILLS_SUBDIR, file.slug);\n fs.mkdirSync(stagedDir, { recursive: true });\n fs.writeFileSync(path.join(stagedDir, SKILL_FILE_NAME), file.body);\n }\n}\n\n/**\n * Remove retired folders, then rename each staged SKILL.md into place. Per-file\n * renames (never directory renames) so an existing folder cannot cause\n * ENOTEMPTY and so Codex never observes a half-written file.\n */\nexport function commitSkillFiles(memoriesDir: string, tmpDir: string, plan: SkillPlan): void {\n if (!plan.supplied) return;\n if (plan.files.length === 0 && plan.retiredSlugs.length === 0) return;\n\n const skillsDir = ensureSafeManagedSubdir(memoriesDir, path.join(memoriesDir, SKILLS_SUBDIR), SKILLS_SUBDIR);\n for (const slug of plan.retiredSlugs) {\n const retiredDir = path.join(skillsDir, slug);\n try {\n // Never follow a symlink out of the managed tree while pruning.\n if (fs.lstatSync(retiredDir).isSymbolicLink()) continue;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n try {\n fs.rmSync(retiredDir, { recursive: true, force: true });\n } catch (err) {\n throw new Error(\n `codex-materialize: failed to remove retired skill ${slug}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n for (const file of plan.files) {\n const destDir = path.join(skillsDir, file.slug);\n fs.mkdirSync(destDir, { recursive: true });\n fs.renameSync(\n path.join(tmpDir, SKILLS_SUBDIR, file.slug, SKILL_FILE_NAME),\n path.join(destDir, SKILL_FILE_NAME),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwCA;AAAA,EACE;AAAA,OACK;AACP,OAAOA,SAAQ;AACf,OAAOC,WAAU;;;ACnCjB,OAAO,QAAQ;AACf,OAAO,UAAU;AASV,SAAS,wBAAwB,aAAqB,QAAgB,OAAuB;AAClG,QAAM,eAAe,GAAG,aAAa,WAAW;AAEhD,MAAI;AACF,UAAM,OAAO,GAAG,UAAU,MAAM;AAChC,QAAI,KAAK,eAAe,GAAG;AACzB,YAAM,IAAI,MAAM,oBAAoB;AAAA,IACtC;AACA,QAAI,CAAC,KAAK,YAAY,GAAG;AACvB,YAAM,IAAI,MAAM,oBAAoB;AAAA,IACtC;AAAA,EACF,SAAS,KAAK;AACZ,QAAK,IAA8B,SAAS,UAAU;AACpD,YAAM,IAAI;AAAA,QACR,6BAA6B,KAAK,iBAAiB,MAAM,KACvD,eAAe,QAAQ,IAAI,UA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,aAAa,aAAa;AAAA,IAC1B,OAAO,MAAM,KAAK;AAAA,IAClB;AAAA,EACF;AACF;","names":["fs","path","fs","path","path","fs","path","fs","prefix"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/summarizer.ts"],"sourcesContent":["import { mkdir, readFile, writeFile, readdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { log } from \"./logger.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig, gatewayTaskChainOptions } from \"./fallback-llm.js\";\nimport { ModelRegistry } from \"./model-registry.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport {\n completeBackgroundGeneration,\n parseBackgroundGenerationJson,\n} from \"./background-generation.js\";\nimport type { HourlySummary, TranscriptEntry, PluginConfig, GatewayConfig } from \"./types.js\";\nimport type { TranscriptManager } from \"./transcript.js\";\nimport { readSummarySnapshot, upsertSummarySnapshot, writeSummarySnapshot } from \"./summary-snapshot.js\";\nimport { encodeStoragePathSegment, resolveSafeStoragePath } from \"./storage-paths.js\";\nimport { sessionStoragePaths } from \"./session-identity.js\";\nimport { resolveLocalLlmCapabilities } from \"./capabilities.js\";\nimport { resolvePipelineProcessingCapabilities } from \"./capabilities.js\";\n\n// Schema for LLM summary output\nconst HourlySummarySchema = z.object({\n bullets: z.array(z.string().trim().min(1)).min(1).describe(\"3-5 bullet points summarizing the hour's activity\"),\n});\n\ntype HourlySummaryResult = z.infer<typeof HourlySummarySchema>;\n\nconst HourlySummaryExtendedSchema = z.object({\n topics: z.array(z.string()).default([]),\n decisions: z.array(z.string()).default([]),\n actionItems: z.array(z.string()).default([]),\n rejected: z.array(z.string()).default([]),\n});\n\ntype HourlySummaryExtendedResult = z.infer<typeof HourlySummaryExtendedSchema>;\n\ntype HourlySummaryExtendedMeta = {\n userTurns: number;\n assistantTurns: number;\n toolCalls: number;\n toolCounts: Record<string, number>;\n};\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Outcome stats of one `runHourly` pass (issue #2783). The summarizer must\n * not report success on empty work: an empty or stale transcript store is\n * the delegate-mode starvation signature, and callers surface these counts\n * and the staleness flag as a distinct warning instead of a bare ok.\n */\nexport interface HourlySummarizerRunStats {\n sessionsConsidered: number;\n sessionsWithEntries: number;\n summariesWritten: number;\n /** True when the newest transcript entry across the store is older than STALE_STORE_MS. */\n staleStore: boolean;\n /** ISO timestamp of the newest transcript entry seen by the scan, when any exist. */\n newestEntryTimestamp: string | null;\n /** True when the transcript scan itself FAILED (unreadable store) — distinct from an empty store. */\n scanFailed: boolean;\n}\n\n/** A store whose newest entry is older than this is considered stale (starvation signal, issue #2783). */\nconst STALE_STORE_MS = 2 * 60 * 60 * 1000;\n\n/**\n * Interpret one {@link HourlySummarizerRunStats} into the operator-facing\n * message/warning (issue #2783). Every degraded shape — failed scan, empty\n * store, backend-down, stale store — is DISTINCT from success; monitoring\n * alerts on `warning`, never on `ok` (ok only means \"the run completed\").\n */\nexport function summarizeHourlyStatus(stats: HourlySummarizerRunStats): {\n message: string;\n warning?: string;\n} {\n if (stats.scanFailed) {\n return {\n message:\n \"Hourly summarization completed, but the transcript store scan FAILED (unreadable directory or I/O error). Investigate the daemon's memoryDir.\",\n warning: \"transcript store scan failed\",\n };\n }\n if (stats.sessionsConsidered === 0) {\n return {\n message:\n \"Hourly summarization completed, but the transcript store is empty — no sessions found. If turns are ingested via observe, transcript persistence may be disabled or failing.\",\n warning: \"transcript store is empty\",\n };\n }\n if (stats.sessionsWithEntries > 0 && stats.summariesWritten === 0) {\n return {\n message: `Hourly summarization found ${stats.sessionsWithEntries} session(s) with transcript entries but wrote no summaries — the summarizer backend may be down.`,\n warning: \"sessions with entries produced no summaries\",\n };\n }\n if (stats.sessionsWithEntries === 0 && stats.staleStore) {\n return {\n message: `Hourly summarization completed with no transcript entries for the target hour, and the store looks stale (newest entry ${stats.newestEntryTimestamp ?? \"unknown\"}).`,\n warning: \"no transcript entries for the target hour and no new entries recently\",\n };\n }\n return {\n message: `Hourly summarization completed: ${stats.summariesWritten} summar${stats.summariesWritten === 1 ? \"y\" : \"ies\"} written across ${stats.sessionsWithEntries} session${stats.sessionsWithEntries === 1 ? \"\" : \"s\"} with transcript entries.`,\n };\n}\n\nexport class HourlySummarizer {\n private summariesDir: string;\n private config: PluginConfig;\n private localLlm: LocalLlmClient;\n private fallbackLlm: FallbackLlmClient;\n private modelRegistry: ModelRegistry;\n private transcript?: TranscriptManager;\n /** Orchestrator-owned stop signal: refuses new summaries and aborts the\n * in-flight local LLM call once teardown begins. */\n private readonly shutdownSignal: AbortSignal | undefined;\n\n constructor(\n config: PluginConfig,\n gatewayConfig?: GatewayConfig,\n modelRegistry?: ModelRegistry,\n transcript?: TranscriptManager,\n shutdownSignal?: AbortSignal\n ) {\n this.config = config;\n this.summariesDir = path.join(config.memoryDir, \"summaries\", \"hourly\");\n this.modelRegistry = modelRegistry ?? new ModelRegistry(config.memoryDir);\n this.transcript = transcript;\n this.shutdownSignal = shutdownSignal;\n\n // Initialize local LLM client with shared model registry\n this.localLlm = new LocalLlmClient(config, this.modelRegistry, shutdownSignal);\n\n // Initialize fallback client with gateway config\n this.fallbackLlm = new FallbackLlmClient(gatewayConfig, fallbackLlmRuntimeContextFromConfig(config));\n\n if (\n !gatewayConfig?.agents?.defaults?.model?.primary &&\n !resolveLocalLlmCapabilities(config).localLlm &&\n config.modelSource !== \"gateway\"\n ) {\n log.warn(\"no gateway default AI and local LLM disabled — hourly summarization disabled\");\n }\n }\n\n private get useGatewayModelSource(): boolean {\n return this.config.modelSource === \"gateway\";\n }\n\n private get shouldUseLocalLlm(): boolean {\n return resolveLocalLlmCapabilities(this.config).localLlm && !this.useGatewayModelSource;\n }\n\n private withGatewayAgent(\n options: import(\"./fallback-llm.js\").FallbackLlmOptions\n ): import(\"./fallback-llm.js\").FallbackLlmOptions {\n if (!this.useGatewayModelSource) return options;\n // Shared resolution (taskModelChain > gatewayAgentId) — gotcha #22. Issue #1365.\n return { ...options, ...gatewayTaskChainOptions(this.config) };\n }\n\n async initialize(): Promise<void> {\n await mkdir(this.summariesDir, { recursive: true });\n log.info(\"hourly summarizer initialized\");\n }\n\n private async summarySessionDir(sessionKey: string): Promise<string> {\n return resolveSafeStoragePath(this.summariesDir, encodeStoragePathSegment(sessionKey, \"session\"));\n }\n\n private async legacySummarySessionDir(sessionKey: string): Promise<string | null> {\n if (sessionKey.includes(\"\\0\")) return null;\n try {\n return await resolveSafeStoragePath(this.summariesDir, sessionKey);\n } catch {\n return null;\n }\n }\n\n private summaryDateString(hour: string): string {\n const dateStr = hour.slice(0, 10);\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateStr)) {\n throw new Error(`invalid hourly summary timestamp: ${hour}`);\n }\n return dateStr;\n }\n\n // Generate summary for a specific hour and session\n async generateSummary(\n sessionKey: string,\n hourStart: Date,\n entries: TranscriptEntry[]\n ): Promise<HourlySummary | null> {\n if (entries.length === 0) return null;\n this.shutdownSignal?.throwIfAborted();\n\n // Format entries for the LLM\n const conversation = entries.map((e) => `[${e.role}] ${e.content}`).join(\"\\n\\n\");\n\n if (resolvePipelineProcessingCapabilities(this.config).hourlySummariesExtended) {\n const extended = await this.generateExtended(sessionKey, hourStart, conversation, entries);\n if (!extended) return null;\n const meta: HourlySummaryExtendedMeta = {\n userTurns: entries.filter((e) => e.role === \"user\").length,\n assistantTurns: entries.filter((e) => e.role === \"assistant\").length,\n toolCalls: extended._meta.toolCalls,\n toolCounts: extended._meta.toolCounts,\n };\n // Keep HourlySummary surface stable; encode \"topics\" as bullets for recall injection.\n const base: HourlySummary = {\n hour: hourStart.toISOString(),\n sessionKey,\n bullets: extended.topics.length > 0 ? extended.topics.slice(0, 5) : [\"(summary generated)\"],\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n const withExtras = base as any;\n withExtras._extended = extended;\n withExtras._extendedMeta = meta;\n return base;\n }\n\n const hourIso = hourStart.toISOString();\n const startTime = Date.now();\n\n if (this.config.backgroundGeneration) {\n try {\n const text = await completeBackgroundGeneration(this.config, [\n {\n role: \"system\",\n content:\n \"You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\\n\\nGuidelines:\\n- Focus on what was accomplished, decided, or discussed\\n- Include specific topics, projects, or entities mentioned\\n- Note any significant user requests or agent actions\\n- Keep bullets brief but informative (1-2 sentences each)\\n- Skip trivial greetings or meta-conversation\\n- Use present tense for ongoing work, past for completed items\\n\\nRespond with valid JSON only, matching this schema:\\n{\\\"bullets\\\": [\\\"bullet 1\\\", \\\"bullet 2\\\", \\\"bullet 3\\\"]}\",\n },\n { role: \"user\", content: `Summarize this conversation:\\n\\n${conversation}` },\n ]);\n const parsed = parseBackgroundGenerationJson(text, (value) => HourlySummarySchema.parse(value));\n if (parsed) {\n return {\n hour: hourIso,\n sessionKey,\n bullets: parsed.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n } catch {\n log.info(\"summary generation: background generation unavailable, continuing\");\n }\n }\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const localResult = await this.generateWithLocalLlm(conversation);\n if (localResult) {\n const durationMs = Date.now() - startTime;\n log.debug(`generated hourly summary for ${sessionKey} at ${hourIso} in ${durationMs}ms using local LLM`);\n return {\n hour: hourIso,\n sessionKey,\n bullets: localResult.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n // Local failed, fall back if allowed\n if (!this.config.localLlmFallback) {\n log.warn(\"summary generation: local LLM failed and fallback disabled\");\n return null;\n }\n log.info(\"summary generation: local LLM unavailable, falling back to gateway default AI\");\n } catch (err) {\n if (!this.config.localLlmFallback) {\n log.warn(\"summary generation: local LLM error and fallback disabled:\", err);\n return null;\n }\n log.info(\"summary generation: local LLM error, falling back to gateway default AI:\", err);\n }\n }\n\n if (this.shutdownSignal?.aborted) return null;\n\n // Fall back to gateway's default AI\n log.info(\"summary generation: falling back to gateway default AI\");\n\n try {\n const messages = [\n {\n role: \"system\" as const,\n content: `You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\n\nGuidelines:\n- Focus on what was accomplished, decided, or discussed\n- Include specific topics, projects, or entities mentioned\n- Note any significant user requests or agent actions\n- Keep bullets brief but informative (1-2 sentences each)\n- Skip trivial greetings or meta-conversation\n- Use present tense for ongoing work, past for completed items\n\nRespond with valid JSON matching this schema:\n{\n \"bullets\": [\"bullet 1\", \"bullet 2\", \"bullet 3\"]\n}`,\n },\n { role: \"user\" as const, content: `Summarize this conversation:\\n\\n${conversation}` },\n ];\n\n const result = await this.fallbackLlm.parseWithSchema(\n messages,\n HourlySummarySchema,\n this.withGatewayAgent({ temperature: 0.3, maxTokens: 8192 })\n );\n\n const durationMs = Date.now() - startTime;\n\n if (result) {\n log.debug(`generated hourly summary for ${sessionKey} at ${hourIso} in ${durationMs}ms via fallback`);\n return {\n hour: hourIso,\n sessionKey,\n bullets: result.bullets,\n turnCount: entries.length,\n generatedAt: new Date().toISOString(),\n };\n }\n\n log.warn(\"summary generation fallback returned no parsed output\");\n return null;\n } catch (err) {\n log.error(\"summary generation fallback failed\", err);\n return null;\n }\n }\n\n private async generateExtended(\n sessionKey: string,\n hourStart: Date,\n conversation: string,\n entries: TranscriptEntry[]\n ): Promise<(HourlySummaryExtendedResult & { _meta: HourlySummaryExtendedMeta }) | null> {\n const hourIso = hourStart.toISOString();\n const startTime = Date.now();\n\n const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000);\n let toolCounts: Record<string, number> = {};\n if (this.config.hourlySummariesIncludeToolStats && this.transcript) {\n const uses = await this.transcript.readToolUse(sessionKey, hourStart, hourEnd);\n for (const u of uses) toolCounts[u.tool] = (toolCounts[u.tool] ?? 0) + 1;\n }\n\n const sys = `You are a conversation summarization system.\\n\\nSummarize the hour into structured sections.\\n\\nReturn valid JSON matching:\\n{\\n \\\"topics\\\": [\\\"...\\\"],\\n \\\"decisions\\\": [\\\"...\\\"],\\n \\\"actionItems\\\": [\\\"...\\\"],\\n \\\"rejected\\\": [\\\"...\\\"]\\n}\\n\\nGuidelines:\\n- Prefer concrete topics and decisions.\\n- Action items should be imperative.\\n- Rejected ideas are things that were explicitly discarded or reversed.\\n- If there are none for a section, return an empty array.\\n`;\n\n const toolStatsLine =\n Object.keys(toolCounts).length > 0\n ? `Tools used (counts): ${Object.entries(toolCounts)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([k, v]) => `${k}=${v}`)\n .join(\", \")}\\n\\n`\n : \"\";\n const userTurns = entries.filter((e) => e.role === \"user\").length;\n const assistantTurns = entries.filter((e) => e.role === \"assistant\").length;\n const toolCalls = Object.values(toolCounts).reduce((a, b) => a + b, 0);\n const statsLine = `Stats: userTurns=${userTurns}, assistantTurns=${assistantTurns}, toolCalls=${toolCalls}\\n\\n`;\n\n const user = `Hour: ${hourIso}\\nSession: ${sessionKey}\\n\\n${statsLine}${toolStatsLine}Conversation:\\n${conversation}\\n`;\n\n if (this.config.backgroundGeneration) {\n try {\n const text = await completeBackgroundGeneration(this.config, [\n { role: \"system\", content: sys },\n { role: \"user\", content: user },\n ]);\n const parsed = parseBackgroundGenerationJson(text, (value) => HourlySummaryExtendedSchema.parse(value));\n if (parsed) {\n log.debug(\n `generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (background)`\n );\n return { ...parsed, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n }\n } catch {\n log.info(\"extended summary: background generation unavailable, continuing\");\n }\n }\n\n // Try local LLM first if enabled\n if (this.shouldUseLocalLlm) {\n try {\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n const truncated =\n user.length > contextSizes.maxInputChars\n ? user.slice(0, contextSizes.maxInputChars) + \"\\n\\n[truncated]\"\n : user;\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"Output valid JSON only.\" },\n { role: \"user\", content: sys + \"\\n\\n\" + truncated },\n ],\n {\n temperature: 0.2,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"hourly_summary_extended\",\n priority: \"background\",\n signal: this.shutdownSignal,\n }\n );\n if (response?.content) {\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n const result = HourlySummaryExtendedSchema.parse(parsed);\n log.debug(\n `generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (local)`\n );\n return { ...result, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n } catch {\n // keep trying candidates\n }\n }\n }\n } catch (err) {\n if (!this.config.localLlmFallback) return null;\n log.info(\"extended summary: local failed, falling back:\", err);\n }\n }\n\n if (this.shutdownSignal?.aborted) return null;\n\n try {\n const result = await this.fallbackLlm.parseWithSchema(\n [\n { role: \"system\" as const, content: sys },\n { role: \"user\" as const, content: user },\n ],\n HourlySummaryExtendedSchema,\n this.withGatewayAgent({ temperature: 0.2, maxTokens: 2048 })\n );\n if (result) {\n log.debug(\n `generated extended hourly summary for ${sessionKey} at ${hourIso} in ${Date.now() - startTime}ms (fallback)`\n );\n return { ...result, _meta: { userTurns, assistantTurns, toolCalls, toolCounts } };\n }\n return null;\n } catch (err) {\n log.error(\"extended summary generation failed\", err);\n return null;\n }\n }\n\n /**\n * Generate summary using local LLM with JSON mode.\n * Uses dynamic context sizing based on model capabilities.\n */\n private async generateWithLocalLlm(conversation: string): Promise<HourlySummaryResult | null> {\n // Get dynamic context sizes based on model capabilities\n const contextSizes = this.modelRegistry.calculateContextSizes(\n this.config.localLlmModel,\n this.config.localLlmMaxContext\n );\n log.debug(`Summarizer model context: ${contextSizes.description}`);\n\n const maxConversationChars = contextSizes.maxInputChars;\n const truncatedConversation =\n conversation.length > maxConversationChars\n ? conversation.slice(0, maxConversationChars) + \"\\n\\n[truncated]\"\n : conversation;\n\n const instructions = `You are a conversation summarization system. Summarize the following conversation transcript into 3-5 concise bullet points.\n\nGuidelines:\n- Focus on what was accomplished, decided, or discussed\n- Include specific topics, projects, or entities mentioned\n- Note any significant user requests or agent actions\n- Keep bullets brief but informative (1-2 sentences each)\n- Skip trivial greetings or meta-conversation\n- Use present tense for ongoing work, past for completed items\n\nRespond with valid JSON matching this schema:\n{\n \"bullets\": [\"bullet 1\", \"bullet 2\", \"bullet 3\"]\n}`;\n\n const fullPrompt = `${instructions}\\n\\nConversation to summarize:\\n${truncatedConversation}`;\n\n const response = await this.localLlm.chatCompletion(\n [\n { role: \"system\", content: \"You are a conversation summarization system. Output valid JSON only.\" },\n { role: \"user\", content: fullPrompt },\n ],\n {\n temperature: 0.3,\n maxTokens: contextSizes.maxOutputTokens,\n operation: \"hourly_summary\",\n priority: \"background\",\n signal: this.shutdownSignal,\n }\n );\n\n if (!response?.content) {\n return null;\n }\n\n try {\n // Parse JSON response\n const content = response.content.trim();\n for (const candidate of extractJsonCandidates(content)) {\n try {\n const parsed = JSON.parse(candidate);\n return HourlySummarySchema.parse(parsed);\n } catch {\n // keep trying candidates\n }\n }\n return null;\n } catch (err) {\n log.warn(\"local LLM summary: failed to parse JSON response:\", err);\n return null;\n }\n }\n\n // Save summary to file\n async saveSummary(summary: HourlySummary): Promise<void> {\n const sessionDir = await this.summarySessionDir(summary.sessionKey);\n await mkdir(sessionDir, { recursive: true });\n\n // Format date as YYYY-MM-DD for the filename\n const dateStr = this.summaryDateString(summary.hour);\n const filePath = await resolveSafeStoragePath(sessionDir, `${dateStr}.md`);\n\n // Format hour as HH:00 for display\n const hourStr = summary.hour.slice(11, 13);\n\n // Build markdown content\n const lines: string[] = [];\n\n // Check if file exists to append or create\n let existingContent = \"\";\n try {\n existingContent = await readFile(filePath, \"utf-8\");\n } catch {\n // File doesn't exist yet, will create new\n }\n\n // Check if this hour already exists (idempotent)\n const hourHeader = `## ${hourStr}:00`;\n if (existingContent.includes(hourHeader)) {\n // Replace existing hour section\n const headerMatch = new RegExp(`(^|\\\\n)${escapeRegExp(hourHeader)}\\\\n`).exec(existingContent);\n const sectionStart = headerMatch\n ? headerMatch.index + headerMatch[1].length\n : existingContent.indexOf(hourHeader);\n const nextHeaderPattern = /\\n## \\d{2}:00\\n/g;\n nextHeaderPattern.lastIndex = sectionStart + hourHeader.length;\n const nextHeader = nextHeaderPattern.exec(existingContent);\n const beforeHour = existingContent.slice(0, sectionStart);\n const afterHour = nextHeader ? existingContent.slice(nextHeader.index + 1) : \"\";\n const newSection = this.formatHourSection(summary, hourHeader);\n existingContent = beforeHour + newSection.trimEnd() + (afterHour ? \"\\n\\n\" + afterHour : \"\\n\");\n\n await writeFile(filePath, existingContent, \"utf-8\");\n log.debug(`updated hourly summary for ${summary.sessionKey} at ${hourStr}:00`);\n } else {\n // Append new hour section\n const newSection = this.formatHourSection(summary, hourHeader);\n\n if (existingContent) {\n // Add to existing file\n await writeFile(filePath, existingContent.trimEnd() + \"\\n\\n\" + newSection, \"utf-8\");\n } else {\n // Create new file with header\n const header = `# Hourly Summaries — ${dateStr}\\n\\n*Session: ${summary.sessionKey}*\\n`;\n await writeFile(filePath, header + \"\\n\" + newSection, \"utf-8\");\n }\n log.debug(`saved hourly summary for ${summary.sessionKey} at ${hourStr}:00`);\n }\n try {\n await upsertSummarySnapshot(this.config.memoryDir, summary);\n } catch (error) {\n log.warn(\n `hourly summarizer: failed to update summary snapshot for ${summary.sessionKey} (fail-open): ${String(error)}`\n );\n }\n }\n\n private formatHourSection(summary: HourlySummary, hourHeader: string): string {\n const ext = (summary as any)._extended as\n | (HourlySummaryExtendedResult & { _meta?: HourlySummaryExtendedMeta })\n | undefined;\n const meta = (summary as any)._extendedMeta as HourlySummaryExtendedMeta | undefined;\n const lines: string[] = [hourHeader, \"\"];\n\n if (resolvePipelineProcessingCapabilities(this.config).hourlySummariesExtended && ext) {\n lines.push(\"### Topics Discussed\");\n for (const t of ext.topics) lines.push(`- ${t}`);\n lines.push(\"\");\n lines.push(\"### Decisions Made\");\n for (const d of ext.decisions) lines.push(`- ${d}`);\n lines.push(\"\");\n lines.push(\"### Action Items\");\n for (const a of ext.actionItems) lines.push(`- ${a}`);\n lines.push(\"\");\n lines.push(\"### Rejected Ideas / Reversals\");\n for (const r of ext.rejected) lines.push(`- ${r}`);\n lines.push(\"\");\n if (meta && Object.keys(meta.toolCounts).length > 0) {\n lines.push(\"### Tools Used\");\n const top = Object.entries(meta.toolCounts)\n .sort((a, b) => b[1] - a[1])\n .slice(0, 12);\n for (const [name, count] of top) lines.push(`- ${name}: ${count}`);\n lines.push(\"\");\n }\n lines.push(\"### Stats\");\n lines.push(`- Turns: ${summary.turnCount}`);\n if (meta) {\n lines.push(`- User turns: ${meta.userTurns}`);\n lines.push(`- Assistant turns: ${meta.assistantTurns}`);\n lines.push(`- Tool calls: ${meta.toolCalls}`);\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n\n for (const bullet of summary.bullets) lines.push(`- ${bullet}`);\n lines.push(` *(${summary.turnCount} turns)*`);\n lines.push(\"\");\n return lines.join(\"\\n\");\n }\n\n // Read recent summaries for recall injection\n async readRecent(sessionKey: string, hours: number): Promise<HourlySummary[]> {\n try {\n const cutoffTime = Date.now() - hours * 60 * 60 * 1000;\n\n const snapshot = await readSummarySnapshot(this.config.memoryDir, sessionKey);\n if (snapshot) {\n return snapshot\n .filter((s) => new Date(s.hour).getTime() >= cutoffTime)\n .sort((a, b) => new Date(b.hour).getTime() - new Date(a.hour).getTime());\n }\n\n const summaries: HourlySummary[] = [];\n const encodedDir = await this.summarySessionDir(sessionKey);\n const legacyDir = await this.legacySummarySessionDir(sessionKey);\n const seenDirs = new Set<string>();\n\n for (const sessionDir of [encodedDir, legacyDir]) {\n if (!sessionDir || seenDirs.has(sessionDir)) continue;\n seenDirs.add(sessionDir);\n const parsed = await this.readSummaryDir(sessionDir, sessionKey);\n summaries.push(...parsed);\n }\n\n const byHour = new Map<string, HourlySummary>();\n for (const summary of summaries) {\n if (!byHour.has(summary.hour)) byHour.set(summary.hour, summary);\n }\n\n const sortedSummaries = Array.from(byHour.values()).sort(\n (a, b) => new Date(b.hour).getTime() - new Date(a.hour).getTime()\n );\n\n // Filter to recent hours while materializing the full parsed history.\n const recent = sortedSummaries.filter((s) => new Date(s.hour).getTime() >= cutoffTime);\n\n if (sortedSummaries.length > 0) {\n try {\n await writeSummarySnapshot(this.config.memoryDir, sessionKey, sortedSummaries);\n } catch (error) {\n log.warn(\n `hourly summarizer: failed to materialize summary snapshot for ${sessionKey} (fail-open): ${String(error)}`\n );\n }\n }\n\n return recent;\n } catch {\n // Directory doesn't exist or error reading\n return [];\n }\n }\n\n private async readSummaryDir(sessionDir: string, sessionKey: string): Promise<HourlySummary[]> {\n let files: string[];\n try {\n files = await readdir(sessionDir);\n } catch {\n return [];\n }\n\n const summaries: HourlySummary[] = [];\n const mdFiles = files.filter((f) => f.endsWith(\".md\"));\n for (const file of mdFiles) {\n const filePath = await resolveSafeStoragePath(sessionDir, file).catch(() => null);\n if (filePath === null) continue;\n\n try {\n const content = await readFile(filePath, \"utf-8\");\n summaries.push(...this.parseSummaryFile(content, sessionKey, file));\n } catch {\n // Skip unreadable summary files.\n }\n }\n\n return summaries;\n }\n\n private parseSummaryFile(content: string, sessionKey: string, filename: string): HourlySummary[] {\n const summaries: HourlySummary[] = [];\n\n // Extract date from filename (YYYY-MM-DD.md)\n const dateMatch = filename.match(/^(\\d{4}-\\d{2}-\\d{2})\\.md$/);\n if (!dateMatch) return summaries;\n const dateStr = dateMatch[1];\n\n // Split by hour sections\n const hourSections = content.split(/\\n## (\\d{2}):00\\n/);\n\n // First element is the header, skip it\n for (let i = 1; i < hourSections.length; i += 2) {\n const hourStr = hourSections[i];\n const sectionContent = hourSections[i + 1] || \"\";\n\n // Parse bullets\n const bullets: string[] = [];\n const lines = sectionContent.split(\"\\n\");\n let turnCount = 0;\n\n let inTopics = false;\n let sawExtendedTopicsHeader = false;\n for (const line of lines) {\n if (line.startsWith(\"### Topics\")) {\n inTopics = true;\n sawExtendedTopicsHeader = true;\n continue;\n }\n if (line.startsWith(\"### \") && !line.startsWith(\"### Topics\")) {\n inTopics = false;\n }\n const bulletMatch = line.match(/^- (.+)$/);\n if (bulletMatch) {\n // For extended format, only treat topic bullets as recall bullets.\n if (!sawExtendedTopicsHeader || inTopics) bullets.push(bulletMatch[1]);\n }\n const turnMatch = line.match(/\\((\\d+) turns?\\)/);\n if (turnMatch) turnCount = parseInt(turnMatch[1], 10);\n }\n\n if (bullets.length > 0) {\n summaries.push({\n hour: `${dateStr}T${hourStr}:00:00.000Z`,\n sessionKey,\n bullets,\n turnCount,\n generatedAt: \"\", // Not stored in file, not needed for recall\n });\n }\n }\n\n return summaries;\n }\n\n // Format summaries for recall injection\n formatForRecall(summaries: HourlySummary[], maxCount: number): string {\n if (summaries.length === 0) return \"\";\n\n const limited = summaries.slice(0, maxCount);\n const lines: string[] = [`## Recent Activity (last ${limited.length} hours)`];\n\n for (const summary of limited) {\n const hourStr = summary.hour.slice(11, 16); // HH:MM\n for (const bullet of summary.bullets) {\n lines.push(`- ${hourStr}: ${bullet}`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n // Main entry point for cron job\n async runHourly(): Promise<HourlySummarizerRunStats> {\n this.shutdownSignal?.throwIfAborted();\n log.debug(\"running hourly summary generation\");\n\n // Get active sessions from transcript. The scan outcome is kept LOCAL to\n // this invocation (review round 2): shared instance state would let two\n // concurrent runHourly calls cross-report each other's timestamps.\n const scan = await this.getActiveSessions();\n const sessions = scan.sessionKeys;\n let sessionsWithEntries = 0;\n let summariesWritten = 0;\n\n for (const sessionKey of sessions) {\n // Calculate the hour we want to summarize (previous hour)\n const now = new Date();\n const hourStart = new Date(now.getTime() - 60 * 60 * 1000);\n hourStart.setMinutes(0, 0, 0);\n const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000);\n\n // Get entries for this session in the target hour\n const entries = await this.getTranscriptEntries(sessionKey, hourStart, hourEnd);\n\n if (entries.length === 0) {\n log.debug(`no transcript entries for ${sessionKey} at ${hourStart.toISOString()}`);\n continue;\n }\n sessionsWithEntries += 1;\n\n // Generate and save summary\n const summary = await this.generateSummary(sessionKey, hourStart, entries);\n if (summary) {\n await this.saveSummary(summary);\n summariesWritten += 1;\n log.info(`generated hourly summary for ${sessionKey} (${entries.length} turns)`);\n }\n }\n\n return {\n sessionsConsidered: sessions.length,\n sessionsWithEntries,\n summariesWritten,\n // Staleness signal (issue #2783): newest entry across the whole\n // store, from the same scan getActiveSessions already performs.\n staleStore:\n scan.newestEntryTimestamp !== null &&\n Date.now() - new Date(scan.newestEntryTimestamp).getTime() > STALE_STORE_MS,\n newestEntryTimestamp: scan.newestEntryTimestamp,\n scanFailed: scan.scanFailed,\n };\n }\n\n // Get list of active sessions from the transcript directory, plus the\n // scan bookkeeping runHourly reports: newest entry timestamp (staleness\n // signal) and whether the scan itself FAILED. A failed scan must not be\n // reported as an empty store — those are different incidents (review\n // round 2).\n private async getActiveSessions(): Promise<{\n sessionKeys: string[];\n newestEntryTimestamp: string | null;\n scanFailed: boolean;\n }> {\n const transcriptDir = await resolveSafeStoragePath(this.config.memoryDir, \"transcripts\").catch(() => null);\n if (transcriptDir === null) {\n return { sessionKeys: [], newestEntryTimestamp: null, scanFailed: false };\n }\n\n const sessionKeys = new Set<string>();\n let newestEntryTimestamp: string | null = null;\n let newestEntryTimeMs = Number.NaN;\n let fileReadFailed = false;\n const collect = async (transcriptPath: string): Promise<void> => {\n try {\n const raw = await readFile(transcriptPath, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n if (typeof entry.sessionKey === \"string\" && entry.sessionKey.length > 0) {\n sessionKeys.add(entry.sessionKey);\n }\n // Compare parsed epoch values, never strings: a malformed\n // timestamp in a hand-edited file must not poison the staleness\n // signal with a lexically-maximal garbage value (review).\n if (typeof entry.timestamp === \"string\") {\n const timeMs = new Date(entry.timestamp).getTime();\n if (Number.isFinite(timeMs) && (Number.isNaN(newestEntryTimeMs) || timeMs > newestEntryTimeMs)) {\n newestEntryTimeMs = timeMs;\n newestEntryTimestamp = entry.timestamp;\n }\n }\n } catch {\n // ignore malformed transcript lines\n }\n }\n } catch (err) {\n // ENOENT is a concurrently-deleted file — ignore. Any other read\n // failure (permissions, I/O) means the store is partially UNREADABLE:\n // mark the scan failed so the caller warns instead of reporting an\n // empty store (review round 3).\n if ((err as NodeJS.ErrnoException)?.code !== \"ENOENT\") {\n fileReadFailed = true;\n }\n }\n };\n\n try {\n const typeEntries = await readdir(transcriptDir, { withFileTypes: true });\n for (const typeEnt of typeEntries) {\n if (!typeEnt.isDirectory()) continue;\n const typeDir = await resolveSafeStoragePath(transcriptDir, typeEnt.name).catch(() => null);\n if (typeDir === null) continue;\n const idEntries = await readdir(typeDir, { withFileTypes: true });\n for (const idEnt of idEntries) {\n if (!idEnt.isDirectory()) continue;\n const chanDir = await resolveSafeStoragePath(typeDir, idEnt.name).catch(() => null);\n if (chanDir === null) continue;\n const files = (await readdir(chanDir)).filter((f) => f.endsWith(\".jsonl\")).sort();\n for (const file of files) {\n const transcriptPath = await resolveSafeStoragePath(chanDir, file).catch(() => null);\n if (transcriptPath === null) continue;\n await collect(transcriptPath);\n }\n }\n }\n return {\n sessionKeys: Array.from(sessionKeys),\n newestEntryTimestamp,\n scanFailed: fileReadFailed,\n };\n } catch (err) {\n // ENOENT on the root is a never-written store — an EMPTY store, not a\n // scan failure (those are different incidents).\n const code = (err as NodeJS.ErrnoException)?.code;\n if (code === \"ENOENT\") {\n return { sessionKeys: [], newestEntryTimestamp: null, scanFailed: false };\n }\n log.warn(`transcript scan failed: ${err}`);\n return { sessionKeys: [], newestEntryTimestamp: null, scanFailed: true };\n }\n }\n\n // Get transcript entries for a session within a time range\n private async getTranscriptEntries(sessionKey: string, startTime: Date, endTime: Date): Promise<TranscriptEntry[]> {\n // Shared session-identity layer (issue #1496, rule #22). Arbitrary keys\n // route to `session/<hash>`; legacy `agent:<id>:...` keep their paths. The\n // shared helper also supplies the read-back-only candidate dirs (mirrors\n // TranscriptManager) so legacy `other/default` AND old `parts.length >= 3`\n // data stays discoverable here too.\n const paths = sessionStoragePaths(sessionKey);\n\n try {\n const transcriptRoot = path.join(this.config.memoryDir, \"transcripts\");\n const candidateDirs = new Set(\n [paths.dir, paths.alternateDir, paths.legacyDir, ...paths.readbackDirs].filter(\n (dir): dir is string => typeof dir === \"string\" && dir.length > 0\n )\n );\n const entries: TranscriptEntry[] = [];\n // Dedup identical raw rows that a partially-applied migration may have\n // left in both the primary dir and a read-back dir (issue #1496, cursor\n // review). Exact raw JSONL line is the stable identity.\n const seenRawLines = new Set<string>();\n\n // Read all daily transcript files in the directory\n for (const candidateDir of candidateDirs) {\n const transcriptDir = await resolveSafeStoragePath(transcriptRoot, candidateDir).catch(() => null);\n if (transcriptDir === null) continue;\n\n const files = await readdir(transcriptDir).catch(() => []);\n for (const file of files) {\n if (!file.endsWith(\".jsonl\")) continue;\n\n const transcriptPath = await resolveSafeStoragePath(transcriptDir, file).catch(() => null);\n if (transcriptPath === null) continue;\n\n try {\n const content = await readFile(transcriptPath, \"utf-8\");\n const lines = content.trim().split(\"\\n\");\n\n for (const line of lines) {\n if (!line.trim()) continue;\n try {\n const entry = JSON.parse(line) as TranscriptEntry;\n const entryTime = new Date(entry.timestamp).getTime();\n\n if (\n entry.sessionKey === sessionKey &&\n entryTime >= startTime.getTime() &&\n entryTime < endTime.getTime() &&\n !seenRawLines.has(line)\n ) {\n seenRawLines.add(line);\n entries.push(entry);\n }\n } catch {\n // Skip malformed lines\n }\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return entries;\n } catch {\n return [];\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,WAAW,eAAe;AACpD,OAAO,UAAU;AACjB,SAAS,SAAS;AAmBlB,IAAM,sBAAsB,EAAE,OAAO;AAAA,EACnC,SAAS,EAAE,MAAM,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,KAAK,MAAM,IAAI;AAC7B,sBAAM,YAAY,IAAI,KAAK,MAAM,SAAS,EAAE,QAAQ;AAEpD,oBACE,MAAM,eAAe,cACrB,aAAa,UAAU,QAAQ,KAC/B,YAAY,QAAQ,QAAQ,KAC5B,CAAC,aAAa,IAAI,IAAI,GACtB;AACA,+BAAa,IAAI,IAAI;AACrB,0BAAQ,KAAK,KAAK;AAAA,gBACpB;AAAA,cACF,QAAQ;AAAA,cAER;AAAA,YACF;AAAA,UACF,QAAQ;AAAA,UAER;AAAA,QACF;AAAA,MACF;AAEA,aAAO;AAAA,IACT,QAAQ;AACN,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AACF;","names":[]}
@@ -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,YAAY;AACrD,UAAM,KAAK,aAAa;AACxB,QAAI,gBAAgB,mCAAmC,KAAK,OAAO,YAAY,GAAG;AAChF,aAAO;AAAA,IACT;AACA,UAAM,YAA4D,CAAC;AACnE,eAAW,SAAS,SAAS;AAC3B,iBAAW,QAAQ,MAAM,OAAO;AAC9B,kBAAU,KAAK,EAAE,WAAW,MAAM,WAAW,KAAK,CAAC;AAAA,MACrD;AAAA,IACF;AAEA,QAAI,mBAAmB,CAAC,QAAQ,KAAK,UAAU,GAAG,KAAK,MAAM,SAAS,0BAA0B,KAAK,OAAO,wBAAwB,CAAC,GAAG;AACtI,aAAO,KAAK,QAAQ,UAAU,SAAS;AAAA,IACzC;AACA,UAAM,UAAU,KAAK,MAAM,WAAW,CAAC;AACvC,UAAM,UAAU;AAAA,MACd,GAAG,IAAI;AAAA,QACL,UACG,IAAI,CAAC,EAAE,UAAU,MAAM,SAAS,EAChC,OAAO,CAAC,cAAc,KAAK,UAAU,SAAS,MAAM,IAAI;AAAA,MAC7D;AAAA,IACF;AACA,UAAM,QAAQ,OAAO,KAAK,OAAO,EAAE;AACnC,UAAM,oBAAoB,KAAK,IAAI,GAAG,QAAQ,QAAQ,SAAS,KAAK,iBAAiB;AACrF,QAAI,oBAAoB,GAAG;AACzB,YAAM,SAAS,KAAK,IAAI,GAAG,KAAK,oBAAoB,QAAQ,MAAM;AAClE,YAAM,UAAU,wBAAwB,SAAS,SAAS,QAAQ,cAAc;AAChF,UAAI,QAAQ,SAAS,KAAK,QAAQ,SAAS,kBAAmB,QAAO,KAAK,QAAQ,UAAU,SAAS;AACrG,iBAAW,OAAO,QAAS,QAAO,QAAQ,GAAG;AAC7C,WAAK,YAAY,YAAY,OAAO;AAAA,IACtC;AAEA,UAAM,WAA4F,CAAC;AACnG,eAAW,EAAE,WAAW,KAAK,KAAK,WAAW;AAC3C,eAAS,KAAK,EAAE,WAAW,MAAM,UAAU,MAAM,KAAK,mBAAmB,WAAW,IAAI,EAAE,CAAC;AAAA,IAC7F;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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AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,0BAAyC;AAK7C,UAAM,KAAK,SAAS,oBAAoB,EAAE,MAAM,MAAM,MAAS;AAC/D,WAAO,KAAK,oBAAoB,OAAO,GAAG;AACxC,YAAM,QAAQ,WAAW,CAAC,GAAG,KAAK,mBAAmB,CAAC;AAAA,IACxD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,0BAAyC;AAC7C,WAAO,KAAK,oBAAoB,OAAO,GAAG;AACxC,YAAM,QAAQ,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/bulk-import/registry.ts","../src/bulk-import/pipeline.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// Bulk-import source adapter registry\n// ---------------------------------------------------------------------------\n\nimport type { BulkImportSourceAdapter } from \"./types.js\";\n\nconst adapters = new Map<string, BulkImportSourceAdapter>();\n\n/**\n * Register a source adapter. Rejects duplicate names and empty names.\n */\nexport function registerBulkImportSource(\n adapter: BulkImportSourceAdapter,\n): void {\n if (!adapter || typeof adapter !== \"object\") {\n throw new Error(\"bulk-import adapter must be an object\");\n }\n if (\n !adapter.name ||\n typeof adapter.name !== \"string\" ||\n adapter.name.trim().length === 0\n ) {\n throw new Error(\"bulk-import adapter name must be a non-empty string\");\n }\n if (typeof adapter.parse !== \"function\") {\n throw new Error(\n `bulk-import adapter '${adapter.name}' must have a parse function`,\n );\n }\n const key = adapter.name.trim();\n if (adapters.has(key)) {\n throw new Error(\n `bulk-import source adapter '${key}' is already registered`,\n );\n }\n // Store adapter with trimmed name so `adapter.name` stays consistent with\n // the registry key returned by `listBulkImportSources()`.\n const normalized: BulkImportSourceAdapter =\n adapter.name === key ? adapter : { ...adapter, name: key };\n adapters.set(key, normalized);\n}\n\n/**\n * Retrieve a registered adapter by name.\n *\n * Names are trimmed on write (see `registerBulkImportSource`), so we\n * also trim on read to avoid the asymmetric-lookup footgun where a\n * whitespace-padded lookup would never find a registered adapter.\n * Non-string or empty-after-trim inputs return undefined.\n */\nexport function getBulkImportSource(\n name: string,\n): BulkImportSourceAdapter | undefined {\n if (typeof name !== \"string\") return undefined;\n const key = name.trim();\n if (key.length === 0) return undefined;\n return adapters.get(key);\n}\n\n/**\n * List all registered adapter names.\n */\nexport function listBulkImportSources(): string[] {\n return [...adapters.keys()];\n}\n\n/**\n * Clear all registered adapters (for testing).\n */\nexport function clearBulkImportSources(): void {\n adapters.clear();\n}\n","// ---------------------------------------------------------------------------\n// Bulk-import batch processing pipeline\n// ---------------------------------------------------------------------------\n\nimport {\n validateImportTurn,\n type BulkImportError,\n type BulkImportOptions,\n type BulkImportResult,\n type BulkImportSource,\n type ImportTurn,\n} from \"./types.js\";\n\nconst DEFAULT_BATCH_SIZE = 20;\nconst MIN_BATCH_SIZE = 1;\nconst MAX_BATCH_SIZE = 1000;\n\nexport interface ProcessBatchResult {\n memoriesCreated: number;\n duplicatesSkipped: number;\n /**\n * Number of entities created by the batch. Optional so Phase-1 stubs that\n * only count memories can omit it; when absent it is treated as 0.\n */\n entitiesCreated?: number;\n}\n\nexport interface ProcessBatchContext {\n dedup: boolean;\n trustLevel: \"import\";\n namespace?: string;\n}\n\nexport type ProcessBatchFn = (\n turns: ImportTurn[],\n context: ProcessBatchContext,\n) => Promise<ProcessBatchResult>;\n\nexport function validateBatchSize(value: number | undefined): number {\n if (value === undefined) return DEFAULT_BATCH_SIZE;\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new Error(\n `batchSize must be a finite number, received ${String(value)}`,\n );\n }\n if (!Number.isInteger(value)) {\n throw new Error(\n `batchSize must be an integer, received ${value}`,\n );\n }\n if (value < MIN_BATCH_SIZE || value > MAX_BATCH_SIZE) {\n throw new Error(\n `batchSize must be between ${MIN_BATCH_SIZE} and ${MAX_BATCH_SIZE}, received ${value}`,\n );\n }\n return value;\n}\n\nexport function resolveBulkImportContext(\n options: BulkImportOptions,\n): ProcessBatchContext {\n if (options.dedup !== undefined && typeof options.dedup !== \"boolean\") {\n throw new Error(\n `dedup must be a boolean when provided, received ${String(options.dedup)}`,\n );\n }\n if (options.trustLevel !== undefined && options.trustLevel !== \"import\") {\n throw new Error(\n `trustLevel must be 'import' when provided, received ${String(options.trustLevel)}`,\n );\n }\n if (options.namespace !== undefined) {\n if (typeof options.namespace !== \"string\" || options.namespace.trim().length === 0) {\n throw new Error(\n `namespace must be a non-empty string when provided, received ${String(options.namespace)}`,\n );\n }\n }\n\n return {\n dedup: options.dedup !== false,\n trustLevel: options.trustLevel ?? \"import\",\n ...(options.namespace !== undefined\n ? { namespace: options.namespace }\n : {}),\n };\n}\n\n/**\n * Format a batch of turns into a conversation transcript string.\n */\nexport function formatBatchTranscript(turns: ImportTurn[]): string {\n return turns\n .map((t) => {\n const prefix =\n t.participantName ?? t.participantId ?? t.role;\n return `[${t.timestamp}] ${prefix}: ${t.content}`;\n })\n .join(\"\\n\");\n}\n\n/**\n * Run the bulk-import pipeline over a parsed source.\n *\n * Splits turns into batches and delegates each to `processBatch`.\n * In dryRun mode, validates and counts without calling `processBatch`.\n */\nexport async function runBulkImportPipeline(\n source: BulkImportSource,\n options: BulkImportOptions = {},\n processBatch: ProcessBatchFn,\n): Promise<BulkImportResult> {\n const batchSize = validateBatchSize(options.batchSize);\n const dryRun = options.dryRun === true;\n const batchContext = resolveBulkImportContext(options);\n\n const result: BulkImportResult = {\n memoriesCreated: 0,\n duplicatesSkipped: 0,\n entitiesCreated: 0,\n turnsProcessed: 0,\n batchesProcessed: 0,\n errors: [],\n };\n\n const turns = source.turns;\n\n if (!turns || turns.length === 0) {\n return result;\n }\n\n // Validate all turns upfront; collect validation errors\n const validTurns: ImportTurn[] = [];\n for (let i = 0; i < turns.length; i += 1) {\n const issues = validateImportTurn(turns[i], i);\n if (issues.length > 0) {\n const error: BulkImportError = {\n batchIndex: -1,\n message: issues.map((iss) => iss.message).join(\"; \"),\n };\n result.errors.push(error);\n } else {\n validTurns.push(turns[i]);\n }\n }\n\n if (dryRun) {\n result.turnsProcessed = validTurns.length;\n result.batchesProcessed =\n validTurns.length > 0\n ? Math.ceil(validTurns.length / batchSize)\n : 0;\n return result;\n }\n\n // Process in batches\n let batchIndex = 0;\n for (let i = 0; i < validTurns.length; i += batchSize) {\n const batch = validTurns.slice(i, i + batchSize);\n try {\n const batchResult = await processBatch(batch, batchContext);\n result.memoriesCreated += batchResult.memoriesCreated;\n result.duplicatesSkipped += batchResult.duplicatesSkipped;\n if (typeof batchResult.entitiesCreated === \"number\") {\n result.entitiesCreated += batchResult.entitiesCreated;\n }\n } catch (err: unknown) {\n const message =\n err instanceof Error ? err.message : String(err);\n result.errors.push({ batchIndex, message });\n }\n result.turnsProcessed += batch.length;\n result.batchesProcessed += 1;\n batchIndex += 1;\n }\n\n return result;\n}\n"],"mappings":";;;;;AAMA,IAAM,WAAW,oBAAI,IAAqC;AAKnD,SAAS,yBACd,SACM;AACN,MAAI,CAAC,WAAW,OAAO,YAAY,UAAU;AAC3C,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AACA,MACE,CAAC,QAAQ,QACT,OAAO,QAAQ,SAAS,YACxB,QAAQ,KAAK,KAAK,EAAE,WAAW,GAC/B;AACA,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AACA,MAAI,OAAO,QAAQ,UAAU,YAAY;AACvC,UAAM,IAAI;AAAA,MACR,wBAAwB,QAAQ,IAAI;AAAA,IACtC;AAAA,EACF;AACA,QAAM,MAAM,QAAQ,KAAK,KAAK;AAC9B,MAAI,SAAS,IAAI,GAAG,GAAG;AACrB,UAAM,IAAI;AAAA,MACR,+BAA+B,GAAG;AAAA,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