agentic-qe 3.10.3 → 3.10.4

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 (333) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +33 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-A62ETL5C.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-NGC6LSQP.js → agent-booster-wasm-EJPDSWON.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-P2IJE4GK.js → agent-handler-2DZB7LGI.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-JXRJ5GKQ.js → agent-memory-branch-SSFYAVIK.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-MTCRAV6N.js +2 -0
  10. package/dist/cli/chunks/audit-42XG5JFB.js +3 -0
  11. package/dist/cli/chunks/base-KKEBUHZC.js +2 -0
  12. package/dist/cli/chunks/{hnswlib-node-64EGGWIC.js → better-sqlite3-PX5JM3DG.js} +2 -2
  13. package/dist/cli/chunks/{brain-handler-SACNDFSW.js → brain-handler-LFHX2TYP.js} +3 -3
  14. package/dist/cli/chunks/{branch-enumerator-LFOTVUDA.js → branch-enumerator-AX7DKGV7.js} +2 -2
  15. package/dist/cli/chunks/{browser-FK7PRF3W.js → browser-4NYLZ7FA.js} +2 -2
  16. package/dist/cli/chunks/browser-workflow-XHYAJUB6.js +2 -0
  17. package/dist/cli/chunks/{chunk-3LRK7PYN.js → chunk-2B6ETC7C.js} +2 -2
  18. package/dist/cli/chunks/{chunk-VRXY4T22.js → chunk-2G2PVVQG.js} +2 -2
  19. package/dist/cli/chunks/{chunk-EETVN2OJ.js → chunk-2L5VFVCG.js} +1 -1
  20. package/dist/cli/chunks/{chunk-CNEWYJKT.js → chunk-2TYO4VZH.js} +3 -3
  21. package/dist/cli/chunks/{chunk-GHNNJHH3.js → chunk-3ISX5B77.js} +2 -2
  22. package/dist/cli/chunks/{chunk-X2B7SANM.js → chunk-3UGUX34A.js} +1 -1
  23. package/dist/cli/chunks/{chunk-VIWIO27R.js → chunk-4BX72XG4.js} +2 -2
  24. package/dist/cli/chunks/{chunk-3HBWDG62.js → chunk-4FTLYIMW.js} +2 -2
  25. package/dist/cli/chunks/{chunk-KG5SM36Y.js → chunk-5FNNCVXR.js} +1 -1
  26. package/dist/cli/chunks/{chunk-72LE6PHL.js → chunk-5Q3L4QEE.js} +2 -2
  27. package/dist/cli/chunks/{chunk-NZHOKLII.js → chunk-5T2HDET6.js} +3 -3
  28. package/dist/cli/chunks/{chunk-OX4R55T3.js → chunk-5T4J3IPG.js} +2 -2
  29. package/dist/cli/chunks/{chunk-QWG76RHA.js → chunk-6OLHPWSN.js} +2 -2
  30. package/dist/cli/chunks/{chunk-M5CDW2ZH.js → chunk-6SCIX2W2.js} +2 -2
  31. package/dist/cli/chunks/{chunk-MQOFFRTA.js → chunk-6WF2MOQB.js} +2 -2
  32. package/dist/cli/chunks/{chunk-JP63XACW.js → chunk-7BQXEYRV.js} +2 -2
  33. package/dist/cli/chunks/{chunk-H56AROF2.js → chunk-7VO5IEJ2.js} +2 -2
  34. package/dist/cli/chunks/{chunk-YXH2CVAF.js → chunk-AIBE3J4A.js} +1 -1
  35. package/dist/cli/chunks/{chunk-BWP3UVPE.js → chunk-AMW27FSS.js} +3 -3
  36. package/dist/cli/chunks/{chunk-3JAOFKEU.js → chunk-AZJYDM2K.js} +1 -1
  37. package/dist/cli/chunks/{chunk-MBSJ5G4I.js → chunk-B6CT4ILU.js} +4 -4
  38. package/dist/cli/chunks/{chunk-FJGSEPFL.js → chunk-BEFRQOLH.js} +2 -2
  39. package/dist/cli/chunks/{chunk-UIJFU4KD.js → chunk-C2446H7G.js} +2 -2
  40. package/dist/cli/chunks/{chunk-YIYV2JB6.js → chunk-D7IWGQTW.js} +2 -2
  41. package/dist/cli/chunks/{chunk-JLL27IGU.js → chunk-D7PI4CYZ.js} +2 -2
  42. package/dist/cli/chunks/{chunk-I42R57ON.js → chunk-DAIM72HV.js} +2 -2
  43. package/dist/cli/chunks/{chunk-YYAPO3CU.js → chunk-DPKECIKN.js} +2 -2
  44. package/dist/cli/chunks/{chunk-E2BJT6A7.js → chunk-E6CGBOZY.js} +2 -2
  45. package/dist/cli/chunks/{chunk-MC7K44M4.js → chunk-EGTOSQZK.js} +2 -2
  46. package/dist/cli/chunks/{chunk-NRCL3WCP.js → chunk-EMZ3DXMG.js} +2 -2
  47. package/dist/cli/chunks/{chunk-NNZMEYLT.js → chunk-EWI37TJA.js} +1 -1
  48. package/dist/cli/chunks/{chunk-NNVXHC74.js → chunk-F34OO2Q7.js} +3 -3
  49. package/dist/cli/chunks/{chunk-U7NMPZE2.js → chunk-F6QPAVWS.js} +2 -2
  50. package/dist/cli/chunks/chunk-F77X5DAF.js +2 -0
  51. package/dist/cli/chunks/{chunk-6GCOIIHY.js → chunk-FDFJJFQT.js} +2 -2
  52. package/dist/cli/chunks/{chunk-OPDTDKN3.js → chunk-FQ7I4JBQ.js} +2 -2
  53. package/dist/cli/chunks/{chunk-RNF47IJ5.js → chunk-G5FPWH5O.js} +2 -2
  54. package/dist/cli/chunks/{chunk-IRR7YA3Q.js → chunk-GDMH7NPV.js} +2 -2
  55. package/dist/cli/chunks/{chunk-6FL3GN4T.js → chunk-GILL32E2.js} +2 -2
  56. package/dist/cli/chunks/{chunk-JE3C7JYN.js → chunk-GLMDRGJD.js} +1 -1
  57. package/dist/cli/chunks/{chunk-JTF6D2RJ.js → chunk-GS33ZRJH.js} +2 -2
  58. package/dist/cli/chunks/chunk-HPYGMKZF.js +2 -0
  59. package/dist/cli/chunks/{chunk-6Q2PPOOF.js → chunk-HTLAPMTK.js} +1 -1
  60. package/dist/cli/chunks/{chunk-RZCAA2PZ.js → chunk-IAK76TIZ.js} +1 -1
  61. package/dist/cli/chunks/{chunk-LZ6TNTGO.js → chunk-ICF5RPQU.js} +2 -2
  62. package/dist/cli/chunks/{chunk-BO2OV2RH.js → chunk-IPAQ4HVX.js} +2 -2
  63. package/dist/cli/chunks/{chunk-FND6V2RV.js → chunk-ISRTT4I7.js} +8 -8
  64. package/dist/cli/chunks/{chunk-KTRB3L53.js → chunk-IYFMDIYZ.js} +2 -2
  65. package/dist/cli/chunks/{chunk-T63EK6GH.js → chunk-JRBGHWAM.js} +2 -2
  66. package/dist/cli/chunks/{chunk-GL3HZN3O.js → chunk-JYR3X4OC.js} +1 -1
  67. package/dist/cli/chunks/{chunk-R5ONQAQL.js → chunk-K72J52JO.js} +2 -2
  68. package/dist/cli/chunks/{chunk-FU77CDEM.js → chunk-K7CW2X6U.js} +2 -2
  69. package/dist/cli/chunks/{chunk-3X2ZQ55B.js → chunk-K7K4TFJM.js} +3 -3
  70. package/dist/cli/chunks/{chunk-2ULVCLOW.js → chunk-KCXE2LZU.js} +2 -2
  71. package/dist/cli/chunks/{chunk-UDV4YB42.js → chunk-KGPAWNNR.js} +1 -1
  72. package/dist/cli/chunks/{chunk-CTDO2UB2.js → chunk-KJ56OXH4.js} +1 -1
  73. package/dist/cli/chunks/{chunk-DF3MJ2YL.js → chunk-KUFC4DBX.js} +1 -1
  74. package/dist/cli/chunks/{chunk-UHDBM7QS.js → chunk-KWZEBHAP.js} +2 -2
  75. package/dist/cli/chunks/{chunk-WWD5IWTV.js → chunk-L6VNEEN6.js} +1 -1
  76. package/dist/cli/chunks/{chunk-7SEHQTYD.js → chunk-LHPR7ROV.js} +1 -1
  77. package/dist/cli/chunks/{chunk-YDKYLNKZ.js → chunk-LKK3NIHC.js} +1 -1
  78. package/dist/cli/chunks/{chunk-YDDZJCKY.js → chunk-LOFA3U4X.js} +1 -1
  79. package/dist/cli/chunks/{chunk-HAO3SPOE.js → chunk-LYKSIOOT.js} +2 -2
  80. package/dist/cli/chunks/chunk-M2PSXKTG.js +2 -0
  81. package/dist/cli/chunks/{chunk-UZL366ZI.js → chunk-M3MKP5VN.js} +1 -1
  82. package/dist/cli/chunks/{chunk-7YYTTWGY.js → chunk-M4ARHDY4.js} +1 -1
  83. package/dist/cli/chunks/{chunk-IL2KOW5W.js → chunk-M5DBKHM4.js} +2 -2
  84. package/dist/cli/chunks/{chunk-SL6YZAT4.js → chunk-MDWJXSBA.js} +2 -2
  85. package/dist/cli/chunks/{chunk-HMFEPKAR.js → chunk-MFWWPRBV.js} +2 -2
  86. package/dist/cli/chunks/{chunk-N7IBYDW5.js → chunk-MHWYQHGN.js} +1 -1
  87. package/dist/cli/chunks/{chunk-Q7EBD24B.js → chunk-MIQBRVK2.js} +1 -1
  88. package/dist/cli/chunks/{chunk-ERYMAYJW.js → chunk-MKZQBBCU.js} +2 -2
  89. package/dist/cli/chunks/{chunk-NEYYLAYS.js → chunk-MQ5WMWUK.js} +2 -2
  90. package/dist/cli/chunks/chunk-MQIAN57O.js +2 -0
  91. package/dist/cli/chunks/{chunk-6B4S7PKP.js → chunk-MU4P4P4E.js} +1 -1
  92. package/dist/cli/chunks/{chunk-B5MMDMH6.js → chunk-MWV4KPOB.js} +2 -2
  93. package/dist/cli/chunks/{chunk-SWOG3PBD.js → chunk-N244P4MM.js} +2 -2
  94. package/dist/cli/chunks/{chunk-7ZSPCGTI.js → chunk-N3MM4Z33.js} +2 -2
  95. package/dist/cli/chunks/{chunk-VDTFRMES.js → chunk-N4CXUGXE.js} +2 -2
  96. package/dist/cli/chunks/{chunk-C6BBRM2J.js → chunk-ND6YSW5N.js} +1 -1
  97. package/dist/cli/chunks/{chunk-5IBJURYB.js → chunk-NJYI7HX7.js} +2 -2
  98. package/dist/cli/chunks/{chunk-4CYLSXA6.js → chunk-NSRDP7RD.js} +2 -2
  99. package/dist/cli/chunks/{chunk-USFZ4IJD.js → chunk-NZGLDOU4.js} +15 -15
  100. package/dist/cli/chunks/{chunk-HM523MTQ.js → chunk-O3SG32PS.js} +1 -1
  101. package/dist/cli/chunks/{chunk-NXPFGPHV.js → chunk-OIFJH7TF.js} +1 -1
  102. package/dist/cli/chunks/{chunk-5EWWA4QP.js → chunk-OKKTDHHF.js} +6 -6
  103. package/dist/cli/chunks/{chunk-5SGEOO2F.js → chunk-OO7KJ34Y.js} +2 -2
  104. package/dist/cli/chunks/{chunk-Z2K5IZM6.js → chunk-OV4BLIKJ.js} +2 -2
  105. package/dist/cli/chunks/{chunk-RTDHWOAG.js → chunk-PISW5HUX.js} +1 -1
  106. package/dist/cli/chunks/{chunk-5ER3COX3.js → chunk-PLD4IGDL.js} +2 -2
  107. package/dist/cli/chunks/{chunk-D2FBUOAR.js → chunk-PMWWWYUM.js} +1 -1
  108. package/dist/cli/chunks/{chunk-OG7CWWFR.js → chunk-PWJZZCHJ.js} +1 -1
  109. package/dist/cli/chunks/{chunk-GELF4ILR.js → chunk-PZ4PRZXN.js} +9 -9
  110. package/dist/cli/chunks/chunk-PZCSJZVJ.js +2 -0
  111. package/dist/cli/chunks/{chunk-ZXQNE4QV.js → chunk-Q53M4LI7.js} +1 -1
  112. package/dist/cli/chunks/{chunk-WPVCSFDA.js → chunk-QPMAXDJ2.js} +2 -2
  113. package/dist/cli/chunks/{chunk-L74CHKFR.js → chunk-RJKYPWFD.js} +2 -2
  114. package/dist/cli/chunks/{chunk-4OUAHZX2.js → chunk-RUC3FCRK.js} +2 -2
  115. package/dist/cli/chunks/{chunk-HRLXU4LH.js → chunk-SC6UFGJ6.js} +2 -2
  116. package/dist/cli/chunks/{chunk-AEJVOJPT.js → chunk-SJC7OKF3.js} +2 -2
  117. package/dist/cli/chunks/{chunk-X3RJ6SFC.js → chunk-STMMZXS6.js} +1 -1
  118. package/dist/cli/chunks/{chunk-CAMEFWRK.js → chunk-SVILIQQQ.js} +1 -1
  119. package/dist/cli/chunks/{chunk-ADV4DH3W.js → chunk-SXMGNMFL.js} +3 -3
  120. package/dist/cli/chunks/{chunk-ZG4P3DTL.js → chunk-SZKFT6CD.js} +2 -2
  121. package/dist/cli/chunks/{chunk-4QFAUSWQ.js → chunk-TBJ566KV.js} +2 -2
  122. package/dist/cli/chunks/{chunk-7RMZAVGO.js → chunk-TCV5DASI.js} +2 -2
  123. package/dist/cli/chunks/{chunk-U6UK3UMX.js → chunk-TWAWEP4X.js} +3 -3
  124. package/dist/cli/chunks/chunk-U27GVYXA.js +2 -0
  125. package/dist/cli/chunks/{chunk-JD2PG4KS.js → chunk-UFKVKNAA.js} +1 -1
  126. package/dist/cli/chunks/{chunk-FLTPHVZ3.js → chunk-USB7GCIC.js} +1 -1
  127. package/dist/cli/chunks/{chunk-HQJMCTWN.js → chunk-UW3ZSFFB.js} +2 -2
  128. package/dist/cli/chunks/{chunk-JTZ3Q2QS.js → chunk-UWAUYDW4.js} +2 -2
  129. package/dist/cli/chunks/{chunk-QEODION5.js → chunk-UXJVR323.js} +2 -2
  130. package/dist/cli/chunks/{chunk-QM65UGPV.js → chunk-V5G3SMAJ.js} +2 -2
  131. package/dist/cli/chunks/{chunk-PL5SLO2W.js → chunk-VDKMBOUK.js} +1 -1
  132. package/dist/cli/chunks/{chunk-HWM2XJ3P.js → chunk-VJ2D6FST.js} +2 -2
  133. package/dist/cli/chunks/{chunk-5LON3MLI.js → chunk-VJOPNK2L.js} +2 -2
  134. package/dist/cli/chunks/{chunk-2L73WXA4.js → chunk-VRE2EBFI.js} +2 -2
  135. package/dist/cli/chunks/{chunk-3RZL4QTT.js → chunk-WI5WXYIS.js} +2 -2
  136. package/dist/cli/chunks/{chunk-XTP2GHI7.js → chunk-WIYWDON4.js} +2 -2
  137. package/dist/cli/chunks/{chunk-SNTMAVPH.js → chunk-WYMQ6FZR.js} +3 -3
  138. package/dist/cli/chunks/{chunk-BT3QLWII.js → chunk-XBFEHVBO.js} +2 -2
  139. package/dist/cli/chunks/{chunk-DY5KEOHX.js → chunk-XDZXLEJK.js} +1 -1
  140. package/dist/cli/chunks/{chunk-PFCAMX6H.js → chunk-XJXCSCCP.js} +1 -1
  141. package/dist/cli/chunks/{chunk-JXIPRMAY.js → chunk-XVA56PXZ.js} +4 -4
  142. package/dist/cli/chunks/{chunk-6ZK24V2Y.js → chunk-Y2EDDV5U.js} +2 -2
  143. package/dist/cli/chunks/{chunk-5G5AAEFF.js → chunk-YSLE6NNG.js} +2 -2
  144. package/dist/cli/chunks/{chunk-PZHZPX3O.js → chunk-Z4BTPQLG.js} +2 -2
  145. package/dist/cli/chunks/{chunk-GJUGSH7T.js → chunk-ZM4QGYGK.js} +3 -3
  146. package/dist/cli/chunks/{ci-AWZ3S5OT.js → ci-2BLMQNX3.js} +2 -2
  147. package/dist/cli/chunks/{ci-output-JLCYTIMT.js → ci-output-XK4PPSN7.js} +2 -2
  148. package/dist/cli/chunks/{circuit-breaker-BJDKBDIL.js → circuit-breaker-W7X4NPFE.js} +2 -2
  149. package/dist/cli/chunks/{claude-flow-setup-KKOP5ZMO.js → claude-flow-setup-GLBLSYNJ.js} +2 -2
  150. package/dist/cli/chunks/client-C6CJOCRN.js +2 -0
  151. package/dist/cli/chunks/{cline-installer-7M525SEA.js → cline-installer-7WX7DBGI.js} +2 -2
  152. package/dist/cli/chunks/{code-27SUVJDO.js → code-SP3HAQWG.js} +2 -2
  153. package/dist/cli/chunks/{code-index-extractor-TTQQZLAK.js → code-index-extractor-44HH36UG.js} +2 -2
  154. package/dist/cli/chunks/{codex-installer-GHNGNPKP.js → codex-installer-LMXRWLPU.js} +2 -2
  155. package/dist/cli/chunks/{completions-JPJD24DG.js → completions-GL5FTZAN.js} +2 -2
  156. package/dist/cli/chunks/{complexity-analyzer-Q74EJV33.js → complexity-analyzer-CQMYGETL.js} +2 -2
  157. package/dist/cli/chunks/{continuedev-installer-ULTRDIML.js → continuedev-installer-CYVYS5B7.js} +2 -2
  158. package/dist/cli/chunks/{copilot-installer-EK52X4CG.js → copilot-installer-M7XVII2A.js} +2 -2
  159. package/dist/cli/chunks/{cost-tracker-2GKBRYXL.js → cost-tracker-S4ET4FH3.js} +2 -2
  160. package/dist/cli/chunks/{coverage-YCLC3W2A.js → coverage-DFVSSQ4A.js} +3 -3
  161. package/dist/cli/chunks/cross-domain-router-I3GEA5G6.js +2 -0
  162. package/dist/cli/chunks/{cursor-installer-B3ALFW5E.js → cursor-installer-KWDSQPQC.js} +2 -2
  163. package/dist/cli/chunks/{daemon-ZKEBVLJA.js → daemon-2HD54QVO.js} +3 -3
  164. package/dist/cli/chunks/daemon-CRX46BBO.js +10 -0
  165. package/dist/cli/chunks/{dag-attention-scheduler-OQPJ6ULA.js → dag-attention-scheduler-SCP6WPZB.js} +2 -2
  166. package/dist/cli/chunks/{detect-YMYIQH3Q.js → detect-XS2GDCEX.js} +2 -2
  167. package/dist/cli/chunks/{dist-node-R4FAYQRY.js → dist-node-U43MVQ3F.js} +2 -2
  168. package/dist/cli/chunks/{domain-handler-IGWXLF2S.js → domain-handler-HITMDULH.js} +2 -2
  169. package/dist/cli/chunks/{domain-transfer-A7YNO76C.js → domain-transfer-TJF7DNI4.js} +2 -2
  170. package/dist/cli/chunks/dream-JCQMG2RL.js +2 -0
  171. package/dist/cli/chunks/{embed-and-insert-pattern-KODZAS7Y.js → embed-and-insert-pattern-JKG33YZK.js} +2 -2
  172. package/dist/cli/chunks/{eval-ALQW7Q2S.js → eval-NF5Y4W37.js} +2 -2
  173. package/dist/cli/chunks/{experience-capture-middleware-3WK4RXWK.js → experience-capture-middleware-VMMFYJ4D.js} +3 -3
  174. package/dist/cli/chunks/{fast-paths-PQWDFIJZ.js → fast-paths-W2Q53IR2.js} +2 -2
  175. package/dist/cli/chunks/{feature-flags-JRUAZCND.js → feature-flags-B4PBMQJO.js} +2 -2
  176. package/dist/cli/chunks/{feature-flags-6X33B3WX.js → feature-flags-PVI7A4RE.js} +2 -2
  177. package/dist/cli/chunks/{file-discovery-SA3YU3IH.js → file-discovery-E4L3I33I.js} +2 -2
  178. package/dist/cli/chunks/{fleet-7TXCAOKQ.js → fleet-LE5SHVLK.js} +3 -3
  179. package/dist/cli/chunks/{gnn-wrapper-ZKNYACEC.js → gnn-wrapper-MWWJBLOH.js} +2 -2
  180. package/dist/cli/chunks/{heartbeat-handler-KRZRZ23F.js → heartbeat-handler-XOUVNPQK.js} +4 -4
  181. package/dist/cli/chunks/heartbeat-scheduler-FBHE4ZWH.js +2 -0
  182. package/dist/cli/chunks/hnsw-adapter-EOOA4WXD.js +2 -0
  183. package/dist/cli/chunks/hnsw-index-TD3KRPND.js +2 -0
  184. package/dist/cli/chunks/{hnsw-legacy-bridge-LVHQ5SG7.js → hnsw-legacy-bridge-W3T5ZDDP.js} +2 -2
  185. package/dist/cli/chunks/{better-sqlite3-HP4JZS6K.js → hnswlib-node-3TZFES5I.js} +2 -2
  186. package/dist/cli/chunks/hooks-RUPQVIUM.js +250 -0
  187. package/dist/cli/chunks/hybrid-router-64O6PXZ2.js +2 -0
  188. package/dist/cli/chunks/{hypergraph-engine-2EZBZMFK.js → hypergraph-engine-VDFK3JYH.js} +2 -2
  189. package/dist/cli/chunks/{hypergraph-handler-GLPWYII2.js → hypergraph-handler-EUDGEF25.js} +3 -3
  190. package/dist/cli/chunks/impact-analyzer-ITQHXGTM.js +2 -0
  191. package/dist/cli/chunks/{init-handler-ZSDO5VMA.js → init-handler-MZEAJOZK.js} +6 -6
  192. package/dist/cli/chunks/init-wizard-DZ4IKGQI.js +2 -0
  193. package/dist/cli/chunks/kernel-HSVY4ZYK.js +2 -0
  194. package/dist/cli/chunks/{kilocode-installer-ATYSDWIV.js → kilocode-installer-ECBYWT6M.js} +2 -2
  195. package/dist/cli/chunks/{kiro-installer-K66YT6PC.js → kiro-installer-KYFCSYTG.js} +2 -2
  196. package/dist/cli/chunks/knowledge-graph-H32TXXX4.js +2 -0
  197. package/dist/cli/chunks/{learning-BVYCC4RI.js → learning-4RAFMDSB.js} +3 -3
  198. package/dist/cli/chunks/{llm-router-VBCXE6DN.js → llm-router-JHBNLYP3.js} +4 -4
  199. package/dist/cli/chunks/llm-router-service-3FKESBUX.js +2 -0
  200. package/dist/cli/chunks/{load-AREDQE2U.js → load-4DVQML7P.js} +2 -2
  201. package/dist/cli/chunks/load-test-LKHURZGZ.js +2 -0
  202. package/dist/cli/chunks/{mcp-NG6H6UC5.js → mcp-LCWMU4GZ.js} +2 -2
  203. package/dist/cli/chunks/{memory-Y65EHG6N.js → memory-3DTJAURT.js} +5 -5
  204. package/dist/cli/chunks/memory-backend-XRJRZ6CK.js +2 -0
  205. package/dist/cli/chunks/memory-handlers-BL6E3XAK.js +2 -0
  206. package/dist/cli/chunks/{multi-model-executor-VRPRFUZT.js → multi-model-executor-AVR5SZOO.js} +2 -2
  207. package/dist/cli/chunks/{opencode-installer-CKQXPM5R.js → opencode-installer-DW2426QM.js} +2 -2
  208. package/dist/cli/chunks/{orchestrator-I7JBKD6G.js → orchestrator-AHF4W5GS.js} +5 -5
  209. package/dist/cli/chunks/{pipeline-MV2RWCBI.js → pipeline-N6THEWYE.js} +2 -2
  210. package/dist/cli/chunks/{platform-VU5P3SOG.js → platform-MRCFQF7X.js} +2 -2
  211. package/dist/cli/chunks/{plugin-6TERLKCB.js → plugin-6YKUN5QM.js} +2 -2
  212. package/dist/cli/chunks/{prime-radiant-advanced-wasm-WIUIN2DL.js → prime-radiant-advanced-wasm-2YPAHSVS.js} +2 -2
  213. package/dist/cli/chunks/protocol-executor-KABPB6PQ.js +2 -0
  214. package/dist/cli/chunks/{protocol-handler-HKWBGARO.js → protocol-handler-Y2NMUKWQ.js} +2 -2
  215. package/dist/cli/chunks/{prove-7CQPHBRJ.js → prove-DZUNWBFD.js} +2 -2
  216. package/dist/cli/chunks/provider-manager-U7EBM3FA.js +2 -0
  217. package/dist/cli/chunks/qe-reasoning-bank-64O2OQIW.js +2 -0
  218. package/dist/cli/chunks/{quality-VLUVXKVG.js → quality-AIFQMGUV.js} +2 -2
  219. package/dist/cli/chunks/queen-coordinator-SV3COGIL.js +2 -0
  220. package/dist/cli/chunks/{real-embeddings-JPZ64KK2.js → real-embeddings-5XL4LOG2.js} +2 -2
  221. package/dist/cli/chunks/{roocode-installer-NONVB3UE.js → roocode-installer-LV3WONT5.js} +2 -2
  222. package/dist/cli/chunks/router-QARRPMED.js +2 -0
  223. package/dist/cli/chunks/routing-feedback-KD2JFTPK.js +2 -0
  224. package/dist/cli/chunks/{routing-handler-YYXDT4J2.js → routing-handler-WSMUILGD.js} +2 -2
  225. package/dist/cli/chunks/{ruvector-commands-5PFMNDLR.js → ruvector-commands-BCEIDTW3.js} +2 -2
  226. package/dist/cli/chunks/{rvf-dual-writer-TF6H7AXH.js → rvf-dual-writer-LRSPC6H3.js} +2 -2
  227. package/dist/cli/chunks/{rvf-migration-adapter-VNGIUZCO.js → rvf-migration-adapter-QHNX6353.js} +2 -2
  228. package/dist/cli/chunks/{rvf-migration-coordinator-VA52YAIY.js → rvf-migration-coordinator-SLNB3XPW.js} +2 -2
  229. package/dist/cli/chunks/rvf-native-adapter-4LLGF5AY.js +2 -0
  230. package/dist/cli/chunks/safe-db-RAX3H2P7.js +2 -0
  231. package/dist/cli/chunks/schedule-RQZGLLUY.js +2 -0
  232. package/dist/cli/chunks/scheduler-ACWTN4LN.js +2 -0
  233. package/dist/cli/chunks/{security-62HEETBF.js → security-CYY6TECQ.js} +3 -3
  234. package/dist/cli/chunks/shared-rvf-adapter-U6JE4O6A.js +2 -0
  235. package/dist/cli/chunks/{shared-rvf-dual-writer-JTZK7LRD.js → shared-rvf-dual-writer-PJBSNBRV.js} +2 -2
  236. package/dist/cli/chunks/sqlite-persistence-SWNBO257.js +2 -0
  237. package/dist/cli/chunks/{status-handler-LSUPUKRF.js → status-handler-W723LXX5.js} +2 -2
  238. package/dist/cli/chunks/{structural-health-Z75A666N.js → structural-health-WZUPZBB5.js} +2 -2
  239. package/dist/cli/chunks/{sync-M3O4T3A3.js → sync-UA22CKUS.js} +2 -2
  240. package/dist/cli/chunks/sync-ZLMF53TB.js +2 -0
  241. package/dist/cli/chunks/{task-handler-AQBSZAQC.js → task-handler-SENTEEXZ.js} +2 -2
  242. package/dist/cli/chunks/{task-handlers-BOZP247V.js → task-handlers-FGVUZOCC.js} +3 -3
  243. package/dist/cli/chunks/{test-FTEGPNN2.js → test-Q37C3WI2.js} +4 -4
  244. package/dist/cli/chunks/{test-scheduling-IGR4U2VQ.js → test-scheduling-E6SPIBTH.js} +3 -3
  245. package/dist/cli/chunks/token-bootstrap-HQFFMZUF.js +2 -0
  246. package/dist/cli/chunks/{token-usage-VCHV47EO.js → token-usage-JHNWTZ7L.js} +2 -2
  247. package/dist/cli/chunks/{transformers-M27QSNFH.js → transformers-TEXDUVNI.js} +2 -2
  248. package/dist/cli/chunks/{tree-sitter-wasm-parser-IIGEJYFU.js → tree-sitter-wasm-parser-MWSS52H6.js} +2 -2
  249. package/dist/cli/chunks/{types-RQFPUUKA.js → types-YQRKHYH3.js} +2 -2
  250. package/dist/cli/chunks/unified-memory-QG3FDRKR.js +2 -0
  251. package/dist/cli/chunks/unified-memory-hnsw-KOR4EOIG.js +2 -0
  252. package/dist/cli/chunks/unified-persistence-J6NIRYKM.js +2 -0
  253. package/dist/cli/chunks/{upgrade-VJMYX3AL.js → upgrade-JKMEDURI.js} +2 -2
  254. package/dist/cli/chunks/{validate-ML7HUAU5.js → validate-URO7G6OE.js} +2 -2
  255. package/dist/cli/chunks/{validate-swarm-RCR6EYRC.js → validate-swarm-VZVJ56Z5.js} +2 -2
  256. package/dist/cli/chunks/{vibium-ZOOS3W5L.js → vibium-G5WZILL6.js} +2 -2
  257. package/dist/cli/chunks/visual-security-RAWV6YLN.js +2 -0
  258. package/dist/cli/chunks/{web-tree-sitter-2YPGYLWK.js → web-tree-sitter-LECH5T6H.js} +2 -2
  259. package/dist/cli/chunks/{windsurf-installer-GOJWUWC5.js → windsurf-installer-2NPLC2YW.js} +2 -2
  260. package/dist/cli/chunks/{witness-chain-3MGSS3Q4.js → witness-chain-X347C36A.js} +2 -2
  261. package/dist/cli/chunks/witness-chain-ZO7FIM35.js +2 -0
  262. package/dist/cli/chunks/{workflow-B5Q77BI4.js → workflow-V4ALYZ73.js} +4 -4
  263. package/dist/cli/chunks/workflow-orchestrator-7SKITNIJ.js +2 -0
  264. package/dist/cli/chunks/wrappers-QXOPRPR4.js +2 -0
  265. package/dist/cli/commands/hooks-handlers/task-hooks.js +50 -0
  266. package/dist/integrations/ruvector/shared-rvf-adapter.js +12 -1
  267. package/dist/integrations/ruvector/shared-rvf-dual-writer.js +6 -2
  268. package/dist/kernel/project-root.d.ts +33 -0
  269. package/dist/kernel/project-root.js +86 -0
  270. package/dist/kernel/unified-memory.d.ts +2 -19
  271. package/dist/kernel/unified-memory.js +8 -64
  272. package/dist/learning/local-judge-client.d.ts +55 -0
  273. package/dist/learning/local-judge-client.js +127 -0
  274. package/dist/learning/nagual-client.d.ts +73 -0
  275. package/dist/learning/nagual-client.js +150 -0
  276. package/dist/learning/pattern-store.js +10 -3
  277. package/dist/mcp/bundle.js +392 -390
  278. package/dist/mcp/entry.js +44 -33
  279. package/dist/mcp/transport/stdio.d.ts +7 -0
  280. package/dist/mcp/transport/stdio.js +39 -2
  281. package/dist/workers/daemon.js +2 -0
  282. package/dist/workers/quality-daemon/git-watcher.js +2 -0
  283. package/dist/workers/quality-daemon/index.js +2 -0
  284. package/dist/workers/worker-manager.js +4 -0
  285. package/package.json +1 -1
  286. package/dist/cli/chunks/adapter-BHPUKMJ5.js +0 -2
  287. package/dist/cli/chunks/aqe-learning-engine-JQ5WD2HM.js +0 -2
  288. package/dist/cli/chunks/audit-BMQ3VESB.js +0 -3
  289. package/dist/cli/chunks/base-E32WLGY2.js +0 -2
  290. package/dist/cli/chunks/browser-workflow-LNNXXAJG.js +0 -2
  291. package/dist/cli/chunks/chunk-2EQVYYBF.js +0 -2
  292. package/dist/cli/chunks/chunk-3VF3HCG4.js +0 -2
  293. package/dist/cli/chunks/chunk-JOLDCS6X.js +0 -2
  294. package/dist/cli/chunks/chunk-JSFYPLMQ.js +0 -2
  295. package/dist/cli/chunks/chunk-YX2HY4MX.js +0 -2
  296. package/dist/cli/chunks/client-2UKBYFX4.js +0 -2
  297. package/dist/cli/chunks/cross-domain-router-FPM3L27L.js +0 -2
  298. package/dist/cli/chunks/daemon-YWINEHG4.js +0 -10
  299. package/dist/cli/chunks/dream-XM33US3V.js +0 -2
  300. package/dist/cli/chunks/heartbeat-scheduler-GM3M2MTG.js +0 -2
  301. package/dist/cli/chunks/hnsw-adapter-K62GEHIL.js +0 -2
  302. package/dist/cli/chunks/hnsw-index-VCAK3TWN.js +0 -2
  303. package/dist/cli/chunks/hooks-6Y3UHYI2.js +0 -248
  304. package/dist/cli/chunks/hybrid-router-432QNCNG.js +0 -2
  305. package/dist/cli/chunks/impact-analyzer-VTSISNN4.js +0 -2
  306. package/dist/cli/chunks/init-wizard-COB5AH7Q.js +0 -2
  307. package/dist/cli/chunks/kernel-ROK7X5FM.js +0 -2
  308. package/dist/cli/chunks/knowledge-graph-YUWIDIWW.js +0 -2
  309. package/dist/cli/chunks/llm-router-service-7VLXJ7VE.js +0 -2
  310. package/dist/cli/chunks/load-test-32524DL3.js +0 -2
  311. package/dist/cli/chunks/memory-backend-BI2V5AAB.js +0 -2
  312. package/dist/cli/chunks/memory-handlers-NSOFWVFN.js +0 -2
  313. package/dist/cli/chunks/protocol-executor-2UPB7SPI.js +0 -2
  314. package/dist/cli/chunks/provider-manager-PDT37MIJ.js +0 -2
  315. package/dist/cli/chunks/qe-reasoning-bank-AQQ2BI4V.js +0 -2
  316. package/dist/cli/chunks/queen-coordinator-6DVDVEU4.js +0 -2
  317. package/dist/cli/chunks/router-O2G4KQ6L.js +0 -2
  318. package/dist/cli/chunks/routing-feedback-TAGTD3KQ.js +0 -2
  319. package/dist/cli/chunks/rvf-native-adapter-46GRWQJR.js +0 -2
  320. package/dist/cli/chunks/safe-db-LNIPXXHH.js +0 -2
  321. package/dist/cli/chunks/schedule-AUH3ZALY.js +0 -2
  322. package/dist/cli/chunks/scheduler-KK3OYPWW.js +0 -2
  323. package/dist/cli/chunks/shared-rvf-adapter-XWTQPGCT.js +0 -2
  324. package/dist/cli/chunks/sqlite-persistence-CYESP7NG.js +0 -2
  325. package/dist/cli/chunks/sync-VI37UHHH.js +0 -2
  326. package/dist/cli/chunks/token-bootstrap-2DFRVMBM.js +0 -2
  327. package/dist/cli/chunks/unified-memory-RISHEANP.js +0 -2
  328. package/dist/cli/chunks/unified-memory-hnsw-2IKXGMNZ.js +0 -2
  329. package/dist/cli/chunks/unified-persistence-ZTTUJNTU.js +0 -2
  330. package/dist/cli/chunks/visual-security-D66DTAO5.js +0 -2
  331. package/dist/cli/chunks/witness-chain-RHWHHDLV.js +0 -2
  332. package/dist/cli/chunks/workflow-orchestrator-OQMFW2TC.js +0 -2
  333. package/dist/cli/chunks/wrappers-MM5VLEPG.js +0 -2
@@ -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.10.4");process.exit(0)}
2
+ var e=null,f=null,t=null,u=!1;async function S(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-4LLGF5AY.js");if(!d())return null;let{getUnifiedMemory:v,findProjectRoot:p}=await import("./unified-memory-QG3FDRKR.js"),o=v().getDatabase();if(!o)return null;let{join:g}=await import("node:path"),m=g(process.env.AQE_PROJECT_ROOT??p(),".agentic-qe","brain.rvf"),{RvfDualWriter:R}=await import("./rvf-dual-writer-LRSPC6H3.js"),l=new R(o,{rvfPath:m,mode:"dual-write",dimensions:384});await l.initialize(),e=l;try{let{getRvfMigrationStage:y}=await import("./feature-flags-PVI7A4RE.js"),n=y();if(n>=2){let{RvfMigrationAdapter:h}=await import("./rvf-migration-adapter-QHNX6353.js"),s=new h({stage:n});s.setSqliteDb(o);let{getSharedRvfAdapter:A}=await import("./shared-rvf-adapter-U6JE4O6A.js"),i=A();if(i){let D={ingest:a=>i.ingest(a),search:(a,w)=>i.search(a,w).map(c=>({id:c.id,score:c.score})),delete:a=>i.delete(a),status:()=>i.status(),close:()=>{}};s.setRvfStore(D)}f=s,console.log(`[RVF] Migration adapter active at stage ${n} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][n]})`)}}catch{}return l}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-KKEBUHZC.js").then(({registerRvfResetFn:r})=>r(M)).catch(()=>{})}})(),t)}function b(){return e}function E(){return f}function M(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{S as a,b,E as c,M as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.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.10.4");process.exit(0)}
2
2
  var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};
@@ -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.10.3");process.exit(0)}
2
- import{a as v,b as k}from"./chunk-ERYMAYJW.js";import{k as g,o as P}from"./chunk-USFZ4IJD.js";import{a as d,b as y,c as R}from"./chunk-3LRK7PYN.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.10.4");process.exit(0)}
2
+ import{a as v,b as k}from"./chunk-MKZQBBCU.js";import{i as g,m as P}from"./chunk-NZGLDOU4.js";import{a as d,b as y,c as R}from"./chunk-2B6ETC7C.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,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.10.3");process.exit(0)}
2
- import{a as t,q as r}from"./chunk-VRXY4T22.js";import{c as l}from"./chunk-CAMEFWRK.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.10.4");process.exit(0)}
2
+ import{a as t,q as r}from"./chunk-2G2PVVQG.js";import{c as l}from"./chunk-SVILIQQQ.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,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.10.3");process.exit(0)}
2
- import{d as m}from"./chunk-7ZSPCGTI.js";import{d as T}from"./chunk-3RZL4QTT.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{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.10.4");process.exit(0)}
2
+ import{d as m}from"./chunk-N3MM4Z33.js";import{d as T}from"./chunk-WI5WXYIS.js";T();function p(t,r,o){let e=0,n=t.length;for(;e<n;){let i=e+n>>>1;o(t[i],r)<=0?e=i+1:n=i}return e}function a(t,r,o){let e=p(t,r,o);return t.splice(e,0,r),e}function s(){return(t,r)=>t.createdAt.getTime()-r.createdAt.getTime()}m();export{a,s 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.10.3");process.exit(0)}
2
- import{b as y,d as p}from"./chunk-PL5SLO2W.js";import{i as h}from"./chunk-RTDHWOAG.js";var f={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var g=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},r,i){this.graph=e,this.config={...f,...t},this.calculator=p(),this.eventBus=r,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),r=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,r),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(n=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",n)),this.emitEvent("mincut.updated",e,{status:r,weakVertexCount:t.length}),{status:r,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let r={critical:0,high:1,medium:2,low:3,info:4};return r[e.severity]-r[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,r]of this.alerts)r.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,r=this.history.filter(n=>n.timestamp.getTime()>t);if(r.length===0){let n=this.calculator.getMinCutValue(this.graph);return{min:n,max:n,average:n,count:0}}let i=r.map(n=>n.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((n,a)=>n+a,0)/i.length,count:r.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,r){if(!this.config.alertsEnabled)return;let i=Date.now();r==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):r==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let n=t.filter(o=>o.weightedDegree===0);n.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${n.length} isolated vertex(es) detected`,e,0,n);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,r,i,n,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let s={id:h(),severity:t,message:r,minCutValue:i,threshold:n,affectedVertices:a.map(l=>l.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(l=>l.suggestions).slice(0,5)};this.alerts.set(s.id,s),this.persistence&&this.persistence.saveAlert(s).catch(l=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",l)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:s})}emitEvent(e,t,r){if(!this.eventBus)return;let i={id:h(),type:e,source:"coordination",timestamp:new Date,correlationId:h(),payload:{minCutValue:t,...r}};this.eventBus.publish(i).catch(n=>{console.error("Failed to publish MinCut event:",n)})}};function v(m,e,t,r){return new g(m,e,t,r)}var d=null,u=null;function C(){return d||(d=y()),d}function P(){return u||(u=v(C())),u}function B(){return d!==null}function F(){return u!==null}export{f as a,v as b,C as c,P as d,B as e,F as f};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.4");process.exit(0)}
2
+ import{b as y,d as p}from"./chunk-VDKMBOUK.js";import{i as h}from"./chunk-PISW5HUX.js";var f={healthyThreshold:3,warningThreshold:2,checkIntervalMs:5e3,maxHistoryEntries:100,alertsEnabled:!0,alertCooldownMs:6e4,selfHealingEnabled:!1,maxHealingActionsPerMinute:5};var g=class{calculator;config;eventBus;persistence;graph;history=[];alerts=new Map;lastAlertTime=new Map;monitoringInterval=null;isMonitoring=!1;constructor(e,t={},r,i){this.graph=e,this.config={...f,...t},this.calculator=p(),this.eventBus=r,this.persistence=i}start(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>this.checkHealth(),this.config.checkIntervalMs),this.checkHealth())}stop(){this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.isMonitoring=!1}updateGraph(e){this.graph=e,this.isMonitoring&&this.checkHealth()}isEmptyTopology(){return this.graph.getVerticesByType("agent").length===0}checkHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph),r=this.isEmptyTopology()?"idle":this.determineStatus(e),i=this.calculateTrend();return this.recordHistory(e),this.isEmptyTopology()||this.checkAlertConditions(e,t,r),this.persistence&&t.length>0&&this.persistence.saveWeakVertices(t).catch(n=>console.warn("[MinCutHealthMonitor] Failed to persist weak vertices:",n)),this.emitEvent("mincut.updated",e,{status:r,weakVertexCount:t.length}),{status:r,minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:i,history:this.history.slice(-20),lastUpdated:new Date}}getHealth(){let e=this.calculator.getMinCutValue(this.graph),t=this.calculator.findWeakVertices(this.graph);return{status:this.isEmptyTopology()?"idle":this.determineStatus(e),minCutValue:e,healthyThreshold:this.config.healthyThreshold,warningThreshold:this.config.warningThreshold,weakVertexCount:t.length,topWeakVertices:t.slice(0,5),trend:this.calculateTrend(),history:this.history.slice(-20),lastUpdated:new Date}}getMinCutValue(){return this.calculator.getMinCutValue(this.graph)}getWeakVertices(){return this.calculator.findWeakVertices(this.graph)}isCritical(){return this.calculator.getMinCutValue(this.graph)<this.config.warningThreshold}isHealthy(){return this.calculator.getMinCutValue(this.graph)>=this.config.healthyThreshold}getActiveAlerts(){return Array.from(this.alerts.values()).filter(e=>!e.acknowledged).sort((e,t)=>{let r={critical:0,high:1,medium:2,low:3,info:4};return r[e.severity]-r[t.severity]})}getAllAlerts(){return Array.from(this.alerts.values())}acknowledgeAlert(e){let t=this.alerts.get(e);return t?(t.acknowledged=!0,!0):!1}clearAcknowledgedAlerts(){let e=[];for(let[t,r]of this.alerts)r.acknowledged&&e.push(t);for(let t of e)this.alerts.delete(t);return e.length}getHistory(){return[...this.history]}getTrend(){return this.calculateTrend()}getStats(e=6e4){let t=Date.now()-e,r=this.history.filter(n=>n.timestamp.getTime()>t);if(r.length===0){let n=this.calculator.getMinCutValue(this.graph);return{min:n,max:n,average:n,count:0}}let i=r.map(n=>n.value);return{min:Math.min(...i),max:Math.max(...i),average:i.reduce((n,a)=>n+a,0)/i.length,count:r.length}}updateConfig(e){Object.assign(this.config,e),e.checkIntervalMs&&this.isMonitoring&&(this.stop(),this.start())}getConfig(){return{...this.config}}determineStatus(e){return e>=this.config.healthyThreshold?"healthy":e>=this.config.warningThreshold?"warning":"critical"}calculateTrend(){if(this.history.length<3)return"stable";let e=this.history.slice(-5),t=e[0].value,i=e[e.length-1].value-t,a=e.reduce((o,c)=>o+c.value,0)/e.length*.1;return i>a?"improving":i<-a?"degrading":"stable"}recordHistory(e){let t={timestamp:new Date,value:e,vertexCount:this.graph.vertexCount,edgeCount:this.graph.edgeCount};for(this.history.push(t);this.history.length>this.config.maxHistoryEntries;)this.history.shift()}checkAlertConditions(e,t,r){if(!this.config.alertsEnabled)return;let i=Date.now();r==="critical"?this.maybeGenerateAlert("critical-threshold","critical",`MinCut value (${e.toFixed(2)}) is below critical threshold (${this.config.warningThreshold})`,e,this.config.warningThreshold,t):r==="warning"&&this.maybeGenerateAlert("warning-threshold","high",`MinCut value (${e.toFixed(2)}) is below healthy threshold (${this.config.healthyThreshold})`,e,this.config.healthyThreshold,t);let n=t.filter(o=>o.weightedDegree===0);n.length>0&&this.maybeGenerateAlert("isolated-vertices","high",`${n.length} isolated vertex(es) detected`,e,0,n);let a=t.filter(o=>o.riskScore>.8);a.length>0&&this.maybeGenerateAlert("critical-vertices","medium",`${a.length} critical vertex(es) with high risk score`,e,0,a)}maybeGenerateAlert(e,t,r,i,n,a){let o=Date.now(),c=this.lastAlertTime.get(e)||0;if(o-c<this.config.alertCooldownMs)return;let s={id:h(),severity:t,message:r,minCutValue:i,threshold:n,affectedVertices:a.map(l=>l.vertexId),timestamp:new Date,acknowledged:!1,remediations:a.flatMap(l=>l.suggestions).slice(0,5)};this.alerts.set(s.id,s),this.persistence&&this.persistence.saveAlert(s).catch(l=>console.warn("[MinCutHealthMonitor] Failed to persist alert:",l)),this.lastAlertTime.set(e,o),this.emitEvent("mincut.alert.generated",i,{alert:s})}emitEvent(e,t,r){if(!this.eventBus)return;let i={id:h(),type:e,source:"coordination",timestamp:new Date,correlationId:h(),payload:{minCutValue:t,...r}};this.eventBus.publish(i).catch(n=>{console.error("Failed to publish MinCut event:",n)})}};function v(m,e,t,r){return new g(m,e,t,r)}var d=null,u=null;function C(){return d||(d=y()),d}function P(){return u||(u=v(C())),u}function B(){return d!==null}function F(){return u!==null}export{f as a,v as b,C as c,P as d,B as e,F as f};
@@ -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.10.3");process.exit(0)}
2
- import{b as f,d as v}from"./chunk-KTRB3L53.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.10.4");process.exit(0)}
2
+ import{b as f,d as v}from"./chunk-IYFMDIYZ.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 +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.10.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.10.4");process.exit(0)}
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.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.10.4");process.exit(0)}
2
2
  var h=Object.create;var e=Object.defineProperty;var i=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var k=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var m=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),n=a=>b=>{var c=a[b];if(c)return c();throw new Error("Module not found in bundle: "+b)};var o=(a,b)=>()=>(a&&(b=a(a=0)),b);var p=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports),q=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0})},g=(a,b,c,f)=>{if(b&&typeof b=="object"||typeof b=="function")for(let d of j(b))!l.call(a,d)&&d!==c&&e(a,d,{get:()=>b[d],enumerable:!(f=i(b,d))||f.enumerable});return a};var r=(a,b,c)=>(c=a!=null?h(k(a)):{},g(b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c,a)),s=a=>g(e({},"__esModule",{value:!0}),a);export{m as a,n as b,o as c,p as d,q as e,r as f,s as g};
@@ -1,12 +1,12 @@
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.10.3");process.exit(0)}
2
- import{a as v}from"./chunk-NXPFGPHV.js";import{a as h}from"./chunk-3VF3HCG4.js";import{c as E}from"./chunk-2L73WXA4.js";import{a as y,c as k}from"./chunk-3LRK7PYN.js";k();h();var l=E.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function Q(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-RISHEANP.js");o=c().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.10.4");process.exit(0)}
2
+ import{a as v}from"./chunk-OIFJH7TF.js";import{a as h}from"./chunk-HPYGMKZF.js";import{c as E}from"./chunk-VRE2EBFI.js";import{a as y,c as k}from"./chunk-2B6ETC7C.js";k();h();var l=E.create("qe-hooks"),u={PreTestGeneration:"qe:pre-test-generation",PostTestGeneration:"qe:post-test-generation",TestExecutionResult:"qe:test-execution-result",PreCoverageAnalysis:"qe:pre-coverage-analysis",PostCoverageAnalysis:"qe:post-coverage-analysis",CoverageGapIdentified:"qe:coverage-gap-identified",QEAgentRouting:"qe:agent-routing",QEAgentCompletion:"qe:agent-completion",QualityScoreCalculated:"qe:quality-score",RiskAssessmentComplete:"qe:risk-assessment",PatternLearned:"qe:pattern-learned",PatternApplied:"qe:pattern-applied",PatternPromoted:"qe:pattern-promoted",PreCompaction:"qe:pre-compaction"};function Q(i){return{[u.PreTestGeneration]:async t=>{let{targetFile:s,testType:a,framework:e,language:r}=t.data,n=await i.routeTask({task:`Generate ${a} tests for ${s}`,taskType:"test-generation",context:{framework:e,language:r,testType:a}});if(!n.success)return{success:!1,error:n.error.message};let o=[];try{let{getUnifiedMemory:c}=await import("./unified-memory-QG3FDRKR.js");o=c().getDatabase().prepare(`
3
3
  SELECT u.pattern_id, u.success, u.feedback
4
4
  FROM qe_pattern_usage u
5
5
  JOIN qe_patterns p ON u.pattern_id = p.id
6
6
  WHERE p.qe_domain = 'test-generation'
7
7
  ORDER BY u.created_at DESC
8
8
  LIMIT 10
9
- `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-RISHEANP.js");r=n().getDatabase().prepare(`
9
+ `).all()}catch{}return{success:!0,routing:n.value,guidance:n.value.guidance,data:{recommendedAgent:n.value.recommendedAgent,patterns:n.value.patterns.map(c=>c.id),recentExperiences:o}}},[u.PostTestGeneration]:async t=>{let{targetFile:s,generatedTests:a,testCount:e,framework:r,language:n,success:o,patternId:c}=t.data,d=0;if(c&&await i.recordOutcome({patternId:c,success:o,metrics:{testsPassed:0,testsFailed:0}}),o&&a&&e>0)try{(await i.storePattern({patternType:"test-template",name:`Generated tests for ${s.split("/").pop()}`,description:`Test template extracted from successful test generation for ${s}`,template:{type:"code",content:a,variables:[]},context:{framework:r,language:n,testType:"unit",tags:["generated","test-template",r,n]}})).success&&(d=1)}catch(p){l.debug("Pattern learning failed",{error:p instanceof Error?p.message:String(p)})}return{success:!0,patternsLearned:d,data:{learned:d>0}}},[u.TestExecutionResult]:async t=>{let{runId:s,patternId:a,passed:e,failed:r,duration:n,flaky:o}=t.data;if(a){let c=e+r>0?e/(e+r):0;await i.recordOutcome({patternId:a,success:c>.8&&!o,metrics:{testsPassed:e,testsFailed:r,executionTimeMs:n}})}return{success:!0,data:{runId:s,successRate:e+r>0?e/(e+r):0}}},[u.PreCoverageAnalysis]:async t=>{let{targetPath:s,currentCoverage:a}=t.data,e=await i.routeTask({task:`Analyze coverage gaps for ${s} (current: ${a}%)`,taskType:"analysis",domain:"coverage-analysis"});if(!e.success)return{success:!1,error:e.error.message};let r=[];try{let{getUnifiedMemory:n}=await import("./unified-memory-QG3FDRKR.js");r=n().getDatabase().prepare(`
10
10
  SELECT u.pattern_id, u.success, u.feedback
11
11
  FROM qe_pattern_usage u
12
12
  JOIN qe_patterns p ON u.pattern_id = p.id
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
- import{a as g}from"./chunk-IRR7YA3Q.js";import{b as p,c}from"./chunk-JD2PG4KS.js";import{a as x,b as f,c as w}from"./chunk-3LRK7PYN.js";import{i as v}from"./chunk-RTDHWOAG.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.4");process.exit(0)}
2
+ import{a as g}from"./chunk-GDMH7NPV.js";import{b as p,c}from"./chunk-UFKVKNAA.js";import{a as x,b as f,c as w}from"./chunk-2B6ETC7C.js";import{i as v}from"./chunk-PISW5HUX.js";w();var l={ProtocolStarted:"coordination.ProtocolStarted",ProtocolCompleted:"coordination.ProtocolCompleted",ProtocolFailed:"coordination.ProtocolFailed",ProtocolCancelled:"coordination.ProtocolCancelled",ActionStarted:"coordination.ActionStarted",ActionCompleted:"coordination.ActionCompleted",ActionFailed:"coordination.ActionFailed"},E=class{constructor(e,t,o){this.eventBus=e;this.memory=t;this.getDomainAPI=o}eventBus;memory;getDomainAPI;protocols=new Map;executions=new Map;scheduledProtocols=new Map;schedulerRunning=!1;registerProtocol(e){this.protocols.set(e.id,e),e.schedule.type==="event"&&e.enabled&&this.setupEventTriggers(e),(e.schedule.type==="cron"||e.schedule.type==="interval")&&e.enabled&&this.scheduleProtocol(e)}unregisterProtocol(e){if(!this.protocols.get(e))return!1;let o=this.scheduledProtocols.get(e);return o?.intervalId&&clearInterval(o.intervalId),this.scheduledProtocols.delete(e),this.protocols.delete(e),!0}getProtocol(e){return this.protocols.get(e)}listProtocols(){return Array.from(this.protocols.values())}async execute(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}async executeOnEvent(e,t){let o=this.protocols.get(e);return o?o.enabled?this.executeProtocol(o,void 0,t):c(new Error(`Protocol is disabled: ${e}`)):c(new Error(`Protocol not found: ${e}`))}getExecution(e){let t=this.executions.get(e);if(t)return this.toImmutableExecution(t.execution)}listActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.execution.status==="running"||e.execution.status==="paused").map(e=>this.toImmutableExecution(e.execution))}async cancelExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"&&t.execution.status!=="paused"?c(new Error(`Cannot cancel execution in status: ${t.execution.status}`)):(t.cancelled=!0,t.execution.status="cancelled",t.execution.completedAt=new Date,await this.publishEvent(l.ProtocolCancelled,{executionId:e,protocolId:t.protocol.id}),p(void 0)):c(new Error(`Execution not found: ${e}`))}async pauseExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="running"?c(new Error(`Cannot pause execution in status: ${t.execution.status}`)):(t.paused=!0,t.execution.status="paused",p(void 0)):c(new Error(`Execution not found: ${e}`))}async resumeExecution(e){let t=this.executions.get(e);return t?t.execution.status!=="paused"?c(new Error(`Cannot resume execution in status: ${t.execution.status}`)):(t.paused=!1,t.execution.status="running",p(void 0)):c(new Error(`Execution not found: ${e}`))}startScheduler(){if(!this.schedulerRunning){this.schedulerRunning=!0;for(let e of this.protocols.values())e.enabled&&(e.schedule.type==="interval"||e.schedule.type==="cron")&&this.scheduleProtocol(e)}}stopScheduler(){this.schedulerRunning=!1;for(let e of this.scheduledProtocols.values())e.intervalId&&(clearInterval(e.intervalId),e.intervalId=void 0)}async dispose(){this.stopScheduler(),this.protocols.clear(),this.executions.clear(),this.scheduledProtocols.clear()}async executeProtocol(e,t,o){let r=v(),a=o?.correlationId??r,n={executionId:r,protocolId:e.id,status:"running",participants:[...e.participants],results:new Map,startedAt:new Date,correlationId:a,triggeredBy:o},u={execution:n,protocol:e,params:t,actionResults:new Map,cancelled:!1,paused:!1};this.executions.set(r,u),await this.publishEvent(l.ProtocolStarted,{executionId:r,protocolId:e.id,participants:e.participants},a);try{await this.executeActions(u);let i=Array.from(u.actionResults.values()).some(s=>s.status==="failed");return u.cancelled?n.status="cancelled":i?(n.status="failed",await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,failedActions:Array.from(u.actionResults.values()).filter(s=>s.status==="failed").map(s=>s.actionId)},a)):(n.status="completed",await this.publishEvent(l.ProtocolCompleted,{executionId:r,protocolId:e.id,duration:Date.now()-n.startedAt.getTime()},a)),n.completedAt=new Date,n.results=u.actionResults,await this.storeExecutionHistory(n),p(this.toImmutableExecution(n))}catch(i){return n.status="failed",n.completedAt=new Date,await this.publishEvent(l.ProtocolFailed,{executionId:r,protocolId:e.id,error:x(i)},a),c(f(i))}}async executeActions(e){let{protocol:t,actionResults:o}=e,r=new Set(t.actions.map(n=>n.id)),a=new Set;for(;r.size>0&&!e.cancelled;){for(;e.paused&&!e.cancelled;)await this.sleep(100);if(e.cancelled)break;let n=t.actions.filter(i=>r.has(i.id)&&this.dependenciesSatisfied(i,a));if(n.length===0&&r.size>0)throw new Error(`Deadlock detected: actions ${Array.from(r).join(", ")} cannot proceed`);let u=await Promise.allSettled(n.map(i=>this.executeAction(i,e)));for(let i=0;i<n.length;i++){let s=n[i],d=u[i],m;d.status==="fulfilled"?m=d.value:m={actionId:s.id,status:"failed",error:d.reason instanceof Error?d.reason.message:String(d.reason)},o.set(s.id,m),r.delete(s.id),m.status==="completed"&&a.add(s.id)}}for(let n of r)o.set(n,{actionId:n,status:e.cancelled?"cancelled":"skipped"})}async executeAction(e,t){let o=new Date;await this.publishEvent(l.ActionStarted,{executionId:t.execution.executionId,actionId:e.id,actionName:e.name,targetDomain:e.targetDomain},t.execution.correlationId);let r=0,a=e.retry?.maxAttempts??1,n;for(;r<a;){r++;try{let i=this.getDomainAPI(e.targetDomain);if(!i)throw new Error(`Domain API not available: ${e.targetDomain}`);let s=i[e.method];if(typeof s!="function")throw new Error(`Method ${e.method} not found on domain ${e.targetDomain}`);let d={...e.params,...t.params},m=await this.executeWithTimeout(s.bind(i)(d),e.timeout??3e4),h=new Date;return await this.publishEvent(l.ActionCompleted,{executionId:t.execution.executionId,actionId:e.id,duration:h.getTime()-o.getTime()},t.execution.correlationId),{actionId:e.id,status:"completed",startedAt:o,completedAt:h,duration:h.getTime()-o.getTime(),result:m,retryAttempts:r>1?r-1:void 0}}catch(i){if(n=f(i),r<a&&e.retry){let s=e.retry.backoffMs*Math.pow(e.retry.backoffMultiplier??2,r-1);await this.sleep(s)}}}let u=new Date;return await this.publishEvent(l.ActionFailed,{executionId:t.execution.executionId,actionId:e.id,error:n?.message??"Unknown error",attempts:r},t.execution.correlationId),{actionId:e.id,status:"failed",startedAt:o,completedAt:u,duration:u.getTime()-o.getTime(),error:n?.message??"Unknown error",retryAttempts:r>1?r-1:void 0}}dependenciesSatisfied(e,t){return!e.dependsOn||e.dependsOn.length===0?!0:e.dependsOn.every(o=>t.has(o))}async executeWithTimeout(e,t){return Promise.race([e,new Promise((o,r)=>setTimeout(()=>r(new Error("Action timeout")),t))])}setupEventTriggers(e){if(e.schedule.type==="event")for(let t of e.schedule.triggerEvents)this.eventBus.subscribe(t,async o=>{await this.executeOnEvent(e.id,o)})}scheduleProtocol(e){if(e.schedule.type==="interval"){let t={protocolId:e.id,schedule:e.schedule};t.intervalId=setInterval(async()=>{this.schedulerRunning&&await this.execute(e.id)},e.schedule.intervalMs),this.scheduledProtocols.set(e.id,t)}}async storeExecutionHistory(e){let t=`protocol-execution:${e.executionId}`;await this.memory.set(t,{...e,results:Object.fromEntries(e.results)},{namespace:"coordination",ttl:864e5})}toImmutableExecution(e){return{executionId:e.executionId,protocolId:e.protocolId,status:e.status,participants:[...e.participants],results:new Map(e.results),startedAt:e.startedAt,completedAt:e.completedAt,correlationId:e.correlationId,triggeredBy:e.triggeredBy}}async publishEvent(e,t,o){let r=g(e,"learning-optimization",t,o);await this.eventBus.publish(r)}sleep(e){return new Promise(t=>setTimeout(t,e))}};function S(P,e,t){return new E(P,e,t)}export{E 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.10.3");process.exit(0)}
2
- import{h as s,k as o,o as h}from"./chunk-USFZ4IJD.js";import{a as m}from"./chunk-3VF3HCG4.js";import{c as r}from"./chunk-2L73WXA4.js";import{a,e as u}from"./chunk-QWG76RHA.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.10.4");process.exit(0)}
2
+ import{f as s,i as o,m as h}from"./chunk-NZGLDOU4.js";import{a as m}from"./chunk-HPYGMKZF.js";import{c as r}from"./chunk-VRE2EBFI.js";import{a,e as u}from"./chunk-6OLHPWSN.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 > ?)
@@ -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.10.3");process.exit(0)}
2
- import{c as N,g as O,i as L}from"./chunk-NZHOKLII.js";import{k as R,o as D}from"./chunk-USFZ4IJD.js";import{b as g,d as w}from"./chunk-KTRB3L53.js";import{a as p,c as q}from"./chunk-3LRK7PYN.js";import{i as h}from"./chunk-RTDHWOAG.js";import{a as S,b as C}from"./chunk-L74CHKFR.js";C();w();q();D();function y(E,e){let n=E.prepare("SELECT confidence, usage_count, successful_uses FROM qe_patterns WHERE id = ?").get(e.patternId);if(!n)return{updated:!1};let t=e.success?1:0,r=n.usage_count+1,a=n.successful_uses+t,s=a/r,i=Math.min(1,r/100),o=n.confidence*.3+i*.2+s*.5,c=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.10.4");process.exit(0)}
2
+ import{c as N,g as O,i as L}from"./chunk-5T2HDET6.js";import{i as R,m as D}from"./chunk-NZGLDOU4.js";import{b as g,d as w}from"./chunk-IYFMDIYZ.js";import{a as p,c as q}from"./chunk-2B6ETC7C.js";import{i as h}from"./chunk-PISW5HUX.js";import{a as S,b as C}from"./chunk-RJKYPWFD.js";C();w();q();D();function y(E,e){let n=E.prepare("SELECT confidence, usage_count, successful_uses FROM qe_patterns WHERE id = ?").get(e.patternId);if(!n)return{updated:!1};let t=e.success?1:0,r=n.usage_count+1,a=n.successful_uses+t,s=a/r,i=Math.min(1,r/100),o=n.confidence*.3+i*.2+s*.5,c=E.prepare(`
3
3
  INSERT INTO qe_pattern_usage (pattern_id, success, metrics_json, feedback)
4
4
  VALUES (?, ?, ?, ?)
5
5
  `),m=E.prepare(`
@@ -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.10.3");process.exit(0)}
2
- import{d as be}from"./chunk-5LON3MLI.js";import{b as D,d as ye}from"./chunk-KTRB3L53.js";import{a as Le}from"./chunk-3VF3HCG4.js";import{c as fe,d as ge,e as Pe}from"./chunk-2L73WXA4.js";import{b as P,c as L}from"./chunk-JD2PG4KS.js";import{a as G,b as A,c as J}from"./chunk-3LRK7PYN.js";Le();import{createRequire as Ce}from"module";var O;function W(){if(!O){let u=Ce(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},We=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},ze=new Q;Pe();var E=1e3;function I(u){let e=u.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.4");process.exit(0)}
2
+ import{d as be}from"./chunk-VJOPNK2L.js";import{b as D,d as ye}from"./chunk-IYFMDIYZ.js";import{a as Le}from"./chunk-HPYGMKZF.js";import{c as fe,d as ge,e as Pe}from"./chunk-VRE2EBFI.js";import{b as P,c as L}from"./chunk-UFKVKNAA.js";import{a as G,b as A,c as J}from"./chunk-2B6ETC7C.js";Le();import{createRequire as Ce}from"module";var O;function W(){if(!O){let u=Ce(import.meta.url);try{O=u("typescript")}catch{try{O=u("typescript/lib/typescript.js")}catch{O=new Proxy({},{get(e,t){if(!(t==="__esModule"||typeof t=="symbol"))throw new Error("TypeScript is required for code analysis. Install it: npm install -g typescript")}})}}}return O}var m=new Proxy({},{get(u,e){return W()[e]},has(u,e){return e in W()},ownKeys(){return Object.keys(W())},getOwnPropertyDescriptor(u,e){let t=W()[e];if(t!==void 0)return{configurable:!0,enumerable:!0,value:t}}});var N=class{parseFile(e,t){return m.createSourceFile(e,t,m.ScriptTarget.Latest,!0,this.getScriptKind(e))}extractFunctions(e){let t=[],s=n=>{m.isFunctionDeclaration(n)&&n.name?t.push(this.extractFunctionDeclaration(n,e)):m.isVariableStatement(n)&&this.extractArrowFunctions(n,e,t),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractClasses(e){let t=[],s=n=>{m.isClassDeclaration(n)&&n.name&&t.push(this.extractClassDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractImports(e){let t=[],s=n=>{m.isImportDeclaration(n)&&t.push(this.extractImportDeclaration(n)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractExports(e){let t=[],s=n=>{if(m.isExportDeclaration(n))this.extractExportDeclaration(n,t);else if(m.isExportAssignment(n))t.push({name:this.getExportAssignmentName(n),type:"unknown",isDefault:!0,isReexport:!1,sourceModule:void 0});else if(m.isFunctionDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"function",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isClassDeclaration(n)&&n.name&&this.hasExportModifier(n))t.push({name:n.name.text,type:"class",isDefault:this.hasDefaultModifier(n),isReexport:!1,sourceModule:void 0});else if(m.isVariableStatement(n)&&this.hasExportModifier(n))for(let i of n.declarationList.declarations)m.isIdentifier(i.name)&&t.push({name:i.name.text,type:"variable",isDefault:!1,isReexport:!1,sourceModule:void 0});else m.isInterfaceDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"interface",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isTypeAliasDeclaration(n)&&this.hasExportModifier(n)?t.push({name:n.name.text,type:"type",isDefault:!1,isReexport:!1,sourceModule:void 0}):m.isEnumDeclaration(n)&&this.hasExportModifier(n)&&t.push({name:n.name.text,type:"enum",isDefault:!1,isReexport:!1,sourceModule:void 0});m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractInterfaces(e){let t=[],s=n=>{m.isInterfaceDeclaration(n)&&t.push(this.extractInterfaceDeclaration(n,e)),m.forEachChild(n,s)};return m.forEachChild(e,s),t}extractEntities(e,t){let s=this.parseFile(t,e),n=[],i=this.extractFunctions(s);for(let a of i)n.push({name:a.name,type:"function",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:a.isAsync,isExported:a.isExported,parameters:a.parameters,returnType:a.returnType});let o=this.extractClasses(s);for(let a of o)n.push({name:a.name,type:"class",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported,extends:a.extends,implements:a.implements});let r=this.extractInterfaces(s);for(let a of r)n.push({name:a.name,type:"interface",line:a.startLine,endLine:a.endLine,visibility:a.isExported?"public":"internal",isAsync:!1,isExported:a.isExported});return n}getScriptKind(e){return e.endsWith(".tsx")?m.ScriptKind.TSX:e.endsWith(".ts")?m.ScriptKind.TS:e.endsWith(".jsx")?m.ScriptKind.JSX:e.endsWith(".js")?m.ScriptKind.JS:m.ScriptKind.TS}extractFunctionDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:e.name?.text??"anonymous",parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,startLine:s+1,endLine:n+1,isAsync:this.hasAsyncModifier(e),isExported:this.hasExportModifier(e),isGenerator:!!e.asteriskToken,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractArrowFunctions(e,t,s){for(let n of e.declarationList.declarations)if(m.isIdentifier(n.name)&&n.initializer&&m.isArrowFunction(n.initializer)){let i=n.initializer,{line:o}=t.getLineAndCharacterOfPosition(e.getStart()),{line:r}=t.getLineAndCharacterOfPosition(e.getEnd());s.push({name:n.name.text,parameters:this.extractParameters(i.parameters),returnType:i.type?i.type.getText(t):void 0,startLine:o+1,endLine:r+1,isAsync:this.hasAsyncModifier(i),isExported:this.hasExportModifier(e),isGenerator:!1,typeParameters:this.extractTypeParameters(i.typeParameters)})}}extractClassDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let c of e.members)m.isMethodDeclaration(c)&&c.name?i.push(this.extractMethodDeclaration(c,t)):m.isPropertyDeclaration(c)&&c.name?o.push(this.extractPropertyDeclaration(c,t)):m.isConstructorDeclaration(c)&&(i.push(this.extractConstructor(c,t)),this.extractParameterProperties(c,o,t));let r,a=[];if(e.heritageClauses){for(let c of e.heritageClauses)if(c.token===m.SyntaxKind.ExtendsKeyword)r=c.types[0]?.expression.getText(t);else if(c.token===m.SyntaxKind.ImplementsKeyword)for(let l of c.types)a.push(l.expression.getText(t))}return{name:e.name?.text??"anonymous",methods:i,properties:o,extends:r,implements:a,isAbstract:this.hasAbstractModifier(e),isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractMethodDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:this.getPropertyName(e.name,t),parameters:this.extractParameters(e.parameters),returnType:e.type?e.type.getText(t):void 0,isAsync:this.hasAsyncModifier(e),isStatic:this.hasStaticModifier(e),isAbstract:this.hasAbstractModifier(e),visibility:this.getVisibility(e),startLine:s+1,endLine:n+1}}extractConstructor(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd());return{name:"constructor",parameters:this.extractParameters(e.parameters),returnType:void 0,isAsync:!1,isStatic:!1,isAbstract:!1,visibility:"public",startLine:s+1,endLine:n+1}}extractParameterProperties(e,t,s){for(let n of e.parameters)this.isParameterProperty(n)&&t.push({name:m.isIdentifier(n.name)?n.name.text:n.name.getText(s),type:n.type?n.type.getText(s):void 0,isStatic:!1,isReadonly:this.hasReadonlyModifier(n),visibility:this.getVisibility(n),hasInitializer:!!n.initializer})}isParameterProperty(e){return!!e.modifiers?.some(t=>t.kind===m.SyntaxKind.PublicKeyword||t.kind===m.SyntaxKind.PrivateKeyword||t.kind===m.SyntaxKind.ProtectedKeyword||t.kind===m.SyntaxKind.ReadonlyKeyword)}extractPropertyDeclaration(e,t){return{name:this.getPropertyName(e.name,t),type:e.type?e.type.getText(t):void 0,isStatic:this.hasStaticModifier(e),isReadonly:this.hasReadonlyModifier(e),visibility:this.getVisibility(e),hasInitializer:!!e.initializer}}extractImportDeclaration(e){let t=e.moduleSpecifier.text,s=[],n,i,o=e.importClause?.isTypeOnly??!1;if(e.importClause&&(e.importClause.name&&(n=e.importClause.name.text),e.importClause.namedBindings)){if(m.isNamespaceImport(e.importClause.namedBindings))i=e.importClause.namedBindings.name.text;else if(m.isNamedImports(e.importClause.namedBindings))for(let r of e.importClause.namedBindings.elements)s.push({name:r.propertyName?.text??r.name.text,alias:r.propertyName?r.name.text:void 0})}return{module:t,namedImports:s,defaultImport:n,namespaceImport:i,isTypeOnly:o}}extractExportDeclaration(e,t){let s=e.moduleSpecifier?e.moduleSpecifier.text:void 0;if(e.exportClause&&m.isNamedExports(e.exportClause))for(let n of e.exportClause.elements)t.push({name:n.name.text,type:"unknown",isDefault:!1,isReexport:!!s,sourceModule:s});else!e.exportClause&&s&&t.push({name:"*",type:"unknown",isDefault:!1,isReexport:!0,sourceModule:s})}extractInterfaceDeclaration(e,t){let{line:s}=t.getLineAndCharacterOfPosition(e.getStart()),{line:n}=t.getLineAndCharacterOfPosition(e.getEnd()),i=[],o=[];for(let a of e.members)m.isPropertySignature(a)&&a.name?i.push({name:this.getPropertyName(a.name,t),type:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken,isReadonly:this.hasReadonlyModifier(a)}):m.isMethodSignature(a)&&a.name&&o.push({name:this.getPropertyName(a.name,t),parameters:this.extractParameters(a.parameters),returnType:a.type?a.type.getText(t):void 0,isOptional:!!a.questionToken});let r=[];if(e.heritageClauses){for(let a of e.heritageClauses)if(a.token===m.SyntaxKind.ExtendsKeyword)for(let c of a.types)r.push(c.expression.getText(t))}return{name:e.name.text,properties:i,methods:o,extends:r,isExported:this.hasExportModifier(e),startLine:s+1,endLine:n+1,typeParameters:this.extractTypeParameters(e.typeParameters)}}extractParameters(e){return e.map(t=>{let s=t.getSourceFile();return{name:m.isIdentifier(t.name)?t.name.text:t.name.getText(s),type:t.type?t.type.getText(s):void 0,isOptional:!!t.questionToken||!!t.initializer,isRest:!!t.dotDotDotToken,defaultValue:t.initializer?t.initializer.getText(s):void 0}})}extractTypeParameters(e){return e?e.map(t=>t.name.text):[]}getPropertyName(e,t){return m.isIdentifier(e)||m.isStringLiteral(e)||m.isNumericLiteral(e)?e.text:e.getText(t)}getExportAssignmentName(e){return m.isIdentifier(e.expression)?e.expression.text:"default"}hasExportModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ExportKeyword)}hasDefaultModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.DefaultKeyword)}hasAsyncModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AsyncKeyword)}hasStaticModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.StaticKeyword)}hasAbstractModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.AbstractKeyword)}hasReadonlyModifier(e){return m.canHaveModifiers(e)&&!!m.getModifiers(e)?.some(t=>t.kind===m.SyntaxKind.ReadonlyKeyword)}getVisibility(e){if(!m.canHaveModifiers(e))return"public";let t=m.getModifiers(e);return t?t.some(s=>s.kind===m.SyntaxKind.PrivateKeyword)?"private":t.some(s=>s.kind===m.SyntaxKind.ProtectedKeyword)?"protected":"public":"public"}},We=new N,Q=class{language="typescript";supportedExtensions=[".ts",".tsx",".js",".jsx",".mjs",".cjs"];parser=new N;async parseFile(e,t){let s=this.parser.parseFile(t,e),n=this.parser.extractFunctions(s),i=this.parser.extractClasses(s),o=this.parser.extractImports(s);return{functions:n.map(r=>this.mapFunction(r)),classes:i.map(r=>this.mapClass(r)),imports:o.map(r=>this.mapImport(r)),language:t.endsWith(".js")||t.endsWith(".jsx")||t.endsWith(".mjs")||t.endsWith(".cjs")?"javascript":"typescript",filePath:t}}mapFunction(e){return{name:e.name,parameters:e.parameters.map(t=>({name:t.name,type:t.type,isOptional:t.isOptional,defaultValue:t.defaultValue})),returnType:e.returnType,isAsync:e.isAsync,isPublic:e.isExported,complexity:1,decorators:[],genericParams:e.typeParameters,startLine:e.startLine,endLine:e.endLine}}mapClass(e){return{name:e.name,methods:e.methods.map(t=>({name:t.name,parameters:t.parameters.map(s=>({name:s.name,type:s.type,isOptional:s.isOptional,defaultValue:s.defaultValue})),returnType:t.returnType,isAsync:t.isAsync,isPublic:t.visibility==="public",complexity:1,decorators:[],genericParams:[],startLine:t.startLine,endLine:t.endLine})),properties:e.properties.map(t=>this.mapProperty(t)),isPublic:e.isExported,implements:e.implements,extends:e.extends,decorators:[],startLine:e.startLine,endLine:e.endLine}}mapProperty(e){return{name:e.name,type:e.type,isPublic:e.visibility==="public",isReadonly:e.isReadonly}}mapImport(e){return{module:e.module,namedImports:e.namedImports.map(t=>t.alias||t.name),isTypeOnly:e.isTypeOnly}}},ze=new Q;Pe();var E=1e3;function I(u){let e=u.split(`
3
3
  `),t=[],s=[],n="",i=0,o=0,r=0,a=0;for(let c=0;c<e.length;c++){let l=e[c],d=l.trim();if(d===""||d.startsWith("//")||d.startsWith("#")||d.startsWith("*")){if(n){n+=" "+d;continue}t.push(l),s.push(c+1);continue}n||(i=c+1),n=n?n+" "+d:l;for(let p of d)p==="("?o++:p===")"?o=Math.max(0,o-1):p==="<"?r++:p===">"?r=Math.max(0,r-1):p==="["?a++:p==="]"&&(a=Math.max(0,a-1));o===0&&r===0&&a===0&&(t.push(n),s.push(i),n="")}return n&&(t.push(n),s.push(i)),{logicalLines:t,lineMap:s}}function B(u,e,t="<",s=">"){if(u[e]!==t)return;let n=1,i=e+1;for(;i<u.length&&n>0;)u[i]===t?n++:u[i]===s&&n--,i++;if(n===0)return u.substring(e+1,i-1)}function C(u,e,t){let s=[];for(let n=e-1;n>=0;n--){let i=u[n].trim();if(i.startsWith(t))s.unshift(i);else{if(i===""||i.startsWith("//")||i.startsWith("*")||i.startsWith("#"))continue;break}}return s}function M(u){let e=[],t=0,s="";for(let n of u)n==="<"||n==="("?t++:(n===">"||n===")")&&t--,n===","&&t===0?(e.push(s.trim()),s=""):s+=n;return s.trim()&&e.push(s.trim()),e}function ce(u){let e=0,t=!1,s="";for(let n=0;n<u.length;n++){let i=u[n];if(t){i===s&&u[n-1]!=="\\"&&(t=!1);continue}i==='"'||i==="'"||i==="`"?(t=!0,s=i):i==="{"?e++:i==="}"&&e--}return e}var Y=class{language="python";supportedExtensions=[".py"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"python",filePath:t}}extractFunctions(e){let t=[],s=e.split(`
4
4
  `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)(async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*([^:]*\S))?\s*:/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[1].length,l=!!a[2],d=a[3],p=a[4],h=a[5]?.trim(),f=i[r]-1,g=f+1;for(let y=f+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){g=y;break}g=y+1}let b=C(s,f,"@");t.push({name:d,parameters:this.parseParams(p),returnType:h,isAsync:l,isPublic:!d.startsWith("_"),complexity:1,decorators:b,genericParams:[],startLine:i[r],endLine:g})}}return t}extractClasses(e){let t=[],s=e.split(`
5
5
  `),{logicalLines:n,lineMap:i}=I(e),o=/^(\s*)class\s+(\w+)(?:\(([^)]*)\))?\s*:/;for(let r=0;r<n.length;r++){let a=n[r].match(o);if(a){let c=a[1].length,l=a[2],d=a[3]?a[3].split(",").map(y=>y.trim()):[],p=i[r]-1,h=p+1;for(let y=p+1;y<s.length;y++){let x=s[y];if(x.trim()===""||x.trim().startsWith("#"))continue;if((x.match(/^(\s*)/)?.[1].length??0)<=c&&x.trim()!==""){h=y;break}h=y+1}let f=s.slice(p+1,h).join(`
@@ -20,7 +20,7 @@ import{d as be}from"./chunk-5LON3MLI.js";import{b as D,d as ye}from"./chunk-KTRB
20
20
  `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(suspend)?\s*fun\s+(?:<[^{]*> +)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*([^{=\s]+(?:\s+[^{=\s]+)*))?\s*/,r=0;for(let a=0;a<n.length;a++){let c=n[a];if(c.length>E){r+=(c.match(/\{/g)?.length??0)-(c.match(/\}/g)?.length??0);continue}let l=c.match(o);if(l&&r<=1){let d=l[1]||"public",p=!!l[2],h=l[3],f=l[4],g=l[5]?.trim();if(g&&g.includes("<")){let x=g.indexOf("<"),w=B(g,x);w!==void 0&&(g=g.substring(0,x)+"<"+w+">")}let b=i[a]-1,y=C(s,b,"@");t.push({name:h,parameters:this.parseParams(f),returnType:g,isAsync:p,isPublic:d==="public",complexity:1,decorators:y,genericParams:[],startLine:i[a],endLine:i[a]})}r+=ce(c),r<0&&(r=0)}return t}extractClasses(e){let t=[],s=e.split(`
21
21
  `),{logicalLines:n,lineMap:i}=I(e),o=/^\s*(public|private|protected|internal)?\s*(data|sealed|abstract|open)?\s*class\s+(\w+)(?:<[^{]*>)?(?:\s*(?:\([^)]*\))?\s*:\s*([^{\s]+(?:\s+[^{\s]+)*))?\s*\{?/;for(let r=0;r<n.length;r++){if(n[r].length>E)continue;let a=n[r].match(o);if(a){let c=a[3],l=a[4]?a[4].split(",").map(h=>h.trim().split("(")[0].trim()):[],d=i[r]-1,p=C(s,d,"@");t.push({name:c,methods:[],properties:[],isPublic:(a[1]||"public")==="public",implements:l.slice(1),extends:l[0]||void 0,decorators:p,startLine:i[r],endLine:i[r]})}}return t}extractImports(e){let t=[],s=e.split(`
22
22
  `);for(let n of s){let i=n.match(/^\s*import\s+([^\s]+)/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){return e.trim()?M(e).map(t=>{let s=t.indexOf(":");if(s===-1)return{name:t.replace("val ","").replace("var ","").trim(),type:void 0,isOptional:!1,defaultValue:void 0};let n=t.substring(0,s).replace("val ","").replace("var ","").trim(),i=t.substring(s+1).trim(),o=i.indexOf("="),r=o>=0?i.substring(0,o).trim():i,a=o>=0;return{name:n,type:r,isOptional:a||r?.endsWith("?")||!1,defaultValue:void 0}}):[]}},re=class{language="dart";supportedExtensions=[".dart"];async parseFile(e,t){return{functions:this.extractFunctions(e),classes:this.extractClasses(e),imports:this.extractImports(e),language:"dart",filePath:t}}extractFunctions(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*([\w<>,.?]+(?:\s+[\w<>,.?]+)*)\s+(\w+)\s*\(([^)]*)\)(?:\s*(async))?\s*\{/;for(let o=0;o<s.length;o++){let r=s[o];if(r.includes(" class ")||r.length>E)continue;let a=r.match(i);if(a){let c=a[1].trim(),l=c;if(c&&c.includes("<")){let f=c.indexOf("<"),g=B(c,f);g!==void 0&&(l=c.substring(0,f)+"<"+g+">")}let d=a[2],p=a[3],h=!!a[4]||l.includes("Future");t.push({name:d,parameters:this.parseParams(p),returnType:l==="void"?void 0:l,isAsync:h,isPublic:!d.startsWith("_"),complexity:1,decorators:[],genericParams:[],startLine:n[o],endLine:n[o]})}}return t}extractClasses(e){let t=[],{logicalLines:s,lineMap:n}=I(e),i=/^\s*(abstract +)?class\s+(\w+)(?:<[^{]*>)?(?:\s+extends\s+(\w+))?(?:\s+(?:with|implements)\s+([^{\s]+(?:\s+[^{\s]+)*))?\s*\{/;for(let o=0;o<s.length;o++){if(s[o].length>E)continue;let r=s[o].match(i);if(r){let a=r[2],c=r[3],l=r[4]?r[4].split(",").map(d=>d.trim()):[];t.push({name:a,methods:[],properties:[],isPublic:!a.startsWith("_"),implements:l,extends:c,decorators:[],startLine:n[o],endLine:n[o]})}}return t}extractImports(e){let t=[],s=e.split(`
23
- `);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),xe=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-IIGEJYFU.js");if(!e.isWasmAvailable()){z.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of xe){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+xe.join(", "))}catch{z.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Re=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Se=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Re)if(f.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let f of Se)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Me=new le,ve=(u,e)=>Me.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Te(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ee(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ee(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=ve(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Te(e),o=[];return await Ee(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Fe}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Fe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as Oe,statSync as ke}from"fs";import{dirname as _e,resolve as $e,join as q}from"path";function Ae(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Ne(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function De(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Ne(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=Ae(e);if(!t)return null;let s=await be(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(De(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var Ke={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Ie=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...Ke,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k,this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
23
+ `);for(let n of s){let i=n.match(/^\s*import\s+'([^']+)'/);i&&t.push({module:i[1],namedImports:[],isTypeOnly:!1})}return t}parseParams(e){if(!e.trim())return[];let t=e.replace(/[{}[\]]/g,"");return M(t).map(s=>s.trim()).filter(s=>s).map(s=>{let n=s.replace("required ","").trim().split(/\s+/),i=n[n.length-1]||"",o=n.slice(0,-1).join(" ")||void 0;return{name:i,type:o,isOptional:s.includes("?")||s.includes("{"),defaultValue:void 0}})}},z=ge("ParserRegistry"),xe=["python","java","csharp","rust","swift"],ae=class u{language;supportedExtensions;wasmParser;regexParser;wasmFailCount=0;static MAX_WASM_RETRIES=3;constructor(e,t){this.wasmParser=e,this.regexParser=t,this.language=e.language,this.supportedExtensions=e.supportedExtensions}async parseFile(e,t){if(this.wasmFailCount<u.MAX_WASM_RETRIES)try{return await this.wasmParser.parseFile(e,t)}catch(s){this.wasmFailCount++;let n=s instanceof Error?s.message:String(s),i=this.wasmFailCount>=u.MAX_WASM_RETRIES;z.warn(`[${this.language}] tree-sitter WASM parser failed (attempt ${this.wasmFailCount}/${u.MAX_WASM_RETRIES}): ${n}. Falling back to regex parser (~97-98% accuracy). `+(i?"Set AQE_PARSER_REGEX_ONLY=1 to silence this warning.":"Will retry WASM on next parse."))}return this.regexParser.parseFile(e,t)}},oe=class{parsers=new Map;_wasmInitPromise=null;constructor(){this.register(new Y),this.register(new Z),this.register(new ee),this.register(new te),this.register(new se),this.register(new ne),this.register(new ie),this.register(new re),this._wasmInitPromise=this._tryLoadWasmParsers()}async _tryLoadWasmParsers(){try{let e=await import("./tree-sitter-wasm-parser-MWSS52H6.js");if(!e.isWasmAvailable()){z.info("tree-sitter WASM parsers disabled or unavailable. Using regex parsers (~97-98% accuracy). Set AQE_PARSER_REGEX_ONLY=0 or ensure web-tree-sitter is installed to enable WASM.");return}let t=e.createWasmParsers();for(let s of xe){let n=t.get(s),i=this.parsers.get(s);n&&i&&this.parsers.set(s,new ae(n,i))}z.info("tree-sitter WASM parsers available for: "+xe.join(", "))}catch{z.info("tree-sitter WASM parser module not available. Using regex parsers for all languages.")}}register(e){this.parsers.set(e.language,e)}getParser(e){return this.parsers.get(e)}async parseFile(e,t,s){this._wasmInitPromise&&(await this._wasmInitPromise,this._wasmInitPromise=null);let n=this.parsers.get(s);if(n)return n.parseFile(e,t)}getSupportedLanguages(){return Array.from(this.parsers.keys())}supportsLanguage(e){return this.parsers.has(e)}},qe=new oe;import*as S from"node:fs/promises";import*as R from"node:path";var Re=[/\.\./,/%2e%2e/i,/%252e%252e/i,/\.\.%2f/i,/%2f\.\./i,/\.\.%5c/i,/\.\.\\/,/%c0%ae/i,/%c0%2f/i,/%c1%9c/i,/\0/,/%00/i],Se=[/^\/etc\//i,/^\/proc\//i,/^\/sys\//i,/^\/dev\//i,/^\/root\//i,/^\/home\/.+\/\./i,/^[A-Z]:\\Windows/i,/^[A-Z]:\\System/i,/^[A-Z]:\\Users\\.+\\AppData/i],le=class{name="path-traversal";getRiskLevel(){return"critical"}validate(e,t={}){let{basePath:s="",allowAbsolute:n=!1,allowedExtensions:i=[],deniedExtensions:o=[".exe",".bat",".cmd",".sh",".ps1",".dll",".so"],maxDepth:r=10,maxLength:a=4096}=t;if(e.length>a)return{valid:!1,error:`Path exceeds maximum length of ${a}`,riskLevel:"medium"};for(let f of Re)if(f.test(e))return{valid:!1,error:"Path traversal attempt detected",riskLevel:"critical"};if(!n&&(e.startsWith("/")||/^[A-Z]:/i.test(e)))return{valid:!1,error:"Absolute paths are not allowed",riskLevel:"high"};for(let f of Se)if(f.test(e))return{valid:!1,error:"Access to system paths is not allowed",riskLevel:"critical"};let c=this.normalizePath(e);if(c.includes(".."))return{valid:!1,error:"Path traversal detected after normalization",riskLevel:"critical"};if(c.split("/").filter(Boolean).length>r)return{valid:!1,error:`Path depth exceeds maximum of ${r}`,riskLevel:"low"};let d=this.getExtension(c);if(d){let f=`.${d.toLowerCase()}`,g=d.toLowerCase();if(o.length>0&&o.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not allowed`,riskLevel:"high"};if(i.length>0&&!i.some(y=>y.toLowerCase()===f||y.toLowerCase()===g))return{valid:!1,error:`File extension '${d}' is not in allowed list`,riskLevel:"medium"}}let p=s?this.joinPathsAbsolute(s,c):c,h=s.startsWith("/")?`/${this.normalizePath(s)}`:this.normalizePath(s);return s&&!p.startsWith(h)?{valid:!1,error:"Path escapes base directory",riskLevel:"critical"}:{valid:!0,normalizedPath:p,riskLevel:"none"}}normalizePath(e){let t=e.replace(/\\/g,"/");t=t.replace(/\/+/g,"/");let s=t.split("/"),n=[];for(let i of s)i==="."||i===""||(i===".."?n.length>0&&n[n.length-1]!==".."&&n.pop():n.push(i));return n.join("/")}joinPaths(...e){return e.length===0?"":e.map(t=>t.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}joinPathsAbsolute(...e){if(e.length===0)return"";let t=e[0].startsWith("/"),s=e.map(n=>{for(;n.startsWith("/");)n=n.slice(1);for(;n.endsWith("/");)n=n.slice(0,-1);return n}).filter(Boolean).join("/");return t?`/${s}`:s}getExtension(e){let t=e.match(/\.([^./\\]+)$/);return t?t[1]:null}},Me=new le,ve=(u,e)=>Me.validate(u,e);ye();var F=class extends Error{constructor(t,s,n,i){super(t);this.filePath=s;this.code=n;this.cause=i;this.name="FileReadError"}filePath;code;cause},V=class extends Error{constructor(t,s,n){super(t);this.filePath=s;this.cause=n;this.name="JsonParseError"}filePath;cause},T=class extends Error{constructor(t,s,n){super(`Path traversal detected: ${s.join(", ")}`);this.requestedPath=t;this.issues=s;this.riskLevel=n;this.name="PathTraversalError"}requestedPath;issues;riskLevel},de=class{constructor(e,t){this.maxSize=e;this.ttlMs=t}maxSize;ttlMs;cache=new Map;accessOrder=[];get(e){let t=this.cache.get(e);if(t){if(Date.now()-t.timestamp>this.ttlMs){this.delete(e);return}return this.updateAccessOrder(e),t.value}}set(e,t,s){for(this.cache.has(e)&&this.delete(e);this.cache.size>=this.maxSize&&this.accessOrder.length>0;){let n=this.accessOrder.shift();n&&this.cache.delete(n)}this.cache.set(e,{value:t,timestamp:Date.now(),size:s}),this.accessOrder.push(e)}delete(e){let t=this.cache.delete(e);if(t){let s=this.accessOrder.indexOf(e);s>-1&&this.accessOrder.splice(s,1)}return t}clear(){this.cache.clear(),this.accessOrder=[]}get size(){return this.cache.size}get totalBytes(){let e=0;return this.cache.forEach(t=>{e+=t.size}),e}updateAccessOrder(e){let t=this.accessOrder.indexOf(e);t>-1&&(this.accessOrder.splice(t,1),this.accessOrder.push(e))}prune(){let e=Date.now(),t=0,s=[];return this.cache.forEach((n,i)=>{e-n.timestamp>this.ttlMs&&s.push(i)}),s.forEach(n=>{this.delete(n),t++}),t}};function Te(u){let e="",t=0;for(;t<u.length;){let s=u[t],n=u[t+1];s==="*"&&n==="*"?u[t+2]==="/"?(e+="(?:.*/)?",t+=3):(e+=".*",t+=2):s==="*"?(e+="[^/]*",t++):s==="?"?(e+="[^/]",t++):".+^${}()|[]\\".includes(s)?(e+="\\"+s,t++):(e+=s,t++)}return new RegExp("^"+e+"$")}async function Ee(u,e,t,s){try{let n=await S.readdir(u,{withFileTypes:!0});for(let i of n){let o=R.join(u,i.name),r=R.relative(s,o);if(i.isDirectory())i.name!=="node_modules"&&!i.name.startsWith(".")&&await Ee(o,e,t,s);else if(i.isFile()){let a=r.replace(/\\/g,"/");e.test(a)&&t.push(o)}}}catch(n){console.debug("[FileReader] Directory read error:",n instanceof Error?n.message:n)}}var k=class{basePath;cache;enableCache;stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:0,cacheEntries:0};constructor(e={}){this.basePath=e.basePath??process.cwd(),this.enableCache=e.enableCache??!0,this.cache=new de(e.maxCacheSize??100,e.cacheTtlMs??300*1e3)}resolvePath(e){let t=R.isAbsolute(e),s=ve(e,{basePath:t?"":this.basePath,allowAbsolute:!0,deniedExtensions:[".exe",".bat",".cmd",".ps1",".dll",".so"]});if(!s.valid)throw new T(e,[s.error||"Path validation failed"],s.riskLevel);if(t&&this.basePath){let n=R.resolve(this.basePath),i=R.resolve(e);if(!i.startsWith(n))throw new T(e,["Path escapes base directory"],"critical");return i}return s.normalizedPath?s.normalizedPath:t?e:R.resolve(this.basePath,e)}async readFile(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}if(this.stats.totalReads++,this.enableCache){let s=this.cache.get(t);if(s!==void 0)return this.stats.cacheHits++,this.updateCacheStats(),P(s);this.stats.cacheMisses++}try{let s=await S.readFile(t,"utf-8");return this.enableCache&&(this.cache.set(t,s,Buffer.byteLength(s,"utf-8")),this.updateCacheStats()),P(s)}catch(s){let n=s,i;switch(n.code){case"ENOENT":i="File not found: "+t;break;case"EACCES":i="Permission denied: "+t;break;case"EISDIR":i="Path is a directory: "+t;break;default:i="Failed to read file: "+t}return L(new F(i,t,n.code,n))}}async readJSON(e){let t=await this.readFile(e);if(!t.success)return t;try{let s=D(t.value);return P(s)}catch(s){let n=s,i=e;try{i=this.resolvePath(e)}catch{}return L(new V("Invalid JSON in file: "+i+" - "+n.message,i,n))}}async fileExists(e){let t;try{t=this.resolvePath(e)}catch(s){if(s instanceof T)return L(s);throw s}try{return await S.access(t,S.constants.F_OK),P(!0)}catch(s){let n=s;return n.code==="ENOENT"?P(!1):L(new F("Cannot check file existence: "+t,t,n.code,n))}}async listFiles(e,t){let s;try{s=t?this.resolvePath(t):this.basePath}catch(n){if(n instanceof T)return L(n);throw n}try{if(!(await S.stat(s)).isDirectory())return L(new F("Base path is not a directory: "+s,s,"ENOTDIR"));let i=Te(e),o=[];return await Ee(s,i,o,s),o.sort(),P(o)}catch(n){let i=n;return L(new F("Failed to list files in: "+s,s,i.code,i))}}invalidateCache(e){let t=this.resolvePath(e);this.cache.delete(t),this.updateCacheStats()}clearCache(){this.cache.clear(),this.updateCacheStats()}pruneCache(){let e=this.cache.prune();return this.updateCacheStats(),e}getStats(){return{...this.stats}}resetStats(){this.stats={cacheHits:0,cacheMisses:0,totalReads:0,cacheSize:this.cache.totalBytes,cacheEntries:this.cache.size}}updateCacheStats(){this.stats.cacheSize=this.cache.totalBytes,this.stats.cacheEntries=this.cache.size}};J();var v={MODEL:"all-MiniLM-L6-v2",DIMENSIONS:384,CONTEXT_WINDOW:8192,BATCH_SIZE:100,MAX_RETRIES:3,RETRY_DELAY_MS:1e3,TIMEOUT_MS:3e4,DEFAULT_OLLAMA_URL:"http://localhost:11434"};var _=class{baseUrl;maxRetries;retryDelayMs;timeoutMs;constructor(e=v.DEFAULT_OLLAMA_URL,t=v.MAX_RETRIES,s=v.RETRY_DELAY_MS,n=v.TIMEOUT_MS){this.baseUrl=e.replace(/\/$/,""),this.maxRetries=t,this.retryDelayMs=s,this.timeoutMs=n}async healthCheck(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);if(!e.ok)return!1;let t=await e.json();return t.models?t.models.some(s=>s.name?.startsWith(v.MODEL)||s.model?.startsWith(v.MODEL)):!1}catch{return!1}}async generateEmbedding(e){let t={model:v.MODEL,prompt:e},s=null;for(let n=0;n<this.maxRetries;n++)try{let i=await this.fetchWithTimeout(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)},this.timeoutMs);if(!i.ok){let r=await i.text();throw new Error(`Ollama API error (${i.status}): ${r}`)}let o=await i.json();if(o.embedding.length!==v.DIMENSIONS)throw new Error(`Invalid embedding dimensions: expected ${v.DIMENSIONS}, got ${o.embedding.length}`);return o.embedding}catch(i){if(s=A(i),s.message.includes("Invalid embedding dimensions"))throw s;if(n<this.maxRetries-1){let o=this.retryDelayMs*Math.pow(2,n);await this.sleep(o)}}throw new Error(`Failed to generate embedding after ${this.maxRetries} attempts: ${s?.message}`)}async fetchWithTimeout(e,t,s){let n=new AbortController,i=setTimeout(()=>n.abort(),s);try{return await fetch(e,{...t,signal:n.signal})}finally{clearTimeout(i)}}sleep(e){return new Promise(t=>setTimeout(t,e))}async getServerInfo(){try{let e=await this.fetchWithTimeout(`${this.baseUrl}/api/tags`,{method:"GET",headers:{"Content-Type":"application/json"}},5e3);return e.ok?await e.json():null}catch{return null}}async ensureModelAvailable(){if(!await this.healthCheck())throw new Error(`Ollama model '${v.MODEL}' is not available. Please run: ollama pull ${v.MODEL}`)}};import{createHash as Fe}from"crypto";var $=class{cache;maxSize;hits;misses;constructor(e=1e4){this.cache=new Map,this.maxSize=e,this.hits=0,this.misses=0}hashContent(e,t){return Fe("sha256").update(`${t}:${e}`).digest("hex")}get(e,t){let s=this.hashContent(e,t),n=this.cache.get(s);return n?(this.hits++,this.cache.delete(s),this.cache.set(s,n),n.embedding):(this.misses++,null)}set(e,t,s){let n=this.hashContent(e,t);if(this.cache.size>=this.maxSize&&!this.cache.has(n)){let o=this.cache.keys().next().value;o&&this.cache.delete(o)}let i={embedding:s,timestamp:Date.now(),model:t};this.cache.set(n,i)}has(e,t){let s=this.hashContent(e,t);return this.cache.has(s)}getStats(){let e=this.hits+this.misses,t=e>0?this.hits/e:0;return{size:this.cache.size,hitRate:t,hits:this.hits,misses:this.misses}}clear(){this.cache.clear(),this.hits=0,this.misses=0}evictOlderThan(e){let s=Date.now()-e,n=0;for(let[i,o]of this.cache.entries())o.timestamp<s&&(this.cache.delete(i),n++);return n}getMemoryUsageEstimate(){return this.cache.size*3172}export(){return Array.from(this.cache.entries()).map(([e,t])=>({key:e,entry:t}))}import(e){this.cache.clear();for(let{key:t,entry:s}of e)this.cache.size<this.maxSize&&this.cache.set(t,s)}};J();var K=class{client;cache;batchSize;enableFallback;ollamaAvailable=null;constructor(e={}){this.client=new _(e.ollamaBaseUrl),this.cache=e.cache??new $(e.maxCacheSize),this.batchSize=e.batchSize??v.BATCH_SIZE,this.enableFallback=e.enableFallback??!0}async embed(e){let t=this.cache.get(e,v.MODEL);if(t)return t;let s;if(await this.isOllamaAvailable())s=await this.client.generateEmbedding(e);else if(this.enableFallback)s=this.generatePseudoEmbedding(e);else throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);return this.cache.set(e,v.MODEL,s),s}formatForEmbedding(e){let t=[];e.language&&t.push(e.language),e.type&&t.push(e.type),e.name&&t.push(e.name);let s=t.length>0?`${t.join(" ")}: `:"",n=v.CONTEXT_WINDOW*4,i=e.content.trim();if(s.length+i.length>n){let o=n-s.length-3;i=i.substring(0,o)+"..."}return s+i}async embedBatch(e){let t=[];for(let s of e){let n=await this.embed(s);t.push(n)}return t}async embedCodeChunks(e,t){let s=Date.now(),n=[],i=0,o=0,r=await this.isOllamaAvailable();if(r)await this.client.ensureModelAvailable();else if(!this.enableFallback)throw new Error(`Ollama is not available and fallback is disabled. Please run: ollama pull ${v.MODEL}`);for(let c=0;c<e.length;c+=this.batchSize){let l=e.slice(c,Math.min(c+this.batchSize,e.length)),d=await this.processBatch(l,r);n.push(...d);for(let p of d)p.cached?i++:o++;if(t){let p=c+l.length,h=e.length,g=(Date.now()-s)/p,y=(h-p)*g;t({current:p,total:h,percentage:p/h*100,estimatedTimeRemainingMs:y})}}let a=Date.now()-s;return{results:n,stats:{totalChunks:e.length,cachedHits:i,computedNew:o,totalTimeMs:a,avgTimePerChunk:a/e.length}}}async processBatch(e,t){let s=[],n=e.map(async o=>{let r=this.formatForEmbedding(o),a=Date.now(),c=this.cache.get(r,v.MODEL);if(c)return{chunkId:o.id,embedding:c,model:v.MODEL,cached:!0,computeTimeMs:Date.now()-a};try{let l;return t?l=await this.client.generateEmbedding(r):l=this.generatePseudoEmbedding(r),this.cache.set(r,v.MODEL,l),{chunkId:o.id,embedding:l,model:t?v.MODEL:"pseudo-embedding",cached:!1,computeTimeMs:Date.now()-a}}catch(l){throw new Error(`Failed to generate embedding for chunk ${o.id}: ${G(l)}`)}}),i=await Promise.all(n);return s.push(...i),s}async isOllamaAvailable(){return this.ollamaAvailable!==null?this.ollamaAvailable:(this.ollamaAvailable=await this.client.healthCheck(),this.ollamaAvailable)}resetOllamaCheck(){this.ollamaAvailable=null}generatePseudoEmbedding(e){let t=new Array(v.DIMENSIONS).fill(0),s=e.split(/\s+|[^\w]+/).filter(o=>o.length>0);for(let o=0;o<s.length;o++){let r=s[o];for(let a=0;a<r.length&&a<t.length;a++)t[(o+a)%t.length]+=r.charCodeAt(a)/1e3}let n=[[/class\s+\w+/,0],[/function\s+\w+/,1],[/async\s+|await\s+|Promise/,2],[/interface\s+\w+/,3],[/export\s+/,4],[/import\s+/,5],[/try\s*{/,6],[/\.(map|filter|reduce)\(/,7]];for(let[o,r]of n)o.test(e)&&(t[r]+=.5);let i=Math.sqrt(t.reduce((o,r)=>o+r*r,0))||1;return t.map(o=>o/i)}clearCache(){this.cache.clear()}getCacheStats(){return this.cache.getStats()}async healthCheck(){return await this.client.healthCheck()}async getServerInfo(){return await this.client.getServerInfo()}getDimensions(){return v.DIMENSIONS}getConfig(){return{model:v.MODEL,dimensions:v.DIMENSIONS,contextWindow:v.CONTEXT_WINDOW,batchSize:this.batchSize,maxRetries:v.MAX_RETRIES,enableFallback:this.enableFallback}}};J();ye();import{existsSync as Oe,statSync as ke}from"fs";import{dirname as _e,resolve as $e,join as q}from"path";function Ae(u){switch(u){case"ts":case"mts":case"cts":return"tree-sitter-typescript.wasm";case"tsx":return"tree-sitter-tsx.wasm";case"js":case"jsx":case"mjs":case"cjs":return"tree-sitter-javascript.wasm";default:return null}}var U=u=>u.startPosition.row+1,j=(u,e)=>u.childForFieldName(e)?.text??"";function ue(u){for(let e=0;e<u.childCount;e++){let t=u.child(e);if(t){if(t.type==="async")return!0;if(t.type==="function"||t.type==="function_declaration")break}}return!1}function Ne(u){for(let e=0;e<u.childCount;e++)if(u.child(e)?.type==="accessibility_modifier"){let s=u.child(e).text;if(s==="private")return"private";if(s==="protected")return"protected"}return"public"}function De(u){let e=j(u,"name")||"(anonymous)",t=u.childForFieldName("body"),s=[];if(t)for(let n=0;n<t.childCount;n++){let i=t.child(n);i&&i.type==="method_definition"&&s.push({name:j(i,"name"),startLine:U(i),isAsync:ue(i),visibility:Ne(i)})}return{name:e,startLine:U(u),methods:s}}function pe(u){return u.replace(/^['"`]|['"`]$/g,"")}async function me(u,e){let t=Ae(e);if(!t)return null;let s=await be(t);if(!s)return null;let n=null;try{let i=s.parse(u);n=i;let o=i.rootNode;if(!o)return null;let r={functions:[],classes:[],interfaces:[],imports:[]},a=[o];for(;a.length;){let c=a.pop(),l=!0;switch(c.type){case"function_declaration":case"generator_function_declaration":r.functions.push({name:j(c,"name"),startLine:U(c),isAsync:ue(c),visibility:"public"}),l=!1;break;case"class_declaration":case"class":r.classes.push(De(c)),l=!1;break;case"interface_declaration":r.interfaces.push({name:j(c,"name"),startLine:U(c)}),l=!1;break;case"lexical_declaration":case"variable_declaration":{for(let d=0;d<c.childCount;d++){let p=c.child(d);if(!p||p.type!=="variable_declarator")continue;let h=p.childForFieldName("value");if(h&&(h.type==="arrow_function"||h.type==="function"||h.type==="function_expression"))r.functions.push({name:j(p,"name"),startLine:U(p),isAsync:ue(h),visibility:"public"});else if(h&&h.type==="call_expression"&&h.child(0)?.text==="require"){let f=h.childForFieldName("arguments")?.child(1);f&&f.type==="string"&&r.imports.push(pe(f.text))}}l=!1;break}case"import_statement":{let d=c.childForFieldName("source");d&&r.imports.push(pe(d.text)),l=!1;break}case"call_expression":{let d=c.child(0);if(d&&d.text==="require"){let h=c.childForFieldName("arguments")?.child(1);h&&h.type==="string"&&r.imports.push(pe(h.text))}break}}if(l)for(let d=c.childCount-1;d>=0;d--){let p=c.child(d);p&&a.push(p)}}return r}catch{return null}finally{n?.delete?.()}}var Ke={maxNodes:1e5,maxEdgesPerNode:500,namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,embeddingDimension:384,enableLLMExtraction:!0,llmModelTier:2,llmMaxTokens:2048},he=fe.create("code-intelligence/knowledge-graph"),H=new Set(["ts","tsx","js","jsx"]),Ie=class{config;memory;nodeCache=new Map;edgeIndex=new Map;allEdgesCache;tsParser;fileReader;embedder;llmRouter;constructor(e,t={}){this.config={...Ke,...t},this.isKnowledgeGraphDependencies(e)?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0),this.tsParser=new N,this.fileReader=new k,this.embedder=new K({enableFallback:!0})}isKnowledgeGraphDependencies(e){return e.memory!==void 0}get nsOpts(){return{namespace:this.config.namespace}}async index(e){let t=Date.now(),s=[],n=0,i=0,o=new Map;try{let{paths:r,incremental:a=!1,includeTests:c=!0,languages:l}=e;a||await this.clear();for(let h of r)try{if(l&&l.length>0){let b=this.getFileExtension(h);if(!this.matchesLanguage(b,l))continue}if(!c&&this.isTestFile(h))continue;let f=this.getFileExtension(h);H.has(f)||o.set(f||"(none)",(o.get(f||"(none)")??0)+1);let g=await this.indexFile(h,a);n+=g.nodes,i+=g.edges}catch(f){s.push({file:h,error:G(f)})}let d=Date.now()-t,p=[];if(o.size>0){let h=Array.from(H).join(", ");for(let[f,g]of o){let b=`${g} file(s) with extension '.${f}' were indexed as plain nodes: no dependency extractor for this language, so 'deps'/'impact' will report 0 edges for them. Supported: ${h}.`;p.push(b),he.warn(b)}}return await this.storeIndexMetadata({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,indexedAt:new Date().toISOString()}),P({filesIndexed:r.length-s.length,nodesCreated:n,edgesCreated:i,duration:d,errors:s,warnings:p})}catch(r){return L(A(r))}}async query(e){try{let{query:t,type:s,limit:n=100}=e;return s==="cypher"?this.executeCypherQuery(t,n):this.executeNaturalLanguageQuery(t,n)}catch(t){return L(A(t))}}async mapDependencies(e){try{let{files:t,direction:s,depth:n=3}=e,i=[],o=[],r=new Set,a=[];for(let l of t)await this.traverseDependencies(l,s,n,r,i,o,[],a);let c=this.calculateDependencyMetrics(i,o);return P({nodes:i,edges:o,cycles:a,metrics:c})}catch(t){return L(A(t))}}async getNode(e){if(this.nodeCache.has(e))return this.nodeCache.get(e);let t=`${this.config.namespace}:node:${e}`,s=await this.memory.get(t,this.nsOpts);return s&&this.nodeCache.set(e,s),s}async getEdges(e,t){let s=await this.loadAllEdges();return this.filterEdgesByDirection(s,e,t)}async loadAllEdges(){if(this.allEdgesCache)return this.allEdgesCache;let e=[],t=`${this.config.namespace}:edge:*`,s=await this.memory.search(t,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let n of s){let i=await this.memory.get(n,this.nsOpts);i&&e.push(i)}return this.allEdgesCache=e,e}async clear(){this.nodeCache.clear(),this.edgeIndex.clear(),this.allEdgesCache=void 0;for(let e of[`${this.config.namespace}:node:`,`${this.config.namespace}:edge:`]){let t=await this.memory.search(`${e}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let s of t)await this.memory.delete(s,this.nsOpts)}}async removeFileFromGraph(e){let t=this.pathToNodeId(e),s=this.config.namespace,n=await this.memory.search(`${s}:node:${t}*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of n)await this.memory.delete(o,this.nsOpts),this.nodeCache.delete(o.slice(`${s}:node:`.length));let i=await this.memory.search(`${s}:edge:*`,Number.MAX_SAFE_INTEGER,this.nsOpts);for(let o of i){let r=await this.memory.get(o,this.nsOpts);r&&(r.source===t||r.source.startsWith(`${t}:`))&&await this.memory.delete(o,this.nsOpts)}this.edgeIndex.delete(t),this.allEdgesCache=void 0}isLLMExtractionAvailable(){return this.config.enableLLMExtraction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async extractRelationshipsWithLLM(e,t){if(!this.llmRouter)return{semanticRelationships:[],designPatterns:[],architecturalBoundaries:[],dependencyImpacts:[]};try{let s=this.buildRelationshipExtractionPrompt(e,t),n=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software architect analyzing code structure. Extract:
24
24
  1. Semantic relationships between code entities (inheritance, composition, dependency, collaboration)
25
25
  2. Design patterns used (Factory, Singleton, Observer, Strategy, etc.)
26
26
  3. Architectural boundaries (layers, modules, domains)
@@ -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.10.4");process.exit(0)}
2
+ import{c as f}from"./chunk-SVILIQQQ.js";import*as o from"fs";import*as n from"path";function u(){t=null}function g(c=process.cwd()){if(t)return t;if(process.env.AQE_PROJECT_ROOT)return t=process.env.AQE_PROJECT_ROOT,t;let l=c,a=n.parse(l).root,e=l,i=null,s=null,r=null;for(;e!==a;)o.existsSync(n.join(e,".agentic-qe"))&&i===null&&(i=e),o.existsSync(n.join(e,".git"))&&s===null&&(s=e),o.existsSync(n.join(e,"package.json"))&&(r=e),e=n.dirname(e);return i?t=i:s?t=s:r?t=r:t=process.cwd(),t}var t,p=f(()=>{"use strict";t=null});export{u as a,g as b,p 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.10.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.10.4");process.exit(0)}
2
2
  var n=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","requirements-validation","code-intelligence","security-compliance","contract-testing","visual-accessibility","chaos-resilience","learning-optimization","enterprise-integration","coordination"];function t(e){return{success:!0,value:e}}function r(e){return{success:!1,error:e}}export{n as a,t as b,r 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.10.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.10.4");process.exit(0)}
2
2
  var l=["var-to-const","add-types","remove-console","promise-to-async","cjs-to-esm","func-to-arrow"],p={"var-to-const":{type:"var-to-const",name:"Var to Const/Let",description:"Convert var declarations to const (if not reassigned) or let (if reassigned)",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"add-types":{type:"add-types",name:"Add TypeScript Types",description:"Add TypeScript type annotations to function parameters and return types",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"remove-console":{type:"remove-console",name:"Remove Console Statements",description:"Remove all console.log, console.warn, console.error, etc. statements",complexity:"simple",wasmAvailable:!0,typicalLatencyMs:1},"promise-to-async":{type:"promise-to-async",name:"Promise to Async/Await",description:"Convert Promise .then()/.catch() chains to async/await syntax",complexity:"complex",wasmAvailable:!0,typicalLatencyMs:10},"cjs-to-esm":{type:"cjs-to-esm",name:"CommonJS to ES Modules",description:"Convert require() calls to import statements and module.exports to export",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:5},"func-to-arrow":{type:"func-to-arrow",name:"Function to Arrow",description:"Convert function declarations and expressions to arrow functions",complexity:"moderate",wasmAvailable:!0,typicalLatencyMs:3}},u={enabled:!0,fallbackToLLM:!0,confidenceThreshold:.7,transforms:[],maxFileSizeBytes:1024*1024,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},t=class extends Error{constructor(e,s,o){super(e);this.code=s;this.cause=o;this.name="AgentBoosterError"}code;cause},a=class extends t{constructor(e,s,o){super(e,"TRANSFORM_ERROR",o);this.transformType=s;this.name="TransformError"}transformType},i=class extends t{constructor(r="WASM module is not available",e){super(r,"WASM_UNAVAILABLE",e),this.name="WasmUnavailableError"}},c=class extends t{constructor(e,s,o){super(e,"TRANSFORM_TIMEOUT");this.transformType=s;this.timeoutMs=o;this.name="TransformTimeoutError"}transformType;timeoutMs},m=class extends t{constructor(e,s,o){super(`File ${e} is too large (${s} bytes, max ${o} bytes)`,"FILE_TOO_LARGE");this.filePath=e;this.sizeBytes=s;this.maxSizeBytes=o;this.name="FileTooLargeError"}filePath;sizeBytes;maxSizeBytes};export{l as a,p as b,u as c,a as d,i as e,c as f,m as g};
@@ -1,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.10.3");process.exit(0)}
2
- import{a as v}from"./chunk-3VF3HCG4.js";import{c as l}from"./chunk-2L73WXA4.js";import{S as R,b as g}from"./chunk-YIYV2JB6.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.10.4");process.exit(0)}
2
+ import{a as v}from"./chunk-HPYGMKZF.js";import{c as l}from"./chunk-VRE2EBFI.js";import{S as R,b as g}from"./chunk-D7IWGQTW.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,