agentic-qe 3.14.6 → 3.14.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 (467) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/auto-memory-hook.mjs +18 -9
  3. package/.claude/helpers/helpers.manifest.json +6 -5
  4. package/.claude/helpers/hook-handler.cjs +40 -12
  5. package/.claude/helpers/memory.cjs +86 -0
  6. package/.claude/helpers/router.cjs +105 -0
  7. package/.claude/helpers/session.cjs +166 -0
  8. package/.claude/helpers/statusline.cjs +73 -621
  9. package/.claude/skills/skills-manifest.json +1 -1
  10. package/CHANGELOG.md +204 -0
  11. package/assets/skills/skills-manifest.json +1 -1
  12. package/dist/adapters/a2a/notifications/retry-queue.js +5 -0
  13. package/dist/adapters/claude-flow/pretrain-bridge.js +3 -2
  14. package/dist/agents/claim-verifier/verifiers/file-verifier.js +3 -2
  15. package/dist/cli/bundle.js +8 -8
  16. package/dist/cli/chunks/adapter-XYCOXQCC.js +2 -0
  17. package/dist/cli/chunks/{agent-booster-wasm-2YGML6OU.js → agent-booster-wasm-67OKGDGZ.js} +2 -2
  18. package/dist/cli/chunks/{agent-handler-D5SSQYNU.js → agent-handler-4HZEQ3WQ.js} +2 -2
  19. package/dist/cli/chunks/{agent-memory-branch-YHPLTITV.js → agent-memory-branch-IBHZQSRN.js} +2 -2
  20. package/dist/cli/chunks/aqe-learning-engine-DTJCROTG.js +2 -0
  21. package/dist/cli/chunks/{arena-7BGOXGXO.js → arena-EJBIGSF4.js} +2 -2
  22. package/dist/cli/chunks/{arena-MCE6EU7K.js → arena-LCLRGUIK.js} +4 -4
  23. package/dist/cli/chunks/{audit-BMWTQECB.js → audit-PY4JNDQQ.js} +3 -3
  24. package/dist/cli/chunks/base-5TQ34GMD.js +2 -0
  25. package/dist/cli/chunks/{better-sqlite3-PMUNGASU.js → better-sqlite3-2JG5K6XT.js} +2 -2
  26. package/dist/cli/chunks/{brain-handler-QPUFYX7F.js → brain-handler-3UYK55GA.js} +4 -4
  27. package/dist/cli/chunks/{branch-enumerator-WKFDGRN4.js → branch-enumerator-GOSWOX46.js} +2 -2
  28. package/dist/cli/chunks/{browser-VY5HKH5X.js → browser-DC2JV47Z.js} +2 -2
  29. package/dist/cli/chunks/browser-workflow-KWX4ESTJ.js +2 -0
  30. package/dist/cli/chunks/{chunk-FWASDOT2.js → chunk-25EEIAHS.js} +2 -2
  31. package/dist/cli/chunks/{chunk-P6OYS755.js → chunk-3576QGPP.js} +1 -1
  32. package/dist/cli/chunks/{chunk-2TMWAQQ3.js → chunk-3EKG7HFV.js} +4 -4
  33. package/dist/cli/chunks/{chunk-QZANMBIT.js → chunk-3FCHH4VP.js} +1 -1
  34. package/dist/cli/chunks/{chunk-CD542DNJ.js → chunk-3S5IIK32.js} +1 -1
  35. package/dist/cli/chunks/{chunk-5VFPCSK7.js → chunk-3X2JSW3R.js} +1 -1
  36. package/dist/cli/chunks/{chunk-D45SG6CP.js → chunk-4HXFPBAA.js} +1 -1
  37. package/dist/cli/chunks/{chunk-JVNTSNWU.js → chunk-4PY44TKH.js} +2 -2
  38. package/dist/cli/chunks/{chunk-DZ3AUAAB.js → chunk-4RNCVSVN.js} +2 -2
  39. package/dist/cli/chunks/{chunk-JBTPOIAC.js → chunk-56M4QNXU.js} +2 -2
  40. package/dist/cli/chunks/{chunk-H52HZ67P.js → chunk-5X4HDW5W.js} +2 -2
  41. package/dist/cli/chunks/{chunk-UNFFDHER.js → chunk-673XJBGW.js} +10 -32
  42. package/dist/cli/chunks/{chunk-RTFO5UQH.js → chunk-6F7MFHTY.js} +2 -2
  43. package/dist/cli/chunks/{chunk-Y3LZ35OG.js → chunk-6GJWT2OY.js} +2 -2
  44. package/dist/cli/chunks/{chunk-JXGFRBUO.js → chunk-6GNWVPMR.js} +2 -2
  45. package/dist/cli/chunks/{chunk-3EA536JF.js → chunk-6VTC3OHD.js} +2 -2
  46. package/dist/cli/chunks/{chunk-W6HXLH5G.js → chunk-775WGWLL.js} +3 -3
  47. package/dist/cli/chunks/{chunk-TVYY3OCX.js → chunk-77WL5HQW.js} +1 -1
  48. package/dist/cli/chunks/chunk-7STWD4KJ.js +3 -0
  49. package/dist/cli/chunks/{chunk-YSLL6VSL.js → chunk-7TNCEVWX.js} +2 -2
  50. package/dist/cli/chunks/{chunk-Z7WODOTH.js → chunk-7X3LMTRA.js} +2 -2
  51. package/dist/cli/chunks/{chunk-RZZCUIAI.js → chunk-A53MMSGC.js} +2 -2
  52. package/dist/cli/chunks/{chunk-QW6VMTBR.js → chunk-A5CLVZC3.js} +2 -2
  53. package/dist/cli/chunks/{chunk-IG5GNEC6.js → chunk-AEYJ4ZLA.js} +1 -1
  54. package/dist/cli/chunks/{chunk-NMAIY4PX.js → chunk-AJ5PCJQ2.js} +11 -11
  55. package/dist/cli/chunks/{chunk-WO4QMXIG.js → chunk-AJMAKUS3.js} +2 -2
  56. package/dist/cli/chunks/{chunk-2NPKIBAZ.js → chunk-AOD2ES44.js} +2 -2
  57. package/dist/cli/chunks/chunk-AR2S4DOB.js +2 -0
  58. package/dist/cli/chunks/{chunk-257E2A5M.js → chunk-AUFV2G2J.js} +5 -5
  59. package/dist/cli/chunks/{chunk-BVR7RMC5.js → chunk-B2QKBQYD.js} +1 -1
  60. package/dist/cli/chunks/{chunk-B6D2CHEH.js → chunk-BCCSV3RH.js} +1 -1
  61. package/dist/cli/chunks/{chunk-2YXGBZWV.js → chunk-BFIXUKOR.js} +1 -1
  62. package/dist/cli/chunks/chunk-BHPTHC5O.js +4 -0
  63. package/dist/cli/chunks/{chunk-AIRGNL55.js → chunk-BITFGVZ4.js} +2 -2
  64. package/dist/cli/chunks/{chunk-MBRHSU6W.js → chunk-BL6273KR.js} +10 -10
  65. package/dist/cli/chunks/{chunk-SMDN3BQZ.js → chunk-BOIUENWW.js} +1 -1
  66. package/dist/cli/chunks/{chunk-YS4FCTWF.js → chunk-BT3MI2BW.js} +1 -1
  67. package/dist/cli/chunks/{chunk-JZOS5FCX.js → chunk-BTBJ2NLH.js} +2 -2
  68. package/dist/cli/chunks/{chunk-CCK4BF76.js → chunk-BUVJIVFG.js} +1 -1
  69. package/dist/cli/chunks/{chunk-2JVWITNK.js → chunk-BZIPW2PA.js} +56 -80
  70. package/dist/cli/chunks/{chunk-BPEDWS6O.js → chunk-C647D42G.js} +2 -2
  71. package/dist/cli/chunks/{chunk-6U7LNMWZ.js → chunk-CBWM5NOO.js} +3 -3
  72. package/dist/cli/chunks/{chunk-72KXSMWI.js → chunk-CIEXUYY7.js} +1 -1
  73. package/dist/cli/chunks/{chunk-SE4WIB26.js → chunk-CLUHGBLN.js} +4 -4
  74. package/dist/cli/chunks/{chunk-JIXUMYKZ.js → chunk-CQEWL32R.js} +1 -1
  75. package/dist/cli/chunks/{chunk-CM7U6TAX.js → chunk-CXUC7YKA.js} +2 -2
  76. package/dist/cli/chunks/{chunk-7LPR6HJG.js → chunk-D2Y36V5J.js} +2 -2
  77. package/dist/cli/chunks/{chunk-BJTJLJRZ.js → chunk-DSJJHPPS.js} +4 -4
  78. package/dist/cli/chunks/{chunk-ZVWVV4EX.js → chunk-DZHXCOSK.js} +1 -1
  79. package/dist/cli/chunks/{chunk-7Z5LHRC3.js → chunk-EBV3WFIR.js} +2 -2
  80. package/dist/cli/chunks/{chunk-KNNISEDY.js → chunk-EKO5QL2B.js} +1 -1
  81. package/dist/cli/chunks/{chunk-XAS3XRYM.js → chunk-EMOZ5O5S.js} +1 -1
  82. package/dist/cli/chunks/{chunk-62N4NUJH.js → chunk-ES7TAJRJ.js} +2 -2
  83. package/dist/cli/chunks/chunk-EXQGHTPD.js +65 -0
  84. package/dist/cli/chunks/{chunk-Q7EAGKAE.js → chunk-F2WAB4WK.js} +2 -2
  85. package/dist/cli/chunks/{chunk-L4RUBPLR.js → chunk-F57FTFWS.js} +2 -2
  86. package/dist/cli/chunks/{chunk-GGRHV6D7.js → chunk-F6JJNBE5.js} +1 -1
  87. package/dist/cli/chunks/{chunk-3EZOZN25.js → chunk-FRC7AFB4.js} +2 -2
  88. package/dist/cli/chunks/{chunk-RSXXCL4A.js → chunk-G36RZF2Y.js} +1 -1
  89. package/dist/cli/chunks/{chunk-ZSPU4MOS.js → chunk-G3C7Z6FO.js} +2 -2
  90. package/dist/cli/chunks/{chunk-SNOBH4AZ.js → chunk-GA63ESNT.js} +2 -2
  91. package/dist/cli/chunks/{chunk-HNFVJP4I.js → chunk-GHMJFICO.js} +2 -2
  92. package/dist/cli/chunks/{chunk-7D3V65N5.js → chunk-GK5WLUX3.js} +1 -1
  93. package/dist/cli/chunks/{chunk-RETBYIAC.js → chunk-GQJ4QDEN.js} +6 -6
  94. package/dist/cli/chunks/chunk-GVLRE3BV.js +12 -0
  95. package/dist/cli/chunks/{chunk-MW2GGZZ5.js → chunk-H5UH234L.js} +1 -1
  96. package/dist/cli/chunks/{chunk-HM6ZSCPI.js → chunk-HBAFXWSO.js} +1 -1
  97. package/dist/cli/chunks/{chunk-DHVX5UB2.js → chunk-HE3BDBAO.js} +2 -2
  98. package/dist/cli/chunks/{chunk-YFBSPLJG.js → chunk-HHANMCD2.js} +1 -1
  99. package/dist/cli/chunks/chunk-HPVYJ6JH.js +2 -0
  100. package/dist/cli/chunks/{chunk-PX5YDCRH.js → chunk-I6NZFBT3.js} +3 -3
  101. package/dist/cli/chunks/{chunk-5J6W7SIA.js → chunk-ISBOHF6Y.js} +1 -1
  102. package/dist/cli/chunks/{chunk-UCFQALXO.js → chunk-J24AJEDE.js} +2 -2
  103. package/dist/cli/chunks/{chunk-FBMN7B46.js → chunk-J5HTQHJK.js} +2 -2
  104. package/dist/cli/chunks/{chunk-GPYVDFB3.js → chunk-JDOVO4E4.js} +205 -195
  105. package/dist/cli/chunks/chunk-JQAJUXRE.js +2 -0
  106. package/dist/cli/chunks/{chunk-RG52OKAM.js → chunk-JRK5GX56.js} +1 -1
  107. package/dist/cli/chunks/{chunk-I33ERSGB.js → chunk-JRLZ7LZ3.js} +2 -2
  108. package/dist/cli/chunks/{chunk-NQZ5AR3D.js → chunk-JTOFLDU7.js} +2 -2
  109. package/dist/cli/chunks/{chunk-NHWGMJAP.js → chunk-K6EOHGKS.js} +2 -2
  110. package/dist/cli/chunks/{chunk-5QQSIGUA.js → chunk-KKXH25IH.js} +2 -2
  111. package/dist/cli/chunks/{chunk-VGFFFKGK.js → chunk-KNSQWM2E.js} +2 -2
  112. package/dist/cli/chunks/{chunk-B6MOJC3X.js → chunk-L5T32SRF.js} +1 -1
  113. package/dist/cli/chunks/{chunk-WGM35YWL.js → chunk-LKFBW2QM.js} +2 -2
  114. package/dist/cli/chunks/{chunk-AJRUJAAK.js → chunk-LMAI74EP.js} +1 -1
  115. package/dist/cli/chunks/{chunk-C6KWXUFJ.js → chunk-LQVS5IWH.js} +2 -2
  116. package/dist/cli/chunks/{chunk-H5BS5VH7.js → chunk-LRGTPUJA.js} +2 -2
  117. package/dist/cli/chunks/{chunk-3HZS4M3O.js → chunk-LTHV4PIG.js} +2 -2
  118. package/dist/cli/chunks/{chunk-7CUQCCMD.js → chunk-M7QKCHLQ.js} +2 -2
  119. package/dist/cli/chunks/{chunk-CF2ISEOJ.js → chunk-N3ASALOL.js} +2 -2
  120. package/dist/cli/chunks/{chunk-ZCRTRYXK.js → chunk-NEXBTLN6.js} +2 -2
  121. package/dist/cli/chunks/{chunk-VMNWDJIZ.js → chunk-NJEEKYEP.js} +3 -3
  122. package/dist/cli/chunks/{chunk-ZEV3YTO7.js → chunk-NWUFTLSF.js} +2 -2
  123. package/dist/cli/chunks/{chunk-MQROI74N.js → chunk-O4QB2GFL.js} +2 -2
  124. package/dist/cli/chunks/{chunk-GDSXITFH.js → chunk-OA75C4HY.js} +2 -2
  125. package/dist/cli/chunks/{chunk-SESK3ARK.js → chunk-OVMG6EEF.js} +2 -2
  126. package/dist/cli/chunks/{chunk-MUOG6QXR.js → chunk-OX7MJFLC.js} +2 -2
  127. package/dist/cli/chunks/{chunk-ELLBS5RP.js → chunk-OZJQN7YE.js} +2 -2
  128. package/dist/cli/chunks/{chunk-D6CJIGRU.js → chunk-PFXCRRR6.js} +55 -55
  129. package/dist/cli/chunks/{chunk-ZL6SYKUK.js → chunk-PVJLQ2YZ.js} +1 -1
  130. package/dist/cli/chunks/{chunk-6LIHFV7O.js → chunk-QDRFLM77.js} +2 -2
  131. package/dist/cli/chunks/{chunk-H6ZM3PUT.js → chunk-QH7C4PTX.js} +1 -1
  132. package/dist/cli/chunks/chunk-QKM4XT2F.js +2 -0
  133. package/dist/cli/chunks/{chunk-V4DM6ELU.js → chunk-QP7EKLWU.js} +2 -2
  134. package/dist/cli/chunks/{chunk-BAMN2CHI.js → chunk-QPACHVDI.js} +1 -1
  135. package/dist/cli/chunks/{chunk-QDFTT3RF.js → chunk-QQVE65ER.js} +2 -2
  136. package/dist/cli/chunks/{chunk-LL3IGZBI.js → chunk-QYCZYJH7.js} +2 -2
  137. package/dist/cli/chunks/{chunk-DUYOVM5I.js → chunk-R6I5I724.js} +2 -2
  138. package/dist/cli/chunks/{chunk-ENGZ4D5V.js → chunk-RJJIPTVH.js} +2 -2
  139. package/dist/cli/chunks/{chunk-7NITCZWD.js → chunk-RM6OC35G.js} +1 -1
  140. package/dist/cli/chunks/{chunk-Q5XTSMWR.js → chunk-RTD4U7IW.js} +2 -2
  141. package/dist/cli/chunks/{chunk-DBDPRORT.js → chunk-SKJQKOFJ.js} +2 -2
  142. package/dist/cli/chunks/{chunk-ICTXTNQZ.js → chunk-SMBGK7XI.js} +1 -1
  143. package/dist/cli/chunks/{chunk-PI7TJS62.js → chunk-SPS472C5.js} +2 -2
  144. package/dist/cli/chunks/{chunk-IV5UZOHH.js → chunk-SUNXA2UR.js} +2 -2
  145. package/dist/cli/chunks/{chunk-IB27QACC.js → chunk-SVP3BP52.js} +2 -2
  146. package/dist/cli/chunks/{chunk-5OOMJGFN.js → chunk-T4WQPE77.js} +1 -1
  147. package/dist/cli/chunks/{chunk-66VWCR67.js → chunk-T53ZN4NO.js} +2 -2
  148. package/dist/cli/chunks/chunk-T6W2EYHC.js +2 -0
  149. package/dist/cli/chunks/{chunk-EAY2JMZG.js → chunk-T7YCNOW5.js} +2 -2
  150. package/dist/cli/chunks/{chunk-FZOBD67M.js → chunk-TCQWVVSR.js} +1 -1
  151. package/dist/cli/chunks/{chunk-SJUXE4IC.js → chunk-TGRHO4ES.js} +2 -2
  152. package/dist/cli/chunks/{chunk-6RE3X4V5.js → chunk-TP7L4EX6.js} +2 -2
  153. package/dist/cli/chunks/{chunk-6SQM2MUX.js → chunk-TT45RCLN.js} +2 -2
  154. package/dist/cli/chunks/{chunk-AVBJYI5I.js → chunk-TUZNWRYC.js} +1 -1
  155. package/dist/cli/chunks/{chunk-YHKEDEAA.js → chunk-U2QTL5T2.js} +3 -3
  156. package/dist/cli/chunks/chunk-U64QORFO.js +2 -0
  157. package/dist/cli/chunks/{chunk-BBT64TII.js → chunk-UHLZKH6B.js} +4 -4
  158. package/dist/cli/chunks/{chunk-GSF6MB64.js → chunk-UIWXKRTK.js} +2 -2
  159. package/dist/cli/chunks/{chunk-JMONHE4B.js → chunk-UNFE4RPV.js} +1 -1
  160. package/dist/cli/chunks/{chunk-DPYSUDAO.js → chunk-UQGIC5OX.js} +1 -1
  161. package/dist/cli/chunks/{chunk-IAF6T27S.js → chunk-VAXTPLO3.js} +2 -2
  162. package/dist/cli/chunks/{chunk-6SH5VZUD.js → chunk-VCSNNLWL.js} +2 -2
  163. package/dist/cli/chunks/chunk-VSPNIDQK.js +21 -0
  164. package/dist/cli/chunks/{chunk-6OS76PHI.js → chunk-VV2JVYOI.js} +2 -2
  165. package/dist/cli/chunks/{chunk-IQO7UCFR.js → chunk-VW7AXJQS.js} +2 -2
  166. package/dist/cli/chunks/{chunk-UQ32JHES.js → chunk-W7JUD4EZ.js} +2 -2
  167. package/dist/cli/chunks/chunk-WFKE7NZ5.js +12 -0
  168. package/dist/cli/chunks/{chunk-RFNPJK6N.js → chunk-WVEHKAIH.js} +3 -3
  169. package/dist/cli/chunks/{chunk-64VGZQLB.js → chunk-XAESN54Q.js} +1 -1
  170. package/dist/cli/chunks/{chunk-BMAPORJ7.js → chunk-XECZYQT5.js} +2 -2
  171. package/dist/cli/chunks/chunk-XFT4FYTC.js +2 -0
  172. package/dist/cli/chunks/{chunk-Y3UOUNHM.js → chunk-YHX74M7C.js} +2 -2
  173. package/dist/cli/chunks/chunk-YIWBJ637.js +2 -0
  174. package/dist/cli/chunks/{chunk-SDRHUMJB.js → chunk-Z5UZOYQS.js} +2 -2
  175. package/dist/cli/chunks/{chunk-7J6QC567.js → chunk-Z6G3QVZ4.js} +12 -12
  176. package/dist/cli/chunks/ci-5LIV2HW5.js +82 -0
  177. package/dist/cli/chunks/{ci-output-LDT24TS3.js → ci-output-UO5BDFU4.js} +2 -2
  178. package/dist/cli/chunks/{circuit-breaker-F5V4KITU.js → circuit-breaker-UQDPXYRD.js} +2 -2
  179. package/dist/cli/chunks/{claude-flow-setup-DT6WQQVD.js → claude-flow-setup-62QES3QX.js} +2 -2
  180. package/dist/cli/chunks/client-AJZKCP4I.js +2 -0
  181. package/dist/cli/chunks/{cline-installer-G7TJOAEX.js → cline-installer-X7VZTSZG.js} +2 -2
  182. package/dist/cli/chunks/{code-PGE6A42V.js → code-H3BF4L4H.js} +3 -3
  183. package/dist/cli/chunks/{code-index-extractor-RNITH372.js → code-index-extractor-BJGFZGGL.js} +2 -2
  184. package/dist/cli/chunks/{codex-installer-LBX77AI3.js → codex-installer-KVZWKU6S.js} +2 -2
  185. package/dist/cli/chunks/{completions-4AWLAARX.js → completions-YMILE6V7.js} +2 -2
  186. package/dist/cli/chunks/{complexity-analyzer-ZPNSS476.js → complexity-analyzer-J26N2PWG.js} +2 -2
  187. package/dist/cli/chunks/{continuedev-installer-UAPWX6OA.js → continuedev-installer-MAR42OV7.js} +2 -2
  188. package/dist/cli/chunks/{copilot-installer-BJN2YJGI.js → copilot-installer-CVOJF6OT.js} +2 -2
  189. package/dist/cli/chunks/core-handlers-MQHEMGDV.js +2 -0
  190. package/dist/cli/chunks/{cost-tracker-MHP2VJ63.js → cost-tracker-SXLWXE55.js} +2 -2
  191. package/dist/cli/chunks/{coverage-PQB4IEFG.js → coverage-D7HCHFP3.js} +3 -3
  192. package/dist/cli/chunks/cross-domain-router-3QNMZV5R.js +2 -0
  193. package/dist/cli/chunks/{cursor-installer-ZXBWYAS3.js → cursor-installer-X37VHIKW.js} +2 -2
  194. package/dist/cli/chunks/{daemon-64C7R6OJ.js → daemon-JN7SOH6F.js} +4 -4
  195. package/dist/cli/chunks/{daemon-N2BEGEFY.js → daemon-LIW47IDM.js} +4 -4
  196. package/dist/cli/chunks/{dag-attention-scheduler-SPZDAPNL.js → dag-attention-scheduler-QCHHIZBT.js} +2 -2
  197. package/dist/cli/chunks/{detect-LXJBSSZW.js → detect-WRFCWAX5.js} +2 -2
  198. package/dist/cli/chunks/{dist-node-U3TKZ2IZ.js → dist-node-6FWT4XZO.js} +2 -2
  199. package/dist/cli/chunks/{domain-handler-3DDWUVSR.js → domain-handler-SNFPNMRT.js} +2 -2
  200. package/dist/cli/chunks/{domain-plugins-JJVWI4OQ.js → domain-plugins-MXKHH62P.js} +2 -2
  201. package/dist/cli/chunks/domain-transfer-47UJNERX.js +2 -0
  202. package/dist/cli/chunks/dream-OSWAITPT.js +2 -0
  203. package/dist/cli/chunks/{embed-and-insert-pattern-JPAR7TXX.js → embed-and-insert-pattern-LZFAUNBQ.js} +2 -2
  204. package/dist/cli/chunks/{eval-SOLG23EA.js → eval-AMUXTMJB.js} +2 -2
  205. package/dist/cli/chunks/{experience-capture-middleware-T7G2VOOD.js → experience-capture-middleware-3D65TR2C.js} +4 -4
  206. package/dist/cli/chunks/{fast-paths-32N3ELI4.js → fast-paths-Y7BBMM56.js} +2 -2
  207. package/dist/cli/chunks/{feature-flags-APJDQ4N7.js → feature-flags-JMQQ7JW4.js} +2 -2
  208. package/dist/cli/chunks/{feature-flags-NAHKLDRN.js → feature-flags-VESRRQ6V.js} +2 -2
  209. package/dist/cli/chunks/{file-discovery-YKVM3MDB.js → file-discovery-JJKQQUV6.js} +2 -2
  210. package/dist/cli/chunks/{fleet-55M5CJS4.js → fleet-WIGHICJF.js} +4 -4
  211. package/dist/cli/chunks/{gnn-wrapper-UD6E6S6Z.js → gnn-wrapper-BFNPETTT.js} +2 -2
  212. package/dist/cli/chunks/{heartbeat-handler-OYVW3VSC.js → heartbeat-handler-HDXKTGUI.js} +4 -4
  213. package/dist/cli/chunks/heartbeat-scheduler-BVRVVIE2.js +2 -0
  214. package/dist/cli/chunks/hnsw-adapter-MZTHXULS.js +2 -0
  215. package/dist/cli/chunks/hnsw-index-KHEX4VDG.js +2 -0
  216. package/dist/cli/chunks/{hnsw-legacy-bridge-HBYIS3ZW.js → hnsw-legacy-bridge-6A7OTAPT.js} +2 -2
  217. package/dist/cli/chunks/{hnswlib-node-EQPM42OU.js → hnswlib-node-LKV2H47B.js} +2 -2
  218. package/dist/cli/chunks/{hooks-5ZSSJWO6.js → hooks-KDSFYQQG.js} +10 -10
  219. package/dist/cli/chunks/hybrid-backend-2B3LCLR4.js +2 -0
  220. package/dist/cli/chunks/{hypergraph-engine-XBGVQ4PD.js → hypergraph-engine-GDLPEPUC.js} +2 -2
  221. package/dist/cli/chunks/{hypergraph-handler-CAWAQ673.js → hypergraph-handler-4UMFA2EW.js} +3 -3
  222. package/dist/cli/chunks/impact-analyzer-4R4VWOGQ.js +2 -0
  223. package/dist/cli/chunks/{init-handler-PRHXSARK.js → init-handler-4GCHPQHD.js} +16 -14
  224. package/dist/cli/chunks/init-wizard-TAOPXHHD.js +2 -0
  225. package/dist/cli/chunks/kernel-6I6VZUWY.js +2 -0
  226. package/dist/cli/chunks/{kilocode-installer-F7LXBM7I.js → kilocode-installer-HJZMT2G5.js} +2 -2
  227. package/dist/cli/chunks/{kiro-installer-NM723ZRG.js → kiro-installer-WUPY67HG.js} +2 -2
  228. package/dist/cli/chunks/knowledge-graph-KFMTTUR5.js +2 -0
  229. package/dist/cli/chunks/{learning-5QYIDHH3.js → learning-AXKIS7IG.js} +4 -4
  230. package/dist/cli/chunks/{llm-router-43HKWPSX.js → llm-router-HUDPNZLJ.js} +4 -4
  231. package/dist/cli/chunks/llm-router-service-2D74XVM3.js +2 -0
  232. package/dist/cli/chunks/{load-5YDBWSCS.js → load-RM44POD7.js} +2 -2
  233. package/dist/cli/chunks/load-test-53FWOWNS.js +2 -0
  234. package/dist/cli/chunks/{mcp-UMAPMNMY.js → mcp-5JVQRBOP.js} +2 -2
  235. package/dist/cli/chunks/{memory-FWCPCQFP.js → memory-VGZ2V6PL.js} +5 -5
  236. package/dist/cli/chunks/memory-backend-KFJDDPEZ.js +2 -0
  237. package/dist/cli/chunks/memory-handlers-EI537Z32.js +2 -0
  238. package/dist/cli/chunks/{multi-model-executor-2XTBGLE4.js → multi-model-executor-WPRKCSCM.js} +2 -2
  239. package/dist/cli/chunks/{opencode-installer-GIXOJ6NS.js → opencode-installer-YAJMRCQO.js} +2 -2
  240. package/dist/cli/chunks/{orchestrator-VW6BKHLI.js → orchestrator-MUGWBUYP.js} +17 -17
  241. package/dist/cli/chunks/pattern-null-store-7DMU5CJ4.js +2 -0
  242. package/dist/cli/chunks/{pattern-usage-recorder-7CEUC3J7.js → pattern-usage-recorder-ZQJJ2YNG.js} +2 -2
  243. package/dist/cli/chunks/{pipeline-IGUQPPPO.js → pipeline-F4DXDUDC.js} +2 -2
  244. package/dist/cli/chunks/{platform-2P636I7B.js → platform-HI3A3OWF.js} +2 -2
  245. package/dist/cli/chunks/{plugin-NY6SWDPE.js → plugin-XRITPTR7.js} +2 -2
  246. package/dist/cli/chunks/{prime-radiant-advanced-wasm-2UUDTIO2.js → prime-radiant-advanced-wasm-HHNJP7CQ.js} +2 -2
  247. package/dist/cli/chunks/{project-root-IOISG5KX.js → project-root-2VN4WO2A.js} +2 -2
  248. package/dist/cli/chunks/protocol-executor-2EMTBTMG.js +2 -0
  249. package/dist/cli/chunks/{protocol-handler-ZTPCRQ5W.js → protocol-handler-ZEVHSEBG.js} +2 -2
  250. package/dist/cli/chunks/{prove-SQX5A3IG.js → prove-C4BLZWBS.js} +2 -2
  251. package/dist/cli/chunks/qe-reasoning-bank-VZHZZPHE.js +2 -0
  252. package/dist/cli/chunks/{quality-DROILKRY.js → quality-M3DTE4KK.js} +2 -2
  253. package/dist/cli/chunks/quality-gate-V6KS7ML3.js +7 -0
  254. package/dist/cli/chunks/queen-coordinator-7MYTTUHI.js +2 -0
  255. package/dist/cli/chunks/{real-embeddings-P5U3MGYC.js → real-embeddings-YWSE3IRT.js} +2 -2
  256. package/dist/cli/chunks/{ref-validation-KY73NQXD.js → ref-validation-ZWOTFA3T.js} +2 -2
  257. package/dist/cli/chunks/{roocode-installer-6JPPRB3W.js → roocode-installer-GJBIWETD.js} +2 -2
  258. package/dist/cli/chunks/router-ZD4LXAWA.js +2 -0
  259. package/dist/cli/chunks/routing-feedback-FSLMDVGD.js +2 -0
  260. package/dist/cli/chunks/{routing-handler-VTJIVFUO.js → routing-handler-CFYLGNAR.js} +2 -2
  261. package/dist/cli/chunks/{ruvector-commands-C6RPSJJO.js → ruvector-commands-EDKG456B.js} +2 -2
  262. package/dist/cli/chunks/rvf-dual-writer-LTKTDRFS.js +2 -0
  263. package/dist/cli/chunks/rvf-migration-adapter-IF24EVC5.js +2 -0
  264. package/dist/cli/chunks/{rvf-migration-coordinator-R53URRIO.js → rvf-migration-coordinator-ZMEYMAI6.js} +2 -2
  265. package/dist/cli/chunks/rvf-native-adapter-E6JNBKMZ.js +2 -0
  266. package/dist/cli/chunks/{rvf-store-integrity-MMXN5TEJ.js → rvf-store-integrity-AH6PNJP6.js} +2 -2
  267. package/dist/cli/chunks/safe-db-F6TRB5KZ.js +2 -0
  268. package/dist/cli/chunks/schedule-HBD4BYTE.js +2 -0
  269. package/dist/cli/chunks/scheduler-6FYWPMQC.js +2 -0
  270. package/dist/cli/chunks/{security-3B3R2NL4.js → security-ZU2GW3ZM.js} +3 -3
  271. package/dist/cli/chunks/{shared-rvf-adapter-VIJB7JUS.js → shared-rvf-adapter-5FOVSL3T.js} +2 -2
  272. package/dist/cli/chunks/{shared-rvf-dual-writer-UVWGDUWC.js → shared-rvf-dual-writer-IO4DC4XV.js} +2 -2
  273. package/dist/cli/chunks/sqlite-persistence-DOU72F5Z.js +2 -0
  274. package/dist/cli/chunks/{standalone-memory-M4LWAAYZ.js → standalone-memory-3UXDZ7HI.js} +2 -2
  275. package/dist/cli/chunks/{status-handler-YYFV6OZL.js → status-handler-264CHTWS.js} +2 -2
  276. package/dist/cli/chunks/{structural-health-27E6LLKB.js → structural-health-E2QPUOZE.js} +2 -2
  277. package/dist/cli/chunks/{sync-J3LJ56WN.js → sync-2ACMWM7D.js} +2 -2
  278. package/dist/cli/chunks/sync-N2L2OST4.js +2 -0
  279. package/dist/cli/chunks/{task-handler-4MCEBQZL.js → task-handler-IB5CVOTY.js} +2 -2
  280. package/dist/cli/chunks/task-handlers-QBMYNJHE.js +9 -0
  281. package/dist/cli/chunks/test-7RGLRDSP.js +33 -0
  282. package/dist/cli/chunks/{test-scheduling-ZJBFRZ3J.js → test-scheduling-RJABJT2W.js} +3 -3
  283. package/dist/cli/chunks/token-bootstrap-JVHMHB72.js +2 -0
  284. package/dist/cli/chunks/{token-usage-3X5WMTG2.js → token-usage-3ECHQVCY.js} +2 -2
  285. package/dist/cli/chunks/{transformers-MVL4C5IX.js → transformers-KJH3IJWI.js} +2 -2
  286. package/dist/cli/chunks/{tree-sitter-wasm-parser-SLW65ZFO.js → tree-sitter-wasm-parser-XN6PFI32.js} +2 -2
  287. package/dist/cli/chunks/{types-TG5P3CRS.js → types-5BAPXOLS.js} +2 -2
  288. package/dist/cli/chunks/unified-memory-GHAYAXWZ.js +2 -0
  289. package/dist/cli/chunks/unified-memory-hnsw-CCC63YXT.js +2 -0
  290. package/dist/cli/chunks/unified-persistence-HKRHI5PG.js +2 -0
  291. package/dist/cli/chunks/{upgrade-ETBHDEPY.js → upgrade-S5NFQZID.js} +2 -2
  292. package/dist/cli/chunks/{validate-C2A73LZK.js → validate-BIBWOLJD.js} +2 -2
  293. package/dist/cli/chunks/{validate-swarm-67XN42ML.js → validate-swarm-WAA3LBHH.js} +2 -2
  294. package/dist/cli/chunks/visual-security-APOXJ3Q3.js +2 -0
  295. package/dist/cli/chunks/{web-tree-sitter-USJN77P4.js → web-tree-sitter-OTBQTHAV.js} +2 -2
  296. package/dist/cli/chunks/{windsurf-installer-5GGZXGJW.js → windsurf-installer-NNQ22EW6.js} +2 -2
  297. package/dist/cli/chunks/witness-chain-7IP5IJGT.js +2 -0
  298. package/dist/cli/chunks/{witness-chain-IWS5ZHHL.js → witness-chain-E7MUBOJW.js} +2 -2
  299. package/dist/cli/chunks/witness-chain-repair-FW4QSN4C.js +2 -0
  300. package/dist/cli/chunks/{witness-chain-verifier-3GEADWPE.js → witness-chain-verifier-YMROEBVL.js} +2 -2
  301. package/dist/cli/chunks/{witness-key-manager-ZWEIK3VJ.js → witness-key-manager-4CGRNDMJ.js} +2 -2
  302. package/dist/cli/chunks/{workflow-KHMVVBBA.js → workflow-4VRSTRAN.js} +4 -4
  303. package/dist/cli/chunks/workflow-orchestrator-2HNW5ZMQ.js +2 -0
  304. package/dist/cli/chunks/wrappers-4M4UTGEU.js +2 -0
  305. package/dist/cli/commands/ci.js +18 -7
  306. package/dist/cli/commands/quality-gate.js +6 -1
  307. package/dist/cli/commands/test.js +18 -3
  308. package/dist/cli/handlers/init-handler.d.ts +2 -0
  309. package/dist/cli/handlers/init-handler.js +8 -2
  310. package/dist/cli/index.js +15 -2
  311. package/dist/cli/process-store-cleanup.d.ts +7 -0
  312. package/dist/cli/process-store-cleanup.js +27 -0
  313. package/dist/cli/utils/ci-config.d.ts +3 -3
  314. package/dist/cli/utils/ci-config.js +202 -68
  315. package/dist/coordination/handlers/test-execution-handlers.js +13 -8
  316. package/dist/coordination/index.d.ts +1 -1
  317. package/dist/coordination/queen-event-handlers.js +9 -6
  318. package/dist/coordination/result-saver.js +1 -1
  319. package/dist/coordination/services/index.d.ts +1 -1
  320. package/dist/coordination/services/task-audit-logger.d.ts +38 -13
  321. package/dist/coordination/services/task-audit-logger.js +33 -5
  322. package/dist/coordination/task-executor.d.ts +5 -0
  323. package/dist/coordination/task-executor.js +10 -5
  324. package/dist/domains/quality-assessment/quality-evidence.d.ts +3 -1
  325. package/dist/domains/quality-assessment/quality-evidence.js +7 -2
  326. package/dist/domains/test-execution/services/retry-handler.js +32 -13
  327. package/dist/domains/test-execution/services/test-executor.d.ts +3 -3
  328. package/dist/domains/test-execution/services/test-executor.js +66 -22
  329. package/dist/domains/test-generation/coordinator.js +6 -5
  330. package/dist/domains/test-generation/interfaces.d.ts +11 -1
  331. package/dist/domains/test-generation/services/behavior-example-validation.d.ts +36 -0
  332. package/dist/domains/test-generation/services/behavior-example-validation.js +89 -0
  333. package/dist/domains/test-generation/services/behavior-examples.d.ts +8 -0
  334. package/dist/domains/test-generation/services/behavior-examples.js +65 -0
  335. package/dist/domains/test-generation/services/test-generator.d.ts +1 -1
  336. package/dist/domains/test-generation/services/test-generator.js +59 -30
  337. package/dist/domains/visual-accessibility/services/axe-core-audit.d.ts +0 -15
  338. package/dist/domains/visual-accessibility/services/axe-core-audit.js +12 -10
  339. package/dist/init/browser-engine-installer.d.ts +5 -5
  340. package/dist/init/browser-engine-installer.js +28 -6
  341. package/dist/init/fleet-integration.js +3 -2
  342. package/dist/init/init-wizard-steps.js +3 -2
  343. package/dist/init/init-wizard.d.ts +2 -0
  344. package/dist/init/orchestrator.js +1 -0
  345. package/dist/init/phases/06-code-intelligence.js +6 -4
  346. package/dist/init/phases/09-assets.js +8 -18
  347. package/dist/init/phases/phase-interface.d.ts +2 -0
  348. package/dist/integrations/agentic-flow/reasoning-bank/index.d.ts +2 -5
  349. package/dist/integrations/ruvector/sona-persistence.d.ts +1 -0
  350. package/dist/integrations/ruvector/sona-persistence.js +74 -20
  351. package/dist/integrations/ruvector/sona-wrapper.d.ts +2 -0
  352. package/dist/integrations/ruvector/sona-wrapper.js +13 -0
  353. package/dist/integrations/vibium/client.d.ts +1 -0
  354. package/dist/integrations/vibium/client.js +24 -11
  355. package/dist/integrations/vibium/runtime.d.ts +14 -0
  356. package/dist/integrations/vibium/runtime.js +94 -0
  357. package/dist/kernel/memory-backend.js +5 -4
  358. package/dist/kernel/pattern-fts-self-heal.d.ts +63 -0
  359. package/dist/kernel/pattern-fts-self-heal.js +193 -0
  360. package/dist/kernel/process-lifecycle.d.ts +60 -0
  361. package/dist/kernel/process-lifecycle.js +91 -0
  362. package/dist/kernel/unified-memory-schemas.d.ts +15 -1
  363. package/dist/kernel/unified-memory-schemas.js +53 -25
  364. package/dist/kernel/unified-memory.js +34 -36
  365. package/dist/kernel/unified-persistence.js +12 -6
  366. package/dist/learning/aqe-learning-engine.js +3 -2
  367. package/dist/learning/experience-capture.d.ts +2 -1
  368. package/dist/learning/experience-capture.js +23 -8
  369. package/dist/learning/pattern-store.d.ts +1 -1
  370. package/dist/learning/pattern-store.js +27 -30
  371. package/dist/learning/qe-patterns.d.ts +6 -0
  372. package/dist/learning/qe-reasoning-bank.d.ts +1 -0
  373. package/dist/learning/qe-reasoning-bank.js +14 -4
  374. package/dist/learning/real-qe-reasoning-bank.d.ts +9 -4
  375. package/dist/learning/real-qe-reasoning-bank.js +28 -4
  376. package/dist/learning/rvf-pattern-store.js +19 -19
  377. package/dist/learning/sqlite-persistence.js +9 -24
  378. package/dist/mcp/bundle.js +545 -581
  379. package/dist/mcp/connection-pool.d.ts +2 -0
  380. package/dist/mcp/connection-pool.js +13 -2
  381. package/dist/mcp/entry.js +52 -6
  382. package/dist/mcp/handlers/domain-handler-configs.js +12 -4
  383. package/dist/mcp/handlers/memory-handlers.d.ts +1 -0
  384. package/dist/mcp/handlers/memory-handlers.js +16 -6
  385. package/dist/mcp/handlers/task-handlers.js +11 -7
  386. package/dist/mcp/protocol-server.js +47 -11
  387. package/dist/mcp/services/reasoning-bank-service.d.ts +6 -1
  388. package/dist/mcp/services/reasoning-bank-service.js +5 -1
  389. package/dist/mcp/tools/test-execution/e2e-execute.js +9 -1
  390. package/dist/mcp/tools/test-generation/generate.d.ts +6 -1
  391. package/dist/mcp/tools/test-generation/generate.js +8 -0
  392. package/dist/mcp/types.d.ts +8 -2
  393. package/dist/optimization/session-cache.js +13 -11
  394. package/dist/plugins/cache.js +10 -3
  395. package/dist/shared/embeddings/embedding-cache.js +4 -4
  396. package/dist/shared/error-utils.d.ts +15 -0
  397. package/dist/shared/error-utils.js +21 -0
  398. package/dist/shared/events/domain-events.d.ts +2 -1
  399. package/dist/shared/llm/cache.js +7 -10
  400. package/dist/shared/retry-engine.js +4 -0
  401. package/dist/shared/test-runner-process.d.ts +10 -0
  402. package/dist/shared/test-runner-process.js +210 -0
  403. package/dist/validation/quality-verdict.js +3 -2
  404. package/dist/workers/quality-daemon/priority-queue.js +4 -1
  405. package/package.json +10 -6
  406. package/dist/cli/chunks/adapter-UYOJPTOX.js +0 -2
  407. package/dist/cli/chunks/aqe-learning-engine-JR5AVQXR.js +0 -2
  408. package/dist/cli/chunks/base-DRZ2LS6X.js +0 -2
  409. package/dist/cli/chunks/browser-workflow-CJ7T3MXF.js +0 -2
  410. package/dist/cli/chunks/chunk-3NIG7S5W.js +0 -2
  411. package/dist/cli/chunks/chunk-4N23RFDU.js +0 -2
  412. package/dist/cli/chunks/chunk-AHKELLIO.js +0 -12
  413. package/dist/cli/chunks/chunk-DK4XN4CU.js +0 -2
  414. package/dist/cli/chunks/chunk-E6G2RD5H.js +0 -4
  415. package/dist/cli/chunks/chunk-MJS53PRX.js +0 -2
  416. package/dist/cli/chunks/chunk-PZPWRQ2M.js +0 -21
  417. package/dist/cli/chunks/chunk-QGA55PFM.js +0 -12
  418. package/dist/cli/chunks/chunk-SPV2VKC5.js +0 -3
  419. package/dist/cli/chunks/chunk-TCHGOB2N.js +0 -2
  420. package/dist/cli/chunks/chunk-UKA2KOXE.js +0 -2
  421. package/dist/cli/chunks/chunk-WCJBU2KI.js +0 -2
  422. package/dist/cli/chunks/chunk-Z6GGIRQQ.js +0 -65
  423. package/dist/cli/chunks/ci-W6K6G2KZ.js +0 -81
  424. package/dist/cli/chunks/client-KHWJT6FB.js +0 -2
  425. package/dist/cli/chunks/core-handlers-HING5RRG.js +0 -2
  426. package/dist/cli/chunks/cross-domain-router-PQTD6AZN.js +0 -2
  427. package/dist/cli/chunks/domain-transfer-M36KUJ2U.js +0 -2
  428. package/dist/cli/chunks/dream-WUGRSNCV.js +0 -2
  429. package/dist/cli/chunks/heartbeat-scheduler-33XX5XNQ.js +0 -2
  430. package/dist/cli/chunks/hnsw-adapter-XQPERX3H.js +0 -2
  431. package/dist/cli/chunks/hnsw-index-2GNXTWHH.js +0 -2
  432. package/dist/cli/chunks/hybrid-backend-CCF7URKI.js +0 -2
  433. package/dist/cli/chunks/impact-analyzer-HGKAZWIG.js +0 -2
  434. package/dist/cli/chunks/init-wizard-72MFBI3G.js +0 -2
  435. package/dist/cli/chunks/kernel-BRCBVMSK.js +0 -2
  436. package/dist/cli/chunks/knowledge-graph-DG44IPEI.js +0 -2
  437. package/dist/cli/chunks/llm-router-service-24KXFX32.js +0 -2
  438. package/dist/cli/chunks/load-test-N4TAYJY3.js +0 -2
  439. package/dist/cli/chunks/memory-backend-NVYFYVAU.js +0 -2
  440. package/dist/cli/chunks/memory-handlers-UTWCNCHL.js +0 -2
  441. package/dist/cli/chunks/pattern-null-store-SBPNYDBR.js +0 -2
  442. package/dist/cli/chunks/protocol-executor-IBYEII5Q.js +0 -2
  443. package/dist/cli/chunks/qe-reasoning-bank-7IETWW6W.js +0 -2
  444. package/dist/cli/chunks/quality-gate-PWKWDJY2.js +0 -7
  445. package/dist/cli/chunks/queen-coordinator-NHUK2MWJ.js +0 -2
  446. package/dist/cli/chunks/router-SRSO3IHF.js +0 -2
  447. package/dist/cli/chunks/routing-feedback-PASRE5HY.js +0 -2
  448. package/dist/cli/chunks/rvf-dual-writer-4M4J67OU.js +0 -2
  449. package/dist/cli/chunks/rvf-migration-adapter-TSXGT5LF.js +0 -2
  450. package/dist/cli/chunks/rvf-native-adapter-MOF3E7BR.js +0 -2
  451. package/dist/cli/chunks/safe-db-QJLFO33B.js +0 -2
  452. package/dist/cli/chunks/schedule-YIVXW5O2.js +0 -2
  453. package/dist/cli/chunks/scheduler-AON7DWSJ.js +0 -2
  454. package/dist/cli/chunks/sqlite-persistence-75VHKKQB.js +0 -2
  455. package/dist/cli/chunks/sync-26CEGSTC.js +0 -2
  456. package/dist/cli/chunks/task-handlers-GYBAWKE2.js +0 -9
  457. package/dist/cli/chunks/test-MPC5HRH5.js +0 -33
  458. package/dist/cli/chunks/token-bootstrap-2Y2XITBX.js +0 -2
  459. package/dist/cli/chunks/unified-memory-UCQ6AB32.js +0 -2
  460. package/dist/cli/chunks/unified-memory-hnsw-IXYUMKRR.js +0 -2
  461. package/dist/cli/chunks/unified-persistence-7E6JQ4FZ.js +0 -2
  462. package/dist/cli/chunks/vibium-NILGKHLN.js +0 -2
  463. package/dist/cli/chunks/visual-security-4VZXPEVG.js +0 -2
  464. package/dist/cli/chunks/witness-chain-JQA2VPZI.js +0 -2
  465. package/dist/cli/chunks/witness-chain-repair-4UA7IPS3.js +0 -2
  466. package/dist/cli/chunks/workflow-orchestrator-GI5NQH7C.js +0 -2
  467. package/dist/cli/chunks/wrappers-N6XIK5PT.js +0 -2
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
- import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chunk-AIRGNL55.js";import{a as z,c as He}from"./chunk-QW6VMTBR.js";import{a as H,b as D,c as We}from"./chunk-SDRHUMJB.js";import{a as qe}from"./chunk-TCHGOB2N.js";import{e as re}from"./chunk-FBMN7B46.js";import{a as X,c as ke}from"./chunk-MJS53PRX.js";import{a as ie,b as je}from"./chunk-PI7TJS62.js";import{a as ae,d as U,e as ce,f as Te}from"./chunk-C6KWXUFJ.js";import{a as b,b as se,e as Be}from"./chunk-6SH5VZUD.js";import{b as R,d as Pe}from"./chunk-64VGZQLB.js";import{createHash as ue}from"node:crypto";function $e(s){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(s)),e}function Ke(s){return typeof s=="string"?Buffer.from(s,"utf8"):s instanceof Uint8Array?Buffer.from(s):Buffer.from(W(s),"utf8")}function W(s){return s===null||typeof s!="object"?JSON.stringify(s)??"null":Array.isArray(s)?`[${s.map(W).join(",")}]`:`{${Object.keys(s).sort().map(t=>`${JSON.stringify(t)}:${W(s[t])}`).join(",")}}`}function _e(...s){let e=ue("sha256");for(let t of s)e.update(t);return e.digest()}function de(s,e,t){return _e(Ye,s,e,$e(t))}var Ye,Ee,O,le=R(()=>{"use strict";Ye=Buffer.from("ruvector:chain:"),Ee=ue("sha256").update("ruvector-proof-gate-v1").digest();O=class s{seq=0;prev=Ee;chain=[];payloadHashes=[];admit(e){let t=_e(Ke(e)),n=de(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=Ee;for(let t=0;t<this.chain.length;t++){if(!de(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 s;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(s){if(!Y.has(s))throw new Error(`Invalid table name: "${s}" is not in the allowlist`);return s}function ot(s){let e=s.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${s}" has too many parts (max: schema.table)`);for(let t of e)if(!pe.test(t))throw new Error(`Invalid SQL identifier: "${s}" \u2014 part "${t}" does not match pattern ${pe}`);return s}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","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);pe=/^[a-z_][a-z0-9_]{0,62}$/});function me(s){s.exec(ge),s.exec(`
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.14.8");process.exit(0)}
2
+ import{d as W,f as it}from"./chunk-RTD4U7IW.js";import{b as I,d as de}from"./chunk-BITFGVZ4.js";import{a as Y,c as ot}from"./chunk-A5CLVZC3.js";import{a as le,d as F,e as ge,f as pe}from"./chunk-LQVS5IWH.js";import{a as X,b as ue,e as st}from"./chunk-VCSNNLWL.js";import{a as _e,c as me,d as at}from"./chunk-T6W2EYHC.js";import{a as tt}from"./chunk-U64QORFO.js";import{e as Te}from"./chunk-J5HTQHJK.js";import{a as O,e as ce}from"./chunk-HPVYJ6JH.js";import{a as H,b as y,c as nt}from"./chunk-Z5UZOYQS.js";import{a as Ee,b as rt}from"./chunk-SPS472C5.js";import{b as R,d as et}from"./chunk-XAESN54Q.js";import{createHash as Se}from"node:crypto";function Tt(n){let e=Buffer.alloc(8);return e.writeBigUInt64LE(BigInt(n)),e}function Et(n){return typeof n=="string"?Buffer.from(n,"utf8"):n instanceof Uint8Array?Buffer.from(n):Buffer.from($(n),"utf8")}function $(n){return n===null||typeof n!="object"?JSON.stringify(n)??"null":Array.isArray(n)?`[${n.map($).join(",")}]`:`{${Object.keys(n).sort().map(t=>`${JSON.stringify(t)}:${$(n[t])}`).join(",")}}`}function he(...n){let e=Se("sha256");for(let t of n)e.update(t);return e.digest()}function Ne(n,e,t){return he(ct,n,e,Tt(t))}var ct,fe,A,Re=R(()=>{"use strict";ct=Buffer.from("ruvector:chain:"),fe=Se("sha256").update("ruvector-proof-gate-v1").digest();A=class n{seq=0;prev=fe;chain=[];payloadHashes=[];admit(e){let t=he(Et(e)),r=Ne(this.prev,t,this.seq);this.prev=r,this.chain.push(r),this.payloadHashes.push(t);let i={sequence:this.seq,payloadHash:t.toString("hex"),chainCommitment:r.toString("hex")};return this.seq+=1,i}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=fe;for(let t=0;t<this.chain.length;t++){if(!Ne(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 n;t.seq=e.seq,t.prev=Buffer.from(e.head,"hex");for(let r of e.chain)t.chain.push(Buffer.from(r,"hex"));for(let r of e.payloadHashes)t.payloadHashes.push(Buffer.from(r,"hex"));return t}}});function v(n){if(!K.has(n))throw new Error(`Invalid table name: "${n}" is not in the allowlist`);return n}function It(n){let e=n.split(".");if(e.length>2)throw new Error(`Invalid SQL identifier: "${n}" has too many parts (max: schema.table)`);for(let t of e)if(!Le.test(t))throw new Error(`Invalid SQL identifier: "${n}" \u2014 part "${t}" does not match pattern ${Le}`);return n}var K,Le,V=R(()=>{"use strict";K=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","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage","qe_agent_co_execution"]);Le=/^[a-z_][a-z0-9_]{0,62}$/});function Ce(n){n.exec(Ie),n.exec(`
3
3
  INSERT OR IGNORE INTO learning_evidence_manifests (
4
4
  id, trajectory_id, trajectory_hash, manifest_hash, task_family,
5
5
  outcome, oracle_refs_json, source_kind, process_signals_json
@@ -23,7 +23,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
23
23
  pattern_id, manifest_id, use_kind
24
24
  )
25
25
  SELECT id, 'legacy-pattern:' || id, 'legacy-context' FROM qe_patterns;
26
- `)}var ge,K=R(()=>{"use strict";ge=`
26
+ `)}var Ie,Q=R(()=>{"use strict";Ie=`
27
27
  CREATE TABLE IF NOT EXISTS learning_evidence_manifests (
28
28
  id TEXT PRIMARY KEY,
29
29
  trajectory_id TEXT,
@@ -131,13 +131,13 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
131
131
  BEGIN SELECT RAISE(ABORT, 'learning evidence admissions are append-only'); END;
132
132
  CREATE TRIGGER IF NOT EXISTS learning_admissions_no_delete BEFORE DELETE ON learning_evidence_admissions
133
133
  BEGIN SELECT RAISE(ABORT, 'learning evidence admissions are append-only'); END;
134
- `});var w,fe,Ne,Se,he,V,Re,Q,Le,Ie,Ce,Oe,Ae=R(()=>{"use strict";ze();He();K();w=13,fe=`
134
+ `});var x,Oe,Ae,ve,be,J,De,Z,b,ee,ye,Xe,Ue,Fe,xe,we,Me,te=R(()=>{"use strict";it();ot();Q();x=13,Oe=`
135
135
  CREATE TABLE IF NOT EXISTS schema_version (
136
136
  id INTEGER PRIMARY KEY CHECK (id = 1),
137
137
  version INTEGER NOT NULL,
138
138
  migrated_at TEXT DEFAULT (datetime('now'))
139
139
  );
140
- `,Ne=`
140
+ `,Ae=`
141
141
  -- Key-Value Store (v2 compatible - same schema as HybridBackend)
142
142
  CREATE TABLE IF NOT EXISTS kv_store (
143
143
  key TEXT NOT NULL,
@@ -149,7 +149,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
149
149
  );
150
150
  CREATE INDEX IF NOT EXISTS idx_kv_namespace ON kv_store(namespace);
151
151
  CREATE INDEX IF NOT EXISTS idx_kv_expires ON kv_store(expires_at) WHERE expires_at IS NOT NULL;
152
- `,Se=`
152
+ `,ve=`
153
153
  -- Vector Embeddings (new in v3 - replaces in-memory AgentDB)
154
154
  CREATE TABLE IF NOT EXISTS vectors (
155
155
  id TEXT PRIMARY KEY,
@@ -162,7 +162,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
162
162
  );
163
163
  CREATE INDEX IF NOT EXISTS idx_vectors_namespace ON vectors(namespace);
164
164
  CREATE INDEX IF NOT EXISTS idx_vectors_dimensions ON vectors(dimensions);
165
- `,he=`
165
+ `,be=`
166
166
  -- Q-Values for RL algorithms (ADR-046)
167
167
  CREATE TABLE IF NOT EXISTS rl_q_values (
168
168
  id TEXT PRIMARY KEY,
@@ -183,7 +183,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
183
183
  CREATE INDEX IF NOT EXISTS idx_qvalues_state ON rl_q_values(agent_id, state_key);
184
184
  CREATE INDEX IF NOT EXISTS idx_qvalues_domain ON rl_q_values(domain);
185
185
  CREATE INDEX IF NOT EXISTS idx_qvalues_updated ON rl_q_values(updated_at);
186
- `,V=`
186
+ `,J=`
187
187
  -- GOAP Goals
188
188
  CREATE TABLE IF NOT EXISTS goap_goals (
189
189
  id TEXT PRIMARY KEY,
@@ -294,7 +294,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
294
294
  -- would fail on "no such column" since CREATE TABLE IF NOT EXISTS above
295
295
  -- silently no-ops against them. unified-memory.ts's v11 migration creates
296
296
  -- this index only after confirming/backfilling the column.
297
- `,Re=`
297
+ `,De=`
298
298
  -- Concept Graph Nodes (Dream Engine)
299
299
  CREATE TABLE IF NOT EXISTS concept_nodes (
300
300
  id TEXT PRIMARY KEY,
@@ -363,7 +363,30 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
363
363
  CREATE INDEX IF NOT EXISTS idx_edge_weight ON concept_edges(weight DESC);
364
364
  CREATE INDEX IF NOT EXISTS idx_insight_cycle ON dream_insights(cycle_id);
365
365
  CREATE INDEX IF NOT EXISTS idx_dream_status ON dream_cycles(status);
366
- `,Q=`
366
+ `,Z=`
367
+ CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
368
+ name, description, pattern_type, qe_domain,
369
+ content='qe_patterns',
370
+ content_rowid='rowid'
371
+ );
372
+ `,b=Object.freeze({qe_patterns_fts_insert:`
373
+ CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_insert AFTER INSERT ON qe_patterns BEGIN
374
+ INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
375
+ VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
376
+ END;
377
+ `,qe_patterns_fts_delete:`
378
+ CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_delete AFTER DELETE ON qe_patterns BEGIN
379
+ INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
380
+ VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
381
+ END;
382
+ `,qe_patterns_fts_update:`
383
+ CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_update AFTER UPDATE ON qe_patterns BEGIN
384
+ INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
385
+ VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
386
+ INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
387
+ VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
388
+ END;
389
+ `}),ee=Z+Object.values(b).join(""),ye=n=>`
367
390
  -- QE Patterns table (unified from sqlite-persistence.ts)
368
391
  CREATE TABLE IF NOT EXISTS qe_patterns (
369
392
  id TEXT PRIMARY KEY,
@@ -476,30 +499,8 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
476
499
  FOREIGN KEY (execution_id) REFERENCES execution_results(id)
477
500
  );
478
501
 
479
- -- FTS5 full-text search index for hybrid vector/text search
480
- CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
481
- name, description, pattern_type, qe_domain,
482
- content='qe_patterns',
483
- content_rowid='rowid'
484
- );
485
-
486
- -- FTS5 triggers to keep index in sync
487
- CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_insert AFTER INSERT ON qe_patterns BEGIN
488
- INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
489
- VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
490
- END;
491
-
492
- CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_delete AFTER DELETE ON qe_patterns BEGIN
493
- INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
494
- VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
495
- END;
496
-
497
- CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_update AFTER UPDATE ON qe_patterns BEGIN
498
- INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
499
- VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
500
- INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
501
- VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
502
- END;
502
+ -- FTS5 full-text search index + sync triggers for hybrid vector/text search
503
+ ${n}
503
504
 
504
505
  -- QE Patterns indexes
505
506
  CREATE INDEX IF NOT EXISTS idx_qe_patterns_domain ON qe_patterns(qe_domain);
@@ -515,7 +516,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
515
516
  CREATE INDEX IF NOT EXISTS idx_execution_results_status ON execution_results(status);
516
517
  CREATE INDEX IF NOT EXISTS idx_executed_steps_execution ON executed_steps(execution_id);
517
518
  CREATE INDEX IF NOT EXISTS idx_executed_steps_action ON executed_steps(action_id);
518
- `,Le=`
519
+ `,Xe=ye(ee),Ue=ye(""),Fe=`
519
520
  -- MinCut Graph Snapshots (ADR-047)
520
521
  CREATE TABLE IF NOT EXISTS mincut_snapshots (
521
522
  id TEXT PRIMARY KEY,
@@ -621,7 +622,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
621
622
  CREATE INDEX IF NOT EXISTS idx_mincut_healing_type ON mincut_healing_actions(action_type);
622
623
  CREATE INDEX IF NOT EXISTS idx_mincut_healing_success ON mincut_healing_actions(success);
623
624
  CREATE INDEX IF NOT EXISTS idx_mincut_observations_iter ON mincut_observations(iteration);
624
- `,Ie=`
625
+ `,xe=`
625
626
  -- SONA Patterns table (ADR-046: Pattern Persistence for Neural Backbone)
626
627
  CREATE TABLE IF NOT EXISTS sona_patterns (
627
628
  id TEXT PRIMARY KEY,
@@ -647,7 +648,7 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
647
648
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_domain ON sona_patterns(domain);
648
649
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_confidence ON sona_patterns(confidence DESC);
649
650
  CREATE INDEX IF NOT EXISTS idx_sona_patterns_updated ON sona_patterns(updated_at DESC);
650
- `,Ce=`
651
+ `,we=`
651
652
  -- Test outcomes (ADR-023: Quality Feedback Loop)
652
653
  CREATE TABLE IF NOT EXISTS test_outcomes (
653
654
  id TEXT PRIMARY KEY,
@@ -730,66 +731,41 @@ import{d as j,f as ze}from"./chunk-Q5XTSMWR.js";import{b as I,d as oe}from"./chu
730
731
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_technique ON coverage_sessions(technique);
731
732
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_agent ON coverage_sessions(agent_id);
732
733
  CREATE INDEX IF NOT EXISTS idx_coverage_sessions_created ON coverage_sessions(created_at);
733
- `,Oe=["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","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage"]});function F(s,e,t){let n={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?s:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function a(o,T,d,E){return o!==d?o-d:T.localeCompare(E)}return{get(){return n.value},set(o,T){let d=T??Date.now();(n.timestamp===0||a(d,s,n.timestamp,n.nodeId)>0)&&(n={value:o,timestamp:d,nodeId:s,version:n.version+1,lastUpdated:Date.now()})},merge(o){let T=o.getState();this.applyState(T)},getState(){return{value:n.value,timestamp:n.timestamp,nodeId:n.nodeId,version:n.version,lastUpdated:n.lastUpdated}},applyState(o){(n.timestamp===0||a(o.timestamp,o.nodeId,n.timestamp,n.nodeId)>0)&&(n={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(n.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return s},getTimestamp(){return n.timestamp}}}function x(s,e){let t=F(s);return t.applyState(e),t}var J=R(()=>{"use strict"});function C(s){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[s]=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[s]=(e.counts[s]||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,o]of Object.entries(t.counts)){let T=e.counts[a]||0;o>T&&(e.counts[a]=o,n=!0)}n&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return s},getLocalCount(){return e.counts[s]||0}}}function G(s,e){let t=C(s);return t.applyState(e),t}var M=R(()=>{"use strict"});function P(s){let e=C(s),t=C(s),n=0,a=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),n++,a=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),n++,a=Date.now())},merge(o){let T=o.getState();this.applyState(T)},getState(){return{positive:e.getState(),negative:t.getState(),version:n,lastUpdated:a}},applyState(o){let T=this.get();e.applyState(o.positive),t.applyState(o.negative);let d=this.get();T!==d&&(n=Math.max(n,o.version)+1,a=Date.now())},getNodeId(){return s}}}function k(s,e){let t=P(s);return t.applyState(e),t}var Z=R(()=>{"use strict";M()});function Ve(s,e){return`${s}:${Date.now()}:${e}`}function ee(s){return typeof s=="string"?`s:${s}`:typeof s=="number"?`n:${s}`:typeof s=="boolean"?`b:${s}`:`j:${JSON.stringify(s)}`}function Qe(s){let e=s.substring(0,2),t=s.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return I(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function q(s){let e=new Map,t=new Map,n=0,a=Date.now(),o=0;function T(E){let u=e.get(E);if(!u||u.size===0)return!1;let _=t.get(E);if(!_||_.size===0)return!0;for(let m of u)if(!_.has(m))return!0;return!1}function d(E){let u=e.get(E);if(!u)return new Set;let _=t.get(E)||new Set,m=new Set;for(let p of u)_.has(p)||m.add(p);return m}return{has(E){let u=ee(E);return T(u)},values(){let E=[];for(let[u]of e)T(u)&&E.push(Qe(u));return E},size(){let E=0;for(let[u]of e)T(u)&&E++;return E},add(E){let u=ee(E),_=Ve(s,o++);e.has(u)||e.set(u,new Set),e.get(u).add(_),n++,a=Date.now()},remove(E){let u=ee(E),_=e.get(u);if(!_||_.size===0)return;t.has(u)||t.set(u,new Set);let m=t.get(u);for(let p of _)m.add(p);n++,a=Date.now()},merge(E){let u=E.getState();this.applyState(u)},getState(){let E={};for(let[_,m]of e)E[_]=Array.from(m);let u={};for(let[_,m]of t)m.size>0&&(u[_]=Array.from(m));return{elements:E,tombstones:u,version:n,lastUpdated:a}},applyState(E){let u=!1;for(let[_,m]of Object.entries(E.elements)){e.has(_)||e.set(_,new Set);let p=e.get(_);for(let l of m)p.has(l)||(p.add(l),u=!0)}for(let[_,m]of Object.entries(E.tombstones)){t.has(_)||t.set(_,new Set);let p=t.get(_);for(let l of m)p.has(l)||(p.add(l),u=!0)}u&&(n=Math.max(n,E.version)+1,a=Date.now())},getNodeId(){return s},clear(){for(let[E,u]of e){t.has(E)||t.set(E,new Set);let _=t.get(E);for(let m of u)_.add(m)}n++,a=Date.now()}}}function B(s,e){let t=q(s);return t.applyState(e),t}var te=R(()=>{"use strict";oe()});function ne(s){let e={...Je,...s},{nodeId:t,enableDeltaTracking:n,maxDeltaHistory:a}=e,o=new Map,T=new Map,d=new Map,E=new Map,u=0,_=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function l(i,r,c){let N={key:i,type:r,operation:c,timestamp:Date.now(),nodeId:t};for(let Ge of m)try{Ge(N)}catch(Me){console.error("[CRDTStore] Error in change listener:",Me)}}function g(i,r){u++,n&&p[i].add(r)}function L(){if(!n||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let r={fromVersion:_.length>0?_[_.length-1].toVersion:0,toVersion:u,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){r.registers={};for(let c of p.registers){let N=o.get(c);N&&(r.registers[c]=N.getState())}p.registers.clear()}if(p.gCounters.size>0){r.gCounters={};for(let c of p.gCounters){let N=T.get(c);N&&(r.gCounters[c]=N.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){r.pnCounters={};for(let c of p.pnCounters){let N=d.get(c);N&&(r.pnCounters[c]=N.getState())}p.pnCounters.clear()}if(p.sets.size>0){r.sets={};for(let c of p.sets){let N=E.get(c);N&&(r.sets[c]=N.getState())}p.sets.clear()}for(_.push(r);_.length>a;)_.shift()}let h={getRegister(i){return o.has(i)||o.set(i,F(t)),o.get(i)},setRegister(i,r){h.getRegister(i).set(r),g("registers",i),l(i,"lww-register","set")},hasRegister(i){return o.has(i)},deleteRegister(i){let r=o.delete(i);return r&&g("registers",i),r},getGCounter(i){return T.has(i)||T.set(i,C(t)),T.get(i)},incrementGCounter(i,r){h.getGCounter(i).increment(r),g("gCounters",i),l(i,"g-counter","increment")},hasGCounter(i){return T.has(i)},deleteGCounter(i){let r=T.delete(i);return r&&g("gCounters",i),r},getCounter(i){return d.has(i)||d.set(i,P(t)),d.get(i)},incrementCounter(i,r){h.getCounter(i).increment(r),g("pnCounters",i),l(i,"pn-counter","increment")},decrementCounter(i,r){h.getCounter(i).decrement(r),g("pnCounters",i),l(i,"pn-counter","decrement")},hasCounter(i){return d.has(i)},deleteCounter(i){let r=d.delete(i);return r&&g("pnCounters",i),r},getSet(i){return E.has(i)||E.set(i,q(t)),E.get(i)},addToSet(i,r){h.getSet(i).add(r),g("sets",i),l(i,"or-set","add")},removeFromSet(i,r){h.getSet(i).remove(r),g("sets",i),l(i,"or-set","remove")},hasSet(i){return E.has(i)},deleteSet(i){let r=E.delete(i);return r&&g("sets",i),r},merge(i){let r=i.getState();h.applyState(r)},getState(){L();let i={version:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[r,c]of o)i.registers[r]=c.getState();for(let[r,c]of T)i.gCounters[r]=c.getState();for(let[r,c]of d)i.pnCounters[r]=c.getState();for(let[r,c]of E)i.sets[r]=c.getState();return i},applyState(i){for(let[r,c]of Object.entries(i.registers))o.has(r)?o.get(r).applyState(c):o.set(r,x(t,c)),g("registers",r),l(r,"lww-register","merge");for(let[r,c]of Object.entries(i.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,G(t,c)),g("gCounters",r),l(r,"g-counter","merge");for(let[r,c]of Object.entries(i.pnCounters))d.has(r)?d.get(r).applyState(c):d.set(r,k(t,c)),g("pnCounters",r),l(r,"pn-counter","merge");for(let[r,c]of Object.entries(i.sets))E.has(r)?E.get(r).applyState(c):E.set(r,B(t,c)),g("sets",r),l(r,"or-set","merge");u=Math.max(u,i.version)+1},getDelta(i){if(L(),_.length===0)return i>=u,null;let r=_.filter(N=>N.toVersion>i);if(r.length===0)return null;let c={fromVersion:i,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(i){if(i.registers)for(let[r,c]of Object.entries(i.registers))o.has(r)?o.get(r).applyState(c):o.set(r,x(t,c)),g("registers",r),l(r,"lww-register","merge");if(i.gCounters)for(let[r,c]of Object.entries(i.gCounters))T.has(r)?T.get(r).applyState(c):T.set(r,G(t,c)),g("gCounters",r),l(r,"g-counter","merge");if(i.pnCounters)for(let[r,c]of Object.entries(i.pnCounters))d.has(r)?d.get(r).applyState(c):d.set(r,k(t,c)),g("pnCounters",r),l(r,"pn-counter","merge");if(i.sets)for(let[r,c]of Object.entries(i.sets))E.has(r)?E.get(r).applyState(c):E.set(r,B(t,c)),g("sets",r),l(r,"or-set","merge");u=Math.max(u,i.toVersion)+1},getVersion(){return u},getNodeId(){return t},on(i,r){if(i==="change")return m.add(r),()=>{m.delete(r)};throw new Error(`Unknown event type: ${i}`)},removeAllListeners(){m.clear()},keys(i){let r=[];return(!i||i==="lww-register")&&r.push(...Array.from(o.keys())),(!i||i==="g-counter")&&r.push(...Array.from(T.keys())),(!i||i==="pn-counter")&&r.push(...Array.from(d.keys())),(!i||i==="or-set")&&r.push(...Array.from(E.keys())),r},clear(){o.clear(),T.clear(),d.clear(),E.clear(),_.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),u=0},getStats(){return{total:o.size+T.size+d.size+E.size,registers:o.size,gCounters:T.size,pnCounters:d.size,sets:E.size,version:u,nodeId:t,deltaHistorySize:_.length}}};return h}var Je,ve=R(()=>{"use strict";J();M();Z();te();Je={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var be=R(()=>{"use strict"});var De=R(()=>{"use strict";J();M();Z();te();ve();be()});var nt={};Pe(nt,{ALLOWED_TABLE_NAMES:()=>Y,BinaryHeap:()=>ae,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>we,UnifiedHnswIndex:()=>U,UnifiedMemoryManager:()=>v,clearProjectRootCache:()=>H,createHnswIndex:()=>ce,findProjectRoot:()=>D,getDefaultDbPath:()=>Ue,getResolvedDefaultConfig:()=>Fe,getUnifiedMemory:()=>xe,initializeUnifiedMemory:()=>Ze,resetUnifiedMemory:()=>et,validateTableName:()=>A});import*as f from"fs";import*as Xe from"os";import*as S from"path";function Ue(){let s=D();return S.join(s,".agentic-qe","memory.db")}function Fe(){return{...we,dbPath:Ue()}}function xe(s){return v.getInstance(s)}async function Ze(s){let e=xe(s);return await e.initialize(),e}function et(){v.resetInstance()}function tt(){if(ye)return;ye=!0;let s=()=>{try{let e=v.instance;e&&e.close()}catch(e){console.debug("[UnifiedMemory] Cleanup error:",e instanceof Error?e.message:e)}};process.on("beforeExit",s),process.on("SIGINT",()=>{s(),process.exit(0)}),process.on("SIGTERM",()=>{s(),process.exit(0)})}var y,we,v,ye,rt=R(()=>{je();oe();ke();Be();qe();le();$();$();Te();Te();Ae();K();De();We();y=re.create("unified-memory");we={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 s{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new U("qe-memory");crdtStore=null;proofGate=null;proofGateEnvChecked=!1;static PROOF_NS="__proofgate__";static PROOF_KEY="chain";constructor(e){let t=Fe();if(this.config={...t,...e},process.env.AQE_MEMORY_BACKEND==="memory"){this.config.dbPath=":memory:";return}if(this.config.dbPath!==":memory:"&&!S.isAbsolute(this.config.dbPath)){let n=D();this.config.dbPath=S.join(n,this.config.dbPath)}}static getInstance(e){return s.instance||(s.instance=new s(e)),s.instance}static async getInstanceAsync(e){return s.instance?.initialized?s.instance:(s.instancePromise||(s.instancePromise=(async()=>{let t=s.getInstance(e);return await t.initialize(),t})()),s.instancePromise)}static resetInstance(){s.instance&&(s.instance.close(),s.instance=null),s.instancePromise=null,H()}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,o=0;if(!t){let T=process.env.AQE_PROJECT_ROOT;if(T){let d=S.resolve(this.config.dbPath),E=S.resolve(T);!d.startsWith(E)&&!d.startsWith(Xe.tmpdir())&&d.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)o=f.statSync(this.config.dbPath).size;else if(f.existsSync(n)){let d=this.findRecentBackups(n);if(d.length>0){let E=d[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
734
+ `,Me=["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","learning_evidence_manifests","learning_evidence_segments","learning_segment_edges","learning_evidence_admissions","pattern_manifest_lineage","pattern_segment_lineage"]});function ne(n,e,t){return n.prepare("SELECT 1 FROM sqlite_master WHERE type = ? AND name = ?").get(e,t)!==void 0}function ke(n){return n.replace(/\s+/g," ").trim().replace(/^CREATE TRIGGER IF NOT EXISTS /i,"CREATE TRIGGER ").replace(/ ?;$/,"").toLowerCase()}function w(n,e){return n.prepare(e).get()?.n??0}function Ge(n){let e=ne(n,"table","qe_patterns_fts"),t=e&&ne(n,"table","qe_patterns_fts_docsize"),r=[],i=[],o=n.prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?");for(let u of dt){let l=o.get(u);l===void 0?r.push(u):ke(l.sql??"")!==ut[u]&&i.push(u)}let E=w(n,"SELECT count(*) AS n FROM qe_patterns"),c=t?w(n,"SELECT count(*) AS n FROM qe_patterns_fts_docsize"):-1,T=t&&c===E?w(n,`SELECT count(*) AS n FROM qe_patterns p
735
+ WHERE NOT EXISTS (SELECT 1 FROM qe_patterns_fts_docsize d WHERE d.id = p.rowid)`):0;return{hasTable:e,hasDocsize:t,missingTriggers:r,mismatchedTriggers:i,patterns:E,indexed:c,unindexed:T}}function Pe(n){return!n.hasTable||n.missingTriggers.length>0||n.mismatchedTriggers.length>0?!0:n.hasDocsize?n.indexed!==n.patterns||n.unindexed>0:!1}function lt(n){if(n.readonly)return!0;try{return Number(n.pragma("query_only",{simple:!0}))===1}catch{return!1}}function qe(n,e={}){let t=e.log??(o=>console.warn(o)),r=e.logPrefix??"[PatternFTS]",i={status:"healthy",createdTable:!1,recreatedTriggers:[],replacedTriggers:[],rebuilt:!1,patternsBefore:-1,indexedBefore:-1,indexedAfter:-1};try{if(!ne(n,"table","qe_patterns"))return i.status="no-patterns",i;if(lt(n))return i.status="readonly",i;let o=Ge(n);if(i.patternsBefore=o.patterns,i.indexedBefore=o.indexed,!Pe(o))return i;let E=n.transaction(()=>{let c=Ge(n);if(!Pe(c))return null;c.hasTable||n.exec(Z);for(let T of c.missingTriggers)n.exec(b[T]);for(let T of c.mismatchedTriggers)n.exec(`DROP TRIGGER IF EXISTS ${T}`),n.exec(b[T]);return n.exec("INSERT INTO qe_patterns_fts(qe_patterns_fts) VALUES('rebuild')"),{s:c,indexedAfter:w(n,"SELECT count(*) AS n FROM qe_patterns_fts_docsize")}}).immediate();if(E){let{s:c}=E;i.createdTable=!c.hasTable,i.recreatedTriggers=[...c.missingTriggers],i.replacedTriggers=[...c.mismatchedTriggers],i.patternsBefore=c.patterns,i.indexedBefore=c.indexed,i.indexedAfter=E.indexedAfter,i.rebuilt=!0}if(i.rebuilt){i.status="healed";let c=[];i.createdTable&&c.push("created qe_patterns_fts"),i.recreatedTriggers.length>0&&c.push(`recreated triggers [${i.recreatedTriggers.join(", ")}]`),i.replacedTriggers.length>0&&c.push(`replaced triggers [${i.replacedTriggers.join(", ")}]`);let T=i.indexedBefore<0?"n/a":String(i.indexedBefore);c.push(`rebuilt index (indexed ${T} -> ${i.indexedAfter}, qe_patterns ${i.patternsBefore})`),t(`${r} Healed qe_patterns FTS5 index: ${c.join("; ")}`)}return i}catch(o){i.status="failed",i.error=O(o);try{t(`${r} qe_patterns FTS5 self-heal skipped: ${i.error} (keyword search may be degraded; vector search unaffected)`)}catch{}return i}}var dt,ut,Be=R(()=>{"use strict";ce();te();dt=Object.keys(b);ut=Object.freeze(Object.fromEntries(Object.entries(b).map(([n,e])=>[n,ke(e)])))});function M(n,e,t){let r={value:e,timestamp:t??(e!==void 0?Date.now():0),nodeId:e!==void 0?n:"",version:e!==void 0?1:0,lastUpdated:Date.now()};function i(o,E,c,T){return o!==c?o-c:E.localeCompare(T)}return{get(){return r.value},set(o,E){let c=E??Date.now();(r.timestamp===0||i(c,n,r.timestamp,r.nodeId)>0)&&(r={value:o,timestamp:c,nodeId:n,version:r.version+1,lastUpdated:Date.now()})},merge(o){let E=o.getState();this.applyState(E)},getState(){return{value:r.value,timestamp:r.timestamp,nodeId:r.nodeId,version:r.version,lastUpdated:r.lastUpdated}},applyState(o){(r.timestamp===0||i(o.timestamp,o.nodeId,r.timestamp,r.nodeId)>0)&&(r={value:o.value,timestamp:o.timestamp,nodeId:o.nodeId,version:Math.max(r.version,o.version)+1,lastUpdated:Date.now()})},getNodeId(){return n},getTimestamp(){return r.timestamp}}}function G(n,e){let t=M(n);return t.applyState(e),t}var re=R(()=>{"use strict"});function C(n){let e={counts:{},version:0,lastUpdated:Date.now()};return e.counts[n]=0,{get(){return Object.values(e.counts).reduce((t,r)=>t+r,0)},increment(t=1){if(t<0)throw new Error("G-Counter can only increment by positive values");t!==0&&(e.counts[n]=(e.counts[n]||0)+t,e.version++,e.lastUpdated=Date.now())},merge(t){let r=t.getState();this.applyState(r)},getState(){return{counts:{...e.counts},version:e.version,lastUpdated:e.lastUpdated}},applyState(t){let r=!1;for(let[i,o]of Object.entries(t.counts)){let E=e.counts[i]||0;o>E&&(e.counts[i]=o,r=!0)}r&&(e.version=Math.max(e.version,t.version)+1,e.lastUpdated=Date.now())},getNodeId(){return n},getLocalCount(){return e.counts[n]||0}}}function P(n,e){let t=C(n);return t.applyState(e),t}var k=R(()=>{"use strict"});function q(n){let e=C(n),t=C(n),r=0,i=Date.now();return{get(){return e.get()-t.get()},increment(o=1){if(o<0)throw new Error("Use decrement() for negative values");o!==0&&(e.increment(o),r++,i=Date.now())},decrement(o=1){if(o<0)throw new Error("Use increment() for negative values");o!==0&&(t.increment(o),r++,i=Date.now())},merge(o){let E=o.getState();this.applyState(E)},getState(){return{positive:e.getState(),negative:t.getState(),version:r,lastUpdated:i}},applyState(o){let E=this.get();e.applyState(o.positive),t.applyState(o.negative);let c=this.get();E!==c&&(r=Math.max(r,o.version)+1,i=Date.now())},getNodeId(){return n}}}function B(n,e){let t=q(n);return t.applyState(e),t}var se=R(()=>{"use strict";k()});function gt(n,e){return`${n}:${Date.now()}:${e}`}function ie(n){return typeof n=="string"?`s:${n}`:typeof n=="number"?`n:${n}`:typeof n=="boolean"?`b:${n}`:`j:${JSON.stringify(n)}`}function pt(n){let e=n.substring(0,2),t=n.substring(2);switch(e){case"s:":return t;case"n:":return Number(t);case"b:":return t==="true";case"j:":return I(t);default:throw new Error(`Unknown serialization type: ${e}`)}}function j(n){let e=new Map,t=new Map,r=0,i=Date.now(),o=0;function E(T){let u=e.get(T);if(!u||u.size===0)return!1;let l=t.get(T);if(!l||l.size===0)return!0;for(let m of u)if(!l.has(m))return!0;return!1}function c(T){let u=e.get(T);if(!u)return new Set;let l=t.get(T)||new Set,m=new Set;for(let p of u)l.has(p)||m.add(p);return m}return{has(T){let u=ie(T);return E(u)},values(){let T=[];for(let[u]of e)E(u)&&T.push(pt(u));return T},size(){let T=0;for(let[u]of e)E(u)&&T++;return T},add(T){let u=ie(T),l=gt(n,o++);e.has(u)||e.set(u,new Set),e.get(u).add(l),r++,i=Date.now()},remove(T){let u=ie(T),l=e.get(u);if(!l||l.size===0)return;t.has(u)||t.set(u,new Set);let m=t.get(u);for(let p of l)m.add(p);r++,i=Date.now()},merge(T){let u=T.getState();this.applyState(u)},getState(){let T={};for(let[l,m]of e)T[l]=Array.from(m);let u={};for(let[l,m]of t)m.size>0&&(u[l]=Array.from(m));return{elements:T,tombstones:u,version:r,lastUpdated:i}},applyState(T){let u=!1;for(let[l,m]of Object.entries(T.elements)){e.has(l)||e.set(l,new Set);let p=e.get(l);for(let g of m)p.has(g)||(p.add(g),u=!0)}for(let[l,m]of Object.entries(T.tombstones)){t.has(l)||t.set(l,new Set);let p=t.get(l);for(let g of m)p.has(g)||(p.add(g),u=!0)}u&&(r=Math.max(r,T.version)+1,i=Date.now())},getNodeId(){return n},clear(){for(let[T,u]of e){t.has(T)||t.set(T,new Set);let l=t.get(T);for(let m of u)l.add(m)}r++,i=Date.now()}}}function z(n,e){let t=j(n);return t.applyState(e),t}var oe=R(()=>{"use strict";de()});function ae(n){let e={..._t,...n},{nodeId:t,enableDeltaTracking:r,maxDeltaHistory:i}=e,o=new Map,E=new Map,c=new Map,T=new Map,u=0,l=[],m=new Set,p={registers:new Set,gCounters:new Set,pnCounters:new Set,sets:new Set};function g(a,s,d){let N={key:a,type:s,operation:d,timestamp:Date.now(),nodeId:t};for(let Je of m)try{Je(N)}catch(Ze){console.error("[CRDTStore] Error in change listener:",Ze)}}function _(a,s){u++,r&&p[a].add(s)}function L(){if(!r||!(p.registers.size>0||p.gCounters.size>0||p.pnCounters.size>0||p.sets.size>0))return;let s={fromVersion:l.length>0?l[l.length-1].toVersion:0,toVersion:u,timestamp:Date.now(),nodeId:t};if(p.registers.size>0){s.registers={};for(let d of p.registers){let N=o.get(d);N&&(s.registers[d]=N.getState())}p.registers.clear()}if(p.gCounters.size>0){s.gCounters={};for(let d of p.gCounters){let N=E.get(d);N&&(s.gCounters[d]=N.getState())}p.gCounters.clear()}if(p.pnCounters.size>0){s.pnCounters={};for(let d of p.pnCounters){let N=c.get(d);N&&(s.pnCounters[d]=N.getState())}p.pnCounters.clear()}if(p.sets.size>0){s.sets={};for(let d of p.sets){let N=T.get(d);N&&(s.sets[d]=N.getState())}p.sets.clear()}for(l.push(s);l.length>i;)l.shift()}let h={getRegister(a){return o.has(a)||o.set(a,M(t)),o.get(a)},setRegister(a,s){h.getRegister(a).set(s),_("registers",a),g(a,"lww-register","set")},hasRegister(a){return o.has(a)},deleteRegister(a){let s=o.delete(a);return s&&_("registers",a),s},getGCounter(a){return E.has(a)||E.set(a,C(t)),E.get(a)},incrementGCounter(a,s){h.getGCounter(a).increment(s),_("gCounters",a),g(a,"g-counter","increment")},hasGCounter(a){return E.has(a)},deleteGCounter(a){let s=E.delete(a);return s&&_("gCounters",a),s},getCounter(a){return c.has(a)||c.set(a,q(t)),c.get(a)},incrementCounter(a,s){h.getCounter(a).increment(s),_("pnCounters",a),g(a,"pn-counter","increment")},decrementCounter(a,s){h.getCounter(a).decrement(s),_("pnCounters",a),g(a,"pn-counter","decrement")},hasCounter(a){return c.has(a)},deleteCounter(a){let s=c.delete(a);return s&&_("pnCounters",a),s},getSet(a){return T.has(a)||T.set(a,j(t)),T.get(a)},addToSet(a,s){h.getSet(a).add(s),_("sets",a),g(a,"or-set","add")},removeFromSet(a,s){h.getSet(a).remove(s),_("sets",a),g(a,"or-set","remove")},hasSet(a){return T.has(a)},deleteSet(a){let s=T.delete(a);return s&&_("sets",a),s},merge(a){let s=a.getState();h.applyState(s)},getState(){L();let a={version:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let[s,d]of o)a.registers[s]=d.getState();for(let[s,d]of E)a.gCounters[s]=d.getState();for(let[s,d]of c)a.pnCounters[s]=d.getState();for(let[s,d]of T)a.sets[s]=d.getState();return a},applyState(a){for(let[s,d]of Object.entries(a.registers))o.has(s)?o.get(s).applyState(d):o.set(s,G(t,d)),_("registers",s),g(s,"lww-register","merge");for(let[s,d]of Object.entries(a.gCounters))E.has(s)?E.get(s).applyState(d):E.set(s,P(t,d)),_("gCounters",s),g(s,"g-counter","merge");for(let[s,d]of Object.entries(a.pnCounters))c.has(s)?c.get(s).applyState(d):c.set(s,B(t,d)),_("pnCounters",s),g(s,"pn-counter","merge");for(let[s,d]of Object.entries(a.sets))T.has(s)?T.get(s).applyState(d):T.set(s,z(t,d)),_("sets",s),g(s,"or-set","merge");u=Math.max(u,a.version)+1},getDelta(a){if(L(),l.length===0)return a>=u,null;let s=l.filter(N=>N.toVersion>a);if(s.length===0)return null;let d={fromVersion:a,toVersion:u,timestamp:Date.now(),nodeId:t,registers:{},gCounters:{},pnCounters:{},sets:{}};for(let N of s)N.registers&&Object.assign(d.registers,N.registers),N.gCounters&&Object.assign(d.gCounters,N.gCounters),N.pnCounters&&Object.assign(d.pnCounters,N.pnCounters),N.sets&&Object.assign(d.sets,N.sets);return Object.keys(d.registers).length===0&&delete d.registers,Object.keys(d.gCounters).length===0&&delete d.gCounters,Object.keys(d.pnCounters).length===0&&delete d.pnCounters,Object.keys(d.sets).length===0&&delete d.sets,d},applyDelta(a){if(a.registers)for(let[s,d]of Object.entries(a.registers))o.has(s)?o.get(s).applyState(d):o.set(s,G(t,d)),_("registers",s),g(s,"lww-register","merge");if(a.gCounters)for(let[s,d]of Object.entries(a.gCounters))E.has(s)?E.get(s).applyState(d):E.set(s,P(t,d)),_("gCounters",s),g(s,"g-counter","merge");if(a.pnCounters)for(let[s,d]of Object.entries(a.pnCounters))c.has(s)?c.get(s).applyState(d):c.set(s,B(t,d)),_("pnCounters",s),g(s,"pn-counter","merge");if(a.sets)for(let[s,d]of Object.entries(a.sets))T.has(s)?T.get(s).applyState(d):T.set(s,z(t,d)),_("sets",s),g(s,"or-set","merge");u=Math.max(u,a.toVersion)+1},getVersion(){return u},getNodeId(){return t},on(a,s){if(a==="change")return m.add(s),()=>{m.delete(s)};throw new Error(`Unknown event type: ${a}`)},removeAllListeners(){m.clear()},keys(a){let s=[];return(!a||a==="lww-register")&&s.push(...Array.from(o.keys())),(!a||a==="g-counter")&&s.push(...Array.from(E.keys())),(!a||a==="pn-counter")&&s.push(...Array.from(c.keys())),(!a||a==="or-set")&&s.push(...Array.from(T.keys())),s},clear(){o.clear(),E.clear(),c.clear(),T.clear(),l.length=0,p.registers.clear(),p.gCounters.clear(),p.pnCounters.clear(),p.sets.clear(),u=0},getStats(){return{total:o.size+E.size+c.size+T.size,registers:o.size,gCounters:E.size,pnCounters:c.size,sets:T.size,version:u,nodeId:t,deltaHistorySize:l.length}}};return h}var _t,je=R(()=>{"use strict";re();k();se();oe();_t={nodeId:"default-node",enableDeltaTracking:!0,maxDeltaHistory:100}});var ze=R(()=>{"use strict"});var He=R(()=>{"use strict";re();k();se();oe();je();ze()});var St={};et(St,{ALLOWED_TABLE_NAMES:()=>K,BinaryHeap:()=>le,DEFAULT_UNIFIED_MEMORY_CONFIG:()=>Ke,UnifiedHnswIndex:()=>F,UnifiedMemoryManager:()=>D,clearProjectRootCache:()=>H,createHnswIndex:()=>ge,findProjectRoot:()=>y,getDefaultDbPath:()=>$e,getResolvedDefaultConfig:()=>Ve,getUnifiedMemory:()=>Qe,initializeUnifiedMemory:()=>mt,resetUnifiedMemory:()=>ft,validateTableName:()=>v});import*as f from"fs";import*as Ye from"os";import*as S from"path";function $e(){let n=y();return S.join(n,".agentic-qe","memory.db")}function Ve(){return{...Ke,dbPath:$e()}}function Qe(n){return D.getInstance(n)}async function mt(n){let e=Qe(n);return await e.initialize(),e}function ft(){D.resetInstance()}function Nt(){if(We)return;We=!0;let n=()=>{try{let t=D.instance;t&&t.close()}catch(t){console.debug("[UnifiedMemory] Cleanup error:",t instanceof Error?t.message:t)}};process.on("beforeExit",n),_e(n);let e=t=>{me(t)||(n(),process.exit(0))};process.on("SIGINT",e),process.on("SIGTERM",e)}var U,Ke,D,We,ht=R(()=>{rt();de();ce();st();tt();Re();V();V();pe();pe();te();Be();Q();He();nt();at();U=Te.create("unified-memory");Ke={dbPath:".agentic-qe/memory.db",walMode:!0,mmapSize:X.MMAP_SIZE_BYTES,cacheSize:X.CACHE_SIZE_KB,busyTimeout:X.BUSY_TIMEOUT_MS,vectorDimensions:X.DEFAULT_VECTOR_DIMENSIONS};D=class n{static instance=null;static instancePromise=null;db=null;config;initialized=!1;vectorsLoaded=!1;initPromise=null;preparedStatements=new Map;vectorIndex=new F("qe-memory");crdtStore=null;proofGate=null;proofGateEnvChecked=!1;static PROOF_NS="__proofgate__";static PROOF_KEY="chain";constructor(e){let t=Ve();if(this.config={...t,...e},process.env.AQE_MEMORY_BACKEND==="memory"){this.config.dbPath=":memory:";return}if(this.config.dbPath!==":memory:"&&!S.isAbsolute(this.config.dbPath)){let r=y();this.config.dbPath=S.join(r,this.config.dbPath)}}static getInstance(e){return n.instance||(n.instance=new n(e)),n.instance}static async getInstanceAsync(e){return n.instance?.initialized?n.instance:(n.instancePromise||(n.instancePromise=(async()=>{let t=n.getInstance(e);return await t.initialize(),t})()),n.instancePromise)}static resetInstance(){n.instance&&(n.instance.close(),n.instance=null),n.instancePromise=null,H()}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:",r="",i=!1,o=0;if(!t){let E=process.env.AQE_PROJECT_ROOT;if(E){let c=S.resolve(this.config.dbPath),T=S.resolve(E);!c.startsWith(T)&&!c.startsWith(Ye.tmpdir())&&c.includes(".agentic-qe")&&(console.error(`[UnifiedMemory] WARNING: DB path "${this.config.dbPath}" points to a production .agentic-qe/ while AQE_PROJECT_ROOT="${E}". Redirecting to test-safe path.`),this.config.dbPath=S.join(E,".agentic-qe","memory.db"))}if(r=S.dirname(this.config.dbPath),f.existsSync(r)||f.mkdirSync(r,{recursive:!0}),i=f.existsSync(this.config.dbPath),i)o=f.statSync(this.config.dbPath).size;else if(f.existsSync(r)){let c=this.findRecentBackups(r);if(c.length>0){let T=c[0];console.error(`[UnifiedMemory] CRITICAL: Database file missing but directory exists!
734
736
  Expected: ${this.config.dbPath}
735
- Found ${d.length} backup(s), newest: ${E.path} (${(E.size/1024/1024).toFixed(1)}MB)
736
- Restoring from backup to prevent data loss...`),f.copyFileSync(E.path,this.config.dbPath);for(let u of["-wal","-shm"]){let _=this.config.dbPath+u;f.existsSync(_)&&f.unlinkSync(_)}o=E.size}}}if(e?.throwIfAborted(),this.db=ie(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&&o>1e6)try{let T=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(T&&T.cnt===0){let d=f.statSync(this.config.dbPath).size;d<o*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
737
- DB was ${(o/1024/1024).toFixed(1)}MB, now ${(d/1024/1024).toFixed(1)}MB with 0 patterns.
737
+ Found ${c.length} backup(s), newest: ${T.path} (${(T.size/1024/1024).toFixed(1)}MB)
738
+ Restoring from backup to prevent data loss...`),f.copyFileSync(T.path,this.config.dbPath);for(let u of["-wal","-shm"]){let l=this.config.dbPath+u;f.existsSync(l)&&f.unlinkSync(l)}o=T.size}}}if(e?.throwIfAborted(),this.db=Ee(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(),qe(this.db,{logPrefix:"[UnifiedMemory]"}),e?.throwIfAborted(),i&&o>1e6)try{let E=this.db.prepare("SELECT COUNT(*) as cnt FROM qe_patterns").get();if(E&&E.cnt===0){let c=f.statSync(this.config.dbPath).size;c<o*.1&&console.error(`[UnifiedMemory] CRITICAL: Possible data loss detected!
739
+ DB was ${(o/1024/1024).toFixed(1)}MB, now ${(c/1024/1024).toFixed(1)}MB with 0 patterns.
738
740
  This looks like the DB was replaced with an empty schema.
739
- 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(o=>o.startsWith("memory")&&o.endsWith(".db")&&o!=="memory.db").map(o=>{let T=S.join(e,o),d=f.statSync(T);return{path:T,size:d.size,mtime:d.mtimeMs}}).filter(o=>o.size>1e6).sort((o,T)=>T.mtime-o.mtime),a=S.join(e,"backups");if(f.existsSync(a)){let o=f.readdirSync(a);for(let T of o)if(T.endsWith(".db")){let d=S.join(a,T),E=f.statSync(d);E.size>1e6&&n.push({path:d,size:E.size,mtime:E.mtimeMs})}n.sort((T,d)=>d.mtime-T.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(o=>S.resolve(o)).filter(o=>o!==t&&f.existsSync(o));a.length>0&&console.warn(`[UnifiedMemory] WARNING: Duplicate database(s) detected!
741
+ Check backups in ${r} 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: ${O(t)}`)}}}findRecentBackups(e){try{let r=f.readdirSync(e).filter(o=>o.startsWith("memory")&&o.endsWith(".db")&&o!=="memory.db").map(o=>{let E=S.join(e,o),c=f.statSync(E);return{path:E,size:c.size,mtime:c.mtimeMs}}).filter(o=>o.size>1e6).sort((o,E)=>E.mtime-o.mtime),i=S.join(e,"backups");if(f.existsSync(i)){let o=f.readdirSync(i);for(let E of o)if(E.endsWith(".db")){let c=S.join(i,E),T=f.statSync(c);T.size>1e6&&r.push({path:c,size:T.size,mtime:T.mtimeMs})}r.sort((E,c)=>c.mtime-E.mtime)}return r}catch{return[]}}warnIfDuplicateDatabases(){if(this.config.dbPath!==":memory:")try{let e=y(),t=S.resolve(this.config.dbPath),i=[S.join(e,".agentic-qe","memory.db"),S.join(e,"v3",".agentic-qe","memory.db")].map(o=>S.resolve(o)).filter(o=>o!==t&&f.existsSync(o));i.length>0&&console.warn(`[UnifiedMemory] WARNING: Duplicate database(s) detected!
740
742
  Canonical: ${t}
741
- Duplicates: ${a.join(", ")}
742
- 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(o=>o.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 T=A(t);try{this.db.exec(`ALTER TABLE ${T} ADD COLUMN ${n} ${a}`),console.log(`[UnifiedMemory] Added column ${n} to ${t} (safe migration)`)}catch(d){console.log(`[UnifiedMemory] Column ${n} on ${t}: ${d instanceof Error?d.message:String(d)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(fe),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<w&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${w}`),this.db.transaction(()=>{t<1&&this.db.exec(Ne),t<2&&this.db.exec(Se),t<3&&(this.db.exec(he),this.db.exec(V),this.db.exec(Re)),t<4&&this.db.exec(Q),t<5&&this.db.exec(Le),t<6&&this.db.exec(j),t<7&&this.db.exec(Ie),t<8&&this.db.exec(Ce),t<9&&(this.db.exec(`
743
- CREATE VIRTUAL TABLE IF NOT EXISTS qe_patterns_fts USING fts5(
744
- name, description, pattern_type, qe_domain,
745
- content='qe_patterns',
746
- content_rowid='rowid'
747
- );
748
-
749
- CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_insert AFTER INSERT ON qe_patterns BEGIN
750
- INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
751
- VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
752
- END;
753
-
754
- CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_delete AFTER DELETE ON qe_patterns BEGIN
755
- INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
756
- VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
757
- END;
758
-
759
- CREATE TRIGGER IF NOT EXISTS qe_patterns_fts_update AFTER UPDATE ON qe_patterns BEGIN
760
- INSERT INTO qe_patterns_fts(qe_patterns_fts, rowid, name, description, pattern_type, qe_domain)
761
- VALUES ('delete', old.rowid, old.name, old.description, old.pattern_type, old.qe_domain);
762
- INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
763
- VALUES (new.rowid, new.name, new.description, new.pattern_type, new.qe_domain);
764
- END;
765
- `),this.db.exec(`
766
- INSERT INTO qe_patterns_fts(rowid, name, description, pattern_type, qe_domain)
767
- SELECT rowid, name, description, pattern_type, qe_domain FROM qe_patterns;
768
- `)),t<10&&this.db.exec(z),t<11&&this.migrateToV11GoapExecutionSteps(),t<12&&me(this.db),t<13&&this.migrateToV13EmbeddingSpace(),this.db.prepare(`
743
+ Duplicates: ${i.join(", ")}
744
+ This can cause data splits. Remove duplicates or set AQE_PROJECT_ROOT.`)}catch(e){U.debug("Duplicate database check failed",{error:e instanceof Error?e.message:String(e)})}}columnExists(e,t){if(!this.db)return!1;try{let r=v(e);return this.db.prepare(`PRAGMA table_info(${r})`).all().some(o=>o.name===t)}catch(r){return U.debug("Column existence check failed",{table:e,column:t,error:r instanceof Error?r.message:String(r)}),!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:r,columnDef:i}of e)if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t)&&!this.columnExists(t,r)){let E=v(t);try{this.db.exec(`ALTER TABLE ${E} ADD COLUMN ${r} ${i}`),console.log(`[UnifiedMemory] Added column ${r} to ${t} (safe migration)`)}catch(c){console.log(`[UnifiedMemory] Column ${r} on ${t}: ${c instanceof Error?c.message:String(c)}`)}}}async runMigrations(){if(!this.db)throw new Error("Database not initialized");this.db.exec(Oe),this.handleV2SchemaIncompatibilities();let t=this.db.prepare("SELECT version FROM schema_version WHERE id = 1").get()?.version??0;t<x&&(console.log(`[UnifiedMemory] Migrating from v${t} to v${x}`),this.db.transaction(()=>{t<1&&this.db.exec(Ae),t<2&&this.db.exec(ve),t<3&&(this.db.exec(be),this.db.exec(J),this.db.exec(De)),t<4&&this.db.exec(Xe),t<5&&this.db.exec(Fe),t<6&&this.db.exec(W),t<7&&this.db.exec(xe),t<8&&this.db.exec(we),t<9&&(this.db.exec(ee),this.db.exec("INSERT INTO qe_patterns_fts(qe_patterns_fts) VALUES('rebuild')")),t<10&&this.db.exec(Y),t<11&&this.migrateToV11GoapExecutionSteps(),t<12&&Ce(this.db),t<13&&this.migrateToV13EmbeddingSpace(),this.db.prepare(`
769
745
  INSERT OR REPLACE INTO schema_version (id, version, migrated_at)
770
746
  VALUES (1, ?, datetime('now'))
771
- `).run(w)})(),console.log("[UnifiedMemory] Migration complete"))}migrateToV11GoapExecutionSteps(){let e=this.db;e.exec(V);let t=(n,a,o)=>{e.prepare(`SELECT name FROM pragma_table_info('${n}')`).all().some(d=>d.name===a)||e.exec(`ALTER TABLE ${n} ADD COLUMN ${a} ${o}`)};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 o=a?Date.now()+a*1e3:null,T=JSON.stringify(t);this.db.prepare(`
747
+ `).run(x)})(),console.log("[UnifiedMemory] Migration complete"))}migrateToV11GoapExecutionSteps(){let e=this.db;e.exec(J);let t=(r,i,o)=>{e.prepare(`SELECT name FROM pragma_table_info('${r}')`).all().some(c=>c.name===i)||e.exec(`ALTER TABLE ${r} ADD COLUMN ${i} ${o}`)};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 r=this.bufferToFloatArray(t.embedding,t.dimensions);this.vectorIndex.add(t.id,r)}this.vectorsLoaded=!0,console.log(`[UnifiedMemory] Loaded ${e.length} vectors into vector index (ruvector flat)`)}async kvSet(e,t,r="default",i){this.ensureInitialized();let o=i?Date.now()+i*1e3:null,E=JSON.stringify(t);this.db.prepare(`
772
748
  INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at)
773
749
  VALUES (?, ?, ?, ?)
774
- `).run(e,n,T,o),this.auditWrite("kvSet",n,e,T)}async kvGet(e,t="default"){this.ensureInitialized();let n=this.db.prepare(`
750
+ `).run(e,r,E,o),this.auditWrite("kvSet",r,e,E)}async kvGet(e,t="default"){this.ensureInitialized();let r=this.db.prepare(`
775
751
  SELECT value, expires_at FROM kv_store
776
752
  WHERE key = ? AND namespace = ?
777
- `).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 I(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(`
753
+ `).get(e,t);if(r){if(r.expires_at&&Date.now()>r.expires_at){this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t);return}return I(r.value)}}async kvDelete(e,t="default"){this.ensureInitialized();let r=this.db.prepare("DELETE FROM kv_store WHERE key = ? AND namespace = ?").run(e,t);return r.changes>0&&this.auditWrite("kvDelete",t,e,""),r.changes>0}async kvExists(e,t="default"){return this.ensureInitialized(),this.db.prepare(`
778
754
  SELECT 1 FROM kv_store
779
755
  WHERE key = ? AND namespace = ? AND (expires_at IS NULL OR expires_at > ?)
780
- `).get(e,t,Date.now())!==void 0}async kvSearch(e,t="default",n=100){this.ensureInitialized();let a=e.replace(/\*/g,"%").replace(/\?/g,"_");return this.db.prepare(`
756
+ `).get(e,t,Date.now())!==void 0}async kvSearch(e,t="default",r=100){this.ensureInitialized();let i=e.replace(/[!%_]/g,"!$&").replace(/\*/g,"%").replace(/\?/g,"_");return this.db.prepare(`
781
757
  SELECT key FROM kv_store
782
- WHERE namespace = ? AND key LIKE ?
758
+ WHERE namespace = ? AND key LIKE ? ESCAPE '!'
783
759
  AND (expires_at IS NULL OR expires_at > ?)
784
760
  LIMIT ?
785
- `).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 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!==s.PROOF_NS)try{this.proofGate.admit({op:e,ns:t,key:n,value:a}),this.persistProofChain()}catch(o){y.warn(`proof-gate audit skipped for ${t}/${n}: ${X(o)}`)}}persistProofChain(){!this.proofGate||!this.db||this.db.prepare(`
761
+ `).all(t,i,Date.now(),r).map(E=>E.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,r,i){if(!this.proofGate){if(this.proofGateEnvChecked||(this.proofGateEnvChecked=!0,process.env.AQE_PROOF_GATE!=="1"))return;this.proofGate=this.loadProofChain()??new A}if(t!==n.PROOF_NS)try{this.proofGate.admit({op:e,ns:t,key:r,value:i}),this.persistProofChain()}catch(o){U.warn(`proof-gate audit skipped for ${t}/${r}: ${O(o)}`)}}persistProofChain(){!this.proofGate||!this.db||this.db.prepare(`
786
762
  INSERT OR REPLACE INTO kv_store (key, namespace, value, expires_at)
787
763
  VALUES (?, ?, ?, NULL)
788
- `).run(s.PROOF_KEY,s.PROOF_NS,JSON.stringify(this.proofGate.toJSON()))}loadProofChain(){if(!this.db)return null;let e=this.db.prepare(`
764
+ `).run(n.PROOF_KEY,n.PROOF_NS,JSON.stringify(this.proofGate.toJSON()))}loadProofChain(){if(!this.db)return null;let e=this.db.prepare(`
789
765
  SELECT value FROM kv_store WHERE key = ? AND namespace = ?
790
- `).get(s.PROOF_KEY,s.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 o=this.floatArrayToBuffer(t),T=a?JSON.stringify(a):null;this.db.prepare(`
766
+ `).get(n.PROOF_KEY,n.PROOF_NS);if(!e)return null;try{return A.fromJSON(JSON.parse(e.value))}catch(t){return U.warn(`proof-gate chain failed to load (starting fresh): ${O(t)}`),null}}async vectorStore(e,t,r="default",i){this.ensureInitialized();let o=this.floatArrayToBuffer(t),E=i?JSON.stringify(i):null;this.db.prepare(`
791
767
  INSERT OR REPLACE INTO vectors (id, namespace, embedding, dimensions, metadata, updated_at)
792
768
  VALUES (?, ?, ?, ?, ?, datetime('now'))
793
- `).run(e,n,o,t.length,T),this.vectorIndex.add(e,t)}async vectorGet(e){this.ensureInitialized();let t=this.db.prepare(`
769
+ `).run(e,r,o,t.length,E),this.vectorIndex.add(e,t)}async vectorGet(e){this.ensureInitialized();let t=this.db.prepare(`
794
770
  SELECT embedding, dimensions, metadata FROM vectors WHERE id = ?
795
- `).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?I(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 o=this.vectorIndex.size(),T=!!(n||a),d=Math.min(o,Math.max(T?t*2:t,1)),E=n?this.db.prepare("SELECT id, namespace, metadata FROM vectors WHERE namespace = ?").all(n):void 0,u=E?new Map(E.map(l=>[l.id,l])):void 0,_=this.vectorIndex.search(e,d);for(;T&&_.filter(l=>(!a||l.id.startsWith(a))&&(!u||u.has(l.id))).length<t&&d<o;)d=Math.min(o,d*2),_=this.vectorIndex.search(e,d);if(_.length===0)return[];let m=u??(()=>{let l=_.map(h=>h.id),g=l.map(()=>"?").join(","),L=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${g})`).all(...l);return new Map(L.map(h=>[h.id,h]))})();if(n){let l=[];for(let g of _){let L=m.get(g.id);if(L&&L.namespace===n&&(!a||g.id.startsWith(a))&&(l.push({id:g.id,score:g.score,metadata:L.metadata?I(L.metadata):void 0}),l.length>=t))break}return l}return(a?_.filter(l=>l.id.startsWith(a)).slice(0,t):_.slice(0,t)).map(l=>{let g=m.get(l.id);return{id:l.id,score:l.score,metadata:g?.metadata?I(g.metadata):void 0}})}migrateToV13EmbeddingSpace(){let e=this.db;if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_embeddings'").get()){e.exec(Q);return}e.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(a=>a.name==="space_id")||e.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)")}getVectorSearchProvenance(){return this.vectorIndex.getProvider().isNativeBackend()?{backend:"native-hnsw",indexType:"hnsw",approximate:!0,estimatedRecall:this.vectorIndex.recall(),qualifiedMaxK:se.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=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=ne({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=Oe.map(a=>{try{let o=this.db.prepare(`SELECT COUNT(*) as count FROM ${a}`).get();return{name:a,rowCount:o.count}}catch(o){return y.debug("Table row count query failed",{table:a,error:o instanceof Error?o.message:String(o)}),{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)}};ye=!1;tt()});export{Y as a,A as b,ot as c,$ as d,ge as e,K as f,Ue as g,we as h,Fe as i,v as j,xe as k,Ze as l,et as m,nt as n,rt as o};
771
+ `).get(e);if(t)return{embedding:this.bufferToFloatArray(t.embedding,t.dimensions),metadata:t.metadata?I(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,r,i){if(this.ensureInitialized(),!Number.isInteger(t)||t<=0)return[];this.vectorsLoaded||await this.loadVectorIndex();let o=this.vectorIndex.size(),E=!!(r||i),c=Math.min(o,Math.max(E?t*2:t,1)),T=r?this.db.prepare("SELECT id, namespace, metadata FROM vectors WHERE namespace = ?").all(r):void 0,u=T?new Map(T.map(g=>[g.id,g])):void 0,l=this.vectorIndex.search(e,c);for(;E&&l.filter(g=>(!i||g.id.startsWith(i))&&(!u||u.has(g.id))).length<t&&c<o;)c=Math.min(o,c*2),l=this.vectorIndex.search(e,c);if(l.length===0)return[];let m=u??(()=>{let g=l.map(h=>h.id),_=g.map(()=>"?").join(","),L=this.db.prepare(`SELECT id, namespace, metadata FROM vectors WHERE id IN (${_})`).all(...g);return new Map(L.map(h=>[h.id,h]))})();if(r){let g=[];for(let _ of l){let L=m.get(_.id);if(L&&L.namespace===r&&(!i||_.id.startsWith(i))&&(g.push({id:_.id,score:_.score,metadata:L.metadata?I(L.metadata):void 0}),g.length>=t))break}return g}return(i?l.filter(g=>g.id.startsWith(i)).slice(0,t):l.slice(0,t)).map(g=>{let _=m.get(g.id);return{id:g.id,score:g.score,metadata:_?.metadata?I(_.metadata):void 0}})}migrateToV13EmbeddingSpace(){let e=this.db;if(!e.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='qe_pattern_embeddings'").get()){e.exec(Ue);return}e.prepare("PRAGMA table_info('qe_pattern_embeddings')").all().some(i=>i.name==="space_id")||e.exec("ALTER TABLE qe_pattern_embeddings ADD COLUMN space_id TEXT"),e.exec("CREATE INDEX IF NOT EXISTS idx_qe_pattern_embeddings_space ON qe_pattern_embeddings(space_id)")}getVectorSearchProvenance(){return this.vectorIndex.getProvider().isNativeBackend()?{backend:"native-hnsw",indexType:"hnsw",approximate:!0,estimatedRecall:this.vectorIndex.recall(),qualifiedMaxK:ue.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=v(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=ae({nodeId:e}),console.log(`[UnifiedMemory] CRDT store initialized for node: ${e}`)}getCRDTStore(){return this.crdtStore}isCRDTInitialized(){return this.crdtStore!==null}async crdtSet(e,t,r="crdt"){this.ensureInitialized(),this.crdtStore&&this.crdtStore.setRegister(e,t),await this.kvSet(e,t,r)}async crdtGet(e,t="crdt"){if(this.crdtStore){let r=this.crdtStore.getRegister(e);if(r)return r.get()}return this.kvGet(e,t)}crdtIncrement(e,t=1){if(!this.crdtStore)throw new Error("CRDT store not initialized. Call initializeCRDT first.");let r=this.crdtStore.getCounter(e);r||(this.crdtStore.incrementCounter(e,0),r=this.crdtStore.getCounter(e));for(let i=0;i<t;i++)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 r=this.preparedStatements.get(e);return r||(r=this.db.prepare(t),this.preparedStatements.set(e,r)),r}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=Me.map(i=>{try{let o=this.db.prepare(`SELECT COUNT(*) as count FROM ${i}`).get();return{name:i,rowCount:o.count}}catch(o){return U.debug("Table row count query failed",{table:i,error:o instanceof Error?o.message:String(o)}),{name:i,rowCount:0}}}),t=0,r=0;try{f.existsSync(this.config.dbPath)&&(t=f.statSync(this.config.dbPath).size);let i=this.config.dbPath+"-wal";f.existsSync(i)&&(r=f.statSync(i).size)}catch(i){console.debug("[UnifiedMemory] File stat error:",i instanceof Error?i.message:i)}return{tables:e,fileSize:t,walSize:r,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 r=0;r<e.length;r++)t.writeFloatLE(e[r],r*4);return t}bufferToFloatArray(e,t){let r=new Float32Array(e.buffer,e.byteOffset,t);return Array.from(r)}};We=!1;Nt()});export{K as a,v as b,It as c,V as d,Ie as e,Q as f,ee as g,te as h,qe as i,Be as j,$e as k,Ke as l,Ve as m,D as n,Qe as o,mt as p,ft as q,St as r,ht as s};
@@ -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.14.6");process.exit(0)}
2
- import{a as R}from"./chunk-TCHGOB2N.js";import{e as g}from"./chunk-FBMN7B46.js";import{S as v,b as l}from"./chunk-DUYOVM5I.js";R();v();import{createHash as m,randomUUID as f}from"crypto";var a=g.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
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.14.8");process.exit(0)}
2
+ import{a as R}from"./chunk-U64QORFO.js";import{e as g}from"./chunk-J5HTQHJK.js";import{S as v,b as l}from"./chunk-R6I5I724.js";R();v();import{createHash as m,randomUUID as f}from"crypto";var a=g.create("witness-chain"),p=class{logLikelihoodRatio=0;upperBound;lowerBound;observations=0;constructor(t=.05,e=.05){this.upperBound=Math.log(1/t),this.lowerBound=Math.log(e)}addWeightedEvidence(t,e){return this.logLikelihoodRatio+=t?e:-e,this.observations++,this.logLikelihoodRatio>=this.upperBound?"PASS":this.logLikelihoodRatio<=this.lowerBound?"FAIL":"INCONCLUSIVE"}addEvidence(t){return this.addWeightedEvidence(t,.5)}getRatio(){return this.logLikelihoodRatio}getObservations(){return this.observations}getBounds(){return{upper:this.upperBound,lower:this.lowerBound}}reset(){this.logLikelihoodRatio=0,this.observations=0}},c="0".repeat(64),h=class{receipts=[];lastHash=c;sprtAccumulators=new Map;appendWitness(t){let e=f(),i=Date.now(),s=this.receipts.length,n=this.lastHash+JSON.stringify(t)+i,o=m("sha256").update(n).digest("hex"),u={id:e,timestamp:i,previousHash:this.lastHash,hash:o,decision:t,chainIndex:s};return this.receipts.push(u),this.lastHash=o,this.updateSPRT(t),a.debug("Witness appended",{chainIndex:s,type:t.type,decision:t.decision,hash:o.slice(0,16)+"..."}),u}verifyChain(){if(this.receipts.length===0)return{valid:!0,length:0,brokenAt:-1,message:"Chain is empty (valid)",lastHash:c};let t=c;for(let e=0;e<this.receipts.length;e++){let i=this.receipts[e];if(i.previousHash!==t)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: previousHash mismatch`,lastHash:this.lastHash};let s=i.previousHash+JSON.stringify(i.decision)+i.timestamp,n=m("sha256").update(s).digest("hex");if(i.hash!==n)return{valid:!1,length:this.receipts.length,brokenAt:e,message:`Chain broken at index ${e}: hash mismatch (tamper detected)`,lastHash:this.lastHash};t=i.hash}return{valid:!0,length:this.receipts.length,brokenAt:-1,message:`Chain valid (${this.receipts.length} receipts)`,lastHash:this.lastHash}}getChain(t){return t!==void 0&&t>0?[...this.receipts.slice(-t)]:[...this.receipts]}getChainLength(){return this.receipts.length}getLastHash(){return this.lastHash}exportChain(){let t={version:"1.0.0",exportedAt:Date.now(),length:this.receipts.length,receipts:this.receipts};return JSON.stringify(t,null,2)}importChain(t){try{let e=JSON.parse(t);if(!e||e.version!=="1.0.0"||!Array.isArray(e.receipts))return a.warn("Import failed: invalid format"),!1;let i=this.receipts,s=this.lastHash;this.receipts=e.receipts,this.lastHash=e.receipts.length>0?e.receipts[e.receipts.length-1].hash:c;let n=this.verifyChain();return n.valid?(a.info("Chain imported successfully",{length:e.receipts.length}),!0):(this.receipts=i,this.lastHash=s,a.warn("Import failed: chain integrity check failed",{message:n.message}),!1)}catch(e){return a.warn("Import failed: parse error",{error:e instanceof Error?e.message:String(e)}),!1}}getSPRT(t,e,i){return this.sprtAccumulators.has(t)||this.sprtAccumulators.set(t,new p(e,i)),this.sprtAccumulators.get(t)}getReceipt(t){return this.receipts[t]}updateSPRT(t){let e=t.decision==="PASS"||t.decision==="PERMIT";this.getSPRT(t.type).addEvidence(e)}},d=class extends h{persistence;constructor(t){super(),this.persistence=t;let e=t.loadAllReceipts();if(e.length>0){let i={version:"1.0.0",exportedAt:Date.now(),length:e.length,receipts:e};this.importChain(JSON.stringify(i))?a.info("Witness chain restored from SQLite",{receipts:e.length}):a.warn("Failed to restore witness chain from SQLite \u2014 starting fresh")}}appendWitness(t){let e=super.appendWitness(t);try{this.persistence.insertReceipt(e)}catch(i){a.warn("Failed to persist witness receipt to SQLite",{chainIndex:e.chainIndex,error:i instanceof Error?i.message:String(i)})}return e}};function C(r){r.exec(`
3
3
  CREATE TABLE IF NOT EXISTS witness_chain_receipts (
4
4
  id TEXT PRIMARY KEY,
5
5
  chain_index INTEGER NOT NULL,
@@ -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.14.6");process.exit(0)}
2
- import{b as l,c}from"./chunk-QW6VMTBR.js";import{i}from"./chunk-DPYSUDAO.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.14.8");process.exit(0)}
2
+ import{b as i,c}from"./chunk-A5CLVZC3.js";import{i as l}from"./chunk-UQGIC5OX.js";c();var u=.15,d=.03,p=.25,s=class{constructor(t){this.db=t;i(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
@@ -7,7 +7,7 @@ import{b as l,c}from"./chunk-QW6VMTBR.js";import{i}from"./chunk-DPYSUDAO.js";c()
7
7
  failure_mode = excluded.failure_mode,
8
8
  trajectory_ref = COALESCE(excluded.trajectory_ref, trajectory_ref),
9
9
  updated_at = datetime('now')
10
- `).run(i(),t.patternId,t.contextFingerprint,t.failureMode,t.trajectoryRef??null,t.evidenceClass??"EXECUTED")}getNullSummaries(t){let e=new Map;if(t.length===0)return e;let a=t.map(()=>"?").join(","),o=this.db.prepare(`
10
+ `).run(l(),t.patternId,t.contextFingerprint,t.failureMode,t.trajectoryRef??null,t.evidenceClass??"EXECUTED")}getNullSummaries(t){let e=new Map;if(t.length===0)return e;let a=t.map(()=>"?").join(","),o=this.db.prepare(`
11
11
  SELECT pattern_id, context_fingerprint, consolidated_count
12
12
  FROM qe_pattern_nulls
13
13
  WHERE pattern_id IN (${a})
@@ -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.14.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.14.8");process.exit(0)}
2
2
  var a=class extends Error{constructor(r){super(r),this.name="TestRunnerExecutionError"}};function y(t,r,s,e,n,i){let d=(i?.testResults??[]).filter(u=>u.status==="failed"&&(t==="vitest"&&u.message||!u.assertionResults?.some(f=>f.status==="failed"))),o;if(s===null?o="terminated without an exit code":e.passed+e.failed+e.skipped===0?o="reported zero tests":d.length>0||(i?.numRuntimeErrorTestSuites??0)>0||(i?.numFailedTestSuites??0)>0&&e.failed===0?o="reported a suite execution error":(s!==0||i?.success===!1)&&e.failed===0&&(o="failed without a failed assertion"),!o)return;let l=[...d.map(u=>u.message).filter(Boolean),n.trim()].filter(Boolean).join(`
3
3
  `).slice(0,4e3);return new a(`${t} ${o} for ${r} (exit code ${s??"unknown"}).`+(l?`
4
4
  ${l}`:""))}import{mkdtempSync as p,readFileSync as m,rmSync as g}from"node:fs";import{tmpdir as R}from"node:os";import{join as c}from"node:path";function h(t,r){if(!r)return;let s;try{s=m(r,"utf-8")}catch(e){if(e.code==="ENOENT")return;throw new Error("Could not read the current Vitest JSON report.")}try{let e=JSON.parse(s);if(!e||!Array.isArray(e.testResults))throw new Error("Invalid report")}catch{throw new Error("The current Vitest JSON report is malformed.")}return s}function b(){let t=p(c(R(),"aqe-vitest-report-")),r=c(t,"report.json"),s=!1;return{path:r,args:[`--outputFile=${r}`],read:e=>h(e,r),cleanup:()=>{if(!s){s=!0;try{g(t,{recursive:!0,force:!0})}catch{}}}}}function j(t){let r=t.some(n=>/(^|[\\/])vitest(\.cmd|\.js|\.mjs)?$/i.test(n)),s=t.some((n,i)=>n==="--reporter=json"||n==="--reporter"&&t[i+1]==="json"),e=t.some(n=>n.startsWith("--outputFile"));return r&&s&&!e}export{a,y as b,b as c,j as d};
@@ -1,5 +1,5 @@
1
- import{createRequire as __cr}from"module";const require=__cr(import.meta.url);if(process.argv.includes('--version')||process.argv.includes('-v')){console.log("3.14.6");process.exit(0)}
2
- var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as Z,freemem as ee,totalmem as te,loadavg as ie}from"os";var g=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as G}from"fs";import{execFile as Q}from"child_process";import{promisify as $}from"util";import{resolve as q,join as H}from"path";import{existsSync as L,readFileSync as U}from"fs";var _=$(Q),z={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},p=class{constructor(e,t){this.queue=e;this.options={...z,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=q(this.options.repoRoot,".git","refs","heads");if(!L(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=G(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
3
- `)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=q(this.options.repoRoot,".git","refs","heads"),o=H(i,e),r;try{r=U(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
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.14.8");process.exit(0)}
2
+ var P="quality-daemon",x=class{constructor(e){this.backend=e}backend;async get(e){return this.backend.kvGet(e,P)}async set(e,t){await this.backend.kvSet(e,t,P)}async search(e){return this.backend.kvSearch(e,P)}};import{cpus as Z,freemem as ee,totalmem as te,loadavg as ie}from"os";var p=class{queues={now:[],next:[],later:[]};_maxSize;constructor(e=1e3){this._maxSize=e}enqueue(e){return this.size>=this._maxSize&&(this.pruneExpired(),this.size>=this._maxSize)?!1:(this.queues[e.priority].push(e),!0)}dequeue(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(;i.length>0;){let o=i.shift();if(!(o.ttlMs&&e-o.createdAt>o.ttlMs))return o}}}peek(){let e=Date.now();for(let t of["now","next","later"]){let i=this.queues[t];for(let o of i)if(!o.ttlMs||e-o.createdAt<=o.ttlMs)return o}}drainPriority(e){let t=this.queues[e].splice(0),i=Date.now();return t.filter(o=>!o.ttlMs||i-o.createdAt<=o.ttlMs)}pruneExpired(){let e=0,t=Date.now();for(let i of["now","next","later"]){let o=this.queues[i].length;this.queues[i]=this.queues[i].filter(r=>!r.ttlMs||t-r.createdAt<=r.ttlMs),e+=o-this.queues[i].length}return e}get size(){return this.queues.now.length+this.queues.next.length+this.queues.later.length}get depths(){return{now:this.queues.now.length,next:this.queues.next.length,later:this.queues.later.length}}get isEmpty(){return this.size===0}clear(){this.queues.now=[],this.queues.next=[],this.queues.later=[]}};import{watch as G}from"fs";import{execFile as Q}from"child_process";import{promisify as $}from"util";import{resolve as q,join as H}from"path";import{existsSync as z,readFileSync as E}from"fs";var _=$(Q),L={repoRoot:process.cwd(),debounceMs:500,maxChangedFiles:200,pollIntervalMs:5e3},g=class{constructor(e,t){this.queue=e;this.options={...L,...t}}queue;watcher;pollTimer;options;lastKnownHeads=new Map;debounceTimer;_running=!1;_polling=!1;get running(){return this._running}async start(){if(this._running)return;let e=q(this.options.repoRoot,".git","refs","heads");if(!z(e))throw new Error(`Git refs directory not found: ${e}`);await this.snapshotHeads(),process.platform==="darwin"||process.platform==="win32"?this.watcher=G(e,{recursive:!0},(i,o)=>{o&&this.handleRefChange(o)}):(this.pollTimer=setInterval(()=>{this.poll().catch(i=>{console.debug("[GitWatcher] Poll error:",i)})},this.options.pollIntervalMs),this.pollTimer.unref?.()),this._running=!0}stop(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0),this.watcher&&(this.watcher.close(),this.watcher=void 0),this._running=!1}async poll(){if(this._polling)return[];this._polling=!0;let e=[];try{let{stdout:t}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let i of t.trim().split(`
3
+ `)){if(!i)continue;let[o,r]=i.split(" "),n=this.lastKnownHeads.get(o);n&&n!==r&&(e.push(o),await this.enqueueCommitAnalysis(o,r)),this.lastKnownHeads.set(o,r)}}catch{}finally{this._polling=!1}return e}handleRefChange(e){this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{this.processRefChange(e).catch(t=>{console.debug("[GitWatcher] Error processing ref change:",t)})},this.options.debounceMs)}async processRefChange(e){let t=e.replace(/\\/g,"/"),i=q(this.options.repoRoot,".git","refs","heads"),o=H(i,e),r;try{r=E(o,"utf-8").trim()}catch{return}this.lastKnownHeads.get(t)!==r&&(this.lastKnownHeads.set(t,r),await this.enqueueCommitAnalysis(t,r))}async enqueueCommitAnalysis(e,t){let i=[];try{let{stdout:n}=await _("git",["diff-tree","--no-commit-id","--name-only","-r",t],{cwd:this.options.repoRoot});i=n.trim().split(`
4
4
  `).filter(Boolean).slice(0,this.options.maxChangedFiles)}catch{}let o={type:"git_commit",branch:e,commitHash:t,changedFiles:i},r={id:`git-${t}-${Date.now()}`,priority:"next",payload:o,createdAt:Date.now(),source:"git-watcher",ttlMs:300*1e3};this.queue.enqueue(r)}async snapshotHeads(){try{let{stdout:e}=await _("git",["for-each-ref","--format=%(refname:short) %(objectname:short)","refs/heads/"],{cwd:this.options.repoRoot});for(let t of e.trim().split(`
5
- `)){if(!t)continue;let[i,o]=t.split(" ");this.lastKnownHeads.set(i,o)}}catch{}}};var E={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...E,...t}}queue;options;async analyze(e,t,i){let o=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!o)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let r=o,n={line:e.overall.line-r.overall.line,branch:e.overall.branch-r.overall.branch,function:e.overall.function-r.overall.function,statement:e.overall.statement-r.overall.statement},s=n.line<-this.options.regressionThreshold||n.branch<-this.options.regressionThreshold,a=i??Object.keys(e.files),u=[],c=[];for(let d of a){let l=e.files[d],m=r.files[d];if(!l)continue;let M=m?l.line-m.line:0,I=m?l.branch-m.branch:0,D=m?l.uncoveredLines.filter(T=>!m.uncoveredLines.includes(T)):l.uncoveredLines;if((M!==0||I!==0||D.length>0)&&u.push({file:d,lineDelta:M,branchDelta:I,newUncoveredLines:D}),l.line<this.options.gapThreshold){let T=this.computeRiskScore(l,D.length);c.push({file:d,uncoveredLines:l.uncoveredLines,currentCoverage:l.line,riskScore:T})}}return(s||c.length>0)&&this.enqueueTestSuggestion(e,r,c),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:u.length,gapCount:c.length}),{regressionDetected:s,overallDelta:n,affectedFiles:u,newGaps:c}}async buildSnapshot(e){let t=await e.get("coverage:latest");if(t)return{timestamp:Date.now(),overall:{line:t.line,branch:t.branch,function:t.function,statement:t.statement},files:t.files??{}}}computeRiskScore(e,t){let o=1-Math.min(100,Math.max(0,e.line))/100,r=Math.min(t/50,1);return Math.min(1,o*.6+r*.4)}enqueueTestSuggestion(e,t,i){let o={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},r={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:o,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(r)}};import{execFile as j}from"child_process";import{promisify as B}from"util";var J=B(j),K={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...K,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],o=[],r=0;for(let[s,a]of Object.entries(t)){let u=a.filter(m=>m.conclusion==="failure").length,c=a.length>0?(a.length-u)/a.length*100:100,d=this.countConsecutiveFailures(a),l=a[0]?.conclusion??"unknown";l==="failure"&&r++,d>=this.options.flakyThreshold&&(o.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:u,successRate:Math.round(c*10)/10,lastConclusion:l,consecutiveFailures:d})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:r,flakyWorkflows:o,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await J("gh",e,{timeout:15e3});return JSON.parse(t).map(o=>({name:o.name,status:o.status,conclusion:o.conclusion??"pending",headBranch:o.headBranch,runNumber:o.number,databaseId:o.databaseId,createdAt:o.createdAt}))}catch{return[]}}groupByWorkflow(e){let t={};for(let i of e)t[i.name]||(t[i.name]=[]),t[i.name].push(i);for(let i of Object.keys(t))t[i]=t[i].slice(0,this.options.runsPerWorkflow);return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,o)=>i+o.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},o={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(o)}};var V={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...V,...e}}async suggest(e,t,i){let o=[],r=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of r){let a=t.includes(s.file),u=this.determinePriority(s,a),c=this.determineTestType(s.file),d=this.estimateEffort(s);o.push({id:`suggestion-${Date.now()}-${o.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:c,description:this.generateDescription(s,c),priority:u,estimatedEffort:d,createdAt:Date.now(),status:"pending"})}o.sort((s,a)=>{let u={high:0,medium:1,low:2};return u[s.priority]-u[a.priority]});let n=o.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let o=await i.get(`${this.options.memoryPrefix}:list`);if(!o)return!1;let r=o.findIndex(s=>s.id===e);if(r===-1)return!1;let n=o.map((s,a)=>a===r?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,o=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${o}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let r=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,r),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:r.length,lastUpdated:Date.now()})}};var Y={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...Y,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),o=new Date().toISOString().split("T")[0],r=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(o,t);await e.set(`${this.options.memoryPrefix}:report:${o}`,s),this.lastRunDate=o;let a={timestamp:Date.now(),patternsConsolidated:r,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,o=Date.now();for(let r of t){if(r.endsWith(":snapshot")||r.endsWith(":list"))continue;let n=await e.get(r);n&&typeof n.timestamp=="number"&&o-n.timestamp>this.options.maxEntryAge&&(await e.set(r,{pruned:!0,prunedAt:o}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};import{writeFileSync as R,mkdirSync as W,readdirSync as S,readFileSync as A,unlinkSync as N}from"fs";import{join as b,resolve as X}from"path";var F={notificationsDir:X(process.cwd(),".agentic-qe","notifications"),maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??F.notificationsDir,this.maxNotifications=e?.maxNotifications??F.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){W(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=S(this.notificationsDir).filter(r=>r.endsWith(".json")).sort().reverse(),o=[];for(let r of i){if(o.length>=t)break;try{let n=A(b(this.notificationsDir,r),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;o.push(s)}catch{}}return o}catch{return[]}}markRead(e){try{let t=S(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),r={...JSON.parse(A(i,"utf-8")),read:!0};return R(i,JSON.stringify(r,null,2)),!0}catch{return!1}}clear(){try{let e=S(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)N(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{W(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);R(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=S(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)N(b(this.notificationsDir,i))}catch{}}};var C={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},O=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??C.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??C.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??C.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??C.cpuThreshold,memoryThreshold:e?.memoryThreshold??C.memoryThreshold},this.queue=new g,this.gitWatcher=new p(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs),this.tickTimer.unref?.())}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let o=this.queue.dequeue();if(!o)break;await this.handleQueueItem(o,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":{this._commitsAnalyzed++;let o=await this.coverageDelta.buildSnapshot(t);if(o){let r=await this.coverageDelta.analyze(o,t,i.changedFiles);if(r.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${r.overallDelta.line.toFixed(1)}% (${r.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:r.overallDelta,commit:i.commitHash}}),r.newGaps.length>0){let n=await this.testSuggester.suggest(r.newGaps,i.changedFiles,t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break}case"coverage_delta":{let o=await this.testSuggester.getPending(t);o.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${o.length} test suggestions awaiting review`,severity:"info",metadata:{count:o.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let o={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,o);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);i&&(this._coverageHealth=Math.round((i.overall.line+i.overall.branch+i.overall.function+i.overall.statement)/4),this._lastCoverageCheck=t)}catch{}}isResourceConstrained(){if(1-ee()/te()>this.config.memoryThreshold)return!0;let t=Z().length;return(t>0?ie()[0]/t:0)>this.config.cpuThreshold}};export{x as a,O as b};
5
+ `)){if(!t)continue;let[i,o]=t.split(" ");this.lastKnownHeads.set(i,o)}}catch{}}};var U={regressionThreshold:2,gapThreshold:60,memoryPrefix:"quality-daemon:coverage"},f=class{constructor(e,t){this.queue=e;this.options={...U,...t}}queue;options;async analyze(e,t,i){let o=await t.get(`${this.options.memoryPrefix}:snapshot`);if(await t.set(`${this.options.memoryPrefix}:snapshot`,e),!o)return{regressionDetected:!1,overallDelta:{line:0,branch:0,function:0,statement:0},affectedFiles:[],newGaps:[]};let r=o,n={line:e.overall.line-r.overall.line,branch:e.overall.branch-r.overall.branch,function:e.overall.function-r.overall.function,statement:e.overall.statement-r.overall.statement},s=n.line<-this.options.regressionThreshold||n.branch<-this.options.regressionThreshold,a=i??Object.keys(e.files),u=[],c=[];for(let d of a){let l=e.files[d],m=r.files[d];if(!l)continue;let M=m?l.line-m.line:0,I=m?l.branch-m.branch:0,D=m?l.uncoveredLines.filter(T=>!m.uncoveredLines.includes(T)):l.uncoveredLines;if((M!==0||I!==0||D.length>0)&&u.push({file:d,lineDelta:M,branchDelta:I,newUncoveredLines:D}),l.line<this.options.gapThreshold){let T=this.computeRiskScore(l,D.length);c.push({file:d,uncoveredLines:l.uncoveredLines,currentCoverage:l.line,riskScore:T})}}return(s||c.length>0)&&this.enqueueTestSuggestion(e,r,c),await t.set(`${this.options.memoryPrefix}:delta`,{timestamp:Date.now(),overallDelta:n,regressionDetected:s,affectedFileCount:u.length,gapCount:c.length}),{regressionDetected:s,overallDelta:n,affectedFiles:u,newGaps:c}}async buildSnapshot(e){let t=await e.get("coverage:latest");if(t)return{timestamp:Date.now(),overall:{line:t.line,branch:t.branch,function:t.function,statement:t.statement},files:t.files??{}}}computeRiskScore(e,t){let o=1-Math.min(100,Math.max(0,e.line))/100,r=Math.min(t/50,1);return Math.min(1,o*.6+r*.4)}enqueueTestSuggestion(e,t,i){let o={type:"coverage_delta",previousSnapshot:`snapshot-${t.timestamp}`,currentSnapshot:`snapshot-${e.timestamp}`},r={id:`coverage-delta-${Date.now()}`,priority:i.some(n=>n.riskScore>.8)?"now":"next",payload:o,createdAt:Date.now(),source:"coverage-delta",ttlMs:600*1e3};this.queue.enqueue(r)}};import{execFile as j}from"child_process";import{promisify as B}from"util";var J=B(j),K={runsPerWorkflow:10,flakyThreshold:3,repo:""},y=class{constructor(e,t){this.queue=e;this.options={...K,...t}}queue;options;async check(){let e=await this.fetchRecentRuns(),t=this.groupByWorkflow(e),i=[],o=[],r=0;for(let[s,a]of Object.entries(t)){let u=a.filter(m=>m.conclusion==="failure").length,c=a.length>0?(a.length-u)/a.length*100:100,d=this.countConsecutiveFailures(a),l=a[0]?.conclusion??"unknown";l==="failure"&&r++,d>=this.options.flakyThreshold&&(o.push(s),this.enqueueFailureAlert(s,a[0])),i.push({name:s,recentRuns:a.length,failedRuns:u,successRate:Math.round(c*10)/10,lastConclusion:l,consecutiveFailures:d})}let n=this.calculateHealthScore(i);return{timestamp:Date.now(),workflows:i,failingWorkflows:r,flakyWorkflows:o,healthScore:n}}async fetchRecentRuns(){try{let e=["run","list","--limit",String(this.options.runsPerWorkflow*5),"--json","name,status,conclusion,headBranch,number,databaseId,createdAt"];this.options.repo&&e.push("--repo",this.options.repo);let{stdout:t}=await J("gh",e,{timeout:15e3});return JSON.parse(t).map(o=>({name:o.name,status:o.status,conclusion:o.conclusion??"pending",headBranch:o.headBranch,runNumber:o.number,databaseId:o.databaseId,createdAt:o.createdAt}))}catch{return[]}}groupByWorkflow(e){let t={};for(let i of e)t[i.name]||(t[i.name]=[]),t[i.name].push(i);for(let i of Object.keys(t))t[i]=t[i].slice(0,this.options.runsPerWorkflow);return t}countConsecutiveFailures(e){let t=0;for(let i of e)if(i.conclusion==="failure")t++;else break;return t}calculateHealthScore(e){if(e.length===0)return 100;let t=e.reduce((i,o)=>i+o.successRate,0)/e.length;return Math.round(t)}enqueueFailureAlert(e,t){let i={type:"ci_failure",workflowName:e,runId:t.databaseId,conclusion:t.conclusion},o={id:`ci-failure-${e}-${Date.now()}`,priority:"now",payload:i,createdAt:Date.now(),source:"ci-monitor",ttlMs:1800*1e3};this.queue.enqueue(o)}};var V={memoryPrefix:"quality-daemon:suggestions",maxSuggestions:100,minRiskScore:.3},v=class{options;constructor(e){this.options={...V,...e}}async suggest(e,t,i){let o=[],r=e.filter(s=>s.riskScore>=this.options.minRiskScore);for(let s of r){let a=t.includes(s.file),u=this.determinePriority(s,a),c=this.determineTestType(s.file),d=this.estimateEffort(s);o.push({id:`suggestion-${Date.now()}-${o.length}`,file:s.file,uncoveredLines:s.uncoveredLines.slice(0,50),suggestedTestType:c,description:this.generateDescription(s,c),priority:u,estimatedEffort:d,createdAt:Date.now(),status:"pending"})}o.sort((s,a)=>{let u={high:0,medium:1,low:2};return u[s.priority]-u[a.priority]});let n=o.slice(0,this.options.maxSuggestions);return await this.storeSuggestions(n,i),n}async getPending(e){return(await e.get(`${this.options.memoryPrefix}:list`)??[]).filter(i=>i.status==="pending")}async updateStatus(e,t,i){let o=await i.get(`${this.options.memoryPrefix}:list`);if(!o)return!1;let r=o.findIndex(s=>s.id===e);if(r===-1)return!1;let n=o.map((s,a)=>a===r?{...s,status:t}:s);return await i.set(`${this.options.memoryPrefix}:list`,n),!0}determinePriority(e,t){return e.riskScore>.8?"high":t||e.riskScore>.5?"medium":"low"}determineTestType(e){return e.includes("/api/")||e.includes("/routes/")||e.includes("/handlers/")?"integration":e.includes("/e2e/")||e.includes("/pages/")||e.includes("/views/")?"e2e":"unit"}estimateEffort(e){return e.uncoveredLines.length<=10?"small":e.uncoveredLines.length<=50?"medium":"large"}generateDescription(e,t){let i=e.uncoveredLines.length,o=Math.round(e.currentCoverage);return`Add ${t} tests for ${e.file} (${i} uncovered lines, ${o}% coverage, risk ${(e.riskScore*100).toFixed(0)}%)`}async storeSuggestions(e,t){let r=[...(await t.get(`${this.options.memoryPrefix}:list`)??[]).filter(n=>n.status!=="pending"),...e].slice(-this.options.maxSuggestions);await t.set(`${this.options.memoryPrefix}:list`,r),await t.set(`${this.options.memoryPrefix}:count`,{pending:e.length,total:r.length,lastUpdated:Date.now()})}};var Y={memoryPrefix:"quality-daemon:nightly",maxEntryAge:6048e5,nightlyHour:2},w=class{constructor(e,t){this.queue=e;this.options={...Y,...t}}queue;options;lastRunDate;shouldRun(){let e=new Date,t=e.toISOString().split("T")[0];return this.lastRunDate===t?!1:e.getHours()>=this.options.nightlyHour}scheduleIfDue(){if(!this.shouldRun())return!1;let e={type:"nightly",tasks:["consolidate_patterns","prune_expired","generate_report"]},t={id:`nightly-${Date.now()}`,priority:"later",payload:e,createdAt:Date.now(),source:"nightly-consolidation",ttlMs:720*60*1e3};return this.queue.enqueue(t)}async execute(e,t){let i=Date.now(),o=new Date().toISOString().split("T")[0],r=await this.consolidatePatterns(e),n=await this.pruneExpired(e),s=this.generateReport(o,t);await e.set(`${this.options.memoryPrefix}:report:${o}`,s),this.lastRunDate=o;let a={timestamp:Date.now(),patternsConsolidated:r,entriesPruned:n,reportGenerated:!0,durationMs:Date.now()-i};return await e.set(`${this.options.memoryPrefix}:last-result`,a),a}async getLastResult(e){return e.get(`${this.options.memoryPrefix}:last-result`)}async consolidatePatterns(e){let t=await e.search("quality-daemon:*"),i=0;return await e.get("quality-daemon:suggestions:count")&&i++,await e.get("quality-daemon:coverage:delta")&&i++,i}async pruneExpired(e){let t=await e.search("quality-daemon:*"),i=0,o=Date.now();for(let r of t){if(r.endsWith(":snapshot")||r.endsWith(":list"))continue;let n=await e.get(r);n&&typeof n.timestamp=="number"&&o-n.timestamp>this.options.maxEntryAge&&(await e.set(r,{pruned:!0,prunedAt:o}),i++)}return i}generateReport(e,t){return{date:e,coverageHealth:t.coverageHealth??0,ciHealth:t.ciHealth??0,commitsAnalyzed:t.commitsAnalyzed??0,suggestionsGenerated:t.suggestionsGenerated??0,notificationsSent:t.notificationsSent??0,queueDepthAvg:t.queueDepthAvg??0,daemonUptime:t.uptimeSeconds??0}}};import{writeFileSync as R,mkdirSync as W,readdirSync as S,readFileSync as A,unlinkSync as N}from"fs";import{join as b,resolve as X}from"path";var F={notificationsDir:X(process.cwd(),".agentic-qe","notifications"),maxNotifications:200},k=class{notificationsDir;maxNotifications;webhookUrl;urlValidator;_sentCount=0;constructor(e){this.notificationsDir=e?.notificationsDir??F.notificationsDir,this.maxNotifications=e?.maxNotifications??F.maxNotifications,this.webhookUrl=e?.webhookUrl,this.urlValidator=e?.urlValidator}get sentCount(){return this._sentCount}initialize(){W(this.notificationsDir,{recursive:!0})}async send(e){let t={...e,id:`notif-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:Date.now(),read:!1};return this.writeToFile(t),this.webhookUrl&&await this.sendWebhook(t),this._sentCount++,this.pruneOldNotifications(),t}list(e){let t=e?.limit??50;try{let i=S(this.notificationsDir).filter(r=>r.endsWith(".json")).sort().reverse(),o=[];for(let r of i){if(o.length>=t)break;try{let n=A(b(this.notificationsDir,r),"utf-8"),s=JSON.parse(n);if(e?.unreadOnly&&s.read||e?.type&&s.type!==e.type)continue;o.push(s)}catch{}}return o}catch{return[]}}markRead(e){try{let t=S(this.notificationsDir).filter(n=>n.endsWith(`-${e}.json`));if(t.length===0)return!1;let i=b(this.notificationsDir,t[0]),r={...JSON.parse(A(i,"utf-8")),read:!0};return R(i,JSON.stringify(r,null,2)),!0}catch{return!1}}clear(){try{let e=S(this.notificationsDir).filter(t=>t.endsWith(".json"));for(let t of e)N(b(this.notificationsDir,t));return e.length}catch{return 0}}writeToFile(e){try{W(this.notificationsDir,{recursive:!0});let t=`${e.timestamp}-${e.id}.json`,i=b(this.notificationsDir,t);R(i,JSON.stringify(e,null,2))}catch(t){console.debug("[NotificationService] Failed to write notification:",t)}}async sendWebhook(e){if(this.webhookUrl){if(this.urlValidator&&!this.urlValidator(this.webhookUrl)){console.warn("[NotificationService] Webhook URL blocked by SSRF guard:",this.webhookUrl);return}try{let t=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:AbortSignal.timeout(5e3)});t.ok||console.debug(`[NotificationService] Webhook returned ${t.status}`)}catch(t){console.debug("[NotificationService] Webhook delivery failed:",t)}}}pruneOldNotifications(){try{let e=S(this.notificationsDir).filter(i=>i.endsWith(".json")).sort();if(e.length<=this.maxNotifications)return;let t=e.slice(0,e.length-this.maxNotifications);for(let i of t)N(b(this.notificationsDir,i))}catch{}}};var C={tickIntervalMs:3e4,ciPollIntervalMs:5*6e4,coverageCheckIntervalMs:2*6e4,cpuThreshold:.7,memoryThreshold:.8},O=class{queue;gitWatcher;coverageDelta;ciMonitor;testSuggester;nightlyConsolidation;notificationService;tickTimer;_running=!1;_startedAt=0;_tickCount=0;_lastTickAt;_throttled=!1;_commitsAnalyzed=0;_suggestionsGenerated=0;_ciHealth=100;_coverageHealth=100;_lastCICheck;_lastCoverageCheck;_memory;config;constructor(e){this.config={tickIntervalMs:e?.tickIntervalMs??C.tickIntervalMs,ciPollIntervalMs:e?.ciPollIntervalMs??C.ciPollIntervalMs,coverageCheckIntervalMs:e?.coverageCheckIntervalMs??C.coverageCheckIntervalMs,cpuThreshold:e?.cpuThreshold??C.cpuThreshold,memoryThreshold:e?.memoryThreshold??C.memoryThreshold},this.queue=new p,this.gitWatcher=new g(this.queue,e?.git),this.coverageDelta=new f(this.queue,e?.coverage),this.ciMonitor=new y(this.queue,e?.ci),this.testSuggester=new v(e?.suggestions),this.nightlyConsolidation=new w(this.queue,e?.nightly),this.notificationService=new k(e?.notifications)}get running(){return this._running}async start(e){this._running||(this._memory=e,this._running=!0,this._startedAt=Date.now(),this.notificationService.initialize(),await this.gitWatcher.start().catch(t=>{console.debug("[QualityDaemon] Git watcher failed to start:",t)}),this.scheduleTick())}async stop(){this._running&&(this._running=!1,this.tickTimer&&(clearTimeout(this.tickTimer),this.tickTimer=void 0),this.gitWatcher.stop(),this._memory&&await this._memory.set("quality-daemon:state",{stoppedAt:Date.now(),tickCount:this._tickCount,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated}))}getStatus(){return{running:this._running,uptimeSeconds:this._running?Math.floor((Date.now()-this._startedAt)/1e3):0,tickCount:this._tickCount,queueDepth:this.queue.depths,lastTickAt:this._lastTickAt,throttled:this._throttled,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,ciHealth:this._ciHealth,coverageHealth:this._coverageHealth,lastCICheck:this._lastCICheck,lastCoverageCheck:this._lastCoverageCheck}}scheduleTick(){this._running&&(this.tickTimer=setTimeout(()=>this.tick(),this.config.tickIntervalMs),this.tickTimer.unref?.())}async tick(){if(!(!this._running||!this._memory)){if(this._tickCount++,this._lastTickAt=Date.now(),this._throttled=this.isResourceConstrained(),this._throttled){await this.processNowItems(this._memory),this.scheduleTick();return}await this.processQueue(this._memory),await this.runPeriodicChecks(this._memory),this.nightlyConsolidation.scheduleIfDue(),this.queue.pruneExpired(),this.scheduleTick()}}async processQueue(e){let t=0,i=10;for(;t<i&&!this.queue.isEmpty;){let o=this.queue.dequeue();if(!o)break;await this.handleQueueItem(o,e),t++}}async processNowItems(e){let t=this.queue.drainPriority("now");for(let i of t)await this.handleQueueItem(i,e)}async handleQueueItem(e,t){let i=e.payload;switch(i.type){case"git_commit":{this._commitsAnalyzed++;let o=await this.coverageDelta.buildSnapshot(t);if(o){let r=await this.coverageDelta.analyze(o,t,i.changedFiles);if(r.regressionDetected&&await this.notificationService.send({type:"coverage_drop",title:"Coverage Regression Detected",message:`Line coverage delta: ${r.overallDelta.line.toFixed(1)}% (${r.affectedFiles.length} files affected)`,severity:"high",metadata:{delta:r.overallDelta,commit:i.commitHash}}),r.newGaps.length>0){let n=await this.testSuggester.suggest(r.newGaps,i.changedFiles,t);this._suggestionsGenerated+=n.length,n.length>0&&await this.notificationService.send({type:"suggestion_available",title:"New Test Suggestions Available",message:`${n.length} test suggestions generated for uncovered code`,severity:"info",metadata:{count:n.length}})}}break}case"coverage_delta":{let o=await this.testSuggester.getPending(t);o.length>0&&await this.notificationService.send({type:"suggestion_available",title:"Test Suggestions Pending",message:`${o.length} test suggestions awaiting review`,severity:"info",metadata:{count:o.length}});break}case"gate_failure":await this.notificationService.send({type:"gate_failure",title:`Quality Gate Failed: ${i.gateName}`,message:`Score ${i.score} below threshold ${i.threshold}`,severity:"critical",metadata:{gate:i.gateName,score:i.score,threshold:i.threshold}});break;case"ci_failure":await this.notificationService.send({type:"ci_failure",title:`CI Failure: ${i.workflowName}`,message:`Workflow ${i.workflowName} run #${i.runId} concluded: ${i.conclusion}`,severity:"high",metadata:{workflow:i.workflowName,runId:i.runId}});break;case"nightly":{let o={coverageHealth:this._coverageHealth,ciHealth:this._ciHealth,commitsAnalyzed:this._commitsAnalyzed,suggestionsGenerated:this._suggestionsGenerated,notificationsSent:this.notificationService.sentCount,queueDepthAvg:this.queue.size,uptimeSeconds:Math.floor((Date.now()-this._startedAt)/1e3)};await this.nightlyConsolidation.execute(t,o);break}default:console.warn("[QualityDaemon] Unhandled payload type:",i.type)}}async runPeriodicChecks(e){let t=Date.now();if(!this._lastCICheck||t-this._lastCICheck>=this.config.ciPollIntervalMs)try{let i=await this.ciMonitor.check();this._ciHealth=i.healthScore,this._lastCICheck=t,i.flakyWorkflows.length>0&&await this.notificationService.send({type:"flaky_detected",title:"Flaky Workflows Detected",message:`${i.flakyWorkflows.length} workflows showing repeated failures: ${i.flakyWorkflows.join(", ")}`,severity:"medium",metadata:{workflows:i.flakyWorkflows}})}catch{}if(!this._lastCoverageCheck||t-this._lastCoverageCheck>=this.config.coverageCheckIntervalMs)try{let i=await this.coverageDelta.buildSnapshot(e);i&&(this._coverageHealth=Math.round((i.overall.line+i.overall.branch+i.overall.function+i.overall.statement)/4),this._lastCoverageCheck=t)}catch{}}isResourceConstrained(){if(1-ee()/te()>this.config.memoryThreshold)return!0;let t=Z().length;return(t>0?ie()[0]/t:0)>this.config.cpuThreshold}};export{x as a,O as b};