agentic-qe 3.10.1 → 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 (412) hide show
  1. package/.claude/hooks/README.txt +17 -0
  2. package/.claude/hooks/aqe-hook.cjs +98 -0
  3. package/.claude/hooks/cross-phase-memory.yaml +296 -0
  4. package/.claude/hooks/post-task-sync.sh +113 -0
  5. package/.claude/hooks/v3-domain-workers.json +121 -0
  6. package/.claude/skills/release/SKILL.md +10 -10
  7. package/.claude/skills/skills-manifest.json +1 -1
  8. package/CHANGELOG.md +131 -0
  9. package/assets/grammars/tree-sitter-c_sharp.wasm +0 -0
  10. package/assets/grammars/tree-sitter-java.wasm +0 -0
  11. package/assets/grammars/tree-sitter-javascript.wasm +0 -0
  12. package/assets/grammars/tree-sitter-python.wasm +0 -0
  13. package/assets/grammars/tree-sitter-rust.wasm +0 -0
  14. package/assets/grammars/tree-sitter-swift.wasm +0 -0
  15. package/assets/grammars/tree-sitter-tsx.wasm +0 -0
  16. package/assets/grammars/tree-sitter-typescript.wasm +0 -0
  17. package/assets/skills/skills-manifest.json +1 -1
  18. package/dist/agents/claim-verifier/claim-verifier-service.js +4 -2
  19. package/dist/agents/claim-verifier/verifiers/test-verifier.js +31 -23
  20. package/dist/agents/devils-advocate/agent.js +1 -1
  21. package/dist/cli/bundle.js +5 -5
  22. package/dist/cli/chunks/adapter-BHPUKMJ5.js +2 -0
  23. package/dist/cli/chunks/{agent-booster-wasm-FZLWOPSX.js → agent-booster-wasm-NGC6LSQP.js} +2 -2
  24. package/dist/cli/chunks/{agent-handler-KAGRVCKS.js → agent-handler-P2IJE4GK.js} +2 -2
  25. package/dist/cli/chunks/{agent-memory-branch-JJKFEXQW.js → agent-memory-branch-JXRJ5GKQ.js} +2 -2
  26. package/dist/cli/chunks/aqe-learning-engine-JQ5WD2HM.js +2 -0
  27. package/dist/cli/chunks/{audit-DN5SY4JJ.js → audit-BMQ3VESB.js} +2 -2
  28. package/dist/cli/chunks/base-E32WLGY2.js +2 -0
  29. package/dist/cli/chunks/{hnswlib-node-YX6OOBN6.js → better-sqlite3-HP4JZS6K.js} +2 -2
  30. package/dist/cli/chunks/{brain-handler-O7MP5BGY.js → brain-handler-SACNDFSW.js} +3 -3
  31. package/dist/cli/chunks/{branch-enumerator-ZPTN5J6V.js → branch-enumerator-LFOTVUDA.js} +2 -2
  32. package/dist/cli/chunks/{browser-PAZE2JSD.js → browser-FK7PRF3W.js} +2 -2
  33. package/dist/cli/chunks/browser-workflow-LNNXXAJG.js +2 -0
  34. package/dist/cli/chunks/{chunk-BF7MUYWC.js → chunk-2EQVYYBF.js} +2 -2
  35. package/dist/cli/chunks/{chunk-BGBSYF3K.js → chunk-2L73WXA4.js} +2 -2
  36. package/dist/cli/chunks/{chunk-W2DT3CDE.js → chunk-2ULVCLOW.js} +2 -2
  37. package/dist/cli/chunks/{chunk-FJSR2U65.js → chunk-3HBWDG62.js} +2 -2
  38. package/dist/cli/chunks/{chunk-WPNZSL4S.js → chunk-3JAOFKEU.js} +2 -2
  39. package/dist/cli/chunks/{chunk-2TDWCXZ6.js → chunk-3LRK7PYN.js} +2 -2
  40. package/dist/cli/chunks/{chunk-MVGVD6LS.js → chunk-3RZL4QTT.js} +2 -2
  41. package/dist/cli/chunks/chunk-3VF3HCG4.js +2 -0
  42. package/dist/cli/chunks/{chunk-6E7GI2UB.js → chunk-3X2ZQ55B.js} +4 -4
  43. package/dist/cli/chunks/{chunk-6QFONVEE.js → chunk-4CYLSXA6.js} +2 -2
  44. package/dist/cli/chunks/{chunk-VOIWDPIU.js → chunk-4OUAHZX2.js} +2 -2
  45. package/dist/cli/chunks/{chunk-EIROAH6N.js → chunk-4QFAUSWQ.js} +2 -2
  46. package/dist/cli/chunks/{chunk-ZEMXMDD3.js → chunk-5ER3COX3.js} +2 -2
  47. package/dist/cli/chunks/{chunk-ECPB7IAH.js → chunk-5EWWA4QP.js} +4 -4
  48. package/dist/cli/chunks/{chunk-AUVC3DDB.js → chunk-5G5AAEFF.js} +2 -2
  49. package/dist/cli/chunks/{chunk-RRLQFFCO.js → chunk-5IBJURYB.js} +3 -3
  50. package/dist/cli/chunks/chunk-5LON3MLI.js +2 -0
  51. package/dist/cli/chunks/{chunk-WMG5F6R6.js → chunk-5SGEOO2F.js} +2 -2
  52. package/dist/cli/chunks/{chunk-SQBB2DC6.js → chunk-6B4S7PKP.js} +3 -3
  53. package/dist/cli/chunks/{chunk-H44WD7QX.js → chunk-6FL3GN4T.js} +2 -2
  54. package/dist/cli/chunks/{chunk-7MSYTHZM.js → chunk-6GCOIIHY.js} +2 -2
  55. package/dist/cli/chunks/{chunk-KKNBYXYA.js → chunk-6Q2PPOOF.js} +1 -1
  56. package/dist/cli/chunks/{chunk-K4T3RDCB.js → chunk-6ZK24V2Y.js} +2 -2
  57. package/dist/cli/chunks/{chunk-G3BQU3Q6.js → chunk-72LE6PHL.js} +3 -3
  58. package/dist/cli/chunks/{chunk-F3OVFA6W.js → chunk-7RMZAVGO.js} +2 -2
  59. package/dist/cli/chunks/{chunk-YYWIA5FX.js → chunk-7SEHQTYD.js} +1 -1
  60. package/dist/cli/chunks/{chunk-UU2Q6XWF.js → chunk-7YYTTWGY.js} +1 -1
  61. package/dist/cli/chunks/{chunk-XKOKMS5A.js → chunk-7ZSPCGTI.js} +2 -2
  62. package/dist/cli/chunks/{chunk-RWYW573C.js → chunk-ADV4DH3W.js} +5 -5
  63. package/dist/cli/chunks/{chunk-OC3OJWLB.js → chunk-AEJVOJPT.js} +2 -2
  64. package/dist/cli/chunks/{chunk-2UN4DOBJ.js → chunk-B5MMDMH6.js} +2 -2
  65. package/dist/cli/chunks/{chunk-WQEZKAUR.js → chunk-BO2OV2RH.js} +2 -2
  66. package/dist/cli/chunks/{chunk-NPSBMDVU.js → chunk-BT3QLWII.js} +2 -2
  67. package/dist/cli/chunks/{chunk-6VQ5MFJ6.js → chunk-BWP3UVPE.js} +7 -7
  68. package/dist/cli/chunks/{chunk-SLNGJW4G.js → chunk-C6BBRM2J.js} +1 -1
  69. package/dist/cli/chunks/{chunk-4AWJ5PE4.js → chunk-CAMEFWRK.js} +1 -1
  70. package/dist/cli/chunks/{chunk-BECU52UY.js → chunk-CNEWYJKT.js} +4 -4
  71. package/dist/cli/chunks/{chunk-EO4B5GS4.js → chunk-CTDO2UB2.js} +1 -1
  72. package/dist/cli/chunks/{chunk-GTGONWGX.js → chunk-D2FBUOAR.js} +1 -1
  73. package/dist/cli/chunks/{chunk-OQP5OFRR.js → chunk-DF3MJ2YL.js} +1 -1
  74. package/dist/cli/chunks/{chunk-KEC5FBAW.js → chunk-DY5KEOHX.js} +1 -1
  75. package/dist/cli/chunks/{chunk-EBQ6YKP2.js → chunk-E2BJT6A7.js} +3 -3
  76. package/dist/cli/chunks/{chunk-WDTCCPK4.js → chunk-EETVN2OJ.js} +1 -1
  77. package/dist/cli/chunks/{chunk-UDVX34ZG.js → chunk-ERYMAYJW.js} +20 -17
  78. package/dist/cli/chunks/{chunk-ELUERFGA.js → chunk-FJGSEPFL.js} +2 -2
  79. package/dist/cli/chunks/{chunk-BN7ERYXI.js → chunk-FLTPHVZ3.js} +1 -1
  80. package/dist/cli/chunks/{chunk-OVENSL64.js → chunk-FND6V2RV.js} +22 -22
  81. package/dist/cli/chunks/{chunk-5ZCVMR5E.js → chunk-FU77CDEM.js} +2 -2
  82. package/dist/cli/chunks/{chunk-VKRMVTWU.js → chunk-GELF4ILR.js} +37 -37
  83. package/dist/cli/chunks/{chunk-H22MMMYY.js → chunk-GHNNJHH3.js} +2 -2
  84. package/dist/cli/chunks/{chunk-32R7EA7B.js → chunk-GJUGSH7T.js} +3 -3
  85. package/dist/cli/chunks/{chunk-HPNEZ7YN.js → chunk-GL3HZN3O.js} +1 -1
  86. package/dist/cli/chunks/{chunk-WL2J6ECN.js → chunk-H56AROF2.js} +2 -2
  87. package/dist/cli/chunks/{chunk-GTRXZJNX.js → chunk-HAO3SPOE.js} +2 -2
  88. package/dist/cli/chunks/{chunk-PUXDXIUE.js → chunk-HM523MTQ.js} +1 -1
  89. package/dist/cli/chunks/{chunk-KRXKU54J.js → chunk-HMFEPKAR.js} +2 -2
  90. package/dist/cli/chunks/{chunk-3YOPJ7DY.js → chunk-HQJMCTWN.js} +2 -2
  91. package/dist/cli/chunks/{chunk-LF7URN2X.js → chunk-HRLXU4LH.js} +2 -2
  92. package/dist/cli/chunks/{chunk-TL5F2S3Z.js → chunk-HWM2XJ3P.js} +24 -24
  93. package/dist/cli/chunks/{chunk-6A2NIR2E.js → chunk-I42R57ON.js} +2 -2
  94. package/dist/cli/chunks/chunk-IL2KOW5W.js +2 -0
  95. package/dist/cli/chunks/{chunk-CR4ERDS2.js → chunk-IRR7YA3Q.js} +2 -2
  96. package/dist/cli/chunks/{chunk-Y2DPXMOR.js → chunk-JD2PG4KS.js} +1 -1
  97. package/dist/cli/chunks/{chunk-TFNLXAK5.js → chunk-JE3C7JYN.js} +1 -1
  98. package/dist/cli/chunks/{chunk-ZTMWJQTZ.js → chunk-JLL27IGU.js} +2 -2
  99. package/dist/cli/chunks/{chunk-YPOTBXPU.js → chunk-JOLDCS6X.js} +2 -2
  100. package/dist/cli/chunks/chunk-JP63XACW.js +62 -0
  101. package/dist/cli/chunks/{chunk-AABKTWXC.js → chunk-JSFYPLMQ.js} +2 -2
  102. package/dist/cli/chunks/{chunk-KCTH5MHE.js → chunk-JTF6D2RJ.js} +4 -4
  103. package/dist/cli/chunks/{chunk-GRG3OP34.js → chunk-JTZ3Q2QS.js} +2 -2
  104. package/dist/cli/chunks/chunk-JXIPRMAY.js +95 -0
  105. package/dist/cli/chunks/{chunk-TNGGVMPQ.js → chunk-KG5SM36Y.js} +1 -1
  106. package/dist/cli/chunks/{chunk-QNW335PD.js → chunk-KTRB3L53.js} +2 -2
  107. package/dist/cli/chunks/{chunk-XRK7FBTY.js → chunk-L74CHKFR.js} +2 -2
  108. package/dist/cli/chunks/{chunk-IHDUWPFY.js → chunk-LZ6TNTGO.js} +2 -2
  109. package/dist/cli/chunks/{chunk-Y357YFLF.js → chunk-M5CDW2ZH.js} +2 -2
  110. package/dist/cli/chunks/{chunk-GRYXNWPF.js → chunk-MBSJ5G4I.js} +12 -12
  111. package/dist/cli/chunks/{chunk-IPRDHKSI.js → chunk-MC7K44M4.js} +2 -2
  112. package/dist/cli/chunks/{chunk-TP77PNN6.js → chunk-MQOFFRTA.js} +2 -2
  113. package/dist/cli/chunks/{chunk-JLKHPIQF.js → chunk-N7IBYDW5.js} +1 -1
  114. package/dist/cli/chunks/{chunk-G5DTENO3.js → chunk-NEYYLAYS.js} +5 -5
  115. package/dist/cli/chunks/{chunk-TNVYKYTO.js → chunk-NNVXHC74.js} +3 -3
  116. package/dist/cli/chunks/{chunk-HRDGN3OK.js → chunk-NNZMEYLT.js} +1 -1
  117. package/dist/cli/chunks/{chunk-25QGPRWN.js → chunk-NRCL3WCP.js} +2 -2
  118. package/dist/cli/chunks/{chunk-NRLT44YB.js → chunk-NXPFGPHV.js} +1 -1
  119. package/dist/cli/chunks/{chunk-PXFQSVA2.js → chunk-NZHOKLII.js} +3 -3
  120. package/dist/cli/chunks/{chunk-7SQD2TTQ.js → chunk-OG7CWWFR.js} +1 -1
  121. package/dist/cli/chunks/{chunk-XGUQYVJR.js → chunk-OPDTDKN3.js} +2 -2
  122. package/dist/cli/chunks/{chunk-2KTRRSKD.js → chunk-OX4R55T3.js} +2 -2
  123. package/dist/cli/chunks/{chunk-COZDJLIL.js → chunk-PFCAMX6H.js} +1 -1
  124. package/dist/cli/chunks/{chunk-UDFLR7GR.js → chunk-PL5SLO2W.js} +1 -1
  125. package/dist/cli/chunks/{chunk-6ZRMQXVL.js → chunk-PZHZPX3O.js} +4 -4
  126. package/dist/cli/chunks/{chunk-57NJQV57.js → chunk-Q7EBD24B.js} +1 -1
  127. package/dist/cli/chunks/{chunk-6D57DWQ6.js → chunk-QEODION5.js} +2 -2
  128. package/dist/cli/chunks/{chunk-K22TPWOJ.js → chunk-QM65UGPV.js} +2 -2
  129. package/dist/cli/chunks/{chunk-2ETDES5W.js → chunk-QWG76RHA.js} +2 -2
  130. package/dist/cli/chunks/{chunk-GXJ4BCGC.js → chunk-R5ONQAQL.js} +2 -2
  131. package/dist/cli/chunks/{chunk-KZJXVIAW.js → chunk-RNF47IJ5.js} +4 -4
  132. package/dist/cli/chunks/{chunk-IK6AJX3C.js → chunk-RTDHWOAG.js} +1 -1
  133. package/dist/cli/chunks/{chunk-NQZYUH6S.js → chunk-RZCAA2PZ.js} +1 -1
  134. package/dist/cli/chunks/{chunk-DQIS6J77.js → chunk-SL6YZAT4.js} +2 -2
  135. package/dist/cli/chunks/{chunk-RPL6K623.js → chunk-SNTMAVPH.js} +5 -5
  136. package/dist/cli/chunks/{chunk-MQYTW2IN.js → chunk-SWOG3PBD.js} +2 -2
  137. package/dist/cli/chunks/{chunk-DMIYWPQQ.js → chunk-T63EK6GH.js} +2 -2
  138. package/dist/cli/chunks/chunk-U6UK3UMX.js +59 -0
  139. package/dist/cli/chunks/{chunk-2S4XHK26.js → chunk-U7NMPZE2.js} +2 -2
  140. package/dist/cli/chunks/{chunk-WS4XVJHI.js → chunk-UDV4YB42.js} +1 -1
  141. package/dist/cli/chunks/{chunk-P7T5Y735.js → chunk-UHDBM7QS.js} +2 -2
  142. package/dist/cli/chunks/{chunk-5EU2VQK3.js → chunk-UIJFU4KD.js} +2 -2
  143. package/dist/cli/chunks/{chunk-Q24OJX44.js → chunk-USFZ4IJD.js} +2 -2
  144. package/dist/cli/chunks/{chunk-Q5VHBI4U.js → chunk-UZL366ZI.js} +1 -1
  145. package/dist/cli/chunks/{chunk-GMKGLZJU.js → chunk-VDTFRMES.js} +2 -2
  146. package/dist/cli/chunks/{chunk-EUJHHXE6.js → chunk-VIWIO27R.js} +3 -3
  147. package/dist/cli/chunks/{chunk-PLRSKAFZ.js → chunk-VRXY4T22.js} +2 -2
  148. package/dist/cli/chunks/{chunk-NDCPEXDN.js → chunk-WPVCSFDA.js} +2 -2
  149. package/dist/cli/chunks/{chunk-TX7SNQKL.js → chunk-WWD5IWTV.js} +1 -1
  150. package/dist/cli/chunks/{chunk-T3UXMPXX.js → chunk-X2B7SANM.js} +1 -1
  151. package/dist/cli/chunks/{chunk-7CKVAYP3.js → chunk-X3RJ6SFC.js} +1 -1
  152. package/dist/cli/chunks/{chunk-6LRCMFLV.js → chunk-XTP2GHI7.js} +2 -2
  153. package/dist/cli/chunks/{chunk-W6ZF2CPN.js → chunk-YDDZJCKY.js} +1 -1
  154. package/dist/cli/chunks/{chunk-5KFCH7RH.js → chunk-YDKYLNKZ.js} +1 -1
  155. package/dist/cli/chunks/{chunk-ELZ67OHQ.js → chunk-YIYV2JB6.js} +2 -2
  156. package/dist/cli/chunks/{chunk-PW6MOFXG.js → chunk-YX2HY4MX.js} +2 -2
  157. package/dist/cli/chunks/{chunk-DVOH75S4.js → chunk-YXH2CVAF.js} +1 -1
  158. package/dist/cli/chunks/{chunk-IITKJCPK.js → chunk-YYAPO3CU.js} +3 -3
  159. package/dist/cli/chunks/{chunk-5OTYBWRL.js → chunk-Z2K5IZM6.js} +2 -2
  160. package/dist/cli/chunks/{chunk-NOCYYXK4.js → chunk-ZG4P3DTL.js} +2 -2
  161. package/dist/cli/chunks/{chunk-YGRTMAWB.js → chunk-ZXQNE4QV.js} +1 -1
  162. package/dist/cli/chunks/{ci-EHRUN7O6.js → ci-AWZ3S5OT.js} +6 -6
  163. package/dist/cli/chunks/{ci-output-EXDXVXKB.js → ci-output-JLCYTIMT.js} +2 -2
  164. package/dist/cli/chunks/{circuit-breaker-LM4QRAAL.js → circuit-breaker-BJDKBDIL.js} +2 -2
  165. package/dist/cli/chunks/{claude-flow-setup-ZHUCZVW7.js → claude-flow-setup-KKOP5ZMO.js} +2 -2
  166. package/dist/cli/chunks/client-2UKBYFX4.js +2 -0
  167. package/dist/cli/chunks/{cline-installer-WMFLQOW2.js → cline-installer-7M525SEA.js} +2 -2
  168. package/dist/cli/chunks/{code-L7KRLU5E.js → code-27SUVJDO.js} +20 -19
  169. package/dist/cli/chunks/{code-index-extractor-FTMUYQC6.js → code-index-extractor-TTQQZLAK.js} +2 -2
  170. package/dist/cli/chunks/{codex-installer-B3F6WI3Z.js → codex-installer-GHNGNPKP.js} +2 -2
  171. package/dist/cli/chunks/{completions-3JZQRNB6.js → completions-JPJD24DG.js} +2 -2
  172. package/dist/cli/chunks/{complexity-analyzer-LB2FFEKX.js → complexity-analyzer-Q74EJV33.js} +2 -2
  173. package/dist/cli/chunks/{continuedev-installer-WH6IMV7R.js → continuedev-installer-ULTRDIML.js} +2 -2
  174. package/dist/cli/chunks/{copilot-installer-NOIEOFJM.js → copilot-installer-EK52X4CG.js} +2 -2
  175. package/dist/cli/chunks/{cost-tracker-IKX2VYSA.js → cost-tracker-2GKBRYXL.js} +2 -2
  176. package/dist/cli/chunks/{coverage-TD37CYSY.js → coverage-YCLC3W2A.js} +3 -3
  177. package/dist/cli/chunks/cross-domain-router-FPM3L27L.js +2 -0
  178. package/dist/cli/chunks/{cursor-installer-4NSVGRM5.js → cursor-installer-B3ALFW5E.js} +2 -2
  179. package/dist/cli/chunks/{daemon-UWEBUIDT.js → daemon-YWINEHG4.js} +4 -4
  180. package/dist/cli/chunks/{daemon-LYDV7NRW.js → daemon-ZKEBVLJA.js} +3 -3
  181. package/dist/cli/chunks/{dag-attention-scheduler-NECJGCHC.js → dag-attention-scheduler-OQPJ6ULA.js} +2 -2
  182. package/dist/cli/chunks/{detect-4XGC7ILO.js → detect-YMYIQH3Q.js} +2 -2
  183. package/dist/cli/chunks/{dist-node-GGJDXRKJ.js → dist-node-R4FAYQRY.js} +2 -2
  184. package/dist/cli/chunks/{domain-handler-UOFONAUT.js → domain-handler-IGWXLF2S.js} +2 -2
  185. package/dist/cli/chunks/{domain-transfer-6JLNOYPA.js → domain-transfer-A7YNO76C.js} +2 -2
  186. package/dist/cli/chunks/dream-XM33US3V.js +2 -0
  187. package/dist/cli/chunks/{embed-and-insert-pattern-ZM75DQ4J.js → embed-and-insert-pattern-KODZAS7Y.js} +2 -2
  188. package/dist/cli/chunks/{eval-CYZJTHEB.js → eval-ALQW7Q2S.js} +3 -3
  189. package/dist/cli/chunks/{experience-capture-middleware-RBOJLDUB.js → experience-capture-middleware-3WK4RXWK.js} +3 -3
  190. package/dist/cli/chunks/{fast-paths-S5BWZR3L.js → fast-paths-PQWDFIJZ.js} +2 -2
  191. package/dist/cli/chunks/{feature-flags-DUNQPDU3.js → feature-flags-6X33B3WX.js} +2 -2
  192. package/dist/cli/chunks/{feature-flags-6E7H3NYP.js → feature-flags-JRUAZCND.js} +2 -2
  193. package/dist/cli/chunks/{file-discovery-PFFKDGYG.js → file-discovery-SA3YU3IH.js} +2 -2
  194. package/dist/cli/chunks/{fleet-RCDZZFXN.js → fleet-7TXCAOKQ.js} +3 -3
  195. package/dist/cli/chunks/{gnn-wrapper-5AG3WDWF.js → gnn-wrapper-ZKNYACEC.js} +2 -2
  196. package/dist/cli/chunks/{heartbeat-handler-O2KAEX4Y.js → heartbeat-handler-KRZRZ23F.js} +4 -4
  197. package/dist/cli/chunks/heartbeat-scheduler-GM3M2MTG.js +2 -0
  198. package/dist/cli/chunks/hnsw-adapter-K62GEHIL.js +2 -0
  199. package/dist/cli/chunks/hnsw-index-VCAK3TWN.js +2 -0
  200. package/dist/cli/chunks/{hnsw-legacy-bridge-C7FG6YGW.js → hnsw-legacy-bridge-LVHQ5SG7.js} +2 -2
  201. package/dist/cli/chunks/{better-sqlite3-XGPW4HK5.js → hnswlib-node-64EGGWIC.js} +2 -2
  202. package/dist/cli/chunks/{hooks-FUHNE2P7.js → hooks-6Y3UHYI2.js} +14 -14
  203. package/dist/cli/chunks/hybrid-router-432QNCNG.js +2 -0
  204. package/dist/cli/chunks/{hypergraph-engine-LQRYBNPV.js → hypergraph-engine-2EZBZMFK.js} +2 -2
  205. package/dist/cli/chunks/{hypergraph-handler-AFFNLZVD.js → hypergraph-handler-GLPWYII2.js} +3 -3
  206. package/dist/cli/chunks/impact-analyzer-VTSISNN4.js +2 -0
  207. package/dist/cli/chunks/{init-handler-BQ6IDBX4.js → init-handler-ZSDO5VMA.js} +6 -6
  208. package/dist/cli/chunks/init-wizard-COB5AH7Q.js +2 -0
  209. package/dist/cli/chunks/kernel-ROK7X5FM.js +2 -0
  210. package/dist/cli/chunks/{kilocode-installer-KS72HUSG.js → kilocode-installer-ATYSDWIV.js} +2 -2
  211. package/dist/cli/chunks/{kiro-installer-2ZEFLGRX.js → kiro-installer-K66YT6PC.js} +2 -2
  212. package/dist/cli/chunks/knowledge-graph-YUWIDIWW.js +2 -0
  213. package/dist/cli/chunks/{learning-GGHGJ6B6.js → learning-BVYCC4RI.js} +3 -3
  214. package/dist/cli/chunks/{llm-router-LP6K5BJF.js → llm-router-VBCXE6DN.js} +12 -12
  215. package/dist/cli/chunks/llm-router-service-7VLXJ7VE.js +2 -0
  216. package/dist/cli/chunks/{load-2MLKXOT2.js → load-AREDQE2U.js} +2 -2
  217. package/dist/cli/chunks/load-test-32524DL3.js +2 -0
  218. package/dist/cli/chunks/{mcp-CDJBJG5H.js → mcp-NG6H6UC5.js} +2 -2
  219. package/dist/cli/chunks/{memory-4LAX7JZS.js → memory-Y65EHG6N.js} +5 -5
  220. package/dist/cli/chunks/memory-backend-BI2V5AAB.js +2 -0
  221. package/dist/cli/chunks/memory-handlers-NSOFWVFN.js +2 -0
  222. package/dist/cli/chunks/{multi-model-executor-SLJV73HE.js → multi-model-executor-VRPRFUZT.js} +2 -2
  223. package/dist/cli/chunks/{opencode-installer-M76SONWV.js → opencode-installer-CKQXPM5R.js} +3 -3
  224. package/dist/cli/chunks/{orchestrator-TJPUDJMP.js → orchestrator-I7JBKD6G.js} +19 -19
  225. package/dist/cli/chunks/{pipeline-2PVNFT6J.js → pipeline-MV2RWCBI.js} +2 -2
  226. package/dist/cli/chunks/{platform-KCSEDKEE.js → platform-VU5P3SOG.js} +2 -2
  227. package/dist/cli/chunks/{plugin-QX47QF5U.js → plugin-6TERLKCB.js} +2 -2
  228. package/dist/cli/chunks/{prime-radiant-advanced-wasm-L6VWL7VR.js → prime-radiant-advanced-wasm-WIUIN2DL.js} +2 -2
  229. package/dist/cli/chunks/protocol-executor-2UPB7SPI.js +2 -0
  230. package/dist/cli/chunks/{protocol-handler-WDNJDEUE.js → protocol-handler-HKWBGARO.js} +2 -2
  231. package/dist/cli/chunks/{prove-3B75DA3S.js → prove-7CQPHBRJ.js} +2 -2
  232. package/dist/cli/chunks/provider-manager-PDT37MIJ.js +2 -0
  233. package/dist/cli/chunks/qe-reasoning-bank-AQQ2BI4V.js +2 -0
  234. package/dist/cli/chunks/{quality-UGASS5WM.js → quality-VLUVXKVG.js} +2 -2
  235. package/dist/cli/chunks/queen-coordinator-6DVDVEU4.js +2 -0
  236. package/dist/cli/chunks/{real-embeddings-COBP2LHS.js → real-embeddings-JPZ64KK2.js} +2 -2
  237. package/dist/cli/chunks/{roocode-installer-TOZ4VLFT.js → roocode-installer-NONVB3UE.js} +2 -2
  238. package/dist/cli/chunks/router-O2G4KQ6L.js +2 -0
  239. package/dist/cli/chunks/routing-feedback-TAGTD3KQ.js +2 -0
  240. package/dist/cli/chunks/{routing-handler-5TDVSILX.js → routing-handler-YYXDT4J2.js} +2 -2
  241. package/dist/cli/chunks/{ruvector-commands-AM63KWQN.js → ruvector-commands-5PFMNDLR.js} +2 -2
  242. package/dist/cli/chunks/{rvf-dual-writer-UANIFE2M.js → rvf-dual-writer-TF6H7AXH.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-adapter-LNPYWAPI.js → rvf-migration-adapter-VNGIUZCO.js} +2 -2
  244. package/dist/cli/chunks/{rvf-migration-coordinator-U47L63DQ.js → rvf-migration-coordinator-VA52YAIY.js} +2 -2
  245. package/dist/cli/chunks/rvf-native-adapter-46GRWQJR.js +2 -0
  246. package/dist/cli/chunks/safe-db-LNIPXXHH.js +2 -0
  247. package/dist/cli/chunks/schedule-AUH3ZALY.js +2 -0
  248. package/dist/cli/chunks/scheduler-KK3OYPWW.js +2 -0
  249. package/dist/cli/chunks/{security-KDQ2AH7G.js → security-62HEETBF.js} +3 -3
  250. package/dist/cli/chunks/{shared-rvf-adapter-5MAGLLYJ.js → shared-rvf-adapter-XWTQPGCT.js} +2 -2
  251. package/dist/cli/chunks/{shared-rvf-dual-writer-GF2OPPM5.js → shared-rvf-dual-writer-JTZK7LRD.js} +2 -2
  252. package/dist/cli/chunks/sqlite-persistence-CYESP7NG.js +2 -0
  253. package/dist/cli/chunks/{status-handler-XZKEL7LO.js → status-handler-LSUPUKRF.js} +2 -2
  254. package/dist/cli/chunks/{structural-health-27QKWW25.js → structural-health-Z75A666N.js} +2 -2
  255. package/dist/cli/chunks/{sync-INNKS6UK.js → sync-M3O4T3A3.js} +2 -2
  256. package/dist/cli/chunks/{sync-V3HGPEJT.js → sync-VI37UHHH.js} +2 -2
  257. package/dist/cli/chunks/{task-handler-LDUVOM6G.js → task-handler-AQBSZAQC.js} +2 -2
  258. package/dist/cli/chunks/{task-handlers-HTCPV7OO.js → task-handlers-BOZP247V.js} +3 -3
  259. package/dist/cli/chunks/{test-PCUVGVJL.js → test-FTEGPNN2.js} +4 -4
  260. package/dist/cli/chunks/{test-scheduling-GYVXWCAA.js → test-scheduling-IGR4U2VQ.js} +4 -4
  261. package/dist/cli/chunks/{token-bootstrap-MJ2ANC4P.js → token-bootstrap-2DFRVMBM.js} +2 -2
  262. package/dist/cli/chunks/{token-usage-ZREHROTF.js → token-usage-VCHV47EO.js} +3 -3
  263. package/dist/cli/chunks/{transformers-6B3FWFYL.js → transformers-M27QSNFH.js} +2 -2
  264. package/dist/cli/chunks/tree-sitter-wasm-parser-IIGEJYFU.js +2 -0
  265. package/dist/cli/chunks/{types-MVZTJI2F.js → types-RQFPUUKA.js} +2 -2
  266. package/dist/cli/chunks/unified-memory-RISHEANP.js +2 -0
  267. package/dist/cli/chunks/unified-memory-hnsw-2IKXGMNZ.js +2 -0
  268. package/dist/cli/chunks/unified-persistence-ZTTUJNTU.js +2 -0
  269. package/dist/cli/chunks/{upgrade-MKTFEILD.js → upgrade-VJMYX3AL.js} +2 -2
  270. package/dist/cli/chunks/{validate-IABGALSW.js → validate-ML7HUAU5.js} +4 -4
  271. package/dist/cli/chunks/{validate-swarm-RHF53RF6.js → validate-swarm-RCR6EYRC.js} +7 -7
  272. package/dist/cli/chunks/{vibium-RAKW6FMF.js → vibium-ZOOS3W5L.js} +2 -2
  273. package/dist/cli/chunks/visual-security-D66DTAO5.js +2 -0
  274. package/dist/cli/chunks/{web-tree-sitter-PYK7F4JZ.js → web-tree-sitter-2YPGYLWK.js} +2 -2
  275. package/dist/cli/chunks/{windsurf-installer-S3U2HWZ4.js → windsurf-installer-GOJWUWC5.js} +2 -2
  276. package/dist/cli/chunks/{witness-chain-435NKQLB.js → witness-chain-3MGSS3Q4.js} +2 -2
  277. package/dist/cli/chunks/witness-chain-RHWHHDLV.js +2 -0
  278. package/dist/cli/chunks/{workflow-5UHJCZ6J.js → workflow-B5Q77BI4.js} +4 -4
  279. package/dist/cli/chunks/workflow-orchestrator-OQMFW2TC.js +2 -0
  280. package/dist/cli/chunks/{wrappers-RD3NCMLK.js → wrappers-MM5VLEPG.js} +2 -2
  281. package/dist/cli/commands/code.js +6 -0
  282. package/dist/cli/commands/hooks-handlers/command-hooks.js +1 -1
  283. package/dist/cli/commands/hooks-handlers/routing-hooks.js +1 -1
  284. package/dist/cli/commands/hooks-handlers/task-hooks.js +1 -1
  285. package/dist/cli/commands/learning.js +5 -5
  286. package/dist/cli/commands/llm-router.js +1 -1
  287. package/dist/cli/commands/workflow.js +1 -0
  288. package/dist/coordination/consensus/providers/native-learning-provider.d.ts +1 -1
  289. package/dist/coordination/consensus/providers/ollama-provider.d.ts +1 -1
  290. package/dist/coordination/consensus/providers/openrouter-provider.d.ts +1 -1
  291. package/dist/coordination/handlers/code-intelligence-handlers.js +6 -0
  292. package/dist/coordination/mincut/neural-goap.js +24 -20
  293. package/dist/coordination/protocols/code-intelligence-index.js +31 -25
  294. package/dist/coordination/queen-coordinator.js +4 -0
  295. package/dist/coordination/queen-work-stealing.js +1 -2
  296. package/dist/domains/chaos-resilience/coordinator.js +19 -15
  297. package/dist/domains/chaos-resilience/services/chaos-engineer.js +5 -2
  298. package/dist/domains/chaos-resilience/services/load-tester.js +15 -11
  299. package/dist/domains/code-intelligence/interfaces.d.ts +5 -0
  300. package/dist/domains/code-intelligence/services/c4-model/index.js +12 -6
  301. package/dist/domains/code-intelligence/services/impact-analyzer.js +6 -2
  302. package/dist/domains/code-intelligence/services/knowledge-graph.d.ts +42 -0
  303. package/dist/domains/code-intelligence/services/knowledge-graph.js +278 -93
  304. package/dist/domains/code-intelligence/services/semantic-analyzer.js +8 -2
  305. package/dist/domains/contract-testing/coordinator.js +1 -1
  306. package/dist/domains/coverage-analysis/coordinator.js +4 -2
  307. package/dist/domains/learning-optimization/coordinator.js +1 -0
  308. package/dist/domains/quality-assessment/coherence/gate-controller.js +32 -26
  309. package/dist/domains/requirements-validation/coordinator.js +1 -0
  310. package/dist/domains/test-execution/services/e2e/wait-condition-handler.js +1 -1
  311. package/dist/domains/test-execution/services/retry-handler.js +18 -12
  312. package/dist/domains/test-generation/coordinator.js +1 -1
  313. package/dist/domains/test-generation/services/pattern-matcher.js +7 -5
  314. package/dist/domains/test-generation/services/test-generator.js +3 -2
  315. package/dist/domains/visual-accessibility/coordinator.js +24 -20
  316. package/dist/index.d.ts +2 -2
  317. package/dist/index.js +2 -2
  318. package/dist/init/init-wizard-hooks.js +271 -271
  319. package/dist/init/phases/07-hooks.d.ts +7 -0
  320. package/dist/init/phases/07-hooks.js +132 -96
  321. package/dist/init/phases/12-verification.js +3 -3
  322. package/dist/integrations/agentic-flow/model-router/router.js +1 -1
  323. package/dist/integrations/embeddings/base/EmbeddingGenerator.js +11 -7
  324. package/dist/integrations/ruvector/hypergraph-engine.js +2 -2
  325. package/dist/integrations/ruvector/spectral-math.js +2 -2
  326. package/dist/integrations/ruvector/spectral-sparsifier.js +1 -1
  327. package/dist/kernel/kernel.js +1 -1
  328. package/dist/kernel/unified-memory-hnsw.js +1 -0
  329. package/dist/learning/agent-routing.d.ts +19 -0
  330. package/dist/learning/agent-routing.js +27 -1
  331. package/dist/learning/dream/dream-scheduler.d.ts +11 -36
  332. package/dist/learning/dream/dream-scheduler.js +44 -0
  333. package/dist/learning/experience-capture.js +1 -1
  334. package/dist/learning/experience-consolidation.d.ts +16 -0
  335. package/dist/learning/experience-consolidation.js +55 -11
  336. package/dist/learning/pattern-lifecycle.d.ts +21 -0
  337. package/dist/learning/pattern-lifecycle.js +70 -6
  338. package/dist/learning/qe-reasoning-bank.js +9 -1
  339. package/dist/learning/qe-unified-memory.js +8 -6
  340. package/dist/mcp/bundle.js +371 -368
  341. package/dist/mcp/handlers/core-handlers.js +2 -2
  342. package/dist/mcp/handlers/cross-phase-handlers.js +5 -3
  343. package/dist/mcp/handlers/handler-factory.d.ts +5 -0
  344. package/dist/mcp/handlers/handler-factory.js +44 -4
  345. package/dist/mcp/http-server.js +1 -0
  346. package/dist/mcp/protocol-server.js +15 -16
  347. package/dist/mcp/tools/code-intelligence/analyze.js +1 -1
  348. package/dist/mcp/tools/learning-optimization/optimize.js +1 -1
  349. package/dist/mcp/tools/qx-analysis/heuristics-engine.js +195 -173
  350. package/dist/mcp/tools/visual-accessibility/index.js +1 -1
  351. package/dist/mcp/transport/stdio.d.ts +20 -0
  352. package/dist/mcp/transport/stdio.js +35 -2
  353. package/dist/mcp/transport/websocket/websocket-transport.js +1 -0
  354. package/dist/optimization/auto-tuner.js +1 -1
  355. package/dist/planning/goap-planner.js +1 -0
  356. package/dist/routing/agent-dependency-graph.js +4 -1
  357. package/dist/shared/llm/router/config-store.js +1 -1
  358. package/dist/shared/metrics/system-metrics.js +6 -4
  359. package/dist/shared/parsers/tree-sitter-wasm-parser.d.ts +12 -0
  360. package/dist/shared/parsers/tree-sitter-wasm-parser.js +35 -0
  361. package/dist/shared/parsers/treesitter-ts-extractor.d.ts +39 -0
  362. package/dist/shared/parsers/treesitter-ts-extractor.js +196 -0
  363. package/dist/shared/utils/rabitq.d.ts +133 -0
  364. package/dist/shared/utils/rabitq.js +201 -0
  365. package/dist/shared/utils/safe-expression-evaluator.js +8 -5
  366. package/dist/sync/cloud/postgres-writer.js +2 -0
  367. package/dist/sync/readers/json-reader.js +1 -1
  368. package/dist/test-scheduling/git-aware/test-selector.js +1 -1
  369. package/dist/workers/quality-daemon/index.js +26 -24
  370. package/package.json +12 -5
  371. package/dist/cli/chunks/adapter-3JS2CN7C.js +0 -2
  372. package/dist/cli/chunks/aqe-learning-engine-Q4GFNGU6.js +0 -2
  373. package/dist/cli/chunks/base-Q3MAL22Y.js +0 -2
  374. package/dist/cli/chunks/browser-workflow-JX3M2UWG.js +0 -2
  375. package/dist/cli/chunks/chunk-622MIAOR.js +0 -59
  376. package/dist/cli/chunks/chunk-CKECJH2A.js +0 -2
  377. package/dist/cli/chunks/chunk-IJ4BUSJN.js +0 -95
  378. package/dist/cli/chunks/chunk-VPCE5CIT.js +0 -2
  379. package/dist/cli/chunks/chunk-WO7KYT3X.js +0 -62
  380. package/dist/cli/chunks/client-PA3UJIHH.js +0 -2
  381. package/dist/cli/chunks/cross-domain-router-BVJRP2ZX.js +0 -2
  382. package/dist/cli/chunks/dream-BXZUEIW2.js +0 -2
  383. package/dist/cli/chunks/heartbeat-scheduler-LEKAWFJF.js +0 -2
  384. package/dist/cli/chunks/hnsw-adapter-2TCEG5M2.js +0 -2
  385. package/dist/cli/chunks/hnsw-index-VDPUTEES.js +0 -2
  386. package/dist/cli/chunks/hybrid-router-2EMDIYIG.js +0 -2
  387. package/dist/cli/chunks/impact-analyzer-HFD6CPWC.js +0 -2
  388. package/dist/cli/chunks/init-wizard-552QIVRC.js +0 -2
  389. package/dist/cli/chunks/kernel-5DN6O6EE.js +0 -2
  390. package/dist/cli/chunks/knowledge-graph-76Y77MB6.js +0 -2
  391. package/dist/cli/chunks/llm-router-service-4O6GCEFH.js +0 -2
  392. package/dist/cli/chunks/load-test-FCI2IWRJ.js +0 -2
  393. package/dist/cli/chunks/memory-backend-MKNCBNDE.js +0 -2
  394. package/dist/cli/chunks/memory-handlers-OBAFR4WV.js +0 -2
  395. package/dist/cli/chunks/protocol-executor-IA7WNT23.js +0 -2
  396. package/dist/cli/chunks/provider-manager-3K5KB5A6.js +0 -2
  397. package/dist/cli/chunks/qe-reasoning-bank-V5Z3BBYY.js +0 -2
  398. package/dist/cli/chunks/queen-coordinator-QOMPA27Z.js +0 -2
  399. package/dist/cli/chunks/router-P5RZUPC4.js +0 -2
  400. package/dist/cli/chunks/routing-feedback-3PS3OZQC.js +0 -2
  401. package/dist/cli/chunks/rvf-native-adapter-TT7OJPKM.js +0 -2
  402. package/dist/cli/chunks/safe-db-PEW7VBAE.js +0 -2
  403. package/dist/cli/chunks/schedule-QHOTHBQE.js +0 -2
  404. package/dist/cli/chunks/scheduler-KXJBYTRT.js +0 -2
  405. package/dist/cli/chunks/sqlite-persistence-TPXJK34J.js +0 -2
  406. package/dist/cli/chunks/tree-sitter-wasm-parser-JVV234MN.js +0 -2
  407. package/dist/cli/chunks/unified-memory-ROS2NKR5.js +0 -2
  408. package/dist/cli/chunks/unified-memory-hnsw-FLEUF3XO.js +0 -2
  409. package/dist/cli/chunks/unified-persistence-QC5L7UNQ.js +0 -2
  410. package/dist/cli/chunks/visual-security-NLIOUQCR.js +0 -2
  411. package/dist/cli/chunks/witness-chain-U7X6JX5J.js +0 -2
  412. package/dist/cli/chunks/workflow-orchestrator-APE6BAXH.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.1");process.exit(0)}
2
- import{a as t,q as r}from"./chunk-PLRSKAFZ.js";import{c as l}from"./chunk-4AWJ5PE4.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.3");process.exit(0)}
2
+ import{a as t,q as r}from"./chunk-VRXY4T22.js";import{c as l}from"./chunk-CAMEFWRK.js";function m(s,e){let o=e?.readonly??!1,n=e?.fileMustExist??!1,i=e?.busyTimeout??5e3,b=e?.walMode??!o,a=new t(s,{readonly:o,fileMustExist:n});return a.pragma(`busy_timeout = ${i}`),b&&a.pragma("journal_mode = WAL"),a}var u=l(()=>{r()});export{m as a,u as b};
@@ -1,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.1");process.exit(0)}
2
- import{a as h}from"./chunk-VPCE5CIT.js";import{c as m}from"./chunk-BGBSYF3K.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.1");process.exit(0)}
2
- import{i as c}from"./chunk-NRLT44YB.js";import{b as g,d as E}from"./chunk-QNW335PD.js";import{a as p}from"./chunk-VPCE5CIT.js";import{c as m}from"./chunk-BGBSYF3K.js";import{a as l,b as _}from"./chunk-XRK7FBTY.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.1");process.exit(0)}
2
- import{b as P,c as x,d as R,f as O,g as j,h as D,i as $,j as L,k as N}from"./chunk-TL5F2S3Z.js";import{b as _,d as T}from"./chunk-QNW335PD.js";import{a as k,c as q}from"./chunk-2TDWCXZ6.js";import{a as v,b as ee}from"./chunk-XRK7FBTY.js";T();import{existsSync as w,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");w(n)||Q(n,{recursive:!0});let r=g(n,"settings.json"),s={};if(w(r))try{let u=I(r,"utf-8");s=_(u)}catch{s={}}let i={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks guard --file "$TOOL_INPUT_file_path" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-command --command "$TOOL_INPUT_command" --json',timeout:3e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5e3,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'npx agentic-qe hooks post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'npx agentic-qe hooks post-command --command "$TOOL_INPUT_command" --success --json',timeout:5e3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'npx agentic-qe hooks post-task --task-id "$TOOL_RESULT_agent_id" --success --json',timeout:5e3,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:"npx agentic-qe hooks route --json",timeout:5e3,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'npx agentic-qe hooks session-start --session-id "$SESSION_ID" --json',timeout:1e4,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:"npx agentic-qe hooks session-end --save-state --json",timeout:5e3,continueOnError:!0}]},{hooks:[{type:"command",command:"npx agentic-qe hooks post-route --success true --json",timeout:5e3,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=O(d,i);let c=s.env||{};s.env={...c,...j(e)};let m=D(e,t);for(let[u,h]of Object.entries(m))if(u==="_aqePermissions"){let p=s.permissions||{},l=p.allow||[],y=h,C=[...new Set([...l,...y])];s.permissions={...p,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");w(e)||Q(e,{recursive:!0});let n=g(e,"cross-phase-memory.yaml");if(w(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(w(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
 
@@ -23,7 +23,7 @@ routing:
23
23
  quality-criteria:
24
24
  - "qe-requirements-validator"
25
25
  - "qe-bdd-generator"
26
- `,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function z(t){let e=g(t,".mcp.json"),n={};if(w(e))try{let s=I(e,"utf-8");n=_(s)}catch{n={}}n.mcpServers||(n.mcpServers={});let r=n.mcpServers;return r["agentic-qe"]={command:"npx",args:["@anthropics/agentic-qe","mcp","start"],env:{AQE_LEARNING_ENABLED:"true",AQE_VERBOSE:"false"},autoStart:!1},S(e,JSON.stringify(n,null,2),"utf-8"),!0}async function U(t,e){let n=g(t,"CLAUDE.md"),r=se(e);if(w(n)){let s=I(n,"utf-8");if(s.includes("## Agentic QE v3"))return!0;let i=g(t,"CLAUDE.md.backup");S(i,s,"utf-8"),S(n,s+`
26
+ `,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function U(t){let e=g(t,".mcp.json"),n={};if(E(e))try{let s=I(e,"utf-8");n=v(s)}catch{n={}}n.mcpServers||(n.mcpServers={});let r=n.mcpServers;return r["agentic-qe"]={command:"npx",args:["@anthropics/agentic-qe","mcp","start"],env:{AQE_LEARNING_ENABLED:"true",AQE_VERBOSE:"false"},autoStart:!1},S(e,JSON.stringify(n,null,2),"utf-8"),!0}async function z(t,e){let n=g(t,"CLAUDE.md"),r=se(e);if(E(n)){let s=I(n,"utf-8");if(s.includes("## Agentic QE v3"))return!0;let i=g(t,"CLAUDE.md.backup");S(i,s,"utf-8"),S(n,s+`
27
27
 
28
28
  `+r,"utf-8")}else S(n,r,"utf-8");return!0}function se(t){let e=t.domains.enabled.slice(0,6).join(", "),n=Math.max(0,t.domains.enabled.length-6);return`## Agentic QE v3
29
29
 
@@ -261,7 +261,7 @@ aqe init --auto
261
261
 
262
262
  ---
263
263
  *Generated by AQE v3 init - ${new Date().toISOString()}*
264
- `}q();import{existsSync as f,mkdirSync as b,writeFileSync as E}from"fs";import{join as o,dirname as ae}from"path";q();ee();T();async function F(t,e){let n=o(t,".agentic-qe","memory.db");try{let r=ae(n);f(r)||b(r,{recursive:!0});let s=v(n);try{s.exec(`
264
+ `}T();import{existsSync as f,mkdirSync as w,writeFileSync as b}from"fs";import{join as o,dirname as ae}from"path";T();ee();P();async function F(t,e){let n=o(t,".agentic-qe","memory.db");try{let r=ae(n);f(r)||w(r,{recursive:!0});let s=_(n);try{s.exec(`
265
265
  CREATE TABLE IF NOT EXISTS kv_store (
266
266
  key TEXT NOT NULL,
267
267
  namespace TEXT NOT NULL,
@@ -276,12 +276,12 @@ 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-XGPW4HK5.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
283
283
  - Ubuntu/Debian: sudo apt-get install build-essential python3
284
- - Alpine: apk add build-base python3`)}let n=o(t,".agentic-qe");f(n)||b(n,{recursive:!0});let r=o(n,"memory.db");try{let s=new e(r);if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.exec(`
284
+ - Alpine: apk add build-base python3`)}let n=o(t,".agentic-qe");f(n)||w(n,{recursive:!0});let r=o(n,"memory.db");try{let s=new e(r);if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.exec(`
285
285
  CREATE TABLE IF NOT EXISTS kv_store (
286
286
  key TEXT NOT NULL,
287
287
  namespace TEXT NOT NULL,
@@ -299,18 +299,18 @@ If you see native compilation errors, ensure build tools are installed:
299
299
  VALUES (?, ?, ?)
300
300
  `).run("_init_test","_system",JSON.stringify({initialized:new Date().toISOString()})),s.close(),console.log(`\u2713 SQLite persistence initialized: ${r}`),!0}catch(s){throw new Error(`SQLite persistence initialization FAILED: ${s}
301
301
  Database path: ${r}
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=v(e),r=n.prepare(`
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-76Y77MB6.js"),{InMemoryBackend:n}=await import("./memory-backend-MKNCBNDE.js"),r=new n;await r.initialize();let s=new e(r,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0}),d=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:d.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 B(t){let e=o(t,".agentic-qe","memory.db");try{let n=v(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
- `).get();return n.close(),r.count}catch{return 0}}async function H(t,e,n){if(!e.learning.enabled)return 0;let r=o(t,".agentic-qe","data");f(r)||b(r,{recursive:!0});let s=o(r,"hnsw");f(s)||b(s,{recursive:!0});let i=o(r,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:o(r,"memory.db"),hnswIndexPath:o(s,"index.bin"),initialized:new Date().toISOString()};E(i,JSON.stringify(d,null,2),"utf-8");let c=0;if(e.learning.pretrainedPatterns&&n){let m=n,a=new Map;for(let p of m.patterns){let l=p.domain||"general";a.has(l)||a.set(l,[]),a.get(l).push(p)}let u=o(r,"pretrained-index.json"),h={version:m.version,totalPatterns:m.statistics.totalPatterns,domains:Array.from(a.entries()).map(([p,l])=>({name:p,patternCount:l.length})),loadedAt:new Date().toISOString()};E(u,JSON.stringify(h,null,2),"utf-8");for(let[p,l]of a){let y=o(r,"patterns",p);f(y)||b(y,{recursive:!0});let C=o(y,"patterns.json");E(C,JSON.stringify(l,null,2),"utf-8"),c+=l.length}return c}return 0}async function J(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let n=o(t,".agentic-qe","workers");f(n)||b(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"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:r,createdAt:new Date().toISOString(),daemonPid:null};E(i,JSON.stringify(d,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()};E(u,JSON.stringify(h,null,2),"utf-8")}let c=o(n,"start-daemon.cjs");return E(c,`#!/usr/bin/env node
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
309
309
  // AQE v3 Worker Daemon Startup Script (cross-platform)
310
310
  // Generated by aqe init
311
311
 
312
312
  console.log("AQE v3 hooks work via CLI commands (no daemon required)");
313
313
  console.log("Use: npx aqe hooks session-start");
314
- `),e.workers.enabled.length}async function X(t,e){if(!e.skills.install)return 0;let r=await $({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return r.errors.length>0&&console.warn("Skills installation warnings:",r.errors),r.installed.length}async function K(t){let n=await L({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return n.errors.length>0&&console.warn("Agents installation warnings:",n.errors),n.installed.length}async function Y(t,e,n){let s=await N({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:n}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:n},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function Z(t,e){if(!e)throw new Error("No configuration to save");let n=o(t,".agentic-qe");f(n)||b(n,{recursive:!0});let r=oe(e),s=o(n,"config.yaml");E(s,r,"utf-8")}function oe(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-4.7" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let n of t.workers.enabled)e.push(` - "${n}"`);e.push(" intervals:");for(let[n,r]of Object.entries(t.workers.intervals))e.push(` ${n}: ${r}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let n of t.autoTuning.parameters)e.push(` - "${n}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let n of t.domains.enabled)e.push(` - "${n}"`);e.push(" disabled:");for(let n of t.domains.disabled)e.push(` - "${n}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
315
- `)}var ie=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],A=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=x(e.projectRoot),this.configurator=R({minimal:e.minimal})}async initialize(){let e=Date.now();try{let n=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),r=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(n):this.applyWizardAnswers(n));await this.runStep("Persistence Database Setup",async()=>await W(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await G(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await V(n.projectRoot);let y=await B(this.projectRoot);return console.log(` Using existing code intelligence index (${y} entries)`),{status:"existing",entries:y}}),i=await this.runStep("Learning System Setup",async()=>r.learning.enabled&&!this.options.skipPatterns?await H(this.projectRoot,r,this.options.pretrainedLibrary):0),d=await this.runStep("Hooks Configuration",async()=>r.hooks.claudeCode?await M(this.projectRoot,r):!1),c=await this.runStep("MCP Configuration",async()=>await z(this.projectRoot)),m=await this.runStep("CLAUDE.md Generation",async()=>await U(this.projectRoot,r)),a=await this.runStep("Background Workers",async()=>r.workers.daemonAutoStart?await J(this.projectRoot,r):0),u=await this.runStep("Skills Installation",async()=>r.skills.install?await X(this.projectRoot,r):0),h=await this.runStep("Agents Installation",async()=>await K(this.projectRoot)),p;if(this.options.withN8n){let l=await this.runStep("N8n Platform Installation",async()=>await Y(this.projectRoot,r,this.options.n8nApiConfig));l&&(p=l)}return await this.runStep("Save Configuration",async()=>await Z(this.projectRoot,r)),await this.runStep("Version Marker",async()=>await F(this.projectRoot,r.version)),{success:!0,config:r,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:i,skillsInstalled:u,agentsInstalled:h,hooksConfigured:d,mcpConfigured:c,claudeMdGenerated:m,workersStarted:a,n8nInstalled:p},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(n){return this.steps.push({step:"Initialization Failed",status:"error",message:k(n),durationMs:0}),{success:!1,config:P("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ie}async runStep(e,n){let r=Date.now();try{let s=await n();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-r}),s}catch(s){throw this.steps.push({step:e,status:"error",message:k(s),durationMs:Date.now()-r}),s}}applyWizardAnswers(e){let n=this.options.wizardAnswers||{},r=this.configurator.recommend(e);switch(n["project-type"]&&n["project-type"]!=="auto"&&(r.project.type=n["project-type"]),n["learning-mode"]){case"full":r.learning.enabled=!0,r.learning.embeddingModel="transformer";break;case"basic":r.learning.enabled=!0,r.learning.embeddingModel="hash";break;case"disabled":r.learning.enabled=!1;break}return n["load-patterns"]===!1&&(r.learning.pretrainedPatterns=!1),n.hooks===!1&&(r.hooks.claudeCode=!1),n.workers===!1&&(r.workers.daemonAutoStart=!1),n.skills===!1&&(r.skills.install=!1),r}};function le(t){return new A(t)}async function xe(t){return await le({projectRoot:t,autoMode:!0}).initialize()}function Re(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let r of t.steps){let s=r.status==="success"?"[OK]":r.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${r.step.padEnd(50)} ${String(r.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let n=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${n.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
- `)}export{A as a,le as b,xe as c,Re as d};
314
+ `),e.workers.enabled.length}async function X(t,e){if(!e.skills.install)return 0;let r=await $({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return r.errors.length>0&&console.warn("Skills installation warnings:",r.errors),r.installed.length}async function K(t){let n=await L({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return n.errors.length>0&&console.warn("Agents installation warnings:",n.errors),n.installed.length}async function Y(t,e,n){let s=await N({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:n}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:n},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function Z(t,e){if(!e)throw new Error("No configuration to save");let n=o(t,".agentic-qe");f(n)||w(n,{recursive:!0});let r=oe(e),s=o(n,"config.yaml");b(s,r,"utf-8")}function oe(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-4.7" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let n of t.workers.enabled)e.push(` - "${n}"`);e.push(" intervals:");for(let[n,r]of Object.entries(t.workers.intervals))e.push(` ${n}: ${r}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let n of t.autoTuning.parameters)e.push(` - "${n}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let n of t.domains.enabled)e.push(` - "${n}"`);e.push(" disabled:");for(let n of t.domains.disabled)e.push(` - "${n}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
315
+ `)}var ie=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],A=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=R(e.projectRoot),this.configurator=D({minimal:e.minimal})}async initialize(){let e=Date.now();try{let n=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),r=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(n):this.applyWizardAnswers(n));await this.runStep("Persistence Database Setup",async()=>await W(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await G(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await V(n.projectRoot);let y=await J(this.projectRoot);return console.log(` Using existing code intelligence index (${y} entries)`),{status:"existing",entries:y}}),i=await this.runStep("Learning System Setup",async()=>r.learning.enabled&&!this.options.skipPatterns?await B(this.projectRoot,r,this.options.pretrainedLibrary):0),p=await this.runStep("Hooks Configuration",async()=>r.hooks.claudeCode?await M(this.projectRoot,r):!1),c=await this.runStep("MCP Configuration",async()=>await U(this.projectRoot)),m=await this.runStep("CLAUDE.md Generation",async()=>await z(this.projectRoot,r)),a=await this.runStep("Background Workers",async()=>r.workers.daemonAutoStart?await H(this.projectRoot,r):0),u=await this.runStep("Skills Installation",async()=>r.skills.install?await X(this.projectRoot,r):0),h=await this.runStep("Agents Installation",async()=>await K(this.projectRoot)),d;if(this.options.withN8n){let l=await this.runStep("N8n Platform Installation",async()=>await Y(this.projectRoot,r,this.options.n8nApiConfig));l&&(d=l)}return await this.runStep("Save Configuration",async()=>await Z(this.projectRoot,r)),await this.runStep("Version Marker",async()=>await F(this.projectRoot,r.version)),{success:!0,config:r,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:i,skillsInstalled:u,agentsInstalled:h,hooksConfigured:p,mcpConfigured:c,claudeMdGenerated:m,workersStarted:a,n8nInstalled:d},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(n){return this.steps.push({step:"Initialization Failed",status:"error",message:k(n),durationMs:0}),{success:!1,config:q("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ie}async runStep(e,n){let r=Date.now();try{let s=await n();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-r}),s}catch(s){throw this.steps.push({step:e,status:"error",message:k(s),durationMs:Date.now()-r}),s}}applyWizardAnswers(e){let n=this.options.wizardAnswers||{},r=this.configurator.recommend(e);switch(n["project-type"]&&n["project-type"]!=="auto"&&(r.project.type=n["project-type"]),n["learning-mode"]){case"full":r.learning.enabled=!0,r.learning.embeddingModel="transformer";break;case"basic":r.learning.enabled=!0,r.learning.embeddingModel="hash";break;case"disabled":r.learning.enabled=!1;break}return n["load-patterns"]===!1&&(r.learning.pretrainedPatterns=!1),n.hooks===!1&&(r.hooks.claudeCode=!1),n.workers===!1&&(r.workers.daemonAutoStart=!1),n.skills===!1&&(r.skills.install=!1),r}};function le(t){return new A(t)}async function Re(t){return await le({projectRoot:t,autoMode:!0}).initialize()}function De(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let r of t.steps){let s=r.status==="success"?"[OK]":r.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${r.step.padEnd(50)} ${String(r.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let n=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${n.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
+ `)}export{A as a,le as b,Re as c,De as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.10.1");process.exit(0)}
2
- import{a as l}from"./chunk-57NJQV57.js";import{a as m}from"./chunk-Y2DPXMOR.js";import{i as a}from"./chunk-IK6AJX3C.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.1");process.exit(0)}
2
- import{a as w,b as A,c as O,e as D,f as z}from"./chunk-GXJ4BCGC.js";import{b as S,d as $}from"./chunk-QNW335PD.js";import{a as N,c as F}from"./chunk-2TDWCXZ6.js";import{i as v}from"./chunk-IK6AJX3C.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.1");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.1");process.exit(0)}
2
- import{o as me}from"./chunk-KKNBYXYA.js";import{b as w,c as E,d as A,f as j,k as de,o as ue}from"./chunk-Q24OJX44.js";import{a as Re,b as _,d as ee}from"./chunk-QNW335PD.js";import{a as v}from"./chunk-VPCE5CIT.js";import{c as b}from"./chunk-BGBSYF3K.js";import{a as d,b as L,c as P}from"./chunk-2TDWCXZ6.js";import{i as I}from"./chunk-IK6AJX3C.js";import{a as T,b as z}from"./chunk-XRK7FBTY.js";import{a as le,d as Te}from"./chunk-MVGVD6LS.js";import{f as Ce}from"./chunk-4AWJ5PE4.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-KKNBYXYA.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};