@testmuai/kane-cli 0.8.13 → 0.8.15

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 (304) hide show
  1. package/dist/{ChatSurface-B6ZIO3JL.js → ChatSurface-2GPR4S7I.js} +3 -3
  2. package/dist/{ChromeProfilePicker-QSICCUMV.js → ChromeProfilePicker-XAZGCJKR.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-LLLNSKW2.js → CliFeedbackPrompt-4SILDU7S.js} +1 -1
  4. package/dist/{CliUploadProgress-N5IY66T2.js → CliUploadProgress-OAQBY55Y.js} +1 -1
  5. package/dist/{ConfigView-UQIRPENS.js → ConfigView-FDBMJC26.js} +1 -1
  6. package/dist/EvidenceViewOffer-YSNRKKPC.js +2 -0
  7. package/dist/FolderPicker-XCTJ5447.js +2 -0
  8. package/dist/{InfoBox-ZGSLEOPE.js → InfoBox-ZPUBB7J4.js} +1 -1
  9. package/dist/{LinksBox-JFT44YUK.js → LinksBox-MNNNOH23.js} +1 -1
  10. package/dist/{ProfilesView-WZSPK3HF.js → ProfilesView-GY5QCIT3.js} +1 -1
  11. package/dist/{ProjectPicker-SBBGVF4L.js → ProjectPicker-UCHMCNFV.js} +1 -1
  12. package/dist/{SaveSessionPrompt-F3563T3C.js → SaveSessionPrompt-ATVHKAHN.js} +1 -1
  13. package/dist/ScrollbackTap-QHJOFYMC.js +2 -0
  14. package/dist/SingleShotApp-IPNZBFXB.js +2 -0
  15. package/dist/{SummaryBox-6N6NESLI.js → SummaryBox-2DTNE25L.js} +1 -1
  16. package/dist/TestMdRunView-2FQIEI5W.js +2 -0
  17. package/dist/{TestrunEvidenceTable-JLJBJ76Q.js → TestrunEvidenceTable-6UE5EMON.js} +1 -1
  18. package/dist/{WhoamiView-PNVUCWLB.js → WhoamiView-TFCHIOW5.js} +1 -1
  19. package/dist/agent-parse-XMWVKCRD.js +2 -0
  20. package/dist/{app-download-NNB52ZRJ.js → app-download-N7MLJQ42.js} +1 -1
  21. package/dist/attach-target-V6LECVES.js +2 -0
  22. package/dist/{auth-JIDDELKY.js → auth-IQPCVCZK.js} +1 -1
  23. package/dist/{binary-LXYAW7WQ.js → binary-VML7EGV4.js} +1 -1
  24. package/dist/bind-YV6V5AI6.js +15 -0
  25. package/dist/{bootstrap-THOC3SS7.js → bootstrap-KCPWDBLX.js} +1 -1
  26. package/dist/bridge-5UKX7YIO.js +2 -0
  27. package/dist/{changelog-BSMZXLTG.js → changelog-CJFWGRIL.js} +1 -1
  28. package/dist/chat-committer-HDE3TP5I.js +2 -0
  29. package/dist/chat-controller-3EPK7UZG.js +2 -0
  30. package/dist/chunk-27ERHOW3.js +2 -0
  31. package/dist/{chunk-RN5ERSV2.js → chunk-2WRBCTNM.js} +1 -1
  32. package/dist/chunk-3D5MKSG3.js +5 -0
  33. package/dist/{chunk-FNIL4G3V.js → chunk-3GELV4IN.js} +3 -3
  34. package/dist/{chunk-EEFZXZTZ.js → chunk-3IXEARDX.js} +1 -1
  35. package/dist/chunk-3N6IAVD5.js +7 -0
  36. package/dist/{chunk-DXFMELKC.js → chunk-4TMQTSIO.js} +1 -1
  37. package/dist/chunk-52WM3XYO.js +4 -0
  38. package/dist/{chunk-R7QAS6LZ.js → chunk-55YDTPB7.js} +1 -1
  39. package/dist/{chunk-477DYMXZ.js → chunk-5HTSKF5K.js} +1 -1
  40. package/dist/{chunk-IDX3TOPY.js → chunk-5LJRZI7S.js} +1 -1
  41. package/dist/chunk-66MOZKD2.js +2 -0
  42. package/dist/chunk-6DHEOPXX.js +9 -0
  43. package/dist/{chunk-NU45ROHH.js → chunk-6GLFQHSW.js} +2 -2
  44. package/dist/chunk-6K4FDYMH.js +89 -0
  45. package/dist/{chunk-7GUFVQOQ.js → chunk-6L5RV62W.js} +1 -1
  46. package/dist/{chunk-TDNM22BQ.js → chunk-74FHTDEE.js} +1 -1
  47. package/dist/chunk-7EGIX6Y4.js +8 -0
  48. package/dist/chunk-7O54QURK.js +2 -0
  49. package/dist/chunk-7WDPU33M.js +2 -0
  50. package/dist/{chunk-BTBUIL4Q.js → chunk-7X4R6464.js} +1 -1
  51. package/dist/{chunk-FUP4AP6J.js → chunk-A557OSRS.js} +1 -1
  52. package/dist/chunk-AHXOKBVE.js +7 -0
  53. package/dist/{chunk-DNNZ353O.js → chunk-ALCE5RLK.js} +1 -1
  54. package/dist/{chunk-I75FRXKE.js → chunk-AYJ2YZP5.js} +1 -1
  55. package/dist/chunk-BMVE73M7.js +21 -0
  56. package/dist/chunk-CAOZKSQ3.js +8 -0
  57. package/dist/{chunk-BJAHVN2F.js → chunk-CNPIJFZM.js} +1 -1
  58. package/dist/{chunk-EV64VI66.js → chunk-CRZUBDJ3.js} +1 -1
  59. package/dist/{chunk-PUM5J56E.js → chunk-D6GBOFK5.js} +1 -1
  60. package/dist/{chunk-YEZYO5QH.js → chunk-DMCEGMGB.js} +1 -1
  61. package/dist/{chunk-TMRLBSIA.js → chunk-DMT3W26F.js} +1 -1
  62. package/dist/{chunk-XS3HIVNS.js → chunk-EDQZIEPJ.js} +1 -1
  63. package/dist/{chunk-VJ3ES3RR.js → chunk-EFTRH35G.js} +1 -1
  64. package/dist/{chunk-Q4YAJJPP.js → chunk-EJXBKCNF.js} +1 -1
  65. package/dist/{chunk-NUWOQS6L.js → chunk-EPE2ELDH.js} +1 -1
  66. package/dist/{chunk-WIAZN7G4.js → chunk-FFVNISYH.js} +1 -1
  67. package/dist/chunk-FQNQVC5O.js +5 -0
  68. package/dist/chunk-FXO7JKMZ.js +4 -0
  69. package/dist/chunk-GP7WD4UY.js +4 -0
  70. package/dist/{chunk-K2UEVCIJ.js → chunk-GSDXZS4U.js} +1 -1
  71. package/dist/{chunk-J2UN2AHO.js → chunk-GZ65ZA4C.js} +1 -1
  72. package/dist/chunk-H6TNBKGR.js +5 -0
  73. package/dist/{chunk-GILD6RGH.js → chunk-HLCETZ73.js} +1 -1
  74. package/dist/chunk-HOA4VWSD.js +5 -0
  75. package/dist/{chunk-33GXXC2L.js → chunk-HYTBEPC2.js} +1 -1
  76. package/dist/{chunk-PWRIG6UB.js → chunk-IAHOLH5W.js} +1 -1
  77. package/dist/chunk-IE3OO5GI.js +2 -0
  78. package/dist/{chunk-UF4JZXEE.js → chunk-JCMHB4KH.js} +1 -1
  79. package/dist/{chunk-KV5BOFPK.js → chunk-JFUFWICY.js} +2 -2
  80. package/dist/{chunk-FE6XRABM.js → chunk-JGAMMOUC.js} +1 -1
  81. package/dist/{chunk-CAO3XRA2.js → chunk-JL3L6KOG.js} +1 -1
  82. package/dist/chunk-JQCOKL6U.js +15 -0
  83. package/dist/{chunk-IZU5ND2C.js → chunk-JSS22MFY.js} +9 -9
  84. package/dist/chunk-JVEZBJJ7.js +2 -0
  85. package/dist/{chunk-3SP4JVDN.js → chunk-KALEPJAV.js} +2 -2
  86. package/dist/{chunk-AIVOYTYQ.js → chunk-KUS324VE.js} +1 -1
  87. package/dist/chunk-KZG4E5RM.js +2 -0
  88. package/dist/{chunk-KSLJOUH4.js → chunk-LJGAXIDU.js} +1 -1
  89. package/dist/chunk-M36MOFJW.js +9 -0
  90. package/dist/{chunk-ZOSY2PJM.js → chunk-MLYNVJNH.js} +1 -1
  91. package/dist/{chunk-XL6HDWM3.js → chunk-N3CVR4Z2.js} +1 -1
  92. package/dist/{chunk-2X3TANEV.js → chunk-NLEA6NPU.js} +1 -1
  93. package/dist/{chunk-4PARDPK2.js → chunk-NUJVYAI4.js} +1 -1
  94. package/dist/{chunk-3M2D7UUI.js → chunk-NWNG5UWD.js} +1 -1
  95. package/dist/{chunk-IWVA37B6.js → chunk-O25AL4B7.js} +1 -1
  96. package/dist/{chunk-KAZGHWGK.js → chunk-O3XBIURC.js} +1 -1
  97. package/dist/chunk-O66WXOOC.js +5 -0
  98. package/dist/{chunk-W2UYUV47.js → chunk-OFWJBOGT.js} +2 -2
  99. package/dist/{chunk-DMLYUTS4.js → chunk-OGDAWNFY.js} +1 -1
  100. package/dist/chunk-OPL2MIQG.js +2 -0
  101. package/dist/{chunk-F5AI3UVS.js → chunk-ORQGQSWG.js} +2 -2
  102. package/dist/{chunk-7KIIM6H7.js → chunk-OWGFFJKK.js} +1 -1
  103. package/dist/{chunk-6AZNGOLH.js → chunk-PGXJ275T.js} +1 -1
  104. package/dist/chunk-Q77QO3PC.js +17 -0
  105. package/dist/{chunk-XH2KDLZO.js → chunk-QVLYK5JL.js} +1 -1
  106. package/dist/{chunk-UZCSVEWP.js → chunk-QXRT6HSV.js} +1 -1
  107. package/dist/{chunk-LWQNRZH3.js → chunk-R7QMZBBH.js} +1 -1
  108. package/dist/{chunk-DIM5X2FR.js → chunk-RI4ILZZC.js} +1 -1
  109. package/dist/{chunk-D4G3SEBU.js → chunk-RQILLYSP.js} +1 -1
  110. package/dist/chunk-S4JUCBCT.js +7 -0
  111. package/dist/{chunk-VYMMGWVO.js → chunk-SHSXOYKT.js} +1 -1
  112. package/dist/{chunk-XAM5E27U.js → chunk-SIYSKT6I.js} +1 -1
  113. package/dist/chunk-SWTJMTBY.js +29 -0
  114. package/dist/chunk-T4R26WER.js +9 -0
  115. package/dist/{chunk-O5U6EAL3.js → chunk-TCAHDVII.js} +1 -1
  116. package/dist/{chunk-LAQBCZ5A.js → chunk-TEHZUSUY.js} +1 -1
  117. package/dist/chunk-TNBF5OMZ.js +2 -0
  118. package/dist/chunk-TU6IMGWO.js +2 -0
  119. package/dist/{chunk-NM76SG3S.js → chunk-TVELOH5A.js} +1 -1
  120. package/dist/chunk-UHSNUUX3.js +35 -0
  121. package/dist/{chunk-5G22NOZK.js → chunk-UHT5SVP5.js} +1 -1
  122. package/dist/{chunk-KXUTO5WC.js → chunk-UZIMYV5U.js} +1 -1
  123. package/dist/chunk-VOTIGXQ4.js +16 -0
  124. package/dist/{chunk-MXDWS7S4.js → chunk-VZDLRJ5N.js} +7 -7
  125. package/dist/{chunk-3FXNQTCE.js → chunk-W77SZLFC.js} +1 -1
  126. package/dist/{chunk-OHK6V7JX.js → chunk-WFBJNVMQ.js} +1 -1
  127. package/dist/{chunk-N2I23ANS.js → chunk-WNB2IYHY.js} +1 -1
  128. package/dist/chunk-XSUJJB7Z.js +11 -0
  129. package/dist/{chunk-TXZ66K4Q.js → chunk-XUJXGE42.js} +1 -1
  130. package/dist/{chunk-AQWTK6IN.js → chunk-XXE7W5AV.js} +1 -1
  131. package/dist/{chunk-EXLXV5OU.js → chunk-YAAQER2L.js} +1 -1
  132. package/dist/{chunk-XS2LZFCH.js → chunk-YCH7H7JX.js} +1 -1
  133. package/dist/{chunk-SEKJZOKW.js → chunk-YGMUNNKH.js} +1 -1
  134. package/dist/{chunk-ARU6KAGY.js → chunk-YKYKOV6U.js} +1 -1
  135. package/dist/chunk-YLQHY4A7.js +2 -0
  136. package/dist/{chunk-KGKJU27A.js → chunk-YYYQ5MVD.js} +1 -1
  137. package/dist/chunk-YZVR7ESF.js +2 -0
  138. package/dist/{chunk-PYQS5ST6.js → chunk-Z3YYMZHT.js} +2 -2
  139. package/dist/{chunk-QD2BUO5M.js → chunk-Z73ZYROU.js} +1 -1
  140. package/dist/{chunk-JX2CAVX6.js → chunk-ZCSEBT2W.js} +1 -1
  141. package/dist/{chunk-MCKBJIBB.js → chunk-ZEVU2OT3.js} +1 -1
  142. package/dist/{chunk-K4SULRBL.js → chunk-ZKCCG3GK.js} +1 -1
  143. package/dist/chunk-ZUZ6QJRA.js +23 -0
  144. package/dist/committer-IYQPXG6C.js +2 -0
  145. package/dist/{config-BCGD2FEX.js → config-UGCWZGH5.js} +1 -1
  146. package/dist/cover-cmd-SWJ2NZUZ.js +3 -0
  147. package/dist/{credentials-YNH5BU2Z.js → credentials-GWLYYRTL.js} +1 -1
  148. package/dist/{deps-bundle-LOFI4DAJ.js → deps-bundle-VNGC2UG6.js} +1 -1
  149. package/dist/{deps-resolve-GA6IPHVZ.js → deps-resolve-YLCEU6I7.js} +1 -1
  150. package/dist/design-committer-J57IAAA5.js +2 -0
  151. package/dist/dispatch-OMQCT7WO.js +2 -0
  152. package/dist/{doctor-W5TQBYB5.js → doctor-B4Z6RPKQ.js} +1 -1
  153. package/dist/docx-convert-WPZS6OIC.js +2 -0
  154. package/dist/{dossier-Y6TJWFZU.js → dossier-UGJMYYAB.js} +1 -1
  155. package/dist/evidence-XJGXVLO5.js +2 -0
  156. package/dist/evolve-cmd-QQQPPGL3.js +2 -0
  157. package/dist/explain-H5HJEDEF.js +2 -0
  158. package/dist/{explain-cmd-XCRO4AS6.js → explain-cmd-R45I5MT7.js} +1 -1
  159. package/dist/explain-cmd-XVE6Z67Q.js +9 -0
  160. package/dist/extract-bind-7IDQS4QP.js +14 -0
  161. package/dist/{extract-cmd-7FKQJNS7.js → extract-cmd-KIEOBRIT.js} +3 -3
  162. package/dist/feeder-RSHMGW6B.js +2 -0
  163. package/dist/gaps-cmd-RGIPUSIR.js +3 -0
  164. package/dist/{generate-headless-OBMB5CSB.js → generate-headless-XGRIDD6O.js} +2 -2
  165. package/dist/headless-io-3A3BZVQ5.js +2 -0
  166. package/dist/index.js +187 -206
  167. package/dist/ingest-QGLVY7ND.js +2 -0
  168. package/dist/ingest-cmd-R5H5SF5K.js +2 -0
  169. package/dist/install-W3VPVPAQ.js +2 -0
  170. package/dist/interactive-bind-X5DVLRRW.js +26 -0
  171. package/dist/lifecycle-cmd-6R2PR2HM.js +2 -0
  172. package/dist/{list-cmd-V3HJ5K4O.js → list-cmd-QCIYKWYQ.js} +1 -1
  173. package/dist/{list-commands-SH4HPFI4.js → list-commands-VRRCVWKO.js} +1 -1
  174. package/dist/{locks-cmd-CSVSWY2Y.js → locks-cmd-67OHQZNV.js} +1 -1
  175. package/dist/logical-ids-DN6IZSUM.js +2 -0
  176. package/dist/login-flow-5HL2QYEL.js +2 -0
  177. package/dist/maintenance-cmd-GZ4EMT3V.js +2 -0
  178. package/dist/{mobile-prompts-UZTRJ3L7.js → mobile-prompts-CMIVWDHQ.js} +1 -1
  179. package/dist/objective-variable-gate-EEYJ6B3X.js +2 -0
  180. package/dist/open-provider-UFSCTIQQ.js +2 -0
  181. package/dist/pdf-convert-5H4HQNN3.js +2 -0
  182. package/dist/{persist-recorded-session-QMRY4DOF.js → persist-recorded-session-JXL5E53A.js} +1 -1
  183. package/dist/phase-seed-HKJ2EF7R.js +2 -0
  184. package/dist/pipeline-RSCRNNPW.js +2 -0
  185. package/dist/prepare-target-XZ3FTVBW.js +2 -0
  186. package/dist/readmodel-IBFRM6EO.js +2 -0
  187. package/dist/reconcile-cmd-4VRTUM2D.js +2 -0
  188. package/dist/reconcile-deps-ZCJ2QCK5.js +4 -0
  189. package/dist/reconcile-engine-IVLZCYZB.js +2 -0
  190. package/dist/{recording-banner-7E75ERQJ.js → recording-banner-SRLPSTFP.js} +1 -1
  191. package/dist/records-TJJJWBUD.js +2 -0
  192. package/dist/registry-CPQHW2L2.js +2 -0
  193. package/dist/{require-project-folder-LBUYWQOF.js → require-project-folder-SKEZMSN7.js} +1 -1
  194. package/dist/{resolve-run-intent-GHISMXLZ.js → resolve-run-intent-THC3EPAX.js} +1 -1
  195. package/dist/{resolver-7JC5VZ4S.js → resolver-2NUNLK7N.js} +1 -1
  196. package/dist/revert-6BBBK3I4.js +2 -0
  197. package/dist/review-cmd-BMJQZ6XJ.js +5 -0
  198. package/dist/run-TURFDLC6.js +2 -0
  199. package/dist/run-UDP5VPYS.js +2 -0
  200. package/dist/{run-test-md-5LPCKCW7.js → run-test-md-MRYNFNPO.js} +2 -2
  201. package/dist/sessions-NH7WQWMX.js +2 -0
  202. package/dist/{sessions-cmd-VDQGRBEM.js → sessions-cmd-DV442ZCY.js} +1 -1
  203. package/dist/{skill-installer-YQPZZB7I.js → skill-installer-CVJ5VTEJ.js} +1 -1
  204. package/dist/{spawner-X2FOOONV.js → spawner-7FUA3JXA.js} +1 -1
  205. package/dist/store-guard-XQ5MSUB2.js +2 -0
  206. package/dist/structured-answers-NADW6D44.js +5 -0
  207. package/dist/sync-cmd-5INKTZN2.js +2 -0
  208. package/dist/sync-setup-4R54VRAO.js +2 -0
  209. package/dist/sync-setup-ui-RC727VK6.js +3 -0
  210. package/dist/tcg-generate-2BOPGRM6.js +2 -0
  211. package/dist/testmd-actions-2CPJZAC2.js +2 -0
  212. package/dist/testmd-sync-HYZI6NRM.js +2 -0
  213. package/dist/token-refresh-NTE4LQRN.js +2 -0
  214. package/dist/{validate-basic-GTSVZFQI.js → validate-basic-OKLJLDML.js} +1 -1
  215. package/dist/{variable-receipt-IHQAYWMZ.js → variable-receipt-CMCDUJI2.js} +1 -1
  216. package/dist/verdicts-EMCYGQWM.js +2 -0
  217. package/dist/{version-check-IPEPJZDX.js → version-check-4DQJBSXW.js} +1 -1
  218. package/dist/{view-cmd-SXXNDZIC.js → view-cmd-P3XRFORJ.js} +1 -1
  219. package/dist/walk-session-MUGS6CZY.js +2 -0
  220. package/dist/with-telemetry-3T53GIQC.js +2 -0
  221. package/package.json +12 -11
  222. package/dist/EvidenceViewOffer-AZRAILJQ.js +0 -2
  223. package/dist/FolderPicker-OJFR7AKZ.js +0 -2
  224. package/dist/ScrollbackTap-Q3IOKNMS.js +0 -2
  225. package/dist/SingleShotApp-72D5VVLE.js +0 -2
  226. package/dist/TestMdRunView-4OA52DA2.js +0 -2
  227. package/dist/bind-F36JFHUK.js +0 -12
  228. package/dist/bridge-KMDML2NB.js +0 -2
  229. package/dist/chat-committer-RAOIL2T6.js +0 -2
  230. package/dist/chat-controller-YJCNU76T.js +0 -2
  231. package/dist/chunk-4WOVHRI2.js +0 -15
  232. package/dist/chunk-54JZ6VEW.js +0 -4
  233. package/dist/chunk-5DT7PIGB.js +0 -5
  234. package/dist/chunk-6FCPS2VT.js +0 -4
  235. package/dist/chunk-6IAA644J.js +0 -9
  236. package/dist/chunk-6J635CRI.js +0 -5
  237. package/dist/chunk-AGRUULPT.js +0 -4
  238. package/dist/chunk-BZTWTYQQ.js +0 -6
  239. package/dist/chunk-CUSTYILP.js +0 -2
  240. package/dist/chunk-DBIBROYW.js +0 -5
  241. package/dist/chunk-I27YRAGO.js +0 -7
  242. package/dist/chunk-IAHKTEET.js +0 -2
  243. package/dist/chunk-IVQX3AKL.js +0 -4
  244. package/dist/chunk-J3Q63NFG.js +0 -2
  245. package/dist/chunk-K6RAOZHP.js +0 -4
  246. package/dist/chunk-KO3FL2XW.js +0 -26
  247. package/dist/chunk-L32DKFRQ.js +0 -16
  248. package/dist/chunk-LPDBTGO5.js +0 -21
  249. package/dist/chunk-N7Z7BQYO.js +0 -3
  250. package/dist/chunk-NVGBE2DR.js +0 -2
  251. package/dist/chunk-OS4VSIHT.js +0 -4
  252. package/dist/chunk-OTMAFCZK.js +0 -8
  253. package/dist/chunk-P5MJMM3X.js +0 -85
  254. package/dist/chunk-QQ5MHSSY.js +0 -2
  255. package/dist/chunk-T7DGNWI2.js +0 -17
  256. package/dist/chunk-UH2ZTX4E.js +0 -2
  257. package/dist/chunk-W3Z7AZNT.js +0 -4
  258. package/dist/chunk-WUV3FJ7C.js +0 -11
  259. package/dist/chunk-XMTSHHYQ.js +0 -4
  260. package/dist/committer-C6UCDYMC.js +0 -2
  261. package/dist/cover-cmd-5LPHIOSI.js +0 -3
  262. package/dist/design-committer-UPC6NZUF.js +0 -2
  263. package/dist/dispatch-FRCPK3AZ.js +0 -2
  264. package/dist/docx-convert-BIV5T7F5.js +0 -2
  265. package/dist/evidence-FHO36EEV.js +0 -2
  266. package/dist/evolve-cmd-6RXLKERE.js +0 -2
  267. package/dist/explain-3HAZY7Q6.js +0 -2
  268. package/dist/explain-cmd-RMJPXD4U.js +0 -9
  269. package/dist/extract-bind-BFJPRNPQ.js +0 -10
  270. package/dist/feeder-IOR3XRNF.js +0 -2
  271. package/dist/gaps-cmd-FDJ3PT4C.js +0 -3
  272. package/dist/headless-io-66RG5NN5.js +0 -2
  273. package/dist/ingest-TTUQ7UDK.js +0 -2
  274. package/dist/ingest-cmd-AV66Q5LC.js +0 -2
  275. package/dist/install-SFJ2FFQ6.js +0 -2
  276. package/dist/interactive-bind-N5AQB26T.js +0 -25
  277. package/dist/lifecycle-cmd-KSMETBPP.js +0 -2
  278. package/dist/logical-ids-MLXAH45L.js +0 -2
  279. package/dist/login-flow-ODVWEPRU.js +0 -2
  280. package/dist/maintenance-cmd-VFYGKY3X.js +0 -2
  281. package/dist/objective-variable-gate-3VUXNDCZ.js +0 -2
  282. package/dist/pdf-convert-OZIRUADA.js +0 -2
  283. package/dist/phase-seed-BMOSAA74.js +0 -2
  284. package/dist/pipeline-5FHWZAXK.js +0 -2
  285. package/dist/prepare-target-UJEY2FSR.js +0 -2
  286. package/dist/readmodel-TDRFVDVI.js +0 -2
  287. package/dist/reconcile-cmd-2QHZML2L.js +0 -2
  288. package/dist/reconcile-deps-ZBWUY3SM.js +0 -4
  289. package/dist/reconcile-engine-YC4RQYF2.js +0 -2
  290. package/dist/records-JLS63SDI.js +0 -2
  291. package/dist/registry-JJTRUPH7.js +0 -2
  292. package/dist/revert-PRR3D4XM.js +0 -2
  293. package/dist/review-cmd-SAGIKWEW.js +0 -4
  294. package/dist/run-43ACVPJK.js +0 -2
  295. package/dist/run-EOTOXNQO.js +0 -2
  296. package/dist/sessions-GIEXOCE4.js +0 -2
  297. package/dist/structured-answers-YAVW65G4.js +0 -5
  298. package/dist/tcg-generate-V4QRNEZV.js +0 -2
  299. package/dist/testmd-actions-2UMU3QMV.js +0 -2
  300. package/dist/testmd-sync-UBXDLWYD.js +0 -2
  301. package/dist/token-refresh-NL5AM446.js +0 -2
  302. package/dist/verdicts-QU6W3TUF.js +0 -2
  303. package/dist/walk-session-7JVB4Z5S.js +0 -2
  304. package/dist/with-telemetry-LRI7H6DH.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as ae}from"./chunk-MMBBQ4OZ.js";import{j as R}from"./chunk-NU45ROHH.js";import{c as ie,e as ne,i as re,j as K}from"./chunk-Z7S3IWUX.js";import{d as $,e as oe}from"./chunk-4JOD47QI.js";import{a as se}from"./chunk-RZ4F3BHX.js";import{spawn as ze}from"child_process";import{closeSync as Xe,existsSync as Ge,mkdirSync as We,openSync as Ye,readFileSync as Ze,rmSync as Qe}from"fs";import{homedir as ge}from"os";import{dirname as X,join as S}from"path";import{access as Re,mkdir as de,readFile as Le}from"fs/promises";import{homedir as Ce}from"os";import{arch as Fe,platform as Be}from"process";import{join as M}from"path";var Ue=35,qe="google_apis",Ve="KaneCLI_Pixel_API35",He="KaneAI_Pixel_API35";function Ht(t){return t===He?Ve:t}var je=1;function Ke(t,e){return t==="darwin"&&e==="arm64"?"arm64-v8a":"x86_64"}function Je(){return{home:Ce(),os:Be,arch:Fe}}async function le(t){try{return await Re(t),!0}catch{return!1}}var J=class{deps;constructor(e={}){this.deps={...Je(),...e}}paths(){let e=M(this.deps.home,".testmuai","kaneai","mobile"),r=M(e,"android-sdk");return{root:r,emulatorDir:M(r,"emulator"),systemImageDir:M(r,"system-images",`android-${Ue}`,qe,Ke(this.deps.os,this.deps.arch)),avdHome:M(e,"avd"),manifest:M(r,"sdk-manifest.json")}}environment(){let e=this.paths();return{ANDROID_HOME:e.root,ANDROID_SDK_ROOT:e.root,ANDROID_AVD_HOME:e.avdHome}}async ensureSdkRootMarkers(){let e=this.paths().root;await de(M(e,"platforms"),{recursive:!0}),await de(M(e,"platform-tools"),{recursive:!0})}async status(){let e=this.paths(),r=null;try{r=JSON.parse(await Le(e.manifest,"utf8"))}catch{}if(!r||r.schemaVersion!==je)return{emulator:!1,systemImage:!1};let o=this.deps.os==="win32"?"emulator.exe":"emulator";return{emulator:!!r.components.emulator&&await le(M(e.emulatorDir,o)),systemImage:!!r.components.systemImage&&await le(M(e.systemImageDir,"system.img"))}}},ue;function B(){return ue??=new J,ue}var G="android",et="http://127.0.0.1:4723/status",tt=2e3,z=(()=>{let t=Number(process.env.KANE_CLI_EMULATOR_BOOT_TIMEOUT_MS);return Number.isFinite(t)&&t>=3e4?t:3e5})(),it=1e3,nt=3e5;var rt=5,ce="Run `kane-cli doctor --target emulator --install` to install the managed Appium tree.",st={device:"ready",unauthorized:"unauthorized",offline:"offline"};function ot(t){let e={};for(let r of t){let o=r.indexOf(":");o<=0||(e[r.slice(0,o)]=r.slice(o+1))}return e}function at(t){let e=[];for(let r of t.split(`
2
+ import{a as ae}from"./chunk-MMBBQ4OZ.js";import{j as R}from"./chunk-6GLFQHSW.js";import{c as ie,e as ne,i as re,j as K}from"./chunk-Z7S3IWUX.js";import{d as $,e as oe}from"./chunk-4JOD47QI.js";import{a as se}from"./chunk-RZ4F3BHX.js";import{spawn as ze}from"child_process";import{closeSync as Xe,existsSync as Ge,mkdirSync as We,openSync as Ye,readFileSync as Ze,rmSync as Qe}from"fs";import{homedir as ge}from"os";import{dirname as X,join as S}from"path";import{access as Re,mkdir as de,readFile as Le}from"fs/promises";import{homedir as Ce}from"os";import{arch as Fe,platform as Be}from"process";import{join as M}from"path";var Ue=35,qe="google_apis",Ve="KaneCLI_Pixel_API35",He="KaneAI_Pixel_API35";function Ht(t){return t===He?Ve:t}var je=1;function Ke(t,e){return t==="darwin"&&e==="arm64"?"arm64-v8a":"x86_64"}function Je(){return{home:Ce(),os:Be,arch:Fe}}async function le(t){try{return await Re(t),!0}catch{return!1}}var J=class{deps;constructor(e={}){this.deps={...Je(),...e}}paths(){let e=M(this.deps.home,".testmuai","kaneai","mobile"),r=M(e,"android-sdk");return{root:r,emulatorDir:M(r,"emulator"),systemImageDir:M(r,"system-images",`android-${Ue}`,qe,Ke(this.deps.os,this.deps.arch)),avdHome:M(e,"avd"),manifest:M(r,"sdk-manifest.json")}}environment(){let e=this.paths();return{ANDROID_HOME:e.root,ANDROID_SDK_ROOT:e.root,ANDROID_AVD_HOME:e.avdHome}}async ensureSdkRootMarkers(){let e=this.paths().root;await de(M(e,"platforms"),{recursive:!0}),await de(M(e,"platform-tools"),{recursive:!0})}async status(){let e=this.paths(),r=null;try{r=JSON.parse(await Le(e.manifest,"utf8"))}catch{}if(!r||r.schemaVersion!==je)return{emulator:!1,systemImage:!1};let o=this.deps.os==="win32"?"emulator.exe":"emulator";return{emulator:!!r.components.emulator&&await le(M(e.emulatorDir,o)),systemImage:!!r.components.systemImage&&await le(M(e.systemImageDir,"system.img"))}}},ue;function B(){return ue??=new J,ue}var G="android",et="http://127.0.0.1:4723/status",tt=2e3,z=(()=>{let t=Number(process.env.KANE_CLI_EMULATOR_BOOT_TIMEOUT_MS);return Number.isFinite(t)&&t>=3e4?t:3e5})(),it=1e3,nt=3e5;var rt=5,ce="Run `kane-cli doctor --target emulator --install` to install the managed Appium tree.",st={device:"ready",unauthorized:"unauthorized",offline:"offline"};function ot(t){let e={};for(let r of t){let o=r.indexOf(":");o<=0||(e[r.slice(0,o)]=r.slice(o+1))}return e}function at(t){let e=[];for(let r of t.split(`
3
3
  `)){let o=r.trim();if(!o||o.startsWith("*"))continue;let u=o.toLowerCase();if(u.startsWith("list of devices")||u.startsWith("adb server"))continue;let g=o.split(/\s+/),p=g[0],w=g[1];if(!p||!w)continue;let v=ot(g.slice(2)),x=/^(localhost|127\.0\.0\.1):\d{1,5}$/.test(p),P=/^[A-Za-z0-9._-]+:\d{1,5}$/.test(p),C=/^sdk_/.test(v.product??"")||/^sdk_/.test(v.model??"")||/^emu/.test(v.device??"");if(!p.startsWith("emulator-")&&!x&&!(P&&C))continue;let l=v.model?v.model.replace(/_/g," "):void 0;e.push({platform:G,kind:"emulator",id:p,displayName:l??p,state:st[w]??"offline"})}return e}function me(t){let e=[];for(let r of t.split(`
4
4
  `)){let o=r.trim();o&&/^[A-Za-z0-9._-]+$/.test(o)&&(e.includes(o)||e.push(o))}return e}function dt(t){for(let e of t.split(`
5
5
  `)){let r=e.trim();if(!(!r||r==="OK"))return r}}function lt(t){let e=/^Version\s+(\S+)/m.exec(t);return e?.[1]?e[1].split("-")[0]:/Android Debug Bridge version\s+(\S+)/.exec(t)?.[1]}function ut(t){let e=[];for(let r of t.split(`
@@ -0,0 +1,7 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as V}from"./chunk-ALCE5RLK.js";import{a as Y}from"./chunk-Q2F5QB2W.js";import{b as C,c as E}from"./chunk-IE3OO5GI.js";import{C as J}from"./chunk-GP7WD4UY.js";import{M as K,c as $,e as G,g as B,m as j,x as U}from"./chunk-3N6IAVD5.js";import{a as L,d as P,f as T}from"./chunk-AKX4VRRR.js";import{existsSync as ve,mkdirSync as he,readFileSync as Ee,writeFileSync as we}from"fs";import{basename as A,dirname as Ie,extname as ee,join as ke}from"path";import{spawnSync as oe}from"child_process";import{appendFileSync as re,existsSync as O,readFileSync as z}from"fs";import{dirname as se,join as H}from"path";var ae="# kane-cli context store: shared through a location, never merged with git",ce=".context/",de=new Set([".context",".context/","/.context","/.context/"]);function X(e,n={}){let t=n.env??process.env;if(t.KANE_CONTEXT_GITIGNORE==="0")return{outcome:"skipped"};try{if(!le(e))return{outcome:"not-a-repo"};let i=H(e,".gitignore");if(me(i))return{outcome:"already",path:i};if((n.checkIgnore??(o=>pe(o,t)))(e)===!0)return{outcome:"already"};let g="";if(O(i)){let o=z(i);o.length>0&&o[o.length-1]!==10&&(g=`
3
+ `)}return re(i,`${g}${ae}
4
+ ${ce}
5
+ `),{outcome:"added",path:i}}catch(i){return{outcome:"failed",reason:i instanceof Error?i.message:String(i)}}}function le(e){let n=e;for(;;){if(O(H(n,".git")))return!0;let t=se(n);if(t===n)return!1;n=t}}function me(e){return O(e)?z(e,"utf8").split(/\r?\n/).some(n=>de.has(n.trim())):!1}function pe(e,n){let t=oe("git",["-C",e,"check-ignore","-q",".context"],{env:{...n,GIT_TERMINAL_PROMPT:"0"},stdio:"ignore",timeout:5e3});return t.error||t.status===null?null:t.status===0?!0:t.status===1?!1:null}import{extname as ue}from"path";var fe={kind:"jira",media_type:"application/x-kane-jira-envelope",extensions:[],cite:"verbatim",maxBytes:2e6},ge={kind:"confluence",media_type:"application/x-kane-confluence-envelope",extensions:[],cite:"verbatim",maxBytes:2e6},De={kind:"web",media_type:"application/x-kane-web-envelope",extensions:[],cite:"verbatim",maxBytes:2e6},xe={kind:"linear",media_type:"application/x-kane-linear-envelope",extensions:[],cite:"verbatim",maxBytes:2e6},_e={kind:"linear-doc",media_type:"application/x-kane-linear-doc-envelope",extensions:[],cite:"verbatim",maxBytes:2e6},q=[{kind:"text",media_type:"text/plain",extensions:[".txt"],cite:"verbatim",maxBytes:2e6},{kind:"markdown",media_type:"text/markdown",extensions:[".md",".markdown"],cite:"verbatim",maxBytes:2e6},{kind:"image",media_type:"image/png",extensions:[".png"],cite:"anchor-only",maxBytes:5e6},{kind:"image",media_type:"image/jpeg",extensions:[".jpg",".jpeg"],cite:"anchor-only",maxBytes:5e6},{kind:"image",media_type:"image/webp",extensions:[".webp"],cite:"anchor-only",maxBytes:5e6},{kind:"text",media_type:"application/json",extensions:[".json"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"application/yaml",extensions:[".yaml",".yml"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"application/toml",extensions:[".toml"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"application/xml",extensions:[".xml"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"text/plain",extensions:[".log"],cite:"verbatim",maxBytes:2e6},{kind:"pdf",media_type:"application/pdf",extensions:[".pdf"],cite:"verbatim",maxBytes:25e6,sniff:e=>e.subarray(0,5).toString("latin1")==="%PDF-"},{kind:"docx",media_type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],cite:"verbatim",maxBytes:25e6,sniff:e=>e.length>=4&&e[0]===80&&e[1]===75&&e[2]===3&&e[3]===4,sniffFail:e=>e.length>=8&&e.subarray(0,8).equals(ye)?"DOCX_ENCRYPTED_OR_LEGACY: password-protected Office file (or a legacy .doc renamed .docx) \u2014 remove the password / save as .docx and re-ingest":void 0},fe,ge,xe,_e],ye=Buffer.from([208,207,17,224,161,177,26,225]),S={pdf:"pdf",docx:"docx",jira:"jira",confluence:"confluence",web:"web",linear:"linear","linear-doc":"linearDoc"},Fe=new Set(Object.keys(S));function W(e){let n=ue(e).toLowerCase(),t=q.find(i=>i.extensions.includes(n));return t?{ok:!0,media:t}:{ok:!1,code:"UNSUPPORTED_MEDIA",allowlist:q.flatMap(i=>i.extensions)}}function w(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function Me(e,n,t){return Y({source_id:e,source_cid:"sha256:".padEnd(71,"0"),doc_kind:n,numbered_text:V(t)})}var Q=2e3;function Be(e){let t=A(e,ee(e)).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"");return B(t),t}function qe(e){let n=/^(.*?)[-_.]?v?\d+$/.exec(e);if(!n)return null;let t=(n[1]??"").replace(/[-_.]+$/,"");return t.length>0&&t!==e?t:null}function te(e){let n=ke(e,"meta.json");return ve(n)?{created:!1}:(he(e,{recursive:!0}),we(n,JSON.stringify({schema:L,canonicalizer:"v1"},null,2)+`
6
+ `),{created:!0,gitignore:X(Ie(e))})}async function We(e){let{contextDir:n,filePath:t,asId:i,confirmSameSource:y,converters:g}=e,o=te(n),p=Ee(t),s=W(t);if(!s.ok)throw new Error(`${A(t)} is a file type kane can't ingest (${ee(t)||"no extension"}) \u2014 supported: ${s.allowlist.join(" ")} [UNSUPPORTED_MEDIA]`);if(p.byteLength>s.media.maxBytes)throw new Error(`${A(t)} is too large \u2014 ${w(p.byteLength)}, the limit for ${s.media.media_type} is ${w(s.media.maxBytes)} [FILE_TOO_LARGE]`);if(s.media.sniff&&!s.media.sniff(p)){let m=s.media.sniffFail?.(p);throw new Error(m??`MEDIA_SNIFF_MISMATCH: ${t} does not look like ${s.media.media_type}`)}let u;i!==void 0?(B(i),u=i):u=Be(t);let l=await Ce({contextDir:n,bytes:p,media:s.media,sourceId:u,label:t,confirmSameSource:y,converters:g});return o.gitignore?{...l,gitignore:o.gitignore}:l}async function Ce(e){let{contextDir:n,bytes:t,media:i,confirmSameSource:y,converters:g}=e,o=e.sourceId,p=e.label??o,s=te(n);if(t.byteLength>i.maxBytes)throw new Error(`the content is too large \u2014 ${w(t.byteLength)}, the limit for ${i.media_type} is ${w(i.maxBytes)} [FILE_TOO_LARGE]`);let u=[],l=S[i.kind];if(i.cite==="verbatim"&&!l){try{new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new Error(`ENCODING_UNSUPPORTED: ${p} is not valid UTF-8 \u2014 re-save it as UTF-8 and re-ingest`)}t.toString("utf8").split(`
7
+ `).some(x=>x.length>Q)&&u.push(`long line detected (> ${Q} chars) \u2014 anchors lose granularity; consider pretty-printing before ingest`)}let m=C(t),v=new Map,c=null,N=!1;for(let x=0;;x++){let b=J(n),f=b.heads.get(o),ne=f!=null?b.getNode(f)?.content:void 0;if(f!=null&&ne?.blob===m)return{status:"unchanged",source_id:o,cid:f,blob:m};if(f==null){for(let[r,_]of b.heads.entries())if(!(r===o||_==null)&&b.getNode(_)?.content.blob===m){let a;if(v.has(r)?a=v.get(r):x===0&&y?(a=await y(r),v.set(r,a)):(a=!1,v.set(r,a),x>0&&u.push(`same bytes already ingested as '${r}' \u2014 minted under '${o}' anyway (the twin appeared mid-commit; not prompted)`)),a)return{status:"unchanged",source_id:r,cid:_,blob:m};break}}if(c===null){let r={},_,a=null,h=null;if(l){let D=g?.[l];if(!D)throw new Error(`${l.toUpperCase()}_CONVERTER_MISSING: ${l} ingestion requires the converter \u2014 the command layer wires it`);let d=await D(t);a=Buffer.from(d.projection,"utf8");let F=Me(o,i.kind,a);if(F>4e5)throw new Error(`PROJECTION_TOO_LARGE: serialized source payload ${F} bytes > ${4e5} \u2014 split the document and re-ingest`);r={text_blob:C(a),...d.inventory.length>0?{images:d.inventory}:{},converter:d.converter},h=d.blobs,_={kind:i.kind,...d.pages!==void 0?{pages:d.pages}:{},delivered:d.delivered.length,omitted:d.inventory.length-d.delivered.length}}let ie=[...r.text_blob?[r.text_blob]:[],...h?h.keys():[]];c={derived:r,composite:_,projBytes:a,derivedBlobs:h,derivedFps:ie}}if(!N){if(E(n,t),c.projBytes!==null&&E(n,c.projBytes),c.derivedBlobs!==null)for(let[,r]of c.derivedBlobs)E(n,r);N=!0}let I=G(o,m),k=T("source",I);if(k.length>0)throw new Error(`source node fails ${k[0].code}: ${k[0].detail}`);let M=$("source",I),R={format:i.kind,media_type:i.media_type,anchors_supported:l?["L-L","img#ref"]:i.cite==="verbatim"?["L-L"]:[],...c.derived};try{K(n,{ts:new Date().toISOString(),proposal_id:null,nodes:[{cid:M,label:P.SOURCE,content:I}],edges:[],review:[],supersessions:[],media:{[o]:R},...e.eventIds&&e.eventIds.length>0?{event_ids:e.eventIds}:{},source_head_moves:{[o]:M}},{expectPrev:b.latestHash,intent:{v:1,verb:"ingest",args:j({source_id:o,blob:m,label:p,media:R,derived_blobs:c.derivedFps,eventIds:e.eventIds??null}),pins:{prior_head:f??null}},provenance:e.provenance})}catch(r){if(r instanceof U&&x<3)continue;throw r}return{status:f!=null?"versioned":"created",source_id:o,cid:M,blob:m,...u.length?{warnings:u}:{},...c.composite?{composite:c.composite}:{},...s.gitignore?{gitignore:s.gitignore}:{}}}}export{X as a,fe as b,ge as c,De as d,xe as e,_e as f,q as g,S as h,Fe as i,W as j,Me as k,Be as l,qe as m,te as n,We as o,Ce as p};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as o}from"./chunk-NVGBE2DR.js";function s(n,r,e){let t=r.mediaOf(e),l=typeof t?.text_blob=="string"&&t.text_blob!==""?t.text_blob:null;if(l!==null)return o(n,l);let i=String(r.getNode(e)?.content.blob??"");return i===""?null:o(n,i)}function b(n){return n.toString("utf8").replace(/\n$/,"").split(`
2
+ import{d as o}from"./chunk-IE3OO5GI.js";function s(n,r,e){let t=r.mediaOf(e),l=typeof t?.text_blob=="string"&&t.text_blob!==""?t.text_blob:null;if(l!==null)return o(n,l);let i=String(r.getNode(e)?.content.blob??"");return i===""?null:o(n,i)}function b(n){return n.toString("utf8").replace(/\n$/,"").split(`
3
3
  `).map((e,t)=>`${String(t+1).padStart(4,"0")}| ${e}`).join(`
4
4
  `)}export{s as a,b};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as Ve}from"./chunk-ZOSY2PJM.js";import{a as Ye}from"./chunk-VYMMGWVO.js";import{a as We}from"./chunk-YCCUBQY4.js";import{a as qe}from"./chunk-VE3SUJMA.js";import{a as be}from"./chunk-ARU6KAGY.js";import{a as Ge}from"./chunk-LAQBCZ5A.js";import{a as He}from"./chunk-NUWOQS6L.js";import{b as Le,y as u}from"./chunk-33GXXC2L.js";import{a as re}from"./chunk-HCBYKLMW.js";import{a as h,b as f,h as Fe,i as Se,k as Ne}from"./chunk-C44QQJR4.js";import{a as we}from"./chunk-6YGTRKDT.js";import{e as $}from"./chunk-UR6MHSHU.js";var je=$(we(),1);import{readFileSync as ct,writeFileSync as ut,mkdirSync as ft}from"fs";import{dirname as dt,join as ze}from"path";var mt=ze(Le,"command-history.json"),Dt=ze(Le,"generate-history.json"),ht=200,De=class{entries;filePath;max;constructor(t=mt,e=ht){this.filePath=t,this.max=e,this.entries=this._load()}push(t){this.entries.length>0&&this.entries[this.entries.length-1]===t||(this.entries.push(t),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(t){let e=t.toLowerCase(),o=[];for(let s=this.entries.length-1;s>=0;s--)this.entries[s].toLowerCase().includes(e)&&o.push(this.entries[s]);return o}_load(){if(this.filePath===null)return[];try{let t=ct(this.filePath,"utf-8"),e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}_save(){if(this.filePath!==null)try{ft(dt(this.filePath),{recursive:!0}),ut(this.filePath,JSON.stringify(this.entries)+`
2
+ import{a as Ve}from"./chunk-MLYNVJNH.js";import{a as Ye}from"./chunk-SHSXOYKT.js";import{a as We}from"./chunk-YCCUBQY4.js";import{a as qe}from"./chunk-VE3SUJMA.js";import{a as be}from"./chunk-YKYKOV6U.js";import{a as Ge}from"./chunk-TEHZUSUY.js";import{a as He}from"./chunk-EPE2ELDH.js";import{b as Le,y as u}from"./chunk-HYTBEPC2.js";import{a as re}from"./chunk-HCBYKLMW.js";import{a as h,b as f,h as Fe,i as Se,k as Ne}from"./chunk-C44QQJR4.js";import{a as we}from"./chunk-6YGTRKDT.js";import{e as $}from"./chunk-UR6MHSHU.js";var je=$(we(),1);import{readFileSync as ct,writeFileSync as ut,mkdirSync as ft}from"fs";import{dirname as dt,join as ze}from"path";var mt=ze(Le,"command-history.json"),Dt=ze(Le,"generate-history.json"),ht=200,De=class{entries;filePath;max;constructor(t=mt,e=ht){this.filePath=t,this.max=e,this.entries=this._load()}push(t){this.entries.length>0&&this.entries[this.entries.length-1]===t||(this.entries.push(t),this.entries.length>this.max&&(this.entries=this.entries.slice(this.entries.length-this.max)),this._save())}getAll(){return[...this.entries]}search(t){let e=t.toLowerCase(),o=[];for(let s=this.entries.length-1;s>=0;s--)this.entries[s].toLowerCase().includes(e)&&o.push(this.entries[s]);return o}_load(){if(this.filePath===null)return[];try{let t=ct(this.filePath,"utf-8"),e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}_save(){if(this.filePath!==null)try{ft(dt(this.filePath),{recursive:!0}),ut(this.filePath,JSON.stringify(this.entries)+`
3
3
  `)}catch{}}};function kt(n){let t=(0,je.useRef)(null);return t.current||(t.current=new De(n)),t.current}var D=$(we(),1);var ke=$(we(),1);var Z=$(re(),1);function Xe({history:n,onSelect:t,onClose:e}){let[o,s]=(0,ke.useState)(""),[l,m]=(0,ke.useState)(0),v=o?n.search(o).slice(0,8):[];return Se((b,d)=>{if(d.escape){e();return}if(d.return){v.length>0&&v[l]?t(v[l]):e();return}if(d.upArrow){m(S=>Math.max(0,S-1));return}if(d.downArrow){m(S=>Math.min(v.length-1,S+1));return}if(d.backspace||d.delete){s(S=>S.slice(0,-1)),m(0);return}b&&!d.ctrl&&!d.meta&&(s(S=>S+b),m(0))}),(0,Z.jsxs)(h,{flexDirection:"column",marginLeft:2,borderStyle:"single",paddingX:1,children:[(0,Z.jsx)(f,{color:u.muted,bold:!0,children:"reverse search"}),(0,Z.jsxs)(h,{gap:1,children:[(0,Z.jsx)(f,{color:u.dim,children:"search:"}),(0,Z.jsx)(f,{children:o}),(0,Z.jsx)(f,{color:u.orange,children:"\u2588"})]}),v.length>0&&(0,Z.jsx)(f,{children:" "}),v.map((b,d)=>(0,Z.jsx)(h,{marginLeft:2,children:(0,Z.jsxs)(f,{color:d===l?u.orange:u.dim,bold:d===l,children:[d===l?"\u25B8 ":" ",b]})},`${d}-${b}`))]})}var X=$(re(),1);function Je({commands:n,selectedIndex:t}){return n.length===0?null:(0,X.jsx)(h,{flexDirection:"column",marginBottom:0,children:n.map((e,o)=>{let s=o===t;return e.disabled?(0,X.jsxs)(h,{children:[(0,X.jsx)(f,{color:u.dim,children:s?"\u276F ":" "}),(0,X.jsxs)(f,{color:u.dim,children:["/",e.name]}),(0,X.jsxs)(f,{color:u.dim,children:[" ",e.disabledReason??e.description]})]},e.name):(0,X.jsxs)(h,{children:[(0,X.jsx)(f,{color:s?u.orange:u.dim,children:s?"\u276F ":" "}),(0,X.jsxs)(f,{color:s?u.orange:void 0,bold:s,children:["/",e.name]}),e.args&&(0,X.jsxs)(f,{color:u.dim,children:[" ",e.args]}),(0,X.jsxs)(f,{color:u.dim,children:[" ",e.description]})]},e.name)})})}var Ze=$(we(),1);var q=$(re(),1),et={scenario:"Scenarios",case:"Test Cases",file:"Files",artifact:"Artifact candidates",installed:"Installed on device"};function Qe(n){let t={scenario:0,case:0,file:0,artifact:0,installed:0};for(let e of n)t[e.kind]++;return["scenario","case","file","artifact","installed"].filter(e=>t[e]>0).map(e=>`${t[e]} ${et[e]}`).join(" \xB7 ")}var Pe=7;function tt({items:n,selectedIndex:t,accent:e=u.orange}){let o=n.length;if(o===0)return null;let s=Math.floor(Pe/2),l=o<=Pe?0:Math.max(0,Math.min(t-s,o-Pe)),m=Math.min(o,l+Pe),v=l,b=o-m;return(0,q.jsxs)(h,{flexDirection:"column",marginBottom:0,children:[v>0&&(0,q.jsx)(h,{children:(0,q.jsx)(f,{color:u.dim,children:` \u22EF ${v} above \u2014 ${Qe(n.slice(0,l))}`})}),n.slice(l,m).map((d,S)=>{let U=l+S,F=d.selectable!==!1,E=U===t&&F,R=S===0||n[U-1].kind!==d.kind;return(0,q.jsxs)(Ze.default.Fragment,{children:[R&&(0,q.jsx)(h,{children:(0,q.jsx)(f,{color:u.dim,children:et[d.kind]})}),(0,q.jsxs)(h,{children:[(0,q.jsx)(f,{color:E?e:u.dim,children:E?"\u276F ":" "}),(0,q.jsxs)(f,{color:E?e:F?void 0:u.dim,bold:E,children:[d.label,d.reason?` \u2014 ${d.reason}`:""]})]})]},`${d.kind}:${d.value}:${U}`)}),b>0&&(0,q.jsx)(h,{children:(0,q.jsx)(f,{color:u.dim,children:` \u22EF ${b} more \u2014 ${Qe(n.slice(m))}`})})]})}var Be=$(we(),1);var gt=27,pt=127,xt=11;function bt(n){return n>=64&&n<=126}function Tt(n,t){n===xt&&t({killToEnd:!0,ctrl:!0,raw:String.fromCharCode(n)})}function vt(n,t){n===pt&&t({backspace:!0,meta:!0,raw:"\x1B\x7F"})}function wt(n,t){let e=n.map(s=>String.fromCharCode(s)).join(""),o=/^\[1;([0-9]+)([A-D])$/.exec(e);if(o){let s=parseInt(o[1],10),l=o[2],m={raw:"\x1B"+e};if(s===2)m.shift=!0;else if(s===3)m.meta=!0;else if(s===5)m.ctrl=!0;else return;l==="A"?m.arrowUp=!0:l==="B"?m.arrowDown=!0:l==="C"?m.arrowRight=!0:l==="D"&&(m.arrowLeft=!0),t(m);return}if(e==="[H"||e==="[1~"||e==="[7~"){t({home:!0,raw:"\x1B"+e});return}if(e==="[F"||e==="[4~"||e==="[8~"){t({end:!0,raw:"\x1B"+e});return}if(e==="[3;5~"){t({delete:!0,ctrl:!0,raw:"\x1B"+e});return}if(e==="[3;3~"){t({delete:!0,meta:!0,raw:"\x1B"+e});return}}function St(n,t){n===72?t({home:!0,raw:"\x1BO"+String.fromCharCode(n)}):n===70&&t({end:!0,raw:"\x1BO"+String.fromCharCode(n)})}function Et(){let n="IDLE",t=[];function e(){n="IDLE",t=[]}return{feed(o,s){for(let l of o)n==="IDLE"?l===gt?(n="ESC",t=[]):Tt(l,s):n==="ESC"?l===91?(n="CSI",t=[]):l===79?(n="SS3",t=[]):(vt(l,s),e()):n==="CSI"?(t.push(l),bt(l)&&(wt([91,...t],s),e())):n==="SS3"&&(St(l,s),e())},flushIdle(o){n==="ESC"&&t.length===0&&o({raw:"\x1B"}),e()}}}function nt(n,t={}){let e=(0,Be.useRef)(n);e.current=n;let{stdin:o}=Fe();(0,Be.useEffect)(()=>{if(t.isActive===!1||!o)return;let s=Et(),l=null,m=v=>{l&&(clearTimeout(l),l=null);let b=Buffer.isBuffer(v)?v:Buffer.from(v,"binary");s.feed(b,d=>e.current(d)),l=setTimeout(()=>{s.flushIdle(d=>e.current(d)),l=null},50)};return o.on("data",m),()=>{o.removeListener("data",m),l&&clearTimeout(l)}},[t.isActive,o])}var w=$(re(),1);function yt(n,t){let e=t-1;for(;e>=0&&n[e]!=="@"&&n[e]!==" "&&n[e]!==`
4
4
  `;)e--;return e<0||n[e]!=="@"||e>0&&n[e-1]!==" "&&n[e-1]!==`
5
5
  `?null:{at:e,query:n.slice(e+1,t).join("")}}function rt(n,t,e){for(let o=t+e;o>=0&&o<n.length;o+=e)if(n[o]?.selectable!==!1)return o;return t}function At(n){let t=n.findIndex(e=>e.selectable!==!1);return t===-1?0:t}var Oe=10;function Rt(n){return n.replace(/\x1b?\[200~/g,"").replace(/\x1b?\[201~/g,"").replace(/\r\n/g,`
@@ -0,0 +1,21 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as d,g as B,k as ee}from"./chunk-YLQHY4A7.js";import{P as Z}from"./chunk-3N6IAVD5.js";import{b as A}from"./chunk-HYTBEPC2.js";import{createHash as Ie,randomBytes as F}from"crypto";import{mkdirSync as xe,mkdtempSync as P,rmSync as $,existsSync as ve,renameSync as ke}from"fs";import{tmpdir as j}from"os";import{join as _,dirname as ce}from"path";import{spawn as te}from"child_process";function N(n,e=process.env){let t=n.replace(/https?:\/\/[^\s/@]+:[^\s/@]+@/gi,"https://[redacted]@").replace(/(authorization\s*[:=])[^\r\n]+/gi,"$1 [redacted]"),r=e.KANE_SYNC_GIT_TOKEN;if(r)for(let i of[r,Buffer.from(`x-access-token:${r}`).toString("base64")])t=t.split(i).join("[redacted]");return t}function be(n,e){if(n.GIT_SSH_COMMAND)return re(n.GIT_SSH_COMMAND);if(!n.GIT_SSH)return e?re(e):"ssh -o BatchMode=yes"}function re(n){return/(^|\s)-o\s*BatchMode=yes(\s|$)/.test(n)?n:`${n} -o BatchMode=yes`}var _e=/^(?:ssh:\/\/|[^/\s@:]+@[^/\s:]+:)/i,ie=new Map;function Ae(n,e){let t=[e??"",n.GIT_CONFIG_GLOBAL??"",n.HOME??""].join("\0"),r=ie.get(t);return r===void 0&&(r=se(["config","--get","core.sshCommand"],n,e,12e4).then(i=>i.code===0&&i.stdout.toString().trim()||void 0,()=>{}),ie.set(t,r)),r}var ne=new Set(["fetch","push","clone","ls-remote"]);function Ce(n,e,t){if(t!==void 0)return t;if(!n.some(i=>ne.has(i)))return 12e4;let r=e.KANE_SYNC_GIT_TRANSFER_TIMEOUT_SECONDS;if(r!==void 0){if(!/^\d+$/.test(r)||Number(r)<60||Number(r)>3600)throw new Error("KANE_SYNC_GIT_TRANSFER_TIMEOUT_SECONDS must be 60 to 3600");return Number(r)*1e3}return 9e5}function Ne(n){if(n.some(t=>/^(--force(?:-with-lease|-if-includes)?(?:=|$)|--mirror(?:=|$)|--delete(?:=|$)|-f$)/.test(t)))throw new Error("Git location cannot force, mirror or delete");let e=n.indexOf("push");if(e>=0){let t=n.slice(e+1);if(t.length!==3||t[0]!=="--porcelain"||!/^[0-9a-f]{40,64}:refs\/(heads|kane\/probe)\/[A-Za-z0-9._/-]+$/.test(t[2]))throw new Error("Git location requires an exact commit SHA and explicit ref")}}var H=async(n,e={})=>{Ne(n);let t={...process.env,...e.env};for(let h of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_CONFIG_PARAMETERS"])delete t[h];e.env?.GIT_INDEX_FILE&&(t.GIT_INDEX_FILE=e.env.GIT_INDEX_FILE);let r=[["core.autocrlf","false"],["core.eol","lf"],["core.symlinks","false"],["core.hooksPath","/dev/null"],["gc.autoDetach","false"],["gc.pruneExpire","3.days.ago"],["maintenance.auto","false"],["push.followTags","false"],["push.gpgSign","false"],["commit.gpgSign","false"]],i=t.KANE_SYNC_GIT_HTTP_POST_BUFFER;if(i!==void 0){if(!/^\d+$/.test(i)||Number(i)<1048576||Number(i)>536870912)throw new Error("KANE_SYNC_GIT_HTTP_POST_BUFFER must be 1048576 to 536870912 bytes; use it only for a proxy that rejects chunked uploads");r.push(["http.postBuffer",i])}for(let h of Object.keys(t))h.startsWith("GIT_TRACE")&&delete t[h];let s=n.find(h=>h.startsWith("https://"));if(t.KANE_SYNC_GIT_TOKEN&&s){let h=new URL(s);r.push([`http.${h.origin}${h.pathname}.extraheader`,""],[`http.${h.origin}${h.pathname}.extraheader`,`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.KANE_SYNC_GIT_TOKEN}`).toString("base64")}`],["credential.helper",""])}for(let h of Object.keys(t))/^GIT_CONFIG_(COUNT|KEY_\d+|VALUE_\d+)$/.test(h)&&delete t[h];let a=!t.GIT_SSH_COMMAND&&!t.GIT_SSH&&n.some(h=>ne.has(h))&&n.some(h=>_e.test(h))?await Ae({...t},e.cwd):void 0;r.forEach(([h,u],g)=>{t[`GIT_CONFIG_KEY_${g}`]=h,t[`GIT_CONFIG_VALUE_${g}`]=u}),t.GIT_CONFIG_COUNT=String(r.length),t.GIT_TERMINAL_PROMPT="0",t.GCM_INTERACTIVE="never",t.GIT_ASKPASS="",t.SSH_ASKPASS="";let c=be(t,a);return c!==void 0&&(t.GIT_SSH_COMMAND=c),t.GIT_NO_REPLACE_OBJECTS="1",se(n,t,e.cwd,Ce(n,t,e.timeout),e.input)};function se(n,e,t,r,i){return new Promise((s,o)=>{let a=te("git",n,{cwd:t,env:e,windowsHide:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),c=[],h=0,u="",g=!1,w=()=>{if(process.platform==="win32"&&a.pid)te("taskkill",["/pid",String(a.pid),"/t","/f"],{windowsHide:!0,stdio:"ignore"}).on("error",()=>a.kill("SIGKILL"));else try{a.pid&&process.kill(-a.pid,"SIGKILL")}catch{a.kill("SIGKILL")}},S=setTimeout(()=>{g=!0,w()},r);a.stdout.on("data",l=>{h+=l.length,h>128*1024*1024?w():c.push(l)}),a.stderr.on("data",l=>{u.length<64e3&&(u+=l.toString())}),a.stdin.on("error",()=>{}),a.on("error",l=>{clearTimeout(S),o(new d("SYNC_GIT_REQUIRED",`Git could not start: ${N(l.message,e)}`,"Install Git 2.31 or newer, then run the command again: https://git-scm.com/downloads"))}),a.on("close",l=>{clearTimeout(S),s({code:g||h>128*1024*1024?124:l??1,stdout:Buffer.concat(c),stderr:N(g?"Git operation timed out":u,e)})}),a.stdin.end(i)})}async function oe(n=H){let e=await n(["--version"],{timeout:1e4}),t=/git version (\d+)\.(\d+)/.exec(e.stdout.toString());if(e.code||!t||+t[1]<2||+t[1]==2&&+t[2]<31)throw new d("SYNC_GIT_REQUIRED","This location needs Git 2.31 or newer.","Install or update Git, then run setup again: https://git-scm.com/downloads")}function ae(n){let e=/^([^/@:]+)@([^/:]+):/.exec(n);if(e)return{user:e[1],host:e[2]};try{let t=new URL(n);return{host:t.hostname||"the server",user:t.username||"git",port:t.port||void 0}}catch{return{host:"the server",user:"git"}}}function gt(n){let e=/^[^/@:]+@([^/:]+):/.exec(n);if(e)return e[1].toLowerCase();try{return new URL(n).hostname.toLowerCase()}catch{return""}}function Y(n,e){let{host:t,user:r,port:i}=ae(e),s=N(n).trim().split(`
3
+ `).slice(-2).join(" ").trim();return/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(n)?{code:"SYNC_LOCATION_DENIED",message:`this computer has not accepted ${t}'s SSH host key yet`,remedy:`in a terminal run: ssh -T ${i?`-p ${i} `:""}${r}@${t} and answer yes, then run the command again`,diagnostic:s}:/Permission denied \(publickey/i.test(n)?{code:"SYNC_LOCATION_DENIED",message:`${t} did not accept your SSH key`,remedy:"load it with ssh-add, or ask the repository owner to grant your account access",diagnostic:s}:/could not read Username|Authentication failed|Access denied|Invalid username or (password|token)|returned error: 401|returned error: 403/i.test(n)?{code:"SYNC_LOCATION_DENIED",message:`sign in is needed, or your account has no access to this repository on ${t}`,remedy:"sign in through Git, or ask the owner to grant your account access",diagnostic:s}:/Could not resolve host|Connection refused|Connection timed out|timed out|Network is unreachable|Failed to connect/i.test(n)?{code:"SYNC_LOCATION_UNREACHABLE",message:`${t} could not be reached`,remedy:"check the address and your network, then run the command again",diagnostic:s}:/not found|does not appear to be a git repository|Repository not found/i.test(n)?{code:"SYNC_LOCATION_UNREACHABLE",message:"no repository answered at that address, or your account cannot see it; a private repository looks missing until access is granted",remedy:"check the address, then run the command again",diagnostic:s}:{code:"SYNC_LOCATION_UNREACHABLE",message:`git could not read the repository on ${t}`,remedy:"check the address and your access, then run the command again",...s?{diagnostic:s}:{}}}function M(n,e){return(n.startsWith(e)?n:n.charAt(0).toUpperCase()+n.slice(1))+"."}function yt(n,e){let t=Y(n,e),{host:r}=ae(e),i=t.remedy.replace(/,? ?(and )?then run the command again$/,"");return i?`${M(t.message,r)} ${M(i,r)}`:M(t.message,r)}var Oe=Buffer.from(`* -text -filter -ident -working-tree-encoding
4
+ `),Re="refs/kane/tip",Pe=/unexpected disconnect|hung up unexpectedly|Connection reset|Connection timed out|timed out|Could not resolve host|Failed to connect|RPC failed|Broken pipe|early EOF/i,$e={GIT_AUTHOR_NAME:"kane-cli context",GIT_AUTHOR_EMAIL:"context@kane-cli.invalid",GIT_COMMITTER_NAME:"kane-cli context",GIT_COMMITTER_EMAIL:"context@kane-cli.invalid"},G=class n{constructor(e){this.options=e;this.exec=e.exec??H,this.prefix=e.prefix?`${e.prefix}/`:"";let t=Ie("sha256").update(JSON.stringify([e.url,e.branch,this.prefix])).digest("hex");if(this.repo=_(e.cacheDir??_(A,"context-sync","mirrors"),`${t}.git`),this.ref=e.ref??`refs/heads/${e.branch}`,!/^refs\/(heads|kane\/probe)\/[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(this.ref)||this.ref.includes(".."))throw new Error("Invalid Git location ref")}kind="git";contractVersion=1;ceilingTier=1;exec;repo;ref;prefix;ready;tip=null;tree=new Map;async run(e,t={}){let r=await this.exec(["--git-dir",this.repo,...e],t);if(r.code)throw new Error(`Git ${e[0]} failed: ${r.stderr||"unable to read the location"}`);return r.stdout}async transfer(e){let t=await this.exec(["--git-dir",this.repo,...e]);if(t.code){let r=Y(t.stderr||"",this.options.url);throw new d(r.code,r.message,r.remedy,r.diagnostic)}return t.stdout}get name(){return this.options.name??"<name>"}takenRemedy(e){return e===1?`${this.name} holds a different history: to work on it, clone it with kane-cli context clone <descriptor of ${this.name}> <dir>; to share this store, add an empty location`:`kane-cli context pull ${this.name} --rebase`}init(){return this.ready??=(async()=>{if(await oe(this.exec),xe(ce(this.repo),{recursive:!0}),!ve(this.repo)){let e=P(_(ce(this.repo),".init-"));try{let t=await this.exec(["init","--bare",e]);if(t.code)throw new Error(`Cannot open Git cache: ${t.stderr}`);try{ke(e,this.repo)}catch(r){if(!["EEXIST","ENOTEMPTY"].includes(r.code??""))throw r}}finally{$(e,{recursive:!0,force:!0})}}if((await this.run(["rev-parse","--is-bare-repository"])).toString().trim()!=="true")throw new Error("The Git cache must be a bare repository");await this.refresh()})()}async refresh(){let t=(await this.transfer(["ls-remote",this.options.url,this.ref])).toString().trim();if(!t){this.tip=null,this.tree=new Map;return}let r=t.split(/\s+/)[0];if(!/^[0-9a-f]{40,64}$/.test(r))throw new Error("Git returned an invalid ref");if(r===this.tip)return;let i=`refs/kane/snapshots/${F(16).toString("hex")}`;await this.transfer(["fetch","--no-tags","--no-write-fetch-head",this.options.url,`${this.ref}:${i}`]);let s=(await this.run(["rev-parse",i])).toString().trim();await this.run(["update-ref",Re,s]),await this.run(["update-ref","-d",i]);let o=await this.readTree(s);this.tip=s,this.tree=o}contextKeys(e){let t=new Map;for(let[r,i]of e)r.startsWith(`${this.prefix}kane-context/`)&&t.set(r,i);return t}async readTree(e){let t=await this.run(["ls-tree","-rz","--full-tree",e]),r=new Map;for(let i of t.toString().split("\0").filter(Boolean)){let s=/^(\d+) (\w+) ([0-9a-f]+)\t([\s\S]+)$/.exec(i);if(!s)throw new Error("Git returned an invalid tree entry");if(s[4].startsWith(`${this.prefix}kane-context/`)&&(s[1]!=="100644"||s[2]!=="blob"))throw new d("SYNC_OBJECT_CORRUPT","Context storage contains a link or non-file object.","Ask the repository owner to restore the original context files.");r.set(s[4],s[3])}return r}key(e){if(!/^[a-zA-Z0-9_~./-]+$/.test(e)||e.split("/").some(t=>!t||t==="."||t===".."||t.toLowerCase()===".git"))throw new Error("Invalid context storage key");return this.prefix+e}async head(e){return await this.init(),this.tree.has(this.key(e))}async get(e){await this.init();let t=this.tree.get(this.key(e));return t?this.run(["cat-file","blob",t]):null}async list(e){return await this.init(),e&&e.replace(/\/$/,"")&&this.key(e.replace(/\/$/,"")),[...this.tree.keys()].filter(t=>t.startsWith(this.prefix+e)).map(t=>t.slice(this.prefix.length)).sort()}async beginTransaction(){await this.init();let e=new Map(this.tree),t=this.tip,r=new Map,i=!1,s=()=>{if(i)throw new Error("Git transaction is closed")},o=async a=>{s();let c=this.key(a),h=r.get(c),u=e.get(c);return h?Buffer.from(h):u?this.run(["cat-file","blob",u]):null};return{get:o,head:async a=>await o(a)!==null,stageIfAbsent:async(a,c)=>{s();let h=this.key(a);if(e.has(h)||r.has(h))return"exists";if(c.length>1e8)throw new d("SYNC_LOCATION_REFUSED_WRITE","A context object is too large for this Git location.","Use an S3 location for this context.");return r.set(h,Buffer.from(c)),"staged"},abort:async()=>{i=!0,r.clear()},commit:async()=>{s();try{if(!r.size)return{created:[]};let a=this.prefix+"kane-context/.gitattributes";e.has(a)||r.set(a,Oe);let c=new Map;for(let[l,m]of r)c.set(l,(await this.run(["hash-object","-w","--no-filters","--stdin"],{input:m})).toString().trim());let h=this.contextKeys(e),u=()=>{this.assertUnchanged(h);for(let[l,m]of this.contextKeys(this.tree))h.set(l,m)},g=!1,w="",S=0;for(let l=0;l<4;l++){u();for(let f of this.tree.keys())if(!(!f.startsWith(this.prefix)||e.has(f)||c.has(f))&&B(f.slice(this.prefix.length))!==null)throw new d("SYNC_BEHIND","the location gained records after this batch was prepared; nothing was published","run kane-cli context pull, then push again");let m=new Map;for(let[f,T]of c){let C=this.tree.get(f);if(C&&C!==T){let R=B(f.slice(this.prefix.length));throw R?new d("SYNC_POSITION_TAKEN",g?`position ${R} on ${this.name} now holds different work; an earlier publication could not be confirmed`:`position ${R} on ${this.name} was published by another writer; this batch was not published`,this.takenRemedy(R)):new d("SYNC_OBJECT_CORRUPT",`existing context object ${f} differs from the intended bytes`,"the object needs a person to look; nothing was published")}C||m.set(f,T)}if(!m.size)return await this.verifyPublication(c),{created:[]};t=this.tip;let I=await this.build(t,m);await this.checkAttributes(I,[...r.keys()]),S++;let E=await this.exec(["--git-dir",this.repo,"push","--porcelain",this.options.url,`${I}:${this.ref}`]),y=N(E.stdout.toString()+`
5
+ `+E.stderr);w=y.trim();let O=E.code!==0&&/\[rejected\]|\[remote rejected\]/.test(y),p=E.code!==0&&(E.code===124||Pe.test(y));g||=p;try{await this.refresh()}catch{throw new d("SYNC_PUBLICATION_UNKNOWN","we could not confirm whether your context was uploaded; your local work is safe","check the connection and retry; kane-cli compares the published data before writing again")}if(u(),[...c].every(([f,T])=>this.tree.get(f)===T)){await this.verifyPublication(c);let f=E.code===0&&!E.stdout.toString().split(`
6
+ `).some(T=>T.startsWith("= "));return f&&await this.maintain(),{created:f?[...m.keys()].map(T=>T.slice(this.prefix.length)):[]}}if(E.code===0)throw new d("SYNC_PUBLICATION_UNKNOWN","the server accepted publication, but a fresh read did not confirm all context objects","retry after checking the location; do not discard local context");if(this.tip===t&&!g)throw new d("SYNC_LOCATION_REFUSED_WRITE",`${this.name} refused publication`,"check repository write access and branch rules, then retry",y.trim());if(this.tip===t&&!O&&g){await new Promise(f=>setTimeout(f,200*(l+1)+Math.random()*200));continue}await new Promise(f=>setTimeout(f,50*(l+1)+Math.random()*100))}throw new d("SYNC_PUBLICATION_UNKNOWN",`publication could not be confirmed after ${S} attempts; your local work is safe`,"run kane-cli context sync status, then retry",w||void 0)}finally{i=!0,r.clear()}}}}async maintain(){try{await this.exec(["--git-dir",this.repo,"gc","--auto","--quiet"],{timeout:3e5})}catch{}}assertUnchanged(e){for(let[t,r]of e)if(t.startsWith(`${this.prefix}kane-context/`)&&this.tree.get(t)!==r)throw new d("SYNC_REMOTE_ROLLED_BACK","The location changed or removed previously observed context data.","Ask the repository owner to restore the published context; keep your local copy.")}async verifyPublication(e){try{await this.verify(e)}catch{throw new d("SYNC_PUBLICATION_UNKNOWN","Publication was observed, but its bytes could not be fully verified. Your local work is safe.","Check the connection and retry before discarding local context.")}}async verify(e){for(let[t,r]of e){if(this.tree.get(t)!==r)throw new Error("Published context verification failed");let i=await this.run(["cat-file","blob",r]);if((await this.run(["hash-object","--no-filters","--stdin"],{input:i})).toString().trim()!==r)throw new Error("Published bytes do not match their Git object")}}async checkAttributes(e,t=[]){if(!e)return;let r=P(_(j(),"kane-git-attributes-"));try{let i={GIT_INDEX_FILE:_(r,"index")};await this.run(["read-tree",e],{env:i});let s=["commits/000000/000000001.json","blobs/ab/1234","proposals/sample/1234.json"].map(u=>`${this.prefix}kane-context/v1/${u}`),o=t.filter(u=>u.startsWith(`${this.prefix}kane-context/`)&&!u.endsWith("/.gitattributes")),a=Buffer.from([...new Set([...s,...o])].join("\0")+"\0"),h=(await this.run(["check-attr","--cached","-z","--stdin","text","filter","ident","working-tree-encoding"],{env:i,input:a})).toString().split("\0");for(let u=0;u+2<h.length;u+=3)if(!["unset","unspecified"].includes(h[u+2]))throw new d("SYNC_LOCATION_REFUSED_WRITE",`Git attributes transform context bytes (${h[u+1]}).`,"Use a dedicated context repository with no text, filter, ident or encoding conversions.")}finally{$(r,{recursive:!0,force:!0})}}async build(e,t){let r=P(_(j(),"kane-git-index-"));try{let i={GIT_INDEX_FILE:_(r,"index")};await this.run(e?["read-tree",e]:["read-tree","--empty"],{env:i});let s=Buffer.from([...t].map(([l,m])=>`100644 ${m} ${l}\0`).join(""));await this.run(["update-index","-z","--index-info"],{env:i,input:s});let a=["commit-tree",(await this.run(["write-tree"],{env:i})).toString().trim(),...e?["-p",e]:[],"-m",`Append context objects
7
+
8
+ Kane-Context: v1`],c=await this.exec(["--git-dir",this.repo,...a]),h=(c.code===0?c.stdout:await this.run(a,{env:$e})).toString().trim(),u=(await this.run(["rev-list","--parents","-n","1",h])).toString().trim().split(" ");if(u.length!==(e?2:1)||e&&u[1]!==e)throw new Error("Unsafe Git commit parent");let g=(await this.run(["diff-tree","--no-commit-id","--name-status","--no-renames","-r","-z",...e?[e,h]:["--root",h]])).toString().split("\0").filter(Boolean);if(g.length!==t.size*2||g.some((l,m)=>m%2===0?l!=="A":!t.has(l)))throw new Error("Unsafe Git commit: unexpected changed path or file mode");let w=await this.readTree(h),S=e?await this.readTree(e):new Map;if(w.size!==S.size+t.size||[...S].some(([l,m])=>w.get(l)!==m)||[...t].some(([l,m])=>S.has(l)||w.get(l)!==m))throw new Error("Unsafe Git commit: only intended new keys may be added");return h}finally{$(r,{recursive:!0,force:!0})}}async putIfAbsent(e,t){let r=await this.beginTransaction();try{if(await r.stageIfAbsent(e,t)==="exists")return"exists";try{return(await r.commit()).created.includes(e)?"created":"exists"}catch(i){if(i instanceof d&&["SYNC_POSITION_TAKEN","SYNC_OBJECT_CORRUPT"].includes(i.code)&&await this.head(e))return"exists";throw i}}finally{await r.abort()}}async probe(){await this.init();let e=ee(F(16).toString("hex"));try{await this.putIfAbsent(e,Buffer.from("connection check"))}catch(c){if(c instanceof d&&c.code==="SYNC_LOCATION_REFUSED_WRITE")return await this.refresh(),{tier:3,detail:"This location can be downloaded, but publication was refused."};throw c}if(await this.putIfAbsent(e,Buffer.from("must not replace"))!=="exists")throw new d("SYNC_PROBE_INCONCLUSIVE","Exclusive create could not be verified.","Retry the connection check.");let t=P(_(j(),"kane-git-reader-"));try{let c=new n({...this.options,cacheDir:t});if(!Buffer.from(await c.get(e)??[]).equals(Buffer.from("connection check"))||!await c.head(e)||!(await c.list(e)).includes(e))throw new Error("Independent reader could not confirm published bytes")}finally{$(t,{recursive:!0,force:!0})}let r=`refs/kane/probe/${F(16).toString("hex")}`,i=Array.from({length:8},()=>new n({...this.options,ref:r}));if((await Promise.allSettled(i.map(c=>c.head(e)))).some(c=>c.status==="rejected"))throw new d("SYNC_PROBE_INCONCLUSIVE","The concurrent connection check could not initialize its independent clients.","Retry the connection check.");let o=await Promise.allSettled(i.map((c,h)=>c.putIfAbsent(e,Buffer.from(`contender ${h}`))));if(o.some(c=>c.status==="rejected"))throw new d("SYNC_PROBE_INCONCLUSIVE","The server did not complete the concurrent connection check. Its scratch-ref policy may differ from the storage branch.","Ask the repository owner to allow the connection-check ref, then retry.");if(o.filter(c=>c.status==="fulfilled"&&c.value==="created").length!==1)throw new d("SYNC_PROBE_INCONCLUSIVE","The concurrent connection check did not produce exactly one winner.","Do not publish to this location until its connection check passes.");return{tier:1,detail:"Can download and publish; independent reads and concurrent writes verified."}}};import{closeSync as Ge,existsSync as Ue,fsyncSync as De,linkSync as Le,lstatSync as Ke,mkdirSync as Be,openSync as He,readFileSync as Me,readdirSync as Ye,realpathSync as q,rmSync as he,statSync as z,writeFileSync as Fe}from"fs";import{randomBytes as je}from"crypto";import{dirname as de,join as ue,resolve as le,sep as U}from"path";var ze=[/^Dropbox( \(.*\))?$/,/^Mobile Documents$/,/^OneDrive(-.*)?$/,/^Google ?Drive(-.*)?$/,/^My Drive$/,/^CloudStorage$/,/^iCloud Drive/],We="a folder synced by Dropbox, OneDrive, Google Drive or iCloud cannot be a location: these keep both sides of a conflict as duplicate files instead of refusing the second write \u2014 use a directory outside the sync client, a git-tracked folder, or an s3:// bucket";function fe(n){return n.split(U).some(e=>ze.some(t=>t.test(e)))}function qe(n){try{return q(n)}catch{return n}}var pe=".tmp-";function Xe(n){try{return Ke(n),!0}catch{return!1}}var b=n=>n.code??"",x=new Set(["ENOENT","ENOTDIR"]),W=new Set(["EACCES","EPERM"]),D=class{kind="dir";contractVersion=1;ceilingTier;root;createRoot;constructor(e,t={}){if(this.root=le(e),fe(this.root)||fe(qe(this.root)))throw new Error(We);this.ceilingTier=1,this.createRoot=t.createRoot??!0}requireRoot(){if(!this.createRoot){try{if(z(this.root).isDirectory())return}catch(e){if(W.has(b(e)))throw this.denied();if(!x.has(b(e)))throw e}throw this.unreachable()}}unreachable(){return new d("SYNC_LOCATION_UNREACHABLE",`nothing answered at ${this.root}: that folder does not exist and cannot be created`,"check the path, then run the command again")}denied(){return new d("SYNC_LOCATION_DENIED",`${this.root} cannot be read by this account`,"ask the owner of the folder for access")}readFault(e){return W.has(b(e))?this.denied():e}writeFault(e){return x.has(b(e))||b(e)==="EROFS"?this.rootExists()?this.refusedWrite("its filesystem is read-only"):this.unreachable():W.has(b(e))?this.refusedWrite("this account has no write access"):e}refusedWrite(e){return new d("SYNC_LOCATION_REFUSED_WRITE",`${this.root} cannot be written: ${e}`,"ask the owner of the folder for write access, or pull from it without pushing")}rootExists(){try{return z(this.root).isDirectory()}catch{return!1}}path(e){let t=e.split("/"),r=e!==""&&!e.startsWith("/")&&!e.includes("\\")&&t.every(s=>s!==""&&s!=="."&&s!==".."),i=r?le(this.root,...t):"";if(!r||!i.startsWith(this.root+U)||!this.contained(i))throw new Error(`bad key ${e}`);return i}contained(e){let t=e;for(;!Xe(t);)t=de(t);if(t===this.root||!t.startsWith(this.root+U))return!0;try{let r=q(this.root),i=q(t);return i===r||i.startsWith(r+U)}catch{return!1}}async head(e){this.requireRoot();try{return z(this.path(e)).isFile()}catch(t){if(x.has(b(t)))return!1;throw this.readFault(t)}}async get(e){this.requireRoot();try{return new Uint8Array(Me(this.path(e)))}catch(t){if(x.has(b(t)))return null;throw this.readFault(t)}}async list(e){this.requireRoot();let t=e.lastIndexOf("/"),r=t===-1?"":e.slice(0,t),i=r===""?this.root:this.path(r),s=[],o=(a,c)=>{for(let h of Ye(a,{withFileTypes:!0})){let u=c+h.name;h.isDirectory()?o(ue(a,h.name),`${u}/`):!h.name.startsWith(pe)&&u.startsWith(e)&&s.push(u)}};try{o(i,r===""?"":`${r}/`)}catch(a){if(x.has(b(a))&&!Ue(i))return[];throw this.readFault(a)}return s.sort()}async putIfAbsent(e,t){this.requireRoot();let r=this.path(e),i=de(r),s=ue(i,`${pe}${process.pid}-${je(6).toString("hex")}`),o;try{Be(i,{recursive:!0}),o=He(s,"wx")}catch(c){throw this.writeFault(c)}try{Fe(o,t),De(o)}finally{Ge(o)}let a="created";try{Le(s,r)}catch(c){if(c.code!=="EEXIST")throw he(s,{force:!0}),c;a="exists"}return he(s,{force:!0}),Z(i),a}};var J=new TextEncoder,Je={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Ve=new Set(["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"]),L=class{constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:i,region:s,cache:o,retries:a,initRetryMs:c}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=i,this.region=s,this.cache=o||new Map,this.retries=a??10,this.initRetryMs=c||50}async sign(e,t){if(e instanceof Request){let{method:s,url:o,headers:a,body:c}=e;t=Object.assign({method:s,url:o,headers:a},t),t.body==null&&a.has("Content-Type")&&(t.body=c!=null&&a.has("X-Amz-Content-Sha256")?c:await e.clone().arrayBuffer()),e=o}let r=new V(Object.assign({url:e.toString()},t,this,t&&t.aws)),i=Object.assign({},t,await r.sign());delete i.aws;try{return new Request(i.url.toString(),i)}catch(s){if(s instanceof TypeError)return new Request(i.url.toString(),Object.assign({duplex:"half"},i));throw s}}async fetch(e,t){for(let r=0;r<=this.retries;r++){let i=fetch(await this.sign(e,t));if(r===this.retries)return i;let s=await i;if(s.status<500&&s.status!==429)return s;await new Promise(o=>setTimeout(o,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new Error("An unknown error occurred, ensure retries is not negative")}},V=class{constructor({method:e,url:t,headers:r,body:i,accessKeyId:s,secretAccessKey:o,sessionToken:a,service:c,region:h,cache:u,datetime:g,signQuery:w,appendSessionToken:S,allHeaders:l,singleEncode:m}){if(t==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(o==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(i?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=i,this.accessKeyId=s,this.secretAccessKey=o,this.sessionToken=a;let I,E;(!c||!h)&&([I,E]=Qe(this.url,this.headers)),this.service=c||I||"",this.region=h||E||"us-east-1",this.cache=u||new Map,this.datetime=g||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=w,this.appendSessionToken=S||this.service==="iotdevicegateway",this.headers.delete("Host"),this.service==="s3"&&!this.signQuery&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD");let y=this.signQuery?this.url.searchParams:this.headers;if(y.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&y.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(p=>l||!Ve.has(p)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(p=>p+":"+(p==="host"?this.url.host:(this.headers.get(p)||"").replace(/\s+/g," "))).join(`
9
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!y.has("X-Amz-Expires")&&y.set("X-Amz-Expires","86400"),y.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),y.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),y.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");m||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ye(this.encodedPath);let O=new Set;this.encodedSearch=[...this.url.searchParams].filter(([p])=>{if(!p)return!1;if(this.service==="s3"){if(O.has(p))return!1;O.add(p)}return!0}).map(p=>p.map(f=>ye(encodeURIComponent(f)))).sort(([p,f],[T,C])=>p<T?-1:p>T?1:f<C?-1:f>C?1:0).map(p=>p.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let i=await v("AWS4"+this.secretAccessKey,e),s=await v(i,this.region),o=await v(s,this.service);r=await v(o,"aws4_request"),this.cache.set(t,r)}return X(await v(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,X(await me(await this.canonicalString()))].join(`
10
+ `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
11
+ `,this.signedHeaders,await this.hexBodyHash()].join(`
12
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256")||(this.service==="s3"&&this.signQuery?"UNSIGNED-PAYLOAD":null);if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new Error("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=X(await me(this.body||""))}return e}};async function v(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?J.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,J.encode(e))}async function me(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?J.encode(n):n)}var ge=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function X(n){let e=new Uint8Array(n),t="";for(let r=0;r<e.length;r++){let i=e[r];t+=ge[i>>>4&15],t+=ge[i&15]}return t}function ye(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}function Qe(n,e){let{hostname:t,pathname:r}=n;if(t.endsWith(".on.aws")){let a=t.match(/^[^.]{1,63}\.lambda-url\.([^.]{1,63})\.on\.aws$/);return a!=null?["lambda",a[1]||""]:["",""]}if(t.endsWith(".r2.cloudflarestorage.com"))return["s3","auto"];if(t.endsWith(".backblazeb2.com")){let a=t.match(/^(?:[^.]{1,63}\.)?s3\.([^.]{1,63})\.backblazeb2\.com$/);return a!=null?["s3",a[1]||""]:["",""]}let i=t.replace("dualstack.","").match(/([^.]{1,63})\.(?:([^.]{0,63})\.)?amazonaws\.com(?:\.cn)?$/),s=i&&i[1]||"",o=i&&i[2];if(o==="us-gov")o="us-gov-west-1";else if(o==="s3"||o==="s3-accelerate")o="us-east-1",s="s3";else if(s==="iot")t.startsWith("iot.")?s="execute-api":t.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let a=(e.get("X-Amz-Target")||"").split(".")[0];a==="AnyScaleFrontendService"?s="application-autoscaling":a==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else o==null&&s.startsWith("s3-")?(o=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):o&&/-\d$/.test(s)&&!/-\d$/.test(o)&&([s,o]=[o,s]);return[Je[s]||s,o||""]}var Q=3,Ze=[300,900],et=200,tt=15e3,rt=/<Key>([^<]*)<\/Key>/g,it=/<NextContinuationToken>([^<]*)<\/NextContinuationToken>/,we=n=>new Promise(e=>setTimeout(e,n));function nt(n){let e=n instanceof Error?n.name:"";return e==="TimeoutError"||e==="AbortError"?"timeout":"network"}async function st(n){try{return await n.text()}catch{return""}}var K=class n{kind="s3";contractVersion=1;ceilingTier=1;client;base;prefix;pageSize;name;constructor(e){this.client=new L({accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey,service:"s3",region:e.region}),this.base=e.endpoint?`${e.endpoint.replace(/\/+$/,"")}/${e.bucket}`:`https://${e.bucket}.s3.${e.region}.amazonaws.com`,this.prefix=e.prefix,this.pageSize=e.pageSize??1e3,this.name=e.name??"this location"}url(e){return`${this.base}/${this.prefix}${e}`}static line(e,t,r){return`${e} ${new URL(t).pathname} -> ${r}`}answer(e,t,r){let i=n.line(e,t,r);return r===404?new d("SYNC_LOCATION_UNREACHABLE",`nothing answered at ${this.base}: no bucket there`,"check the bucket name and the endpoint, then run the command again",i):r===401||r===403?new d("SYNC_LOCATION_DENIED",`the bucket at ${this.base} did not accept ${this.name}'s access keys, even for reading`,`ask the owner of the bucket for access, or bind it again with the right keys: kane-cli context sync add ${this.name} <descriptor> --credential-env <VAR>`,i):r>=500||r===429?this.unreachable(i):r===301||r===307||r===308?new d("SYNC_LOCATION_UNREACHABLE",`the bucket at ${this.base} answered with a redirect: it lives in another region or behind another endpoint`,`set region=<its region> (or endpoint=<its endpoint>) in the descriptor, then bind ${this.name} again`,i):new Error(i)}unreachable(e){return new d("SYNC_LOCATION_UNREACHABLE",`nothing answered at ${this.base}`,"check the endpoint and your network, then run the command again",e)}async request(e,t,r={}){let i="";for(let s=0;s<Q;s++){s>0&&await we(Ze[s-1]);let o;try{o=await fetch(await this.client.sign(t,{method:e,headers:r.headers,body:r.body&&new Uint8Array(r.body),signal:AbortSignal.timeout(tt)}))}catch(a){i=nt(a);continue}if((o.status>=500||o.status===429)&&s<Q-1){i=String(o.status);continue}return o}throw this.unreachable(`${n.line(e,t,i)} after ${Q} attempts`)}async head(e){let t=await this.request("HEAD",this.url(e));if(t.status===200)return!0;if(t.status===404)return!1;throw this.answer("HEAD",this.url(e),t.status)}async bodyOf(e,t,r,i){try{return await i(e)}catch{throw this.unreachable(n.line(t,r,"body read failed"))}}async get(e){let t=await this.request("GET",this.url(e));if(t.status===200)return new Uint8Array(await this.bodyOf(t,"GET",this.url(e),r=>r.arrayBuffer()));if(t.status===404)return null;throw this.answer("GET",this.url(e),t.status)}async list(e){let t=[],r=null;do{let i=new URLSearchParams({"list-type":"2",prefix:this.prefix+e,"max-keys":String(this.pageSize)});r&&i.set("continuation-token",r);let s=`${this.base}?${i.toString()}`,o=await this.request("GET",s);if(o.status!==200)throw this.answer("GET",s,o.status);let a=await this.bodyOf(o,"GET",s,c=>c.text());for(let c of a.matchAll(rt))t.push(c[1].slice(this.prefix.length));r=it.exec(a)?.[1]??null}while(r);return t.sort()}async putIfAbsent(e,t){let r=await this.create(e,t);if(r!=="conflict")return r;if(await we(et),await this.head(e))return"exists";let i=await this.create(e,t);if(i!=="conflict")return i;throw new Error(`${n.line("PUT",this.url(e),409)} twice (ConditionalRequestConflict) and the key is still absent`)}async create(e,t){let r=this.url(e),i=await this.request("PUT",r,{headers:{"If-None-Match":"*","Content-Type":"application/octet-stream"},body:t});if(i.status===200||i.status===201)return"created";if(i.status===412)return"exists";if(i.status===409&&(await st(i)).includes("ConditionalRequestConflict"))return"conflict";throw i.status===401||i.status===403?new d("SYNC_LOCATION_REFUSED_WRITE",`${this.name}'s access keys cannot write to ${this.base}`,"ask the owner of the bucket for write access, or pull from it without pushing",n.line("PUT",r,i.status)):this.answer("PUT",r,i.status)}};import{chmodSync as ot,mkdirSync as at,readFileSync as ct,rmSync as ht,writeFileSync as dt}from"fs";import{join as Se}from"path";var Ee="context-sync",ut=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function k(n,e=A){if(!ut.test(n))throw new Error(`bad location name ${JSON.stringify(n)} \u2014 letters, digits, dot, dash and underscore only`);return Se(e,Ee,`${n}.json`)}function Te(n,e=A){let t=process.env.KANE_SYNC_S3_ACCESS_KEY_ID,r=process.env.KANE_SYNC_S3_SECRET_ACCESS_KEY;if(t&&r)return{accessKeyId:t,secretAccessKey:r};let i=k(n,e),s;try{s=ct(i,"utf-8")}catch{return null}let o;try{o=JSON.parse(s)}catch(a){throw new Error(`${i} is not readable JSON: ${a instanceof Error?a.message:String(a)}`)}if(typeof o!="object"||o===null||!("accessKeyId"in o)||!("secretAccessKey"in o)||typeof o.accessKeyId!="string"||typeof o.secretAccessKey!="string")throw new Error(`${i} does not hold an access key and a secret \u2014 re-add the location to replace it`);return{accessKeyId:o.accessKeyId,secretAccessKey:o.secretAccessKey}}function Mt(n,e,t=A){let r=k(n,t);at(Se(t,Ee),{recursive:!0,mode:448}),dt(r,JSON.stringify(e)+`
13
+ `,{mode:384}),ot(r,384)}function Yt(n,e=A){ht(k(n,e),{force:!0})}function Xt(n,e,t,r={}){switch(n.kind){case"fake":{let i=t?.get(n.location.slice(7));if(!i)throw new Error(`${n.location} is a test-only location and no test registered it`);return i}case"git":return new G({url:n.gitUrl,branch:n.branch,prefix:n.prefix,name:e});case"dir":return new D(n.path,{createRoot:r.createRoot});case"s3":{let i=Te(e);if(!i)throw new Error(`no credentials for ${e} \u2014 re-add it with --credential-env <VAR> or --credential-file <path> (kane-cli context sync add), set KANE_SYNC_S3_ACCESS_KEY_ID and KANE_SYNC_S3_SECRET_ACCESS_KEY, or write {"accessKeyId", "secretAccessKey"} to ${k(e)} with mode 0600`);return new K({endpoint:n.endpoint,region:n.region,bucket:n.bucket,prefix:n.prefix,name:e,...i})}}}export{H as a,oe as b,gt as c,yt as d,k as e,Mt as f,Yt as g,Xt as h};
14
+ /*! Bundled license information:
15
+
16
+ aws4fetch/dist/aws4fetch.esm.mjs:
17
+ (**
18
+ * @license MIT <https://opensource.org/licenses/MIT>
19
+ * @copyright Michael Hart 2024
20
+ *)
21
+ */
@@ -0,0 +1,8 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as h}from"./chunk-VZ7KXRXB.js";import{c as _}from"./chunk-EYOCNMUM.js";import{dirname as T,isAbsolute as F,resolve as j}from"path";var k=["db","api","js","smartui","network_query","network_assertion"];var a=class extends Error{constructor(r,o,e){super(`[${o}${e!=null?`:${e}`:""}] ${r}`);this.file=o;this.line=e;this.name="TestMdParseError"}};var R=["if","elif","else","end-if","while","end-while"];var C={"end-if":"if","end-while":"while"};function v(n,t){let r=[],o=()=>r[r.length-1];for(let s of t){let i=s.controlFlow;if(i==="if"||i==="while"){r.push({kind:i,id:s.index,branch:0,elseSeen:!1}),s.block={id:s.index,branch:0,depth:r.length};continue}if(i==="elif"||i==="else"){let c=o();if(!c||c.kind!=="if")throw new a(`@${i} outside an open @if`,n,s.headingLine);if(c.elseSeen)throw new a(`@${i} after @else`,n,s.headingLine);c.branch+=1,c.elseSeen=i==="else",s.block={id:c.id,branch:c.branch,depth:r.length};continue}if(i==="end-if"||i==="end-while"){let c=o(),d=C[i];if(!c||c.kind!==d)throw new a(`@${i} without an open @${d}`,n,s.headingLine);s.block={id:c.id,branch:-1,depth:r.length},r.pop();continue}let l=o();l&&(s.block={id:l.id,branch:l.branch,depth:r.length})}let e=o();if(e){let s=t.find(i=>i.index===e.id);throw new a(`unclosed @${e.kind} block`,n,s?.headingLine)}}var P=new Set(["username","access_key","oauth","profile","project_id","folder_id"]),$=new Set(["mode","max_steps","timeout","global_context","local_context","variables","session_context","code_export","code_language","url","target","chrome_profile","cdp_endpoint","ws_endpoint","headless","app","no_reset","os_version","device_name","on_lock_conflict","tags","assurance","dataset"]),O=new Set(["optional"]),Y=new Set(["optional","variables"]),M=new Set(["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"]),N=new Set(["app","no_reset","os_version","device_name"]),B=new Set(["mode","on_lock_conflict","tags","assurance","dataset"]);function be(n,t){let r=t.split(`
3
+ `),{global:o,bodyStartLine:e}=I(n,r),{title:s,steps:i}=oe(n,r,e);return{path:n,title:s,global:o,steps:i}}function I(n,t){if(t[0]?.trim()!=="---")return{global:{},bodyStartLine:0};let r=-1;for(let l=1;l<t.length;l++)if(t[l].trim()==="---"){r=l;break}if(r===-1)throw new a("frontmatter is missing closing '---'",n,1);let o=t.slice(1,r).join(`
4
+ `),e;try{e=h(o)??{}}catch(l){throw new a(`invalid YAML in frontmatter: ${l.message}`,n,1)}if(E(n,e,"frontmatter",1),e.on_lock_conflict!==void 0){let l=e.on_lock_conflict;if(l!=="readonly"&&l!=="fail"&&l!=="wait")throw new a(`on_lock_conflict must be 'readonly' | 'fail' | 'wait', got: ${JSON.stringify(l)}`,n,1)}if(L(n,e,1),se(n,e,1),e.assurance!==void 0){let l=e.assurance;if(l===null||typeof l!="object"||Array.isArray(l))throw new a("assurance must be a mapping with sub-keys {id, base}",n,1);let c=l;for(let d of Object.keys(c))if(d!=="id"&&d!=="base")throw new a(`unknown assurance sub-key '${d}' \u2014 the engine block allows only {id, base}`,n,1);if(typeof c.id!="string"||c.id.length===0)throw new a("assurance.id must be a non-empty string (logical id)",n,1);if(c.base!==void 0&&!(typeof c.base=="string"&&/^sha256:[0-9a-f]+$/.test(c.base)))throw new a("assurance.base must be a 'sha256:<hex>' string",n,1)}if(e.tags!==void 0){let l=e.tags,c=Array.isArray(l)?l.map(d=>String(d)).join(","):String(l);e.tags=G(c,n,1)}if(e.target!==void 0&&(e.target=q(e.target,n,1)),e.app!==void 0&&(e.app=H(e.app,n,1)),e.no_reset!==void 0&&typeof e.no_reset!="boolean")throw new a(`no_reset must be boolean: got ${typeof e.no_reset}`,n,1);if(e.os_version!==void 0&&typeof e.os_version!="string")if(typeof e.os_version=="number")e.os_version=String(e.os_version);else throw new a(`os_version must be a string: got ${typeof e.os_version}`,n,1);let s=e.target,i=s==="emulator"||s==="simulator";if(i&&e.app===void 0)throw new a(`target: ${String(s)} needs an app \u2014 add \`app: <path-to-build | AppId>\``,n,1);if(!i&&e.app!==void 0)throw new a("app requires a mobile target \u2014 add `target: emulator` or `target: simulator`",n,1);if(!i&&e.no_reset!==void 0)throw new a("no_reset requires a mobile target \u2014 add `target: emulator` or `target: simulator`",n,1);if(!i&&e.os_version!==void 0)throw new a("os_version requires a mobile target \u2014 add `target: emulator` or `target: simulator`",n,1);if(e.device_name!==void 0&&typeof e.device_name!="string")throw new a(`device_name must be a string: got ${typeof e.device_name}`,n,1);if(!i&&e.device_name!==void 0)throw new a("device_name requires a mobile target \u2014 add `target: emulator` or `target: simulator`",n,1);return{global:e,bodyStartLine:r+1}}function G(n,t,r){let e=n.trim().replace(/^\[/,"").replace(/\]$/,"").split(",").map(s=>s.trim().toLowerCase());if(e.length===0||e.some(s=>s.length===0))throw new a("tags must be a non-empty list of non-empty strings",t,r);return[...new Set(e)]}var V=new Set(["chrome","cdp","ws","emulator","simulator"]),W="target must be one of 'chrome' | 'cdp' | 'ws' (web) or 'emulator' | 'simulator' (mobile, with a root `app:` key)";function q(n,t,r){if(typeof n=="string"&&V.has(n))return n;throw n!==null&&typeof n=="object"&&!Array.isArray(n)?new a(`the mapping form of target is no longer accepted \u2014 write flat keys:
5
+ target: emulator | simulator
6
+ app: <path-to-build | AppId>`,t,r):new a(`${W} \u2014 got: ${JSON.stringify(n)}`,t,r)}function H(n,t,r){if(typeof n!="string"||n.trim().length===0)throw new a("app must be a build (e.g. ./builds/app-debug.apk) or an app id from your cloud uploads",t,r);let o=n.trim();if(!/\.(apk|zip)$/i.test(o)&&!/^APP\d{6,}$/.test(o))throw new a(`app '${o}' is not a build \u2014 expected a path ending in .apk or .zip, or an app id from your cloud uploads.`,t,r);return z(o,t)}function z(n,t){return/^APP[0-9A-Za-z_-]+$/.test(n)||F(n)?n:j(T(t),n)}function ye(n){let t=n.target;if(!(t!=="emulator"&&t!=="simulator"))return{platform:_(t)??"",app:n.app??"",...n.no_reset!==void 0?{no_reset:n.no_reset}:{},...n.os_version!==void 0?{os_version:n.os_version}:{},...n.device_name!==void 0?{device_name:n.device_name}:{}}}function he(n){let t=n.target;return t==="chrome"||t==="cdp"||t==="ws"?t:void 0}var D=/\s@verifies\s+(ac-[\w.:\/-]+(?:\s*,\s*ac-[\w.:\/-]+)*)\s*$/;function J(n,t,r){let o=D.exec(t);if(o)return{label:t.slice(0,o.index).trim(),verifies:o[1].split(",").map(s=>s.trim())};let e=t.lastIndexOf("@verifies");if(e>0&&/\s/.test(t[e-1])){let s=t.slice(e+9).split(/[\s,]+/).filter(i=>i.length>0);if(s.length===0||s.every(i=>i.startsWith("ac-")))throw new a("malformed @verifies directive \u2014 expected '@verifies ac-<id>[, ac-<id>\u2026]' at the end of the heading",n,r)}return{label:t,verifies:[]}}var S=k.join("|"),U=new RegExp(`^(.*\\S)\\s+@(${S})\\s*$`),Z=new RegExp(`^@(${S})\\s*$`);function Q(n,t,r,o){let e=Z.exec(t);if(e)throw new a(`replay-only marker @${e[1]} needs a step label before it (e.g. '## Step 3 @${e[1]}')`,n,r);let s=U.exec(t);if(!s)return null;let i=s[2];if(o)throw new a(`only one replay-only marker per step \u2014 found @${o} and @${i}`,n,r);return{label:s[1].trim(),replayOnly:i}}var x=R.join("|"),X=new RegExp(`^(.*\\S)\\s+@(${x})\\s*$`),ee=new RegExp(`^@(${x})\\s*$`);function ne(n,t,r,o){let e=ee.exec(t);if(e)throw new a(`control-flow marker @${e[1]} needs a step label before it (e.g. '## banner is visible @${e[1]}')`,n,r);let s=X.exec(t);if(!s)return null;let i=s[2];if(o)throw new a(`only one control-flow marker per step \u2014 found @${o} and @${i}`,n,r);return{label:s[1].trim(),controlFlow:i}}function te(n,t,r){let o=t,e,s,i=()=>{let c=Q(n,o,r,e);c&&({label:o,replayOnly:e}=c);let d=ne(n,o,r,s);d&&({label:o,controlFlow:s}=d)};i();let l=J(n,o,r);if(o=l.label,i(),e&&s)throw new a(`@${s} is a control-flow marker and @${e} a replay-only marker \u2014 a step carries one or the other`,n,r);return{label:o,verifies:l.verifies,...e?{replayOnly:e}:{},...s?{controlFlow:s}:{}}}function oe(n,t,r){let o,e=r;for(;e<t.length&&t[e].trim()==="";)e++;let s=e<t.length?/^#\s+(.+?)\s*$/.exec(t[e]):null;s&&(o=s[1],e++);let i=[];for(let c=e;c<t.length;c++)/^##\s/.test(t[c])&&i.push(c);let l=[];for(let c=0;c<i.length;c++){let d=i[c],p=i[c+1]??t.length,m=t[d].replace(/^##\s+/,"").trim(),{label:w,verifies:f,replayOnly:u,controlFlow:g}=te(n,m,d+1),b=t.slice(d+1,p),{config:A,body:y,optional:K}=re(n,d+1,b);if(u&&y.kind==="import_ref")throw new a(`@${u} is a replay-only marker for objective steps \u2014 it cannot mark an @import row`,n,d+1);if(g&&y.kind==="import_ref")throw new a(`@${g} is a control-flow marker for objective steps \u2014 it cannot mark an @import row`,n,d+1);l.push({index:c+1,heading:w,verifies:f,config:A,body:y,headingLine:d+1,optional:K,...u?{replayOnly:u}:{},...g?{controlFlow:g}:{}})}return v(n,l),{title:o,steps:l}}function re(n,t,r){let o=0;for(;o<r.length&&r[o].trim()==="";)o++;let e,s=t;if(o<r.length&&/^```yaml\s*$/.test(r[o])){let f=o;s=t+f,o++;let u=-1;for(;o<r.length;){if(/^```\s*$/.test(r[o])){u=o;break}o++}if(u===-1)throw new a("step-config fenced ```yaml block is not closed",n,s);let g=r.slice(f+1,u).join(`
7
+ `);try{e=h(g)??{}}catch(b){throw new a(`invalid YAML in step config: ${b.message}`,n,s)}o=u+1}let i=ie(r.slice(o)),l=i.filter(f=>f.trim()!=="");if(l.length>0&&/^@session\s+/.test(l[0].trim()))throw new a("@session is no longer supported (iteration 3); use @import instead",n,t);let c=/^@import\s+(\S.*)$/,p=i.filter(f=>c.test(f.trim())).length>0;if(p&&l.length!==1)throw new a("step body must be exactly one of prose / @import",n,t);let m=!1,w;if(e){if(E(n,e,p?"step config (ref)":"step config (objective)",s),L(n,e,s),typeof e.optional=="boolean")m=e.optional;else if(e.optional!==void 0)throw new a(`step config 'optional' must be boolean: got ${typeof e.optional}`,n,s);let f={...e};delete f.optional,p&&delete f.variables,!p&&Object.keys(f).length>0&&(w=f)}if(p){let u=c.exec(l[0].trim())[1].trim(),g=e?.variables;return{body:{kind:"import_ref",path:u,...g&&Object.keys(g).length>0?{bindings:g}:{}},optional:m}}return{body:{kind:"objective",text:i.join(`
8
+ `).trim()},config:w,optional:m}}function ie(n){let t=0,r=n.length;for(;t<r&&n[t].trim()==="";)t++;for(;r>t&&n[r-1].trim()==="";)r--;return n.slice(t,r)}function L(n,t,r){let o=t.variables;if(o==null)return;if(typeof o!="object"||Array.isArray(o))throw new a("variables must be an object map",n,r);let e={};for(let[s,i]of Object.entries(o))if(typeof i=="string")e[s]={value:i};else if(i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.value=="string")e[s]=i;else throw new a(`variable '${s}' must be a string or { value: ... } object`,n,r);t.variables=e}function se(n,t,r){let o=t.dataset;if(o==null)return;if(typeof o=="string"){if(!o.trim())throw new a("dataset needs an id",n,r);t.dataset={id:o.trim()};return}if(typeof o!="object"||Array.isArray(o))throw new a("dataset must be an id or a mapping { id, row }",n,r);let e=o;for(let i of Object.keys(e))if(i!=="id"&&i!=="row")throw new a(`unknown dataset sub-key '${i}' \u2014 only { id, row } are allowed`,n,r);if(typeof e.id!="string"||!e.id.trim())throw new a("dataset needs an id",n,r);let s={id:e.id.trim()};if(e.row!==void 0){let i=e.row;if(!(typeof i=="string"&&i.trim().length>0&&!/^\d+$/.test(i.trim())))throw new a(`dataset row must be the row's _id as Test Manager shows it, not a position: got ${JSON.stringify(i)}`,n,r);s.row=i.trim()}t.dataset=s}function E(n,t,r,o){for(let e of Object.keys(t)){if(P.has(e))throw new a(`auth/identity keys are CLI-only: ${e}`,n,o);if(r==="frontmatter"){if(O.has(e))throw new a(`step-only key in frontmatter: ${e}`,n,o);if(!$.has(e))throw new a(`unknown config key: ${e}`,n,o)}else if(r==="step config (objective)"){if(!$.has(e)&&!O.has(e))throw new a(`unknown config key: ${e}`,n,o);if(M.has(e))throw new a(`chrome config is global-only: ${e}`,n,o);if(N.has(e))throw new a(`'${e}' is global-only: the whole run drives one app`,n,o);if(B.has(e))throw new a(`'${e}' is run-level and cannot be set per-step`,n,o)}else if(!Y.has(e))throw new a(`step config on @import may only contain 'optional' / 'variables': got ${e}`,n,o)}}export{be as a,ye as b,he as c,D as d};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as Bt}from"./chunk-ZMNJBUAO.js";import{f as tr}from"./chunk-W5TTF7GB.js";import{a as Ft}from"./chunk-I7TIGB7K.js";import{a as te,c as Yt,e as Zt,f as qe,g as Qt,h as nr}from"./chunk-6IAA644J.js";import{a as Xt,b as rr,c as sr,d as ir,e as dt,f as or}from"./chunk-5G22NOZK.js";import{a as ke,b as qt,c as Gt,d as Lt,e as Vt}from"./chunk-YEZYO5QH.js";import{a as Kt,b as Jt}from"./chunk-BZAGVBCX.js";import{a as er}from"./chunk-GX3FPJUG.js";import{a as zt}from"./chunk-L2TV4G56.js";import{c as Wt}from"./chunk-IVQX3AKL.js";import{e as Ut}from"./chunk-J2UN2AHO.js";import{a as Fe}from"./chunk-TMRLBSIA.js";import{g as Mt}from"./chunk-54JZ6VEW.js";import{a as $e,b as ct}from"./chunk-DNNZ353O.js";import{b as Nt}from"./chunk-YKTYVJBN.js";import{a as Ht,e as jt}from"./chunk-EV64VI66.js";import{a as Se}from"./chunk-NVGBE2DR.js";import{b as nt}from"./chunk-IDX3TOPY.js";import{C as ee,m as be,q as Be}from"./chunk-W3Z7AZNT.js";import{g as It}from"./chunk-XMTSHHYQ.js";import{e as at}from"./chunk-DBIBROYW.js";import{d as me}from"./chunk-AKX4VRRR.js";import{b as Ot}from"./chunk-IAHKTEET.js";import{a as At}from"./chunk-5EOX4MEY.js";import{appendFileSync as wr,mkdirSync as ut,rmdirSync as br,writeFileSync as lt}from"fs";import{dirname as mr,extname as Sr,join as ce}from"path";var X=class extends Error{code;constructor(e,a){super(`${e}: ${a}`),this.name="ProposalAdapterError",this.code=e}};function cr(r){return r.version===2}var ar=8;function vr(r){let e=/^extract@(\d+)$/.exec(r??"");return e?Number.parseInt(e[1],10):null}var yr=r=>typeof r=="object"&&r!==null&&"op"in r;function Ge(r,e,a){return{anchor:r.anchor,quote:r.quote,...a||r.source_id!==e?{source_id:r.source_id}:{}}}function dr(r,e,a={}){let m=vr(a.templateVersion),x=m!==null&&m>=5,_=m!==null&&m<5,y=r.archived!=null&&r.archived.length>0&&m!==null&&m<5;if(y&&a.warn?.(`dropped ${r.archived.length} archive op(s): the bound extract template @${m} never described archiving \u2014 nothing was archived; the use-cases still land`),!x&&r.read_basis.length!==1)throw new X("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${r.read_basis.length}`);if(r.read_basis.length===0)throw new X("READ_BASIS_COUNT","read_basis must not be empty");let v=r.read_basis[0],h=r.read_basis.length>1,$=r.use_cases.map(i=>{if(_&&i.cite.length!==1)throw new X("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);if(i.cite.length<1||i.cite.length>ar)throw new X("CITE_COUNT",`${i.temp_ref}: 1..${ar} cites allowed, got ${i.cite.length}`);let M=(f,re)=>{if(!x&&f!==v.source_id)throw new X("SOURCE_MISMATCH",`${re}: cite source ${f} != read_basis source ${v.source_id} (single-source)`)};M(i.cite[0].source_id,i.temp_ref);let P=i.cite.map(f=>(M(f.source_id,i.temp_ref),Ge(f,v.source_id,x&&(h||f.source_id!==v.source_id)))),l=(i.updated?.criteria??[]).some(yr);if(!x&&l)throw new X("CRITERIA_OPS_UNSUPPORTED",`${i.temp_ref}: op-union updated.criteria (keep/set/remove) needs an extract@5+ binding \u2014 this session is bound to ${a.templateVersion??"an unversioned template"}`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:P[0],...P.length>1?{cites:P}:{},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:{...i.updated.title!=null?{title:i.updated.title}:{},...i.updated.description!=null?{description:i.updated.description}:{},...i.updated.summary!=null?{summary:i.updated.summary}:{},...i.updated.actors!=null?{actors:i.updated.actors}:{},...i.updated.value!=null?{value:i.updated.value}:{},...i.updated.risk!=null?{risk:i.updated.risk}:{},...i.updated.criteria!=null?{criteria:l?i.updated.criteria.map(f=>f.op==="set"?{op:"set",text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}:f.op==="keep"?{op:"keep",ref:f.ref,text:f.text}:{op:"remove",ref:f.ref,text:f.text,reason:f.reason}):i.updated.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.updated.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{}}}:{},...i.change_note!=null?{change_note:i.change_note}:{}}});return{version:1,read_basis:e,source:{source_id:v.source_id,source_cid:v.source_cid},use_cases:$,...h?{sources:r.read_basis.map(i=>({source_id:i.source_id,source_cid:i.source_cid}))}:{},...r.extraction_of!=null&&r.extraction_of.length>0?{extraction_claims:r.extraction_of.map(i=>({source_id:i.source_id,completeness:i.completeness}))}:{},...r.archived!=null&&r.archived.length>0&&!y?{archived:r.archived.map(i=>({target:i.target,reason:i.reason,basis:i.basis}))}:{}}}function ur(r){let{contextDir:e,graph:a}=r,m=r.maxDigestBytes??4096,x={},_=[];for(let[h,$]of a.heads){if(x[h]=$,typeof $!="string")continue;let i=a.mediaOf($),M=a.getNode($)?.content?.blob;if(typeof M=="string")if(i.format==="image")_.push({source_id:h,cid:$,format:"image",blobRef:{path:Se(e,M),cid:M}});else{let P=$e(e,a,$)?.toString("utf8")??"";_.push({source_id:h,cid:$,format:i.format,text:P})}}_.sort((h,$)=>h.source_id<$.source_id?-1:1);let y=[];for(let h of a.byLabel(me.STYLENOTE).sort(($,i)=>$.cid<i.cid?-1:1))a.superseded.has(h.cid)||y.push(`\u2022 ${String(h.content.statement)} [${String(h.content.learned_from_kind)}]`);let v="";for(let h of y){if(Buffer.byteLength(v+h+`
2
+ import{b as Bt}from"./chunk-ZMNJBUAO.js";import{f as tr}from"./chunk-W5TTF7GB.js";import{a as Ft}from"./chunk-I7TIGB7K.js";import{a as te,c as Yt,e as Zt,f as qe,g as Qt,h as nr}from"./chunk-6DHEOPXX.js";import{a as Xt,b as rr,c as sr,d as ir,e as dt,f as or}from"./chunk-UHT5SVP5.js";import{a as ke,b as qt,c as Gt,d as Lt,e as Vt}from"./chunk-DMCEGMGB.js";import{a as zt}from"./chunk-L2TV4G56.js";import{a as Kt,b as Jt}from"./chunk-BZAGVBCX.js";import{c as Wt}from"./chunk-52WM3XYO.js";import{b as Nt}from"./chunk-YKTYVJBN.js";import{a as Ht,e as jt}from"./chunk-CRZUBDJ3.js";import{a as er}from"./chunk-GX3FPJUG.js";import{i as Mt}from"./chunk-AHXOKBVE.js";import{a as $e,b as ct}from"./chunk-ALCE5RLK.js";import{e as Ut}from"./chunk-GZ65ZA4C.js";import{a as Fe}from"./chunk-DMT3W26F.js";import{a as Se}from"./chunk-IE3OO5GI.js";import{c as nt}from"./chunk-5LJRZI7S.js";import{C as ee,m as be,q as Be}from"./chunk-GP7WD4UY.js";import{H as It,b as Ot}from"./chunk-3N6IAVD5.js";import{f as at}from"./chunk-FQNQVC5O.js";import{d as me}from"./chunk-AKX4VRRR.js";import{a as At}from"./chunk-5EOX4MEY.js";import{appendFileSync as wr,mkdirSync as ut,rmdirSync as br,writeFileSync as lt}from"fs";import{dirname as mr,extname as Sr,join as ce}from"path";var X=class extends Error{code;constructor(e,a){super(`${e}: ${a}`),this.name="ProposalAdapterError",this.code=e}};function cr(r){return r.version===2}var ar=8;function vr(r){let e=/^extract@(\d+)$/.exec(r??"");return e?Number.parseInt(e[1],10):null}var yr=r=>typeof r=="object"&&r!==null&&"op"in r;function Ge(r,e,a){return{anchor:r.anchor,quote:r.quote,...a||r.source_id!==e?{source_id:r.source_id}:{}}}function dr(r,e,a={}){let m=vr(a.templateVersion),x=m!==null&&m>=5,_=m!==null&&m<5,y=r.archived!=null&&r.archived.length>0&&m!==null&&m<5;if(y&&a.warn?.(`dropped ${r.archived.length} archive op(s): the bound extract template @${m} never described archiving \u2014 nothing was archived; the use-cases still land`),!x&&r.read_basis.length!==1)throw new X("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${r.read_basis.length}`);if(r.read_basis.length===0)throw new X("READ_BASIS_COUNT","read_basis must not be empty");let v=r.read_basis[0],h=r.read_basis.length>1,$=r.use_cases.map(i=>{if(_&&i.cite.length!==1)throw new X("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);if(i.cite.length<1||i.cite.length>ar)throw new X("CITE_COUNT",`${i.temp_ref}: 1..${ar} cites allowed, got ${i.cite.length}`);let M=(f,re)=>{if(!x&&f!==v.source_id)throw new X("SOURCE_MISMATCH",`${re}: cite source ${f} != read_basis source ${v.source_id} (single-source)`)};M(i.cite[0].source_id,i.temp_ref);let P=i.cite.map(f=>(M(f.source_id,i.temp_ref),Ge(f,v.source_id,x&&(h||f.source_id!==v.source_id)))),l=(i.updated?.criteria??[]).some(yr);if(!x&&l)throw new X("CRITERIA_OPS_UNSUPPORTED",`${i.temp_ref}: op-union updated.criteria (keep/set/remove) needs an extract@5+ binding \u2014 this session is bound to ${a.templateVersion??"an unversioned template"}`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:P[0],...P.length>1?{cites:P}:{},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:{...i.updated.title!=null?{title:i.updated.title}:{},...i.updated.description!=null?{description:i.updated.description}:{},...i.updated.summary!=null?{summary:i.updated.summary}:{},...i.updated.actors!=null?{actors:i.updated.actors}:{},...i.updated.value!=null?{value:i.updated.value}:{},...i.updated.risk!=null?{risk:i.updated.risk}:{},...i.updated.criteria!=null?{criteria:l?i.updated.criteria.map(f=>f.op==="set"?{op:"set",text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}:f.op==="keep"?{op:"keep",ref:f.ref,text:f.text}:{op:"remove",ref:f.ref,text:f.text,reason:f.reason}):i.updated.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.updated.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{}}}:{},...i.change_note!=null?{change_note:i.change_note}:{}}});return{version:1,read_basis:e,source:{source_id:v.source_id,source_cid:v.source_cid},use_cases:$,...h?{sources:r.read_basis.map(i=>({source_id:i.source_id,source_cid:i.source_cid}))}:{},...r.extraction_of!=null&&r.extraction_of.length>0?{extraction_claims:r.extraction_of.map(i=>({source_id:i.source_id,completeness:i.completeness}))}:{},...r.archived!=null&&r.archived.length>0&&!y?{archived:r.archived.map(i=>({target:i.target,reason:i.reason,basis:i.basis}))}:{}}}function ur(r){let{contextDir:e,graph:a}=r,m=r.maxDigestBytes??4096,x={},_=[];for(let[h,$]of a.heads){if(x[h]=$,typeof $!="string")continue;let i=a.mediaOf($),M=a.getNode($)?.content?.blob;if(typeof M=="string")if(i.format==="image")_.push({source_id:h,cid:$,format:"image",blobRef:{path:Se(e,M),cid:M}});else{let P=$e(e,a,$)?.toString("utf8")??"";_.push({source_id:h,cid:$,format:i.format,text:P})}}_.sort((h,$)=>h.source_id<$.source_id?-1:1);let y=[];for(let h of a.byLabel(me.STYLENOTE).sort(($,i)=>$.cid<i.cid?-1:1))a.superseded.has(h.cid)||y.push(`\u2022 ${String(h.content.statement)} [${String(h.content.learned_from_kind)}]`);let v="";for(let h of y){if(Buffer.byteLength(v+h+`
3
3
  `,"utf8")>m)break;v+=h+`
4
4
  `}return{read_basis:x,sources:_,styleNoteDigest:v}}function lr(r,e){let a=ur({contextDir:r,graph:e}).styleNoteDigest;return a.length>0?a:void 0}function mt(r,e,a,m,x){let _=null,y=()=>_??=x&&Object.keys(x).length>0?Promise.resolve(x):Ut().catch(()=>({}));return{contextDir:r,rootSid:e,locks:at(r,e),probe:m??Ft(r,{resolveAlias:async v=>qt(v,{env:process.env,auth:await y()}),embed:async(v,h)=>Gt(v,h,{env:process.env,auth:await y()}),readVector:(v,h)=>Lt(r,v,h),writeVector:(v,h,$)=>Vt(r,v,h,$)}),...a?.length?{reservedEventIds:a}:{}}}function ht(r,e){let a=[],m=[];for(let x of r.use_cases){let _=x.matches_existing;_?.cid&&e.hasNode(_.cid)?a.push({ref:_.cid,expectedTip:e.tipOf(_.cid)}):m.push({tempRef:x.temp_ref,title:String(x.title??""),probeText:String(x.title??"")})}return{verb:"extract",ucTargets:a,newBuCandidates:m,sourcePins:[{source_id:r.source.source_id,source_cid:r.source.source_cid}],readBasis:r.read_basis??null}}function $r(r,e){let a=(r.images??[]).filter(m=>m.delivery==="selected");if(a.length!==0)return a.map(m=>({ref:m.ref,...m.page!==void 0?{page:m.page}:{},...m.loc!==void 0?{loc:m.loc}:{},media_type:m.media_type,blob_ref:{path:Se(e,m.blob),cid:m.blob}}))}function kr(r){return r.length>8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>12&&r.toString("ascii",0,4)==="RIFF"&&r.toString("ascii",8,12)==="WEBP"?"image/webp":null}function Le(r){return r.toISOString().replace(/[-:]/g,"").slice(0,15)}function hr(r){return r.startsWith("su-conv-")?`conv-${Ot(Buffer.from(r,"utf8")).slice(0,8)}`:r}function pr(r){return r.source_id.startsWith("su-conv-")?"the conversation":r.source_id}function Rr(r,e,a){return`reading ${pr(r)}${a>1?` (source ${e} of ${a})`:""}`}function Re(r){return r.toLowerCase().trim().replace(/\s+/g," ")}function gr(r,e){let a=new Map,m=new Map,x=new Map;for(let{cid:y,content:v}of e.byLabel(me.USECASE)){if(e.superseded.has(y))continue;(e.trust.get(y)==="archived"?x:m).set(Re(String(v.title??"")),y)}let _=y=>e.trust.get(y)==="archived"?{cid:y,archived:!0,reason:e.archivedReason.get(y)}:{cid:y};for(let y of r.use_cases){if(y.matches_existing){let $=y.matches_existing.cid;if(e.superseded.has($)){let i=e.tipOf($);$=e.superseded.has(i)?null:i}if($!==null){a.set(y.temp_ref,_($));continue}}let v=m.get(Re(y.title));if(v){a.set(y.temp_ref,{cid:v});continue}let h=x.get(Re(y.title));h&&a.set(y.temp_ref,_(h))}return a}var fr=/^(\S+)\.criteria\[(\d+)\]/;function Cr(r,e,a){if(e.length===0||!e.every(x=>fr.test(x.detail)))return!1;let m=new Map;for(let x of e){let _=fr.exec(x.detail),y=m.get(_[1])??new Set;y.add(Number(_[2])),m.set(_[1],y)}for(let x of r.use_cases){let _=m.get(x.temp_ref);_?.size&&(x.criteria=(x.criteria??[]).filter((y,v)=>!_.has(v)),a(`${x.temp_ref}: dropped ${_.size} criteria with unverifiable cites \u2014 committed without them (criteria are hints, not oracles)`))}return!0}async function gt(r,e,a,m,x=()=>{},_,y){let v=(h,$)=>x(h,$,r.session_id);return Zt(r,e,a,m,x,{async onProposalEvent(h){let $=h,i=null,M=null;if(cr($))try{i=dr($,r.read_basis,{templateVersion:y?.()??null,warn:P=>{e.out(`warning: ${P}`),v("adapter",{warn:P})}}),v("adapter",{ok:!0,use_cases:i.use_cases.length})}catch(P){M=P instanceof X?P.message:String(P),v("adapter",{ok:!1,error:M})}else i=$;return i&&i.use_cases.length===0&&(e.out("warning: the agent proposed ZERO use-cases for this source"),e.emit?.({type:"warning",code:"ZERO_USE_CASES",message:"the agent proposed ZERO use-cases for this source"})),i&&_&&await _(i),{proposal:i,error:M}}})}var Dr=new Set(["agent","ci","override"]);async function Ss(r,e){let a=`ext-${Le(e.now?.()??new Date)}-lk${Math.random().toString(36).slice(2,8)}`,x=at(e.contextDir,a,e.now?{now:e.now}:void 0).tryAcquire([{kind:"extract"}],{hold:"session",verb:"extract"});if("contended"in x){let _=x.contended.holder,y=`another extraction is running on this context${_?` (pid ${_.pid})`:""} \u2014 retry when it finishes`;return e.out(y),e.emit?.({type:"error",message:y,code:"EXTRACT_LOCKED"}),2}try{return await Er(r,e)}finally{x.release()}}async function Er(r,e){let a=r.mode??"interactive";if(r.posture==="reconcile"){if(r.trust==="hold"){let o="error: --trust hold has no meaning here \u2014 a reconcile IS the review; drop the flag";return e.out(`${o} [TRUST_USAGE]`),e.emit?.({type:"error",message:o,code:"TRUST_USAGE"}),2}if(!r.source||!r.changeContext){let o="reconcile posture needs a pinned source and its change context \u2014 internal wiring fault";return e.out(`error: ${o}`),e.emit?.({type:"error",message:o,code:"POSTURE_USAGE"}),2}if(a==="ci"){let o="reconcile posture is not available under --mode ci \u2014 a held changeset needs a durable session; use --mode agent";return e.out(`error: ${o}`),e.emit?.({type:"error",message:o,code:"POSTURE_USAGE"}),2}}if(r.trust==="hold"&&a==="interactive")return e.out("error: --trust hold only applies to headless runs \u2014 in interactive chat you review items in-session anyway; use --mode agent to hold everything for review"),e.emit?.({type:"error",message:"error: --trust hold only applies to headless runs \u2014 use --mode agent",code:"TRUST_USAGE"}),2;if(a==="interactive"){if(!e.isTTY)return e.out("extract: --mode interactive needs a TTY (use --mode agent|ci|override headless)"),2}else if(!Dr.has(a))return e.out(`extract: unknown mode "${a}" \u2014 interactive | agent | ci | override`),2;if(r.trust!==void 0){if(a==="ci")return e.out("error: --trust is not available under --mode ci (ci is fail-closed \u2014 no trust dials)"),e.emit?.({type:"error",message:"error: --trust is not available under --mode ci",code:"TRUST_UNDER_CI"}),2;if(r.trust!=="auto"&&r.trust!=="hold")return e.out(`error: --trust must be auto | hold, got '${r.trust}'`),e.emit?.({type:"error",message:`error: --trust must be auto | hold, got '${r.trust}'`,code:"TRUST_USAGE"}),2}let m=e.telemetry?.enabled?e.telemetry:void 0,x=Le(e.now?.()??new Date),_=m?At(m.ids.context_instance_id??null,"extract",m.ids.session_id):ce(e.contextDir,"logs",`extract-${x}.log`);ut(mr(_),{recursive:!0});let y=`run-${x}-${Math.random().toString(36).slice(2,8)}`,v=o=>o==="error"||o==="failed_proposal"?"error":o==="repair_respawn"?"warn":"info",h=(o,u,s)=>{try{wr(_,JSON.stringify({ts:new Date().toISOString(),level:v(o),run_id:y,...m?{user_session_id:m.ids.session_id}:{},...s?{session_id:s}:{},kind:o,data:u})+`
5
5
  `)}catch{}m?.wireTrace(o,u,s)};{let o=e.out;e.out=u=>{h("transcript",{line:u}),o(u)}}e.chat||e.out(`trace: ${te(_)}`),e.emit?.({type:"run_start",mode:a,trace:_,...m?{session:m.ids.session_id}:{}});let $=Nt();if($&&e.out($),e.preflightTurn){let o=await e.preflightTurn();if(h("preflight",o),!o.ok)return e.out(o.message??"error: turn-endpoint preflight failed"),e.emit?.({type:"error",message:o.message??"error: turn-endpoint preflight failed",code:"PREFLIGHT"}),2}let i=ee(e.contextDir),M=lr(e.contextDir,i),P=r.sources?.length?r.sources:r.source?[r.source]:[];if(P.length>0){if(r.resume){let o="error: --source cannot be combined with --resume (the resumed session already has its scope)";return e.out(o),e.emit?.({type:"error",message:o,code:"SOURCE_WITH_RESUME"}),2}for(let o of P){let u=i.heads.get(o);if(typeof u!="string"){let s=u===null?`error: --source ${o} was ingested but is retired \u2014 re-ingest it to extract again`:`error: --source ${o} is not an ingested source (kane-cli context list shows them)`;return e.out(s),e.emit?.({type:"error",message:s,code:"SOURCE_UNKNOWN"}),2}}}let l=null,f=null;if(r.resume){try{{let c=await or(e.contextDir,r.resume,i,{verb:"extract",deps:{onWarn:C=>e.out(`note: ${C}`)}});{let C=Object.keys(c.handle.state.read_basis??{});if(C.length>1){let B=`error: session ${r.resume} spans ${C.length} sources \u2014 multi-source resume isn't supported yet; committed work is preserved (re-run kane-cli context extract for anything remaining)`;return e.out(B),e.emit?.({type:"error",message:B,code:"MULTI_SOURCE_RESUME"}),c.handle.release(),2}f=c,h("resume_kind",{kind:c.view.pointer===null?"bare-base":c.view.pointer.at==="final"?"pause":"crash"}),l={handle:c.handle,represent:c.represent,questions:c.questions,staleBasis:c.drift.map(B=>B.subject)}}}}catch(c){let C=c instanceof Error?c.message:String(c);return e.out(`error: ${C}`),e.emit?.({type:"error",message:`error: ${C}`,...c instanceof dt?{code:c.code}:{}}),c instanceof dt?2:1}let o=f?null:Xt(l.handle.state.verb,"extract",r.resume);if(o)return e.out(o.message),e.emit?.({type:"error",message:o.message,code:o.code}),l.handle.release(),2;let u=l.handle.state.change_basis;if(u&&(i.heads.get(u.source_id)??null)!==u.new_head){let c=`error: ${u.source_id} moved while this reconcile extraction was paused \u2014 its recorded change context no longer matches; re-run kane-cli maintain reconcile against the current file (session ${r.resume} is defunct and can be ignored)`;return e.out(c),e.emit?.({type:"error",message:c,code:"CHANGE_BASIS_MOVED"}),l.handle.release(),2}if(f&&f.view.pointer!==null&&f.drift.length>0){if(!await e.confirmStale(`changed since the pause: ${f.drift.map(C=>C.subject).join(", ")} \u2014 re-ground and continue against the current versions?`)){let C=`resume aborted: the context moved since the pause (${f.drift.map(B=>B.subject).join(", ")}) \u2014 session ${r.resume} is preserved`;return e.out(C),e.emit?.({type:"error",message:C,code:"RESUME_DRIFT"}),l.handle.release(),2}}else l.staleBasis.length>0&&e.out(`note: changed since the pause: ${l.staleBasis.join(", ")} \u2014 re-presented items may be stale`);let s=[...new Set([...l.handle.state.held_receipts??[],...f?.view.kane?.held_receipts??[]])];if(s.length>0)if(e.chat?.holdReceipt)for(let c of s)e.chat.holdReceipt(c);else e={...e,initialMessage:[s.join(`
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as V,e as I,i as L}from"./chunk-XMTSHHYQ.js";var N="ckpt/1";var H="checkpoints",P="base.json",y=t=>`delta-${t}.json`,w=t=>`full-${t}.json`,oe=["turn","ask","final"],ae=["extract","design","walk"];function _(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function x(t){return Array.isArray(t)&&t.every(n=>typeof n=="string")}function B(t){let n=[],e=(s,a)=>{s||n.push(a)};if(!_(t))return{ok:!1,errors:["record: not an object"]};e(t.schema===N,`schema: expected "${N}"`);let r=t.kind;if(r==="base")e(typeof t.sid=="string"&&t.sid.length>0,"base.sid: non-empty string"),e(typeof t.verb=="string"&&ae.includes(t.verb),"base.verb: extract|design|walk"),e(typeof t.mode=="string","base.mode: string"),e(typeof t.created_at=="string","base.created_at: string"),e(_(t.run_config),"base.run_config: object"),_(t.run_config)&&e(!("resume"in t.run_config),"base.run_config: must not carry `resume`"),e(typeof t.conv_source=="string",'base.conv_source: string ("" when absent)'),e(typeof t.store_watermark=="string"||t.store_watermark===null,"base.store_watermark: string | null (null = genesis)");else if(r==="delta"||r==="full"){e(typeof t.sid=="string"&&t.sid.length>0,"delta.sid: non-empty string"),e(Number.isInteger(t.seq)&&t.seq>=1,"delta.seq: integer \u2265 1"),e(Number.isInteger(t.turn_id),"delta.turn_id: integer"),e(typeof t.at=="string"&&oe.includes(t.at),"delta.at: turn|ask|final"),e(typeof t.ts=="string","delta.ts: string");let s=t.agent;if(_(s)){e(Number.isInteger(s.agent_state_schema),"agent.agent_state_schema: integer"),e(Array.isArray(s.delta_items),"agent.delta_items: array"),e(_(s.binding),"agent.binding: object");let o=s.usage_total;e(_(o)&&typeof o.input_tokens=="number"&&typeof o.output_tokens=="number"&&typeof o.credits=="number","agent.usage_total: {input_tokens, output_tokens, credits} numbers"),s.base_fingerprint!==void 0&&e(typeof s.base_fingerprint=="string","agent.base_fingerprint: string when present"),r==="full"&&e(typeof s.base_fingerprint=="string","full: agent.base_fingerprint required")}else n.push("delta.agent: object");let a=t.kane;if(_(a)){e(x(a.applied_events),"kane.applied_events: string[]"),e(x(a.held_receipts),"kane.held_receipts: string[]");let o=a.pending;e(_(o)&&Array.isArray(o.questions)&&Array.isArray(o.proposals),"kane.pending: {questions[], proposals[]}"),e(Array.isArray(a.parent_asks),"kane.parent_asks: array"),e(_(a.read_basis),"kane.read_basis: object");let p=a.corpus_cursor;e(_(p)&&x(p.remaining),"kane.corpus_cursor: {remaining: string[]}"),e(typeof a.store_watermark=="string"||a.store_watermark===null,"kane.store_watermark: string | null (null = genesis)"),a.ingest_registry!==void 0&&e(Array.isArray(a.ingest_registry)&&a.ingest_registry.every(i=>_(i)&&typeof i.ref=="string"&&typeof i.entered_at=="string"),"kane.ingest_registry: [{ref, entered_at, consumed?}]"),a.ingest_schedule!==void 0&&e(Array.isArray(a.ingest_schedule)&&a.ingest_schedule.every(i=>_(i)&&typeof i.source_id=="string"&&typeof i.cid=="string"&&["pending","done","skipped"].includes(String(i.status))),"kane.ingest_schedule: [{source_id, cid, status}]")}else n.push("delta.kane: object")}else n.push('kind: expected "base" | "delta" | "full"');return{ok:n.length===0,errors:n}}import{closeSync as U,existsSync as Z,fsyncSync as Y,mkdirSync as ee,openSync as W,readFileSync as te,readdirSync as ne,renameSync as ce,rmSync as K,statSync as pe,writeFileSync as de}from"fs";import{join as m}from"path";var ue=3,we=600*1e3,A=class extends Error{constructor(e,r){super(`${e}: ${r}`);this.code=e}},S=class extends Error{constructor(n){super(`CHECKPOINT_WRITE: ${n}`)}},j=class extends S{},E=(t,n)=>m(t,"sessions",n,H),le=(t,n)=>m(t,"sessions",n,"state.json");function F(t,n,e){let r=`${t}.tmp-${process.pid}`,s=W(r,"w");try{de(s,n,{mode:384}),Y(s)}finally{U(s)}ce(r,t);try{let a=W(e,"r");Y(a),U(a)}catch{}}var ge=new Set,J=new Set;function G(t){let n=0;try{for(let e of ne(t))try{n+=pe(m(t,e)).size}catch{}}catch{return 0}return n}function z(t,n,e){for(let r of ge)try{r(t,n,e)}catch{}}var fe=new Set;function Se(t,n=new Date){for(let e of fe)try{e(t,n)}catch{}}function Ae(t,n,e){let r=E(t,n);ee(r,{recursive:!0});let s=m(r,P);Z(s)||F(s,JSON.stringify(e)+`
2
+ import{F as I,L,p as V}from"./chunk-3N6IAVD5.js";var N="ckpt/1";var H="checkpoints",P="base.json",y=t=>`delta-${t}.json`,w=t=>`full-${t}.json`,oe=["turn","ask","final"],ae=["extract","design","walk"];function _(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function x(t){return Array.isArray(t)&&t.every(n=>typeof n=="string")}function B(t){let n=[],e=(s,a)=>{s||n.push(a)};if(!_(t))return{ok:!1,errors:["record: not an object"]};e(t.schema===N,`schema: expected "${N}"`);let r=t.kind;if(r==="base")e(typeof t.sid=="string"&&t.sid.length>0,"base.sid: non-empty string"),e(typeof t.verb=="string"&&ae.includes(t.verb),"base.verb: extract|design|walk"),e(typeof t.mode=="string","base.mode: string"),e(typeof t.created_at=="string","base.created_at: string"),e(_(t.run_config),"base.run_config: object"),_(t.run_config)&&e(!("resume"in t.run_config),"base.run_config: must not carry `resume`"),e(typeof t.conv_source=="string",'base.conv_source: string ("" when absent)'),e(typeof t.store_watermark=="string"||t.store_watermark===null,"base.store_watermark: string | null (null = genesis)");else if(r==="delta"||r==="full"){e(typeof t.sid=="string"&&t.sid.length>0,"delta.sid: non-empty string"),e(Number.isInteger(t.seq)&&t.seq>=1,"delta.seq: integer \u2265 1"),e(Number.isInteger(t.turn_id),"delta.turn_id: integer"),e(typeof t.at=="string"&&oe.includes(t.at),"delta.at: turn|ask|final"),e(typeof t.ts=="string","delta.ts: string");let s=t.agent;if(_(s)){e(Number.isInteger(s.agent_state_schema),"agent.agent_state_schema: integer"),e(Array.isArray(s.delta_items),"agent.delta_items: array"),e(_(s.binding),"agent.binding: object");let o=s.usage_total;e(_(o)&&typeof o.input_tokens=="number"&&typeof o.output_tokens=="number"&&typeof o.credits=="number","agent.usage_total: {input_tokens, output_tokens, credits} numbers"),s.base_fingerprint!==void 0&&e(typeof s.base_fingerprint=="string","agent.base_fingerprint: string when present"),r==="full"&&e(typeof s.base_fingerprint=="string","full: agent.base_fingerprint required")}else n.push("delta.agent: object");let a=t.kane;if(_(a)){e(x(a.applied_events),"kane.applied_events: string[]"),e(x(a.held_receipts),"kane.held_receipts: string[]");let o=a.pending;e(_(o)&&Array.isArray(o.questions)&&Array.isArray(o.proposals),"kane.pending: {questions[], proposals[]}"),e(Array.isArray(a.parent_asks),"kane.parent_asks: array"),e(_(a.read_basis),"kane.read_basis: object");let p=a.corpus_cursor;e(_(p)&&x(p.remaining),"kane.corpus_cursor: {remaining: string[]}"),e(typeof a.store_watermark=="string"||a.store_watermark===null,"kane.store_watermark: string | null (null = genesis)"),a.ingest_registry!==void 0&&e(Array.isArray(a.ingest_registry)&&a.ingest_registry.every(i=>_(i)&&typeof i.ref=="string"&&typeof i.entered_at=="string"),"kane.ingest_registry: [{ref, entered_at, consumed?}]"),a.ingest_schedule!==void 0&&e(Array.isArray(a.ingest_schedule)&&a.ingest_schedule.every(i=>_(i)&&typeof i.source_id=="string"&&typeof i.cid=="string"&&["pending","done","skipped"].includes(String(i.status))),"kane.ingest_schedule: [{source_id, cid, status}]")}else n.push("delta.kane: object")}else n.push('kind: expected "base" | "delta" | "full"');return{ok:n.length===0,errors:n}}import{closeSync as U,existsSync as Z,fsyncSync as Y,mkdirSync as ee,openSync as W,readFileSync as te,readdirSync as ne,renameSync as ce,rmSync as K,statSync as pe,writeFileSync as de}from"fs";import{join as m}from"path";var ue=3,we=600*1e3,A=class extends Error{constructor(e,r){super(`${e}: ${r}`);this.code=e}},S=class extends Error{constructor(n){super(`CHECKPOINT_WRITE: ${n}`)}},j=class extends S{},E=(t,n)=>m(t,"sessions",n,H),le=(t,n)=>m(t,"sessions",n,"state.json");function F(t,n,e){let r=`${t}.tmp-${process.pid}`,s=W(r,"w");try{de(s,n,{mode:384}),Y(s)}finally{U(s)}ce(r,t);try{let a=W(e,"r");Y(a),U(a)}catch{}}var ge=new Set,J=new Set;function G(t){let n=0;try{for(let e of ne(t))try{n+=pe(m(t,e)).size}catch{}}catch{return 0}return n}function z(t,n,e){for(let r of ge)try{r(t,n,e)}catch{}}var fe=new Set;function Se(t,n=new Date){for(let e of fe)try{e(t,n)}catch{}}function Ae(t,n,e){let r=E(t,n);ee(r,{recursive:!0});let s=m(r,P);Z(s)||F(s,JSON.stringify(e)+`
3
3
  `,r)}function _e(t,n){let e;try{e=JSON.parse(n)}catch(s){throw new A("CHECKPOINT_CORRUPT",`${t}: ${s.message}`)}let r=B(e);if(!r.ok)throw new A("CHECKPOINT_CORRUPT",`${t}: ${r.errors.join("; ")}`);return e}function M(t,n,e){let r=m(E(t,n),e);return _e(e,te(r,"utf8"))}function re(t,n){let e=[],r=[],s=[];try{s=ne(E(t,n))}catch{return{deltas:e,fulls:r}}for(let a of s){let o=/^delta-(\d+)\.json$/.exec(a);o&&e.push(Number(o[1]));let p=/^full-(\d+)\.json$/.exec(a);p&&r.push(Number(p[1]))}return e.sort((a,o)=>a-o),r.sort((a,o)=>a-o),{deltas:e,fulls:r}}function me(t,n){try{return JSON.parse(te(le(t,n),"utf8")).checkpoint??null}catch{return null}}function se(t,n,e){let r=[],s,a=0;if(e.full_seq!==null){let i=M(t,n,w(e.full_seq));r.push(i),s=i.agent.base_fingerprint,a=e.full_seq}let o;for(let i=a+1;i<=e.seq;i++)try{let d=M(t,n,y(i));r.push(d),!s&&d.agent.base_fingerprint&&(s=d.agent.base_fingerprint)}catch(d){if(d instanceof A&&d.code==="CHECKPOINT_CORRUPT"){o={resumableAt:i-1,turnsLost:e.seq-(i-1)};break}throw d}if(r.length===0)throw new A("CHECKPOINT_CORRUPT",`${n}: pointer names seq ${e.seq} but no chain records exist`);return{items:r.flatMap(i=>i.agent.delta_items),last:r[r.length-1],base_fingerprint:s,fallback:o}}function Re(t,n,e,r,s){let a=performance.now(),o=n.state.sid,p=n.state.checkpoint;if(p){if(e.seq<p.seq)throw new S(`seq regression: got ${e.seq}, pointer at ${p.seq} (${o})`);if(e.seq===p.seq){if(e.turn_id===p.turn_id&&e.at===p.at)return p;throw new S(`seq regression: seq ${e.seq} re-used with different metadata (turn ${e.turn_id}/${p.turn_id}, at ${e.at}/${p.at}) (${o})`)}}let i=E(t,o);ee(i,{recursive:!0});let d=(s?.now??(()=>new Date))(),b=d.toISOString(),l={schema:N,kind:"delta",sid:o,seq:e.seq,turn_id:e.turn_id,at:e.at,ts:b,agent:{agent_state_schema:e.agent_state_schema,delta_items:e.delta_items,binding:e.binding,usage_total:e.usage_total,...e.base_fingerprint!==void 0?{base_fingerprint:e.base_fingerprint}:{}},kane:r},k=Math.max(1,s?.retries??ue),g=JSON.stringify(l)+`
4
4
  `,O=!1;Buffer.byteLength(g)>524288&&!J.has(o)&&(J.add(o),O=!0,s?.onSoftCap?.("note: this session's checkpoints are getting large \u2014 long pasted inputs are kept verbatim; consider ingesting big documents as sources instead"));let R=!1,v;for(let c=0;c<k&&!R;c++)try{F(m(i,y(e.seq)),g,i),R=!0}catch(u){v=u}if(!R)throw new S(`delta-${e.seq} write failed after ${k} attempts: ${v?.message??"unknown"} (${o})`);let h=p?.full_seq??null,$=G(i)>67108864;if(e.seq%25===0||$){let c=[],u=e.base_fingerprint;if(p){let C=se(t,o,p);c=C.items,u=u??C.base_fingerprint}if(c=[...c,...e.delta_items],!u)throw new S(`compaction at seq ${e.seq}: no base_fingerprint anywhere in the chain (${o})`);let f={...l,kind:"full",agent:{...l.agent,delta_items:c,base_fingerprint:u}};F(m(i,w(e.seq)),JSON.stringify(f)+`
5
5
  `,i),h=e.seq}let q={seq:e.seq,turn_id:e.turn_id,at:e.at,ts:b,full_seq:h};if(n.save({checkpoint:q}),h===e.seq){let{deltas:c,fulls:u}=re(t,o);for(let f of c)f<=h&&K(m(i,y(f)),{force:!0});for(let f of u)f<h&&K(m(i,w(f)),{force:!0})}let T=G(i);if($&&T>67108864)throw z(o,q,d),new j(`session ${o} checkpoint dir is ${Math.round(T/(1024*1024))}MB (cap ${Math.round(67108864/(1024*1024))}MB) even after compaction \u2014 pausing; resume in a fresh session or trim the conversation`);return z(o,q,d),s?.onStat?.({sid:o,seq:e.seq,persist_ms:performance.now()-a,bytes:Buffer.byteLength(g),dir_bytes:T,compacted:h===e.seq,soft_warned:O}),q}function Pe(t,n,e){let r=e?._readPointer??(()=>me(t,n)),s=m(E(t,n),P);if(!Z(s))throw new A("CHECKPOINT_MISSING",`${n}: no ${P} \u2014 not a checkpoint session`);let a=M(t,n,P),o=i=>{let{deltas:d,fulls:b}=re(t,n);if(!i){let g=[...d.map(y),...b.map(w)];return{base:a,agent:null,kane:null,pointer:null,orphans:g}}let l=se(t,n,i),k=[...d.filter(g=>g>i.seq).map(y),...b.filter(g=>g>i.seq).map(w)];return{base:a,agent:{delta_items:l.items,binding:l.last.agent.binding,base_fingerprint:l.base_fingerprint,agent_state_schema:l.last.agent.agent_state_schema},kane:l.last.kane,pointer:i,orphans:k,...l.fallback?{fallback:l.fallback}:{}}},p=r();try{return o(p)}catch(i){if(!(i.code==="ENOENT"))throw i;return o(r())}}function Ee(t,n){let e=[];for(let r of I(t).records)if(r.sid===n)for(let s of r.event_ids??[])e.push(s);return e}function ve(t,n,e,r,s){let a=s.verb??"extract",o=I(t),p=0;if(e.store_watermark!==null){let c=o.hashes.indexOf(e.store_watermark);if(c===-1)throw new V(`watermark not in chain: ${e.store_watermark} names no record in this store (rebuilt or foreign?) \u2014 re-ground the session or abandon it`);p=c+1}let i=L(t,{seq:p,hash:e.store_watermark}).records,d=o.records.filter(c=>c.sid===n).map(c=>c.seq),b=c=>d.filter(u=>u<=c.seq).length,l=new Set(e.applied_events),k=0,g=[];for(let c of i){if(typeof c.sid!="string"){k+=1;continue}if(c.sid===n){if((c.event_ids??[]).length===0){k+=1;continue}g.push(c)}}k>0&&s.onNote?.(`reconcile: skipped ${k} store record(s) not attributable to this session (pre-sid grace)`);let O=s.ownActors??["extract-agent","design-agent","owner"],R=[],v=[];for(let c of g){let u=(c.event_ids??[]).filter(ie=>!l.has(ie));if(u.length===0)continue;v.push(...u);let f;try{f=s.composeReceipt(c,r,{verb:a,commitN:b(c),...s.ucRef?{ucRef:s.ucRef}:{}}).text}catch{f=`commit ${u[0]} at ${c.ts} \u2014 details unavailable (graph moved since)`}let C=c.review?.[0]?.by;C?.id&&!O.includes(C.id)&&(f+=`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as l}from"./chunk-RZ4F3BHX.js";import{a,b as c,e as o}from"./chunk-33GXXC2L.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
2
+ import{a as l}from"./chunk-RZ4F3BHX.js";import{a,b as c,e as o}from"./chunk-HYTBEPC2.js";import{readFileSync as f,writeFileSync as d,mkdirSync as h,realpathSync as g}from"fs";import{join as y}from"path";var C="npm install -g @testmuai/kane-cli@latest",b="brew upgrade lambdatest/kane/kane-cli";function w(){try{let t=process.argv[1];if(t&&g(t).includes("/Cellar/"))return b}catch{}return C}var m=y(c,"version-check.json"),S=1440*60*1e3;function k(){try{let t=JSON.parse(f(m,"utf-8"));if(Date.now()-t.checkedAt<S)return t}catch{}return null}function A(t){try{h(c,{recursive:!0}),d(m,JSON.stringify({latest:t,checkedAt:Date.now()}))}catch{}}function u(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);for(let s=0;s<3;s++){let e=(n[s]??0)-(i[s]??0);if(e!==0)return e}return 0}function p(t,r){let i=t.split(".").map(Number),n=r.split(".").map(Number);return(n[0]??0)!==(i[0]??0)?"major":(n[1]??0)!==(i[1]??0)?"minor":"patch"}async function j(){try{let t=k();if(t)return u(a,t.latest)>0?{current:a,latest:t.latest,severity:p(a,t.latest)}:null;let r=new AbortController,i=setTimeout(()=>r.abort(),5e3),n=await l(o,{headers:{Accept:"application/json"},signal:r.signal});if(clearTimeout(i),!n.ok)return null;let e=(await n.json())["dist-tags"]?.latest;return e?(A(e),u(a,e)>0?{current:a,latest:e,severity:p(a,e)}:null):null}catch{return null}}export{w as a,u as b,p as c,j as d};
@@ -1,3 +1,3 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as X}from"./chunk-BB2W35TW.js";import{a as $}from"./chunk-YKTYVJBN.js";import{C as T,n as z,o as Y,p as H}from"./chunk-W3Z7AZNT.js";import{b as q,h as N}from"./chunk-XMTSHHYQ.js";import{a as W,d as S,f as L}from"./chunk-DBIBROYW.js";import{c as C}from"./chunk-UD7KKHPW.js";import{a as K,b as J}from"./chunk-33GXXC2L.js";var ce=3,de=1e4,Q=()=>new Promise(r=>setTimeout(r,25+Math.floor(Math.random()*50))),Z=r=>r==="design"||r==="maintain"?"session":r==="revert"||r==="shape-op"?"exclusive":"commit";function le(r,e,o){for(let s of r){for(let t of s.supersessions)if(t.kind==="node"&&(o.has(t.old)||t.new!==null&&o.has(t.new)))return!0;for(let t of s.nodes)if(t.label==="usecase"&&e.newBuCandidates.length>0||o.has(t.cid))return!0;if(s.design_generation&&e.generationTicket&&s.design_generation.uc_root===e.generationTicket.uc_root)return!0;for(let t of e.sourcePins)if(Object.prototype.hasOwnProperty.call(s.source_head_moves,t.source_id))return!0}return!1}async function De(r,e,o){let{contextDir:s,locks:t,probe:a}=r,m=r.sid??r.rootSid,f=e.newBuCandidates.map(b=>({tempRef:b.tempRef,probeText:b.probeText})),k=0,g=!0,p={hits:[],degraded:!1,probeBasis:null};for(;;){g&&(f.length>0&&(p=await a.batchSimilar(T(s),f)),g=!1);let b=T(s),_={seq:b.lastSeq,hash:b.latestHash},P=new Map,w=[],v=[],R=new Set;for(let d of e.ucTargets){let c=H(b,d.ref);if(c===null)return{ok:!1,kind:"validation",errors:[{code:"UNKNOWN_REF",detail:`${d.ref}: names no living node (unknown or tombstoned chain)`}]};d.expectedTip!==void 0&&d.expectedTip!==c.cid&&P.set(d.expectedTip,c.cid),R.add(c.cid),v.push(L(b,d.ref).key)}(e.verb==="revert"||e.verb==="shape-op")&&(v.length=0,v.push({kind:"context",mode:"exclusive"}));let y;try{y=t.acquire(S(v),{hold:Z(e.verb),verb:e.verb})}catch(d){if(d instanceof W&&(d.code==="UC_HELD"||d.code==="CONTEXT_HELD"))return{ok:!1,kind:"contended",err:d};throw d}let V=!1,M=!1;try{let d=await t.withKeySerialized(v,async()=>{let c=T(s),O=_.hash===c.latestHash?[]:N(s,_.seq,_.hash).records;for(let n of e.ucTargets){let i=H(c,n.ref);if(i===null){w.push({kind:"supersession",ref:n.ref,detail:`${n.ref} was retired while this commit staged \u2014 re-ground or abandon`});continue}for(let l of R)c.superseded.has(l)&&c.tipOf(l)===i.cid&&P.set(l,i.cid)}for(let n of e.sourcePins){let i=c.heads.get(n.source_id);i!=null&&i!==n.source_cid&&w.push({kind:"pin",ref:n.source_id,detail:`source '${n.source_id}' moved (pinned ${n.source_cid.slice(0,19)}, head ${i.slice(0,19)}) \u2014 re-ground or abandon`})}if(w.length>0)return{ok:!1,kind:"drifted",asks:w};if(e.generationTicket){let n=X(c,e.generationTicket);if(n!==null)return{ok:!1,kind:"validation",errors:[n]}}if(f.length>0&&O.length>0){let n=new Set(p.hits.map(u=>u.candidateCid)),i=a.recheckLocal(c,f,p.probeBasis,O);if(i.hits.some(u=>!n.has(u.candidateCid))||i.uncachedNewNodes.length>0)return M=!0,"restart"}if(e.verb!=="revert"&&e.verb!=="shape-op"){let n=S(e.ucTargets.map(u=>L(c,u.ref).key)),i=S(v);if(!(n.length===i.length&&n.every((u,h)=>JSON.stringify(u)===JSON.stringify(i[h]))))return"restart"}if(e.eventIds&&e.eventIds.length>0&&e.eventIds.every(n=>c.appliedEvents.has(n)))return{ok:!0,skipped:"already-applied"};let ae=Date.now()+de,j=c.latestHash,E=c;for(;;){let n={graph:E,expectPrev:j,redirects:P,probeHits:p.hits,degradedProbe:p.degraded,sid:m,eventIds:(l,u)=>{if(e.eventIds&&e.eventIds.length>0)return e.eventIds.slice(0,u);let h=Y(E,r.rootSid,l,u),U=r.reservedEventIds??[];if(U.length===0)return h;let D=`${r.rootSid}:${l}:`,A=0;for(let F of U){if(!F.startsWith(D))continue;let x=F.slice(D.length);/^\d+$/.test(x)&&(A=Math.max(A,Number.parseInt(x,10)))}if(A===0)return h;let G=Number.parseInt(h[0].slice(D.length),10);return!Number.isInteger(G)||G>A?h:Array.from({length:u},(F,x)=>z(r.rootSid,l,A+1+x))},assertLocks:()=>y.assertHeld()};if(r.revalidate){let l=r.revalidate(n);if(l.length>0)return{ok:!1,kind:"validation",errors:l}}y.assertHeld();let i;try{i=o(n)}catch(l){if(l instanceof q){let u=T(s),h=N(s,E.lastSeq,E.latestHash).records;if(!le(h,e,R)&&Date.now()<ae){await Q(),E=u,j=u.latestHash;continue}return"restart"}throw l}return"errors"in i?{ok:!1,kind:"validation",errors:i.errors}:(Z(e.verb)==="session"&&y.touch(),{ok:!0,result:i.result,record:i.record})}});if(d==="restart")V=!0;else return d}finally{y.release()}if(V){if(k+=1,k>=ce)return{ok:!1,kind:"unsettled",attempts:k};M&&(g=!0),await Q();continue}}}import{readFileSync as ue,writeFileSync as fe,renameSync as me,mkdirSync as pe}from"fs";import{dirname as he,join as ge}from"path";var B=1,be=720*60*1e3;function I(r){return ge(J,"embeddings",`alias-${r}.json`)}function ee(r,e=Date.now()){return r!==null&&e-r.fetchedAt<be}function re(r){try{let e=JSON.parse(ue(r,"utf-8"));return e.wrapperVersion!==B||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:B,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function te(r,e,o=I(r)){let t=re(o)?.purposes?.[e];return!t||typeof t.alias!="string"||typeof t.dims!="number"||typeof t.fetchedAt!="number"?null:{alias:t.alias,dims:t.dims,fetchedAt:t.fetchedAt}}function se(r,e,o,s=I(r)){try{pe(he(s),{recursive:!0});let a=re(s)?.purposes??{};a[e]={alias:o.alias,dims:o.dims,fetchedAt:Date.now()};let m={wrapperVersion:B,writtenByVersion:K,purposes:a},f=`${s}.tmp`;fe(f,JSON.stringify(m,null,2)+`
2
+ import{d as X}from"./chunk-BB2W35TW.js";import{a as $}from"./chunk-YKTYVJBN.js";import{C as T,n as z,o as Y,p as H}from"./chunk-GP7WD4UY.js";import{K as N,x as q}from"./chunk-3N6IAVD5.js";import{a as W,e as S,g as L}from"./chunk-FQNQVC5O.js";import{c as C}from"./chunk-UD7KKHPW.js";import{a as K,b as J}from"./chunk-HYTBEPC2.js";var ce=3,de=1e4,Q=()=>new Promise(r=>setTimeout(r,25+Math.floor(Math.random()*50))),Z=r=>r==="design"||r==="maintain"?"session":r==="revert"||r==="shape-op"?"exclusive":"commit";function le(r,e,o){for(let s of r){for(let t of s.supersessions)if(t.kind==="node"&&(o.has(t.old)||t.new!==null&&o.has(t.new)))return!0;for(let t of s.nodes)if(t.label==="usecase"&&e.newBuCandidates.length>0||o.has(t.cid))return!0;if(s.design_generation&&e.generationTicket&&s.design_generation.uc_root===e.generationTicket.uc_root)return!0;for(let t of e.sourcePins)if(Object.prototype.hasOwnProperty.call(s.source_head_moves,t.source_id))return!0}return!1}async function De(r,e,o){let{contextDir:s,locks:t,probe:a}=r,m=r.sid??r.rootSid,f=e.newBuCandidates.map(b=>({tempRef:b.tempRef,probeText:b.probeText})),k=0,g=!0,p={hits:[],degraded:!1,probeBasis:null};for(;;){g&&(f.length>0&&(p=await a.batchSimilar(T(s),f)),g=!1);let b=T(s),_={seq:b.lastSeq,hash:b.latestHash},P=new Map,w=[],v=[],R=new Set;for(let d of e.ucTargets){let c=H(b,d.ref);if(c===null)return{ok:!1,kind:"validation",errors:[{code:"UNKNOWN_REF",detail:`${d.ref}: names no living node (unknown or tombstoned chain)`}]};d.expectedTip!==void 0&&d.expectedTip!==c.cid&&P.set(d.expectedTip,c.cid),R.add(c.cid),v.push(L(b,d.ref).key)}(e.verb==="revert"||e.verb==="shape-op")&&(v.length=0,v.push({kind:"context",mode:"exclusive"}));let y;try{y=t.acquire(S(v),{hold:Z(e.verb),verb:e.verb})}catch(d){if(d instanceof W&&(d.code==="UC_HELD"||d.code==="CONTEXT_HELD"))return{ok:!1,kind:"contended",err:d};throw d}let V=!1,M=!1;try{let d=await t.withKeySerialized(v,async()=>{let c=T(s),O=_.hash===c.latestHash?[]:N(s,_.seq,_.hash).records;for(let n of e.ucTargets){let i=H(c,n.ref);if(i===null){w.push({kind:"supersession",ref:n.ref,detail:`${n.ref} was retired while this commit staged \u2014 re-ground or abandon`});continue}for(let l of R)c.superseded.has(l)&&c.tipOf(l)===i.cid&&P.set(l,i.cid)}for(let n of e.sourcePins){let i=c.heads.get(n.source_id);i!=null&&i!==n.source_cid&&w.push({kind:"pin",ref:n.source_id,detail:`source '${n.source_id}' moved (pinned ${n.source_cid.slice(0,19)}, head ${i.slice(0,19)}) \u2014 re-ground or abandon`})}if(w.length>0)return{ok:!1,kind:"drifted",asks:w};if(e.generationTicket){let n=X(c,e.generationTicket);if(n!==null)return{ok:!1,kind:"validation",errors:[n]}}if(f.length>0&&O.length>0){let n=new Set(p.hits.map(u=>u.candidateCid)),i=a.recheckLocal(c,f,p.probeBasis,O);if(i.hits.some(u=>!n.has(u.candidateCid))||i.uncachedNewNodes.length>0)return M=!0,"restart"}if(e.verb!=="revert"&&e.verb!=="shape-op"){let n=S(e.ucTargets.map(u=>L(c,u.ref).key)),i=S(v);if(!(n.length===i.length&&n.every((u,h)=>JSON.stringify(u)===JSON.stringify(i[h]))))return"restart"}if(e.eventIds&&e.eventIds.length>0&&e.eventIds.every(n=>c.appliedEvents.has(n)))return{ok:!0,skipped:"already-applied"};let ae=Date.now()+de,j=c.latestHash,E=c;for(;;){let n={graph:E,expectPrev:j,redirects:P,probeHits:p.hits,degradedProbe:p.degraded,sid:m,eventIds:(l,u)=>{if(e.eventIds&&e.eventIds.length>0)return e.eventIds.slice(0,u);let h=Y(E,r.rootSid,l,u),U=r.reservedEventIds??[];if(U.length===0)return h;let D=`${r.rootSid}:${l}:`,A=0;for(let F of U){if(!F.startsWith(D))continue;let x=F.slice(D.length);/^\d+$/.test(x)&&(A=Math.max(A,Number.parseInt(x,10)))}if(A===0)return h;let G=Number.parseInt(h[0].slice(D.length),10);return!Number.isInteger(G)||G>A?h:Array.from({length:u},(F,x)=>z(r.rootSid,l,A+1+x))},assertLocks:()=>y.assertHeld()};if(r.revalidate){let l=r.revalidate(n);if(l.length>0)return{ok:!1,kind:"validation",errors:l}}y.assertHeld();let i;try{i=o(n)}catch(l){if(l instanceof q){let u=T(s),h=N(s,E.lastSeq,E.latestHash).records;if(!le(h,e,R)&&Date.now()<ae){await Q(),E=u,j=u.latestHash;continue}return"restart"}throw l}return"errors"in i?{ok:!1,kind:"validation",errors:i.errors}:(Z(e.verb)==="session"&&y.touch(),{ok:!0,result:i.result,record:i.record})}});if(d==="restart")V=!0;else return d}finally{y.release()}if(V){if(k+=1,k>=ce)return{ok:!1,kind:"unsettled",attempts:k};M&&(g=!0),await Q();continue}}}import{readFileSync as ue,writeFileSync as fe,renameSync as me,mkdirSync as pe}from"fs";import{dirname as he,join as ge}from"path";var B=1,be=720*60*1e3;function I(r){return ge(J,"embeddings",`alias-${r}.json`)}function ee(r,e=Date.now()){return r!==null&&e-r.fetchedAt<be}function re(r){try{let e=JSON.parse(ue(r,"utf-8"));return e.wrapperVersion!==B||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:B,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function te(r,e,o=I(r)){let t=re(o)?.purposes?.[e];return!t||typeof t.alias!="string"||typeof t.dims!="number"||typeof t.fetchedAt!="number"?null:{alias:t.alias,dims:t.dims,fetchedAt:t.fetchedAt}}function se(r,e,o,s=I(r)){try{pe(he(s),{recursive:!0});let a=re(s)?.purposes??{};a[e]={alias:o.alias,dims:o.dims,fetchedAt:Date.now()};let m={wrapperVersion:B,writtenByVersion:K,purposes:a},f=`${s}.tmp`;fe(f,JSON.stringify(m,null,2)+`
3
3
  `),me(f,s)}catch(t){C(`[embed] Failed to save alias cache: ${t instanceof Error?t.message:String(t)}`,"EMBED_CACHE_WRITE_FAILED")}}function ve(r){return r.TESTMUAI_ENV==="stage"?"stage":"prod"}function oe(r){let e=r.env??process.env,o=r.auth?.TESTMUAI_BASIC_AUTH||e.TESTMUAI_BASIC_AUTH;if(o)return{authorization:`Basic ${o}`};let s=r.auth?.TESTMUAI_API_KEY||e.TESTMUAI_API_KEY;return s?{authorization:`Bearer ${s}`}:{}}async function Oe(r,e={}){let o=e.env??process.env,s=ve(o),t=e.aliasCacheFile??I(s),a=e.now??Date.now,m=te(s,r,t);if(ee(m,a()))return{alias:m.alias,dims:m.dims};let k=`${$(o)}/assurance/embed/alias?purpose=${encodeURIComponent(r)}`,g=await(e.fetchImpl??fetch)(k,{method:"GET",headers:oe(e)});if(!g.ok)throw new Error(`embed alias resolve failed: ${g.status}`);let p=await g.json();return se(s,r,{alias:p.alias,dims:p.dims},t),{alias:p.alias,dims:p.dims}}async function je(r,e,o={}){let s=o.env??process.env,t=$(s),a=await(o.fetchImpl??fetch)(`${t}/assurance/embed`,{method:"POST",headers:{...oe(o),"content-type":"application/json"},body:JSON.stringify({purpose:r,input:e})});if(!a.ok)throw new Error(`embed failed: ${a.status}`);return await a.json()}import{readFileSync as ke,writeFileSync as ye,renameSync as Ee,mkdirSync as Ae}from"fs";import{dirname as Te,join as ne}from"path";function we(r){return ne(r,"embeddings")}function xe(r){let e=r.indexOf(":");return e>=0?r.slice(e+1):r}function ie(r,e,o){let s=xe(o);return ne(we(r),e,s.slice(0,2),`${s.slice(2)}.f32`)}function We(r,e,o){try{let s=ke(ie(r,e,o)),t=new Float32Array(Math.floor(s.length/4));for(let a=0;a<t.length;a++)t[a]=s.readFloatLE(a*4);return t}catch{return null}}function qe(r,e,o,s){try{let t=ie(r,e,o);Ae(Te(t),{recursive:!0});let a=Buffer.alloc(s.length*4);for(let f=0;f<s.length;f++)a.writeFloatLE(s[f],f*4);let m=`${t}.tmp`;ye(m,a),Ee(m,t)}catch(t){C(`[embed] Failed to cache vector: ${t instanceof Error?t.message:String(t)}`,"EMBED_CACHE_WRITE_FAILED")}}export{De as a,Oe as b,je as c,We as d,qe as e};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as n}from"./chunk-33GXXC2L.js";import{createHash as _}from"crypto";import{existsSync as m,readFileSync as u}from"fs";import{dirname as T,join as f,resolve as o}from"path";import{fileURLToPath as E}from"url";var s=T(E(import.meta.url)),l=2;function p(e,r){let t=_("sha256");return t.update(`kane-assurance-contract
2
+ import{a as n}from"./chunk-HYTBEPC2.js";import{createHash as _}from"crypto";import{existsSync as m,readFileSync as u}from"fs";import{dirname as T,join as f,resolve as o}from"path";import{fileURLToPath as E}from"url";var s=T(E(import.meta.url)),l=2;function p(e,r){let t=_("sha256");return t.update(`kane-assurance-contract
3
3
  `),t.update(e),t.update(`
4
4
  agent_state_schema=${r}`),"sha256:"+t.digest("hex")}function d(){return[o(s,".."),o(s,"../../..")]}function i(){return"sha256:4f00de27d151118e79aafd46ebe51bb69ce7dd9fabe647124c62f2d187e11aa7"}var a=class extends Error{constructor(t,c){super(`agent/cli contract mismatch (cli ${t||"<unset>"}, agent ${c||"<unset>"}) \u2014 rebuild or reinstall the stale half`);this.expected=t;this.actual=c;this.name="PairMismatchError"}};function I(){return{TESTMUAI_CONTRACT_DIGEST:i(),TESTMUAI_CLIENT_VERSION:process.env.KANE_DEV_FORCE_CLIENT_RELEASE??`kane-cli/${n}`}}export{a,I as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as t}from"./chunk-33GXXC2L.js";import{join as i}from"path";function e(n=t){return i(n,"plugins")}function g(n,r=t){return i(e(r),n)}function c(n,r,o=t){return i(g(n,o),r)}function f(n,r=t){return i(g(n,r),"current")}function x(n,r=t){return i(g(n,r),"config.json")}function l(n,r=t){return i(g(n,r),".jobs")}function s(n=t){return i(n,"bin")}function h(n=t){return i(s(n),"hyperexecute")}export{e as a,g as b,c,f as d,x as e,l as f,s as g,h};
2
+ import{b as t}from"./chunk-HYTBEPC2.js";import{join as i}from"path";function e(n=t){return i(n,"plugins")}function g(n,r=t){return i(e(r),n)}function c(n,r,o=t){return i(g(n,o),r)}function f(n,r=t){return i(g(n,r),"current")}function x(n,r=t){return i(g(n,r),"config.json")}function l(n,r=t){return i(g(n,r),".jobs")}function s(n=t){return i(n,"bin")}function h(n=t){return i(s(n),"hyperexecute")}export{e as a,g as b,c,f as d,x as e,l as f,s as g,h};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as m}from"./chunk-ARU6KAGY.js";import{y as t}from"./chunk-33GXXC2L.js";import{a as p}from"./chunk-HCBYKLMW.js";import{a,b as r,i as u}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as n}from"./chunk-UR6MHSHU.js";var c=n(b(),1);var e=n(p(),1);function R({onSubmit:l}){let[o,f]=(0,c.useState)(0),s=(0,c.useRef)(!1);return u((x,i)=>{s.current||(i.leftArrow||i.rightArrow?f(d=>d===0?1:0):i.return?(s.current=!0,l(o===0?"positive":"negative")):i.escape&&(s.current=!0,l(null)))}),(0,e.jsxs)(a,{flexDirection:"column",marginTop:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(r,{color:t.secondary,children:"Rate this session: "}),(0,e.jsx)(r,{color:o===0?t.orange:t.dim,children:o===0?"[ \u{1F44D} ]":" \u{1F44D} "}),(0,e.jsx)(r,{children:" "}),(0,e.jsx)(r,{color:o===1?t.orange:t.dim,children:o===1?"[ \u{1F44E} ]":" \u{1F44E} "})]}),(0,e.jsx)(m,{bindings:[{keys:"\u2190/\u2192",label:"select"},{keys:"\u21B5",label:"submit"}],escBackLabel:"skip"})]})}export{R as a};
2
+ import{a as m}from"./chunk-YKYKOV6U.js";import{y as t}from"./chunk-HYTBEPC2.js";import{a as p}from"./chunk-HCBYKLMW.js";import{a,b as r,i as u}from"./chunk-C44QQJR4.js";import{a as b}from"./chunk-6YGTRKDT.js";import{e as n}from"./chunk-UR6MHSHU.js";var c=n(b(),1);var e=n(p(),1);function R({onSubmit:l}){let[o,f]=(0,c.useState)(0),s=(0,c.useRef)(!1);return u((x,i)=>{s.current||(i.leftArrow||i.rightArrow?f(d=>d===0?1:0):i.return?(s.current=!0,l(o===0?"positive":"negative")):i.escape&&(s.current=!0,l(null)))}),(0,e.jsxs)(a,{flexDirection:"column",marginTop:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(r,{color:t.secondary,children:"Rate this session: "}),(0,e.jsx)(r,{color:o===0?t.orange:t.dim,children:o===0?"[ \u{1F44D} ]":" \u{1F44D} "}),(0,e.jsx)(r,{children:" "}),(0,e.jsx)(r,{color:o===1?t.orange:t.dim,children:o===1?"[ \u{1F44E} ]":" \u{1F44E} "})]}),(0,e.jsx)(m,{bindings:[{keys:"\u2190/\u2192",label:"select"},{keys:"\u21B5",label:"submit"}],escBackLabel:"skip"})]})}export{R as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as b}from"./chunk-ARU6KAGY.js";import{m as d,y as o}from"./chunk-33GXXC2L.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
2
+ import{a as b}from"./chunk-YKYKOV6U.js";import{m as d,y as o}from"./chunk-HYTBEPC2.js";import{a as L}from"./chunk-HCBYKLMW.js";import{a as u,b as c,i as A}from"./chunk-C44QQJR4.js";import{a as D}from"./chunk-6YGTRKDT.js";import{e as h}from"./chunk-UR6MHSHU.js";var x=h(D(),1);import{readdirSync as N,mkdirSync as B,statSync as k}from"fs";import{join as P}from"path";var r=h(L(),1);function O(n){try{return N(n).filter(l=>{try{return k(P(n,l)).isDirectory()}catch{return!1}})}catch{return[]}}function E(n,l,f,v){return{name:n,path:l,label:n,isActive:v}}function H({currentPath:n,onSelect:l,onCancel:f}){let s=O(d).map(i=>{let e=P(d,i);return E(i,e,n,e===n)}),p=!n,R=s.length+2,[a,C]=(0,x.useState)(()=>{if(p)return 0;let i=s.findIndex(e=>e.isActive);return i>=0?i+1:0}),[T,I]=(0,x.useState)(!1),[S,g]=(0,x.useState)("");return A((i,e)=>{if(T){if(e.escape){I(!1),g("");return}if(e.return){let t=S.trim();if(t){let m=P(d,t);B(m,{recursive:!0}),l(m),f()}return}if(e.backspace||e.delete){g(t=>t.slice(0,-1));return}i&&!e.ctrl&&!e.meta&&g(t=>t+i);return}if(e.escape){f();return}if(e.upArrow){C(t=>Math.max(0,t-1));return}if(e.downArrow){C(t=>Math.min(R-1,t+1));return}if(e.return){if(a===0){p||l(""),f();return}if(a===s.length+1){B(d,{recursive:!0}),I(!0),g("");return}let t=s[a-1];t&&!t.isActive&&l(t.path),f();return}}),T?(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile \u203A New"}),(0,r.jsxs)(u,{marginTop:1,children:[(0,r.jsx)(c,{color:o.secondary,children:"Name: "}),(0,r.jsx)(c,{children:S}),(0,r.jsx)(c,{color:o.dim,children:"\u2588"})]}),(0,r.jsx)(b,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:"back"})]}):(0,r.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,r.jsx)(c,{color:o.orange,bold:!0,children:"Chrome Profile"}),(0,r.jsxs)(u,{flexDirection:"column",marginTop:1,children:[(0,r.jsxs)(c,{color:p?o.green:a===0?o.orange:o.dim,children:[a===0?"\u276F ":" ","Use temporary (no profile)",p?" \u25CF active":""]}),s.map((i,e)=>{let m=e+1===a,w=m?"\u276F ":" ",y=i.isActive?o.green:m?o.orange:void 0;return(0,r.jsxs)(c,{color:y,children:[w,i.label,i.isActive?" \u25CF active":""]},i.name)}),(0,r.jsxs)(c,{color:a===s.length+1?o.orange:o.dim,children:[a===s.length+1?"\u276F ":" ","+ Create new"]})]}),(0,r.jsx)(b,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}export{O as a,E as b,H as c};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{x as s}from"./chunk-33GXXC2L.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost,mobileAppBaseUrl:process.env.KANE_STAGE_MOBILE_APP_URL??e.mobileAppBaseUrl}}export{n as a};
2
+ import{x as s}from"./chunk-HYTBEPC2.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost,mobileAppBaseUrl:process.env.KANE_STAGE_MOBILE_APP_URL??e.mobileAppBaseUrl}}export{n as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{g as h}from"./chunk-EV64VI66.js";import{e as l}from"./chunk-XMTSHHYQ.js";import{b as u}from"./chunk-DBIBROYW.js";import{d as f}from"./chunk-AKX4VRRR.js";import{existsSync as w,readFileSync as _,readdirSync as R}from"fs";import{join as p}from"path";function g(i,r){let{records:t}=l(i),o=new Set;for(let e of t)for(let n of e.review)n.resolution!=="pending"&&o.add(n.id);let s=[],d=new Set;for(let e=t.length-1;e>=0;e--)for(let n of t[e].dedup_hits??[]){if(n.new_cid===void 0)continue;let c=`${n.new_cid}|${n.candidate_cid}`;d.has(c)||(d.add(c),!o.has(n.new_cid)&&(r.superseded.has(n.new_cid)||r.superseded.has(n.candidate_cid)||r.trust.get(n.new_cid)==="derived"&&s.push({new_cid:n.new_cid,candidate_cid:n.candidate_cid,score:n.score,scorer:n.scorer})))}return s}var a=(i,r)=>i.displayNameOf(r)??r.slice(0,19);function m(i,r){return{design_children:i.edgesInto(r).filter(o=>(o.type==="belongs_to"||o.type==="scoped_to")&&!i.superseded.has(o.src)).length}}function v(i,r){let{records:t}=l(i),o=new Set,s=new Map;for(let e of t)for(let n of e.review)n.kind==="pending_archive"?s.set(n.id,n.reason):n.resolution!=="pending"&&o.add(n.id);let d=new Map;for(let[e,n]of s)r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||d.set(e,n);return{all:s,live:d}}function y(i,r){let t=[],o=new Set;for(let e of g(i.contextDir,r)){o.add(e.new_cid);let n=e.scorer==="lexical_fallback"?" (lexical fallback \u2014 the probe ran degraded)":"";t.push({kind:"PAIR",ref:a(r,e.new_cid),title:String(r.getNode(e.new_cid)?.content.title??e.new_cid.slice(0,12)),why:`possible duplicate of ${a(r,e.candidate_cid)} \u2014 score ${e.score}${n}`,pair:{candidate_cid:e.candidate_cid,candidate_ref:a(r,e.candidate_cid),score:e.score,scorer:e.scorer}})}let{all:s,live:d}=v(i.contextDir,r);for(let[e,n]of d)t.push({kind:"REVIEW",ref:a(r,e),title:String(r.getNode(e)?.content.title??e.slice(0,12)),why:`archive held for interactive confirmation${n?` \u2014 ${n}`:""}`,held:!0,impact:m(r,e)});for(let e of k(i.contextDir))t.push({kind:"MODIFY_HELD",ref:`${e.sid}:${e.tempRef}`,title:String(e.content.title??e.tempRef),why:`${e.rationale} \u2014 held by paused/dead session ${e.sid}`,heldPayload:e});for(let{cid:e,content:n}of r.byLabel(f.USECASE))r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||s.has(e)||t.push({kind:"REVIEW",ref:a(r,e),title:String(n.title??e.slice(0,12)),why:"unreviewed \u2014 approve, archive, or defer",impact:m(r,e)});return t}function F(i,r){let t={REVIEW:0,PAIR:0,MODIFY_HELD:0};for(let o of y(i,r))t[o.kind]++;return t}function b(i,r){try{let t=JSON.parse(_(p(i,"sessions",r,".lock"),"utf8"));return typeof t.pid=="number"&&u(t.pid)}catch{return!1}}function k(i){let r=[],t=p(i,"sessions");if(!w(t))return r;let o=[];try{o=R(t)}catch{return r}for(let s of o){if(!w(p(t,s,"state.json"))||b(i,s))continue;let d=[],e=!1;try{let c=h(i,s).kane;c?.pending?.proposals?.length&&(d=c.pending.proposals,e=!0)}catch{e=!1}if(!e)try{d=JSON.parse(_(p(t,s,"state.json"),"utf8")).pending?.proposals??[]}catch{continue}for(let n of d)r.push({sid:s,tempRef:String(n.tempRef??n.temp_ref??"held"),...typeof n.event_id=="string"?{event_id:n.event_id}:{},label:String(n.label??"usecase"),content:n.content??{},rationale:String(n.rationale??"held payload")})}return r}export{m as a,v as b,y as c,F as d};
2
+ import{g as h}from"./chunk-CRZUBDJ3.js";import{F as l}from"./chunk-3N6IAVD5.js";import{b as u}from"./chunk-FQNQVC5O.js";import{d as f}from"./chunk-AKX4VRRR.js";import{existsSync as w,readFileSync as _,readdirSync as R}from"fs";import{join as p}from"path";function g(i,r){let{records:t}=l(i),o=new Set;for(let e of t)for(let n of e.review)n.resolution!=="pending"&&o.add(n.id);let s=[],d=new Set;for(let e=t.length-1;e>=0;e--)for(let n of t[e].dedup_hits??[]){if(n.new_cid===void 0)continue;let c=`${n.new_cid}|${n.candidate_cid}`;d.has(c)||(d.add(c),!o.has(n.new_cid)&&(r.superseded.has(n.new_cid)||r.superseded.has(n.candidate_cid)||r.trust.get(n.new_cid)==="derived"&&s.push({new_cid:n.new_cid,candidate_cid:n.candidate_cid,score:n.score,scorer:n.scorer})))}return s}var a=(i,r)=>i.displayNameOf(r)??r.slice(0,19);function m(i,r){return{design_children:i.edgesInto(r).filter(o=>(o.type==="belongs_to"||o.type==="scoped_to")&&!i.superseded.has(o.src)).length}}function v(i,r){let{records:t}=l(i),o=new Set,s=new Map;for(let e of t)for(let n of e.review)n.kind==="pending_archive"?s.set(n.id,n.reason):n.resolution!=="pending"&&o.add(n.id);let d=new Map;for(let[e,n]of s)r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||d.set(e,n);return{all:s,live:d}}function y(i,r){let t=[],o=new Set;for(let e of g(i.contextDir,r)){o.add(e.new_cid);let n=e.scorer==="lexical_fallback"?" (lexical fallback \u2014 the probe ran degraded)":"";t.push({kind:"PAIR",ref:a(r,e.new_cid),title:String(r.getNode(e.new_cid)?.content.title??e.new_cid.slice(0,12)),why:`possible duplicate of ${a(r,e.candidate_cid)} \u2014 score ${e.score}${n}`,pair:{candidate_cid:e.candidate_cid,candidate_ref:a(r,e.candidate_cid),score:e.score,scorer:e.scorer}})}let{all:s,live:d}=v(i.contextDir,r);for(let[e,n]of d)t.push({kind:"REVIEW",ref:a(r,e),title:String(r.getNode(e)?.content.title??e.slice(0,12)),why:`archive held for interactive confirmation${n?` \u2014 ${n}`:""}`,held:!0,impact:m(r,e)});for(let e of k(i.contextDir))t.push({kind:"MODIFY_HELD",ref:`${e.sid}:${e.tempRef}`,title:String(e.content.title??e.tempRef),why:`${e.rationale} \u2014 held by paused/dead session ${e.sid}`,heldPayload:e});for(let{cid:e,content:n}of r.byLabel(f.USECASE))r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||s.has(e)||t.push({kind:"REVIEW",ref:a(r,e),title:String(n.title??e.slice(0,12)),why:"unreviewed \u2014 approve, archive, or defer",impact:m(r,e)});return t}function F(i,r){let t={REVIEW:0,PAIR:0,MODIFY_HELD:0};for(let o of y(i,r))t[o.kind]++;return t}function b(i,r){try{let t=JSON.parse(_(p(i,"sessions",r,".lock"),"utf8"));return typeof t.pid=="number"&&u(t.pid)}catch{return!1}}function k(i){let r=[],t=p(i,"sessions");if(!w(t))return r;let o=[];try{o=R(t)}catch{return r}for(let s of o){if(!w(p(t,s,"state.json"))||b(i,s))continue;let d=[],e=!1;try{let c=h(i,s).kane;c?.pending?.proposals?.length&&(d=c.pending.proposals,e=!0)}catch{e=!1}if(!e)try{d=JSON.parse(_(p(t,s,"state.json"),"utf8")).pending?.proposals??[]}catch{continue}for(let n of d)r.push({sid:s,tempRef:String(n.tempRef??n.temp_ref??"held"),...typeof n.event_id=="string"?{event_id:n.event_id}:{},label:String(n.label??"usecase"),content:n.content??{},rationale:String(n.rationale??"held payload")})}return r}export{m as a,v as b,y as c,F as d};
@@ -0,0 +1,5 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as N}from"./chunk-UD7KKHPW.js";import{closeSync as D,existsSync as J,mkdirSync as C,openSync as U,readFileSync as M,readdirSync as X,renameSync as $,rmSync as h,watch as F,writeFileSync as _}from"fs";import{join as g}from"path";import{randomBytes as q}from"crypto";var R=1440*60*1e3,m=class extends Error{constructor(a,u,f,k){super(`${a}: ${f}`);this.code=a;this.key=u;this.holder=k}},E=e=>(e?.now??(()=>new Date))();function P(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(i){return i.code==="EPERM"}}function G(e,i){let a=i.getTime()-new Date(e.ts).getTime();return!P(e.pid)||a>=R||Number.isNaN(a)}var L=e=>g(e,"locks"),H=e=>g(L(e),"waiters");function T(e,i){return i.kind==="context"?g(L(e),"context.lock"):i.kind==="extract"?g(L(e),"extract.lock"):g(L(e),`uc-${i.id}.lock`)}var x=e=>e.kind==="uc"?e.id:e.kind,v=e=>e.kind==="uc"?`uc:${e.id}`:e.kind,K=e=>e.kind==="uc"?e.id:`~${e.kind}`;function I(e){return[...e].sort((i,a)=>K(i)<K(a)?-1:K(i)>K(a)?1:0)}function p(e){try{return JSON.parse(M(e,"utf8"))}catch{return null}}function W(e,i,a){let u=`${e}.break-${a}`;try{$(e,u)}catch(k){if(k.code==="ENOENT")return!1;throw k}let f;try{f=JSON.parse(M(u,"utf8"))}catch{f=null}if(f===null||f.nonce===i)return h(u,{force:!0}),!0;try{$(u,e)}catch{h(u,{force:!0})}return!1}var y=new Map,O=new Map;function V(e,i,a){let u=o=>`${e}|${i}|${x(o)}`;function f(o,d,s=0){if(s>20)throw new m("LOCK_CONTENTION_UNSETTLED",o,`${v(o)}: lock contention did not settle`);let c=T(e,o);C(L(e),{recursive:!0});let n=q(8).toString("hex");try{let t=U(c,"wx",384);return _(t,JSON.stringify({...d,nonce:n})+`
3
+ `),D(t),n}catch(t){if(t.code!=="EEXIST")throw t;let r=p(c),l=E(a);if(r!==null&&!G(r,l)){let S=o.kind==="context"?"CONTEXT_HELD":o.kind==="extract"?"EXTRACT_HELD":"UC_HELD";throw new m(S,o,`${v(o)} is held by ${r.owner_sid} (${r.verb})`,{owner_sid:r.owner_sid,pid:r.pid,ts:r.ts,verb:r.verb,alive:P(r.pid)})}return W(c,r?.nonce,n)&&N({type:"lock_steal",key:v(o),stale_owner:r?.owner_sid??"corrupt",by:i,ts:l.toISOString()}),f(o,d,s+1)}}function k(o,d){let s=!1;return{keys:d,assertHeld(){for(let{key:c,sk:n}of o){let t=y.get(n),r=t?p(t.path):null;if(!t||r===null||r.nonce!==t.nonce)throw new m("LOCK_LOST",c,`${v(c)} grant was taken over or removed`)}},touch(){for(let{sk:c}of o){let n=y.get(c);if(!n)continue;let t=p(n.path);t!==null&&t.nonce===n.nonce&&_(n.path,JSON.stringify({...t,ts:E(a).toISOString()})+`
4
+ `,{mode:384})}},release(){if(!s){s=!0;for(let{sk:c}of[...o].reverse()){let n=y.get(c);if(n&&(n.count-=1,n.count<=0)){y.delete(c);let t=p(n.path);t!==null&&t.nonce===n.nonce&&h(n.path,{force:!0})}}}}}}function w(o,d){let s=I(o),c=[];try{for(let n of s){let t=u(n),r=y.get(t);if(r)r.count+=1;else{let l=f(n,{owner_sid:i,pid:process.pid,ts:E(a).toISOString(),verb:d.verb??"unknown",hold:d.hold,...n.kind==="uc"?{logical_display:n.id.toUpperCase()}:{}});y.set(t,{nonce:l,count:1,path:T(e,n),key:n})}c.push({key:n,sk:t})}return k(c,s)}catch(n){for(let{sk:t}of[...c].reverse()){let r=y.get(t);if(r&&(r.count-=1,r.count<=0)){y.delete(t);let l=p(r.path);l!==null&&l.nonce===r.nonce&&h(r.path,{force:!0})}}throw n}}return{acquire:w,tryAcquire(o,d){try{return w(o,d)}catch(s){if(s instanceof m&&(s.code==="UC_HELD"||s.code==="CONTEXT_HELD"||s.code==="EXTRACT_HELD"))return{contended:s};throw s}},holder(o){return p(T(e,o))},async wait(o,d){let s=T(e,o);C(H(e),{recursive:!0});let c=g(H(e),`${x(o)}.${i}.${process.pid}.json`);try{_(c,JSON.stringify({sid:i,pid:process.pid,ts:E(a).toISOString()})+`
5
+ `,{mode:384})}catch{}let n=Date.now()+d.timeoutMs,t=null,r=null;try{try{t=F(L(e),()=>{r?.()}),t.on("error",()=>{r?.(),t=null})}catch{t=null}for(;;){if(d.signal?.aborted)return"cancelled";let l=p(s);if(l===null||G(l,E(a)))return"free";let S=n-Date.now();if(S<=0)return"timeout";await new Promise(b=>{r=b;let A=setTimeout(b,Math.min(t?250:100,Math.max(1,S)));d.signal?.addEventListener?.("abort",()=>{clearTimeout(A),b()},{once:!0})}),r=null}}finally{t?.close(),h(c,{force:!0})}},async withKeySerialized(o,d){let c=I(o).map(l=>`${e}|${x(l)}`),n=c.map(l=>O.get(l)??Promise.resolve()),t,r=new Promise(l=>{t=l});for(let l of c)O.set(l,r);await Promise.all(n);try{return await d()}finally{t();for(let l of c)O.get(l)===r&&O.delete(l)}},releaseAll(o){let d=`${e}|${o}|`;for(let[s,c]of[...y]){if(!s.startsWith(d))continue;y.delete(s);let n=p(c.path);n!==null&&n.nonce===c.nonce&&h(c.path,{force:!0})}}}}function Y(e,i){let a=e.resolve(i);if(a===null)return{key:{kind:"uc",id:i.toLowerCase()},display:i};let u=e.displayNameOf(a.tip)??e.displayNameOf(a.cid);if(u!==null&&/^uc-\d+$/i.test(u))return{key:{kind:"uc",id:u.toLowerCase()},display:u.toUpperCase()};let f=new Map;for(let[d,s]of e.superseded)typeof s=="string"&&f.set(s,d);let k=a.cid,w=new Set;for(;f.has(k)&&!w.has(k);)w.add(k),k=f.get(k);let o=k.slice(0,12);return{key:{kind:"uc",id:o},display:u??o}}function Z(e){let i=L(e);if(!J(i))return[];let a=[];for(let u of X(i)){if(!u.endsWith(".lock"))continue;let f=p(g(i,u));f!==null&&a.push({key:u.replace(/\.lock$/,""),grant:f})}return a}export{m as a,P as b,G as c,H as d,I as e,V as f,Y as g,Z as h};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{j as be,k as se,l as ae,m as xe,n as De,o as ce}from"./chunk-ORQGQSWG.js";import{a as re,c as ie,d as Pe,f as oe}from"./chunk-PGXJ275T.js";import{d as Ee}from"./chunk-6J5T5FEY.js";import{a as S}from"./chunk-TCAHDVII.js";import{a as ee,b as W,c as ne,d as G,e as $e,g as O,h as te}from"./chunk-W5TTF7GB.js";import{a as _e}from"./chunk-BZAGVBCX.js";import{b as J,c as Q,d as X}from"./chunk-Q77QO3PC.js";import{j as ke,l as Re}from"./chunk-AHXOKBVE.js";import{P as E,Q as ge,S as he,U as ve,V as we,W as ye,X as Z}from"./chunk-UHSNUUX3.js";import{C as I}from"./chunk-GP7WD4UY.js";import{H as B,t as pe}from"./chunk-3N6IAVD5.js";import{existsSync as Oe,statSync as Te}from"fs";import{basename as q,resolve as U}from"path";function Ie(e){if(!e||e.stale_refs.length===0)return"\u2014";let n=e.direct_refs??[];return`${e.stale_refs.length} stale${n.length>0?` \xB7 ${n.length} direct`:""}`}function le(e,n){let t=[...e.rows.filter(s=>s.kind!=="REMOVE").map(s=>[s.kind,S(s.ref),s.reason,Ie(s.impact)]),...e.archive.map(s=>["ARCHIVE",S(s.ref),s.why,Ie(s.impact)])],r=Math.max(40,n??100),i=[`reconcile ${e.source_id} \u2014 head ${e.head.status} \xB7 ${t.length} decision${t.length===1?"":"s"}`];return t.length>0&&i.push(...Ee(["kind","ref","why","impact"],t,r,2)),e.changed&&i.push(e.held?`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i.push("each row becomes a card below \u2014 verdicts commit as they land"),e.planPath&&i.push(`plan: ${e.planPath}`),i}var Ue=new Set(["interactive","agent","ci","override"]);function Be(e,n){if(e.mode!==void 0&&!Ue.has(e.mode))return{error:`--mode must be interactive | agent | ci | override, got '${e.mode}'`,code:"MODE_USAGE"};let t=e.mode,r="reconcile without a TTY needs an explicit mode \u2014 pass --mode agent|ci|override, or --plan for a preview";return t==="interactive"&&!n?{error:r}:t||(n?"interactive":e.plan?"override":{error:r})}async function Se(e){let{makeHeadlessIO:n,agentRefusal:t}=await import("./headless-io-3A3BZVQ5.js");return t(n("ndjson","reconcile"),e,"MODE_USAGE")}function Ve(e,n,t,r){if(Q(t)){let m=X(t),a=m?.sourceIdFor(t)??null;if(m===null||a===null)return{error:`--from '${t}' is not a supported remote URL \u2014 supported: ${J.map(f=>f.hint).join("; ")}`};if(r!==void 0&&r!==a)return{error:`--source-id '${r}' does not match this URL's own identity '${a}' \u2014 re-run without --source-id. A source adopted with --as updates by re-running context ingest with the same --as; reconcile follows only the URL's own id`};let c=I(e);if(!c.heads.has(a))return{error:`unknown source '${a}' \u2014 see \`kane-cli context list --type source\`. If this URL was ingested under a custom id, update it by re-running context ingest with the same --as`};if(c.heads.get(a)==null)return{error:`source '${a}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let _=z(e,a,{remoteUrl:t});return _!==null?{error:_}:{sourceId:a,remoteUrl:t}}if(r===void 0)return{error:"reconcile needs --from <file> AND --source-id <id> \u2014 see `kane-cli context list --type source` for ids"};let i=U(n,t);if(!Oe(i)||!Te(i).isFile())return{error:`--from '${t}' is not a file \u2014 pass the changed source document`};let s=ke(i);if(!s.ok)return{error:`--from '${t}' is not an ingestable document \u2014 allowed: ${s.allowlist.join(", ")}`};let o=I(e);if(!o.heads.has(r))return{error:`unknown source '${r}' \u2014 see \`kane-cli context list --type source\``};if(o.heads.get(r)==null)return{error:`source '${r}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let w=z(e,r,{filePath:i});if(w!==null)return{error:w};let d=null;try{d=Re(i)}catch{}return d!==null&&d!==r&&o.heads.get(d)!=null?{error:`'${q(i)}' already backs live source '${d}' \u2014 did you mean --source-id ${d}? To truly move these bytes under '${r}', retire '${d}' first`}:{sourceId:r,filePath:i}}function C(e){return e==null?"(none)":e.slice(0,19)}function K(e,n,t,r=!1,i){if(e.out(`reconcile ${n.source_id}: head ${n.head.status} \u2014 ${C(n.head.before)} \u2192 ${C(n.head.after)}`),r||(e.out(`note: ${n.note}`),e.out(`skipped arms: ${n.skipped_arms}`)),n.changed&&(e.out(n.held?`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i?.({type:"defaults_taken",count:t?.defaultsTaken??0})),r){let s=n.changeset??[],o=(d,m)=>{let a=s.filter(c=>c.kind===d).length;return a>0?`${a} ${m}`:null},w=[o("ADD","add"),o("MODIFY","modify"),o("ARCHIVE","archive")].filter(Boolean);n.changed&&e.out(`changeset: ${s.length} item(s)${w.length?` \u2014 ${w.join(" \xB7 ")}`:""}`),e.out(`plan: ${n.rows.length} row(s) \u2014 each gets a card below`);return}if(n.changed){let s=n.changeset??[];e.out(`changeset: ${s.length} item(s)`);for(let o of s)if(o.kind==="MODIFY")e.out(` [MODIFY] ${S(o.ref)} \u2014 ${o.summary} (${C(o.old_cid)} \u2192 ${o.new_cid===null?"(staged)":C(o.new_cid)})`);else if(o.kind==="ADD")e.out(` [ADD] ${S(o.ref)}`);else{e.out(` [ARCHIVE] ${S(o.ref)} \u2014 ${o.why}`);let w=de(o.impact,"retiring drops");w&&e.out(` ${w}`)}}e.out(`plan: ${n.rows.length} row(s)`);for(let s of n.rows){e.out(` [${s.kind}] ${S(s.ref)} \u2014 ${s.reason}`);let o=de(s.impact,"approving marks");o&&e.out(` ${o}`),e.out(` provenance: ${s.provenance}`),e.out(` action: ${s.action}`)}}function Ae(e,n){return le({source_id:e.source_id,head:{status:e.head.status},rows:e.rows,archive:(e.changeset??[]).filter(t=>t.kind==="ARCHIVE"),changed:e.changed,held:!!e.held,defaultsTaken:n?.defaultsTaken},process.stdout.columns)}function de(e,n){if(!e||e.stale_refs.length===0)return null;let t=e.direct_refs??[];return`impact: ${n} ${e.stale_refs.length} item(s) stale`+(t.length>0?` \u2014 ${t.length} directly touched: ${t.join(", ")}`:"")}function D(e){return e==="interactive"?"override":e}async function H(e,n,t,r,i,s,o=[],w="override",d,m,a,c,_,f,P){let p;try{p=te(e)}catch(u){return E(r,u instanceof Error?u.message:String(u)),1}try{if(!t){let{runWalkSession:u}=await import("./walk-session-MUGS6CZY.js"),{telemetryEnvName:R}=await import("./bootstrap-KCPWDBLX.js");return await u({dir:e,rows:n,archive:o,held:d??null,childMode:w,runDesign:c??null,mark:s,markA:a,...m?{archiveState:m}:{},...f?{meta:{verb:"reconcile",sid:f,env:R()}}:{},...P?{resumeCmd:P}:{},signals:b=>A(e,b.ref,b.verdict,b.reason),..._?{script:_}:{}})}return await Ye(e,n,t,r,i,s,o,w,d,m)}finally{p()}}var F=(e,n)=>e?`kane-cli maintain reconcile --from ${e} --source-id ${n}`:void 0,Le=e=>e===null?void 0:"filePath"in e?e.filePath:e.remoteUrl,L=e=>`${e} high-risk item(s) need a human \u2014 ci mode won't guess. Walk interactively or use --mode agent.`;function T(e,n,t){let r=n.rows;e({type:"reconcile_plan",source_id:n.source_id,plan_path:t,rows:r.map(i=>({kind:i.kind,ref:i.ref,why:i.reason})),archive:n.changeset.filter(i=>i.kind==="ARCHIVE").map(i=>({ref:i.ref,why:i.why}))})}function ue(e={}){return{type:"reconcile_summary",applied:0,skipped:0,deferred:0,plan_only:0,failed:0,paused:0,stale_created:0,...e}}var j=ue();async function Y(e,n,t,r,i,s,o,w,d){T(i,n,t);let m=n.changeset.filter(_=>_.kind==="ARCHIVE"&&d?.[_.ref]===void 0),a=n.rows,c;try{c=te(e)}catch(_){return i({type:"error",message:_ instanceof Error?_.message:String(_)}),i(ue()),2}try{return await je(e,n,t,r,i,s,o,a,m,w)}finally{c()}}async function je(e,n,t,r,i,s,o,w,d,m){let a=0,c=0,_=0,f=0,P=0,p=0,u=0,R=new Set,b=(v,g)=>{try{m?.(v,g)}catch{}};for(let[v,g]of w.entries()){i({type:"reconcile_row_start",kind:g.kind,ref:g.ref,...g.impact?{stale:g.impact.stale_refs.length,direct:g.impact.direct_refs?.length??0}:{}});let h=(l,$,x)=>i({type:"reconcile_row_end",kind:g.kind,ref:g.ref,outcome:l,...$!==void 0?{exit_code:$}:{},...x?{detail:x}:{}});if(g.applied){c++,h("skipped");continue}if(g.kind==="REMOVE"){P++,h("plan-only");continue}if(g.held_ref&&n.held){let l=new Set;if(g.kind==="MODIFY"&&g.impact){let x=I(e);for(let M of g.impact.stale_refs){let N=x.resolve(M);N&&x.stale(N.tip)==="fresh"&&l.add(M)}}let $=se(e,n.held,g.held_ref,fe);if(!$.ok){_++,u===0&&(u=1),h("failed",1,$.message);continue}if($.kind==="ADD"){let x=await r($.ref,{yes:!0,mode:o});if(x!==0){x===3?(f++,u===0&&(u=3),h("paused",3)):(_++,u===0&&(u=1),h("failed",x));continue}}a++,$.kind!=="ADD"&&g.impact&&(p+=l.size),b(v,"approved"),A(e,g.ref,$.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve"),h("applied");continue}let k=re(I(e),g.ref);if(!k.ok){c++,h("skipped");continue}let y=k.target;if(R.has(y.ucTip)){c++,h("skipped");continue}if(g.kind==="ADD"){let l=await r(y.seamRef,{yes:!0,mode:o});if(l===3){f++,u===0&&(u=3),h("paused",3);continue}if(l!==0){_++,u===0&&(u=1),h("failed",l);continue}R.add(y.ucTip),a++,b(v,"approved"),A(e,g.ref,"gap-resolved-create"),h("applied")}else{let l=await ie(e,y,{yes:!0,mode:o},s,r,"batch");l.outcome==="evolved"?(R.add(y.ucTip),a++,b(v,"approved"),A(e,g.ref,"gap-resolved-evolve"),h("applied")):l.outcome==="paused"?(f++,u===0&&(u=l.code),h("paused",l.code)):l.outcome==="failed"?(_++,u===0&&(u=1),h("failed",l.code)):(c++,h("skipped"))}}return d.length>0&&(i({type:"reconcile_paused",plan_path:t,pending:d.map(v=>({ref:v.ref,why:v.why}))}),f+=d.length,u===0&&(u=3)),i(ue({applied:a,skipped:c,plan_only:P,failed:_,paused:f,stale_created:p})),u}var fe={kind:"human",id:process.env.USER??"operator"};function A(e,n,t,r){_e(e,{ts:new Date().toISOString(),command:"reconcile-walk",id:n,verdict:t,polarity:"preference",by:fe,target:n,...r!==void 0?{reason:r}:{}})}async function Ye(e,n,t,r,i,s,o=[],w="override",d,m){let a=0,c=0,_=0,f=0,P=0,p=0,u=0,R=new Set;for(let[b,v]of n.entries()){if(v.applied){r.out(`skipped ${v.ref} \u2014 already applied (${v.applied.outcome} at ${v.applied.at})`),c++;continue}let g=l=>{try{s?.(b,l)}catch($){E(r,`could not record applied state for ${v.ref}: ${$ instanceof Error?$.message:String($)}`)}};if(v.kind==="REMOVE"){r.out(`REMOVE ${v.ref} \u2014 plan-only in this release (not executed)`),f++;continue}if(v.held_ref&&d){let l=se(e,d,v.held_ref,fe);if(!l.ok){E(r,`held ${v.ref}: ${l.message}`),P++,u===0&&(u=1);continue}if(r.out(`committed ${l.ref} (${v.kind==="ADD"?"minted":"updated \u2014 old\u2192new redirect"})`),l.kind==="ADD"){let $=await i(l.ref,{yes:t,mode:w});if($===3){r.out(`design session for ${l.ref} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above`),p++,u===0&&(u=3),g("approved");continue}if($!==0){E(r,`design run for ${l.ref} ended with exit code ${$}`),P++,u===0&&(u=1),g("approved");continue}}a++,g("approved"),A(e,v.ref,v.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve");continue}let h=I(e),k=re(h,v.ref);if(!k.ok){r.out(`skipped ${v.ref} \u2014 ${k.message}`),c++;continue}let y=k.target;if(R.has(y.ucTip)){r.out(`skipped ${v.ref} \u2014 use-case ${y.display} already handled in this walk`),c++;continue}if(v.kind==="ADD"){let l=await i(y.seamRef,{yes:t,mode:w});if(l===3){r.out(`design session for ${y.display} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above; this row lands when that session completes`),p++,u===0&&(u=3);continue}if(l!==0){E(r,`design run for ${y.display} ended with exit code ${l}`),P++,u===0&&(u=1);continue}R.add(y.ucTip),a++,g("approved"),A(e,v.ref,"gap-resolved-create")}else{let l=await ie(e,y,{yes:!0,mode:w},r,i,"batch");l.outcome==="evolved"?(R.add(y.ucTip),a++,g("approved"),A(e,v.ref,"gap-resolved-evolve")):l.outcome==="paused"?(p++,u===0&&(u=l.code)):l.outcome==="failed"?(P++,u===0&&(u=l.code)):c++}}for(let b of o)if(b.kind==="ARCHIVE"&&m?.[b.ref]===void 0){r.out(`[ARCHIVE] ${b.ref} \u2014 ${b.why}`);{let v=de(b.impact,"retiring drops");v&&r.out(` ${v}`)}r.out(" plan-only \u2014 retire belongs to the interactive session (never headless)"),f++}return r.out(`reconcile walk: ${a} applied, ${c} skipped, ${_} deferred, ${f} plan-only`+(P>0?`, ${P} failed`:"")+(p>0?`, ${p} paused`:"")),u}var Ke=new Set(J.map(e=>e.name));function z(e,n,t){let r=I(e),i=r.heads.get(n);if(i==null)return null;let s=r.mediaOf(i);if("remoteUrl"in t){let o=X(t.remoteUrl)?.name??"remote";return s.format!==o?`source '${n}' is backed by ${s.format} content, not a ${o} source \u2014 reconcile it with the --from it was originally ingested from`:null}return Ke.has(s.format)?`source '${n}' is a remote ${s.format} source \u2014 pass its URL to --from, not a file`:null}function me(e,n,t,r){return"remoteUrl"in n?De(e,n.remoteUrl,{out:t.out,err:t.err},r.remoteFindProvider):xe(e,n.filePath)}function Me(e){return e.remote_url!==void 0?{remoteUrl:e.remote_url}:e.backing_path!==void 0?{filePath:e.backing_path}:null}async function He(e,n,t,r,i,s=!1,o=!1){let w=i.seams??{reingest:me(e,t,r,i),reextract:ce(e,{stage:s,hostOut:c=>r.out(c),hostEmit:c=>{c.type!=="run_start"&&i.emitEvent?.(c)},...i.emitEvent?{}:{hostProgress:c=>process.stderr.write(c+`
3
+ `)}})},d=null,m={reingest:w.reingest,reextract:async c=>d=await w.reextract(c)},a;try{r.out(`reconciling ${n}: re-reading the source and comparing against the graph\u2026`),a=await(i.buildPlan??ae)(e,n,m)}catch(c){return E(r,`reconcile failed: ${c instanceof Error?c.message:String(c)}`),null}if(a.changed)if(o)for(let c of Ae(a,d))r.out(c);else K(r,a,d,!1,i.emitEvent);return a}async function Ne(e){let[{render:n},t,{ScrollbackProvider:r},{ChatSurface:i},{makeChatController:s},{makeReconcileDeps:o}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-2GPR4S7I.js"),import("./chat-controller-3EPK7UZG.js"),import("./reconcile-deps-ZCJ2QCK5.js")]),w=t.default??t,d=s(),m=o({contextDir:e,note:a=>d.note(a)});return new Promise(a=>{let c=n(w.createElement(r,null,w.createElement(i,{controller:d,verb:"extract",reconcile:m,autoReview:!0,onReviewExit:()=>{c.unmount(),a(0)},onCtrlC:()=>{c.unmount(),a(m.pending()?3:0)}})),{exitOnCtrlC:!1})})}async function We(e,n,t,r,i){let s=W(e,n);if("error"in s)return E(r,s.error),2;let{plan:o,path:w}=s,d=t==="override"||t==="ci";if(n===void 0&&t==="interactive"&&r.isTTY&&!await r.confirm(`apply plan ${q(w)} for ${o.source_id} (created ${o.created})?`))return r.out(`not applying ${q(w)}`),0;let m=i.runDesignForUc??oe,a=i.runDesignForUc??null,c=i.sessionScript,_=(v,g)=>O(w,v,g),f=(v,g)=>G(w,v,g),P=B(e);if(P===o.head_pin){if(t==="agent"){let g=i.emitEvent??(()=>{});return Y(e,V(o),w,m,g,r,D(t),_,o.archive_state)}let v=ne(o);if(t==="ci"&&v.length>0)return E(r,L(v.length)),2;if(r.out(`applying stored plan ${q(w)} for ${o.source_id} (${o.rows.length} row(s))`),!d)for(let g of le({source_id:o.source_id,head:{status:"stored plan"},rows:o.rows,archive:(o.changeset??[]).filter(h=>h.kind==="ARCHIVE"),changed:!1,held:!!o.held},process.stdout.columns))r.out(g);return H(e,o.rows,d,r,m,_,o.changeset??[],D(t),o.held,o.archive_state,f,a,c,o.source_id,F(o.backing_path??o.remote_url,o.source_id))}if(r.out(`graph moved since this plan (${C(o.head_pin)} \u2192 ${C(P)}) \u2014 recomputing`),o.held)return Fe(e,o,r,i,t,m,!1);let p=Me(o);if(p===null)return E(r,`stored plan for ${o.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let u=z(e,o.source_id,p);if(u!==null)return E(r,`stored plan cannot replay: ${u}`),2;let R=await He(e,o.source_id,p,r,i,!1,t==="interactive");if(!R)return 1;if(!R.changed)return K(r,R,null,!1,i.emitEvent),0;if(t==="agent"){let v=i.emitEvent??(()=>{});return Y(e,R,null,m,v,r,D(t))}let b=R.changeset.filter(v=>v.kind==="ARCHIVE");return t==="ci"&&b.length>0?(E(r,L(b.length)),2):H(e,R.rows,d,r,m,void 0,R.changeset,D(t),R.held,void 0,void 0,a,c,R.source_id,F(Le(p),R.source_id))}function V(e,n=!1){return{source_id:e.source_id,changed:!0,head:{status:"unchanged",before:e.head_pin,after:e.head_pin},note:e.note,skipped_arms:e.skipped_arms,changeset:e.changeset??[],rows:n?e.rows.filter(t=>t.applied===void 0):e.rows,...e.held?{held:e.held}:{}}}async function Ge(e,n,t,r,i,s,o){let w=r.runDesignForUc??null,d=r.sessionScript,m=$e(e,n);if(m===null)return null;if("error"in m)return E(t,m.error),2;let{plan:a,path:c}=m,_=a.rows.filter(u=>u.applied===void 0),f=ne(a),P=r.emitEvent??(()=>{});if(_.length===0&&f.length===0){t.out(`already reconciled \u2014 plan ${a.created} applied ${a.rows.length} row(s)`);let u=Pe(I(e)).staleCount;return u>0&&(t.out(`${u} item(s) still stale \u2014 kane-cli maintain evolve --from-stale`),P({type:"stale_debt",count:u})),i==="agent"&&(T(P,V(a),c),P({...j})),0}let p=B(e);return p!==a.head_pin?(t.out(`plan ${a.created} superseded \u2014 graph moved (${C(a.head_pin)} \u2192 ${C(p)}); recomputing`),Fe(e,a,t,r,i,s,o)):(t.out(`resuming plan ${a.created} \u2014 ${_.length} pending row(s)${f.length>0?`, ${f.length} undecided archive item(s)`:""}`),o?(K(t,V(a),null,!1,r.emitEvent),t.out(`plan stored: ${c}`),i==="agent"&&(T(P,V(a),c),P({...j})),0):i==="agent"?Y(e,V(a),c,s,P,t,D(i),(u,R)=>O(c,u,R),a.archive_state):i==="ci"&&f.length>0?(E(t,L(f.length)),2):H(e,a.rows,i==="override"||i==="ci",t,s,(u,R)=>O(c,u,R),a.changeset??[],D(i),a.held,a.archive_state,(u,R)=>G(c,u,R),w,d,a.source_id,F(a.backing_path??a.remote_url,a.source_id)))}async function Fe(e,n,t,r,i,s,o){let w=r.runDesignForUc??null,d=r.sessionScript,m;if(n.held){let h=I(e),k=new Set(n.rows.filter(l=>l.held_ref!==void 0&&l.applied!==void 0).map(l=>l.held_ref)),y=[];for(let l of n.held.rows){if(k.has(l.temp_ref))continue;if(!l.matched_cid){y.push(l);continue}let $=h.tipOf(l.matched_cid);if(h.superseded.get($)===null){t.out(`dropped held "${l.title}" \u2014 its use-case was retired meanwhile`),r.emitEvent?.({type:"held_dropped",ref:l.temp_ref,title:l.title,reason:"target_retired"});continue}y.push($===l.matched_cid?l:{...l,matched_cid:$,uc:{...l.uc,matches_existing:{cid:$}}})}m={source_id:n.held.source_id,rows:y}}let a=Me(n);if(a===null)return E(t,`stored plan for ${n.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let c=z(e,n.source_id,a);if(c!==null)return E(t,`stored plan cannot replay: ${c}`),2;let _=r.seams??{reingest:me(e,a,t,r),reextract:ce(e,{stage:m!==void 0,hostOut:h=>t.out(h),hostEmit:h=>{h.type!=="run_start"&&r.emitEvent?.(h)},...r.emitEvent?{}:{hostProgress:h=>process.stderr.write(h+`
4
+ `)}})},f;try{f=await(r.buildPlan??ae)(e,n.source_id,_,{resumeHeld:m})}catch(h){return E(t,`reconcile failed: ${h instanceof Error?h.message:String(h)}`),1}if(i==="interactive"&&!o)for(let h of Ae(f,null))t.out(h);else K(t,f,null,!1,r.emitEvent);let P=B(e),p=null;if(P!=null){let h={},k=new Set(f.changeset.filter(y=>y.kind==="ARCHIVE").map(y=>y.ref));for(let[y,l]of Object.entries(n.archive_state??{}))k.has(y)&&(h[y]=l);p=ee(e,{version:2,source_id:f.source_id,...n.remote_url!==void 0?{remote_url:n.remote_url}:{backing_path:n.backing_path},head_pin:P,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:f.skipped_arms,note:f.note,changeset:f.changeset,rows:f.rows,...f.held?{held:f.held}:{},...Object.keys(h).length>0?{archive_state:h}:{}}),t.out(`plan stored: ${p}`)}if(o){if(i==="agent"){let h=r.emitEvent??(()=>{});T(h,f,p),h({...j})}return 0}let u=r.emitEvent??(()=>{}),R=p?W(e,p).plan.archive_state:void 0,b=p?(h,k)=>O(p,h,k):void 0,v=p?(h,k)=>G(p,h,k):void 0;if(i==="agent")return Y(e,f,p,s,u,t,D(i),b,R);let g=f.changeset.filter(h=>h.kind==="ARCHIVE"&&R?.[h.ref]===void 0);return i==="ci"&&g.length>0?(E(t,L(g.length)),2):H(e,f.rows,i==="override"||i==="ci",t,s,b,f.changeset,D(i),f.held,R,v,w,d,f.source_id,F(n.backing_path??n.remote_url,f.source_id))}async function Ce(e,n,t={},r=process.cwd()){let{telemetryBootstrap:i,telemetryEnvName:s}=await import("./bootstrap-KCPWDBLX.js"),o=i({verb:"reconcile",mode:typeof e.mode=="string"?e.mode:"interactive",contextRoot:U(r,".context"),env:s(),applyPlanPath:typeof e.apply=="string"?U(r,e.apply):void 0,write:!0,longSession:!0});e.mode==="agent"&&t.emitEvent?.({type:"run_start",session:o.ids.session_id});{let m=Oe(U(r,".context"))?ye(U(r,".context")):null;if(m)return e.mode==="agent"?t.emitEvent?.(Z(m)):(E(n,m.text),(n.err??n.out)(`next: ${m.remedy}`)),await o.end({exit_code:2}),2}let w=await ve(U(r,".context"));w&&(e.mode==="agent"?t.emitEvent?.(we(w)):(n.err??n.out)(w.text));let d=await qe(e,n,t,r);return d===1&&e.mode!=="agent"&&(n.err??n.out)(o.supportFooter()),await o.end({exit_code:d}),d}async function qe(e,n,t={},r=process.cwd()){let i=e.apply!==void 0&&e.apply!==!1,s=typeof e.apply=="string"?e.apply:void 0;if(e.plan&&i)return E(n,"pass --plan OR --apply, not both"),2;let o=e.from!==void 0||!i,w=e.from!==void 0&&Q(e.from);if(o&&(!e.from||!e.sourceId&&!w))return E(n,"reconcile needs --from <file|url> AND --source-id <id> (files only \u2014 a URL derives its own id) \u2014 see `kane-cli context list --type source` for ids"),2;if(e.from&&s!==void 0)return E(n,"pass --from OR --apply <path>, not both \u2014 a stored plan names its own source"),2;let d=ge(r,n);if(!d)return 2;if(e.mode!==void 0&&!Ue.has(e.mode))return Se(`--mode must be interactive | agent | ci | override, got '${e.mode}'`);let m=e.mode==="agent"||e.mode==="ci"||e.mode==="override";if(i&&!m&&!n.isTTY)return E(n,"refusing to apply without a TTY to confirm \u2014 pass --mode override|ci"),2;let a=!e.plan,c="override";if(e.from){let k=Be(e,n.isTTY);if(typeof k=="object")return k.code==="MODE_USAGE"?Se(k.error):(E(n,k.error),2);c=k}let _=c==="override"||c==="ci";if(i&&!e.from){let{makeReconcileDeps:k}=await import("./reconcile-deps-ZCJ2QCK5.js"),y=s===void 0?k({contextDir:d}).pending():null;if(y?.kind==="cards"){let $=e.mode??"interactive";return!n.isTTY||$!=="interactive"?(E(n,`a held changeset for ${y.source} awaits review (${y.count} change(s)) \u2014 resume in a terminal: kane-cli maintain reconcile --apply [HELD_REVIEW]`),2):(t.cardApplyMount??Ne)(d)}let l=e.mode??"interactive";return We(d,s===void 0?void 0:U(r,s),l,n,t)}let f=Ve(d,r,e.from,e.sourceId);if("error"in f)return E(n,f.error),2;if(!i){let{sessionsHoldingSource:k}=await import("./sessions-NH7WQWMX.js"),{holders:y,corrupt:l}=k(d,f.sourceId);if(l>0)return E(n,`cannot verify review holds \u2014 ${l} session file(s) unreadable; inspect with kane-cli context sessions list, clean with kane-cli context sessions clean, then retry [SESSIONS_UNREADABLE]`),2;if(y.length>0)return E(n,`session ${y[0]} holds item(s) for review pinned to ${f.sourceId} \u2014 finish that review first: kane-cli context extract --resume ${y[0]} [SOURCE_HELD]`),2}if(c==="interactive"&&!e.plan&&!i){let k=t.seams?.reingest??me(d,f,n,t),y;try{y=await k(f.sourceId)}catch($){return E(n,$ instanceof Error?$.message:String($)),1}let l=y.status==="unchanged"?null:be(d,f.sourceId);if(y.status!=="unchanged"&&!l)return n.out(`${f.sourceId} landed for the first time \u2014 extract it: kane-cli context extract --source ${f.sourceId}`),0;if(l){let x=await(t.chatMount??(async M=>{let{bindExtractInteractive:N}=await import("./extract-bind-7IDQS4QP.js");return N(M)}))({mode:"interactive",posture:"reconcile",source:f.sourceId,changeContext:l});if(x===3){let{sessionsHoldingSource:M}=await import("./sessions-NH7WQWMX.js");if(M(d,f.sourceId).holders.length===0)return 0}return x}}let P="remoteUrl"in f?{remoteUrl:f.remoteUrl}:{filePath:f.filePath},p=await He(d,f.sourceId,P,n,t,!!e.plan||c==="interactive",c==="interactive"&&!e.plan);if(!p)return 1;let u=t.runDesignForUc??oe,R=t.runDesignForUc??null,b=t.sessionScript;if(!p.changed){let k=await Ge(d,f.sourceId,n,t,c,u,!!e.plan);if(k!==null)return k;if(K(n,p,null,!1,t.emitEvent),c==="agent"){let y=t.emitEvent??(()=>{});T(y,p,null),y({...j})}return 0}let v=B(d),g=null;if(v!=null?g=ee(d,{version:2,source_id:p.source_id,..."remoteUrl"in P?{remote_url:P.remoteUrl}:{backing_path:P.filePath},head_pin:v,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:p.skipped_arms,note:p.note,changeset:p.changeset,rows:p.rows,...p.held?{held:p.held}:{}}):E(n,"no chain head after extract \u2014 plan not stored"),c==="agent"){let k=t.emitEvent??(()=>{});if(!a)return T(k,p,g),k({...j}),0;let y=g?(l,$)=>O(g,l,$):void 0;return Y(d,p,g,u,k,n,D(c),y)}if(!a)return g&&n.out(`plan stored: ${g}`),0;let h=p.changeset.filter(k=>k.kind==="ARCHIVE");if(c==="ci"&&h.length>0)return g&&n.out(`plan stored: ${g}`),E(n,L(h.length)),2;if(g){n.out(`plan stored: ${g}`);let k=g;return H(d,ze(d,k)??p.rows,_,n,u,(y,l)=>O(k,y,l),p.changeset,D(c),p.held,void 0,void 0,R,b,p.source_id,F(e.from,p.source_id))}return H(d,p.rows,_,n,u,void 0,p.changeset,D(c),p.held,void 0,void 0,R,b,p.source_id,F(e.from,p.source_id))}function ze(e,n){let t=W(e,n);return"error"in t?null:t.plan.rows}async function hn(e,n={},t,r=process.cwd()){if(e.mode==="agent"){let{makeHeadlessIO:i}=await import("./headless-io-3A3BZVQ5.js"),s=t?i("ndjson","reconcile",t):i("ndjson","reconcile"),o={out:s.out,err:m=>s.event({type:"error",message:m}),isTTY:!1,confirm:async()=>!1,ask:async()=>""},{runWithChannel:w}=await import("./run-channel-RGH4WIQX.js"),d=2;try{d=await w({event:m=>s.event(m)},()=>Ce(e,o,{...n,emitEvent:m=>s.event(m)},r))}catch(m){m instanceof pe?(d=2,s.event(Z({code:m.code,text:m.message,remedy:m.remedy}))):(d=1,s.event({type:"error",message:m instanceof Error?m.message:String(m)}))}return s.done(d)}return Ce(e,he(),n,r)}export{Be as a,Ve as b,D as c,A as d,Ce as e,hn as f};