agentic-qe 3.9.30 → 3.9.32

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 (345) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +208 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/bridge/captured-experience-bridge.js +31 -2
  5. package/dist/cli/bundle.js +5 -5
  6. package/dist/cli/chunks/adapter-CDQOF5TF.js +2 -0
  7. package/dist/cli/chunks/{agent-booster-wasm-TOSXWTUQ.js → agent-booster-wasm-WKS3E6KT.js} +2 -2
  8. package/dist/cli/chunks/{agent-handler-2BU6TYZZ.js → agent-handler-LYCAWE7S.js} +2 -2
  9. package/dist/cli/chunks/{agent-memory-branch-JFG3BXZY.js → agent-memory-branch-XF7IOMRK.js} +2 -2
  10. package/dist/cli/chunks/aqe-learning-engine-RZK22CJB.js +2 -0
  11. package/dist/cli/chunks/{audit-4IGZZKUW.js → audit-D2AY3HFP.js} +2 -2
  12. package/dist/cli/chunks/base-UGH6TVO4.js +2 -0
  13. package/dist/cli/chunks/{hnswlib-node-STKRZIU3.js → better-sqlite3-K2VWFDKT.js} +2 -2
  14. package/dist/cli/chunks/{brain-handler-RIDW27HH.js → brain-handler-NNW4TAO2.js} +4 -4
  15. package/dist/cli/chunks/{branch-enumerator-GMYHLLWD.js → branch-enumerator-OM5HNZKV.js} +2 -2
  16. package/dist/cli/chunks/{browser-N76A3I2P.js → browser-Y2FU2NV4.js} +2 -2
  17. package/dist/cli/chunks/browser-workflow-SGOL3FCJ.js +2 -0
  18. package/dist/cli/chunks/{chunk-ETEHVG76.js → chunk-2L5GAOST.js} +2 -2
  19. package/dist/cli/chunks/{chunk-ECX6VXMW.js → chunk-2XC4XVCI.js} +1 -1
  20. package/dist/cli/chunks/{chunk-L7X3A36M.js → chunk-2Z2IQBIJ.js} +1 -1
  21. package/dist/cli/chunks/{chunk-UYLHIGNC.js → chunk-33PGBYTC.js} +2 -2
  22. package/dist/cli/chunks/{chunk-OOFWYDG6.js → chunk-3MHWBCSC.js} +1 -1
  23. package/dist/cli/chunks/{chunk-FI4HRS2G.js → chunk-3R4CMTWF.js} +2 -2
  24. package/dist/cli/chunks/{chunk-IP6ZTXNJ.js → chunk-45N22VAB.js} +2 -2
  25. package/dist/cli/chunks/{chunk-FG5GL26L.js → chunk-4H4PEZUX.js} +2 -2
  26. package/dist/cli/chunks/{chunk-CNNVL5W4.js → chunk-4VAZSCTZ.js} +2 -2
  27. package/dist/cli/chunks/{chunk-AWWD3EI3.js → chunk-5A6LBGRU.js} +2 -2
  28. package/dist/cli/chunks/{chunk-ER6BT4GS.js → chunk-5DSANX6S.js} +2 -2
  29. package/dist/cli/chunks/chunk-5R5WOLZM.js +5 -0
  30. package/dist/cli/chunks/{chunk-RNO6CE7I.js → chunk-5WR42V5O.js} +2 -2
  31. package/dist/cli/chunks/{chunk-UEXOMDRS.js → chunk-5XY6SULI.js} +2 -2
  32. package/dist/cli/chunks/{chunk-WVODEWH5.js → chunk-62UXGD5J.js} +14 -8
  33. package/dist/cli/chunks/{chunk-EWNJ6OAT.js → chunk-667I4RTC.js} +1 -1
  34. package/dist/cli/chunks/{chunk-ND6VCNN5.js → chunk-6EKXBWJD.js} +2 -2
  35. package/dist/cli/chunks/{chunk-Y57V4FDT.js → chunk-6R6QCGNU.js} +2 -2
  36. package/dist/cli/chunks/{chunk-VRP4GB4Y.js → chunk-6SYP7QX6.js} +4 -4
  37. package/dist/cli/chunks/{chunk-BFJLKG3D.js → chunk-6YGFAJ3X.js} +1 -1
  38. package/dist/cli/chunks/{chunk-UWWX4RK7.js → chunk-6ZG6TBWF.js} +4 -4
  39. package/dist/cli/chunks/{chunk-QSV4ROZD.js → chunk-7AISRWBS.js} +2 -2
  40. package/dist/cli/chunks/{chunk-SJCEPKZO.js → chunk-7IDPVSTF.js} +1 -1
  41. package/dist/cli/chunks/{chunk-HQIWLMDS.js → chunk-7PTW3M67.js} +2 -2
  42. package/dist/cli/chunks/{chunk-TA3QYAZ6.js → chunk-A4UNK5SY.js} +2 -2
  43. package/dist/cli/chunks/chunk-A6VI5BZU.js +95 -0
  44. package/dist/cli/chunks/{chunk-XVTZXCHI.js → chunk-BBPOTFIY.js} +2 -2
  45. package/dist/cli/chunks/{chunk-OEGFOMXP.js → chunk-BDXEL3GM.js} +2 -2
  46. package/dist/cli/chunks/{chunk-YETPSL6H.js → chunk-BGRC4676.js} +3 -3
  47. package/dist/cli/chunks/chunk-BQML7B4W.js +180 -0
  48. package/dist/cli/chunks/{chunk-DEDFPHJL.js → chunk-BV3SGEV7.js} +1 -1
  49. package/dist/cli/chunks/{chunk-FGMHVSLV.js → chunk-DBE2LIYG.js} +2 -2
  50. package/dist/cli/chunks/{chunk-2GBBZLXT.js → chunk-DFY7F4TE.js} +1 -1
  51. package/dist/cli/chunks/{chunk-LDGNVPBZ.js → chunk-EFEJLZDN.js} +1 -1
  52. package/dist/cli/chunks/{chunk-ZKZTSYPU.js → chunk-ESNBKAT6.js} +2 -2
  53. package/dist/cli/chunks/{chunk-5F26LSG2.js → chunk-EVSUZKD5.js} +2 -2
  54. package/dist/cli/chunks/{chunk-QOJ7EAF5.js → chunk-FFBF5BLQ.js} +1 -1
  55. package/dist/cli/chunks/{chunk-3AICELMQ.js → chunk-FIONYUVH.js} +2 -2
  56. package/dist/cli/chunks/{chunk-UROPIIB2.js → chunk-FNQCWEVJ.js} +2 -2
  57. package/dist/cli/chunks/{chunk-5DJAJPBG.js → chunk-FV2MU6CY.js} +2 -2
  58. package/dist/cli/chunks/{chunk-QTS2DS42.js → chunk-FWEYOD3S.js} +2 -2
  59. package/dist/cli/chunks/{chunk-XK6YXCS7.js → chunk-G6AJMFWL.js} +3 -3
  60. package/dist/cli/chunks/{chunk-R57J3O6I.js → chunk-G6VVOUUF.js} +2 -2
  61. package/dist/cli/chunks/{chunk-2O5TT3UT.js → chunk-G77CYF7H.js} +3 -3
  62. package/dist/cli/chunks/{chunk-TULNR2AH.js → chunk-H7YKTJMY.js} +2 -2
  63. package/dist/cli/chunks/{chunk-GEXVUFK4.js → chunk-HGWQC7PR.js} +2 -2
  64. package/dist/cli/chunks/{chunk-QLNS6DGB.js → chunk-HHBFI3YA.js} +2 -2
  65. package/dist/cli/chunks/{chunk-WP6X67YI.js → chunk-HPQZSXED.js} +1 -1
  66. package/dist/cli/chunks/{chunk-HA7N45KB.js → chunk-HR6NX6DW.js} +2 -2
  67. package/dist/cli/chunks/{chunk-HB52S6IV.js → chunk-I6Q6BPVH.js} +1 -1
  68. package/dist/cli/chunks/{chunk-BM73MJLE.js → chunk-IGEZVFOM.js} +2 -2
  69. package/dist/cli/chunks/{chunk-QBDXUI2H.js → chunk-IGQPGXP7.js} +2 -2
  70. package/dist/cli/chunks/{chunk-Q26GG6WO.js → chunk-IJQJV7BC.js} +3 -3
  71. package/dist/cli/chunks/chunk-JDW6GN3A.js +2 -0
  72. package/dist/cli/chunks/{chunk-GZ3U2QT2.js → chunk-JRYNHFZA.js} +1 -1
  73. package/dist/cli/chunks/{chunk-MV3NUANS.js → chunk-KHZRNJ3A.js} +1 -1
  74. package/dist/cli/chunks/chunk-LHDTXTS7.js +2 -0
  75. package/dist/cli/chunks/{chunk-52TRKIAQ.js → chunk-LI2IOJMM.js} +1 -1
  76. package/dist/cli/chunks/{heartbeat-scheduler-CNJBAO5C.js → chunk-LR5VW3OS.js} +2 -2
  77. package/dist/cli/chunks/{chunk-2NFGUFYU.js → chunk-LTSNDM5N.js} +2 -2
  78. package/dist/cli/chunks/{chunk-3EP2YZSY.js → chunk-M5PYPGBC.js} +2 -2
  79. package/dist/cli/chunks/{chunk-JCWHX4XV.js → chunk-MEHNT37H.js} +2 -2
  80. package/dist/cli/chunks/{chunk-QHKK2H4H.js → chunk-MERMCKPG.js} +1 -1
  81. package/dist/cli/chunks/{chunk-Q53UMLLC.js → chunk-MIHQIAVK.js} +2 -2
  82. package/dist/cli/chunks/{chunk-VOBNJWZF.js → chunk-MMVSERJQ.js} +2 -2
  83. package/dist/cli/chunks/{chunk-37I6K7QO.js → chunk-MQQANXFS.js} +2 -2
  84. package/dist/cli/chunks/{chunk-YKFURJNP.js → chunk-MTOHV22P.js} +1 -1
  85. package/dist/cli/chunks/{chunk-MOLOWMON.js → chunk-NVZHCAEB.js} +2 -2
  86. package/dist/cli/chunks/{chunk-YXR5RYRE.js → chunk-NW5FYGDE.js} +2 -2
  87. package/dist/cli/chunks/{chunk-NMBHF7ZD.js → chunk-NZRJWK5H.js} +61 -121
  88. package/dist/cli/chunks/chunk-O5NEZCTB.js +2 -0
  89. package/dist/cli/chunks/{chunk-E7UHOKKL.js → chunk-O5UGJ3OI.js} +2 -2
  90. package/dist/cli/chunks/{chunk-Q4HJRYQB.js → chunk-OK2TFTXP.js} +2 -2
  91. package/dist/cli/chunks/{chunk-FGDEM4HU.js → chunk-OKEHGXIS.js} +2 -2
  92. package/dist/cli/chunks/{chunk-C6TNYLD7.js → chunk-OKRY4LNE.js} +3 -3
  93. package/dist/cli/chunks/{chunk-3WIU2E2Y.js → chunk-OMOGD2NN.js} +2 -2
  94. package/dist/cli/chunks/{chunk-DJRWVNHK.js → chunk-ONNTJXU7.js} +2 -2
  95. package/dist/cli/chunks/chunk-OPOGZAN5.js +14 -0
  96. package/dist/cli/chunks/{chunk-OTFJCZNY.js → chunk-PG5F2VHA.js} +2 -2
  97. package/dist/cli/chunks/{chunk-MYF7F3ZP.js → chunk-PHRMWRXA.js} +2 -2
  98. package/dist/cli/chunks/{chunk-7D2DM23U.js → chunk-PIXUX2NR.js} +2 -2
  99. package/dist/cli/chunks/{chunk-IWC6GR24.js → chunk-PLGMPG7S.js} +2 -2
  100. package/dist/cli/chunks/{chunk-T2DIMSQF.js → chunk-PPS6VN24.js} +1 -1
  101. package/dist/cli/chunks/{chunk-AUNNGKLN.js → chunk-PQAYCK2U.js} +2 -2
  102. package/dist/cli/chunks/{chunk-FU74OETU.js → chunk-PS6ISBED.js} +2 -2
  103. package/dist/cli/chunks/{chunk-JNRRDG7O.js → chunk-QPYNQSWD.js} +2 -2
  104. package/dist/cli/chunks/{chunk-MHPK4ZPK.js → chunk-QRTZ67BC.js} +2 -2
  105. package/dist/cli/chunks/{chunk-Z3TXQOS7.js → chunk-REW3W3ZW.js} +1 -1
  106. package/dist/cli/chunks/{chunk-3PZDXE5E.js → chunk-RHXYZ6AZ.js} +127 -127
  107. package/dist/cli/chunks/{chunk-IEGAEXQX.js → chunk-RZXAXWBD.js} +2 -2
  108. package/dist/cli/chunks/{chunk-4UZQSPR4.js → chunk-S4M7U6CZ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-H27XUYWZ.js → chunk-SJETAUZA.js} +1 -1
  110. package/dist/cli/chunks/{chunk-MZ7M2CDV.js → chunk-SLH7LFVY.js} +2 -2
  111. package/dist/cli/chunks/{chunk-6EP3GHED.js → chunk-SRJ5N7LD.js} +2 -2
  112. package/dist/cli/chunks/{chunk-XDYTQPJM.js → chunk-T5ADVYPH.js} +1 -1
  113. package/dist/cli/chunks/{chunk-TYZGEVP6.js → chunk-THYGFSTA.js} +12 -6
  114. package/dist/cli/chunks/{chunk-XKH4E2IQ.js → chunk-TX2DBLTL.js} +1 -1
  115. package/dist/cli/chunks/{chunk-HJDHQBMJ.js → chunk-UJMGNO6L.js} +1 -1
  116. package/dist/cli/chunks/{chunk-MCXRS2TZ.js → chunk-UUQ3SOKM.js} +1 -1
  117. package/dist/cli/chunks/{chunk-USN2JKUW.js → chunk-V5RLGPEW.js} +2 -2
  118. package/dist/cli/chunks/chunk-V6HM2BKJ.js +2 -0
  119. package/dist/cli/chunks/{chunk-R5IW5ARI.js → chunk-V7I6FTLG.js} +1 -1
  120. package/dist/cli/chunks/{chunk-2MKSEL6F.js → chunk-V7ZBPSVG.js} +1 -1
  121. package/dist/cli/chunks/{chunk-IOINZWNA.js → chunk-VJL7DNUU.js} +29 -17
  122. package/dist/cli/chunks/{chunk-JCDEMPJS.js → chunk-VKCWWR6C.js} +1 -1
  123. package/dist/cli/chunks/chunk-VKNCMGOJ.js +29 -0
  124. package/dist/cli/chunks/{chunk-GRPEDIYG.js → chunk-W2VTHUDK.js} +2 -2
  125. package/dist/cli/chunks/{chunk-SAVITYEX.js → chunk-W3JB3G7C.js} +2 -2
  126. package/dist/cli/chunks/{chunk-WTXRPYNN.js → chunk-WQ4MT74X.js} +1 -1
  127. package/dist/cli/chunks/{chunk-GY4EGQO3.js → chunk-WTNM7NA4.js} +1 -1
  128. package/dist/cli/chunks/chunk-XB3SIYGU.js +62 -0
  129. package/dist/cli/chunks/{chunk-IHRFR5SV.js → chunk-XCUNQ3FK.js} +2 -2
  130. package/dist/cli/chunks/{chunk-ITBPDVK5.js → chunk-XHQFVTFD.js} +1 -1
  131. package/dist/cli/chunks/{chunk-KJZXBZQR.js → chunk-YBUUAFKR.js} +1 -1
  132. package/dist/cli/chunks/{chunk-KR2PGNXX.js → chunk-YJV6TTCW.js} +2 -2
  133. package/dist/cli/chunks/{chunk-BQLFOJ5G.js → chunk-YUSGT2CU.js} +1 -1
  134. package/dist/cli/chunks/{chunk-5E3YCZC5.js → chunk-YUTSN5BK.js} +2 -2
  135. package/dist/cli/chunks/{chunk-DDMFTEJP.js → chunk-YVMJTBXB.js} +3 -3
  136. package/dist/cli/chunks/chunk-YVQ4PR4H.js +2 -0
  137. package/dist/cli/chunks/{chunk-RYMHYTOK.js → chunk-Z2EDNMCQ.js} +3 -3
  138. package/dist/cli/chunks/{chunk-QNSUPXUU.js → chunk-ZESMMAKZ.js} +2 -2
  139. package/dist/cli/chunks/chunk-ZIVOT3B7.js +2 -0
  140. package/dist/cli/chunks/{ci-BYCH3NPL.js → ci-NSF6OHB4.js} +2 -2
  141. package/dist/cli/chunks/{ci-output-P7P4XH6F.js → ci-output-ZPDJ42U3.js} +2 -2
  142. package/dist/cli/chunks/{circuit-breaker-VLX556ZI.js → circuit-breaker-Y2RUJDYG.js} +2 -2
  143. package/dist/cli/chunks/{claude-flow-setup-JPR425PL.js → claude-flow-setup-OH6G6KM2.js} +2 -2
  144. package/dist/cli/chunks/client-QQGRKAY7.js +2 -0
  145. package/dist/cli/chunks/{cline-installer-FOY47NSH.js → cline-installer-IHH4F27G.js} +2 -2
  146. package/dist/cli/chunks/{code-57SN4ZDY.js → code-SFAHWFTX.js} +2 -2
  147. package/dist/cli/chunks/{code-index-extractor-GT7UFRYU.js → code-index-extractor-GXECMOM2.js} +2 -2
  148. package/dist/cli/chunks/{codex-installer-JAGWONAV.js → codex-installer-UPMSAFCQ.js} +2 -2
  149. package/dist/cli/chunks/{completions-7YLHPGSV.js → completions-5TX6LDHY.js} +2 -2
  150. package/dist/cli/chunks/{complexity-analyzer-TQUF6BEI.js → complexity-analyzer-J2ZR3XZB.js} +2 -2
  151. package/dist/cli/chunks/{continuedev-installer-TICV6IGT.js → continuedev-installer-GWYZKB5A.js} +2 -2
  152. package/dist/cli/chunks/{copilot-installer-A6PDMI52.js → copilot-installer-DQZMQWI7.js} +2 -2
  153. package/dist/cli/chunks/{cost-tracker-NZPNHNV2.js → cost-tracker-V7KIGCLZ.js} +2 -2
  154. package/dist/cli/chunks/{coverage-HBEB2LKS.js → coverage-3X6LA2GZ.js} +3 -3
  155. package/dist/cli/chunks/cross-domain-router-3SHAGRVP.js +2 -0
  156. package/dist/cli/chunks/{cursor-installer-R4FM7MGN.js → cursor-installer-ENDG4JIU.js} +2 -2
  157. package/dist/cli/chunks/daemon-4XVAO7GT.js +16 -0
  158. package/dist/cli/chunks/daemon-TC65CQFK.js +10 -0
  159. package/dist/cli/chunks/{dag-attention-scheduler-2L7VCYZ3.js → dag-attention-scheduler-JOSCDRZC.js} +2 -2
  160. package/dist/cli/chunks/{detect-EEWB4IYE.js → detect-KWZX3OMK.js} +2 -2
  161. package/dist/cli/chunks/{dist-node-7RM6BB2X.js → dist-node-R4U2PJ47.js} +2 -2
  162. package/dist/cli/chunks/{domain-handler-RVGHBDUJ.js → domain-handler-BMYYZO2L.js} +2 -2
  163. package/dist/cli/chunks/{domain-transfer-M5MERQG5.js → domain-transfer-MSDBBDLC.js} +2 -2
  164. package/dist/cli/chunks/dream-OCZK42FM.js +2 -0
  165. package/dist/cli/chunks/{embed-and-insert-pattern-MS55QS73.js → embed-and-insert-pattern-MFINPOLS.js} +2 -2
  166. package/dist/cli/chunks/{eval-MBTMI7KN.js → eval-OER6UNUY.js} +2 -2
  167. package/dist/cli/chunks/{experience-capture-middleware-Z5XB7D6A.js → experience-capture-middleware-F5I77ECG.js} +3 -3
  168. package/dist/cli/chunks/{fast-paths-FSWLHI4I.js → fast-paths-P3KT5DUQ.js} +2 -2
  169. package/dist/cli/chunks/{feature-flags-QUPNH2J5.js → feature-flags-5EBWQ5WU.js} +2 -2
  170. package/dist/cli/chunks/{feature-flags-ATYOPR5D.js → feature-flags-DYFZSQLV.js} +2 -2
  171. package/dist/cli/chunks/{file-discovery-SOJJEQ2E.js → file-discovery-MOBVABSM.js} +2 -2
  172. package/dist/cli/chunks/{fleet-PWBTDWVG.js → fleet-J3R3NQNC.js} +3 -3
  173. package/dist/cli/chunks/{gnn-wrapper-2N67VQOQ.js → gnn-wrapper-QD76SULF.js} +2 -2
  174. package/dist/cli/chunks/{heartbeat-handler-5PSG2UPO.js → heartbeat-handler-AJEWTPZ4.js} +4 -4
  175. package/dist/cli/chunks/heartbeat-scheduler-EAVZR6TJ.js +2 -0
  176. package/dist/cli/chunks/hnsw-adapter-BY4XB7FB.js +2 -0
  177. package/dist/cli/chunks/hnsw-index-657CZRG7.js +2 -0
  178. package/dist/cli/chunks/{hnsw-legacy-bridge-YIXH5T4U.js → hnsw-legacy-bridge-5VRM5N7K.js} +2 -2
  179. package/dist/cli/chunks/{better-sqlite3-3U2AVWQ3.js → hnswlib-node-BWUH4OQT.js} +2 -2
  180. package/dist/cli/chunks/hooks-7PMVKQOE.js +248 -0
  181. package/dist/cli/chunks/{hybrid-router-RL47S47Z.js → hybrid-router-2K2LW45J.js} +2 -2
  182. package/dist/cli/chunks/{hypergraph-engine-XW2IHFWW.js → hypergraph-engine-2CQ735JO.js} +2 -2
  183. package/dist/cli/chunks/{hypergraph-handler-AQXKY4UF.js → hypergraph-handler-AQ53GVIW.js} +3 -3
  184. package/dist/cli/chunks/impact-analyzer-GI6UVAMT.js +2 -0
  185. package/dist/cli/chunks/{init-handler-KXYGJQI5.js → init-handler-ZOVJPAWO.js} +6 -6
  186. package/dist/cli/chunks/init-wizard-HOH577MH.js +2 -0
  187. package/dist/cli/chunks/kernel-JDYBG5GE.js +2 -0
  188. package/dist/cli/chunks/{kilocode-installer-VSULDGRO.js → kilocode-installer-GWQCNLKI.js} +2 -2
  189. package/dist/cli/chunks/{kiro-installer-SH4D2UXW.js → kiro-installer-6KVES4MO.js} +2 -2
  190. package/dist/cli/chunks/knowledge-graph-RAQOWLG3.js +2 -0
  191. package/dist/cli/chunks/learning-6XMNWXRT.js +117 -0
  192. package/dist/cli/chunks/{llm-router-YXXSQX5K.js → llm-router-GS4AZJJC.js} +4 -4
  193. package/dist/cli/chunks/{load-S52R2SLL.js → load-FEMEQNE6.js} +2 -2
  194. package/dist/cli/chunks/load-test-3MEJ43U2.js +2 -0
  195. package/dist/cli/chunks/{mcp-ZWMAJIU7.js → mcp-6V2H7EXU.js} +2 -2
  196. package/dist/cli/chunks/{memory-4YTWWDK7.js → memory-YLGPOB2H.js} +5 -5
  197. package/dist/cli/chunks/memory-backend-2A47ZRGO.js +2 -0
  198. package/dist/cli/chunks/memory-handlers-UBTBC7D2.js +2 -0
  199. package/dist/cli/chunks/{multi-model-executor-F3VEM2UF.js → multi-model-executor-SL2EKAH2.js} +2 -2
  200. package/dist/cli/chunks/{opencode-installer-Z2CUJQ6D.js → opencode-installer-ADOJVGNA.js} +2 -2
  201. package/dist/cli/chunks/{orchestrator-UPXR2XOF.js → orchestrator-O4IWW2VU.js} +37 -18
  202. package/dist/cli/chunks/{pipeline-6MEMAIXM.js → pipeline-5BD5YQNQ.js} +2 -2
  203. package/dist/cli/chunks/{platform-H72FLOM7.js → platform-HXSUOOJH.js} +2 -2
  204. package/dist/cli/chunks/{plugin-GIMQFDVR.js → plugin-HOLH5CUH.js} +2 -2
  205. package/dist/cli/chunks/{prime-radiant-advanced-wasm-DM5FR5SV.js → prime-radiant-advanced-wasm-PJTL7OLS.js} +2 -2
  206. package/dist/cli/chunks/protocol-executor-3FR7FBVM.js +2 -0
  207. package/dist/cli/chunks/{protocol-handler-YW3N333B.js → protocol-handler-K27YGLC7.js} +2 -2
  208. package/dist/cli/chunks/{prove-IJY524KK.js → prove-MHCLHQQ6.js} +2 -2
  209. package/dist/cli/chunks/{provider-manager-FNG6YR2V.js → provider-manager-3645PPXX.js} +2 -2
  210. package/dist/cli/chunks/qe-reasoning-bank-CHNYPYQW.js +2 -0
  211. package/dist/cli/chunks/{quality-EZLAMSCP.js → quality-NDE6EDOY.js} +2 -2
  212. package/dist/cli/chunks/queen-coordinator-J6ZRYTBX.js +2 -0
  213. package/dist/cli/chunks/{real-embeddings-MFRCC6GH.js → real-embeddings-VD3EVV3U.js} +2 -2
  214. package/dist/cli/chunks/{roocode-installer-H3ZIRGWU.js → roocode-installer-63Y45UUG.js} +2 -2
  215. package/dist/cli/chunks/router-23HRN2Z6.js +2 -0
  216. package/dist/cli/chunks/routing-feedback-R6A4B6ZG.js +2 -0
  217. package/dist/cli/chunks/{routing-handler-T2A7FYHW.js → routing-handler-76XISU2E.js} +2 -2
  218. package/dist/cli/chunks/{ruvector-commands-TCLWBP2M.js → ruvector-commands-AEKOZZHZ.js} +2 -2
  219. package/dist/cli/chunks/{rvf-dual-writer-BE3JCPYC.js → rvf-dual-writer-4DMUIZQF.js} +2 -2
  220. package/dist/cli/chunks/{rvf-migration-adapter-MLUX5YGR.js → rvf-migration-adapter-YUTXFOZ3.js} +2 -2
  221. package/dist/cli/chunks/{rvf-migration-coordinator-OAQXTASZ.js → rvf-migration-coordinator-XJ5N2W37.js} +2 -2
  222. package/dist/cli/chunks/rvf-native-adapter-QINEJZM7.js +2 -0
  223. package/dist/cli/chunks/safe-db-YXMCSKFH.js +2 -0
  224. package/dist/cli/chunks/schedule-XVFD27P5.js +2 -0
  225. package/dist/cli/chunks/scheduler-NWH2IDEU.js +2 -0
  226. package/dist/cli/chunks/{security-SHWJWJ4M.js → security-6YS6GQGO.js} +3 -3
  227. package/dist/cli/chunks/shared-rvf-adapter-FTZY35WI.js +2 -0
  228. package/dist/cli/chunks/{shared-rvf-dual-writer-BKSR2FFK.js → shared-rvf-dual-writer-MH2Y65HA.js} +2 -2
  229. package/dist/cli/chunks/sqlite-persistence-BR6YJF5P.js +2 -0
  230. package/dist/cli/chunks/{status-handler-QK5KMKYC.js → status-handler-57JQMPY5.js} +2 -2
  231. package/dist/cli/chunks/{structural-health-3BRNCAYQ.js → structural-health-34D5VWRD.js} +2 -2
  232. package/dist/cli/chunks/sync-HJD2US5P.js +2 -0
  233. package/dist/cli/chunks/sync-TTQ6ZB5D.js +17 -0
  234. package/dist/cli/chunks/{task-handler-VH2CLUIA.js → task-handler-4RF57637.js} +2 -2
  235. package/dist/cli/chunks/{task-handlers-BUZNV2VX.js → task-handlers-BRSK7HDE.js} +3 -3
  236. package/dist/cli/chunks/{test-K24JQQZ2.js → test-GMUW2VR3.js} +4 -4
  237. package/dist/cli/chunks/{test-scheduling-MHXRV5VI.js → test-scheduling-7LF24IFV.js} +3 -3
  238. package/dist/cli/chunks/{token-bootstrap-3NZDLG52.js → token-bootstrap-VYT4RTHU.js} +2 -2
  239. package/dist/cli/chunks/{token-usage-C4BGA2O7.js → token-usage-NFNCPQGW.js} +2 -2
  240. package/dist/cli/chunks/{transformers-ZIIFB2V4.js → transformers-GGD5GIEY.js} +2 -2
  241. package/dist/cli/chunks/{tree-sitter-wasm-parser-GES2AV7A.js → tree-sitter-wasm-parser-GKYG6NKT.js} +2 -2
  242. package/dist/cli/chunks/{types-L3MO5VNC.js → types-WJ3ZTRD5.js} +2 -2
  243. package/dist/cli/chunks/unified-memory-AT3Z4CY7.js +2 -0
  244. package/dist/cli/chunks/unified-memory-hnsw-6FOIGINN.js +2 -0
  245. package/dist/cli/chunks/unified-persistence-TCJB7MQS.js +2 -0
  246. package/dist/cli/chunks/{upgrade-EKJYS5S5.js → upgrade-IMBT4F6K.js} +2 -2
  247. package/dist/cli/chunks/{validate-WYWWB5PQ.js → validate-76OVF45Z.js} +2 -2
  248. package/dist/cli/chunks/{validate-swarm-SBSWKJ3H.js → validate-swarm-HH2ZYWXA.js} +2 -2
  249. package/dist/cli/chunks/{vibium-VEMTLNFV.js → vibium-74WQNDBX.js} +2 -2
  250. package/dist/cli/chunks/visual-security-IBAUX2K5.js +2 -0
  251. package/dist/cli/chunks/{web-tree-sitter-STW2WR2J.js → web-tree-sitter-W6RGE4SL.js} +2 -2
  252. package/dist/cli/chunks/{windsurf-installer-6ZXMJASZ.js → windsurf-installer-7DMSFCA2.js} +2 -2
  253. package/dist/cli/chunks/{witness-chain-PTULB4MR.js → witness-chain-BLZ4ZKAD.js} +2 -2
  254. package/dist/cli/chunks/witness-chain-GNNF23XU.js +2 -0
  255. package/dist/cli/chunks/{workflow-TEBAAHNR.js → workflow-RNSDKRZ4.js} +4 -4
  256. package/dist/cli/chunks/workflow-orchestrator-S2YONHGM.js +2 -0
  257. package/dist/cli/chunks/{wrappers-DVMVRKXK.js → wrappers-J7RXMIOY.js} +2 -2
  258. package/dist/cli/commands/hooks-handlers/editing-hooks.js +9 -3
  259. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +16 -24
  260. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +1 -1
  261. package/dist/cli/commands/hooks-handlers/hooks-shared.js +8 -1
  262. package/dist/cli/commands/hooks-handlers/routing-hooks.js +15 -3
  263. package/dist/cli/commands/hooks-handlers/task-hooks.js +37 -46
  264. package/dist/cli/commands/learning.js +194 -0
  265. package/dist/domains/learning-optimization/services/learning-coordinator.js +37 -17
  266. package/dist/init/phases/10-workers.js +20 -1
  267. package/dist/kernel/hybrid-backend.d.ts +17 -7
  268. package/dist/kernel/hybrid-backend.js +24 -10
  269. package/dist/kernel/interfaces.d.ts +33 -6
  270. package/dist/kernel/kernel.d.ts +1 -0
  271. package/dist/kernel/kernel.js +57 -0
  272. package/dist/kernel/memory-backend.d.ts +5 -5
  273. package/dist/kernel/memory-backend.js +14 -7
  274. package/dist/kernel/unified-memory-schemas.d.ts +1 -1
  275. package/dist/kernel/unified-memory-schemas.js +7 -1
  276. package/dist/learning/agent-routing.d.ts +134 -1
  277. package/dist/learning/agent-routing.js +185 -2
  278. package/dist/learning/dream/dream-insights-pruner.d.ts +49 -0
  279. package/dist/learning/dream/dream-insights-pruner.js +53 -0
  280. package/dist/learning/dream/dream-scheduler.js +17 -0
  281. package/dist/learning/loop-health.d.ts +84 -0
  282. package/dist/learning/loop-health.js +91 -0
  283. package/dist/learning/pattern-usage-recorder.d.ts +58 -0
  284. package/dist/learning/pattern-usage-recorder.js +72 -0
  285. package/dist/learning/qe-reasoning-bank-types.d.ts +11 -0
  286. package/dist/learning/qe-reasoning-bank.d.ts +11 -0
  287. package/dist/learning/qe-reasoning-bank.js +86 -3
  288. package/dist/learning/routing-topology-gate.d.ts +40 -0
  289. package/dist/learning/routing-topology-gate.js +55 -0
  290. package/dist/learning/sqlite-persistence.d.ts +6 -1
  291. package/dist/learning/sqlite-persistence.js +14 -20
  292. package/dist/mcp/bundle.js +3837 -3811
  293. package/dist/mcp/handlers/core-handlers.js +21 -0
  294. package/dist/routing/routing-feedback.js +7 -3
  295. package/dist/routing/routing-outcomes-migration.d.ts +31 -0
  296. package/dist/routing/routing-outcomes-migration.js +60 -0
  297. package/dist/workers/interfaces.d.ts +26 -0
  298. package/dist/workers/worker-manager.d.ts +15 -12
  299. package/dist/workers/worker-manager.js +11 -0
  300. package/dist/workers/workers/learning-consolidation.d.ts +28 -0
  301. package/dist/workers/workers/learning-consolidation.js +302 -71
  302. package/package.json +3 -1
  303. package/dist/cli/chunks/adapter-HV42JOZD.js +0 -2
  304. package/dist/cli/chunks/aqe-learning-engine-GL22PE2V.js +0 -2
  305. package/dist/cli/chunks/base-4KQ2FGUX.js +0 -2
  306. package/dist/cli/chunks/browser-workflow-CTE7BDM4.js +0 -2
  307. package/dist/cli/chunks/chunk-3NGNSKL3.js +0 -14
  308. package/dist/cli/chunks/chunk-6HSFZ6SL.js +0 -180
  309. package/dist/cli/chunks/chunk-7Z3GBQNV.js +0 -2
  310. package/dist/cli/chunks/chunk-AQJ6XS34.js +0 -2
  311. package/dist/cli/chunks/chunk-H2IMXQCJ.js +0 -2
  312. package/dist/cli/chunks/chunk-SPCANEJY.js +0 -95
  313. package/dist/cli/chunks/client-FRVNMXQO.js +0 -2
  314. package/dist/cli/chunks/cross-domain-router-BVCPAWG2.js +0 -2
  315. package/dist/cli/chunks/daemon-PHIZPZIE.js +0 -19
  316. package/dist/cli/chunks/dream-77ODIFIF.js +0 -2
  317. package/dist/cli/chunks/hnsw-adapter-CQGQS3V7.js +0 -2
  318. package/dist/cli/chunks/hnsw-index-2ACF6FOJ.js +0 -2
  319. package/dist/cli/chunks/hooks-YROFO6PE.js +0 -259
  320. package/dist/cli/chunks/impact-analyzer-LWEGK23B.js +0 -2
  321. package/dist/cli/chunks/init-wizard-7BS3QMWR.js +0 -2
  322. package/dist/cli/chunks/kernel-TX67WXSI.js +0 -2
  323. package/dist/cli/chunks/knowledge-graph-TDSP2UE2.js +0 -2
  324. package/dist/cli/chunks/learning-RRWV3SEL.js +0 -107
  325. package/dist/cli/chunks/load-test-GEBBBUMV.js +0 -2
  326. package/dist/cli/chunks/memory-backend-WQS2MLW2.js +0 -2
  327. package/dist/cli/chunks/memory-handlers-RTY5MBA5.js +0 -2
  328. package/dist/cli/chunks/protocol-executor-DT7XHMLL.js +0 -2
  329. package/dist/cli/chunks/qe-reasoning-bank-LDNETZVA.js +0 -2
  330. package/dist/cli/chunks/queen-coordinator-AF7HCQSM.js +0 -2
  331. package/dist/cli/chunks/router-OWQ5EI72.js +0 -2
  332. package/dist/cli/chunks/routing-feedback-B43DEQMK.js +0 -2
  333. package/dist/cli/chunks/rvf-native-adapter-XBJDXHNI.js +0 -2
  334. package/dist/cli/chunks/safe-db-RT3LEDUG.js +0 -2
  335. package/dist/cli/chunks/schedule-EHUDCKS2.js +0 -2
  336. package/dist/cli/chunks/scheduler-GEGZ4J3C.js +0 -2
  337. package/dist/cli/chunks/shared-rvf-adapter-LNBUNRAM.js +0 -2
  338. package/dist/cli/chunks/sqlite-persistence-3DGRJH3K.js +0 -2
  339. package/dist/cli/chunks/sync-5CDYOT3H.js +0 -23
  340. package/dist/cli/chunks/unified-memory-ZSBX4LYU.js +0 -2
  341. package/dist/cli/chunks/unified-memory-hnsw-Y6EKAMRP.js +0 -2
  342. package/dist/cli/chunks/unified-persistence-2PDVU2U5.js +0 -2
  343. package/dist/cli/chunks/visual-security-RHMFLKVQ.js +0 -2
  344. package/dist/cli/chunks/witness-chain-QO237QOF.js +0 -2
  345. package/dist/cli/chunks/workflow-orchestrator-RHM5MIGE.js +0 -2
@@ -1,259 +0,0 @@
1
- #!/usr/bin/env node
2
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
3
- import{a as R,b as oe,c as re}from"./chunk-C6TNYLD7.js";import{a as ae,b as ie}from"./chunk-HA7N45KB.js";import{g as K}from"./chunk-WVODEWH5.js";import"./chunk-VRP4GB4Y.js";import"./chunk-R5IW5ARI.js";import"./chunk-2GBBZLXT.js";import"./chunk-QHKK2H4H.js";import"./chunk-IOINZWNA.js";import"./chunk-3AICELMQ.js";import{a as se}from"./chunk-XK6YXCS7.js";import"./chunk-QTS2DS42.js";import"./chunk-5DJAJPBG.js";import"./chunk-4UZQSPR4.js";import{f as T,k as j,o as H}from"./chunk-TYZGEVP6.js";import"./chunk-DJRWVNHK.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import{b as ne,d as we}from"./chunk-Q4HJRYQB.js";import"./chunk-LDGNVPBZ.js";import"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import"./chunk-CNNVL5W4.js";import"./chunk-TULNR2AH.js";import"./chunk-7D2DM23U.js";import"./chunk-37I6K7QO.js";import"./chunk-XVTZXCHI.js";import"./chunk-KR2PGNXX.js";import"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";import{Command as Be}from"commander";import P from"chalk";import me from"node:path";H();import{randomUUID as B}from"crypto";import x from"chalk";var N="dream-scheduler:hook-state",ce=36e5,de=20,ue=3e5;async function Y(n){try{let e=await n.get(N);if(!e)return{triggered:!1,reason:"no-state"};let t=Date.now(),s=e.lastDreamTime?new Date(e.lastDreamTime).getTime():0,o=t-s;if(o<ue)return{triggered:!1,reason:"too-soon"};let r=o>=ce,a=e.experienceCount>=de;if(!r&&!a)return{triggered:!1,reason:"conditions-not-met"};let c=r?"time-interval":"experience-threshold";console.log(x.dim(`[hooks] Dream trigger: ${c} (${e.experienceCount} experiences, ${Math.round(o/6e4)}min since last dream)`));try{let{getUnifiedMemory:m}=await import("./unified-memory-ZSBX4LYU.js"),y=m();if(y.isInitialized()){let I=y.getDatabase().prepare(`SELECT COUNT(*) AS n FROM dream_cycles
4
- WHERE status = 'running'
5
- AND start_time > datetime('now', '-60 seconds')`).get();if(I&&I.n>0)return{triggered:!1,reason:"already-running"}}}catch{}let{createDreamEngine:i}=await import("./dream-77ODIFIF.js"),{createQEReasoningBank:h}=await import("./qe-reasoning-bank-LDNETZVA.js"),d=i({maxDurationMs:1e4,minConceptsRequired:3});await d.initialize();let p=h(n,void 0,{enableLearning:!0,enableGuidance:!1,enableRouting:!1,embeddingDimension:384,useONNXEmbeddings:!0});await p.initialize();let u=await p.searchPatterns("",{limit:100,minConfidence:.3});if(u.success&&u.value.length>0){let m=u.value.map(y=>({id:y.pattern.id,name:y.pattern.name,description:y.pattern.description||`${y.pattern.patternType} pattern`,domain:y.pattern.qeDomain||"learning-optimization",patternType:y.pattern.patternType,confidence:y.pattern.confidence,successRate:y.pattern.successRate||.5}));await d.loadPatternsAsConcepts(m)}let l=await d.dream(1e4),f=0;try{for(let m of l.insights)m.actionable&&m.confidenceScore>=.5&&(await d.applyInsight(m.id)).success&&f++}catch(m){console.error(x.dim(`[hooks] Dream apply: ${m instanceof Error?m.message:"unknown"}`))}return e.lastDreamTime=new Date().toISOString(),e.experienceCount=0,e.totalDreamsThisSession++,await n.set(N,e),await d.close(),{triggered:!0,reason:c,insightsGenerated:l.insights.length,insightsApplied:f}}catch(e){return console.error(x.dim(`[hooks] Dream trigger failed: ${e instanceof Error?e.message:"unknown"}`)),{triggered:!1,reason:"error"}}}async function O(n){try{let e=await n.get(N);return e||(e={lastDreamTime:null,experienceCount:0,sessionStartTime:new Date().toISOString(),totalDreamsThisSession:0}),e.experienceCount++,await n.set(N,e),e.experienceCount}catch{return 0}}async function U(n){try{let{getUnifiedMemory:e}=await import("./unified-memory-ZSBX4LYU.js"),t=e();t.isInitialized()||await t.initialize();let{initializeExperienceCapture:s}=await import("./experience-capture-middleware-Z5XB7D6A.js");await s();let o=t.getDatabase();try{o.pragma("busy_timeout = 60000")}catch{}let r=`cli-${Date.now()}-${B().slice(0,8)}`,a=n.durationMs||0,c;if(n.success){let i=a>0&&a<5e3?.1:0,h=n.source.includes("post-task")?.1:n.source.includes("post-edit")?.05:0;c=Math.min(.95,.7+i+h)}else{let i=n.source.includes("post-task")?.15:n.source.includes("post-edit")?.1:0;c=Math.min(.6,.3+i)}o.prepare(`
6
- INSERT OR REPLACE INTO captured_experiences
7
- (id, task, agent, domain, success, quality, duration_ms,
8
- started_at, completed_at, source)
9
- VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'), ?)
10
- `).run(r,n.task.slice(0,500),n.agent,n.domain,n.success?1:0,c,a,n.source),(async()=>{try{let{computeRealEmbedding:i}=await import("./real-embeddings-MFRCC6GH.js"),h=`${n.domain}: ${n.task}`.slice(0,512),d=await i(h);o.prepare("UPDATE captured_experiences SET embedding = ?, embedding_dimension = ? WHERE id = ?").run(Buffer.from(new Float32Array(d).buffer),d.length,r)}catch{}})()}catch(e){console.error(x.dim(`[hooks] persistCommandExperience: ${e instanceof Error?e.message:"unknown"}`))}}async function Z(n){let{getUnifiedMemory:e}=await import("./unified-memory-ZSBX4LYU.js"),t=e();t.isInitialized()||await t.initialize();let s=t.getDatabase();try{s.pragma("busy_timeout = 60000")}catch{}let o=`exp-${Date.now()}-${B().slice(0,8)}`,r=`${n.agent}:${n.taskId}`,a=n.durationMs??0,c=n.success?1:0,i=a<100?1:a<500?.8:a<2e3?.6:a<5e3?.4:a<1e4?.2:.1,h=.25*c+.325+.1*i,d=null,p=0,u=0,l=s.transaction(()=>{s.prepare(`
11
- INSERT INTO captured_experiences
12
- (id, task, agent, domain, success, quality, duration_ms,
13
- model_tier, started_at, completed_at, source)
14
- VALUES (?, ?, ?, ?, ?, ?, ?, NULL, datetime('now'), datetime('now'), ?)
15
- `).run(o,r.slice(0,500),n.agent,n.domain??"general",n.success?1:0,h,a,"cli-hook-post-task"),s.prepare(`
16
- INSERT INTO experience_applications
17
- (id, experience_id, task, success, tokens_saved, feedback, applied_at)
18
- VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
19
- `).run(`app-${Date.now()}-${B().slice(0,8)}`,o,r,n.success?1:0,Math.round(h*100),`[Patch 060] post-task outcome: ${n.success?"success":"failure"}`);try{let m=s.prepare(`
20
- SELECT key, value FROM kv_store
21
- WHERE namespace = 'task-bridge'
22
- AND (expires_at IS NULL OR expires_at > strftime('%s','now') * 1000)
23
- ORDER BY created_at DESC
24
- LIMIT 1
25
- `).get();if(m?.value)try{d=JSON.parse(m.value)}catch{d=null}if(d&&Array.isArray(d.selectedPatternIds)&&d.selectedPatternIds.length>0){let y=d.estimatedTokenSavings&&d.selectedPatternIds.length?Math.round(d.estimatedTokenSavings/d.selectedPatternIds.length):0,$=s.prepare(`
26
- INSERT INTO experience_applications
27
- (id, experience_id, task, success, tokens_saved, feedback, applied_at)
28
- VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
29
- `),I=s.prepare(`
30
- UPDATE qe_patterns SET
31
- usage_count = usage_count + 1,
32
- successful_uses = successful_uses + ?,
33
- success_rate = CAST(successful_uses + ? AS REAL) / CAST(usage_count + 1 AS REAL),
34
- quality_score = ? * 0.3
35
- + MIN(CAST(usage_count + 1 AS REAL) / 100.0, 1.0) * 0.2
36
- + (CAST(successful_uses + ? AS REAL) / CAST(usage_count + 1 AS REAL)) * 0.5,
37
- last_used_at = datetime('now'),
38
- updated_at = datetime('now')
39
- WHERE id = ?
40
- `),J=s.prepare("SELECT confidence FROM qe_patterns WHERE id = ?"),A=s.prepare(`
41
- SELECT tier, successful_uses, success_rate, confidence
42
- FROM qe_patterns
43
- WHERE id = ?
44
- `),G=s.prepare(`
45
- UPDATE qe_patterns
46
- SET tier = 'long-term', updated_at = datetime('now')
47
- WHERE id = ?
48
- AND tier = 'short-term'
49
- AND successful_uses >= 3
50
- AND success_rate >= 0.7
51
- AND confidence >= 0.6
52
- `);for(let M of d.selectedPatternIds){$.run(`app-${Date.now()}-${B().slice(0,8)}`,o,`${r}:pattern:${M}`,n.success?1:0,y,`[Patch 160+300] task-bridge pattern_id=${M} ts=${y}`);try{let q=J.get(M);if(q){let V=n.success?1:0;I.run(V,V,q.confidence,V,M)}}catch{}try{let q=A.get(M);q?.tier==="short-term"&&q.successful_uses>=3&&q.success_rate>=.7&&q.confidence>=.6&&G.run(M)}catch{}}m&&s.prepare("DELETE FROM kv_store WHERE namespace='task-bridge' AND key = ?").run(m.key)}}catch(m){console.error(x.dim(`[hooks] post-task bridge: ${m instanceof Error?m.message:"unknown"}`))}let f=`traj-${Date.now()}-${B().slice(0,8)}`;s.prepare(`
53
- INSERT INTO qe_trajectories (id, task, agent, domain, started_at, ended_at, success, steps_json)
54
- VALUES (?, ?, ?, ?, datetime('now'), datetime('now'), ?, ?)
55
- `).run(f,r,n.agent,n.domain??"general",n.success?1:0,JSON.stringify([{step:1,task:n.taskId,success:n.success}]));try{let m=s.prepare(`
56
- SELECT id, task, agent, success, started_at, completed_at
57
- FROM captured_experiences
58
- WHERE consolidated_into IS NULL
59
- AND task LIKE ?
60
- AND started_at > datetime('now', '-1 hour')
61
- ORDER BY started_at ASC
62
- `).all(`%:${n.taskId}`);if(m.length>=2){let y=`traj-multi-${Date.now()}-${B().slice(0,8)}`,$=JSON.stringify(m.map((A,G)=>({step:G+1,task:A.task,agent:A.agent,success:!!A.success,started_at:A.started_at,completed_at:A.completed_at}))),I=m.every(A=>!!A.success);s.prepare(`
63
- INSERT INTO qe_trajectories (id, task, agent, domain, started_at, ended_at, success, steps_json)
64
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
65
- `).run(y,`multi:${n.taskId}`,n.agent,n.domain??"general",m[0].started_at,m[m.length-1].completed_at,I?1:0,$);let J=m.map(()=>"?").join(",");s.prepare(`UPDATE captured_experiences SET consolidated_into = ? WHERE id IN (${J})`).run(y,...m.map(A=>A.id)),p=m.length}}catch(m){console.error(x.dim(`[hooks] post-task stitch: ${m instanceof Error?m.message:"unknown"}`))}if(n.success)try{u=s.prepare(`
66
- UPDATE dream_insights
67
- SET applied = COALESCE(applied, 0) + 1
68
- WHERE id IN (
69
- SELECT id FROM dream_insights
70
- WHERE actionable = 1
71
- ORDER BY created_at DESC
72
- LIMIT 3
73
- )
74
- `).run().changes??0}catch{}});try{l()}catch(f){console.error(x.dim(`[hooks] persistTaskOutcome txn: ${f instanceof Error?f.message:"unknown"}`))}return(async()=>{try{let{computeRealEmbedding:f}=await import("./real-embeddings-MFRCC6GH.js"),m=`${n.domain??"general"}: ${r}`.slice(0,512),y=await f(m);s.prepare("UPDATE captured_experiences SET embedding = ?, embedding_dimension = ? WHERE id = ?").run(Buffer.from(new Float32Array(y).buffer),y.length,o)}catch{}})(),{experienceId:o,qualityScore:h,bridge:d,stitchedSiblings:p,insightsApplied:u}}async function X(n){try{let{getUnifiedMemory:e}=await import("./unified-memory-ZSBX4LYU.js"),t=e();t.isInitialized()||await t.initialize();let s=t.getDatabase();try{s.pragma("busy_timeout = 60000")}catch{}let o=`${n.taskType}|${n.priority}|${n.domain||"any"}|${n.complexityBucket}`,r=n.agent,a=`q-learning:aqe-hook-router:${o}:${r}`,c=n.success?.1:-1,i=.1,h=.9,d=s.prepare(`
75
- SELECT q_value FROM rl_q_values WHERE id = ?
76
- `).get(a),p=d&&typeof d.q_value=="number"?d.q_value:0,u=s.prepare(`
77
- SELECT MAX(q_value) AS m FROM rl_q_values WHERE state_key = ?
78
- `).get(o),l=u&&typeof u.m=="number"?u.m:0,f=p+i*(c+h*l-p);s.prepare(`
79
- INSERT INTO rl_q_values
80
- (id, algorithm, agent_id, state_key, action_key, q_value, visits, last_reward, domain, created_at, updated_at)
81
- VALUES (?, 'q-learning', 'aqe-hook-router', ?, ?, ?, 1, ?, ?, datetime('now'), datetime('now'))
82
- ON CONFLICT(algorithm, agent_id, state_key, action_key) DO UPDATE SET
83
- q_value = excluded.q_value,
84
- visits = visits + 1,
85
- last_reward = excluded.last_reward,
86
- updated_at = datetime('now')
87
- `).run(a,o,r,f,c,n.domain||"any")}catch(e){console.error(x.dim(`[hooks] q-learning update: ${e instanceof Error?e.message:"unknown"}`))}}async function ee(n){try{let{getUnifiedMemory:e}=await import("./unified-memory-ZSBX4LYU.js"),t=e();t.isInitialized()||await t.initialize();let s=t.getDatabase();try{s.pragma("busy_timeout = 60000")}catch{}s.prepare(`
88
- UPDATE routing_outcomes
89
- SET success = ?, quality_score = ?, duration_ms = ?
90
- WHERE id IN (
91
- SELECT id FROM routing_outcomes
92
- WHERE quality_score = -1
93
- AND task_json LIKE '%"taskId"%'
94
- AND created_at > datetime('now', '-30 minutes')
95
- ORDER BY (CASE WHEN used_agent = ? THEN 0 ELSE 1 END), created_at DESC
96
- LIMIT 1
97
- )
98
- `).run(n.success?1:0,n.qualityScore,n.durationMs,n.agent)}catch(e){console.error(x.dim(`[hooks] routing UPDATE: ${e instanceof Error?e.message:"unknown"}`))}}async function te(){let{getUnifiedMemory:n}=await import("./unified-memory-ZSBX4LYU.js"),e=n();e.isInitialized()||await e.initialize();let t=e.getDatabase();try{t.pragma("busy_timeout = 60000")}catch{}let s=new Set(t.prepare("PRAGMA table_info(captured_experiences)").all().map(i=>i.name)),o=[["consolidated_into","TEXT DEFAULT NULL"],["consolidation_count","INTEGER DEFAULT 1"],["quality_updated_at","TEXT DEFAULT NULL"],["reuse_success_count","INTEGER DEFAULT 0"],["reuse_failure_count","INTEGER DEFAULT 0"]];for(let[i,h]of o)s.has(i)||t.exec(`ALTER TABLE captured_experiences ADD COLUMN ${i} ${h}`);let r=t.prepare(`
99
- SELECT
100
- domain,
101
- agent,
102
- COUNT(*) as cnt,
103
- AVG(quality) as avg_quality,
104
- SUM(success) as successes,
105
- CAST(SUM(success) AS REAL) / COUNT(*) as success_rate,
106
- AVG(duration_ms) as avg_duration,
107
- GROUP_CONCAT(DISTINCT source) as sources
108
- FROM captured_experiences
109
- WHERE application_count = 0
110
- GROUP BY domain, agent
111
- HAVING cnt >= 3 AND avg_quality >= 0.5 AND success_rate >= 0.6
112
- ORDER BY avg_quality DESC
113
- LIMIT 50
114
- `).all();if(r.length===0)return 0;let{v4:a}=await import("./dist-node-7RM6BB2X.js"),c=0;for(let i of r)try{let h=new Date().toISOString().slice(0,7),d=`${i.agent}-${i.domain}-${h}`,p=t.prepare(`
115
- SELECT id FROM qe_patterns
116
- WHERE qe_domain = ? AND name = ?
117
- LIMIT 1
118
- `).get(i.domain,d);if(p)t.prepare(`
119
- UPDATE qe_patterns
120
- SET usage_count = usage_count + ?,
121
- successful_uses = successful_uses + ?,
122
- confidence = MIN(0.99, confidence + 0.01),
123
- quality_score = MIN(0.99, quality_score + 0.005),
124
- updated_at = datetime('now')
125
- WHERE id = ?
126
- `).run(i.cnt,i.successes,p.id);else{let u=a(),l=Math.min(.95,i.avg_quality*.8+i.success_rate*.2),f=l*.3+Math.min(i.cnt,100)/100*.2+i.success_rate*.5,m=`Auto-consolidated from ${i.cnt} experiences. Agent: ${i.agent}, success rate: ${(i.success_rate*100).toFixed(0)}%`,y=(i.sources||"").split(",").filter(Boolean);t.prepare(`
127
- INSERT INTO qe_patterns (
128
- id, pattern_type, qe_domain, domain, name, description,
129
- confidence, usage_count, success_rate, quality_score, tier,
130
- template_json, context_json, created_at, successful_uses
131
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), ?)
132
- `).run(u,"workflow",i.domain,i.domain,d,m,l,i.cnt,i.success_rate,f,"short-term",JSON.stringify({type:"workflow",content:`${i.agent} pattern for ${i.domain}`,variables:[]}),JSON.stringify({tags:y,sourceType:"session-consolidation",extractedAt:new Date().toISOString()}),i.successes);let{ensurePatternEmbedding:$}=await import("./embed-and-insert-pattern-MS55QS73.js");await $(t,u,d,m,y),c++}t.prepare(`
133
- UPDATE captured_experiences
134
- SET application_count = application_count + 1
135
- WHERE domain = ? AND agent = ? AND application_count = 0
136
- `).run(i.domain,i.agent)}catch{}return c}var g={reasoningBank:null,hookRegistry:null,coherenceService:null,sessionId:null,initialized:!1,initializationPromise:null};async function S(){if(g.initializationPromise&&await g.initializationPromise,g.initialized&&g.reasoningBank&&g.hookRegistry)return{reasoningBank:g.reasoningBank,hookRegistry:g.hookRegistry};if(g.initializationPromise=be(),await g.initializationPromise,g.initializationPromise=null,!g.reasoningBank||!g.hookRegistry)throw new Error("Failed to initialize hooks system");return{reasoningBank:g.reasoningBank,hookRegistry:g.hookRegistry}}async function be(){if(!g.initialized)try{let n=T(),e=me.join(n,".agentic-qe"),t=await D(e);try{g.coherenceService=await ae(ie),console.log(P.dim("[hooks] CoherenceService initialized with WASM engines"))}catch(a){console.log(P.dim(`[hooks] CoherenceService WASM unavailable, using fallback: ${a instanceof Error?a.message:"unknown"}`))}g.reasoningBank=K(t,void 0,{enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0},g.coherenceService??void 0);let s=1e4,o=new AbortController,r=setTimeout(()=>o.abort(new Error("ReasoningBank init timeout")),s);try{await g.reasoningBank.initialize({signal:o.signal})}finally{clearTimeout(r)}try{let{getSharedRvfDualWriter:a}=await import("./shared-rvf-dual-writer-BKSR2FFK.js"),c=await a();c&&g.reasoningBank.setRvfDualWriter(c)}catch(a){process.env.DEBUG&&console.debug("[hooks] RVF wiring skipped:",a instanceof Error?a.message:a)}g.hookRegistry=re(g.reasoningBank),g.initialized=!0,console.log(P.dim("[hooks] System initialized"))}catch(n){console.warn(P.yellow(`[hooks] Using fallback mode: ${n instanceof Error?n.message:"unknown error"}`));let e=Te();g.reasoningBank=K(e,void 0,{enableLearning:!0,enableGuidance:!0,enableRouting:!0}),g.hookRegistry=new oe,g.hookRegistry.initialize(g.reasoningBank),g.initialized=!0}}function L(n){try{n.pragma("busy_timeout = 60000")}catch{}}async function D(n){let t=new se({sqlite:{path:me.join(n,"memory.db"),walMode:!0,poolSize:3,busyTimeout:6e4},enableFallback:!0,defaultNamespace:"qe-patterns"}),s=!1,o=t.initialize(),r=new Promise((a,c)=>setTimeout(()=>{s=!0,c(new Error("Backend init timeout"))},5e3));try{await Promise.race([o,r])}catch(a){throw s&&o.then(()=>t.dispose()).catch(()=>{}),a}return t}function Te(){let n=new Map;return{initialize:async()=>{},dispose:async()=>{n.clear()},get:async e=>{let t=n.get(e);return t?t.value:void 0},set:async(e,t,s)=>{n.set(e,{value:t})},delete:async e=>n.delete(e),has:async e=>n.has(e),search:async(e,t)=>{let s=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(s.replace(/\*/g,".*"));return Array.from(n.keys()).filter(r=>o.test(r))},vectorSearch:async(e,t)=>[],storeVector:async(e,t,s)=>{},count:async e=>{let t=0,s=`${e}:`;for(let o of n.keys())o.startsWith(s)&&t++;return t},hasCodeIntelligenceIndex:async()=>{let e="code-intelligence:kg:";for(let t of n.keys())if(t.startsWith(e))return!0;return!1}}}function k(n){console.log(JSON.stringify(n,null,2))}function v(n){console.log(P.green("\u2713"),n)}function _(n){console.error(P.red("\u2717"),n)}function W(n){if(n.length===0){console.log(P.dim(" No specific guidance"));return}n.forEach((e,t)=>{console.log(P.cyan(` ${t+1}.`),e)})}async function Q(n=500){return process.stdin.isTTY?"":new Promise(e=>{let t="",s=setTimeout(()=>{process.stdin.removeAllListeners(),process.stdin.pause(),e(t)},n);process.stdin.setEncoding("utf8"),process.stdin.on("data",o=>{t+=o}),process.stdin.on("end",()=>{clearTimeout(s),e(t)}),process.stdin.on("error",()=>{clearTimeout(s),e(t)}),process.stdin.resume()})}function le(n){if(!n.trim())return"";let e;try{e=JSON.parse(n)}catch{return""}let t=e.tool_input,s=e.toolInput,o=[t?.file_path,t?.filePath,s?.file_path,s?.filePath,e.file_path,e.filePath];for(let r of o)if(typeof r=="string"&&r.trim())return r;return""}import C from"chalk";import Re from"node:path";H();function ge(n){n.command("pre-edit").description("Get context and guidance before editing a file").requiredOption("-f, --file <path>","File path to edit").option("-o, --operation <type>","Operation type: create, update, delete, refactor","update").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await S(),o=(await t.emit(R.PreTestGeneration,{targetFile:e.file,testType:"unit",operation:e.operation}))[0]||{success:!0,guidance:[],routing:null};if(e.json){let r=o.guidance||[],c=[o.routing?.recommendedAgent?`Recommended agent: ${o.routing.recommendedAgent} (${(o.routing.confidence*100).toFixed(0)}% confidence).`:"",...r.map(i=>i)].filter(Boolean).join(" ");k({hookSpecificOutput:{hookEventName:"PreToolUse",additionalContext:c||void 0},file:e.file,operation:e.operation,patterns:o.routing?.patterns?.length||0})}else console.log(C.bold(`
137
- \u{1F4DD} Pre-Edit Analysis`)),console.log(C.dim(` File: ${e.file}`)),console.log(C.dim(` Operation: ${e.operation}`)),o.routing&&(console.log(C.bold(`
138
- \u{1F3AF} Recommended Agent:`),C.cyan(o.routing.recommendedAgent)),console.log(C.dim(` Confidence: ${(o.routing.confidence*100).toFixed(1)}%`))),console.log(C.bold(`
139
- \u{1F4A1} Guidance:`)),W(o.guidance||[]);return}catch(t){throw _(`pre-edit failed: ${t instanceof Error?t.message:"unknown"}`),t}}),n.command("post-edit").description("Record editing outcome for pattern learning").requiredOption("-f, --file <path>","File path that was edited").option("--success","Edit was successful").option("--failure","Edit failed").option("--pattern-id <id>","Pattern ID that was applied").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await S(),s=e.success||!e.failure,o=e.file||"";if(!o.trim())try{let u=await Q();o=le(u)}catch{}let r=o.split("/").pop()||"unknown",c=/\.(test|spec)\.(ts|js|tsx|jsx)$/.test(r)?"test-generation":"code-intelligence",i=e.patternId||`edit:${c}:${r}`,d=(await t.emit(R.PostTestGeneration,{targetFile:o,success:s,patternId:i,generatedTests:null,testCount:0}))[0]||{success:!0,patternsLearned:0};try{let{reasoningBank:u}=await S();await u.recordOutcome({patternId:i,success:s,metrics:{executionTimeMs:0},feedback:`Edit ${s?"succeeded":"failed"}: ${o}`})}catch{}try{await U({task:`edit: ${o}`,agent:"cli-hook",domain:c,success:s,source:"cli-hook-post-edit"})}catch{}let p=!1;try{let u=T(),l=Re.join(u,".agentic-qe"),f=await D(l);await O(f)}catch{}e.json?k({success:!0,file:o,editSuccess:s,patternsLearned:d.patternsLearned||0,dreamTriggered:p}):(v(`Recorded edit outcome for ${o||"(unknown file)"}`),d.patternsLearned&&console.log(C.green(` Patterns learned: ${d.patternsLearned}`)));return}catch(t){throw _(`post-edit failed: ${t instanceof Error?t.message:"unknown"}`),t}})}H();import{randomUUID as Ae}from"crypto";import w from"chalk";import De from"node:path";function ve(n){if(!n.trim())return"";let e;try{e=JSON.parse(n)}catch{return n.trim()}let t=[e.prompt,e.user_prompt,e.command,e.tool_input?.prompt,e.tool_input?.description,e.toolInput?.prompt,e.toolInput?.description];for(let s of t)if(typeof s=="string"&&s.trim())return s;return""}function pe(n){n.command("route").description("Route a task to the optimal QE agent").option("-t, --task <description>","Task description (falls back to stdin event JSON)").option("-d, --domain <domain>","Target QE domain hint").option("-c, --capabilities <caps...>","Required capabilities").option("--json","Output as JSON").action(async e=>{try{let t=e.task??"";if(!t.trim()){let c=await Q();t=ve(c)}if(!t.trim())throw new Error("No task provided. Pass --task <description> or pipe a Claude Code hook event JSON to stdin.");let{reasoningBank:s}=await S(),o={task:t,domain:e.domain,capabilities:e.capabilities},r=await s.routeTask(o);if(!r.success)throw new Error(r.error.message);let a=r.value;e.json?k({recommendedAgent:a.recommendedAgent,confidence:a.confidence,alternatives:a.alternatives,domains:a.domains,patternCount:a.patterns.length,guidance:a.guidance,reasoning:a.reasoning}):(console.log(w.bold(`
140
- \u{1F3AF} Task Routing Result`)),console.log(w.dim(` Task: "${t}"`)),console.log(w.bold(`
141
- \u{1F464} Recommended Agent:`),w.cyan(a.recommendedAgent)),console.log(w.dim(` Confidence: ${(a.confidence*100).toFixed(1)}%`)),a.alternatives.length>0&&(console.log(w.bold(`
142
- \u{1F504} Alternatives:`)),a.alternatives.forEach(c=>{console.log(w.dim(` - ${c.agent}: ${(c.score*100).toFixed(1)}%`))})),console.log(w.bold(`
143
- \u{1F4C2} Detected Domains:`),a.domains.join(", ")),console.log(w.bold(`
144
- \u{1F4A1} Guidance:`)),W(a.guidance),console.log(w.bold(`
145
- \u{1F4D6} Reasoning:`),w.dim(a.reasoning)));try{let{getUnifiedMemory:c}=await import("./unified-memory-ZSBX4LYU.js"),i=c();i.isInitialized()||await i.initialize();let h=i.getDatabase();L(h);let d=`route-${Date.now()}-${Ae().slice(0,8)}`,p=a.confidence<.5;h.prepare(`
146
- INSERT OR REPLACE INTO routing_outcomes (
147
- id, task_json, decision_json, used_agent,
148
- followed_recommendation, success, quality_score,
149
- duration_ms, error
150
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
151
- `).run(d,JSON.stringify({description:t,domain:e.domain}),JSON.stringify({recommended:a.recommendedAgent,confidence:a.confidence,alternatives:a.alternatives,lowConfidence:p}),a.recommendedAgent,1,0,-1,0,p?"low-confidence":null);let u=T(),l=De.join(u,".agentic-qe"),f=await D(l);await O(f)}catch(c){console.error(w.dim(`[hooks] route persist: ${c instanceof Error?c.message:"unknown"}`))}return}catch(t){throw _(`route failed: ${t instanceof Error?t.message:"unknown"}`),t}}),n.command("post-route").description("Close the most-recent route sentinel from a Stop hook (#451)").option("--success <bool>","Whether the turn completed successfully","true").option("--json","Output as JSON").action(async e=>{try{let t=e.success==="true"||e.success===!0,s=.325+(t?.25:0)+.1,o=j();o.isInitialized()||await o.initialize();let r=o.getDatabase();L(r);let a=r.prepare(`
152
- UPDATE routing_outcomes
153
- SET success = ?, quality_score = ?, duration_ms = 0, error = NULL
154
- WHERE id = (
155
- SELECT id FROM routing_outcomes
156
- WHERE quality_score = -1
157
- AND task_json NOT LIKE '%"taskId"%'
158
- ORDER BY created_at DESC
159
- LIMIT 1
160
- )
161
- `).run(t?1:0,s),c=r.prepare(`
162
- UPDATE routing_outcomes
163
- SET success = 0,
164
- quality_score = 0.325,
165
- duration_ms = 0,
166
- error = 'stale-sentinel'
167
- WHERE quality_score = -1
168
- AND task_json NOT LIKE '%"taskId"%'
169
- AND created_at < datetime('now', '-300 seconds')
170
- `).run();e.json?k({success:!0,resolved:a.changes>0,staleSwept:c.changes,qualityScore:s,turnSuccess:t}):c.changes>0&&console.log(w.dim(`[hooks] post-route: swept ${c.changes} stale sentinel(s)`));return}catch(t){e.json?k({success:!1,error:t instanceof Error?t.message:"unknown"}):console.error(w.dim(`[hooks] post-route: ${t instanceof Error?t.message:"unknown"}`));return}})}import E from"chalk";we();function fe(n){n.command("stats").description("Display hooks system statistics").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await S(),s=await t.getStats();if(e.json)k(s);else{console.log(E.bold(`
171
- \u{1F4CA} Hooks System Statistics
172
- `)),console.log(E.bold("Patterns:")),console.log(` Total: ${E.cyan(s.totalPatterns)}`),console.log(` Short-term: ${s.patternStoreStats.byTier.shortTerm}`),console.log(` Long-term: ${s.patternStoreStats.byTier.longTerm}`),console.log(E.bold(`
173
- By Domain:`));for(let[o,r]of Object.entries(s.byDomain))r>0&&console.log(` ${o}: ${r}`);console.log(E.bold(`
174
- Routing:`)),console.log(` Requests: ${s.routingRequests}`),console.log(` Avg Confidence: ${(s.avgRoutingConfidence*100).toFixed(1)}%`),console.log(E.bold(`
175
- Learning:`)),console.log(` Outcomes: ${s.learningOutcomes}`),console.log(` Success Rate: ${(s.patternSuccessRate*100).toFixed(1)}%`),console.log(E.bold(`
176
- Search Performance:`)),console.log(` Operations: ${s.patternStoreStats.searchOperations}`),console.log(` Avg Latency: ${s.patternStoreStats.avgSearchLatencyMs.toFixed(2)}ms`),console.log(` HNSW Native: ${s.patternStoreStats.hnswStats.nativeAvailable?"\u2713":"\u2717"}`)}}catch(t){throw _(`stats failed: ${t instanceof Error?t.message:"unknown"}`),t}}),n.command("list").description("List all registered QE hook events").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await S(),s=t.getRegisteredEvents();if(e.json)k({events:s,totalEvents:Object.keys(R).length,registeredEvents:s.length});else{console.log(E.bold(`
177
- \u{1F4CB} Registered QE Hook Events
178
- `)),console.log(E.bold("All Available Events:"));for(let[o,r]of Object.entries(R)){let c=s.includes(r)?E.green("\u2713"):E.dim("\u25CB");console.log(` ${c} ${o}: ${E.dim(r)}`)}console.log(E.dim(`
179
- Registered: ${s.length}/${Object.keys(R).length}`))}}catch(t){throw _(`list failed: ${t instanceof Error?t.message:"unknown"}`),t}}),n.command("emit").description("Emit a QE hook event").requiredOption("-e, --event <name>","Event name (e.g., qe:pattern-applied)").option("-d, --data <json>","Event data as JSON","{}").option("--json","Output as JSON").action(async e=>{try{let{hookRegistry:t}=await S(),s;try{s=ne(e.data)}catch{throw new Error(`Invalid JSON data: ${e.data}`)}let o=await t.emit(e.event,s);e.json?k({event:e.event,results:o}):(console.log(E.bold(`
180
- \u{1F4E1} Hook Event Emitted`)),console.log(E.dim(` Event: ${e.event}`)),console.log(E.dim(` Handlers: ${o.length}`)),o.forEach((r,a)=>{let c=r.success?E.green("\u2713"):E.red("\u2717");console.log(` ${c} Handler ${a+1}: ${r.success?"success":r.error}`),r.patternsLearned&&console.log(E.green(` Patterns learned: ${r.patternsLearned}`))}))}catch(t){throw _(`emit failed: ${t instanceof Error?t.message:"unknown"}`),t}}),n.command("learn").description("Store a new pattern in the reasoning bank").requiredOption("-n, --name <name>","Pattern name").requiredOption("-d, --description <desc>","Pattern description").option("-t, --type <type>","Pattern type","test-template").option("--domain <domain>","QE domain").option("--tags <tags...>","Pattern tags").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await S(),s=await t.storePattern({patternType:e.type,name:e.name,description:e.description,template:{type:"prompt",content:e.description,variables:[]},context:{tags:e.tags||[]}});if(!s.success)throw new Error(s.error.message);let o=s.value;e.json?k({success:!0,pattern:{id:o.id,name:o.name,type:o.patternType,domain:o.qeDomain}}):(v(`Pattern stored: ${o.name}`),console.log(E.dim(` ID: ${o.id}`)),console.log(E.dim(` Domain: ${o.qeDomain}`)),console.log(E.dim(` Tier: ${o.tier}`)))}catch(t){throw _(`learn failed: ${t instanceof Error?t.message:"unknown"}`),t}}),n.command("search").description("Search for patterns in the reasoning bank").requiredOption("-q, --query <query>","Search query").option("-l, --limit <n>","Maximum results","10").option("-d, --domain <domain>","Filter by domain").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await S(),s=await t.searchPatterns(e.query,{limit:parseInt(e.limit,10),domain:e.domain});if(!s.success)throw new Error(s.error.message);let o=s.value;e.json?k({query:e.query,total:o.length,patterns:o.map(r=>({id:r.pattern.id,name:r.pattern.name,score:r.score,domain:r.pattern.qeDomain,matchType:r.matchType}))}):(console.log(E.bold(`
181
- \u{1F50D} Search Results for "${e.query}"
182
- `)),o.length===0?console.log(E.dim(" No patterns found")):o.forEach((r,a)=>{console.log(`${E.cyan(`${a+1}.`)} ${r.pattern.name} ${E.dim(`(${(r.score*100).toFixed(1)}%)`)}`),console.log(E.dim(` Domain: ${r.pattern.qeDomain}`)),console.log(E.dim(` Match: ${r.matchType}`)),console.log(E.dim(` ID: ${r.pattern.id}`)),console.log()}),console.log(E.dim(`Found ${o.length} pattern(s)`)))}catch(t){throw _(`search failed: ${t instanceof Error?t.message:"unknown"}`),t}})}H();import F from"chalk";import $e from"node:path";function ke(n){n.command("session-start").description("Initialize session state when Claude Code session starts").option("-s, --session-id <id>","Session ID").option("--json","Output as JSON").action(async e=>{try{let t=e.sessionId||`session-${Date.now()}`;g.sessionId=t;let{reasoningBank:s}=await S(),o=await s.getStats(),r=T(),a=$e.join(r,".agentic-qe"),c=await D(a),i=await c.get(N),h=!i||!i.sessionStartTime;i?(i.sessionStartTime=new Date().toISOString(),i.totalDreamsThisSession=0):i={lastDreamTime:null,experienceCount:0,sessionStartTime:new Date().toISOString(),totalDreamsThisSession:0},await c.set(N,i);let d=[];d.push(`AQE Learning: ${o.totalPatterns} patterns loaded`);let p=Object.entries(o.byDomain).filter(([,l])=>l>0).sort(([,l],[,f])=>f-l).slice(0,5);p.length>0&&d.push(`Top domains: ${p.map(([l,f])=>`${l}(${f})`).join(", ")}`),o.patternSuccessRate>0&&d.push(`Pattern success rate: ${(o.patternSuccessRate*100).toFixed(0)}%`),o.routingRequests>0&&d.push(`Routing confidence: ${(o.avgRoutingConfidence*100).toFixed(0)}% across ${o.routingRequests} requests`);let u=d.join(". ")+".";e.json?k({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:u},sessionId:t,initialized:!0,patternsLoaded:o.totalPatterns,dreamScheduler:{enabled:!0,lastDreamTime:i.lastDreamTime,pendingExperiences:i.experienceCount}}):(v(`Session started: ${t}`),console.log(F.dim(` Patterns loaded: ${o.totalPatterns}`)),console.log(F.dim(` Dream scheduler: enabled (${i.experienceCount} pending experiences)`)));return}catch(t){e.json&&k({success:!1,error:t instanceof Error?t.message:"unknown"});return}}),n.command("session-end").description("Save session state when Claude Code session ends").option("--save-state","Save learning state to disk").option("--export-metrics","Export session metrics").option("--json","Output as JSON").action(async e=>{try{let t=g.sessionId||"unknown",s=null;if(g.initialized&&g.reasoningBank)try{s=await g.reasoningBank.getStats()}catch{}let o=0;try{o=await te()}catch{}if(e.json){let r=s?`Session complete: ${s.totalPatterns} patterns, ${s.routingRequests} routings, ${(s.patternSuccessRate*100).toFixed(0)}% success rate`:"Session complete";k({continue:!0,sessionId:t,stateSaved:e.saveState||!1,metricsExported:e.exportMetrics||!1,patternsConsolidated:o,finalStats:s?{patternsLearned:s.totalPatterns,routingRequests:s.routingRequests,successRate:s.patternSuccessRate}:null})}else v(`Session ended: ${t}`),s&&(console.log(F.dim(` Patterns: ${s.totalPatterns}`)),console.log(F.dim(` Routing requests: ${s.routingRequests}`))),o>0&&console.log(F.dim(` Patterns consolidated: ${o}`));return}catch(t){e.json&&k({success:!1,error:t instanceof Error?t.message:"unknown"});return}})}import{createHash as xe,randomUUID as Oe}from"node:crypto";import b from"chalk";import Ie from"node:path";H();var Ne="task-bridge",Pe=6e5,ye=.5;function Ce(n){let e=n.toLowerCase();return/\bgenerate[- ]?test|\btest[- ]?gen|\bgenerate.+spec/.test(e)?"test-generation":/\bcoverage|\banalyze.+cover/.test(e)?"coverage-analysis":/\bquality|\bassess|\baudit/.test(e)?"quality-assessment":/\bsecurity|\bvulnerab|\bcompliance/.test(e)?"security-compliance":/\bdefect|\bbug|\bdiagnos/.test(e)?"defect-intelligence":/\brequirement|\bspec\b/.test(e)?"requirements-validation":/\brefactor|\brewrite|\boptim/.test(e)?"refactoring":/\btest|\brun.+test/.test(e)?"test-execution":"unknown"}function qe(n){return xe("sha256").update(n).digest("hex").slice(0,16)}function he(n){n.command("pre-task").description("Get context and guidance before spawning a Task agent").option("--task-id <id>","Task identifier").option("-d, --description <desc>","Task description").option("--json","Output as JSON").action(async e=>{try{let{reasoningBank:t}=await S(),s=null;if(e.description){let d=await t.routeTask({task:e.description});d.success&&(s=d.value)}let o=(s?.patterns??[]).slice(0,5).map(d=>d?.id).filter(d=>typeof d=="string"),r=null,a=[],c=0,i=null;try{let d=j();d.isInitialized()||await d.initialize();let p=d.getDatabase();L(p);try{let u=p.prepare(`
183
- SELECT used_agent AS agent,
184
- ROUND(AVG(quality_score), 3) AS avgQuality,
185
- COUNT(*) AS n
186
- FROM routing_outcomes
187
- WHERE success = 1 AND quality_score >= 0
188
- GROUP BY used_agent
189
- ORDER BY avgQuality DESC, n DESC
190
- LIMIT 1
191
- `).get();u&&(r=u)}catch{}try{a=p.prepare(`
192
- SELECT key, value
193
- FROM kv_store
194
- WHERE namespace = 'verdicts'
195
- AND created_at > datetime('now', '-7 days')
196
- ORDER BY created_at DESC
197
- LIMIT 3
198
- `).all().map(l=>({key:l.key,summary:String(l.value).slice(0,200)}))}catch{}if(o.length>0)try{let u=o.map(()=>"?").join(","),l=p.prepare(`
199
- SELECT COALESCE(SUM(average_token_savings), 0) AS sum
200
- FROM qe_patterns
201
- WHERE id IN (${u})
202
- `).get(...o);c=Math.max(0,Math.round(l?.sum??0))}catch{}if(e.description&&o.length>0)try{let u=String(e.description),l=Ce(u),f="normal",m=s?.domains?.[0]??"any",y=Math.max(0,Math.min(10,Math.round(Math.min(u.length/200,1)*10)));i=`task:${qe(u)}`;let $=JSON.stringify({selectedPatternIds:o,agent:s?.recommendedAgent??null,description:u.slice(0,200),taskType:l,priority:f,domain:m,complexityBucket:y,estimatedTokenSavings:c,ts:Date.now()}),I=Date.now()+Pe;p.prepare(`
203
- INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at, created_at)
204
- VALUES (?, ?, ?, ?, strftime('%s','now')*1000)
205
- `).run(i,Ne,$,I)}catch(u){console.error(b.dim(`[hooks] pre-task bridge: ${u instanceof Error?u.message:"unknown"}`))}if(s?.recommendedAgent)try{let u=e.taskId||`hook-${Date.now()}`,l=`route-${Date.now()}-${Oe().slice(0,8)}`,f=s.confidence<ye;p.prepare(`
206
- INSERT INTO routing_outcomes (
207
- id, task_json, decision_json, used_agent,
208
- followed_recommendation, success, quality_score,
209
- duration_ms, error
210
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
211
- `).run(l,JSON.stringify({description:e.description,taskId:u}),JSON.stringify({recommended:s.recommendedAgent,confidence:s.confidence,alternatives:s.alternatives,lowConfidence:f}),s.recommendedAgent,1,0,-1,0,f?"low-confidence":null)}catch(u){console.error(b.dim(`[hooks] pre-task sentinel: ${u instanceof Error?u.message:"unknown"}`))}}catch(d){console.error(b.dim(`[hooks] pre-task memory: ${d instanceof Error?d.message:"unknown"}`))}let h=s?s.confidence<ye:!1;e.json?k({success:!0,taskId:e.taskId,description:e.description,recommendedAgent:s?.recommendedAgent,confidence:s?.confidence,guidance:s?.guidance||[],selectedPatternIds:o,historicalBest:r,priorVerdicts:a,estimatedTokenSavings:c,lowConfidence:h,bridgeKey:i}):(console.log(b.bold(`
212
- \u{1F680} Pre-Task Analysis`)),console.log(b.dim(` Task ID: ${e.taskId||"N/A"}`)),s&&(console.log(b.bold(`
213
- \u{1F3AF} Recommended:`),b.cyan(s.recommendedAgent)),console.log(b.dim(` Confidence: ${(s.confidence*100).toFixed(1)}%`)),h&&console.log(b.yellow(" \u26A0 Low confidence \u2014 consider providing more context"))));return}catch(t){e.json&&k({success:!1,error:t instanceof Error?t.message:"unknown"});return}}),n.command("post-task").description("Record task outcome for pattern learning").option("--task-id <id>","Task identifier").option("--success <bool>","Whether task succeeded","true").option("--agent <name>","Agent that executed the task").option("--duration <ms>","Task duration in milliseconds").option("--json","Output as JSON").action(async e=>{try{let t=e.success==="true"||e.success===!0,s=0,o={triggered:!1};try{let{hookRegistry:r,reasoningBank:a}=await S();s=(await r.emit(R.QEAgentCompletion,{taskId:e.taskId,success:t,agent:e.agent,duration:e.duration?parseInt(e.duration,10):void 0,timestamp:Date.now()})).reduce((u,l)=>u+(l.patternsLearned||0),0);{let u=e.taskId||`hook-${Date.now()}`,l=e.agent||"unknown",f=e.duration?parseInt(e.duration,10):0;await a.recordOutcome({patternId:`task:${l}:${u}`,success:t,metrics:{executionTimeMs:f},feedback:`Agent: ${l}, Task: ${u}`});let m=await Z({taskId:u,agent:l,durationMs:f,success:t}),y=l==="unknown"&&m.bridge?.agent?m.bridge.agent:l;await ee({agent:y,success:t,durationMs:f,qualityScore:m.qualityScore}),m.bridge&&await X({taskType:m.bridge.taskType,priority:m.bridge.priority,domain:m.bridge.domain,complexityBucket:m.bridge.complexityBucket,agent:y,success:t})}let i=T(),h=Ie.join(i,".agentic-qe"),d=await D(h),p=await O(d);o=await Y(d)}catch(r){console.error(b.dim(`[hooks] Learning init: ${r instanceof Error?r.message:"unknown"}`))}if(e.json)k({success:!0,taskId:e.taskId,taskSuccess:t,patternsLearned:s,dreamTriggered:o.triggered,dreamReason:o.reason,dreamInsights:o.insightsGenerated,dreamInsightsApplied:o.insightsApplied});else if(v(`Task completed: ${e.taskId||"unknown"}`),console.log(b.dim(` Success: ${t}`)),s>0&&console.log(b.green(` Patterns learned: ${s}`)),o.triggered){let r=typeof o.insightsApplied=="number"?`, ${o.insightsApplied} applied`:"";console.log(b.blue(` \u{1F319} Dream cycle triggered (${o.reason}): ${o.insightsGenerated} insights${r}`))}return}catch(t){e.json&&k({success:!1,error:t instanceof Error?t.message:"unknown"});return}})}import{existsSync as Le,readFileSync as Me}from"node:fs";import{randomUUID as Ee}from"node:crypto";import z from"chalk";import Se from"node:path";H();function je(n){return/\bjest\b/i.test(n)?"jest":/\bvitest\b/i.test(n)?"vitest":/\bpytest\b/i.test(n)?"pytest":/\bmocha\b/i.test(n)?"mocha":null}async function He(n){try{let e=j();e.isInitialized()||await e.initialize();let t=e.getDatabase();L(t);let s=n.framework==="pytest"?"python":"javascript",o=n.command.split(/\s+/).slice(0,3).join("-").slice(0,80);t.prepare(`
214
- INSERT INTO test_outcomes (
215
- id, test_id, test_name, generated_by, framework, language, domain,
216
- passed, execution_time_ms, maintainability_score, created_at
217
- ) VALUES (?, ?, ?, 'cli-hook-post-command', ?, ?, 'test-execution',
218
- ?, ?, 0.5, datetime('now'))
219
- `).run(`to-${Date.now()}-${Ee().slice(0,8)}`,`cmd:${o}`,n.command.slice(0,200),n.framework,s,n.success?1:0,n.durationMs);try{let r=Se.join(process.cwd(),"coverage","coverage-summary.json");if(Le(r)){let c=JSON.parse(Me(r,"utf-8")).total??{},i=Number(c.lines?.pct??0),h=Number(c.branches?.pct??0),d=Number(c.functions?.pct??0),p=t.prepare(`
220
- SELECT after_lines, after_branches, after_functions
221
- FROM coverage_sessions
222
- WHERE target_path = ?
223
- ORDER BY created_at DESC
224
- LIMIT 1
225
- `).get(process.cwd()),u=new Date().toISOString();t.prepare(`
226
- INSERT INTO coverage_sessions (
227
- id, target_path, agent_id, technique,
228
- before_lines, before_branches, before_functions,
229
- after_lines, after_branches, after_functions,
230
- tests_generated, tests_passed, duration_ms,
231
- started_at, completed_at
232
- ) VALUES (?, ?, 'cli-hook-post-command', ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)
233
- `).run(`cs-${Date.now()}-${Ee().slice(0,8)}`,process.cwd(),n.framework,p?.after_lines??0,p?.after_branches??0,p?.after_functions??0,i,h,d,n.success?1:0,n.durationMs,u,u)}}catch(r){console.error(z.dim(`[hooks] coverage_sessions: ${r instanceof Error?r.message:"unknown"}`))}}catch(e){console.error(z.dim(`[hooks] test_outcomes: ${e instanceof Error?e.message:"unknown"}`))}}function _e(n){n.command("guard").description("File guardian - block edits to protected files").requiredOption("-f, --file <path>","File path to check").option("--json","Output as JSON (required for hook API)").action(async e=>{try{let t=e.file||"",s=t.replace(/\\/g,"/"),r=[{pattern:/^\.env($|\.)/,reason:"Environment file contains secrets"},{pattern:/\.env\.[a-zA-Z]+$/,reason:"Environment file contains secrets"},{pattern:/\.lock$/,reason:"Lock files are auto-generated"},{pattern:/(^|\/)node_modules\//,reason:"node_modules is managed by package manager"},{pattern:/(^|\/)\.agentic-qe\/memory\.db/,reason:"AQE memory database must not be directly edited"},{pattern:/(^|\/)\.agentic-qe\/memory\.db-wal$/,reason:"AQE WAL file must not be directly edited"},{pattern:/(^|\/)\.agentic-qe\/memory\.db-shm$/,reason:"AQE shared memory file must not be directly edited"}].find(a=>a.pattern.test(s));r?e.json?k({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Protected file: ${r.reason} (${t})`}}):_(`Blocked: ${r.reason} (${t})`):e.json?k({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}}):v(`Allowed: ${t}`);return}catch{e.json&&k({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}});return}}),n.command("pre-command").description("Get context before executing a Bash command").option("-c, --command <cmd>","Command to be executed").option("--json","Output as JSON").action(async e=>{try{let t=e.command||"",s=[{pattern:/rm\s+(-[a-zA-Z]*f[a-zA-Z]*\s+)?-[a-zA-Z]*r[a-zA-Z]*\s+\/(?!\w)/,reason:"Recursive delete of root filesystem"},{pattern:/rm\s+(-[a-zA-Z]*r[a-zA-Z]*\s+)?-[a-zA-Z]*f[a-zA-Z]*\s+\/(?!\w)/,reason:"Recursive delete of root filesystem"},{pattern:/rm\s+-rf\s+~/,reason:"Recursive delete of home directory"},{pattern:/DROP\s+(TABLE|DATABASE|SCHEMA)/i,reason:"Destructive SQL operation"},{pattern:/git\s+push\s+.*--force(?!-)/,reason:"Force push can overwrite remote history"},{pattern:/git\s+reset\s+--hard/,reason:"Hard reset discards uncommitted changes"},{pattern:/>\s*\/dev\/sd[a-z]/,reason:"Direct write to block device"},{pattern:/dd\s+if=.*of=\/dev\/sd/,reason:"Direct disk write via dd"},{pattern:/chmod\s+777\s/,reason:"World-writable permissions are a security risk"},{pattern:/:\(\)\s*\{\s*:\|\s*:&\s*\}\s*;?\s*:/,reason:"Fork bomb detected"},{pattern:/mkfs\./,reason:"Filesystem format operation"},{pattern:/>\s*\/dev\/null\s*2>&1\s*&\s*disown/,reason:"Stealth background process"}],o=[{pattern:/\.agentic-qe.*rm/,reason:"Deleting AQE data files"},{pattern:/rm\s+-rf\s/,reason:"Recursive force delete"},{pattern:/git\s+clean\s+-[a-zA-Z]*f/,reason:"Force cleaning untracked files"}],r=s.find(c=>c.pattern.test(t)),a=o.filter(c=>c.pattern.test(t)).map(c=>c.reason);if(r)e.json?k({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Dangerous command blocked: ${r.reason}`}}):_(`Blocked: ${r.reason}`);else if(e.json){let c={hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}};a.length>0&&(c.hookSpecificOutput.additionalContext=`Warnings: ${a.join("; ")}`),k(c)}else a.length>0&&(console.log(z.yellow(`
234
- \u26A0\uFE0F Command Warnings:`)),a.forEach(c=>console.log(z.yellow(` - ${c}`))));return}catch{e.json&&k({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow"}});return}}),n.command("post-command").description("Record Bash command outcome").option("-c, --command <cmd>","Command that was executed").option("--success <bool>","Whether command succeeded","true").option("--exit-code <code>","Command exit code").option("--json","Output as JSON").action(async e=>{try{let t=e.success==="true"||e.success===!0,s=e.exitCode?parseInt(e.exitCode,10):t?0:1,o=(e.command||"").substring(0,200),r=/\b(test|vitest|jest|pytest|mocha)\b/i.test(o),a=/\b(build|compile|tsc)\b/i.test(o),c=/\b(lint|eslint|prettier)\b/i.test(o),i=0,h=!1;try{let{reasoningBank:d}=await S();if(r){let{hookRegistry:$}=await S();await $.emit(R.TestExecutionResult,{runId:`cmd-${Date.now()}`,patternId:`cmd:test:${o.split(/\s+/).slice(0,3).join("-")}`,passed:t?1:0,failed:t?0:1,duration:0,flaky:!1})}let p=o.replace(/[^a-zA-Z0-9]/g,"-").slice(0,80),u=r?"test-execution":a?"code-intelligence":c?"quality-assessment":"code-intelligence";await d.recordOutcome({patternId:`cmd:${p}`,success:t,metrics:{executionTimeMs:0},feedback:`Command: ${o}, exit: ${s}`}),i=1,(r||a||c)&&(await U({task:`bash: ${o}`,agent:"cli-hook",domain:u,success:t,source:"cli-hook-post-command"}),h=!0);let l=je(o);l&&await He({command:o,framework:l,success:t,durationMs:0});let f=T(),m=Se.join(f,".agentic-qe"),y=await D(m);await O(y)}catch(d){console.error(z.dim(`[hooks] post-command learning: ${d instanceof Error?d.message:"unknown"}`))}e.json&&k({success:!0,command:o.substring(0,100),commandSuccess:t,exitCode:s,patternsLearned:i,experienceRecorded:h});return}catch(t){e.json&&k({success:!1,error:t instanceof Error?t.message:"unknown"});return}})}function Gt(){let n=new Be("hooks").description("Self-learning QE hooks for pattern recognition and guidance").addHelpText("after",`
235
- Examples:
236
- # File editing hooks (learning from edits)
237
- aqe hooks pre-edit --file src/utils.ts --operation create
238
- aqe hooks post-edit --file src/utils.ts --success
239
-
240
- # Task routing and guidance
241
- aqe hooks route --task "Generate tests for UserService"
242
- aqe hooks pre-task --description "Generate tests" --json
243
- aqe hooks post-task --task-id "task-123" --success true
244
- aqe hooks post-route --success true --json # Stop hook (#451)
245
-
246
- # Bash command hooks
247
- aqe hooks pre-command --command "npm test" --json
248
- aqe hooks post-command --command "npm test" --success true
249
-
250
- # Session lifecycle (Stop hook)
251
- aqe hooks session-start --session-id "session-123"
252
- aqe hooks session-end --save-state --json
253
-
254
- # Pattern management
255
- aqe hooks learn --name "test-pattern" --description "A test pattern"
256
- aqe hooks search --query "authentication"
257
- aqe hooks stats
258
- aqe hooks list
259
- `);return ge(n),pe(n),fe(n),ke(n),he(n),_e(n),n}export{R as QE_HOOK_EVENTS,Gt as createHooksCommand,S as getHooksSystem,g as hooksState};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{a}from"./chunk-QBDXUI2H.js";import"./chunk-2O5TT3UT.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import"./chunk-Q4HJRYQB.js";import"./chunk-LDGNVPBZ.js";import"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import"./chunk-ITBPDVK5.js";export{a as ImpactAnalyzerService};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{a,b,c,d}from"./chunk-UWWX4RK7.js";import"./chunk-E7UHOKKL.js";import"./chunk-OOFWYDG6.js";import"./chunk-Z3TXQOS7.js";import"./chunk-HJDHQBMJ.js";import"./chunk-Q4HJRYQB.js";import"./chunk-RNO6CE7I.js";import"./chunk-CNNVL5W4.js";import"./chunk-TULNR2AH.js";import"./chunk-ITBPDVK5.js";export{a as InitOrchestrator,b as createInitOrchestrator,d as formatInitResult,c as quickInit};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{y as a,z as b}from"./chunk-3PZDXE5E.js";import"./chunk-XKH4E2IQ.js";import"./chunk-WTXRPYNN.js";import"./chunk-C6TNYLD7.js";import"./chunk-DEDFPHJL.js";import"./chunk-TA3QYAZ6.js";import"./chunk-OTFJCZNY.js";import"./chunk-MV3NUANS.js";import"./chunk-YXR5RYRE.js";import"./chunk-3EP2YZSY.js";import"./chunk-H2IMXQCJ.js";import"./chunk-AWWD3EI3.js";import"./chunk-XDYTQPJM.js";import"./chunk-YETPSL6H.js";import"./chunk-SPCANEJY.js";import"./chunk-ND6VCNN5.js";import"./chunk-DDMFTEJP.js";import"./chunk-HA7N45KB.js";import"./chunk-WVODEWH5.js";import"./chunk-VRP4GB4Y.js";import"./chunk-R5IW5ARI.js";import"./chunk-2GBBZLXT.js";import"./chunk-QHKK2H4H.js";import"./chunk-IOINZWNA.js";import"./chunk-Y57V4FDT.js";import"./chunk-JNRRDG7O.js";import"./chunk-3AICELMQ.js";import"./chunk-XK6YXCS7.js";import"./chunk-JCWHX4XV.js";import"./chunk-FI4HRS2G.js";import"./chunk-FG5GL26L.js";import"./chunk-IEGAEXQX.js";import"./chunk-QTS2DS42.js";import"./chunk-QBDXUI2H.js";import"./chunk-2O5TT3UT.js";import"./chunk-R57J3O6I.js";import"./chunk-UROPIIB2.js";import"./chunk-5DJAJPBG.js";import"./chunk-4UZQSPR4.js";import"./chunk-IHRFR5SV.js";import"./chunk-TYZGEVP6.js";import"./chunk-DJRWVNHK.js";import"./chunk-MZ7M2CDV.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import"./chunk-FGDEM4HU.js";import"./chunk-Q4HJRYQB.js";import"./chunk-LDGNVPBZ.js";import"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import"./chunk-AQJ6XS34.js";import"./chunk-CNNVL5W4.js";import"./chunk-TULNR2AH.js";import"./chunk-7D2DM23U.js";import"./chunk-37I6K7QO.js";import"./chunk-XVTZXCHI.js";import"./chunk-KR2PGNXX.js";import"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";export{a as QEKernelImpl,b as createKernel};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{g as a}from"./chunk-2O5TT3UT.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import"./chunk-Q4HJRYQB.js";import"./chunk-LDGNVPBZ.js";import"./chunk-RNO6CE7I.js";import"./chunk-ITBPDVK5.js";export{a as KnowledgeGraphService};
@@ -1,107 +0,0 @@
1
- #!/usr/bin/env node
2
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.30");process.exit(0)}
3
- import{a as ee}from"./chunk-MYF7F3ZP.js";import{b as Z}from"./chunk-ND6VCNN5.js";import{g as X}from"./chunk-WVODEWH5.js";import"./chunk-VRP4GB4Y.js";import"./chunk-R5IW5ARI.js";import"./chunk-2GBBZLXT.js";import{i as q}from"./chunk-QHKK2H4H.js";import"./chunk-IOINZWNA.js";import"./chunk-3AICELMQ.js";import{a as Y}from"./chunk-XK6YXCS7.js";import"./chunk-QTS2DS42.js";import"./chunk-5DJAJPBG.js";import"./chunk-4UZQSPR4.js";import{f as T,o as K}from"./chunk-TYZGEVP6.js";import"./chunk-DJRWVNHK.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import{b as z,d as de}from"./chunk-Q4HJRYQB.js";import"./chunk-LDGNVPBZ.js";import"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import{a as C,b as J}from"./chunk-CNNVL5W4.js";import"./chunk-TULNR2AH.js";import"./chunk-7D2DM23U.js";import"./chunk-37I6K7QO.js";import"./chunk-XVTZXCHI.js";import"./chunk-KR2PGNXX.js";import"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";K();de();import{Command as fe}from"commander";import o from"chalk";import S from"node:path";import{existsSync as w,writeFileSync as ce,readFileSync as W,mkdirSync as le,copyFileSync as B,renameSync as ie}from"node:fs";import{stat as M,unlink as E}from"node:fs/promises";J();K();import x from"chalk";import U from"node:path";import{createReadStream as te,createWriteStream as ne}from"node:fs";import{createGzip as pe,createGunzip as ge}from"node:zlib";import{pipeline as oe}from"node:stream/promises";J();var A={reasoningBank:null,initialized:!1};async function O(){if(A.initialized&&A.reasoningBank)return A.reasoningBank;let s=T(),t=U.join(s,".agentic-qe"),e=new Y({sqlite:{path:U.join(t,"memory.db"),walMode:!0,poolSize:3,busyTimeout:5e3},enableFallback:!0,defaultNamespace:"qe-patterns"});await e.initialize(),A.reasoningBank=X(e,void 0,{enableLearning:!0,enableGuidance:!0,enableRouting:!0,embeddingDimension:384,useONNXEmbeddings:!0}),await A.reasoningBank.initialize();try{let{getSharedRvfDualWriter:n}=await import("./shared-rvf-dual-writer-BKSR2FFK.js"),l=await n();l&&A.reasoningBank.setRvfDualWriter(l)}catch(n){process.env.DEBUG&&console.debug("[learning] RVF wiring skipped:",n instanceof Error?n.message:n)}return A.initialized=!0,A.reasoningBank}function v(s){console.log(JSON.stringify(s,null,2))}function P(s){console.log(x.green("\u2713"),s)}function R(s){console.error(x.red("\u2717"),s)}function I(s){console.log(x.blue("\u2139"),s)}function ae(s){let{current:t,topDomains:e}=s,n={tl:"\u250C",tr:"\u2510",bl:"\u2514",br:"\u2518",h:"\u2500",v:"\u2502",ml:"\u251C",mr:"\u2524"},l=55,i=n.h.repeat(l-2);console.log(""),console.log(`${n.tl}${i}${n.tr}`),console.log(`${n.v}${me("AQE LEARNING DASHBOARD",l-2)}${n.v}`),console.log(`${n.ml}${i}${n.mr}`);let m=t.patternsCreatedToday>0?x.green(` (+${t.patternsCreatedToday} today)`):"";console.log(`${n.v} Patterns: ${D(String(t.totalPatterns)+m,32)}${n.v}`);let p=t.experiencesToday>0?x.green(` (+${t.experiencesToday} today)`):"";console.log(`${n.v} Experiences: ${D(String(t.totalExperiences)+p,32)}${n.v}`),console.log(`${n.v} Q-Values: ${D(String(t.totalQValues),32)}${n.v}`);let d=t.avgReward.toFixed(2),g=t.avgRewardDelta>=0?x.green(`(\u2191 ${Math.abs(t.avgRewardDelta).toFixed(2)} from last week)`):x.red(`(\u2193 ${Math.abs(t.avgRewardDelta).toFixed(2)} from last week)`);console.log(`${n.v} Avg Reward: ${D(`${d} ${g}`,32)}${n.v}`);let r=(t.successRate*100).toFixed(1);if(console.log(`${n.v} Success Rate: ${D(`${r}%`,32)}${n.v}`),console.log(`${n.v} Short-term: ${D(String(t.shortTermPatterns),32)}${n.v}`),console.log(`${n.v} Long-term: ${D(String(t.longTermPatterns),32)}${n.v}`),console.log(`${n.v}${" ".repeat(l-2)}${n.v}`),console.log(`${n.v} ${x.bold("Domain Coverage:")}${" ".repeat(l-19)}${n.v}`),e.length===0)console.log(`${n.v} ${x.dim("No patterns yet")}${" ".repeat(l-19)}${n.v}`);else{let c=Math.max(...e.map(f=>f.count),1),u=14;for(let{domain:f,count:h}of e){let $=Math.round(h/c*u),b=u-$,k=x.green("\u2588".repeat($))+x.dim("\u2591".repeat(b)),F=D(f,20),L=ue(String(h),3);console.log(`${n.v} ${F} ${k} ${L} patterns ${n.v}`)}let a=new Set(e.map(f=>f.domain)),y=q.filter(f=>!a.has(f)).slice(0,3);for(let f of y){let h=x.dim("\u2591".repeat(u)),$=D(f,20);console.log(`${n.v} ${$} ${h} 0 patterns ${n.v}`)}}console.log(`${n.bl}${i}${n.br}`),console.log("")}function me(s,t){let e=G(s),n=Math.max(0,t-e.length),l=Math.floor(n/2),i=n-l;return" ".repeat(l)+s+" ".repeat(i)}function D(s,t){let e=G(s),n=Math.max(0,t-e.length);return s+" ".repeat(n)}function ue(s,t){let e=G(s),n=Math.max(0,t-e.length);return" ".repeat(n)+s}function G(s){return s.replace(/\x1b\[[0-9;]*m/g,"")}function j(){let s=T();return U.join(s,".agentic-qe","memory.db")}async function Q(s,t){let e=t||`${s}.gz`;return await oe(te(s),pe(),ne(e)),e}async function V(s,t){await oe(te(s),ge(),ne(t))}async function _(s){try{let t=C(s,{readonly:!0}),e=t.prepare("PRAGMA integrity_check").get();return t.close(),e.integrity_check==="ok"?{valid:!0,message:"Database integrity verified"}:{valid:!1,message:`Integrity check failed: ${e.integrity_check}`}}catch(t){return{valid:!1,message:`Failed to verify: ${t instanceof Error?t.message:"unknown error"}`}}}async function N(s){try{let t=C(s,{readonly:!0});if(!t.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='schema_version'").get())return t.close(),0;let n=t.prepare("SELECT version FROM schema_version WHERE id = 1").get();return t.close(),n?.version??0}catch{return 0}}var H="3.1.0",re={generate:"test-generation","test-generation":"test-generation",analyze:"coverage-analysis",coverage:"coverage-analysis","coverage-analysis":"coverage-analysis",run:"test-execution","test-execution":"test-execution",report:"quality-assessment",quality:"quality-assessment","quality-analysis":"quality-assessment",security:"security-compliance",sast:"security-compliance",owasp:"security-compliance",secrets:"security-compliance",audit:"security-compliance",recommend:"defect-intelligence",predict:"defect-intelligence","complexity-analysis":"code-intelligence","code-analysis":"code-intelligence",stabilize:"chaos-resilience",flaky:"chaos-resilience",quarantine:"chaos-resilience",retry:"chaos-resilience",stress:"chaos-resilience",load:"chaos-resilience",endurance:"chaos-resilience",baseline:"chaos-resilience"},se={generate:"test-template","test-generation":"test-template",analyze:"coverage-strategy",coverage:"coverage-strategy","coverage-analysis":"coverage-strategy",run:"test-template","test-execution":"test-template",report:"assertion-pattern",quality:"assertion-pattern","quality-analysis":"assertion-pattern",security:"assertion-pattern",sast:"assertion-pattern",owasp:"assertion-pattern",secrets:"assertion-pattern",audit:"assertion-pattern",recommend:"assertion-pattern",predict:"assertion-pattern","complexity-analysis":"assertion-pattern","code-analysis":"assertion-pattern",stabilize:"flaky-fix",flaky:"flaky-fix",quarantine:"flaky-fix",retry:"flaky-fix",stress:"perf-benchmark",load:"perf-benchmark",endurance:"perf-benchmark",baseline:"perf-benchmark",mock:"mock-pattern",dependency:"mock-pattern"};function at(){let s=new fe("learning").description("AQE self-learning system management (standalone, no claude-flow required)").addHelpText("after",`
4
- Examples:
5
- # Check learning system status
6
- aqe learning stats
7
-
8
- # Consolidate patterns (promote successful patterns to long-term memory)
9
- aqe learning consolidate
10
-
11
- # Export learned patterns for sharing
12
- aqe learning export --output patterns.json
13
-
14
- # Import patterns from another project
15
- aqe learning import --input patterns.json
16
-
17
- # Run background learning consolidation
18
- aqe learning daemon --interval 3600
19
- `);return ye(s),he(s),we(s),$e(s),be(s),Se(s),ve(s),Re(s),Ee(s),ke(s),xe(s),De(s),Ce(s),Oe(s),Pe(s),Ae(s),s}function ye(s){s.command("stats").description("Display learning system statistics").option("--json","Output as JSON").option("--detailed","Show detailed breakdown").action(async t=>{try{let n=await(await O()).getStats();if(t.json)v(n);else{console.log(o.bold(`
20
- \u{1F4CA} AQE Learning System Statistics
21
- `)),console.log(o.bold("Patterns:")),console.log(` Total: ${o.cyan(n.totalPatterns)}`),console.log(` Short-term: ${n.patternStoreStats.byTier.shortTerm}`),console.log(` Long-term: ${n.patternStoreStats.byTier.longTerm}`),console.log(` Avg Confidence: ${(n.patternStoreStats.avgConfidence*100).toFixed(1)}%`),console.log(` Avg Quality: ${(n.patternStoreStats.avgQualityScore*100).toFixed(1)}%`),console.log(o.bold(`
22
- By Domain:`));let l=Object.entries(n.byDomain).filter(([m,p])=>p>0).sort((m,p)=>p[1]-m[1]);if(l.length===0)console.log(o.dim(" No patterns yet"));else for(let[m,p]of l)console.log(` ${m}: ${p}`);console.log(o.bold(`
23
- Learning:`)),console.log(` Routing Requests: ${n.routingRequests}`),console.log(` Avg Routing Confidence: ${(n.avgRoutingConfidence*100).toFixed(1)}%`),console.log(` Learning Outcomes: ${n.learningOutcomes}`),console.log(` Pattern Success Rate: ${(n.patternSuccessRate*100).toFixed(1)}%`),console.log(o.bold(`
24
- Search Performance:`)),console.log(` Operations: ${n.patternStoreStats.searchOperations}`),console.log(` Avg Latency: ${n.patternStoreStats.avgSearchLatencyMs.toFixed(2)}ms`),console.log(` HNSW Native: ${n.patternStoreStats.hnswStats.nativeAvailable?o.green("\u2713"):o.dim("\u25CB")}`),console.log(` Vector Count: ${n.patternStoreStats.hnswStats.vectorCount}`);let i=n.asymmetricLearning;if(i&&(console.log(o.bold(`
25
- Asymmetric Learning (ADR-061):`)),console.log(` Failure Penalty Ratio: ${i.failurePenaltyRatio||"10:1"}`),console.log(` Quarantined Patterns: ${i.quarantinedPatterns||0}`),console.log(` Rehabilitated: ${i.rehabilitatedPatterns||0}`),console.log(` Avg Confidence Delta: ${((i.avgConfidenceDelta||0)*100).toFixed(1)}%`)),t.detailed){console.log(o.bold(`
26
- By Pattern Type:`));for(let[m,p]of Object.entries(n.patternStoreStats.byType))p>0&&console.log(` ${m}: ${p}`)}console.log("")}return}catch(e){throw R(`stats failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function he(s){s.command("consolidate").description("Consolidate patterns - promote successful patterns to long-term memory").option("--dry-run","Show what would be promoted without making changes").option("--threshold <n>","Minimum successful uses for promotion","3").option("--success-rate <n>","Minimum success rate for promotion (0-1)","0.7").option("--json","Output as JSON").action(async t=>{try{let e=await O(),n=parseInt(t.threshold,10),l=parseFloat(t.successRate),i=[],m=await e.searchPatterns("*",{limit:1e3});if(m.success)for(let p of m.value){let d=p.pattern;d.tier==="short-term"&&d.successfulUses>=n&&d.successRate>=l&&i.push({id:d.id,name:d.name,domain:d.qeDomain,successfulUses:d.successfulUses,successRate:d.successRate,currentTier:d.tier})}if(t.json)v({dryRun:t.dryRun||!1,eligibleCount:i.length,threshold:n,successRateMin:l,patterns:i});else{if(console.log(o.bold(`
27
- \u{1F504} Pattern Consolidation
28
- `)),console.log(` Promotion threshold: ${n} successful uses`),console.log(` Minimum success rate: ${(l*100).toFixed(0)}%`),console.log(` Eligible patterns: ${i.length}
29
- `),i.length===0)console.log(o.dim(" No patterns eligible for promotion yet."));else{console.log(o.bold(" Patterns to promote:"));for(let p of i)console.log(` ${o.cyan(p.name)}`),console.log(o.dim(` Domain: ${p.domain}, Uses: ${p.successfulUses}, Rate: ${(p.successRate*100).toFixed(0)}%`));t.dryRun?console.log(o.yellow(`
30
- Dry run - no changes made`)):console.log(o.yellow(`
31
- Promotion would happen here (not yet implemented)`))}console.log("")}return}catch(e){throw R(`consolidate failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function we(s){s.command("export").description("Export learned patterns for sharing").option("-o, --output <file>","Output file path","aqe-patterns.json").option("-d, --domain <domain>","Filter by domain").option("--long-term-only","Only export long-term patterns").option("--json","Output as JSON (to stdout)").action(async t=>{try{let n=await(await O()).searchPatterns("*",{limit:1e4,domain:t.domain});if(!n.success)throw new Error(n.error.message);let l=n.value.map(m=>m.pattern).filter(m=>!t.longTermOnly||m.tier==="long-term"),i={version:"3.0.0",exportedAt:new Date().toISOString(),source:process.cwd(),patternCount:l.length,patterns:l.map(m=>({id:m.id,name:m.name,description:m.description,patternType:m.patternType,qeDomain:m.qeDomain,tier:m.tier,confidence:m.confidence,successRate:m.successRate,successfulUses:m.successfulUses,qualityScore:m.qualityScore,template:m.template,context:m.context}))};if(t.json)v(i);else{let m=S.resolve(t.output);ce(m,JSON.stringify(i,null,2),"utf-8"),P(`Exported ${l.length} patterns to ${m}`)}return}catch(e){throw R(`export failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function $e(s){s.command("import").description("Import patterns from file").requiredOption("-i, --input <file>","Input file path").option("--dry-run","Show what would be imported without making changes").option("--json","Output as JSON").action(async t=>{try{let e=S.resolve(t.input);if(!w(e))throw new Error(`File not found: ${e}`);let n=W(e,"utf-8"),l=z(n);if(!l.patterns||!Array.isArray(l.patterns))throw new Error("Invalid pattern file format");let i=await O(),m=0,p=0,d=[];if(!t.dryRun)for(let g of l.patterns)try{let r=await i.storePattern({patternType:g.patternType,name:g.name,description:g.description,template:g.template,context:g.context});r.success?m++:(p++,d.push(`${g.name}: ${r.error.message}`))}catch(r){p++,d.push(`${g.name}: ${r instanceof Error?r.message:"unknown"}`)}t.json?v({dryRun:t.dryRun||!1,totalPatterns:l.patterns.length,imported:m,skipped:p,errors:d}):(console.log(o.bold(`
32
- \u{1F4E5} Pattern Import
33
- `)),console.log(` Source: ${e}`),console.log(` Total patterns: ${l.patterns.length}`),t.dryRun?(console.log(o.yellow(`
34
- Dry run - no changes made`)),console.log(` Would import: ${l.patterns.length} patterns`)):(console.log(o.green(`
35
- Imported: ${m}`)),p>0&&console.log(o.yellow(` Skipped: ${p}`))),console.log(""));return}catch(e){throw R(`import failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function be(s){s.command("reset").description("Reset learning data (patterns and metrics)").option("--confirm","Confirm reset without prompting").option("--patterns-only","Only reset patterns, keep metrics").action(async t=>{try{if(!t.confirm){console.log(o.yellow(`
36
- \u26A0\uFE0F This will reset your learning data.`)),console.log(o.gray(` Use --confirm to proceed
37
- `));return}let e=T(),n=S.join(e,".agentic-qe"),l=[S.join(n,"data","patterns"),S.join(n,"data","hnsw")];t.patternsOnly||l.push(S.join(n,"data","learning-config.json")),console.log(o.bold(`
38
- \u{1F5D1}\uFE0F Resetting Learning Data
39
- `));for(let i of l)w(i)&&console.log(o.dim(` Removing: ${S.relative(e,i)}`));P(`Learning data reset. Run "aqe init --auto" to reinitialize.
40
- `);return}catch(e){throw R(`reset failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function Se(s){s.command("extract").description("Extract QE patterns from existing learning experiences").option("--min-reward <n>","Minimum reward threshold for pattern extraction","0.7").option("--min-count <n>","Minimum occurrences to form a pattern","3").option("--dry-run","Show what would be extracted without saving").option("--json","Output as JSON").action(async t=>{try{let e=T(),n=S.join(e,".agentic-qe","memory.db");if(!w(n))throw new Error('No memory database found. Run "aqe init --auto" first.');let l=parseFloat(t.minReward),i=parseInt(t.minCount,10);console.log(o.bold(`
41
- \u{1F52C} Pattern Extraction from Learning Experiences
42
- `)),console.log(` Min reward threshold: ${l}`),console.log(` Min occurrences: ${i}
43
- `);let m=C(n,{readonly:!0}),p=m.prepare(`
44
- SELECT domain as task_type, COUNT(*) as count, AVG(quality) as avg_reward, MAX(quality) as max_reward,
45
- MIN(quality) as min_reward, GROUP_CONCAT(DISTINCT agent) as actions
46
- FROM captured_experiences WHERE quality >= ? AND agent != 'cli-hook' GROUP BY domain HAVING COUNT(*) >= ? ORDER BY avg_reward DESC
47
- `).all(l,i),d=[];try{d=m.prepare(`
48
- SELECT substr(key, 1, 40) as key_prefix, COUNT(*) as count
49
- FROM memory_entries WHERE key LIKE 'phase2/learning/%'
50
- GROUP BY substr(key, 1, 40) HAVING COUNT(*) >= ? ORDER BY COUNT(*) DESC LIMIT 20
51
- `).all(i)}catch{}m.close();let g=[];for(let r of p){let c=re[r.task_type]||"code-intelligence",u=se[r.task_type]||"test-template",a=r.actions?r.actions.split(",").slice(0,5):[];g.push({name:`${r.task_type}-success-pattern`,domain:c,patternType:u,confidence:Math.min(.95,r.avg_reward/2),sourceCount:r.count,avgReward:r.avg_reward,actions:a})}if(t.json)v({minReward:l,minCount:i,dryRun:t.dryRun||!1,experienceGroups:p.length,memoryPatterns:d.length,extractedPatterns:g});else{if(console.log(o.bold("Learning Experience Groups:")),p.length===0)console.log(o.dim(" No qualifying experience groups found"));else for(let r of p){let c=r.avg_reward>=1?o.green:r.avg_reward>=.5?o.yellow:o.red;console.log(` ${o.cyan(r.task_type)}`),console.log(` Count: ${r.count}, Avg Reward: ${c(r.avg_reward.toFixed(2))}`)}console.log(o.bold(`
52
- Memory Pattern Sources:`));for(let r of d.slice(0,10))console.log(` ${r.key_prefix}... (${r.count})`);if(console.log(o.bold(`
53
- Extracted Patterns:`)),g.length===0)console.log(o.dim(" No patterns extracted"));else for(let r of g)console.log(` ${o.green("+")} ${o.cyan(r.name)}`),console.log(o.dim(` Domain: ${r.domain}, Type: ${r.patternType}`)),console.log(o.dim(` Confidence: ${(r.confidence*100).toFixed(0)}%, Sources: ${r.sourceCount}`));if(!t.dryRun&&g.length>0){let r=await O(),c=0,u=[];for(let a of g)try{let y=a.actions.length>0?`// ${a.name}
54
- // Steps: ${a.actions.join(" -> ")}
55
-
56
- {{implementation}}`:`// ${a.name}
57
- // Extracted pattern with ${a.sourceCount} successful uses
58
-
59
- {{implementation}}`,f=await r.storePattern({patternType:a.patternType,name:a.name,description:`Extracted from ${a.sourceCount} learning experiences with avg reward ${a.avgReward.toFixed(2)}`,template:{type:"code",content:y,variables:[{name:"implementation",type:"code",required:!0,description:"Implementation code for this pattern"}]},context:{tags:[a.domain,a.patternType,`sources:${a.sourceCount}`,`reward:${a.avgReward.toFixed(2)}`]}});f.success?c++:u.push(`${a.name}: ${f.error.message}`)}catch(y){u.push(`${a.name}: ${y instanceof Error?y.message:"unknown"}`)}console.log(o.green(`
60
- \u2713 Stored ${c} new patterns`)),u.length>0&&u.length<=5&&console.log(o.yellow(` Errors: ${u.slice(0,3).join(", ")}${u.length>3?"...":""}`))}else t.dryRun&&console.log(o.yellow(`
61
- Dry run - no patterns stored`));console.log("")}return}catch(e){throw R(`extract failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function ve(s){s.command("dashboard").description("Display learning system dashboard with metrics and trends").option("--json","Output as JSON").option("--save-snapshot","Save a daily metrics snapshot").action(async t=>{try{let e=T(),n=Z(e);await n.initialize(),t.saveSnapshot&&(await n.saveSnapshot(),P("Daily snapshot saved"));let l=await n.getDashboardData();n.close(),t.json?v(l):ae(l);return}catch(e){throw R(`dashboard failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function Re(s){s.command("info").description("Show learning system configuration and paths").action(async()=>{try{let t=T(),e=S.join(t,".agentic-qe");console.log(o.bold(`
62
- \u{1F4CB} AQE Learning System Info
63
- `)),console.log(o.bold("Paths:")),console.log(` Data directory: ${e}`),console.log(` Memory database: ${S.join(e,"memory.db")}`),console.log(` HNSW index: ${S.join(e,"data","hnsw")}`),console.log(` Patterns: ${S.join(e,"data","patterns")}`),console.log(o.bold(`
64
- Configuration:`)),console.log(` Learning enabled: ${process.env.AQE_LEARNING_ENABLED!=="false"?o.green("yes"):o.red("no")}`),console.log(` V3 mode: ${process.env.AQE_V3_MODE==="true"?o.green("yes"):o.dim("no")}`),console.log(` Promotion threshold: ${process.env.AQE_V3_PATTERN_PROMOTION_THRESHOLD||"3"} uses`),console.log(` Success rate threshold: ${process.env.AQE_V3_SUCCESS_RATE_THRESHOLD||"0.7"}`),console.log(o.bold(`
65
- Domains:`)),console.log(` ${q.join(", ")}`),console.log(o.bold(`
66
- Hooks:`)),console.log(" Configure in .claude/settings.json"),console.log(` Events: pre-edit, post-edit, pre-task, post-task, route
67
- `);return}catch(t){throw R(`info failed: ${t instanceof Error?t.message:"unknown"}`),t}})}function Ee(s){s.command("backup").description("Backup learning database to a file").option("-o, --output <path>","Output file path").option("--compress","Compress backup with gzip").option("--verify","Verify backup integrity after creation").option("--json","Output as JSON").action(async t=>{try{let e=j();if(!w(e))throw new Error(`No learning database found at: ${e}`);let n=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),l=S.join(process.cwd(),"backups",`learning-${n}.db`),i=t.output?S.resolve(t.output):l,m=S.dirname(i);w(m)||le(m,{recursive:!0});let p=await M(e),d=(p.size/1024).toFixed(2);B(e,i);let g=`${e}-wal`;w(g)&&B(g,`${i}-wal`);let r=i;t.compress&&(r=await Q(i),await E(i),w(`${i}-wal`)&&await E(`${i}-wal`));let c=await M(r),u=(c.size/1024).toFixed(2),a;t.verify&&!t.compress&&(a=await _(i));let y=await N(e);if(t.json)v({success:!0,sourcePath:e,backupPath:r,sourceSizeKB:parseFloat(d),backupSizeKB:parseFloat(u),compressed:t.compress||!1,schemaVersion:y,verification:a,timestamp:new Date().toISOString()});else{if(console.log(o.bold(`
68
- \u{1F4BE} Learning Database Backup
69
- `)),console.log(` Source: ${e}`),console.log(` Source size: ${d} KB`),console.log(` Backup: ${r}`),console.log(` Backup size: ${u} KB`),console.log(` Schema version: ${y}`),t.compress){let f=((1-c.size/p.size)*100).toFixed(1);console.log(` Compression: ${f}% reduction`)}a&&console.log(a.valid?o.green(` Verification: ${a.message}`):o.red(` Verification: ${a.message}`)),P(`Backup saved to: ${r}
70
- `)}return}catch(e){throw R(`backup failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function ke(s){s.command("restore").description("Restore learning database from backup").requiredOption("-i, --input <path>","Backup file path to restore from").option("--verify","Verify backup integrity before restore").option("--force","Overwrite existing database without confirmation").option("--json","Output as JSON").action(async t=>{try{let e=S.resolve(t.input),n=j();if(!w(e))throw new Error(`Backup file not found: ${e}`);let l=e.endsWith(".gz"),i=e;if(l){let g=e.replace(".gz",".tmp");await V(e,g),i=g}if(t.verify){let g=await _(i);if(!g.valid)throw l&&w(i)&&await E(i),new Error(`Backup verification failed: ${g.message}`)}if(w(n)&&!t.force)throw l&&w(i)&&await E(i),new Error(`Database already exists at: ${n}. Use --force to overwrite`);let m=S.dirname(n);w(m)||le(m,{recursive:!0}),w(n)&&await E(n),w(`${n}-wal`)&&await E(`${n}-wal`),w(`${n}-shm`)&&await E(`${n}-shm`),B(i,n),l&&w(i)&&await E(i);let p=await M(n),d=await N(n);t.json?v({success:!0,backupPath:e,restoredPath:n,sizeKB:parseFloat((p.size/1024).toFixed(2)),schemaVersion:d,wasCompressed:l,timestamp:new Date().toISOString()}):(console.log(o.bold(`
71
- \u{1F504} Learning Database Restore
72
- `)),console.log(` Backup: ${e}`),console.log(` Restored to: ${n}`),console.log(` Size: ${(p.size/1024).toFixed(2)} KB`),console.log(` Schema version: ${d}`),P(`Database restored successfully
73
- `));return}catch(e){throw R(`restore failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function xe(s){s.command("verify").description("Verify learning database integrity").option("-f, --file <path>","Database file to verify (defaults to current)").option("--json","Output as JSON").action(async t=>{try{let e=t.file?S.resolve(t.file):j();if(!w(e))throw new Error(`Database file not found: ${e}`);let n=await _(e),l=await N(e),i=await M(e),m={};try{let p=C(e,{readonly:!0});for(let d of["qe_patterns","qe_trajectories","captured_experiences","kv_store","vectors"])try{let g=p.prepare(`SELECT COUNT(*) as count FROM ${d}`).get();m[d]=g.count}catch{}p.close()}catch{}if(t.json)v({valid:n.valid,message:n.message,path:e,sizeKB:parseFloat((i.size/1024).toFixed(2)),schemaVersion:l,tableCounts:m,timestamp:new Date().toISOString()});else{if(console.log(o.bold(`
74
- \u{1F50D} Database Verification
75
- `)),console.log(` Path: ${e}`),console.log(` Size: ${(i.size/1024).toFixed(2)} KB`),console.log(` Schema version: ${l}`),console.log(n.valid?o.green(` Status: ${n.message}`):o.red(` Status: ${n.message}`)),Object.keys(m).length>0){console.log(o.bold(`
76
- Table Counts:`));for(let[p,d]of Object.entries(m))console.log(` ${p}: ${d}`)}console.log("")}if(!n.valid)throw new Error(`Database verification failed: ${n.message}`);return}catch(e){throw R(`verify failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function De(s){s.command("export-full").description("Export all learning data including patterns, trajectories, and experiences").option("-o, --output <file>","Output file path","aqe-learning-export.json").option("--compress","Compress output with gzip").option("--include-trajectories","Include learning trajectories").option("--include-experiences","Include learning experiences").option("--json","Output as JSON (to stdout)").action(async t=>{try{let e=j();if(!w(e))throw new Error('No learning database found. Run "aqe init --auto" first.');let n=await O(),l=await N(e),i=await n.searchPatterns("*",{limit:1e4});if(!i.success)throw new Error(i.error.message);let m=i.value.map(d=>({id:d.pattern.id,name:d.pattern.name,description:d.pattern.description,patternType:d.pattern.patternType,qeDomain:d.pattern.qeDomain,tier:d.pattern.tier,confidence:d.pattern.confidence,successRate:d.pattern.successRate,successfulUses:d.pattern.successfulUses,qualityScore:d.pattern.qualityScore,template:d.pattern.template,context:d.pattern.context,createdAt:d.pattern.createdAt instanceof Date?d.pattern.createdAt.toISOString():d.pattern.createdAt||void 0,lastUsedAt:d.pattern.lastUsedAt instanceof Date?d.pattern.lastUsedAt.toISOString():d.pattern.lastUsedAt||void 0})),p={version:H,exportedAt:new Date().toISOString(),source:process.cwd(),schemaVersion:l,patternCount:m.length,patterns:m};if(t.includeTrajectories)try{let d=C(e,{readonly:!0}),g=d.prepare("SELECT id, task, agent, domain, success, steps_json FROM qe_trajectories ORDER BY started_at DESC LIMIT 1000").all();p.trajectories=g.map(r=>({id:r.id,task:r.task,agent:r.agent,domain:r.domain,success:r.success,stepsJson:r.steps_json})),d.close()}catch{}if(t.includeExperiences)try{let d=C(e,{readonly:!0}),g=d.prepare("SELECT domain as task_type, agent as action, AVG(quality) as avg_reward, COUNT(*) as count FROM captured_experiences WHERE agent != 'cli-hook' GROUP BY domain, agent ORDER BY count DESC LIMIT 500").all();p.experiences=g.map(c=>({taskType:c.task_type,action:c.action,reward:c.avg_reward,count:c.count}));let r=d.prepare("SELECT COUNT(*) as total, AVG(quality) as avg_reward FROM captured_experiences WHERE agent != 'cli-hook'").get();p.metadata={totalExperiences:r.total,avgReward:r.avg_reward},d.close()}catch{}if(t.json)v(p);else{let d=S.resolve(t.output);if(ce(d,JSON.stringify(p,null,2),"utf-8"),t.compress){let g=await Q(d);await E(d),d=g}console.log(o.bold(`
77
- \u{1F4E4} Learning Data Export
78
- `)),console.log(` Patterns: ${m.length}`),p.trajectories&&console.log(` Trajectories: ${p.trajectories.length}`),p.experiences&&console.log(` Experience groups: ${p.experiences.length}`),console.log(` Schema version: ${l}`),console.log(` Export format: ${H}`),P(`Exported to: ${d}
79
- `)}return}catch(e){throw R(`export-full failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function Ce(s){s.command("import-merge").description("Import and merge patterns from export file (preserves existing data)").requiredOption("-i, --input <file>","Input file path").option("--skip-duplicates","Skip patterns with matching names (default: update)").option("--dry-run","Show what would be imported without making changes").option("--json","Output as JSON").action(async t=>{try{let e=S.resolve(t.input);if(!w(e))throw new Error(`File not found: ${e}`);let n;if(e.endsWith(".gz")){let f=e.replace(".gz",".tmp.json");await V(e,f),n=W(f,"utf-8"),await E(f)}else n=W(e,"utf-8");let l=z(n);if(!l.patterns||!Array.isArray(l.patterns))throw new Error("Invalid import file format: missing patterns array");let i=await O(),m=await i.searchPatterns("*",{limit:1e4}),p=new Set;if(m.success)for(let f of m.value)p.add(f.pattern.name);let d=0,g=0,r=0,c=[];if(!t.dryRun)for(let f of l.patterns){let h=p.has(f.name);if(h&&t.skipDuplicates){g++;continue}try{let $=await i.storePattern({patternType:f.patternType,name:f.name,description:f.description,template:f.template,context:f.context});$.success?h?r++:d++:(g++,c.push(`${f.name}: ${$.error.message}`))}catch($){g++,c.push(`${f.name}: ${$ instanceof Error?$.message:"unknown"}`)}}let u=0,a=0,y=0;if(t.dryRun)for(let f of l.patterns){let h=p.has(f.name);h&&t.skipDuplicates?a++:h?y++:u++}t.json?v({dryRun:t.dryRun||!1,importVersion:l.version,totalPatterns:l.patterns.length,imported:t.dryRun?u:d,updated:t.dryRun?y:r,skipped:t.dryRun?a:g,errors:c.slice(0,10)}):(console.log(o.bold(`
80
- \u{1F4E5} Learning Data Import (Merge)
81
- `)),console.log(` Source: ${e}`),console.log(` Export version: ${l.version||"unknown"}`),console.log(` Total patterns: ${l.patterns.length}`),console.log(` Existing patterns: ${p.size}`),t.dryRun?(console.log(o.yellow(`
82
- Dry run - no changes made`)),console.log(` Would import: ${u}
83
- Would update: ${y}
84
- Would skip: ${a}`)):(console.log(o.green(`
85
- Imported: ${d}`)),console.log(o.blue(` Updated: ${r}`)),g>0&&console.log(o.yellow(` Skipped: ${g}`)),c.length>0&&console.log(o.red(` Errors: ${c.length}`))),console.log(""));return}catch(e){throw R(`import-merge failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function Oe(s){s.command("dream").description("Run dream cycles for pattern discovery via spreading activation").option("--duration <ms>","Duration of dream cycle in milliseconds","30000").option("--quick","Run a quick 5-second dream cycle").option("--full","Run a full 30-second dream cycle").option("--status","Show dream system status").option("--history","Show past dream cycles").option("--insights","Show pending insights from previous cycles").option("--apply <id>","Apply a specific insight by ID").option("--limit <n>","Maximum results for history/insights","20").option("--min-patterns <n>","Minimum patterns required to dream","10").option("--json","Output as JSON").action(async t=>{try{let{createDreamEngine:e}=await import("./dream-77ODIFIF.js");if(t.status){let r=e();await r.initialize();let c=r.isDreaming(),u=await r.getDreamHistory(100),a=await r.getPendingInsights(100),y=u.reduce((h,$)=>h+$.insightsGenerated,0),f=u[0];if(t.json)v({isDreaming:c,totalCycles:u.length,totalInsights:y,pendingInsights:a.length,lastDreamTime:f?.startTime.toISOString()||null});else{if(console.log(o.bold(`
86
- \u{1F319} Dream System Status
87
- `)),console.log(` Currently dreaming: ${c?o.green("Yes"):o.dim("No")}`),console.log(` Total dream cycles: ${u.length}`),console.log(` Total insights generated: ${y}`),console.log(` Pending insights: ${a.length}`),console.log(` Last dream: ${f?f.startTime.toISOString():o.dim("never")}`),u.length>0){console.log(o.bold(`
88
- Recent cycles:`));for(let h of u.slice(0,3)){let $=h.status==="completed"?o.green(h.status):o.yellow(h.status);console.log(` ${h.id.slice(0,8)} | ${$} | ${h.durationMs||0}ms | ${h.insightsGenerated} insights`)}}console.log("")}await r.close();return}if(t.history){let r=parseInt(t.limit,10),c=e();await c.initialize();let u=await c.getDreamHistory(r);if(t.json)v(u.map(a=>({id:a.id,startTime:a.startTime.toISOString(),endTime:a.endTime?.toISOString(),durationMs:a.durationMs,status:a.status,conceptsProcessed:a.conceptsProcessed,associationsFound:a.associationsFound,insightsGenerated:a.insightsGenerated})));else{if(console.log(o.bold(`
89
- \u{1F319} Dream Cycle History (${u.length} cycles)
90
- `)),u.length===0)console.log(o.dim(" No dream cycles found. Run: aqe learning dream"));else for(let a of u){let y=a.status==="completed"?o.green("\u2713"):a.status==="failed"?o.red("\u2717"):o.yellow("\u22EF");console.log(` ${y} ${a.id.slice(0,8)} | ${a.startTime.toISOString()}`),console.log(o.dim(` Duration: ${a.durationMs||0}ms | Concepts: ${a.conceptsProcessed} | Associations: ${a.associationsFound} | Insights: ${a.insightsGenerated}`))}console.log("")}await c.close();return}if(t.insights){let r=parseInt(t.limit,10),c=e();await c.initialize();let u=await c.getPendingInsights(r);if(t.json)v(u.map(a=>({id:a.id,type:a.type,description:a.description,noveltyScore:a.noveltyScore,confidenceScore:a.confidenceScore,actionable:a.actionable,applied:a.applied||!1,suggestedAction:a.suggestedAction,createdAt:a.createdAt?.toISOString()})));else{if(console.log(o.bold(`
91
- \u{1F4A1} Pending Dream Insights (${u.length})
92
- `)),u.length===0)console.log(o.dim(" No pending insights. Run a dream cycle first: aqe learning dream"));else for(let a of u){let y=a.noveltyScore>=.7?o.green(`${(a.noveltyScore*100).toFixed(0)}%`):o.yellow(`${(a.noveltyScore*100).toFixed(0)}%`),f=a.confidenceScore>=.7?o.green(`${(a.confidenceScore*100).toFixed(0)}%`):o.yellow(`${(a.confidenceScore*100).toFixed(0)}%`);console.log(` ${o.cyan(a.id.slice(0,8))} [${a.type}] ${a.actionable?"\u26A1":" "}`),console.log(` ${a.description}`),console.log(o.dim(` Novelty: ${y} | Confidence: ${f}`)),a.suggestedAction&&console.log(o.dim(` Action: ${a.suggestedAction}`))}console.log("")}await c.close();return}if(t.apply){let r=t.apply,c=e();await c.initialize();let a=(await c.getPendingInsights(100)).find($=>$.id===r||$.id.startsWith(r));if(!a)throw await c.close(),new Error(`Insight not found: ${r}`);if(!a.actionable)throw await c.close(),new Error(`Insight ${r} is not actionable`);let y=await c.applyInsight(a.id),h=await(await O()).storePattern({patternType:"test-template",name:`Dream Insight: ${a.type}`,description:`${a.description} (confidence: ${a.confidenceScore.toFixed(2)})`,template:{type:"workflow",content:a.suggestedAction||a.description,variables:[]},context:{tags:["dream-generated",a.type,...a.sourceConcepts.slice(0,3)],complexity:"medium"}});if(t.json?v({insightId:a.id,applied:y.success,patternId:h.success?h.value.id:null,error:y.error||(h.success?null:h.error?.message)}):y.success?(P(`Applied insight ${a.id.slice(0,8)}`),h.success&&P(`Created pattern ${h.value.id} in ReasoningBank`)):R(`Failed to apply insight: ${y.error}`),await c.close(),!y.success)throw new Error(`Failed to apply insight: ${y.error}`);return}let n=parseInt(t.duration,10);t.quick&&(n=5e3),t.full&&(n=3e4),n=Math.min(n,6e4);let l=parseInt(t.minPatterns,10);I(`Starting dream cycle (${n}ms, min ${l} patterns)...`);let i=e({maxDurationMs:n,minConceptsRequired:l});await i.initialize();let p=await(await O()).searchPatterns("",{limit:100,minConfidence:.3}),d=0;if(p.success&&p.value.length>0){let r=p.value.map(c=>({id:c.pattern.id,name:c.pattern.name,description:c.pattern.description||`${c.pattern.patternType} pattern`,domain:c.pattern.qeDomain||"learning-optimization",patternType:c.pattern.patternType,confidence:c.pattern.confidence,successRate:c.pattern.successRate||.5}));d=await i.loadPatternsAsConcepts(r),I(`Loaded ${d} patterns from ReasoningBank as concepts`)}else I("No patterns found in ReasoningBank \u2014 dreaming with existing concepts");let g=await i.dream(n);if(t.json)v({cycleId:g.cycle.id,status:g.cycle.status,durationMs:g.cycle.durationMs||0,conceptsProcessed:g.cycle.conceptsProcessed,associationsFound:g.cycle.associationsFound,insightsGenerated:g.cycle.insightsGenerated,activationStats:g.activationStats,patternsCreated:g.patternsCreated,insights:g.insights.map(r=>({id:r.id,type:r.type,description:r.description,noveltyScore:r.noveltyScore,confidenceScore:r.confidenceScore,actionable:r.actionable}))});else{if(console.log(o.bold(`
93
- \u{1F319} Dream Cycle Complete
94
- `)),console.log(` Cycle ID: ${g.cycle.id.slice(0,8)}`),console.log(` Status: ${g.cycle.status==="completed"?o.green("completed"):o.yellow(g.cycle.status)}`),console.log(` Duration: ${g.cycle.durationMs||0}ms`),console.log(` Concepts: ${g.cycle.conceptsProcessed}`),console.log(` Associations: ${g.cycle.associationsFound}`),console.log(` Insights: ${g.cycle.insightsGenerated}`),g.activationStats&&(console.log(o.bold(`
95
- Activation Stats:`)),console.log(` Iterations: ${g.activationStats.totalIterations}`),console.log(` Peak level: ${g.activationStats.peakActivation.toFixed(3)}`),console.log(` Nodes active: ${g.activationStats.nodesActivated}`)),g.insights.length>0){console.log(o.bold(`
96
- Generated Insights:`));for(let r of g.insights){let c=r.noveltyScore>=.7?o.green(`${(r.noveltyScore*100).toFixed(0)}%`):o.yellow(`${(r.noveltyScore*100).toFixed(0)}%`);console.log(` ${o.cyan(r.id.slice(0,8))} [${r.type}] ${r.actionable?"\u26A1 actionable":""}`),console.log(` ${r.description}`),console.log(o.dim(` Novelty: ${c} | Confidence: ${(r.confidenceScore*100).toFixed(0)}%`))}console.log(o.dim(`
97
- Apply insights with: aqe learning dream --apply <insight-id>`))}else console.log(o.dim(`
98
- No insights generated this cycle.`)),console.log(o.dim(" Try loading more patterns or running a longer cycle."));console.log("")}await i.close();return}catch(e){throw R(`dream failed: ${e instanceof Error?e.message:"unknown"}`),e instanceof Error&&e.stack&&console.error(o.dim(e.stack)),e}})}function Pe(s){s.command("repair").description("Repair a corrupted learning database (dump + reimport to rebuild indexes)").option("-f, --file <path>","Database file to repair (defaults to current project)").option("--dry-run","Show what would be done without modifying files").option("--json","Output as JSON").action(async t=>{try{let e=t.file?S.resolve(t.file):j();if(!w(e))throw new Error(`Database file not found: ${e}`);let n=await _(e);if(n.valid){t.json?v({status:"healthy",message:"Database is already healthy, no repair needed",path:e}):P("Database integrity check passed \u2014 no repair needed.");return}I(`Corruption detected: ${n.message}`);let l={};try{let b=C(e,{readonly:!0}),k=b.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();for(let F of k)try{let L=b.prepare(`SELECT COUNT(*) as count FROM "${F.name}"`).get();l[F.name]=L.count}catch{}b.close()}catch{}let i=Object.values(l).reduce((b,k)=>b+k,0);if(I(`Found ${Object.keys(l).length} tables, ~${i} total rows`),t.dryRun){t.json?v({status:"dry-run",corruptionDetected:!0,message:n.message,tables:l,totalRows:i}):(console.log(o.bold(`
99
- Dry run \u2014 would perform these steps:`)),console.log(" 1. Backup corrupted DB"),console.log(" 2. Dump all data via .dump"),console.log(" 3. Reimport into fresh DB (rebuilds all indexes)"),console.log(" 4. Verify integrity of repaired DB"),console.log(" 5. Verify row counts match"),console.log(" 6. Swap repaired DB into place"),console.log(""));return}let m=`${e}.bak-${Date.now()}`;B(e,m),I(`Backup created: ${m}`);for(let b of["-wal","-shm"]){let k=e+b;w(k)&&await E(k)}let{execFileSync:p}=await import("node:child_process"),{openSync:d,closeSync:g,readFileSync:r}=await import("node:fs"),c=`${e}.repaired`,u=`${e}.dump.sql`;try{let b=d(u,"w");try{p("sqlite3",[e,".dump"],{stdio:["ignore",b,"pipe"],timeout:12e4})}finally{g(b)}p("sqlite3",[c],{input:r(u),stdio:["pipe","pipe","pipe"],timeout:12e4}),p("sqlite3",[c,"PRAGMA journal_mode=WAL;"],{stdio:"pipe"})}catch(b){throw w(c)&&await E(c),w(u)&&await E(u),new Error(`sqlite3 dump/reimport failed: ${b instanceof Error?b.message:"unknown"}. Is sqlite3 installed?`)}let a=await _(c);if(!a.valid)throw w(u)&&await E(u),new Error(`Repaired DB still has integrity issues: ${a.message}. Backup preserved at ${m}`);let y={},f=C(c,{readonly:!0}),h=f.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();for(let b of h)try{let k=f.prepare(`SELECT COUNT(*) as count FROM "${b.name}"`).get();y[b.name]=k.count}catch{}f.close();let $=Object.values(y).reduce((b,k)=>b+k,0);ie(e,`${e}.pre-repair`),ie(c,e),w(u)&&await E(u),t.json?v({status:"repaired",backupPath:m,rowsBefore:i,rowsAfter:$,tablesRepaired:Object.keys(y).length,rowCounts:y}):(P("Database repaired successfully!"),console.log(` Backup: ${m}`),console.log(` Rows before: ${i}`),console.log(` Rows after: ${$}`),$<i&&console.log(o.yellow(` Warning: ${i-$} rows may have been lost due to data page corruption`)),console.log(` Tables: ${Object.keys(y).length}`),console.log(` Integrity: ${o.green("OK")}`),console.log(""));return}catch(e){throw R(`repair failed: ${e instanceof Error?e.message:"unknown"}`),e}})}function Te(s){switch(s){case"sublinear":return{arrow:"\u25B2",label:"Sublinear (learning)",color:o.green};case"linear":return{arrow:"\u2192",label:"Linear (stagnating)",color:o.yellow};case"superlinear":return{arrow:"\u25BC",label:"Superlinear (degrading)",color:o.red};default:return{arrow:"?",label:"Insufficient data",color:o.dim}}}function Ae(s){s.command("health").description("Display per-domain learning health based on regret tracking").option("--json","Output as JSON").option("--domain <domain>","Filter to a specific domain").action(async t=>{try{let e=T(),n=S.join(e,".agentic-qe","memory.db");if(!w(n))throw new Error('Database not found. Run "aqe init --auto" first.');let l=ee(),i=C(n,{readonly:!0});if(i.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='captured_experiences'").get()){let c=t.domain?"AND domain = ?":"",u=[];t.domain&&u.push(t.domain);let a=i.prepare(`
100
- SELECT domain, quality, success, started_at
101
- FROM captured_experiences
102
- WHERE agent != 'cli-hook'
103
- AND domain IS NOT NULL
104
- AND domain != ''
105
- ${c}
106
- ORDER BY started_at ASC
107
- `).all(...u);for(let y of a){let f=y.quality??(y.success?1:0);l.recordDecision(y.domain,f,1)}}i.close();let p=l.getHealthSummary();if(t.json){v(p);return}if(console.log(""),console.log(o.bold("Learning Health Dashboard:")),p.length===0){console.log(o.dim(" No domain data available. Run some QE tasks to generate learning data.")),console.log("");return}let d=Math.max(...p.map(c=>c.domain.length),20);for(let c of p){let{arrow:u,label:a,color:y}=Te(c.growthRate),f=D(c.domain+":",d+1),h=y(`${u} ${D(a,26)}`),$=`regret: ${c.cumulativeRegret.toFixed(1)}`,b=`decisions: ${c.totalDecisions}`;console.log(` ${f} ${h} ${$} ${b}`)}let g=p.filter(c=>c.stagnating);g.length>0&&(console.log(""),console.log(o.yellow(` Warning: ${g.length} domain(s) showing stagnation: ${g.map(c=>c.domain).join(", ")}`)));let r=p.filter(c=>c.growthRate==="sublinear");r.length>0&&console.log(o.green(` ${r.length} domain(s) actively learning`)),console.log("");return}catch(e){throw R(`health check failed: ${e instanceof Error?e.message:"unknown"}`),e}})}export{at as createLearningCommand,O as initializeLearningSystem};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{a}from"./chunk-GRPEDIYG.js";import"./chunk-OEGFOMXP.js";import"./chunk-XK6YXCS7.js";import"./chunk-TYZGEVP6.js";import"./chunk-DJRWVNHK.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import"./chunk-Q4HJRYQB.js";import"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import"./chunk-CNNVL5W4.js";import"./chunk-TULNR2AH.js";import"./chunk-7D2DM23U.js";import"./chunk-37I6K7QO.js";import"./chunk-XVTZXCHI.js";import"./chunk-KR2PGNXX.js";import"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";export{a as LoadTestTool};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{a}from"./chunk-AQJ6XS34.js";import"./chunk-XVTZXCHI.js";import"./chunk-KR2PGNXX.js";import"./chunk-ITBPDVK5.js";export{a as InMemoryBackend};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{c as a,d as c}from"./chunk-NMBHF7ZD.js";import"./chunk-USN2JKUW.js";import"./chunk-MHPK4ZPK.js";import"./chunk-H27XUYWZ.js";import"./chunk-IP6ZTXNJ.js";import"./chunk-MYF7F3ZP.js";import"./chunk-Q26GG6WO.js";import"./chunk-5E3YCZC5.js";import"./chunk-2MKSEL6F.js";import"./chunk-QSV4ROZD.js";import"./chunk-FU74OETU.js";import"./chunk-2NFGUFYU.js";import"./chunk-UEXOMDRS.js";import"./chunk-RYMHYTOK.js";import"./chunk-5F26LSG2.js";import"./chunk-Q53UMLLC.js";import"./chunk-GRPEDIYG.js";import"./chunk-3NGNSKL3.js";import"./chunk-52TRKIAQ.js";import"./chunk-IWC6GR24.js";import"./chunk-VOBNJWZF.js";import"./chunk-HB52S6IV.js";import"./chunk-SAVITYEX.js";import"./chunk-OOFWYDG6.js";import"./chunk-3PZDXE5E.js";import"./chunk-XKH4E2IQ.js";import"./chunk-WTXRPYNN.js";import"./chunk-C6TNYLD7.js";import"./chunk-DEDFPHJL.js";import"./chunk-TA3QYAZ6.js";import"./chunk-OTFJCZNY.js";import"./chunk-ER6BT4GS.js";import"./chunk-ETEHVG76.js";import"./chunk-MV3NUANS.js";import"./chunk-YXR5RYRE.js";import"./chunk-6HSFZ6SL.js";import"./chunk-L7X3A36M.js";import"./chunk-ZKZTSYPU.js";import"./chunk-HJDHQBMJ.js";import"./chunk-3EP2YZSY.js";import"./chunk-H2IMXQCJ.js";import{a as m,b as R,d as $,e as y,f as g,i as b}from"./chunk-AWWD3EI3.js";import"./chunk-XDYTQPJM.js";import"./chunk-YETPSL6H.js";import"./chunk-SPCANEJY.js";import"./chunk-ND6VCNN5.js";import"./chunk-DDMFTEJP.js";import"./chunk-HA7N45KB.js";import"./chunk-WVODEWH5.js";import"./chunk-VRP4GB4Y.js";import"./chunk-R5IW5ARI.js";import"./chunk-2GBBZLXT.js";import"./chunk-QHKK2H4H.js";import"./chunk-IOINZWNA.js";import"./chunk-Y57V4FDT.js";import"./chunk-JNRRDG7O.js";import"./chunk-3AICELMQ.js";import"./chunk-OEGFOMXP.js";import"./chunk-XK6YXCS7.js";import"./chunk-JCWHX4XV.js";import"./chunk-FI4HRS2G.js";import"./chunk-FG5GL26L.js";import"./chunk-IEGAEXQX.js";import"./chunk-QTS2DS42.js";import"./chunk-QBDXUI2H.js";import"./chunk-2O5TT3UT.js";import"./chunk-R57J3O6I.js";import"./chunk-UROPIIB2.js";import"./chunk-5DJAJPBG.js";import{b as w}from"./chunk-4UZQSPR4.js";import"./chunk-IHRFR5SV.js";import"./chunk-TYZGEVP6.js";import"./chunk-DJRWVNHK.js";import"./chunk-MZ7M2CDV.js";import"./chunk-7Z3GBQNV.js";import"./chunk-3WIU2E2Y.js";import"./chunk-FGDEM4HU.js";import"./chunk-Q4HJRYQB.js";import"./chunk-LDGNVPBZ.js";import{a as i,c as S}from"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import"./chunk-AQJ6XS34.js";import"./chunk-CNNVL5W4.js";import"./chunk-TULNR2AH.js";import"./chunk-7D2DM23U.js";import"./chunk-37I6K7QO.js";import"./chunk-XVTZXCHI.js";import"./chunk-KR2PGNXX.js";import"./chunk-GEXVUFK4.js";import"./chunk-QNSUPXUU.js";import"./chunk-UYLHIGNC.js";import"./chunk-ITBPDVK5.js";S();async function T(e){if(!c())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{kernel:s}=a();try{let t=e.namespace||"default",n=`${t}:${e.key}`;if(m()){let r=g(e.key,e.value,t,{tags:e.metadata?.tags}),o=await y.evaluateWrite(r);if(!o.allowed){if(R()&&b.recordViolation({type:"contradiction",severity:"medium",gate:"memoryWriteGate",description:`Memory write blocked for key ${e.key}: ${o.reason}`,context:{key:e.key,namespace:t,reason:o.reason,conflictingPatterns:o.conflictingPatterns}}),$())return{success:!1,error:`Memory write blocked by governance: ${o.reason}`};console.warn(`[MemoryHandler] Write allowed with warning: ${o.reason}`)}}await s.memory.set(n,e.value,{ttl:e.ttl});try{let r=`${e.key} ${JSON.stringify(e.value)}`,o=await w(r);await s.memory.storeVector(n,o,{key:e.key,namespace:t,storedAt:Date.now()})}catch(r){console.warn(`[MemoryHandler] Vector indexing failed for ${e.key}: ${i(r)}`)}return m()&&y.registerPattern(g(e.key,e.value,t)),{success:!0,data:{stored:!0,key:e.key,namespace:t,timestamp:new Date().toISOString(),persisted:!0}}}catch(t){return{success:!1,error:`Failed to store memory: ${i(t)}`}}}async function z(e){if(!c())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{kernel:s}=a();try{let n=`${e.namespace||"default"}:${e.key}`,r=await s.memory.get(n);if(r===void 0)return{success:!0,data:{found:!1,key:e.key}};let o={found:!0,key:e.key,value:r,timestamp:new Date().toISOString()};return e.includeMetadata&&(o.metadata={}),{success:!0,data:o}}catch(t){return{success:!1,error:`Failed to retrieve memory: ${i(t)}`}}}function v(e){return e.includes(" ")&&!e.includes("*")&&!e.includes("?")}async function E(e){if(!c())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{kernel:s}=a();try{let t=e.namespace||"default",n=e.limit||100,r=e.offset||0;if((e.semantic===!0||e.semantic!==!1&&e.pattern&&v(e.pattern))&&e.pattern)try{let l=await w(e.pattern),u=await s.memory.vectorSearch(l,n+r),M=t!=="default"?u.filter(d=>d.key.startsWith(`${t}:`)):u;return{success:!0,data:{entries:M.slice(r,r+n).map(d=>{let k=d.key.split(":");return{key:k.length>1?k.slice(1).join(":"):d.key,namespace:k.length>1?k[0]:t,score:d.score}}),total:M.length,hasMore:r+n<M.length,searchType:"semantic"}}}catch(l){console.error(`[MemoryHandler] Semantic search failed, falling back to pattern: ${i(l)}`)}let f=e.pattern?`${t}:${e.pattern}`:`${t}:*`,h=await s.memory.search(f,n+r);return{success:!0,data:{entries:h.slice(r,r+n).map(l=>{let u=l.split(":");return{key:u.slice(1).join(":"),namespace:u[0]}}),total:h.length,hasMore:r+n<h.length,searchType:"pattern"}}}catch(t){return{success:!1,error:`Failed to query memory: ${i(t)}`}}}async function K(e){if(!c())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{kernel:s}=a();try{let t=e.namespace||"default",n=`${t}:${e.key}`;return{success:!0,data:{deleted:await s.memory.delete(n),key:e.key,namespace:t}}}catch(t){return{success:!1,error:`Failed to delete memory: ${i(t)}`}}}async function W(){if(!c())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{kernel:e}=a();try{let s=await e.memory.search("*",1e4),t=0,n=1;try{let r=e.memory;r.getVectorStats&&(t=(await r.getVectorStats())?.vectorCount??0);let o=new Set(s.map(f=>f.split(":")[0]).filter(Boolean));n=Math.max(1,o.size)}catch{}return{success:!0,data:{entries:s.length,vectors:t,namespaces:n,size:{current:s.length,limit:Number.MAX_SAFE_INTEGER,unit:"entries"}}}}catch(s){return{success:!1,error:`Failed to get memory usage: ${i(s)}`}}}async function _(e){if(!c())return{success:!1,error:"Fleet not initialized. Call fleet_init first."};let{kernel:s}=a();try{let t=`shared:${e.knowledgeDomain}:${Date.now()}`,n={source:e.sourceAgentId,targets:e.targetAgentIds,domain:e.knowledgeDomain,content:e.knowledgeContent,timestamp:new Date().toISOString()};if(m()){let r=g(t,n,e.knowledgeDomain,{agentId:e.sourceAgentId}),o=await y.evaluateWrite(r);if(!o.allowed&&(R()&&b.recordViolation({type:"contradiction",severity:"medium",agentId:e.sourceAgentId,gate:"memoryWriteGate",description:`Shared knowledge blocked for domain ${e.knowledgeDomain}: ${o.reason}`,context:{sourceAgent:e.sourceAgentId,targetAgents:e.targetAgentIds,domain:e.knowledgeDomain,reason:o.reason}}),$()))return{success:!1,error:`Knowledge sharing blocked by governance: ${o.reason}`}}return await s.memory.set(t,n,{namespace:"agent-knowledge"}),m()&&y.registerPattern(g(t,n,e.knowledgeDomain)),{success:!0,data:{shared:!0,sourceAgent:e.sourceAgentId,targetAgents:e.targetAgentIds,domain:e.knowledgeDomain}}}catch(t){return{success:!1,error:`Failed to share memory: ${i(t)}`}}}export{K as handleMemoryDelete,E as handleMemoryQuery,z as handleMemoryRetrieve,_ as handleMemoryShare,T as handleMemoryStore,W as handleMemoryUsage};
@@ -1,2 +0,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.9.30");process.exit(0)}
2
- import{a,b}from"./chunk-ETEHVG76.js";import"./chunk-MV3NUANS.js";import"./chunk-YXR5RYRE.js";import"./chunk-LDGNVPBZ.js";import"./chunk-RNO6CE7I.js";import"./chunk-GY4EGQO3.js";import"./chunk-ITBPDVK5.js";export{a as DefaultProtocolExecutor,b as createProtocolExecutor};