agentic-qe 3.15.6 → 3.15.8

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 (441) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +263 -0
  3. package/README.md +2 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/cli/bundle.js +8 -6
  6. package/dist/cli/chunks/adapter-FC4EY447.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-SY7UCLBL.js → agent-booster-wasm-W3V5P7LE.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-KAMYBU3S.js → agent-handler-2NQFHAWE.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-2CAW3KUM.js → agent-memory-branch-457ECHHK.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-AUAL6UBL.js +2 -0
  11. package/dist/cli/chunks/{arena-QCCVIOAH.js → arena-IYBQ3GPY.js} +4 -4
  12. package/dist/cli/chunks/{arena-4OFLJ3R2.js → arena-JV3WSEHU.js} +2 -2
  13. package/dist/cli/chunks/{audit-RBDQJQJB.js → audit-5OS3T3K6.js} +3 -3
  14. package/dist/cli/chunks/base-2XML4WH7.js +2 -0
  15. package/dist/cli/chunks/{better-sqlite3-5JRACCDQ.js → better-sqlite3-IQKBFVAO.js} +2 -2
  16. package/dist/cli/chunks/{brain-handler-W4QIIRT4.js → brain-handler-KA3SGAFM.js} +3 -3
  17. package/dist/cli/chunks/{branch-enumerator-IBNGI572.js → branch-enumerator-QZDU2VOQ.js} +2 -2
  18. package/dist/cli/chunks/{browser-GMSCVAOI.js → browser-ZL7OLKJQ.js} +2 -2
  19. package/dist/cli/chunks/browser-workflow-2IFEUAAK.js +2 -0
  20. package/dist/cli/chunks/{chunk-6HWARQWV.js → chunk-22DOS3PM.js} +2 -2
  21. package/dist/cli/chunks/{chunk-VCONCVSY.js → chunk-2DPHFCMW.js} +2 -2
  22. package/dist/cli/chunks/{chunk-ALCIUWFC.js → chunk-2GSAAUW3.js} +1 -1
  23. package/dist/cli/chunks/{chunk-AX26QJ6T.js → chunk-2JCLACCS.js} +2 -2
  24. package/dist/cli/chunks/{chunk-7XTANLTN.js → chunk-2QRGIEQV.js} +1 -1
  25. package/dist/cli/chunks/{chunk-MP3FSUNB.js → chunk-2UN4JOTN.js} +2 -2
  26. package/dist/cli/chunks/{chunk-CR66HNAE.js → chunk-2ZRNXEVI.js} +1 -1
  27. package/dist/cli/chunks/{chunk-WKDWRRDT.js → chunk-3LFLO2WK.js} +2 -2
  28. package/dist/cli/chunks/{chunk-QLYO3H7E.js → chunk-3N627QRU.js} +2 -2
  29. package/dist/cli/chunks/{chunk-VVF337SV.js → chunk-4C3RYBTT.js} +2 -2
  30. package/dist/cli/chunks/{chunk-MQCTLTGE.js → chunk-4C7KE2EL.js} +2 -2
  31. package/dist/cli/chunks/{chunk-AUN4FG7V.js → chunk-4GUVVGJX.js} +1 -1
  32. package/dist/cli/chunks/{chunk-ZOUEQ6DL.js → chunk-4GYFONJB.js} +1 -1
  33. package/dist/cli/chunks/{chunk-24ZSGYC6.js → chunk-4I35ARWW.js} +1 -1
  34. package/dist/cli/chunks/{chunk-6MXAJBEA.js → chunk-4NTLGGXO.js} +1 -1
  35. package/dist/cli/chunks/{chunk-EF5UHDCG.js → chunk-4TZLZRZ4.js} +1 -1
  36. package/dist/cli/chunks/{chunk-RD5BYLN7.js → chunk-4YUBWU3E.js} +1 -1
  37. package/dist/cli/chunks/{chunk-7TVIX4WL.js → chunk-52YRSWPS.js} +2 -2
  38. package/dist/cli/chunks/{chunk-LAY7NCQK.js → chunk-5DZDLOY6.js} +3 -3
  39. package/dist/cli/chunks/{chunk-34MDMFET.js → chunk-5MBNRTT5.js} +2 -2
  40. package/dist/cli/chunks/{chunk-VAYZ5QIE.js → chunk-5ONJ7AV6.js} +1 -1
  41. package/dist/cli/chunks/{chunk-RV6HSMKJ.js → chunk-5YOO5QSE.js} +1 -1
  42. package/dist/cli/chunks/{chunk-BUTGIVKW.js → chunk-62T7U25U.js} +1 -1
  43. package/dist/cli/chunks/{chunk-66NW3ZB4.js → chunk-6CKTLVYV.js} +2 -2
  44. package/dist/cli/chunks/{chunk-TUDENMAE.js → chunk-6E7EOHMN.js} +2 -2
  45. package/dist/cli/chunks/{chunk-GVRFSXY6.js → chunk-6GIC2263.js} +2 -2
  46. package/dist/cli/chunks/{chunk-KIDOBLUO.js → chunk-767SR7WH.js} +2 -2
  47. package/dist/cli/chunks/{chunk-NBUXM5X6.js → chunk-7C6FMLQR.js} +2 -2
  48. package/dist/cli/chunks/{chunk-4POOJYXA.js → chunk-7CVMT64N.js} +1 -1
  49. package/dist/cli/chunks/{chunk-R363XXGH.js → chunk-7DHSHD5B.js} +2 -2
  50. package/dist/cli/chunks/{chunk-IEPWO4XP.js → chunk-7H3GNRNA.js} +2 -2
  51. package/dist/cli/chunks/{chunk-DQNUPEY5.js → chunk-7SLEUVPZ.js} +2 -2
  52. package/dist/cli/chunks/{chunk-YNG7E26C.js → chunk-7XGM7Q2N.js} +2 -2
  53. package/dist/cli/chunks/{chunk-5MT7DMD7.js → chunk-A2UGPKCS.js} +2 -2
  54. package/dist/cli/chunks/{chunk-2CIDFR2H.js → chunk-A6GCO6ZU.js} +2 -2
  55. package/dist/cli/chunks/{chunk-XFPQIWEH.js → chunk-BEVWCF3Q.js} +3 -3
  56. package/dist/cli/chunks/{chunk-LCCTJ2PC.js → chunk-BLZEOGQE.js} +2 -2
  57. package/dist/cli/chunks/{chunk-6R3FBFCJ.js → chunk-BQUIZ5QT.js} +2 -2
  58. package/dist/cli/chunks/{chunk-ZUTFHGEO.js → chunk-BTMEOZYY.js} +1 -1
  59. package/dist/cli/chunks/{chunk-FU7LNUD7.js → chunk-CDLG3Q2O.js} +2 -2
  60. package/dist/cli/chunks/{chunk-NYS2GUNO.js → chunk-CQ3SBRDP.js} +2 -2
  61. package/dist/cli/chunks/chunk-CQ5G64EA.js +3 -0
  62. package/dist/cli/chunks/{chunk-JCE76MPP.js → chunk-CRUQ6RXU.js} +2 -2
  63. package/dist/cli/chunks/{chunk-XBFQJZWX.js → chunk-D4IBIMWI.js} +2 -2
  64. package/dist/cli/chunks/{chunk-LZWJ5BMP.js → chunk-D4O3TJI7.js} +2 -2
  65. package/dist/cli/chunks/{chunk-AUOSHM63.js → chunk-DAFMHM64.js} +2 -2
  66. package/dist/cli/chunks/{chunk-V3OLS2NG.js → chunk-DCYUHCPK.js} +2 -2
  67. package/dist/cli/chunks/{chunk-F7A2UBZO.js → chunk-DKFSCJEF.js} +2 -2
  68. package/dist/cli/chunks/{chunk-5LST62QR.js → chunk-DN3AKAPY.js} +2 -2
  69. package/dist/cli/chunks/{chunk-OQ4S6B7P.js → chunk-DY37YMMQ.js} +1 -1
  70. package/dist/cli/chunks/{chunk-XQ53PZEF.js → chunk-EUVSSIGR.js} +3 -3
  71. package/dist/cli/chunks/{chunk-6WOZUSSN.js → chunk-FAYXES7R.js} +2 -2
  72. package/dist/cli/chunks/{chunk-GNYOHZVV.js → chunk-FEN2DHFM.js} +1 -1
  73. package/dist/cli/chunks/{chunk-BAYGQRNP.js → chunk-FEPFXXI7.js} +2 -2
  74. package/dist/cli/chunks/{chunk-DLSFT6PO.js → chunk-FJAO4UX2.js} +2 -2
  75. package/dist/cli/chunks/{chunk-22OZIJAD.js → chunk-FWXNFPLS.js} +2 -2
  76. package/dist/cli/chunks/{chunk-X33F7NXH.js → chunk-G6CLO74Q.js} +3 -3
  77. package/dist/cli/chunks/{chunk-HAN4MS5T.js → chunk-G77Q22EN.js} +2 -2
  78. package/dist/cli/chunks/{chunk-5DH5QI7G.js → chunk-GENNJRNK.js} +3 -3
  79. package/dist/cli/chunks/{chunk-LMAEMVPA.js → chunk-GGSTLKY5.js} +1 -1
  80. package/dist/cli/chunks/{chunk-EJ4KZFZN.js → chunk-GSOK4M6V.js} +1 -1
  81. package/dist/cli/chunks/{chunk-DA7DGDTI.js → chunk-HI6OBDDY.js} +2 -2
  82. package/dist/cli/chunks/{chunk-XZ46CI35.js → chunk-HNGNRIZZ.js} +2 -2
  83. package/dist/cli/chunks/{chunk-CLAMMGY3.js → chunk-HXCGV5UJ.js} +2 -2
  84. package/dist/cli/chunks/{chunk-5UPIL62W.js → chunk-I4U7YCXG.js} +3 -3
  85. package/dist/cli/chunks/{chunk-RFDFET3O.js → chunk-I77D65X5.js} +2 -2
  86. package/dist/cli/chunks/{chunk-HEGGV2PT.js → chunk-IJSFZO7P.js} +2 -2
  87. package/dist/cli/chunks/{chunk-GWM4M5NF.js → chunk-IMSRWNWF.js} +1 -1
  88. package/dist/cli/chunks/{chunk-B7RHBKHL.js → chunk-J6LL25QJ.js} +2 -2
  89. package/dist/cli/chunks/{chunk-KYVIOC3C.js → chunk-J7FLNP5L.js} +2 -2
  90. package/dist/cli/chunks/{chunk-YLNYPQDR.js → chunk-J7RCI25Q.js} +1 -1
  91. package/dist/cli/chunks/{chunk-72MQCZSM.js → chunk-JFWQFB3S.js} +2 -2
  92. package/dist/cli/chunks/{chunk-SV5BUYHH.js → chunk-JLTGO5BB.js} +2 -2
  93. package/dist/cli/chunks/{chunk-CCL436IU.js → chunk-JWPYMRIX.js} +14 -6
  94. package/dist/cli/chunks/{chunk-ONPPBLRB.js → chunk-K4N2MBCE.js} +2 -2
  95. package/dist/cli/chunks/{chunk-7SAMMQVS.js → chunk-K5R3WUJP.js} +1 -1
  96. package/dist/cli/chunks/{chunk-GI5HWS4H.js → chunk-KITKQUBX.js} +1 -1
  97. package/dist/cli/chunks/{chunk-7TJZDRDU.js → chunk-KJNUETCB.js} +1 -1
  98. package/dist/cli/chunks/{chunk-JYKQVYX2.js → chunk-KMVFBYJO.js} +2 -2
  99. package/dist/cli/chunks/{chunk-ZSBD4FUX.js → chunk-KMZW2P3R.js} +2 -2
  100. package/dist/cli/chunks/{chunk-PEMSXSP2.js → chunk-KNHLOANK.js} +2 -2
  101. package/dist/cli/chunks/{chunk-47Q7JL3V.js → chunk-KNQUHGNY.js} +2 -2
  102. package/dist/cli/chunks/{chunk-A7ANPS4E.js → chunk-KVMKYUOE.js} +2 -2
  103. package/dist/cli/chunks/{chunk-XBEI2JBA.js → chunk-LHRVSK44.js} +2 -2
  104. package/dist/cli/chunks/{chunk-AJT3XDRD.js → chunk-LPSMVBB3.js} +2 -2
  105. package/dist/cli/chunks/{chunk-ORBODZSO.js → chunk-LVHZK7GW.js} +2 -2
  106. package/dist/cli/chunks/{chunk-ZTB32K5N.js → chunk-LZWBUVCK.js} +3 -3
  107. package/dist/cli/chunks/{chunk-OPDZBRIL.js → chunk-MMY52Y6R.js} +2 -2
  108. package/dist/cli/chunks/{chunk-MQTA6KIO.js → chunk-MUDBF2JC.js} +1 -1
  109. package/dist/cli/chunks/{chunk-GFB6BZWU.js → chunk-MV4S3TEC.js} +2 -2
  110. package/dist/cli/chunks/{chunk-UB6DQGWM.js → chunk-NF63NHJH.js} +2 -2
  111. package/dist/cli/chunks/{chunk-D5N2O5EH.js → chunk-NHOMVBCI.js} +2 -2
  112. package/dist/cli/chunks/{chunk-3NJ7O3OH.js → chunk-NLYUC63R.js} +2 -2
  113. package/dist/cli/chunks/{chunk-4CLDYT36.js → chunk-NQDYOF35.js} +2 -2
  114. package/dist/cli/chunks/{chunk-ORFL3YXB.js → chunk-NW7HTOSN.js} +2 -2
  115. package/dist/cli/chunks/{chunk-FQ5N666N.js → chunk-NWFBF3KT.js} +1 -1
  116. package/dist/cli/chunks/{chunk-P7DXVL2S.js → chunk-NZATJ2C6.js} +2 -2
  117. package/dist/cli/chunks/{chunk-HOEWMEF2.js → chunk-O4RRVTXN.js} +2 -2
  118. package/dist/cli/chunks/{chunk-4KOVHQXK.js → chunk-OCLAMZJG.js} +2 -2
  119. package/dist/cli/chunks/{chunk-TLUIO37P.js → chunk-OJWEZYLR.js} +2 -2
  120. package/dist/cli/chunks/{chunk-A74J23QB.js → chunk-OWBFVAEH.js} +2 -2
  121. package/dist/cli/chunks/{chunk-6T6AHVLF.js → chunk-P2EA62YS.js} +1 -1
  122. package/dist/cli/chunks/{chunk-TL5GV3PR.js → chunk-P4UT4LBE.js} +3 -3
  123. package/dist/cli/chunks/{chunk-IVJIHZSM.js → chunk-PICEGWGB.js} +1 -1
  124. package/dist/cli/chunks/{chunk-ITIJ23K2.js → chunk-PIEKGKW6.js} +2 -2
  125. package/dist/cli/chunks/{chunk-2ZTWPMTK.js → chunk-PJGQ2TKN.js} +2 -2
  126. package/dist/cli/chunks/{chunk-KCB6P463.js → chunk-PPIM7B5G.js} +2 -2
  127. package/dist/cli/chunks/{chunk-L2TDHJR3.js → chunk-PUYQ6EKC.js} +2 -2
  128. package/dist/cli/chunks/{chunk-2IWPJUVV.js → chunk-PWA6XBW4.js} +8 -8
  129. package/dist/cli/chunks/{chunk-XPB5BVU6.js → chunk-PZ7FJ4UG.js} +2 -2
  130. package/dist/cli/chunks/{chunk-SOSJWM3E.js → chunk-QFYUZYRA.js} +4 -4
  131. package/dist/cli/chunks/{chunk-RUTO67PT.js → chunk-R2NHGESM.js} +2 -2
  132. package/dist/cli/chunks/{chunk-K55EAWZ5.js → chunk-RG42LDOB.js} +2 -2
  133. package/dist/cli/chunks/{chunk-JAPBSSFY.js → chunk-RSMPJWQH.js} +1 -1
  134. package/dist/cli/chunks/{chunk-46HBVDMU.js → chunk-SFPGLUXS.js} +1 -1
  135. package/dist/cli/chunks/{chunk-TVLOED6O.js → chunk-SHEVM5PF.js} +2 -2
  136. package/dist/cli/chunks/{chunk-6RDVY26I.js → chunk-SJMZZMHP.js} +2 -2
  137. package/dist/cli/chunks/{chunk-3DJNKNBR.js → chunk-ST7ASEJO.js} +57 -57
  138. package/dist/cli/chunks/{chunk-QS5KZYUZ.js → chunk-SWY6KGMF.js} +2 -2
  139. package/dist/cli/chunks/{chunk-UHHMAKPE.js → chunk-T2TDTBFV.js} +1 -1
  140. package/dist/cli/chunks/{chunk-5HAPS6VD.js → chunk-TC52M542.js} +2 -2
  141. package/dist/cli/chunks/chunk-TMNEK7TP.js +2 -0
  142. package/dist/cli/chunks/{chunk-ELI4GDQO.js → chunk-U3BWBP6B.js} +2 -2
  143. package/dist/cli/chunks/{chunk-CZBIREL5.js → chunk-U7CIY3YR.js} +2 -2
  144. package/dist/cli/chunks/{chunk-X2DR27AY.js → chunk-UDCYQLTD.js} +2 -2
  145. package/dist/cli/chunks/{chunk-CEXNW5TR.js → chunk-UKKFZJME.js} +1 -1
  146. package/dist/cli/chunks/{chunk-5NC7QEJ6.js → chunk-UQLAN5TX.js} +4 -4
  147. package/dist/cli/chunks/{chunk-BIXRTOH3.js → chunk-UTFMMZ57.js} +3 -3
  148. package/dist/cli/chunks/{chunk-YXU35GGD.js → chunk-UTNKMPTC.js} +1 -1
  149. package/dist/cli/chunks/{chunk-HZFK2Z2Z.js → chunk-V4QJ3MMT.js} +1 -1
  150. package/dist/cli/chunks/{chunk-LJCEDTUM.js → chunk-V7VZSNDK.js} +3 -3
  151. package/dist/cli/chunks/{chunk-RLB7K7QP.js → chunk-VKFVJCIH.js} +1 -1
  152. package/dist/cli/chunks/{chunk-5GIJU2ZY.js → chunk-VQRBBR27.js} +2 -2
  153. package/dist/cli/chunks/{chunk-Q2RBOC7V.js → chunk-VVK4ECVJ.js} +2 -2
  154. package/dist/cli/chunks/{chunk-624QRKQX.js → chunk-VWRNG3UK.js} +1 -1
  155. package/dist/cli/chunks/{chunk-F3KS3TAB.js → chunk-VWSGWYRB.js} +2 -2
  156. package/dist/cli/chunks/{chunk-I7WAW7TM.js → chunk-W5A36V3Z.js} +2 -2
  157. package/dist/cli/chunks/chunk-WAWKAYPY.js +2 -0
  158. package/dist/cli/chunks/{chunk-NMY4KTWA.js → chunk-WLXGUQOZ.js} +2 -2
  159. package/dist/cli/chunks/{chunk-7VTKR44N.js → chunk-X3HM7SV4.js} +2 -2
  160. package/dist/cli/chunks/chunk-X6VYQVUM.js +2 -0
  161. package/dist/cli/chunks/{chunk-ZL5LJT7D.js → chunk-X7ZQIFES.js} +2 -2
  162. package/dist/cli/chunks/{chunk-5VUIXDY2.js → chunk-XOOBLZXR.js} +2 -2
  163. package/dist/cli/chunks/{chunk-L4D3TPFP.js → chunk-XZQVC3GD.js} +1 -1
  164. package/dist/cli/chunks/{chunk-BO7UFNYV.js → chunk-Y5ZBF7MA.js} +2 -2
  165. package/dist/cli/chunks/{chunk-ULCHPPW2.js → chunk-YNQPHRUZ.js} +1 -1
  166. package/dist/cli/chunks/{chunk-ZCP4P6O2.js → chunk-YRH7KMTU.js} +2 -2
  167. package/dist/cli/chunks/{chunk-QLKUCMZC.js → chunk-YTYS2XSY.js} +1 -1
  168. package/dist/cli/chunks/{chunk-JPJEAK4G.js → chunk-YUP3APSN.js} +1 -1
  169. package/dist/cli/chunks/{chunk-BXATKI5S.js → chunk-YVWMJZ6O.js} +2 -2
  170. package/dist/cli/chunks/{chunk-PS6WFCA4.js → chunk-Z3LDUPLQ.js} +2 -2
  171. package/dist/cli/chunks/{chunk-FOJRPEIP.js → chunk-ZBI7PJFX.js} +2 -2
  172. package/dist/cli/chunks/{chunk-NHRF3V4B.js → chunk-ZG7UKWBB.js} +2 -2
  173. package/dist/cli/chunks/{chunk-7XUB7U6Z.js → chunk-ZOHS32SI.js} +2 -2
  174. package/dist/cli/chunks/{chunk-RHIQ6QO5.js → chunk-ZOVAZTXE.js} +430 -430
  175. package/dist/cli/chunks/{chunk-7QVPMH25.js → chunk-ZWMFKZEQ.js} +2 -2
  176. package/dist/cli/chunks/{ci-GEJCXMBK.js → ci-7NUCRGWO.js} +2 -2
  177. package/dist/cli/chunks/{ci-config-2ZVV4OXL.js → ci-config-VQVECCFI.js} +2 -2
  178. package/dist/cli/chunks/{ci-output-E45OGVPR.js → ci-output-P7GQ6TKF.js} +2 -2
  179. package/dist/cli/chunks/{circuit-breaker-X73ITYZC.js → circuit-breaker-5YP6N6HE.js} +2 -2
  180. package/dist/cli/chunks/{claude-flow-setup-W4PPH46C.js → claude-flow-setup-W5H7CMU6.js} +2 -2
  181. package/dist/cli/chunks/client-RFUSQRUZ.js +2 -0
  182. package/dist/cli/chunks/{cline-installer-NUEPMWDE.js → cline-installer-OYANSZ54.js} +2 -2
  183. package/dist/cli/chunks/{code-6WQHBS7G.js → code-OMT4UEZI.js} +3 -3
  184. package/dist/cli/chunks/{code-index-extractor-BXQIFIFT.js → code-index-extractor-M2JEWKNF.js} +2 -2
  185. package/dist/cli/chunks/{codex-installer-Z337R2KH.js → codex-installer-YBS6N5O3.js} +2 -2
  186. package/dist/cli/chunks/{completions-F5DMYFHV.js → completions-U7GS5RG6.js} +2 -2
  187. package/dist/cli/chunks/{complexity-analyzer-W2SYPZDI.js → complexity-analyzer-QSXPIUIU.js} +2 -2
  188. package/dist/cli/chunks/{continuedev-installer-ZCHUIFTN.js → continuedev-installer-W5TTT743.js} +2 -2
  189. package/dist/cli/chunks/{copilot-installer-M5JNODXF.js → copilot-installer-KC2RT24C.js} +2 -2
  190. package/dist/cli/chunks/core-handlers-ZC7QB432.js +2 -0
  191. package/dist/cli/chunks/{cost-tracker-LSYTHBHV.js → cost-tracker-OQPVR6V4.js} +2 -2
  192. package/dist/cli/chunks/{coverage-PGMRS5SS.js → coverage-TCO2A2NX.js} +3 -3
  193. package/dist/cli/chunks/cross-domain-router-GRBK7YFZ.js +2 -0
  194. package/dist/cli/chunks/{cursor-installer-XPUA73UW.js → cursor-installer-MH7GWD4L.js} +2 -2
  195. package/dist/cli/chunks/daemon-JER6HE2J.js +12 -0
  196. package/dist/cli/chunks/{daemon-ITKDIYMW.js → daemon-UJEARJZ2.js} +3 -3
  197. package/dist/cli/chunks/{dag-attention-scheduler-T55AXLD6.js → dag-attention-scheduler-F3SUJU5O.js} +2 -2
  198. package/dist/cli/chunks/{detect-DR7J6K4O.js → detect-5QTCRB32.js} +2 -2
  199. package/dist/cli/chunks/{dist-node-LAJJBOUT.js → dist-node-XKZPHDBO.js} +2 -2
  200. package/dist/cli/chunks/{domain-handler-OMSHCRMK.js → domain-handler-V3UEADKW.js} +2 -2
  201. package/dist/cli/chunks/{domain-plugins-EQXSKC5K.js → domain-plugins-7PES4UHZ.js} +2 -2
  202. package/dist/cli/chunks/{domain-transfer-FKRAGVSW.js → domain-transfer-NF7UJW7B.js} +2 -2
  203. package/dist/cli/chunks/dream-VALD726W.js +2 -0
  204. package/dist/cli/chunks/{embed-and-insert-pattern-JZFPCNL3.js → embed-and-insert-pattern-D2HWORHF.js} +2 -2
  205. package/dist/cli/chunks/{eval-JSNNASBW.js → eval-UF2UBAUC.js} +2 -2
  206. package/dist/cli/chunks/{experience-capture-middleware-UPD3IZBK.js → experience-capture-middleware-2OUCEHHM.js} +3 -3
  207. package/dist/cli/chunks/{fast-paths-YNMIBS2E.js → fast-paths-KV5DKKHC.js} +2 -2
  208. package/dist/cli/chunks/{feature-flags-SRLXDKBI.js → feature-flags-6YWMTNO5.js} +2 -2
  209. package/dist/cli/chunks/{feature-flags-VIR7O4L7.js → feature-flags-MTW6NMR3.js} +2 -2
  210. package/dist/cli/chunks/file-discovery-VL73ASNI.js +2 -0
  211. package/dist/cli/chunks/{fleet-K2ED46EL.js → fleet-GJ66QFXK.js} +3 -3
  212. package/dist/cli/chunks/{gnn-wrapper-QCU4ZRYW.js → gnn-wrapper-52V6ANOY.js} +2 -2
  213. package/dist/cli/chunks/{heartbeat-handler-YYQI4WZM.js → heartbeat-handler-X7NHNRC7.js} +4 -4
  214. package/dist/cli/chunks/heartbeat-scheduler-FSX7A3ZA.js +2 -0
  215. package/dist/cli/chunks/hnsw-adapter-UX2QT6RL.js +2 -0
  216. package/dist/cli/chunks/hnsw-index-WRDDAMXH.js +2 -0
  217. package/dist/cli/chunks/{hnsw-legacy-bridge-C5TJSWTZ.js → hnsw-legacy-bridge-DZBE3KMK.js} +2 -2
  218. package/dist/cli/chunks/{hnswlib-node-SE3MJJYS.js → hnswlib-node-2AWWUJAZ.js} +2 -2
  219. package/dist/cli/chunks/{hooks-C572SRDH.js → hooks-XLPVROL3.js} +10 -10
  220. package/dist/cli/chunks/hybrid-backend-O67NGIB5.js +2 -0
  221. package/dist/cli/chunks/{hypergraph-engine-35A6G3M5.js → hypergraph-engine-6TI7YP6P.js} +2 -2
  222. package/dist/cli/chunks/{hypergraph-handler-U2756CWI.js → hypergraph-handler-DBIBBOXS.js} +3 -3
  223. package/dist/cli/chunks/impact-analyzer-6VXWWYWM.js +2 -0
  224. package/dist/cli/chunks/init-guard-OSO6MIDD.js +2 -0
  225. package/dist/cli/chunks/init-handler-7S7IHMUF.js +88 -0
  226. package/dist/cli/chunks/init-wizard-VH34J4TL.js +2 -0
  227. package/dist/cli/chunks/kernel-KJD24NO7.js +2 -0
  228. package/dist/cli/chunks/{kilocode-installer-32PX5YH7.js → kilocode-installer-2KBRFXMA.js} +2 -2
  229. package/dist/cli/chunks/{kiro-installer-C4ROMMUS.js → kiro-installer-5VFR4OQZ.js} +2 -2
  230. package/dist/cli/chunks/knowledge-graph-343O2HEZ.js +2 -0
  231. package/dist/cli/chunks/{learning-GEPVZGJQ.js → learning-G5NHL3DV.js} +20 -20
  232. package/dist/cli/chunks/{llm-router-XRKTTJTX.js → llm-router-4EAPPMHS.js} +4 -4
  233. package/dist/cli/chunks/llm-router-service-2M4BT2AO.js +2 -0
  234. package/dist/cli/chunks/{load-XVH6HW7E.js → load-UYMZPEY6.js} +2 -2
  235. package/dist/cli/chunks/load-test-OTQ2JQ5F.js +2 -0
  236. package/dist/cli/chunks/{mcp-IULSTM4Z.js → mcp-NOTDZBW5.js} +2 -2
  237. package/dist/cli/chunks/{memory-6K7IAU4T.js → memory-QL53YIHP.js} +5 -5
  238. package/dist/cli/chunks/memory-backend-4QSNRRV6.js +2 -0
  239. package/dist/cli/chunks/{memory-handlers-CG6DRLAW.js → memory-handlers-YFFYRSM6.js} +2 -2
  240. package/dist/cli/chunks/{multi-model-executor-VZDUYPLX.js → multi-model-executor-PDDDXF2B.js} +2 -2
  241. package/dist/cli/chunks/{opencode-installer-QUTXKNH4.js → opencode-installer-75D2SKOT.js} +2 -2
  242. package/dist/cli/chunks/{orchestrator-PCKKUWOP.js → orchestrator-3WIZBV4T.js} +5 -5
  243. package/dist/cli/chunks/pattern-null-store-5USH5MNR.js +2 -0
  244. package/dist/cli/chunks/{pattern-usage-recorder-PX5HQVRL.js → pattern-usage-recorder-TEX2JGHA.js} +2 -2
  245. package/dist/cli/chunks/{pipeline-O562GTOG.js → pipeline-7ATPA6LU.js} +2 -2
  246. package/dist/cli/chunks/{platform-PM7Q2AZS.js → platform-WPSKRJE7.js} +2 -2
  247. package/dist/cli/chunks/{plugin-OTYTFGPY.js → plugin-UUFOVVMU.js} +2 -2
  248. package/dist/cli/chunks/{prime-radiant-advanced-wasm-6CFXTHC2.js → prime-radiant-advanced-wasm-PDFSYWKZ.js} +2 -2
  249. package/dist/cli/chunks/project-root-SRTA6TBL.js +2 -0
  250. package/dist/cli/chunks/protocol-executor-4WYPCNBS.js +2 -0
  251. package/dist/cli/chunks/{protocol-handler-PPGNSAOS.js → protocol-handler-3VRYRIQB.js} +2 -2
  252. package/dist/cli/chunks/{prove-WQ3BKRZG.js → prove-2NAUROGF.js} +2 -2
  253. package/dist/cli/chunks/qe-reasoning-bank-I4D6SFS4.js +2 -0
  254. package/dist/cli/chunks/{quality-C5WUU3AA.js → quality-ZIEI2WGA.js} +2 -2
  255. package/dist/cli/chunks/{quality-gate-WSSRKD5U.js → quality-gate-KWJO4SWQ.js} +3 -3
  256. package/dist/cli/chunks/queen-coordinator-24UMTZTE.js +2 -0
  257. package/dist/cli/chunks/{real-embeddings-CFQE7IRQ.js → real-embeddings-TSZ4UIAE.js} +2 -2
  258. package/dist/cli/chunks/{ref-validation-DHKHXVZT.js → ref-validation-DWFFRETJ.js} +2 -2
  259. package/dist/cli/chunks/{roocode-installer-3PPODABV.js → roocode-installer-XTZHLUBO.js} +2 -2
  260. package/dist/cli/chunks/router-AUD4GATI.js +2 -0
  261. package/dist/cli/chunks/routing-feedback-2FE6SIKQ.js +2 -0
  262. package/dist/cli/chunks/{routing-handler-JNXTGT6T.js → routing-handler-GG525TDM.js} +2 -2
  263. package/dist/cli/chunks/{ruvector-commands-6YLROPVP.js → ruvector-commands-QKRJDM7Z.js} +2 -2
  264. package/dist/cli/chunks/rvf-dual-writer-P5LEUF25.js +2 -0
  265. package/dist/cli/chunks/rvf-migration-adapter-ZCYD5YJS.js +2 -0
  266. package/dist/cli/chunks/{rvf-migration-coordinator-4DWB4WRK.js → rvf-migration-coordinator-FF52OS6Q.js} +2 -2
  267. package/dist/cli/chunks/rvf-native-adapter-QGV6BW2W.js +2 -0
  268. package/dist/cli/chunks/{rvf-store-integrity-YKR2ZNBF.js → rvf-store-integrity-M6DXTAZ4.js} +2 -2
  269. package/dist/cli/chunks/safe-db-Q6JUKG2A.js +2 -0
  270. package/dist/cli/chunks/schedule-44OSMGE5.js +2 -0
  271. package/dist/cli/chunks/scheduler-V3HO2QQT.js +2 -0
  272. package/dist/cli/chunks/security-EHXSW22U.js +18 -0
  273. package/dist/cli/chunks/{shared-rvf-adapter-LNRLFP5I.js → shared-rvf-adapter-6EH7UVJL.js} +2 -2
  274. package/dist/cli/chunks/{shared-rvf-dual-writer-GWU6YQNS.js → shared-rvf-dual-writer-WML274E7.js} +2 -2
  275. package/dist/cli/chunks/sqlite-persistence-N5T7DWMR.js +2 -0
  276. package/dist/cli/chunks/{standalone-memory-46KKBSSV.js → standalone-memory-C7QKAXS4.js} +2 -2
  277. package/dist/cli/chunks/{status-handler-35T5FTDQ.js → status-handler-VLI7MRLM.js} +2 -2
  278. package/dist/cli/chunks/{structural-health-P7QPQWLO.js → structural-health-3LPG6MQN.js} +2 -2
  279. package/dist/cli/chunks/{sync-Y43EWBSY.js → sync-4IMMQEPT.js} +2 -2
  280. package/dist/cli/chunks/{sync-W6Z4R4PL.js → sync-JFJEJBVK.js} +2 -2
  281. package/dist/cli/chunks/{task-handler-5CX3ZYT7.js → task-handler-IED3K6E4.js} +2 -2
  282. package/dist/cli/chunks/{task-handlers-DQZGOJNE.js → task-handlers-FH6DNTHW.js} +3 -3
  283. package/dist/cli/chunks/{test-TPP53VVV.js → test-GPKT3CKZ.js} +4 -4
  284. package/dist/cli/chunks/{test-scheduling-WBV4UMQH.js → test-scheduling-Z42XXZP6.js} +3 -3
  285. package/dist/cli/chunks/{token-bootstrap-GIIDXHLC.js → token-bootstrap-HMM3AHXM.js} +2 -2
  286. package/dist/cli/chunks/{token-usage-AKK37RB7.js → token-usage-6Y2ERYIY.js} +2 -2
  287. package/dist/cli/chunks/{transformers-7MASPELS.js → transformers-MB63T2XO.js} +2 -2
  288. package/dist/cli/chunks/{tree-sitter-wasm-parser-YZKD6UGB.js → tree-sitter-wasm-parser-56GDQCMR.js} +2 -2
  289. package/dist/cli/chunks/{types-AZ3BTXDP.js → types-J4J6QV3I.js} +2 -2
  290. package/dist/cli/chunks/unified-memory-RQ3Q4CU3.js +2 -0
  291. package/dist/cli/chunks/unified-memory-hnsw-ZOP5FEYX.js +2 -0
  292. package/dist/cli/chunks/unified-persistence-72OCJJKK.js +2 -0
  293. package/dist/cli/chunks/{upgrade-L7OTDKEK.js → upgrade-U4XU7LFM.js} +2 -2
  294. package/dist/cli/chunks/{validate-O3QVFIGP.js → validate-B57HA4YK.js} +2 -2
  295. package/dist/cli/chunks/{validate-swarm-2UGBGLTX.js → validate-swarm-UPPA4M6T.js} +2 -2
  296. package/dist/cli/chunks/visual-security-7F5UV23J.js +2 -0
  297. package/dist/cli/chunks/{web-tree-sitter-J75IYPRO.js → web-tree-sitter-GDZMUKOZ.js} +2 -2
  298. package/dist/cli/chunks/{windsurf-installer-FQ5DBFCG.js → windsurf-installer-VJRWCHXP.js} +2 -2
  299. package/dist/cli/chunks/witness-chain-KZ57QUFE.js +2 -0
  300. package/dist/cli/chunks/{witness-chain-I7TN4MXZ.js → witness-chain-LFASSMZK.js} +2 -2
  301. package/dist/cli/chunks/{witness-chain-repair-D3NE3NQK.js → witness-chain-repair-TPHN4DXN.js} +2 -2
  302. package/dist/cli/chunks/{witness-chain-verifier-RU2WOP5M.js → witness-chain-verifier-Z23FVABW.js} +2 -2
  303. package/dist/cli/chunks/{witness-key-manager-IHQB2FR5.js → witness-key-manager-745MJ7WO.js} +2 -2
  304. package/dist/cli/chunks/{workflow-6BWTNVV6.js → workflow-T245QNQM.js} +4 -4
  305. package/dist/cli/chunks/workflow-orchestrator-ZNWEUYBN.js +2 -0
  306. package/dist/cli/chunks/{wrappers-URVP25VU.js → wrappers-WCAYIQUX.js} +2 -2
  307. package/dist/cli/commands/learning.js +3 -2
  308. package/dist/cli/commands/security.d.ts +16 -0
  309. package/dist/cli/commands/security.js +76 -9
  310. package/dist/cli/handlers/init-guard.d.ts +21 -1
  311. package/dist/cli/handlers/init-guard.js +51 -8
  312. package/dist/cli/handlers/init-handler.js +57 -56
  313. package/dist/cli/index.js +11 -0
  314. package/dist/cli/utils/ci-output.d.ts +5 -0
  315. package/dist/cli/utils/ci-output.js +8 -0
  316. package/dist/coordination/handlers/security-handlers.js +22 -6
  317. package/dist/coordination/protocols/defect-investigation.js +7 -1
  318. package/dist/coordination/protocols/learning-consolidation.js +6 -12
  319. package/dist/coordination/protocols/security-audit.js +11 -0
  320. package/dist/coordination/result-saver.d.ts +9 -0
  321. package/dist/coordination/result-saver.js +34 -4
  322. package/dist/domains/coverage-analysis/collected-metrics.d.ts +2 -0
  323. package/dist/domains/coverage-analysis/collected-metrics.js +8 -1
  324. package/dist/domains/defect-intelligence/services/defect-predictor.js +9 -6
  325. package/dist/domains/learning-optimization/active-patterns.d.ts +55 -0
  326. package/dist/domains/learning-optimization/active-patterns.js +77 -0
  327. package/dist/domains/learning-optimization/coordinator.js +12 -9
  328. package/dist/domains/learning-optimization/services/learning-coordinator.js +15 -17
  329. package/dist/domains/quality-assessment/interfaces.d.ts +4 -0
  330. package/dist/domains/quality-assessment/quality-evidence.d.ts +1 -1
  331. package/dist/domains/quality-assessment/services/quality-analyzer.js +7 -5
  332. package/dist/domains/quality-assessment/services/quality-gate.js +12 -3
  333. package/dist/domains/security-compliance/dependency-advisory-engine.d.ts +52 -0
  334. package/dist/domains/security-compliance/dependency-advisory-engine.js +113 -0
  335. package/dist/domains/security-compliance/interfaces.d.ts +30 -0
  336. package/dist/domains/security-compliance/plugin.d.ts +7 -1
  337. package/dist/domains/security-compliance/plugin.js +19 -0
  338. package/dist/domains/security-compliance/services/scanners/dependency-resolver.d.ts +71 -0
  339. package/dist/domains/security-compliance/services/scanners/dependency-resolver.js +232 -0
  340. package/dist/domains/security-compliance/services/scanners/dependency-scanner.d.ts +21 -6
  341. package/dist/domains/security-compliance/services/scanners/dependency-scanner.js +142 -64
  342. package/dist/domains/security-compliance/services/scanners/lockfile-versions.d.ts +43 -0
  343. package/dist/domains/security-compliance/services/scanners/lockfile-versions.js +248 -0
  344. package/dist/domains/security-compliance/services/scanners/scanner-types.d.ts +30 -2
  345. package/dist/domains/security-compliance/services/security-auditor.d.ts +19 -6
  346. package/dist/domains/security-compliance/services/security-auditor.js +133 -92
  347. package/dist/domains/test-execution/services/retry-handler.js +34 -7
  348. package/dist/domains/test-execution/services/test-executor.d.ts +1 -0
  349. package/dist/domains/test-execution/services/test-executor.js +87 -7
  350. package/dist/kernel/shared-dirs.js +17 -5
  351. package/dist/learning/dream/dream-engine.d.ts +27 -1
  352. package/dist/learning/dream/dream-engine.js +56 -2
  353. package/dist/learning/dream/rvcow-branch-manager.d.ts +8 -0
  354. package/dist/learning/dream/rvcow-branch-manager.js +8 -0
  355. package/dist/learning/dream/speculative-dreamer.d.ts +8 -0
  356. package/dist/learning/dream/speculative-dreamer.js +8 -0
  357. package/dist/mcp/background-workers.d.ts +15 -0
  358. package/dist/mcp/background-workers.js +71 -0
  359. package/dist/mcp/bundle.js +881 -878
  360. package/dist/mcp/entry.js +4 -49
  361. package/dist/mcp/handlers/domain-handler-configs.d.ts +4 -0
  362. package/dist/mcp/handlers/domain-handler-configs.js +5 -1
  363. package/dist/mcp/protocol-server.js +2 -1
  364. package/dist/mcp/types.d.ts +6 -0
  365. package/dist/shared/security/index.d.ts +2 -2
  366. package/dist/shared/security/index.js +1 -1
  367. package/dist/shared/security/osv-client.d.ts +79 -132
  368. package/dist/shared/security/osv-client.js +344 -167
  369. package/dist/shared/security/osv-lookup.d.ts +124 -0
  370. package/dist/shared/security/osv-lookup.js +246 -0
  371. package/dist/shared/security/osv-types.d.ts +119 -0
  372. package/dist/shared/security/osv-types.js +6 -0
  373. package/dist/workers/daemon.d.ts +5 -0
  374. package/dist/workers/daemon.js +16 -2
  375. package/dist/workers/interfaces.d.ts +6 -1
  376. package/dist/workers/namespaced-keys.d.ts +16 -0
  377. package/dist/workers/namespaced-keys.js +24 -0
  378. package/dist/workers/quality-daemon/persistent-memory.d.ts +1 -1
  379. package/dist/workers/quality-daemon/persistent-memory.js +2 -2
  380. package/dist/workers/worker-env.d.ts +45 -0
  381. package/dist/workers/worker-env.js +76 -0
  382. package/dist/workers/worker-manager.js +5 -2
  383. package/dist/workers/workers/defect-predictor.d.ts +25 -8
  384. package/dist/workers/workers/defect-predictor.js +223 -216
  385. package/dist/workers/workers/learning-consolidation.d.ts +20 -0
  386. package/dist/workers/workers/learning-consolidation.js +53 -22
  387. package/dist/workers/workers/performance-baseline.d.ts +24 -9
  388. package/dist/workers/workers/performance-baseline.js +187 -230
  389. package/dist/workers/workers/quality-gate.d.ts +11 -9
  390. package/dist/workers/workers/quality-gate.js +125 -267
  391. package/dist/workers/workers/security-scan-records.d.ts +111 -0
  392. package/dist/workers/workers/security-scan-records.js +128 -0
  393. package/dist/workers/workers/security-scan.d.ts +25 -7
  394. package/dist/workers/workers/security-scan.js +187 -164
  395. package/package.json +2 -2
  396. package/dist/cli/chunks/adapter-PP3XIXDV.js +0 -2
  397. package/dist/cli/chunks/aqe-learning-engine-VDUQJKKY.js +0 -2
  398. package/dist/cli/chunks/base-QSYWWPCE.js +0 -2
  399. package/dist/cli/chunks/browser-workflow-WXXPBSCM.js +0 -2
  400. package/dist/cli/chunks/chunk-45MVRQG4.js +0 -2
  401. package/dist/cli/chunks/chunk-5VZVMO7B.js +0 -3
  402. package/dist/cli/chunks/chunk-EECF4CMA.js +0 -2
  403. package/dist/cli/chunks/client-6XKSQ4JT.js +0 -2
  404. package/dist/cli/chunks/core-handlers-OJYW4Y6M.js +0 -2
  405. package/dist/cli/chunks/cross-domain-router-QVUPQ2SC.js +0 -2
  406. package/dist/cli/chunks/daemon-QBYTCIMH.js +0 -10
  407. package/dist/cli/chunks/dream-3UABDRZJ.js +0 -2
  408. package/dist/cli/chunks/file-discovery-ZFGZTKZ4.js +0 -2
  409. package/dist/cli/chunks/heartbeat-scheduler-MJ6MTPDF.js +0 -2
  410. package/dist/cli/chunks/hnsw-adapter-FQWJCFVW.js +0 -2
  411. package/dist/cli/chunks/hnsw-index-NJYKJUHC.js +0 -2
  412. package/dist/cli/chunks/hybrid-backend-SL7RFID7.js +0 -2
  413. package/dist/cli/chunks/impact-analyzer-5ZJTXPVC.js +0 -2
  414. package/dist/cli/chunks/init-handler-PCLYQUSB.js +0 -88
  415. package/dist/cli/chunks/init-wizard-MQMDSIOF.js +0 -2
  416. package/dist/cli/chunks/kernel-MEJ5GMRH.js +0 -2
  417. package/dist/cli/chunks/knowledge-graph-XUBZSEZE.js +0 -2
  418. package/dist/cli/chunks/llm-router-service-QZAPAEPX.js +0 -2
  419. package/dist/cli/chunks/load-test-OVXIQ3AF.js +0 -2
  420. package/dist/cli/chunks/memory-backend-TRPOMPK4.js +0 -2
  421. package/dist/cli/chunks/pattern-null-store-JWYBRBZG.js +0 -2
  422. package/dist/cli/chunks/project-root-VVSTHIP4.js +0 -2
  423. package/dist/cli/chunks/protocol-executor-PXZCLZD3.js +0 -2
  424. package/dist/cli/chunks/qe-reasoning-bank-42FRS5V3.js +0 -2
  425. package/dist/cli/chunks/queen-coordinator-UI3B7DI6.js +0 -2
  426. package/dist/cli/chunks/router-HYRPWLAY.js +0 -2
  427. package/dist/cli/chunks/routing-feedback-BPZ5R6F3.js +0 -2
  428. package/dist/cli/chunks/rvf-dual-writer-DEKDQ6KO.js +0 -2
  429. package/dist/cli/chunks/rvf-migration-adapter-L53VBS7I.js +0 -2
  430. package/dist/cli/chunks/rvf-native-adapter-I6RUGD2D.js +0 -2
  431. package/dist/cli/chunks/safe-db-KS65XDCP.js +0 -2
  432. package/dist/cli/chunks/schedule-KD2VN6GB.js +0 -2
  433. package/dist/cli/chunks/scheduler-ZH3RMUHY.js +0 -2
  434. package/dist/cli/chunks/security-PWQTGDRU.js +0 -13
  435. package/dist/cli/chunks/sqlite-persistence-6DTVME5D.js +0 -2
  436. package/dist/cli/chunks/unified-memory-FCX7NLFZ.js +0 -2
  437. package/dist/cli/chunks/unified-memory-hnsw-VU5QJK37.js +0 -2
  438. package/dist/cli/chunks/unified-persistence-FM376LGE.js +0 -2
  439. package/dist/cli/chunks/visual-security-EU7Y3X46.js +0 -2
  440. package/dist/cli/chunks/witness-chain-CSEBT52D.js +0 -2
  441. package/dist/cli/chunks/workflow-orchestrator-ALNKOM3N.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{l as d}from"./chunk-5HAPS6VD.js";import{a as u,e as g}from"./chunk-KYVIOC3C.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{l as d}from"./chunk-TC52M542.js";import{a as u,e as g}from"./chunk-J7FLNP5L.js";g();var m=[{type:"email",pattern:/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,mask:n=>n[0]+"***@"+n.split("@")[1]},{type:"ssn",pattern:/\b\d{3}-\d{2}-\d{4}\b/g,mask:()=>"***-**-****"},{type:"credit-card",pattern:/\b(?:\d[ -]*?){13,19}\b/g,mask:n=>"****-****-****-"+n.replace(/\D/g,"").slice(-4)},{type:"phone",pattern:/\b(?:\+?1[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)?\d{3}[-.\s]?\d{4}\b/g,mask:n=>n.slice(0,3)+"***"+n.slice(-2)},{type:"api-key",pattern:/(?:key|token|api_key|apikey|secret|password|passwd|auth)=([A-Za-z0-9_\-]{16,})/gi,mask:()=>"***REDACTED***"}],y=class extends d{config={name:"qe/security/url-validate",description:"Validate URL security: checks for XSS/injection patterns, unsafe protocols, and scans URL query parameters for PII exposure (emails, SSNs, credit cards, API keys).",domain:"security-compliance",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{url:{type:"string",description:"URL to validate for security threats and PII exposure"},enablePII:{type:"boolean",description:"Enable PII exposure scanning in URL and query parameters",default:!0}},required:["url"]}}async execute(s,r){try{let e=this.validateURLSecurity(s.url),t=s.enablePII!==!1?this.scanForPII(s.url):{scanned:!1,found:!1,types:[],details:[]},c=e.issues.length+(t.found?t.types.length:0)===0?`URL passed all checks (security: clean, PII: ${t.scanned?"none found":"not scanned"})`:`URL has ${e.issues.length} security issue(s)${t.found?` and ${t.types.length} PII type(s) exposed in URL`:""}`;return{success:!0,data:{url:s.url,urlSecurity:e,piiExposure:t,summary:c}}}catch(e){return{success:!1,error:u(e)}}}validateURLSecurity(s){let r=[],e="none";try{let t=new URL(s);["http:","https:"].includes(t.protocol)||(r.push({type:"unsafe-protocol",description:`Protocol ${t.protocol} is not allowed`,severity:"high"}),e="high");let o=[/<script/i,/javascript:/i,/on\w+=/i,/data:text\/html/i];for(let i of o)if(i.test(s)){r.push({type:"xss",description:"Potential XSS pattern detected in URL",severity:"critical"}),e="critical";break}let c=[/'.*or.*'/i,/union.*select/i,/drop.*table/i,/;\s*--/i];for(let i of c)if(i.test(s)){r.push({type:"sql-injection",description:"Potential SQL injection pattern detected in URL",severity:"critical"}),e="critical";break}/\.\.[/\\]/.test(s)&&(r.push({type:"path-traversal",description:"Potential path traversal pattern (../) detected",severity:"high"}),e!=="critical"&&(e="high"));let a=["redirect","url","next","return","returnUrl","goto"];for(let i of a){let l=t.searchParams.get(i);l&&/^https?:\/\//.test(l)&&(r.push({type:"open-redirect",description:`Query parameter "${i}" contains an external URL \u2014 potential open redirect`,severity:"medium"}),e==="none"&&(e="medium"))}}catch{r.push({type:"invalid-url",description:"URL could not be parsed",severity:"critical"}),e="critical"}return{valid:r.length===0,riskLevel:e,issues:r}}scanForPII(s){let r=[],e=new Set,t;try{t=decodeURIComponent(s)}catch{t=s}let o="",c="";try{let a=new URL(t);o=a.search,c=a.pathname}catch{o=t}for(let{type:a,pattern:i,mask:l}of m){i.lastIndex=0;let p;for(;(p=i.exec(t))!==null;){e.add(a);let h=o.includes(p[0])?"query-parameter":c.includes(p[0])?"path":"url";r.push({type:a,location:h,masked:l(p[0])})}}return{scanned:!0,found:e.size>0,types:Array.from(e),details:r}}};export{y as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{a as c,e as h}from"./chunk-5LST62QR.js";import{a as l,d}from"./chunk-5MT7DMD7.js";d();h();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),c.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*c.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=c.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s.replace(/\*/g,".*").replace(/\?/g,".")}$`,"su"),i=[],o=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys()){if(o&&!a.startsWith(o))continue;let p=o?a.slice(o.length):a;if(n.test(p)&&(i.push(a),i.length>=r))break}return i}async vectorSearch(t,r,e){let s=[];for(let[n,i]of this.vectors.entries()){if(e&&!n.startsWith(e))continue;let o=l(t,i.embedding);s.push({key:n,score:o,metadata:i.metadata})}return s.sort((n,i)=>i.score-n.score).slice(0,r)}getVectorSearchProvenance(){return{backend:"in-memory",indexType:"flat",approximate:!1,estimatedRecall:1}}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{a as c,e as h}from"./chunk-DN3AKAPY.js";import{a as l,d}from"./chunk-A2UGPKCS.js";d();h();var u=class{store=new Map;vectors=new Map;cleanupInterval;async initialize(){this.cleanupInterval=setInterval(()=>this.cleanup(),c.CLEANUP_INTERVAL_MS),this.cleanupInterval.unref&&this.cleanupInterval.unref()}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.store.clear(),this.vectors.clear()}async set(t,r,e){let s={value:r,namespace:e?.namespace??"default",createdAt:Date.now()};e?.ttl&&(s.expiresAt=Date.now()+e.ttl*c.TTL_MULTIPLIER_MS);let n=this.buildKey(t,e?.namespace);this.store.set(n,s)}async get(t,r){let e=this.buildKey(t,r?.namespace),s=this.store.get(e);if(s){if(s.expiresAt&&Date.now()>s.expiresAt){this.store.delete(e);return}return s.value}}async delete(t,r){let e=this.buildKey(t,r?.namespace);return this.store.delete(e)}async has(t,r){return await this.get(t,r)!==void 0}async search(t,r=c.DEFAULT_SEARCH_LIMIT,e){let s=t.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`^${s.replace(/\*/g,".*").replace(/\?/g,".")}$`,"su"),i=[],o=e?.namespace?`${e.namespace}:`:void 0;for(let a of this.store.keys()){if(o&&!a.startsWith(o))continue;let p=o?a.slice(o.length):a;if(n.test(p)&&(i.push(a),i.length>=r))break}return i}async vectorSearch(t,r,e){let s=[];for(let[n,i]of this.vectors.entries()){if(e&&!n.startsWith(e))continue;let o=l(t,i.embedding);s.push({key:n,score:o,metadata:i.metadata})}return s.sort((n,i)=>i.score-n.score).slice(0,r)}getVectorSearchProvenance(){return{backend:"in-memory",indexType:"flat",approximate:!1,estimatedRecall:1}}async storeVector(t,r,e){this.vectors.set(t,{embedding:r,metadata:e})}buildKey(t,r){return r?`${r}:${t}`:t}cleanup(){let t=Date.now();for(let[r,e]of this.store.entries())e.expiresAt&&t>e.expiresAt&&this.store.delete(r)}getStats(){return{entries:this.store.size,vectors:this.vectors.size}}async clear(t){if(t){let r=`${t}:`;for(let e of this.store.keys())e.startsWith(r)&&this.store.delete(e)}else this.store.clear()}async count(t){let r=0,e=`${t}:`;for(let s of this.store.keys())if(s.startsWith(e)){let n=this.store.get(s);n&&(!n.expiresAt||Date.now()<=n.expiresAt)&&r++}return r}async hasCodeIntelligenceIndex(){return await this.count("code-intelligence:kg")>0}};export{u as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{a as q}from"./chunk-EJ4KZFZN.js";import{g as O,h as X,i as L,j as k,o as I,s as B}from"./chunk-YNG7E26C.js";import{b as h,d as x}from"./chunk-22OZIJAD.js";import{a as y,b as A,h as f,l as C,n as D,p as g}from"./chunk-XFPQIWEH.js";import{i as w}from"./chunk-IVJIHZSM.js";import{a as _,e as U}from"./chunk-KYVIOC3C.js";import{a as N,b as v}from"./chunk-AJT3XDRD.js";v();x();U();B();X();k();var H={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function ee(l,e=384){let t=new Array(e).fill(0),n=l.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<n.length;s++){let i=n.charCodeAt(s),o=i*(s+1)*(a+1)%e;t[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(t.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)t[a]/=r;return t}function P(l){return l.normalize("NFKD").replace(/\p{M}+/gu,"").toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}var S=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...H,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=I(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),t=await import("fs"),n=e.dirname(this.config.dbPath);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),this.db=N(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),L(this.db,{logPrefix:"[SQLitePatternStore]"}),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.ensureEmbeddingSpaceSchema(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{a as q}from"./chunk-GSOK4M6V.js";import{g as O,h as X,i as L,j as k,o as I,s as B}from"./chunk-7XGM7Q2N.js";import{b as h,d as x}from"./chunk-FWXNFPLS.js";import{a as y,b as A,h as f,l as C,n as D,p as g}from"./chunk-BEVWCF3Q.js";import{i as w}from"./chunk-PICEGWGB.js";import{a as _,e as U}from"./chunk-J7FLNP5L.js";import{a as N,b as v}from"./chunk-LPSMVBB3.js";v();x();U();B();X();k();var H={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:256*1024*1024,cacheSize:-64e3,foreignKeys:!0,useUnified:!0};function ee(l,e=384){let t=new Array(e).fill(0),n=l.toLowerCase().trim();for(let a=0;a<3;a++)for(let s=0;s<n.length;s++){let i=n.charCodeAt(s),o=i*(s+1)*(a+1)%e;t[o]+=Math.sin(i*(a+1))/(s+1)}let r=Math.sqrt(t.reduce((a,s)=>a+s*s,0));if(r>0)for(let a=0;a<e;a++)t[a]/=r;return t}function P(l){return l.normalize("NFKD").replace(/\p{M}+/gu,"").toLowerCase().match(/[\p{L}\p{N}]+/gu)??[]}var S=class{db=null;config;prepared=new Map;initialized=!1;unifiedMemory=null;constructor(e={}){this.config={...H,...e}}getDatabase(){return this.db}async initialize(){if(!this.initialized)try{if(this.config.useUnified)this.unifiedMemory=I(),await this.unifiedMemory.initialize(),this.db=this.unifiedMemory.getDatabase(),console.log(`[SQLitePatternStore] Using unified storage: ${this.unifiedMemory.getDbPath()}`);else{let e=await import("path"),t=await import("fs"),n=e.dirname(this.config.dbPath);t.existsSync(n)||t.mkdirSync(n,{recursive:!0}),this.db=N(this.config.dbPath),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.config.foreignKeys&&this.db.pragma("foreign_keys = ON"),L(this.db,{logPrefix:"[SQLitePatternStore]"}),this.createSchema(),console.log(`[SQLitePatternStore] Initialized (legacy): ${this.config.dbPath}`)}this.deduplicatePatterns(),this.ensureEmbeddingSpaceSchema(),this.prepareStatements(),this.initialized=!0}catch(e){throw new Error(`Failed to initialize SQLite: ${_(e)}`)}}createSchema(){if(!this.db)throw new Error("Database not initialized");this.db.exec(`
3
3
  -- QE Patterns table
4
4
  CREATE TABLE IF NOT EXISTS qe_patterns (
5
5
  id TEXT PRIMARY KEY,
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
2
  var e=!1;function o(){e=!0;let r=!1;return()=>{r||(r=!0,e=!1)}}function t(){return e}export{o as a,t as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{a as w}from"./chunk-4CLDYT36.js";import{i as v}from"./chunk-IVJIHZSM.js";import{c as p,d as l}from"./chunk-QLKUCMZC.js";import{a as g,b as x,e as y}from"./chunk-KYVIOC3C.js";y();var h=class extends Error{constructor(e){super(`Action timed out after ${e}ms; outcome is unknown`),this.name="ActionTimeoutError"}},m={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolOutcomeUnknown:"coordination.ProtocolOutcomeUnknown",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed",ActionOutcomeUnknown:"coordination.ActionOutcomeUnknown"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):l(new Error(`Protocol is disabled: ${e}`)):l(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):l(new Error(`Protocol is disabled: ${e}`)):l(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?l(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(m.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):l(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?l(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):l(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?l(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):l(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let n=v(),a=o?.correlationId??n,i={executionId:n,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},d={execution:i,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(n,d),await this.publishEvent(m.ProtocolStarted,{executionId:n,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(d);let r=Array.from(d.actionResults.values()),s=r.filter(c=>c.status==="unknown").map(c=>c.actionId),u=r.filter(c=>c.status==="failed").map(c=>c.actionId);return d.cancelled?i.status="cancelled":s.length>0?(i.status="unknown",await this.publishEvent(m.ProtocolOutcomeUnknown,{executionId:n,protocolId:e.id,unknownActions:s,failedActions:u},a)):u.length>0?(i.status="failed",await this.publishEvent(m.ProtocolFailed,{executionId:n,protocolId:e.id,failedActions:u},a)):(i.status="completed",await this.publishEvent(m.ProtocolCompleted,{executionId:n,protocolId:e.id,duration:Date.now()-i.startedAt.getTime()},a)),i.completedAt=new Date,i.results=d.actionResults,await this.storeExecutionHistory(i),p(this.toImmutableExecution(i))}catch(r){return i.status="failed",i.completedAt=new Date,await this.publishEvent(m.ProtocolFailed,{executionId:n,protocolId:e.id,error:g(r)},a),l(x(r))}}async executeActions(e){let{protocol:t,actionResults:o}=e,n=new Set(t.actions.map(i=>i.id)),a=new Set;for(;n.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let i=t.actions.filter(r=>n.has(r.id)&&this.dependenciesSatisfied(r,a));if(i.length===0&&n.size>0){let r=!1;for(let s of t.actions)n.has(s.id)&&s.dependsOn?.some(u=>{let c=o.get(u)?.status;return c!==void 0&&c!=="completed"})&&(o.set(s.id,{actionId:s.id,status:"skipped"}),n.delete(s.id),r=!0);if(r)continue;throw new Error(`Deadlock detected: actions ${Array.from(n).join(", ")} cannot proceed`)}let d=await Promise.allSettled(i.map(r=>this.executeAction(r,e)));for(let r=0;r<i.length;r++){let s=i[r],u=d[r],c;u.status==="fulfilled"?c=u.value:c={actionId:s.id,status:"failed",error:u.reason instanceof Error?u.reason.message:String(u.reason)},o.set(s.id,c),n.delete(s.id),c.status==="completed"&&a.add(s.id)}}for(let i of n)o.set(i,{actionId:i,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(m.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let n=0,a=e.retry?.maxAttempts??1,i;for(;n<a;){n++;try{let r=this.getDomainAPI(e.targetDomain);if(!r)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=r[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let u={...e.params,...t.params},c=await this.executeWithTimeout(s.bind(r)(u),e.timeout??3e4),P=new Date;return await this.publishEvent(m.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:P.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:P,duration:P.getTime()-o.getTime(),result:c,retryAttempts:n>1?n-1:void 0}}catch(r){if(i=x(r),r instanceof h){let s=new Date;return await this.publishEvent(m.ActionOutcomeUnknown,{executionId:t.execution.executionId,actionId:e.id,error:r.message,attempts:n},t.execution.correlationId),{actionId:e.id,status:"unknown",startedAt:o,completedAt:s,duration:s.getTime()-o.getTime(),error:r.message,retryAttempts:n>1?n-1:void 0}}if(n<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,n-1);await this.sleep(s)}}}let d=new Date;return await this.publishEvent(m.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:i?.message??"Unknown error",attempts:n},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:d,duration:d.getTime()-o.getTime(),error:i?.message??"Unknown error",retryAttempts:n>1?n-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){let o;try{return await Promise.race([e,new Promise((n,a)=>{o=setTimeout(()=>a(new h(t)),t)})])}finally{o&&clearTimeout(o)}}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:86400})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let n=w(e,"learning-optimization",t,o);await this.eventBus.publish(n)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(f,e,t){return new E(f,e,t)}export{E as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{a as w}from"./chunk-NQDYOF35.js";import{i as v}from"./chunk-PICEGWGB.js";import{c as p,d as l}from"./chunk-YTYS2XSY.js";import{a as g,b as x,e as y}from"./chunk-J7FLNP5L.js";y();var h=class extends Error{constructor(e){super(`Action timed out after ${e}ms; outcome is unknown`),this.name="ActionTimeoutError"}},m={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolOutcomeUnknown:"coordination.ProtocolOutcomeUnknown",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed",ActionOutcomeUnknown:"coordination.ActionOutcomeUnknown"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):l(new Error(`Protocol is disabled: ${e}`)):l(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):l(new Error(`Protocol is disabled: ${e}`)):l(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?l(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(m.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):l(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?l(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):l(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?l(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):l(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let n=v(),a=o?.correlationId??n,i={executionId:n,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},d={execution:i,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(n,d),await this.publishEvent(m.ProtocolStarted,{executionId:n,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(d);let r=Array.from(d.actionResults.values()),s=r.filter(c=>c.status==="unknown").map(c=>c.actionId),u=r.filter(c=>c.status==="failed").map(c=>c.actionId);return d.cancelled?i.status="cancelled":s.length>0?(i.status="unknown",await this.publishEvent(m.ProtocolOutcomeUnknown,{executionId:n,protocolId:e.id,unknownActions:s,failedActions:u},a)):u.length>0?(i.status="failed",await this.publishEvent(m.ProtocolFailed,{executionId:n,protocolId:e.id,failedActions:u},a)):(i.status="completed",await this.publishEvent(m.ProtocolCompleted,{executionId:n,protocolId:e.id,duration:Date.now()-i.startedAt.getTime()},a)),i.completedAt=new Date,i.results=d.actionResults,await this.storeExecutionHistory(i),p(this.toImmutableExecution(i))}catch(r){return i.status="failed",i.completedAt=new Date,await this.publishEvent(m.ProtocolFailed,{executionId:n,protocolId:e.id,error:g(r)},a),l(x(r))}}async executeActions(e){let{protocol:t,actionResults:o}=e,n=new Set(t.actions.map(i=>i.id)),a=new Set;for(;n.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let i=t.actions.filter(r=>n.has(r.id)&&this.dependenciesSatisfied(r,a));if(i.length===0&&n.size>0){let r=!1;for(let s of t.actions)n.has(s.id)&&s.dependsOn?.some(u=>{let c=o.get(u)?.status;return c!==void 0&&c!=="completed"})&&(o.set(s.id,{actionId:s.id,status:"skipped"}),n.delete(s.id),r=!0);if(r)continue;throw new Error(`Deadlock detected: actions ${Array.from(n).join(", ")} cannot proceed`)}let d=await Promise.allSettled(i.map(r=>this.executeAction(r,e)));for(let r=0;r<i.length;r++){let s=i[r],u=d[r],c;u.status==="fulfilled"?c=u.value:c={actionId:s.id,status:"failed",error:u.reason instanceof Error?u.reason.message:String(u.reason)},o.set(s.id,c),n.delete(s.id),c.status==="completed"&&a.add(s.id)}}for(let i of n)o.set(i,{actionId:i,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(m.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let n=0,a=e.retry?.maxAttempts??1,i;for(;n<a;){n++;try{let r=this.getDomainAPI(e.targetDomain);if(!r)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=r[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let u={...e.params,...t.params},c=await this.executeWithTimeout(s.bind(r)(u),e.timeout??3e4),P=new Date;return await this.publishEvent(m.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:P.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:P,duration:P.getTime()-o.getTime(),result:c,retryAttempts:n>1?n-1:void 0}}catch(r){if(i=x(r),r instanceof h){let s=new Date;return await this.publishEvent(m.ActionOutcomeUnknown,{executionId:t.execution.executionId,actionId:e.id,error:r.message,attempts:n},t.execution.correlationId),{actionId:e.id,status:"unknown",startedAt:o,completedAt:s,duration:s.getTime()-o.getTime(),error:r.message,retryAttempts:n>1?n-1:void 0}}if(n<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,n-1);await this.sleep(s)}}}let d=new Date;return await this.publishEvent(m.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:i?.message??"Unknown error",attempts:n},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:d,duration:d.getTime()-o.getTime(),error:i?.message??"Unknown error",retryAttempts:n>1?n-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){let o;try{return await Promise.race([e,new Promise((n,a)=>{o=setTimeout(()=>a(new h(t)),t)})])}finally{o&&clearTimeout(o)}}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:86400})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let n=w(e,"learning-optimization",t,o);await this.eventBus.publish(n)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(f,e,t){return new E(f,e,t)}export{E as a,S as b};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{b as v,d as S}from"./chunk-D5N2O5EH.js";import{b as l}from"./chunk-7SAMMQVS.js";function A(o){return o.replace(w,(e,t,i,n)=>x(i)?`${t}${i}${t}${n}${t}<REDACTED:sensitive-key>${t}`:e)}function x(o){let e=o.toLowerCase().replace(/[^a-z0-9]/g,"");return D.has(e)||N.some(t=>e.endsWith(t))}function a(o,e=E.maxStringLength){if(typeof o!="string")return _(o);if(o.length>O)return`[REDACTED:size-limit ${o.length} chars]`;let t=o;for(let[i,n]of k)t=t.replace(i,n);return t=A(t),t=v(t,"balanced").text,t.length>e?`${t.slice(0,e)}\u2026[truncated ${t.length-e} chars]`:t}function u(o,e={}){return f(o,{...E,...e},0,[])}function _(o){try{if(o instanceof Error){let e=a(o.stack||`${o.name}: ${o.message}`),t=o.cause;for(let i=0;t!==void 0&&i<3;i++)e+=`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{b as v,d as S}from"./chunk-NHOMVBCI.js";import{b as l}from"./chunk-K5R3WUJP.js";function A(o){return o.replace(w,(e,t,i,n)=>x(i)?`${t}${i}${t}${n}${t}<REDACTED:sensitive-key>${t}`:e)}function x(o){let e=o.toLowerCase().replace(/[^a-z0-9]/g,"");return D.has(e)||N.some(t=>e.endsWith(t))}function a(o,e=E.maxStringLength){if(typeof o!="string")return _(o);if(o.length>O)return`[REDACTED:size-limit ${o.length} chars]`;let t=o;for(let[i,n]of k)t=t.replace(i,n);return t=A(t),t=v(t,"balanced").text,t.length>e?`${t.slice(0,e)}\u2026[truncated ${t.length-e} chars]`:t}function u(o,e={}){return f(o,{...E,...e},0,[])}function _(o){try{if(o instanceof Error){let e=a(o.stack||`${o.name}: ${o.message}`),t=o.cause;for(let i=0;t!==void 0&&i<3;i++)e+=`
3
3
  Caused by: ${t instanceof Error?a(t.stack||`${t.name}: ${t.message}`):JSON.stringify(u(t,{maxDepth:3}))}`,t=t instanceof Error?t.cause:void 0;return e}return typeof o=="string"?a(o):JSON.stringify(u(o,{maxDepth:3}))??String(o)}catch{return"[REDACTED:sanitization-failed]"}}function f(o,e,t,i){try{if(o==null||typeof o=="number"||typeof o=="boolean")return o;if(typeof o=="string")return a(o,e.maxStringLength);if(typeof o=="bigint"||typeof o=="symbol")return o.toString();if(typeof o=="function")return"[function]";let n=o;if(i.includes(n))return"[circular]";if(t>=e.maxDepth)return"[object]";if(ArrayBuffer.isView(n))return`[binary ${n.byteLength} bytes]`;if(n instanceof ArrayBuffer)return`[binary ${n.byteLength} bytes]`;if(n instanceof Date)return Number.isNaN(n.getTime())?"[invalid date]":n.toISOString();if(n instanceof Map||n instanceof Set)return`[${n.constructor.name}(${n.size})]`;let r=[...i,n];if(Array.isArray(n)){let s=n.slice(0,e.maxEntries).map(g=>f(g,e,t+1,r));return n.length>e.maxEntries&&s.push(`[+${n.length-e.maxEntries} more]`),s}return n instanceof Error?T(n,e,t,r):F(n,Object.keys(n),e,t,r)}catch{return"[REDACTED:sanitization-failed]"}}function T(o,e,t,i){let n={name:a(String(o.name),e.maxStringLength),message:a(String(o.message),e.maxStringLength)};typeof o.stack=="string"&&(n.stack=a(o.stack,e.maxStringLength));let r=o.code;(typeof r=="string"||typeof r=="number")&&(n.code=r);let s=o.cause;return s!==void 0&&(n.cause=f(s,e,t+1,i)),n}function F(o,e,t,i,n){let r={};for(let s of e.slice(0,t.maxEntries)){let g=Object.getOwnPropertyDescriptor(o,s);if(!g)continue;if(!("value"in g)){r[s]="[getter]";continue}let c=g.value;if(x(s)&&c!==null&&c!==void 0&&typeof c!="boolean"){r[s]="[REDACTED:sensitive-key]";continue}r[s]=f(c,t,i+1,n)}return e.length>t.maxEntries&&(r["[truncated]"]=`${e.length-t.maxEntries} more keys`),r}var E,O,D,N,k,w,C=l(()=>{"use strict";S();E={maxDepth:6,maxEntries:100,maxStringLength:8192},O=1e6,D=new Set(["auth","dsn","pwd","proxyauthorization","setcookie","sessionid"]),N=["token","secret","password","passwd","passphrase","apikey","privatekey","accesskey","secretkey","credential","credentials","cookie","authorization","sessionid","connectionstring"],k=[[/(:\/\/)[^\s/@:"']*:[^\s/@"']+@/g,"$1<REDACTED:credentials>@"],[/\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi,"$1 <REDACTED:credential>"],[/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}/g,"<REDACTED:api_key>"],[/\b(set-cookie|cookie):\s*[^\n]+/gi,"$1: <REDACTED:cookie>"],[/\b([A-Za-z0-9_-]{0,64}?[_-](?:token|secret|password|passwd))=([^\s&"'#]+)/gi,"$1=<REDACTED:credential>"]],w=/(["'])([A-Za-z0-9_.-]{1,64})\1(\s*:\s*)("(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?|-?\d[\d.eE+-]*)/g});function R(o){switch(o.toUpperCase()){case"DEBUG":return 0;case"INFO":return 1;case"WARN":case"WARNING":return 2;case"ERROR":return 3;case"SILENT":case"NONE":case"OFF":return 4;default:return 1}}var y,h=l(()=>{"use strict";y={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR",4:"SILENT"}});var m,L,d,b=l(()=>{"use strict";h();C();m={includeTimestamp:!0,includeLevel:!0,timestampFormat:"short",prettyPrint:!1,maxContextDepth:3},L=class o{domain;level;config;inheritedContext;constructor(e,t=1,i={},n={}){this.domain=e,this.level=t,this.config={...m,...i},this.inheritedContext=n}debug(e,t){this.level<=0&&this.output(0,e,t)}info(e,t){this.level<=1&&this.output(1,e,t)}warn(e,t){this.level<=2&&this.output(2,e,t)}error(e,t,i){if(this.level<=3){let n={...i};if(t){n.errorName=t.name,n.errorMessage=t.message,t.stack&&(n.stack=t.stack);let r=t;r.cause!==void 0&&(n.cause=r.cause)}this.output(3,e,n)}}isEnabled(e){return this.level<=e}getDomain(){return this.domain}child(e){return new o(this.domain,this.level,this.config,{...this.inheritedContext,...e})}output(e,t,i){let n=this.format(e,t,i);switch(e){case 0:console.debug(n);break;case 1:console.info(n);break;case 2:console.warn(n);break;case 3:console.error(n);break}}format(e,t,i){let n=[];this.config.includeTimestamp&&n.push(this.formatTimestamp()),this.config.includeLevel&&n.push(this.formatLevel(e)),n.push(`[${this.domain}]`),n.push(a(t));let r=this.mergeContext(i);return r&&Object.keys(r).length>0&&n.push(this.formatContext(r)),n.join(" ")}formatTimestamp(){let e=new Date;if(this.config.timestampFormat==="iso")return`[${e.toISOString()}]`;let t=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),n=String(e.getSeconds()).padStart(2,"0"),r=String(e.getMilliseconds()).padStart(3,"0");return`[${t}:${i}:${n}.${r}]`}formatLevel(e){return`[${y[e].padEnd(5)}]`}mergeContext(e){if(!(!e&&Object.keys(this.inheritedContext).length===0))return{...this.inheritedContext,...e}}formatContext(e){try{let t=u(e,{maxDepth:this.config.maxContextDepth+1});return this.config.prettyPrint?`
4
4
  `+JSON.stringify(t,null,2):JSON.stringify(t)}catch{return"[unserializable context]"}}},d=class{domain;constructor(e="null"){this.domain=e}debug(e,t){}info(e,t){}warn(e,t){}error(e,t,i){}isEnabled(e){return!1}getDomain(){return this.domain}child(e){return this}}});function X(o,e){return p.create(o,e)}var $,p,G=l(()=>{"use strict";h();b();$={defaultLevel:1,domainLevels:new Map,consoleConfig:m,silent:!1},p=class{static config={...$};static customProvider=null;static instances=new Map;static setLevel(e){this.config.defaultLevel=e,this.instances.clear()}static setLevelFromString(e){this.setLevel(R(e))}static getLevel(){return this.config.defaultLevel}static setDomainLevel(e,t){this.config.domainLevels.set(e,t),this.instances.delete(e)}static getDomainLevel(e){return this.config.domainLevels.get(e)??this.config.defaultLevel}static clearDomainLevel(e){this.config.domainLevels.delete(e),this.instances.delete(e)}static configure(e){this.config.consoleConfig={...this.config.consoleConfig,...e},this.instances.clear()}static setSilent(e){this.config.silent=e,this.instances.clear()}static isSilent(){return this.config.silent}static setProvider(e){this.customProvider=e,this.instances.clear()}static create(e,t){if(!t&&this.instances.has(e))return this.instances.get(e);let i=this.getDomainLevel(e),n;return this.config.silent?n=new d(e):this.customProvider?n=this.customProvider(e,i,t):n=new L(e,i,this.config.consoleConfig,t),t||this.instances.set(e,n),n}static getLogger(e,t){return this.create(e,t)}static reset(){this.config={defaultLevel:1,domainLevels:new Map,consoleConfig:{...m},silent:!1},this.customProvider=null,this.instances.clear()}static initFromEnv(){let e=process.env.LOG_LEVEL;e&&this.setLevelFromString(e);let t=process.env.LOG_TIMESTAMP;t!==void 0&&this.configure({includeTimestamp:t.toLowerCase()==="true"});let i=process.env.LOG_PRETTY;i!==void 0&&this.configure({prettyPrint:i.toLowerCase()==="true"})}static getStats(){return{cachedLoggers:this.instances.size,domains:Array.from(this.instances.keys()),domainOverrides:this.config.domainLevels.size,currentLevel:this.config.defaultLevel,silent:this.config.silent}}}});export{h as a,_ as b,C as c,b as d,p as e,X as f,G as g};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{b as i}from"./chunk-7SAMMQVS.js";function d(){return Object.create(null)}function o(e,n){return Object.hasOwn(e,n)?e[n]:void 0}function u(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function s(e,n,t=1){let r=(o(e,n)??0)+t;return u(e,n,r),r}var c=i(()=>{"use strict"});export{d as a,o as b,u as c,s as d,c as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{b as i}from"./chunk-K5R3WUJP.js";function d(){return Object.create(null)}function o(e,n){return Object.hasOwn(e,n)?e[n]:void 0}function u(e,n,t){Object.defineProperty(e,n,{value:t,writable:!0,enumerable:!0,configurable:!0})}function s(e,n,t=1){let r=(o(e,n)??0)+t;return u(e,n,r),r}var c=i(()=>{"use strict"});export{d as a,o as b,u as c,s as d,c as e};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{d as W,f as Tt}from"./chunk-X2DR27AY.js";import{b as I,d as ge}from"./chunk-22OZIJAD.js";import{a as K,b as $,c as V,d as Ne,e as dt}from"./chunk-DQNUPEY5.js";import{a as Y,c as Et}from"./chunk-LZWJ5BMP.js";import{a as _e,d as F,e as me,f as fe}from"./chunk-RUTO67PT.js";import{a as X,b as pe,e as ct}from"./chunk-5LST62QR.js";import{a as Se,c as he,d as ut}from"./chunk-HEGGV2PT.js";import{a as it}from"./chunk-45MVRQG4.js";import{e as ue}from"./chunk-IEPWO4XP.js";import{a as O,e as de}from"./chunk-KYVIOC3C.js";import{a as H,c as y,d as ot}from"./chunk-TVLOED6O.js";import{a as le,b as at}from"./chunk-AJT3XDRD.js";import{b as R,d as st}from"./chunk-7SAMMQVS.js";import{createHash as Ie}from"node:crypto";function gt(n){let t=Buffer.alloc(8);return t.writeBigUInt64LE(BigInt(n)),t}function pt(n){return typeof n=="string"?Buffer.from(n,"utf8"):n instanceof Uint8Array?Buffer.from(n):Buffer.from(Q(n),"utf8")}function Q(n){return n===null||typeof n!="object"?JSON.stringify(n)??"null":Array.isArray(n)?`[${n.map(Q).join(",")}]`:`{${Object.keys(n).sort().map(e=>`${JSON.stringify(e)}:${Q(n[e])}`).join(",")}}`}function Ce(...n){let t=Ie("sha256");for(let e of n)t.update(e);return t.digest()}function Le(n,t,e){return Ce(lt,n,t,gt(e))}var lt,Re,A,Oe=R(()=>{"use strict";lt=Buffer.from("ruvector:chain:"),Re=Ie("sha256").update("ruvector-proof-gate-v1").digest();A=class n{seq=0;prev=Re;chain=[];payloadHashes=[];admit(t){let e=Ce(pt(t)),r=Le(this.prev,e,this.seq);this.prev=r,this.chain.push(r),this.payloadHashes.push(e);let o={sequence:this.seq,payloadHash:e.toString("hex"),chainCommitment:r.toString("hex")};return this.seq+=1,o}verifyReceipt(t){return t.sequence>=0&&t.sequence<this.chain.length&&this.chain[t.sequence].toString("hex")===t.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let t=Re;for(let e=0;e<this.chain.length;e++){if(!Le(t,this.payloadHashes[e],e).equals(this.chain[e]))return!1;t=this.chain[e]}return t.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(t=>t.toString("hex")),payloadHashes:this.payloadHashes.map(t=>t.toString("hex"))}}static fromJSON(t){let e=new n;e.seq=t.seq,e.prev=Buffer.from(t.head,"hex");for(let r of t.chain)e.chain.push(Buffer.from(r,"hex"));for(let r of t.payloadHashes)e.payloadHashes.push(Buffer.from(r,"hex"));return e}}});function v(n){if(!J.has(n))throw new Error(`Invalid table name: "${n}" is not in the allowlist`);return n}function bt(n){let t=n.split(".");if(t.length>2)throw new Error(`Invalid SQL identifier: "${n}" has too many parts (max: schema.table)`);for(let e of t)if(!Ae.test(e))throw new Error(`Invalid SQL identifier: "${n}" \u2014 part "${e}" does not match pattern ${Ae}`);return n}var J,Ae,Z=R(()=>{"use strict";J=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);Ae=/^[a-z_][a-z0-9_]{0,62}$/});function be(n){n.exec(ve),n.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{d as W,f as Tt}from"./chunk-UDCYQLTD.js";import{b as I,d as ge}from"./chunk-FWXNFPLS.js";import{a as K,b as $,c as V,d as Ne,e as dt}from"./chunk-7SLEUVPZ.js";import{a as Y,c as Et}from"./chunk-D4O3TJI7.js";import{a as _e,d as F,e as me,f as fe}from"./chunk-R2NHGESM.js";import{a as X,b as pe,e as ct}from"./chunk-DN3AKAPY.js";import{a as Se,c as he,d as ut}from"./chunk-IJSFZO7P.js";import{a as it}from"./chunk-X6VYQVUM.js";import{e as ue}from"./chunk-7H3GNRNA.js";import{a as O,e as de}from"./chunk-J7FLNP5L.js";import{a as H,c as y,d as ot}from"./chunk-SHEVM5PF.js";import{a as le,b as at}from"./chunk-LPSMVBB3.js";import{b as R,d as st}from"./chunk-K5R3WUJP.js";import{createHash as Ie}from"node:crypto";function gt(n){let t=Buffer.alloc(8);return t.writeBigUInt64LE(BigInt(n)),t}function pt(n){return typeof n=="string"?Buffer.from(n,"utf8"):n instanceof Uint8Array?Buffer.from(n):Buffer.from(Q(n),"utf8")}function Q(n){return n===null||typeof n!="object"?JSON.stringify(n)??"null":Array.isArray(n)?`[${n.map(Q).join(",")}]`:`{${Object.keys(n).sort().map(e=>`${JSON.stringify(e)}:${Q(n[e])}`).join(",")}}`}function Ce(...n){let t=Ie("sha256");for(let e of n)t.update(e);return t.digest()}function Le(n,t,e){return Ce(lt,n,t,gt(e))}var lt,Re,A,Oe=R(()=>{"use strict";lt=Buffer.from("ruvector:chain:"),Re=Ie("sha256").update("ruvector-proof-gate-v1").digest();A=class n{seq=0;prev=Re;chain=[];payloadHashes=[];admit(t){let e=Ce(pt(t)),r=Le(this.prev,e,this.seq);this.prev=r,this.chain.push(r),this.payloadHashes.push(e);let o={sequence:this.seq,payloadHash:e.toString("hex"),chainCommitment:r.toString("hex")};return this.seq+=1,o}verifyReceipt(t){return t.sequence>=0&&t.sequence<this.chain.length&&this.chain[t.sequence].toString("hex")===t.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let t=Re;for(let e=0;e<this.chain.length;e++){if(!Le(t,this.payloadHashes[e],e).equals(this.chain[e]))return!1;t=this.chain[e]}return t.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(t=>t.toString("hex")),payloadHashes:this.payloadHashes.map(t=>t.toString("hex"))}}static fromJSON(t){let e=new n;e.seq=t.seq,e.prev=Buffer.from(t.head,"hex");for(let r of t.chain)e.chain.push(Buffer.from(r,"hex"));for(let r of t.payloadHashes)e.payloadHashes.push(Buffer.from(r,"hex"));return e}}});function v(n){if(!J.has(n))throw new Error(`Invalid table name: "${n}" is not in the allowlist`);return n}function bt(n){let t=n.split(".");if(t.length>2)throw new Error(`Invalid SQL identifier: "${n}" has too many parts (max: schema.table)`);for(let e of t)if(!Ae.test(e))throw new Error(`Invalid SQL identifier: "${n}" \u2014 part "${e}" does not match pattern ${Ae}`);return n}var J,Ae,Z=R(()=>{"use strict";J=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);Ae=/^[a-z_][a-z0-9_]{0,62}$/});function be(n){n.exec(ve),n.exec(`
3
3
  INSERT OR IGNORE INTO learning_evidence_manifests (
4
4
  id, trajectory_id, trajectory_hash, manifest_hash, task_family,
5
5
  outcome, oracle_refs_json, source_kind, process_signals_json
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{b as h}from"./chunk-7SAMMQVS.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{b as h}from"./chunk-K5R3WUJP.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{e as P}from"./chunk-SOSJWM3E.js";import{a as w}from"./chunk-BUTGIVKW.js";import{a as T,b as S}from"./chunk-LCCTJ2PC.js";import{r as M,s as I}from"./chunk-YNG7E26C.js";import{a as k,e as D}from"./chunk-KYVIOC3C.js";import{c as C,d as F}from"./chunk-TVLOED6O.js";import{f as A}from"./chunk-7SAMMQVS.js";F();import{createHash as $}from"crypto";import*as x from"path";function H(){let o="3.15.6",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var L={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function Q(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function U(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...L,...e}}computeFingerprint(e,t,r,i){let n=Q({action:t,build:H(),domain:e,input:r,scope:U(i)});return $("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{e as P}from"./chunk-QFYUZYRA.js";import{a as w}from"./chunk-62T7U25U.js";import{a as T,b as S}from"./chunk-BLZEOGQE.js";import{r as M,s as I}from"./chunk-7XGM7Q2N.js";import{a as k,e as D}from"./chunk-J7FLNP5L.js";import{c as C,d as F}from"./chunk-SHEVM5PF.js";import{f as A}from"./chunk-K5R3WUJP.js";F();import{createHash as $}from"crypto";import*as x from"path";function H(){let o="3.15.8",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${o}+${e}`:o}var L={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function Q(o){let e=JSON.parse(JSON.stringify(o));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}function U(o){let e=o?.projectRoot;if(!e)try{e=C()}catch{e=""}let t=o?.cwd;if(!t)try{t=process.cwd()}catch{t=""}return{projectRoot:e?x.resolve(e):"",cwd:t?x.resolve(t):"",inputs:o?.inputs??{}}}var v=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...L,...e}}computeFingerprint(e,t,r,i){let n=Q({action:t,build:H(),domain:e,input:r,scope:U(i)});return $("sha256").update(n).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.generation++}getGeneration(){return this.generation}invalidateAll(){let e=this.cache.size;if(this.cache.clear(),this.generation++,this.config.persistToDb)try{d()?.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache'").run()}catch{}return e}invalidateDomain(e){this.generation++;let t=0;for(let[r,i]of this.cache)i.domain===e&&(this.cache.delete(r),this.deletePersisted(i.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=d();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{b as j,d as z}from"./chunk-5MT7DMD7.js";import{a as F,e as ce}from"./chunk-KYVIOC3C.js";import{c as k,d as pe}from"./chunk-TVLOED6O.js";z();ce();z();import*as N from"node:http";import*as M from"node:https";import{createHash as me}from"node:crypto";import{URL as Q}from"node:url";var x={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ue="AQE embedder endpoint identity canary v1",fe="/v1/embeddings";function X(t){if(t.startsWith("unix:"))return t;try{let e=new Q(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function ge(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new Q(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var q=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},_=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??x.model,expectedDim:e.expectedDim??x.expectedDim,connectTimeoutMs:e.connectTimeoutMs??x.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??x.requestTimeoutMs,failureThreshold:e.failureThreshold??x.failureThreshold,failureWindowMs:e.failureWindowMs??x.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=ge(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new M.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new N.Agent({keepAlive:!0});this.breaker=new q(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([ue]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=me("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return j(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(fe,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=N.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?M.request:N.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,R=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);R(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,S=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(S),w.destroy(S)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};pe();import{join as J,resolve as he}from"node:path";import{existsSync as Ee,mkdirSync as be}from"node:fs";import{createRequire as ye}from"node:module";var we=ye(import.meta.url);function Ie(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:he(k(),t):J(k(),".agentic-qe","memory.db")}var K="_system",Y="embedder_identity:",T=null,U=!1;function Z(){if(T)return T;if(U)return null;try{let t=we("better-sqlite3"),e=Ie(),n=J(e,"..");Ee(n)||be(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{b as j,d as z}from"./chunk-A2UGPKCS.js";import{a as F,e as ce}from"./chunk-J7FLNP5L.js";import{c as k,d as pe}from"./chunk-SHEVM5PF.js";z();ce();z();import*as N from"node:http";import*as M from"node:https";import{createHash as me}from"node:crypto";import{URL as Q}from"node:url";var x={model:"Xenova/all-MiniLM-L6-v2",expectedDim:384,connectTimeoutMs:5e3,requestTimeoutMs:3e4,failureThreshold:3,failureWindowMs:6e4},ue="AQE embedder endpoint identity canary v1",fe="/v1/embeddings";function X(t){if(t.startsWith("unix:"))return t;try{let e=new Q(t);return e.username||e.password?(e.username="",e.password="",e.toString().replace(/\/$/,"")):t}catch{return t}}function ge(t){if(t.startsWith("unix:")){let r=t.slice(5);if(!r.startsWith("/"))throw new Error(`unix endpoint must be an absolute path: ${t}`);return{transport:"unix",socketPath:r,safeUrl:t}}let e=new Q(t);if(e.protocol!=="http:"&&e.protocol!=="https:")throw new Error(`unsupported embedder endpoint protocol: ${e.protocol}`);return(e.username||e.password)&&(console.warn("[EmbedderEndpointClient] endpoint URL contained userinfo; stripping. Use AQE_EMBEDDER_TOKEN env var for credentials."),e.username="",e.password=""),{transport:e.protocol==="https:"?"https":"http",host:e.hostname,port:e.port?Number(e.port):e.protocol==="https:"?443:80,protocol:e.protocol,safeUrl:e.toString().replace(/\/$/,"")}}var q=class{constructor(e,n,r=()=>{}){this.threshold=e;this.windowMs=n;this.onRecover=r}threshold;windowMs;onRecover;failures=[];trippedAt=null;recordSuccess(){this.failures=[],this.trippedAt=null}recordFailure(){let e=Date.now();this.failures=this.failures.filter(n=>e-n<this.windowMs),this.failures.push(e),this.failures.length>=this.threshold&&(this.trippedAt=e)}isOpen(){return this.trippedAt===null?!1:Date.now()-this.trippedAt>=this.windowMs?(this.failures=[],this.trippedAt=null,this.onRecover(),!1):!0}getState(){return{open:this.isOpen(),failures:this.failures.length,trippedAt:this.trippedAt}}},_=class{parsed;agent;breaker;opts;cachedIdentity=null;probeInFlight=null;constructor(e){if(this.opts={endpoint:e.endpoint,token:e.token,model:e.model??x.model,expectedDim:e.expectedDim??x.expectedDim,connectTimeoutMs:e.connectTimeoutMs??x.connectTimeoutMs,requestTimeoutMs:e.requestTimeoutMs??x.requestTimeoutMs,failureThreshold:e.failureThreshold??x.failureThreshold,failureWindowMs:e.failureWindowMs??x.failureWindowMs,tlsOptions:e.tlsOptions},this.parsed=ge(e.endpoint),this.parsed.transport==="https"){let n=e.tlsOptions??{};this.agent=new M.Agent({keepAlive:!0,ca:n.ca,cert:n.cert,key:n.key,rejectUnauthorized:n.rejectUnauthorized!==!1,servername:n.servername})}else this.agent=new N.Agent({keepAlive:!0});this.breaker=new q(this.opts.failureThreshold,this.opts.failureWindowMs,()=>{this.cachedIdentity=null})}getSafeEndpoint(){return this.parsed.safeUrl}async embed(e){if(e.length===0)return[];if(this.breaker.isOpen())throw new Error(`[EmbedderEndpointClient] circuit breaker open for ${this.parsed.safeUrl} \u2014 fast-failing`);this.cachedIdentity===null&&await this.ensureProbed();try{let n=await this.postEmbeddings(e),r=this.decodeAndNormalize(n,e.length);return this.breaker.recordSuccess(),r}catch(n){throw this.breaker.recordFailure(),n}}async probe(){return this.probeInFlight?this.probeInFlight:(this.probeInFlight=this.doProbe().finally(()=>{this.probeInFlight=null}),this.probeInFlight)}async ensureProbed(){return this.cachedIdentity?this.cachedIdentity:this.probe()}async doProbe(){let e;try{let a=await this.postEmbeddings([ue]);e=this.decodeAndNormalize(a,1)[0],this.breaker.recordSuccess()}catch(a){throw this.breaker.recordFailure(),a}if(!e||e.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch: expected ${this.opts.expectedDim}, got ${e?.length??0} from ${this.parsed.safeUrl}`);let n=Buffer.alloc(e.length*2);for(let a=0;a<e.length;a++){let i=Math.max(-32768,Math.min(32767,Math.round(e[a]*32767)));n.writeInt16LE(i,a*2)}let r=me("sha256").update(n).digest("hex").slice(0,16);return this.cachedIdentity={dim:e.length,fingerprint:r,endpoint:this.parsed.safeUrl},this.cachedIdentity}getCachedIdentity(){return this.cachedIdentity}getBreakerState(){return this.breaker.getState()}close(){this.agent.destroy()}decodeAndNormalize(e,n){if(!e||typeof e!="object"||!Array.isArray(e.data))throw new Error("[EmbedderEndpointClient] response missing data array");let r=e.data;if(r.length!==n)throw new Error(`[EmbedderEndpointClient] response count mismatch: expected ${n}, got ${r.length}`);let a=r.map((i,s)=>({idx:typeof i.index=="number"?i.index:s,embedding:i.embedding}));return a.sort((i,s)=>i.idx-s.idx),a.map(({embedding:i},s)=>{if(typeof i=="string")throw new Error(`[EmbedderEndpointClient] received base64 embedding at position ${s} \u2014 server ignored encoding_format=float. Configure the server to return float arrays.`);if(!Array.isArray(i))throw new Error(`[EmbedderEndpointClient] missing embedding at position ${s}`);if(i.length!==this.opts.expectedDim)throw new Error(`[EmbedderEndpointClient] dim mismatch at position ${s}: expected ${this.opts.expectedDim}, got ${i.length}`);return j(i)})}postEmbeddings(e){let n=JSON.stringify({model:this.opts.model,input:e,encoding_format:"float"});return this.request(fe,n)}request(e,n){let r={"content-type":"application/json","content-length":Buffer.byteLength(n),accept:"application/json"};this.opts.token&&(r.authorization=`Bearer ${this.opts.token}`);let a={method:"POST",path:e,headers:r,agent:this.agent},i,s;this.parsed.transport==="unix"?(i={...a,socketPath:this.parsed.socketPath},s=N.request):(i={...a,host:this.parsed.host,port:this.parsed.port,protocol:this.parsed.protocol},s=this.parsed.transport==="https"?M.request:N.request);let o=this.parsed.safeUrl,l=this.opts.connectTimeoutMs,m=this.opts.requestTimeoutMs;return new Promise((b,$)=>{let y=!1,R=d=>{y||(y=!0,b(d))},h=d=>{y||(y=!0,$(d))},w=s(i,d=>{let g=[];d.on("data",u=>g.push(Buffer.from(u))),d.on("end",()=>{let u=Buffer.concat(g).toString("utf-8");if(!d.statusCode||d.statusCode<200||d.statusCode>=300){h(new Error(`[EmbedderEndpointClient] HTTP ${d.statusCode} from ${o}: ${u.slice(0,200)}`));return}try{let E=JSON.parse(u);R(E)}catch(E){h(new Error(`[EmbedderEndpointClient] invalid JSON from ${o}: ${E.message}`))}}),d.on("error",u=>h(u))});w.on("socket",d=>{d.setTimeout(l);let g=()=>{d.setTimeout(m)};d.connecting?d.once("connect",g):g(),d.on("timeout",()=>{let u=d.connecting?"connect":"request",E=d.connecting?l:m,S=new Error(`[EmbedderEndpointClient] ${u} timeout after ${E}ms`);h(S),w.destroy(S)})}),w.on("error",d=>h(d)),w.write(n),w.end()})}};pe();import{join as J,resolve as he}from"node:path";import{existsSync as Ee,mkdirSync as be}from"node:fs";import{createRequire as ye}from"node:module";var we=ye(import.meta.url);function Ie(){let t=process.env.AQE_MEMORY_PATH;return t&&t.length>0?t===":memory:"?t:he(k(),t):J(k(),".agentic-qe","memory.db")}var K="_system",Y="embedder_identity:",T=null,U=!1;function Z(){if(T)return T;if(U)return null;try{let t=we("better-sqlite3"),e=Ie(),n=J(e,"..");Ee(n)||be(n,{recursive:!0});let r=new t(e);return r.pragma("journal_mode = WAL"),r.pragma("busy_timeout = 5000"),r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS kv_store (
4
4
  key TEXT NOT NULL,
5
5
  namespace TEXT NOT NULL,
@@ -10,4 +10,4 @@ import{b as j,d as z}from"./chunk-5MT7DMD7.js";import{a as F,e as ce}from"./chun
10
10
  );
11
11
  CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
12
12
  `),T=r,r}catch{return U=!0,null}}function ee(t){let e=Z();if(!e)return null;try{let n=e.prepare("SELECT value FROM kv_store WHERE namespace = ? AND key = ?").get(K,Y+t);if(!n)return null;let r=JSON.parse(n.value);return!r.fingerprint||typeof r.dim!="number"?null:{fingerprint:r.fingerprint,dim:r.dim,endpoint:r.endpoint}}catch{return null}}function te(t){let e=Z();if(!e)return;let n={fingerprint:t.fingerprint,dim:t.dim,endpoint:t.endpoint,updatedAt:Date.now()};e.prepare("INSERT OR REPLACE INTO kv_store (key, namespace, value) VALUES (?, ?, ?)").run(Y+t.endpoint,K,JSON.stringify(n))}function ne(){if(T)try{T.close()}catch{}T=null,U=!1}z();import{createHash as ie}from"node:crypto";import{existsSync as Ae,readFileSync as xe,renameSync as Te,writeFileSync as Se}from"node:fs";var oe="aqe embedding-space compatibility canary v1";var I=class extends Error{constructor(n,r){super(`${n}: ${r}`);this.code=n;this.name="EmbeddingSpaceError"}code};function Ne(t){return JSON.stringify({provider:t.provider,model:t.model,dimensions:t.dimensions,pooling:t.pooling??null,normalized:t.normalized,preprocessingVersion:t.preprocessingVersion??null,implementation:t.implementation??null,runtimeFingerprint:t.runtimeFingerprint})}function se(t){let e=Buffer.alloc(t.length*2);for(let n=0;n<t.length;n++){let r=Math.max(-32768,Math.min(32767,Math.round(t[n]*32767)));e.writeInt16LE(r,n*2)}return ie("sha256").update(e).digest("hex").slice(0,16)}function V(t){if(!t.runtimeFingerprint)throw new Error("Embedding space identity requires executable runtime evidence");let e=ie("sha256").update("aqe:embedding-space:v1\0").update(Ne(t)).digest("hex");return{...t,spaceId:e}}function Le(t,e){let n=[...new Set(t.flatMap(o=>o.spaceId?[o.spaceId]:[]))].sort(),r=t.filter(o=>!o.spaceId).length,a=e?t.filter(o=>o.spaceId===e).length:0,i=e?t.filter(o=>o.spaceId!==null&&o.spaceId!==e).length:t.length-r;return{status:r>0||!e?"unverified":i>0||n.length>1?"vector_space_mismatch":"healthy",activeSpaceId:e,storedSpaceIds:n,verifiedVectors:a,mismatchedVectors:i,unverifiedVectors:r}}var Ce="[VectorSearch] WARN: semantic vector search is not active: no embedding runtime was available when the ANN indexes were opened (set AQE_EMBEDDER_ENDPOINT, or install @huggingface/transformers). Any existing vectors in patterns.rvf and brain.rvf are kept and will be used once an embedder is available; until then pattern search uses SQLite text matching.",He="VECTOR_SPACE_UNVERIFIED: no embedding runtime was available when the RVF index was opened; index left unbound (existing vectors are kept)",re=!1;function We(){re||(re=!0,console.warn(Ce))}function Re(t){return`${t}.space.json`}function Ge(t,e,n){if(!e)throw new I("VECTOR_SPACE_UNVERIFIED",`cannot open ANN index ${t} without runtime provenance`);let r=Re(t);if(Ae(r)){let s;try{s=JSON.parse(xe(r,"utf8"))}catch{throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} is unreadable`)}if(s.version!==1||!s.spaceId)throw new I("VECTOR_SPACE_UNVERIFIED",`ANN index manifest ${r} has no verified space`);if(s.spaceId!==e)throw new I("VECTOR_SPACE_MISMATCH",`ANN index space ${s.spaceId} != active space ${e}`);return}if(n>0)throw new I("VECTOR_SPACE_UNVERIFIED",`populated ANN index ${t} has no embedding-space manifest; rebuild required`);let a={version:1,spaceId:e},i=`${r}.${process.pid}.tmp`;Se(i,`${JSON.stringify(a)}
13
- `,{encoding:"utf8",mode:384}),Te(i,r)}var B=null,f=null,C=null,P=!1,D="",v=null,c=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},p=new Map,ae=36e5;function L(t){return c?`endpoint:${c.fingerprint}:${t}`:`inproc:${t}`}function de(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(P)throw new Error(`Transformer initialization previously failed: ${D}`);if(C)return C;let e={...H,...t};return C=(async()=>{try{if(e.endpoint){let l=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new _({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:O()}),c=await v.probe(),A=V({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:c.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:c.endpoint,runtimeFingerprint:c.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${c.dim} fingerprint=${c.fingerprint}`);try{let m=ee(c.endpoint);m&&m.fingerprint!==c.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${c.fingerprint} dim=${c.dim}. Vectors written before this change may no longer be comparable.`),te(c)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=_e(v);return}let n;try{n=await import("./transformers-7MASPELS.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}B=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await B("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(oe,{pooling:"mean",normalize:!0}),s=Array.from(i.data);A=V({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:se(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw P=!0,D=F(n),new Error(`Failed to initialize transformer model: ${D}`)}})(),C}function _e(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??O(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function Ye(t,e={}){let n={...H,...e};if(de(t))return new Array(O()).fill(0);if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");let r=L(t);if(n.enableCache){let l=p.get(r);if(l&&Date.now()-l.timestamp<ae)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(p.size>=n.maxCacheSize){let l=p.keys().next().value;l&&p.delete(l)}p.set(r,{embedding:s,timestamp:Date.now()})}return s}async function Ze(t,e={}){let n={...H,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)de(t[o])?i[o]=new Array(O()).fill(0):s.push(o);if(s.length===0)return i;if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=p.get(L(t[o]));l&&Date.now()-l.timestamp<ae?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),R=await f(y,{pooling:"mean",normalize:!0}),h=R.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(R.data.slice(u,u+d)),S=b+g,le=a[S];if(i[le]=E,n.enableCache){if(p.size>=n.maxCacheSize){let G=p.keys().next().value;G&&p.delete(G)}p.set(L(r[S]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function et(){p.clear(),console.log("[RealEmbeddings] Cache cleared")}function tt(){return{size:p.size,hitRate:0}}function nt(){return!P&&f!==null}function O(){return 384}function rt(){B=null,f=null,C=null,P=!1,D="",p.clear(),v&&v.close(),v=null,c=null,A=null,ne()}function it(){return v!==null}function ot(){return c}function st(){return A}async function at(){if(A)return A;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await W({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),A):null}export{oe as a,Le as b,He as c,We as d,Ge as e,H as f,Ye as g,Ze as h,et as i,tt as j,nt as k,O as l,rt as m,it as n,ot as o,st as p,at as q};
13
+ `,{encoding:"utf8",mode:384}),Te(i,r)}var B=null,f=null,C=null,P=!1,D="",v=null,c=null,A=null,H={modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0,maxCacheSize:1e4,endpoint:process.env.AQE_EMBEDDER_ENDPOINT,endpointToken:process.env.AQE_EMBEDDER_TOKEN},p=new Map,ae=36e5;function L(t){return c?`endpoint:${c.fingerprint}:${t}`:`inproc:${t}`}function de(t){let e=t.trim();return!!(e.startsWith("{")&&/["']metrics["']/.test(e)||e.startsWith("[")&&e.endsWith("]")&&e.length>50||(e.match(/[a-zA-Z]/g)||[]).length/Math.max(e.length,1)<.3&&e.length>20)}async function W(t={}){if(P)throw new Error(`Transformer initialization previously failed: ${D}`);if(C)return C;let e={...H,...t};return C=(async()=>{try{if(e.endpoint){let l=X(e.endpoint);console.log(`[RealEmbeddings] Using external embedder endpoint: ${l}`),v=new _({endpoint:e.endpoint,token:e.endpointToken,model:e.modelName,expectedDim:O()}),c=await v.probe(),A=V({provider:"openai-compatible-endpoint",model:e.modelName,dimensions:c.dim,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:c.endpoint,runtimeFingerprint:c.fingerprint}),console.log(`[RealEmbeddings] Endpoint identity: dim=${c.dim} fingerprint=${c.fingerprint}`);try{let m=ee(c.endpoint);m&&m.fingerprint!==c.fingerprint&&console.warn(`[RealEmbeddings] WARNING: endpoint identity changed since last run. Previous fingerprint=${m.fingerprint} dim=${m.dim}, current fingerprint=${c.fingerprint} dim=${c.dim}. Vectors written before this change may no longer be comparable.`),te(c)}catch(m){console.warn(`[RealEmbeddings] Could not persist endpoint identity: ${F(m)}`)}f=_e(v);return}let n;try{n=await import("./transformers-MB63T2XO.js")}catch{throw new Error('In-process embeddings require the optional package "@huggingface/transformers", which is not installed. Configure an embedding endpoint (EmbeddingConfig.endpoint / AQE_EMBEDDER_ENDPOINT) so no local model is loaded. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj.')}B=n.pipeline,console.log(`[RealEmbeddings] Loading model: ${e.modelName}`);let r=performance.now();f=await B("feature-extraction",e.modelName,{quantized:e.quantized});let a=f;if(!a)throw new Error("Transformer pipeline returned no embedding model");let i=await a(oe,{pooling:"mean",normalize:!0}),s=Array.from(i.data);A=V({provider:"huggingface-transformers",model:e.modelName,dimensions:s.length,pooling:"mean",normalized:!0,preprocessingVersion:"aqe-text-v1",implementation:`transformers:${e.quantized?"quantized":"full"}`,runtimeFingerprint:se(s)});let o=performance.now()-r;console.log(`[RealEmbeddings] Model loaded in ${o.toFixed(0)}ms`)}catch(n){throw P=!0,D=F(n),new Error(`Failed to initialize transformer model: ${D}`)}})(),C}function _e(t){return async e=>{let n=Array.isArray(e)?e:[e],r=await t.embed(n),a=r[0]?.length??O(),i=new Float32Array(n.length*a);for(let s=0;s<r.length;s++)i.set(r[s],s*a);return{data:i,dims:[n.length,a]}}}async function Ye(t,e={}){let n={...H,...e};if(de(t))return new Array(O()).fill(0);if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");let r=L(t);if(n.enableCache){let l=p.get(r);if(l&&Date.now()-l.timestamp<ae)return l.embedding}let a=performance.now(),i=await f(t,{pooling:"mean",normalize:!0}),s=Array.from(i.data),o=performance.now()-a;if(o>500&&console.warn(`[RealEmbeddings] Slow embedding computation: ${o.toFixed(1)}ms for "${t.slice(0,50)}..."`),n.enableCache){if(p.size>=n.maxCacheSize){let l=p.keys().next().value;l&&p.delete(l)}p.set(r,{embedding:s,timestamp:Date.now()})}return s}async function Ze(t,e={}){let n={...H,...e},r=[],a=[],i=new Array(t.length).fill(null),s=[];for(let o=0;o<t.length;o++)de(t[o])?i[o]=new Array(O()).fill(0):s.push(o);if(s.length===0)return i;if(f||await W(e),!f)throw new Error("Embedding model failed to initialize");if(n.enableCache)for(let o of s){let l=p.get(L(t[o]));l&&Date.now()-l.timestamp<ae?i[o]=l.embedding:(r.push(t[o]),a.push(o))}else for(let o of s)r.push(t[o]),a.push(o);if(r.length>0){let o=performance.now(),l=32;for(let b=0;b<r.length;b+=l){let $=Math.min(b+l,r.length),y=r.slice(b,$),R=await f(y,{pooling:"mean",normalize:!0}),h=R.dims||[y.length,384],w=h[0],d=h[1];for(let g=0;g<w;g++){let u=g*d,E=Array.from(R.data.slice(u,u+d)),S=b+g,le=a[S];if(i[le]=E,n.enableCache){if(p.size>=n.maxCacheSize){let G=p.keys().next().value;G&&p.delete(G)}p.set(L(r[S]),{embedding:E,timestamp:Date.now()})}}}let m=performance.now()-o;console.log(`[RealEmbeddings] Batch computed ${r.length} embeddings in ${m.toFixed(0)}ms`)}return i.filter(o=>o!==null)}function et(){p.clear(),console.log("[RealEmbeddings] Cache cleared")}function tt(){return{size:p.size,hitRate:0}}function nt(){return!P&&f!==null}function O(){return 384}function rt(){B=null,f=null,C=null,P=!1,D="",p.clear(),v&&v.close(),v=null,c=null,A=null,ne()}function it(){return v!==null}function ot(){return c}function st(){return A}async function at(){if(A)return A;let t=process.env.AQE_EMBEDDER_ENDPOINT;return t?(await W({endpoint:t,endpointToken:process.env.AQE_EMBEDDER_TOKEN}),A):null}export{oe as a,Le as b,He as c,We as d,Ge as e,H as f,Ye as g,Ze as h,et as i,tt as j,nt as k,O as l,rt as m,it as n,ot as o,st as p,at as q};
@@ -1,3 +1,3 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{o as f,s as P}from"./chunk-YNG7E26C.js";import{b as h,d as U}from"./chunk-22OZIJAD.js";import{f as p,g as y}from"./chunk-IEPWO4XP.js";import{a as T,e as C}from"./chunk-KYVIOC3C.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{o as f,s as P}from"./chunk-7XGM7Q2N.js";import{b as h,d as U}from"./chunk-FWXNFPLS.js";import{f as p,g as y}from"./chunk-7H3GNRNA.js";import{a as T,e as C}from"./chunk-J7FLNP5L.js";P();C();U();y();import{randomUUID as v}from"crypto";var M=p("TokenTracker"),S={costPerInputToken:.003/1e3,costPerOutputToken:.015/1e3},I={filePath:".agentic-qe/token-metrics.json",autoSaveIntervalMs:6e4,maxMetricsInMemory:1e4},m=class u{taskMetrics=[];agentMetrics=new Map;domainMetrics=new Map;sessionId;sessionStartTime;costConfig;cacheHits=0;earlyExits=0;totalTokensSaved=0;totalPatternsReused=0;initialized=!1;persistenceConfig=I;autoSaveTimer=null;isDirty=!1;db=null;kvPersistCount=0;static KV_NAMESPACE="token-usage-metrics";static KV_KEY="token-tracker-snapshot";static KV_TTL=604800;static KV_PERSIST_INTERVAL=10;constructor(){this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.costConfig=S}initialize(t){this.initialized||(this.initialized=!0,t&&(this.costConfig={...S,...t}),this.initializeDb().catch(e=>{M.warn("DB initialization failed",{error:e instanceof Error?e.message:String(e)})}),this.startAutoSave())}setCostConfig(t){this.costConfig={...this.costConfig,...t}}recordTokenUsage(t,e,n,a,s,r){this.ensureInitialized();let c,d,i,o,l,k;typeof e=="object"?(c="default",d="unknown",i="unknown",o=e,l=!1,k=0):(c=e,d=n??"unknown",i=a??"unknown",o=s,l=r?.patternReused??!1,k=r?.tokensSaved??0),o.estimatedCostUsd===void 0&&(o.estimatedCostUsd=this.calculateCost(o));let g={taskId:t,agentId:c,domain:d,operation:i,timestamp:Date.now(),usage:o,patternReused:l,tokensSaved:k};this.taskMetrics.push(g),this.updateAgentMetrics(c,o,l,k),this.updateDomainMetrics(d,o),l&&this.totalPatternsReused++,k>0&&(this.totalTokensSaved+=k),this.isDirty=!0,this.maybePersistToKv()}recordPatternReuse(t,e){this.ensureInitialized(),this.totalPatternsReused++,this.totalTokensSaved+=e;let n={taskId:t,agentId:"pattern-cache",domain:"optimization",operation:"pattern-reuse",timestamp:Date.now(),usage:{inputTokens:0,outputTokens:0,totalTokens:0,estimatedCostUsd:0},patternReused:!0,tokensSaved:e};this.taskMetrics.push(n),this.isDirty=!0}recordCacheHit(t){this.cacheHits++,this.totalTokensSaved+=t,this.isDirty=!0}recordEarlyExit(t){this.earlyExits++,this.totalTokensSaved+=t,this.isDirty=!0}getSessionSummary(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),n=this.aggregateTokenUsage(e),a=new Map;for(let i of e){let o=a.get(i.agentId);o?(o.totalInputTokens+=i.usage.inputTokens,o.totalOutputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.totalCost+=i.usage.estimatedCostUsd||0,o.tasksExecuted++,i.patternReused&&o.patternsReused++,o.estimatedTokensSaved+=i.tokensSaved||0):a.set(i.agentId,{agentId:i.agentId,totalInputTokens:i.usage.inputTokens,totalOutputTokens:i.usage.outputTokens,totalTokens:i.usage.totalTokens,totalCost:i.usage.estimatedCostUsd||0,tasksExecuted:1,patternsReused:i.patternReused?1:0,estimatedTokensSaved:i.tokensSaved||0})}let s=new Map;for(let i of e){let o=s.get(i.domain);o?(o.inputTokens+=i.usage.inputTokens,o.outputTokens+=i.usage.outputTokens,o.totalTokens+=i.usage.totalTokens,o.estimatedCostUsd=(o.estimatedCostUsd||0)+(i.usage.estimatedCostUsd||0)):s.set(i.domain,{...i.usage})}let r=n.totalTokens,c=this.totalTokensSaved,d=r+c>0?c/(r+c)*100:0;return{sessionId:this.sessionId,startTime:this.sessionStartTime,endTime:Date.now(),byAgent:a,byDomain:s,totalUsage:n,optimizationStats:{patternsReused:this.totalPatternsReused,cacheHits:this.cacheHits,earlyExits:this.earlyExits,tokensSaved:this.totalTokensSaved,savingsPercentage:Math.round(d*100)/100}}}getAgentMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.agentId===t);return this.aggregateAgentMetrics(t,s)}let a=new Map;for(let s of n){let r=a.get(s.agentId)||[];r.push(s),a.set(s.agentId,r)}return Array.from(a.entries()).map(([s,r])=>this.aggregateAgentMetrics(s,r))}getDomainMetrics(t,e){this.ensureInitialized();let n=this.filterByTimeframe(this.taskMetrics,e);if(t){let s=n.filter(r=>r.domain===t);return this.aggregateTokenUsage(s)}let a=new Map;for(let s of n){let r=a.get(s.domain);r?(r.inputTokens+=s.usage.inputTokens,r.outputTokens+=s.usage.outputTokens,r.totalTokens+=s.usage.totalTokens,r.estimatedCostUsd=(r.estimatedCostUsd||0)+(s.usage.estimatedCostUsd||0)):a.set(s.domain,{...s.usage})}return a}getTaskMetrics(t){return this.ensureInitialized(),this.filterByTimeframe(this.taskMetrics,t)}getEfficiencyReport(t){return this.getTokenEfficiency(t)}getTokenEfficiency(t){this.ensureInitialized();let e=this.filterByTimeframe(this.taskMetrics,t),a=this.aggregateTokenUsage(e).totalTokens,s=this.totalTokensSaved,r=a+s>0?s/(a+s)*100:0,c=e.length,d=c>0?e.filter(l=>l.patternReused).length/c:0,i=c>0?a/c:0,o=this.generateRecommendations(e);return{totalTokensUsed:a,totalTokensSaved:s,savingsPercentage:Math.round(r*100)/100,patternReuseRate:Math.round(d*100)/100,averageTokensPerTask:Math.round(i),recommendations:o}}reset(){this.stopAutoSave(),this.taskMetrics=[],this.agentMetrics.clear(),this.domainMetrics.clear(),this.sessionId=`session-${Date.now()}-${v().substring(0,8)}`,this.sessionStartTime=Date.now(),this.cacheHits=0,this.earlyExits=0,this.totalTokensSaved=0,this.totalPatternsReused=0,this.isDirty=!1}configurePersistence(t){this.persistenceConfig={...this.persistenceConfig,...t},t.autoSaveIntervalMs!==void 0&&(this.stopAutoSave(),t.autoSaveIntervalMs>0&&this.startAutoSave())}startAutoSave(){this.autoSaveTimer||this.persistenceConfig.autoSaveIntervalMs>0&&(this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.save().catch(t=>{console.warn("[TokenMetricsCollector] Auto-save failed:",t)})},this.persistenceConfig.autoSaveIntervalMs))}stopAutoSave(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=null)}async save(){let t=await import("fs"),e=await import("path"),n={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()},a=e.resolve(this.persistenceConfig.filePath),s=e.dirname(a);t.existsSync(s)||t.mkdirSync(s,{recursive:!0}),t.writeFileSync(a,JSON.stringify(n,null,2)),this.isDirty=!1}async load(){let t=await import("fs"),n=(await import("path")).resolve(this.persistenceConfig.filePath);if(!t.existsSync(n))return!1;try{let a=t.readFileSync(n,"utf-8"),s=h(a);if(!s.version||!s.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible data version, skipping load"),!1;let r=s.taskMetrics||[];this.taskMetrics=[...r,...this.taskMetrics],this.cacheHits+=s.optimizationStats?.cacheHits||0,this.earlyExits+=s.optimizationStats?.earlyExits||0,this.totalTokensSaved+=s.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=s.optimizationStats?.totalPatternsReused||0;for(let c of r)this.updateAgentMetrics(c.agentId,c.usage,c.patternReused,c.tokensSaved||0),this.updateDomainMetrics(c.domain,c.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}catch(a){return console.warn("[TokenMetricsCollector] Failed to load persisted data:",a),!1}}getPersistenceFilePath(){return this.persistenceConfig.filePath}hasUnsavedChanges(){return this.isDirty}async initializeDb(){try{this.db=f(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(t){console.warn("[TokenMetricsCollector] DB init failed, using memory-only:",T(t)),this.db=null}}async persistToKv(){if(!this.db)return;let t={version:"1.0.0",sessionId:this.sessionId,sessionStartTime:this.sessionStartTime,taskMetrics:this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory),optimizationStats:{cacheHits:this.cacheHits,earlyExits:this.earlyExits,totalTokensSaved:this.totalTokensSaved,totalPatternsReused:this.totalPatternsReused},lastSavedAt:Date.now()};await this.db.kvSet(u.KV_KEY,t,u.KV_NAMESPACE,u.KV_TTL)}async loadFromKv(){if(!this.db)return!1;let t=await this.db.kvGet(u.KV_KEY,u.KV_NAMESPACE);if(!t)return!1;if(!t.version||!t.version.startsWith("1."))return console.warn("[TokenMetricsCollector] Incompatible kv_store data version, skipping load"),!1;let e=t.taskMetrics||[];this.taskMetrics=[...e,...this.taskMetrics],this.cacheHits+=t.optimizationStats?.cacheHits||0,this.earlyExits+=t.optimizationStats?.earlyExits||0,this.totalTokensSaved+=t.optimizationStats?.totalTokensSaved||0,this.totalPatternsReused+=t.optimizationStats?.totalPatternsReused||0;for(let n of e)this.updateAgentMetrics(n.agentId,n.usage,n.patternReused,n.tokensSaved||0),this.updateDomainMetrics(n.domain,n.usage);return this.taskMetrics.length>this.persistenceConfig.maxMetricsInMemory&&(this.taskMetrics=this.taskMetrics.slice(-this.persistenceConfig.maxMetricsInMemory)),!0}maybePersistToKv(){this.kvPersistCount++,this.kvPersistCount>=u.KV_PERSIST_INTERVAL&&(this.kvPersistCount=0,this.persistToKv().catch(t=>{M.warn("KV persist failed",{error:t instanceof Error?t.message:String(t)})}))}ensureInitialized(){this.initialized||this.initialize()}calculateCost(t){let e=t.inputTokens*this.costConfig.costPerInputToken,n=t.outputTokens*this.costConfig.costPerOutputToken;return Math.round((e+n)*1e5)/1e5}filterByTimeframe(t,e){if(!e)return t;let n=Date.now(),a;switch(e){case"1h":a=n-3600*1e3;break;case"24h":a=n-1440*60*1e3;break;case"7d":a=n-10080*60*1e3;break;case"30d":a=n-720*60*60*1e3;break;default:return t}return t.filter(s=>s.timestamp>=a)}aggregateTokenUsage(t){let e=0,n=0,a=0,s=0;for(let r of t)e+=r.usage.inputTokens,n+=r.usage.outputTokens,a+=r.usage.totalTokens,s+=r.usage.estimatedCostUsd||0;return{inputTokens:e,outputTokens:n,totalTokens:a,estimatedCostUsd:Math.round(s*1e5)/1e5}}aggregateAgentMetrics(t,e){let n=0,a=0,s=0,r=0,c=0,d=0;for(let i of e)n+=i.usage.inputTokens,a+=i.usage.outputTokens,s+=i.usage.totalTokens,r+=i.usage.estimatedCostUsd||0,i.patternReused&&c++,d+=i.tokensSaved||0;return{agentId:t,totalInputTokens:n,totalOutputTokens:a,totalTokens:s,totalCost:Math.round(r*1e5)/1e5,tasksExecuted:e.length,patternsReused:c,estimatedTokensSaved:d}}updateAgentMetrics(t,e,n,a){let s=this.agentMetrics.get(t);s?(s.totalInputTokens+=e.inputTokens,s.totalOutputTokens+=e.outputTokens,s.totalTokens+=e.totalTokens,s.totalCost+=e.estimatedCostUsd||0,s.tasksExecuted++,n&&s.patternsReused++,s.estimatedTokensSaved+=a):this.agentMetrics.set(t,{agentId:t,totalInputTokens:e.inputTokens,totalOutputTokens:e.outputTokens,totalTokens:e.totalTokens,totalCost:e.estimatedCostUsd||0,tasksExecuted:1,patternsReused:n?1:0,estimatedTokensSaved:a})}updateDomainMetrics(t,e){let n=this.domainMetrics.get(t);n?(n.inputTokens+=e.inputTokens,n.outputTokens+=e.outputTokens,n.totalTokens+=e.totalTokens,n.estimatedCostUsd=(n.estimatedCostUsd||0)+(e.estimatedCostUsd||0)):this.domainMetrics.set(t,{...e})}generateRecommendations(t){let e=[];if(t.length===0)return["No token usage data available yet. Start executing tasks to track consumption."];let n=t.filter(i=>i.patternReused).length/t.length;n<.2?e.push("Low pattern reuse rate detected. Consider enabling pattern caching for similar tasks."):n>.5&&e.push("Good pattern reuse rate. Continue leveraging cached patterns for token savings.");let a=new Map;for(let i of t){let o=a.get(i.domain)||0;a.set(i.domain,o+i.usage.totalTokens)}let s=Array.from(a.entries()).sort((i,o)=>o[1]-i[1]);if(s.length>0){let i=s[0];e.push(`Highest token consumer: ${i[0]} (${i[1].toLocaleString()} tokens). Consider optimizing prompts or increasing caching.`)}let r=t.reduce((i,o)=>i+o.usage.inputTokens,0);return t.reduce((i,o)=>i+o.usage.outputTokens,0)/(r||1)>2&&e.push("High output-to-input token ratio. Consider requesting more concise responses."),this.cacheHits===0&&t.length>10&&e.push("No cache hits detected. Enable response caching to reduce duplicate API calls."),this.earlyExits===0&&t.length>20&&e.push("Early exit optimization not utilized. Enable high-confidence pattern matching to skip unnecessary LLM calls."),e}};function b(u){return u.toLocaleString("en-US")}function z(u){if(process.env.AQE_TOKEN_DASHBOARD_ENABLED==="false")return"Token dashboard disabled (AQE_TOKEN_DASHBOARD_ENABLED=false)";if(!u){let d=E.getSessionSummary(),i=d.totalUsage.totalTokens,o=d.totalUsage.estimatedCostUsd??0,l=d.optimizationStats.tokensSaved,k=i>0?o/i:0,g=l*k;u={totalTokens:i,totalCostUsd:o,savedTokens:l,savedCostUsd:g}}let t=u.totalTokens??0,e=u.totalCostUsd??0,n=u.savedTokens??0,a=u.savedCostUsd??0,s=u.budgetLimitUsd;if(t===0&&n===0)return"Token Dashboard: No data available";let r=`Token Usage: ${b(t)} tokens ($${e.toFixed(2)})`;n>0&&(r+=` | Saved: ${b(n)} tokens ($${a.toFixed(2)}) via pattern reuse`);let c=[];if(s!==void 0&&s>0){let d=Math.round(e/s*100);c.push(`Budget: $${e.toFixed(2)} / $${s.toFixed(2)} (${d}%)`)}if(u.tierSplit&&Object.keys(u.tierSplit).length>0){let d=Object.entries(u.tierSplit).sort((i,o)=>o[1]-i[1]).map(([i,o])=>`${i} ${o}%`);c.push(`Tier split: ${d.join(" | ")}`)}return c.length===0?r:`${r}
3
3
  ${c.join(" | ")}`}var E=new m;function $(u){return`$${u.toFixed(2)}`}export{z as a,E as b,$ as c};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{a as R}from"./chunk-45MVRQG4.js";import{e as g}from"./chunk-IEPWO4XP.js";import{S as v,b as l}from"./chunk-A7ANPS4E.js";R();v();import{createHash as m,randomUUID as f}from"crypto";var a=g.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{a as R}from"./chunk-X6VYQVUM.js";import{e as g}from"./chunk-7H3GNRNA.js";import{S as v,b as l}from"./chunk-KVMKYUOE.js";R();v();import{createHash as m,randomUUID as f}from"crypto";var a=g.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain_receipts (
4
4
  id TEXT PRIMARY KEY,
5
5
  chain_index INTEGER NOT NULL,
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
2
  function M(u){let e=u|0;return()=>{e=e+1831565813|0;let n=Math.imul(e^e>>>15,1|e);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}var A=2,y=10,x=200,p=1e-8,b=class{epsilon;seed;constructor(e){if(this.epsilon=e?.epsilon??.3,this.seed=e?.seed,this.epsilon<=0||this.epsilon>=1)throw new Error("SparsifierConfig.epsilon must be in (0, 1)")}sparsify(e){if(e.nodeCount<=0||e.edges.length===0)return{nodeCount:e.nodeCount,edges:[]};let n=this.seed!==void 0?M(this.seed):Math.random,t=this.approximateEffectiveResistances(e),i=e.nodeCount,r=e.edges.length,o=Math.max(1,Math.log(i)),m=this.epsilon*this.epsilon,l=Math.min(r,Math.max(i-1,A*(i-1)*(1-this.epsilon))),s=new Float64Array(r),c=0;for(let a=0;a<r;a++){let d=e.edges[a][2];s[a]=d*t[a],c+=s[a]}if(c<=0)return{nodeCount:e.nodeCount,edges:[]};let f=[];for(let a=0;a<r;a++){let[d,C,E]=e.edges[a],g=Math.min(1,s[a]/c*l);if(n()<g){let w=E/g;f.push([d,C,w])}}return{nodeCount:e.nodeCount,edges:f}}validateSpectral(e,n){let t=Math.min(y,Math.max(1,e.nodeCount-1)),i=this.computeLaplacian(e),r=this.computeLaplacian(n),o=this.computeTopEigenvalues(i,t),m=this.computeTopEigenvalues(r,t),l=[],s=!0,c=this.epsilon;for(let f=0;f<o.length;f++){if(o[f]<1e-10)continue;let a=m[f]/o[f];l.push(a),(a<1-c||a>1+c)&&(s=!1)}return{isValid:s,eigenvalueRatios:l,originalEdgeCount:e.edges.length,sparsifiedEdgeCount:n.edges.length,compressionRatio:e.edges.length>0?n.edges.length/e.edges.length:0}}computeLaplacian(e){let n=e.nodeCount,t=Array.from({length:n},()=>new Array(n).fill(0));for(let[i,r,o]of e.edges)i<0||i>=n||r<0||r>=n||(t[i][i]+=o,t[r][r]+=o,t[i][r]-=o,t[r][i]-=o);return t}computeTopEigenvalues(e,n){let t=e.length;if(t===0)return[];let i=[],r=[],o=e.map(m=>[...m]);for(let m=0;m<Math.min(n,t);m++){let l=this.powerIteration(o,t,r);if(l===null)break;i.push(l.eigenvalue),r.push(l.eigenvector),V(o,l.eigenvalue,l.eigenvector)}return i}approximateEffectiveResistances(e){let n=e.nodeCount,t=new Float64Array(n);for(let[r,o,m]of e.edges)r>=0&&r<n&&(t[r]+=m),o>=0&&o<n&&(t[o]+=m);let i=new Array(e.edges.length);for(let r=0;r<e.edges.length;r++){let[o,m]=e.edges[r],l=t[o]||1,s=t[m]||1;i[r]=1/l+1/s}return i}powerIteration(e,n,t){let i=0;for(let s=0;s<n;s++)for(let c=0;c<n;c++)i+=e[s][c]*e[s][c];if(i<p*p)return null;let r=t.length,o=new Array(n);for(let s=0;s<n;s++)o[s]=Math.sin((s+1)*(r+1)*1.618033988749895)+.1*(s-n/2);for(let s of t)h(o,s);if(R(o)<p)return null;let l=0;for(let s=0;s<x;s++){let c=L(e,o);for(let d of t)h(c,d);let f=S(c,o),a=v(c);if(a<p)return{eigenvalue:0,eigenvector:o};for(let d=0;d<n;d++)o[d]=c[d]/a;if(Math.abs(f-l)<p){l=f;break}l=f}return{eigenvalue:Math.abs(l),eigenvector:o}}};function L(u,e){let n=u.length,t=new Array(n).fill(0);for(let i=0;i<n;i++){let r=0;for(let o=0;o<n;o++)r+=u[i][o]*e[o];t[i]=r}return t}function v(u){let e=0;for(let n=0;n<u.length;n++)e+=u[n]*u[n];return Math.sqrt(e)}function R(u){let e=v(u);if(e>0)for(let n=0;n<u.length;n++)u[n]/=e;return e}function S(u,e){let n=0;for(let t=0;t<u.length;t++)n+=u[t]*e[t];return n}function h(u,e){let n=S(u,e);for(let t=0;t<u.length;t++)u[t]-=n*e[t]}function V(u,e,n){let t=n.length;for(let i=0;i<t;i++)for(let r=0;r<t;r++)u[i][r]-=e*n[i]*n[r]}export{b as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{e as U,h as W,i as G}from"./chunk-BIXRTOH3.js";import{b as F}from"./chunk-OPDZBRIL.js";import{o as j,q as V}from"./chunk-ONPPBLRB.js";import{b as D,c as $,d as Y}from"./chunk-K55EAWZ5.js";import{a as T,e as N}from"./chunk-KYVIOC3C.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{e as U,h as W,i as G}from"./chunk-UTFMMZ57.js";import{b as F}from"./chunk-MMY52Y6R.js";import{o as j,q as V}from"./chunk-K4N2MBCE.js";import{b as D,c as $,d as Y}from"./chunk-RG42LDOB.js";import{a as T,e as N}from"./chunk-J7FLNP5L.js";N();Y();import*as C from"fs";import*as b from"path";import*as H from"yaml";var z=5,X=4,Z=3e4,ee=".claude/skills",te=5e3,se=500,K=100,re=1e3,q=500,ne=.8,ae=.2,ie=.1,w=.1,oe=.1,le=.1,ce=.1,ue=200,de=500,pe=300,me=1,ge=.9,Q={maxWorkers:z,batchSize:X,retryFailedTests:!0,timeout:Z,skillsDir:ee,progressIntervalMs:te},S=class{async execute(e,r,s){let t=$(K,se+K);return await new Promise(i=>setTimeout(i,t)),{output:this.generateMockResponse(e),tokensUsed:D(q,re+q),durationMs:t}}generateMockResponse(e){let r=[];return e.includes("alt")&&r.push("alt","1.1.1","perceivable"),e.includes("contrast")&&r.push("contrast","1.4.3","4.5:1"),e.includes("keyboard")&&r.push("keyboard","2.1.1","operable","button"),e.includes("label")&&r.push("label","3.3.2","understandable"),e.includes("ARIA")&&r.push("ARIA","4.1.2","robust"),e.includes("focus")&&r.push("focus","2.4.7","outline"),e.includes("lang")&&r.push("lang","3.1.1","language"),e.includes("caption")&&r.push("caption","1.2.2","track"),e.includes("accessible")&&r.push("accessible","compliant"),r.length===0&&r.push("accessibility","WCAG","finding"),`Analysis complete. Found issues related to: ${r.join(", ")}.
3
3
  Recommendations: Implement proper ${r[0]} attributes for better accessibility.
4
4
  Severity: ${e.includes("critical")?"critical":"serious"}`}},P=class{constructor(e,r,s){this.executor=r;this.config=s;this.id=e}executor;config;id;status="idle";tasksCompleted=0;tasksFailed=0;lastHeartbeat=Date.now();async executeBatch(e){this.status="running";let r=[];for(let s of e){this.lastHeartbeat=Date.now();try{let t=await this.executeTestCase(s);if(r.push(t),t.passed)this.tasksCompleted++;else if(this.tasksFailed++,this.config.retryFailedTests&&!t.passed){let a=await this.executeTestCase(s,!0);a.passed&&(r[r.length-1]=a,this.tasksCompleted++,this.tasksFailed--)}}catch(t){this.tasksFailed++,r.push({testId:s.testCaseId,passed:!1,expectedPatterns:s.testCase.expected_output.must_contain||[],actualPatterns:[],reasoningQuality:0,category:s.testCase.category,priority:s.testCase.priority,error:T(t)})}}return this.status="idle",r}async executeTestCase(e,r=!1){let s=Date.now(),t=this.buildPrompt(e),a=await this.executor.execute(t,e.model,{timeout:this.config.timeout}),i=this.validateResponse(a.output,e.testCase.expected_output,e.testCase.validation);return{testId:e.testCaseId,passed:i.passed,expectedPatterns:e.testCase.expected_output.must_contain||[],actualPatterns:i.foundPatterns,reasoningQuality:i.reasoningQuality,executionTimeMs:Date.now()-s,category:e.testCase.category,priority:e.testCase.priority,error:i.error}}buildPrompt(e){let{testCase:r}=e,s=r.input.context;return`Analyze the following ${s.language||"HTML"} code for accessibility issues.
5
5
  Context: ${s.description||r.description}
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{b as h,d as v,f as T}from"./chunk-7SAMMQVS.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>I,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>_,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var O,g,_,I,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{O=A(import.meta.url),g=O("@ruvector/rvf-node"),_=g,{RuvectorLayer:I,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}has(e){return this.ensureOpen(),this.strToNum.has(e)}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{b as h,d as v,f as T}from"./chunk-K5R3WUJP.js";var y={};v(y,{DotProductAttention:()=>z,FlashAttention:()=>k,HyperbolicAttention:()=>C,LinearAttention:()=>j,MoEAttention:()=>W,MultiHeadAttention:()=>F,RuvectorLayer:()=>I,SonaEngine:()=>K,TensorCompress:()=>E,default:()=>_,differentiableSearch:()=>L,getCompressionLevel:()=>B,hierarchicalForward:()=>V,init:()=>D,pipeline:()=>q});import{createRequire as A}from"module";var O,g,_,I,E,L,V,B,D,k,z,F,C,j,W,K,q,R=h(()=>{O=A(import.meta.url),g=O("@ruvector/rvf-node"),_=g,{RuvectorLayer:I,TensorCompress:E,differentiableSearch:L,hierarchicalForward:V,getCompressionLevel:B,init:D,FlashAttention:k,DotProductAttention:z,MultiHeadAttention:F,HyperbolicAttention:C,LinearAttention:j,MoEAttention:W,SonaEngine:K,pipeline:q}=g||{}});var Z={};v(Z,{createRvfStore:()=>$,isRvfNativeAvailable:()=>X,openRvfStore:()=>G,openRvfStoreReadonly:()=>U});import{readFileSync as J,writeFileSync as H,copyFileSync as Q,existsSync as Y}from"fs";function c(){if(S)return m;S=!0;try{let s=(R(),T(y));!s.RvfDatabase&&s.default&&s.default.RvfDatabase&&(s=s.default),m=s}catch{m=null}return m}function w(s){return`${s}.idmap.json`}function N(s){let e=w(s),t=new Map,n=new Map,i=1;if(Y(e))try{let r=JSON.parse(J(e,"utf-8"));i=r.nextLabel;for(let[a,p]of r.entries)t.set(a,p),n.set(p,a)}catch{}return{strToNum:t,numToStr:n,nextLabel:i}}function b(s,e,t){let n={nextLabel:t,entries:Array.from(e.entries())};H(w(s),JSON.stringify(n),"utf-8")}function $(s,e){let t=c();if(!t)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let n=t.RvfDatabase.create(s,{dimension:e}),i=n.dimension();return new d(n,s,i,new Map,new Map,1)}function G(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.open(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function U(s){let e=c();if(!e)throw new Error("@ruvector/rvf-node is not available \u2014 install the package or check platform compatibility");let t=e.RvfDatabase.openReadonly(s),n=t.dimension(),{strToNum:i,numToStr:r,nextLabel:a}=N(s);return new d(t,s,n,i,r,a)}function X(){return process.env.AQE_MEMORY_BACKEND==="memory"?!1:c()!==null}var m,S,d,P=h(()=>{m=null,S=!1;d=class s{db;_path;_dimension;strToNum;numToStr;nextLabel;_open;constructor(e,t,n,i,r,a){this.db=e,this._path=t,this._dimension=n,this.strToNum=i,this.numToStr=r,this.nextLabel=a,this._open=!0}ingest(e){if(this.ensureOpen(),e.length===0)return{accepted:0,rejected:0};let t=this._dimension,n=new Float32Array(e.length*t),i=[],r=[];for(let o=0;o<e.length;o++){let{id:u,vector:f,metadata:x}=e[o],l=this.strToNum.get(u);l===void 0&&(l=this.nextLabel++,this.strToNum.set(u,l),this.numToStr.set(l,u)),i.push(l),r.push(x);let M=f instanceof Float32Array?f:new Float32Array(f);n.set(M.subarray(0,t),o*t)}let a;if(r.some(o=>o!==void 0)&&typeof this.db.ingestBatchWithMetadata=="function"){let o=r.map(u=>u?JSON.stringify(u):"");a=this.db.ingestBatchWithMetadata(n,i,o)}else a=this.db.ingestBatch(n,i);return this.persistIdMap(),{accepted:a.accepted,rejected:a.rejected}}has(e){return this.ensureOpen(),this.strToNum.has(e)}search(e,t){this.ensureOpen();let n=e instanceof Float32Array?e:new Float32Array(e);return this.db.query(n,t).map(r=>{let a=this.numToStr.get(r.id);return a===void 0?null:{id:a,distance:r.distance,score:1/(1+r.distance)}}).filter(r=>r!==null)}delete(e){this.ensureOpen();let t=[];for(let i of e){let r=this.strToNum.get(i);r!==void 0&&t.push(r)}if(t.length===0)return 0;let n=this.db.delete(t);for(let i of e){let r=this.strToNum.get(i);r!==void 0&&(this.strToNum.delete(i),this.numToStr.delete(r))}return this.persistIdMap(),n.deleted}fork(e){this.ensureOpen(),Q(this._path,e);let t=new Map(this.strToNum),n=new Map(this.numToStr);b(e,t,this.nextLabel);let r=c().RvfDatabase.open(e);return new s(r,e,this._dimension,t,n,this.nextLabel)}status(){this.ensureOpen();let e=this.db.status(),n=this.db.segments().filter(i=>i.segType==="witness");return{totalVectors:e.totalVectors,totalSegments:e.totalSegments,fileSizeBytes:e.fileSize,epoch:e.currentEpoch,witnessValid:n.length>0,witnessEntries:n.length,deadSpaceRatio:typeof e.deadSpaceRatio=="number"?e.deadSpaceRatio:0}}dimension(){return this._dimension}size(){return this.ensureOpen(),this.db.status().totalVectors}compact(){this.ensureOpen();try{let e=this.db.compact();return e&&typeof e=="object"?{segmentsCompacted:typeof e.segmentsCompacted=="number"?e.segmentsCompacted:0,bytesReclaimed:typeof e.bytesReclaimed=="number"?e.bytesReclaimed:0,epoch:typeof e.epoch=="number"?e.epoch:0}:{segmentsCompacted:0,bytesReclaimed:0,epoch:0}}catch{return null}}close(){this._open&&(this.db.close(),this._open=!1)}isOpen(){return this._open}path(){return this._path}embedKernel(e){return this.ensureOpen(),this.db.embedKernel(0,99,0,e,0,"")}extractKernel(){return this.ensureOpen(),this.db.extractKernel()}verifyWitness(){this.ensureOpen();let e=this.tryNative("verifyWitness");return e?{valid:e.valid??!0,totalEntries:e.totalEntries??0,errors:Array.isArray(e.errors)?e.errors:[]}:{valid:!0,totalEntries:0,errors:[]}}sign(e){this.ensureOpen();let t=this.tryNative("sign",e);return typeof t=="string"?t:null}fileId(){this.ensureOpen();let e=this.tryNative("fileId");return typeof e=="string"?e:null}parentId(){this.ensureOpen();let e=this.tryNative("parentId");return typeof e=="string"?e:null}lineageDepth(){this.ensureOpen();let e=this.tryNative("lineageDepth");return typeof e=="number"?e:0}indexStats(){let e=this.status();return{totalVectors:e.totalVectors,dimension:this._dimension,totalSegments:e.totalSegments,fileSizeBytes:e.fileSizeBytes,epoch:e.epoch,witnessValid:e.witnessValid,witnessEntries:e.witnessEntries,idMapSize:this.strToNum.size}}freeze(){this.ensureOpen();let e=this.tryNative("freeze");return typeof e=="number"?e:0}derive(e){this.ensureOpen();let t=c();if(typeof this.db.derive=="function")try{let n=this.db.derive(e),i=new Map(this.strToNum),r=new Map(this.numToStr);return b(e,i,this.nextLabel),new s(n,e,this._dimension,i,r,this.nextLabel)}catch{}return this.fork(e)}ensureOpen(){if(!this._open)throw new Error("RVF database is closed")}tryNative(e,...t){if(typeof this.db[e]!="function")return null;try{return this.db[e](...t)}catch{return null}}persistIdMap(){b(this._path,this.strToNum,this.nextLabel)}}});export{$ as a,G as b,U as c,X as d,Z as e,P as f};
@@ -0,0 +1,3 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{b as S}from"./chunk-K5R3WUJP.js";import{createHash as C}from"crypto";import*as a from"fs";import*as c from"os";import*as n from"path";function P(t){try{return a.realpathSync.native(t)}catch{return t}}function i(){let t="",r="";try{t=c.tmpdir()}catch{}try{r=c.homedir()}catch{}return{platform:process.platform,tmpdir:t,homedir:r,env:process.env,realpath:P}}function m(t){return t==="win32"?n.win32:n.posix}function l(t,r=i()){let e=m(r.platform),o=e.resolve(r.realpath(e.resolve(t))),s=e.parse(o).root.length;for(;o.length>s&&/[\\/]$/.test(o);)o=o.slice(0,-1);return r.platform==="win32"?o.toLowerCase():o}function w(t,r=i()){let e=m(r.platform),o=l(t,r);if(r.tmpdir&&o===l(r.tmpdir,r))return!0;if(r.platform==="win32")return o===e.parse(o).root.toLowerCase();let s=e.resolve(t);return y.some(p=>p===s||l(p,r)===o)}function b(t,r=i()){if(r.platform==="win32")return!1;try{return(a.statSync(t).mode&514)===514}catch{return!1}}function k(t,r=i()){return w(t,r)||b(t,r)}function A(t=i()){let r=m(t.platform),e;if(t.platform==="win32")e=t.env.LOCALAPPDATA||r.join(t.homedir,"AppData","Local");else if(t.platform==="darwin")e=r.join(t.homedir,"Library","Caches");else{let o=t.env.XDG_CACHE_HOME;e=o&&r.isAbsolute(o)?o:r.join(t.homedir,".cache")}return r.join(e,"agentic-qe","scratch")}function E(t,r=i()){let e=C("sha256").update(l(t,r)).digest("hex").slice(0,16);return m(r.platform).join(A(r),e)}function u(t){a.mkdirSync(t,{recursive:!0,mode:448}),process.platform!=="win32"&&a.chmodSync(t,448)}function R(t,r=i()){let e=E(t,r);try{return u(e),d(e,t),e}catch(o){let s=typeof process.getuid=="function"?String(process.getuid()):"user",p=n.join(r.tmpdir||c.tmpdir(),`agentic-qe-scratch-${s}`),f=n.join(p,n.basename(e));try{return u(p),u(f),d(f,t),f}catch(v){let g=h=>h instanceof Error?h.message:String(h);throw new Error(`Cannot create a private AQE scratch root for "${t}". User cache "${e}" failed: ${g(o)}. Temporary fallback "${f}" failed: ${g(v)}. Set AQE_PROJECT_ROOT to a project directory or make the user cache writable.`)}}}function d(t,r){let e=n.join(t,"SCRATCH_ROOT_FOR");try{a.existsSync(e)||a.writeFileSync(e,`${n.resolve(r)}
3
+ `,{mode:384})}catch{}}var y,O=S(()=>{"use strict";y=["/","/tmp","/var/tmp","/usr/tmp","/dev/shm","/run/shm","/private","/private/tmp","/private/var","/private/var/tmp","/var","/usr","/etc","/opt","/srv","/mnt","/media","/run","/home","/Users","/Volumes"]});export{w as a,b,k as c,E as d,R as e,O as f};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.6");process.exit(0)}
2
- import{b as s}from"./chunk-7SAMMQVS.js";function A(r=l,o=process.env){let t=o.AQE_OLLAMA_URL??o.OLLAMA_URL??r,e=t.length;for(;e>0&&t.charCodeAt(e-1)===47;)e-=1;return t.slice(0,e)}var l,n=s(()=>{"use strict";l="http://localhost:11434"});export{A as a,n as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.8");process.exit(0)}
2
+ import{b as s}from"./chunk-K5R3WUJP.js";function A(r=l,o=process.env){let t=o.AQE_OLLAMA_URL??o.OLLAMA_URL??r,e=t.length;for(;e>0&&t.charCodeAt(e-1)===47;)e-=1;return t.slice(0,e)}var l,n=s(()=>{"use strict";l="http://localhost:11434"});export{A as a,n as b};