agentic-qe 3.10.2 → 3.10.3

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 (387) hide show
  1. package/.claude/skills/release/SKILL.md +10 -10
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +55 -0
  4. package/assets/grammars/tree-sitter-c_sharp.wasm +0 -0
  5. package/assets/grammars/tree-sitter-java.wasm +0 -0
  6. package/assets/grammars/tree-sitter-javascript.wasm +0 -0
  7. package/assets/grammars/tree-sitter-python.wasm +0 -0
  8. package/assets/grammars/tree-sitter-rust.wasm +0 -0
  9. package/assets/grammars/tree-sitter-swift.wasm +0 -0
  10. package/assets/grammars/tree-sitter-tsx.wasm +0 -0
  11. package/assets/grammars/tree-sitter-typescript.wasm +0 -0
  12. package/assets/skills/skills-manifest.json +1 -1
  13. package/dist/agents/claim-verifier/claim-verifier-service.js +4 -2
  14. package/dist/agents/claim-verifier/verifiers/test-verifier.js +31 -23
  15. package/dist/agents/devils-advocate/agent.js +1 -1
  16. package/dist/cli/bundle.js +5 -5
  17. package/dist/cli/chunks/adapter-BHPUKMJ5.js +2 -0
  18. package/dist/cli/chunks/{agent-booster-wasm-DHSIPFTH.js → agent-booster-wasm-NGC6LSQP.js} +2 -2
  19. package/dist/cli/chunks/{agent-handler-FPQVHGGT.js → agent-handler-P2IJE4GK.js} +2 -2
  20. package/dist/cli/chunks/{agent-memory-branch-OLOF5ZHV.js → agent-memory-branch-JXRJ5GKQ.js} +2 -2
  21. package/dist/cli/chunks/aqe-learning-engine-JQ5WD2HM.js +2 -0
  22. package/dist/cli/chunks/{audit-ALRYPHGP.js → audit-BMQ3VESB.js} +2 -2
  23. package/dist/cli/chunks/base-E32WLGY2.js +2 -0
  24. package/dist/cli/chunks/{hnswlib-node-ZGSUMHDC.js → better-sqlite3-HP4JZS6K.js} +2 -2
  25. package/dist/cli/chunks/{brain-handler-ROZUHCOT.js → brain-handler-SACNDFSW.js} +3 -3
  26. package/dist/cli/chunks/{branch-enumerator-VK7G4NKJ.js → branch-enumerator-LFOTVUDA.js} +2 -2
  27. package/dist/cli/chunks/{browser-Q2S75M2F.js → browser-FK7PRF3W.js} +2 -2
  28. package/dist/cli/chunks/browser-workflow-LNNXXAJG.js +2 -0
  29. package/dist/cli/chunks/{chunk-UWXH2UQK.js → chunk-2EQVYYBF.js} +2 -2
  30. package/dist/cli/chunks/{chunk-JF53LRBL.js → chunk-2L73WXA4.js} +2 -2
  31. package/dist/cli/chunks/{chunk-5HB54RUS.js → chunk-2ULVCLOW.js} +2 -2
  32. package/dist/cli/chunks/{chunk-UUFOHMUG.js → chunk-3HBWDG62.js} +2 -2
  33. package/dist/cli/chunks/{chunk-22D6VBPD.js → chunk-3JAOFKEU.js} +2 -2
  34. package/dist/cli/chunks/{chunk-XPCNUX2U.js → chunk-3LRK7PYN.js} +2 -2
  35. package/dist/cli/chunks/{chunk-WNR2KAUH.js → chunk-3RZL4QTT.js} +2 -2
  36. package/dist/cli/chunks/chunk-3VF3HCG4.js +2 -0
  37. package/dist/cli/chunks/{chunk-3Z4FHA2E.js → chunk-3X2ZQ55B.js} +4 -4
  38. package/dist/cli/chunks/{chunk-YACT5WFC.js → chunk-4CYLSXA6.js} +2 -2
  39. package/dist/cli/chunks/{chunk-7QRMARM7.js → chunk-4OUAHZX2.js} +2 -2
  40. package/dist/cli/chunks/{chunk-G5U6Q42D.js → chunk-4QFAUSWQ.js} +2 -2
  41. package/dist/cli/chunks/{chunk-SJH3HYNC.js → chunk-5ER3COX3.js} +2 -2
  42. package/dist/cli/chunks/{chunk-LZCBSFAU.js → chunk-5EWWA4QP.js} +4 -4
  43. package/dist/cli/chunks/{chunk-VSUTI4G6.js → chunk-5G5AAEFF.js} +2 -2
  44. package/dist/cli/chunks/{chunk-7V5UHLNY.js → chunk-5IBJURYB.js} +3 -3
  45. package/dist/cli/chunks/chunk-5LON3MLI.js +2 -0
  46. package/dist/cli/chunks/{chunk-3RHHKYUR.js → chunk-5SGEOO2F.js} +2 -2
  47. package/dist/cli/chunks/{chunk-6NZHEM4V.js → chunk-6B4S7PKP.js} +3 -3
  48. package/dist/cli/chunks/{chunk-MEY43PIQ.js → chunk-6FL3GN4T.js} +2 -2
  49. package/dist/cli/chunks/{chunk-Y63MBMOV.js → chunk-6GCOIIHY.js} +2 -2
  50. package/dist/cli/chunks/{chunk-EQBEGDTG.js → chunk-6Q2PPOOF.js} +1 -1
  51. package/dist/cli/chunks/{chunk-PXTDEO65.js → chunk-6ZK24V2Y.js} +2 -2
  52. package/dist/cli/chunks/{chunk-7Z46RDDV.js → chunk-72LE6PHL.js} +3 -3
  53. package/dist/cli/chunks/{chunk-SVYTN2GT.js → chunk-7RMZAVGO.js} +2 -2
  54. package/dist/cli/chunks/{chunk-S3OZ7XSY.js → chunk-7SEHQTYD.js} +1 -1
  55. package/dist/cli/chunks/{chunk-UYYBPWU3.js → chunk-7YYTTWGY.js} +1 -1
  56. package/dist/cli/chunks/{chunk-DRWGK3YO.js → chunk-7ZSPCGTI.js} +2 -2
  57. package/dist/cli/chunks/{chunk-UVU7XLJY.js → chunk-ADV4DH3W.js} +5 -5
  58. package/dist/cli/chunks/{chunk-FO43SQXP.js → chunk-AEJVOJPT.js} +2 -2
  59. package/dist/cli/chunks/{chunk-ETN5563K.js → chunk-B5MMDMH6.js} +2 -2
  60. package/dist/cli/chunks/{chunk-ZXTO4C7R.js → chunk-BO2OV2RH.js} +2 -2
  61. package/dist/cli/chunks/{chunk-TJKDATEU.js → chunk-BT3QLWII.js} +2 -2
  62. package/dist/cli/chunks/{chunk-AV7KYE5P.js → chunk-BWP3UVPE.js} +5 -5
  63. package/dist/cli/chunks/{chunk-PEK6NGVJ.js → chunk-C6BBRM2J.js} +1 -1
  64. package/dist/cli/chunks/{chunk-ORF2UKQH.js → chunk-CAMEFWRK.js} +1 -1
  65. package/dist/cli/chunks/{chunk-EVCOCGVJ.js → chunk-CNEWYJKT.js} +4 -4
  66. package/dist/cli/chunks/{chunk-MYWQTCS4.js → chunk-CTDO2UB2.js} +1 -1
  67. package/dist/cli/chunks/{chunk-2OH3ALYB.js → chunk-D2FBUOAR.js} +1 -1
  68. package/dist/cli/chunks/{chunk-ZDHMZPSL.js → chunk-DF3MJ2YL.js} +1 -1
  69. package/dist/cli/chunks/{chunk-7SJX4CFK.js → chunk-DY5KEOHX.js} +1 -1
  70. package/dist/cli/chunks/{chunk-DZZEHPSJ.js → chunk-E2BJT6A7.js} +3 -3
  71. package/dist/cli/chunks/{chunk-2244IFZA.js → chunk-EETVN2OJ.js} +1 -1
  72. package/dist/cli/chunks/{chunk-FY3CUPNN.js → chunk-ERYMAYJW.js} +2 -2
  73. package/dist/cli/chunks/{chunk-ZK2BH23O.js → chunk-FJGSEPFL.js} +2 -2
  74. package/dist/cli/chunks/{chunk-HJORBNXW.js → chunk-FLTPHVZ3.js} +1 -1
  75. package/dist/cli/chunks/{chunk-RLXTBL3H.js → chunk-FND6V2RV.js} +22 -22
  76. package/dist/cli/chunks/{chunk-PIZYRPMT.js → chunk-FU77CDEM.js} +2 -2
  77. package/dist/cli/chunks/{chunk-HA63NBFK.js → chunk-GELF4ILR.js} +37 -37
  78. package/dist/cli/chunks/{chunk-U3EUH6LX.js → chunk-GHNNJHH3.js} +2 -2
  79. package/dist/cli/chunks/{chunk-NZO4WUSO.js → chunk-GJUGSH7T.js} +3 -3
  80. package/dist/cli/chunks/{chunk-QJ2EHLJ2.js → chunk-GL3HZN3O.js} +1 -1
  81. package/dist/cli/chunks/{chunk-MMIQ5DMA.js → chunk-H56AROF2.js} +2 -2
  82. package/dist/cli/chunks/{chunk-AWFIEGR3.js → chunk-HAO3SPOE.js} +2 -2
  83. package/dist/cli/chunks/{chunk-MNUTRAUV.js → chunk-HM523MTQ.js} +1 -1
  84. package/dist/cli/chunks/{chunk-IICTTDAA.js → chunk-HMFEPKAR.js} +2 -2
  85. package/dist/cli/chunks/{chunk-4GTDW2XL.js → chunk-HQJMCTWN.js} +2 -2
  86. package/dist/cli/chunks/{chunk-5PL7WTCU.js → chunk-HRLXU4LH.js} +2 -2
  87. package/dist/cli/chunks/{chunk-5WJ3FWL4.js → chunk-HWM2XJ3P.js} +24 -24
  88. package/dist/cli/chunks/{chunk-BQCSCAUC.js → chunk-I42R57ON.js} +2 -2
  89. package/dist/cli/chunks/chunk-IL2KOW5W.js +2 -0
  90. package/dist/cli/chunks/{chunk-QSE67XJO.js → chunk-IRR7YA3Q.js} +2 -2
  91. package/dist/cli/chunks/{chunk-FPAW77XV.js → chunk-JD2PG4KS.js} +1 -1
  92. package/dist/cli/chunks/{chunk-LQTWPSYL.js → chunk-JE3C7JYN.js} +1 -1
  93. package/dist/cli/chunks/{chunk-6KSCXPPL.js → chunk-JLL27IGU.js} +2 -2
  94. package/dist/cli/chunks/{chunk-7DKYCVJI.js → chunk-JOLDCS6X.js} +2 -2
  95. package/dist/cli/chunks/{chunk-YNNOY3XN.js → chunk-JP63XACW.js} +2 -2
  96. package/dist/cli/chunks/{chunk-ZQUXNG5X.js → chunk-JSFYPLMQ.js} +2 -2
  97. package/dist/cli/chunks/{chunk-MNV3E5KY.js → chunk-JTF6D2RJ.js} +4 -4
  98. package/dist/cli/chunks/{chunk-OXCEUR5F.js → chunk-JTZ3Q2QS.js} +2 -2
  99. package/dist/cli/chunks/{chunk-OPFN5LFT.js → chunk-JXIPRMAY.js} +4 -4
  100. package/dist/cli/chunks/{chunk-XDU624HU.js → chunk-KG5SM36Y.js} +1 -1
  101. package/dist/cli/chunks/{chunk-SW4OKUTC.js → chunk-KTRB3L53.js} +2 -2
  102. package/dist/cli/chunks/{chunk-MCZHKXB4.js → chunk-L74CHKFR.js} +2 -2
  103. package/dist/cli/chunks/{chunk-2EDWGHDA.js → chunk-LZ6TNTGO.js} +2 -2
  104. package/dist/cli/chunks/{chunk-5PRFFHFV.js → chunk-M5CDW2ZH.js} +2 -2
  105. package/dist/cli/chunks/{chunk-PYIHZXCI.js → chunk-MBSJ5G4I.js} +4 -4
  106. package/dist/cli/chunks/{chunk-OIRZJCZY.js → chunk-MC7K44M4.js} +2 -2
  107. package/dist/cli/chunks/{chunk-2JDLQWSV.js → chunk-MQOFFRTA.js} +2 -2
  108. package/dist/cli/chunks/{chunk-4BXGVM2C.js → chunk-N7IBYDW5.js} +1 -1
  109. package/dist/cli/chunks/{chunk-MCOFJHSJ.js → chunk-NEYYLAYS.js} +5 -5
  110. package/dist/cli/chunks/{chunk-A5RMQG4N.js → chunk-NNVXHC74.js} +3 -3
  111. package/dist/cli/chunks/{chunk-QBRHKTFT.js → chunk-NNZMEYLT.js} +1 -1
  112. package/dist/cli/chunks/{chunk-WDMPJ2M2.js → chunk-NRCL3WCP.js} +2 -2
  113. package/dist/cli/chunks/{chunk-ZGNZJJFF.js → chunk-NXPFGPHV.js} +1 -1
  114. package/dist/cli/chunks/{chunk-AH7FXNFE.js → chunk-NZHOKLII.js} +3 -3
  115. package/dist/cli/chunks/{chunk-EA7ZSN3V.js → chunk-OG7CWWFR.js} +1 -1
  116. package/dist/cli/chunks/{chunk-YWZHMXTO.js → chunk-OPDTDKN3.js} +2 -2
  117. package/dist/cli/chunks/{chunk-24LUQICS.js → chunk-OX4R55T3.js} +2 -2
  118. package/dist/cli/chunks/{chunk-QEPFXY6G.js → chunk-PFCAMX6H.js} +1 -1
  119. package/dist/cli/chunks/{chunk-DMQPO43S.js → chunk-PL5SLO2W.js} +1 -1
  120. package/dist/cli/chunks/{chunk-XGBAHAGC.js → chunk-PZHZPX3O.js} +4 -4
  121. package/dist/cli/chunks/{chunk-HJME6G5M.js → chunk-Q7EBD24B.js} +1 -1
  122. package/dist/cli/chunks/{chunk-4F3ZTXHP.js → chunk-QEODION5.js} +2 -2
  123. package/dist/cli/chunks/{chunk-AIUSZC6K.js → chunk-QM65UGPV.js} +2 -2
  124. package/dist/cli/chunks/{chunk-HHCYSAH3.js → chunk-QWG76RHA.js} +2 -2
  125. package/dist/cli/chunks/{chunk-5QHSLWLP.js → chunk-R5ONQAQL.js} +2 -2
  126. package/dist/cli/chunks/{chunk-S3ZO7JXS.js → chunk-RNF47IJ5.js} +4 -4
  127. package/dist/cli/chunks/{chunk-AOI67HA3.js → chunk-RTDHWOAG.js} +1 -1
  128. package/dist/cli/chunks/{chunk-C2M74HCN.js → chunk-RZCAA2PZ.js} +1 -1
  129. package/dist/cli/chunks/{chunk-7IVQ6OVR.js → chunk-SL6YZAT4.js} +2 -2
  130. package/dist/cli/chunks/{chunk-KB5L5TTF.js → chunk-SNTMAVPH.js} +5 -5
  131. package/dist/cli/chunks/{chunk-XTCUN36Z.js → chunk-SWOG3PBD.js} +2 -2
  132. package/dist/cli/chunks/{chunk-7IZ2OPC2.js → chunk-T63EK6GH.js} +2 -2
  133. package/dist/cli/chunks/chunk-U6UK3UMX.js +59 -0
  134. package/dist/cli/chunks/{chunk-7SWD3D6Y.js → chunk-U7NMPZE2.js} +2 -2
  135. package/dist/cli/chunks/{chunk-THRTUW4Z.js → chunk-UDV4YB42.js} +1 -1
  136. package/dist/cli/chunks/{chunk-CV2SBMBW.js → chunk-UHDBM7QS.js} +2 -2
  137. package/dist/cli/chunks/{chunk-CIRPP7RQ.js → chunk-UIJFU4KD.js} +2 -2
  138. package/dist/cli/chunks/{chunk-L7VIX22Y.js → chunk-USFZ4IJD.js} +2 -2
  139. package/dist/cli/chunks/{chunk-CMACGG4Z.js → chunk-UZL366ZI.js} +1 -1
  140. package/dist/cli/chunks/{chunk-QQNCSEZG.js → chunk-VDTFRMES.js} +2 -2
  141. package/dist/cli/chunks/{chunk-6ZFHIKQG.js → chunk-VIWIO27R.js} +3 -3
  142. package/dist/cli/chunks/{chunk-YI6GNRQM.js → chunk-VRXY4T22.js} +2 -2
  143. package/dist/cli/chunks/{chunk-WSVUSIAZ.js → chunk-WPVCSFDA.js} +2 -2
  144. package/dist/cli/chunks/{chunk-X2VAOIUY.js → chunk-WWD5IWTV.js} +1 -1
  145. package/dist/cli/chunks/{chunk-WZJUMJ2S.js → chunk-X2B7SANM.js} +1 -1
  146. package/dist/cli/chunks/{chunk-R2O6OKT2.js → chunk-X3RJ6SFC.js} +1 -1
  147. package/dist/cli/chunks/{chunk-OWQ6HEYI.js → chunk-XTP2GHI7.js} +2 -2
  148. package/dist/cli/chunks/{chunk-XRJECWZE.js → chunk-YDDZJCKY.js} +1 -1
  149. package/dist/cli/chunks/{chunk-HO37VP4O.js → chunk-YDKYLNKZ.js} +1 -1
  150. package/dist/cli/chunks/{chunk-ON4D4TJ4.js → chunk-YIYV2JB6.js} +2 -2
  151. package/dist/cli/chunks/{chunk-RNREAOY4.js → chunk-YX2HY4MX.js} +2 -2
  152. package/dist/cli/chunks/{chunk-XDSA7YUQ.js → chunk-YXH2CVAF.js} +1 -1
  153. package/dist/cli/chunks/{chunk-XMJTTF5N.js → chunk-YYAPO3CU.js} +3 -3
  154. package/dist/cli/chunks/{chunk-STEGWLH5.js → chunk-Z2K5IZM6.js} +2 -2
  155. package/dist/cli/chunks/{chunk-OIEQF7PG.js → chunk-ZG4P3DTL.js} +2 -2
  156. package/dist/cli/chunks/{chunk-CTDLI2ON.js → chunk-ZXQNE4QV.js} +1 -1
  157. package/dist/cli/chunks/{ci-PYCRCL7G.js → ci-AWZ3S5OT.js} +6 -6
  158. package/dist/cli/chunks/{ci-output-EKQQFE2D.js → ci-output-JLCYTIMT.js} +2 -2
  159. package/dist/cli/chunks/{circuit-breaker-RH3Q2MJO.js → circuit-breaker-BJDKBDIL.js} +2 -2
  160. package/dist/cli/chunks/{claude-flow-setup-DUDXB4VV.js → claude-flow-setup-KKOP5ZMO.js} +2 -2
  161. package/dist/cli/chunks/client-2UKBYFX4.js +2 -0
  162. package/dist/cli/chunks/{cline-installer-3Q4WIWUG.js → cline-installer-7M525SEA.js} +2 -2
  163. package/dist/cli/chunks/{code-E4Q6DGOO.js → code-27SUVJDO.js} +20 -19
  164. package/dist/cli/chunks/{code-index-extractor-2PCISUOW.js → code-index-extractor-TTQQZLAK.js} +2 -2
  165. package/dist/cli/chunks/{codex-installer-YNNNOLJ6.js → codex-installer-GHNGNPKP.js} +2 -2
  166. package/dist/cli/chunks/{completions-2F7TUFBD.js → completions-JPJD24DG.js} +2 -2
  167. package/dist/cli/chunks/{complexity-analyzer-2B6MHO7W.js → complexity-analyzer-Q74EJV33.js} +2 -2
  168. package/dist/cli/chunks/{continuedev-installer-ENOKRU5M.js → continuedev-installer-ULTRDIML.js} +2 -2
  169. package/dist/cli/chunks/{copilot-installer-6YD2KM5F.js → copilot-installer-EK52X4CG.js} +2 -2
  170. package/dist/cli/chunks/{cost-tracker-FCH4QOEA.js → cost-tracker-2GKBRYXL.js} +2 -2
  171. package/dist/cli/chunks/{coverage-JTOXZE3T.js → coverage-YCLC3W2A.js} +3 -3
  172. package/dist/cli/chunks/cross-domain-router-FPM3L27L.js +2 -0
  173. package/dist/cli/chunks/{cursor-installer-QZFBUGLQ.js → cursor-installer-B3ALFW5E.js} +2 -2
  174. package/dist/cli/chunks/{daemon-M422U3ZA.js → daemon-YWINEHG4.js} +4 -4
  175. package/dist/cli/chunks/{daemon-K4QFB5FQ.js → daemon-ZKEBVLJA.js} +3 -3
  176. package/dist/cli/chunks/{dag-attention-scheduler-BXAAW33V.js → dag-attention-scheduler-OQPJ6ULA.js} +2 -2
  177. package/dist/cli/chunks/{detect-UGSWIOAD.js → detect-YMYIQH3Q.js} +2 -2
  178. package/dist/cli/chunks/{dist-node-FN3HX3OK.js → dist-node-R4FAYQRY.js} +2 -2
  179. package/dist/cli/chunks/{domain-handler-7PP7VYA7.js → domain-handler-IGWXLF2S.js} +2 -2
  180. package/dist/cli/chunks/{domain-transfer-XZM44W7I.js → domain-transfer-A7YNO76C.js} +2 -2
  181. package/dist/cli/chunks/dream-XM33US3V.js +2 -0
  182. package/dist/cli/chunks/{embed-and-insert-pattern-JZVERJ5L.js → embed-and-insert-pattern-KODZAS7Y.js} +2 -2
  183. package/dist/cli/chunks/{eval-466NFF2D.js → eval-ALQW7Q2S.js} +3 -3
  184. package/dist/cli/chunks/{experience-capture-middleware-I7IQCC7V.js → experience-capture-middleware-3WK4RXWK.js} +3 -3
  185. package/dist/cli/chunks/{fast-paths-34OICNZA.js → fast-paths-PQWDFIJZ.js} +2 -2
  186. package/dist/cli/chunks/{feature-flags-X5WBBWSO.js → feature-flags-6X33B3WX.js} +2 -2
  187. package/dist/cli/chunks/{feature-flags-6UBIVTAD.js → feature-flags-JRUAZCND.js} +2 -2
  188. package/dist/cli/chunks/{file-discovery-NLMDBWXX.js → file-discovery-SA3YU3IH.js} +2 -2
  189. package/dist/cli/chunks/{fleet-W7CYCHDI.js → fleet-7TXCAOKQ.js} +3 -3
  190. package/dist/cli/chunks/{gnn-wrapper-K4VTAG5X.js → gnn-wrapper-ZKNYACEC.js} +2 -2
  191. package/dist/cli/chunks/{heartbeat-handler-ZGKF2Z6T.js → heartbeat-handler-KRZRZ23F.js} +4 -4
  192. package/dist/cli/chunks/heartbeat-scheduler-GM3M2MTG.js +2 -0
  193. package/dist/cli/chunks/hnsw-adapter-K62GEHIL.js +2 -0
  194. package/dist/cli/chunks/hnsw-index-VCAK3TWN.js +2 -0
  195. package/dist/cli/chunks/{hnsw-legacy-bridge-ELDRLKK5.js → hnsw-legacy-bridge-LVHQ5SG7.js} +2 -2
  196. package/dist/cli/chunks/{better-sqlite3-5BT5FO64.js → hnswlib-node-64EGGWIC.js} +2 -2
  197. package/dist/cli/chunks/{hooks-T4CBINAV.js → hooks-6Y3UHYI2.js} +12 -12
  198. package/dist/cli/chunks/hybrid-router-432QNCNG.js +2 -0
  199. package/dist/cli/chunks/{hypergraph-engine-UWFW3XP5.js → hypergraph-engine-2EZBZMFK.js} +2 -2
  200. package/dist/cli/chunks/{hypergraph-handler-PK2BI46K.js → hypergraph-handler-GLPWYII2.js} +3 -3
  201. package/dist/cli/chunks/impact-analyzer-VTSISNN4.js +2 -0
  202. package/dist/cli/chunks/{init-handler-HNG6KJOU.js → init-handler-ZSDO5VMA.js} +6 -6
  203. package/dist/cli/chunks/init-wizard-COB5AH7Q.js +2 -0
  204. package/dist/cli/chunks/kernel-ROK7X5FM.js +2 -0
  205. package/dist/cli/chunks/{kilocode-installer-25V7FEJ4.js → kilocode-installer-ATYSDWIV.js} +2 -2
  206. package/dist/cli/chunks/{kiro-installer-7RMTTCQB.js → kiro-installer-K66YT6PC.js} +2 -2
  207. package/dist/cli/chunks/knowledge-graph-YUWIDIWW.js +2 -0
  208. package/dist/cli/chunks/{learning-XQC2MG2R.js → learning-BVYCC4RI.js} +3 -3
  209. package/dist/cli/chunks/{llm-router-6KTTONH4.js → llm-router-VBCXE6DN.js} +12 -12
  210. package/dist/cli/chunks/llm-router-service-7VLXJ7VE.js +2 -0
  211. package/dist/cli/chunks/{load-BV64P3AL.js → load-AREDQE2U.js} +2 -2
  212. package/dist/cli/chunks/load-test-32524DL3.js +2 -0
  213. package/dist/cli/chunks/{mcp-U5ZN77TA.js → mcp-NG6H6UC5.js} +2 -2
  214. package/dist/cli/chunks/{memory-WB5BNBK7.js → memory-Y65EHG6N.js} +5 -5
  215. package/dist/cli/chunks/memory-backend-BI2V5AAB.js +2 -0
  216. package/dist/cli/chunks/memory-handlers-NSOFWVFN.js +2 -0
  217. package/dist/cli/chunks/{multi-model-executor-3X3W3UTY.js → multi-model-executor-VRPRFUZT.js} +2 -2
  218. package/dist/cli/chunks/{opencode-installer-TTTMG7ZZ.js → opencode-installer-CKQXPM5R.js} +3 -3
  219. package/dist/cli/chunks/{orchestrator-BLCGSHMZ.js → orchestrator-I7JBKD6G.js} +8 -8
  220. package/dist/cli/chunks/{pipeline-DZPGMRG7.js → pipeline-MV2RWCBI.js} +2 -2
  221. package/dist/cli/chunks/{platform-EVMZAUNV.js → platform-VU5P3SOG.js} +2 -2
  222. package/dist/cli/chunks/{plugin-OR55K4HT.js → plugin-6TERLKCB.js} +2 -2
  223. package/dist/cli/chunks/{prime-radiant-advanced-wasm-4ODV27HD.js → prime-radiant-advanced-wasm-WIUIN2DL.js} +2 -2
  224. package/dist/cli/chunks/protocol-executor-2UPB7SPI.js +2 -0
  225. package/dist/cli/chunks/{protocol-handler-ZOTI5PID.js → protocol-handler-HKWBGARO.js} +2 -2
  226. package/dist/cli/chunks/{prove-DIMBYJ7V.js → prove-7CQPHBRJ.js} +2 -2
  227. package/dist/cli/chunks/provider-manager-PDT37MIJ.js +2 -0
  228. package/dist/cli/chunks/qe-reasoning-bank-AQQ2BI4V.js +2 -0
  229. package/dist/cli/chunks/{quality-7MX4VL6M.js → quality-VLUVXKVG.js} +2 -2
  230. package/dist/cli/chunks/queen-coordinator-6DVDVEU4.js +2 -0
  231. package/dist/cli/chunks/{real-embeddings-YPUHWRN2.js → real-embeddings-JPZ64KK2.js} +2 -2
  232. package/dist/cli/chunks/{roocode-installer-WG5AU4QM.js → roocode-installer-NONVB3UE.js} +2 -2
  233. package/dist/cli/chunks/router-O2G4KQ6L.js +2 -0
  234. package/dist/cli/chunks/routing-feedback-TAGTD3KQ.js +2 -0
  235. package/dist/cli/chunks/{routing-handler-LZB4MN2K.js → routing-handler-YYXDT4J2.js} +2 -2
  236. package/dist/cli/chunks/{ruvector-commands-YE4ADBMC.js → ruvector-commands-5PFMNDLR.js} +2 -2
  237. package/dist/cli/chunks/{rvf-dual-writer-QS5ATW4C.js → rvf-dual-writer-TF6H7AXH.js} +2 -2
  238. package/dist/cli/chunks/{rvf-migration-adapter-YIGKSBD3.js → rvf-migration-adapter-VNGIUZCO.js} +2 -2
  239. package/dist/cli/chunks/{rvf-migration-coordinator-2NDCWP7F.js → rvf-migration-coordinator-VA52YAIY.js} +2 -2
  240. package/dist/cli/chunks/rvf-native-adapter-46GRWQJR.js +2 -0
  241. package/dist/cli/chunks/safe-db-LNIPXXHH.js +2 -0
  242. package/dist/cli/chunks/schedule-AUH3ZALY.js +2 -0
  243. package/dist/cli/chunks/scheduler-KK3OYPWW.js +2 -0
  244. package/dist/cli/chunks/{security-HT4SUT24.js → security-62HEETBF.js} +3 -3
  245. package/dist/cli/chunks/{shared-rvf-adapter-4IZOJL33.js → shared-rvf-adapter-XWTQPGCT.js} +2 -2
  246. package/dist/cli/chunks/{shared-rvf-dual-writer-ZKFO7CBY.js → shared-rvf-dual-writer-JTZK7LRD.js} +2 -2
  247. package/dist/cli/chunks/sqlite-persistence-CYESP7NG.js +2 -0
  248. package/dist/cli/chunks/{status-handler-AMEMKBI4.js → status-handler-LSUPUKRF.js} +2 -2
  249. package/dist/cli/chunks/{structural-health-RBADRLC3.js → structural-health-Z75A666N.js} +2 -2
  250. package/dist/cli/chunks/{sync-PCB23M4K.js → sync-M3O4T3A3.js} +2 -2
  251. package/dist/cli/chunks/{sync-ARDDLQBS.js → sync-VI37UHHH.js} +2 -2
  252. package/dist/cli/chunks/{task-handler-J26FSCH5.js → task-handler-AQBSZAQC.js} +2 -2
  253. package/dist/cli/chunks/{task-handlers-AQRLR6BL.js → task-handlers-BOZP247V.js} +3 -3
  254. package/dist/cli/chunks/{test-YXWSIOSB.js → test-FTEGPNN2.js} +4 -4
  255. package/dist/cli/chunks/{test-scheduling-XY532GI4.js → test-scheduling-IGR4U2VQ.js} +4 -4
  256. package/dist/cli/chunks/{token-bootstrap-KL2QIQ36.js → token-bootstrap-2DFRVMBM.js} +2 -2
  257. package/dist/cli/chunks/{token-usage-2MJVE4DT.js → token-usage-VCHV47EO.js} +3 -3
  258. package/dist/cli/chunks/{transformers-QSNTOD2Z.js → transformers-M27QSNFH.js} +2 -2
  259. package/dist/cli/chunks/tree-sitter-wasm-parser-IIGEJYFU.js +2 -0
  260. package/dist/cli/chunks/{types-RNKRSYMO.js → types-RQFPUUKA.js} +2 -2
  261. package/dist/cli/chunks/unified-memory-RISHEANP.js +2 -0
  262. package/dist/cli/chunks/unified-memory-hnsw-2IKXGMNZ.js +2 -0
  263. package/dist/cli/chunks/unified-persistence-ZTTUJNTU.js +2 -0
  264. package/dist/cli/chunks/{upgrade-EKJHIFWP.js → upgrade-VJMYX3AL.js} +2 -2
  265. package/dist/cli/chunks/{validate-KS4T7LWC.js → validate-ML7HUAU5.js} +4 -4
  266. package/dist/cli/chunks/{validate-swarm-SKKWRP2H.js → validate-swarm-RCR6EYRC.js} +7 -7
  267. package/dist/cli/chunks/{vibium-FLUQO4IF.js → vibium-ZOOS3W5L.js} +2 -2
  268. package/dist/cli/chunks/visual-security-D66DTAO5.js +2 -0
  269. package/dist/cli/chunks/{web-tree-sitter-UMC63DWD.js → web-tree-sitter-2YPGYLWK.js} +2 -2
  270. package/dist/cli/chunks/{windsurf-installer-V3FQGJIQ.js → windsurf-installer-GOJWUWC5.js} +2 -2
  271. package/dist/cli/chunks/{witness-chain-GE74TLSO.js → witness-chain-3MGSS3Q4.js} +2 -2
  272. package/dist/cli/chunks/witness-chain-RHWHHDLV.js +2 -0
  273. package/dist/cli/chunks/{workflow-4YZ2RPWA.js → workflow-B5Q77BI4.js} +4 -4
  274. package/dist/cli/chunks/workflow-orchestrator-OQMFW2TC.js +2 -0
  275. package/dist/cli/chunks/{wrappers-37NLMKPE.js → wrappers-MM5VLEPG.js} +2 -2
  276. package/dist/cli/commands/code.js +6 -0
  277. package/dist/cli/commands/learning.js +5 -5
  278. package/dist/cli/commands/llm-router.js +1 -1
  279. package/dist/cli/commands/workflow.js +1 -0
  280. package/dist/coordination/consensus/providers/native-learning-provider.d.ts +1 -1
  281. package/dist/coordination/consensus/providers/ollama-provider.d.ts +1 -1
  282. package/dist/coordination/consensus/providers/openrouter-provider.d.ts +1 -1
  283. package/dist/coordination/handlers/code-intelligence-handlers.js +6 -0
  284. package/dist/coordination/mincut/neural-goap.js +24 -20
  285. package/dist/coordination/protocols/code-intelligence-index.js +31 -25
  286. package/dist/coordination/queen-coordinator.js +4 -0
  287. package/dist/coordination/queen-work-stealing.js +1 -2
  288. package/dist/domains/chaos-resilience/coordinator.js +19 -15
  289. package/dist/domains/chaos-resilience/services/chaos-engineer.js +5 -2
  290. package/dist/domains/chaos-resilience/services/load-tester.js +15 -11
  291. package/dist/domains/code-intelligence/interfaces.d.ts +5 -0
  292. package/dist/domains/code-intelligence/services/c4-model/index.js +12 -6
  293. package/dist/domains/code-intelligence/services/impact-analyzer.js +6 -2
  294. package/dist/domains/code-intelligence/services/knowledge-graph.d.ts +42 -0
  295. package/dist/domains/code-intelligence/services/knowledge-graph.js +278 -93
  296. package/dist/domains/code-intelligence/services/semantic-analyzer.js +8 -2
  297. package/dist/domains/contract-testing/coordinator.js +1 -1
  298. package/dist/domains/coverage-analysis/coordinator.js +4 -2
  299. package/dist/domains/learning-optimization/coordinator.js +1 -0
  300. package/dist/domains/quality-assessment/coherence/gate-controller.js +32 -26
  301. package/dist/domains/requirements-validation/coordinator.js +1 -0
  302. package/dist/domains/test-execution/services/e2e/wait-condition-handler.js +1 -1
  303. package/dist/domains/test-execution/services/retry-handler.js +18 -12
  304. package/dist/domains/test-generation/coordinator.js +1 -1
  305. package/dist/domains/test-generation/services/pattern-matcher.js +7 -5
  306. package/dist/domains/test-generation/services/test-generator.js +3 -2
  307. package/dist/domains/visual-accessibility/coordinator.js +24 -20
  308. package/dist/index.d.ts +2 -2
  309. package/dist/index.js +2 -2
  310. package/dist/init/phases/12-verification.js +3 -3
  311. package/dist/integrations/agentic-flow/model-router/router.js +1 -1
  312. package/dist/integrations/embeddings/base/EmbeddingGenerator.js +11 -7
  313. package/dist/integrations/ruvector/hypergraph-engine.js +2 -2
  314. package/dist/integrations/ruvector/spectral-math.js +2 -2
  315. package/dist/integrations/ruvector/spectral-sparsifier.js +1 -1
  316. package/dist/kernel/kernel.js +1 -1
  317. package/dist/kernel/unified-memory-hnsw.js +1 -0
  318. package/dist/learning/experience-capture.js +1 -1
  319. package/dist/learning/qe-reasoning-bank.js +9 -1
  320. package/dist/learning/qe-unified-memory.js +8 -6
  321. package/dist/mcp/bundle.js +354 -354
  322. package/dist/mcp/handlers/core-handlers.js +2 -2
  323. package/dist/mcp/handlers/cross-phase-handlers.js +5 -3
  324. package/dist/mcp/handlers/handler-factory.d.ts +5 -0
  325. package/dist/mcp/handlers/handler-factory.js +44 -4
  326. package/dist/mcp/http-server.js +1 -0
  327. package/dist/mcp/protocol-server.js +2 -2
  328. package/dist/mcp/tools/code-intelligence/analyze.js +1 -1
  329. package/dist/mcp/tools/learning-optimization/optimize.js +1 -1
  330. package/dist/mcp/tools/qx-analysis/heuristics-engine.js +195 -173
  331. package/dist/mcp/tools/visual-accessibility/index.js +1 -1
  332. package/dist/mcp/transport/websocket/websocket-transport.js +1 -0
  333. package/dist/optimization/auto-tuner.js +1 -1
  334. package/dist/planning/goap-planner.js +1 -0
  335. package/dist/routing/agent-dependency-graph.js +4 -1
  336. package/dist/shared/llm/router/config-store.js +1 -1
  337. package/dist/shared/metrics/system-metrics.js +6 -4
  338. package/dist/shared/parsers/tree-sitter-wasm-parser.d.ts +12 -0
  339. package/dist/shared/parsers/tree-sitter-wasm-parser.js +35 -0
  340. package/dist/shared/parsers/treesitter-ts-extractor.d.ts +39 -0
  341. package/dist/shared/parsers/treesitter-ts-extractor.js +196 -0
  342. package/dist/shared/utils/safe-expression-evaluator.js +8 -5
  343. package/dist/sync/cloud/postgres-writer.js +2 -0
  344. package/dist/sync/readers/json-reader.js +1 -1
  345. package/dist/test-scheduling/git-aware/test-selector.js +1 -1
  346. package/dist/workers/quality-daemon/index.js +26 -24
  347. package/package.json +5 -4
  348. package/dist/cli/chunks/adapter-CR6J5C76.js +0 -2
  349. package/dist/cli/chunks/aqe-learning-engine-2MNTHMB6.js +0 -2
  350. package/dist/cli/chunks/base-AOQNGMTL.js +0 -2
  351. package/dist/cli/chunks/browser-workflow-UJ4A2ZXO.js +0 -2
  352. package/dist/cli/chunks/chunk-FO73PZVU.js +0 -2
  353. package/dist/cli/chunks/chunk-I677W5BT.js +0 -59
  354. package/dist/cli/chunks/chunk-IAZEDWRX.js +0 -2
  355. package/dist/cli/chunks/client-RDPWGOSA.js +0 -2
  356. package/dist/cli/chunks/cross-domain-router-4K5ZVZEZ.js +0 -2
  357. package/dist/cli/chunks/dream-RPNWM7VS.js +0 -2
  358. package/dist/cli/chunks/heartbeat-scheduler-JBCXMMZO.js +0 -2
  359. package/dist/cli/chunks/hnsw-adapter-3SC2HZIG.js +0 -2
  360. package/dist/cli/chunks/hnsw-index-FQORAR6K.js +0 -2
  361. package/dist/cli/chunks/hybrid-router-6CBFDXPR.js +0 -2
  362. package/dist/cli/chunks/impact-analyzer-SOEFVZWG.js +0 -2
  363. package/dist/cli/chunks/init-wizard-3E4IU5M4.js +0 -2
  364. package/dist/cli/chunks/kernel-GFZP4G5J.js +0 -2
  365. package/dist/cli/chunks/knowledge-graph-BKRKBU26.js +0 -2
  366. package/dist/cli/chunks/llm-router-service-KE4IGZPP.js +0 -2
  367. package/dist/cli/chunks/load-test-VSYJV2AO.js +0 -2
  368. package/dist/cli/chunks/memory-backend-B72RGHRF.js +0 -2
  369. package/dist/cli/chunks/memory-handlers-NWCH7AUO.js +0 -2
  370. package/dist/cli/chunks/protocol-executor-V3F37FPO.js +0 -2
  371. package/dist/cli/chunks/provider-manager-2PN72TT6.js +0 -2
  372. package/dist/cli/chunks/qe-reasoning-bank-P665QNIR.js +0 -2
  373. package/dist/cli/chunks/queen-coordinator-XD4F7BGB.js +0 -2
  374. package/dist/cli/chunks/router-4SSNWDJC.js +0 -2
  375. package/dist/cli/chunks/routing-feedback-O2JSIBW6.js +0 -2
  376. package/dist/cli/chunks/rvf-native-adapter-WIUHYXRB.js +0 -2
  377. package/dist/cli/chunks/safe-db-WL5Y7ZNS.js +0 -2
  378. package/dist/cli/chunks/schedule-U7QDGU5A.js +0 -2
  379. package/dist/cli/chunks/scheduler-LXKGQYXA.js +0 -2
  380. package/dist/cli/chunks/sqlite-persistence-4KFO3SEB.js +0 -2
  381. package/dist/cli/chunks/tree-sitter-wasm-parser-QJOKHOIW.js +0 -2
  382. package/dist/cli/chunks/unified-memory-7AS4LIEF.js +0 -2
  383. package/dist/cli/chunks/unified-memory-hnsw-GREESNJX.js +0 -2
  384. package/dist/cli/chunks/unified-persistence-BPJOMZOA.js +0 -2
  385. package/dist/cli/chunks/visual-security-BW662FHQ.js +0 -2
  386. package/dist/cli/chunks/witness-chain-OXVDLNVT.js +0 -2
  387. package/dist/cli/chunks/workflow-orchestrator-KKNR46XV.js +0 -2
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.2");process.exit(0)}
2
- import{a as h}from"./chunk-IAZEDWRX.js";import{c as m}from"./chunk-JF53LRBL.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{a as h}from"./chunk-3VF3HCG4.js";import{c as m}from"./chunk-2L73WXA4.js";h();var g=m.create("regret-tracker"),l=50,R=.9,d=1.1;function f(o,t){let e=o.length;if(e<2)return 0;let n=0,r=0,i=0,a=0;for(let s=0;s<e;s++)n+=o[s],r+=t[s],i+=o[s]*t[s],a+=o[s]*o[s];let u=e*a-n*n;return Math.abs(u)<1e-10?0:(e*i-n*r)/u}var c=class{domains=new Map;alertCallbacks=[];alerts=[];maxAlerts;recentWindow;constructor(t){this.maxAlerts=t?.maxAlerts??100,this.recentWindow=t?.recentWindow??20}recordDecision(t,e,n){let r=this.getOrCreateDomainState(t),i=Math.max(0,n-e);if(r.cumulativeRegret+=i,r.decisionCount++,r.points.push({decisionCount:r.decisionCount,cumulativeRegret:r.cumulativeRegret,timestamp:Date.now()}),r.decisionCount>=l){let a=this.classifyGrowthRate(r.points);r.lastGrowthRate!=="insufficient_data"&&a!==r.lastGrowthRate&&this.emitAlert(t,r.lastGrowthRate,a),r.lastGrowthRate=a}}getCumulativeRegret(t){return this.domains.get(t)?.cumulativeRegret??0}getRegretCurve(t){let e=this.domains.get(t);return e?[...e.points]:[]}getRegretGrowthRate(t){let e=this.domains.get(t);return e?this.classifyGrowthRate(e.points):"insufficient_data"}detectStagnation(t){let e=this.getRegretGrowthRate(t);return e==="linear"||e==="superlinear"}getHealthSummary(){let t=[];for(let[e,n]of this.domains){let r=this.classifyGrowthRate(n.points),i=this.computeLogLogSlope(n.points),a=this.computeRecentAvgRegret(n);t.push({domain:e,totalDecisions:n.decisionCount,cumulativeRegret:n.cumulativeRegret,growthRate:r,stagnating:r==="linear"||r==="superlinear",slope:i,recentAvgRegret:a})}return t.sort((e,n)=>e.domain.localeCompare(n.domain)),t}onAlert(t){this.alertCallbacks.push(t)}getAlerts(){return[...this.alerts]}getTrackedDomains(){return[...this.domains.keys()].sort()}getTotalDecisions(){let t=0;for(let e of this.domains.values())t+=e.decisionCount;return t}reset(t){t?this.domains.delete(t):(this.domains.clear(),this.alerts=[])}getOrCreateDomainState(t){let e=this.domains.get(t);return e||(e={points:[],cumulativeRegret:0,decisionCount:0,lastGrowthRate:"insufficient_data"},this.domains.set(t,e)),e}classifyGrowthRate(t){if(t.length<l)return"insufficient_data";let e=this.computeLogLogSlope(t);return e===void 0?"insufficient_data":e<R?"sublinear":e<=d?"linear":"superlinear"}computeLogLogSlope(t){if(t.length<l)return;let e=t.filter(i=>i.cumulativeRegret>0&&i.decisionCount>0);if(e.length<2)return;let n=e.map(i=>Math.log(i.decisionCount)),r=e.map(i=>Math.log(i.cumulativeRegret));return f(n,r)}computeRecentAvgRegret(t){if(t.points.length<2)return 0;let e=Math.min(this.recentWindow,t.points.length),n=t.points.slice(-e),r=n[0],i=n[n.length-1],a=i.cumulativeRegret-r.cumulativeRegret,u=i.decisionCount-r.decisionCount;return u<=0?0:a/u}emitAlert(t,e,n){let r={domain:t,previousRate:e,newRate:n,timestamp:Date.now(),message:`Domain "${t}" regret growth changed from ${e} to ${n}`};this.alerts.push(r),this.alerts.length>this.maxAlerts&&this.alerts.shift(),g.info("Regret growth rate transition",{domain:t,previousRate:e,newRate:n});for(let i of this.alertCallbacks)try{i(r)}catch(a){g.error("Alert callback error",a instanceof Error?a:void 0)}}};function b(o){return new c(o)}export{b as a};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.2");process.exit(0)}
2
- import{i as c}from"./chunk-ZGNZJJFF.js";import{b as g,d as E}from"./chunk-SW4OKUTC.js";import{a as p}from"./chunk-IAZEDWRX.js";import{c as m}from"./chunk-JF53LRBL.js";import{a as l,b as _}from"./chunk-MCZHKXB4.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{i as c}from"./chunk-NXPFGPHV.js";import{b as g,d as E}from"./chunk-KTRB3L53.js";import{a as p}from"./chunk-3VF3HCG4.js";import{c as m}from"./chunk-2L73WXA4.js";import{a as l,b as _}from"./chunk-L74CHKFR.js";_();import b from"node:path";import{existsSync as h}from"node:fs";E();p();var T=m.create("metrics-tracker"),d=class{db=null;dbPath;initialized=!1;constructor(e=process.cwd()){this.dbPath=b.join(e,".agentic-qe","memory.db")}async initialize(){if(!this.initialized){if(!h(this.dbPath))throw new Error(`Database not found: ${this.dbPath}. Run "aqe init --auto" first.`);this.db=l(this.dbPath),this.ensureMetricsTable(),this.initialized=!0}}ensureMetricsTable(){this.db&&this.db.exec(`
3
3
  CREATE TABLE IF NOT EXISTS learning_daily_snapshots (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
5
5
  snapshot_date TEXT NOT NULL UNIQUE,
@@ -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.2");process.exit(0)}
2
- import{b as q,c as R,d as D,f as O,g as j,h as x,i as $,j as L,k as N}from"./chunk-5WJ3FWL4.js";import{b as v,d as P}from"./chunk-SW4OKUTC.js";import{a as k,c as T}from"./chunk-XPCNUX2U.js";import{a as _,b as ee}from"./chunk-MCZHKXB4.js";P();import{existsSync as E,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");E(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(E(r))try{let u=I(r,"utf-8");s=v(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5e3,continueOnError:!0}]}]},p=s.hooks||{};s.hooks=O(p,i);let c=s.env||{};s.env={...c,...j(e)};let m=x(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let d=s.permissions||{},l=d.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...d,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");E(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(E(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(E(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{b as q,c as R,d as D,f as O,g as j,h as x,i as $,j as L,k as N}from"./chunk-HWM2XJ3P.js";import{b as v,d as P}from"./chunk-KTRB3L53.js";import{a as k,c as T}from"./chunk-3LRK7PYN.js";import{a as _,b as ee}from"./chunk-L74CHKFR.js";P();import{existsSync as E,mkdirSync as Q,writeFileSync as S,readFileSync as I,copyFileSync as te}from"fs";import{join as g,dirname as ne}from"path";async function M(t,e){if(!e.hooks.claudeCode)return!1;let n=g(t,".claude");E(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(E(r))try{let u=I(r,"utf-8");s=v(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5e3,continueOnError:!0}]}]},p=s.hooks||{};s.hooks=O(p,i);let c=s.env||{};s.env={...c,...j(e)};let m=x(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let d=s.permissions||{},l=d.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...d,allow:C}}else s[u]=h;let a=s.enabledMcpjsonServers||[];return a=a.filter(u=>u!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,S(r,JSON.stringify(s,null,2),"utf-8"),await re(t),!0}async function re(t){let e=g(t,".claude","hooks");E(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(E(n))return;let r=[g(ne(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),g(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let i of r)try{if(E(i)){te(i,n),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}S(n,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/anthropics/agentic-qe/docs/cross-phase-memory.md
5
5
 
@@ -276,7 +276,7 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),i),s.prepare(`
277
277
  INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
278
  VALUES (?, '_system', ?, ?)
279
- `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-5BT5FO64.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),i),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(i){return s.close(),console.warn(` \u26A0 Could not write version: ${k(i)}`),!1}}catch(r){return console.warn(` \u26A0 Could not open memory.db: ${k(r)}`),!1}}async function W(t){let e=null;try{e=(await import("./better-sqlite3-HP4JZS6K.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
280
  Install it with: npm install better-sqlite3
281
281
  If you see native compilation errors, ensure build tools are installed:
282
282
  - macOS: xcode-select --install
@@ -302,7 +302,7 @@ Database path: ${r}
302
302
  Ensure the directory is writable and has sufficient disk space.`)}}async function G(t){let e=o(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let n=_(e),r=n.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-BKRKBU26.js"),{InMemoryBackend:n}=await import("./memory-backend-B72RGHRF.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),p=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:p.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function J(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
305
+ `).get();return n.close(),r.count>0}catch{return!1}}async function V(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-YUWIDIWW.js"),{InMemoryBackend:n}=await import("./memory-backend-BI2V5AAB.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),p=await(await import("fast-glob")).default(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"]}),c=await s.index({paths:p.map(m=>o(t,m)),incremental:!1,includeTests:!0});return s.destroy(),c.success?{status:"indexed",entries:c.value.nodesCreated+c.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",k(e)),{status:"skipped",entries:0}}}async function J(t){let e=o(t,".agentic-qe","memory.db");try{let n=_(e),r=n.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
308
  `).get();return n.close(),r.count}catch{return 0}}async function B(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");f(r)||w(r,{recursive:!0});let s=o(r,"hnsw");f(s)||w(s,{recursive:!0});let i=o(r,"learning-config.json"),p={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};b(i,JSON.stringify(p,null,2),"utf-8");let c=0;if(e.learning.pretrainedPatterns&&n){let m=n,a=new Map;for(let d of m.patterns){let l=d.domain||"general";a.has(l)||a.set(l,[]),a.get(l).push(d)}let u=o(r,"pretrained-index.json"),h={version:m.version,totalPatterns:m.statistics.totalPatterns,domains:Array.from(a.entries()).map(([d,l])=>({name:d,patternCount:l.length})),loadedAt:new Date().toISOString()};b(u,JSON.stringify(h,null,2),"utf-8");for(let[d,l]of a){let y=o(r,"patterns",d);f(y)||w(y,{recursive:!0});let C=o(y,"patterns.json");b(C,JSON.stringify(l,null,2),"utf-8"),c+=l.length}return c}return 0}async function H(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");f(n)||w(n,{recursive:!0});let r={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)r[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let i=o(n,"registry.json"),p={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};b(i,JSON.stringify(p,null,2),"utf-8");for(let a of e.workers.enabled){let u=o(n,`${a}.json`),h={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:o(t,".agentic-qe","data"),createdAt:new Date().toISOString()};b(u,JSON.stringify(h,null,2),"utf-8")}let c=o(n,"start-daemon.cjs");return b(c,`#!/usr/bin/env node
@@ -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.2");process.exit(0)}
2
- import{a as l}from"./chunk-HJME6G5M.js";import{a as m}from"./chunk-FPAW77XV.js";import{i as a}from"./chunk-AOI67HA3.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y 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.3");process.exit(0)}
2
+ import{a as l}from"./chunk-Q7EBD24B.js";import{a as m}from"./chunk-JD2PG4KS.js";import{i as a}from"./chunk-RTDHWOAG.js";var u=class{constructor(t,e){this.eventBus=t;this.maxHistorySize=e?.maxHistorySize??1e4,this.eventHistory=new l(this.maxHistorySize),this.correlationTimeout=e?.correlationTimeout??6e4,this.maxEventsPerCorrelation=e?.maxEventsPerCorrelation??100}eventBus;subscriptions=new Map;correlations=new Map;eventHistory;routes=[];domainSubscriptions=new Map;maxHistorySize;correlationTimeout;maxEventsPerCorrelation;initialized=!1;async initialize(){if(!this.initialized){for(let t of m){let e=this.eventBus.subscribeToChannel(t,async i=>{await this.handleIncomingEvent(i)});this.domainSubscriptions.set(t,e)}this.eventBus.subscribe("*",async t=>{m.includes(t.source)||await this.handleIncomingEvent(t)}),this.initialized=!0}}subscribeToDoamin(t,e){let i=`sub_domain_${a()}`;return this.subscriptions.set(i,{id:i,type:"domain",filter:t,handler:e,active:!0}),i}subscribeToEventType(t,e){let i=`sub_type_${a()}`;return this.subscriptions.set(i,{id:i,type:"eventType",filter:t,handler:e,active:!0}),i}unsubscribe(t){let e=this.subscriptions.get(t);return e?(e.active=!1,this.subscriptions.delete(t),!0):!1}async route(t){this.addToHistory(t),t.correlationId&&this.trackCorrelation(t);let i=this.findMatchingSubscriptions(t).map(async o=>{try{await o.handler(t)}catch(n){console.error(`Error in subscription handler ${o.id}:`,n instanceof Error?n.message:n)}}),r=await this.applyRoutes(t);await Promise.allSettled([...i,...r])}getCorrelation(t){let e=this.correlations.get(t);if(e)return{correlationId:e.correlationId,events:[...e.events],domains:new Set(e.domains),startedAt:e.startedAt,lastEventAt:e.lastEventAt,complete:e.complete}}trackCorrelation(t){if(!t.correlationId)return;let e=this.correlations.get(t.correlationId);e||(e={correlationId:t.correlationId,events:[],domains:new Set,startedAt:t.timestamp,lastEventAt:t.timestamp,complete:!1,timeout:null},this.correlations.set(t.correlationId,e)),e.events.length<this.maxEventsPerCorrelation&&(e.events.push(t),e.domains.add(t.source),e.lastEventAt=t.timestamp),e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(()=>{e.complete=!0,e.timeout=null},this.correlationTimeout)}aggregate(t,e){let i=this.eventHistory.toArray().filter(s=>s.timestamp>=t&&s.timestamp<=e),r=new Map,o=new Map;for(let s of i)r.set(s.type,(r.get(s.type)??0)+1),o.set(s.source,(o.get(s.source)??0)+1);let n={totalEvents:i.length,uniqueEventTypes:r.size,uniqueDomains:o.size,eventsPerSecond:i.length>0?i.length/((e.getTime()-t.getTime())/1e3):0};return{id:a(),windowStart:t,windowEnd:e,events:i,countByType:r,countByDomain:o,metrics:n}}getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(i=>t.eventTypes.includes(i.type))),t.domains?.length&&(e=e.filter(i=>t.domains.includes(i.source))),t.fromTimestamp&&(e=e.filter(i=>i.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(i=>i.timestamp<=t.toTimestamp)),t.limit&&(e=e.slice(-t.limit))),e}addRoute(t){let e=t.priority??0,i=this.routes.findIndex(r=>(r.priority??0)<e);i===-1?this.routes.push(t):this.routes.splice(i,0,t)}removeRoute(t,e){let i=this.routes.findIndex(r=>r.eventPattern===t&&(e===void 0||r.source===e));return i!==-1?(this.routes.splice(i,1),!0):!1}async dispose(){this.subscriptions.clear();for(let t of this.domainSubscriptions.values())t.unsubscribe();this.domainSubscriptions.clear();for(let t of this.correlations.values())t.timeout&&clearTimeout(t.timeout);this.correlations.clear(),this.eventHistory.clear(),this.initialized=!1}async handleIncomingEvent(t){await this.route(t)}findMatchingSubscriptions(t){let e=[];for(let i of this.subscriptions.values())i.active&&(i.type==="domain"&&i.filter===t.source||i.type==="eventType"&&this.matchEventType(t.type,i.filter))&&e.push(i);return e}matchEventType(t,e){if(e==="*")return!0;let i=e.replace(/\\/g,"\\\\").replace(/\./g,"\\.").replace(/\*/g,".*");return new RegExp(`^${i}$`).test(t)}async applyRoutes(t){let e=[];for(let i of this.routes){if(!(i.source==="*"||i.source===t.source||Array.isArray(i.source)&&i.source.includes(t.source))||!this.matchEventType(t.type,i.eventPattern)||i.filter&&!i.filter(t))continue;let o=i.transform?i.transform(t):t;for(let n of i.targets)n!==t.source&&e.push(this.eventBus.publish({...o,id:a(),correlationId:t.correlationId??t.id}))}return e}addToHistory(t){this.eventHistory.push(t)}};function y(c,t){return new u(c,t)}export{u as a,y 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.2");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as z}from"./chunk-5QHSLWLP.js";import{b as S,d as $}from"./chunk-SW4OKUTC.js";import{a as N,c as F}from"./chunk-XPCNUX2U.js";import{i as v}from"./chunk-AOI67HA3.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{a as w,b as A,c as O,e as D,f as z}from"./chunk-R5ONQAQL.js";import{b as S,d as $}from"./chunk-KTRB3L53.js";import{a as N,c as F}from"./chunk-3LRK7PYN.js";import{i as v}from"./chunk-RTDHWOAG.js";import*as I from"node:path";z();$();var P=["function","module","test","file","class"],L=["calls","imports","tests","depends_on","covers"],b=class{ensureSchema(e){e.transaction(()=>{e.exec(w),e.exec(A),e.exec(O)})()}schemaExists(e){return D(e)}getNodeTypes(){return P}getEdgeTypes(){return L}isValidNodeType(e){return P.includes(e)}isValidEdgeType(e){return L.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function C(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?U(n.embedding):null}}function T(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?S(n.metadata):void 0,embedding:n.embedding?W(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function M(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function H(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?S(n.properties):void 0,createdAt:n.created_at}}function x(n,e,t){return`${n}--${t}-->${e}`}function U(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function W(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}F();var B={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},R=class{config;schemaManager;initialized=!1;constructor(e){this.config={...B,...e},this.schemaManager=new b}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=v(),r={id:t,...e},s=C(r);return this.config.db.prepare(`
3
3
  INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
4
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
5
  `).run(s.id,s.type,s.name,s.file_path,s.line_start,s.line_end,s.complexity,s.coverage,s.metadata,s.embedding),t}async addEdge(e){this.ensureInitialized();let t=x(e.sourceId,e.targetId,e.type),r={id:t,...e},s=M(r);return this.config.db.prepare(`
@@ -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.2");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.3");process.exit(0)}
2
2
  var t=["claude","openai","ollama","openrouter","gemini","azure-openai","bedrock","onnx"];var e={maxAttempts:3,delayMs:100,trySameProviderAlternateModel:!0,skipOpenCircuits:!0,retryableErrors:["RATE_LIMITED","TIMEOUT","NETWORK_ERROR","PROVIDER_UNAVAILABLE"]},r=[{provider:"claude",models:["claude-sonnet-4-6","claude-haiku-4-5-20251001"],enabled:!0,priority:100,maxAttempts:2,timeoutMs:3e4},{provider:"openai",models:["gpt-4o","gpt-4o-mini"],enabled:!0,priority:90,maxAttempts:2,timeoutMs:3e4},{provider:"openrouter",models:["anthropic/claude-sonnet-4","openai/gpt-4o"],enabled:!0,priority:85,maxAttempts:2,timeoutMs:3e4},{provider:"ollama",models:["llama3.1","mistral"],enabled:!0,priority:80,maxAttempts:2,timeoutMs:6e4},{provider:"onnx",models:["phi-4","all-MiniLM-L6-v2"],enabled:!0,priority:70,maxAttempts:1,timeoutMs:12e4}],o={id:"default-fallback-chain",entries:r,maxRetries:3,retryDelayMs:100,backoffMultiplier:2,maxDelayMs:5e3},n={mode:"rule-based",rules:[],defaultProvider:"claude",defaultModel:"claude-sonnet-4-6",fallbackChain:o,fallbackBehavior:e,providers:{claude:{enabled:!0,defaultModel:"claude-sonnet-4-6"},openai:{enabled:!0,defaultModel:"gpt-4o"},ollama:{enabled:!0,defaultModel:"llama3.1"},openrouter:{enabled:!0,defaultModel:"anthropic/claude-sonnet-4"},gemini:{enabled:!1,defaultModel:"gemini-pro"},"azure-openai":{enabled:!1},bedrock:{enabled:!1},onnx:{enabled:!0,defaultModel:"phi-4"}},enableMetrics:!0,metricsConfig:{enabled:!0,collectionIntervalMs:6e4,retentionMs:864e5,trackPerRequest:!0},maxDecisionTimeMs:10,cacheDecisions:!0,decisionCacheTtlMs:6e4,cacheConfig:{enabled:!0,ttlMs:6e4,maxEntries:1e3,keyStrategy:"agent-domain"},auditConfig:{enabled:!0,maxEntries:1e4,logContent:!1,logResponse:!1}},a=[{canonicalId:"claude-opus-4-7",canonicalName:"Claude Opus 4.7",providerIds:{claude:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:1e6,maxOutputTokens:128e3},tier:"flagship",family:"claude",inputCostPer1M:5,outputCostPer1M:25},{canonicalId:"claude-sonnet-4-6",canonicalName:"Claude Sonnet 4.6",providerIds:{claude:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!0,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:64e3},tier:"advanced",family:"claude",inputCostPer1M:3,outputCostPer1M:15},{canonicalId:"claude-haiku-4-5",canonicalName:"Claude Haiku 4.5",providerIds:{claude:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!0,supportsJsonMode:!0,maxContextTokens:2e5,maxOutputTokens:16384},tier:"standard",family:"claude",inputCostPer1M:1,outputCostPer1M:5},{canonicalId:"gpt-4o",canonicalName:"GPT-4o",providerIds:{openai:"gpt-4o","azure-openai":"gpt-4o",openrouter:"openai/gpt-4o"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"advanced",family:"gpt",inputCostPer1M:2.5,outputCostPer1M:10},{canonicalId:"gpt-4o-mini",canonicalName:"GPT-4o Mini",providerIds:{openai:"gpt-4o-mini","azure-openai":"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:16384},tier:"standard",family:"gpt",inputCostPer1M:.15,outputCostPer1M:.6},{canonicalId:"gemini-pro",canonicalName:"Gemini 2.0 Pro",providerIds:{gemini:"gemini-2.0-pro",openrouter:"google/gemini-2.0-pro"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!0,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:2e6,maxOutputTokens:8192},tier:"advanced",family:"gemini",inputCostPer1M:1.25,outputCostPer1M:5},{canonicalId:"llama-3.1-70b",canonicalName:"LLaMA 3.1 70B",providerIds:{ollama:"llama3.1:70b",openrouter:"meta-llama/llama-3.1-70b",bedrock:"meta.llama3-1-70b-instruct-v1:0"},capabilities:{supportsStreaming:!0,supportsTools:!0,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!0,maxContextTokens:128e3,maxOutputTokens:4096},tier:"advanced",family:"llama",inputCostPer1M:.9,outputCostPer1M:.9},{canonicalId:"phi-4",canonicalName:"Microsoft Phi-4",providerIds:{ollama:"phi4",onnx:"phi-4",openrouter:"microsoft/phi-4"},capabilities:{supportsStreaming:!0,supportsTools:!1,supportsMCP:!1,supportsVision:!1,supportsExtendedThinking:!1,supportsJsonMode:!1,maxContextTokens:16e3,maxOutputTokens:4096,requiresNetwork:!1},tier:"efficient",family:"phi",inputCostPer1M:0,outputCostPer1M:0}];export{t as a,n as b,a as c};
@@ -1,11 +1,11 @@
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.2");process.exit(0)}
2
- import{o as me}from"./chunk-EQBEGDTG.js";import{b as w,c as E,d as A,f as j,k as de,o as ue}from"./chunk-L7VIX22Y.js";import{a as Re,b as _,d as ee}from"./chunk-SW4OKUTC.js";import{a as v}from"./chunk-IAZEDWRX.js";import{c as b}from"./chunk-JF53LRBL.js";import{a as d,b as L,c as P}from"./chunk-XPCNUX2U.js";import{i as I}from"./chunk-AOI67HA3.js";import{a as T,b as z}from"./chunk-MCZHKXB4.js";import{a as le,d as Te}from"./chunk-WNR2KAUH.js";import{f as Ce}from"./chunk-ORF2UKQH.js";var k={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();A();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var Ae=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return Ae.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function ke(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}A();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
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{o as me}from"./chunk-6Q2PPOOF.js";import{b as w,c as E,d as k,f as j,k as de,o as ue}from"./chunk-USFZ4IJD.js";import{a as Re,b as _,d as ee}from"./chunk-KTRB3L53.js";import{a as v}from"./chunk-3VF3HCG4.js";import{c as b}from"./chunk-2L73WXA4.js";import{a as d,b as L,c as P}from"./chunk-3LRK7PYN.js";import{i as I}from"./chunk-RTDHWOAG.js";import{a as T,b as z}from"./chunk-L74CHKFR.js";import{a as le,d as Te}from"./chunk-3RZL4QTT.js";import{f as Ce}from"./chunk-CAMEFWRK.js";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},Pe={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();k();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Re(),1);P();import{randomUUID as ve}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${ve().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as _e}from"child_process";import{createConnection as xe}from"net";var ke=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return ke.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var M=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=xe({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=_e("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function Ae(l){return new M(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function $(l){return l.connectionString?new B(l.connectionString):new M(l)}k();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),$e=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=$e("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
3
3
  INSERT INTO ${u} (${p.join(", ")})
4
4
  VALUES ${s.join(", ")}
5
5
  ${h}
6
- `;try{return(await this.client.query(y,a)).rowCount||0}catch(f){throw N.debug(`Upsert failed for ${e}`,{error:d(f)}),f}}async execute(e,t){if(!this.client)throw new Error("Not connected");await this.client.query(e,t)}async query(e,t){if(!this.client)throw new Error("Not connected");return(await this.client.query(e,t)).rows}async close(){this.inTransaction&&await this.rollback(),this.client&&(await this.client.end(),this.client=null,this.connected=!1,console.log("[PostgresWriter] Connection closed"))}serializeValue(e,t){if(e==null)return null;if(Buffer.isBuffer(e)){try{let n=new Float32Array(e.buffer,e.byteOffset,e.length/4);if(n.length>0&&n.length<=1024)return`[${Array.from(n).join(",")}]`}catch(n){N.debug("Buffer to float array conversion failed",{error:n instanceof Error?n.message:String(n)})}return null}if(typeof e=="number")return e>9466848e5&&e<41024448e5?new Date(e).toISOString():e>946684800&&e<4102444800?new Date(e*1e3).toISOString():e;if(Array.isArray(e))return e.length>0&&typeof e[0]=="number"?`[${e.join(",")}]`:JSON.stringify(e);if(typeof e=="object"){let n=JSON.stringify(e);if(t&&this.isJsonbColumn(t)){n=n.replace(/\u0000/g,"");try{JSON.parse(n)}catch{return JSON.stringify(String(e))}}return n}if(typeof e=="string"){if(e===""&&t&&["created_at","updated_at","last_used_at","started_at","ended_at","completed_at","expires_at","last_update"].includes(t))return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;let n=parseInt(e,10);if(!isNaN(n)&&n>9466848e5&&n<41024448e5)return new Date(n).toISOString();if(t&&this.isJsonbColumn(t)){let r=e.replace(/\u0000/g,"");try{return JSON.parse(r),r}catch{return JSON.stringify(r)}}}return e}isJsonbColumn(e){return["action_value","state","action","next_state","preconditions","effects","metadata","value","payload","context_json","template_json","execution_trace","action_sequence","initial_state","goal_state","sequence","task_json","decision_json","steps_json","metadata_json"].includes(e)}inferConflictColumns(e,t){let n=e.includes(".")?e.split(".")[1]:e,r=["qe_patterns","sona_patterns","goap_actions","goap_plans","patterns","events","routing_outcomes","qe_trajectories","dream_insights","intelligence_memories"];return t.includes("id")&&r.includes(n)?["id"]:n==="memory_entries"&&t.includes("key")&&t.includes("source_env")?t.includes("partition")?["key","partition","source_env"]:["key","source_env"]:n==="claude_flow_memory"&&t.includes("key")&&t.includes("source_env")?["key","source_env"]:n==="qlearning_patterns"&&t.includes("state")&&t.includes("action")&&t.includes("source_env")?["state","action","source_env"]:n==="claude_flow_workers"&&t.includes("worker_type")&&t.includes("source_env")?["worker_type","source_env"]:[]}createMockClient(){let e=[];return{async connect(){console.log("[MockPgClient] Connected (mock mode)")},async query(t,n){return console.log(`[MockPgClient] Query: ${t.slice(0,100)}... (${n?.length||0} params)`),{rows:e,rowCount:0}},async end(){console.log("[MockPgClient] Disconnected (mock mode)")}}}};function O(l){return new J(l)}A();P();v();var G=b.create("postgres-reader"),Q=class{writer;environment;constructor(e){this.writer=e.writer,this.environment=e.environment}sanitizeCloudTable(e){let t=e.indexOf(".");if(t===-1||t===0||t===e.length-1)throw new Error(`Invalid cloud table format '${e}': expected 'schema.table' (e.g., 'aqe.qe_patterns')`);let n=e.substring(0,t),r=e.substring(t+1);return`${E(n)}.${E(r)}`}async readAll(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT * FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT * FROM ${t}`,r=[]);try{let i=await this.writer.query(n,r);return G.debug(`Read ${i.length} records from ${e.cloudTable}`,{env:this.environment}),i.map(o=>this.transformRecord(o,e))}catch(i){throw new Error(`Failed to read from ${e.cloudTable}: ${d(i)}`)}}async readChanged(e,t){let n=this.sanitizeCloudTable(e.cloudTable),r=await this.findTimestampColumn(n);if(!r)return G.debug(`No timestamp column found for ${e.cloudTable}, falling back to readAll`),this.readAll(e);let i,o;this.environment!=="all"?(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1 AND source_env = $2`,o=[t.toISOString(),this.environment]):(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1`,o=[t.toISOString()]);try{return(await this.writer.query(i,o)).map(a=>this.transformRecord(a,e))}catch(s){return G.debug(`Changed query failed for ${e.cloudTable}, falling back to readAll`,{error:d(s)}),this.readAll(e)}}async count(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT COUNT(*) as count FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT COUNT(*) as count FROM ${t}`,r=[]);try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let i=await this.writer.query(n,r);return await this.writer.commit(),typeof i[0]?.count=="string"?parseInt(i[0].count,10):i[0]?.count||0}catch(i){try{await this.writer.rollback()}catch{}return G.debug(`Count query failed for ${e.cloudTable}`,{error:d(i)}),-1}}transformRecord(e,t){let n={};for(let[r,i]of Object.entries(e)){if(t.dropColumns?.includes(r))continue;let o=t.columnMap?.[r]||r;n[o]=this.transformValue(i,r,t.transforms)}return n}transformValue(e,t,n){if(e==null)return null;let r=n?.[t];return r==="boolean-to-int"?typeof e=="boolean"?e?1:0:e==="true"||e==="t"?1:e==="false"||e==="f"?0:e:r==="jsonb-to-text"?typeof e=="object"?JSON.stringify(e):e:r==="timestamptz-to-text"?e instanceof Date?e.toISOString():e:typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:e}async findTimestampColumn(e){let t=["updated_at","created_at","last_update","last_used_at"];try{let n=e.split(".")[0],r=e.split(".")[1],o=(await this.writer.query(`SELECT column_name FROM information_schema.columns
6
+ `;try{return(await this.client.query(y,a)).rowCount||0}catch(f){throw N.debug(`Upsert failed for ${e}`,{error:d(f)}),f}}async execute(e,t){if(!this.client)throw new Error("Not connected");await this.client.query(e,t)}async query(e,t){if(!this.client)throw new Error("Not connected");return(await this.client.query(e,t)).rows}async close(){this.inTransaction&&await this.rollback(),this.client&&(await this.client.end(),this.client=null,this.connected=!1,console.log("[PostgresWriter] Connection closed"))}serializeValue(e,t){if(e==null)return null;if(Buffer.isBuffer(e)){try{let n=new Float32Array(e.buffer,e.byteOffset,e.length/4);if(n.length>0&&n.length<=1024)return`[${Array.from(n).join(",")}]`}catch(n){N.debug("Buffer to float array conversion failed",{error:n instanceof Error?n.message:String(n)})}return null}if(typeof e=="number")return e>9466848e5&&e<41024448e5?new Date(e).toISOString():e>946684800&&e<4102444800?new Date(e*1e3).toISOString():e;if(Array.isArray(e))return e.length>0&&typeof e[0]=="number"?`[${e.join(",")}]`:JSON.stringify(e);if(typeof e=="object"){let n=JSON.stringify(e);if(t&&this.isJsonbColumn(t)){n=n.replace(/\u0000/g,"");try{JSON.parse(n)}catch{return JSON.stringify(String(e))}}return n}if(typeof e=="string"){if(e===""&&t&&["created_at","updated_at","last_used_at","started_at","ended_at","completed_at","expires_at","last_update"].includes(t))return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;let n=parseInt(e,10);if(!isNaN(n)&&n>9466848e5&&n<41024448e5)return new Date(n).toISOString();if(t&&this.isJsonbColumn(t)){let r=e.replace(/\u0000/g,"");try{return JSON.parse(r),r}catch{return JSON.stringify(r)}}}return e}isJsonbColumn(e){return["action_value","state","action","next_state","preconditions","effects","metadata","value","payload","context_json","template_json","execution_trace","action_sequence","initial_state","goal_state","sequence","task_json","decision_json","steps_json","metadata_json"].includes(e)}inferConflictColumns(e,t){let n=e.includes(".")?e.split(".")[1]:e,r=["qe_patterns","sona_patterns","goap_actions","goap_plans","patterns","events","routing_outcomes","qe_trajectories","dream_insights","intelligence_memories"];return t.includes("id")&&r.includes(n)?["id"]:n==="memory_entries"&&t.includes("key")&&t.includes("source_env")?t.includes("partition")?["key","partition","source_env"]:["key","source_env"]:n==="claude_flow_memory"&&t.includes("key")&&t.includes("source_env")?["key","source_env"]:n==="qlearning_patterns"&&t.includes("state")&&t.includes("action")&&t.includes("source_env")?["state","action","source_env"]:n==="claude_flow_workers"&&t.includes("worker_type")&&t.includes("source_env")?["worker_type","source_env"]:[]}createMockClient(){let e=[];return{async connect(){console.log("[MockPgClient] Connected (mock mode)")},async query(t,n){return console.log(`[MockPgClient] Query: ${t.slice(0,100)}... (${n?.length||0} params)`),{rows:e,rowCount:0}},async end(){console.log("[MockPgClient] Disconnected (mock mode)")}}}};function O(l){return new J(l)}k();P();v();var G=b.create("postgres-reader"),Q=class{writer;environment;constructor(e){this.writer=e.writer,this.environment=e.environment}sanitizeCloudTable(e){let t=e.indexOf(".");if(t===-1||t===0||t===e.length-1)throw new Error(`Invalid cloud table format '${e}': expected 'schema.table' (e.g., 'aqe.qe_patterns')`);let n=e.substring(0,t),r=e.substring(t+1);return`${E(n)}.${E(r)}`}async readAll(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT * FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT * FROM ${t}`,r=[]);try{let i=await this.writer.query(n,r);return G.debug(`Read ${i.length} records from ${e.cloudTable}`,{env:this.environment}),i.map(o=>this.transformRecord(o,e))}catch(i){throw new Error(`Failed to read from ${e.cloudTable}: ${d(i)}`)}}async readChanged(e,t){let n=this.sanitizeCloudTable(e.cloudTable),r=await this.findTimestampColumn(n);if(!r)return G.debug(`No timestamp column found for ${e.cloudTable}, falling back to readAll`),this.readAll(e);let i,o;this.environment!=="all"?(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1 AND source_env = $2`,o=[t.toISOString(),this.environment]):(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1`,o=[t.toISOString()]);try{return(await this.writer.query(i,o)).map(a=>this.transformRecord(a,e))}catch(s){return G.debug(`Changed query failed for ${e.cloudTable}, falling back to readAll`,{error:d(s)}),this.readAll(e)}}async count(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT COUNT(*) as count FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT COUNT(*) as count FROM ${t}`,r=[]);try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let i=await this.writer.query(n,r);return await this.writer.commit(),typeof i[0]?.count=="string"?parseInt(i[0].count,10):i[0]?.count||0}catch(i){try{await this.writer.rollback()}catch{}return G.debug(`Count query failed for ${e.cloudTable}`,{error:d(i)}),-1}}transformRecord(e,t){let n={};for(let[r,i]of Object.entries(e)){if(t.dropColumns?.includes(r))continue;let o=t.columnMap?.[r]||r;n[o]=this.transformValue(i,r,t.transforms)}return n}transformValue(e,t,n){if(e==null)return null;let r=n?.[t];return r==="boolean-to-int"?typeof e=="boolean"?e?1:0:e==="true"||e==="t"?1:e==="false"||e==="f"?0:e:r==="jsonb-to-text"?typeof e=="object"?JSON.stringify(e):e:r==="timestamptz-to-text"?e instanceof Date?e.toISOString():e:typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:e}async findTimestampColumn(e){let t=["updated_at","created_at","last_update","last_used_at"];try{let n=e.split(".")[0],r=e.split(".")[1],o=(await this.writer.query(`SELECT column_name FROM information_schema.columns
7
7
  WHERE table_schema = $1 AND table_name = $2
8
- AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(s=>s.column_name);for(let s of t)if(o.includes(s))return s;return o[0]||null}catch{return null}}};function ie(l){return new Q(l)}z();A();P();v();import*as ye from"fs";var D=b.create("sqlite-writer"),V=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!ye.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=T(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),D.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=w(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return D.debug(`No columns found for table ${e}`),0;let i=new Set(r),o=0;for(let s=0;s<t.length;s+=this.batchSize){let a=t.slice(s,s+this.batchSize);try{let c=this.upsertBatch(n,a,i);o+=c}catch(c){let u=Math.floor(s/this.batchSize)+1;D.debug(`Batch ${u} failed for ${e}, retrying individually`,{error:d(c)});let p=0;for(let m of a)try{p+=this.upsertBatch(n,[m],i)}catch(g){let h=m.id||m.key||"?";D.debug(`Skipped record ${String(h).slice(0,50)} in ${e}`,{error:d(g)})}o+=p}}return o}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=w(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,D.debug("SQLite writer closed"))}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(i=>i.pk>0).sort((i,o)=>i.pk-o.pk).map(i=>i.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],i=Object.keys(r).filter(g=>n.has(g));if(i.length===0)return 0;let o=i.map(E),s=i.map(()=>"?").join(", "),a=e.replace(/"/g,""),c=this.getPrimaryKeyColumns(a),u;if(c.length>0){let g=c.map(E),h=i.filter(y=>!c.includes(y));if(h.length>0){let y=h.map(f=>`${E(f)} = excluded.${E(f)}`).join(", ");u=`INSERT INTO ${e} (${o.join(", ")}) VALUES (${s}) ON CONFLICT(${g.join(", ")}) DO UPDATE SET ${y}`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`;let p=this.db.prepare(u);return this.db.transaction(g=>{let h=0;for(let y of g){let f=i.map(S=>this.serializeValue(y[S]));p.run(...f),h++}return h})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function oe(l){return new V(l)}v();P();var Ne=b.create("sync-agent"),H=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...x,...e,local:{...x.local,...e.local},cloud:{...x.cloud,...e.cloud},sync:{...x.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let i=await this.syncSource(r);this.report.results.push(i),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let i=await this.syncSourceIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let i=await r.readAll();if(this.log(`Read ${i.length} records from ${e.name}`),i.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let o=await this.writer.upsert(e.targetTable,i,{skipIfExists:e.mode==="append"});n.recordsSynced=o}else n.recordsSynced=i.length,this.log(`[DRY RUN] Would sync ${i.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let i=this.readers.get(e.name);if(!i)throw new Error(`Reader not found: ${e.name}`);let o=await i.readChanged(t);if(this.log(`Read ${o.length} changed records from ${e.name} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o);r.recordsSynced=s}else r.recordsSynced=o.length;r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),i=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let o=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),i=o[0]?.count||0}catch(o){try{await this.writer.rollback()}catch{}Ne.debug("Cloud count query failed",{source:t.name,error:o instanceof Error?o.message:String(o)}),i=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:i,match:r===i,diff:r-i})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?re({source:e,baseDir:t,environment:n}):e.type==="json"?ne({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=$(this.config.cloud);this.writer=O({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function se(l){return new H(l)}async function Oe(l){let e=se({...l,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function De(l,e){let t=se({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(l)}finally{await t.close()}}import*as Y from"fs";import*as ae from"path";ue();P();v();var Lt=b.create("pull-agent"),X=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...k,...e,cloud:{...k.cloud,...e.cloud},sources:e.sources||k.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=$(this.config.cloud);this.cloudWriter=O({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=ie({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=oe({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let i=await this.pullTableIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let i=await this.writer.upsert(e.localTable,r);n.recordsSynced=i,n.recordsSkipped=r.length-i}n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let i=await this.reader.readChanged(e,t);if(this.log(`Read ${i.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),i.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=i.length;else{let o=await this.writer.upsert(e.localTable,i);r.recordsSynced=o}r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?ae.resolve(this.config.targetDb):ae.resolve(j(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Y.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Y.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${d(r)}`,"warn")}}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function ce(l){return new X(l)}async function qe(l){let e=ce({...l,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function Le(l,e){let t=ce({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(l)}finally{await t.close()}}z();ue();ee();import{join as be}from"path";import{existsSync as Ie,mkdirSync as ze}from"fs";var K=class{memoryCache;maxSize;ttl;persistent;compression;db=null;storagePath;useUnified;unifiedMemory=null;pendingWrites=[];dbInitializing=!1;constructor(e={}){this.maxSize=e.maxSize||1e4,this.ttl=e.ttl||0,this.persistent=e.persistent??!0,this.compression=e.compression??!0,this.useUnified=e.useUnified??!0,this.storagePath=e.storagePath||be(j(),".agentic-qe","embeddings-cache.db"),this.memoryCache=new Map;let t=["text","code","test","coverage","defect"];for(let n of t)this.memoryCache.set(n,new Map);this.persistent&&this.initializePersistentStorage()}initializePersistentStorage(){try{if(this.useUnified)this.unifiedMemory=de(),this.dbInitializing=!0,this.unifiedMemory.initialize().then(()=>{this.db=this.unifiedMemory.getDatabase(),this.dbInitializing=!1,console.log(`[EmbeddingCache] Using unified storage: ${this.unifiedMemory.getDbPath()}`),this.loadFromDisk(),this.flushPendingWrites()}).catch(e=>{console.warn("[EmbeddingCache] Failed to initialize unified storage:",e),this.db=null,this.dbInitializing=!1,this.unifiedMemory=null,this.pendingWrites=[]});else{let e=be(this.storagePath,"..");Ie(e)||ze(e,{recursive:!0}),this.db=T(this.storagePath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.exec(`
8
+ AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(s=>s.column_name);for(let s of t)if(o.includes(s))return s;return o[0]||null}catch{return null}}};function ie(l){return new Q(l)}z();k();P();v();import*as ye from"fs";var D=b.create("sqlite-writer"),V=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!ye.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=T(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),D.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=w(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return D.debug(`No columns found for table ${e}`),0;let i=new Set(r),o=0;for(let s=0;s<t.length;s+=this.batchSize){let a=t.slice(s,s+this.batchSize);try{let c=this.upsertBatch(n,a,i);o+=c}catch(c){let u=Math.floor(s/this.batchSize)+1;D.debug(`Batch ${u} failed for ${e}, retrying individually`,{error:d(c)});let p=0;for(let m of a)try{p+=this.upsertBatch(n,[m],i)}catch(g){let h=m.id||m.key||"?";D.debug(`Skipped record ${String(h).slice(0,50)} in ${e}`,{error:d(g)})}o+=p}}return o}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=w(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,D.debug("SQLite writer closed"))}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(i=>i.pk>0).sort((i,o)=>i.pk-o.pk).map(i=>i.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],i=Object.keys(r).filter(g=>n.has(g));if(i.length===0)return 0;let o=i.map(E),s=i.map(()=>"?").join(", "),a=e.replace(/"/g,""),c=this.getPrimaryKeyColumns(a),u;if(c.length>0){let g=c.map(E),h=i.filter(y=>!c.includes(y));if(h.length>0){let y=h.map(f=>`${E(f)} = excluded.${E(f)}`).join(", ");u=`INSERT INTO ${e} (${o.join(", ")}) VALUES (${s}) ON CONFLICT(${g.join(", ")}) DO UPDATE SET ${y}`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`;let p=this.db.prepare(u);return this.db.transaction(g=>{let h=0;for(let y of g){let f=i.map(S=>this.serializeValue(y[S]));p.run(...f),h++}return h})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function oe(l){return new V(l)}v();P();var Ne=b.create("sync-agent"),H=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...x,...e,local:{...x.local,...e.local},cloud:{...x.cloud,...e.cloud},sync:{...x.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let i=await this.syncSource(r);this.report.results.push(i),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let i=await this.syncSourceIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let i=await r.readAll();if(this.log(`Read ${i.length} records from ${e.name}`),i.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let o=await this.writer.upsert(e.targetTable,i,{skipIfExists:e.mode==="append"});n.recordsSynced=o}else n.recordsSynced=i.length,this.log(`[DRY RUN] Would sync ${i.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let i=this.readers.get(e.name);if(!i)throw new Error(`Reader not found: ${e.name}`);let o=await i.readChanged(t);if(this.log(`Read ${o.length} changed records from ${e.name} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o);r.recordsSynced=s}else r.recordsSynced=o.length;r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),i=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let o=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),i=o[0]?.count||0}catch(o){try{await this.writer.rollback()}catch{}Ne.debug("Cloud count query failed",{source:t.name,error:o instanceof Error?o.message:String(o)}),i=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:i,match:r===i,diff:r-i})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?re({source:e,baseDir:t,environment:n}):e.type==="json"?ne({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=$(this.config.cloud);this.writer=O({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function se(l){return new H(l)}async function Oe(l){let e=se({...l,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function De(l,e){let t=se({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(l)}finally{await t.close()}}import*as Y from"fs";import*as ae from"path";ue();P();v();var Lt=b.create("pull-agent"),X=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...A,...e,cloud:{...A.cloud,...e.cloud},sources:e.sources||A.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=$(this.config.cloud);this.cloudWriter=O({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=ie({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=oe({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let i=await this.pullTableIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let i=await this.writer.upsert(e.localTable,r);n.recordsSynced=i,n.recordsSkipped=r.length-i}n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let i=await this.reader.readChanged(e,t);if(this.log(`Read ${i.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),i.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=i.length;else{let o=await this.writer.upsert(e.localTable,i);r.recordsSynced=o}r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?ae.resolve(this.config.targetDb):ae.resolve(j(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Y.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Y.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${d(r)}`,"warn")}}createReport(e){return{syncId:I(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function ce(l){return new X(l)}async function qe(l){let e=ce({...l,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function Le(l,e){let t=ce({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(l)}finally{await t.close()}}z();ue();ee();import{join as be}from"path";import{existsSync as Ie,mkdirSync as ze}from"fs";var K=class{memoryCache;maxSize;ttl;persistent;compression;db=null;storagePath;useUnified;unifiedMemory=null;pendingWrites=[];dbInitializing=!1;constructor(e={}){this.maxSize=e.maxSize||1e4,this.ttl=e.ttl||0,this.persistent=e.persistent??!0,this.compression=e.compression??!0,this.useUnified=e.useUnified??!0,this.storagePath=e.storagePath||be(j(),".agentic-qe","embeddings-cache.db"),this.memoryCache=new Map;let t=["text","code","test","coverage","defect"];for(let n of t)this.memoryCache.set(n,new Map);this.persistent&&this.initializePersistentStorage()}initializePersistentStorage(){try{if(this.useUnified)this.unifiedMemory=de(),this.dbInitializing=!0,this.unifiedMemory.initialize().then(()=>{this.db=this.unifiedMemory.getDatabase(),this.dbInitializing=!1,console.log(`[EmbeddingCache] Using unified storage: ${this.unifiedMemory.getDbPath()}`),this.loadFromDisk(),this.flushPendingWrites()}).catch(e=>{console.warn("[EmbeddingCache] Failed to initialize unified storage:",e),this.db=null,this.dbInitializing=!1,this.unifiedMemory=null,this.pendingWrites=[]});else{let e=be(this.storagePath,"..");Ie(e)||ze(e,{recursive:!0}),this.db=T(this.storagePath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.exec(`
9
9
  CREATE TABLE IF NOT EXISTS embeddings (
10
10
  key TEXT NOT NULL,
11
11
  namespace TEXT NOT NULL,
@@ -26,4 +26,4 @@ import{o as me}from"./chunk-EQBEGDTG.js";import{b as w,c as E,d as A,f as j,k as
26
26
  INSERT OR REPLACE INTO embeddings
27
27
  (key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
28
28
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
29
- `).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",r)}}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Te();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8";this.model=await me("feature-extraction",this.config.model,{dtype:n,progress_callback:r=>{r.status==="progress"&&typeof r.progress=="number"&&console.log(`Downloading model: ${(r.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:le(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(i=>Math.fround(i)));case"int8":let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(i=>Math.round(i/n*127)));case"binary":let r=new Uint8Array(Math.ceil(e.length/8));for(let i=0;i<e.length;i++)e[i]>=0&&(r[Math.floor(i/8)]|=1<<i%8);return r;default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();A();P();ee();v();import{resolve as je,dirname as Fe}from"path";import{fileURLToPath as We}from"url";var Se=b.create("sync-embedding-generator"),Ue=We(import.meta.url),Be=Fe(Ue),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||je(Be,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){Se.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){Se.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function we(l){return new q(l)}export{k as a,Pe as b,x as c,W as d,re as e,U as f,ne as g,M as h,ke as i,B as j,$ as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,Oe as t,De as u,X as v,ce as w,qe as x,Le as y,q as z,we as A};
29
+ `).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,Date.now())}catch(r){console.warn("Failed to persist embedding:",r)}}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Te();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8";this.model=await me("feature-extraction",this.config.model,{dtype:n,progress_callback:r=>{r.status==="progress"&&typeof r.progress=="number"&&console.log(`Downloading model: ${(r.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:le(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(n=>Math.fround(n)));case"int8":{let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(r=>Math.round(r/n*127)))}case"binary":{let n=new Uint8Array(Math.ceil(e.length/8));for(let r=0;r<e.length;r++)e[r]>=0&&(n[Math.floor(r/8)]|=1<<r%8);return n}default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();k();P();ee();v();import{resolve as je,dirname as Fe}from"path";import{fileURLToPath as We}from"url";var Se=b.create("sync-embedding-generator"),Ue=We(import.meta.url),Be=Fe(Ue),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||je(Be,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){Se.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){Se.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function we(l){return new q(l)}export{A as a,Pe as b,x as c,W as d,re as e,U as f,ne as g,M as h,Ae as i,B as j,$ as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,Oe as t,De as u,X as v,ce as w,qe as x,Le as y,q as z,we as A};
@@ -1,6 +1,6 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.2");process.exit(0)}
2
- import{e as x,f as C,j as y,k as R,q as F}from"./chunk-UUFOHMUG.js";import{b as I,c as k}from"./chunk-XPCNUX2U.js";import{c as w}from"./chunk-ORF2UKQH.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
3
- Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-FLUQO4IF.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
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{e as x,f as C,j as y,k as R,q as F}from"./chunk-3HBWDG62.js";import{b as I,c as k}from"./chunk-3LRK7PYN.js";import{c as w}from"./chunk-CAMEFWRK.js";var P,S=w(()=>{"use strict";P={enabled:!0,headless:!0,timeout:3e4,retryAttempts:3,fallbackEnabled:!0,browserType:"chromium",viewport:{width:1280,height:720},userAgent:"",devtools:!1,slowMo:0,screenshotDir:".agentic-qe/screenshots"}});function B(i){return i instanceof o}function a(i,e="Unknown Vibium error"){return B(i)?i:i instanceof Error?new o(i.message||e,"UNKNOWN_ERROR",i):new o(typeof i=="string"?i:e,"UNKNOWN_ERROR")}var o,c,f,g,l,p,m,b,A=w(()=>{"use strict";o=class i extends Error{constructor(t,r,s){super(t);this.code=r;this.cause=s;this.name="VibiumError",Error.captureStackTrace&&Error.captureStackTrace(this,i),s?.stack&&(this.stack+=`
3
+ Caused by: ${s.stack}`)}code;cause},c=class extends o{constructor(e="Vibium MCP server is unavailable",t){super(e,"VIBIUM_UNAVAILABLE",t),this.name="VibiumUnavailableError"}},f=class extends o{constructor(e="Browser operation timed out",t){super(e,"VIBIUM_TIMEOUT",t),this.name="VibiumTimeoutError"}},g=class extends o{selector;constructor(e,t){super(`Element not found: ${e}`,"ELEMENT_NOT_FOUND",t),this.name="VibiumElementNotFoundError",this.selector=e}},l=class extends o{constructor(e="Failed to connect to browser",t){super(e,"CONNECTION_ERROR",t),this.name="VibiumConnectionError"}},p=class extends o{url;statusCode;constructor(e,t,r){let s=t?`Navigation failed: ${e} (HTTP ${t})`:`Navigation failed: ${e}`;super(s,"NAVIGATION_ERROR",r),this.name="VibiumNavigationError",this.url=e,this.statusCode=t}},m=class extends o{constructor(e="Failed to capture screenshot",t){super(e,"SCREENSHOT_ERROR",t),this.name="VibiumScreenshotError"}},b=class extends o{action;selector;constructor(e,t,r){super(`Failed to ${e} element: ${t}`,"INTERACTION_ERROR",r),this.name="VibiumInteractionError",this.action=e,this.selector=t}}});import{randomUUID as _}from"crypto";async function V(){if(v!==null)return v;try{return v=(await import("./vibium-ZOOS3W5L.js")).browser,O=!0,v}catch(i){return console.warn("[Vibium] Failed to load vibium package:",i),O=!1,null}}async function T(i,e,t){let r;for(let s=1;s<=e;s++)try{return await i()}catch(n){if(r=I(n),s<e){let u=Math.min(100*Math.pow(2,s-1),2e3);await new Promise(d=>setTimeout(d,u))}}throw new o(`${t} failed after ${e} attempts`,"RETRY_EXHAUSTED",r)}async function h(i,e){let t=Date.now();try{let r=await i();return R()&&console.log(`[Vibium] ${e}: ${Date.now()-t}ms`),r}catch(r){throw R()&&console.log(`[Vibium] ${e} failed: ${Date.now()-t}ms`,r),r}}var v,O,E,N,M=w(()=>{S();A();k();F();v=null,O=!1;E=class{config;currentSession=null;lastHealthCheck=null;_initialized=!1;_available=null;vibeInstance=null;constructor(e={}){this.config={...P,...e}}async isAvailable(){if(!this.config.enabled)return!1;if(this._available!==null)return this._available;try{let e=await V();return this._available=e!==null,this._available}catch{return this._available=!1,!1}}async getHealth(){let e=new Date;if(!this.config.enabled)return{status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium is disabled by configuration",sessionActive:!1};try{await this.isAvailable()?this.lastHealthCheck={status:this.vibeInstance?"connected":"disconnected",version:"0.1.2",browserType:this.config.browserType,features:["browser-launch","navigation","element-interaction","screenshots","script-evaluation","accessibility-testing"],latencyMs:10,lastChecked:e,sessionActive:this.vibeInstance!==null}:this.lastHealthCheck={status:"unavailable",features:["fallback-only"],lastChecked:e,error:"Vibium package not available - install with: npm install vibium",sessionActive:!1}}catch(t){this.lastHealthCheck={status:"error",features:["fallback-only"],lastChecked:e,error:t instanceof Error?t.message:"Unknown error",sessionActive:!1}}return this.lastHealthCheck}async getSession(){return this.currentSession}async launch(e){if(!x())return{success:!1,error:new c("Browser mode is disabled by feature flags")};let t=async()=>{let r=await V();if(!r)throw new c("Vibium package not available. Install with: npm install vibium");let s=e?.headless??this.config.headless;this.vibeInstance=await r.launch({headless:s});let n={id:this.generateSessionId(),browserType:this.config.browserType,launchedAt:new Date,status:"connected",viewport:e?.viewport??this.config.viewport,headless:s};return this.currentSession=n,n};try{return{success:!0,value:y()?await T(()=>h(t,"browser_launch"),this.config.retryAttempts,"browser_launch"):await h(t,"browser_launch")}}catch(r){return{success:!1,error:a(r,"Failed to launch browser")}}}async quit(){if(!this.vibeInstance)return{success:!1,error:new l("No active browser session")};let e=async()=>{this.vibeInstance&&(await this.vibeInstance.quit(),this.vibeInstance=null),this.currentSession=null};try{return await h(e,"browser_quit"),{success:!0,value:void 0}}catch(t){return{success:!1,error:a(t,"Failed to quit browser")}}}async navigate(e){this.ensureSession();let t=async()=>{let r=Date.now();await this.vibeInstance.go(e.url);let s="";try{s=await this.vibeInstance.evaluate("document.title")}catch{s="Unknown"}let n={url:e.url,statusCode:200,title:s,durationMs:Date.now()-r,success:!0};return this.currentSession&&(this.currentSession.currentUrl=e.url),n};try{return{success:!0,value:y()?await T(()=>h(t,"page_navigate"),this.config.retryAttempts,"page_navigate"):await h(t,"page_navigate")}}catch(r){return{success:!1,error:new p(e.url,void 0,r instanceof Error?r:void 0)}}}async getPageInfo(){this.ensureSession();try{let e=await this.vibeInstance.evaluate("window.location.href"),t=await this.vibeInstance.evaluate("document.title");return{success:!0,value:{url:e,title:t,viewport:this.config.viewport,loadState:"loaded"}}}catch(e){return{success:!1,error:a(e,"Failed to get page info")}}}async goBack(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.back()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go back")}}}async goForward(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.history.forward()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to go forward")}}}async reload(){this.ensureSession();try{return await this.vibeInstance.evaluate("window.location.reload()"),{success:!0,value:void 0}}catch(e){return{success:!1,error:a(e,"Failed to reload page")}}}async findElement(e){this.ensureSession();try{let t=await this.vibeInstance.find(e.selector,{timeout:e.timeout??this.config.timeout});return{success:!0,value:{selector:e.selector,tagName:t.info.tag,textContent:t.info.text,attributes:{},boundingBox:t.info.box,visible:!0,enabled:!0}}}catch(t){return{success:!1,error:new g(e.selector,t instanceof Error?t:void 0)}}}async findElements(e){this.ensureSession();try{let t=e.selector.replace(/\\/g,"\\\\").replace(/'/g,"\\'");return{success:!0,value:(await this.vibeInstance.evaluate(`
4
4
  Array.from(document.querySelectorAll('${t}'))
5
5
  .map(el => ({
6
6
  tag: el.tagName.toLowerCase(),
@@ -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.2");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.3");process.exit(0)}
2
2
  import{existsSync as _,readdirSync as d,statSync as w}from"fs";import{join as i,extname as E}from"path";var T=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"]),v=[".test.",".spec.","_test.","_spec."],b=new Set(["node_modules","dist","build","coverage",".git","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".next",".nuxt",".output"]);function O(s,p={}){let{maxDepth:f=6,includeTests:m=!1,testsOnly:x=!1,extraExtensions:S=[]}=p;if(!_(s))return[];let o=w(s);if(o.isFile())return[s];if(!o.isDirectory())return[];let y=new Set(S.map(t=>t.startsWith(".")?t:`.${t}`)),n=[];function r(t,c){if(c>f)return;let a;try{a=d(t,{withFileTypes:!0})}catch{return}for(let e of a)if(e.isDirectory()){if(b.has(e.name))continue;r(i(t,e.name),c+1)}else if(e.isFile()){let u=E(e.name).toLowerCase();if(!(T.has(u)||y.has(u))||e.name.endsWith(".d.ts"))continue;let l=v.some(h=>e.name.includes(h))||e.name.startsWith("test_");x?l&&n.push(i(t,e.name)):(m||!l)&&n.push(i(t,e.name))}}return r(s,0),n}export{T as a,O as b};