agentic-qe 3.11.3 → 3.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (426) hide show
  1. package/.claude/hooks/aqe-hook.cjs +44 -10
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +106 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/audit/witness-chain.d.ts +25 -0
  6. package/dist/audit/witness-chain.js +69 -22
  7. package/dist/audit/witness-key-manager.d.ts +11 -0
  8. package/dist/audit/witness-key-manager.js +24 -0
  9. package/dist/cli/brain-commands.js +2 -1
  10. package/dist/cli/bundle.js +5 -5
  11. package/dist/cli/chunks/adapter-KNM5R47J.js +2 -0
  12. package/dist/cli/chunks/{agent-booster-wasm-BFRW7HEU.js → agent-booster-wasm-CSTBLNYZ.js} +2 -2
  13. package/dist/cli/chunks/{agent-handler-ZVC3VFPC.js → agent-handler-M4W4GTXN.js} +2 -2
  14. package/dist/cli/chunks/{agent-memory-branch-3WU3CVSX.js → agent-memory-branch-VGXFYLSQ.js} +2 -2
  15. package/dist/cli/chunks/aqe-learning-engine-MXPJLVR3.js +2 -0
  16. package/dist/cli/chunks/{arena-QMRLNQUC.js → arena-FKSD3LLM.js} +4 -4
  17. package/dist/cli/chunks/{arena-JMVTWWG5.js → arena-IQBRGWAG.js} +2 -2
  18. package/dist/cli/chunks/audit-7NSGRR4Z.js +3 -0
  19. package/dist/cli/chunks/base-X4EXQ2AS.js +2 -0
  20. package/dist/cli/chunks/{hnswlib-node-EBRXKEX5.js → better-sqlite3-2KR4LQRU.js} +2 -2
  21. package/dist/cli/chunks/brain-handler-M6A3UB66.js +89 -0
  22. package/dist/cli/chunks/{branch-enumerator-CJJG6X3I.js → branch-enumerator-2JGKY4BB.js} +2 -2
  23. package/dist/cli/chunks/{browser-LI2CDWVR.js → browser-J43WQPJL.js} +2 -2
  24. package/dist/cli/chunks/browser-workflow-4HX6RP5F.js +2 -0
  25. package/dist/cli/chunks/{chunk-DS7AZD26.js → chunk-26WEI3P4.js} +2 -2
  26. package/dist/cli/chunks/{chunk-OVEG5MEL.js → chunk-2XPMATEK.js} +2 -2
  27. package/dist/cli/chunks/{chunk-36HTS4EP.js → chunk-2XQHG56O.js} +2 -2
  28. package/dist/cli/chunks/{chunk-CGKHG46K.js → chunk-354367AP.js} +2 -2
  29. package/dist/cli/chunks/{chunk-FPKKKUWF.js → chunk-37ZUF5NX.js} +1 -1
  30. package/dist/cli/chunks/{chunk-H7Y43HBQ.js → chunk-3I4TCMOJ.js} +1 -1
  31. package/dist/cli/chunks/{chunk-WV66MXJI.js → chunk-3JF5A72M.js} +2 -2
  32. package/dist/cli/chunks/{chunk-MX5FMAY5.js → chunk-3LY7OCSO.js} +1 -1
  33. package/dist/cli/chunks/{chunk-KHUN65Q3.js → chunk-3V36WMIO.js} +1 -1
  34. package/dist/cli/chunks/{chunk-VFEU4JM4.js → chunk-3WR35GFF.js} +2 -2
  35. package/dist/cli/chunks/{chunk-A43MKBSX.js → chunk-4LODYRNV.js} +2 -2
  36. package/dist/cli/chunks/{chunk-3E3PSEC5.js → chunk-4MHN7JWC.js} +3 -3
  37. package/dist/cli/chunks/chunk-4QOI5JS7.js +14 -0
  38. package/dist/cli/chunks/{chunk-LKLWIP4Z.js → chunk-4RTWPR3X.js} +1 -1
  39. package/dist/cli/chunks/chunk-4XJ2A3HY.js +65 -0
  40. package/dist/cli/chunks/{chunk-PMHSTMHV.js → chunk-4Y3LGBKJ.js} +3 -3
  41. package/dist/cli/chunks/{chunk-SFDBIO64.js → chunk-52U5BFZP.js} +2 -2
  42. package/dist/cli/chunks/{chunk-YPRM6ZFL.js → chunk-53YOYZW5.js} +2 -2
  43. package/dist/cli/chunks/{chunk-REZ2GZQ3.js → chunk-5WMU7XCF.js} +1 -1
  44. package/dist/cli/chunks/{chunk-VUEYLW5P.js → chunk-62OTU2AP.js} +2 -2
  45. package/dist/cli/chunks/{chunk-3XLGXCSX.js → chunk-62UM7Q5N.js} +1 -1
  46. package/dist/cli/chunks/{chunk-DZZ4AJQI.js → chunk-6Q57K4YD.js} +2 -2
  47. package/dist/cli/chunks/chunk-6R3YOAKO.js +2 -0
  48. package/dist/cli/chunks/chunk-6T65OKUM.js +2 -0
  49. package/dist/cli/chunks/{chunk-VTDWQ7WI.js → chunk-7BCRULCP.js} +2 -2
  50. package/dist/cli/chunks/{chunk-XCSEJQXR.js → chunk-7DTMENY6.js} +2 -2
  51. package/dist/cli/chunks/{chunk-N2K2EQFH.js → chunk-7KXPNNMR.js} +2 -2
  52. package/dist/cli/chunks/{chunk-XKUN5PDH.js → chunk-7P6X4BFO.js} +3 -3
  53. package/dist/cli/chunks/{chunk-3CBYKKRW.js → chunk-7YSBATSN.js} +2 -2
  54. package/dist/cli/chunks/{chunk-ZDPQB67L.js → chunk-ABU64UWB.js} +1 -1
  55. package/dist/cli/chunks/{chunk-IJHPZMEQ.js → chunk-AF6P5RWY.js} +2 -2
  56. package/dist/cli/chunks/{chunk-7S7QF4HJ.js → chunk-AGJOGUP5.js} +1 -1
  57. package/dist/cli/chunks/{chunk-EHEFI6LR.js → chunk-AL5VJJN4.js} +1 -1
  58. package/dist/cli/chunks/{chunk-Q2A2XQGF.js → chunk-AOQYORVA.js} +2 -2
  59. package/dist/cli/chunks/{chunk-6WWNK67C.js → chunk-AOXJFDH5.js} +180 -176
  60. package/dist/cli/chunks/{chunk-SWRGPCZ2.js → chunk-AXKWV5NF.js} +4 -4
  61. package/dist/cli/chunks/{chunk-3BREKEL5.js → chunk-B2VBDMDI.js} +2 -2
  62. package/dist/cli/chunks/{chunk-RXN5DWVM.js → chunk-BJLA2IX7.js} +2 -2
  63. package/dist/cli/chunks/{chunk-DPYNXEBC.js → chunk-BLPWJQTY.js} +2 -2
  64. package/dist/cli/chunks/{chunk-SMHYPPO6.js → chunk-BTLUWH4R.js} +2 -2
  65. package/dist/cli/chunks/{chunk-PUK5NE47.js → chunk-C4EZNOWK.js} +1 -1
  66. package/dist/cli/chunks/{chunk-ATFADWGD.js → chunk-C5C4W572.js} +2 -2
  67. package/dist/cli/chunks/{chunk-WTKT2AD3.js → chunk-CDJP6COA.js} +2 -2
  68. package/dist/cli/chunks/{chunk-G6MPXBCD.js → chunk-CKOF27L7.js} +2 -2
  69. package/dist/cli/chunks/{chunk-BQ5EJPK3.js → chunk-D45QLJEL.js} +1 -1
  70. package/dist/cli/chunks/{chunk-WCVZHXWL.js → chunk-DFRRWOEX.js} +2 -2
  71. package/dist/cli/chunks/{chunk-PSL53AQ4.js → chunk-DLBVADWQ.js} +92 -92
  72. package/dist/cli/chunks/{chunk-HRD5I7ES.js → chunk-DPL762HU.js} +1 -1
  73. package/dist/cli/chunks/{chunk-7QIYYYUE.js → chunk-DVW66FPU.js} +1 -1
  74. package/dist/cli/chunks/{chunk-ABD6JBNO.js → chunk-EDOGRFAG.js} +1 -1
  75. package/dist/cli/chunks/{chunk-7SBMTSGY.js → chunk-EEKG35K5.js} +5 -5
  76. package/dist/cli/chunks/{chunk-PW4GGJMP.js → chunk-EK3HPH6A.js} +1 -1
  77. package/dist/cli/chunks/{chunk-QPMISAWB.js → chunk-FGD6HINU.js} +1 -1
  78. package/dist/cli/chunks/{chunk-SLU35IDJ.js → chunk-FGSIID5C.js} +2 -2
  79. package/dist/cli/chunks/{chunk-DNOBN3IR.js → chunk-FHTYEAQ3.js} +2 -2
  80. package/dist/cli/chunks/{chunk-S2T2BXUL.js → chunk-FII3WCCY.js} +2 -2
  81. package/dist/cli/chunks/{chunk-77QJQRL2.js → chunk-FIPKIIMS.js} +2 -2
  82. package/dist/cli/chunks/{chunk-WYJFVSEB.js → chunk-FMNXHVIN.js} +2 -2
  83. package/dist/cli/chunks/{chunk-FZLCKIPP.js → chunk-G2ZIJZJ7.js} +2 -2
  84. package/dist/cli/chunks/{chunk-L6PH7JIE.js → chunk-GODAWJMZ.js} +2 -2
  85. package/dist/cli/chunks/{chunk-KTYESESI.js → chunk-GW6XWMX2.js} +2 -2
  86. package/dist/cli/chunks/{chunk-AC6OZTY4.js → chunk-HC6KTVFR.js} +2 -2
  87. package/dist/cli/chunks/{chunk-EXCU4J7T.js → chunk-HJWT4KME.js} +1 -1
  88. package/dist/cli/chunks/{chunk-GBCDJJWH.js → chunk-I3ANRYQ6.js} +2 -2
  89. package/dist/cli/chunks/{chunk-KXRI4MR3.js → chunk-I3NWKPXJ.js} +2 -2
  90. package/dist/cli/chunks/chunk-IBDQWKI3.js +2 -0
  91. package/dist/cli/chunks/{chunk-7FVWETN4.js → chunk-IU5RSN6M.js} +2 -2
  92. package/dist/cli/chunks/{chunk-L44XXD3X.js → chunk-J5XDKVI7.js} +2 -2
  93. package/dist/cli/chunks/{chunk-NJ2RY4OL.js → chunk-J6PFPY7V.js} +2 -2
  94. package/dist/cli/chunks/{chunk-27MMZQ7X.js → chunk-JATLFS6A.js} +1 -1
  95. package/dist/cli/chunks/{chunk-SIAJP3YA.js → chunk-JBKZ5TUM.js} +2 -2
  96. package/dist/cli/chunks/{chunk-PLQADRA6.js → chunk-JDSHUECG.js} +2 -2
  97. package/dist/cli/chunks/chunk-K4C25BWV.js +24 -0
  98. package/dist/cli/chunks/{chunk-UFZCHVLH.js → chunk-K4I7UIU5.js} +1 -1
  99. package/dist/cli/chunks/{chunk-6F43POT6.js → chunk-KP3R2M2G.js} +1 -1
  100. package/dist/cli/chunks/chunk-KQVIWE3W.js +2 -0
  101. package/dist/cli/chunks/{chunk-JWTMVC6E.js → chunk-KVVJVMDM.js} +2 -2
  102. package/dist/cli/chunks/{chunk-EZ4GKHSI.js → chunk-LOE2JETO.js} +2 -2
  103. package/dist/cli/chunks/{chunk-O7ZDQ5FF.js → chunk-LPR2R3AN.js} +3 -3
  104. package/dist/cli/chunks/{chunk-AKOGQT3A.js → chunk-M6FW56MV.js} +2 -2
  105. package/dist/cli/chunks/{chunk-NBOEXSV2.js → chunk-MCHEUSY4.js} +1 -1
  106. package/dist/cli/chunks/{chunk-B7XPSXK6.js → chunk-MEIU7457.js} +2 -2
  107. package/dist/cli/chunks/{chunk-3FOFPGHH.js → chunk-MHMQ6MCT.js} +2 -2
  108. package/dist/cli/chunks/{chunk-6JR2RSY2.js → chunk-MIU5RUBJ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-QCCXH5DK.js → chunk-MMEXHZUC.js} +37 -12
  110. package/dist/cli/chunks/{chunk-LW5TUN5F.js → chunk-MTBGOWJA.js} +2 -2
  111. package/dist/cli/chunks/{chunk-JVXPKHND.js → chunk-NCSXLMDL.js} +77 -27
  112. package/dist/cli/chunks/{chunk-WLLGPGQY.js → chunk-O7J54OHN.js} +1 -1
  113. package/dist/cli/chunks/{chunk-ZM7WOA3K.js → chunk-OGNTCZKK.js} +1 -1
  114. package/dist/cli/chunks/{chunk-CYJ6O5VZ.js → chunk-OS2HHJTM.js} +2 -2
  115. package/dist/cli/chunks/{chunk-242B625Q.js → chunk-OS62Y77J.js} +2 -2
  116. package/dist/cli/chunks/{chunk-CLZ5RQVA.js → chunk-PVDXNQPL.js} +2 -2
  117. package/dist/cli/chunks/{chunk-PUUGIBFF.js → chunk-PW72M2FE.js} +2 -2
  118. package/dist/cli/chunks/{chunk-RWUGXU2K.js → chunk-Q5TR6ETB.js} +22 -22
  119. package/dist/cli/chunks/{chunk-CCDGNJZX.js → chunk-QKK7VBVB.js} +2 -2
  120. package/dist/cli/chunks/{chunk-BHZI6PDR.js → chunk-RFLHPLET.js} +1 -1
  121. package/dist/cli/chunks/{chunk-KULBMV6K.js → chunk-RJN2RM76.js} +2 -2
  122. package/dist/cli/chunks/{chunk-LGEZ3ZJX.js → chunk-RKXZLTWR.js} +2 -2
  123. package/dist/cli/chunks/{chunk-OFMVC6P3.js → chunk-SE3JFUKP.js} +1 -1
  124. package/dist/cli/chunks/{chunk-S7KDHA6P.js → chunk-SK754ZSH.js} +4 -4
  125. package/dist/cli/chunks/{chunk-OQGELUM2.js → chunk-SO6G4IX3.js} +2 -2
  126. package/dist/cli/chunks/{chunk-5746QYRF.js → chunk-SUL3I6QZ.js} +2 -2
  127. package/dist/cli/chunks/{chunk-22CUJA33.js → chunk-TBT3OFRW.js} +2 -2
  128. package/dist/cli/chunks/{chunk-26KHL4VO.js → chunk-TEIWJ3GJ.js} +1 -1
  129. package/dist/cli/chunks/{chunk-SFGBC5RP.js → chunk-TRNBQFFG.js} +8 -20
  130. package/dist/cli/chunks/{chunk-UTGW75AZ.js → chunk-TTJJ4DQE.js} +2 -2
  131. package/dist/cli/chunks/{chunk-H6YFMUFG.js → chunk-UBI2EOS3.js} +1 -1
  132. package/dist/cli/chunks/{chunk-GCIL7PK7.js → chunk-UBY322ED.js} +2 -2
  133. package/dist/cli/chunks/{chunk-P4UGVVVX.js → chunk-UORTQXJ2.js} +1 -1
  134. package/dist/cli/chunks/{chunk-BFBZFUBP.js → chunk-URP75DL4.js} +1 -1
  135. package/dist/cli/chunks/chunk-V6NAB5UZ.js +2 -0
  136. package/dist/cli/chunks/{chunk-DZ7PWB6E.js → chunk-VMFAANWX.js} +2 -2
  137. package/dist/cli/chunks/{chunk-6KKKPVOF.js → chunk-VMWRMINE.js} +1 -1
  138. package/dist/cli/chunks/{chunk-ECGASTG7.js → chunk-VN2HHBZN.js} +2 -2
  139. package/dist/cli/chunks/{chunk-6GVRP64A.js → chunk-W72FJA2H.js} +2 -2
  140. package/dist/cli/chunks/chunk-W7TYKPLY.js +27 -0
  141. package/dist/cli/chunks/{chunk-2OUXYSQV.js → chunk-WHHQIL4F.js} +2 -2
  142. package/dist/cli/chunks/{chunk-RRSUW2TK.js → chunk-WMZ2QGGS.js} +2 -2
  143. package/dist/cli/chunks/{chunk-54TDOQAH.js → chunk-WPSK237F.js} +3 -3
  144. package/dist/cli/chunks/{chunk-LMA6KEZH.js → chunk-XKQY2Z3Q.js} +1 -1
  145. package/dist/cli/chunks/{chunk-UMWYL37S.js → chunk-XLT3FYS7.js} +2 -2
  146. package/dist/cli/chunks/{chunk-5EW36WTI.js → chunk-XT4TDLOB.js} +2 -2
  147. package/dist/cli/chunks/{chunk-7UOH55UT.js → chunk-Y25PO65W.js} +2 -2
  148. package/dist/cli/chunks/{chunk-ED7MD6OI.js → chunk-Y6DWJKHU.js} +3 -3
  149. package/dist/cli/chunks/{chunk-A4NYOH7P.js → chunk-YBPLJRVT.js} +2 -2
  150. package/dist/cli/chunks/{chunk-BA7PJS3Y.js → chunk-YFCULQBP.js} +2 -2
  151. package/dist/cli/chunks/{chunk-B65CRJN6.js → chunk-YGVDP6X7.js} +1 -1
  152. package/dist/cli/chunks/chunk-YR2JKBZO.js +2 -0
  153. package/dist/cli/chunks/{chunk-FJRRXCIS.js → chunk-YZSTZUGJ.js} +1 -1
  154. package/dist/cli/chunks/{chunk-H2YOWAEB.js → chunk-ZG5UAEEO.js} +2 -2
  155. package/dist/cli/chunks/{chunk-MU36VPXV.js → chunk-ZLBY25MB.js} +1 -1
  156. package/dist/cli/chunks/chunk-ZMPAM4DY.js +2 -0
  157. package/dist/cli/chunks/{chunk-4ITHKHR5.js → chunk-ZPP57WQU.js} +2 -2
  158. package/dist/cli/chunks/{chunk-B6USJW5E.js → chunk-ZXEWTZFR.js} +1 -1
  159. package/dist/cli/chunks/{ci-JW4O2J3W.js → ci-CBNVLOOQ.js} +2 -2
  160. package/dist/cli/chunks/{ci-output-JNXJV4B2.js → ci-output-I4HY2FYJ.js} +2 -2
  161. package/dist/cli/chunks/{circuit-breaker-XDD4KUGR.js → circuit-breaker-5VRBKGWL.js} +2 -2
  162. package/dist/cli/chunks/{claude-flow-setup-L6IZOGYZ.js → claude-flow-setup-XPJPKHIO.js} +2 -2
  163. package/dist/cli/chunks/client-AHXNCOHK.js +2 -0
  164. package/dist/cli/chunks/{cline-installer-PK5SMN2B.js → cline-installer-OFRDUUWZ.js} +2 -2
  165. package/dist/cli/chunks/{code-ZDVX3SQH.js → code-QIZQVB3E.js} +2 -2
  166. package/dist/cli/chunks/{code-index-extractor-VXZNKEU5.js → code-index-extractor-LMUUWEX4.js} +2 -2
  167. package/dist/cli/chunks/{codex-installer-OXKSIX7H.js → codex-installer-N2MKIZ2S.js} +2 -2
  168. package/dist/cli/chunks/{completions-VRFFK223.js → completions-Y36S3C5J.js} +2 -2
  169. package/dist/cli/chunks/{complexity-analyzer-FTIMV74J.js → complexity-analyzer-73YS3WUD.js} +2 -2
  170. package/dist/cli/chunks/{continuedev-installer-KTYBBPN4.js → continuedev-installer-SAOTP6J3.js} +2 -2
  171. package/dist/cli/chunks/{copilot-installer-WDC3YNUR.js → copilot-installer-A4HXF6HE.js} +2 -2
  172. package/dist/cli/chunks/core-handlers-EEFLLMAZ.js +2 -0
  173. package/dist/cli/chunks/{cost-tracker-6MH4H33B.js → cost-tracker-P26XUVZS.js} +2 -2
  174. package/dist/cli/chunks/{coverage-NHATLNS4.js → coverage-HVNHSMVJ.js} +3 -3
  175. package/dist/cli/chunks/cross-domain-router-LT3H4SNJ.js +2 -0
  176. package/dist/cli/chunks/{cursor-installer-VQSUJDFB.js → cursor-installer-46BQFTYZ.js} +2 -2
  177. package/dist/cli/chunks/{daemon-3VAOEKQW.js → daemon-Y54O3FLT.js} +3 -3
  178. package/dist/cli/chunks/daemon-YE7K2AZF.js +10 -0
  179. package/dist/cli/chunks/{dag-attention-scheduler-HZ6OGYIH.js → dag-attention-scheduler-ETA7YY52.js} +2 -2
  180. package/dist/cli/chunks/{detect-CGU3SC63.js → detect-5WLQ2J3E.js} +2 -2
  181. package/dist/cli/chunks/{dist-node-DIBQ7PTA.js → dist-node-45WW6I7J.js} +2 -2
  182. package/dist/cli/chunks/{domain-handler-DCMGAYXS.js → domain-handler-J7DQV74M.js} +2 -2
  183. package/dist/cli/chunks/domain-transfer-GD2EGQVR.js +2 -0
  184. package/dist/cli/chunks/dream-4K3BK4IG.js +2 -0
  185. package/dist/cli/chunks/{embed-and-insert-pattern-7247LAU3.js → embed-and-insert-pattern-JELNEA2D.js} +2 -2
  186. package/dist/cli/chunks/{eval-6KR7TFOK.js → eval-A4PA5G2U.js} +2 -2
  187. package/dist/cli/chunks/{experience-capture-middleware-IIOR6RVV.js → experience-capture-middleware-MLHTYWTA.js} +3 -3
  188. package/dist/cli/chunks/{fast-paths-M7OGD4ZI.js → fast-paths-QYDTITRV.js} +2 -2
  189. package/dist/cli/chunks/{feature-flags-U75KFIGH.js → feature-flags-H4MSY26Z.js} +2 -2
  190. package/dist/cli/chunks/{feature-flags-GGUXHRJI.js → feature-flags-MQYYRHIK.js} +2 -2
  191. package/dist/cli/chunks/{file-discovery-V52AYEB7.js → file-discovery-RMFVJNGL.js} +2 -2
  192. package/dist/cli/chunks/{fleet-2UH72CK4.js → fleet-7KZQOTAC.js} +4 -4
  193. package/dist/cli/chunks/{gnn-wrapper-J2GDLT3P.js → gnn-wrapper-NMZFTGVH.js} +2 -2
  194. package/dist/cli/chunks/{heartbeat-handler-QIDQHRXT.js → heartbeat-handler-7BQDK7MG.js} +4 -4
  195. package/dist/cli/chunks/heartbeat-scheduler-IMPPGQUK.js +2 -0
  196. package/dist/cli/chunks/hnsw-adapter-EIAA6R2L.js +2 -0
  197. package/dist/cli/chunks/hnsw-index-ZXXP6AXZ.js +2 -0
  198. package/dist/cli/chunks/{hnsw-legacy-bridge-IU62PIY5.js → hnsw-legacy-bridge-TPPGBPKF.js} +2 -2
  199. package/dist/cli/chunks/{better-sqlite3-QNZJOJAB.js → hnswlib-node-E6NSZPP2.js} +2 -2
  200. package/dist/cli/chunks/{hooks-ZI4D3ATS.js → hooks-CYZIUYSH.js} +48 -52
  201. package/dist/cli/chunks/hybrid-router-LXWG4MLH.js +2 -0
  202. package/dist/cli/chunks/{hypergraph-engine-6JEERAGA.js → hypergraph-engine-WC6DMTYQ.js} +2 -2
  203. package/dist/cli/chunks/{hypergraph-handler-YMDGYCB6.js → hypergraph-handler-GTGA3TXJ.js} +3 -3
  204. package/dist/cli/chunks/impact-analyzer-TP5LRFYH.js +2 -0
  205. package/dist/cli/chunks/{init-handler-N57NW3QI.js → init-handler-N3Z72JNI.js} +6 -6
  206. package/dist/cli/chunks/init-wizard-AIOA5KOY.js +2 -0
  207. package/dist/cli/chunks/kernel-SQALRU6Q.js +2 -0
  208. package/dist/cli/chunks/{kilocode-installer-7ABTGXJ5.js → kilocode-installer-FUX4V6II.js} +2 -2
  209. package/dist/cli/chunks/{kiro-installer-2JFOHLVI.js → kiro-installer-ZSNZT7ZR.js} +2 -2
  210. package/dist/cli/chunks/knowledge-graph-JFVT6SNN.js +2 -0
  211. package/dist/cli/chunks/{learning-3P3ZXRGD.js → learning-UQY64COU.js} +3 -3
  212. package/dist/cli/chunks/{llm-router-AWB2KHDW.js → llm-router-CMHGGX6N.js} +4 -4
  213. package/dist/cli/chunks/llm-router-service-XHFKTH3I.js +2 -0
  214. package/dist/cli/chunks/{load-GGVBCBGX.js → load-E6WH4QN2.js} +2 -2
  215. package/dist/cli/chunks/load-test-JEIFJKNN.js +2 -0
  216. package/dist/cli/chunks/{mcp-33NHIBN3.js → mcp-UM5VTW6N.js} +2 -2
  217. package/dist/cli/chunks/{memory-IVAQS4OW.js → memory-7Q3XDUE5.js} +5 -5
  218. package/dist/cli/chunks/memory-backend-NT7I37CP.js +2 -0
  219. package/dist/cli/chunks/memory-handlers-746D7NE7.js +2 -0
  220. package/dist/cli/chunks/{multi-model-executor-NWQY6IN2.js → multi-model-executor-LZENWVRR.js} +2 -2
  221. package/dist/cli/chunks/{opencode-installer-FBB4JOEV.js → opencode-installer-O2JAIPLF.js} +2 -2
  222. package/dist/cli/chunks/{orchestrator-GDAXR7DH.js → orchestrator-DKZWXDRI.js} +5 -5
  223. package/dist/cli/chunks/pattern-null-store-6QU6WHDW.js +2 -0
  224. package/dist/cli/chunks/pattern-usage-recorder-CLUL4M55.js +2 -0
  225. package/dist/cli/chunks/{pipeline-VIKAOIBE.js → pipeline-2VDLTR5J.js} +2 -2
  226. package/dist/cli/chunks/{platform-FFVP36LH.js → platform-4N4Q5XYX.js} +2 -2
  227. package/dist/cli/chunks/{plugin-TI6QOLXH.js → plugin-GY5AU5CS.js} +2 -2
  228. package/dist/cli/chunks/{prime-radiant-advanced-wasm-AZRNI2OL.js → prime-radiant-advanced-wasm-TQ4DKDZS.js} +2 -2
  229. package/dist/cli/chunks/protocol-executor-GT2MZYUU.js +2 -0
  230. package/dist/cli/chunks/{protocol-handler-J4EA34B3.js → protocol-handler-T3LZ3WRG.js} +2 -2
  231. package/dist/cli/chunks/{prove-ADVRMAWS.js → prove-OV7S5J4W.js} +2 -2
  232. package/dist/cli/chunks/provider-manager-OATJ7R3D.js +2 -0
  233. package/dist/cli/chunks/qe-reasoning-bank-IJXNQ67O.js +2 -0
  234. package/dist/cli/chunks/{quality-GB5SJFSD.js → quality-AXD4NLQA.js} +2 -2
  235. package/dist/cli/chunks/queen-coordinator-6RBHWCUG.js +2 -0
  236. package/dist/cli/chunks/{real-embeddings-GDRJ4XSH.js → real-embeddings-2PUCC7FG.js} +2 -2
  237. package/dist/cli/chunks/{roocode-installer-Q6EISUDV.js → roocode-installer-WJ5ARGLW.js} +2 -2
  238. package/dist/cli/chunks/router-XKQRT5JK.js +2 -0
  239. package/dist/cli/chunks/routing-feedback-ACPSD4LW.js +2 -0
  240. package/dist/cli/chunks/{routing-handler-RO4RTRAG.js → routing-handler-CU6657SZ.js} +2 -2
  241. package/dist/cli/chunks/{ruvector-commands-FFIHCGVQ.js → ruvector-commands-IIF6VSFW.js} +2 -2
  242. package/dist/cli/chunks/{rvf-dual-writer-JGEK3A5Y.js → rvf-dual-writer-YMQI7XO2.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-adapter-OVYC4QM6.js → rvf-migration-adapter-HDE3PR2W.js} +2 -2
  244. package/dist/cli/chunks/{rvf-migration-coordinator-U6L77QTS.js → rvf-migration-coordinator-MQV5OA7K.js} +2 -2
  245. package/dist/cli/chunks/rvf-native-adapter-SIWRKE33.js +2 -0
  246. package/dist/cli/chunks/safe-db-LCPUYMX4.js +2 -0
  247. package/dist/cli/chunks/schedule-HIQJCWXG.js +2 -0
  248. package/dist/cli/chunks/scheduler-QE5EJ5LE.js +2 -0
  249. package/dist/cli/chunks/{security-QPQIDAIL.js → security-UM3IGDSM.js} +3 -3
  250. package/dist/cli/chunks/{shared-rvf-adapter-JRJTI4UD.js → shared-rvf-adapter-I3SOJ6M4.js} +2 -2
  251. package/dist/cli/chunks/{shared-rvf-dual-writer-DSHGURDA.js → shared-rvf-dual-writer-KQGC2UO7.js} +2 -2
  252. package/dist/cli/chunks/sqlite-persistence-EU54UTMH.js +2 -0
  253. package/dist/cli/chunks/status-handler-OX4CJZME.js +46 -0
  254. package/dist/cli/chunks/{structural-health-UVECCN7U.js → structural-health-PYUMVBXJ.js} +2 -2
  255. package/dist/cli/chunks/{sync-XXIGTGCG.js → sync-2TED3YTY.js} +2 -2
  256. package/dist/cli/chunks/{sync-ZLZ4CZFJ.js → sync-VALFNTA6.js} +2 -2
  257. package/dist/cli/chunks/{task-handler-73YAVOKJ.js → task-handler-VPGAJVPC.js} +2 -2
  258. package/dist/cli/chunks/{task-handlers-PKECV27D.js → task-handlers-IB4UAMU6.js} +3 -3
  259. package/dist/cli/chunks/{test-U3SXW4SV.js → test-OMRJOZB6.js} +4 -4
  260. package/dist/cli/chunks/{test-scheduling-POJND3GV.js → test-scheduling-ZL3YFPBU.js} +3 -3
  261. package/dist/cli/chunks/{token-bootstrap-ICX6SIXJ.js → token-bootstrap-DNWZI7SH.js} +2 -2
  262. package/dist/cli/chunks/{token-usage-WCHJUVGT.js → token-usage-IYO7RGFF.js} +2 -2
  263. package/dist/cli/chunks/{transformers-L77UIHIY.js → transformers-53ALC34T.js} +2 -2
  264. package/dist/cli/chunks/{tree-sitter-wasm-parser-CVAXURQP.js → tree-sitter-wasm-parser-WUKJ2I2Q.js} +2 -2
  265. package/dist/cli/chunks/{types-LNVJBDM2.js → types-47FTEPMV.js} +2 -2
  266. package/dist/cli/chunks/unified-memory-CJLMC2I4.js +2 -0
  267. package/dist/cli/chunks/unified-memory-hnsw-FDGR4D2J.js +2 -0
  268. package/dist/cli/chunks/unified-persistence-UFH5GLDN.js +2 -0
  269. package/dist/cli/chunks/{upgrade-4ND5RQFY.js → upgrade-QPLMJA5Z.js} +2 -2
  270. package/dist/cli/chunks/{validate-ZA4XT6K2.js → validate-3GVKZOVF.js} +2 -2
  271. package/dist/cli/chunks/{validate-swarm-FNK3GCJ4.js → validate-swarm-XCRTLVM6.js} +2 -2
  272. package/dist/cli/chunks/{vibium-E2CK2GBQ.js → vibium-CH4VPKVZ.js} +2 -2
  273. package/dist/cli/chunks/visual-security-4ARJ7J2Y.js +2 -0
  274. package/dist/cli/chunks/{web-tree-sitter-63VRNKZV.js → web-tree-sitter-JDBNAZTV.js} +2 -2
  275. package/dist/cli/chunks/{windsurf-installer-5BTCVOLH.js → windsurf-installer-3MNPVJBP.js} +2 -2
  276. package/dist/cli/chunks/witness-chain-73QC33ED.js +2 -0
  277. package/dist/cli/chunks/{witness-chain-6CUUGISD.js → witness-chain-HR5UBV5J.js} +2 -2
  278. package/dist/cli/chunks/witness-key-manager-G5SQTIBZ.js +2 -0
  279. package/dist/cli/chunks/{workflow-V7ED22XT.js → workflow-43EMD5FY.js} +4 -4
  280. package/dist/cli/chunks/workflow-orchestrator-RKMMPXNA.js +2 -0
  281. package/dist/cli/chunks/{wrappers-7S3NTTLW.js → wrappers-3N7AYNM3.js} +2 -2
  282. package/dist/cli/commands/audit.d.ts +12 -0
  283. package/dist/cli/commands/audit.js +64 -4
  284. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +45 -19
  285. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +13 -0
  286. package/dist/cli/commands/hooks-handlers/hooks-shared.js +38 -0
  287. package/dist/cli/commands/hooks-handlers/task-hooks.js +19 -1
  288. package/dist/cli/handlers/status-handler.d.ts +18 -0
  289. package/dist/cli/handlers/status-handler.js +47 -0
  290. package/dist/coordination/consensus/providers/ollama-provider.js +3 -2
  291. package/dist/coordination/mincut/queen-integration.js +24 -7
  292. package/dist/coordination/protocol-executor.js +2 -1
  293. package/dist/coordination/queen-lifecycle.js +4 -1
  294. package/dist/domains/code-intelligence/coordinator.js +10 -6
  295. package/dist/domains/code-intelligence/services/product-factors-bridge.js +3 -1
  296. package/dist/domains/defect-intelligence/services/defect-predictor.d.ts +6 -0
  297. package/dist/domains/defect-intelligence/services/defect-predictor.js +21 -0
  298. package/dist/domains/learning-optimization/interfaces.d.ts +7 -0
  299. package/dist/domains/learning-optimization/plugin.js +5 -0
  300. package/dist/domains/learning-optimization/services/learning-coordinator.d.ts +10 -0
  301. package/dist/domains/learning-optimization/services/learning-coordinator.js +57 -0
  302. package/dist/domains/test-execution/plugin.js +2 -2
  303. package/dist/domains/test-execution/services/flaky-detector.js +1 -1
  304. package/dist/domains/test-generation/coordinator.js +22 -8
  305. package/dist/domains/test-generation/interfaces.d.ts +3 -0
  306. package/dist/domains/test-generation/services/test-generator.js +9 -1
  307. package/dist/integrations/ruvector/delta-tracker.js +10 -1
  308. package/dist/integrations/ruvector/proof-gate.d.ts +68 -0
  309. package/dist/integrations/ruvector/proof-gate.js +135 -0
  310. package/dist/integrations/ruvector/sona-persistence.d.ts +24 -0
  311. package/dist/integrations/ruvector/sona-persistence.js +76 -0
  312. package/dist/integrations/ruvector/sona-three-loop.d.ts +15 -0
  313. package/dist/integrations/ruvector/sona-three-loop.js +17 -0
  314. package/dist/kernel/unified-memory-schemas.d.ts +2 -2
  315. package/dist/kernel/unified-memory-schemas.js +48 -2
  316. package/dist/kernel/unified-memory.d.ts +57 -0
  317. package/dist/kernel/unified-memory.js +148 -0
  318. package/dist/learning/aqe-learning-engine.js +3 -1
  319. package/dist/learning/dream/concept-graph.d.ts +31 -1
  320. package/dist/learning/dream/concept-graph.js +109 -3
  321. package/dist/learning/dream/dream-engine.d.ts +13 -1
  322. package/dist/learning/dream/dream-engine.js +146 -10
  323. package/dist/learning/dream/index.d.ts +1 -1
  324. package/dist/learning/dream/types.d.ts +23 -0
  325. package/dist/learning/local-judge-client.js +2 -1
  326. package/dist/learning/pattern-store.d.ts +2 -2
  327. package/dist/learning/pattern-store.js +14 -3
  328. package/dist/learning/qe-reasoning-bank.js +34 -31
  329. package/dist/learning/routing-topology-gate.d.ts +12 -2
  330. package/dist/learning/routing-topology-gate.js +15 -3
  331. package/dist/learning/rvf-pattern-store.d.ts +1 -1
  332. package/dist/learning/rvf-pattern-store.js +21 -8
  333. package/dist/learning/sqlite-persistence.js +12 -9
  334. package/dist/mcp/bundle.js +524 -445
  335. package/dist/mcp/qe-tool-bridge.js +7 -2
  336. package/dist/mcp/tools/base.d.ts +29 -0
  337. package/dist/mcp/tools/base.js +25 -0
  338. package/dist/mcp/tools/coverage-analysis/index.js +6 -4
  339. package/dist/mcp/tools/learning-optimization/dream.d.ts +4 -13
  340. package/dist/mcp/tools/learning-optimization/dream.js +10 -96
  341. package/dist/mcp/tools/planning/goap-execute.d.ts +13 -1
  342. package/dist/mcp/tools/planning/goap-execute.js +33 -18
  343. package/dist/mcp/tools/registry.js +7 -2
  344. package/dist/persistence/rvf-migration-coordinator.js +2 -1
  345. package/dist/planning/actions/qe-action-library.js +124 -1
  346. package/dist/planning/goap-planner.d.ts +14 -2
  347. package/dist/planning/goap-planner.js +51 -9
  348. package/dist/planning/index.d.ts +1 -1
  349. package/dist/planning/plan-executor.d.ts +84 -4
  350. package/dist/planning/plan-executor.js +221 -56
  351. package/dist/planning/types.d.ts +27 -0
  352. package/dist/routing/free-tier/coordinator-support.d.ts +6 -3
  353. package/dist/routing/free-tier/coordinator-support.js +6 -3
  354. package/dist/routing/free-tier/executor.d.ts +14 -0
  355. package/dist/routing/free-tier/executor.js +21 -0
  356. package/dist/routing/free-tier/index.d.ts +1 -0
  357. package/dist/routing/free-tier/index.js +1 -0
  358. package/dist/routing/free-tier/pattern-cache.d.ts +57 -0
  359. package/dist/routing/free-tier/pattern-cache.js +148 -0
  360. package/dist/routing/free-tier/provider.js +9 -1
  361. package/dist/routing/value-score.js +3 -0
  362. package/dist/shared/embeddings/ollama-client.js +2 -1
  363. package/dist/shared/events/domain-events.d.ts +2 -0
  364. package/dist/shared/llm/model-mapping.js +26 -0
  365. package/dist/shared/llm/model-registry.d.ts +10 -0
  366. package/dist/shared/llm/model-registry.js +92 -0
  367. package/dist/shared/llm/ollama-url.d.ts +17 -0
  368. package/dist/shared/llm/ollama-url.js +25 -0
  369. package/dist/shared/llm/providers/ollama-timeout.d.ts +26 -0
  370. package/dist/shared/llm/providers/ollama-timeout.js +31 -0
  371. package/dist/shared/llm/providers/ollama.d.ts +10 -0
  372. package/dist/shared/llm/providers/ollama.js +31 -4
  373. package/dist/shared/llm/router/hybrid-router.js +18 -1
  374. package/dist/workers/workers/learning-consolidation.js +21 -1
  375. package/package.json +5 -1
  376. package/dist/cli/chunks/adapter-IU3H3MD7.js +0 -2
  377. package/dist/cli/chunks/aqe-learning-engine-BGOC63IN.js +0 -2
  378. package/dist/cli/chunks/audit-TTWAAV7P.js +0 -3
  379. package/dist/cli/chunks/base-DVPRE3WO.js +0 -2
  380. package/dist/cli/chunks/brain-handler-FXPLJCPV.js +0 -89
  381. package/dist/cli/chunks/browser-workflow-MP5P7KZF.js +0 -2
  382. package/dist/cli/chunks/chunk-2SZQDTI5.js +0 -2
  383. package/dist/cli/chunks/chunk-6IHB3T6M.js +0 -2
  384. package/dist/cli/chunks/chunk-7PDUD7FF.js +0 -2
  385. package/dist/cli/chunks/chunk-EBCUWMLX.js +0 -27
  386. package/dist/cli/chunks/chunk-NWUVXLBB.js +0 -65
  387. package/dist/cli/chunks/chunk-OCACCUFO.js +0 -2
  388. package/dist/cli/chunks/chunk-PY2Q6MN3.js +0 -24
  389. package/dist/cli/chunks/chunk-UNH2DE2G.js +0 -2
  390. package/dist/cli/chunks/client-ADCDBTEE.js +0 -2
  391. package/dist/cli/chunks/core-handlers-HCACMLUW.js +0 -2
  392. package/dist/cli/chunks/cross-domain-router-HXFQAU4M.js +0 -2
  393. package/dist/cli/chunks/daemon-ZSK6CLQR.js +0 -10
  394. package/dist/cli/chunks/domain-transfer-UWFKBZTJ.js +0 -2
  395. package/dist/cli/chunks/dream-SVWQH62A.js +0 -2
  396. package/dist/cli/chunks/heartbeat-scheduler-QW5TW5QS.js +0 -2
  397. package/dist/cli/chunks/hnsw-adapter-D6EJWYAL.js +0 -2
  398. package/dist/cli/chunks/hnsw-index-4MWR4U5W.js +0 -2
  399. package/dist/cli/chunks/hybrid-router-BYVUBHER.js +0 -2
  400. package/dist/cli/chunks/impact-analyzer-OK2UIMSG.js +0 -2
  401. package/dist/cli/chunks/init-wizard-6NNPNS6J.js +0 -2
  402. package/dist/cli/chunks/kernel-F4A4GRNO.js +0 -2
  403. package/dist/cli/chunks/knowledge-graph-MSJDEZCF.js +0 -2
  404. package/dist/cli/chunks/llm-router-service-27IQAO7G.js +0 -2
  405. package/dist/cli/chunks/load-test-TT5VLAN7.js +0 -2
  406. package/dist/cli/chunks/memory-backend-FVSK53IM.js +0 -2
  407. package/dist/cli/chunks/memory-handlers-OPUDOZNT.js +0 -2
  408. package/dist/cli/chunks/pattern-null-store-7MVEDWCY.js +0 -2
  409. package/dist/cli/chunks/protocol-executor-BLDDYEJ4.js +0 -2
  410. package/dist/cli/chunks/provider-manager-ZYCFRYZQ.js +0 -2
  411. package/dist/cli/chunks/qe-reasoning-bank-P66CCPHM.js +0 -2
  412. package/dist/cli/chunks/queen-coordinator-LPHT3SX5.js +0 -2
  413. package/dist/cli/chunks/router-XQ2TERUT.js +0 -2
  414. package/dist/cli/chunks/routing-feedback-K52O752B.js +0 -2
  415. package/dist/cli/chunks/rvf-native-adapter-G4DV7FK3.js +0 -2
  416. package/dist/cli/chunks/safe-db-TMSEITES.js +0 -2
  417. package/dist/cli/chunks/schedule-RWFLA43O.js +0 -2
  418. package/dist/cli/chunks/scheduler-2V55MJJR.js +0 -2
  419. package/dist/cli/chunks/sqlite-persistence-L7QM6IWF.js +0 -2
  420. package/dist/cli/chunks/status-handler-SBT3MZTX.js +0 -45
  421. package/dist/cli/chunks/unified-memory-ZSULA46X.js +0 -2
  422. package/dist/cli/chunks/unified-memory-hnsw-SQEWFUBN.js +0 -2
  423. package/dist/cli/chunks/unified-persistence-EDCTT6SE.js +0 -2
  424. package/dist/cli/chunks/visual-security-SOGAETFP.js +0 -2
  425. package/dist/cli/chunks/witness-chain-AJCECBH5.js +0 -2
  426. package/dist/cli/chunks/workflow-orchestrator-UXRUCOZR.js +0 -2
@@ -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.11.3");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.11.5");process.exit(0)}
@@ -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.11.3");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.11.5");process.exit(0)}
2
2
  import*as o from"fs";import*as l from"path";var m=class{cacheDir;keepVersions;constructor(e={}){this.cacheDir=e.cacheDir??l.join(process.cwd(),".agentic-qe","plugins"),this.keepVersions=e.keepVersions??2}has(e,t){let s=this.versionDir(e,t);return o.existsSync(s)&&o.existsSync(l.join(s,"qe-plugin.json"))}get(e,t){if(!this.has(e,t))return;let s=this.versionDir(e,t),i=o.readFileSync(l.join(s,"qe-plugin.json"),"utf-8"),r=JSON.parse(i),c=o.statSync(s);return{manifest:r,path:s,cachedAt:c.birthtime.toISOString()}}store(e,t){let s=this.versionDir(e.name,e.version);return o.existsSync(s)||(o.mkdirSync(s,{recursive:!0}),this.copyDir(t,s),o.writeFileSync(l.join(s,"qe-plugin.json"),JSON.stringify(e,null,2)),this.pruneOldVersions(e.name)),s}remove(e,t){let s=this.versionDir(e,t);return o.existsSync(s)?(o.rmSync(s,{recursive:!0,force:!0}),!0):!1}listVersions(e){let t=l.join(this.cacheDir,e);if(!o.existsSync(t))return[];let s=[],i=o.readdirSync(t);for(let r of i){let c=l.join(t,r),h=l.join(c,"qe-plugin.json");if(o.existsSync(h))try{let a=o.readFileSync(h,"utf-8"),f=JSON.parse(a),u=o.statSync(c);s.push({manifest:f,path:c,cachedAt:u.birthtime.toISOString()})}catch{}}return s}listAll(){if(!o.existsSync(this.cacheDir))return[];let e=[],t=o.readdirSync(this.cacheDir);for(let s of t){let i=this.listVersions(s);i.length>0&&(i.sort((r,c)=>c.manifest.version.localeCompare(r.manifest.version)),e.push(i[0]))}return e}versionDir(e,t){return l.join(this.cacheDir,e,t)}pruneOldVersions(e){let t=this.listVersions(e);if(t.length<=this.keepVersions)return;t.sort((i,r)=>i.cachedAt.localeCompare(r.cachedAt));let s=t.slice(0,t.length-this.keepVersions);for(let i of s)o.rmSync(i.path,{recursive:!0,force:!0})}copyDir(e,t){if(!o.existsSync(e))return;let s=o.readdirSync(e,{withFileTypes:!0});for(let i of s){let r=l.join(e,i.name),c=l.join(t,i.name);if(i.isDirectory()){if(i.name===".git"||i.name==="node_modules")continue;o.mkdirSync(c,{recursive:!0}),this.copyDir(r,c)}else o.copyFileSync(r,c)}}};var R=/^[a-z][a-z0-9-]*$/,S=/^\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/,j=["aqe-core-","agentic-qe-core-"];function E(n){let e=[],t=[];if(!n||typeof n!="object")return{valid:!1,errors:["Manifest must be a non-null object"],warnings:[]};let s=n;if(!s.name||typeof s.name!="string"?e.push("name is required and must be a string"):D(s.name,e,t),!s.version||typeof s.version!="string"?e.push("version is required and must be a string"):S.test(s.version)||e.push(`version "${s.version}" is not valid semver (expected: major.minor.patch)`),!s.description||typeof s.description!="string"?e.push("description is required and must be a string"):s.description.length>500&&t.push("description exceeds 500 characters"),(!s.author||typeof s.author!="string")&&e.push("author is required and must be a string"),!Array.isArray(s.domains)||s.domains.length===0)e.push("domains is required and must be a non-empty array");else for(let i of s.domains)if(typeof i!="string"){e.push("Each domain must be a string");break}if(!s.entryPoint||typeof s.entryPoint!="string"?e.push("entryPoint is required and must be a string"):V(s.entryPoint,e),s.dependencies!==void 0)if(typeof s.dependencies!="object"||s.dependencies===null||Array.isArray(s.dependencies))e.push("dependencies must be an object mapping plugin names to semver ranges");else for(let[i,r]of Object.entries(s.dependencies))typeof r!="string"&&e.push(`Dependency "${i}" must have a string version range`);if(s.hooks!==void 0)if(typeof s.hooks!="object"||s.hooks===null||Array.isArray(s.hooks))e.push("hooks must be an object mapping event names to handler paths");else for(let[,i]of Object.entries(s.hooks)){if(typeof i!="string"){e.push("Hook handler paths must be strings");break}i.includes("..")&&e.push(`Hook handler path "${i}" must not contain ".." (path traversal)`)}if(s.minAqeVersion!==void 0&&(typeof s.minAqeVersion!="string"||!S.test(s.minAqeVersion))&&t.push("minAqeVersion should be valid semver"),s.permissions!==void 0){if(!Array.isArray(s.permissions))e.push("permissions must be an array of strings");else for(let i of s.permissions)if(typeof i!="string"){e.push("Each permission must be a string");break}}return{valid:e.length===0,errors:e,warnings:t}}function b(n){let e=typeof n=="string"?JSON.parse(n):n,t=E(e);if(!t.valid)throw new Error(`Invalid plugin manifest:
3
3
  - ${t.errors.join(`
4
4
  - `)}`);return e}function D(n,e,t){n.length>64&&e.push("name must be 64 characters or fewer"),R.test(n)||e.push("name must be lowercase alphanumeric with hyphens, starting with a letter"),/[^\x00-\x7F]/.test(n)&&e.push("name must contain only ASCII characters");for(let s of j)n.startsWith(s)&&e.push(`name cannot start with reserved prefix "${s}"`);["plugin","test","tool"].includes(n)&&t.push(`name "${n}" is very generic \u2014 consider a more descriptive name`)}function V(n,e){n.includes("..")&&e.push('entryPoint must not contain ".." (path traversal)'),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path"),!n.endsWith(".js")&&!n.endsWith(".ts")&&!n.endsWith(".mjs")&&e.push("entryPoint must end in .js, .ts, or .mjs")}var y=class{resolve(e){let t=new Map;for(let a of e)t.set(a.name,a);let s=[],i=new Set,r=new Set,c=new Map,h=(a,f)=>{if(i.has(a))return;if(r.has(a)){let g=[...f.slice(f.indexOf(a)),a];throw new Error(`Dependency cycle detected: ${g.join(" -> ")}`)}let u=t.get(a);if(!u)return;r.add(a);let k=Object.keys(u.dependencies??{}),P=[];for(let g of k)t.has(g)?h(g,[...f,a]):P.push(g);P.length>0&&c.set(a,P),r.delete(a),i.add(a),s.push(u)};for(let a of e)h(a.name,[]);return{ordered:s.map((a,f)=>({manifest:a,order:f})),missing:c}}canLoad(e,t){let i=Object.keys(e.dependencies??{}).filter(r=>!t.has(r));return{canLoad:i.length===0,missingDeps:i}}};var N=["aqe-core-","agentic-qe-core-","agentic-qe-internal-"],M=new Set(["aqe","agentic-qe","ruflo","claude-flow"]),_=["..","~","/etc/","/proc/","/dev/","node_modules/"];function A(n){let e=[];return $(n.name,e),q(n.entryPoint,e),C(n.hooks,e),I(n.permissions,e),{safe:e.length===0,violations:e}}function $(n,e){/[^\x20-\x7E]/.test(n)&&e.push(`Plugin name "${n}" contains non-ASCII characters`),M.has(n.toLowerCase())&&e.push(`Plugin name "${n}" is a reserved name`);for(let s of N)n.toLowerCase().startsWith(s)&&e.push(`Plugin name "${n}" uses reserved prefix "${s}"`);let t=n.toLowerCase().replace(/[0o]/g,"o").replace(/[1il]/g,"l").replace(/[-_]/g,"");M.has(t)&&e.push(`Plugin name "${n}" is visually similar to a reserved name`)}function q(n,e){w(n,"entryPoint",e),(n.startsWith("/")||n.startsWith("\\"))&&e.push("entryPoint must be a relative path, not absolute")}function C(n,e){if(n)for(let[t,s]of Object.entries(n))w(s,`hook[${t}]`,e)}function w(n,e,t){for(let s of _)n.includes(s)&&t.push(`${e} contains dangerous path pattern "${s}"`);n.includes("\0")&&t.push(`${e} contains null byte (path injection attempt)`)}function I(n,e){if(!n)return;let t=["fs:write-root","net:arbitrary","exec:shell"];for(let s of n)t.includes(s)&&e.push(`Plugin requests dangerous permission: ${s}`)}import*as p from"fs";import*as d from"path";var v=class{type="local";async resolve(e){let t=d.resolve(e),s=d.join(t,"qe-plugin.json");if(!p.existsSync(s))throw new Error(`No qe-plugin.json found at ${s}`);let i=p.readFileSync(s,"utf-8");return b(i)}async getPluginPath(e){let t=d.resolve(e);if(!p.existsSync(t))throw new Error(`Plugin directory does not exist: ${t}`);return t}};var x=class{cache;resolver;sources=new Map;constructor(e={}){this.cache=e.cache??new m,this.resolver=new y;let t=new v;if(this.sources.set("local",t),e.sources)for(let s of e.sources)this.sources.set(s.type,s)}async install(e,t="local"){if(process.env.AQE_PLUGINS_DISABLED==="true")return{success:!1,errors:["Plugin loading is disabled (AQE_PLUGINS_DISABLED=true)"],securityViolations:[]};let s=[],i=this.sources.get(t);if(!i)return{success:!1,errors:[`Unknown source type: ${t}. Available: ${[...this.sources.keys()].join(", ")}`],securityViolations:[]};let r;try{r=await i.resolve(e)}catch(u){return{success:!1,errors:[`Failed to resolve plugin: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let c=E(r);if(!c.valid)return{success:!1,manifest:r,errors:c.errors,securityViolations:[]};let h=A(r);if(!h.safe)return{success:!1,manifest:r,errors:["Plugin failed security checks"],securityViolations:h.violations};if(this.cache.has(r.name,r.version)){let u=this.cache.get(r.name,r.version);return{success:!0,manifest:r,cachePath:u.path,errors:[],securityViolations:[]}}let a;try{a=await i.getPluginPath(e)}catch(u){return{success:!1,manifest:r,errors:[`Failed to get plugin path: ${u instanceof Error?u.message:String(u)}`],securityViolations:[]}}let f=this.cache.store(r,a);return{success:!0,manifest:r,cachePath:f,errors:s,securityViolations:[]}}remove(e,t){if(t)return this.cache.remove(e,t);let s=this.cache.listVersions(e),i=!1;for(let r of s)this.cache.remove(e,r.manifest.version)&&(i=!0);return i}list(){return this.cache.listAll().map(t=>({name:t.manifest.name,version:t.manifest.version,description:t.manifest.description,domains:t.manifest.domains,source:"cached",cachePath:t.path}))}resolveLoadOrder(){let e=this.cache.listAll();return this.resolver.resolve(e.map(t=>t.manifest))}registerSource(e){this.sources.set(e.type,e)}};export{b as a,m as b,x as c};
@@ -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.11.3");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.11.5");process.exit(0)}
2
2
  var i={copilot:{id:"copilot",name:"GitHub Copilot",configPath:".vscode/mcp.json",configFormat:"json",configKey:"servers",rulesPath:".github/copilot-instructions.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cursor:{id:"cursor",name:"Cursor",configPath:".cursor/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".cursorrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},cline:{id:"cline",name:"Cline",configPath:".vscode/cline_mcp_settings.json",configFormat:"json",configKey:"mcpServers",rulesPath:".vscode/cline_custom_modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},kilocode:{id:"kilocode",name:"Kilo Code",configPath:".kilocode/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".kilocode/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},roocode:{id:"roocode",name:"Roo Code",configPath:".roo/mcp.json",configFormat:"json",configKey:"mcpServers",rulesPath:".roo/modes.json",rulesFormat:"json",supportsAutoApprove:!0,supportsCustomModes:!0,globalConfig:!1},codex:{id:"codex",name:"OpenAI Codex CLI",configPath:".codex/config.toml",configFormat:"toml",configKey:"mcp_servers",rulesPath:"AGENTS.md",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},windsurf:{id:"windsurf",name:"Windsurf",configPath:".windsurf/mcp_config.json",configFormat:"json",configKey:"mcpServers",rulesPath:".windsurfrules",rulesFormat:"markdown",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1},continuedev:{id:"continuedev",name:"Continue.dev",configPath:".continue/config.yaml",configFormat:"yaml",configKey:"mcpServers",rulesPath:".continue/rules/aqe-qe-standards.yaml",rulesFormat:"yaml",supportsAutoApprove:!1,supportsCustomModes:!1,globalConfig:!1}},l=["fleet_init","fleet_status","fleet_health","agent_list","agent_metrics","agent_status","team_list","team_health","task_list","task_status","test_generate_enhanced","coverage_analyze_sublinear","quality_assess","defect_predict","code_index","memory_store","memory_retrieve","memory_query","memory_usage","model_route","routing_metrics","aqe_health"];function u(t){return t?{AQE_MEMORY_BACKEND:"memory",AQE_V3_MODE:"true"}:{AQE_MEMORY_PATH:".agentic-qe/memory.db",AQE_V3_MODE:"true"}}function m(t,o){let e={command:"npx",args:["-y","agentic-qe@latest","mcp"],env:u(o)};return t&&(e.disabled=!1,e.alwaysAllow=l),e}function g(t,o){let e=m(t.supportsAutoApprove,o);if(t.id==="copilot"){let r={[t.configKey]:{"agentic-qe":{type:"stdio",...e}}};return JSON.stringify(r,null,2)+`
3
3
  `}let n={[t.configKey]:{"agentic-qe":e}};return JSON.stringify(n,null,2)+`
4
4
  `}function f(t){return`# Agentic QE MCP Server
@@ -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.11.3");process.exit(0)}
2
- import{a as D,b as _,c as $,d as I}from"./chunk-P4UGVVVX.js";import{a as X}from"./chunk-NWUVXLBB.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-PUUGIBFF.js";import{b as C,f as G,i as U}from"./chunk-NBOEXSV2.js";import{g as R}from"./chunk-EBCUWMLX.js";import{e as H}from"./chunk-SFGBC5RP.js";import{i as j,m as de}from"./chunk-JVXPKHND.js";import{a as z}from"./chunk-UNH2DE2G.js";import{c as T}from"./chunk-7UOH55UT.js";import{b as k,c as A}from"./chunk-REZ2GZQ3.js";import{a as h,b as V,c as W}from"./chunk-LGEZ3ZJX.js";import{S as pe,b as B}from"./chunk-L6PH7JIE.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{a as D,b as _,c as $,d as I}from"./chunk-UORTQXJ2.js";import{a as X}from"./chunk-4XJ2A3HY.js";import{c as K,d as Y,e as J,f as Z}from"./chunk-PW72M2FE.js";import{b as C,f as G,i as U}from"./chunk-MCHEUSY4.js";import{g as R}from"./chunk-W7TYKPLY.js";import{d as H}from"./chunk-TRNBQFFG.js";import{i as j,m as de}from"./chunk-NCSXLMDL.js";import{a as z}from"./chunk-ZMPAM4DY.js";import{c as T}from"./chunk-Y25PO65W.js";import{b as k,c as A}from"./chunk-5WMU7XCF.js";import{a as h,b as V,c as W}from"./chunk-RKXZLTWR.js";import{S as pe,b as B}from"./chunk-GODAWJMZ.js";z();W();var N={enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0,maxRoutingCandidates:10,routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4};var q=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -278,7 +278,7 @@ On promotion:
278
278
  - Move from short-term to long-term tier
279
279
  - Boost confidence by 10%
280
280
  - Enable for cross-domain transfer to related domains
281
- - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as ee}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},me=.4,ge=20,fe=3;function he(n){return 1/(1+Math.exp(-n))}function ye(n,e){if(!e||e.visits===0)return{score:n,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/ge,1)*me,t=he(e.qValue);return{score:n*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function te(n){let e=n.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,i=n.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*i,0),1),baseEpsilon:t,safetyMultiplier:i}}function re(n,e){if(e<=0||n.length<2)return;let r=Math.round(e*1e6);if(r<=0||ee(0,1e6)>=r)return;let t=Math.min(4,n.length),i=ee(1,t),o=n[i];n[i]=n[0],n[0]=o,n[0].exploration=!0,n[0].reasoning=[...n[0].reasoning,"(exploration)"]}function ne(n){let e=n.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function ie(n){return`${n.taskType}|${n.priority??"normal"}|${n.domain??"any"}`}function Q(n,e,r,t,i=x,o,s){let a=[];for(let[c,u]of Object.entries(i)){let l=0,p=[],m=n.filter(d=>u.domains.includes(d)).length,y=Math.min(n.length,fe),b=m>0?Math.min(m/y,1)*.4:0;if(l+=b*t.similarity,b>0&&p.push(`Domain match: ${(b*100).toFixed(0)}%`),e&&e.length>0){let d=e.filter(w=>u.capabilities.some(P=>P.toLowerCase().includes(w.toLowerCase()))).length,g=d>0?d/e.length*.3:0;l+=g*t.capabilities,g>0&&p.push(`Capability match: ${(g*100).toFixed(0)}%`)}else l+=.15*t.capabilities;if(l+=u.performanceScore*.3*t.performance,p.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),o&&u.languages&&u.languages.length>0){let d=t.language??1,g=o.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===g)){let P=.15*d;l+=P,p.push(`Language match: ${o}`)}}let S=r.get(c)||0;if(S>0){let d=Math.min(.1,S*.02);l+=d,p.push(`Pattern matches: ${S}`)}let E=l;if(s){let d=s(c),g=ye(E,d);l=g.score,g.qWeight>0&&p.push(`Q-bonus (w=${g.qWeight.toFixed(2)}, v=${g.qVisits})`),a.push({agent:c,score:l,reasoning:p,staticScore:E,qWeight:g.qWeight,qValue:g.qValue,qVisits:g.qVisits})}else a.push({agent:c,score:l,reasoning:p,staticScore:E})}return a.sort((c,u)=>u.score-c.score),a}var M={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function ae(){try{return!Z()||!J()||K().isEmpty()?!1:Y().isCritical()}catch{return!1}}de();function oe(n,e){if(n.length===e)return n;if(n.length>e){let r=n.length/e,t=new Array(e).fill(0);for(let i=0;i<e;i++){let o=Math.floor(i*r),s=Math.floor((i+1)*r),a=0;for(let c=o;c<s;c++)a+=n[c];t[i]=a/(s-o)}return O(t)}else{let r=new Array(e).fill(0),t=(n.length-1)/(e-1);for(let i=0;i<e;i++){let o=i*t,s=Math.floor(o),a=Math.min(s+1,n.length-1),c=o-s;r[i]=n[s]*(1-c)+n[a]*c}return O(r)}}function se(n,e){let r=new Array(e).fill(0),t=n.toLowerCase().trim();for(let i=0;i<3;i++)for(let o=0;o<t.length;o++){let s=t.charCodeAt(o),a=s*(o+1)*(i+1)%e;r[a]+=Math.sin(s*(i+1))/(o+1)}return O(r)}function O(n){let e=Math.sqrt(n.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<n.length;r++)n[r]/=e;return n}z();W();pe();var v=T.create("PatternPromotion");async function ce(n,e){let r=G(n);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),s=[...t.success?t.value.map(c=>c.pattern):[],n].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),a=await e.coherenceService.checkCoherence(s);if(a.energy>=e.coherenceThreshold){let c={patternId:n.id,patternName:n.name,reason:"coherence_violation",energy:a.energy,existingPatternConflicts:a.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${n.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),v.info("Pattern promotion blocked due to coherence violation",{name:n.name,energy:a.energy}),!1}}return!0}async function le(n,e){let r=await e.patternStore.promote(n);if(r.success){try{e.getSqliteStore().promotePattern(n)}catch(t){v.warn("SQLite pattern promotion persist failed",{error:h(t)})}if(B().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let i=new F(t),o=await e.getPattern(n);if(o){let s=await e.searchPatterns("",{domain:o.qeDomain,tier:"long-term",limit:20});if(s.success)for(let{pattern:a}of s.value)a.id!==n&&i.recordCoOccurrence(n,a.id)}}}catch(t){v.warn("Citation graph update failed (non-fatal)",{error:h(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(n);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(n,t.embedding)}catch(t){v.warn("RVF dual-write on promote failed (non-fatal)",{patternId:n,error:h(t)})}R().then(t=>t.append("PATTERN_PROMOTE",{patternId:n},"reasoning-bank")).catch(t=>{v.warn("Witness chain PATTERN_PROMOTE failed",{error:h(t)})}),v.info("Promoted pattern to long-term",{patternId:n}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${n}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:n,newTier:"long-term"}})}else v.error("Failed to promote pattern",r.error,{patternId:n})}async function ue(n){let{signal:e}=n;e?.throwIfAborted();let r=await n.patternStore.getStats(),t=0,i=0;for(let[o,s]of Object.entries(M)){e?.throwIfAborted();let a=o,c=r.byDomain[a]||0;if(c===0)continue;let u=await n.searchPatterns("",{domain:a,limit:50});if(u.success)for(let l of s){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){i++;continue}for(let{pattern:m}of u.value){e?.throwIfAborted();let y=await n.searchPatterns(m.name,{domain:l,limit:1});if(y.success&&y.value.length>0&&y.value[0].score>.8){i++;continue}let b=Math.max(.3,(m.confidence||.5)*.8);(await n.storePattern({patternType:m.patternType,qeDomain:l,name:`${m.name} (from ${a})`,description:`${m.description} [Transferred from ${a} domain]`,template:m.template,context:{...m.context,relatedDomains:[a,l],tags:[...m.context.tags,"cross-domain-transfer",`source:${a}`]},confidence:b})).success?t++:i++}}}return v.info("Cross-domain transfer complete",{transferred:t,skipped:i}),{transferred:t,skipped:i}}var be=`
281
+ - Mark as reusable for token savings optimization`,variables:[{name:"patternName",type:"string",required:!0,description:"Pattern to evaluate for promotion"}]},context:{tags:["promotion","learning","quality","pipeline"]},confidence:.6}];import{randomInt as ee}from"crypto";var x={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88,languages:["typescript","javascript"]},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9,languages:["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}},me=.4,ge=20,fe=3;function he(n){return 1/(1+Math.exp(-n))}function ye(n,e){if(!e||e.visits===0)return{score:n,qWeight:0,qValue:0,qVisits:0};let r=Math.min(e.visits/ge,1)*me,t=he(e.qValue);return{score:n*(1-r)+t*r,qWeight:r,qValue:e.qValue,qVisits:e.visits}}function te(n){let e=n.envOverride,r=e!==void 0?Number.parseFloat(e):NaN,t=Number.isFinite(r)&&r>=0&&r<=1?r:.05,i=n.topologyCritical?.2:1;return{epsilon:Math.min(Math.max(t*i,0),1),baseEpsilon:t,safetyMultiplier:i}}function re(n,e){if(e<=0||n.length<2)return;let r=Math.round(e*1e6);if(r<=0||ee(0,1e6)>=r)return;let t=Math.min(4,n.length),i=ee(1,t),o=n[i];n[i]=n[0],n[0]=o,n[0].exploration=!0,n[0].reasoning=[...n[0].reasoning,"(exploration)"]}function ne(n){let e=n.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function ie(n){return`${n.taskType}|${n.priority??"normal"}|${n.domain??"any"}`}function Q(n,e,r,t,i=x,o,s){let a=[];for(let[c,u]of Object.entries(i)){let l=0,p=[],m=n.filter(d=>u.domains.includes(d)).length,y=Math.min(n.length,fe),b=m>0?Math.min(m/y,1)*.4:0;if(l+=b*t.similarity,b>0&&p.push(`Domain match: ${(b*100).toFixed(0)}%`),e&&e.length>0){let d=e.filter(w=>u.capabilities.some(P=>P.toLowerCase().includes(w.toLowerCase()))).length,g=d>0?d/e.length*.3:0;l+=g*t.capabilities,g>0&&p.push(`Capability match: ${(g*100).toFixed(0)}%`)}else l+=.15*t.capabilities;if(l+=u.performanceScore*.3*t.performance,p.push(`Performance score: ${(u.performanceScore*100).toFixed(0)}%`),o&&u.languages&&u.languages.length>0){let d=t.language??1,g=o.toLowerCase();if(u.languages.some(P=>P.toLowerCase()===g)){let P=.15*d;l+=P,p.push(`Language match: ${o}`)}}let S=r.get(c)||0;if(S>0){let d=Math.min(.1,S*.02);l+=d,p.push(`Pattern matches: ${S}`)}let E=l;if(s){let d=s(c),g=ye(E,d);l=g.score,g.qWeight>0&&p.push(`Q-bonus (w=${g.qWeight.toFixed(2)}, v=${g.qVisits})`),a.push({agent:c,score:l,reasoning:p,staticScore:E,qWeight:g.qWeight,qValue:g.qValue,qVisits:g.qVisits})}else a.push({agent:c,score:l,reasoning:p,staticScore:E})}return a.sort((c,u)=>u.score-c.score),a}var M={"test-generation":["test-execution","coverage-analysis","requirements-validation"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"]};function ae(){try{return!Z()||!J()||K().getVerticesByType("agent").length===0?!1:Y().isCritical()}catch{return!1}}de();function oe(n,e){if(n.length===e)return n;if(n.length>e){let r=n.length/e,t=new Array(e).fill(0);for(let i=0;i<e;i++){let o=Math.floor(i*r),s=Math.floor((i+1)*r),a=0;for(let c=o;c<s;c++)a+=n[c];t[i]=a/(s-o)}return O(t)}else{let r=new Array(e).fill(0),t=(n.length-1)/(e-1);for(let i=0;i<e;i++){let o=i*t,s=Math.floor(o),a=Math.min(s+1,n.length-1),c=o-s;r[i]=n[s]*(1-c)+n[a]*c}return O(r)}}function se(n,e){let r=new Array(e).fill(0),t=n.toLowerCase().trim();for(let i=0;i<3;i++)for(let o=0;o<t.length;o++){let s=t.charCodeAt(o),a=s*(o+1)*(i+1)%e;r[a]+=Math.sin(s*(i+1))/(o+1)}return O(r)}function O(n){let e=Math.sqrt(n.reduce((r,t)=>r+t*t,0));if(e>0)for(let r=0;r<n.length;r++)n[r]/=e;return n}z();W();pe();var v=T.create("PatternPromotion");async function ce(n,e){let r=G(n);if(!r.meetsUsageCriteria||!r.meetsQualityCriteria)return!1;if(e.coherenceService&&e.coherenceService.isInitialized()){let t=await e.searchPatterns("",{tier:"long-term",limit:1e3}),s=[...t.success?t.value.map(c=>c.pattern):[],n].map(c=>({id:c.id,embedding:c.embedding||[],weight:c.confidence,metadata:{name:c.name,domain:c.qeDomain}})),a=await e.coherenceService.checkCoherence(s);if(a.energy>=e.coherenceThreshold){let c={patternId:n.id,patternName:n.name,reason:"coherence_violation",energy:a.energy,existingPatternConflicts:a.contradictions?.map(u=>u.nodeIds).flat()};return e.eventBus&&await e.eventBus.publish({id:`pattern-promotion-blocked-${n.id}`,type:"pattern:promotion_blocked",timestamp:new Date,source:"learning-optimization",payload:c}),v.info("Pattern promotion blocked due to coherence violation",{name:n.name,energy:a.energy}),!1}}return!0}async function le(n,e){let r=await e.patternStore.promote(n);if(r.success){try{e.getSqliteStore().promotePattern(n)}catch(t){v.warn("SQLite pattern promotion persist failed",{error:h(t)})}if(B().useSublinearSolver)try{let t=e.getSqliteStore().getDatabase?.();if(t){let i=new F(t),o=await e.getPattern(n);if(o){let s=await e.searchPatterns("",{domain:o.qeDomain,tier:"long-term",limit:20});if(s.success)for(let{pattern:a}of s.value)a.id!==n&&i.recordCoOccurrence(n,a.id)}}}catch(t){v.warn("Citation graph update failed (non-fatal)",{error:h(t)})}if(e.rvfDualWriter)try{let t=await e.getPattern(n);t?.embedding&&t.embedding.length>0&&e.rvfDualWriter.writePattern(n,t.embedding)}catch(t){v.warn("RVF dual-write on promote failed (non-fatal)",{patternId:n,error:h(t)})}R().then(t=>t.append("PATTERN_PROMOTE",{patternId:n},"reasoning-bank")).catch(t=>{v.warn("Witness chain PATTERN_PROMOTE failed",{error:h(t)})}),v.info("Promoted pattern to long-term",{patternId:n}),e.eventBus&&await e.eventBus.publish({id:`pattern-promoted-${n}`,type:"pattern:promoted",timestamp:new Date,source:"learning-optimization",payload:{patternId:n,newTier:"long-term"}})}else v.error("Failed to promote pattern",r.error,{patternId:n})}async function ue(n){let{signal:e}=n;e?.throwIfAborted();let r=await n.patternStore.getStats(),t=0,i=0;for(let[o,s]of Object.entries(M)){e?.throwIfAborted();let a=o,c=r.byDomain[a]||0;if(c===0)continue;let u=await n.searchPatterns("",{domain:a,limit:50});if(u.success)for(let l of s){if(e?.throwIfAborted(),(r.byDomain[l]||0)>=c){i++;continue}for(let{pattern:m}of u.value){e?.throwIfAborted();let y=await n.searchPatterns(m.name,{domain:l,limit:1});if(y.success&&y.value.length>0&&y.value[0].score>.8){i++;continue}let b=Math.max(.3,(m.confidence||.5)*.8);(await n.storePattern({patternType:m.patternType,qeDomain:l,name:`${m.name} (from ${a})`,description:`${m.description} [Transferred from ${a} domain]`,template:m.template,context:{...m.context,relatedDomains:[a,l],tags:[...m.context.tags,"cross-domain-transfer",`source:${a}`]},confidence:b})).success?t++:i++}}}return v.info("Cross-domain transfer complete",{transferred:t,skipped:i}),{transferred:t,skipped:i}}var be=`
282
282
  CREATE TABLE IF NOT EXISTS pattern_citations (
283
283
  source_pattern_id TEXT NOT NULL,
284
284
  target_pattern_id TEXT NOT NULL,
@@ -311,10 +311,10 @@ On promotion:
311
311
  `).all(),c=this.db.prepare(`
312
312
  INSERT OR IGNORE INTO pattern_citations (source_pattern_id, target_pattern_id, weight, relationship)
313
313
  VALUES (?, ?, 2.0, 'derivation')
314
- `);for(let u of a)c.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var f=T.create("QEReasoningBank"),L=class{constructor(e,r,t={},i){this.memory=e;this.eventBus=r;this.coherenceService=i;this.config={...N,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=X(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=H(),this.sqliteStore.initialize().catch(e=>{f.warn("SQLitePatternStore init failed",{error:h(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){f.warn("Failed to wire SQLitePatternStore into PatternStore",{error:h(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let o=await this.patternStore.getStats();f.info("Cross-domain transfer already complete",{totalPatterns:o.totalPatterns})}}catch(t){if(r?.aborted)throw t;f.warn("Cross-domain seeding failed (non-fatal)",{error:t})}f.info("Initialized")}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){f.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let i=(()=>{let a=process.env.AQE_RVF_BACKFILL_LIMIT,c=a?Number(a):NaN;return Number.isFinite(c)&&c>0?Math.floor(c):1e3})(),s=this.getSqliteStore().getRecentEmbeddings(i).filter(({embedding:a})=>a&&a.length>0).map(({patternId:a,embedding:c})=>({id:a,vector:c instanceof Float32Array?c:new Float32Array(c)}));if(s.length>0){let{accepted:a,rejected:c}=t.ingest(s);f.info("Backfilled RVF from SQLite",{requested:s.length,accepted:a,cap:i,truncated:s.length>=i}),c>0&&f.warn("RVF backfill partially rejected",{accepted:a,rejected:c})}}catch(i){f.warn("RVF backfill failed (non-fatal)",{error:h(i)})}return}for(let t of q){e?.throwIfAborted();try{await this.storePattern(t)}catch(i){if(e?.aborted)throw i;f.warn("Failed to load pattern",{name:t.name,error:i})}}f.info("Loaded foundational patterns",{count:q.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),ue({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return A(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(R().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{f.warn("Witness chain PATTERN_CREATE failed",{error:h(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){f.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:h(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,i=!0;return typeof e=="string"&&(e.trim()===""?(i=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:i})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return k(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success);try{this.getSqliteStore().recordUsage(e.patternId,e.success,e.metrics,e.feedback)}catch(t){f.warn("SQLite pattern usage persist failed",{error:h(t)})}if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,R().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{f.warn("Witness chain PATTERN_UPDATE failed",{error:h(o)})});let t=await this.getPattern(e.patternId),i=this.getPromotionDeps();t&&await ce(t,i)&&(await le(e.patternId,i),f.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return A(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:C(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),i=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),o=i.success?i.value.map(d=>d.pattern):[],s=new Map;for(let[d,g]of Object.entries(x)){let w=o.filter(P=>g.domains.includes(P.qeDomain)).length;w>0&&s.set(d,w)}let a=ie({taskType:ne(e.task),priority:"normal",domain:r[0]}),c=this.buildQValueLookup(a),u=Q(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,c),l=1;try{let d=ae(),g=te({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:d});l=g.safetyMultiplier,re(u,g.epsilon)}catch{}let p=u[0],m=u.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let d=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=p.score;let b=u.reduce((d,g)=>d+(g.qWeight??0),0),S=u.length>0?b/u.length:0,E={recommendedAgent:p.agent,confidence:p.score,alternatives:m.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:o,guidance:y,reasoning:p.reasoning.join("; "),exploration:p.exploration===!0,criticality:l,qWeight:S};return k(E)}catch(r){return A(V(r))}}buildQValueLookup(e){try{let r=j();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let o=t.prepare(`
314
+ `);for(let u of a)c.run(u.source_pattern_id,u.target_pattern_id).changes>0&&e++;return e}getEdgeCount(){return this.ensureSchema(),this.db.prepare("SELECT COUNT(*) as cnt FROM pattern_citations").get().cnt}};var f=T.create("QEReasoningBank"),L=class{constructor(e,r,t={},i){this.memory=e;this.eventBus=r;this.coherenceService=i;this.config={...N,...t},t.rvfDualWriter&&(this.rvfDualWriter=t.rvfDualWriter),this.patternStore=X(e,{embeddingDimension:this.config.embeddingDimension,...t.patternStore})}memory;eventBus;coherenceService;config;patternStore;initialized=!1;sqliteStore=null;rvfDualWriter=null;getSqliteStore(){return this.sqliteStore||(this.sqliteStore=H(),this.sqliteStore.initialize().catch(e=>{f.warn("SQLitePatternStore init failed",{error:h(e)})})),this.sqliteStore}setRvfDualWriter(e){this.rvfDualWriter=e}stats={routingRequests:0,totalRoutingConfidence:0,learningOutcomes:0,successfulOutcomes:0};async initialize(e){if(this.initialized)return;let r=e?.signal;r?.throwIfAborted(),await this.patternStore.initialize(),r?.throwIfAborted();try{let t=this.getSqliteStore();await t.initialize(),this.patternStore.setSqliteStore?.(t)}catch(t){f.warn("Failed to wire SQLitePatternStore into PatternStore",{error:h(t)})}r?.throwIfAborted(),this.initialized=!0,await this.loadPretrainedPatterns(r),r?.throwIfAborted();try{let t="reasoning-bank:cross-domain-seeded";if(!await this.memory.get(t))await this.memory.set(t,!0),await this.seedCrossDomainPatterns(r);else{let o=await this.patternStore.getStats();f.info("Cross-domain transfer already complete",{totalPatterns:o.totalPatterns})}}catch(t){if(r?.aborted)throw t;f.warn("Cross-domain seeding failed (non-fatal)",{error:t})}f.info("Initialized")}async loadPretrainedPatterns(e){e?.throwIfAborted();let r=await this.patternStore.getStats();if(r.totalPatterns>0){f.info("Found existing patterns",{totalPatterns:r.totalPatterns});let t=this.patternStore.getAdapter?.();if(t&&(t.status()?.totalVectors??0)===0)try{let i=(()=>{let a=process.env.AQE_RVF_BACKFILL_LIMIT,c=a?Number(a):NaN;return Number.isFinite(c)&&c>0?Math.floor(c):1e3})(),s=this.getSqliteStore().getRecentEmbeddings(i).filter(({embedding:a})=>a&&a.length>0).map(({patternId:a,embedding:c})=>({id:a,vector:c instanceof Float32Array?c:new Float32Array(c)}));if(s.length>0){let{accepted:a,rejected:c}=t.ingest(s);f.info("Backfilled RVF from SQLite",{requested:s.length,accepted:a,cap:i,truncated:s.length>=i}),c>0&&f.warn("RVF backfill partially rejected",{accepted:a,rejected:c})}}catch(i){f.warn("RVF backfill failed (non-fatal)",{error:h(i)})}return}for(let t of q){e?.throwIfAborted();try{await this.storePattern(t)}catch(i){if(e?.aborted)throw i;f.warn("Failed to load pattern",{name:t.name,error:i})}}f.info("Loaded foundational patterns",{count:q.length})}async seedCrossDomainPatterns(e){return this.initialized||await this.initialize({signal:e}),ue({searchPatterns:this.searchPatterns.bind(this),storePattern:this.storePattern.bind(this),patternStore:this.patternStore,signal:e})}async storePattern(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return A(new Error("Pattern learning is disabled"));if(!e.embedding){let t=await this.embed(`${e.name} ${e.description} ${e.context?.tags?.join(" ")||""}`);e={...e,embedding:t}}let r=await this.patternStore.create(e);if(r.success&&(R().then(t=>t.append("PATTERN_CREATE",{patternId:r.value.id,domain:r.value.qeDomain,confidence:r.value.confidence,name:r.value.name},"reasoning-bank")).catch(t=>{f.warn("Witness chain PATTERN_CREATE failed",{error:h(t)})}),this.rvfDualWriter&&r.value.embedding&&r.value.embedding.length>0))try{this.rvfDualWriter.writePattern(r.value.id,r.value.embedding)}catch(t){f.warn("RVF dual-write failed (non-fatal)",{patternId:r.value.id,error:h(t)})}return r}async searchPatterns(e,r){this.initialized||await this.initialize();let t=e,i=!0;return typeof e=="string"&&(e.trim()===""?(i=!1,t=""):t=await this.embed(e)),this.patternStore.search(t,{...r,useVectorSearch:i})}async getPattern(e){return this.initialized||await this.initialize(),this.patternStore.get(e)}async recordOutcome(e){if(this.initialized||await this.initialize(),!this.config.enableLearning)return k(void 0);let r=await this.patternStore.recordUsage(e.patternId,e.success,e.metrics,e.feedback);if(r.success){this.stats.learningOutcomes++,e.success&&this.stats.successfulOutcomes++,R().then(o=>o.append("PATTERN_UPDATE",{patternId:e.patternId,success:e.success},"reasoning-bank")).catch(o=>{f.warn("Witness chain PATTERN_UPDATE failed",{error:h(o)})});let t=await this.getPattern(e.patternId),i=this.getPromotionDeps();t&&await ce(t,i)&&(await le(e.patternId,i),f.info("Pattern promoted to long-term",{name:t.name}))}return r}getPromotionDeps(){return{patternStore:this.patternStore,coherenceService:this.coherenceService,eventBus:this.eventBus,coherenceThreshold:this.config.coherenceThreshold||.4,getSqliteStore:this.getSqliteStore.bind(this),rvfDualWriter:this.rvfDualWriter,searchPatterns:this.searchPatterns.bind(this),getPattern:this.getPattern.bind(this)}}async routeTask(e){if(this.initialized||await this.initialize(),!this.config.enableRouting)return A(new Error("Task routing is disabled"));this.stats.routingRequests++;try{let r=e.domain?[e.domain]:C(e.task);r.length===0&&r.push("test-generation");let t=await this.embed(e.task),i=await this.patternStore.search(t,{limit:this.config.maxRoutingCandidates,domain:r[0],useVectorSearch:!0}),o=i.success?i.value.map(d=>d.pattern):[],s=new Map;for(let[d,g]of Object.entries(x)){let w=o.filter(P=>g.domains.includes(P.qeDomain)).length;w>0&&s.set(d,w)}let a=ie({taskType:ne(e.task),priority:"normal",domain:r[0]}),c=this.buildQValueLookup(a),u=Q(r,e.capabilities,s,this.config.routingWeights,x,e.context?.language,c),l=1;try{let d=ae(),g=te({envOverride:process.env.AQE_ROUTER_EXPLORATION_RATE,topologyCritical:d});l=g.safetyMultiplier,re(u,g.epsilon)}catch{}let p=u[0],m=u.slice(1,4),y=[];if(this.config.enableGuidance&&r.length>0){let d=_(r[0],{framework:e.context?.framework,language:e.context?.language,includeAntiPatterns:!0});y.push(...d.slice(0,5))}this.stats.totalRoutingConfidence+=p.score;let b=u.reduce((d,g)=>d+(g.qWeight??0),0),S=u.length>0?b/u.length:0,E={recommendedAgent:p.agent,confidence:p.score,alternatives:m.map(d=>({agent:d.agent,score:d.score})),domains:r,patterns:o,guidance:y,reasoning:p.reasoning.join("; "),exploration:p.exploration===!0,criticality:l,qWeight:S};return k(E)}catch(r){return A(V(r))}}buildQValueLookup(e){try{let r=j();if(!r.isInitialized())return()=>{};let t=r.getDatabase();if(!t.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='rl_q_values'").get())return()=>{};let o=t.prepare(`
315
315
  SELECT q_value, visits FROM rl_q_values
316
316
  WHERE algorithm = 'q-learning'
317
317
  AND agent_id = 'aqe-hook-router'
318
318
  AND state_key = ?
319
319
  AND action_key = ?
320
- `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-GDRJ4XSH.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-GDRJ4XSH.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;if(t===0||o===0)try{let a=this.getSqliteStore().getAggregateOutcomeStats();t===0&&a.routingRequests>0&&(t=a.routingRequests,i=a.avgRoutingConfidence),o===0&&a.learningOutcomes>0&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
320
+ `);return s=>{try{let a=o.get(e,s);return a?{qValue:a.q_value,visits:a.visits}:void 0}catch{return}}}catch{return()=>{}}}getGuidance(e,r){return D(e)}generateContext(e,r){return I(e,r||{})}checkAntiPatterns(e,r){return $(e,r)}async embed(e){if(this.config.useONNXEmbeddings)try{let{computeRealEmbedding:r}=await import("./real-embeddings-2PUCC7FG.js"),t=await r(e);return t.length!==this.config.embeddingDimension?oe(t,this.config.embeddingDimension):t}catch(r){let{isUsingEndpoint:t}=await import("./real-embeddings-2PUCC7FG.js");if(t())throw r;process.env.DEBUG&&f.warn("ONNX embeddings unavailable, using hash fallback",{error:h(r)})}return se(e,this.config.embeddingDimension)}async getStats(){this.initialized||await this.initialize();let e=await this.patternStore.getStats(),r={};for(let a of U)r[a]=e.byDomain[a]||0;let t=this.stats.routingRequests,i=this.stats.routingRequests>0?this.stats.totalRoutingConfidence/this.stats.routingRequests:0,o=this.stats.learningOutcomes,s=this.stats.learningOutcomes>0?this.stats.successfulOutcomes/this.stats.learningOutcomes:0;try{let a=this.getSqliteStore().getAggregateOutcomeStats();a.routingRequests>t&&(t=a.routingRequests,i=a.avgRoutingConfidence),a.learningOutcomes>o&&(o=a.learningOutcomes,s=a.learningOutcomes>0?a.successfulOutcomes/a.learningOutcomes:a.avgPatternSuccessRate)}catch{}return{totalPatterns:e.totalPatterns,byDomain:r,routingRequests:t,avgRoutingConfidence:i,learningOutcomes:o,patternSuccessRate:s,patternStoreStats:e}}async dispose(){if(await this.patternStore.dispose(),this.sqliteStore&&(this.sqliteStore.close(),this.sqliteStore=null),this.rvfDualWriter){try{this.rvfDualWriter.close()}catch{}this.rvfDualWriter=null}this.initialized=!1}};function pt(n,e,r,t){return new L(n,e,r,t)}export{N as a,q as b,x as c,ne as d,Q as e,M as f,L as g,pt as h};
@@ -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.11.3");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.11.5");process.exit(0)}
2
2
  function r(e,f){if(e==null)return e;let n={...e};for(let t of f){let o=n[t];typeof o=="string"&&(n[t]=new Date(o))}return n}export{r as a};
@@ -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.11.3");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.11.5");process.exit(0)}
2
2
  import{writeFileSync as p,readFileSync as m}from"node:fs";import{resolve as f,dirname as c,join as d}from"node:path";import{mkdirSync as g}from"node:fs";import{fileURLToPath as h}from"node:url";function $(){try{let e=typeof __dirname<"u"?__dirname:c(h(import.meta.url));for(let t=0;t<5;t++){let n=d(e,"package.json");try{let r=JSON.parse(m(n,"utf-8"));if(r.version)return r.version}catch{}e=c(e)}}catch{}return"unknown"}var T=["-F, --format <format>","Output format (text|json|sarif|junit|markdown)","text"],x=["-o, --output <path>","Write output to file instead of stdout"];function C(e,t,n){if(t){let r=f(t);g(c(r),{recursive:!0}),p(r,e,"utf-8"),n&&console.log(n),console.log(`Output written to: ${r}`)}else console.log(e)}function R(e){return JSON.stringify(e,null,2)}var v="https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json";function w(e){let t=i=>{switch(i.toLowerCase()){case"critical":case"high":return"error";case"medium":return"warning";case"low":case"info":return"note";default:return"warning"}},n=new Map,r=[];for(let i of e.vulnerabilities){let o=i.ruleId||`AQE/${i.type.replace(/\s+/g,"-").toLowerCase()}`;n.has(o)||n.set(o,{id:o,name:i.type,shortDescription:i.type,...i.cweId?{helpUri:`https://cwe.mitre.org/data/definitions/${i.cweId.replace("CWE-","")}.html`}:{}}),r.push({ruleId:o,level:t(i.severity),message:{text:i.message},locations:[{physicalLocation:{artifactLocation:{uri:i.file,uriBaseId:"%SRCROOT%"},region:{startLine:i.line,startColumn:1}}}],...i.cweId?{taxa:[{id:i.cweId,toolComponent:{name:"CWE"}}]}:{}})}let s={$schema:v,version:"2.1.0",runs:[{tool:{driver:{name:"agentic-qe",version:$(),informationUri:"https://github.com/proffesor-for-testing/agentic-qe",rules:Array.from(n.values()).map(i=>({id:i.id,name:i.name,shortDescription:{text:i.shortDescription},...i.helpUri?{helpUri:i.helpUri}:{},defaultConfiguration:{level:"warning"}}))}},results:r,invocations:[{executionSuccessful:!0,commandLine:`aqe security --sast --format sarif -t ${e.target}`}]}]};return JSON.stringify(s,null,2)}function a(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function I(e){let t=e.tests||[],n=e.passed+e.failed+e.skipped,r=(e.duration/1e3).toFixed(3),s=`<?xml version="1.0" encoding="UTF-8"?>
3
3
  `;if(s+=`<testsuites tests="${n}" failures="${e.failed}" errors="0" time="${r}">
4
4
  `,s+=` <testsuite name="aqe-test-run" tests="${n}" failures="${e.failed}" errors="0" skipped="${e.skipped}" time="${r}" id="${a(e.runId)}">
@@ -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.11.3");process.exit(0)}
2
- import{b as f,d as v}from"./chunk-G6MPXBCD.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
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.11.5");process.exit(0)}
2
+ import{b as f,d as v}from"./chunk-CKOF27L7.js";import q,{MultiBar as F,Presets as k}from"cli-progress";import O from"ora";import o from"chalk";v();import{existsSync as w,readFileSync as y,writeFileSync as j,mkdirSync as W,unlinkSync as V}from"fs";import{join as p}from"path";import{homedir as C}from"os";var u={wizards:{enabled:!0,themes:["default","minimal","detailed"],defaultTheme:"default"},progress:{style:"multi-bar",updateIntervalMs:100,showETA:!0,colors:!0},completion:{maxSuggestions:10,historyWeight:.3,contextWeight:.7,fuzzyMatch:!0},streaming:{enabled:!0,bufferSize:100,updateIntervalMs:50}};function x(){return p(C(),".aqe")}function E(){return p(x(),"cli-config.json")}var g=null,d=0,T=5e3;function S(){return g?Date.now()-d<T:!1}function A(s){let e=[],t=s;if(typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"wizards.enabled",message:"must be a boolean"}),t.themes!==void 0)if(!Array.isArray(t.themes))e.push({path:"wizards.themes",message:"must be an array"});else{let r=["default","minimal","detailed"];for(let n of t.themes)r.includes(n)||e.push({path:"wizards.themes",message:`invalid theme: ${n}`})}return t.defaultTheme!==void 0&&(["default","minimal","detailed"].includes(t.defaultTheme)||e.push({path:"wizards.defaultTheme",message:`invalid theme: ${t.defaultTheme}`})),e}function P(s){let e=[],t=s;return t.style!==void 0&&(["multi-bar","single-bar","spinner"].includes(t.style)||e.push({path:"progress.style",message:`invalid style: ${t.style}`})),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"progress.updateIntervalMs",message:"must be a number >= 10"}),typeof t.showETA!="boolean"&&t.showETA!==void 0&&e.push({path:"progress.showETA",message:"must be a boolean"}),typeof t.colors!="boolean"&&t.colors!==void 0&&e.push({path:"progress.colors",message:"must be a boolean"}),e}function $(s){let e=[],t=s;return t.maxSuggestions!==void 0&&(typeof t.maxSuggestions!="number"||t.maxSuggestions<1)&&e.push({path:"completion.maxSuggestions",message:"must be a number >= 1"}),t.historyWeight!==void 0&&(typeof t.historyWeight!="number"||t.historyWeight<0||t.historyWeight>1)&&e.push({path:"completion.historyWeight",message:"must be a number between 0 and 1"}),t.contextWeight!==void 0&&(typeof t.contextWeight!="number"||t.contextWeight<0||t.contextWeight>1)&&e.push({path:"completion.contextWeight",message:"must be a number between 0 and 1"}),typeof t.fuzzyMatch!="boolean"&&t.fuzzyMatch!==void 0&&e.push({path:"completion.fuzzyMatch",message:"must be a boolean"}),e}function I(s){let e=[],t=s;return typeof t.enabled!="boolean"&&t.enabled!==void 0&&e.push({path:"streaming.enabled",message:"must be a boolean"}),t.bufferSize!==void 0&&(typeof t.bufferSize!="number"||t.bufferSize<1)&&e.push({path:"streaming.bufferSize",message:"must be a number >= 1"}),t.updateIntervalMs!==void 0&&(typeof t.updateIntervalMs!="number"||t.updateIntervalMs<10)&&e.push({path:"streaming.updateIntervalMs",message:"must be a number >= 10"}),e}function M(s){let e=[];if(typeof s!="object"||s===null)return{valid:!1,errors:[{path:"",message:"config must be an object"}]};let t=s;return t.wizards!==void 0&&(typeof t.wizards!="object"||t.wizards===null?e.push({path:"wizards",message:"must be an object"}):e.push(...A(t.wizards))),t.progress!==void 0&&(typeof t.progress!="object"||t.progress===null?e.push({path:"progress",message:"must be an object"}):e.push(...P(t.progress))),t.completion!==void 0&&(typeof t.completion!="object"||t.completion===null?e.push({path:"completion",message:"must be an object"}):e.push(...$(t.completion))),t.streaming!==void 0&&(typeof t.streaming!="object"||t.streaming===null?e.push({path:"streaming",message:"must be an object"}):e.push(...I(t.streaming))),{valid:e.length===0,errors:e}}var z=["__proto__","constructor","prototype"];function m(s,e){let t={...s};for(let r of Object.keys(e)){if(z.includes(r)){console.warn(`Security: Skipping forbidden key '${String(r)}' in configuration merge`);continue}let n=e[r],i=s[r];n!==void 0&&typeof n=="object"&&!Array.isArray(n)&&typeof i=="object"&&!Array.isArray(i)?t[r]=m(i,n):n!==void 0&&(t[r]=n)}return t}function D(){let s=E();if(!w(s))return{...u};try{let e=y(s,"utf-8"),t=f(e),r=M(t);return r.valid?m(u,t):(console.warn(`CLI config validation errors: ${r.errors.map(n=>`${n.path}: ${n.message}`).join(", ")}`),console.warn("Using default configuration"),{...u})}catch(e){return console.warn(`Failed to load CLI config: ${e instanceof Error?e.message:"Unknown error"}`),{...u}}}function c(){return S()||(g=D(),d=Date.now()),g}function B(){return process.stdout.isTTY===!0}function h(){let s=c();return process.env.NO_COLOR!==void 0?!1:process.env.FORCE_COLOR!==void 0?!0:s.progress.colors&&B()}var b=class{multiBar;agentBars=new Map;agentStates=new Map;fleetBar=null;startTime=Date.now();options;isActive=!1;constructor(e={}){let t=c(),r=h();this.options={title:"Fleet Progress",showEta:t.progress.showETA,showPercentage:!0,...e};let n=r?o.cyan("{bar}"):"{bar}",i=this.options.format||`{name} ${n} {percentage}% | {status} {eta}`;this.multiBar=new F({clearOnComplete:!1,hideCursor:!0,format:i,barCompleteChar:"\u2588",barIncompleteChar:"\u2591",forceRedraw:!0,fps:Math.round(1e3/t.progress.updateIntervalMs)},k.shades_classic)}start(e){this.isActive=!0,this.startTime=Date.now(),console.log(o.blue(`
3
3
  ${this.options.title}
4
4
  `)),this.fleetBar=this.multiBar.create(100,0,{name:o.white("Fleet Progress".padEnd(30)),status:"",eta:""})}addAgent(e){if(!this.isActive)return;this.agentStates.set(e.id,e);let t=this.multiBar.create(100,e.progress,{name:o.gray(this.truncateName(e.name,30).padEnd(30)),status:this.getStatusIcon(e.status),eta:e.eta?this.formatEta(e.eta):""});this.agentBars.set(e.id,t),this.updateFleetProgress()}updateAgent(e,t,r){if(!this.isActive)return;let n=this.agentStates.get(e),i=this.agentBars.get(e);!n||!i||(n.progress=Math.min(100,Math.max(0,t)),r?.status&&(n.status=r.status),r?.message&&(n.message=r.message),r?.eta!==void 0&&(n.eta=r.eta),i.update(n.progress,{name:this.getAgentNameDisplay(n),status:this.getStatusIcon(n.status),eta:n.eta?this.formatEta(n.eta):""}),this.updateFleetProgress())}completeAgent(e,t=!0){if(!this.isActive)return;let r=this.agentStates.get(e),n=this.agentBars.get(e);!r||!n||(r.status=t?"completed":"failed",r.progress=t?100:r.progress,n.update(r.progress,{name:this.getAgentNameDisplay(r),status:this.getStatusIcon(r.status),eta:""}),this.updateFleetProgress())}stop(){if(!this.isActive)return;this.isActive=!1,this.multiBar.stop();let e=Array.from(this.agentStates.values()).filter(i=>i.status==="completed").length,t=Array.from(this.agentStates.values()).filter(i=>i.status==="failed").length,r=this.agentStates.size,n=Date.now()-this.startTime;console.log(""),console.log(t===0?o.green(`All ${e}/${r} agents completed successfully (${this.formatDuration(n)})`):o.yellow(`${e}/${r} agents completed, ${t} failed (${this.formatDuration(n)})`)),console.log("")}updateFleetProgress(){if(!this.fleetBar)return;let e=Array.from(this.agentStates.values()),t=e.reduce((a,l)=>a+l.progress,0),r=e.length>0?Math.round(t/e.length):0,n=e.filter(a=>a.status==="completed").length,i=e.filter(a=>a.status==="running").length;this.fleetBar.update(r,{status:o.gray(`${n}/${e.length} complete, ${i} running`),eta:this.options.showEta?this.estimateFleetEta(e):""})}getAgentNameDisplay(e){let t=this.truncateName(e.name,26);switch(e.status){case"completed":return o.green(t.padEnd(30));case"failed":return o.red(t.padEnd(30));case"running":return o.yellow(t.padEnd(30));default:return o.gray(t.padEnd(30))}}getStatusIcon(e){switch(e){case"completed":return o.green("\u2713");case"failed":return o.red("\u2717");case"running":return o.yellow("\u25B6");default:return o.gray("\u25CB")}}truncateName(e,t){return e.length<=t?e:e.slice(0,t-3)+"..."}formatEta(e){return e<=0?"":e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:`${Math.round(e/36e5)}h`}formatDuration(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}estimateFleetEta(e){let t=e.filter(a=>a.status==="running"||a.status==="pending");if(t.length===0)return"";let r=t.map(a=>a.eta||0).filter(a=>a>0);if(r.length>0){let a=Math.max(...r);return o.gray(`ETA: ${this.formatEta(a)}`)}let n=Date.now()-this.startTime,i=t.reduce((a,l)=>a+l.progress,0)/t.length;if(i>0){let a=n/(i/100),l=Math.max(0,a-n);return o.gray(`ETA: ${this.formatEta(l)}`)}return""}};function X(s){let e=Date.now(),t=O({text:s,color:"cyan"}).start(),r=setInterval(()=>{let i=((Date.now()-e)/1e3).toFixed(1);t.text=`${s} (${i}s)`},100);r.unref?.();let n=()=>{clearInterval(r)};return{spinner:t,stop:()=>{n(),t.stop()},succeed:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.succeed(i||`${s} (${a}s)`)},fail:i=>{n();let a=((Date.now()-e)/1e3).toFixed(1);t.fail(i||`${s} failed (${a}s)`)}}}export{b as a,X as b};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.3");process.exit(0)}
2
- import{a as t,q as r}from"./chunk-2OUXYSQV.js";import{c as l}from"./chunk-PUK5NE47.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{a as t,q as r}from"./chunk-WHHQIL4F.js";import{c as l}from"./chunk-C4EZNOWK.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
@@ -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.11.3");process.exit(0)}
2
- import{a as v}from"./chunk-UNH2DE2G.js";import{c as l}from"./chunk-7UOH55UT.js";import{S as R,b as g}from"./chunk-L6PH7JIE.js";v();R();import{createHash as m,randomUUID as f}from"crypto";var a=l.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{a as v}from"./chunk-ZMPAM4DY.js";import{c as l}from"./chunk-Y25PO65W.js";import{S as R,b as g}from"./chunk-GODAWJMZ.js";v();R();import{createHash as m,randomUUID as f}from"crypto";var a=l.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain_receipts (
4
4
  id TEXT PRIMARY KEY,
5
5
  chain_index INTEGER NOT NULL,
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.3");process.exit(0)}
2
- import{c as T}from"./chunk-PUK5NE47.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{c as T}from"./chunk-C4EZNOWK.js";var S,E,t,N,_=T(()=>{"use strict";S={MMAP_SIZE_BYTES:67108864,CACHE_SIZE_KB:-32e3,BUSY_TIMEOUT_MS:5e3,DEFAULT_VECTOR_DIMENSIONS:384,DEFAULT_SEARCH_LIMIT:100,CLEANUP_INTERVAL_MS:6e4,TTL_MULTIPLIER_MS:1e3},E={M_CONNECTIONS:16,EF_CONSTRUCTION:200,EF_SEARCH:100,DEFAULT_K_NEIGHBORS:10,COVERAGE_VECTOR_DIMENSION:384},t={MAX_CONCURRENT_AGENTS:15,DEFAULT_AGENT_TTL_MS:36e5,DEFAULT_AGENT_TIMEOUT_MS:12e4,MAX_POOL_SIZE:10},N={MAX_HISTORY_SIZE:1e4}});export{S as a,E as b,t as c,N as d,_ as e};
@@ -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.11.3");process.exit(0)}
2
- import{e as a}from"./chunk-RXN5DWVM.js";import{b as w,d as y}from"./chunk-G6MPXBCD.js";import{a as f,c as P}from"./chunk-LGEZ3ZJX.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{e as a}from"./chunk-BJLA2IX7.js";import{b as w,d as y}from"./chunk-CKOF27L7.js";import{a as f,c as P}from"./chunk-RKXZLTWR.js";import{randomUUID as v}from"crypto";import*as i from"fs";import*as n from"path";import*as c from"os";y();P();var k=".aqe",b="schedules.json",F="1.0.0",g=5e3,x=50,p=10*1024*1024,d=class{schedulesPath;debug;lockFile;initialized=!1;constructor(e={}){e.schedulesPath&&this.validateSchedulesPath(e.schedulesPath),this.schedulesPath=e.schedulesPath??this.getDefaultSchedulesPath(),this.lockFile=`${this.schedulesPath}.lock`,this.debug=e.debug??!1}validateSchedulesPath(e){let s=c.homedir(),t=n.resolve(e),r=n.resolve(s);if(t.startsWith(r+n.sep)||t===r)return;let l=process.cwd(),h=n.resolve(l);if(t.startsWith(h+n.sep)||t===h)return;let u=c.tmpdir(),S=n.resolve(u);if(!(t.startsWith(S+n.sep)||t===S))throw new Error(`Security: Custom schedulesPath must be within home directory (${s}), current working directory (${l}), or temp directory (${u}). Provided path: ${e}`)}getDefaultSchedulesPath(){let e=c.homedir();return n.join(e,k,b)}async initialize(){if(this.initialized)return;let e=n.dirname(this.schedulesPath);i.existsSync(e)||(i.mkdirSync(e,{recursive:!0}),this.log(`Created directory: ${e}`)),this.initialized=!0}async loadSchedules(){if(await this.initialize(),!i.existsSync(this.schedulesPath))return this.log("Schedules file does not exist, returning empty array"),[];try{let e=i.readFileSync(this.schedulesPath,"utf-8"),s=this.parseSchedulesFile(e);return this.log(`Loaded ${s.schedules.length} schedules`),s.schedules}catch(e){return await this.handleCorruptFile(e),[]}}async saveSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.findIndex(r=>r.id===e.id);t>=0?(s[t]=e,this.log(`Updated schedule: ${e.id}`)):(s.push(e),this.log(`Added schedule: ${e.id}`)),await this.writeSchedules(s)})}async removeSchedule(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.filter(r=>r.id!==e);if(t.length===s.length){this.log(`Schedule not found: ${e}`);return}await this.writeSchedules(t),this.log(`Removed schedule: ${e}`)})}async getSchedules(){return this.loadSchedules()}async getSchedule(e){return(await this.loadSchedules()).find(t=>t.id===e)}async getDueSchedules(){let e=await this.loadSchedules(),s=new Date;return e.filter(t=>t.enabled?new Date(t.nextRun)<=s:!1)}async markExecuted(e){await this.initialize(),await this.withFileLock(async()=>{let s=await this.loadSchedulesUnsafe(),t=s.find(l=>l.id===e);if(!t)throw new Error(`Schedule not found: ${e}`);let r=new Date;t.lastRun=r.toISOString(),t.nextRun=a(t.schedule,r).toISOString(),await this.writeSchedules(s),this.log(`Marked executed: ${e}, next run: ${t.nextRun}`)})}async setEnabled(e,s){await this.initialize(),await this.withFileLock(async()=>{let t=await this.loadSchedulesUnsafe(),r=t.find(l=>l.id===e);if(!r)throw new Error(`Schedule not found: ${e}`);r.enabled=s,s&&(r.nextRun=a(r.schedule,new Date).toISOString()),await this.writeSchedules(t),this.log(`Set enabled=${s}: ${e}`)})}async getEnabledSchedules(){return(await this.loadSchedules()).filter(s=>s.enabled)}async getSchedulesByWorkflow(e){return(await this.loadSchedules()).filter(t=>t.workflowId===e)}async clearAll(){await this.initialize(),await this.withFileLock(async()=>{await this.writeSchedules([]),this.log("Cleared all schedules")})}async getStats(){let e=await this.loadSchedules(),s=new Date;return{total:e.length,enabled:e.filter(t=>t.enabled).length,disabled:e.filter(t=>!t.enabled).length,due:e.filter(t=>t.enabled&&new Date(t.nextRun)<=s).length}}async loadSchedulesUnsafe(){if(!i.existsSync(this.schedulesPath))return[];try{let e=i.readFileSync(this.schedulesPath,"utf-8");return this.parseSchedulesFile(e).schedules}catch{return[]}}parseSchedulesFile(e){let s=Buffer.byteLength(e,"utf-8");if(s>p)throw new Error(`Schedules file exceeds maximum allowed size (${p/(1024*1024)}MB). File is ${(s/(1024*1024)).toFixed(2)}MB.`);let t=w(e);if(!t.schedules||!Array.isArray(t.schedules))throw new Error("Invalid schedules file: missing schedules array");for(let r of t.schedules)if(!r.id||!r.workflowId||!r.schedule)throw new Error("Invalid schedule entry: missing required fields");return t}async writeSchedules(e){let s={version:F,updatedAt:new Date().toISOString(),schedules:e},t=JSON.stringify(s,null,2);i.writeFileSync(this.schedulesPath,t,"utf-8"),this.log(`Wrote ${e.length} schedules to disk`)}async handleCorruptFile(e){let s=f(e);this.log(`Corrupt schedules file detected: ${s}`);let t=`${this.schedulesPath}.corrupt.${Date.now()}`;try{i.existsSync(this.schedulesPath)&&(i.copyFileSync(this.schedulesPath,t),this.log(`Backed up corrupt file to: ${t}`))}catch(r){this.log(`Failed to backup corrupt file: ${r}`)}try{i.existsSync(this.schedulesPath)&&(i.unlinkSync(this.schedulesPath),this.log("Removed corrupt schedules file"))}catch(r){this.log(`Failed to remove corrupt file: ${r}`)}}async withFileLock(e){await this.acquireLock();try{return await e()}finally{this.releaseLock()}}async acquireLock(){let e=Date.now();for(;i.existsSync(this.lockFile);){try{let s=i.statSync(this.lockFile);if(Date.now()-s.mtimeMs>g){i.unlinkSync(this.lockFile),this.log("Removed stale lock file");break}}catch{break}if(Date.now()-e>g)throw new Error("Timeout waiting for scheduler lock");await this.sleep(x)}try{i.writeFileSync(this.lockFile,`${process.pid}:${Date.now()}`,{flag:"wx"})}catch(s){if(s.code==="EEXIST")return this.acquireLock();throw s}}releaseLock(){try{i.existsSync(this.lockFile)&&i.unlinkSync(this.lockFile)}catch(e){console.debug("[PersistentScheduler] Lock release error:",e instanceof Error?e.message:e)}}sleep(e){return new Promise(s=>setTimeout(s,e))}log(e){this.debug&&console.log(`[PersistentScheduler] ${e}`)}};function E(o={}){return new d(o)}function m(){let o=Date.now().toString(36),e=v().slice(0,8);return`sched-${o}-${e}`}function $(o){let e=new Date;return{id:m(),workflowId:o.workflowId,pipelinePath:o.pipelinePath,schedule:o.schedule,scheduleDescription:o.scheduleDescription,nextRun:a(o.schedule,e).toISOString(),enabled:o.enabled??!0,createdAt:e.toISOString()}}export{d as a,E as b,m as c,$ as d};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.3");process.exit(0)}
2
- import{a as F}from"./chunk-7S7QF4HJ.js";import{a as q,e as C,f as B}from"./chunk-3BREKEL5.js";import{a as I}from"./chunk-6KKKPVOF.js";import{a as z,b as H,c as _,d as U}from"./chunk-P4UGVVVX.js";import{a as A,b as N,f as W,i as O}from"./chunk-NBOEXSV2.js";import{e as j}from"./chunk-SFGBC5RP.js";import{b as v,d as L,f as M,g as P}from"./chunk-O7ZDQ5FF.js";import{a as K}from"./chunk-UNH2DE2G.js";import{c as D}from"./chunk-7UOH55UT.js";import{b as w,d as Y}from"./chunk-G6MPXBCD.js";import{b as f,c as h}from"./chunk-REZ2GZQ3.js";import{a as Q,b,c as J}from"./chunk-LGEZ3ZJX.js";import{i as T}from"./chunk-UFZCHVLH.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=j(this.qeConfig.sqlite),this.asymmetricEngine=new F}coherenceService;qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-EBRXKEX5.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{a as F}from"./chunk-AGJOGUP5.js";import{a as q,e as C,f as B}from"./chunk-B2VBDMDI.js";import{a as I}from"./chunk-VMWRMINE.js";import{a as z,b as H,c as _,d as U}from"./chunk-UORTQXJ2.js";import{a as A,b as N,f as W,i as O}from"./chunk-MCHEUSY4.js";import{d as j}from"./chunk-TRNBQFFG.js";import{b as v,d as L,f as M,g as P}from"./chunk-LPR2R3AN.js";import{a as K}from"./chunk-ZMPAM4DY.js";import{c as D}from"./chunk-Y25PO65W.js";import{b as w,d as Y}from"./chunk-CKOF27L7.js";import{b as f,c as h}from"./chunk-5WMU7XCF.js";import{a as Q,b,c as J}from"./chunk-RKXZLTWR.js";import{i as T}from"./chunk-K4I7UIU5.js";K();J();Y();var o=D.create("RealQEReasoningBank"),V={sqlite:{dbPath:".agentic-qe/memory.db",walMode:!0,useUnified:!0},embeddings:{modelName:"Xenova/all-MiniLM-L6-v2",quantized:!0,enableCache:!0},enableLearning:!0,enableRouting:!0,enableGuidance:!0,hnsw:{M:16,efConstruction:200,efSearch:100},routingWeights:{similarity:.3,performance:.4,capabilities:.3},coherenceThreshold:.4},R=class{constructor(e={},t){this.coherenceService=t;this.qeConfig={...V,...e},this.sqliteStore=j(this.qeConfig.sqlite),this.asymmetricEngine=new F}coherenceService;qeConfig;sqliteStore;hnswIndex=null;patternIdMap=new Map;initialized=!1;stats={routingRequests:0,totalRoutingLatency:0,learningOutcomes:0,successfulOutcomes:0};routingLatencies=new I(1e3);asymmetricEngine;agentCapabilities={"qe-test-generator":{domains:["test-generation"],capabilities:["test-generation","tdd","bdd","unit-test","integration-test"],performanceScore:.85},"qe-coverage-analyzer":{domains:["coverage-analysis"],capabilities:["coverage-analysis","gap-detection","risk-scoring"],performanceScore:.92},"qe-coverage-specialist":{domains:["coverage-analysis"],capabilities:["sublinear-analysis","branch-coverage","mutation-testing"],performanceScore:.88},"qe-test-architect":{domains:["test-generation","coverage-analysis"],capabilities:["test-strategy","test-pyramid","architecture"],performanceScore:.9},"qe-api-contract-validator":{domains:["contract-testing"],capabilities:["contract-testing","openapi","graphql","pact"],performanceScore:.87},"qe-security-auditor":{domains:["security-compliance"],capabilities:["sast","dast","vulnerability","owasp"],performanceScore:.82},"qe-visual-tester":{domains:["visual-accessibility"],capabilities:["screenshot","visual-regression","percy","chromatic"],performanceScore:.8},"qe-a11y-ally":{domains:["visual-accessibility"],capabilities:["wcag","aria","screen-reader","contrast"],performanceScore:.85},"qe-performance-tester":{domains:["chaos-resilience"],capabilities:["load-testing","stress-testing","k6","artillery"],performanceScore:.83},"qe-flaky-investigator":{domains:["test-execution"],capabilities:["flaky-detection","test-stability","retry"],performanceScore:.78},"qe-chaos-engineer":{domains:["chaos-resilience"],capabilities:["chaos-testing","resilience","fault-injection"],performanceScore:.75}};async initialize(){if(this.initialized)return;let e=performance.now();await this.sqliteStore.initialize(),o.info("SQLite persistence initialized"),await this.initializeHNSW(),o.info("HNSW index initialized"),await this.loadPatternsIntoHNSW(),this.sqliteStore.getStats().totalPatterns===0&&(this.sqliteStore.hasAnyHistoricalData?.()??!1?o.error("qe_patterns table is EMPTY but historical data exists \u2014 possible data loss! Restore from backup instead of loading seed patterns. Skipping foundational pattern load to avoid masking data loss."):await this.loadFoundationalPatterns()),this.initialized=!0;let i=performance.now()-e;o.info("Fully initialized",{durationMs:Math.round(i)})}async initializeHNSW(){try{let e=await import("./hnswlib-node-E6NSZPP2.js"),i=e.default?.HierarchicalNSW||e.HierarchicalNSW;if(typeof i!="function")throw new Error("HierarchicalNSW not found in hnswlib-node module");let n=i,a=P();this.hnswIndex=new n("cosine",a),this.hnswIndex.initIndex(1e5,this.qeConfig.hnsw.M,this.qeConfig.hnsw.efConstruction),this.hnswIndex.setEf(this.qeConfig.hnsw.efSearch),o.info("HNSW initialized",{dimension:a,M:this.qeConfig.hnsw.M})}catch(e){throw o.error("HNSW initialization failed",e instanceof Error?e:void 0),e}}async loadPatternsIntoHNSW(){if(!this.hnswIndex)return;let e=this.sqliteStore.getAllEmbeddings(),t=P(),i=0,n=0;for(let{patternId:a,embedding:s}of e){if(!s||!Array.isArray(s)||s.length!==t){n++;continue}let r=this.hnswIndex.getCurrentCount();this.hnswIndex.addPoint(s,r),this.patternIdMap.set(r,a),i++}n>0&&o.warn("Skipped invalid embeddings",{skipped:n,expectedDim:t}),o.info("Loaded patterns into HNSW index",{count:i})}async loadFoundationalPatterns(){let e=[{patternType:"test-template",name:"AAA Unit Test",description:"Arrange-Act-Assert pattern for clear, maintainable unit tests",template:{type:"code",content:`describe('{{className}}', () => {
3
3
  describe('{{methodName}}', () => {
4
4
  it('should {{expectedBehavior}}', {{async}} () => {
5
5
  // Arrange
@@ -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.11.3");process.exit(0)}
2
- import{c as s,e as t}from"./chunk-PUK5NE47.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>i,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>m,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>M,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>F,isDeterministicDitherEnabled:()=>C,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>P,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>T,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>u,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function i(){return{...e}}function o(n){e={...e,...n}}function u(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function C(){return e.useDeterministicDither}function T(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function M(){return e.useCusumDriftDetection}function F(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function m(){return e.useColdTierGNN}function P(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,i as b,o as c,u as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,C as l,T as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,M as C,F as D,L as E,x as F,h as G,m as H,P as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
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.11.5");process.exit(0)}
2
+ import{c as s,e as t}from"./chunk-C4EZNOWK.js";var K={};t(K,{DEFAULT_FEATURE_FLAGS:()=>r,getRuVectorFeatureFlags:()=>i,getRvfMigrationStage:()=>H,initFeatureFlagsFromEnv:()=>z,isAgentMemoryBranchingEnabled:()=>I,isCNNVisualRegressionEnabled:()=>b,isCognitiveRoutingEnabled:()=>Y,isCoherenceActionGateEnabled:()=>A,isCoherenceGateEnabled:()=>f,isColdTierGNNEnabled:()=>m,isCrossDomainTransferEnabled:()=>N,isCusumDriftDetectionEnabled:()=>M,isDAGAttentionEnabled:()=>g,isDeltaEventSourcingEnabled:()=>F,isDeterministicDitherEnabled:()=>C,isEpropOnlineLearningEnabled:()=>Q,isEwcPlusPlusEnabled:()=>L,isFlashAttentionEnabled:()=>E,isGNNIndexEnabled:()=>R,isGrangerCausalityEnabled:()=>B,isGraphMAEEnabled:()=>x,isHDCFingerprintingEnabled:()=>D,isHnswHealthMonitorEnabled:()=>U,isHopfieldMemoryEnabled:()=>h,isHyperbolicHnswEnabled:()=>k,isMetaLearningEnabled:()=>P,isMetadataFilteringEnabled:()=>S,isNativeHNSWEnabled:()=>_,isNeuralRoutingEnabled:()=>T,isRVFPatternStoreEnabled:()=>V,isReasoningQECEnabled:()=>v,isRegretTrackingEnabled:()=>O,isReservoirReplayEnabled:()=>w,isSONAEnabled:()=>a,isSONAThreeLoopEnabled:()=>p,isSpectralSparsificationEnabled:()=>W,isSublinearSolverEnabled:()=>y,isTemporalCompressionEnabled:()=>c,isUnifiedHnswEnabled:()=>G,isWitnessChainEnabled:()=>d,resetRuVectorFeatureFlags:()=>u,setRuVectorFeatureFlags:()=>o,shouldLogMigrationMetrics:()=>l});function i(){return{...e}}function o(n){e={...e,...n}}function u(){e={...r}}function a(){return e.useQESONA}function E(){return e.useQEFlashAttention}function R(){return e.useQEGNNIndex}function l(){return e.logMigrationMetrics}function _(){return e.useNativeHNSW}function c(){return e.useTemporalCompression}function S(){return e.useMetadataFiltering}function C(){return e.useDeterministicDither}function T(){return e.useNeuralRouting}function p(){return e.useSONAThreeLoop}function N(){return e.useCrossDomainTransfer}function U(){return e.useHnswHealthMonitor}function O(){return e.useRegretTracking}function f(){return e.useCoherenceGate}function d(){return e.useWitnessChain}function b(){return e.useCNNVisualRegression}function g(){return e.useDAGAttention}function A(){return e.useCoherenceActionGate}function v(){return e.useReasoningQEC}function V(){return e.useRVFPatternStore}function I(){return e.useAgentMemoryBranching}function G(){return e.useUnifiedHnsw}function H(){return e.rvfMigrationStage}function D(){return e.useHDCFingerprinting}function M(){return e.useCusumDriftDetection}function F(){return e.useDeltaEventSourcing}function L(){return e.useEwcPlusPlusRegularization}function x(){return e.useGraphMAEEmbeddings}function h(){return e.useHopfieldMemory}function m(){return e.useColdTierGNN}function P(){return e.useMetaLearningEnhancements}function y(){return e.useSublinearSolver}function W(){return e.useSpectralSparsification}function w(){return e.useReservoirReplay}function Q(){return e.useEpropOnlineLearning}function B(){return e.useGrangerCausality}function Y(){return e.useCognitiveRouting}function k(){return e.useHyperbolicHnsw}function z(){let n={};process.env.RUVECTOR_USE_SONA!==void 0&&(n.useQESONA=process.env.RUVECTOR_USE_SONA==="true"),process.env.RUVECTOR_USE_FLASH_ATTENTION!==void 0&&(n.useQEFlashAttention=process.env.RUVECTOR_USE_FLASH_ATTENTION==="true"),process.env.RUVECTOR_USE_GNN_INDEX!==void 0&&(n.useQEGNNIndex=process.env.RUVECTOR_USE_GNN_INDEX==="true"),process.env.RUVECTOR_LOG_MIGRATION_METRICS!==void 0&&(n.logMigrationMetrics=process.env.RUVECTOR_LOG_MIGRATION_METRICS==="true"),process.env.RUVECTOR_USE_NATIVE_HNSW!==void 0&&(n.useNativeHNSW=process.env.RUVECTOR_USE_NATIVE_HNSW==="true"),process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION!==void 0&&(n.useTemporalCompression=process.env.RUVECTOR_USE_TEMPORAL_COMPRESSION==="true"),process.env.RUVECTOR_USE_METADATA_FILTERING!==void 0&&(n.useMetadataFiltering=process.env.RUVECTOR_USE_METADATA_FILTERING==="true"),process.env.RUVECTOR_USE_DETERMINISTIC_DITHER!==void 0&&(n.useDeterministicDither=process.env.RUVECTOR_USE_DETERMINISTIC_DITHER==="true"),process.env.RUVECTOR_USE_NEURAL_ROUTING!==void 0&&(n.useNeuralRouting=process.env.RUVECTOR_USE_NEURAL_ROUTING==="true"),process.env.RUVECTOR_USE_SONA_THREE_LOOP!==void 0&&(n.useSONAThreeLoop=process.env.RUVECTOR_USE_SONA_THREE_LOOP==="true"),process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER!==void 0&&(n.useCrossDomainTransfer=process.env.RUVECTOR_USE_CROSS_DOMAIN_TRANSFER==="true"),process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR!==void 0&&(n.useHnswHealthMonitor=process.env.RUVECTOR_USE_HNSW_HEALTH_MONITOR==="true"),process.env.RUVECTOR_USE_REGRET_TRACKING!==void 0&&(n.useRegretTracking=process.env.RUVECTOR_USE_REGRET_TRACKING==="true"),process.env.RUVECTOR_USE_COHERENCE_GATE!==void 0&&(n.useCoherenceGate=process.env.RUVECTOR_USE_COHERENCE_GATE==="true"),process.env.RUVECTOR_USE_WITNESS_CHAIN!==void 0&&(n.useWitnessChain=process.env.RUVECTOR_USE_WITNESS_CHAIN==="true"),process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION!==void 0&&(n.useCNNVisualRegression=process.env.RUVECTOR_USE_CNN_VISUAL_REGRESSION==="true"),process.env.RUVECTOR_USE_DAG_ATTENTION!==void 0&&(n.useDAGAttention=process.env.RUVECTOR_USE_DAG_ATTENTION==="true"),process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE!==void 0&&(n.useCoherenceActionGate=process.env.RUVECTOR_USE_COHERENCE_ACTION_GATE==="true"),process.env.RUVECTOR_USE_REASONING_QEC!==void 0&&(n.useReasoningQEC=process.env.RUVECTOR_USE_REASONING_QEC==="true"),process.env.RUVECTOR_USE_HDC_FINGERPRINTING!==void 0&&(n.useHDCFingerprinting=process.env.RUVECTOR_USE_HDC_FINGERPRINTING==="true"),process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION!==void 0&&(n.useCusumDriftDetection=process.env.RUVECTOR_USE_CUSUM_DRIFT_DETECTION==="true"),process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING!==void 0&&(n.useDeltaEventSourcing=process.env.RUVECTOR_USE_DELTA_EVENT_SOURCING==="true"),process.env.RUVECTOR_USE_EWC_PLUS_PLUS!==void 0&&(n.useEwcPlusPlusRegularization=process.env.RUVECTOR_USE_EWC_PLUS_PLUS==="true"),process.env.RUVECTOR_USE_META_LEARNING!==void 0&&(n.useMetaLearningEnhancements=process.env.RUVECTOR_USE_META_LEARNING==="true"),process.env.RUVECTOR_USE_SUBLINEAR_SOLVER!==void 0&&(n.useSublinearSolver=process.env.RUVECTOR_USE_SUBLINEAR_SOLVER==="true"),process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION!==void 0&&(n.useSpectralSparsification=process.env.RUVECTOR_USE_SPECTRAL_SPARSIFICATION==="true"),process.env.RUVECTOR_USE_RESERVOIR_REPLAY!==void 0&&(n.useReservoirReplay=process.env.RUVECTOR_USE_RESERVOIR_REPLAY==="true"),process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING!==void 0&&(n.useEpropOnlineLearning=process.env.RUVECTOR_USE_EPROP_ONLINE_LEARNING==="true"),process.env.RUVECTOR_USE_GRANGER_CAUSALITY!==void 0&&(n.useGrangerCausality=process.env.RUVECTOR_USE_GRANGER_CAUSALITY==="true"),process.env.RUVECTOR_USE_COGNITIVE_ROUTING!==void 0&&(n.useCognitiveRouting=process.env.RUVECTOR_USE_COGNITIVE_ROUTING==="true"),process.env.RUVECTOR_USE_HYPERBOLIC_HNSW!==void 0&&(n.useHyperbolicHnsw=process.env.RUVECTOR_USE_HYPERBOLIC_HNSW==="true"),o(n)}var r,e,X=s(()=>{r={useQESONA:!0,useQEFlashAttention:!0,useQEGNNIndex:!0,logMigrationMetrics:!0,useNativeHNSW:!0,useTemporalCompression:!0,useMetadataFiltering:!0,useDeterministicDither:!0,useNeuralRouting:!0,useSONAThreeLoop:!0,useCrossDomainTransfer:!0,useHnswHealthMonitor:!0,useRegretTracking:!0,useCoherenceGate:!0,useWitnessChain:!0,useCNNVisualRegression:!0,useDAGAttention:!0,useCoherenceActionGate:!0,useReasoningQEC:!0,useRVFPatternStore:!0,useAgentMemoryBranching:!0,useUnifiedHnsw:!0,rvfMigrationStage:2,useHDCFingerprinting:!0,useCusumDriftDetection:!0,useDeltaEventSourcing:!0,useEwcPlusPlusRegularization:!0,useGraphMAEEmbeddings:!0,useHopfieldMemory:!0,useColdTierGNN:!0,useMetaLearningEnhancements:!0,useSublinearSolver:!0,useSpectralSparsification:!0,useReservoirReplay:!0,useEpropOnlineLearning:!0,useGrangerCausality:!0,useCognitiveRouting:!1,useHyperbolicHnsw:!1},e={...r}});export{r as a,i as b,o as c,u as d,a as e,E as f,R as g,l as h,_ as i,c as j,S as k,C as l,T as m,p as n,N as o,U as p,O as q,f as r,d as s,b as t,g as u,A as v,v as w,V as x,I as y,G as z,H as A,D as B,M as C,F as D,L as E,x as F,h as G,m as H,P as I,y as J,W as K,w as L,Q as M,B as N,Y as O,k as P,z as Q,K as R,X as S};
@@ -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.11.3");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-6JR2RSY2.js";import{i as g,m as P}from"./chunk-JVXPKHND.js";import{a as d,b as y,c as R}from"./chunk-LGEZ3ZJX.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-MIU5RUBJ.js";import{i as g,m as P}from"./chunk-NCSXLMDL.js";import{a as d,b as y,c as R}from"./chunk-RKXZLTWR.js";R();import{randomUUID as M}from"crypto";var p=class{constructor(e){this.config=e}config;_status="idle";_lastResult;_lastRunAt;_nextRunAt;_totalExecutions=0;_successfulExecutions=0;_failedExecutions=0;_executionDurations=[];_recentResults=[];get status(){return this._status}get lastResult(){return this._lastResult}get lastRunAt(){return this._lastRunAt}get nextRunAt(){return this._nextRunAt}async initialize(){this._status="idle",this._nextRunAt=new Date(Date.now()+this.config.intervalMs)}async execute(e){let r=Date.now();this._status="running",this._lastRunAt=new Date,this._totalExecutions++;let n,t;for(let a=0;a<=this.config.retryCount;a++)try{if(e.signal.aborted)throw new Error("Worker execution aborted");t=await this.executeWithTimeout(()=>this.doExecute(e),this.config.timeoutMs,e.signal);break}catch(u){n=y(u),e.logger.warn(`Worker ${this.config.id} attempt ${a+1} failed: ${n.message}`),a<this.config.retryCount&&await this.delay(this.config.retryDelayMs)}let o=Date.now()-r;return t?(this._successfulExecutions++,this._lastResult=t):(this._failedExecutions++,t=this.createErrorResult(n,o),this._lastResult=t),this._executionDurations.push(o),this._executionDurations.length>100&&this._executionDurations.shift(),this._recentResults.push({timestamp:new Date,success:t.success,durationMs:o}),this._recentResults.length>5&&this._recentResults.shift(),this._nextRunAt=new Date(Date.now()+this.config.intervalMs),this._status=t.success?"idle":"error",await e.eventBus.publish({type:"worker.executed",workerId:this.config.id,timestamp:new Date,payload:{success:t.success,durationMs:o,findingsCount:t.findings.length,healthScore:t.metrics.healthScore}}),t}pause(){this._status!=="stopped"&&(this._status="paused")}resume(){this._status==="paused"&&(this._status="idle")}async stop(){this._status="stopped"}getHealth(){let e=this._executionDurations.length>0?this._executionDurations.reduce((n,t)=>n+t,0)/this._executionDurations.length:0,r=this._totalExecutions>0?this._successfulExecutions/this._totalExecutions:1;return{status:this._status,healthScore:Math.round(r*100),totalExecutions:this._totalExecutions,successfulExecutions:this._successfulExecutions,failedExecutions:this._failedExecutions,avgDurationMs:Math.round(e),recentResults:[...this._recentResults]}}async executeWithTimeout(e,r,n){return new Promise((t,o)=>{let a=setTimeout(()=>{o(new Error(`Worker execution timed out after ${r}ms`))},r),u=()=>{clearTimeout(a),o(new Error("Worker execution aborted"))};n.addEventListener("abort",u,{once:!0}),e().then(c=>{clearTimeout(a),n.removeEventListener("abort",u),t(c)}).catch(c=>{clearTimeout(a),n.removeEventListener("abort",u),o(c)})})}createErrorResult(e,r){return{workerId:this.config.id,timestamp:new Date,durationMs:r,success:!1,error:e.message,metrics:{itemsAnalyzed:0,issuesFound:0,healthScore:0,trend:"degrading",domainMetrics:{}},findings:[],recommendations:[]}}createResult(e,r,n,t){return{workerId:this.config.id,timestamp:new Date,durationMs:e,success:!0,metrics:r,findings:n,recommendations:t}}delay(e){return new Promise(r=>setTimeout(r,e))}generateId(){return`${Date.now()}-${M().slice(0,9)}`}};P();R();var W={id:"heartbeat-scheduler",name:"Heartbeat Scheduler",description:"Token-free maintenance: pattern promotion, stale detection, experience buffer monitoring",intervalMs:1800*1e3,priority:"normal",targetDomains:["learning-optimization"],enabled:!0,timeoutMs:6e4,retryCount:1,retryDelayMs:5e3},b=class extends p{lifecycleManager=null;dailyLogger;lastRunTimestamp=0;constructor(){super(W),this.dailyLogger=new k}async getLifecycleManager(){if(this.lifecycleManager)return this.lifecycleManager;try{let e=g();await e.initialize();let r=e.getDatabase();return this.lifecycleManager=v(r,{promotionRewardThreshold:.7,promotionMinOccurrences:2,promotionMinSuccessRate:.7,deprecationFailureThreshold:3,staleDaysThreshold:30,confidenceDecayRate:.01,minActiveConfidence:.3}),this.lifecycleManager}catch{return null}}getPendingExperienceCount(){try{return g().getDatabase().prepare("SELECT COUNT(*) as pending FROM qe_pattern_usage WHERE created_at > datetime('now', '-1 day')").get()?.pending??0}catch{return 0}}async doExecute(e){let r=Date.now();e.logger.info("Heartbeat scheduler running (token-free maintenance)");let n=[],t=[],o=await this.getLifecycleManager();if(!o)return e.logger.warn("Unified memory unavailable \u2014 returning zero-metric heartbeat"),this.createResult(Date.now()-r,{itemsAnalyzed:0,issuesFound:0,healthScore:50,trend:"stable",domainMetrics:{promoted:0,deprecated:0,decayed:0,stalePatterns:0,pendingExperiences:0,avgConfidence:0,avgSuccessRate:0}},[],[]);let a=0,u=0;try{let s=o.promoteEligiblePatterns();a=s.promoted,u=s.checked,a>0&&n.push({type:"heartbeat-promotion",severity:"info",domain:"learning-optimization",title:"Patterns Promoted",description:`${a} of ${u} short-term patterns promoted to long-term`})}catch(s){e.logger.warn("Pattern promotion failed",{error:d(s)})}let c=0,h=0;try{let s=o.deprecateStalePatterns();c=s.deprecated,h=s.checked,c>0&&n.push({type:"heartbeat-deprecation",severity:"low",domain:"learning-optimization",title:"Stale Patterns Deprecated",description:`${c} of ${h} patterns deprecated (stale, failed, or low confidence)`})}catch(s){e.logger.warn("Stale pattern detection failed",{error:d(s)})}let l=0;try{let s=this.lastRunTimestamp>0?(Date.now()-this.lastRunTimestamp)/864e5:1;l=o.applyConfidenceDecay(Math.min(s,7)).decayed}catch(s){e.logger.warn("Confidence decay failed",{error:d(s)})}let m=this.getPendingExperienceCount(),i={totalPatterns:0,activePatterns:0,deprecatedPatterns:0,promotedPatterns:0,shortTermPatterns:0,longTermPatterns:0,avgConfidence:0,avgSuccessRate:0,patternsNearDeprecation:0};try{i=o.getStats()}catch(s){e.logger.warn("Stats retrieval failed",{error:d(s)})}try{this.dailyLogger.log({timestamp:new Date,type:"pattern-promoted",summary:`Heartbeat: ${a} promoted, ${c} deprecated, ${l} decayed, ${m} pending exp, ${i.activePatterns} active patterns (avg conf: ${i.avgConfidence.toFixed(2)})`,details:{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,totalPatterns:i.totalPatterns,activePatterns:i.activePatterns,avgConfidence:i.avgConfidence,avgSuccessRate:i.avgSuccessRate}}),this.dailyLogger.flush()}catch(s){e.logger.warn("Daily log write failed",{error:d(s)})}this.lastRunTimestamp=Date.now(),i.activePatterns>0&&i.patternsNearDeprecation/i.activePatterns>.5&&t.push({priority:"p2",domain:"learning-optimization",action:"Review At-Risk Patterns",description:`${i.patternsNearDeprecation} of ${i.activePatterns} active patterns are near deprecation. Manual review recommended.`,estimatedImpact:"medium",effort:"low",autoFixable:!1});let f=this.calculateHealthScore(i,a,c),D=this.determineTrend(a,c,i.activePatterns),_=Math.max(u,h),x=a+c+i.patternsNearDeprecation;return e.logger.info("Heartbeat complete",{promoted:a,deprecated:c,decayed:l,pendingExperiences:m,healthScore:f}),this.createResult(Date.now()-r,{itemsAnalyzed:_,issuesFound:x,healthScore:f,trend:D,domainMetrics:{promoted:a,deprecated:c,decayed:l,stalePatterns:i.patternsNearDeprecation,pendingExperiences:m,avgConfidence:Number(i.avgConfidence.toFixed(3)),avgSuccessRate:Number(i.avgSuccessRate.toFixed(3))}},n,t)}calculateHealthScore(e,r,n){let t=70;if(t+=Math.min(15,r*5),e.avgConfidence>0&&(t+=Math.round((e.avgConfidence-.5)*30)),e.activePatterns>0){let o=n/e.activePatterns;t-=Math.round(o*20)}return e.activePatterns>0&&e.patternsNearDeprecation/e.activePatterns>.5&&(t-=10),Math.max(0,Math.min(100,Math.round(t)))}determineTrend(e,r,n){return n===0?"stable":e>r?"improving":r>e&&r/n>.1?"degrading":"stable"}};export{p as a,b};
@@ -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.11.3");process.exit(0)}
2
- import{p as O,q}from"./chunk-CLZ5RQVA.js";import{i as T,m as U}from"./chunk-JVXPKHND.js";import{i as b}from"./chunk-UFZCHVLH.js";import{b as M,c as H}from"./chunk-OVEG5MEL.js";import{g as C}from"./chunk-PUK5NE47.js";U();var _=null;function w(){if(_)return _;let E=(q(),C(O));if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function L(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;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.initialized=new Set,this.nextId=new Map,this.useUnified=L(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=(H(),C(M)),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=w(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=w(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var W={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...W,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=T();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=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.11.5");process.exit(0)}
2
+ import{p as O,q}from"./chunk-PVDXNQPL.js";import{i as T,m as U}from"./chunk-NCSXLMDL.js";import{i as b}from"./chunk-K4I7UIU5.js";import{b as M,c as H}from"./chunk-2XPMATEK.js";import{g as C}from"./chunk-C4EZNOWK.js";U();var _=null;function w(){if(_)return _;let E=(q(),C(O));if(!E.HierarchicalNSW)throw new Error("hnswlib-node module missing HierarchicalNSW export");return _=E.HierarchicalNSW,_}function L(){return!0}var x=class{indexes;config;initialized;nextId;unifiedAdapters=null;useUnified;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.initialized=new Set,this.nextId=new Map,this.useUnified=L(),this.useUnified&&(this.unifiedAdapters=new Map)}initializeIndex(e){if(this.initialized.has(e))return;if(this.useUnified&&this.unifiedAdapters)try{let{HnswAdapter:s}=(H(),C(M)),d=new s(`embedding-${e}`,{dimensions:this.config.dimension,M:this.config.M,efConstruction:this.config.efConstruction,efSearch:this.config.efSearch,metric:this.config.metric==="dotproduct"?"cosine":this.config.metric});this.unifiedAdapters.set(e,d),this.initialized.add(e),this.nextId.set(e,0);return}catch{}let t={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",n=w(),r=new n(t,this.config.dimension);r.initIndex({maxElements:1e4,m:this.config.M,efConstruction:this.config.efConstruction}),this.indexes.set(e,r),this.initialized.add(e),this.nextId.set(e,0)}addEmbedding(e,i){let t=e.namespace;this.initialized.has(t)||this.initializeIndex(t);let n=i??this.nextId.get(t);i===void 0&&this.nextId.set(t,n+1);let r=this.unifiedAdapters?.get(t);if(r){let o=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.add(n,o),n}let s=this.indexes.get(t),d=this.toFloatArray(e.vector);return s.addPoint(d,n),n}addEmbeddingsBatch(e){return e.map(i=>this.addEmbedding(i.embedding,i.id))}search(e,i={}){let t=i.namespace||e.namespace;if(!this.initialized.has(t))return[];let n=i.limit||10,r=this.unifiedAdapters?.get(t);if(r){let l=e.vector instanceof Float32Array?e.vector:new Float32Array(this.toFloatArray(e.vector));return r.search(l,n).map(u=>({id:u.id,distance:1-u.score}))}let s=this.indexes.get(t),d=this.toFloatArray(e.vector),o=s.searchKnn(d,n);return o.neighbors.map((l,m)=>({id:l,distance:o.distances[m]}))}getIndexStats(e){if(!this.initialized.has(e))return null;let i=this.unifiedAdapters?.get(e);return i?{size:i.size(),maxElements:1e4,dimension:i.dimensions(),metric:this.config.metric}:{size:this.indexes.get(e).getCurrentCount(),maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}}async saveIndex(e,i){if(!this.initialized.has(e))throw new Error(`Namespace ${e} not initialized`);if(this.unifiedAdapters?.has(e)){console.warn(`[HNSWEmbeddingIndex] saveIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally.`);return}await this.indexes.get(e).writeIndex(i)}async loadIndex(e,i){if(this.useUnified){console.warn(`[HNSWEmbeddingIndex] loadIndex() is a no-op for namespace '${e}' \u2014 unified HnswAdapter manages persistence internally. Initialize via initializeIndex() instead.`);return}let n={cosine:"cosine",euclidean:"l2",dotproduct:"ip"}[this.config.metric]||"cosine",r=w(),s=new r(n,this.config.dimension);await s.readIndex(i),this.indexes.set(e,s),this.initialized.add(e)}clearIndex(e){if(this.initialized.has(e)){let i=this.unifiedAdapters?.get(e);i&&(i.clear?.(),this.unifiedAdapters.delete(e)),this.indexes.delete(e),this.initialized.delete(e),this.nextId.delete(e)}}clearAll(){if(this.unifiedAdapters){for(let e of this.unifiedAdapters.values())e.clear?.();this.unifiedAdapters.clear()}this.indexes.clear(),this.initialized.clear(),this.nextId.clear()}resizeIndex(e,i){this.initialized.has(e)&&(this.clearIndex(e),this.initializeIndex(e))}setEfSearch(e){this.config.efSearch=e}toFloatArray(e){if(Array.isArray(e))return e;if(e instanceof Float32Array)return Array.from(e);if(e instanceof Int8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=e[t]/128;return i}if(e instanceof Uint8Array){let i=new Array(e.length);for(let t=0;t<e.length;t++)i[t]=(e[t]-128)/128;return i}throw new Error(`Unsupported vector type: ${typeof e}`)}getConfig(){return{...this.config}}isInitialized(e){return this.initialized.has(e)}getInitializedNamespaces(){return Array.from(this.initialized)}getSize(e){if(!this.initialized.has(e))return 0;let i=this.unifiedAdapters?.get(e);return i?i.size():this.nextId.get(e)||0}};var W={mergeSimilarityThreshold:.85,maxMergesPerRun:50,softThreshold:400,hardThreshold:2e3,archiveMinAgeDays:30,archiveQualityThreshold:.15,mergeQualityBoost:.02,contradictionSimilarityThreshold:.85,contradictionQualityDelta:.4},R=class{config;db=null;initialized=!1;constructor(e={}){this.config={...W,...e}}async initialize(e){if(!this.initialized){if(e)this.db=e;else{let i=T();await i.initialize(),this.db=i.getDatabase()}this.initialized=!0}}async consolidateAll(e){this.ensureInitialized();let i={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[]},t=this.db.prepare("SELECT domain, COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL GROUP BY domain").all(),n=e?t.filter(s=>e.includes(s.domain)):t.filter(s=>s.cnt>this.config.softThreshold);for(let{domain:s,cnt:d}of n){let o=await this.consolidateDomain(s,d);i.merged+=o.merged,i.contradicted+=o.contradicted,i.qualityUpdated+=o.qualityUpdated,i.archived+=o.archived,i.hardDeleted+=o.hardDeleted,i.domainsProcessed.push(s)}let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE consolidated_into IS NULL").get();return i.activeRemaining=r.cnt,(i.merged>0||i.archived>0||i.contradicted>0)&&console.log(`[ExperienceConsolidator] Consolidated: ${i.merged} merged, ${i.contradicted} contradicted, ${i.archived} archived, ${i.activeRemaining} active`),i}async consolidateDomain(e,i){this.ensureInitialized();let t={merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]},n=await this.clusterAndMerge(e);t.merged=n.merged,t.contradicted=n.contradicted,t.qualityUpdated=this.reinforceQuality(e),t.archived=this.archiveValueless(e);let r=this.db.prepare("SELECT COUNT(*) as cnt FROM captured_experiences WHERE domain = ? AND consolidated_into IS NULL").get(e).cnt,s=0;return r>this.config.hardThreshold&&(s=this.hardDeleteExcess(e,r),t.archived+=s),t.activeRemaining=r-s,t}async bootstrapDomain(e){if(this.ensureInitialized(),this.db.prepare("SELECT value FROM kv_store WHERE key = ?").get(`consolidation_bootstrap_${e}`))return console.log(`[ExperienceConsolidator] Domain ${e} already bootstrapped`),{merged:0,contradicted:0,qualityUpdated:0,archived:0,hardDeleted:0,activeRemaining:0,domainsProcessed:[e]};let t={...this.config};this.config.mergeSimilarityThreshold=.8,this.config.maxMergesPerRun=200;let n=await this.consolidateDomain(e);Object.assign(this.config,t);try{this.db.prepare("INSERT OR REPLACE INTO kv_store (key, value, namespace) VALUES (?, ?, 'system')").run(`consolidation_bootstrap_${e}`,new Date().toISOString())}catch{}return console.log(`[ExperienceConsolidator] Bootstrap ${e}: ${n.merged} merged, ${n.archived} archived`),n}async clusterAndMerge(e){let i=this.db.prepare(`
3
3
  SELECT id, task, domain, quality, success, application_count,
4
4
  consolidation_count, reuse_success_count, reuse_failure_count,
5
5
  embedding, embedding_dimension, started_at
@@ -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.11.3");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.11.5");process.exit(0)}
2
2
  import r from"chalk";function s(e){switch(e){case"healthy":case"completed":return r.green(e);case"idle":return r.cyan(e);case"degraded":case"running":return r.yellow(e);case"unhealthy":case"failed":return r.red(e);default:return r.gray(e)}}function a(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:e<36e5?`${(e/6e4).toFixed(1)}m`:`${(e/36e5).toFixed(1)}h`}function l(e){let t=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4),o=Math.floor(e%6e4/1e3);return`${t}h ${n}m ${o}s`}export{s as a,a as b,l as c};
@@ -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.11.3");process.exit(0)}
2
- import{S as f,b as p}from"./chunk-L6PH7JIE.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.11.5");process.exit(0)}
2
+ import{S as f,b as p}from"./chunk-GODAWJMZ.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
@@ -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.11.3");process.exit(0)}
2
- import{f as s,i as o,m as h}from"./chunk-JVXPKHND.js";import{a as m}from"./chunk-UNH2DE2G.js";import{c as r}from"./chunk-7UOH55UT.js";import{a,e as u}from"./chunk-77QJQRL2.js";h();u();m();var l=r.create("hybrid-backend"),c=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),d=await this.unifiedMemory.vectorDelete(e);return n||d}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().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.11.5");process.exit(0)}
2
+ import{f as s,i as o,m as h}from"./chunk-NCSXLMDL.js";import{a as m}from"./chunk-ZMPAM4DY.js";import{c as r}from"./chunk-Y25PO65W.js";import{a,e as u}from"./chunk-FIPKIIMS.js";h();u();m();var l=r.create("hybrid-backend"),c=class{unifiedMemory=null;config;cleanupInterval;cleanupCount=0;initialized=!1;constructor(e){this.config={sqlite:{path:e?.sqlite?.path??".agentic-qe/memory.db",walMode:e?.sqlite?.walMode??!0,poolSize:e?.sqlite?.poolSize??5,busyTimeout:e?.sqlite?.busyTimeout??a.BUSY_TIMEOUT_MS,...e?.sqlite},agentdb:{path:e?.agentdb?.path??".agentic-qe/memory.db",...e?.agentdb},enableFallback:e?.enableFallback??!0,defaultNamespace:e?.defaultNamespace??"default",cleanupInterval:e?.cleanupInterval??a.CLEANUP_INTERVAL_MS}}async initialize(e){if(this.initialized)return;let i=e?.signal;i?.throwIfAborted();let t={dbPath:this.config.sqlite.path??s.dbPath,walMode:this.config.sqlite.walMode??!0,busyTimeout:this.config.sqlite.busyTimeout??a.BUSY_TIMEOUT_MS};this.unifiedMemory=o(t),i?.throwIfAborted(),await this.unifiedMemory.initialize({signal:i}),i?.throwIfAborted(),this.cleanupInterval=setInterval(()=>this.cleanup(),this.config.cleanupInterval),this.cleanupInterval.unref&&this.cleanupInterval.unref(),this.initialized=!0,console.log(`[HybridBackend] Initialized with unified memory: ${this.unifiedMemory.getDbPath()}`)}async dispose(){this.cleanupInterval&&clearInterval(this.cleanupInterval),this.initialized=!1}async set(e,i,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;await this.unifiedMemory.kvSet(e,i,n,t?.ttl)}async get(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvGet(e,t)}async delete(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace,n=await this.unifiedMemory.kvDelete(e,t),d=await this.unifiedMemory.vectorDelete(e);return n||d}async has(e,i){this.ensureInitialized();let t=i?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvExists(e,t)}async search(e,i=100,t){this.ensureInitialized();let n=t?.namespace??this.config.defaultNamespace;return this.unifiedMemory.kvSearch(e,n,i)}async vectorSearch(e,i){return this.ensureInitialized(),(await this.unifiedMemory.vectorSearch(e,i)).map(n=>({key:n.id,score:n.score,metadata:n.metadata}))}async storeVector(e,i,t){this.ensureInitialized(),await this.unifiedMemory.vectorStore(e,i,this.config.defaultNamespace,t)}getHealth(){return{sqlite:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",sqlitePersistent:!0,agentdb:this.unifiedMemory?.isInitialized()?"healthy":"unavailable",fallback:"inactive"}}isPersistent(){return this.unifiedMemory?.isInitialized()??!1}getConfig(){return{...this.config}}async setWithBackend(e,i,t,n){await this.set(e,i,n)}async getVectorStats(){if(!this.unifiedMemory?.isInitialized())return null;let e=await this.unifiedMemory.vectorCount(),i=this.unifiedMemory.getStats();return{vectorCount:e,indexSize:i.vectorIndexSize}}getUnifiedMemory(){return this.unifiedMemory}async count(e){return this.ensureInitialized(),this.unifiedMemory.getDatabase().prepare(`
3
3
  SELECT COUNT(*) as count FROM kv_store
4
4
  WHERE namespace LIKE ?
5
5
  AND (expires_at IS NULL OR expires_at > ?)
@@ -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.11.5");process.exit(0)}
2
+ import{b as k,c as p}from"./chunk-YFCULQBP.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,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.11.3");process.exit(0)}
2
- import{c as t}from"./chunk-PUK5NE47.js";function o(e){try{return 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.11.5");process.exit(0)}
2
+ import{c as t}from"./chunk-C4EZNOWK.js";function o(e){try{return e.prepare(`
3
3
  SELECT COUNT(*) as count FROM sqlite_master
4
4
  WHERE type='table' AND name IN ('hypergraph_nodes', 'hypergraph_edges')
5
5
  `).get().count===2}catch{return!1}}var r,a,E,n,p=t(()=>{"use strict";r=`