@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
@@ -1,14 +1,15 @@
1
1
  import {
2
2
  LocalLlmClient
3
- } from "./chunk-QFTK6EDM.js";
3
+ } from "./chunk-BFZFNXOC.js";
4
+ import "./chunk-KYZMCH4I.js";
4
5
  import "./chunk-MJFL75J6.js";
5
6
  import "./chunk-GT2HWRST.js";
6
7
  import "./chunk-U4LUIE6Y.js";
7
- import "./chunk-KYZMCH4I.js";
8
8
  import "./chunk-5YQXWVCP.js";
9
9
  import {
10
10
  OUTPUT_LANGUAGE_POLICY
11
11
  } from "./chunk-YN2DQ2D6.js";
12
+ import "./chunk-QW27DOHG.js";
12
13
  import "./chunk-TOTT6S2V.js";
13
14
  import {
14
15
  FallbackLlmClient
@@ -18,7 +19,6 @@ import "./chunk-L2EXJQJP.js";
18
19
  import "./chunk-45GF7Y3V.js";
19
20
  import "./chunk-QSF5SJAM.js";
20
21
  import "./chunk-E2AWJ7KQ.js";
21
- import "./chunk-QW27DOHG.js";
22
22
  import "./chunk-YBA52OKG.js";
23
23
  import {
24
24
  writeFileAtomically
@@ -286,8 +286,29 @@ ${correctionText}${existingRulesText}`
286
286
  return [];
287
287
  }
288
288
  }
289
- function buildCalibrationRecallSection(rules, query, maxChars = 1200) {
289
+ function calibrationRuleQueryScore(rule, query) {
290
+ const norm = (s) => s.toLowerCase().split(/[^a-z0-9]+/).filter((t) => t.length > 2);
291
+ const queryTokens = new Set(norm(query));
292
+ const ruleTokens = new Set(
293
+ norm(
294
+ `${rule.condition} ${rule.modelTendency} ${rule.userExpectation} ${rule.calibration}`
295
+ )
296
+ );
297
+ if (queryTokens.size === 0 || ruleTokens.size === 0) return 0;
298
+ let inter = 0;
299
+ for (const t of queryTokens) {
300
+ if (ruleTokens.has(t)) inter++;
301
+ }
302
+ const union = /* @__PURE__ */ new Set([...queryTokens, ...ruleTokens]);
303
+ return inter / Math.max(1, union.size);
304
+ }
305
+ function rankCalibrationRulesForQuery(rules, query) {
306
+ return rules.map((rule, index) => ({ rule, index, score: calibrationRuleQueryScore(rule, query) })).sort((a, b) => b.score - a.score || a.index - b.index).map((entry) => entry.rule);
307
+ }
308
+ function buildCalibrationRecallSection(rules, query, maxChars = 1200, maxRules) {
290
309
  if (rules.length === 0) return null;
310
+ const ranked = rankCalibrationRulesForQuery(rules, query);
311
+ const selected = maxRules !== void 0 ? ranked.slice(0, Math.max(0, maxRules)) : ranked;
291
312
  const lines = [
292
313
  "## Model Calibration (learned from past corrections)",
293
314
  "",
@@ -295,7 +316,7 @@ function buildCalibrationRecallSection(rules, query, maxChars = 1200) {
295
316
  ""
296
317
  ];
297
318
  let totalChars = lines.join("\n").length;
298
- for (const rule of rules) {
319
+ for (const rule of selected) {
299
320
  const line = `- **${rule.condition}**: ${rule.modelTendency} \u2192 Instead: ${rule.calibration}`;
300
321
  if (totalChars + line.length + 1 > maxChars) break;
301
322
  lines.push(line);
@@ -391,7 +412,9 @@ export {
391
412
  appliedCalibrationWeekId,
392
413
  buildCalibrationRecallSection,
393
414
  calibrationConsolidationInput,
415
+ calibrationRuleQueryScore,
394
416
  getCalibrationRulesForRecall,
417
+ rankCalibrationRulesForQuery,
395
418
  readCalibrationCorrections,
396
419
  readCalibrationIndex,
397
420
  runCalibrationConsolidation,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/calibration.ts"],"sourcesContent":["/**\n * calibration.ts — Prediction-Error-Driven Model-User Calibration\n *\n * Analyzes patterns in user corrections to identify systematic miscalibration\n * between the model's predictions and the user's actual expectations.\n * During consolidation, replays chains of similar corrections through an LLM\n * to synthesize CalibrationRules that adjust model behavior for this specific user.\n *\n * Inspired by:\n * - Cerebellar motor calibration (prediction errors drive lasting adjustments)\n * - Temporal difference learning (dopamine signals prediction error)\n * - Tesla FSD shadow mode (divergence between prediction and reality = training signal)\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { resolveLocalLlmCapabilities } from \"./capabilities.js\";\nimport { OUTPUT_LANGUAGE_POLICY } from \"./extraction-prompt.js\";\nimport { FallbackLlmClient } from \"./fallback-llm.js\";\nimport { listJsonFiles } from \"./json-store.js\";\nimport { isMacOsReplicationJunkBasename } from \"./utils/macos-replication-junk.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { log } from \"./logger.js\";\nimport { writeFileAtomically } from \"./maintenance/atomic-file.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, PluginConfig } from \"./types.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CalibrationRule {\n id: string;\n ruleType: \"model_tendency\" | \"user_expectation\" | \"scope_boundary\" | \"verification_required\";\n condition: string;\n modelTendency: string;\n userExpectation: string;\n calibration: string;\n confidence: number;\n evidenceCount: number;\n evidenceCorrectionIds: string[];\n createdAt: string;\n lastReinforcedAt: string;\n}\n\nexport interface CalibrationIndex {\n rules: CalibrationRule[];\n updatedAt: string;\n totalCorrectionsAnalyzed: number;\n /**\n * Weeks whose rule reinforcement is already committed. A retry of any of\n * these weeks must not increment `evidenceCount` again. Older indexes\n * persisted a single `appliedWeekId`; reads fold it into this list.\n */\n appliedWeekIds?: string[];\n}\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\nfunction calibrationDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"calibration\");\n}\n\nfunction calibrationIndexPath(memoryDir: string): string {\n return path.join(calibrationDir(memoryDir), \"calibration-index.json\");\n}\n\n/** Week ids are short (`YYYY-Www`). Longer values are not used as stamps. */\nconst MAX_APPLIED_WEEK_ID_LENGTH = 32;\n\nexport function appliedCalibrationWeekId(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0 || trimmed.length > MAX_APPLIED_WEEK_ID_LENGTH) return undefined;\n return trimmed;\n}\n\nexport async function readCalibrationIndex(memoryDir: string): Promise<CalibrationIndex> {\n try {\n const raw = JSON.parse(await readFile(calibrationIndexPath(memoryDir), \"utf8\"));\n const appliedWeekIds = normalizeAppliedWeekIds(raw.appliedWeekIds, raw.appliedWeekId);\n return {\n rules: Array.isArray(raw.rules) ? raw.rules : [],\n updatedAt: typeof raw.updatedAt === \"string\" ? raw.updatedAt : new Date().toISOString(),\n totalCorrectionsAnalyzed: typeof raw.totalCorrectionsAnalyzed === \"number\" ? raw.totalCorrectionsAnalyzed : 0,\n ...(appliedWeekIds.length > 0 ? { appliedWeekIds } : {}),\n };\n } catch {\n return { rules: [], updatedAt: new Date().toISOString(), totalCorrectionsAnalyzed: 0 };\n }\n}\n\nfunction normalizeAppliedWeekIds(list: unknown, additional: unknown): string[] {\n const weeks: string[] = [];\n if (Array.isArray(list)) {\n for (const entry of list) {\n const week = appliedCalibrationWeekId(entry);\n if (week && !weeks.includes(week)) weeks.push(week);\n }\n }\n const extra = appliedCalibrationWeekId(additional);\n if (extra && !weeks.includes(extra)) weeks.push(extra);\n return weeks;\n}\n\n/**\n * Attach the week stamp to the index that will be written with the reinforced\n * rules. The stamp and the evidence increment commit together. Every\n * previously applied week stays in the list so an out-of-order retry of an\n * older week is still recognized as already applied.\n */\nexport function withAppliedCalibrationWeek(\n index: CalibrationIndex,\n idempotencyKey: string | undefined,\n): CalibrationIndex {\n const appliedWeekIds = normalizeAppliedWeekIds(index.appliedWeekIds, idempotencyKey);\n return {\n rules: index.rules,\n updatedAt: index.updatedAt,\n totalCorrectionsAnalyzed: index.totalCorrectionsAnalyzed,\n ...(appliedWeekIds.length > 0 ? { appliedWeekIds } : {}),\n };\n}\n\nasync function writeCalibrationIndex(memoryDir: string, index: CalibrationIndex): Promise<void> {\n const dir = calibrationDir(memoryDir);\n await mkdir(dir, { recursive: true });\n const appliedWeekIds = normalizeAppliedWeekIds(index.appliedWeekIds, undefined);\n const stamped: CalibrationIndex = {\n rules: index.rules,\n updatedAt: new Date().toISOString(),\n totalCorrectionsAnalyzed: index.totalCorrectionsAnalyzed,\n ...(appliedWeekIds.length > 0 ? { appliedWeekIds } : {}),\n };\n await writeFileAtomically(calibrationIndexPath(memoryDir), JSON.stringify(stamped, null, 2));\n}\n\n// ─── Correction Reading ──────────────────────────────────────────────────────\n\nexport interface CorrectionMemory {\n id: string;\n content: string;\n created: string;\n confidence: number;\n entityRefs: string[];\n tags: string[];\n}\n\nconst CALIBRATION_RULE_TYPES = new Set([\n \"model_tendency\",\n \"user_expectation\",\n \"scope_boundary\",\n \"verification_required\",\n]);\n\nfunction parseConfidence(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return Math.max(0, Math.min(1, value));\n}\n\nfunction parseEvidenceIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Exported for entity-contamination R-11 regression coverage (#682\n * PR 2/3 — codex review). Tests can drive the real correction-reading\n * path instead of duplicating the regex inline, so calibration parser\n * regressions surface via the contamination suite.\n */\nexport async function readCalibrationCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrectionsImpl(memoryDir: string): Promise<CorrectionMemory[]> {\n const correctionsDir = path.join(memoryDir, \"corrections\");\n const files = await listJsonFiles(correctionsDir).catch(() => {\n // Corrections might be in facts/ directories too\n return [] as string[];\n });\n\n // Also scan facts directories for correction-category files\n const factsDir = path.join(memoryDir, \"facts\");\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const dayDirs = (await readdir(factsDir)).filter((d: string) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n for (const day of dayDirs) {\n const dayPath = path.join(factsDir, day);\n const dayFiles = (await readdir(dayPath))\n .filter((f: string) => !isMacOsReplicationJunkBasename(f) && f.startsWith(\"correction-\") && f.endsWith(\".md\"))\n .map((f: string) => path.join(dayPath, f));\n files.push(...dayFiles);\n }\n } catch {\n // facts dir might not exist\n }\n\n // Also check the dedicated corrections directory\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const corrFiles = (await readdir(correctionsDir))\n .filter((f: string) => !isMacOsReplicationJunkBasename(f) && f.endsWith(\".md\"))\n .map((f: string) => path.join(correctionsDir, f));\n files.push(...corrFiles);\n } catch {\n // corrections dir might not exist\n }\n\n const corrections: CorrectionMemory[] = [];\n const seen = new Set<string>();\n\n for (const filePath of files) {\n try {\n const raw = await readFile(filePath, \"utf8\");\n\n // Parse frontmatter\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) continue;\n\n const content = fmMatch[2].trim();\n if (!content || content.length < 10) continue;\n\n // Extract id from frontmatter\n const idMatch = fmMatch[1].match(/^id:\\s*(.+)$/m);\n const id = idMatch?.[1]?.trim() ?? path.basename(filePath, \".md\");\n\n if (seen.has(id)) continue;\n seen.add(id);\n\n const confMatch = fmMatch[1].match(/^confidence:\\s*(.+)$/m);\n const confidence = confMatch ? parseFloat(confMatch[1]) : 0.9;\n\n const entityMatch = fmMatch[1].match(/^entityRef:\\s*(.+)$/m);\n const entityRefs = entityMatch ? [entityMatch[1].trim()] : [];\n\n corrections.push({ id, content, created: \"\", confidence, entityRefs, tags: [] });\n } catch {\n // skip unparseable files\n }\n }\n\n return corrections;\n}\n\n// ─── LLM-Assisted Clustering and Replay ──────────────────────────────────────\n\nexport const CLUSTER_PROMPT = `You are analyzing user corrections to an AI assistant. Each correction represents a moment where the assistant's prediction of what the user wanted was WRONG.\n\nYour job: Group these corrections into clusters where the SAME TYPE of misunderstanding is happening. Then for each cluster, synthesize a CalibrationRule.\n\nA CalibrationRule describes:\n- condition: When does this type of mistake happen?\n- modelTendency: What does the model tend to assume or do wrong?\n- userExpectation: What does the user actually want instead?\n- calibration: How should the model adjust its behavior?\n- ruleType: One of \"model_tendency\", \"user_expectation\", \"scope_boundary\", \"verification_required\"\n\nFocus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.\n${OUTPUT_LANGUAGE_POLICY}\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\n \"ruleType\": \"model_tendency\",\n \"condition\": \"When discussing project scope or task boundaries\",\n \"modelTendency\": \"The model tends to assume broader scope than the user intends\",\n \"userExpectation\": \"The user prefers narrow, specific task definitions and wants to be asked before scope expansion\",\n \"calibration\": \"When uncertain about scope, ask for clarification rather than assuming. Default to the narrower interpretation.\",\n \"confidence\": 0.85,\n \"evidenceIds\": [\"correction-id-1\", \"correction-id-2\"]\n }\n ]\n}`;\n\ninterface CalibrationChatClient {\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: {\n temperature?: number;\n maxTokens?: number;\n agentId?: string;\n modelChain?: AgentPersonaModelConfig;\n }\n ): Promise<{ content?: string | null } | null>;\n}\n\ninterface CalibrationLlmOptions {\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n /** Plugin config. Supplies `localLlm*` settings when the gateway chain is empty. */\n pluginConfig?: PluginConfig;\n}\n\nfunction resolveCalibrationChatClient(options: CalibrationLlmOptions): CalibrationChatClient | null {\n const gateway = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n if (gateway.isAvailable({ agentId: options.gatewayAgentId, modelChain: options.modelChain })) {\n return gateway;\n }\n const pluginConfig = options.pluginConfig;\n if (pluginConfig && resolveLocalLlmCapabilities(pluginConfig).localLlm) {\n log.info(`[calibration] using configured local LLM (model=${pluginConfig.localLlmModel})`);\n const local = new LocalLlmClient(pluginConfig);\n return {\n chatCompletion(messages, chatOptions) {\n return local.chatCompletion(messages, {\n temperature: chatOptions?.temperature,\n maxTokens: chatOptions?.maxTokens,\n });\n },\n };\n }\n log.warn(\"[calibration] no LLM available — skipping consolidation\");\n return null;\n}\n\nexport async function synthesizeCalibrationRules(\n corrections: CorrectionMemory[],\n llm: CalibrationChatClient,\n existingRules: CalibrationRule[],\n agentId?: string,\n modelChain?: AgentPersonaModelConfig\n): Promise<CalibrationRule[]> {\n if (corrections.length < 2) return [];\n\n // Format corrections for the LLM\n const correctionText = corrections\n .slice(0, 50) // limit to avoid huge prompts\n .map((c, i) => `[${c.id}] ${c.content}`)\n .join(\"\\n\\n\");\n\n const existingRulesText =\n existingRules.length > 0\n ? `\\n\\nExisting calibration rules (avoid duplicating these):\\n${existingRules.map((r) => `- ${r.condition}: ${r.calibration}`).join(\"\\n\")}`\n : \"\";\n\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CLUSTER_PROMPT },\n {\n role: \"user\",\n content: `Here are ${corrections.length} corrections from this user:\\n\\n${correctionText}${existingRulesText}`,\n },\n ],\n { temperature: 0.3, maxTokens: 3000, agentId, modelChain }\n );\n\n if (!response?.content) return [];\n\n try {\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n if (!Array.isArray(parsed.rules)) return [];\n\n const now = new Date().toISOString();\n const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n return rawRules\n .map((r: unknown): CalibrationRule | undefined => {\n if (!r || typeof r !== \"object\" || Array.isArray(r)) return undefined;\n const raw = r as Record<string, unknown>;\n const ruleType = nonEmptyString(raw.ruleType);\n const condition = nonEmptyString(raw.condition);\n const modelTendency = nonEmptyString(raw.modelTendency);\n const calibration = nonEmptyString(raw.calibration);\n const confidence = parseConfidence(raw.confidence);\n if (\n !ruleType ||\n !CALIBRATION_RULE_TYPES.has(ruleType) ||\n !condition ||\n !modelTendency ||\n !calibration ||\n confidence === undefined\n ) {\n return undefined;\n }\n const evidenceCorrectionIds = parseEvidenceIds(raw.evidenceIds);\n return {\n id: `cal-${createHash(\"sha256\")\n .update(condition + calibration)\n .digest(\"hex\")\n .slice(0, 12)}`,\n ruleType: ruleType as CalibrationRule[\"ruleType\"],\n condition,\n modelTendency,\n userExpectation: nonEmptyString(raw.userExpectation) ?? \"\",\n calibration,\n confidence,\n evidenceCount: evidenceCorrectionIds.length,\n evidenceCorrectionIds,\n createdAt: now,\n lastReinforcedAt: now,\n };\n })\n .filter((rule): rule is CalibrationRule => !!rule);\n } catch {\n log.warn(\"[calibration] failed to parse LLM response\");\n return [];\n }\n}\n\n// ─── Recall Section ──────────────────────────────────────────────────────────\n\n/**\n * Build a recall section from calibration rules relevant to the current query.\n * Uses the LLM to select which rules apply to the current context.\n */\nexport function buildCalibrationRecallSection(\n rules: CalibrationRule[],\n query: string,\n maxChars: number = 1200,\n): string | null {\n if (rules.length === 0) return null;\n\n // Simple relevance: include all rules (they're already filtered to this user)\n // In production, could use embedding similarity to filter\n const lines: string[] = [\n \"## Model Calibration (learned from past corrections)\",\n \"\",\n \"Adjustments for this specific user, learned from patterns in their corrections:\",\n \"\",\n ];\n\n let totalChars = lines.join(\"\\n\").length;\n\n for (const rule of rules) {\n const line = `- **${rule.condition}**: ${rule.modelTendency} → Instead: ${rule.calibration}`;\n if (totalChars + line.length + 1 > maxChars) break;\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length <= 4) return null;\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Options weekly compounding passes into calibration. Gateway agent and task\n * chain fields stay limited to `modelSource: \"gateway\"`. `pluginConfig` carries\n * the `localLlm*` settings used when that chain is empty.\n */\nexport function calibrationConsolidationInput(config: PluginConfig): {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig: PluginConfig;\n} {\n const gateway = config.modelSource === \"gateway\";\n return {\n memoryDir: config.memoryDir,\n gatewayConfig: config.gatewayConfig,\n gatewayAgentId: gateway ? (config.gatewayAgentId || undefined) : undefined,\n modelChain: gateway ? config.taskModelChain : undefined,\n workspaceDir: config.workspaceDir,\n pluginConfig: config,\n };\n}\n\n/**\n * Run the full calibration pipeline:\n * 1. Read all corrections\n * 2. Send to LLM for clustering and rule synthesis\n * 3. Merge with existing rules\n * 4. Write updated index\n */\nexport async function runCalibrationConsolidation(options: {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n /**\n * When set, a week whose reinforcement is already in the index is returned\n * as-is. Weekly synthesis passes the ISO week id so a retry after a later\n * artifact failure does not count the same corrections twice.\n */\n idempotencyKey?: string;\n}): Promise<CalibrationRule[]> {\n try {\n const idempotencyKey = appliedCalibrationWeekId(options.idempotencyKey);\n const existingIndex = await readCalibrationIndex(options.memoryDir);\n if (idempotencyKey && (existingIndex.appliedWeekIds ?? []).includes(idempotencyKey)) {\n log.debug(`[calibration] week ${idempotencyKey} already applied — skipping`);\n return existingIndex.rules;\n }\n\n const llm = resolveCalibrationChatClient(options);\n if (!llm) return [];\n\n const corrections = await readCorrections(options.memoryDir);\n if (corrections.length < 3) {\n log.info(`[calibration] only ${corrections.length} corrections — need at least 3`);\n return [];\n }\n\n const newRules = await synthesizeCalibrationRules(\n corrections,\n llm,\n existingIndex.rules,\n options.gatewayAgentId,\n options.modelChain\n );\n if (newRules.length === 0) {\n log.info(\"[calibration] no new calibration rules synthesized\");\n return existingIndex.rules;\n }\n\n // Merge: keep existing rules, add new ones (deduplicate by id)\n const ruleMap = new Map(existingIndex.rules.map((r) => [r.id, r]));\n for (const rule of newRules) {\n if (ruleMap.has(rule.id)) {\n // Reinforce existing rule\n const existing = ruleMap.get(rule.id)!;\n existing.lastReinforcedAt = new Date().toISOString();\n existing.evidenceCount += rule.evidenceCount;\n existing.confidence = Math.min(1, existing.confidence + 0.05);\n } else {\n ruleMap.set(rule.id, rule);\n }\n }\n\n const allRules = [...ruleMap.values()];\n await writeCalibrationIndex(options.memoryDir, withAppliedCalibrationWeek({\n rules: allRules,\n updatedAt: existingIndex.updatedAt,\n totalCorrectionsAnalyzed: corrections.length,\n appliedWeekIds: existingIndex.appliedWeekIds,\n }, idempotencyKey));\n\n log.debug(`[calibration] synthesized ${newRules.length} new rule(s), ${allRules.length} total`);\n return allRules;\n } catch (error) {\n log.warn(\n `[calibration] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`\n );\n return [];\n }\n}\n\n/**\n * Standalone entry point for calibration consolidation that can be called\n * independently of weekly compounding. The compounding engine's\n * `synthesizeWeekly()` is one trigger, but orchestrators or periodic\n * maintenance jobs should call this directly so calibration is not gated\n * on weekly compounding being enabled.\n */\nexport async function runCalibrationIfEnabled(options: {\n memoryDir: string;\n calibrationEnabled: boolean;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n}): Promise<CalibrationRule[]> {\n if (!options.calibrationEnabled) {\n return [];\n }\n return runCalibrationConsolidation({\n memoryDir: options.memoryDir,\n gatewayConfig: options.gatewayConfig,\n gatewayAgentId: options.gatewayAgentId,\n modelChain: options.modelChain,\n workspaceDir: options.workspaceDir,\n pluginConfig: options.pluginConfig,\n });\n}\n\n/**\n * Get calibration rules for recall injection.\n * Reads the pre-computed calibration index.\n */\nexport async function getCalibrationRulesForRecall(\n memoryDir: string,\n): Promise<CalibrationRule[]> {\n const index = await readCalibrationIndex(memoryDir);\n return index.rules;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,gBAAgB;AAChC,OAAO,UAAU;AAyCjB,SAAS,eAAe,WAA2B;AACjD,SAAO,KAAK,KAAK,WAAW,SAAS,aAAa;AACpD;AAEA,SAAS,qBAAqB,WAA2B;AACvD,SAAO,KAAK,KAAK,eAAe,SAAS,GAAG,wBAAwB;AACtE;AAGA,IAAM,6BAA6B;AAE5B,SAAS,yBAAyB,OAAoC;AAC3E,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,KAAK,QAAQ,SAAS,2BAA4B,QAAO;AAChF,SAAO;AACT;AAEA,eAAsB,qBAAqB,WAA8C;AACvF,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAM,SAAS,qBAAqB,SAAS,GAAG,MAAM,CAAC;AAC9E,UAAM,iBAAiB,wBAAwB,IAAI,gBAAgB,IAAI,aAAa;AACpF,WAAO;AAAA,MACL,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC;AAAA,MAC/C,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,MACtF,0BAA0B,OAAO,IAAI,6BAA6B,WAAW,IAAI,2BAA2B;AAAA,MAC5G,GAAI,eAAe,SAAS,IAAI,EAAE,eAAe,IAAI,CAAC;AAAA,IACxD;AAA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AAA,MACF,mDAAmD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,IAC3G;AACA,WAAO,CAAC;AAAA,EACV;AACF;AASA,eAAsB,wBAAwB,SAQf;AAC7B,MAAI,CAAC,QAAQ,oBAAoB;AAC/B,WAAO,CAAC;AAAA,EACV;AACA,SAAO,4BAA4B;AAAA,IACjC,WAAW,QAAQ;AAAA,IACnB,eAAe,QAAQ;AAAA,IACvB,gBAAgB,QAAQ;AAAA,IACxB,YAAY,QAAQ;AAAA,IACpB,cAAc,QAAQ;AAAA,IACtB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;AAMA,eAAsB,6BACpB,WAC4B;AAC5B,QAAM,QAAQ,MAAM,qBAAqB,SAAS;AAClD,SAAO,MAAM;AACf;","names":[]}
1
+ {"version":3,"sources":["../src/calibration.ts"],"sourcesContent":["/**\n * calibration.ts — Prediction-Error-Driven Model-User Calibration\n *\n * Analyzes patterns in user corrections to identify systematic miscalibration\n * between the model's predictions and the user's actual expectations.\n * During consolidation, replays chains of similar corrections through an LLM\n * to synthesize CalibrationRules that adjust model behavior for this specific user.\n *\n * Inspired by:\n * - Cerebellar motor calibration (prediction errors drive lasting adjustments)\n * - Temporal difference learning (dopamine signals prediction error)\n * - Tesla FSD shadow mode (divergence between prediction and reality = training signal)\n */\n\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { resolveLocalLlmCapabilities } from \"./capabilities.js\";\nimport { OUTPUT_LANGUAGE_POLICY } from \"./extraction-prompt.js\";\nimport { FallbackLlmClient } from \"./fallback-llm.js\";\nimport { listJsonFiles } from \"./json-store.js\";\nimport { isMacOsReplicationJunkBasename } from \"./utils/macos-replication-junk.js\";\nimport { LocalLlmClient } from \"./local-llm.js\";\nimport { log } from \"./logger.js\";\nimport { writeFileAtomically } from \"./maintenance/atomic-file.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, PluginConfig } from \"./types.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CalibrationRule {\n id: string;\n ruleType: \"model_tendency\" | \"user_expectation\" | \"scope_boundary\" | \"verification_required\";\n condition: string;\n modelTendency: string;\n userExpectation: string;\n calibration: string;\n confidence: number;\n evidenceCount: number;\n evidenceCorrectionIds: string[];\n createdAt: string;\n lastReinforcedAt: string;\n}\n\nexport interface CalibrationIndex {\n rules: CalibrationRule[];\n updatedAt: string;\n totalCorrectionsAnalyzed: number;\n /**\n * Weeks whose rule reinforcement is already committed. A retry of any of\n * these weeks must not increment `evidenceCount` again. Older indexes\n * persisted a single `appliedWeekId`; reads fold it into this list.\n */\n appliedWeekIds?: string[];\n}\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\nfunction calibrationDir(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"calibration\");\n}\n\nfunction calibrationIndexPath(memoryDir: string): string {\n return path.join(calibrationDir(memoryDir), \"calibration-index.json\");\n}\n\n/** Week ids are short (`YYYY-Www`). Longer values are not used as stamps. */\nconst MAX_APPLIED_WEEK_ID_LENGTH = 32;\n\nexport function appliedCalibrationWeekId(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n if (trimmed.length === 0 || trimmed.length > MAX_APPLIED_WEEK_ID_LENGTH) return undefined;\n return trimmed;\n}\n\nexport async function readCalibrationIndex(memoryDir: string): Promise<CalibrationIndex> {\n try {\n const raw = JSON.parse(await readFile(calibrationIndexPath(memoryDir), \"utf8\"));\n const appliedWeekIds = normalizeAppliedWeekIds(raw.appliedWeekIds, raw.appliedWeekId);\n return {\n rules: Array.isArray(raw.rules) ? raw.rules : [],\n updatedAt: typeof raw.updatedAt === \"string\" ? raw.updatedAt : new Date().toISOString(),\n totalCorrectionsAnalyzed: typeof raw.totalCorrectionsAnalyzed === \"number\" ? raw.totalCorrectionsAnalyzed : 0,\n ...(appliedWeekIds.length > 0 ? { appliedWeekIds } : {}),\n };\n } catch {\n return { rules: [], updatedAt: new Date().toISOString(), totalCorrectionsAnalyzed: 0 };\n }\n}\n\nfunction normalizeAppliedWeekIds(list: unknown, additional: unknown): string[] {\n const weeks: string[] = [];\n if (Array.isArray(list)) {\n for (const entry of list) {\n const week = appliedCalibrationWeekId(entry);\n if (week && !weeks.includes(week)) weeks.push(week);\n }\n }\n const extra = appliedCalibrationWeekId(additional);\n if (extra && !weeks.includes(extra)) weeks.push(extra);\n return weeks;\n}\n\n/**\n * Attach the week stamp to the index that will be written with the reinforced\n * rules. The stamp and the evidence increment commit together. Every\n * previously applied week stays in the list so an out-of-order retry of an\n * older week is still recognized as already applied.\n */\nexport function withAppliedCalibrationWeek(\n index: CalibrationIndex,\n idempotencyKey: string | undefined,\n): CalibrationIndex {\n const appliedWeekIds = normalizeAppliedWeekIds(index.appliedWeekIds, idempotencyKey);\n return {\n rules: index.rules,\n updatedAt: index.updatedAt,\n totalCorrectionsAnalyzed: index.totalCorrectionsAnalyzed,\n ...(appliedWeekIds.length > 0 ? { appliedWeekIds } : {}),\n };\n}\n\nasync function writeCalibrationIndex(memoryDir: string, index: CalibrationIndex): Promise<void> {\n const dir = calibrationDir(memoryDir);\n await mkdir(dir, { recursive: true });\n const appliedWeekIds = normalizeAppliedWeekIds(index.appliedWeekIds, undefined);\n const stamped: CalibrationIndex = {\n rules: index.rules,\n updatedAt: new Date().toISOString(),\n totalCorrectionsAnalyzed: index.totalCorrectionsAnalyzed,\n ...(appliedWeekIds.length > 0 ? { appliedWeekIds } : {}),\n };\n await writeFileAtomically(calibrationIndexPath(memoryDir), JSON.stringify(stamped, null, 2));\n}\n\n// ─── Correction Reading ──────────────────────────────────────────────────────\n\nexport interface CorrectionMemory {\n id: string;\n content: string;\n created: string;\n confidence: number;\n entityRefs: string[];\n tags: string[];\n}\n\nconst CALIBRATION_RULE_TYPES = new Set([\n \"model_tendency\",\n \"user_expectation\",\n \"scope_boundary\",\n \"verification_required\",\n]);\n\nfunction parseConfidence(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return Math.max(0, Math.min(1, value));\n}\n\nfunction parseEvidenceIds(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction nonEmptyString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Exported for entity-contamination R-11 regression coverage (#682\n * PR 2/3 — codex review). Tests can drive the real correction-reading\n * path instead of duplicating the regex inline, so calibration parser\n * regressions surface via the contamination suite.\n */\nexport async function readCalibrationCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrections(memoryDir: string): Promise<CorrectionMemory[]> {\n return readCorrectionsImpl(memoryDir);\n}\n\nasync function readCorrectionsImpl(memoryDir: string): Promise<CorrectionMemory[]> {\n const correctionsDir = path.join(memoryDir, \"corrections\");\n const files = await listJsonFiles(correctionsDir).catch(() => {\n // Corrections might be in facts/ directories too\n return [] as string[];\n });\n\n // Also scan facts directories for correction-category files\n const factsDir = path.join(memoryDir, \"facts\");\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const dayDirs = (await readdir(factsDir)).filter((d: string) => /^\\d{4}-\\d{2}-\\d{2}$/.test(d));\n for (const day of dayDirs) {\n const dayPath = path.join(factsDir, day);\n const dayFiles = (await readdir(dayPath))\n .filter((f: string) => !isMacOsReplicationJunkBasename(f) && f.startsWith(\"correction-\") && f.endsWith(\".md\"))\n .map((f: string) => path.join(dayPath, f));\n files.push(...dayFiles);\n }\n } catch {\n // facts dir might not exist\n }\n\n // Also check the dedicated corrections directory\n try {\n const { readdir } = await import(\"node:fs/promises\");\n const corrFiles = (await readdir(correctionsDir))\n .filter((f: string) => !isMacOsReplicationJunkBasename(f) && f.endsWith(\".md\"))\n .map((f: string) => path.join(correctionsDir, f));\n files.push(...corrFiles);\n } catch {\n // corrections dir might not exist\n }\n\n const corrections: CorrectionMemory[] = [];\n const seen = new Set<string>();\n\n for (const filePath of files) {\n try {\n const raw = await readFile(filePath, \"utf8\");\n\n // Parse frontmatter\n const fmMatch = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) continue;\n\n const content = fmMatch[2].trim();\n if (!content || content.length < 10) continue;\n\n // Extract id from frontmatter\n const idMatch = fmMatch[1].match(/^id:\\s*(.+)$/m);\n const id = idMatch?.[1]?.trim() ?? path.basename(filePath, \".md\");\n\n if (seen.has(id)) continue;\n seen.add(id);\n\n const confMatch = fmMatch[1].match(/^confidence:\\s*(.+)$/m);\n const confidence = confMatch ? parseFloat(confMatch[1]) : 0.9;\n\n const entityMatch = fmMatch[1].match(/^entityRef:\\s*(.+)$/m);\n const entityRefs = entityMatch ? [entityMatch[1].trim()] : [];\n\n corrections.push({ id, content, created: \"\", confidence, entityRefs, tags: [] });\n } catch {\n // skip unparseable files\n }\n }\n\n return corrections;\n}\n\n// ─── LLM-Assisted Clustering and Replay ──────────────────────────────────────\n\nexport const CLUSTER_PROMPT = `You are analyzing user corrections to an AI assistant. Each correction represents a moment where the assistant's prediction of what the user wanted was WRONG.\n\nYour job: Group these corrections into clusters where the SAME TYPE of misunderstanding is happening. Then for each cluster, synthesize a CalibrationRule.\n\nA CalibrationRule describes:\n- condition: When does this type of mistake happen?\n- modelTendency: What does the model tend to assume or do wrong?\n- userExpectation: What does the user actually want instead?\n- calibration: How should the model adjust its behavior?\n- ruleType: One of \"model_tendency\", \"user_expectation\", \"scope_boundary\", \"verification_required\"\n\nFocus on PATTERNS, not individual corrections. A cluster needs at least 2 corrections to be worth a rule.\n${OUTPUT_LANGUAGE_POLICY}\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\n \"ruleType\": \"model_tendency\",\n \"condition\": \"When discussing project scope or task boundaries\",\n \"modelTendency\": \"The model tends to assume broader scope than the user intends\",\n \"userExpectation\": \"The user prefers narrow, specific task definitions and wants to be asked before scope expansion\",\n \"calibration\": \"When uncertain about scope, ask for clarification rather than assuming. Default to the narrower interpretation.\",\n \"confidence\": 0.85,\n \"evidenceIds\": [\"correction-id-1\", \"correction-id-2\"]\n }\n ]\n}`;\n\ninterface CalibrationChatClient {\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: {\n temperature?: number;\n maxTokens?: number;\n agentId?: string;\n modelChain?: AgentPersonaModelConfig;\n }\n ): Promise<{ content?: string | null } | null>;\n}\n\ninterface CalibrationLlmOptions {\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n /** Plugin config. Supplies `localLlm*` settings when the gateway chain is empty. */\n pluginConfig?: PluginConfig;\n}\n\nfunction resolveCalibrationChatClient(options: CalibrationLlmOptions): CalibrationChatClient | null {\n const gateway = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n if (gateway.isAvailable({ agentId: options.gatewayAgentId, modelChain: options.modelChain })) {\n return gateway;\n }\n const pluginConfig = options.pluginConfig;\n if (pluginConfig && resolveLocalLlmCapabilities(pluginConfig).localLlm) {\n log.info(`[calibration] using configured local LLM (model=${pluginConfig.localLlmModel})`);\n const local = new LocalLlmClient(pluginConfig);\n return {\n chatCompletion(messages, chatOptions) {\n return local.chatCompletion(messages, {\n temperature: chatOptions?.temperature,\n maxTokens: chatOptions?.maxTokens,\n });\n },\n };\n }\n log.warn(\"[calibration] no LLM available — skipping consolidation\");\n return null;\n}\n\nexport async function synthesizeCalibrationRules(\n corrections: CorrectionMemory[],\n llm: CalibrationChatClient,\n existingRules: CalibrationRule[],\n agentId?: string,\n modelChain?: AgentPersonaModelConfig\n): Promise<CalibrationRule[]> {\n if (corrections.length < 2) return [];\n\n // Format corrections for the LLM\n const correctionText = corrections\n .slice(0, 50) // limit to avoid huge prompts\n .map((c, i) => `[${c.id}] ${c.content}`)\n .join(\"\\n\\n\");\n\n const existingRulesText =\n existingRules.length > 0\n ? `\\n\\nExisting calibration rules (avoid duplicating these):\\n${existingRules.map((r) => `- ${r.condition}: ${r.calibration}`).join(\"\\n\")}`\n : \"\";\n\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CLUSTER_PROMPT },\n {\n role: \"user\",\n content: `Here are ${corrections.length} corrections from this user:\\n\\n${correctionText}${existingRulesText}`,\n },\n ],\n { temperature: 0.3, maxTokens: 3000, agentId, modelChain }\n );\n\n if (!response?.content) return [];\n\n try {\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n if (!Array.isArray(parsed.rules)) return [];\n\n const now = new Date().toISOString();\n const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n return rawRules\n .map((r: unknown): CalibrationRule | undefined => {\n if (!r || typeof r !== \"object\" || Array.isArray(r)) return undefined;\n const raw = r as Record<string, unknown>;\n const ruleType = nonEmptyString(raw.ruleType);\n const condition = nonEmptyString(raw.condition);\n const modelTendency = nonEmptyString(raw.modelTendency);\n const calibration = nonEmptyString(raw.calibration);\n const confidence = parseConfidence(raw.confidence);\n if (\n !ruleType ||\n !CALIBRATION_RULE_TYPES.has(ruleType) ||\n !condition ||\n !modelTendency ||\n !calibration ||\n confidence === undefined\n ) {\n return undefined;\n }\n const evidenceCorrectionIds = parseEvidenceIds(raw.evidenceIds);\n return {\n id: `cal-${createHash(\"sha256\")\n .update(condition + calibration)\n .digest(\"hex\")\n .slice(0, 12)}`,\n ruleType: ruleType as CalibrationRule[\"ruleType\"],\n condition,\n modelTendency,\n userExpectation: nonEmptyString(raw.userExpectation) ?? \"\",\n calibration,\n confidence,\n evidenceCount: evidenceCorrectionIds.length,\n evidenceCorrectionIds,\n createdAt: now,\n lastReinforcedAt: now,\n };\n })\n .filter((rule): rule is CalibrationRule => !!rule);\n } catch {\n log.warn(\"[calibration] failed to parse LLM response\");\n return [];\n }\n}\n\n// ─── Recall Section ──────────────────────────────────────────────────────────\n\n/**\n * Lexical similarity score in `[0, 1]` between a query and a calibration\n * rule — the same token-overlap idiom as `session-experience-recall.ts`\n * (Jaccard over lowercase tokens longer than two chars). Shared code so\n * the ranker and any future embedding scorer share one field mapping:\n * the rule's *when/how* text, not its id.\n */\nexport function calibrationRuleQueryScore(\n rule: CalibrationRule,\n query: string,\n): number {\n const norm = (s: string) =>\n s\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((t) => t.length > 2);\n const queryTokens = new Set(norm(query));\n const ruleTokens = new Set(\n norm(\n `${rule.condition} ${rule.modelTendency} ${rule.userExpectation} ${rule.calibration}`,\n ),\n );\n if (queryTokens.size === 0 || ruleTokens.size === 0) return 0;\n let inter = 0;\n for (const t of queryTokens) {\n if (ruleTokens.has(t)) inter++;\n }\n const union = new Set([...queryTokens, ...ruleTokens]);\n return inter / Math.max(1, union.size);\n}\n\n/**\n * Order calibration rules by query relevance (issue #3552). Highest\n * lexical-similarity first; ties and all-zero scores keep index order, so\n * an unscoreable query yields the historical include-all ordering.\n */\nexport function rankCalibrationRulesForQuery(\n rules: readonly CalibrationRule[],\n query: string,\n): CalibrationRule[] {\n return rules\n .map((rule, index) => ({ rule, index, score: calibrationRuleQueryScore(rule, query) }))\n .sort((a, b) => b.score - a.score || a.index - b.index)\n .map((entry) => entry.rule);\n}\n\n/**\n * Build a recall section from calibration rules relevant to the current query.\n * Rules are similarity-ranked against the query before `maxRules` and\n * `maxChars` caps apply, so relevant rules win the budget instead of\n * whichever happen to sit earliest in the index. When nothing matches\n * the query the index order is preserved — the include-all fallback.\n */\nexport function buildCalibrationRecallSection(\n rules: CalibrationRule[],\n query: string,\n maxChars: number = 1200,\n maxRules?: number,\n): string | null {\n if (rules.length === 0) return null;\n\n const ranked = rankCalibrationRulesForQuery(rules, query);\n const selected =\n maxRules !== undefined ? ranked.slice(0, Math.max(0, maxRules)) : ranked;\n\n const lines: string[] = [\n \"## Model Calibration (learned from past corrections)\",\n \"\",\n \"Adjustments for this specific user, learned from patterns in their corrections:\",\n \"\",\n ];\n\n let totalChars = lines.join(\"\\n\").length;\n\n for (const rule of selected) {\n const line = `- **${rule.condition}**: ${rule.modelTendency} → Instead: ${rule.calibration}`;\n if (totalChars + line.length + 1 > maxChars) break;\n lines.push(line);\n totalChars += line.length + 1;\n }\n\n if (lines.length <= 4) return null;\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Options weekly compounding passes into calibration. Gateway agent and task\n * chain fields stay limited to `modelSource: \"gateway\"`. `pluginConfig` carries\n * the `localLlm*` settings used when that chain is empty.\n */\nexport function calibrationConsolidationInput(config: PluginConfig): {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig: PluginConfig;\n} {\n const gateway = config.modelSource === \"gateway\";\n return {\n memoryDir: config.memoryDir,\n gatewayConfig: config.gatewayConfig,\n gatewayAgentId: gateway ? (config.gatewayAgentId || undefined) : undefined,\n modelChain: gateway ? config.taskModelChain : undefined,\n workspaceDir: config.workspaceDir,\n pluginConfig: config,\n };\n}\n\n/**\n * Run the full calibration pipeline:\n * 1. Read all corrections\n * 2. Send to LLM for clustering and rule synthesis\n * 3. Merge with existing rules\n * 4. Write updated index\n */\nexport async function runCalibrationConsolidation(options: {\n memoryDir: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n /**\n * When set, a week whose reinforcement is already in the index is returned\n * as-is. Weekly synthesis passes the ISO week id so a retry after a later\n * artifact failure does not count the same corrections twice.\n */\n idempotencyKey?: string;\n}): Promise<CalibrationRule[]> {\n try {\n const idempotencyKey = appliedCalibrationWeekId(options.idempotencyKey);\n const existingIndex = await readCalibrationIndex(options.memoryDir);\n if (idempotencyKey && (existingIndex.appliedWeekIds ?? []).includes(idempotencyKey)) {\n log.debug(`[calibration] week ${idempotencyKey} already applied — skipping`);\n return existingIndex.rules;\n }\n\n const llm = resolveCalibrationChatClient(options);\n if (!llm) return [];\n\n const corrections = await readCorrections(options.memoryDir);\n if (corrections.length < 3) {\n log.info(`[calibration] only ${corrections.length} corrections — need at least 3`);\n return [];\n }\n\n const newRules = await synthesizeCalibrationRules(\n corrections,\n llm,\n existingIndex.rules,\n options.gatewayAgentId,\n options.modelChain\n );\n if (newRules.length === 0) {\n log.info(\"[calibration] no new calibration rules synthesized\");\n return existingIndex.rules;\n }\n\n // Merge: keep existing rules, add new ones (deduplicate by id)\n const ruleMap = new Map(existingIndex.rules.map((r) => [r.id, r]));\n for (const rule of newRules) {\n if (ruleMap.has(rule.id)) {\n // Reinforce existing rule\n const existing = ruleMap.get(rule.id)!;\n existing.lastReinforcedAt = new Date().toISOString();\n existing.evidenceCount += rule.evidenceCount;\n existing.confidence = Math.min(1, existing.confidence + 0.05);\n } else {\n ruleMap.set(rule.id, rule);\n }\n }\n\n const allRules = [...ruleMap.values()];\n await writeCalibrationIndex(options.memoryDir, withAppliedCalibrationWeek({\n rules: allRules,\n updatedAt: existingIndex.updatedAt,\n totalCorrectionsAnalyzed: corrections.length,\n appliedWeekIds: existingIndex.appliedWeekIds,\n }, idempotencyKey));\n\n log.debug(`[calibration] synthesized ${newRules.length} new rule(s), ${allRules.length} total`);\n return allRules;\n } catch (error) {\n log.warn(\n `[calibration] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`\n );\n return [];\n }\n}\n\n/**\n * Standalone entry point for calibration consolidation that can be called\n * independently of weekly compounding. The compounding engine's\n * `synthesizeWeekly()` is one trigger, but orchestrators or periodic\n * maintenance jobs should call this directly so calibration is not gated\n * on weekly compounding being enabled.\n */\nexport async function runCalibrationIfEnabled(options: {\n memoryDir: string;\n calibrationEnabled: boolean;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n}): Promise<CalibrationRule[]> {\n if (!options.calibrationEnabled) {\n return [];\n }\n return runCalibrationConsolidation({\n memoryDir: options.memoryDir,\n gatewayConfig: options.gatewayConfig,\n gatewayAgentId: options.gatewayAgentId,\n modelChain: options.modelChain,\n workspaceDir: options.workspaceDir,\n pluginConfig: options.pluginConfig,\n });\n}\n\n/**\n * Get calibration rules for recall injection.\n * Reads the pre-computed calibration index.\n */\nexport async function getCalibrationRulesForRecall(\n memoryDir: string,\n): Promise<CalibrationRule[]> {\n const index = await readCalibrationIndex(memoryDir);\n return index.rules;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,gBAAgB;AAChC,OAAO,UAAU;AAyCjB,SAAS,eAAe,WAA2B;AACjD,SAAO,KAAK,KAAK,WAAW,SAAS,aAAa;AACpD;AAEA,SAAS,qBAAqB,WAA2B;AACvD,SAAO,KAAK,KAAK,eAAe,SAAS,GAAG,wBAAwB;AACtE;AAGA,IAAM,6BAA6B;AAE5B,SAAS,yBAAyB,OAAoC;AAC3E,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,KAAK,QAAQ,SAAS,2BAA4B,QAAO;AAChF,SAAO;AACT;AAEA,eAAsB,qBAAqB,WAA8C;AACvF,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAM,SAAS,qBAAqB,SAAS,GAAG,MAAM,CAAC;AAC9E,UAAM,iBAAiB,wBAAwB,IAAI,gBAAgB,IAAI,aAAa;AACpF,WAAO;AAAA,MACL,OAAO,MAAM,QAAQ,IAAI,KAAK,IAAI,IAAI,QAAQ,CAAC;AAAA,MAC/C,WAAW,OAAO,IAA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AC3G;AACA,WAAO,CAAC;AAAA,EACV;AACF;AASA,eAAsB,wBAAwB,SAQf;AAC7B,MAAI,CAAC,QAAQ,oBAAoB;AAC/B,WAAO,CAAC;AAAA,EACV;AACA,SAAO,4BAA4B;AAAA,IACjC,WAAW,QAAQ;AAAA,IACnB,eAAe,QAAQ;AAAA,IACvB,gBAAgB,QAAQ;AAAA,IACxB,YAAY,QAAQ;AAAA,IACpB,cAAc,QAAQ;AAAA,IACtB,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;AAMA,eAAsB,6BACpB,WAC4B;AAC5B,QAAM,QAAQ,MAAM,qBAAqB,SAAS;AAClD,SAAO,MAAM;AACf;","names":[]}
@@ -3,7 +3,7 @@ import {
3
3
  decryptCapsuleFileInMemory,
4
4
  encryptCapsuleFile,
5
5
  isEncryptedCapsuleFile
6
- } from "./chunk-UVYI6VIX.js";
6
+ } from "./chunk-X7Y7WX73.js";
7
7
  import "./chunk-BJMBJZ2Y.js";
8
8
  import "./chunk-UKJAGEXH.js";
9
9
  import "./chunk-FP2373TW.js";
@@ -15,4 +15,4 @@ export {
15
15
  encryptCapsuleFile,
16
16
  isEncryptedCapsuleFile
17
17
  };
18
- //# sourceMappingURL=capsule-crypto-GWVG7LGC.js.map
18
+ //# sourceMappingURL=capsule-crypto-7FJQINUR.js.map
@@ -17,7 +17,7 @@ import "./chunk-5WITETWU.js";
17
17
  import "./chunk-6CIAGZ6X.js";
18
18
  import {
19
19
  parseExportBundle
20
- } from "./chunk-WEHSQBFR.js";
20
+ } from "./chunk-AIF6V2OX.js";
21
21
  import {
22
22
  assertIsDirectoryNotSymlink,
23
23
  assertRealpathInsideRoot,
@@ -274,4 +274,4 @@ async function readLocalFile(absPath) {
274
274
  export {
275
275
  mergeCapsule
276
276
  };
277
- //# sourceMappingURL=capsule-merge-VHBRF65A.js.map
277
+ //# sourceMappingURL=capsule-merge-BADOICNP.js.map
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  readChainIndex,
3
3
  resolveChainsDir
4
- } from "./chunk-RB7NXZ2E.js";
4
+ } from "./chunk-W4Q65VJL.js";
5
5
  import "./chunk-B7RWBZXW.js";
6
6
  import {
7
7
  resolveCausalTrajectoryStoreDir
8
- } from "./chunk-GMO3BGOF.js";
8
+ } from "./chunk-QC2MHZDD.js";
9
9
  import {
10
10
  normalizeRecallTokens
11
11
  } from "./chunk-YCVB7X56.js";
@@ -6,9 +6,9 @@ import {
6
6
  stitchCausalChain,
7
7
  validateCausalEdge,
8
8
  writeChainIndex
9
- } from "./chunk-RB7NXZ2E.js";
9
+ } from "./chunk-W4Q65VJL.js";
10
10
  import "./chunk-B7RWBZXW.js";
11
- import "./chunk-GMO3BGOF.js";
11
+ import "./chunk-QC2MHZDD.js";
12
12
  import "./chunk-YCVB7X56.js";
13
13
  import "./chunk-A2IYSXDQ.js";
14
14
  import "./chunk-2Z5DIDQD.js";
@@ -1,15 +1,15 @@
1
1
  import {
2
2
  readChainIndex,
3
3
  resolveChainsDir
4
- } from "./chunk-RB7NXZ2E.js";
4
+ } from "./chunk-W4Q65VJL.js";
5
5
  import {
6
6
  buildExtensionsBlockForConsolidation
7
- } from "./chunk-GBSXTTLP.js";
7
+ } from "./chunk-ITGAGNX5.js";
8
8
  import {
9
9
  runPostConsolidationMaterialize
10
- } from "./chunk-L7SEYUHS.js";
10
+ } from "./chunk-3I3NXB6X.js";
11
11
  import "./chunk-3UXOZBHV.js";
12
- import "./chunk-AL3TCNSJ.js";
12
+ import "./chunk-H3MLOQ7F.js";
13
13
  import "./chunk-5JMAGU26.js";
14
14
  import "./chunk-B7RWBZXW.js";
15
15
  import "./chunk-TOTT6S2V.js";
@@ -18,27 +18,27 @@ import "./chunk-ZCUTSMR2.js";
18
18
  import "./chunk-QDW3E4RD.js";
19
19
  import {
20
20
  resolveCausalTrajectoryStoreDir
21
- } from "./chunk-GMO3BGOF.js";
22
- import "./chunk-OWM2VWNX.js";
21
+ } from "./chunk-QC2MHZDD.js";
22
+ import "./chunk-FSXYBIEZ.js";
23
+ import "./chunk-UHVXE24Y.js";
23
24
  import "./chunk-QGVCFVX6.js";
24
25
  import "./chunk-BL7WULM5.js";
25
- import "./chunk-UHVXE24Y.js";
26
26
  import "./chunk-7F7HRJI2.js";
27
27
  import "./chunk-G6OFEGUR.js";
28
- import "./chunk-AVWOULJH.js";
29
- import "./chunk-7OCKK5M5.js";
28
+ import "./chunk-SH3GOZWK.js";
29
+ import "./chunk-GWY5ZFHP.js";
30
+ import "./chunk-66DUCUOC.js";
30
31
  import "./chunk-CYEPCZN5.js";
31
32
  import "./chunk-DLR3SBOM.js";
32
33
  import "./chunk-YCK26VSL.js";
33
34
  import "./chunk-EXYT52NR.js";
34
35
  import "./chunk-3DJ6R4CC.js";
35
- import "./chunk-66DUCUOC.js";
36
36
  import "./chunk-WNEVEMJ3.js";
37
37
  import "./chunk-Y5NLBXPV.js";
38
- import "./chunk-WQUGCOKF.js";
38
+ import "./chunk-TFA6HPOA.js";
39
+ import "./chunk-F4TWWUMP.js";
39
40
  import "./chunk-72A4L5JJ.js";
40
41
  import "./chunk-A7Q43EUZ.js";
41
- import "./chunk-F4TWWUMP.js";
42
42
  import "./chunk-S2V7RUCL.js";
43
43
  import "./chunk-PPUNC7UX.js";
44
44
  import "./chunk-X3724WL4.js";
@@ -58,18 +58,19 @@ import "./chunk-3WU7XOFN.js";
58
58
  import "./chunk-P4GUQSK3.js";
59
59
  import "./chunk-4LZ7SVKM.js";
60
60
  import "./chunk-YHTG64XV.js";
61
- import "./chunk-G7D6GZ5J.js";
62
61
  import "./chunk-E5QI6C6C.js";
63
62
  import "./chunk-KM4QO4LN.js";
64
63
  import "./chunk-5WITETWU.js";
65
64
  import "./chunk-6CIAGZ6X.js";
65
+ import "./chunk-G7D6GZ5J.js";
66
+ import "./chunk-7VLBZKNB.js";
66
67
  import "./chunk-Y33KJ556.js";
67
- import "./chunk-4D2EY4WM.js";
68
+ import "./chunk-K2DTHNDY.js";
69
+ import "./chunk-IUM3VSHI.js";
68
70
  import "./chunk-B7HYXVME.js";
69
71
  import "./chunk-IXI6S2VJ.js";
70
72
  import "./chunk-AF2XMJKD.js";
71
73
  import "./chunk-OR42ZI54.js";
72
- import "./chunk-IUM3VSHI.js";
73
74
  import "./chunk-23G5P7TA.js";
74
75
  import {
75
76
  FallbackLlmClient
@@ -81,7 +82,6 @@ import {
81
82
  fallbackLlmRuntimeContextFromConfig
82
83
  } from "./chunk-QSF5SJAM.js";
83
84
  import "./chunk-E2AWJ7KQ.js";
84
- import "./chunk-7VLBZKNB.js";
85
85
  import "./chunk-MEVBSF6T.js";
86
86
  import "./chunk-W5BIQOAJ.js";
87
87
  import "./chunk-4WCLZBM2.js";
@@ -93,7 +93,7 @@ import "./chunk-YBA52OKG.js";
93
93
  import "./chunk-X26YOFGS.js";
94
94
  import "./chunk-BT7NVCML.js";
95
95
  import "./chunk-TOSPNM4T.js";
96
- import "./chunk-L272A5QW.js";
96
+ import "./chunk-YYDUBGUF.js";
97
97
  import "./chunk-BNZAR6PO.js";
98
98
  import "./chunk-ZA53AZND.js";
99
99
  import "./chunk-7RJUVTVF.js";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  readChainIndex,
3
3
  resolveChainsDir
4
- } from "./chunk-RB7NXZ2E.js";
4
+ } from "./chunk-W4Q65VJL.js";
5
5
  import "./chunk-B7RWBZXW.js";
6
6
  import {
7
7
  readCausalTrajectoryRecords,
8
8
  searchCausalTrajectories
9
- } from "./chunk-GMO3BGOF.js";
9
+ } from "./chunk-QC2MHZDD.js";
10
10
  import "./chunk-YCVB7X56.js";
11
11
  import "./chunk-A2IYSXDQ.js";
12
12
  import "./chunk-2Z5DIDQD.js";
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  appendEdge
3
- } from "./chunk-73TPOGS4.js";
4
- import "./chunk-LXY5VVGM.js";
3
+ } from "./chunk-BFBS7OFQ.js";
5
4
  import "./chunk-QGJSBU4R.js";
5
+ import "./chunk-DEUNUKTD.js";
6
+ import "./chunk-LXY5VVGM.js";
6
7
  import "./chunk-GKCXTSFF.js";
7
8
  import "./chunk-2LSZVONP.js";
8
- import "./chunk-DEUNUKTD.js";
9
9
  import "./chunk-EBV6VXKF.js";
10
10
  import "./chunk-X4OZMANG.js";
11
11
  import "./chunk-R2MBW2S4.js";
@@ -9,7 +9,7 @@ import {
9
9
  resolveCausalTrajectoryStoreDir,
10
10
  searchCausalTrajectories,
11
11
  validateCausalTrajectoryRecord
12
- } from "./chunk-GMO3BGOF.js";
12
+ } from "./chunk-QC2MHZDD.js";
13
13
  import "./chunk-YCVB7X56.js";
14
14
  import "./chunk-A2IYSXDQ.js";
15
15
  import "./chunk-2Z5DIDQD.js";
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-765K3SAT.js";
4
4
  import {
5
5
  encryptCapsuleFile
6
- } from "./chunk-UVYI6VIX.js";
6
+ } from "./chunk-X7Y7WX73.js";
7
7
  import {
8
8
  computeTransferOutputRel,
9
9
  isTransferPathExcluded
@@ -109,4 +109,4 @@ async function enforceRetention(outDirAbs, retentionDays) {
109
109
  export {
110
110
  backupMemoryDir
111
111
  };
112
- //# sourceMappingURL=chunk-OWHERGF2.js.map
112
+ //# sourceMappingURL=chunk-2NLLXCJG.js.map