agentic-qe 3.9.33 → 3.9.35
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.
- package/.claude/skills/skills-manifest.json +1 -1
- package/CHANGELOG.md +104 -0
- package/assets/skills/skills-manifest.json +1 -1
- package/dist/audit/witness-chain.d.ts +7 -0
- package/dist/audit/witness-chain.js +9 -0
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-JUISYMI3.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-DUOP4SS6.js → agent-booster-wasm-4PJZ34PF.js} +2 -2
- package/dist/cli/chunks/{agent-handler-6AHMQ5OK.js → agent-handler-OB5JATVT.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-77WTL4KU.js → agent-memory-branch-ZEHRWZ5R.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-DEIUPULJ.js +2 -0
- package/dist/cli/chunks/{audit-ZRSUAGID.js → audit-PWFRSBBW.js} +2 -2
- package/dist/cli/chunks/base-7SMQWXHT.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-SDVX3I7F.js → better-sqlite3-XEIBI22V.js} +2 -2
- package/dist/cli/chunks/{brain-handler-EPNKL22C.js → brain-handler-6SMUCFO7.js} +3 -3
- package/dist/cli/chunks/{branch-enumerator-VVPWHTZ4.js → branch-enumerator-U6ROQR4O.js} +2 -2
- package/dist/cli/chunks/{browser-NNQ6UHFJ.js → browser-BMM57TA3.js} +2 -2
- package/dist/cli/chunks/browser-workflow-4DGHRZLS.js +2 -0
- package/dist/cli/chunks/{chunk-KQDWD34T.js → chunk-2FTSVPVG.js} +1 -1
- package/dist/cli/chunks/{chunk-JHFQJKTW.js → chunk-2ICMLI2T.js} +2 -2
- package/dist/cli/chunks/{chunk-IQ5OS342.js → chunk-2UY3X3KE.js} +9 -9
- package/dist/cli/chunks/{chunk-2NRCDJBB.js → chunk-3BDZSWCA.js} +2 -2
- package/dist/cli/chunks/{chunk-DLUEORKO.js → chunk-3R6YQEQY.js} +4 -4
- package/dist/cli/chunks/{chunk-TGMZ7K72.js → chunk-3UGY4ZQB.js} +1 -1
- package/dist/cli/chunks/{chunk-FRS4DYHG.js → chunk-3YIVRMQB.js} +1 -1
- package/dist/cli/chunks/{chunk-54B5QL4A.js → chunk-42QMNST6.js} +2 -2
- package/dist/cli/chunks/{chunk-4HJAUI2N.js → chunk-4HJVTKJD.js} +1 -1
- package/dist/cli/chunks/{chunk-LFPYLTNN.js → chunk-4NVDPO7L.js} +2 -2
- package/dist/cli/chunks/{chunk-LAPIIGZ2.js → chunk-4UZ7G2KT.js} +2 -2
- package/dist/cli/chunks/{chunk-4MRVNLCT.js → chunk-4YKHVRQH.js} +3 -3
- package/dist/cli/chunks/{chunk-JEGTTVTL.js → chunk-56O5V5MP.js} +2 -2
- package/dist/cli/chunks/{chunk-SR2EV7PQ.js → chunk-5CZDHJZX.js} +1 -1
- package/dist/cli/chunks/{chunk-VJHKNSOC.js → chunk-5Q7X5SDB.js} +2 -2
- package/dist/cli/chunks/{chunk-KF3R6OCB.js → chunk-5XXZQCHS.js} +1 -1
- package/dist/cli/chunks/{chunk-6DBS53L7.js → chunk-6CCKOU2U.js} +2 -2
- package/dist/cli/chunks/{chunk-KLTN2AVK.js → chunk-6SN55CMC.js} +2 -2
- package/dist/cli/chunks/{chunk-TIEXYJMS.js → chunk-6TYWIS4R.js} +2 -2
- package/dist/cli/chunks/{chunk-H5AQHFIA.js → chunk-6WZNRHJJ.js} +1 -1
- package/dist/cli/chunks/{chunk-LERCHSFI.js → chunk-72HXOVRN.js} +1 -1
- package/dist/cli/chunks/{chunk-JF4SWEMU.js → chunk-7RNLOYAP.js} +2 -2
- package/dist/cli/chunks/{chunk-C2XCETKV.js → chunk-A5LZVQQL.js} +3 -3
- package/dist/cli/chunks/chunk-A7QP5E46.js +2 -0
- package/dist/cli/chunks/{chunk-JMSQW6KN.js → chunk-AAVOYIKA.js} +1 -1
- package/dist/cli/chunks/chunk-ACL5JFJR.js +2 -0
- package/dist/cli/chunks/{chunk-CCSISDAP.js → chunk-BBHTM2RF.js} +1 -1
- package/dist/cli/chunks/chunk-BCD2IMXF.js +9 -0
- package/dist/cli/chunks/{chunk-LXWXZPEB.js → chunk-BEJAUYFA.js} +2 -2
- package/dist/cli/chunks/{chunk-GVO53VR5.js → chunk-BKF3E3UJ.js} +1 -1
- package/dist/cli/chunks/{chunk-ZUFM5K7F.js → chunk-BSM7YJBY.js} +1 -1
- package/dist/cli/chunks/{chunk-PIINM2PD.js → chunk-BTPDHALG.js} +2 -2
- package/dist/cli/chunks/{chunk-3J4TTZP7.js → chunk-BTQA2E2Y.js} +2 -2
- package/dist/cli/chunks/{chunk-23VQRQCC.js → chunk-BXBUUSJN.js} +3 -3
- package/dist/cli/chunks/{chunk-BLNISJ3M.js → chunk-C7QVMFCJ.js} +3 -3
- package/dist/cli/chunks/{chunk-GLA2TD4M.js → chunk-CMKNLC3Q.js} +4 -4
- package/dist/cli/chunks/{chunk-7HRE2VTG.js → chunk-CROIRPKG.js} +2 -2
- package/dist/cli/chunks/{chunk-MZ6GBVQY.js → chunk-CTU4V32J.js} +2 -2
- package/dist/cli/chunks/{chunk-L77OGJVK.js → chunk-D2ITP3ON.js} +2 -2
- package/dist/cli/chunks/{chunk-Q5JL7NZG.js → chunk-DEJW6GYF.js} +2 -2
- package/dist/cli/chunks/{chunk-LKEQBIX2.js → chunk-E7N6CRFV.js} +1 -1
- package/dist/cli/chunks/{chunk-IWBJ7KB7.js → chunk-F6R2TGNS.js} +2 -2
- package/dist/cli/chunks/{chunk-IXWIABRJ.js → chunk-FMAUTL26.js} +2 -2
- package/dist/cli/chunks/{chunk-7ZMRQKO2.js → chunk-FMV22K3J.js} +2 -2
- package/dist/cli/chunks/{chunk-AVQS5H7Y.js → chunk-FMZ7I4XV.js} +1 -1
- package/dist/cli/chunks/{chunk-LJBVPR3Z.js → chunk-FPPV7TYI.js} +2 -2
- package/dist/cli/chunks/{chunk-UBOH75WQ.js → chunk-FXITHMQB.js} +4 -4
- package/dist/cli/chunks/{chunk-EYCV6IYA.js → chunk-G6BJ5I57.js} +1 -1
- package/dist/cli/chunks/{chunk-WRPQJZSP.js → chunk-GHMIADYW.js} +2 -2
- package/dist/cli/chunks/{chunk-JGCTXHHZ.js → chunk-GQCIW2ZZ.js} +1 -1
- package/dist/cli/chunks/{chunk-B4N7XODV.js → chunk-GR732YA3.js} +2 -2
- package/dist/cli/chunks/{chunk-CG2IM6IA.js → chunk-GWROZUWK.js} +1 -1
- package/dist/cli/chunks/{chunk-JTXZ3MMZ.js → chunk-GWXP36YP.js} +2 -2
- package/dist/cli/chunks/{chunk-KGA5XCHX.js → chunk-H7V3ZQT7.js} +2 -2
- package/dist/cli/chunks/{chunk-MI5TV5HT.js → chunk-HAOGVFKR.js} +2 -2
- package/dist/cli/chunks/{chunk-BD6BS2AL.js → chunk-HGJGU625.js} +2 -2
- package/dist/cli/chunks/{chunk-GBMKXJKW.js → chunk-HKQ23RPJ.js} +5 -5
- package/dist/cli/chunks/{chunk-HCAWQ7ZD.js → chunk-HMIRBSTI.js} +2 -2
- package/dist/cli/chunks/{chunk-JJY6K3OI.js → chunk-HSR7EHVN.js} +1 -1
- package/dist/cli/chunks/{chunk-QCFJQZXN.js → chunk-I5XEXLBF.js} +1 -1
- package/dist/cli/chunks/{chunk-TNQW3FUW.js → chunk-I7XQT6YM.js} +2 -2
- package/dist/cli/chunks/{chunk-6TC6UCDL.js → chunk-ICYM7H6T.js} +2 -2
- package/dist/cli/chunks/{chunk-SFNSMZGU.js → chunk-II6DIMY6.js} +2 -2
- package/dist/cli/chunks/{chunk-OPC4ZVSN.js → chunk-INCNWH3R.js} +2 -2
- package/dist/cli/chunks/{chunk-YDIHYU7V.js → chunk-IQ363U37.js} +2 -2
- package/dist/cli/chunks/{chunk-46LV5MI3.js → chunk-IXOGBA7C.js} +13 -13
- package/dist/cli/chunks/{chunk-EVDEFUJG.js → chunk-J2LOP3GE.js} +2 -2
- package/dist/cli/chunks/{chunk-BIXDUMZ4.js → chunk-JNK742DP.js} +1 -1
- package/dist/cli/chunks/{chunk-473YM6LV.js → chunk-JW4N25B5.js} +2 -2
- package/dist/cli/chunks/{chunk-NCTSH4T6.js → chunk-KAEWFVGD.js} +2 -2
- package/dist/cli/chunks/{chunk-HVC3F4IM.js → chunk-M4BCSFVN.js} +1 -1
- package/dist/cli/chunks/{chunk-C5UGKQUG.js → chunk-M7TDNJMZ.js} +1 -1
- package/dist/cli/chunks/{chunk-QYIGUM3F.js → chunk-MHUPY3YO.js} +2 -2
- package/dist/cli/chunks/{chunk-GU5DISHT.js → chunk-MSEG7GKM.js} +1 -1
- package/dist/cli/chunks/chunk-NAVH552F.js +15 -0
- package/dist/cli/chunks/{chunk-F6WQ3ES6.js → chunk-NFIOKKA6.js} +2 -2
- package/dist/cli/chunks/{chunk-63SAZCUH.js → chunk-NJUNYXMH.js} +2 -2
- package/dist/cli/chunks/{chunk-N44DNZTM.js → chunk-NPUMPLL7.js} +1 -1
- package/dist/cli/chunks/{chunk-V7GV54AY.js → chunk-NS4P3VRA.js} +2 -2
- package/dist/cli/chunks/{chunk-IYDZ4NWA.js → chunk-NWWXVXXG.js} +2 -2
- package/dist/cli/chunks/{chunk-UDJLIERV.js → chunk-NZB2JE2D.js} +2 -2
- package/dist/cli/chunks/{chunk-5RILQ3EG.js → chunk-O3MTYRBX.js} +1 -1
- package/dist/cli/chunks/{chunk-ZGR5LFER.js → chunk-OJ5GBEXU.js} +2 -2
- package/dist/cli/chunks/{chunk-FQQJUIN7.js → chunk-OPD6AENV.js} +2 -2
- package/dist/cli/chunks/chunk-PHJK33IV.js +2 -0
- package/dist/cli/chunks/{chunk-24M7JF3G.js → chunk-PK3NAZQI.js} +2 -2
- package/dist/cli/chunks/{chunk-6S5H34AN.js → chunk-PY7PJT2Y.js} +2 -2
- package/dist/cli/chunks/{chunk-YCD3EBQJ.js → chunk-QOAVXGAU.js} +2 -2
- package/dist/cli/chunks/{chunk-FHSCCEHZ.js → chunk-RP5SDWCL.js} +22 -16
- package/dist/cli/chunks/{chunk-MFMPTRZW.js → chunk-RPRFDO23.js} +1 -1
- package/dist/cli/chunks/{chunk-AL54ARD4.js → chunk-RZDMSTAQ.js} +2 -2
- package/dist/cli/chunks/{chunk-GJKTHVFE.js → chunk-S3QU54ZQ.js} +1 -1
- package/dist/cli/chunks/{chunk-DEXOYNIQ.js → chunk-SBDRHY3I.js} +2 -2
- package/dist/cli/chunks/{chunk-NFFA2UKL.js → chunk-SI6VUQSI.js} +3 -3
- package/dist/cli/chunks/{chunk-RP2RRUKT.js → chunk-SMPMLODT.js} +1 -1
- package/dist/cli/chunks/{chunk-VVGXCLJF.js → chunk-SSJV4AZ7.js} +5 -5
- package/dist/cli/chunks/{chunk-HRE4TFMN.js → chunk-T26ENWX5.js} +8 -8
- package/dist/cli/chunks/{chunk-MAP6IAOP.js → chunk-T2QVCK56.js} +1 -1
- package/dist/cli/chunks/{chunk-NNFWNI6A.js → chunk-T4HZLBM4.js} +2 -2
- package/dist/cli/chunks/{chunk-FEJCPLXV.js → chunk-TE27EK44.js} +2 -2
- package/dist/cli/chunks/{chunk-U5L7FALK.js → chunk-TLBIFZM4.js} +2 -2
- package/dist/cli/chunks/{chunk-OXGZKXSI.js → chunk-UDKBQAAH.js} +2 -2
- package/dist/cli/chunks/{chunk-AGMHJ3GS.js → chunk-UJTI5MRE.js} +2 -2
- package/dist/cli/chunks/{chunk-3B5ZAFB2.js → chunk-UQ6JC3UY.js} +3 -3
- package/dist/cli/chunks/{chunk-K5YL3O22.js → chunk-VLZ3LC6L.js} +2 -2
- package/dist/cli/chunks/{chunk-MULV6D5J.js → chunk-VMMPOLUV.js} +2 -2
- package/dist/cli/chunks/{chunk-R3U7DSLA.js → chunk-WFVBK7N3.js} +2 -2
- package/dist/cli/chunks/{chunk-UYMA75Y4.js → chunk-WGWOCTQW.js} +1 -1
- package/dist/cli/chunks/{chunk-JPJURL4N.js → chunk-WSJN6HFR.js} +2 -2
- package/dist/cli/chunks/{chunk-KD2B54EH.js → chunk-WU3RGTLV.js} +1 -1
- package/dist/cli/chunks/{chunk-VSV6PV47.js → chunk-X27VMOIH.js} +1 -1
- package/dist/cli/chunks/{chunk-GY2G2YYH.js → chunk-X3GKTB6R.js} +1 -1
- package/dist/cli/chunks/{chunk-CAZQL4G2.js → chunk-XMCMLPXY.js} +2 -2
- package/dist/cli/chunks/{chunk-TLVEBQCX.js → chunk-XUZ73S3Y.js} +2 -2
- package/dist/cli/chunks/{chunk-VK7AXSAI.js → chunk-YBGQT3OS.js} +2 -2
- package/dist/cli/chunks/{chunk-BOHAND5J.js → chunk-YL56FMCJ.js} +1 -1
- package/dist/cli/chunks/{chunk-QSH4Y5E6.js → chunk-YLYKRAGZ.js} +2 -2
- package/dist/cli/chunks/{chunk-LYWA4OU6.js → chunk-YPJ2O3TE.js} +2 -2
- package/dist/cli/chunks/{chunk-HJETZJJO.js → chunk-YQRABKOC.js} +2 -2
- package/dist/cli/chunks/{chunk-LICFVB4C.js → chunk-YTB7DDLE.js} +1 -1
- package/dist/cli/chunks/{chunk-JYDWDNNZ.js → chunk-YYKZVBIG.js} +2 -2
- package/dist/cli/chunks/{chunk-TH2BBFJ6.js → chunk-Z6NUCGQA.js} +1 -1
- package/dist/cli/chunks/{chunk-ZSDK26IP.js → chunk-ZAGCKWOC.js} +1 -1
- package/dist/cli/chunks/{ci-WZ4E35B6.js → ci-GXSOJB6I.js} +2 -2
- package/dist/cli/chunks/{ci-output-WMYWSAHI.js → ci-output-GNUGZD2F.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-4E4ZZ47P.js → circuit-breaker-LAW2AAHF.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-Q37FECGF.js → claude-flow-setup-VF5NUUJZ.js} +2 -2
- package/dist/cli/chunks/client-OSUT6W6W.js +2 -0
- package/dist/cli/chunks/{cline-installer-O7GPSWES.js → cline-installer-H7RPYI3G.js} +2 -2
- package/dist/cli/chunks/{code-AEIXP2UD.js → code-COHRPYF6.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-5RXCWE5W.js → code-index-extractor-353PWY6B.js} +2 -2
- package/dist/cli/chunks/{codex-installer-HDPSP2IN.js → codex-installer-DIXHDH63.js} +2 -2
- package/dist/cli/chunks/{completions-LYTPZCND.js → completions-NGPREB6E.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-WBRRBUIA.js → complexity-analyzer-BO3QCTWT.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-6KICDS72.js → continuedev-installer-SG4HUNX6.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-2YI4SWDH.js → copilot-installer-RC6ZFHQG.js} +2 -2
- package/dist/cli/chunks/{cost-tracker-YEVYFYK5.js → cost-tracker-Q76KFISR.js} +2 -2
- package/dist/cli/chunks/{coverage-MO2TU62L.js → coverage-PT23ZOGU.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-X5EEGWMA.js +2 -0
- package/dist/cli/chunks/{cursor-installer-AO2JNN27.js → cursor-installer-ZDS65WC6.js} +2 -2
- package/dist/cli/chunks/{daemon-WCSJ3HS2.js → daemon-M32BWOES.js} +4 -4
- package/dist/cli/chunks/{daemon-6DWF4GAR.js → daemon-ZRDBUK4Q.js} +3 -3
- package/dist/cli/chunks/{dag-attention-scheduler-NI6TAE7Y.js → dag-attention-scheduler-GUPZT7PR.js} +2 -2
- package/dist/cli/chunks/{detect-3MTKRZEI.js → detect-PZNLC2CO.js} +2 -2
- package/dist/cli/chunks/{dist-node-32YFXCS3.js → dist-node-QO5MMHVF.js} +2 -2
- package/dist/cli/chunks/{domain-handler-TFVVUKSC.js → domain-handler-OH2YSZCT.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-7HWX6PVA.js → domain-transfer-TVTK2YX5.js} +2 -2
- package/dist/cli/chunks/dream-CP4VOPNU.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-GGNDGEHX.js → embed-and-insert-pattern-2ARE7NCX.js} +2 -2
- package/dist/cli/chunks/{eval-T2KWZU2L.js → eval-64RXRKM4.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-JHQPDNVK.js → experience-capture-middleware-TH7JERGY.js} +3 -3
- package/dist/cli/chunks/{fast-paths-KJQ56NG6.js → fast-paths-IAWNSJFU.js} +2 -2
- package/dist/cli/chunks/{feature-flags-DJU7Z6UH.js → feature-flags-22FDDEFG.js} +2 -2
- package/dist/cli/chunks/{feature-flags-IPK5DUQM.js → feature-flags-TAKLIOWM.js} +2 -2
- package/dist/cli/chunks/{file-discovery-G5I7VV34.js → file-discovery-QWEHC5VO.js} +2 -2
- package/dist/cli/chunks/{fleet-BRKXQGTC.js → fleet-5PQX4H2Q.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-F44UEMIK.js → gnn-wrapper-RR5EYGCL.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-4EJQ3VWP.js → heartbeat-handler-QOVPD6JV.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-MX7EHYU5.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-B7FZYZGZ.js +2 -0
- package/dist/cli/chunks/hnsw-index-7OVB67MX.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-HVFM7LAR.js → hnsw-legacy-bridge-RRTRMCEL.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-QOENX3WX.js → hnswlib-node-XEOLAMMR.js} +2 -2
- package/dist/cli/chunks/{hooks-QFQSVB2C.js → hooks-DTEIDS42.js} +34 -34
- package/dist/cli/chunks/{hybrid-router-TZPIYG3I.js → hybrid-router-E36GZC7Q.js} +2 -2
- package/dist/cli/chunks/{hypergraph-engine-HXG5GI27.js → hypergraph-engine-7VTF3N6A.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-R4LFFQ3Z.js → hypergraph-handler-CTUGX3DL.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-TG34YBHU.js +2 -0
- package/dist/cli/chunks/{init-handler-NJKVTURQ.js → init-handler-HRSUGKSE.js} +6 -6
- package/dist/cli/chunks/init-wizard-MS3A2X5C.js +2 -0
- package/dist/cli/chunks/kernel-J4IW4DA6.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-T6CMAQ6P.js → kilocode-installer-UGB5UY5B.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-IOAHUSWU.js → kiro-installer-7SAM5O2F.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-4LCYX5AN.js +2 -0
- package/dist/cli/chunks/{learning-2AH5KAFV.js → learning-GBRPEBXN.js} +3 -3
- package/dist/cli/chunks/{llm-router-I3YBDMC7.js → llm-router-YP2RW2QC.js} +4 -4
- package/dist/cli/chunks/{load-MTLOPMP4.js → load-3TRJPJBJ.js} +2 -2
- package/dist/cli/chunks/load-test-TFBVT7V3.js +2 -0
- package/dist/cli/chunks/{mcp-EEINX3NP.js → mcp-U7ZYZTEU.js} +2 -2
- package/dist/cli/chunks/{memory-OBDYP5P7.js → memory-CLBPDAAE.js} +5 -5
- package/dist/cli/chunks/memory-backend-E7OCG27P.js +2 -0
- package/dist/cli/chunks/{memory-handlers-TTMZ2JK6.js → memory-handlers-JEOU6AOR.js} +2 -2
- package/dist/cli/chunks/{multi-model-executor-OCANACFF.js → multi-model-executor-MPPD63KI.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-4PNJOOKX.js → opencode-installer-DIMXI5PK.js} +2 -2
- package/dist/cli/chunks/{orchestrator-DGIKNLST.js → orchestrator-YKOSNTFS.js} +5 -5
- package/dist/cli/chunks/{pipeline-4DZ3FRRT.js → pipeline-SDCM3CNA.js} +2 -2
- package/dist/cli/chunks/{platform-A27VETGX.js → platform-7UH4BXN7.js} +2 -2
- package/dist/cli/chunks/{plugin-SAIG2MCN.js → plugin-KIVAXJ3P.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-XBCJETFT.js → prime-radiant-advanced-wasm-PONLGWM6.js} +2 -2
- package/dist/cli/chunks/protocol-executor-MYFH7ZP4.js +2 -0
- package/dist/cli/chunks/{protocol-handler-NDOZLFK7.js → protocol-handler-6RYLLDOG.js} +2 -2
- package/dist/cli/chunks/{prove-XVUI5VJL.js → prove-PDFFRQQW.js} +2 -2
- package/dist/cli/chunks/{provider-manager-W6CZHTWY.js → provider-manager-I6R4EQGK.js} +2 -2
- package/dist/cli/chunks/qe-reasoning-bank-G46PVD2U.js +2 -0
- package/dist/cli/chunks/{quality-MRCQ7SDM.js → quality-KQVKAGWL.js} +2 -2
- package/dist/cli/chunks/queen-coordinator-ZQRKBBUH.js +2 -0
- package/dist/cli/chunks/{real-embeddings-3NBKHQSF.js → real-embeddings-VQXMPAH6.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-FPWTSZG7.js → roocode-installer-RYPQ25JO.js} +2 -2
- package/dist/cli/chunks/router-UBQULTOO.js +2 -0
- package/dist/cli/chunks/routing-feedback-3VBS3SYD.js +2 -0
- package/dist/cli/chunks/{routing-handler-SYAT3QTK.js → routing-handler-U4FEWPIN.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-Y3JV2RC4.js → ruvector-commands-YID52EZ6.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-4IS5JKSA.js → rvf-dual-writer-HABBORJW.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-FPEUOS55.js → rvf-migration-adapter-JE5NWU3J.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-FR4NHRNG.js → rvf-migration-coordinator-FBIFWTAD.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-NDKSHCMG.js +2 -0
- package/dist/cli/chunks/safe-db-ZPGX4NYW.js +2 -0
- package/dist/cli/chunks/schedule-JZUKDE6O.js +2 -0
- package/dist/cli/chunks/scheduler-7YIQOOW3.js +2 -0
- package/dist/cli/chunks/{security-EPJBWOM2.js → security-22ERFMD6.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-YU7XN6ND.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-MSUS3ROX.js → shared-rvf-dual-writer-G5VIQHSN.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-4STSI5SJ.js +2 -0
- package/dist/cli/chunks/{status-handler-7T6ZWWSG.js → status-handler-5B3FP2DN.js} +2 -2
- package/dist/cli/chunks/{structural-health-IT5COKMM.js → structural-health-6YSKVKQG.js} +2 -2
- package/dist/cli/chunks/{sync-MVC5LKWT.js → sync-2YCW23XX.js} +2 -2
- package/dist/cli/chunks/{sync-CYTAJ62F.js → sync-OFSJUYBU.js} +2 -2
- package/dist/cli/chunks/{task-handler-R5T6DQ62.js → task-handler-6OIPFSXX.js} +2 -2
- package/dist/cli/chunks/{task-handlers-BQDACRA4.js → task-handlers-6QY5Q5IH.js} +3 -3
- package/dist/cli/chunks/{test-JQ6DNHJU.js → test-VR6EP23Y.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-47CCXYB3.js → test-scheduling-OI7N5QBA.js} +3 -3
- package/dist/cli/chunks/{token-bootstrap-THINRRHA.js → token-bootstrap-HZES3TAA.js} +2 -2
- package/dist/cli/chunks/{token-usage-AQOWJPTG.js → token-usage-2NSXSNS7.js} +2 -2
- package/dist/cli/chunks/{transformers-KRVEZU55.js → transformers-4U4PX5YQ.js} +2 -2
- package/dist/cli/chunks/{tree-sitter-wasm-parser-UDOTWN4W.js → tree-sitter-wasm-parser-NQ3JYKHC.js} +2 -2
- package/dist/cli/chunks/{types-YZSDKHGD.js → types-YGTXBQ4T.js} +2 -2
- package/dist/cli/chunks/unified-memory-R72C7IBY.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-A4LOFKDQ.js +2 -0
- package/dist/cli/chunks/unified-persistence-MYD2R4LE.js +2 -0
- package/dist/cli/chunks/{upgrade-UX6VHS4H.js → upgrade-GS4EJOHW.js} +2 -2
- package/dist/cli/chunks/{validate-SUS7IEZG.js → validate-4X7OETYQ.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-E2YE6GY2.js → validate-swarm-RSVPLHZQ.js} +2 -2
- package/dist/cli/chunks/{vibium-UZMTKRTE.js → vibium-SN2J4QEA.js} +2 -2
- package/dist/cli/chunks/visual-security-CUKQ5N37.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-XXU37FYS.js → web-tree-sitter-ZO6DPXRC.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-WRTVYD3Y.js → windsurf-installer-RGSOOJSH.js} +2 -2
- package/dist/cli/chunks/{witness-chain-6OSAEH67.js → witness-chain-7XBKRDAW.js} +2 -2
- package/dist/cli/chunks/witness-chain-S7ADS6TA.js +2 -0
- package/dist/cli/chunks/{workflow-7XKEQVKT.js → workflow-H7KG5R6L.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-3GIDXU43.js +2 -0
- package/dist/cli/chunks/{wrappers-2HDILUDI.js → wrappers-3YCDNHDG.js} +2 -2
- package/dist/cli/commands/hooks-handlers/hooks-shared.js +12 -21
- package/dist/integrations/ruvector/rvf-dual-writer.d.ts +22 -0
- package/dist/integrations/ruvector/rvf-dual-writer.js +21 -0
- package/dist/integrations/ruvector/rvf-native-adapter.d.ts +18 -1
- package/dist/integrations/ruvector/rvf-native-adapter.js +15 -1
- package/dist/integrations/ruvector/shared-rvf-adapter.d.ts +46 -1
- package/dist/integrations/ruvector/shared-rvf-adapter.js +137 -0
- package/dist/kernel/hybrid-backend.d.ts +14 -3
- package/dist/kernel/hybrid-backend.js +16 -3
- package/dist/kernel/unified-memory.d.ts +3 -1
- package/dist/kernel/unified-memory.js +28 -3
- package/dist/learning/dream/dream-scheduler.d.ts +18 -0
- package/dist/learning/dream/dream-scheduler.js +68 -0
- package/dist/learning/qe-reasoning-bank.js +19 -2
- package/dist/learning/sqlite-persistence.d.ts +11 -0
- package/dist/learning/sqlite-persistence.js +30 -0
- package/dist/mcp/bundle.js +352 -346
- package/package.json +6 -2
- package/dist/cli/chunks/adapter-PSHWPJGO.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-2WOSQ42V.js +0 -2
- package/dist/cli/chunks/base-QZ6CGEZG.js +0 -2
- package/dist/cli/chunks/browser-workflow-T74U33BJ.js +0 -2
- package/dist/cli/chunks/chunk-AE7P7VDM.js +0 -9
- package/dist/cli/chunks/chunk-LVCQ4LSA.js +0 -2
- package/dist/cli/chunks/chunk-MCONVCB6.js +0 -15
- package/dist/cli/chunks/chunk-ND33EKHX.js +0 -2
- package/dist/cli/chunks/chunk-SHAXRSWJ.js +0 -2
- package/dist/cli/chunks/client-3YW2WA67.js +0 -2
- package/dist/cli/chunks/cross-domain-router-2MAV2XPY.js +0 -2
- package/dist/cli/chunks/dream-4N3YBX36.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-5KZS7T6Q.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-A4XK3GZU.js +0 -2
- package/dist/cli/chunks/hnsw-index-TI7LZBWF.js +0 -2
- package/dist/cli/chunks/impact-analyzer-NQZBRTZH.js +0 -2
- package/dist/cli/chunks/init-wizard-UZR2AKQA.js +0 -2
- package/dist/cli/chunks/kernel-2HFKLNTS.js +0 -2
- package/dist/cli/chunks/knowledge-graph-GHICW2ZM.js +0 -2
- package/dist/cli/chunks/load-test-DUOZJLRA.js +0 -2
- package/dist/cli/chunks/memory-backend-AMPSDQR7.js +0 -2
- package/dist/cli/chunks/protocol-executor-4HZSMKVG.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-OGPCKVDP.js +0 -2
- package/dist/cli/chunks/queen-coordinator-ETWOFJGR.js +0 -2
- package/dist/cli/chunks/router-OMWLL5V3.js +0 -2
- package/dist/cli/chunks/routing-feedback-SULO56IE.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-PFMHXYDR.js +0 -2
- package/dist/cli/chunks/safe-db-V34EBOPG.js +0 -2
- package/dist/cli/chunks/schedule-WJALMS5B.js +0 -2
- package/dist/cli/chunks/scheduler-CBWMQLTY.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-KOZOSWBO.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-7RV55RNF.js +0 -2
- package/dist/cli/chunks/unified-memory-FHP2C2NF.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-MI27GSUL.js +0 -2
- package/dist/cli/chunks/unified-persistence-67RJXTNL.js +0 -2
- package/dist/cli/chunks/visual-security-JF6AGYOT.js +0 -2
- package/dist/cli/chunks/witness-chain-HNY2ED2G.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-OPUU4TNV.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{k as G,o as oe}from"./chunk-46LV5MI3.js";import{b as W,d as we}from"./chunk-AL54ARD4.js";import{a as S,b as ze,c as q}from"./chunk-Q5JL7NZG.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"),I=()=>m.isGateEnabled("trustAccumulator");var le=()=>m.isGateEnabled("budgetMeter"),ue=()=>m.isGateEnabled("deterministicGateway");var T=()=>m.isGateEnabled("adversarialDefense"),x=()=>m.isGateEnabled("complianceReporter"),U=()=>m.isGateEnabled("constitutionalEnforcer"),y=()=>m.getFlags().global.strictMode;var Ie=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 Ie;function xe(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(`
|
|
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.35");process.exit(0)}
|
|
2
|
+
import{k as G,o as oe}from"./chunk-IXOGBA7C.js";import{b as W,d as we}from"./chunk-RZDMSTAQ.js";import{a as S,b as ze,c as q}from"./chunk-DEJW6GYF.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"),I=()=>m.isGateEnabled("trustAccumulator");var le=()=>m.isGateEnabled("budgetMeter"),ue=()=>m.isGateEnabled("deterministicGateway");var T=()=>m.isGateEnabled("adversarialDefense"),x=()=>m.isGateEnabled("complianceReporter"),U=()=>m.isGateEnabled("constitutionalEnforcer"),y=()=>m.getFlags().global.strictMode;var Ie=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 Ie;function xe(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
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:0,budgetRemaining:{tokens:Number.MAX_SAFE_INTEGER,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==="pause"||e.decision==="stop",r=!i,s=e.reasons.length>0?e.reasons.join("; "):void 0;if(i&&n.throttleOnExceed){let a=e.decision==="stop"?3e4:15e3;this.throttledAgents.set(t,Date.now()+a)}return{shouldContinue:r,reason:s,throttleMs:e.decision==="throttle"?5e3:e.decision==="pause"?15e3:e.decision==="stop"?3e4:void 0,escalate:i,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(!I())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(!I())return .7;let t=this.agentMetrics.get(e);return t?t.trustScore:.7}getTrustTier(e){if(!I())return"medium";let t=this.agentMetrics.get(e);return t?t.trustTier:"medium"}canHandleCriticalTask(e){if(!I())return!0;let t=m.getFlags().trustAccumulator;return this.getTrustScore(e)>=t.minTrustForCritical}getAgentMetrics(e){return I()&&this.agentMetrics.get(e)||null}selectBestAgent(e,t,n={}){if(!I()||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(!I())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(!I())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(!I())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&&(x()&&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 x()&&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 x()&&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}),x()&&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}),x()&&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=xe(e.key,e.value,e.domain,{agentId:e.agentId,tags:e.tags,supersedes:e.supersedes});return K.evaluateWrite(t)}registerPattern(e){let t=xe(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&&x()&&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&&(x()&&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&&(x()&&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(!x())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
4
|
`).replace(/\r/g,`
|
|
5
5
|
`),this.parseShard(t)}catch(t){if(t.code==="ENOENT")return null;throw t}}parseShard(e){let t=e.split(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
import{d as k,f as we}from"./chunk-
|
|
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.35");process.exit(0)}
|
|
2
|
+
import{d as k,f as we}from"./chunk-NFIOKKA6.js";import{b as C,d as Z}from"./chunk-RZDMSTAQ.js";import{a as ye}from"./chunk-PHJK33IV.js";import{c as Q}from"./chunk-BTPDHALG.js";import{a as V,c as ve}from"./chunk-DEJW6GYF.js";import{a as J,b as Xe}from"./chunk-NZB2JE2D.js";import{a as ee,d as v,e as te,f as ne}from"./chunk-FPPV7TYI.js";import{a as b,e as De}from"./chunk-UJTI5MRE.js";import{c as R,e as be}from"./chunk-HSR7EHVN.js";function A(i){if(!q.has(i))throw new Error(`Invalid table name: "${i}" is not in the allowlist`);return i}function ze(i){let e=i.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${i}" has too many parts (max: schema.table)`);for(let t of e)if(!re.test(t))throw new Error(`Invalid SQL identifier: "${i}" \u2014 part "${t}" does not match pattern ${re}`);return i}var q,re,z=R(()=>{"use strict";q=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);re=/^[a-z_][a-z0-9_]{0,62}$/});var D,se,oe,ie,ae,ce,Te,Ee,de,ue,le,pe,ge=R(()=>{"use strict";we();D=9,se=`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS schema_version (
|
|
4
4
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
5
5
|
version INTEGER NOT NULL,
|
|
@@ -551,16 +551,16 @@ import{d as k,f as we}from"./chunk-F6WQ3ES6.js";import{b as C,d as Z}from"./chun
|
|
|
551
551
|
CREATE INDEX IF NOT EXISTS idx_coverage_sessions_technique ON coverage_sessions(technique);
|
|
552
552
|
CREATE INDEX IF NOT EXISTS idx_coverage_sessions_agent ON coverage_sessions(agent_id);
|
|
553
553
|
CREATE INDEX IF NOT EXISTS idx_coverage_sessions_created ON coverage_sessions(created_at);
|
|
554
|
-
`,pe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function y(i,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?i:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function c(o,a,l,E){return o!==l?o-l:a.localeCompare(E)}return{get(){return n.value},set(o,a){let l=a??Date.now();(n.timestamp===0||c(l,i,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:l,nodeId:i,version:n.version+1,lastUpdated:Date.now()})},merge(o){let a=o.getState();this.applyState(a)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||c(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return i},getTimestamp(){return n.timestamp}}}function X(i,e){let t=y(i);return t.applyState(e),t}var j=R(()=>{"use strict"});function I(i){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[i]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[i]=(e.counts[i]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[c,o]of Object.entries(t.counts)){let a=e.counts[c]||0;o>a&&(e.counts[c]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return i},getLocalCount(){return e.counts[i]||0}}}function w(i,e){let t=I(i);return t.applyState(e),t}var U=R(()=>{"use strict"});function F(i){let e=I(i),t=I(i),n=0,c=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,c=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,c=Date.now())},merge(o){let a=o.getState();this.applyState(a)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:c}},applyState(o){let a=this.get();e.applyState(o.positive),t.applyState(o.negative);let l=this.get();a!==l&&(n=Math.max(n,o.version)+1,c=Date.now())},getNodeId(){return i}}}function x(i,e){let t=F(i);return t.applyState(e),t}var B=R(()=>{"use strict";U()});function Ue(i,e){return`${i}:${Date.now()}:${e}`}function W(i){return typeof i=="string"?`s:${i}`:typeof i=="number"?`n:${i}`:typeof i=="boolean"?`b:${i}`:`j:${JSON.stringify(i)}`}function Fe(i){let e=i.substring(0,2),t=i.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return C(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function M(i){let e=new Map,t=new Map,n=0,c=Date.now(),o=0;function a(E){let d=e.get(E);if(!d||d.size===0)return!1;let u=t.get(E);if(!u||u.size===0)return!0;for(let m of d)if(!u.has(m))return!0;return!1}function l(E){let d=e.get(E);if(!d)return new Set;let u=t.get(E)||new Set,m=new Set;for(let p of d)u.has(p)||m.add(p);return m}return{has(E){let d=W(E);return a(d)},values(){let E=[];for(let[d]of e)a(d)&&E.push(Fe(d));return E},size(){let E=0;for(let[d]of e)a(d)&&E++;return E},add(E){let d=W(E),u=Ue(i,o++);e.has(d)||e.set(d,new Set),e.get(d).add(u),n++,c=Date.now()},remove(E){let d=W(E),u=e.get(d);if(!u||u.size===0)return;t.has(d)||t.set(d,new Set);let m=t.get(d);for(let p of u)m.add(p);n++,c=Date.now()},merge(E){let d=E.getState();this.applyState(d)},getState(){let E={};for(let[u,m]of e)E[u]=Array.from(m);let d={};for(let[u,m]of t)m.size>0&&(d[u]=Array.from(m));return{elements:E,tombstones:d,version:n,lastUpdated:c}},applyState(E){let d=!1;for(let[u,m]of Object.entries(E.elements)){e.has(u)||e.set(u,new Set);let p=e.get(u);for(let S of m)p.has(S)||(p.add(S),d=!0)}for(let[u,m]of Object.entries(E.tombstones)){t.has(u)||t.set(u,new Set);let p=t.get(u);for(let S of m)p.has(S)||(p.add(S),d=!0)}d&&(n=Math.max(n,E.version)+1,c=Date.now())},getNodeId(){return i},clear(){for(let[E,d]of e){t.has(E)||t.set(E,new Set);let u=t.get(E);for(let m of d)u.add(m)}n++,c=Date.now()}}}function P(i,e){let t=M(i);return t.applyState(e),t}var Y=R(()=>{"use strict";Z()});function H(i){let e={...xe,...i},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:c}=e,o=new Map,a=new Map,l=new Map,E=new Map,d=0,u=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function S(s,r,T){let _={key:s,type:r,operation:T,timestamp:Date.now(),nodeId:t};for(let Oe of m)try{Oe(_)}catch(Ae){console.error("[CRDTStore] Error in change listener:",Ae)}}function N(s,r){d++,n&&p[s].add(r)}function K(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:u.length>0?u[u.length-1].toVersion:0,toVersion:d,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let T of p.registers){let _=o.get(T);_&&(r.registers[T]=_.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let T of p.gCounters){let _=a.get(T);_&&(r.gCounters[T]=_.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let T of p.pnCounters){let _=l.get(T);_&&(r.pnCounters[T]=_.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let T of p.sets){let _=E.get(T);_&&(r.sets[T]=_.getState())}p.sets.clear()}for(u.push(r);u.length>c;)u.shift()}let L={getRegister(s){return o.has(s)||o.set(s,y(t)),o.get(s)},setRegister(s,r){L.getRegister(s).set(r),N("registers",s),S(s,"lww-register","set")},hasRegister(s){return o.has(s)},deleteRegister(s){let r=o.delete(s);return r&&N("registers",s),r},getGCounter(s){return a.has(s)||a.set(s,I(t)),a.get(s)},incrementGCounter(s,r){L.getGCounter(s).increment(r),N("gCounters",s),S(s,"g-counter","increment")},hasGCounter(s){return a.has(s)},deleteGCounter(s){let r=a.delete(s);return r&&N("gCounters",s),r},getCounter(s){return l.has(s)||l.set(s,F(t)),l.get(s)},incrementCounter(s,r){L.getCounter(s).increment(r),N("pnCounters",s),S(s,"pn-counter","increment")},decrementCounter(s,r){L.getCounter(s).decrement(r),N("pnCounters",s),S(s,"pn-counter","decrement")},hasCounter(s){return l.has(s)},deleteCounter(s){let r=l.delete(s);return r&&N("pnCounters",s),r},getSet(s){return E.has(s)||E.set(s,M(t)),E.get(s)},addToSet(s,r){L.getSet(s).add(r),N("sets",s),S(s,"or-set","add")},removeFromSet(s,r){L.getSet(s).remove(r),N("sets",s),S(s,"or-set","remove")},hasSet(s){return E.has(s)},deleteSet(s){let r=E.delete(s);return r&&N("sets",s),r},merge(s){let r=s.getState();L.applyState(r)},getState(){K();let s={version:d,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,T]of o)s.registers[r]=T.getState();for(let[r,T]of a)s.gCounters[r]=T.getState();for(let[r,T]of l)s.pnCounters[r]=T.getState();for(let[r,T]of E)s.sets[r]=T.getState();return s},applyState(s){for(let[r,T]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(T):o.set(r,X(t,T)),N("registers",r),S(r,"lww-register","merge");for(let[r,T]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(T):a.set(r,w(t,T)),N("gCounters",r),S(r,"g-counter","merge");for(let[r,T]of Object.entries(s.pnCounters))l.has(r)?l.get(r).applyState(T):l.set(r,x(t,T)),N("pnCounters",r),S(r,"pn-counter","merge");for(let[r,T]of Object.entries(s.sets))E.has(r)?E.get(r).applyState(T):E.set(r,P(t,T)),N("sets",r),S(r,"or-set","merge");d=Math.max(d,s.version)+1},getDelta(s){if(K(),u.length===0)return s>=d,null;let r=u.filter(_=>_.toVersion>s);if(r.length===0)return null;let T={fromVersion:s,toVersion:d,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let _ of r)_.registers&&Object.assign(T.registers,_.registers),_.gCounters&&Object.assign(T.gCounters,_.gCounters),_.pnCounters&&Object.assign(T.pnCounters,_.pnCounters),_.sets&&Object.assign(T.sets,_.sets);return Object.keys(T.registers).length===0&&delete T.registers,Object.keys(T.gCounters).length===0&&delete T.gCounters,Object.keys(T.pnCounters).length===0&&delete T.pnCounters,Object.keys(T.sets).length===0&&delete T.sets,T},applyDelta(s){if(s.registers)for(let[r,T]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(T):o.set(r,X(t,T)),N("registers",r),S(r,"lww-register","merge");if(s.gCounters)for(let[r,T]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(T):a.set(r,w(t,T)),N("gCounters",r),S(r,"g-counter","merge");if(s.pnCounters)for(let[r,T]of Object.entries(s.pnCounters))l.has(r)?l.get(r).applyState(T):l.set(r,x(t,T)),N("pnCounters",r),S(r,"pn-counter","merge");if(s.sets)for(let[r,T]of Object.entries(s.sets))E.has(r)?E.get(r).applyState(T):E.set(r,P(t,T)),N("sets",r),S(r,"or-set","merge");d=Math.max(d,s.toVersion)+1},getVersion(){return d},getNodeId(){return t},on(s,r){if(s==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){m.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(o.keys())),(!s||s==="g-counter")&&r.push(...Array.from(a.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(l.keys())),(!s||s==="or-set")&&r.push(...Array.from(E.keys())),r},clear(){o.clear(),a.clear(),l.clear(),E.clear(),u.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),d=0},getStats(){return{total:o.size+a.size+l.size+E.size,registers:o.size,gCounters:a.size,pnCounters:l.size,sets:E.size,version:d,nodeId:t,deltaHistorySize:u.length}}};return L}var xe,me=R(()=>{"use strict";j();U();B();Y();xe={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var _e=R(()=>{"use strict"});var fe=R(()=>{"use strict";j();U();B();Y();me();_e()});var ke={};ve(ke,{ALLOWED_TABLE_NAMES:()=>q,BinaryHeap:()=>ee,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>Le,UnifiedHnswIndex:()=>D,UnifiedMemoryManager:()=>A,clearProjectRootCache:()=>Re,createHnswIndex:()=>te,findProjectRoot:()=>G,getDefaultDbPath:()=>he,getResolvedDefaultConfig:()=>Ce,getUnifiedMemory:()=>Ie,initializeUnifiedMemory:()=>Me,resetUnifiedMemory:()=>Pe,validateTableName:()=>O});import*as g from"fs";import*as Ne from"os";import*as f from"path";function Re(){h=null}function G(i=process.cwd()){if(h)return h;if(process.env.AQE_PROJECT_ROOT)return h=process.env.AQE_PROJECT_ROOT,h;let e=i,t=f.parse(e).root,n=e,c=null,o=null,a=null;for(;n!==t;)g.existsSync(f.join(n,".agentic-qe"))&&(c=n),g.existsSync(f.join(n,".git"))&&o===null&&(o=n),g.existsSync(f.join(n,"package.json"))&&(a=n),n=f.dirname(n);return c?h=c:o?h=o:a?h=a:h=process.cwd(),h}function he(){let i=G();return f.join(i,".agentic-qe","memory.db")}function Ce(){return{...Le,dbPath:he()}}function Ie(i){return A.getInstance(i)}async function Me(i){let e=Ie(i);return await e.initialize(),e}function Pe(){A.resetInstance()}function Ge(){if(Se)return;Se=!0;let i=()=>{try{let e=A.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",i),process.on("SIGINT",()=>{i(),process.exit(0)}),process.on("SIGTERM",()=>{i(),process.exit(0)})}var $,h,Le,A,Se,qe=R(()=>{Xe();Z();De();be();ye();z();z();ne();ne();ge();fe();$=Q.create("unified-memory"),h=null;Le={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:v.MMAP_SIZE_BYTES,cacheSize:v.CACHE_SIZE_KB,busyTimeout:v.BUSY_TIMEOUT_MS,vectorDimensions:v.DEFAULT_VECTOR_DIMENSIONS};A=class i{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new D("qe-memory");crdtStore=null;constructor(e){let t=Ce();if(this.config={...t,...e},!f.isAbsolute(this.config.dbPath)){let n=G();this.config.dbPath=f.join(n,this.config.dbPath)}}static getInstance(e){return i.instance||(i.instance=new i(e)),i.instance}static async getInstanceAsync(e){return i.instance?.initialized?i.instance:(i.instancePromise||(i.instancePromise=(async()=>{let t=i.getInstance(e);return await t.initialize(),t})()),i.instancePromise)}static resetInstance(){i.instance&&(i.instance.close(),i.instance=null),i.instancePromise=null,Re()}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{let e=process.env.AQE_PROJECT_ROOT;if(e){let o=f.resolve(this.config.dbPath),a=f.resolve(e);!o.startsWith(a)&&!o.startsWith(Ne.tmpdir())&&o.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${e}". Redirecting to test-safe path.`),this.config.dbPath=f.join(e,".agentic-qe","memory.db"))}let t=f.dirname(this.config.dbPath);g.existsSync(t)||g.mkdirSync(t,{recursive:!0});let n=g.existsSync(this.config.dbPath),c=0;if(n)c=g.statSync(this.config.dbPath).size;else if(g.existsSync(t)){let o=this.findRecentBackups(t);if(o.length>0){let a=o[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
|
|
554
|
+
`,pe=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function y(i,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?i:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function T(o,a,u,d){return o!==u?o-u:a.localeCompare(d)}return{get(){return n.value},set(o,a){let u=a??Date.now();(n.timestamp===0||T(u,i,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:u,nodeId:i,version:n.version+1,lastUpdated:Date.now()})},merge(o){let a=o.getState();this.applyState(a)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||T(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return i},getTimestamp(){return n.timestamp}}}function X(i,e){let t=y(i);return t.applyState(e),t}var j=R(()=>{"use strict"});function I(i){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[i]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[i]=(e.counts[i]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[T,o]of Object.entries(t.counts)){let a=e.counts[T]||0;o>a&&(e.counts[T]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return i},getLocalCount(){return e.counts[i]||0}}}function w(i,e){let t=I(i);return t.applyState(e),t}var U=R(()=>{"use strict"});function F(i){let e=I(i),t=I(i),n=0,T=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,T=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,T=Date.now())},merge(o){let a=o.getState();this.applyState(a)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:T}},applyState(o){let a=this.get();e.applyState(o.positive),t.applyState(o.negative);let u=this.get();a!==u&&(n=Math.max(n,o.version)+1,T=Date.now())},getNodeId(){return i}}}function x(i,e){let t=F(i);return t.applyState(e),t}var B=R(()=>{"use strict";U()});function Ue(i,e){return`${i}:${Date.now()}:${e}`}function W(i){return typeof i=="string"?`s:${i}`:typeof i=="number"?`n:${i}`:typeof i=="boolean"?`b:${i}`:`j:${JSON.stringify(i)}`}function Fe(i){let e=i.substring(0,2),t=i.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return C(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function M(i){let e=new Map,t=new Map,n=0,T=Date.now(),o=0;function a(d){let E=e.get(d);if(!E||E.size===0)return!1;let l=t.get(d);if(!l||l.size===0)return!0;for(let m of E)if(!l.has(m))return!0;return!1}function u(d){let E=e.get(d);if(!E)return new Set;let l=t.get(d)||new Set,m=new Set;for(let p of E)l.has(p)||m.add(p);return m}return{has(d){let E=W(d);return a(E)},values(){let d=[];for(let[E]of e)a(E)&&d.push(Fe(E));return d},size(){let d=0;for(let[E]of e)a(E)&&d++;return d},add(d){let E=W(d),l=Ue(i,o++);e.has(E)||e.set(E,new Set),e.get(E).add(l),n++,T=Date.now()},remove(d){let E=W(d),l=e.get(E);if(!l||l.size===0)return;t.has(E)||t.set(E,new Set);let m=t.get(E);for(let p of l)m.add(p);n++,T=Date.now()},merge(d){let E=d.getState();this.applyState(E)},getState(){let d={};for(let[l,m]of e)d[l]=Array.from(m);let E={};for(let[l,m]of t)m.size>0&&(E[l]=Array.from(m));return{elements:d,tombstones:E,version:n,lastUpdated:T}},applyState(d){let E=!1;for(let[l,m]of Object.entries(d.elements)){e.has(l)||e.set(l,new Set);let p=e.get(l);for(let S of m)p.has(S)||(p.add(S),E=!0)}for(let[l,m]of Object.entries(d.tombstones)){t.has(l)||t.set(l,new Set);let p=t.get(l);for(let S of m)p.has(S)||(p.add(S),E=!0)}E&&(n=Math.max(n,d.version)+1,T=Date.now())},getNodeId(){return i},clear(){for(let[d,E]of e){t.has(d)||t.set(d,new Set);let l=t.get(d);for(let m of E)l.add(m)}n++,T=Date.now()}}}function P(i,e){let t=M(i);return t.applyState(e),t}var Y=R(()=>{"use strict";Z()});function H(i){let e={...xe,...i},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:T}=e,o=new Map,a=new Map,u=new Map,d=new Map,E=0,l=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function S(s,r,c){let _={key:s,type:r,operation:c,timestamp:Date.now(),nodeId:t};for(let Ae of m)try{Ae(_)}catch(Oe){console.error("[CRDTStore] Error in change listener:",Oe)}}function N(s,r){E++,n&&p[s].add(r)}function K(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:l.length>0?l[l.length-1].toVersion:0,toVersion:E,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let c of p.registers){let _=o.get(c);_&&(r.registers[c]=_.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let c of p.gCounters){let _=a.get(c);_&&(r.gCounters[c]=_.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let c of p.pnCounters){let _=u.get(c);_&&(r.pnCounters[c]=_.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let c of p.sets){let _=d.get(c);_&&(r.sets[c]=_.getState())}p.sets.clear()}for(l.push(r);l.length>T;)l.shift()}let L={getRegister(s){return o.has(s)||o.set(s,y(t)),o.get(s)},setRegister(s,r){L.getRegister(s).set(r),N("registers",s),S(s,"lww-register","set")},hasRegister(s){return o.has(s)},deleteRegister(s){let r=o.delete(s);return r&&N("registers",s),r},getGCounter(s){return a.has(s)||a.set(s,I(t)),a.get(s)},incrementGCounter(s,r){L.getGCounter(s).increment(r),N("gCounters",s),S(s,"g-counter","increment")},hasGCounter(s){return a.has(s)},deleteGCounter(s){let r=a.delete(s);return r&&N("gCounters",s),r},getCounter(s){return u.has(s)||u.set(s,F(t)),u.get(s)},incrementCounter(s,r){L.getCounter(s).increment(r),N("pnCounters",s),S(s,"pn-counter","increment")},decrementCounter(s,r){L.getCounter(s).decrement(r),N("pnCounters",s),S(s,"pn-counter","decrement")},hasCounter(s){return u.has(s)},deleteCounter(s){let r=u.delete(s);return r&&N("pnCounters",s),r},getSet(s){return d.has(s)||d.set(s,M(t)),d.get(s)},addToSet(s,r){L.getSet(s).add(r),N("sets",s),S(s,"or-set","add")},removeFromSet(s,r){L.getSet(s).remove(r),N("sets",s),S(s,"or-set","remove")},hasSet(s){return d.has(s)},deleteSet(s){let r=d.delete(s);return r&&N("sets",s),r},merge(s){let r=s.getState();L.applyState(r)},getState(){K();let s={version:E,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,c]of o)s.registers[r]=c.getState();for(let[r,c]of a)s.gCounters[r]=c.getState();for(let[r,c]of u)s.pnCounters[r]=c.getState();for(let[r,c]of d)s.sets[r]=c.getState();return s},applyState(s){for(let[r,c]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(c):o.set(r,X(t,c)),N("registers",r),S(r,"lww-register","merge");for(let[r,c]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(c):a.set(r,w(t,c)),N("gCounters",r),S(r,"g-counter","merge");for(let[r,c]of Object.entries(s.pnCounters))u.has(r)?u.get(r).applyState(c):u.set(r,x(t,c)),N("pnCounters",r),S(r,"pn-counter","merge");for(let[r,c]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(c):d.set(r,P(t,c)),N("sets",r),S(r,"or-set","merge");E=Math.max(E,s.version)+1},getDelta(s){if(K(),l.length===0)return s>=E,null;let r=l.filter(_=>_.toVersion>s);if(r.length===0)return null;let c={fromVersion:s,toVersion:E,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let _ of r)_.registers&&Object.assign(c.registers,_.registers),_.gCounters&&Object.assign(c.gCounters,_.gCounters),_.pnCounters&&Object.assign(c.pnCounters,_.pnCounters),_.sets&&Object.assign(c.sets,_.sets);return Object.keys(c.registers).length===0&&delete c.registers,Object.keys(c.gCounters).length===0&&delete c.gCounters,Object.keys(c.pnCounters).length===0&&delete c.pnCounters,Object.keys(c.sets).length===0&&delete c.sets,c},applyDelta(s){if(s.registers)for(let[r,c]of Object.entries(s.registers))o.has(r)?o.get(r).applyState(c):o.set(r,X(t,c)),N("registers",r),S(r,"lww-register","merge");if(s.gCounters)for(let[r,c]of Object.entries(s.gCounters))a.has(r)?a.get(r).applyState(c):a.set(r,w(t,c)),N("gCounters",r),S(r,"g-counter","merge");if(s.pnCounters)for(let[r,c]of Object.entries(s.pnCounters))u.has(r)?u.get(r).applyState(c):u.set(r,x(t,c)),N("pnCounters",r),S(r,"pn-counter","merge");if(s.sets)for(let[r,c]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(c):d.set(r,P(t,c)),N("sets",r),S(r,"or-set","merge");E=Math.max(E,s.toVersion)+1},getVersion(){return E},getNodeId(){return t},on(s,r){if(s==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){m.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(o.keys())),(!s||s==="g-counter")&&r.push(...Array.from(a.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(u.keys())),(!s||s==="or-set")&&r.push(...Array.from(d.keys())),r},clear(){o.clear(),a.clear(),u.clear(),d.clear(),l.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),E=0},getStats(){return{total:o.size+a.size+u.size+d.size,registers:o.size,gCounters:a.size,pnCounters:u.size,sets:d.size,version:E,nodeId:t,deltaHistorySize:l.length}}};return L}var xe,me=R(()=>{"use strict";j();U();B();Y();xe={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var _e=R(()=>{"use strict"});var fe=R(()=>{"use strict";j();U();B();Y();me();_e()});var ke={};be(ke,{ALLOWED_TABLE_NAMES:()=>q,BinaryHeap:()=>ee,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>Le,UnifiedHnswIndex:()=>v,UnifiedMemoryManager:()=>O,clearProjectRootCache:()=>Re,createHnswIndex:()=>te,findProjectRoot:()=>G,getDefaultDbPath:()=>he,getResolvedDefaultConfig:()=>Ce,getUnifiedMemory:()=>Ie,initializeUnifiedMemory:()=>Me,resetUnifiedMemory:()=>Pe,validateTableName:()=>A});import*as g from"fs";import*as Ne from"os";import*as f from"path";function Re(){h=null}function G(i=process.cwd()){if(h)return h;if(process.env.AQE_PROJECT_ROOT)return h=process.env.AQE_PROJECT_ROOT,h;let e=i,t=f.parse(e).root,n=e,T=null,o=null,a=null;for(;n!==t;)g.existsSync(f.join(n,".agentic-qe"))&&(T=n),g.existsSync(f.join(n,".git"))&&o===null&&(o=n),g.existsSync(f.join(n,"package.json"))&&(a=n),n=f.dirname(n);return T?h=T:o?h=o:a?h=a:h=process.cwd(),h}function he(){let i=G();return f.join(i,".agentic-qe","memory.db")}function Ce(){return{...Le,dbPath:he()}}function Ie(i){return O.getInstance(i)}async function Me(i){let e=Ie(i);return await e.initialize(),e}function Pe(){O.resetInstance()}function Ge(){if(Se)return;Se=!0;let i=()=>{try{let e=O.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",i),process.on("SIGINT",()=>{i(),process.exit(0)}),process.on("SIGTERM",()=>{i(),process.exit(0)})}var $,h,Le,O,Se,qe=R(()=>{Xe();Z();ve();De();ye();z();z();ne();ne();ge();fe();$=Q.create("unified-memory"),h=null;Le={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:b.MMAP_SIZE_BYTES,cacheSize:b.CACHE_SIZE_KB,busyTimeout:b.BUSY_TIMEOUT_MS,vectorDimensions:b.DEFAULT_VECTOR_DIMENSIONS};O=class i{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new v("qe-memory");crdtStore=null;constructor(e){let t=Ce();if(this.config={...t,...e},!f.isAbsolute(this.config.dbPath)){let n=G();this.config.dbPath=f.join(n,this.config.dbPath)}}static getInstance(e){return i.instance||(i.instance=new i(e)),i.instance}static async getInstanceAsync(e){return i.instance?.initialized?i.instance:(i.instancePromise||(i.instancePromise=(async()=>{let t=i.getInstance(e);return await t.initialize(),t})()),i.instancePromise)}static resetInstance(){i.instance&&(i.instance.close(),i.instance=null),i.instancePromise=null,Re()}async initialize(e){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize(e?.signal)),this.initPromise}async _doInitialize(e){if(!this.initialized){e?.throwIfAborted();try{let t=process.env.AQE_PROJECT_ROOT;if(t){let a=f.resolve(this.config.dbPath),u=f.resolve(t);!a.startsWith(u)&&!a.startsWith(Ne.tmpdir())&&a.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${t}". Redirecting to test-safe path.`),this.config.dbPath=f.join(t,".agentic-qe","memory.db"))}let n=f.dirname(this.config.dbPath);g.existsSync(n)||g.mkdirSync(n,{recursive:!0});let T=g.existsSync(this.config.dbPath),o=0;if(T)o=g.statSync(this.config.dbPath).size;else if(g.existsSync(n)){let a=this.findRecentBackups(n);if(a.length>0){let u=a[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
|
|
555
555
|
Expected: ${this.config.dbPath}
|
|
556
|
-
Found ${
|
|
557
|
-
Restoring from backup to prevent data loss...`),g.copyFileSync(
|
|
558
|
-
DB was ${(
|
|
556
|
+
Found ${a.length} backup(s), newest: ${u.path} (${(u.size/1024/1024).toFixed(1)}MB)
|
|
557
|
+
Restoring from backup to prevent data loss...`),g.copyFileSync(u.path,this.config.dbPath);for(let d of["-wal","-shm"]){let E=this.config.dbPath+d;g.existsSync(E)&&g.unlinkSync(E)}o=u.size}}if(e?.throwIfAborted(),this.db=J(this.config.dbPath,{walMode:this.config.walMode,busyTimeout:this.config.busyTimeout}),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.db.pragma("foreign_keys = ON"),e?.aborted){try{this.db.close()}catch{}this.db=null,e.throwIfAborted()}if(await this.runMigrations(),e?.throwIfAborted(),T&&o>1e6)try{let a=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(a&&a.cnt===0){let u=g.statSync(this.config.dbPath).size;u<o*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
|
|
558
|
+
DB was ${(o/1024/1024).toFixed(1)}MB, now ${(u/1024/1024).toFixed(1)}MB with 0 patterns.
|
|
559
559
|
This looks like the DB was replaced with an empty schema.
|
|
560
|
-
Check backups in ${
|
|
560
|
+
Check backups in ${n} and restore manually.`)}}catch{}this.vectorsLoaded=!1,this.initialized=!0,console.log(`[UnifiedMemory] Initialized: ${this.config.dbPath}`),this.warnIfDuplicateDatabases()}catch(t){throw this.initPromise=null,t instanceof Error&&(t.name==="AbortError"||(e?.aborted??!1))?t:new Error(`Failed to initialize UnifiedMemoryManager: ${V(t)}`)}}}findRecentBackups(e){try{let n=g.readdirSync(e).filter(o=>o.startsWith("memory")&&o.endsWith(".db")&&o!=="memory.db").map(o=>{let a=f.join(e,o),u=g.statSync(a);return{path:a,size:u.size,mtime:u.mtimeMs}}).filter(o=>o.size>1e6).sort((o,a)=>a.mtime-o.mtime),T=f.join(e,"backups");if(g.existsSync(T)){let o=g.readdirSync(T);for(let a of o)if(a.endsWith(".db")){let u=f.join(T,a),d=g.statSync(u);d.size>1e6&&n.push({path:u,size:d.size,mtime:d.mtimeMs})}n.sort((a,u)=>u.mtime-a.mtime)}return n}catch{return[]}}warnIfDuplicateDatabases(){try{let e=G(),t=f.resolve(this.config.dbPath),T=[f.join(e,".agentic-qe","memory.db"),f.join(e,"v3",".agentic-qe","memory.db")].map(o=>f.resolve(o)).filter(o=>o!==t&&g.existsSync(o));T.length>0&&console.warn(`[UnifiedMemory] WARNING: Duplicate database(s) detected!
|
|
561
561
|
Canonical: ${t}
|
|
562
|
-
Duplicates: ${
|
|
563
|
-
This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){$.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=
|
|
562
|
+
Duplicates: ${T.join(", ")}
|
|
563
|
+
This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){$.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=A(e);return this.db.prepare(`PRAGMA table_info(${n})`).all().some(o=>o.name===t)}catch(n){return $.debug("Column existence check failed",{table:e,column:t,error:n instanceof Error?n.message:String(n)}),!1}}handleV2SchemaIncompatibilities(){if(!this.db)return;let e=[{table:"goap_plans",requiredColumn:"status",columnDef:"TEXT DEFAULT 'pending'"},{table:"goap_actions",requiredColumn:"agent_type",columnDef:"TEXT DEFAULT 'unknown'"},{table:"concept_nodes",requiredColumn:"concept_type",columnDef:"TEXT DEFAULT 'general'"},{table:"concept_edges",requiredColumn:"edge_type",columnDef:"TEXT DEFAULT 'related'"},{table:"dream_insights",requiredColumn:"cycle_id",columnDef:"TEXT DEFAULT ''"},{table:"rl_q_values",requiredColumn:"algorithm",columnDef:"TEXT DEFAULT 'q-learning'"}];for(let{table:t,requiredColumn:n,columnDef:T}of e)if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)&&!this.columnExists(t,n)){let a=A(t);try{this.db.exec(`ALTER TABLE ${a} ADD COLUMN ${n} ${T}`),console.log(`[UnifiedMemory] Added column ${n} to ${t} (safe migration)`)}catch(u){console.log(`[UnifiedMemory] Column ${n} on ${t}: ${u instanceof Error?u.message:String(u)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(se),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<D&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${D}`),this.db.transaction(()=>{t<1&&this.db.exec(oe),t<2&&this.db.exec(ie),t<3&&(this.db.exec(ae),this.db.exec(ce),this.db.exec(Te)),t<4&&this.db.exec(Ee),t<5&&this.db.exec(de),t<6&&this.db.exec(k),t<7&&this.db.exec(ue),t<8&&this.db.exec(le),t<9&&(this.db.exec(`
|
|
564
564
|
CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
|
|
565
565
|
name, description, pattern_type, qe_domain,
|
|
566
566
|
content='qe_patterns',
|
|
@@ -589,7 +589,7 @@ import{d as k,f as we}from"./chunk-F6WQ3ES6.js";import{b as C,d as Z}from"./chun
|
|
|
589
589
|
`)),this.db.prepare(`
|
|
590
590
|
INSERT OR REPLACE INTO schema_version (id, version, migrated_at)
|
|
591
591
|
VALUES (1, ?, datetime('now'))
|
|
592
|
-
`).run(
|
|
592
|
+
`).run(D)})(),console.log("[UnifiedMemory] Migration complete"))}async loadVectorIndex(){if(this.vectorsLoaded)return;if(!this.db)throw new Error("Database not initialized");this.vectorIndex.clear();let e=this.db.prepare("SELECT id, embedding, dimensions FROM vectors").all();for(let t of e){let n=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,n)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,n="default",T){this.ensureInitialized();let o=T?Date.now()+T*1e3:null,a=JSON.stringify(t);this.db.prepare(`
|
|
593
593
|
INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at)
|
|
594
594
|
VALUES (?, ?, ?, ?)
|
|
595
595
|
`).run(e,n,a,o)}async kvGet(e,t="default"){this.ensureInitialized();let n=this.db.prepare(`
|
|
@@ -598,14 +598,14 @@ import{d as k,f as we}from"./chunk-F6WQ3ES6.js";import{b as C,d as Z}from"./chun
|
|
|
598
598
|
`).get(e,t);if(n){if(n.expires_at&&Date.now()>n.expires_at){this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t);return}return C(n.value)}}async kvDelete(e,t="default"){return this.ensureInitialized(),this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t).changes>0}async kvExists(e,t="default"){return this.ensureInitialized(),this.db.prepare(`
|
|
599
599
|
SELECT 1 FROM kv_store
|
|
600
600
|
WHERE key = ? AND namespace = ? AND (expires_at IS NULL OR expires_at > ?)
|
|
601
|
-
`).get(e,t,Date.now())!==void 0}async kvSearch(e,t="default",n=100){this.ensureInitialized();let
|
|
601
|
+
`).get(e,t,Date.now())!==void 0}async kvSearch(e,t="default",n=100){this.ensureInitialized();let T=e.replace(/\*/g,"%").replace(/\?/g,"_");return this.db.prepare(`
|
|
602
602
|
SELECT key FROM kv_store
|
|
603
603
|
WHERE namespace = ? AND key LIKE ?
|
|
604
604
|
AND (expires_at IS NULL OR expires_at > ?)
|
|
605
605
|
LIMIT ?
|
|
606
|
-
`).all(t,
|
|
606
|
+
`).all(t,T,Date.now(),n).map(a=>a.key)}async kvCleanupExpired(){return this.ensureInitialized(),this.db.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now()).changes}async vectorStore(e,t,n="default",T){this.ensureInitialized();let o=this.floatArrayToBuffer(t),a=T?JSON.stringify(T):null;this.db.prepare(`
|
|
607
607
|
INSERT OR REPLACE INTO vectors (id, namespace, embedding, dimensions, metadata, updated_at)
|
|
608
608
|
VALUES (?, ?, ?, ?, ?, datetime('now'))
|
|
609
609
|
`).run(e,n,o,t.length,a),this.vectorIndex.add(e,t)}async vectorGet(e){this.ensureInitialized();let t=this.db.prepare(`
|
|
610
610
|
SELECT embedding, dimensions, metadata FROM vectors WHERE id = ?
|
|
611
|
-
`).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?C(t.metadata):void 0}}async vectorDelete(e){this.ensureInitialized();let t=this.db.prepare("DELETE FROM vectors WHERE id = ?").run(e);return this.vectorIndex.remove(e),t.changes>0}async vectorSearch(e,t=10,n){this.ensureInitialized(),this.vectorsLoaded||await this.loadVectorIndex();let
|
|
611
|
+
`).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?C(t.metadata):void 0}}async vectorDelete(e){this.ensureInitialized();let t=this.db.prepare("DELETE FROM vectors WHERE id = ?").run(e);return this.vectorIndex.remove(e),t.changes>0}async vectorSearch(e,t=10,n){this.ensureInitialized(),this.vectorsLoaded||await this.loadVectorIndex();let T=this.vectorIndex.search(e,t*2);if(T.length===0)return[];let o=T.map(E=>E.id),a=o.map(()=>"?").join(","),u=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${a})`).all(...o),d=new Map(u.map(E=>[E.id,E]));if(n){let E=[];for(let l of T){let m=d.get(l.id);if(m&&m.namespace===n&&(E.push({id:l.id,score:l.score,metadata:m.metadata?C(m.metadata):void 0}),E.length>=t))break}return E}return T.slice(0,t).map(E=>{let l=d.get(E.id);return{id:E.id,score:E.score,metadata:l?.metadata?C(l.metadata):void 0}})}async vectorCount(e){return this.ensureInitialized(),e?this.db.prepare("SELECT COUNT(*) as count FROM vectors WHERE namespace = ?").get(e).count:this.db.prepare("SELECT COUNT(*) as count FROM vectors").get().count}queryCount(e){this.ensureInitialized();let t=A(e);return this.db.prepare(`SELECT COUNT(*) as c FROM ${t}`).get().c}initializeCRDT(e){if(this.crdtStore){console.warn("[UnifiedMemory] CRDT store already initialized");return}this.crdtStore=H({nodeId:e}),console.log(`[UnifiedMemory] CRDT store initialized for node: ${e}`)}getCRDTStore(){return this.crdtStore}isCRDTInitialized(){return this.crdtStore!==null}async crdtSet(e,t,n="crdt"){this.ensureInitialized(),this.crdtStore&&this.crdtStore.setRegister(e,t),await this.kvSet(e,t,n)}async crdtGet(e,t="crdt"){if(this.crdtStore){let n=this.crdtStore.getRegister(e);if(n)return n.get()}return this.kvGet(e,t)}crdtIncrement(e,t=1){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");let n=this.crdtStore.getCounter(e);n||(this.crdtStore.incrementCounter(e,0),n=this.crdtStore.getCounter(e));for(let T=0;T<t;T++)this.crdtStore.incrementCounter(e)}crdtGetCounter(e){return this.crdtStore?this.crdtStore.getCounter(e)?.get()??0:0}crdtAddToSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.addToSet(e,t)}crdtRemoveFromSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.removeFromSet(e,t)}crdtGetSet(e){if(!this.crdtStore)return new Set;let t=this.crdtStore.getSet(e);return new Set(t.values())}crdtGetState(){return this.crdtStore?this.crdtStore.getState():null}crdtGetDelta(e){return this.crdtStore?this.crdtStore.getDelta(e??0):null}crdtMerge(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyState(e)}crdtApplyDelta(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyDelta(e)}async crdtPersist(){if(!this.crdtStore)return;let e=this.crdtStore.getState();await this.kvSet("__crdt_state__",e,"crdt-internal")}async crdtRestore(){if(!this.crdtStore)return!1;let e=await this.kvGet("__crdt_state__","crdt-internal");return e?(this.crdtStore.applyState(e),!0):!1}getDatabase(){if(!this.db||!this.initialized)throw new Error("UnifiedMemoryManager not initialized");return this.db}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.db)throw new Error("Database not initialized");let n=this.preparedStatements.get(e);return n||(n=this.db.prepare(t),this.preparedStatements.set(e,n)),n}transaction(e){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(e)()}getStats(){if(!this.db)throw new Error("Database not initialized");let e=pe.map(T=>{try{let o=this.db.prepare(`SELECT COUNT(*) as count FROM ${T}`).get();return{name:T,rowCount:o.count}}catch(o){return $.debug("Table row count query failed",{table:T,error:o instanceof Error?o.message:String(o)}),{name:T,rowCount:0}}}),t=0,n=0;try{g.existsSync(this.config.dbPath)&&(t=g.statSync(this.config.dbPath).size);let T=this.config.dbPath+"-wal";g.existsSync(T)&&(n=g.statSync(T).size)}catch(T){console.debug("[UnifiedMemory] File stat error:",T instanceof Error?T.message:T)}return{tables:e,fileSize:t,walSize:n,vectorIndexSize:this.vectorIndex.size()}}vacuum(){if(!this.db)throw new Error("Database not initialized");this.db.exec("VACUUM")}checkpoint(){if(!this.db)throw new Error("Database not initialized");this.db.pragma("wal_checkpoint(TRUNCATE)")}close(){this.db&&(this.preparedStatements.clear(),this.vectorIndex.clear(),this.db.close(),this.db=null,this.initialized=!1,console.log("[UnifiedMemory] Database closed"))}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("UnifiedMemoryManager not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=new Float32Array(e.buffer,e.byteOffset,t);return Array.from(n)}};Se=!1;Ge()});export{q as a,A as b,ze as c,z as d,Re as e,G as f,he as g,Le as h,Ce as i,O as j,Ie as k,Me as l,Pe as m,ke as n,qe as o};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.9.
|
|
2
|
-
var e=null,f=null,t=null,u=!1;async function M(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-
|
|
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.35");process.exit(0)}
|
|
2
|
+
var e=null,f=null,t=null,u=!1;async function M(){return u&&!t?e:t||(t=(async()=>{try{if(process.env.AQE_RVF_MODE==="sqlite-only")return null;let{isRvfNativeAvailable:d}=await import("./rvf-native-adapter-NDKSHCMG.js");if(!d())return null;let{getUnifiedMemory:v}=await import("./unified-memory-R72C7IBY.js"),l=v().getDatabase();if(!l)return null;let{RvfDualWriter:p}=await import("./rvf-dual-writer-HABBORJW.js"),o=new p(l,{rvfPath:".agentic-qe/brain.rvf",mode:"dual-write",dimensions:384});await o.initialize(),e=o;try{let{getRvfMigrationStage:g}=await import("./feature-flags-TAKLIOWM.js"),n=g();if(n>=2){let{RvfMigrationAdapter:m}=await import("./rvf-migration-adapter-JE5NWU3J.js"),s=new m({stage:n});s.setSqliteDb(l);let{getSharedRvfAdapter:R}=await import("./shared-rvf-adapter-YU7XN6ND.js"),i=R();if(i){let y={ingest:a=>i.ingest(a),search:(a,D)=>i.search(a,D).map(c=>({id:c.id,score:c.score})),delete:a=>i.delete(a),status:()=>i.status(),close:()=>{}};s.setRvfStore(y)}f=s,console.log(`[RVF] Migration adapter active at stage ${n} (${["sqlite-only","hybrid","dual-sqlite","dual-rvf","rvf-primary"][n]})`)}}catch{}return o}catch(r){return(process.env.DEBUG||process.env.AQE_VERBOSE)&&console.debug("[RVF] Dual-writer init failed, degrading to sqlite-only:",r instanceof Error?r.message:r),null}finally{u=!0,t=null,import("./base-7SMQWXHT.js").then(({registerRvfResetFn:r})=>r(h)).catch(()=>{})}})(),t)}function w(){return e}function W(){return f}function h(){if(e){try{e.close()}catch{}e=null}f=null,t=null,u=!1}export{M as a,w as b,W as c,h as d};
|