agentic-qe 3.15.17 → 3.15.18

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 (495) hide show
  1. package/.claude/helpers/brain-checkpoint.cjs +107 -10
  2. package/.claude/skills/agentic-quality-engineering/SKILL.md +67 -44
  3. package/.claude/skills/brutal-honesty-review/SKILL.md +12 -7
  4. package/.claude/skills/brutal-honesty-review/evals/brutal-honesty-review.yaml +120 -0
  5. package/.claude/skills/brutal-honesty-review/schemas/output.json +9 -3
  6. package/.claude/skills/code-review-quality/SKILL.md +2 -2
  7. package/.claude/skills/holistic-testing-pact/SKILL.md +11 -11
  8. package/.claude/skills/sherlock-review/SKILL.md +4 -2
  9. package/.claude/skills/sherlock-review/evals/sherlock-review.yaml +124 -0
  10. package/.claude/skills/skills-manifest.json +1 -1
  11. package/.claude/skills/technical-writing/SKILL.md +12 -6
  12. package/.claude/skills/technical-writing/evals/technical-writing.yaml +96 -0
  13. package/.opencode/skills/qe-agentic-quality-engineering.yaml +2 -2
  14. package/.opencode/skills/qe-holistic-testing-pact.yaml +2 -2
  15. package/CHANGELOG.md +123 -0
  16. package/assets/skills/agentic-quality-engineering/SKILL.md +67 -44
  17. package/assets/skills/brutal-honesty-review/SKILL.md +12 -8
  18. package/assets/skills/brutal-honesty-review/evals/brutal-honesty-review.yaml +120 -0
  19. package/assets/skills/brutal-honesty-review/schemas/output.json +9 -3
  20. package/assets/skills/code-review-quality/SKILL.md +2 -2
  21. package/assets/skills/holistic-testing-pact/SKILL.md +11 -11
  22. package/assets/skills/sherlock-review/SKILL.md +4 -3
  23. package/assets/skills/sherlock-review/evals/sherlock-review.yaml +124 -0
  24. package/assets/skills/skills-manifest.json +1 -1
  25. package/assets/skills/technical-writing/SKILL.md +12 -6
  26. package/assets/skills/technical-writing/evals/technical-writing.yaml +96 -0
  27. package/dist/cli/brain-commands.d.ts +5 -0
  28. package/dist/cli/brain-commands.js +4 -0
  29. package/dist/cli/bundle.js +6 -6
  30. package/dist/cli/chunks/adapter-WRSDXLOT.js +2 -0
  31. package/dist/cli/chunks/{agent-booster-wasm-6BUOFQZA.js → agent-booster-wasm-UFNJNF3M.js} +2 -2
  32. package/dist/cli/chunks/{agent-handler-HPDK3JI3.js → agent-handler-EAYVRJXN.js} +2 -2
  33. package/dist/cli/chunks/{agent-memory-branch-5QKUTWK5.js → agent-memory-branch-M65C6WAQ.js} +2 -2
  34. package/dist/cli/chunks/aqe-learning-engine-O6NJBCCM.js +2 -0
  35. package/dist/cli/chunks/{arena-HZ35LESR.js → arena-2GDICP6R.js} +4 -4
  36. package/dist/cli/chunks/{arena-7OKPMNHD.js → arena-CG3X67OE.js} +2 -2
  37. package/dist/cli/chunks/{audit-XI575SVK.js → audit-F4FSPJPL.js} +3 -3
  38. package/dist/cli/chunks/base-J2FXOE77.js +2 -0
  39. package/dist/cli/chunks/{better-sqlite3-YO5X7ZJS.js → better-sqlite3-2MCFXW4J.js} +2 -2
  40. package/dist/cli/chunks/brain-handler-WGTJNYNB.js +95 -0
  41. package/dist/cli/chunks/{branch-enumerator-N6G44UU2.js → branch-enumerator-KL7C535H.js} +2 -2
  42. package/dist/cli/chunks/{browser-EVKPTLOI.js → browser-SJEXDVHS.js} +2 -2
  43. package/dist/cli/chunks/browser-workflow-LXGER6ZD.js +2 -0
  44. package/dist/cli/chunks/{chunk-VLTDW7XJ.js → chunk-244RKAEP.js} +2 -2
  45. package/dist/cli/chunks/{chunk-CVPXHDQU.js → chunk-27TUMXPD.js} +1 -1
  46. package/dist/cli/chunks/{chunk-FBBPRVNF.js → chunk-2MBYDPCP.js} +2 -2
  47. package/dist/cli/chunks/{chunk-P3D7SEHW.js → chunk-2Q6DTBMT.js} +1 -1
  48. package/dist/cli/chunks/{chunk-NE3LRUNC.js → chunk-355MI7RV.js} +13 -13
  49. package/dist/cli/chunks/{chunk-YCVLKU6H.js → chunk-3LX5OKBD.js} +2 -2
  50. package/dist/cli/chunks/{chunk-74MDUIAZ.js → chunk-3RPDKJGV.js} +1 -1
  51. package/dist/cli/chunks/{chunk-OWIQR6N2.js → chunk-3YMIT73A.js} +2 -2
  52. package/dist/cli/chunks/{chunk-VKREKVFI.js → chunk-43KUVBSU.js} +2 -2
  53. package/dist/cli/chunks/chunk-477FKXSS.js +2 -0
  54. package/dist/cli/chunks/{chunk-XPTCQKVE.js → chunk-4BIMTRRX.js} +1 -1
  55. package/dist/cli/chunks/{chunk-HD6W6PHV.js → chunk-4CVNVBX5.js} +2 -2
  56. package/dist/cli/chunks/{chunk-CQER6IJ5.js → chunk-4HL3SD4A.js} +1 -1
  57. package/dist/cli/chunks/{chunk-ZNXM6WVL.js → chunk-4PEG4DU2.js} +2 -2
  58. package/dist/cli/chunks/{chunk-BSIWI4ES.js → chunk-4QSQKFED.js} +2 -2
  59. package/dist/cli/chunks/chunk-53ZBETYR.js +16 -0
  60. package/dist/cli/chunks/{chunk-BHQ2DLJU.js → chunk-544KDWL4.js} +1 -1
  61. package/dist/cli/chunks/chunk-54RCGMLB.js +8 -0
  62. package/dist/cli/chunks/{chunk-TDZ6N43D.js → chunk-5AGXIZQ5.js} +2 -2
  63. package/dist/cli/chunks/{chunk-RKCN4B26.js → chunk-5M24X6W7.js} +2 -2
  64. package/dist/cli/chunks/{chunk-GG7PMTHD.js → chunk-5O5T4LEU.js} +1 -1
  65. package/dist/cli/chunks/{chunk-OWIZBZLN.js → chunk-5RFXX4IF.js} +2 -2
  66. package/dist/cli/chunks/{chunk-VQFV2IPV.js → chunk-62MLAQRJ.js} +1 -1
  67. package/dist/cli/chunks/{chunk-PCL5JRKN.js → chunk-6D6TGL2E.js} +2 -2
  68. package/dist/cli/chunks/{chunk-WBDWHHKP.js → chunk-6IHZDSDL.js} +2 -2
  69. package/dist/cli/chunks/{chunk-UOVCTK5L.js → chunk-6P3Y45QL.js} +2 -2
  70. package/dist/cli/chunks/{chunk-45223KK6.js → chunk-6TEVM3X3.js} +10 -10
  71. package/dist/cli/chunks/{chunk-K7WAI662.js → chunk-7XTUKKRA.js} +1 -1
  72. package/dist/cli/chunks/chunk-A3GDX6UF.js +2 -0
  73. package/dist/cli/chunks/{chunk-GN6OE3JT.js → chunk-A5YTKKNA.js} +1 -1
  74. package/dist/cli/chunks/{chunk-KR2TAAF6.js → chunk-ADNGZAT2.js} +1 -1
  75. package/dist/cli/chunks/{chunk-J7Q5TXFZ.js → chunk-AWQAE3SW.js} +2 -2
  76. package/dist/cli/chunks/{chunk-ZN35XSKF.js → chunk-AXDBQFR4.js} +2 -2
  77. package/dist/cli/chunks/{chunk-ND72UDVH.js → chunk-AXVD7O3F.js} +2 -2
  78. package/dist/cli/chunks/{chunk-SAEECT23.js → chunk-B52ULNYO.js} +2 -2
  79. package/dist/cli/chunks/chunk-B6S4FC7M.js +3 -0
  80. package/dist/cli/chunks/{chunk-Z7SKUC6P.js → chunk-BDVFSMOQ.js} +1 -1
  81. package/dist/cli/chunks/{chunk-CXCMATZ6.js → chunk-BGXXMX3Y.js} +2 -2
  82. package/dist/cli/chunks/{chunk-R3KBOQ3O.js → chunk-BKMQQY5T.js} +2 -2
  83. package/dist/cli/chunks/{chunk-SAZ4PJBR.js → chunk-BN2FROBQ.js} +2 -2
  84. package/dist/cli/chunks/{chunk-G2X3OLMN.js → chunk-BO6EQNOC.js} +2 -2
  85. package/dist/cli/chunks/{chunk-776K4ZLE.js → chunk-BOVAKCDC.js} +2 -2
  86. package/dist/cli/chunks/{chunk-QSQNXBD2.js → chunk-BSXKZDKO.js} +2 -2
  87. package/dist/cli/chunks/{chunk-MGZ6XZHU.js → chunk-C5QVJ5XQ.js} +1 -1
  88. package/dist/cli/chunks/{chunk-LOLSZG5J.js → chunk-CFQLLF3D.js} +2 -2
  89. package/dist/cli/chunks/{chunk-J6QRNQJF.js → chunk-DUCVLT3F.js} +7 -7
  90. package/dist/cli/chunks/{chunk-QTQDX4TZ.js → chunk-E4RMJCGA.js} +3 -3
  91. package/dist/cli/chunks/{chunk-MLMD3I75.js → chunk-EONDCWY4.js} +1 -1
  92. package/dist/cli/chunks/{chunk-7BSOO3CY.js → chunk-F4AGNKL2.js} +2 -2
  93. package/dist/cli/chunks/{chunk-IKB3M7OF.js → chunk-F6YD3BOW.js} +1 -1
  94. package/dist/cli/chunks/{chunk-LIF6UWHV.js → chunk-FQRS7WVA.js} +2 -2
  95. package/dist/cli/chunks/{chunk-QJSSUBO3.js → chunk-FT24SSDG.js} +2 -2
  96. package/dist/cli/chunks/chunk-FV4YNSAJ.js +5 -0
  97. package/dist/cli/chunks/{chunk-VITV7AEC.js → chunk-FVDM3X42.js} +2 -2
  98. package/dist/cli/chunks/{chunk-LN7NKE3N.js → chunk-FVH7TXWU.js} +2 -2
  99. package/dist/cli/chunks/{chunk-FBSBXCZS.js → chunk-FWR5QY37.js} +2 -2
  100. package/dist/cli/chunks/{chunk-X2DWHGCC.js → chunk-FYINK2B7.js} +2 -2
  101. package/dist/cli/chunks/{chunk-ECKHDHR2.js → chunk-GGISVPOZ.js} +2 -2
  102. package/dist/cli/chunks/{chunk-SRBCBVSI.js → chunk-GPIJIZJQ.js} +2 -2
  103. package/dist/cli/chunks/{chunk-YR5QBUHZ.js → chunk-GXEVOT5F.js} +2 -2
  104. package/dist/cli/chunks/{chunk-ZTP3DQ5M.js → chunk-GZ4VB5RI.js} +1 -1
  105. package/dist/cli/chunks/{chunk-HWQPMUSN.js → chunk-HBDSCYSK.js} +2 -2
  106. package/dist/cli/chunks/{chunk-XBTGEYED.js → chunk-HGG4HR7C.js} +2 -2
  107. package/dist/cli/chunks/{chunk-YD2C6EPN.js → chunk-HSCKWWO2.js} +2 -2
  108. package/dist/cli/chunks/{chunk-LOMT4UC2.js → chunk-HSQ3GUYJ.js} +2 -2
  109. package/dist/cli/chunks/{chunk-ZC3KDNJW.js → chunk-HZQBW5EM.js} +3 -3
  110. package/dist/cli/chunks/{chunk-SUAZ5Z47.js → chunk-IGIYANVT.js} +2 -2
  111. package/dist/cli/chunks/{chunk-IHQGNDMX.js → chunk-IPWMSXBF.js} +2 -2
  112. package/dist/cli/chunks/{chunk-6V6BD6PH.js → chunk-IWVNC7VY.js} +1 -1
  113. package/dist/cli/chunks/{chunk-M2YI5YUR.js → chunk-IZODXKZD.js} +2 -2
  114. package/dist/cli/chunks/{chunk-LG5PPJT7.js → chunk-J2MT2OJV.js} +1 -1
  115. package/dist/cli/chunks/{chunk-6LSZCEW2.js → chunk-JKIJVVSP.js} +1 -1
  116. package/dist/cli/chunks/{chunk-REY52O7J.js → chunk-JMRDT2XK.js} +1 -1
  117. package/dist/cli/chunks/{chunk-XEYFZLIT.js → chunk-JR2UMTKG.js} +1 -1
  118. package/dist/cli/chunks/{chunk-DJDVD6RM.js → chunk-K6CH4CFF.js} +2 -2
  119. package/dist/cli/chunks/{chunk-2PCEMDIX.js → chunk-K7KW5QB5.js} +78 -87
  120. package/dist/cli/chunks/{chunk-EPVPXHL7.js → chunk-KFCQP434.js} +2 -2
  121. package/dist/cli/chunks/{chunk-TWBZONKT.js → chunk-KH4T6STG.js} +2 -2
  122. package/dist/cli/chunks/{chunk-JI33PMPZ.js → chunk-KJBYZO57.js} +1 -1
  123. package/dist/cli/chunks/{chunk-PK34KJH7.js → chunk-KP4OKOKV.js} +2 -2
  124. package/dist/cli/chunks/chunk-L2MBKVSE.js +2 -0
  125. package/dist/cli/chunks/{chunk-JVWZAE2H.js → chunk-L3IPUIT3.js} +2 -2
  126. package/dist/cli/chunks/{chunk-KT2QCXO6.js → chunk-L7PSU2YN.js} +2 -2
  127. package/dist/cli/chunks/{chunk-HAQJFUAQ.js → chunk-LA3JPGQA.js} +2 -2
  128. package/dist/cli/chunks/{chunk-LV7UIK4Q.js → chunk-LC2QRN7V.js} +14 -13
  129. package/dist/cli/chunks/{chunk-KTORRIX3.js → chunk-LHY7TMTM.js} +2 -2
  130. package/dist/cli/chunks/{chunk-IJSROBM6.js → chunk-LLQ2UMF6.js} +3 -3
  131. package/dist/cli/chunks/{chunk-NKUHMA4T.js → chunk-LOJ7OO6W.js} +2 -2
  132. package/dist/cli/chunks/{chunk-OJIUIEI4.js → chunk-LPUSH3VF.js} +1 -1
  133. package/dist/cli/chunks/{chunk-WAOEQA3W.js → chunk-LSEC2BU7.js} +2 -2
  134. package/dist/cli/chunks/{chunk-YMUY3TES.js → chunk-LTGB7OIU.js} +2 -2
  135. package/dist/cli/chunks/{chunk-CVYPMGUM.js → chunk-LUG7YNVZ.js} +2 -2
  136. package/dist/cli/chunks/{chunk-YAJOBZE5.js → chunk-LWAFRYKE.js} +2 -2
  137. package/dist/cli/chunks/{chunk-ZP5AWQRO.js → chunk-M24ZAZ4U.js} +2 -2
  138. package/dist/cli/chunks/{chunk-HFZD5KLR.js → chunk-MKRKRXTX.js} +1 -1
  139. package/dist/cli/chunks/{chunk-4YM45Z5B.js → chunk-MNNLONAD.js} +1 -1
  140. package/dist/cli/chunks/{chunk-CMN7PU2H.js → chunk-MQM37KAR.js} +2 -2
  141. package/dist/cli/chunks/{chunk-COTQ44YO.js → chunk-MSX2OHYT.js} +2 -2
  142. package/dist/cli/chunks/{chunk-4UKTIQDT.js → chunk-MVYQRVLP.js} +2 -2
  143. package/dist/cli/chunks/{chunk-HRUHHHVR.js → chunk-MZC5WM2P.js} +2 -2
  144. package/dist/cli/chunks/{chunk-YKRLUTK7.js → chunk-MZRBNBB3.js} +2 -2
  145. package/dist/cli/chunks/{chunk-XEMCHGAJ.js → chunk-N3KQU4UC.js} +2 -2
  146. package/dist/cli/chunks/{chunk-DS5IFRY6.js → chunk-NKU3FFM4.js} +2 -2
  147. package/dist/cli/chunks/chunk-O5EWFR76.js +2 -0
  148. package/dist/cli/chunks/{chunk-J3QFJI2Y.js → chunk-O5RDHD5T.js} +2 -2
  149. package/dist/cli/chunks/chunk-O6UWIXME.js +3 -0
  150. package/dist/cli/chunks/{chunk-Q6F3DYZN.js → chunk-OA4EQDC4.js} +2 -2
  151. package/dist/cli/chunks/{chunk-NQFDJ6BT.js → chunk-OBCXCRXK.js} +1 -1
  152. package/dist/cli/chunks/{chunk-S3TBOKAZ.js → chunk-OHU5P25N.js} +4 -4
  153. package/dist/cli/chunks/{chunk-DNVRTJKB.js → chunk-OOSV2RIA.js} +2 -2
  154. package/dist/cli/chunks/{chunk-NZJVDOUN.js → chunk-OW23N2Y5.js} +2 -2
  155. package/dist/cli/chunks/{chunk-ZWUF27P4.js → chunk-OXOO3YDL.js} +2 -2
  156. package/dist/cli/chunks/{chunk-4L6WX5KC.js → chunk-OYGKSSSI.js} +1 -1
  157. package/dist/cli/chunks/{chunk-DCDSN67A.js → chunk-PGO46IIW.js} +1 -1
  158. package/dist/cli/chunks/{chunk-C7QLLMYI.js → chunk-PZOYQHWS.js} +1 -1
  159. package/dist/cli/chunks/{chunk-BKHEQIRZ.js → chunk-Q2BZSG7Z.js} +2 -2
  160. package/dist/cli/chunks/{chunk-5FSPELOG.js → chunk-Q7V722K5.js} +2 -2
  161. package/dist/cli/chunks/{chunk-2EQK7B5L.js → chunk-QZU6M5IO.js} +2 -2
  162. package/dist/cli/chunks/{chunk-HVT7RMGV.js → chunk-R55Y76SJ.js} +1 -1
  163. package/dist/cli/chunks/{chunk-POPSZDI2.js → chunk-RMEQYJPU.js} +4 -4
  164. package/dist/cli/chunks/{chunk-H2LHWZRE.js → chunk-RTYXFXTI.js} +2 -2
  165. package/dist/cli/chunks/{chunk-QN7HP2UW.js → chunk-SJF3O4FX.js} +236 -236
  166. package/dist/cli/chunks/{chunk-2YWYW7NU.js → chunk-SOUS7Z2H.js} +2 -2
  167. package/dist/cli/chunks/{chunk-U5SMBJ6F.js → chunk-SRVNR3R3.js} +2 -2
  168. package/dist/cli/chunks/{chunk-ZAQMRFBB.js → chunk-SU3SXMVG.js} +2 -2
  169. package/dist/cli/chunks/chunk-SWGPLXWW.js +32 -0
  170. package/dist/cli/chunks/{chunk-S3DT5TPR.js → chunk-TRB3EVH3.js} +2 -2
  171. package/dist/cli/chunks/{chunk-IJZFJPHS.js → chunk-TVBDUMKT.js} +2 -2
  172. package/dist/cli/chunks/{chunk-7SNSI4VY.js → chunk-TWTXPSFU.js} +1 -1
  173. package/dist/cli/chunks/{chunk-ORQ2YBRR.js → chunk-ULYUVUL2.js} +2 -2
  174. package/dist/cli/chunks/{chunk-MVVVGQJ6.js → chunk-UNTBVJ5X.js} +2 -2
  175. package/dist/cli/chunks/{chunk-5WATBVU6.js → chunk-UQAA4PHU.js} +2 -2
  176. package/dist/cli/chunks/{chunk-5WYZVSL2.js → chunk-UWSJVKTE.js} +1 -1
  177. package/dist/cli/chunks/{chunk-JHKKIJT2.js → chunk-V2LJ54KP.js} +2 -2
  178. package/dist/cli/chunks/{chunk-2UUZCQSD.js → chunk-VCCTTKP3.js} +2 -2
  179. package/dist/cli/chunks/{chunk-P4OB6WDJ.js → chunk-VEGUYUVS.js} +1 -1
  180. package/dist/cli/chunks/{chunk-WX4PO65Q.js → chunk-VUQPVWNK.js} +2 -2
  181. package/dist/cli/chunks/{chunk-IQL6XRF5.js → chunk-VVGUE2T2.js} +2 -2
  182. package/dist/cli/chunks/{chunk-HZ5O7G2P.js → chunk-W5ASDHJQ.js} +1 -1
  183. package/dist/cli/chunks/{chunk-U4S74IIZ.js → chunk-WGXT5NWQ.js} +1 -1
  184. package/dist/cli/chunks/chunk-WJN3V7QB.js +7 -0
  185. package/dist/cli/chunks/chunk-WPCRQIIF.js +29 -0
  186. package/dist/cli/chunks/{chunk-AGCS5GSO.js → chunk-WQNLXUWA.js} +6 -6
  187. package/dist/cli/chunks/{chunk-LRY6UIRI.js → chunk-WZVRMKG2.js} +2 -2
  188. package/dist/cli/chunks/{chunk-KPIPVSIP.js → chunk-X27IUWTD.js} +2 -2
  189. package/dist/cli/chunks/{chunk-VDEKVIP5.js → chunk-X4B345B6.js} +2 -2
  190. package/dist/cli/chunks/{chunk-ERYADKMZ.js → chunk-X5I2Y4VO.js} +2 -2
  191. package/dist/cli/chunks/{chunk-EUWG2JG4.js → chunk-X7IQIFTS.js} +2 -2
  192. package/dist/cli/chunks/chunk-XJN3RKUD.js +3 -0
  193. package/dist/cli/chunks/{chunk-JRIJM4LE.js → chunk-XQMGXTHJ.js} +3 -3
  194. package/dist/cli/chunks/{chunk-VYPVU3JF.js → chunk-XTSAMB2Q.js} +2 -2
  195. package/dist/cli/chunks/{chunk-4NKZU2JZ.js → chunk-XZLIF4O2.js} +2 -2
  196. package/dist/cli/chunks/{chunk-XFTX3KLE.js → chunk-Y4LSEOZ3.js} +1 -1
  197. package/dist/cli/chunks/{chunk-ZVMSSCTH.js → chunk-Y4YN2RXR.js} +2 -2
  198. package/dist/cli/chunks/{chunk-X5QD76IU.js → chunk-YDI56L35.js} +2 -2
  199. package/dist/cli/chunks/{chunk-LRKLATSH.js → chunk-YFILS5D5.js} +2 -2
  200. package/dist/cli/chunks/{chunk-AVHYJ3XP.js → chunk-YISDX6WB.js} +2 -2
  201. package/dist/cli/chunks/{chunk-GPPTRKEM.js → chunk-YP2GHQSV.js} +2 -2
  202. package/dist/cli/chunks/{chunk-OO2M2QUV.js → chunk-YSX756AM.js} +4 -4
  203. package/dist/cli/chunks/{chunk-E7XIMOKW.js → chunk-YWANOASW.js} +2 -2
  204. package/dist/cli/chunks/{chunk-UHJVZEQA.js → chunk-YYIJLG7S.js} +2 -2
  205. package/dist/cli/chunks/{chunk-LCWEQRZI.js → chunk-Z7SD7LXM.js} +2 -2
  206. package/dist/cli/chunks/{chunk-TM75GAXG.js → chunk-ZDWD73UF.js} +2 -2
  207. package/dist/cli/chunks/{chunk-IRHXGCQR.js → chunk-ZFT3RLA4.js} +2 -2
  208. package/dist/cli/chunks/{chunk-ZGV7L4MW.js → chunk-ZNTHX5G3.js} +1 -1
  209. package/dist/cli/chunks/{chunk-D75GLKEL.js → chunk-ZS27R7VL.js} +2 -2
  210. package/dist/cli/chunks/{chunk-INI3Q4CN.js → chunk-ZXHHHR7K.js} +1 -1
  211. package/dist/cli/chunks/{ci-3RTTTS2D.js → ci-N5MOMNXH.js} +2 -2
  212. package/dist/cli/chunks/{ci-config-XRUR3I4K.js → ci-config-6L2ROQCW.js} +2 -2
  213. package/dist/cli/chunks/{ci-output-E5IAMU2U.js → ci-output-DSRBYEIK.js} +2 -2
  214. package/dist/cli/chunks/{circuit-breaker-SHR2P44P.js → circuit-breaker-VRPTNBL7.js} +2 -2
  215. package/dist/cli/chunks/{claude-flow-setup-ZDDILFMF.js → claude-flow-setup-4YFG3FU5.js} +2 -2
  216. package/dist/cli/chunks/client-I3L6BKRQ.js +2 -0
  217. package/dist/cli/chunks/{cline-installer-BGYVUM6G.js → cline-installer-7RGYJWGN.js} +2 -2
  218. package/dist/cli/chunks/{code-PJ4MC3MC.js → code-ISC6NW2K.js} +3 -3
  219. package/dist/cli/chunks/{code-index-extractor-IW2P22YG.js → code-index-extractor-2FID75YV.js} +2 -2
  220. package/dist/cli/chunks/{codex-installer-A7WZ6OGL.js → codex-installer-DZ7OG6KM.js} +2 -2
  221. package/dist/cli/chunks/{completions-KS23WD5J.js → completions-SM3LICWK.js} +2 -2
  222. package/dist/cli/chunks/{complexity-analyzer-Q7GLSR2E.js → complexity-analyzer-ZWD2CTAD.js} +2 -2
  223. package/dist/cli/chunks/{continuedev-installer-SK55BFW2.js → continuedev-installer-AGASOA26.js} +2 -2
  224. package/dist/cli/chunks/{copilot-installer-3N5J3WTM.js → copilot-installer-CLPZYTQC.js} +2 -2
  225. package/dist/cli/chunks/core-handlers-5EFOJ37H.js +2 -0
  226. package/dist/cli/chunks/{cost-tracker-NENVSO4A.js → cost-tracker-7PIGQYDV.js} +2 -2
  227. package/dist/cli/chunks/{coverage-5L7UQWDH.js → coverage-T2GEBTYS.js} +9 -9
  228. package/dist/cli/chunks/cross-domain-router-65WJAKVD.js +2 -0
  229. package/dist/cli/chunks/{cursor-installer-XXBO2ZE6.js → cursor-installer-KXBID4MB.js} +2 -2
  230. package/dist/cli/chunks/daemon-43MXIVH3.js +18 -0
  231. package/dist/cli/chunks/{daemon-CDCQU3LR.js → daemon-VAMJLQJ5.js} +3 -3
  232. package/dist/cli/chunks/{dag-attention-scheduler-HOMMF7FA.js → dag-attention-scheduler-UBP4VHTA.js} +2 -2
  233. package/dist/cli/chunks/{detect-FXCOUG6X.js → detect-QWFIQRKI.js} +2 -2
  234. package/dist/cli/chunks/{dist-node-GXQ7FMTY.js → dist-node-I2GICS3W.js} +2 -2
  235. package/dist/cli/chunks/{domain-handler-TI3JBAPC.js → domain-handler-Z66ISB2A.js} +2 -2
  236. package/dist/cli/chunks/{domain-plugins-R7LTUM32.js → domain-plugins-KHMD3FKT.js} +2 -2
  237. package/dist/cli/chunks/{domain-transfer-LBIAFHIQ.js → domain-transfer-JWGNNA6K.js} +2 -2
  238. package/dist/cli/chunks/dream-VQ2PZCVR.js +2 -0
  239. package/dist/cli/chunks/embed-and-insert-pattern-F5P5B6JX.js +3 -0
  240. package/dist/cli/chunks/{embedding-space-HHLWTBF5.js → embedding-space-KHG6TITM.js} +2 -2
  241. package/dist/cli/chunks/{eval-KDOZMAXJ.js → eval-43OHU7EI.js} +2 -2
  242. package/dist/cli/chunks/{experience-capture-middleware-X45PECQN.js → experience-capture-middleware-KXD47H6P.js} +3 -3
  243. package/dist/cli/chunks/{fast-paths-462V6UUB.js → fast-paths-6D75D5KD.js} +2 -2
  244. package/dist/cli/chunks/{feature-flags-NIRQ4YDM.js → feature-flags-IE35Y55N.js} +2 -2
  245. package/dist/cli/chunks/{feature-flags-G66OT3AS.js → feature-flags-OYYHY7LS.js} +2 -2
  246. package/dist/cli/chunks/file-discovery-LGBTY3ID.js +2 -0
  247. package/dist/cli/chunks/{fleet-PXWGB7CU.js → fleet-AGVJMFGD.js} +16 -16
  248. package/dist/cli/chunks/{gnn-wrapper-7MUW3M5M.js → gnn-wrapper-5L66A7LW.js} +2 -2
  249. package/dist/cli/chunks/{heartbeat-handler-5237PB35.js → heartbeat-handler-2BY6YYOT.js} +5 -5
  250. package/dist/cli/chunks/heartbeat-scheduler-3DU3M5AT.js +2 -0
  251. package/dist/cli/chunks/hnsw-adapter-N2IMSRPV.js +2 -0
  252. package/dist/cli/chunks/hnsw-index-DVU7TTJE.js +2 -0
  253. package/dist/cli/chunks/{hnsw-legacy-bridge-OSQPW7JP.js → hnsw-legacy-bridge-RYMWFNAH.js} +2 -2
  254. package/dist/cli/chunks/{hnswlib-node-GX6WG2GB.js → hnswlib-node-GG47HP2P.js} +2 -2
  255. package/dist/cli/chunks/{hooks-GUWHL7VC.js → hooks-FQNACS24.js} +10 -10
  256. package/dist/cli/chunks/hybrid-backend-AS2PNHOD.js +2 -0
  257. package/dist/cli/chunks/{hypergraph-engine-SRWLLCU3.js → hypergraph-engine-6BYNJQEP.js} +2 -2
  258. package/dist/cli/chunks/{hypergraph-handler-AVOPRHHO.js → hypergraph-handler-CYTAXZKJ.js} +3 -3
  259. package/dist/cli/chunks/impact-analyzer-Y4OONLFP.js +2 -0
  260. package/dist/cli/chunks/{init-guard-P4N6EVZS.js → init-guard-METTAV5O.js} +2 -2
  261. package/dist/cli/chunks/{init-handler-LRGWOJMD.js → init-handler-GFT74U5Y.js} +6 -6
  262. package/dist/cli/chunks/init-wizard-HLNUBJQN.js +2 -0
  263. package/dist/cli/chunks/kernel-XKFWCL7Y.js +2 -0
  264. package/dist/cli/chunks/{kilocode-installer-7R2EPOQ6.js → kilocode-installer-GZV2D3FF.js} +2 -2
  265. package/dist/cli/chunks/{kiro-installer-QNM7DPOB.js → kiro-installer-Q4ZXUFC7.js} +2 -2
  266. package/dist/cli/chunks/knowledge-graph-CNL77CSZ.js +2 -0
  267. package/dist/cli/chunks/{learning-7OIZBPXZ.js → learning-WA2QEYL7.js} +35 -34
  268. package/dist/cli/chunks/{llm-router-SIDXES23.js → llm-router-GRTCHWH7.js} +4 -4
  269. package/dist/cli/chunks/llm-router-service-UIYTYKP6.js +2 -0
  270. package/dist/cli/chunks/{load-EI2E2C3S.js → load-WXN3Q7Y5.js} +2 -2
  271. package/dist/cli/chunks/load-test-PXLW4A5B.js +2 -0
  272. package/dist/cli/chunks/{mcp-IOE5WOCS.js → mcp-LIQCPSJN.js} +2 -2
  273. package/dist/cli/chunks/{memory-DLYGJAP7.js → memory-OP6CHRFH.js} +5 -5
  274. package/dist/cli/chunks/memory-backend-XYOSO73Q.js +2 -0
  275. package/dist/cli/chunks/memory-handlers-PQFYVNVG.js +2 -0
  276. package/dist/cli/chunks/{multi-model-executor-WHH4YCHM.js → multi-model-executor-H54DEVRZ.js} +2 -2
  277. package/dist/cli/chunks/{opencode-installer-63FDZAMS.js → opencode-installer-BSQV6UAT.js} +2 -2
  278. package/dist/cli/chunks/{orchestrator-3LA776KK.js → orchestrator-TJDPQ4VL.js} +122 -35
  279. package/dist/cli/chunks/pattern-null-store-BKGTQFNF.js +2 -0
  280. package/dist/cli/chunks/{pattern-usage-recorder-NW54QUGI.js → pattern-usage-recorder-FOVS4M5L.js} +2 -2
  281. package/dist/cli/chunks/{pipeline-P3TYX6J6.js → pipeline-4AY2ZIC6.js} +2 -2
  282. package/dist/cli/chunks/{platform-FNA2WLI6.js → platform-FCSITYMR.js} +2 -2
  283. package/dist/cli/chunks/{plugin-NJS7BC2S.js → plugin-E56TV5S2.js} +2 -2
  284. package/dist/cli/chunks/{prime-radiant-advanced-wasm-NIAVL2OT.js → prime-radiant-advanced-wasm-ACOPC533.js} +2 -2
  285. package/dist/cli/chunks/project-root-MPX7CN2C.js +2 -0
  286. package/dist/cli/chunks/protocol-executor-CRQOCC4A.js +2 -0
  287. package/dist/cli/chunks/{protocol-handler-JU5C4JHY.js → protocol-handler-KRVXF4LS.js} +2 -2
  288. package/dist/cli/chunks/{prove-35VOSLYP.js → prove-KMFPSKGD.js} +2 -2
  289. package/dist/cli/chunks/qe-reasoning-bank-UEGQ3O7F.js +2 -0
  290. package/dist/cli/chunks/{quality-ET74X7HN.js → quality-6DBI3HLB.js} +2 -2
  291. package/dist/cli/chunks/{quality-gate-FEDQISNB.js → quality-gate-3ROZMEIL.js} +3 -3
  292. package/dist/cli/chunks/queen-coordinator-32574XSG.js +2 -0
  293. package/dist/cli/chunks/real-embeddings-MIGZNKK3.js +2 -0
  294. package/dist/cli/chunks/{ref-validation-DTBPYCEB.js → ref-validation-EYIP7DHW.js} +2 -2
  295. package/dist/cli/chunks/{roocode-installer-LYQEMR4J.js → roocode-installer-IGGZHR2Y.js} +2 -2
  296. package/dist/cli/chunks/router-CZJY5WX6.js +2 -0
  297. package/dist/cli/chunks/routing-feedback-RC3UBNFX.js +2 -0
  298. package/dist/cli/chunks/{routing-handler-DJOJFPII.js → routing-handler-BWNHBYDC.js} +2 -2
  299. package/dist/cli/chunks/{ruvector-commands-VXYGJDPW.js → ruvector-commands-PXIHF432.js} +2 -2
  300. package/dist/cli/chunks/rvf-dual-writer-OG7OV2AK.js +2 -0
  301. package/dist/cli/chunks/rvf-migration-adapter-THYMW7ZO.js +2 -0
  302. package/dist/cli/chunks/rvf-migration-coordinator-3H6CLFU7.js +2 -0
  303. package/dist/cli/chunks/rvf-native-adapter-6JQJIKKW.js +2 -0
  304. package/dist/cli/chunks/{rvf-store-integrity-GA2ZYOEG.js → rvf-store-integrity-CVB3NMSL.js} +2 -2
  305. package/dist/cli/chunks/safe-db-QFKCVTIJ.js +2 -0
  306. package/dist/cli/chunks/schedule-6JLVMMYB.js +2 -0
  307. package/dist/cli/chunks/scheduler-3MPZRMJD.js +2 -0
  308. package/dist/cli/chunks/{security-MM6YOECX.js → security-DCRGOTWU.js} +3 -3
  309. package/dist/cli/chunks/{shared-rvf-adapter-6AHPA3V5.js → shared-rvf-adapter-GKD74QUB.js} +2 -2
  310. package/dist/cli/chunks/{shared-rvf-dual-writer-EYAVY2GZ.js → shared-rvf-dual-writer-HVAAVEOH.js} +2 -2
  311. package/dist/cli/chunks/sqlite-persistence-LGTIKAEX.js +2 -0
  312. package/dist/cli/chunks/{standalone-memory-A3PLB4CZ.js → standalone-memory-O7O2U5N4.js} +2 -2
  313. package/dist/cli/chunks/{status-handler-OSSFAP4Z.js → status-handler-BQTPJJTL.js} +2 -2
  314. package/dist/cli/chunks/{structural-health-PGY5XUNO.js → structural-health-4H6J4OHK.js} +2 -2
  315. package/dist/cli/chunks/sync-DJ4TF6QX.js +2 -0
  316. package/dist/cli/chunks/{sync-CWEHYGNN.js → sync-WW5TAVYW.js} +2 -2
  317. package/dist/cli/chunks/{task-handler-LHMQ75W4.js → task-handler-HEM4IEOW.js} +2 -2
  318. package/dist/cli/chunks/{task-handlers-S2TX5FTR.js → task-handlers-JRA3NXIR.js} +3 -3
  319. package/dist/cli/chunks/{test-4EGZZ6NJ.js → test-772ZXVG2.js} +4 -4
  320. package/dist/cli/chunks/test-runner-process-XGF2U3NG.js +2 -0
  321. package/dist/cli/chunks/{test-scheduling-YJQHH3XE.js → test-scheduling-4TRB7LZ7.js} +3 -3
  322. package/dist/cli/chunks/token-bootstrap-CICBIJ7T.js +2 -0
  323. package/dist/cli/chunks/{token-usage-WPNOJR6H.js → token-usage-B7PEKE2G.js} +2 -2
  324. package/dist/cli/chunks/{transformers-4MRPXCPU.js → transformers-V7X7BDZX.js} +2 -2
  325. package/dist/cli/chunks/tree-sitter-wasm-parser-OXPFKFZS.js +2 -0
  326. package/dist/cli/chunks/{types-6P5FB4EB.js → types-AHHTUY3I.js} +2 -2
  327. package/dist/cli/chunks/unified-memory-GUR3IUI6.js +2 -0
  328. package/dist/cli/chunks/unified-memory-hnsw-NJP2F2RY.js +2 -0
  329. package/dist/cli/chunks/unified-persistence-NILBWXDP.js +2 -0
  330. package/dist/cli/chunks/{upgrade-4ICTN63Y.js → upgrade-DZ4DLUQ5.js} +2 -2
  331. package/dist/cli/chunks/{validate-HQF5GZ7L.js → validate-4DTLIDJE.js} +2 -2
  332. package/dist/cli/chunks/{validate-swarm-45JYG7VW.js → validate-swarm-A26UFVIS.js} +2 -2
  333. package/dist/cli/chunks/visual-security-YECYZ27X.js +2 -0
  334. package/dist/cli/chunks/{web-tree-sitter-UOTWZLNH.js → web-tree-sitter-F2C7QRYT.js} +2 -2
  335. package/dist/cli/chunks/{windsurf-installer-WDWSBXGN.js → windsurf-installer-OOBTDA6W.js} +2 -2
  336. package/dist/cli/chunks/{witness-chain-DOYMNPC7.js → witness-chain-KGFZJP32.js} +2 -2
  337. package/dist/cli/chunks/witness-chain-LYBXFLJB.js +2 -0
  338. package/dist/cli/chunks/witness-chain-repair-CNTXOGPN.js +2 -0
  339. package/dist/cli/chunks/{witness-chain-verifier-JB42X62J.js → witness-chain-verifier-OB7ZZOI3.js} +2 -2
  340. package/dist/cli/chunks/{witness-key-manager-LXXO6L2G.js → witness-key-manager-YCKGKGQI.js} +2 -2
  341. package/dist/cli/chunks/{workflow-6ARK47NF.js → workflow-PRERHWKY.js} +4 -4
  342. package/dist/cli/chunks/workflow-orchestrator-UIBGWCU3.js +2 -0
  343. package/dist/cli/chunks/wrappers-L4UY4V63.js +2 -0
  344. package/dist/cli/commands/coverage.js +4 -1
  345. package/dist/cli/commands/learning-prune.js +9 -1
  346. package/dist/cli/handlers/brain-handler.js +32 -2
  347. package/dist/cli/handlers/heartbeat-handler.js +3 -1
  348. package/dist/cli/utils/coverage-data.js +5 -1
  349. package/dist/cli/utils/coverage-verdict.d.ts +10 -2
  350. package/dist/cli/utils/coverage-verdict.js +23 -8
  351. package/dist/cli/utils/fleet-operation.js +9 -3
  352. package/dist/coordination/handlers/code-intelligence-handlers.js +17 -3
  353. package/dist/coordination/handlers/coverage-handlers.js +22 -9
  354. package/dist/coordination/handlers/coverage-target.d.ts +22 -2
  355. package/dist/coordination/handlers/coverage-target.js +45 -9
  356. package/dist/coordination/handlers/handler-utils.d.ts +19 -0
  357. package/dist/coordination/handlers/handler-utils.js +22 -8
  358. package/dist/coordination/protocols/code-intelligence-index.js +6 -3
  359. package/dist/coordination/protocols/learning-consolidation-archive.d.ts +6 -3
  360. package/dist/coordination/protocols/learning-consolidation-archive.js +4 -3
  361. package/dist/coordination/workflow-builtin.js +1 -0
  362. package/dist/domains/defect-intelligence/interfaces.d.ts +2 -0
  363. package/dist/domains/defect-intelligence/prediction-history.d.ts +15 -1
  364. package/dist/domains/defect-intelligence/prediction-history.js +63 -7
  365. package/dist/domains/defect-intelligence/services/defect-predictor.d.ts +1 -0
  366. package/dist/domains/defect-intelligence/services/defect-predictor.js +33 -13
  367. package/dist/domains/learning-optimization/coordinator.js +17 -10
  368. package/dist/domains/learning-optimization/domain-ranking.d.ts +26 -0
  369. package/dist/domains/learning-optimization/domain-ranking.js +28 -0
  370. package/dist/domains/learning-optimization/interfaces.d.ts +5 -0
  371. package/dist/domains/learning-optimization/pattern-archive.d.ts +55 -8
  372. package/dist/domains/learning-optimization/pattern-archive.js +90 -17
  373. package/dist/domains/learning-optimization/pattern-consolidation.js +18 -2
  374. package/dist/domains/learning-optimization/pattern-merge.d.ts +26 -0
  375. package/dist/domains/learning-optimization/pattern-merge.js +127 -0
  376. package/dist/domains/learning-optimization/services/learning-coordinator.js +21 -35
  377. package/dist/domains/test-execution/services/test-executor.js +6 -2
  378. package/dist/init/init-wizard-steps.js +3 -1
  379. package/dist/init/phases/07-hooks.js +97 -10
  380. package/dist/integrations/embeddings/cache/EmbeddingCache.js +1 -1
  381. package/dist/integrations/ruvector/brain-rvf-exporter.d.ts +16 -1
  382. package/dist/integrations/ruvector/brain-rvf-exporter.js +18 -32
  383. package/dist/integrations/ruvector/brain-rvf-richness.d.ts +75 -0
  384. package/dist/integrations/ruvector/brain-rvf-richness.js +127 -0
  385. package/dist/kernel/unified-memory-migration.js +1 -1
  386. package/dist/learning/checkpoint-shrink-ack.d.ts +25 -0
  387. package/dist/learning/checkpoint-shrink-ack.js +57 -0
  388. package/dist/learning/dream/dream-engine.d.ts +44 -3
  389. package/dist/learning/dream/dream-engine.js +6 -2
  390. package/dist/learning/embedder-identity-store.js +3 -1
  391. package/dist/learning/embedding-space-legacy-adoption.d.ts +53 -0
  392. package/dist/learning/embedding-space-legacy-adoption.js +115 -0
  393. package/dist/learning/embedding-space-registry.d.ts +15 -0
  394. package/dist/learning/embedding-space-registry.js +50 -11
  395. package/dist/learning/experience-capture.d.ts +3 -1
  396. package/dist/learning/experience-capture.js +15 -5
  397. package/dist/learning/experience-space-verification.d.ts +2 -0
  398. package/dist/learning/experience-space-verification.js +3 -2
  399. package/dist/learning/learning-retention.js +4 -0
  400. package/dist/learning/pattern-promotion.d.ts +7 -0
  401. package/dist/learning/pattern-promotion.js +64 -12
  402. package/dist/learning/real-embeddings.js +31 -7
  403. package/dist/learning/rvf-pattern-store.js +6 -1
  404. package/dist/mcp/bundle.js +570 -558
  405. package/dist/mcp/handlers/domain-handler-configs.d.ts +3 -0
  406. package/dist/mcp/handlers/domain-handler-configs.js +1 -0
  407. package/dist/mcp/handlers/heartbeat-handlers.d.ts +4 -2
  408. package/dist/mcp/tools/learning-optimization/optimize.d.ts +6 -1
  409. package/dist/mcp/tools/learning-optimization/optimize.js +20 -11
  410. package/dist/planning/goap-planner.js +4 -0
  411. package/dist/planning/plan-executor.js +6 -2
  412. package/dist/shared/git/git-analyzer.d.ts +30 -11
  413. package/dist/shared/git/git-analyzer.js +95 -48
  414. package/dist/shared/io/confined-read.d.ts +32 -7
  415. package/dist/shared/io/confined-read.js +58 -25
  416. package/dist/shared/io/file-reader.js +4 -1
  417. package/dist/shared/safe-db.d.ts +1 -1
  418. package/dist/shared/safe-db.js +20 -5
  419. package/dist/shared/sqlite-journal-mode.d.ts +39 -0
  420. package/dist/shared/sqlite-journal-mode.js +53 -0
  421. package/dist/sync/claude-flow-bridge.js +1 -1
  422. package/dist/sync/readers/sqlite-reader.js +3 -4
  423. package/dist/sync/writers/sqlite-writer.js +1 -1
  424. package/dist/workers/interfaces.d.ts +2 -2
  425. package/dist/workers/quality-daemon/git-watcher.d.ts +8 -0
  426. package/dist/workers/quality-daemon/git-watcher.js +54 -12
  427. package/dist/workers/quality-daemon/index.js +1 -1
  428. package/dist/workers/quality-daemon/priority-queue.d.ts +2 -1
  429. package/dist/workers/workers/defect-predictor.d.ts +9 -4
  430. package/dist/workers/workers/defect-predictor.js +98 -37
  431. package/package.json +1 -1
  432. package/dist/cli/chunks/adapter-OMILP6KH.js +0 -2
  433. package/dist/cli/chunks/aqe-learning-engine-OXH5CCOS.js +0 -2
  434. package/dist/cli/chunks/base-MAK2BLTG.js +0 -2
  435. package/dist/cli/chunks/brain-handler-GCQZFZGQ.js +0 -95
  436. package/dist/cli/chunks/browser-workflow-IR3VF2TL.js +0 -2
  437. package/dist/cli/chunks/chunk-4EJLHNER.js +0 -12
  438. package/dist/cli/chunks/chunk-A4BVDYIL.js +0 -2
  439. package/dist/cli/chunks/chunk-BE7ZHM34.js +0 -3
  440. package/dist/cli/chunks/chunk-DHKSPOUQ.js +0 -16
  441. package/dist/cli/chunks/chunk-FAQ24UHB.js +0 -29
  442. package/dist/cli/chunks/chunk-IOWEBPXJ.js +0 -5
  443. package/dist/cli/chunks/chunk-KB34MTFZ.js +0 -3
  444. package/dist/cli/chunks/chunk-MCXW3DKE.js +0 -8
  445. package/dist/cli/chunks/chunk-O7VJ3VKD.js +0 -2
  446. package/dist/cli/chunks/chunk-PIWGKGWP.js +0 -3
  447. package/dist/cli/chunks/chunk-SFITYZLV.js +0 -7
  448. package/dist/cli/chunks/chunk-TIVKDIF7.js +0 -2
  449. package/dist/cli/chunks/client-NO5FOWT4.js +0 -2
  450. package/dist/cli/chunks/core-handlers-JNAZPXE2.js +0 -2
  451. package/dist/cli/chunks/cross-domain-router-HEBM767Z.js +0 -2
  452. package/dist/cli/chunks/daemon-JEBJGEUK.js +0 -18
  453. package/dist/cli/chunks/dream-GQDCEJMS.js +0 -2
  454. package/dist/cli/chunks/embed-and-insert-pattern-33KLHDD5.js +0 -3
  455. package/dist/cli/chunks/file-discovery-33USPLB5.js +0 -2
  456. package/dist/cli/chunks/heartbeat-scheduler-LIXLC5IH.js +0 -2
  457. package/dist/cli/chunks/hnsw-adapter-62D5UH27.js +0 -2
  458. package/dist/cli/chunks/hnsw-index-GSGUMQQC.js +0 -2
  459. package/dist/cli/chunks/hybrid-backend-FRWP4BOY.js +0 -2
  460. package/dist/cli/chunks/impact-analyzer-7KF3AQXV.js +0 -2
  461. package/dist/cli/chunks/init-wizard-XWWAXY25.js +0 -2
  462. package/dist/cli/chunks/kernel-ZEJPNDBW.js +0 -2
  463. package/dist/cli/chunks/knowledge-graph-RRZQS7KY.js +0 -2
  464. package/dist/cli/chunks/llm-router-service-3OSW67LC.js +0 -2
  465. package/dist/cli/chunks/load-test-7TRIH2WJ.js +0 -2
  466. package/dist/cli/chunks/memory-backend-G7ZW6Q2B.js +0 -2
  467. package/dist/cli/chunks/memory-handlers-TPF3KCO5.js +0 -2
  468. package/dist/cli/chunks/pattern-null-store-OU3ZC3NR.js +0 -2
  469. package/dist/cli/chunks/project-root-GMOFJEKD.js +0 -2
  470. package/dist/cli/chunks/protocol-executor-AD345XRO.js +0 -2
  471. package/dist/cli/chunks/qe-reasoning-bank-NLTP26RC.js +0 -2
  472. package/dist/cli/chunks/queen-coordinator-2TB4FWS6.js +0 -2
  473. package/dist/cli/chunks/real-embeddings-II6CXTCI.js +0 -2
  474. package/dist/cli/chunks/router-PLM3MWME.js +0 -2
  475. package/dist/cli/chunks/routing-feedback-I7VOX2HU.js +0 -2
  476. package/dist/cli/chunks/rvf-dual-writer-GQZHFWO2.js +0 -2
  477. package/dist/cli/chunks/rvf-migration-adapter-3TVKBCAM.js +0 -2
  478. package/dist/cli/chunks/rvf-migration-coordinator-XUHKLMT6.js +0 -2
  479. package/dist/cli/chunks/rvf-native-adapter-5GUTYOWS.js +0 -2
  480. package/dist/cli/chunks/safe-db-RZPQGLGQ.js +0 -2
  481. package/dist/cli/chunks/schedule-G7JMQDUX.js +0 -2
  482. package/dist/cli/chunks/scheduler-4SEGPCKD.js +0 -2
  483. package/dist/cli/chunks/sqlite-persistence-IVE4SQXR.js +0 -2
  484. package/dist/cli/chunks/sync-PM6D7EQF.js +0 -2
  485. package/dist/cli/chunks/test-runner-process-72YACW6M.js +0 -2
  486. package/dist/cli/chunks/token-bootstrap-DJNETMVW.js +0 -2
  487. package/dist/cli/chunks/tree-sitter-wasm-parser-UVWSDXFR.js +0 -2
  488. package/dist/cli/chunks/unified-memory-2VMGSGQL.js +0 -2
  489. package/dist/cli/chunks/unified-memory-hnsw-3KULVD3N.js +0 -2
  490. package/dist/cli/chunks/unified-persistence-QCSLU2SV.js +0 -2
  491. package/dist/cli/chunks/visual-security-ZYP2KPH7.js +0 -2
  492. package/dist/cli/chunks/witness-chain-5QRT7EMX.js +0 -2
  493. package/dist/cli/chunks/witness-chain-repair-CUF2AFQB.js +0 -2
  494. package/dist/cli/chunks/workflow-orchestrator-RYDDWIXN.js +0 -2
  495. package/dist/cli/chunks/wrappers-CYQBOMPL.js +0 -2
@@ -0,0 +1,95 @@
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.15.18");process.exit(0)}
2
+ import{A as Pe,a as j,b as Q,c as Y,d as S,e as fe,f as K,g as Z,h as O,i as me,j as ue,k as ee,l as Ne,m as H,n as pe,o as $e,p as V,q as ne,r as te,s as re,t as oe,u as De,v as z,w as Te,x as Me,y as Fe}from"./chunk-WQNLXUWA.js";import{c as Ae}from"./chunk-O5RDHD5T.js";import{b as Be}from"./chunk-GPIJIZJQ.js";import{a as ke,d as de,e as Oe}from"./chunk-TWTXPSFU.js";import"./chunk-OW23N2Y5.js";import"./chunk-YDI56L35.js";import"./chunk-ZFT3RLA4.js";import"./chunk-MZRBNBB3.js";import"./chunk-MSX2OHYT.js";import"./chunk-SRVNR3R3.js";import"./chunk-Z7SD7LXM.js";import"./chunk-QZU6M5IO.js";import"./chunk-LWAFRYKE.js";import"./chunk-YFILS5D5.js";import{b as T,d as ce}from"./chunk-MQM37KAR.js";import"./chunk-M24ZAZ4U.js";import"./chunk-4QSQKFED.js";import"./chunk-O5EWFR76.js";import"./chunk-NKU3FFM4.js";import"./chunk-Q7V722K5.js";import"./chunk-KH4T6STG.js";import"./chunk-V2LJ54KP.js";import"./chunk-YP2GHQSV.js";import"./chunk-ZDWD73UF.js";import{a as xe,b as Ie,c as X,d as U,f as gn}from"./chunk-BSXKZDKO.js";import{d as q,e as yn}from"./chunk-WJN3V7QB.js";import"./chunk-L2MBKVSE.js";import"./chunk-AWQAE3SW.js";import"./chunk-244RKAEP.js";import"./chunk-BDVFSMOQ.js";import A from"path";import{readFileSync as ot}from"fs";import o from"chalk";yn();ce();import{existsSync as ie,mkdirSync as hn,writeFileSync as bn,readFileSync as ge}from"fs";import{join as F,resolve as ye}from"path";function ae(e,n){let r="shake256",t=JSON.stringify(n),a=e.prepare("SELECT * FROM witness_chain ORDER BY id DESC LIMIT 1").get(),i=a?de(r,Oe(a)):ke;e.prepare(`
3
+ INSERT INTO witness_chain
4
+ (prev_hash, action_hash, action_type, action_data, timestamp, actor, hash_algo)
5
+ VALUES (?, ?, 'BRAIN_IMPORT', ?, ?, 'brain-import', ?)
6
+ `).run(i,de(r,t),t,new Date().toISOString(),r)}var Rn={rl_q_values:"includeQValues",dream_insights:"includeDreamInsights",dream_cycles:"includeDreamInsights",witness_chain:"includeWitnessChain",vectors:"includeVectors"};function wn(e,n){let r=Rn[e.tableName];return!(r&&n[r]===!1)}var vn=1e4;function Sn(e,n,r,t){if(!wn(n,r))return pe(F(t,n.fileName),[]),{count:0,rows:[]};let[a,i]=n.domainColumn?H(r.domains,n.domainColumn):[void 0,[]];if(r.domains&&r.domains.length>0&&!n.domainColumn){let d=r.domains.map(()=>"?").join(","),c=`manifest_id IN (SELECT id FROM learning_evidence_manifests WHERE task_family IN (${d}))`;["learning_evidence_segments","learning_segment_edges","learning_evidence_admissions"].includes(n.tableName)?(a=c,i=[...r.domains]):["pattern_manifest_lineage","pattern_segment_lineage"].includes(n.tableName)&&(a=`${c} AND pattern_id IN (SELECT id FROM qe_patterns WHERE qe_domain IN (${d}))`,i=[...r.domains,...r.domains])}if(ue(e,n.tableName,a,i)>=vn){let d=n.blobColumns,c=d&&d.length>0?p=>K(p,d):void 0;return{count:$e(F(t,n.fileName),Ne(e,n.tableName,a,i),c)}}let s=ee(e,n.tableName,a,i);return n.blobColumns&&n.blobColumns.length>0&&(s=s.map(d=>K(d,n.blobColumns))),pe(F(t,n.fileName),s),{count:s.length,rows:s}}function Le(e){let n=[];for(let r of S){let t=F(e,r.fileName);ie(t)?n.push(O(ge(t,"utf-8"))):n.push(O(""))}return O(n.join(":"))}function qe(e,n,r="memory.db"){let t=ye(n.outputPath);ie(t)||hn(t,{recursive:!0});let a=0,i={},l=new Set;for(let m of S){let p=Sn(e,m,n,t);if(i[m.tableName]=p.count,a+=p.count,m.tableName==="qe_patterns"){if(p.rows)for(let b of p.rows)b.qe_domain&&l.add(b.qe_domain);else if(p.count>0){let[b,C]=m.domainColumn?H(n.domains,m.domainColumn):[void 0,[]],f=`SELECT DISTINCT qe_domain FROM qe_patterns ${b?`WHERE ${b} AND qe_domain IS NOT NULL`:"WHERE qe_domain IS NOT NULL"}`;try{let R=e.prepare(f).all(...C||[]);for(let y of R)l.add(y.qe_domain)}catch{}}}}let s=n.includeVectors!==!1?ue(e,"vectors"):0,d=Le(t),c={version:"3.0",exportedAt:new Date().toISOString(),sourceDb:r,stats:{patternCount:i.qe_patterns||0,vectorCount:s,qValueCount:i.rl_q_values||0,dreamInsightCount:i.dream_insights||0,witnessChainLength:i.witness_chain||0,totalRecords:a},domains:[...l].sort(),checksum:d,tableRecordCounts:i};return bn(F(t,"manifest.json"),JSON.stringify(c,null,2),"utf-8"),c}var _n=new Set(["qe_patterns","rl_q_values","dream_insights","witness_chain"]);function En(e){return e==="1.0"?S.filter(n=>_n.has(n.tableName)):e==="3.0"?S:(console.warn(`[brain-import] Unknown manifest version '${e}'. Attempting full import \u2014 some files may be missing.`),S)}function je(e,n,r){let t=ye(n),a=F(t,"manifest.json");if(!ie(a))throw new Error(`Manifest not found at ${a}`);let i=T(ge(a,"utf-8")),l=Le(t);if(l!==i.checksum)throw new Error(`Checksum mismatch: expected ${i.checksum}, got ${l}. The export may have been tampered with or corrupted.`);let s=En(i.version),d=0,c=0,m=0,p=()=>{let b=new Map,C=new Map,g=0;for(let f of s){let R=F(t,f.fileName),y=V(R,T);if(f.tableName==="witness_chain"){g+=y.length,c+=y.length;continue}f.blobColumns&&f.blobColumns.length>0&&(y=y.map(h=>Z(h,f.blobColumns)));for(let h of y){let N=ne(h,b),w;if(f.dedupColumns&&f.dedupColumns.length>0)w=re(e,f.tableName,N,f.dedupColumns,f.preserveId);else{let M=j[f.tableName]||"id",u=Y[f.tableName],x=Q[f.tableName];w=te(e,f.tableName,N,M,r.mergeStrategy,u,x,b,C,h.pattern_id)}d+=w.imported,c+=w.skipped,m+=w.conflicts}}ae(e,{sourceChecksum:i.checksum,sourceWitnessRows:g,importedRecords:d,skippedRecords:c,conflicts:m}),d+=1};return oe(e,r.dryRun??!1,p),{imported:d,skipped:c,conflicts:m}}function Ve(e){let n=ye(e),r=F(n,"manifest.json");if(!ie(r))throw new Error(`Manifest not found at ${r}`);return T(ge(r,"utf-8"))}gn();import{existsSync as W,readdirSync as Cn,renameSync as xn,statSync as In,unlinkSync as be,writeFileSync as Bn}from"fs";import{basename as kn,dirname as On,join as An,resolve as G}from"path";var Nn=128*1024*1024;var We=`substr(id, 1, ${z.length}) = ?`;function $n(e,n){if(e!=="vectors")return!1;let r=n.id;return typeof r=="string"&&r.startsWith(z)}var se=class extends Error{constructor(r,t,a,i){let l=Object.entries(a).filter(([,s])=>s>=1048576).sort((s,d)=>d[1]-s[1]).slice(0,3).map(([s,d])=>`${s} ${he(d)}`).join(", ");super(`RVF_KERNEL_TOO_LARGE: the brain kernel needs ${i?"":"at least "}${he(r)}, over the ${he(t)} limit of the native RVF writer.`+(l?` Largest tables: ${l}.`:"")+" Nothing was written. Use --format jsonl (no size limit), or reduce the largest learning tables first.");this.kernelBytes=r;this.limitBytes=t;this.tableBytes=a;this.complete=i;this.name="RvfKernelTooLargeError"}kernelBytes;limitBytes;tableBytes;complete;code="RVF_KERNEL_TOO_LARGE"};function he(e){return`${(e/(1024*1024)).toFixed(1)} MB`}var Ue=["",".idmap.json",".manifest.json"],Dn=[...Ue,".lock"];function Je(e){for(let n of Dn)try{let r=`${e}${n}`;W(r)&&be(r)}catch{}}function Tn(e){let n=On(e),r=`${kn(e)}.tmp.`,t;try{t=Cn(n)}catch{return}for(let a of t){if(!a.startsWith(r))continue;let i=Number.parseInt(a.slice(r.length).split(".")[0],10);if(!(!Number.isInteger(i)||i<=0)&&!(i!==process.pid&&Mn(i)))try{be(An(n,a))}catch{}}}function Mn(e){try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function Ke(e,n,r="memory.db"){if(!U())throw new Error("@ruvector/rvf-node is not available. Install it or use --format jsonl instead.");let t=G(n.outputPath),a=n.dimension??384,i=`${t}.tmp.${process.pid}`;Tn(t),Je(i);let l=n.maxKernelBytes??Nn,s={},d=[],c={},m={},p={},b=new Set,C=0,g=0;for(let u of S){let[x,$]=u.domainColumn?H(n.domains,u.domainColumn):[void 0,[]];if(u.tableName==="vectors"&&me(e,"vectors")){let{n:_}=e.prepare(`SELECT COUNT(*) AS n FROM vectors WHERE ${We}`).get(z);_>0&&(p.vectors=_),x=`(id IS NULL OR NOT ${We})`,$=[z]}let v=ee(e,u.tableName,x,$);if(n.domains&&n.domains.length>0){let _=new Set((s.learning_evidence_manifests??[]).map(I=>I.id)),P=new Set((s.qe_patterns??[]).map(I=>I.id));["learning_evidence_segments","learning_segment_edges","learning_evidence_admissions"].includes(u.tableName)?v=v.filter(I=>_.has(I.manifest_id)):u.tableName==="pattern_manifest_lineage"?v=v.filter(I=>{let D=I;return _.has(D.manifest_id)&&P.has(D.pattern_id)}):u.tableName==="pattern_segment_lineage"&&(v=v.filter(I=>{let D=I;return _.has(D.manifest_id)&&P.has(D.pattern_id)}))}if(u.tableName==="qe_patterns")for(let _ of v)_.qe_domain&&b.add(_.qe_domain);let L=fe[u.tableName];L&&L.length>0&&(v=v.map(_=>K(_,L))),(u.tableName==="qe_patterns"||u.tableName==="learning_evidence_manifests")&&(s[u.tableName]=v),m[u.tableName]=v.length,C+=v.length;let J=JSON.stringify(v);if(d.push([u.tableName,J]),c[u.tableName]=Buffer.byteLength(J),g+=c[u.tableName],g>l)throw new se(g,l,c,!1)}let f=new Date().toISOString(),R=[...b].sort(),y=`{"version":"3.0","format":"rvf","exportedAt":${JSON.stringify(f)},"sourceDb":${JSON.stringify(r)},"domains":${JSON.stringify(R)},"tables":{`+d.map(([u,x])=>`${JSON.stringify(u)}:${x}`).join(",")+"}}";d.length=0;let h=Buffer.from(y);if(h.length>l)throw new se(h.length,l,c,!0);let N=O(y),w=xe(i,a),M=!1;try{let u=0,x=[];if(me(e,"qe_pattern_embeddings")){let k=e.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(E=>E.name==="space_id"),B=e.prepare(`SELECT pattern_id, embedding, dimension, ${k?"space_id":"NULL"} AS space_id
7
+ FROM qe_pattern_embeddings`).all();for(let E of B)E.embedding&&E.dimension===a&&E.space_id&&x.push({id:`pe:${E.pattern_id}`,vector:new Float32Array(E.embedding.buffer,E.embedding.byteOffset,a),metadata:{tableName:"qe_pattern_embeddings",spaceId:E.space_id}})}x.length>0&&(u=w.ingest(x).accepted),w.embedKernel(h);let $=n.sign?w.sign(h)??void 0:void 0,v=$?n.signerKeyId??"default":void 0,L=w.fileId(),J=L?{fileId:L,parentId:w.parentId(),lineageDepth:w.lineageDepth()}:void 0,_=w.status(),P={version:"3.0",format:"rvf",exportedAt:f,sourceDb:r,stats:{patternCount:m.qe_patterns??0,embeddingCount:u,qValueCount:m.rl_q_values??0,dreamInsightCount:m.dream_insights??0,witnessChainLength:m.witness_chain??0,totalRecords:C,tableCounts:m,...Object.keys(p).length>0?{skippedCacheRows:p}:{}},domains:R,checksum:N,rvfStatus:{totalVectors:_.totalVectors,totalSegments:_.totalSegments,fileSizeBytes:_.fileSizeBytes},...$?{signature:$,signerKeyId:v}:{},...J?{lineage:J}:{}};if($)try{w.freeze()}catch{}Bn(`${i}.manifest.json`,JSON.stringify(P,null,2),"utf-8"),w.close(),M=!0;let I=n.compareWithPath?G(n.compareWithPath):t,D=n.allowOverwriteRicher===!0;if(n.shrinkAck!==void 0&&!D){let k=Pe(n.shrinkAck,S.map(({tableName:B})=>B),P.stats.tableCounts);n.onShrinkAck?.(k),D=k.honoured}if(W(I)&&!D){let k;try{k=ze(I,!0)}catch(B){if(Fn(I)||!Pn(B)){let E=B instanceof Error?B.message:String(B);throw new Te("RVF_MIRROR_INSPECTION_AMBIGUOUS",`the existing mirror is readable but its richness could not be established (${E}). Preserve/import it before retrying, or repeat with --force-overwrite-richer after preserving a backup.`)}}k&&Fe(S.map(({tableName:B})=>B),k.stats.tableCounts,P.stats.tableCounts,n.richnessPolicy)}for(let k of[...Ue].reverse()){let B=`${i}${k}`,E=`${t}${k}`;W(B)?xn(B,E):W(E)&&be(E)}return P}catch(u){if(!M)try{w.close()}catch{}throw Je(i),u}}function Fn(e){let n;try{return n=X(G(e)),!!n.extractKernel()?.image}catch{return!1}finally{try{n?.close()}catch{}}}function Pn(e){let n=e instanceof Error?e.message:String(e);return/ManifestNotFound|InvalidMagic|ChecksumMismatch|CorruptStore/i.test(n)}var Ln={patterns:"qe_patterns",qValues:"rl_q_values",dreamInsights:"dream_insights",witnessChain:"witness_chain"};function He(e,n,r){if(!U())throw new Error("@ruvector/rvf-node is not available. Install it or use JSONL format.");let t=G(n);if(!W(t))throw new Error(`RVF file not found: ${t}`);let a=r.dryRun?X(t):Ie(t);try{let i=a.verifyWitness();if(!i.valid&&(i.totalEntries>0||i.errors.length>0)){let g=i.errors.length>0?i.errors.join("; "):"unknown integrity error";throw new Error(`RVF witness verification failed: ${g}`)}let l=a.extractKernel();if(!l||!l.image)throw new Error("No brain data found in RVF file (missing kernel segment)");let s;try{s=JSON.parse(l.image.toString("utf-8"))}catch(g){throw new Error(`Failed to parse brain kernel data as JSON: ${g instanceof Error?g.message:g}`)}let d=0,c=0,m=0,p=0,b={};if(s.tables)Object.assign(b,s.tables);else for(let[g,f]of Object.entries(Ln)){let R=s[g];Array.isArray(R)&&(b[f]=R)}let C=()=>{let g=new Map,f=new Map,R=0;for(let y of S){let h=b[y.tableName];if(!h||!Array.isArray(h))continue;if(y.tableName==="witness_chain"){R+=h.length,c+=h.length;continue}let N=fe[y.tableName];N&&N.length>0&&(h=h.map(w=>Z(w,N)));for(let w of h){let M=ne(w,g),u;if(y.dedupColumns&&y.dedupColumns.length>0)u=re(e,y.tableName,M,y.dedupColumns,y.preserveId);else{let x=j[y.tableName]||"id",$=Y[y.tableName],v=Q[y.tableName];u=te(e,y.tableName,M,x,r.mergeStrategy,$,v,g,f,w.pattern_id)}if(u.imported)for(let x of N??[])M[x]instanceof Buffer&&p++;d+=u.imported,c+=u.skipped,m+=u.conflicts}}ae(e,{sourceChecksum:O(l.image.toString("utf-8")),sourceWitnessRows:R,importedRecords:d,skippedRecords:c,conflicts:m}),d+=1};if(oe(e,r.dryRun??!1,C),!r.dryRun&&m>0)try{a.compact()}catch{}return{imported:d,skipped:c,conflicts:m,embeddingsRestored:p}}finally{a.close()}}function le(e){return ze(e,!1)}function ze(e,n){if(!U())throw new Error("@ruvector/rvf-node is not available.");let r=G(e);if(!W(r))throw new Error(`RVF file not found: ${r}`);let t=X(r);try{let a=t.extractKernel();if(!a||!a.image)throw new Error("No brain data found in RVF file");let i=a.image.toString("utf-8"),l;try{l=JSON.parse(i)}catch(f){throw new Error(`Failed to parse brain kernel data as JSON: ${f instanceof Error?f.message:f}`)}let s=t.status(),d=In(r).size,c=l.tables,m=c?c.qe_patterns?.length??0:l.patterns?.length??0,p=c?c.rl_q_values?.length??0:l.qValues?.length??0,b=c?c.dream_insights?.length??0:l.dreamInsights?.length??0,C=c?c.witness_chain?.length??0:l.witnessChain?.length??0,g=c&&typeof c=="object"&&!Array.isArray(c)?Object.fromEntries(Object.entries(c).filter(f=>Array.isArray(f[1])).map(([f,R])=>[f,n?R.filter(y=>!$n(f,y)).length:R.length])):void 0;return{version:"3.0",format:"rvf",exportedAt:l.exportedAt??"unknown",sourceDb:l.sourceDb??"unknown",stats:{patternCount:m,embeddingCount:s.totalVectors,qValueCount:p,dreamInsightCount:b,witnessChainLength:C,...g?{tableCounts:g}:{}},domains:l.domains??[],checksum:O(i),rvfStatus:{totalVectors:s.totalVectors,totalSegments:s.totalSegments,fileSizeBytes:d}}}finally{t.close()}}function Re(){return U()}ce();import{existsSync as ve,readFileSync as qn,statSync as jn}from"fs";import{join as we,resolve as Ge}from"path";function Ze(e,n,r={}){let t=Ge(e),a=Ge(n),i=Xe(t),l=Xe(a),s=Qe(t,i),d=Qe(a,l),c=i==="jsonl"&&l==="jsonl",m=Jn({pathA:t,pathB:a,manifestA:s,manifestB:d,recordLevel:c,tableFilter:r.tableFilter,maxIdsPerBucket:r.maxIdsPerBucket??500}),p=new Set(s.domains),b=new Set(d.domains),C=s.domains.filter(h=>!b.has(h)),g=d.domains.filter(h=>!p.has(h)),f=s.checksum===d.checksum,R=s.version===d.version,y=f&&R&&m.every(h=>h.delta===0&&(h.added?.length??0)===0&&(h.removed?.length??0)===0&&(h.changed?.length??0)===0);return{pathA:t,pathB:a,formatA:i,formatB:l,manifestA:s,manifestB:d,checksumMatch:f,versionMatch:R,identical:y,recordLevel:c,tableDiffs:m,domainsOnlyInA:C,domainsOnlyInB:g}}function Xe(e){if(!ve(e))throw new Error(`Path not found: ${e}`);if(e.endsWith(".rvf"))return"rvf";if(jn(e).isFile())throw new Error(`Unsupported brain export: ${e} (expected a .rvf file or a JSONL directory)`);return"jsonl"}function Qe(e,n){return n==="rvf"?Wn(e):Vn(e)}function Vn(e){let n=we(e,"manifest.json");if(!ve(n))throw new Error(`Manifest not found at ${n}`);let r=T(qn(n,"utf-8"));return en(r,"jsonl")}function Wn(e){let n=le(e);return en(n,"rvf")}function en(e,n){return{format:n,version:e.version??"unknown",exportedAt:e.exportedAt??"unknown",sourceDb:e.sourceDb??"unknown",checksum:e.checksum??"",totalRecords:e.stats?.totalRecords??0,domains:e.domains??[],tableRecordCounts:e.tableRecordCounts??{}}}function Jn(e){let n=e.tableFilter?S.filter(t=>t.tableName===e.tableFilter):S;if(e.tableFilter&&n.length===0)throw new Error(`Unknown table: ${e.tableFilter}`);let r=[];for(let t of n){let a=e.manifestA.tableRecordCounts[t.tableName]??0,i=e.manifestB.tableRecordCounts[t.tableName]??0,l=i-a,s,d,c;if(e.recordLevel&&Un(t)){let m=Kn(we(e.pathA,t.fileName),we(e.pathB,t.fileName),t,e.maxIdsPerBucket);s=m.added,d=m.removed,c=m.changed}r.push({tableName:t.tableName,countA:a,countB:i,delta:l,...s!==void 0?{added:s}:{},...d!==void 0?{removed:d}:{},...c!==void 0?{changed:c}:{}})}return r}function Un(e){return!0}function Kn(e,n,r,t){let a=Ye(e,r),i=Ye(n,r),l=[],s=[],d=[];for(let[c,m]of a){let p=i.get(c);if(p===void 0)s.length<t&&s.push(c);else if(p!==m){if(r.dedupColumns&&r.dedupColumns.length>0)continue;d.length<t&&d.push(c)}}for(let c of i.keys())a.has(c)||l.length<t&&l.push(c);return l.sort(),s.sort(),d.sort(),{added:l,removed:s,changed:d}}function Ye(e,n){let r=new Map;if(!ve(e))return r;let t=V(e,T);for(let a of t){let i=Hn(a,n);if(i===void 0)continue;let l=zn(a);r.set(i,Gn(l))}return r}function Hn(e,n){if(n.dedupColumns&&n.dedupColumns.length>0){let a=[];for(let i of n.dedupColumns){let l=e[i];if(l==null)return;a.push(String(l))}return a.join("")}let r=j[n.tableName]??"id",t=e[r];if(t!=null)return String(t)}function zn(e){let n=Object.keys(e).sort(),r={};for(let t of n)r[t]=e[t];return JSON.stringify(r)}function Gn(e){return O(e)}ce();import{existsSync as Se,statSync as Xn}from"fs";import{join as nn,resolve as Qn}from"path";var Yn=20,Zn="qe_patterns";function tn(e,n={}){let r=Qn(e);tt(r);let t=n.table??Zn,a=S.find(R=>R.tableName===t);if(!a)throw new Error(`Unknown table: ${t}`);let i=nn(r,a.fileName);if(!Se(i))throw new Error(`Table file not found: ${a.fileName} (expected in ${r}). Was this export generated with --format jsonl?`);let l=V(i,T),s=a.domainColumn,d=Math.max(1,n.limit??Yn),c=n.query?n.query.toLowerCase():void 0,m=n.domains&&n.domains.length>0?new Set(n.domains):void 0,p=n.since,b=n.until,C=n.patternType,g=0,f=[];for(let R of l)et(R,{domainColumn:s,domains:m,patternType:C,since:p,until:b,queryLower:c})&&(g++,f.length<d&&f.push(nt(R,a.tableName,s)));return{table:t,inputPath:r,totalScanned:l.length,totalMatched:g,limit:d,hits:f,truncated:g>d}}function et(e,n){if(n.domains){if(!n.domainColumn)return!1;let r=e[n.domainColumn];if(typeof r!="string"||!n.domains.has(r))return!1}if(n.patternType!==void 0&&e.pattern_type!==n.patternType)return!1;if(n.since!==void 0||n.until!==void 0){let r=rn(e);if(r===void 0||n.since!==void 0&&r<n.since||n.until!==void 0&&r>n.until)return!1}if(n.queryLower!==void 0){let r=typeof e.name=="string"?e.name.toLowerCase():"",t=typeof e.description=="string"?e.description.toLowerCase():"";if(!r.includes(n.queryLower)&&!t.includes(n.queryLower))return!1}return!0}function rn(e){for(let n of["updated_at","created_at","timestamp"]){let r=e[n];if(typeof r=="string"&&r.length>0)return r}}function nt(e,n,r){let t=(typeof e.id=="string"||typeof e.id=="number"?String(e.id):void 0)??`${n}:?`,a={name:typeof e.name=="string"?e.name:void 0,description:typeof e.description=="string"?e.description:void 0,domain:r&&typeof e[r]=="string"?e[r]:void 0,patternType:typeof e.pattern_type=="string"?e.pattern_type:void 0,confidence:typeof e.confidence=="number"?e.confidence:void 0,updatedAt:rn(e)};return{id:t,display:a,row:e}}function tt(e){if(!Se(e))throw new Error(`Path not found: ${e}`);if(Xn(e).isFile())throw e.endsWith(".rvf")?new Error("Brain search does not support RVF exports. Re-export with --format jsonl, or use `aqe brain info` for RVF summaries."):new Error(`Unsupported brain export: ${e} (expected a JSONL directory)`);let r=nn(e,"manifest.json");if(!Se(r))throw new Error(`Manifest not found at ${r}. Is this a brain export directory?`)}function on(e,n){if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_patterns'").get())return{created:0,skipped:0};e.exec(`
8
+ CREATE TEMP TABLE IF NOT EXISTS _covered_patterns (
9
+ pattern_id TEXT PRIMARY KEY
10
+ )
11
+ `),e.exec("DELETE FROM _covered_patterns"),e.exec(`
12
+ INSERT INTO _covered_patterns (pattern_id)
13
+ SELECT DISTINCT json_extract(action_data, '$.patternId')
14
+ FROM witness_chain
15
+ WHERE action_type = 'PATTERN_CREATE'
16
+ AND json_extract(action_data, '$.patternId') IS NOT NULL
17
+ `),e.exec(`
18
+ INSERT OR IGNORE INTO _covered_patterns (pattern_id)
19
+ SELECT DISTINCT json_extract(action_data, '$.pattern_id')
20
+ FROM witness_chain
21
+ WHERE action_type = 'PATTERN_CREATE'
22
+ AND json_extract(action_data, '$.pattern_id') IS NOT NULL
23
+ `);let t=e.prepare(`SELECT p.id, p.pattern_type, p.qe_domain, p.name, p.created_at
24
+ FROM qe_patterns p
25
+ LEFT JOIN _covered_patterns c ON p.id = c.pattern_id
26
+ WHERE c.pattern_id IS NULL
27
+ ORDER BY p.created_at ASC`).all(),i=e.prepare("SELECT COUNT(*) as count FROM qe_patterns").get().count-t.length,l=0;for(let s of t)n.append("PATTERN_CREATE",{patternId:s.id,patternType:s.pattern_type,qeDomain:s.qe_domain,name:s.name,originalCreatedAt:s.created_at,backfilled:!0},"system:backfill"),l++;return e.exec("DROP TABLE IF EXISTS _covered_patterns"),{created:l,skipped:i}}async function an(e,n){if(rt(n.format)==="rvf"){let a=q(e,{readonly:!0});try{return Ke(a,{outputPath:n.outputPath,domains:n.domains,allowOverwriteRicher:n.allowOverwriteRicher,compareWithPath:n.compareWithPath,richnessPolicy:n.richnessPolicy,shrinkAck:n.shrinkAck,onShrinkAck:n.onShrinkAck},e)}finally{a.close()}}let t=q(e,{readonly:!0});try{return qe(t,n,e)}finally{t.close()}}async function sn(e,n,r){if(mn(n,r.format)==="rvf"){let i=q(e);try{return He(i,n,{mergeStrategy:r.mergeStrategy,dryRun:r.dryRun})}finally{i.close()}}let a=q(e);try{return je(a,n,r)}finally{a.close()}}async function ln(e,n){return mn(e,n)==="rvf"?le(e):Ve(e)}async function cn(e,n,r={}){return Ze(e,n,r)}async function dn(e,n={}){return tn(e,n)}async function fn(e){let n=q(e);try{let r=Ae(n,Be());return await r.initialize(),on(n,r)}finally{n.close()}}function rt(e){if(e==="jsonl")return"jsonl";if(e==="rvf"){if(!Re())throw new Error("RVF format requested but @ruvector/rvf-node is not available on this platform. Use --format jsonl instead.");return"rvf"}return Re()?"rvf":"jsonl"}function mn(e,n){return n==="rvf"?"rvf":n==="jsonl"?"jsonl":e.endsWith(".rvf")?"rvf":"jsonl"}var at=new Set(["RVF_KERNEL_TOO_LARGE","RVF_MIRROR_RICHER","RVF_MIRROR_INSPECTION_AMBIGUOUS"]),Ce=class{name="brain";description="Export, import, and inspect QE brain state";cleanupAndExit;ensureInitialized;constructor(n,r){this.cleanupAndExit=n,this.ensureInitialized=r}register(n,r){let t=n.command("brain").description(this.description);t.command("export").description("Export brain state to a portable directory").requiredOption("-o, --output <path>","Output directory path").option("--format <format>","Export format: rvf (default) or jsonl","rvf").option("--db <path>","Source database path").option("--force-overwrite-richer","Allow replacing an existing RVF with fewer patterns",!1).option("--compare-with <path>","RVF to check richness against instead of the output path (rvf format)").option("--richness-policy <policy>","Richness guard: strict (default) or checkpoint (refuses only a collapse)","strict").option("--accept-shrink <path>","Deliberate-shrink acknowledgement to honour if it still applies (checkpoint hook)").action(async a=>{await this.executeExport(a)}),t.command("import").description("Import brain state from an export directory").requiredOption("-i, --input <path>","Path to brain export directory").option("--strategy <strategy>","Merge strategy","skip-conflicts").option("--dry-run","Preview import without writing",!1).option("--db <path>","Target database path").action(async a=>{await this.executeImport(a)}),t.command("info").description("Show manifest info for a brain export").requiredOption("-i, --input <path>","Path to brain export directory").action(async a=>{await this.executeInfo(a)}),t.command("witness-backfill").description("Create witness chain entries for patterns that predate the witness chain").option("--db <path>","Database path").action(async a=>{await this.executeWitnessBackfill(a)}),t.command("diff").description("Compare two brain exports (JSONL directory or .rvf file)").argument("<a>","Path to first brain export").argument("<b>","Path to second brain export").option("--table <name>","Restrict comparison to a single table").option("--verbose","Show the IDs of added/removed/changed records",!1).option("--json","Emit the diff as JSON to stdout",!1).action(async(a,i,l)=>{await this.executeDiff(a,i,l)}),t.command("search").description("Search a JSONL brain export with filters").requiredOption("-i, --input <path>","Path to brain export directory (JSONL)").option("--table <name>","Table to search (default: qe_patterns)").option("--domain <name...>","Restrict to one or more domains").option("--pattern-type <type>","Restrict to a specific pattern_type (qe_patterns only)").option("--since <iso>","Include rows with timestamp \u2265 <iso>").option("--until <iso>","Include rows with timestamp \u2264 <iso>").option("-q, --query <text>","Substring match across name + description (case-insensitive)").option("-l, --limit <n>","Maximum results to return","20").option("--json","Emit results as JSON to stdout",!1).action(async a=>{await this.executeSearch(a)})}async executeExport(n){try{if(console.log(o.blue(`
28
+ Exporting brain state (format: ${n.format})...
29
+ `)),!Me(n.richnessPolicy))throw new Error(`--richness-policy must be one of ${De.join(", ")}, got "${n.richnessPolicy}"`);let r=await _e(n.db),t=await an(r,{outputPath:A.resolve(n.output),format:n.format,allowOverwriteRicher:n.forceOverwriteRicher,compareWithPath:n.compareWith?A.resolve(n.compareWith):void 0,richnessPolicy:n.richnessPolicy,...n.acceptShrink?{shrinkAck:it(n.acceptShrink),onShrinkAck:i=>console.log(i.honoured?` SHRINK_ACK_HONOURED: ${i.producer}`:` SHRINK_ACK_IGNORED: ${i.reason}`)}:{}});if(console.log(o.green(" Export complete.")),console.log(` Format: ${o.cyan("format"in t?t.format??"jsonl":"jsonl")}`),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"embeddingCount"in t.stats?console.log(` Vectors: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`),"rvfStatus"in t){let i=t.rvfStatus;console.log(` RVF Size: ${o.cyan(un(i.fileSizeBytes))}`),console.log(` Segments: ${o.cyan(i.totalSegments)}`)}let a=t.stats.skippedCacheRows?.vectors;a&&console.log(` Skipped: ${o.gray(`${a} code-index vectors (regenerable: aqe code index <path>)`)}`),console.log(` Checksum: ${o.gray(t.checksum)}`),console.log(` Output: ${o.cyan(A.resolve(n.output))}`),console.log(""),await this.cleanupAndExit(0)}catch(r){at.has(String(r?.code))?console.error(o.red(`
30
+ Brain export failed:`),r.message):console.error(o.red(`
31
+ Brain export failed:`),r),await this.cleanupAndExit(1)}}async executeImport(n){try{n.dryRun?console.log(o.yellow(`
32
+ Dry-run mode \u2014 no data will be written.
33
+ `)):console.log(o.blue(`
34
+ Importing brain state...
35
+ `));let r=await _e(n.db),t=await sn(r,A.resolve(n.input),{mergeStrategy:n.strategy,dryRun:n.dryRun});console.log(o.green(" Import complete.")),console.log(` Imported: ${o.cyan(t.imported)}`),console.log(` Skipped: ${o.yellow(t.skipped)}`),console.log(` Conflicts: ${o.red(t.conflicts)}`),"embeddingsRestored"in t&&console.log(` Embeddings: ${o.cyan(t.embeddingsRestored)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
36
+ Brain import failed:`),r),await this.cleanupAndExit(1)}}async executeInfo(n){try{console.log(o.blue(`
37
+ Brain Export Info
38
+ `));let r=A.resolve(n.input),t=await ln(r),a="format"in t?t.format??"jsonl":"jsonl";if(console.log(` Version: ${o.cyan(t.version)}`),console.log(` Format: ${o.cyan(a)}`),console.log(` Exported: ${o.cyan(t.exportedAt)}`),console.log(` Source DB: ${o.cyan(t.sourceDb)}`),console.log(o.blue(`
39
+ Learning Data:`)),console.log(` Patterns: ${o.cyan(t.stats.patternCount)}`),"qValueCount"in t.stats&&console.log(` Q-Values: ${o.cyan(t.stats.qValueCount)}`),"dreamInsightCount"in t.stats){let s=t.stats.dreamInsightCount,c=("tableRecordCounts"in t?t.tableRecordCounts:void 0)?.dream_cycles,m=c!==void 0?` (${c} cycles)`:"";console.log(` Dream Insights: ${o.cyan(s)}${o.gray(m)}`)}"witnessChainLength"in t.stats&&console.log(` Witness Chain: ${o.cyan(t.stats.witnessChainLength)} entries`),"embeddingCount"in t.stats?console.log(` Embeddings: ${o.cyan(t.stats.embeddingCount)}`):"vectorCount"in t.stats&&console.log(` Vectors: ${o.cyan(t.stats.vectorCount)}`);let i="tableRecordCounts"in t?t.tableRecordCounts:void 0;if(i){let s=Object.entries(i).filter(([d,c])=>c>0&&!["qe_patterns","rl_q_values","dream_insights","dream_cycles","witness_chain","vectors","qe_pattern_embeddings"].includes(d));if(s.length>0)for(let[d,c]of s){let p=`${d.replace(/_/g," ").replace(/\b\w/g,b=>b.toUpperCase())}:`.padEnd(15);console.log(` ${p}${o.cyan(c)}`)}}let l="totalRecords"in t.stats?t.stats.totalRecords:void 0;if(l!==void 0&&(console.log(o.blue(`
40
+ Summary:`)),console.log(` Total Records: ${o.cyan(l)}`)),"domains"in t&&Array.isArray(t.domains)&&t.domains.length>0&&(l||console.log(o.blue(`
41
+ Summary:`)),console.log(` Domains: ${o.cyan(t.domains.join(", "))}`)),"rvfStatus"in t){let s=t.rvfStatus;console.log(o.blue(`
42
+ RVF Details:`)),console.log(` File Size: ${o.cyan(un(s.fileSizeBytes))}`),console.log(` Vectors: ${o.cyan(s.totalVectors)}`),console.log(` Segments: ${o.cyan(s.totalSegments)}`)}if("lineage"in t){let s=t.lineage;s&&(console.log(o.blue(`
43
+ Lineage:`)),console.log(` File ID: ${o.cyan(s.fileId)}`),console.log(` Parent ID: ${o.cyan(s.parentId??"none (root)")}`),console.log(` Depth: ${o.cyan(s.lineageDepth)}`))}if("signature"in t){let s=t.signature,d=t.signerKeyId;console.log(o.blue(`
44
+ Signature:`)),s?(console.log(` Status: ${o.green("Signed")}`),console.log(` Key ID: ${o.cyan(d??"unknown")}`),console.log(` Signature: ${o.gray(s.slice(0,32)+"...")}`)):console.log(` Status: ${o.yellow("Unsigned")}`)}console.log(`
45
+ Checksum: ${o.gray(t.checksum)}`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
46
+ Failed to read brain info:`),r),await this.cleanupAndExit(1)}}async executeDiff(n,r,t){try{let a=await cn(A.resolve(n),A.resolve(r),{tableFilter:t.table});if(t.json){process.stdout.write(JSON.stringify(a,null,2)+`
47
+ `),await this.cleanupAndExit(a.identical?0:1);return}ct(a,t.verbose),await this.cleanupAndExit(a.identical?0:1)}catch(a){console.error(o.red(`
48
+ Brain diff failed:`),a),await this.cleanupAndExit(2)}}async executeSearch(n){try{let r=st(n.limit),t=lt(n.domain),a=await dn(A.resolve(n.input),{table:n.table,domains:t,patternType:n.patternType,since:n.since,until:n.until,query:n.query,limit:r});if(n.json){process.stdout.write(JSON.stringify(a,null,2)+`
49
+ `),await this.cleanupAndExit(a.totalMatched>0?0:3);return}mt(a),await this.cleanupAndExit(a.totalMatched>0?0:3)}catch(r){console.error(o.red(`
50
+ Brain search failed:`),r),await this.cleanupAndExit(2)}}async executeWitnessBackfill(n){try{console.log(o.blue(`
51
+ Running witness chain backfill...
52
+ `));let r=await _e(n.db),t=await fn(r);console.log(o.green(" Backfill complete.")),console.log(` Created: ${o.cyan(t.created)} new witness entries`),console.log(` Skipped: ${o.cyan(t.skipped)} (already witnessed)`),console.log(""),await this.cleanupAndExit(0)}catch(r){console.error(o.red(`
53
+ Witness backfill failed:`),r),await this.cleanupAndExit(1)}}getHelp(){return`
54
+ Export, import, and inspect QE brain state.
55
+
56
+ Formats:
57
+ rvf \u2014 Single portable .rvf file (default, requires @ruvector/rvf-node)
58
+ jsonl \u2014 JSONL directory format (fallback when native not available)
59
+
60
+ Usage:
61
+ aqe brain export -o brain.rvf [--format rvf] [--db <path>]
62
+ aqe brain export -o ./brain-dir --format jsonl [--db <path>]
63
+ aqe brain import -i brain.rvf [--strategy skip-conflicts] [--dry-run] [--db <path>]
64
+ aqe brain info -i brain.rvf
65
+
66
+ Subcommands:
67
+ export Export brain state to a portable .rvf file or JSONL directory
68
+ import Import a brain export into the local database
69
+ info Show manifest metadata for an existing brain export
70
+ diff Compare two brain exports (manifest always; record-level for JSONL)
71
+ search Filtered search over a JSONL brain export
72
+
73
+ Examples:
74
+ aqe brain export -o .agentic-qe/brain.rvf
75
+ aqe brain export -o .agentic-qe/brain.rvf --format rvf
76
+ aqe brain export -o ./brain-export --format jsonl
77
+ aqe brain import -i .agentic-qe/brain.rvf --strategy latest-wins
78
+ aqe brain import -i .agentic-qe/brain.rvf --dry-run
79
+ aqe brain info -i .agentic-qe/brain.rvf
80
+ aqe brain diff ./brain-a ./brain-b --verbose
81
+ aqe brain search -i ./brain-export --query oauth --domain test-generation
82
+ aqe brain search -i ./brain-export --since 2026-03-01 --limit 50 --json
83
+ `}};function it(e){try{return JSON.parse(ot(A.resolve(e),"utf-8"))}catch{return null}}async function _e(e){if(e)return e;let{findProjectRoot:n}=await import("./unified-memory-GUR3IUI6.js");return A.join(n(),".agentic-qe","memory.db")}function un(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function st(e){let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<1?20:n}function lt(e){if(e===void 0)return;let n=Array.isArray(e)?e:[e],r=[];for(let t of n)for(let a of t.split(",")){let i=a.trim();i&&r.push(i)}return r.length>0?r:void 0}function ct(e,n){console.log(o.blue(`
84
+ Brain Diff
85
+ `)),console.log(` A: ${o.cyan(e.pathA)} (${e.formatA})`),console.log(` B: ${o.cyan(e.pathB)} (${e.formatB})`),console.log(` Versions: ${o.cyan(e.manifestA.version)} \u2192 ${o.cyan(e.manifestB.version)}`+(e.versionMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Checksums: ${o.gray(e.manifestA.checksum.slice(0,12))}\u2026 \u2192 ${o.gray(e.manifestB.checksum.slice(0,12))}\u2026`+(e.checksumMatch?o.gray(" (match)"):o.yellow(" (differ)"))),console.log(` Exported: ${o.gray(e.manifestA.exportedAt)} \u2192 ${o.gray(e.manifestB.exportedAt)}`),console.log(` Records: ${o.cyan(e.manifestA.totalRecords)} \u2192 ${o.cyan(e.manifestB.totalRecords)} `+pn(e.manifestB.totalRecords-e.manifestA.totalRecords)),(e.domainsOnlyInA.length>0||e.domainsOnlyInB.length>0)&&(console.log(o.blue(`
86
+ Domains:`)),e.domainsOnlyInA.length>0&&console.log(` Only in A: ${o.yellow(e.domainsOnlyInA.join(", "))}`),e.domainsOnlyInB.length>0&&console.log(` Only in B: ${o.yellow(e.domainsOnlyInB.join(", "))}`)),e.recordLevel||console.log(o.gray(`
87
+ Note: record-level diff is only available when both sides are JSONL exports.
88
+ Per-table counts shown below; re-export with --format jsonl for added/removed/changed IDs.`)),console.log(o.blue(`
89
+ Tables:`));let r=e.tableDiffs.filter(dt);if(r.length===0)console.log(o.gray(" (no differences)"));else for(let t of r)console.log(` ${t.tableName.padEnd(28)} ${o.cyan(String(t.countA).padStart(7))} \u2192 ${o.cyan(String(t.countB).padStart(7))} ${pn(t.delta)}`+ft(t,n)),n&&(t.added&&t.added.length>0&&Ee("added",t.added),t.removed&&t.removed.length>0&&Ee("removed",t.removed),t.changed&&t.changed.length>0&&Ee("changed",t.changed));console.log(""),e.identical?console.log(o.green(` Result: identical
90
+ `)):console.log(o.yellow(` Result: differences found
91
+ `))}function dt(e){return!!(e.delta!==0||e.added&&e.added.length>0||e.removed&&e.removed.length>0||e.changed&&e.changed.length>0)}function pn(e){return e===0?o.gray("(\xB10)"):e>0?o.green(`(+${e})`):o.red(`(${e})`)}function ft(e,n){let r=[];return e.added&&e.added.length>0&&r.push(o.green(`+${e.added.length}`)),e.removed&&e.removed.length>0&&r.push(o.red(`-${e.removed.length}`)),e.changed&&e.changed.length>0&&r.push(o.yellow(`~${e.changed.length}`)),r.length===0?"":n?" "+r.join(" "):" "+o.gray("[")+r.join(" ")+o.gray("]")}function Ee(e,n){let r=n.slice(0,10).join(", "),t=n.length>10?o.gray(` \u2026(+${n.length-10} more)`):"";console.log(` ${o.gray(e+":")} ${r}${t}`)}function mt(e){if(console.log(o.blue(`
92
+ Brain Search
93
+ `)),console.log(` Input: ${o.cyan(e.inputPath)}`),console.log(` Table: ${o.cyan(e.table)}`),console.log(` Scanned: ${o.cyan(e.totalScanned)} Matched: ${o.cyan(e.totalMatched)} Shown: ${o.cyan(e.hits.length)}`+(e.truncated?o.yellow(` (truncated to limit ${e.limit})`):"")),e.hits.length===0){console.log(o.yellow(`
94
+ No matching rows.
95
+ `));return}console.log("");for(let n of e.hits){let r=o.cyan(n.id)+(n.display.patternType?o.gray(` ${n.display.patternType}`):"")+(n.display.domain?o.gray(` [${n.display.domain}]`):"")+(n.display.confidence!==void 0?o.gray(` conf=${n.display.confidence.toFixed(2)}`):"");if(console.log(` ${r}`),n.display.name&&console.log(` ${o.bold(n.display.name)}`),n.display.description){let t=n.display.description.length>200?n.display.description.slice(0,200)+"\u2026":n.display.description;console.log(` ${o.gray(t)}`)}n.display.updatedAt&&console.log(` ${o.gray(n.display.updatedAt)}`),console.log("")}}function er(e,n){return new Ce(e,n)}export{Ce as BrainHandler,er as createBrainHandler};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import"./chunk-Z7SKUC6P.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
+ import"./chunk-BDVFSMOQ.js";var f=class{language;constructor(e="typescript"){this.language=e}enumerate(e,s){let r=[],n=e.split(`
3
3
  `),l=!1;for(let i=0;i<n.length;i++){let d=n[i],t=d.trim(),c=i+1,u=d.length-d.trimStart().length+1;if(l){t.includes("*/")&&(l=!1);continue}if(t.startsWith("/*")){l=!t.includes("*/");continue}if(t.startsWith("//"))continue;if(/^\s*if\s*\(/.test(d)&&(this.findMatchingElse(n,i)||r.push({file:s,line:c,column:u,language:this.language,construct:"if-without-else",triggerCondition:"when condition is false",currentHandling:"falls through \u2014 no else branch",suggestedGuard:"Add else branch or document why falsy path is safe",severity:"medium"})),/^\s*switch\s*\(/.test(d)){let a=this.extractBlock(n,i);if(a&&!a.includes("default:")&&!a.includes("default :")&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-no-default",triggerCondition:"when value matches no case",currentHandling:"falls through \u2014 no default case",suggestedGuard:"Add default case with error handling or exhaustive check",severity:"high"}),a){let g=a.match(/case\s+[^:]+:/g)||[],h=a.match(/\b(break|return|throw|continue)\b/g)||[];g.length>0&&h.length<g.length&&r.push({file:s,line:c,column:u,language:this.language,construct:"switch-missing-break",triggerCondition:"when case falls through to next case",currentHandling:"fall-through \u2014 may execute unintended cases",suggestedGuard:"Add break/return to each case or add explicit // falls through comment",severity:"medium"})}}if(/\bcatch\s*\(/.test(t)||/\bcatch\s*\{/.test(t)){let a=this.extractBlock(n,i);if(a!==null){let g=a.replace(/[{}]/g,"").trim();(g.length===0||/^\s*\/\//.test(g))&&r.push({file:s,line:c,column:u,language:this.language,construct:"try-empty-catch",triggerCondition:"when exception is thrown",currentHandling:"exception silently swallowed",suggestedGuard:"Log the error or rethrow with context",severity:"high"})}}if(/\btry\s*\{/.test(t)&&this.extractBlock(n,i)&&(n.slice(i,Math.min(i+30,n.length)).join(`
4
4
  `).includes("finally")||r.push({file:s,line:c,column:u,language:this.language,construct:"try-no-finally",triggerCondition:"when cleanup is needed regardless of success/failure",currentHandling:"no finally block \u2014 cleanup may be skipped on exception",suggestedGuard:"Add finally block for resource cleanup if applicable",severity:"low"})),t.includes("?.")){let a=t.match(/(\w+(?:\.\w+)*)\?\./g)||[];for(let g of a)if(!t.includes("??")&&!t.includes("|| ")&&!t.includes("if")){r.push({file:s,line:c,column:u,language:this.language,construct:"optional-chaining-null-path",triggerCondition:`when ${g.replace("?.","")} is null/undefined`,currentHandling:"returns undefined \u2014 may propagate",suggestedGuard:"Add ?? fallback or explicit null check",severity:"low"});break}}if(t.includes("??")&&!t.includes("?.")&&r.push({file:s,line:c,column:u,language:this.language,construct:"nullish-coalescing-fallback",triggerCondition:"when left side is null/undefined",currentHandling:"uses fallback value",suggestedGuard:"Verify fallback value is appropriate for all null cases",severity:"low"}),/\.\s*then\s*\(/.test(t)&&!t.includes(".catch")&&!t.includes("await")){let a=n.slice(i,Math.min(i+5,n.length)).join(" ");!a.includes(".catch")&&!a.includes("try")&&r.push({file:s,line:c,column:u,language:this.language,construct:"promise-no-catch",triggerCondition:"when promise rejects",currentHandling:"unhandled rejection \u2014 may crash process",suggestedGuard:"Add .catch() handler or use try/catch with await",severity:"high"})}let p=["map","filter","reduce","forEach","find","some","every","flatMap"];for(let a of p)if(new RegExp(`\\.${a}\\s*\\(`).test(t)){let h=n.slice(Math.max(0,i-3),i).join(" ");if(!h.includes(".length")&&!h.includes("if (")&&!h.includes("?.")){r.push({file:s,line:c,column:u,language:this.language,construct:"array-callback-empty",triggerCondition:`when array is empty before .${a}()`,currentHandling:a==="reduce"?"may throw without initial value":"returns empty result \u2014 may cause downstream issues",suggestedGuard:a==="reduce"?"Provide initial value or check array length":"Check array length or handle empty result",severity:a==="reduce"?"high":"low"});break}}/\|\|\s*['"`\d]/.test(t)&&!t.includes("??")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-or-falsy",triggerCondition:'when left side is falsy (0, "", false, null, undefined)',currentHandling:'uses fallback \u2014 may unintentionally override 0, "", or false',suggestedGuard:"Use ?? instead of || if only null/undefined should trigger fallback",severity:"medium"}),/&&\s*\w+\s*\(/.test(t)&&!t.includes("if")&&!t.includes("while")&&r.push({file:s,line:c,column:u,language:this.language,construct:"logical-and-short-circuit",triggerCondition:"when left side is falsy \u2014 right side never executes",currentHandling:"short-circuits \u2014 function call skipped silently",suggestedGuard:"Use explicit if-statement for clarity when side effects matter",severity:"low"}),(t.match(/\?/g)||[]).length>=2&&t.includes(":")&&r.push({file:s,line:c,column:u,language:this.language,construct:"ternary-complex",triggerCondition:"when nested ternary conditions interact",currentHandling:"nested ternary \u2014 hard to read and maintain",suggestedGuard:"Refactor to if/else or switch for readability",severity:"medium"}),(/\btypeof\s+\w+\s*===?\s*['"]/.test(t)||/\binstanceof\b/.test(t))&&!t.includes("else")&&!this.findMatchingElse(n,i)&&r.push({file:s,line:c,column:u,language:this.language,construct:"type-guard-unhandled",triggerCondition:"when value does not match the guarded type",currentHandling:"unguarded type path \u2014 may cause runtime type errors",suggestedGuard:"Add else branch or exhaustive type checking",severity:"medium"})}return r}findMatchingElse(e,s){let r={depth:0};for(let n=s;n<Math.min(s+30,e.length);n++){let l=e[n];for(let i of l)i==="{"&&r.depth++,i==="}"&&r.depth--;if(r.depth===0&&n>s){if((e[n+1]?.trim()||"").startsWith("else")||e[n].trim().endsWith("else")||e[n].trim().endsWith("else {")||e[n].includes("} else"))return!0;break}}return!1}extractBlock(e,s){let r=0,n=!1,l=[];for(let i=s;i<Math.min(s+50,e.length);i++){let d=e[i];for(let t of d)t==="{"&&(r++,n=!0),t==="}"&&r--;if(n&&(l.push(d),r===0))return l.join(`
5
5
  `)}return null}};function y(o,e,s){let r=Date.now(),n=s||(e.endsWith(".ts")||e.endsWith(".tsx")?"typescript":"javascript"),i=new f(n).enumerate(o,e);return{file:e,language:n,branches:i,totalConstructs:i.length,unhandledCount:i.length,duration:Date.now()-r}}function b(o){let e=[];if(e.push(`# Branch Enumeration Report: ${o.file}`),e.push(""),e.push(`**Language**: ${o.language} | **Branches**: ${o.unhandledCount} | **Duration**: ${o.duration}ms`),e.push(""),o.branches.length===0)return e.push("No unhandled branches detected."),e.join(`
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as m}from"./chunk-KR2TAAF6.js";import{c,e as y}from"./chunk-YKRLUTK7.js";import"./chunk-Z7SKUC6P.js";import{readFile as w,readdir as W}from"fs/promises";import{join as f,basename as b,dirname as v}from"path";import{fileURLToPath as E}from"url";import{parse as d}from"yaml";y();var x=E(import.meta.url),O=v(x),l=class{templatesDir;cache=new Map;constructor(t){this.templatesDir=t||f(O,"templates")}async load(t){if(this.cache.has(t))return this.cache.get(t);try{let e=f(this.templatesDir,`${t}.yaml`),n=await w(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${t}:
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.15.18");process.exit(0)}
2
+ import{a as m}from"./chunk-ADNGZAT2.js";import{c,e as y}from"./chunk-MZRBNBB3.js";import"./chunk-BDVFSMOQ.js";import{readFile as w,readdir as W}from"fs/promises";import{join as f,basename as b,dirname as v}from"path";import{fileURLToPath as E}from"url";import{parse as d}from"yaml";y();var x=E(import.meta.url),O=v(x),l=class{templatesDir;cache=new Map;constructor(t){this.templatesDir=t||f(O,"templates")}async load(t){if(this.cache.has(t))return this.cache.get(t);try{let e=f(this.templatesDir,`${t}.yaml`),n=await w(e,"utf-8"),o=d(n),i=await this.validate(o);if(!i.valid)throw new Error(`Invalid workflow template ${t}:
3
3
  ${i.errors.join(`
4
4
  `)}`);return this.cache.set(t,o),o}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${t}`):e}}async list(){try{return(await W(this.templatesDir)).filter(e=>e.endsWith(".yaml")||e.endsWith(".yml")).map(e=>b(e,e.endsWith(".yaml")?".yaml":".yml")).sort()}catch(t){if(t.code==="ENOENT")return[];throw t}}async validate(t){let e=[],n=[];if(t.name||e.push("Workflow must have a name"),t.version||e.push("Workflow must have a version"),t.description||n.push("Workflow should have a description"),Array.isArray(t.variables)?t.variables.forEach((o,i)=>{o.name||e.push(`Variable at index ${i} must have a name`),o.type||e.push(`Variable ${o.name} must have a type`),o.required===void 0&&n.push(`Variable ${o.name} should specify if it's required`)}):e.push("Workflow must have a variables array"),!Array.isArray(t.steps))e.push("Workflow must have a steps array");else if(t.steps.length===0)e.push("Workflow must have at least one step");else{t.steps.forEach((r,s)=>{r.name||e.push(`Step at index ${s} must have a name`),r.action||e.push(`Step ${r.name||s} must have an action`),(!r.config||typeof r.config!="object")&&e.push(`Step ${r.name||s} must have a config object`),r.assertions&&Array.isArray(r.assertions)&&r.assertions.forEach((u,p)=>{u.condition||e.push(`Assertion ${p} in step ${r.name||s} must have a condition`),u.message||n.push(`Assertion ${p} in step ${r.name||s} should have a message`)})});let o=t.steps.map(r=>r.name),i=o.filter((r,s)=>o.indexOf(r)!==s);i.length>0&&e.push(`Duplicate step names found: ${i.join(", ")}`)}return{valid:e.length===0,errors:e,warnings:n}}async createContext(t,e){let n=await this.load(t),o=n.variables.filter(r=>r.required&&!Object.hasOwn(e,r.name)).map(r=>r.name);if(o.length>0)throw new Error(`Missing required variables: ${o.join(", ")}`);let i={};return n.variables.forEach(r=>{Object.hasOwn(e,r.name)?c(i,r.name,e[r.name]):"default"in r&&c(i,r.name,r.default)}),{variables:i,results:new Map,metadata:{startTime:Date.now(),workflow:n.name,templateName:t}}}async getMetadata(t){try{let e=f(this.templatesDir,`${t}.yaml`),n=await w(e,"utf-8"),o=d(n);return{name:o.name,version:o.version,description:o.description}}catch(e){throw e.code==="ENOENT"?new Error(`Workflow template not found: ${t}`):e}}clearCache(){this.cache.clear()}async reload(t){return this.cache.delete(t),this.load(t)}},T=new l;function g(a,t){return a.replace(/\{\{([^}]+)\}\}/g,(e,n)=>{let i=n.trim().split("."),r=t;for(let s of i)if(r&&typeof r=="object"&&Object.hasOwn(r,s))r=r[s];else return e;return r!=null?String(r):e})}function A(a,t){let e={...t.variables,result:t.results.get("__last_result__")},n=g(a,e);return m(n,e,!1)}var h=["login-flow","oauth-flow","scraping-workflow","visual-regression","form-validation","navigation-flow","api-integration","performance-audit","accessibility-audit"],R={"login-flow":"Authentication testing workflow for login forms with credential validation","oauth-flow":"OAuth2/OIDC authentication testing workflow with provider integration","scraping-workflow":"Data extraction workflow for web scraping with pagination and structured output","visual-regression":"Screenshot comparison workflow for visual regression testing across breakpoints","form-validation":"Input validation testing workflow for form fields with error handling","navigation-flow":"Multi-page navigation workflow for testing user journeys and state persistence","api-integration":"Browser-API hybrid testing workflow for validating frontend-backend integration","performance-audit":"Lighthouse-style performance audit workflow with Core Web Vitals","accessibility-audit":"WCAG 2.1 Level AA compliance audit workflow with automated accessibility testing"},k={authentication:["login-flow","oauth-flow"],testing:["form-validation","navigation-flow","api-integration"],quality:["visual-regression","performance-audit","accessibility-audit"],automation:["scraping-workflow"]};function L(a){return k[a]}function N(a){return h.includes(a)}function B(){return h.map(a=>{let t=Object.entries(k).find(([e,n])=>n.includes(a))?.[0]||"other";return{name:a,description:R[a],category:t}})}export{k as WORKFLOW_CATEGORIES,R as WORKFLOW_DESCRIPTIONS,h as WORKFLOW_TEMPLATES,l as WorkflowLoader,T as defaultWorkflowLoader,A as evaluateCondition,B as getAllWorkflowTemplates,L as getWorkflowsByCategory,g as interpolateVariables,N as isValidWorkflowTemplate};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
+ import{a}from"./chunk-SU3SXMVG.js";import"./chunk-YISDX6WB.js";import"./chunk-X7IQIFTS.js";import"./chunk-YYIJLG7S.js";import"./chunk-4BIMTRRX.js";import"./chunk-OW23N2Y5.js";import"./chunk-YDI56L35.js";import"./chunk-ZFT3RLA4.js";import"./chunk-MZRBNBB3.js";import"./chunk-MSX2OHYT.js";import"./chunk-SRVNR3R3.js";import"./chunk-Z7SD7LXM.js";import"./chunk-QZU6M5IO.js";import"./chunk-LWAFRYKE.js";import"./chunk-YFILS5D5.js";import"./chunk-MQM37KAR.js";import"./chunk-M24ZAZ4U.js";import"./chunk-4QSQKFED.js";import"./chunk-O5EWFR76.js";import"./chunk-NKU3FFM4.js";import"./chunk-Q7V722K5.js";import"./chunk-KH4T6STG.js";import"./chunk-V2LJ54KP.js";import"./chunk-YP2GHQSV.js";import"./chunk-ZDWD73UF.js";import"./chunk-WJN3V7QB.js";import"./chunk-L2MBKVSE.js";import"./chunk-AWQAE3SW.js";import"./chunk-244RKAEP.js";import"./chunk-BDVFSMOQ.js";export{a as BrowserWorkflowTool};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{b as t,d as o}from"./chunk-Z7SKUC6P.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
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.15.18");process.exit(0)}
2
+ import{b as t,d as o}from"./chunk-BDVFSMOQ.js";var L={};o(L,{DotProductAttention:()=>d,FlashAttention:()=>u,HyperbolicAttention:()=>f,LinearAttention:()=>h,MoEAttention:()=>_,MultiHeadAttention:()=>A,RuvectorLayer:()=>a,SonaEngine:()=>b,TensorCompress:()=>c,default:()=>n,differentiableSearch:()=>l,getCompressionLevel:()=>p,hierarchicalForward:()=>s,init:()=>m,pipeline:()=>q});import{createRequire as r}from"module";var i,e,n,a,c,l,s,p,m,u,d,A,f,h,_,b,q,g=t(()=>{i=r(import.meta.url),e=i("better-sqlite3"),n=e,{RuvectorLayer:a,TensorCompress:c,differentiableSearch:l,hierarchicalForward:s,getCompressionLevel:p,init:m,FlashAttention:u,DotProductAttention:d,MultiHeadAttention:A,HyperbolicAttention:f,LinearAttention:h,MoEAttention:_,SonaEngine:b,pipeline:q}=e||{}});export{n as a,a as b,c,l as d,s as e,p as f,m as g,u as h,d as i,A as j,f as k,h as l,_ as m,b as n,q as o,L as p,g as q};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
2
  import{readFileSync as O,existsSync as x,readdirSync as A}from"fs";import{join as m,basename as w}from"path";function f(r){let e=[];if(!r||typeof r!="object")return e.push("Overlay must be a non-null object"),e;let n=r;if((!n.agent||typeof n.agent!="string")&&e.push('Overlay must have a string "agent" field'),n.replace!==void 0)if(typeof n.replace!="object"||n.replace===null)e.push('"replace" must be an object');else{let t=n.replace;t.description!==void 0&&typeof t.description!="string"&&e.push('"replace.description" must be a string'),t.domains!==void 0&&!Array.isArray(t.domains)&&e.push('"replace.domains" must be an array'),t.complexity!==void 0&&typeof t.complexity!="string"&&e.push('"replace.complexity" must be a string')}if(n.append!==void 0)if(typeof n.append!="object"||n.append===null)e.push('"append" must be an object');else{let t=n.append;t.instructions!==void 0&&typeof t.instructions!="string"&&e.push('"append.instructions" must be a string'),t.capabilities!==void 0&&!Array.isArray(t.capabilities)&&e.push('"append.capabilities" must be an array'),t.tags!==void 0&&!Array.isArray(t.tags)&&e.push('"append.tags" must be an array')}if(n.config!==void 0)if(typeof n.config!="object"||n.config===null)e.push('"config" must be an object');else{let t=n.config;t.minimumFindings!==void 0&&typeof t.minimumFindings!="number"&&e.push('"config.minimumFindings" must be a number'),t.maxParallelAgents!==void 0&&typeof t.maxParallelAgents!="number"&&e.push('"config.maxParallelAgents" must be a number'),t.preferredFrameworks!==void 0&&!Array.isArray(t.preferredFrameworks)&&e.push('"config.preferredFrameworks" must be an array'),t.needsContext!==void 0&&typeof t.needsContext!="boolean"&&e.push('"config.needsContext" must be a boolean')}return e}var v=".claude/agent-overrides",F=new Set(["__proto__","constructor","prototype"]);function $(r){let e={},n=p=>{let a=Object.hasOwn(e,p)?e[p]:void 0;if(a!==null&&typeof a=="object")return a;let l={};return e[p]=l,l},t=r.split(`
3
3
  `),i=null,s=null,o=null;for(let p of t){let a=p.replace(/\r$/,"");if(a.trim().startsWith("#")||a.trim()==="")continue;let l=a.length-a.trimStart().length,u=a.trim();if(u.startsWith("- ")){let b=u.slice(2).trim().replace(/^["']|["']$/g,"");s&&s.push(b);continue}s&&o&&(i&&(n(i)[o]=s),s=null,o=null);let g=u.match(/^(\w[\w.-]*)\s*:\s*(.*)$/);if(!g)continue;let[,c,h]=g,d=h.trim().replace(/^["']|["']$/g,"");if(F.has(c)){l===0&&(i=null);continue}l===0?d===""||d===void 0?(i=c,n(c)):(e[c]=y(d),i=null):l<=4&&i&&(d===""||d===void 0?(s=[],o=c):n(i)[c]=y(d))}return s&&o&&i&&(n(i)[o]=s),e}function y(r){if(r==="true")return!0;if(r==="false")return!1;if(r==="null")return null;let e=Number(r);return!isNaN(e)&&r!==""?e:r}function _(r){let e=m(r,v),n={overlays:[],warnings:[],errors:[]};if(!x(e))return n;let t;try{t=A(e).filter(i=>(i.endsWith(".yaml")||i.endsWith(".yml"))&&!i.startsWith("_"))}catch(i){return n.errors.push(`Failed to read overrides directory: ${i.message}`),n}for(let i of t){let s=m(e,i);try{let o=O(s,"utf-8"),p=$(o);if(!p.agent){let l=w(i).replace(/\.(override|customize)\.(yaml|yml)$/,"");p.agent=l}let a=f(p);if(a.length>0){n.warnings.push(`Overlay ${i} has validation issues: ${a.join("; ")}. Loading without overlay.`);continue}n.overlays.push(p)}catch(o){n.warnings.push(`Failed to parse overlay ${i}: ${o.message}. Agent loads without overlay.`)}}return n}function L(r,e){let n=r,t={agentName:e.agent,overlayFile:`${e.agent}.override.yaml`,replacedFields:[],appendedFields:[],configOverrides:[]};if(e.replace){if(e.replace.description){let i=/^(description:\s*).+$/m;i.test(n)&&(n=n.replace(i,`$1${e.replace.description}`),t.replacedFields.push("description"))}if(e.replace.domains){let i=/^(domain:\s*).+$/m;i.test(n)&&(n=n.replace(i,`$1${e.replace.domains.join(", ")}`),t.replacedFields.push("domains"))}if(e.replace.complexity){let i=/^(complexity:\s*).+$/m;i.test(n)&&(n=n.replace(i,`$1${e.replace.complexity}`),t.replacedFields.push("complexity"))}}if(e.append){if(e.append.instructions&&(n+=`
4
4
 
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as n}from"./chunk-EUWG2JG4.js";import{a as i}from"./chunk-UHJVZEQA.js";import{a as o,e as d}from"./chunk-LCWEQRZI.js";import{existsSync as m,statSync as s}from"node:fs";import{extname as l,join as c}from"node:path";d();var _=o.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function p(t,r=!0){let e;switch(t.type){case"memory":e=new i;break;case"sqlite":e=new n({sqlite:t.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:t.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(t.hybrid);break;default:throw new Error(`Unknown memory backend type: ${t.type}`)}return r&&await e.initialize(),{backend:e,type:t.type,initialized:r}}async function P(t=!0){let r=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH,a=e?e===":memory:"?e:m(e)?s(e).isDirectory()?c(e,"memory.db"):e:/\.(db|sqlite|sqlite3)$/i.test(l(e))?e:c(e,"memory.db"):y;return p({type:r,sqlite:{path:a,walMode:!0},agentdb:{path:a},hybrid:{enableFallback:!0,sqlite:{path:a}}},t)}export{p as a,P as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
+ import{a as n}from"./chunk-X7IQIFTS.js";import{a as i}from"./chunk-YYIJLG7S.js";import{a as o,e as d}from"./chunk-Z7SD7LXM.js";import{existsSync as m,statSync as s}from"node:fs";import{extname as l,join as c}from"node:path";d();var _=o.CLEANUP_INTERVAL_MS,y=".agentic-qe/memory.db";async function p(t,r=!0){let e;switch(t.type){case"memory":e=new i;break;case"sqlite":e=new n({sqlite:t.sqlite,enableFallback:!0});break;case"agentdb":e=new n({sqlite:{path:t.agentdb?.path??y},enableFallback:!0});break;case"hybrid":e=new n(t.hybrid);break;default:throw new Error(`Unknown memory backend type: ${t.type}`)}return r&&await e.initialize(),{backend:e,type:t.type,initialized:r}}async function P(t=!0){let r=process.env.AQE_MEMORY_BACKEND??"memory",e=process.env.AQE_MEMORY_PATH,a=e?e===":memory:"?e:m(e)?s(e).isDirectory()?c(e,"memory.db"):e:/\.(db|sqlite|sqlite3)$/i.test(l(e))?e:c(e,"memory.db"):y;return p({type:r,sqlite:{path:a,walMode:!0},agentdb:{path:a},hybrid:{enableFallback:!0,sqlite:{path:a}}},t)}export{p as a,P as b};
@@ -1,3 +1,3 @@
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.15.17");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
2
  import{readFileSync as R,existsSync as v,readdirSync as y}from"fs";import{join as S}from"path";var M=100*1024,b=/mcp__([a-z][a-z0-9-]*)__([a-z][a-z0-9_]*)/g,x=/^```/;function w(e,r){let n=e.length>M?e.slice(0,M):e,o=[],i=n.split(`
3
3
  `),a=!1;for(let s=0;s<i.length;s++){let p=i[s];if(x.test(p.trim())){a=!a;continue}let l,c=new RegExp(b.source,"g");for(;(l=c.exec(p))!==null;){let t=l[1],g=l[2],f=l[0],d=a?"code-block":"prose",u=d==="prose"?.9:.5;o.push({toolName:f,serverName:t,actionName:g,confidence:u,context:d,lineNumber:s+1})}}return o}function E(e){let r=new Map;for(let n of e)r.has(n.serverName)||r.set(n.serverName,[]),r.get(n.serverName).push(n);return r}function N(e){let r=[],n=[S(e,".claude","mcp.json"),S(e,".mcp.json")],o=process.env.HOME||process.env.USERPROFILE||"";o&&n.push(S(o,".claude","mcp.json"));for(let i of n)if(v(i))try{let a=R(i,"utf-8"),s=JSON.parse(a);s.mcpServers&&typeof s.mcpServers=="object"&&r.push(...Object.keys(s.mcpServers))}catch{}return[...new Set(r)]}function h(e,r,n){if(!v(e))return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Agent file not found: ${e}`],allSatisfied:!0};let o;try{o=R(e,"utf-8")}catch{return{agentName:r,references:[],requiredServers:[],availableServers:n,missingServers:[],warnings:[`Failed to read agent file: ${e}`],allSatisfied:!0}}let i=w(o,r),a=E(i),s=[...a.keys()],p=new Set(n),l=s.filter(t=>!p.has(t)),c=[];for(let t of l){let g=a.get(t)||[],f=Math.max(...g.map(m=>m.confidence)),d=g.length,u=[...new Set(g.map(m=>m.context))].join(", ");c.push(`[advisory] Agent "${r}" references MCP server "${t}" (${d} tool ref${d>1?"s":""}, confidence: ${f}, context: ${u}) but server is not configured. Agent may have reduced capabilities.`)}return{agentName:r,references:i,requiredServers:s,availableServers:n,missingServers:l,warnings:c,allSatisfied:l.length===0}}function C(e,r){let n=Date.now(),o=[],i=[],a=N(r);if(!v(e))return{agents:[],totalServersReferenced:0,globalMissingServers:[],agentsWithMissingDeps:[],warnings:[`Agents directory not found: ${e}`],durationMs:Date.now()-n};try{let c=y(e);for(let g of c){if(!g.endsWith(".md"))continue;let f=g.replace(".md",""),d=S(e,g),u=h(d,f,a);o.push(u),i.push(...u.warnings)}let t=S(e,"subagents");if(v(t)){let g=y(t);for(let f of g){if(!f.endsWith(".md"))continue;let d=f.replace(".md",""),u=S(t,f),m=h(u,d,a);o.push(m),i.push(...m.warnings)}}}catch(c){i.push(`Error scanning agents directory: ${c.message}`)}let s=new Set,p=new Set,l=[];for(let c of o){for(let t of c.requiredServers)s.add(t);for(let t of c.missingServers)p.add(t);c.missingServers.length>0&&l.push(c.agentName)}return{agents:o,totalServersReferenced:s.size,globalMissingServers:[...p],agentsWithMissingDeps:l,warnings:i,durationMs:Date.now()-n}}export{N as a,C as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{b as R,c as D,d as O,e as x,g as j,h as L,i as $,j as M,k as N,l as Q,m as U,n as z,o as F,p as W,q as G,r as V}from"./chunk-WAOEQA3W.js";import{b as _,d as P}from"./chunk-CMN7PU2H.js";import{a as T,b as q,c as ce,d as v,e as ue}from"./chunk-SFITYZLV.js";import{a as h,e as A}from"./chunk-J7Q5TXFZ.js";P();import{existsSync as y,mkdirSync as J,writeFileSync as b,readFileSync as C,copyFileSync as de}from"fs";import{join as u,dirname as pe}from"path";async function H(t,e){if(!e.hooks.claudeCode)return!1;let r=u(t,".claude");y(r)||J(r,{recursive:!0});let n=u(r,"settings.json"),s={};if(y(n))try{let m=C(n,"utf-8");s=_(m)}catch{s={}}let o={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=j(d,o);let l=s.env;s.env=L(l,$(e));let p=U(e,t);Q(s,p);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,x(n),b(n,JSON.stringify(s,null,2),"utf-8"),await me(t),!0}async function me(t){let e=u(t,".claude","hooks");y(e)||J(e,{recursive:!0});let r=u(e,"cross-phase-memory.yaml");if(y(r))return;let n=[u(pe(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),u(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),u(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let o of n)try{if(y(o)){de(o,r),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(r,`# Cross-Phase Memory Hooks Configuration
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
+ import{b as D,c as O,d as x,e as j,g as L,h as $,i as M,j as N,k as Q,l as U,m as z,n as F,o as W,p as G,q as V,r as J}from"./chunk-LSEC2BU7.js";import{b as _,d as R}from"./chunk-MQM37KAR.js";import{a as T,b as q,c as ue,d as v,e as pe}from"./chunk-WJN3V7QB.js";import{a as P,b as de}from"./chunk-L2MBKVSE.js";import{a as h,e as A}from"./chunk-AWQAE3SW.js";R();import{existsSync as y,mkdirSync as H,writeFileSync as b,readFileSync as C,copyFileSync as me}from"fs";import{join as u,dirname as ge}from"path";async function B(t,e){if(!e.hooks.claudeCode)return!1;let r=u(t,".claude");y(r)||H(r,{recursive:!0});let n=u(r,"settings.json"),s={};if(y(n))try{let m=C(n,"utf-8");s=_(m)}catch{s={}}let o={PreToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" guard --file "$TOOL_INPUT_file_path" --json',timeout:3,continueOnError:!0}]},{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-edit --file "$TOOL_INPUT_file_path" --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-command --command "$TOOL_INPUT_command" --json',timeout:3,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" pre-task --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],PostToolUse:[{matcher:"^(Write|Edit|MultiEdit)$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-edit --file "$TOOL_INPUT_file_path" --success --json',timeout:5,continueOnError:!0}]},{matcher:"^Bash$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-command --command "$TOOL_INPUT_command" --success true --json',timeout:5,continueOnError:!0}]},{matcher:"^Task$",hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-task --task-id "$TOOL_RESULT_agent_id" --agent "$TOOL_INPUT_subagent_type" --success true --description "$TOOL_INPUT_prompt" --json',timeout:5,continueOnError:!0}]}],UserPromptSubmit:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" route --json',timeout:5,continueOnError:!0}]}],SessionStart:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-start --session-id "$SESSION_ID" --json',timeout:10,continueOnError:!0}]}],Stop:[{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" session-end --save-state --json',timeout:5,continueOnError:!0}]},{hooks:[{type:"command",command:'node "${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/aqe-hook.cjs" post-route --success true --json',timeout:5,continueOnError:!0}]}]},d=s.hooks||{};s.hooks=L(d,o);let l=s.env;s.env=$(l,M(e));let p=z(e,t);U(s,p);let a=s.enabledMcpjsonServers||[];return a=a.filter(m=>m!=="aqe"),a.includes("agentic-qe")||a.push("agentic-qe"),s.enabledMcpjsonServers=a,j(n),b(n,JSON.stringify(s,null,2),"utf-8"),await he(t),!0}async function he(t){let e=u(t,".claude","hooks");y(e)||H(e,{recursive:!0});let r=u(e,"cross-phase-memory.yaml");if(y(r))return;let n=[u(ge(import.meta.url.replace("file://","")),"..","..","assets","hooks","cross-phase-memory.yaml"),u(process.cwd(),"assets","hooks","cross-phase-memory.yaml"),u(process.cwd(),"v3","assets","hooks","cross-phase-memory.yaml")];for(let o of n)try{if(y(o)){me(o,r),console.log(" \u2713 Cross-phase memory hooks installed");return}}catch{}b(r,`# Cross-Phase Memory Hooks Configuration
3
3
  # Generated by aqe init
4
4
  # See: https://github.com/proffesor-for-testing/agentic-qe/blob/main/docs/architecture/CROSS-PHASE-MEMORY-IMPLEMENTATION.md
5
5
 
@@ -23,9 +23,9 @@ routing:
23
23
  quality-criteria:
24
24
  - "qe-requirements-validator"
25
25
  - "qe-bdd-generator"
26
- `,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function B(t,e={}){if(!e.force&&z(t).enabled)return console.log(F(t)),N(u(t,".mcp.json")),!1;let r=u(t,".mcp.json"),n={};if(y(r))try{let o=C(r,"utf-8");n=_(o)}catch{n={}}n.mcpServers||(n.mcpServers={});let s=n.mcpServers;return M(s),s["agentic-qe"]={command:"aqe-mcp",args:[],env:{AQE_LEARNING_ENABLED:"true",AQE_VERBOSE:"false"},autoStart:!1},b(r,JSON.stringify(n,null,2),"utf-8"),!0}async function X(t,e){let r=u(t,"CLAUDE.md"),n=ge(e);if(y(r)){let s=C(r,"utf-8");if(s.includes("## Agentic QE v3"))return!0;let o=u(t,"CLAUDE.md.backup");b(o,s,"utf-8"),b(r,s+`
26
+ `,"utf-8"),console.log(" \u2713 Cross-phase memory hooks created (minimal config)")}async function X(t,e={}){if(!e.force&&F(t).enabled)return console.log(W(t)),Q(u(t,".mcp.json")),!1;let r=u(t,".mcp.json"),n={};if(y(r))try{let o=C(r,"utf-8");n=_(o)}catch{n={}}n.mcpServers||(n.mcpServers={});let s=n.mcpServers;return N(s),s["agentic-qe"]={command:"aqe-mcp",args:[],env:{AQE_LEARNING_ENABLED:"true",AQE_VERBOSE:"false"},autoStart:!1},b(r,JSON.stringify(n,null,2),"utf-8"),!0}async function K(t,e){let r=u(t,"CLAUDE.md"),n=fe(e);if(y(r)){let s=C(r,"utf-8");if(s.includes("## Agentic QE v3"))return!0;let o=u(t,"CLAUDE.md.backup");b(o,s,"utf-8"),b(r,s+`
27
27
 
28
- `+n,"utf-8")}else b(r,n,"utf-8");return!0}function ge(t){let e=t.domains.enabled.slice(0,6).join(", "),r=Math.max(0,t.domains.enabled.length-6);return`## Agentic QE v3
28
+ `+n,"utf-8")}else b(r,n,"utf-8");return!0}function fe(t){let e=t.domains.enabled.slice(0,6).join(", "),r=Math.max(0,t.domains.enabled.length-6);return`## Agentic QE v3
29
29
 
30
30
  This project uses **Agentic QE v3** - a Domain-Driven Quality Engineering platform with 12 bounded contexts, ReasoningBank learning, and HNSW vector search.
31
31
 
@@ -261,7 +261,7 @@ aqe init --auto
261
261
 
262
262
  ---
263
263
  *Generated by AQE v3 init - ${new Date().toISOString()}*
264
- `}A();import{existsSync as f,mkdirSync as k,writeFileSync as E}from"fs";import{join as i,dirname as he}from"path";A();ce();ue();P();async function K(t,e){let r=i(t,".agentic-qe","memory.db");try{let n=he(r);f(n)||k(n,{recursive:!0});let s=v(r);try{s.exec(`
264
+ `}A();import{existsSync as f,mkdirSync as k,writeFileSync as E}from"fs";import{join as i,dirname as ye}from"path";A();ue();pe();de();R();async function Y(t,e){let r=i(t,".agentic-qe","memory.db");try{let n=ye(r);f(n)||k(n,{recursive:!0});let s=v(r);try{s.exec(`
265
265
  CREATE TABLE IF NOT EXISTS kv_store (
266
266
  key TEXT NOT NULL,
267
267
  namespace TEXT NOT NULL,
@@ -276,12 +276,12 @@ aqe init --auto
276
276
  `).run("aqe_version",JSON.stringify(e),o),s.prepare(`
277
277
  INSERT OR REPLACE INTO kv_store (key, namespace, value, created_at)
278
278
  VALUES (?, '_system', ?, ?)
279
- `).run("init_timestamp",JSON.stringify(new Date().toISOString()),o),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(o){return s.close(),console.warn(` \u26A0 Could not write version: ${h(o)}`),!1}}catch(n){return console.warn(` \u26A0 Could not open memory.db: ${h(n)}`),!1}}async function Y(t){let e=null;try{e=(await import("./better-sqlite3-YO5X7ZJS.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
279
+ `).run("init_timestamp",JSON.stringify(new Date().toISOString()),o),s.close(),console.log(` \u2713 Version ${e} written to memory.db`),!0}catch(o){return s.close(),console.warn(` \u26A0 Could not write version: ${h(o)}`),!1}}catch(n){return console.warn(` \u26A0 Could not open memory.db: ${h(n)}`),!1}}async function Z(t){let e=null;try{e=(await import("./better-sqlite3-2MCFXW4J.js")).default}catch{throw new Error(`SQLite persistence REQUIRED but better-sqlite3 is not installed.
280
280
  Install it with: npm install better-sqlite3
281
281
  If you see native compilation errors, ensure build tools are installed:
282
282
  - macOS: xcode-select --install
283
283
  - Ubuntu/Debian: sudo apt-get install build-essential python3
284
- - Alpine: apk add build-base python3`)}let r=i(t,".agentic-qe");f(r)||k(r,{recursive:!0});let n=i(r,"memory.db");try{let s=new e(n);if(s.pragma("journal_mode = WAL"),s.pragma("busy_timeout = 5000"),s.exec(`
284
+ - Alpine: apk add build-base python3`)}let r=i(t,".agentic-qe");f(r)||k(r,{recursive:!0});let n=i(r,"memory.db");try{let s=new e(n);if(s.pragma("busy_timeout = 5000"),P(s,"WAL",5e3),s.exec(`
285
285
  CREATE TABLE IF NOT EXISTS kv_store (
286
286
  key TEXT NOT NULL,
287
287
  namespace TEXT NOT NULL,
@@ -299,18 +299,18 @@ If you see native compilation errors, ensure build tools are installed:
299
299
  VALUES (?, ?, ?)
300
300
  `).run("_init_test","_system",JSON.stringify({initialized:new Date().toISOString()})),s.close(),console.log(`\u2713 SQLite persistence initialized: ${n}`),!0}catch(s){throw q(s)?new Error(`SQLite persistence initialization FAILED: ${h(T(s))}`,{cause:s}):new Error(`SQLite persistence initialization FAILED: ${s}
301
301
  Database path: ${n}
302
- Ensure the directory is writable and has sufficient disk space.`)}}async function Z(t){let e=i(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let r=v(e),n=r.prepare(`
302
+ Ensure the directory is writable and has sufficient disk space.`)}}async function ee(t){let e=i(t,".agentic-qe","memory.db");if(!f(e))return!1;try{let r=v(e),n=r.prepare(`
303
303
  SELECT COUNT(*) as count FROM kv_store
304
304
  WHERE namespace = 'code-intelligence:kg'
305
- `).get();return r.close(),n.count>0}catch{return!1}}async function ee(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-RRZQS7KY.js"),{InMemoryBackend:r}=await import("./memory-backend-G7ZW6Q2B.js"),n=new r;await n.initialize();let s=new e(n,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,projectRoot:t}),{glob:o}=await import("tinyglobby"),d=await o(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"],expandDirectories:!1}),l=await s.index({paths:d.map(p=>i(t,p)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",h(e)),{status:"skipped",entries:0}}}async function te(t){let e=i(t,".agentic-qe","memory.db");try{let r=v(e),n=r.prepare(`
305
+ `).get();return r.close(),n.count>0}catch{return!1}}async function te(t){try{let{KnowledgeGraphService:e}=await import("./knowledge-graph-CNL77CSZ.js"),{InMemoryBackend:r}=await import("./memory-backend-XYOSO73Q.js"),n=new r;await n.initialize();let s=new e(n,{namespace:"code-intelligence:kg",enableVectorEmbeddings:!0,projectRoot:t}),{glob:o}=await import("tinyglobby"),d=await o(["**/*.ts","**/*.tsx","**/*.js","**/*.jsx","**/*.py"],{cwd:t,ignore:["node_modules/**","dist/**","coverage/**",".agentic-qe/**"],expandDirectories:!1}),l=await s.index({paths:d.map(p=>i(t,p)),incremental:!1,includeTests:!0});return s.destroy(),l.success?{status:"indexed",entries:l.value.nodesCreated+l.value.edgesCreated}:{status:"error",entries:0}}catch(e){return console.warn("Code intelligence scan warning:",h(e)),{status:"skipped",entries:0}}}async function ne(t){let e=i(t,".agentic-qe","memory.db");try{let r=v(e),n=r.prepare(`
306
306
  SELECT COUNT(*) as count FROM kv_store
307
307
  WHERE namespace LIKE 'code-intelligence:kg%'
308
- `).get();return r.close(),n.count}catch{return 0}}async function ne(t,e,r){if(!e.learning.enabled)return 0;let n=i(t,".agentic-qe","data");f(n)||k(n,{recursive:!0});let s=i(n,"hnsw");f(s)||k(s,{recursive:!0});let o=i(n,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:i(n,"memory.db"),hnswIndexPath:i(s,"index.bin"),initialized:new Date().toISOString()};E(o,JSON.stringify(d,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&r){let p=r,a=new Map;for(let g of p.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=i(n,"pretrained-index.json"),S={version:p.version,totalPatterns:p.statistics.totalPatterns,domains:Array.from(a.entries()).map(([g,c])=>({name:g,patternCount:c.length})),loadedAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8");for(let[g,c]of a){let w=i(n,"patterns",g);f(w)||k(w,{recursive:!0});let le=i(w,"patterns.json");E(le,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function re(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let r=i(t,".agentic-qe","workers");f(r)||k(r,{recursive:!0});let n={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)n[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let o=i(r,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:n,createdAt:new Date().toISOString(),daemonPid:null};E(o,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let m=i(r,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:i(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=i(r,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
308
+ `).get();return r.close(),n.count}catch{return 0}}async function re(t,e,r){if(!e.learning.enabled)return 0;let n=i(t,".agentic-qe","data");f(n)||k(n,{recursive:!0});let s=i(n,"hnsw");f(s)||k(s,{recursive:!0});let o=i(n,"learning-config.json"),d={embeddingModel:e.learning.embeddingModel,hnswConfig:e.learning.hnswConfig,qualityThreshold:e.learning.qualityThreshold,promotionThreshold:e.learning.promotionThreshold,databasePath:i(n,"memory.db"),hnswIndexPath:i(s,"index.bin"),initialized:new Date().toISOString()};E(o,JSON.stringify(d,null,2),"utf-8");let l=0;if(e.learning.pretrainedPatterns&&r){let p=r,a=new Map;for(let g of p.patterns){let c=g.domain||"general";a.has(c)||a.set(c,[]),a.get(c).push(g)}let m=i(n,"pretrained-index.json"),S={version:p.version,totalPatterns:p.statistics.totalPatterns,domains:Array.from(a.entries()).map(([g,c])=>({name:g,patternCount:c.length})),loadedAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8");for(let[g,c]of a){let w=i(n,"patterns",g);f(w)||k(w,{recursive:!0});let ce=i(w,"patterns.json");E(ce,JSON.stringify(c,null,2),"utf-8"),l+=c.length}return l}return 0}async function se(t,e){if(!e.workers.daemonAutoStart||e.workers.enabled.length===0)return 0;let r=i(t,".agentic-qe","workers");f(r)||k(r,{recursive:!0});let n={},s={"pattern-consolidator":6e4,"coverage-gap-scanner":3e5,"flaky-test-detector":6e5,"routing-accuracy-monitor":12e4};for(let a of e.workers.enabled)n[a]={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,lastRun:null,status:"pending"};let o=i(r,"registry.json"),d={version:e.version,maxConcurrent:e.workers.maxConcurrent,workers:n,createdAt:new Date().toISOString(),daemonPid:null};E(o,JSON.stringify(d,null,2),"utf-8");for(let a of e.workers.enabled){let m=i(r,`${a}.json`),S={name:a,enabled:!0,interval:e.workers.intervals[a]||s[a]||6e4,projectRoot:t,dataDir:i(t,".agentic-qe","data"),createdAt:new Date().toISOString()};E(m,JSON.stringify(S,null,2),"utf-8")}let l=i(r,"start-daemon.cjs");return E(l,`#!/usr/bin/env node
309
309
  // AQE v3 Worker Daemon Startup Script (cross-platform)
310
310
  // Generated by aqe init
311
311
 
312
312
  console.log("AQE v3 hooks work via CLI commands (no daemon required)");
313
313
  console.log("Use: npx aqe hooks session-start");
314
- `),e.workers.enabled.length}async function se(t,e){if(!e.skills.install)return 0;let n=await W({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return n.errors.length>0&&console.warn("Skills installation warnings:",n.errors),n.installed.length}async function ae(t){let r=await G({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return r.errors.length>0&&console.warn("Agents installation warnings:",r.errors),r.installed.length}async function oe(t,e,r){let s=await V({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:r}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:r},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function ie(t,e){if(!e)throw new Error("No configuration to save");let r=i(t,".agentic-qe");f(r)||k(r,{recursive:!0});let n=fe(e),s=i(r,"config.yaml");E(s,n,"utf-8")}function fe(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-5.5" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let r of t.workers.enabled)e.push(` - "${r}"`);e.push(" intervals:");for(let[r,n]of Object.entries(t.workers.intervals))e.push(` ${r}: ${n}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let r of t.autoTuning.parameters)e.push(` - "${r}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let r of t.domains.enabled)e.push(` - "${r}"`);e.push(" disabled:");for(let r of t.domains.disabled)e.push(` - "${r}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
315
- `)}var ye=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],I=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=D(e.projectRoot),this.configurator=O({minimal:e.minimal})}async initialize(){let e=Date.now();try{let r=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),n=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(r):this.applyWizardAnswers(r));await this.runStep("Persistence Database Setup",async()=>await Y(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await Z(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await ee(r.projectRoot);let w=await te(this.projectRoot);return console.log(` Using existing code intelligence index (${w} entries)`),{status:"existing",entries:w}}),o=await this.runStep("Learning System Setup",async()=>n.learning.enabled&&!this.options.skipPatterns?await ne(this.projectRoot,n,this.options.pretrainedLibrary):0),d=await this.runStep("Hooks Configuration",async()=>n.hooks.claudeCode?await H(this.projectRoot,n):!1),l=await this.runStep("MCP Configuration",async()=>this.options.noMcp?!1:await B(this.projectRoot,{force:this.options.withMcp})),p=await this.runStep("CLAUDE.md Generation",async()=>await X(this.projectRoot,n)),a=await this.runStep("Background Workers",async()=>n.workers.daemonAutoStart?await re(this.projectRoot,n):0),m=await this.runStep("Skills Installation",async()=>n.skills.install?await se(this.projectRoot,n):0),S=await this.runStep("Agents Installation",async()=>await ae(this.projectRoot)),g;if(this.options.withN8n){let c=await this.runStep("N8n Platform Installation",async()=>await oe(this.projectRoot,n,this.options.n8nApiConfig));c&&(g=c)}return await this.runStep("Save Configuration",async()=>await ie(this.projectRoot,n)),await this.runStep("Version Marker",async()=>await K(this.projectRoot,n.version)),{success:!0,config:n,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:o,skillsInstalled:m,agentsInstalled:S,hooksConfigured:d,mcpConfigured:l,claudeMdGenerated:p,workersStarted:a,n8nInstalled:g},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(r){return this.steps.push({step:"Initialization Failed",status:"error",message:h(r),durationMs:0}),{success:!1,config:R("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return ye}async runStep(e,r){let n=Date.now();try{let s=await r();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-n}),s}catch(s){throw this.steps.push({step:e,status:"error",message:h(s),durationMs:Date.now()-n}),s}}applyWizardAnswers(e){let r=this.options.wizardAnswers||{},n=this.configurator.recommend(e);switch(r["project-type"]&&r["project-type"]!=="auto"&&(n.project.type=r["project-type"]),r["learning-mode"]){case"full":n.learning.enabled=!0,n.learning.embeddingModel="transformer";break;case"basic":n.learning.enabled=!0,n.learning.embeddingModel="hash";break;case"disabled":n.learning.enabled=!1;break}return r["load-patterns"]===!1&&(n.learning.pretrainedPatterns=!1),r.hooks===!1&&(n.hooks.claudeCode=!1),r.workers===!1&&(n.workers.daemonAutoStart=!1),r.skills===!1&&(n.skills.install=!1),n}};function ke(t){return new I(t)}async function We(t){return await ke({projectRoot:t,autoMode:!0}).initialize()}function Ge(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let n of t.steps){let s=n.status==="success"?"[OK]":n.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${n.step.padEnd(50)} ${String(n.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let r=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${r.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
- `)}export{I as a,ke as b,We as c,Ge as d};
314
+ `),e.workers.enabled.length}async function ae(t,e){if(!e.skills.install)return 0;let n=await G({projectRoot:t,installV2Skills:e.skills.installV2,installV3Skills:e.skills.installV3,overwrite:e.skills.overwrite}).install();return n.errors.length>0&&console.warn("Skills installation warnings:",n.errors),n.installed.length}async function oe(t){let r=await V({projectRoot:t,installQEAgents:!0,installSubagents:!0,overwrite:!1}).install();return r.errors.length>0&&console.warn("Agents installation warnings:",r.errors),r.installed.length}async function ie(t,e,r){let s=await J({projectRoot:t,installAgents:!0,installSkills:!0,overwrite:!1,n8nApiConfig:r}).install();return s.errors.length>0&&console.warn("N8n installation warnings:",s.errors),e.platforms||(e.platforms={}),e.platforms.n8n={enabled:!0,installAgents:!0,installSkills:!0,installTypeScriptAgents:!1,n8nApiConfig:r},{agents:s.agentsInstalled.length,skills:s.skillsInstalled.length}}async function le(t,e){if(!e)throw new Error("No configuration to save");let r=i(t,".agentic-qe");f(r)||k(r,{recursive:!0});let n=ke(e),s=i(r,"config.yaml");E(s,n,"utf-8")}function ke(t){let e=["# Agentic QE v3 Configuration","# Generated by aqe init",`# ${new Date().toISOString()}`,""];e.push(`version: "${t.version}"`),e.push(""),e.push("project:"),e.push(` name: "${t.project.name}"`),e.push(` root: "${t.project.root}"`),e.push(` type: "${t.project.type}"`),e.push(""),e.push("learning:"),e.push(` enabled: ${t.learning.enabled}`),e.push(` embeddingModel: "${t.learning.embeddingModel}"`),e.push(" hnswConfig:"),e.push(` M: ${t.learning.hnswConfig.M}`),e.push(` efConstruction: ${t.learning.hnswConfig.efConstruction}`),e.push(` efSearch: ${t.learning.hnswConfig.efSearch}`),e.push(` qualityThreshold: ${t.learning.qualityThreshold}`),e.push(` promotionThreshold: ${t.learning.promotionThreshold}`),e.push(` pretrainedPatterns: ${t.learning.pretrainedPatterns}`),e.push(""),e.push("routing:"),e.push(` mode: "${t.routing.mode}"`),e.push(` confidenceThreshold: ${t.routing.confidenceThreshold}`),e.push(` feedbackEnabled: ${t.routing.feedbackEnabled}`),e.push(""),e.push("# ADR-092: Advisor Strategy \u2014 agents consult a stronger model for strategic guidance"),e.push("# Set provider/model to override auto-detection from environment API keys"),e.push("advisor:"),e.push(' # provider: "openrouter" # openrouter | claude | ollama (auto-detected if not set)'),e.push(' # model: "anthropic/claude-opus-5.5" # provider-specific model ID'),e.push(' # maxUses: "3" # per-task advisor call cap'),e.push(' redact: "strict" # strict | balanced | off'),e.push(""),e.push("workers:"),e.push(" enabled:");for(let r of t.workers.enabled)e.push(` - "${r}"`);e.push(" intervals:");for(let[r,n]of Object.entries(t.workers.intervals))e.push(` ${r}: ${n}`);e.push(` maxConcurrent: ${t.workers.maxConcurrent}`),e.push(` daemonAutoStart: ${t.workers.daemonAutoStart}`),e.push(""),e.push("hooks:"),e.push(` claudeCode: ${t.hooks.claudeCode}`),e.push(` preCommit: ${t.hooks.preCommit}`),e.push(` ciIntegration: ${t.hooks.ciIntegration}`),e.push(""),e.push("skills:"),e.push(` install: ${t.skills.install}`),e.push(` installV2: ${t.skills.installV2}`),e.push(` installV3: ${t.skills.installV3}`),e.push(` overwrite: ${t.skills.overwrite}`),e.push(""),e.push("autoTuning:"),e.push(` enabled: ${t.autoTuning.enabled}`),e.push(" parameters:");for(let r of t.autoTuning.parameters)e.push(` - "${r}"`);e.push(` evaluationPeriodMs: ${t.autoTuning.evaluationPeriodMs}`),e.push(""),e.push("domains:"),e.push(" enabled:");for(let r of t.domains.enabled)e.push(` - "${r}"`);e.push(" disabled:");for(let r of t.domains.disabled)e.push(` - "${r}"`);return e.push(""),e.push("agents:"),e.push(` maxConcurrent: ${t.agents.maxConcurrent}`),e.push(` defaultTimeout: ${t.agents.defaultTimeout}`),e.push(""),e.join(`
315
+ `)}var Ee=[{id:"welcome",title:"Welcome to AQE v3",description:"This wizard will configure Agentic QE for your project.",type:"info"},{id:"project-type",title:"Project Type",description:"What type of project is this?",type:"choice",options:[{value:"auto",label:"Auto-detect",description:"Let AQE analyze your project",recommended:!0},{value:"single",label:"Single Package",description:"Standard single-package project"},{value:"monorepo",label:"Monorepo",description:"Multi-package workspace"},{value:"library",label:"Library",description:"Publishable package/library"}],default:"auto"},{id:"learning-mode",title:"Learning System",description:"How should AQE learn from your project?",type:"choice",options:[{value:"full",label:"Full Learning",description:"Transformer embeddings + SQLite persistence",recommended:!0},{value:"basic",label:"Basic Learning",description:"Hash-based embeddings, in-memory"},{value:"disabled",label:"Disabled",description:"No pattern learning"}],default:"full"},{id:"load-patterns",title:"Pre-trained Patterns",description:"Load pre-trained QE patterns for faster results?",type:"confirm",default:!0},{id:"hooks",title:"Claude Code Integration",description:"Enable Claude Code hooks for seamless integration?",type:"confirm",default:!0},{id:"workers",title:"Background Workers",description:"Start background workers for continuous monitoring?",type:"confirm",default:!0},{id:"skills",title:"Install Skills",description:"Install AQE skills (v2 methodology + v3 domain skills)?",type:"confirm",default:!0},{id:"agents",title:"Install Agents",description:"Install V3 QE agents for Claude Code Task tool?",type:"confirm",default:!0}],I=class{projectRoot;options;analyzer;configurator;steps=[];constructor(e){this.options=e,this.projectRoot=e.projectRoot,this.analyzer=O(e.projectRoot),this.configurator=x({minimal:e.minimal})}async initialize(){let e=Date.now();try{let r=await this.runStep("Project Analysis",async()=>await this.analyzer.analyze()),n=await this.runStep("Configuration Generation",async()=>this.options.autoMode?this.configurator.recommend(r):this.applyWizardAnswers(r));await this.runStep("Persistence Database Setup",async()=>await Z(this.projectRoot));let s=await this.runStep("Code Intelligence Pre-Scan",async()=>{if(!await ee(this.projectRoot))return console.log(" Building knowledge graph for code intelligence..."),await te(r.projectRoot);let w=await ne(this.projectRoot);return console.log(` Using existing code intelligence index (${w} entries)`),{status:"existing",entries:w}}),o=await this.runStep("Learning System Setup",async()=>n.learning.enabled&&!this.options.skipPatterns?await re(this.projectRoot,n,this.options.pretrainedLibrary):0),d=await this.runStep("Hooks Configuration",async()=>n.hooks.claudeCode?await B(this.projectRoot,n):!1),l=await this.runStep("MCP Configuration",async()=>this.options.noMcp?!1:await X(this.projectRoot,{force:this.options.withMcp})),p=await this.runStep("CLAUDE.md Generation",async()=>await K(this.projectRoot,n)),a=await this.runStep("Background Workers",async()=>n.workers.daemonAutoStart?await se(this.projectRoot,n):0),m=await this.runStep("Skills Installation",async()=>n.skills.install?await ae(this.projectRoot,n):0),S=await this.runStep("Agents Installation",async()=>await oe(this.projectRoot)),g;if(this.options.withN8n){let c=await this.runStep("N8n Platform Installation",async()=>await ie(this.projectRoot,n,this.options.n8nApiConfig));c&&(g=c)}return await this.runStep("Save Configuration",async()=>await le(this.projectRoot,n)),await this.runStep("Version Marker",async()=>await Y(this.projectRoot,n.version)),{success:!0,config:n,steps:this.steps,summary:{projectAnalyzed:!0,configGenerated:!0,codeIntelligenceIndexed:s?.entries??0,patternsLoaded:o,skillsInstalled:m,agentsInstalled:S,hooksConfigured:d,mcpConfigured:l,claudeMdGenerated:p,workersStarted:a,n8nInstalled:g},totalDurationMs:Date.now()-e,timestamp:new Date}}catch(r){return this.steps.push({step:"Initialization Failed",status:"error",message:h(r),durationMs:0}),{success:!1,config:D("unknown",this.projectRoot),steps:this.steps,summary:{projectAnalyzed:!1,configGenerated:!1,codeIntelligenceIndexed:0,patternsLoaded:0,skillsInstalled:0,agentsInstalled:0,hooksConfigured:!1,mcpConfigured:!1,claudeMdGenerated:!1,workersStarted:0},totalDurationMs:Date.now()-e,timestamp:new Date}}}getWizardSteps(){return Ee}async runStep(e,r){let n=Date.now();try{let s=await r();return this.steps.push({step:e,status:"success",message:`${e} completed successfully`,durationMs:Date.now()-n}),s}catch(s){throw this.steps.push({step:e,status:"error",message:h(s),durationMs:Date.now()-n}),s}}applyWizardAnswers(e){let r=this.options.wizardAnswers||{},n=this.configurator.recommend(e);switch(r["project-type"]&&r["project-type"]!=="auto"&&(n.project.type=r["project-type"]),r["learning-mode"]){case"full":n.learning.enabled=!0,n.learning.embeddingModel="transformer";break;case"basic":n.learning.enabled=!0,n.learning.embeddingModel="hash";break;case"disabled":n.learning.enabled=!1;break}return r["load-patterns"]===!1&&(n.learning.pretrainedPatterns=!1),r.hooks===!1&&(n.hooks.claudeCode=!1),r.workers===!1&&(n.workers.daemonAutoStart=!1),r.skills===!1&&(n.skills.install=!1),n}};function we(t){return new I(t)}async function Je(t){return await we({projectRoot:t,autoMode:!0}).initialize()}function He(t){let e=[];e.push(""),e.push("+-------------------------------------------------------------+"),e.push("| AQE v3 Initialization |"),e.push("+-------------------------------------------------------------+");for(let n of t.steps){let s=n.status==="success"?"[OK]":n.status==="error"?"[!!]":"[ ]";e.push(`| ${s} ${n.step.padEnd(50)} ${String(n.durationMs).padStart(4)}ms |`)}e.push("+-------------------------------------------------------------+"),e.push(`| Project: ${t.config.project.name.padEnd(47)} |`),e.push(`| Type: ${t.config.project.type.padEnd(50)} |`),e.push(`| Code Intel Indexed: ${String(t.summary.codeIntelligenceIndexed).padEnd(36)} |`),e.push(`| Patterns Loaded: ${String(t.summary.patternsLoaded).padEnd(39)} |`),e.push(`| Skills Installed: ${String(t.summary.skillsInstalled).padEnd(38)} |`),e.push(`| Agents Installed: ${String(t.summary.agentsInstalled).padEnd(38)} |`),e.push(`| Workers Started: ${String(t.summary.workersStarted).padEnd(39)} |`),e.push(`| Hooks Configured: ${t.summary.hooksConfigured?"Yes":"No".padEnd(38)} |`),e.push(`| MCP Server: ${t.summary.mcpConfigured?"Yes":"No".padEnd(44)} |`),e.push(`| CLAUDE.md: ${t.summary.claudeMdGenerated?"Yes":"No".padEnd(45)} |`),e.push("+-------------------------------------------------------------+");let r=t.success?"[OK] AQE v3 initialized as self-learning platform":"[!!] Initialization failed";return e.push(`| ${r.padEnd(57)} |`),e.push("+-------------------------------------------------------------+"),e.push(""),e.join(`
316
+ `)}export{I as a,we as b,Je as c,He as d};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{e as l,l as c}from"./chunk-AVHYJ3XP.js";import{a as i}from"./chunk-C7QLLMYI.js";import{a as n,e as h}from"./chunk-J7Q5TXFZ.js";h();var d=class extends c{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){if(s.gitRef!==void 0){let a=i(s.gitRef,"gitRef");if(a)return{success:!1,error:a}}try{let{runTestPipeline:a}=await import("./test-scheduling-YJQHH3XE.js"),u=await l(o),t=await a({cwd:s.cwd||process.cwd(),memory:u,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),f=t.phaseResults.reduce((e,r)=>e+r.totalTests,0),p=t.phaseResults.reduce((e,r)=>e+r.passed,0),g=t.phaseResults.reduce((e,r)=>e+r.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${f} tests (${p} passed, ${g} failed) in ${t.totalDurationMs}ms`}}}catch(a){return{success:!1,error:n(a)}}}};export{d as a};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
+ import{e as l,l as c}from"./chunk-YISDX6WB.js";import{a as i}from"./chunk-PZOYQHWS.js";import{a as n,e as h}from"./chunk-AWQAE3SW.js";h();var d=class extends c{config={name:"qe/tests/schedule",description:"Schedule and execute tests using phase-based pipeline with git-aware selection and flaky tracking. Runs tests in phases (unit, integration, e2e), selects affected tests from git changes, and tracks flaky tests.",domain:"test-execution",schema:this.buildSchema()};buildSchema(){return{type:"object",properties:{cwd:{type:"string",description:"Working directory for test execution (defaults to project root)"},gitRef:{type:"string",description:'Git ref to compare for affected test selection (e.g., "main", "HEAD~3")'},useGitAware:{type:"boolean",description:"Enable git-aware test selection to only run affected tests",default:!0},trackFlaky:{type:"boolean",description:"Enable flaky test tracking and quarantine",default:!0}}}}async execute(s,o){if(s.gitRef!==void 0){let a=i(s.gitRef,"gitRef");if(a)return{success:!1,error:a}}try{let{runTestPipeline:a}=await import("./test-scheduling-4TRB7LZ7.js"),u=await l(o),t=await a({cwd:s.cwd||process.cwd(),memory:u,baseRef:s.gitRef,flakyHistoryPath:s.trackFlaky!==!1?".agentic-qe/flaky-history.json":void 0,runAllTests:s.useGitAware===!1}),f=t.phaseResults.reduce((e,r)=>e+r.totalTests,0),p=t.phaseResults.reduce((e,r)=>e+r.passed,0),g=t.phaseResults.reduce((e,r)=>e+r.failed,0);return{success:!0,data:{pipelineId:o.requestId,phases:t.phaseResults.map(e=>({phaseId:e.phaseId,phaseName:e.phaseName,totalTests:e.totalTests,passed:e.passed,failed:e.failed,passRate:e.passRate,durationMs:e.durationMs})),gitAware:{enabled:!t.ranAllTests,selectedTests:t.selectedTests.length,gitRef:s.gitRef},flakyTracking:{enabled:s.trackFlaky!==!1},totalDuration:t.totalDurationMs,ranAllTests:t.ranAllTests,summary:`Executed ${t.phaseResults.length} phases, ${f} tests (${p} passed, ${g} failed) in ${t.totalDurationMs}ms`}}}catch(a){return{success:!1,error:n(a)}}}};export{d as a};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
2
  var n=class{constructor(t){this.capacity=t;this.buffer=new Array(t)}capacity;buffer;head=0;tail=0;count=0;push(t){this.buffer[this.tail]=t,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}toArray(){let t=[];for(let e=0;e<this.count;e++){let i=(this.head+e)%this.capacity;t.push(this.buffer[i])}return t}get length(){return this.count}get size(){return this.count}clear(){this.buffer=new Array(this.capacity),this.head=0,this.tail=0,this.count=0}last(t){let e=[],i=Math.max(0,this.count-t);for(let s=i;s<this.count;s++){let r=(this.head+s)%this.capacity;e.push(this.buffer[r])}return e}percentile(t){if(this.count===0)return;let e=this.toArray().sort((s,r)=>Number(s)-Number(r)),i=Math.floor(t/100*(e.length-1));return e[i]}reduce(t,e){let i=e;for(let s=0;s<this.count;s++){let r=(this.head+s)%this.capacity;i=t(i,this.buffer[r])}return i}average(){return this.count===0?0:this.reduce((e,i)=>e+i,0)/this.count}};export{n as a};
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as u,d as f}from"./chunk-5FSPELOG.js";f();var c=class extends Error{constructor(t){super(u(t,Number.POSITIVE_INFINITY)),this.name="TestRunnerExecutionError"}};function x(e,t=4e3){return u(e,Number.POSITIVE_INFINITY).slice(0,t)}function F(e,t,r,n,a,o){let l=(o?.testResults??[]).filter(i=>i.status==="failed"&&(e==="vitest"&&i.message||!i.assertionResults?.some(d=>d.status==="failed"))),s;if(r===null?s="terminated without an exit code":n.passed+n.failed+n.skipped===0?s="reported zero tests":l.length>0||(o?.numRuntimeErrorTestSuites??0)>0||(o?.numFailedTestSuites??0)>0&&n.failed===0?s="reported a suite execution error":(r!==0||o?.success===!1)&&n.failed===0&&(s="failed without a failed assertion"),!s)return;let m=[...l.map(i=>i.message).filter(Boolean),a.trim()].filter(Boolean).join(`
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.15.18");process.exit(0)}
2
+ import{a as u,d as f}from"./chunk-Q7V722K5.js";f();var c=class extends Error{constructor(t){super(u(t,Number.POSITIVE_INFINITY)),this.name="TestRunnerExecutionError"}};function x(e,t=4e3){return u(e,Number.POSITIVE_INFINITY).slice(0,t)}function F(e,t,r,n,a,o){let l=(o?.testResults??[]).filter(i=>i.status==="failed"&&(e==="vitest"&&i.message||!i.assertionResults?.some(d=>d.status==="failed"))),s;if(r===null?s="terminated without an exit code":n.passed+n.failed+n.skipped===0?s="reported zero tests":l.length>0||(o?.numRuntimeErrorTestSuites??0)>0||(o?.numFailedTestSuites??0)>0&&n.failed===0?s="reported a suite execution error":(r!==0||o?.success===!1)&&n.failed===0&&(s="failed without a failed assertion"),!s)return;let m=[...l.map(i=>i.message).filter(Boolean),a.trim()].filter(Boolean).join(`
3
3
  `);return new c(`${e} ${s} for ${t} (exit code ${r??"unknown"}).`+(m?`
4
4
  ${x(m)}`:""))}import{realpathSync as R,statSync as $}from"node:fs";import{basename as b,dirname as E,extname as T,resolve as g,sep as h}from"node:path";function p(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function y(e,t=process.cwd()){let r=g(t,e);try{return g(R(E(r)),b(r))}catch{return r}}function I(e){try{return $(e).isDirectory()}catch{return T(e)===""}}function k(e,t=process.cwd()){let r=y(e,t),n=r.split(h).join("/"),a=I(r)?"(?:/|$)":"$";return`^${p(n)}${a}`}function v(e,t){let r=`^${t.split(" ").map(p).join("(?: > | )")}$`;return e==="mocha"?`--grep=${r}`:`--testNamePattern=${r}`}function A(e){return e.some(t=>/(^|[\\/])jest(\.cmd|\.js|\.mjs)?$/i.test(t))}export{c as a,x as b,F as c,y as d,k as e,v as f,A as g};
@@ -1,2 +1,2 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as v}from"./chunk-SAZ4PJBR.js";import{h as U}from"./chunk-WX4PO65Q.js";import{c as D,d as R,e as h,g as x}from"./chunk-IJZFJPHS.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-OMILP6KH.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};
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.15.18");process.exit(0)}
2
+ import{a as v}from"./chunk-BN2FROBQ.js";import{h as U}from"./chunk-VUQPVWNK.js";import{c as D,d as R,e as h,g as x}from"./chunk-TVBDUMKT.js";var f=class{config;trackers;globalCostTodayUsd=0;lastGlobalReset=new Date;constructor(e){this.config=e,this.trackers=new Map;for(let t of[0,1,2,3,4])this.trackers.set(t,{tier:t,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,lastHourlyReset:new Date,lastDailyReset:new Date,requestHistory:[]})}async checkBudget(e,t){if(!this.config.enabled)return this.createAllowedDecision(e,e,t,!1,[]);this.autoReset();let r=this.config.tierBudgets[e];if(!r||!r.enabled)return this.createAllowedDecision(e,e,t,!1,["Tier budget not configured or disabled"]);let s=this.getUsage(e),i=[],c=this.config.maxDailyCostUsd-this.globalCostTodayUsd;if(this.globalCostTodayUsd+t>this.config.maxDailyCostUsd)return this.handleBudgetExceeded(e,t,s,"Global daily budget would be exceeded");if(this.globalCostTodayUsd+t>=this.config.maxDailyCostUsd*this.config.warningThreshold&&(i.push(`Approaching global daily budget limit: $${this.globalCostTodayUsd.toFixed(2)}/$${this.config.maxDailyCostUsd.toFixed(2)}`),this.config.onBudgetWarning==="downgrade"))return this.downgradeTier(e,t,s,i);let a=[{exceeded:s.costSpentTodayUsd+t>r.maxDailyCostUsd,message:`Tier ${e} daily cost limit would be exceeded: $${s.costSpentTodayUsd.toFixed(2)}/$${r.maxDailyCostUsd.toFixed(2)}`},{exceeded:s.requestsThisHour>=r.maxRequestsPerHour,message:`Tier ${e} hourly request limit reached: ${s.requestsThisHour}/${r.maxRequestsPerHour}`},{exceeded:s.requestsToday>=r.maxRequestsPerDay,message:`Tier ${e} daily request limit reached: ${s.requestsToday}/${r.maxRequestsPerDay}`},{exceeded:t>r.maxCostPerRequest,message:`Tier ${e} per-request cost limit would be exceeded: $${t.toFixed(4)}/$${r.maxCostPerRequest.toFixed(4)}`}];for(let n of a)if(n.exceeded)return this.handleBudgetExceeded(e,t,s,n.message);return s.budgetUtilization>=this.config.warningThreshold&&(i.push(`Tier ${e} at ${(s.budgetUtilization*100).toFixed(1)}% of daily budget`),this.config.onBudgetWarning==="downgrade")?this.downgradeTier(e,t,s,i):this.createAllowedDecision(e,e,t,!1,i)}async recordCost(e,t){if(!this.config.enabled)return;let r=this.trackers.get(e);r&&(this.autoReset(),r.costSpentTodayUsd+=t,r.requestsThisHour++,r.requestsToday++,this.globalCostTodayUsd+=t,r.requestHistory.push({timestamp:new Date,costUsd:t}),r.requestHistory.length>1e3&&(r.requestHistory=r.requestHistory.slice(-1e3)))}getUsage(e){this.autoReset();let t=this.trackers.get(e);if(!t)return this.createEmptyUsage(e);let r=this.config.tierBudgets[e];if(!r)return this.createEmptyUsage(e);let s=r.maxDailyCostUsd>0?t.costSpentTodayUsd/r.maxDailyCostUsd:0,i=t.costSpentTodayUsd>=r.maxDailyCostUsd||t.requestsThisHour>=r.maxRequestsPerHour||t.requestsToday>=r.maxRequestsPerDay,c=s>=this.config.warningThreshold,a=new Date,n=new Date(a);return n.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:t.costSpentTodayUsd,requestsThisHour:t.requestsThisHour,requestsToday:t.requestsToday,budgetUtilization:s,isExceeded:i,isNearLimit:c,resetTime:n,remainingBudgetUsd:Math.max(0,r.maxDailyCostUsd-t.costSpentTodayUsd),remainingRequestsThisHour:Math.max(0,r.maxRequestsPerHour-t.requestsThisHour),remainingRequestsToday:Math.max(0,r.maxRequestsPerDay-t.requestsToday)}}getAllUsage(){let e={};for(let t of[0,1,2,3,4])e[t]=this.getUsage(t);return e}reset(){let e=new Date;for(let t of this.trackers.values())t.costSpentTodayUsd=0,t.requestsThisHour=0,t.requestsToday=0,t.lastHourlyReset=e,t.lastDailyReset=e,t.requestHistory=[];this.globalCostTodayUsd=0,this.lastGlobalReset=e}handleBudgetExceeded(e,t,r,s){switch(this.config.onBudgetExceeded){case"error":throw new h(`Budget exceeded: ${s}`,e,r);case"downgrade":return this.downgradeTier(e,t,r,[s]);case"queue":throw new h(`Budget exceeded (queueing not yet implemented): ${s}`,e,r);default:throw new h(`Budget exceeded: ${s}`,e,r)}}downgradeTier(e,t,r,s){for(let i=e-1;i>=0;i--){let c=this.config.tierBudgets[i];if(!c||!c.enabled)continue;let a=this.getUsage(i);if(!a.isExceeded){let n=t*.5;if(a.costSpentTodayUsd+n<=c.maxDailyCostUsd)return this.createAllowedDecision(e,i,n,!0,[...s,`Downgraded from Tier ${e} to Tier ${i} due to budget constraints`])}}throw new h(`Budget exceeded and no lower tier available: ${s.join("; ")}`,e,r)}createAllowedDecision(e,t,r,s,i){let c=this.getUsage(t);return{allowed:!0,reason:s?`Budget enforced: downgraded to Tier ${t}`:"Budget check passed",requestedTier:e,approvedTier:t,wasDowngraded:s,estimatedCostUsd:r,currentUsage:c,warnings:i}}createEmptyUsage(e){let t=new Date,r=new Date(t);return r.setUTCHours(24,0,0,0),{tier:e,costSpentTodayUsd:0,requestsThisHour:0,requestsToday:0,budgetUtilization:0,isExceeded:!1,isNearLimit:!1,resetTime:r,remainingBudgetUsd:0,remainingRequestsThisHour:0,remainingRequestsToday:0}}autoReset(){let e=new Date;this.shouldResetDaily(this.lastGlobalReset,e)&&(this.globalCostTodayUsd=0,this.lastGlobalReset=e);for(let t of this.trackers.values())this.shouldResetHourly(t.lastHourlyReset,e)&&(t.requestsThisHour=0,t.lastHourlyReset=e),this.shouldResetDaily(t.lastDailyReset,e)&&(t.costSpentTodayUsd=0,t.requestsToday=0,t.requestHistory=[],t.lastDailyReset=e)}shouldResetHourly(e,t){return(t.getTime()-e.getTime())/36e5>=1}shouldResetDaily(e,t){return t.getUTCDate()!==e.getUTCDate()||t.getUTCMonth()!==e.getUTCMonth()||t.getUTCFullYear()!==e.getUTCFullYear()}getSessionCostSummary(){this.autoReset();let e=this.config.maxDailyCostUsd,t=0,r={},s={0:"AgentBooster",1:"Haiku",2:"Sonnet",3:"SonnetExtended",4:"Opus"};for(let[c,a]of this.trackers.entries()){let n=this.config.tierBudgets[c],o=s[c]??`Tier${c}`;t+=a.costSpentTodayUsd,r[o]={spent:a.costSpentTodayUsd,limit:n?.maxDailyCostUsd??0,requests:a.requestsToday}}let i=e>0?Math.round(t/e*100):0;return{totalSpentUsd:t,dailyLimitUsd:e,utilizationPercent:i,byTier:r}}};var w=class{cache=new Map;maxSize;ttlMs;enabled;constructor(e,t,r){this.enabled=e,this.maxSize=t,this.ttlMs=r}generateKey(e){return`${e.agentType||"unknown"}:${e.domain||"unknown"}:${e.task.slice(0,100)}`}get(e){if(!this.enabled)return null;let t=this.generateKey(e),r=this.cache.get(t);return r?Date.now()>r.expiresAt?(this.cache.delete(t),null):{...r.decision,metadata:{...r.decision.metadata,fromCache:!0,decisionTimeMs:0}}:null}set(e,t){if(!this.enabled)return;let r=this.generateKey(e);if(this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s&&this.cache.delete(s)}this.cache.set(r,{decision:t,expiresAt:Date.now()+this.ttlMs})}clear(){this.cache.clear()}getStats(){return{size:this.cache.size,hitRate:0}}},M=class{events=[];enabled;maxEvents=1e4;constructor(e){this.enabled=e}record(e){this.enabled&&(this.events.push(e),this.events.length>this.maxEvents&&(this.events=this.events.slice(-this.maxEvents)))}getMetrics(){if(this.events.length===0)return this.createEmptyMetrics();let e=new Date,t={};for(let o of[0,1,2,3,4]){let d=this.events.filter(l=>l.tier===o);if(d.length===0)continue;let T=d.filter(l=>l.success),m=d.filter(l=>!l.wasManualOverride),b=d.filter(l=>l.wasDowngraded),y=d.map(l=>l.latencyMs).sort((l,g)=>l-g),B=Math.floor(y.length*.95);t[o]={tier:o,selectionCount:d.length,autoRouteCount:m.length,manualOverrideCount:d.length-m.length,budgetDowngradeCount:b.length,successRate:T.length/d.length,avgComplexity:d.reduce((l,g)=>l+g.complexity,0)/d.length,totalCostUsd:d.reduce((l,g)=>l+g.costUsd,0),avgLatencyMs:d.reduce((l,g)=>l+g.latencyMs,0)/d.length,p95LatencyMs:y[B]||0,budgetUtilization:0}}let r=this.events.map(o=>o.latencyMs).sort((o,d)=>o-d),s=Math.floor(r.length*.95),i=Math.floor(r.length*.99),c=this.events.filter(o=>o.agentBoosterEligible).length,a=this.events.filter(o=>o.tier===0).length,n=this.events.filter(o=>o.tier===0&&o.success).length;return{byTier:t,totalDecisions:this.events.length,avgDecisionTimeMs:this.events.reduce((o,d)=>o+d.latencyMs,0)/this.events.length,p95DecisionTimeMs:r[s]||0,p99DecisionTimeMs:r[i]||0,fallbackRate:this.events.filter(o=>o.wasDowngraded).length/this.events.length,ruleMatchRate:this.events.filter(o=>!o.wasManualOverride).length/this.events.length,estimatedCostSavings:0,agentBoosterStats:{eligible:c,used:a,fallbackToLLM:Math.max(0,c-a),successRate:a>0?n/a:0},budgetStats:{totalSpentUsd:this.events.reduce((o,d)=>o+d.costUsd,0),budgetUtilization:0,downgradeCount:this.events.filter(o=>o.wasDowngraded).length,overrideCount:this.events.filter(o=>o.wasManualOverride).length},period:{start:this.events[0]?.timestamp||e,end:this.events[this.events.length-1]?.timestamp||e}}}reset(){this.events=[]}createEmptyMetrics(){let e=new Date;return{byTier:{},totalDecisions:0,avgDecisionTimeMs:0,p95DecisionTimeMs:0,p99DecisionTimeMs:0,fallbackRate:0,ruleMatchRate:0,estimatedCostSavings:0,agentBoosterStats:{eligible:0,used:0,fallbackToLLM:0,successRate:0},budgetStats:{totalSpentUsd:0,budgetUtilization:0,downgradeCount:0,overrideCount:0},period:{start:e,end:e}}}},p=class{config;complexityAnalyzer;budgetEnforcer;agentBoosterAdapter;cache;metrics;persistentMetricsTracker;patternsLoaded=!1;tierHierarchyFromPatterns=null;constructor(e={},t,r){this.config={...D,...e},this.agentBoosterAdapter=t,this.persistentMetricsTracker=r,this.complexityAnalyzer=U(this.config,t),this.budgetEnforcer=new f(this.config.budgetConfig),this.cache=new w(this.config.enableDecisionCache,1e3,this.config.decisionCacheTtlMs),this.metrics=new M(this.config.enableMetrics)}setPersistentMetricsTracker(e){this.persistentMetricsTracker=e}async loadPatternsFromLoader(){try{let t=await v().getTierHierarchy();if(t){this.tierHierarchyFromPatterns=t,this.patternsLoaded=!0,console.info("[ModelRouter] Loaded tier hierarchy from PatternLoader",{tiers:Object.keys(t)});return}console.debug("[ModelRouter] PatternLoader returned no tier hierarchy, using defaults")}catch(e){console.warn("[ModelRouter] Failed to load patterns from PatternLoader, using defaults",{error:e instanceof Error?e.message:"Unknown error"})}this.patternsLoaded=!1}getPatternsLoaded(){return this.patternsLoaded}getTierHierarchyFromPatterns(){return this.tierHierarchyFromPatterns}async route(e){let t=Date.now(),r=e.metadata?.correlationId;try{let s=this.cache.get(e);if(s)return s;let i=await Promise.race([this.routeInternal(e,t,r),new Promise((c,a)=>setTimeout(()=>a(new x("Routing decision timed out",this.config.maxDecisionTimeMs)),this.config.maxDecisionTimeMs))]);return this.cache.set(e,i),this.recordMetrics(i,!0),i}catch(s){let i=await this.createFallbackDecision(e,t,r,s instanceof Error?s:new Error("Unknown error"));return this.recordMetrics(i,!1),i}}getMetrics(){return this.metrics.getMetrics()}async getAgentBoosterHealth(){if(!this.agentBoosterAdapter)throw new R("Agent Booster adapter not available","AGENT_BOOSTER_UNAVAILABLE");return this.agentBoosterAdapter.getHealth()}resetMetrics(){this.metrics.reset()}async dispose(){this.cache.clear(),this.metrics.reset(),this.agentBoosterAdapter&&await this.agentBoosterAdapter.dispose()}async routeInternal(e,t,r){let s=[];if(e.manualTier!==void 0&&this.config.allowManualOverrides)return this.handleManualOverride(e,e.manualTier,t,r);let i=await this.complexityAnalyzer.analyze(e),c=i.recommendedTier,a=this.estimateCost(c,e.task.length),n=await this.budgetEnforcer.checkBudget(c,a),o=n.approvedTier;s.push(...n.warnings);let d=o===0&&i.signals.isMechanicalTransform,T=this.getModelIdForTier(o),m=this.buildRationale(i,n,o),b=this.buildAlternatives(i,o),y=Date.now()-t;return{tier:o,modelId:T,complexityAnalysis:i,budgetDecision:n,confidence:i.confidence,rationale:m,agentBoosterEligible:d,agentBoosterTransform:d?i.signals.detectedTransformType:void 0,alternativeTiers:b,metadata:{timestamp:new Date,decisionTimeMs:y,fromCache:!1,correlationId:r},warnings:s}}async handleManualOverride(e,t,r,s){let i=await this.complexityAnalyzer.analyze(e),c=this.estimateCost(t,e.task.length),a=await this.budgetEnforcer.checkBudget(t,c);!a.allowed&&e.isCritical&&this.config.budgetConfig.allowCriticalOverrides&&(a={...a,allowed:!0,reason:"Critical task override",warnings:[...a.warnings,"Budget exceeded but allowed due to critical task override"]});let n=a.approvedTier,o=this.getModelIdForTier(n),d=Date.now()-r;return{tier:n,modelId:o,complexityAnalysis:i,budgetDecision:a,confidence:1,rationale:`Manual override to Tier ${n}${a.wasDowngraded?" (downgraded due to budget)":""}`,agentBoosterEligible:n===0,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:d,fromCache:!1,correlationId:s},warnings:a.warnings}}async createFallbackDecision(e,t,r,s){let i=this.config.fallbackTier,c=this.getModelIdForTier(i),a={overall:50,codeComplexity:50,reasoningComplexity:50,scopeComplexity:50,confidence:.3,signals:{hasArchitectureScope:!1,hasSecurityScope:!1,requiresMultiStepReasoning:!1,requiresCrossDomainCoordination:!1,isMechanicalTransform:!1,requiresCreativity:!1,keywordMatches:{simple:[],moderate:[],complex:[],critical:[]}},recommendedTier:i,alternateTiers:[],explanation:`Fallback to Tier ${i} due to routing error`},n={allowed:!0,reason:"Fallback routing",requestedTier:i,approvedTier:i,wasDowngraded:!1,estimatedCostUsd:0,currentUsage:this.budgetEnforcer.getUsage(i),warnings:[]},o=Date.now()-t;return{tier:i,modelId:c,complexityAnalysis:a,budgetDecision:n,confidence:.3,rationale:`Fallback to Tier ${i} due to error: ${s.message}`,agentBoosterEligible:!1,alternativeTiers:[],metadata:{timestamp:new Date,decisionTimeMs:o,fromCache:!1,correlationId:r},warnings:[`Routing error: ${s.message}`,"Using fallback tier"]}}estimateCost(e,t){let r=[0,.001,.01,.05,.2],s=Math.max(1,t/1e3);return r[e]*s}getModelIdForTier(e){return this.config.tierModels[e]||`tier-${e}-default`}buildRationale(e,t,r){let s=[];return s.push(`Complexity: ${e.overall}/100`),s.push(`Tier ${r} selected`),t.wasDowngraded&&s.push(`Downgraded due to budget: ${t.reason}`),s.push(e.explanation),s.join(". ")}buildAlternatives(e,t){return e.alternateTiers.filter(r=>r!==t).map(r=>({tier:r,modelId:this.getModelIdForTier(r),reason:`Alternative tier ${r}`}))}recordMetrics(e,t){this.metrics.record({timestamp:e.metadata.timestamp,tier:e.tier,complexity:e.complexityAnalysis.overall,costUsd:e.budgetDecision.estimatedCostUsd,latencyMs:e.metadata.decisionTimeMs,wasDowngraded:e.budgetDecision.wasDowngraded,wasManualOverride:!1,agentBoosterEligible:e.agentBoosterEligible,success:t}),this.recordPersistentMetrics(e,t).catch(console.error)}async recordPersistentMetrics(e,t){if(this.persistentMetricsTracker)try{let r=`router-tier${e.tier}-${Date.now()}`;await this.persistentMetricsTracker.recordOutcome("router",r,t,e.metadata.decisionTimeMs,{subType:`tier-${e.tier}`,confidence:e.confidence,usedFallback:e.budgetDecision.wasDowngraded})}catch(r){console.warn("[ModelRouter] Failed to record persistent metrics:",r)}}};function H(u={},e,t){return new p(u,e,t)}async function $(u={},e){let{createAgentBoosterAdapter:t}=await import("./adapter-WRSDXLOT.js"),r=await t({enabled:!0}),s=new p(u,r,e);return await s.loadPatternsFromLoader(),s}export{p as a,H as b,$ as c};
@@ -0,0 +1,2 @@
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.18");process.exit(0)}
2
+ import{createHash as h}from"node:crypto";var g=32,y=4096,k=10080*60*1e3,p="defect-intelligence",R=["critical","high","medium","low","info"],d=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function b(e){if(!d(e))return null;let{file:t,probability:i,riskLevel:r}=e;if(typeof t!="string"||t.length===0||typeof i!="number"||!Number.isFinite(i)||i<0||i>1||!R.includes(r))return null;let n=Array.isArray(e.factors)?e.factors.filter(c=>d(c)&&typeof c.name=="string"&&typeof c.contribution=="number"&&Number.isFinite(c.contribution)):[],o=Array.isArray(e.recommendations)?e.recommendations.filter(c=>typeof c=="string"):[];return{file:t,probability:i,riskLevel:r,factors:n,recommendations:o}}function N(e){let t=`files:${[...new Set(e)].sort().join(",")}`;return t.length<=y?t:`files-sha256:${h("sha256").update(t).digest("hex")}`}function A(e,t){if(!d(e)||typeof e.id!="string"||typeof e.timestamp!="string")return null;let i=Date.parse(e.timestamp);if(!Number.isFinite(i)||i>t+6e4||t-i>k||e.target!==void 0&&(typeof e.target!="string"||e.target.length>y)||!Array.isArray(e.predictions)||e.predictions.length===0)return null;let r=e.predictions.map(b);return r.some(n=>n===null)?null:{id:e.id,timestamp:e.timestamp,predictions:r,target:e.target??"",...e.predictionMethod==="static-code-indicators"?{predictionMethod:"static-code-indicators",estimated:!0,filesSkipped:typeof e.filesSkipped=="number"&&Number.isSafeInteger(e.filesSkipped)&&e.filesSkipped>=0?e.filesSkipped:0}:{}}}function S(e){if(!d(e)||typeof e.timestamp!="string")return null;let t=Date.parse(e.timestamp);return Number.isFinite(t)?t:null}function E(e){let t=new Map,i=[];for(let n of e){let o=t.get(n.target);o===void 0&&t.set(n.target,n.timestamp),(o===void 0||o===n.timestamp)&&i.push(n)}let r=new Set(i.slice(0,g).map(n=>n.key));for(let n of e){if(r.size>=g)break;r.add(n.key)}return r}async function $(e,t="defect-intelligence:predictor"){let i=`${t}:prediction:`,r=await e.search(`${i}*`,Number.MAX_SAFE_INTEGER,{namespace:p}),n=Date.now(),o=[],c=[];for(let a of r){let s=a.startsWith(`${p}:${i}`)?a.slice(p.length+1):a;if(!s.startsWith(i))continue;let m=await e.get(s,{namespace:p}),f=S(m);if(f!==null&&n-f>k){c.push(s);continue}let u=A(m,n);u&&o.push({key:s,timestamp:Date.parse(u.timestamp),id:u.id,target:u.target})}o.sort((a,s)=>s.timestamp-a.timestamp||(a.id===s.id?a.key===s.key?0:a.key>s.key?-1:1:a.id>s.id?-1:1));let l=E(o);for(let a of[...c,...o.filter(s=>!l.has(s.key)).map(s=>s.key)])await e.delete(a,{namespace:p})}function _(e){let t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp(`^${t.replace(/\*/g,".*").replace(/\?/g,".")}$`,"s")}function x(e,t,i){return _(i).test(e)?e:e.startsWith(`${t}:`)?e.slice(t.length+1):e}var M=1e4,v=32;async function D(e,t,i={}){let r=Math.max(1,Math.floor(i.pageSize??M)),n=await e.search(t,r,i.retrieve);for(let l=1;n.length>=r;l++){if(l>=v)throw new Error(`searchAllKeys('${t}'): the backend never returned a short page after ${l} requests (last limit ${r}); refusing to return a possibly incomplete key list`);r*=2,n=await e.search(t,r,i.retrieve)}let o=i.retrieve?.namespace,c=o?n.map(l=>x(l,o,t)):n;return[...new Set(c)].sort()}export{y as a,N as b,A as c,$ as d,x as e,D as f};