agentic-qe 3.9.17 → 3.9.19

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 (312) hide show
  1. package/.claude/helpers/statusline-v3.cjs +1 -1
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +56 -0
  4. package/README.md +65 -0
  5. package/assets/skills/skills-manifest.json +1 -1
  6. package/dist/cli/bundle.js +5 -5
  7. package/dist/cli/chunks/adapter-5NI3IO42.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-JN7W7O5X.js → agent-booster-wasm-HVBKHNIS.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-F6Q75SJQ.js → agent-handler-XNBDYRSJ.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-3GGTDVR4.js → agent-memory-branch-YCVTQEMJ.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-JOUK5HMO.js +2 -0
  12. package/dist/cli/chunks/{audit-R7KN45HM.js → audit-6C2PE7OY.js} +2 -2
  13. package/dist/cli/chunks/base-DCAB7AHK.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-2LTGEMYR.js → better-sqlite3-HZPCHUQU.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-PML5L6WQ.js → brain-handler-OV75Q2NM.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-OKUPS2XC.js → branch-enumerator-QW6D42HJ.js} +2 -2
  17. package/dist/cli/chunks/{browser-KOQOTSAT.js → browser-5BA7Q7OR.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-A4UV73SZ.js +2 -0
  19. package/dist/cli/chunks/{chunk-ZLOMFM25.js → chunk-255CWHTF.js} +2 -2
  20. package/dist/cli/chunks/{chunk-QW554DTP.js → chunk-2SIQ742L.js} +1 -1
  21. package/dist/cli/chunks/{chunk-XMMKAV5R.js → chunk-2SSDY6OE.js} +2 -2
  22. package/dist/cli/chunks/{chunk-HMT6LKHH.js → chunk-2WJLEZKP.js} +2 -2
  23. package/dist/cli/chunks/{chunk-VX6XHAG2.js → chunk-2WM4NYM5.js} +2 -2
  24. package/dist/cli/chunks/{chunk-6PRIY3HT.js → chunk-2XATUQIG.js} +2 -2
  25. package/dist/cli/chunks/{chunk-BCBC3DVN.js → chunk-3546SG2L.js} +2 -2
  26. package/dist/cli/chunks/{chunk-ORNWQXEX.js → chunk-37DTXQ6P.js} +2 -2
  27. package/dist/cli/chunks/{chunk-3GYAIW2P.js → chunk-3HQ4AZDH.js} +2 -2
  28. package/dist/cli/chunks/{chunk-YUCMGFHE.js → chunk-3X3QQZ7Q.js} +2 -2
  29. package/dist/cli/chunks/{chunk-ZQKNVZPD.js → chunk-44SPMVML.js} +2 -2
  30. package/dist/cli/chunks/{chunk-65Z6HMDA.js → chunk-5KGFDNYI.js} +2 -2
  31. package/dist/cli/chunks/{chunk-OUSQ4KQN.js → chunk-5LXWEAEJ.js} +2 -2
  32. package/dist/cli/chunks/{chunk-DJXYFFGA.js → chunk-5MGRZ4YD.js} +2 -2
  33. package/dist/cli/chunks/{chunk-6YFEWIL5.js → chunk-5R2DUR3A.js} +2 -2
  34. package/dist/cli/chunks/{chunk-QMVGGG4B.js → chunk-5X2AUPK2.js} +1 -1
  35. package/dist/cli/chunks/{chunk-QYDBV5MD.js → chunk-6BRUQTC7.js} +1 -1
  36. package/dist/cli/chunks/{chunk-RP2RHB7H.js → chunk-7IV2RK5M.js} +2 -2
  37. package/dist/cli/chunks/{chunk-A3WC5KTG.js → chunk-7WMHLBNZ.js} +1 -1
  38. package/dist/cli/chunks/{chunk-VYCFMW64.js → chunk-AEET2WOI.js} +68 -67
  39. package/dist/cli/chunks/{chunk-V4DMYY6P.js → chunk-AG7J7DTM.js} +2 -2
  40. package/dist/cli/chunks/{chunk-JT2KLBDB.js → chunk-ALYUJEYA.js} +2 -2
  41. package/dist/cli/chunks/{chunk-L6ZJSFAA.js → chunk-AOASQYOO.js} +1 -1
  42. package/dist/cli/chunks/{chunk-6YCZDIGF.js → chunk-AZKVGH5I.js} +2 -2
  43. package/dist/cli/chunks/{chunk-3UGV2XWF.js → chunk-B2EHSFUW.js} +2 -2
  44. package/dist/cli/chunks/{chunk-TATCL3AK.js → chunk-B65GTWF3.js} +2 -2
  45. package/dist/cli/chunks/{chunk-PMH52K5J.js → chunk-BB3KUX6C.js} +1 -1
  46. package/dist/cli/chunks/{chunk-EGBRCXYT.js → chunk-BFBR2ZZJ.js} +2 -2
  47. package/dist/cli/chunks/{chunk-LD4OYOX2.js → chunk-BGTYOZRK.js} +2 -2
  48. package/dist/cli/chunks/{chunk-KUEG6K4A.js → chunk-BOUCIIUI.js} +1 -1
  49. package/dist/cli/chunks/{chunk-AZWCJFT6.js → chunk-C5YFCM2H.js} +2 -2
  50. package/dist/cli/chunks/{chunk-F5X3U57Y.js → chunk-CYLQTVIA.js} +2 -2
  51. package/dist/cli/chunks/{chunk-G3G5QEHL.js → chunk-D2EHD2KF.js} +1 -1
  52. package/dist/cli/chunks/{chunk-AFLTMVMT.js → chunk-D74RGYKI.js} +1 -1
  53. package/dist/cli/chunks/{chunk-QVJQXRHU.js → chunk-DAPBSAVT.js} +2 -2
  54. package/dist/cli/chunks/{chunk-BGY4CHZA.js → chunk-DZS7XQ2Z.js} +2 -2
  55. package/dist/cli/chunks/{chunk-RYATPB5L.js → chunk-EW5TQQBR.js} +2 -2
  56. package/dist/cli/chunks/{chunk-L5JZIORJ.js → chunk-EZZJ5XD6.js} +2 -2
  57. package/dist/cli/chunks/{chunk-MNSF47HC.js → chunk-FJJLNCSL.js} +3 -3
  58. package/dist/cli/chunks/{chunk-6F6BNLVP.js → chunk-FL2DMHOQ.js} +1 -1
  59. package/dist/cli/chunks/{chunk-EVQYUUQ3.js → chunk-FNVA7U7X.js} +2 -2
  60. package/dist/cli/chunks/{chunk-I3NUJ6KJ.js → chunk-FPVXXQVX.js} +3 -3
  61. package/dist/cli/chunks/{chunk-K4FG3CRS.js → chunk-FT3MAIRW.js} +3 -3
  62. package/dist/cli/chunks/{chunk-CZXV3JAF.js → chunk-G2V4GMPR.js} +3 -3
  63. package/dist/cli/chunks/chunk-GJ5FON37.js +15 -0
  64. package/dist/cli/chunks/{chunk-6PCGUJCG.js → chunk-GL742O2V.js} +4 -4
  65. package/dist/cli/chunks/{chunk-X66N7E7D.js → chunk-GVDLCJC5.js} +1 -1
  66. package/dist/cli/chunks/{chunk-3KIUCAVI.js → chunk-GYDE5TCN.js} +1 -1
  67. package/dist/cli/chunks/{chunk-2K7GRX5U.js → chunk-GYESQBDU.js} +2 -2
  68. package/dist/cli/chunks/{chunk-63ERVKIO.js → chunk-H4QM37XS.js} +1 -1
  69. package/dist/cli/chunks/{chunk-VI2I5R6C.js → chunk-HCSTXZYE.js} +2 -2
  70. package/dist/cli/chunks/{chunk-6HGRJPD6.js → chunk-HJ7CRPZY.js} +1 -1
  71. package/dist/cli/chunks/{chunk-G5DEPXD4.js → chunk-HQFREZRX.js} +2 -2
  72. package/dist/cli/chunks/{chunk-7VGZDTY4.js → chunk-HVNW3TZS.js} +1 -1
  73. package/dist/cli/chunks/{chunk-W5HTZ3VZ.js → chunk-I3JRRFVT.js} +2 -2
  74. package/dist/cli/chunks/{chunk-Y47U7ICT.js → chunk-IG2RCBHJ.js} +1 -1
  75. package/dist/cli/chunks/{chunk-4TDIA2EN.js → chunk-IPLQPBJA.js} +2 -2
  76. package/dist/cli/chunks/{chunk-ARN2KDLJ.js → chunk-IV74GAZN.js} +2 -2
  77. package/dist/cli/chunks/{chunk-I64R2D4U.js → chunk-J7F65KKG.js} +4 -4
  78. package/dist/cli/chunks/{chunk-A67FRRPJ.js → chunk-JCPJG2KU.js} +3 -3
  79. package/dist/cli/chunks/{chunk-HQXRCW7Z.js → chunk-JLX35EPX.js} +2 -2
  80. package/dist/cli/chunks/{chunk-42TUEMH7.js → chunk-JYHZK44T.js} +1 -1
  81. package/dist/cli/chunks/{chunk-63V33NAB.js → chunk-K554X3T4.js} +2 -2
  82. package/dist/cli/chunks/{chunk-P2V5ZG3Q.js → chunk-KTDGHN2J.js} +1 -1
  83. package/dist/cli/chunks/{chunk-FVVZWNLV.js → chunk-KU7OXAFY.js} +1 -1
  84. package/dist/cli/chunks/{chunk-5J444NJR.js → chunk-LDBHCOM3.js} +2 -2
  85. package/dist/cli/chunks/{chunk-PGTMLW5K.js → chunk-LTE3CDOY.js} +2 -2
  86. package/dist/cli/chunks/{chunk-WP55YBB2.js → chunk-M6EP724N.js} +1 -1
  87. package/dist/cli/chunks/{chunk-Z5R46W6Q.js → chunk-MIQAFOFO.js} +1 -1
  88. package/dist/cli/chunks/{chunk-OSBJWQZL.js → chunk-MMVSIESL.js} +2 -2
  89. package/dist/cli/chunks/{chunk-WGEJ646F.js → chunk-MN4366PQ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-7PWW2OXP.js → chunk-MTHO6A3V.js} +1 -1
  91. package/dist/cli/chunks/{chunk-UTO2M76W.js → chunk-N2PLNYEV.js} +1 -1
  92. package/dist/cli/chunks/{chunk-BCIEQ4IP.js → chunk-NBBIA3QA.js} +2 -2
  93. package/dist/cli/chunks/{chunk-2LXXYKAP.js → chunk-NMYZSZHW.js} +2 -2
  94. package/dist/cli/chunks/{chunk-V3VJNWOF.js → chunk-NPSWRGNT.js} +2 -2
  95. package/dist/cli/chunks/{chunk-PEHHOJE6.js → chunk-NXO7CT5K.js} +2 -2
  96. package/dist/cli/chunks/{chunk-42HSEBOH.js → chunk-O5ZP3CBF.js} +2 -2
  97. package/dist/cli/chunks/{chunk-DR6SJ6P3.js → chunk-O6UMETOH.js} +2 -2
  98. package/dist/cli/chunks/{chunk-CPZUNBSQ.js → chunk-OEQCZBBM.js} +2 -2
  99. package/dist/cli/chunks/{chunk-PJZHNAUT.js → chunk-P6EYD4V3.js} +2 -2
  100. package/dist/cli/chunks/{chunk-DDJUVCKF.js → chunk-PS72GF4R.js} +3 -3
  101. package/dist/cli/chunks/{chunk-LA565BGJ.js → chunk-PUUTYV32.js} +2 -2
  102. package/dist/cli/chunks/{chunk-AZQ476BM.js → chunk-QOK4TIE4.js} +2 -2
  103. package/dist/cli/chunks/chunk-R5IL3XD5.js +69 -0
  104. package/dist/cli/chunks/{chunk-BUWZOMC7.js → chunk-RL5CBCBV.js} +1 -1
  105. package/dist/cli/chunks/{chunk-FYNDV2NZ.js → chunk-SKDDAPBV.js} +1 -1
  106. package/dist/cli/chunks/{chunk-K44EQV74.js → chunk-SKNHAGYP.js} +2 -2
  107. package/dist/cli/chunks/{chunk-CQSU7NTG.js → chunk-SLDYG7LC.js} +2 -2
  108. package/dist/cli/chunks/{chunk-PV6WBC2D.js → chunk-SRKBR4DU.js} +2 -2
  109. package/dist/cli/chunks/{chunk-XZOJWFLH.js → chunk-TCUIYIZ4.js} +1 -1
  110. package/dist/cli/chunks/{chunk-JVDYHVF2.js → chunk-TMAIHTE3.js} +4 -4
  111. package/dist/cli/chunks/{chunk-B36RPXAQ.js → chunk-TXCOK5DC.js} +2 -2
  112. package/dist/cli/chunks/{chunk-KTUSZRS3.js → chunk-U257SS7D.js} +2 -2
  113. package/dist/cli/chunks/{chunk-32FWC6G3.js → chunk-U2WMCNNR.js} +2 -2
  114. package/dist/cli/chunks/{chunk-I5BLJ2QQ.js → chunk-UIASVDYG.js} +2 -2
  115. package/dist/cli/chunks/{chunk-CY73RJJJ.js → chunk-V7ZPTEP7.js} +1 -1
  116. package/dist/cli/chunks/{chunk-YE5AYBHX.js → chunk-VHG67L7O.js} +2 -2
  117. package/dist/cli/chunks/{chunk-FCWB2FJG.js → chunk-VLQYU7ZQ.js} +1 -1
  118. package/dist/cli/chunks/{chunk-R3COBKOP.js → chunk-VPDZTMMB.js} +3 -3
  119. package/dist/cli/chunks/{chunk-QFFSQWXP.js → chunk-VRGXYOIN.js} +1 -1
  120. package/dist/cli/chunks/{chunk-PMNZN4K7.js → chunk-VSI45JCP.js} +1 -1
  121. package/dist/cli/chunks/{chunk-DVEQOD74.js → chunk-VWWLJBRA.js} +45 -44
  122. package/dist/cli/chunks/{chunk-6MRUG5G2.js → chunk-VXUIIZNG.js} +1 -1
  123. package/dist/cli/chunks/{chunk-QXOAFWWK.js → chunk-W3IO4FQ5.js} +2 -2
  124. package/dist/cli/chunks/{chunk-XB4JRJU4.js → chunk-WULMXLNN.js} +1 -1
  125. package/dist/cli/chunks/{chunk-MER7IHAZ.js → chunk-WZUQT2BE.js} +2 -2
  126. package/dist/cli/chunks/{chunk-USORP6QK.js → chunk-XF32XZMY.js} +2 -2
  127. package/dist/cli/chunks/{chunk-ZI3UBCIN.js → chunk-XKD6AFY5.js} +1 -1
  128. package/dist/cli/chunks/{chunk-Z77BVREU.js → chunk-XP4T7CZY.js} +2 -2
  129. package/dist/cli/chunks/{chunk-APWO3FI3.js → chunk-XQZ63XSL.js} +1 -1
  130. package/dist/cli/chunks/{chunk-MPEQXXXR.js → chunk-XXHJKAE6.js} +2 -2
  131. package/dist/cli/chunks/{chunk-N64PBOR5.js → chunk-Y3GX66VZ.js} +2 -2
  132. package/dist/cli/chunks/{chunk-B3M3JEFD.js → chunk-YXLQJ226.js} +2 -2
  133. package/dist/cli/chunks/chunk-Z2E5DTKX.js +2 -0
  134. package/dist/cli/chunks/{ci-TRWQ33L2.js → ci-FTZE4PD3.js} +2 -2
  135. package/dist/cli/chunks/{ci-output-TCFNHOTU.js → ci-output-C3ORCIHU.js} +2 -2
  136. package/dist/cli/chunks/{circuit-breaker-GO2TIL7E.js → circuit-breaker-GS5OTOJZ.js} +2 -2
  137. package/dist/cli/chunks/{claude-flow-setup-U77JVSVU.js → claude-flow-setup-RWOFP5L2.js} +2 -2
  138. package/dist/cli/chunks/client-UTNF2C5K.js +2 -0
  139. package/dist/cli/chunks/{cline-installer-XFD3SMGS.js → cline-installer-D7RGRAUH.js} +2 -2
  140. package/dist/cli/chunks/{code-V3VE2TMW.js → code-HBDMMYHY.js} +2 -2
  141. package/dist/cli/chunks/{code-index-extractor-C6DHOOWA.js → code-index-extractor-B2KUPAEH.js} +2 -2
  142. package/dist/cli/chunks/{codex-installer-IUR7MVE6.js → codex-installer-MPXV4AOD.js} +2 -2
  143. package/dist/cli/chunks/{completions-R7FZHNJJ.js → completions-QJS6QOZQ.js} +2 -2
  144. package/dist/cli/chunks/{complexity-analyzer-EP4QF5CS.js → complexity-analyzer-YQQXWZIL.js} +2 -2
  145. package/dist/cli/chunks/{continuedev-installer-6DW2SBMQ.js → continuedev-installer-Z6PBKYMB.js} +2 -2
  146. package/dist/cli/chunks/{copilot-installer-U3UOX7D5.js → copilot-installer-RWVD44CV.js} +2 -2
  147. package/dist/cli/chunks/{cost-tracker-5QZ5A46I.js → cost-tracker-DFPBFYWL.js} +2 -2
  148. package/dist/cli/chunks/{coverage-QOOOITLD.js → coverage-DYST26FK.js} +3 -3
  149. package/dist/cli/chunks/cross-domain-router-FCM34JOR.js +2 -0
  150. package/dist/cli/chunks/{cursor-installer-SY3TRE2I.js → cursor-installer-LL6UWKTZ.js} +2 -2
  151. package/dist/cli/chunks/{daemon-HBSBIPUZ.js → daemon-6PIHFZNR.js} +3 -3
  152. package/dist/cli/chunks/{dag-attention-scheduler-ZNLUW2HL.js → dag-attention-scheduler-WS3HJW4F.js} +2 -2
  153. package/dist/cli/chunks/{detect-DMUJPGNC.js → detect-J4OITSUD.js} +2 -2
  154. package/dist/cli/chunks/{dist-node-4RPPRXUH.js → dist-node-QSLD5K6K.js} +2 -2
  155. package/dist/cli/chunks/{domain-handler-XJFDML77.js → domain-handler-BD53QZ4Q.js} +2 -2
  156. package/dist/cli/chunks/{domain-transfer-MXPKJ2A2.js → domain-transfer-VZBWINQL.js} +2 -2
  157. package/dist/cli/chunks/dream-6KCS7EWS.js +2 -0
  158. package/dist/cli/chunks/embed-and-insert-pattern-5UAFXNDX.js +3 -0
  159. package/dist/cli/chunks/{eval-DHBZ74RL.js → eval-GBKU6VTD.js} +2 -2
  160. package/dist/cli/chunks/{fast-paths-WTNFCV2I.js → fast-paths-MYZ6GITZ.js} +2 -2
  161. package/dist/cli/chunks/{feature-flags-VC7BQNHU.js → feature-flags-2WVV66AO.js} +2 -2
  162. package/dist/cli/chunks/{feature-flags-264QUQ3E.js → feature-flags-6ALWBTHS.js} +2 -2
  163. package/dist/cli/chunks/{file-discovery-LXQPIRKG.js → file-discovery-FOYCPGD6.js} +2 -2
  164. package/dist/cli/chunks/{fleet-4OAZWNXG.js → fleet-JROEDHAT.js} +3 -3
  165. package/dist/cli/chunks/{gnn-wrapper-MAXAOMTP.js → gnn-wrapper-KAXTFFEE.js} +2 -2
  166. package/dist/cli/chunks/{heartbeat-handler-ZTUI75EB.js → heartbeat-handler-PG24CBMQ.js} +4 -4
  167. package/dist/cli/chunks/{heartbeat-scheduler-VWPA7XKA.js → heartbeat-scheduler-LSS3RD6E.js} +2 -2
  168. package/dist/cli/chunks/hnsw-adapter-PG6O67CQ.js +2 -0
  169. package/dist/cli/chunks/hnsw-index-AHYZHLNZ.js +2 -0
  170. package/dist/cli/chunks/{hnsw-legacy-bridge-EQDYPKGL.js → hnsw-legacy-bridge-HYH4AJAO.js} +2 -2
  171. package/dist/cli/chunks/{hnswlib-node-G4QGTGIB.js → hnswlib-node-WTTST5LC.js} +2 -2
  172. package/dist/cli/chunks/hooks-RDZSAFQG.js +214 -0
  173. package/dist/cli/chunks/{hybrid-router-XODWORQ3.js → hybrid-router-HNPS6EFL.js} +2 -2
  174. package/dist/cli/chunks/{hypergraph-engine-T73DH7N6.js → hypergraph-engine-JUFXRXCC.js} +2 -2
  175. package/dist/cli/chunks/{hypergraph-handler-OZJJJW5B.js → hypergraph-handler-YFRF53TF.js} +3 -3
  176. package/dist/cli/chunks/impact-analyzer-USAJVJY5.js +2 -0
  177. package/dist/cli/chunks/{init-handler-YXXNCXM4.js → init-handler-P4W5F57S.js} +6 -6
  178. package/dist/cli/chunks/init-wizard-GL7LAZID.js +2 -0
  179. package/dist/cli/chunks/kernel-2YAIESTR.js +2 -0
  180. package/dist/cli/chunks/{kilocode-installer-3RCK2JPW.js → kilocode-installer-5VWY4DMH.js} +2 -2
  181. package/dist/cli/chunks/{kiro-installer-LKC42QRS.js → kiro-installer-PZC3BQII.js} +2 -2
  182. package/dist/cli/chunks/knowledge-graph-QSIYZRAG.js +2 -0
  183. package/dist/cli/chunks/{learning-BIBRKCYL.js → learning-4OH4ZG25.js} +3 -3
  184. package/dist/cli/chunks/{llm-router-Z6Z7TTBI.js → llm-router-LZBR6SZQ.js} +4 -4
  185. package/dist/cli/chunks/{load-T2QUB663.js → load-SPWP6VB3.js} +2 -2
  186. package/dist/cli/chunks/load-test-UEHSHLVN.js +2 -0
  187. package/dist/cli/chunks/{mcp-QBOL6TK4.js → mcp-QYPQMM7L.js} +2 -2
  188. package/dist/cli/chunks/{memory-7RQ2SF36.js → memory-54ILJMWQ.js} +5 -5
  189. package/dist/cli/chunks/memory-backend-4NE4ADPG.js +2 -0
  190. package/dist/cli/chunks/{memory-handlers-5OHDUBJS.js → memory-handlers-YK7H5UCX.js} +2 -2
  191. package/dist/cli/chunks/{multi-model-executor-PGSNT3NO.js → multi-model-executor-XAOAVPPI.js} +2 -2
  192. package/dist/cli/chunks/{opencode-installer-AEOXTTFG.js → opencode-installer-CNS4XMUF.js} +2 -2
  193. package/dist/cli/chunks/{orchestrator-6K2L36JA.js → orchestrator-SSEMSKUI.js} +6 -6
  194. package/dist/cli/chunks/{pipeline-MFQCW7JD.js → pipeline-DS3AENTB.js} +2 -2
  195. package/dist/cli/chunks/{platform-DM6RQ3FM.js → platform-BL6LH5NF.js} +2 -2
  196. package/dist/cli/chunks/{plugin-CCTGDC55.js → plugin-FNXPEQ2C.js} +2 -2
  197. package/dist/cli/chunks/{prime-radiant-advanced-wasm-J4FXB63L.js → prime-radiant-advanced-wasm-E6S6BGNA.js} +2 -2
  198. package/dist/cli/chunks/protocol-executor-YI4HNXND.js +2 -0
  199. package/dist/cli/chunks/{protocol-handler-7UOBNLET.js → protocol-handler-D4WIUU3W.js} +2 -2
  200. package/dist/cli/chunks/{prove-VAPGITFF.js → prove-OLB3PKW6.js} +2 -2
  201. package/dist/cli/chunks/{provider-manager-F6TLUJFW.js → provider-manager-GKTQ75DT.js} +2 -2
  202. package/dist/cli/chunks/qe-reasoning-bank-ANBAXQXC.js +2 -0
  203. package/dist/cli/chunks/{quality-7LJQI3SB.js → quality-ZYJVYTUL.js} +2 -2
  204. package/dist/cli/chunks/queen-coordinator-MYYUSWVX.js +2 -0
  205. package/dist/cli/chunks/{real-embeddings-NHWAUSV3.js → real-embeddings-SKJRHLCS.js} +2 -2
  206. package/dist/cli/chunks/{roocode-installer-HQFQJJPU.js → roocode-installer-WZGKOLWE.js} +2 -2
  207. package/dist/cli/chunks/router-RYCLZ7A4.js +2 -0
  208. package/dist/cli/chunks/routing-feedback-5KSRG2UI.js +2 -0
  209. package/dist/cli/chunks/{routing-handler-VH66WSPU.js → routing-handler-4GIMINCI.js} +2 -2
  210. package/dist/cli/chunks/{ruvector-commands-IPUWLJFU.js → ruvector-commands-YZONXZ2W.js} +2 -2
  211. package/dist/cli/chunks/{rvf-dual-writer-KRFEM6JH.js → rvf-dual-writer-WSS5GF54.js} +2 -2
  212. package/dist/cli/chunks/{rvf-migration-adapter-SVCZ72IU.js → rvf-migration-adapter-WS4HHVEU.js} +2 -2
  213. package/dist/cli/chunks/{rvf-migration-coordinator-FYBIF3SX.js → rvf-migration-coordinator-6BY5GI47.js} +2 -2
  214. package/dist/cli/chunks/rvf-native-adapter-NEIOLJRF.js +2 -0
  215. package/dist/cli/chunks/safe-db-3JQP4EPU.js +2 -0
  216. package/dist/cli/chunks/schedule-2QKCL64E.js +2 -0
  217. package/dist/cli/chunks/scheduler-FMOP45FC.js +2 -0
  218. package/dist/cli/chunks/{security-C2I6CG7B.js → security-HCNOL2K3.js} +3 -3
  219. package/dist/cli/chunks/shared-rvf-adapter-BMFIVWMJ.js +2 -0
  220. package/dist/cli/chunks/{shared-rvf-dual-writer-BPIFGN7I.js → shared-rvf-dual-writer-QRNLSDS7.js} +2 -2
  221. package/dist/cli/chunks/sqlite-persistence-I5RYLFOE.js +2 -0
  222. package/dist/cli/chunks/{status-handler-57UA6GNR.js → status-handler-QXZ442MY.js} +2 -2
  223. package/dist/cli/chunks/{structural-health-KMHBG6FO.js → structural-health-OFYZ3Z4A.js} +2 -2
  224. package/dist/cli/chunks/{sync-53YM6U4S.js → sync-J4BG65NF.js} +2 -2
  225. package/dist/cli/chunks/{task-handler-W2XPS5WW.js → task-handler-UBSFCKK3.js} +2 -2
  226. package/dist/cli/chunks/{task-handlers-BG4IAMBJ.js → task-handlers-JFUT2FQ7.js} +2 -2
  227. package/dist/cli/chunks/{test-QJBBVPL2.js → test-WTNAHJHH.js} +4 -4
  228. package/dist/cli/chunks/{test-scheduling-Y4J6EY2K.js → test-scheduling-QREBYRGW.js} +3 -3
  229. package/dist/cli/chunks/{token-bootstrap-3TKR3UIE.js → token-bootstrap-HE5H77OL.js} +2 -2
  230. package/dist/cli/chunks/{token-usage-5FUNHHVZ.js → token-usage-V5B6K3JL.js} +2 -2
  231. package/dist/cli/chunks/{transformers-KVPA35SR.js → transformers-HIVMQP4O.js} +2 -2
  232. package/dist/cli/chunks/{tree-sitter-wasm-parser-LTBBLY5U.js → tree-sitter-wasm-parser-WP2SF2M5.js} +2 -2
  233. package/dist/cli/chunks/{types-Y2BHPD6B.js → types-7ZBTAO5Z.js} +2 -2
  234. package/dist/cli/chunks/unified-memory-2ETCY22B.js +2 -0
  235. package/dist/cli/chunks/unified-memory-hnsw-OALJW537.js +2 -0
  236. package/dist/cli/chunks/unified-persistence-SQMP7A3O.js +2 -0
  237. package/dist/cli/chunks/{upgrade-E4VAQZQR.js → upgrade-WIFAJDBG.js} +2 -2
  238. package/dist/cli/chunks/{validate-4ICDQCKJ.js → validate-W63V36GA.js} +2 -2
  239. package/dist/cli/chunks/{validate-swarm-AIEOQOUF.js → validate-swarm-CK5BM3YY.js} +2 -2
  240. package/dist/cli/chunks/{vibium-AF2K6YXR.js → vibium-MJCCO36E.js} +2 -2
  241. package/dist/cli/chunks/visual-security-JUJPF2QO.js +2 -0
  242. package/dist/cli/chunks/{web-tree-sitter-PM67K5SP.js → web-tree-sitter-ESERXLPK.js} +2 -2
  243. package/dist/cli/chunks/{windsurf-installer-4MKUQ2KT.js → windsurf-installer-FDWQ5BWI.js} +2 -2
  244. package/dist/cli/chunks/{witness-chain-FLPF7CS6.js → witness-chain-L5KSYE2S.js} +2 -2
  245. package/dist/cli/chunks/witness-chain-QJVKAAZT.js +2 -0
  246. package/dist/cli/chunks/{workflow-DHTCI6QD.js → workflow-34GYJDFW.js} +4 -4
  247. package/dist/cli/chunks/workflow-orchestrator-WXB2RVVW.js +2 -0
  248. package/dist/cli/chunks/{wrappers-5K6UGI3T.js → wrappers-VGKEBQLW.js} +2 -2
  249. package/dist/cli/commands/hooks-handlers/command-hooks.js +104 -11
  250. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.d.ts +98 -0
  251. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +285 -1
  252. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +20 -1
  253. package/dist/cli/commands/hooks-handlers/hooks-shared.js +35 -3
  254. package/dist/cli/commands/hooks-handlers/routing-hooks.js +15 -5
  255. package/dist/cli/commands/hooks-handlers/task-hooks.js +216 -5
  256. package/dist/coordination/handlers/test-execution-handlers.d.ts +18 -0
  257. package/dist/coordination/handlers/test-execution-handlers.js +77 -9
  258. package/dist/coordination/task-executor.js +11 -2
  259. package/dist/domains/test-generation/generators/jest-vitest-generator.js +13 -3
  260. package/dist/domains/test-generation/interfaces.d.ts +12 -0
  261. package/dist/domains/test-generation/services/test-generator.js +5 -1
  262. package/dist/governance/continue-gate-integration.d.ts +13 -0
  263. package/dist/governance/continue-gate-integration.js +31 -8
  264. package/dist/init/phases/07-hooks.js +2 -2
  265. package/dist/integrations/ruvector/hypergraph-engine.js +63 -4
  266. package/dist/integrations/ruvector/hypergraph-schema.d.ts +6 -2
  267. package/dist/learning/embed-and-insert-pattern.d.ts +36 -0
  268. package/dist/learning/embed-and-insert-pattern.js +52 -0
  269. package/dist/learning/pattern-store.d.ts +8 -0
  270. package/dist/learning/pattern-store.js +66 -43
  271. package/dist/mcp/bundle.js +400 -392
  272. package/dist/mcp/entry.js +21 -1
  273. package/dist/mcp/protocol-server.js +6 -1
  274. package/dist/mcp/tools/coverage-analysis/index.js +11 -2
  275. package/dist/workers/workers/learning-consolidation.js +6 -1
  276. package/package.json +1 -1
  277. package/dist/cli/chunks/adapter-2BIT6BGH.js +0 -2
  278. package/dist/cli/chunks/aqe-learning-engine-B5G3RG4W.js +0 -2
  279. package/dist/cli/chunks/base-A3ZRMSIZ.js +0 -2
  280. package/dist/cli/chunks/browser-workflow-C6Z53ZH6.js +0 -2
  281. package/dist/cli/chunks/chunk-2ARCG4XJ.js +0 -2
  282. package/dist/cli/chunks/chunk-JC4O47QG.js +0 -66
  283. package/dist/cli/chunks/chunk-KTJWRVFR.js +0 -15
  284. package/dist/cli/chunks/client-B3QSCZSJ.js +0 -2
  285. package/dist/cli/chunks/cross-domain-router-OYBTXKCV.js +0 -2
  286. package/dist/cli/chunks/dream-R2F6L47W.js +0 -2
  287. package/dist/cli/chunks/hnsw-adapter-TQPQE4OJ.js +0 -2
  288. package/dist/cli/chunks/hnsw-index-2X3NMTDU.js +0 -2
  289. package/dist/cli/chunks/hooks-RBVHAPBL.js +0 -101
  290. package/dist/cli/chunks/impact-analyzer-B7GBDSA3.js +0 -2
  291. package/dist/cli/chunks/init-wizard-7N6MCER4.js +0 -2
  292. package/dist/cli/chunks/kernel-6CJ4FP5Z.js +0 -2
  293. package/dist/cli/chunks/knowledge-graph-4XYLO6ZW.js +0 -2
  294. package/dist/cli/chunks/load-test-UODCPBYF.js +0 -2
  295. package/dist/cli/chunks/memory-backend-PUPAE4QQ.js +0 -2
  296. package/dist/cli/chunks/protocol-executor-X3EYJINP.js +0 -2
  297. package/dist/cli/chunks/qe-reasoning-bank-3RDWPSYG.js +0 -2
  298. package/dist/cli/chunks/queen-coordinator-XIQZIYAZ.js +0 -2
  299. package/dist/cli/chunks/router-AFEFPU2A.js +0 -2
  300. package/dist/cli/chunks/routing-feedback-AGYMQFMV.js +0 -2
  301. package/dist/cli/chunks/rvf-native-adapter-AFOWXCZH.js +0 -2
  302. package/dist/cli/chunks/safe-db-NNF5DE5T.js +0 -2
  303. package/dist/cli/chunks/schedule-HJUZSHEA.js +0 -2
  304. package/dist/cli/chunks/scheduler-DZ53RPJQ.js +0 -2
  305. package/dist/cli/chunks/shared-rvf-adapter-5UQSTUSR.js +0 -2
  306. package/dist/cli/chunks/sqlite-persistence-27ESC5DX.js +0 -2
  307. package/dist/cli/chunks/unified-memory-O7GFUSD3.js +0 -2
  308. package/dist/cli/chunks/unified-memory-hnsw-XBLROJEN.js +0 -2
  309. package/dist/cli/chunks/unified-persistence-YBHEAL2S.js +0 -2
  310. package/dist/cli/chunks/visual-security-4F7VYCAU.js +0 -2
  311. package/dist/cli/chunks/witness-chain-AXJ44BGW.js +0 -2
  312. package/dist/cli/chunks/workflow-orchestrator-UAFUPHD3.js +0 -2
package/dist/mcp/entry.js CHANGED
@@ -207,10 +207,30 @@ async function main() {
207
207
  version,
208
208
  });
209
209
  originalStderrWrite('[MCP] Ready\n');
210
+ // Eagerly initialize CrossPhaseHooks so kv_store / qcsd-memory rows
211
+ // actually grow under sustained queen-event-handlers traffic. The lazy
212
+ // singleton in hooks/cross-phase-hooks.ts is created on first use, but
213
+ // its initialize() (config-load + memory wiring) only runs when
214
+ // explicitly called. Doing it here means hook events fire through a
215
+ // fully-initialized executor from the first MCP request.
216
+ try {
217
+ const { getCrossPhaseHookExecutor } = await import('../hooks/cross-phase-hooks.js');
218
+ await getCrossPhaseHookExecutor().initialize();
219
+ originalStderrWrite('[MCP] CrossPhaseHooks initialized (eager init via patch 010)\n');
220
+ }
221
+ catch (cpErr) {
222
+ originalStderrWrite(`[MCP] WARNING: CrossPhaseHooks eager init failed: ${cpErr instanceof Error ? cpErr.message : 'unknown'}\n`);
223
+ }
210
224
  // IMP-10: Start background workers (heartbeat scheduler, etc.)
211
225
  try {
212
226
  const { getDaemon } = await import('../workers/daemon.js');
213
- const daemon = getDaemon({ autoStart: false });
227
+ // ADR-001 Bug A fix: use the canonical getDaemon() default. Passing
228
+ // `{ autoStart: false }` here would neuter workerManager.startAll() —
229
+ // the only call path that schedules per-worker setInterval timers, so
230
+ // workers would register but never tick. DEFAULT_CONFIG.autoStart=true
231
+ // (workers/daemon.ts) is the contracted default; matches the
232
+ // shutdownDaemon() call site above.
233
+ const daemon = getDaemon();
214
234
  await daemon.start();
215
235
  const status = daemon.getStatus();
216
236
  originalStderrWrite(`[MCP] Background workers started (${status.workerManager.totalWorkers} workers)\n`);
@@ -683,12 +683,17 @@ export class MCPProtocolServer {
683
683
  this.registerTool({
684
684
  definition: {
685
685
  name: 'test_generate_enhanced',
686
- description: 'Generate unit/integration/e2e tests with AI pattern recognition and anti-pattern detection. Example: test_generate_enhanced({ sourceCode: "function add(a,b){return a+b}", testType: "unit" })',
686
+ description: 'Generate unit/integration/e2e tests with AI pattern recognition and anti-pattern detection. Example: test_generate_enhanced({ sourceCode: "function add(a,b){return a+b}", testType: "unit", framework: "jest" })',
687
687
  category: 'domain',
688
688
  parameters: [
689
689
  { name: 'sourceCode', type: 'string', description: 'Source code to generate tests for' },
690
+ { name: 'filePath', type: 'string', description: 'Original source file path (used as the import target in generated tests; if omitted, generated tests reference the temp source)' },
690
691
  { name: 'language', type: 'string', description: 'Programming language' },
691
692
  { name: 'testType', type: 'string', description: 'Type of tests', enum: ['unit', 'integration', 'e2e'] },
693
+ { name: 'framework', type: 'string', description: 'Test framework to use', enum: ['jest', 'vitest', 'mocha', 'pytest', 'node-test'], default: 'vitest' },
694
+ { name: 'coverageGoal', type: 'number', description: 'Target coverage percentage (0-100)', default: 80 },
695
+ { name: 'aiEnhancement', type: 'boolean', description: 'Enable AI-powered enhancement', default: true },
696
+ { name: 'detectAntiPatterns', type: 'boolean', description: 'Detect and report anti-patterns', default: false },
692
697
  ],
693
698
  },
694
699
  handler: (params) => handleTestGenerate(params),
@@ -332,11 +332,20 @@ export class CoverageGapsTool extends MCPToolBase {
332
332
  this.markAsDemoData(context, 'Demo mode explicitly requested');
333
333
  return this.getDemoGapsResult(target, minRisk, limit, context);
334
334
  }
335
- // If no coverage data found, return error with actionable guidance
335
+ // If no coverage data found, return error with actionable guidance.
336
+ // Distinguish between an explicitly-passed empty/invalid coverageFile
337
+ // (user passed a path; the file parsed but contained no usable data)
338
+ // and an autodiscover miss (no coverageFile passed; nothing found under target).
336
339
  if (!parsedReport || parsedReport.files.size === 0) {
340
+ if (coverageFile) {
341
+ return {
342
+ success: false,
343
+ error: `Coverage file '${coverageFile}' contains no usable coverage data (parsed 0 files). Verify the file is a non-empty Istanbul/LCOV/JaCoCo/etc. report.`,
344
+ };
345
+ }
337
346
  return {
338
347
  success: false,
339
- error: `No coverage data found in '${target}'. Run your test suite with coverage enabled to generate coverage reports before detecting gaps.`,
348
+ error: `No coverage data found by autodiscovery under target '${target}'. Run your test suite with coverage enabled, or pass coverageFile pointing to an existing report.`,
340
349
  };
341
350
  }
342
351
  // Mark as real data - we have actual coverage
@@ -299,6 +299,7 @@ export class LearningConsolidationWorker extends BaseWorker {
299
299
  try {
300
300
  const { v4: uuidv4 } = await import('uuid');
301
301
  const patternId = uuidv4();
302
+ const description = `Auto-extracted pattern from ${candidate.sourceExperiences} experiences. Avg reward: ${candidate.avgReward.toFixed(3)}`;
302
303
  db.prepare(`
303
304
  INSERT INTO qe_patterns (
304
305
  id, pattern_type, qe_domain, domain, name, description,
@@ -306,7 +307,7 @@ export class LearningConsolidationWorker extends BaseWorker {
306
307
  template_json, context_json, created_at, successful_uses
307
308
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), ?)
308
309
  `).run(patternId, candidate.patternType, candidate.domain, candidate.domain, // AQE domain same as QE domain
309
- candidate.name, `Auto-extracted pattern from ${candidate.sourceExperiences} experiences. Avg reward: ${candidate.avgReward.toFixed(3)}`, candidate.confidence, candidate.sourceExperiences, candidate.successRate, candidate.confidence * 0.3 + (Math.min(candidate.sourceExperiences, 100) / 100) * 0.2 + candidate.successRate * 0.5, 'short-term', JSON.stringify({
310
+ candidate.name, description, candidate.confidence, candidate.sourceExperiences, candidate.successRate, candidate.confidence * 0.3 + (Math.min(candidate.sourceExperiences, 100) / 100) * 0.2 + candidate.successRate * 0.5, 'short-term', JSON.stringify({
310
311
  type: 'workflow',
311
312
  content: candidate.templateContent,
312
313
  variables: [],
@@ -315,6 +316,10 @@ export class LearningConsolidationWorker extends BaseWorker {
315
316
  sourceType: 'experience-extraction',
316
317
  extractedAt: new Date().toISOString(),
317
318
  }), Math.round(candidate.sourceExperiences * candidate.successRate));
319
+ // Pair the qe_patterns row with an embedding so HNSW pattern recall
320
+ // doesn't see this as a "ghost" (ADR-058 embedding-locality). Fail-soft.
321
+ const { ensurePatternEmbedding } = await import('../../learning/embed-and-insert-pattern.js');
322
+ await ensurePatternEmbedding(db, patternId, candidate.name, description, candidate.actions);
318
323
  created++;
319
324
  }
320
325
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentic-qe",
3
- "version": "3.9.17",
3
+ "version": "3.9.19",
4
4
  "description": "Agentic Quality Engineering V3 - Domain-Driven Design Architecture with 13 Bounded Contexts, O(log n) coverage analysis, ReasoningBank learning, 60 specialized QE agents, mathematical Coherence verification, deep Claude Flow integration",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.17");process.exit(0)}
2
- import{a,b,c}from"./chunk-MNSF47HC.js";import"./chunk-3GYAIW2P.js";import"./chunk-P2V5ZG3Q.js";import"./chunk-6YFEWIL5.js";import"./chunk-DJXYFFGA.js";import"./chunk-XB4JRJU4.js";export{a as AgentBoosterAdapter,b as createAgentBoosterAdapter,c as createAgentBoosterAdapterSync};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.17");process.exit(0)}
2
- import{a,b,c,d,e,f}from"./chunk-R3COBKOP.js";import"./chunk-OUSQ4KQN.js";import"./chunk-A67FRRPJ.js";import"./chunk-I64R2D4U.js";import"./chunk-BUWZOMC7.js";import"./chunk-6F6BNLVP.js";import"./chunk-QYDBV5MD.js";import"./chunk-WGEJ646F.js";import"./chunk-JT2KLBDB.js";import"./chunk-VX6XHAG2.js";import"./chunk-PEHHOJE6.js";import"./chunk-CPZUNBSQ.js";import"./chunk-6YCZDIGF.js";import"./chunk-B36RPXAQ.js";import"./chunk-V4DMYY6P.js";import"./chunk-2ARCG4XJ.js";import"./chunk-65Z6HMDA.js";import"./chunk-6YFEWIL5.js";import"./chunk-UTO2M76W.js";import"./chunk-DJXYFFGA.js";import"./chunk-Z5R46W6Q.js";import"./chunk-LA565BGJ.js";import"./chunk-F5X3U57Y.js";import"./chunk-2K7GRX5U.js";import"./chunk-K44EQV74.js";import"./chunk-MER7IHAZ.js";import"./chunk-ARN2KDLJ.js";import"./chunk-USORP6QK.js";import"./chunk-B3M3JEFD.js";import"./chunk-QXOAFWWK.js";import"./chunk-XB4JRJU4.js";export{b as AQELearningEngine,a as DEFAULT_ENGINE_CONFIG,c as DEFAULT_META_LEARNING_CONFIG,d as MetaLearningEngine,e as createAQELearningEngine,f as createDefaultLearningEngine};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.17");process.exit(0)}
2
- import{a,b,c,d,e,f}from"./chunk-DR6SJ6P3.js";import"./chunk-HQXRCW7Z.js";import"./chunk-B36RPXAQ.js";import"./chunk-V4DMYY6P.js";import"./chunk-2ARCG4XJ.js";import"./chunk-65Z6HMDA.js";import"./chunk-6YFEWIL5.js";import"./chunk-DJXYFFGA.js";import"./chunk-Z5R46W6Q.js";import"./chunk-LA565BGJ.js";import"./chunk-F5X3U57Y.js";import"./chunk-2K7GRX5U.js";import"./chunk-K44EQV74.js";import"./chunk-MER7IHAZ.js";import"./chunk-ARN2KDLJ.js";import"./chunk-USORP6QK.js";import"./chunk-B3M3JEFD.js";import"./chunk-QXOAFWWK.js";import"./chunk-XB4JRJU4.js";export{f as MCPToolBase,e as defaultToolLogger,d as getMemoryBackend,b as getSharedMemoryBackend,a as registerRvfResetFn,c as resetSharedMemoryBackend};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.17");process.exit(0)}
2
- import{a}from"./chunk-BCIEQ4IP.js";import"./chunk-DR6SJ6P3.js";import"./chunk-HQXRCW7Z.js";import"./chunk-B36RPXAQ.js";import"./chunk-V4DMYY6P.js";import"./chunk-2ARCG4XJ.js";import"./chunk-65Z6HMDA.js";import"./chunk-6YFEWIL5.js";import"./chunk-DJXYFFGA.js";import"./chunk-Z5R46W6Q.js";import"./chunk-LA565BGJ.js";import"./chunk-F5X3U57Y.js";import"./chunk-2K7GRX5U.js";import"./chunk-K44EQV74.js";import"./chunk-MER7IHAZ.js";import"./chunk-ARN2KDLJ.js";import"./chunk-USORP6QK.js";import"./chunk-B3M3JEFD.js";import"./chunk-QXOAFWWK.js";import"./chunk-XB4JRJU4.js";export{a as BrowserWorkflowTool};
@@ -1,2 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.17");process.exit(0)}
2
- import{a as e,b as g,e as r}from"./chunk-65Z6HMDA.js";import{c as o}from"./chunk-XB4JRJU4.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
@@ -1,66 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.17");process.exit(0)}
2
- import{a as I,b as H,c as C,e as S,f as L}from"./chunk-V4DMYY6P.js";import{b as T,d as P}from"./chunk-6YFEWIL5.js";import{a as f,c as O}from"./chunk-DJXYFFGA.js";import{i as x}from"./chunk-Z5R46W6Q.js";L();P();var v=["function","module","test","file","class"],w=["calls","imports","tests","depends_on","covers"],E=class{ensureSchema(e){e.transaction(()=>{e.exec(I),e.exec(H),e.exec(C)})()}schemaExists(e){return S(e)}getNodeTypes(){return v}getEdgeTypes(){return w}isValidNodeType(e){return v.includes(e)}isValidEdgeType(e){return w.includes(e)}getStats(e){if(!this.schemaExists(e))return{nodeCount:0,edgeCount:0};let t=e.prepare("SELECT COUNT(*) as count FROM hypergraph_nodes").get().count,r=e.prepare("SELECT COUNT(*) as count FROM hypergraph_edges").get().count;return{nodeCount:t,edgeCount:r}}dropSchema(e){let t=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_nodes").get()?.cnt??0,r=e.prepare("SELECT COUNT(*) as cnt FROM hypergraph_edges").get()?.cnt??0;if(t>0||r>0)throw new Error(`REFUSING to drop hypergraph schema: tables contain data (${t} nodes, ${r} edges). Backup and manually drop if needed.`);e.transaction(()=>{e.exec("DROP TABLE IF EXISTS hypergraph_edges"),e.exec("DROP TABLE IF EXISTS hypergraph_nodes")})()}};function N(n){return{id:n.id,type:n.type,name:n.name,file_path:n.filePath??null,line_start:n.lineStart??null,line_end:n.lineEnd??null,complexity:n.complexity??null,coverage:n.coverage??null,metadata:n.metadata?JSON.stringify(n.metadata):null,embedding:n.embedding?M(n.embedding):null}}function l(n){return{id:n.id,type:n.type,name:n.name,filePath:n.file_path??void 0,lineStart:n.line_start??void 0,lineEnd:n.line_end??void 0,complexity:n.complexity??void 0,coverage:n.coverage??void 0,metadata:n.metadata?T(n.metadata):void 0,embedding:n.embedding?F(n.embedding):void 0,createdAt:n.created_at,updatedAt:n.updated_at}}function A(n){return{id:n.id,source_id:n.sourceId,target_id:n.targetId,type:n.type,weight:n.weight??1,properties:n.properties?JSON.stringify(n.properties):null}}function b(n){return{id:n.id,sourceId:n.source_id,targetId:n.target_id,type:n.type,weight:n.weight,properties:n.properties?T(n.properties):void 0,createdAt:n.created_at}}function _(n,e,t){return`${n}--${t}-->${e}`}function M(n){let e=Buffer.alloc(n.length*4);for(let t=0;t<n.length;t++)e.writeFloatLE(n[t],t*4);return e}function F(n){let e=[],t=n.length/4;for(let r=0;r<t;r++)e.push(n.readFloatLE(r*4));return e}O();var z={maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:!1},y=class{config;schemaManager;initialized=!1;constructor(e){this.config={...z,...e},this.schemaManager=new E}async initialize(){this.initialized||(this.schemaManager.ensureSchema(this.config.db),this.initialized=!0)}isInitialized(){return this.initialized}async addNode(e){this.ensureInitialized();let t=x(),r={id:t,...e},i=N(r);return this.config.db.prepare(`
3
- INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage, metadata, embedding)
4
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5
- `).run(i.id,i.type,i.name,i.file_path,i.line_start,i.line_end,i.complexity,i.coverage,i.metadata,i.embedding),t}async addEdge(e){this.ensureInitialized();let t=_(e.sourceId,e.targetId,e.type),r={id:t,...e},i=A(r);return this.config.db.prepare(`
6
- INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight, properties)
7
- VALUES (?, ?, ?, ?, ?, ?)
8
- `).run(i.id,i.source_id,i.target_id,i.type,i.weight,i.properties),t}async getNode(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_nodes WHERE id = ?").get(e);return t?l(t):null}async getEdge(e){this.ensureInitialized();let t=this.config.db.prepare("SELECT * FROM hypergraph_edges WHERE id = ?").get(e);return t?b(t):null}async updateNode(e,t){this.ensureInitialized();let r=await this.getNode(e);if(!r)throw new Error(`Node not found: ${e}`);let i={...r,...t},a=N(i);this.config.db.prepare(`
9
- UPDATE hypergraph_nodes
10
- SET type = ?, name = ?, file_path = ?, line_start = ?, line_end = ?,
11
- complexity = ?, coverage = ?, metadata = ?, embedding = ?,
12
- updated_at = datetime('now')
13
- WHERE id = ?
14
- `).run(a.type,a.name,a.file_path,a.line_start,a.line_end,a.complexity,a.coverage,a.metadata,a.embedding,e)}async deleteNode(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE source_id = ? OR target_id = ?").run(e,e),this.config.db.prepare("DELETE FROM hypergraph_nodes WHERE id = ?").run(e)}async deleteEdge(e){this.ensureInitialized(),this.config.db.prepare("DELETE FROM hypergraph_edges WHERE id = ?").run(e)}async findNodes(e){this.ensureInitialized();let t=[],r=[];if(e.type){let s=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${s.map(()=>"?").join(", ")})`),r.push(...s)}e.filePath&&(e.filePath.includes("%")?t.push("file_path LIKE ?"):t.push("file_path = ?"),r.push(e.filePath)),e.name&&typeof e.name=="string"&&(t.push("name = ?"),r.push(e.name)),e.minComplexity!==void 0&&(t.push("complexity >= ?"),r.push(e.minComplexity)),e.maxComplexity!==void 0&&(t.push("complexity <= ?"),r.push(e.maxComplexity)),e.minCoverage!==void 0&&(t.push("coverage >= ?"),r.push(e.minCoverage)),e.maxCoverage!==void 0&&(t.push("coverage <= ?"),r.push(e.maxCoverage));let i=t.length>0?`WHERE ${t.join(" AND ")}`:"",a=e.limit??this.config.maxQueryResults,p=`SELECT * FROM hypergraph_nodes ${i} LIMIT ?`;r.push(a);let o=this.config.db.prepare(p).all(...r).map(l);return e.name instanceof RegExp&&(o=o.filter(s=>e.name instanceof RegExp&&e.name.test(s.name))),o}async findEdges(e){this.ensureInitialized();let t=[],r=[];if(e.type){let o=Array.isArray(e.type)?e.type:[e.type];t.push(`type IN (${o.map(()=>"?").join(", ")})`),r.push(...o)}e.sourceId&&(t.push("source_id = ?"),r.push(e.sourceId)),e.targetId&&(t.push("target_id = ?"),r.push(e.targetId)),e.minWeight!==void 0&&(t.push("weight >= ?"),r.push(e.minWeight));let i=t.length>0?`WHERE ${t.join(" AND ")}`:"",a=e.limit??this.config.maxQueryResults,p=`SELECT * FROM hypergraph_edges ${i} LIMIT ?`;return r.push(a),this.config.db.prepare(p).all(...r).map(b)}async traverse(e,t=[],r=5){this.ensureInitialized();let i=new Map,a=new Map,p=[],g=0,o=[{nodeId:e,depth:0,path:{nodes:[e],edges:[]}}],s=Math.min(r,this.config.maxTraversalDepth);for(;o.length>0;){let{nodeId:d,depth:c,path:h}=o.shift();if(!i.has(d)){let u=await this.getNode(d);u&&i.set(d,u)}if(g=Math.max(g,c),c>=s){p.push(h);continue}let m={sourceId:d};t.length>0&&(m.type=t);let R=await this.findEdges(m);if(R.length===0){p.push(h);continue}for(let u of R)if(!a.has(u.id)){a.set(u.id,u);let D={nodes:[...h.nodes,u.targetId],edges:[...h.edges,u.id]};o.push({nodeId:u.targetId,depth:c+1,path:D})}}return{nodes:Array.from(i.values()),edges:Array.from(a.values()),paths:p,maxDepthReached:g}}async findUntestedFunctions(){return this.ensureInitialized(),this.config.db.prepare(`
15
- SELECT n.* FROM hypergraph_nodes n
16
- WHERE n.type = 'function'
17
- AND NOT EXISTS (
18
- SELECT 1 FROM hypergraph_edges e
19
- JOIN hypergraph_nodes t ON t.id = e.source_id
20
- WHERE e.target_id = n.id
21
- AND e.type = 'covers'
22
- AND t.type = 'test'
23
- )
24
- ORDER BY n.complexity DESC NULLS LAST
25
- LIMIT ?
26
- `).all(this.config.maxQueryResults).map(l)}async findImpactedTests(e){if(this.ensureInitialized(),e.length===0)return[];let r=`
27
- SELECT DISTINCT t.* FROM hypergraph_nodes t
28
- JOIN hypergraph_edges e ON e.source_id = t.id
29
- JOIN hypergraph_nodes f ON f.id = e.target_id
30
- WHERE t.type = 'test'
31
- AND e.type = 'covers'
32
- AND f.type = 'function'
33
- AND f.file_path IN (${e.map(()=>"?").join(", ")})
34
- LIMIT ?
35
- `,i=[...e,this.config.maxQueryResults];return this.config.db.prepare(r).all(...i).map(l)}async findCoverageGaps(e=50){return this.ensureInitialized(),this.config.db.prepare(`
36
- SELECT * FROM hypergraph_nodes
37
- WHERE type = 'function'
38
- AND coverage IS NOT NULL
39
- AND coverage <= ?
40
- ORDER BY coverage ASC, complexity DESC NULLS LAST
41
- LIMIT ?
42
- `).all(e,this.config.maxQueryResults).map(l)}async findModuleDependencies(e){this.ensureInitialized();let t=await this.findNodes({type:"module",filePath:e,limit:1});if(t.length===0){let d=await this.findNodes({type:"file",filePath:e,limit:1});if(d.length===0)throw new Error(`Module not found: ${e}`);t.push(d[0])}let r=t[0],i=await this.findEdges({sourceId:r.id,type:["imports","depends_on"]}),a=[];for(let d of i){let c=await this.getNode(d.targetId);c&&a.push(c)}let p=await this.findEdges({targetId:r.id,type:["imports","depends_on"]}),g=[];for(let d of p){let c=await this.getNode(d.sourceId);c&&g.push(c)}let o=await this.traverse(r.id,["imports","depends_on"],5),s=o.nodes.filter(d=>d.id!==r.id);return{module:r,directDependencies:a,dependents:g,transitiveDependencies:s,maxDependencyDepth:o.maxDepthReached}}async buildFromIndexResult(e){this.ensureInitialized();let t=Date.now(),r=0,i=0,a=0,p=[];return this.config.db.transaction(()=>{for(let o of e.files)try{let s=`file:${o.path}`;this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(s)?i++:(this.config.db.prepare(`
43
- INSERT INTO hypergraph_nodes (id, type, name, file_path)
44
- VALUES (?, 'file', ?, ?)
45
- `).run(s,o.path.split("/").pop()||o.path,o.path),r++)}catch(s){p.push({entity:`file:${o.path}`,error:f(s)})}for(let o of e.files)for(let s of o.entities)try{let d=`${s.type}:${o.path}:${s.name}`,c=this.mapEntityTypeToNodeType(s.type);this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(d)?(this.config.db.prepare(`
46
- UPDATE hypergraph_nodes
47
- SET line_start = ?, line_end = ?, complexity = ?, coverage = ?,
48
- updated_at = datetime('now')
49
- WHERE id = ?
50
- `).run(s.lineStart,s.lineEnd,s.complexity,s.coverage,d),i++):(this.config.db.prepare(`
51
- INSERT INTO hypergraph_nodes (id, type, name, file_path, line_start, line_end, complexity, coverage)
52
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
53
- `).run(d,c,s.name,o.path,s.lineStart,s.lineEnd,s.complexity,s.coverage),r++)}catch(d){p.push({entity:`${s.type}:${s.name}`,error:f(d)})}for(let o of e.files){let s=`file:${o.path}`;for(let d of o.imports)try{let c=`file:${d}`;if(this.config.db.prepare("SELECT id FROM hypergraph_nodes WHERE id = ?").get(c)){let m=_(s,c,"imports");this.config.db.prepare(`
54
- INSERT OR REPLACE INTO hypergraph_edges (id, source_id, target_id, type, weight)
55
- VALUES (?, ?, ?, 'imports', 1.0)
56
- `).run(m,s,c),a++}}catch(c){p.push({entity:`import:${d}`,error:f(c)})}}})(),{nodesCreated:r,nodesUpdated:i,edgesCreated:a,durationMs:Date.now()-t,errors:p}}async syncWithKnowledgeGraph(e){this.ensureInitialized();let t=Date.now(),r=0,i=0,a=0,p=0,g=await this.findNodes({});for(let s of g){let d=await e.getNode(s.id);r++}return i=(await this.findEdges({})).length,{nodesSynced:r,edgesSynced:i,nodesAdded:a,nodesRemoved:p,durationMs:Date.now()-t}}async getStats(){this.ensureInitialized();let e=this.schemaManager.getStats(this.config.db),t=this.config.db.prepare(`
57
- SELECT type, COUNT(*) as count FROM hypergraph_nodes GROUP BY type
58
- `).all(),r={function:0,module:0,test:0,file:0,class:0};for(let g of t)g.type in r&&(r[g.type]=g.count);let i=this.config.db.prepare(`
59
- SELECT type, COUNT(*) as count FROM hypergraph_edges GROUP BY type
60
- `).all(),a={calls:0,imports:0,tests:0,depends_on:0,covers:0};for(let g of i)g.type in a&&(a[g.type]=g.count);let p=this.config.db.prepare(`
61
- SELECT
62
- AVG(complexity) as avg_complexity,
63
- AVG(coverage) as avg_coverage,
64
- COUNT(CASE WHEN embedding IS NOT NULL THEN 1 END) as nodes_with_embeddings
65
- FROM hypergraph_nodes
66
- `).get();return{totalNodes:e.nodeCount,totalEdges:e.edgeCount,nodesByType:r,edgesByType:a,avgComplexity:p.avg_complexity??0,avgCoverage:p.avg_coverage??0,nodesWithEmbeddings:p.nodes_with_embeddings}}ensureInitialized(){if(!this.initialized)throw new Error("HypergraphEngine not initialized. Call initialize() first.")}mapEntityTypeToNodeType(e){return{function:"function",class:"class",module:"module",interface:"module",file:"file",test:"test"}[e]??"function"}};async function V(n){let e=new y(n);return await e.initialize(),e}function Y(n){return new y(n)}var k=y;export{z as a,y as b,V as c,Y as d,k as e};
@@ -1,15 +0,0 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.17");process.exit(0)}
2
- import{k as G,o as oe}from"./chunk-B36RPXAQ.js";import{b as W,d as we}from"./chunk-6YFEWIL5.js";import{a as S,b as ze,c as q}from"./chunk-DJXYFFGA.js";var He={continueGate:{enabled:!0,maxConsecutiveRetries:3,reworkRatioThreshold:.5,idleTimeoutMs:9e5,throttleOnExceed:!0},memoryWriteGate:{enabled:!0,contradictionDetection:!0,temporalDecayDays:30,minUsesForRetention:3,domainNamespacing:!0},trustAccumulator:{enabled:!0,performanceWeight:.5,taskSimilarityWeight:.3,capabilityMatchWeight:.2,minTrustForCritical:.7,autoTierAdjustment:!0},proofEnvelope:{enabled:!0,hashChaining:!0,auditLogRetentionDays:90,requireProofForClaims:!0,chainPersistence:!1,maxChainLength:1e4,signAllEnvelopes:!0},budgetMeter:{enabled:!0,maxSessionCostUsd:50,maxTokensPerSession:1e6,warningThresholdPercent:80},deterministicGateway:{enabled:!0,deduplicationWindowMs:5e3,cacheResultsForIdempotent:!0,validateSchemas:!0},evolutionPipeline:{enabled:!0,autoPromoteThreshold:.9,autoDemoteThreshold:.3,minSamplesForDecision:20,learningRate:.1},shardRetriever:{enabled:!0,shardsPath:".claude/guidance/shards",cacheEnabled:!0,cacheTtlMs:3e5,maxShardsPerQuery:3,relevanceThreshold:.3},abBenchmarking:{enabled:!0,defaultConfidenceLevel:.95,defaultMinSampleSize:100,autoApplyWinners:!1,maxConcurrentBenchmarks:5},shardEmbeddings:{enabled:!0,embeddingDimensions:384,persistEmbeddings:!1,autoRebuildOnChange:!0,ngramMin:2,ngramMax:4,persistPath:".agentic-qe/shard-embeddings.json"},adversarialDefense:{enabled:!0,blockThreshold:.7,sanitizeInputs:!0,penalizeOnDetection:!0,logDetections:!0},complianceReporter:{enabled:!0,autoRecordViolations:!0,retentionDays:90,alertOnCritical:!0,generateDailyReport:!1},constitutionalEnforcer:{enabled:!0,strictEnforcement:!1,escalateViolations:!0,constitutionPath:".claude/guidance/constitution.md",logAllChecks:!0},global:{enableAllGates:!0,strictMode:!1,logViolations:!0,escalateToQueen:!0}};function Le(){let c=process.env;return{continueGate:{enabled:c.GOVERNANCE_CONTINUE_GATE!=="false",maxConsecutiveRetries:parseInt(c.GOVERNANCE_MAX_RETRIES||"3",10),reworkRatioThreshold:parseFloat(c.GOVERNANCE_REWORK_THRESHOLD||"0.5"),idleTimeoutMs:parseInt(c.GOVERNANCE_IDLE_TIMEOUT||"900000",10),throttleOnExceed:c.GOVERNANCE_THROTTLE!=="false"},memoryWriteGate:{enabled:c.GOVERNANCE_MEMORY_GATE!=="false",contradictionDetection:c.GOVERNANCE_CONTRADICTION_CHECK!=="false",temporalDecayDays:parseInt(c.GOVERNANCE_DECAY_DAYS||"30",10),minUsesForRetention:parseInt(c.GOVERNANCE_MIN_USES||"3",10),domainNamespacing:c.GOVERNANCE_DOMAIN_NS!=="false"},trustAccumulator:{enabled:c.GOVERNANCE_TRUST!=="false",performanceWeight:parseFloat(c.GOVERNANCE_PERF_WEIGHT||"0.5"),taskSimilarityWeight:parseFloat(c.GOVERNANCE_SIMILARITY_WEIGHT||"0.3"),capabilityMatchWeight:parseFloat(c.GOVERNANCE_CAPABILITY_WEIGHT||"0.2"),minTrustForCritical:parseFloat(c.GOVERNANCE_MIN_TRUST||"0.7"),autoTierAdjustment:c.GOVERNANCE_AUTO_TIER!=="false"},proofEnvelope:{enabled:c.GOVERNANCE_PROOF!=="false",hashChaining:c.GOVERNANCE_HASH_CHAIN!=="false",auditLogRetentionDays:parseInt(c.GOVERNANCE_AUDIT_DAYS||"90",10),requireProofForClaims:c.GOVERNANCE_REQUIRE_PROOF!=="false",chainPersistence:c.GOVERNANCE_CHAIN_PERSIST==="true",maxChainLength:parseInt(c.GOVERNANCE_MAX_CHAIN_LENGTH||"10000",10),signAllEnvelopes:c.GOVERNANCE_SIGN_ALL!=="false"},budgetMeter:{enabled:c.GOVERNANCE_BUDGET!=="false",maxSessionCostUsd:parseFloat(c.GOVERNANCE_MAX_COST||"50"),maxTokensPerSession:parseInt(c.GOVERNANCE_MAX_TOKENS||"1000000",10),warningThresholdPercent:parseInt(c.GOVERNANCE_WARNING_PERCENT||"80",10)},deterministicGateway:{enabled:c.GOVERNANCE_DETERMINISTIC!=="false",deduplicationWindowMs:parseInt(c.GOVERNANCE_DEDUP_WINDOW||"5000",10),cacheResultsForIdempotent:c.GOVERNANCE_CACHE_IDEMPOTENT!=="false",validateSchemas:c.GOVERNANCE_VALIDATE_SCHEMAS!=="false"},evolutionPipeline:{enabled:c.GOVERNANCE_EVOLUTION!=="false",autoPromoteThreshold:parseFloat(c.GOVERNANCE_PROMOTE_THRESHOLD||"0.9"),autoDemoteThreshold:parseFloat(c.GOVERNANCE_DEMOTE_THRESHOLD||"0.3"),minSamplesForDecision:parseInt(c.GOVERNANCE_MIN_SAMPLES||"20",10),learningRate:parseFloat(c.GOVERNANCE_LEARNING_RATE||"0.1")},shardRetriever:{enabled:c.GOVERNANCE_SHARD_RETRIEVER!=="false",shardsPath:c.GOVERNANCE_SHARDS_PATH||".claude/guidance/shards",cacheEnabled:c.GOVERNANCE_SHARD_CACHE!=="false",cacheTtlMs:parseInt(c.GOVERNANCE_SHARD_CACHE_TTL||"300000",10),maxShardsPerQuery:parseInt(c.GOVERNANCE_MAX_SHARDS||"3",10),relevanceThreshold:parseFloat(c.GOVERNANCE_RELEVANCE_THRESHOLD||"0.3")},abBenchmarking:{enabled:c.GOVERNANCE_AB_BENCHMARKING!=="false",defaultConfidenceLevel:parseFloat(c.GOVERNANCE_AB_CONFIDENCE||"0.95"),defaultMinSampleSize:parseInt(c.GOVERNANCE_AB_MIN_SAMPLES||"100",10),autoApplyWinners:c.GOVERNANCE_AB_AUTO_APPLY==="true",maxConcurrentBenchmarks:parseInt(c.GOVERNANCE_AB_MAX_CONCURRENT||"5",10)},shardEmbeddings:{enabled:c.GOVERNANCE_SHARD_EMBEDDINGS!=="false",embeddingDimensions:parseInt(c.GOVERNANCE_EMBEDDING_DIMENSIONS||"384",10),persistEmbeddings:c.GOVERNANCE_PERSIST_EMBEDDINGS==="true",autoRebuildOnChange:c.GOVERNANCE_AUTO_REBUILD!=="false",ngramMin:parseInt(c.GOVERNANCE_NGRAM_MIN||"2",10),ngramMax:parseInt(c.GOVERNANCE_NGRAM_MAX||"4",10),persistPath:c.GOVERNANCE_EMBEDDINGS_PATH||".agentic-qe/shard-embeddings.json"},adversarialDefense:{enabled:c.GOVERNANCE_ADVERSARIAL_DEFENSE!=="false",blockThreshold:parseFloat(c.GOVERNANCE_BLOCK_THRESHOLD||"0.7"),sanitizeInputs:c.GOVERNANCE_SANITIZE_INPUTS!=="false",penalizeOnDetection:c.GOVERNANCE_PENALIZE_DETECTION!=="false",logDetections:c.GOVERNANCE_LOG_DETECTIONS!=="false"},complianceReporter:{enabled:c.GOVERNANCE_COMPLIANCE_REPORTER!=="false",autoRecordViolations:c.GOVERNANCE_AUTO_RECORD_VIOLATIONS!=="false",retentionDays:parseInt(c.GOVERNANCE_VIOLATION_RETENTION_DAYS||"90",10),alertOnCritical:c.GOVERNANCE_ALERT_ON_CRITICAL!=="false",generateDailyReport:c.GOVERNANCE_DAILY_REPORT==="true"},constitutionalEnforcer:{enabled:c.GOVERNANCE_CONSTITUTIONAL_ENFORCER!=="false",strictEnforcement:c.GOVERNANCE_CONSTITUTIONAL_STRICT==="true",escalateViolations:c.GOVERNANCE_CONSTITUTIONAL_ESCALATE!=="false",constitutionPath:c.GOVERNANCE_CONSTITUTION_PATH||".claude/guidance/constitution.md",logAllChecks:c.GOVERNANCE_CONSTITUTIONAL_LOG!=="false"},global:{enableAllGates:c.GOVERNANCE_ENABLED!=="false",strictMode:c.GOVERNANCE_STRICT==="true",logViolations:c.GOVERNANCE_LOG_VIOLATIONS!=="false",escalateToQueen:c.GOVERNANCE_ESCALATE!=="false"}}}function ce(c=He,e=Le(),t={}){let n=(i,r)=>{let s={...i};for(let a in r)r[a]!==void 0&&(typeof r[a]=="object"&&!Array.isArray(r[a])?s[a]=n(i[a],r[a]):s[a]=r[a]);return s};return n(n(c,e),t)}var Ae=class{flags;listeners=new Set;constructor(){this.flags=ce()}getFlags(){return this.flags}isGateEnabled(e){return this.flags.global.enableAllGates?this.flags[e].enabled:!1}updateFlags(e){this.flags=ce(this.flags,{},e),this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){this.listeners.forEach(e=>e(this.flags))}reset(){this.flags=ce(),this.notifyListeners()}enableStrictMode(){this.updateFlags({global:{...this.flags.global,strictMode:!0}})}disableAllGates(){this.updateFlags({global:{...this.flags.global,enableAllGates:!1}})}},m=new Ae,F=()=>m.isGateEnabled("continueGate"),j=()=>m.isGateEnabled("memoryWriteGate"),x=()=>m.isGateEnabled("trustAccumulator");var le=()=>m.isGateEnabled("budgetMeter"),ue=()=>m.isGateEnabled("deterministicGateway");var T=()=>m.isGateEnabled("adversarialDefense"),I=()=>m.isGateEnabled("complianceReporter"),U=()=>m.isGateEnabled("constitutionalEnforcer"),y=()=>m.getFlags().global.strictMode;var xe=class{patternIndex=new Map;domainPatterns=new Map;guidanceMemoryGate=null;initialized=!1;async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/memory-gate");t&&typeof t.createMemoryWriteGate=="function"&&(this.guidanceMemoryGate=t.createMemoryWriteGate({enableContradictionTracking:!0}),console.log("[MemoryWriteGateIntegration] Guidance MemoryWriteGate loaded"))}catch{this.guidanceMemoryGate=null}this.initialized=!0}}async evaluateWrite(e){if(!j())return{allowed:!0};await this.initialize();let t=m.getFlags().memoryWriteGate;e.timestamp=e.timestamp||Date.now(),e.useCount=e.useCount||0;let n=this.localEvaluation(e,t);if(this.guidanceMemoryGate&&n.allowed&&!n.reason)try{let i={agentId:e.agentId||"unknown",role:"worker",namespaces:[e.domain],maxWritesPerMinute:60,canDelete:!1,canOverwrite:!0,trustLevel:.7},r=this.guidanceMemoryGate.evaluateWrite(i,e.key,e.domain,e.value);if(!r.allowed)return this.mapGuidanceDecision(r)}catch{}return n}localEvaluation(e,t){if(t.domainNamespacing&&e.agentId){let n=this.getAllowedDomainsForAgent(e.agentId);if(!n.includes(e.domain)&&!n.includes("*"))return this.logViolation(e,"domain_violation",`Agent ${e.agentId} cannot write to domain ${e.domain}`),{allowed:!y(),reason:`Agent ${e.agentId} not authorized to write to domain ${e.domain}`,requiresManualReview:!0}}if(t.contradictionDetection){let n=this.findConflictingPatterns(e);if(n.length>0)return n.every(r=>e.supersedes?.includes(r.key))?{allowed:!0,conflictingPatterns:n,suggestedResolution:"supersede"}:(this.logViolation(e,"contradiction",`Conflicts with ${n.length} existing pattern(s)`),{allowed:!y(),reason:`Pattern conflicts with ${n.length} existing pattern(s)`,conflictingPatterns:n,suggestedResolution:this.suggestResolution(e,n),requiresManualReview:n.some(r=>(r.useCount||0)>5)})}return{allowed:!0}}findConflictingPatterns(e){let t=this.domainPatterns.get(e.domain);if(!t)return[];let n=[];for(let i of t){let r=this.patternIndex.get(i);!r||r.key===e.key||this.areContradictory(e,r)&&n.push(r)}return n}areContradictory(e,t){if(e.key===t.key)return!1;let n=JSON.stringify(e.value).toLowerCase(),i=JSON.stringify(t.value).toLowerCase(),r=[{positive:"should",negative:"should not"},{positive:"always",negative:"never"},{positive:"enabled",negative:"disabled"},{positive:"true",negative:"false"},{positive:"allow",negative:"deny"},{positive:"include",negative:"exclude"}];for(let s of r)if(n.includes(s.positive)&&i.includes(s.negative)||n.includes(s.negative)&&i.includes(s.positive)){let a=new Set(n.match(/\b\w{4,}\b/g)||[]),o=new Set(i.match(/\b\w{4,}\b/g)||[]);if([...a].filter(u=>o.has(u)).length>=2)return!0}return!!(e.tags&&t.tags&&e.tags.filter(a=>t.tags?.includes(a)).length>0&&e.value!==t.value)}suggestResolution(e,t){let n=e.timestamp||0,i=Math.min(...t.map(r=>r.timestamp||0));return n-i>10080*60*1e3?"supersede":t.some(r=>(r.useCount||0)>10)?"reject":"merge"}getAllowedDomainsForAgent(e){return{"qe-test-architect":["test-generation","learning-optimization"],"qe-coverage-specialist":["coverage-analysis","learning-optimization"],"qe-security-scanner":["security-compliance"],"qe-chaos-engineer":["chaos-resilience"],"qe-defect-predictor":["defect-intelligence","learning-optimization"],"qe-learning-coordinator":["*"],"qe-quality-gate":["quality-assessment"],"qe-parallel-executor":["test-execution"],"qe-contract-validator":["contract-testing"],"qe-accessibility-auditor":["visual-accessibility"],"qe-requirements-validator":["requirements-validation"],"qe-code-intelligence":["code-intelligence"]}[e]||[e.split("-").pop()||"unknown"]}getExistingPatterns(e){let t=this.domainPatterns.get(e);return t?[...t].map(n=>this.patternIndex.get(n)).filter(n=>n!==void 0):[]}mapGuidanceDecision(e){return{allowed:e.allowed,reason:e.reason,requiresManualReview:!e.authorityCheck.passed||e.contradictions.length>0,suggestedResolution:e.contradictions.length>0?"reject":void 0}}logViolation(e,t,n){m.getFlags().global.logViolations&&console.warn("[MemoryWriteGate] Violation detected:",{patternKey:e.key,domain:e.domain,violationType:t,details:n,timestamp:new Date().toISOString()})}registerPattern(e){this.patternIndex.set(e.key,e),this.domainPatterns.has(e.domain)||this.domainPatterns.set(e.domain,new Set),this.domainPatterns.get(e.domain).add(e.key)}unregisterPattern(e){let t=this.patternIndex.get(e);t&&(this.domainPatterns.get(t.domain)?.delete(e),this.patternIndex.delete(e))}incrementUseCount(e){let t=this.patternIndex.get(e);t&&(t.useCount=(t.useCount||0)+1)}async applyTemporalDecay(){let e=m.getFlags().memoryWriteGate,t=e.temporalDecayDays*24*60*60*1e3,n=Date.now(),i=[];for(let[r,s]of this.patternIndex){let a=n-(s.timestamp||0),o=s.useCount||0;a>t&&o<e.minUsesForRetention&&(i.push(r),this.unregisterPattern(r))}return i.length>0&&console.info(`[MemoryWriteGate] Archived ${i.length} patterns due to temporal decay`),i}getStats(){let e={};for(let[t,n]of this.domainPatterns)e[t]=n.size;return{totalPatterns:this.patternIndex.size,patternsByDomain:e}}reset(){this.patternIndex.clear(),this.domainPatterns.clear()}loadPatternsFromBank(e){for(let t of e)this.registerPattern(t)}},K=new xe;function Ie(c,e,t,n={}){return{key:c,value:e,domain:t,timestamp:Date.now(),useCount:0,...n}}import{randomUUID as We}from"node:crypto";we();import{randomUUID as ot,createHash as ct}from"node:crypto";q();we();import{createHash as st,createHmac as at}from"node:crypto";var Me=class{kernel=null;initialized=!1;initError=null;metrics={backend:"js",avgHashTimeMs:0,totalOperations:0,totalTimeMs:0,operationCounts:{hash:0,hashChain:0,verify:0,hmac:0}};async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/wasm-kernel");t&&typeof t.getKernel=="function"&&(this.kernel=t.getKernel(),this.metrics.backend=this.kernel?.available?"wasm":"js")}catch(e){this.initError=ze(e),this.kernel=null,this.metrics.backend="js"}this.initialized=!0}}isWasmAvailable(){return this.kernel?.available??!1}getVersion(){return this.kernel?.version??"js-fallback"}getInitError(){return this.initError}hash(e){let t=performance.now(),n;if(this.kernel?.available){let i=typeof e=="string"?e:Buffer.from(e).toString("utf-8");n=this.kernel.sha256(i)}else n=this.jsHash(e);return this.recordOperation("hash",performance.now()-t),n}hmac(e,t){let n=performance.now(),i;return this.kernel?.available?i=this.kernel.hmacSha256(e,t):i=at("sha256",e).update(t).digest("hex"),this.recordOperation("hmac",performance.now()-n),i}hashChain(e){let t=performance.now();if(e.length===0)return this.recordOperation("hashChain",performance.now()-t),this.hash("");if(e.length===1)return this.recordOperation("hashChain",performance.now()-t),e[0];let n=e[0];for(let i=1;i<e.length;i++)n=this.hash(n+e[i]);return this.recordOperation("hashChain",performance.now()-t),n}verify(e,t){let n=performance.now(),r=this.hash(e)===t;return this.recordOperation("verify",performance.now()-n),r}contentHash(e){let t=performance.now(),n,i=typeof e=="string"?e:JSON.stringify(e);return this.kernel?.available?n=this.kernel.contentHash(i):n=this.jsContentHash(i),this.recordOperation("hash",performance.now()-t),n}signEnvelope(e,t){let n=JSON.stringify(t);return this.kernel?.available?this.kernel.signEnvelope(e,n):this.hmac(e,n)}getPerformanceMetrics(){return{...this.metrics}}resetMetrics(){this.metrics={backend:this.kernel?.available?"wasm":"js",avgHashTimeMs:0,totalOperations:0,totalTimeMs:0,operationCounts:{hash:0,hashChain:0,verify:0,hmac:0}}}reset(){this.kernel=null,this.initialized=!1,this.initError=null,this.resetMetrics()}jsHash(e){let t=st("sha256");return typeof e=="string"?t.update(e):t.update(Buffer.from(e)),t.digest("hex")}jsContentHash(e){try{let t=W(e),n=this.sortKeys(t);return this.jsHash(JSON.stringify(n))}catch{return this.jsHash(e)}}sortKeys(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>this.sortKeys(n));let t={};for(let n of Object.keys(e).sort())t[n]=this.sortKeys(e[n]);return t}recordOperation(e,t){this.metrics.totalOperations++,this.metrics.totalTimeMs+=t,this.metrics.operationCounts[e]++,this.metrics.avgHashTimeMs=this.metrics.totalTimeMs/this.metrics.totalOperations}},qe=new Me;var ne="0".repeat(64),de=class{kernel;chain=[];signingKey="";guidanceProofChain=null;initialized=!1;envelopeIndex=new Map;constructor(e){this.kernel=e??qe}async initialize(e){if(!this.initialized){await this.kernel.initialize(),this.signingKey=e||ct("sha256").update(`aqe-proof-envelope:${process.cwd()}`).digest("hex");try{let n=await import("@claude-flow/guidance/proof");n&&typeof n.createProofChain=="function"&&(this.guidanceProofChain=n.createProofChain({signingKey:this.signingKey}),console.log("[ProofEnvelopeIntegration] Guidance ProofChain loaded"))}catch{this.guidanceProofChain=null}this.initialized=!0}}isInitialized(){return this.initialized}getFlags(){return m.getFlags().proofEnvelope}createEnvelope(e,t,n,i){let r=this.generateEnvelopeId(),s=Date.now(),a=this.chain.length>0?this.chain[this.chain.length-1].contentHash:ne,o={id:r,timestamp:s,agentId:e,action:t,payload:n,metadata:i},l=this.kernel.contentHash(o);return{id:r,timestamp:s,agentId:e,action:t,payload:n,contentHash:l,previousHash:a,signature:"",metadata:i}}signEnvelope(e,t){let n=t??this.signingKey,i=`${e.contentHash}:${e.previousHash}`,r=this.kernel.hmac(n,i);return{...e,signature:r}}createSignedEnvelope(e,t,n,i){let r=this.createEnvelope(e,t,n,i);return this.signEnvelope(r)}appendToChain(e){let t=this.verifyEnvelope(e);if(!t.valid)throw new Error(`Cannot append invalid envelope: ${t.error}`);let n=this.chain.length>0?this.chain[this.chain.length-1].contentHash:ne;if(e.previousHash!==n)throw new Error(`Envelope does not link to chain. Expected previous hash ${n}, got ${e.previousHash}`);let i=this.chain.length;if(this.chain.push(e),this.envelopeIndex.set(e.id,i),this.guidanceProofChain)try{let r={eventId:e.id,taskId:e.metadata?.taskId?String(e.metadata.taskId):e.id,guidanceHash:e.contentHash,retrievedRuleIds:[],toolsUsed:e.action?[e.action]:[],filesTouched:[],diffSummary:{linesAdded:0,linesRemoved:0,filesChanged:0},testResults:{passed:0,failed:0,skipped:0},metrics:{},timestamp:new Date(e.timestamp).toISOString()};this.guidanceProofChain.append(r,[],[],{agentId:e.agentId,sessionId:e.metadata?.sessionId?String(e.metadata.sessionId):"aqe"})}catch{}}getChain(){return[...this.chain]}getChainLength(){return this.chain.length}getLastEnvelope(){return this.chain.length===0?null:this.chain[this.chain.length-1]}clearChain(){this.chain=[],this.envelopeIndex.clear()}verifyEnvelope(e,t){let n=t??this.signingKey,i={contentHashValid:!1,signatureValid:!1,chainLinkValid:!0},r={id:e.id,timestamp:e.timestamp,agentId:e.agentId,action:e.action,payload:e.payload,metadata:e.metadata},s=this.kernel.contentHash(r);if(i.contentHashValid=e.contentHash===s,!i.contentHashValid)return{valid:!1,details:i,error:"Content hash does not match envelope content"};let a=`${e.contentHash}:${e.previousHash}`,o=this.kernel.hmac(n,a);if(i.signatureValid=e.signature===o,!i.signatureValid)return{valid:!1,details:i,error:"Signature verification failed"};let l=this.envelopeIndex.get(e.id);if(l!==void 0&&l>0){let u=this.chain[l-1];if(i.chainLinkValid=e.previousHash===u.contentHash,!i.chainLinkValid)return{valid:!1,details:i,error:"Chain link is broken - previous hash does not match"}}return{valid:!0,details:i}}verifyChain(e){let t=[],n=-1;for(let i=0;i<this.chain.length;i++){let r=this.chain[i],s=this.verifyEnvelope(r,e);s.valid||(t.push({index:i,envelopeId:r.id,error:s.error??"Unknown error"}),n===-1&&(n=i));let a=i>0?this.chain[i-1].contentHash:ne;r.previousHash!==a&&(t.push({index:i,envelopeId:r.id,error:`Chain link broken at index ${i}`}),n===-1&&(n=i))}return{valid:t.length===0,envelopesVerified:this.chain.length,firstInvalidIndex:n,merkleRoot:this.computeMerkleRoot(),errors:t}}detectTampering(){let e=[],t=[];for(let n=0;n<this.chain.length;n++){let i=this.chain[n],r={id:i.id,timestamp:i.timestamp,agentId:i.agentId,action:i.action,payload:i.payload,metadata:i.metadata},s=this.kernel.contentHash(r);i.contentHash!==s&&(t.push(n),e.push({index:n,envelopeId:i.id,issue:"Content hash mismatch - envelope content was modified"}));let a=n>0?this.chain[n-1].contentHash:ne;i.previousHash!==a&&(t.includes(n)||t.push(n),e.push({index:n,envelopeId:i.id,issue:"Chain link broken - previous hash does not match"}))}return{tampered:t.length>0,tamperedIndices:t,details:e}}getEnvelopeById(e){let t=this.envelopeIndex.get(e);return t===void 0?null:this.chain[t]}getEnvelopesByAgent(e){return this.chain.filter(t=>t.agentId===e)}getEnvelopesByAction(e){return this.chain.filter(t=>t.action===e)}getEnvelopesSince(e){return this.chain.filter(t=>t.timestamp>=e)}getEnvelopesInRange(e,t){return this.chain.filter(n=>n.timestamp>=e&&n.timestamp<=t)}exportChain(e){let t={version:1,exportedAt:Date.now(),chainLength:this.chain.length,merkleRoot:this.computeMerkleRoot(),envelopes:this.chain};if(e==="json")return JSON.stringify(t,null,2);let n=JSON.stringify(t);return new TextEncoder().encode(n)}importChain(e,t=!0){let n;typeof e=="string"?n=e:n=new TextDecoder().decode(e);let i=W(n);if(!i.envelopes||!Array.isArray(i.envelopes))throw new Error("Invalid chain data: missing envelopes array");this.clearChain();for(let r of i.envelopes){let s=this.chain.length;this.chain.push(r),this.envelopeIndex.set(r.id,s)}if(t){let r=this.verifyChain();if(!r.valid)throw this.clearChain(),new Error(`Imported chain failed verification: ${r.errors[0]?.error}`)}}getProofStats(){let e={},t=new Set;for(let i of this.chain)t.add(i.agentId),e[i.action]=(e[i.action]||0)+1;let n=this.chain.length===0||this.verifyChain().valid;return{chainLength:this.chain.length,firstTimestamp:this.chain.length>0?this.chain[0].timestamp:null,lastTimestamp:this.chain.length>0?this.chain[this.chain.length-1].timestamp:null,uniqueAgents:Array.from(t),actionCounts:e,merkleRoot:this.computeMerkleRoot(),chainValid:n}}computeMerkleRoot(){if(this.chain.length===0)return ne;let e=this.chain.map(t=>t.contentHash);for(;e.length>1;){let t=[];for(let n=0;n<e.length;n+=2)n+1<e.length?t.push(this.kernel.hash(e[n]+e[n+1])):t.push(e[n]);e=t}return e[0]}getMerkleProof(e){let t=this.envelopeIndex.get(e);if(t===void 0)return null;let n=[],i=this.chain.map(s=>s.contentHash),r=t;for(;i.length>1;){let s=r%2===0?r+1:r-1;s<i.length&&n.push(i[s]);let a=[];for(let o=0;o<i.length;o+=2)o+1<i.length?a.push(this.kernel.hash(i[o]+i[o+1])):a.push(i[o]);i=a,r=Math.floor(r/2)}return n}verifyMerkleProof(e,t,n){let i=e,r=n;for(let s of t)r%2===0?i=this.kernel.hash(i+s):i=this.kernel.hash(s+i),r=Math.floor(r/2);return i===this.computeMerkleRoot()}generateEnvelopeId(){return`env_${ot()}`}reset(){this.chain=[],this.envelopeIndex.clear(),this.signingKey="",this.initialized=!1}},Pe=new de;oe();q();var Ue={enabled:!0,autoRecordViolations:!0,retentionDays:90,alertOnCritical:!0,generateDailyReport:!1},lt={low:1,medium:3,high:7,critical:15},je=100,ut=.5,Q=5,me=class c{violations=new Map;alertThresholds=new Map;proofIntegration;flags;initialized=!1;scoreHistory=[];alertListeners=new Set;db=null;persistCount=0;static NAMESPACE="compliance-audit";static TTL_SECONDS=2592e3;static PERSIST_INTERVAL=10;constructor(e,t){this.proofIntegration=e??Pe,this.flags={...Ue,...t}}async initialize(){if(!this.initialized){try{this.db=G(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[ComplianceReporter] DB init failed, using memory-only:",S(e)),this.db=null}this.proofIntegration.isInitialized()||await this.proofIntegration.initialize(),this.alertThresholds.set("continueGate",70),this.alertThresholds.set("memoryWriteGate",70),this.alertThresholds.set("trustAccumulator",70),this.alertThresholds.set("budgetMeter",60),this.alertThresholds.set("adversarialDefense",80),this.initialized=!0}}isInitialized(){return this.initialized}getFlags(){return{...this.flags}}updateFlags(e){this.flags={...this.flags,...e}}recordViolation(e){let t=this.generateViolationId(),n=Date.now(),i={...e,id:t,timestamp:n,resolved:!1};if(this.violations.set(t,i),m.getFlags().proofEnvelope.enabled)try{let r=this.proofIntegration.createSignedEnvelope(e.agentId??"system","violation_recorded",{violationId:t,type:e.type,severity:e.severity,gate:e.gate,description:e.description});this.proofIntegration.appendToChain(r),i.proofEnvelopeId=r.id}catch{}return this.flags.alertOnCritical&&e.severity==="critical"&&this.triggerAlert(e.gate,"Critical violation detected","critical"),this.persistSnapshot(),this.cleanupOldViolations(),t}resolveViolation(e,t){let n=this.violations.get(e);if(!n)throw new Error(`Violation not found: ${e}`);if(n.resolved=!0,n.resolution=t,n.resolvedAt=Date.now(),m.getFlags().proofEnvelope.enabled)try{let i=this.proofIntegration.createSignedEnvelope(n.agentId??"system","violation_resolved",{violationId:e,resolution:t});this.proofIntegration.appendToChain(i)}catch{}}getViolation(e){return this.violations.get(e)??null}getViolations(e){let t=Array.from(this.violations.values());return e&&(e.type!==void 0&&(t=t.filter(n=>n.type===e.type)),e.severity!==void 0&&(t=t.filter(n=>n.severity===e.severity)),e.agentId!==void 0&&(t=t.filter(n=>n.agentId===e.agentId)),e.gate!==void 0&&(t=t.filter(n=>n.gate===e.gate)),e.resolved!==void 0&&(t=t.filter(n=>n.resolved===e.resolved)),e.startTime!==void 0&&(t=t.filter(n=>n.timestamp>=e.startTime)),e.endTime!==void 0&&(t=t.filter(n=>n.timestamp<=e.endTime)),e.limit!==void 0&&(t=t.slice(0,e.limit))),t.sort((n,i)=>i.timestamp-n.timestamp)}calculateScore(e){let t=Date.now(),n=e??{start:t-1440*60*1e3,end:t},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.calculateOverallScore(i),s={},a=this.groupBy(i,"gate");for(let[g,f]of Object.entries(a))s[g]=this.calculateOverallScore(f);let o={},l=this.groupBy(i,"agentId");for(let[g,f]of Object.entries(l))g!=="undefined"&&(o[g]=this.calculateOverallScore(f));let u=this.calculateTrend(n),d=i.filter(g=>g.resolved).length,h={overall:r,byGate:s,byAgent:o,trend:u,period:n,totalViolations:i.length,resolvedViolations:d};return this.scoreHistory.push(h),this.scoreHistory.length>100&&this.scoreHistory.shift(),h}getScoreHistory(e){return this.scoreHistory.slice(-e)}generateReport(e={}){let t=Date.now(),n=e.timeWindow??{start:t-1440*60*1e3,end:t},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.calculateScore(n),s={loop_detected:0,contradiction:0,trust_violation:0,budget_exceeded:0,adversarial_detected:0,invariant_violated:0,unauthorized_access:0,chain_tampered:0,schema_violation:0,rate_limit_exceeded:0};for(let g of i)s[g.type]++;let a={low:0,medium:0,high:0,critical:0};for(let g of i)a[g.severity]++;let o={},l=this.groupBy(i,"gate");for(let[g,f]of Object.entries(l))o[g]={score:this.calculateOverallScore(f),violations:f.length,trend:this.calculateGateTrend(g,n)};let u=i.filter(g=>g.resolved).length,d=i.length>0?u/i.length:1,h={generatedAt:t,timeWindow:n,summary:{overallScore:r.overall,totalViolations:i.length,criticalViolations:a.critical,highViolations:a.high,resolvedViolations:u,resolutionRate:d,trend:r.trend},gateScores:o,violationsByType:s,violationsBySeverity:a};if(e.includeAgentRankings){let g=this.groupBy(i,"agentId");h.agentRankings=Object.entries(g).filter(([f])=>f!=="undefined").map(([f,k])=>({agentId:f,score:this.calculateOverallScore(k),violations:k.length,trend:this.calculateAgentTrend(f,n)})).sort((f,k)=>k.score-f.score)}if(e.includeViolations){let g=e.maxViolations??50;h.violations=i.slice(0,g)}return e.includeRecommendations&&(h.recommendations=this.generateRecommendations(i,r)),e.includeTrendAnalysis&&(h.trendAnalysis=this.calculateTrendAnalysis(n)),h}exportReport(e,t){return t==="json"?JSON.stringify(e,null,2):this.generateMarkdownReport(e)}attachProof(e,t){let n=this.violations.get(e);if(!n)throw new Error(`Violation not found: ${e}`);if(!this.proofIntegration.getEnvelopeById(t))throw new Error(`Proof envelope not found: ${t}`);n.proofEnvelopeId=t}getViolationsWithProof(){return Array.from(this.violations.values()).filter(e=>e.proofEnvelopeId!==void 0)}getViolationProof(e){let t=this.violations.get(e);return t?.proofEnvelopeId?this.proofIntegration.getEnvelopeById(t.proofEnvelopeId):null}setAlertThreshold(e,t){if(t<0||t>100)throw new Error("Threshold must be between 0 and 100");this.alertThresholds.set(e,t)}getAlertThreshold(e){return this.alertThresholds.get(e)}checkAlerts(){let e=[],t=this.calculateScore();for(let[n,i]of this.alertThresholds){let r=t.byGate[n];if(r!==void 0&&r<i){let s={id:this.generateAlertId(),gate:n,message:`Compliance score for ${n} (${r.toFixed(1)}) dropped below threshold (${i})`,severity:r<i*.5?"critical":"high",timestamp:Date.now(),currentScore:r,threshold:i};e.push(s),this.notifyAlertListeners(s)}}return e}onAlert(e){return this.alertListeners.add(e),()=>this.alertListeners.delete(e)}getComplianceStats(){let e=Array.from(this.violations.values()),t=e.filter(d=>d.resolved),n={loop_detected:0,contradiction:0,trust_violation:0,budget_exceeded:0,adversarial_detected:0,invariant_violated:0,unauthorized_access:0,chain_tampered:0,schema_violation:0,rate_limit_exceeded:0};for(let d of e)n[d.type]++;let i={low:0,medium:0,high:0,critical:0};for(let d of e)i[d.severity]++;let r={};for(let d of e)r[d.gate]=(r[d.gate]||0)+1;let s={};for(let d of e)d.agentId&&(s[d.agentId]=(s[d.agentId]||0)+1);let a=0,o=0;for(let d of t)d.resolvedAt&&(a+=d.resolvedAt-d.timestamp,o++);let l=o>0?a/o:0,u=e.filter(d=>d.proofEnvelopeId).length;return{totalViolations:e.length,resolvedViolations:t.length,resolutionRate:e.length>0?t.length/e.length:1,byType:n,bySeverity:i,byGate:r,byAgent:s,avgResolutionTime:l,violationsWithProof:u,currentScore:this.calculateScore().overall}}clearViolations(){this.violations.clear(),this.scoreHistory=[]}reset(){this.violations.clear(),this.alertThresholds.clear(),this.scoreHistory=[],this.alertListeners.clear(),this.initialized=!1}async loadFromKv(){if(!this.db)return;let e=await this.db.kvGet("snapshot",c.NAMESPACE);if(e){if(e.violations)for(let[t,n]of Object.entries(e.violations))this.violations.set(t,n);e.scoreHistory&&(this.scoreHistory=e.scoreHistory)}}persistSnapshot(){if(this.db&&(this.persistCount++,this.persistCount%c.PERSIST_INTERVAL===0))try{let e=Array.from(this.violations.entries()).slice(-500),t={violations:Object.fromEntries(e),scoreHistory:this.scoreHistory.slice(-100)};this.db.kvSet("snapshot",t,c.NAMESPACE,c.TTL_SECONDS).catch(()=>{})}catch(e){console.warn("[ComplianceReporter] Persist failed:",S(e))}}generateViolationId(){return`viol_${We()}`}generateAlertId(){return`alert_${We()}`}calculateOverallScore(e){if(e.length===0)return je;let t=0;for(let i of e){let r=i.resolved?.5:1;t+=lt[i.severity]*r}let n=je*Math.exp(-ut*t/10);return Math.max(0,Math.min(100,Math.round(n*10)/10))}calculateTrend(e){let t=e.end-e.start,n={start:e.start-t,end:e.start},i=this.getViolations({startTime:n.start,endTime:n.end}),r=this.getViolations({startTime:e.start,endTime:e.end}),s=this.calculateOverallScore(i),o=this.calculateOverallScore(r)-s;return o>Q?"improving":o<-Q?"declining":"stable"}calculateGateTrend(e,t){let n=t.end-t.start,i={start:t.start-n,end:t.start},r=this.getViolations({gate:e,startTime:i.start,endTime:i.end}),s=this.getViolations({gate:e,startTime:t.start,endTime:t.end}),a=this.calculateOverallScore(r),l=this.calculateOverallScore(s)-a;return l>Q?"improving":l<-Q?"declining":"stable"}calculateAgentTrend(e,t){let n=t.end-t.start,i={start:t.start-n,end:t.start},r=this.getViolations({agentId:e,startTime:i.start,endTime:i.end}),s=this.getViolations({agentId:e,startTime:t.start,endTime:t.end}),a=this.calculateOverallScore(r),l=this.calculateOverallScore(s)-a;return l>Q?"improving":l<-Q?"declining":"stable"}calculateTrendAnalysis(e){let t=e.end-e.start,n={start:e.start-t,end:e.start},i=this.getViolations({startTime:e.start,endTime:e.end}),r=this.getViolations({startTime:n.start,endTime:n.end}),s=this.calculateOverallScore(i),a=this.calculateOverallScore(r),o=i.length-r.length,l;return o>2?l="increasing":o<-2?l="decreasing":l="stable",{currentPeriodScore:s,previousPeriodScore:a,change:s-a,violationTrend:l}}generateRecommendations(e,t){let n=[],i=e.filter(a=>a.severity==="critical").length;i>0&&n.push(`URGENT: ${i} critical violation(s) require immediate attention.`);let r=e.filter(a=>!a.resolved).length;r>5&&n.push(`${r} violations remain unresolved. Consider allocating resources for resolution.`);for(let[a,o]of Object.entries(t.byGate))o<70&&n.push(`${a} compliance score is ${o.toFixed(1)}. Review ${a} configuration and add monitoring.`);for(let[a,o]of Object.entries(t.byAgent))o<60&&n.push(`Agent ${a} has low compliance score (${o.toFixed(1)}). Consider retraining or restricting permissions.`);let s=new Map;for(let a of e)s.set(a.type,(s.get(a.type)||0)+1);for(let[a,o]of s)o>=5&&n.push(`${a} violations occurred ${o} times. Investigate root cause and add preventive measures.`);return t.trend==="declining"&&n.push("Overall compliance trend is declining. Schedule a governance review meeting."),n.length===0&&n.push("Compliance is within acceptable parameters. Continue monitoring."),n}generateMarkdownReport(e){let t=[],n=new Date(e.generatedAt).toISOString();t.push("# Compliance Report"),t.push(""),t.push(`**Generated:** ${n}`),t.push(`**Period:** ${new Date(e.timeWindow.start).toISOString()} to ${new Date(e.timeWindow.end).toISOString()}`),t.push(""),t.push("## Executive Summary"),t.push(""),t.push("| Metric | Value |"),t.push("|--------|-------|"),t.push(`| Overall Score | ${e.summary.overallScore.toFixed(1)} |`),t.push(`| Total Violations | ${e.summary.totalViolations} |`),t.push(`| Critical Violations | ${e.summary.criticalViolations} |`),t.push(`| High Violations | ${e.summary.highViolations} |`),t.push(`| Resolution Rate | ${(e.summary.resolutionRate*100).toFixed(1)}% |`),t.push(`| Trend | ${e.summary.trend} |`),t.push(""),t.push("## Gate Compliance Scores"),t.push(""),t.push("| Gate | Score | Violations | Trend |"),t.push("|------|-------|------------|-------|");for(let[i,r]of Object.entries(e.gateScores))t.push(`| ${i} | ${r.score.toFixed(1)} | ${r.violations} | ${r.trend} |`);t.push(""),t.push("## Violations by Type"),t.push(""),t.push("| Type | Count |"),t.push("|------|-------|");for(let[i,r]of Object.entries(e.violationsByType))r>0&&t.push(`| ${i} | ${r} |`);t.push(""),t.push("## Violations by Severity"),t.push(""),t.push("| Severity | Count |"),t.push("|----------|-------|");for(let[i,r]of Object.entries(e.violationsBySeverity))t.push(`| ${i} | ${r} |`);if(t.push(""),e.agentRankings&&e.agentRankings.length>0){t.push("## Agent Compliance Rankings"),t.push(""),t.push("| Agent | Score | Violations | Trend |"),t.push("|-------|-------|------------|-------|");for(let i of e.agentRankings)t.push(`| ${i.agentId} | ${i.score.toFixed(1)} | ${i.violations} | ${i.trend} |`);t.push("")}if(e.trendAnalysis&&(t.push("## Trend Analysis"),t.push(""),t.push(`- **Current Period Score:** ${e.trendAnalysis.currentPeriodScore.toFixed(1)}`),t.push(`- **Previous Period Score:** ${e.trendAnalysis.previousPeriodScore.toFixed(1)}`),t.push(`- **Change:** ${e.trendAnalysis.change>0?"+":""}${e.trendAnalysis.change.toFixed(1)}`),t.push(`- **Violation Trend:** ${e.trendAnalysis.violationTrend}`),t.push("")),e.recommendations&&e.recommendations.length>0){t.push("## Recommendations"),t.push("");for(let i of e.recommendations)t.push(`- ${i}`);t.push("")}if(e.violations&&e.violations.length>0){t.push("## Recent Violations"),t.push("");for(let i of e.violations.slice(0,10)){let r=i.resolved?"RESOLVED":"OPEN",s=new Date(i.timestamp).toISOString();t.push(`### ${i.id}`),t.push(""),t.push(`- **Type:** ${i.type}`),t.push(`- **Severity:** ${i.severity}`),t.push(`- **Gate:** ${i.gate}`),t.push(`- **Status:** ${r}`),t.push(`- **Time:** ${s}`),i.agentId&&t.push(`- **Agent:** ${i.agentId}`),t.push(`- **Description:** ${i.description}`),i.proofEnvelopeId&&t.push(`- **Proof:** ${i.proofEnvelopeId}`),t.push("")}}return t.push("---"),t.push("*Report generated by Agentic QE Compliance Reporter*"),t.join(`
3
- `)}groupBy(e,t){let n={};for(let i of e){let r=String(i[t]);n[r]||(n[r]=[]),n[r].push(i)}return n}cleanupOldViolations(){let e=Date.now()-this.flags.retentionDays*24*60*60*1e3;for(let[t,n]of this.violations)n.timestamp<e&&this.violations.delete(t)}triggerAlert(e,t,n){let i={id:this.generateAlertId(),gate:e,message:t,severity:n,timestamp:Date.now(),currentScore:0,threshold:0};this.notifyAlertListeners(i)}notifyAlertListeners(e){for(let t of this.alertListeners)try{t(e)}catch{}}},R=new me;oe();q();var De=class c{actionHistory=new Map;throttledAgents=new Map;guidanceContinueGate=null;initialized=!1;db=null;persistCount=0;static KV_NAMESPACE="continue-gate-actions";static KV_KEY="snapshot";static PERSIST_INTERVAL=20;static KV_TTL=3600;async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/continue-gate");if(t&&typeof t.createContinueGate=="function"){let n=m.getFlags().continueGate;this.guidanceContinueGate=t.createContinueGate({maxConsecutiveSteps:n.maxConsecutiveRetries*10,maxReworkRatio:n.reworkRatioThreshold,checkpointIntervalSteps:25}),console.log("[ContinueGateIntegration] Guidance ContinueGate loaded")}}catch{this.guidanceContinueGate=null}try{this.db=G(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[ContinueGateIntegration] DB init failed, using memory-only:",S(e)),this.db=null}this.initialized=!0}}async loadFromKv(){if(!this.db)return;let e=await this.db.kvGet(c.KV_KEY,c.KV_NAMESPACE);if(e){for(let[n,i]of e.actionHistory)this.actionHistory.set(n,i);let t=Date.now();for(let[n,i]of e.throttledAgents)i>t&&this.throttledAgents.set(n,i);console.log("[ContinueGateIntegration] Loaded state from DB")}}async persistSnapshot(){if(this.db)try{await this.db.kvSet(c.KV_KEY,{actionHistory:Array.from(this.actionHistory.entries()).map(([e,t])=>[e,t.slice(-50)]),throttledAgents:Array.from(this.throttledAgents.entries())},c.KV_NAMESPACE,c.KV_TTL)}catch(e){console.warn("[ContinueGateIntegration] Persist failed:",S(e))}}recordAction(e){if(!F())return;let t=this.actionHistory.get(e.agentId)||[];t.push(e),t.length>100&&t.shift(),this.actionHistory.set(e.agentId,t),this.persistCount++,this.persistCount%c.PERSIST_INTERVAL===0&&this.persistSnapshot().catch(()=>{})}async evaluate(e){if(!F())return{shouldContinue:!0};await this.initialize();let t=m.getFlags().continueGate,n=this.actionHistory.get(e)||[],i=this.throttledAgents.get(e);if(i&&Date.now()<i){let s=i-Date.now();return{shouldContinue:!y(),reason:`Agent throttled for ${Math.ceil(s/1e3)}s`,throttleMs:s,escalate:!1}}let r=this.localEvaluation(e,n,t);if(this.guidanceContinueGate&&r.shouldContinue&&!r.reason)try{let s=this.calculateReworkRatio(n.slice(-10)),a={stepNumber:n.length,totalToolCalls:n.length,reworkCount:n.filter(l=>!l.success).length,coherenceScore:1-s,uncertaintyScore:s,elapsedMs:n.length>0?Date.now()-n[0].timestamp:0,lastCheckpointStep:0,totalTokensUsed:n.length*500,budgetRemaining:{tokens:Math.max(0,t.maxConsecutiveRetries*10*500-n.length*500),toolCalls:Math.max(0,t.maxConsecutiveRetries*10-n.length),timeMs:Math.max(0,t.idleTimeoutMs-(n.length>0?Date.now()-n[n.length-1].timestamp:0))},recentDecisions:[]},o=this.guidanceContinueGate.evaluateWithHistory(a);if(o.decision!=="continue")return this.mapGuidanceDecision(o,e)}catch{}return r}localEvaluation(e,t,n){if(t.length<2)return{shouldContinue:!0};let i=t.slice(-10),r=this.countConsecutiveIdentical(i);if(r>=n.maxConsecutiveRetries){let l=Math.min(r*1e3,3e4);return n.throttleOnExceed&&this.throttledAgents.set(e,Date.now()+l),this.logViolation(e,"consecutive_identical_actions",r),{shouldContinue:!y(),reason:`Agent exceeded max consecutive retries (${r}/${n.maxConsecutiveRetries})`,throttleMs:l,escalate:r>=n.maxConsecutiveRetries*2,consecutiveCount:r}}let s=this.calculateReworkRatio(i);if(s>n.reworkRatioThreshold)return n.throttleOnExceed&&this.throttledAgents.set(e,Date.now()+5e3),this.logViolation(e,"high_rework_ratio",s),{shouldContinue:!y(),reason:`Agent rework ratio too high (${(s*100).toFixed(1)}% > ${n.reworkRatioThreshold*100}%)`,throttleMs:5e3,escalate:s>.8,reworkRatio:s};let a=t[t.length-1],o=Date.now()-a.timestamp;return o>n.idleTimeoutMs?(this.logViolation(e,"idle_timeout",o),{shouldContinue:!y(),reason:`Agent idle for ${Math.ceil(o/1e3)}s (limit: ${n.idleTimeoutMs/1e3}s)`,escalate:!0}):{shouldContinue:!0}}countConsecutiveIdentical(e){if(e.length===0)return 0;let t=1,n=e[e.length-1].actionHash;for(let i=e.length-2;i>=0&&e[i].actionHash===n;i--)t++;return t}calculateReworkRatio(e){return e.length===0?0:e.filter(n=>!n.success).length/e.length}mapGuidanceDecision(e,t){let n=m.getFlags().continueGate,i=e.decision==="continue"||e.decision==="checkpoint",r=e.reasons.length>0?e.reasons.join("; "):void 0;if(!i&&n.throttleOnExceed){let s=e.decision==="stop"?3e4:e.decision==="pause"?15e3:5e3;this.throttledAgents.set(t,Date.now()+s)}return{shouldContinue:i,reason:r,throttleMs:e.decision==="throttle"?5e3:e.decision==="pause"?15e3:e.decision==="stop"?3e4:void 0,escalate:e.decision==="stop"||e.decision==="pause",reworkRatio:e.metrics.reworkRatio}}logViolation(e,t,n){m.getFlags().global.logViolations&&console.warn("[ContinueGate] Violation detected:",{agentId:e,violationType:t,value:n,timestamp:new Date().toISOString()})}clearThrottle(e){this.throttledAgents.delete(e)}clearHistory(e){this.actionHistory.delete(e),this.throttledAgents.delete(e)}getAgentStats(e){let t=this.actionHistory.get(e)||[],n=this.throttledAgents.get(e)||0,i=Date.now();return{actionCount:t.length,reworkRatio:this.calculateReworkRatio(t),isThrottled:n>i,throttleRemainingMs:Math.max(0,n-i)}}reset(){this.actionHistory.clear(),this.throttledAgents.clear()}},E=new De;function dt(c,e,t){let n=JSON.stringify({actionType:c,target:e,params:t}),i=0;for(let r=0;r<n.length;r++){let s=n.charCodeAt(r);i=(i<<5)-i+s,i=i&i}return i.toString(16)}function he(c,e,t,n,i){return{agentId:c,actionType:e,actionHash:dt(e,t,n),timestamp:Date.now(),success:i}}import{randomUUID as mt}from"node:crypto";var Ke={low:0,medium:.3,high:.5,critical:.7},ge=class{agentMetrics=new Map;taskHistory=new Map;tierThresholds={...Ke};guidanceTrustSystem=null;initialized=!1;async initialize(){if(!this.initialized){try{let t=await import("@claude-flow/guidance/trust");t&&typeof t.createTrustSystem=="function"&&(this.guidanceTrustSystem=t.createTrustSystem({initialTrust:.7,allowDelta:.02,denyDelta:.05,warnDelta:.01,decayRate:.05,decayIntervalMs:3e5}),console.log("[TrustAccumulatorIntegration] Guidance TrustSystem loaded"))}catch{this.guidanceTrustSystem=null}this.initialized=!0}}recordTaskOutcome(e,t,n,i,r={}){if(!x())return;let s={taskId:`${e}-${Date.now()}`,taskType:t,success:n,durationMs:i,qualityScore:r.qualityScore,timestamp:Date.now(),errorType:r.errorType},a=this.taskHistory.get(e)||[];if(a.push(s),a.length>100&&a.shift(),this.taskHistory.set(e,a),this.updateAgentMetrics(e,s),this.guidanceTrustSystem)try{let l=n?"allow":"deny";this.guidanceTrustSystem.recordOutcome(e,l,`Task ${t}: ${n?"success":"failure"}`)}catch{}m.getFlags().trustAccumulator.autoTierAdjustment&&this.adjustTier(e)}getTrustScore(e){if(!x())return .7;let t=this.agentMetrics.get(e);return t?t.trustScore:.7}getTrustTier(e){if(!x())return"medium";let t=this.agentMetrics.get(e);return t?t.trustTier:"medium"}canHandleCriticalTask(e){if(!x())return!0;let t=m.getFlags().trustAccumulator;return this.getTrustScore(e)>=t.minTrustForCritical}getAgentMetrics(e){return x()&&this.agentMetrics.get(e)||null}selectBestAgent(e,t,n={}){if(!x()||t.length===0)return{selectedAgent:t[0]||null,confidence:.5,reason:"TrustAccumulator disabled or no agents available",alternatives:[]};let i=m.getFlags().trustAccumulator,r=n.requireCriticalTrust?i.minTrustForCritical:n.minTrustScore??0,s=t.map(l=>{let u=this.agentMetrics.get(l),d=this.calculateAgentScore(l,e,u);return{agentId:l,score:d,trustScore:u?.trustScore??.7,meetsMinTrust:(u?.trustScore??.7)>=r}}).filter(l=>l.meetsMinTrust).sort((l,u)=>u.score-l.score);if(s.length===0){if(y())return{selectedAgent:null,confidence:0,reason:`No agents meet minimum trust threshold (${r})`,alternatives:t.map(u=>({agentId:u,trustScore:this.getTrustScore(u),reason:"Trust score below threshold"}))};let l=t.map(u=>({agentId:u,score:this.calculateAgentScore(u,e,this.agentMetrics.get(u)),trustScore:this.getTrustScore(u)})).sort((u,d)=>d.score-u.score);return{selectedAgent:l[0]?.agentId||null,confidence:.3,reason:"No agents meet trust threshold, selected best available (non-strict mode)",alternatives:l.slice(1).map(u=>({agentId:u.agentId,trustScore:u.trustScore,reason:`Score: ${u.score.toFixed(3)}`}))}}let a=s[0],o=Math.min(1,a.score*1.2);return{selectedAgent:a.agentId,confidence:o,reason:`Selected based on combined score (trust: ${a.trustScore.toFixed(3)}, task fit: ${(a.score-a.trustScore*i.performanceWeight).toFixed(3)})`,alternatives:s.slice(1,4).map(l=>({agentId:l.agentId,trustScore:l.trustScore,reason:`Score: ${l.score.toFixed(3)}`}))}}adjustTier(e){if(!x())return;let t=this.agentMetrics.get(e);if(!t)return;let n=t.trustTier,i=this.calculateTier(t.trustScore);n!==i&&(t.trustTier=i,t.tierHistory.push({tier:i,timestamp:Date.now(),reason:`Trust score changed to ${t.trustScore.toFixed(3)}`}),t.tierHistory.length>20&&t.tierHistory.shift(),this.logTierChange(e,n,i,t.trustScore))}boostTrust(e,t,n){if(!x())return;let i=this.getOrCreateMetrics(e),r=i.trustScore;i.trustScore=Math.min(1,i.trustScore+t),i.lastUpdated=Date.now(),this.logTrustChange(e,r,i.trustScore,`Boost: ${n}`),m.getFlags().trustAccumulator.autoTierAdjustment&&this.adjustTier(e)}penalizeTrust(e,t,n){if(!x())return;let i=this.getOrCreateMetrics(e),r=i.trustScore;i.trustScore=Math.max(0,i.trustScore-t),i.lastUpdated=Date.now(),this.logTrustChange(e,r,i.trustScore,`Penalty: ${n}`),m.getFlags().trustAccumulator.autoTierAdjustment&&this.adjustTier(e)}getAllAgentMetrics(){return Array.from(this.agentMetrics.values())}getAgentsByTier(e){return Array.from(this.agentMetrics.entries()).filter(([t,n])=>n.trustTier===e).map(([t])=>t)}getTaskExperience(e){return this.agentMetrics.get(e)?.taskTypeExperience??new Map}setTierThresholds(e){this.tierThresholds={...this.tierThresholds,...e};for(let t of Array.from(this.agentMetrics.keys()))this.adjustTier(t)}reset(){this.agentMetrics.clear(),this.taskHistory.clear(),this.tierThresholds={...Ke}}resetAgent(e){this.agentMetrics.delete(e),this.taskHistory.delete(e)}updateAgentMetrics(e,t){let n=this.getOrCreateMetrics(e);n.totalTasks++,t.success&&n.successfulTasks++,n.successRate=n.successfulTasks/n.totalTasks;let i=.3,r=t.success?0:1,s=1-n.successRate;n.errorRate=i*r+(1-i)*s,n.totalTasks===1?n.avgDurationMs=t.durationMs:n.avgDurationMs=i*t.durationMs+(1-i)*n.avgDurationMs;let a=n.taskTypeExperience.get(t.taskType)||0;n.taskTypeExperience.set(t.taskType,a+1),this.recalculateTrustScore(n,t),n.lastUpdated=Date.now()}recalculateTrustScore(e,t){let n=m.getFlags().trustAccumulator,i=e.successRate,r=e.taskTypeExperience.get(t.taskType)||0,a=Math.min(1,r/20),o=t.qualityScore??(t.success?.7:.3),l=1-e.errorRate,u=(o+l)/2,d=n.performanceWeight*i+n.taskSimilarityWeight*a+n.capabilityMatchWeight*u;e.totalTasks===1?e.trustScore=d:e.trustScore=.2*d+(1-.2)*e.trustScore,e.trustScore=Math.max(0,Math.min(1,e.trustScore))}calculateAgentScore(e,t,n){let i=m.getFlags().trustAccumulator;if(!n)return .7*i.performanceWeight;let r=n.trustScore*i.performanceWeight,s=n.taskTypeExperience.get(t)||0,o=Math.min(.3,s*.03)*i.taskSimilarityWeight,l=(1-n.errorRate)*i.capabilityMatchWeight;return r+o+l}calculateTier(e){return e>=this.tierThresholds.critical?"critical":e>=this.tierThresholds.high?"high":e>=this.tierThresholds.medium?"medium":"low"}getOrCreateMetrics(e){let t=this.agentMetrics.get(e);return t||(t={agentId:e,trustScore:.7,trustTier:"high",totalTasks:0,successfulTasks:0,successRate:0,avgDurationMs:0,errorRate:0,taskTypeExperience:new Map,lastUpdated:Date.now(),tierHistory:[{tier:"high",timestamp:Date.now(),reason:"Initial tier assignment"}]},this.agentMetrics.set(e,t)),t}logTrustChange(e,t,n,i){m.getFlags().global.logViolations&&console.warn("[TrustAccumulator] Trust change:",{agentId:e,oldScore:t.toFixed(3),newScore:n.toFixed(3),change:(n-t).toFixed(3),reason:i,timestamp:new Date().toISOString()})}logTierChange(e,t,n,i){if(!m.getFlags().global.logViolations)return;let r=this.compareTiers(n,t)>0?"PROMOTED":"DEMOTED";console.warn(`[TrustAccumulator] Tier change (${r}):`,{agentId:e,oldTier:t,newTier:n,trustScore:i.toFixed(3),timestamp:new Date().toISOString()})}compareTiers(e,t){let n={low:0,medium:1,high:2,critical:3};return n[e]-n[t]}},Ve=new ge;var ht=[{name:"ignore-instructions",category:"prompt-injection",pattern:/ignore\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|rules?|guidelines?|prompts?)/i,severity:.9,description:"Attempts to override previous instructions",enabled:!0},{name:"system-prompt-override",category:"prompt-injection",pattern:/\[?(system|admin|root|sudo)\]?\s*[:>]\s*.{0,50}(override|bypass|ignore|forget|reset)/i,severity:.95,description:"Attempts to impersonate system prompt",enabled:!0},{name:"new-instructions",category:"prompt-injection",pattern:/your\s+(new|real|actual|true)\s+(instructions?|task|purpose|goal)\s+(are?|is)/i,severity:.85,description:"Attempts to redefine agent instructions",enabled:!0},{name:"disregard-previous",category:"prompt-injection",pattern:/(disregard|forget|omit|skip|delete)\s+(everything|all|anything)\s+(above|before|previous)/i,severity:.9,description:"Attempts to clear context",enabled:!0},{name:"prompt-leak",category:"prompt-injection",pattern:/(show|reveal|display|output|print|echo)\s+(your|the|my)?\s*(system\s*)?(prompt|instructions?|rules?|config)/i,severity:.8,description:"Attempts to extract system prompt",enabled:!0},{name:"dan-jailbreak",category:"jailbreak",pattern:/\b(DAN|do\s*anything\s*now|jailbreak|unrestricted|unfiltered)\b/i,severity:.95,description:"Known jailbreak attempt (DAN/unrestricted mode)",enabled:!0},{name:"developer-mode",category:"jailbreak",pattern:/(developer|debug|maintenance|test)\s*mode\s*(enabled?|on|active|activate)/i,severity:.9,description:"Attempts to enable developer/debug mode",enabled:!0},{name:"hypothetical-bypass",category:"jailbreak",pattern:/(hypothetically|in\s+theory|imagine\s+if|let's\s+say|what\s+if).{0,50}(no\s+rules?|no\s+restrictions?|anything|everything)/i,severity:.7,description:"Hypothetical scenario to bypass restrictions",enabled:!0},{name:"roleplay-bypass",category:"jailbreak",pattern:/(roleplay|role-play|pretend|act)\s*(as|like|that).{0,30}(no|without)\s*(restrictions?|limits?|rules?|ethics?)/i,severity:.85,description:"Roleplay scenario to bypass ethics",enabled:!0},{name:"pretend-you-are",category:"role-manipulation",pattern:/(pretend|imagine|act|behave)\s+(you\s+are|as\s+if\s+you're|like\s+you're|that\s+you're)/i,severity:.6,description:"Attempts to change agent identity",enabled:!0},{name:"you-are-now",category:"role-manipulation",pattern:/you\s+are\s+now\s+(a|an|the)?\s*[a-z]+/i,severity:.65,description:"Direct role reassignment attempt",enabled:!0},{name:"from-now-on",category:"role-manipulation",pattern:/from\s+now\s+on\s*(,\s*)?(you|your)\s+(will|are|should|must|have\s+to)/i,severity:.7,description:"Attempts to change future behavior",enabled:!0},{name:"persona-switch",category:"role-manipulation",pattern:/(switch|change|transform)\s*(to|into)\s*(a|an)?\s*(different|new|another)\s*(persona|character|role|identity)/i,severity:.75,description:"Attempts to switch persona",enabled:!0},{name:"api-key-request",category:"data-exfiltration",pattern:/(show|reveal|give|tell|output|display|print)\s*(me\s*)?(your|the|any)?\s*(api|access|secret)?\s*key/i,severity:.85,description:"Attempts to extract API keys",enabled:!0},{name:"credential-request",category:"data-exfiltration",pattern:/(show|reveal|give|tell|output)\s*(me\s*)?(the|your|any)?\s*(credentials?|passwords?|tokens?|secrets?)/i,severity:.9,description:"Attempts to extract credentials",enabled:!0},{name:"environment-dump",category:"data-exfiltration",pattern:/(dump|print|show|list|output)\s*(all\s*)?(environment|env)\s*(variables?)?/i,severity:.8,description:"Attempts to dump environment variables",enabled:!0},{name:"internal-state",category:"data-exfiltration",pattern:/(show|reveal|access|dump)\s*(your|the)?\s*(internal|hidden|private)\s*(state|data|memory|context)/i,severity:.75,description:"Attempts to access internal state",enabled:!0},{name:"shell-command",category:"command-injection",pattern:/[;\|\&`]\s*(rm|cat|wget|curl|nc|bash|sh|python|perl|ruby|eval|exec)\s+/i,severity:.95,description:"Shell command injection attempt",enabled:!0},{name:"sql-injection",category:"command-injection",pattern:/(['";]\s*(or|and|union|select|drop|delete|insert|update)\s+)/i,severity:.9,description:"SQL injection attempt",enabled:!0},{name:"path-traversal",category:"command-injection",pattern:/\.\.[\/\\]+/,severity:.7,description:"Path traversal attempt",enabled:!0},{name:"code-execution",category:"command-injection",pattern:/(eval|exec|system|popen|subprocess)\s*\(/i,severity:.85,description:"Code execution function call",enabled:!0},{name:"base64-encoded",category:"encoded-payload",pattern:/[A-Za-z0-9+\/]{50,}={0,2}/,severity:.5,description:"Potential base64 encoded payload",enabled:!0},{name:"unicode-escape",category:"encoded-payload",pattern:/(\\u[0-9a-fA-F]{4}){4,}/,severity:.6,description:"Unicode escape sequence (potential obfuscation)",enabled:!0},{name:"hex-encoded",category:"encoded-payload",pattern:/(\\x[0-9a-fA-F]{2}){8,}/,severity:.65,description:"Hex-encoded data (potential obfuscation)",enabled:!0},{name:"url-encoded",category:"encoded-payload",pattern:/(%[0-9a-fA-F]{2}){5,}/,severity:.55,description:"URL-encoded sequence (potential obfuscation)",enabled:!0}],pe=class{patterns=new Map;blocklist=new Map;stats=this.createEmptyStats();assessmentHistory=[];guidanceThreatDetector=null;guidanceCollusionDetector=null;initialized=!1;async initialize(){if(!this.initialized){for(let e of ht)this.patterns.set(e.name,e);this.initialized=!0;try{let t=await import("@claude-flow/guidance/adversarial");t&&typeof t.createThreatDetector=="function"&&(this.guidanceThreatDetector=t.createThreatDetector(),console.log("[AdversarialDefense] Guidance ThreatDetector loaded")),t&&typeof t.createCollusionDetector=="function"&&(this.guidanceCollusionDetector=t.createCollusionDetector(),console.log("[AdversarialDefense] Guidance CollusionDetector loaded"))}catch{this.guidanceThreatDetector=null,this.guidanceCollusionDetector=null}}}assessThreat(e,t){if(!T())return this.createSafeAssessment(e);let n=m.getFlags().adversarialDefense,i=this.detectInjectionPatterns(e),r=this.checkBlocklist(e);if(this.guidanceThreatDetector&&i.length===0)try{let d={agentId:t?.agentId||"",toolName:t?.taskType||""},h=this.guidanceThreatDetector.analyzeInput(e,d);if(h&&Array.isArray(h)&&h.length>0)for(let g of h)i.push({name:`guidance:${g.category||"unknown"}`,category:g.category||"custom",matched:g.description||"",position:0,severity:g.severity||.5,description:g.description||"Detected by guidance ThreatDetector"})}catch{}let s=0;if(i.length>0){let d=i.map(h=>h.severity).sort((h,g)=>g-h);s=d[0];for(let h=1;h<d.length;h++)s+=d[h]*Math.pow(.5,h);s=Math.min(1,s)}r.length>0&&(s=Math.min(1,s+.3));let a=this.shouldBlock({threatScore:s,detectedPatterns:i.map(d=>d.name),isBlocked:!1,recommendations:[],timestamp:Date.now(),assessmentId:""}),o=this.generateRecommendations(i,s,a),l;n.sanitizeInputs&&!a&&(l=this.sanitizeInput(e));let u={threatScore:s,detectedPatterns:i.map(d=>d.name),isBlocked:a,sanitizedInput:l,recommendations:o,timestamp:Date.now(),assessmentId:`assess-${mt()}`};return this.updateStats(u,i),this.assessmentHistory.push(u),this.assessmentHistory.length>1e3&&this.assessmentHistory.shift(),n.penalizeOnDetection&&t?.agentId&&i.length>0&&this.penalizeAgent(t.agentId,u),n.logDetections&&i.length>0&&this.logDetection(u,t),u}detectInjectionPatterns(e){if(!T())return[];let t=[],n=e.toLowerCase();for(let[i,r]of this.patterns){if(!r.enabled)continue;let s=r.pattern.exec(e)||r.pattern.exec(n);s&&(t.push({name:r.name,category:r.category,matched:s[0],position:s.index,severity:r.severity,description:r.description}),this.stats.patternMatchCounts[i]=(this.stats.patternMatchCounts[i]||0)+1)}return t}sanitizeInput(e){if(!T())return e;let t=e;for(let[i,r]of this.patterns)r.enabled&&r.severity>=.8&&(t=t.replace(r.pattern,"[REDACTED]"));t=t.replace(/[;\|\&`$]/g,""),t=t.replace(/\s{3,}/g," ");let n=1e4;return t.length>n&&(t=t.substring(0,n)+"...[TRUNCATED]"),this.stats.sanitizedInputs++,t}escapeSpecialCharacters(e){return e.replace(/[;&|`$]/g,t=>`\\${t}`).replace(/[']/g,"''").replace(/(?<!\\)\\/g,"\\\\")}shouldBlock(e){if(!T())return!1;let t=m.getFlags().adversarialDefense;return!!(e.threatScore>=t.blockThreshold||y()&&e.threatScore>=t.blockThreshold*.7)}addToBlocklist(e,t){T()&&this.blocklist.set(e.toLowerCase(),{pattern:e,reason:t,addedAt:Date.now(),matchCount:0})}removeFromBlocklist(e){this.blocklist.delete(e.toLowerCase())}checkBlocklist(e){let t=[],n=e.toLowerCase();for(let[i,r]of this.blocklist)n.includes(i)&&(r.matchCount++,t.push(r));return t}recordAgentInteraction(e,t,n){if(T()&&this.guidanceCollusionDetector)try{this.guidanceCollusionDetector.recordInteraction(e,t,n)}catch{}}detectCollusion(){if(!T())return null;if(this.guidanceCollusionDetector)try{return this.guidanceCollusionDetector.detectCollusion()}catch{}return null}penalizeAgent(e,t){if(!T())return;let i=.05+t.threatScore*.15;Ve.penalizeTrust(e,i,`Adversarial input detected: ${t.detectedPatterns.join(", ")} (score: ${t.threatScore.toFixed(2)})`),this.stats.agentPenalties++}addCustomPattern(e){let t={...e,category:e.category||"custom"};this.patterns.set(e.name,t)}removePattern(e){return this.patterns.delete(e)}setPatternEnabled(e,t){let n=this.patterns.get(e);return n?(n.enabled=t,!0):!1}getPattern(e){return this.patterns.get(e)}getAllPatterns(){return Array.from(this.patterns.values())}getPatternStats(){let e=Array.from(this.patterns.values()),t={"prompt-injection":0,jailbreak:0,"role-manipulation":0,"data-exfiltration":0,"command-injection":0,"encoded-payload":0,custom:0},n=0,i=0,r=0;for(let s of e)t[s.category]++,s.enabled?n++:i++,s.category==="custom"&&r++;return{totalPatterns:e.length,patternsByCategory:t,enabledPatterns:n,disabledPatterns:i,customPatterns:r}}getDefenseStats(){return{...this.stats}}getBlocklist(){return Array.from(this.blocklist.values())}getAssessmentHistory(e=100){return this.assessmentHistory.slice(-e)}reset(){this.patterns.clear(),this.blocklist.clear(),this.assessmentHistory=[],this.stats=this.createEmptyStats(),this.initialized=!1}resetStats(){this.stats=this.createEmptyStats()}createEmptyStats(){return{totalAssessments:0,blockedInputs:0,sanitizedInputs:0,averageThreatScore:0,patternMatchCounts:{},categoryBreakdown:{"prompt-injection":0,jailbreak:0,"role-manipulation":0,"data-exfiltration":0,"command-injection":0,"encoded-payload":0,custom:0},agentPenalties:0,lastAssessment:null}}createSafeAssessment(e){return{threatScore:0,detectedPatterns:[],isBlocked:!1,sanitizedInput:e,recommendations:[],timestamp:Date.now(),assessmentId:`safe-${Date.now()}`}}updateStats(e,t){this.stats.totalAssessments++,e.isBlocked&&this.stats.blockedInputs++;let n=this.stats.totalAssessments;this.stats.averageThreatScore=(this.stats.averageThreatScore*(n-1)+e.threatScore)/n;for(let i of t)this.stats.categoryBreakdown[i.category]++;this.stats.lastAssessment=e.timestamp}generateRecommendations(e,t,n){let i=[];if(n&&(i.push("Input blocked due to high threat score"),i.push("Review input source and sanitize before retry")),t>=.7&&(i.push("Consider additional input validation"),i.push("Log this attempt for security review")),e.length>0){let r=new Set(e.map(s=>s.category));r.has("prompt-injection")&&(i.push("Implement input boundary markers"),i.push("Use separate instruction and data channels")),r.has("jailbreak")&&(i.push("Monitor for repeated jailbreak attempts"),i.push("Consider rate limiting this user")),r.has("role-manipulation")&&(i.push("Validate agent identity constraints"),i.push("Prevent role switching via user input")),r.has("command-injection")&&(i.push("Never pass user input directly to command execution"),i.push("Use parameterized commands or allowlists")),r.has("data-exfiltration")&&(i.push("Audit access to sensitive data"),i.push("Implement principle of least privilege")),r.has("encoded-payload")&&(i.push("Decode and validate payloads before processing"),i.push("Consider rejecting deeply encoded inputs")),i.length===0&&i.push("Review input for potential security issues")}return i}logDetection(e,t){m.getFlags().global.logViolations&&console.warn("[AdversarialDefense] Threat detected:",{assessmentId:e.assessmentId,threatScore:e.threatScore.toFixed(3),patterns:e.detectedPatterns,isBlocked:e.isBlocked,agentId:t?.agentId,taskType:t?.taskType,source:t?.source,timestamp:new Date().toISOString()})}},O=new pe;O.initialize().catch(()=>{});function fe(c){return O.initialized||O.initialize(),O.assessThreat(c)}function Ge(c){return O.initialized||O.initialize(),O.sanitizeInput(c)}import*as ie from"fs";import*as J from"path";var Qe={enabled:!0,strictEnforcement:!1,escalateViolations:!0,constitutionPath:".claude/guidance/constitution.md",logAllChecks:!0},ye=class{invariants=new Map;initialized=!1;constitutionLoaded=!1;flags;stats={totalChecks:0,passedChecks:0,failedChecks:0,blockedViolations:0,escalations:0,checksByInvariant:{},lastCheckTimestamp:null,passRate:1};escalationCallbacks=new Set;gateIntegrations=new Map;constructor(e){this.flags={...Qe,...e}}async initialize(){if(!this.initialized){this.loadDefaultInvariants();try{await this.loadConstitution()}catch{this.flags.logAllChecks&&console.warn("[ConstitutionalEnforcer] Could not load constitution file, using defaults")}this.initialized=!0}}isInitialized(){return this.initialized}loadDefaultInvariants(){let e=[{id:"test-execution-integrity",name:"Test Execution Integrity",description:"Claims of test success require execution proof",condition:"IF task.claims_tests_passed THEN EXISTS execution_proof",enforcement:"ContinueGate blocks claims without execution proof",enabled:!0},{id:"security-scan-required",name:"Security Scan Requirement",description:"Auth/security code changes require security scan",condition:"IF change.affects_auth_code THEN EXISTS security_scan WITH status=complete AND critical_vulnerabilities=0",enforcement:"Quality gates block deployment without security scan",enabled:!0},{id:"backup-before-delete",name:"Backup Before Delete",description:"Destructive operations require verified backup",condition:"IF operation.type=delete AND target IN protected_files THEN EXISTS backup.verified=true",enforcement:"MemoryWriteGate blocks destructive operations without backup",enabled:!0},{id:"loop-detection",name:"Loop Detection",description:"Agents must not exceed retry or rework limits",condition:"agent.consecutive_identical_actions < 3 AND agent.rework_ratio < 0.5",enforcement:"ContinueGate throttles or blocks agents exceeding limits",enabled:!0},{id:"budget-enforcement",name:"Budget Enforcement",description:"Sessions must not exceed budget limits",condition:"session.total_cost <= budget_limit AND session.token_usage <= token_limit",enforcement:"BudgetMeter blocks operations exceeding budget",enabled:!0},{id:"memory-consistency",name:"Memory Consistency",description:"No contradictory patterns without supersession",condition:"NOT EXISTS conflicting_pattern WHERE supersession_marker IS NULL",enforcement:"MemoryWriteGate blocks contradictory patterns",enabled:!0},{id:"verification-before-claim",name:"Verification Before Claim",description:"All success claims require verification proof",condition:"FOR ALL claim IN success_claims: EXISTS verification.result=passed",enforcement:"All success claims require proof of verification",enabled:!0}];for(let t of e)this.invariants.set(t.id,t),this.stats.checksByInvariant[t.id]={passed:0,failed:0}}async loadConstitution(e){let t=e||this.flags.constitutionPath,n=t;if(!J.isAbsolute(t)){let r=[J.join(process.cwd(),t),J.join(process.cwd(),"..",t),J.join(process.cwd(),"../..",t)];for(let s of r)if(ie.existsSync(s)){n=s;break}}if(!ie.existsSync(n))throw new Error(`Constitution file not found: ${n}`);let i=ie.readFileSync(n,"utf-8");this.parseConstitution(i),this.constitutionLoaded=!0}parseConstitution(e){let t=/### Invariant (\d+): ([^\n]+)\n+```\n([\s\S]*?)```\n+\*\*Enforcement\*\*: ([^\n]+)/g,n;for(;(n=t.exec(e))!==null;){let[,i,r,s,a]=n,o=this.generateInvariantId(r),l=this.invariants.get(o);l&&(l.condition=s.trim(),l.enforcement=a.trim())}}generateInvariantId(e){return e.toLowerCase().replace(/\s+/g,"-")}getInvariants(){return Array.from(this.invariants.values())}getInvariant(e){return this.invariants.get(e)||null}setInvariantEnabled(e,t){let n=this.invariants.get(e);n&&(n.enabled=t)}checkInvariant(e,t){let n=this.invariants.get(e);if(!n)return this.createCheck(e,!1,t,`Unknown invariant: ${e}`);if(!n.enabled)return this.createCheck(e,!0,t);switch(e){case"test-execution-integrity":return this.checkTestExecutionIntegrity(t.taskId,t.claimsTestsPassed,t.executionProof);case"security-scan-required":return this.checkSecurityScanRequirement(t.changeId,t.affectsAuthCode,t.securityScan);case"backup-before-delete":return this.checkBackupBeforeDelete(t.operation,t.backup);case"loop-detection":return this.checkLoopDetection(t.agentId,t.stats);case"budget-enforcement":return this.checkBudgetEnforcement(t.sessionCost,t.sessionTokens);case"memory-consistency":return this.checkMemoryConsistency(t.pattern,t.existingPatterns);case"verification-before-claim":return this.checkVerificationBeforeClaim(t.claimId,t.verification);default:return this.createCheck(e,!0,t)}}checkAllInvariants(e){let t=[];for(let n of this.invariants.values())if(n.enabled){let i=this.checkInvariant(n.id,e);t.push(i)}return t}checkTestExecutionIntegrity(e,t,n){let i={taskId:e,claimsTestsPassed:t,hasProof:!!n};return t?n?n.taskId!==e?this.createCheck("test-execution-integrity",!1,i,`Execution proof task_id (${n.taskId}) does not match claim task_id (${e})`,"Ensure execution proof is for the correct task"):n.allTestsExecuted?n.timestamp?this.createCheck("test-execution-integrity",!0,i):this.createCheck("test-execution-integrity",!1,i,"Execution proof missing timestamp","Include timestamp in execution proof"):this.createCheck("test-execution-integrity",!1,i,"Execution proof indicates not all tests were executed","Execute all tests before claiming success"):this.createCheck("test-execution-integrity",!1,i,"Test success claimed without execution proof","Provide ExecutionProof with task_id matching the claim and all_tests_executed=true"):this.createCheck("test-execution-integrity",!0,i)}checkSecurityScanRequirement(e,t,n){let i={changeId:e,affectsAuthCode:t,hasScan:!!n};return t?n?n.changeId!==e?this.createCheck("security-scan-required",!1,i,`Security scan change_id (${n.changeId}) does not match (${e})`,"Ensure security scan is for the correct change"):n.status!=="complete"?this.createCheck("security-scan-required",!1,i,`Security scan status is ${n.status}, not complete`,"Wait for security scan to complete"):n.criticalVulnerabilities>0?this.createCheck("security-scan-required",!1,i,`Security scan found ${n.criticalVulnerabilities} critical vulnerabilities`,"Fix all critical vulnerabilities before deploying"):this.createCheck("security-scan-required",!0,i):this.createCheck("security-scan-required",!1,i,"Auth/security code change without security scan","Run security scan before deploying auth-related changes"):this.createCheck("security-scan-required",!0,i)}checkBackupBeforeDelete(e,t){let n={operation:e,hasBackup:!!t};return!e||!e.target?this.createCheck("backup-before-delete",!0,n):["memory.db","coverage/",".db"].some(s=>e.target.includes(s))?t?t.source!==e.target?this.createCheck("backup-before-delete",!1,n,`Backup source (${t.source}) does not match delete target (${e.target})`,"Create backup for the correct target"):t.timestamp>=e.timestamp?this.createCheck("backup-before-delete",!1,n,"Backup timestamp is after operation timestamp","Create backup before starting delete operation"):t.verified?this.createCheck("backup-before-delete",!0,n):this.createCheck("backup-before-delete",!1,n,"Backup is not verified","Verify backup integrity before proceeding"):this.createCheck("backup-before-delete",!1,n,`Delete operation on protected target (${e.target}) without backup`,"Create and verify backup before deleting protected files"):this.createCheck("backup-before-delete",!0,n)}checkLoopDetection(e,t){let n={agentId:e,stats:t};if(!t)return this.createCheck("loop-detection",!0,n);let i=m.getFlags().continueGate.maxConsecutiveRetries,r=m.getFlags().continueGate.reworkRatioThreshold;return t.consecutiveIdenticalActions>=i?this.createCheck("loop-detection",!1,n,`Agent ${e} exceeded max consecutive retries (${t.consecutiveIdenticalActions}/${i})`,"Break the loop by trying a different approach or escalating"):t.reworkRatio>r?this.createCheck("loop-detection",!1,n,`Agent ${e} rework ratio too high (${(t.reworkRatio*100).toFixed(1)}% > ${r*100}%)`,"Review agent strategy or reassign task"):this.createCheck("loop-detection",!0,n)}checkBudgetEnforcement(e,t){let n={sessionCost:e,sessionTokens:t},i=m.getFlags().budgetMeter;return e>i.maxSessionCostUsd?this.createCheck("budget-enforcement",!1,n,`Session cost ($${e.toFixed(2)}) exceeds limit ($${i.maxSessionCostUsd})`,"Stop current operations or request budget increase"):t>i.maxTokensPerSession?this.createCheck("budget-enforcement",!1,n,`Session tokens (${t}) exceeds limit (${i.maxTokensPerSession})`,"Optimize token usage or request limit increase"):this.createCheck("budget-enforcement",!0,n)}checkMemoryConsistency(e,t){let n={patternKey:e?.key,domain:e?.domain};if(!e||!t)return this.createCheck("memory-consistency",!0,n);let i=t.filter(r=>r.domain===e.domain);for(let r of i)if(r.key===e.key&&!e.supersessionMarker&&JSON.stringify(r.value)!==JSON.stringify(e.value))return this.createCheck("memory-consistency",!1,{...n,conflictingPattern:r.key},`Pattern ${e.key} contradicts existing pattern without supersession marker`,"Add supersession marker to explicitly replace the old pattern");return this.createCheck("memory-consistency",!0,n)}checkVerificationBeforeClaim(e,t){let n={claimId:e,hasVerification:!!t};return t?t.claimId!==e?this.createCheck("verification-before-claim",!1,n,`Verification claim_id (${t.claimId}) does not match (${e})`,"Ensure verification is for the correct claim"):["test_execution","manual_review","automated_check"].includes(t.method)?t.result!=="passed"?this.createCheck("verification-before-claim",!1,n,`Verification result is ${t.result}, not passed`,"Cannot claim success with pending or failed verification"):this.createCheck("verification-before-claim",!0,n):this.createCheck("verification-before-claim",!1,n,`Invalid verification method: ${t.method}`,"Use one of: test_execution, manual_review, automated_check"):this.createCheck("verification-before-claim",!1,n,`Success claim ${e} made without verification`,"Provide verification through test_execution, manual_review, or automated_check")}enforceInvariant(e){let t={blocked:!1,escalated:!1};return e.passed||(this.shouldBlock(e)&&(t.blocked=!0,t.reason=e.violationDetails,this.stats.blockedViolations++,this.flags.logAllChecks&&console.warn(`[ConstitutionalEnforcer] BLOCKED: ${e.invariantId}`,{violation:e.violationDetails,context:e.context})),this.flags.escalateViolations&&(this.escalateViolation(e),t.escalated=!0,this.stats.escalations++)),t}shouldBlock(e){if(!e.passed&&(this.flags.strictEnforcement||y()))return!0;let t=["test-execution-integrity","security-scan-required","budget-enforcement"];return!!(!e.passed&&t.includes(e.invariantId))}escalateViolation(e){e.passed||(this.flags.logAllChecks&&console.warn(`[ConstitutionalEnforcer] ESCALATION: ${e.invariantId}`,{violation:e.violationDetails,recommendation:e.recommendation}),this.escalationCallbacks.forEach(t=>{try{t(e)}catch(n){console.error("[ConstitutionalEnforcer] Escalation callback error:",n)}}))}onEscalation(e){return this.escalationCallbacks.add(e),()=>this.escalationCallbacks.delete(e)}integrateWithGate(e,t){this.gateIntegrations.set(e,t)}runGateChecks(){let e=[];for(let[t,n]of this.gateIntegrations)try{let i=n();e.push(i)}catch(i){console.error(`[ConstitutionalEnforcer] Gate check error for ${t}:`,i)}return e}getEnforcementStats(){return{...this.stats,passRate:this.stats.totalChecks>0?this.stats.passedChecks/this.stats.totalChecks:1}}resetStats(){this.stats={totalChecks:0,passedChecks:0,failedChecks:0,blockedViolations:0,escalations:0,checksByInvariant:{},lastCheckTimestamp:null,passRate:1};for(let e of this.invariants.keys())this.stats.checksByInvariant[e]={passed:0,failed:0}}createCheck(e,t,n,i,r){let s={invariantId:e,passed:t,context:n,timestamp:Date.now(),violationDetails:i,recommendation:r};return this.stats.totalChecks++,this.stats.lastCheckTimestamp=s.timestamp,t?this.stats.passedChecks++:this.stats.failedChecks++,this.stats.checksByInvariant[e]||(this.stats.checksByInvariant[e]={passed:0,failed:0}),t?this.stats.checksByInvariant[e].passed++:this.stats.checksByInvariant[e].failed++,this.flags.logAllChecks&&!t&&console.warn(`[ConstitutionalEnforcer] Check failed: ${e}`,{violationDetails:i,recommendation:r}),s}getFlags(){return{...this.flags}}updateFlags(e){this.flags={...this.flags,...e}}reset(){this.invariants.clear(),this.gateIntegrations.clear(),this.escalationCallbacks.clear(),this.initialized=!1,this.constitutionLoaded=!1,this.resetStats()}},Y=new ye;var Fe=class{initialized=!1;sessionCost=0;sessionTokens=0;escalationCallbacks=new Set;async initialize(){this.initialized||(await E.initialize(),this.initialized=!0,console.log("[QueenGovernance] Initialized with flags:",{continueGate:F(),memoryWriteGate:j(),budgetMeter:le(),strictMode:y()}))}async beforeTaskExecution(e){let t={allowed:!0};if(T()&&e.payload){let i=JSON.stringify(e.payload),r=fe(i);if(t.threatAssessment=r,r.isBlocked&&(I()&&R.recordViolation({type:"adversarial_detected",severity:r.threatScore>.7?"critical":"high",agentId:e.agentId,gate:"adversarialDefense",description:`Adversarial threat detected in task ${e.taskId}: ${r.detectedPatterns.join(", ")}`,context:{taskId:e.taskId,threatScore:r.threatScore,detectedPatterns:r.detectedPatterns,domain:e.domain}}),console.warn("[QueenGovernance] Adversarial threat detected:",{taskId:e.taskId,agentId:e.agentId,threatScore:r.threatScore,patterns:r.detectedPatterns}),y()))return{allowed:!1,reason:`Adversarial threat detected: ${r.detectedPatterns.join(", ")}`,threatAssessment:r}}if(!F())return t;E.recordAction(he(e.agentId,`task:${e.taskType}`,e.domain,{taskId:e.taskId,retryCount:e.retryCount||0},!0));let n=await E.evaluate(e.agentId);if(!n.shouldContinue)return I()&&R.recordViolation({type:"loop_detected",severity:"high",agentId:e.agentId,gate:"continueGate",description:`Agent ${e.agentId} loop detected in task ${e.taskId}: ${n.reason}`,context:{taskId:e.taskId,reason:n.reason,throttleMs:n.throttleMs}}),n.escalate&&m.getFlags().global.escalateToQueen&&this.triggerEscalation(e,n.reason||"Unknown"),{...t,allowed:!1,reason:n.reason,throttleMs:n.throttleMs,escalate:n.escalate,agentStats:E.getAgentStats(e.agentId)};if(le()){let i=this.checkBudget();if(!i.allowed)return I()&&R.recordViolation({type:"budget_exceeded",severity:"high",agentId:e.agentId,gate:"budgetMeter",description:`Budget exceeded for task ${e.taskId}: ${i.reason}`,context:{taskId:e.taskId,reason:i.reason,sessionCost:this.sessionCost,sessionTokens:this.sessionTokens}}),{...t,allowed:!1,reason:i.reason}}return{...t,allowed:!0,agentStats:E.getAgentStats(e.agentId)}}async afterTaskExecution(e,t,n,i,r){if(E.recordAction(he(e.agentId,`task-result:${e.taskType}`,e.domain,{taskId:e.taskId,success:t},t)),n!==void 0&&(this.sessionCost+=n),i!==void 0&&(this.sessionTokens+=i),U()&&r){let s=r.passed>0&&r.failed===0,a=s?{taskId:e.taskId,allTestsExecuted:!0,timestamp:Date.now(),passed:r.passed,failed:r.failed,skipped:r.skipped}:void 0,o=Y.checkTestExecutionIntegrity(e.taskId,s,a);o.passed||(console.warn("[QueenGovernance] Constitutional invariant violation:",{invariantId:o.invariantId,taskId:e.taskId,violation:o.violationDetails}),I()&&R.recordViolation({type:"invariant_violated",severity:"critical",agentId:e.agentId,gate:"constitutionalEnforcer",description:`Test execution integrity violation for task ${e.taskId}: ${o.violationDetails}`,context:{taskId:e.taskId,invariantId:o.invariantId,violationDetails:o.violationDetails,recommendation:o.recommendation}}))}if(U()&&t){let s={claimId:e.taskId,method:"automated_check",result:"passed",timestamp:Date.now(),evidence:`Task ${e.taskId} completed by agent ${e.agentId}`},a=Y.checkVerificationBeforeClaim(e.taskId,s);a.passed||(console.warn("[QueenGovernance] Claim without verification:",{invariantId:a.invariantId,taskId:e.taskId,violation:a.violationDetails}),I()&&R.recordViolation({type:"invariant_violated",severity:"high",agentId:e.agentId,gate:"constitutionalEnforcer",description:`Verification-before-claim violation for task ${e.taskId}: ${a.violationDetails}`,context:{taskId:e.taskId,invariantId:a.invariantId,violationDetails:a.violationDetails}}))}!t&&(e.retryCount||0)>=2&&E.getAgentStats(e.agentId).reworkRatio>.5&&this.triggerEscalation(e,`High failure rate after ${e.retryCount} retries`)}async beforeMemoryWrite(e){if(!j())return{allowed:!0};let t=Ie(e.key,e.value,e.domain,{agentId:e.agentId,tags:e.tags,supersedes:e.supersedes});return K.evaluateWrite(t)}registerPattern(e){let t=Ie(e.key,e.value,e.domain,{agentId:e.agentId,tags:e.tags});K.registerPattern(t)}onAgentAction(e){F()&&E.recordAction(he(e.agentId,e.actionType,e.target,e.params,e.success))}validateUserInput(e,t){if(!T())return{safe:!0,sanitized:e};let n=fe(e),i=Ge(e);return n.isBlocked&&I()&&R.recordViolation({type:"adversarial_detected",severity:n.threatScore>.7?"critical":"high",agentId:t?.agentId||"unknown",gate:"adversarialDefense",description:`Adversarial input detected from ${t?.source||"user_input"}: ${n.detectedPatterns.join(", ")}`,context:{source:t?.source||"user_input",threatScore:n.threatScore,detectedPatterns:n.detectedPatterns}}),{safe:!n.isBlocked,sanitized:i,threatAssessment:n}}async checkSecurityScanRequired(e,t,n){if(!U())return{allowed:!0};let i=Y.checkSecurityScanRequirement(e,t,n);return!i.passed&&(I()&&R.recordViolation({type:"invariant_violated",severity:"critical",gate:"constitutionalEnforcer",description:`Security scan required for change ${e}: ${i.violationDetails}`,context:{invariantId:i.invariantId,changeId:e,affectsAuthCode:t,violationDetails:i.violationDetails}}),y())?{allowed:!1,reason:i.violationDetails}:{allowed:!0}}async checkBackupRequired(e,t){if(!U())return{allowed:!0};let n={type:"delete",target:e,timestamp:Date.now()},i=Y.checkBackupBeforeDelete(n,t);return!i.passed&&(I()&&R.recordViolation({type:"invariant_violated",severity:"high",gate:"constitutionalEnforcer",description:`Backup required before delete of ${e}: ${i.violationDetails}`,context:{invariantId:i.invariantId,targetPath:e,violationDetails:i.violationDetails}}),y())?{allowed:!1,reason:i.violationDetails}:{allowed:!0}}getComplianceReport(){if(!I())return null;let e=R.getComplianceStats(),t=R.getViolations(),n;return e.currentScore>=90?n="A":e.currentScore>=80?n="B":e.currentScore>=70?n="C":e.currentScore>=60?n="D":n="F",{score:e.currentScore,grade:n,violations:t}}isAgentThrottled(e){return E.getAgentStats(e).isThrottled}getThrottleRemaining(e){return E.getAgentStats(e).throttleRemainingMs}clearAgentThrottle(e){E.clearThrottle(e)}onEscalation(e){return this.escalationCallbacks.add(e),()=>this.escalationCallbacks.delete(e)}checkBudget(){let e=m.getFlags().budgetMeter;if(this.sessionCost>=e.maxSessionCostUsd)return{allowed:!y(),reason:`Session cost limit exceeded ($${this.sessionCost.toFixed(2)} >= $${e.maxSessionCostUsd})`};if(this.sessionTokens>=e.maxTokensPerSession)return{allowed:!y(),reason:`Session token limit exceeded (${this.sessionTokens} >= ${e.maxTokensPerSession})`};let t=this.sessionCost/e.maxSessionCostUsd*100,n=this.sessionTokens/e.maxTokensPerSession*100;return(t>=e.warningThresholdPercent||n>=e.warningThresholdPercent)&&console.warn(`[QueenGovernance] Budget warning: ${Math.max(t,n).toFixed(1)}% consumed`),{allowed:!0}}triggerEscalation(e,t){console.warn("[QueenGovernance] Escalation triggered:",{agentId:e.agentId,taskId:e.taskId,domain:e.domain,reason:t}),this.escalationCallbacks.forEach(n=>{try{n(e,t)}catch(i){console.error("[QueenGovernance] Escalation callback error:",i)}})}getStats(){let e=K.getStats();return{sessionCost:this.sessionCost,sessionTokens:this.sessionTokens,memoryPatterns:e.totalPatterns,patternsByDomain:e.patternsByDomain}}async applyMemoryDecay(){return K.applyTemporalDecay()}reset(){E.reset(),K.reset(),this.sessionCost=0,this.sessionTokens=0}enableStrictMode(){m.enableStrictMode()}disableAllGates(){m.disableAllGates()}},vn=new Fe;var gt=[/\(\.\*\)\+/,/\(\.\+\)\+/,/\([^)]*?\?\)\+/,/\([^)]*?\*\)\+/,/\([^)]*?\+\)\+/,/\(\[[^\]]*\]\+\)\+/,/\(\[[^\]]*\]\*\)\+/,/\(\[[^\]]*\]\?\)\+/,/\(\[[^\]]*\]\*\)\*/,/\.\*\.\*/,/\.\+\.\+/,/\(\.\|\.\)/],pt=3;function ft(c){let e=0,t=0,n=!1,i=!1;for(let r=0;r<c.length;r++){let s=c[r];if(i){i=!1;continue}if(s==="\\"){i=!0;continue}if(s==="("){n=!0;continue}if(s===")"){n=!1;let a=c[r+1];(a==="*"||a==="+"||a==="?"||a==="{")&&(t++,e=Math.max(e,t));continue}(s==="*"||s==="+"||s==="?")&&!n&&(t=1,e=Math.max(e,t))}return e}function yt(c){return[/\(\[^\\]*\]\+\)\+/,/\(\[^\\]*\]\*\)\*/,/\([^)]+\|[^)]+\)\+/,/\(\.\*\)[*+]/,/\(\.\+\)[*+]/].some(t=>t.test(c))}var Oe=class{name="regex-safety";maxComplexity;constructor(e=pt){this.maxComplexity=e}getRiskLevel(){return"high"}validate(e,t={}){let{maxLength:n=1e4,maxComplexity:i=this.maxComplexity}=t;if(e.length>n)return{valid:!1,error:`Pattern exceeds maximum length of ${n}`,riskLevel:"medium"};let r=this.isRegexSafe(e,i);return{valid:r.safe,error:r.error,riskLevel:r.safe?"none":"high"}}isRegexSafe(e,t=this.maxComplexity){let n=[];for(let r of gt)r.test(e)&&n.push(r.source);let i=ft(e);return i>t&&n.push(`Quantifier nesting depth: ${i} (max: ${t})`),yt(e)&&n.push("Exponential backtracking potential detected"),{safe:n.length===0,pattern:e,escapedPattern:this.escapeRegex(e),riskyPatterns:n,error:n.length>0?"Pattern may cause ReDoS":void 0}}escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}createSafeRegex(e,t,n=1e4){if(!this.isRegexSafe(e).safe||e.length>n)return null;try{return new RegExp(e,t)}catch{return null}}},vt=new Oe;var Je=(c,e,t)=>vt.createSafeRegex(c,e,t);function ve(){return m.getFlags().deterministicGateway??{enabled:!1,deduplicationWindowMs:5e3,cacheResultsForIdempotent:!0,validateSchemas:!0}}var _e=class{requestHistory=new Map;resultCache=new Map;toolSchemas=new Map;guidanceGateway=null;initialized=!1;async initialize(){if(!this.initialized){this.registerDefaultSchemas(),this.initialized=!0;try{let t=await import("@claude-flow/guidance/gateway");t&&typeof t.createToolGateway=="function"&&(this.guidanceGateway=t.createToolGateway(),console.log("[DeterministicGateway] Guidance ToolGateway loaded"))}catch{this.guidanceGateway=null}}}registerDefaultSchemas(){this.registerToolSchema({toolName:"memory_store",params:{key:{type:"string",required:!0,minLength:1},value:{type:"object",required:!0},namespace:{type:"string",required:!1}},isIdempotent:!0,cacheableDurationMs:6e4}),this.registerToolSchema({toolName:"memory_retrieve",params:{key:{type:"string",required:!0,minLength:1},namespace:{type:"string",required:!1}},isIdempotent:!0,cacheableDurationMs:3e4}),this.registerToolSchema({toolName:"test_execute",params:{testFiles:{type:"array",required:!0},parallel:{type:"boolean",required:!1}},isIdempotent:!1}),this.registerToolSchema({toolName:"coverage_analyze",params:{target:{type:"string",required:!0},detectGaps:{type:"boolean",required:!1}},isIdempotent:!0,cacheableDurationMs:12e4}),this.registerToolSchema({toolName:"quality_assess",params:{target:{type:"string",required:!0},metrics:{type:"array",required:!1}},isIdempotent:!0,cacheableDurationMs:6e4})}registerToolSchema(e){this.toolSchemas.set(e.toolName,e)}async beforeToolCall(e,t,n){if(!ue())return{allowed:!0};await this.initialize();let i=ve(),r=n||this.generateIdempotencyKey(e,t);if(this.cleanupExpiredEntries(),this.isDuplicate(r)){let s=this.requestHistory.get(r);return s.completed&&i.cacheResultsForIdempotent?(this.logEvent(e,"duplicate_with_cache",r),{allowed:!1,reason:"Duplicate request - returning cached result",cachedResult:s.result,isDuplicate:!0,idempotencyKey:r}):(this.logEvent(e,"duplicate_in_flight",r),{allowed:!y(),reason:"Duplicate request in-flight",isDuplicate:!0,idempotencyKey:r})}if(this.requestHistory.set(r,{idempotencyKey:r,toolName:e,params:t,timestamp:Date.now(),completed:!1}),i.validateSchemas){let s=this.validateParams(e,t);if(s.length>0)return this.logEvent(e,"validation_failed",r,s),{allowed:!y(),reason:`Schema validation failed: ${s.map(a=>a.message).join(", ")}`,validationErrors:s,idempotencyKey:r}}if(i.cacheResultsForIdempotent){let s=this.getCachedResult(r);if(s!==null)return this.logEvent(e,"cache_hit",r),{allowed:!1,reason:"Returning cached result for idempotent operation",cachedResult:s,idempotencyKey:r}}if(this.guidanceGateway&&typeof t=="object"&&t!==null)try{let s=this.guidanceGateway.evaluate(e,t);if(!s.allowed)return this.logEvent(e,"guidance_denied",r),{allowed:!y(),reason:`Guidance gateway: ${s.reason}`,idempotencyKey:r}}catch{}return{allowed:!0,idempotencyKey:r}}async afterToolCall(e,t,n){if(!ue())return;let i=ve(),r=this.requestHistory.get(n);if(r&&(r.completed=!0,r.result=t),i.cacheResultsForIdempotent){let s=this.toolSchemas.get(e);if(s?.isIdempotent){let a=s.cacheableDurationMs||6e4;this.resultCache.set(n,{result:t,timestamp:Date.now(),toolName:e,expiresAt:Date.now()+a})}}}generateIdempotencyKey(e,t){let n=JSON.stringify({toolName:e,params:t},this.sortKeys);return this.hashString(n)}isDuplicate(e){let t=ve(),n=this.requestHistory.get(e);return n?Date.now()-n.timestamp<t.deduplicationWindowMs:!1}getCachedResult(e){let t=this.resultCache.get(e);return t?Date.now()>t.expiresAt?(this.resultCache.delete(e),null):t.result:null}validateParams(e,t){let n=this.toolSchemas.get(e);if(!n)return[];let i=[],r=typeof t=="object"&&t!==null?t:{};for(let[s,a]of Object.entries(n.params)){let o=r[s],l=this.validateValue(o,a,s);i.push(...l)}return i}validateValue(e,t,n){let i=[];if(t.required&&e==null)return i.push({path:n,message:`${n} is required`,expected:t.type,received:"undefined"}),i;if(e==null)return i;let r=Array.isArray(e)?"array":typeof e;if(r!==t.type)return i.push({path:n,message:`${n} must be of type ${t.type}`,expected:t.type,received:r}),i;if(t.type==="string"&&typeof e=="string"){t.minLength!==void 0&&e.length<t.minLength&&i.push({path:n,message:`${n} must be at least ${t.minLength} characters`,expected:`minLength: ${t.minLength}`,received:`length: ${e.length}`}),t.maxLength!==void 0&&e.length>t.maxLength&&i.push({path:n,message:`${n} must be at most ${t.maxLength} characters`,expected:`maxLength: ${t.maxLength}`,received:`length: ${e.length}`});let s=t.pattern?Je(t.pattern):null;s&&!s.test(e)&&i.push({path:n,message:`${n} must match pattern ${t.pattern}`,expected:`pattern: ${t.pattern}`,received:e})}if(t.type==="number"&&typeof e=="number"&&(t.min!==void 0&&e<t.min&&i.push({path:n,message:`${n} must be at least ${t.min}`,expected:`min: ${t.min}`,received:`${e}`}),t.max!==void 0&&e>t.max&&i.push({path:n,message:`${n} must be at most ${t.max}`,expected:`max: ${t.max}`,received:`${e}`})),t.enum&&!t.enum.includes(e)&&i.push({path:n,message:`${n} must be one of: ${t.enum.join(", ")}`,expected:`enum: [${t.enum.join(", ")}]`,received:String(e)}),t.type==="array"&&Array.isArray(e)&&t.items&&e.forEach((s,a)=>{let o=this.validateValue(s,t.items,`${n}[${a}]`);i.push(...o)}),t.type==="object"&&typeof e=="object"&&t.properties){let s=e;for(let[a,o]of Object.entries(t.properties)){let l=this.validateValue(s[a],o,`${n}.${a}`);i.push(...l)}}return i}cleanupExpiredEntries(){let e=Date.now(),t=ve();for(let[n,i]of this.requestHistory){let r=e-i.timestamp;!i.completed&&r>t.deduplicationWindowMs?this.requestHistory.delete(n):i.completed&&r>t.deduplicationWindowMs*10&&this.requestHistory.delete(n)}for(let[n,i]of this.resultCache)e>i.expiresAt&&this.resultCache.delete(n)}logEvent(e,t,n,i){m.getFlags().global.logViolations&&console.info(`[DeterministicGateway] ${t}:`,{toolName:e,idempotencyKey:n.substring(0,16)+"...",eventType:t,details:i,timestamp:new Date().toISOString()})}sortKeys=(e,t)=>{if(t&&typeof t=="object"&&!Array.isArray(t)){let n={};for(let i of Object.keys(t).sort())n[i]=t[i];return n}return t};hashString(e){let t=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);t=(t<<5)-t+r,t=t&t}return`idem_${Math.abs(t).toString(16).padStart(8,"0")}`}getStats(){return{pendingRequests:[...this.requestHistory.values()].filter(t=>!t.completed).length,cachedResults:this.resultCache.size,registeredSchemas:this.toolSchemas.size,duplicatesPrevented:[...this.requestHistory.values()].filter(t=>t.completed).length}}clearCache(e){this.resultCache.delete(e),this.requestHistory.delete(e)}clearAllCaches(){this.resultCache.clear(),this.requestHistory.clear()}reset(){this.requestHistory.clear(),this.resultCache.clear(),this.toolSchemas.clear(),this.initialized=!1}getToolSchema(e){return this.toolSchemas.get(e)}isToolIdempotent(e){return this.toolSchemas.get(e)?.isIdempotent??!1}},kn=new _e;oe();q();function _(){let c=m.getFlags();return c.global.enableAllGates?c.evolutionPipeline?.enabled??!1:!1}function re(){return m.getFlags().evolutionPipeline??{enabled:!1,autoPromoteThreshold:.9,autoDemoteThreshold:.3,minSamplesForDecision:20,learningRate:.1}}var be=class c{rules=new Map;variantTests=new Map;taskOutcomes=new Map;guidanceEvolution=null;initialized=!1;db=null;persistCount=0;static NAMESPACE="rule-evolution";static TTL_SECONDS=604800;static PERSIST_INTERVAL=10;stats={autoPromotions:0,autoDemotions:0,learningOutcomes:0};TIME_WINDOWS={HOUR:3600*1e3,DAY:1440*60*1e3,WEEK:10080*60*1e3};async initialize(){if(!this.initialized){try{this.db=G(),this.db.isInitialized()||await this.db.initialize(),await this.loadFromKv()}catch(e){console.warn("[EvolutionPipeline] DB init failed, using memory-only:",S(e)),this.db=null}try{let t=await import("@claude-flow/guidance/evolution");t&&typeof t.createEvolutionPipeline=="function"&&(this.guidanceEvolution=t.createEvolutionPipeline(),console.log("[EvolutionPipeline] Guidance EvolutionPipeline loaded"))}catch{this.guidanceEvolution=null}this.initialized=!0,this.logEvent("initialize","Evolution Pipeline initialized")}}recordRuleApplication(e,t,n){if(!_())return;let i=this.getOrCreateRuleRecord(e),r={ruleId:e,context:t,success:n,timestamp:Date.now()};i.applications.push(r),this.pruneApplicationHistory(i),this.checkAutoPromotionDemotion(e),this.persistSnapshot(),this.logEvent("rule_application",`Rule ${e} applied: ${n?"success":"failure"}`)}getRuleEffectiveness(e){let t=this.rules.get(e);if(!t)return this.createEmptyEffectiveness(e);let n=Date.now(),i=t.applications,r=i.filter(p=>n-p.timestamp<this.TIME_WINDOWS.HOUR),s=i.filter(p=>n-p.timestamp<this.TIME_WINDOWS.DAY),a=i.filter(p=>n-p.timestamp<this.TIME_WINDOWS.WEEK),o=i.length,l=i.filter(p=>p.success).length,u=o>0?l/o:0,d=this.calculateWilsonConfidenceInterval(l,o,.95),h=new Map,g=this.groupBy(i,p=>p.context.domain||"unknown");for(let[p,v]of Object.entries(g)){let b=v.filter(w=>w.success).length;h.set(p,{domain:p,applications:v.length,successes:b,successRate:v.length>0?b/v.length:0})}let f=new Map,k=this.groupBy(i,p=>p.context.taskType||"unknown");for(let[p,v]of Object.entries(k)){let b=v.filter(w=>w.success).length;f.set(p,{taskType:p,applications:v.length,successes:b,successRate:v.length>0?b/v.length:0})}let C=re(),M=o>=C.minSamplesForDecision;return{ruleId:e,totalApplications:o,successfulApplications:l,successRate:u,successRate1h:this.calculateSuccessRate(r),successRate24h:this.calculateSuccessRate(s),successRate7d:this.calculateSuccessRate(a),confidenceInterval:d,isStatisticallySignificant:M,byDomain:h,byTaskType:f,promotionStatus:t.promotionStatus,lastUpdated:n}}promoteRule(e,t){if(!_())return;let n=this.getOrCreateRuleRecord(e),i=n.promotionStatus,r;switch(i){case"candidate":case"demoted":r="promoted";break;case"deprecated":r="candidate";break;default:r=i}if(r!==i){if(n.promotionStatus=r,n.promotionHistory.push({status:r,timestamp:Date.now(),reason:t}),this.guidanceEvolution)try{this.guidanceEvolution.propose({kind:"rule-promote",title:`Promote rule ${e}`,description:t,author:"aqe-evolution-pipeline",targetPath:`rules/${e}`,diff:{before:i,after:r},rationale:t,riskAssessment:{level:"low",factors:["automated-promotion"]}})}catch{}this.logEvent("rule_promotion",`Rule ${e} promoted: ${i} -> ${r}. Reason: ${t}`)}}demoteRule(e,t){if(!_())return;let n=this.getOrCreateRuleRecord(e),i=n.promotionStatus,r;switch(i){case"promoted":case"candidate":r="demoted";break;case"demoted":r="deprecated";break;default:r=i}if(r!==i){if(n.promotionStatus=r,n.promotionHistory.push({status:r,timestamp:Date.now(),reason:t}),this.guidanceEvolution)try{this.guidanceEvolution.propose({kind:"rule-remove",title:`Demote rule ${e}`,description:t,author:"aqe-evolution-pipeline",targetPath:`rules/${e}`,diff:{before:i,after:r},rationale:t,riskAssessment:{level:r==="deprecated"?"medium":"low",factors:["automated-demotion"]}})}catch{}this.logEvent("rule_demotion",`Rule ${e} demoted: ${i} -> ${r}. Reason: ${t}`)}}createVariant(e,t){if(!_())return`${e}-variant-disabled`;let n=this.rules.get(e),i=`${e}-variant-${Date.now()}`,r={ruleId:i,name:t.name||`${n?.name||e} (Variant)`,createdAt:Date.now(),promotionStatus:"variant",baseRuleId:e,applications:[],promotionHistory:[{status:"variant",timestamp:Date.now(),reason:`Variant created: ${t.changeDescription}`}]};return this.rules.set(i,r),this.logEvent("variant_created",`Variant ${i} created from ${e}: ${t.changeDescription}`),i}learnFromOutcome(e,t){if(_()){if(this.taskOutcomes.set(e,t),this.stats.learningOutcomes++,t.appliedRules&&t.appliedRules.length>0){let n={taskType:t.taskType};for(let i of t.appliedRules)this.recordRuleApplication(i,n,t.success)}if(this.taskOutcomes.size>1e4){let n=Array.from(this.taskOutcomes.entries()).sort((i,r)=>i[1].timestamp-r[1].timestamp).slice(0,1e3);for(let[i]of n)this.taskOutcomes.delete(i)}this.logEvent("learning_outcome",`Learned from task ${e}: ${t.success?"success":"failure"}`)}}suggestRuleOptimizations(){if(!_())return[];let e=[],t=re();for(let[n,i]of Array.from(this.rules.entries())){let r=this.getRuleEffectiveness(n);if(r.isStatisticallySignificant){if(r.successRate<t.autoDemoteThreshold){e.push({ruleId:n,optimizationType:"deprecation",current:r.successRate,suggested:null,reasoning:`Rule has ${(r.successRate*100).toFixed(1)}% success rate (below ${(t.autoDemoteThreshold*100).toFixed(1)}% threshold)`,estimatedImprovement:1-r.successRate,confidence:Math.min(1,r.totalApplications/100)});continue}for(let[s,a]of Array.from(r.byDomain.entries()))a.applications>=10&&a.successRate>r.successRate+.1&&e.push({ruleId:n,optimizationType:"context_restriction",current:{domain:"all"},suggested:{domain:s},reasoning:`Rule performs ${((a.successRate-r.successRate)*100).toFixed(1)}% better in ${s} domain`,estimatedImprovement:a.successRate-r.successRate,confidence:Math.min(1,a.applications/50)});for(let[s,a]of Array.from(r.byTaskType.entries()))a.applications>=10&&a.successRate>r.successRate+.1&&e.push({ruleId:n,optimizationType:"context_restriction",current:{taskType:"all"},suggested:{taskType:s},reasoning:`Rule performs ${((a.successRate-r.successRate)*100).toFixed(1)}% better for ${s} tasks`,estimatedImprovement:a.successRate-r.successRate,confidence:Math.min(1,a.applications/50)})}}return e.sort((n,i)=>i.estimatedImprovement-n.estimatedImprovement),e}registerVariantTest(e,t){if(!_())return;if(t.length<2)throw new Error("A/B test requires at least 2 variants");let n={testId:e,variants:t,startTime:Date.now(),endTime:null,results:new Map,status:"running",winner:null,significanceAchieved:!1};for(let i of t)n.results.set(i,{variantId:i,applications:0,successes:0,successRate:0,avgDurationMs:0});this.variantTests.set(e,n),this.logEvent("variant_test_registered",`A/B test ${e} registered with ${t.length} variants`)}recordVariantOutcome(e,t,n,i){if(!_())return;let r=this.variantTests.get(e);if(!r){this.logEvent("variant_test_error",`A/B test ${e} not found`);return}if(r.status!=="running"){this.logEvent("variant_test_error",`A/B test ${e} is not running (status: ${r.status})`);return}let s=r.results.get(t);if(!s){this.logEvent("variant_test_error",`Variant ${t} not found in test ${e}`);return}s.applications++,n&&s.successes++,s.successRate=s.applications>0?s.successes/s.applications:0,i!==void 0&&(s.avgDurationMs=(s.avgDurationMs*(s.applications-1)+i)/s.applications),this.checkVariantTestSignificance(r)}getWinningVariant(e){let t=this.variantTests.get(e);return t?t.winner?t.winner:t.significanceAchieved?this.determineWinner(t):null:null}getActiveTests(){return Array.from(this.variantTests.values()).filter(e=>e.status==="running")}completeVariantTest(e){let t=this.variantTests.get(e);return t?(t.status="completed",t.endTime=Date.now(),t.winner=this.determineWinner(t),t.winner&&t.significanceAchieved&&this.promoteRule(t.winner,`Won A/B test ${e}`),this.logEvent("variant_test_completed",`A/B test ${e} completed. Winner: ${t.winner||"none"}`),t):null}cancelVariantTest(e){let t=this.variantTests.get(e);t&&(t.status="cancelled",t.endTime=Date.now(),this.logEvent("variant_test_cancelled",`A/B test ${e} cancelled`))}getEvolutionStats(){let e=Array.from(this.rules.values()),t=re(),n={candidate:0,promoted:0,demoted:0,deprecated:0,variant:0,control:0},i=0,r=0,s=0,a=0;for(let u of e){n[u.promotionStatus]++;let d=this.getRuleEffectiveness(u.ruleId);d.totalApplications>0&&(a++,i+=d.successRate,d.successRate>=t.autoPromoteThreshold?r++:d.successRate<=t.autoDemoteThreshold&&s++)}let o=Array.from(this.variantTests.values()).filter(u=>u.status==="running").length,l=Array.from(this.variantTests.values()).filter(u=>u.status==="completed").length;return{totalRules:e.length,byStatus:n,activeTests:o,completedTests:l,autoPromotions:this.stats.autoPromotions,autoDemotions:this.stats.autoDemotions,learningOutcomes:this.stats.learningOutcomes,avgSuccessRate:a>0?i/a:0,aboveThreshold:r,belowThreshold:s}}getAllRules(){return Array.from(this.rules.values())}getRulesByStatus(e){return Array.from(this.rules.entries()).filter(([t,n])=>n.promotionStatus===e).map(([t])=>t)}reset(){this.rules.clear(),this.variantTests.clear(),this.taskOutcomes.clear(),this.stats={autoPromotions:0,autoDemotions:0,learningOutcomes:0},this.initialized=!1}resetRule(e){this.rules.delete(e)}async loadFromKv(){if(!this.db)return;let e=await this.db.kvGet("snapshot",c.NAMESPACE);if(e)for(let[t,n]of Object.entries(e))this.rules.set(t,n)}persistSnapshot(){if(this.db&&(this.persistCount++,this.persistCount%c.PERSIST_INTERVAL===0))try{let e=Object.fromEntries(this.rules);this.db.kvSet("snapshot",e,c.NAMESPACE,c.TTL_SECONDS).catch(()=>{})}catch(e){console.warn("[EvolutionPipeline] Persist failed:",S(e))}}getOrCreateRuleRecord(e){let t=this.rules.get(e);return t||(t={ruleId:e,name:e,createdAt:Date.now(),promotionStatus:"candidate",applications:[],promotionHistory:[{status:"candidate",timestamp:Date.now(),reason:"Initial creation"}]},this.rules.set(e,t)),t}createEmptyEffectiveness(e){return{ruleId:e,totalApplications:0,successfulApplications:0,successRate:0,successRate1h:0,successRate24h:0,successRate7d:0,confidenceInterval:{lower:0,upper:1},isStatisticallySignificant:!1,byDomain:new Map,byTaskType:new Map,promotionStatus:"candidate",lastUpdated:Date.now()}}calculateSuccessRate(e){return e.length===0?0:e.filter(n=>n.success).length/e.length}calculateWilsonConfidenceInterval(e,t,n){if(t===0)return{lower:0,upper:1};let i=n===.95?1.96:n===.99?2.576:1.645,r=e/t,s=t,a=1+i*i/s,o=r+i*i/(2*s),l=i*Math.sqrt((r*(1-r)+i*i/(4*s))/s),u=Math.max(0,(o-l)/a),d=Math.min(1,(o+l)/a);return{lower:u,upper:d}}checkAutoPromotionDemotion(e){let t=re(),n=this.getRuleEffectiveness(e);if(!n.isStatisticallySignificant)return;let i=this.rules.get(e);i&&(n.successRate>=t.autoPromoteThreshold&&i.promotionStatus!=="promoted"&&i.promotionStatus!=="variant"&&(this.promoteRule(e,`Auto-promoted: ${(n.successRate*100).toFixed(1)}% success rate >= ${(t.autoPromoteThreshold*100).toFixed(1)}% threshold`),this.stats.autoPromotions++),n.successRate<=t.autoDemoteThreshold&&i.promotionStatus!=="demoted"&&i.promotionStatus!=="deprecated"&&(this.demoteRule(e,`Auto-demoted: ${(n.successRate*100).toFixed(1)}% success rate <= ${(t.autoDemoteThreshold*100).toFixed(1)}% threshold`),this.stats.autoDemotions++))}pruneApplicationHistory(e){let i=Date.now();e.applications=e.applications.filter(r=>i-r.timestamp<2592e6),e.applications.length>1e3&&(e.applications=e.applications.slice(-1e3))}groupBy(e,t){let n={};for(let i of e){let r=t(i);n[r]||(n[r]=[]),n[r].push(i)}return n}checkVariantTestSignificance(e){let t=re(),n=Array.from(e.results.values());if(!n.every(l=>l.applications>=t.minSamplesForDecision))return;let r=n.reduce((l,u)=>l+u.applications,0),s=n.reduce((l,u)=>l+u.successes,0)/r,a=0;for(let l of n){let u=l.applications*s;if(u>0){let d=l.successes-u;a+=d*d/u}}let o=n.length===2?3.841:n.length===3?5.991:7.815;e.significanceAchieved=a>=o,e.significanceAchieved&&(e.winner=this.determineWinner(e),this.logEvent("variant_test_significant",`A/B test ${e.testId} achieved significance. Winner: ${e.winner}`))}determineWinner(e){let t=Array.from(e.results.values());if(t.length===0)return null;let n=t[0];for(let i of t)i.successRate>n.successRate&&(n=i);return n.variantId}logEvent(e,t){m.getFlags().global.logViolations&&console.info(`[EvolutionPipeline] ${e}:`,{message:t,timestamp:new Date().toISOString()})}},$=new be;import{promises as Ye}from"fs";import*as X from"path";q();var Xe={"test-generation":["test-generation","generate-tests","tdd","property-testing","test-creation","unit-test","integration-test"],"test-execution":["test-execution","run-tests","test-run","parallel-testing","flaky-detection","retry"],"coverage-analysis":["coverage-analysis","coverage","gap-detection","coverage-report","uncovered-code"],"quality-assessment":["quality-assessment","quality-gate","quality-check","deployment-decision","release-validation"],"defect-intelligence":["defect-intelligence","defect-prediction","root-cause","bug-prediction","regression-risk"],"requirements-validation":["requirements-validation","bdd","gherkin","acceptance-criteria","requirements-check"],"code-intelligence":["code-intelligence","code-analysis","complexity-analysis","dependency-analysis","code-structure"],"security-compliance":["security-compliance","security-scan","sast","dast","vulnerability","owasp","compliance"],"contract-testing":["contract-testing","api-contract","consumer-driven","pact","schema-validation"],"visual-accessibility":["visual-accessibility","accessibility","a11y","wcag","visual-regression","screenshot"],"chaos-resilience":["chaos-resilience","chaos-testing","fault-injection","resilience","load-testing","performance"],"learning-optimization":["learning-optimization","pattern-learning","knowledge-transfer","experience-learning","optimization"]},Ze={test:["test-generation","test-execution"],coverage:["coverage-analysis"],quality:["quality-assessment"],security:["security-compliance"],defect:["defect-intelligence"],bug:["defect-intelligence"],requirements:["requirements-validation"],bdd:["requirements-validation"],code:["code-intelligence"],analysis:["code-intelligence","coverage-analysis"],contract:["contract-testing"],api:["contract-testing"],accessibility:["visual-accessibility"],a11y:["visual-accessibility"],chaos:["chaos-resilience"],performance:["chaos-resilience"],learning:["learning-optimization"],pattern:["learning-optimization"],compliance:["security-compliance"],vulnerability:["security-compliance"]};function N(){let c=m.getFlags();return c.global.enableAllGates?c.shardRetriever?.enabled??!1:!1}function B(){return m.getFlags().shardRetriever??et}var et={enabled:!0,shardsPath:".claude/guidance/shards",cacheEnabled:!0,cacheTtlMs:300*1e3,maxShardsPerQuery:3,relevanceThreshold:.3},Z=class{shardCache=new Map;cacheHits=0;cacheMisses=0;lastCacheCleanup=null;parseErrors=[];guidanceRetriever=null;initialized=!1;basePath;constructor(e){this.basePath=e??process.cwd()}async initialize(){if(!this.initialized){if(!N()){this.initialized=!0;return}try{let t=await import("@claude-flow/guidance/retriever");t&&typeof t.createRetriever=="function"&&(this.guidanceRetriever=t.createRetriever(),console.log("[ShardRetrieverIntegration] Guidance ShardRetriever loaded"))}catch{this.guidanceRetriever=null}await this.loadAllShards(),this.initialized=!0}}async loadAllShards(){let e=new Map;if(!N())return e;let t=B(),n=X.resolve(this.basePath,t.shardsPath);try{let r=(await Ye.readdir(n)).filter(s=>s.endsWith(".shard.md"));for(let s of r){let a=s.replace(".shard.md","");try{let o=await this.loadShardFromFile(X.join(n,s));o&&(e.set(a,o),this.cacheShardIfEnabled(a,o))}catch(o){let l=`Failed to load shard ${s}: ${S(o)}`;this.parseErrors.push(l),this.logError(l)}}}catch(i){let r=`Failed to read shards directory: ${S(i)}`;this.parseErrors.push(r),this.logError(r)}return e}async loadShard(e){if(!N())return null;let t=this.getCachedShard(e);if(t)return this.cacheHits++,t;this.cacheMisses++;let n=B(),i=X.resolve(this.basePath,n.shardsPath),r=X.join(i,`${e}.shard.md`);try{let s=await this.loadShardFromFile(r);return s&&this.cacheShardIfEnabled(e,s),s}catch(s){return this.logError(`Failed to load shard for domain ${e}: ${S(s)}`),null}}async retrieveForTask(e,t){if(!N())return[];await this.initialize();let n=B(),i=await this.getAllCachedOrLoadedShards(),r=new Set;if(this.guidanceRetriever)try{let o=await this.guidanceRetriever.retrieve({taskDescription:`${e}: ${t.intent||""} ${(t.keywords||[]).join(" ")}`,maxShards:n.maxShardsPerQuery});if(o&&o.shards){for(let l of o.shards)if(l.shard?.rule?.domains)for(let u of l.shard.rule.domains)r.add(u)}}catch{}let s=[];for(let o of i.values()){let l=this.calculateRelevance(o,{...t,taskType:e});r.has(o.domain)&&(l=Math.min(1,l+.1)),l>=n.relevanceThreshold&&s.push({shard:o,score:l})}return s.sort((o,l)=>l.score-o.score),s.slice(0,n.maxShardsPerQuery).map(o=>o.shard)}async retrieveByIntent(e){if(!N())return[];await this.initialize();let t=B(),n=e.toLowerCase(),i=new Set;for(let[s,a]of Object.entries(Ze))n.includes(s)&&a.forEach(o=>i.add(o));for(let s of Object.keys(Xe))n.includes(s)&&i.add(s);let r=[];for(let s of i){let a=await this.loadShard(s);a&&r.push(a)}return r.slice(0,t.maxShardsPerQuery)}async retrieveByDomain(e){return N()?this.loadShard(e):null}calculateRelevance(e,t){let n=0,i={domainMatch:.4,taskTypeMatch:.25,keywordMatch:.15,intentMatch:.1,agentMatch:.1};t.domain===e.domain&&(n+=i.domainMatch);let r=Xe[e.domain]||[],s=t.taskType.toLowerCase();for(let a of r)if(s.includes(a)||a.includes(s)){n+=i.taskTypeMatch;break}if(t.keywords&&t.keywords.length>0){let a=e.rawContent.toLowerCase(),o=0;for(let l of t.keywords)a.includes(l.toLowerCase())&&o++;n+=o/t.keywords.length*i.keywordMatch}if(t.intent){let a=t.intent.toLowerCase();this.getDomainsForIntent(a).includes(e.domain)&&(n+=i.intentMatch)}return t.agentId&&[...e.agentConstraints.primary.map(o=>o.agentId),...e.agentConstraints.secondary.map(o=>o.agentId),...e.agentConstraints.support.map(o=>o.agentId)].includes(t.agentId)&&(n+=i.agentMatch),t.requiresSecurity&&e.domain==="security-compliance"&&(n+=.15),t.requiresCompliance&&e.domain==="security-compliance"&&(n+=.1),t.requiresCoverage&&e.domain==="coverage-analysis"&&(n+=.15),t.requiresLearning&&e.domain==="learning-optimization"&&(n+=.1),Math.min(1,n)}async getTopShards(e,t){if(!N())return[];await this.initialize();let n=await this.getAllCachedOrLoadedShards(),i=[];for(let r of n.values()){let s=this.calculateRelevance(r,e);i.push({shard:r,score:s})}return i.sort((r,s)=>s.score-r.score),i.slice(0,t).map(r=>r.shard)}async injectRulesForContext(e){let t={rules:[],thresholds:{},constraints:{primary:[],secondary:[],support:[],readonly:[],forbidden:[]},escalations:[],sourceDomains:[]};if(!N())return t;let n=await this.retrieveForTask(e.taskType,e);if(n.length===0)return t;let i=[],r={},s={primary:[],secondary:[],support:[],readonly:[],forbidden:[]},a=[],o=[];for(let l of n)l.rules.forEach(u=>{i.push(`[${l.domain}] ${u}`)}),Object.assign(r,l.thresholds),s.primary.push(...l.agentConstraints.primary),s.secondary.push(...l.agentConstraints.secondary),s.support.push(...l.agentConstraints.support),s.readonly.push(...l.agentConstraints.readonly),s.forbidden.push(...l.agentConstraints.forbidden),a.push(...l.escalationTriggers),o.push(l.domain);return s.primary=this.dedupeAgentRoles(s.primary),s.secondary=this.dedupeAgentRoles(s.secondary),s.support=this.dedupeAgentRoles(s.support),s.readonly=this.dedupeAgentRoles(s.readonly),s.forbidden=[...new Set(s.forbidden)],{rules:i,thresholds:r,constraints:s,escalations:a,sourceDomains:o}}getShardStats(){let e=this.shardCache,t=Array.from(e.keys());return{totalShards:12,loadedShards:e.size,domains:t,lastRefresh:e.size>0?Math.max(...Array.from(e.values()).map(n=>n.loadedAt)):null,parseErrors:[...this.parseErrors]}}getCacheStats(){let e=B(),t=this.cacheHits+this.cacheMisses;return{enabled:e.cacheEnabled,size:this.shardCache.size,hits:this.cacheHits,misses:this.cacheMisses,hitRate:t>0?this.cacheHits/t:0,lastCleanup:this.lastCacheCleanup}}clearCache(){this.shardCache.clear(),this.cacheHits=0,this.cacheMisses=0,this.lastCacheCleanup=Date.now()}reset(){this.shardCache.clear(),this.cacheHits=0,this.cacheMisses=0,this.lastCacheCleanup=null,this.parseErrors=[],this.initialized=!1}async loadShardFromFile(e){try{let t=await Ye.readFile(e,"utf-8");return t=t.replace(/\r\n/g,`
4
- `).replace(/\r/g,`
5
- `),this.parseShard(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}parseShard(e){let t=e.split(`
6
- `),n=this.extractMetadata(e,"Domain")||"unknown",i=this.extractMetadata(e,"Version")||"1.0.0",r=this.extractMetadata(e,"Last Updated")||new Date().toISOString().split("T")[0],s=this.extractMetadata(e,"Parent Constitution")||"",a=this.extractRules(e),o=this.extractThresholds(e),l=this.extractInvariants(e),u=this.extractPatterns(e),d=this.extractAgentConstraints(e),h=this.extractEscalationTriggers(e),g=this.extractMemoryNamespace(e),f=this.extractIntegrationPoints(e);return{domain:n,version:i,lastUpdated:r,parentConstitution:s,rules:a,thresholds:o,invariants:l,patterns:u,agentConstraints:d,escalationTriggers:h,memoryNamespace:g,integrationPoints:f,rawContent:e}}extractMetadata(e,t){let n=new RegExp(`\\*\\*${t}\\*\\*:\\s*(.+?)(?:\\r?\\n|$)`,"i"),i=e.match(n);return i?i[1].trim().replace(/`/g,""):null}extractRules(e){let t=[],n=this.extractSection(e,"Domain Rules");if(!n)return t;let i=/\d+\.\s+\*\*([^*]+)\*\*:\s*(.+?)(?=\n\d+\.|\n\n|$)/gs,r;for(;(r=i.exec(n))!==null;){let s=r[1].trim(),a=r[2].trim().replace(/\n/g," ");t.push(`${s}: ${a}`)}return t}extractThresholds(e){let t={},n=this.extractSection(e,"Quality Thresholds");if(!n)return t;let i=n.split(`
7
- `).filter(r=>r.includes("|")&&!r.includes("---"));for(let r=1;r<i.length;r++){let s=i[r].split("|").map(a=>a.trim()).filter(a=>a);if(s.length>=3){let a=s[0],o=this.parseThresholdValue(s[1]),l=this.parseThresholdValue(s[2]),u=s.length>3?this.parseThresholdValue(s[3]):void 0;o!==null&&l!==null&&(t[a]={minimum:o,target:l},u!=null&&(t[a].critical=u))}}return t}parseThresholdValue(e){if(!e||e==="N/A")return null;let t=e.replace(/[<>]/g,"").replace(/%/g,"").replace(/\/week/g,"").replace(/\s*secrets?/gi,"").replace(/\s*days?/gi,"").replace(/\s*\(.*?\)/g,"").trim();if(t.includes("O("))return null;let n=parseFloat(t);return isNaN(n)?null:n}extractInvariants(e){let t=[],n=this.extractSection(e,"Invariants");if(!n)return t;let i=/```[\s\S]*?INVARIANT\s+(\w+):[\s\S]*?```/g,r;for(;(r=i.exec(n))!==null;){let s=r[1],a=r[0].replace(/```/g,"").trim();t.push(a)}return t}extractPatterns(e){let t=[],n=this.extractSection(e,"Patterns");if(!n)return t;let i=n.split(`
8
- `).filter(r=>r.includes("|")&&!r.includes("---"));for(let r=1;r<i.length;r++){let s=i[r].split("|").map(a=>a.trim()).filter(a=>a);s.length>=3&&t.push({name:s[0],location:s[1].replace(/`/g,""),description:s[2]})}return t}extractAgentConstraints(e){let t={primary:[],secondary:[],support:[],readonly:[],forbidden:[]},n=this.extractSection(e,"Agent Constraints");if(!n)return t;let i=n.split(`
9
- `).filter(s=>s.includes("|")&&!s.includes("---"));for(let s=1;s<i.length;s++){let a=i[s].split("|").map(o=>o.trim()).filter(o=>o);if(a.length>=3){let o=a[0].toLowerCase().replace(/\*\*/g,""),l=a[1].replace(/`/g,""),u=a[2],d={agentId:l,permissions:u};o.includes("primary")?t.primary.push(d):o.includes("secondary")?t.secondary.push(d):o.includes("support")?t.support.push(d):(o.includes("readonly")||o.includes("approval"))&&t.readonly.push(d)}}let r=n.match(/\*\*Forbidden[^:]*:\*\*\s*([^\n]+)/i);if(r){let a=r[1].match(/agents?\s+(?:without|MUST\s+NOT)[^.]+/gi);a&&t.forbidden.push(...a)}return t}extractEscalationTriggers(e){let t=[],n=this.extractSection(e,"Escalation Triggers");if(!n)return t;let i=n.split(`
10
- `).filter(r=>r.includes("|")&&!r.includes("---"));for(let r=1;r<i.length;r++){let s=i[r].split("|").map(a=>a.trim()).filter(a=>a);if(s.length>=3){let a=s[0],o=this.parseSeverity(s[1]),l=s[2];t.push({trigger:a,severity:o,action:l})}}return t}parseSeverity(e){let t=e.toUpperCase().trim();return t==="CRITICAL"?"CRITICAL":t==="HIGH"?"HIGH":t==="MEDIUM"?"MEDIUM":"LOW"}extractMemoryNamespace(e){let t=this.extractSection(e,"Memory Namespace"),n={namespace:"qe-patterns/unknown",retention:"30 days",contradictionCheck:!0};if(!t)return n;let i=t.match(/\*\*Namespace\*\*:\s*`([^`]+)`/);i&&(n.namespace=i[1]);let r=t.match(/\*\*Retention\*\*:\s*([^\n]+)/);r&&(n.retention=r[1].trim());let s=t.match(/\*\*Contradiction Check\*\*:\s*(\w+)/i);return s&&(n.contradictionCheck=s[1].toLowerCase()==="enabled"),n}extractIntegrationPoints(e){let t=[],n=this.extractSection(e,"Integration Points");if(!n)return t;let i=n.split(`
11
- `).filter(r=>r.includes("|")&&!r.includes("---"));for(let r=1;r<i.length;r++){let s=i[r].split("|").map(a=>a.trim()).filter(a=>a);if(s.length>=3){let a=s[0].replace(/`/g,""),o=this.parseIntegrationType(s[1]),l=s[2];t.push({domain:a,type:o,purpose:l})}}return t}parseIntegrationType(e){let t=e.toLowerCase().trim();return t==="bidirectional"?"Bidirectional":t==="output"?"Output":"Input"}extractSection(e,t){let n=new RegExp(`## ${t}[\\s\\S]*?(?=\\n## |\\n---\\n\\*|$)`,"i"),i=e.match(n);return i?i[0].replace(new RegExp(`## ${t}\\n*`,"i"),"").trim():null}cacheShardIfEnabled(e,t){let n=B();if(!n.cacheEnabled)return;let i=Date.now();this.shardCache.set(e,{shard:t,loadedAt:i,expiresAt:i+n.cacheTtlMs})}getCachedShard(e){if(!B().cacheEnabled)return null;let n=this.shardCache.get(e);return n?Date.now()>n.expiresAt?(this.shardCache.delete(e),null):n.shard:null}async getAllCachedOrLoadedShards(){if(B().cacheEnabled&&this.shardCache.size>0){let t=new Map,n=Date.now();for(let[i,r]of this.shardCache)n<=r.expiresAt&&t.set(i,r.shard);if(t.size>0)return t}return this.loadAllShards()}getDomainsForIntent(e){let t=new Set;for(let[n,i]of Object.entries(Ze))e.includes(n)&&i.forEach(r=>t.add(r));return Array.from(t)}dedupeAgentRoles(e){let t=new Map;for(let n of e)t.has(n.agentId)||t.set(n.agentId,n);return Array.from(t.values())}logError(e){m.getFlags().global.logViolations&&console.error(`[ShardRetriever] ${e}`)}},bt=new Z;function H(){let c=m.getFlags();return c.global.enableAllGates?c.abBenchmarking?.enabled??!1:!1}function tt(){return m.getFlags().abBenchmarking??{enabled:!1,defaultConfidenceLevel:.95,defaultMinSampleSize:100,autoApplyWinners:!1,maxConcurrentBenchmarks:5}}function P(c){return c.length===0?0:c.reduce((e,t)=>e+t,0)/c.length}function se(c){if(c.length<2)return 0;let e=P(c),t=c.map(n=>Math.pow(n-e,2));return Math.sqrt(t.reduce((n,i)=>n+i,0)/(c.length-1))}function St(c,e,t,n){return c+t<=2?0:Math.sqrt(((c-1)*e*e+(t-1)*n*n)/(c+t-2))}function Tt(c,e,t){if(t===0)return{value:0,interpretation:"negligible"};let n=Math.abs(c-e)/t,i;return n<.2?i="negligible":n<.5?i="small":n<.8?i="medium":i="large",{value:n,interpretation:i}}function nt(c,e,t,n,i,r){if(t<2||r<2)return{tStatistic:0,degreesOfFreedom:0,pValue:1};let s=e*e/t,a=i*i/r,o=Math.sqrt(s+a);if(o===0)return{tStatistic:0,degreesOfFreedom:t+r-2,pValue:1};let l=(c-n)/o,u=Math.pow(s+a,2)/(Math.pow(s,2)/(t-1)+Math.pow(a,2)/(r-1)),d=Et(Math.abs(l),u);return{tStatistic:l,degreesOfFreedom:u,pValue:d}}function Et(c,e){if(e<=0)return 1;let t=c*Math.sqrt(e/(e+c*c));return 2*(1-Se(Math.abs(t)))}function Se(c){let e=.254829592,t=-.284496736,n=1.421413741,i=-1.453152027,r=1.061405429,s=.3275911,a=c<0?-1:1;c=Math.abs(c)/Math.SQRT2;let o=1/(1+s*c),l=1-((((r*o+i)*o+n)*o+t)*o+e)*o*Math.exp(-c*c);return .5*(1+a*l)}function kt(c){let e=c.length;if(e<2)return{statistic:0,pValue:1,degreesOfFreedom:0};let t=c.reduce((l,u)=>l+u.successes,0),n=c.reduce((l,u)=>l+u.failures,0),i=t+n;if(i===0)return{statistic:0,pValue:1,degreesOfFreedom:e-1};let r=t/i,s=0;for(let l of c){let u=l.successes+l.failures;if(u===0)continue;let d=u*r,h=u*(1-r);d>0&&(s+=Math.pow(l.successes-d,2)/d),h>0&&(s+=Math.pow(l.failures-h,2)/h)}let a=e-1,o=Ct(s,a);return{statistic:s,pValue:o,degreesOfFreedom:a}}function Ct(c,e){if(e<=0||c<0)return 1;let t=2/(9*e),i=(Math.pow(c/e,1/3)-(1-t))/Math.sqrt(t);return 1-Se(i)}function Rt(c,e,t,n){if(e<2||t<2)return 0;let i=2*e*t/(e+t),r=c*Math.sqrt(i/2),s=$e(1-n/2),a=1-Se(s-r)+Se(-s-r);return Math.max(0,Math.min(1,a))}function wt(c,e,t){if(c<=0)return 1e3;let n=$e(1-e/2),i=$e(t),r=2*Math.pow((n+i)/c,2);return Math.ceil(r)}function $e(c){if(c<=0)return-1/0;if(c>=1)return 1/0;if(c===.5)return 0;let e=[-39.69683028665376,220.9460984245205,-275.9285104469687,138.357751867269,-30.66479806614716,2.506628277459239],t=[-54.47609879822406,161.5858368580409,-155.6989798598866,66.80131188771972,-13.28068155288572],n=[-.007784894002430293,-.3223964580411365,-2.400758277161838,-2.549732539343734,4.374664141464968,2.938163982698783],i=[.007784695709041462,.3224671290700398,2.445134137142996,3.754408661907416],r=.02425,s=1-r,a,o;return c<r?(a=Math.sqrt(-2*Math.log(c)),(((((n[0]*a+n[1])*a+n[2])*a+n[3])*a+n[4])*a+n[5])/((((i[0]*a+i[1])*a+i[2])*a+i[3])*a+1)):c<=s?(a=c-.5,o=a*a,(((((e[0]*o+e[1])*o+e[2])*o+e[3])*o+e[4])*o+e[5])*a/(((((t[0]*o+t[1])*o+t[2])*o+t[3])*o+t[4])*o+1)):(a=Math.sqrt(-2*Math.log(1-c)),-(((((n[0]*a+n[1])*a+n[2])*a+n[3])*a+n[4])*a+n[5])/((((i[0]*a+i[1])*a+i[2])*a+i[3])*a+1))}var Te=class{benchmarks=new Map;initialized=!1;async initialize(){this.initialized||(await $.initialize(),this.initialized=!0,this.logEvent("initialize","A/B Benchmarking Framework initialized"))}createBenchmark(e){if(!H())return`${e.testId}-disabled`;let t=tt();if(this.getActiveBenchmarks().length>=t.maxConcurrentBenchmarks)throw new Error(`Maximum concurrent benchmarks (${t.maxConcurrentBenchmarks}) reached. Stop an existing benchmark before creating a new one.`);if(e.variants.length<2)throw new Error("Benchmark requires at least 2 variants");if(e.metrics.length===0)throw new Error("Benchmark requires at least 1 metric");let i=e.metrics.reduce((s,a)=>s+a.weight,0);if(Math.abs(i-1)>.01)throw new Error(`Metric weights must sum to 1.0, got ${i}`);let r={config:e,status:"pending",startTime:null,endTime:null,variantMetrics:new Map,winnerId:null};for(let s of e.variants){r.variantMetrics.set(s.id,{variantId:s.id,successes:0,failures:0,metrics:new Map});for(let a of e.metrics)r.variantMetrics.get(s.id).metrics.set(a.name,[])}return this.benchmarks.set(e.testId,r),$.registerVariantTest(e.testId,e.variants.map(s=>s.id)),this.logEvent("benchmark_created",`Benchmark ${e.testId} created with ${e.variants.length} variants`),e.testId}startBenchmark(e){if(!H())return;let t=this.benchmarks.get(e);if(!t)throw new Error(`Benchmark ${e} not found`);if(t.status!=="running"){if(t.status==="completed")throw new Error(`Benchmark ${e} is already completed`);t.status="running",t.startTime=Date.now(),this.logEvent("benchmark_started",`Benchmark ${e} started`)}}stopBenchmark(e){if(!H())return;let t=this.benchmarks.get(e);if(!t)throw new Error(`Benchmark ${e} not found`);t.status==="running"&&(t.status="stopped",t.endTime=Date.now(),$.completeVariantTest(e),this.logEvent("benchmark_stopped",`Benchmark ${e} stopped`))}recordMetric(e,t,n,i){if(!H())return;let r=this.benchmarks.get(e);if(!r){this.logEvent("record_error",`Benchmark ${e} not found`);return}if(r.status!=="running"){this.logEvent("record_error",`Benchmark ${e} is not running`);return}let s=r.variantMetrics.get(t);if(!s){this.logEvent("record_error",`Variant ${t} not found in benchmark ${e}`);return}let a=s.metrics.get(n);if(!a){this.logEvent("record_error",`Metric ${n} not configured for benchmark ${e}`);return}a.push({value:i,timestamp:Date.now()}),this.checkBenchmarkCompletion(r)}recordOutcome(e,t,n,i){if(!H())return;let r=this.benchmarks.get(e);if(!r){this.logEvent("record_error",`Benchmark ${e} not found`);return}if(r.status!=="running"){this.logEvent("record_error",`Benchmark ${e} is not running`);return}let s=r.variantMetrics.get(t);if(!s){this.logEvent("record_error",`Variant ${t} not found in benchmark ${e}`);return}if(n?s.successes++:s.failures++,i)for(let[a,o]of Object.entries(i)){let l=s.metrics.get(a);l&&l.push({value:o,timestamp:Date.now()})}$.recordVariantOutcome(e,t,n),this.checkBenchmarkCompletion(r)}getBenchmarkResults(e){let t=this.benchmarks.get(e);if(!t)throw new Error(`Benchmark ${e} not found`);let n=this.createBenchmarkSummary(e,t),i=this.getVariantResults(t),r=this.hasEnoughSamples(t)?this.calculateStatisticalSignificance(e):null,s=this.getWinner(e);return{benchmark:n,variants:i,significance:r,winner:s}}calculateStatisticalSignificance(e){let t=this.benchmarks.get(e);if(!t)throw new Error(`Benchmark ${e} not found`);let{config:n,variantMetrics:i}=t,r=1-n.confidenceLevel,s=n.metrics.length,a=r/s,o=Array.from(i.values()).map(p=>({successes:p.successes,failures:p.failures})),l=kt(o),u=[],d=Array.from(i.keys());if(d.length>=2){let p=i.get(d[0]),v=i.get(d[1]);for(let b of n.metrics){let w=(p.metrics.get(b.name)||[]).map(A=>A.value),D=(v.metrics.get(b.name)||[]).map(A=>A.value);if(w.length>=2&&D.length>=2){let A=P(w),ee=P(D),te=se(w),V=se(D),ke=w.length,Ce=D.length,Re=nt(A,te,ke,ee,V,Ce),rt=St(ke,te,Ce,V),Be=Tt(A,ee,rt);u.push({metric:b.name,variantA:{mean:A,stdDev:te,sampleSize:ke},variantB:{mean:ee,stdDev:V,sampleSize:Ce},tStatistic:Re.tStatistic,pValue:Re.pValue,effectSize:Be.value,effectSizeInterpretation:Be.interpretation,isSignificant:Re.pValue<a})}}}let h=Array.from(i.values()),g=P(h.map(p=>p.successes+p.failures)),f=u.length>0?P(u.map(p=>p.effectSize)):.5,k=Rt(f,g,g,r),C=wt(f,r,.8),M=l.pValue<r||u.some(p=>p.isSignificant);return{benchmarkId:e,confidenceLevel:n.confidenceLevel,isSignificant:M,chiSquareTest:{statistic:l.statistic,pValue:l.pValue,degreesOfFreedom:l.degreesOfFreedom,isSignificant:l.pValue<r},metricStatistics:u,bonferroniAlpha:a,powerAnalysis:{currentPower:k,recommendedSampleSize:C,targetPower:.8}}}getWinner(e){let t=this.benchmarks.get(e);if(!t||!this.hasEnoughSamples(t))return null;let n=this.calculateCombinedScores(t);if(n.length===0)return null;n.sort((u,d)=>d.score-u.score);let i=n[0],r=this.calculateStatisticalSignificance(e),s=n.length>1?i.score-n[1].score:i.score,a=r.isSignificant?Math.min(.99,.5+s*.5+r.powerAnalysis.currentPower*.25):Math.min(.5,s*.5),o=r.metricStatistics.filter(u=>u.isSignificant).map(u=>u.metric),l=t.config.variants.find(u=>u.id===i.variantId);return{benchmarkId:e,winnerId:i.variantId,winnerName:l?.name||i.variantId,confidence:a,combinedScore:i.score,significantMetrics:o,recommendation:this.generateWinnerRecommendation(i,a,o)}}compareVariants(e,t,n){let i=this.benchmarks.get(e);if(!i)throw new Error(`Benchmark ${e} not found`);let r=i.variantMetrics.get(t),s=i.variantMetrics.get(n);if(!r||!s)throw new Error(`Variant not found: ${r?n:t}`);let{config:a}=i,o=1-a.confidenceLevel,l=[],u=0,d=0;for(let C of a.metrics){let M=(r.metrics.get(C.name)||[]).map(V=>V.value),p=(s.metrics.get(C.name)||[]).map(V=>V.value),v=M.length>0?P(M):0,b=p.length>0?P(p):0,w=!1;M.length>=2&&p.length>=2&&(w=nt(v,se(M),M.length,b,se(p),p.length).pValue<o);let D=null,A=0;v!==b&&(C.higherIsBetter?(D=v>b?t:n,A=Math.abs(v-b)/Math.max(v,b,.001)):(D=v<b?t:n,A=Math.abs(v-b)/Math.max(v,b,.001))),l.push({metric:C.name,variantAValue:v,variantBValue:b,winner:D,improvement:A,isSignificant:w});let ee=this.normalizeMetric(v,C),te=this.normalizeMetric(b,C);u+=ee*C.weight,d+=te*C.weight}let h=this.getSuccessRate(r),g=this.getSuccessRate(s),f=u>d?t:d>u?n:null,k=Math.abs(u-d)/Math.max(u,d,.001);return{benchmarkId:e,variantA:t,variantB:n,winner:f,confidence:Math.min(1,k),metricComparisons:l,combinedScores:{variantA:u,variantB:d}}}suggestWinner(e){let t=this.benchmarks.get(e);if(!t)throw new Error(`Benchmark ${e} not found`);let n=[],i=[],r=!1,s=null,{config:a,variantMetrics:o}=t,l=Array.from(o.values()).map(g=>g.successes+g.failures),u=Math.min(...l);u<a.minSampleSize?i.push(`Insufficient samples: ${u} < ${a.minSampleSize} required`):n.push(`Sample size requirement met: ${u} >= ${a.minSampleSize}`);let d=this.hasEnoughSamples(t)?this.calculateStatisticalSignificance(e):null;d&&(d.isSignificant?n.push("Statistical significance achieved"):i.push(`Not yet statistically significant at ${a.confidenceLevel*100}% confidence`),d.powerAnalysis.currentPower<.8&&i.push(`Low statistical power (${(d.powerAnalysis.currentPower*100).toFixed(1)}%). Recommend ${d.powerAnalysis.recommendedSampleSize} samples per variant.`));let h=this.getWinner(e);return h?(s=h.winnerId,n.push(`Winner: ${h.winnerName} (score: ${h.combinedScore.toFixed(3)})`),h.significantMetrics.length>0&&n.push(`Significant improvements in: ${h.significantMetrics.join(", ")}`),h.confidence>=.95?(r=!0,n.push("High confidence - ready to apply")):h.confidence>=.8&&d?.isSignificant?(r=!0,n.push("Good confidence with statistical significance - ready to apply")):i.push(`Confidence (${(h.confidence*100).toFixed(1)}%) below recommended threshold`)):i.push("No clear winner determined"),{benchmarkId:e,suggestedWinnerId:s,confidence:h?.confidence??0,reasoning:n,caveats:i,readyToApply:r}}applyWinner(e){if(!H())return;let t=this.benchmarks.get(e);if(!t)throw new Error(`Benchmark ${e} not found`);let n=this.getWinner(e);if(!n)throw new Error(`No winner determined for benchmark ${e}`);t.status="completed",t.endTime=Date.now(),t.winnerId=n.winnerId,$.promoteRule(n.winnerId,`Won A/B benchmark ${e} with ${(n.confidence*100).toFixed(1)}% confidence`),$.completeVariantTest(e),this.logEvent("winner_applied",`Applied winner ${n.winnerId} for benchmark ${e}`)}getActiveBenchmarks(){return Array.from(this.benchmarks.entries()).filter(([e,t])=>t.status==="running"||t.status==="pending").map(([e,t])=>this.createBenchmarkSummary(e,t))}getBenchmarkHistory(){return Array.from(this.benchmarks.entries()).map(([e,t])=>this.createBenchmarkSummary(e,t)).sort((e,t)=>(t.startTime||0)-(e.startTime||0))}reset(){this.benchmarks.clear(),this.initialized=!1}hasEnoughSamples(e){let{config:t,variantMetrics:n}=e;for(let i of Array.from(n.values()))if(i.successes+i.failures<t.minSampleSize)return!1;return!0}checkBenchmarkCompletion(e){let{config:t}=e;if(e.startTime&&Date.now()-e.startTime>t.maxDurationMs){e.status="completed",e.endTime=Date.now(),this.logEvent("benchmark_auto_completed",`Benchmark ${t.testId} auto-completed due to max duration`);return}this.hasEnoughSamples(e)&&tt().autoApplyWinners&&this.suggestWinner(t.testId).readyToApply&&this.applyWinner(t.testId)}createBenchmarkSummary(e,t){let n=Array.from(t.variantMetrics.values()).reduce((i,r)=>i+r.successes+r.failures,0);return{benchmarkId:e,status:t.status,variantCount:t.config.variants.length,totalSamples:n,startTime:t.startTime,duration:t.startTime&&t.endTime?t.endTime-t.startTime:t.startTime?Date.now()-t.startTime:null,winnerId:t.winnerId,confidenceLevel:t.config.confidenceLevel}}getVariantResults(e){return e.config.variants.map(t=>{let n=e.variantMetrics.get(t.id),i=n.successes+n.failures,r=i>0?n.successes/i:0,s={};for(let[a,o]of Array.from(n.metrics.entries())){let l=o.map(u=>u.value);s[a]={mean:l.length>0?P(l):0,stdDev:l.length>1?se(l):0}}return{id:t.id,name:t.name,successRate:r,sampleSize:i,metrics:s}})}calculateCombinedScores(e){let{config:t,variantMetrics:n}=e,i=[];for(let[r,s]of Array.from(n.entries())){let a=0;for(let l of t.metrics){let d=(s.metrics.get(l.name)||[]).map(f=>f.value),h=d.length>0?P(d):0,g=this.normalizeMetric(h,l);a+=g*l.weight}if(!t.metrics.some(l=>l.type==="success_rate")){let l=this.getSuccessRate(s);a+=l*.5}i.push({variantId:r,score:a})}return i}normalizeMetric(e,t){switch(t.type){case"success_rate":return e;case"latency":return t.higherIsBetter?Math.min(1,e/1e4):Math.max(0,1-e/1e4);case"cost":return t.higherIsBetter?Math.min(1,e/100):Math.max(0,1-e/100);case"quality_score":return Math.min(1,Math.max(0,e));default:return e}}getSuccessRate(e){let t=e.successes+e.failures;return t>0?e.successes/t:0}generateWinnerRecommendation(e,t,n){return t>=.95?`Strongly recommend applying ${e.variantId}. High confidence (${(t*100).toFixed(1)}%) with significant improvements in: ${n.length>0?n.join(", "):"overall performance"}.`:t>=.8?`Recommend applying ${e.variantId}. Good confidence (${(t*100).toFixed(1)}%). Consider collecting more samples for higher confidence.`:t>=.6?`${e.variantId} shows promise with moderate confidence (${(t*100).toFixed(1)}%). Recommend collecting more samples before applying.`:`Results are inconclusive. ${e.variantId} is currently leading but confidence (${(t*100).toFixed(1)}%) is low. Continue collecting data.`}logEvent(e,t){m.getFlags().global.logViolations&&console.info(`[ABBenchmarking] ${e}:`,{message:t,timestamp:new Date().toISOString()})}},At=new Te;import{promises as Ne}from"fs";import*as ae from"path";q();we();oe();var it={enabled:!0,embeddingDimensions:384,persistEmbeddings:!1,autoRebuildOnChange:!0,ngramMin:2,ngramMax:4,persistPath:".agentic-qe/shard-embeddings.json"};function z(){let c=m.getFlags();return c.global.enableAllGates?c.shardEmbeddings?.enabled??!0:!1}function L(){let c=m.getFlags();return{...it,...c.shardEmbeddings}}var Ee=class{embeddings=new Map;vocabulary=new Map;idfScores=new Map;documentFrequency=new Map;initialized=!1;lastRebuild=null;shardRetriever;basePath;persistedToFile=!1;constructor(e,t){this.basePath=e??process.cwd(),this.shardRetriever=t??new Z(e)}async initialize(){if(this.initialized)return;if(!z()){this.initialized=!0;return}if(L().persistEmbeddings&&await this.loadPersistedEmbeddings()){this.initialized=!0;return}await this.generateEmbeddings(),this.initialized=!0}async generateEmbeddings(){if(!z())return;await this.shardRetriever.initialize();let e=await this.shardRetriever.loadAllShards();this.embeddings.clear(),this.vocabulary.clear(),this.idfScores.clear(),this.documentFrequency.clear();let t=[];for(let[r,s]of e){let a=this.extractSections(r,s);for(let o of a){let l=this.tokenize(o.content);t.push({key:o.key,tokens:l});for(let d of l)this.vocabulary.has(d)||this.vocabulary.set(d,this.vocabulary.size);let u=new Set(l);for(let d of u)this.documentFrequency.set(d,(this.documentFrequency.get(d)||0)+1)}}let n=t.length;for(let[r,s]of this.documentFrequency)this.idfScores.set(r,Math.log(n/s)+1);for(let[r,s]of e){let a=this.extractSections(r,s);for(let o of a){let l=this.computeTfIdfEmbedding(o.content);this.embeddings.set(o.key,{domain:r,sectionType:o.type,content:o.content,embedding:l,metadata:o.metadata})}}this.lastRebuild=Date.now(),L().persistEmbeddings&&await this.persistEmbeddings()}async generateEmbeddingForShard(e){if(!z())return[];let t=await this.shardRetriever.loadShard(e);if(!t)return[];let n=[],i=this.extractSections(e,t);if(this.vocabulary.size===0)return await this.generateEmbeddings(),Array.from(this.embeddings.values()).filter(s=>s.domain===e);for(let s of i){let a=this.tokenize(s.content),o=new Set(a);for(let l of a)this.vocabulary.has(l)||this.vocabulary.set(l,this.vocabulary.size);for(let l of o)this.documentFrequency.set(l,(this.documentFrequency.get(l)||0)+1)}let r=this.embeddings.size+i.length;for(let[s,a]of this.documentFrequency)this.idfScores.set(s,Math.log(r/a)+1);for(let s of i){let a=this.computeTfIdfEmbedding(s.content),o={domain:e,sectionType:s.type,content:s.content,embedding:a,metadata:s.metadata};this.embeddings.set(s.key,o),n.push(o)}return n}async searchBySimilarity(e,t=10){if(!z())return[];if(await this.initialize(),this.embeddings.size===0)return[];let n=this.computeTfIdfEmbedding(e),i=[];for(let[,r]of this.embeddings){let s=this.cosineSimilarity(n,r.embedding);i.push({domain:r.domain,sectionType:r.sectionType,similarity:s,content:r.content,metadata:r.metadata})}return i.sort((r,s)=>s.similarity-r.similarity),i.slice(0,t)}async findRelevantShards(e,t=5){if(!z())return[];await this.initialize();let n=await this.searchBySimilarity(e,this.embeddings.size),i=new Map;for(let s of n){i.has(s.domain)||i.set(s.domain,{totalSimilarity:0,count:0,sectionScores:{rules:0,invariants:0,thresholds:0,patterns:0,full:0},matchingSections:[]});let a=i.get(s.domain);a.totalSimilarity+=s.similarity,a.count++,a.sectionScores[s.sectionType]=Math.max(a.sectionScores[s.sectionType],s.similarity),s.similarity>.1&&!a.matchingSections.includes(s.sectionType)&&a.matchingSections.push(s.sectionType)}let r=[];for(let[s,a]of i){let o=await this.shardRetriever.loadShard(s);r.push({domain:s,overallSimilarity:a.totalSimilarity/a.count,sectionScores:a.sectionScores,matchingSections:a.matchingSections,shard:o})}return r.sort((s,a)=>a.overallSimilarity-s.overallSimilarity),r.slice(0,t)}async indexEmbedding(e){if(!z())return;let t=`${e.domain}:${e.sectionType}`;this.embeddings.set(t,e)}async rebuildIndex(){z()&&(this.embeddings.clear(),this.vocabulary.clear(),this.idfScores.clear(),this.documentFrequency.clear(),this.initialized=!1,await this.generateEmbeddings(),this.initialized=!0)}getIndexStats(){let e={},t={rules:0,invariants:0,thresholds:0,patterns:0,full:0};for(let[,i]of this.embeddings)e[i.domain]=(e[i.domain]||0)+1,t[i.sectionType]++;let n=L();return{totalEmbeddings:this.embeddings.size,embeddingsByDomain:e,embeddingsBySectionType:t,dimensions:n.embeddingDimensions,lastRebuild:this.lastRebuild,vocabularySize:this.vocabulary.size,persistedToFile:this.persistedToFile}}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let n=0,i=0,r=0;for(let a=0;a<e.length;a++)n+=e[a]*t[a],i+=e[a]*e[a],r+=t[a]*t[a];let s=Math.sqrt(i)*Math.sqrt(r);return s===0?0:n/s}async getEmbeddingForText(e){return z()?(await this.initialize(),this.computeTfIdfEmbedding(e)):[]}reset(){this.embeddings.clear(),this.vocabulary.clear(),this.idfScores.clear(),this.documentFrequency.clear(),this.initialized=!1,this.lastRebuild=null,this.persistedToFile=!1}isInitialized(){return this.initialized}extractSections(e,t){let n=[];t.rules.length>0&&n.push({key:`${e}:rules`,type:"rules",content:t.rules.join(`
12
- `),metadata:{ruleCount:t.rules.length,version:t.version}}),t.invariants.length>0&&n.push({key:`${e}:invariants`,type:"invariants",content:t.invariants.join(`
13
- `),metadata:{invariantCount:t.invariants.length,version:t.version}});let i=Object.keys(t.thresholds);if(i.length>0){let r=i.map(s=>`${s}: min=${t.thresholds[s].minimum} target=${t.thresholds[s].target}`).join(`
14
- `);n.push({key:`${e}:thresholds`,type:"thresholds",content:r,metadata:{thresholdCount:i.length,metrics:i,version:t.version}})}if(t.patterns.length>0){let r=t.patterns.map(s=>`${s.name}: ${s.description} (${s.location})`).join(`
15
- `);n.push({key:`${e}:patterns`,type:"patterns",content:r,metadata:{patternCount:t.patterns.length,patternNames:t.patterns.map(s=>s.name),version:t.version}})}return n.push({key:`${e}:full`,type:"full",content:t.rawContent,metadata:{domain:t.domain,version:t.version,lastUpdated:t.lastUpdated,agentCount:t.agentConstraints.primary.length+t.agentConstraints.secondary.length+t.agentConstraints.support.length,integrationCount:t.integrationPoints.length}}),n}tokenize(e){let t=L(),n=[],r=e.toLowerCase().replace(/[^a-z0-9\s-]/g," ").replace(/\s+/g," ").trim().split(" ").filter(s=>s.length>2);n.push(...r);for(let s of r)for(let a=t.ngramMin;a<=Math.min(t.ngramMax,s.length);a++)for(let o=0;o<=s.length-a;o++)n.push(s.substring(o,o+a));return n}computeTfIdfEmbedding(e){let t=L(),n=this.tokenize(e),i=t.embeddingDimensions,r=new Array(i).fill(0);if(n.length===0)return r;let s=new Map;for(let l of n)s.set(l,(s.get(l)||0)+1);let a=n.length;for(let[l,u]of s)s.set(l,u/a);for(let[l,u]of s){let d=this.idfScores.get(l)||1,h=u*d,g=this.hashToken(l,i);for(let{index:f,sign:k}of g)r[f]+=k*h}let o=Math.sqrt(r.reduce((l,u)=>l+u*u,0));if(o>0)for(let l=0;l<r.length;l++)r[l]/=o;return r}hashToken(e,t){let n=[];for(let r=0;r<4;r++){let s=2166136261^r*31;for(let l=0;l<e.length;l++)s^=e.charCodeAt(l),s=Math.imul(s,16777619);let a=Math.abs(s)%t,o=(s&1)===0?1:-1;n.push({index:a,sign:o})}return n}async persistEmbeddings(){let e=L(),t=ae.resolve(this.basePath,e.persistPath),n={version:1,timestamp:Date.now(),dimensions:e.embeddingDimensions,vocabulary:Array.from(this.vocabulary.entries()),idfScores:Array.from(this.idfScores.entries()),documentFrequency:Array.from(this.documentFrequency.entries()),embeddings:Array.from(this.embeddings.entries()).map(([i,r])=>({key:i,...r}))};try{await Ne.mkdir(ae.dirname(t),{recursive:!0}),await Ne.writeFile(t,JSON.stringify(n,null,2),"utf-8"),this.persistedToFile=!0}catch(i){this.logError(`Failed to persist embeddings to file: ${S(i)}`)}try{let i=G();await i.initialize();for(let[r,s]of this.embeddings)await i.vectorStore(`shard:${r}`,s.embedding,`shard:${s.domain}`,{domain:s.domain,sectionType:s.sectionType,content:s.content,metadata:s.metadata})}catch{}}async loadPersistedEmbeddings(){let e=L(),t=ae.resolve(this.basePath,e.persistPath);try{let n=await Ne.readFile(t,"utf-8"),i=W(n);if(i.version!==1||i.dimensions!==e.embeddingDimensions)return!1;this.vocabulary=new Map(i.vocabulary),this.idfScores=new Map(i.idfScores),this.documentFrequency=new Map(i.documentFrequency),this.embeddings=new Map;for(let r of i.embeddings)this.embeddings.set(r.key,{domain:r.domain,sectionType:r.sectionType,content:r.content,embedding:r.embedding,metadata:r.metadata});return this.lastRebuild=i.timestamp,this.persistedToFile=!0,!0}catch{return!1}}logError(e){m.getFlags().global.logViolations&&console.error(`[ShardEmbeddings] ${e}`)}},xt=new Ee;export{j as a,I as b,U as c,y as d,K as e,Ie as f,Je as g,Y as h,R as i,vn as j};