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
@@ -1,16 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as $}from"./chunk-IHQGNDMX.js";import{i as q}from"./chunk-XPTCQKVE.js";import{B as V,C as K}from"./chunk-NZJVDOUN.js";import{a as N,c as y,d}from"./chunk-REY52O7J.js";import{a as k,b as M,e as Q}from"./chunk-J7Q5TXFZ.js";import{f as H}from"./chunk-Z7SKUC6P.js";Q();var v={WorkflowStarted:"workflow.WorkflowStarted",WorkflowCompleted:"workflow.WorkflowCompleted",WorkflowFailed:"workflow.WorkflowFailed",WorkflowCancelled:"workflow.WorkflowCancelled",StepStarted:"workflow.StepStarted",StepCompleted:"workflow.StepCompleted",StepFailed:"workflow.StepFailed",StepSkipped:"workflow.StepSkipped",StepAwaitingApproval:"workflow.StepAwaitingApproval",StepApproved:"workflow.StepApproved",StepRejected:"workflow.StepRejected"},O={maxConcurrentWorkflows:10,defaultStepTimeout:6e4,defaultWorkflowTimeout:6e5,enableEventTriggers:!0,persistExecutions:!0};import{createHash as J}from"node:crypto";function R(s){if(["__proto__","constructor","prototype"].includes(s.id))throw new Error(`parallel_output_invalid_path: unsafe step ID ${s.id}`);let e=[{stepId:s.id,path:s.id,segments:[s.id]}];for(let t of Object.values(s.outputMapping??{}).sort()){let i=t.split(".");if(i.some(r=>!r||["__proto__","constructor","prototype"].includes(r)))throw new Error(`parallel_output_invalid_path: ${s.id} maps to ${t}`);e.push({stepId:s.id,path:t,segments:i})}return e}function j(s){let e=s.flatMap(R),t=[];for(let i=0;i<e.length;i++)for(let r=i+1;r<e.length;r++){let o=e[i],a=e[r];if(o.stepId===a.stepId)continue;let n=Math.min(o.segments.length,a.segments.length);o.segments.slice(0,n).every((c,l)=>c===a.segments[l])&&t.push({pathA:o.path,stepA:o.stepId,pathB:a.path,stepB:a.stepId,kind:o.segments.length===a.segments.length?"exact":"ancestor-descendant"})}return t}function L(s){let e=[];for(let t of s){let i=[...Object.values(t.inputMapping??{}),t.condition?.path,t.skipCondition?.path].filter(r=>typeof r=="string");for(let r of i)for(let o of s){if(o.id===t.id)continue;if(r==="results"){e.push({stepId:t.id,sourcePath:r,otherStepId:o.id});continue}if(!r.startsWith("results."))continue;let a=r.slice(8).split(".");R(o).some(c=>{let l=Math.min(a.length,c.segments.length);return c.segments.slice(0,l).every((f,S)=>f===a[S])})&&e.push({stepId:t.id,sourcePath:r,otherStepId:o.id})}}return e}function x(s,e){if(s===null||typeof s=="string"||typeof s=="boolean")return s;if(typeof s=="number")return["number",String(s)];if(typeof s=="bigint")return["bigint",String(s)];if(s===void 0)return["undefined"];if(typeof s!="object")throw new Error("parallel_output_unhashable");if(e.has(s))throw new Error("parallel_output_cyclic");e.add(s);try{if(s instanceof Date)return["date",s.toISOString()];if(s instanceof ArrayBuffer)return["bytes",Buffer.from(s).toString("base64")];if(ArrayBuffer.isView(s))return["bytes",s.constructor.name,Buffer.from(s.buffer,s.byteOffset,s.byteLength).toString("base64")];if(Array.isArray(s))return["array",s.map(i=>x(i,e))];if(s instanceof Set)return["set",[...s].map(r=>x(r,e)).sort((r,o)=>JSON.stringify(r).localeCompare(JSON.stringify(o)))];if(s instanceof Map)return["map",[...s].map(([r,o])=>[x(r,e),x(o,e)]).sort((r,o)=>JSON.stringify(r).localeCompare(JSON.stringify(o)))];let t=s;return["object",Object.keys(t).sort().map(i=>[i,x(t[i],e)])]}finally{e.delete(s)}}function A(s){let e=JSON.stringify(x(s,new Set));return J("sha256").update(e).digest("hex")}var X="qe-coverage-analysis",T=`(agent_id != '${X}' OR (CASE WHEN json_valid(context_json) THEN json_extract(context_json, '$.measured') END) = 1)`;function P(){try{let{getUnifiedMemory:s}=(K(),H(V)),e=s();return e.isInitialized()?e.getDatabase():null}catch{return null}}var Y={id:"quality-gate-check",domain:"quality-assessment",action:"gate-check",async execute(s){let e=typeof s.coverageMin=="number"?s.coverageMin:80,t=typeof s.testsPassingMin=="number"?s.testsPassingMin:90,i=typeof s.maxBugs=="number"?s.maxBugs:5,r=typeof s.currentCoverage=="number"?s.currentCoverage:null,o=typeof s.currentTestsPassingRate=="number"?s.currentTestsPassingRate:null,a=typeof s.currentBugs=="number"?s.currentBugs:null;if(r===null||o===null||a===null){let b=P();if(b)try{if(r===null){let h=b.prepare(`SELECT after_lines FROM coverage_sessions WHERE ${T} ORDER BY created_at DESC LIMIT 1`).get();r=typeof h?.after_lines=="number"?h.after_lines:null}if(o===null){let h=b.prepare(`SELECT COUNT(*) as total,
3
- SUM(CASE WHEN passed = 1 THEN 1 ELSE 0 END) as passed
4
- FROM test_outcomes
5
- WHERE created_at > datetime('now', '-7 days')`).get();o=h&&h.total>0?h.passed/h.total*100:0}a===null&&(a=b.prepare(`SELECT COUNT(*) as bugs FROM test_outcomes
6
- WHERE passed = 0 AND flaky = 0
7
- AND created_at > datetime('now', '-7 days')`).get()?.bugs??0)}catch{}}let n=r!==null;o=o??0,a=a??0;let c=r!==null&&r>=e,l=o>=t,f=a<=i,S=c&&l&&f,I=r===null?0:Math.min(r/e,1),u=Math.min(o/t,1),w=i>0?Math.max(0,1-a/i):a===0?1:0,m=(I+u+w)/3;return y({passed:S,score:Math.round(m*100)/100,source:typeof s.currentCoverage=="number"?"input":"database",details:{coverage:{current:r,threshold:e,passed:c,...n?{}:{unmeasured:!0}},testsPassing:{current:o,threshold:t,passed:l},bugs:{current:a,threshold:i,passed:f}}})}},Z={id:"coverage-threshold",domain:"coverage-analysis",action:"threshold-check",async execute(s){let e=typeof s.minCoverage=="number"?s.minCoverage:80,t=typeof s.currentCoverage=="number"?s.currentCoverage:null,i="input";if(t===null){i="database";let a=P();if(a)try{let n=a.prepare(`SELECT after_lines FROM coverage_sessions WHERE ${T} ORDER BY created_at DESC LIMIT 1`).get();t=typeof n?.after_lines=="number"?n.after_lines:null}catch{t=null}else t=null}let r=t!==null&&t>=e,o=t===null?null:r?0:Math.round((e-t)*100)/100;return y({currentCoverage:t,passed:r,gap:o,minCoverage:e,source:i,...t===null?{unmeasured:!0}:{}})}},ee={id:"pattern-health",domain:"learning-optimization",action:"health-check",async execute(s){let e=typeof s.totalPatterns=="number"?s.totalPatterns:null,t=typeof s.activePatterns=="number"?s.activePatterns:null,i=typeof s.avgConfidence=="number"?s.avgConfidence:null,r="input";if(e===null||t===null||i===null){r="database";let c=P();if(c)try{let l=c.prepare(`
8
- SELECT COUNT(*) as total,
9
- SUM(CASE WHEN deprecated_at IS NULL AND confidence >= 0.3 THEN 1 ELSE 0 END) as active,
10
- AVG(confidence) as avg_conf
11
- FROM qe_patterns
12
- `).get();e=e??l?.total??0,t=t??l?.active??0,i=i??l?.avg_conf??0}catch{}}e=e??0,t=t??0,i=i??0;let o=Math.min(e/100,1),a=e>0?t/e:0,n=Math.round((o*.3+a*.3+i*.4)*100)/100;return y({totalPatterns:e,activePatterns:t,avgConfidence:i,healthScore:n,source:r})}},te={id:"routing-accuracy",domain:"learning-optimization",action:"routing-check",async execute(s){let e=typeof s.totalOutcomes=="number"?s.totalOutcomes:null,t=typeof s.successfulOutcomes=="number"?s.successfulOutcomes:null,i=typeof s.confidenceCorrelation=="number"?s.confidenceCorrelation:null,r="input";if(e===null||t===null){r="database";let a=P();if(a)try{let n=a.prepare(`
13
- SELECT COUNT(*) as total,
14
- SUM(CASE WHEN success = 1 THEN 1 ELSE 0 END) as successful
15
- FROM routing_outcomes
16
- `).get();e=e??n?.total??0,t=t??n?.successful??0}catch{}}e=e??0,t=t??0,i=i??0;let o=e>0?Math.round(t/e*1e4)/100:0;return y({successRate:o,totalOutcomes:e,successfulOutcomes:t,confidenceCorrelation:i,source:r})}},re=[Y,Z,ee,te];function B(s,e){return re.find(t=>t.domain===s&&t.action===e)}function z(){return[ie(),ne(),oe(),se(),ae(),le()]}var G=["comprehensive-testing","defect-prevention","pre-release","continuous-learning","morning-sync","qcsd-ideation-swarm"];function ie(){return{id:"comprehensive-testing",name:"Comprehensive Testing Workflow",description:"test-generation -> test-execution -> coverage-analysis -> quality-assessment",version:"1.0.0",tags:["testing","quality"],steps:[{id:"generate-tests",name:"Generate Tests",domain:"test-generation",action:"generateTests",inputMapping:{sourceFiles:"input.sourceFiles",framework:"input.framework"},outputMapping:{testFiles:"generatedTests.files",testCount:"generatedTests.count"},timeout:12e4,retry:{maxAttempts:2,backoffMs:1e3}},{id:"execute-tests",name:"Execute Tests",domain:"test-execution",action:"execute",dependsOn:["generate-tests"],inputMapping:{testFiles:"results.generatedTests.files"},outputMapping:{runId:"execution.runId",passed:"execution.passed",failed:"execution.failed"},timeout:3e5},{id:"analyze-coverage",name:"Analyze Coverage",domain:"coverage-analysis",action:"analyze",dependsOn:["execute-tests"],inputMapping:{runId:"results.execution.runId"},outputMapping:{line:"coverage.line",branch:"coverage.branch",overall:"coverage.overall"}},{id:"assess-quality",name:"Assess Quality",domain:"quality-assessment",action:"evaluateGate",dependsOn:["analyze-coverage"],inputMapping:{coverage:"results.coverage",testResults:"results.execution"},outputMapping:{passed:"quality.gatePassed",score:"quality.score"}},{id:"generate-more-tests",name:"Generate Additional Tests",domain:"test-generation",action:"generateTests",dependsOn:["analyze-coverage"],condition:{path:"results.coverage.overall",operator:"lt",value:80},inputMapping:{sourceFiles:"input.sourceFiles",targetCoverage:"input.targetCoverage"},continueOnFailure:!0}]}}function ne(){return{id:"defect-prevention",name:"Defect Prevention Workflow",description:"code-intelligence (impact) -> defect-intelligence (predict) -> test-generation (for risky areas)",version:"1.0.0",tags:["defect","prevention","ai"],steps:[{id:"analyze-impact",name:"Analyze Code Impact",domain:"code-intelligence",action:"analyzeImpact",inputMapping:{changedFiles:"input.changedFiles"},outputMapping:{impactedFiles:"impact.files",impactedTests:"impact.tests",riskLevel:"impact.riskLevel"},timeout:6e4},{id:"predict-defects",name:"Predict Defects",domain:"defect-intelligence",action:"predictDefects",dependsOn:["analyze-impact"],inputMapping:{files:"results.impact.files"},outputMapping:{predictions:"defects.predictions",highRiskFiles:"defects.highRiskFiles"}},{id:"generate-targeted-tests",name:"Generate Targeted Tests",domain:"test-generation",action:"generateTests",dependsOn:["predict-defects"],condition:{path:"results.defects.highRiskFiles",operator:"exists",value:!0},inputMapping:{sourceFiles:"results.defects.highRiskFiles",priority:"input.priority"}}],triggers:[{eventType:"code-intelligence.ImpactAnalysisCompleted",inputMapping:{changedFiles:"event.changedFiles"}}]}}function oe(){return{id:"pre-release",name:"Pre-Release Workflow",description:"security-audit -> quality-gate -> deployment-advisor",version:"1.0.0",tags:["release","security","deployment"],steps:[{id:"security-audit",name:"Security Audit",domain:"security-compliance",action:"runAudit",inputMapping:{targetFiles:"input.targetFiles",includeDependencies:"input.includeDependencies"},outputMapping:{vulnerabilities:"security.vulnerabilities",riskScore:"security.riskScore",passed:"security.passed"},timeout:18e4},{id:"quality-gate",name:"Quality Gate Evaluation",domain:"quality-assessment",action:"evaluateGate",dependsOn:["security-audit"],inputMapping:{securityResults:"results.security",releaseCandidate:"input.releaseCandidate"},outputMapping:{passed:"quality.gatePassed",checks:"quality.checks"}},{id:"deployment-advice",name:"Get Deployment Advice",domain:"quality-assessment",action:"getDeploymentAdvice",dependsOn:["quality-gate"],inputMapping:{releaseCandidate:"input.releaseCandidate",qualityResults:"results.quality",securityResults:"results.security"},outputMapping:{decision:"deployment.decision",recommendations:"deployment.recommendations",riskScore:"deployment.riskScore"}}],triggers:[{eventType:"quality-assessment.QualityGateEvaluated",condition:{path:"event.passed",operator:"eq",value:!0}}]}}function se(){return{id:"continuous-learning",name:"Continuous Learning Workflow",description:"Collect patterns -> consolidate -> transfer -> optimize",version:"1.0.0",tags:["learning","optimization","ai"],steps:[{id:"collect-patterns",name:"Collect Patterns",domain:"learning-optimization",action:"runLearningCycle",inputMapping:{domain:"input.targetDomain"},outputMapping:{patternsLearned:"learning.patterns",experiencesProcessed:"learning.experiences"}},{id:"consolidate-patterns",name:"Consolidate Patterns",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["collect-patterns"],condition:{path:"results.learning.patterns",operator:"gt",value:0},outputMapping:{knowledgeShared:"consolidation.shared",domainsUpdated:"consolidation.domains"}},{id:"transfer-knowledge",name:"Transfer Knowledge",domain:"learning-optimization",action:"shareCrossDomainLearnings",dependsOn:["consolidate-patterns"],outputMapping:{transferSuccessRate:"transfer.successRate",newPatternsCreated:"transfer.newPatterns"}},{id:"optimize-strategies",name:"Optimize Strategies",domain:"learning-optimization",action:"optimizeAllStrategies",dependsOn:["transfer-knowledge"],outputMapping:{domainsOptimized:"optimization.domains",avgImprovement:"optimization.improvement"}}]}}function ae(){return{id:"morning-sync",name:"Morning Sync Protocol",description:"Daily quality synchronization across all domains",version:"1.0.0",tags:["protocol","daily","sync"],steps:[{id:"collect-metrics",name:"Collect Quality Metrics",domain:"quality-assessment",action:"analyzeQuality",inputMapping:{sourceFiles:"input.sourceFiles"},outputMapping:{score:"metrics.qualityScore"}},{id:"analyze-trends",name:"Analyze Coverage Trends",domain:"coverage-analysis",action:"getTrend",inputMapping:{timeRange:"input.timeRange",granularity:"input.granularity"},outputMapping:{trend:"trends.coverage",forecast:"trends.forecast"}},{id:"check-security",name:"Check Security Posture",domain:"security-compliance",action:"getSecurityPosture",outputMapping:{overallScore:"security.score",criticalIssues:"security.critical",recommendations:"security.recommendations"}},{id:"get-defect-predictions",name:"Get Defect Predictions",domain:"defect-intelligence",action:"predictDefects",inputMapping:{files:"input.changedFiles"},outputMapping:{predictions:"defects.predictions"}},{id:"generate-learning-report",name:"Generate Learning Dashboard",domain:"learning-optimization",action:"getLearningDashboard",dependsOn:["collect-metrics","analyze-trends","check-security","get-defect-predictions"],outputMapping:{learningRate:"learning.rate",topDomains:"learning.topDomains"}}]}}function le(){return{id:"qcsd-ideation-swarm",name:"QCSD Ideation Swarm",description:"Quality Conscious Software Delivery ideation phase: [url-extraction] -> [flag-detection] -> quality-criteria (HTSM) -> [testability, risk, requirements, security*, accessibility*, qx*] in parallel -> aggregated report. Supports live website URLs with conditional agent spawning based on HAS_UI, HAS_SECURITY, HAS_UX flags.",version:"3.0.0",tags:["qcsd","ideation","quality-criteria","htsm","shift-left","url-analysis"],steps:[{id:"website-content-extraction",name:"Website Content Extraction",domain:"requirements-validation",action:"extractWebsiteContent",inputMapping:{url:"input.url"},outputMapping:{extractedDescription:"extraction.description",extractedFeatures:"extraction.features",extractedAcceptanceCriteria:"extraction.acceptanceCriteria",detectedFlags:"extraction.flags",isWebsite:"extraction.isWebsite"},timeout:6e4,continueOnFailure:!0},{id:"quality-criteria-analysis",name:"HTSM Quality Criteria Analysis",domain:"requirements-validation",action:"analyzeQualityCriteria",dependsOn:["website-content-extraction"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{qualityCriteria:"qualityCriteria.criteria",qualityScore:"qualityCriteria.score"},timeout:18e4,retry:{maxAttempts:2,backoffMs:2e3}},{id:"testability-assessment",name:"Testability Scoring (10 Principles)",domain:"requirements-validation",action:"assessTestability",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{overallScore:"testability.overallScore",principles:"testability.principles",blockers:"testability.blockers",recommendations:"testability.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"risk-assessment",name:"Quality Risk Assessment",domain:"requirements-validation",action:"assessRisks",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType",description:"results.website-content-extraction.extractedDescription || input.description"},outputMapping:{overallRisk:"risks.overallRisk",riskScore:"risks.riskScore",factors:"risks.factors",mitigations:"risks.mitigations"},timeout:9e4,continueOnFailure:!0},{id:"requirements-validation",name:"Requirements & Acceptance Criteria Validation",domain:"requirements-validation",action:"validateRequirements",dependsOn:["quality-criteria-analysis"],inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",acceptanceCriteria:"results.website-content-extraction.extractedAcceptanceCriteria || input.acceptanceCriteria"},outputMapping:{valid:"requirements.valid",issues:"requirements.issues",suggestions:"requirements.suggestions"},timeout:9e4,continueOnFailure:!0},{id:"security-threat-modeling",name:"Early Security Threat Modeling (STRIDE)",domain:"security-compliance",action:"modelSecurityThreats",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",description:"results.website-content-extraction.extractedDescription || input.description",securityCritical:"results.website-content-extraction.detectedFlags.hasSecurity || input.securityCritical"},outputMapping:{threats:"security.threats",overallRisk:"security.overallRisk",recommendations:"security.recommendations"},timeout:12e4,continueOnFailure:!0},{id:"accessibility-audit",name:"Accessibility Audit (WCAG 2.2)",domain:"visual-accessibility",action:"auditAccessibility",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUI || input.hasUI",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{wcagLevel:"accessibility.wcagLevel",violations:"accessibility.violations",recommendations:"accessibility.recommendations"},timeout:18e4,continueOnFailure:!0},{id:"quality-experience-analysis",name:"Quality Experience Analysis (QX Partner)",domain:"coordination",action:"analyzeQualityExperience",dependsOn:["quality-criteria-analysis"],condition:{path:"results.website-content-extraction.detectedFlags.hasUX || input.hasUX",operator:"eq",value:!0},inputMapping:{targetId:"input.targetId",url:"input.url",description:"results.website-content-extraction.extractedDescription || input.description",features:"results.website-content-extraction.extractedFeatures"},outputMapping:{journeys:"qx.journeys",frictionPoints:"qx.frictionPoints",recommendations:"qx.recommendations"},timeout:15e4,continueOnFailure:!0},{id:"aggregate-ideation-report",name:"Generate Ideation Report",domain:"requirements-validation",action:"generateIdeationReport",dependsOn:["quality-criteria-analysis","testability-assessment","risk-assessment","requirements-validation","security-threat-modeling","accessibility-audit","quality-experience-analysis"],inputMapping:{targetId:"input.targetId",targetType:"input.targetType"},outputMapping:{report:"ideation.report",readyForDevelopment:"ideation.readyForDevelopment",blockers:"ideation.blockers",recommendations:"ideation.recommendations",testStrategy:"ideation.testStrategy"},timeout:6e4},{id:"store-ideation-learnings",name:"Store Ideation Learnings",domain:"learning-optimization",action:"storeIdeationLearnings",dependsOn:["aggregate-ideation-report"],inputMapping:{targetId:"input.targetId",report:"results.ideation.report"},outputMapping:{stored:"learning.stored",patternId:"learning.patternId"},continueOnFailure:!0}],triggers:[{eventType:"requirements-validation.EpicCreated",inputMapping:{targetId:"event.epicId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}},{eventType:"requirements-validation.SprintPlanningStarted",inputMapping:{targetId:"event.sprintId",targetType:"event.type",description:"event.description",acceptanceCriteria:"event.acceptanceCriteria"}}]}}var _=class{constructor(e,t,i,r={}){this.eventBus=e;this.memory=t;this.agentCoordinator=i;this.config={...O,...r}}eventBus;memory;agentCoordinator;config;workflows=new Map;executions=new Map;actionRegistry={};eventSubscriptions=[];approvalGates=new Map;initialized=!1;async initialize(){this.initialized||(this.registerBuiltInWorkflows(),this.config.enableEventTriggers&&this.setupEventTriggers(),await this.loadPersistedWorkflows(),this.initialized=!0)}async dispose(){for(let e of this.executions.values())e.status==="running"&&await this.cancelWorkflow(e.executionId);for(let e of this.eventSubscriptions)e.unsubscribe();await this.persistWorkflows(),this.initialized=!1}registerWorkflow(e){try{let t=this.validateWorkflowDefinition(e);return t.success?(this.workflows.set(e.id,e),this.config.enableEventTriggers&&e.triggers&&this.registerWorkflowTriggers(e),y(void 0)):t}catch(t){return d(M(t))}}unregisterWorkflow(e){if(!this.workflows.has(e))return d(new Error(`Workflow not found: ${e}`));let t=Array.from(this.executions.values()).filter(i=>i.workflowId===e&&i.status==="running");return t.length>0?d(new Error(`Cannot unregister workflow with ${t.length} active execution(s)`)):(this.workflows.delete(e),y(void 0))}async executeWorkflow(e,t={},i){let r=this.workflows.get(e);if(!r)return d(new Error(`Workflow not found: ${e}`));if(Array.from(this.executions.values()).filter(f=>f.status==="running").length>=this.config.maxConcurrentWorkflows)return d(new Error(`Maximum concurrent workflows (${this.config.maxConcurrentWorkflows}) reached`));let a=q(),n=new Date,c={input:t,results:{},metadata:{executionId:a,workflowId:e,correlationId:i||a,startedAt:n}},l={executionId:a,workflowId:e,workflowName:r.name,status:"running",startedAt:n,progress:0,currentSteps:[],completedSteps:[],failedSteps:[],skippedSteps:[],context:c,stepResults:new Map,parallelCompositionReceipts:[]};return this.executions.set(a,l),await this.publishWorkflowStarted(l,r),this.runWorkflow(r,l).catch(async f=>{l.status="failed",l.error=k(f),l.completedAt=new Date,l.duration=l.completedAt.getTime()-n.getTime(),await this.publishWorkflowFailed(l,"unknown",String(f))}),y(a)}getWorkflowStatus(e){return this.executions.get(e)}async cancelWorkflow(e){let t=this.executions.get(e);return t?t.status!=="running"&&t.status!=="paused"?d(new Error(`Cannot cancel workflow in status: ${t.status}`)):(t.status="cancelled",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime(),this.closeApprovalGates(e,"Workflow cancelled"),await this.publishEvent(v.WorkflowCancelled,{executionId:e,workflowId:t.workflowId,workflowName:t.workflowName},t.context.metadata.correlationId),y(void 0)):d(new Error(`Execution not found: ${e}`))}async pauseWorkflow(e){let t=this.executions.get(e);return t?t.status!=="running"?d(new Error(`Cannot pause workflow in status: ${t.status}`)):(t.status="paused",y(void 0)):d(new Error(`Execution not found: ${e}`))}async resumeWorkflow(e){let t=this.executions.get(e);if(!t)return d(new Error(`Execution not found: ${e}`));if(t.status!=="paused")return d(new Error(`Cannot resume workflow in status: ${t.status}`));let i=this.workflows.get(t.workflowId);return i?(t.status="running",this.runWorkflow(i,t).catch(async r=>{t.status="failed",t.error=k(r)}),y(void 0)):d(new Error(`Workflow definition not found: ${t.workflowId}`))}listWorkflows(){return Array.from(this.workflows.values()).map(e=>({id:e.id,name:e.name,description:e.description,version:e.version,stepCount:e.steps.length,tags:e.tags,triggers:e.triggers?.map(t=>t.eventType)}))}getActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.status==="running"||e.status==="paused")}getWorkflow(e){return this.workflows.get(e)}approveStep(e,t){let i=`${e}:${t}`,r=this.approvalGates.get(i);return r?(r.resolve({approved:!0}),this.approvalGates.delete(i),!0):!1}rejectStep(e,t,i){let r=`${e}:${t}`,o=this.approvalGates.get(r);return o?(o.resolve({approved:!1,reason:i}),this.approvalGates.delete(r),!0):!1}isActionRegistered(e,t){return this.lookupAction(e,t)!==void 0}lookupAction(e,t){let i=Object.hasOwn(this.actionRegistry,e)?this.actionRegistry[e]:void 0;return i&&Object.hasOwn(i,t)?i[t]:void 0}getRegisteredActions(e){return Object.keys(this.actionRegistry[e]||{})}getDomainsWithActions(){return Object.keys(this.actionRegistry)}async spawnWorkflowAgent(e,t,i){return this.agentCoordinator.canSpawn()?this.agentCoordinator.spawn({name:`workflow-agent-${e.slice(0,8)}-${t}`,domain:i,type:"coordinator",capabilities:["workflow-execution",t],config:{workflowId:e,stepId:t}}):d(new Error("Agent limit reached"))}async stopWorkflowAgent(e){return this.agentCoordinator.stop(e)}getAvailableAgentCapacity(){return this.agentCoordinator.canSpawn()?this.config.maxConcurrentWorkflows-this.getActiveExecutions().length:0}registerAction(e,t,i){let r=["__proto__","constructor","prototype"];if(r.includes(e)||r.includes(t))throw new Error("Invalid domain or action name: contains dangerous prototype key");this.actionRegistry[e]||(this.actionRegistry[e]={}),this.actionRegistry[e][t]=i}async executeFromBehaviorTree(e){let t=new Date;try{let i=await e.tick(),r=new Date,o=r.getTime()-t.getTime();return{status:i==="SUCCESS"?"completed":i==="RUNNING"?"running":"failed",startedAt:t,completedAt:r,duration:o,treeStatus:i,treeName:e.name}}catch(i){let r=new Date,o=r.getTime()-t.getTime();return{status:"failed",startedAt:t,completedAt:r,duration:o,treeStatus:"FAILURE",treeName:e.name,error:k(i)}}}async runWorkflow(e,t){let i=e.timeout||this.config.defaultWorkflowTimeout,r,o=new Promise((a,n)=>{r=setTimeout(()=>n(new Error(`Workflow timeout after ${i}ms`)),i)});try{await Promise.race([this.executeSteps(e,t),o]),t.status==="running"&&(t.status="completed",t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime(),t.progress=100,await this.publishWorkflowCompleted(t))}catch(a){if(t.status==="running"){t.status="failed",t.error=k(a),this.closeApprovalGates(t.executionId,"Workflow failed"),t.completedAt=new Date,t.duration=t.completedAt.getTime()-t.startedAt.getTime();let n=t.currentSteps[0]||"unknown";t.currentSteps=[],await this.publishWorkflowFailed(t,n,k(a))}}finally{r&&clearTimeout(r)}this.config.persistExecutions&&await this.persistExecution(t)}async executeSteps(e,t){let i=e.steps,r=new Set(t.completedSteps),o=new Set(t.skippedSteps),a=new Set(t.failedSteps),n=i.filter(c=>!r.has(c.id)&&!o.has(c.id)&&!a.has(c.id));for(;n.length>0&&t.status==="running";){let c=n.filter(u=>(u.dependsOn||[]).every(m=>r.has(m)||o.has(m)));if(c.length===0)break;let l=c.filter(u=>!u.dependsOn?.length),f=c.filter(u=>u.dependsOn?.length);if(l.length===1&&f.unshift(l[0]),l.length>1){t.currentSteps=l.map(p=>p.id);let u={version:1,workflowId:e.id,workflowRevision:`${e.version}:${A(e)}`,executionId:t.executionId,groupId:l.map(p=>p.id).join("|"),steps:[],conflicts:[],strategy:"rejected",disposition:"invalid"};t.parallelCompositionReceipts??=[],t.parallelCompositionReceipts.push(u);try{u.steps=l.map(p=>({stepId:p.id,disposition:"not_started",writes:R(p).map(g=>g.path)})),u.conflicts=j(l)}catch(p){throw new Error(`parallel_output_invalid_path: ${k(p)}`)}if(u.conflicts.length>0)throw u.disposition="conflict",new Error(`parallel_output_conflict: ${u.conflicts.map(p=>`${p.stepA}.${p.pathA} \u2194 ${p.stepB}.${p.pathB}`).join(", ")}`);let w=L(l);if(w.length>0)throw new Error(`parallel_dependency_error: ${w.map(p=>`${p.stepId} reads ${p.sourcePath} from concurrent step ${p.otherStepId}`).join(", ")}`);let m,b,h;try{m=structuredClone(t.context),h=A(m.results),b=l.map(()=>structuredClone(m))}catch(p){throw new Error(`parallel_context_uncloneable: ${k(p)}`)}let F=await Promise.allSettled(l.map((p,g)=>this.executeStep(p,t,e,b[g],!0))),D;for(let p=0;p<l.length;p++){let g=l[p],W=F[p];if(W.status==="fulfilled"){let C=W.value;if(t.stepResults.set(g.id,C),C.status==="completed"){r.add(g.id),t.completedSteps.push(g.id),u.steps[p].disposition="succeeded";try{u.steps[p].outputHash=A(C.output)}catch(U){throw new Error(`parallel_output_unhashable: ${k(U)}`)}}else C.status==="skipped"?(o.add(g.id),t.skippedSteps.push(g.id),u.steps[p].disposition="skipped"):C.status==="failed"&&(a.add(g.id),t.failedSteps.push(g.id),u.steps[p].disposition="failed",g.continueOnFailure||(D??=C.error??"Unknown error"))}else a.add(g.id),t.failedSteps.push(g.id),u.steps[p].disposition="failed",g.continueOnFailure||(D??=k(W.reason));let E=n.indexOf(g);E!==-1&&n.splice(E,1)}if(t.status!=="running"||D!==void 0){if(u.disposition="partial",D!==void 0)throw new Error(D);if(t.status!=="running")return}else try{let p={...m,results:structuredClone(m.results)};for(let W=0;W<l.length;W++){let E=F[W];E.status==="fulfilled"&&E.value.status==="completed"&&this.mapStepOutput(l[W],E.value.output,p)}let g=A(p.results);if(t.status!=="running"){u.disposition="partial";return}if(A(t.context.results)!==h)throw new Error("parallel_context_changed: shared results changed before composition");t.context.results=p.results,u.combinedStateHash=g,u.strategy="disjoint",u.disposition="composed"}catch(p){throw u.disposition="invalid",new Error(`parallel_output_invalid: ${k(p)}`)}}for(let u of f){if(t.status!=="running")break;t.currentSteps=[u.id];let w=await this.executeStep(u,t,e);if(w.status==="completed")r.add(u.id),t.completedSteps.push(u.id);else if(w.status==="skipped")o.add(u.id),t.skippedSteps.push(u.id);else if(w.status==="failed"&&(a.add(u.id),t.failedSteps.push(u.id),!u.continueOnFailure)){t.status="failed",t.error=w.error;return}let m=n.indexOf(u);m!==-1&&n.splice(m,1)}let S=i.length,I=r.size+o.size+a.size;t.progress=Math.round(I/S*100)}t.currentSteps=[]}async executeStep(e,t,i,r=t.context,o=!1){let a=new Date,n={stepId:e.id,status:"pending",startedAt:a};try{if(e.skipCondition&&this.evaluateCondition(e.skipCondition,r))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;if(e.condition&&!this.evaluateCondition(e.condition,r))return n.status="skipped",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepSkipped(t,e),n;n.status="running",await this.publishStepStarted(t,e);let c=this.buildStepInput(e,r);if(e.approval){n.status="awaiting_approval",t.stepResults.set(e.id,n);let u=await this.waitForApproval(e,t);if(!u.approved||t.status!=="running")return n.status="failed",n.error=u.reason||"Step rejected at approval gate",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),await this.publishStepFailed(t,e,n.error),n;n.status="running"}let l,f=e.retry?.maxAttempts||1,S=e.retry?.backoffMs||1e3,I=e.retry?.backoffMultiplier||2;for(let u=1;u<=f;u++){n.retryCount=u-1;try{let w=e.timeout||this.config.defaultStepTimeout,m=await this.executeStepAction(e,c,r,w);o||this.mapStepOutput(e,m,r);let b;try{b=o?structuredClone(m):m}catch(h){throw new Error(`parallel_output_uncloneable: ${k(h)}`)}return n.status="completed",n.output=b,n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepCompleted(t,e,n),n}catch(w){if(l=M(w),l.message.startsWith("parallel_output_uncloneable:"))break;u<f&&(await this.delay(S),S*=I)}}return n.status="failed",n.error=l?.message||"Unknown error",n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),e.rollback&&await this.executeRollback(e.rollback,r),await this.publishStepFailed(t,e,n.error),n}catch(c){return n.status="failed",n.error=k(c),n.completedAt=new Date,n.duration=n.completedAt.getTime()-a.getTime(),o||t.stepResults.set(e.id,n),await this.publishStepFailed(t,e,n.error),n}}async executeStepAction(e,t,i,r){let o=new Promise((c,l)=>{setTimeout(()=>l(new Error(`Step timeout after ${r}ms`)),r)}),a=B(e.domain,e.action);if(a){let c=await Promise.race([a.execute(t,i),o]);if(!c.success)throw c.error;return c.value}let n=this.lookupAction(e.domain,e.action);if(n){let c=await Promise.race([n(t,i),o]);if(!c.success)throw c.error;return c.value}throw new Error(`Action '${e.action}' not registered for domain '${e.domain}'. Register it using orchestrator.registerAction('${e.domain}', '${e.action}', handler)`)}async executeRollback(e,t){try{let i=this.lookupAction(e.domain,e.action);if(!i){console.warn(`Rollback action '${e.action}' not registered for domain '${e.domain}'. Skipping rollback.`);return}let r=await i(e.input||{},t);r.success||console.error(`Rollback failed for ${e.domain}.${e.action}:`,r.error)}catch(i){console.error(`Rollback failed for ${e.domain}.${e.action}:`,i)}}buildStepInput(e,t){let i={};if(e.inputMapping)for(let[r,o]of Object.entries(e.inputMapping)){let a=this.getValueByPath(t,o);a!==void 0&&(i[r]=a)}return i}mapStepOutput(e,t,i){if(Object.defineProperty(i.results,e.id,{value:t,writable:!0,enumerable:!0,configurable:!0}),e.outputMapping&&typeof t=="object"&&t!==null)for(let[r,o]of Object.entries(e.outputMapping)){let a=this.getValueByPath(t,r);a!==void 0&&this.setValueByPath(i.results,o,a)}}getValueByPath(e,t){let i=t.split("."),r=e;for(let o of i){if(r==null)return;if(typeof r=="object"&&Object.hasOwn(r,o))r=r[o];else return}return r}setValueByPath(e,t,i){let r=t.split("."),o=new Set(["__proto__","constructor","prototype"]);for(let c of r)if(o.has(c))throw new Error("Invalid path: contains dangerous prototype key");let a=e;for(let c=0;c<r.length-1;c++){let l=r[c];Object.hasOwn(a,l)||Object.defineProperty(a,l,{value:Object.create(null),writable:!0,enumerable:!0,configurable:!0}),a=a[l]}let n=r[r.length-1];Object.defineProperty(a,n,{value:i,writable:!0,enumerable:!0,configurable:!0})}evaluateCondition(e,t){let i=this.getValueByPath(t,e.path);switch(e.operator){case"eq":return i===e.value;case"neq":return i!==e.value;case"gt":return typeof i=="number"&&i>e.value;case"gte":return typeof i=="number"&&i>=e.value;case"lt":return typeof i=="number"&&i<e.value;case"lte":return typeof i=="number"&&i<=e.value;case"contains":return Array.isArray(i)?i.includes(e.value):typeof i=="string"?i.includes(String(e.value)):!1;case"exists":return i!=null;default:return!1}}async publishEvent(e,t,i){let r=$(e,"learning-optimization",t,i);await this.eventBus.publish(r)}async publishWorkflowStarted(e,t){await this.publishEvent(v.WorkflowStarted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,stepCount:t.steps.length},e.context.metadata.correlationId)}async publishWorkflowCompleted(e){await this.publishEvent(v.WorkflowCompleted,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,duration:e.duration||0,completedSteps:e.completedSteps.length,skippedSteps:e.skippedSteps.length},e.context.metadata.correlationId)}async publishWorkflowFailed(e,t,i){await this.publishEvent(v.WorkflowFailed,{executionId:e.executionId,workflowId:e.workflowId,workflowName:e.workflowName,failedStep:t,error:i},e.context.metadata.correlationId)}async publishStepStarted(e,t){await this.publishEvent(v.StepStarted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}async publishStepCompleted(e,t,i){await this.publishEvent(v.StepCompleted,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,duration:i.duration},e.context.metadata.correlationId)}async publishStepFailed(e,t,i){await this.publishEvent(v.StepFailed,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain,error:i},e.context.metadata.correlationId)}async publishStepSkipped(e,t){await this.publishEvent(v.StepSkipped,{executionId:e.executionId,workflowId:e.workflowId,stepId:t.id,stepName:t.name,domain:t.domain},e.context.metadata.correlationId)}validateWorkflowDefinition(e){if(!e.id)return d(new Error("Workflow ID is required"));if(!e.name)return d(new Error("Workflow name is required"));if(!e.steps||e.steps.length===0)return d(new Error("Workflow must have at least one step"));let t=new Set;for(let r of e.steps){if(!r.id)return d(new Error("Step ID is required"));if(t.has(r.id))return d(new Error(`Duplicate step ID: ${r.id}`));if(t.add(r.id),!r.domain)return d(new Error(`Step ${r.id} must have a domain`));if(!N.includes(r.domain))return d(new Error(`Invalid domain for step ${r.id}: ${r.domain}`));if(!r.action)return d(new Error(`Step ${r.id} must have an action`));if(r.approval&&typeof r.approval=="object"){let{expiresAfter:o,autoApproveAfter:a}=r.approval;if(o!==void 0&&a!==void 0)return d(new Error(`Step ${r.id} sets both approval expiry fields`));let n=o??a;if(n!==void 0&&(!Number.isSafeInteger(n)||n<0||n>2147483647))return d(new Error(`Step ${r.id} has an invalid approval expiry`))}if(r.dependsOn){for(let o of r.dependsOn)if(!e.steps.some(a=>a.id===o))return d(new Error(`Step ${r.id} depends on unknown step: ${o}`))}}let i=this.detectCircularDependencies(e.steps);return i?d(new Error(`Circular dependency detected: ${i}`)):y(void 0)}detectCircularDependencies(e){let t=new Set,i=new Set,r=(o,a)=>{if(i.has(o))return[...a,o].join(" -> ");if(t.has(o))return null;t.add(o),i.add(o);let n=e.find(c=>c.id===o);if(n?.dependsOn)for(let c of n.dependsOn){let l=r(c,[...a,o]);if(l)return l}return i.delete(o),null};for(let o of e){let a=r(o.id,[]);if(a)return a}return null}setupEventTriggers(){let e=this.eventBus.subscribe("*",async t=>{await this.handleEventForTriggers(t)});this.eventSubscriptions.push(e)}registerWorkflowTriggers(e){}async handleEventForTriggers(e){for(let t of this.workflows.values())if(t.triggers)for(let i of t.triggers){if(i.eventType!==e.type||i.sourceDomain&&i.sourceDomain!==e.source)continue;if(i.condition){let o={input:{event:e.payload},results:{},metadata:{executionId:"",workflowId:t.id,startedAt:new Date}};if(!this.evaluateCondition(i.condition,o))continue}let r={};if(i.inputMapping)for(let[o,a]of Object.entries(i.inputMapping)){let n=this.getValueByPath({event:e.payload},a);n!==void 0&&(r[o]=n)}else r.triggerEvent=e.payload;await this.executeWorkflow(t.id,r,e.correlationId)}}registerBuiltInWorkflows(){let e=z();for(let t of e)this.registerWorkflow(t)}async loadPersistedWorkflows(){try{let e=await this.memory.search("workflow:definition:*",100);for(let t of e){let i=await this.memory.get(t);i&&!this.workflows.has(i.id)&&this.workflows.set(i.id,i)}}catch(e){console.error("Failed to load persisted workflows:",e)}}async persistWorkflows(){try{for(let e of this.workflows.values())G.includes(e.id)||await this.memory.set(`workflow:definition:${e.id}`,e,{namespace:"coordination",persist:!0})}catch(e){console.error("Failed to persist workflows:",e)}}async persistExecution(e){try{let t={...e,stepResults:Object.fromEntries(e.stepResults)};await this.memory.set(`workflow:execution:${e.executionId}`,t,{namespace:"coordination",ttl:86400*7})}catch(t){console.error("Failed to persist execution:",t)}}closeApprovalGates(e,t){for(let[i,r]of this.approvalGates.entries())i.startsWith(`${e}:`)&&r.resolve({approved:!1,reason:t})}async waitForApproval(e,t){if(t.status!=="running")return{approved:!1,reason:`Workflow is ${t.status}`};let i=typeof e.approval=="object"?e.approval:{},r=i.expiresAfter??i.autoApproveAfter??3e5,o=i.message??`Awaiting approval for step: ${e.name}`;if(!Number.isSafeInteger(r)||r<0||r>2147483647)return{approved:!1,reason:"Invalid approval expiry"};let a=`${t.executionId}:${e.id}`,n,c=new Promise(l=>{let f={resolve:S=>{this.approvalGates.get(a)===f&&(this.approvalGates.delete(a),n&&clearTimeout(n),l(S))}};this.approvalGates.set(a,f),r>0&&(n=setTimeout(()=>{f.resolve({approved:!1,reason:"Approval expired"})},r))});try{await this.publishEvent(v.StepAwaitingApproval,{executionId:t.executionId,workflowId:t.workflowId,stepId:e.id,stepName:e.name,domain:e.domain,message:o,expiresAfter:r>0?r:void 0},t.context.metadata.correlationId)}catch(l){throw this.approvalGates.get(a)?.resolve({approved:!1,reason:"Approval event failed"}),l}return c}delay(e){return new Promise(t=>setTimeout(t,e))}};function Re(s,e,t,i){return new _(s,e,t,i)}export{v as a,O as b,T as c,_ as d,Re as e};
@@ -1,29 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{i as j}from"./chunk-XPTCQKVE.js";import{C as me,g as w,h as E,i as k,w as ue}from"./chunk-NZJVDOUN.js";import{a as Te,b as _,d as ee}from"./chunk-CMN7PU2H.js";import{c as le,d as Re}from"./chunk-LRKLATSH.js";import{a as de,d as Pe}from"./chunk-ZP5AWQRO.js";import{a as v}from"./chunk-TIVKDIF7.js";import{c as b}from"./chunk-DS5IFRY6.js";import{c as I}from"./chunk-GPPTRKEM.js";import{d as T,e as z}from"./chunk-SFITYZLV.js";import{a as d,b as L,e as P}from"./chunk-J7Q5TXFZ.js";import{e as Ce}from"./chunk-Z7SKUC6P.js";var A={cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},environment:process.env.AQE_ENV||"all",batchSize:1e3,sources:[{name:"qe-patterns",cloudTable:"aqe.qe_patterns",localTable:"qe_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","embedding","sync_version"],transforms:{reusable:"boolean-to-int"}},{name:"sona-patterns",cloudTable:"aqe.sona_patterns",localTable:"sona_patterns",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],transforms:{is_active:"boolean-to-int",requires_fine_tuning:"boolean-to-int"}},{name:"goap-actions",cloudTable:"aqe.goap_actions",localTable:"goap_actions",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{duration_estimate:"estimated_duration_ms"}},{name:"goap-plans",cloudTable:"aqe.goap_plans",localTable:"goap_plans",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{estimated_duration:"estimated_duration_ms"}},{name:"memory-entries",cloudTable:"aqe.memory_entries",localTable:"kv_store",enabled:!0,priority:"high",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}},{name:"learning-experiences",cloudTable:"aqe.learning_experiences",localTable:"captured_experiences",enabled:!0,priority:"high",mode:"append",dropColumns:["id","source_env","sync_version"],columnMap:{agent_id:"agent",task_id:"task",task_type:"domain",state:"result_json",action:"steps_json",reward:"quality",next_state:"routing_json",episode_id:"tags",created_at:"started_at"}},{name:"qlearning-patterns",cloudTable:"aqe.qlearning_patterns",localTable:"rl_q_values",enabled:!0,priority:"medium",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{state:"state_key",action:"action_key",last_update:"updated_at"}},{name:"routing-outcomes",cloudTable:"aqe.routing_outcomes",localTable:"routing_outcomes",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version"]},{name:"qe-trajectories",cloudTable:"aqe.qe_trajectories",localTable:"qe_trajectories",enabled:!0,priority:"medium",mode:"append",dropColumns:["source_env","sync_version","embedding"]},{name:"dream-insights",cloudTable:"aqe.dream_insights",localTable:"dream_insights",enabled:!0,priority:"low",mode:"append",dropColumns:["source_env","sync_version"]},{name:"claude-flow-memory",cloudTable:"aqe.claude_flow_memory",localTable:"kv_store",enabled:!0,priority:"low",mode:"incremental",dropColumns:["source_env","sync_version"],columnMap:{partition:"namespace"}}]},ve={TEXT:"TEXT",INTEGER:"INTEGER",REAL:"REAL",BLOB:"BYTEA",NULL:"NULL"},x={local:{v3MemoryDb:"./.agentic-qe/memory.db",rootMemoryDb:"./.agentic-qe/memory.db",claudeFlowMemory:"./.claude-flow/memory/store.json",claudeFlowDaemon:"./.claude-flow/daemon-state.json",claudeFlowMetrics:"./.claude-flow/metrics/",intelligenceJson:"./.ruvector/intelligence.json",swarmMemoryDb:"./.swarm/memory.db",v2PatternsDb:""},cloud:{project:process.env.GCP_PROJECT||"",zone:process.env.GCP_ZONE||"",instance:process.env.GCP_INSTANCE||"",database:process.env.GCP_DATABASE||"",user:process.env.GCP_USER||"",tunnelPort:parseInt(process.env.GCP_TUNNEL_PORT||"15432",10)},sync:{mode:"incremental",interval:"1h",batchSize:1e3,conflictResolution:"newer-wins",sourcePriority:{qePatterns:1,sonaPatterns:2,goapActions:3,kvStore:4,experiences:5,claudeFlowMemory:6,intelligenceJson:7},sources:[{name:"root-qe-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_patterns",priority:"high",mode:"incremental",query:"SELECT id, pattern_type, qe_domain, domain, name, description, confidence, usage_count, success_rate, quality_score, tier, template_json, context_json, successful_uses, created_at, updated_at, last_used_at, tokens_used, input_tokens, output_tokens, latency_ms, reusable, reuse_count, average_token_savings, total_tokens_saved FROM qe_patterns",enabled:!0},{name:"root-sona-patterns",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.sona_patterns",priority:"high",mode:"incremental",query:"SELECT * FROM sona_patterns",enabled:!0},{name:"root-goap-actions",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_actions",priority:"high",mode:"incremental",query:"SELECT * FROM goap_actions",enabled:!0},{name:"root-kv-store",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.memory_entries",priority:"high",mode:"incremental",query:"SELECT key, namespace as partition, CASE WHEN json_valid(value) THEN value ELSE json_quote(value) END as value, created_at, expires_at FROM kv_store WHERE json_valid(value) OR json_valid(json_quote(value))",enabled:!0},{name:"root-captured-experiences",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.learning_experiences",priority:"high",mode:"append",query:"SELECT agent as agent_id, task as task_id, domain as task_type, COALESCE(result_json, '{}') as state, COALESCE(steps_json, '{}') as action, quality as reward, COALESCE(routing_json, '{}') as next_state, tags as episode_id, started_at as created_at FROM captured_experiences",enabled:!0},{name:"root-goap-plans",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.goap_plans",priority:"medium",mode:"incremental",query:"SELECT id, goal_id, action_sequence as sequence, initial_state, goal_state, action_sequence, total_cost, estimated_duration_ms as estimated_duration, status, created_at, completed_at FROM goap_plans",enabled:!0},{name:"root-rl-q-values",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qlearning_patterns",priority:"medium",mode:"incremental",query:"SELECT DISTINCT state_key as state, action_key as action, q_value, visits, updated_at as last_update, created_at FROM rl_q_values GROUP BY state_key, action_key",enabled:!0},{name:"root-routing-outcomes",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.routing_outcomes",priority:"medium",mode:"append",query:"SELECT * FROM routing_outcomes",enabled:!0},{name:"root-qe-trajectories",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.qe_trajectories",priority:"medium",mode:"append",query:"SELECT * FROM qe_trajectories",enabled:!0},{name:"root-dream-insights",type:"sqlite",path:"./.agentic-qe/memory.db",targetTable:"aqe.dream_insights",priority:"low",mode:"append",query:"SELECT * FROM dream_insights",enabled:!0},{name:"claude-flow-memory",type:"json",path:"./.claude-flow/memory/store.json",targetTable:"aqe.claude_flow_memory",priority:"medium",mode:"full",enabled:!0},{name:"intelligence-qlearning",type:"json",path:"./.ruvector/intelligence.json",targetTable:"aqe.qlearning_patterns",priority:"low",mode:"full",jsonPath:"$.qvalues",enabled:!0}]},environment:process.env.AQE_ENV||"devpod"};z();k();ee();P();v();import*as te from"fs";import*as ge from"path";var F=b.create("sqlite-reader"),W=class{name;type="sqlite";db=null;config;dbPath;constructor(e){this.config=e,this.name=e.source.name,this.dbPath=ge.resolve(e.baseDir,e.source.path)}async initialize(){if(!this.db){if(!te.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}`);try{this.db=T(this.dbPath,{readonly:!0}),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),console.log(`[SQLiteReader:${this.name}] Initialized: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async readAll(){if(!this.db)throw new Error("Reader not initialized");let e=this.config.source.query||`SELECT * FROM ${w(this.getTableName())}`;try{return this.tableExists(this.getTableName())?this.db.prepare(e).all().map(r=>this.transformRecord(r)):(console.warn(`[SQLiteReader:${this.name}] Table not found, returning empty`),[])}catch(t){throw new Error(`Failed to read from ${this.name}: ${d(t)}`)}}async readChanged(e){if(!this.db)throw new Error("Reader not initialized");let t=this.findTimestampColumn();if(!t)return console.warn(`[SQLiteReader:${this.name}] No timestamp column found, falling back to readAll`),this.readAll();let n=this.getTableName();if(!this.tableExists(n))return[];let r=e.toISOString(),i=`SELECT * FROM ${w(n)} WHERE ${t} > ?`;try{return this.db.prepare(i).all(r).map(a=>this.transformRecord(a))}catch{return console.warn(`[SQLiteReader:${this.name}] Changed query failed, falling back to readAll`),this.readAll()}}async count(){if(!this.db)throw new Error("Reader not initialized");let e=this.getTableName();if(!this.tableExists(e))return 0;try{return this.db.prepare(`SELECT COUNT(*) as count FROM ${w(e)}`).get().count}catch(t){return F.debug("Record count query failed",{table:e,error:d(t)}),0}}async close(){this.db&&(this.db.close(),this.db=null,console.log(`[SQLiteReader:${this.name}] Closed`))}getTableName(){let e=this.config.source.query;if(e){let r=e.match(/FROM\s+(\w+)/i);if(r)return r[1]}let n=this.config.source.targetTable.split(".");return n[n.length-1]}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch(t){return F.debug("Table existence check failed",{table:e,error:t instanceof Error?t.message:String(t)}),!1}}findTimestampColumn(){if(!this.db)return null;let e=this.getTableName(),t=["updated_at","created_at","timestamp","last_used_at","modified_at"];try{let i=this.db.prepare(`PRAGMA table_info(${w(e)})`).all().map(o=>o.name.toLowerCase());for(let o of t)if(i.includes(o))return o}catch(n){return F.debug("Timestamp column detection failed",{table:e,error:n instanceof Error?n.message:String(n)}),null}return null}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t)){if(typeof r=="string"&&this.looksLikeJson(r))try{t[n]=_(r)}catch(i){F.debug("JSON parse failed for record field",{key:n,error:i instanceof Error?i.message:String(i)})}if(n.endsWith("_at")&&typeof r=="number"&&(t[n]=new Date(r).toISOString()),r instanceof Buffer)if(n.includes("embedding")){let i=e.dimension||384;t[n]=Array.from(new Float32Array(r.buffer,r.byteOffset,i))}else t[n]=r.toString("base64")}return t}looksLikeJson(e){if(!e)return!1;let t=e.trim();return t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")}getInfo(){let e=te.existsSync(this.dbPath),t=[];if(e&&this.db)try{t=this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(r=>r.name)}catch(n){console.debug("[SQLiteReader] Table listing error:",n instanceof Error?n.message:n)}return{path:this.dbPath,exists:e,tables:t}}};function re(l){return new W(l)}var he=Ce(Te(),1);P();import{randomUUID as _e}from"crypto";import*as C from"fs";import*as pe from"path";var U=class{name;type="json";config;filePath;data=null;fileModTime=null;constructor(e){this.config=e,this.name=e.source.name,this.filePath=pe.resolve(e.baseDir,e.source.path)}async initialize(){if(!C.existsSync(this.filePath)){console.warn(`[JSONReader:${this.name}] File not found: ${this.filePath}`),this.data=[];return}let e=C.statSync(this.filePath);this.fileModTime=e.mtime,console.log(`[JSONReader:${this.name}] Initialized: ${this.filePath}`)}async readAll(){if(!C.existsSync(this.filePath))return[];try{let e=C.readFileSync(this.filePath,"utf-8"),t=he.default.parse(e);return this.extractRecords(t).map(r=>this.transformRecord(r))}catch(e){return console.error(`[JSONReader:${this.name}] Failed to read: ${d(e)}`),[]}}async readChanged(e){return C.existsSync(this.filePath)?C.statSync(this.filePath).mtime<=e?[]:this.readAll():[]}async count(){return(await this.readAll()).length}async close(){this.data=null,this.fileModTime=null,console.log(`[JSONReader:${this.name}] Closed`)}extractRecords(e){return this.config.source.jsonPath?this.extractByPath(e,this.config.source.jsonPath):this.name.includes("claude-flow-memory")?this.extractClaudeFlowMemory(e):this.name.includes("intelligence")||this.name.includes("qlearning")?this.extractIntelligence(e):this.name.includes("daemon")?this.extractDaemonState(e):Array.isArray(e)?e:typeof e=="object"&&e!==null?Object.entries(e).map(([n,r])=>({key:n,value:r})):[]}extractByPath(e,t){let n=t.replace(/^\$\./,"").split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&Object.hasOwn(r,i))r=r[i];else return[];return Array.isArray(r)?r:typeof r=="object"&&r!==null?Object.entries(r).map(([i,o])=>({state:i,...typeof o=="object"?o:{value:o}})):[]}extractClaudeFlowMemory(e){if(!e||typeof e!="object")return[];let t=[],n=e;for(let[r,i]of Object.entries(n)){if(r.startsWith("_"))continue;let o="general";r.includes("adr")?o="adr-analysis":r.includes("agent")?o="agent-patterns":r.includes("pattern")?o="patterns":r.includes("metric")&&(o="metrics"),t.push({key:r,value:typeof i=="object"?i:{data:i},category:o})}return t}extractIntelligence(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.qvalues&&typeof n.qvalues=="object"){let r=n.qvalues;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null)for(let[s,a]of Object.entries(o)){let c=typeof a=="object"?a:{value:a};t.push({state:i,action:s,q_value:c.value||c.q_value||0,visits:c.visits||0,last_update:c.lastUpdate||c.last_update})}}if(n.memories&&Array.isArray(n.memories)){for(let r of n.memories)if(typeof r=="object"&&r!==null){let i=r;t.push({id:i.id||`mem_${Date.now()}_${_e().slice(0,12)}`,memory_type:i.type||"file_access",content:i.content||i.path,embedding:i.embedding,metadata:i.metadata,timestamp:i.timestamp})}}return t}extractDaemonState(e){if(!e||typeof e!="object")return[];let t=[],n=e;if(n.workers&&typeof n.workers=="object"){let r=n.workers;for(let[i,o]of Object.entries(r))if(typeof o=="object"&&o!==null){let s=o;t.push({worker_type:i,run_count:s.runCount||s.runs||0,success_count:s.successCount||s.successes||0,failure_count:s.failureCount||s.failures||0,avg_duration_ms:s.avgDuration||s.averageDurationMs,last_run:s.lastRun})}}return t}transformRecord(e){let t={...e,source_env:this.config.environment};for(let[n,r]of Object.entries(t))(n.includes("timestamp")||n.endsWith("_at")||n==="last_update")&&(typeof r=="number"?t[n]=new Date(r).toISOString():typeof r=="string"&&!isNaN(Date.parse(r))&&(t[n]=new Date(r).toISOString())),typeof r=="object"&&r!==null&&!Array.isArray(r)&&["value","metadata","embedding"].includes(n);return t.created_at||(t.created_at=new Date().toISOString()),t}getInfo(){let e=C.existsSync(this.filePath),t=0,n=null;if(e){let r=C.statSync(this.filePath);t=r.size,n=r.mtime}return{path:this.filePath,exists:e,modTime:n,size:t}}};function ne(l){return new U(l)}v();import{spawn as xe}from"child_process";import{createConnection as ke}from"net";var Ae=b.create("tunnel-manager");function fe(l){try{let e=new URL(l);return e.password&&(e.password="***"),e.toString()}catch(e){return Ae.debug("URL parse failed during redaction, using regex fallback",{error:e instanceof Error?e.message:String(e)}),l.replace(/:\/\/([^:]+):([^@]+)@/,"://$1:***@")}}var $=class{process=null;connection=null;config;constructor(e){this.config=e}checkPort(e,t,n=2e3){return new Promise(r=>{let i=ke({host:e,port:t}),o=setTimeout(()=>{i.destroy(),r(!1)},n);i.on("connect",()=>{clearTimeout(o),i.destroy(),r(!0)}),i.on("error",()=>{clearTimeout(o),i.destroy(),r(!1)})})}async start(){return this.process&&this.connection?(console.log("[TunnelManager] Tunnel already running"),this.connection):await this.checkPort("localhost",this.config.tunnelPort)?(console.log(`[TunnelManager] External tunnel detected on port ${this.config.tunnelPort}, reusing`),this.connection={host:"localhost",port:this.config.tunnelPort,startedAt:new Date},this.connection):new Promise((t,n)=>{let r=["compute","start-iap-tunnel",this.config.instance,"5432",`--local-host-port=localhost:${this.config.tunnelPort}`,`--zone=${this.config.zone}`,`--project=${this.config.project}`];console.log(`[TunnelManager] Starting IAP tunnel: gcloud ${r.join(" ")}`),this.process=xe("gcloud",r,{stdio:["ignore","pipe","pipe"]});let i=!1,o="",s=!1;this.process.stderr?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`),["Listening on port","tunnel is running","Testing if tunnel connection works"].some(m=>c.includes(m))&&!i&&!s&&(s=!0,setTimeout(async()=>{for(let g=0;g<10;g++){if(console.log(`[TunnelManager] Checking port connectivity (attempt ${g+1}/10)...`),await this.checkPort("localhost",this.config.tunnelPort)){i=!0,this.connection={host:"localhost",port:this.config.tunnelPort,pid:this.process?.pid,startedAt:new Date},console.log(`[TunnelManager] Tunnel ready on port ${this.config.tunnelPort}`),t(this.connection);return}await new Promise(y=>setTimeout(y,1e3))}s=!1},2e3)),o+=c}),this.process.stdout?.on("data",a=>{let c=a.toString();console.log(`[TunnelManager] ${c.trim()}`)}),this.process.on("error",a=>{console.error(`[TunnelManager] Process error: ${a.message}`),i||n(new Error(`Failed to start tunnel: ${a.message}`))}),this.process.on("close",a=>{console.log(`[TunnelManager] Process closed with code ${a}`),this.process=null,this.connection=null,i||n(new Error(`Tunnel process exited with code ${a}: ${o}`))}),setTimeout(()=>{i||(this.stop(),n(new Error("Tunnel connection timeout")))},6e4)})}async stop(){this.process&&(console.log("[TunnelManager] Stopping tunnel"),this.process.kill("SIGTERM"),await new Promise(e=>setTimeout(e,1e3)),this.process&&this.process.kill("SIGKILL"),this.process=null,this.connection=null)}isActive(){return this.process!==null&&this.connection!==null}getConnection(){return this.connection}getConnectionString(){if(!this.connection)throw new Error("Tunnel not active");let{database:e,user:t}=this.config,n=process.env.PGPASSWORD||"",r=this.connection.host,i=this.connection.port;return`postgresql://${t}:${n}@${r}:${i}/${e}`}getRedactedConnectionString(){return fe(this.getConnectionString())}};function $e(l){return new $(l)}var B=class{connection=null;connectionString;constructor(e){this.connectionString=e}async start(){let e=new URL(this.connectionString);return this.connection={host:e.hostname,port:parseInt(e.port||"5432",10),startedAt:new Date},this.connection}async stop(){this.connection=null}isActive(){return this.connection!==null}getConnection(){return this.connection}getConnectionString(){return this.connectionString}getRedactedConnectionString(){return fe(this.connectionString)}};function M(l){return l.connectionString?new B(l.connectionString):new $(l)}k();P();v();import{createRequire as Me}from"module";var N=b.create("postgres-writer"),Ne=Me(import.meta.url),J=class{client=null;config;inTransaction=!1;connected=!1;constructor(e){this.config=e}async connect(){if(this.connected)return;this.config.tunnelManager.isActive()||await this.config.tunnelManager.start();let e=this.config.tunnelManager.getConnection();if(!e)throw new Error("No tunnel connection available");let t;try{t=Ne("pg")}catch(o){N.debug("pg module not installed, using mock mode",{error:o instanceof Error?o.message:String(o)}),console.warn("[PostgresWriter] pg module not installed, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let n=t.default,r=t.Client||n?.Client;if(!r){console.warn("[PostgresWriter] pg.Client not found in module, running in mock mode"),this.client=this.createMockClient(),this.connected=!0;return}let i={host:e.host,port:e.port,database:this.config.cloud.database,user:this.config.cloud.user,password:process.env.PGPASSWORD||"",connectionTimeoutMillis:this.config.connectionTimeout||1e4};this.client=new r(i),await this.client.connect(),this.connected=!0,console.log(`[PostgresWriter] Connected to ${e.host}:${e.port}/${this.config.cloud.database}`)}async beginTransaction(){if(!this.client)throw new Error("Not connected");await this.client.query("BEGIN"),this.inTransaction=!0}async commit(){if(!this.client||!this.inTransaction)throw new Error("No active transaction");await this.client.query("COMMIT"),this.inTransaction=!1}async rollback(){!this.client||!this.inTransaction||(await this.client.query("ROLLBACK"),this.inTransaction=!1)}async upsert(e,t,n){if(!this.client)throw new Error("Not connected");if(t.length===0)return 0;let r=t[0],i=Object.keys(r),o=n?.conflictColumns||this.inferConflictColumns(e,i),s=n?.updateColumns||i.filter(u=>!o.includes(u)),a=0,c=100;for(let u=0;u<t.length;u+=c){let p=t.slice(u,u+c);try{let m=await this.upsertBatch(e,p,i,o,s,n?.skipIfExists);a+=m}catch(m){let g=Math.floor(u/c)+1,h=Math.ceil(t.length/c);N.debug(`Batch ${g}/${h} failed for ${e}, retrying individually`,{error:d(m)});let y=0;for(let f of p)try{let S=await this.upsertBatch(e,[f],i,o,s,n?.skipIfExists);y+=S}catch(S){let R=f.id||f.key||"?";N.debug(`Skipped record ${String(R).slice(0,50)} in ${e}`,{error:d(S)})}a+=y,y<p.length&&console.warn(`[PostgresWriter] Batch ${g}/${h} for ${e}: ${y}/${p.length} recovered (${p.length-y} skipped)`)}}return a}async upsertBatch(e,t,n,r,i,o){if(!this.client)return 0;let s=[],a=[],c=1;for(let f of t){let S=[];for(let R of n){let Ee=f[R];S.push(`$${c++}`),a.push(this.serializeValue(Ee,R))}s.push(`(${S.join(", ")})`)}let u=E(e),p=n.map(E),m=r.map(E),g=i.map(E),h="";if(m.length>0){if(o)h=`ON CONFLICT (${m.join(", ")}) DO NOTHING`;else if(g.length>0){let f=g.map(S=>`${S} = EXCLUDED.${S}`).join(", ");h=`ON CONFLICT (${m.join(", ")}) DO UPDATE SET ${f}`}}let y=`
3
- INSERT INTO ${u} (${p.join(", ")})
4
- VALUES ${s.join(", ")}
5
- ${h}
6
- `;try{return(await this.client.query(y,a)).rowCount||0}catch(f){throw N.debug(`Upsert failed for ${e}`,{error:d(f)}),f}}async execute(e,t){if(!this.client)throw new Error("Not connected");await this.client.query(e,t)}async query(e,t){if(!this.client)throw new Error("Not connected");return(await this.client.query(e,t)).rows}async close(){this.inTransaction&&await this.rollback(),this.client&&(await this.client.end(),this.client=null,this.connected=!1,console.log("[PostgresWriter] Connection closed"))}serializeValue(e,t){if(e==null)return null;if(Buffer.isBuffer(e)){try{let n=new Float32Array(e.buffer,e.byteOffset,e.length/4);if(n.length>0&&n.length<=1024)return`[${Array.from(n).join(",")}]`}catch(n){N.debug("Buffer to float array conversion failed",{error:n instanceof Error?n.message:String(n)})}return null}if(typeof e=="number")return e>9466848e5&&e<41024448e5?new Date(e).toISOString():e>946684800&&e<4102444800?new Date(e*1e3).toISOString():e;if(Array.isArray(e))return e.length>0&&typeof e[0]=="number"?`[${e.join(",")}]`:JSON.stringify(e);if(typeof e=="object"){let n=JSON.stringify(e);if(t&&this.isJsonbColumn(t)){n=n.replace(/\u0000/g,"");try{JSON.parse(n)}catch{return JSON.stringify(String(e))}}return n}if(typeof e=="string"){if(e===""&&t&&["created_at","updated_at","last_used_at","started_at","ended_at","completed_at","expires_at","last_update"].includes(t))return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return e;let n=parseInt(e,10);if(!isNaN(n)&&n>9466848e5&&n<41024448e5)return new Date(n).toISOString();if(t&&this.isJsonbColumn(t)){let r=e.replace(/\u0000/g,"");try{return JSON.parse(r),r}catch{return JSON.stringify(r)}}}return e}isJsonbColumn(e){return["action_value","state","action","next_state","preconditions","effects","metadata","value","payload","context_json","template_json","execution_trace","action_sequence","initial_state","goal_state","sequence","task_json","decision_json","steps_json","metadata_json"].includes(e)}inferConflictColumns(e,t){let n=e.includes(".")?e.split(".")[1]:e,r=["qe_patterns","sona_patterns","goap_actions","goap_plans","patterns","events","routing_outcomes","qe_trajectories","dream_insights","intelligence_memories"];return t.includes("id")&&r.includes(n)?["id"]:n==="memory_entries"&&t.includes("key")&&t.includes("source_env")?t.includes("partition")?["key","partition","source_env"]:["key","source_env"]:n==="claude_flow_memory"&&t.includes("key")&&t.includes("source_env")?["key","source_env"]:n==="qlearning_patterns"&&t.includes("state")&&t.includes("action")&&t.includes("source_env")?["state","action","source_env"]:n==="claude_flow_workers"&&t.includes("worker_type")&&t.includes("source_env")?["worker_type","source_env"]:[]}createMockClient(){let e=[];return{async connect(){console.log("[MockPgClient] Connected (mock mode)")},async query(t,n){return console.log(`[MockPgClient] Query: ${t.slice(0,100)}... (${n?.length||0} params)`),{rows:e,rowCount:0}},async end(){console.log("[MockPgClient] Disconnected (mock mode)")}}}};function O(l){return new J(l)}k();P();v();var G=b.create("postgres-reader"),Q=class{writer;environment;constructor(e){this.writer=e.writer,this.environment=e.environment}sanitizeCloudTable(e){let t=e.indexOf(".");if(t===-1||t===0||t===e.length-1)throw new Error(`Invalid cloud table format '${e}': expected 'schema.table' (e.g., 'aqe.qe_patterns')`);let n=e.substring(0,t),r=e.substring(t+1);return`${E(n)}.${E(r)}`}async readAll(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT * FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT * FROM ${t}`,r=[]);try{let i=await this.writer.query(n,r);return G.debug(`Read ${i.length} records from ${e.cloudTable}`,{env:this.environment}),i.map(o=>this.transformRecord(o,e))}catch(i){throw new Error(`Failed to read from ${e.cloudTable}: ${d(i)}`)}}async readChanged(e,t){let n=this.sanitizeCloudTable(e.cloudTable),r=await this.findTimestampColumn(n);if(!r)return G.debug(`No timestamp column found for ${e.cloudTable}, falling back to readAll`),this.readAll(e);let i,o;this.environment!=="all"?(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1 AND source_env = $2`,o=[t.toISOString(),this.environment]):(i=`SELECT * FROM ${n} WHERE ${E(r)} > $1`,o=[t.toISOString()]);try{return(await this.writer.query(i,o)).map(a=>this.transformRecord(a,e))}catch(s){return G.debug(`Changed query failed for ${e.cloudTable}, falling back to readAll`,{error:d(s)}),this.readAll(e)}}async count(e){let t=this.sanitizeCloudTable(e.cloudTable),n,r;this.environment!=="all"?(n=`SELECT COUNT(*) as count FROM ${t} WHERE source_env = $1`,r=[this.environment]):(n=`SELECT COUNT(*) as count FROM ${t}`,r=[]);try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let i=await this.writer.query(n,r);return await this.writer.commit(),typeof i[0]?.count=="string"?parseInt(i[0].count,10):i[0]?.count||0}catch(i){try{await this.writer.rollback()}catch{}return G.debug(`Count query failed for ${e.cloudTable}`,{error:d(i)}),-1}}transformRecord(e,t){let n={};for(let[r,i]of Object.entries(e)){if(t.dropColumns?.includes(r))continue;let o=t.columnMap?.[r]||r;n[o]=this.transformValue(i,r,t.transforms)}return n}transformValue(e,t,n){if(e==null)return null;let r=n?.[t];return r==="boolean-to-int"?typeof e=="boolean"?e?1:0:e==="true"||e==="t"?1:e==="false"||e==="f"?0:e:r==="jsonb-to-text"?typeof e=="object"?JSON.stringify(e):e:r==="timestamptz-to-text"?e instanceof Date?e.toISOString():e:typeof e=="object"&&!Buffer.isBuffer(e)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:e}async findTimestampColumn(e){let t=["updated_at","created_at","last_update","last_used_at"];try{let n=e.split(".")[0],r=e.split(".")[1],o=(await this.writer.query(`SELECT column_name FROM information_schema.columns
7
- WHERE table_schema = $1 AND table_name = $2
8
- AND data_type IN ('timestamp with time zone', 'timestamp without time zone')`,[n,r])).map(s=>s.column_name);for(let s of t)if(o.includes(s))return s;return o[0]||null}catch{return null}}};function ie(l){return new Q(l)}z();k();P();v();import*as ye from"fs";var D=b.create("sqlite-writer"),V=class{db=null;dbPath;batchSize;constructor(e){this.dbPath=e.dbPath,this.batchSize=e.batchSize||500}async connect(){if(!this.db){if(!ye.existsSync(this.dbPath))throw new Error(`SQLite database not found: ${this.dbPath}. Run 'aqe init' to create it.`);try{this.db=T(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),D.debug(`Opened SQLite database: ${this.dbPath}`)}catch(e){throw new Error(`Failed to open SQLite database ${this.dbPath}: ${d(e)}`)}}}async upsert(e,t){if(!this.db)throw new Error("Not connected");if(t.length===0)return 0;let n=w(e);if(!this.tableExists(e))return console.warn(`[SQLiteWriter] Table '${e}' does not exist in local database \u2014 ${t.length} records skipped. Run 'aqe init' to create schema.`),0;let r=this.getTableColumns(e);if(r.length===0)return D.debug(`No columns found for table ${e}`),0;let i=new Set(r),o=0;for(let s=0;s<t.length;s+=this.batchSize){let a=t.slice(s,s+this.batchSize);try{let c=this.upsertBatch(n,a,i);o+=c}catch(c){let u=Math.floor(s/this.batchSize)+1;D.debug(`Batch ${u} failed for ${e}, retrying individually`,{error:d(c)});let p=0;for(let m of a)try{p+=this.upsertBatch(n,[m],i)}catch(g){let h=m.id||m.key||"?";D.debug(`Skipped record ${String(h).slice(0,50)} in ${e}`,{error:d(g)})}o+=p}}return o}async count(e){if(!this.db)throw new Error("Not connected");if(!this.tableExists(e))return 0;try{let t=w(e);return this.db.prepare(`SELECT COUNT(*) as count FROM ${t}`).get().count}catch{return 0}}async close(){this.db&&(this.db.close(),this.db=null,D.debug("SQLite writer closed"))}tableExists(e){if(!this.db)return!1;try{return!!this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(e)}catch{return!1}}getTableColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().map(r=>r.name)}catch{return[]}}getPrimaryKeyColumns(e){if(!this.db)return[];try{let t=w(e);return this.db.prepare(`PRAGMA table_info(${t})`).all().filter(i=>i.pk>0).sort((i,o)=>i.pk-o.pk).map(i=>i.name)}catch{return[]}}upsertBatch(e,t,n){if(!this.db||t.length===0)return 0;let r=t[0],i=Object.keys(r).filter(g=>n.has(g));if(i.length===0)return 0;let o=i.map(E),s=i.map(()=>"?").join(", "),a=e.replace(/"/g,""),c=this.getPrimaryKeyColumns(a),u;if(c.length>0){let g=c.map(E),h=i.filter(y=>!c.includes(y));if(h.length>0){let y=h.map(f=>`${E(f)} = excluded.${E(f)}`).join(", ");u=`INSERT INTO ${e} (${o.join(", ")}) VALUES (${s}) ON CONFLICT(${g.join(", ")}) DO UPDATE SET ${y}`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`}else u=`INSERT OR IGNORE INTO ${e} (${o.join(", ")}) VALUES (${s})`;let p=this.db.prepare(u);return this.db.transaction(g=>{let h=0;for(let y of g){let f=i.map(S=>this.serializeValue(y[S]));p.run(...f),h++}return h})(t)}serializeValue(e){return e==null?null:typeof e=="object"&&!Buffer.isBuffer(e)&&!(e instanceof Date)?JSON.stringify(e):e instanceof Date?e.toISOString():typeof e=="boolean"?e?1:0:(Buffer.isBuffer(e),e)}};function oe(l){return new V(l)}v();P();var Oe=b.create("sync-agent"),H=class{config;readers=new Map;writer=null;report=null;constructor(e={}){this.config={...x,...e,local:{...x.local,...e.local},cloud:{...x.cloud,...e.cloud},sync:{...x.sync,...e.sync}}}async initialize(){this.log("Initializing sync agent...");let e=this.config.sync.sources.filter(t=>t.enabled!==!1);for(let t of e){let n=this.createReader(t);if(n)try{await n.initialize(),this.readers.set(t.name,n),this.log(`Initialized reader: ${t.name}`)}catch(r){this.log(`Warning: Failed to initialize reader ${t.name}: ${r}`,"warn")}}this.log(`Initialized ${this.readers.size} readers`)}async syncAll(){this.report=this.createReport("full");try{await this.connectToCloud();let e=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)).sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]}),t=0,n=e.length;for(let r of e){this.progress(`Syncing ${r.name}...`,t/n);let i=await this.syncSource(r);this.report.results.push(i),t++}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0)}return this.report}async syncIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{await this.connectToCloud();let n=this.config.sync.sources.filter(r=>r.enabled!==!1&&this.readers.has(r.name)&&r.mode!=="full").sort((r,i)=>{let o={high:0,medium:1,low:2};return o[r.priority]-o[i.priority]});for(let r of n){this.progress(`Incremental sync ${r.name}...`,0);let i=await this.syncSourceIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{await this.disconnect(),this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((n,r)=>n+r.recordsSynced,0)}return this.report}async syncSource(e){let t=Date.now(),n={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{let r=this.readers.get(e.name);if(!r)throw new Error(`Reader not found: ${e.name}`);let i=await r.readAll();if(this.log(`Read ${i.length} records from ${e.name}`),i.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.writer&&!this.config.sync.dryRun){let o=await this.writer.upsert(e.targetTable,i,{skipIfExists:e.mode==="append"});n.recordsSynced=o}else n.recordsSynced=i.length,this.log(`[DRY RUN] Would sync ${i.length} records to ${e.targetTable}`);n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async syncSourceIncremental(e,t){let n=Date.now(),r={success:!1,table:e.targetTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{let i=this.readers.get(e.name);if(!i)throw new Error(`Reader not found: ${e.name}`);let o=await i.readChanged(t);if(this.log(`Read ${o.length} changed records from ${e.name} (since ${t.toISOString()})`),o.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.writer&&!this.config.sync.dryRun){let s=await this.writer.upsert(e.targetTable,o);r.recordsSynced=s}else r.recordsSynced=o.length;r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async getStatus(){let e=[];for(let t of this.config.sync.sources){let n=this.readers.get(t.name);if(n){let r=await n.count();e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:r,enabled:t.enabled!==!1,priority:t.priority})}else e.push({name:t.name,type:t.type,targetTable:t.targetTable,recordCount:0,enabled:t.enabled!==!1,priority:t.priority,error:"Reader not initialized"})}return{sources:e}}async verify(){let e=[];for(let t of this.config.sync.sources.filter(n=>n.enabled!==!1)){let n=this.readers.get(t.name);if(!n)continue;let r=await n.count(),i=0;if(this.writer)try{await this.writer.beginTransaction(),await this.writer.execute("SET LOCAL enable_indexonlyscan = off");let o=await this.writer.query(`SELECT COUNT(*) as count FROM ${t.targetTable} WHERE source_env = $1`,[this.config.environment]);await this.writer.commit(),i=o[0]?.count||0}catch(o){try{await this.writer.rollback()}catch{}Oe.debug("Cloud count query failed",{source:t.name,error:o instanceof Error?o.message:String(o)}),i=-1}e.push({source:t.name,table:t.targetTable,localCount:r,cloudCount:i,match:r===i,diff:r-i})}return{verified:e.every(t=>t.match||t.cloudCount===-1),results:e}}async close(){await this.disconnect();for(let e of Array.from(this.readers.entries())){let[t,n]=e;try{await n.close()}catch(r){this.log(`Warning: Failed to close reader ${t}: ${r}`,"warn")}}this.readers.clear(),this.log("Sync agent closed")}createReader(e){let t=process.cwd(),n=this.config.environment;return e.type==="sqlite"?re({source:e,baseDir:t,environment:n}):e.type==="json"?ne({source:e,baseDir:t,environment:n}):null}async connectToCloud(){if(this.writer)return;let e=M(this.config.cloud);this.writer=O({cloud:this.config.cloud,tunnelManager:e}),await this.writer.connect(),this.log("Connected to cloud database")}async disconnect(){this.writer&&(await this.writer.close(),this.writer=null)}createReport(e){return{syncId:j(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[CloudSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function se(l){return new H(l)}async function De(l){let e=se({...l,verbose:!0});await e.initialize();try{return await e.syncAll()}finally{await e.close()}}async function qe(l,e){let t=se({...e,verbose:!0});await t.initialize();try{return await t.syncIncremental(l)}finally{await t.close()}}import*as Y from"fs";import*as ae from"path";me();P();v();var It=b.create("pull-agent"),X=class{config;reader=null;writer=null;cloudWriter=null;report=null;constructor(e={}){this.config={...A,...e,cloud:{...A.cloud,...e.cloud},sources:e.sources||A.sources}}async initialize(){this.log("Initializing pull sync agent...");let e=M(this.config.cloud);this.cloudWriter=O({cloud:this.config.cloud,tunnelManager:e}),await this.cloudWriter.connect(),this.log("Connected to cloud database"),this.reader=ie({writer:this.cloudWriter,environment:this.config.environment});let t=this.resolveTargetDb();this.writer=oe({dbPath:t}),await this.writer.connect(),this.log(`Connected to local database: ${t}`)}async pullAll(){this.report=this.createReport("full");try{this.ensureInitialized(),this.backupLocalDb();let e=this.getEnabledSources(),t=0;for(let n of e){this.progress(`Pulling ${n.name}...`,t/e.length);let r=await this.pullTable(n);this.report.results.push(r),t++}this.report.status=this.report.results.every(n=>n.success)?"completed":"partial"}catch(e){this.report.status="failed",this.report.errors.push(d(e))}finally{this.finalizeReport()}return this.report}async pullIncremental(e){this.report=this.createReport("incremental");let t=e||new Date(Date.now()-1440*60*1e3);try{this.ensureInitialized(),this.backupLocalDb();let n=this.getEnabledSources().filter(r=>r.mode!=="full");for(let r of n){this.progress(`Incremental pull ${r.name}...`,0);let i=await this.pullTableIncremental(r,t);this.report.results.push(i)}this.report.status=this.report.results.every(r=>r.success)?"completed":"partial"}catch(n){this.report.status="failed",this.report.errors.push(d(n))}finally{this.finalizeReport()}return this.report}async pullTable(e){let t=Date.now(),n={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0,warnings:[]};try{this.ensureInitialized();let r=await this.reader.readAll(e);if(this.log(`Read ${r.length} records from cloud ${e.cloudTable}`),r.length===0)return n.success=!0,n.durationMs=Date.now()-t,n;if(this.config.dryRun)n.recordsSynced=r.length,this.log(`[DRY RUN] Would write ${r.length} records to local ${e.localTable}`);else{let i=await this.writer.upsert(e.localTable,r);n.recordsSynced=i,n.recordsSkipped=r.length-i}n.success=!0}catch(r){n.error=d(r),this.config.onError?.(L(r),e.name)}return n.durationMs=Date.now()-t,n}async pullTableIncremental(e,t){let n=Date.now(),r={success:!1,table:e.localTable,source:e.name,recordsSynced:0,conflictsResolved:0,recordsSkipped:0,durationMs:0};try{this.ensureInitialized();let i=await this.reader.readChanged(e,t);if(this.log(`Read ${i.length} changed records from cloud ${e.cloudTable} (since ${t.toISOString()})`),i.length===0)return r.success=!0,r.durationMs=Date.now()-n,r;if(this.config.dryRun)r.recordsSynced=i.length;else{let o=await this.writer.upsert(e.localTable,i);r.recordsSynced=o}r.success=!0}catch(i){r.error=d(i)}return r.durationMs=Date.now()-n,r}async verify(){this.ensureInitialized();let e=[];for(let t of this.getEnabledSources()){let n=await this.reader.count(t),r=await this.writer.count(t.localTable);e.push({source:t.name,cloudTable:t.cloudTable,localTable:t.localTable,cloudCount:n,localCount:r,match:n===r||n===-1,diff:r-n})}return{verified:e.every(t=>t.match),results:e}}async close(){this.writer&&(await this.writer.close(),this.writer=null),this.cloudWriter&&(await this.cloudWriter.close(),this.cloudWriter=null),this.reader=null,this.log("Pull sync agent closed")}ensureInitialized(){if(!this.reader||!this.writer)throw new Error("PullSyncAgent not initialized. Call initialize() first.")}getEnabledSources(){let e=this.config.sources.filter(n=>n.enabled);if(this.config.tables&&this.config.tables.length>0){let n=new Set(this.config.tables);e=e.filter(r=>n.has(r.localTable)||n.has(r.name))}let t={high:0,medium:1,low:2};return e.sort((n,r)=>t[n.priority]-t[r.priority])}resolveTargetDb(){return this.config.targetDb?ae.resolve(this.config.targetDb):ae.resolve(I(),".agentic-qe/memory.db")}backupLocalDb(){if(this.config.dryRun)return;let e=this.resolveTargetDb();if(!Y.existsSync(e))return;let t=Math.floor(Date.now()/1e3),n=`${e}.bak-${t}`;try{Y.copyFileSync(e,n),this.log(`Backed up local DB to ${n}`)}catch(r){this.log(`Warning: Failed to backup local DB: ${d(r)}`,"warn")}}createReport(e){return{syncId:j(),startedAt:new Date,status:"running",environment:this.config.environment,mode:e,results:[],totalRecordsSynced:0,totalConflictsResolved:0,totalDurationMs:0,errors:[]}}finalizeReport(){this.report&&(this.report.completedAt=new Date,this.report.totalDurationMs=this.report.completedAt.getTime()-this.report.startedAt.getTime(),this.report.totalRecordsSynced=this.report.results.reduce((e,t)=>e+t.recordsSynced,0),this.report.totalConflictsResolved=this.report.results.reduce((e,t)=>e+t.conflictsResolved,0))}log(e,t="info"){if(!this.config.verbose&&t==="info")return;let n=`[PullSync:${this.config.environment}]`;switch(t){case"warn":console.warn(`${n} ${e}`);break;case"error":console.error(`${n} ${e}`);break;default:console.log(`${n} ${e}`)}}progress(e,t){this.config.onProgress?.(e,t),this.log(e)}};function ce(l){return new X(l)}async function Le(l){let e=ce({...l,verbose:!0});await e.initialize();try{return await e.pullAll()}finally{await e.close()}}async function Ie(l,e){let t=ce({...e,verbose:!0});await t.initialize();try{return await t.pullIncremental(l)}finally{await t.close()}}z();me();ee();Re();import{join as be}from"path";import{existsSync as ze,mkdirSync as je}from"fs";var K=class{memoryCache;maxSize;ttl;persistent;compression;db=null;storagePath;useUnified;unifiedMemory=null;pendingWrites=[];dbInitializing=!1;constructor(e={}){this.maxSize=e.maxSize||1e4,this.ttl=e.ttl||0,this.persistent=e.persistent??!0,this.compression=e.compression??!0,this.useUnified=e.useUnified??!0,this.storagePath=e.storagePath||be(I(),".agentic-qe","embeddings-cache.db"),this.memoryCache=new Map;let t=["text","code","test","coverage","defect"];for(let n of t)this.memoryCache.set(n,new Map);this.persistent&&this.initializePersistentStorage()}initializePersistentStorage(){try{if(this.useUnified)this.unifiedMemory=ue(),this.dbInitializing=!0,this.unifiedMemory.initialize().then(()=>{this.db=this.unifiedMemory.getDatabase(),this.dbInitializing=!1,console.log(`[EmbeddingCache] Using unified storage: ${this.unifiedMemory.getDbPath()}`),this.loadFromDisk(),this.flushPendingWrites()}).catch(e=>{console.warn("[EmbeddingCache] Failed to initialize unified storage:",e),this.db=null,this.dbInitializing=!1,this.unifiedMemory=null,this.pendingWrites=[]});else{let e=be(this.storagePath,"..");ze(e)||je(e,{recursive:!0}),this.db=T(this.storagePath),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.exec(`
9
- CREATE TABLE IF NOT EXISTS embeddings (
10
- key TEXT NOT NULL,
11
- namespace TEXT NOT NULL,
12
- vector BLOB NOT NULL,
13
- dimension INTEGER NOT NULL,
14
- text TEXT NOT NULL,
15
- timestamp INTEGER NOT NULL,
16
- quantization TEXT NOT NULL,
17
- metadata TEXT,
18
- access_count INTEGER DEFAULT 1,
19
- last_access INTEGER NOT NULL,
20
- PRIMARY KEY (key, namespace)
21
- );
22
-
23
- CREATE INDEX IF NOT EXISTS idx_namespace ON embeddings(namespace);
24
- CREATE INDEX IF NOT EXISTS idx_timestamp ON embeddings(timestamp);
25
- `),console.log(`[EmbeddingCache] Initialized (legacy): ${this.storagePath}`),this.loadFromDisk()}}catch(e){console.warn("Failed to initialize persistent storage:",e),this.db=null}}get(e,t="text"){let n=this.memoryCache.get(t);if(!n)return null;let r=n.get(e);return r?this.ttl>0&&Date.now()-r.lastAccess>this.ttl*1e3?(n.delete(e),null):(r.accessCount++,r.lastAccess=Date.now(),r.embedding):null}set(e,t,n="text"){let r=this.memoryCache.get(n);if(!r)return;r.size>=this.maxSize&&!r.has(e)&&this.evictLRU(n);let i={key:e,embedding:t,accessCount:1,lastAccess:Date.now()};r.set(e,i),this.persistent&&(this.db?this.persistToDisk(e,t,n):this.dbInitializing&&this.pendingWrites.push({key:e,embedding:t,namespace:n}))}has(e,t="text"){return this.memoryCache.get(t)?.has(e)||!1}delete(e,t="text"){let r=this.memoryCache.get(t)?.delete(e)||!1;return r&&this.persistent&&this.db&&this.persist("delete",i=>i.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(e,t)),r}clear(e){if(e)this.memoryCache.get(e)?.clear(),this.persistent&&this.db&&this.persist("clear",n=>n.prepare("DELETE FROM embeddings WHERE namespace = ?").run(e));else{for(let t of this.memoryCache.values())t.clear();this.persistent&&this.db&&this.persist("clear",t=>t.exec("DELETE FROM embeddings"))}}getAll(e){let t=[];if(e)this.memoryCache.get(e)?.forEach(r=>t.push(r.embedding));else for(let n of this.memoryCache.values())n.forEach(r=>t.push(r.embedding));return t}evictLRU(e){let t=this.memoryCache.get(e);if(!t||t.size===0)return;let n=null,r=1/0;for(let[i,o]of t.entries())o.lastAccess<r&&(r=o.lastAccess,n=i);if(n&&(t.delete(n),this.persistent&&this.db)){let i=n;this.persist("evict",o=>o.prepare("DELETE FROM embeddings WHERE key = ? AND namespace = ?").run(i,e))}}persistToDisk(e,t,n){if(this.db)try{let r=this.serializeVector(t.vector),i=t.metadata?JSON.stringify(t.metadata):null,o=Date.now();this.persist("persist",s=>s.prepare(`
26
- INSERT OR REPLACE INTO embeddings
27
- (key, namespace, vector, dimension, text, timestamp, quantization, metadata, last_access)
28
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
29
- `).run(e,n,r,t.dimension,t.text,t.timestamp,t.quantization,i,o))}catch(r){console.warn("Failed to persist embedding:",r)}}persist(e,t){let n=this.db;n&&le(n,()=>t(n)).catch(r=>{console.warn(`Failed to ${e} embedding cache entry:`,r)})}flushPendingWrites(){if(this.pendingWrites.length===0||!this.db)return;let e=this.pendingWrites;this.pendingWrites=[];for(let{key:t,embedding:n,namespace:r}of e)this.persistToDisk(t,n,r);e.length>0&&console.log(`[EmbeddingCache] Flushed ${e.length} pending writes after DB init`)}loadFromDisk(){if(this.db)try{let t=this.db.prepare("SELECT * FROM embeddings").all();for(let n of t){let r={vector:this.deserializeVector(n.vector),dimension:n.dimension,namespace:n.namespace,text:n.text,timestamp:n.timestamp,quantization:n.quantization,metadata:n.metadata?_(n.metadata):void 0},i=this.memoryCache.get(n.namespace);i&&i.set(n.key,{key:n.key,embedding:r,accessCount:n.access_count||1,lastAccess:n.last_access})}}catch(e){console.warn("Failed to load embeddings from disk:",e)}}serializeVector(e){if(e instanceof Float32Array)return Buffer.from(e.buffer);if(e instanceof Int8Array)return Buffer.from(e.buffer);if(e instanceof Uint8Array)return Buffer.from(e.buffer);{let t=new Float32Array(e);return Buffer.from(t.buffer)}}deserializeVector(e){let t=new Float32Array(e.buffer,e.byteOffset,e.byteLength/Float32Array.BYTES_PER_ELEMENT);return Array.from(t)}getStats(){let e=0,t={text:0,code:0,test:0,coverage:0,defect:0,experiences:0};for(let[r,i]of this.memoryCache.entries()){let o=i.size;t[r]=o,e+=o}let n=e*384*4;return{totalEntries:e,entriesByNamespace:t,memoryUsage:n,hitRate:0}}resetStats(){}close(){this.db&&(this.unifiedMemory?console.log("[EmbeddingCache] Detached from unified storage (not closing shared connection)"):(this.db.close(),console.log("[EmbeddingCache] Database closed")),this.db=null,this.unifiedMemory=null,this.pendingWrites=[],this.dbInitializing=!1)}getMostAccessed(e="text",t=10){let n=this.memoryCache.get(e);return n?Array.from(n.entries()).map(([r,i])=>({key:r,accessCount:i.accessCount})).sort((r,i)=>i.accessCount-r.accessCount).slice(0,t):[]}optimize(e=2,t){let n=0,r=i=>{let o=this.memoryCache.get(i);if(!o)return;let s=[];for(let[a,c]of o.entries())c.accessCount<e&&s.push(a);for(let a of s)o.delete(a),n++};if(t)r(t);else for(let i of this.memoryCache.keys())r(i);return n}};Pe();var Z=class{model=null;config;cache;stats;constructor(e={}){this.config={type:e.type||"transformers",model:e.model||"Xenova/all-MiniLM-L6-v2",dimension:e.dimension||384,quantization:e.quantization||"none",cacheEnabled:e.cacheEnabled??!0,onnxEnabled:e.onnxEnabled??!0,maxSequenceLength:e.maxSequenceLength||512},this.cache=new K({maxSize:1e4,ttl:0,persistent:!0,compression:!0}),this.stats=this.initializeStats()}async initialize(){if(this.model)return;let e=performance.now();if(this.config.onnxEnabled){let n=this.config.quantization==="none"?"fp32":this.config.quantization==="fp16"?"fp16":this.config.quantization==="int8"?"int8":"q8",r;try{({pipeline:r}=await import("./transformers-4MRPXCPU.js"))}catch(i){throw new Error(`Local (in-process) embeddings require the optional dependency "@huggingface/transformers", which is not installed. Configure an embedding endpoint (e.g. Cognitum /v1/embeddings) so the local backend is not needed. Installing @huggingface/transformers@4.2.0 is an explicit security opt-in: its compatible dependency chain currently has unresolved HIGH advisories GHSA-xcpc-8h2w-3j85 and GHSA-f88m-g3jw-g9cj. Underlying import error: ${i instanceof Error?i.message:String(i)}`)}this.model=await r("feature-extraction",this.config.model,{dtype:n,progress_callback:i=>{i.status==="progress"&&typeof i.progress=="number"&&console.log(`Downloading model: ${(i.progress*100).toFixed(0)}%`)}})}let t=performance.now()-e;console.log(`Model loaded in ${t.toFixed(2)}ms`)}async embed(e,t={}){let n=performance.now(),r=t.namespace||"text";if(t.cache!==!1&&this.config.cacheEnabled){let c=this.cache.get(e,r);if(c)return this.stats.cacheHits++,c;this.stats.cacheMisses++}await this.initialize();let i;if(this.model){let c=await this.model(e,{pooling:"mean",normalize:!0});i=Array.from(c.data)}else throw new Error("Model not initialized");let o=i;if(t.quantization||this.config.quantization){let c=t.quantization||this.config.quantization;o=this.quantize(i,c)}let s={vector:o,dimension:this.config.dimension,namespace:r,text:e,timestamp:Date.now(),quantization:t.quantization||this.config.quantization,metadata:t?.metadata};t.cache!==!1&&this.config.cacheEnabled&&this.cache.set(e,s,r);let a=performance.now()-n;return this.stats.avgEmbeddingTime=(this.stats.avgEmbeddingTime*this.stats.totalEmbeddings+a)/(this.stats.totalEmbeddings+1),this.stats.totalEmbeddings++,this.stats.byNamespace[r]++,s}async embedBatch(e,t={}){let n=performance.now(),r=0,i=0,o=[];for(let a of e){let c=await this.embed(a,t);this.cache.get(a,t.namespace||"text")?r++:i++,o.push(c),t.onProgress&&t.onProgress(o.length/e.length)}let s=performance.now()-n;return{embeddings:o,totalTime:s,avgTime:s/e.length,cacheHits:r,cacheMisses:i}}async findSimilar(e,t={}){let n=t.limit||10,r=t.threshold||.7,i=typeof e=="string"?await this.embed(e,{namespace:t.namespace}):e,s=this.cache.getAll(t.namespace).map(a=>({target:a.text,score:de(i.vector,a.vector),rank:0})).filter(a=>a.score>=r).sort((a,c)=>c.score-a.score).slice(0,n);return s.forEach((a,c)=>{a.rank=c+1}),s}quantize(e,t){switch(t){case"fp16":return new Float32Array(e.map(n=>Math.fround(n)));case"int8":{let n=Math.max(...e.map(Math.abs));return new Int8Array(e.map(r=>Math.round(r/n*127)))}case"binary":{let n=new Uint8Array(Math.ceil(e.length/8));for(let r=0;r<e.length;r++)e[r]>=0&&(n[Math.floor(r/8)]|=1<<r%8);return n}default:return e}}getStats(){let e=this.cache.getStats();return{...this.stats,cacheHitRate:this.stats.cacheHits+this.stats.cacheMisses>0?this.stats.cacheHits/(this.stats.cacheHits+this.stats.cacheMisses):0,memoryUsage:e.memoryUsage,memoryReduction:this.calculateMemoryReduction()}}calculateMemoryReduction(){switch(this.config.quantization){case"fp16":return 50;case"int8":return 75;case"binary":return 97;default:return 0}}initializeStats(){return{totalEmbeddings:0,byNamespace:{text:0,code:0,test:0,coverage:0,defect:0,experiences:0},cacheHits:0,cacheMisses:0,cacheHitRate:0,avgEmbeddingTime:0,memoryUsage:0,memoryReduction:0,indexSize:0,indexBuildTime:0}}resetStats(){this.stats=this.initializeStats(),this.cache.resetStats()}async clear(){this.cache.clear(),this.model=null}};z();k();P();ee();v();import{resolve as Fe,dirname as We}from"path";import{fileURLToPath as Ue}from"url";var Se=b.create("sync-embedding-generator"),Be=Ue(import.meta.url),Je=We(Be),q=class{generator;dbPath;initialized=!1;constructor(e){this.dbPath=e||Fe(Je,"../../../../.agentic-qe/memory.db"),this.generator=new Z({model:"Xenova/all-MiniLM-L6-v2",dimension:384,cacheEnabled:!0,onnxEnabled:!0})}async initialize(){this.initialized||(await this.generator.initialize(),this.initialized=!0,console.log("[SyncEmbedding] Model initialized"))}async generateForPattern(e){await this.initialize();let t=this.extractText(e),n=await this.generator.embed(t,{namespace:"text"});return{id:e.id,embedding:Array.isArray(n.vector)?n.vector:Array.from(n.vector),text:t,dimension:n.dimension,generatedAt:new Date}}async generateForAllPatterns(e="patterns",t={}){let n=Date.now(),r={totalPatterns:0,patternsWithEmbeddings:0,patternsGenerated:0,patternsSkipped:0,errors:[],durationMs:0};await this.initialize();let i=T(this.dbPath);try{i.prepare(`PRAGMA table_info(${w(e)})`).all().some(h=>h.name==="embedding")||(i.prepare(`ALTER TABLE ${w(e)} ADD COLUMN embedding TEXT`).run(),console.log(`[SyncEmbedding] Added embedding column to ${e}`));let a=w(e),c=t.force?`SELECT * FROM ${a}`:`SELECT * FROM ${a} WHERE embedding IS NULL OR embedding = ''`,u=i.prepare(c).all();r.totalPatterns=u.length,t.verbose&&console.log(`[SyncEmbedding] Processing ${u.length} patterns from ${e}`);let p=i.prepare(`SELECT COUNT(*) as count FROM ${a} WHERE embedding IS NOT NULL AND embedding != ''`).get();r.patternsWithEmbeddings=p.count;let m=i.prepare(`UPDATE ${a} SET embedding = ? WHERE id = ?`),g=t.batchSize||50;for(let h=0;h<u.length;h+=g){let y=u.slice(h,Math.min(h+g,u.length));for(let f of y)try{let S=await this.generateForPattern(f),R=JSON.stringify(S.embedding);m.run(R,f.id),r.patternsGenerated++,t.verbose&&r.patternsGenerated%10===0&&console.log(`[SyncEmbedding] Generated ${r.patternsGenerated}/${u.length}`)}catch(S){let R=d(S);r.errors.push(`Pattern ${f.id}: ${R}`),r.patternsSkipped++}}return r.durationMs=Date.now()-n,t.verbose&&(console.log(`[SyncEmbedding] Completed: ${r.patternsGenerated} generated, ${r.patternsSkipped} skipped`),console.log(`[SyncEmbedding] Duration: ${r.durationMs}ms`)),r}finally{i.close()}}async findSimilarPatterns(e,t={}){await this.initialize();let n=t.limit||10,r=t.threshold||.5,i=t.tableName||"patterns",o=await this.generator.embed(e,{namespace:"text"}),s=Array.isArray(o.vector)?o.vector:Array.from(o.vector),a=T(this.dbPath,{readonly:!0});try{let c=a.prepare(`SELECT * FROM ${w(i)} WHERE embedding IS NOT NULL AND embedding != ''`).all(),u=[];for(let p of c)try{let m=typeof p.embedding=="string"?_(p.embedding):p.embedding;if(Array.isArray(m)&&m.length===s.length){let g=this.cosineSimilarity(s,m);g>=r&&u.push({pattern:p,similarity:g})}}catch(m){Se.debug("Invalid embedding in search pattern",{error:m instanceof Error?m.message:String(m)})}return u.sort((p,m)=>m.similarity-p.similarity).slice(0,n)}finally{a.close()}}extractText(e){let t=[];if(e.pattern&&t.push(e.pattern),e.content)try{let r=typeof e.content=="string"?_(e.content):e.content;typeof r=="object"?(r.description&&t.push(r.description),r.name&&t.push(r.name),r.summary&&t.push(r.summary),r.text&&t.push(r.text)):typeof r=="string"&&t.push(r)}catch(r){Se.debug("Pattern content is not JSON, using as string",{error:r instanceof Error?r.message:String(r)}),t.push(String(e.content))}return e.type&&t.push(`type:${e.type}`),e.domain&&t.push(`domain:${e.domain}`),t.join(" ").trim().substring(0,512)}cosineSimilarity(e,t){let n=0,r=0,i=0;for(let s=0;s<e.length;s++)n+=e[s]*t[s],r+=e[s]*e[s],i+=t[s]*t[s];let o=Math.sqrt(r)*Math.sqrt(i);return o===0?0:n/o}getStats(){return this.generator.getStats()}async clear(){await this.generator.clear(),this.initialized=!1}};function we(l){return new q(l)}export{A as a,ve as b,x as c,W as d,re as e,U as f,ne as g,$ as h,$e as i,B as j,M as k,J as l,O as m,Q as n,ie as o,V as p,oe as q,H as r,se as s,De as t,qe as u,X as v,ce as w,Le as x,Ie as y,q as z,we as A};
@@ -1,5 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as F,d as C}from"./chunk-4UKTIQDT.js";import{a as E}from"./chunk-C7QLLMYI.js";import{a as O,b as P,c as x,e as J}from"./chunk-YKRLUTK7.js";import{b as W,d as B}from"./chunk-GPPTRKEM.js";var Q=new Set(["false","0","off","no"]),K=new Set([...Q,"disabled","disable","none","never"]),V=30,G=36500;function pe(l=process.env){let e=l.AQE_WORKERS_ENABLED;return e===void 0?!0:!Q.has(e.trim().toLowerCase())}function ge(l=process.env){let e=l.AQE_DISABLED_WORKERS;if(!e)return[];let t=e.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i.length>0);return Array.from(new Set(t))}function fe(l=process.env){let e=l.AQE_DREAM_INSIGHTS_RETENTION_DAYS;if(e===void 0||e.trim()==="")return{retentionDays:V};let t=e.trim().toLowerCase();if(K.has(t))return{retentionDays:null};if(/^\d+$/.test(t)){let i=Number(t);if(i>=1&&i<=G)return{retentionDays:i}}return{retentionDays:null,warning:`Invalid AQE_DREAM_INSIGHTS_RETENTION_DAYS=${JSON.stringify(e)}; expected a whole number of days (1-${G}), 0 or "off". The dream_insights retention sweep is off until this is fixed; nothing is deleted.`}}var I="quality-daemon",R=class{constructor(e){this.backend=e}backend;async get(e,t){return this.backend.kvGet(e,t?.namespace??I)}async set(e,t){await this.backend.kvSet(e,t,I)}async search(e,t,i){return this.backend.kvSearch(e,i?.namespace??I,t)}};import{cpus as ce,freemem as de,totalmem as he,loadavg as me}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let r=i.shift();if(!(r.ttlMs&&e-r.createdAt>r.ttlMs))return r}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let r of i)if(!r.ttlMs||e-r.createdAt<=r.ttlMs)return r}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(r=>!r.ttlMs||i-r.createdAt<=r.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let r=this.queues[i].length;this.queues[i]=this.queues[i].filter(o=>!o.ttlMs||t-o.createdAt<=o.ttlMs),e+=r-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as Y}from"fs";import{resolve as $,join as X}from"path";import{existsSync as Z,readFileSync as ee}from"fs";var M=1e4,te={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...te,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=$(this.options.repoRoot,".git","refs","heads");if(!Z(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=Y(e,{recursive:!0},(i,r)=>{r&&this.handleRefChange(r)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let t=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let i of t.trim().split(`
3
- `)){if(!i)continue;let[r,o]=i.split(" "),n=this.lastKnownHeads.get(r);n&&n!==o&&(e.push(r),await this.enqueueCommitAnalysis(r,o)),this.lastKnownHeads.set(r,o)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=$(this.options.repoRoot,".git","refs","heads"),r=X(i,e),o;try{o=ee(r,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==o&&(this.lastKnownHeads.set(t,o),await this.enqueueCommitAnalysis(t,o))}async enqueueCommitAnalysis(e,t){if(E(t,"commit hash"))return;let i=[];try{i=(await C(["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot,timeout:M})).trim().split(`
4
- `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let r={type:"git_commit",branch:e,commitHash:t,changedFiles:i},o={id:`git-${t}-${Date.now()}`,priority:"next",payload:r,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(o)}async snapshotHeads(){try{let e=await C(["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot,timeout:M});for(let t of e.trim().split(`
5
- `)){if(!t)continue;let[i,r]=t.split(" ");this.lastKnownHeads.set(i,r)}}catch{}}};function A(l,e){return l===null||e===null?0:l-e}var ie={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...ie,...t}}queue;options;async analyze(e,t,i){let r=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!r)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let o=r,n={line:e.overall.line-o.overall.line,branch:A(e.overall.branch,o.overall.branch??null),function:A(e.overall.function,o.overall.function??null),statement:A(e.overall.statement,o.overall.statement??null)},s=n.line<-this.options.regressionThreshold||(n.branch??0)<-this.options.regressionThreshold,a=i??Object.keys(e.files),c=[],d=[];for(let h of a){let u=e.files[h],m=o.files[h];if(!u)continue;let q=m?u.line-m.line:0,N=m?u.branch-m.branch:0,T=m?u.uncoveredLines.filter(_=>!m.uncoveredLines.includes(_)):u.uncoveredLines;if((q!==0||N!==0||T.length>0)&&c.push({file:h,lineDelta:q,branchDelta:N,newUncoveredLines:T}),u.line<this.options.gapThreshold){let _=this.computeRiskScore(u,T.length);d.push({file:h,uncoveredLines:u.uncoveredLines,currentCoverage:u.line,riskScore:_})}}return(s||d.length>0)&&this.enqueueTestSuggestion(e,o,d),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:c.length,gapCount:d.length}),{regressionDetected:s,overallDelta:n,affectedFiles:c,newGaps:d}}async buildSnapshot(e){let t=await e.get("coverage:latest"),i=F(t);if(i)return{timestamp:Date.now(),overall:{line:i.line,branch:i.branch,function:i.function,statement:i.statement},files:t&&typeof t.files=="object"?t.files:{}}}computeRiskScore(e,t){let r=1-Math.min(100,Math.max(0,e.line))/100,o=Math.min(t/50,1);return Math.min(1,r*.6+o*.4)}enqueueTestSuggestion(e,t,i){let r={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},o={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:r,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(o)}};J();import{execFile as re}from"child_process";import{promisify as oe}from"util";var ne=oe(re),se={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...se,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],r=[],o=0;for(let[s,a]of Object.entries(t)){let c=a.filter(m=>m.conclusion==="failure").length,d=a.length>0?(a.length-c)/a.length*100:100,h=this.countConsecutiveFailures(a),u=a[0]?.conclusion??"unknown";u==="failure"&&o++,h>=this.options.flakyThreshold&&(r.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:c,successRate:Math.round(d*10)/10,lastConclusion:u,consecutiveFailures:h})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:o,flakyWorkflows:r,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await ne("gh",e,{timeout:15e3});return JSON.parse(t).map(r=>({name:r.name,status:r.status,conclusion:r.conclusion??"pending",headBranch:r.headBranch,runNumber:r.number,databaseId:r.databaseId,createdAt:r.createdAt}))}catch{return[]}}groupByWorkflow(e){let t=O();for(let i of e){let r=P(t,i.name);r||(r=[],x(t,i.name,r)),r.push(i)}for(let i of Object.keys(t))x(t,i,P(t,i).slice(0,this.options.runsPerWorkflow));return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,r)=>i+r.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},r={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(r)}};var ae={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...ae,...e}}async suggest(e,t,i){let r=[],o=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of o){let a=t.includes(s.file),c=this.determinePriority(s,a),d=this.determineTestType(s.file),h=this.estimateEffort(s);r.push({id:`suggestion-${Date.now()}-${r.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:d,description:this.generateDescription(s,d),priority:c,estimatedEffort:h,createdAt:Date.now(),status:"pending"})}r.sort((s,a)=>{let c={high:0,medium:1,low:2};return c[s.priority]-c[a.priority]});let n=r.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let r=await i.get(`${this.options.memoryPrefix}:list`);if(!r)return!1;let o=r.findIndex(s=>s.id===e);if(o===-1)return!1;let n=r.map((s,a)=>a===o?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,r=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${r}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let o=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,o),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:o.length,lastUpdated:Date.now()})}};var le={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...le,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),r=new Date().toISOString().split("T")[0],o=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(r,t);await e.set(`${this.options.memoryPrefix}:report:${r}`,s),this.lastRunDate=r;let a={timestamp:Date.now(),patternsConsolidated:o,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,r=Date.now();for(let o of t){if(o.endsWith(":snapshot")||o.endsWith(":list"))continue;let n=await e.get(o);n&&typeof n.timestamp=="number"&&r-n.timestamp>this.options.maxEntryAge&&(await e.set(o,{pruned:!0,prunedAt:r}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};B();import{writeFileSync as H,mkdirSync as L,readdirSync as D,readFileSync as U,unlinkSync as z}from"fs";import{join as b}from"path";var ue={maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??W("notifications"),this.maxNotifications=e?.maxNotifications??ue.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){L(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=D(this.notificationsDir).filter(o=>o.endsWith(".json")).sort().reverse(),r=[];for(let o of i){if(r.length>=t)break;try{let n=U(b(this.notificationsDir,o),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;r.push(s)}catch{}}return r}catch{return[]}}markRead(e){try{let t=D(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),o={...JSON.parse(U(i,"utf-8")),read:!0};return H(i,JSON.stringify(o,null,2)),!0}catch{return!1}}clear(){try{let e=D(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)z(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{L(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);H(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=D(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)z(b(this.notificationsDir,i))}catch{}}};var S={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},j=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??S.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??S.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??S.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??S.cpuThreshold,memoryThreshold:e?.memoryThreshold??S.memoryThreshold},this.queue=new p,this.gitWatcher=new g(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs),this.tickTimer.unref?.())}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let r=this.queue.dequeue();if(!r)break;await this.handleQueueItem(r,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":{this._commitsAnalyzed++;let r=await this.coverageDelta.buildSnapshot(t);if(r){let o=await this.coverageDelta.analyze(r,t,i.changedFiles);if(o.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${o.overallDelta.line.toFixed(1)}% (${o.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:o.overallDelta,commit:i.commitHash}}),o.newGaps.length>0){let n=await this.testSuggester.suggest(o.newGaps,i.changedFiles,t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break}case"coverage_delta":{let r=await this.testSuggester.getPending(t);r.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${r.length} test suggestions awaiting review`,severity:"info",metadata:{count:r.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let r={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,r);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);if(i){let r=[i.overall.line,i.overall.branch,i.overall.function,i.overall.statement].filter(o=>typeof o=="number");this._coverageHealth=Math.round(r.reduce((o,n)=>o+n,0)/r.length),this._lastCoverageCheck=t}}catch{}}isResourceConstrained(){if(1-de()/he()>this.config.memoryThreshold)return!0;let t=ce().length;return(t>0?me()[0]/t:0)>this.config.cpuThreshold}};export{pe as a,ge as b,fe as c,R as d,j as e};
@@ -1,3 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{c as p}from"./chunk-PIWGKGWP.js";import*as u from"fs";import*as m from"path";var y=["coverage/coverage-final.json","coverage/coverage-summary.json",".coverage/coverage-final.json"];function F(r){for(let o of y){let s=m.join(r,o);if(u.existsSync(s))try{let t=u.readFileSync(s,"utf-8"),c=JSON.parse(t);if(c.total&&c.total.lines)return x(c,r);let n=new Map;for(let e of p(t).files)n.set(e.path,e);return n.size>0?n:null}catch{continue}}return null}function x(r,o){let s=new Map;for(let[t,c]of Object.entries(r)){if(t==="total")continue;let n=c;s.set(t,{path:t,lines:{covered:n.lines.covered,total:n.lines.total},branches:{covered:n.branches.covered,total:n.branches.total},functions:{covered:n.functions.covered,total:n.functions.total},statements:{covered:n.statements.covered,total:n.statements.total},uncoveredLines:[],uncoveredBranches:[]})}return s.size>0?s:null}function S(r,o){let t=o.split(`
3
- `).length,n=[r.replace(".ts",".test.ts").replace("/src/","/tests/"),r.replace(".ts",".spec.ts").replace("/src/","/tests/"),r.replace(".ts",".test.ts"),r.replace("/src/","/test/").replace(".ts",".test.ts")].some(f=>u.existsSync(f)),e=(o.match(/\bexport\b/g)||[]).length,a=(o.match(/\b(function|=>)\b/g)||[]).length,i=(o.match(/\b(if|switch|case|\?\?|\|\|)\b/g)||[]).length,l;if(n){let f=Math.min(i*.005,.15),b=Math.min(t*1e-4,.1);l=.85-f-b}else l=.2+(e>5?.1:0);l=Math.max(.05,Math.min(.95,l));let v=Math.floor(t*l),g=Math.max(a,1),d=Math.max(i,1),C=Math.floor(v*.7),M=Math.floor(g*l*.9),h=Array.from({length:t-v},(f,b)=>b+v+1);return{path:r,lines:{covered:v,total:t},branches:{covered:Math.min(C,d),total:d},functions:{covered:Math.min(M,g),total:g},statements:{covered:v,total:t},uncoveredLines:h,uncoveredBranches:h.slice(0,Math.floor(h.length/2))}}function L(r){let o=e=>r.reduce((a,i)=>a+e(i),0),s=(e,a)=>a>0?Math.round(e/a*100):0,t=o(e=>e.lines.total),c=o(e=>e.lines.covered),n=o(e=>e.statements.total);return{line:s(c,t),branch:s(o(e=>e.branches.covered),o(e=>e.branches.total)),function:s(o(e=>e.functions.covered),o(e=>e.functions.total)),statement:n>0?s(o(e=>e.statements.covered),n):s(c,t),files:r.length}}function B(r,o){let s=o||process.cwd(),t=F(s),c=[],n=[],e=!1;if(t&&t.size>0){e=!0;for(let a of r){let i=m.resolve(a),l=t.get(i)||t.get(a)||t.get(m.relative(s,i));l?c.push({...l,path:a}):n.push(a)}}else for(let a of r){let i=u.existsSync(a)?u.readFileSync(a,"utf-8"):"";c.push(S(a,i))}return{files:c,summary:L(c),instrumented:e,...n.length>0?{unmeasuredFiles:n}:{}}}export{L as a,B as b};
@@ -1,8 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as V,c as Y,d as q,e as R,f as K,j as H}from"./chunk-PIWGKGWP.js";import{c as P,e as Te}from"./chunk-Q6F3DYZN.js";import{c as B,d as C}from"./chunk-O7VJ3VKD.js";import{c as z,d as $e}from"./chunk-GPPTRKEM.js";import*as x from"fs";import*as v from"path";import*as p from"fs";import*as ee from"os";import*as g from"path";Te();function Ae(e=process.env){let t=(e.AQE_COVERAGE_NO_EXEC??"").trim().toLowerCase();return t?t!=="false"&&t!=="0"&&t!=="no"&&t!=="off":!1}var De=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]),te=new Set(["node_modules","dist","build","coverage",".git",".claude",".agentic-qe","__pycache__",".venv","target","vendor"]),ne=new Set(["tests","test","__tests__","benches","examples","spec"]),Pe=[/\.test\./i,/\.spec\./i,/_test\./i,/_spec\./i,/^test_/i,/^test\./i,/^conftest\./i];function E(e,t){let n=e.split(g.sep).join("/"),r=g.basename(n);if(Pe.some(o=>o.test(r)))return!0;let s=n;if(t){let o=g.resolve(t).split(g.sep).join("/"),i=g.resolve(e).split(g.sep).join("/");(i===o||i.startsWith(`${o}/`))&&(s=i.slice(o.length).replace(/^\//,""))}return s.split("/").some(o=>ne.has(o))}function _e(e){let t=e.split(""),n=e.length,r=0,s=(o,i)=>{for(let a=o;a<i&&a<n;a++)e[a]!==`
3
- `&&(t[a]=" ")};for(;r<n;){let o=e[r];if(o==="/"&&e[r+1]==="/"){let a=e.indexOf(`
4
- `,r),c=a===-1?n:a;s(r,c),r=c;continue}if(o==="/"&&e[r+1]==="*"){let a=0,c=r;for(;r<n;){if(e[r]==="/"&&e[r+1]==="*"){a++,r+=2;continue}if(e[r]==="*"&&e[r+1]==="/"){if(a--,r+=2,a===0)break;continue}r++}s(c,r);continue}let i=/^b?r(#*)"/.exec(e.slice(r,r+300));if(i){let a=`"${i[1]}`,c=r+i[0].length,u=e.indexOf(a,c),f=u===-1?n:u+a.length;s(r,f),r=f;continue}if(o==='"'){let a=r;for(r++;r<n;){if(e[r]==="\\"){r+=2;continue}if(e[r]==='"'){r++;break}r++}s(a,r);continue}if(o==="'"){let a=-1;if(e[r+1]==="\\"){let c=e.indexOf("'",r+2);c!==-1&&c<=r+5&&(a=c+1)}else e[r+2]==="'"&&(a=r+3);if(a!==-1){s(r,a),r=a;continue}}r++}return t.join("")}function Ne(e,t){if(t!==".rs")return[];let n=_e(e).split(`
5
- `),r=[];for(let s=0;s<n.length;s++){if(!/#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]/.test(n[s]))continue;let o=-1;for(let c=s;c<Math.min(n.length,s+10);c++){let u=n[c],f=u.indexOf("{"),h=u.indexOf(";");if(h!==-1&&(f===-1||h<f))break;if(f!==-1){let b=n.slice(s,c+1).join(" ");/\bmod\s+\w+/.test(b)&&(o=c);break}}if(o===-1)continue;let i=0,a=-1;for(let c=o;c<n.length;c++){for(let u of n[c])u==="{"?i++:u==="}"&&i--;if(i<=0){a=c;break}}r.push([s+1,(a===-1?n.length-1:a)+1]),s=a===-1?n.length:a}return r}function Me(e){if(e.length===0)return 0;let t=e.split(`
6
- `);return t[t.length-1]===""&&t.pop(),t.length}function re(e,t=6){let n=g.resolve(e);try{if(!p.existsSync(n))return null;p.statSync(n).isDirectory()||(n=g.dirname(n))}catch{return null}for(let r=0;r<=t;r++){if(p.existsSync(g.join(n,"Cargo.toml")))return p.realpathSync(n);let s=g.dirname(n);if(s===n)break;n=s}return null}function se(e,t=0){if(t>4)return!1;let n;try{n=p.readdirSync(e,{withFileTypes:!0})}catch{return!1}for(let r of n)if(r.isFile()&&g.extname(r.name)===".rs")return!0;for(let r of n)if(r.isDirectory()&&!te.has(r.name)&&se(g.join(e,r.name),t+1))return!0;return!1}function vt(e){let t=re(e);if(t===null)return!1;let n=g.resolve(e);return n===t||se(n)}async function bt(e,t={}){if(Ae())return null;let n=t.timeoutMs??3e5,r=re(e);if(!r)return null;let s=await P("cargo",["llvm-cov","--version"],{cwd:r,timeout:3e4});if(s.error||s.status!==0)return null;let o=g.join(p.mkdtempSync(g.join(ee.tmpdir(),"aqe-rust-cov-")),"lcov.info");try{let i=await P("cargo",["llvm-cov","--lcov","--output-path",o],{cwd:r,timeout:n});if(i.error||i.status!==0||!p.existsSync(o))return null;let c=R(p.readFileSync(o,"utf-8")).files.filter(h=>!E(h.path,r));if(c.length===0)return null;let u=oe(c),f=c.some(h=>h.branches.total>0);return{data:u,provenance:{method:"cargo-llvm-cov",estimated:!1,branchDataCollected:f,functionDataCollected:c.some(h=>h.functions.total>0),notes:f?[]:["cargo-llvm-cov reported no branch data (Rust branch coverage requires a nightly toolchain with -Z coverage-options=branch). Branch coverage is reported as null rather than assumed."]}}}catch{return null}finally{try{p.rmSync(g.dirname(o),{recursive:!0,force:!0})}catch{}}}var Z={".rs":{fn:/\bfn\s+\w+/g,branch:/\b(if|match|while|for)\b|\?\?|\|\||&&/g},".go":{fn:/\bfunc\s+\w*/g,branch:/\b(if|switch|case|for|select)\b|\|\||&&/g},".py":{fn:/\b(def|lambda)\b/g,branch:/\b(if|elif|for|while|except)\b|\band\b|\bor\b/g},".java":{fn:/\b(public|private|protected|static)[\w<>,\s[\]]+\w+\s*\(/g,branch:/\b(if|switch|case|for|while|catch)\b|\|\||&&/g},".rb":{fn:/\bdef\s+\w+/g,branch:/\b(if|elsif|unless|case|when|while)\b|\|\||&&/g},default:{fn:/\bfunction\b|=>|\b\w+\s*\([^)]*\)\s*\{/g,branch:/\b(if|switch|case|for|while|catch)\b|\?\?|\|\||&&/g}};function Ie(e){return Z[e]??Z.default}function Q(e,t){return(e.match(new RegExp(t.source,t.flags))||[]).length}function oe(e){let t=o=>e.reduce((i,a)=>i+o(a),0),n=(o,i)=>i>0?Math.round(o/i*100):0,r=t(o=>o.lines.total),s=t(o=>o.lines.covered);return{files:e,summary:{line:n(s,r),branch:n(t(o=>o.branches.covered),t(o=>o.branches.total)),function:n(t(o=>o.functions.covered),t(o=>o.functions.total)),statement:n(s,r),files:e.length}}}function _(e){let t=[],n=e;function r(s,o){if(o>6)return;let i;try{i=p.readdirSync(s,{withFileTypes:!0})}catch{return}for(let a of i){let c=g.join(s,a.name);if(a.isDirectory()){if(te.has(a.name)||ne.has(a.name))continue;r(c,o+1)}else if(a.isFile()){if(!De.has(g.extname(a.name))||E(c,n))continue;t.push(c)}}}return r(e,0),t}function yt(e){if(!p.existsSync(e)||!p.statSync(e).isDirectory())return null;let t=_(e);if(t.length===0)return null;let n=t.map(r=>{let s="";try{s=C(r,{outsideRoot:"allow"})}catch{}let o=g.extname(r),i=Me(s),a=Ne(s,o),c=y=>a.some(([A,D])=>y>=A&&y<=D),u=a.reduce((y,[A,D])=>y+(D-A+1),0),f=Math.max(i-u,0),h=Ie(o),b=Q(s,h.fn),Ce=a.length>0,Se=Le(r),we=Ce||Se,Ee=Q(s,h.branch),je=Math.min(Ee*.005,.15),Re=Math.min(f*1e-4,.1),ke=Math.max(.05,Math.min(.95,we?.85-je-Re:.2)),T=Math.floor(f*ke),X=[];for(let y=1;y<=i;y++)c(y)||X.push(y);let Fe=X.slice(T);return{path:r,lines:{covered:T,total:f},branches:{covered:0,total:0},functions:{covered:0,total:b},statements:{covered:T,total:f},uncoveredLines:Fe,uncoveredBranches:[]}});return{data:oe(n),provenance:{method:"static-estimation",estimated:!0,branchDataCollected:!1,functionDataCollected:!1,notes:["No instrumentation ran. These numbers are a STATIC ESTIMATE derived from source shape (file size, declaration counts, presence of a test file) \u2014 they are not measured coverage and must not be reported as such.","Branch and function coverage were not collected and are reported as null."]}}}function Le(e){let t=g.extname(e),n=e.slice(0,-t.length);return[`${n}.test${t}`,`${n}.spec${t}`,`${n}_test${t}`,`${n}.test${t}`.replace("/src/","/tests/"),`${n}.spec${t}`.replace("/src/","/tests/"),`${n}${t}`.replace("/src/","/tests/")].some(s=>{try{return p.existsSync(s)}catch{return!1}})}import*as M from"fs";import*as m from"path";var I=["ts","mts","cts","js","mjs","cjs"],Oe=[...I.map(e=>`vitest.config.${e}`),...I.map(e=>`vite.config.${e}`)],We=[...I.map(e=>`jest.config.${e}`),"jest.config.json"],Ue=[".nycrc",".nycrc.json"],Je=[".c8rc",".c8rc.json"];function Ge(e){return e.replace(/[.+^$()|[\]\\]/g,"\\$&")}function ce(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r==="*"&&e[n+1]==="*")e[n+2]==="/"?(t+="(?:.*/)?",n+=2):(t+=".*",n+=1);else if(r==="*")t+="[^/]*";else if(r==="?")t+="[^/]";else if(r==="{"){let s=e.indexOf("}",n);if(s===-1){t+="\\{";continue}t+=`(?:${e.slice(n+1,s).split(",").map(ce).join("|")})`,n=s}else t+=Ge(r)}return t}function ie(e){let t=e.replace(/^<rootDir>\//,"").replace(/^\.\//,"").replace(/\/+$/,"");return new RegExp(`^${ce(t)}(?:/.*)?$`)}function le(e){let t="";for(let n=0;n<e.length;n++){let r=e[n];if(r==='"'||r==="'"||r==="`"){let s=n;for(n++;n<e.length&&e[n]!==r;n++)e[n]==="\\"&&n++;t+=e.slice(s,n+1)}else if(r==="/"&&e[n+1]==="/"){for(;n<e.length&&e[n]!==`
7
- `;)n++;t+=`
8
- `}else if(r==="/"&&e[n+1]==="*"){let s=e.indexOf("*/",n+2);n=s===-1?e.length:s+1}else t+=r}return t}function ue(e,t){let n={"[":"]","{":"}","(":")"},r=[];for(let s=t;s<e.length;s++){let o=e[s];if(o==='"'||o==="'"||o==="`")for(s++;s<e.length&&e[s]!==o;s++)e[s]==="\\"&&s++;else if(n[o])r.push(n[o]);else if(o===r[r.length-1]&&(r.pop(),r.length===0))return s+1}return-1}function Xe(e){let t=[],n=0,r=0;for(let s=0;s<e.length;s++){let o=e[s];if(o==='"'||o==="'"||o==="`")for(s++;s<e.length&&e[s]!==o;s++)e[s]==="\\"&&s++;else"[{(".includes(o)?n++:"]})".includes(o)?n--:o===","&&n===0&&(t.push(e.slice(r,s)),r=s+1)}return t.push(e.slice(r)),t.map(s=>s.trim()).filter(s=>s.length>0)}var ae=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$|^`([^`$\\]*)`$/;function $(e,t){let n=new RegExp(`(?:^|[\\s,{])['"]?${t}['"]?\\s*:\\s*`).exec(e);if(!n)return;let r=n.index+n[0].length;if(e[r]==="'"||e[r]==='"'){let i=ae.exec(e.slice(r,ze(e,r)));return i?[i[2]??i[3]]:null}if(e[r]!=="[")return null;let s=ue(e,r);if(s===-1)return null;let o=[];for(let i of Xe(e.slice(r+1,s-1))){if(/^\.\.\.[\w$.]*defaults?\b/i.test(i))continue;let a=ae.exec(i);if(!a)return null;o.push(a[2]??a[3])}return o}function ze(e,t){let n=t+1;for(;n<e.length&&e[n]!==e[t];n++)e[n]==="\\"&&n++;return n+1}function L(e){try{return C(e,{outsideRoot:"allow"})}catch{return null}}function N(e){let t=L(e);if(t===null)return null;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null?n:null}catch{return null}}var k=e=>e===void 0?void 0:typeof e=="string"?[e]:Array.isArray(e)&&e.every(t=>typeof t=="string")?e:null;function S(e,t){let n=[t.include,t.exclude,t.collectFrom,t.ignore].every(o=>o!==null),r=t.collectFrom??[],s=[];for(let o of t.ignore??[])try{s.push(new RegExp(o))}catch{}return{source:e,readable:n,ignorePatterns:s,include:[...t.include??[],...r.filter(o=>!o.startsWith("!"))],exclude:[...t.exclude??[],...r.filter(o=>o.startsWith("!")).map(o=>o.slice(1))]}}function Be(e,t){let n=le(t),r=/(?:^|[\s,{])['"]?coverage['"]?\s*(?::\s*|(?=[,}]))/.exec(n);if(!r)return null;let s=r.index+r[0].length;if(!r[0].includes(":")||n[s]!=="{")return S(e,{include:null});let o=ue(n,s),i=o===-1?"":n.slice(s,o);return S(e,{include:$(i,"include"),exclude:$(i,"exclude")})}function Ve(e,t){let n=le(t),r=$(n,"collectCoverageFrom"),s=$(n,"coveragePathIgnorePatterns");return r===void 0&&s===void 0?null:S(e,{collectFrom:r,ignore:s})}function F(e,t){return!t||typeof t!="object"?null:"collectCoverageFrom"in t||"coveragePathIgnorePatterns"in t?S(e,{collectFrom:k(t.collectCoverageFrom),ignore:k(t.coveragePathIgnorePatterns)}):"include"in t||"exclude"in t?S(e,{include:k(t.include),exclude:k(t.exclude)}):null}function fe(e){for(let r of Oe){let s=L(m.join(e,r));if(s!==null){let o=Be(r,s);if(o)return o}}for(let r of We){let s=m.join(e,r);if(!M.existsSync(s))continue;let o=r.endsWith(".json")?F(r,N(s)??void 0):Ve(r,L(s)??"");if(o)return o}let t=N(m.join(e,"package.json")),n=F('package.json "jest"',t?.jest);if(n)return n;for(let[r,s]of[[Ue,"nyc"],[Je,"c8"]]){for(let i of r){let a=N(m.join(e,i)),c=F(i,a??void 0);if(c)return c;if(!a&&M.existsSync(m.join(e,i)))return S(i,{include:null})}let o=F(`package.json "${s}"`,t?.[s]);if(o)return o}return null}function ge(e,t,n){if(!e)return!0;let r=m.relative(n,t).split(m.sep).join("/");if(e.include.length>0&&!e.include.some(i=>ie(i).test(r))||e.exclude.some(i=>ie(i).test(r)))return!1;let s=t.split(m.sep).join("/"),o=n.split(m.sep).join("/");return!e.ignorePatterns.some(i=>i.test(s)||i.test(s.replace(o,"<rootDir>")))}var Ye=[[".ts",".tsx",".js",".jsx",".mjs",".cjs"],[".py"],[".go"],[".rs"],[".java"],[".rb"]];function pe(e){let t=v.extname(e).toLowerCase();return Ye.find(n=>n.includes(t))}function qe(e){let t=v.basename(e);return t.endsWith(".d.ts")||t.startsWith(".")||/\.config\.[cm]?[jt]sx?$/.test(t)}function j(e){try{return x.realpathSync(e)}catch{return v.resolve(e)}}function de(e,t){let n=j(t);return new Set(e.map(r=>v.isAbsolute(r.path)?j(r.path):j(v.resolve(n,r.path))))}function Ke(e,t,n){let r=!1;try{r=x.statSync(n).isDirectory()}catch{}if(!r)return{targetFiles:[],unmeasured:[]};let s=j(t),o=fe(s),i=new Set(e.map(u=>pe(u.path)).filter(Boolean)),a=de(e,t),c=_(n).filter(u=>i.has(pe(u))&&!qe(u)).map(j).filter(u=>ge(o,u,s));return{targetFiles:c,unmeasured:c.filter(u=>!a.has(u)).sort(),...o?{coverageScope:{source:o.source,readable:o.readable}}:{}}}function He(e,t){let n;try{n=x.statSync(e).mtimeMs}catch{return}let r=t.filter(s=>{try{return x.statSync(s).mtimeMs>n}catch{return!1}}).sort();return r.length>0?{reportPath:e,reportModified:new Date(n).toISOString(),newerFiles:r}:void 0}function he(e,t,n,r,s={}){let{targetFiles:o,unmeasured:i,coverageScope:a}=s.checkCompleteness===!1?{targetFiles:[],unmeasured:[],coverageScope:void 0}:Ke(e.files,n,r),c=new Set([...o,...de(t,n)]),u=s.reportPath?He(s.reportPath,[...c].filter(b=>x.existsSync(b))):void 0,f=s.excluded??[],h=[...new Set(f.flatMap(b=>b.file?[b.file]:[]))].sort();return{status:i.length>0||u||h.length>0?"insufficient-evidence":"complete",unmeasuredFiles:i,targetFiles:c.size+h.filter(b=>!c.has(b)).length,...u?{stale:u}:{},...a?{coverageScope:a}:{},...f.length>0?{excludedEntries:f}:{},...h.length>0?{conflictingFiles:h}:{}}}var w=5;function O(e,t){return e.slice(0,w).map(r=>v.relative(t,r)||r).join(", ")+(e.length>w?`, \u2026 ${e.length-w} more`:"")}function jt(e,t){if(!e)return[];let n=[],r=e.unmeasuredFiles.length;if(r>0){let o=e.coverageScope,i=o&&!o.readable?` The coverage include/exclude in ${o.source} could not be read statically, so files it leaves out may be listed here; write them as literal string arrays to have them honoured.`:"";n.push(`${r} of ${e.targetFiles} source files under the target are not in the coverage report (UNMEASURED, not counted as covered): ${O(e.unmeasuredFiles,t)}. Regenerate the report with coverage for the whole target, or exclude files that are not meant to be measured in the coverage tool's include/exclude config.${i}`)}let s=e.conflictingFiles??[];if(s.length>0&&n.push(`${s.length} source file${s.length===1?" is":"s are"} listed in the coverage report under two spellings (e.g. \`./src/a.ts\` and \`src/a.ts\`), so which entry is right is unknown; they are UNMEASURED and left out of the figures: ${O(s,t)}`),e.stale){let o=e.stale.newerFiles.length;n.push(`the coverage report ${v.relative(t,e.stale.reportPath)||e.stale.reportPath} is STALE: ${o} source file${o===1?" was":"s were"} modified after it was written (${e.stale.reportModified}): ${O(e.stale.newerFiles,t)}`)}return n}var Ze={"outside-project":"outside the project root","windows-path":"a Windows path, which cannot name a file here","duplicate-spelling":"a second spelling of a file the report already lists"};function Rt(e){let t=(e?.excludedEntries??[]).filter(s=>s.reason!=="duplicate-spelling");if(t.length===0)return[];let n=t.slice(0,w).map(s=>`${s.path} (${Ze[s.reason]})`),r=t.length>w?`, \u2026 ${t.length-w} more`:"";return[`${t.length} coverage report entr${t.length===1?"y is":"ies are"} not a project file and ${t.length===1?"is":"are"} left out of the figures: ${n.join(", ")}${r}.`]}import*as d from"fs";import*as ye from"os";import*as l from"path";$e();var Qe=["package.json","pyproject.toml","setup.py","setup.cfg","go.mod","Cargo.toml","pom.xml","build.gradle","build.gradle.kts",".git"],et=["vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","vitest.config.cts","vitest.config.cjs","vitest.workspace.ts","vitest.workspace.js","vitest.workspace.mts","vitest.workspace.mjs","vitest.workspace.json","vite.config.ts","vite.config.js","vite.config.mts","vite.config.mjs","jest.config.ts","jest.config.js","jest.config.mts","jest.config.mjs","jest.config.cts","jest.config.cjs","jest.config.json"];function me(e){return et.some(t=>d.existsSync(l.join(e,t)))?!0:G(e)?.jest!==void 0}function W(e){let t=G(e);if(!t)return null;let n={...t.devDependencies,...t.dependencies};return n.jest||n["@jest/core"]?"jest":n.mocha||n.nyc?"nyc":n.vitest?"vitest":null}function tt(e){try{return d.readdirSync(e).some(t=>/^\.(mocharc|nycrc)(\.|$)/.test(t))}catch{return!1}}function nt(e,t){if(tt(e))return(W(t)??"vitest")==="nyc";let n=W(e);return n===null||n===(W(t)??"vitest")}function G(e){try{let t=JSON.parse(C(l.join(e,"package.json"),{outsideRoot:"allow"}));return typeof t=="object"&&t!==null?t:null}catch{return null}}function xe(e){let t=[],n=!1,s=G(e)?.workspaces,o=Array.isArray(s)?s:typeof s=="object"&&s!==null&&Array.isArray(s.packages)?s.packages:null;s!=null&&typeof s=="object"&&(n=!0),o&&t.push(...o.filter(i=>typeof i=="string"));try{let i=C(l.join(e,"pnpm-workspace.yaml"),{outsideRoot:"allow"});n=!0;let a=!1;for(let c of i.split(/\r?\n/)){let u=c.replace(/\s+#.*$/,"").trimEnd();if(/^packages\s*:/.test(u)){a=!0;continue}if(a){let f=/^\s+-\s+(.+)$/.exec(u);f?t.push(f[1].trim().replace(/^['"]|['"]$/g,"")):/^\S/.test(u)&&(a=!1)}}}catch{}return n?t:null}function rt(e){let r=e.replace(/^\.\//,"").replace(/\/+$/,"").replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"\0").replace(/\*\*/g,"").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").split("\0").join("(?:.*/)?").split("").join(".*");return new RegExp(`^${r}$`)}function st(e,t){let n=xe(e);if(!n)return!1;let r=l.relative(e,t).split(l.sep).join("/");if(r===""||r.startsWith("..")||l.isAbsolute(r))return!1;let s=!1;for(let o of n){let i=o.startsWith("!"),a=i?o.slice(1):o;l.isAbsolute(a)||/^[A-Za-z]:/.test(a)||a.split(/[\\/]/).includes("..")||rt(a).test(r)&&(s=!i)}return s}function J(e,t){let n=l.relative(t,e);return n===""||!n.startsWith("..")&&!l.isAbsolute(n)}function ot(e){try{return d.realpathSync(l.resolve(z(e)))}catch{return null}}function ve(e,t=12){let n;try{let a=l.resolve(e);if(!d.existsSync(a))return null;let c=d.realpathSync(a);n=d.statSync(c).isDirectory()?c:l.dirname(c)}catch{return null}let r=null;try{r=d.realpathSync(ye.homedir())}catch{r=null}let s=n,o=null,i=null;for(let a=0;a<=t;a++){if(r!==null&&n===r&&n!==s)return o;if(!o&&Qe.some(u=>d.existsSync(l.join(n,u)))){if(o=n,me(n)||!d.existsSync(l.join(n,"package.json")))return n}else if(o&&xe(n)!==null)return i??=ot(s)??"",i&&J(n,i)&&J(o,i)&&st(n,o)&&me(n)&&nt(o,n)?n:o;if(o&&d.existsSync(l.join(n,".git")))return o;let c=l.dirname(n);if(c===n)return o;n=c}return o}function _t(e,t){try{let n=d.realpathSync(t),r=d.realpathSync(l.resolve(e)),s=d.statSync(r).isDirectory()?r:l.dirname(r);for(;s!==n&&J(s,n);){if(d.existsSync(l.join(s,"package.json")))return`${l.relative(n,s).split(l.sep).join("/")}/`;let o=l.dirname(s);if(o===s)break;s=o}}catch{}return null}var it=new Set(["lcov.info","coverage-final.json","coverage-summary.json","coverage.xml","cobertura-coverage.xml","cobertura.xml"]);function at(e){let t=l.basename(e).toLowerCase();return it.has(t)||t.endsWith(".lcov")||t.endsWith(".lcov.info")}async function ct(e){let t;try{t=await B(e,{outsideRoot:"allow"})}catch{return null}if(t.trim().length===0)return null;try{let n=l.basename(e).toLowerCase(),r;if(n.endsWith(".json")){let s=JSON.parse(t);if(ut(s))r=q(t);else if(lt(s))r=Y(t);else return null}else n.endsWith(".xml")?r=K(t):r=R(t);return r.files.length>0?r:null}catch{return null}}function lt(e){let t=Object.values(e);return t.length>0&&t.every(n=>typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof n.s=="object"&&typeof n.statementMap=="object")}function ut(e){let t=e.total;return typeof t=="object"&&t!==null&&typeof t.lines=="object"}function ft(e,t){let n=l.relative(t,e);return n===""||!n.startsWith("..")&&!l.isAbsolute(n)}function U(e){try{return d.realpathSync(e)}catch{return l.resolve(e)}}function gt(e,t,n){let r=U(t),s=U(n);return s===r?[...e.files]:e.files.filter(o=>{let i=l.isAbsolute(o.path)?U(o.path):l.resolve(r,o.path);return ft(i,s)})}function be(e,t,n,r={}){if(r.numTotalTests===0)return{status:"no-data",reason:"no-tests-ran"};let s=gt(e,t,n),{keys:o,excluded:i}=H(s.map(f=>f.path),t),a=s.filter(f=>o.has(f.path));if(a.length===0)return{status:"no-data",reason:"target-not-covered"};let c=a.filter(f=>!E(f.path,t));if(c.length===0)return{status:"no-data",reason:"test-only-report"};let u=he(e,c,t,n,{reportPath:r.reportPath,checkCompleteness:r.checkCompleteness,excluded:i.filter(f=>!f.file||!E(f.file,t))});return{status:"measured",files:c,evidence:u}}async function Nt(e){let t=l.resolve(e),n;try{n=d.statSync(t)}catch{return{status:"target-missing",target:t}}if(n.isFile()&&at(t)){let o=l.dirname(t),i=ve(o)??(l.basename(o)==="coverage"?l.dirname(o):o),a=await ct(t),c=a?be(a,i,i,{reportPath:t,checkCompleteness:!1}):{status:"no-data",reason:"unreadable-report"};return{status:"evaluated",target:t,projectRoot:i,source:"report-file",evaluation:c}}let r=ve(t)??(n.isDirectory()?t:l.dirname(t)),s=await V(r);return s?{status:"evaluated",target:t,projectRoot:r,source:"project-report",evaluation:be(s.data,r,t,{reportPath:s.path})}:{status:"no-report",target:t,projectRoot:r}}function Mt(e,t,n){let r=[e.line];n.statement!==!1&&r.push(e.statement),n.branch&&r.push(e.branch),n.function&&r.push(e.function);let s=r.reduce((o,i)=>o+i,0)/r.length;return{overall:s,meetsThreshold:s>=t}}var pt=/^Coverage is [\d.]+% below threshold/i;function It(e,t,n,r){let s=e.filter(o=>!pt.test(o)&&(r.branch||!/branch coverage/i.test(o))&&(r.function||!/function coverage/i.test(o)));return t.meetsThreshold?s:[`Coverage is ${(n-t.overall).toFixed(1)}% below threshold. Focus on high-risk files first.`,...s]}function Lt(e){return e==="target-not-covered"||e==="no-tests-ran"}function Ot(e,t,n){switch(e){case"target-missing":return`Target does not exist: ${t}`;case"unreadable-report":return`Unreadable coverage report: ${t}. It could not be parsed or lists no files. Supported: lcov.info, istanbul coverage-final.json / coverage-summary.json, Cobertura XML. Raw V8 output is not supported \u2014 convert it with c8 or your runner's istanbul reporter.`;case"test-only-report":return"The coverage report contains only test files, so there is no production coverage to report. Coverage OF a test file is not a meaningful metric. Check that your coverage tool is instrumenting your source directory.";case"target-not-covered":return`Target is UNMEASURED: the coverage data for project ${n??"?"} has no entry for any production file under ${t}. This is not 0% coverage \u2014 no measurement exists for it. Check your coverage tool's include/exclude settings, or regenerate the report.`;case"no-tests-ran":return`Target is UNMEASURED: the test runner reported running 0 tests from ${n??"?"}. This is not 0% coverage.`}}export{Ae as a,re as b,vt as c,bt as d,yt as e,jt as f,Rt as g,_t as h,ct as i,gt as j,be as k,Nt as l,Mt as m,It as n,Lt as o,Ot as p};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{c as w,d as N}from"./chunk-GPPTRKEM.js";import{c as x,e as E}from"./chunk-J7Q5TXFZ.js";N();E();import{constants as S}from"node:fs";import*as l from"node:fs";import*as p from"node:fs/promises";import*as u from"node:path";var v=128*1024*1024,m=class extends x{constructor(e,c,n){super(`Cannot read ${e}: ${c}`);this.filePath=e;this.reason=c;this.name="ConfinedReadError",this.code=n??c.toUpperCase().replace(/-/g,"_")}filePath;reason;code},O=S.O_RDONLY|(S.O_NOFOLLOW??0)|(S.O_NONBLOCK??0);function g(t,r){let e=u.relative(t,r);return e===""||e!==".."&&!e.startsWith(`..${u.sep}`)&&!u.isAbsolute(e)}async function B(t,r,e){let c=async i=>{let o=await p.stat(i).catch(()=>null);return o!==null&&o.dev===e.dev&&o.ino===e.ino},n=await p.realpath(`/proc/self/fd/${t}`).catch(()=>null);if(n&&u.isAbsolute(n)&&await c(n))return n;let a=await p.realpath(r).catch(()=>null);return a&&await c(a)?a:null}function F(t,r,e){let c=o=>{try{let y=l.statSync(o);return y.dev===e.dev&&y.ino===e.ino}catch{return!1}},n=o=>{try{return l.realpathSync(o)}catch{return null}},a=n(`/proc/self/fd/${t}`);if(a&&u.isAbsolute(a)&&c(a))return a;let i=n(r);return i&&c(i)?i:null}function R(t){let r=t?.code;return r==="ENOENT"||r==="ENOTDIR"?"not-found":r==="EISDIR"||r==="ELOOP"?"not-a-file":"unreadable"}function s(t,r,e){return new m(t,r,e?.code)}function b(t,r,e){if(typeof t!="string"||t===""||t.includes("\0"))throw s(String(t),"unreadable");let c=u.resolve(e.projectRoot??w()),n=u.resolve(t),a=g(c,n)||g(r,n);if(!a&&e.outsideRoot!=="allow")throw s(t,"outside-project-root");return{lexical:n,rootReal:r,inRoot:a,limit:e.maxBytes??v}}function C(t,r,e){if(!r.isFile())throw s(t,"not-a-file");if(r.size>e)throw s(t,"too-large")}async function j(t,r={}){let e=u.resolve(r.projectRoot??w()),c=await p.realpath(e).catch(()=>e),n=b(t,c,r),a;try{a=await p.realpath(n.lexical)}catch(o){throw s(t,R(o),o)}if(n.inRoot&&!g(n.rootReal,a))throw s(t,"outside-project-root");let i;try{i=await p.open(a,O)}catch(o){throw s(t,R(o),o)}try{let o=await i.stat();if(C(t,o,n.limit),n.inRoot){let f=await B(i.fd,a,o);if(!f||!g(n.rootReal,f))throw s(t,"outside-project-root")}let y=[],d=0;for(;;){let f=Buffer.allocUnsafe(Math.min(65536,n.limit+1-d)),{bytesRead:h}=await i.read(f,0,f.length,null);if(h===0)break;if(y.push(f.subarray(0,h)),d+=h,d>n.limit)throw s(t,"too-large")}return Buffer.concat(y,d)}catch(o){throw o instanceof m?o:s(t,R(o),o)}finally{await i.close().catch(()=>{})}}async function D(t,r={}){return(await j(t,r)).toString("utf-8")}function L(t,r={}){let e=u.resolve(r.projectRoot??w()),c=e;try{c=l.realpathSync(e)}catch{}let n=b(t,c,r),a;try{a=l.realpathSync(n.lexical)}catch(o){throw s(t,R(o),o)}if(n.inRoot&&!g(n.rootReal,a))throw s(t,"outside-project-root");let i;try{i=l.openSync(a,O)}catch(o){throw s(t,R(o),o)}try{let o=l.fstatSync(i);if(C(t,o,n.limit),n.inRoot){let f=F(i,a,o);if(!f||!g(n.rootReal,f))throw s(t,"outside-project-root")}let y=[],d=0;for(;;){let f=Buffer.allocUnsafe(Math.min(65536,n.limit+1-d)),h=l.readSync(i,f,0,f.length,null);if(h===0)break;if(y.push(f.subarray(0,h)),d+=h,d>n.limit)throw s(t,"too-large")}return Buffer.concat(y,d)}catch(o){throw o instanceof m?o:s(t,R(o),o)}finally{try{l.closeSync(i)}catch{}}}function I(t,r={}){return L(t,r).toString("utf-8")}export{m as a,j as b,D as c,I as d};
@@ -1,3 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{c as J}from"./chunk-NQFDJ6BT.js";import{c as $}from"./chunk-O7VJ3VKD.js";import{b as K,d as Q}from"./chunk-CMN7PU2H.js";import{c as P,d as G}from"./chunk-GPPTRKEM.js";import*as W from"fs/promises";import*as C from"path";Q();async function ie(e){let s=[C.join(e,"coverage","coverage-final.json"),C.join(e,"coverage","lcov.info"),C.join(e,".nyc_output","coverage-final.json"),C.join(e,"coverage-final.json"),C.join(e,"coverage","coverage-summary.json"),C.join(e,"coverage.xml"),C.join(e,"htmlcov","status.json"),C.join(e,"cobertura-coverage.xml")];for(let t of s)try{let c=await $(t,{outsideRoot:"allow"});if(t.endsWith("coverage-summary.json"))return{data:Z(c),path:t};if(t.endsWith(".json"))return{data:Y(c),path:t};if(t.endsWith(".info"))return{data:ee(c),path:t};if(t.endsWith(".xml"))return{data:te(c),path:t}}catch{}return null}function V(e){let s=new Map,t=e.statementMap||{};for(let[c,l]of Object.entries(e.s||{})){let r=t[c]?.start?.line;if(typeof r!="number")continue;let o=s.get(r);(o===void 0||o<l)&&s.set(r,l)}return s}function Y(e){let s=K(e),t=[],c=0,l=0,r=0,o=0,n=0,u=0,g=0,a=0;for(let[b,f]of Object.entries(s)){let p=f,d=p.s||{},F=p.branchMap||{},v=p.b||{},R=p.f||{},i=V(p),w=i.size,x=[...i.values()].filter(h=>h>0).length,y=Object.values(v).flat().length,N=Object.values(v).flat().filter(h=>h>0).length,L=Object.keys(R).length,S=Object.values(R).filter(h=>h>0).length,k=Object.keys(d).length,I=Object.values(d).filter(h=>h>0).length,_=[...i.entries()].filter(([,h])=>h===0).map(([h])=>h),B=[];for(let[h,M]of Object.entries(v)){let D=F[h];M.forEach((E,j)=>{E===0&&D?.locations?.[j]?.start?.line&&B.push(D.locations[j].start.line)})}t.push({path:b,lines:{covered:x,total:w},branches:{covered:N,total:y},functions:{covered:S,total:L},statements:{covered:I,total:k},uncoveredLines:_.sort((h,M)=>h-M),uncoveredBranches:Array.from(new Set(B)).sort((h,M)=>h-M)}),c+=w,l+=x,r+=y,o+=N,n+=L,u+=S,g+=k,a+=I}return{files:t,summary:{line:c>0?l/c*100:0,branch:r>0?o/r*100:0,function:n>0?u/n*100:0,statement:g>0?a/g*100:0,files:t.length}}}function Z(e){let s=K(e),t=o=>({covered:Number(o?.covered)||0,total:Number(o?.total)||0}),c=[];for(let[o,n]of Object.entries(s))o==="total"||typeof n!="object"||n===null||!n.lines||c.push({path:o,lines:t(n.lines),branches:t(n.branches),functions:t(n.functions),statements:t(n.statements??n.lines),uncoveredLines:[],uncoveredBranches:[]});let l=o=>c.reduce((n,u)=>({covered:n.covered+o(u).covered,total:n.total+o(u).total}),{covered:0,total:0}),r=o=>o.total>0?o.covered/o.total*100:0;return{files:c,summary:{line:r(l(o=>o.lines)),branch:r(l(o=>o.branches)),function:r(l(o=>o.functions)),statement:r(l(o=>o.statements)),files:c.length}}}function ee(e){let s=[],t=e.split(`
3
- `),c=null,l=0,r=0,o=0,n=0,u=0,g=0,a=[],b=[];for(let i of t)if(i.startsWith("SF:"))c=i.slice(3);else if(i.startsWith("LF:"))l=parseInt(i.slice(3),10);else if(i.startsWith("LH:"))r=parseInt(i.slice(3),10);else if(i.startsWith("BRF:"))o=parseInt(i.slice(4),10);else if(i.startsWith("BRH:"))n=parseInt(i.slice(4),10);else if(i.startsWith("FNF:"))u=parseInt(i.slice(4),10);else if(i.startsWith("FNH:"))g=parseInt(i.slice(4),10);else if(i.startsWith("DA:")){let[w,x]=i.slice(3).split(",").map(y=>parseInt(y,10));x===0&&a.push(w)}else if(i.startsWith("BRDA:")){let w=i.slice(5).split(","),x=parseInt(w[0],10),y=w[3];(y==="0"||y==="-")&&b.push(x)}else i==="end_of_record"&&c&&(s.push({path:c,lines:{covered:r,total:l},branches:{covered:n,total:o},functions:{covered:g,total:u},statements:{covered:0,total:0},uncoveredLines:Array.from(new Set(a)),uncoveredBranches:Array.from(new Set(b))}),c=null,l=r=0,o=n=0,u=g=0,a.length=0,b.length=0);let f=0,p=0,d=0,F=0,v=0,R=0;for(let i of s)f+=i.lines.total,p+=i.lines.covered,d+=i.branches.total,F+=i.branches.covered,v+=i.functions.total,R+=i.functions.covered;return{files:s,summary:{line:f>0?p/f*100:0,branch:d>0?F/d*100:0,function:v>0?R/v*100:0,statement:f>0?p/f*100:0,files:s.length}}}function te(e){let s=[];function t(d,F){let v=d.match(new RegExp(`${F}=["']([^"']*)["']`));return v?v[1]:null}let c=/<class\s[^>]*?>/g,l;for(;(l=c.exec(e))!==null;){let d=l[0],F=t(d,"filename");if(!F)continue;let v=parseFloat(t(d,"line-rate")||"NaN"),R=parseFloat(t(d,"branch-rate")||"NaN"),i=l.index,w=e.indexOf("</class>",i),x=w>i?e.slice(i,w):"",y=0,N=0,L=0,S=0,k=0,I=0,_=[],B=[],h=/<line\s([^>]*?)\/>/g,M;for(;(M=h.exec(x))!==null;){let j=M[1],T=parseInt(t(j,"number")||"0",10),O=parseInt(t(j,"hits")||"0",10),z=t(j,"branch")==="true",A=t(j,"condition-coverage");y++,O>0?N++:_.push(T),z&&(L++,(A?parseInt(A,10):O>0?100:0)===100?S++:B.push(T))}let D=/<method\s([^>]*?)>/g,E;for(;(E=D.exec(x))!==null;){k++;let j=E.index,T=x.indexOf("</method>",j);if(T>j){let O=x.slice(j,T),z=/<line\s([^>]*?)\/>/g,A=!1,H;for(;(H=z.exec(O))!==null;)if(parseInt(t(H[1],"hits")||"0",10)>0){A=!0;break}A&&I++}}y===0&&!isNaN(v)&&(y=100,N=Math.round(Math.max(0,Math.min(1,v))*100)),s.push({path:F,lines:{covered:N,total:y},branches:{covered:S,total:L},functions:{covered:I,total:k},statements:{covered:0,total:0},uncoveredLines:_,uncoveredBranches:B})}let r=0,o=0,n=0,u=0,g=0,a=0;for(let d of s)r+=d.lines.total,o+=d.lines.covered,n+=d.branches.total,u+=d.branches.covered,g+=d.functions.total,a+=d.functions.covered;let b=e.match(/<coverage\s[^>]*?>/),f=b?parseFloat(t(b[0],"line-rate")||"NaN")*100:NaN,p=b?parseFloat(t(b[0],"branch-rate")||"NaN")*100:NaN;return{files:s,summary:{line:isNaN(f)?r>0?o/r*100:0:f,branch:isNaN(p)?n>0?u/n*100:0:p,function:g>0?a/g*100:0,statement:r>0?o/r*100:0,files:s.length}}}async function ce(e,s={}){let t=[],{includeTests:c=!0,languages:l,maxFiles:r=5e3,completeScope:o=!1}=s,n=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs",".py",".pyw",".go",".rs",".java",".kt",".kts",".rb",".cs",".php",".swift",".c",".h",".cpp",".hpp",".cc",".scala"];if(l&&l.length>0){n=[];for(let a of l)a==="typescript"&&n.push(".ts",".tsx",".mts",".cts"),a==="javascript"&&n.push(".js",".jsx",".mjs",".cjs"),a==="python"&&n.push(".py",".pyw"),a==="go"&&n.push(".go"),a==="rust"&&n.push(".rs"),a==="java"&&n.push(".java"),a==="kotlin"&&n.push(".kt",".kts"),a==="ruby"&&n.push(".rb"),(a==="csharp"||a==="c#")&&n.push(".cs"),a==="php"&&n.push(".php"),a==="swift"&&n.push(".swift"),(a==="c"||a==="cpp"||a==="c++")&&n.push(".c",".h",".cpp",".hpp",".cc"),a==="scala"&&n.push(".scala")}o&&(!l||l.length===0)&&n.push(".vue",".svelte");async function u(a){try{let b=await W.readdir(a,{withFileTypes:!0});for(let f of b){let p=C.join(a,f.name);if(f.isDirectory()){if(["node_modules",".git","dist","build","coverage",".nyc_output","__pycache__",".venv","venv",".tox",".mypy_cache","target",".gradle","vendor",".bundle",".cache",".npm",".yarn",".next",".nuxt",".svelte-kit","out",".turbo","tmp","temp",".tmp"].includes(f.name)||J(a,f.name,a===e))continue;if(t.length>=r)return;await u(p)}else if(f.isFile()||o&&f.isSymbolicLink()&&await g(p)){let d=C.extname(f.name);if(!n.includes(d)||!c&&(f.name.includes(".test.")||f.name.includes(".spec.")||f.name.endsWith("_test.ts")||f.name.endsWith("_test.js")||p.includes("/__tests__/")||p.includes("/test/")||p.includes("/tests/")))continue;if(t.length>=r)return;t.push(p)}}}catch{}}async function g(a){try{return(await W.stat(a)).isFile()}catch{return!1}}try{if((await W.stat(e)).isFile())return[e];await u(e)}catch{}return t}function le(e){let s=new Set,t={injection:"Use parameterized queries and input validation to prevent injection attacks",xss:"Sanitize user input and use Content-Security-Policy headers","sensitive-data":"Never hardcode secrets; use environment variables or secret managers","access-control":"Implement proper authentication and authorization checks","security-misconfiguration":"Review and harden security configurations","insecure-deserialization":"Avoid deserializing untrusted data; use safe alternatives","broken-auth":"Use strong authentication mechanisms and secure session management",dependencies:"Keep dependencies updated and regularly audit for vulnerabilities"};for(let r of e){let o=t[r.category];o&&s.add(o)}let c=e.some(r=>r.severity==="critical"),l=e.some(r=>r.severity==="high");return c&&s.add("CRITICAL: Address critical vulnerabilities immediately before deployment"),l&&s.add("Prioritize fixing high-severity issues in the next sprint"),s.size===0&&e.length===0&&s.add("No vulnerabilities found - maintain current security practices"),Array.from(s)}G();import*as U from"fs";import*as m from"path";function X(e,s){return m.isAbsolute(e)?m.normalize(e):m.resolve(s??P(),e)}function q(e,s){let t=m.relative(e,s);return t!==""&&t!==".."&&!t.startsWith(`..${m.sep}`)&&!m.isAbsolute(t)}function ne(e){try{return U.realpathSync(e)}catch{return e}}function se(e,s){let t=m.resolve(s??P()),c=ne(t),l=new Map,r=[],o=new Map;for(let n of e){if(!m.isAbsolute(n)&&m.win32.isAbsolute(n)){r.push({path:n,reason:"windows-path"});continue}let u=X(n,t);if(!q(t,u)&&!q(c,u)){r.push({path:n,reason:"outside-project"});continue}l.set(n,u),o.set(u,(o.get(u)??0)+1)}for(let[n,u]of l)(o.get(u)??0)>1&&(l.delete(n),r.push({path:n,reason:"duplicate-spelling",file:u}));return{keys:l,excluded:r}}function de(e,s){return se(e,s).keys}function pe(e,s){let t=`coverage:file:${X(e,s)}`,c=`coverage:file:${e}`;return t===c?[t]:[t,c]}function he(e){return{branch:e.some(s=>s.branches.total>0),function:e.some(s=>s.functions.total>0),statement:e.some(s=>s.statements.total>0)}}function me(e,s){return{line:e.line,branch:s.branch?e.branch:null,function:s.function?e.function:null,statement:s.statement?e.statement:null,files:e.files}}export{ie as a,V as b,Y as c,Z as d,ee as e,te as f,ce as g,le as h,X as i,se as j,de as k,pe as l,he as m,me as n};
@@ -1,7 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as u,e as I}from"./chunk-J7Q5TXFZ.js";import{a as p,q as D}from"./chunk-VLTDW7XJ.js";import{b as E}from"./chunk-Z7SKUC6P.js";import{existsSync as l,renameSync as m,copyFileSync as O,readdirSync as F,statSync as N,openSync as j,readSync as B,closeSync as U,writeFileSync as C,rmSync as S}from"node:fs";import{join as _,dirname as Q}from"node:path";function $(e){if(!l(e))return!0;let t;try{t=N(e).size}catch{return!1}if(t===0)return!0;if(t<g.length)return!1;let n;try{n=j(e,"r");let r=Buffer.alloc(g.length);return B(n,r,0,g.length,0),r.equals(g)}catch{return!1}finally{if(n!==void 0)try{U(n)}catch{}}}function W(e){let t;try{return t=new p(e,{readonly:!0,fileMustExist:!0}),t.pragma("integrity_check",{simple:!0})==="ok"}catch{return!1}finally{try{t?.close()}catch{}}}function q(e){return _(Q(e),"backups","verified")}function G(e){if(!l(e))return null;let t=F(e).filter(n=>n.startsWith("memory-")&&n.endsWith(".db")).map(n=>{let r=_(e,n);return{path:r,mtime:N(r).mtimeMs}}).sort((n,r)=>r.mtime-n.mtime);for(let n of t)if(W(n.path))return n.path;return null}function v(e,t){if($(e))return{restored:!1,reason:"healthy"};let n=t?.backupDir??q(e),r=G(n);if(!r)return{restored:!1,reason:"no-verified-backup"};let o=`${e}.restore.lock`;try{C(o,String(process.pid),{flag:"wx"})}catch{return{restored:!1,reason:"restore-in-progress"}}try{if($(e))return{restored:!1,reason:"healthy"};let f=t?.now??Date.now(),a=`${e}.corrupt-${f}`;try{l(e)&&m(e,a);for(let i of["-wal","-shm"])l(e+i)&&m(e+i,a+i)}catch{return{restored:!1,reason:"park-failed"}}let c=`${e}.restoring-${f}`;try{O(r,c),m(c,e)}catch{try{l(c)&&S(c,{force:!0}),!l(e)&&l(a)&&m(a,e)}catch{}return{restored:!1,reason:"copy-failed"}}return{restored:!0,reason:"restored-from-backup",backupUsed:r,parkedTo:a}}finally{try{S(o,{force:!0})}catch{}}}var g,R=E(()=>{"use strict";D();g=Buffer.concat([Buffer.from("SQLite format 3","latin1"),Buffer.from([0])])});function H(e){let t=[],n=e;for(let r=0;n!=null&&r<5;r++){t.push(u(n));let o=n.code;typeof o=="string"&&t.push(o),n=n.cause}return t.join(`
3
- `)}function Y(e){let t=e.split(`
4
- `)[0].trim();return t.endsWith("Tried:")?t.slice(0,-6).trimEnd():t}function A(e,t="better-sqlite3"){if(e==null)return null;let n=H(e),r=Y(u(e));return K.some(o=>o.test(n))?{moduleName:t,reason:"missing-binding",detail:r}:V.some(o=>o.test(n))?{moduleName:t,reason:"abi-mismatch",detail:r}:z.some(o=>o.test(n))?{moduleName:t,reason:"load-failed",detail:r}:null}function Z(e){let{moduleName:t}=e;return[`${t} ${h}: ${X[e.reason]}`," Fix a global install (reinstall, naming the package):",` npm install -g agentic-qe --allow-scripts=${J}`," Or rebuild just the native module in an existing global install:",` npm rebuild -g ${t} --allow-scripts=${t}`," For a project-local install (devDependency), run in the project:",` npm install-scripts approve ${t} && npm rebuild ${t}`,` Original error: ${e.detail}`].join(`
5
- `)}function M(e,t="better-sqlite3"){if(e instanceof d||u(e).includes(h))return e;let n=A(e,t);return n?new d(n,e):e}function se(e){return e instanceof d||u(e).includes(h)||A(e)!==null}var h,J,K,V,z,X,d,x=E(()=>{"use strict";I();h="native module could not be loaded",J="agentic-qe,better-sqlite3,hnswlib-node",K=[/Could not locate the bindings file/i],V=[/NODE_MODULE_VERSION/,/compiled against a different Node\.js version/i,/Module did not self-register/i],z=[/ERR_DLOPEN_FAILED/,/invalid ELF header/i,/wrong ELF class/i,/incompatible architecture/i,/mach-o file, but is an incompatible architecture/i,/\.node: cannot open shared object file/i,/is not a valid Win32 application/i];X={"missing-binding":"its compiled binary is missing. Its install script never ran \u2014 npm 12+ blocks dependency install scripts unless they are allowed (allowScripts).","abi-mismatch":`it was built for a different Node.js version than the one running now (${process.version}). Rebuild it after switching Node versions.`,"load-failed":"the binary exists but the OS refused to load it (wrong platform/architecture or a corrupt build)."};d=class extends Error{moduleName;reason;constructor(t,n){super(Z(t),{cause:n}),this.name="NativeModuleLoadError",this.moduleName=t.moduleName,this.reason=t.reason}}});import{basename as P}from"node:path";function fe(e,t){let n=t?.readonly??!1,r=t?.fileMustExist??!1,o=t?.busyTimeout??5e3,f=t?.walMode??!n;if(t?.autoRestore&&!n){let s=v(e,{backupDir:t.backupDir});s.restored?console.warn(`[safe-db] memory DB at ${e} was malformed; auto-restored from ${s.backupUsed}. Corrupt original parked at ${s.parkedTo}.`):s.reason==="no-verified-backup"&&console.error(`[safe-db] memory DB at ${e} appears malformed and NO verified backup was found to restore from. Leaving it in place for manual inspection.`)}let a=(process.env.AQE_JOURNAL_MODE??"").trim().toUpperCase(),c=process.env.AQE_DISABLE_WAL==="1"||a==="DELETE"||a==="TRUNCATE",i;try{i=new p(e,{readonly:n,fileMustExist:r})}catch(s){throw M(s)}if(i.pragma(`busy_timeout = ${o}`),c){if(!n){let s=(a||"DELETE").toUpperCase(),y=String(i.pragma("journal_mode",{simple:!0})??"").toUpperCase();if(y!==s){try{i.pragma(`journal_mode = ${s}`)}catch(b){let k=b?.code;if(i.close(),k!=="SQLITE_BUSY"&&k!=="SQLITE_LOCKED")throw b;let T=P(e),L=process.env.AQE_DISABLE_WAL==="1"?"AQE_DISABLE_WAL=1":`AQE_JOURNAL_MODE=${a}`;throw new Error(`[safe-db] cannot switch ${e} from '${y}' to '${s}' \u2014 another process holds the database open. ${L} declares WAL unsafe on this filesystem, so writing in '${y}' is NOT safe and this open is refused. Find the holder with:
6
- for p in /proc/[0-9]*; do for f in $p/fd/*; do readlink "$f" 2>/dev/null | grep -q ${JSON.stringify(T)} && echo "$(basename $p) $(tr '\\0' ' ' < $p/cmdline)"; done; done | sort -u
7
- then stop it and retry. Original error: ${b.message}`)}let w=String(i.pragma("journal_mode",{simple:!0})??"").toUpperCase();if(w!==s)throw i.close(),new Error(`[safe-db] journal_mode switch to '${s}' silently did not take on ${e} (still '${w}'). Refusing to write in an unsafe mode.`)}}}else f&&i.pragma("journal_mode = WAL");return i}var ee=E(()=>{D();R();x()});export{M as a,se as b,x as c,fe as d,ee as e};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a as e,b as g,e as t}from"./chunk-DS5IFRY6.js";import{d as r}from"./chunk-5FSPELOG.js";import{b as o}from"./chunk-Z7SKUC6P.js";var L=o(()=>{"use strict";e();g();t();r()});export{L as a};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{c as a,d as b,e as c}from"./chunk-UOVCTK5L.js";import"./chunk-KT2QCXO6.js";import"./chunk-Q6F3DYZN.js";import"./chunk-7BSOO3CY.js";import"./chunk-J7Q5TXFZ.js";import"./chunk-Z7SKUC6P.js";c();export{a as VibiumClientImpl,b as VibiumClientProvider};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i,m as j,n as k,o as l}from"./chunk-2PCEMDIX.js";import"./chunk-INI3Q4CN.js";import"./chunk-VYPVU3JF.js";import"./chunk-2YWYW7NU.js";import"./chunk-WBDWHHKP.js";import"./chunk-YR5QBUHZ.js";import"./chunk-MCXW3DKE.js";import"./chunk-PK34KJH7.js";import"./chunk-OJIUIEI4.js";import"./chunk-SUAZ5Z47.js";import"./chunk-G2X3OLMN.js";import"./chunk-K7WAI662.js";import"./chunk-HFZD5KLR.js";import"./chunk-ECKHDHR2.js";import"./chunk-YCVLKU6H.js";import"./chunk-ZVMSSCTH.js";import"./chunk-VDEKVIP5.js";import"./chunk-ZAQMRFBB.js";import"./chunk-AVHYJ3XP.js";import"./chunk-ORQ2YBRR.js";import"./chunk-JRIJM4LE.js";import"./chunk-VKREKVFI.js";import"./chunk-SAZ4PJBR.js";import"./chunk-WX4PO65Q.js";import"./chunk-VQFV2IPV.js";import"./chunk-IJZFJPHS.js";import"./chunk-QN7HP2UW.js";import"./chunk-5WATBVU6.js";import"./chunk-ZC3KDNJW.js";import"./chunk-PIWGKGWP.js";import"./chunk-AGCS5GSO.js";import"./chunk-X2DWHGCC.js";import"./chunk-NQFDJ6BT.js";import"./chunk-A4BVDYIL.js";import"./chunk-4UKTIQDT.js";import"./chunk-MLMD3I75.js";import"./chunk-CQER6IJ5.js";import"./chunk-JI33PMPZ.js";import"./chunk-DCDSN67A.js";import"./chunk-OWIQR6N2.js";import"./chunk-KR2TAAF6.js";import"./chunk-XEYFZLIT.js";import"./chunk-UOVCTK5L.js";import"./chunk-KT2QCXO6.js";import"./chunk-J6QRNQJF.js";import"./chunk-LV7UIK4Q.js";import"./chunk-DHKSPOUQ.js";import"./chunk-IHQGNDMX.js";import"./chunk-QTQDX4TZ.js";import"./chunk-MGZ6XZHU.js";import"./chunk-P3D7SEHW.js";import"./chunk-PCL5JRKN.js";import"./chunk-776K4ZLE.js";import"./chunk-RKCN4B26.js";import"./chunk-6V6BD6PH.js";import"./chunk-HRUHHHVR.js";import"./chunk-74MDUIAZ.js";import"./chunk-S3DT5TPR.js";import"./chunk-ZWUF27P4.js";import"./chunk-XEMCHGAJ.js";import"./chunk-CVPXHDQU.js";import"./chunk-Q6F3DYZN.js";import"./chunk-C7QLLMYI.js";import"./chunk-DNVRTJKB.js";import"./chunk-S3TBOKAZ.js";import"./chunk-O7VJ3VKD.js";import"./chunk-HWQPMUSN.js";import"./chunk-EPVPXHL7.js";import"./chunk-FBSBXCZS.js";import"./chunk-7BSOO3CY.js";import"./chunk-LN7NKE3N.js";import"./chunk-QJSSUBO3.js";import"./chunk-OO2M2QUV.js";import"./chunk-M2YI5YUR.js";import"./chunk-ND72UDVH.js";import"./chunk-LOMT4UC2.js";import"./chunk-LIF6UWHV.js";import"./chunk-DJDVD6RM.js";import"./chunk-45223KK6.js";import"./chunk-TDZ6N43D.js";import"./chunk-POPSZDI2.js";import"./chunk-MVVVGQJ6.js";import"./chunk-XFTX3KLE.js";import"./chunk-IKB3M7OF.js";import"./chunk-6LSZCEW2.js";import"./chunk-ERYADKMZ.js";import"./chunk-J3QFJI2Y.js";import"./chunk-SRBCBVSI.js";import"./chunk-7SNSI4VY.js";import"./chunk-4NKZU2JZ.js";import"./chunk-EUWG2JG4.js";import"./chunk-UHJVZEQA.js";import"./chunk-CVYPMGUM.js";import"./chunk-LG5PPJT7.js";import"./chunk-IJSROBM6.js";import"./chunk-JVWZAE2H.js";import"./chunk-SAEECT23.js";import"./chunk-NKUHMA4T.js";import"./chunk-LRY6UIRI.js";import"./chunk-KTORRIX3.js";import"./chunk-H2LHWZRE.js";import"./chunk-IQL6XRF5.js";import"./chunk-YMUY3TES.js";import"./chunk-XPTCQKVE.js";import"./chunk-ZGV7L4MW.js";import"./chunk-NZJVDOUN.js";import"./chunk-X5QD76IU.js";import"./chunk-IRHXGCQR.js";import"./chunk-CMN7PU2H.js";import"./chunk-YKRLUTK7.js";import"./chunk-COTQ44YO.js";import"./chunk-U5SMBJ6F.js";import"./chunk-LCWEQRZI.js";import"./chunk-2EQK7B5L.js";import"./chunk-YAJOBZE5.js";import"./chunk-OWIZBZLN.js";import"./chunk-4EJLHNER.js";import"./chunk-LRKLATSH.js";import"./chunk-CXCMATZ6.js";import"./chunk-ZP5AWQRO.js";import"./chunk-VITV7AEC.js";import"./chunk-REY52O7J.js";import"./chunk-BSIWI4ES.js";import"./chunk-TIVKDIF7.js";import"./chunk-DS5IFRY6.js";import"./chunk-5FSPELOG.js";import"./chunk-TWBZONKT.js";import"./chunk-JHKKIJT2.js";import"./chunk-R3KBOQ3O.js";import"./chunk-GPPTRKEM.js";import"./chunk-TM75GAXG.js";import"./chunk-U4S74IIZ.js";import"./chunk-QSQNXBD2.js";import"./chunk-SFITYZLV.js";import"./chunk-J7Q5TXFZ.js";import"./chunk-VLTDW7XJ.js";import"./chunk-Z7SKUC6P.js";export{c as adoptExternalFleet,e as assignAgentLevel,k as disposeFleet,f as getAgentLevel,g as getAllAgentLevels,a as getFleetState,d as getFleetTopology,l as handleAQEHealth,j as handleFleetHealth,h as handleFleetInit,i as handleFleetStatus,b as isFleetInitialized};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.15.17");process.exit(0)}
2
- import{a,b}from"./chunk-HRUHHHVR.js";import"./chunk-74MDUIAZ.js";import"./chunk-XPTCQKVE.js";import"./chunk-REY52O7J.js";import"./chunk-Z7SKUC6P.js";export{a as CrossDomainEventRouter,b as createCrossDomainRouter};