agentic-qe 3.14.4 → 3.14.5

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 (403) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +93 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/audit/witness-chain.d.ts +1 -1
  5. package/dist/audit/witness-chain.js +29 -22
  6. package/dist/cli/bundle.js +13 -10
  7. package/dist/cli/chunks/adapter-IYC62SXA.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-5PC7D2FW.js → agent-booster-wasm-EDNKP3SP.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-RDNTK4CA.js → agent-handler-V6CZ7Q6S.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-NAAMBWIR.js → agent-memory-branch-ZMD6ULC3.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-LLOU2IXD.js +2 -0
  12. package/dist/cli/chunks/{arena-HXTWJ5YY.js → arena-4UPAEHFT.js} +4 -4
  13. package/dist/cli/chunks/{arena-KXFHRWX4.js → arena-QLSBESC7.js} +2 -2
  14. package/dist/cli/chunks/{audit-YSGA7UWT.js → audit-CVZQMF55.js} +3 -3
  15. package/dist/cli/chunks/base-P3Z4IKCT.js +2 -0
  16. package/dist/cli/chunks/{better-sqlite3-UICJZIDG.js → better-sqlite3-4DSBPDRH.js} +2 -2
  17. package/dist/cli/chunks/brain-handler-GBY4EZ4P.js +94 -0
  18. package/dist/cli/chunks/{branch-enumerator-SS7UNVIA.js → branch-enumerator-XYBVXCNO.js} +2 -2
  19. package/dist/cli/chunks/{browser-77GI6KBE.js → browser-32F6MREU.js} +2 -2
  20. package/dist/cli/chunks/browser-workflow-YYHQQ25X.js +2 -0
  21. package/dist/cli/chunks/{chunk-FGYMFUE2.js → chunk-2JGEZHWY.js} +2 -2
  22. package/dist/cli/chunks/{chunk-MOBNBMFW.js → chunk-2KJQ2UQE.js} +1 -1
  23. package/dist/cli/chunks/{chunk-C2WU3533.js → chunk-2OMLTYQK.js} +1 -1
  24. package/dist/cli/chunks/{chunk-CU46J64M.js → chunk-37TUN44F.js} +2 -2
  25. package/dist/cli/chunks/{chunk-Z3RHREWF.js → chunk-3DDXWYMO.js} +1 -1
  26. package/dist/cli/chunks/{chunk-Q5DO24IJ.js → chunk-3EZ5DR2R.js} +3 -3
  27. package/dist/cli/chunks/{chunk-WLG5AJ4N.js → chunk-3KDL6QDK.js} +2 -2
  28. package/dist/cli/chunks/{chunk-MTZH7AHC.js → chunk-3VIXOHMS.js} +1 -1
  29. package/dist/cli/chunks/{chunk-ISDMD6EU.js → chunk-3YUB5HER.js} +96 -96
  30. package/dist/cli/chunks/{chunk-CDKG6EI7.js → chunk-4FWTLJEP.js} +2 -2
  31. package/dist/cli/chunks/{chunk-HDSAM2RE.js → chunk-52L77RMG.js} +2 -2
  32. package/dist/cli/chunks/{chunk-MEGDYJPV.js → chunk-5D36YHS3.js} +4 -4
  33. package/dist/cli/chunks/{chunk-T6BVLVI5.js → chunk-5WOSWNDN.js} +1 -1
  34. package/dist/cli/chunks/{chunk-M2JBBZQB.js → chunk-67YV75XP.js} +2 -2
  35. package/dist/cli/chunks/{chunk-KHFNNVJA.js → chunk-6A44AOGN.js} +2 -2
  36. package/dist/cli/chunks/{chunk-IPR4QP3H.js → chunk-6CR4VQBQ.js} +2 -2
  37. package/dist/cli/chunks/{chunk-XRT2WRMS.js → chunk-6ITZZIQX.js} +2 -2
  38. package/dist/cli/chunks/{chunk-4OYFXLBK.js → chunk-6LKDHEBY.js} +2 -2
  39. package/dist/cli/chunks/{chunk-FLYOJOKN.js → chunk-6TU7FEMD.js} +1 -1
  40. package/dist/cli/chunks/{chunk-6QYNWR7U.js → chunk-6VAZAHQG.js} +2 -2
  41. package/dist/cli/chunks/{chunk-TWAWHOP7.js → chunk-73EI4C2E.js} +2 -2
  42. package/dist/cli/chunks/{chunk-5R3QL7WN.js → chunk-75QJ5HWE.js} +2 -2
  43. package/dist/cli/chunks/{chunk-Y3MW3YBC.js → chunk-7CD7PBHY.js} +2 -2
  44. package/dist/cli/chunks/chunk-7DETTOPZ.js +14 -0
  45. package/dist/cli/chunks/{chunk-KSKEF7LZ.js → chunk-7JZJJA7U.js} +3 -3
  46. package/dist/cli/chunks/{chunk-AIHDEEJO.js → chunk-7VFY7TUR.js} +2 -2
  47. package/dist/cli/chunks/chunk-7X7JYWT4.js +27 -0
  48. package/dist/cli/chunks/chunk-AF4XKLXO.js +2 -0
  49. package/dist/cli/chunks/{chunk-6KJABXAR.js → chunk-AFEDJ3RU.js} +2 -2
  50. package/dist/cli/chunks/{chunk-5SJHQ2CO.js → chunk-AMMQOV35.js} +2 -2
  51. package/dist/cli/chunks/{chunk-6VRA2QGL.js → chunk-BHFR2EXL.js} +1 -1
  52. package/dist/cli/chunks/{chunk-ZBAKA4YB.js → chunk-BJPL6THQ.js} +1 -1
  53. package/dist/cli/chunks/{chunk-DOTK76IJ.js → chunk-BXVAVFGU.js} +2 -2
  54. package/dist/cli/chunks/{chunk-MNW6QGNJ.js → chunk-BYG36QC5.js} +2 -2
  55. package/dist/cli/chunks/chunk-C3HQL6S4.js +2 -0
  56. package/dist/cli/chunks/{chunk-PZJOPURC.js → chunk-C3Z4VVHP.js} +5 -5
  57. package/dist/cli/chunks/{chunk-OULHKEVH.js → chunk-CPC7FN52.js} +2 -2
  58. package/dist/cli/chunks/{chunk-BFP7KO7P.js → chunk-CVMNJSCB.js} +2 -2
  59. package/dist/cli/chunks/{chunk-AUXFKCQL.js → chunk-CYE2TJFV.js} +2 -2
  60. package/dist/cli/chunks/{chunk-7D777LTF.js → chunk-CZO4BJG5.js} +2 -2
  61. package/dist/cli/chunks/{chunk-VD6QRULW.js → chunk-D6OUCB2H.js} +2 -2
  62. package/dist/cli/chunks/{chunk-6UWGMOND.js → chunk-DDCIYOGT.js} +2 -2
  63. package/dist/cli/chunks/{chunk-STJCATGN.js → chunk-DKUBQQFG.js} +2 -2
  64. package/dist/cli/chunks/{chunk-M4WJKGVK.js → chunk-DLF5BOJD.js} +1 -1
  65. package/dist/cli/chunks/{chunk-DA5K5754.js → chunk-DO6EI5KB.js} +1 -1
  66. package/dist/cli/chunks/{chunk-BDESSCVR.js → chunk-DPBRWP4J.js} +3 -3
  67. package/dist/cli/chunks/{chunk-HV2J7KKQ.js → chunk-E3W6XQ57.js} +2 -2
  68. package/dist/cli/chunks/{chunk-MDWCE7YW.js → chunk-E4AZXCT5.js} +1 -1
  69. package/dist/cli/chunks/{chunk-F3SBRQC6.js → chunk-E4EYPYR3.js} +2 -2
  70. package/dist/cli/chunks/{chunk-55RWDRJD.js → chunk-EFV4ADMO.js} +4 -4
  71. package/dist/cli/chunks/{chunk-5YPYDPBJ.js → chunk-ELBZON4V.js} +2 -2
  72. package/dist/cli/chunks/{chunk-PO3IXGMQ.js → chunk-EOR2UT72.js} +2 -2
  73. package/dist/cli/chunks/{chunk-EDJ3O7RH.js → chunk-F34OAHOM.js} +2 -2
  74. package/dist/cli/chunks/{chunk-XRYF6JV7.js → chunk-FUNGTIF2.js} +2 -2
  75. package/dist/cli/chunks/{chunk-EKQ673SA.js → chunk-G3L5L6YQ.js} +1 -1
  76. package/dist/cli/chunks/{chunk-NJBGXDQ7.js → chunk-G3W6BMVJ.js} +1 -1
  77. package/dist/cli/chunks/{chunk-CIZ5JPDC.js → chunk-GTKCGPJZ.js} +3 -3
  78. package/dist/cli/chunks/{chunk-QGIU2WRL.js → chunk-HBCGYMQU.js} +1 -1
  79. package/dist/cli/chunks/{chunk-V3QLFNA2.js → chunk-HSVKZ5KI.js} +4 -4
  80. package/dist/cli/chunks/{chunk-BGE6FOLM.js → chunk-HVU64GP5.js} +2 -2
  81. package/dist/cli/chunks/chunk-HVXJC3OC.js +2 -0
  82. package/dist/cli/chunks/{chunk-MIQTXNBG.js → chunk-HYEJJJY3.js} +1 -1
  83. package/dist/cli/chunks/{chunk-CLTMDCSE.js → chunk-I2NENQ44.js} +2 -2
  84. package/dist/cli/chunks/{chunk-SGYJ4NFZ.js → chunk-I6X3EGJI.js} +1 -1
  85. package/dist/cli/chunks/{chunk-BOARZKU3.js → chunk-IGBEJ4UJ.js} +2 -2
  86. package/dist/cli/chunks/{chunk-FWGOHAAB.js → chunk-IIAR5S7Q.js} +2 -2
  87. package/dist/cli/chunks/{chunk-DHJPWQBR.js → chunk-IJHCIXJC.js} +2 -2
  88. package/dist/cli/chunks/{chunk-UEM7ZF5K.js → chunk-IUDWEOLX.js} +2 -2
  89. package/dist/cli/chunks/chunk-IUHB5GVS.js +3 -0
  90. package/dist/cli/chunks/{chunk-M5QUBZY6.js → chunk-IYTLXUBO.js} +2 -2
  91. package/dist/cli/chunks/chunk-J27F4NSB.js +2 -0
  92. package/dist/cli/chunks/{chunk-G6T45OIC.js → chunk-J5UNP6W3.js} +2 -2
  93. package/dist/cli/chunks/{chunk-3UPAMMCB.js → chunk-JES6R5KP.js} +1 -1
  94. package/dist/cli/chunks/{chunk-ZBQY5GLF.js → chunk-JROVR6YS.js} +2 -2
  95. package/dist/cli/chunks/chunk-JSZ663MU.js +2 -0
  96. package/dist/cli/chunks/{chunk-PFR4G3DJ.js → chunk-JVQBWYHW.js} +2 -2
  97. package/dist/cli/chunks/{chunk-JBNEE5UH.js → chunk-K27SU3RE.js} +2 -2
  98. package/dist/cli/chunks/{chunk-JZ3ORVZ3.js → chunk-K7NJHFLZ.js} +3 -3
  99. package/dist/cli/chunks/{chunk-3VOQRIQM.js → chunk-KEY43ANX.js} +2 -2
  100. package/dist/cli/chunks/chunk-KIP6WZGV.js +13 -0
  101. package/dist/cli/chunks/{chunk-UDHKLT4C.js → chunk-KKHYJF5U.js} +1 -1
  102. package/dist/cli/chunks/{chunk-ZNEMGX5O.js → chunk-KLTP5IDB.js} +1 -1
  103. package/dist/cli/chunks/{chunk-ONII3572.js → chunk-KO4FNAUR.js} +3 -3
  104. package/dist/cli/chunks/{chunk-TSRSV3LD.js → chunk-KYA5LARK.js} +1 -1
  105. package/dist/cli/chunks/{chunk-2JW3BCGG.js → chunk-LSUILON7.js} +1 -1
  106. package/dist/cli/chunks/chunk-LULD4JV2.js +15 -0
  107. package/dist/cli/chunks/{chunk-FRH6VAUS.js → chunk-M23ZOZVY.js} +1 -1
  108. package/dist/cli/chunks/{chunk-R5NE6B2M.js → chunk-M5AEL7IS.js} +2 -2
  109. package/dist/cli/chunks/chunk-MI5Q55DG.js +65 -0
  110. package/dist/cli/chunks/chunk-N7H767TP.js +4 -0
  111. package/dist/cli/chunks/{chunk-RJCYCLZV.js → chunk-NQI7FWCS.js} +2 -2
  112. package/dist/cli/chunks/{chunk-CXQPR5MY.js → chunk-NRE4NAVA.js} +1 -1
  113. package/dist/cli/chunks/{chunk-ODKLFVYC.js → chunk-NU7UTXMP.js} +2 -2
  114. package/dist/cli/chunks/{chunk-MVPCNSPY.js → chunk-NVYBM3R4.js} +2 -2
  115. package/dist/cli/chunks/{chunk-MVNP7GIR.js → chunk-O3JTQ7N4.js} +1 -1
  116. package/dist/cli/chunks/{chunk-6CQN24ZK.js → chunk-OEIQTWQP.js} +1 -1
  117. package/dist/cli/chunks/{chunk-U5K45TFH.js → chunk-PSPKSUF6.js} +1 -1
  118. package/dist/cli/chunks/{chunk-CDHQFHRP.js → chunk-QIRL6B3C.js} +2 -2
  119. package/dist/cli/chunks/{chunk-OSLYSG3B.js → chunk-QRCIZFNK.js} +2 -2
  120. package/dist/cli/chunks/{chunk-BOZZYWCR.js → chunk-QWUXCG2L.js} +1 -1
  121. package/dist/cli/chunks/{chunk-HIYXCDEP.js → chunk-QYOGD2VW.js} +1 -1
  122. package/dist/cli/chunks/{chunk-A4FYONNU.js → chunk-QZMUXJHZ.js} +2 -2
  123. package/dist/cli/chunks/{chunk-3TW5W5LX.js → chunk-R6IU3EWP.js} +2 -2
  124. package/dist/cli/chunks/{chunk-3X3DJZJJ.js → chunk-R74ZKREV.js} +1 -1
  125. package/dist/cli/chunks/{chunk-HIVA55CJ.js → chunk-RD2VGOUH.js} +1 -1
  126. package/dist/cli/chunks/{chunk-TPGED2IF.js → chunk-RD6TEZ64.js} +2 -2
  127. package/dist/cli/chunks/{chunk-4MHXCAG2.js → chunk-RGGK6VZ7.js} +1 -1
  128. package/dist/cli/chunks/{chunk-UGVHCMUN.js → chunk-RIZVC4XY.js} +3 -3
  129. package/dist/cli/chunks/{chunk-R4VL6E65.js → chunk-RKOUXVZZ.js} +2 -2
  130. package/dist/cli/chunks/{chunk-IFCLB7FJ.js → chunk-RP2ZKPYV.js} +1 -1
  131. package/dist/cli/chunks/{chunk-34WO57CW.js → chunk-SQF6HRXR.js} +1 -1
  132. package/dist/cli/chunks/{chunk-YNXS6CGV.js → chunk-SQKW3B6B.js} +1 -1
  133. package/dist/cli/chunks/{chunk-TDZ53WO2.js → chunk-SX4JLSLV.js} +2 -2
  134. package/dist/cli/chunks/{chunk-PAWXJ73E.js → chunk-TUSSPKRM.js} +1 -1
  135. package/dist/cli/chunks/{chunk-DFZCKIGY.js → chunk-TY5WC3FT.js} +3 -3
  136. package/dist/cli/chunks/{chunk-J6GNQS62.js → chunk-UDHVCKGA.js} +2 -2
  137. package/dist/cli/chunks/{chunk-CIKSHTEQ.js → chunk-UJWAWIRV.js} +4 -4
  138. package/dist/cli/chunks/{chunk-XJ7QNVI5.js → chunk-UKGXWW64.js} +3 -3
  139. package/dist/cli/chunks/{chunk-64PFWE2F.js → chunk-UMGFMKDW.js} +2 -2
  140. package/dist/cli/chunks/{chunk-DPFRKBOG.js → chunk-URVHZPWY.js} +2 -2
  141. package/dist/cli/chunks/{chunk-MCUJEZT6.js → chunk-UTBYJ4RF.js} +2 -2
  142. package/dist/cli/chunks/{chunk-HUWNIPZ5.js → chunk-VD5IO5EO.js} +1 -1
  143. package/dist/cli/chunks/{chunk-7ZIOFPL3.js → chunk-VTOVWHEM.js} +2 -2
  144. package/dist/cli/chunks/{chunk-SRKETSFF.js → chunk-W2XCZU62.js} +1 -1
  145. package/dist/cli/chunks/{chunk-CNG6GQEZ.js → chunk-WJHWH5D2.js} +2 -2
  146. package/dist/cli/chunks/{chunk-ZJ26AQA5.js → chunk-WJTSY5MC.js} +1 -1
  147. package/dist/cli/chunks/{chunk-OCWWP5PL.js → chunk-WK7B4B6Y.js} +2 -2
  148. package/dist/cli/chunks/{chunk-KPA7MZ6C.js → chunk-WLXK2KNU.js} +2 -2
  149. package/dist/cli/chunks/{chunk-ZBJ4XOOV.js → chunk-WOIGKU2N.js} +4 -4
  150. package/dist/cli/chunks/{chunk-ZZDIMOOV.js → chunk-WX6RRIGW.js} +2 -2
  151. package/dist/cli/chunks/{chunk-STM3UDNO.js → chunk-XEZIIQYJ.js} +2 -2
  152. package/dist/cli/chunks/{chunk-3QHGWY7T.js → chunk-XFPPERA2.js} +2 -2
  153. package/dist/cli/chunks/{chunk-VIHTL3U2.js → chunk-XLAUGSW7.js} +2 -2
  154. package/dist/cli/chunks/{chunk-XC7DYDSY.js → chunk-XQSIRBKT.js} +2 -2
  155. package/dist/cli/chunks/{chunk-GPLQ6DOK.js → chunk-XUR2M2WB.js} +2 -2
  156. package/dist/cli/chunks/{chunk-KCZR45PA.js → chunk-XZSMZHM2.js} +2 -2
  157. package/dist/cli/chunks/{chunk-ZNPKDCZR.js → chunk-Y5L3ES4L.js} +2 -2
  158. package/dist/cli/chunks/{chunk-W7BWUTVV.js → chunk-YDFL445W.js} +2 -2
  159. package/dist/cli/chunks/{chunk-AWWNB2T7.js → chunk-YQGPQBCX.js} +2 -2
  160. package/dist/cli/chunks/{chunk-DAEFDCJ4.js → chunk-YXP6BKGS.js} +17 -17
  161. package/dist/cli/chunks/{chunk-OBAP2TXZ.js → chunk-ZBABIZ2D.js} +2 -2
  162. package/dist/cli/chunks/{chunk-CSU5NYOX.js → chunk-ZCWERUYB.js} +4 -4
  163. package/dist/cli/chunks/{ci-464KPQNP.js → ci-RACDAJMR.js} +2 -2
  164. package/dist/cli/chunks/{ci-output-I7FX2RSO.js → ci-output-EHRSZBKG.js} +2 -2
  165. package/dist/cli/chunks/{circuit-breaker-3FW237WW.js → circuit-breaker-GBV7M5XG.js} +2 -2
  166. package/dist/cli/chunks/{claude-flow-setup-6JKMBPGU.js → claude-flow-setup-5LVJOFKP.js} +2 -2
  167. package/dist/cli/chunks/client-HUVFA5PF.js +2 -0
  168. package/dist/cli/chunks/{cline-installer-UWFHT6VY.js → cline-installer-W4NMXJSG.js} +2 -2
  169. package/dist/cli/chunks/{code-KQSUT3FS.js → code-JWXJMYXB.js} +3 -3
  170. package/dist/cli/chunks/{code-index-extractor-PABBNUSC.js → code-index-extractor-RVI2IFTM.js} +2 -2
  171. package/dist/cli/chunks/codex-installer-3BORJINH.js +14 -0
  172. package/dist/cli/chunks/{completions-7RWHAUAR.js → completions-A55NCTAO.js} +2 -2
  173. package/dist/cli/chunks/{complexity-analyzer-XPOAF33E.js → complexity-analyzer-JCXHGGLY.js} +2 -2
  174. package/dist/cli/chunks/{continuedev-installer-V4F2FIZP.js → continuedev-installer-PUVFMGYW.js} +2 -2
  175. package/dist/cli/chunks/{copilot-installer-JMICURQB.js → copilot-installer-4DCMYWHB.js} +2 -2
  176. package/dist/cli/chunks/core-handlers-UEXO3VAA.js +2 -0
  177. package/dist/cli/chunks/{cost-tracker-5OFHEYFJ.js → cost-tracker-5TV2GGKY.js} +2 -2
  178. package/dist/cli/chunks/{coverage-QKN57JDS.js → coverage-NNWM7TX3.js} +3 -3
  179. package/dist/cli/chunks/cross-domain-router-ODU5IZD6.js +2 -0
  180. package/dist/cli/chunks/{cursor-installer-GBJ7YXSM.js → cursor-installer-4NCHGJGK.js} +2 -2
  181. package/dist/cli/chunks/{daemon-IAVSO6HK.js → daemon-QIKCXKWO.js} +4 -4
  182. package/dist/cli/chunks/{daemon-GKP7CMEK.js → daemon-T4JO4IXP.js} +3 -3
  183. package/dist/cli/chunks/{dag-attention-scheduler-S225TCI7.js → dag-attention-scheduler-RPAAIDAD.js} +2 -2
  184. package/dist/cli/chunks/{detect-IUYH422U.js → detect-SBEEVDSN.js} +2 -2
  185. package/dist/cli/chunks/{dist-node-2YRE6A7C.js → dist-node-ZHI6NCSU.js} +2 -2
  186. package/dist/cli/chunks/{domain-handler-PL2TZC6H.js → domain-handler-LBC3GJ7Z.js} +2 -2
  187. package/dist/cli/chunks/{domain-plugins-HCGLXKIT.js → domain-plugins-H6IZ5USZ.js} +2 -2
  188. package/dist/cli/chunks/{domain-transfer-KQJRUPXA.js → domain-transfer-JZA5TMW3.js} +2 -2
  189. package/dist/cli/chunks/dream-HE3OX42F.js +2 -0
  190. package/dist/cli/chunks/embed-and-insert-pattern-AHTR7CRU.js +3 -0
  191. package/dist/cli/chunks/{eval-WCK7KNFN.js → eval-DZU2KISM.js} +2 -2
  192. package/dist/cli/chunks/{experience-capture-middleware-2MSQWSAR.js → experience-capture-middleware-5IQCWKSL.js} +4 -4
  193. package/dist/cli/chunks/{fast-paths-VYOSIBKF.js → fast-paths-2KLDUWCY.js} +2 -2
  194. package/dist/cli/chunks/{feature-flags-UJRHFBRX.js → feature-flags-7AC3XDZA.js} +2 -2
  195. package/dist/cli/chunks/{feature-flags-WCFUKHNQ.js → feature-flags-N6UAEZY4.js} +2 -2
  196. package/dist/cli/chunks/{file-discovery-JDGL4ZWS.js → file-discovery-5SDIW4V2.js} +2 -2
  197. package/dist/cli/chunks/{fleet-ROXVMZ2F.js → fleet-ZIQCAZ2Y.js} +3 -3
  198. package/dist/cli/chunks/{gnn-wrapper-NIO4ZCO3.js → gnn-wrapper-DUMBZJEV.js} +2 -2
  199. package/dist/cli/chunks/{heartbeat-handler-PI42WD3C.js → heartbeat-handler-6HVM6ZMR.js} +4 -4
  200. package/dist/cli/chunks/heartbeat-scheduler-QUIFGGLX.js +2 -0
  201. package/dist/cli/chunks/hnsw-adapter-42KB37KP.js +2 -0
  202. package/dist/cli/chunks/hnsw-index-T2PGO77J.js +2 -0
  203. package/dist/cli/chunks/{hnsw-legacy-bridge-YLC7SPK2.js → hnsw-legacy-bridge-5DRL5FLX.js} +2 -2
  204. package/dist/cli/chunks/{hnswlib-node-LG6OS3B7.js → hnswlib-node-GW67GTCL.js} +2 -2
  205. package/dist/cli/chunks/{hooks-WVALP5GX.js → hooks-QHH6FVO4.js} +10 -10
  206. package/dist/cli/chunks/hybrid-backend-FRNWYRKH.js +2 -0
  207. package/dist/cli/chunks/{hypergraph-engine-GJEMW3EG.js → hypergraph-engine-7XDCCVG2.js} +2 -2
  208. package/dist/cli/chunks/{hypergraph-handler-BLF6LXEV.js → hypergraph-handler-QHF7NOU5.js} +3 -3
  209. package/dist/cli/chunks/impact-analyzer-A5QYOYBR.js +2 -0
  210. package/dist/cli/chunks/{init-handler-K25RWRYY.js → init-handler-5UIVOM7K.js} +6 -6
  211. package/dist/cli/chunks/init-wizard-XBU674YH.js +2 -0
  212. package/dist/cli/chunks/kernel-DV5MTNZD.js +2 -0
  213. package/dist/cli/chunks/{kilocode-installer-BXN6WZ7G.js → kilocode-installer-TGGV6K5Q.js} +2 -2
  214. package/dist/cli/chunks/{kiro-installer-PM362DLN.js → kiro-installer-4XYBHZWW.js} +2 -2
  215. package/dist/cli/chunks/knowledge-graph-4ACGVJQK.js +2 -0
  216. package/dist/cli/chunks/{learning-CPERDDRG.js → learning-STE5W6BS.js} +3 -3
  217. package/dist/cli/chunks/{llm-router-GOAV5FPI.js → llm-router-NKF7J3RI.js} +4 -4
  218. package/dist/cli/chunks/llm-router-service-PSMASERT.js +2 -0
  219. package/dist/cli/chunks/{load-2BG6SHAK.js → load-B2T77UJQ.js} +2 -2
  220. package/dist/cli/chunks/load-test-MRUO2VPF.js +2 -0
  221. package/dist/cli/chunks/mcp-JGSFCEMH.js +2 -0
  222. package/dist/cli/chunks/{memory-4NHBYT6S.js → memory-WRFZKG56.js} +6 -6
  223. package/dist/cli/chunks/memory-backend-2MPGI6JW.js +2 -0
  224. package/dist/cli/chunks/memory-handlers-XT4HMITB.js +2 -0
  225. package/dist/cli/chunks/{multi-model-executor-KCWSGCDT.js → multi-model-executor-26Q5BSVG.js} +2 -2
  226. package/dist/cli/chunks/{opencode-installer-ATZLLK74.js → opencode-installer-J36EMQU7.js} +2 -2
  227. package/dist/cli/chunks/{orchestrator-RKB7XJRG.js → orchestrator-D5IFV65I.js} +18 -18
  228. package/dist/cli/chunks/pattern-null-store-TGWUL237.js +2 -0
  229. package/dist/cli/chunks/{pattern-usage-recorder-7VE4XDAI.js → pattern-usage-recorder-BVMTWI3E.js} +2 -2
  230. package/dist/cli/chunks/{pipeline-LQZSNDD2.js → pipeline-OWAHDUAQ.js} +2 -2
  231. package/dist/cli/chunks/platform-ANGBFWBV.js +2 -0
  232. package/dist/cli/chunks/{plugin-EJ6K2MGU.js → plugin-OO7ON2YW.js} +2 -2
  233. package/dist/cli/chunks/{prime-radiant-advanced-wasm-OIHTKJMN.js → prime-radiant-advanced-wasm-HFG3BXWU.js} +2 -2
  234. package/dist/cli/chunks/project-root-LNOYVTYY.js +2 -0
  235. package/dist/cli/chunks/protocol-executor-GEVH5KD6.js +2 -0
  236. package/dist/cli/chunks/{protocol-handler-NRBROAU7.js → protocol-handler-CE3Q6LY4.js} +2 -2
  237. package/dist/cli/chunks/{prove-EJOGEGD3.js → prove-7XPN53PY.js} +2 -2
  238. package/dist/cli/chunks/qe-reasoning-bank-DJ2JL6QB.js +2 -0
  239. package/dist/cli/chunks/{quality-E55UC73D.js → quality-TT23JRFX.js} +2 -2
  240. package/dist/cli/chunks/{quality-gate-OIQATNT3.js → quality-gate-PPPRP255.js} +3 -3
  241. package/dist/cli/chunks/queen-coordinator-F7E3AS26.js +2 -0
  242. package/dist/cli/chunks/real-embeddings-EYNZIFJE.js +2 -0
  243. package/dist/cli/chunks/{ref-validation-OPO6J7OL.js → ref-validation-QQR64ZXD.js} +2 -2
  244. package/dist/cli/chunks/{roocode-installer-ODY5KRWU.js → roocode-installer-UIGS7ZJD.js} +2 -2
  245. package/dist/cli/chunks/router-OZH3QSAU.js +2 -0
  246. package/dist/cli/chunks/routing-feedback-J2E3ADZB.js +2 -0
  247. package/dist/cli/chunks/{routing-handler-KQM6VWLC.js → routing-handler-6AENUIRG.js} +2 -2
  248. package/dist/cli/chunks/{ruvector-commands-U2GVV6PF.js → ruvector-commands-5AWMEV34.js} +2 -2
  249. package/dist/cli/chunks/rvf-dual-writer-HK525Y5Y.js +2 -0
  250. package/dist/cli/chunks/rvf-migration-adapter-Q7FB3BKR.js +2 -0
  251. package/dist/cli/chunks/rvf-migration-coordinator-NWRJ7C22.js +2 -0
  252. package/dist/cli/chunks/rvf-native-adapter-5ZRCGUI6.js +2 -0
  253. package/dist/cli/chunks/{rvf-store-integrity-KMIHD3LP.js → rvf-store-integrity-ISKRP563.js} +2 -2
  254. package/dist/cli/chunks/safe-db-3OYEPVEH.js +2 -0
  255. package/dist/cli/chunks/schedule-AG4C2EIQ.js +2 -0
  256. package/dist/cli/chunks/scheduler-SQS2CZFZ.js +2 -0
  257. package/dist/cli/chunks/{security-P5NM353C.js → security-325A7FMB.js} +3 -3
  258. package/dist/cli/chunks/{shared-rvf-adapter-LVIUOO4S.js → shared-rvf-adapter-NFL6QSZ6.js} +2 -2
  259. package/dist/cli/chunks/{shared-rvf-dual-writer-2CSG7C4W.js → shared-rvf-dual-writer-THFDYS2Z.js} +2 -2
  260. package/dist/cli/chunks/sqlite-persistence-MAKDFSHC.js +2 -0
  261. package/dist/cli/chunks/standalone-memory-UD4MJ6GZ.js +2 -0
  262. package/dist/cli/chunks/{status-handler-6TU6O37R.js → status-handler-CPFTN4XL.js} +2 -2
  263. package/dist/cli/chunks/{structural-health-KBIJSTXJ.js → structural-health-2MG2IVBL.js} +2 -2
  264. package/dist/cli/chunks/{sync-LNHI5SB7.js → sync-EE4VVKOW.js} +2 -2
  265. package/dist/cli/chunks/{sync-UHOX6RJW.js → sync-MBTW5XBF.js} +2 -2
  266. package/dist/cli/chunks/task-handler-7H5OYJG4.js +54 -0
  267. package/dist/cli/chunks/task-handlers-NH4GJHCJ.js +9 -0
  268. package/dist/cli/chunks/{test-DHAAI3DU.js → test-MPHGT4T6.js} +4 -4
  269. package/dist/cli/chunks/{test-scheduling-XDBZ3QC2.js → test-scheduling-CHQ4ZLLJ.js} +3 -3
  270. package/dist/cli/chunks/token-bootstrap-SSDCYEKK.js +2 -0
  271. package/dist/cli/chunks/{token-usage-Q2YG5YQN.js → token-usage-EBXUJNRB.js} +2 -2
  272. package/dist/cli/chunks/{transformers-F5UQTQCY.js → transformers-ZEKS2OJZ.js} +2 -2
  273. package/dist/cli/chunks/{tree-sitter-wasm-parser-DEGOHS6F.js → tree-sitter-wasm-parser-J6ZMAK37.js} +2 -2
  274. package/dist/cli/chunks/{types-JQ7EQO5Q.js → types-KYAA5VLV.js} +2 -2
  275. package/dist/cli/chunks/unified-memory-DDWMC435.js +2 -0
  276. package/dist/cli/chunks/unified-memory-hnsw-4JA7SGBK.js +2 -0
  277. package/dist/cli/chunks/unified-persistence-F6OSNTXY.js +2 -0
  278. package/dist/cli/chunks/{upgrade-TJRVGHGD.js → upgrade-UJBJ5AYM.js} +2 -2
  279. package/dist/cli/chunks/{validate-BWPCVHBN.js → validate-RUV6YMWS.js} +2 -2
  280. package/dist/cli/chunks/{validate-swarm-QVVKCQLP.js → validate-swarm-IVEVMGVM.js} +2 -2
  281. package/dist/cli/chunks/{vibium-ZFATIWHO.js → vibium-HOGMFJ2Z.js} +2 -2
  282. package/dist/cli/chunks/visual-security-25SMBIYT.js +2 -0
  283. package/dist/cli/chunks/{web-tree-sitter-KPLY7ONR.js → web-tree-sitter-AVWA6HKE.js} +2 -2
  284. package/dist/cli/chunks/{windsurf-installer-H7XM7ISA.js → windsurf-installer-DAH7HI2W.js} +2 -2
  285. package/dist/cli/chunks/{witness-chain-RRN6NDCH.js → witness-chain-PJOQPFUX.js} +2 -2
  286. package/dist/cli/chunks/witness-chain-ZW6KKUZU.js +2 -0
  287. package/dist/cli/chunks/{witness-key-manager-DFRL42GE.js → witness-key-manager-JSTBMG43.js} +2 -2
  288. package/dist/cli/chunks/{workflow-2ZQO6WYI.js → workflow-TWOIA6LZ.js} +4 -4
  289. package/dist/cli/chunks/workflow-orchestrator-UKSIDM7Q.js +2 -0
  290. package/dist/cli/chunks/{wrappers-SUS6XEJD.js → wrappers-UR7BLXKV.js} +2 -2
  291. package/dist/cli/commands/mcp.js +6 -0
  292. package/dist/cli/commands/memory.d.ts +1 -1
  293. package/dist/cli/commands/memory.js +8 -8
  294. package/dist/cli/commands/platform.js +15 -2
  295. package/dist/cli/commands/upgrade.d.ts +3 -3
  296. package/dist/cli/commands/upgrade.js +3 -3
  297. package/dist/cli/handlers/init-handler.d.ts +10 -0
  298. package/dist/cli/handlers/task-handler.js +24 -3
  299. package/dist/cli/helpers/standalone-memory.d.ts +12 -0
  300. package/dist/cli/helpers/standalone-memory.js +46 -0
  301. package/dist/cli/index.js +37 -41
  302. package/dist/cli/log-gate.d.ts +66 -0
  303. package/dist/cli/log-gate.js +170 -0
  304. package/dist/init/codex-installer.js +18 -6
  305. package/dist/init/orchestrator.js +1 -0
  306. package/dist/init/phases/09-assets.d.ts +10 -0
  307. package/dist/init/phases/09-assets.js +3 -0
  308. package/dist/init/token-bootstrap.d.ts +1 -1
  309. package/dist/init/token-bootstrap.js +12 -2
  310. package/dist/init/types.d.ts +10 -0
  311. package/dist/integrations/ruvector/brain-exporter.js +17 -0
  312. package/dist/integrations/ruvector/brain-import-audit.d.ts +20 -0
  313. package/dist/integrations/ruvector/brain-import-audit.js +22 -0
  314. package/dist/integrations/ruvector/brain-rvf-exporter.js +16 -0
  315. package/dist/integrations/ruvector/brain-shared.js +1 -1
  316. package/dist/integrations/ruvector/rvf-dual-writer.js +6 -1
  317. package/dist/kernel/hybrid-backend.d.ts +6 -0
  318. package/dist/kernel/hybrid-backend.js +18 -0
  319. package/dist/kernel/kernel.js +9 -14
  320. package/dist/kernel/project-root.d.ts +1 -1
  321. package/dist/kernel/project-root.js +24 -3
  322. package/dist/learning/embedder-identity-store.js +4 -3
  323. package/dist/learning/pattern-store.js +5 -1
  324. package/dist/learning/real-embeddings.d.ts +8 -0
  325. package/dist/learning/real-embeddings.js +16 -0
  326. package/dist/learning/rvf-pattern-store.js +10 -3
  327. package/dist/mcp/bundle.js +442 -442
  328. package/dist/mcp/entry.js +2 -0
  329. package/dist/mcp/handlers/memory-handlers.d.ts +6 -1
  330. package/dist/mcp/handlers/memory-handlers.js +44 -22
  331. package/dist/mcp/handlers/task-handlers.js +14 -1
  332. package/dist/mcp/protocol-server.js +1 -0
  333. package/dist/mcp/services/session-store.js +5 -1
  334. package/dist/plugins/cache.d.ts +2 -0
  335. package/dist/plugins/cache.js +15 -2
  336. package/dist/plugins/lifecycle.js +15 -2
  337. package/dist/plugins/manifest.js +7 -5
  338. package/dist/plugins/resolver.d.ts +13 -22
  339. package/dist/plugins/resolver.js +169 -61
  340. package/dist/plugins/version-policy.d.ts +13 -0
  341. package/dist/plugins/version-policy.js +18 -0
  342. package/dist/shared/types/index.d.ts +6 -0
  343. package/dist/shared/types/index.js +8 -0
  344. package/package.json +2 -1
  345. package/dist/cli/chunks/adapter-TNNNJRDG.js +0 -2
  346. package/dist/cli/chunks/aqe-learning-engine-5ZRMYJLB.js +0 -2
  347. package/dist/cli/chunks/base-KWZHOPSH.js +0 -2
  348. package/dist/cli/chunks/brain-handler-ET6YAP4B.js +0 -90
  349. package/dist/cli/chunks/browser-workflow-2FZTKDUL.js +0 -2
  350. package/dist/cli/chunks/chunk-33YYYWBQ.js +0 -4
  351. package/dist/cli/chunks/chunk-5Z6XZV7K.js +0 -65
  352. package/dist/cli/chunks/chunk-6J62K3SW.js +0 -2
  353. package/dist/cli/chunks/chunk-6TPKK7LD.js +0 -15
  354. package/dist/cli/chunks/chunk-DEYLEDJN.js +0 -27
  355. package/dist/cli/chunks/chunk-KGT36Z42.js +0 -14
  356. package/dist/cli/chunks/chunk-NA7B2QYB.js +0 -2
  357. package/dist/cli/chunks/chunk-NDPFGIMJ.js +0 -13
  358. package/dist/cli/chunks/chunk-PEPFCPES.js +0 -2
  359. package/dist/cli/chunks/chunk-TT23RRB7.js +0 -2
  360. package/dist/cli/chunks/chunk-XWMZ6D6N.js +0 -2
  361. package/dist/cli/chunks/client-7E4LM2WW.js +0 -2
  362. package/dist/cli/chunks/codex-installer-CQ24DTP5.js +0 -14
  363. package/dist/cli/chunks/core-handlers-IFG3757P.js +0 -2
  364. package/dist/cli/chunks/cross-domain-router-EK7W4PGP.js +0 -2
  365. package/dist/cli/chunks/dream-NFSCSLY7.js +0 -2
  366. package/dist/cli/chunks/embed-and-insert-pattern-ZPAG7235.js +0 -3
  367. package/dist/cli/chunks/heartbeat-scheduler-ZATCDJDK.js +0 -2
  368. package/dist/cli/chunks/hnsw-adapter-WXQABRCA.js +0 -2
  369. package/dist/cli/chunks/hnsw-index-TPSWLEA5.js +0 -2
  370. package/dist/cli/chunks/impact-analyzer-HNIU45P5.js +0 -2
  371. package/dist/cli/chunks/init-wizard-JUIPBMHG.js +0 -2
  372. package/dist/cli/chunks/kernel-5BOZQ754.js +0 -2
  373. package/dist/cli/chunks/knowledge-graph-EWDAENWM.js +0 -2
  374. package/dist/cli/chunks/llm-router-service-3YT7JGBS.js +0 -2
  375. package/dist/cli/chunks/load-test-BP2CPLIV.js +0 -2
  376. package/dist/cli/chunks/mcp-5TTB37DC.js +0 -2
  377. package/dist/cli/chunks/memory-backend-4PYQBPRM.js +0 -2
  378. package/dist/cli/chunks/memory-handlers-2B27NITS.js +0 -2
  379. package/dist/cli/chunks/pattern-null-store-OYOQOV2O.js +0 -2
  380. package/dist/cli/chunks/platform-OD5H5U6G.js +0 -2
  381. package/dist/cli/chunks/protocol-executor-3ATJTXWG.js +0 -2
  382. package/dist/cli/chunks/qe-reasoning-bank-LLMYZT4X.js +0 -2
  383. package/dist/cli/chunks/queen-coordinator-RN7L6KG5.js +0 -2
  384. package/dist/cli/chunks/real-embeddings-FPFFNOSZ.js +0 -2
  385. package/dist/cli/chunks/router-MDHITQ2V.js +0 -2
  386. package/dist/cli/chunks/routing-feedback-5XLNJ3Y3.js +0 -2
  387. package/dist/cli/chunks/rvf-dual-writer-JBW4O3II.js +0 -2
  388. package/dist/cli/chunks/rvf-migration-adapter-BPPQL4XJ.js +0 -2
  389. package/dist/cli/chunks/rvf-migration-coordinator-V2GHCJKN.js +0 -2
  390. package/dist/cli/chunks/rvf-native-adapter-S4562CG5.js +0 -2
  391. package/dist/cli/chunks/safe-db-FIRHSXVF.js +0 -2
  392. package/dist/cli/chunks/schedule-RVXFB4HK.js +0 -2
  393. package/dist/cli/chunks/scheduler-IKKAMAOO.js +0 -2
  394. package/dist/cli/chunks/sqlite-persistence-SQ3HCUQ7.js +0 -2
  395. package/dist/cli/chunks/task-handler-AVDHMLGI.js +0 -49
  396. package/dist/cli/chunks/task-handlers-KYK4VTRA.js +0 -9
  397. package/dist/cli/chunks/token-bootstrap-GUTTLPZX.js +0 -2
  398. package/dist/cli/chunks/unified-memory-CXHLHB5I.js +0 -2
  399. package/dist/cli/chunks/unified-memory-hnsw-I7WAE54M.js +0 -2
  400. package/dist/cli/chunks/unified-persistence-6CPF65WI.js +0 -2
  401. package/dist/cli/chunks/visual-security-GNPHME5H.js +0 -2
  402. package/dist/cli/chunks/witness-chain-VT4UHHBR.js +0 -2
  403. package/dist/cli/chunks/workflow-orchestrator-DB3HIECD.js +0 -2
@@ -0,0 +1,94 @@
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.14.5");process.exit(0)}
2
+ import{a as L,b as z,c as K,d as _,e as ie,f as W,g as G,h as A,i as Ce,j as se,k as Q,l as xe,m as J,n as le,o as Ie,p as P,q as Y,r as X,s as Z,t as ee}from"./chunk-RIZVC4XY.js";import{a as we,b as Re,c as H,d as V,f as tn}from"./chunk-SX4JLSLV.js";import{a as Se,d as ae,e as _e,h as Ee}from"./chunk-7X7JYWT4.js";import{b as ve}from"./chunk-RD6TEZ64.js";import"./chunk-EFV4ADMO.js";import"./chunk-RKOUXVZZ.js";import{b as k,d as oe}from"./chunk-IJHCIXJC.js";import"./chunk-NQI7FWCS.js";import"./chunk-C3HQL6S4.js";import"./chunk-J27F4NSB.js";import"./chunk-7CD7PBHY.js";import"./chunk-J5UNP6W3.js";import{a as F,b as nn}from"./chunk-HVU64GP5.js";import"./chunk-ELBZON4V.js";import"./chunk-52L77RMG.js";import"./chunk-XZSMZHM2.js";import"./chunk-CVMNJSCB.js";import"./chunk-NU7UTXMP.js";import"./chunk-D6OUCB2H.js";import"./chunk-6A44AOGN.js";import"./chunk-WJHWH5D2.js";import"./chunk-JSZ663MU.js";import $ from"path";import o from"chalk";nn();oe();import{existsSync as te,mkdirSync as rn,writeFileSync as on,readFileSync as ce}from"fs";import{join as D,resolve as de}from"path";function ne(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?ae(r,_e(a)):Se;e.prepare(`
3
+ INSERT INTO witness_chain
4
+ (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo)
5
+ VALUES (?, ?, 'BRAIN_IMPORT', ?, ?, 'brain-import', ?)
6
+ `).run(i,ae(r,t),t,new Date().toISOString(),r)}var an={rl_q_values:"includeQValues",dream_insights:"includeDreamInsights",dream_cycles:"includeDreamInsights",witness_chain:"includeWitnessChain",vectors:"includeVectors"};function sn(e,n){let r=an[e.tableName];return!(r&&n[r]===!1)}var ln=1e4;function cn(e,n,r,t){if(!sn(n,r))return le(D(t,n.fileName),[]),{count:0,rows:[]};let[a,i]=n.domainColumn?J(r.domains,n.domainColumn):[void 0,[]];if(r.domains&&r.domains.length>0&&!n.domainColumn){let s=r.domains.map(()=>"?").join(","),d=`manifest_id IN (SELECT id FROM learning_evidence_manifests WHERE task_family IN (${s}))`;["learning_evidence_segments","learning_segment_edges","learning_evidence_admissions"].includes(n.tableName)?(a=d,i=[...r.domains]):["pattern_manifest_lineage","pattern_segment_lineage"].includes(n.tableName)&&(a=`${d} AND pattern_id IN (SELECT id FROM qe_patterns WHERE qe_domain IN (${s}))`,i=[...r.domains,...r.domains])}if(se(e,n.tableName,a,i)>=ln){let s=n.blobColumns,d=s&&s.length>0?y=>W(y,s):void 0;return{count:Ie(D(t,n.fileName),xe(e,n.tableName,a,i),d)}}let l=Q(e,n.tableName,a,i);return n.blobColumns&&n.blobColumns.length>0&&(l=l.map(s=>W(s,n.blobColumns))),le(D(t,n.fileName),l),{count:l.length,rows:l}}function Be(e){let n=[];for(let r of _){let t=D(e,r.fileName);te(t)?n.push(A(ce(t,"utf-8"))):n.push(A(""))}return A(n.join(":"))}function Oe(e,n,r="memory.db"){let t=de(n.outputPath);te(t)||rn(t,{recursive:!0});let a=0,i={},c=new Set;for(let f of _){let y=cn(e,f,n,t);if(i[f.tableName]=y.count,a+=y.count,f.tableName==="qe_patterns"){if(y.rows)for(let h of y.rows)h.qe_domain&&c.add(h.qe_domain);else if(y.count>0){let[h,E]=f.domainColumn?J(n.domains,f.domainColumn):[void 0,[]],u=`SELECT DISTINCT qe_domain FROM qe_patterns ${h?`WHERE ${h} AND qe_domain IS NOT NULL`:"WHERE qe_domain IS NOT NULL"}`;try{let R=e.prepare(u).all(...E||[]);for(let g of R)c.add(g.qe_domain)}catch{}}}}let l=n.includeVectors!==!1?se(e,"vectors"):0,s=Be(t),d={version:"3.0",exportedAt:new Date().toISOString(),sourceDb:r,stats:{patternCount:i.qe_patterns||0,vectorCount:l,qValueCount:i.rl_q_values||0,dreamInsightCount:i.dream_insights||0,witnessChainLength:i.witness_chain||0,totalRecords:a},domains:[...c].sort(),checksum:s,tableRecordCounts:i};return on(D(t,"manifest.json"),JSON.stringify(d,null,2),"utf-8"),d}var dn=new Set(["qe_patterns","rl_q_values","dream_insights","witness_chain"]);function fn(e){return e==="1.0"?_.filter(n=>dn.has(n.tableName)):e==="3.0"?_:(console.warn(`[brain-import] Unknown manifest version '${e}'. Attempting full import \u2014 some files may be missing.`),_)}function Ae(e,n,r){let t=de(n),a=D(t,"manifest.json");if(!te(a))throw new Error(`Manifest not found at ${a}`);let i=k(ce(a,"utf-8")),c=Be(t);if(c!==i.checksum)throw new Error(`Checksum mismatch: expected ${i.checksum}, got ${c}. The export may have been tampered with or corrupted.`);let l=fn(i.version),s=0,d=0,f=0,y=()=>{let h=new Map,E=new Map,m=0;for(let u of l){let R=D(t,u.fileName),g=P(R,k);if(u.tableName==="witness_chain"){m+=g.length,d+=g.length;continue}u.blobColumns&&u.blobColumns.length>0&&(g=g.map(b=>G(b,u.blobColumns)));for(let b of g){let O=Y(b,h),x;if(u.dedupColumns&&u.dedupColumns.length>0)x=Z(e,u.tableName,O,u.dedupColumns,u.preserveId);else{let N=L[u.tableName]||"id",I=K[u.tableName],p=z[u.tableName];x=X(e,u.tableName,O,N,r.mergeStrategy,I,p,h,E,b.pattern_id)}s+=x.imported,d+=x.skipped,f+=x.conflicts}}ne(e,{sourceChecksum:i.checksum,sourceWitnessRows:m,importedRecords:s,skippedRecords:d,conflicts:f}),s+=1};return ee(e,r.dryRun??!1,y),{imported:s,skipped:d,conflicts:f}}function Ne(e){let n=de(e),r=D(n,"manifest.json");if(!te(r))throw new Error(`Manifest not found at ${r}`);return k(ce(r,"utf-8"))}tn();import{existsSync as j,readdirSync as mn,renameSync as un,statSync as pn,unlinkSync as fe,writeFileSync as gn}from"fs";import{basename as yn,dirname as hn,join as bn,resolve as re}from"path";var De=["",".idmap.json",".manifest.json"],wn=[...De,".lock"];function ke(e){for(let n of wn)try{let r=`${e}${n}`;j(r)&&fe(r)}catch{}}function Rn(e){let n=hn(e),r=`${yn(e)}.tmp.`,t;try{t=mn(n)}catch{return}for(let a of t){if(!a.startsWith(r))continue;let i=Number.parseInt(a.slice(r.length).split(".")[0],10);if(!(!Number.isInteger(i)||i<=0)&&!(i!==process.pid&&vn(i)))try{fe(bn(n,a))}catch{}}}function vn(e){try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function $e(e,n,r="memory.db"){if(!V())throw new Error("@ruvector/rvf-node is not available. Install it or use --format jsonl instead.");let t=re(n.outputPath),a=n.dimension??384,i=`${t}.tmp.${process.pid}`;Rn(t),ke(i);let c=we(i,a),l=!1;try{let s={},d=new Set,f=0;for(let p of _){let[S,w]=p.domainColumn?J(n.domains,p.domainColumn):[void 0,[]],C=Q(e,p.tableName,S,w);if(n.domains&&n.domains.length>0){let v=new Set((s.learning_evidence_manifests??[]).map(B=>B.id)),q=new Set((s.qe_patterns??[]).map(B=>B.id));["learning_evidence_segments","learning_segment_edges","learning_evidence_admissions"].includes(p.tableName)?C=C.filter(B=>v.has(B.manifest_id)):p.tableName==="pattern_manifest_lineage"?C=C.filter(B=>{let T=B;return v.has(T.manifest_id)&&q.has(T.pattern_id)}):p.tableName==="pattern_segment_lineage"&&(C=C.filter(B=>{let T=B;return v.has(T.manifest_id)&&q.has(T.pattern_id)}))}if(p.tableName==="qe_patterns")for(let v of C)v.qe_domain&&d.add(v.qe_domain);let M=ie[p.tableName];M&&M.length>0&&(C=C.map(v=>W(v,M))),s[p.tableName]=C,f+=C.length}let y=0,h=[];if(Ce(e,"qe_pattern_embeddings")){let p=e.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(w=>w.name==="space_id"),S=e.prepare(`SELECT pattern_id, embedding, dimension, ${p?"space_id":"NULL"} AS space_id
7
+ FROM qe_pattern_embeddings`).all();for(let w of S)w.embedding&&w.dimension===a&&w.space_id&&h.push({id:`pe:${w.pattern_id}`,vector:new Float32Array(w.embedding.buffer,w.embedding.byteOffset,a),metadata:{tableName:"qe_pattern_embeddings",spaceId:w.space_id}})}h.length>0&&(y=c.ingest(h).accepted);let E={version:"3.0",format:"rvf",exportedAt:new Date().toISOString(),sourceDb:r,domains:[...d].sort(),tables:s},m=JSON.stringify(E),u=A(m),R=Buffer.from(m);c.embedKernel(R);let g=n.sign?c.sign(R)??void 0:void 0,b=g?n.signerKeyId??"default":void 0,O=c.fileId(),x=O?{fileId:O,parentId:c.parentId(),lineageDepth:c.lineageDepth()}:void 0,N=c.status(),I={version:"3.0",format:"rvf",exportedAt:E.exportedAt,sourceDb:r,stats:{patternCount:(s.qe_patterns||[]).length,embeddingCount:y,qValueCount:(s.rl_q_values||[]).length,dreamInsightCount:(s.dream_insights||[]).length,witnessChainLength:(s.witness_chain||[]).length,totalRecords:f,tableCounts:Object.fromEntries(_.map(({tableName:p})=>[p,s[p]?.length??0]))},domains:E.domains,checksum:u,rvfStatus:{totalVectors:N.totalVectors,totalSegments:N.totalSegments,fileSizeBytes:N.fileSizeBytes},...g?{signature:g,signerKeyId:b}:{},...x?{lineage:x}:{}};if(g)try{c.freeze()}catch{}if(gn(`${i}.manifest.json`,JSON.stringify(I,null,2),"utf-8"),c.close(),l=!0,j(t)&&!n.allowOverwriteRicher){let p;try{p=U(t)}catch(S){if(Sn(t)||!_n(S)){let w=S instanceof Error?S.message:String(S);throw new Error(`RVF_MIRROR_INSPECTION_AMBIGUOUS: the existing mirror is readable but its richness could not be established (${w}). Preserve/import it before retrying, or repeat with --force-overwrite-richer after preserving a backup.`)}}if(p){let S=p.stats.tableCounts,w=I.stats.tableCounts,C=_.map(({tableName:v})=>v).filter(v=>!S||!Number.isSafeInteger(S[v]));if(C.length>0)throw new Error(`RVF_MIRROR_INSPECTION_AMBIGUOUS: existing mirror lacks trustworthy counts for ${C.join(", ")}. Preserve/import it before retrying, or repeat with --force-overwrite-richer after preserving a backup.`);let M=_.map(({tableName:v})=>({tableName:v,existing:S[v],candidate:w[v]})).filter(({existing:v,candidate:q})=>v>q);if(M.length>0){let v=M.map(({tableName:q,existing:B,candidate:T})=>`${q} ${B} -> ${T}`).join(", ");throw new Error(`RVF_MIRROR_RICHER: refusing to replace richer mirrored tables: ${v}. Restore/import the mirror first, or repeat with --force-overwrite-richer after preserving a backup.`)}}}for(let p of[...De].reverse()){let S=`${i}${p}`,w=`${t}${p}`;j(S)?un(S,w):j(w)&&fe(w)}return I}catch(s){if(!l)try{c.close()}catch{}throw ke(i),s}}function Sn(e){let n;try{return n=H(re(e)),!!n.extractKernel()?.image}catch{return!1}finally{try{n?.close()}catch{}}}function _n(e){let n=e instanceof Error?e.message:String(e);return/ManifestNotFound|InvalidMagic|ChecksumMismatch|CorruptStore/i.test(n)}var En={patterns:"qe_patterns",qValues:"rl_q_values",dreamInsights:"dream_insights",witnessChain:"witness_chain"};function Te(e,n,r){if(!V())throw new Error("@ruvector/rvf-node is not available. Install it or use JSONL format.");let t=re(n);if(!j(t))throw new Error(`RVF file not found: ${t}`);let a=r.dryRun?H(t):Re(t);try{let i=a.verifyWitness();if(!i.valid&&(i.totalEntries>0||i.errors.length>0)){let m=i.errors.length>0?i.errors.join("; "):"unknown integrity error";throw new Error(`RVF witness verification failed: ${m}`)}let c=a.extractKernel();if(!c||!c.image)throw new Error("No brain data found in RVF file (missing kernel segment)");let l;try{l=JSON.parse(c.image.toString("utf-8"))}catch(m){throw new Error(`Failed to parse brain kernel data as JSON: ${m instanceof Error?m.message:m}`)}let s=0,d=0,f=0,y=0,h={};if(l.tables)Object.assign(h,l.tables);else for(let[m,u]of Object.entries(En)){let R=l[m];Array.isArray(R)&&(h[u]=R)}let E=()=>{let m=new Map,u=new Map,R=0;for(let g of _){let b=h[g.tableName];if(!b||!Array.isArray(b))continue;if(g.tableName==="witness_chain"){R+=b.length,d+=b.length;continue}let O=ie[g.tableName];O&&O.length>0&&(b=b.map(x=>G(x,O)));for(let x of b){let N=Y(x,m),I;if(g.dedupColumns&&g.dedupColumns.length>0)I=Z(e,g.tableName,N,g.dedupColumns,g.preserveId);else{let p=L[g.tableName]||"id",S=K[g.tableName],w=z[g.tableName];I=X(e,g.tableName,N,p,r.mergeStrategy,S,w,m,u,x.pattern_id)}if(I.imported)for(let p of O??[])N[p]instanceof Buffer&&y++;s+=I.imported,d+=I.skipped,f+=I.conflicts}}ne(e,{sourceChecksum:A(c.image.toString("utf-8")),sourceWitnessRows:R,importedRecords:s,skippedRecords:d,conflicts:f}),s+=1};if(ee(e,r.dryRun??!1,E),!r.dryRun&&f>0)try{a.compact()}catch{}return{imported:s,skipped:d,conflicts:f,embeddingsRestored:y}}finally{a.close()}}function U(e){if(!V())throw new Error("@ruvector/rvf-node is not available.");let n=re(e);if(!j(n))throw new Error(`RVF file not found: ${n}`);let r=H(n);try{let t=r.extractKernel();if(!t||!t.image)throw new Error("No brain data found in RVF file");let a=t.image.toString("utf-8"),i;try{i=JSON.parse(a)}catch(m){throw new Error(`Failed to parse brain kernel data as JSON: ${m instanceof Error?m.message:m}`)}let c=r.status(),l=pn(n).size,s=i.tables,d=s?s.qe_patterns?.length??0:i.patterns?.length??0,f=s?s.rl_q_values?.length??0:i.qValues?.length??0,y=s?s.dream_insights?.length??0:i.dreamInsights?.length??0,h=s?s.witness_chain?.length??0:i.witnessChain?.length??0,E=s&&typeof s=="object"&&!Array.isArray(s)?Object.fromEntries(Object.entries(s).filter(m=>Array.isArray(m[1])).map(([m,u])=>[m,u.length])):void 0;return{version:"3.0",format:"rvf",exportedAt:i.exportedAt??"unknown",sourceDb:i.sourceDb??"unknown",stats:{patternCount:d,embeddingCount:c.totalVectors,qValueCount:f,dreamInsightCount:y,witnessChainLength:h,...E?{tableCounts:E}:{}},domains:i.domains??[],checksum:A(a),rvfStatus:{totalVectors:c.totalVectors,totalSegments:c.totalSegments,fileSizeBytes:l}}}finally{r.close()}}function me(){return V()}oe();import{existsSync as pe,readFileSync as Cn,statSync as xn}from"fs";import{join as ue,resolve as Me}from"path";function Pe(e,n,r={}){let t=Me(e),a=Me(n),i=qe(t),c=qe(a),l=Fe(t,i),s=Fe(a,c),d=i==="jsonl"&&c==="jsonl",f=On({pathA:t,pathB:a,manifestA:l,manifestB:s,recordLevel:d,tableFilter:r.tableFilter,maxIdsPerBucket:r.maxIdsPerBucket??500}),y=new Set(l.domains),h=new Set(s.domains),E=l.domains.filter(b=>!h.has(b)),m=s.domains.filter(b=>!y.has(b)),u=l.checksum===s.checksum,R=l.version===s.version,g=u&&R&&f.every(b=>b.delta===0&&(b.added?.length??0)===0&&(b.removed?.length??0)===0&&(b.changed?.length??0)===0);return{pathA:t,pathB:a,formatA:i,formatB:c,manifestA:l,manifestB:s,checksumMatch:u,versionMatch:R,identical:g,recordLevel:d,tableDiffs:f,domainsOnlyInA:E,domainsOnlyInB:m}}function qe(e){if(!pe(e))throw new Error(`Path not found: ${e}`);if(e.endsWith(".rvf"))return"rvf";if(xn(e).isFile())throw new Error(`Unsupported brain export: ${e} (expected a .rvf file or a JSONL directory)`);return"jsonl"}function Fe(e,n){return n==="rvf"?Bn(e):In(e)}function In(e){let n=ue(e,"manifest.json");if(!pe(n))throw new Error(`Manifest not found at ${n}`);let r=k(Cn(n,"utf-8"));return je(r,"jsonl")}function Bn(e){let n=U(e);return je(n,"rvf")}function je(e,n){return{format:n,version:e.version??"unknown",exportedAt:e.exportedAt??"unknown",sourceDb:e.sourceDb??"unknown",checksum:e.checksum??"",totalRecords:e.stats?.totalRecords??0,domains:e.domains??[],tableRecordCounts:e.tableRecordCounts??{}}}function On(e){let n=e.tableFilter?_.filter(t=>t.tableName===e.tableFilter):_;if(e.tableFilter&&n.length===0)throw new Error(`Unknown table: ${e.tableFilter}`);let r=[];for(let t of n){let a=e.manifestA.tableRecordCounts[t.tableName]??0,i=e.manifestB.tableRecordCounts[t.tableName]??0,c=i-a,l,s,d;if(e.recordLevel&&An(t)){let f=Nn(ue(e.pathA,t.fileName),ue(e.pathB,t.fileName),t,e.maxIdsPerBucket);l=f.added,s=f.removed,d=f.changed}r.push({tableName:t.tableName,countA:a,countB:i,delta:c,...l!==void 0?{added:l}:{},...s!==void 0?{removed:s}:{},...d!==void 0?{changed:d}:{}})}return r}function An(e){return!0}function Nn(e,n,r,t){let a=Le(e,r),i=Le(n,r),c=[],l=[],s=[];for(let[d,f]of a){let y=i.get(d);if(y===void 0)l.length<t&&l.push(d);else if(y!==f){if(r.dedupColumns&&r.dedupColumns.length>0)continue;s.length<t&&s.push(d)}}for(let d of i.keys())a.has(d)||c.length<t&&c.push(d);return c.sort(),l.sort(),s.sort(),{added:c,removed:l,changed:s}}function Le(e,n){let r=new Map;if(!pe(e))return r;let t=P(e,k);for(let a of t){let i=kn(a,n);if(i===void 0)continue;let c=Dn(a);r.set(i,$n(c))}return r}function kn(e,n){if(n.dedupColumns&&n.dedupColumns.length>0){let a=[];for(let i of n.dedupColumns){let c=e[i];if(c==null)return;a.push(String(c))}return a.join("")}let r=L[n.tableName]??"id",t=e[r];if(t!=null)return String(t)}function Dn(e){let n=Object.keys(e).sort(),r={};for(let t of n)r[t]=e[t];return JSON.stringify(r)}function $n(e){return A(e)}oe();import{existsSync as ge,statSync as Tn}from"fs";import{join as Ve,resolve as Mn}from"path";var qn=20,Fn="qe_patterns";function We(e,n={}){let r=Mn(e);jn(r);let t=n.table??Fn,a=_.find(R=>R.tableName===t);if(!a)throw new Error(`Unknown table: ${t}`);let i=Ve(r,a.fileName);if(!ge(i))throw new Error(`Table file not found: ${a.fileName} (expected in ${r}). Was this export generated with --format jsonl?`);let c=P(i,k),l=a.domainColumn,s=Math.max(1,n.limit??qn),d=n.query?n.query.toLowerCase():void 0,f=n.domains&&n.domains.length>0?new Set(n.domains):void 0,y=n.since,h=n.until,E=n.patternType,m=0,u=[];for(let R of c)Ln(R,{domainColumn:l,domains:f,patternType:E,since:y,until:h,queryLower:d})&&(m++,u.length<s&&u.push(Pn(R,a.tableName,l)));return{table:t,inputPath:r,totalScanned:c.length,totalMatched:m,limit:s,hits:u,truncated:m>s}}function Ln(e,n){if(n.domains){if(!n.domainColumn)return!1;let r=e[n.domainColumn];if(typeof r!="string"||!n.domains.has(r))return!1}if(n.patternType!==void 0&&e.pattern_type!==n.patternType)return!1;if(n.since!==void 0||n.until!==void 0){let r=Je(e);if(r===void 0||n.since!==void 0&&r<n.since||n.until!==void 0&&r>n.until)return!1}if(n.queryLower!==void 0){let r=typeof e.name=="string"?e.name.toLowerCase():"",t=typeof e.description=="string"?e.description.toLowerCase():"";if(!r.includes(n.queryLower)&&!t.includes(n.queryLower))return!1}return!0}function Je(e){for(let n of["updated_at","created_at","timestamp"]){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function Pn(e,n,r){let t=(typeof e.id=="string"||typeof e.id=="number"?String(e.id):void 0)??`${n}:?`,a={name:typeof e.name=="string"?e.name:void 0,description:typeof e.description=="string"?e.description:void 0,domain:r&&typeof e[r]=="string"?e[r]:void 0,patternType:typeof e.pattern_type=="string"?e.pattern_type:void 0,confidence:typeof e.confidence=="number"?e.confidence:void 0,updatedAt:Je(e)};return{id:t,display:a,row:e}}function jn(e){if(!ge(e))throw new Error(`Path not found: ${e}`);if(Tn(e).isFile())throw e.endsWith(".rvf")?new Error("Brain search does not support RVF exports. Re-export with --format jsonl, or use `aqe brain info` for RVF summaries."):new Error(`Unsupported brain export: ${e} (expected a JSONL directory)`);let r=Ve(e,"manifest.json");if(!ge(r))throw new Error(`Manifest not found at ${r}. Is this a brain export directory?`)}function Ue(e,n){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return{created:0,skipped:0};e.exec(`
8
+ CREATE TEMP TABLE IF NOT EXISTS _covered_patterns (
9
+ pattern_id TEXT PRIMARY KEY
10
+ )
11
+ `),e.exec("DELETE FROM _covered_patterns"),e.exec(`
12
+ INSERT INTO _covered_patterns (pattern_id)
13
+ SELECT DISTINCT json_extract(action_data, '$.patternId')
14
+ FROM witness_chain
15
+ WHERE action_type = 'PATTERN_CREATE'
16
+ AND json_extract(action_data, '$.patternId') IS NOT NULL
17
+ `),e.exec(`
18
+ INSERT OR IGNORE INTO _covered_patterns (pattern_id)
19
+ SELECT DISTINCT json_extract(action_data, '$.pattern_id')
20
+ FROM witness_chain
21
+ WHERE action_type = 'PATTERN_CREATE'
22
+ AND json_extract(action_data, '$.pattern_id') IS NOT NULL
23
+ `);let t=e.prepare(`SELECT p.id, p.pattern_type, p.qe_domain, p.name, p.created_at
24
+ FROM qe_patterns p
25
+ LEFT JOIN _covered_patterns c ON p.id = c.pattern_id
26
+ WHERE c.pattern_id IS NULL
27
+ ORDER BY p.created_at ASC`).all(),i=e.prepare("SELECT COUNT(*) as count FROM qe_patterns").get().count-t.length,c=0;for(let l of t)n.append("PATTERN_CREATE",{patternId:l.id,patternType:l.pattern_type,qeDomain:l.qe_domain,name:l.name,originalCreatedAt:l.created_at,backfilled:!0},"system:backfill"),c++;return e.exec("DROP TABLE IF EXISTS _covered_patterns"),{created:c,skipped:i}}async function He(e,n){if(Vn(n.format)==="rvf"){let a=F(e,{readonly:!0});try{return $e(a,{outputPath:n.outputPath,domains:n.domains,allowOverwriteRicher:n.allowOverwriteRicher},e)}finally{a.close()}}let t=F(e,{readonly:!0});try{return Oe(t,n,e)}finally{t.close()}}async function ze(e,n,r){if(Xe(n,r.format)==="rvf"){let i=F(e);try{return Te(i,n,{mergeStrategy:r.mergeStrategy,dryRun:r.dryRun})}finally{i.close()}}let a=F(e);try{return Ae(a,n,r)}finally{a.close()}}async function Ke(e,n){return Xe(e,n)==="rvf"?U(e):Ne(e)}async function Ge(e,n,r={}){return Pe(e,n,r)}async function Qe(e,n={}){return We(e,n)}async function Ye(e){let n=F(e);try{let r=Ee(n,ve());return await r.initialize(),Ue(n,r)}finally{n.close()}}function Vn(e){if(e==="jsonl")return"jsonl";if(e==="rvf"){if(!me())throw new Error("RVF format requested but @ruvector/rvf-node is not available on this platform. Use --format jsonl instead.");return"rvf"}return me()?"rvf":"jsonl"}function Xe(e,n){return n==="rvf"?"rvf":n==="jsonl"?"jsonl":e.endsWith(".rvf")?"rvf":"jsonl"}var be=class{name="brain";description="Export, import, and inspect QE brain state";cleanupAndExit;ensureInitialized;constructor(n,r){this.cleanupAndExit=n,this.ensureInitialized=r}register(n,r){let t=n.command("brain").description(this.description);t.command("export").description("Export brain state to a portable directory").requiredOption("-o, --output <path>","Output directory path").option("--format <format>","Export format: rvf (default) or jsonl","rvf").option("--db <path>","Source database path").option("--force-overwrite-richer","Allow replacing an existing RVF with fewer patterns",!1).action(async a=>{await this.executeExport(a)}),t.command("import").description("Import brain state from an export directory").requiredOption("-i, --input <path>","Path to brain export directory").option("--strategy <strategy>","Merge strategy","skip-conflicts").option("--dry-run","Preview import without writing",!1).option("--db <path>","Target database path").action(async a=>{await this.executeImport(a)}),t.command("info").description("Show manifest info for a brain export").requiredOption("-i, --input <path>","Path to brain export directory").action(async a=>{await this.executeInfo(a)}),t.command("witness-backfill").description("Create witness chain entries for patterns that predate the witness chain").option("--db <path>","Database path").action(async a=>{await this.executeWitnessBackfill(a)}),t.command("diff").description("Compare two brain exports (JSONL directory or .rvf file)").argument("<a>","Path to first brain export").argument("<b>","Path to second brain export").option("--table <name>","Restrict comparison to a single table").option("--verbose","Show the IDs of added/removed/changed records",!1).option("--json","Emit the diff as JSON to stdout",!1).action(async(a,i,c)=>{await this.executeDiff(a,i,c)}),t.command("search").description("Search a JSONL brain export with filters").requiredOption("-i, --input <path>","Path to brain export directory (JSONL)").option("--table <name>","Table to search (default: qe_patterns)").option("--domain <name...>","Restrict to one or more domains").option("--pattern-type <type>","Restrict to a specific pattern_type (qe_patterns only)").option("--since <iso>","Include rows with timestamp \u2265 <iso>").option("--until <iso>","Include rows with timestamp \u2264 <iso>").option("-q, --query <text>","Substring match across name + description (case-insensitive)").option("-l, --limit <n>","Maximum results to return","20").option("--json","Emit results as JSON to stdout",!1).action(async a=>{await this.executeSearch(a)})}async executeExport(n){try{console.log(o.blue(`
28
+ Exporting brain state (format: ${n.format})...
29
+ `));let r=await ye(n.db),t=await He(r,{outputPath:$.resolve(n.output),format:n.format,allowOverwriteRicher:n.forceOverwriteRicher});if(console.log(o.green(" Export complete.")),console.log(` Format: ${o.cyan("format"in t?t.format??"jsonl":"jsonl")}`),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"embeddingCount"in t.stats?console.log(` Vectors: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`),"rvfStatus"in t){let a=t.rvfStatus;console.log(` RVF Size: ${o.cyan(Ze(a.fileSizeBytes))}`),console.log(` Segments: ${o.cyan(a.totalSegments)}`)}console.log(` Checksum: ${o.gray(t.checksum)}`),console.log(` Output: ${o.cyan($.resolve(n.output))}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
30
+ Brain export failed:`),r),await this.cleanupAndExit(1)}}async executeImport(n){try{n.dryRun?console.log(o.yellow(`
31
+ Dry-run mode \u2014 no data will be written.
32
+ `)):console.log(o.blue(`
33
+ Importing brain state...
34
+ `));let r=await ye(n.db),t=await ze(r,$.resolve(n.input),{mergeStrategy:n.strategy,dryRun:n.dryRun});console.log(o.green(" Import complete.")),console.log(` Imported: ${o.cyan(t.imported)}`),console.log(` Skipped: ${o.yellow(t.skipped)}`),console.log(` Conflicts: ${o.red(t.conflicts)}`),"embeddingsRestored"in t&&console.log(` Embeddings: ${o.cyan(t.embeddingsRestored)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
35
+ Brain import failed:`),r),await this.cleanupAndExit(1)}}async executeInfo(n){try{console.log(o.blue(`
36
+ Brain Export Info
37
+ `));let r=$.resolve(n.input),t=await Ke(r),a="format"in t?t.format??"jsonl":"jsonl";if(console.log(` Version: ${o.cyan(t.version)}`),console.log(` Format: ${o.cyan(a)}`),console.log(` Exported: ${o.cyan(t.exportedAt)}`),console.log(` Source DB: ${o.cyan(t.sourceDb)}`),console.log(o.blue(`
38
+ Learning Data:`)),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"qValueCount"in t.stats&&console.log(` Q-Values: ${o.cyan(t.stats.qValueCount)}`),"dreamInsightCount"in t.stats){let l=t.stats.dreamInsightCount,d=("tableRecordCounts"in t?t.tableRecordCounts:void 0)?.dream_cycles,f=d!==void 0?` (${d} cycles)`:"";console.log(` Dream Insights: ${o.cyan(l)}${o.gray(f)}`)}"witnessChainLength"in t.stats&&console.log(` Witness Chain: ${o.cyan(t.stats.witnessChainLength)} entries`),"embeddingCount"in t.stats?console.log(` Embeddings: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`);let i="tableRecordCounts"in t?t.tableRecordCounts:void 0;if(i){let l=Object.entries(i).filter(([s,d])=>d>0&&!["qe_patterns","rl_q_values","dream_insights","dream_cycles","witness_chain","vectors","qe_pattern_embeddings"].includes(s));if(l.length>0)for(let[s,d]of l){let y=`${s.replace(/_/g," ").replace(/\b\w/g,h=>h.toUpperCase())}:`.padEnd(15);console.log(` ${y}${o.cyan(d)}`)}}let c="totalRecords"in t.stats?t.stats.totalRecords:void 0;if(c!==void 0&&(console.log(o.blue(`
39
+ Summary:`)),console.log(` Total Records: ${o.cyan(c)}`)),"domains"in t&&Array.isArray(t.domains)&&t.domains.length>0&&(c||console.log(o.blue(`
40
+ Summary:`)),console.log(` Domains: ${o.cyan(t.domains.join(", "))}`)),"rvfStatus"in t){let l=t.rvfStatus;console.log(o.blue(`
41
+ RVF Details:`)),console.log(` File Size: ${o.cyan(Ze(l.fileSizeBytes))}`),console.log(` Vectors: ${o.cyan(l.totalVectors)}`),console.log(` Segments: ${o.cyan(l.totalSegments)}`)}if("lineage"in t){let l=t.lineage;l&&(console.log(o.blue(`
42
+ Lineage:`)),console.log(` File ID: ${o.cyan(l.fileId)}`),console.log(` Parent ID: ${o.cyan(l.parentId??"none (root)")}`),console.log(` Depth: ${o.cyan(l.lineageDepth)}`))}if("signature"in t){let l=t.signature,s=t.signerKeyId;console.log(o.blue(`
43
+ Signature:`)),l?(console.log(` Status: ${o.green("Signed")}`),console.log(` Key ID: ${o.cyan(s??"unknown")}`),console.log(` Signature: ${o.gray(l.slice(0,32)+"...")}`)):console.log(` Status: ${o.yellow("Unsigned")}`)}console.log(`
44
+ Checksum: ${o.gray(t.checksum)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
45
+ Failed to read brain info:`),r),await this.cleanupAndExit(1)}}async executeDiff(n,r,t){try{let a=await Ge($.resolve(n),$.resolve(r),{tableFilter:t.table});if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
46
+ `),await this.cleanupAndExit(a.identical?0:1);return}Un(a,t.verbose),await this.cleanupAndExit(a.identical?0:1)}catch(a){console.error(o.red(`
47
+ Brain diff failed:`),a),await this.cleanupAndExit(2)}}async executeSearch(n){try{let r=Wn(n.limit),t=Jn(n.domain),a=await Qe($.resolve(n.input),{table:n.table,domains:t,patternType:n.patternType,since:n.since,until:n.until,query:n.query,limit:r});if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
48
+ `),await this.cleanupAndExit(a.totalMatched>0?0:3);return}Kn(a),await this.cleanupAndExit(a.totalMatched>0?0:3)}catch(r){console.error(o.red(`
49
+ Brain search failed:`),r),await this.cleanupAndExit(2)}}async executeWitnessBackfill(n){try{console.log(o.blue(`
50
+ Running witness chain backfill...
51
+ `));let r=await ye(n.db),t=await Ye(r);console.log(o.green(" Backfill complete.")),console.log(` Created: ${o.cyan(t.created)} new witness entries`),console.log(` Skipped: ${o.cyan(t.skipped)} (already witnessed)`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
52
+ Witness backfill failed:`),r),await this.cleanupAndExit(1)}}getHelp(){return`
53
+ Export, import, and inspect QE brain state.
54
+
55
+ Formats:
56
+ rvf \u2014 Single portable .rvf file (default, requires @ruvector/rvf-node)
57
+ jsonl \u2014 JSONL directory format (fallback when native not available)
58
+
59
+ Usage:
60
+ aqe brain export -o brain.rvf [--format rvf] [--db <path>]
61
+ aqe brain export -o ./brain-dir --format jsonl [--db <path>]
62
+ aqe brain import -i brain.rvf [--strategy skip-conflicts] [--dry-run] [--db <path>]
63
+ aqe brain info -i brain.rvf
64
+
65
+ Subcommands:
66
+ export Export brain state to a portable .rvf file or JSONL directory
67
+ import Import a brain export into the local database
68
+ info Show manifest metadata for an existing brain export
69
+ diff Compare two brain exports (manifest always; record-level for JSONL)
70
+ search Filtered search over a JSONL brain export
71
+
72
+ Examples:
73
+ aqe brain export -o .agentic-qe/brain.rvf
74
+ aqe brain export -o .agentic-qe/brain.rvf --format rvf
75
+ aqe brain export -o ./brain-export --format jsonl
76
+ aqe brain import -i .agentic-qe/brain.rvf --strategy latest-wins
77
+ aqe brain import -i .agentic-qe/brain.rvf --dry-run
78
+ aqe brain info -i .agentic-qe/brain.rvf
79
+ aqe brain diff ./brain-a ./brain-b --verbose
80
+ aqe brain search -i ./brain-export --query oauth --domain test-generation
81
+ aqe brain search -i ./brain-export --since 2026-03-01 --limit 50 --json
82
+ `}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-DDWMC435.js");return $.join(n(),".agentic-qe","memory.db")}function Ze(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Wn(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function Jn(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function Un(e,n){console.log(o.blue(`
83
+ Brain Diff
84
+ `)),console.log(` A: ${o.cyan(e.pathA)} (${e.formatA})`),console.log(` B: ${o.cyan(e.pathB)} (${e.formatB})`),console.log(` Versions: ${o.cyan(e.manifestA.version)} \u2192 ${o.cyan(e.manifestB.version)}`+(e.versionMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Checksums: ${o.gray(e.manifestA.checksum.slice(0,12))}\u2026 \u2192 ${o.gray(e.manifestB.checksum.slice(0,12))}\u2026`+(e.checksumMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Exported: ${o.gray(e.manifestA.exportedAt)} \u2192 ${o.gray(e.manifestB.exportedAt)}`),console.log(` Records: ${o.cyan(e.manifestA.totalRecords)} \u2192 ${o.cyan(e.manifestB.totalRecords)} `+en(e.manifestB.totalRecords-e.manifestA.totalRecords)),(e.domainsOnlyInA.length>0||e.domainsOnlyInB.length>0)&&(console.log(o.blue(`
85
+ Domains:`)),e.domainsOnlyInA.length>0&&console.log(` Only in A: ${o.yellow(e.domainsOnlyInA.join(", "))}`),e.domainsOnlyInB.length>0&&console.log(` Only in B: ${o.yellow(e.domainsOnlyInB.join(", "))}`)),e.recordLevel||console.log(o.gray(`
86
+ Note: record-level diff is only available when both sides are JSONL exports.
87
+ Per-table counts shown below; re-export with --format jsonl for added/removed/changed IDs.`)),console.log(o.blue(`
88
+ Tables:`));let r=e.tableDiffs.filter(Hn);if(r.length===0)console.log(o.gray(" (no differences)"));else for(let t of r)console.log(` ${t.tableName.padEnd(28)} ${o.cyan(String(t.countA).padStart(7))} \u2192 ${o.cyan(String(t.countB).padStart(7))} ${en(t.delta)}`+zn(t,n)),n&&(t.added&&t.added.length>0&&he("added",t.added),t.removed&&t.removed.length>0&&he("removed",t.removed),t.changed&&t.changed.length>0&&he("changed",t.changed));console.log(""),e.identical?console.log(o.green(` Result: identical
89
+ `)):console.log(o.yellow(` Result: differences found
90
+ `))}function Hn(e){return!!(e.delta!==0||e.added&&e.added.length>0||e.removed&&e.removed.length>0||e.changed&&e.changed.length>0)}function en(e){return e===0?o.gray("(\xB10)"):e>0?o.green(`(+${e})`):o.red(`(${e})`)}function zn(e,n){let r=[];return e.added&&e.added.length>0&&r.push(o.green(`+${e.added.length}`)),e.removed&&e.removed.length>0&&r.push(o.red(`-${e.removed.length}`)),e.changed&&e.changed.length>0&&r.push(o.yellow(`~${e.changed.length}`)),r.length===0?"":n?" "+r.join(" "):" "+o.gray("[")+r.join(" ")+o.gray("]")}function he(e,n){let r=n.slice(0,10).join(", "),t=n.length>10?o.gray(` \u2026(+${n.length-10} more)`):"";console.log(` ${o.gray(e+":")} ${r}${t}`)}function Kn(e){if(console.log(o.blue(`
91
+ Brain Search
92
+ `)),console.log(` Input: ${o.cyan(e.inputPath)}`),console.log(` Table: ${o.cyan(e.table)}`),console.log(` Scanned: ${o.cyan(e.totalScanned)} Matched: ${o.cyan(e.totalMatched)} Shown: ${o.cyan(e.hits.length)}`+(e.truncated?o.yellow(` (truncated to limit ${e.limit})`):"")),e.hits.length===0){console.log(o.yellow(`
93
+ No matching rows.
94
+ `));return}console.log("");for(let n of e.hits){let r=o.cyan(n.id)+(n.display.patternType?o.gray(` ${n.display.patternType}`):"")+(n.display.domain?o.gray(` [${n.display.domain}]`):"")+(n.display.confidence!==void 0?o.gray(` conf=${n.display.confidence.toFixed(2)}`):"");if(console.log(` ${r}`),n.display.name&&console.log(` ${o.bold(n.display.name)}`),n.display.description){let t=n.display.description.length>200?n.display.description.slice(0,200)+"\u2026":n.display.description;console.log(` ${o.gray(t)}`)}n.display.updatedAt&&console.log(` ${o.gray(n.display.updatedAt)}`),console.log("")}}function Dt(e,n){return new be(e,n)}export{be as BrainHandler,Dt as createBrainHandler};
@@ -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.14.4");process.exit(0)}
2
- import"./chunk-TT23RRB7.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
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.14.5");process.exit(0)}
2
+ import"./chunk-JSZ663MU.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
3
3
  `),l=!1;for(let i=0;i<n.length;i++){let d=n[i],t=d.trim(),c=i+1,u=d.length-d.trimStart().length+1;if(l){t.includes("*/")&&(l=!1);continue}if(t.startsWith("/*")){l=!t.includes("*/");continue}if(t.startsWith("//"))continue;if(/^\s*if\s*\(/.test(d)&&(this.findMatchingElse(n,i)||r.push({file:s,line:c,column:u,language:this.language,construct:"if-without-else",triggerCondition:"when condition is false",currentHandling:"falls through \u2014 no else branch",suggestedGuard:"Add else branch or document why falsy path is safe",severity:"medium"})),/^\s*switch\s*\(/.test(d)){let a=this.extractBlock(n,i);if(a&&!a.includes("default:")&&!a.includes("default :")&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-no-default",triggerCondition:"when value matches no case",currentHandling:"falls through \u2014 no default case",suggestedGuard:"Add default case with error handling or exhaustive check",severity:"high"}),a){let g=a.match(/case\s+[^:]+:/g)||[],h=a.match(/\b(break|return|throw|continue)\b/g)||[];g.length>0&&h.length<g.length&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-missing-break",triggerCondition:"when case falls through to next case",currentHandling:"fall-through \u2014 may execute unintended cases",suggestedGuard:"Add break/return to each case or add explicit // falls through comment",severity:"medium"})}}if(/\bcatch\s*\(/.test(t)||/\bcatch\s*\{/.test(t)){let a=this.extractBlock(n,i);if(a!==null){let g=a.replace(/[{}]/g,"").trim();(g.length===0||/^\s*\/\//.test(g))&&r.push({file:s,line:c,column:u,language:this.language,construct:"try-empty-catch",triggerCondition:"when exception is thrown",currentHandling:"exception silently swallowed",suggestedGuard:"Log the error or rethrow with context",severity:"high"})}}if(/\btry\s*\{/.test(t)&&this.extractBlock(n,i)&&(n.slice(i,Math.min(i+30,n.length)).join(`
4
4
  `).includes("finally")||r.push({file:s,line:c,column:u,language:this.language,construct:"try-no-finally",triggerCondition:"when cleanup is needed regardless of success/failure",currentHandling:"no finally block \u2014 cleanup may be skipped on exception",suggestedGuard:"Add finally block for resource cleanup if applicable",severity:"low"})),t.includes("?.")){let a=t.match(/(\w+(?:\.\w+)*)\?\./g)||[];for(let g of a)if(!t.includes("??")&&!t.includes("|| ")&&!t.includes("if")){r.push({file:s,line:c,column:u,language:this.language,construct:"optional-chaining-null-path",triggerCondition:`when ${g.replace("?.","")} is null/undefined`,currentHandling:"returns undefined \u2014 may propagate",suggestedGuard:"Add ?? fallback or explicit null check",severity:"low"});break}}if(t.includes("??")&&!t.includes("?.")&&r.push({file:s,line:c,column:u,language:this.language,construct:"nullish-coalescing-fallback",triggerCondition:"when left side is null/undefined",currentHandling:"uses fallback value",suggestedGuard:"Verify fallback value is appropriate for all null cases",severity:"low"}),/\.\s*then\s*\(/.test(t)&&!t.includes(".catch")&&!t.includes("await")){let a=n.slice(i,Math.min(i+5,n.length)).join(" ");!a.includes(".catch")&&!a.includes("try")&&r.push({file:s,line:c,column:u,language:this.language,construct:"promise-no-catch",triggerCondition:"when promise rejects",currentHandling:"unhandled rejection \u2014 may crash process",suggestedGuard:"Add .catch() handler or use try/catch with await",severity:"high"})}let p=["map","filter","reduce","forEach","find","some","every","flatMap"];for(let a of p)if(new RegExp(`\\.${a}\\s*\\(`).test(t)){let h=n.slice(Math.max(0,i-3),i).join(" ");if(!h.includes(".length")&&!h.includes("if (")&&!h.includes("?.")){r.push({file:s,line:c,column:u,language:this.language,construct:"array-callback-empty",triggerCondition:`when array is empty before .${a}()`,currentHandling:a==="reduce"?"may throw without initial value":"returns empty result \u2014 may cause downstream issues",suggestedGuard:a==="reduce"?"Provide initial value or check array length":"Check array length or handle empty result",severity:a==="reduce"?"high":"low"});break}}/\|\|\s*['"`\d]/.test(t)&&!t.includes("??")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-or-falsy",triggerCondition:'when left side is falsy (0, "", false, null, undefined)',currentHandling:'uses fallback \u2014 may unintentionally override 0, "", or false',suggestedGuard:"Use ?? instead of || if only null/undefined should trigger fallback",severity:"medium"}),/&&\s*\w+\s*\(/.test(t)&&!t.includes("if")&&!t.includes("while")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-and-short-circuit",triggerCondition:"when left side is falsy \u2014 right side never executes",currentHandling:"short-circuits \u2014 function call skipped silently",suggestedGuard:"Use explicit if-statement for clarity when side effects matter",severity:"low"}),(t.match(/\?/g)||[]).length>=2&&t.includes(":")&&r.push({file:s,line:c,column:u,language:this.language,construct:"ternary-complex",triggerCondition:"when nested ternary conditions interact",currentHandling:"nested ternary \u2014 hard to read and maintain",suggestedGuard:"Refactor to if/else or switch for readability",severity:"medium"}),(/\btypeof\s+\w+\s*===?\s*['"]/.test(t)||/\binstanceof\b/.test(t))&&!t.includes("else")&&!this.findMatchingElse(n,i)&&r.push({file:s,line:c,column:u,language:this.language,construct:"type-guard-unhandled",triggerCondition:"when value does not match the guarded type",currentHandling:"unguarded type path \u2014 may cause runtime type errors",suggestedGuard:"Add else branch or exhaustive type checking",severity:"medium"})}return r}findMatchingElse(e,s){let r={depth:0};for(let n=s;n<Math.min(s+30,e.length);n++){let l=e[n];for(let i of l)i==="{"&&r.depth++,i==="}"&&r.depth--;if(r.depth===0&&n>s){if((e[n+1]?.trim()||"").startsWith("else")||e[n].trim().endsWith("else")||e[n].trim().endsWith("else {")||e[n].includes("} else"))return!0;break}}return!1}extractBlock(e,s){let r=0,n=!1,l=[];for(let i=s;i<Math.min(s+50,e.length);i++){let d=e[i];for(let t of d)t==="{"&&(r++,n=!0),t==="}"&&r--;if(n&&(l.push(d),r===0))return l.join(`
5
5
  `)}return null}};function y(o,e,s){let r=Date.now(),n=s||(e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"javascript"),i=new f(n).enumerate(o,e);return{file:e,language:n,branches:i,totalConstructs:i.length,unhandledCount:i.length,duration:Date.now()-r}}function b(o){let e=[];if(e.push(`# Branch Enumeration Report: ${o.file}`),e.push(""),e.push(`**Language**: ${o.language} | **Branches**: ${o.unhandledCount} | **Duration**: ${o.duration}ms`),e.push(""),o.branches.length===0)return e.push("No unhandled branches detected."),e.join(`
@@ -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.14.4");process.exit(0)}
2
- import{a as p}from"./chunk-UDHKLT4C.js";import"./chunk-TT23RRB7.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${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.14.5");process.exit(0)}
2
+ import{a as p}from"./chunk-KKHYJF5U.js";import"./chunk-JSZ663MU.js";import{readFile as m,readdir as k}from"fs/promises";import{join as c,basename as y,dirname as W}from"path";import{fileURLToPath as v}from"url";import{parse as d}from"yaml";var b=v(import.meta.url),E=W(b),l=class{templatesDir;cache=new Map;constructor(r){this.templatesDir=r||c(E,"templates")}async load(r){if(this.cache.has(r))return this.cache.get(r);try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${r}:
3
3
  ${i.errors.join(`
4
4
  `)}`);return this.cache.set(r,o),o}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}async list(){try{return(await k(this.templatesDir)).filter(e=>e.endsWith(".yaml")||e.endsWith(".yml")).map(e=>y(e,e.endsWith(".yaml")?".yaml":".yml")).sort()}catch(r){if(r.code==="ENOENT")return[];throw r}}async validate(r){let e=[],n=[];if(r.name||e.push("Workflow must have a name"),r.version||e.push("Workflow must have a version"),r.description||n.push("Workflow should have a description"),Array.isArray(r.variables)?r.variables.forEach((o,i)=>{o.name||e.push(`Variable at index ${i} must have a name`),o.type||e.push(`Variable ${o.name} must have a type`),o.required===void 0&&n.push(`Variable ${o.name} should specify if it's required`)}):e.push("Workflow must have a variables array"),!Array.isArray(r.steps))e.push("Workflow must have a steps array");else if(r.steps.length===0)e.push("Workflow must have at least one step");else{r.steps.forEach((t,s)=>{t.name||e.push(`Step at index ${s} must have a name`),t.action||e.push(`Step ${t.name||s} must have an action`),(!t.config||typeof t.config!="object")&&e.push(`Step ${t.name||s} must have a config object`),t.assertions&&Array.isArray(t.assertions)&&t.assertions.forEach((f,u)=>{f.condition||e.push(`Assertion ${u} in step ${t.name||s} must have a condition`),f.message||n.push(`Assertion ${u} in step ${t.name||s} should have a message`)})});let o=r.steps.map(t=>t.name),i=o.filter((t,s)=>o.indexOf(t)!==s);i.length>0&&e.push(`Duplicate step names found: ${i.join(", ")}`)}return{valid:e.length===0,errors:e,warnings:n}}async createContext(r,e){let n=await this.load(r),o=n.variables.filter(t=>t.required&&!(t.name in e)).map(t=>t.name);if(o.length>0)throw new Error(`Missing required variables: ${o.join(", ")}`);let i={};return n.variables.forEach(t=>{t.name in e?i[t.name]=e[t.name]:"default"in t&&(i[t.name]=t.default)}),{variables:i,results:new Map,metadata:{startTime:Date.now(),workflow:n.name,templateName:r}}}async getMetadata(r){try{let e=c(this.templatesDir,`${r}.yaml`),n=await m(e,"utf-8"),o=d(n);return{name:o.name,version:o.version,description:o.description}}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${r}`):e}}clearCache(){this.cache.clear()}async reload(r){return this.cache.delete(r),this.load(r)}},x=new l;function w(a,r){return a.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=n.trim().split("."),t=r;for(let s of i)if(t&&typeof t=="object"&&s in t)t=t[s];else return e;return t!=null?String(t):e})}function T(a,r){let e={...r.variables,result:r.results.get("__last_result__")},n=w(a,e);return p(n,e,!1)}var g=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],A={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},h={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]};function _(a){return h[a]}function P(a){return g.includes(a)}function L(){return g.map(a=>{let r=Object.entries(h).find(([e,n])=>n.includes(a))?.[0]||"other";return{name:a,description:A[a],category:r}})}export{h as WORKFLOW_CATEGORIES,A as WORKFLOW_DESCRIPTIONS,g as WORKFLOW_TEMPLATES,l as WorkflowLoader,x as defaultWorkflowLoader,T as evaluateCondition,L as getAllWorkflowTemplates,_ as getWorkflowsByCategory,w as interpolateVariables,P as isValidWorkflowTemplate};
@@ -0,0 +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.14.5");process.exit(0)}
2
+ import{a}from"./chunk-E3W6XQ57.js";import"./chunk-YDFL445W.js";import"./chunk-LULD4JV2.js";import"./chunk-EFV4ADMO.js";import"./chunk-RKOUXVZZ.js";import"./chunk-IJHCIXJC.js";import"./chunk-NQI7FWCS.js";import"./chunk-C3HQL6S4.js";import"./chunk-J27F4NSB.js";import"./chunk-7CD7PBHY.js";import"./chunk-J5UNP6W3.js";import"./chunk-W2XCZU62.js";import"./chunk-7VFY7TUR.js";import"./chunk-HVU64GP5.js";import"./chunk-ELBZON4V.js";import"./chunk-52L77RMG.js";import"./chunk-XZSMZHM2.js";import"./chunk-CVMNJSCB.js";import"./chunk-NU7UTXMP.js";import"./chunk-D6OUCB2H.js";import"./chunk-6A44AOGN.js";import"./chunk-WJHWH5D2.js";import"./chunk-JSZ663MU.js";export{a as BrowserWorkflowTool};
@@ -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.14.4");process.exit(0)}
2
- import{k as f,o as P}from"./chunk-55RWDRJD.js";import{d as p,e as y}from"./chunk-Y3MW3YBC.js";import{b as h,d as U}from"./chunk-DHJPWQBR.js";import{a as T,c as C}from"./chunk-G6T45OIC.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.14.5");process.exit(0)}
2
+ import{k as f,o as P}from"./chunk-EFV4ADMO.js";import{b as h,d as U}from"./chunk-IJHCIXJC.js";import{d as p,e as y}from"./chunk-7CD7PBHY.js";import{a as T,c as C}from"./chunk-J5UNP6W3.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,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.14.4");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.14.5");process.exit(0)}
2
2
  import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
3
3
  `),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C 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.14.4");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.14.5");process.exit(0)}
2
2
  var i=class r{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new r(e)}};var s=class r{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new r(e)}static fromPercentage(e){return new r(e/100)}},u=class r{constructor(e,t){this._start=e;this._end=t;if(e>t)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,t){return new r(e,t)}static lastNDays(e){let t=new Date,n=new Date(t.getTime()-e*24*60*60*1e3);return new r(n,t)}},o=class r{constructor(e,t,n,a){this._major=e;this._minor=t;this._patch=n;this._prerelease=a}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,t,n,a){return new r(e,t,n,a)}static parse(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw new Error(`Invalid version format: ${e}`);return new r(parseInt(t[1]),parseInt(t[2]),parseInt(t[3]),t[4])}};export{i as a,s as b,u as c,o as d};
@@ -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.14.4");process.exit(0)}
2
- import{a as p}from"./chunk-6CQN24ZK.js";import{j as m,n as E}from"./chunk-3TW5W5LX.js";import{o as T}from"./chunk-55RWDRJD.js";import{b as V}from"./chunk-PEPFCPES.js";import k from"node:path";async function y(e){if(e.checklist.requirements.length===0)throw new Error("RequirementChecklist must have a non-empty, constant denominator (ADR-117).");if(!(e.oracle!=null&&e.oracle.baselinePassed&&e.oracle.passed)){let s=e.oracle==null?"oracle did not run":e.oracle.baselinePassed?"mutation score below threshold":"tests did not execute against the reference implementation";return{verdict:"fail",mechanical:"fail",specCoverage:null,unmet:[],attempts:0,reason:`mechanical gate failed: ${s}`}}if(!await e.judge.preflight())return{verdict:"inconclusive",mechanical:"pass",specCoverage:null,unmet:[],attempts:0,reason:"judge preflight failed: judge tooling did not run \u2014 refusing to report success"};let r=[],n=null,a=[],o=0;for(let s=0;s<2;s++){o++;let u=await e.judge.grade(e.artifact,e.checklist);if(u.ran&&(r.push(u),(n==null||u.coverage>n)&&(n=u.coverage,a=u.unmet),u.coverage>=1))return{verdict:"pass",mechanical:"pass",specCoverage:u.coverage,unmet:[],attempts:o,reason:`spec gate passed at coverage ${u.coverage.toFixed(3)} on attempt ${o}`}}return r.length>=2?{verdict:"fail",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate failed: ${r.length} real opinions, best coverage ${(n??0).toFixed(3)} < 1 (${a.length} unmet)`}:{verdict:"inconclusive",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate inconclusive: only ${r.length} real opinion(s) obtainable (need 2 to fail) \u2014 retry later, record neither pass nor fail`}}T();import{createHash as R}from"node:crypto";function I(e){let{manifestHash:t,...i}=e;return`sha256:${R("sha256").update(h(i)).digest("hex")}`}function b(e){return`sha256:${R("sha256").update(e).digest("hex")}`}function x(e,t={}){q(e);let i=I(e);if(e.manifestHash!==i)throw new Error(`Verification reach manifestHash mismatch: expected ${i}`);let r=t.now??new Date,n=r.toISOString(),a=e.expiresAt!=null&&r.getTime()>l(e.expiresAt,"expiresAt"),o=e.risks.map(s=>O(s,e,a,r.getTime()));return{manifestId:e.id,manifestHash:e.manifestHash,systemUnderTest:e.systemUnderTest,artifact:structuredClone(e.artifact),coverageVerdict:P(o.map(s=>s.verdict)),risks:o,evaluatedAt:n}}function O(e,t,i,r){let n=new Set,a=new Set,o=new Set,s=new Set,u=new Set;for(let c of e.checks){for(let v of c.limitations)u.add(v);if(S(c,t,i,r)){if(c.reach==="partial"){a.add(c.checkId);continue}if(c.reach==="direct"&&e.requiredObservations.includes(c.channel)&&c.oracleRef===e.requiredOracle){if(c.executionStatus==="failed"){o.add(c.checkId);continue}c.executionStatus==="passed"&&(n.add(c.checkId),s.add(c.channel))}}}let d=e.requiredObservations.filter(c=>!s.has(c)),f=o.size>0?"fail":d.length===0?"pass":e.dispositionWhenUncovered;return{riskId:e.riskId,failureMode:e.failureMode,severity:e.severity,verdict:f,directCheckIds:[...n],partialCheckIds:[...a],failedCheckIds:[...o],uncoveredObservations:d,limitations:[...u],reason:j(f,o,d,i)}}function S(e,t,i,r){if(i||!$(e.target,t.artifact)||e.evidenceClass!=="EXECUTED"||e.executionStatus==="not-run"||e.executionStatus==="unavailable"||!e.observedAt)return!1;let n=l(e.observedAt,`check ${e.checkId} observedAt`),a=l(t.generatedAt,"generatedAt");return!(n<a||n>r||t.expiresAt&&n>l(t.expiresAt,"expiresAt"))}function $(e,t){return e.revision===t.revision&&e.digest===t.digest&&e.environment===t.environment}function P(e){return e.some(t=>t==="fail")?"fail":e.some(t=>t==="human-review")?"human-review":e.some(t=>t==="inconclusive")?"inconclusive":"pass"}function j(e,t,i,r){return r?`verification manifest expired; uncovered: ${i.join(", ")}`:t.size>0?`direct check failed: ${[...t].join(", ")}`:e==="pass"?"all required observation channels have direct executed reach":`required reach is uncovered (${i.join(", ")}); disposition: ${e}`}function q(e){if(!e.id||!e.systemUnderTest)throw new Error("Verification reach manifest requires id and systemUnderTest");if(!e.artifact.revision||!e.artifact.digest||!e.artifact.environment)throw new Error("Verification reach manifest artifact requires revision, digest, and environment");if(l(e.generatedAt,"generatedAt"),e.expiresAt&&l(e.expiresAt,"expiresAt"),e.risks.length===0)throw new Error("Verification reach manifest requires at least one failure mode");let t=new Set;for(let i of e.risks){if(t.has(i.riskId))throw new Error(`Duplicate riskId: ${i.riskId}`);if(t.add(i.riskId),!i.riskId||!i.failureMode||!i.requiredOracle)throw new Error("Each failure mode requires riskId, failureMode, and requiredOracle");if(i.requiredObservations.length===0)throw new Error(`Failure mode ${i.riskId} requires at least one observation channel`)}}function l(e,t){let i=Date.parse(e);if(!Number.isFinite(i))throw new Error(`Invalid ${t} timestamp: ${e}`);return i}function h(e){return Array.isArray(e)?`[${e.map(h).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>`${JSON.stringify(i)}:${h(r)}`).join(",")}}`:JSON.stringify(e)}var U="verification/anchors/qe-anchor-v1.json";async function te(e){let t=J(e.checklistId,e.anchorPath);if(e.verificationManifest&&e.verificationManifest.artifact.digest!==b(e.artifact))throw new Error("Verification reach manifest artifact digest does not match the judged artifact");let i=e.verificationManifest?{kind:"verified",...x(e.verificationManifest)}:{kind:"legacy-unknown",coverageVerdict:"inconclusive",reason:"legacy quality-gate request has no verification reach manifest"},r=i.coverageVerdict,n=await y({oracle:e.oracleResult,artifact:e.artifact,checklist:t,judge:e.judge});return{...n,qualityVerdict:n.verdict,coverageVerdict:r,verdict:F(n.verdict,r),verification:i}}function F(e,t){return e==="fail"||t==="fail"?"fail":e==="pass"&&t==="pass"?"pass":"inconclusive"}function J(e,t){let i=C(t),r=p(i),n=r.items.find(a=>a.id===e);if(!n){let a=r.items.map(o=>o.id).join(", ");throw new Error(`Unknown checklist id "${e}" in anchor ${i}. Available: ${a}`)}return{id:n.id,requirements:n.requirements}}function ie(e){return p(C(e)).items.map(i=>i.id)}function C(e){if(e&&k.isAbsolute(e))return e;let t=V();return k.resolve(t,e??U)}E();var D=6e4,Q=15e3;function N(e){let t=e.timeoutMs??D,i=e.logger??(()=>{}),r=e.model??"frontier",n=e.ping??(async()=>{let a=await w(e.complete("Reply with exactly: OK"),Math.min(Q,t),"judge preflight ping");return typeof a=="string"&&a.trim().length>0});return{async preflight(){try{let a=await n();return a||i(`frontier-judge preflight: provider (${r}) returned empty \u2014 not ready`),a}catch(a){return i(`frontier-judge preflight failed (${r}): ${M(a)}`),!1}},async grade(a,o){let s=o.requirements.length;try{let u=H(a,o),d=await w(e.complete(u),t,"judge grade"),f=G(d,s);if(f==null)return i(`frontier-judge grade: could not parse response for ${o.id}`),{ran:!1,coverage:0,unmet:[]};let c=[...f].sort((g,A)=>g-A).map(g=>o.requirements[g]);return{ran:!0,coverage:(s-c.length)/s,unmet:c}}catch(u){return i(`frontier-judge grade failed for ${o.id} (${r}): ${M(u)}`),{ran:!1,coverage:0,unmet:[]}}}}}function _(e,t={}){let i=t.model??m;return async r=>(await e.chat({messages:[{role:"user",content:r}],model:i,strictModel:!0,preferredProvider:t.preferredProvider,temperature:t.temperature??0,maxTokens:t.maxTokens??1024,timeoutMs:t.timeoutMs,skipCache:!0})).content??""}function ae(e,t={}){let i=t.model??m;return N({complete:_(e,{...t,model:i}),model:i,timeoutMs:t.timeoutMs,logger:t.logger})}function oe(e){return{preflight:()=>!1,grade:()=>({ran:!1,coverage:0,unmet:[]})}}function H(e,t){let i=t.requirements.map((r,n)=>`${n+1}. ${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.14.5");process.exit(0)}
2
+ import{a as p}from"./chunk-OEIQTWQP.js";import{j as m,n as E}from"./chunk-R6IU3EWP.js";import{o as T}from"./chunk-EFV4ADMO.js";import{b as V}from"./chunk-C3HQL6S4.js";import k from"node:path";async function y(e){if(e.checklist.requirements.length===0)throw new Error("RequirementChecklist must have a non-empty, constant denominator (ADR-117).");if(!(e.oracle!=null&&e.oracle.baselinePassed&&e.oracle.passed)){let s=e.oracle==null?"oracle did not run":e.oracle.baselinePassed?"mutation score below threshold":"tests did not execute against the reference implementation";return{verdict:"fail",mechanical:"fail",specCoverage:null,unmet:[],attempts:0,reason:`mechanical gate failed: ${s}`}}if(!await e.judge.preflight())return{verdict:"inconclusive",mechanical:"pass",specCoverage:null,unmet:[],attempts:0,reason:"judge preflight failed: judge tooling did not run \u2014 refusing to report success"};let r=[],n=null,a=[],o=0;for(let s=0;s<2;s++){o++;let u=await e.judge.grade(e.artifact,e.checklist);if(u.ran&&(r.push(u),(n==null||u.coverage>n)&&(n=u.coverage,a=u.unmet),u.coverage>=1))return{verdict:"pass",mechanical:"pass",specCoverage:u.coverage,unmet:[],attempts:o,reason:`spec gate passed at coverage ${u.coverage.toFixed(3)} on attempt ${o}`}}return r.length>=2?{verdict:"fail",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate failed: ${r.length} real opinions, best coverage ${(n??0).toFixed(3)} < 1 (${a.length} unmet)`}:{verdict:"inconclusive",mechanical:"pass",specCoverage:n,unmet:a,attempts:o,reason:`spec gate inconclusive: only ${r.length} real opinion(s) obtainable (need 2 to fail) \u2014 retry later, record neither pass nor fail`}}T();import{createHash as R}from"node:crypto";function I(e){let{manifestHash:t,...i}=e;return`sha256:${R("sha256").update(h(i)).digest("hex")}`}function b(e){return`sha256:${R("sha256").update(e).digest("hex")}`}function x(e,t={}){q(e);let i=I(e);if(e.manifestHash!==i)throw new Error(`Verification reach manifestHash mismatch: expected ${i}`);let r=t.now??new Date,n=r.toISOString(),a=e.expiresAt!=null&&r.getTime()>l(e.expiresAt,"expiresAt"),o=e.risks.map(s=>O(s,e,a,r.getTime()));return{manifestId:e.id,manifestHash:e.manifestHash,systemUnderTest:e.systemUnderTest,artifact:structuredClone(e.artifact),coverageVerdict:P(o.map(s=>s.verdict)),risks:o,evaluatedAt:n}}function O(e,t,i,r){let n=new Set,a=new Set,o=new Set,s=new Set,u=new Set;for(let c of e.checks){for(let v of c.limitations)u.add(v);if(S(c,t,i,r)){if(c.reach==="partial"){a.add(c.checkId);continue}if(c.reach==="direct"&&e.requiredObservations.includes(c.channel)&&c.oracleRef===e.requiredOracle){if(c.executionStatus==="failed"){o.add(c.checkId);continue}c.executionStatus==="passed"&&(n.add(c.checkId),s.add(c.channel))}}}let d=e.requiredObservations.filter(c=>!s.has(c)),f=o.size>0?"fail":d.length===0?"pass":e.dispositionWhenUncovered;return{riskId:e.riskId,failureMode:e.failureMode,severity:e.severity,verdict:f,directCheckIds:[...n],partialCheckIds:[...a],failedCheckIds:[...o],uncoveredObservations:d,limitations:[...u],reason:j(f,o,d,i)}}function S(e,t,i,r){if(i||!$(e.target,t.artifact)||e.evidenceClass!=="EXECUTED"||e.executionStatus==="not-run"||e.executionStatus==="unavailable"||!e.observedAt)return!1;let n=l(e.observedAt,`check ${e.checkId} observedAt`),a=l(t.generatedAt,"generatedAt");return!(n<a||n>r||t.expiresAt&&n>l(t.expiresAt,"expiresAt"))}function $(e,t){return e.revision===t.revision&&e.digest===t.digest&&e.environment===t.environment}function P(e){return e.some(t=>t==="fail")?"fail":e.some(t=>t==="human-review")?"human-review":e.some(t=>t==="inconclusive")?"inconclusive":"pass"}function j(e,t,i,r){return r?`verification manifest expired; uncovered: ${i.join(", ")}`:t.size>0?`direct check failed: ${[...t].join(", ")}`:e==="pass"?"all required observation channels have direct executed reach":`required reach is uncovered (${i.join(", ")}); disposition: ${e}`}function q(e){if(!e.id||!e.systemUnderTest)throw new Error("Verification reach manifest requires id and systemUnderTest");if(!e.artifact.revision||!e.artifact.digest||!e.artifact.environment)throw new Error("Verification reach manifest artifact requires revision, digest, and environment");if(l(e.generatedAt,"generatedAt"),e.expiresAt&&l(e.expiresAt,"expiresAt"),e.risks.length===0)throw new Error("Verification reach manifest requires at least one failure mode");let t=new Set;for(let i of e.risks){if(t.has(i.riskId))throw new Error(`Duplicate riskId: ${i.riskId}`);if(t.add(i.riskId),!i.riskId||!i.failureMode||!i.requiredOracle)throw new Error("Each failure mode requires riskId, failureMode, and requiredOracle");if(i.requiredObservations.length===0)throw new Error(`Failure mode ${i.riskId} requires at least one observation channel`)}}function l(e,t){let i=Date.parse(e);if(!Number.isFinite(i))throw new Error(`Invalid ${t} timestamp: ${e}`);return i}function h(e){return Array.isArray(e)?`[${e.map(h).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,i])=>i!==void 0).sort(([i],[r])=>i<r?-1:i>r?1:0).map(([i,r])=>`${JSON.stringify(i)}:${h(r)}`).join(",")}}`:JSON.stringify(e)}var U="verification/anchors/qe-anchor-v1.json";async function te(e){let t=J(e.checklistId,e.anchorPath);if(e.verificationManifest&&e.verificationManifest.artifact.digest!==b(e.artifact))throw new Error("Verification reach manifest artifact digest does not match the judged artifact");let i=e.verificationManifest?{kind:"verified",...x(e.verificationManifest)}:{kind:"legacy-unknown",coverageVerdict:"inconclusive",reason:"legacy quality-gate request has no verification reach manifest"},r=i.coverageVerdict,n=await y({oracle:e.oracleResult,artifact:e.artifact,checklist:t,judge:e.judge});return{...n,qualityVerdict:n.verdict,coverageVerdict:r,verdict:F(n.verdict,r),verification:i}}function F(e,t){return e==="fail"||t==="fail"?"fail":e==="pass"&&t==="pass"?"pass":"inconclusive"}function J(e,t){let i=C(t),r=p(i),n=r.items.find(a=>a.id===e);if(!n){let a=r.items.map(o=>o.id).join(", ");throw new Error(`Unknown checklist id "${e}" in anchor ${i}. Available: ${a}`)}return{id:n.id,requirements:n.requirements}}function ie(e){return p(C(e)).items.map(i=>i.id)}function C(e){if(e&&k.isAbsolute(e))return e;let t=V();return k.resolve(t,e??U)}E();var D=6e4,Q=15e3;function N(e){let t=e.timeoutMs??D,i=e.logger??(()=>{}),r=e.model??"frontier",n=e.ping??(async()=>{let a=await w(e.complete("Reply with exactly: OK"),Math.min(Q,t),"judge preflight ping");return typeof a=="string"&&a.trim().length>0});return{async preflight(){try{let a=await n();return a||i(`frontier-judge preflight: provider (${r}) returned empty \u2014 not ready`),a}catch(a){return i(`frontier-judge preflight failed (${r}): ${M(a)}`),!1}},async grade(a,o){let s=o.requirements.length;try{let u=H(a,o),d=await w(e.complete(u),t,"judge grade"),f=G(d,s);if(f==null)return i(`frontier-judge grade: could not parse response for ${o.id}`),{ran:!1,coverage:0,unmet:[]};let c=[...f].sort((g,A)=>g-A).map(g=>o.requirements[g]);return{ran:!0,coverage:(s-c.length)/s,unmet:c}}catch(u){return i(`frontier-judge grade failed for ${o.id} (${r}): ${M(u)}`),{ran:!1,coverage:0,unmet:[]}}}}}function _(e,t={}){let i=t.model??m;return async r=>(await e.chat({messages:[{role:"user",content:r}],model:i,strictModel:!0,preferredProvider:t.preferredProvider,temperature:t.temperature??0,maxTokens:t.maxTokens??1024,timeoutMs:t.timeoutMs,skipCache:!0})).content??""}function ae(e,t={}){let i=t.model??m;return N({complete:_(e,{...t,model:i}),model:i,timeoutMs:t.timeoutMs,logger:t.logger})}function oe(e){return{preflight:()=>!1,grade:()=>({ran:!1,coverage:0,unmet:[]})}}function H(e,t){let i=t.requirements.map((r,n)=>`${n+1}. ${r}`).join(`
3
3
  `);return["You are a rigorous, frontier-tier quality oracle grading a software artifact","against a FIXED requirement checklist. Judge only what the artifact actually","verifies \u2014 do not give credit for requirements it merely mentions or leaves",'implicit. A requirement is "met" only if the artifact demonstrably covers it.',"",`Checklist id: ${t.id}`,"Requirements (the denominator is fixed \u2014 grade ALL of them):",i,"","--- ARTIFACT UNDER JUDGEMENT ---",e,"--- END ARTIFACT ---","","Return ONLY a single JSON object, no prose, no markdown fences, of the form:",'{"unmet": [<numbers of requirements NOT met>]}','Use the requirement numbers above. If every requirement is met, return {"unmet": []}.'].join(`
4
4
  `)}function G(e,t){let i=L(e);if(i==null||!Array.isArray(i.unmet))return null;let r=i.unmet,n=new Set;for(let a of r){let o=typeof a=="number"?a:typeof a=="string"?Number(a.trim()):NaN;if(!Number.isInteger(o))continue;let s=o-1;s>=0&&s<t&&n.add(s)}return r.length>0&&n.size===0?null:n}function L(e){if(typeof e!="string")return null;let t=e.indexOf("{");if(t===-1)return null;let i=0,r=!1,n=!1;for(let a=t;a<e.length;a++){let o=e[a];if(r){n?n=!1:o==="\\"?n=!0:o==='"'&&(r=!1);continue}if(o==='"')r=!0;else if(o==="{")i++;else if(o==="}"&&(i--,i===0))try{return JSON.parse(e.slice(t,a+1))}catch{return null}}return null}function w(e,t,i){return new Promise((r,n)=>{let a=setTimeout(()=>n(new Error(`${i} timed out after ${t}ms`)),t);e.then(o=>{clearTimeout(a),r(o)},o=>{clearTimeout(a),n(o)})})}function M(e){return e instanceof Error?e.message:String(e)}export{te as a,ie as b,ae as c,oe as d};
@@ -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.14.4");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.14.5");process.exit(0)}
2
2
  var o=!1;function r(t){if(!o){for(let e of["ALTER TABLE routing_outcomes ADD COLUMN exploration INTEGER NOT NULL DEFAULT 0","ALTER TABLE routing_outcomes ADD COLUMN criticality REAL","ALTER TABLE routing_outcomes ADD COLUMN q_weight REAL"])try{t.prepare(e).run()}catch{}try{t.prepare("CREATE INDEX IF NOT EXISTS idx_routing_outcomes_exploration ON routing_outcomes(exploration)").run()}catch{}o=!0}}export{r 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.14.4");process.exit(0)}
2
- import{a as Y}from"./chunk-HIYXCDEP.js";import{a as q,e as C,f as J}from"./chunk-CDHQFHRP.js";import{a as T}from"./chunk-6VRA2QGL.js";import{a as U,b as j,c as G,d as B,f as $}from"./chunk-IFCLB7FJ.js";import{a as O,b as z,f as _,i as H}from"./chunk-T6BVLVI5.js";import{d as F}from"./chunk-MCUJEZT6.js";import{a as M,e as P,g as A,i as N,j as S,n as W}from"./chunk-NDPFGIMJ.js";import{a as Z}from"./chunk-NA7B2QYB.js";import{c as L}from"./chunk-Y3MW3YBC.js";import{b as v,d as ee}from"./chunk-DHJPWQBR.js";import{b as h,c as p}from"./chunk-STM3UDNO.js";import{a as I,b as f,c as X}from"./chunk-G6T45OIC.js";import{i as D}from"./chunk-SRKETSFF.js";Z();X();ee();var o=L.create("RealQEReasoningBank"),te={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...te,...e},this.sqliteStore=F(this.qeConfig.sqlite),this.asymmetricEngine=new Y}coherenceService;qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new T(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await P(M,this.qeConfig.embeddings),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-LG6OS3B7.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=S();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=S(),i=0,n=0,a=W()?.spaceId;for(let{patternId:s,embedding:r,spaceId:c}of e){if(!a||c!==a||!r||!Array.isArray(r)||r.length!==t){n++;continue}let m=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(r,m),this.patternIdMap.set(m,s),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
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.14.5");process.exit(0)}
2
+ import{a as Y}from"./chunk-QYOGD2VW.js";import{a as q,e as C,f as J}from"./chunk-QIRL6B3C.js";import{a as D}from"./chunk-BHFR2EXL.js";import{a as U,b as j,c as G,d as B,f as $}from"./chunk-RP2ZKPYV.js";import{a as O,b as z,f as _,i as H}from"./chunk-5WOSWNDN.js";import{d as F}from"./chunk-UTBYJ4RF.js";import{a as M,e as P,g as A,i as N,j as S,n as W}from"./chunk-KIP6WZGV.js";import{b as v,d as ee}from"./chunk-IJHCIXJC.js";import{c as h,d as p}from"./chunk-XEZIIQYJ.js";import{a as Z}from"./chunk-J27F4NSB.js";import{c as T}from"./chunk-7CD7PBHY.js";import{a as I,b as f,c as X}from"./chunk-J5UNP6W3.js";import{i as L}from"./chunk-W2XCZU62.js";Z();X();ee();var o=T.create("RealQEReasoningBank"),te={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...te,...e},this.sqliteStore=F(this.qeConfig.sqlite),this.asymmetricEngine=new Y}coherenceService;qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new D(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await P(M,this.qeConfig.embeddings),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-GW67GTCL.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=S();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=S(),i=0,n=0,a=W()?.spaceId;for(let{patternId:s,embedding:r,spaceId:c}of e){if(!a||c!==a||!r||!Array.isArray(r)||r.length!==t){n++;continue}let m=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(r,m),this.patternIdMap.set(m,s),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -12,7 +12,7 @@ import{a as Y}from"./chunk-HIYXCDEP.js";import{a as q,e as C,f as J}from"./chunk
12
12
  {{assertCode}}
13
13
  });
14
14
  });
15
- });`,variables:[{name:"className",type:"string",required:!0},{name:"methodName",type:"string",required:!0},{name:"expectedBehavior",type:"string",required:!0}]},context:{testType:"unit",tags:["unit-test","aaa","best-practice"]}},{patternType:"coverage-strategy",name:"Risk-Based Coverage",description:"Prioritize coverage by code risk and complexity",template:{type:"prompt",content:"Analyze coverage gaps focusing on critical business logic, error handling, and high-complexity functions.",variables:[]},context:{tags:["coverage","risk-based"]}}];for(let t of e)try{await this.storeQEPattern(t)}catch(i){o.warn("Failed to load foundational pattern",{name:t.name,error:i})}o.info("Loaded foundational patterns",{count:e.length})}async storeQEPattern(e){try{let t=`${e.name} ${e.description||""} ${e.context?.tags?.join(" ")||""}`,i=await P(t,this.qeConfig.embeddings),n=O(t)||"test-generation";if(q())try{let r=J(e.name,{description:e.description,template:e.template,patternType:e.patternType},n,{tags:e.context?.tags}),c=await C.evaluateWrite(r);if(!c.allowed&&(o.warn("Pattern blocked by MemoryWriteGate",{name:e.name,reason:c.reason,conflicts:c.conflictingPatterns?.join(", ")||"none"}),c.reason?.includes("strict")))return p(new Error(`Pattern blocked by governance: ${c.reason}`))}catch(r){o.warn("MemoryWriteGate check error (continuing)",{error:r})}let a=D(),s={id:a,patternType:e.patternType,qeDomain:n,domain:n,name:e.name,description:e.description||"",confidence:.5,usageCount:0,successRate:0,qualityScore:0,tier:"short-term",template:e.template,context:{tags:[],...e.context},createdAt:new Date,lastUsedAt:new Date,successfulUses:0,embedding:i,reusable:!1,reuseCount:0,averageTokenSavings:0};if(this.sqliteStore.storePattern(s,i),this.hnswIndex){let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(i,r),this.patternIdMap.set(r,a)}if(q())try{C.registerPattern({key:a,value:{name:s.name,description:s.description,patternType:s.patternType},domain:s.domain})}catch(r){o.warn("Pattern registration with MemoryWriteGate failed",{error:r})}return h(s)}catch(t){return p(f(t))}}async searchQEPatterns(e,t={}){let i=performance.now();try{if(!this.hnswIndex)return p(new Error("HNSW index not available"));let n=await P(e,this.qeConfig.embeddings),a=t.limit||10,s=this.hnswIndex.searchKnn(n,a*2),r=[];for(let m=0;m<s.neighbors.length&&r.length<a;m++){let g=s.neighbors[m],l=1-s.distances[m];if(t.minSimilarity&&l<t.minSimilarity)continue;let d=this.patternIdMap.get(g);if(!d)continue;let u=this.sqliteStore.getPattern(d);u&&(t.domain&&u.qeDomain!==t.domain||r.push({pattern:u,similarity:l}))}let c=performance.now()-i;return c>10&&o.warn("Slow search",{searchTimeMs:Number(c.toFixed(1))}),h(r)}catch(n){return p(f(n))}}async routeTask(e){let t=performance.now();this.stats.routingRequests++;try{let i=e.domain?[e.domain]:z(e.task);i.length===0&&i.push("test-generation");let n=await this.searchQEPatterns(e.task,{limit:10,domain:i[0]}),a=n.success?n.value.map(l=>l.pattern):[],s=[];for(let[l,d]of Object.entries(this.agentCapabilities)){let u=0,b=[],Q=i.filter(y=>d.domains.includes(y)).length,E=Q>0?Q/i.length*.4:0;if(u+=E*this.qeConfig.routingWeights.similarity,E>0&&b.push(`Domain: ${(E*100).toFixed(0)}%`),e.capabilities&&e.capabilities.length>0){let y=e.capabilities.filter(K=>d.capabilities.some(V=>V.toLowerCase().includes(K.toLowerCase()))).length,w=y>0?y/e.capabilities.length*.3:0;u+=w*this.qeConfig.routingWeights.capabilities,w>0&&b.push(`Caps: ${(w*100).toFixed(0)}%`)}else u+=.15*this.qeConfig.routingWeights.capabilities;u+=d.performanceScore*.3*this.qeConfig.routingWeights.performance,b.push(`Perf: ${(d.performanceScore*100).toFixed(0)}%`),s.push({agent:l,score:u,reasoning:b})}s.sort((l,d)=>d.score-l.score);let r=s[0],c=s.slice(1,4),m=[];if(this.qeConfig.enableGuidance&&i.length>0){let l=j(i[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});m.push(...l.slice(0,5))}let g=performance.now()-t;this.stats.totalRoutingLatency+=g,this.routingLatencies.push(g);let x={recommendedAgent:r.agent,confidence:r.score,alternatives:c.map(l=>({agent:l.agent,score:l.score})),domains:i,patterns:a,guidance:m,reasoning:r.reasoning.join("; "),latencyMs:g};return h($(e.includePatternGuidance,x,n.success?n.value:[]))}catch(i){return p(f(i))}}async recordOutcome(e){if(!this.qeConfig.enableLearning)return h(void 0);try{this.sqliteStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback),this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++;let t=this.sqliteStore.getPattern(e.patternId);if(t){let i=t.qeDomain,n=this.asymmetricEngine.computeConfidenceUpdate(t.confidence,e.success?"success":"failure",i);this.asymmetricEngine.shouldQuarantine(n,i).shouldQuarantine&&o.info("Pattern quarantined (asymmetric drop)",{name:t.name}),this.sqliteStore.updatePattern(e.patternId,{confidence:n}),await this.checkPatternPromotionWithCoherence(t)&&(this.sqliteStore.promotePattern(e.patternId),o.info("Pattern promoted to long-term",{name:t.name}))}return h(void 0)}catch(t){return p(f(t))}}async checkPatternPromotionWithCoherence(e){let t=_(e);if(!t.meetsUsageCriteria||!t.meetsQualityCriteria)return!1;if(this.coherenceService&&this.coherenceService.isInitialized()){let a=[...await this.getLongTermPatterns(),e].map(r=>({id:r.id,embedding:r.embedding||[],weight:r.confidence,metadata:{name:r.name,domain:r.qeDomain}})),s=await this.coherenceService.checkCoherence(a);if(s.energy>=(this.qeConfig.coherenceThreshold||.4))return o.info("Pattern promotion blocked due to coherence violation",{name:e.name,energy:s.energy}),s.contradictions&&s.contradictions.length>0&&o.info("Conflicts with existing patterns",{conflictingNodeIds:s.contradictions.map(r=>r.nodeIds).flat()}),!1}return!0}async getLongTermPatterns(){return this.sqliteStore.getPatterns({limit:1e3}).filter(t=>t.tier==="long-term")}shouldPromote(e){return e.tier==="short-term"&&e.successfulUses>=3&&e.successRate>=.7&&e.confidence>=.6}getQEGuidance(e){return U(e)}generateQEContext(e,t){return B(e,t||{})}checkQEAntiPatterns(e,t){return G(e,t)}async getQEStats(){let e=this.sqliteStore.getStats(),t=this.routingLatencies.percentile(95)||0,i={};for(let n of H)i[n]=e.byDomain[n]||0;return{totalPatterns:e.totalPatterns,byDomain:i,byTier:e.byTier,routingRequests:this.stats.routingRequests,avgRoutingLatencyMs:this.stats.routingRequests>0?this.stats.totalRoutingLatency/this.stats.routingRequests:0,p95RoutingLatencyMs:t,learningOutcomes:this.stats.learningOutcomes,patternSuccessRate:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0,embeddingCacheSize:0,transformerAvailable:N(),embeddingDimension:S(),sqliteDbPath:this.qeConfig.sqlite.dbPath||".agentic-qe/memory.db",asymmetricLearning:{failurePenaltyRatio:"10:1",quarantinedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!0).length,rehabilitatedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!1&&n.quarantinedAt).length,avgConfidenceDelta:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes-.5:0}}}async storeLoopPattern(e){try{let t=await this.storeQEPattern({patternType:"anti-pattern",name:`loop-detection:${e.toolCallSignature}`,description:`Tool call loop detected for agent ${e.agentId} during ${e.taskType}. Steering: ${e.steeringUsed}. Resolved: ${e.resolved}`,template:{type:"prompt",content:e.steeringUsed,variables:[]},context:{tags:["anti-pattern","loop-detection","learning-optimization",e.taskType]}});return t.success?{success:!0,patternId:t.value.id}:{success:!1,error:t.error?.message??"Unknown error"}}catch(t){return{success:!1,error:I(t)}}}async recordPatternOutcome(e,t,i){let n=this.sqliteStore.getPattern(e);if(!n)return;let a=n.usageCount+1,s=t?n.successfulUses+1:n.successfulUses,r=s/a,c=.3,m=(1-c)*n.qualityScore+c*i,g=Math.min(1,.5+a*.05+r*.3);this.sqliteStore.updatePattern(e,{usageCount:a,successfulUses:s,successRate:r,qualityScore:m,confidence:g})}async checkPatternPromotion(e,t,i,n){let a=this.sqliteStore.getPattern(e);return a?a.tier==="short-term"?t>=3&&i>=.6&&n>=.5:a.tier==="long-term"?t>=10&&i>=.75&&n>=.7:!1:!1}async promotePattern(e){this.sqliteStore.promotePattern(e)}async demotePattern(e){let t=this.sqliteStore.getPattern(e);if(!t)return;let i=["short-term","working","long-term"],n=i.indexOf(t.tier);if(n>0){let a=i[n-1];this.sqliteStore.updatePattern(e,{tier:a}),o.info("Pattern demoted",{name:t.name,newTier:a})}}cleanupPatternIdMap(){if(!this.initialized)return 0;let e=0,t=this.sqliteStore.getPatterns({limit:1e5}),i=new Set(t.map(n=>n.id));for(let[n,a]of Array.from(this.patternIdMap.entries()))i.has(a)||(this.patternIdMap.delete(n),e++);return e>0&&o.info("Cleaned stale patternIdMap entries",{count:e}),e}removePatternFromHNSW(e){for(let[t,i]of Array.from(this.patternIdMap.entries()))if(i===e)return this.patternIdMap.delete(t),o.info("Removed pattern from HNSW mapping",{patternId:e}),!0;return!1}getMemoryStats(){return{patternIdMapSize:this.patternIdMap.size,routingLatenciesSize:this.routingLatencies.length,hnswIndexCount:this.hnswIndex?.getCurrentCount()??0}}async storeTrajectory(e){return this.sqliteStore.getDb().prepare(`
15
+ });`,variables:[{name:"className",type:"string",required:!0},{name:"methodName",type:"string",required:!0},{name:"expectedBehavior",type:"string",required:!0}]},context:{testType:"unit",tags:["unit-test","aaa","best-practice"]}},{patternType:"coverage-strategy",name:"Risk-Based Coverage",description:"Prioritize coverage by code risk and complexity",template:{type:"prompt",content:"Analyze coverage gaps focusing on critical business logic, error handling, and high-complexity functions.",variables:[]},context:{tags:["coverage","risk-based"]}}];for(let t of e)try{await this.storeQEPattern(t)}catch(i){o.warn("Failed to load foundational pattern",{name:t.name,error:i})}o.info("Loaded foundational patterns",{count:e.length})}async storeQEPattern(e){try{let t=`${e.name} ${e.description||""} ${e.context?.tags?.join(" ")||""}`,i=await P(t,this.qeConfig.embeddings),n=O(t)||"test-generation";if(q())try{let r=J(e.name,{description:e.description,template:e.template,patternType:e.patternType},n,{tags:e.context?.tags}),c=await C.evaluateWrite(r);if(!c.allowed&&(o.warn("Pattern blocked by MemoryWriteGate",{name:e.name,reason:c.reason,conflicts:c.conflictingPatterns?.join(", ")||"none"}),c.reason?.includes("strict")))return p(new Error(`Pattern blocked by governance: ${c.reason}`))}catch(r){o.warn("MemoryWriteGate check error (continuing)",{error:r})}let a=L(),s={id:a,patternType:e.patternType,qeDomain:n,domain:n,name:e.name,description:e.description||"",confidence:.5,usageCount:0,successRate:0,qualityScore:0,tier:"short-term",template:e.template,context:{tags:[],...e.context},createdAt:new Date,lastUsedAt:new Date,successfulUses:0,embedding:i,reusable:!1,reuseCount:0,averageTokenSavings:0};if(this.sqliteStore.storePattern(s,i),this.hnswIndex){let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(i,r),this.patternIdMap.set(r,a)}if(q())try{C.registerPattern({key:a,value:{name:s.name,description:s.description,patternType:s.patternType},domain:s.domain})}catch(r){o.warn("Pattern registration with MemoryWriteGate failed",{error:r})}return h(s)}catch(t){return p(f(t))}}async searchQEPatterns(e,t={}){let i=performance.now();try{if(!this.hnswIndex)return p(new Error("HNSW index not available"));let n=await P(e,this.qeConfig.embeddings),a=t.limit||10,s=this.hnswIndex.searchKnn(n,a*2),r=[];for(let m=0;m<s.neighbors.length&&r.length<a;m++){let g=s.neighbors[m],l=1-s.distances[m];if(t.minSimilarity&&l<t.minSimilarity)continue;let d=this.patternIdMap.get(g);if(!d)continue;let u=this.sqliteStore.getPattern(d);u&&(t.domain&&u.qeDomain!==t.domain||r.push({pattern:u,similarity:l}))}let c=performance.now()-i;return c>10&&o.warn("Slow search",{searchTimeMs:Number(c.toFixed(1))}),h(r)}catch(n){return p(f(n))}}async routeTask(e){let t=performance.now();this.stats.routingRequests++;try{let i=e.domain?[e.domain]:z(e.task);i.length===0&&i.push("test-generation");let n=await this.searchQEPatterns(e.task,{limit:10,domain:i[0]}),a=n.success?n.value.map(l=>l.pattern):[],s=[];for(let[l,d]of Object.entries(this.agentCapabilities)){let u=0,b=[],Q=i.filter(y=>d.domains.includes(y)).length,E=Q>0?Q/i.length*.4:0;if(u+=E*this.qeConfig.routingWeights.similarity,E>0&&b.push(`Domain: ${(E*100).toFixed(0)}%`),e.capabilities&&e.capabilities.length>0){let y=e.capabilities.filter(K=>d.capabilities.some(V=>V.toLowerCase().includes(K.toLowerCase()))).length,w=y>0?y/e.capabilities.length*.3:0;u+=w*this.qeConfig.routingWeights.capabilities,w>0&&b.push(`Caps: ${(w*100).toFixed(0)}%`)}else u+=.15*this.qeConfig.routingWeights.capabilities;u+=d.performanceScore*.3*this.qeConfig.routingWeights.performance,b.push(`Perf: ${(d.performanceScore*100).toFixed(0)}%`),s.push({agent:l,score:u,reasoning:b})}s.sort((l,d)=>d.score-l.score);let r=s[0],c=s.slice(1,4),m=[];if(this.qeConfig.enableGuidance&&i.length>0){let l=j(i[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});m.push(...l.slice(0,5))}let g=performance.now()-t;this.stats.totalRoutingLatency+=g,this.routingLatencies.push(g);let x={recommendedAgent:r.agent,confidence:r.score,alternatives:c.map(l=>({agent:l.agent,score:l.score})),domains:i,patterns:a,guidance:m,reasoning:r.reasoning.join("; "),latencyMs:g};return h($(e.includePatternGuidance,x,n.success?n.value:[]))}catch(i){return p(f(i))}}async recordOutcome(e){if(!this.qeConfig.enableLearning)return h(void 0);try{this.sqliteStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback),this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++;let t=this.sqliteStore.getPattern(e.patternId);if(t){let i=t.qeDomain,n=this.asymmetricEngine.computeConfidenceUpdate(t.confidence,e.success?"success":"failure",i);this.asymmetricEngine.shouldQuarantine(n,i).shouldQuarantine&&o.info("Pattern quarantined (asymmetric drop)",{name:t.name}),this.sqliteStore.updatePattern(e.patternId,{confidence:n}),await this.checkPatternPromotionWithCoherence(t)&&(this.sqliteStore.promotePattern(e.patternId),o.info("Pattern promoted to long-term",{name:t.name}))}return h(void 0)}catch(t){return p(f(t))}}async checkPatternPromotionWithCoherence(e){let t=_(e);if(!t.meetsUsageCriteria||!t.meetsQualityCriteria)return!1;if(this.coherenceService&&this.coherenceService.isInitialized()){let a=[...await this.getLongTermPatterns(),e].map(r=>({id:r.id,embedding:r.embedding||[],weight:r.confidence,metadata:{name:r.name,domain:r.qeDomain}})),s=await this.coherenceService.checkCoherence(a);if(s.energy>=(this.qeConfig.coherenceThreshold||.4))return o.info("Pattern promotion blocked due to coherence violation",{name:e.name,energy:s.energy}),s.contradictions&&s.contradictions.length>0&&o.info("Conflicts with existing patterns",{conflictingNodeIds:s.contradictions.map(r=>r.nodeIds).flat()}),!1}return!0}async getLongTermPatterns(){return this.sqliteStore.getPatterns({limit:1e3}).filter(t=>t.tier==="long-term")}shouldPromote(e){return e.tier==="short-term"&&e.successfulUses>=3&&e.successRate>=.7&&e.confidence>=.6}getQEGuidance(e){return U(e)}generateQEContext(e,t){return B(e,t||{})}checkQEAntiPatterns(e,t){return G(e,t)}async getQEStats(){let e=this.sqliteStore.getStats(),t=this.routingLatencies.percentile(95)||0,i={};for(let n of H)i[n]=e.byDomain[n]||0;return{totalPatterns:e.totalPatterns,byDomain:i,byTier:e.byTier,routingRequests:this.stats.routingRequests,avgRoutingLatencyMs:this.stats.routingRequests>0?this.stats.totalRoutingLatency/this.stats.routingRequests:0,p95RoutingLatencyMs:t,learningOutcomes:this.stats.learningOutcomes,patternSuccessRate:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0,embeddingCacheSize:0,transformerAvailable:N(),embeddingDimension:S(),sqliteDbPath:this.qeConfig.sqlite.dbPath||".agentic-qe/memory.db",asymmetricLearning:{failurePenaltyRatio:"10:1",quarantinedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!0).length,rehabilitatedPatterns:this.sqliteStore.getPatterns({limit:1e4}).filter(n=>n.quarantined===!1&&n.quarantinedAt).length,avgConfidenceDelta:this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes-.5:0}}}async storeLoopPattern(e){try{let t=await this.storeQEPattern({patternType:"anti-pattern",name:`loop-detection:${e.toolCallSignature}`,description:`Tool call loop detected for agent ${e.agentId} during ${e.taskType}. Steering: ${e.steeringUsed}. Resolved: ${e.resolved}`,template:{type:"prompt",content:e.steeringUsed,variables:[]},context:{tags:["anti-pattern","loop-detection","learning-optimization",e.taskType]}});return t.success?{success:!0,patternId:t.value.id}:{success:!1,error:t.error?.message??"Unknown error"}}catch(t){return{success:!1,error:I(t)}}}async recordPatternOutcome(e,t,i){let n=this.sqliteStore.getPattern(e);if(!n)return;let a=n.usageCount+1,s=t?n.successfulUses+1:n.successfulUses,r=s/a,c=.3,m=(1-c)*n.qualityScore+c*i,g=Math.min(1,.5+a*.05+r*.3);this.sqliteStore.updatePattern(e,{usageCount:a,successfulUses:s,successRate:r,qualityScore:m,confidence:g})}async checkPatternPromotion(e,t,i,n){let a=this.sqliteStore.getPattern(e);return a?a.tier==="short-term"?t>=3&&i>=.6&&n>=.5:a.tier==="long-term"?t>=10&&i>=.75&&n>=.7:!1:!1}async promotePattern(e){this.sqliteStore.promotePattern(e)}async demotePattern(e){let t=this.sqliteStore.getPattern(e);if(!t)return;let i=["short-term","working","long-term"],n=i.indexOf(t.tier);if(n>0){let a=i[n-1];this.sqliteStore.updatePattern(e,{tier:a}),o.info("Pattern demoted",{name:t.name,newTier:a})}}cleanupPatternIdMap(){if(!this.initialized)return 0;let e=0,t=this.sqliteStore.getPatterns({limit:1e5}),i=new Set(t.map(n=>n.id));for(let[n,a]of Array.from(this.patternIdMap.entries()))i.has(a)||(this.patternIdMap.delete(n),e++);return e>0&&o.info("Cleaned stale patternIdMap entries",{count:e}),e}removePatternFromHNSW(e){for(let[t,i]of Array.from(this.patternIdMap.entries()))if(i===e)return this.patternIdMap.delete(t),o.info("Removed pattern from HNSW mapping",{patternId:e}),!0;return!1}getMemoryStats(){return{patternIdMapSize:this.patternIdMap.size,routingLatenciesSize:this.routingLatencies.length,hnswIndexCount:this.hnswIndex?.getCurrentCount()??0}}async storeTrajectory(e){return this.sqliteStore.getDb().prepare(`
16
16
  INSERT OR REPLACE INTO qe_trajectories (
17
17
  id, task, agent, domain, started_at, ended_at, success, steps_json, metadata_json
18
18
  ) VALUES (?, ?, ?, ?, datetime('now'), datetime('now'), ?, ?, ?)
@@ -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.14.4");process.exit(0)}
2
- import{n as g}from"./chunk-NDPFGIMJ.js";var m={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},b=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let r={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.db?this.db.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(s=>s.name==="space_id"):!1,c=g()?.spaceId??this.config.embeddingSpaceId;if(!n||!c)return r;let o=this.config.stage<4,i=this.config.stage>=2;if(o&&this.db){let s=performance.now();try{let a=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);n?this.db.prepare(`
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.14.5");process.exit(0)}
2
+ import{n as g}from"./chunk-KIP6WZGV.js";var m={0:"sqlite-only",1:"hybrid",2:"dual-write-sqlite-primary",3:"dual-write-rvf-primary",4:"rvf-primary"},b=class{config;db=null;rvfStore=null;totalWrites=0;totalReads=0;rvfWriteFailures=0;rvfReadFailures=0;fallbacksUsed=0;sqliteLatencies=[];rvfLatencies=[];sqliteWriteLatencies=[];rvfWriteLatencies=[];constructor(e){this.config={rvfPath:".agentic-qe/patterns.rvf",dimensions:384,enableFallback:!0,...e}}setSqliteDb(e){this.db=e}setRvfStore(e){this.rvfStore=e}get stage(){return this.config.stage}setStage(e){this.config={...this.config,stage:e}}write(e,t){this.totalWrites++;let r={sqliteSuccess:!1,rvfSuccess:!1,stage:this.config.stage,fallbackUsed:!1},n=this.db?this.db.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(s=>s.name==="space_id"):!1,c=g()?.spaceId??this.config.embeddingSpaceId;if(!n||!c)return r;let o=this.config.stage<4,i=this.config.stage>=2;if(o&&this.db){let s=performance.now();try{let a=Buffer.from(t instanceof Float32Array?t.buffer:new Float32Array(t).buffer);n?this.db.prepare(`
3
3
  INSERT INTO qe_pattern_embeddings (pattern_id, embedding, dimension, model, space_id, created_at)
4
4
  VALUES (?, ?, ?, 'all-MiniLM-L6-v2', ?, datetime('now'))
5
5
  ON CONFLICT(pattern_id) DO UPDATE SET
@@ -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.14.4");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.14.5");process.exit(0)}
2
2
  var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};