agentic-qe 3.12.2 → 3.13.0
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/helpers/.helpers-version +1 -1
- package/.claude/helpers/auto-memory-hook.mjs +430 -430
- package/.claude/helpers/helpers.manifest.json +6 -5
- package/.claude/helpers/hook-handler.cjs +565 -311
- package/.claude/helpers/intelligence.cjs +1058 -1058
- package/.claude/helpers/statusline.cjs +995 -682
- package/.claude/skills/qe-court/SKILL.md +186 -0
- package/.claude/skills/qe-court/config.json +27 -0
- package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +38 -0
- package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.test.ts +21 -0
- package/.claude/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.ts +25 -0
- package/.claude/skills/qe-court/evals/qe-court.yaml +70 -0
- package/.claude/skills/qe-court/schemas/output.json +92 -0
- package/.claude/skills/qe-court/scripts/validate-config.json +30 -0
- package/.claude/skills/skills-manifest.json +9 -8
- package/CHANGELOG.md +104 -0
- package/README.md +3 -3
- package/assets/skills/qe-court/SKILL.md +186 -0
- package/assets/skills/qe-court/config.json +27 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/README.md +38 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.test.ts +21 -0
- package/assets/skills/qe-court/evals/fixtures/seeded-mutant-delivery/budget.ts +25 -0
- package/assets/skills/qe-court/evals/qe-court.yaml +70 -0
- package/assets/skills/qe-court/schemas/output.json +92 -0
- package/assets/skills/qe-court/scripts/validate-config.json +30 -0
- package/assets/skills/skills-manifest.json +9 -8
- package/dist/cli/bundle.js +5 -5
- package/dist/cli/chunks/adapter-CWIMFWAI.js +2 -0
- package/dist/cli/chunks/{agent-booster-wasm-3KYNICBC.js → agent-booster-wasm-ACX2DK7Y.js} +2 -2
- package/dist/cli/chunks/{agent-handler-NGPTMI6E.js → agent-handler-B45WP4ZJ.js} +2 -2
- package/dist/cli/chunks/{agent-memory-branch-GNTQKQMG.js → agent-memory-branch-QQLZDE56.js} +2 -2
- package/dist/cli/chunks/aqe-learning-engine-OTXT2DLN.js +2 -0
- package/dist/cli/chunks/{arena-HQEP2NWI.js → arena-G3IKZAG5.js} +4 -4
- package/dist/cli/chunks/{arena-PA7VIYD4.js → arena-SDB7723R.js} +2 -2
- package/dist/cli/chunks/{audit-XSDM57GC.js → audit-GY46XUZA.js} +3 -3
- package/dist/cli/chunks/base-O3SPSWBA.js +2 -0
- package/dist/cli/chunks/{hnswlib-node-BCASOCNU.js → better-sqlite3-DUZ6FFAH.js} +2 -2
- package/dist/cli/chunks/brain-handler-347CYMPN.js +89 -0
- package/dist/cli/chunks/{branch-enumerator-ZW7RNMUF.js → branch-enumerator-Z3ULBFSM.js} +2 -2
- package/dist/cli/chunks/{browser-4LU22CPP.js → browser-OYEIHD7F.js} +2 -2
- package/dist/cli/chunks/browser-workflow-MXS3ZKY2.js +2 -0
- package/dist/cli/chunks/{chunk-CKFZOPZN.js → chunk-2DIT5AUU.js} +2 -2
- package/dist/cli/chunks/{chunk-RXH2TC2K.js → chunk-2NRZYQSF.js} +2 -2
- package/dist/cli/chunks/chunk-2VQVEQS4.js +153 -0
- package/dist/cli/chunks/{chunk-KDGLNJPB.js → chunk-32ZGV4Q4.js} +1 -1
- package/dist/cli/chunks/{chunk-327YEKBU.js → chunk-34PEINFS.js} +2 -2
- package/dist/cli/chunks/{chunk-CTFW7CMI.js → chunk-3GSYD5SL.js} +2 -2
- package/dist/cli/chunks/{chunk-YRO7HNS4.js → chunk-3JVUWKCO.js} +2 -2
- package/dist/cli/chunks/{chunk-TERRRQVY.js → chunk-3K4SF57Q.js} +1 -1
- package/dist/cli/chunks/{chunk-6N62KS3C.js → chunk-3NOCK6ED.js} +2 -2
- package/dist/cli/chunks/{chunk-7DV42KFP.js → chunk-3UHEZ5HZ.js} +2 -2
- package/dist/cli/chunks/{chunk-N57BKUVE.js → chunk-4BDLD7V2.js} +1 -1
- package/dist/cli/chunks/{chunk-5SM57X4D.js → chunk-4BESADKE.js} +2 -2
- package/dist/cli/chunks/{chunk-GCQATSMK.js → chunk-54MFKCLT.js} +2 -2
- package/dist/cli/chunks/{chunk-GUGUYFU5.js → chunk-56WZFXTQ.js} +2 -2
- package/dist/cli/chunks/{chunk-OELLHV7S.js → chunk-5EIOQCGN.js} +2 -2
- package/dist/cli/chunks/{chunk-Z63IOTDW.js → chunk-5FLTZ3KT.js} +2 -2
- package/dist/cli/chunks/{chunk-EKTWIEEO.js → chunk-5ICQL42E.js} +2 -2
- package/dist/cli/chunks/{chunk-VQU2JXTK.js → chunk-5KAT6WBQ.js} +2 -2
- package/dist/cli/chunks/{chunk-VHYACXLN.js → chunk-6AOBLBR4.js} +2 -2
- package/dist/cli/chunks/{chunk-Z3FA5KR6.js → chunk-6DTOGSDV.js} +4 -4
- package/dist/cli/chunks/{chunk-SYLTJKN2.js → chunk-6SXKCIN5.js} +2 -2
- package/dist/cli/chunks/{chunk-MF4FULAI.js → chunk-7DMXCCSD.js} +1 -1
- package/dist/cli/chunks/{chunk-BOR5MME3.js → chunk-7UNY32PU.js} +1 -1
- package/dist/cli/chunks/{chunk-T6TQPF5P.js → chunk-7YXT6BXN.js} +3 -3
- package/dist/cli/chunks/{chunk-ADZTWGEB.js → chunk-A4QLGPYO.js} +2 -2
- package/dist/cli/chunks/{chunk-RFQIC6ZF.js → chunk-A7GLWWSE.js} +1 -1
- package/dist/cli/chunks/{chunk-WC5PM33J.js → chunk-ANIDFJCT.js} +3 -3
- package/dist/cli/chunks/{chunk-TFVWUR2U.js → chunk-ANYYTWOQ.js} +2 -2
- package/dist/cli/chunks/{chunk-YZ44FUVJ.js → chunk-AO7AHX6K.js} +2 -2
- package/dist/cli/chunks/{chunk-PHIEJAQK.js → chunk-BCKTBGDM.js} +3 -3
- package/dist/cli/chunks/{chunk-GECWGFRR.js → chunk-BGYLNCL6.js} +2 -2
- package/dist/cli/chunks/{chunk-PXKVW6PT.js → chunk-BOVH6WSM.js} +2 -2
- package/dist/cli/chunks/{chunk-P65S7AZA.js → chunk-BUGWPTMF.js} +2 -2
- package/dist/cli/chunks/{chunk-RXEQB4OT.js → chunk-CFVEDUTW.js} +2 -2
- package/dist/cli/chunks/{chunk-HNU32LN3.js → chunk-CPH5JP4L.js} +1 -1
- package/dist/cli/chunks/{chunk-LIAW5FD7.js → chunk-CQFT7H3F.js} +2 -2
- package/dist/cli/chunks/{chunk-WY5CX3VH.js → chunk-CWUBOLKY.js} +2 -2
- package/dist/cli/chunks/{chunk-X47GHZY3.js → chunk-CYL2FV23.js} +2 -2
- package/dist/cli/chunks/{chunk-W7LBT3BF.js → chunk-D3MPV5G7.js} +2 -2
- package/dist/cli/chunks/{chunk-7KMYBRKJ.js → chunk-DRIJYTSK.js} +2 -2
- package/dist/cli/chunks/{chunk-BDVOXGY5.js → chunk-DYUC7WFA.js} +1 -1
- package/dist/cli/chunks/{chunk-ZBYMF2QJ.js → chunk-E3B5XTXJ.js} +1 -1
- package/dist/cli/chunks/{chunk-TMQ3S7HR.js → chunk-EECM5XKY.js} +1 -1
- package/dist/cli/chunks/{chunk-7OD6HFCP.js → chunk-EFRESRLB.js} +3 -3
- package/dist/cli/chunks/{chunk-HU6ETNA7.js → chunk-ES7WCYOU.js} +1 -1
- package/dist/cli/chunks/chunk-FAQLI3P5.js +2 -0
- package/dist/cli/chunks/{chunk-K43YXI7C.js → chunk-FBBZHATF.js} +2 -2
- package/dist/cli/chunks/{chunk-2R7J4ZGT.js → chunk-FL3BM54K.js} +1 -1
- package/dist/cli/chunks/{chunk-KBXW7S3W.js → chunk-FQLWQWRU.js} +3 -3
- package/dist/cli/chunks/{chunk-LWVUNBZO.js → chunk-FQY3UTGA.js} +2 -2
- package/dist/cli/chunks/{chunk-2L7K2J2T.js → chunk-FUU32QY5.js} +2 -2
- package/dist/cli/chunks/{chunk-3LELACAQ.js → chunk-G4GTE3RJ.js} +2 -2
- package/dist/cli/chunks/{chunk-APVXTHTA.js → chunk-G5DFYX3J.js} +3 -3
- package/dist/cli/chunks/chunk-G7FMYFTN.js +2 -0
- package/dist/cli/chunks/{chunk-CMKCPRWX.js → chunk-GFBLWFRV.js} +1 -1
- package/dist/cli/chunks/{chunk-5YLY2WT2.js → chunk-GJMZR7WU.js} +3 -3
- package/dist/cli/chunks/{chunk-R6LDR3IO.js → chunk-GTUFX7AR.js} +2 -2
- package/dist/cli/chunks/{chunk-5CGTBAVF.js → chunk-GUEZQOHL.js} +1 -1
- package/dist/cli/chunks/{chunk-DGOZ3CGB.js → chunk-HL2QMM4M.js} +2 -2
- package/dist/cli/chunks/{chunk-VOHYQ6MX.js → chunk-HOKON5EL.js} +2 -2
- package/dist/cli/chunks/{chunk-DTXHRALB.js → chunk-HTPM3URI.js} +2 -2
- package/dist/cli/chunks/chunk-HVB2L52I.js +2 -0
- package/dist/cli/chunks/{chunk-GP7IXYOY.js → chunk-IHQTXJAQ.js} +1 -1
- package/dist/cli/chunks/{chunk-LOZAUP6L.js → chunk-IPHLXAMX.js} +2 -2
- package/dist/cli/chunks/{chunk-56MXYSYY.js → chunk-IYDYJ33J.js} +2 -2
- package/dist/cli/chunks/{chunk-QYST2TZW.js → chunk-IZRLIWFN.js} +2 -2
- package/dist/cli/chunks/{chunk-XNNYHQLW.js → chunk-J3L52EA4.js} +5 -5
- package/dist/cli/chunks/{chunk-P2FYRAC5.js → chunk-JGM6XCCP.js} +1 -1
- package/dist/cli/chunks/chunk-JPIBPKBP.js +54 -0
- package/dist/cli/chunks/{chunk-ILNQPPKB.js → chunk-K5N6SLHO.js} +1 -1
- package/dist/cli/chunks/{chunk-UEIIIDBJ.js → chunk-KSYLRM4Q.js} +2 -2
- package/dist/cli/chunks/{chunk-TRHUH24V.js → chunk-KUA4HHU6.js} +2 -2
- package/dist/cli/chunks/{chunk-OEZNUXY7.js → chunk-KVL63BSU.js} +1 -1
- package/dist/cli/chunks/{chunk-WMNGPIP3.js → chunk-KZTBNDNE.js} +1 -1
- package/dist/cli/chunks/{chunk-OSAPKOGN.js → chunk-L2SFGFE6.js} +1 -1
- package/dist/cli/chunks/{chunk-IQ56KMMH.js → chunk-L4LLA5U7.js} +1 -1
- package/dist/cli/chunks/{chunk-KBAXD6PH.js → chunk-L4S722JD.js} +1 -1
- package/dist/cli/chunks/{chunk-C7VNQ4PY.js → chunk-LBE2P6UC.js} +2 -2
- package/dist/cli/chunks/{chunk-KNOO6TFO.js → chunk-LOXVVMS4.js} +3 -3
- package/dist/cli/chunks/{chunk-B7DI76SY.js → chunk-LWYLW7RX.js} +2 -2
- package/dist/cli/chunks/{chunk-6SWR2BN7.js → chunk-LXPB7H2P.js} +1 -1
- package/dist/cli/chunks/{chunk-LGEPR7MH.js → chunk-MBCGI3M2.js} +3 -3
- package/dist/cli/chunks/{chunk-WL5VMIO4.js → chunk-MVI2QMRW.js} +1 -1
- package/dist/cli/chunks/{chunk-OIUIVV2N.js → chunk-N5MMBA35.js} +1 -1
- package/dist/cli/chunks/{chunk-TQNNKW7K.js → chunk-N7VOOI3U.js} +2 -2
- package/dist/cli/chunks/{chunk-BPSEFLJ6.js → chunk-NETN3OUG.js} +1 -1
- package/dist/cli/chunks/chunk-NQNKKVNO.js +29 -0
- package/dist/cli/chunks/{chunk-ACDZ2CRV.js → chunk-NUQBJGGF.js} +2 -2
- package/dist/cli/chunks/chunk-OETDMOOE.js +2 -0
- package/dist/cli/chunks/{chunk-R5HC6JVJ.js → chunk-OXXMVQDF.js} +2 -2
- package/dist/cli/chunks/{chunk-J6EFAKDQ.js → chunk-OZR25R7W.js} +2 -2
- package/dist/cli/chunks/{chunk-ZL7ZOIHO.js → chunk-PERJO2DY.js} +1 -1
- package/dist/cli/chunks/{chunk-WKWIUS5G.js → chunk-PP2RYSHT.js} +3 -3
- package/dist/cli/chunks/{chunk-WE5QHYL7.js → chunk-Q7PBGNUD.js} +1 -1
- package/dist/cli/chunks/{chunk-E5XWCGSX.js → chunk-QCEW4ZDW.js} +2 -2
- package/dist/cli/chunks/{chunk-EGU54SNK.js → chunk-QI4CGJNK.js} +1 -1
- package/dist/cli/chunks/{chunk-MNNNA57O.js → chunk-QQB55ZJJ.js} +2 -2
- package/dist/cli/chunks/{chunk-KV5OZ6T3.js → chunk-QTU3CVOB.js} +2 -2
- package/dist/cli/chunks/{chunk-M4XVEUUM.js → chunk-QWYISZTN.js} +2 -2
- package/dist/cli/chunks/{chunk-OMIGKGJJ.js → chunk-R3GEXYO4.js} +2 -2
- package/dist/cli/chunks/{chunk-4KEOBDEI.js → chunk-RDU4WTV2.js} +2 -2
- package/dist/cli/chunks/{chunk-3AJUJAUJ.js → chunk-RJZRWVL4.js} +1 -1
- package/dist/cli/chunks/{chunk-UFPCNUJA.js → chunk-RLCWR7TS.js} +10 -10
- package/dist/cli/chunks/{chunk-FTG4ZVTX.js → chunk-RSFIOR2I.js} +10 -10
- package/dist/cli/chunks/{chunk-FKUH33L3.js → chunk-RVJPWRV6.js} +2 -2
- package/dist/cli/chunks/{chunk-AMPYON7M.js → chunk-RVRBTOWX.js} +2 -2
- package/dist/cli/chunks/{chunk-AJ6DZXKK.js → chunk-SHCTEXNH.js} +2 -2
- package/dist/cli/chunks/chunk-SNTUKW4Q.js +2 -0
- package/dist/cli/chunks/{chunk-F3CKOVZM.js → chunk-SRQ3CPJE.js} +6 -6
- package/dist/cli/chunks/{chunk-V2QYW5KW.js → chunk-THBTN7XB.js} +2 -2
- package/dist/cli/chunks/{chunk-6FBXYS6X.js → chunk-TNRIGQ6U.js} +2 -2
- package/dist/cli/chunks/{chunk-UF3YOGHV.js → chunk-TVMFH5N2.js} +2 -2
- package/dist/cli/chunks/{chunk-FUBN5GPY.js → chunk-TZ73SXQ5.js} +1 -1
- package/dist/cli/chunks/chunk-TZPKTRJB.js +9 -0
- package/dist/cli/chunks/{chunk-IKIKIHFQ.js → chunk-U2SW6KK5.js} +2 -2
- package/dist/cli/chunks/{chunk-ZHWXI4SK.js → chunk-UIPPJKON.js} +2 -2
- package/dist/cli/chunks/{chunk-MNHGBG4D.js → chunk-UMG5URNV.js} +1 -1
- package/dist/cli/chunks/{chunk-YYV3FYVB.js → chunk-UNIBND6A.js} +1 -1
- package/dist/cli/chunks/{chunk-HH5Y4NCR.js → chunk-USMDIIHY.js} +2 -2
- package/dist/cli/chunks/{chunk-TLYZPOA7.js → chunk-VC6EXDGY.js} +2 -2
- package/dist/cli/chunks/{chunk-BMRR3MBR.js → chunk-VHYMSZNF.js} +2 -2
- package/dist/cli/chunks/{chunk-SVUWAV6Y.js → chunk-VLBV2VL3.js} +1 -1
- package/dist/cli/chunks/{chunk-BDX54WJV.js → chunk-VLNPJAVH.js} +1 -1
- package/dist/cli/chunks/{chunk-R554WVIG.js → chunk-VSNRPMAZ.js} +2 -2
- package/dist/cli/chunks/{chunk-AL5QT6OX.js → chunk-W5YEIHIO.js} +2 -2
- package/dist/cli/chunks/{chunk-NDAJWCXN.js → chunk-WRYT4HTZ.js} +2 -2
- package/dist/cli/chunks/{chunk-PSA2SOON.js → chunk-XFCWYQHW.js} +2 -2
- package/dist/cli/chunks/{chunk-6X65BGGK.js → chunk-XKFE3FLI.js} +2 -2
- package/dist/cli/chunks/{chunk-ZF65VOQH.js → chunk-YFGAHNCG.js} +2 -2
- package/dist/cli/chunks/{chunk-YSCEUK55.js → chunk-YPTGE5NJ.js} +2 -2
- package/dist/cli/chunks/{chunk-YDZIPP3Y.js → chunk-YRQLVGCI.js} +2 -2
- package/dist/cli/chunks/{chunk-ERQL3D2O.js → chunk-Z6QCOZ2H.js} +2 -2
- package/dist/cli/chunks/{chunk-WYFEVPLO.js → chunk-ZCFZ4USU.js} +1 -1
- package/dist/cli/chunks/{chunk-2R7XZ2WP.js → chunk-ZEIG5IQ4.js} +2 -2
- package/dist/cli/chunks/{chunk-KJJP446A.js → chunk-ZJG6N2OK.js} +1 -1
- package/dist/cli/chunks/{chunk-BUKGW63B.js → chunk-ZJIX5FGQ.js} +3 -3
- package/dist/cli/chunks/{chunk-EZ3JVN6S.js → chunk-ZLXBNNNT.js} +2 -2
- package/dist/cli/chunks/{chunk-4FHJYJCH.js → chunk-ZOXWASCC.js} +2 -2
- package/dist/cli/chunks/{ci-NT4DUGQ4.js → ci-74ZUCO5V.js} +2 -2
- package/dist/cli/chunks/{ci-output-PXBD2QPH.js → ci-output-HD6IZNJA.js} +2 -2
- package/dist/cli/chunks/{circuit-breaker-ZPCCEEDX.js → circuit-breaker-USZVMA42.js} +2 -2
- package/dist/cli/chunks/{claude-flow-setup-CZCDFZOE.js → claude-flow-setup-S4XKNCD5.js} +2 -2
- package/dist/cli/chunks/client-33PGO5FA.js +2 -0
- package/dist/cli/chunks/{cline-installer-6J2S7GLM.js → cline-installer-6EW4CHAR.js} +2 -2
- package/dist/cli/chunks/{code-UTERK5AP.js → code-TOLWD2XL.js} +2 -2
- package/dist/cli/chunks/{code-index-extractor-O3MJTOS2.js → code-index-extractor-UA4QQ7B3.js} +2 -2
- package/dist/cli/chunks/{codex-installer-AZJIVXJR.js → codex-installer-C2CUP4FW.js} +2 -2
- package/dist/cli/chunks/{completions-A6ANQSZN.js → completions-KVUMQQ4K.js} +2 -2
- package/dist/cli/chunks/{complexity-analyzer-MRSN7VUP.js → complexity-analyzer-DFH6LMK2.js} +2 -2
- package/dist/cli/chunks/{continuedev-installer-6LMKQRUI.js → continuedev-installer-LYDQSAU7.js} +2 -2
- package/dist/cli/chunks/{copilot-installer-KP3TWUNO.js → copilot-installer-7USXLZHZ.js} +2 -2
- package/dist/cli/chunks/core-handlers-CSNZIM3A.js +2 -0
- package/dist/cli/chunks/{cost-tracker-R3C5IQPZ.js → cost-tracker-JBDIUMKZ.js} +2 -2
- package/dist/cli/chunks/{coverage-MR4QA2NM.js → coverage-RGO3K357.js} +3 -3
- package/dist/cli/chunks/cross-domain-router-DRIBR5L3.js +2 -0
- package/dist/cli/chunks/{cursor-installer-LPZ7NGOS.js → cursor-installer-YEZGD37F.js} +2 -2
- package/dist/cli/chunks/{daemon-X5KXHRY3.js → daemon-FVETQ3LL.js} +3 -3
- package/dist/cli/chunks/{daemon-K3KW2UDV.js → daemon-LPEXHNYG.js} +4 -4
- package/dist/cli/chunks/{dag-attention-scheduler-J4FJSGNN.js → dag-attention-scheduler-UKYE2FII.js} +2 -2
- package/dist/cli/chunks/{detect-22TX2NCA.js → detect-WBG5P7ER.js} +2 -2
- package/dist/cli/chunks/{dist-node-QI4I4QPS.js → dist-node-YW6YRBCU.js} +2 -2
- package/dist/cli/chunks/{domain-handler-ZYZGPNOQ.js → domain-handler-HH7J4A32.js} +2 -2
- package/dist/cli/chunks/{domain-transfer-2EEQTNIU.js → domain-transfer-V34GXD5I.js} +2 -2
- package/dist/cli/chunks/dream-WUNO723O.js +2 -0
- package/dist/cli/chunks/{embed-and-insert-pattern-LYCTU5BS.js → embed-and-insert-pattern-WYLRS3CL.js} +2 -2
- package/dist/cli/chunks/{eval-SOA72GUX.js → eval-EIMVXY5J.js} +2 -2
- package/dist/cli/chunks/{experience-capture-middleware-AFFYOMYM.js → experience-capture-middleware-QMZHRUKM.js} +3 -3
- package/dist/cli/chunks/{fast-paths-WNMHOSUH.js → fast-paths-NHLW6XS6.js} +2 -2
- package/dist/cli/chunks/{feature-flags-HAP5IAAY.js → feature-flags-N3UHMSZ3.js} +2 -2
- package/dist/cli/chunks/{feature-flags-FT4YBZH4.js → feature-flags-NE3MBL3P.js} +2 -2
- package/dist/cli/chunks/{file-discovery-B4FFOH3Z.js → file-discovery-SI44X4YS.js} +2 -2
- package/dist/cli/chunks/{fleet-2ICPYV3J.js → fleet-MMYUXRRM.js} +3 -3
- package/dist/cli/chunks/{gnn-wrapper-XIBJAHMW.js → gnn-wrapper-RLYXYU2Q.js} +2 -2
- package/dist/cli/chunks/{heartbeat-handler-NSLSKDOI.js → heartbeat-handler-6EDRUYLV.js} +4 -4
- package/dist/cli/chunks/heartbeat-scheduler-VAFQDJLL.js +2 -0
- package/dist/cli/chunks/hnsw-adapter-TIRPA7XE.js +2 -0
- package/dist/cli/chunks/hnsw-index-SSQBRQCQ.js +2 -0
- package/dist/cli/chunks/{hnsw-legacy-bridge-FTV4CCBB.js → hnsw-legacy-bridge-RVM7EAIH.js} +2 -2
- package/dist/cli/chunks/{better-sqlite3-RQCOOAZC.js → hnswlib-node-RJPBJU2Q.js} +2 -2
- package/dist/cli/chunks/{hooks-SM4EU52N.js → hooks-ZF4VKHEO.js} +10 -10
- package/dist/cli/chunks/hybrid-router-AKBWZOQ3.js +2 -0
- package/dist/cli/chunks/{hypergraph-engine-RRMX4N3L.js → hypergraph-engine-YWS66PGO.js} +2 -2
- package/dist/cli/chunks/{hypergraph-handler-MNFGDKAP.js → hypergraph-handler-OQHVRPWB.js} +3 -3
- package/dist/cli/chunks/impact-analyzer-46FQIZ6Y.js +2 -0
- package/dist/cli/chunks/{init-handler-BNHIJ5TX.js → init-handler-YW74YF2V.js} +6 -6
- package/dist/cli/chunks/init-wizard-U3NHGYSS.js +2 -0
- package/dist/cli/chunks/kernel-ZDXHT6QF.js +2 -0
- package/dist/cli/chunks/{kilocode-installer-GFKUKPLY.js → kilocode-installer-APWB2GMA.js} +2 -2
- package/dist/cli/chunks/{kiro-installer-YBIYKODN.js → kiro-installer-DICKFVNC.js} +2 -2
- package/dist/cli/chunks/knowledge-graph-6XTW6WO6.js +2 -0
- package/dist/cli/chunks/{learning-QEWUPCK6.js → learning-MXHNYW5D.js} +3 -3
- package/dist/cli/chunks/{llm-router-D5FQIMVQ.js → llm-router-LTFIX7NY.js} +5 -5
- package/dist/cli/chunks/llm-router-service-3F4E64SY.js +2 -0
- package/dist/cli/chunks/{load-CLBUCKZQ.js → load-JUMIQ4LZ.js} +2 -2
- package/dist/cli/chunks/load-test-SWZNGEIY.js +2 -0
- package/dist/cli/chunks/{mcp-VOMG5DPV.js → mcp-WHIARJGO.js} +2 -2
- package/dist/cli/chunks/{memory-WZO63VSC.js → memory-KAHS6Z5A.js} +5 -5
- package/dist/cli/chunks/memory-backend-PR74ZPBA.js +2 -0
- package/dist/cli/chunks/memory-handlers-DG3RRXB6.js +2 -0
- package/dist/cli/chunks/{multi-model-executor-7UKW43VV.js → multi-model-executor-E3Y2RHMX.js} +2 -2
- package/dist/cli/chunks/{opencode-installer-MLFPRRL2.js → opencode-installer-3RKGNGGE.js} +2 -2
- package/dist/cli/chunks/{orchestrator-XNYDBGIN.js → orchestrator-TXITUKWD.js} +5 -5
- package/dist/cli/chunks/pattern-null-store-EPE36BVT.js +2 -0
- package/dist/cli/chunks/{pattern-usage-recorder-ZAP7ASQI.js → pattern-usage-recorder-EE2BUFZT.js} +2 -2
- package/dist/cli/chunks/{pipeline-4EJYOPBC.js → pipeline-AXTT6KZB.js} +2 -2
- package/dist/cli/chunks/{platform-ALPOWCOH.js → platform-TICPVKE2.js} +2 -2
- package/dist/cli/chunks/{plugin-S2RX3KHR.js → plugin-VQKNV3EM.js} +2 -2
- package/dist/cli/chunks/{prime-radiant-advanced-wasm-P2JB73XX.js → prime-radiant-advanced-wasm-6GY5YY7D.js} +2 -2
- package/dist/cli/chunks/protocol-executor-IELENNST.js +2 -0
- package/dist/cli/chunks/{protocol-handler-ZBJXSESA.js → protocol-handler-YFWDR7UZ.js} +2 -2
- package/dist/cli/chunks/{prove-MYJ5YV45.js → prove-FUMRCXAA.js} +2 -2
- package/dist/cli/chunks/provider-manager-3R3KOBHG.js +2 -0
- package/dist/cli/chunks/qe-reasoning-bank-S2R2PCBS.js +2 -0
- package/dist/cli/chunks/{quality-NIACQC4M.js → quality-2APISBW5.js} +2 -2
- package/dist/cli/chunks/{quality-gate-OAZ23ON5.js → quality-gate-MCC3E5TM.js} +3 -3
- package/dist/cli/chunks/queen-coordinator-2E23NEV4.js +2 -0
- package/dist/cli/chunks/{real-embeddings-6I4LP7PL.js → real-embeddings-CC5TNOTI.js} +2 -2
- package/dist/cli/chunks/{roocode-installer-LRQHP6MK.js → roocode-installer-YAHTEVPI.js} +2 -2
- package/dist/cli/chunks/router-3FVLWO6S.js +2 -0
- package/dist/cli/chunks/routing-feedback-ZQLRNNR7.js +2 -0
- package/dist/cli/chunks/{routing-handler-A7BW7MV4.js → routing-handler-6NQBW4TQ.js} +2 -2
- package/dist/cli/chunks/{ruvector-commands-ZDRRFSJS.js → ruvector-commands-ZHXLHUPG.js} +2 -2
- package/dist/cli/chunks/{rvf-dual-writer-QWE3Z6BB.js → rvf-dual-writer-5KF2DGCW.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-adapter-6UDAP7QB.js → rvf-migration-adapter-BBU57BGF.js} +2 -2
- package/dist/cli/chunks/{rvf-migration-coordinator-FEW2N4R4.js → rvf-migration-coordinator-VN4VRZA4.js} +2 -2
- package/dist/cli/chunks/rvf-native-adapter-YFGLQNEB.js +2 -0
- package/dist/cli/chunks/rvf-store-integrity-XCY2XQZA.js +2 -0
- package/dist/cli/chunks/safe-db-4SBLBTW7.js +2 -0
- package/dist/cli/chunks/schedule-5Y3BGVAA.js +2 -0
- package/dist/cli/chunks/scheduler-DOID3QF3.js +2 -0
- package/dist/cli/chunks/{security-KFXBV65O.js → security-PYP4H3KN.js} +3 -3
- package/dist/cli/chunks/shared-rvf-adapter-3CJHRNX6.js +2 -0
- package/dist/cli/chunks/{shared-rvf-dual-writer-CXXTB7CU.js → shared-rvf-dual-writer-MKSLKWDI.js} +2 -2
- package/dist/cli/chunks/sqlite-persistence-M4JEQO57.js +2 -0
- package/dist/cli/chunks/{status-handler-CXSVM236.js → status-handler-VYIZ3VJF.js} +2 -2
- package/dist/cli/chunks/{structural-health-LMHSM7MJ.js → structural-health-MVV4OWXP.js} +2 -2
- package/dist/cli/chunks/{sync-DMOUY2EY.js → sync-G47OYIQ3.js} +2 -2
- package/dist/cli/chunks/sync-VNX6L3TI.js +2 -0
- package/dist/cli/chunks/{task-handler-DMSNFIH3.js → task-handler-GOWF2GEH.js} +2 -2
- package/dist/cli/chunks/{task-handlers-3Z3QV7X7.js → task-handlers-J2WC6J37.js} +3 -3
- package/dist/cli/chunks/{test-U6CGMDLN.js → test-DMCJ3BXS.js} +4 -4
- package/dist/cli/chunks/{test-scheduling-YHYA3BP5.js → test-scheduling-TRFHHKFM.js} +3 -3
- package/dist/cli/chunks/token-bootstrap-KEQ7AHFF.js +2 -0
- package/dist/cli/chunks/{token-usage-EOOTM7Q3.js → token-usage-B54FOFOF.js} +2 -2
- package/dist/cli/chunks/transformers-IACZG7IV.js +2 -0
- package/dist/cli/chunks/{tree-sitter-wasm-parser-HTGAXDQA.js → tree-sitter-wasm-parser-N7H4X37E.js} +2 -2
- package/dist/cli/chunks/{types-GLRXY4RY.js → types-B3SHT4OD.js} +2 -2
- package/dist/cli/chunks/unified-memory-WNYWTGVX.js +2 -0
- package/dist/cli/chunks/unified-memory-hnsw-YPAV7U4E.js +2 -0
- package/dist/cli/chunks/unified-persistence-TJ252S7L.js +2 -0
- package/dist/cli/chunks/{upgrade-KU55H77X.js → upgrade-A2PQ5EWK.js} +2 -2
- package/dist/cli/chunks/{validate-26VSBOJN.js → validate-UXV7UQUT.js} +2 -2
- package/dist/cli/chunks/{validate-swarm-OIALRDKF.js → validate-swarm-MMBU4FPP.js} +2 -2
- package/dist/cli/chunks/{vibium-LOTWW25P.js → vibium-R4GUVADA.js} +2 -2
- package/dist/cli/chunks/visual-security-VKYXEGJB.js +2 -0
- package/dist/cli/chunks/{web-tree-sitter-6LWPPBYU.js → web-tree-sitter-MP6E6CJB.js} +2 -2
- package/dist/cli/chunks/{windsurf-installer-ILOQYENG.js → windsurf-installer-Z6BWMUUO.js} +2 -2
- package/dist/cli/chunks/{witness-chain-YBS6OHS4.js → witness-chain-EFLTABBA.js} +2 -2
- package/dist/cli/chunks/witness-chain-WVXRXKQP.js +2 -0
- package/dist/cli/chunks/{witness-key-manager-SI3WV3ZQ.js → witness-key-manager-PN36TV43.js} +2 -2
- package/dist/cli/chunks/{workflow-GY6SJRQW.js → workflow-A2AX3RJU.js} +4 -4
- package/dist/cli/chunks/workflow-orchestrator-GOWSPR3G.js +2 -0
- package/dist/cli/chunks/{wrappers-MMO5YKOZ.js → wrappers-NA6FHA63.js} +2 -2
- package/dist/cli/commands/llm-router.js +1 -0
- package/dist/init/skills-installer.js +1 -0
- package/dist/integrations/embeddings/base/EmbeddingGenerator.js +13 -1
- package/dist/integrations/ruvector/brain-rvf-exporter.js +115 -13
- package/dist/integrations/ruvector/rvf-dual-writer.js +20 -3
- package/dist/integrations/ruvector/rvf-store-integrity.d.ts +49 -0
- package/dist/integrations/ruvector/rvf-store-integrity.js +137 -0
- package/dist/integrations/ruvector/shared-rvf-adapter.js +23 -5
- package/dist/kernel/unified-memory.js +4 -0
- package/dist/learning/pattern-store.js +23 -5
- package/dist/learning/qe-flywheel/corpus-scorer.js +10 -7
- package/dist/learning/qe-flywheel/generation.d.ts +7 -0
- package/dist/learning/qe-flywheel/generation.js +5 -0
- package/dist/learning/qe-flywheel/platform-signer.d.ts +32 -0
- package/dist/learning/qe-flywheel/platform-signer.js +60 -0
- package/dist/learning/qe-flywheel/receipt.js +9 -2
- package/dist/learning/qe-flywheel/witness-verify.d.ts +86 -0
- package/dist/learning/qe-flywheel/witness-verify.js +156 -0
- package/dist/mcp/bundle.js +398 -387
- package/dist/shared/db-recovery.d.ts +55 -0
- package/dist/shared/db-recovery.js +184 -0
- package/dist/shared/llm/billing-modes.js +5 -2
- package/dist/shared/llm/cost-tracker.js +1 -0
- package/dist/shared/llm/interfaces.d.ts +14 -1
- package/dist/shared/llm/provider-manager.d.ts +1 -1
- package/dist/shared/llm/provider-manager.js +7 -3
- package/dist/shared/llm/providers/claude-code.js +12 -3
- package/dist/shared/llm/providers/codex.d.ts +58 -0
- package/dist/shared/llm/providers/codex.js +305 -0
- package/dist/shared/llm/providers/index.d.ts +1 -0
- package/dist/shared/llm/providers/index.js +1 -0
- package/dist/shared/llm/router/config-store.js +5 -0
- package/dist/shared/llm/router/hybrid-router.js +2 -2
- package/dist/shared/llm/spend-ledger.d.ts +24 -0
- package/dist/shared/llm/spend-ledger.js +86 -15
- package/dist/shared/llm/translation/message-formatter.js +1 -0
- package/dist/shared/safe-db.d.ts +10 -0
- package/dist/shared/safe-db.js +17 -0
- package/dist/skills/qe-court/referee.d.ts +62 -0
- package/dist/skills/qe-court/referee.js +78 -0
- package/dist/validation/gate-reexecute.d.ts +9 -0
- package/dist/validation/gate-reexecute.js +61 -0
- package/dist/validation/paired-bootstrap.d.ts +36 -0
- package/dist/validation/paired-bootstrap.js +58 -0
- package/package.json +8 -4
- package/dist/cli/chunks/adapter-RL6GNUOS.js +0 -2
- package/dist/cli/chunks/aqe-learning-engine-UEEW6AQG.js +0 -2
- package/dist/cli/chunks/base-JQA5YULE.js +0 -2
- package/dist/cli/chunks/brain-handler-T7RDPKNM.js +0 -89
- package/dist/cli/chunks/browser-workflow-XTKUHTIT.js +0 -2
- package/dist/cli/chunks/chunk-ABHKXMOJ.js +0 -2
- package/dist/cli/chunks/chunk-CDMAVNV5.js +0 -2
- package/dist/cli/chunks/chunk-CQKEVUMO.js +0 -153
- package/dist/cli/chunks/chunk-KPV4N4KT.js +0 -9
- package/dist/cli/chunks/chunk-MALFTRCT.js +0 -29
- package/dist/cli/chunks/chunk-T75VH6NT.js +0 -2
- package/dist/cli/chunks/chunk-VM6VBRRU.js +0 -43
- package/dist/cli/chunks/chunk-WRMUQVKY.js +0 -2
- package/dist/cli/chunks/chunk-YY4KXDI6.js +0 -2
- package/dist/cli/chunks/client-S7DIRNFJ.js +0 -2
- package/dist/cli/chunks/core-handlers-NM2KCI6Z.js +0 -2
- package/dist/cli/chunks/cross-domain-router-3TSZMCBM.js +0 -2
- package/dist/cli/chunks/dream-QIIJONYI.js +0 -2
- package/dist/cli/chunks/heartbeat-scheduler-CDNGLJJO.js +0 -2
- package/dist/cli/chunks/hnsw-adapter-CR7Y4OAM.js +0 -2
- package/dist/cli/chunks/hnsw-index-TEDO4MQC.js +0 -2
- package/dist/cli/chunks/hybrid-router-O24ZDIP5.js +0 -2
- package/dist/cli/chunks/impact-analyzer-PDM4SDB6.js +0 -2
- package/dist/cli/chunks/init-wizard-F4KODPNW.js +0 -2
- package/dist/cli/chunks/kernel-77UM35L6.js +0 -2
- package/dist/cli/chunks/knowledge-graph-R6ZWWV2K.js +0 -2
- package/dist/cli/chunks/llm-router-service-7QYCZ66H.js +0 -2
- package/dist/cli/chunks/load-test-AWVA3CAQ.js +0 -2
- package/dist/cli/chunks/memory-backend-YESSIHFW.js +0 -2
- package/dist/cli/chunks/memory-handlers-EOOWSUHI.js +0 -2
- package/dist/cli/chunks/pattern-null-store-X3UXLJNL.js +0 -2
- package/dist/cli/chunks/protocol-executor-KXDCTMWI.js +0 -2
- package/dist/cli/chunks/provider-manager-XJZVHYI6.js +0 -2
- package/dist/cli/chunks/qe-reasoning-bank-DPHPNIC6.js +0 -2
- package/dist/cli/chunks/queen-coordinator-EVGWME5C.js +0 -2
- package/dist/cli/chunks/router-R2N7TMAS.js +0 -2
- package/dist/cli/chunks/routing-feedback-G6W3H26L.js +0 -2
- package/dist/cli/chunks/rvf-native-adapter-D7R2GWXK.js +0 -2
- package/dist/cli/chunks/safe-db-CQZGF2KA.js +0 -2
- package/dist/cli/chunks/schedule-UP7E3LRC.js +0 -2
- package/dist/cli/chunks/scheduler-ENIZHYSL.js +0 -2
- package/dist/cli/chunks/shared-rvf-adapter-HDDCXCHY.js +0 -2
- package/dist/cli/chunks/sqlite-persistence-CEVJVWS5.js +0 -2
- package/dist/cli/chunks/sync-REEFKICL.js +0 -2
- package/dist/cli/chunks/token-bootstrap-MQCTJURQ.js +0 -2
- package/dist/cli/chunks/transformers-EKDJW2H6.js +0 -2
- package/dist/cli/chunks/unified-memory-PXOQ4N53.js +0 -2
- package/dist/cli/chunks/unified-memory-hnsw-VEXD6ASE.js +0 -2
- package/dist/cli/chunks/unified-persistence-46G6MZYC.js +0 -2
- package/dist/cli/chunks/visual-security-4X3T3MFL.js +0 -2
- package/dist/cli/chunks/witness-chain-XW4S3LVW.js +0 -2
- package/dist/cli/chunks/workflow-orchestrator-IIVV6TCP.js +0 -2
|
@@ -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.
|
|
2
|
-
import{b as A,d as M}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.13.0");process.exit(0)}
|
|
2
|
+
import{b as A,d as M}from"./chunk-2DIT5AUU.js";import{a as S,b as D}from"./chunk-YRQLVGCI.js";import{S as Q,l as E}from"./chunk-3GSYD5SL.js";import{g as C}from"./chunk-ES7WCYOU.js";M();Q();var v=(1+Math.sqrt(5))/2,R=1/v;function k(t,e=0){if(t<0||!Number.isFinite(t))throw new Error(`Invalid dither sequence length: ${t}`);if(!Number.isFinite(e))throw new Error(`Invalid dither seed: ${e}`);let n=new Float32Array(t),r=(e*R%1+1)%1;for(let i=0;i<t;i++)n[i]=((r+(i+1)*v)%1+1)%1;return n}function I(t,e,n=0){if(!(t instanceof Float32Array))throw new Error("Input vector must be a Float32Array");if(t.length===0)return{quantized:new Int32Array(0),dequantized:new Float32Array(0),bitDepth:e,seed:n,stepSize:0,minValue:0,maxValue:0};if(e<1||e>32||!Number.isInteger(e))throw new Error(`Invalid bit depth: ${e}. Must be an integer in [1, 32].`);let r=t[0],i=t[0];for(let d=1;d<t.length;d++)t[d]<r&&(r=t[d]),t[d]>i&&(i=t[d]);let s=(1<<e)-1,a=i-r,o=a===0?1:a/s,m=k(t.length,n),l=new Int32Array(t.length),u=new Float32Array(t.length);for(let d=0;d<t.length;d++){if(a===0)l[d]=Math.round(s/2);else{let L=(t[d]-r)/o+(m[d]-.5);l[d]=Math.max(0,Math.min(s,Math.round(L)))}u[d]=l[d]*o+r}return{quantized:l,dequantized:u,bitDepth:e,seed:n,stepSize:o,minValue:r,maxValue:i}}var h=null,b=null,p=null,g=null,f=null,w=null,x=!1;try{let t=(D(),C(S));h=t.RuvectorLayer,b=t.TensorCompress,p=t.differentiableSearch,g=t.hierarchicalForward,f=t.getCompressionLevel,w=t.init,x=!0}catch{}function H(){return x}function c(){if(!x)throw new Error("@ruvector/gnn native module is not available on this platform. Install the appropriate optional dependency for your platform, or use a platform where pre-built binaries are available.")}var F=!1;function V(){if(!F){c();let t=w();return F=!0,t}return"@ruvector/gnn already initialized"}var y=class{indexes;config;nextId;gnnLayers;compressor;constructor(e={}){this.config={M:e.M||16,efConstruction:e.efConstruction||200,efSearch:e.efSearch||50,dimension:e.dimension||384,metric:e.metric||"cosine",quantization:e.quantization||"none"},this.indexes=new Map,this.nextId=new Map,this.gnnLayers=new Map,c(),this.compressor=new b,V()}initializeIndex(e){this.indexes.has(e)||(this.indexes.set(e,new Map),this.nextId.set(e,0))}addEmbedding(e,n){let r=e.namespace;this.indexes.has(r)||this.initializeIndex(r);let i=this.indexes.get(r),s=n??this.nextId.get(r);return n===void 0&&this.nextId.set(r,s+1),i.set(s,e),s}addEmbeddingsBatch(e){let n=[];for(let r of e){let i=this.addEmbedding(r.embedding,r.id);n.push(i)}return n}search(e,n={}){let r=n.namespace||e.namespace;if(!this.indexes.has(r))return[];let i=this.indexes.get(r),s=n.limit||10,a=[];for(let[u,d]of i.entries())a.push({id:u,vector:Array.from(d.vector)});if(a.length===0)return[];let o=new Float32Array(e.vector),m=a.map(u=>new Float32Array(u.vector)),l=p(o,m,Math.min(s,a.length),1);return l.indices.map((u,d)=>({id:a[u]?.id??u,distance:1-l.weights[d]}))}differentiableSearchWithWeights(e,n,r,i=1){let s=new Float32Array(e.vector),a=n.map(m=>new Float32Array(m.embedding.vector)),o=p(s,a,Math.min(r,n.length),i);return{indices:o.indices.map(m=>n[m]?.id??m),weights:o.weights}}hierarchicalForward(e,n,r){let i=r.map(l=>`${l.inputDim}-${l.hiddenDim}`).join(",");if(!this.gnnLayers.has(i)){let l=[];for(let u of r){let d=new h(u.inputDim,u.hiddenDim,u.heads,u.dropout);l.push(d)}this.gnnLayers.set(i,l[0])}let a=this.gnnLayers.get(i).toJson(),o=new Float32Array(e),m=n.map(l=>l.map(u=>new Float32Array(u)));return Array.from(g(o,m,[a]))}compressEmbedding(e,n){let r=f(n),s={none:"none",half:"half",pq8:"pq8",pq4:"pq4",binary:"binary"}[r]??"none",a=new Float32Array(e.vector),o=this.compressor.compress(a,n);return{dimension:Array.from(e.vector).length,level:s,data:o,accessFreq:n}}decompressEmbedding(e){let n=this.compressor.decompress(e.data),r={none:"none",half:"fp16",pq8:"int8",pq4:"int8",binary:"binary"};return{vector:n,dimension:e.dimension,namespace:"code",text:"",timestamp:Date.now(),quantization:r[e.level]??"none"}}getCompressionLevelForFrequency(e){return c(),f(e)}getIndexStats(e){return this.indexes.has(e)?{size:this.indexes.get(e).size,maxElements:1e4,dimension:this.config.dimension,metric:this.config.metric}:null}clearIndex(e){this.indexes.delete(e),this.nextId.delete(e)}clearAll(){this.indexes.clear(),this.nextId.clear()}resizeIndex(e){}setEfSearch(e){this.config.efSearch=e}getConfig(){return{...this.config}}isInitialized(e){return this.indexes.has(e)}getInitializedNamespaces(){return Array.from(this.indexes.keys())}getSize(e){return this.indexes.get(e)?.size??0}async saveIndex(e,n){let r=this.indexes.get(e);if(!r)throw new Error(`Namespace ${e} not initialized`);let i=Array.from(r.entries()).map(([a,o])=>({id:a,vector:Array.from(o.vector),metadata:o.metadata}));await(await import("fs/promises")).writeFile(n,JSON.stringify(i,null,2))}async loadIndex(e,n){let i=await(await import("fs/promises")).readFile(n,"utf-8"),s=A(i);this.initializeIndex(e);for(let a of s){let o={vector:a.vector,dimension:a.vector.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none",metadata:a.metadata};this.addEmbedding(o,a.id)}}},q=class{static instances=new Map;static getInstance(e,n){return this.instances.has(e)||this.instances.set(e,new y(n)),this.instances.get(e)}static closeInstance(e){let n=this.instances.get(e);n&&(n.clearAll(),this.instances.delete(e))}static closeAll(){for(let e of this.instances.values())e.clearAll();this.instances.clear()}},z=class{static layers=new Map;static getLayer(e){let n=`${e.inputDim}-${e.hiddenDim}-${e.heads}-${e.dropout}`;if(!this.layers.has(n)){c();let r=new h(e.inputDim,e.hiddenDim,e.heads,e.dropout);this.layers.set(n,r)}return this.layers.get(n)}static layerFromJson(e){return c(),h.fromJson(e)}static clearCache(){this.layers.clear()}},N=class{static _compressor=null;static get compressor(){return this._compressor||(c(),this._compressor=new b),this._compressor}static compressWithLevel(e,n){let r={levelType:n,scale:1,subvectors:n==="pq8"?8:n==="pq4"?16:void 0,centroids:n==="pq8"?256:void 0,outlierThreshold:n==="pq4"?3:void 0,threshold:n==="binary"?0:void 0},i=e instanceof Float32Array?e:new Float32Array(e);return this.compressor.compressWithLevel(i,r)}static decompress(e){return this.compressor.decompress(e)}static getLevel(e){return c(),f(e)}static compressWithDither(e,n,r){let i=e instanceof Float32Array?e:new Float32Array(e),s;if(E()){let o={none:32,half:16,pq8:8,pq4:4,binary:1},m=r?.bitDepth??o[n]??8,l=r?.seed??0;s=I(i,m,l)}return{compressed:this.compressWithLevel(s?s.dequantized:e,n),ditherResult:s}}};function G(){return c(),h}function J(){return c(),b}function O(){return c(),p}function j(){return c(),g}function B(){return c(),f}function K(){return c(),w}function U(t){return t instanceof Float32Array?t:"vector"in t?t.vector instanceof Float32Array?t.vector:new Float32Array(t.vector):new Float32Array(t)}function X(t){return"vector"in t?Array.from(t.vector):Array.from(t)}function Y(t,e="code"){return{vector:t,dimension:t.length,namespace:e,text:"",timestamp:Date.now(),quantization:"none"}}function Z(t,e,n,r=1){let i=[],s=e.map(a=>a instanceof Float32Array?a:new Float32Array(a));for(let a of t){let o=a instanceof Float32Array?a:new Float32Array(a),m=p(o,s,n,r);i.push({indices:m.indices,weights:m.weights})}return i}export{H as a,V as b,y as c,q as d,z as e,N as f,G as g,J as h,O as i,j,B as k,K as l,U as m,X as n,Y as o,Z as p};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.0");process.exit(0)}
|
|
2
|
+
import{a as e,b as g,e as r}from"./chunk-OXXMVQDF.js";import{c as o}from"./chunk-ES7WCYOU.js";var L=o(()=>{"use strict";e();g();r()});export{L as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
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.13.0");process.exit(0)}
|
|
2
2
|
var p={"claude-sonnet-4-5":{canonical:"Claude Sonnet 4.5",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-5-20250929",openrouter:"anthropic/claude-sonnet-4.5",bedrock:"anthropic.claude-sonnet-4-5-v2:0"}},"claude-opus-4":{canonical:"Claude Opus 4",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-20250514",openrouter:"anthropic/claude-opus-4",bedrock:"anthropic.claude-opus-4-v1:0"}},"claude-opus-4-5":{canonical:"Claude Opus 4.5",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-5-20251101",openrouter:"anthropic/claude-opus-4.5",bedrock:"anthropic.claude-opus-4-5-v1:0"}},"claude-haiku-3-5":{canonical:"Claude Haiku 3.5",family:"claude",tier:"economy",providers:{anthropic:"claude-3-5-haiku-20241022",openrouter:"anthropic/claude-3.5-haiku",bedrock:"anthropic.claude-3-5-haiku-v1:0"}},"claude-sonnet-4":{canonical:"Claude Sonnet 4",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-20250514",openrouter:"anthropic/claude-sonnet-4",bedrock:"anthropic.claude-sonnet-4-v1:0"}},"claude-opus-4-7":{canonical:"Claude Opus 4.7",family:"claude",tier:"flagship",providers:{anthropic:"claude-opus-4-7",openrouter:"anthropic/claude-opus-4.7",bedrock:"anthropic.claude-opus-4-7-v1:0"}},"claude-sonnet-4-6":{canonical:"Claude Sonnet 4.6",family:"claude",tier:"standard",providers:{anthropic:"claude-sonnet-4-6",openrouter:"anthropic/claude-sonnet-4.6",bedrock:"anthropic.claude-sonnet-4-6-v1:0"}},"claude-haiku-4-5":{canonical:"Claude Haiku 4.5",family:"claude",tier:"economy",providers:{anthropic:"claude-haiku-4-5-20251001",openrouter:"anthropic/claude-haiku-4.5",bedrock:"anthropic.claude-haiku-4-5-v1:0"}},"gpt-4o":{canonical:"GPT-4o",family:"gpt",tier:"standard",providers:{openai:"gpt-4o",azure:"gpt-4o",openrouter:"openai/gpt-4o"}},"gpt-4o-mini":{canonical:"GPT-4o Mini",family:"gpt",tier:"economy",providers:{openai:"gpt-4o-mini",azure:"gpt-4o-mini",openrouter:"openai/gpt-4o-mini"}},"gpt-4-turbo":{canonical:"GPT-4 Turbo",family:"gpt",tier:"premium",providers:{openai:"gpt-4-turbo",azure:"gpt-4-turbo",openrouter:"openai/gpt-4-turbo"}},"gpt-4":{canonical:"GPT-4",family:"gpt",tier:"premium",providers:{openai:"gpt-4",azure:"gpt-4",openrouter:"openai/gpt-4"}},o1:{canonical:"OpenAI o1",family:"gpt",tier:"flagship",providers:{openai:"o1",azure:"o1",openrouter:"openai/o1"}},"o1-mini":{canonical:"OpenAI o1 Mini",family:"gpt",tier:"standard",providers:{openai:"o1-mini",azure:"o1-mini",openrouter:"openai/o1-mini"}},"gemini-pro":{canonical:"Gemini Pro",family:"gemini",tier:"standard",providers:{gemini:"gemini-pro",openrouter:"google/gemini-pro"}},"gemini-pro-1.5":{canonical:"Gemini Pro 1.5",family:"gemini",tier:"standard",providers:{gemini:"gemini-1.5-pro",openrouter:"google/gemini-pro-1.5"}},"gemini-flash-1.5":{canonical:"Gemini Flash 1.5",family:"gemini",tier:"economy",providers:{gemini:"gemini-1.5-flash",openrouter:"google/gemini-flash-1.5"}},"gemini-ultra":{canonical:"Gemini Ultra",family:"gemini",tier:"flagship",providers:{gemini:"gemini-ultra",openrouter:"google/gemini-ultra"}},llama3:{canonical:"Llama 3",family:"llama",tier:"economy",providers:{ollama:"llama3",openrouter:"meta-llama/llama-3-8b-instruct"}},"llama3.1":{canonical:"Llama 3.1",family:"llama",tier:"economy",providers:{ollama:"llama3.1",openrouter:"meta-llama/llama-3.1-8b-instruct"}},codellama:{canonical:"CodeLlama",family:"llama",tier:"economy",providers:{ollama:"codellama",openrouter:"meta-llama/codellama-34b-instruct"}},mistral:{canonical:"Mistral",family:"mistral",tier:"economy",providers:{ollama:"mistral",openrouter:"mistralai/mistral-7b-instruct"}},mixtral:{canonical:"Mixtral",family:"mistral",tier:"standard",providers:{ollama:"mixtral",openrouter:"mistralai/mixtral-8x7b-instruct"}},phi3:{canonical:"Phi-3",family:"phi",tier:"economy",providers:{ollama:"phi3",azure:"phi-3-mini-128k-instruct"}},qwen2:{canonical:"Qwen 2",family:"qwen",tier:"economy",providers:{ollama:"qwen2",openrouter:"qwen/qwen-2-7b-instruct"}},"qwen3:8b":{canonical:"Qwen3 8B",family:"qwen",tier:"economy",providers:{ollama:"qwen3:8b"}},"qwen3:30b-a3b":{canonical:"Qwen3 30B-A3B",family:"qwen",tier:"economy",providers:{ollama:"qwen3:30b-a3b"}},"qwen3-coder:30b":{canonical:"Qwen3 Coder 30B-A3B",family:"qwen",tier:"economy",providers:{ollama:"qwen3-coder:30b"}}};function a(){let t=new Map;for(let[e,s]of Object.entries(p)){t.set(e,e),t.set(e.toLowerCase(),e);for(let[r,o]of Object.entries(s.providers))o&&(t.set(o,e),t.set(o.toLowerCase(),e),t.set(`${r}/${o}`,e),t.set(`${r}/${o}`.toLowerCase(),e))}return t}var n=a();function c(t,e){let s=i(t),r=p[s];if(!r)throw new Error(`Unknown model: ${t}`);let o=r.providers[e];if(!o)throw new Error(`Model '${s}' (${r.canonical}) is not available on provider '${e}'`);return o}function i(t){let e=n.get(t);if(e||(e=n.get(t.toLowerCase()),e))return e;let s=[/^anthropic\//i,/^openai\//i,/^google\//i,/^meta-llama\//i,/^mistralai\//i,/^qwen\//i];for(let r of s){let o=t.replace(r,"");if(e=n.get(o),e||(e=n.get(o.toLowerCase()),e))return e}throw new Error(`Unknown model ID: ${t}`)}function u(t){try{let e=i(t);return p[e]}catch{return}}var l={"claude-sonnet-4-5":{name:"Claude Sonnet 4.5",family:"claude",tier:"standard",description:"Most intelligent model, best for complex reasoning and coding tasks",releaseDate:"2025-09-29",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-opus-4":{name:"Claude Opus 4",family:"claude",tier:"flagship",description:"Flagship model with exceptional reasoning and reliability",releaseDate:"2025-05-14",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:75}},"claude-opus-4-5":{name:"Claude Opus 4.5",family:"claude",tier:"flagship",description:"Latest flagship model with enhanced reasoning capabilities",releaseDate:"2025-11-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:32768,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:75}},"claude-haiku-3-5":{name:"Claude Haiku 3.5",family:"claude",tier:"economy",description:"Fast and cost-effective for routine tasks",releaseDate:"2024-10-22",deprecationDate:"2026-02-19",recommended:!1,capabilities:{contextLength:2e5,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:1,outputCostPerMillion:5}},"claude-sonnet-4":{name:"Claude Sonnet 4",family:"claude",tier:"standard",description:"Balanced model for general-purpose tasks",releaseDate:"2025-05-14",deprecationDate:"2026-06-15",recommended:!1,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-opus-4-7":{name:"Claude Opus 4.7",family:"claude",tier:"flagship",description:"Flagship agentic-coding model (2026-04-16). 1M context at standard pricing, xhigh effort level, adaptive thinking only. New tokenizer emits 1.0\u20131.35\xD7 more tokens.",releaseDate:"2026-04-16",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:128e3,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!0,supportsEffortXHigh:!0,tokenizerVersion:"opus-4-7"},cost:{inputCostPerMillion:5,outputCostPerMillion:25}},"claude-sonnet-4-6":{name:"Claude Sonnet 4.6",family:"claude",tier:"standard",description:"Steady-state agentic-coding workhorse (2026). Standard 200k context, same pricing as Sonnet 4. ADR-093 Tier 3 default for the AQE fleet.",releaseDate:"2026-02-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:64e3,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!1,supportsEffortXHigh:!1,tokenizerVersion:"legacy"},cost:{inputCostPerMillion:3,outputCostPerMillion:15}},"claude-haiku-4-5":{name:"Claude Haiku 4.5",family:"claude",tier:"economy",description:"Fast economy model replacing Haiku 3.5 (retired 2026-02-19). Extended thinking support.",releaseDate:"2025-10-01",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!0,supportsEmbeddings:!1,supportsCodeExecution:!1,supportsAdaptiveThinking:!1,supportsEffortXHigh:!1,tokenizerVersion:"legacy"},cost:{inputCostPerMillion:1,outputCostPerMillion:5}},"gpt-4o":{name:"GPT-4o",family:"gpt",tier:"standard",description:"OpenAI flagship multimodal model, fast and capable",releaseDate:"2024-05-13",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:5,outputCostPerMillion:15,imageCostPerUnit:.00765}},"gpt-4o-mini":{name:"GPT-4o Mini",family:"gpt",tier:"economy",description:"Small, fast, and affordable for lightweight tasks",releaseDate:"2024-07-18",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:16384,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:.15,outputCostPerMillion:.6,imageCostPerUnit:.001275}},"gpt-4-turbo":{name:"GPT-4 Turbo",family:"gpt",tier:"premium",description:"Previous flagship with vision and function calling",releaseDate:"2024-04-09",recommended:!1,capabilities:{contextLength:128e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:10,outputCostPerMillion:30}},"gpt-4":{name:"GPT-4",family:"gpt",tier:"premium",description:"Original GPT-4 model, now superseded by GPT-4o",releaseDate:"2023-03-14",deprecationDate:"2025-06-01",recommended:!1,capabilities:{contextLength:8192,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:30,outputCostPerMillion:60}},o1:{name:"OpenAI o1",family:"gpt",tier:"flagship",description:"Reasoning-focused model with extended thinking",releaseDate:"2024-12-05",recommended:!0,capabilities:{contextLength:2e5,maxOutputTokens:1e5,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:15,outputCostPerMillion:60}},"o1-mini":{name:"OpenAI o1 Mini",family:"gpt",tier:"standard",description:"Faster reasoning model optimized for STEM tasks",releaseDate:"2024-09-12",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:65536,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:3,outputCostPerMillion:12}},"gemini-pro":{name:"Gemini Pro",family:"gemini",tier:"standard",description:"Google balanced model for diverse tasks",releaseDate:"2023-12-06",recommended:!1,capabilities:{contextLength:32e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:.5,outputCostPerMillion:1.5}},"gemini-pro-1.5":{name:"Gemini Pro 1.5",family:"gemini",tier:"standard",description:"Google mid-size model with 1M context window",releaseDate:"2024-02-15",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!0},cost:{inputCostPerMillion:3.5,outputCostPerMillion:10.5}},"gemini-flash-1.5":{name:"Gemini Flash 1.5",family:"gemini",tier:"economy",description:"Fast and efficient with 1M context window",releaseDate:"2024-05-14",recommended:!0,capabilities:{contextLength:1e6,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!0},cost:{inputCostPerMillion:.075,outputCostPerMillion:.3}},"gemini-ultra":{name:"Gemini Ultra",family:"gemini",tier:"flagship",description:"Google most capable model",releaseDate:"2024-02-08",recommended:!1,capabilities:{contextLength:32e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!0,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:12,outputCostPerMillion:36}},llama3:{name:"Llama 3",family:"llama",tier:"economy",description:"Meta open-source 8B model, runs locally",releaseDate:"2024-04-18",recommended:!0,capabilities:{contextLength:8192,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},"llama3.1":{name:"Llama 3.1",family:"llama",tier:"economy",description:"Meta latest open-source model with tool support",releaseDate:"2024-07-23",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},codellama:{name:"CodeLlama",family:"llama",tier:"economy",description:"Meta code-specialized model",releaseDate:"2023-08-24",recommended:!0,capabilities:{contextLength:1e5,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},mistral:{name:"Mistral",family:"mistral",tier:"economy",description:"Mistral AI 7B instruction-tuned model",releaseDate:"2023-09-27",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},mixtral:{name:"Mixtral",family:"mistral",tier:"standard",description:"Mistral AI mixture of experts model",releaseDate:"2023-12-11",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},phi3:{name:"Phi-3",family:"phi",tier:"economy",description:"Microsoft small language model, efficient",releaseDate:"2024-04-23",recommended:!0,capabilities:{contextLength:128e3,maxOutputTokens:4096,supportsTools:!1,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!1,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},qwen2:{name:"Qwen 2",family:"qwen",tier:"economy",description:"Alibaba multilingual model",releaseDate:"2024-06-07",recommended:!0,capabilities:{contextLength:32e3,maxOutputTokens:4096,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},"qwen3:8b":{name:"Qwen3 8B",family:"qwen",tier:"economy",description:"Alibaba Qwen3 8B \u2014 tools + thinking; below the QE test-gen floor (use for judge/triage)",releaseDate:"2025-04-29",recommended:!1,capabilities:{contextLength:40960,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},"qwen3:30b-a3b":{name:"Qwen3 30B-A3B",family:"qwen",tier:"economy",description:"Alibaba Qwen3 30B MoE (3B active) \u2014 fast general local model; clears the QE test-gen floor",releaseDate:"2025-04-29",recommended:!0,capabilities:{contextLength:262144,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!0,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}},"qwen3-coder:30b":{name:"Qwen3 Coder 30B-A3B",family:"qwen",tier:"economy",description:"Alibaba Qwen3-Coder 30B MoE (3B active) \u2014 code-tuned, non-thinking; preferred local QE test-gen model",releaseDate:"2025-07-31",recommended:!0,capabilities:{contextLength:262144,maxOutputTokens:8192,supportsTools:!0,supportsStreaming:!0,supportsVision:!1,supportsJsonMode:!0,supportsSystemPrompt:!0,supportsExtendedThinking:!1,supportsMCP:!1,supportsEmbeddings:!1,supportsCodeExecution:!1},cost:{inputCostPerMillion:0,outputCostPerMillion:0}}};function d(t){let e=i(t),s=l[e];if(!s)throw new Error(`Model not found in registry: ${t}`);return{...s.capabilities}}function M(t){try{return d(t).supportsTools}catch{return!0}}var h="claude-opus-4-7";export{c as a,i as b,u as c,d,M as e,h as f};
|
|
@@ -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.
|
|
2
|
-
import{c as s}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.13.0");process.exit(0)}
|
|
2
|
+
import{c as s}from"./chunk-ES7WCYOU.js";function A(r=l,o=process.env){let t=o.AQE_OLLAMA_URL??o.OLLAMA_URL??r,e=t.length;for(;e>0&&t.charCodeAt(e-1)===47;)e-=1;return t.slice(0,e)}var l,n=s(()=>{"use strict";l="http://localhost:11434"});export{A as a,n as b};
|
|
@@ -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.
|
|
2
|
-
import{i as e}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.13.0");process.exit(0)}
|
|
2
|
+
import{i as e}from"./chunk-E3B5XTXJ.js";function g(t,n,r,a){return{id:e(),type:t,timestamp:new Date,source:n,correlationId:a,payload:r}}var i={TestGenerated:"test-generation.TestGenerated",TestSuiteCreated:"test-generation.TestSuiteCreated",PatternLearned:"test-generation.PatternLearned",GenerationFailed:"test-generation.GenerationFailed"},s={TestRunStarted:"test-execution.TestRunStarted",TestRunCompleted:"test-execution.TestRunCompleted",FlakyTestDetected:"test-execution.FlakyTestDetected",RetryTriggered:"test-execution.RetryTriggered"},o={CoverageReportCreated:"coverage-analysis.CoverageReportCreated",CoverageGapDetected:"coverage-analysis.CoverageGapDetected",RiskZoneIdentified:"coverage-analysis.RiskZoneIdentified"},d={QualityGateEvaluated:"quality-assessment.QualityGateEvaluated",DeploymentApproved:"quality-assessment.DeploymentApproved",DeploymentBlocked:"quality-assessment.DeploymentBlocked"},l={DefectPredicted:"defect-intelligence.DefectPredicted",RootCauseIdentified:"defect-intelligence.RootCauseIdentified",RegressionRiskAnalyzed:"defect-intelligence.RegressionRiskAnalyzed"},c={KnowledgeGraphUpdated:"code-intelligence.KnowledgeGraphUpdated",ImpactAnalysisCompleted:"code-intelligence.ImpactAnalysisCompleted",SemanticSearchCompleted:"code-intelligence.SemanticSearchCompleted",C4DiagramsGenerated:"code-intelligence.C4DiagramsGenerated"},m={VulnerabilityDetected:"security-compliance.VulnerabilityDetected",ComplianceValidated:"security-compliance.ComplianceValidated",SecurityAuditCompleted:"security-compliance.SecurityAuditCompleted"},p={PatternConsolidated:"learning-optimization.PatternConsolidated",TransferCompleted:"learning-optimization.TransferCompleted",OptimizationApplied:"learning-optimization.OptimizationApplied",DreamCycleCompleted:"learning-optimization.dream.completed"},y={...i,...s,...o,...d,...l,...c,...m,...p};export{g as a,i as b,s as c,o as d,d as e,l as f,c as g,m as h,p as i};
|
|
@@ -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.
|
|
2
|
-
import{c as h}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.13.0");process.exit(0)}
|
|
2
|
+
import{c as h}from"./chunk-ES7WCYOU.js";function i(t,r){if(t.length!==r.length)throw new Error(`Vector length mismatch: ${t.length} vs ${r.length}`);let e=0,o=0,l=0;for(let n=0;n<t.length;n++)e+=t[n]*r[n],o+=t[n]*t[n],l+=r[n]*r[n];let u=Math.sqrt(o)*Math.sqrt(l);return u===0?0:e/u}function c(t){let r=Math.sqrt(t.reduce((e,o)=>e+o*o,0));return r===0?t.slice():t.map(e=>e/r)}function g(t){let r=0;for(let e=0;e<t.length;e++)r+=t[e]*t[e];return Math.sqrt(r)}var m=h(()=>{"use strict"});export{i as a,c as b,g as c,m as d};
|
|
@@ -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.
|
|
2
|
-
import{a as q}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.13.0");process.exit(0)}
|
|
2
|
+
import{a as q}from"./chunk-FQY3UTGA.js";import{c as V,d as W}from"./chunk-GJMZR7WU.js";import{c as x}from"./chunk-CFVEDUTW.js";import{a as G}from"./chunk-HVB2L52I.js";import{c as R}from"./chunk-OXXMVQDF.js";import{b as E,d as $}from"./chunk-2DIT5AUU.js";import{a as C,c as H}from"./chunk-CYL2FV23.js";import{i as v}from"./chunk-E3B5XTXJ.js";import{a as M,b as U,d as ee}from"./chunk-RDU4WTV2.js";var P={dbPath:".agentic-qe/dream.db",similarityThreshold:.5,maxEdgesPerNode:20,walMode:!0,debug:!1};$();H();var T=class p{config;db=null;persistence=null;prepared=new Map;initialized=!1;constructor(e){this.config={...P,...e}}async initialize(){if(!this.initialized)try{if(this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.prepareStatements(),this.initialized=!0,this.config.debug){let e=await this.getStats();console.log(`[ConceptGraph] Initialized: ${this.persistence.getDbPath()}`,e)}}catch(e){throw new Error(`Failed to initialize ConceptGraph: ${C(e)}`)}}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("insertNode",this.db.prepare(`
|
|
3
3
|
INSERT INTO concept_nodes
|
|
4
4
|
(id, concept_type, content, embedding, activation_level, last_activated, pattern_id, metadata)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -63,7 +63,7 @@ import{a as q}from"./chunk-LWVUNBZO.js";import{c as V,d as W}from"./chunk-5YLY2W
|
|
|
63
63
|
ORDER BY weight DESC
|
|
64
64
|
LIMIT -1 OFFSET ?
|
|
65
65
|
)
|
|
66
|
-
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-HAP5IAAY.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
|
|
66
|
+
`).run(s,e);r+=c.changes}return r})(),n>0&&console.log(`[ConceptGraph] Pruned ${n} edges (maxPerNode=${e}, minWeight=${t})`),n}async getStats(){this.ensureInitialized();let e=this.prepared.get("countNodes"),t=this.prepared.get("countEdges"),n=this.prepared.get("countByType");if(!e||!t||!n)throw new Error("Prepared statements not found");let i=e.get().count,r=t.get().count,a={pattern:0,technique:0,domain:0,outcome:0,error:0},o=n.all();for(let c of o)a[c.concept_type]=c.count;let s=0;return i>0&&(s=this.db.prepare("SELECT AVG(activation_level) as avg FROM concept_nodes").get().avg||0),{nodeCount:i,edgeCount:r,byType:a,avgEdgesPerNode:i>0?r/i:0,avgActivation:s}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("ConceptGraph not initialized. Call initialize() first.")}async getEdgeBetween(e,t){let n=this.prepared.get("getEdge");if(!n)throw new Error("Prepared statement not found: getEdge");let i=n.get(e,t);return i?this.rowToEdge(i):null}async findDomainNode(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE concept_type = 'domain' AND content = ?").get(e);return n?this.rowToNode(n):null}async findNodeByPatternId(e){if(!this.db)return null;let n=this.db.prepare("SELECT * FROM concept_nodes WHERE pattern_id = ? LIMIT 1").get(e);return n?this.rowToNode(n):null}rowToNode(e){let t;if(e.embedding){let n=e.embedding,i=new Float32Array(n.buffer,n.byteOffset,n.byteLength/4);t=Array.from(i)}return{id:e.id,conceptType:e.concept_type,content:e.content,embedding:t,activationLevel:e.activation_level||0,lastActivated:e.last_activated?new Date(e.last_activated):void 0,patternId:e.pattern_id||void 0,metadata:e.metadata?E(e.metadata):void 0,createdAt:e.created_at?new Date(e.created_at):void 0}}rowToEdge(e){return{id:e.id,source:e.source,target:e.target,weight:e.weight,edgeType:e.edge_type,evidence:e.evidence,createdAt:e.created_at?new Date(e.created_at):void 0,updatedAt:e.updated_at?new Date(e.updated_at):void 0}}};function te(p){return new T(p)}ee();function ne(p,e){if(e<0||e>=p.length)return p[0]??0;let t=0,n=p.length-1;for(;t<n;){let i=t+n>>1;if(p[i]<p[t]){let s=p[t];p[t]=p[i],p[i]=s}if(p[n]<p[t]){let s=p[t];p[t]=p[n],p[n]=s}if(p[i]<p[n]){let s=p[i];p[i]=p[n],p[n]=s}let r=p[n],a=t;for(let s=t;s<n;s++)if(p[s]<=r){let c=p[a];p[a]=p[s],p[s]=c,a++}let o=p[a];if(p[a]=p[n],p[n]=o,a===e)return p[a];a<e?t=a+1:n=a-1}return p[t]}var B=1e4,O=5e4,F=.8,j={decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},w=class{graph;config;activationHistory=new Map;coActivationCounts=new Map;constructor(e,t={}){this.graph=e,this.config={...j,...t}}async spread(e,t=1,n){let i=e.filter(d=>this.graph.getConcept(d)!==void 0);if(i.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};for(let d of i)this.graph.setActivation(d,t),this.recordActivation(d,t);let r=0,a=t,o=0,s=0;for(;r<this.config.maxIterations&&!(n!==void 0&&Date.now()>=n);){let d=await this.spreadIteration(),h=this.graph.getActiveNodes(this.config.threshold);for(let g of h)g.activationLevel>a&&(a=g.activationLevel);if(h.length===o&&d===0){if(s++,s>=3)break}else s=0;o=h.length,r++}let c=this.graph.getActiveNodes(this.config.threshold).map(d=>({nodeId:d.id,activation:d.activationLevel})).sort((d,h)=>h.activation-d.activation),l=await this.findNovelAssociations(this.config.threshold);return this.trimHistory(),{iterations:r,nodesActivated:c.length,peakActivation:a,activatedNodes:c,novelAssociations:l.map(d=>({source:d.source.id,target:d.target.id,strength:d.coActivation}))}}async dream(e){let t=Date.now(),n=[],i=0,r=0,a=new Set,o=this.graph.getAllConcepts(0);if(o.length===0)return{iterations:0,nodesActivated:0,peakActivation:0,activatedNodes:[],novelAssociations:[]};let s=t+e;for(;Date.now()<s;){let d=U(0,o.length),h=o[d];if(h){let g=this.config.noiseLevel+M()*this.config.noiseLevel*2,m=h.activationLevel,y=Math.min(1,m+g+.3);this.graph.setActivation(h.id,y);let f=await this.spread([h.id],y,s);i+=f.iterations,f.peakActivation>r&&(r=f.peakActivation);for(let D of f.activatedNodes)a.add(D.nodeId);for(let D of f.novelAssociations)n.push(D)}if(Date.now()>=s)break;await this.sleep(50+M()*50)}let c=this.deduplicateAssociations(n),l=Array.from(a).map(d=>{let h=this.graph.getConcept(d);return{nodeId:d,activation:h?.activationLevel??0}}).filter(d=>d.activation>0).sort((d,h)=>h.activation-d.activation);return this.trimHistory(),{iterations:i,nodesActivated:l.length,peakActivation:r,activatedNodes:l,novelAssociations:c.slice(0,20)}}async findNovelAssociations(e){let t=e??this.config.threshold,n=this.graph.getActiveNodes(t);if(n.length<2)return[];let i=200;n.length>i&&(n=n.sort((a,o)=>o.activationLevel-a.activationLevel).slice(0,i));let r=[];for(let a=0;a<n.length;a++)for(let o=a+1;o<n.length;o++){let s=n[a],c=n[o],l=Math.sqrt(s.activationLevel*c.activationLevel),d=this.graph.getEdge(s.id,c.id),h=this.graph.getEdge(c.id,s.id),g=d!==void 0||h!==void 0,m=d?.weight??h?.weight??0,y=!g||m<.3;l>.3&&(r.push({source:s,target:c,coActivation:l,isNovel:y}),this.trackCoActivation(s.id,c.id))}return r.sort((a,o)=>a.isNovel!==o.isNovel?a.isNovel?-1:1:o.coActivation-a.coActivation).slice(0,10)}async reset(){let e=this.graph.getAllConcepts(0);for(let t of e)this.graph.setActivation(t.id,0);this.activationHistory.clear(),this.coActivationCounts.clear()}getConfig(){return{...this.config}}trimActivationHistory(){if(this.activationHistory.size<=B)return;let e=Math.floor(B*F),t=this.activationHistory.size-e,n=Array.from(this.activationHistory.keys()).slice(0,t);for(let i of n)this.activationHistory.delete(i)}trimCoActivationCounts(){if(this.coActivationCounts.size<=O)return;let e=Math.floor(O*F),t=this.coActivationCounts.size-e,n=Array.from(this.coActivationCounts.values()),i=ne(n,t-1),r=[];for(let[a,o]of this.coActivationCounts){if(r.length>=t)break;o<=i&&r.push(a)}for(let a of r)this.coActivationCounts.delete(a)}trimHistory(){this.trimActivationHistory(),this.trimCoActivationCounts()}getHistorySizes(){return{activationHistorySize:this.activationHistory.size,coActivationCountsSize:this.coActivationCounts.size}}async spreadIteration(){let e=this.graph.getActiveNodes(this.config.threshold),t=0,n=[];for(let i of e){let r=this.graph.getEdges(i.id);for(let a of r){let o=this.graph.getConcept(a.target);if(!o)continue;let s=i.activationLevel*a.weight*this.config.spreadFactor;if(s>.01){let c=o.activationLevel,l=Math.min(1,c+s);n.push({nodeId:a.target,newActivation:l})}}}for(let i of n){let r=this.graph.getConcept(i.nodeId);r&&i.newActivation>r.activationLevel&&(this.graph.setActivation(i.nodeId,i.newActivation),this.recordActivation(i.nodeId,i.newActivation),t++)}return this.applyDecay(),this.injectNoise(),t}applyDecay(){let e=1-this.config.decayRate;this.graph.decayActivations(e)}injectNoise(){if(this.config.noiseLevel<=0)return;let e=this.graph.getAllConcepts(0);for(let t of e)if(t.activationLevel>0){let n=(M()-.5)*2*this.config.noiseLevel,i=Math.max(0,Math.min(1,t.activationLevel+n));this.graph.setActivation(t.id,i)}}recordActivation(e,t){let n=this.activationHistory.get(e)||[];n.push(t),n.length>50&&n.shift(),this.activationHistory.set(e,n)}trackCoActivation(e,t){let n=[e,t].sort().join(":"),i=this.coActivationCounts.get(n)||0;this.coActivationCounts.set(n,i+1)}deduplicateAssociations(e){let t=new Map;for(let n of e){let i=[n.source,n.target].sort().join(":"),r=t.get(i);(!r||n.strength>r.strength)&&t.set(i,n)}return Array.from(t.values()).sort((n,i)=>i.strength-n.strength)}sleep(e){return new Promise(t=>setTimeout(t,e))}};import{randomUUID as ie}from"crypto";var Q={minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},_=class{graph;config;constructor(e,t={}){this.graph=e,this.config={...Q,...t}}async generateFromActivation(e,t){let n=[],i=t.activatedNodes.map(c=>this.graph.getConcept(c.nodeId)).filter(c=>c!==void 0);if(i.length<2)return[];let r=await this.detectPatternMerges(i);for(let c of r)c.cycleId=e,n.push(c);let a=await this.detectNovelAssociations(t.novelAssociations);for(let c of a)c.cycleId=e,n.push(c);let o=await this.detectOptimizations(i);for(let c of o)c.cycleId=e,n.push(c);let s=await this.detectGaps(i);for(let c of s)c.cycleId=e,n.push(c);return n.filter(c=>c.noveltyScore>=this.config.minNoveltyScore).sort((c,l)=>l.noveltyScore-c.noveltyScore).slice(0,this.config.maxInsightsPerCycle)}async detectPatternMerges(e){let t=[],n=e.filter(i=>i.conceptType==="pattern"||i.conceptType==="technique");if(n.length<2)return t;for(let i=0;i<n.length;i++)for(let r=i+1;r<n.length;r++){let a=n[i],o=n[r],s=this.graph.getEdge(a.id,o.id),c=this.graph.getEdge(o.id,a.id),l=Math.max(s?.weight??0,c?.weight??0),d=this.calculateContentSimilarity(a.content,o.content),h=Math.sqrt(a.activationLevel*o.activationLevel),g=l*.4+d*.3+h*.3;if(g>.5){let m=this.calculateNovelty({type:"pattern_merge",sourceConcepts:[a.id,o.id]}),y=this.calculateConfidence({type:"pattern_merge",sourceConcepts:[a.id,o.id],edgeWeight:l,contentSimilarity:d,coActivation:h});t.push({id:this.generateId(),cycleId:"",type:"pattern_merge",sourceConcepts:[a.id,o.id],description:this.generatePatternMergeDescription(a,o,g),noveltyScore:m,confidenceScore:y,actionable:y>=this.config.minConfidence,applied:!1,suggestedAction:y>=this.config.minConfidence?`Merge "${this.truncate(a.content,30)}" with "${this.truncate(o.content,30)}" into a unified pattern.`:void 0,createdAt:new Date})}}return t}async detectNovelAssociations(e){let t=[];for(let n of e){let i=this.graph.getConcept(n.source),r=this.graph.getConcept(n.target);if(!i||!r)continue;let a=this.graph.getEdge(n.source,n.target);if(a&&a.weight>.5)continue;let o=i.conceptType!==r.conceptType,s=this.calculateNovelty({type:"novel_association",sourceConcepts:[n.source,n.target],isCrossDomain:o,strength:n.strength}),c=this.calculateConfidence({type:"novel_association",sourceConcepts:[n.source,n.target],coActivation:n.strength,isCrossDomain:o});t.push({id:this.generateId(),cycleId:"",type:"novel_association",sourceConcepts:[n.source,n.target],description:this.generateNovelAssociationDescription(i,r,n.strength,o),noveltyScore:s,confidenceScore:c,actionable:c>=this.config.minConfidence,applied:!1,suggestedAction:c>=this.config.minConfidence?`Investigate connection between "${this.truncate(i.content,25)}" and "${this.truncate(r.content,25)}".`:void 0,createdAt:new Date})}return t}async detectOptimizations(e){let t=[];for(let n of e){if(n.conceptType!=="pattern"&&n.conceptType!=="technique")continue;let i=n.metadata??{},r=i.successRate,a=i.executionCount,o=i.confidence,s=r!==void 0&&r<.7,c=a!==void 0&&a>10,l=o!==void 0&&o<.6;if(s||c&&l){let d=this.calculateNovelty({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c}),h=this.calculateConfidence({type:"optimization",sourceConcepts:[n.id],hasLowSuccess:s,hasHighUsage:c,metadata:i});t.push({id:this.generateId(),cycleId:"",type:"optimization",sourceConcepts:[n.id],description:this.generateOptimizationDescription(n,r,a),noveltyScore:d,confidenceScore:h,actionable:h>=this.config.minConfidence,applied:!1,suggestedAction:h>=this.config.minConfidence?`Review and optimize "${this.truncate(n.content,40)}" to improve success rate.`:void 0,createdAt:new Date})}}return t}async detectGaps(e){let t=[],n={pattern:[],technique:[],domain:[],outcome:[],error:[]};for(let i of e){let r=i.conceptType??"pattern";n[r]||(n[r]=[]),n[r].push(i)}for(let i of n.error??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&(s.conceptType==="pattern"||s.conceptType==="technique")})){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_resolution"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`No resolution pattern found for error: "${this.truncate(i.content,50)}". Consider creating a fix pattern.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Create a resolution pattern for: "${this.truncate(i.content,40)}".`,createdAt:new Date})}for(let i of n.outcome??[])if(!this.graph.getEdges(i.id).some(o=>{let s=this.graph.getConcept(o.target);return s&&s.conceptType==="technique"})&&(n.technique?.length??0)===0){let o=this.calculateNovelty({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"}),s=this.calculateConfidence({type:"gap_detection",sourceConcepts:[i.id],gapType:"missing_technique"});t.push({id:this.generateId(),cycleId:"",type:"gap_detection",sourceConcepts:[i.id],description:`Outcome "${this.truncate(i.content,40)}" has no associated technique. Document how this outcome is achieved.`,noveltyScore:o,confidenceScore:s,actionable:!0,applied:!1,suggestedAction:`Document the technique for achieving: "${this.truncate(i.content,35)}".`,createdAt:new Date})}return t}calculateNovelty(e){let t=.5;if(e.isCrossDomain&&(t+=.2),e.strength!==void 0&&e.strength>.5&&(t+=.15),e.type==="gap_detection"&&(t+=.2),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.sourceConcepts.length>=2){let n=this.graph.getEdge(e.sourceConcepts[0],e.sourceConcepts[1]);n?n.weight<.3&&(t+=.05):t+=.1}return Math.min(1,Math.max(0,t))}calculateConfidence(e){let t=.4;if(e.coActivation!==void 0&&(t+=e.coActivation*.3),e.edgeWeight!==void 0&&(t+=e.edgeWeight*.2),e.contentSimilarity!==void 0&&e.type==="pattern_merge"&&(t+=e.contentSimilarity*.2),e.isCrossDomain&&(t-=.1),e.hasHighUsage&&e.hasLowSuccess&&(t+=.15),e.metadata){let n=Math.min(Object.keys(e.metadata).length*.05,.15);t+=n}return e.gapType&&(t+=.1),Math.min(1,Math.max(0,t))}async insightToPattern(e){if(!e.actionable)return null;let t=e.sourceConcepts.map(n=>this.graph.getConcept(n)).filter(n=>n!==void 0);if(t.length===0)return null;switch(e.type){case"pattern_merge":{let[n,i]=t;return{name:`Merged: ${this.truncate(n?.content??"",20)} + ${this.truncate(i?.content??"",20)}`,description:e.description,template:{type:"merged_pattern",sourcePatterns:e.sourceConcepts,mergedContent:t.map(r=>r.content).join(" | "),metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"novel_association":{let[n,i]=t;return{name:`Association: ${n?.conceptType} - ${i?.conceptType}`,description:e.description,template:{type:"association_pattern",source:{id:n?.id,type:n?.conceptType,content:n?.content},target:{id:i?.id,type:i?.conceptType,content:i?.content},metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"optimization":{let[n]=t;return{name:`Optimized: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"optimization_pattern",originalPattern:n?.id,suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}case"gap_detection":{let[n]=t;return{name:`Gap Fill: ${this.truncate(n?.content??"",30)}`,description:e.description,template:{type:"gap_fill_pattern",relatedConcept:n?.id,gapType:n?.conceptType==="error"?"missing_resolution":"missing_technique",suggestedAction:e.suggestedAction,metadata:{noveltyScore:e.noveltyScore,confidenceScore:e.confidenceScore,createdFrom:"dream_insight"}}}}default:return null}}generateId(){let e=Date.now(),t=ie().slice(0,8);return`insight-${e}-${t}`}calculateContentSimilarity(e,t){let n=e.toLowerCase().split(/\s+/),i=t.toLowerCase().split(/\s+/),r=new Set(n),a=new Set(i),o=n.filter(c=>a.has(c)),s=r.size+a.size-o.length;return s===0?0:o.length/s}truncate(e,t){return e.length<=t?e:e.substring(0,t-3)+"..."}generatePatternMergeDescription(e,t,n){return`Pattern merge opportunity (${Math.round(n*100)}% match): "${this.truncate(e.content,40)}" and "${this.truncate(t.content,40)}" share similar structure and could be combined.`}generateNovelAssociationDescription(e,t,n,i){let r=Math.round(n*100);return`Novel association discovered${i?" (cross-domain)":""}: [${e.conceptType}] "${this.truncate(e.content,30)}" is connected to [${t.conceptType}] "${this.truncate(t.content,30)}" with ${r}% co-activation strength.`}generateOptimizationDescription(e,t,n){let i=[`Optimization opportunity for "${this.truncate(e.content,40)}":`];return t!==void 0&&i.push(`Success rate is ${Math.round(t*100)}%.`),n!==void 0&&i.push(`Used ${n} times.`),i.push("Consider reviewing and improving this pattern."),i.join(" ")}getConfig(){return{...this.config}}};$();H();G();import{existsSync as re,unlinkSync as ae}from"fs";var A={maxPatternCountDrop:.05,maxAvgConfidenceDrop:.02,maxHighConfidenceLoss:.05},b=class{constructor(e,t=A){this.db=e;this.thresholds=t}db;thresholds;activeBranches=new Map;listeners=[];rvfAdapter;useRvfFork=!1;_witnessChain=null;set witnessChain(e){this._witnessChain=e}setRvfAdapter(e,t=!0){this.rvfAdapter=e,this.useRvfFork=t,import("./feature-flags-N3UHMSZ3.js").then(({isRVFPatternStoreEnabled:n})=>{this.useRvfFork=n()}).catch(()=>{})}createBranch(e){if(this.activeBranches.has(e))throw new Error(`Branch '${e}' already exists`);let t=this.sanitizeSavepointName(e),n=this.captureBaseline();this.db.exec(`SAVEPOINT "${t}"`);let i={name:e,createdAt:new Date,status:"active",baselineSnapshot:n};if(this.rvfAdapter&&this.useRvfFork)try{let r=`/tmp/dream-branch-${t}.rvf`,a=this.rvfAdapter.derive(r),o=i;o._rvfBranchPath=r,o._rvfChildAdapter=a}catch{}return this.activeBranches.set(e,i),this.emit("dream:branch_created",i),i}validateBranch(e,t){this.ensureBranchActive(e.name);let n=t??e.baselineSnapshot,i=this.captureBaseline(),r=i.patternCount-n.patternCount,a=i.avgConfidence-n.avgConfidence,o=n.highConfidenceCount-i.highConfidenceCount,s=[],c=!0;if(n.patternCount>0){let d=-r/n.patternCount;d>this.thresholds.maxPatternCountDrop&&(c=!1,s.push(`Pattern count dropped by ${(d*100).toFixed(1)}% (threshold: ${(this.thresholds.maxPatternCountDrop*100).toFixed(1)}%)`))}if(a<-this.thresholds.maxAvgConfidenceDrop&&(c=!1,s.push(`Avg confidence dropped by ${(-a).toFixed(4)} (threshold: ${this.thresholds.maxAvgConfidenceDrop})`)),n.highConfidenceCount>0&&o>0){let d=o/n.highConfidenceCount;d>this.thresholds.maxHighConfidenceLoss&&(c=!1,s.push(`${o} high-confidence patterns lost (${(d*100).toFixed(1)}%, threshold: ${(this.thresholds.maxHighConfidenceLoss*100).toFixed(1)}%)`))}if(this.rvfAdapter&&this.useRvfFork&&n.patternCount>0)try{let d=this.rvfAdapter.dimension?.()??384,h=new Float32Array(d);for(let m=0;m<d;m++)h[m]=Math.sin(m*.1);let g=this.rvfAdapter.search?.(h,10)??[];g.length<Math.min(5,n.patternCount)&&s.push(`Search recall degraded: only ${g.length} results returned (expected \u2265${Math.min(5,n.patternCount)})`)}catch{}let l=c?"All quality checks passed":`Validation failed: ${s.join("; ")}`;return{passed:c,reason:l,patternCountDelta:r,avgConfidenceDelta:a,highConfidenceLost:Math.max(0,o),postDreamMetrics:i}}mergeBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="merged",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_merged",e);try{this._witnessChain?.append("BRANCH_MERGE",{branchName:e.name},"rvcow-branch-manager")}catch{}}discardBranch(e){this.ensureBranchActive(e.name);let t=this.sanitizeSavepointName(e.name);this.db.exec(`ROLLBACK TO SAVEPOINT "${t}"`),this.db.exec(`RELEASE SAVEPOINT "${t}"`),e.status="discarded",this.activeBranches.delete(e.name),this.cleanupRvfBranch(e),this.emit("dream:branch_discarded",e)}listBranches(){return Array.from(this.activeBranches.values())}onEvent(e){this.listeners.push(e)}offEvent(e){let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}captureBaseline(){let e=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get(),t=this.db.prepare("SELECT AVG(confidence) as avg_conf FROM qe_patterns").get(),n=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns WHERE confidence >= 0.8").get();return{patternCount:e?.cnt??0,avgConfidence:t?.avg_conf??0,highConfidenceCount:n?.cnt??0,capturedAt:new Date}}ensureBranchActive(e){let t=this.activeBranches.get(e);if(!t)throw new Error(`Branch '${e}' not found or not active`);if(t.status!=="active")throw new Error(`Branch '${e}' is ${t.status}, not active`)}cleanupRvfBranch(e){let t=e;try{t._rvfChildAdapter?.close?.()}catch{}try{let n=t._rvfBranchPath;n&&re(n)&&ae(n)}catch{}}sanitizeSavepointName(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}emit(e,t,n){for(let i of this.listeners)try{i(e,t,n)}catch{}}};var S=R.create("dream-engine"),X={maxDurationMs:3e4,minConceptsRequired:10,activationConfig:{decayRate:.1,spreadFactor:.5,threshold:.1,maxIterations:20,noiseLevel:.05},insightConfig:{minNoveltyScore:.3,minConfidence:.5,maxInsightsPerCycle:10},enableBranching:!0,branchValidationThresholds:{...A}},k=class{constructor(e){this.graph=e}graph;nodeCache=new Map;edgeCache=new Map;activationLevels=new Map;async loadIntoMemory(e){this.nodeCache.clear(),this.edgeCache.clear(),this.activationLevels.clear();let t=await this.graph.getActiveNodes(0);e&&t.length>e&&(t=t.sort((n,i)=>i.activationLevel-n.activationLevel).slice(0,e));for(let n of t)this.nodeCache.set(n.id,n),this.activationLevels.set(n.id,n.activationLevel);for(let n of t){let r=(await this.graph.getNeighbors(n.id)).map(a=>a.edge);this.edgeCache.set(n.id,r)}}async persistActivations(){let e=Array.from(this.activationLevels.entries());for(let[t,n]of e)await this.graph.updateActivation(t,n)}getConcept(e){let t=this.nodeCache.get(e);if(t)return{...t,activationLevel:this.activationLevels.get(e)??t.activationLevel}}getAllConcepts(e){let t=e??0;return Array.from(this.nodeCache.values()).map(n=>({...n,activationLevel:this.activationLevels.get(n.id)??n.activationLevel})).filter(n=>n.activationLevel>=t)}getActiveNodes(e){return this.getAllConcepts(e)}getEdges(e){return this.edgeCache.get(e)??[]}getEdge(e,t){return(this.edgeCache.get(e)??[]).find(i=>i.target===t)}setActivation(e,t){this.activationLevels.set(e,Math.max(0,Math.min(1,t)))}decayActivations(e){let t=Array.from(this.activationLevels.entries());for(let[n,i]of t)this.activationLevels.set(n,i*e)}getStats(){let e=Array.from(this.nodeCache.values()),t={pattern:0,technique:0,domain:0,outcome:0,error:0},n=0;for(let a of e)t[a.conceptType]=(t[a.conceptType]??0)+1,n+=this.activationLevels.get(a.id)??a.activationLevel;let i=0,r=Array.from(this.edgeCache.values());for(let a of r)i+=a.length;return{nodeCount:e.length,edgeCount:i,byType:t,avgEdgesPerNode:e.length>0?i/e.length:0,avgActivation:e.length>0?n/e.length:0}}},N=class{config;persistence=null;graph=null;db=null;branchManager=null;currentCycle=null;initialized=!1;cancelled=!1;branchEventListeners=[];_witnessChain=null;set witnessChain(e){this._witnessChain=e}_rvfAdapter=null;set rvfAdapter(e){this._rvfAdapter=e}constructor(e){this.config={...X,...e}}async initialize(){if(!this.initialized)try{this.persistence=x(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase();try{this.db.pragma("busy_timeout = 60000")}catch{}this.migrateSchema(),this.graph=new T,await this.graph.initialize(),this.config.enableBranching&&(this.branchManager=new b(this.db,this.config.branchValidationThresholds),this._rvfAdapter&&(this.branchManager.setRvfAdapter(this._rvfAdapter,!0),console.log("[DreamEngine] RVF COW branching activated (ADR-069)"))),this.initialized=!0,console.log(`[DreamEngine] Initialized: ${this.persistence.getDbPath()}`)}catch(e){throw new Error(`Failed to initialize DreamEngine: ${C(e)}`)}}migrateSchema(){if(this.db)try{let e=this.db.prepare("PRAGMA table_info(dream_cycles)").all(),t=e.some(s=>s.name==="duration_ms"),n=e.some(s=>s.name==="duration");!t&&n&&this.db.exec("ALTER TABLE dream_cycles RENAME COLUMN duration TO duration_ms");let i=this.db.prepare("PRAGMA table_info(dream_insights)").all(),r=new Set(i.map(s=>s.name)),a=r.has("insight_type"),o=r.has("source_concepts");if(!a)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN insight_type TEXT NOT NULL DEFAULT 'general'"),S.info("Added insight_type column to dream_insights (safe migration)")}catch{}if(!o)try{this.db.exec("ALTER TABLE dream_insights ADD COLUMN source_concepts TEXT NOT NULL DEFAULT '[]'"),S.info("Added source_concepts column to dream_insights (safe migration)")}catch{}this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_type ON dream_insights(insight_type)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_insight_novelty ON dream_insights(novelty_score DESC)")}catch(e){S.debug("Dream schema migration skipped",{error:e instanceof Error?e.message:String(e)})}}async dream(e){this.ensureInitialized(),this.cancelled=!1;let t=e??this.config.maxDurationMs,n=Date.now();this.currentCycle={id:v(),startTime:new Date,conceptsProcessed:0,associationsFound:0,insightsGenerated:0,status:"running"},await this.saveCycle(this.currentCycle);let i=null;if(this.branchManager){let r=`dream-${this.currentCycle.id}-${Date.now()}`;i=this.branchManager.createBranch(r),this.emitBranchEvent("dream:branch_created",i)}try{let r=await this.graph.getActiveNodes(0);if(r.length<this.config.minConceptsRequired)throw new Error(`Insufficient concepts: ${r.length} < ${this.config.minConceptsRequired}`);let a=new k(this.graph);await a.loadIntoMemory(30);let s=await new w(a,this.config.activationConfig).dream(t);if(this.cancelled)throw this.currentCycle.status="interrupted",this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle),new Error("Dream cycle cancelled");this.currentCycle.conceptsProcessed=s.nodesActivated,this.currentCycle.associationsFound=s.novelAssociations.length,await a.persistActivations();let l=await new _(a,this.config.insightConfig).generateFromActivation(this.currentCycle.id,s);this.currentCycle.insightsGenerated=l.length;for(let h of l)await this.saveInsight(h);if(this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,this.currentCycle.status="completed",await this.updateCycle(this.currentCycle),i&&this.branchManager){let h=this.branchManager.validateBranch(i);if(h.passed){this.branchManager.mergeBranch(i),this.emitBranchEvent("dream:branch_merged",i,h);try{this._witnessChain?.append("DREAM_MERGE",{cycleId:this.currentCycle.id,branchName:i.name},"dream-engine")}catch{}}else{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i,h);try{this._witnessChain?.append("DREAM_DISCARD",{cycleId:this.currentCycle.id,branchName:i.name,reason:h.reason},"dream-engine")}catch{}S.warn("Dream branch discarded: quality validation failed",{cycleId:this.currentCycle.id,reason:h.reason})}i=null}let d={cycle:{...this.currentCycle},insights:l,activationStats:{totalIterations:s.iterations,peakActivation:s.peakActivation,nodesActivated:s.nodesActivated},patternsCreated:0};return this.currentCycle=null,d}catch(r){if(i&&this.branchManager)try{this.branchManager.discardBranch(i),this.emitBranchEvent("dream:branch_discarded",i)}catch{}throw this.currentCycle&&(this.currentCycle.status==="running"&&(this.currentCycle.status="failed"),this.currentCycle.error=C(r),this.currentCycle.endTime=new Date,this.currentCycle.durationMs=Date.now()-n,await this.updateCycle(this.currentCycle)),this.currentCycle=null,r}}async loadPatternsAsConcepts(e){return this.ensureInitialized(),this.graph.loadFromPatterns(e)}async loadFailuresAsConcepts(e){return this.ensureInitialized(),this.graph.loadFailuresAsErrors(e)}async loadSuccessesAsConcepts(e){return this.ensureInitialized(),this.graph.loadSuccessesAsOutcomes(e)}async ensureConceptsLoaded(){this.ensureInitialized();try{let n=this.db.prepare(`SELECT n.id as id, n.pattern_id as sourcePatternId, p.qe_domain as domain, n.failure_mode as failureMode
|
|
67
67
|
FROM qe_pattern_nulls n
|
|
68
68
|
JOIN qe_patterns p ON p.id = n.pattern_id
|
|
69
69
|
ORDER BY n.updated_at DESC
|
|
@@ -89,7 +89,7 @@ import{a as q}from"./chunk-LWVUNBZO.js";import{c as V,d as W}from"./chunk-5YLY2W
|
|
|
89
89
|
WHERE confidence >= 0.3 AND success_rate < 0.7
|
|
90
90
|
ORDER BY usage_count DESC
|
|
91
91
|
LIMIT 40
|
|
92
|
-
)`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-
|
|
92
|
+
)`).all();return t.length===0?0:this.graph.loadFromPatterns(t)}async applyInsight(e){this.ensureInitialized();try{let t=await this.getInsightRowById(e);if(!t)return{success:!1,error:`Insight not found: ${e}`};if(t.actionable!==1)return{success:!1,error:"Insight is not actionable"};if(t.applied===1)return{success:!0,patternId:t.pattern_id??void 0,error:"Insight already applied"};let{getSharedMemoryBackend:n}=await import("./base-O3SPSWBA.js"),{createQEReasoningBank:i}=await import("./qe-reasoning-bank-S2R2PCBS.js"),r=await n(),a=i(r);await a.initialize();try{let{getSharedRvfDualWriter:d}=await import("./shared-rvf-dual-writer-MKSLKWDI.js"),h=await d();h&&a.setRvfDualWriter(h)}catch(d){process.env.DEBUG&&S.debug("RVF wiring skipped",{error:C(d)})}let o=[];try{o=E(t.source_concepts)}catch{}let s=await a.storePattern({patternType:se(t.insight_type),name:`Dream Insight: ${t.insight_type}`,description:`${t.description} (confidence: ${t.confidence_score.toFixed(2)})`,template:{type:"workflow",content:t.suggested_action||t.description,variables:[]},context:{tags:["dream-generated",t.insight_type,...o.slice(0,3)],complexity:"medium"}});if(!s.success)return{success:!1,error:`Failed to create pattern: ${s.error?.message??"unknown error"}`};let c=s.value.id;return this.db.prepare(`
|
|
93
93
|
UPDATE dream_insights
|
|
94
94
|
SET applied = 1, pattern_id = ?
|
|
95
95
|
WHERE id = ?
|
|
@@ -117,4 +117,4 @@ import{a as q}from"./chunk-LWVUNBZO.js";import{c as V,d as W}from"./chunk-5YLY2W
|
|
|
117
117
|
(id, cycle_id, insight_type, source_concepts, description, novelty_score,
|
|
118
118
|
confidence_score, actionable, applied, suggested_action, pattern_id)
|
|
119
119
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
120
|
-
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-HAP5IAAY.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-HDDCXCHY.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-HDDCXCHY.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-CXXTB7CU.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
|
|
120
|
+
`).run(e.id,e.cycleId,e.type,JSON.stringify(e.sourceConcepts),e.description,e.noveltyScore,e.confidenceScore,e.actionable?1:0,0,e.suggestedAction??null,null)}async getInsightRowById(e){return this.db?this.db.prepare("SELECT * FROM dream_insights WHERE id = ?").get(e)??null:null}getBranchManager(){return this.branchManager}onBranchEvent(e){this.branchEventListeners.push(e)}emitBranchEvent(e,t,n){for(let i of this.branchEventListeners)try{i(e,t,n)}catch{}}async close(){this.graph&&(await this.graph.close(),this.graph=null),this.db=null,this.persistence=null,this.branchManager=null,this.initialized=!1,this.currentCycle=null}ensureInitialized(){if(!this.initialized||!this.graph||!this.db)throw new Error("DreamEngine not initialized. Call initialize() first.")}rowToCycle(e){return{id:e.id,startTime:new Date(e.start_time),endTime:e.end_time?new Date(e.end_time):void 0,durationMs:e.duration_ms??void 0,conceptsProcessed:e.concepts_processed,associationsFound:e.associations_found,insightsGenerated:e.insights_generated,status:e.status,error:e.error??void 0}}rowToInsight(e){return{id:e.id,cycleId:e.cycle_id,type:e.insight_type,sourceConcepts:E(e.source_concepts),description:e.description,noveltyScore:e.novelty_score,confidenceScore:e.confidence_score,actionable:e.actionable===1,applied:e.applied===1,patternId:e.pattern_id??void 0,suggestedAction:e.suggested_action??void 0,createdAt:new Date(e.created_at)}}};function se(p){return{"cross-domain":"coverage-strategy","novel-path":"test-template",cluster:"refactor-safe","high-activation":"assertion-pattern",bridge:"mock-pattern"}[p]||"test-template"}function oe(p){let e=new N(p);return import("./feature-flags-N3UHMSZ3.js").then(({isRVFPatternStoreEnabled:t})=>t()?import("./shared-rvf-adapter-3CJHRNX6.js"):null).then(t=>{if(!t)return;let n=t.getSharedRvfAdapter();n&&(e.rvfAdapter=n)}).catch(()=>{}),e}var ce=N;G();var Y="learning:loop-health";async function J(p,e,t){try{let n=new Date().toISOString(),i=await p.get(Y)??{overallLastSuccess:"",bootedAt:n,components:{}},r=i.components[e]??{lastSuccessAt:"",ticksSinceBoot:0,successesSinceBoot:0};if(r.ticksSinceBoot+=1,t.success)r.lastSuccessAt=n,r.successesSinceBoot+=1,delete r.lastError;else if(t.error){let o=t.error instanceof Error?t.error.message:String(t.error);r.lastError={message:o,at:n}}i.components[e]=r;let a=Object.values(i.components).map(o=>o?.lastSuccessAt??"").filter(o=>o!=="");i.overallLastSuccess=a.length>0?a.sort().pop():"",await p.set(Y,i)}catch{}}var u=R.create("DreamScheduler"),Z={autoScheduleIntervalMs:36e5,minTimeBetweenDreamsMs:3e5,experienceThreshold:20,enableExperienceTrigger:!0,enableQualityGateFailureTrigger:!0,enableDomainMilestoneTrigger:!1,defaultDreamDurationMs:1e4,quickDreamDurationMs:5e3,fullDreamDurationMs:3e4,autoApplyHighConfidenceInsights:!1,insightConfidenceThreshold:.8},K="dream-scheduler:hook-state",L=class p{config;dreamEngine;eventBus;memoryBackend;initialized=!1;running=!1;dreaming=!1;experienceBuffer=[];lastDreamTime=null;scheduledDreamTimer=null;totalDreamsCompleted=0;subscriptions=[];lastDreamResult=null;metaLearningEngine;metaLearningSnapshots=[];metricsTracker=null;static MAX_META_SNAPSHOTS=20;detectedInsights=[];static MAX_DETECTED_INSIGHTS=100;constructor(e,t){if(!e.dreamEngine)throw new Error("DreamScheduler requires dreamEngine dependency");if(!e.eventBus)throw new Error("DreamScheduler requires eventBus dependency");this.dreamEngine=e.dreamEngine,this.eventBus=e.eventBus,this.memoryBackend=e.memoryBackend,this.config={...Z,...t},this.metaLearningEngine=new W}async initialize(){if(!this.initialized){if(this.config.enableQualityGateFailureTrigger){let e=this.eventBus.subscribe("quality-assessment:gate:completed",this.handleQualityGateEvent.bind(this));this.subscriptions.push(e)}if(this.config.enableDomainMilestoneTrigger){let e=this.eventBus.subscribe("coordination:milestone:reached",this.handleDomainMilestoneEvent.bind(this));this.subscriptions.push(e)}await this.restoreState(),this.initialized=!0,u.info("Initialized")}}start(){this.ensureInitialized(),!this.running&&(this.running=!0,this.scheduleNextDream(),u.info("Started"))}stop(){this.running&&(this.running=!1,this.clearScheduledDream(),u.info("Stopped"))}async dispose(){this.stop();for(let e of this.subscriptions)e.unsubscribe();this.subscriptions=[],this.metricsTracker&&(this.metricsTracker.close(),this.metricsTracker=null),await this.saveState(),this.initialized=!1,u.info("Disposed")}async triggerDream(e){if(this.ensureInitialized(),!this.canDream()){let t=this.getTimeUntilCanDream();throw new Error(`Cannot start dream: minimum interval not met. Wait ${Math.ceil(t/1e3)}s.`)}return this.executeDream(e??this.config.defaultDreamDurationMs)}async triggerQuickDream(){return this.triggerDream(this.config.quickDreamDurationMs)}async triggerFullDream(){return this.triggerDream(this.config.fullDreamDurationMs)}recordExperience(e){this.experienceBuffer.push(e),this.config.enableExperienceTrigger&&this.experienceBuffer.length>=this.config.experienceThreshold&&this.canDream()&&!this.dreaming&&(u.info("Experience threshold reached, triggering dream",{threshold:this.config.experienceThreshold}),this.executeDream(this.config.defaultDreamDurationMs).catch(t=>{u.error("Experience-triggered dream failed",t instanceof Error?t:void 0)}))}getExperienceBuffer(){return[...this.experienceBuffer]}clearExperienceBuffer(){this.experienceBuffer=[]}getStatus(){let e=this.scheduledDreamTimer?this.getTimeUntilScheduledDream():null;return{initialized:this.initialized,running:this.running,dreaming:this.dreaming,experienceCount:this.experienceBuffer.length,experienceThreshold:this.config.experienceThreshold,timeUntilNextDream:e,totalDreamsCompleted:this.totalDreamsCompleted,lastDreamTime:this.lastDreamTime,autoSchedulingEnabled:this.running}}getLastDreamResult(){return this.lastDreamResult}getMetaInsights(e){let t=[...this.detectedInsights].reverse();return e!==void 0?t.slice(0,e):t}async executeDream(e){if(this.dreaming)throw new Error("A dream is already in progress");this.dreaming=!0,u.info("Starting dream cycle",{durationMs:e});let t;try{let n=await this.dreamEngine.ensureConceptsLoaded();n>0&&u.info("Auto-loaded concepts for dream",{loaded:n});let i=await this.dreamEngine.dream(e);if(this.lastDreamTime=new Date,this.lastDreamResult=i,this.totalDreamsCompleted++,this.clearExperienceBuffer(),await this.reconcileHookState(),this.config.autoApplyHighConfidenceInsights&&await this.autoApplyInsights(i),await this.publishDreamCompletedEvent(i),await this.maybeCompactPatternsRvf(),process.env.AQE_META_LEARNING_ENABLED==="true")try{await this.runPostDreamMetaLearning()}catch(r){u.warn("Post-dream meta-learning failed (non-critical)",{error:r instanceof Error?r.message:String(r)})}return this.running&&this.scheduleNextDream(),u.info("Dream completed",{insightsGenerated:i.insights.length}),i}catch(n){throw t=n instanceof Error?n:new Error(String(n)),n}finally{this.dreaming=!1,this.memoryBackend&&await J(this.memoryBackend,"dreamScheduler",{success:!t,error:t})}}async autoApplyInsights(e){let t=e.insights.filter(n=>n.actionable&&n.confidenceScore>=this.config.insightConfidenceThreshold);for(let n of t)try{let i=await this.dreamEngine.applyInsight(n.id);i.success&&u.info("Auto-applied insight",{insightId:n.id,patternId:i.patternId})}catch(i){u.error("Failed to auto-apply insight",i instanceof Error?i:void 0,{insightId:n.id})}}async maybeCompactPatternsRvf(){try{let t=(await import("./shared-rvf-adapter-3CJHRNX6.js")).compactSharedRvfAdapter();t&&t.bytesReclaimed>0&&u.info("patterns.rvf compacted",{bytesReclaimed:t.bytesReclaimed,segmentsCompacted:t.segmentsCompacted})}catch(e){u.warn("patterns.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}try{let t=(await import("./shared-rvf-dual-writer-MKSLKWDI.js")).getSharedRvfDualWriterSync();if(t){let n=t.compact();n&&n.bytesReclaimed>0&&u.info("brain.rvf compacted",{bytesReclaimed:n.bytesReclaimed,segmentsCompacted:n.segmentsCompacted})}}catch(e){u.warn("brain.rvf compaction skipped (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async runPostDreamMetaLearning(){this.metricsTracker||(this.metricsTracker=new q,await this.metricsTracker.initialize());let e=await this.metricsTracker.collectUnifiedSnapshot();for(this.metaLearningSnapshots.push(e);this.metaLearningSnapshots.length>p.MAX_META_SNAPSHOTS;)this.metaLearningSnapshots.shift();let t=V.minSnapshotsForAnalysis;if(this.metaLearningSnapshots.length>=t){let n=this.metaLearningEngine.runMetaLearningCycle(this.metaLearningSnapshots);if(n.length>0){u.info("Meta-learning insights detected",{count:n.length,types:n.map(i=>i.type)});for(let i of n)u.info(`Meta-insight [${i.type}]: ${i.description}`,{confidence:i.confidence.toFixed(2),suggestedAction:i.suggestedAction}),this.detectedInsights.push(i);for(;this.detectedInsights.length>p.MAX_DETECTED_INSIGHTS;)this.detectedInsights.shift();try{this.eventBus.publish({id:v(),type:"meta-learning.insight-detected",timestamp:new Date,source:"learning-optimization",payload:{count:n.length,insights:n.map(i=>({id:i.id,type:i.type,description:i.description,confidence:i.confidence,suggestedAction:i.suggestedAction,detectedAt:i.detectedAt}))}})}catch{u.debug("Failed to publish meta-learning insight event")}}}else u.debug("Meta-learning: accumulating snapshots",{current:this.metaLearningSnapshots.length,required:t})}scheduleNextDream(){if(this.clearScheduledDream(),!this.running)return;let e=this.calculateNextDreamDelay();this.scheduledDreamTimer=setTimeout(async()=>{if(!(!this.running||this.dreaming))try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Scheduled dream failed",t instanceof Error?t:void 0),this.running&&this.scheduleNextDream()}},e),u.info("Next dream scheduled",{delaySeconds:Math.ceil(e/1e3)})}clearScheduledDream(){this.scheduledDreamTimer&&(clearTimeout(this.scheduledDreamTimer),this.scheduledDreamTimer=null)}calculateNextDreamDelay(){if(!this.lastDreamTime)return this.config.autoScheduleIntervalMs;let e=Date.now()-this.lastDreamTime.getTime(),t=this.config.autoScheduleIntervalMs-e;return Math.max(t,this.config.minTimeBetweenDreamsMs)}getTimeUntilScheduledDream(){return this.calculateNextDreamDelay()}canDream(){return this.lastDreamTime?Date.now()-this.lastDreamTime.getTime()>=this.config.minTimeBetweenDreamsMs:!0}getTimeUntilCanDream(){if(!this.lastDreamTime)return 0;let e=Date.now()-this.lastDreamTime.getTime();return Math.max(0,this.config.minTimeBetweenDreamsMs-e)}async handleQualityGateEvent(e){if(!e.payload.passed){if(!this.canDream()||this.dreaming){u.info("Quality gate failed but cannot start dream yet");return}u.info("Quality gate failed, triggering analysis dream");try{await this.executeDream(this.config.quickDreamDurationMs)}catch(t){u.error("Quality gate triggered dream failed",t instanceof Error?t:void 0)}}}async handleDomainMilestoneEvent(e){if(!this.canDream()||this.dreaming){u.info("Milestone reached but cannot start dream yet");return}u.info("Domain milestone reached, triggering consolidation dream");try{await this.executeDream(this.config.defaultDreamDurationMs)}catch(t){u.error("Milestone triggered dream failed",t instanceof Error?t:void 0)}}async publishDreamCompletedEvent(e){try{await this.eventBus.publish({id:v(),type:"learning-optimization:dream:completed",timestamp:new Date,source:"learning-optimization",payload:{cycleId:e.cycle.id,insightsGenerated:e.insights.length,patternsCreated:e.patternsCreated,duration:e.cycle.durationMs}})}catch(t){u.error("Failed to publish dream completed event",t instanceof Error?t:void 0)}}async reconcileHookState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get(K),t={lastDreamTime:(this.lastDreamTime??new Date).toISOString(),experienceCount:0,sessionStartTime:e?.sessionStartTime,totalDreamsThisSession:(e?.totalDreamsThisSession??0)+1};await this.memoryBackend.set(K,t)}catch(e){u.warn("Dream hook-state reconcile failed (non-critical)",{error:e instanceof Error?e.message:String(e)})}}async saveState(){if(this.memoryBackend)try{await this.memoryBackend.set("dream-scheduler:state",{lastDreamTime:this.lastDreamTime?.toISOString()??null,totalDreamsCompleted:this.totalDreamsCompleted,experienceBuffer:this.experienceBuffer},{namespace:"learning-optimization",persist:!0})}catch(e){u.error("Failed to save state",e instanceof Error?e:void 0)}}async restoreState(){if(this.memoryBackend)try{let e=await this.memoryBackend.get("dream-scheduler:state");e&&(this.lastDreamTime=e.lastDreamTime?new Date(e.lastDreamTime):null,this.totalDreamsCompleted=e.totalDreamsCompleted??0,this.experienceBuffer=e.experienceBuffer??[],u.info("Restored state",{totalDreamsCompleted:this.totalDreamsCompleted,experienceCount:this.experienceBuffer.length}))}catch(e){u.error("Failed to restore state",e instanceof Error?e:void 0)}}ensureInitialized(){if(!this.initialized)throw new Error("DreamScheduler not initialized. Call initialize() first.")}};function de(p,e){return new L(p,e)}var pe=[{name:"aggressive-exploration",description:"High noise, fast decay -- explores widely but forgets quickly",activationConfig:{decayRate:.2,spreadFactor:.7,noiseLevel:.15,maxIterations:30}},{name:"conservative-consolidation",description:"Low noise, slow decay -- strengthens existing associations",activationConfig:{decayRate:.05,spreadFactor:.3,noiseLevel:.02,maxIterations:15}},{name:"balanced-discovery",description:"Moderate parameters -- balanced between exploration and consolidation",activationConfig:{decayRate:.1,spreadFactor:.5,noiseLevel:.05,maxIterations:20}}],z=class{constructor(e,t){this.db=e;this.branchManager=new b(e,t??A)}db;branchManager;async dream(e,t){if(e.length<1)throw new Error("At least one strategy is required");if(e.length>5)throw new Error("Maximum 5 strategies allowed to limit resource usage");let n=Date.now(),i=this.branchManager.captureBaseline(),r=[];for(let s of e){let c=await this.executeStrategy(s,i,t);r.push(c)}let a=r.filter(s=>s.validation.passed),o=null;if(a.length>0){o=a.reduce((c,l)=>{let d=this.scoreValidation(c.validation);return this.scoreValidation(l.validation)>d?l:c});let s=this.branchManager.createBranch(`dream-final-${o.strategy.name}-${Date.now()}`);try{await t(o.strategy.activationConfig),this.branchManager.mergeBranch(s),o.selected=!0}catch{this.branchManager.discardBranch(s),o.selected=!1,o=null}}return{strategies:r,winner:o,totalDurationMs:Date.now()-n}}getBranchManager(){return this.branchManager}async executeStrategy(e,t,n){let i=`dream-spec-${e.name}-${Date.now()}`,r=this.branchManager.createBranch(i),a=Date.now();try{await n(e.activationConfig);let o=this.branchManager.validateBranch(r,t);return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:o,selected:!1,durationMs:Date.now()-a}}catch{return this.branchManager.discardBranch(r),{strategy:e,branch:r,validation:{passed:!1,reason:"Dream execution threw an error",patternCountDelta:0,avgConfidenceDelta:0,highConfidenceLost:0,postDreamMetrics:t},selected:!1,durationMs:Date.now()-a}}}scoreValidation(e){return e.avgConfidenceDelta*100+e.patternCountDelta*.1-e.highConfidenceLost*5}};export{J as a,P as b,T as c,te as d,B as e,O as f,F as g,j as h,w as i,Q as j,_ as k,A as l,b as m,X as n,N as o,oe as p,ce as q,pe as r,z as s,Z as t,L as u,de as v};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.
|
|
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.13.0");process.exit(0)}
|
|
2
2
|
import a from"chalk";import{existsSync as m,statSync as S}from"fs";import{join as p,relative as P}from"path";var l=class{static prompt(t,e){return new Promise(r=>{t.question(e,s=>{r(s)})})}static printStepHeader(t,e,r){console.log(""),console.log(a.cyan(`Step ${t}: ${e}`)),r&&console.log(a.gray(r)),console.log("")}static printWizardHeader(t,e){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(` ${t}`)),console.log(a.blue("========================================")),e&&console.log(a.gray(e)),console.log(a.gray("Press Ctrl+C to cancel at any time")),console.log("")}static printSummaryHeader(){console.log(""),console.log(a.blue("========================================")),console.log(a.blue.bold(" Configuration Summary")),console.log(a.blue("========================================")),console.log("")}static printSummaryField(t,e,r){let s=r?.indent??" ",i=r?.maxItems??5,c=r?.formatValue??(o=>a.cyan(o));if(Array.isArray(e))e.length===0?console.log(a.white(`${s}${t}: ${a.gray("(none)")}`)):e.length<=i?console.log(a.white(`${s}${t}: ${c(e.join(", "))}`)):(console.log(a.white(`${s}${t}:`)),e.slice(0,i).forEach(o=>{console.log(a.gray(`${s} - ${o}`))}),console.log(a.gray(`${s} ... and ${e.length-i} more`)));else{let o=t.padEnd(16);console.log(a.white(`${s}${o}${c(e)}`))}}static printDerivedSettings(t,e=" "){console.log(""),console.log(a.gray(`${e}Derived settings:`));for(let[r,s]of Object.entries(t))console.log(a.gray(`${e} ${r}: ${s}`));console.log("")}};var h=class u{static getSourceDirectories(t){let e=[],r=["src","lib","app","packages","api"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&e.push(s)}return e}static getCoverageTargets(t){let e=u.getSourceDirectories(t),r=["coverage","coverage/lcov.info","coverage/coverage-final.json",".nyc_output"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getSecurityTargets(t){let e=u.getSourceDirectories(t),r=["package.json","package-lock.json","yarn.lock","pnpm-lock.yaml",".env",".env.example","docker-compose.yml","Dockerfile"];for(let s of r){let i=p(t,s);m(i)&&e.push(s)}return e}static getTestSourceFiles(t){let e=[],r=["src","lib","app","packages"];for(let s of r){let i=p(t,s);m(i)&&S(i).isDirectory()&&(e.push(`${s}/**/*.ts`),e.push(s))}return m(p(t,"src"))&&(e.push("src/services/**/*.ts"),e.push("src/utils/**/*.ts"),e.push("src/components/**/*.tsx")),e}static checkPatternsExist(t){return[p(t,".agentic-qe","patterns"),p(t,".agentic-qe","memory.db"),p(t,".aqe","patterns"),p(t,"data","patterns")].some(r=>m(r))}},f=class{static relativePath(t,e){return P(e,t)||"."}static yesNo(t){return t?"Yes":"No"}static enabledDisabled(t){return t?"Enabled":"Disabled"}static percentage(t){return`${t}%`}static truncatedList(t,e=5){return t.length===0?"(none)":t.length<=e?t.join(", "):`${t.slice(0,e).join(", ")}... and ${t.length-e} more`}};import n from"chalk";import{existsSync as w}from"fs";import{resolve as I}from"path";var d=class{constructor(t){this.defaultValue=t}defaultValue;description;getDefaultValue(){return this.defaultValue}success(t){return{value:t,continue:!0}}cancelled(){return{value:this.defaultValue,continue:!1}}error(t){return{value:this.defaultValue,continue:!1,error:t}}};var y=class extends d{id;stepNumber;title;description;options;validValues;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.options.forEach(i=>{let c=[];i.isRecommended?c.push(n.green(" (recommended)")):(i.isDefault||i.value===this.defaultValue)&&c.push(n.green(" (default)")),console.log(n.white(` ${i.key}. ${i.label||i.value}${c.join("")}`)),i.description&&console.log(n.gray(` ${i.description}`))}),console.log("");let r=(await l.prompt(t.rl,`Select ${this.title.toLowerCase()} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);return s>=1&&s<=this.options.length?this.success(this.options[s-1].value):this.validValues.includes(r)?this.success(r):(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue))}},b=class extends d{id;stepNumber;title;description;options;validValues;instructions;allowEmpty;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.options=t.options,this.validValues=t.validValues,this.instructions=t.instructions,this.allowEmpty=t.allowEmpty??!1}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.instructions&&(console.log(n.gray(this.instructions)),console.log("")),this.options.forEach(o=>{let N=o.isDefaultSelected||this.defaultValue.includes(o.value)?n.green(" *"):"";console.log(n.white(` ${o.key}. ${o.label||o.value}${N}`)),o.description&&console.log(n.gray(` ${o.description}`))}),console.log(""),console.log(n.gray(" * = included in default selection")),console.log("");let e=this.defaultValue.join(","),s=(await l.prompt(t.rl,`Select options [${n.gray(e)}]: `)).trim();if(!s)return this.success(this.defaultValue);let i=s.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o.length>0),c=[];for(let o of i){let g=parseInt(o,10);g>=1&&g<=this.options.length?c.push(this.options[g-1].value):this.validValues.includes(o)&&c.push(o)}return c.length===0?this.allowEmpty?this.success([]):(console.log(n.yellow(` Invalid input, using default: ${e}`)),this.success(this.defaultValue)):this.success([...new Set(c)])}},v=class extends d{id;stepNumber;title;description;additionalInfo;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.additionalInfo=t.additionalInfo}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.additionalInfo&&(console.log(n.gray(this.additionalInfo)),console.log(""));let e=this.defaultValue?"Y/n":"y/N",s=(await l.prompt(t.rl,`${this.title}? [${n.gray(e)}]: `)).trim().toLowerCase();return s===""?this.success(this.defaultValue):s==="n"||s==="no"?this.success(!1):s==="y"||s==="yes"?this.success(!0):this.success(this.defaultValue)}},x=class extends d{id;stepNumber;title;description;presets;min;max;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.presets=t.presets,this.min=t.min,this.max=t.max}async execute(t){if(t.nonInteractive)return this.success(this.defaultValue);l.printStepHeader(this.stepNumber,this.title,this.description),this.presets&&this.presets.length>0&&(this.presets.forEach(i=>{let c=i.value===this.defaultValue?n.green(" (default)"):"";console.log(n.gray(` ${i.key}. ${i.label}${c}`))}),this.min!==void 0&&this.max!==void 0&&console.log(n.gray(` Or enter a custom number (${this.min}-${this.max})`)),console.log(""));let r=(await l.prompt(t.rl,`${this.title} [${n.gray(String(this.defaultValue))}]: `)).trim();if(!r)return this.success(this.defaultValue);let s=parseInt(r,10);if(this.presets){let i=s;if(i>=1&&i<=this.presets.length)return this.success(this.presets[i-1].value)}return isNaN(s)?(console.log(n.yellow(` Invalid input, using default: ${this.defaultValue}`)),this.success(this.defaultValue)):this.min!==void 0&&s<this.min?(console.log(n.yellow(` Value too low, using minimum: ${this.min}`)),this.success(this.min)):this.max!==void 0&&s>this.max?(console.log(n.yellow(` Value too high, using maximum: ${this.max}`)),this.success(this.max)):this.success(s)}},C=class extends d{id;stepNumber;title;description;examples;suggestionsProvider;validatePath;constructor(t){super(t.defaultValue),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description,this.examples=t.examples,this.suggestionsProvider=t.suggestionsProvider,this.validatePath=t.validatePath??!0}async execute(t){if(t.nonInteractive){let i=I(t.cwd,this.defaultValue);return this.success(w(i)?i:t.cwd)}if(l.printStepHeader(this.stepNumber,this.title,this.description),this.examples&&(console.log(n.gray(`Examples: ${this.examples}`)),console.log("")),this.suggestionsProvider){let i=this.suggestionsProvider(t.cwd);i.length>0&&(console.log(n.yellow("Detected directories:")),i.slice(0,5).forEach((c,o)=>{console.log(n.gray(` ${o+1}. ${c}`))}),console.log(""))}let r=(await l.prompt(t.rl,`${this.title} [${n.gray(this.defaultValue)}]: `)).trim()||this.defaultValue,s=I(t.cwd,r);return this.validatePath&&!w(s)?(console.log(n.yellow(` Warning: '${r}' does not exist, using current directory.`)),this.success(t.cwd)):this.success(s)}};var T=class extends d{id;stepNumber;title;description;constructor(t){super({}),this.id=t.id,this.stepNumber=t.stepNumber,this.title=t.title,this.description=t.description}async execute(t){if(t.nonInteractive)return this.success({});l.printStepHeader(this.stepNumber,this.title,this.description);let e=await l.prompt(t.rl,`Include patterns [${n.gray("e.g., src/**/*.ts")}]: `),r=await l.prompt(t.rl,`Exclude patterns [${n.gray("e.g., **/*.test.ts,dist/**")}]: `),s={};return e.trim()&&(s.include=e.split(",").map(i=>i.trim()).filter(i=>i.length>0)),r.trim()&&(s.exclude=r.split(",").map(i=>i.trim()).filter(i=>i.length>0)),this.success(s)}};import{createInterface as R}from"readline";import $ from"chalk";var V=class{options;cwd;constructor(t){this.options=t,this.cwd=process.cwd()}async run(){if(this.isNonInteractive())return this.getDefaults();let t=R({input:process.stdin,output:process.stdout});try{this.printHeader();let e={},r=this.getCommands();for(let c of r){let o={rl:t,cwd:this.cwd,results:e,nonInteractive:!1},g=await c.execute(o);if(!g.continue)return this.getCancelled();e[c.id]=g.value}let s=this.buildResult(e);return this.printSummary(s),await this.promptConfirmation(t)?s:this.getCancelled()}finally{t.close()}}printHeader(){l.printWizardHeader(this.getTitle(),this.getSubtitle())}async promptConfirmation(t){console.log("");let r=(await l.prompt(t,`${$.green(this.getConfirmationPrompt())} [${$.gray("Y/n")}]: `)).trim().toLowerCase();return r==="n"||r==="no"?(console.log($.yellow(`
|
|
3
3
|
Wizard cancelled.`)),!1):!0}};export{l as a,h as b,f as c,y as d,b as e,v as f,x as g,C as h,T as i,V as j};
|