agentic-qe 3.14.7 → 3.15.0

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 (428) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/auto-memory-hook.mjs +18 -9
  3. package/.claude/helpers/helpers.manifest.json +6 -5
  4. package/.claude/helpers/hook-handler.cjs +40 -12
  5. package/.claude/helpers/memory.cjs +86 -0
  6. package/.claude/helpers/router.cjs +105 -0
  7. package/.claude/helpers/session.cjs +166 -0
  8. package/.claude/helpers/statusline.cjs +73 -621
  9. package/.claude/skills/release/SKILL.md +6 -0
  10. package/.claude/skills/skills-manifest.json +1 -1
  11. package/CHANGELOG.md +275 -0
  12. package/README.md +143 -366
  13. package/assets/readme/credit-ruflo.svg +1 -0
  14. package/assets/readme/credit-ruvector.svg +1 -0
  15. package/assets/readme/project-header.svg +1 -0
  16. package/assets/readme/quality-loop.svg +1 -0
  17. package/assets/skills/skills-manifest.json +1 -1
  18. package/dist/adapters/a2a/notifications/retry-queue.js +10 -1
  19. package/dist/adapters/ag-ui/json-patch.js +14 -7
  20. package/dist/adapters/ag-ui/state-delta-cache.js +20 -12
  21. package/dist/adapters/claude-flow/pretrain-bridge.js +3 -2
  22. package/dist/agents/claim-verifier/verifiers/file-verifier.js +3 -2
  23. package/dist/cli/bundle.js +6 -6
  24. package/dist/cli/chunks/adapter-D7G5MIDQ.js +2 -0
  25. package/dist/cli/chunks/{agent-booster-wasm-AK2W76RG.js → agent-booster-wasm-GDHJ6QUN.js} +2 -2
  26. package/dist/cli/chunks/{agent-handler-MGZCWHIY.js → agent-handler-MPYYQ2RZ.js} +2 -2
  27. package/dist/cli/chunks/{agent-memory-branch-JZ54MCSP.js → agent-memory-branch-QBSHKLA2.js} +2 -2
  28. package/dist/cli/chunks/aqe-learning-engine-G6TUFGHC.js +2 -0
  29. package/dist/cli/chunks/{arena-YSWTKBCL.js → arena-UJE2FROF.js} +4 -4
  30. package/dist/cli/chunks/{arena-CUVH3V7H.js → arena-WIGSL37B.js} +2 -2
  31. package/dist/cli/chunks/{audit-LVU76QGA.js → audit-VT7Y2Z7V.js} +3 -3
  32. package/dist/cli/chunks/base-B45BOC7E.js +2 -0
  33. package/dist/cli/chunks/{better-sqlite3-DB3LOJQU.js → better-sqlite3-DSL7LFRK.js} +2 -2
  34. package/dist/cli/chunks/{brain-handler-SD63KOQ6.js → brain-handler-N3C2MDMK.js} +4 -4
  35. package/dist/cli/chunks/{branch-enumerator-4MNOPUC7.js → branch-enumerator-B6NSQ3PZ.js} +2 -2
  36. package/dist/cli/chunks/{browser-OLPNTWQE.js → browser-KQ3YNRGW.js} +2 -2
  37. package/dist/cli/chunks/browser-workflow-MIBU4XMV.js +2 -0
  38. package/dist/cli/chunks/{chunk-ZWEKAEEV.js → chunk-2ORTL5WG.js} +1 -1
  39. package/dist/cli/chunks/{chunk-KD2BLA5Y.js → chunk-2ZEV3O24.js} +1 -1
  40. package/dist/cli/chunks/{chunk-25P6JA6V.js → chunk-32YSI6OT.js} +1 -1
  41. package/dist/cli/chunks/{chunk-A5MA7A23.js → chunk-3DKYBHNA.js} +6 -6
  42. package/dist/cli/chunks/{chunk-JOZ47MV6.js → chunk-3Y24VTZ3.js} +1 -1
  43. package/dist/cli/chunks/{chunk-2G63VIJE.js → chunk-4BWDCUZZ.js} +1 -1
  44. package/dist/cli/chunks/{chunk-36VKMAMN.js → chunk-4DCDIKBX.js} +2 -2
  45. package/dist/cli/chunks/chunk-4EEY23JS.js +4 -0
  46. package/dist/cli/chunks/{chunk-BD7FEUN3.js → chunk-4FOKHGP5.js} +3 -3
  47. package/dist/cli/chunks/{chunk-MQZ53OR3.js → chunk-4OQSAUKR.js} +2 -2
  48. package/dist/cli/chunks/{chunk-EYXE2XKP.js → chunk-4YPL3OXS.js} +2 -2
  49. package/dist/cli/chunks/{chunk-PCJQCEBA.js → chunk-5DJGP4TA.js} +2 -2
  50. package/dist/cli/chunks/{chunk-RC2A4JZ5.js → chunk-5KN4QL3G.js} +2 -2
  51. package/dist/cli/chunks/chunk-5LN7FQZI.js +2 -0
  52. package/dist/cli/chunks/{chunk-LU2EDWQK.js → chunk-5PNRUMRV.js} +2 -2
  53. package/dist/cli/chunks/{chunk-YRHTQZU4.js → chunk-62IEVKN3.js} +2 -2
  54. package/dist/cli/chunks/{chunk-DOBKEXMJ.js → chunk-6GTIJNRO.js} +1 -1
  55. package/dist/cli/chunks/{chunk-O5V7RHVG.js → chunk-6MN4L6BS.js} +2 -2
  56. package/dist/cli/chunks/{chunk-6PJPQGF4.js → chunk-7D6NVIGP.js} +6 -6
  57. package/dist/cli/chunks/{chunk-B2YGVSOP.js → chunk-7JABIXP3.js} +2 -2
  58. package/dist/cli/chunks/chunk-7JC3LHA6.js +742 -0
  59. package/dist/cli/chunks/{chunk-P7XSPP5D.js → chunk-7WUHVGGT.js} +2 -2
  60. package/dist/cli/chunks/{chunk-RKI3IQKQ.js → chunk-A37YYHUD.js} +3 -3
  61. package/dist/cli/chunks/{chunk-UBJG3IHT.js → chunk-AAQNRZKT.js} +2 -2
  62. package/dist/cli/chunks/{chunk-ND4QTZOL.js → chunk-AGYPPPXR.js} +2 -2
  63. package/dist/cli/chunks/chunk-AIE6OKCD.js +2 -0
  64. package/dist/cli/chunks/{chunk-JHJUSSAU.js → chunk-ANUZGOLQ.js} +2 -2
  65. package/dist/cli/chunks/{chunk-RLW25X66.js → chunk-AQZSF32Y.js} +2 -2
  66. package/dist/cli/chunks/{chunk-OIDWDGLG.js → chunk-ATXAMGVE.js} +2 -2
  67. package/dist/cli/chunks/{chunk-GLGKQX2V.js → chunk-AV3RX2L5.js} +2 -2
  68. package/dist/cli/chunks/{chunk-7QYOTUOX.js → chunk-AW5OWYQ4.js} +2 -2
  69. package/dist/cli/chunks/{chunk-B4I43GE2.js → chunk-B6QTNTCU.js} +2 -2
  70. package/dist/cli/chunks/{chunk-P2UPYSDJ.js → chunk-BAPMEDWC.js} +1 -1
  71. package/dist/cli/chunks/{chunk-Y6AKKQIQ.js → chunk-BH2SQQ2N.js} +1 -1
  72. package/dist/cli/chunks/{chunk-O6MO5KMR.js → chunk-C6M27NQE.js} +2 -2
  73. package/dist/cli/chunks/{chunk-XBYQ2BS4.js → chunk-CMYZWIXS.js} +2 -2
  74. package/dist/cli/chunks/{chunk-DYTQHRUS.js → chunk-CZWWC7GC.js} +1 -1
  75. package/dist/cli/chunks/{chunk-WF6UISKW.js → chunk-D7NOHASX.js} +4 -4
  76. package/dist/cli/chunks/{chunk-H5RQPO3X.js → chunk-DGRE6ZAA.js} +2 -2
  77. package/dist/cli/chunks/{chunk-53BXTTRO.js → chunk-DSGRXW6K.js} +3 -3
  78. package/dist/cli/chunks/{chunk-A2VUCUTT.js → chunk-DXA7RLYU.js} +2 -2
  79. package/dist/cli/chunks/{chunk-GVVFTFMB.js → chunk-DZHIE5UW.js} +2 -2
  80. package/dist/cli/chunks/{chunk-MZB2UV2O.js → chunk-EBK6CUBD.js} +1 -1
  81. package/dist/cli/chunks/{chunk-WIH522AP.js → chunk-EPEKEUCF.js} +1 -1
  82. package/dist/cli/chunks/{chunk-SRPLERER.js → chunk-EQ4SDE4L.js} +25 -25
  83. package/dist/cli/chunks/{chunk-EGOIIUBD.js → chunk-EZPWSS3B.js} +2 -2
  84. package/dist/cli/chunks/{chunk-EADSQN5T.js → chunk-F76SYOBT.js} +1 -1
  85. package/dist/cli/chunks/{chunk-XL5KIYE3.js → chunk-F7JVDLOI.js} +2 -2
  86. package/dist/cli/chunks/{chunk-QGOWNVVG.js → chunk-FCSETOWZ.js} +4 -4
  87. package/dist/cli/chunks/{chunk-A3DK3XNZ.js → chunk-FFE4XAQA.js} +1 -1
  88. package/dist/cli/chunks/{chunk-7EZ2Z2CK.js → chunk-FPTZP7W5.js} +1 -1
  89. package/dist/cli/chunks/{chunk-GV4DYPJP.js → chunk-FTFIA4I5.js} +2 -2
  90. package/dist/cli/chunks/{chunk-SM2YJ2AL.js → chunk-FTS6NGBP.js} +2 -2
  91. package/dist/cli/chunks/{chunk-XWYELBZS.js → chunk-FZ3TQAPW.js} +1 -1
  92. package/dist/cli/chunks/{chunk-HPWWYT67.js → chunk-G35KP72N.js} +2 -2
  93. package/dist/cli/chunks/{chunk-HZY42OVU.js → chunk-GCHDMO5V.js} +2 -2
  94. package/dist/cli/chunks/{chunk-23CX7JNL.js → chunk-GRN47ANK.js} +2 -2
  95. package/dist/cli/chunks/{chunk-HYFQUWNB.js → chunk-GV7P5JYF.js} +2 -2
  96. package/dist/cli/chunks/{chunk-YO4ESCB4.js → chunk-GX5RFGW2.js} +1 -1
  97. package/dist/cli/chunks/{chunk-TFK2AYIN.js → chunk-H77AUJNW.js} +2 -2
  98. package/dist/cli/chunks/{chunk-NBLDBVAW.js → chunk-HBIV7PQH.js} +1 -1
  99. package/dist/cli/chunks/{chunk-VYDVI6FZ.js → chunk-HOPXHZA3.js} +2 -2
  100. package/dist/cli/chunks/{chunk-HYOPJHHW.js → chunk-I3BH3KIF.js} +1 -1
  101. package/dist/cli/chunks/{chunk-ZELWDJXT.js → chunk-ILKMNDUM.js} +2 -2
  102. package/dist/cli/chunks/{chunk-C3FXFU2T.js → chunk-IRHBR56R.js} +1 -1
  103. package/dist/cli/chunks/{chunk-FYPX5WBJ.js → chunk-ISAMM7QA.js} +1 -1
  104. package/dist/cli/chunks/{chunk-V5AK56DA.js → chunk-ISGFAMHZ.js} +2 -2
  105. package/dist/cli/chunks/{chunk-KUHLTVWC.js → chunk-J46XGXPS.js} +1 -1
  106. package/dist/cli/chunks/{chunk-ZS4XVJGV.js → chunk-J4XCBOPA.js} +2 -2
  107. package/dist/cli/chunks/{chunk-BEFTQVEW.js → chunk-JIWMFLHV.js} +2 -2
  108. package/dist/cli/chunks/{chunk-UFSVUBTR.js → chunk-JJ7WAU4I.js} +2 -2
  109. package/dist/cli/chunks/{chunk-WOV6XI3A.js → chunk-JLPNYHJJ.js} +1 -1
  110. package/dist/cli/chunks/{chunk-77QZHIVX.js → chunk-JO2YLIZH.js} +2 -2
  111. package/dist/cli/chunks/{chunk-J7AQZLIH.js → chunk-JSYNSJDQ.js} +4 -4
  112. package/dist/cli/chunks/{chunk-OAZX6WFU.js → chunk-JYRBOSOF.js} +2 -2
  113. package/dist/cli/chunks/{chunk-EJ6MMYLK.js → chunk-KEZ4PXVF.js} +1 -1
  114. package/dist/cli/chunks/{chunk-N5XOXPHZ.js → chunk-KLGFEHEN.js} +2 -2
  115. package/dist/cli/chunks/{chunk-7MIOK72I.js → chunk-KU4WLKDK.js} +7 -7
  116. package/dist/cli/chunks/{chunk-Z4Q5PCRZ.js → chunk-KUTMQBV4.js} +4 -4
  117. package/dist/cli/chunks/{chunk-VW6FRMLW.js → chunk-L6PUBB6L.js} +2 -2
  118. package/dist/cli/chunks/{chunk-OEPNNLR4.js → chunk-LDJ5DZT5.js} +1 -1
  119. package/dist/cli/chunks/{chunk-QQFQDEUE.js → chunk-LLS6JYPN.js} +2 -2
  120. package/dist/cli/chunks/{chunk-UOI6ULCH.js → chunk-LPCFIFZF.js} +2 -2
  121. package/dist/cli/chunks/{chunk-6RD44SCE.js → chunk-M5EKZA7Q.js} +1 -1
  122. package/dist/cli/chunks/chunk-MEYSIVMP.js +2 -0
  123. package/dist/cli/chunks/{chunk-YMW57PEL.js → chunk-MFGLRMO4.js} +1 -1
  124. package/dist/cli/chunks/{chunk-BE4KALTE.js → chunk-MM57SD2F.js} +1 -1
  125. package/dist/cli/chunks/{chunk-FW4DJ4FJ.js → chunk-MO3QXLF2.js} +1 -1
  126. package/dist/cli/chunks/{chunk-QFETNCNN.js → chunk-MRIZY6HB.js} +2 -2
  127. package/dist/cli/chunks/{chunk-RT6O2HW2.js → chunk-N2MDNEF7.js} +2 -2
  128. package/dist/cli/chunks/{chunk-UA7TDVL7.js → chunk-N5ZHIQAV.js} +4 -4
  129. package/dist/cli/chunks/{chunk-Q6NTEICT.js → chunk-NZ556KZN.js} +2 -2
  130. package/dist/cli/chunks/{chunk-CVOQ6ESD.js → chunk-O5AUOBGU.js} +2 -2
  131. package/dist/cli/chunks/{chunk-5D7ZFWDS.js → chunk-OBSX3I4Y.js} +2 -2
  132. package/dist/cli/chunks/{chunk-NOHWJOBS.js → chunk-OLD2CIDI.js} +1 -1
  133. package/dist/cli/chunks/{chunk-5U6N4V5M.js → chunk-OTJ22IO2.js} +4 -4
  134. package/dist/cli/chunks/{chunk-5GFKTJ65.js → chunk-OYVDTD3A.js} +2 -2
  135. package/dist/cli/chunks/{chunk-LY7MFGBD.js → chunk-P2PPJUGD.js} +147 -150
  136. package/dist/cli/chunks/{chunk-OZGIOKEA.js → chunk-P4FRYNHL.js} +1 -1
  137. package/dist/cli/chunks/{chunk-X7ADKL7T.js → chunk-P4WE6VRR.js} +2 -2
  138. package/dist/cli/chunks/{chunk-ZUB5YOCM.js → chunk-P725KXHX.js} +2 -2
  139. package/dist/cli/chunks/{chunk-74IOEOMH.js → chunk-P7MNF2SK.js} +2 -2
  140. package/dist/cli/chunks/{chunk-TXSPBLBT.js → chunk-PJU5HVWV.js} +2 -2
  141. package/dist/cli/chunks/{chunk-MT7UNBZ7.js → chunk-PN3FYSQ6.js} +2 -2
  142. package/dist/cli/chunks/{chunk-F2OPFVQH.js → chunk-PPFW3H7E.js} +1 -1
  143. package/dist/cli/chunks/{chunk-IEJ7ZV3M.js → chunk-Q4RCUCHD.js} +1 -1
  144. package/dist/cli/chunks/{chunk-IAENZ2DR.js → chunk-QRALXNNX.js} +2 -2
  145. package/dist/cli/chunks/{chunk-AJUBT4NP.js → chunk-QVX22EIM.js} +3 -3
  146. package/dist/cli/chunks/chunk-R6CZCMKD.js +2 -0
  147. package/dist/cli/chunks/chunk-ROK5YQ5P.js +3 -0
  148. package/dist/cli/chunks/{chunk-ON2UTP2U.js → chunk-S2GNFAOC.js} +2 -2
  149. package/dist/cli/chunks/{chunk-HXXHMLJ5.js → chunk-S644OORE.js} +1 -1
  150. package/dist/cli/chunks/{chunk-XYLQZWF6.js → chunk-S7CROKX4.js} +2 -2
  151. package/dist/cli/chunks/{chunk-T77GZF4B.js → chunk-S7QUHLXV.js} +1 -1
  152. package/dist/cli/chunks/{chunk-RDGPXENG.js → chunk-UGYXUPGN.js} +2 -2
  153. package/dist/cli/chunks/{chunk-QVH5Y7AP.js → chunk-URRPJ3M7.js} +1 -1
  154. package/dist/cli/chunks/{chunk-AEUEMVJK.js → chunk-URUOTHPO.js} +2 -2
  155. package/dist/cli/chunks/{chunk-VXKWNRGA.js → chunk-VCYOFWMG.js} +2 -2
  156. package/dist/cli/chunks/{chunk-6EGS77BB.js → chunk-VQVFGFYK.js} +1 -1
  157. package/dist/cli/chunks/{chunk-NHUGHAY6.js → chunk-VT5SMBEM.js} +1 -1
  158. package/dist/cli/chunks/{chunk-ROVZSZCS.js → chunk-VTGRGYY4.js} +3 -3
  159. package/dist/cli/chunks/{chunk-QPLSYEWJ.js → chunk-VWCFXCSV.js} +2 -2
  160. package/dist/cli/chunks/{chunk-ENK44A6Q.js → chunk-VY4557VF.js} +2 -2
  161. package/dist/cli/chunks/{chunk-5FSLMYAC.js → chunk-VYERAOQL.js} +2 -2
  162. package/dist/cli/chunks/{chunk-EIGRV3J6.js → chunk-W6H2SOIK.js} +2 -2
  163. package/dist/cli/chunks/{chunk-CBONQM5D.js → chunk-WBR4VRQE.js} +2 -2
  164. package/dist/cli/chunks/{chunk-JZT7BU44.js → chunk-WDV6CBED.js} +2 -2
  165. package/dist/cli/chunks/{chunk-G367W7XR.js → chunk-WO7NPGUD.js} +19 -19
  166. package/dist/cli/chunks/{chunk-4INST4ZL.js → chunk-WPOYFV4X.js} +1 -1
  167. package/dist/cli/chunks/{chunk-3M7J4U74.js → chunk-WPSGMTI4.js} +4 -4
  168. package/dist/cli/chunks/{chunk-RKUAWQOF.js → chunk-WQMXQO3O.js} +2 -2
  169. package/dist/cli/chunks/{chunk-Q3NSU24F.js → chunk-WR54SKKL.js} +2 -2
  170. package/dist/cli/chunks/{chunk-UYUJT6QO.js → chunk-X4OESN7M.js} +2 -2
  171. package/dist/cli/chunks/{chunk-ZUOVNFXK.js → chunk-X5RELRY7.js} +2 -2
  172. package/dist/cli/chunks/{chunk-BLG7SH4A.js → chunk-X7JEBPEW.js} +1 -1
  173. package/dist/cli/chunks/{chunk-FSSR6WBE.js → chunk-XEABMIUH.js} +2 -2
  174. package/dist/cli/chunks/{chunk-ONR2NXXD.js → chunk-XELFJC77.js} +3 -3
  175. package/dist/cli/chunks/{chunk-MM56VPNE.js → chunk-XPUY3ZKD.js} +3 -3
  176. package/dist/cli/chunks/{chunk-QUORH2MG.js → chunk-XZDPR6I2.js} +8 -8
  177. package/dist/cli/chunks/{chunk-MZMG6CUJ.js → chunk-Y63DADOR.js} +2 -2
  178. package/dist/cli/chunks/{chunk-CQNMGK6Y.js → chunk-YFRZVNE4.js} +2 -2
  179. package/dist/cli/chunks/{chunk-3QJU4Q4R.js → chunk-YIDZ3TEN.js} +2 -2
  180. package/dist/cli/chunks/{chunk-4EKV7PHB.js → chunk-Z6CRROLU.js} +2 -2
  181. package/dist/cli/chunks/{chunk-IWFFO6VT.js → chunk-ZPH2YT3J.js} +2 -2
  182. package/dist/cli/chunks/{chunk-PYKY22GC.js → chunk-ZV7LJPSI.js} +5 -5
  183. package/dist/cli/chunks/chunk-ZXIIB3QE.js +2 -0
  184. package/dist/cli/chunks/ci-63JINRNB.js +82 -0
  185. package/dist/cli/chunks/{ci-output-RLS32FUY.js → ci-output-CRFWLUAA.js} +2 -2
  186. package/dist/cli/chunks/{circuit-breaker-MRCC7WCM.js → circuit-breaker-PJLG3WYL.js} +2 -2
  187. package/dist/cli/chunks/{claude-flow-setup-LIZCEKDF.js → claude-flow-setup-UKHSQMJU.js} +2 -2
  188. package/dist/cli/chunks/client-A4FTITK3.js +2 -0
  189. package/dist/cli/chunks/{cline-installer-T7H6R2RC.js → cline-installer-PYQ27AS3.js} +2 -2
  190. package/dist/cli/chunks/{code-XMBLI7OF.js → code-K7VGLZ3W.js} +3 -3
  191. package/dist/cli/chunks/{code-index-extractor-QS7BYLEX.js → code-index-extractor-NNWAVWSL.js} +2 -2
  192. package/dist/cli/chunks/{codex-installer-6PGT5FM6.js → codex-installer-U4VJIKRN.js} +2 -2
  193. package/dist/cli/chunks/{completions-2A3WRXY2.js → completions-DOCI3P4W.js} +2 -2
  194. package/dist/cli/chunks/{complexity-analyzer-23HOOGJ7.js → complexity-analyzer-RFW2QRFR.js} +2 -2
  195. package/dist/cli/chunks/{continuedev-installer-4FSF7B3N.js → continuedev-installer-S5WXXOBU.js} +2 -2
  196. package/dist/cli/chunks/{copilot-installer-A5GRQQUU.js → copilot-installer-AAQ6YLVJ.js} +2 -2
  197. package/dist/cli/chunks/core-handlers-FO3QTNWI.js +2 -0
  198. package/dist/cli/chunks/{cost-tracker-Z4STQ5VB.js → cost-tracker-R4VOHTWQ.js} +2 -2
  199. package/dist/cli/chunks/{coverage-NUPP6KZZ.js → coverage-P54HPCLV.js} +3 -3
  200. package/dist/cli/chunks/cross-domain-router-LIV6SRWF.js +2 -0
  201. package/dist/cli/chunks/{cursor-installer-FVJ7ROPJ.js → cursor-installer-VHBWZE5A.js} +2 -2
  202. package/dist/cli/chunks/{daemon-D662EX5N.js → daemon-BTRSWNB4.js} +4 -4
  203. package/dist/cli/chunks/{daemon-7ZZA2MMN.js → daemon-JLH5TTWZ.js} +4 -4
  204. package/dist/cli/chunks/{dag-attention-scheduler-IB4TQ2KA.js → dag-attention-scheduler-5Z6DCRFK.js} +2 -2
  205. package/dist/cli/chunks/{detect-LGLBZN4I.js → detect-NWGASRJJ.js} +2 -2
  206. package/dist/cli/chunks/{dist-node-Z3OL42YE.js → dist-node-XMNNSEFJ.js} +2 -2
  207. package/dist/cli/chunks/{domain-handler-L3CLNL7U.js → domain-handler-BWVBZTNR.js} +2 -2
  208. package/dist/cli/chunks/{domain-plugins-GQ3V5X6L.js → domain-plugins-YAD4USA4.js} +2 -2
  209. package/dist/cli/chunks/domain-transfer-Z3MRPZEZ.js +2 -0
  210. package/dist/cli/chunks/dream-DNLGHYXY.js +2 -0
  211. package/dist/cli/chunks/{embed-and-insert-pattern-UGD6USYH.js → embed-and-insert-pattern-5CCO45WC.js} +2 -2
  212. package/dist/cli/chunks/{eval-3B7UIYGY.js → eval-JEMLTGY4.js} +2 -2
  213. package/dist/cli/chunks/{experience-capture-middleware-3RQ4NYY3.js → experience-capture-middleware-FKVYBBAN.js} +4 -4
  214. package/dist/cli/chunks/{fast-paths-QOSAEPYD.js → fast-paths-TFL32H3C.js} +2 -2
  215. package/dist/cli/chunks/{feature-flags-3S5TH6P4.js → feature-flags-CNGAUUMT.js} +2 -2
  216. package/dist/cli/chunks/{feature-flags-TLF4NKOH.js → feature-flags-OHGD2NCW.js} +2 -2
  217. package/dist/cli/chunks/{file-discovery-AEVMJRNB.js → file-discovery-IHGDYW34.js} +2 -2
  218. package/dist/cli/chunks/{fleet-E6WTXWFL.js → fleet-OGTSDGJ2.js} +4 -4
  219. package/dist/cli/chunks/{gnn-wrapper-MCKH3AUU.js → gnn-wrapper-QYTTKNCE.js} +2 -2
  220. package/dist/cli/chunks/{heartbeat-handler-U7XENHRR.js → heartbeat-handler-R5OD2SKN.js} +4 -4
  221. package/dist/cli/chunks/heartbeat-scheduler-DL4LXXJF.js +2 -0
  222. package/dist/cli/chunks/hnsw-adapter-Y64M43J4.js +2 -0
  223. package/dist/cli/chunks/hnsw-index-5V6DDMTA.js +2 -0
  224. package/dist/cli/chunks/{hnsw-legacy-bridge-5GW4SAEI.js → hnsw-legacy-bridge-ULJWYXBQ.js} +2 -2
  225. package/dist/cli/chunks/{hnswlib-node-7BLZBK5T.js → hnswlib-node-SYKJXGE2.js} +2 -2
  226. package/dist/cli/chunks/{hooks-F3O2SB6H.js → hooks-XAJXPXTU.js} +10 -10
  227. package/dist/cli/chunks/hybrid-backend-JWT2V4FQ.js +2 -0
  228. package/dist/cli/chunks/{hypergraph-engine-PV4EKXHB.js → hypergraph-engine-GIBPGW4N.js} +2 -2
  229. package/dist/cli/chunks/{hypergraph-handler-VOWO5ZTW.js → hypergraph-handler-ENFK6IDN.js} +3 -3
  230. package/dist/cli/chunks/impact-analyzer-XUZQSZZC.js +2 -0
  231. package/dist/cli/chunks/{init-handler-ENJ5ONJX.js → init-handler-CSA62LGT.js} +6 -6
  232. package/dist/cli/chunks/init-wizard-KDJKHEPN.js +2 -0
  233. package/dist/cli/chunks/kernel-MUDYPGFR.js +2 -0
  234. package/dist/cli/chunks/{kilocode-installer-HNNJOOPE.js → kilocode-installer-YXFIRTSA.js} +2 -2
  235. package/dist/cli/chunks/{kiro-installer-UZBIQ3IC.js → kiro-installer-JW3BG2MQ.js} +2 -2
  236. package/dist/cli/chunks/knowledge-graph-GR52N7PU.js +2 -0
  237. package/dist/cli/chunks/{learning-YMLCVFUT.js → learning-BDBZ7ZVG.js} +4 -4
  238. package/dist/cli/chunks/{llm-router-YWTARCCT.js → llm-router-CCX2DYTC.js} +4 -4
  239. package/dist/cli/chunks/llm-router-service-QL6LVKZ4.js +2 -0
  240. package/dist/cli/chunks/{load-DKE3F3IP.js → load-UJTTEOOK.js} +2 -2
  241. package/dist/cli/chunks/load-test-76V75WZ5.js +2 -0
  242. package/dist/cli/chunks/{mcp-5PSGIUCW.js → mcp-2NAJYREC.js} +2 -2
  243. package/dist/cli/chunks/{memory-3L3O6JMM.js → memory-C3UQSN5F.js} +5 -5
  244. package/dist/cli/chunks/memory-backend-SMQRS5QN.js +2 -0
  245. package/dist/cli/chunks/memory-handlers-ESFIJENU.js +2 -0
  246. package/dist/cli/chunks/{multi-model-executor-AEEO7IA4.js → multi-model-executor-SIHSHAD7.js} +2 -2
  247. package/dist/cli/chunks/{opencode-installer-ABBO355U.js → opencode-installer-KDYHUGPG.js} +2 -2
  248. package/dist/cli/chunks/{orchestrator-E36Q7MKE.js → orchestrator-MJHIQEHD.js} +6 -6
  249. package/dist/cli/chunks/pattern-null-store-MWAJMOYU.js +2 -0
  250. package/dist/cli/chunks/{pattern-usage-recorder-H4XKSID4.js → pattern-usage-recorder-OLBE4UIF.js} +2 -2
  251. package/dist/cli/chunks/{pipeline-BGFEHXIN.js → pipeline-IOK2CV3U.js} +2 -2
  252. package/dist/cli/chunks/{platform-GK7ZVDJI.js → platform-53JQ7JXN.js} +2 -2
  253. package/dist/cli/chunks/{plugin-CAH2CKI6.js → plugin-L5SDIWDI.js} +2 -2
  254. package/dist/cli/chunks/{prime-radiant-advanced-wasm-M5EYRONA.js → prime-radiant-advanced-wasm-2DS67JFS.js} +2 -2
  255. package/dist/cli/chunks/{project-root-BSNZC243.js → project-root-LQMOFO2Z.js} +2 -2
  256. package/dist/cli/chunks/protocol-executor-32X3GAJT.js +2 -0
  257. package/dist/cli/chunks/{protocol-handler-JDSSC2SF.js → protocol-handler-NXG2M43B.js} +2 -2
  258. package/dist/cli/chunks/{prove-ANPTOZJE.js → prove-7K7PFSSX.js} +2 -2
  259. package/dist/cli/chunks/qe-reasoning-bank-KAFV3TGI.js +2 -0
  260. package/dist/cli/chunks/{quality-SXWGYRQR.js → quality-ATILUGMJ.js} +2 -2
  261. package/dist/cli/chunks/quality-gate-MPZMDPIZ.js +7 -0
  262. package/dist/cli/chunks/queen-coordinator-L3SODGRX.js +2 -0
  263. package/dist/cli/chunks/{real-embeddings-WSRYAOZM.js → real-embeddings-VZN3KIAI.js} +2 -2
  264. package/dist/cli/chunks/{ref-validation-AZ3LRWEK.js → ref-validation-EUATPVXX.js} +2 -2
  265. package/dist/cli/chunks/{roocode-installer-2QKGFIEU.js → roocode-installer-7M2GOUNZ.js} +2 -2
  266. package/dist/cli/chunks/router-DDCSSXYQ.js +2 -0
  267. package/dist/cli/chunks/routing-feedback-RFASKYCD.js +2 -0
  268. package/dist/cli/chunks/{routing-handler-UYDC5MMD.js → routing-handler-VWANE652.js} +2 -2
  269. package/dist/cli/chunks/{ruvector-commands-QXADPVEY.js → ruvector-commands-B2YIPGOV.js} +2 -2
  270. package/dist/cli/chunks/rvf-dual-writer-HCIF2G56.js +2 -0
  271. package/dist/cli/chunks/rvf-migration-adapter-UVAHQ7SV.js +2 -0
  272. package/dist/cli/chunks/{rvf-migration-coordinator-GD4NBFKT.js → rvf-migration-coordinator-RQXOQJ5T.js} +2 -2
  273. package/dist/cli/chunks/rvf-native-adapter-F2I5FFHK.js +2 -0
  274. package/dist/cli/chunks/{rvf-store-integrity-7SXG66IL.js → rvf-store-integrity-7P5YDXRH.js} +2 -2
  275. package/dist/cli/chunks/safe-db-6ZAA4S23.js +2 -0
  276. package/dist/cli/chunks/schedule-SM5Q6UVP.js +2 -0
  277. package/dist/cli/chunks/scheduler-4EYP4EZ6.js +2 -0
  278. package/dist/cli/chunks/{security-YKB622PK.js → security-VJ7TVSQF.js} +3 -3
  279. package/dist/cli/chunks/{shared-rvf-adapter-KMLAV7JK.js → shared-rvf-adapter-63NXQFBX.js} +2 -2
  280. package/dist/cli/chunks/{shared-rvf-dual-writer-OYY27DFV.js → shared-rvf-dual-writer-JQRP7P5A.js} +2 -2
  281. package/dist/cli/chunks/sqlite-persistence-KLN2K266.js +2 -0
  282. package/dist/cli/chunks/{standalone-memory-2DOABVLC.js → standalone-memory-WJ72PH5P.js} +2 -2
  283. package/dist/cli/chunks/{status-handler-EXRKETV7.js → status-handler-G72ZSLAX.js} +2 -2
  284. package/dist/cli/chunks/{structural-health-2SKK6DU6.js → structural-health-HYBGP4BD.js} +2 -2
  285. package/dist/cli/chunks/{sync-DQ2YUNI6.js → sync-5YMZZIF4.js} +2 -2
  286. package/dist/cli/chunks/{sync-UW7SX7GO.js → sync-O5FQAHT7.js} +2 -2
  287. package/dist/cli/chunks/{task-handler-LYQ6WYUY.js → task-handler-E6IFNHZG.js} +2 -2
  288. package/dist/cli/chunks/{task-handlers-DIJO232S.js → task-handlers-P3GC2L5L.js} +3 -3
  289. package/dist/cli/chunks/{test-WRHZMUCW.js → test-OU6ERW67.js} +6 -6
  290. package/dist/cli/chunks/{test-scheduling-HI23RXFK.js → test-scheduling-3HY4I3HY.js} +7 -7
  291. package/dist/cli/chunks/{token-bootstrap-23SA6SWZ.js → token-bootstrap-A5QA4CWK.js} +2 -2
  292. package/dist/cli/chunks/{token-usage-M7RRDPXO.js → token-usage-MUNQVPFT.js} +2 -2
  293. package/dist/cli/chunks/{transformers-4TC35KKS.js → transformers-IEO25W5V.js} +2 -2
  294. package/dist/cli/chunks/{tree-sitter-wasm-parser-F4LTKAWD.js → tree-sitter-wasm-parser-T2EQHEAY.js} +2 -2
  295. package/dist/cli/chunks/{types-NBXV6LXQ.js → types-ODCPGCID.js} +2 -2
  296. package/dist/cli/chunks/unified-memory-B5IA2KKQ.js +2 -0
  297. package/dist/cli/chunks/unified-memory-hnsw-YF74LL3Z.js +2 -0
  298. package/dist/cli/chunks/unified-persistence-VZMGNGWY.js +2 -0
  299. package/dist/cli/chunks/{upgrade-4BGOU5RM.js → upgrade-4DN6EIW2.js} +2 -2
  300. package/dist/cli/chunks/{validate-EDWAR63H.js → validate-TBNAPDE3.js} +2 -2
  301. package/dist/cli/chunks/{validate-swarm-VI72CPR7.js → validate-swarm-ZN7XXUY4.js} +2 -2
  302. package/dist/cli/chunks/visual-security-ZV3BLLSH.js +2 -0
  303. package/dist/cli/chunks/{web-tree-sitter-Y5XBRQXF.js → web-tree-sitter-DWAWVD2X.js} +2 -2
  304. package/dist/cli/chunks/{windsurf-installer-VEX23WAF.js → windsurf-installer-U6EROS5S.js} +2 -2
  305. package/dist/cli/chunks/{witness-chain-3YNL6YGY.js → witness-chain-EQEJS2P4.js} +2 -2
  306. package/dist/cli/chunks/witness-chain-OA24MQWX.js +2 -0
  307. package/dist/cli/chunks/{witness-chain-repair-MJZGZRWT.js → witness-chain-repair-KBXDRXS3.js} +2 -2
  308. package/dist/cli/chunks/{witness-chain-verifier-TTJYXTBE.js → witness-chain-verifier-HSQGZ4R4.js} +2 -2
  309. package/dist/cli/chunks/{witness-key-manager-EM6YXYOY.js → witness-key-manager-RAODG73T.js} +2 -2
  310. package/dist/cli/chunks/{workflow-2RBDOM7V.js → workflow-KNFJNNKG.js} +4 -4
  311. package/dist/cli/chunks/workflow-orchestrator-IMX2LSVE.js +2 -0
  312. package/dist/cli/chunks/{wrappers-5OTAVVOV.js → wrappers-NIJBA22T.js} +2 -2
  313. package/dist/cli/commands/ci.js +17 -6
  314. package/dist/cli/commands/quality-gate.js +6 -1
  315. package/dist/cli/index.js +7 -2
  316. package/dist/cli/process-store-cleanup.d.ts +7 -0
  317. package/dist/cli/process-store-cleanup.js +27 -0
  318. package/dist/cli/utils/ci-config.d.ts +3 -3
  319. package/dist/cli/utils/ci-config.js +202 -68
  320. package/dist/cli/utils/workflow-parser.js +73 -57
  321. package/dist/domains/code-intelligence/services/metric-collector/test-counter.d.ts +1 -1
  322. package/dist/domains/code-intelligence/services/metric-collector/test-counter.js +17 -15
  323. package/dist/domains/quality-assessment/quality-evidence.d.ts +3 -1
  324. package/dist/domains/quality-assessment/quality-evidence.js +7 -2
  325. package/dist/domains/test-execution/services/retry-handler.js +38 -16
  326. package/dist/domains/test-execution/services/test-executor.d.ts +3 -3
  327. package/dist/domains/test-execution/services/test-executor.js +66 -22
  328. package/dist/governance/ab-benchmarking.d.ts +5 -1
  329. package/dist/governance/ab-benchmarking.js +64 -29
  330. package/dist/init/fleet-integration.js +3 -2
  331. package/dist/init/init-wizard-steps.js +3 -2
  332. package/dist/init/phases/06-code-intelligence.js +6 -4
  333. package/dist/integrations/ruvector/sona-persistence.d.ts +1 -0
  334. package/dist/integrations/ruvector/sona-persistence.js +74 -20
  335. package/dist/integrations/ruvector/sona-wrapper.d.ts +2 -0
  336. package/dist/integrations/ruvector/sona-wrapper.js +13 -0
  337. package/dist/kernel/memory-backend.js +5 -4
  338. package/dist/kernel/unified-memory.js +3 -2
  339. package/dist/learning/aqe-learning-engine.js +3 -2
  340. package/dist/mcp/bundle.js +474 -471
  341. package/dist/mcp/connection-pool.d.ts +2 -0
  342. package/dist/mcp/connection-pool.js +13 -2
  343. package/dist/mcp/handlers/memory-handlers.d.ts +1 -0
  344. package/dist/mcp/handlers/memory-handlers.js +16 -6
  345. package/dist/mcp/protocol-server.js +29 -8
  346. package/dist/mcp/security/rate-limiter.d.ts +1 -0
  347. package/dist/mcp/security/rate-limiter.js +22 -5
  348. package/dist/mcp/services/session-store.js +17 -17
  349. package/dist/mcp/tools/planning/goap-status.d.ts +2 -0
  350. package/dist/mcp/tools/planning/goap-status.js +8 -2
  351. package/dist/mcp/types.d.ts +2 -0
  352. package/dist/optimization/session-cache.js +13 -11
  353. package/dist/planning/goap-planner.d.ts +3 -0
  354. package/dist/planning/goap-planner.js +80 -37
  355. package/dist/plugins/cache.js +10 -3
  356. package/dist/shared/embeddings/embedding-cache.js +5 -5
  357. package/dist/shared/embeddings/nomic-embedder.js +17 -7
  358. package/dist/shared/embeddings/ollama-client.js +5 -3
  359. package/dist/shared/git/git-analyzer.js +31 -30
  360. package/dist/shared/http/http-client.js +20 -13
  361. package/dist/shared/io/file-reader.js +11 -8
  362. package/dist/shared/llm/cache.d.ts +8 -29
  363. package/dist/shared/llm/cache.js +12 -11
  364. package/dist/shared/llm/cost-tracker.js +2 -1
  365. package/dist/shared/llm/provider-manager.js +4 -22
  366. package/dist/shared/llm/providers/gemini.d.ts +1 -0
  367. package/dist/shared/llm/providers/gemini.js +14 -5
  368. package/dist/shared/llm/providers/openrouter.js +6 -3
  369. package/dist/shared/metrics/code-metrics.js +1 -1
  370. package/dist/shared/metrics/system-metrics.js +8 -2
  371. package/dist/shared/retry-engine.js +6 -12
  372. package/dist/shared/test-runner-process.d.ts +10 -0
  373. package/dist/shared/test-runner-process.js +210 -0
  374. package/dist/test-scheduling/executors/vitest-executor.js +26 -17
  375. package/dist/validation/quality-verdict.js +3 -2
  376. package/dist/workers/quality-daemon/priority-queue.js +4 -1
  377. package/package.json +6 -4
  378. package/dist/cli/chunks/adapter-TVQKH65T.js +0 -2
  379. package/dist/cli/chunks/aqe-learning-engine-ULGTVVWE.js +0 -2
  380. package/dist/cli/chunks/base-W42BURDL.js +0 -2
  381. package/dist/cli/chunks/browser-workflow-HKGHFFFT.js +0 -2
  382. package/dist/cli/chunks/chunk-2IMSJ7IO.js +0 -2
  383. package/dist/cli/chunks/chunk-FBZC4IGB.js +0 -2
  384. package/dist/cli/chunks/chunk-LXZMP3VX.js +0 -736
  385. package/dist/cli/chunks/chunk-MNQN7UZX.js +0 -4
  386. package/dist/cli/chunks/chunk-OXHF3L2T.js +0 -2
  387. package/dist/cli/chunks/chunk-PELENDDQ.js +0 -2
  388. package/dist/cli/chunks/chunk-TW3SR4TS.js +0 -2
  389. package/dist/cli/chunks/chunk-V6RE4YRQ.js +0 -2
  390. package/dist/cli/chunks/chunk-ZQZD55MN.js +0 -3
  391. package/dist/cli/chunks/ci-J3TDK5RA.js +0 -81
  392. package/dist/cli/chunks/client-3BD2DI4N.js +0 -2
  393. package/dist/cli/chunks/core-handlers-C3H2ZCS2.js +0 -2
  394. package/dist/cli/chunks/cross-domain-router-JCQ7SWDP.js +0 -2
  395. package/dist/cli/chunks/domain-transfer-MFCI76IY.js +0 -2
  396. package/dist/cli/chunks/dream-FTP33IJB.js +0 -2
  397. package/dist/cli/chunks/heartbeat-scheduler-HXBJVJL2.js +0 -2
  398. package/dist/cli/chunks/hnsw-adapter-TU6WG2ME.js +0 -2
  399. package/dist/cli/chunks/hnsw-index-MS5KODD7.js +0 -2
  400. package/dist/cli/chunks/hybrid-backend-HT45LBHC.js +0 -2
  401. package/dist/cli/chunks/impact-analyzer-AP4AGTG5.js +0 -2
  402. package/dist/cli/chunks/init-wizard-I5DFZUQL.js +0 -2
  403. package/dist/cli/chunks/kernel-MISPSPPA.js +0 -2
  404. package/dist/cli/chunks/knowledge-graph-L26JESGE.js +0 -2
  405. package/dist/cli/chunks/llm-router-service-MWGC43ZA.js +0 -2
  406. package/dist/cli/chunks/load-test-H5ISNNM5.js +0 -2
  407. package/dist/cli/chunks/memory-backend-HWDNOBKW.js +0 -2
  408. package/dist/cli/chunks/memory-handlers-ZFDVQZM5.js +0 -2
  409. package/dist/cli/chunks/pattern-null-store-GQP6ICWK.js +0 -2
  410. package/dist/cli/chunks/protocol-executor-AD5A4DAI.js +0 -2
  411. package/dist/cli/chunks/qe-reasoning-bank-W3Z2PKTR.js +0 -2
  412. package/dist/cli/chunks/quality-gate-GYNCA4ZY.js +0 -7
  413. package/dist/cli/chunks/queen-coordinator-HQRHLIJX.js +0 -2
  414. package/dist/cli/chunks/router-MTP5LH4H.js +0 -2
  415. package/dist/cli/chunks/routing-feedback-GWETVB4L.js +0 -2
  416. package/dist/cli/chunks/rvf-dual-writer-4UE5S7WP.js +0 -2
  417. package/dist/cli/chunks/rvf-migration-adapter-PHH3HF4Q.js +0 -2
  418. package/dist/cli/chunks/rvf-native-adapter-KTLZBUWV.js +0 -2
  419. package/dist/cli/chunks/safe-db-FWWGAPVE.js +0 -2
  420. package/dist/cli/chunks/schedule-TPA4V4D5.js +0 -2
  421. package/dist/cli/chunks/scheduler-5ZTEPNDD.js +0 -2
  422. package/dist/cli/chunks/sqlite-persistence-HPTT624C.js +0 -2
  423. package/dist/cli/chunks/unified-memory-OVFEPRPS.js +0 -2
  424. package/dist/cli/chunks/unified-memory-hnsw-KKRSCZHR.js +0 -2
  425. package/dist/cli/chunks/unified-persistence-7GLR4RI3.js +0 -2
  426. package/dist/cli/chunks/visual-security-2FUM5GLI.js +0 -2
  427. package/dist/cli/chunks/witness-chain-MH6GA5L6.js +0 -2
  428. package/dist/cli/chunks/workflow-orchestrator-H6G65YKU.js +0 -2
@@ -1,9 +1,9 @@
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.7");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-IWFFO6VT.js";import{c as Ee}from"./chunk-B2YGVSOP.js";import{a as we,b as Re,c as H,d as V,f as tn}from"./chunk-XBYQ2BS4.js";import{b as ve}from"./chunk-36VKMAMN.js";import{a as Se,d as ae,e as _e}from"./chunk-4INST4ZL.js";import"./chunk-QUORH2MG.js";import"./chunk-ZELWDJXT.js";import{b as k,d as oe}from"./chunk-OIDWDGLG.js";import"./chunk-UFSVUBTR.js";import"./chunk-IAENZ2DR.js";import"./chunk-PELENDDQ.js";import"./chunk-TW3SR4TS.js";import"./chunk-5GFKTJ65.js";import"./chunk-5D7ZFWDS.js";import"./chunk-ZUOVNFXK.js";import{a as F,b as nn}from"./chunk-ND4QTZOL.js";import"./chunk-JZT7BU44.js";import"./chunk-P7XSPP5D.js";import"./chunk-RDGPXENG.js";import"./chunk-VYDVI6FZ.js";import"./chunk-HYFQUWNB.js";import"./chunk-B4I43GE2.js";import"./chunk-CBONQM5D.js";import"./chunk-AEUEMVJK.js";import"./chunk-YO4ESCB4.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(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");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-ZPH2YT3J.js";import{c as Ee}from"./chunk-7JABIXP3.js";import{b as ve}from"./chunk-4DCDIKBX.js";import{a as Se,d as ae,e as _e}from"./chunk-WPOYFV4X.js";import"./chunk-XZDPR6I2.js";import"./chunk-ILKMNDUM.js";import{b as k,d as oe}from"./chunk-ATXAMGVE.js";import"./chunk-JJ7WAU4I.js";import"./chunk-7WUHVGGT.js";import"./chunk-UGYXUPGN.js";import"./chunk-HOPXHZA3.js";import"./chunk-B6QTNTCU.js";import"./chunk-WBR4VRQE.js";import"./chunk-GV7P5JYF.js";import"./chunk-5LN7FQZI.js";import"./chunk-AIE6OKCD.js";import"./chunk-OYVDTD3A.js";import"./chunk-OBSX3I4Y.js";import"./chunk-X5RELRY7.js";import"./chunk-URUOTHPO.js";import"./chunk-QRALXNNX.js";import{a as we,b as Re,c as H,d as V,f as nn}from"./chunk-CMYZWIXS.js";import{a as F,b as tn}from"./chunk-AGYPPPXR.js";import"./chunk-WDV6CBED.js";import"./chunk-GX5RFGW2.js";import $ from"path";import o from"chalk";tn();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
3
  INSERT INTO witness_chain
4
4
  (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo)
5
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
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"))}nn();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
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
8
  CREATE TEMP TABLE IF NOT EXISTS _covered_patterns (
9
9
  pattern_id TEXT PRIMARY KEY
@@ -79,7 +79,7 @@ Examples:
79
79
  aqe brain diff ./brain-a ./brain-b --verbose
80
80
  aqe brain search -i ./brain-export --query oauth --domain test-generation
81
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-OVFEPRPS.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(`
82
+ `}};async function ye(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-B5IA2KKQ.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
83
  Brain Diff
84
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
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(`
@@ -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.7");process.exit(0)}
2
- import"./chunk-YO4ESCB4.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.15.0");process.exit(0)}
2
+ import"./chunk-GX5RFGW2.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.7");process.exit(0)}
2
- import{a as p}from"./chunk-FYPX5WBJ.js";import"./chunk-YO4ESCB4.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.15.0");process.exit(0)}
2
+ import{a as p}from"./chunk-ISAMM7QA.js";import"./chunk-GX5RFGW2.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.15.0");process.exit(0)}
2
+ import{a}from"./chunk-JO2YLIZH.js";import"./chunk-5PNRUMRV.js";import"./chunk-WQMXQO3O.js";import"./chunk-R6CZCMKD.js";import"./chunk-XZDPR6I2.js";import"./chunk-ILKMNDUM.js";import"./chunk-ATXAMGVE.js";import"./chunk-JJ7WAU4I.js";import"./chunk-7WUHVGGT.js";import"./chunk-UGYXUPGN.js";import"./chunk-HOPXHZA3.js";import"./chunk-B6QTNTCU.js";import"./chunk-WBR4VRQE.js";import"./chunk-GV7P5JYF.js";import"./chunk-MO3QXLF2.js";import"./chunk-5LN7FQZI.js";import"./chunk-AIE6OKCD.js";import"./chunk-OYVDTD3A.js";import"./chunk-OBSX3I4Y.js";import"./chunk-X5RELRY7.js";import"./chunk-URUOTHPO.js";import"./chunk-QRALXNNX.js";import"./chunk-AGYPPPXR.js";import"./chunk-WDV6CBED.js";import"./chunk-GX5RFGW2.js";export{a as BrowserWorkflowTool};
@@ -1 +1 @@
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.7");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
@@ -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.7");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");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,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.7");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
2
  async function o(n){await n.loadAll();let a=new Map;for(let i of n.getLoaded())a.set(i,await n.load(i));return a}export{o 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.7");process.exit(0)}
2
- import{b as P,c as q,d as R,e as D,g as O,h as j,i as x,j as $,k as L,l as N,m as Q,n as M}from"./chunk-MM56VPNE.js";import{b as v,d as T}from"./chunk-OIDWDGLG.js";import{a as y,e as A}from"./chunk-ZUOVNFXK.js";import{a as _,b as re}from"./chunk-ND4QTZOL.js";T();import{existsSync as f,mkdirSync as U,writeFileSync as b,readFileSync as C,copyFileSync as se}from"fs";import{join as p,dirname as ae}from"path";async function z(t,e){if(!e.hooks.claudeCode)return!1;let n=p(t,".claude");f(n)||U(n,{recursive:!0});let r=p(n,"settings.json"),s={};if(f(r))try{let m=C(r,"utf-8");s=v(m)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,i);let l=s.env;s.env=j(l,x(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(r),b(r,JSON.stringify(s,null,2),"utf-8"),await oe(t),!0}async function oe(t){let e=p(t,".claude","hooks");f(e)||U(e,{recursive:!0});let n=p(e,"cross-phase-memory.yaml");if(f(n))return;let r=[p(ae(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(f(i)){se(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(n,`# Cross-Phase Memory Hooks Configuration
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
+ import{b as P,c as q,d as R,e as D,g as O,h as x,i as j,j as $,k as L,l as N,m as Q,n as M}from"./chunk-XPUY3ZKD.js";import{b as v,d as T}from"./chunk-ATXAMGVE.js";import{a as y,e as A}from"./chunk-X5RELRY7.js";import{a as _,b as re}from"./chunk-AGYPPPXR.js";T();import{existsSync as f,mkdirSync as U,writeFileSync as b,readFileSync as C,copyFileSync as se}from"fs";import{join as p,dirname as ae}from"path";async function z(t,e){if(!e.hooks.claudeCode)return!1;let n=p(t,".claude");f(n)||U(n,{recursive:!0});let r=p(n,"settings.json"),s={};if(f(r))try{let m=C(r,"utf-8");s=v(m)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},u=s.hooks||{};s.hooks=O(u,i);let l=s.env;s.env=x(l,j(e));let d=L(e,t);$(s,d);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,D(r),b(r,JSON.stringify(s,null,2),"utf-8"),await oe(t),!0}async function oe(t){let e=p(t,".claude","hooks");f(e)||U(e,{recursive:!0});let n=p(e,"cross-phase-memory.yaml");if(f(n))return;let r=[p(ae(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),p(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(f(i)){se(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(n,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
5
 
@@ -276,7 +276,7 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
277
  INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
278
  VALUES (?, '_system', ?, ?)
279
- `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${y(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${y(r)}`),!1}}async function V(t){let e=null;try{e=(await import("./better-sqlite3-DB3LOJQU.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${y(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${y(r)}`),!1}}async function V(t){let e=null;try{e=(await import("./better-sqlite3-DSL7LFRK.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
280
  Install it with: npm install better-sqlite3
281
281
  If you see native compilation errors, ensure build tools are installed:
282
282
  - macOS: xcode-select --install
@@ -302,7 +302,7 @@ Database path: ${r}
302
302
  Ensure the directory is writable and has sufficient disk space.`)}}async function J(t){let e=o(t,".agentic-qe","memory.db");if(!h(e))return!1;try{let n=_(e),r=n.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return n.close(),r.count>0}catch{return!1}}async function B(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-L26JESGE.js"),{InMemoryBackend:n}=await import("./memory-backend-HWDNOBKW.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),u=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),l=await s.index({paths:u.map(d=>o(t,d)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",y(e)),{status:"skipped",entries:0}}}async function H(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function B(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-GR52N7PU.js"),{InMemoryBackend:n}=await import("./memory-backend-SMQRS5QN.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),{glob:i}=await import("tinyglobby"),u=await i(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"],expandDirectories:!1}),l=await s.index({paths:u.map(d=>o(t,d)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",y(e)),{status:"skipped",entries:0}}}async function H(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
308
  `).get();return n.close(),r.count}catch{return 0}}async function X(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");h(r)||k(r,{recursive:!0});let s=o(r,"hnsw");h(s)||k(s,{recursive:!0});let i=o(r,"learning-config.json"),u={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(u,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&n){let d=n,a=new Map;for(let g of d.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=o(r,"pretrained-index.json"),S={version:d.version,totalPatterns:d.statistics.totalPatterns,domains:Array.from(a.entries()).map(([g,c])=>({name:g,patternCount:c.length})),loadedAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8");for(let[g,c]of a){let w=o(r,"patterns",g);h(w)||k(w,{recursive:!0});let ne=o(w,"patterns.json");E(ne,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function K(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");h(n)||k(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),u={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(u,null,2),"utf-8");for(let a of e.workers.enabled){let m=o(n,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=o(n,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
@@ -312,5 +312,5 @@ Ensure the directory is writable and has sufficient disk space.`)}}async functio
312
312
  console.log("AQE v3 hooks work via CLI commands (no daemon required)");
313
313
  console.log("Use: npx aqe hooks session-start");
314
314
  `),e.workers.enabled.length}async function Y(t,e){if(!e.skills.install)return 0;let r=await N({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return r.errors.length>0&&console.warn("Skills installation warnings:",r.errors),r.installed.length}async function Z(t){let n=await Q({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return n.errors.length>0&&console.warn("Agents installation warnings:",n.errors),n.installed.length}async function ee(t,e,n){let s=await M({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:n}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:n},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function te(t,e){if(!e)throw new Error("No configuration to save");let n=o(t,".agentic-qe");h(n)||k(n,{recursive:!0});let r=ce(e),s=o(n,"config.yaml");E(s,r,"utf-8")}function ce(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-5.5" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let n of t.workers.enabled)e.push(` - "${n}"`);e.push(" intervals:");for(let[n,r]of Object.entries(t.workers.intervals))e.push(` ${n}: ${r}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let n of t.autoTuning.parameters)e.push(` - "${n}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let n of t.domains.enabled)e.push(` - "${n}"`);e.push(" disabled:");for(let n of t.domains.disabled)e.push(` - "${n}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
315
- `)}var ue=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],I=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=q(e.projectRoot),this.configurator=R({minimal:e.minimal})}async initialize(){let e=Date.now();try{let n=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),r=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(n):this.applyWizardAnswers(n));await this.runStep("Persistence Database Setup",async()=>await V(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await J(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await B(n.projectRoot);let w=await H(this.projectRoot);return console.log(` Using existing code intelligence index (${w} entries)`),{status:"existing",entries:w}}),i=await this.runStep("Learning System Setup",async()=>r.learning.enabled&&!this.options.skipPatterns?await X(this.projectRoot,r,this.options.pretrainedLibrary):0),u=await this.runStep("Hooks Configuration",async()=>r.hooks.claudeCode?await z(this.projectRoot,r):!1),l=await this.runStep("MCP Configuration",async()=>await F(this.projectRoot)),d=await this.runStep("CLAUDE.md Generation",async()=>await W(this.projectRoot,r)),a=await this.runStep("Background Workers",async()=>r.workers.daemonAutoStart?await K(this.projectRoot,r):0),m=await this.runStep("Skills Installation",async()=>r.skills.install?await Y(this.projectRoot,r):0),S=await this.runStep("Agents Installation",async()=>await Z(this.projectRoot)),g;if(this.options.withN8n){let c=await this.runStep("N8n Platform Installation",async()=>await ee(this.projectRoot,r,this.options.n8nApiConfig));c&&(g=c)}return await this.runStep("Save Configuration",async()=>await te(this.projectRoot,r)),await this.runStep("Version Marker",async()=>await G(this.projectRoot,r.version)),{success:!0,config:r,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:i,skillsInstalled:m,agentsInstalled:S,hooksConfigured:u,mcpConfigured:l,claudeMdGenerated:d,workersStarted:a,n8nInstalled:g},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(n){return this.steps.push({step:"Initialization Failed",status:"error",message:y(n),durationMs:0}),{success:!1,config:P("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ue}async runStep(e,n){let r=Date.now();try{let s=await n();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-r}),s}catch(s){throw this.steps.push({step:e,status:"error",message:y(s),durationMs:Date.now()-r}),s}}applyWizardAnswers(e){let n=this.options.wizardAnswers||{},r=this.configurator.recommend(e);switch(n["project-type"]&&n["project-type"]!=="auto"&&(r.project.type=n["project-type"]),n["learning-mode"]){case"full":r.learning.enabled=!0,r.learning.embeddingModel="transformer";break;case"basic":r.learning.enabled=!0,r.learning.embeddingModel="hash";break;case"disabled":r.learning.enabled=!1;break}return n["load-patterns"]===!1&&(r.learning.pretrainedPatterns=!1),n.hooks===!1&&(r.hooks.claudeCode=!1),n.workers===!1&&(r.workers.daemonAutoStart=!1),n.skills===!1&&(r.skills.install=!1),r}};function de(t){return new I(t)}async function je(t){return await de({projectRoot:t,autoMode:!0}).initialize()}function xe(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let r of t.steps){let s=r.status==="success"?"[OK]":r.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${r.step.padEnd(50)} ${String(r.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let n=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${n.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
- `)}export{I as a,de as b,je as c,xe as d};
315
+ `)}var ue=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],I=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=q(e.projectRoot),this.configurator=R({minimal:e.minimal})}async initialize(){let e=Date.now();try{let n=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),r=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(n):this.applyWizardAnswers(n));await this.runStep("Persistence Database Setup",async()=>await V(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await J(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await B(n.projectRoot);let w=await H(this.projectRoot);return console.log(` Using existing code intelligence index (${w} entries)`),{status:"existing",entries:w}}),i=await this.runStep("Learning System Setup",async()=>r.learning.enabled&&!this.options.skipPatterns?await X(this.projectRoot,r,this.options.pretrainedLibrary):0),u=await this.runStep("Hooks Configuration",async()=>r.hooks.claudeCode?await z(this.projectRoot,r):!1),l=await this.runStep("MCP Configuration",async()=>await F(this.projectRoot)),d=await this.runStep("CLAUDE.md Generation",async()=>await W(this.projectRoot,r)),a=await this.runStep("Background Workers",async()=>r.workers.daemonAutoStart?await K(this.projectRoot,r):0),m=await this.runStep("Skills Installation",async()=>r.skills.install?await Y(this.projectRoot,r):0),S=await this.runStep("Agents Installation",async()=>await Z(this.projectRoot)),g;if(this.options.withN8n){let c=await this.runStep("N8n Platform Installation",async()=>await ee(this.projectRoot,r,this.options.n8nApiConfig));c&&(g=c)}return await this.runStep("Save Configuration",async()=>await te(this.projectRoot,r)),await this.runStep("Version Marker",async()=>await G(this.projectRoot,r.version)),{success:!0,config:r,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:i,skillsInstalled:m,agentsInstalled:S,hooksConfigured:u,mcpConfigured:l,claudeMdGenerated:d,workersStarted:a,n8nInstalled:g},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(n){return this.steps.push({step:"Initialization Failed",status:"error",message:y(n),durationMs:0}),{success:!1,config:P("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ue}async runStep(e,n){let r=Date.now();try{let s=await n();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-r}),s}catch(s){throw this.steps.push({step:e,status:"error",message:y(s),durationMs:Date.now()-r}),s}}applyWizardAnswers(e){let n=this.options.wizardAnswers||{},r=this.configurator.recommend(e);switch(n["project-type"]&&n["project-type"]!=="auto"&&(r.project.type=n["project-type"]),n["learning-mode"]){case"full":r.learning.enabled=!0,r.learning.embeddingModel="transformer";break;case"basic":r.learning.enabled=!0,r.learning.embeddingModel="hash";break;case"disabled":r.learning.enabled=!1;break}return n["load-patterns"]===!1&&(r.learning.pretrainedPatterns=!1),n.hooks===!1&&(r.hooks.claudeCode=!1),n.workers===!1&&(r.workers.daemonAutoStart=!1),n.skills===!1&&(r.skills.install=!1),r}};function de(t){return new I(t)}async function xe(t){return await de({projectRoot:t,autoMode:!0}).initialize()}function je(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let r of t.steps){let s=r.status==="success"?"[OK]":r.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${r.step.padEnd(50)} ${String(r.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let n=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${n.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
+ `)}export{I as a,de as b,xe as c,je 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.7");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
2
  var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
@@ -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.7");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
2
  import{writeFileSync as d,readFileSync as m}from"node:fs";import{resolve as f,dirname as u,join as g}from"node:path";import{mkdirSync as h}from"node:fs";import{fileURLToPath as v}from"node:url";function y(){try{let e=typeof __dirname<"u"?__dirname:u(v(import.meta.url));for(let n=0;n<5;n++){let t=g(e,"package.json");try{let o=JSON.parse(m(t,"utf-8"));if(o.version)return o.version}catch{}e=u(e)}}catch{}return"unknown"}function l(e){return e.status??e.evidence?.completeness??"unverified"}var R=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],T=["-o, --output <path>","Write output to file instead of stdout"];function w(e,n,t){if(n){let o=f(n);h(u(o),{recursive:!0}),d(o,e,"utf-8"),t&&console.log(t),console.log(`Output written to: ${o}`)}else console.log(e)}function $(e){return JSON.stringify(e,null,2)}var S="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function F(e){let n=l(e),t=s=>{switch(s.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},o=new Map,r=[];for(let s of e.vulnerabilities){let a=s.ruleId||`AQE/${s.type.replace(/\s+/g,"-").toLowerCase()}`;o.has(a)||o.set(a,{id:a,name:s.type,shortDescription:s.type,...s.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${s.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:a,level:t(s.severity),message:{text:s.message},locations:[{physicalLocation:{artifactLocation:{uri:s.file,uriBaseId:"%SRCROOT%"},region:{startLine:s.line,startColumn:1}}}],...s.cweId?{taxa:[{id:s.cweId,toolComponent:{name:"CWE"}}]}:{}})}let i={$schema:S,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:y(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(o.values()).map(s=>({id:s.id,name:s.name,shortDescription:{text:s.shortDescription},...s.helpUri?{helpUri:s.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,properties:{securityScan:{status:n,target:e.target,scanType:e.scanType,coverage:e.evidence?e.coverage:void 0,evidence:e.evidence,discovery:e.discovery,checks:e.checks}},invocations:[{executionSuccessful:n==="complete",...n==="complete"?{}:{toolExecutionNotifications:[{level:"warning",message:{text:`Security analysis ${n}; findings do not establish complete coverage.`}}]}}]}]};return JSON.stringify(i,null,2)}function c(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function A(e){let n=e.tests||[],t=e.passed+e.failed+e.skipped,o=(e.duration/1e3).toFixed(3),r=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `;if(r+=`<testsuites tests="${t}" failures="${e.failed}" errors="0" time="${o}">
4
4
  `,r+=` <testsuite name="aqe-test-run" tests="${t}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${o}" id="${c(e.runId)}">
@@ -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.7");process.exit(0)}
2
- import{b as k,c as p}from"./chunk-IAENZ2DR.js";p();import{generateKeyPairSync as g,createPrivateKey as v,createPublicKey as I,sign as m,verify as D,createHash as b}from"crypto";import{existsSync as d,mkdirSync as P,writeFileSync as y,readFileSync as o,readdirSync as w}from"fs";import{join as n}from"path";var f=class{keys=new Map;activeKeyId=null;keyDir;constructor(e={}){this.keyDir=e.keyDir??null,this.keyDir&&this.loadFromDisk(),e.autoGenerate!==!1&&this.keys.size===0&&this.generateKeyPair()}generateKeyPair(){let{publicKey:e,privateKey:i}=g("ed25519"),r=e.export({type:"spki",format:"der"}),t=b("sha256").update(r).digest("hex").slice(0,16),s={keyId:t,publicKey:e,privateKey:i,createdAt:new Date().toISOString(),retired:!1};return this.keys.set(t,s),this.activeKeyId=t,this.keyDir&&(this.saveKeyPairToDisk(s),this.saveActiveKeyId()),{keyId:t,publicKey:r}}sign(e,i){let r=i??this.activeKeyId;if(!r)throw new Error("No active key available for signing");let t=this.keys.get(r);if(!t)throw new Error(`Key not found: ${r}`);return{signature:m(null,e,t.privateKey),keyId:r}}verify(e,i,r){let t=this.keys.get(r);if(!t)return!1;try{return D(null,e,t.publicKey,i)}catch{return!1}}rotateKey(){let e=this.activeKeyId;if(!e)throw new Error("No active key to rotate");let i=this.keys.get(e);i&&(i.retired=!0,this.keyDir&&this.saveKeyPairToDisk(i));let{keyId:r}=this.generateKeyPair();return{oldKeyId:e,newKeyId:r}}getActiveKeyId(){if(!this.activeKeyId)throw new Error("No active key");return this.activeKeyId}hasKey(e){return this.keys.has(e)}getKeyCount(){return this.keys.size}saveKeyPairToDisk(e){if(!this.keyDir)return;d(this.keyDir)||P(this.keyDir,{recursive:!0});let i=n(this.keyDir,e.keyId);y(`${i}.pub.pem`,e.publicKey.export({type:"spki",format:"pem"}),"utf-8"),y(`${i}.key.pem`,e.privateKey.export({type:"pkcs8",format:"pem"}),{encoding:"utf-8",mode:384}),y(`${i}.meta.json`,JSON.stringify({keyId:e.keyId,createdAt:e.createdAt,retired:e.retired}),"utf-8")}saveActiveKeyId(){!this.keyDir||!this.activeKeyId||y(n(this.keyDir,"active-key-id"),this.activeKeyId,"utf-8")}loadFromDisk(){if(!this.keyDir||!d(this.keyDir))return;let i=w(this.keyDir).filter(t=>t.endsWith(".meta.json"));for(let t of i)try{let s=JSON.parse(o(n(this.keyDir,t),"utf-8")),a=n(this.keyDir,s.keyId),l=o(`${a}.pub.pem`,"utf-8"),K=o(`${a}.key.pem`,"utf-8"),h={keyId:s.keyId,publicKey:I(l),privateKey:v(K),createdAt:s.createdAt,retired:s.retired};this.keys.set(s.keyId,h)}catch{}let r=n(this.keyDir,"active-key-id");if(d(r)){let t=o(r,"utf-8").trim();this.keys.has(t)&&(this.activeKeyId=t)}if(!this.activeKeyId){let t=[...this.keys.values()].filter(s=>!s.retired).sort((s,a)=>a.createdAt.localeCompare(s.createdAt));t.length>0&&(this.activeKeyId=t[0].keyId)}}},c=null;function F(){if(!c){let u=n(k(),".agentic-qe","witness-keys");c=new f({keyDir:u})}return c}function O(){c=null}export{f as a,F as b,O as c};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
+ import{b as k,c as p}from"./chunk-QRALXNNX.js";p();import{generateKeyPairSync as g,createPrivateKey as v,createPublicKey as I,sign as m,verify as D,createHash as b}from"crypto";import{existsSync as d,mkdirSync as P,writeFileSync as y,readFileSync as o,readdirSync as w}from"fs";import{join as n}from"path";var f=class{keys=new Map;activeKeyId=null;keyDir;constructor(e={}){this.keyDir=e.keyDir??null,this.keyDir&&this.loadFromDisk(),e.autoGenerate!==!1&&this.keys.size===0&&this.generateKeyPair()}generateKeyPair(){let{publicKey:e,privateKey:i}=g("ed25519"),r=e.export({type:"spki",format:"der"}),t=b("sha256").update(r).digest("hex").slice(0,16),s={keyId:t,publicKey:e,privateKey:i,createdAt:new Date().toISOString(),retired:!1};return this.keys.set(t,s),this.activeKeyId=t,this.keyDir&&(this.saveKeyPairToDisk(s),this.saveActiveKeyId()),{keyId:t,publicKey:r}}sign(e,i){let r=i??this.activeKeyId;if(!r)throw new Error("No active key available for signing");let t=this.keys.get(r);if(!t)throw new Error(`Key not found: ${r}`);return{signature:m(null,e,t.privateKey),keyId:r}}verify(e,i,r){let t=this.keys.get(r);if(!t)return!1;try{return D(null,e,t.publicKey,i)}catch{return!1}}rotateKey(){let e=this.activeKeyId;if(!e)throw new Error("No active key to rotate");let i=this.keys.get(e);i&&(i.retired=!0,this.keyDir&&this.saveKeyPairToDisk(i));let{keyId:r}=this.generateKeyPair();return{oldKeyId:e,newKeyId:r}}getActiveKeyId(){if(!this.activeKeyId)throw new Error("No active key");return this.activeKeyId}hasKey(e){return this.keys.has(e)}getKeyCount(){return this.keys.size}saveKeyPairToDisk(e){if(!this.keyDir)return;d(this.keyDir)||P(this.keyDir,{recursive:!0});let i=n(this.keyDir,e.keyId);y(`${i}.pub.pem`,e.publicKey.export({type:"spki",format:"pem"}),"utf-8"),y(`${i}.key.pem`,e.privateKey.export({type:"pkcs8",format:"pem"}),{encoding:"utf-8",mode:384}),y(`${i}.meta.json`,JSON.stringify({keyId:e.keyId,createdAt:e.createdAt,retired:e.retired}),"utf-8")}saveActiveKeyId(){!this.keyDir||!this.activeKeyId||y(n(this.keyDir,"active-key-id"),this.activeKeyId,"utf-8")}loadFromDisk(){if(!this.keyDir||!d(this.keyDir))return;let i=w(this.keyDir).filter(t=>t.endsWith(".meta.json"));for(let t of i)try{let s=JSON.parse(o(n(this.keyDir,t),"utf-8")),a=n(this.keyDir,s.keyId),l=o(`${a}.pub.pem`,"utf-8"),K=o(`${a}.key.pem`,"utf-8"),h={keyId:s.keyId,publicKey:I(l),privateKey:v(K),createdAt:s.createdAt,retired:s.retired};this.keys.set(s.keyId,h)}catch{}let r=n(this.keyDir,"active-key-id");if(d(r)){let t=o(r,"utf-8").trim();this.keys.has(t)&&(this.activeKeyId=t)}if(!this.activeKeyId){let t=[...this.keys.values()].filter(s=>!s.retired).sort((s,a)=>a.createdAt.localeCompare(s.createdAt));t.length>0&&(this.activeKeyId=t[0].keyId)}}},c=null;function F(){if(!c){let u=n(k(),".agentic-qe","witness-keys");c=new f({keyDir:u})}return c}function O(){c=null}export{f as a,F as b,O as c};
@@ -0,0 +1,4 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
+ import{a as p}from"./chunk-MM57SD2F.js";import{j as m,n as E}from"./chunk-H77AUJNW.js";import{s as T}from"./chunk-XZDPR6I2.js";import{b as V}from"./chunk-QRALXNNX.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===!0&&e.oracle.passed===!0)){let s=e.oracle==null?"oracle did not run":e.oracle.baselinePassed!==!0?"tests did not execute against the reference implementation":"mutation score below threshold";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
+ `);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
+ `)}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,6 +1,6 @@
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.7");process.exit(0)}
2
- import{d as C}from"./chunk-Z4Q5PCRZ.js";import{a as T}from"./chunk-HYOPJHHW.js";import{a as w,b as S}from"./chunk-4EKV7PHB.js";import{r as D,s as F}from"./chunk-QUORH2MG.js";import{a as R,e as A}from"./chunk-ZUOVNFXK.js";import{f as O}from"./chunk-YO4ESCB4.js";import{createHash as M}from"crypto";function I(){let s="3.14.7",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${s}+${e}`:s}var $={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function x(s){if(s==null||typeof s!="object")return JSON.stringify(s);if(Array.isArray(s))return"["+s.map(i=>x(i)).join(",")+"]";let e=s;return"{"+Object.keys(e).sort().map(i=>JSON.stringify(i)+":"+x(e[i])).join(",")+"}"}var b=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...$,...e}}computeFingerprint(e,t,r){let i=x({action:t,build:I(),domain:e,input:r});return M("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;this.cache.size>=this.config.maxEntries&&this.evictOldest();let o={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,o),this.config.persistToDb&&this.persistEntry(o)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
+ import{d as C}from"./chunk-KUTMQBV4.js";import{a as T}from"./chunk-I3BH3KIF.js";import{a as R,b as S}from"./chunk-Z6CRROLU.js";import{r as A,s as D}from"./chunk-XZDPR6I2.js";import{a as k,e as O}from"./chunk-X5RELRY7.js";import{f as z}from"./chunk-GX5RFGW2.js";import{createHash as F}from"crypto";function M(){let a="3.15.0",e=(process.env.AQE_SESSION_CACHE_SALT??"").trim();return e?`${a}+${e}`:a}var I={enabled:!0,maxEntries:500,ttlMs:3600*1e3,persistToDb:!0};function $(a){let e=JSON.parse(JSON.stringify(a));function t(r){if(r===null||typeof r!="object")return JSON.stringify(r);if(Array.isArray(r))return"["+r.map(t).join(",")+"]";let i=r;return"{"+Object.keys(i).sort().map(n=>JSON.stringify(n)+":"+t(i[n])).join(",")+"}"}return t(e)}var x=class{cache=new Map;config;hits=0;misses=0;generation=0;constructor(e){this.config={...I,...e}}computeFingerprint(e,t,r){let i=$({action:t,build:M(),domain:e,input:r});return F("sha256").update(i).digest("hex").slice(0,16)}get(e){if(!this.config.enabled)return null;let t=this.cache.get(e);return t?Date.now()-t.cachedAt>this.config.ttlMs?(this.cache.delete(e),this.misses++,null):(t.hitCount++,t.lastHitAt=Date.now(),this.hits++,t):(this.misses++,null)}set(e,t,r,i,n){if(!this.config.enabled)return;!this.cache.has(e)&&this.cache.size>=this.config.maxEntries&&this.evictOldest();let s={fingerprint:e,domain:t,action:r,result:i,tokensSaved:n,cachedAt:Date.now(),hitCount:0,lastHitAt:0};this.cache.set(e,s),this.config.persistToDb&&this.persistEntry(s)}loadFromDb(){try{let e=d();if(!e)return;let t=Date.now()-this.config.ttlMs,r=e.prepare(`SELECT key, value FROM kv_store
3
3
  WHERE namespace = 'session_cache'
4
4
  AND created_at > ?
5
5
  ORDER BY created_at DESC LIMIT ?`).all(t,this.config.maxEntries);for(let i of r)try{let n=JSON.parse(i.value);Date.now()-n.cachedAt<=this.config.ttlMs&&this.cache.set(n.fingerprint,n)}catch{}}catch{}}getStats(){let e=this.hits+this.misses,t=0;for(let r of this.cache.values())t+=r.tokensSaved*r.hitCount;return{size:this.cache.size,hits:this.hits,misses:this.misses,hitRate:e>0?this.hits/e:0,estimatedTokensSaved:t}}clear(){this.cache.clear(),this.hits=0,this.misses=0,this.generation++}getGeneration(){return this.generation}invalidateAll(){let e=this.cache.size;if(this.cache.clear(),this.generation++,this.config.persistToDb)try{d()?.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache'").run()}catch{}return e}invalidateDomain(e){this.generation++;let t=0;for(let[r,i]of this.cache)i.domain===e&&(this.cache.delete(r),this.deletePersisted(i.fingerprint),t++);return t}evictOldest(){let e=null,t=1/0;for(let[r,i]of this.cache)i.cachedAt<t&&(t=i.cachedAt,e=r);e&&this.cache.delete(e)}persistEntry(e){try{let t=d();if(!t)return;t.prepare(`INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
6
- VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}deletePersisted(e){try{let t=d();if(!t)return;t.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache' AND key = ?").run(`session_cache:${e}`)}catch{}}};function d(){try{let{getUnifiedMemory:s}=(F(),O(D)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function p(s){return f||(f=new b(s),f.loadFromDb()),f}import{randomUUID as H}from"crypto";A();var v={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},j={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},G={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},g=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...v,...t}}async checkEarlyExit(e){let t=performance.now(),r=new Date;try{let i=e.domain??T(e.description)??void 0,n={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};i&&(n.domain=i),e.context&&(n.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let o=e.embedding??e.description,m=await this.patternStore.search(o,n),l=performance.now()-t;if(!m.success){let a="error"in m?m.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${a}`,l);return this.recordAttempt("search_error",i),h}let c=m.value;if(c.length===0){let a=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",l);return this.recordAttempt("no_matching_pattern",i),a}let u=null;for(let{pattern:a,score:h}of c){let y=this.evaluatePatternEligibility(a,h,r);if(y.eligible){let E=this.estimateTokensSaved(a),z={canExit:!0,reusedPattern:a,estimatedTokensSaved:E,confidence:a.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${a.name}" with ${(a.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:l};return this.recordReuse(a.id,E,a.confidence,h,l,i),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${a.name} (confidence: ${a.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${E})`),z}u===null&&(u={reason:y.reason,explanation:y.explanation})}if(u){let a=this.createResult(!1,u.reason,u.explanation,l);return this.recordAttempt(u.reason,i),a}let P=this.createResult(!1,"no_matching_pattern",`Found ${c.length} patterns but none met eligibility criteria`,l);return this.recordAttempt("no_matching_pattern",i),P}catch(i){let n=performance.now()-t,o=this.createResult(!1,"search_error",`Error during pattern search: ${R(i)}`,n);return this.recordAttempt("search_error"),o}}evaluatePatternEligibility(e,t,r){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let i=r.getTime()-e.lastUsedAt.getTime();if(i>this.config.maxPatternAge){let n=Math.floor(i/864e5),o=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${n} days > max ${o} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,r=Math.ceil(e.template.content.length/4);t+=r,t+=50;let o={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*o)}createResult(e,t,r,i){return{canExit:e,reason:t,explanation:r,searchLatencyMs:i}}recordReuse(e,t,r,i,n,o){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:r,similarity:i,latencyMs:n,domain:o,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:o,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,r=0,i=0,n=0,o=0;for(let c of this.reuseHistory)r+=c.tokensSaved,i+=c.confidence,n+=c.similarity,o+=c.latencyMs;let m={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let c of this.attemptHistory)m[c.reason]++;let l={};for(let c of this.reuseHistory){let u=c.domain??"unknown";l[u]||(l[u]={reuses:0,tokens:0}),l[u].reuses++,l[u].tokens+=c.tokensSaved}return{totalReuses:e,tokensSaved:r,avgConfidence:e>0?i/e:0,avgSimilarity:e>0?n/e:0,avgSearchLatencyMs:e>0?o/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:m,domainBreakdown:l}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var _={enabled:!0,earlyExit:v,verbose:!1},k=class{optimizer=null;patternStore=null;config=_;initialized=!1;readyPromise=null;memoryBackend=null;async initialize(e,t){this.initialized||(this.readyPromise=null,this.patternStore=null,this.optimizer=null,this.config={..._,...t},this.memoryBackend=e,this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Registered (lazy \u2014 pattern store not yet created)"))}async ensurePatternStoreReady(){if(!this.optimizer&&!(!this.initialized||!this.config.enabled||!this.memoryBackend))return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{try{this.patternStore=C(this.memoryBackend),await this.patternStore.initialize(),this.optimizer=new g(this.patternStore,this.config.earlyExit),this.config.verbose&&console.log("[TokenOptimizerService] Pattern store ready (lazy init)")}catch(e){console.warn("[TokenOptimizerService] Lazy pattern store init failed:",e)}})(),this.readyPromise)}async checkEarlyExit(e){if(!this.initialized||!this.config.enabled)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let r=p(),i=r.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),n=r.get(i);if(n)return S.recordEarlyExit(n.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${i.slice(0,8)}... (saved ${n.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:n.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${i.slice(0,8)}...)`,searchLatencyMs:0}}catch{}if(await this.ensurePatternStoreReady(),!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Pattern store unavailable (lazy init failed or disabled)",searchLatencyMs:0};let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(S.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(await this.ensurePatternStoreReady(),!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${H().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return w()}cacheOperationResult(e,t,r,i,n){try{let o=p(),m=o.computeFingerprint(e,t,r);o.set(m,e,t,i,n)}catch{}}getSessionCacheStats(){try{return p().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.readyPromise=null,this.memoryBackend=null,this.config=_}},L=new k;async function ie(s,e){await L.initialize(s,e)}export{p as a,L as b,ie as c};
6
+ VALUES (?, 'session_cache', ?, ?)`).run(`session_cache:${e.fingerprint}`,JSON.stringify(e),Date.now())}catch{}}deletePersisted(e){try{let t=d();if(!t)return;t.prepare("DELETE FROM kv_store WHERE namespace = 'session_cache' AND key = ?").run(`session_cache:${e}`)}catch{}}};function d(){try{let{getUnifiedMemory:a}=(D(),z(A)),e=a();return e.isInitialized()?e.getDatabase():null}catch{return null}}var f=null;function p(a){return f||(f=new x(a),f.loadFromDb()),f}import{randomUUID as H}from"crypto";O();var v={minConfidenceForExit:.85,minSuccessRate:.9,maxPatternAge:10080*60*1e3,minQualityScore:.7,minSuccessfulUses:2,maxSearchResults:5,similarityThreshold:.8,verbose:!1},j={minConfidenceForExit:.75,minSuccessRate:.8,maxPatternAge:336*60*60*1e3,minQualityScore:.6,minSuccessfulUses:1,maxSearchResults:10,similarityThreshold:.7,verbose:!1},G={minConfidenceForExit:.92,minSuccessRate:.95,maxPatternAge:4320*60*1e3,minQualityScore:.85,minSuccessfulUses:3,maxSearchResults:3,similarityThreshold:.9,verbose:!1},g=class{patternStore;config;reuseHistory=[];attemptHistory=[];constructor(e,t){this.patternStore=e,this.config={...v,...t}}async checkEarlyExit(e){let t=performance.now(),r=new Date;try{let i=e.domain??T(e.description)??void 0,n={limit:this.config.maxSearchResults*2,useVectorSearch:!!e.embedding};i&&(n.domain=i),e.context&&(n.context={language:e.context.language,framework:e.context.framework,testType:e.context.testType});let s=e.embedding??e.description,m=await this.patternStore.search(s,n),l=performance.now()-t;if(!m.success){let o="error"in m?m.error.message:"Unknown error",h=this.createResult(!1,"search_error",`Pattern search failed: ${o}`,l);return this.recordAttempt("search_error",i),h}let c=m.value;if(c.length===0){let o=this.createResult(!1,"no_matching_pattern","No matching patterns found in store",l);return this.recordAttempt("no_matching_pattern",i),o}let u=null;for(let{pattern:o,score:h}of c){let y=this.evaluatePatternEligibility(o,h,r);if(y.eligible){let E=this.estimateTokensSaved(o),P={canExit:!0,reusedPattern:o,estimatedTokensSaved:E,confidence:o.confidence,similarityScore:h,reason:"pattern_reused",explanation:`Reusing pattern "${o.name}" with ${(o.confidence*100).toFixed(1)}% confidence`,searchLatencyMs:l};return this.recordReuse(o.id,E,o.confidence,h,l,i),this.config.verbose&&console.log(`[EarlyExitTokenOptimizer] Pattern reuse: ${o.name} (confidence: ${o.confidence.toFixed(2)}, similarity: ${h.toFixed(2)}, tokens saved: ${E})`),P}u===null&&(u={reason:y.reason,explanation:y.explanation})}if(u){let o=this.createResult(!1,u.reason,u.explanation,l);return this.recordAttempt(u.reason,i),o}let w=this.createResult(!1,"no_matching_pattern",`Found ${c.length} patterns but none met eligibility criteria`,l);return this.recordAttempt("no_matching_pattern",i),w}catch(i){let n=performance.now()-t,s=this.createResult(!1,"search_error",`Error during pattern search: ${k(i)}`,n);return this.recordAttempt("search_error"),s}}evaluatePatternEligibility(e,t,r){if(t<this.config.similarityThreshold)return{eligible:!1,reason:"similarity_too_low",explanation:`Similarity ${(t*100).toFixed(1)}% < threshold ${(this.config.similarityThreshold*100).toFixed(1)}%`};if(e.confidence<this.config.minConfidenceForExit)return{eligible:!1,reason:"confidence_too_low",explanation:`Confidence ${(e.confidence*100).toFixed(1)}% < threshold ${(this.config.minConfidenceForExit*100).toFixed(1)}%`};if(e.successRate<this.config.minSuccessRate)return{eligible:!1,reason:"success_rate_too_low",explanation:`Success rate ${(e.successRate*100).toFixed(1)}% < threshold ${(this.config.minSuccessRate*100).toFixed(1)}%`};let i=r.getTime()-e.lastUsedAt.getTime();if(i>this.config.maxPatternAge){let n=Math.floor(i/864e5),s=Math.floor(this.config.maxPatternAge/(1440*60*1e3));return{eligible:!1,reason:"pattern_too_old",explanation:`Pattern age ${n} days > max ${s} days`}}return e.qualityScore<this.config.minQualityScore?{eligible:!1,reason:"quality_score_too_low",explanation:`Quality score ${(e.qualityScore*100).toFixed(1)}% < threshold ${(this.config.minQualityScore*100).toFixed(1)}%`}:e.successfulUses<this.config.minSuccessfulUses?{eligible:!1,reason:"insufficient_uses",explanation:`Successful uses ${e.successfulUses} < minimum ${this.config.minSuccessfulUses}`}:{eligible:!0,reason:"pattern_reused",explanation:"Pattern meets all eligibility criteria"}}estimateTokensSaved(e){let t=100,r=Math.ceil(e.template.content.length/4);t+=r,t+=50;let s={"test-template":1.5,"assertion-pattern":1,"mock-pattern":1.2,"coverage-strategy":1.3,"api-contract":1.4,"visual-baseline":1.1,"perf-benchmark":1.4,"flaky-fix":1.3,"error-handling":1.2}[e.patternType]??1;return Math.ceil(t*s)}createResult(e,t,r,i){return{canExit:e,reason:t,explanation:r,searchLatencyMs:i}}recordReuse(e,t,r,i,n,s){this.reuseHistory.push({patternId:e,tokensSaved:t,confidence:r,similarity:i,latencyMs:n,domain:s,timestamp:new Date}),this.attemptHistory.push({reason:"pattern_reused",domain:s,timestamp:new Date}),this.reuseHistory.length>1e4&&(this.reuseHistory=this.reuseHistory.slice(-1e4))}recordAttempt(e,t){this.attemptHistory.push({reason:e,domain:t,timestamp:new Date}),this.attemptHistory.length>1e4&&(this.attemptHistory=this.attemptHistory.slice(-1e4))}recordSuccessfulReuse(e){this.patternStore.recordUsage(e,!0).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record successful reuse for ${e}:`,t)})}recordFailedReuse(e){this.patternStore.recordUsage(e,!1).catch(t=>{console.warn(`[EarlyExitTokenOptimizer] Failed to record failed reuse for ${e}:`,t)})}getReuseStats(){let e=this.reuseHistory.length,t=this.attemptHistory.length,r=0,i=0,n=0,s=0;for(let c of this.reuseHistory)r+=c.tokensSaved,i+=c.confidence,n+=c.similarity,s+=c.latencyMs;let m={pattern_reused:0,no_matching_pattern:0,confidence_too_low:0,success_rate_too_low:0,pattern_too_old:0,quality_score_too_low:0,insufficient_uses:0,similarity_too_low:0,search_error:0};for(let c of this.attemptHistory)m[c.reason]++;let l={};for(let c of this.reuseHistory){let u=c.domain??"unknown";l[u]||(l[u]={reuses:0,tokens:0}),l[u].reuses++,l[u].tokens+=c.tokensSaved}return{totalReuses:e,tokensSaved:r,avgConfidence:e>0?i/e:0,avgSimilarity:e>0?n/e:0,avgSearchLatencyMs:e>0?s/e:0,totalAttempts:t,exitRate:t>0?e/t:0,reasonBreakdown:m,domainBreakdown:l}}resetStats(){this.reuseHistory=[],this.attemptHistory=[]}getConfig(){return{...this.config}}updateConfig(e){Object.assign(this.config,e)}};var b={enabled:!0,earlyExit:v,verbose:!1},_=class{optimizer=null;patternStore=null;config=b;initialized=!1;readyPromise=null;memoryBackend=null;async initialize(e,t){this.initialized||(this.readyPromise=null,this.patternStore=null,this.optimizer=null,this.config={...b,...t},this.memoryBackend=e,this.initialized=!0,this.config.verbose&&console.log("[TokenOptimizerService] Registered (lazy \u2014 pattern store not yet created)"))}async ensurePatternStoreReady(){if(!this.optimizer&&!(!this.initialized||!this.config.enabled||!this.memoryBackend))return this.readyPromise?this.readyPromise:(this.readyPromise=(async()=>{try{this.patternStore=C(this.memoryBackend),await this.patternStore.initialize(),this.optimizer=new g(this.patternStore,this.config.earlyExit),this.config.verbose&&console.log("[TokenOptimizerService] Pattern store ready (lazy init)")}catch(e){console.warn("[TokenOptimizerService] Lazy pattern store init failed:",e)}})(),this.readyPromise)}async checkEarlyExit(e){if(!this.initialized||!this.config.enabled)return{canExit:!1,reason:"no_matching_pattern",explanation:"Token optimizer service not initialized",searchLatencyMs:0};try{let r=p(),i=r.computeFingerprint(e.domain??"unknown",e.description,e.context??{}),n=r.get(i);if(n)return S.recordEarlyExit(n.tokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Session cache hit: ${i.slice(0,8)}... (saved ${n.tokensSaved} tokens)`),{canExit:!0,estimatedTokensSaved:n.tokensSaved,confidence:1,similarityScore:1,reason:"pattern_reused",explanation:`Session cache exact match (fingerprint: ${i.slice(0,8)}...)`,searchLatencyMs:0}}catch{}if(await this.ensurePatternStoreReady(),!this.optimizer)return{canExit:!1,reason:"no_matching_pattern",explanation:"Pattern store unavailable (lazy init failed or disabled)",searchLatencyMs:0};let t=await this.optimizer.checkEarlyExit(e);return t.canExit&&t.estimatedTokensSaved&&(S.recordEarlyExit(t.estimatedTokensSaved),this.config.verbose&&console.log(`[TokenOptimizerService] Early exit: ${t.reusedPattern?.name} (saved ${t.estimatedTokensSaved} tokens)`)),t}async checkTaskEarlyExit(e,t){return this.checkEarlyExit({description:e,domain:t})}recordSuccessfulReuse(e){this.optimizer&&this.optimizer.recordSuccessfulReuse(e)}recordFailedReuse(e){this.optimizer&&this.optimizer.recordFailedReuse(e)}async storePattern(e){if(await this.ensurePatternStoreReady(),!this.patternStore)return null;try{let t=await this.patternStore.store({...e,id:`pattern-${Date.now()}-${H().slice(0,8)}`,createdAt:new Date,lastUsedAt:new Date});return t.success?t.value:null}catch(t){return console.warn("[TokenOptimizerService] Failed to store pattern:",t),null}}getReuseStats(){return this.optimizer?this.optimizer.getReuseStats():null}isEnabled(){return this.initialized&&this.config.enabled}getConfig(){return{...this.config}}getDashboardSummary(){return R()}cacheOperationResult(e,t,r,i,n){try{let s=p(),m=s.computeFingerprint(e,t,r);s.set(m,e,t,i,n)}catch{}}getSessionCacheStats(){try{return p().getStats()}catch{return{size:0,hits:0,misses:0,hitRate:0,estimatedTokensSaved:0}}}reset(){this.optimizer&&this.optimizer.resetStats(),this.optimizer=null,this.patternStore=null,this.initialized=!1,this.readyPromise=null,this.memoryBackend=null,this.config=b}},L=new _;async function ie(a,e){await L.initialize(a,e)}export{p as a,L as b,ie as c};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.7");process.exit(0)}
2
- import{c as g,n as S,o as _}from"./chunk-3M7J4U74.js";function q(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??S()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-KTLZBUWV.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}this.activeSpaceId()||await _();let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-7SXG66IL.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=q(n,this.config.dimensions),g(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(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.15.0");process.exit(0)}
2
+ import{c as g,n as S,o as _}from"./chunk-WPSGMTI4.js";function q(i,e){return{ingest(t){i.ingest(t)},search(t,r){return i.search(t,r).map(s=>({id:s.id,score:s.score}))},delete(t){i.delete(t)},status(){let t=i.status();return{totalVectors:t.totalVectors,dimensions:e,totalSegments:t.totalSegments,fileSizeBytes:t.fileSizeBytes,epoch:t.epoch,witnessValid:t.witnessValid,witnessEntries:t.witnessEntries}},close(){i.close()},compact(){return i.compact()}}}function f(i,e){return(i.prepare("SELECT COUNT(*) as cnt FROM sqlite_master WHERE type='table' AND name=?").get(e)?.cnt??0)>0}function m(i,e,t){return i.prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===t)}var h=class{db;config;rvfStore=null;rvfAvailable=!1;constructor(e,t){this.db=e,this.config={...t,dimensions:t.dimensions??384},f(this.db,"qe_pattern_embeddings")&&!m(this.db,"qe_pattern_embeddings","space_id")&&(this.db.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)"))}activeSpaceId(){return this.config.embeddingSpaceId??S()?.spaceId}async initialize(){if(this.config.mode==="sqlite-only"){this.rvfAvailable=!1;return}try{let e=await import("./rvf-native-adapter-F2I5FFHK.js");if(!e.isRvfNativeAvailable()){this.rvfAvailable=!1;return}this.activeSpaceId()||await _();let{isRvfLockHeldError:t,removeStaleRvfLock:r,quarantineUnusableStore:s}=await import("./rvf-store-integrity-7P5YDXRH.js"),l=()=>{try{return{store:e.openRvfStore(this.config.rvfPath),error:null}}catch(o){return{store:null,error:o}}},{store:n,error:a}=l();if(!n&&t(a)&&(!r(this.config.rvfPath)||({store:n,error:a}=l(),!n&&t(a))))throw a;if(!n)try{n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}catch(o){if({store:n,error:a}=l(),!n){if(t(a))throw a;if(!s(this.config.rvfPath,o instanceof Error?o.message:String(o),a))throw o;n=e.createRvfStore(this.config.rvfPath,this.config.dimensions)}}this.rvfStore=q(n,this.config.dimensions),g(this.config.rvfPath,this.activeSpaceId()??null,this.rvfStore.status().totalVectors),this.rvfAvailable=!0}catch(e){try{this.rvfStore?.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1,console.warn(`[RVF] Dual-writer disabled for ${this.config.rvfPath}; falling back to SQLite: ${e instanceof Error?e.message:String(e)}`)}}setRvfStore(e){this.rvfStore=e,this.rvfAvailable=!0}writePattern(e,t){let r={sqliteSuccess:!1,rvfSuccess:!1};if(!m(this.db,"qe_pattern_embeddings","space_id")||!this.activeSpaceId())return{...r,divergence:"VECTOR_SPACE_UNVERIFIED"};try{this.writeSqliteEmbedding(e,t),r.sqliteSuccess=!0}catch{r.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.ingest([{id:e,vector:t instanceof Float32Array?Array.from(t):t}]),r.rvfSuccess=!0}catch{r.rvfSuccess=!1,r.divergence="rvf-write-failed"}return r}deletePattern(e){let t={sqliteSuccess:!1,rvfSuccess:!1};try{this.deleteSqliteEmbedding(e),t.sqliteSuccess=!0}catch{t.sqliteSuccess=!1}if(this.shouldWriteRvf())try{this.rvfStore.delete([e]),t.rvfSuccess=!0}catch{t.rvfSuccess=!1,t.divergence="rvf-delete-failed"}return t}search(e,t){if(!this.hasCompatibleEmbeddingSpace())return[];if(this.config.mode==="rvf-primary"&&this.rvfAvailable&&this.rvfStore)try{return this.rvfStore.search(e,t)}catch{}return this.searchSqlite(e,t)}getDivergenceReport(){let e={totalChecked:0,divergences:0,details:[]},t=this.getSqliteEmbeddingCount();if(e.totalChecked=t,!this.rvfAvailable||!this.rvfStore)return this.config.mode!=="sqlite-only"&&t>0&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e;let s=this.rvfStore.status().totalVectors;return t!==s&&(e.divergences=1,e.details.push({patternId:"*",issue:"count-mismatch"})),e}isPromotionSafe(){return this.getDivergenceReport().divergences===0}status(){let e=this.getSqlitePatternCount(),t=this.getSqliteEmbeddingCount(),r=null;if(this.rvfAvailable&&this.rvfStore)try{r=this.rvfStore.status()}catch{r=null}return{sqlite:{patternCount:e,vectorCount:t},rvf:r,mode:this.config.mode}}close(){if(this.rvfStore){try{this.rvfStore.close()}catch{}this.rvfStore=null,this.rvfAvailable=!1}}compact(){if(!this.rvfStore||!this.rvfAvailable||!this.rvfStore.compact)return null;try{return this.rvfStore.compact()??null}catch{return null}}shouldWriteRvf(){return(this.config.mode==="dual-write"||this.config.mode==="rvf-primary")&&this.rvfAvailable&&this.rvfStore!==null}hasCompatibleEmbeddingSpace(){if(!m(this.db,"qe_pattern_embeddings","space_id"))return!1;let e=this.activeSpaceId();return e?(this.db.prepare(`
3
3
  SELECT COUNT(*) AS incompatible
4
4
  FROM qe_pattern_embeddings
5
5
  WHERE space_id IS NULL OR space_id <> ?
@@ -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.7");process.exit(0)}
2
- import{b as E,d as S}from"./chunk-OIDWDGLG.js";import{a as D,b as Q}from"./chunk-CBONQM5D.js";import{S as M,l as A}from"./chunk-AEUEMVJK.js";import{f as C}from"./chunk-YO4ESCB4.js";S();M();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(Q(),C(D));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=E(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(A()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.0");process.exit(0)}
2
+ import{b as E,d as S}from"./chunk-ATXAMGVE.js";import{a as D,b as Q}from"./chunk-WBR4VRQE.js";import{S as M,l as A}from"./chunk-URUOTHPO.js";import{f as C}from"./chunk-GX5RFGW2.js";S();M();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(Q(),C(D));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=E(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(A()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};