agentic-qe 3.13.6 → 3.13.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (336) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +63 -0
  3. package/assets/skills/skills-manifest.json +1 -1
  4. package/dist/cli/bundle.js +5 -5
  5. package/dist/cli/chunks/adapter-DM2E2X4Q.js +2 -0
  6. package/dist/cli/chunks/{agent-booster-wasm-TMON22NL.js → agent-booster-wasm-W5KKWWGM.js} +2 -2
  7. package/dist/cli/chunks/{agent-handler-JOX6O26U.js → agent-handler-U27BOQIY.js} +2 -2
  8. package/dist/cli/chunks/{agent-memory-branch-AMIJIDCM.js → agent-memory-branch-FYEN2L2U.js} +2 -2
  9. package/dist/cli/chunks/aqe-learning-engine-STMX2LM7.js +2 -0
  10. package/dist/cli/chunks/{arena-RKLFXDMO.js → arena-7GWHLRNN.js} +4 -4
  11. package/dist/cli/chunks/{arena-N6SO2CCQ.js → arena-F2ZO52SD.js} +2 -2
  12. package/dist/cli/chunks/{audit-ZJE3DUH6.js → audit-O4RLECCQ.js} +3 -3
  13. package/dist/cli/chunks/base-EPDGZB2X.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-5G6AR6LX.js → better-sqlite3-3VQVXH7I.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-QD4DZ574.js → brain-handler-Z4FSHVHF.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-PG3OUYE6.js → branch-enumerator-VW7QDS3O.js} +2 -2
  17. package/dist/cli/chunks/{browser-Y2DJG7HQ.js → browser-P5PZI236.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-CRZ6635H.js +2 -0
  19. package/dist/cli/chunks/{chunk-Z6SAS2NU.js → chunk-22TNTFEN.js} +1 -1
  20. package/dist/cli/chunks/{chunk-TMM5NKPI.js → chunk-2CJ5V2DT.js} +1 -1
  21. package/dist/cli/chunks/{chunk-2FTAMEOB.js → chunk-2CSKJ5JM.js} +1 -1
  22. package/dist/cli/chunks/{chunk-N7JRGAJF.js → chunk-2GD3RLVF.js} +2 -2
  23. package/dist/cli/chunks/{chunk-2ILX73JG.js → chunk-2Q7T3PL4.js} +1 -1
  24. package/dist/cli/chunks/{chunk-TWNXZOJY.js → chunk-3KSB2PDF.js} +2 -2
  25. package/dist/cli/chunks/{chunk-75QKZ6VX.js → chunk-3OJWLZIO.js} +2 -2
  26. package/dist/cli/chunks/{chunk-RBNSZFVL.js → chunk-3UENFJEV.js} +3 -3
  27. package/dist/cli/chunks/{chunk-FH6H4KOZ.js → chunk-426SRHIW.js} +20 -20
  28. package/dist/cli/chunks/{chunk-7TON6JSG.js → chunk-4GTPYV66.js} +2 -2
  29. package/dist/cli/chunks/{chunk-JGQZ7ECC.js → chunk-55UQC4BO.js} +1 -1
  30. package/dist/cli/chunks/{chunk-3TC4ZPGR.js → chunk-5LLHM6NK.js} +2 -2
  31. package/dist/cli/chunks/{chunk-X75OYPS6.js → chunk-5P2K6VVS.js} +1 -1
  32. package/dist/cli/chunks/{chunk-IHUAEQZN.js → chunk-5PRVDHNG.js} +1 -1
  33. package/dist/cli/chunks/{chunk-VK5I4JSN.js → chunk-5QZAXVUI.js} +2 -2
  34. package/dist/cli/chunks/{chunk-RDSO3R2R.js → chunk-65LJ2QU4.js} +3 -3
  35. package/dist/cli/chunks/{chunk-NX6FOAS4.js → chunk-6BNPFSFE.js} +1 -1
  36. package/dist/cli/chunks/{chunk-6ITWOYET.js → chunk-6H3VRSJ4.js} +2 -2
  37. package/dist/cli/chunks/{chunk-2SVDR5KB.js → chunk-756OZOSH.js} +2 -2
  38. package/dist/cli/chunks/{chunk-NUDDFJYU.js → chunk-7QJ344ZA.js} +2 -2
  39. package/dist/cli/chunks/{chunk-PX7MVV6F.js → chunk-7TK24XF7.js} +2 -2
  40. package/dist/cli/chunks/{chunk-OS56PKRO.js → chunk-7VWAKVRE.js} +2 -2
  41. package/dist/cli/chunks/{chunk-QQA4N3YT.js → chunk-A3V4SRLU.js} +2 -2
  42. package/dist/cli/chunks/{chunk-UNLH7NPY.js → chunk-ACZ7CNBM.js} +1 -1
  43. package/dist/cli/chunks/{chunk-XZPAKAFJ.js → chunk-AGJG5PAS.js} +1 -1
  44. package/dist/cli/chunks/{chunk-CBXJ4AQS.js → chunk-AKCNLYE3.js} +2 -2
  45. package/dist/cli/chunks/{chunk-R2GHZ2QG.js → chunk-AMTA6V5L.js} +2 -2
  46. package/dist/cli/chunks/{chunk-6QZSF6RL.js → chunk-BC37ZYBO.js} +2 -2
  47. package/dist/cli/chunks/{chunk-MOIKR7RU.js → chunk-BS4ZARET.js} +2 -2
  48. package/dist/cli/chunks/{chunk-DS53MJCN.js → chunk-BTCQJOI2.js} +1 -1
  49. package/dist/cli/chunks/{chunk-Y2QZK46R.js → chunk-BU6HG2RT.js} +2 -2
  50. package/dist/cli/chunks/{chunk-E7MD5LHC.js → chunk-C37IK75J.js} +2 -2
  51. package/dist/cli/chunks/{chunk-CTILSLXF.js → chunk-CB23FNZW.js} +2 -2
  52. package/dist/cli/chunks/{chunk-PA6SUNDD.js → chunk-CB6FBMND.js} +1 -1
  53. package/dist/cli/chunks/{chunk-PW3JLQGH.js → chunk-CDBTYQ4N.js} +2 -2
  54. package/dist/cli/chunks/{chunk-V5MS6XNT.js → chunk-CDVGXGUX.js} +2 -2
  55. package/dist/cli/chunks/{chunk-KBHSID6C.js → chunk-CK2I5QTK.js} +2 -2
  56. package/dist/cli/chunks/{chunk-K7ZFBGLE.js → chunk-CR5ZQXMN.js} +2 -2
  57. package/dist/cli/chunks/{chunk-EKWEJOV7.js → chunk-CZTNTQZA.js} +1 -1
  58. package/dist/cli/chunks/{chunk-LYGHX4II.js → chunk-D2SHZXX7.js} +1 -1
  59. package/dist/cli/chunks/{chunk-XRH2D6JV.js → chunk-D45ZSWZD.js} +3 -3
  60. package/dist/cli/chunks/{chunk-EYHRYIBX.js → chunk-D53CCDCD.js} +1 -1
  61. package/dist/cli/chunks/{chunk-5VGQABM3.js → chunk-DKX6SIVF.js} +4 -4
  62. package/dist/cli/chunks/{chunk-FGQH5LOG.js → chunk-DPQ2IANL.js} +2 -2
  63. package/dist/cli/chunks/{chunk-U63JEFF5.js → chunk-DTN5NUAJ.js} +2 -2
  64. package/dist/cli/chunks/{chunk-7NYCYSGW.js → chunk-DW5F6DJM.js} +2 -2
  65. package/dist/cli/chunks/{chunk-WA553ALQ.js → chunk-DZHVLIR6.js} +1 -1
  66. package/dist/cli/chunks/{chunk-MTEEFP6V.js → chunk-E2OORKCW.js} +2 -2
  67. package/dist/cli/chunks/{chunk-ADYY2GKC.js → chunk-EO3RV7QV.js} +2 -2
  68. package/dist/cli/chunks/{chunk-KHDE4KT5.js → chunk-FMTURKX4.js} +4 -4
  69. package/dist/cli/chunks/{chunk-QSO5RFJ4.js → chunk-FSKEQ625.js} +4 -4
  70. package/dist/cli/chunks/{chunk-HWWMINXV.js → chunk-GO6GSIHE.js} +2 -2
  71. package/dist/cli/chunks/{chunk-5VV5MOED.js → chunk-GPRPGL5N.js} +2 -2
  72. package/dist/cli/chunks/{chunk-DR2M2SI2.js → chunk-GVX4IAKF.js} +2 -2
  73. package/dist/cli/chunks/{chunk-2BUDKFIE.js → chunk-HBM423QM.js} +1 -1
  74. package/dist/cli/chunks/{chunk-2VUXU22M.js → chunk-HD22NMGP.js} +2 -2
  75. package/dist/cli/chunks/{chunk-UHQA6EH6.js → chunk-HP76TI6A.js} +2 -2
  76. package/dist/cli/chunks/{chunk-4YFBAXRD.js → chunk-HQQI4ZEO.js} +1 -1
  77. package/dist/cli/chunks/{chunk-4VWB64OH.js → chunk-HRAU4ZC3.js} +1 -1
  78. package/dist/cli/chunks/{chunk-JPJSOS4H.js → chunk-I6LGE3DO.js} +1 -1
  79. package/dist/cli/chunks/{chunk-EVJSK56E.js → chunk-ICET3FUT.js} +3 -3
  80. package/dist/cli/chunks/{chunk-PTBW2QXE.js → chunk-IYOGT6HD.js} +2 -2
  81. package/dist/cli/chunks/{chunk-R5FSKAS3.js → chunk-J3EDJVZR.js} +1 -1
  82. package/dist/cli/chunks/{chunk-ACHMNMEJ.js → chunk-JKSAZL2F.js} +1 -1
  83. package/dist/cli/chunks/chunk-K6XYLMXO.js +2 -0
  84. package/dist/cli/chunks/{chunk-YOVQBSTW.js → chunk-L24DBYXX.js} +2 -2
  85. package/dist/cli/chunks/{chunk-6VUEUYFL.js → chunk-LXGDJ5TO.js} +5 -5
  86. package/dist/cli/chunks/{chunk-POZ3S4UO.js → chunk-M3PXWTNF.js} +2 -2
  87. package/dist/cli/chunks/{chunk-DLBJ7IZT.js → chunk-M7O7UKP3.js} +10 -10
  88. package/dist/cli/chunks/{chunk-GEH3S5DI.js → chunk-MKCCKFUY.js} +2 -2
  89. package/dist/cli/chunks/{chunk-GSZL3WST.js → chunk-MLFS3MVR.js} +2 -2
  90. package/dist/cli/chunks/{chunk-7KRZ2Q6B.js → chunk-MMNNQ5PO.js} +3 -3
  91. package/dist/cli/chunks/{chunk-YL7CAOQG.js → chunk-MQKQTX4T.js} +3 -3
  92. package/dist/cli/chunks/{chunk-JDADNBWS.js → chunk-MRLPZMA3.js} +1 -1
  93. package/dist/cli/chunks/{chunk-VSP2IB5N.js → chunk-N7ITWNQP.js} +2 -2
  94. package/dist/cli/chunks/{chunk-Q4RU4XG6.js → chunk-NJ7SVXE6.js} +2 -2
  95. package/dist/cli/chunks/{chunk-ISOTSVI7.js → chunk-NW5XQQMC.js} +1 -1
  96. package/dist/cli/chunks/{chunk-UN2MXDJT.js → chunk-NXTV6EJQ.js} +2 -2
  97. package/dist/cli/chunks/{chunk-D777E2MT.js → chunk-OWWLOSVW.js} +2 -2
  98. package/dist/cli/chunks/{chunk-523XPMTU.js → chunk-OZSYL2CL.js} +1 -1
  99. package/dist/cli/chunks/{chunk-P4CHYYJN.js → chunk-P6PRMORM.js} +2 -2
  100. package/dist/cli/chunks/{chunk-V4QQTPZF.js → chunk-PDIJAWCK.js} +2 -2
  101. package/dist/cli/chunks/{chunk-463VBHHH.js → chunk-PIPV2C7N.js} +2 -2
  102. package/dist/cli/chunks/{chunk-BDVZF46F.js → chunk-PLIUHFVE.js} +2 -2
  103. package/dist/cli/chunks/{chunk-BAOKXLIV.js → chunk-PTAX4IY2.js} +2 -2
  104. package/dist/cli/chunks/{chunk-F66FYZQF.js → chunk-PVUQMV6P.js} +2 -2
  105. package/dist/cli/chunks/{chunk-YQUZGPUQ.js → chunk-PZS742LW.js} +1 -1
  106. package/dist/cli/chunks/{chunk-LQYAJ7RR.js → chunk-Q53NBMNL.js} +2 -2
  107. package/dist/cli/chunks/{chunk-7225UNNY.js → chunk-QFHOF4F3.js} +2 -2
  108. package/dist/cli/chunks/{chunk-X3CHYV7G.js → chunk-QMMRUFEI.js} +2 -2
  109. package/dist/cli/chunks/{chunk-NUCVMWDJ.js → chunk-QWACAQQ4.js} +2 -2
  110. package/dist/cli/chunks/{chunk-LVLGRUUJ.js → chunk-QYPXBIP5.js} +1 -1
  111. package/dist/cli/chunks/{chunk-5CMZDVUR.js → chunk-QYZLZ6P3.js} +2 -2
  112. package/dist/cli/chunks/{chunk-TGSL4OOT.js → chunk-R557EYUJ.js} +2 -2
  113. package/dist/cli/chunks/{chunk-PGDDPZ7W.js → chunk-RWSBQ2AD.js} +1 -1
  114. package/dist/cli/chunks/{chunk-OIGWREK7.js → chunk-SBGMMCPJ.js} +1 -1
  115. package/dist/cli/chunks/{chunk-YRRYKR7U.js → chunk-SECJ2IQE.js} +2 -2
  116. package/dist/cli/chunks/{chunk-DXM7IN2W.js → chunk-SEOOA2FX.js} +2 -2
  117. package/dist/cli/chunks/{chunk-AOUULKKT.js → chunk-SLTIRAYZ.js} +2 -2
  118. package/dist/cli/chunks/{chunk-GV3C224P.js → chunk-SSIOQDWN.js} +2 -2
  119. package/dist/cli/chunks/{chunk-PSAXLKDZ.js → chunk-SXSCWO6M.js} +2 -2
  120. package/dist/cli/chunks/{chunk-3QJH5W55.js → chunk-SYPXKVVR.js} +2 -2
  121. package/dist/cli/chunks/{chunk-E3OKRZCH.js → chunk-SZYHPGZD.js} +2 -2
  122. package/dist/cli/chunks/{chunk-EYWR4Y3J.js → chunk-TM55OOPV.js} +1 -1
  123. package/dist/cli/chunks/{chunk-PLYGIUFO.js → chunk-TQL4CSAS.js} +2 -2
  124. package/dist/cli/chunks/{chunk-JQXAWTS5.js → chunk-U6O3CFIW.js} +3 -3
  125. package/dist/cli/chunks/{chunk-P6A35LKJ.js → chunk-UGBHQC32.js} +2 -2
  126. package/dist/cli/chunks/{chunk-NNIAUDHF.js → chunk-UJ5KZ764.js} +1 -1
  127. package/dist/cli/chunks/{chunk-EY44JDUL.js → chunk-UK2267F4.js} +3 -3
  128. package/dist/cli/chunks/{chunk-FV47SYXK.js → chunk-VJDGJ6CW.js} +1 -1
  129. package/dist/cli/chunks/{chunk-7GTB7LVJ.js → chunk-W2FT6OUU.js} +3 -3
  130. package/dist/cli/chunks/{chunk-LLVXOXAK.js → chunk-W4CW6TKP.js} +1 -1
  131. package/dist/cli/chunks/{chunk-O34674VM.js → chunk-WIDOUTFF.js} +2 -2
  132. package/dist/cli/chunks/{chunk-THW6LF5I.js → chunk-WMRLLJDW.js} +2 -2
  133. package/dist/cli/chunks/{chunk-LGP26FTM.js → chunk-WR3PYP6X.js} +2 -2
  134. package/dist/cli/chunks/{chunk-BGLSIA4U.js → chunk-X4FHVATG.js} +2 -2
  135. package/dist/cli/chunks/{chunk-CKYRZ3TA.js → chunk-X6MSSQFP.js} +2 -2
  136. package/dist/cli/chunks/{chunk-GQCYO54W.js → chunk-X6VCAUOX.js} +2 -2
  137. package/dist/cli/chunks/{chunk-HBNMEYJS.js → chunk-XIJGRH5I.js} +10 -10
  138. package/dist/cli/chunks/chunk-XJT6TR5E.js +2 -0
  139. package/dist/cli/chunks/{chunk-6UPQD42K.js → chunk-XKKCH24C.js} +2 -2
  140. package/dist/cli/chunks/{chunk-EP4ORDFE.js → chunk-XONUAS4K.js} +2 -2
  141. package/dist/cli/chunks/{chunk-DSTQ2OWI.js → chunk-XPMQEFQI.js} +1 -1
  142. package/dist/cli/chunks/{chunk-R5LDNZVB.js → chunk-XUB5UG7C.js} +2 -2
  143. package/dist/cli/chunks/{chunk-BI6UU3Z3.js → chunk-Y5JWDXGB.js} +1 -1
  144. package/dist/cli/chunks/{chunk-XLDEWLP4.js → chunk-Y6EFJG52.js} +1 -1
  145. package/dist/cli/chunks/{chunk-6FICUNAV.js → chunk-Y7ALSL72.js} +1 -1
  146. package/dist/cli/chunks/{chunk-KMCI3RGD.js → chunk-YCL7OWK3.js} +2 -2
  147. package/dist/cli/chunks/{chunk-BOM5NGCR.js → chunk-YEGZUE6G.js} +1 -1
  148. package/dist/cli/chunks/{chunk-3OUHOJBN.js → chunk-YHV23E6J.js} +1 -1
  149. package/dist/cli/chunks/{chunk-MSA6MD5C.js → chunk-YISGZEZR.js} +1 -1
  150. package/dist/cli/chunks/{chunk-N6QUDQ5H.js → chunk-YLFM5AZ4.js} +2 -2
  151. package/dist/cli/chunks/{chunk-AU3APBY2.js → chunk-YRSKYBOL.js} +2 -2
  152. package/dist/cli/chunks/{chunk-XF2TKGSC.js → chunk-YTBW2SLZ.js} +1 -1
  153. package/dist/cli/chunks/{chunk-HPRX5S74.js → chunk-YWISQTXQ.js} +1 -1
  154. package/dist/cli/chunks/{chunk-JH6KUV74.js → chunk-ZKOIWNH7.js} +2 -2
  155. package/dist/cli/chunks/{chunk-DKGDBKBJ.js → chunk-ZLWYE47I.js} +1 -1
  156. package/dist/cli/chunks/{chunk-DSIS6WQD.js → chunk-ZNJJLA64.js} +3 -3
  157. package/dist/cli/chunks/{chunk-SZO6JIFM.js → chunk-ZO6QWQ2G.js} +2 -2
  158. package/dist/cli/chunks/{ci-MWQVCZ2W.js → ci-3Z3OSULB.js} +2 -2
  159. package/dist/cli/chunks/{ci-output-ZCH4IZ7H.js → ci-output-ETGFFPKJ.js} +2 -2
  160. package/dist/cli/chunks/{circuit-breaker-N3VSQM5X.js → circuit-breaker-G7ABL353.js} +2 -2
  161. package/dist/cli/chunks/{claude-flow-setup-TSJFOGXN.js → claude-flow-setup-EKBBG7HG.js} +2 -2
  162. package/dist/cli/chunks/client-IAOK3VSF.js +2 -0
  163. package/dist/cli/chunks/{cline-installer-OHKWAB4I.js → cline-installer-TRNHEMDA.js} +2 -2
  164. package/dist/cli/chunks/{code-3UTIL3QR.js → code-JMENIVDM.js} +2 -2
  165. package/dist/cli/chunks/{code-index-extractor-TVG2V2NY.js → code-index-extractor-JIYCGDUF.js} +2 -2
  166. package/dist/cli/chunks/{codex-installer-L6ZOTOO2.js → codex-installer-XBHDOIN7.js} +2 -2
  167. package/dist/cli/chunks/{completions-SFRB664X.js → completions-HF6I7WD3.js} +2 -2
  168. package/dist/cli/chunks/{complexity-analyzer-HDZKVO6D.js → complexity-analyzer-MWV6KUSW.js} +2 -2
  169. package/dist/cli/chunks/{continuedev-installer-HKLZR3UO.js → continuedev-installer-YWTPGW7K.js} +2 -2
  170. package/dist/cli/chunks/{copilot-installer-5P3LX3C5.js → copilot-installer-V2SX7GBX.js} +2 -2
  171. package/dist/cli/chunks/core-handlers-624KK362.js +2 -0
  172. package/dist/cli/chunks/{cost-tracker-MZR5RB6E.js → cost-tracker-RQJRRISN.js} +2 -2
  173. package/dist/cli/chunks/{coverage-L6V6NFIM.js → coverage-IZ43CIOL.js} +3 -3
  174. package/dist/cli/chunks/cross-domain-router-2DAGKVTZ.js +2 -0
  175. package/dist/cli/chunks/{cursor-installer-FD6DT23Y.js → cursor-installer-K3VUWVE3.js} +2 -2
  176. package/dist/cli/chunks/{daemon-HTSRODRG.js → daemon-HFAAQUIJ.js} +4 -4
  177. package/dist/cli/chunks/{daemon-I5ESGZGX.js → daemon-N6AICOXE.js} +3 -3
  178. package/dist/cli/chunks/{dag-attention-scheduler-JPTHWB2Q.js → dag-attention-scheduler-7TFE4MSB.js} +2 -2
  179. package/dist/cli/chunks/{detect-RTUZDBEZ.js → detect-VFGXI7AL.js} +2 -2
  180. package/dist/cli/chunks/{dist-node-5HLWHNYA.js → dist-node-P2JPEBHL.js} +2 -2
  181. package/dist/cli/chunks/{domain-handler-R7IPUX54.js → domain-handler-CIMGA5Z3.js} +2 -2
  182. package/dist/cli/chunks/{domain-transfer-E3I2LMCB.js → domain-transfer-UHNJ2JW4.js} +2 -2
  183. package/dist/cli/chunks/dream-EYG2RXNJ.js +2 -0
  184. package/dist/cli/chunks/{embed-and-insert-pattern-BXUWG73R.js → embed-and-insert-pattern-UWK2RRN4.js} +2 -2
  185. package/dist/cli/chunks/{eval-3ZFM75YA.js → eval-NXHZ7BQE.js} +2 -2
  186. package/dist/cli/chunks/{experience-capture-middleware-NJ3BT657.js → experience-capture-middleware-RVQ7F34S.js} +3 -3
  187. package/dist/cli/chunks/{fast-paths-Q3V5C5IM.js → fast-paths-DRXANKX2.js} +2 -2
  188. package/dist/cli/chunks/{feature-flags-D3JGPHXY.js → feature-flags-NW6VEQMN.js} +2 -2
  189. package/dist/cli/chunks/{feature-flags-XZGJNPZ7.js → feature-flags-V45DD537.js} +2 -2
  190. package/dist/cli/chunks/{file-discovery-MZOYXIOS.js → file-discovery-GJO7L2NH.js} +2 -2
  191. package/dist/cli/chunks/{fleet-FG3EBA75.js → fleet-O35WUOSC.js} +3 -3
  192. package/dist/cli/chunks/{gnn-wrapper-PKZLZHL2.js → gnn-wrapper-AUVW767T.js} +2 -2
  193. package/dist/cli/chunks/{heartbeat-handler-YZTRVH75.js → heartbeat-handler-5YXDBHH4.js} +4 -4
  194. package/dist/cli/chunks/heartbeat-scheduler-43Q5PRW7.js +2 -0
  195. package/dist/cli/chunks/hnsw-adapter-XN2M6KGB.js +2 -0
  196. package/dist/cli/chunks/hnsw-index-4TEELZ7L.js +2 -0
  197. package/dist/cli/chunks/{hnsw-legacy-bridge-WONHB63F.js → hnsw-legacy-bridge-BYJY6BS3.js} +2 -2
  198. package/dist/cli/chunks/{hnswlib-node-Q4VPSJJM.js → hnswlib-node-DOAKQHTK.js} +2 -2
  199. package/dist/cli/chunks/{hooks-RWX5ZZCE.js → hooks-AXI33SEK.js} +10 -10
  200. package/dist/cli/chunks/hybrid-router-L4IMWRLC.js +2 -0
  201. package/dist/cli/chunks/{hypergraph-engine-G6N24L5G.js → hypergraph-engine-SMYLLI4Z.js} +2 -2
  202. package/dist/cli/chunks/{hypergraph-handler-4RGOLL6F.js → hypergraph-handler-GYPRTMRE.js} +3 -3
  203. package/dist/cli/chunks/impact-analyzer-GNCMGV2E.js +2 -0
  204. package/dist/cli/chunks/{init-handler-L7DZAHXO.js → init-handler-DO5NFTZT.js} +6 -6
  205. package/dist/cli/chunks/init-wizard-6XY76PR6.js +2 -0
  206. package/dist/cli/chunks/kernel-KSJDDMZX.js +2 -0
  207. package/dist/cli/chunks/{kilocode-installer-G7PUCUDZ.js → kilocode-installer-CVWXBLG6.js} +2 -2
  208. package/dist/cli/chunks/{kiro-installer-H6234HEB.js → kiro-installer-DK7J7XL7.js} +2 -2
  209. package/dist/cli/chunks/knowledge-graph-MDPRHCAD.js +2 -0
  210. package/dist/cli/chunks/{learning-346CA4DH.js → learning-QHDQFBN4.js} +3 -3
  211. package/dist/cli/chunks/{llm-router-ATNRDTEM.js → llm-router-AMNXDGQ2.js} +4 -4
  212. package/dist/cli/chunks/llm-router-service-Y5Q7C6J5.js +2 -0
  213. package/dist/cli/chunks/{load-3L2CK4ML.js → load-2NZHFE5D.js} +2 -2
  214. package/dist/cli/chunks/load-test-NZZNYHOR.js +2 -0
  215. package/dist/cli/chunks/{mcp-JJ4ZDUJB.js → mcp-MX4GB3MU.js} +2 -2
  216. package/dist/cli/chunks/{memory-U3K2Y777.js → memory-NZACDD2C.js} +7 -7
  217. package/dist/cli/chunks/memory-backend-H3JXCBSZ.js +2 -0
  218. package/dist/cli/chunks/memory-handlers-KV7IJ2XA.js +2 -0
  219. package/dist/cli/chunks/{multi-model-executor-DPCU4CSM.js → multi-model-executor-ABZUIP3S.js} +2 -2
  220. package/dist/cli/chunks/{opencode-installer-KNUCUSRG.js → opencode-installer-V3IFSJQT.js} +2 -2
  221. package/dist/cli/chunks/{orchestrator-DJV2NUWD.js → orchestrator-GCK47DTJ.js} +5 -5
  222. package/dist/cli/chunks/pattern-null-store-DXW5PB5E.js +2 -0
  223. package/dist/cli/chunks/{pattern-usage-recorder-TQ7KECBB.js → pattern-usage-recorder-TAD2TRNY.js} +2 -2
  224. package/dist/cli/chunks/{pipeline-JG57VFOB.js → pipeline-ZIXBDYN5.js} +2 -2
  225. package/dist/cli/chunks/{platform-L7LOBG4E.js → platform-4B7OOTAM.js} +2 -2
  226. package/dist/cli/chunks/{plugin-ATBPEU2K.js → plugin-QQ3SOXY2.js} +2 -2
  227. package/dist/cli/chunks/{prime-radiant-advanced-wasm-XCX7CNVW.js → prime-radiant-advanced-wasm-4BYJTTZX.js} +2 -2
  228. package/dist/cli/chunks/protocol-executor-RRLH6VOX.js +2 -0
  229. package/dist/cli/chunks/{protocol-handler-DOFLSB4N.js → protocol-handler-VNRDG3KY.js} +2 -2
  230. package/dist/cli/chunks/{prove-CDBMRPBD.js → prove-WVPJXN6K.js} +2 -2
  231. package/dist/cli/chunks/provider-manager-S7QOPTRO.js +2 -0
  232. package/dist/cli/chunks/qe-reasoning-bank-SPKHDTEL.js +2 -0
  233. package/dist/cli/chunks/{quality-5CMQBYP3.js → quality-E3VPSE2L.js} +2 -2
  234. package/dist/cli/chunks/{quality-gate-LU66IWRT.js → quality-gate-2ZPH7H7Z.js} +3 -3
  235. package/dist/cli/chunks/queen-coordinator-T7LEO2QL.js +2 -0
  236. package/dist/cli/chunks/{real-embeddings-3B7AXYOP.js → real-embeddings-CYHZLS5U.js} +2 -2
  237. package/dist/cli/chunks/{roocode-installer-GF4YJW7E.js → roocode-installer-A2PJDZ6G.js} +2 -2
  238. package/dist/cli/chunks/router-LMBUXWVM.js +2 -0
  239. package/dist/cli/chunks/routing-feedback-A5JZ2HTV.js +2 -0
  240. package/dist/cli/chunks/{routing-handler-PWQMWFND.js → routing-handler-WASZ7YUM.js} +2 -2
  241. package/dist/cli/chunks/{ruvector-commands-SMD6KSBD.js → ruvector-commands-USEIUYOT.js} +2 -2
  242. package/dist/cli/chunks/{rvf-dual-writer-M5TEJ56X.js → rvf-dual-writer-GC2SZLOS.js} +2 -2
  243. package/dist/cli/chunks/{rvf-migration-adapter-EHLWMZYI.js → rvf-migration-adapter-RMXAP7UZ.js} +2 -2
  244. package/dist/cli/chunks/{rvf-migration-coordinator-GMVLX3FX.js → rvf-migration-coordinator-22D6BTI5.js} +2 -2
  245. package/dist/cli/chunks/rvf-native-adapter-IVKAJC5C.js +2 -0
  246. package/dist/cli/chunks/{rvf-store-integrity-PDADEHAZ.js → rvf-store-integrity-B5676PI2.js} +2 -2
  247. package/dist/cli/chunks/safe-db-MREVE34L.js +2 -0
  248. package/dist/cli/chunks/schedule-QUQSORLA.js +2 -0
  249. package/dist/cli/chunks/scheduler-POQUTUKP.js +2 -0
  250. package/dist/cli/chunks/{security-PSMBTUSM.js → security-GYR2YU72.js} +3 -3
  251. package/dist/cli/chunks/{shared-rvf-adapter-DP2Z4YLV.js → shared-rvf-adapter-RTWRMMCR.js} +2 -2
  252. package/dist/cli/chunks/{shared-rvf-dual-writer-UOU6ORBJ.js → shared-rvf-dual-writer-4YKFV67E.js} +2 -2
  253. package/dist/cli/chunks/sqlite-persistence-K4TX4WXV.js +2 -0
  254. package/dist/cli/chunks/{status-handler-T565F47D.js → status-handler-CBPWW3QD.js} +2 -2
  255. package/dist/cli/chunks/{structural-health-54WNSZ7Y.js → structural-health-CATUHO2L.js} +2 -2
  256. package/dist/cli/chunks/{sync-5ZGYF7JF.js → sync-ADHPFKN6.js} +2 -2
  257. package/dist/cli/chunks/{sync-EXADT5IZ.js → sync-YFHOSBNL.js} +2 -2
  258. package/dist/cli/chunks/{task-handler-JXWQZDEX.js → task-handler-R2KZIXXF.js} +2 -2
  259. package/dist/cli/chunks/{task-handlers-UKHRILMM.js → task-handlers-HLXWXRC4.js} +3 -3
  260. package/dist/cli/chunks/{test-3SU56PMM.js → test-A5SJ4CSH.js} +4 -4
  261. package/dist/cli/chunks/{test-scheduling-CZZ4KKWM.js → test-scheduling-NWAUSA6A.js} +3 -3
  262. package/dist/cli/chunks/{token-bootstrap-RSIAPUIV.js → token-bootstrap-KOZLR5KD.js} +2 -2
  263. package/dist/cli/chunks/{token-usage-7HW43ORO.js → token-usage-7EDWF7XZ.js} +2 -2
  264. package/dist/cli/chunks/{transformers-A5REG7OI.js → transformers-OJGVAPSE.js} +2 -2
  265. package/dist/cli/chunks/{tree-sitter-wasm-parser-F43MC7E5.js → tree-sitter-wasm-parser-A2BLMPCC.js} +2 -2
  266. package/dist/cli/chunks/{types-DEOHTTJ3.js → types-AU2VADM6.js} +2 -2
  267. package/dist/cli/chunks/unified-memory-EWCB3EHN.js +2 -0
  268. package/dist/cli/chunks/unified-memory-hnsw-PH2ECVGQ.js +2 -0
  269. package/dist/cli/chunks/unified-persistence-2AM7JHBZ.js +2 -0
  270. package/dist/cli/chunks/{upgrade-7NKNCL2I.js → upgrade-JLXJ6UTR.js} +2 -2
  271. package/dist/cli/chunks/{validate-SN2UY7CT.js → validate-AMJG6AVL.js} +2 -2
  272. package/dist/cli/chunks/{validate-swarm-YITFMCXY.js → validate-swarm-6J4VKCBH.js} +2 -2
  273. package/dist/cli/chunks/{vibium-AZNIG6O7.js → vibium-YATMPDAF.js} +2 -2
  274. package/dist/cli/chunks/visual-security-B4KSJUTG.js +2 -0
  275. package/dist/cli/chunks/{web-tree-sitter-DY4YXPMR.js → web-tree-sitter-UCDN3H4X.js} +2 -2
  276. package/dist/cli/chunks/{windsurf-installer-HXD4BK7N.js → windsurf-installer-WHKYYVAM.js} +2 -2
  277. package/dist/cli/chunks/{witness-chain-UV7BOO6T.js → witness-chain-NDBGA7TH.js} +2 -2
  278. package/dist/cli/chunks/witness-chain-QHAHCB7E.js +2 -0
  279. package/dist/cli/chunks/{witness-key-manager-BCNW3SZH.js → witness-key-manager-2PQHTQVG.js} +2 -2
  280. package/dist/cli/chunks/{workflow-R3SSSWA5.js → workflow-F5HE4FGG.js} +4 -4
  281. package/dist/cli/chunks/workflow-orchestrator-LYU63YL7.js +2 -0
  282. package/dist/cli/chunks/{wrappers-6JUXYAML.js → wrappers-UHG2KXGO.js} +2 -2
  283. package/dist/cli/commands/memory.js +3 -0
  284. package/dist/kernel/hybrid-backend.d.ts +2 -1
  285. package/dist/kernel/hybrid-backend.js +4 -0
  286. package/dist/kernel/interfaces.d.ts +10 -0
  287. package/dist/kernel/memory-backend.d.ts +2 -1
  288. package/dist/kernel/memory-backend.js +8 -0
  289. package/dist/kernel/native-hnsw-backend.js +8 -6
  290. package/dist/kernel/unified-memory.d.ts +2 -0
  291. package/dist/kernel/unified-memory.js +43 -8
  292. package/dist/mcp/bundle.js +213 -213
  293. package/dist/mcp/handlers/memory-handlers.d.ts +2 -0
  294. package/dist/mcp/handlers/memory-handlers.js +13 -2
  295. package/dist/mcp/types.d.ts +10 -0
  296. package/package.json +4 -2
  297. package/dist/cli/chunks/adapter-7XXMDGFO.js +0 -2
  298. package/dist/cli/chunks/aqe-learning-engine-2KGMCBJG.js +0 -2
  299. package/dist/cli/chunks/base-4M3VL4XK.js +0 -2
  300. package/dist/cli/chunks/browser-workflow-DHIPXEGO.js +0 -2
  301. package/dist/cli/chunks/chunk-CVXEOTIK.js +0 -2
  302. package/dist/cli/chunks/chunk-GA7PUAMT.js +0 -2
  303. package/dist/cli/chunks/client-IEN43WBH.js +0 -2
  304. package/dist/cli/chunks/core-handlers-PBITKHVP.js +0 -2
  305. package/dist/cli/chunks/cross-domain-router-JGCWQ7BO.js +0 -2
  306. package/dist/cli/chunks/dream-52MPUF5Q.js +0 -2
  307. package/dist/cli/chunks/heartbeat-scheduler-LMAEJQYQ.js +0 -2
  308. package/dist/cli/chunks/hnsw-adapter-DGGDYJEL.js +0 -2
  309. package/dist/cli/chunks/hnsw-index-KA7WDTHX.js +0 -2
  310. package/dist/cli/chunks/hybrid-router-Q6JQTV55.js +0 -2
  311. package/dist/cli/chunks/impact-analyzer-7LFSGIQP.js +0 -2
  312. package/dist/cli/chunks/init-wizard-T4K44J6D.js +0 -2
  313. package/dist/cli/chunks/kernel-TGHK6X7F.js +0 -2
  314. package/dist/cli/chunks/knowledge-graph-MV3OSGCB.js +0 -2
  315. package/dist/cli/chunks/llm-router-service-OOCNAPJO.js +0 -2
  316. package/dist/cli/chunks/load-test-4OZPYWL4.js +0 -2
  317. package/dist/cli/chunks/memory-backend-LMRIHJQY.js +0 -2
  318. package/dist/cli/chunks/memory-handlers-J6CVQ5DS.js +0 -2
  319. package/dist/cli/chunks/pattern-null-store-AQWPHLRW.js +0 -2
  320. package/dist/cli/chunks/protocol-executor-FWUT6L6K.js +0 -2
  321. package/dist/cli/chunks/provider-manager-4PY7IR3V.js +0 -2
  322. package/dist/cli/chunks/qe-reasoning-bank-M4XVWRPY.js +0 -2
  323. package/dist/cli/chunks/queen-coordinator-KSRI42QZ.js +0 -2
  324. package/dist/cli/chunks/router-F2TCXNSG.js +0 -2
  325. package/dist/cli/chunks/routing-feedback-VHOWXUY7.js +0 -2
  326. package/dist/cli/chunks/rvf-native-adapter-XG3LFOYW.js +0 -2
  327. package/dist/cli/chunks/safe-db-CTHJ3SXC.js +0 -2
  328. package/dist/cli/chunks/schedule-LLYADLGL.js +0 -2
  329. package/dist/cli/chunks/scheduler-72YIGDIX.js +0 -2
  330. package/dist/cli/chunks/sqlite-persistence-N7OO3ZOE.js +0 -2
  331. package/dist/cli/chunks/unified-memory-Q55MJWAM.js +0 -2
  332. package/dist/cli/chunks/unified-memory-hnsw-4BEKV2K5.js +0 -2
  333. package/dist/cli/chunks/unified-persistence-IIB5MR67.js +0 -2
  334. package/dist/cli/chunks/visual-security-F4FUP6KV.js +0 -2
  335. package/dist/cli/chunks/witness-chain-SQ5LCKUQ.js +0 -2
  336. package/dist/cli/chunks/workflow-orchestrator-Z4PZXWVY.js +0 -2
@@ -1,11 +1,11 @@
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.6");process.exit(0)}
2
- import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chunk-E7MD5LHC.js";import{a as Ge}from"./chunk-GA7PUAMT.js";import{c as te}from"./chunk-F66FYZQF.js";import{a as W,b as D,c as ze}from"./chunk-SZO6JIFM.js";import{b as C,d as re}from"./chunk-2VUXU22M.js";import{a as X,c as Fe}from"./chunk-6UPQD42K.js";import{a as ne,b as Pe}from"./chunk-5CMZDVUR.js";import{a as se,d as w,e as oe,f as ie}from"./chunk-PW3JLQGH.js";import{a as b,e as Me}from"./chunk-Q4RU4XG6.js";import{c as h,e as xe}from"./chunk-ISOTSVI7.js";import{createHash as Te}from"node:crypto";function Be(o){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(o)),e}function We(o){return typeof o=="string"?Buffer.from(o,"utf8"):o instanceof Uint8Array?Buffer.from(o):Buffer.from(H(o),"utf8")}function H(o){return o===null||typeof o!="object"?JSON.stringify(o)??"null":Array.isArray(o)?`[${o.map(H).join(",")}]`:`{${Object.keys(o).sort().map(t=>`${JSON.stringify(t)}:${H(o[t])}`).join(",")}}`}function de(...o){let e=Te("sha256");for(let t of o)e.update(t);return e.digest()}function ce(o,e,t){return de(je,o,e,Be(t))}var je,ae,O,Ee=h(()=>{"use strict";je=Buffer.from("ruvector:chain:"),ae=Te("sha256").update("ruvector-proof-gate-v1").digest();O=class o{seq=0;prev=ae;chain=[];payloadHashes=[];admit(e){let t=de(We(e)),n=ce(this.prev,t,this.seq);this.prev=n,this.chain.push(n),this.payloadHashes.push(t);let a={sequence:this.seq,payloadHash:t.toString("hex"),chainCommitment:n.toString("hex")};return this.seq+=1,a}verifyReceipt(e){return e.sequence>=0&&e.sequence<this.chain.length&&this.chain[e.sequence].toString("hex")===e.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let e=ae;for(let t=0;t<this.chain.length;t++){if(!ce(e,this.payloadHashes[t],t).equals(this.chain[t]))return!1;e=this.chain[t]}return e.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(e=>e.toString("hex")),payloadHashes:this.payloadHashes.map(e=>e.toString("hex"))}}static fromJSON(e){let t=new o;t.seq=e.seq,t.prev=Buffer.from(e.head,"hex");for(let n of e.chain)t.chain.push(Buffer.from(n,"hex"));for(let n of e.payloadHashes)t.payloadHashes.push(Buffer.from(n,"hex"));return t}}});function A(o){if(!Y.has(o))throw new Error(`Invalid table name: "${o}" is not in the allowlist`);return o}function nt(o){let e=o.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${o}" has too many parts (max: schema.table)`);for(let t of e)if(!ue.test(t))throw new Error(`Invalid SQL identifier: "${o}" \u2014 part "${t}" does not match pattern ${ue}`);return o}var Y,ue,$=h(()=>{"use strict";Y=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);ue=/^[a-z_][a-z0-9_]{0,62}$/});var U,pe,le,ge,me,K,_e,fe,Ne,Se,he,Re,Le=h(()=>{"use strict";ke();qe();U=11,pe=`
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.8");process.exit(0)}
2
+ import{d as j,f as qe}from"./chunk-SSIOQDWN.js";import{a as B,c as ze}from"./chunk-C37IK75J.js";import{a as Pe}from"./chunk-K6XYLMXO.js";import{c as ne}from"./chunk-PVUQMV6P.js";import{a as W,b as y,c as je}from"./chunk-ZO6QWQ2G.js";import{b as C,d as se}from"./chunk-HD22NMGP.js";import{a as X,c as Me}from"./chunk-XKKCH24C.js";import{a as re,b as ke}from"./chunk-QYZLZ6P3.js";import{a as oe,d as w,e as ie,f as ae}from"./chunk-CDBTYQ4N.js";import{a as b,b as te,e as Ge}from"./chunk-NJ7SVXE6.js";import{c as R,e as Fe}from"./chunk-NW5XQQMC.js";import{createHash as de}from"node:crypto";function We(o){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(o)),e}function He(o){return typeof o=="string"?Buffer.from(o,"utf8"):o instanceof Uint8Array?Buffer.from(o):Buffer.from(H(o),"utf8")}function H(o){return o===null||typeof o!="object"?JSON.stringify(o)??"null":Array.isArray(o)?`[${o.map(H).join(",")}]`:`{${Object.keys(o).sort().map(t=>`${JSON.stringify(t)}:${H(o[t])}`).join(",")}}`}function Ee(...o){let e=de("sha256");for(let t of o)e.update(t);return e.digest()}function Te(o,e,t){return Ee(Be,o,e,We(t))}var Be,ce,A,ue=R(()=>{"use strict";Be=Buffer.from("ruvector:chain:"),ce=de("sha256").update("ruvector-proof-gate-v1").digest();A=class o{seq=0;prev=ce;chain=[];payloadHashes=[];admit(e){let t=Ee(He(e)),n=Te(this.prev,t,this.seq);this.prev=n,this.chain.push(n),this.payloadHashes.push(t);let a={sequence:this.seq,payloadHash:t.toString("hex"),chainCommitment:n.toString("hex")};return this.seq+=1,a}verifyReceipt(e){return e.sequence>=0&&e.sequence<this.chain.length&&this.chain[e.sequence].toString("hex")===e.chainCommitment}chainRoot(){return this.prev.toString("hex")}get length(){return this.seq}get isEmpty(){return this.seq===0}verifyIntegrity(){if(this.chain.length!==this.payloadHashes.length)return!1;let e=ce;for(let t=0;t<this.chain.length;t++){if(!Te(e,this.payloadHashes[t],t).equals(this.chain[t]))return!1;e=this.chain[t]}return e.equals(this.prev)}toJSON(){return{seq:this.seq,head:this.prev.toString("hex"),chain:this.chain.map(e=>e.toString("hex")),payloadHashes:this.payloadHashes.map(e=>e.toString("hex"))}}static fromJSON(e){let t=new o;t.seq=e.seq,t.prev=Buffer.from(e.head,"hex");for(let n of e.chain)t.chain.push(Buffer.from(n,"hex"));for(let n of e.payloadHashes)t.payloadHashes.push(Buffer.from(n,"hex"));return t}}});function O(o){if(!Y.has(o))throw new Error(`Invalid table name: "${o}" is not in the allowlist`);return o}function rt(o){let e=o.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${o}" has too many parts (max: schema.table)`);for(let t of e)if(!pe.test(t))throw new Error(`Invalid SQL identifier: "${o}" \u2014 part "${t}" does not match pattern ${pe}`);return o}var Y,pe,$=R(()=>{"use strict";Y=new Set(["schema_version","kv_store","vectors","rl_q_values","goap_goals","goap_actions","goap_plans","goap_plan_signatures","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","sona_patterns","sona_fisher_matrices","test_outcomes","routing_outcomes","coverage_sessions","patterns","hypergraph_nodes","hypergraph_edges","hypergraph_vertices","hypergraph_hyperedges","hypergraph_edge_vertices","hypergraph_vertex_properties","hypergraph_edge_properties","captured_experiences","experience_applications","witness_chain","witness_chain_receipts","witness_chain_archive","trajectories","trajectory_steps","pattern_evolution_events","pattern_relationships","pattern_versions","learning_daily_snapshots","metrics_outcomes","experience_consolidation_log","qe_pattern_reuse","qe_agent_co_execution"]);pe=/^[a-z_][a-z0-9_]{0,62}$/});var U,le,ge,me,_e,K,fe,Ne,Se,he,Re,Le,Ce=R(()=>{"use strict";qe();ze();U=11,le=`
3
3
  CREATE TABLE IF NOT EXISTS schema_version (
4
4
  id INTEGER PRIMARY KEY CHECK (id = 1),
5
5
  version INTEGER NOT NULL,
6
6
  migrated_at TEXT DEFAULT (datetime('now'))
7
7
  );
8
- `,le=`
8
+ `,ge=`
9
9
  -- Key-Value Store (v2 compatible - same schema as HybridBackend)
10
10
  CREATE TABLE IF NOT EXISTS kv_store (
11
11
  key TEXT NOT NULL,
@@ -17,7 +17,7 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
17
17
  );
18
18
  CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
19
19
  CREATE INDEX IF NOT EXISTS idx_kv_expires ON kv_store(expires_at) WHERE expires_at IS NOT NULL;
20
- `,ge=`
20
+ `,me=`
21
21
  -- Vector Embeddings (new in v3 - replaces in-memory AgentDB)
22
22
  CREATE TABLE IF NOT EXISTS vectors (
23
23
  id TEXT PRIMARY KEY,
@@ -30,7 +30,7 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
30
30
  );
31
31
  CREATE INDEX IF NOT EXISTS idx_vectors_namespace ON vectors(namespace);
32
32
  CREATE INDEX IF NOT EXISTS idx_vectors_dimensions ON vectors(dimensions);
33
- `,me=`
33
+ `,_e=`
34
34
  -- Q-Values for RL algorithms (ADR-046)
35
35
  CREATE TABLE IF NOT EXISTS rl_q_values (
36
36
  id TEXT PRIMARY KEY,
@@ -162,7 +162,7 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
162
162
  -- would fail on "no such column" since CREATE TABLE IF NOT EXISTS above
163
163
  -- silently no-ops against them. unified-memory.ts's v11 migration creates
164
164
  -- this index only after confirming/backfilling the column.
165
- `,_e=`
165
+ `,fe=`
166
166
  -- Concept Graph Nodes (Dream Engine)
167
167
  CREATE TABLE IF NOT EXISTS concept_nodes (
168
168
  id TEXT PRIMARY KEY,
@@ -231,7 +231,7 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
231
231
  CREATE INDEX IF NOT EXISTS idx_edge_weight ON concept_edges(weight DESC);
232
232
  CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id);
233
233
  CREATE INDEX IF NOT EXISTS idx_dream_status ON dream_cycles(status);
234
- `,fe=`
234
+ `,Ne=`
235
235
  -- QE Patterns table (unified from sqlite-persistence.ts)
236
236
  CREATE TABLE IF NOT EXISTS qe_patterns (
237
237
  id TEXT PRIMARY KEY,
@@ -381,7 +381,7 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
381
381
  CREATE INDEX IF NOT EXISTS idx_execution_results_status ON execution_results(status);
382
382
  CREATE INDEX IF NOT EXISTS idx_executed_steps_execution ON executed_steps(execution_id);
383
383
  CREATE INDEX IF NOT EXISTS idx_executed_steps_action ON executed_steps(action_id);
384
- `,Ne=`
384
+ `,Se=`
385
385
  -- MinCut Graph Snapshots (ADR-047)
386
386
  CREATE TABLE IF NOT EXISTS mincut_snapshots (
387
387
  id TEXT PRIMARY KEY,
@@ -487,7 +487,7 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
487
487
  CREATE INDEX IF NOT EXISTS idx_mincut_healing_type ON mincut_healing_actions(action_type);
488
488
  CREATE INDEX IF NOT EXISTS idx_mincut_healing_success ON mincut_healing_actions(success);
489
489
  CREATE INDEX IF NOT EXISTS idx_mincut_observations_iter ON mincut_observations(iteration);
490
- `,Se=`
490
+ `,he=`
491
491
  -- SONA Patterns table (ADR-046: Pattern Persistence for Neural Backbone)
492
492
  CREATE TABLE IF NOT EXISTS sona_patterns (
493
493
  id TEXT PRIMARY KEY,
@@ -513,7 +513,7 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
513
513
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_domain ON sona_patterns(domain);
514
514
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_confidence ON sona_patterns(confidence DESC);
515
515
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_updated ON sona_patterns(updated_at DESC);
516
- `,he=`
516
+ `,Re=`
517
517
  -- Test outcomes (ADR-023: Quality Feedback Loop)
518
518
  CREATE TABLE IF NOT EXISTS test_outcomes (
519
519
  id TEXT PRIMARY KEY,
@@ -596,16 +596,16 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
596
596
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_technique ON coverage_sessions(technique);
597
597
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_agent ON coverage_sessions(agent_id);
598
598
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_created ON coverage_sessions(created_at);
599
- `,Re=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","goap_execution_steps","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function x(o,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?o:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function a(i,c,E,d){return i!==E?i-E:c.localeCompare(d)}return{get(){return n.value},set(i,c){let E=c??Date.now();(n.timestamp===0||a(E,o,n.timestamp,n.nodeId)>0)&&(n={value:i,timestamp:E,nodeId:o,version:n.version+1,lastUpdated:Date.now()})},merge(i){let c=i.getState();this.applyState(c)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(i){(n.timestamp===0||a(i.timestamp,i.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:i.value,timestamp:i.timestamp,nodeId:i.nodeId,version:Math.max(n.version,i.version)+1,lastUpdated:Date.now()})},getNodeId(){return o},getTimestamp(){return n.timestamp}}}function F(o,e){let t=x(o);return t.applyState(e),t}var V=h(()=>{"use strict"});function I(o){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[o]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[o]=(e.counts[o]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[a,i]of Object.entries(t.counts)){let c=e.counts[a]||0;i>c&&(e.counts[a]=i,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return o},getLocalCount(){return e.counts[o]||0}}}function M(o,e){let t=I(o);return t.applyState(e),t}var G=h(()=>{"use strict"});function P(o){let e=I(o),t=I(o),n=0,a=Date.now();return{get(){return e.get()-t.get()},increment(i=1){if(i<0)throw new Error("Use decrement() for negative values");i!==0&&(e.increment(i),n++,a=Date.now())},decrement(i=1){if(i<0)throw new Error("Use increment() for negative values");i!==0&&(t.increment(i),n++,a=Date.now())},merge(i){let c=i.getState();this.applyState(c)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:a}},applyState(i){let c=this.get();e.applyState(i.positive),t.applyState(i.negative);let E=this.get();c!==E&&(n=Math.max(n,i.version)+1,a=Date.now())},getNodeId(){return o}}}function k(o,e){let t=P(o);return t.applyState(e),t}var Q=h(()=>{"use strict";G()});function He(o,e){return`${o}:${Date.now()}:${e}`}function J(o){return typeof o=="string"?`s:${o}`:typeof o=="number"?`n:${o}`:typeof o=="boolean"?`b:${o}`:`j:${JSON.stringify(o)}`}function Ye(o){let e=o.substring(0,2),t=o.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return C(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function q(o){let e=new Map,t=new Map,n=0,a=Date.now(),i=0;function c(d){let u=e.get(d);if(!u||u.size===0)return!1;let p=t.get(d);if(!p||p.size===0)return!0;for(let _ of u)if(!p.has(_))return!0;return!1}function E(d){let u=e.get(d);if(!u)return new Set;let p=t.get(d)||new Set,_=new Set;for(let g of u)p.has(g)||_.add(g);return _}return{has(d){let u=J(d);return c(u)},values(){let d=[];for(let[u]of e)c(u)&&d.push(Ye(u));return d},size(){let d=0;for(let[u]of e)c(u)&&d++;return d},add(d){let u=J(d),p=He(o,i++);e.has(u)||e.set(u,new Set),e.get(u).add(p),n++,a=Date.now()},remove(d){let u=J(d),p=e.get(u);if(!p||p.size===0)return;t.has(u)||t.set(u,new Set);let _=t.get(u);for(let g of p)_.add(g);n++,a=Date.now()},merge(d){let u=d.getState();this.applyState(u)},getState(){let d={};for(let[p,_]of e)d[p]=Array.from(_);let u={};for(let[p,_]of t)_.size>0&&(u[p]=Array.from(_));return{elements:d,tombstones:u,version:n,lastUpdated:a}},applyState(d){let u=!1;for(let[p,_]of Object.entries(d.elements)){e.has(p)||e.set(p,new Set);let g=e.get(p);for(let l of _)g.has(l)||(g.add(l),u=!0)}for(let[p,_]of Object.entries(d.tombstones)){t.has(p)||t.set(p,new Set);let g=t.get(p);for(let l of _)g.has(l)||(g.add(l),u=!0)}u&&(n=Math.max(n,d.version)+1,a=Date.now())},getNodeId(){return o},clear(){for(let[d,u]of e){t.has(d)||t.set(d,new Set);let p=t.get(d);for(let _ of u)p.add(_)}n++,a=Date.now()}}}function z(o,e){let t=q(o);return t.applyState(e),t}var Z=h(()=>{"use strict";re()});function ee(o){let e={...$e,...o},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:a}=e,i=new Map,c=new Map,E=new Map,d=new Map,u=0,p=[],_=new Set,g={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function l(s,r,T){let N={key:s,type:r,operation:T,timestamp:Date.now(),nodeId:t};for(let we of _)try{we(N)}catch(Ue){console.error("[CRDTStore] Error in change listener:",Ue)}}function m(s,r){u++,n&&g[s].add(r)}function L(){if(!n||!(g.registers.size>0||g.gCounters.size>0||g.pnCounters.size>0||g.sets.size>0))return;let r={fromVersion:p.length>0?p[p.length-1].toVersion:0,toVersion:u,timestamp:Date.now(),nodeId:t};if(g.registers.size>0){r.registers={};for(let T of g.registers){let N=i.get(T);N&&(r.registers[T]=N.getState())}g.registers.clear()}if(g.gCounters.size>0){r.gCounters={};for(let T of g.gCounters){let N=c.get(T);N&&(r.gCounters[T]=N.getState())}g.gCounters.clear()}if(g.pnCounters.size>0){r.pnCounters={};for(let T of g.pnCounters){let N=E.get(T);N&&(r.pnCounters[T]=N.getState())}g.pnCounters.clear()}if(g.sets.size>0){r.sets={};for(let T of g.sets){let N=d.get(T);N&&(r.sets[T]=N.getState())}g.sets.clear()}for(p.push(r);p.length>a;)p.shift()}let R={getRegister(s){return i.has(s)||i.set(s,x(t)),i.get(s)},setRegister(s,r){R.getRegister(s).set(r),m("registers",s),l(s,"lww-register","set")},hasRegister(s){return i.has(s)},deleteRegister(s){let r=i.delete(s);return r&&m("registers",s),r},getGCounter(s){return c.has(s)||c.set(s,I(t)),c.get(s)},incrementGCounter(s,r){R.getGCounter(s).increment(r),m("gCounters",s),l(s,"g-counter","increment")},hasGCounter(s){return c.has(s)},deleteGCounter(s){let r=c.delete(s);return r&&m("gCounters",s),r},getCounter(s){return E.has(s)||E.set(s,P(t)),E.get(s)},incrementCounter(s,r){R.getCounter(s).increment(r),m("pnCounters",s),l(s,"pn-counter","increment")},decrementCounter(s,r){R.getCounter(s).decrement(r),m("pnCounters",s),l(s,"pn-counter","decrement")},hasCounter(s){return E.has(s)},deleteCounter(s){let r=E.delete(s);return r&&m("pnCounters",s),r},getSet(s){return d.has(s)||d.set(s,q(t)),d.get(s)},addToSet(s,r){R.getSet(s).add(r),m("sets",s),l(s,"or-set","add")},removeFromSet(s,r){R.getSet(s).remove(r),m("sets",s),l(s,"or-set","remove")},hasSet(s){return d.has(s)},deleteSet(s){let r=d.delete(s);return r&&m("sets",s),r},merge(s){let r=s.getState();R.applyState(r)},getState(){L();let s={version:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,T]of i)s.registers[r]=T.getState();for(let[r,T]of c)s.gCounters[r]=T.getState();for(let[r,T]of E)s.pnCounters[r]=T.getState();for(let[r,T]of d)s.sets[r]=T.getState();return s},applyState(s){for(let[r,T]of Object.entries(s.registers))i.has(r)?i.get(r).applyState(T):i.set(r,F(t,T)),m("registers",r),l(r,"lww-register","merge");for(let[r,T]of Object.entries(s.gCounters))c.has(r)?c.get(r).applyState(T):c.set(r,M(t,T)),m("gCounters",r),l(r,"g-counter","merge");for(let[r,T]of Object.entries(s.pnCounters))E.has(r)?E.get(r).applyState(T):E.set(r,k(t,T)),m("pnCounters",r),l(r,"pn-counter","merge");for(let[r,T]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(T):d.set(r,z(t,T)),m("sets",r),l(r,"or-set","merge");u=Math.max(u,s.version)+1},getDelta(s){if(L(),p.length===0)return s>=u,null;let r=p.filter(N=>N.toVersion>s);if(r.length===0)return null;let T={fromVersion:s,toVersion:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let N of r)N.registers&&Object.assign(T.registers,N.registers),N.gCounters&&Object.assign(T.gCounters,N.gCounters),N.pnCounters&&Object.assign(T.pnCounters,N.pnCounters),N.sets&&Object.assign(T.sets,N.sets);return Object.keys(T.registers).length===0&&delete T.registers,Object.keys(T.gCounters).length===0&&delete T.gCounters,Object.keys(T.pnCounters).length===0&&delete T.pnCounters,Object.keys(T.sets).length===0&&delete T.sets,T},applyDelta(s){if(s.registers)for(let[r,T]of Object.entries(s.registers))i.has(r)?i.get(r).applyState(T):i.set(r,F(t,T)),m("registers",r),l(r,"lww-register","merge");if(s.gCounters)for(let[r,T]of Object.entries(s.gCounters))c.has(r)?c.get(r).applyState(T):c.set(r,M(t,T)),m("gCounters",r),l(r,"g-counter","merge");if(s.pnCounters)for(let[r,T]of Object.entries(s.pnCounters))E.has(r)?E.get(r).applyState(T):E.set(r,k(t,T)),m("pnCounters",r),l(r,"pn-counter","merge");if(s.sets)for(let[r,T]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(T):d.set(r,z(t,T)),m("sets",r),l(r,"or-set","merge");u=Math.max(u,s.toVersion)+1},getVersion(){return u},getNodeId(){return t},on(s,r){if(s==="change")return _.add(r),()=>{_.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){_.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(i.keys())),(!s||s==="g-counter")&&r.push(...Array.from(c.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(E.keys())),(!s||s==="or-set")&&r.push(...Array.from(d.keys())),r},clear(){i.clear(),c.clear(),E.clear(),d.clear(),p.length=0,g.registers.clear(),g.gCounters.clear(),g.pnCounters.clear(),g.sets.clear(),u=0},getStats(){return{total:i.size+c.size+E.size+d.size,registers:i.size,gCounters:c.size,pnCounters:E.size,sets:d.size,version:u,nodeId:t,deltaHistorySize:p.length}}};return R}var $e,Ce=h(()=>{"use strict";V();G();Q();Z();$e={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var Ie=h(()=>{"use strict"});var Oe=h(()=>{"use strict";V();G();Q();Z();Ce();Ie()});var Je={};xe(Je,{ALLOWED_TABLE_NAMES:()=>Y,BinaryHeap:()=>se,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>De,UnifiedHnswIndex:()=>w,UnifiedMemoryManager:()=>v,clearProjectRootCache:()=>W,createHnswIndex:()=>oe,findProjectRoot:()=>D,getDefaultDbPath:()=>be,getResolvedDefaultConfig:()=>ye,getUnifiedMemory:()=>Xe,initializeUnifiedMemory:()=>Ke,resetUnifiedMemory:()=>Ve,validateTableName:()=>A});import*as f from"fs";import*as ve from"os";import*as S from"path";function be(){let o=D();return S.join(o,".agentic-qe","memory.db")}function ye(){return{...De,dbPath:be()}}function Xe(o){return v.getInstance(o)}async function Ke(o){let e=Xe(o);return await e.initialize(),e}function Ve(){v.resetInstance()}function Qe(){if(Ae)return;Ae=!0;let o=()=>{try{let e=v.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",o),process.on("SIGINT",()=>{o(),process.exit(0)}),process.on("SIGTERM",()=>{o(),process.exit(0)})}var y,De,v,Ae,Ze=h(()=>{Pe();re();Fe();Me();Ge();Ee();$();$();ie();ie();Le();Oe();ze();y=te.create("unified-memory");De={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:b.MMAP_SIZE_BYTES,cacheSize:b.CACHE_SIZE_KB,busyTimeout:b.BUSY_TIMEOUT_MS,vectorDimensions:b.DEFAULT_VECTOR_DIMENSIONS};v=class o{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new w("qe-memory");crdtStore=null;proofGate=null;proofGateEnvChecked=!1;static PROOF_NS="__proofgate__";static PROOF_KEY="chain";constructor(e){let t=ye();if(this.config={...t,...e},process.env.AQE_MEMORY_BACKEND==="memory"){this.config.dbPath=":memory:";return}if(!S.isAbsolute(this.config.dbPath)){let n=D();this.config.dbPath=S.join(n,this.config.dbPath)}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}static async getInstanceAsync(e){return o.instance?.initialized?o.instance:(o.instancePromise||(o.instancePromise=(async()=>{let t=o.getInstance(e);return await t.initialize(),t})()),o.instancePromise)}static resetInstance(){o.instance&&(o.instance.close(),o.instance=null),o.instancePromise=null,W()}async initialize(e){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize(e?.signal)),this.initPromise}async _doInitialize(e){if(!this.initialized){e?.throwIfAborted();try{let t=this.config.dbPath===":memory:",n="",a=!1,i=0;if(!t){let c=process.env.AQE_PROJECT_ROOT;if(c){let E=S.resolve(this.config.dbPath),d=S.resolve(c);!E.startsWith(d)&&!E.startsWith(ve.tmpdir())&&E.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${c}". Redirecting to test-safe path.`),this.config.dbPath=S.join(c,".agentic-qe","memory.db"))}if(n=S.dirname(this.config.dbPath),f.existsSync(n)||f.mkdirSync(n,{recursive:!0}),a=f.existsSync(this.config.dbPath),a)i=f.statSync(this.config.dbPath).size;else if(f.existsSync(n)){let E=this.findRecentBackups(n);if(E.length>0){let d=E[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
599
+ `,Le=["kv_store","vectors","rl_q_values","goap_actions","goap_goals","goap_plans","goap_plan_signatures","goap_execution_steps","concept_nodes","concept_edges","dream_cycles","dream_insights","qe_patterns","qe_pattern_embeddings","qe_pattern_usage","qe_trajectories","embeddings","execution_results","executed_steps","mincut_snapshots","mincut_history","mincut_weak_vertices","mincut_alerts","mincut_healing_actions","mincut_observations","hypergraph_nodes","hypergraph_edges","sona_patterns","witness_chain"]});function x(o,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?o:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function a(i,T,E,d){return i!==E?i-E:T.localeCompare(d)}return{get(){return n.value},set(i,T){let E=T??Date.now();(n.timestamp===0||a(E,o,n.timestamp,n.nodeId)>0)&&(n={value:i,timestamp:E,nodeId:o,version:n.version+1,lastUpdated:Date.now()})},merge(i){let T=i.getState();this.applyState(T)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(i){(n.timestamp===0||a(i.timestamp,i.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:i.value,timestamp:i.timestamp,nodeId:i.nodeId,version:Math.max(n.version,i.version)+1,lastUpdated:Date.now()})},getNodeId(){return o},getTimestamp(){return n.timestamp}}}function F(o,e){let t=x(o);return t.applyState(e),t}var V=R(()=>{"use strict"});function I(o){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[o]=0,{get(){return Object.values(e.counts).reduce((t,n)=>t+n,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[o]=(e.counts[o]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let n=t.getState();this.applyState(n)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let n=!1;for(let[a,i]of Object.entries(t.counts)){let T=e.counts[a]||0;i>T&&(e.counts[a]=i,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return o},getLocalCount(){return e.counts[o]||0}}}function M(o,e){let t=I(o);return t.applyState(e),t}var G=R(()=>{"use strict"});function P(o){let e=I(o),t=I(o),n=0,a=Date.now();return{get(){return e.get()-t.get()},increment(i=1){if(i<0)throw new Error("Use decrement() for negative values");i!==0&&(e.increment(i),n++,a=Date.now())},decrement(i=1){if(i<0)throw new Error("Use increment() for negative values");i!==0&&(t.increment(i),n++,a=Date.now())},merge(i){let T=i.getState();this.applyState(T)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:a}},applyState(i){let T=this.get();e.applyState(i.positive),t.applyState(i.negative);let E=this.get();T!==E&&(n=Math.max(n,i.version)+1,a=Date.now())},getNodeId(){return o}}}function k(o,e){let t=P(o);return t.applyState(e),t}var Q=R(()=>{"use strict";G()});function Ye(o,e){return`${o}:${Date.now()}:${e}`}function J(o){return typeof o=="string"?`s:${o}`:typeof o=="number"?`n:${o}`:typeof o=="boolean"?`b:${o}`:`j:${JSON.stringify(o)}`}function $e(o){let e=o.substring(0,2),t=o.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return C(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function q(o){let e=new Map,t=new Map,n=0,a=Date.now(),i=0;function T(d){let u=e.get(d);if(!u||u.size===0)return!1;let p=t.get(d);if(!p||p.size===0)return!0;for(let _ of u)if(!p.has(_))return!0;return!1}function E(d){let u=e.get(d);if(!u)return new Set;let p=t.get(d)||new Set,_=new Set;for(let g of u)p.has(g)||_.add(g);return _}return{has(d){let u=J(d);return T(u)},values(){let d=[];for(let[u]of e)T(u)&&d.push($e(u));return d},size(){let d=0;for(let[u]of e)T(u)&&d++;return d},add(d){let u=J(d),p=Ye(o,i++);e.has(u)||e.set(u,new Set),e.get(u).add(p),n++,a=Date.now()},remove(d){let u=J(d),p=e.get(u);if(!p||p.size===0)return;t.has(u)||t.set(u,new Set);let _=t.get(u);for(let g of p)_.add(g);n++,a=Date.now()},merge(d){let u=d.getState();this.applyState(u)},getState(){let d={};for(let[p,_]of e)d[p]=Array.from(_);let u={};for(let[p,_]of t)_.size>0&&(u[p]=Array.from(_));return{elements:d,tombstones:u,version:n,lastUpdated:a}},applyState(d){let u=!1;for(let[p,_]of Object.entries(d.elements)){e.has(p)||e.set(p,new Set);let g=e.get(p);for(let l of _)g.has(l)||(g.add(l),u=!0)}for(let[p,_]of Object.entries(d.tombstones)){t.has(p)||t.set(p,new Set);let g=t.get(p);for(let l of _)g.has(l)||(g.add(l),u=!0)}u&&(n=Math.max(n,d.version)+1,a=Date.now())},getNodeId(){return o},clear(){for(let[d,u]of e){t.has(d)||t.set(d,new Set);let p=t.get(d);for(let _ of u)p.add(_)}n++,a=Date.now()}}}function z(o,e){let t=q(o);return t.applyState(e),t}var Z=R(()=>{"use strict";se()});function ee(o){let e={...Ke,...o},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:a}=e,i=new Map,T=new Map,E=new Map,d=new Map,u=0,p=[],_=new Set,g={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function l(s,r,c){let N={key:s,type:r,operation:c,timestamp:Date.now(),nodeId:t};for(let Ue of _)try{Ue(N)}catch(xe){console.error("[CRDTStore] Error in change listener:",xe)}}function m(s,r){u++,n&&g[s].add(r)}function L(){if(!n||!(g.registers.size>0||g.gCounters.size>0||g.pnCounters.size>0||g.sets.size>0))return;let r={fromVersion:p.length>0?p[p.length-1].toVersion:0,toVersion:u,timestamp:Date.now(),nodeId:t};if(g.registers.size>0){r.registers={};for(let c of g.registers){let N=i.get(c);N&&(r.registers[c]=N.getState())}g.registers.clear()}if(g.gCounters.size>0){r.gCounters={};for(let c of g.gCounters){let N=T.get(c);N&&(r.gCounters[c]=N.getState())}g.gCounters.clear()}if(g.pnCounters.size>0){r.pnCounters={};for(let c of g.pnCounters){let N=E.get(c);N&&(r.pnCounters[c]=N.getState())}g.pnCounters.clear()}if(g.sets.size>0){r.sets={};for(let c of g.sets){let N=d.get(c);N&&(r.sets[c]=N.getState())}g.sets.clear()}for(p.push(r);p.length>a;)p.shift()}let h={getRegister(s){return i.has(s)||i.set(s,x(t)),i.get(s)},setRegister(s,r){h.getRegister(s).set(r),m("registers",s),l(s,"lww-register","set")},hasRegister(s){return i.has(s)},deleteRegister(s){let r=i.delete(s);return r&&m("registers",s),r},getGCounter(s){return T.has(s)||T.set(s,I(t)),T.get(s)},incrementGCounter(s,r){h.getGCounter(s).increment(r),m("gCounters",s),l(s,"g-counter","increment")},hasGCounter(s){return T.has(s)},deleteGCounter(s){let r=T.delete(s);return r&&m("gCounters",s),r},getCounter(s){return E.has(s)||E.set(s,P(t)),E.get(s)},incrementCounter(s,r){h.getCounter(s).increment(r),m("pnCounters",s),l(s,"pn-counter","increment")},decrementCounter(s,r){h.getCounter(s).decrement(r),m("pnCounters",s),l(s,"pn-counter","decrement")},hasCounter(s){return E.has(s)},deleteCounter(s){let r=E.delete(s);return r&&m("pnCounters",s),r},getSet(s){return d.has(s)||d.set(s,q(t)),d.get(s)},addToSet(s,r){h.getSet(s).add(r),m("sets",s),l(s,"or-set","add")},removeFromSet(s,r){h.getSet(s).remove(r),m("sets",s),l(s,"or-set","remove")},hasSet(s){return d.has(s)},deleteSet(s){let r=d.delete(s);return r&&m("sets",s),r},merge(s){let r=s.getState();h.applyState(r)},getState(){L();let s={version:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,c]of i)s.registers[r]=c.getState();for(let[r,c]of T)s.gCounters[r]=c.getState();for(let[r,c]of E)s.pnCounters[r]=c.getState();for(let[r,c]of d)s.sets[r]=c.getState();return s},applyState(s){for(let[r,c]of Object.entries(s.registers))i.has(r)?i.get(r).applyState(c):i.set(r,F(t,c)),m("registers",r),l(r,"lww-register","merge");for(let[r,c]of Object.entries(s.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,M(t,c)),m("gCounters",r),l(r,"g-counter","merge");for(let[r,c]of Object.entries(s.pnCounters))E.has(r)?E.get(r).applyState(c):E.set(r,k(t,c)),m("pnCounters",r),l(r,"pn-counter","merge");for(let[r,c]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(c):d.set(r,z(t,c)),m("sets",r),l(r,"or-set","merge");u=Math.max(u,s.version)+1},getDelta(s){if(L(),p.length===0)return s>=u,null;let r=p.filter(N=>N.toVersion>s);if(r.length===0)return null;let c={fromVersion:s,toVersion:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let N of r)N.registers&&Object.assign(c.registers,N.registers),N.gCounters&&Object.assign(c.gCounters,N.gCounters),N.pnCounters&&Object.assign(c.pnCounters,N.pnCounters),N.sets&&Object.assign(c.sets,N.sets);return Object.keys(c.registers).length===0&&delete c.registers,Object.keys(c.gCounters).length===0&&delete c.gCounters,Object.keys(c.pnCounters).length===0&&delete c.pnCounters,Object.keys(c.sets).length===0&&delete c.sets,c},applyDelta(s){if(s.registers)for(let[r,c]of Object.entries(s.registers))i.has(r)?i.get(r).applyState(c):i.set(r,F(t,c)),m("registers",r),l(r,"lww-register","merge");if(s.gCounters)for(let[r,c]of Object.entries(s.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,M(t,c)),m("gCounters",r),l(r,"g-counter","merge");if(s.pnCounters)for(let[r,c]of Object.entries(s.pnCounters))E.has(r)?E.get(r).applyState(c):E.set(r,k(t,c)),m("pnCounters",r),l(r,"pn-counter","merge");if(s.sets)for(let[r,c]of Object.entries(s.sets))d.has(r)?d.get(r).applyState(c):d.set(r,z(t,c)),m("sets",r),l(r,"or-set","merge");u=Math.max(u,s.toVersion)+1},getVersion(){return u},getNodeId(){return t},on(s,r){if(s==="change")return _.add(r),()=>{_.delete(r)};throw new Error(`Unknown event type: ${s}`)},removeAllListeners(){_.clear()},keys(s){let r=[];return(!s||s==="lww-register")&&r.push(...Array.from(i.keys())),(!s||s==="g-counter")&&r.push(...Array.from(T.keys())),(!s||s==="pn-counter")&&r.push(...Array.from(E.keys())),(!s||s==="or-set")&&r.push(...Array.from(d.keys())),r},clear(){i.clear(),T.clear(),E.clear(),d.clear(),p.length=0,g.registers.clear(),g.gCounters.clear(),g.pnCounters.clear(),g.sets.clear(),u=0},getStats(){return{total:i.size+T.size+E.size+d.size,registers:i.size,gCounters:T.size,pnCounters:E.size,sets:d.size,version:u,nodeId:t,deltaHistorySize:p.length}}};return h}var Ke,Ie=R(()=>{"use strict";V();G();Q();Z();Ke={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var Ae=R(()=>{"use strict"});var Oe=R(()=>{"use strict";V();G();Q();Z();Ie();Ae()});var Ze={};Fe(Ze,{ALLOWED_TABLE_NAMES:()=>Y,BinaryHeap:()=>oe,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>De,UnifiedHnswIndex:()=>w,UnifiedMemoryManager:()=>v,clearProjectRootCache:()=>W,createHnswIndex:()=>ie,findProjectRoot:()=>y,getDefaultDbPath:()=>ye,getResolvedDefaultConfig:()=>Xe,getUnifiedMemory:()=>we,initializeUnifiedMemory:()=>Ve,resetUnifiedMemory:()=>Qe,validateTableName:()=>O});import*as f from"fs";import*as be from"os";import*as S from"path";function ye(){let o=y();return S.join(o,".agentic-qe","memory.db")}function Xe(){return{...De,dbPath:ye()}}function we(o){return v.getInstance(o)}async function Ve(o){let e=we(o);return await e.initialize(),e}function Qe(){v.resetInstance()}function Je(){if(ve)return;ve=!0;let o=()=>{try{let e=v.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",o),process.on("SIGINT",()=>{o(),process.exit(0)}),process.on("SIGTERM",()=>{o(),process.exit(0)})}var D,De,v,ve,et=R(()=>{ke();se();Me();Ge();Pe();ue();$();$();ae();ae();Ce();Oe();je();D=ne.create("unified-memory");De={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:b.MMAP_SIZE_BYTES,cacheSize:b.CACHE_SIZE_KB,busyTimeout:b.BUSY_TIMEOUT_MS,vectorDimensions:b.DEFAULT_VECTOR_DIMENSIONS};v=class o{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new w("qe-memory");crdtStore=null;proofGate=null;proofGateEnvChecked=!1;static PROOF_NS="__proofgate__";static PROOF_KEY="chain";constructor(e){let t=Xe();if(this.config={...t,...e},process.env.AQE_MEMORY_BACKEND==="memory"){this.config.dbPath=":memory:";return}if(!S.isAbsolute(this.config.dbPath)){let n=y();this.config.dbPath=S.join(n,this.config.dbPath)}}static getInstance(e){return o.instance||(o.instance=new o(e)),o.instance}static async getInstanceAsync(e){return o.instance?.initialized?o.instance:(o.instancePromise||(o.instancePromise=(async()=>{let t=o.getInstance(e);return await t.initialize(),t})()),o.instancePromise)}static resetInstance(){o.instance&&(o.instance.close(),o.instance=null),o.instancePromise=null,W()}async initialize(e){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize(e?.signal)),this.initPromise}async _doInitialize(e){if(!this.initialized){e?.throwIfAborted();try{let t=this.config.dbPath===":memory:",n="",a=!1,i=0;if(!t){let T=process.env.AQE_PROJECT_ROOT;if(T){let E=S.resolve(this.config.dbPath),d=S.resolve(T);!E.startsWith(d)&&!E.startsWith(be.tmpdir())&&E.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${T}". Redirecting to test-safe path.`),this.config.dbPath=S.join(T,".agentic-qe","memory.db"))}if(n=S.dirname(this.config.dbPath),f.existsSync(n)||f.mkdirSync(n,{recursive:!0}),a=f.existsSync(this.config.dbPath),a)i=f.statSync(this.config.dbPath).size;else if(f.existsSync(n)){let E=this.findRecentBackups(n);if(E.length>0){let d=E[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
600
600
  Expected: ${this.config.dbPath}
601
601
  Found ${E.length} backup(s), newest: ${d.path} (${(d.size/1024/1024).toFixed(1)}MB)
602
- Restoring from backup to prevent data loss...`),f.copyFileSync(d.path,this.config.dbPath);for(let u of["-wal","-shm"]){let p=this.config.dbPath+u;f.existsSync(p)&&f.unlinkSync(p)}i=d.size}}}if(e?.throwIfAborted(),this.db=ne(this.config.dbPath,{walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,autoRestore:!0}),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.db.pragma("foreign_keys = ON"),e?.aborted){try{this.db.close()}catch{}this.db=null,e.throwIfAborted()}if(await this.runMigrations(),e?.throwIfAborted(),a&&i>1e6)try{let c=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(c&&c.cnt===0){let E=f.statSync(this.config.dbPath).size;E<i*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
602
+ Restoring from backup to prevent data loss...`),f.copyFileSync(d.path,this.config.dbPath);for(let u of["-wal","-shm"]){let p=this.config.dbPath+u;f.existsSync(p)&&f.unlinkSync(p)}i=d.size}}}if(e?.throwIfAborted(),this.db=re(this.config.dbPath,{walMode:this.config.walMode,busyTimeout:this.config.busyTimeout,autoRestore:!0}),this.db.pragma(`mmap_size = ${this.config.mmapSize}`),this.db.pragma(`cache_size = ${this.config.cacheSize}`),this.db.pragma("foreign_keys = ON"),e?.aborted){try{this.db.close()}catch{}this.db=null,e.throwIfAborted()}if(await this.runMigrations(),e?.throwIfAborted(),a&&i>1e6)try{let T=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(T&&T.cnt===0){let E=f.statSync(this.config.dbPath).size;E<i*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
603
603
  DB was ${(i/1024/1024).toFixed(1)}MB, now ${(E/1024/1024).toFixed(1)}MB with 0 patterns.
604
604
  This looks like the DB was replaced with an empty schema.
605
- Check backups in ${n} and restore manually.`)}}catch{}this.vectorsLoaded=!1,this.initialized=!0,console.log(`[UnifiedMemory] Initialized: ${this.config.dbPath}`),this.warnIfDuplicateDatabases()}catch(t){throw this.initPromise=null,t instanceof Error&&(t.name==="AbortError"||(e?.aborted??!1))?t:new Error(`Failed to initialize UnifiedMemoryManager: ${X(t)}`)}}}findRecentBackups(e){try{let n=f.readdirSync(e).filter(i=>i.startsWith("memory")&&i.endsWith(".db")&&i!=="memory.db").map(i=>{let c=S.join(e,i),E=f.statSync(c);return{path:c,size:E.size,mtime:E.mtimeMs}}).filter(i=>i.size>1e6).sort((i,c)=>c.mtime-i.mtime),a=S.join(e,"backups");if(f.existsSync(a)){let i=f.readdirSync(a);for(let c of i)if(c.endsWith(".db")){let E=S.join(a,c),d=f.statSync(E);d.size>1e6&&n.push({path:E,size:d.size,mtime:d.mtimeMs})}n.sort((c,E)=>E.mtime-c.mtime)}return n}catch{return[]}}warnIfDuplicateDatabases(){if(this.config.dbPath!==":memory:")try{let e=D(),t=S.resolve(this.config.dbPath),a=[S.join(e,".agentic-qe","memory.db"),S.join(e,"v3",".agentic-qe","memory.db")].map(i=>S.resolve(i)).filter(i=>i!==t&&f.existsSync(i));a.length>0&&console.warn(`[UnifiedMemory] WARNING: Duplicate database(s) detected!
605
+ Check backups in ${n} and restore manually.`)}}catch{}this.vectorsLoaded=!1,this.initialized=!0,console.log(`[UnifiedMemory] Initialized: ${this.config.dbPath}`),this.warnIfDuplicateDatabases()}catch(t){throw this.initPromise=null,t instanceof Error&&(t.name==="AbortError"||(e?.aborted??!1))?t:new Error(`Failed to initialize UnifiedMemoryManager: ${X(t)}`)}}}findRecentBackups(e){try{let n=f.readdirSync(e).filter(i=>i.startsWith("memory")&&i.endsWith(".db")&&i!=="memory.db").map(i=>{let T=S.join(e,i),E=f.statSync(T);return{path:T,size:E.size,mtime:E.mtimeMs}}).filter(i=>i.size>1e6).sort((i,T)=>T.mtime-i.mtime),a=S.join(e,"backups");if(f.existsSync(a)){let i=f.readdirSync(a);for(let T of i)if(T.endsWith(".db")){let E=S.join(a,T),d=f.statSync(E);d.size>1e6&&n.push({path:E,size:d.size,mtime:d.mtimeMs})}n.sort((T,E)=>E.mtime-T.mtime)}return n}catch{return[]}}warnIfDuplicateDatabases(){if(this.config.dbPath!==":memory:")try{let e=y(),t=S.resolve(this.config.dbPath),a=[S.join(e,".agentic-qe","memory.db"),S.join(e,"v3",".agentic-qe","memory.db")].map(i=>S.resolve(i)).filter(i=>i!==t&&f.existsSync(i));a.length>0&&console.warn(`[UnifiedMemory] WARNING: Duplicate database(s) detected!
606
606
  Canonical: ${t}
607
607
  Duplicates: ${a.join(", ")}
608
- This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){y.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=A(e);return this.db.prepare(`PRAGMA table_info(${n})`).all().some(i=>i.name===t)}catch(n){return y.debug("Column existence check failed",{table:e,column:t,error:n instanceof Error?n.message:String(n)}),!1}}handleV2SchemaIncompatibilities(){if(!this.db)return;let e=[{table:"goap_plans",requiredColumn:"status",columnDef:"TEXT DEFAULT 'pending'"},{table:"goap_actions",requiredColumn:"agent_type",columnDef:"TEXT DEFAULT 'unknown'"},{table:"concept_nodes",requiredColumn:"concept_type",columnDef:"TEXT DEFAULT 'general'"},{table:"concept_edges",requiredColumn:"edge_type",columnDef:"TEXT DEFAULT 'related'"},{table:"dream_insights",requiredColumn:"cycle_id",columnDef:"TEXT DEFAULT ''"},{table:"rl_q_values",requiredColumn:"algorithm",columnDef:"TEXT DEFAULT 'q-learning'"}];for(let{table:t,requiredColumn:n,columnDef:a}of e)if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)&&!this.columnExists(t,n)){let c=A(t);try{this.db.exec(`ALTER TABLE ${c} ADD COLUMN ${n} ${a}`),console.log(`[UnifiedMemory] Added column ${n} to ${t} (safe migration)`)}catch(E){console.log(`[UnifiedMemory] Column ${n} on ${t}: ${E instanceof Error?E.message:String(E)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(pe),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<U&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${U}`),this.db.transaction(()=>{t<1&&this.db.exec(le),t<2&&this.db.exec(ge),t<3&&(this.db.exec(me),this.db.exec(K),this.db.exec(_e)),t<4&&this.db.exec(fe),t<5&&this.db.exec(Ne),t<6&&this.db.exec(j),t<7&&this.db.exec(Se),t<8&&this.db.exec(he),t<9&&(this.db.exec(`
608
+ This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){D.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let n=O(e);return this.db.prepare(`PRAGMA table_info(${n})`).all().some(i=>i.name===t)}catch(n){return D.debug("Column existence check failed",{table:e,column:t,error:n instanceof Error?n.message:String(n)}),!1}}handleV2SchemaIncompatibilities(){if(!this.db)return;let e=[{table:"goap_plans",requiredColumn:"status",columnDef:"TEXT DEFAULT 'pending'"},{table:"goap_actions",requiredColumn:"agent_type",columnDef:"TEXT DEFAULT 'unknown'"},{table:"concept_nodes",requiredColumn:"concept_type",columnDef:"TEXT DEFAULT 'general'"},{table:"concept_edges",requiredColumn:"edge_type",columnDef:"TEXT DEFAULT 'related'"},{table:"dream_insights",requiredColumn:"cycle_id",columnDef:"TEXT DEFAULT ''"},{table:"rl_q_values",requiredColumn:"algorithm",columnDef:"TEXT DEFAULT 'q-learning'"}];for(let{table:t,requiredColumn:n,columnDef:a}of e)if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)&&!this.columnExists(t,n)){let T=O(t);try{this.db.exec(`ALTER TABLE ${T} ADD COLUMN ${n} ${a}`),console.log(`[UnifiedMemory] Added column ${n} to ${t} (safe migration)`)}catch(E){console.log(`[UnifiedMemory] Column ${n} on ${t}: ${E instanceof Error?E.message:String(E)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(le),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<U&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${U}`),this.db.transaction(()=>{t<1&&this.db.exec(ge),t<2&&this.db.exec(me),t<3&&(this.db.exec(_e),this.db.exec(K),this.db.exec(fe)),t<4&&this.db.exec(Ne),t<5&&this.db.exec(Se),t<6&&this.db.exec(j),t<7&&this.db.exec(he),t<8&&this.db.exec(Re),t<9&&(this.db.exec(`
609
609
  CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
610
610
  name, description, pattern_type, qe_domain,
611
611
  content='qe_patterns',
@@ -634,10 +634,10 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
634
634
  `)),t<10&&this.db.exec(B),t<11&&this.migrateToV11GoapExecutionSteps(),this.db.prepare(`
635
635
  INSERT OR REPLACE INTO schema_version (id, version, migrated_at)
636
636
  VALUES (1, ?, datetime('now'))
637
- `).run(U)})(),console.log("[UnifiedMemory] Migration complete"))}migrateToV11GoapExecutionSteps(){let e=this.db;e.exec(K);let t=(n,a,i)=>{e.prepare(`SELECT name FROM pragma_table_info('${n}')`).all().some(E=>E.name===a)||e.exec(`ALTER TABLE ${n} ADD COLUMN ${a} ${i}`)};t("goap_execution_steps","execution_id","TEXT"),t("goap_execution_steps","retries","INTEGER DEFAULT 0"),t("goap_execution_steps","started_at","TEXT"),t("goap_execution_steps","agent_output","TEXT"),t("goap_actions","method","TEXT"),t("goap_actions","params","TEXT"),t("goap_actions","implemented","INTEGER DEFAULT 0"),e.exec("CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_execution ON goap_execution_steps(execution_id)")}async loadVectorIndex(){if(this.vectorsLoaded)return;if(!this.db)throw new Error("Database not initialized");this.vectorIndex.clear();let e=this.db.prepare("SELECT id, embedding, dimensions FROM vectors").all();for(let t of e){let n=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,n)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,n="default",a){this.ensureInitialized();let i=a?Date.now()+a*1e3:null,c=JSON.stringify(t);this.db.prepare(`
637
+ `).run(U)})(),console.log("[UnifiedMemory] Migration complete"))}migrateToV11GoapExecutionSteps(){let e=this.db;e.exec(K);let t=(n,a,i)=>{e.prepare(`SELECT name FROM pragma_table_info('${n}')`).all().some(E=>E.name===a)||e.exec(`ALTER TABLE ${n} ADD COLUMN ${a} ${i}`)};t("goap_execution_steps","execution_id","TEXT"),t("goap_execution_steps","retries","INTEGER DEFAULT 0"),t("goap_execution_steps","started_at","TEXT"),t("goap_execution_steps","agent_output","TEXT"),t("goap_actions","method","TEXT"),t("goap_actions","params","TEXT"),t("goap_actions","implemented","INTEGER DEFAULT 0"),e.exec("CREATE INDEX IF NOT EXISTS idx_goap_exec_steps_execution ON goap_execution_steps(execution_id)")}async loadVectorIndex(){if(this.vectorsLoaded)return;if(!this.db)throw new Error("Database not initialized");this.vectorIndex.clear();let e=this.db.prepare("SELECT id, embedding, dimensions FROM vectors").all();for(let t of e){let n=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,n)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,n="default",a){this.ensureInitialized();let i=a?Date.now()+a*1e3:null,T=JSON.stringify(t);this.db.prepare(`
638
638
  INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at)
639
639
  VALUES (?, ?, ?, ?)
640
- `).run(e,n,c,i),this.auditWrite("kvSet",n,e,c)}async kvGet(e,t="default"){this.ensureInitialized();let n=this.db.prepare(`
640
+ `).run(e,n,T,i),this.auditWrite("kvSet",n,e,T)}async kvGet(e,t="default"){this.ensureInitialized();let n=this.db.prepare(`
641
641
  SELECT value, expires_at FROM kv_store
642
642
  WHERE key = ? AND namespace = ?
643
643
  `).get(e,t);if(n){if(n.expires_at&&Date.now()>n.expires_at){this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t);return}return C(n.value)}}async kvDelete(e,t="default"){this.ensureInitialized();let n=this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t);return n.changes>0&&this.auditWrite("kvDelete",t,e,""),n.changes>0}async kvExists(e,t="default"){return this.ensureInitialized(),this.db.prepare(`
@@ -648,14 +648,14 @@ import{d as j,f as ke}from"./chunk-GV3C224P.js";import{a as B,c as qe}from"./chu
648
648
  WHERE namespace = ? AND key LIKE ?
649
649
  AND (expires_at IS NULL OR expires_at > ?)
650
650
  LIMIT ?
651
- `).all(t,a,Date.now(),n).map(c=>c.key)}async kvCleanupExpired(){return this.ensureInitialized(),this.db.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now()).changes}enableProofGate(){this.ensureInitialized(),this.proofGateEnvChecked=!0,!this.proofGate&&(this.proofGate=this.loadProofChain()??new O)}isProofGateEnabled(){return this.proofGate!==null}verifyMemoryIntegrity(){if(!this.proofGate)throw new Error("Proof-gate not enabled \u2014 call enableProofGate() or set AQE_PROOF_GATE=1");return this.proofGate.verifyIntegrity()}getProofChainRoot(){return this.proofGate?this.proofGate.chainRoot():null}getProofChainLength(){return this.proofGate?this.proofGate.length:0}auditWrite(e,t,n,a){if(!this.proofGate){if(this.proofGateEnvChecked||(this.proofGateEnvChecked=!0,process.env.AQE_PROOF_GATE!=="1"))return;this.proofGate=this.loadProofChain()??new O}if(t!==o.PROOF_NS)try{this.proofGate.admit({op:e,ns:t,key:n,value:a}),this.persistProofChain()}catch(i){y.warn(`proof-gate audit skipped for ${t}/${n}: ${X(i)}`)}}persistProofChain(){!this.proofGate||!this.db||this.db.prepare(`
651
+ `).all(t,a,Date.now(),n).map(T=>T.key)}async kvCleanupExpired(){return this.ensureInitialized(),this.db.prepare("DELETE FROM kv_store WHERE expires_at IS NOT NULL AND expires_at < ?").run(Date.now()).changes}enableProofGate(){this.ensureInitialized(),this.proofGateEnvChecked=!0,!this.proofGate&&(this.proofGate=this.loadProofChain()??new A)}isProofGateEnabled(){return this.proofGate!==null}verifyMemoryIntegrity(){if(!this.proofGate)throw new Error("Proof-gate not enabled \u2014 call enableProofGate() or set AQE_PROOF_GATE=1");return this.proofGate.verifyIntegrity()}getProofChainRoot(){return this.proofGate?this.proofGate.chainRoot():null}getProofChainLength(){return this.proofGate?this.proofGate.length:0}auditWrite(e,t,n,a){if(!this.proofGate){if(this.proofGateEnvChecked||(this.proofGateEnvChecked=!0,process.env.AQE_PROOF_GATE!=="1"))return;this.proofGate=this.loadProofChain()??new A}if(t!==o.PROOF_NS)try{this.proofGate.admit({op:e,ns:t,key:n,value:a}),this.persistProofChain()}catch(i){D.warn(`proof-gate audit skipped for ${t}/${n}: ${X(i)}`)}}persistProofChain(){!this.proofGate||!this.db||this.db.prepare(`
652
652
  INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at)
653
653
  VALUES (?, ?, ?, NULL)
654
654
  `).run(o.PROOF_KEY,o.PROOF_NS,JSON.stringify(this.proofGate.toJSON()))}loadProofChain(){if(!this.db)return null;let e=this.db.prepare(`
655
655
  SELECT value FROM kv_store WHERE key = ? AND namespace = ?
656
- `).get(o.PROOF_KEY,o.PROOF_NS);if(!e)return null;try{return O.fromJSON(JSON.parse(e.value))}catch(t){return y.warn(`proof-gate chain failed to load (starting fresh): ${X(t)}`),null}}async vectorStore(e,t,n="default",a){this.ensureInitialized();let i=this.floatArrayToBuffer(t),c=a?JSON.stringify(a):null;this.db.prepare(`
656
+ `).get(o.PROOF_KEY,o.PROOF_NS);if(!e)return null;try{return A.fromJSON(JSON.parse(e.value))}catch(t){return D.warn(`proof-gate chain failed to load (starting fresh): ${X(t)}`),null}}async vectorStore(e,t,n="default",a){this.ensureInitialized();let i=this.floatArrayToBuffer(t),T=a?JSON.stringify(a):null;this.db.prepare(`
657
657
  INSERT OR REPLACE INTO vectors (id, namespace, embedding, dimensions, metadata, updated_at)
658
658
  VALUES (?, ?, ?, ?, ?, datetime('now'))
659
- `).run(e,n,i,t.length,c),this.vectorIndex.add(e,t)}async vectorGet(e){this.ensureInitialized();let t=this.db.prepare(`
659
+ `).run(e,n,i,t.length,T),this.vectorIndex.add(e,t)}async vectorGet(e){this.ensureInitialized();let t=this.db.prepare(`
660
660
  SELECT embedding, dimensions, metadata FROM vectors WHERE id = ?
661
- `).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?C(t.metadata):void 0}}async vectorDelete(e){this.ensureInitialized();let t=this.db.prepare("DELETE FROM vectors WHERE id = ?").run(e);return this.vectorIndex.remove(e),t.changes>0}async vectorSearch(e,t=10,n,a){this.ensureInitialized(),this.vectorsLoaded||await this.loadVectorIndex();let i=this.vectorIndex.size(),c=Math.min(i,Math.max(t*2,1)),E=this.vectorIndex.search(e,c);for(;a&&E.filter(l=>l.id.startsWith(a)).length<t&&c<i;)c=Math.min(i,c*2),E=this.vectorIndex.search(e,c);if(E.length===0)return[];let d=E.map(l=>l.id),u=d.map(()=>"?").join(","),p=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${u})`).all(...d),_=new Map(p.map(l=>[l.id,l]));if(n){let l=[];for(let m of E){let L=_.get(m.id);if(L&&L.namespace===n&&(!a||m.id.startsWith(a))&&(l.push({id:m.id,score:m.score,metadata:L.metadata?C(L.metadata):void 0}),l.length>=t))break}return l}return(a?E.filter(l=>l.id.startsWith(a)).slice(0,t):E.slice(0,t)).map(l=>{let m=_.get(l.id);return{id:l.id,score:l.score,metadata:m?.metadata?C(m.metadata):void 0}})}async vectorCount(e){return this.ensureInitialized(),e?this.db.prepare("SELECT COUNT(*) as count FROM vectors WHERE namespace = ?").get(e).count:this.db.prepare("SELECT COUNT(*) as count FROM vectors").get().count}queryCount(e){this.ensureInitialized();let t=A(e);return this.db.prepare(`SELECT COUNT(*) as c FROM ${t}`).get().c}initializeCRDT(e){if(this.crdtStore){console.warn("[UnifiedMemory] CRDT store already initialized");return}this.crdtStore=ee({nodeId:e}),console.log(`[UnifiedMemory] CRDT store initialized for node: ${e}`)}getCRDTStore(){return this.crdtStore}isCRDTInitialized(){return this.crdtStore!==null}async crdtSet(e,t,n="crdt"){this.ensureInitialized(),this.crdtStore&&this.crdtStore.setRegister(e,t),await this.kvSet(e,t,n)}async crdtGet(e,t="crdt"){if(this.crdtStore){let n=this.crdtStore.getRegister(e);if(n)return n.get()}return this.kvGet(e,t)}crdtIncrement(e,t=1){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");let n=this.crdtStore.getCounter(e);n||(this.crdtStore.incrementCounter(e,0),n=this.crdtStore.getCounter(e));for(let a=0;a<t;a++)this.crdtStore.incrementCounter(e)}crdtGetCounter(e){return this.crdtStore?this.crdtStore.getCounter(e)?.get()??0:0}crdtAddToSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.addToSet(e,t)}crdtRemoveFromSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.removeFromSet(e,t)}crdtGetSet(e){if(!this.crdtStore)return new Set;let t=this.crdtStore.getSet(e);return new Set(t.values())}crdtGetState(){return this.crdtStore?this.crdtStore.getState():null}crdtGetDelta(e){return this.crdtStore?this.crdtStore.getDelta(e??0):null}crdtMerge(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyState(e)}crdtApplyDelta(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyDelta(e)}async crdtPersist(){if(!this.crdtStore)return;let e=this.crdtStore.getState();await this.kvSet("__crdt_state__",e,"crdt-internal")}async crdtRestore(){if(!this.crdtStore)return!1;let e=await this.kvGet("__crdt_state__","crdt-internal");return e?(this.crdtStore.applyState(e),!0):!1}getDatabase(){if(!this.db||!this.initialized)throw new Error("UnifiedMemoryManager not initialized");return this.db}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.db)throw new Error("Database not initialized");let n=this.preparedStatements.get(e);return n||(n=this.db.prepare(t),this.preparedStatements.set(e,n)),n}transaction(e){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(e)()}getStats(){if(!this.db)throw new Error("Database not initialized");let e=Re.map(a=>{try{let i=this.db.prepare(`SELECT COUNT(*) as count FROM ${a}`).get();return{name:a,rowCount:i.count}}catch(i){return y.debug("Table row count query failed",{table:a,error:i instanceof Error?i.message:String(i)}),{name:a,rowCount:0}}}),t=0,n=0;try{f.existsSync(this.config.dbPath)&&(t=f.statSync(this.config.dbPath).size);let a=this.config.dbPath+"-wal";f.existsSync(a)&&(n=f.statSync(a).size)}catch(a){console.debug("[UnifiedMemory] File stat error:",a instanceof Error?a.message:a)}return{tables:e,fileSize:t,walSize:n,vectorIndexSize:this.vectorIndex.size()}}vacuum(){if(!this.db)throw new Error("Database not initialized");this.db.exec("VACUUM")}checkpoint(){if(!this.db)throw new Error("Database not initialized");this.db.pragma("wal_checkpoint(TRUNCATE)")}close(){this.db&&(this.preparedStatements.clear(),this.vectorIndex.clear(),this.db.close(),this.db=null,this.initialized=!1,console.log("[UnifiedMemory] Database closed"))}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("UnifiedMemoryManager not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=new Float32Array(e.buffer,e.byteOffset,t);return Array.from(n)}};Ae=!1;Qe()});export{Y as a,A as b,nt as c,$ as d,be as e,De as f,ye as g,v as h,Xe as i,Ke as j,Ve as k,Je as l,Ze as m};
661
+ `).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?C(t.metadata):void 0}}async vectorDelete(e){this.ensureInitialized();let t=this.db.prepare("DELETE FROM vectors WHERE id = ?").run(e);return this.vectorIndex.remove(e),t.changes>0}async vectorSearch(e,t=10,n,a){if(this.ensureInitialized(),!Number.isInteger(t)||t<=0)return[];this.vectorsLoaded||await this.loadVectorIndex();let i=this.vectorIndex.size(),T=!!(n||a),E=Math.min(i,Math.max(T?t*2:t,1)),d=n?this.db.prepare("SELECT id, namespace, metadata FROM vectors WHERE namespace = ?").all(n):void 0,u=d?new Map(d.map(l=>[l.id,l])):void 0,p=this.vectorIndex.search(e,E);for(;T&&p.filter(l=>(!a||l.id.startsWith(a))&&(!u||u.has(l.id))).length<t&&E<i;)E=Math.min(i,E*2),p=this.vectorIndex.search(e,E);if(p.length===0)return[];let _=u??(()=>{let l=p.map(h=>h.id),m=l.map(()=>"?").join(","),L=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${m})`).all(...l);return new Map(L.map(h=>[h.id,h]))})();if(n){let l=[];for(let m of p){let L=_.get(m.id);if(L&&L.namespace===n&&(!a||m.id.startsWith(a))&&(l.push({id:m.id,score:m.score,metadata:L.metadata?C(L.metadata):void 0}),l.length>=t))break}return l}return(a?p.filter(l=>l.id.startsWith(a)).slice(0,t):p.slice(0,t)).map(l=>{let m=_.get(l.id);return{id:l.id,score:l.score,metadata:m?.metadata?C(m.metadata):void 0}})}getVectorSearchProvenance(){return this.vectorIndex.getProvider().isNativeBackend()?{backend:"native-hnsw",indexType:"hnsw",approximate:!0,estimatedRecall:this.vectorIndex.recall(),qualifiedMaxK:te.EF_SEARCH}:{backend:"progressive-hnsw",indexType:"flat",approximate:!1,estimatedRecall:1}}async vectorCount(e){return this.ensureInitialized(),e?this.db.prepare("SELECT COUNT(*) as count FROM vectors WHERE namespace = ?").get(e).count:this.db.prepare("SELECT COUNT(*) as count FROM vectors").get().count}queryCount(e){this.ensureInitialized();let t=O(e);return this.db.prepare(`SELECT COUNT(*) as c FROM ${t}`).get().c}initializeCRDT(e){if(this.crdtStore){console.warn("[UnifiedMemory] CRDT store already initialized");return}this.crdtStore=ee({nodeId:e}),console.log(`[UnifiedMemory] CRDT store initialized for node: ${e}`)}getCRDTStore(){return this.crdtStore}isCRDTInitialized(){return this.crdtStore!==null}async crdtSet(e,t,n="crdt"){this.ensureInitialized(),this.crdtStore&&this.crdtStore.setRegister(e,t),await this.kvSet(e,t,n)}async crdtGet(e,t="crdt"){if(this.crdtStore){let n=this.crdtStore.getRegister(e);if(n)return n.get()}return this.kvGet(e,t)}crdtIncrement(e,t=1){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");let n=this.crdtStore.getCounter(e);n||(this.crdtStore.incrementCounter(e,0),n=this.crdtStore.getCounter(e));for(let a=0;a<t;a++)this.crdtStore.incrementCounter(e)}crdtGetCounter(e){return this.crdtStore?this.crdtStore.getCounter(e)?.get()??0:0}crdtAddToSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.addToSet(e,t)}crdtRemoveFromSet(e,t){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.removeFromSet(e,t)}crdtGetSet(e){if(!this.crdtStore)return new Set;let t=this.crdtStore.getSet(e);return new Set(t.values())}crdtGetState(){return this.crdtStore?this.crdtStore.getState():null}crdtGetDelta(e){return this.crdtStore?this.crdtStore.getDelta(e??0):null}crdtMerge(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyState(e)}crdtApplyDelta(e){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");this.crdtStore.applyDelta(e)}async crdtPersist(){if(!this.crdtStore)return;let e=this.crdtStore.getState();await this.kvSet("__crdt_state__",e,"crdt-internal")}async crdtRestore(){if(!this.crdtStore)return!1;let e=await this.kvGet("__crdt_state__","crdt-internal");return e?(this.crdtStore.applyState(e),!0):!1}getDatabase(){if(!this.db||!this.initialized)throw new Error("UnifiedMemoryManager not initialized");return this.db}isInitialized(){return this.initialized}getDbPath(){return this.config.dbPath}prepare(e,t){if(!this.db)throw new Error("Database not initialized");let n=this.preparedStatements.get(e);return n||(n=this.db.prepare(t),this.preparedStatements.set(e,n)),n}transaction(e){if(!this.db)throw new Error("Database not initialized");return this.db.transaction(e)()}getStats(){if(!this.db)throw new Error("Database not initialized");let e=Le.map(a=>{try{let i=this.db.prepare(`SELECT COUNT(*) as count FROM ${a}`).get();return{name:a,rowCount:i.count}}catch(i){return D.debug("Table row count query failed",{table:a,error:i instanceof Error?i.message:String(i)}),{name:a,rowCount:0}}}),t=0,n=0;try{f.existsSync(this.config.dbPath)&&(t=f.statSync(this.config.dbPath).size);let a=this.config.dbPath+"-wal";f.existsSync(a)&&(n=f.statSync(a).size)}catch(a){console.debug("[UnifiedMemory] File stat error:",a instanceof Error?a.message:a)}return{tables:e,fileSize:t,walSize:n,vectorIndexSize:this.vectorIndex.size()}}vacuum(){if(!this.db)throw new Error("Database not initialized");this.db.exec("VACUUM")}checkpoint(){if(!this.db)throw new Error("Database not initialized");this.db.pragma("wal_checkpoint(TRUNCATE)")}close(){this.db&&(this.preparedStatements.clear(),this.vectorIndex.clear(),this.db.close(),this.db=null,this.initialized=!1,console.log("[UnifiedMemory] Database closed"))}ensureInitialized(){if(!this.initialized||!this.db)throw new Error("UnifiedMemoryManager not initialized. Call initialize() first.")}floatArrayToBuffer(e){let t=Buffer.alloc(e.length*4);for(let n=0;n<e.length;n++)t.writeFloatLE(e[n],n*4);return t}bufferToFloatArray(e,t){let n=new Float32Array(e.buffer,e.byteOffset,t);return Array.from(n)}};ve=!1;Je()});export{Y as a,O as b,rt as c,$ as d,ye as e,De as f,Xe as g,v as h,we as i,Ve as j,Qe as k,Ze as l,et as m};
@@ -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.13.6");process.exit(0)}
2
- import{a as p,b as A,c as L}from"./chunk-6UPQD42K.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=D(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:1-e.distance,resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=N(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:p(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let d of e.agents)this.addNode(d.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,o={risk:i,fiedlerValue:n,collapseImminent:i>.7,weakVertices:r,recommendations:this.generateRecommendations(i,n,r),durationMs:a,usedFallback:!1};return this.logger.info("Analyzed swarm state",{agentCount:e.agents.length,risk:i,fiedlerValue:n,durationMs:a}),o}buildEdgesFromAgents(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.computeAgentSimilarity(e[t],e[i]);n>.3&&this.addEdge(e[t].agentId,e[i].agentId,n)}}computeAgentSimilarity(e,t){let i=1-Math.abs(e.health-t.health),n=1-Math.abs(e.successRate-t.successRate),r=e.agentType===t.agentType?.2:0,a=0,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,d)),i*.3+n*.3+r+a*.2}computeBeliefOverlap(e,t){if(e.length===0||t.length===0)return 0;let i=0,n=0;for(let r of e)for(let a of t)i+=this.cosineSimilarity(r.embedding,a.embedding),n++;return n>0?i/n:0}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}generateRecommendations(e,t,i){let n=[];return e>.7?(n.push("CRITICAL: Immediate action required to prevent swarm collapse."),n.push("Consider spawning additional coordination agents to strengthen connectivity.")):e>.5&&n.push("WARNING: Elevated collapse risk detected. Monitor closely."),t<.1&&n.push("Network connectivity is weak. Consider adding redundant communication channels."),t<.05&&(n.push("ALERT: Near-zero Fiedler value indicates potential false consensus."),n.push("Recommend spawning an independent reviewer to verify decisions.")),i.length>0&&n.push(`At-risk agents: ${i.join(", ")}. Consider reassigning critical tasks.`),n.length===0&&n.push("Swarm health is good. No immediate action required."),n}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared spectral graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("SpectralAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}};function O(u){let e=null,t=null,i=new Map,n=()=>({cause:e?Array.from(e):[],effect:t?Array.from(t):[],confounders:Object.fromEntries(Array.from(i.entries()).map(([r,a])=>[r,Array.from(a)]))});return{set_data(r,a){e=r,t=a},add_confounder(r,a){i.set(r,a)},compute_causal_effect(){let r=n();return u.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(u.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return u.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var b=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=O(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),durationMs:l,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:c.isCausal,relationshipType:d,effectStrength:r,durationMs:l}),c}setData(e,t){if(this.ensureInitialized(),e.length!==t.length)throw new Error(`Cause and effect arrays must have same length. Got ${e.length} and ${t.length}.`);let i=new Float64Array(e),n=new Float64Array(t);this.engine.set_data(i,n),this.logger.debug("Set causal data",{sampleSize:e.length})}addConfounder(e,t){this.ensureInitialized();let i=new Float64Array(t);this.engine.add_confounder(e,i),this.logger.debug("Added confounder",{name:e,valueCount:t.length})}computeCausalEffect(){this.ensureInitialized();let e=this.engine.compute_causal_effect();return this.logger.debug("Computed causal effect",{effect:e}),e}detectSpuriousCorrelation(){this.ensureInitialized();let e=this.engine.detect_spurious_correlation();return this.logger.debug("Detected spurious correlation",{isSpurious:e}),e}getConfounders(){return this.ensureInitialized(),this.engine.get_confounders()}determineRelationshipType(e,t,i){return e<.1?"none":t?"spurious":i?"confounded":e<0?"reverse":"causal"}computeConfidence(e,t,i){let n=Math.min(1,e/100)*.5;return n+=Math.abs(t)*.3,i&&(n+=.15),Math.min(.95,n)}generateExplanation(e,t,i,n,r){switch(i){case"causal":return`Analysis indicates a true causal relationship between '${e}' and '${t}'. Effect strength: ${(n*100).toFixed(1)}%. Changes in '${e}' are likely to cause changes in '${t}'.`;case"spurious":return`The correlation between '${e}' and '${t}' appears to be spurious. No true causal mechanism detected. This may be coincidental or due to a hidden common cause.`;case"reverse":return`Analysis suggests reverse causation: '${t}' may cause '${e}', not the other way around. Consider swapping the direction of your hypothesis.`;case"confounded":return`The relationship between '${e}' and '${t}' is confounded by: ${r.join(", ")}. These variables may explain the observed correlation without direct causation.`;case"none":return`No significant relationship detected between '${e}' and '${t}'. Effect strength is below the detection threshold.`;default:return`Analysis complete for '${e}' -> '${t}'.`}}clear(){this.ensureInitialized(),this.engine.clear(),this.currentCause="",this.currentEffect="",this.logger.debug("Cleared causal engine state")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.initialized=!1,this.logger.info("CausalAdapter disposed")}};function H(u){let e=new Map,t=[],i=()=>({objects:Array.from(e.entries()).map(([n,r])=>({name:n,schema:r})),morphisms:t.map(n=>({source:n.source,target:n.target,name:n.name}))});return{add_type(n,r){e.set(n,r)},add_morphism(n,r,a){t.push({source:n,target:r,name:a})},verify_composition(n){if(n.length<2)return!0;for(let a=0;a<n.length-1;a++){let o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&l.target===d))return!1}let r=i();return u.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var C=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=H(i),this.initialized=!0,this.logger.info("CategoryAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CategoryAdapter not initialized. Call initialize() first.")}addType(e,t){this.ensureInitialized(),this.types.set(e,t),this.engine.add_type(e,t),this.logger.debug("Added type to category",{name:e})}addMorphism(e,t,i){this.ensureInitialized(),this.morphisms.push({source:e,target:t,name:i}),this.engine.add_morphism(e,t,i),this.logger.debug("Added morphism to category",{source:e,target:t,name:i})}verifyComposition(e){if(this.ensureInitialized(),e.length<2)return!0;let t=this.engine.verify_composition(e);return this.logger.debug("Verified composition",{path:e,isValid:t}),t}checkTypeConsistency(){this.ensureInitialized();let t=this.engine.check_type_consistency().map(i=>this.transformMismatch(i));return this.logger.debug("Checked type consistency",{mismatchCount:t.length}),t}verifyPipeline(e){let t=Date.now();this.clear(),this.addType(e.inputType,this.inferSchema(e.inputType)),this.addType(e.outputType,this.inferSchema(e.outputType));for(let s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),d}buildCompositionPath(e){let t=[e.inputType];for(let i of e.elements)i.inputType!==t[t.length-1]&&t.push(i.inputType),t.push(i.outputType);return t[t.length-1]!==e.outputType&&t.push(e.outputType),t}inferSchema(e){return e.endsWith("[]")?`{ items: ${e.slice(0,-2)}[] }`:e.includes("|")?`{ union: [${e.split("|").map(t=>`"${t.trim()}"`).join(", ")}] }`:`{ type: "${e}" }`}transformMismatch(e){return{location:e.location,expected:e.expected,actual:e.actual,severity:this.determineMismatchSeverity(e)}}determineMismatchSeverity(e){return e.expected==="never"||e.actual==="never"?"critical":e.actual==="any"||e.actual==="unknown"?"high":e.expected.includes(e.actual)||e.actual.includes(e.expected)?"medium":"low"}generateWarnings(e,t,i){let n=[];t||n.push(`Pipeline '${e.id}' has an invalid composition chain. Types do not connect properly from input to output.`);for(let a of e.elements)(a.inputType==="any"||a.outputType==="any")&&n.push(`Element '${a.name}' uses 'any' type, which bypasses type safety.`);for(let a of e.elements)(a.inputType.includes("<T>")||a.outputType.includes("<T>"))&&n.push(`Element '${a.name}' has unconstrained generic types.`);let r=i.filter(a=>a.severity==="critical");return r.length>0&&n.push(`Found ${r.length} critical type mismatch(es) that will cause runtime errors.`),n}clear(){this.ensureInitialized(),this.types.clear(),this.morphisms.length=0,this.engine.clear(),this.logger.debug("Cleared category")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.types.clear(),this.morphisms.length=0,this.initialized=!1,this.logger.info("CategoryAdapter disposed")}getTypeCount(){return this.types.size}getMorphismCount(){return this.morphisms.length}};function V(u){let e=new Map,t=new Map;return{add_proposition(i,n){e.set(i,{formula:n,proven:!1})},add_proof(i,n){let r=e.get(i);if(!r)return!1;let a={id:i,proof:n},o={formula:r.formula};return u.typeCheck(a,o)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return u.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var w=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=V(i),this.initialized=!0,this.logger.info("HomotopyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("HomotopyAdapter not initialized. Call initialize() first.")}addProposition(e,t){this.ensureInitialized();let i={id:e,formula:t,proven:!1};this.propositions.set(e,i),this.engine.add_proposition(e,t),this.logger.debug("Added proposition",{id:e,formula:t})}addProof(e,t){this.ensureInitialized();let i=this.propositions.get(e);if(!i)return this.logger.warn("Proposition not found",{propositionId:e}),!1;let n=this.engine.add_proof(e,t);return n?(i.proven=!0,this.logger.info("Proposition proven",{propositionId:e})):this.logger.warn("Proof rejected",{propositionId:e}),n}verifyPathEquivalence(e,t){this.ensureInitialized();let i=this.engine.verify_path_equivalence(e,t),n=this.generateEquivalenceExplanation(e,t,i),r={equivalent:i,path1:e,path2:t,explanation:n};return this.logger.debug("Verified path equivalence",{path1Length:e.length,path2Length:t.length,equivalent:i}),r}generateEquivalenceExplanation(e,t,i){if(i)return e.length===t.length?"The execution paths are homotopically equivalent. Both paths traverse the same abstract structure and will produce equivalent results.":`The execution paths are equivalent despite different lengths. The ${e.length>t.length?"first":"second"} path contains redundant steps that can be contracted without changing the result (homotopy contraction).`;{let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n===0?`The execution paths diverge immediately. Path 1 starts with '${e[0]}' while Path 2 starts with '${t[0]}'. These lead to fundamentally different computation spaces.`:`The execution paths diverge at step ${n+1}. After '${e[n-1]}', Path 1 proceeds to '${e[n]}' while Path 2 proceeds to '${t[n]}'. No homotopy exists between these paths.`}}getUnprovenPropositions(){return this.ensureInitialized(),this.engine.get_unproven_propositions()}getVerificationStatus(){let e=this.propositions.size,t=Array.from(this.propositions.values()).filter(n=>n.proven).length,i=this.getUnprovenPropositions();return{totalPropositions:e,provenCount:t,unprovenIds:i,verificationPercentage:e>0?t/e*100:100}}getProposition(e){return this.propositions.get(e)}clear(){this.ensureInitialized(),this.propositions.clear(),this.engine.clear(),this.logger.debug("Cleared homotopy engine")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.propositions.clear(),this.initialized=!1,this.logger.info("HomotopyAdapter disposed")}getPropositionCount(){return this.propositions.size}};import{createHash as $}from"crypto";var E=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=$("sha256");return i.update(e),t&&i.update(t,"utf-8"),i.digest("hex")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("WitnessAdapter not initialized. Call initialize() first.")}createWitness(e){this.ensureInitialized();let t=this.serializeDecision(e),i=this.getLastWitness(),n=i?.hash,r=this.engine.create_witness(t,n),a=`witness-${++this.witnessCounter}-${Date.now()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}verifyWitness(e,t){this.ensureInitialized();let i=this.serializeDecision(e),n=this.engine.verify_witness(i,t);return this.logger.debug("Verified witness",{decisionId:e.id,hash:t,isValid:n}),n}verifyChain(e){if(this.ensureInitialized(),e.length===0)return!0;let t=e.map(n=>({hash:n.hash,previousHash:n.previousWitnessId?this.witnesses.get(n.previousWitnessId)?.hash:void 0,position:n.chainPosition,timestamp:n.timestamp.getTime()})),i=this.engine.verify_chain(t);return this.logger.info("Verified witness chain",{chainLength:e.length,isValid:i}),i}replayFromWitness(e){let t=Date.now(),i=this.witnesses.get(e);if(!i)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Witness not found: ${e}`],durationMs:Date.now()-t};let n=this.decisions.get(i.decisionId);if(!n)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Decision not found: ${i.decisionId}`],durationMs:Date.now()-t};let r=this.verifyWitness(n,i.hash),a=Date.now()-t,o={success:!0,decision:n,matchesOriginal:r,differences:r?void 0:["Hash mismatch detected"],durationMs:a};return this.logger.info("Replayed from witness",{witnessId:e,decisionId:n.id,matchesOriginal:r,durationMs:a}),o}getChainLength(){return this.ensureInitialized(),this.engine.get_chain_length()}getWitnessChain(){return Array.from(this.witnesses.values()).sort((e,t)=>e.chainPosition-t.chainPosition)}getWitness(e){return this.witnesses.get(e)}getLastWitness(){let e=this.getWitnessChain();return e[e.length-1]}serializeDecision(e){let t=JSON.stringify({id:e.id,type:e.type,inputs:e.inputs,output:e.output,agents:e.agents,timestamp:e.timestamp.toISOString(),reasoning:e.reasoning});return new TextEncoder().encode(t)}createEmptyDecision(){return{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date}}dispose(){this.witnesses.clear(),this.decisions.clear(),this.witnessCounter=0,this.engine=null,this.initialized=!1,this.logger.info("WitnessAdapter disposed")}};var I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new f("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",A(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let o of e)this.cohomologyAdapter.addNode(o);this.buildEdgesFromNodes(e);let i=this.cohomologyAdapter.computeEnergy(),n=this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold),r=this.computeLane(i),a=Date.now()-t;return this.updateStats(i,a,n.length,r,!1),{energy:i,isCoherent:i<this.config.coherenceThreshold,lane:r,contradictions:n,recommendations:this.generateRecommendations(i,r,n),durationMs:a,usedFallback:!1}}checkCoherenceWithFallback(e,t){this.stats.fallbackCount++;let i=0,n=0,r=[];for(let s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].id,e[l].id],severity:c>2?"critical":"high",description:`High distance (${c.toFixed(2)}) between nodes`,confidence:Math.min(1,c/2)})}let a=n>0?i/n:0,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,r),durationMs:d,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+d.successRate,0)/Math.max(e.agents.length,1),r=0;r+=(1-i)*.3,r+=(1-n)*.3,r+=e.errorRate*.2,r+=e.utilization>.9?.2:e.utilization*.1;let a=e.agents.filter(o=>o.health<.5||o.successRate<.5).map(o=>o.agentId);return{risk:Math.min(1,r),fiedlerValue:i*n,collapseImminent:r>.7,weakVertices:a,recommendations:r>.5?["System health degraded. Consider spawning additional agents."]:["System health is acceptable."],durationMs:Date.now()-t,usedFallback:!0}}async verifyCausality(e,t,i){return this.ensureInitialized(),this.causalAdapter?.isInitialized()?this.causalAdapter.verifyCausality(e,t,i):this.verifyCausalityWithFallback(e,t,i)}verifyCausalityWithFallback(e,t,i){let n=Date.now(),r=this.computeCorrelation(i.causeValues,i.effectValues),a=Math.abs(r);return{isCausal:a>.5,effectStrength:a,relationshipType:a<.2?"none":a>.5?"causal":"spurious",confidence:Math.min(.7,i.sampleSize/100),confounders:[],explanation:`Correlation-based analysis: r=${r.toFixed(3)}. Note: Correlation does not imply causation. This is a fallback analysis without full causal inference.`,durationMs:Date.now()-n,usedFallback:!0}}async verifyTypes(e){return this.ensureInitialized(),this.categoryAdapter?.isInitialized()?this.categoryAdapter.verifyPipeline(e):this.verifyTypesWithFallback(e)}verifyTypesWithFallback(e){let t=Date.now(),i=[],n=e.inputType;for(let r of e.elements)r.inputType!==n&&n!=="any"&&i.push({location:r.name,expected:n,actual:r.inputType,severity:"high"}),n=r.outputType;return n!==e.outputType&&n!=="any"&&i.push({location:"pipeline output",expected:e.outputType,actual:n,severity:"critical"}),{isValid:i.length===0,mismatches:i,warnings:["Using fallback type verification. Full categorical analysis unavailable."],durationMs:Date.now()-t,usedFallback:!0}}async createWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.createWitness(e):{witnessId:`witness-fallback-${Date.now()}`,decisionId:e.id,hash:this.simpleHash(JSON.stringify(e)),chainPosition:0,timestamp:new Date}}async replayFromWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.replayFromWitness(e):{success:!1,decision:{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date},matchesOriginal:!1,differences:["Replay not available in fallback mode"],durationMs:0}}async checkSwarmCoherence(e){this.ensureInitialized();let t=[];return e.forEach((i,n)=>{let r=this.agentHealthToEmbedding(i);t.push({id:n,embedding:r,weight:i.health,metadata:{agentType:i.agentType,successRate:i.successRate,errorCount:i.errorCount}})}),this.checkCoherence(t)}async verifyConsensus(e){this.ensureInitialized();let t=Date.now();if(e.length<2)return{isValid:e.length===1,confidence:e.length===1?e[0].confidence:0,isFalseConsensus:!1,fiedlerValue:e.length===1?1:0,collapseRisk:0,recommendation:e.length===0?"No votes to analyze":"Single vote - consensus trivially achieved",durationMs:Date.now()-t,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{this.spectralAdapter.clear();for(let a of e)this.spectralAdapter.addNode(a.agentId);let i=0;for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].confidence)),i++);if(i===0)return this.logger.debug("No agreement edges, using fallback consensus"),this.verifyConsensusWithFallback(e,t);let n=this.spectralAdapter.predictCollapseRisk(),r=this.spectralAdapter.computeFiedlerValue();return{isValid:n<.3&&r>.1,confidence:1-n,isFalseConsensus:r<.05,fiedlerValue:r,collapseRisk:n,recommendation:n>.3?"Spawn independent reviewer":"Consensus verified",durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+d.confidence,0)/e.length;return{isValid:r>.6,confidence:r*a,isFalseConsensus:i.size===1&&e.length>2,fiedlerValue:r,collapseRisk:1-r,recommendation:r<.6?"No clear majority. Consider spawning additional agents.":r===1&&i.size===1?"Unanimous consensus may indicate false consensus. Consider adding diversity.":"Majority consensus achieved.",durationMs:Date.now()-t,usedFallback:!0}}async filterCoherent(e,t){if(this.ensureInitialized(),e.length===0)return[];if(e.length===1)return e;let i=e.map(a=>({id:a.id,embedding:a.embedding})),n=await this.checkCoherence(i);if(n.isCoherent)return e;let r=new Set;for(let a of n.contradictions)a.nodeIds.forEach(o=>r.add(o));return e.filter(a=>!r.has(a.id))}getStats(){return{...this.stats,averageEnergy:this.stats.totalChecks>0?this.totalEnergySum/this.stats.totalChecks:0,averageDurationMs:this.stats.totalChecks>0?this.totalDurationSum/this.stats.totalChecks:0,lastCheckAt:this.stats.lastCheckAt}}async dispose(){this.cohomologyAdapter?.dispose(),this.spectralAdapter?.dispose(),this.causalAdapter?.dispose(),this.categoryAdapter?.dispose(),this.homotopyAdapter?.dispose(),this.witnessAdapter?.dispose(),this.cohomologyAdapter=null,this.spectralAdapter=null,this.causalAdapter=null,this.categoryAdapter=null,this.homotopyAdapter=null,this.witnessAdapter=null,this.initialized=!1,this.logger.info("CoherenceService disposed")}computeLane(e){let{laneConfig:t}=this.config;return e<t.reflexThreshold?"reflex":e<t.retrievalThreshold?"retrieval":e<t.heavyThreshold?"heavy":"human"}updateStats(e,t,i,n,r){this.stats.totalChecks++,this.totalEnergySum+=e,this.totalDurationSum+=t,this.stats.totalContradictions+=i,this.stats.laneDistribution[n]++,this.stats.lastCheckAt=new Date,e<this.config.coherenceThreshold?this.stats.coherentCount++:this.stats.incoherentCount++,r&&this.stats.fallbackCount++}generateRecommendations(e,t,i){let n=[];if(t==="reflex"?n.push("Low energy detected. Safe to proceed with immediate execution."):t==="retrieval"?n.push("Moderate energy detected. Consider fetching additional context before proceeding."):t==="heavy"?n.push("High energy detected. Deep analysis recommended before proceeding."):n.push("Critical energy level. Escalate to human review (Queen agent)."),i.length>0){let r=i.filter(a=>a.severity==="critical");r.length>0&&n.push(`Found ${r.length} critical contradiction(s) that must be resolved.`)}return n}agentHealthToEmbedding(e){let t=e.beliefs??[];return[e.health,e.successRate,Math.min(1,e.errorCount/10),this.agentTypeToNumber(e.agentType),t.length/10,...t[0]?.embedding.slice(0,5)||[0,0,0,0,0],...t[1]?.embedding.slice(0,5)||[0,0,0,0,0],...t[2]?.embedding.slice(0,5)||[0,0,0,0,0]]}agentTypeToNumber(e){let t=["coordinator","specialist","analyzer","generator","validator","tester","reviewer","optimizer"],i=t.indexOf(e);return i>=0?i/t.length:.5}euclideanDistance(e,t){if(e.length!==t.length)return 1/0;let i=0;for(let n=0;n<e.length;n++)i+=(e[n]-t[n])**2;return Math.sqrt(i)}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}computeCorrelation(e,t){if(e.length!==t.length||e.length<2)return 0;let i=e.length,n=e.reduce((l,c)=>l+c,0)/i,r=t.reduce((l,c)=>l+c,0)/i,a=0,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}simpleHash(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return(t>>>0).toString(16).padStart(8,"0")}};async function Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=class{state="unloaded";wasmModule=null;engines=null;loadPromise=null;lastError=null;config;version="";fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0};retryTimer=null;degradedModeStartTime=null;eventListeners;constructor(e={}){this.config={...z,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=A(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(i))return!0;return!1}catch{return!1}}async load(){if(await this.getEngines(),!this.wasmModule)throw new h("WASM module failed to load");return this.wasmModule}getModule(){if(!this.wasmModule)throw new h("WASM module is not loaded. Call load() first.");return this.wasmModule}on(e,t){let i=this.eventListeners.get(e);return i&&i.add(t),()=>{i?.delete(t)}}off(e,t){let i=this.eventListeners.get(e);i&&i.delete(t)}reset(){if(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.engines)try{this.engines.cohomology.free(),this.engines.spectral.free(),this.engines.causal.free(),this.engines.category.free(),this.engines.hott.free(),this.engines.quantum.free()}catch(e){console.debug("[WASMLoader] Cleanup error during unload:",e instanceof Error?e.message:e)}this.state="unloaded",this.wasmModule=null,this.engines=null,this.loadPromise=null,this.lastError=null,this.version="",this.fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0},this.degradedModeStartTime=null}async forceRetry(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),(this.state==="failed"||this.state==="degraded")&&(this.state="unloaded",this.fallbackState.mode="recovering");try{return await this.getEngines(),!0}catch{return!1}}async loadWithRetry(){let{maxAttempts:e,baseDelayMs:t,maxDelayMs:i}=this.config,n=new Error("Unknown error");for(let r=1;r<=e;r++)try{let a=performance.now(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-XCX7CNVW.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(a=>a!==null),n=null;for(let a of i)if(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
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.8");process.exit(0)}
2
+ import{a as p,b as A,c as L}from"./chunk-XKKCH24C.js";var R={reflexThreshold:.1,retrievalThreshold:.4,heavyThreshold:.7},M={enabled:!0,laneConfig:R,coherenceThreshold:.1,fallbackEnabled:!0,timeoutMs:5e3,cacheEnabled:!0,cacheTtlMs:300*1e3},m={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},f=class extends Error{constructor(t,i,n){super(t);this.code=i;this.cause=n;this.name="CoherenceError"}code;cause},h=class extends f{constructor(e="WASM module is not loaded",t){super(e,"WASM_NOT_LOADED",t),this.name="WasmNotLoadedError"}};var T=class extends f{constructor(t,i,n){super(t,"WASM_LOAD_FAILED",n);this.attempts=i;this.name="WasmLoadError"}attempts},z={maxAttempts:3,baseDelayMs:100,maxDelayMs:5e3,timeoutMs:1e4};L();function D(u){let e=new Map,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({nodes:Array.from(e.entries()).map(([s,l])=>({id:a(s),label:s,section:Array.from(l.embedding),weight:1})),edges:t.map(s=>({source:a(s.source),target:a(s.target),weight:s.weight}))});return{add_node(s,l){e.set(s,{embedding:l}),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},remove_edge(s,l){let c=t.findIndex(g=>g.source===s&&g.target===l);c>=0&&t.splice(c,1)},sheaf_laplacian_energy(){let s=d();return u.consistencyEnergy(s)},detect_contradictions(s){let l=d(),c=u.detectObstructions(l);return c?c.filter(g=>g.energy>s).map(g=>({node1:o(g.node1),node2:o(g.node2),severity:g.energy,distance:g.energy})):[]},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var y=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Map;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CohomologyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CohomologyAdapter.");let t=await this.wasmLoader.load(),i=new t.CohomologyEngine;this.engine=D(i),this.initialized=!0,this.logger.info("CohomologyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CohomologyAdapter not initialized. Call initialize() first.")}addNode(e){this.ensureInitialized(),this.nodes.set(e.id,e);let t=new Float64Array(e.embedding);this.engine.add_node(e.id,t),this.logger.debug("Added node to cohomology graph",{nodeId:e.id,embeddingDim:e.embedding.length})}addEdge(e){this.ensureInitialized(),this.edges.push(e),this.engine.add_edge(e.source,e.target,e.weight),this.logger.debug("Added edge to cohomology graph",{source:e.source,target:e.target,weight:e.weight})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);let t=[];this.edges.forEach((i,n)=>{(i.source===e||i.target===e)&&t.push(n)}),t.reverse().forEach(i=>this.edges.splice(i,1)),this.logger.debug("Removed node from cohomology graph",{nodeId:e})}removeEdge(e,t){this.ensureInitialized();let i=this.edges.findIndex(n=>n.source===e&&n.target===t);i>=0&&this.edges.splice(i,1),this.engine.remove_edge(e,t),this.logger.debug("Removed edge from cohomology graph",{source:e,target:t})}computeEnergy(){this.ensureInitialized();let e=this.engine.sheaf_laplacian_energy();return this.logger.debug("Computed sheaf Laplacian energy",{energy:e}),e}detectContradictions(e=.1){this.ensureInitialized();let i=this.engine.detect_contradictions(e).map(n=>this.transformContradiction(n));return this.logger.debug("Detected contradictions",{count:i.length,threshold:e}),i}transformContradiction(e){return{nodeIds:[e.node1,e.node2],severity:this.severityFromDistance(e.severity),description:this.generateContradictionDescription(e),confidence:1-e.distance,resolution:this.suggestResolution(e)}}severityFromDistance(e){return e>=.9?"critical":e>=.7?"high":e>=.4?"medium":e>=.2?"low":"info"}generateContradictionDescription(e){let t=this.nodes.get(e.node1),i=this.nodes.get(e.node2);return t?.metadata?.statement&&i?.metadata?.statement?`Contradiction detected between "${t.metadata.statement}" and "${i.metadata.statement}"`:`Contradiction detected between nodes '${e.node1}' and '${e.node2}' with distance ${e.distance.toFixed(3)}`}suggestResolution(e){return e.severity>=.9?"Critical contradiction requires manual review. Consider removing one of the conflicting beliefs.":e.severity>=.7?"High-severity contradiction. Recommend gathering additional evidence to determine which belief is correct.":e.severity>=.4?"Moderate contradiction. Consider adding context or constraints to differentiate the beliefs.":"Low-severity contradiction. May be resolved with additional context or can be safely ignored."}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared cohomology graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("CohomologyAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}getNode(e){return this.nodes.get(e)}};L();function N(u){let e=new Set,t=[],i=new Map,n=new Map,r=0,a=s=>{let l=i.get(s);return l===void 0&&(l=r++,i.set(s,l),n.set(l,s)),l},o=s=>n.get(s)??`unknown-${s}`,d=()=>({n:e.size,edges:t.map(s=>[a(s.source),a(s.target),s.weight])});return{add_node(s){e.add(s),a(s)},add_edge(s,l,c){t.push({source:s,target:l,weight:c}),a(s),a(l)},remove_node(s){e.delete(s);for(let l=t.length-1;l>=0;l--)(t[l].source===s||t[l].target===s)&&t.splice(l,1)},compute_fiedler_value(){if(e.size<2||t.length===0)return 0;try{let s=d(),l=u.algebraicConnectivity(s);return Number.isFinite(l)&&l>=0?l:0}catch(s){return console.warn("[SpectralAdapter] algebraicConnectivity failed:",s),0}},predict_collapse_risk(){if(e.size<2)return 0;if(t.length===0)return 1;try{let s=d(),l=u.algebraicConnectivity(s),c=Number.isFinite(l)&&l>=0?l:0;return Math.max(0,Math.min(1,1-c))}catch(s){return console.warn("[SpectralAdapter] predict_collapse_risk failed:",s),.8}},get_weak_vertices(s){if(e.size===0)return[];if(t.length===0)return Array.from(e).slice(0,s);try{let l=d(),c=u.predictMinCut(l);return c?.vertices?c.vertices.slice(0,s).map(g=>o(g)):Array.from(e).slice(0,s)}catch(l){return console.warn("[SpectralAdapter] predictMinCut failed:",l),Array.from(e).slice(0,s)}},clear(){e.clear(),t.length=0,i.clear(),n.clear(),r=0}}}var v=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;nodes=new Set;edges=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing SpectralAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize SpectralAdapter.");let t=await this.wasmLoader.load(),i=new t.SpectralEngine;this.engine=N(i),this.initialized=!0,this.logger.info("SpectralAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("SpectralAdapter not initialized. Call initialize() first.")}addNode(e){if(this.ensureInitialized(),this.nodes.has(e)){this.logger.debug("Node already exists",{nodeId:e});return}this.nodes.add(e),this.engine.add_node(e),this.logger.debug("Added node to spectral graph",{nodeId:e})}addEdge(e,t,i){this.ensureInitialized(),this.nodes.has(e)||this.addNode(e),this.nodes.has(t)||this.addNode(t),this.edges.push({source:e,target:t,weight:i}),this.engine.add_edge(e,t,i),this.logger.debug("Added edge to spectral graph",{source:e,target:t,weight:i})}removeNode(e){this.ensureInitialized(),this.nodes.delete(e),this.engine.remove_node(e);for(let t=this.edges.length-1;t>=0;t--){let i=this.edges[t];(i.source===e||i.target===e)&&this.edges.splice(t,1)}this.logger.debug("Removed node from spectral graph",{nodeId:e})}computeFiedlerValue(){if(this.ensureInitialized(),this.nodes.size<2||this.edges.length===0)return 0;try{let e=this.engine.compute_fiedler_value();return this.logger.debug("Computed Fiedler value",{fiedlerValue:e}),e}catch(e){return this.logger.warn("Failed to compute Fiedler value",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),0}}predictCollapseRisk(){if(this.ensureInitialized(),this.nodes.size<2)return 0;if(this.edges.length===0)return 1;try{let e=this.engine.predict_collapse_risk();return this.logger.debug("Predicted collapse risk",{risk:e}),e}catch(e){return this.logger.warn("Failed to predict collapse risk",{error:p(e),nodeCount:this.nodes.size,edgeCount:this.edges.length}),.8}}getWeakVertices(e){if(this.ensureInitialized(),this.nodes.size===0)return[];if(this.edges.length===0)return Array.from(this.nodes).slice(0,e);let t=Math.min(e,this.nodes.size);try{let i=this.engine.get_weak_vertices(t);return this.logger.debug("Retrieved weak vertices",{requested:e,returned:i.length}),i}catch(i){return this.logger.warn("Failed to get weak vertices",{error:p(i),nodeCount:this.nodes.size,edgeCount:this.edges.length}),Array.from(this.nodes).slice(0,e)}}analyzeSwarmState(e){let t=Date.now();this.clear();for(let d of e.agents)this.addNode(d.agentId);this.buildEdgesFromAgents(e.agents);let i=this.predictCollapseRisk(),n=this.computeFiedlerValue(),r=this.getWeakVertices(5),a=Date.now()-t,o={risk:i,fiedlerValue:n,collapseImminent:i>.7,weakVertices:r,recommendations:this.generateRecommendations(i,n,r),durationMs:a,usedFallback:!1};return this.logger.info("Analyzed swarm state",{agentCount:e.agents.length,risk:i,fiedlerValue:n,durationMs:a}),o}buildEdgesFromAgents(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.computeAgentSimilarity(e[t],e[i]);n>.3&&this.addEdge(e[t].agentId,e[i].agentId,n)}}computeAgentSimilarity(e,t){let i=1-Math.abs(e.health-t.health),n=1-Math.abs(e.successRate-t.successRate),r=e.agentType===t.agentType?.2:0,a=0,o=e.beliefs??[],d=t.beliefs??[];return o.length>0&&d.length>0&&(a=this.computeBeliefOverlap(o,d)),i*.3+n*.3+r+a*.2}computeBeliefOverlap(e,t){if(e.length===0||t.length===0)return 0;let i=0,n=0;for(let r of e)for(let a of t)i+=this.cosineSimilarity(r.embedding,a.embedding),n++;return n>0?i/n:0}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}generateRecommendations(e,t,i){let n=[];return e>.7?(n.push("CRITICAL: Immediate action required to prevent swarm collapse."),n.push("Consider spawning additional coordination agents to strengthen connectivity.")):e>.5&&n.push("WARNING: Elevated collapse risk detected. Monitor closely."),t<.1&&n.push("Network connectivity is weak. Consider adding redundant communication channels."),t<.05&&(n.push("ALERT: Near-zero Fiedler value indicates potential false consensus."),n.push("Recommend spawning an independent reviewer to verify decisions.")),i.length>0&&n.push(`At-risk agents: ${i.join(", ")}. Consider reassigning critical tasks.`),n.length===0&&n.push("Swarm health is good. No immediate action required."),n}clear(){this.ensureInitialized(),this.nodes.clear(),this.edges.length=0,this.engine.clear(),this.logger.debug("Cleared spectral graph")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.nodes.clear(),this.edges.length=0,this.initialized=!1,this.logger.info("SpectralAdapter disposed")}getNodeCount(){return this.nodes.size}getEdgeCount(){return this.edges.length}};function O(u){let e=null,t=null,i=new Map,n=()=>({cause:e?Array.from(e):[],effect:t?Array.from(t):[],confounders:Object.fromEntries(Array.from(i.entries()).map(([r,a])=>[r,Array.from(a)]))});return{set_data(r,a){e=r,t=a},add_confounder(r,a){i.set(r,a)},compute_causal_effect(){let r=n();return u.computeCausalEffect(r,"cause","effect",1)?.effect??0},detect_spurious_correlation(){let r=n();return(u.findConfounders(r,"cause","effect")?.length??0)>0},get_confounders(){let r=n();return u.findConfounders(r,"cause","effect")??Array.from(i.keys())},clear(){e=null,t=null,i.clear()}}}var b=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;currentCause="";currentEffect="";async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CausalAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CausalAdapter.");let t=await this.wasmLoader.load(),i=new t.CausalEngine;this.engine=O(i),this.initialized=!0,this.logger.info("CausalAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CausalAdapter not initialized. Call initialize() first.")}verifyCausality(e,t,i){this.ensureInitialized();let n=Date.now();if(this.clear(),this.currentCause=e,this.currentEffect=t,this.setData(i.causeValues,i.effectValues),i.confounders)for(let[g,F]of Object.entries(i.confounders))this.addConfounder(g,F);let r=this.computeCausalEffect(),a=this.detectSpuriousCorrelation(),o=this.getConfounders(),d=this.determineRelationshipType(r,a,o.length>0),s=this.computeConfidence(i.sampleSize,r,a),l=Date.now()-n,c={isCausal:d==="causal",effectStrength:r,relationshipType:d,confidence:s,confounders:o,explanation:this.generateExplanation(e,t,d,r,o),durationMs:l,usedFallback:!1};return this.logger.info("Verified causality",{cause:e,effect:t,isCausal:c.isCausal,relationshipType:d,effectStrength:r,durationMs:l}),c}setData(e,t){if(this.ensureInitialized(),e.length!==t.length)throw new Error(`Cause and effect arrays must have same length. Got ${e.length} and ${t.length}.`);let i=new Float64Array(e),n=new Float64Array(t);this.engine.set_data(i,n),this.logger.debug("Set causal data",{sampleSize:e.length})}addConfounder(e,t){this.ensureInitialized();let i=new Float64Array(t);this.engine.add_confounder(e,i),this.logger.debug("Added confounder",{name:e,valueCount:t.length})}computeCausalEffect(){this.ensureInitialized();let e=this.engine.compute_causal_effect();return this.logger.debug("Computed causal effect",{effect:e}),e}detectSpuriousCorrelation(){this.ensureInitialized();let e=this.engine.detect_spurious_correlation();return this.logger.debug("Detected spurious correlation",{isSpurious:e}),e}getConfounders(){return this.ensureInitialized(),this.engine.get_confounders()}determineRelationshipType(e,t,i){return e<.1?"none":t?"spurious":i?"confounded":e<0?"reverse":"causal"}computeConfidence(e,t,i){let n=Math.min(1,e/100)*.5;return n+=Math.abs(t)*.3,i&&(n+=.15),Math.min(.95,n)}generateExplanation(e,t,i,n,r){switch(i){case"causal":return`Analysis indicates a true causal relationship between '${e}' and '${t}'. Effect strength: ${(n*100).toFixed(1)}%. Changes in '${e}' are likely to cause changes in '${t}'.`;case"spurious":return`The correlation between '${e}' and '${t}' appears to be spurious. No true causal mechanism detected. This may be coincidental or due to a hidden common cause.`;case"reverse":return`Analysis suggests reverse causation: '${t}' may cause '${e}', not the other way around. Consider swapping the direction of your hypothesis.`;case"confounded":return`The relationship between '${e}' and '${t}' is confounded by: ${r.join(", ")}. These variables may explain the observed correlation without direct causation.`;case"none":return`No significant relationship detected between '${e}' and '${t}'. Effect strength is below the detection threshold.`;default:return`Analysis complete for '${e}' -> '${t}'.`}}clear(){this.ensureInitialized(),this.engine.clear(),this.currentCause="",this.currentEffect="",this.logger.debug("Cleared causal engine state")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.initialized=!1,this.logger.info("CausalAdapter disposed")}};function H(u){let e=new Map,t=[],i=()=>({objects:Array.from(e.entries()).map(([n,r])=>({name:n,schema:r})),morphisms:t.map(n=>({source:n.source,target:n.target,name:n.name}))});return{add_type(n,r){e.set(n,r)},add_morphism(n,r,a){t.push({source:n,target:r,name:a})},verify_composition(n){if(n.length<2)return!0;for(let a=0;a<n.length-1;a++){let o=n[a],d=n[a+1];if(!t.some(l=>l.source===o&&l.target===d))return!1}let r=i();return u.verifyCategoryLaws(r)},check_type_consistency(){let n=[];for(let r of t)e.has(r.source)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.source}'`}),e.has(r.target)||n.push({location:r.name,expected:"defined type",actual:`undefined type '${r.target}'`});return n},clear(){e.clear(),t.length=0}}}var C=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;types=new Map;morphisms=[];async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing CategoryAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize CategoryAdapter.");let t=await this.wasmLoader.load(),i=new t.CategoryEngine;this.engine=H(i),this.initialized=!0,this.logger.info("CategoryAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("CategoryAdapter not initialized. Call initialize() first.")}addType(e,t){this.ensureInitialized(),this.types.set(e,t),this.engine.add_type(e,t),this.logger.debug("Added type to category",{name:e})}addMorphism(e,t,i){this.ensureInitialized(),this.morphisms.push({source:e,target:t,name:i}),this.engine.add_morphism(e,t,i),this.logger.debug("Added morphism to category",{source:e,target:t,name:i})}verifyComposition(e){if(this.ensureInitialized(),e.length<2)return!0;let t=this.engine.verify_composition(e);return this.logger.debug("Verified composition",{path:e,isValid:t}),t}checkTypeConsistency(){this.ensureInitialized();let t=this.engine.check_type_consistency().map(i=>this.transformMismatch(i));return this.logger.debug("Checked type consistency",{mismatchCount:t.length}),t}verifyPipeline(e){let t=Date.now();this.clear(),this.addType(e.inputType,this.inferSchema(e.inputType)),this.addType(e.outputType,this.inferSchema(e.outputType));for(let s of e.elements)this.addType(s.inputType,this.inferSchema(s.inputType)),this.addType(s.outputType,this.inferSchema(s.outputType));for(let s of e.elements)this.addMorphism(s.inputType,s.outputType,s.name);let i=this.buildCompositionPath(e),n=this.verifyComposition(i),r=this.checkTypeConsistency(),a=this.generateWarnings(e,n,r),o=Date.now()-t,d={isValid:n&&r.length===0,mismatches:r,warnings:a,durationMs:o,usedFallback:!1};return this.logger.info("Verified pipeline",{pipelineId:e.id,isValid:d.isValid,mismatchCount:r.length,warningCount:a.length,durationMs:o}),d}buildCompositionPath(e){let t=[e.inputType];for(let i of e.elements)i.inputType!==t[t.length-1]&&t.push(i.inputType),t.push(i.outputType);return t[t.length-1]!==e.outputType&&t.push(e.outputType),t}inferSchema(e){return e.endsWith("[]")?`{ items: ${e.slice(0,-2)}[] }`:e.includes("|")?`{ union: [${e.split("|").map(t=>`"${t.trim()}"`).join(", ")}] }`:`{ type: "${e}" }`}transformMismatch(e){return{location:e.location,expected:e.expected,actual:e.actual,severity:this.determineMismatchSeverity(e)}}determineMismatchSeverity(e){return e.expected==="never"||e.actual==="never"?"critical":e.actual==="any"||e.actual==="unknown"?"high":e.expected.includes(e.actual)||e.actual.includes(e.expected)?"medium":"low"}generateWarnings(e,t,i){let n=[];t||n.push(`Pipeline '${e.id}' has an invalid composition chain. Types do not connect properly from input to output.`);for(let a of e.elements)(a.inputType==="any"||a.outputType==="any")&&n.push(`Element '${a.name}' uses 'any' type, which bypasses type safety.`);for(let a of e.elements)(a.inputType.includes("<T>")||a.outputType.includes("<T>"))&&n.push(`Element '${a.name}' has unconstrained generic types.`);let r=i.filter(a=>a.severity==="critical");return r.length>0&&n.push(`Found ${r.length} critical type mismatch(es) that will cause runtime errors.`),n}clear(){this.ensureInitialized(),this.types.clear(),this.morphisms.length=0,this.engine.clear(),this.logger.debug("Cleared category")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.types.clear(),this.morphisms.length=0,this.initialized=!1,this.logger.info("CategoryAdapter disposed")}getTypeCount(){return this.types.size}getMorphismCount(){return this.morphisms.length}};function V(u){let e=new Map,t=new Map;return{add_proposition(i,n){e.set(i,{formula:n,proven:!1})},add_proof(i,n){let r=e.get(i);if(!r)return!1;let a={id:i,proof:n},o={formula:r.formula};return u.typeCheck(a,o)?.valid?(r.proven=!0,t.set(i,n),!0):!1},verify_path_equivalence(i,n){let r={steps:i},a={steps:n};return u.checkTypeEquivalence(r,a)},get_unproven_propositions(){let i=[];return e.forEach((n,r)=>{n.proven||i.push(r)}),i},clear(){e.clear(),t.clear()}}}var w=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;propositions=new Map;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing HomotopyAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize HomotopyAdapter.");let t=await this.wasmLoader.load(),i=new t.HoTTEngine;this.engine=V(i),this.initialized=!0,this.logger.info("HomotopyAdapter initialized successfully")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("HomotopyAdapter not initialized. Call initialize() first.")}addProposition(e,t){this.ensureInitialized();let i={id:e,formula:t,proven:!1};this.propositions.set(e,i),this.engine.add_proposition(e,t),this.logger.debug("Added proposition",{id:e,formula:t})}addProof(e,t){this.ensureInitialized();let i=this.propositions.get(e);if(!i)return this.logger.warn("Proposition not found",{propositionId:e}),!1;let n=this.engine.add_proof(e,t);return n?(i.proven=!0,this.logger.info("Proposition proven",{propositionId:e})):this.logger.warn("Proof rejected",{propositionId:e}),n}verifyPathEquivalence(e,t){this.ensureInitialized();let i=this.engine.verify_path_equivalence(e,t),n=this.generateEquivalenceExplanation(e,t,i),r={equivalent:i,path1:e,path2:t,explanation:n};return this.logger.debug("Verified path equivalence",{path1Length:e.length,path2Length:t.length,equivalent:i}),r}generateEquivalenceExplanation(e,t,i){if(i)return e.length===t.length?"The execution paths are homotopically equivalent. Both paths traverse the same abstract structure and will produce equivalent results.":`The execution paths are equivalent despite different lengths. The ${e.length>t.length?"first":"second"} path contains redundant steps that can be contracted without changing the result (homotopy contraction).`;{let n=0,r=Math.min(e.length,t.length);for(;n<r&&e[n]===t[n];)n++;return n===0?`The execution paths diverge immediately. Path 1 starts with '${e[0]}' while Path 2 starts with '${t[0]}'. These lead to fundamentally different computation spaces.`:`The execution paths diverge at step ${n+1}. After '${e[n-1]}', Path 1 proceeds to '${e[n]}' while Path 2 proceeds to '${t[n]}'. No homotopy exists between these paths.`}}getUnprovenPropositions(){return this.ensureInitialized(),this.engine.get_unproven_propositions()}getVerificationStatus(){let e=this.propositions.size,t=Array.from(this.propositions.values()).filter(n=>n.proven).length,i=this.getUnprovenPropositions();return{totalPropositions:e,provenCount:t,unprovenIds:i,verificationPercentage:e>0?t/e*100:100}}getProposition(e){return this.propositions.get(e)}clear(){this.ensureInitialized(),this.propositions.clear(),this.engine.clear(),this.logger.debug("Cleared homotopy engine")}dispose(){this.engine&&(this.engine.clear(),this.engine=null),this.propositions.clear(),this.initialized=!1,this.logger.info("HomotopyAdapter disposed")}getPropositionCount(){return this.propositions.size}};import{createHash as $}from"crypto";var E=class{constructor(e,t=m){this.wasmLoader=e;this.logger=t}wasmLoader;logger;engine=null;initialized=!1;witnesses=new Map;decisions=new Map;witnessCounter=0;async initialize(){if(this.initialized)return;if(this.logger.debug("Initializing WitnessAdapter"),!await this.wasmLoader.isAvailable())throw new h("WASM module is not available. Cannot initialize WitnessAdapter.");let t=await this.wasmLoader.load();this.engine=this.createWitnessEngine(t),this.initialized=!0,this.logger.info("WitnessAdapter initialized successfully")}createWitnessEngine(e){return this.createFallbackEngine()}createFallbackEngine(){let e=[];return{create_witness:(t,i)=>{let r={hash:this.computeHash(t,i),previousHash:i,position:e.length,timestamp:Date.now()};return e.push(r),r},verify_witness:(t,i)=>{let n=e.find(a=>a.hash===i);return this.computeHash(t,n?.previousHash)===i},verify_chain:t=>{if(t.length===0)return!0;if(t[0].previousHash!==void 0)return!1;for(let i=1;i<t.length;i++)if(t[i].previousHash!==t[i-1].hash)return!1;return!0},get_chain_length:()=>e.length}}computeHash(e,t){let i=$("sha256");return i.update(e),t&&i.update(t,"utf-8"),i.digest("hex")}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized||!this.engine)throw new h("WitnessAdapter not initialized. Call initialize() first.")}createWitness(e){this.ensureInitialized();let t=this.serializeDecision(e),i=this.getLastWitness(),n=i?.hash,r=this.engine.create_witness(t,n),a=`witness-${++this.witnessCounter}-${Date.now()}`,o={witnessId:a,decisionId:e.id,hash:r.hash,previousWitnessId:i?.witnessId,chainPosition:r.position,timestamp:new Date(r.timestamp)};return this.witnesses.set(a,o),this.decisions.set(e.id,e),this.logger.info("Created witness",{witnessId:a,decisionId:e.id,chainPosition:o.chainPosition}),o}verifyWitness(e,t){this.ensureInitialized();let i=this.serializeDecision(e),n=this.engine.verify_witness(i,t);return this.logger.debug("Verified witness",{decisionId:e.id,hash:t,isValid:n}),n}verifyChain(e){if(this.ensureInitialized(),e.length===0)return!0;let t=e.map(n=>({hash:n.hash,previousHash:n.previousWitnessId?this.witnesses.get(n.previousWitnessId)?.hash:void 0,position:n.chainPosition,timestamp:n.timestamp.getTime()})),i=this.engine.verify_chain(t);return this.logger.info("Verified witness chain",{chainLength:e.length,isValid:i}),i}replayFromWitness(e){let t=Date.now(),i=this.witnesses.get(e);if(!i)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Witness not found: ${e}`],durationMs:Date.now()-t};let n=this.decisions.get(i.decisionId);if(!n)return{success:!1,decision:this.createEmptyDecision(),matchesOriginal:!1,differences:[`Decision not found: ${i.decisionId}`],durationMs:Date.now()-t};let r=this.verifyWitness(n,i.hash),a=Date.now()-t,o={success:!0,decision:n,matchesOriginal:r,differences:r?void 0:["Hash mismatch detected"],durationMs:a};return this.logger.info("Replayed from witness",{witnessId:e,decisionId:n.id,matchesOriginal:r,durationMs:a}),o}getChainLength(){return this.ensureInitialized(),this.engine.get_chain_length()}getWitnessChain(){return Array.from(this.witnesses.values()).sort((e,t)=>e.chainPosition-t.chainPosition)}getWitness(e){return this.witnesses.get(e)}getLastWitness(){let e=this.getWitnessChain();return e[e.length-1]}serializeDecision(e){let t=JSON.stringify({id:e.id,type:e.type,inputs:e.inputs,output:e.output,agents:e.agents,timestamp:e.timestamp.toISOString(),reasoning:e.reasoning});return new TextEncoder().encode(t)}createEmptyDecision(){return{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date}}dispose(){this.witnesses.clear(),this.decisions.clear(),this.witnessCounter=0,this.engine=null,this.initialized=!1,this.logger.info("WitnessAdapter disposed")}};var I=class{constructor(e,t={},i){this.wasmLoader=e;this.config={...M,...t},this.logger=i||m}wasmLoader;config;logger;cohomologyAdapter=null;spectralAdapter=null;causalAdapter=null;categoryAdapter=null;homotopyAdapter=null;witnessAdapter=null;initialized=!1;stats={totalChecks:0,coherentCount:0,incoherentCount:0,averageEnergy:0,averageDurationMs:0,totalContradictions:0,laneDistribution:{reflex:0,retrieval:0,heavy:0,human:0},fallbackCount:0,wasmAvailable:!1};totalEnergySum=0;totalDurationSum=0;async initialize(){if(this.initialized)return;this.logger.info("Initializing CoherenceService");let e=await this.wasmLoader.isAvailable();if(!e&&!this.config.fallbackEnabled)throw new h("WASM module is not available and fallback is disabled. Enable fallbackEnabled in config to use TypeScript fallback.");if(this.stats.wasmAvailable=e,e)try{this.cohomologyAdapter=new y(this.wasmLoader,this.logger),this.spectralAdapter=new v(this.wasmLoader,this.logger),this.causalAdapter=new b(this.wasmLoader,this.logger),this.categoryAdapter=new C(this.wasmLoader,this.logger),this.homotopyAdapter=new w(this.wasmLoader,this.logger),this.witnessAdapter=new E(this.wasmLoader,this.logger),await Promise.all([this.cohomologyAdapter.initialize(),this.spectralAdapter.initialize(),this.causalAdapter.initialize(),this.categoryAdapter.initialize(),this.homotopyAdapter.initialize(),this.witnessAdapter.initialize()]),this.logger.info("All coherence engine adapters initialized")}catch(t){if(!this.config.fallbackEnabled)throw t;this.logger.warn("WASM initialization failed, using fallback",{error:t instanceof Error?t.message:"Unknown error"}),this.stats.wasmAvailable=!1}else this.logger.info("WASM not available, using TypeScript fallback");this.initialized=!0,this.logger.info("CoherenceService initialized",{wasmAvailable:this.stats.wasmAvailable,fallbackEnabled:this.config.fallbackEnabled})}isInitialized(){return this.initialized}ensureInitialized(){if(!this.initialized)throw new f("CoherenceService not initialized. Call initialize() first.","NOT_INITIALIZED")}async checkCoherence(e){this.ensureInitialized();let t=Date.now();try{return this.cohomologyAdapter?.isInitialized()?await this.checkCoherenceWithWasm(e,t):this.checkCoherenceWithFallback(e,t)}catch(i){return this.logger.error("Coherence check failed",A(i)),{energy:1,isCoherent:!1,lane:"human",contradictions:[],recommendations:["Coherence check failed. Manual review recommended."],durationMs:Date.now()-t,usedFallback:!0}}}async checkCoherenceWithWasm(e,t){this.cohomologyAdapter.clear();for(let o of e)this.cohomologyAdapter.addNode(o);this.buildEdgesFromNodes(e);let i=this.cohomologyAdapter.computeEnergy(),n=this.cohomologyAdapter.detectContradictions(this.config.coherenceThreshold),r=this.computeLane(i),a=Date.now()-t;return this.updateStats(i,a,n.length,r,!1),{energy:i,isCoherent:i<this.config.coherenceThreshold,lane:r,contradictions:n,recommendations:this.generateRecommendations(i,r,n),durationMs:a,usedFallback:!1}}checkCoherenceWithFallback(e,t){this.stats.fallbackCount++;let i=0,n=0,r=[];for(let s=0;s<e.length;s++)for(let l=s+1;l<e.length;l++){let c=this.euclideanDistance(e[s].embedding,e[l].embedding);i+=c,n++,c>1.5&&r.push({nodeIds:[e[s].id,e[l].id],severity:c>2?"critical":"high",description:`High distance (${c.toFixed(2)}) between nodes`,confidence:Math.min(1,c/2)})}let a=n>0?i/n:0,o=this.computeLane(a),d=Date.now()-t;return this.updateStats(a,d,r.length,o,!0),{energy:a,isCoherent:a<this.config.coherenceThreshold,lane:o,contradictions:r,recommendations:this.generateRecommendations(a,o,r),durationMs:d,usedFallback:!0}}buildEdgesFromNodes(e){for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++){let n=this.cosineSimilarity(e[t].embedding,e[i].embedding);n>.3&&this.cohomologyAdapter.addEdge({source:e[t].id,target:e[i].id,weight:n})}}async detectContradictions(e){this.ensureInitialized();let t=e.map(n=>({id:n.id,embedding:n.embedding,weight:n.confidence,metadata:{statement:n.statement,source:n.source}}));return(await this.checkCoherence(t)).contradictions}async predictCollapse(e){if(this.ensureInitialized(),!e.agents||e.agents.length===0)return{risk:0,fiedlerValue:0,collapseImminent:!1,weakVertices:[],recommendations:["No agents to analyze"],durationMs:0,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{return this.spectralAdapter.analyzeSwarmState(e)}catch(t){return this.logger.warn("Spectral collapse prediction failed, using fallback",{error:p(t),agentCount:e.agents.length}),this.predictCollapseWithFallback(e)}return this.predictCollapseWithFallback(e)}predictCollapseWithFallback(e){let t=Date.now(),i=e.agents.reduce((o,d)=>o+d.health,0)/Math.max(e.agents.length,1),n=e.agents.reduce((o,d)=>o+d.successRate,0)/Math.max(e.agents.length,1),r=0;r+=(1-i)*.3,r+=(1-n)*.3,r+=e.errorRate*.2,r+=e.utilization>.9?.2:e.utilization*.1;let a=e.agents.filter(o=>o.health<.5||o.successRate<.5).map(o=>o.agentId);return{risk:Math.min(1,r),fiedlerValue:i*n,collapseImminent:r>.7,weakVertices:a,recommendations:r>.5?["System health degraded. Consider spawning additional agents."]:["System health is acceptable."],durationMs:Date.now()-t,usedFallback:!0}}async verifyCausality(e,t,i){return this.ensureInitialized(),this.causalAdapter?.isInitialized()?this.causalAdapter.verifyCausality(e,t,i):this.verifyCausalityWithFallback(e,t,i)}verifyCausalityWithFallback(e,t,i){let n=Date.now(),r=this.computeCorrelation(i.causeValues,i.effectValues),a=Math.abs(r);return{isCausal:a>.5,effectStrength:a,relationshipType:a<.2?"none":a>.5?"causal":"spurious",confidence:Math.min(.7,i.sampleSize/100),confounders:[],explanation:`Correlation-based analysis: r=${r.toFixed(3)}. Note: Correlation does not imply causation. This is a fallback analysis without full causal inference.`,durationMs:Date.now()-n,usedFallback:!0}}async verifyTypes(e){return this.ensureInitialized(),this.categoryAdapter?.isInitialized()?this.categoryAdapter.verifyPipeline(e):this.verifyTypesWithFallback(e)}verifyTypesWithFallback(e){let t=Date.now(),i=[],n=e.inputType;for(let r of e.elements)r.inputType!==n&&n!=="any"&&i.push({location:r.name,expected:n,actual:r.inputType,severity:"high"}),n=r.outputType;return n!==e.outputType&&n!=="any"&&i.push({location:"pipeline output",expected:e.outputType,actual:n,severity:"critical"}),{isValid:i.length===0,mismatches:i,warnings:["Using fallback type verification. Full categorical analysis unavailable."],durationMs:Date.now()-t,usedFallback:!0}}async createWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.createWitness(e):{witnessId:`witness-fallback-${Date.now()}`,decisionId:e.id,hash:this.simpleHash(JSON.stringify(e)),chainPosition:0,timestamp:new Date}}async replayFromWitness(e){return this.ensureInitialized(),this.witnessAdapter?.isInitialized()?this.witnessAdapter.replayFromWitness(e):{success:!1,decision:{id:"",type:"routing",inputs:{},output:null,agents:[],timestamp:new Date},matchesOriginal:!1,differences:["Replay not available in fallback mode"],durationMs:0}}async checkSwarmCoherence(e){this.ensureInitialized();let t=[];return e.forEach((i,n)=>{let r=this.agentHealthToEmbedding(i);t.push({id:n,embedding:r,weight:i.health,metadata:{agentType:i.agentType,successRate:i.successRate,errorCount:i.errorCount}})}),this.checkCoherence(t)}async verifyConsensus(e){this.ensureInitialized();let t=Date.now();if(e.length<2)return{isValid:e.length===1,confidence:e.length===1?e[0].confidence:0,isFalseConsensus:!1,fiedlerValue:e.length===1?1:0,collapseRisk:0,recommendation:e.length===0?"No votes to analyze":"Single vote - consensus trivially achieved",durationMs:Date.now()-t,usedFallback:!0};if(this.spectralAdapter?.isInitialized())try{this.spectralAdapter.clear();for(let a of e)this.spectralAdapter.addNode(a.agentId);let i=0;for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++)e[a].verdict===e[o].verdict&&(this.spectralAdapter.addEdge(e[a].agentId,e[o].agentId,Math.min(e[a].confidence,e[o].confidence)),i++);if(i===0)return this.logger.debug("No agreement edges, using fallback consensus"),this.verifyConsensusWithFallback(e,t);let n=this.spectralAdapter.predictCollapseRisk(),r=this.spectralAdapter.computeFiedlerValue();return{isValid:n<.3&&r>.1,confidence:1-n,isFalseConsensus:r<.05,fiedlerValue:r,collapseRisk:n,recommendation:n>.3?"Spawn independent reviewer":"Consensus verified",durationMs:Date.now()-t,usedFallback:!1}}catch(i){return this.logger.warn("Spectral consensus verification failed, using fallback",{error:p(i),voteCount:e.length}),this.verifyConsensusWithFallback(e,t)}return this.verifyConsensusWithFallback(e,t)}verifyConsensusWithFallback(e,t){let i=new Map;for(let o of e){let d=String(o.verdict);i.set(d,(i.get(d)||0)+1)}let n=0;i.forEach(o=>{n=Math.max(n,o)});let r=n/e.length,a=e.reduce((o,d)=>o+d.confidence,0)/e.length;return{isValid:r>.6,confidence:r*a,isFalseConsensus:i.size===1&&e.length>2,fiedlerValue:r,collapseRisk:1-r,recommendation:r<.6?"No clear majority. Consider spawning additional agents.":r===1&&i.size===1?"Unanimous consensus may indicate false consensus. Consider adding diversity.":"Majority consensus achieved.",durationMs:Date.now()-t,usedFallback:!0}}async filterCoherent(e,t){if(this.ensureInitialized(),e.length===0)return[];if(e.length===1)return e;let i=e.map(a=>({id:a.id,embedding:a.embedding})),n=await this.checkCoherence(i);if(n.isCoherent)return e;let r=new Set;for(let a of n.contradictions)a.nodeIds.forEach(o=>r.add(o));return e.filter(a=>!r.has(a.id))}getStats(){return{...this.stats,averageEnergy:this.stats.totalChecks>0?this.totalEnergySum/this.stats.totalChecks:0,averageDurationMs:this.stats.totalChecks>0?this.totalDurationSum/this.stats.totalChecks:0,lastCheckAt:this.stats.lastCheckAt}}async dispose(){this.cohomologyAdapter?.dispose(),this.spectralAdapter?.dispose(),this.causalAdapter?.dispose(),this.categoryAdapter?.dispose(),this.homotopyAdapter?.dispose(),this.witnessAdapter?.dispose(),this.cohomologyAdapter=null,this.spectralAdapter=null,this.causalAdapter=null,this.categoryAdapter=null,this.homotopyAdapter=null,this.witnessAdapter=null,this.initialized=!1,this.logger.info("CoherenceService disposed")}computeLane(e){let{laneConfig:t}=this.config;return e<t.reflexThreshold?"reflex":e<t.retrievalThreshold?"retrieval":e<t.heavyThreshold?"heavy":"human"}updateStats(e,t,i,n,r){this.stats.totalChecks++,this.totalEnergySum+=e,this.totalDurationSum+=t,this.stats.totalContradictions+=i,this.stats.laneDistribution[n]++,this.stats.lastCheckAt=new Date,e<this.config.coherenceThreshold?this.stats.coherentCount++:this.stats.incoherentCount++,r&&this.stats.fallbackCount++}generateRecommendations(e,t,i){let n=[];if(t==="reflex"?n.push("Low energy detected. Safe to proceed with immediate execution."):t==="retrieval"?n.push("Moderate energy detected. Consider fetching additional context before proceeding."):t==="heavy"?n.push("High energy detected. Deep analysis recommended before proceeding."):n.push("Critical energy level. Escalate to human review (Queen agent)."),i.length>0){let r=i.filter(a=>a.severity==="critical");r.length>0&&n.push(`Found ${r.length} critical contradiction(s) that must be resolved.`)}return n}agentHealthToEmbedding(e){let t=e.beliefs??[];return[e.health,e.successRate,Math.min(1,e.errorCount/10),this.agentTypeToNumber(e.agentType),t.length/10,...t[0]?.embedding.slice(0,5)||[0,0,0,0,0],...t[1]?.embedding.slice(0,5)||[0,0,0,0,0],...t[2]?.embedding.slice(0,5)||[0,0,0,0,0]]}agentTypeToNumber(e){let t=["coordinator","specialist","analyzer","generator","validator","tester","reviewer","optimizer"],i=t.indexOf(e);return i>=0?i/t.length:.5}euclideanDistance(e,t){if(e.length!==t.length)return 1/0;let i=0;for(let n=0;n<e.length;n++)i+=(e[n]-t[n])**2;return Math.sqrt(i)}cosineSimilarity(e,t){if(e.length!==t.length||e.length===0)return 0;let i=0,n=0,r=0;for(let o=0;o<e.length;o++)i+=e[o]*t[o],n+=e[o]*e[o],r+=t[o]*t[o];let a=Math.sqrt(n)*Math.sqrt(r);return a===0?0:i/a}computeCorrelation(e,t){if(e.length!==t.length||e.length<2)return 0;let i=e.length,n=e.reduce((l,c)=>l+c,0)/i,r=t.reduce((l,c)=>l+c,0)/i,a=0,o=0,d=0;for(let l=0;l<i;l++){let c=e[l]-n,g=t[l]-r;a+=c*g,o+=c*c,d+=g*g}let s=Math.sqrt(o*d);return s===0?0:a/s}simpleHash(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return(t>>>0).toString(16).padStart(8,"0")}};async function Q(u,e,t){let i=new I(u,e,t);return await i.initialize(),i}L();import{createRequire as _}from"node:module";import{fileURLToPath as K}from"node:url";import{dirname as x,join as S}from"node:path";import{readFileSync as X,existsSync as P}from"node:fs";var W=[1e3,2e3,4e3],k=class{state="unloaded";wasmModule=null;engines=null;loadPromise=null;lastError=null;config;version="";fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0};retryTimer=null;degradedModeStartTime=null;eventListeners;constructor(e={}){this.config={...z,...e},this.eventListeners=new Map,this.eventListeners.set("loaded",new Set),this.eventListeners.set("error",new Set),this.eventListeners.set("retry",new Set),this.eventListeners.set("degraded_mode",new Set),this.eventListeners.set("recovered",new Set)}isLoaded(){return this.state==="loaded"&&this.engines!==null}getState(){return this.state}getVersion(){return this.version}getLastError(){return this.lastError}isInDegradedMode(){return this.state==="degraded"||this.fallbackState.mode==="fallback"}getFallbackState(){return{...this.fallbackState}}getFallbackResult(){return{usedFallback:!0,confidence:.5,retryCount:this.fallbackState.consecutiveFailures,lastError:this.lastError?.message,activatedAt:this.degradedModeStartTime??new Date}}async getEngines(){if(this.state==="loaded"&&this.engines)return this.engines;if(this.state==="loading"&&this.loadPromise)return this.loadPromise;this.state="loading",this.loadPromise=this.loadWithRetry();try{return this.engines=await this.loadPromise,this.state="loaded",(this.fallbackState.mode==="fallback"||this.fallbackState.mode==="recovering")&&this.emitRecoveryEvent(),this.fallbackState.mode="wasm",this.fallbackState.consecutiveFailures=0,this.fallbackState.lastSuccessfulLoad=new Date,this.engines}catch(e){throw this.state="failed",this.lastError=A(e),this.enterDegradedMode(this.lastError),e}finally{this.loadPromise=null}}async getEnginesWithFallback(){if(this.state==="loaded"&&this.engines)return{engines:this.engines,fallback:{usedFallback:!1,confidence:1,retryCount:0}};if(this.state==="degraded")return{engines:null,fallback:this.getFallbackResult()};try{return{engines:await this.getEngines(),fallback:{usedFallback:!1,confidence:1,retryCount:0}}}catch{return{engines:null,fallback:this.getFallbackResult()}}}getEnginesSync(){if(!this.engines)throw new h("WASM module is not loaded. Call getEngines() first.");return this.engines}async isAvailable(){if(this.state==="loaded"&&this.wasmModule)return!0;if(this.state==="failed")return!1;try{let e=_(import.meta.url),t=[(()=>{try{let i=e.resolve("prime-radiant-advanced-wasm");return S(x(i),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(i=>i!==null);for(let i of t)if(P(i))return!0;return!1}catch{return!1}}async load(){if(await this.getEngines(),!this.wasmModule)throw new h("WASM module failed to load");return this.wasmModule}getModule(){if(!this.wasmModule)throw new h("WASM module is not loaded. Call load() first.");return this.wasmModule}on(e,t){let i=this.eventListeners.get(e);return i&&i.add(t),()=>{i?.delete(t)}}off(e,t){let i=this.eventListeners.get(e);i&&i.delete(t)}reset(){if(this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),this.engines)try{this.engines.cohomology.free(),this.engines.spectral.free(),this.engines.causal.free(),this.engines.category.free(),this.engines.hott.free(),this.engines.quantum.free()}catch(e){console.debug("[WASMLoader] Cleanup error during unload:",e instanceof Error?e.message:e)}this.state="unloaded",this.wasmModule=null,this.engines=null,this.loadPromise=null,this.lastError=null,this.version="",this.fallbackState={mode:"wasm",consecutiveFailures:0,totalActivations:0,nextRetryAt:void 0,lastSuccessfulLoad:void 0},this.degradedModeStartTime=null}async forceRetry(){this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null),(this.state==="failed"||this.state==="degraded")&&(this.state="unloaded",this.fallbackState.mode="recovering");try{return await this.getEngines(),!0}catch{return!1}}async loadWithRetry(){let{maxAttempts:e,baseDelayMs:t,maxDelayMs:i}=this.config,n=new Error("Unknown error");for(let r=1;r<=e;r++)try{let a=performance.now(),o=await this.attemptLoad(),d=performance.now()-a;return this.emit("loaded",{version:this.version,loadTimeMs:Math.round(d*100)/100}),o}catch(a){if(n=A(a),this.emit("error",{error:n,fatal:r>=e,attempt:r}),r<e){let o=Math.min(t*Math.pow(2,r-1),i);this.emit("retry",{attempt:r+1,maxAttempts:e,delayMs:o,previousError:n}),await this.sleep(o)}}throw new T(`Failed to load WASM module after ${e} attempts: ${n.message}`,e,n)}async attemptLoad(){let e;try{e=_(import.meta.url)}catch{e=globalThis.require||(await import("module")).createRequire(__filename)}let t;try{t=await import("./prime-radiant-advanced-wasm-4BYJTTZX.js")}catch(r){try{t=e("prime-radiant-advanced-wasm")}catch{throw new Error(`Failed to import prime-radiant-advanced-wasm: ${p(r)}`)}}if(typeof process<"u"&&process.versions!=null&&process.versions.node!=null?await this.initializeForNodeJs(t,e):t.default&&typeof t.default=="function"&&await t.default(),t.initModule&&typeof t.initModule=="function")try{t.initModule()}catch{}return t.getVersion&&typeof t.getVersion=="function"&&(this.version=t.getVersion()),this.wasmModule=t,{cohomology:new t.CohomologyEngine,spectral:new t.SpectralEngine,causal:new t.CausalEngine,category:new t.CategoryEngine,hott:new t.HoTTEngine,quantum:new t.QuantumEngine}}async initializeForNodeJs(e,t){let i=[(()=>{try{let a=t.resolve("prime-radiant-advanced-wasm");return S(x(a),"prime_radiant_advanced_wasm_bg.wasm")}catch{return null}})(),S(x(K(import.meta.url)),"../../../../node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm"),S(process.cwd(),"node_modules/prime-radiant-advanced-wasm/prime_radiant_advanced_wasm_bg.wasm")].filter(a=>a!==null),n=null;for(let a of i)if(P(a)){n=a;break}if(!n)throw new Error(`Could not find WASM binary. Searched paths:
3
3
  ${i.join(`
4
4
  `)}
5
5
  Ensure prime-radiant-advanced-wasm is installed.`);let r=X(n);if(e.initSync&&typeof e.initSync=="function")e.initSync({module:r});else throw new Error("WASM module does not export initSync function")}emit(e,t){let i=this.eventListeners.get(e);if(i){let n=Array.from(i);for(let r=0;r<n.length;r++)try{n[r](t)}catch{}}}sleep(e){return new Promise(t=>setTimeout(t,e))}enterDegradedMode(e){this.state="degraded",this.fallbackState.mode="fallback",this.fallbackState.consecutiveFailures++,this.fallbackState.totalActivations++,this.degradedModeStartTime||(this.degradedModeStartTime=new Date);let t=Math.min(this.fallbackState.consecutiveFailures-1,W.length-1),i=W[t],n=new Date(Date.now()+i);this.fallbackState.nextRetryAt=n,console.warn(`[WasmLoader] WASM load failed, entering degraded mode. Retry ${this.fallbackState.consecutiveFailures}/3 in ${i}ms. Error: ${e.message}`),this.emit("degraded_mode",{reason:"WASM load failed after retries",retryCount:this.fallbackState.consecutiveFailures,lastError:e.message,activatedAt:this.degradedModeStartTime,nextRetryAt:n}),this.fallbackState.consecutiveFailures<W.length&&this.scheduleBackgroundRetry(i)}scheduleBackgroundRetry(e){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.fallbackState.mode="recovering",this.attemptBackgroundRecovery()},e)}async attemptBackgroundRecovery(){this.state="unloaded",this.loadPromise=null;try{await this.getEngines()}catch{}}emitRecoveryEvent(){if(!this.degradedModeStartTime)return;let e=Date.now()-this.degradedModeStartTime.getTime();console.info(`[WasmLoader] WASM recovered after ${e}ms in degraded mode. Retry count: ${this.fallbackState.consecutiveFailures}`),this.emit("recovered",{degradedDurationMs:e,retryCount:this.fallbackState.consecutiveFailures,version:this.version}),this.degradedModeStartTime=null}},J=new k;var Z={emaAlpha:.1,minSamplesForCalibration:10,maxHistorySize:1e3,targetFalsePositiveRate:.05,targetFalseNegativeRate:.02,maxAdjustmentPerCycle:.05,autoCalibrate:!1,autoCalibrateInterval:100,defaultThresholds:{...R}};export{Q as a,J 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.13.6");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.8");process.exit(0)}
2
2
  var h=class{executionHistory=[];learnedDurations=new Map;runCount=0;lastPrunedCount=0;learningRate;maxHistorySize;constructor(t){this.learningRate=t?.learningRate??.3,this.maxHistorySize=t?.maxHistorySize??1e4}buildTestDAG(t){let e=new Map,n=new Map;for(let i of t){let s=this.applyLearnedDuration(i);e.set(s.id,s),n.set(s.id,[])}for(let i of t)for(let s of i.dependencies){if(!e.has(s))throw new Error(`Test '${i.id}' depends on '${s}' which does not exist in the test set`);n.get(s).push(i.id)}let o=this.computeCriticalPath(e,n),a=this.computeParallelGroups(e,n);return{nodes:e,edges:n,criticalPath:o,parallelGroups:a}}findCriticalPath(t){return t.criticalPath.map(e=>t.nodes.get(e)).filter(e=>e!==void 0)}findParallelBranches(t){return t.parallelGroups.map(e=>e.map(n=>t.nodes.get(n)).filter(n=>n!==void 0))}pruneByMinCut(t,e){let n=this.sumDurations(t.nodes);if(n<=e)return this.lastPrunedCount=0,t;let o=this.computeAttentionScores(t),a=Array.from(o.entries()).sort((r,l)=>r[1]-l[1]),i=new Set(t.criticalPath),s=new Set,c=n;for(let[r]of a){if(c<=e)break;if(i.has(r)||(t.edges.get(r)??[]).some(p=>!s.has(p)))continue;let d=t.nodes.get(r);d&&(s.add(r),c-=d.estimatedDuration)}this.lastPrunedCount=s.size;let u=Array.from(t.nodes.values()).filter(r=>!s.has(r.id));return this.buildTestDAG(u)}schedule(t){if(t.length===0)return{phases:[],totalEstimatedTime:0,criticalPathTime:0,parallelism:0};let e=this.buildTestDAG(t),o=this.findParallelBranches(e).map(u=>({tests:u,canRunInParallel:u.length>1})),a=this.computeCriticalPathDuration(e),i=this.sumDurations(e.nodes),s=o.reduce((u,r)=>r.canRunInParallel?u+Math.max(...r.tests.map(l=>l.estimatedDuration)):u+r.tests.reduce((l,d)=>l+d.estimatedDuration,0),0),c=s>0?i/s:1;return this.runCount++,{phases:o,totalEstimatedTime:s,criticalPathTime:a,parallelism:c}}getOptimizationStats(){return{totalTests:0,criticalPathLength:0,parallelGroupCount:0,prunedTests:this.lastPrunedCount,estimatedTimeSaved:0,historicalRuns:this.runCount,usingNativeBackend:!1}}recordExecution(t,e,n){this.executionHistory.push({testId:t,actualDuration:e,result:n,timestamp:Date.now()}),this.executionHistory.length>this.maxHistorySize&&(this.executionHistory=this.executionHistory.slice(-this.maxHistorySize));let o=this.learnedDurations.get(t);o!==void 0?this.learnedDurations.set(t,o*(1-this.learningRate)+e*this.learningRate):this.learnedDurations.set(t,e)}getLearnedDuration(t){return this.learnedDurations.get(t)}isNativeBackendAvailable(){return!1}computeCriticalPath(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map,a=new Map;for(let r of n)o.set(r,t.get(r).estimatedDuration),a.set(r,null);for(let r of n){let l=o.get(r);for(let d of e.get(r)??[]){let p=t.get(d);if(!p)continue;let g=l+p.estimatedDuration;g>(o.get(d)??0)&&(o.set(d,g),a.set(d,r))}}let i=0,s=null;for(let[r,l]of o)l>i&&(i=l,s=r);if(!s)return[];let c=[],u=s;for(;u!==null;)c.unshift(u),u=a.get(u)??null;return c}computeCriticalPathDuration(t){return t.criticalPath.reduce((e,n)=>e+(t.nodes.get(n)?.estimatedDuration??0),0)}computeParallelGroups(t,e){let n=this.topologicalSort(t,e);if(n.length===0)return[];let o=new Map;for(let[u,r]of t)o.set(u,new Set(r.dependencies));let a=new Map;for(let u of n){let r=-1;for(let l of o.get(u)??new Set){let d=a.get(l);d!==void 0&&d>r&&(r=d)}a.set(u,r+1)}let i=new Map;for(let u of n){let r=a.get(u)??0;i.has(r)||i.set(r,[]),i.get(r).push(u)}let s=Math.max(...Array.from(i.keys()),-1),c=[];for(let u=0;u<=s;u++){let r=i.get(u);r&&r.length>0&&c.push(r)}return c}computeAttentionScores(t){let e=new Map,n=this.countTransitiveDependents(t);for(let[o,a]of t.nodes){let i=a.lastResult==="fail"?2:1,s=n.get(o)??0;e.set(o,a.priority*i*(1+s))}return e}countTransitiveDependents(t){let e=new Map,n=new Map,o=a=>{if(n.has(a))return n.get(a);let i=new Set;for(let s of t.edges.get(a)??[]){i.add(s);for(let c of o(s))i.add(c)}return n.set(a,i),i};for(let a of t.nodes.keys())e.set(a,o(a).size);return e}topologicalSort(t,e){let n=new Map;for(let i of t.keys())n.set(i,0);for(let i of e.values())for(let s of i)n.has(s)&&n.set(s,(n.get(s)??0)+1);let o=[];for(let[i,s]of n)s===0&&o.push(i);let a=[];for(;o.length>0;){let i=o.shift();a.push(i);for(let s of e.get(i)??[]){let c=(n.get(s)??0)-1;n.set(s,c),c===0&&o.push(s)}}if(a.length!==t.size)throw new Error(`Cycle detected in test DAG: sorted ${a.length} of ${t.size} nodes`);return a}applyLearnedDuration(t){let e=this.learnedDurations.get(t.id);return e!==void 0?{...t,estimatedDuration:Math.round(e)}:t}sumDurations(t){let e=0;for(let n of t.values())e+=n.estimatedDuration;return e}};function m(f){return new h(f)}export{h as a,m as b};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
2
- import{b as l,c}from"./chunk-E7MD5LHC.js";import{i}from"./chunk-XF2TKGSC.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;l(t)}db;recordNull(t){this.db.prepare(`
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.8");process.exit(0)}
2
+ import{b as l,c}from"./chunk-C37IK75J.js";import{i}from"./chunk-YTBW2SLZ.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;l(t)}db;recordNull(t){this.db.prepare(`
3
3
  INSERT INTO qe_pattern_nulls (id, pattern_id, context_fingerprint, failure_mode, trajectory_ref, evidence_class)
4
4
  VALUES (?, ?, ?, ?, ?, ?)
5
5
  ON CONFLICT(pattern_id, context_fingerprint) DO UPDATE SET
@@ -1,4 +1,4 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.6");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.8");process.exit(0)}
2
2
  function l(s,e){let t=s.prepare("SELECT confidence, usage_count, successful_uses FROM qe_patterns WHERE id = ?").get(e.patternId);if(!t)return{updated:!1};let c=e.success?1:0,n=t.usage_count+1,a=t.successful_uses+c,u=a/n,o=Math.min(1,n/100),r=t.confidence*.3+o*.2+u*.5,i=s.prepare(`
3
3
  INSERT INTO qe_pattern_usage (pattern_id, success, metrics_json, feedback)
4
4
  VALUES (?, ?, ?, ?)
@@ -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.13.6");process.exit(0)}
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.8");process.exit(0)}
2
2
  import{existsSync as c,readFileSync as f}from"fs";import{join as p,dirname as i}from"path";import{fileURLToPath as s}from"url";function u(o,a=10){let t=i(s(o));for(let r=0;r<a;r++){let n=p(t,"package.json");if(c(n))try{if(JSON.parse(f(n,"utf-8")).name==="agentic-qe")return t}catch{}let e=i(t);if(e===t)break;t=e}return null}export{u 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.13.6");process.exit(0)}
2
- import{S as f,b as p}from"./chunk-7NYCYSGW.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};
1
+ import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.13.8");process.exit(0)}
2
+ import{S as f,b as p}from"./chunk-DW5F6DJM.js";f();var y={predictionWindowSize:10,compressionThreshold:.3,maxConcurrentStreams:8,oscillationFrequencyMs:100};function d(s){try{return JSON.stringify(s).length}catch{return 0}}function w(s,t){let e={},n=!1;for(let r of Object.keys(t))JSON.stringify(s[r])!==JSON.stringify(t[r])&&(e[r]=t[r],n=!0);for(let r of Object.keys(s))r in t||(e[r]=void 0,n=!0);return n?e:null}function v(s,t){let e={...s};for(let[n,r]of Object.entries(t))r===void 0?delete e[n]:e[n]=r;return e}var l=class{windowSize;windows=new Map;constructor(t){this.windowSize=Math.max(1,t)}predict(t){let e=this.windows.get(t);if(!e||e.length===0)return null;let n=e[e.length-1];return typeof n!="object"||n===null||Array.isArray(n)?null:{...n}}record(t,e){let n=this.windows.get(t);n||(n=[],this.windows.set(t,n)),n.push(e),n.length>this.windowSize&&n.shift()}removeStream(t){this.windows.delete(t)}},h=class{maxStreams;cycleMs;streamIds=[];currentIndex=0;constructor(t,e){this.maxStreams=Math.max(1,t),this.cycleMs=Math.max(1,e)}addStream(t){return this.streamIds.includes(t)||this.streamIds.length>=this.maxStreams?!1:(this.streamIds.push(t),!0)}removeStream(t){let e=this.streamIds.indexOf(t);return e===-1?!1:(this.streamIds.splice(e,1),this.currentIndex>=this.streamIds.length&&(this.currentIndex=0),!0)}nextStream(){if(this.streamIds.length===0)return null;let t=this.streamIds[this.currentIndex];return this.currentIndex=(this.currentIndex+1)%this.streamIds.length,t}getActiveStreams(){return[...this.streamIds]}get activeCount(){return this.streamIds.length}},g=class{config;predictor;router;lastPayloads=new Map;totalMessages=0;compressedMessages=0;totalOriginalBytes=0;totalCompressedBytes=0;constructor(t){this.config={...y,...t},this.predictor=new l(this.config.predictionWindowSize),this.router=new h(this.config.maxConcurrentStreams,this.config.oscillationFrequencyMs)}send(t,e,n,r){this.totalMessages++;let i=d(r);this.totalOriginalBytes+=i;let c=!1,o=r,a=i;if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let m=this.predictor.predict(t);if(m){let u=w(m,r);u?1-d(u)/Math.max(i,1)>=this.config.compressionThreshold&&(o={__delta:!0,__changes:u},a=d(o),c=!0,this.compressedMessages++):(o={__delta:!0,__changes:{}},a=d(o),c=!0,this.compressedMessages++)}}return this.totalCompressedBytes+=a,this.predictor.record(t,r),this.lastPayloads.set(t,r),{streamId:t,senderId:e,receiverId:n,payload:o,compressed:c,originalSize:i,compressedSize:a,timestamp:Date.now()}}receive(t){if(!t.compressed||typeof t.payload!="object"||t.payload===null)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let e=t.payload;if(!e.__delta)return this.lastPayloads.set(t.streamId,t.payload),this.predictor.record(t.streamId,t.payload),t.payload;let n=this.predictor.predict(t.streamId),r=e.__changes??{};if(!n)return r;let i=v(n,r);return this.predictor.record(t.streamId,i),this.lastPayloads.set(t.streamId,i),i}getStats(){let t=this.totalOriginalBytes-this.totalCompressedBytes;return{totalMessages:this.totalMessages,compressedMessages:this.compressedMessages,bandwidthSavedBytes:Math.max(0,t),bandwidthReductionPercent:this.totalOriginalBytes>0?Math.max(0,t)/this.totalOriginalBytes*100:0,activeStreams:this.router.activeCount}}addStream(t){this.router.addStream(t)}removeStream(t){this.router.removeStream(t),this.predictor.removeStream(t),this.lastPayloads.delete(t)}};function M(s){return S()?new g(s):null}function S(){return p().useCognitiveRouting}export{M as a,S as b};