@testmuai/kane-cli 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (270) hide show
  1. package/bin/kane-cli.cjs +5 -1
  2. package/dist/{ChatSurface-S2P7WMBI.js → ChatSurface-LS3KF7XY.js} +1 -1
  3. package/dist/{ChromeProfilePicker-7DTJK2QW.js → ChromeProfilePicker-UIJ5ZBLY.js} +1 -1
  4. package/dist/{CliFeedbackPrompt-Y3OYZX54.js → CliFeedbackPrompt-EIQQBWDY.js} +1 -1
  5. package/dist/{CliUploadProgress-I3N5WDNJ.js → CliUploadProgress-6U77ZBAX.js} +1 -1
  6. package/dist/ConfigView-MVFLCF5N.js +2 -0
  7. package/dist/EvidenceViewOffer-ANVEOXJA.js +2 -0
  8. package/dist/FolderPicker-HVI6KITN.js +2 -0
  9. package/dist/{InfoBox-QBXPPMM2.js → InfoBox-57MRRSJI.js} +1 -1
  10. package/dist/{LinksBox-L24KON4U.js → LinksBox-RKAEQBFS.js} +1 -1
  11. package/dist/{ProfilesView-H6XCTIXI.js → ProfilesView-RQCQFIXH.js} +1 -1
  12. package/dist/{ProjectPicker-F6JGF2B3.js → ProjectPicker-5JEEHLY3.js} +1 -1
  13. package/dist/{SaveSessionPrompt-QGO65DZN.js → SaveSessionPrompt-TQROE5JM.js} +1 -1
  14. package/dist/SingleShotApp-VJVY3F4H.js +2 -0
  15. package/dist/{SummaryBox-OZIZQY4B.js → SummaryBox-C4UY6R65.js} +1 -1
  16. package/dist/TestMdRunView-X3CCNYV5.js +2 -0
  17. package/dist/{TestrunEvidenceTable-A7WTTKTV.js → TestrunEvidenceTable-LY24PK3T.js} +1 -1
  18. package/dist/{WhoamiView-EB5AV27X.js → WhoamiView-2FIHHS4G.js} +1 -1
  19. package/dist/{app-download-SQ4RDY3E.js → app-download-TO672LBR.js} +1 -1
  20. package/dist/{auth-TW24FZQF.js → auth-EVXJVU72.js} +1 -1
  21. package/dist/{binary-5LMQJ3CZ.js → binary-Y4DKNDQH.js} +1 -1
  22. package/dist/{bind-SJ6DOVQ4.js → bind-FVCVYYL3.js} +3 -3
  23. package/dist/{bootstrap-BTEXO6HX.js → bootstrap-4XBQFKWF.js} +1 -1
  24. package/dist/bridge-6DCBL3GY.js +2 -0
  25. package/dist/{changelog-JLSLSA3Y.js → changelog-LAQ2VGK6.js} +1 -1
  26. package/dist/chat-committer-K3NOTLOU.js +2 -0
  27. package/dist/chat-controller-YJCNU76T.js +2 -0
  28. package/dist/chunk-2MQP4SSF.js +20 -0
  29. package/dist/{chunk-S66MCU2Y.js → chunk-36ZVMJTJ.js} +1 -1
  30. package/dist/{chunk-USI2WMAK.js → chunk-3GZ4FQ4L.js} +1 -1
  31. package/dist/{chunk-CLLQQPBZ.js → chunk-4BIJCAR4.js} +1 -1
  32. package/dist/chunk-4PMZ5FCD.js +2 -0
  33. package/dist/{chunk-2DCNCH32.js → chunk-54JZ6VEW.js} +1 -1
  34. package/dist/{chunk-ZGBSGZZM.js → chunk-5G22NOZK.js} +1 -1
  35. package/dist/{chunk-YEQVJWEF.js → chunk-5LYPSIBC.js} +1 -1
  36. package/dist/{chunk-RDNKYRKY.js → chunk-5M5BG4MT.js} +1 -1
  37. package/dist/{chunk-YHTYPTDD.js → chunk-5YCOYFZH.js} +1 -1
  38. package/dist/chunk-6FCPS2VT.js +4 -0
  39. package/dist/{chunk-4NSP2NPT.js → chunk-6LYQ4MJH.js} +1 -1
  40. package/dist/{chunk-XY325HDJ.js → chunk-6T3DWH56.js} +1 -1
  41. package/dist/{chunk-D4SRHIJ5.js → chunk-6TVNJDSE.js} +1 -1
  42. package/dist/{chunk-P3RKXL3V.js → chunk-7CXIOJB3.js} +1 -1
  43. package/dist/{chunk-RZLD7TPG.js → chunk-7RTITBZG.js} +1 -1
  44. package/dist/{chunk-JCD6FP7A.js → chunk-7UCICMK7.js} +3 -3
  45. package/dist/{chunk-SS5TOK2J.js → chunk-7UYSTQMI.js} +1 -1
  46. package/dist/chunk-7YX2HUHY.js +2 -0
  47. package/dist/chunk-AKX4VRRR.js +2 -0
  48. package/dist/{chunk-KQ2MYMOS.js → chunk-AO5QH6UU.js} +1 -1
  49. package/dist/{chunk-YZ45OEH3.js → chunk-AS5UKK27.js} +1 -1
  50. package/dist/{chunk-JN44V63O.js → chunk-ATIX6CVS.js} +2 -2
  51. package/dist/{chunk-TDS6LG6T.js → chunk-AZ73FJRK.js} +1 -1
  52. package/dist/{chunk-ZRKPZLLG.js → chunk-BAKOH2BR.js} +1 -1
  53. package/dist/{chunk-Z35BUPZT.js → chunk-BRE426DP.js} +1 -1
  54. package/dist/{chunk-IGJIDN4U.js → chunk-BYOXTXLC.js} +1 -1
  55. package/dist/{chunk-JFAFKHDX.js → chunk-BZAGVBCX.js} +1 -1
  56. package/dist/{chunk-FYS5VIOG.js → chunk-CQCV2RJK.js} +2 -2
  57. package/dist/{chunk-FJYDEWOA.js → chunk-DHPBVHED.js} +1 -1
  58. package/dist/{chunk-7KORP5FF.js → chunk-EEFZXZTZ.js} +1 -1
  59. package/dist/{chunk-GFKCTYCA.js → chunk-EV64VI66.js} +1 -1
  60. package/dist/{chunk-IWM5EZC3.js → chunk-FGRTNRBS.js} +2 -2
  61. package/dist/{chunk-NT3UETTV.js → chunk-FL6TCYA5.js} +1 -1
  62. package/dist/{chunk-IMR64OCZ.js → chunk-GX3FPJUG.js} +1 -1
  63. package/dist/{chunk-FUNKVREV.js → chunk-GZLQ2AR6.js} +1 -1
  64. package/dist/chunk-H4WIA4IP.js +26 -0
  65. package/dist/{chunk-ZLSWHCWO.js → chunk-H6YGG3GC.js} +1 -1
  66. package/dist/chunk-HJOGBE23.js +26 -0
  67. package/dist/{chunk-DN3E6RT6.js → chunk-HK3FFI7Y.js} +2 -2
  68. package/dist/{chunk-TYI4MLFJ.js → chunk-HPBI3P6I.js} +3 -3
  69. package/dist/{chunk-FMUCZWS3.js → chunk-HZDNGNO2.js} +1 -1
  70. package/dist/chunk-IPEA7ZOF.js +8 -0
  71. package/dist/{chunk-6KPPGMO2.js → chunk-IVQX3AKL.js} +1 -1
  72. package/dist/chunk-IWVA37B6.js +5 -0
  73. package/dist/chunk-JE6OO2Q6.js +8 -0
  74. package/dist/{chunk-PT7V5WDQ.js → chunk-JPGRUMCS.js} +1 -1
  75. package/dist/chunk-JQW2QFSX.js +2 -0
  76. package/dist/{chunk-JZ26R6UL.js → chunk-JUJ4SAGH.js} +1 -1
  77. package/dist/chunk-K5DL7CZ4.js +2 -0
  78. package/dist/{chunk-TKYJTXWL.js → chunk-K6JRFRGS.js} +1 -1
  79. package/dist/chunk-KAZGHWGK.js +5 -0
  80. package/dist/{chunk-AFPHLUQ5.js → chunk-KGKJU27A.js} +1 -1
  81. package/dist/{chunk-E5S4BASB.js → chunk-LI5FMAUO.js} +1 -1
  82. package/dist/{chunk-INK66XQS.js → chunk-LMYE3M75.js} +1 -1
  83. package/dist/{chunk-OFW3ZVTP.js → chunk-LPH4TERT.js} +1 -1
  84. package/dist/chunk-N5I2QYFD.js +2 -0
  85. package/dist/chunk-N7Z7BQYO.js +3 -0
  86. package/dist/{chunk-EXERQHXV.js → chunk-NAZ36RKI.js} +1 -1
  87. package/dist/chunk-O4IEPE3T.js +4 -0
  88. package/dist/{chunk-CLGC7VEO.js → chunk-O5U6EAL3.js} +1 -1
  89. package/dist/chunk-OGJR5VIG.js +363 -0
  90. package/dist/{chunk-A44G533S.js → chunk-OO7LFDET.js} +1 -1
  91. package/dist/chunk-OQAN2WYO.js +26 -0
  92. package/dist/{chunk-GC5U55MW.js → chunk-P67CGWD6.js} +1 -1
  93. package/dist/{chunk-C4WTZSX4.js → chunk-PQYBIWZH.js} +1 -1
  94. package/dist/chunk-PYHWCV2V.js +2 -0
  95. package/dist/{chunk-AO3PBE2V.js → chunk-Q6743UUQ.js} +1 -1
  96. package/dist/{chunk-5DBK6QNS.js → chunk-QQ5MHSSY.js} +1 -1
  97. package/dist/{chunk-DZCG7FFP.js → chunk-QVR2PB6Y.js} +1 -1
  98. package/dist/{chunk-WMQJBEQP.js → chunk-QXLX6LMJ.js} +1 -1
  99. package/dist/{chunk-VOBXYDJW.js → chunk-R4PLEH2A.js} +47 -47
  100. package/dist/{chunk-TQKIE7AX.js → chunk-RHL7KZNC.js} +1 -1
  101. package/dist/chunk-RSSOJ3L2.js +21 -0
  102. package/dist/{chunk-VMCSRLRC.js → chunk-S6M36UIV.js} +1 -1
  103. package/dist/{chunk-SQC4P2Q7.js → chunk-SQWVGI3J.js} +1 -1
  104. package/dist/{chunk-ATWDQCDA.js → chunk-UDW4ZZAW.js} +7 -7
  105. package/dist/{chunk-CUM23TLF.js → chunk-UH2ZTX4E.js} +1 -1
  106. package/dist/{chunk-XJILZ2WN.js → chunk-UPHF2J5E.js} +1 -1
  107. package/dist/{chunk-SQGBFCFO.js → chunk-UY2ES2Z6.js} +1 -1
  108. package/dist/{chunk-3LEVCW6R.js → chunk-UYLNH4SH.js} +1 -1
  109. package/dist/{chunk-OYJBABRV.js → chunk-V5DYLGAM.js} +1 -1
  110. package/dist/{chunk-7VZCXW74.js → chunk-VCDXUUJQ.js} +1 -1
  111. package/dist/{chunk-5COGCNED.js → chunk-VQVERWC3.js} +1 -1
  112. package/dist/chunk-W3Z7AZNT.js +4 -0
  113. package/dist/{chunk-BN6AHQL7.js → chunk-WALVOFKR.js} +4 -4
  114. package/dist/{chunk-3UUPP5W3.js → chunk-WDOEMLFZ.js} +1 -1
  115. package/dist/chunk-WHEWZR2C.js +15 -0
  116. package/dist/{chunk-VRVFPMCR.js → chunk-WIAZN7G4.js} +1 -1
  117. package/dist/{chunk-AWD56KGX.js → chunk-WPSQYEBP.js} +2 -2
  118. package/dist/{chunk-RX5TZZNQ.js → chunk-WRIPTYSN.js} +1 -1
  119. package/dist/{chunk-GELPKSLC.js → chunk-WYOEOJM2.js} +1 -1
  120. package/dist/{chunk-B4Q6FMIP.js → chunk-XFTF7OOY.js} +3 -3
  121. package/dist/{chunk-QISE272H.js → chunk-XJ4TJARR.js} +1 -1
  122. package/dist/{chunk-KDXQNLVV.js → chunk-XLVH4CIZ.js} +3 -3
  123. package/dist/{chunk-DUAXZYAD.js → chunk-XMTSHHYQ.js} +3 -3
  124. package/dist/{chunk-XWKUZJCP.js → chunk-YMLC55J4.js} +1 -1
  125. package/dist/chunk-Z7S3IWUX.js +2 -0
  126. package/dist/chunk-ZDAO5D6D.js +16 -0
  127. package/dist/{chunk-TZFT7R7B.js → chunk-ZHKBSKCB.js} +1 -1
  128. package/dist/chunk-ZIJLOYXX.js +21 -0
  129. package/dist/{chunk-4ONGF4NT.js → chunk-ZKRL6HMY.js} +2 -2
  130. package/dist/{chunk-2R7KL7YG.js → chunk-ZSFOANLG.js} +1 -1
  131. package/dist/committer-C6UCDYMC.js +2 -0
  132. package/dist/{config-6TQIMTNB.js → config-5UNFAVY6.js} +1 -1
  133. package/dist/cover-cmd-5LPHIOSI.js +3 -0
  134. package/dist/{credentials-ZSNM4BTD.js → credentials-64JYS7AQ.js} +1 -1
  135. package/dist/{deps-bundle-D2ZC2SPT.js → deps-bundle-5JPHXHQV.js} +1 -1
  136. package/dist/{deps-resolve-VRBMFUTX.js → deps-resolve-WFZZ22XH.js} +1 -1
  137. package/dist/descriptor-PWUUNYV7.js +2 -0
  138. package/dist/design-committer-UPC6NZUF.js +2 -0
  139. package/dist/device-ref-LAZWPRQN.js +2 -0
  140. package/dist/dispatch-JLMCXOSK.js +2 -0
  141. package/dist/doctor-KJMR7NRK.js +2 -0
  142. package/dist/dossier-Y6TJWFZU.js +3 -0
  143. package/dist/evidence-OFTY5U4X.js +2 -0
  144. package/dist/evolve-cmd-LU6LPT4F.js +2 -0
  145. package/dist/exit-manager-ZLDO54S4.js +2 -0
  146. package/dist/{explain-UAAQWHYR.js → explain-3HAZY7Q6.js} +1 -1
  147. package/dist/{explain-cmd-EX24XKD6.js → explain-cmd-RMJPXD4U.js} +1 -1
  148. package/dist/{explain-cmd-2TKO7GRW.js → explain-cmd-XCRO4AS6.js} +1 -1
  149. package/dist/{extract-bind-TJ2STXV5.js → extract-bind-YYIOEAYR.js} +3 -3
  150. package/dist/{extract-cmd-FLOYO6HL.js → extract-cmd-Q7OG6RY6.js} +2 -2
  151. package/dist/{feeder-C3TOJPKK.js → feeder-IOR3XRNF.js} +1 -1
  152. package/dist/gaps-cmd-JIUM5YDY.js +3 -0
  153. package/dist/{gate-54BRAE7N.js → gate-E3BLIUEA.js} +1 -1
  154. package/dist/{generate-headless-DBT4MKQT.js → generate-headless-NCVM643E.js} +2 -2
  155. package/dist/index.js +137 -131
  156. package/dist/ingest-TTUQ7UDK.js +2 -0
  157. package/dist/ingest-cmd-42VRDSPV.js +2 -0
  158. package/dist/install-5NMP6ZV4.js +2 -0
  159. package/dist/{interactive-bind-7UDJY4CF.js → interactive-bind-ZDJS7PCV.js} +4 -4
  160. package/dist/lifecycle-cmd-KSMETBPP.js +2 -0
  161. package/dist/list-cmd-V3HJ5K4O.js +3 -0
  162. package/dist/{list-commands-DA4ZXOPJ.js → list-commands-3IKFZSGB.js} +1 -1
  163. package/dist/logical-ids-MLXAH45L.js +2 -0
  164. package/dist/login-flow-UXUQ7GQT.js +2 -0
  165. package/dist/{maintenance-cmd-6XSVO6FO.js → maintenance-cmd-VFYGKY3X.js} +1 -1
  166. package/dist/{mobile-prompts-JS7GPVKS.js → mobile-prompts-XPQSRBIW.js} +1 -1
  167. package/dist/persist-recorded-session-MFQ7JCLJ.js +3 -0
  168. package/dist/phase-seed-BMOSAA74.js +2 -0
  169. package/dist/pipeline-2XITQU5W.js +2 -0
  170. package/dist/prepare-target-CKRWHYXS.js +2 -0
  171. package/dist/readmodel-TDRFVDVI.js +2 -0
  172. package/dist/reconcile-cmd-BKIJFVQT.js +2 -0
  173. package/dist/reconcile-deps-Y5G456WD.js +4 -0
  174. package/dist/reconcile-engine-WDC2MEOY.js +2 -0
  175. package/dist/{recording-banner-YMKWR3M3.js → recording-banner-P3RUW62P.js} +1 -1
  176. package/dist/records-JLS63SDI.js +2 -0
  177. package/dist/registry-OEY4IXB6.js +2 -0
  178. package/dist/{require-project-folder-3KS7KTME.js → require-project-folder-ZGQLWZV5.js} +1 -1
  179. package/dist/resolve-run-intent-DHZD6A4B.js +2 -0
  180. package/dist/{resolver-V5VP5FLT.js → resolver-W54NOQXY.js} +1 -1
  181. package/dist/revert-PRR3D4XM.js +2 -0
  182. package/dist/review-cmd-SAGIKWEW.js +4 -0
  183. package/dist/run-7TZTUTTU.js +2 -0
  184. package/dist/run-BGQTRIU4.js +2 -0
  185. package/dist/{run-test-md-FO2RNNOD.js → run-test-md-WO2UDYPM.js} +2 -2
  186. package/dist/{sessions-cmd-ZZIZN2VB.js → sessions-cmd-VDQGRBEM.js} +1 -1
  187. package/dist/{skill-installer-W4TT5MST.js → skill-installer-UTVUPOTD.js} +1 -1
  188. package/dist/{spawner-ZSYJQGQW.js → spawner-SHCGHLQS.js} +1 -1
  189. package/dist/{structured-answers-5EY2AZN7.js → structured-answers-YAVW65G4.js} +1 -1
  190. package/dist/tcg-generate-YDNE643C.js +2 -0
  191. package/dist/testmd-actions-UCJ4ULSX.js +2 -0
  192. package/dist/token-refresh-ZNV2OSZC.js +2 -0
  193. package/dist/{validate-basic-727KRHX6.js → validate-basic-XEPS5I6V.js} +1 -1
  194. package/dist/verdicts-SOX22V6V.js +2 -0
  195. package/dist/{version-check-A2JQYRI2.js → version-check-LWDLMWBJ.js} +1 -1
  196. package/dist/{view-cmd-KPJTP4DI.js → view-cmd-SXXNDZIC.js} +1 -1
  197. package/dist/walk-session-M3OIWR5K.js +2 -0
  198. package/dist/with-telemetry-SF5RHYQE.js +2 -0
  199. package/package.json +11 -14
  200. package/dist/ConfigView-EOYCKYJS.js +0 -2
  201. package/dist/EvidenceViewOffer-AQ3KB3EN.js +0 -2
  202. package/dist/FolderPicker-RCHRYYC4.js +0 -2
  203. package/dist/SingleShotApp-AY3XFEYT.js +0 -2
  204. package/dist/TestMdRunView-RPW4MIJA.js +0 -2
  205. package/dist/bridge-GQJ35GTL.js +0 -2
  206. package/dist/chat-committer-ZWWCLJFD.js +0 -2
  207. package/dist/chat-controller-R4THYYPU.js +0 -2
  208. package/dist/chunk-3Q6WAK6P.js +0 -2
  209. package/dist/chunk-56PAQAX5.js +0 -19
  210. package/dist/chunk-B5QGIUJA.js +0 -26
  211. package/dist/chunk-BRTARADN.js +0 -4
  212. package/dist/chunk-CZUOGGUK.js +0 -2
  213. package/dist/chunk-DEZ7CXGM.js +0 -21
  214. package/dist/chunk-ESC7AOCX.js +0 -2
  215. package/dist/chunk-KLTKEGDH.js +0 -355
  216. package/dist/chunk-LN7233E2.js +0 -20
  217. package/dist/chunk-LQQXPY5B.js +0 -4
  218. package/dist/chunk-MKSTP2XN.js +0 -26
  219. package/dist/chunk-Q4V2GK5U.js +0 -2
  220. package/dist/chunk-QBG7XEGQ.js +0 -15
  221. package/dist/chunk-QQAAPFIR.js +0 -2
  222. package/dist/chunk-R5T4RLF5.js +0 -2
  223. package/dist/chunk-SORVX3KI.js +0 -7
  224. package/dist/chunk-TH47OOBV.js +0 -4
  225. package/dist/chunk-TRJUD3XJ.js +0 -5
  226. package/dist/chunk-V444REBC.js +0 -11
  227. package/dist/chunk-VAYBKR76.js +0 -4
  228. package/dist/chunk-WXHQYYD5.js +0 -2
  229. package/dist/chunk-XQFITNA3.js +0 -2
  230. package/dist/chunk-ZSXDZI56.js +0 -20
  231. package/dist/committer-SWEWEYNX.js +0 -2
  232. package/dist/cover-cmd-7JILZJUK.js +0 -3
  233. package/dist/descriptor-OEUZZCOK.js +0 -2
  234. package/dist/design-committer-VYT6NU3T.js +0 -2
  235. package/dist/dispatch-2PBSJ7YW.js +0 -2
  236. package/dist/doctor-OWRRDA4Z.js +0 -2
  237. package/dist/dossier-KTLTGT2X.js +0 -3
  238. package/dist/evidence-NDAKCCHQ.js +0 -2
  239. package/dist/evolve-cmd-DIA5EWUT.js +0 -2
  240. package/dist/exit-manager-3FVBTNYR.js +0 -2
  241. package/dist/gaps-cmd-3ZX3PZF4.js +0 -3
  242. package/dist/ingest-JO5NJENZ.js +0 -2
  243. package/dist/ingest-cmd-T6HM3AHK.js +0 -2
  244. package/dist/install-NIVU4XVS.js +0 -2
  245. package/dist/lifecycle-cmd-O2324GN6.js +0 -2
  246. package/dist/list-cmd-N4KMA34H.js +0 -3
  247. package/dist/logical-ids-TEBCQJGO.js +0 -2
  248. package/dist/login-flow-NHBJVDW6.js +0 -2
  249. package/dist/persist-recorded-session-LE3LGFOS.js +0 -3
  250. package/dist/phase-seed-DIRETNU6.js +0 -2
  251. package/dist/pipeline-MTAZDCZR.js +0 -2
  252. package/dist/prepare-target-YK2DLDWB.js +0 -2
  253. package/dist/readmodel-XOYGGQ3S.js +0 -2
  254. package/dist/reconcile-cmd-CYRYVS5B.js +0 -2
  255. package/dist/reconcile-deps-FYXRAMF2.js +0 -4
  256. package/dist/reconcile-engine-6AT6EVGS.js +0 -2
  257. package/dist/records-IOZTZUZV.js +0 -2
  258. package/dist/registry-V45ZQ6Q5.js +0 -2
  259. package/dist/resolve-run-intent-W32G6WM6.js +0 -2
  260. package/dist/revert-NQ7GEVSE.js +0 -2
  261. package/dist/review-cmd-DQRKQUMG.js +0 -4
  262. package/dist/run-26IR3CKX.js +0 -2
  263. package/dist/run-5IYI2TJI.js +0 -2
  264. package/dist/tcg-generate-ONLV5GXG.js +0 -2
  265. package/dist/testmd-actions-NPILETCQ.js +0 -2
  266. package/dist/token-refresh-G2CSTY4B.js +0 -2
  267. package/dist/types-O23GN2YM.js +0 -2
  268. package/dist/verdicts-TDJLJJ3F.js +0 -2
  269. package/dist/walk-session-HB3OOWVR.js +0 -2
  270. package/dist/with-telemetry-HSD6CXDS.js +0 -2
@@ -1,17 +1,17 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as we}from"./chunk-YKTYVJBN.js";import{a as N,b as he,c as ye,d as be,e as Ee,f as _e,m as T}from"./chunk-2DCNCH32.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-NVGBE2DR.js";import{A as j}from"./chunk-TH47OOBV.js";import{w as ge}from"./chunk-OFW3ZVTP.js";var A="https://integrations.lambdatest.com",E=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function ft(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${ge[n].shareApiBaseUrl}/lis/api/v1`}function gt(t){let n=t.env??process.env,e=t.auth?.TESTMUAI_BASIC_AUTH||n.TESTMUAI_BASIC_AUTH;if(e)return{authorization:`Basic ${e}`};let r=t.auth?.TESTMUAI_API_KEY||n.TESTMUAI_API_KEY;return r?{authorization:`Bearer ${r}`}:{}}function k(t){let n=t.split(`
2
+ import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as we}from"./chunk-YKTYVJBN.js";import{a as N,b as he,c as ye,d as be,e as Ee,f as _e,m as T}from"./chunk-54JZ6VEW.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-NVGBE2DR.js";import{C as j}from"./chunk-W3Z7AZNT.js";import{w as ge}from"./chunk-LPH4TERT.js";var A="https://integrations.lambdatest.com",E=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function ft(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${ge[n].shareApiBaseUrl}/lis/api/v1`}function gt(t){let n=t.env??process.env,e=t.auth?.TESTMUAI_BASIC_AUTH||n.TESTMUAI_BASIC_AUTH;if(e)return{authorization:`Basic ${e}`};let r=t.auth?.TESTMUAI_API_KEY||n.TESTMUAI_API_KEY;return r?{authorization:`Bearer ${r}`}:{}}function k(t){let n=t.split(`
3
3
  `,1)[0].replace(/[\u0000-\u001f\u007f-\u009f]/g,"");return n.length>200?`${n.slice(0,200)}\u2026`:n}function ht(t,n,e="the issue"){return t===401||t===403?new E("LIS_AUTH","credentials rejected \u2014 run `kane-cli login` and retry"):t>=500?new E("LIS_UNAVAILABLE",`the integrations service returned an error (HTTP ${t}) \u2014 retry later`):new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${e}: ${k(n)||`HTTP ${t}`}`)}function C(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{throw new E("LIS_UNAVAILABLE","the integrations service returned a malformed response \u2014 retry later")}}function ce(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{return{}}}function Le(t){return ce(t).code}function S(t,n="the issue",e="Atlassian"){let r=ce(t),s=e==="Atlassian"?"Confluence":e;switch(r.code){case"TOKEN_EXPIRED":return new E("LIS_SETUP",`your ${e} connection needs a resync \u2014 reconnect at ${A} and retry`);case"NOT_INSTALLED":return new E("LIS_SETUP",`no ${e} connection for this account \u2014 create one at ${A} and retry`);case"SCOPE_MISSING":return new E("LIS_SETUP",`the connection has no ${s} access \u2014 reconnect with ${s} at ${A} and retry`);case"FORBIDDEN":return new E("LIS_FORBIDDEN",`you don't have access to ${n}`);case"NOT_FOUND":return new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${n}: ${k(r.message??"")||"not found"}`);case"PAYLOAD_TOO_LARGE":return new E("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");case"INVALID_PAYLOAD":return new E("LIS_UNAVAILABLE",`the integrations service rejected the request (${k(r.message??"")||"invalid payload"}) \u2014 retry later`);case"NOT_SUPPORTED":return new E("LIS_UNAVAILABLE","the integrations service does not support this operation yet");case"UPSTREAM_ERROR":case"UPSTREAM_TIMEOUT":return new E("LIS_UNAVAILABLE",`${e} is not responding through the integrations service \u2014 retry later`);default:return ht(t.status,r.message??"",n)}}var yt=3e4,bt=5;async function $(t,n,e){let r=e.env??process.env,s=e.fetchImpl??fetch;for(let o=0;;o++){let l=new AbortController,u=setTimeout(()=>l.abort(),yt);try{let i=await s(`${ft(r)}${t}`,{...n,headers:{"content-type":"application/json",...gt(e),...n.headers??{}},signal:l.signal}),c=await Promise.race([i.arrayBuffer(),new Promise((d,p)=>{l.signal.addEventListener("abort",()=>p(new DOMException("aborted","AbortError")),{once:!0})})]),a={status:i.status,ok:i.ok,headers:i.headers,bytes:Buffer.from(c)};if(a.status===429){if(o>0)throw new E("LIS_RATE_LIMITED","the integrations service is busy \u2014 try again in a moment");let d=ce(a).data?.retry_after_sec,p=Math.min(Math.max(typeof d=="number"&&Number.isFinite(d)?d:1,0),bt);clearTimeout(u),await new Promise(y=>setTimeout(y,p*1e3));continue}return a}catch(i){throw i instanceof E?i:l.signal.aborted?new E("LIS_UNAVAILABLE","the integrations service did not respond within 30 seconds \u2014 retry later"):new E("LIS_UNAVAILABLE",`could not reach the integrations service (${k(i instanceof Error?i.message:String(i))}) \u2014 check your connection and retry`)}finally{clearTimeout(u)}}}function V(t){let n=t.headers.get("content-type")??"application/octet-stream";if(n.includes("json"))try{let e=JSON.parse(t.bytes.toString("utf8")),r=e.content??e.data?.content;if(typeof r=="string")return{bytes:Buffer.from(r,"base64"),mediaType:e.mime_type??e.data?.mime_type??"application/octet-stream"}}catch{}return{bytes:t.bytes,mediaType:n}}async function H(t={}){let n=await $("/jira/info",{method:"GET"},t);if(!n.ok)throw S(n);let e=C(n),r=(e.data?.SELECTED_PROJECTS??[]).map(s=>s?.key).filter(s=>typeof s=="string"&&s.length>0);return{installed:e.data?.INSTALLED==="YES",selectAll:e.data?.SELECT_ALL===!0,selectedProjects:r,capabilities:{document:e.data?.capabilities?.document===!0,comments:e.data?.capabilities?.comments===!0}}}async function z(t,n={}){let e=await $("/jira/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"jira",issueKey:t})},n);if(!e.ok)throw S(e);let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Ie=100,Et=5e3,_t=60;async function X(t,n={}){let e=[],r=new Set,s=null,o=0;for(let l=0;;l++){if(l>=_t)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let u=await $("/jira/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Ie,cursor:s,start_at:o,order_by:"created",fetch_all:!1})},n);if(!u.ok)throw S(u,"the issue's comments");let i=C(u);if(i.type==="error"||!i.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(i.message??"")||"unavailable"}`);for(let w of i.data.comments??[]){let f=String(w.id);r.has(f)||(r.add(f),e.push(w))}let c=i.data.pagination;if(!c?.has_more)return e;if(e.length>=Et)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let a=c.next_cursor??null,d=c.next_start_at!=null,p=d?c.next_start_at:o+Ie;if(!(a!=null&&a!==s||a==null&&d&&p!==o))throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=a,o=p}}async function Z(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok){if(Le(e)===void 0){if(e.status===413)throw new E("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");if(e.status===404)throw new E("JIRA_NOT_CONNECTED",`Jira is not connected for this account \u2014 connect it at ${A} and retry`)}throw S(e,`attachment ${t}`)}return V(e)}var q="kane.source.jira/2";function Ae(t){if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t)){let n=t.map(Ae).filter(e=>e!==null);return n.length===0?null:n.join(", ")}if(t!==null&&typeof t=="object"){let n=t;for(let e of["name","value","displayName"])if(typeof n[e]=="string")return n[e];return null}return null}function ve(t,n,e){let r=[],s={},o=t.additional_fields??{};for(let a of Object.keys(o).sort()){let d=Ae(o[a]);if(d===null){r.push(`field "${a}" has no stable text form \u2014 dropped from the envelope`);continue}s[a]=d}let l=[...t.attachments??[]].map(a=>({id:String(a.id),filename:a.filename??"",media_type:a.mime_type??"application/octet-stream",size:a.size??0})).sort((a,d)=>{let p=Number(a.id),y=Number(d.id);return Number.isFinite(p)&&Number.isFinite(y)?p-y:a.id<d.id?-1:a.id>d.id?1:0}),u=e.map(a=>({id:String(a.id),author:a.author?.display_name??"",body:a.body??"",created:a.created??""})).sort((a,d)=>{if(a.created!==d.created)return a.created<d.created?-1:1;let p=Number(a.id),y=Number(d.id);return Number.isFinite(p)&&Number.isFinite(y)&&p!==y?p-y:a.id<d.id?-1:a.id>d.id?1:0}),i=t.key;if(!/^[A-Za-z][A-Za-z0-9_]*-\d+$/.test(i))throw new Error(`cannot build a stable identity for issue key "${i}" \u2014 expected a PROJECT-NUMBER key`);let c={schema:q,site:n,project:i.slice(0,i.lastIndexOf("-")),issue:{id:t.id,key:i},content:{summary:t.summary??"",description:t.description??"",fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(c),"utf8"),envelope:c,warnings:r}}var Se=64,wt=16,Lt=6e6,It=5e7,At=12e6,vt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},St=new Set(["png","jpeg","webp"]);function $e(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("JIRA_ENVELOPE_SCHEMA: source bytes are not a kane jira envelope")}if(e.schema!==q)throw new Error(`JIRA_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${q}`);let r=[],s=new Map,o=[],l=0,u=new Map,i=[];for(let d=0;d<e.attachments.length;d++){let p=e.attachments[d],y=`i${d+1}`,w=`attachment:${p.filename}`,f=v=>`[img#${y}] ${p.filename} (${p.media_type}, ${p.size} bytes${v?"":" \u2014 not delivered"})`,h=(v,R,x)=>{r.push({ref:y,loc:w,media_type:v,...x?.blob?{blob:x.blob}:{},...x?.appearance?{appearance:x.appearance}:{},delivery:R,...x?.duplicate_of?{duplicate_of:x.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),i.push(f(!1));continue}let _;try{_=await t.fetchAttachment(p.id)}catch{h(p.media_type,"external-image-not-fetched"),i.push(f(!1));continue}let b=_.bytes,g=J(b),m=vt[g.format],I=B(b);if(s.set(I,b),!St.has(g.format)){let v=g.format==="gif"||g.format==="bmp"||g.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(m,v,{blob:I}),i.push(f(!1));continue}if(g.width===void 0||g.height===void 0||g.width*g.height>It){h(m,"undecodable",{blob:I}),i.push(f(!1));continue}let L;if(g.format==="png"||g.format==="jpeg"){let v=F(b,g.format);if(v===null){h(m,"undecodable",{blob:I}),i.push(f(!1));continue}L=M(v.data,{width:v.width,height:v.height,channels:v.channels})}if(g.width<Se||g.height<Se){h(m,"below-dimension-floor",{blob:I,appearance:L}),i.push(f(!1));continue}let O=u.get(I);if(O!==void 0){h(m,"duplicate",{blob:I,appearance:L,duplicate_of:O}),i.push(f(!1));continue}if(b.byteLength>Lt){h(m,"image-too-large",{blob:I,appearance:L}),i.push(f(!1));continue}if(l+b.byteLength>At){h(m,"vision-byte-budget-reached",{blob:I,appearance:L}),i.push(f(!1));continue}if(o.length>=wt){h(m,"image-cap-reached",{blob:I,appearance:L}),i.push(f(!1));continue}u.set(I,y),l+=b.byteLength,o.push(y),h(m,"selected",{blob:I,appearance:L}),i.push(f(!0))}let c=[];c.push(`${e.issue.key} \xB7 ${e.site}/${e.project}`,`Summary: ${e.content.summary}`),e.content.description!==""&&c.push("",...e.content.description.split(`
4
4
  `));let a=Object.keys(e.content.fields);return a.length>0&&c.push("","--- fields ---",...a.map(d=>`${d}: ${e.content.fields[d]}`)),i.length>0&&c.push("","--- attachments ---",...i),e.comments.length>0&&(c.push("","--- comments ---"),e.comments.forEach((d,p)=>{p>0&&c.push(""),c.push(`[${p+1}] ${d.author} \xB7 ${d.created}`,...d.body.split(`
5
5
  `))})),{projection:c.join(`
6
6
  `)+`
7
- `,inventory:r,blobs:s,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var $t=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function Q(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.lastIndexOf("browse");if(r===-1||r+1>=e.length)return null;let s=e[r+1];return $t.test(s)?{site:n.hostname,issueKey:s.toUpperCase()}:null}function ee(t,n){let e=j(t),r=e.heads.get(n);return r==null?null:Ce(t,e,r)}function te(t,n){let r=ee(t,n)?.site;return typeof r=="string"&&r.length>0?r:null}function ke(t,n,e,r){let s=j(t);for(let[o,l]of s.heads){if(l==null||s.mediaOf(l).format!==n)continue;let u=Ce(t,s,l);if(u===null)continue;let i=u;for(let c of e){if(i===null||typeof i!="object"){i=void 0;break}i=i[c]}if(i===r)return o}return null}function Ce(t,n,e){let r=n.getNode(e)?.content?.blob;if(typeof r!="string")return null;let s=W(t,r);if(s===null)return null;try{let o=JSON.parse(s.toString("utf8"));return o!==null&&typeof o=="object"?o:null}catch{return null}}var Re={jira:"a jira issue source",confluence:"a confluence page source",linear:"a linear issue source","linear-doc":"a linear document source",web:"a web page source"};function P(t,n,e){let r=j(t),s=r.heads.get(n);if(s==null)return null;let o=r.mediaOf(s).format;if(o===e)return null;let l=Re[o]??`${o} content`;return`source '${n}' is already backed by ${l}, not ${Re[e]??e} \u2014 retire it first (kane-cli context retire ${n}) or ingest under a different id with --as`}async function Rt(t,n,e,r,s){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Jira issue URL (https://<site>/browse/KEY-123)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X};try{let i={auth:await(s?.authEnv??(await import("./auth-TW24FZQF.js")).resolveLisAuthEnv)(),env:process.env},c=await l.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issue comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(a))return(e.err??e.out)(`error: ${t}: project ${a} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${A}`),{code:1};let d=await l.jiraIssue(o.issueKey,i),p=await l.jiraComments(o.issueKey,i),y=o.site;if(d.host)try{y=new URL(d.host).hostname}catch{y=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:f}=ve(d,y,p),h=n??o.issueKey.toLowerCase();N(h);let _=P(r,h,"jira");if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=te(r,h);if(b!==null&&b!==y)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${b}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let g=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:m=>l.jiraAttachment(m,i)})}});e.out(U(e.isTTY,g,o.issueKey));for(let m of f)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: jira, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${kt(u instanceof Error?u.message:String(u))}`),{code:1})}}function kt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the issue's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the description or attachments in Jira and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the issue's text is too large to ingest \u2014 trim the description in Jira and retry":t}var Oe={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>Q(t)!==null,ingest:Rt,sourceIdFor:t=>{let n=Q(t);return n?n.issueKey.toLowerCase():null}};async function Ne(t,n={}){let e=await $("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the page");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${k(r.message??"")||"page not found or not accessible"}`);return r.data}async function Te(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw S(e,"the page's attachment");return{bytes:V(e).bytes}}var ne="kane.source.confluence/1";function Pe(t,n){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this page \u2014 the integrations service returned no page id");let e=[...t.labels??[]].filter(o=>typeof o=="string").sort(),r=[...t.attachments??[]].map(o=>({id:String(o.id),filename:o.filename??"",media_type:o.mime_type??"application/octet-stream",size:o.size??0})).sort((o,l)=>o.id<l.id?-1:o.id>l.id?1:0),s={schema:ne,site:n,page:{id:t.id},space:{key:t.space?.key??""},title:t.title??"",labels:e,content:{body:t.body??""},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ue=64,Ct=16,Ot=6e6,Nt=5e7,Tt=12e6,Pt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Ut=new Set(["png","jpeg","webp"]);function xe(t){let n=new Map(Object.entries(t.downloads));return async e=>{let r;try{r=JSON.parse(e.toString("utf8"))}catch{throw new Error("CONFLUENCE_ENVELOPE_SCHEMA: source bytes are not a kane confluence envelope")}if(r.schema!==ne)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${ne}`);let s=[],o=new Map,l=[],u=0,i=new Map,c=[];for(let d=0;d<r.attachments.length;d++){let p=r.attachments[d],y=`i${d+1}`,w=`attachment:${p.filename}`,f=R=>`[img#${y}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:y,loc:w,media_type:R,...D?.blob?{blob:D.blob}:{},...D?.appearance?{appearance:D.appearance}:{},delivery:x,...D?.duplicate_of?{duplicate_of:D.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),c.push(f(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let b;try{b=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let g=b.bytes,m=J(g),I=Pt[m.format],L=B(g);if(o.set(L,g),!Ut.has(m.format)){let R=m.format==="gif"||m.format==="bmp"||m.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(f(!1));continue}if(m.width===void 0||m.height===void 0||m.width*m.height>Nt){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}let O;if(m.format==="png"||m.format==="jpeg"){let R=F(g,m.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(m.width<Ue||m.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(f(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(f(!1));continue}if(g.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(f(!1));continue}if(u+g.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(f(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(f(!1));continue}i.set(L,y),u+=g.byteLength,l.push(y),h(I,"selected",{blob:L,appearance:O}),c.push(f(!0))}let a=[];return a.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&a.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&a.push("",...r.content.body.split(`
7
+ `,inventory:r,blobs:s,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var $t=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function Q(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.lastIndexOf("browse");if(r===-1||r+1>=e.length)return null;let s=e[r+1];return $t.test(s)?{site:n.hostname,issueKey:s.toUpperCase()}:null}function ee(t,n){let e=j(t),r=e.heads.get(n);return r==null?null:Ce(t,e,r)}function te(t,n){let r=ee(t,n)?.site;return typeof r=="string"&&r.length>0?r:null}function ke(t,n,e,r){let s=j(t);for(let[o,l]of s.heads){if(l==null||s.mediaOf(l).format!==n)continue;let u=Ce(t,s,l);if(u===null)continue;let i=u;for(let c of e){if(i===null||typeof i!="object"){i=void 0;break}i=i[c]}if(i===r)return o}return null}function Ce(t,n,e){let r=n.getNode(e)?.content?.blob;if(typeof r!="string")return null;let s=W(t,r);if(s===null)return null;try{let o=JSON.parse(s.toString("utf8"));return o!==null&&typeof o=="object"?o:null}catch{return null}}var Re={jira:"a jira issue source",confluence:"a confluence page source",linear:"a linear issue source","linear-doc":"a linear document source",web:"a web page source"};function P(t,n,e){let r=j(t),s=r.heads.get(n);if(s==null)return null;let o=r.mediaOf(s).format;if(o===e)return null;let l=Re[o]??`${o} content`;return`source '${n}' is already backed by ${l}, not ${Re[e]??e} \u2014 retire it first (kane-cli context retire ${n}) or ingest under a different id with --as`}async function Rt(t,n,e,r,s){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Jira issue URL (https://<site>/browse/KEY-123)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X};try{let i={auth:await(s?.authEnv??(await import("./auth-EVXJVU72.js")).resolveLisAuthEnv)(),env:process.env},c=await l.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issue comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(a))return(e.err??e.out)(`error: ${t}: project ${a} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${A}`),{code:1};let d=await l.jiraIssue(o.issueKey,i),p=await l.jiraComments(o.issueKey,i),y=o.site;if(d.host)try{y=new URL(d.host).hostname}catch{y=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:f}=ve(d,y,p),h=n??o.issueKey.toLowerCase();N(h);let _=P(r,h,"jira");if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=te(r,h);if(b!==null&&b!==y)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${b}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let g=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:m=>l.jiraAttachment(m,i)})}});e.out(U(e.isTTY,g,o.issueKey));for(let m of f)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: jira, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${kt(u instanceof Error?u.message:String(u))}`),{code:1})}}function kt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the issue's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the description or attachments in Jira and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the issue's text is too large to ingest \u2014 trim the description in Jira and retry":t}var Oe={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>Q(t)!==null,ingest:Rt,sourceIdFor:t=>{let n=Q(t);return n?n.issueKey.toLowerCase():null}};async function Ne(t,n={}){let e=await $("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the page");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${k(r.message??"")||"page not found or not accessible"}`);return r.data}async function Te(t,n={}){let e=await $("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw S(e,"the page's attachment");return{bytes:V(e).bytes}}var ne="kane.source.confluence/1";function Pe(t,n){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this page \u2014 the integrations service returned no page id");let e=[...t.labels??[]].filter(o=>typeof o=="string").sort(),r=[...t.attachments??[]].map(o=>({id:String(o.id),filename:o.filename??"",media_type:o.mime_type??"application/octet-stream",size:o.size??0})).sort((o,l)=>o.id<l.id?-1:o.id>l.id?1:0),s={schema:ne,site:n,page:{id:t.id},space:{key:t.space?.key??""},title:t.title??"",labels:e,content:{body:t.body??""},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ue=64,Ct=16,Ot=6e6,Nt=5e7,Tt=12e6,Pt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Ut=new Set(["png","jpeg","webp"]);function xe(t){let n=new Map(Object.entries(t.downloads));return async e=>{let r;try{r=JSON.parse(e.toString("utf8"))}catch{throw new Error("CONFLUENCE_ENVELOPE_SCHEMA: source bytes are not a kane confluence envelope")}if(r.schema!==ne)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${ne}`);let s=[],o=new Map,l=[],u=0,i=new Map,c=[];for(let d=0;d<r.attachments.length;d++){let p=r.attachments[d],y=`i${d+1}`,w=`attachment:${p.filename}`,f=R=>`[img#${y}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:y,loc:w,media_type:R,...D?.blob?{blob:D.blob}:{},...D?.appearance?{appearance:D.appearance}:{},delivery:x,...D?.duplicate_of?{duplicate_of:D.duplicate_of}:{}})};if(!p.media_type.startsWith("image/")){h(p.media_type,"unsupported-vision-media-type"),c.push(f(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let b;try{b=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(f(!1));continue}let g=b.bytes,m=J(g),I=Pt[m.format],L=B(g);if(o.set(L,g),!Ut.has(m.format)){let R=m.format==="gif"||m.format==="bmp"||m.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(f(!1));continue}if(m.width===void 0||m.height===void 0||m.width*m.height>Nt){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}let O;if(m.format==="png"||m.format==="jpeg"){let R=F(g,m.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(f(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(m.width<Ue||m.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(f(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(f(!1));continue}if(g.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(f(!1));continue}if(u+g.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(f(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(f(!1));continue}i.set(L,y),u+=g.byteLength,l.push(y),h(I,"selected",{blob:L,appearance:O}),c.push(f(!0))}let a=[];return a.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&a.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&a.push("",...r.content.body.split(`
8
8
  `)),c.length>0&&a.push("","--- attachments ---",...c),{projection:a.join(`
9
9
  `)+`
10
- `,inventory:s,blobs:o,delivered:l,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var xt=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function re(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.indexOf("wiki");if(r===-1||e[r+1]!=="spaces"||e[r+3]!=="pages")return null;let s=e[r+2],o=e[r+4];return s===void 0||o===void 0||!xt.test(s)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:s,pageId:o}}async function Dt(t,n,e,r,s){let o=re(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Confluence page URL (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X},u=s?.confluence??{confluenceDocument:Ne,confluenceAttachment:Te};try{let c={auth:await(s?.authEnv??(await import("./auth-TW24FZQF.js")).resolveLisAuthEnv)(),env:process.env},a=await l.jiraInfo(c);if(!a.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(a.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${A} and retry`),{code:1};let d=await u.confluenceDocument(o.pageId,c),p=o.site;if(d.url)try{p=new URL(d.url).hostname}catch{}let{bytes:y,warnings:w}=Pe(d,p),f=n??`page-${o.pageId}`;N(f);let h=P(r,f,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,f);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${f}) or ingest under a different id with --as`),{code:1};let b=Object.fromEntries((d.attachments??[]).filter(m=>typeof m.download=="string"&&m.download.length>0).map(m=>[String(m.id),m.download])),g=await T({contextDir:r,bytes:y,media:ye,sourceId:f,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:b,fetchAttachment:m=>u.confluenceAttachment(m.download,c)})}});e.out(U(e.isTTY,g,`${o.spaceKey}/${o.pageId}`));for(let m of w)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: confluence, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(i){return i instanceof E?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${jt(i instanceof Error?i.message:String(i))}`),{code:1})}}function jt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the page in Confluence and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page's text is too large to ingest \u2014 trim the page in Confluence and retry":t}var De={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>re(t)!==null,ingest:Dt,sourceIdFor:t=>{let n=re(t);return n?`page-${n.pageId}`:null}};async function je(t={}){let n=await $("/linear-app/info",{method:"GET"},t);if(!n.ok)throw S(n,"the connection","Linear");let e=C(n);return{installed:e.data?.INSTALLED==="YES",capabilities:{issue:e.data?.capabilities?.issue===!0,comments:e.data?.capabilities?.comments===!0,document:e.data?.capabilities?.document===!0}}}async function Be(t,n={}){let e=await $("/linear-app/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"linear-app",issueKey:t})},n);if(!e.ok)throw S(e,"the issue","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Bt=100,Mt=5e3,Jt=60;async function Me(t,n={}){let e=[],r=new Set,s=null;for(let o=0;;o++){if(o>=Jt)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let l=await $("/linear-app/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Bt,...s===null?{}:{cursor:s},fetch_all:!1})},n);if(!l.ok)throw S(l,"the issue's comments","Linear");let u=C(l);if(u.type==="error"||!u.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(u.message??"")||"unavailable"}`);if(u.data.partial)throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 retry later");for(let a of u.data.comments??[]){if(typeof a.id!="string"||a.id==="")throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 a comment row has no comment id");r.has(a.id)||(r.add(a.id),e.push(a))}let i=u.data.pagination;if(!i?.has_more)return e;if(e.length>=Mt)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let c=i.next_cursor??null;if(c==null||c===s)throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=c}}async function Je(t,n={}){let e=await $("/linear-app/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the document","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the document: ${k(r.message??"")||"document not found or not accessible"}`);return r.data}async function Fe(t,n={}){let e=await $("/linear-app/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok)throw S(e,"the attachment","Linear");return{bytes:V(e).bytes}}var oe="kane.source.linear/1",ie="kane.source.linear-doc/1",Ft=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g;function G(t){return t.replace(Ft,n=>{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)})}function Ve(t,n){return t.id<n.id?-1:t.id>n.id?1:0}function Vt(t,n){return Ve(t,n)||(t.filename<n.filename?-1:t.filename>n.filename?1:0)||(t.url<n.url?-1:t.url>n.url?1:0)}function Ge(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this issue \u2014 the integrations service returned no issue id");let r=t.key;if(!/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(r)){let c=String(r).replace(/[\u0000-\u001f\u007f-\u009f]/g,"").slice(0,80);throw new Error(`cannot build a stable identity for issue key "${c}" \u2014 expected a TEAM-NUMBER key`)}let s={},o=[...t.labels??[]].filter(c=>typeof c=="string").sort();o.length>0&&(s.labels=o.join(", ")),typeof t.priority=="string"&&t.priority!==""&&(s.priority=t.priority),typeof t.project=="string"&&t.project!==""&&(s.project=t.project),typeof t.status=="string"&&t.status!==""&&(s.status=t.status);let l=(t.attachments??[]).map(c=>({id:c.id!=null&&String(c.id)!==""?String(c.id):G(c.download??""),filename:c.filename??"",url:G(c.download??"")})).sort(Vt),u=n.map(c=>({id:String(c.id),author:c.author?.display_name??"",body:G(c.body??""),created:c.created??""})).sort((c,a)=>c.created!==a.created?c.created<a.created?-1:1:Ve(c,a)),i={schema:oe,site:e,team:r.slice(0,r.lastIndexOf("-")),issue:{uuid:t.id,key:r},content:{title:t.summary??"",description:G(t.description??""),fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(i),"utf8"),envelope:i,warnings:[]}}function Ye(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this document \u2014 the integrations service returned no document id");let r=(t.attachments??[]).map(o=>({url:G(o.download??String(o.id??"")),filename:o.filename??""})).sort((o,l)=>o.url<l.url?-1:o.url>l.url?1:0),s={schema:ie,site:n,document:{uuid:t.id,slug_id:e},project:{id:t.space?.key??""},title:t.title??"",content:{body:G(t.body??"")},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ke=64,Gt=16,Yt=6e6,Kt=5e7,Wt=12e6,se=64,We="https://uploads.linear.app/",Ht=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g,zt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Xt=new Set(["png","jpeg","webp"]);async function He(t,n){let e=[],r=new Map,s=[],o=0,l=new Map,u=[];for(let i=0;i<t.length;i++){let c=t[i],a=`i${i+1}`,d=m=>`[img#${a}] ${c.label}${m?"":" \u2014 not delivered"}`,p=(m,I,L)=>{e.push({ref:a,loc:c.loc,media_type:m,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},y;try{y=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=y.bytes,f=J(w),h=zt[f.format],_=B(w);if(r.set(_,w),!Xt.has(f.format)){let m=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,m,{blob:_}),u.push(d(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let b;if(f.format==="png"||f.format==="jpeg"){let m=F(w,f.format);if(m===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}b=M(m.data,{width:m.width,height:m.height,channels:m.channels})}if(f.width<Ke||f.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:b}),u.push(d(!1));continue}let g=l.get(_);if(g!==void 0){p(h,"duplicate",{blob:_,appearance:b,duplicate_of:g}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:b}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:b}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:b}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:b}),u.push(d(!0))}return{inventory:e,blobs:r,delivered:s,lines:u}}function Zt(t){let n=new Set,e=[];for(let r of t.match(Ht)??[])n.has(r)||(n.add(r),e.push(r));return e}function ze(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_ENVELOPE_SCHEMA: source bytes are not a kane linear envelope")}if(e.schema!==oe)throw new Error(`LINEAR_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${oe}`);let r=[],s=new Set;for(let a of Zt(e.content.description))s.add(a),r.push({url:a,label:a,loc:`body:${a}`});let o=[];for(let a of e.attachments)if(a.url.startsWith(We)){if(s.has(a.url)){if(a.filename!==""){let d=r.find(p=>p.url===a.url);d!==void 0&&d.label===d.url&&(d.label=a.filename)}continue}s.add(a.url),r.push({url:a.url,label:a.filename||a.url,loc:`attachment:${a.filename||a.url}`})}else a.url!==""&&o.push(`[${o.length+1}] ${a.filename||a.url} \u2014 ${a.url}`);let l=Math.max(0,r.length-se),u=await He(r.slice(0,se),t.fetchAttachment);l>0&&u.lines.push(`${l} more upload links not examined`);let i=[];i.push(`${e.issue.key} \xB7 ${e.site}`,`Title: ${e.content.title}`),e.content.description!==""&&i.push("",...e.content.description.split(`
10
+ `,inventory:s,blobs:o,delivered:l,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var xt=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function re(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}let e=n.pathname.split("/").filter(Boolean),r=e.indexOf("wiki");if(r===-1||e[r+1]!=="spaces"||e[r+3]!=="pages")return null;let s=e[r+2],o=e[r+4];return s===void 0||o===void 0||!xt.test(s)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:s,pageId:o}}async function Dt(t,n,e,r,s){let o=re(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Confluence page URL (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)`),{code:1};let l=s?.lis??{jiraInfo:H,jiraIssue:z,jiraAttachment:Z,jiraComments:X},u=s?.confluence??{confluenceDocument:Ne,confluenceAttachment:Te};try{let c={auth:await(s?.authEnv??(await import("./auth-EVXJVU72.js")).resolveLisAuthEnv)(),env:process.env},a=await l.jiraInfo(c);if(!a.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${A} and retry`),{code:1};if(a.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${A} and retry`),{code:1};let d=await u.confluenceDocument(o.pageId,c),p=o.site;if(d.url)try{p=new URL(d.url).hostname}catch{}let{bytes:y,warnings:w}=Pe(d,p),f=n??`page-${o.pageId}`;N(f);let h=P(r,f,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,f);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${f}) or ingest under a different id with --as`),{code:1};let b=Object.fromEntries((d.attachments??[]).filter(m=>typeof m.download=="string"&&m.download.length>0).map(m=>[String(m.id),m.download])),g=await T({contextDir:r,bytes:y,media:ye,sourceId:f,label:t,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:b,fetchAttachment:m=>u.confluenceAttachment(m.download,c)})}});e.out(U(e.isTTY,g,`${o.spaceKey}/${o.pageId}`));for(let m of w)e.out(`warning: ${m}`);for(let m of g.warnings??[])e.out(`warning: ${m}`);if(g.composite){let m=g.composite.delivered+g.composite.omitted;e.out(`${g.source_id}: confluence, ${m} attachments, ${g.composite.delivered} images delivered (${g.composite.omitted} omitted)`)}return{code:0,result:{status:g.status,source_id:g.source_id,source_cid:g.cid}}}catch(i){return i instanceof E?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${jt(i instanceof Error?i.message:String(i))}`),{code:1})}}function jt(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page's content is too large to ingest (${n[1]}; the limit is ${n[2]}) \u2014 trim the page in Confluence and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page's text is too large to ingest \u2014 trim the page in Confluence and retry":t}var De={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>re(t)!==null,ingest:Dt,sourceIdFor:t=>{let n=re(t);return n?`page-${n.pageId}`:null}};async function je(t={}){let n=await $("/linear-app/info",{method:"GET"},t);if(!n.ok)throw S(n,"the connection","Linear");let e=C(n);return{installed:e.data?.INSTALLED==="YES",capabilities:{issue:e.data?.capabilities?.issue===!0,comments:e.data?.capabilities?.comments===!0,document:e.data?.capabilities?.document===!0}}}async function Be(t,n={}){let e=await $("/linear-app/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"linear-app",issueKey:t})},n);if(!e.ok)throw S(e,"the issue","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${k(r.message??"")||"issue not found or not accessible"}`);return r.data}var Bt=100,Mt=5e3,Jt=60;async function Me(t,n={}){let e=[],r=new Set,s=null;for(let o=0;;o++){if(o>=Jt)throw new E("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let l=await $("/linear-app/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:Bt,...s===null?{}:{cursor:s},fetch_all:!1})},n);if(!l.ok)throw S(l,"the issue's comments","Linear");let u=C(l);if(u.type==="error"||!u.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${k(u.message??"")||"unavailable"}`);if(u.data.partial)throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 retry later");for(let a of u.data.comments??[]){if(typeof a.id!="string"||a.id==="")throw new E("JIRA_ISSUE_UNAVAILABLE","the integrations service returned an incomplete comment set \u2014 a comment row has no comment id");r.has(a.id)||(r.add(a.id),e.push(a))}let i=u.data.pagination;if(!i?.has_more)return e;if(e.length>=Mt)throw new E("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let c=i.next_cursor??null;if(c==null||c===s)throw new E("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");s=c}}async function Je(t,n={}){let e=await $("/linear-app/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw S(e,"the document","Linear");let r=C(e);if(r.type==="error"||!r.data)throw new E("JIRA_ISSUE_UNAVAILABLE",`could not fetch the document: ${k(r.message??"")||"document not found or not accessible"}`);return r.data}async function Fe(t,n={}){let e=await $("/linear-app/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok)throw S(e,"the attachment","Linear");return{bytes:V(e).bytes}}var oe="kane.source.linear/1",ie="kane.source.linear-doc/1",Ft=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g;function G(t){return t.replace(Ft,n=>{let e=n.indexOf("?");return e===-1?n:n.slice(0,e)})}function Ve(t,n){return t.id<n.id?-1:t.id>n.id?1:0}function Vt(t,n){return Ve(t,n)||(t.filename<n.filename?-1:t.filename>n.filename?1:0)||(t.url<n.url?-1:t.url>n.url?1:0)}function Ge(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this issue \u2014 the integrations service returned no issue id");let r=t.key;if(!/^[A-Za-z][A-Za-z0-9]*-\d+$/.test(r)){let c=String(r).replace(/[\u0000-\u001f\u007f-\u009f]/g,"").slice(0,80);throw new Error(`cannot build a stable identity for issue key "${c}" \u2014 expected a TEAM-NUMBER key`)}let s={},o=[...t.labels??[]].filter(c=>typeof c=="string").sort();o.length>0&&(s.labels=o.join(", ")),typeof t.priority=="string"&&t.priority!==""&&(s.priority=t.priority),typeof t.project=="string"&&t.project!==""&&(s.project=t.project),typeof t.status=="string"&&t.status!==""&&(s.status=t.status);let l=(t.attachments??[]).map(c=>({id:c.id!=null&&String(c.id)!==""?String(c.id):G(c.download??""),filename:c.filename??"",url:G(c.download??"")})).sort(Vt),u=n.map(c=>({id:String(c.id),author:c.author?.display_name??"",body:G(c.body??""),created:c.created??""})).sort((c,a)=>c.created!==a.created?c.created<a.created?-1:1:Ve(c,a)),i={schema:oe,site:e,team:r.slice(0,r.lastIndexOf("-")),issue:{uuid:t.id,key:r},content:{title:t.summary??"",description:G(t.description??""),fields:s},attachments:l,comments:u};return{bytes:Buffer.from(JSON.stringify(i),"utf8"),envelope:i,warnings:[]}}function Ye(t,n,e){if(typeof t.id!="string"||t.id==="")throw new Error("cannot build a stable identity for this document \u2014 the integrations service returned no document id");let r=(t.attachments??[]).map(o=>({url:G(o.download??String(o.id??"")),filename:o.filename??""})).sort((o,l)=>o.url<l.url?-1:o.url>l.url?1:0),s={schema:ie,site:n,document:{uuid:t.id,slug_id:e},project:{id:t.space?.key??""},title:t.title??"",content:{body:G(t.body??"")},attachments:r};return{bytes:Buffer.from(JSON.stringify(s),"utf8"),envelope:s,warnings:[]}}var Ke=64,Gt=16,Yt=6e6,Kt=5e7,Wt=12e6,se=64,We="https://uploads.linear.app/",Ht=/https:\/\/uploads\.linear\.app\/[^\s)"'`]+/g,zt={png:"image/png",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp",tiff:"image/tiff",emf:"image/emf",wmf:"image/wmf",unknown:"application/octet-stream"},Xt=new Set(["png","jpeg","webp"]);async function He(t,n){let e=[],r=new Map,s=[],o=0,l=new Map,u=[];for(let i=0;i<t.length;i++){let c=t[i],a=`i${i+1}`,d=m=>`[img#${a}] ${c.label}${m?"":" \u2014 not delivered"}`,p=(m,I,L)=>{e.push({ref:a,loc:c.loc,media_type:m,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},y;try{y=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=y.bytes,f=J(w),h=zt[f.format],_=B(w);if(r.set(_,w),!Xt.has(f.format)){let m=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,m,{blob:_}),u.push(d(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let b;if(f.format==="png"||f.format==="jpeg"){let m=F(w,f.format);if(m===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}b=M(m.data,{width:m.width,height:m.height,channels:m.channels})}if(f.width<Ke||f.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:b}),u.push(d(!1));continue}let g=l.get(_);if(g!==void 0){p(h,"duplicate",{blob:_,appearance:b,duplicate_of:g}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:b}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:b}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:b}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:b}),u.push(d(!0))}return{inventory:e,blobs:r,delivered:s,lines:u}}function Zt(t){let n=new Set,e=[];for(let r of t.match(Ht)??[])n.has(r)||(n.add(r),e.push(r));return e}function ze(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_ENVELOPE_SCHEMA: source bytes are not a kane linear envelope")}if(e.schema!==oe)throw new Error(`LINEAR_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${oe}`);let r=[],s=new Set;for(let a of Zt(e.content.description))s.add(a),r.push({url:a,label:a,loc:`body:${a}`});let o=[];for(let a of e.attachments)if(a.url.startsWith(We)){if(s.has(a.url)){if(a.filename!==""){let d=r.find(p=>p.url===a.url);d!==void 0&&d.label===d.url&&(d.label=a.filename)}continue}s.add(a.url),r.push({url:a.url,label:a.filename||a.url,loc:`attachment:${a.filename||a.url}`})}else a.url!==""&&o.push(`[${o.length+1}] ${a.filename||a.url} \u2014 ${a.url}`);let l=Math.max(0,r.length-se),u=await He(r.slice(0,se),t.fetchAttachment);l>0&&u.lines.push(`${l} more upload links not examined`);let i=[];i.push(`${e.issue.key} \xB7 ${e.site}`,`Title: ${e.content.title}`),e.content.description!==""&&i.push("",...e.content.description.split(`
11
11
  `));let c=Object.keys(e.content.fields);return c.length>0&&i.push("","--- fields ---",...c.map(a=>`${a}: ${e.content.fields[a]}`)),u.lines.length>0&&i.push("","--- images ---",...u.lines),o.length>0&&i.push("","--- links ---",...o),e.comments.length>0&&(i.push("","--- comments ---"),e.comments.forEach((a,d)=>{d>0&&i.push(""),i.push(`[${d+1}] ${a.author} \xB7 ${a.created}`,...a.body.split(`
12
12
  `))})),{projection:i.join(`
13
13
  `)+`
14
14
  `,inventory:u.inventory,blobs:u.blobs,delivered:u.delivered,converter:{name:"linear-convert",version:"1",policy:"v1"}}}}function Xe(t){return async n=>{let e;try{e=JSON.parse(n.toString("utf8"))}catch{throw new Error("LINEAR_DOC_ENVELOPE_SCHEMA: source bytes are not a kane linear document envelope")}if(e.schema!==ie)throw new Error(`LINEAR_DOC_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${ie}`);let r=new Set,s=[];for(let i of e.attachments)!i.url.startsWith(We)||r.has(i.url)||(r.add(i.url),s.push({url:i.url,label:i.filename||i.url,loc:`body:${i.url}`}));let o=Math.max(0,s.length-se),l=await He(s.slice(0,se),t.fetchAttachment);o>0&&l.lines.push(`${o} more upload links not examined`);let u=[];return u.push(`${e.title} \xB7 ${e.site}`),e.content.body!==""&&u.push("",...e.content.body.split(`
15
15
  `)),l.lines.length>0&&u.push("","--- images ---",...l.lines),{projection:u.join(`
16
16
  `)+`
17
- `,inventory:l.inventory,blobs:l.blobs,delivered:l.delivered,converter:{name:"linear-doc-convert",version:"1",policy:"v1"}}}}var qt=/^[A-Za-z][A-Za-z0-9]*-\d+$/,Qt=/-([0-9a-f]{12})$/;function ue(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname.toLowerCase()!=="linear.app"?null:n.pathname.split("/").filter(Boolean)}function Ze(t){let n=ue(t);return n===null||n.length<3?null:{workspace:n[0],segs:n}}function Y(t){let n=Ze(t);if(n===null||n.segs[1]!=="issue")return null;let e=n.segs[2];return qt.test(e)?{workspace:n.workspace,key:e}:null}function K(t){let n=Ze(t);if(n===null||n.segs[1]!=="document")return null;let e=n.segs[2].match(Qt);return e===null?null:{workspace:n.workspace,slugId:e[1]}}var en=new Set(["project","team","view","initiative","cycle","roadmap","inbox","triage","my-issues"]),qe=new Set(["docs","features","method","blog","customers","pricing","integrations","developers","changelog","about","careers","security","download","contact","now","switch","homepage"]);function le(t){let n=ue(t);return n===null||n.length<2||!en.has(n[1])||qe.has(n[0].toLowerCase())?null:{workspace:n[0],section:n[1]}}function de(t){let n=ue(t);return n===null||n.length<2||n[1]!=="issue"&&n[1]!=="document"||qe.has(n[0].toLowerCase())||Y(t)!==null||K(t)!==null?null:{workspace:n[0],section:n[1]}}function Qe(t){let n=Y(t);return n?n.key.toLowerCase():null}function et(t){let n=K(t);return n?`doc-${n.slugId}`:null}var tt={linearInfo:je,linearIssue:Be,linearComments:Me,linearDocument:Je,linearAttachment:Fe};function nt(t,n){if(t)try{let e=new URL(t).pathname.split("/").filter(Boolean)[0];if(e)return`linear.app/${e.toLowerCase()}`}catch{}return`linear.app/${n.toLowerCase()}`}function rt(t,n,e,r,s,o){let l=ee(t,r);if(l!==null&&typeof l.schema=="string"&&l.schema.startsWith(`kane.source.${n}/`)){let i=l;for(let c of e)i=i!==null&&typeof i=="object"?i[c]:void 0;if(typeof i=="string"&&i!==""&&i!==s)return`source '${r}' was ingested from a different ${o} that used this key \u2014 the key was recycled; retire it first (kane-cli context retire ${r}) or ingest under a different id with --as`}let u=ke(t,n,e,s);return u!==null&&u!==r?`this ${o} is already ingested as '${u}' (its key changed) \u2014 reconcile that source, or retire it to re-ingest under the new key`:null}function ot(t,n,e,r){let s=ee(t,e);if(s===null||typeof s.schema!="string"||!s.schema.startsWith(`kane.source.${n}/`))return null;let o=s.site;return typeof o!="string"||o.length===0||o===r?null:`source '${e}' was ingested from ${o}, but this read serves ${r} \u2014 retire it first (kane-cli context retire ${e}) or ingest under a different id with --as`}async function tn(t,n,e,r,s){let o=Y(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear issue URL (https://linear.app/<workspace>/issue/KEY-123)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-TW24FZQF.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.issue===!1||c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issues or their comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearIssue(o.key,i),d=await l.linearComments(o.key,i),p=nt(a.host,o.workspace),{bytes:y,envelope:w,warnings:f}=Ge(a,d,p),h=n??o.key.toLowerCase();N(h);let _=rt(r,"linear",["issue","uuid"],h,w.issue.uuid,"issue")??P(r,h,"linear")??ot(r,"linear",h,p);if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=await T({contextDir:r,bytes:y,media:Ee,sourceId:h,label:t,confirmSameSource:e.isTTY?g=>e.confirm(`identical content already ingested as ${g} \u2014 treat as the same source?`):void 0,converters:{linear:ze({fetchAttachment:g=>l.linearAttachment(g,i)})}});e.out(U(e.isTTY,b,w.issue.key));for(let g of f)e.out(`warning: ${g}`);for(let g of b.warnings??[])e.out(`warning: ${g}`);if(b.composite){let g=b.composite.delivered+b.composite.omitted;e.out(`${b.source_id}: linear, ${g} images, ${b.composite.delivered} delivered (${b.composite.omitted} omitted)`)}return{code:0,result:{status:b.status,source_id:b.source_id,source_cid:b.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"issue","Linear")}`),{code:1})}}async function nn(t,n,e,r,s){let o=K(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear document URL (https://linear.app/<workspace>/document/<slug>)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-TW24FZQF.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read documents yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearDocument(o.slugId,i),d=nt(a.url,o.workspace),{bytes:p,envelope:y,warnings:w}=Ye(a,d,o.slugId),f=n??`doc-${o.slugId}`;N(f);let h=rt(r,"linear-doc",["document","uuid"],f,y.document.uuid,"document")??P(r,f,"linear-doc")??ot(r,"linear-doc",f,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:f,label:t,confirmSameSource:e.isTTY?b=>e.confirm(`identical content already ingested as ${b} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:b=>l.linearAttachment(b,i)})}});e.out(U(e.isTTY,_,y.title||`document ${o.slugId}`));for(let b of w)e.out(`warning: ${b}`);for(let b of _.warnings??[])e.out(`warning: ${b}`);if(_.composite){let b=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${b} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"document","Linear")}`),{code:1})}}function it(t,n,e){let r=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return r?`the ${n}'s content is too large to ingest (${r[1]}; the limit is ${r[2]}) \u2014 trim the ${n} in ${e} and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?`the ${n}'s text is too large to ingest \u2014 trim the ${n} in ${e} and retry`:t}var st={name:"linear",hint:"Linear issue URLs (https://linear.app/<workspace>/issue/KEY-123)",match:t=>Y(t)!==null,ingest:tn,sourceIdFor:Qe},at={name:"linear-doc",hint:"Linear document URLs (https://linear.app/<workspace>/document/<slug>)",match:t=>K(t)!==null,ingest:nn,sourceIdFor:et},ct={name:"linear-page",hint:"Linear issue or document URLs (other linear.app pages are not ingestable)",match:t=>le(t)!==null||de(t)!==null,ingest:async(t,n,e)=>{let r=le(t);if(r===null){let s=de(t);return s!==null?((e.err??e.out)(`error: ${t}: this Linear ${s.section} link is incomplete or malformed \u2014 use the full form (https://linear.app/${s.workspace}/issue/KEY-123 or https://linear.app/${s.workspace}/document/<slug>-<id>)`),{code:1}):((e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear workspace page`),{code:1})}return(e.err??e.out)(`error: ${t}: this Linear page can't be ingested \u2014 only issue and document URLs are supported; ingest the project's issues or documents individually (https://linear.app/${r.workspace}/issue/KEY-123)`),{code:1}},sourceIdFor:()=>null};var rn=new Set(["invalid_url","target_disallowed","page_not_found","page_access_blocked","page_paywalled","unsupported_content_type","page_too_large","page_timeout","scrape_unavailable","scrape_rate_limited","internal_error","credit_denied"]);async function ut(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,s=we(e),o={"Content-Type":"application/json"},l=await n.authEnv(),u=l.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=l.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;u?o.Authorization=`Basic ${u}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${s}/assurance/web/scrape`,{method:"POST",headers:o,body:JSON.stringify({url:t}),signal:AbortSignal.timeout(n.timeoutMs??55e3)})}catch{return{ok:!1,kind:"transport_unreachable"}}if(c.status===401)return{ok:!1,kind:"auth_rejected"};let a;try{a=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let p=a.page;return p===void 0||typeof p.markdown!="string"||p.markdown===""||typeof p.final_url!="string"||p.final_url===""||typeof p.projection?.kind!="string"||typeof p.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:p}}let d=a.code;return typeof d=="string"&&rn.has(d)?{ok:!1,kind:d}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var pe="kane.source.web/1";function lt(t,n,e){if(e==="")throw new Error("cannot build a web source from an empty page projection");if(n.kind===""||n.version==="")throw new Error("cannot build a stable identity without a server-reported projection kind/version");let r={schema:pe,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var on=new Set(["markdown"]);function dt(){return async t=>{let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("this web source's stored envelope is not readable \u2014 re-ingest the page")}if(n.schema!==pe)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!on.has(n.projection?.kind??""))throw new Error(`unknown web projection kind '${String(n.projection?.kind)}' \u2014 update kane-cli to read this source`);if(typeof n.content?.markdown!="string"||n.content.markdown==="")throw new Error("this web source's stored envelope carries no content \u2014 re-ingest the page");return{projection:n.content.markdown,inventory:[],blobs:new Map,delivered:[],converter:{name:"web-convert",version:"1",policy:"markdown-passthrough"}}}}import{createHash as sn}from"crypto";function pt(t){return ae(t)!==null}function ae(t){if(!/^https?:\/\//i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname===""?null:(n.hash="",n.username="",n.password="",n.toString())}function me(t){let n=ae(t);if(n===null)return null;let e=new URL(n),r=(e.hostname+e.pathname).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,""),s=sn("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${s}`}function an(t,n){let e=j(t),r=e.heads.get(n);if(r==null)return null;let s=e.getNode(r)?.content?.blob;if(typeof s!="string")return null;let o=W(t,s);if(o===null)return null;try{let l=JSON.parse(o.toString("utf8"));return l.schema!=="kane.source.web/1"?null:typeof l.url=="string"&&l.url.length>0?l.url:null}catch{return null}}function fe(t){switch(t){case"invalid_url":return"this is not a valid public HTTP or HTTPS page URL \u2014 check the address and try again";case"target_disallowed":return"that address cannot be fetched because it does not point to an allowed public web page";case"page_not_found":return"the page could not be found \u2014 check that the URL is correct and that the page still exists";case"page_access_blocked":return"the page refused automated access, so its contents could not be ingested \u2014 use a publicly accessible version of the page";case"page_paywalled":return"the page is behind a paywall or sign-in screen, so its full contents could not be ingested \u2014 use a publicly accessible copy";case"unsupported_content_type":return"the URL does not point to an HTML web page \u2014 download the document and ingest the supported file instead";case"page_too_large":return"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first";case"page_timeout":return"the page took too long to load \u2014 try again later";case"scrape_unavailable":case"scrape_rate_limited":case"internal_error":return"the page ingest service is temporarily unavailable \u2014 try again later";case"credit_denied":return"the page could not be ingested \u2014 your organization is out of credits";case"auth_rejected":return"your credentials were rejected \u2014 run `kane-cli login` and retry";case"route_missing":return"ingesting web pages is not available in your environment yet \u2014 nothing is wrong with the URL; try again later";case"transport_unreachable":return"the page ingest service could not be reached \u2014 check your connection and try again";case"malformed_response":return"the page ingest service returned a response that could not be read safely \u2014 try again later"}}function cn(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page contains too much text to ingest as a single source (${n[1]}; the limit is ${n[2]}) \u2014 use a narrower page or trim the content first`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first":t}async function un(t,n,e,r,s){let o=ae(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};let l=me(t),u=n??l;if(u===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};try{N(u)}catch(y){return(e.err??e.out)(`error: ${t}: ${y instanceof Error?y.message:String(y)}`),{code:1}}let i=P(r,u,"web");if(i!==null)return(e.err??e.out)(`error: ${t}: ${i}`),{code:1};let c=an(r,u);if(c!==null&&c!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${u}' was ingested from ${c} \u2014 re-run on a TTY to adopt the new URL as its next version, or ingest under a different id with --as`),{code:1};if(!await e.confirm(`source '${u}' was ingested from ${c} \u2014 treat ${o} as its new version (replaces the current version; items built on it go stale)?`))return e.out(`skipped ${t} \u2014 ingest under a different id with --as to keep both pages`),{code:1}}let a=s?.web?.scrape??ut,d=s?.authEnv??(async()=>(await import("./spawner-ZSYJQGQW.js")).resolveAgentAuthEnv()),p=await a(o,{authEnv:d});if(!p.ok)return(e.err??e.out)(`error: ${t}: ${fe(p.kind)}`),{code:1};try{let{bytes:y}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:y,media:be,sourceId:u,label:o,confirmSameSource:e.isTTY?h=>e.confirm(`identical content already ingested as ${h} \u2014 treat as the same source?`):void 0,converters:{web:dt()}}),f=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,f));for(let h of w.warnings??[])e.out(`warning: ${h}`);return e.isTTY&&p.page.title&&e.out(` title: ${p.page.title}`),{code:0,result:{status:w.status,source_id:w.source_id,source_cid:w.cid}}}catch(y){return(e.err??e.out)(`error: ${t}: ${cn(y instanceof Error?y.message:String(y))}`),{code:1}}}var mt={name:"web",hint:"any public web page URL (https://\u2026)",match:pt,ingest:un,sourceIdFor:me};function U(t,n,e){return t?n.status==="created"?`landed ${n.source_id} (${e}) \u2014 new source`:n.status==="versioned"?`landed ${n.source_id} (${e}) \u2014 new version; dependents go stale`:`${n.source_id} unchanged \u2014 already landed`:`${n.status} ${n.source_id} source ${n.cid} blob ${n.blob}`}var ln=[Oe,De,st,at,ct,mt];function Kr(t){return/^https?:\/\/.+/i.test(t)}function Wr(t){return ln.find(n=>n.match(t))??null}export{U as a,ln as b,Kr as c,Wr as d};
17
+ `,inventory:l.inventory,blobs:l.blobs,delivered:l.delivered,converter:{name:"linear-doc-convert",version:"1",policy:"v1"}}}}var qt=/^[A-Za-z][A-Za-z0-9]*-\d+$/,Qt=/-([0-9a-f]{12})$/;function ue(t){if(!/^https?:\/\/.+/i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname.toLowerCase()!=="linear.app"?null:n.pathname.split("/").filter(Boolean)}function Ze(t){let n=ue(t);return n===null||n.length<3?null:{workspace:n[0],segs:n}}function Y(t){let n=Ze(t);if(n===null||n.segs[1]!=="issue")return null;let e=n.segs[2];return qt.test(e)?{workspace:n.workspace,key:e}:null}function K(t){let n=Ze(t);if(n===null||n.segs[1]!=="document")return null;let e=n.segs[2].match(Qt);return e===null?null:{workspace:n.workspace,slugId:e[1]}}var en=new Set(["project","team","view","initiative","cycle","roadmap","inbox","triage","my-issues"]),qe=new Set(["docs","features","method","blog","customers","pricing","integrations","developers","changelog","about","careers","security","download","contact","now","switch","homepage"]);function le(t){let n=ue(t);return n===null||n.length<2||!en.has(n[1])||qe.has(n[0].toLowerCase())?null:{workspace:n[0],section:n[1]}}function de(t){let n=ue(t);return n===null||n.length<2||n[1]!=="issue"&&n[1]!=="document"||qe.has(n[0].toLowerCase())||Y(t)!==null||K(t)!==null?null:{workspace:n[0],section:n[1]}}function Qe(t){let n=Y(t);return n?n.key.toLowerCase():null}function et(t){let n=K(t);return n?`doc-${n.slugId}`:null}var tt={linearInfo:je,linearIssue:Be,linearComments:Me,linearDocument:Je,linearAttachment:Fe};function nt(t,n){if(t)try{let e=new URL(t).pathname.split("/").filter(Boolean)[0];if(e)return`linear.app/${e.toLowerCase()}`}catch{}return`linear.app/${n.toLowerCase()}`}function rt(t,n,e,r,s,o){let l=ee(t,r);if(l!==null&&typeof l.schema=="string"&&l.schema.startsWith(`kane.source.${n}/`)){let i=l;for(let c of e)i=i!==null&&typeof i=="object"?i[c]:void 0;if(typeof i=="string"&&i!==""&&i!==s)return`source '${r}' was ingested from a different ${o} that used this key \u2014 the key was recycled; retire it first (kane-cli context retire ${r}) or ingest under a different id with --as`}let u=ke(t,n,e,s);return u!==null&&u!==r?`this ${o} is already ingested as '${u}' (its key changed) \u2014 reconcile that source, or retire it to re-ingest under the new key`:null}function ot(t,n,e,r){let s=ee(t,e);if(s===null||typeof s.schema!="string"||!s.schema.startsWith(`kane.source.${n}/`))return null;let o=s.site;return typeof o!="string"||o.length===0||o===r?null:`source '${e}' was ingested from ${o}, but this read serves ${r} \u2014 retire it first (kane-cli context retire ${e}) or ingest under a different id with --as`}async function tn(t,n,e,r,s){let o=Y(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear issue URL (https://linear.app/<workspace>/issue/KEY-123)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-EVXJVU72.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.issue===!1||c.capabilities.comments===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read issues or their comments yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearIssue(o.key,i),d=await l.linearComments(o.key,i),p=nt(a.host,o.workspace),{bytes:y,envelope:w,warnings:f}=Ge(a,d,p),h=n??o.key.toLowerCase();N(h);let _=rt(r,"linear",["issue","uuid"],h,w.issue.uuid,"issue")??P(r,h,"linear")??ot(r,"linear",h,p);if(_!==null)return(e.err??e.out)(`error: ${t}: ${_}`),{code:1};let b=await T({contextDir:r,bytes:y,media:Ee,sourceId:h,label:t,confirmSameSource:e.isTTY?g=>e.confirm(`identical content already ingested as ${g} \u2014 treat as the same source?`):void 0,converters:{linear:ze({fetchAttachment:g=>l.linearAttachment(g,i)})}});e.out(U(e.isTTY,b,w.issue.key));for(let g of f)e.out(`warning: ${g}`);for(let g of b.warnings??[])e.out(`warning: ${g}`);if(b.composite){let g=b.composite.delivered+b.composite.omitted;e.out(`${b.source_id}: linear, ${g} images, ${b.composite.delivered} delivered (${b.composite.omitted} omitted)`)}return{code:0,result:{status:b.status,source_id:b.source_id,source_cid:b.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"issue","Linear")}`),{code:1})}}async function nn(t,n,e,r,s){let o=K(t);if(o===null)return(e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear document URL (https://linear.app/<workspace>/document/<slug>)`),{code:1};let l=s?.linear??tt;try{let i={auth:await(s?.authEnv??(await import("./auth-EVXJVU72.js")).resolveLisAuthEnv)(),env:process.env},c=await l.linearInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Linear connection for this account \u2014 create one at ${A} and retry`),{code:1};if(c.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection cannot read documents yet \u2014 resync it at ${A} and retry`),{code:1};let a=await l.linearDocument(o.slugId,i),d=nt(a.url,o.workspace),{bytes:p,envelope:y,warnings:w}=Ye(a,d,o.slugId),f=n??`doc-${o.slugId}`;N(f);let h=rt(r,"linear-doc",["document","uuid"],f,y.document.uuid,"document")??P(r,f,"linear-doc")??ot(r,"linear-doc",f,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:f,label:t,confirmSameSource:e.isTTY?b=>e.confirm(`identical content already ingested as ${b} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:b=>l.linearAttachment(b,i)})}});e.out(U(e.isTTY,_,y.title||`document ${o.slugId}`));for(let b of w)e.out(`warning: ${b}`);for(let b of _.warnings??[])e.out(`warning: ${b}`);if(_.composite){let b=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${b} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid}}}catch(u){return u instanceof E?((e.err??e.out)(`error: ${t}: ${u.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${it(u instanceof Error?u.message:String(u),"document","Linear")}`),{code:1})}}function it(t,n,e){let r=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return r?`the ${n}'s content is too large to ingest (${r[1]}; the limit is ${r[2]}) \u2014 trim the ${n} in ${e} and retry`:t.startsWith("PROJECTION_TOO_LARGE:")?`the ${n}'s text is too large to ingest \u2014 trim the ${n} in ${e} and retry`:t}var st={name:"linear",hint:"Linear issue URLs (https://linear.app/<workspace>/issue/KEY-123)",match:t=>Y(t)!==null,ingest:tn,sourceIdFor:Qe},at={name:"linear-doc",hint:"Linear document URLs (https://linear.app/<workspace>/document/<slug>)",match:t=>K(t)!==null,ingest:nn,sourceIdFor:et},ct={name:"linear-page",hint:"Linear issue or document URLs (other linear.app pages are not ingestable)",match:t=>le(t)!==null||de(t)!==null,ingest:async(t,n,e)=>{let r=le(t);if(r===null){let s=de(t);return s!==null?((e.err??e.out)(`error: ${t}: this Linear ${s.section} link is incomplete or malformed \u2014 use the full form (https://linear.app/${s.workspace}/issue/KEY-123 or https://linear.app/${s.workspace}/document/<slug>-<id>)`),{code:1}):((e.err??e.out)(`error: ${t}: unsupported remote URL \u2014 expected a Linear workspace page`),{code:1})}return(e.err??e.out)(`error: ${t}: this Linear page can't be ingested \u2014 only issue and document URLs are supported; ingest the project's issues or documents individually (https://linear.app/${r.workspace}/issue/KEY-123)`),{code:1}},sourceIdFor:()=>null};var rn=new Set(["invalid_url","target_disallowed","page_not_found","page_access_blocked","page_paywalled","unsupported_content_type","page_too_large","page_timeout","scrape_unavailable","scrape_rate_limited","internal_error","credit_denied"]);async function ut(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,s=we(e),o={"Content-Type":"application/json"},l=await n.authEnv(),u=l.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=l.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;u?o.Authorization=`Basic ${u}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${s}/assurance/web/scrape`,{method:"POST",headers:o,body:JSON.stringify({url:t}),signal:AbortSignal.timeout(n.timeoutMs??55e3)})}catch{return{ok:!1,kind:"transport_unreachable"}}if(c.status===401)return{ok:!1,kind:"auth_rejected"};let a;try{a=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let p=a.page;return p===void 0||typeof p.markdown!="string"||p.markdown===""||typeof p.final_url!="string"||p.final_url===""||typeof p.projection?.kind!="string"||typeof p.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:p}}let d=a.code;return typeof d=="string"&&rn.has(d)?{ok:!1,kind:d}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var pe="kane.source.web/1";function lt(t,n,e){if(e==="")throw new Error("cannot build a web source from an empty page projection");if(n.kind===""||n.version==="")throw new Error("cannot build a stable identity without a server-reported projection kind/version");let r={schema:pe,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var on=new Set(["markdown"]);function dt(){return async t=>{let n;try{n=JSON.parse(t.toString("utf8"))}catch{throw new Error("this web source's stored envelope is not readable \u2014 re-ingest the page")}if(n.schema!==pe)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!on.has(n.projection?.kind??""))throw new Error(`unknown web projection kind '${String(n.projection?.kind)}' \u2014 update kane-cli to read this source`);if(typeof n.content?.markdown!="string"||n.content.markdown==="")throw new Error("this web source's stored envelope carries no content \u2014 re-ingest the page");return{projection:n.content.markdown,inventory:[],blobs:new Map,delivered:[],converter:{name:"web-convert",version:"1",policy:"markdown-passthrough"}}}}import{createHash as sn}from"crypto";function pt(t){return ae(t)!==null}function ae(t){if(!/^https?:\/\//i.test(t))return null;let n;try{n=new URL(t)}catch{return null}return n.hostname===""?null:(n.hash="",n.username="",n.password="",n.toString())}function me(t){let n=ae(t);if(n===null)return null;let e=new URL(n),r=(e.hostname+e.pathname).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40).replace(/-+$/,""),s=sn("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${s}`}function an(t,n){let e=j(t),r=e.heads.get(n);if(r==null)return null;let s=e.getNode(r)?.content?.blob;if(typeof s!="string")return null;let o=W(t,s);if(o===null)return null;try{let l=JSON.parse(o.toString("utf8"));return l.schema!=="kane.source.web/1"?null:typeof l.url=="string"&&l.url.length>0?l.url:null}catch{return null}}function fe(t){switch(t){case"invalid_url":return"this is not a valid public HTTP or HTTPS page URL \u2014 check the address and try again";case"target_disallowed":return"that address cannot be fetched because it does not point to an allowed public web page";case"page_not_found":return"the page could not be found \u2014 check that the URL is correct and that the page still exists";case"page_access_blocked":return"the page refused automated access, so its contents could not be ingested \u2014 use a publicly accessible version of the page";case"page_paywalled":return"the page is behind a paywall or sign-in screen, so its full contents could not be ingested \u2014 use a publicly accessible copy";case"unsupported_content_type":return"the URL does not point to an HTML web page \u2014 download the document and ingest the supported file instead";case"page_too_large":return"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first";case"page_timeout":return"the page took too long to load \u2014 try again later";case"scrape_unavailable":case"scrape_rate_limited":case"internal_error":return"the page ingest service is temporarily unavailable \u2014 try again later";case"credit_denied":return"the page could not be ingested \u2014 your organization is out of credits";case"auth_rejected":return"your credentials were rejected \u2014 run `kane-cli login` and retry";case"route_missing":return"ingesting web pages is not available in your environment yet \u2014 nothing is wrong with the URL; try again later";case"transport_unreachable":return"the page ingest service could not be reached \u2014 check your connection and try again";case"malformed_response":return"the page ingest service returned a response that could not be read safely \u2014 try again later"}}function cn(t){let n=t.match(/too large — ([\d.]+ [KM]B), the limit for .+ is ([\d.]+ [KM]B) \[FILE_TOO_LARGE\]/);return n?`the page contains too much text to ingest as a single source (${n[1]}; the limit is ${n[2]}) \u2014 use a narrower page or trim the content first`:t.startsWith("PROJECTION_TOO_LARGE:")?"the page contains too much text to ingest as a single source \u2014 use a narrower page or trim the content first":t}async function un(t,n,e,r,s){let o=ae(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};let l=me(t),u=n??l;if(u===null)return(e.err??e.out)(`error: ${t}: ${fe("invalid_url")}`),{code:1};try{N(u)}catch(y){return(e.err??e.out)(`error: ${t}: ${y instanceof Error?y.message:String(y)}`),{code:1}}let i=P(r,u,"web");if(i!==null)return(e.err??e.out)(`error: ${t}: ${i}`),{code:1};let c=an(r,u);if(c!==null&&c!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${u}' was ingested from ${c} \u2014 re-run on a TTY to adopt the new URL as its next version, or ingest under a different id with --as`),{code:1};if(!await e.confirm(`source '${u}' was ingested from ${c} \u2014 treat ${o} as its new version (replaces the current version; items built on it go stale)?`))return e.out(`skipped ${t} \u2014 ingest under a different id with --as to keep both pages`),{code:1}}let a=s?.web?.scrape??ut,d=s?.authEnv??(async()=>(await import("./spawner-SHCGHLQS.js")).resolveAgentAuthEnv()),p=await a(o,{authEnv:d});if(!p.ok)return(e.err??e.out)(`error: ${t}: ${fe(p.kind)}`),{code:1};try{let{bytes:y}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:y,media:be,sourceId:u,label:o,confirmSameSource:e.isTTY?h=>e.confirm(`identical content already ingested as ${h} \u2014 treat as the same source?`):void 0,converters:{web:dt()}}),f=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,f));for(let h of w.warnings??[])e.out(`warning: ${h}`);return e.isTTY&&p.page.title&&e.out(` title: ${p.page.title}`),{code:0,result:{status:w.status,source_id:w.source_id,source_cid:w.cid}}}catch(y){return(e.err??e.out)(`error: ${t}: ${cn(y instanceof Error?y.message:String(y))}`),{code:1}}}var mt={name:"web",hint:"any public web page URL (https://\u2026)",match:pt,ingest:un,sourceIdFor:me};function U(t,n,e){return t?n.status==="created"?`landed ${n.source_id} (${e}) \u2014 new source`:n.status==="versioned"?`landed ${n.source_id} (${e}) \u2014 new version; dependents go stale`:`${n.source_id} unchanged \u2014 already landed`:`${n.status} ${n.source_id} source ${n.cid} blob ${n.blob}`}var ln=[Oe,De,st,at,ct,mt];function Kr(t){return/^https?:\/\/.+/i.test(t)}function Wr(t){return ln.find(n=>n.match(t))??null}export{U as a,ln as b,Kr as c,Wr as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f}from"./chunk-RX5TZZNQ.js";import{x as t}from"./chunk-OFW3ZVTP.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a,b as n}from"./chunk-C44QQJR4.js";import{a as R}from"./chunk-6YGTRKDT.js";import{e as c}from"./chunk-UR6MHSHU.js";var p=c(R(),1);var e=c(x(),1);function v(){return[{name:"convert",label:"Converting session data",status:"pending"},{name:"zip",label:"Compressing artifacts",status:"pending"},{name:"presign",label:"Requesting upload URLs",status:"pending"},{name:"upload",label:"Uploading to KaneAI",status:"pending"},{name:"atomic_replace",label:"Replacing local output",status:"pending"},{name:"commit_lock",label:"Committing to TMS",status:"pending"},{name:"finalize",label:"Finalizing test case",status:"pending"},{name:"code_export",label:"Downloading test code",status:"pending"}]}function U(s,o,d,i){return s.map(l=>l.name===o?{...l,status:d,detail:i}:l)}function D(s){let o=s/1e3;if(o<60)return`${o.toFixed(1)}s`;let d=Math.floor(o/60),i=Math.round(o%60);return`${d}m ${i}s`}function w(s){let[o,d]=(0,p.useState)(0),i=p.default.useRef(Date.now());return(0,p.useEffect)(()=>{if(!s)return;i.current=Date.now();let l=setInterval(()=>{d(Date.now()-i.current)},100);return()=>clearInterval(l)},[s]),o}function h({steps:s,status:o,testUrl:d,error:i}){let l=w(o==="uploading");return o==="uploading"?(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.orange,children:"\u2601 "}),(0,e.jsx)(n,{color:t.orange,bold:!0,children:"Saving to KaneAI"}),(0,e.jsxs)(n,{color:t.dim,children:[" ",D(l)]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:s.filter(r=>r.status!=="skipped"||r.detail).map((r,S,T)=>{let b=S===T.length-1?"\u2514\u2500":"\u251C\u2500",u=r.status==="done",m=r.status==="running",g=r.status==="failed",B=r.status==="skipped";return(0,e.jsxs)(a,{children:[(0,e.jsxs)(n,{color:t.dim,children:[" ",b," "]}),(0,e.jsx)(a,{width:3,children:m?(0,e.jsx)(f,{}):u?(0,e.jsx)(n,{color:t.green,children:"\u2713"}):g?(0,e.jsx)(n,{color:t.red,children:"\u2717"}):B?(0,e.jsx)(n,{color:t.muted,children:"\u2013"}):(0,e.jsx)(n,{color:t.muted,children:"\u25CB"})}),(0,e.jsx)(n,{color:u?t.dim:m?void 0:g?t.red:t.muted,children:r.label}),r.detail&&(0,e.jsxs)(n,{color:t.dim,children:[" ",r.detail]})]},r.name)})}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(n,{color:t.muted,children:" press Ctrl+C twice to force exit"})})]}):o==="success"?(0,e.jsx)(e.Fragment,{}):(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.red,children:"\u2601 "}),(0,e.jsx)(n,{color:t.red,bold:!0,children:"Save failed"})]}),i&&(0,e.jsxs)(a,{marginTop:0,children:[(0,e.jsx)(n,{color:t.dim,children:" "}),(0,e.jsx)(n,{color:t.dim,children:i})]})]})}export{v as a,U as b,h as c};
2
+ import{a as f}from"./chunk-WRIPTYSN.js";import{x as t}from"./chunk-LPH4TERT.js";import{a as x}from"./chunk-HCBYKLMW.js";import{a,b as n}from"./chunk-C44QQJR4.js";import{a as R}from"./chunk-6YGTRKDT.js";import{e as c}from"./chunk-UR6MHSHU.js";var p=c(R(),1);var e=c(x(),1);function v(){return[{name:"convert",label:"Converting session data",status:"pending"},{name:"zip",label:"Compressing artifacts",status:"pending"},{name:"presign",label:"Requesting upload URLs",status:"pending"},{name:"upload",label:"Uploading to KaneAI",status:"pending"},{name:"atomic_replace",label:"Replacing local output",status:"pending"},{name:"commit_lock",label:"Committing to TMS",status:"pending"},{name:"finalize",label:"Finalizing test case",status:"pending"},{name:"code_export",label:"Downloading test code",status:"pending"}]}function U(s,o,d,i){return s.map(l=>l.name===o?{...l,status:d,detail:i}:l)}function D(s){let o=s/1e3;if(o<60)return`${o.toFixed(1)}s`;let d=Math.floor(o/60),i=Math.round(o%60);return`${d}m ${i}s`}function w(s){let[o,d]=(0,p.useState)(0),i=p.default.useRef(Date.now());return(0,p.useEffect)(()=>{if(!s)return;i.current=Date.now();let l=setInterval(()=>{d(Date.now()-i.current)},100);return()=>clearInterval(l)},[s]),o}function h({steps:s,status:o,testUrl:d,error:i}){let l=w(o==="uploading");return o==="uploading"?(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.orange,children:"\u2601 "}),(0,e.jsx)(n,{color:t.orange,bold:!0,children:"Saving to KaneAI"}),(0,e.jsxs)(n,{color:t.dim,children:[" ",D(l)]})]}),(0,e.jsx)(a,{flexDirection:"column",marginTop:1,children:s.filter(r=>r.status!=="skipped"||r.detail).map((r,S,T)=>{let b=S===T.length-1?"\u2514\u2500":"\u251C\u2500",u=r.status==="done",m=r.status==="running",g=r.status==="failed",B=r.status==="skipped";return(0,e.jsxs)(a,{children:[(0,e.jsxs)(n,{color:t.dim,children:[" ",b," "]}),(0,e.jsx)(a,{width:3,children:m?(0,e.jsx)(f,{}):u?(0,e.jsx)(n,{color:t.green,children:"\u2713"}):g?(0,e.jsx)(n,{color:t.red,children:"\u2717"}):B?(0,e.jsx)(n,{color:t.muted,children:"\u2013"}):(0,e.jsx)(n,{color:t.muted,children:"\u25CB"})}),(0,e.jsx)(n,{color:u?t.dim:m?void 0:g?t.red:t.muted,children:r.label}),r.detail&&(0,e.jsxs)(n,{color:t.dim,children:[" ",r.detail]})]},r.name)})}),(0,e.jsx)(a,{marginTop:1,children:(0,e.jsx)(n,{color:t.muted,children:" press Ctrl+C twice to force exit"})})]}):o==="success"?(0,e.jsx)(e.Fragment,{}):(0,e.jsxs)(a,{flexDirection:"column",paddingX:1,paddingY:1,children:[(0,e.jsxs)(a,{children:[(0,e.jsx)(n,{color:t.red,children:"\u2601 "}),(0,e.jsx)(n,{color:t.red,bold:!0,children:"Save failed"})]}),i&&(0,e.jsxs)(a,{marginTop:0,children:[(0,e.jsx)(n,{color:t.dim,children:" "}),(0,e.jsx)(n,{color:t.dim,children:i})]})]})}export{v as a,U as b,h as c};
@@ -0,0 +1,15 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as k,c as j}from"./chunk-IPEA7ZOF.js";import{dirname as J,basename as L,join as c}from"path";function W(t){let e=L(t);return e.endsWith("_test.md")?e.slice(0,-8):e.endsWith(".md")?e.slice(0,-3):e}function h(t){return c(J(t),`output-${W(t)}`)}function ot(t){return c(h(t),"Result.md")}function O(t){return c(h(t),".internal")}function R(t){return c(O(t),"meta.json")}function st(t,e,n){return c(h(t),`${e}-${n}-code`)}function dt(t){return c(h(t),"generated-code")}function ct(t){return h(t)+".staging"}function H(t){return c(O(t),"steps")}function at(t,e,n){return c(H(t),`${e}-${n}`)}import{existsSync as s,renameSync as b,rmSync as g}from"fs";function ft(t){let e=`${t}.staging`,n=`${t}.bak`;if(!s(e))throw new Error(`atomicReplaceDir: staging missing: ${e}`);if(process.platform==="win32"){s(t)&&g(t,{recursive:!0,force:!0}),b(e,t);return}s(t)&&(s(n)&&g(n,{recursive:!0,force:!0}),b(t,n)),b(e,t),s(n)&&g(n,{recursive:!0,force:!0})}function gt(t){let e=`${t}.staging`,n=`${t}.bak`;if(process.platform==="win32"){s(e)&&(s(t)?g(e,{recursive:!0,force:!0}):b(e,t));return}if(s(n)&&!s(t)){b(n,t),s(e)&&g(e,{recursive:!0,force:!0});return}s(n)&&s(t)&&g(n,{recursive:!0,force:!0}),s(e)&&s(t)&&g(e,{recursive:!0,force:!0})}import{readFileSync as Q,existsSync as X}from"fs";import{basename as E,dirname as Z,isAbsolute as B,resolve as F}from"path";import{createHash as I}from"crypto";function y(t){if(t==null)return null;if(Array.isArray(t))return t.map(y);if(typeof t=="object"){let e={};for(let n of Object.keys(t).sort()){let r=t[n];r!==void 0&&(e[n]=y(r))}return e}return t}function U(t){if(t.body.kind!=="objective")throw new Error("stepMd5: only objective steps have an md5; @import rows do not");let e={...t.config??{},optional:t.optional??!1},n=JSON.stringify(y(e));return I("md5").update(t.body.text).update(`
3
+ `).update(n).digest("hex")}function C(t){let e={};for(let[r,o]of Object.entries(t.bindings??{}))e[r]={value:o.value,...o.secret===!0?{secret:!0}:{},...o.syntax?{syntax:o.syntax}:{}};let n=JSON.stringify(y({bindings:e,optional:t.optional}));return I("md5").update(t.path).update(`
4
+ `).update(n).digest("hex")}function ht(t){return U({index:t.trace[t.trace.length-1].stepIndex,heading:t.trace[t.trace.length-1].heading,verifies:[],body:{kind:"objective",text:t.objective},config:t.parsedConfig,headingLine:1,optional:t.optional})}import{writeFileSync as Y,mkdirSync as z,readFileSync as q}from"fs";import{dirname as $}from"path";function T(t){try{return JSON.parse(q(R(t),"utf8"))}catch{return null}}function xt(t){let e=R(t.sourcePath);try{z($(e),{recursive:!0})}catch(r){return process.stderr.write(`
5
+ \u26A0 Failed to create output directory.
6
+ ${r.message}
7
+ Path: ${$(e)}
8
+
9
+ `),e}let n={commit_id:t.commitId};t.testId!==void 0&&(n.test_id=t.testId),t.testcaseId!==void 0&&(n.testcase_id=t.testcaseId),t.projectId!==void 0&&(n.project_id=t.projectId),t.folderId!==void 0&&(n.folder_id=t.folderId),t.orgId!==void 0&&(n.org_id=t.orgId),t.sessionName!==void 0&&(n.session_name=t.sessionName),t.plan!==void 0&&(n.plan=t.plan);try{Y(e,JSON.stringify(n,null,2)+`
10
+ `,"utf8")}catch(r){process.stderr.write(`
11
+ \u26A0 Failed to write meta.json.
12
+ ${r.message}
13
+ Path: ${e}
14
+
15
+ `)}return e}var D=["target","chrome_profile","cdp_endpoint","ws_endpoint","headless"],tt=["app","no_reset","os_version","device_name"],et=["mode","on_lock_conflict","tags","target","chrome_profile","cdp_endpoint","ws_endpoint","headless","app","no_reset","os_version","device_name"],l=class extends Error{constructor(e){super(e),this.name="TestMdResolveError"}};function S(t){return E(t).endsWith("_test.md")?"test":"helper"}function Ot(t){let e=F(t),n=V(e),r=nt(n.global),o=[],a=[],d=[{file:e,kind:S(e)}],p=[];return P(n,a,o,[],e,{},d,p,{}),o.forEach((m,_)=>m.flatIndex=_+1),{rootPath:e,rootTitle:n.title,rootGlobal:n.global,rootSteps:n.steps,chrome:r,steps:o,unitFiles:d,warnings:p}}function It(t){let e=[];for(let n of t.unitFiles){if(n.kind!=="test")continue;let r=T(n.file);r&&e.push({file:n.file,...r.project_id?{project_id:String(r.project_id)}:{},...r.org_id?{org_id:String(r.org_id)}:{}})}return e}function V(t){if(!X(t))throw new l(`@import path not found: ${t}`);let e=Q(t,"utf8");return k(t,e)}function P(t,e,n,r,o,a,d,p,u){if(e.includes(t.path)){let i=[...e,t.path].map(f=>E(f)).join(" \u2192 ");throw new l(`cyclic reference: ${i}`)}e.push(t.path);let m=r.length===0,_=t.global.variables??{};for(let i of Object.keys(a))if(Object.hasOwn(_,i))throw new l(`callsite binding '${i}' collides with a declared variable in ${t.path} (frontmatter variables are pinned; parameters are its undeclared names)`);let w=t.global;if(!m){let i={...t.global};for(let f of et)i[f]!==void 0&&(p.push(`${t.path}: '${f}' is root-governed on imported units \u2014 ignored`),delete i[f]);i.url!==void 0&&(u.pending=String(i.url),delete i.url),w=i}for(let i of t.steps){let f=i.body.kind!=="objective";if(i.optional&&f&&!m)throw new l(`intermediate-ref 'optional' is not supported in v1: ${t.path}:${i.headingLine}`);if(i.body.kind==="objective"){let x={file:t.path,stepIndex:i.index,heading:i.heading,optional:i.optional??!1},G=it(w,i.config,a),M={flatIndex:0,objective:i.body.text,sourceFile:t.path,trace:[...r,x],config:G,parsedConfig:i.config,optional:i.optional??!1,verifies:i.verifies,owningFile:t.path,unitKind:S(t.path)};u.pending&&(M.unitEntryUrl=u.pending,u.pending=void 0),n.push(M);continue}let A={file:t.path,stepIndex:i.index,heading:i.heading,optional:i.optional??!1,rowMd5:C({path:i.body.path,bindings:i.body.bindings,optional:i.optional??!1})},K=Z(t.path),v=B(i.body.path)?i.body.path:F(K,i.body.path),N=V(v);d.some(x=>x.file===v)||d.push({file:v,kind:S(v)}),P(N,e,n,[...r,A],o,i.body.bindings??{},d,p,u)}m||(u.pending=void 0),e.pop()}function nt(t){let e={};for(let n of D){if(n==="target"){let r=j(t);r!==void 0&&(e.target=r);continue}t[n]!==void 0&&(e[n]=t[n])}return e}function it(t,e,n){let r={};for(let[d,p]of Object.entries(t))D.includes(d)||tt.includes(d)||(r[d]=p);let o={...r,...e??{}},a={...n,...t.variables??{},...e?.variables??{}};return Object.keys(a).length>0?o.variables=a:delete o.variables,o}export{W as a,h as b,ot as c,O as d,R as e,st as f,dt as g,ct as h,H as i,at as j,ft as k,gt as l,C as m,ht as n,T as o,xt as p,l as q,Ot as r,It as s};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{g as h}from"./chunk-GFKCTYCA.js";import{d as l}from"./chunk-DUAXZYAD.js";import{b as u}from"./chunk-DBIBROYW.js";import{d as f}from"./chunk-WXHQYYD5.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-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};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as n}from"./chunk-OFW3ZVTP.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-LPH4TERT.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
- agent_state_schema=${r}`),"sha256:"+t.digest("hex")}function d(){return[o(s,".."),o(s,"../../..")]}function i(){return"sha256:85dd52f33a9fd9cf22ebb81f04dfd3c05bdbeca2e62e3a7a53e8caaaa4060752"}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};
4
+ agent_state_schema=${r}`),"sha256:"+t.digest("hex")}function d(){return[o(s,".."),o(s,"../../..")]}function i(){return"sha256:da159529b51d00a7c5455d7773dc5143fa670ec0af9646aa5346f22faeb367db"}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{a}from"./chunk-5Y2G4NC7.js";import{x as o}from"./chunk-OFW3ZVTP.js";import{a as n}from"./chunk-HCBYKLMW.js";import{b as t}from"./chunk-C44QQJR4.js";import{a as s}from"./chunk-6YGTRKDT.js";import{e as r}from"./chunk-UR6MHSHU.js";var l=r(s(),1);var m=r(n(),1),i=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function b({active:e=!0}){let[p,c]=(0,l.useState)(0);return a(()=>{c(f=>(f+1)%i.length)},e?80:null),(0,m.jsx)(t,{color:o.orange,children:e?i[p]:"\u25CF"})}export{b as a};
2
+ import{a}from"./chunk-5Y2G4NC7.js";import{x as o}from"./chunk-LPH4TERT.js";import{a as n}from"./chunk-HCBYKLMW.js";import{b as t}from"./chunk-C44QQJR4.js";import{a as s}from"./chunk-6YGTRKDT.js";import{e as r}from"./chunk-UR6MHSHU.js";var l=r(s(),1);var m=r(n(),1),i=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function b({active:e=!0}){let[p,c]=(0,l.useState)(0);return a(()=>{c(f=>(f+1)%i.length)},e?80:null),(0,m.jsx)(t,{color:o.orange,children:e?i[p]:"\u25CF"})}export{b as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as B}from"./chunk-S3DAAAE5.js";import{a as g}from"./chunk-NT3UETTV.js";import{x as s}from"./chunk-OFW3ZVTP.js";import{a as w}from"./chunk-HCBYKLMW.js";import{a as x,b as t,c as h,i as P,j as S}from"./chunk-C44QQJR4.js";import{a as C}from"./chunk-6YGTRKDT.js";import{e as T}from"./chunk-UR6MHSHU.js";var o=T(C(),1);var e=T(w(),1);function D({defaultName:i,onSubmit:c}){let[d,p]=(0,o.useState)("confirm"),[f,a]=(0,o.useState)(""),[m,u]=(0,o.useState)(null),l=(0,o.useMemo)(()=>f.trim()||i,[f,i]);return P((n,r)=>{if(d==="confirm"){if(n==="y"||n==="Y"){a(i),p("name");return}if(n==="n"||n==="N"||r.escape||r.ctrl&&n==="c"){c(null);return}if(r.return){c(i);return}return}if(r.return){if(!B(l)){u(`name "${l}" is invalid; allowed: letters, digits, underscore, hyphen`);return}c(l);return}if(r.escape||r.ctrl&&n==="c"){c(null);return}if(r.backspace||r.delete){a(v=>v.slice(0,-1)),u(null);return}n&&!r.ctrl&&!r.meta&&(a(v=>v+n),u(null))}),d==="confirm"?(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsx)(t,{color:s.orange,children:i})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save with this name"}),(0,e.jsx)(t,{color:s.dim,children:"Y \u2014 edit name"}),(0,e.jsx)(t,{color:s.dim,children:"N/esc \u2014 discard session"})]})}):(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsxs)(x,{children:[(0,e.jsx)(t,{color:s.orange,children:f}),(0,e.jsx)(t,{inverse:!0,children:" "})]})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[m&&(0,e.jsx)(t,{color:s.red,children:m}),(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save \xB7 esc \u2014 discard"})]})})}function V(){return new Date().toISOString().slice(0,19).replace(/:/g,"-")}async function Y(i){return new Promise(c=>{function d(){let{exit:a}=S(),[m,u]=(0,o.useState)(!1);return(0,o.useEffect)(()=>{if(m){let l=setTimeout(()=>a(),50);return()=>clearTimeout(l)}},[m,a]),(0,e.jsx)(D,{defaultName:i,onSubmit:l=>{c(l),u(!0)}})}let{waitUntilExit:p,unmount:f}=h((0,e.jsx)(d,{}),{stdout:process.stderr,exitOnCtrlC:!1});p().then(()=>{try{f()}catch{}})})}export{D as a,V as b,Y as c};
2
+ import{b as B}from"./chunk-S3DAAAE5.js";import{a as g}from"./chunk-FL6TCYA5.js";import{x as s}from"./chunk-LPH4TERT.js";import{a as w}from"./chunk-HCBYKLMW.js";import{a as x,b as t,c as h,i as P,j as S}from"./chunk-C44QQJR4.js";import{a as C}from"./chunk-6YGTRKDT.js";import{e as T}from"./chunk-UR6MHSHU.js";var o=T(C(),1);var e=T(w(),1);function D({defaultName:i,onSubmit:c}){let[d,p]=(0,o.useState)("confirm"),[f,a]=(0,o.useState)(""),[m,u]=(0,o.useState)(null),l=(0,o.useMemo)(()=>f.trim()||i,[f,i]);return P((n,r)=>{if(d==="confirm"){if(n==="y"||n==="Y"){a(i),p("name");return}if(n==="n"||n==="N"||r.escape||r.ctrl&&n==="c"){c(null);return}if(r.return){c(i);return}return}if(r.return){if(!B(l)){u(`name "${l}" is invalid; allowed: letters, digits, underscore, hyphen`);return}c(l);return}if(r.escape||r.ctrl&&n==="c"){c(null);return}if(r.backspace||r.delete){a(v=>v.slice(0,-1)),u(null);return}n&&!r.ctrl&&!r.meta&&(a(v=>v+n),u(null))}),d==="confirm"?(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsx)(t,{color:s.orange,children:i})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save with this name"}),(0,e.jsx)(t,{color:s.dim,children:"Y \u2014 edit name"}),(0,e.jsx)(t,{color:s.dim,children:"N/esc \u2014 discard session"})]})}):(0,e.jsx)(g,{title:"Save session?",titleColor:"#ff9500",rows:[{label:"name",value:(0,e.jsxs)(x,{children:[(0,e.jsx)(t,{color:s.orange,children:f}),(0,e.jsx)(t,{inverse:!0,children:" "})]})}],footer:(0,e.jsxs)(x,{flexDirection:"column",children:[m&&(0,e.jsx)(t,{color:s.red,children:m}),(0,e.jsx)(t,{color:s.dim,children:"enter \u2014 save \xB7 esc \u2014 discard"})]})})}function V(){return new Date().toISOString().slice(0,19).replace(/:/g,"-")}async function Y(i){return new Promise(c=>{function d(){let{exit:a}=S(),[m,u]=(0,o.useState)(!1);return(0,o.useEffect)(()=>{if(m){let l=setTimeout(()=>a(),50);return()=>clearTimeout(l)}},[m,a]),(0,e.jsx)(D,{defaultName:i,onSubmit:l=>{c(l),u(!0)}})}let{waitUntilExit:p,unmount:f}=h((0,e.jsx)(d,{}),{stdout:process.stderr,exitOnCtrlC:!1});p().then(()=>{try{f()}catch{}})})}export{D as a,V as b,Y as c};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{j as Re,k as oe,l as se,m as _e,n as $e,o as ae}from"./chunk-JN44V63O.js";import{a as te,c as re,d as ye,f as ie}from"./chunk-7VZCXW74.js";import{a as P,b as we,d as ke}from"./chunk-OS4VSIHT.js";import{d as ve}from"./chunk-6J5T5FEY.js";import{a as S}from"./chunk-CLGC7VEO.js";import{a as X,b as N,c as ee,d as W,e as he,g as O,h as ne}from"./chunk-W5TTF7GB.js";import{a as ge}from"./chunk-JFAFKHDX.js";import{b as Z,c as J,d as Q}from"./chunk-BN6AHQL7.js";import{h as me,j as pe}from"./chunk-2DCNCH32.js";import{A as I}from"./chunk-TH47OOBV.js";import{f as T}from"./chunk-DUAXZYAD.js";import{existsSync as Oe,statSync as Ue}from"fs";import{basename as G,resolve as q}from"path";function Ee(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 ce(e,n){let t=[...e.rows.filter(a=>a.kind!=="REMOVE").map(a=>[a.kind,S(a.ref),a.reason,Ee(a.impact)]),...e.archive.map(a=>["ARCHIVE",S(a.ref),a.why,Ee(a.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(...ve(["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 xe=new Set(["interactive","agent","ci","override"]);function Ae(e,n){if(e.mode!==void 0&&!xe.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 Pe(e){let{makeHeadlessIO:n,agentRefusal:t}=await import("./headless-io-66RG5NN5.js");return t(n("ndjson","reconcile"),e,"MODE_USAGE")}function Me(e,n,t,r){if(J(t)){let v=Q(t),s=v?.sourceIdFor(t)??null;if(v===null||s===null)return{error:`--from '${t}' is not a supported remote URL \u2014 supported: ${Z.map(u=>u.hint).join("; ")}`};if(r!==void 0&&r!==s)return{error:`--source-id '${r}' does not match this URL's own identity '${s}' \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(s))return{error:`unknown source '${s}' \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(s)==null)return{error:`source '${s}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let _=z(e,s,{remoteUrl:t});return _!==null?{error:_}:{sourceId:s,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=q(n,t);if(!Oe(i)||!Ue(i).isFile())return{error:`--from '${t}' is not a file \u2014 pass the changed source document`};let a=me(i);if(!a.ok)return{error:`--from '${t}' is not an ingestable document \u2014 allowed: ${a.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 f=null;try{f=pe(i)}catch{}return f!==null&&f!==r&&o.heads.get(f)!=null?{error:`'${G(i)}' already backs live source '${f}' \u2014 did you mean --source-id ${f}? To truly move these bytes under '${r}', retire '${f}' first`}:{sourceId:r,filePath:i}}function C(e){return e==null?"(none)":e.slice(0,19)}function Y(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 a=n.changeset??[],o=(f,v)=>{let s=a.filter(c=>c.kind===f).length;return s>0?`${s} ${v}`:null},w=[o("ADD","add"),o("MODIFY","modify"),o("ARCHIVE","archive")].filter(Boolean);n.changed&&e.out(`changeset: ${a.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 a=n.changeset??[];e.out(`changeset: ${a.length} item(s)`);for(let o of a)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=le(o.impact,"retiring drops");w&&e.out(` ${w}`)}}e.out(`plan: ${n.rows.length} row(s)`);for(let a of n.rows){e.out(` [${a.kind}] ${S(a.ref)} \u2014 ${a.reason}`);let o=le(a.impact,"approving marks");o&&e.out(` ${o}`),e.out(` provenance: ${a.provenance}`),e.out(` action: ${a.action}`)}}function De(e,n){return ce({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 le(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 M(e,n,t,r,i,a,o=[],w="override",f,v,s,c,_,u,E){let m;try{m=ne(e)}catch(d){return P(r,d instanceof Error?d.message:String(d)),1}try{if(!t){let{runWalkSession:d}=await import("./walk-session-HB3OOWVR.js"),{telemetryEnvName:R}=await import("./bootstrap-BTEXO6HX.js");return await d({dir:e,rows:n,archive:o,held:f??null,childMode:w,runDesign:c??null,mark:a,markA:s,...v?{archiveState:v}:{},...u?{meta:{verb:"reconcile",sid:u,env:R()}}:{},...E?{resumeCmd:E}:{},signals:b=>U(e,b.ref,b.verdict,b.reason),..._?{script:_}:{}})}return await Te(e,n,t,r,i,a,o,w,f,v)}finally{m()}}var H=(e,n)=>e?`kane-cli maintain reconcile --from ${e} --source-id ${n}`:void 0,He=e=>e===null?void 0:"filePath"in e?e.filePath:e.remoteUrl,V=e=>`${e} high-risk item(s) need a human \u2014 ci mode won't guess. Walk interactively or use --mode agent.`;function F(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 de(e={}){return{type:"reconcile_summary",applied:0,skipped:0,deferred:0,plan_only:0,failed:0,paused:0,stale_created:0,...e}}var L=de();async function j(e,n,t,r,i,a,o,w,f){F(i,n,t);let v=n.changeset.filter(_=>_.kind==="ARCHIVE"&&f?.[_.ref]===void 0),s=n.rows,c;try{c=ne(e)}catch(_){return i({type:"error",message:_ instanceof Error?_.message:String(_)}),i(de()),2}try{return await Fe(e,n,t,r,i,a,o,s,v,w)}finally{c()}}async function Fe(e,n,t,r,i,a,o,w,f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set,b=(h,p)=>{try{v?.(h,p)}catch{}};for(let[h,p]of w.entries()){i({type:"reconcile_row_start",kind:p.kind,ref:p.ref,...p.impact?{stale:p.impact.stale_refs.length,direct:p.impact.direct_refs?.length??0}:{}});let g=(l,$,x)=>i({type:"reconcile_row_end",kind:p.kind,ref:p.ref,outcome:l,...$!==void 0?{exit_code:$}:{},...x?{detail:x}:{}});if(p.applied){c++,g("skipped");continue}if(p.kind==="REMOVE"){E++,g("plan-only");continue}if(p.held_ref&&n.held){let l=new Set;if(p.kind==="MODIFY"&&p.impact){let x=I(e);for(let A of p.impact.stale_refs){let K=x.resolve(A);K&&x.stale(K.tip)==="fresh"&&l.add(A)}}let $=oe(e,n.held,p.held_ref,ue);if(!$.ok){_++,d===0&&(d=1),g("failed",1,$.message);continue}if($.kind==="ADD"){let x=await r($.ref,{yes:!0,mode:o});if(x!==0){x===3?(u++,d===0&&(d=3),g("paused",3)):(_++,d===0&&(d=1),g("failed",x));continue}}s++,$.kind!=="ADD"&&p.impact&&(m+=l.size),b(h,"approved"),U(e,p.ref,$.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve"),g("applied");continue}let y=te(I(e),p.ref);if(!y.ok){c++,g("skipped");continue}let k=y.target;if(R.has(k.ucTip)){c++,g("skipped");continue}if(p.kind==="ADD"){let l=await r(k.seamRef,{yes:!0,mode:o});if(l===3){u++,d===0&&(d=3),g("paused",3);continue}if(l!==0){_++,d===0&&(d=1),g("failed",l);continue}R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-create"),g("applied")}else{let l=await re(e,k,{yes:!0,mode:o},a,r,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-evolve"),g("applied")):l.outcome==="paused"?(u++,d===0&&(d=l.code),g("paused",l.code)):l.outcome==="failed"?(_++,d===0&&(d=1),g("failed",l.code)):(c++,g("skipped"))}}return f.length>0&&(i({type:"reconcile_paused",plan_path:t,pending:f.map(h=>({ref:h.ref,why:h.why}))}),u+=f.length,d===0&&(d=3)),i(de({applied:s,skipped:c,plan_only:E,failed:_,paused:u,stale_created:m})),d}var ue={kind:"human",id:process.env.USER??"operator"};function U(e,n,t,r){ge(e,{ts:new Date().toISOString(),command:"reconcile-walk",id:n,verdict:t,polarity:"preference",by:ue,target:n,...r!==void 0?{reason:r}:{}})}async function Te(e,n,t,r,i,a,o=[],w="override",f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set;for(let[b,h]of n.entries()){if(h.applied){r.out(`skipped ${h.ref} \u2014 already applied (${h.applied.outcome} at ${h.applied.at})`),c++;continue}let p=l=>{try{a?.(b,l)}catch($){P(r,`could not record applied state for ${h.ref}: ${$ instanceof Error?$.message:String($)}`)}};if(h.kind==="REMOVE"){r.out(`REMOVE ${h.ref} \u2014 plan-only in this release (not executed)`),u++;continue}if(h.held_ref&&f){let l=oe(e,f,h.held_ref,ue);if(!l.ok){P(r,`held ${h.ref}: ${l.message}`),E++,d===0&&(d=1);continue}if(r.out(`committed ${l.ref} (${h.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`),m++,d===0&&(d=3),p("approved");continue}if($!==0){P(r,`design run for ${l.ref} ended with exit code ${$}`),E++,d===0&&(d=1),p("approved");continue}}s++,p("approved"),U(e,h.ref,h.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve");continue}let g=I(e),y=te(g,h.ref);if(!y.ok){r.out(`skipped ${h.ref} \u2014 ${y.message}`),c++;continue}let k=y.target;if(R.has(k.ucTip)){r.out(`skipped ${h.ref} \u2014 use-case ${k.display} already handled in this walk`),c++;continue}if(h.kind==="ADD"){let l=await i(k.seamRef,{yes:t,mode:w});if(l===3){r.out(`design session for ${k.display} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above; this row lands when that session completes`),m++,d===0&&(d=3);continue}if(l!==0){P(r,`design run for ${k.display} ended with exit code ${l}`),E++,d===0&&(d=1);continue}R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-create")}else{let l=await re(e,k,{yes:!0,mode:w},r,i,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-evolve")):l.outcome==="paused"?(m++,d===0&&(d=l.code)):l.outcome==="failed"?(E++,d===0&&(d=l.code)):c++}}for(let b of o)if(b.kind==="ARCHIVE"&&v?.[b.ref]===void 0){r.out(`[ARCHIVE] ${b.ref} \u2014 ${b.why}`);{let h=le(b.impact,"retiring drops");h&&r.out(` ${h}`)}r.out(" plan-only \u2014 retire belongs to the interactive session (never headless)"),u++}return r.out(`reconcile walk: ${s} applied, ${c} skipped, ${_} deferred, ${u} plan-only`+(E>0?`, ${E} failed`:"")+(m>0?`, ${m} paused`:"")),d}var Be=new Set(Z.map(e=>e.name));function z(e,n,t){let r=I(e),i=r.heads.get(n);if(i==null)return null;let a=r.mediaOf(i);if("remoteUrl"in t){let o=Q(t.remoteUrl)?.name??"remote";return a.format!==o?`source '${n}' is backed by ${a.format} content, not a ${o} source \u2014 reconcile it with the --from it was originally ingested from`:null}return Be.has(a.format)?`source '${n}' is a remote ${a.format} source \u2014 pass its URL to --from, not a file`:null}function fe(e,n,t,r){return"remoteUrl"in n?$e(e,n.remoteUrl,{out:t.out,err:t.err},r.remoteFindProvider):_e(e,n.filePath)}function Ie(e){return e.remote_url!==void 0?{remoteUrl:e.remote_url}:e.backing_path!==void 0?{filePath:e.backing_path}:null}async function Se(e,n,t,r,i,a=!1,o=!1){let w=i.seams??{reingest:fe(e,t,r,i),reextract:ae(e,{stage:a,hostOut:c=>r.out(c),hostEmit:c=>{c.type!=="run_start"&&i.emitEvent?.(c)},...i.emitEvent?{}:{hostProgress:c=>process.stderr.write(c+`
3
- `)}})},f=null,v={reingest:w.reingest,reextract:async c=>f=await w.reextract(c)},s;try{r.out(`reconciling ${n}: re-reading the source and comparing against the graph\u2026`),s=await(i.buildPlan??se)(e,n,v)}catch(c){return P(r,`reconcile failed: ${c instanceof Error?c.message:String(c)}`),null}if(s.changed)if(o)for(let c of De(s,f))r.out(c);else Y(r,s,f,!1,i.emitEvent);return s}async function Ve(e){let[{render:n},t,{ScrollbackProvider:r},{ChatSurface:i},{makeChatController:a},{makeReconcileDeps:o}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-S2P7WMBI.js"),import("./chat-controller-R4THYYPU.js"),import("./reconcile-deps-FYXRAMF2.js")]),w=t.default??t,f=a(),v=o({contextDir:e,note:s=>f.note(s)});return new Promise(s=>{let c=n(w.createElement(r,null,w.createElement(i,{controller:f,verb:"extract",reconcile:v,autoReview:!0,onReviewExit:()=>{c.unmount(),s(0)},onCtrlC:()=>{c.unmount(),s(v.pending()?3:0)}})),{exitOnCtrlC:!1})})}async function Le(e,n,t,r,i){let a=N(e,n);if("error"in a)return P(r,a.error),2;let{plan:o,path:w}=a,f=t==="override"||t==="ci";if(n===void 0&&t==="interactive"&&r.isTTY&&!await r.confirm(`apply plan ${G(w)} for ${o.source_id} (created ${o.created})?`))return r.out(`not applying ${G(w)}`),0;let v=i.runDesignForUc??ie,s=i.runDesignForUc??null,c=i.sessionScript,_=(h,p)=>O(w,h,p),u=(h,p)=>W(w,h,p),E=T(e);if(E===o.head_pin){if(t==="agent"){let p=i.emitEvent??(()=>{});return j(e,B(o),w,v,p,r,D(t),_,o.archive_state)}let h=ee(o);if(t==="ci"&&h.length>0)return P(r,V(h.length)),2;if(r.out(`applying stored plan ${G(w)} for ${o.source_id} (${o.rows.length} row(s))`),!f)for(let p of ce({source_id:o.source_id,head:{status:"stored plan"},rows:o.rows,archive:(o.changeset??[]).filter(g=>g.kind==="ARCHIVE"),changed:!1,held:!!o.held},process.stdout.columns))r.out(p);return M(e,o.rows,f,r,v,_,o.changeset??[],D(t),o.held,o.archive_state,u,s,c,o.source_id,H(o.backing_path??o.remote_url,o.source_id))}if(r.out(`graph moved since this plan (${C(o.head_pin)} \u2192 ${C(E)}) \u2014 recomputing`),o.held)return Ce(e,o,r,i,t,v,!1);let m=Ie(o);if(m===null)return P(r,`stored plan for ${o.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let d=z(e,o.source_id,m);if(d!==null)return P(r,`stored plan cannot replay: ${d}`),2;let R=await Se(e,o.source_id,m,r,i,!1,t==="interactive");if(!R)return 1;if(!R.changed)return Y(r,R,null,!1,i.emitEvent),0;if(t==="agent"){let h=i.emitEvent??(()=>{});return j(e,R,null,v,h,r,D(t))}let b=R.changeset.filter(h=>h.kind==="ARCHIVE");return t==="ci"&&b.length>0?(P(r,V(b.length)),2):M(e,R.rows,f,r,v,void 0,R.changeset,D(t),R.held,void 0,void 0,s,c,R.source_id,H(He(m),R.source_id))}function B(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 je(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v=he(e,n);if(v===null)return null;if("error"in v)return P(t,v.error),2;let{plan:s,path:c}=v,_=s.rows.filter(d=>d.applied===void 0),u=ee(s),E=r.emitEvent??(()=>{});if(_.length===0&&u.length===0){t.out(`already reconciled \u2014 plan ${s.created} applied ${s.rows.length} row(s)`);let d=ye(I(e)).staleCount;return d>0&&(t.out(`${d} item(s) still stale \u2014 kane-cli maintain evolve --from-stale`),E({type:"stale_debt",count:d})),i==="agent"&&(F(E,B(s),c),E({...L})),0}let m=T(e);return m!==s.head_pin?(t.out(`plan ${s.created} superseded \u2014 graph moved (${C(s.head_pin)} \u2192 ${C(m)}); recomputing`),Ce(e,s,t,r,i,a,o)):(t.out(`resuming plan ${s.created} \u2014 ${_.length} pending row(s)${u.length>0?`, ${u.length} undecided archive item(s)`:""}`),o?(Y(t,B(s),null,!1,r.emitEvent),t.out(`plan stored: ${c}`),i==="agent"&&(F(E,B(s),c),E({...L})),0):i==="agent"?j(e,B(s),c,a,E,t,D(i),(d,R)=>O(c,d,R),s.archive_state):i==="ci"&&u.length>0?(P(t,V(u.length)),2):M(e,s.rows,i==="override"||i==="ci",t,a,(d,R)=>O(c,d,R),s.changeset??[],D(i),s.held,s.archive_state,(d,R)=>W(c,d,R),w,f,s.source_id,H(s.backing_path??s.remote_url,s.source_id)))}async function Ce(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v;if(n.held){let g=I(e),y=new Set(n.rows.filter(l=>l.held_ref!==void 0&&l.applied!==void 0).map(l=>l.held_ref)),k=[];for(let l of n.held.rows){if(y.has(l.temp_ref))continue;if(!l.matched_cid){k.push(l);continue}let $=g.tipOf(l.matched_cid);if(g.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}k.push($===l.matched_cid?l:{...l,matched_cid:$,uc:{...l.uc,matches_existing:{cid:$}}})}v={source_id:n.held.source_id,rows:k}}let s=Ie(n);if(s===null)return P(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,s);if(c!==null)return P(t,`stored plan cannot replay: ${c}`),2;let _=r.seams??{reingest:fe(e,s,t,r),reextract:ae(e,{stage:v!==void 0,hostOut:g=>t.out(g),hostEmit:g=>{g.type!=="run_start"&&r.emitEvent?.(g)},...r.emitEvent?{}:{hostProgress:g=>process.stderr.write(g+`
4
- `)}})},u;try{u=await(r.buildPlan??se)(e,n.source_id,_,{resumeHeld:v})}catch(g){return P(t,`reconcile failed: ${g instanceof Error?g.message:String(g)}`),1}if(i==="interactive"&&!o)for(let g of De(u,null))t.out(g);else Y(t,u,null,!1,r.emitEvent);let E=T(e),m=null;if(E!=null){let g={},y=new Set(u.changeset.filter(k=>k.kind==="ARCHIVE").map(k=>k.ref));for(let[k,l]of Object.entries(n.archive_state??{}))y.has(k)&&(g[k]=l);m=X(e,{version:2,source_id:u.source_id,...n.remote_url!==void 0?{remote_url:n.remote_url}:{backing_path:n.backing_path},head_pin:E,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:u.skipped_arms,note:u.note,changeset:u.changeset,rows:u.rows,...u.held?{held:u.held}:{},...Object.keys(g).length>0?{archive_state:g}:{}}),t.out(`plan stored: ${m}`)}if(o){if(i==="agent"){let g=r.emitEvent??(()=>{});F(g,u,m),g({...L})}return 0}let d=r.emitEvent??(()=>{}),R=m?N(e,m).plan.archive_state:void 0,b=m?(g,y)=>O(m,g,y):void 0,h=m?(g,y)=>W(m,g,y):void 0;if(i==="agent")return j(e,u,m,a,d,t,D(i),b,R);let p=u.changeset.filter(g=>g.kind==="ARCHIVE"&&R?.[g.ref]===void 0);return i==="ci"&&p.length>0?(P(t,V(p.length)),2):M(e,u.rows,i==="override"||i==="ci",t,a,b,u.changeset,D(i),u.held,R,h,w,f,u.source_id,H(n.backing_path??n.remote_url,u.source_id))}async function be(e,n,t={},r=process.cwd()){let{telemetryBootstrap:i,telemetryEnvName:a}=await import("./bootstrap-BTEXO6HX.js"),o=i({verb:"reconcile",mode:typeof e.mode=="string"?e.mode:"interactive",contextRoot:q(r,".context"),env:a(),applyPlanPath:typeof e.apply=="string"?q(r,e.apply):void 0,write:!0,longSession:!0});e.mode==="agent"&&t.emitEvent?.({type:"run_start",session:o.ids.session_id});let w=await Ye(e,n,t,r);return w===1&&e.mode!=="agent"&&(n.err??n.out)(o.supportFooter()),await o.end({exit_code:w}),w}async function Ye(e,n,t={},r=process.cwd()){let i=e.apply!==void 0&&e.apply!==!1,a=typeof e.apply=="string"?e.apply:void 0;if(e.plan&&i)return P(n,"pass --plan OR --apply, not both"),2;let o=e.from!==void 0||!i,w=e.from!==void 0&&J(e.from);if(o&&(!e.from||!e.sourceId&&!w))return P(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&&a!==void 0)return P(n,"pass --from OR --apply <path>, not both \u2014 a stored plan names its own source"),2;let f=we(r,n);if(!f)return 2;if(e.mode!==void 0&&!xe.has(e.mode))return Pe(`--mode must be interactive | agent | ci | override, got '${e.mode}'`);let v=e.mode==="agent"||e.mode==="ci"||e.mode==="override";if(i&&!v&&!n.isTTY)return P(n,"refusing to apply without a TTY to confirm \u2014 pass --mode override|ci"),2;let s=!e.plan,c="override";if(e.from){let y=Ae(e,n.isTTY);if(typeof y=="object")return y.code==="MODE_USAGE"?Pe(y.error):(P(n,y.error),2);c=y}let _=c==="override"||c==="ci";if(i&&!e.from){let{makeReconcileDeps:y}=await import("./reconcile-deps-FYXRAMF2.js"),k=a===void 0?y({contextDir:f}).pending():null;if(k?.kind==="cards"){let $=e.mode??"interactive";return!n.isTTY||$!=="interactive"?(P(n,`a held changeset for ${k.source} awaits review (${k.count} change(s)) \u2014 resume in a terminal: kane-cli maintain reconcile --apply [HELD_REVIEW]`),2):(t.cardApplyMount??Ve)(f)}let l=e.mode??"interactive";return Le(f,a===void 0?void 0:q(r,a),l,n,t)}let u=Me(f,r,e.from,e.sourceId);if("error"in u)return P(n,u.error),2;if(!i){let{sessionsHoldingSource:y}=await import("./sessions-GIEXOCE4.js"),{holders:k,corrupt:l}=y(f,u.sourceId);if(l>0)return P(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(k.length>0)return P(n,`session ${k[0]} holds item(s) for review pinned to ${u.sourceId} \u2014 finish that review first: kane-cli context extract --resume ${k[0]} [SOURCE_HELD]`),2}if(c==="interactive"&&!e.plan&&!i){let y=t.seams?.reingest??fe(f,u,n,t),k;try{k=await y(u.sourceId)}catch($){return P(n,$ instanceof Error?$.message:String($)),1}let l=k.status==="unchanged"?null:Re(f,u.sourceId);if(k.status!=="unchanged"&&!l)return n.out(`${u.sourceId} landed for the first time \u2014 extract it: kane-cli context extract --source ${u.sourceId}`),0;if(l){let x=await(t.chatMount??(async A=>{let{bindExtractInteractive:K}=await import("./extract-bind-TJ2STXV5.js");return K(A)}))({mode:"interactive",posture:"reconcile",source:u.sourceId,changeContext:l});if(x===3){let{sessionsHoldingSource:A}=await import("./sessions-GIEXOCE4.js");if(A(f,u.sourceId).holders.length===0)return 0}return x}}let E="remoteUrl"in u?{remoteUrl:u.remoteUrl}:{filePath:u.filePath},m=await Se(f,u.sourceId,E,n,t,!!e.plan||c==="interactive",c==="interactive"&&!e.plan);if(!m)return 1;let d=t.runDesignForUc??ie,R=t.runDesignForUc??null,b=t.sessionScript;if(!m.changed){let y=await je(f,u.sourceId,n,t,c,d,!!e.plan);if(y!==null)return y;if(Y(n,m,null,!1,t.emitEvent),c==="agent"){let k=t.emitEvent??(()=>{});F(k,m,null),k({...L})}return 0}let h=T(f),p=null;if(h!=null?p=X(f,{version:2,source_id:m.source_id,..."remoteUrl"in E?{remote_url:E.remoteUrl}:{backing_path:E.filePath},head_pin:h,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:m.skipped_arms,note:m.note,changeset:m.changeset,rows:m.rows,...m.held?{held:m.held}:{}}):P(n,"no chain head after extract \u2014 plan not stored"),c==="agent"){let y=t.emitEvent??(()=>{});if(!s)return F(y,m,p),y({...L}),0;let k=p?(l,$)=>O(p,l,$):void 0;return j(f,m,p,d,y,n,D(c),k)}if(!s)return p&&n.out(`plan stored: ${p}`),0;let g=m.changeset.filter(y=>y.kind==="ARCHIVE");if(c==="ci"&&g.length>0)return p&&n.out(`plan stored: ${p}`),P(n,V(g.length)),2;if(p){n.out(`plan stored: ${p}`);let y=p;return M(f,Ke(f,y)??m.rows,_,n,d,(k,l)=>O(y,k,l),m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}return M(f,m.rows,_,n,d,void 0,m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}function Ke(e,n){let t=N(e,n);return"error"in t?null:t.plan.rows}async function dn(e,n={},t,r=process.cwd()){if(e.mode==="agent"){let{makeHeadlessIO:i}=await import("./headless-io-66RG5NN5.js"),a=t?i("ndjson","reconcile",t):i("ndjson","reconcile"),o={out:a.out,err:v=>a.event({type:"error",message:v}),isTTY:!1,confirm:async()=>!1,ask:async()=>""},{runWithChannel:w}=await import("./run-channel-RGH4WIQX.js"),f=2;try{f=await w({event:v=>a.event(v)},()=>be(e,o,{...n,emitEvent:v=>a.event(v)},r))}catch(v){f=1,a.event({type:"error",message:v instanceof Error?v.message:String(v)})}return a.done(f)}return be(e,ke(),n,r)}export{Ae as a,Me as b,D as c,U as d,be as e,dn as f};
2
+ import{j as Re,k as oe,l as se,m as _e,n as $e,o as ae}from"./chunk-ATIX6CVS.js";import{a as te,c as re,d as ye,f as ie}from"./chunk-VCDXUUJQ.js";import{a as P,b as we,d as ke}from"./chunk-OS4VSIHT.js";import{d as ve}from"./chunk-6J5T5FEY.js";import{a as S}from"./chunk-O5U6EAL3.js";import{a as X,b as N,c as ee,d as W,e as he,g as O,h as ne}from"./chunk-W5TTF7GB.js";import{a as ge}from"./chunk-BZAGVBCX.js";import{b as Z,c as J,d as Q}from"./chunk-WALVOFKR.js";import{h as me,j as pe}from"./chunk-54JZ6VEW.js";import{C as I}from"./chunk-W3Z7AZNT.js";import{g as T}from"./chunk-XMTSHHYQ.js";import{existsSync as Oe,statSync as Ue}from"fs";import{basename as G,resolve as q}from"path";function Ee(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 ce(e,n){let t=[...e.rows.filter(a=>a.kind!=="REMOVE").map(a=>[a.kind,S(a.ref),a.reason,Ee(a.impact)]),...e.archive.map(a=>["ARCHIVE",S(a.ref),a.why,Ee(a.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(...ve(["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 xe=new Set(["interactive","agent","ci","override"]);function Ae(e,n){if(e.mode!==void 0&&!xe.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 Pe(e){let{makeHeadlessIO:n,agentRefusal:t}=await import("./headless-io-66RG5NN5.js");return t(n("ndjson","reconcile"),e,"MODE_USAGE")}function Me(e,n,t,r){if(J(t)){let v=Q(t),s=v?.sourceIdFor(t)??null;if(v===null||s===null)return{error:`--from '${t}' is not a supported remote URL \u2014 supported: ${Z.map(u=>u.hint).join("; ")}`};if(r!==void 0&&r!==s)return{error:`--source-id '${r}' does not match this URL's own identity '${s}' \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(s))return{error:`unknown source '${s}' \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(s)==null)return{error:`source '${s}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let _=z(e,s,{remoteUrl:t});return _!==null?{error:_}:{sourceId:s,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=q(n,t);if(!Oe(i)||!Ue(i).isFile())return{error:`--from '${t}' is not a file \u2014 pass the changed source document`};let a=me(i);if(!a.ok)return{error:`--from '${t}' is not an ingestable document \u2014 allowed: ${a.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 f=null;try{f=pe(i)}catch{}return f!==null&&f!==r&&o.heads.get(f)!=null?{error:`'${G(i)}' already backs live source '${f}' \u2014 did you mean --source-id ${f}? To truly move these bytes under '${r}', retire '${f}' first`}:{sourceId:r,filePath:i}}function C(e){return e==null?"(none)":e.slice(0,19)}function Y(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 a=n.changeset??[],o=(f,v)=>{let s=a.filter(c=>c.kind===f).length;return s>0?`${s} ${v}`:null},w=[o("ADD","add"),o("MODIFY","modify"),o("ARCHIVE","archive")].filter(Boolean);n.changed&&e.out(`changeset: ${a.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 a=n.changeset??[];e.out(`changeset: ${a.length} item(s)`);for(let o of a)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=le(o.impact,"retiring drops");w&&e.out(` ${w}`)}}e.out(`plan: ${n.rows.length} row(s)`);for(let a of n.rows){e.out(` [${a.kind}] ${S(a.ref)} \u2014 ${a.reason}`);let o=le(a.impact,"approving marks");o&&e.out(` ${o}`),e.out(` provenance: ${a.provenance}`),e.out(` action: ${a.action}`)}}function De(e,n){return ce({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 le(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 M(e,n,t,r,i,a,o=[],w="override",f,v,s,c,_,u,E){let m;try{m=ne(e)}catch(d){return P(r,d instanceof Error?d.message:String(d)),1}try{if(!t){let{runWalkSession:d}=await import("./walk-session-M3OIWR5K.js"),{telemetryEnvName:R}=await import("./bootstrap-4XBQFKWF.js");return await d({dir:e,rows:n,archive:o,held:f??null,childMode:w,runDesign:c??null,mark:a,markA:s,...v?{archiveState:v}:{},...u?{meta:{verb:"reconcile",sid:u,env:R()}}:{},...E?{resumeCmd:E}:{},signals:b=>U(e,b.ref,b.verdict,b.reason),..._?{script:_}:{}})}return await Te(e,n,t,r,i,a,o,w,f,v)}finally{m()}}var H=(e,n)=>e?`kane-cli maintain reconcile --from ${e} --source-id ${n}`:void 0,He=e=>e===null?void 0:"filePath"in e?e.filePath:e.remoteUrl,V=e=>`${e} high-risk item(s) need a human \u2014 ci mode won't guess. Walk interactively or use --mode agent.`;function F(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 de(e={}){return{type:"reconcile_summary",applied:0,skipped:0,deferred:0,plan_only:0,failed:0,paused:0,stale_created:0,...e}}var L=de();async function j(e,n,t,r,i,a,o,w,f){F(i,n,t);let v=n.changeset.filter(_=>_.kind==="ARCHIVE"&&f?.[_.ref]===void 0),s=n.rows,c;try{c=ne(e)}catch(_){return i({type:"error",message:_ instanceof Error?_.message:String(_)}),i(de()),2}try{return await Fe(e,n,t,r,i,a,o,s,v,w)}finally{c()}}async function Fe(e,n,t,r,i,a,o,w,f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set,b=(h,p)=>{try{v?.(h,p)}catch{}};for(let[h,p]of w.entries()){i({type:"reconcile_row_start",kind:p.kind,ref:p.ref,...p.impact?{stale:p.impact.stale_refs.length,direct:p.impact.direct_refs?.length??0}:{}});let g=(l,$,x)=>i({type:"reconcile_row_end",kind:p.kind,ref:p.ref,outcome:l,...$!==void 0?{exit_code:$}:{},...x?{detail:x}:{}});if(p.applied){c++,g("skipped");continue}if(p.kind==="REMOVE"){E++,g("plan-only");continue}if(p.held_ref&&n.held){let l=new Set;if(p.kind==="MODIFY"&&p.impact){let x=I(e);for(let A of p.impact.stale_refs){let K=x.resolve(A);K&&x.stale(K.tip)==="fresh"&&l.add(A)}}let $=oe(e,n.held,p.held_ref,ue);if(!$.ok){_++,d===0&&(d=1),g("failed",1,$.message);continue}if($.kind==="ADD"){let x=await r($.ref,{yes:!0,mode:o});if(x!==0){x===3?(u++,d===0&&(d=3),g("paused",3)):(_++,d===0&&(d=1),g("failed",x));continue}}s++,$.kind!=="ADD"&&p.impact&&(m+=l.size),b(h,"approved"),U(e,p.ref,$.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve"),g("applied");continue}let y=te(I(e),p.ref);if(!y.ok){c++,g("skipped");continue}let k=y.target;if(R.has(k.ucTip)){c++,g("skipped");continue}if(p.kind==="ADD"){let l=await r(k.seamRef,{yes:!0,mode:o});if(l===3){u++,d===0&&(d=3),g("paused",3);continue}if(l!==0){_++,d===0&&(d=1),g("failed",l);continue}R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-create"),g("applied")}else{let l=await re(e,k,{yes:!0,mode:o},a,r,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-evolve"),g("applied")):l.outcome==="paused"?(u++,d===0&&(d=l.code),g("paused",l.code)):l.outcome==="failed"?(_++,d===0&&(d=1),g("failed",l.code)):(c++,g("skipped"))}}return f.length>0&&(i({type:"reconcile_paused",plan_path:t,pending:f.map(h=>({ref:h.ref,why:h.why}))}),u+=f.length,d===0&&(d=3)),i(de({applied:s,skipped:c,plan_only:E,failed:_,paused:u,stale_created:m})),d}var ue={kind:"human",id:process.env.USER??"operator"};function U(e,n,t,r){ge(e,{ts:new Date().toISOString(),command:"reconcile-walk",id:n,verdict:t,polarity:"preference",by:ue,target:n,...r!==void 0?{reason:r}:{}})}async function Te(e,n,t,r,i,a,o=[],w="override",f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set;for(let[b,h]of n.entries()){if(h.applied){r.out(`skipped ${h.ref} \u2014 already applied (${h.applied.outcome} at ${h.applied.at})`),c++;continue}let p=l=>{try{a?.(b,l)}catch($){P(r,`could not record applied state for ${h.ref}: ${$ instanceof Error?$.message:String($)}`)}};if(h.kind==="REMOVE"){r.out(`REMOVE ${h.ref} \u2014 plan-only in this release (not executed)`),u++;continue}if(h.held_ref&&f){let l=oe(e,f,h.held_ref,ue);if(!l.ok){P(r,`held ${h.ref}: ${l.message}`),E++,d===0&&(d=1);continue}if(r.out(`committed ${l.ref} (${h.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`),m++,d===0&&(d=3),p("approved");continue}if($!==0){P(r,`design run for ${l.ref} ended with exit code ${$}`),E++,d===0&&(d=1),p("approved");continue}}s++,p("approved"),U(e,h.ref,h.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve");continue}let g=I(e),y=te(g,h.ref);if(!y.ok){r.out(`skipped ${h.ref} \u2014 ${y.message}`),c++;continue}let k=y.target;if(R.has(k.ucTip)){r.out(`skipped ${h.ref} \u2014 use-case ${k.display} already handled in this walk`),c++;continue}if(h.kind==="ADD"){let l=await i(k.seamRef,{yes:t,mode:w});if(l===3){r.out(`design session for ${k.display} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above; this row lands when that session completes`),m++,d===0&&(d=3);continue}if(l!==0){P(r,`design run for ${k.display} ended with exit code ${l}`),E++,d===0&&(d=1);continue}R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-create")}else{let l=await re(e,k,{yes:!0,mode:w},r,i,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-evolve")):l.outcome==="paused"?(m++,d===0&&(d=l.code)):l.outcome==="failed"?(E++,d===0&&(d=l.code)):c++}}for(let b of o)if(b.kind==="ARCHIVE"&&v?.[b.ref]===void 0){r.out(`[ARCHIVE] ${b.ref} \u2014 ${b.why}`);{let h=le(b.impact,"retiring drops");h&&r.out(` ${h}`)}r.out(" plan-only \u2014 retire belongs to the interactive session (never headless)"),u++}return r.out(`reconcile walk: ${s} applied, ${c} skipped, ${_} deferred, ${u} plan-only`+(E>0?`, ${E} failed`:"")+(m>0?`, ${m} paused`:"")),d}var Be=new Set(Z.map(e=>e.name));function z(e,n,t){let r=I(e),i=r.heads.get(n);if(i==null)return null;let a=r.mediaOf(i);if("remoteUrl"in t){let o=Q(t.remoteUrl)?.name??"remote";return a.format!==o?`source '${n}' is backed by ${a.format} content, not a ${o} source \u2014 reconcile it with the --from it was originally ingested from`:null}return Be.has(a.format)?`source '${n}' is a remote ${a.format} source \u2014 pass its URL to --from, not a file`:null}function fe(e,n,t,r){return"remoteUrl"in n?$e(e,n.remoteUrl,{out:t.out,err:t.err},r.remoteFindProvider):_e(e,n.filePath)}function Ie(e){return e.remote_url!==void 0?{remoteUrl:e.remote_url}:e.backing_path!==void 0?{filePath:e.backing_path}:null}async function Se(e,n,t,r,i,a=!1,o=!1){let w=i.seams??{reingest:fe(e,t,r,i),reextract:ae(e,{stage:a,hostOut:c=>r.out(c),hostEmit:c=>{c.type!=="run_start"&&i.emitEvent?.(c)},...i.emitEvent?{}:{hostProgress:c=>process.stderr.write(c+`
3
+ `)}})},f=null,v={reingest:w.reingest,reextract:async c=>f=await w.reextract(c)},s;try{r.out(`reconciling ${n}: re-reading the source and comparing against the graph\u2026`),s=await(i.buildPlan??se)(e,n,v)}catch(c){return P(r,`reconcile failed: ${c instanceof Error?c.message:String(c)}`),null}if(s.changed)if(o)for(let c of De(s,f))r.out(c);else Y(r,s,f,!1,i.emitEvent);return s}async function Ve(e){let[{render:n},t,{ScrollbackProvider:r},{ChatSurface:i},{makeChatController:a},{makeReconcileDeps:o}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-LS3KF7XY.js"),import("./chat-controller-YJCNU76T.js"),import("./reconcile-deps-Y5G456WD.js")]),w=t.default??t,f=a(),v=o({contextDir:e,note:s=>f.note(s)});return new Promise(s=>{let c=n(w.createElement(r,null,w.createElement(i,{controller:f,verb:"extract",reconcile:v,autoReview:!0,onReviewExit:()=>{c.unmount(),s(0)},onCtrlC:()=>{c.unmount(),s(v.pending()?3:0)}})),{exitOnCtrlC:!1})})}async function Le(e,n,t,r,i){let a=N(e,n);if("error"in a)return P(r,a.error),2;let{plan:o,path:w}=a,f=t==="override"||t==="ci";if(n===void 0&&t==="interactive"&&r.isTTY&&!await r.confirm(`apply plan ${G(w)} for ${o.source_id} (created ${o.created})?`))return r.out(`not applying ${G(w)}`),0;let v=i.runDesignForUc??ie,s=i.runDesignForUc??null,c=i.sessionScript,_=(h,p)=>O(w,h,p),u=(h,p)=>W(w,h,p),E=T(e);if(E===o.head_pin){if(t==="agent"){let p=i.emitEvent??(()=>{});return j(e,B(o),w,v,p,r,D(t),_,o.archive_state)}let h=ee(o);if(t==="ci"&&h.length>0)return P(r,V(h.length)),2;if(r.out(`applying stored plan ${G(w)} for ${o.source_id} (${o.rows.length} row(s))`),!f)for(let p of ce({source_id:o.source_id,head:{status:"stored plan"},rows:o.rows,archive:(o.changeset??[]).filter(g=>g.kind==="ARCHIVE"),changed:!1,held:!!o.held},process.stdout.columns))r.out(p);return M(e,o.rows,f,r,v,_,o.changeset??[],D(t),o.held,o.archive_state,u,s,c,o.source_id,H(o.backing_path??o.remote_url,o.source_id))}if(r.out(`graph moved since this plan (${C(o.head_pin)} \u2192 ${C(E)}) \u2014 recomputing`),o.held)return Ce(e,o,r,i,t,v,!1);let m=Ie(o);if(m===null)return P(r,`stored plan for ${o.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let d=z(e,o.source_id,m);if(d!==null)return P(r,`stored plan cannot replay: ${d}`),2;let R=await Se(e,o.source_id,m,r,i,!1,t==="interactive");if(!R)return 1;if(!R.changed)return Y(r,R,null,!1,i.emitEvent),0;if(t==="agent"){let h=i.emitEvent??(()=>{});return j(e,R,null,v,h,r,D(t))}let b=R.changeset.filter(h=>h.kind==="ARCHIVE");return t==="ci"&&b.length>0?(P(r,V(b.length)),2):M(e,R.rows,f,r,v,void 0,R.changeset,D(t),R.held,void 0,void 0,s,c,R.source_id,H(He(m),R.source_id))}function B(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 je(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v=he(e,n);if(v===null)return null;if("error"in v)return P(t,v.error),2;let{plan:s,path:c}=v,_=s.rows.filter(d=>d.applied===void 0),u=ee(s),E=r.emitEvent??(()=>{});if(_.length===0&&u.length===0){t.out(`already reconciled \u2014 plan ${s.created} applied ${s.rows.length} row(s)`);let d=ye(I(e)).staleCount;return d>0&&(t.out(`${d} item(s) still stale \u2014 kane-cli maintain evolve --from-stale`),E({type:"stale_debt",count:d})),i==="agent"&&(F(E,B(s),c),E({...L})),0}let m=T(e);return m!==s.head_pin?(t.out(`plan ${s.created} superseded \u2014 graph moved (${C(s.head_pin)} \u2192 ${C(m)}); recomputing`),Ce(e,s,t,r,i,a,o)):(t.out(`resuming plan ${s.created} \u2014 ${_.length} pending row(s)${u.length>0?`, ${u.length} undecided archive item(s)`:""}`),o?(Y(t,B(s),null,!1,r.emitEvent),t.out(`plan stored: ${c}`),i==="agent"&&(F(E,B(s),c),E({...L})),0):i==="agent"?j(e,B(s),c,a,E,t,D(i),(d,R)=>O(c,d,R),s.archive_state):i==="ci"&&u.length>0?(P(t,V(u.length)),2):M(e,s.rows,i==="override"||i==="ci",t,a,(d,R)=>O(c,d,R),s.changeset??[],D(i),s.held,s.archive_state,(d,R)=>W(c,d,R),w,f,s.source_id,H(s.backing_path??s.remote_url,s.source_id)))}async function Ce(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v;if(n.held){let g=I(e),y=new Set(n.rows.filter(l=>l.held_ref!==void 0&&l.applied!==void 0).map(l=>l.held_ref)),k=[];for(let l of n.held.rows){if(y.has(l.temp_ref))continue;if(!l.matched_cid){k.push(l);continue}let $=g.tipOf(l.matched_cid);if(g.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}k.push($===l.matched_cid?l:{...l,matched_cid:$,uc:{...l.uc,matches_existing:{cid:$}}})}v={source_id:n.held.source_id,rows:k}}let s=Ie(n);if(s===null)return P(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,s);if(c!==null)return P(t,`stored plan cannot replay: ${c}`),2;let _=r.seams??{reingest:fe(e,s,t,r),reextract:ae(e,{stage:v!==void 0,hostOut:g=>t.out(g),hostEmit:g=>{g.type!=="run_start"&&r.emitEvent?.(g)},...r.emitEvent?{}:{hostProgress:g=>process.stderr.write(g+`
4
+ `)}})},u;try{u=await(r.buildPlan??se)(e,n.source_id,_,{resumeHeld:v})}catch(g){return P(t,`reconcile failed: ${g instanceof Error?g.message:String(g)}`),1}if(i==="interactive"&&!o)for(let g of De(u,null))t.out(g);else Y(t,u,null,!1,r.emitEvent);let E=T(e),m=null;if(E!=null){let g={},y=new Set(u.changeset.filter(k=>k.kind==="ARCHIVE").map(k=>k.ref));for(let[k,l]of Object.entries(n.archive_state??{}))y.has(k)&&(g[k]=l);m=X(e,{version:2,source_id:u.source_id,...n.remote_url!==void 0?{remote_url:n.remote_url}:{backing_path:n.backing_path},head_pin:E,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:u.skipped_arms,note:u.note,changeset:u.changeset,rows:u.rows,...u.held?{held:u.held}:{},...Object.keys(g).length>0?{archive_state:g}:{}}),t.out(`plan stored: ${m}`)}if(o){if(i==="agent"){let g=r.emitEvent??(()=>{});F(g,u,m),g({...L})}return 0}let d=r.emitEvent??(()=>{}),R=m?N(e,m).plan.archive_state:void 0,b=m?(g,y)=>O(m,g,y):void 0,h=m?(g,y)=>W(m,g,y):void 0;if(i==="agent")return j(e,u,m,a,d,t,D(i),b,R);let p=u.changeset.filter(g=>g.kind==="ARCHIVE"&&R?.[g.ref]===void 0);return i==="ci"&&p.length>0?(P(t,V(p.length)),2):M(e,u.rows,i==="override"||i==="ci",t,a,b,u.changeset,D(i),u.held,R,h,w,f,u.source_id,H(n.backing_path??n.remote_url,u.source_id))}async function be(e,n,t={},r=process.cwd()){let{telemetryBootstrap:i,telemetryEnvName:a}=await import("./bootstrap-4XBQFKWF.js"),o=i({verb:"reconcile",mode:typeof e.mode=="string"?e.mode:"interactive",contextRoot:q(r,".context"),env:a(),applyPlanPath:typeof e.apply=="string"?q(r,e.apply):void 0,write:!0,longSession:!0});e.mode==="agent"&&t.emitEvent?.({type:"run_start",session:o.ids.session_id});let w=await Ye(e,n,t,r);return w===1&&e.mode!=="agent"&&(n.err??n.out)(o.supportFooter()),await o.end({exit_code:w}),w}async function Ye(e,n,t={},r=process.cwd()){let i=e.apply!==void 0&&e.apply!==!1,a=typeof e.apply=="string"?e.apply:void 0;if(e.plan&&i)return P(n,"pass --plan OR --apply, not both"),2;let o=e.from!==void 0||!i,w=e.from!==void 0&&J(e.from);if(o&&(!e.from||!e.sourceId&&!w))return P(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&&a!==void 0)return P(n,"pass --from OR --apply <path>, not both \u2014 a stored plan names its own source"),2;let f=we(r,n);if(!f)return 2;if(e.mode!==void 0&&!xe.has(e.mode))return Pe(`--mode must be interactive | agent | ci | override, got '${e.mode}'`);let v=e.mode==="agent"||e.mode==="ci"||e.mode==="override";if(i&&!v&&!n.isTTY)return P(n,"refusing to apply without a TTY to confirm \u2014 pass --mode override|ci"),2;let s=!e.plan,c="override";if(e.from){let y=Ae(e,n.isTTY);if(typeof y=="object")return y.code==="MODE_USAGE"?Pe(y.error):(P(n,y.error),2);c=y}let _=c==="override"||c==="ci";if(i&&!e.from){let{makeReconcileDeps:y}=await import("./reconcile-deps-Y5G456WD.js"),k=a===void 0?y({contextDir:f}).pending():null;if(k?.kind==="cards"){let $=e.mode??"interactive";return!n.isTTY||$!=="interactive"?(P(n,`a held changeset for ${k.source} awaits review (${k.count} change(s)) \u2014 resume in a terminal: kane-cli maintain reconcile --apply [HELD_REVIEW]`),2):(t.cardApplyMount??Ve)(f)}let l=e.mode??"interactive";return Le(f,a===void 0?void 0:q(r,a),l,n,t)}let u=Me(f,r,e.from,e.sourceId);if("error"in u)return P(n,u.error),2;if(!i){let{sessionsHoldingSource:y}=await import("./sessions-GIEXOCE4.js"),{holders:k,corrupt:l}=y(f,u.sourceId);if(l>0)return P(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(k.length>0)return P(n,`session ${k[0]} holds item(s) for review pinned to ${u.sourceId} \u2014 finish that review first: kane-cli context extract --resume ${k[0]} [SOURCE_HELD]`),2}if(c==="interactive"&&!e.plan&&!i){let y=t.seams?.reingest??fe(f,u,n,t),k;try{k=await y(u.sourceId)}catch($){return P(n,$ instanceof Error?$.message:String($)),1}let l=k.status==="unchanged"?null:Re(f,u.sourceId);if(k.status!=="unchanged"&&!l)return n.out(`${u.sourceId} landed for the first time \u2014 extract it: kane-cli context extract --source ${u.sourceId}`),0;if(l){let x=await(t.chatMount??(async A=>{let{bindExtractInteractive:K}=await import("./extract-bind-YYIOEAYR.js");return K(A)}))({mode:"interactive",posture:"reconcile",source:u.sourceId,changeContext:l});if(x===3){let{sessionsHoldingSource:A}=await import("./sessions-GIEXOCE4.js");if(A(f,u.sourceId).holders.length===0)return 0}return x}}let E="remoteUrl"in u?{remoteUrl:u.remoteUrl}:{filePath:u.filePath},m=await Se(f,u.sourceId,E,n,t,!!e.plan||c==="interactive",c==="interactive"&&!e.plan);if(!m)return 1;let d=t.runDesignForUc??ie,R=t.runDesignForUc??null,b=t.sessionScript;if(!m.changed){let y=await je(f,u.sourceId,n,t,c,d,!!e.plan);if(y!==null)return y;if(Y(n,m,null,!1,t.emitEvent),c==="agent"){let k=t.emitEvent??(()=>{});F(k,m,null),k({...L})}return 0}let h=T(f),p=null;if(h!=null?p=X(f,{version:2,source_id:m.source_id,..."remoteUrl"in E?{remote_url:E.remoteUrl}:{backing_path:E.filePath},head_pin:h,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:m.skipped_arms,note:m.note,changeset:m.changeset,rows:m.rows,...m.held?{held:m.held}:{}}):P(n,"no chain head after extract \u2014 plan not stored"),c==="agent"){let y=t.emitEvent??(()=>{});if(!s)return F(y,m,p),y({...L}),0;let k=p?(l,$)=>O(p,l,$):void 0;return j(f,m,p,d,y,n,D(c),k)}if(!s)return p&&n.out(`plan stored: ${p}`),0;let g=m.changeset.filter(y=>y.kind==="ARCHIVE");if(c==="ci"&&g.length>0)return p&&n.out(`plan stored: ${p}`),P(n,V(g.length)),2;if(p){n.out(`plan stored: ${p}`);let y=p;return M(f,Ke(f,y)??m.rows,_,n,d,(k,l)=>O(y,k,l),m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}return M(f,m.rows,_,n,d,void 0,m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}function Ke(e,n){let t=N(e,n);return"error"in t?null:t.plan.rows}async function dn(e,n={},t,r=process.cwd()){if(e.mode==="agent"){let{makeHeadlessIO:i}=await import("./headless-io-66RG5NN5.js"),a=t?i("ndjson","reconcile",t):i("ndjson","reconcile"),o={out:a.out,err:v=>a.event({type:"error",message:v}),isTTY:!1,confirm:async()=>!1,ask:async()=>""},{runWithChannel:w}=await import("./run-channel-RGH4WIQX.js"),f=2;try{f=await w({event:v=>a.event(v)},()=>be(e,o,{...n,emitEvent:v=>a.event(v)},r))}catch(v){f=1,a.event({type:"error",message:v instanceof Error?v.message:String(v)})}return a.done(f)}return be(e,ke(),n,r)}export{Ae as a,Me as b,D as c,U as d,be as e,dn as f};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as A}from"./chunk-YCCUBQY4.js";import{a as _}from"./chunk-CZUOGGUK.js";import{a as B}from"./chunk-BPMSNGXQ.js";import{a as R}from"./chunk-AO3PBE2V.js";import{a as k}from"./chunk-OYJBABRV.js";import{x as c}from"./chunk-OFW3ZVTP.js";import{a as P}from"./chunk-HCBYKLMW.js";import{a as u,b as l}from"./chunk-C44QQJR4.js";import{a as J}from"./chunk-6YGTRKDT.js";import{e as L}from"./chunk-UR6MHSHU.js";var t=L(J(),1);var e=L(P(),1);function X(n,i,y,m){return{id:n,label:`${i} (${n}) \xB7 ${y} tests`,isActive:n===m}}function W({resolver:n,projectId:i,currentFolderId:y,env:m,onSelect:x,onCancel:w}){let[I,M]=(0,t.useState)([]),[$,d]=(0,t.useState)(!0),[O,g]=(0,t.useState)(!1),[U,N]=(0,t.useState)(null),[p,b]=(0,t.useState)("list"),[S,v]=(0,t.useState)(""),[E,f]=(0,t.useState)(null),h=(0,t.useRef)(!1);(0,t.useEffect)(()=>{if(!n){N("Login first to browse folders"),d(!1);return}let o=new AbortController;return d(!0),g(!0),(async()=>{try{let r=n.cached??await n.resolve();if(!r){N("Login first to browse folders"),d(!1),g(!1);return}let a=k(m),T=new B(a.tmsBaseUrl,r.username,r.access_key),F=(async function*(){if(o.signal.aborted)return;let s=await T.listFolders(i);yield{page:1,folders:s,totalLoaded:s.length,done:!0}})();for await(let s of F){if(d(!1),s.totalLoaded===0){h.current=!0,b("naming"),g(!1);return}M(s.folders.map(C=>X(C.id,C.name,C.test_cases_count,y))),s.done&&g(!1)}}catch(r){if(r?.name==="AbortError")return;N(r instanceof Error?r.message:String(r)),d(!1),g(!1)}})(),()=>o.abort()},[n,i,y,m]);let D=(0,t.useCallback)(o=>{let r=o.trim();if(!r){f("Name cannot be empty");return}if(!i){f("No project selected \u2014 pick a project first");return}f(null),b("creating"),(async()=>{try{if(!n)throw new Error("Not authenticated");let a=n.cached??await n.resolve();if(!a)throw new Error("Not authenticated");let T=k(m),s=await new B(T.tmsBaseUrl,a.username,a.access_key).createFolder(i,r);x(s.id,s.name)}catch(a){f(a instanceof Error?a.message:String(a)),b("naming")}})()},[n,i,m,x]),H=(0,t.useCallback)(()=>{v(""),f(null),h.current?w():b("list")},[w]);return p==="naming"||p==="creating"?(0,e.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:c.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:c.orange,bold:!0,children:"Create new folder"}),h.current&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.dim,children:"No folders yet \u2014 let's create one."})}),(0,e.jsxs)(u,{marginTop:1,children:[(0,e.jsx)(l,{color:c.dim,children:"Name: "}),p==="naming"?(0,e.jsx)(A,{value:S,onChange:o=>{v(o),E&&f(null)},onSubmit:D,onCancel:H}):(0,e.jsx)(l,{children:S})]}),E&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.red,children:E})}),p==="creating"&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.dim,children:"Creating..."})}),p==="naming"&&(0,e.jsx)(R,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:h.current?"cancel":"back"})]}):(0,e.jsx)(_,{title:"Folders",items:I,loading:$,loadingMore:O,preserveSelectionById:!0,error:U,itemNoun:"folders",onTab:()=>{h.current=!1,b("naming")},extraHint:"tab to create new",onSelect:o=>{let r=o.label.split(" (")[0];x(o.id,r)},onCancel:w})}export{X as a,W as b};
2
+ import{a as A}from"./chunk-YCCUBQY4.js";import{a as _}from"./chunk-PYHWCV2V.js";import{a as B}from"./chunk-BPMSNGXQ.js";import{a as R}from"./chunk-Q6743UUQ.js";import{a as k}from"./chunk-V5DYLGAM.js";import{x as c}from"./chunk-LPH4TERT.js";import{a as P}from"./chunk-HCBYKLMW.js";import{a as u,b as l}from"./chunk-C44QQJR4.js";import{a as J}from"./chunk-6YGTRKDT.js";import{e as L}from"./chunk-UR6MHSHU.js";var t=L(J(),1);var e=L(P(),1);function X(n,i,y,m){return{id:n,label:`${i} (${n}) \xB7 ${y} tests`,isActive:n===m}}function W({resolver:n,projectId:i,currentFolderId:y,env:m,onSelect:x,onCancel:w}){let[I,M]=(0,t.useState)([]),[$,d]=(0,t.useState)(!0),[O,g]=(0,t.useState)(!1),[U,N]=(0,t.useState)(null),[p,b]=(0,t.useState)("list"),[S,v]=(0,t.useState)(""),[E,f]=(0,t.useState)(null),h=(0,t.useRef)(!1);(0,t.useEffect)(()=>{if(!n){N("Login first to browse folders"),d(!1);return}let o=new AbortController;return d(!0),g(!0),(async()=>{try{let r=n.cached??await n.resolve();if(!r){N("Login first to browse folders"),d(!1),g(!1);return}let a=k(m),T=new B(a.tmsBaseUrl,r.username,r.access_key),F=(async function*(){if(o.signal.aborted)return;let s=await T.listFolders(i);yield{page:1,folders:s,totalLoaded:s.length,done:!0}})();for await(let s of F){if(d(!1),s.totalLoaded===0){h.current=!0,b("naming"),g(!1);return}M(s.folders.map(C=>X(C.id,C.name,C.test_cases_count,y))),s.done&&g(!1)}}catch(r){if(r?.name==="AbortError")return;N(r instanceof Error?r.message:String(r)),d(!1),g(!1)}})(),()=>o.abort()},[n,i,y,m]);let D=(0,t.useCallback)(o=>{let r=o.trim();if(!r){f("Name cannot be empty");return}if(!i){f("No project selected \u2014 pick a project first");return}f(null),b("creating"),(async()=>{try{if(!n)throw new Error("Not authenticated");let a=n.cached??await n.resolve();if(!a)throw new Error("Not authenticated");let T=k(m),s=await new B(T.tmsBaseUrl,a.username,a.access_key).createFolder(i,r);x(s.id,s.name)}catch(a){f(a instanceof Error?a.message:String(a)),b("naming")}})()},[n,i,m,x]),H=(0,t.useCallback)(()=>{v(""),f(null),h.current?w():b("list")},[w]);return p==="naming"||p==="creating"?(0,e.jsxs)(u,{flexDirection:"column",borderStyle:"round",borderColor:c.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(l,{color:c.orange,bold:!0,children:"Create new folder"}),h.current&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.dim,children:"No folders yet \u2014 let's create one."})}),(0,e.jsxs)(u,{marginTop:1,children:[(0,e.jsx)(l,{color:c.dim,children:"Name: "}),p==="naming"?(0,e.jsx)(A,{value:S,onChange:o=>{v(o),E&&f(null)},onSubmit:D,onCancel:H}):(0,e.jsx)(l,{children:S})]}),E&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.red,children:E})}),p==="creating"&&(0,e.jsx)(u,{marginTop:1,children:(0,e.jsx)(l,{color:c.dim,children:"Creating..."})}),p==="naming"&&(0,e.jsx)(R,{bindings:[{keys:"\u21B5",label:"create"}],escBackLabel:h.current?"cancel":"back"})]}):(0,e.jsx)(_,{title:"Folders",items:I,loading:$,loadingMore:O,preserveSelectionById:!0,error:U,itemNoun:"folders",onTab:()=>{h.current=!1,b("naming")},extraHint:"tab to create new",onSelect:o=>{let r=o.label.split(" (")[0];x(o.id,r)},onCancel:w})}export{X as a,W as b};
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as p,c as E,d as j,e as y,f as M,g as C,i as A,l as D,m as F,q as T,s as $,t as O}from"./chunk-DEZ7CXGM.js";import{c as H,d as z}from"./chunk-2YQ6TW77.js";import{a as k}from"./chunk-BRTARADN.js";import{p as B,q as R}from"./chunk-56PAQAX5.js";import{a as P}from"./chunk-OFW3ZVTP.js";import{e as q}from"./chunk-UR6MHSHU.js";import{existsSync as f,mkdirSync as V,readFileSync as Z,renameSync as N,writeFileSync as K}from"fs";import{join as Q}from"path";function fe(e){D(p(e));let t=p(e);if(!f(t))return;let n=Q(t,"meta.json"),r=y(e);if(f(n)&&!f(r))try{V(j(e),{recursive:!0}),N(n,r)}catch(o){process.stderr.write(`warn: meta.json migration failed: ${o.message}
3
- `)}let i=C(e);if(f(i)){let o="python";try{let c=new k().load();c.code_export?.language&&(o=c.code_export.language)}catch{}let a=M(e,"playwright",o);if(!f(a))try{N(i,a)}catch(c){process.stderr.write(`warn: generated-code migration failed: ${c.message}
2
+ import{b as p,c as j,d as M,e as y,f as C,g as A,i as D,l as F,o as T,q as $,r as O}from"./chunk-WHEWZR2C.js";import{c as H,d as z}from"./chunk-2YQ6TW77.js";import{a as E}from"./chunk-IPEA7ZOF.js";import{a as k}from"./chunk-O4IEPE3T.js";import{r as B,s as R}from"./chunk-RSSOJ3L2.js";import{a as P}from"./chunk-LPH4TERT.js";import{e as q}from"./chunk-UR6MHSHU.js";import{existsSync as f,mkdirSync as V,readFileSync as Z,renameSync as N,writeFileSync as K}from"fs";import{join as Q}from"path";function fe(e){F(p(e));let t=p(e);if(!f(t))return;let n=Q(t,"meta.json"),r=y(e);if(f(n)&&!f(r))try{V(M(e),{recursive:!0}),N(n,r)}catch(o){process.stderr.write(`warn: meta.json migration failed: ${o.message}
3
+ `)}let i=A(e);if(f(i)){let o="python";try{let c=new k().load();c.code_export?.language&&(o=c.code_export.language)}catch{}let a=C(e,"playwright",o);if(!f(a))try{N(i,a)}catch(c){process.stderr.write(`warn: generated-code migration failed: ${c.message}
4
4
  `)}}if(f(r))try{let o=JSON.parse(Z(r,"utf8"));"md5sum"in o&&(delete o.md5sum,K(r,JSON.stringify(o,null,2)+`
5
5
  `,"utf8"))}catch(o){process.stderr.write(`warn: meta.json md5sum strip failed: ${o.message}
6
- `)}}async function ye(e){if(!e.isInteractive)return{recovered:!1};if(W(e.creds))return{recovered:!1};let{SingleShotApp:t}=await import("./SingleShotApp-AY3XFEYT.js"),{ScrollbackProvider:n}=await import("./scrollback-JLPJR25X.js"),{render:r}=await import("./build-JIKYOZUH.js"),i=await import("./react-QWOAB3TB.js"),o={current:null},a={current:!1},{waitUntilExit:c,unmount:l}=r(i.default.createElement(n,null,i.default.createElement(t,{resultRef:o,mode:"login",loginCompleteRef:a})),{exitOnCtrlC:!1});R(()=>l()),await c();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),a.current?{recovered:!0}:(B(0,"Startup gate cancelled"),{recovered:!1})}function W(e){let t=e.getActiveProfile(),n=e.getDefaultEnv();if(!t||!!!(e.loadBasicAuth(t,n)||e.loadCredentials(t,n)))return!1;let i=e.loadProfileConfig(t,n)??{};return!!i.project_id&&!!i.folder_id}var J=q(H(),1);import{existsSync as v,readFileSync as U,readdirSync as X,statSync as Y}from"fs";import{dirname as ee,isAbsolute as te,join as g,relative as x,resolve as re,sep as h}from"path";import{createHash as ne}from"crypto";var S="testmd-bundle.json",d=class extends Error{constructor(t){super(t),this.name="BundleUsageError"}},_=e=>e.split(h).join("/");function I(e){if(!v(e))return[];let t=[];for(let n of X(e).sort()){let r=g(e,n);Y(r).isDirectory()?t.push(...I(r)):t.push(r)}return t}function se(e){let t=e.map(r=>ee(r).split(h)),n=t[0];for(let r of t.slice(1)){let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;n=n.slice(0,i)}return n.join(h)||h}function ie(e){for(let t of e){let n=F(t,U(t,"utf8"));for(let r of n.steps)if(r.body.kind==="import_ref"&&te(r.body.path))throw new d(`bundle sync: absolute @import is not portable after unzip: ${t} step ${r.index} (@import ${r.body.path})`)}}function G(e){let t=re(e),n=T(t);if(!n?.commit_id||!n?.test_id)throw new d(`bundle sync: ${t} is not authored \u2014 run \`kane-cli testmd run\` first (output-<stem>/.internal/meta.json needs commit_id + test_id)`);let r;try{r=O(t)}catch(s){throw s instanceof $?new d(`bundle sync: ${s.message}`):s}let i=[t];for(let s of r.steps)for(let u of s.trace.slice(1))i.includes(u.file)||i.push(u.file);ie(i);let o=[];for(let s of r.unitFiles){if(s.file===t)continue;let u=p(s.file);o.includes(u)||o.push(u)}let a=[...i],c=s=>{v(s)&&a.push(s)};c(E(t)),a.push(y(t)),c(g(p(t),".internal","execution.json")),a.push(...I(A(t)));for(let s of o)c(g(s,"Result.md")),a.push(...I(g(s,".internal","steps")));let l=se(a);if(v(g(l,S)))throw new d(`bundle sync: a real file named ${S} exists at the zip root (${l}) \u2014 it would collide with the generated manifest`);let b=a.map(s=>{let u=U(s);return{abs:s,rel:_(x(l,s)),sha256:ne("sha256").update(u).digest("hex"),bytes:u.length}}).sort((s,u)=>s.rel<u.rel?-1:1),m=_(x(l,t)),L={schema_version:2,entry:m,commit_id:n.commit_id,test_id:n.test_id,testcase_id:n.testcase_id??null,project_id:n.project_id??null,folder_id:n.folder_id??null,org_id:n.org_id??null,created_at:new Date().toISOString(),producer:{name:"kane-cli",version:P},files:b.map(s=>({path:s.rel,sha256:s.sha256,bytes:s.bytes})),units:r.unitFiles.filter(s=>s.file!==t).map(s=>({path:_(x(l,s.file)),kind:s.kind}))};return{zipRoot:l,entry:m,files:b,manifest:L}}var w=e=>e instanceof Error?e.message:String(e);function oe(e){return new Promise((t,n)=>{let r=(0,J.default)("zip",{zlib:{level:6}}),i=[];r.on("data",o=>i.push(o)),r.on("error",n),r.on("end",()=>t(Buffer.concat(i))),r.append(JSON.stringify(e.manifest,null,2)+`
6
+ `)}}async function ye(e){if(!e.isInteractive)return{recovered:!1};if(W(e.creds))return{recovered:!1};let{SingleShotApp:t}=await import("./SingleShotApp-VJVY3F4H.js"),{ScrollbackProvider:n}=await import("./scrollback-JLPJR25X.js"),{render:r}=await import("./build-JIKYOZUH.js"),i=await import("./react-QWOAB3TB.js"),o={current:null},a={current:!1},{waitUntilExit:c,unmount:l}=r(i.default.createElement(n,null,i.default.createElement(t,{resultRef:o,mode:"login",loginCompleteRef:a})),{exitOnCtrlC:!1});R(()=>l()),await c();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),a.current?{recovered:!0}:(B(0,"Startup gate cancelled"),{recovered:!1})}function W(e){let t=e.getActiveProfile(),n=e.getDefaultEnv();if(!t||!!!(e.loadBasicAuth(t,n)||e.loadCredentials(t,n)))return!1;let i=e.loadProfileConfig(t,n)??{};return!!i.project_id&&!!i.folder_id}var J=q(H(),1);import{existsSync as v,readFileSync as U,readdirSync as X,statSync as Y}from"fs";import{dirname as ee,isAbsolute as te,join as g,relative as x,resolve as re,sep as h}from"path";import{createHash as ne}from"crypto";var S="testmd-bundle.json",d=class extends Error{constructor(t){super(t),this.name="BundleUsageError"}},_=e=>e.split(h).join("/");function I(e){if(!v(e))return[];let t=[];for(let n of X(e).sort()){let r=g(e,n);Y(r).isDirectory()?t.push(...I(r)):t.push(r)}return t}function se(e){let t=e.map(r=>ee(r).split(h)),n=t[0];for(let r of t.slice(1)){let i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;n=n.slice(0,i)}return n.join(h)||h}function ie(e){for(let t of e){let n=E(t,U(t,"utf8"));for(let r of n.steps)if(r.body.kind==="import_ref"&&te(r.body.path))throw new d(`bundle sync: absolute @import is not portable after unzip: ${t} step ${r.index} (@import ${r.body.path})`)}}function G(e){let t=re(e),n=T(t);if(!n?.commit_id||!n?.test_id)throw new d(`bundle sync: ${t} is not authored \u2014 run \`kane-cli testmd run\` first (output-<stem>/.internal/meta.json needs commit_id + test_id)`);let r;try{r=O(t)}catch(s){throw s instanceof $?new d(`bundle sync: ${s.message}`):s}let i=[t];for(let s of r.steps)for(let u of s.trace.slice(1))i.includes(u.file)||i.push(u.file);ie(i);let o=[];for(let s of r.unitFiles){if(s.file===t)continue;let u=p(s.file);o.includes(u)||o.push(u)}let a=[...i],c=s=>{v(s)&&a.push(s)};c(j(t)),a.push(y(t)),c(g(p(t),".internal","execution.json")),a.push(...I(D(t)));for(let s of o)c(g(s,"Result.md")),a.push(...I(g(s,".internal","steps")));let l=se(a);if(v(g(l,S)))throw new d(`bundle sync: a real file named ${S} exists at the zip root (${l}) \u2014 it would collide with the generated manifest`);let b=a.map(s=>{let u=U(s);return{abs:s,rel:_(x(l,s)),sha256:ne("sha256").update(u).digest("hex"),bytes:u.length}}).sort((s,u)=>s.rel<u.rel?-1:1),m=_(x(l,t)),L={schema_version:2,entry:m,commit_id:n.commit_id,test_id:n.test_id,testcase_id:n.testcase_id??null,project_id:n.project_id??null,folder_id:n.folder_id??null,org_id:n.org_id??null,created_at:new Date().toISOString(),producer:{name:"kane-cli",version:P},files:b.map(s=>({path:s.rel,sha256:s.sha256,bytes:s.bytes})),units:r.unitFiles.filter(s=>s.file!==t).map(s=>({path:_(x(l,s.file)),kind:s.kind}))};return{zipRoot:l,entry:m,files:b,manifest:L}}var w=e=>e instanceof Error?e.message:String(e);function oe(e){return new Promise((t,n)=>{let r=(0,J.default)("zip",{zlib:{level:6}}),i=[];r.on("data",o=>i.push(o)),r.on("error",n),r.on("end",()=>t(Buffer.concat(i))),r.append(JSON.stringify(e.manifest,null,2)+`
7
7
  `,{name:S});for(let o of e.files)r.file(o.abs,{name:o.rel});r.finalize()})}async function ae(e){let{plan:t,controller:n,testId:r,sessionId:i,commitId:o}=e,a;try{a=await oe(t)}catch(l){return{ok:!1,stage:"zip",error:w(l)}}let c;try{let l={key:"testmd",content_type:"application/zip",filename:`${o}-testmd.zip`},m=(await n.getPresignedUrls(r,i,[l])).urls?.testmd?.upload_url;if(!m)return{ok:!1,stage:"presign",error:"presign response missing testmd upload_url"};c=m}catch(l){return{ok:!1,stage:"presign",error:w(l)}}try{await z(c,a,"application/zip")}catch(l){return{ok:!1,stage:"upload",error:w(l)}}return{ok:!0,bytes:a.length}}async function Ee(e){let t;try{t=G(e.sourcePath)}catch(n){return n instanceof d?{ok:!1,stage:"collect",error:n.message}:{ok:!1,stage:"collect",error:w(n)}}return ae({...e,plan:t})}function je(e){return e.shouldUploadPipeline&&e.uploadSucceeded&&!!e.metaCommitId&&!!e.metaTestId}export{fe as a,ye as b,G as c,Ee as d,je as e};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as O}from"./chunk-DBIBROYW.js";import{a as $}from"./chunk-WXHQYYD5.js";import{a as E,b as N}from"./chunk-IAHKTEET.js";import{closeSync as S,existsSync as F,fsyncSync as k,mkdirSync as P,openSync as q,readFileSync as p,readdirSync as T,renameSync as R,rmSync as v,writeFileSync as A}from"fs";import{join as u}from"path";var i=class extends Error{};function _(e,t){if(e.schema_version!==void 0&&e.schema_version!==$)throw new i(`record ${t} is stamped ${e.schema_version}, this build reads ${$} \u2014 migrate explicitly`);if(e.parents!==void 0&&!(e.prev_hash===null?e.parents.length===0:e.parents.length===1&&e.parents[0]===e.prev_hash))throw new i(`record ${t}: parents does not mirror prev_hash \u2014 multi-parent records need a DAG-aware reader`)}var C=class extends i{},b=class extends i{code="CONTEXT_APPEND_BUSY"};function I(e,t){P(e,{recursive:!0});let r=u(e,".lock"),c=Date.now()+(t?t.deadlineMs:2e3);for(;;)try{let o=q(r,"wx");return A(o,`${process.pid}
3
- `),S(o),()=>{try{v(r)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;if(t){let n=null,a=null;try{a=p(r,"utf8");let h=Number.parseInt(a.trim(),10);n=Number.isInteger(h)?h:null}catch{a=null}if(a!==null&&(n===null||!O(n))){let h=`${r}.break-${process.pid}-${Date.now()}`;try{R(r,h);let s=null;try{s=p(h,"utf8")}catch{s=null}if(s===null||s===a)v(h,{force:!0});else try{R(h,r)}catch{v(h,{force:!0})}}catch(s){if(s.code!=="ENOENT")throw s}continue}if(Date.now()>c)throw new b(`.context append is busy: ${r} held by live pid ${String(n)} past the deadline`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25+Math.floor(Math.random()*50));continue}if(Date.now()>c)throw new i(`.context is locked by another process \u2014 remove ${r} if that process is gone`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25)}}var j=/^\d{6}-[0-9a-f]{12}\.json$/,f=e=>u(e,"commits");function w(e){return"sha256:"+N(Buffer.from(E(e),"utf8"))}function y(e){let t=f(e);return F(t)?T(t).filter(r=>j.test(r)).sort():[]}function H(e){let t=y(e),r=[],c=[],o=null;return t.forEach((n,a)=>{let h=p(u(f(e),n),"utf8"),s;try{s=JSON.parse(h)}catch(d){throw new i(`corrupt commit record ${n}: ${String(d)}`)}if(s.seq!==a+1)throw new i(`sequence gap: expected seq ${a+1}, ${n} has ${s.seq}`);if(s.prev_hash!==o)throw new i(`broken chain at ${n}: prev_hash ${String(s.prev_hash)} != ${String(o)}`);_(s,n);let m=w(s),l=n.slice(7,19);if(!m.slice(7).startsWith(l))throw new i(`tampered record ${n}: content hash ${m} does not match filename`);r.push(s),c.push(m),o=m}),{records:r,hashes:c}}function J(e){let t=y(e);if(t.length===0)return null;let r=t[t.length-1],c=p(u(f(e),r),"utf8"),o;try{o=JSON.parse(c)}catch(a){throw new i(`corrupt tail record ${r}: ${String(a)}`)}_(o,r);let n=w(o);if(!n.slice(7).startsWith(r.slice(7,19)))throw new i(`tampered tail record ${r}: content hash ${n} does not match filename`);if(o.seq!==t.length)throw new i(`sequence gap at tail: ${t.length} record files but tail seq is ${o.seq}`);return{seq:o.seq,hash:n}}function U(e){return J(e)?.hash??null}function B(e,t,r){let c=y(e);if(c.length<t)throw new i(`derived state is ahead of the record log (applied seq ${t}, ${c.length} records) \u2014 run kane-cli context rebuild`);let o=[],n=[],a=r;for(let h=t;h<c.length;h++){let s=c[h],m=p(u(f(e),s),"utf8"),l;try{l=JSON.parse(m)}catch(g){throw new i(`corrupt commit record ${s}: ${String(g)}`)}if(l.seq!==h+1)throw new i(`sequence gap: expected seq ${h+1}, ${s} has ${l.seq}`);if(l.prev_hash!==a)throw new i(`broken chain at ${s}: prev_hash ${String(l.prev_hash)} != ${String(a)}`);_(l,s);let d=w(l);if(!d.slice(7).startsWith(s.slice(7,19)))throw new i(`tampered record ${s}: content hash ${d} does not match filename`);o.push(l),n.push(d),a=d}return{records:o,hashes:n}}function V(e,t){if(t.seq===0){if(t.hash!==null)throw new i("watermark not in chain: seq 0 cannot carry a hash");return H(e)}let r=y(e);if(r.length<t.seq)throw new i(`watermark not in chain: seq ${t.seq} is beyond the ${r.length}-record chain`);let c=r[t.seq-1],o;try{o=JSON.parse(p(u(f(e),c),"utf8"))}catch(a){throw new i(`watermark record ${c} unreadable: ${String(a)}`)}let n=w(o);if(n!==t.hash)throw new i(`watermark not in chain: seq ${t.seq} hashes ${n}, watermark claims ${String(t.hash)}`);return B(e,t.seq,t.hash)}function Y(e,t,r){let c=I(e,r.busyRetry);try{return M(e,t,r)}finally{c()}}function K(e,t){let r=I(e);try{return M(e,t,{})}finally{r()}}function M(e,t,r){let c=J(e),o=(c?.seq??0)+1,n=c?.hash??null;if(r.expectPrev!==void 0&&r.expectPrev!==n)throw new C(`concurrent append detected: validated against ${String(r.expectPrev)} but the chain head is ${String(n)} \u2014 re-open and retry`);let a={seq:o,prev_hash:n,...t,schema_version:$,parents:n===null?[]:[n]},h=w(a),s=f(e);P(s,{recursive:!0});let m=`${String(o).padStart(6,"0")}-${h.slice(7,19)}.json`,l=u(s,m),d=l+".tmp",g=q(d,"w");try{A(g,JSON.stringify(a)+`
4
- `),k(g)}finally{S(g)}R(d,l);try{let x=q(s,"r");k(x),S(x)}catch{}return{seq:o,hash:h,file:l,record:a}}export{i as a,C as b,b as c,H as d,J as e,U as f,B as g,V as h,Y as i,K as j};
2
+ import{b as O}from"./chunk-DBIBROYW.js";import{a as $}from"./chunk-AKX4VRRR.js";import{a as E,b as N}from"./chunk-IAHKTEET.js";import{closeSync as S,existsSync as F,fsyncSync as k,mkdirSync as P,openSync as q,readFileSync as p,readdirSync as T,renameSync as R,rmSync as v,writeFileSync as A}from"fs";import{join as u}from"path";var i=class extends Error{};function x(e,t){if(e.schema_version!==void 0&&e.schema_version!==$)throw new i(`record ${t} is stamped ${e.schema_version}, this build reads ${$} \u2014 migrate explicitly`);if(e.parents!==void 0&&!(e.prev_hash===null?e.parents.length===0:e.parents.length===1&&e.parents[0]===e.prev_hash))throw new i(`record ${t}: parents does not mirror prev_hash \u2014 multi-parent records need a DAG-aware reader`)}var C=class extends i{},b=class extends i{code="CONTEXT_APPEND_BUSY"};function I(e,t){P(e,{recursive:!0});let r=u(e,".lock"),c=Date.now()+(t?t.deadlineMs:2e3);for(;;)try{let o=q(r,"wx");return A(o,`${process.pid}
3
+ `),S(o),()=>{try{v(r)}catch{}}}catch(o){if(o.code!=="EEXIST")throw o;if(t){let n=null,a=null;try{a=p(r,"utf8");let h=Number.parseInt(a.trim(),10);n=Number.isInteger(h)?h:null}catch{a=null}if(a!==null&&(n===null||!O(n))){let h=`${r}.break-${process.pid}-${Date.now()}`;try{R(r,h);let s=null;try{s=p(h,"utf8")}catch{s=null}if(s===null||s===a)v(h,{force:!0});else try{R(h,r)}catch{v(h,{force:!0})}}catch(s){if(s.code!=="ENOENT")throw s}continue}if(Date.now()>c)throw new b(`.context append is busy: ${r} held by live pid ${String(n)} past the deadline`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25+Math.floor(Math.random()*50));continue}if(Date.now()>c)throw new i(`.context is locked by another process \u2014 remove ${r} if that process is gone`);Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25)}}var j=/^\d{6}-[0-9a-f]{12}\.json$/,f=e=>u(e,"commits");function w(e){return"sha256:"+N(Buffer.from(E(e),"utf8"))}function y(e){let t=f(e);return F(t)?T(t).filter(r=>j.test(r)).sort():[]}function H(e){let t=y(e),r=[],c=[],o=null;return t.forEach((n,a)=>{let h=p(u(f(e),n),"utf8"),s;try{s=JSON.parse(h)}catch(d){throw new i(`corrupt commit record ${n}: ${String(d)}`)}if(s.seq!==a+1)throw new i(`sequence gap: expected seq ${a+1}, ${n} has ${s.seq}`);if(s.prev_hash!==o)throw new i(`broken chain at ${n}: prev_hash ${String(s.prev_hash)} != ${String(o)}`);x(s,n);let m=w(s),l=n.slice(7,19);if(!m.slice(7).startsWith(l))throw new i(`tampered record ${n}: content hash ${m} does not match filename`);r.push(s),c.push(m),o=m}),{records:r,hashes:c}}function J(e){let t=y(e);if(t.length===0)return null;let r=t[t.length-1],c=p(u(f(e),r),"utf8"),o;try{o=JSON.parse(c)}catch(a){throw new i(`corrupt tail record ${r}: ${String(a)}`)}x(o,r);let n=w(o);if(!n.slice(7).startsWith(r.slice(7,19)))throw new i(`tampered tail record ${r}: content hash ${n} does not match filename`);if(o.seq!==t.length)throw new i(`sequence gap at tail: ${t.length} record files but tail seq is ${o.seq}`);return{seq:o.seq,hash:n}}function U(e){return J(e)?.hash??null}function B(e,t,r){let c=y(e);if(c.length<t)throw new i(`derived state is ahead of the record log (applied seq ${t}, ${c.length} records) \u2014 run kane-cli context rebuild`);let o=[],n=[],a=r;for(let h=t;h<c.length;h++){let s=c[h],m=p(u(f(e),s),"utf8"),l;try{l=JSON.parse(m)}catch(g){throw new i(`corrupt commit record ${s}: ${String(g)}`)}if(l.seq!==h+1)throw new i(`sequence gap: expected seq ${h+1}, ${s} has ${l.seq}`);if(l.prev_hash!==a)throw new i(`broken chain at ${s}: prev_hash ${String(l.prev_hash)} != ${String(a)}`);x(l,s);let d=w(l);if(!d.slice(7).startsWith(s.slice(7,19)))throw new i(`tampered record ${s}: content hash ${d} does not match filename`);o.push(l),n.push(d),a=d}return{records:o,hashes:n}}function V(e,t){if(t.seq===0){if(t.hash!==null)throw new i("watermark not in chain: seq 0 cannot carry a hash");return H(e)}let r=y(e);if(r.length<t.seq)throw new i(`watermark not in chain: seq ${t.seq} is beyond the ${r.length}-record chain`);let c=r[t.seq-1],o;try{o=JSON.parse(p(u(f(e),c),"utf8"))}catch(a){throw new i(`watermark record ${c} unreadable: ${String(a)}`)}let n=w(o);if(n!==t.hash)throw new i(`watermark not in chain: seq ${t.seq} hashes ${n}, watermark claims ${String(t.hash)}`);return B(e,t.seq,t.hash)}function Y(e,t,r){let c=I(e,r.busyRetry);try{return M(e,t,r)}finally{c()}}function K(e,t){let r=I(e);try{return M(e,t,{})}finally{r()}}function M(e,t,r){let c=J(e),o=(c?.seq??0)+1,n=c?.hash??null;if(r.expectPrev!==void 0&&r.expectPrev!==n)throw new C(`concurrent append detected: validated against ${String(r.expectPrev)} but the chain head is ${String(n)} \u2014 re-open and retry`);let a={seq:o,prev_hash:n,...t,schema_version:$,parents:n===null?[]:[n]},h=w(a),s=f(e);P(s,{recursive:!0});let m=`${String(o).padStart(6,"0")}-${h.slice(7,19)}.json`,l=u(s,m),d=l+".tmp",g=q(d,"w");try{A(g,JSON.stringify(a)+`
4
+ `),k(g)}finally{S(g)}R(d,l);try{let _=q(s,"r");k(_),S(_)}catch{}return{seq:o,hash:h,file:l,record:a}}export{i as a,C as b,b as c,I as d,H as e,J as f,U as g,B as h,V as i,Y as j,K as k};