@testmuai/kane-cli 0.8.11 → 0.8.12

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 (213) hide show
  1. package/dist/{ChatSurface-YFJDAXOG.js → ChatSurface-DALSIICW.js} +1 -1
  2. package/dist/{ChromeProfilePicker-PUCZN6WU.js → ChromeProfilePicker-ZMVZH3AK.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-JAIB5MHS.js → CliFeedbackPrompt-K66H7YE6.js} +1 -1
  4. package/dist/{CliUploadProgress-53LQMQJD.js → CliUploadProgress-5DZHZY4M.js} +1 -1
  5. package/dist/{ConfigView-7HFP4OXS.js → ConfigView-S5KBV62S.js} +1 -1
  6. package/dist/EvidenceViewOffer-UACWB3YJ.js +2 -0
  7. package/dist/FolderPicker-YH5TKMX3.js +2 -0
  8. package/dist/{InfoBox-62YG3YNQ.js → InfoBox-7PAM2FQH.js} +1 -1
  9. package/dist/{LinksBox-6NS3GHWO.js → LinksBox-2NVZ3FHJ.js} +1 -1
  10. package/dist/{ProfilesView-HIKK2HPC.js → ProfilesView-SIUBF7IU.js} +1 -1
  11. package/dist/{ProjectPicker-2CJMO5TD.js → ProjectPicker-5NI554X3.js} +1 -1
  12. package/dist/{SaveSessionPrompt-4DTPZSXD.js → SaveSessionPrompt-5OULBV5N.js} +1 -1
  13. package/dist/SingleShotApp-LA3EMPUK.js +2 -0
  14. package/dist/{SummaryBox-A6LKKQXJ.js → SummaryBox-GTGF3CBO.js} +1 -1
  15. package/dist/TestMdRunView-5MNKJJMS.js +2 -0
  16. package/dist/{TestrunEvidenceTable-7SCCTZPH.js → TestrunEvidenceTable-7WBCOGYW.js} +1 -1
  17. package/dist/{WhoamiView-PDMQ6F5N.js → WhoamiView-E2SVBHLC.js} +1 -1
  18. package/dist/{app-download-K2ELUXWR.js → app-download-SAXSYXIV.js} +1 -1
  19. package/dist/{auth-5WJSFLCP.js → auth-3LLVDHOJ.js} +1 -1
  20. package/dist/{binary-QVQRWQFK.js → binary-WSMIRJNC.js} +1 -1
  21. package/dist/{bind-5WELCZ4S.js → bind-A3M4PV4V.js} +3 -3
  22. package/dist/{bootstrap-3LNHRDQH.js → bootstrap-QTVHGL45.js} +1 -1
  23. package/dist/bridge-E2C5VV3H.js +2 -0
  24. package/dist/{changelog-TK6DWFVW.js → changelog-CNYWOB2V.js} +1 -1
  25. package/dist/{chat-committer-MAW25ICC.js → chat-committer-RAOIL2T6.js} +1 -1
  26. package/dist/chat-controller-YJCNU76T.js +2 -0
  27. package/dist/{chunk-5LEO463W.js → chunk-24QPDHRD.js} +1 -1
  28. package/dist/{chunk-DLJIML73.js → chunk-2LXJ2ZM3.js} +1 -1
  29. package/dist/{chunk-GSNGC7HI.js → chunk-2MTAXT2U.js} +1 -1
  30. package/dist/{chunk-5NBT5IVT.js → chunk-3CCD434H.js} +1 -1
  31. package/dist/{chunk-K6BWPGBO.js → chunk-3G3LY6BM.js} +1 -1
  32. package/dist/{chunk-2E55VQYA.js → chunk-3N2YOHD6.js} +1 -1
  33. package/dist/{chunk-OC7TJTQG.js → chunk-3OU2F34I.js} +1 -1
  34. package/dist/{chunk-DHWS7SLT.js → chunk-3XWKKSIM.js} +2 -2
  35. package/dist/{chunk-TB2CCKL7.js → chunk-43DM2I6Q.js} +1 -1
  36. package/dist/{chunk-WRVDIZAI.js → chunk-4ASRA7CD.js} +2 -2
  37. package/dist/{chunk-ZMJD3CI7.js → chunk-4E4GJPEM.js} +1 -1
  38. package/dist/{chunk-CABRAZOL.js → chunk-4O6XBS5G.js} +1 -1
  39. package/dist/{chunk-DJJO4IHY.js → chunk-4T35SA2O.js} +1 -1
  40. package/dist/{chunk-YSNBXUM6.js → chunk-4TZSEC2C.js} +1 -1
  41. package/dist/{chunk-3D7VYEDP.js → chunk-54JZ6VEW.js} +1 -1
  42. package/dist/{chunk-FIODM24X.js → chunk-5A4QG7ZM.js} +1 -1
  43. package/dist/{chunk-A76UL3EN.js → chunk-5AHOVOWV.js} +1 -1
  44. package/dist/{chunk-6DOS5CJ5.js → chunk-5FYO3PFG.js} +1 -1
  45. package/dist/{chunk-QHSF2CXK.js → chunk-5G22NOZK.js} +1 -1
  46. package/dist/{chunk-47WY2637.js → chunk-5KLDW3ZW.js} +58 -57
  47. package/dist/{chunk-7P3JGF2X.js → chunk-6A47PRDS.js} +1 -1
  48. package/dist/{chunk-FYLMTZ3J.js → chunk-6FCPS2VT.js} +1 -1
  49. package/dist/{chunk-A4BDLZOD.js → chunk-75HF3GPO.js} +1 -1
  50. package/dist/{chunk-BE4FBVKY.js → chunk-7KAPHA56.js} +1 -1
  51. package/dist/{chunk-3FJNTRAS.js → chunk-7NXHVC7G.js} +1 -1
  52. package/dist/{chunk-Y4ODYIOP.js → chunk-7R5K4IGS.js} +1 -1
  53. package/dist/{chunk-JJJREAFQ.js → chunk-7RFGO3TH.js} +1 -1
  54. package/dist/{chunk-NVRXDLJN.js → chunk-AFNDJK2A.js} +1 -1
  55. package/dist/{chunk-X6WB2QTT.js → chunk-AHRL4E3M.js} +1 -1
  56. package/dist/{chunk-7KRCBN6X.js → chunk-APZCLVZD.js} +1 -1
  57. package/dist/{chunk-4VZRBBLF.js → chunk-ASYWKYTQ.js} +1 -1
  58. package/dist/{chunk-QIRZBOKA.js → chunk-COVIEKZN.js} +1 -1
  59. package/dist/{chunk-HJBORIFP.js → chunk-CQ3ZQ5UK.js} +3 -3
  60. package/dist/{chunk-4FXSDPQW.js → chunk-DYXYNH6X.js} +1 -1
  61. package/dist/{chunk-OKBEMFAW.js → chunk-EEFZXZTZ.js} +1 -1
  62. package/dist/{chunk-DP7GPS6S.js → chunk-EV64VI66.js} +1 -1
  63. package/dist/{chunk-7HUJVIMO.js → chunk-F2CET54H.js} +2 -2
  64. package/dist/{chunk-NYUMJDCE.js → chunk-FAREJ4P2.js} +1 -1
  65. package/dist/{chunk-CRPBARFG.js → chunk-FBYB3SRE.js} +1 -1
  66. package/dist/{chunk-TSW5A7W3.js → chunk-FHYG3QLL.js} +1 -1
  67. package/dist/{chunk-NLSR2IFN.js → chunk-G2Q2TP3O.js} +1 -1
  68. package/dist/{chunk-F7R6A6P5.js → chunk-G52YPXKT.js} +1 -1
  69. package/dist/{chunk-XB7EMX6J.js → chunk-GNAPBOAJ.js} +1 -1
  70. package/dist/chunk-GRDYYYIQ.js +2 -0
  71. package/dist/{chunk-2ZBY2GME.js → chunk-H6NHARB4.js} +1 -1
  72. package/dist/chunk-H6VS5RYO.js +11 -0
  73. package/dist/{chunk-3PMEHGH3.js → chunk-HPUQJRDX.js} +1 -1
  74. package/dist/{chunk-GV5BX2IQ.js → chunk-HWHLKBUT.js} +1 -1
  75. package/dist/{chunk-VGLY4HWA.js → chunk-I57TM22L.js} +1 -1
  76. package/dist/{chunk-OGJ6ZSLC.js → chunk-IE4BCGUE.js} +1 -1
  77. package/dist/{chunk-M3Q7IQMS.js → chunk-IGW77FMB.js} +1 -1
  78. package/dist/{chunk-B7K5WOOU.js → chunk-IVQX3AKL.js} +1 -1
  79. package/dist/{chunk-ZES42R57.js → chunk-IWVA37B6.js} +1 -1
  80. package/dist/{chunk-CQKKDIKA.js → chunk-JDGBRACP.js} +1 -1
  81. package/dist/{chunk-Z6GMZOVL.js → chunk-JOATASPP.js} +3 -3
  82. package/dist/{chunk-S63XGGBE.js → chunk-KAZGHWGK.js} +1 -1
  83. package/dist/{chunk-Z4QLCWLB.js → chunk-KGKJU27A.js} +1 -1
  84. package/dist/{chunk-JAO7TZBV.js → chunk-L2BCQQLJ.js} +1 -1
  85. package/dist/{chunk-OKCULEBD.js → chunk-L7GAZQYL.js} +1 -1
  86. package/dist/{chunk-7B7OSHPX.js → chunk-LLY7TQSI.js} +1 -1
  87. package/dist/{chunk-CBLUNSF4.js → chunk-M4WSRYRA.js} +1 -1
  88. package/dist/{chunk-FQRWYXFG.js → chunk-MMQLVGUJ.js} +1 -1
  89. package/dist/{chunk-6GH4DRKR.js → chunk-N7Z7BQYO.js} +1 -1
  90. package/dist/{chunk-DEUDRSU7.js → chunk-NJJQL54J.js} +1 -1
  91. package/dist/{chunk-GMXM4WHF.js → chunk-NSD2H67E.js} +1 -1
  92. package/dist/{chunk-YELGHSVH.js → chunk-O5U6EAL3.js} +1 -1
  93. package/dist/{chunk-4VYWTTT4.js → chunk-O7U5BVX5.js} +2 -2
  94. package/dist/{chunk-4AZ7IG2A.js → chunk-QZRHXGNI.js} +1 -1
  95. package/dist/{chunk-SNKFWPEM.js → chunk-RV7Q4RUV.js} +2 -2
  96. package/dist/{chunk-IX4FH5W6.js → chunk-SA6EDKUF.js} +1 -1
  97. package/dist/{chunk-O7RB4X6I.js → chunk-SACCB44S.js} +2 -2
  98. package/dist/{chunk-2QSG5ZG6.js → chunk-TLFNUXKS.js} +1 -1
  99. package/dist/chunk-U27OWZPW.js +368 -0
  100. package/dist/{chunk-HFRMJP2P.js → chunk-U2CIXGZR.js} +1 -1
  101. package/dist/{chunk-G5ZGEZCA.js → chunk-UDFDTFBL.js} +1 -1
  102. package/dist/{chunk-TYRTD5DD.js → chunk-UH2ZTX4E.js} +1 -1
  103. package/dist/{chunk-CL3AMEK6.js → chunk-UZXCCO7V.js} +1 -1
  104. package/dist/{chunk-YQ4MRF57.js → chunk-VDM3TWF6.js} +4 -4
  105. package/dist/{chunk-ASK4AZFC.js → chunk-VG7BTA5G.js} +1 -1
  106. package/dist/{chunk-R4EGL7VM.js → chunk-W3Z7AZNT.js} +1 -1
  107. package/dist/{chunk-VUOAFV27.js → chunk-WHYEXCTG.js} +1 -1
  108. package/dist/{chunk-HULEZ3D3.js → chunk-WIAZN7G4.js} +1 -1
  109. package/dist/{chunk-M7CGNE2D.js → chunk-WMVPJWWA.js} +1 -1
  110. package/dist/{chunk-4SXJKDHO.js → chunk-X6APRDUM.js} +2 -2
  111. package/dist/{chunk-OXHMUZJV.js → chunk-XMTSHHYQ.js} +1 -1
  112. package/dist/{chunk-B7TJIUKZ.js → chunk-XWO5MDEU.js} +1 -1
  113. package/dist/{chunk-AXW3WDFO.js → chunk-YF26DH4Z.js} +1 -1
  114. package/dist/{chunk-W7NI6JCF.js → chunk-YTAAF62A.js} +1 -1
  115. package/dist/{chunk-XYSFPVJX.js → chunk-ZVJGHQNG.js} +1 -1
  116. package/dist/{chunk-NGASEXVA.js → chunk-ZVZHE7KH.js} +2 -2
  117. package/dist/{chunk-W4IRHQGO.js → chunk-ZXN67F4U.js} +1 -1
  118. package/dist/{chunk-URLZULC7.js → chunk-ZZI4Y3CX.js} +1 -1
  119. package/dist/{committer-42AFWMEX.js → committer-C6UCDYMC.js} +1 -1
  120. package/dist/{config-KU2UICMC.js → config-HUK7V364.js} +1 -1
  121. package/dist/{cover-cmd-HAOBK2IC.js → cover-cmd-5LPHIOSI.js} +1 -1
  122. package/dist/{credentials-BEC4I5SE.js → credentials-6DP4KAMJ.js} +1 -1
  123. package/dist/{deps-bundle-EY5T7OH3.js → deps-bundle-PZNXSKLC.js} +1 -1
  124. package/dist/{deps-resolve-MPLFFCZZ.js → deps-resolve-62XK3LKV.js} +1 -1
  125. package/dist/design-committer-UPC6NZUF.js +2 -0
  126. package/dist/dispatch-7JCKGQVC.js +2 -0
  127. package/dist/{doctor-JBXA6WNL.js → doctor-ZQQ4VMPY.js} +1 -1
  128. package/dist/docx-convert-BIV5T7F5.js +1 -1
  129. package/dist/{dossier-WSWXZAPL.js → dossier-Y6TJWFZU.js} +1 -1
  130. package/dist/{evidence-MJV3PY2J.js → evidence-YAXIWZ6A.js} +1 -1
  131. package/dist/evolve-cmd-5ACHYQPE.js +2 -0
  132. package/dist/explain-3HAZY7Q6.js +2 -0
  133. package/dist/{explain-cmd-BXFR5DB6.js → explain-cmd-RMJPXD4U.js} +1 -1
  134. package/dist/{explain-cmd-IRQ2YX5L.js → explain-cmd-XCRO4AS6.js} +1 -1
  135. package/dist/{extract-bind-PPMY4FFA.js → extract-bind-BF2G6AS6.js} +3 -3
  136. package/dist/{extract-cmd-RHVLPNQB.js → extract-cmd-IPBCCR3T.js} +2 -2
  137. package/dist/{feeder-52VBZY3R.js → feeder-IOR3XRNF.js} +1 -1
  138. package/dist/{gaps-cmd-MSDGU6OU.js → gaps-cmd-3WXL6PAW.js} +1 -1
  139. package/dist/{generate-headless-NSK32S53.js → generate-headless-CLMSXEAS.js} +2 -2
  140. package/dist/index.js +115 -110
  141. package/dist/ingest-TTUQ7UDK.js +2 -0
  142. package/dist/ingest-cmd-KP5M6XTA.js +2 -0
  143. package/dist/install-5VWCH5GW.js +2 -0
  144. package/dist/{interactive-bind-4FNW3OYT.js → interactive-bind-MOV2VWHJ.js} +4 -4
  145. package/dist/{lifecycle-cmd-HYNG5KH6.js → lifecycle-cmd-KSMETBPP.js} +1 -1
  146. package/dist/{list-cmd-Y4WEOT3E.js → list-cmd-V3HJ5K4O.js} +1 -1
  147. package/dist/{list-commands-CJCEW7MQ.js → list-commands-KUDSKVP5.js} +1 -1
  148. package/dist/{logical-ids-N3UZACB4.js → logical-ids-MLXAH45L.js} +1 -1
  149. package/dist/login-flow-GZ3XHVCS.js +2 -0
  150. package/dist/{maintenance-cmd-UJNH47SG.js → maintenance-cmd-VFYGKY3X.js} +1 -1
  151. package/dist/{mobile-prompts-SJZVJWSB.js → mobile-prompts-WJVFBWW5.js} +1 -1
  152. package/dist/objective-variable-gate-GCQYYM77.js +2 -0
  153. package/dist/{persist-recorded-session-FWBAOQEF.js → persist-recorded-session-MHLD4A32.js} +1 -1
  154. package/dist/{phase-seed-2WI7KUYO.js → phase-seed-BMOSAA74.js} +1 -1
  155. package/dist/pipeline-G7KWRK2G.js +2 -0
  156. package/dist/prepare-target-SQ5IGKXD.js +2 -0
  157. package/dist/readmodel-TDRFVDVI.js +2 -0
  158. package/dist/reconcile-cmd-NI3AYU3Y.js +2 -0
  159. package/dist/{reconcile-deps-GMQA6ULT.js → reconcile-deps-DCHUFIEC.js} +2 -2
  160. package/dist/{reconcile-engine-XLLYS5ZB.js → reconcile-engine-QXUKUKSL.js} +1 -1
  161. package/dist/{recording-banner-CQBXZMT3.js → recording-banner-4H4AL6YN.js} +1 -1
  162. package/dist/{records-EW4PIJ5W.js → records-JLS63SDI.js} +1 -1
  163. package/dist/registry-R6QNPI5E.js +2 -0
  164. package/dist/{require-project-folder-K3E3QIOZ.js → require-project-folder-G2G4WKWW.js} +1 -1
  165. package/dist/{resolve-run-intent-3CENNCF3.js → resolve-run-intent-MZRPYN4V.js} +1 -1
  166. package/dist/{resolver-PSNP72H4.js → resolver-X5NHNX5O.js} +1 -1
  167. package/dist/{revert-RXHWWUMQ.js → revert-PRR3D4XM.js} +1 -1
  168. package/dist/{review-cmd-JUOWTME4.js → review-cmd-SAGIKWEW.js} +1 -1
  169. package/dist/run-PBS2J4N4.js +2 -0
  170. package/dist/run-VTUYLPSG.js +2 -0
  171. package/dist/{run-test-md-XBM6RMCI.js → run-test-md-4VRH7FU5.js} +2 -2
  172. package/dist/{sessions-cmd-PGE6LP2W.js → sessions-cmd-VDQGRBEM.js} +1 -1
  173. package/dist/{skill-installer-FBOPYFYS.js → skill-installer-WPW6NDCR.js} +1 -1
  174. package/dist/{spawner-URQ5OAY7.js → spawner-R3XOP3GP.js} +1 -1
  175. package/dist/{structured-answers-BZWJUX22.js → structured-answers-YAVW65G4.js} +1 -1
  176. package/dist/tcg-generate-HIC5AA3L.js +2 -0
  177. package/dist/testmd-actions-VOSP7L74.js +2 -0
  178. package/dist/{testmd-sync-TPUBEORI.js → testmd-sync-GNCDKPQN.js} +1 -1
  179. package/dist/token-refresh-GSFVJ6GU.js +2 -0
  180. package/dist/{validate-basic-BXBHTTTO.js → validate-basic-YNGP5JFB.js} +1 -1
  181. package/dist/variable-receipt-2VCUG7NN.js +2 -0
  182. package/dist/verdicts-PRXUKSDV.js +2 -0
  183. package/dist/{version-check-BGHE3LAK.js → version-check-GUGRBTIH.js} +1 -1
  184. package/dist/{view-cmd-XD5ENSML.js → view-cmd-SXXNDZIC.js} +1 -1
  185. package/dist/{walk-session-EYBUURRA.js → walk-session-G3DLBR24.js} +1 -1
  186. package/dist/{with-telemetry-L3SO6J3L.js → with-telemetry-5Y2CVPXK.js} +1 -1
  187. package/package.json +11 -11
  188. package/dist/EvidenceViewOffer-2T2ZGHIF.js +0 -2
  189. package/dist/FolderPicker-LTQW4YNR.js +0 -2
  190. package/dist/SingleShotApp-KXZF5ZJM.js +0 -2
  191. package/dist/TestMdRunView-6X6W5YAP.js +0 -2
  192. package/dist/bridge-WFSSMJ57.js +0 -2
  193. package/dist/chat-controller-6GW2HSJP.js +0 -2
  194. package/dist/chunk-2KQF6WLX.js +0 -363
  195. package/dist/design-committer-2BQVZPO4.js +0 -2
  196. package/dist/dispatch-NE35HS5F.js +0 -2
  197. package/dist/evolve-cmd-I4Z6IPIM.js +0 -2
  198. package/dist/explain-O3A2HZWD.js +0 -2
  199. package/dist/ingest-WTPY2VLS.js +0 -2
  200. package/dist/ingest-cmd-GOPW3SNF.js +0 -2
  201. package/dist/install-BDHZVEY4.js +0 -2
  202. package/dist/login-flow-DLG2WHSZ.js +0 -2
  203. package/dist/pipeline-B2TYZBMB.js +0 -2
  204. package/dist/prepare-target-JGVB7OKC.js +0 -2
  205. package/dist/readmodel-YDLGQDMH.js +0 -2
  206. package/dist/reconcile-cmd-6ILIXD3U.js +0 -2
  207. package/dist/registry-AA5YIO5Y.js +0 -2
  208. package/dist/run-6CMGGU2W.js +0 -2
  209. package/dist/run-PZIYMD35.js +0 -2
  210. package/dist/tcg-generate-BPLQ7WJ5.js +0 -2
  211. package/dist/testmd-actions-WJS2YM7B.js +0 -2
  212. package/dist/token-refresh-IT4LVE2H.js +0 -2
  213. package/dist/verdicts-J5MJHUGG.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 M}from"./chunk-N2P4MI32.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-3D7VYEDP.js";import{b as B,d as W}from"./chunk-NVGBE2DR.js";import{C as j}from"./chunk-R4EGL7VM.js";import{w as ge}from"./chunk-DEUDRSU7.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 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 J,b as F}from"./chunk-2UIHS2FH.js";import{a as M}from"./chunk-N2P4MI32.js";import{a as we}from"./chunk-YKTYVJBN.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-NJJQL54J.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-5WJSFLCP.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-3LLVDHOJ.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-5WJSFLCP.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-3LLVDHOJ.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-5WJSFLCP.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-5WJSFLCP.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-URQ5OAY7.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-3LLVDHOJ.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-3LLVDHOJ.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-R3XOP3GP.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{b as O,d as S}from"./chunk-4FXSDPQW.js";import{c as L}from"./chunk-RFHMDQXZ.js";import{n as P,o as R}from"./chunk-RSSOJ3L2.js";import{x as s}from"./chunk-DEUDRSU7.js";import{a as y}from"./chunk-HCBYKLMW.js";import{a as E,b as o,i as h}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var n=d(B(),1);import{basename as D}from"path";var r=d(y(),1),U="evidence-view-server";function Q({packPath:m,viewerBase:w,onDone:V,openUrl:k}){let[t,a]=(0,n.useState)("ask"),[g,b]=(0,n.useState)(null),[l,p]=(0,n.useState)(null),f=(0,n.useRef)(null),u=(0,n.useRef)(!1),x=async()=>{let e=f.current;f.current=null,e&&(R(U),await e.close())},v=()=>{u.current||(u.current=!0,V())};return h((e,i)=>{u.current||(t==="ask"?e==="y"||e==="Y"?a("starting"):(e==="n"||e==="N"||i.return||i.escape)&&v():t==="serving"&&(e==="q"||e==="Q"||i.escape)&&x().then(v))}),(0,n.useEffect)(()=>{if(t!=="starting")return;let e=!1;return(async()=>{try{let i=D(m),c=await O({packs:new Map([[i,m]]),allowedOrigins:[new URL(w).origin]});if(e){await c.close();return}f.current=c,P(U,()=>{c.close()});let T=S(c.urlFor(i),w);b(T);try{await(k??(q=>L(q)))(T)}catch{p("could not open browser \u2014 open the URL manually")}a("serving")}catch(i){p(`evidence view failed \u2014 ${i.message}`),a("failed")}})(),()=>{e=!0}},[t]),(0,n.useEffect)(()=>{if(t!=="failed")return;let e=setTimeout(v,0);return()=>clearTimeout(e)},[t]),(0,n.useEffect)(()=>()=>{x()},[]),t==="ask"?(0,r.jsxs)(o,{children:["View evidence in browser? ",(0,r.jsx)(o,{color:s.dim,children:"(y/N)"})]}):t==="serving"||t==="starting"?(0,r.jsxs)(E,{flexDirection:"column",children:[g?(0,r.jsxs)(o,{children:["viewer ",(0,r.jsx)(o,{color:s.orange,children:g})]}):(0,r.jsx)(o,{color:s.dim,children:"starting\u2026"}),l?(0,r.jsx)(o,{color:"yellow",children:l}):null,t==="serving"?(0,r.jsx)(o,{color:s.dim,children:"Press q when done"}):null]}):l?(0,r.jsx)(o,{color:"yellow",children:l}):null}export{Q as a};
2
+ import{b as O,d as S}from"./chunk-DYXYNH6X.js";import{c as L}from"./chunk-RFHMDQXZ.js";import{n as P,o as R}from"./chunk-RSSOJ3L2.js";import{x as s}from"./chunk-NJJQL54J.js";import{a as y}from"./chunk-HCBYKLMW.js";import{a as E,b as o,i as h}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var n=d(B(),1);import{basename as D}from"path";var r=d(y(),1),U="evidence-view-server";function Q({packPath:m,viewerBase:w,onDone:V,openUrl:k}){let[t,a]=(0,n.useState)("ask"),[g,b]=(0,n.useState)(null),[l,p]=(0,n.useState)(null),f=(0,n.useRef)(null),u=(0,n.useRef)(!1),x=async()=>{let e=f.current;f.current=null,e&&(R(U),await e.close())},v=()=>{u.current||(u.current=!0,V())};return h((e,i)=>{u.current||(t==="ask"?e==="y"||e==="Y"?a("starting"):(e==="n"||e==="N"||i.return||i.escape)&&v():t==="serving"&&(e==="q"||e==="Q"||i.escape)&&x().then(v))}),(0,n.useEffect)(()=>{if(t!=="starting")return;let e=!1;return(async()=>{try{let i=D(m),c=await O({packs:new Map([[i,m]]),allowedOrigins:[new URL(w).origin]});if(e){await c.close();return}f.current=c,P(U,()=>{c.close()});let T=S(c.urlFor(i),w);b(T);try{await(k??(q=>L(q)))(T)}catch{p("could not open browser \u2014 open the URL manually")}a("serving")}catch(i){p(`evidence view failed \u2014 ${i.message}`),a("failed")}})(),()=>{e=!0}},[t]),(0,n.useEffect)(()=>{if(t!=="failed")return;let e=setTimeout(v,0);return()=>clearTimeout(e)},[t]),(0,n.useEffect)(()=>()=>{x()},[]),t==="ask"?(0,r.jsxs)(o,{children:["View evidence in browser? ",(0,r.jsx)(o,{color:s.dim,children:"(y/N)"})]}):t==="serving"||t==="starting"?(0,r.jsxs)(E,{flexDirection:"column",children:[g?(0,r.jsxs)(o,{children:["viewer ",(0,r.jsx)(o,{color:s.orange,children:g})]}):(0,r.jsx)(o,{color:s.dim,children:"starting\u2026"}),l?(0,r.jsx)(o,{color:"yellow",children:l}):null,t==="serving"?(0,r.jsx)(o,{color:s.dim,children:"Press q when done"}):null]}):l?(0,r.jsx)(o,{color:"yellow",children:l}):null}export{Q as a};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as be}from"./chunk-JQW2QFSX.js";import{a as xe,b as Re}from"./chunk-FYLMTZ3J.js";import{a as se,b as q,d as ue}from"./chunk-TYRTD5DD.js";import{a as Ne,b as Ee,g as le,j as ee}from"./chunk-OXHMUZJV.js";import{d as te,e as w,f as re,g as oe,h as de}from"./chunk-AKX4VRRR.js";function Me(r,s){let t=r.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(t.length>60){let o=t.lastIndexOf("-",60);t=(o>0?t.slice(0,o):t.slice(0,60)).replace(/-+$/g,"")}if(!ae.test(t))return null;let e=t;for(let o=2;s(e);o++)e=`${t}-${o}`;return ae.test(e)?e:null}var Ve={source:"src",usecase:"uc",scenario:"sc",ac:"ac",test:"t",gap:"gap",stylenote:"sty"};function ze(r,s,t){let e=Ve[r];return Me(e?`${e} ${s}`:s,t)}var Pe={usecase:"uc",scenario:"sc",ac:"ac",test:"t",gap:"gap",stylenote:"sty"},Oe=/^(uc|sc|ac|t|gap|sty)-\d+$/i;function we(r,s,t){let e=Pe[r];if(!e)return null;let o=new RegExp(`^${e}-(\\d+)$`),d=0;for(let p of t){let l=o.exec(p);if(!l)continue;let n=Number(l[1]);Number.isSafeInteger(n)&&n>d&&(d=n)}let c=d+1;for(;s(`${e}-${c}`);)c+=1;return`${e}-${c}`}var Le=/^L([1-9]\d*)-L([1-9]\d*)$/,Ge=/^img#(p[1-9]\d*-[1-9]\d*|i[1-9]\d*)$/;function pe(r){if(r==="img#whole")return{kind:"img-whole"};let s=Ge.exec(r);if(s)return{kind:"img-part",ref:s[1]};let t=Le.exec(r);return t?{kind:"lines",a:parseInt(t[1],10),b:parseInt(t[2],10)}:null}function Ue(r,s){let t=/^L(\d+)-L(\d+)$/.exec(s);if(!t)return null;let e=parseInt(t[1],10),o=parseInt(t[2],10),d=r.split(`
2
+ import{a as be}from"./chunk-JQW2QFSX.js";import{a as xe,b as Re}from"./chunk-6FCPS2VT.js";import{a as se,b as q,d as ue}from"./chunk-UH2ZTX4E.js";import{a as Ne,b as Ee,g as le,j as ee}from"./chunk-XMTSHHYQ.js";import{d as te,e as w,f as re,g as oe,h as de}from"./chunk-AKX4VRRR.js";function Me(r,s){let t=r.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(t.length>60){let o=t.lastIndexOf("-",60);t=(o>0?t.slice(0,o):t.slice(0,60)).replace(/-+$/g,"")}if(!ae.test(t))return null;let e=t;for(let o=2;s(e);o++)e=`${t}-${o}`;return ae.test(e)?e:null}var Ve={source:"src",usecase:"uc",scenario:"sc",ac:"ac",test:"t",gap:"gap",stylenote:"sty"};function ze(r,s,t){let e=Ve[r];return Me(e?`${e} ${s}`:s,t)}var Pe={usecase:"uc",scenario:"sc",ac:"ac",test:"t",gap:"gap",stylenote:"sty"},Oe=/^(uc|sc|ac|t|gap|sty)-\d+$/i;function we(r,s,t){let e=Pe[r];if(!e)return null;let o=new RegExp(`^${e}-(\\d+)$`),d=0;for(let p of t){let l=o.exec(p);if(!l)continue;let n=Number(l[1]);Number.isSafeInteger(n)&&n>d&&(d=n)}let c=d+1;for(;s(`${e}-${c}`);)c+=1;return`${e}-${c}`}var Le=/^L([1-9]\d*)-L([1-9]\d*)$/,Ge=/^img#(p[1-9]\d*-[1-9]\d*|i[1-9]\d*)$/;function pe(r){if(r==="img#whole")return{kind:"img-whole"};let s=Ge.exec(r);if(s)return{kind:"img-part",ref:s[1]};let t=Le.exec(r);return t?{kind:"lines",a:parseInt(t[1],10),b:parseInt(t[2],10)}:null}function Ue(r,s){let t=/^L(\d+)-L(\d+)$/.exec(s);if(!t)return null;let e=parseInt(t[1],10),o=parseInt(t[2],10),d=r.split(`
3
3
  `);return e<1||o<e||o>d.length?null:d.slice(e-1,o).map(c=>c.replace(/^\d+\| /,"")).join(`
4
4
  `)}function Te(r,s,t){let e=pe(s.anchor);if(r.format==="image")return e?.kind==="img-whole"?[]:[{code:"CITE_ANCHOR_INVALID",detail:`image cites are anchor-only (img#whole), got ${s.anchor}`}];if(e?.kind==="img-part")return new Set((r.images??[]).map(c=>c.ref)).has(e.ref)?[]:[{code:"CITE_ANCHOR_INVALID",detail:`anchor ${s.anchor} names no embedded image of this source version`}];if(!s.anchor||s.quote===void 0||s.quote==="")return[{code:"MISSING_CITE",detail:"text-kind cites need anchor+quote"}];let o=t!==null?Ue(t,s.anchor):null;return o===null?[{code:"BAD_ANCHOR",detail:`anchor ${s.anchor} does not resolve in the source`}]:o.includes(s.quote)?[]:[{code:"QUOTE_MISMATCH",detail:`quote is not verbatim within ${s.anchor}`}]}import{existsSync as Fe,readFileSync as He}from"fs";function dt(r){let s=Re(r),t=new Map(Object.entries(s.heads)),e=new Map(Object.entries(s.trust)),o=new Map(Object.entries(s.nodeLabel)),d=new Map(Object.entries(s.superseded)),c=new Map(Object.entries(s.names)),p=new Map(Object.entries(s.archivedReason)),l=new Set(s.appliedEvents),n=new Map(Object.entries(s.conv)),m=g=>s.media[g]??{format:"text",media_type:"text/plain",anchors_supported:["L-L"]},f=new Map;for(let[g,_]of c)f.set(_,g);let a=new Map,S=g=>{if(a.has(g))return a.get(g);if(!o.has(g))return a.set(g,null),null;let _=xe(r,g);if(!Fe(_))throw new Ne(`derived node file missing for ${g} \u2014 run kane-cli context rebuild`);let I=JSON.parse(He(_,"utf8"));return a.set(g,I),I},v=g=>{let _=g,I=new Set;for(;d.has(_)&&!I.has(_);){I.add(_);let O=d.get(_);if(typeof O!="string")break;_=O}return _},N=null,y=g=>{let _=f.get(g);if(_!==void 0)return _;if(N===null){N=new Map;for(let[G,D]of d)typeof D=="string"&&N.set(D,G)}let I=new Set,O=g;for(;!I.has(O);){I.add(O);let G=N.get(O);if(G===void 0)return null;let D=f.get(G);if(D!==void 0)return D;O=G}return null},b=g=>{Oe.test(g)&&(g=g.toLowerCase());let _=t.get(g),I=o.has(g)?g:c.get(g)??(typeof _=="string"?_:void 0);if(I===void 0||!o.has(I))return null;let O=v(I);return{cid:I,tip:O,superseded:d.has(I)||d.has(O)}},V=new Map;for(let g of Object.values(s.forward))for(let _ of g){let I=V.get(_.dst);I?I.push(_):V.set(_.dst,[_])}let A=g=>(g??[]).filter(_=>!d.has(_.ecid)),K=g=>A(V.get(g)),P=g=>K(g).filter(_=>_.type===w.DERIVES),J=g=>A(s.forward[g]).some(_=>oe(_.type)?.pin?.comparesTo==="dst_tip"&&d.has(_.dst)),ie=g=>{if(d.has(g))return"superseded";let _=P(g);if(_.length===0)return J(g)?"stale":"fresh";let I=new Map;for(let D of _)I.set(D.props.source_id,D);let O=!1,G=!1;for(let[D,k]of I){let U=t.get(D);if(U!=null&&(O=!0,U!==k.props.source_cid)){let i=n.get(D)?.chain;(!i||!i.includes(k.props.source_cid))&&(G=!0)}}return O?G||J(g)?"stale":"fresh":"orphaned"};return{heads:t,trust:e,nodeLabel:o,superseded:d,names:c,nameOf:f,archivedReason:p,appliedEvents:l,convChains:n,mediaOf:m,extractedSourceCids:new Set(s.extracted),extractionCompleteness:new Map(Object.entries(s.completeness??{}).map(([g,{seq:_,...I}])=>[g,I])),designOf:new Map(Object.entries(s.design_of??{})),designGenerationOf:new Map(Object.entries(s.design_generation??{})),latestHash:s.applied.hash,lastSeq:s.applied.seq,hasNode:g=>o.has(g),getNode:S,byLabel:g=>[...o.entries()].filter(([,_])=>_===g).map(([_])=>({cid:_,content:S(_)?.content??{}})),edgesFrom:g=>A(s.forward[g]),edgesInto:K,derivesInto:P,resolve:b,tipOf:v,displayNameOf:y,stale:ie,staleList:()=>[...o.keys()].map(g=>({cid:g,state:ie(g)})).filter(g=>g.state!=="fresh"),execHistory:g=>{let _=b(g);if(!_)return[];let I=v(_.cid),O=new Set([I]),G=!0;for(;G;){G=!1;for(let[k,U]of d)U!==null&&O.has(U)&&!O.has(k)&&(O.add(k),G=!0)}let D=[];for(let k of Object.entries(s.exec??{}))O.has(k[0])&&D.push(...k[1]);return D.sort((k,U)=>k.started_at<U.started_at?-1:1)},retractedEdgesTouching:g=>{let _=new Set([v(g),g]),I=!0;for(;I;){I=!1;for(let[k,U]of d)typeof U=="string"&&_.has(U)&&!_.has(k)&&(_.add(k),I=!0)}let O=s.edgeRetractions??{},G=[],D=new Set;for(let k of _)for(let U of[...s.forward[k]??[],...V.get(k)??[]]){let i=O[U.ecid];!i||D.has(U.ecid)||(D.add(U.ecid),G.push({...U,retraction:i}))}return G}}}function at(r,s){if(r.stale(s)!=="stale")return!1;let t=new Map;for(let e of r.derivesInto(s))t.set(e.props.source_id,e);for(let[e,o]of t){let d=r.heads.get(e);if(d==null||d===o.props.source_cid)continue;let c=r.convChains.get(e)?.chain;if(!c||!c.includes(o.props.source_cid))return!0}for(let e of r.edgesFrom(s)){if(oe(e.type)?.pin?.comparesTo!=="dst_tip"||!r.superseded.has(e.dst))continue;let o=r.tipOf(e.dst);if(r.superseded.has(o)||r.nodeLabel.get(o)==="usecase")return!0}return!1}function fe(r,s){let t=new Map;for(let[c,p]of r.superseded)typeof p=="string"&&p!==c&&t.set(p,[...t.get(p)??[],c]);let e=[],o=[s],d=new Set;for(;o.length>0;){let c=o.pop();d.has(c)||(d.add(c),e.push(c),o.push(...t.get(c)??[]))}return e}function je(r,s){return(r.extraction_claims??[]).some(t=>t.source_id===s&&t.completeness==="complete")}function qe(r,s){let t=new Set;for(let e of fe(r,s))for(let o of r.derivesInto(e))t.add(o.props?.source_id??"conversation");return t}function ve(r,s){let t=[],e=[],o=r.archived??[];if(o.length===0)return{valid:t,errors:e};let d=new Set([...r.source?[r.source.source_id]:[],...(r.sources??[]).map(p=>p.source_id)]),c=new Set;for(let p of r.use_cases){if(!p.matches_existing)continue;let l=s.resolve(p.matches_existing.cid);l&&c.add(s.tipOf(l.cid))}for(let p of o){let l=`archived[${p.target}]`,n=s.resolve(p.target),m=n?s.tipOf(n.cid):null;if(!m||(s.trust.get(m)??null)==="archived"){e.push({code:"ARCHIVE_TARGET_UNKNOWN",detail:`${l}: target does not resolve to an existing, live item`});continue}let f=qe(s,m);if(!f.has(p.basis)){e.push({code:"ARCHIVE_FOREIGN_PROVENANCE",detail:`${l}: its provenance does not include ${p.basis} \u2014 an archive claim must come from a source that evidences the item`});continue}if(!d.has(p.basis)){e.push({code:"ARCHIVE_WITHOUT_COMPLETE_CLAIM",detail:`${l}: ${p.basis} was not read by this extraction \u2014 a completeness claim only counts for a source this run actually read`});continue}if(!je(r,p.basis)){e.push({code:"ARCHIVE_WITHOUT_COMPLETE_CLAIM",detail:`${l}: archiving needs an EXPLICIT complete extraction claim for ${p.basis} (the omitted-claims default does not count) \u2014 add extraction_claims`});continue}if(c.has(m)){e.push({code:"ARCHIVE_TARGET_MATCHED",detail:`${l}: this proposal also matches the target via matches_existing \u2014 a matched item cannot be archived by the same extraction; propose the change as an update instead`});continue}let a=[...f].filter(S=>S!==p.basis);if(a.length>0){e.push({code:"ARCHIVE_OTHER_LIVE_EVIDENCE",detail:`${l}: still evidenced by ${a.join(", ")} \u2014 an item another live source evidences is never archived from here`});continue}t.push({op:p,cid:m})}return{valid:t,errors:e}}function Se(r,s,t){return r.superseded.has(t)}function ke(r){let{graph:s,oldTip:t,newCid:e,newLabel:o,by:d}=r,c=[],p=[],l=[],n=[],m=new Set;for(let f of s.edgesFrom(t)){if(f.type===w.DERIVES||r.skipEcids?.has(f.ecid))continue;p.push({kind:"edge",ecid:f.ecid,reason:r.reason,by:d}),m.add(f.ecid);let a=r.dstRedirect?.get(f.dst)??f.dst,S=s.nodeLabel.get(f.dst)??"(unknown)",v=de(f.type,o,S,f.props);if(v.length>0){l.push(`rebless ${f.type} \u2192 ${f.dst}: ${v.map(b=>b.detail).join("; ")}`);continue}let N=be(s,{type:f.type,src:e,dst:a},{pending:n,retracted:m},`rebless ${f.type}`);if(N){l.push(N.detail);continue}let y=q(f.type,e,a,f.props);if(s.superseded.has(y)){l.push(`rebless ${f.type} \u2192 ${a}: the re-derived edge (${y}) was retracted \u2014 retraction is terminal, the successor cannot revive it`);continue}c.push({ecid:y,type:f.type,src:e,dst:a,props:f.props}),n.push({src:e,dst:a,type:f.type})}return{edges:c,supersessions:p,errors:l}}var ae=/^[a-z0-9][a-z0-9-]{1,63}$/;function De(r,s,t,e){if(!s)return{error:{code:"SUPERSEDE_TARGET_MISSING",detail:"supersede verdict needs a target (slug or cid)"}};let o=r.resolve(s);return o?o.superseded||e.has(o.cid)?{error:{code:"ALREADY_SUPERSEDED",detail:`${s} is already superseded (tip: ${o.tip})`}}:o.cid===t?{error:{code:"SELF_SUPERSEDE",detail:"a node cannot supersede itself"}}:{targetCid:o.cid}:{error:{code:"UNKNOWN_SUPERSEDE_TARGET",detail:`${s} names nothing in the graph`}}}function Ke(r,s,t,e,o=[]){if(!oe(s)?.acyclic)return null;if(t===e)return{code:"EDGE_CYCLE",detail:`${s} ${t} \u2192 itself`};let c=n=>[...r.edgesFrom(n).filter(m=>m.type===s).map(m=>m.dst),...o.filter(m=>m.type===s&&m.src===n).map(m=>m.dst)],p=new Set,l=[e];for(;l.length>0;){let n=l.pop();if(n===t)return{code:"EDGE_CYCLE",detail:`${s} ${t} \u2192 ${e} closes a cycle`};p.has(n)||(p.add(n),l.push(...c(n)))}return null}function Rt(r,s,t,e){let d=oe(s)?.cardinality;if(d!=="one-live-per-src"&&d!=="one-live-per-src-and-dst")return null;let c=r.edgesFrom(t).filter(p=>p.type===s&&!r.superseded.has(p.dst));if(c.length>0)return{code:"CARDINALITY_VIOLATION",detail:`${s} from ${t} already has a live edge (${c[0].ecid}) \u2014 supersede it first`};if(d==="one-live-per-src-and-dst"&&e!==void 0){let p=r.edgesInto(e).filter(l=>l.type===s&&!r.superseded.has(l.src));if(p.length>0)return{code:"CARDINALITY_VIOLATION",detail:`${s} onto ${e} already has a live edge (${p[0].ecid}) \u2014 strict 1:1, supersede it first`}}return null}var Ie=new Set(["high","med","low"]),ge=r=>r.cites&&r.cites.length>0?r.cites:[r.cite];function he(r){let s=0;for(let t of r)typeof t=="object"&&t!==null&&"op"in t&&s++;return s===0?"flat":s===r.length?"ops":"mixed"}var We=/^c[1-9][0-9]*$/;function Ae(r,s,t,e){let o=new Map,d=[],c=[];for(let[l,n]of s.entries()){let m=`${r}.updated.criteria[${l}]`;if(n.op==="keep"||n.op==="remove"){if(!We.test(n.ref??"")){e.push({code:"CRITERIA_REF_UNKNOWN",detail:`${m}: ref ${JSON.stringify(n.ref)} is not a c<N> criterion index`});continue}if(o.has(n.ref)){e.push({code:"CRITERIA_REF_DUPLICATE",detail:`${m}: ${n.ref} is already named by another op \u2014 every prior criterion appears in exactly one keep or remove`});continue}o.set(n.ref,n);let f=Number.parseInt(n.ref.slice(1),10);if(f>t.length){e.push({code:"CRITERIA_REF_UNKNOWN",detail:`${m}: ${n.ref} \u2014 the live target has ${t.length} criteria`});continue}if(t[f-1]!==n.text){e.push({code:"CRITERIA_REF_MISMATCH",detail:`${m}: ${n.ref} echo mismatch \u2014 the live target's criterion ${f} reads ${JSON.stringify(t[f-1])}, the op echoed ${JSON.stringify(n.text)} \u2014 re-read the node and re-emit`});continue}n.op==="remove"&&(d.push(n.text),(!n.reason||!n.reason.trim())&&e.push({code:"EMPTY_REASON",detail:`${m}: a remove op carries its reason`}))}else!n.text||!n.text.trim()?e.push({code:"EMPTY_CRITERION",detail:`${m}: set text is empty`}):c.push(n.text)}let p=[];for(let l=1;l<=t.length;l++)o.has(`c${l}`)||p.push(`c${l}`);p.length>0&&e.push({code:"CRITERIA_PARTITION_INCOMPLETE",detail:`${r}: prior criteria ${p.join(", ")} named by no keep/remove op \u2014 every prior criterion must be kept or removed (with a reason)`});for(let l of d)c.includes(l)&&e.push({code:"CRITERIA_OP_CONFLICT",detail:`${r}: ${JSON.stringify(l)} is removed AND re-set in the same update \u2014 drop one of the two ops`})}function bt(r,s,t){let e=[],o=r.sources??[r.source],d=new Map(o.map(n=>[n.source_id,n.source_cid])),c=new Map;if(typeof s=="string")c.set(r.source.source_id,{media:t.mediaOf(r.source.source_cid),numberedText:s});else for(let[n,m]of s)c.set(n,m);for(let n of o)t.hasNode(n.source_cid)||e.push({code:"MISSING_SOURCE_NODE",detail:`source ${n.source_id} (${n.source_cid}) is not a committed node \u2014 ingest it first`});let p=(n,m)=>{let f=m.source_id??r.source.source_id;if(!d.has(f)){e.push({code:"CITE_SOURCE_UNKNOWN",detail:`${n}: cite source ${JSON.stringify(f)} is not in read_basis`});return}let a=c.get(f);if(!a){e.push({code:"MISSING_SOURCE_NODE",detail:`${n}: no citable text available for source ${f}`});return}for(let S of Te(a.media,m,a.numberedText))e.push({code:S.code,detail:`${n}: ${S.detail}`})},l=new Set;for(let n of r.use_cases){if(l.has(n.temp_ref)&&e.push({code:"DUP_TEMP_REF",detail:`duplicate temp_ref ${n.temp_ref}`}),l.add(n.temp_ref),(!n.title||!n.title.trim())&&e.push({code:"EMPTY_TITLE",detail:`${n.temp_ref}: title is empty`}),Ie.has(n.risk)||e.push({code:"BAD_RISK",detail:`${n.temp_ref}: risk ${JSON.stringify(n.risk)} not in high|med|low`}),!n.cite||!n.cite.anchor)e.push({code:"MISSING_CITE",detail:`${n.temp_ref}: every derived use-case must carry a cite`});else for(let f of ge(n))p(n.temp_ref,f);n.matches_existing&&!t.hasNode(n.matches_existing.cid)&&e.push({code:"UNKNOWN_MATCH",detail:`${n.temp_ref}: matches_existing ${n.matches_existing.cid} is not in the graph`});for(let[f,a]of(n.criteria??[]).entries())(!a.text||!a.text.trim())&&e.push({code:"EMPTY_CRITERION",detail:`${n.temp_ref}.criteria[${f}]: text is empty`}),!a.cite||!a.cite.anchor?e.push({code:"MISSING_CITE",detail:`${n.temp_ref}.criteria[${f}]: every criterion carries its own cite`}):p(`${n.temp_ref}.criteria[${f}]`,a.cite);let m=n.updated?.criteria??[];if(m.length>0){let f=he(m);if(f==="mixed")e.push({code:"CRITERIA_SHAPE_MIXED",detail:`${n.temp_ref}.updated.criteria mixes op-shaped (keep/set/remove) and {text, cite} entries \u2014 emit ONE shape for the whole array`});else if(f==="ops"){let a=m,S=n.matches_existing?Ye(t,n.matches_existing.cid):null;if(!S)e.push({code:"CRITERIA_REF_UNKNOWN",detail:`${n.temp_ref}: op-union criteria address a prior version \u2014 they need a resolvable matches_existing target`});else{let v=t.getNode(S.cid)?.content.criteria??[];Ae(n.temp_ref,a,v,e)}for(let[v,N]of a.entries())N.op==="set"&&(!N.cite||!N.cite.anchor?e.push({code:"MISSING_CITE",detail:`${n.temp_ref}.updated.criteria[${v}]: a set op carries the proposing source's cite`}):p(`${n.temp_ref}.updated.criteria[${v}]`,N.cite))}else for(let[a,S]of m.entries())(!S.text||!S.text.trim())&&e.push({code:"EMPTY_CRITERION",detail:`${n.temp_ref}.updated.criteria[${a}]: text is empty`}),!S.cite||!S.cite.anchor?e.push({code:"MISSING_CITE",detail:`${n.temp_ref}.updated.criteria[${a}]: every updated criterion carries its own cite`}):p(`${n.temp_ref}.updated.criteria[${a}]`,S.cite)}}return e.push(...ve(r,t).errors),e}function Be(r,s,t){return`${r}:${s}:${t}`}function Je(r,s,t,e){let o=`${s}:${t}:`,d=0;for(let c of r.appliedEvents){if(!c.startsWith(o))continue;let p=c.slice(o.length);if(!/^\d+$/.test(p))continue;let l=Number.parseInt(p,10);l>d&&(d=l)}return Array.from({length:e},(c,p)=>Be(s,t,d+1+p))}function Ye(r,s){let t=r.resolve(s);if(t===null)return null;let e=t.cid;if(r.superseded.has(e)){let o=r.tipOf(e);return r.superseded.has(o)?null:{cid:o,redirected:!0}}return{cid:e,redirected:!1}}function Ot(r){let{contextDir:s,graph:t,proposal:e,proposalId:o,verdicts:d,by:c,allowStaleBasis:p,extractorVersion:l,autoName:n}=r,m=le(s);if(!p&&e.read_basis!==m)return{record:null,errors:[{code:"STALE_BASIS",detail:`proposal read_basis ${String(e.read_basis)} != latest ${String(m)}`}]};for(let i of e.sources??[e.source])if(!t.hasNode(i.source_cid))return{record:null,errors:[{code:"MISSING_SOURCE_NODE",detail:`source ${i.source_id} (${i.source_cid}) is not a committed node \u2014 ingest it first`}]};let f=new Map((e.sources??[e.source]).map(i=>[i.source_id,i.source_cid])),a=[],S=[],v=new Map,N=[],y=t.mediaOf(e.source.source_cid),b=new Set,V=[],A=[],K=[],P=[];for(let i of ve(e,t).valid)P.push({id:i.cid,kind:"pending_archive",resolution:"pending",edit:null,reason:i.op.reason,by:c});let J=[],ie=[],g=new Set,_=new Set,I=(i,h,F)=>{let Y=De(t,h.supersedeTarget,F,g);if("error"in Y){a.push({code:Y.error.code,detail:`${i}: ${Y.error.detail}`});return}g.add(Y.targetCid),J.push({kind:"node",old:Y.targetCid,new:F,reason:h.reason??`superseded via review by ${c.id}`,by:c})};for(let i of e.use_cases){let h=d.get(i.temp_ref)??{resolution:"skipped"};b.has(i.temp_ref)&&a.push({code:"DUP_TEMP_REF",detail:`duplicate temp_ref ${i.temp_ref}`}),b.add(i.temp_ref),(!i.title||!i.title.trim())&&a.push({code:"EMPTY_TITLE",detail:`${i.temp_ref}: title is empty`}),Ie.has(i.risk)||a.push({code:"BAD_RISK",detail:`${i.temp_ref}: risk ${JSON.stringify(i.risk)} not in high|med|low`});let F=pe(i.cite?.anchor??""),Y=i.cite?.source_id!==void 0&&f.has(i.cite.source_id)?t.mediaOf(f.get(i.cite.source_id)):y;if(Y.format==="image"){if(F?.kind!=="img-whole"){a.push({code:i.cite?.anchor?"CITE_ANCHOR_INVALID":"MISSING_CITE",detail:`${i.temp_ref}: image cites are anchor-only (img#whole)`});continue}}else if(F?.kind==="img-part"){if(!(Y.images??[]).some(E=>E.ref===F.ref)){a.push({code:"CITE_ANCHOR_INVALID",detail:`${i.temp_ref}: anchor ${i.cite?.anchor} names no embedded image of this source version`});continue}}else if(!i.cite||!i.cite.anchor||!i.cite.quote){a.push({code:"MISSING_CITE",detail:`${i.temp_ref}: every derived use-case must cite anchor+quote`});continue}h.resolution==="edited"&&h.edit&&(h.edit.title!==void 0&&!h.edit.title.trim()&&a.push({code:"EMPTY_TITLE",detail:`${i.temp_ref}: edited title is empty`}),h.edit.risk!==void 0&&!Ie.has(h.edit.risk)&&a.push({code:"BAD_RISK",detail:`${i.temp_ref}: edited risk ${JSON.stringify(h.edit.risk)} invalid`}));let me=ue({title:h.edit?.title??i.title,description:i.description,summary:h.edit?.summary??i.summary,actors:i.actors,value:i.value,risk:h.edit?.risk??i.risk,...i.criteria&&i.criteria.length>0?{criteria:i.criteria.map(u=>u.text)}:{}}),x=se("usecase",me),_e=i.cite.source_id??e.source.source_id,Ce=f.get(_e);if(i.cite.source_id!==void 0&&Ce===void 0){a.push({code:"CITE_SOURCE_UNKNOWN",detail:`${i.temp_ref}: cite source ${JSON.stringify(_e)} is not in read_basis`});continue}let Z={source_id:_e,source_cid:Ce??e.source.source_cid,anchor:i.cite.anchor,...i.cite.quote?{quote:i.cite.quote}:{}};if(i.matches_existing&&!t.hasNode(i.matches_existing.cid)){a.push({code:"UNKNOWN_MATCH",detail:`${i.temp_ref}: matches_existing ${i.matches_existing.cid} is not in the graph`});continue}let R=i.matches_existing?.cid??(t.hasNode(x)?x:null);if(R&&t.superseded.has(R)){let u=t.tipOf(R);R=t.superseded.has(u)?null:u}if(R&&i.matches_existing&&(t.trust.get(R)??null)==="derived"){let u=i.updated?.criteria??[];if(i.changed&&u.length>0&&he(u)==="ops"&&(h.resolution==="approved"||h.resolution==="edited")){a.push({code:"UC_UNREVIEWED",detail:`${i.temp_ref}: merge target ${R.slice(0,19)} is unreviewed (derived) \u2014 bless it first (kane-cli context review) and re-propose the merge`});continue}let E=(r.probeHits??[]).find(C=>C.tempRef===i.temp_ref&&C.candidateCid===R);N.push({tempRef:i.temp_ref,candidate_cid:R,score:E?.score??1,scorer:E?.scorer??"lexical_fallback"}),R=null}if(R){if(i.changed&&(h.resolution==="approved"||h.resolution==="edited")){let u=i.updated;if(!u||Object.keys(u).length===0){a.push({code:"CHANGED_NEEDS_PAYLOAD",detail:`${i.temp_ref}: changed:true needs an updated{...} payload naming the moved fields`});continue}let E=t.getNode(R)?.content??{},C=u.criteria??[],M=C.length>0?he(C):"flat";if(M==="mixed"){a.push({code:"CRITERIA_SHAPE_MIXED",detail:`${i.temp_ref}.updated.criteria mixes op-shaped (keep/set/remove) and {text, cite} entries \u2014 emit ONE shape for the whole array`});continue}if(M==="ops"){let L=C,H=E.criteria??[],j=a.length;Ae(i.temp_ref,L,H,a);for(let[ne,ce]of L.entries())ce.op==="set"&&(!ce.cite||!ce.cite.anchor)&&a.push({code:"MISSING_CITE",detail:`${i.temp_ref}.updated.criteria[${ne}]: a set op carries the proposing source's cite`});if(a.length>j)continue;let T=L.filter(ne=>ne.op!=="remove").map(ne=>ne.text),B=ue({title:h.edit?.title??u.title??String(E.title??i.title),...u.description??E.description?{description:u.description??E.description}:{},...h.edit?.summary??u.summary??E.summary?{summary:h.edit?.summary??u.summary??E.summary}:{},...u.actors??E.actors?{actors:u.actors??E.actors}:{},...u.value??E.value?{value:u.value??E.value}:{},risk:h.edit?.risk??u.risk??String(E.risk??i.risk),...T.length>0?{criteria:T}:{}}),Q=se("usecase",B);if(Q!==R){for(let $ of re("usecase",B))a.push({code:$.code,detail:`${i.temp_ref}: ${$.detail}`});V.push({cid:Q,label:te.USECASE,content:B});for(let $ of ge(i)){let X=$.source_id??e.source.source_id,W=f.get(X);if(!W){a.push({code:"CITE_SOURCE_UNKNOWN",detail:`${i.temp_ref}: cite source ${JSON.stringify(X)} is not in read_basis`});continue}let z={source_id:X,source_cid:W,anchor:$.anchor,...$.quote?{quote:$.quote}:{}};A.push({ecid:q("DERIVES",W,Q,z),type:w.DERIVES,src:W,dst:Q,props:z})}let ce=fe(t,R).flatMap($=>t.edgesInto($)).filter($=>$.type===w.DERIVES&&typeof $.props.claim=="string");for(let $ of L){if($.op!=="keep")continue;let X=new Set;for(let W of ce){let z=W.props;if(z.claim!==$.text)continue;let $e=`${z.source_id}|${z.source_cid}|${z.anchor}`;if(X.has($e))continue;X.add($e);let ye={...W.props};A.push({ecid:q("DERIVES",W.src,Q,ye),type:w.DERIVES,src:W.src,dst:Q,props:ye})}}for(let $ of L){if($.op!=="set")continue;let X=$.cite.source_id??e.source.source_id,W=f.get(X);if(!W){a.push({code:"CITE_SOURCE_UNKNOWN",detail:`${i.temp_ref}: set cite source ${JSON.stringify(X)} is not in read_basis`});continue}let z={source_id:X,source_cid:W,anchor:$.cite.anchor,...$.cite.quote?{quote:$.cite.quote}:{},claim:$.text};A.push({ecid:q("DERIVES",W,Q,z),type:w.DERIVES,src:W,dst:Q,props:z})}for(let $ of L)$.op==="remove"&&S.push({about:R,ref:$.ref,text:$.text,reason:$.reason});I(i.temp_ref,{resolution:"supersede",supersedeTarget:R,reason:h.reason??`criteria merge: ${e.source.source_id} (${L.filter($=>$.op==="keep").length} kept, ${L.filter($=>$.op==="set").length} set, ${L.filter($=>$.op==="remove").length} removed)`},Q),P.push({id:Q,kind:"review-item",resolution:h.resolution,edit:h.resolution==="edited"?{...h.edit}:null,reason:null,by:c});continue}}else{let L=C.map(T=>typeof T=="string"?{text:T,cite:void 0}:T),H=ue({title:h.edit?.title??u.title??String(E.title??i.title),...u.description??E.description?{description:u.description??E.description}:{},...h.edit?.summary??u.summary??E.summary?{summary:h.edit?.summary??u.summary??E.summary}:{},...u.actors??E.actors?{actors:u.actors??E.actors}:{},...u.value??E.value?{value:u.value??E.value}:{},risk:h.edit?.risk??u.risk??String(E.risk??i.risk),...u.criteria?L.length>0?{criteria:L.map(T=>T.text)}:{}:E.criteria?{criteria:E.criteria}:{}}),j=se("usecase",H);if(j!==R){for(let T of re("usecase",H))a.push({code:T.code,detail:`${i.temp_ref}: ${T.detail}`});V.push({cid:j,label:te.USECASE,content:H}),A.push({ecid:q("DERIVES",Z.source_cid,j,Z),type:w.DERIVES,src:Z.source_cid,dst:j,props:Z});for(let T of L){if(!T.cite)continue;let B={source_id:e.source.source_id,source_cid:e.source.source_cid,anchor:T.cite.anchor,...T.cite.quote?{quote:T.cite.quote}:{},claim:T.text};A.push({ecid:q("DERIVES",B.source_cid,j,B),type:w.DERIVES,src:B.source_cid,dst:j,props:B})}I(i.temp_ref,{resolution:"supersede",supersedeTarget:R,reason:h.reason??`matches-but-changed: ${e.source.source_id} moved (${Object.keys(u).join(", ")})`},j),P.push({id:j,kind:"review-item",resolution:h.resolution,edit:h.resolution==="edited"?{...h.edit}:null,reason:null,by:c});continue}for(let T of L){if(!T.cite)continue;let B={source_id:e.source.source_id,source_cid:e.source.source_cid,anchor:T.cite.anchor,...T.cite.quote?{quote:T.cite.quote}:{},claim:T.text};A.push({ecid:q("DERIVES",B.source_cid,R,B),type:w.DERIVES,src:B.source_cid,dst:R,props:B})}}}if(i.changed&&h.resolution==="skipped"){let u=i.updated?.criteria??[];u.length>0&&he(u)==="ops"&&P.push({id:R,kind:"pending_update",resolution:"pending",edit:{temp_ref:i.temp_ref,source_id:e.source.source_id,updated:i.updated},reason:i.change_note??null,by:c})}if(h.resolution!=="rejected"){for(let u of ge(i)){let E=u.source_id??e.source.source_id,C=f.get(E);if(!C){a.push({code:"CITE_SOURCE_UNKNOWN",detail:`${i.temp_ref}: cite source ${JSON.stringify(E)} is not in read_basis`});continue}let M={source_id:E,source_cid:C,anchor:u.anchor,...u.quote?{quote:u.quote}:{}};A.push({ecid:q("DERIVES",C,R,M),type:w.DERIVES,src:C,dst:R,props:M})}(h.resolution==="approved"||h.resolution==="edited"||h.resolution==="supersede")&&P.push({id:R,kind:"review-item",resolution:"approved",edit:null,reason:null,by:c}),h.resolution==="supersede"&&I(i.temp_ref,h,R)}continue}for(let u of re("usecase",me))a.push({code:u.code,detail:`${i.temp_ref}: ${u.detail}`});for(let u of de(w.DERIVES,"source","usecase",Z))a.push({code:u.code,detail:`${i.temp_ref}: ${u.detail}`});V.push({cid:x,label:te.USECASE,content:me}),v.set(i.temp_ref,x),A.push({ecid:q("DERIVES",Z.source_cid,x,Z),type:w.DERIVES,src:Z.source_cid,dst:x,props:Z});for(let u of ge(i).slice(1)){let E=u.source_id??e.source.source_id,C=f.get(E);if(!C){a.push({code:"CITE_SOURCE_UNKNOWN",detail:`${i.temp_ref}: cite source ${JSON.stringify(E)} is not in read_basis`});continue}let M={source_id:E,source_cid:C,anchor:u.anchor,...u.quote?{quote:u.quote}:{}};for(let L of de(w.DERIVES,"source","usecase",M))a.push({code:L.code,detail:`${i.temp_ref}: ${L.detail}`});A.push({ecid:q("DERIVES",C,x,M),type:w.DERIVES,src:C,dst:x,props:M})}for(let u of i.criteria??[]){let E=u.cite.source_id??e.source.source_id,C=f.get(E);if(!C){a.push({code:"CITE_SOURCE_UNKNOWN",detail:`${i.temp_ref}: criterion cite source ${JSON.stringify(E)} is not in read_basis`});continue}let M={source_id:E,source_cid:C,anchor:u.cite.anchor,...u.cite.quote?{quote:u.cite.quote}:{},claim:u.text};A.push({ecid:q("DERIVES",M.source_cid,x,M),type:w.DERIVES,src:M.source_cid,dst:x,props:M})}for(let u of i.depends_on_hint??[]){let E=H=>H.toLowerCase().trim().replace(/\s+/g," "),C=null,M=t.resolve(u);if(M&&!M.superseded&&t.nodeLabel.get(M.cid)===te.USECASE&&(C=M.cid),!C){for(let{cid:H,content:j}of t.byLabel(te.USECASE))if(!t.superseded.has(H)&&E(String(j.title??""))===E(u)){C=H;break}}if(!C){let H=V.find(j=>j.label===te.USECASE&&E(String(j.content.title??""))===E(u));H&&(C=H.cid)}!C||C===x||Ke(t,w.DEPENDS_ON,x,C,K)||K.some(H=>H.src===x&&H.dst===C)||(A.push({ecid:q(w.DEPENDS_ON,x,C,{reason:"extract hint"}),type:w.DEPENDS_ON,src:x,dst:C,props:{reason:"extract hint"}}),K.push({src:x,dst:C,type:w.DEPENDS_ON}))}if((h.resolution==="approved"||h.resolution==="edited"||h.resolution==="supersede")&&t.superseded.get(x)===null&&!g.has(x)&&J.push({kind:"node",old:x,new:x,reason:`re-minted after tombstone via review by ${c.id}`,by:c}),n){let u=we("usecase",E=>_.has(E),t.names.keys());u!==null&&!t.nameOf.has(x)&&(_.add(u),ie.push({cid:x,slug:u,by:c}))}h.resolution==="approved"?P.push({id:x,kind:"review-item",resolution:"approved",edit:null,reason:null,by:c}):h.resolution==="edited"?P.push({id:x,kind:"review-item",resolution:"edited",edit:{...h.edit},reason:null,by:c}):h.resolution==="rejected"?P.push({id:x,kind:"review-item",resolution:"rejected",edit:null,reason:h.reason??null,by:c}):h.resolution==="supersede"&&(P.push({id:x,kind:"review-item",resolution:"approved",edit:null,reason:h.reason??null,by:c}),I(i.temp_ref,h,x))}if(a.length)return{record:null,errors:a};let O=new Date().toISOString(),G=(e.sources?.length??0)>1||(e.extraction_claims?.length??0)>0,D;if(G){let i=[];if(e.extraction_claims==null)i.push({source_id:e.source.source_id,source_cid:e.source.source_cid,completeness:"complete",...l?{extractor_version:l}:{},at:O});else{let h=new Map(e.extraction_claims.map(F=>[F.source_id,F.completeness]));for(let F of e.sources??[e.source]){let Y=h.get(F.source_id)??null;Y!==null&&i.push({source_id:F.source_id,source_cid:F.source_cid,completeness:Y,...l?{extractor_version:l}:{},at:O})}}D=i}else D=e.source.source_cid;let k=[];for(let i of r.probeHits??[])k.push({...v.has(i.tempRef)?{new_cid:v.get(i.tempRef)}:{},candidate_cid:i.candidateCid,score:i.score,scorer:i.scorer,probe_basis:null});for(let i of N){let h=v.get(i.tempRef);k.some(F=>F.new_cid===h&&F.candidate_cid===i.candidate_cid)||k.push({...h!==void 0?{new_cid:h}:{},candidate_cid:i.candidate_cid,score:i.score,scorer:i.scorer,probe_basis:null})}return{record:ee(s,{ts:O,proposal_id:o,...o!=null?{extraction_of:D}:{},...o!=null&&l?{extractor_version:l}:{},...S.length>0?{criteria_removed:S}:{},...k.length>0?{dedup_hits:k}:{},nodes:V,edges:A,review:P,supersessions:J,...ie.length>0?{names:ie}:{},...r.judgements&&r.judgements.length>0?{judgements:r.judgements}:{},...r.eventIds&&r.eventIds.length>0?{event_ids:r.eventIds}:r.sid?{event_ids:Je(t,r.sid,"extract",1)}:{},...r.sid?{sid:r.sid}:{},source_head_moves:{}},{expectPrev:m}).record,errors:null}}function wt(r){let{contextDir:s,graph:t,verdicts:e,by:o}=r,d=[],c=[],p=[],l=[],n=[],m=new Set,f=new Map;for(let[S,v]of e){if(v.resolution!=="edited")continue;let N=t.resolve(S);if(!N||N.superseded)continue;let y=t.getNode(N.cid);if(!y)continue;let b={...y.content,...v.edit?.title!==void 0?{title:v.edit.title}:{},...v.edit?.summary!==void 0?{summary:v.edit.summary}:{},...v.edit?.risk!==void 0?{risk:v.edit.risk}:{}};if(re(y.label,b).length>0)continue;let V=se(y.label,b);V===N.cid||Se(t,N.cid,V)||f.set(N.cid,V)}for(let[S,v]of e){if(v.resolution==="skipped")continue;let N=t.resolve(S);if(!N){d.push({code:"UNKNOWN_NODE",detail:`${S} names nothing in the graph`});continue}if(N.superseded){d.push({code:"SUPERSEDED_TARGET",detail:`${S} is superseded \u2014 review the tip (${N.tip})`});continue}let y=N.cid;if(v.resolution==="approved")l.push({id:y,kind:"review-item",resolution:"approved",edit:null,reason:null,by:o});else if(v.resolution==="rejected")r.holdArchives?l.push({id:y,kind:"pending_archive",resolution:"pending",edit:null,reason:v.reason??null,by:o}):l.push({id:y,kind:"review-item",resolution:"rejected",edit:null,reason:v.reason??null,by:o});else if(v.resolution==="edited"){if(m.has(y)){d.push({code:"DUPLICATE_TARGET",detail:`${S}: this node was already superseded by another verdict in this batch \u2014 one verdict per node`});continue}let b=t.getNode(y);if(!b){d.push({code:"UNKNOWN_NODE",detail:`${S}: node file unreadable`});continue}let V={...b.content,...v.edit?.title!==void 0?{title:v.edit.title}:{},...v.edit?.summary!==void 0?{summary:v.edit.summary}:{},...v.edit?.risk!==void 0?{risk:v.edit.risk}:{}},A=re(b.label,V);if(A.length>0){for(let J of A)d.push({code:J.code,detail:`${S}: ${J.detail}`});continue}let K=se(b.label,V);if(K===y){l.push({id:y,kind:"review-item",resolution:"approved",edit:null,reason:null,by:o});continue}if(Se(t,y,K)){d.push({code:"SUPERSEDE_CYCLE",detail:`${S}: edit reproduces an already-superseded version (supersession cycle guard) \u2014 re-edit forward or redesign`});continue}let P=ke({graph:t,oldTip:y,newCid:K,newLabel:b.label,by:o,reason:`re-blessed onto ${K} (edited in review)`,dstRedirect:f});if(P.errors.length>0){for(let J of P.errors)d.push({code:"REBLESS_REFUSED",detail:`${S}: ${J}`});continue}c.push({cid:K,label:b.label,content:V}),p.push(...P.edges),m.add(y),n.push({kind:"node",old:y,new:K,reason:v.reason??"edited in review",by:o}),n.push(...P.supersessions),l.push({id:K,kind:"review-item",resolution:"edited",edit:{...v.edit},reason:null,by:o})}else if(v.resolution==="supersede"){let b=De(t,v.supersedeTarget,y,m);if("error"in b){d.push({code:b.error.code,detail:`${S}: ${b.error.detail}`});continue}m.add(b.targetCid),r.holdArchives?l.push({id:b.targetCid,kind:"pending_archive",resolution:"pending",edit:null,reason:`supersede by ${y}${v.reason?` \u2014 ${v.reason}`:""}`,by:o}):(n.push({kind:"node",old:b.targetCid,new:y,reason:v.reason??`superseded via review by ${o.id}`,by:o}),l.push({id:y,kind:"review-item",resolution:"approved",edit:null,reason:v.reason??null,by:o}))}}return d.length?{record:null,errors:d}:l.length===0&&n.length===0?{record:null,errors:[{code:"NO_VERDICTS",detail:"every item was skipped \u2014 nothing to commit"}]}:{record:ee(s,{ts:new Date().toISOString(),proposal_id:null,nodes:c,edges:p,review:l,supersessions:n,source_head_moves:{}},{expectPrev:t.latestHash}).record,errors:null}}function Tt(r){let{contextDir:s,graph:t,survivor:e,merged:o,reason:d,by:c}=r,p=t.resolve(e),l=t.resolve(o);return p?l?p.superseded||l.superseded?{record:null,errors:[{code:"ALREADY_SUPERSEDED",detail:"a side of the pair is already superseded \u2014 the pair is drained"}]}:p.cid===l.cid?{record:null,errors:[{code:"SELF_SUPERSEDE",detail:"a pair cannot merge a node into itself"}]}:{record:ee(s,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[{kind:"node",old:l.cid,new:p.cid,reason:d??`pair merge: duplicate of ${e}`,by:c}],source_head_moves:{}},{expectPrev:t.latestHash}).record,errors:null}:{record:null,errors:[{code:"UNKNOWN_NODE",detail:`${o} names nothing in the graph`}]}:{record:null,errors:[{code:"UNKNOWN_NODE",detail:`${e} names nothing in the graph`}]}}function kt(r){let{contextDir:s,graph:t,assignments:e,by:o}=r,d=[],c=[],p=new Set;for(let{ref:n,slug:m}of e){if(!ae.test(m)){d.push({code:"BAD_SLUG",detail:`${JSON.stringify(m)} \u2014 slugs are kebab-case ${String(ae)}`});continue}let f=t.resolve(n);if(!f){d.push({code:"UNKNOWN_REF",detail:`${n} names nothing in the graph`});continue}if(f.superseded){d.push({code:"SUPERSEDED_TARGET",detail:`${n} is superseded \u2014 name the tip instead (${f.tip})`});continue}let a=t.names.get(m);if(a!==void 0&&!t.superseded.has(a)&&a!==f.cid||p.has(m)){d.push({code:"SLUG_TAKEN",detail:`${m} already names ${a??"another node in this record"}`});continue}p.add(m),c.push({cid:f.cid,slug:m,by:o})}return d.length?{record:null,errors:d}:c.length===0?{record:null,errors:[{code:"NO_ASSIGNMENTS",detail:"nothing to name"}]}:{record:ee(s,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[],names:c,source_head_moves:{}},{expectPrev:t.latestHash}).record,errors:null}}function Dt(r){let{contextDir:s,graph:t,sourceId:e,reason:o,by:d}=r,c=t.heads.get(e);return c===void 0?{record:null,errors:[{code:"UNKNOWN_SOURCE",detail:`no source ${e} in the graph`}]}:c===null?{record:null,errors:[{code:"ALREADY_RETIRED",detail:`source ${e} is already retired`}]}:{record:ee(s,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[{kind:"node",old:c,new:null,reason:o??`retired source ${e}`,by:d}],source_head_moves:{[e]:null},names:[]},{expectPrev:t.latestHash}).record,errors:null}}function At(r){let s=re("gap",r.content);if(s.length>0)return{ok:!1,refusal:`defer gap failed schema validation: ${s.map(d=>d.detail).join("; ")}`};let t=se("gap",r.content),e={reason:"reconcile change deferred"},o=r.annotates?[{ecid:q(w.ANNOTATES,t,r.annotates,e),type:w.ANNOTATES,src:t,dst:r.annotates,props:e}]:[];for(let d=0;;d++)try{return ee(r.contextDir,{ts:new Date().toISOString(),proposal_id:null,nodes:[{cid:t,label:"gap",content:r.content}],edges:o,review:[],supersessions:[],source_head_moves:{}},{expectPrev:le(r.contextDir)}),{ok:!0,cid:t}}catch(c){if(c instanceof Ee){if(d<3)continue;return{ok:!1,refusal:"concurrent activity kept moving the store \u2014 try the card again"}}throw c}}function Mt(r){let s=r.graph.byLabel("gap").filter(t=>t.content.kind==="reconcile_deferred"&&typeof t.content.uc=="string"&&r.graph.tipOf(t.content.uc)===r.targetTip&&(r.sourceId===void 0||t.content.basis?.source_id===void 0||t.content.basis.source_id===r.sourceId)&&!r.graph.superseded.has(t.cid)&&r.graph.trust.get(t.cid)!=="archived");if(s.length===0)return{resolved:0};for(let t=0;;t++)try{return ee(r.contextDir,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:s.map(e=>({kind:"node",old:e.cid,new:r.resolvedBy,reason:"reconcile change resolved by a later verdict",by:r.by})),source_head_moves:{}},{expectPrev:le(r.contextDir)}),{resolved:s.length}}catch(e){if(e instanceof Ee){if(t<3)continue;return{resolved:0}}throw e}}export{pe as a,Ue as b,Te as c,ve as d,Se as e,ke as f,ae as g,Ke as h,Rt as i,ge as j,he as k,Ae as l,bt as m,Be as n,Je as o,Ye as p,Ot as q,wt as r,Tt as s,kt as t,Dt as u,At as v,Mt as w,Me as x,Ve as y,ze as z,Oe as A,we as B,dt as C,at as D,fe as E};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as u,d as p}from"./chunk-G5ZGEZCA.js";import{spawn as h}from"child_process";var k=new Set(["progress","ask_user","graph_query","ingest_request","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete","state_checkpoint"]);function v(g,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:u();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=g.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=h(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(g.session_id,n.auth)});if(t.stdin.write(JSON.stringify(g)+`
2
+ import{c as u,d as p}from"./chunk-UDFDTFBL.js";import{spawn as h}from"child_process";var k=new Set(["progress","ask_user","graph_query","ingest_request","proposal","design","error","done","reasoning_delta","reasoning_done","tool_activity","decision_activity","text_delta","usage","receipt","chat_ops","session_paused","session_complete","state_checkpoint"]);function v(g,n={}){let a=n.spawnCmd!==void 0?n.spawnCmd:u();if(!a)throw new Error("assurance agent not found \u2014 your platform package may be missing; reinstall kane-cli (npm i -g @testmuai/kane-cli)");let f=g.source.images?.length??0;a.tier==="dev-python"&&f>0&&n.onWarn?.("warn: development agent in use \u2014 if image citations are missing, update the agent package");let t=h(a.cmd,a.args,{stdio:["pipe","pipe","pipe"],env:p(g.session_id,n.auth)});if(t.stdin.write(JSON.stringify(g)+`
3
3
  `),n.onStderr){let e="";t.stderr.on("data",r=>{e+=r.toString("utf8");let i;for(;(i=e.indexOf(`
4
4
  `))>=0;){let o=e.slice(0,i);e=e.slice(i+1),o.trim()&&n.onStderr(o)}})}let d=new Promise(e=>{t.on("exit",(r,i)=>e({code:r,signal:i}))});async function*m(){let e="",r=!1;for await(let i of t.stdout){e+=i.toString("utf8");let o;for(;(o=e.indexOf(`
5
5
  `))>=0;){let l=e.slice(0,o).trim();if(e=e.slice(o+1),!l)continue;let c;try{c=JSON.parse(l)}catch{n.onWarn?.(`agent: skipping malformed line: ${l.slice(0,120)}`);continue}let s=c;if(!s||typeof s!="object"||!k.has(s.type)){n.onWarn?.(`agent: skipping unknown event type "${s&&typeof s=="object"?String(s.type??"?"):"?"}"`);continue}if(yield s,s.type==="done"){r=!0;break}}if(r)break}await d.catch(()=>{})}return{events:m(),send:e=>{t.stdin&&!t.stdin.destroyed&&t.stdin.write(JSON.stringify(e)+`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{g as h}from"./chunk-DP7GPS6S.js";import{e as l}from"./chunk-OXHMUZJV.js";import{b as u}from"./chunk-DBIBROYW.js";import{d as f}from"./chunk-AKX4VRRR.js";import{existsSync as w,readFileSync as _,readdirSync as R}from"fs";import{join as p}from"path";function g(i,r){let{records:t}=l(i),o=new Set;for(let e of t)for(let n of e.review)n.resolution!=="pending"&&o.add(n.id);let s=[],d=new Set;for(let e=t.length-1;e>=0;e--)for(let n of t[e].dedup_hits??[]){if(n.new_cid===void 0)continue;let c=`${n.new_cid}|${n.candidate_cid}`;d.has(c)||(d.add(c),!o.has(n.new_cid)&&(r.superseded.has(n.new_cid)||r.superseded.has(n.candidate_cid)||r.trust.get(n.new_cid)==="derived"&&s.push({new_cid:n.new_cid,candidate_cid:n.candidate_cid,score:n.score,scorer:n.scorer})))}return s}var a=(i,r)=>i.displayNameOf(r)??r.slice(0,19);function m(i,r){return{design_children:i.edgesInto(r).filter(o=>(o.type==="belongs_to"||o.type==="scoped_to")&&!i.superseded.has(o.src)).length}}function v(i,r){let{records:t}=l(i),o=new Set,s=new Map;for(let e of t)for(let n of e.review)n.kind==="pending_archive"?s.set(n.id,n.reason):n.resolution!=="pending"&&o.add(n.id);let d=new Map;for(let[e,n]of s)r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||d.set(e,n);return{all:s,live:d}}function y(i,r){let t=[],o=new Set;for(let e of g(i.contextDir,r)){o.add(e.new_cid);let n=e.scorer==="lexical_fallback"?" (lexical fallback \u2014 the probe ran degraded)":"";t.push({kind:"PAIR",ref:a(r,e.new_cid),title:String(r.getNode(e.new_cid)?.content.title??e.new_cid.slice(0,12)),why:`possible duplicate of ${a(r,e.candidate_cid)} \u2014 score ${e.score}${n}`,pair:{candidate_cid:e.candidate_cid,candidate_ref:a(r,e.candidate_cid),score:e.score,scorer:e.scorer}})}let{all:s,live:d}=v(i.contextDir,r);for(let[e,n]of d)t.push({kind:"REVIEW",ref:a(r,e),title:String(r.getNode(e)?.content.title??e.slice(0,12)),why:`archive held for interactive confirmation${n?` \u2014 ${n}`:""}`,held:!0,impact:m(r,e)});for(let e of k(i.contextDir))t.push({kind:"MODIFY_HELD",ref:`${e.sid}:${e.tempRef}`,title:String(e.content.title??e.tempRef),why:`${e.rationale} \u2014 held by paused/dead session ${e.sid}`,heldPayload:e});for(let{cid:e,content:n}of r.byLabel(f.USECASE))r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||s.has(e)||t.push({kind:"REVIEW",ref:a(r,e),title:String(n.title??e.slice(0,12)),why:"unreviewed \u2014 approve, archive, or defer",impact:m(r,e)});return t}function F(i,r){let t={REVIEW:0,PAIR:0,MODIFY_HELD:0};for(let o of y(i,r))t[o.kind]++;return t}function b(i,r){try{let t=JSON.parse(_(p(i,"sessions",r,".lock"),"utf8"));return typeof t.pid=="number"&&u(t.pid)}catch{return!1}}function k(i){let r=[],t=p(i,"sessions");if(!w(t))return r;let o=[];try{o=R(t)}catch{return r}for(let s of o){if(!w(p(t,s,"state.json"))||b(i,s))continue;let d=[],e=!1;try{let c=h(i,s).kane;c?.pending?.proposals?.length&&(d=c.pending.proposals,e=!0)}catch{e=!1}if(!e)try{d=JSON.parse(_(p(t,s,"state.json"),"utf8")).pending?.proposals??[]}catch{continue}for(let n of d)r.push({sid:s,tempRef:String(n.tempRef??n.temp_ref??"held"),...typeof n.event_id=="string"?{event_id:n.event_id}:{},label:String(n.label??"usecase"),content:n.content??{},rationale:String(n.rationale??"held payload")})}return r}export{m as a,v as b,y as c,F as d};
2
+ import{g as h}from"./chunk-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,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{c as m,d as g,e as f}from"./chunk-ZMJD3CI7.js";import{b as d}from"./chunk-DEUDRSU7.js";import{mkdirSync as M,writeFileSync as o,existsSync as c,readFileSync as O}from"fs";import{join as a}from"path";var p={name:"remote-execution",version:"0.3.0",backendId:"hyper",kaneCompat:">=0.4.0",defaults:{runson:"mac",concurrency:1}},E={runson:"mac",concurrency:1,timeoutMinutes:120},y=`version: "0.1"
2
+ import{c as m,d as g,e as f}from"./chunk-4E4GJPEM.js";import{b as d}from"./chunk-NJJQL54J.js";import{mkdirSync as M,writeFileSync as o,existsSync as c,readFileSync as O}from"fs";import{join as a}from"path";var p={name:"remote-execution",version:"0.3.0",backendId:"hyper",kaneCompat:">=0.4.0",defaults:{runson:"mac",concurrency:1}},E={runson:"mac",concurrency:1,timeoutMinutes:120},y=`version: "0.1"
3
3
  runson: {{runson}}
4
4
  autosplit: true
5
5
  concurrency: {{concurrency}}
@@ -1,8 +1,8 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as K}from"./chunk-HFRMJP2P.js";import{a as B,b as U,c as Y}from"./chunk-Z4QLCWLB.js";import{a as j}from"./chunk-DNNZ353O.js";import{d as F}from"./chunk-YMLC55J4.js";import{C as k,a as L,b as V,m as G,q as N}from"./chunk-R4EGL7VM.js";import{e as I}from"./chunk-OXHMUZJV.js";import{d as v,e as x,g as H}from"./chunk-AKX4VRRR.js";function ee(t,e,n,i,s){let f=n.rows.filter(u=>{let d=i.get(u.temp_ref);return d!==void 0&&d!=="reject"});if(f.length===0)return{record:null,errors:null};let o={version:1,read_basis:e.latestHash,source:{source_id:n.source_id,source_cid:e.heads.get(n.source_id)??""},use_cases:f.map(u=>u.uc)},p=new Map;for(let u of f){let d=i.get(u.temp_ref);typeof d=="object"?p.set(u.temp_ref,{resolution:"edited",edit:d.edited}):p.set(u.temp_ref,{resolution:u.uc.matches_existing&&u.uc.changed?"edited":"approved"})}let g=Y(o,e,n.staged_source_cid);if(g.errors!==null)return{record:null,errors:g.errors};let r=g.proposal,l=o.source.source_cid?D(t,e,o.source.source_cid):null;if(l!==null){r=U(r,l);let u=G(r,B(l),e);if(u.length>0)return{record:null,errors:[{code:"HELD_CITES_STALE",detail:"the source moved after this plan staged \u2014 its quotes no longer verify against the current head; re-run kane-cli maintain reconcile to re-stage"},...u]}}let m=`held-${(e.latestHash??"root").slice(-12)}-${f.length}`;return N({contextDir:t,graph:e,proposal:r,proposalId:m,verdicts:p,by:s,autoName:!0})}function W(t,e,n=[]){let i=K(t,e),s=new Set,f=[],o=l=>{!l||s.has(l)||(s.add(l),f.push(y(t,l)))};for(let l of i.pairs)o(l.scenario),o(l.test);for(let[l,m]of i.verifies){o(l);for(let u of m)o(u)}if(n.length===0)return{stale_refs:f};let p=l=>`${String(l.props.source_id)}\0${String(l.props.anchor)}`,g=new Set;for(let{cid:l}of t.byLabel(v.USECASE))if(t.tipOf(l)===e)for(let m of t.edgesInto(l)){if(m.type!==x.DERIVES)continue;let u=m.props.claim;typeof u=="string"&&n.includes(u)&&g.add(p(m))}if(g.size===0)return{stale_refs:f};let r=new Set;for(let[l,m]of i.verifies)if(t.edgesInto(l).some(d=>d.type===x.DERIVES&&g.has(p(d)))){r.add(y(t,l));for(let d of m)r.add(y(t,d))}return{stale_refs:f,...r.size>0?{direct_refs:[...r]}:{}}}var q="this release plans changes only \u2014 blast-radius impact and drift meaning-checks are not measured, and REMOVE rows are never executed automatically",te="suite untouched; graph updated";function M(t,e){return!t.superseded.has(e)&&t.trust.get(e)!=="archived"}function y(t,e,n=new Set){let i=t.nameOf.get(e);if(i!==void 0)return i;if(n.has(e))return e;n.add(e);for(let[s,f]of t.superseded){if(f!==e)continue;let o=y(t,s,n);if(o!==s)return o}return e}function C(t){return String(t).slice(0,19)}function A(t,e,n){let i=t.edgesFrom(e).find(s=>s.type===n);return i?t.tipOf(i.dst):null}function X(t,e){let n=t.nodeLabel.get(e);if(n===v.USECASE)return e;if(n===v.SCENARIO)return A(t,e,x.BELONGS_TO);if(n===v.AC){let i=A(t,e,x.SCOPED_TO);return i?t.nodeLabel.get(i)===v.USECASE?i:A(t,i,x.BELONGS_TO):null}if(n===v.TEST){let i=A(t,e,x.AUTOMATES);return i?A(t,i,x.BELONGS_TO):null}return null}function z(t,e){let n=[],i=new Map;for(let s of t.derivesInto(e))i.set(String(s.props.source_id),s);for(let[s,f]of i){let o=t.heads.get(s);if(o==null){n.push(`DERIVES pin ${s} @ ${C(f.props.source_cid)} \u2014 source retired`);continue}if(o!==f.props.source_cid){let p=t.convChains.get(s)?.chain;if(p&&p.includes(String(f.props.source_cid)))continue;n.push(`DERIVES pin ${s} @ ${C(f.props.source_cid)} \u2014 source head moved to ${C(o)}`)}}for(let s of t.edgesFrom(e))H(s.type)?.pin?.comparesTo==="dst_tip"&&t.superseded.has(s.dst)&&n.push(`${s.type} pin \u2192 ${y(t,s.dst)} \u2014 target superseded`);return n.join("; ")||"structural pin broken"}var ne=new Set([v.USECASE,v.SCENARIO,v.AC,v.TEST]);function $(t,e){return t.ref<e.ref?-1:t.ref>e.ref?1:0}function D(t,e,n){let i=j(t,e,n);return i===null?null:i.toString("utf8")}function se(t,e,n,i,s){let f=n.props.quote;if(typeof f=="string"&&f.length>0)return i.includes(f);let o=String(n.props.source_cid);s.has(o)||s.set(o,D(t,e,o));let p=s.get(o);if(p===null)return!1;let g=V(p,String(n.props.anchor));return g===null?!1:g.split(`
2
+ import{b as K}from"./chunk-U2CIXGZR.js";import{a as B,b as U,c as Y}from"./chunk-KGKJU27A.js";import{a as j}from"./chunk-DNNZ353O.js";import{d as F}from"./chunk-YMLC55J4.js";import{C as k,a as L,b as V,m as G,q as N}from"./chunk-W3Z7AZNT.js";import{e as I}from"./chunk-XMTSHHYQ.js";import{d as v,e as x,g as H}from"./chunk-AKX4VRRR.js";function ee(t,e,n,i,s){let f=n.rows.filter(u=>{let d=i.get(u.temp_ref);return d!==void 0&&d!=="reject"});if(f.length===0)return{record:null,errors:null};let o={version:1,read_basis:e.latestHash,source:{source_id:n.source_id,source_cid:e.heads.get(n.source_id)??""},use_cases:f.map(u=>u.uc)},p=new Map;for(let u of f){let d=i.get(u.temp_ref);typeof d=="object"?p.set(u.temp_ref,{resolution:"edited",edit:d.edited}):p.set(u.temp_ref,{resolution:u.uc.matches_existing&&u.uc.changed?"edited":"approved"})}let g=Y(o,e,n.staged_source_cid);if(g.errors!==null)return{record:null,errors:g.errors};let r=g.proposal,l=o.source.source_cid?D(t,e,o.source.source_cid):null;if(l!==null){r=U(r,l);let u=G(r,B(l),e);if(u.length>0)return{record:null,errors:[{code:"HELD_CITES_STALE",detail:"the source moved after this plan staged \u2014 its quotes no longer verify against the current head; re-run kane-cli maintain reconcile to re-stage"},...u]}}let m=`held-${(e.latestHash??"root").slice(-12)}-${f.length}`;return N({contextDir:t,graph:e,proposal:r,proposalId:m,verdicts:p,by:s,autoName:!0})}function W(t,e,n=[]){let i=K(t,e),s=new Set,f=[],o=l=>{!l||s.has(l)||(s.add(l),f.push(y(t,l)))};for(let l of i.pairs)o(l.scenario),o(l.test);for(let[l,m]of i.verifies){o(l);for(let u of m)o(u)}if(n.length===0)return{stale_refs:f};let p=l=>`${String(l.props.source_id)}\0${String(l.props.anchor)}`,g=new Set;for(let{cid:l}of t.byLabel(v.USECASE))if(t.tipOf(l)===e)for(let m of t.edgesInto(l)){if(m.type!==x.DERIVES)continue;let u=m.props.claim;typeof u=="string"&&n.includes(u)&&g.add(p(m))}if(g.size===0)return{stale_refs:f};let r=new Set;for(let[l,m]of i.verifies)if(t.edgesInto(l).some(d=>d.type===x.DERIVES&&g.has(p(d)))){r.add(y(t,l));for(let d of m)r.add(y(t,d))}return{stale_refs:f,...r.size>0?{direct_refs:[...r]}:{}}}var q="this release plans changes only \u2014 blast-radius impact and drift meaning-checks are not measured, and REMOVE rows are never executed automatically",te="suite untouched; graph updated";function M(t,e){return!t.superseded.has(e)&&t.trust.get(e)!=="archived"}function y(t,e,n=new Set){let i=t.nameOf.get(e);if(i!==void 0)return i;if(n.has(e))return e;n.add(e);for(let[s,f]of t.superseded){if(f!==e)continue;let o=y(t,s,n);if(o!==s)return o}return e}function C(t){return String(t).slice(0,19)}function A(t,e,n){let i=t.edgesFrom(e).find(s=>s.type===n);return i?t.tipOf(i.dst):null}function X(t,e){let n=t.nodeLabel.get(e);if(n===v.USECASE)return e;if(n===v.SCENARIO)return A(t,e,x.BELONGS_TO);if(n===v.AC){let i=A(t,e,x.SCOPED_TO);return i?t.nodeLabel.get(i)===v.USECASE?i:A(t,i,x.BELONGS_TO):null}if(n===v.TEST){let i=A(t,e,x.AUTOMATES);return i?A(t,i,x.BELONGS_TO):null}return null}function z(t,e){let n=[],i=new Map;for(let s of t.derivesInto(e))i.set(String(s.props.source_id),s);for(let[s,f]of i){let o=t.heads.get(s);if(o==null){n.push(`DERIVES pin ${s} @ ${C(f.props.source_cid)} \u2014 source retired`);continue}if(o!==f.props.source_cid){let p=t.convChains.get(s)?.chain;if(p&&p.includes(String(f.props.source_cid)))continue;n.push(`DERIVES pin ${s} @ ${C(f.props.source_cid)} \u2014 source head moved to ${C(o)}`)}}for(let s of t.edgesFrom(e))H(s.type)?.pin?.comparesTo==="dst_tip"&&t.superseded.has(s.dst)&&n.push(`${s.type} pin \u2192 ${y(t,s.dst)} \u2014 target superseded`);return n.join("; ")||"structural pin broken"}var ne=new Set([v.USECASE,v.SCENARIO,v.AC,v.TEST]);function $(t,e){return t.ref<e.ref?-1:t.ref>e.ref?1:0}function D(t,e,n){let i=j(t,e,n);return i===null?null:i.toString("utf8")}function se(t,e,n,i,s){let f=n.props.quote;if(typeof f=="string"&&f.length>0)return i.includes(f);let o=String(n.props.source_cid);s.has(o)||s.set(o,D(t,e,o));let p=s.get(o);if(p===null)return!1;let g=V(p,String(n.props.anchor));return g===null?!1:g.split(`
3
3
  `).some(r=>r.trim().length>0&&i.includes(r.trim()))}function oe(t,e,n){let i=L(String(e.props.anchor));if(i?.kind!=="img-part")return!1;let f=(t.mediaOf(String(e.props.source_cid)).images??[]).find(r=>r.ref===i.ref),o=f?.blob;if(o===void 0)return!1;let p=t.mediaOf(n).images??[];if(p.some(r=>r.blob===o))return!0;let g=f?.appearance;return g!==void 0&&p.filter(r=>r.appearance===g).length===1}var J=128*1024,Q=64*1024;function re(t,e){let n=t.split(`
4
4
  `),i=e.split(`
5
5
  `),s=0;for(;s<n.length&&s<i.length&&n[s]===i[s];)s++;let f=n.length,o=i.length;for(;f>s&&o>s&&n[f-1]===i[o-1];)f--,o--;if(f===s&&o===s)return"";let p=n.slice(s,f),g=i.slice(s,o),l=ie(p,g,2e3),m=[];if(l===null)m.push(`@@ old L${s+1}-L${f} \u2192 new L${s+1}-L${o} @@`,...p.map(u=>`- ${u}`),...g.map(u=>`+ ${u}`));else{let u=l.map((a,h)=>a.op==="="?-1:h).filter(a=>a>=0),d=0;for(;d<u.length;){let a=d;for(;a+1<u.length&&u[a+1]-u[a]<=3;)a++;let h=Math.max(u[d]-1,0),R=Math.min(u[a]+1,l.length-1),b=l.slice(h,R+1),S=s+(b[0].ai??0)+1,_=s+(b[0].bi??0)+1,c=b.filter(E=>E.op!=="+").length,w=b.filter(E=>E.op!=="-").length;m.push(`@@ old L${S}-L${S+Math.max(c-1,0)} \u2192 new L${_}-L${_+Math.max(w-1,0)} @@`);for(let E of b)m.push(E.op==="="?` ${E.line}`:`${E.op} ${E.line}`);d=a+1}}return m.join(`
6
6
  `)}function ie(t,e,n){let i=t.length,s=e.length,f=Math.min(i+s,n),o=new Map([[1,0]]),p=[],g=!1;for(let u=0;u<=f&&!g;u++){p.push(new Map(o));for(let d=-u;d<=u;d+=2){let a=d===-u||d!==u&&(o.get(d-1)??0)<(o.get(d+1)??0)?o.get(d+1)??0:(o.get(d-1)??0)+1,h=a-d;for(;a<i&&h<s&&t[a]===e[h];)a++,h++;if(o.set(d,a),a>=i&&h>=s){g=!0;break}}}if(!g)return null;let r=i,l=s,m=[];for(let u=p.length-1;u>0;u--){let d=p[u],a=r-l,h=a===-u||a!==u&&(d.get(a-1)??0)<(d.get(a+1)??0)?a+1:a-1,R=d.get(h)??0,b=R-h;for(;r>R&&l>b;)m.push({op:"=",line:t[r-1],ai:r-1,bi:l-1}),r--,l--;u>0&&(r===R?(m.push({op:"+",line:e[l-1],ai:r,bi:l-1}),l--):(m.push({op:"-",line:t[r-1],ai:r-1,bi:l}),r--))}for(;r>0&&l>0;)m.push({op:"=",line:t[r-1],ai:r-1,bi:l-1}),r--,l--;for(;r>0;)m.push({op:"-",line:t[r-1],ai:r-1,bi:0}),r--;for(;l>0;)m.push({op:"+",line:e[l-1],ai:0,bi:l-1}),l--;return m.reverse()}function ce(t){let e=Buffer.byteLength(t,"utf8");if(e<=J+Q)return{diff:t,truncated:!1};let n=Buffer.from(t,"utf8"),i=J;for(;i>0&&(n[i]&192)===128;)i--;let s=e-Q;for(;s<e&&(n[s]&192)===128;)s++;let f=n.subarray(0,i).toString("utf8"),o=n.subarray(s).toString("utf8");return{diff:`${f}
7
7
  \u2026 [diff truncated: ${e-i-(e-s)} bytes omitted] \u2026
8
- ${o}`,truncated:!0}}function ae(t,e){let n=k(t),i=n.heads.get(e);if(typeof i!="string")return null;let s=[];for(let d of I(t).records){let a=d.source_head_moves?.[e];a!==void 0&&a!==s[s.length-1]&&s.push(a)}let f=s.lastIndexOf(i),o=f>0?s[f-1]:null;if(typeof o!="string"||o===i)return null;let p=D(t,n,o),g=D(t,n,i);if(p===null||g===null)return null;let{diff:r,truncated:l}=ce(re(p,g)),m=new Set,u=[];for(let d of n.edgesFrom(o))d.type!==x.DERIVES||n.nodeLabel.get(d.dst)!==v.USECASE||m.has(d.dst)||(m.add(d.dst),u.push({id:d.dst,title:String(n.getNode(d.dst)?.content.title??"")}));return{source_id:e,old_head:o,new_head:i,diff:r,...l?{truncated:!0}:{},prior_ucs:u}}function de(t,e,n){let i=t.getNode(e)?.content??{},s=t.getNode(n)?.content??{},o=[...new Set([...Object.keys(i),...Object.keys(s)])].sort().filter(p=>JSON.stringify(i[p])!==JSON.stringify(s[p]));return o.length>0?`updated: ${o.join(", ")}`:"updated"}function le(t,e,n,i,s,f,o){let p=new Set((o?.rows??[]).map(a=>a.matched_cid).filter(a=>!!a)),g=[];for(let[a,h]of n.superseded)h===null||a===h||e.superseded.has(a)||n.nodeLabel.get(a)===v.USECASE&&g.push({kind:"MODIFY",ref:y(n,a),old_cid:a,new_cid:h,summary:de(n,a,h)});let r=f.map(a=>({kind:"ADD",ref:y(n,a),cid:a}));for(let a of o?.rows??[])a.kind==="MODIFY"&&a.matched_cid?g.push({kind:"MODIFY",ref:y(n,a.matched_cid),old_cid:a.matched_cid,new_cid:null,summary:`${a.why} (staged)`}):a.kind==="ADD"&&r.push({kind:"ADD",ref:a.title,cid:null});let l=[],m=D(t,n,s),u=new Map;for(let{cid:a}of n.byLabel(v.USECASE)){if(!M(n,a)||p.has(a))continue;let h=n.derivesInto(a),R=h.filter(_=>String(_.props.source_id)===i);R.length===0||R.some(_=>_.props.source_cid===s)||R.some(_=>{let c=String(_.props.anchor),w=L(c);return w?.kind==="img-whole"?!1:w?.kind==="img-part"?oe(n,_,s):m!==null&&se(t,n,_,m,u)})||h.some(_=>{let c=String(_.props.source_id);if(c===i)return!1;let w=n.heads.get(c);return w!=null})||l.push({kind:"ARCHIVE",ref:y(n,a),cid:a,why:`evidence decayed: no quote from ${i} relocates into @${C(s)}, no other live source, no fresh evidence this run`,impact:W(n,n.tipOf(a))})}let d=(a,h)=>a.ref<h.ref?-1:a.ref>h.ref?1:0;return[...g.sort(d),...r.sort(d),...l.sort(d)]}function Ee(t,e,n,i,s){let f=e.rows.find(d=>d.temp_ref===n);if(!f)return{ok:!1,message:`held item ${n} missing from the plan artifact`};let o=f,p=k(t);if(o.matched_cid){let d=p.tipOf(o.matched_cid);if(p.superseded.get(d)===null)return{ok:!1,message:`use-case for "${o.title}" was retired meanwhile \u2014 nothing to update`};d!==o.matched_cid&&(o={...o,matched_cid:d,uc:{...o.uc,matches_existing:{cid:d}}})}let g=s?{edited:s}:"approve",r=ee(t,p,{source_id:e.source_id,...e.staged_source_cid!==void 0?{staged_source_cid:e.staged_source_cid}:{},rows:[o]},new Map([[o.temp_ref,g]]),i);if(r.errors)return{ok:!1,message:r.errors.map(d=>`${d.code}: ${d.detail}`).join("; ")};let l=k(t),m=o.matched_cid?l.tipOf(o.matched_cid):r.record?.nodes.find(d=>d.label==="usecase")?.cid??r.record?.review[0]?.id;return{ok:!0,ref:m?y(l,m):o.title,kind:o.kind}}async function Re(t,e,n,i={}){let s=k(t),f=s.heads.get(e)??null,o=new Set(s.staleList().filter(c=>c.state==="stale").map(c=>c.cid)),p=await n.reingest(e);if(p.status==="unchanged"&&!i.resumeHeld)return{source_id:e,changed:!1,head:{status:p.status,before:f,after:p.cid},note:`nothing to reconcile \u2014 ${e} is unchanged`,skipped_arms:q,changeset:[],rows:[]};let g=i.resumeHeld?{minted:[],matched:[],held:i.resumeHeld}:await n.reextract(e),r=k(t),l=g.minted.map(c=>{let w=y(r,c);return{kind:"ADD",origin:"content-change",ref:w,reason:`new use-case extracted from ${e}`,provenance:`extraction commit \u2014 DERIVES ${e} @ ${C(p.cid)}`,action:`kane-cli design tests --use-case ${w}`}}),m=r.staleList().filter(c=>c.state==="stale"&&!o.has(c.cid)&&M(r,c.cid)).map(c=>c.cid),u=m.map(c=>{let w=y(r,c),E=ne.has(r.nodeLabel.get(c)??"");return{kind:"MODIFY",origin:"structural-stale",ref:w,reason:"stale (structural)",provenance:z(r,c),action:E?`kane-cli maintain evolve ${w}`:`kane-cli design explain ${w}`}}),d=[],a=[];for(let c of g.held?.rows??[])if(c.kind==="ADD")d.push({kind:"ADD",origin:"content-change",ref:c.title,held_ref:c.temp_ref,reason:`${c.why} (staged \u2014 commits on approval)`,provenance:`staged extraction of ${e} @ ${C(p.cid)}`,action:"approve to commit + design"});else{let w=c.matched_cid?r.tipOf(c.matched_cid):null,E=w?r.getNode(w)?.content.criteria??[]:[],T=(c.uc.updated?.criteria??[]).map(O=>typeof O=="string"?O:O.text),Z=[...T.filter(O=>!E.includes(O)),...c.uc.updated?.criteria!==void 0?E.filter(O=>!T.includes(O)):[]],P=w?W(r,w,Z):void 0;a.push({kind:"MODIFY",origin:"content-change",ref:c.matched_cid?y(r,c.matched_cid):c.title,held_ref:c.temp_ref,reason:`${c.why} (staged \u2014 commits on approval)`,provenance:`staged extraction of ${e} @ ${C(p.cid)}`,action:"approve to commit the updated version (old\u2192new redirect)",...P?{impact:P}:{}})}let h=new Set;for(let c of[...g.minted,...g.matched])h.add(r.tipOf(c));for(let c of g.held?.rows??[])c.matched_cid&&h.add(r.tipOf(c.matched_cid));for(let c of m){let w=X(r,r.tipOf(c));w&&r.nodeLabel.get(w)===v.USECASE&&h.add(r.tipOf(w))}let R=[];for(let c of await F(r,"design")){if(c.kind!=="no-verifies")continue;let w=r.resolve(c.ref);if(!w)continue;let E=X(r,w.tip);!E||!h.has(r.tipOf(E))||R.push({kind:"ADD",origin:"content-change",ref:c.ref,reason:c.why,provenance:`gaps engine (design) \u2014 uncovered AC of touched use-case ${y(r,E)}`,action:c.ready_command})}let b=[];for(let{cid:c}of r.byLabel(v.USECASE))M(r,c)&&r.stale(c)==="orphaned"&&b.push({kind:"REMOVE",ref:y(r,c),reason:"orphaned \u2014 no live source evidences this use-case",provenance:z(r,c),action:"plan-only \u2014 REMOVE is not executed in this release"});let S=new Set,_=[...l.sort($),...d.sort($),...R.sort($),...a.sort($),...u.sort($),...b.sort($)].filter(c=>{let w=`${c.kind}\0${c.ref}`;return S.has(w)?!1:(S.add(w),!0)});return{source_id:e,changed:!0,head:{status:p.status,before:f,after:p.cid},note:te,skipped_arms:q,changeset:le(t,s,r,e,p.cid,g.minted,g.held),rows:_,...g.held?{held:g.held}:{}}}function ye(t,e){return async n=>{let{ingestFile:i}=await import("./ingest-WTPY2VLS.js"),{convertPdf:s}=await import("./pdf-convert-OZIRUADA.js"),{convertDocx:f}=await import("./docx-convert-BIV5T7F5.js"),o=await i({contextDir:t,filePath:e,asId:n,converters:{pdf:s,docx:f}});return{status:o.status,cid:o.cid}}}function be(t,e,n,i){return async()=>{let f=(i??(await import("./dispatch-NE35HS5F.js")).findProvider)(e);if(!f)throw new Error(`the remote re-ingest failed \u2014 no provider matches '${e}'`);let o=await f.ingest(e,void 0,{out:n.out,err:n.err,confirm:async()=>!0,isTTY:!1},t,void 0);if(o.code!==0||!o.result)throw new Error("the remote re-ingest failed \u2014 fix the reported problem and re-run");return{status:o.result.status,cid:o.result.source_cid}}}function xe(t,e={}){return async n=>{let i=[],[{runExtract:s},{resolveAgentAuthEnv:f},{runAgent:o},{preflightTurn:p}]=await Promise.all([import("./run-PZIYMD35.js"),import("./spawner-URQ5OAY7.js"),import("./bridge-WFSSMJ57.js"),import("./turn-preflight-JGYT7LXP.js")]),g=await f(),r=new Set(k(t).byLabel(v.USECASE).map(S=>S.cid)),l=ae(t,n)??void 0,m=0,u=await s({mode:"override",source:n,...l?{changeContext:l}:{}},{contextDir:t,agent:o,preflightTurn:()=>p(g),ask:async()=>[],review:async S=>{if(!e.stage)return new Map(S.map(c=>[c.temp_ref,{resolution:c.matches_existing&&c.changed?"edited":"skipped"}]));let _=new Map;for(let c of S){if(c.matches_existing&&!c.changed){_.set(c.temp_ref,{resolution:"skipped"});continue}i.push({kind:c.matches_existing?"MODIFY":"ADD",temp_ref:c.temp_ref,title:c.title,why:c.matches_existing?`updated: ${Object.keys(c.updated??{}).join(", ")||"content"}`:`newly extracted from ${n}`,...c.matches_existing?{matched_cid:c.matches_existing.cid,updated:c.updated}:{},uc:c}),_.set(c.temp_ref,{resolution:"rejected"})}return _},confirmStale:async()=>!1,out:S=>e.hostOut?.(S),progress:S=>e.hostProgress?.(S),emit:S=>{S.type==="commit"&&typeof S.assumed=="number"&&(m+=S.assumed),e.hostEmit?.(S)},isTTY:!1,auth:g});if(u!==0)throw new Error(`reconcile: re-extract of ${n} failed (exit ${u})`);let d=k(t),a=d.heads.get(n),h=[],R=[];if(typeof a=="string"){let S=new Set;for(let _ of d.edgesFrom(a))_.type!==x.DERIVES||d.nodeLabel.get(_.dst)!==v.USECASE||S.has(_.dst)||(S.add(_.dst),!(e.stage&&d.trust.get(_.dst)==="archived")&&(r.has(_.dst)?R:h).push(_.dst))}let b=k(t).heads.get(n);return{minted:h,matched:R,defaultsTaken:m,...e.stage?{held:{source_id:n,...b!=null?{staged_source_cid:b}:{},rows:i}}:{}}}}export{ee as a,W as b,q as c,te as d,M as e,X as f,ne as g,re as h,ce as i,ae as j,Ee as k,Re as l,ye as m,be as n,xe as o};
8
+ ${o}`,truncated:!0}}function ae(t,e){let n=k(t),i=n.heads.get(e);if(typeof i!="string")return null;let s=[];for(let d of I(t).records){let a=d.source_head_moves?.[e];a!==void 0&&a!==s[s.length-1]&&s.push(a)}let f=s.lastIndexOf(i),o=f>0?s[f-1]:null;if(typeof o!="string"||o===i)return null;let p=D(t,n,o),g=D(t,n,i);if(p===null||g===null)return null;let{diff:r,truncated:l}=ce(re(p,g)),m=new Set,u=[];for(let d of n.edgesFrom(o))d.type!==x.DERIVES||n.nodeLabel.get(d.dst)!==v.USECASE||m.has(d.dst)||(m.add(d.dst),u.push({id:d.dst,title:String(n.getNode(d.dst)?.content.title??"")}));return{source_id:e,old_head:o,new_head:i,diff:r,...l?{truncated:!0}:{},prior_ucs:u}}function de(t,e,n){let i=t.getNode(e)?.content??{},s=t.getNode(n)?.content??{},o=[...new Set([...Object.keys(i),...Object.keys(s)])].sort().filter(p=>JSON.stringify(i[p])!==JSON.stringify(s[p]));return o.length>0?`updated: ${o.join(", ")}`:"updated"}function le(t,e,n,i,s,f,o){let p=new Set((o?.rows??[]).map(a=>a.matched_cid).filter(a=>!!a)),g=[];for(let[a,h]of n.superseded)h===null||a===h||e.superseded.has(a)||n.nodeLabel.get(a)===v.USECASE&&g.push({kind:"MODIFY",ref:y(n,a),old_cid:a,new_cid:h,summary:de(n,a,h)});let r=f.map(a=>({kind:"ADD",ref:y(n,a),cid:a}));for(let a of o?.rows??[])a.kind==="MODIFY"&&a.matched_cid?g.push({kind:"MODIFY",ref:y(n,a.matched_cid),old_cid:a.matched_cid,new_cid:null,summary:`${a.why} (staged)`}):a.kind==="ADD"&&r.push({kind:"ADD",ref:a.title,cid:null});let l=[],m=D(t,n,s),u=new Map;for(let{cid:a}of n.byLabel(v.USECASE)){if(!M(n,a)||p.has(a))continue;let h=n.derivesInto(a),R=h.filter(_=>String(_.props.source_id)===i);R.length===0||R.some(_=>_.props.source_cid===s)||R.some(_=>{let c=String(_.props.anchor),w=L(c);return w?.kind==="img-whole"?!1:w?.kind==="img-part"?oe(n,_,s):m!==null&&se(t,n,_,m,u)})||h.some(_=>{let c=String(_.props.source_id);if(c===i)return!1;let w=n.heads.get(c);return w!=null})||l.push({kind:"ARCHIVE",ref:y(n,a),cid:a,why:`evidence decayed: no quote from ${i} relocates into @${C(s)}, no other live source, no fresh evidence this run`,impact:W(n,n.tipOf(a))})}let d=(a,h)=>a.ref<h.ref?-1:a.ref>h.ref?1:0;return[...g.sort(d),...r.sort(d),...l.sort(d)]}function Ee(t,e,n,i,s){let f=e.rows.find(d=>d.temp_ref===n);if(!f)return{ok:!1,message:`held item ${n} missing from the plan artifact`};let o=f,p=k(t);if(o.matched_cid){let d=p.tipOf(o.matched_cid);if(p.superseded.get(d)===null)return{ok:!1,message:`use-case for "${o.title}" was retired meanwhile \u2014 nothing to update`};d!==o.matched_cid&&(o={...o,matched_cid:d,uc:{...o.uc,matches_existing:{cid:d}}})}let g=s?{edited:s}:"approve",r=ee(t,p,{source_id:e.source_id,...e.staged_source_cid!==void 0?{staged_source_cid:e.staged_source_cid}:{},rows:[o]},new Map([[o.temp_ref,g]]),i);if(r.errors)return{ok:!1,message:r.errors.map(d=>`${d.code}: ${d.detail}`).join("; ")};let l=k(t),m=o.matched_cid?l.tipOf(o.matched_cid):r.record?.nodes.find(d=>d.label==="usecase")?.cid??r.record?.review[0]?.id;return{ok:!0,ref:m?y(l,m):o.title,kind:o.kind}}async function Re(t,e,n,i={}){let s=k(t),f=s.heads.get(e)??null,o=new Set(s.staleList().filter(c=>c.state==="stale").map(c=>c.cid)),p=await n.reingest(e);if(p.status==="unchanged"&&!i.resumeHeld)return{source_id:e,changed:!1,head:{status:p.status,before:f,after:p.cid},note:`nothing to reconcile \u2014 ${e} is unchanged`,skipped_arms:q,changeset:[],rows:[]};let g=i.resumeHeld?{minted:[],matched:[],held:i.resumeHeld}:await n.reextract(e),r=k(t),l=g.minted.map(c=>{let w=y(r,c);return{kind:"ADD",origin:"content-change",ref:w,reason:`new use-case extracted from ${e}`,provenance:`extraction commit \u2014 DERIVES ${e} @ ${C(p.cid)}`,action:`kane-cli design tests --use-case ${w}`}}),m=r.staleList().filter(c=>c.state==="stale"&&!o.has(c.cid)&&M(r,c.cid)).map(c=>c.cid),u=m.map(c=>{let w=y(r,c),E=ne.has(r.nodeLabel.get(c)??"");return{kind:"MODIFY",origin:"structural-stale",ref:w,reason:"stale (structural)",provenance:z(r,c),action:E?`kane-cli maintain evolve ${w}`:`kane-cli design explain ${w}`}}),d=[],a=[];for(let c of g.held?.rows??[])if(c.kind==="ADD")d.push({kind:"ADD",origin:"content-change",ref:c.title,held_ref:c.temp_ref,reason:`${c.why} (staged \u2014 commits on approval)`,provenance:`staged extraction of ${e} @ ${C(p.cid)}`,action:"approve to commit + design"});else{let w=c.matched_cid?r.tipOf(c.matched_cid):null,E=w?r.getNode(w)?.content.criteria??[]:[],T=(c.uc.updated?.criteria??[]).map(O=>typeof O=="string"?O:O.text),Z=[...T.filter(O=>!E.includes(O)),...c.uc.updated?.criteria!==void 0?E.filter(O=>!T.includes(O)):[]],P=w?W(r,w,Z):void 0;a.push({kind:"MODIFY",origin:"content-change",ref:c.matched_cid?y(r,c.matched_cid):c.title,held_ref:c.temp_ref,reason:`${c.why} (staged \u2014 commits on approval)`,provenance:`staged extraction of ${e} @ ${C(p.cid)}`,action:"approve to commit the updated version (old\u2192new redirect)",...P?{impact:P}:{}})}let h=new Set;for(let c of[...g.minted,...g.matched])h.add(r.tipOf(c));for(let c of g.held?.rows??[])c.matched_cid&&h.add(r.tipOf(c.matched_cid));for(let c of m){let w=X(r,r.tipOf(c));w&&r.nodeLabel.get(w)===v.USECASE&&h.add(r.tipOf(w))}let R=[];for(let c of await F(r,"design")){if(c.kind!=="no-verifies")continue;let w=r.resolve(c.ref);if(!w)continue;let E=X(r,w.tip);!E||!h.has(r.tipOf(E))||R.push({kind:"ADD",origin:"content-change",ref:c.ref,reason:c.why,provenance:`gaps engine (design) \u2014 uncovered AC of touched use-case ${y(r,E)}`,action:c.ready_command})}let b=[];for(let{cid:c}of r.byLabel(v.USECASE))M(r,c)&&r.stale(c)==="orphaned"&&b.push({kind:"REMOVE",ref:y(r,c),reason:"orphaned \u2014 no live source evidences this use-case",provenance:z(r,c),action:"plan-only \u2014 REMOVE is not executed in this release"});let S=new Set,_=[...l.sort($),...d.sort($),...R.sort($),...a.sort($),...u.sort($),...b.sort($)].filter(c=>{let w=`${c.kind}\0${c.ref}`;return S.has(w)?!1:(S.add(w),!0)});return{source_id:e,changed:!0,head:{status:p.status,before:f,after:p.cid},note:te,skipped_arms:q,changeset:le(t,s,r,e,p.cid,g.minted,g.held),rows:_,...g.held?{held:g.held}:{}}}function ye(t,e){return async n=>{let{ingestFile:i}=await import("./ingest-TTUQ7UDK.js"),{convertPdf:s}=await import("./pdf-convert-OZIRUADA.js"),{convertDocx:f}=await import("./docx-convert-BIV5T7F5.js"),o=await i({contextDir:t,filePath:e,asId:n,converters:{pdf:s,docx:f}});return{status:o.status,cid:o.cid}}}function be(t,e,n,i){return async()=>{let f=(i??(await import("./dispatch-7JCKGQVC.js")).findProvider)(e);if(!f)throw new Error(`the remote re-ingest failed \u2014 no provider matches '${e}'`);let o=await f.ingest(e,void 0,{out:n.out,err:n.err,confirm:async()=>!0,isTTY:!1},t,void 0);if(o.code!==0||!o.result)throw new Error("the remote re-ingest failed \u2014 fix the reported problem and re-run");return{status:o.result.status,cid:o.result.source_cid}}}function xe(t,e={}){return async n=>{let i=[],[{runExtract:s},{resolveAgentAuthEnv:f},{runAgent:o},{preflightTurn:p}]=await Promise.all([import("./run-VTUYLPSG.js"),import("./spawner-R3XOP3GP.js"),import("./bridge-E2C5VV3H.js"),import("./turn-preflight-JGYT7LXP.js")]),g=await f(),r=new Set(k(t).byLabel(v.USECASE).map(S=>S.cid)),l=ae(t,n)??void 0,m=0,u=await s({mode:"override",source:n,...l?{changeContext:l}:{}},{contextDir:t,agent:o,preflightTurn:()=>p(g),ask:async()=>[],review:async S=>{if(!e.stage)return new Map(S.map(c=>[c.temp_ref,{resolution:c.matches_existing&&c.changed?"edited":"skipped"}]));let _=new Map;for(let c of S){if(c.matches_existing&&!c.changed){_.set(c.temp_ref,{resolution:"skipped"});continue}i.push({kind:c.matches_existing?"MODIFY":"ADD",temp_ref:c.temp_ref,title:c.title,why:c.matches_existing?`updated: ${Object.keys(c.updated??{}).join(", ")||"content"}`:`newly extracted from ${n}`,...c.matches_existing?{matched_cid:c.matches_existing.cid,updated:c.updated}:{},uc:c}),_.set(c.temp_ref,{resolution:"rejected"})}return _},confirmStale:async()=>!1,out:S=>e.hostOut?.(S),progress:S=>e.hostProgress?.(S),emit:S=>{S.type==="commit"&&typeof S.assumed=="number"&&(m+=S.assumed),e.hostEmit?.(S)},isTTY:!1,auth:g});if(u!==0)throw new Error(`reconcile: re-extract of ${n} failed (exit ${u})`);let d=k(t),a=d.heads.get(n),h=[],R=[];if(typeof a=="string"){let S=new Set;for(let _ of d.edgesFrom(a))_.type!==x.DERIVES||d.nodeLabel.get(_.dst)!==v.USECASE||S.has(_.dst)||(S.add(_.dst),!(e.stage&&d.trust.get(_.dst)==="archived")&&(r.has(_.dst)?R:h).push(_.dst))}let b=k(t).heads.get(n);return{minted:h,matched:R,defaultsTaken:m,...e.stage?{held:{source_id:n,...b!=null?{staged_source_cid:b}:{},rows:i}}:{}}}}export{ee as a,W as b,q as c,te as d,M as e,X as f,ne as g,re as h,ce as i,ae as j,Ee as k,Re as l,ye as m,be as n,xe as o};
@@ -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 E,b as N}from"./chunk-IAHKTEET.js";import{a as $}from"./chunk-AKX4VRRR.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}
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
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
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};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as h}from"./chunk-CRPBARFG.js";import{a as f}from"./chunk-K6BWPGBO.js";import{a as m}from"./chunk-BE4FBVKY.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:g,log:t}=c,e=null,u=null;if(l&&g)e={username:l,access_key:g},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,p=new h(v.controllerBaseUrl,b,y,t),s=await p.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:p,resolvedCreds:s}}export{o as a,k as b};
2
+ import{a as h}from"./chunk-FBYB3SRE.js";import{a as f}from"./chunk-3G3LY6BM.js";import{a as m}from"./chunk-7KAPHA56.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:g,log:t}=c,e=null,u=null;if(l&&g)e={username:l,access_key:g},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,p=new h(v.controllerBaseUrl,b,y,t),s=await p.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:p,resolvedCreds:s}}export{o as a,k as b};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as R}from"./chunk-TDPWFYTJ.js";import{a as x}from"./chunk-7KRCBN6X.js";import{d as S}from"./chunk-4VZRBBLF.js";import{a as y}from"./chunk-MMBBQ4OZ.js";import{a as p}from"./chunk-BE4FBVKY.js";import{d as g,i as E}from"./chunk-DEUDRSU7.js";import{spawn as M,execSync as h}from"child_process";import{appendFileSync as b,existsSync as m,mkdirSync as C}from"fs";import{homedir as L}from"os";import{join as V,resolve as s,dirname as v,delimiter as T}from"path";import{fileURLToPath as U}from"url";import{createInterface as I}from"readline";async function*A(e){let n=I({input:e,crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let i=JSON.parse(o);i&&typeof i.type=="string"&&(yield i)}catch{}}}function O(e){return e==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true",V16_BIFURCATION_PHASES:"1"},unset:["V16_NETWORK_WS","V16_NETWORK_SSE"]}:{set:{V16_BIFURCATION_PHASES:"1"},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS","V16_NETWORK_WS","V16_NETWORK_SSE"]}}function w(e){return e?{set:{},unset:["V16_AGENT_SKIP_CP_FINAL"]}:{set:{V16_AGENT_SKIP_CP_FINAL:"true"},unset:[]}}function N(e){return e==="dom"?{set:{V16_AGENT_ENABLE_TEXTUAL_VISUAL:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_TEXTUAL_VISUAL"]}}var c=v(U(import.meta.url));function k(){for(let e of["python3","python"])try{return h(`${e} --version`,{stdio:"ignore"}),e}catch{}return null}function D(){let n=process.platform==="win32"?"v16-runner.exe":"v16-runner",r={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"linux-arm64":["@testmuai/kane-cli-linux-arm64","@lambdatestincprivate/kane-cli-linux-arm64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},o=`${process.platform}-${process.arch}`,i=r[o];if(i)for(let t of i){let a=[s(c,"..","node_modules",t,"bin",n),s(c,"..","..","node_modules",t,"bin",n),s(c,"..","..","..","node_modules",t,"bin",n),s(c,"..","..","..","..","node_modules",t,"bin",n)];for(let u of a)if(m(u))return{cmd:u,args:[]}}let d=[s(c,"bin",n),s(c,"..","bin",n),s(c,"..","..","..","..","v16-runner","dist",n),s(c,"..","..","..","v16-runner","dist",n),s(c,"..","..","v16-runner","dist",n),s(process.cwd(),"v16-runner","dist",n),s(process.cwd(),"..","v16-runner","dist",n)];for(let t of d)if(m(t))return{cmd:t,args:[]};let l=[s(c,"..","..","v16-runner"),s(c,"..","..","..","..","v16-runner"),s(c,"..","..","..","v16-runner"),s(process.cwd(),"v16-runner"),s(process.cwd(),"..","v16-runner")];for(let t of l)if(m(s(t,"main.py"))){for(let u of[s(t,".venv","bin","python"),s(t,"..",".venv","bin","python"),s(t,"..","browser-agent",".venv","bin","python")])if(m(u))return{cmd:u,args:["main.py"],cwd:t};let a=k();if(a)return{cmd:a,args:["main.py"],cwd:t}}return null}function P(e){return e?V(L(),".testmuai","kaneai","sessions",e,"runner-stderr.log"):null}function K(e){let n=M(e.runner.cmd,e.runner.args,{stdio:["pipe","pipe","pipe"],env:e.env,cwd:e.runner.cwd});n.stdin.on("error",()=>{});let r=P(e.sessionId);if(r)try{C(v(r),{recursive:!0})}catch{}let o=1e5,i="";n.stderr.on("data",u=>{if(i+=u.toString(),i.length>o&&(i=i.slice(-o)),r)try{b(r,u)}catch{}}),n.on("error",u=>{e.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:u.message})});let d=null,l=null,t=new Promise(u=>{n.on("close",(f,_)=>{d=f,l=_?String(_):null,e.log?.("info","RUNNER_EXIT","Runner exited",{code:f,signal:l??"none"}),u({code:f,signal:l})})}),a=A(n.stdout);return{child:n,events:a,getStderr:()=>i,getExitCode:()=>d,getExitSignal:()=>l,exited:t}}async function B(e,n){if(!n?.platform||!n.target_kind)return;let r=await S(n.platform)?.toolEnv(n.target_kind)??{dirs:[]};if(r.dirs.length>0&&(e.PATH=[...r.dirs,e.PATH??""].filter(Boolean).join(T)),r.appiumHome&&(e.APPIUM_HOME=r.appiumHome),r.wdaRoot&&(e.TESTMU_IOS_WDA_DERIVED_DATA=r.wdaRoot),n.platform==="android"){let o=y();o&&(e.PATH=[o.platformToolsDir,e.PATH??""].filter(Boolean).join(T),e.ANDROID_HOME=o.root,e.ANDROID_SDK_ROOT=o.root)}}function H(e){let n={...process.env};e.environment&&(n.TESTMUAI_ENV=e.environment),n.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(n.PYTHONIOENCODING="utf-8",n.PYTHONUTF8="1");let r=p(e.environment);n.V16_SERVER_API_HOST=r.v16ServerHost,n.ATMS_URL=r.tmsBaseUrl.replace(/\/api\/?$/,""),e.username&&e.accessKey&&(n.LT_USERNAME=e.username,n.LT_ACCESS_KEY=e.accessKey),e.sessionId&&(n.TESTMUAI_SESSION_ID=e.sessionId);let o=O(e.mode??"testing");Object.assign(n,o.set);for(let a of o.unset)delete n[a];let i=new x().load(),d=N(e.assertionMode??(i.assertion_mode==="visual"?"visual":"dom"));Object.assign(n,d.set);for(let a of d.unset)delete n[a];let l=e.finalValidation??i.final_validation,t=w(l);Object.assign(n,t.set);for(let a of t.unset)delete n[a];return n}function G(e,n){let r=p(n?.environment),o=R();o!==void 0&&e.ap_mode===void 0&&(e.ap_mode=o),e.telemetry_proxy_url===void 0&&process.env.KANE_TELEMETRY!=="0"&&(e.telemetry_proxy_url=E),e.media_upload===void 0&&e.org_id&&e.username&&e.access_key&&(e.media_upload={url:r.shareApiBaseUrl.replace(/\/$/,"")+"/mfs/v1.0/media/upload",artefacts_host:r.mediaArtefactsHost,org_id:e.org_id,media_dir:g})}async function oe(e,n){let r=D();if(!r)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");process.env.KANE_SPAWN_DEBUG&&process.stderr.write(`[spawn-debug] ${JSON.stringify(r)}
2
+ import{a as R}from"./chunk-TDPWFYTJ.js";import{a as x}from"./chunk-APZCLVZD.js";import{d as S}from"./chunk-ASYWKYTQ.js";import{a as y}from"./chunk-MMBBQ4OZ.js";import{a as p}from"./chunk-7KAPHA56.js";import{d as g,i as E}from"./chunk-NJJQL54J.js";import{spawn as M,execSync as h}from"child_process";import{appendFileSync as b,existsSync as m,mkdirSync as C}from"fs";import{homedir as L}from"os";import{join as V,resolve as s,dirname as v,delimiter as T}from"path";import{fileURLToPath as U}from"url";import{createInterface as I}from"readline";async function*A(e){let n=I({input:e,crlfDelay:1/0});for await(let r of n){let o=r.trim();if(o)try{let i=JSON.parse(o);i&&typeof i.type=="string"&&(yield i)}catch{}}}function O(e){return e==="action"?{set:{V16_AGENT_ENABLE_ALL_BLOCKERS:"true",V16_BIFURCATION_PHASES:"1"},unset:["V16_NETWORK_WS","V16_NETWORK_SSE"]}:{set:{V16_BIFURCATION_PHASES:"1"},unset:["V16_AGENT_ENABLE_ALL_BLOCKERS","V16_NETWORK_WS","V16_NETWORK_SSE"]}}function w(e){return e?{set:{},unset:["V16_AGENT_SKIP_CP_FINAL"]}:{set:{V16_AGENT_SKIP_CP_FINAL:"true"},unset:[]}}function N(e){return e==="dom"?{set:{V16_AGENT_ENABLE_TEXTUAL_VISUAL:"true"},unset:[]}:{set:{},unset:["V16_AGENT_ENABLE_TEXTUAL_VISUAL"]}}var c=v(U(import.meta.url));function k(){for(let e of["python3","python"])try{return h(`${e} --version`,{stdio:"ignore"}),e}catch{}return null}function D(){let n=process.platform==="win32"?"v16-runner.exe":"v16-runner",r={"darwin-arm64":["@testmuai/kane-cli-darwin-arm64","@lambdatestincprivate/kane-cli-darwin-arm64"],"darwin-x64":["@testmuai/kane-cli-darwin-x64","@lambdatestincprivate/kane-cli-darwin-x64"],"linux-x64":["@testmuai/kane-cli-linux-x64","@lambdatestincprivate/kane-cli-linux-x64"],"linux-arm64":["@testmuai/kane-cli-linux-arm64","@lambdatestincprivate/kane-cli-linux-arm64"],"win32-x64":["@testmuai/kane-cli-win-x64","@lambdatestincprivate/kane-cli-win-x64"]},o=`${process.platform}-${process.arch}`,i=r[o];if(i)for(let t of i){let a=[s(c,"..","node_modules",t,"bin",n),s(c,"..","..","node_modules",t,"bin",n),s(c,"..","..","..","node_modules",t,"bin",n),s(c,"..","..","..","..","node_modules",t,"bin",n)];for(let u of a)if(m(u))return{cmd:u,args:[]}}let d=[s(c,"bin",n),s(c,"..","bin",n),s(c,"..","..","..","..","v16-runner","dist",n),s(c,"..","..","..","v16-runner","dist",n),s(c,"..","..","v16-runner","dist",n),s(process.cwd(),"v16-runner","dist",n),s(process.cwd(),"..","v16-runner","dist",n)];for(let t of d)if(m(t))return{cmd:t,args:[]};let l=[s(c,"..","..","v16-runner"),s(c,"..","..","..","..","v16-runner"),s(c,"..","..","..","v16-runner"),s(process.cwd(),"v16-runner"),s(process.cwd(),"..","v16-runner")];for(let t of l)if(m(s(t,"main.py"))){for(let u of[s(t,".venv","bin","python"),s(t,"..",".venv","bin","python"),s(t,"..","browser-agent",".venv","bin","python")])if(m(u))return{cmd:u,args:["main.py"],cwd:t};let a=k();if(a)return{cmd:a,args:["main.py"],cwd:t}}return null}function P(e){return e?V(L(),".testmuai","kaneai","sessions",e,"runner-stderr.log"):null}function K(e){let n=M(e.runner.cmd,e.runner.args,{stdio:["pipe","pipe","pipe"],env:e.env,cwd:e.runner.cwd});n.stdin.on("error",()=>{});let r=P(e.sessionId);if(r)try{C(v(r),{recursive:!0})}catch{}let o=1e5,i="";n.stderr.on("data",u=>{if(i+=u.toString(),i.length>o&&(i=i.slice(-o)),r)try{b(r,u)}catch{}}),n.on("error",u=>{e.log?.("error","RUNNER_SPAWN_ERROR","Runner spawn error",{error:u.message})});let d=null,l=null,t=new Promise(u=>{n.on("close",(f,_)=>{d=f,l=_?String(_):null,e.log?.("info","RUNNER_EXIT","Runner exited",{code:f,signal:l??"none"}),u({code:f,signal:l})})}),a=A(n.stdout);return{child:n,events:a,getStderr:()=>i,getExitCode:()=>d,getExitSignal:()=>l,exited:t}}async function B(e,n){if(!n?.platform||!n.target_kind)return;let r=await S(n.platform)?.toolEnv(n.target_kind)??{dirs:[]};if(r.dirs.length>0&&(e.PATH=[...r.dirs,e.PATH??""].filter(Boolean).join(T)),r.appiumHome&&(e.APPIUM_HOME=r.appiumHome),r.wdaRoot&&(e.TESTMU_IOS_WDA_DERIVED_DATA=r.wdaRoot),n.platform==="android"){let o=y();o&&(e.PATH=[o.platformToolsDir,e.PATH??""].filter(Boolean).join(T),e.ANDROID_HOME=o.root,e.ANDROID_SDK_ROOT=o.root)}}function H(e){let n={...process.env};e.environment&&(n.TESTMUAI_ENV=e.environment),n.TESTMUAI_SOURCE="kane-cli",process.platform==="win32"&&(n.PYTHONIOENCODING="utf-8",n.PYTHONUTF8="1");let r=p(e.environment);n.V16_SERVER_API_HOST=r.v16ServerHost,n.ATMS_URL=r.tmsBaseUrl.replace(/\/api\/?$/,""),e.username&&e.accessKey&&(n.LT_USERNAME=e.username,n.LT_ACCESS_KEY=e.accessKey),e.sessionId&&(n.TESTMUAI_SESSION_ID=e.sessionId);let o=O(e.mode??"testing");Object.assign(n,o.set);for(let a of o.unset)delete n[a];let i=new x().load(),d=N(e.assertionMode??(i.assertion_mode==="visual"?"visual":"dom"));Object.assign(n,d.set);for(let a of d.unset)delete n[a];let l=e.finalValidation??i.final_validation,t=w(l);Object.assign(n,t.set);for(let a of t.unset)delete n[a];return n}function G(e,n){let r=p(n?.environment),o=R();o!==void 0&&e.ap_mode===void 0&&(e.ap_mode=o),e.telemetry_proxy_url===void 0&&process.env.KANE_TELEMETRY!=="0"&&(e.telemetry_proxy_url=E),e.media_upload===void 0&&e.org_id&&e.username&&e.access_key&&(e.media_upload={url:r.shareApiBaseUrl.replace(/\/$/,"")+"/mfs/v1.0/media/upload",artefacts_host:r.mediaArtefactsHost,org_id:e.org_id,media_dir:g})}async function oe(e,n){let r=D();if(!r)throw new Error("v16-runner not found. Build the binary with `cd v16-runner && python build.py` or ensure Python is available.");process.env.KANE_SPAWN_DEBUG&&process.stderr.write(`[spawn-debug] ${JSON.stringify(r)}
3
3
  `);let o=H({environment:n?.environment,mode:n?.mode,assertionMode:n?.assertionMode,finalValidation:n?.finalValidation,username:e.username,accessKey:e.access_key,sessionId:e.session_id});e.device?.platform&&await B(o,e.device),G(e,{environment:n?.environment});let i=K({env:o,runner:r,log:n?.log,sessionId:e.session_id}),d=i.child;d.stdin.write(JSON.stringify(e)+`
4
4
  `);let l=P(e.session_id);if(l)try{C(v(l),{recursive:!0}),b(l,`--- runner spawn ${new Date().toISOString()} run_index=${e.run_index} ---
5
5
  `)}catch{}return{child:d,events:i.events,sendUserResponse(t){let a=JSON.stringify({type:"user_response",answer:t});try{d.stdin.write(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-6DOS5CJ5.js";import{x as s}from"./chunk-DEUDRSU7.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-5FYO3PFG.js";import{x as s}from"./chunk-NJJQL54J.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};