@testmuai/kane-cli 0.8.21 → 0.8.22

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 (189) hide show
  1. package/dist/{ChatSurface-U3Y3WUMS.js → ChatSurface-PA73V3NT.js} +1 -1
  2. package/dist/{ChromeProfilePicker-E6I6K2HO.js → ChromeProfilePicker-XX223SYB.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-MPQVZM6J.js → CliFeedbackPrompt-J6DW6TZL.js} +1 -1
  4. package/dist/{CliUploadProgress-CADDDCS6.js → CliUploadProgress-TWEL7NWG.js} +1 -1
  5. package/dist/{ConfigView-IFXESQBB.js → ConfigView-ROFNVFDQ.js} +1 -1
  6. package/dist/{EvidenceViewOffer-GW7XLM45.js → EvidenceViewOffer-XUP44BGJ.js} +1 -1
  7. package/dist/FolderPicker-XLAK7324.js +2 -0
  8. package/dist/{InfoBox-CQWRYU6P.js → InfoBox-ELZ5Q65V.js} +1 -1
  9. package/dist/{LinksBox-ZFXUQZ2D.js → LinksBox-2V26KLTJ.js} +1 -1
  10. package/dist/{ProfilesView-OBN423WX.js → ProfilesView-P4Z42LSX.js} +1 -1
  11. package/dist/{ProjectPicker-FG3VJ22U.js → ProjectPicker-2QNFNN7T.js} +1 -1
  12. package/dist/{SaveSessionPrompt-SNFSJUGW.js → SaveSessionPrompt-XMWL3P6G.js} +1 -1
  13. package/dist/SingleShotApp-3YZSE3AA.js +2 -0
  14. package/dist/{SummaryBox-V7XVROAD.js → SummaryBox-RWO4BYYD.js} +1 -1
  15. package/dist/TestMdRunView-QHPMG46M.js +2 -0
  16. package/dist/{TestrunEvidenceTable-R3UQQI67.js → TestrunEvidenceTable-MUOGF6CZ.js} +1 -1
  17. package/dist/{WhoamiView-IGIALZNC.js → WhoamiView-4EYWZR4N.js} +1 -1
  18. package/dist/{app-download-VXEW7EI7.js → app-download-KUJVMZ7L.js} +1 -1
  19. package/dist/{auth-CSYBNMIH.js → auth-5HAY24TN.js} +1 -1
  20. package/dist/{binary-QLRLXZ6K.js → binary-6UEOI7PT.js} +1 -1
  21. package/dist/{bind-URA64IPV.js → bind-3C2IIPML.js} +2 -2
  22. package/dist/{bootstrap-PYBM5YT2.js → bootstrap-DBAQWVNA.js} +1 -1
  23. package/dist/bridge-NHXCRSIU.js +2 -0
  24. package/dist/{changelog-FMT3SSEI.js → changelog-QAGRYBEZ.js} +1 -1
  25. package/dist/{chunk-P7URFYFG.js → chunk-26HZJJN6.js} +2 -2
  26. package/dist/{chunk-47MLKCMG.js → chunk-2G5CJQOR.js} +1 -1
  27. package/dist/{chunk-IDQYOWKL.js → chunk-2HFNP2LM.js} +1 -1
  28. package/dist/{chunk-KMMOJDN4.js → chunk-2OIIXLXW.js} +1 -1
  29. package/dist/{chunk-NPFG4T7Q.js → chunk-3BUYTNAV.js} +2 -2
  30. package/dist/{chunk-QXIY5WRL.js → chunk-3H3KTCL7.js} +2 -2
  31. package/dist/{chunk-JH5RLIAH.js → chunk-3M6OM3T4.js} +1 -1
  32. package/dist/{chunk-PZJJIH4T.js → chunk-3MWLFHPO.js} +1 -1
  33. package/dist/{chunk-FHH7AFSC.js → chunk-3NMXXTHE.js} +1 -1
  34. package/dist/{chunk-5LLXVZXW.js → chunk-44NNFVCJ.js} +1 -1
  35. package/dist/{chunk-YY6RXHIL.js → chunk-46U7TRPE.js} +64 -64
  36. package/dist/{chunk-QG5OZHRH.js → chunk-4VW3B7SE.js} +1 -1
  37. package/dist/{chunk-LEWESZ24.js → chunk-4ZBI54KE.js} +2 -2
  38. package/dist/{chunk-IXJ33HYF.js → chunk-5BHB5D2C.js} +1 -1
  39. package/dist/{chunk-H2VMZL7J.js → chunk-5D6YMG63.js} +2 -2
  40. package/dist/{chunk-JVQI3EVW.js → chunk-5E4JLXR5.js} +1 -1
  41. package/dist/{chunk-FPGSEOG6.js → chunk-5FQYB5SM.js} +1 -1
  42. package/dist/{chunk-K7WJFQJU.js → chunk-5ILTSBWT.js} +1 -1
  43. package/dist/{chunk-JW7M3ENB.js → chunk-5TQIKRKP.js} +1 -1
  44. package/dist/{chunk-ETFRGYOT.js → chunk-5XAX4C5N.js} +1 -1
  45. package/dist/{chunk-6WOGVXQV.js → chunk-6C35NKQ7.js} +1 -1
  46. package/dist/{chunk-HX2HTIOQ.js → chunk-6MCQ2UKE.js} +1 -1
  47. package/dist/{chunk-LGJ7JMCR.js → chunk-ADBOWRMW.js} +1 -1
  48. package/dist/chunk-BNC4DJCC.js +7 -0
  49. package/dist/{chunk-45GRUU6A.js → chunk-BPDFI2DC.js} +2 -2
  50. package/dist/{chunk-VL3NGTTK.js → chunk-BPYRVV7O.js} +1 -1
  51. package/dist/chunk-CBUSNWHA.js +2 -0
  52. package/dist/{chunk-P6PNLVNS.js → chunk-CE23VDW5.js} +1 -1
  53. package/dist/{chunk-UXCXU6P4.js → chunk-DF4EBXGN.js} +1 -1
  54. package/dist/{chunk-4HPJ4S6H.js → chunk-DZCJE77P.js} +1 -1
  55. package/dist/{chunk-SYKBHHAJ.js → chunk-E2KV4BQB.js} +1 -1
  56. package/dist/{chunk-FLGQXY65.js → chunk-EVBCKI7D.js} +1 -1
  57. package/dist/chunk-FBRTUEAL.js +26 -0
  58. package/dist/{chunk-HJBTALBX.js → chunk-FDXDFZ7J.js} +1 -1
  59. package/dist/{chunk-7EVSM4V7.js → chunk-FR3LVUAB.js} +1 -1
  60. package/dist/{chunk-FGRDGMJP.js → chunk-GF32QBCM.js} +1 -1
  61. package/dist/{chunk-EZKC2LFH.js → chunk-GVE5GEW2.js} +1 -1
  62. package/dist/{chunk-YZZJUMKN.js → chunk-GYLMH2EX.js} +1 -1
  63. package/dist/{chunk-Z4DH3J7O.js → chunk-HKIBJDKE.js} +1 -1
  64. package/dist/{chunk-RSN4EHDN.js → chunk-I4SO2FQV.js} +1 -1
  65. package/dist/{chunk-X3ULX7LO.js → chunk-JHBNXTG6.js} +1 -1
  66. package/dist/{chunk-6ZHEIBI5.js → chunk-JHYWNWS5.js} +2 -2
  67. package/dist/{chunk-FY7WTTDQ.js → chunk-JPOFRYTX.js} +1 -1
  68. package/dist/{chunk-ZIYSW2F4.js → chunk-JQ3JB5CO.js} +1 -1
  69. package/dist/{chunk-LO6WSBLS.js → chunk-L35DJDX7.js} +1 -1
  70. package/dist/{chunk-5UY2JMFC.js → chunk-LKPOOZYN.js} +2 -2
  71. package/dist/{chunk-X5FZCQVO.js → chunk-LSRNUBIV.js} +1 -1
  72. package/dist/{chunk-DGQKGGCB.js → chunk-MHMEEA4S.js} +1 -1
  73. package/dist/{chunk-YJUWYQIO.js → chunk-MXI5P373.js} +1 -1
  74. package/dist/chunk-NAWGHDA3.js +15 -0
  75. package/dist/{chunk-2R55Y3X4.js → chunk-NMAPNJRY.js} +1 -1
  76. package/dist/chunk-NUYGWRB2.js +11 -0
  77. package/dist/{chunk-VLBUZOGF.js → chunk-O4LJWUSJ.js} +1 -1
  78. package/dist/{chunk-XWUK7FDE.js → chunk-OBB57E2L.js} +1 -1
  79. package/dist/{chunk-WTRUUT4E.js → chunk-OT3VKXJX.js} +1 -1
  80. package/dist/{chunk-ASJPV3O7.js → chunk-P37ALET7.js} +1 -1
  81. package/dist/{chunk-JD3OZ5H7.js → chunk-PLIQ72LH.js} +1 -1
  82. package/dist/{chunk-X3YTLBZR.js → chunk-PUFZTE6L.js} +1 -1
  83. package/dist/{chunk-SRJCAJYM.js → chunk-QV445GUU.js} +1 -1
  84. package/dist/{chunk-VNWRMLJ2.js → chunk-R43ELADV.js} +2 -2
  85. package/dist/{chunk-UUV5VP5T.js → chunk-R7ZDLGMU.js} +1 -1
  86. package/dist/{chunk-WSHADDNC.js → chunk-REPKBN7I.js} +1 -1
  87. package/dist/{chunk-FQVK46L7.js → chunk-RFDL7MHI.js} +1 -1
  88. package/dist/{chunk-P7PDRCQR.js → chunk-RUSRN7YE.js} +1 -1
  89. package/dist/{chunk-J4Z34AZN.js → chunk-SB5XM4YV.js} +1 -1
  90. package/dist/{chunk-TEYEMBS7.js → chunk-SIXPXYCH.js} +1 -1
  91. package/dist/{chunk-MI6UFDRC.js → chunk-SJZJ7ASF.js} +1 -1
  92. package/dist/{chunk-LXRZ5SM4.js → chunk-SREUA7YQ.js} +1 -1
  93. package/dist/{chunk-MFOEJ2RX.js → chunk-SVJBOVI4.js} +1 -1
  94. package/dist/{chunk-PQ63VSMO.js → chunk-SW54RAAT.js} +1 -1
  95. package/dist/{chunk-EXSFOB4X.js → chunk-T6MGCP57.js} +4 -4
  96. package/dist/{chunk-NLEFCLLY.js → chunk-UXR57BCE.js} +1 -1
  97. package/dist/{chunk-RN2PEWDD.js → chunk-VCY7UNEL.js} +1 -1
  98. package/dist/{chunk-C3366X5X.js → chunk-VW3PFRCO.js} +1 -1
  99. package/dist/{chunk-ZUWU7LJ6.js → chunk-WBH5GYFM.js} +1 -1
  100. package/dist/{chunk-KXGZLYUF.js → chunk-WGIZQGR5.js} +1 -1
  101. package/dist/{chunk-MZPLTQVK.js → chunk-WHNF5SWS.js} +2 -2
  102. package/dist/{chunk-GGOOD6KP.js → chunk-WPBETG6U.js} +3 -3
  103. package/dist/{chunk-N6J2YUDC.js → chunk-WRGPMDDE.js} +1 -1
  104. package/dist/{chunk-RH4QTLEG.js → chunk-XFQLR6MF.js} +1 -1
  105. package/dist/chunk-XKYL4K4A.js +2 -0
  106. package/dist/{chunk-4XYPIPYO.js → chunk-XQNJSM5C.js} +1 -1
  107. package/dist/{chunk-ICPCU7AL.js → chunk-YFBJWIBU.js} +1 -1
  108. package/dist/{chunk-CP2TVGKB.js → chunk-Z2XKFYMH.js} +1 -1
  109. package/dist/{chunk-N5ZEI42N.js → chunk-ZUJGYHZ2.js} +1 -1
  110. package/dist/{config-7ZZAHUGW.js → config-HVSKN6L4.js} +1 -1
  111. package/dist/{cover-cmd-ASKH4ZPV.js → cover-cmd-ZZJA5C6H.js} +1 -1
  112. package/dist/{credentials-DAYWXKP3.js → credentials-FH6VZPJS.js} +1 -1
  113. package/dist/{deps-bundle-KPOXT7E7.js → deps-bundle-QUROUKJI.js} +1 -1
  114. package/dist/{deps-resolve-LKA4VWF2.js → deps-resolve-N2KKJ37Q.js} +1 -1
  115. package/dist/{device-env-CAW6YN75.js → device-env-ID7EDDOD.js} +1 -1
  116. package/dist/{dispatch-DCQVGUGM.js → dispatch-BYA5Q2SD.js} +1 -1
  117. package/dist/{doctor-4FHKGRTC.js → doctor-MGHY2M36.js} +1 -1
  118. package/dist/{evidence-QCDPTFG3.js → evidence-XYKLWPPY.js} +1 -1
  119. package/dist/{evolve-cmd-YBQCNBL6.js → evolve-cmd-BURJDLVF.js} +1 -1
  120. package/dist/{explain-cmd-XFMMVUKV.js → explain-cmd-53EO2IMN.js} +1 -1
  121. package/dist/{extract-bind-AHNYCTPX.js → extract-bind-T7GKUEJ6.js} +2 -2
  122. package/dist/{extract-cmd-7ZBAPANP.js → extract-cmd-WXG34RMY.js} +1 -1
  123. package/dist/{gaps-cmd-PITBOXQK.js → gaps-cmd-T55FFFVB.js} +1 -1
  124. package/dist/{generate-headless-CDOH5LDS.js → generate-headless-BSBY47K2.js} +2 -2
  125. package/dist/index.js +109 -109
  126. package/dist/{ingest-cmd-T2LTILCD.js → ingest-cmd-BYOZCTVG.js} +1 -1
  127. package/dist/install-OABVIXAE.js +2 -0
  128. package/dist/{interactive-bind-SOLR3JCP.js → interactive-bind-JAB6XUPX.js} +3 -3
  129. package/dist/{lifecycle-cmd-MXYNJ55S.js → lifecycle-cmd-QVGYYJSG.js} +1 -1
  130. package/dist/{list-cmd-SDXYRMO3.js → list-cmd-RQYRC345.js} +1 -1
  131. package/dist/{list-commands-S4FMWRUU.js → list-commands-VTWPMFG3.js} +1 -1
  132. package/dist/login-flow-HUORIV6P.js +2 -0
  133. package/dist/{maintenance-cmd-EGWCWSBX.js → maintenance-cmd-NC2VI5G7.js} +1 -1
  134. package/dist/{mobile-prompts-5XLY7R4U.js → mobile-prompts-VCA73IYP.js} +1 -1
  135. package/dist/objective-variable-gate-WZFN5I7Y.js +2 -0
  136. package/dist/{open-provider-STFAULQU.js → open-provider-YXHFPVDE.js} +1 -1
  137. package/dist/persist-recorded-session-SZDBBSNH.js +3 -0
  138. package/dist/{pipeline-SBSLJEQT.js → pipeline-FAU3PBDH.js} +1 -1
  139. package/dist/prepare-target-XYOTVK2I.js +2 -0
  140. package/dist/{reconcile-cmd-YPSGEA5W.js → reconcile-cmd-2BFK7RFL.js} +1 -1
  141. package/dist/{reconcile-deps-N32E7NQU.js → reconcile-deps-CYWH6GM4.js} +2 -2
  142. package/dist/{reconcile-engine-CEWZQPFK.js → reconcile-engine-ZWIJFYBP.js} +1 -1
  143. package/dist/{recording-banner-NW5J3XKA.js → recording-banner-FRH2EJBM.js} +1 -1
  144. package/dist/registry-QR3BDI5F.js +2 -0
  145. package/dist/{require-project-folder-7DEBG4MC.js → require-project-folder-A6YTVLAK.js} +1 -1
  146. package/dist/{resolve-run-intent-A77ZCVXW.js → resolve-run-intent-PHAXPW6C.js} +1 -1
  147. package/dist/{resolver-NFGCIGX5.js → resolver-U55SNASN.js} +1 -1
  148. package/dist/{review-cmd-ZXTE7J6C.js → review-cmd-ZKCXBMFP.js} +1 -1
  149. package/dist/{run-2AVVCSQ2.js → run-76I4OYXD.js} +1 -1
  150. package/dist/run-XJK3YOW2.js +2 -0
  151. package/dist/{run-test-md-QBQ5PYV4.js → run-test-md-A3QRWLCW.js} +2 -2
  152. package/dist/{skill-installer-IK7AVGLZ.js → skill-installer-LSDCMJ6P.js} +1 -1
  153. package/dist/{spawner-YSJNIMNY.js → spawner-HZXP66DS.js} +1 -1
  154. package/dist/{store-guard-ZNNZGLQE.js → store-guard-27XJZ7WF.js} +1 -1
  155. package/dist/{sync-cmd-EJL5UMHU.js → sync-cmd-JZ3MXGEU.js} +1 -1
  156. package/dist/{sync-setup-6MUOKQ2U.js → sync-setup-HGG7ALGA.js} +1 -1
  157. package/dist/tcg-generate-S77VVSVU.js +2 -0
  158. package/dist/testmd-actions-VQJ22WZZ.js +2 -0
  159. package/dist/testmd-sync-RKSGTCZA.js +2 -0
  160. package/dist/token-refresh-AOCGYGEC.js +2 -0
  161. package/dist/{validate-basic-X46S6YL2.js → validate-basic-5NYH5WYI.js} +1 -1
  162. package/dist/variable-receipt-C3US6X4M.js +2 -0
  163. package/dist/{verdicts-K7NEM446.js → verdicts-VPTU4YAS.js} +1 -1
  164. package/dist/{version-check-LFAPVUOE.js → version-check-YY57B2A4.js} +1 -1
  165. package/dist/{view-cmd-BMIT3223.js → view-cmd-KWIBYZ5S.js} +1 -1
  166. package/dist/{walk-session-WFINXPLQ.js → walk-session-YSKEJM2F.js} +1 -1
  167. package/dist/{with-telemetry-CETNH2F6.js → with-telemetry-2NY4CPL5.js} +1 -1
  168. package/package.json +11 -11
  169. package/dist/FolderPicker-XILMCQE5.js +0 -2
  170. package/dist/SingleShotApp-BTBHN35J.js +0 -2
  171. package/dist/TestMdRunView-NQMTHTK6.js +0 -2
  172. package/dist/bridge-Z5PPK6CD.js +0 -2
  173. package/dist/chunk-DRVZE2XJ.js +0 -2
  174. package/dist/chunk-F3BN7Z3Z.js +0 -7
  175. package/dist/chunk-FRSS6LMZ.js +0 -26
  176. package/dist/chunk-OTTGA3LT.js +0 -11
  177. package/dist/chunk-TI5JQZ7J.js +0 -15
  178. package/dist/install-XDQH2EM3.js +0 -2
  179. package/dist/login-flow-XJARBECG.js +0 -2
  180. package/dist/objective-variable-gate-L25PM6IM.js +0 -2
  181. package/dist/persist-recorded-session-WJCW7M5R.js +0 -3
  182. package/dist/prepare-target-KJ2P2BC7.js +0 -2
  183. package/dist/registry-RV2NWZD6.js +0 -2
  184. package/dist/run-DGVXRJEG.js +0 -2
  185. package/dist/tcg-generate-UO4I35AT.js +0 -2
  186. package/dist/testmd-actions-R34VVDEL.js +0 -2
  187. package/dist/testmd-sync-L4ZFKGFZ.js +0 -2
  188. package/dist/token-refresh-LS3PRAT5.js +0 -2
  189. package/dist/variable-receipt-KAS4JVFJ.js +0 -2
@@ -1,17 +1,17 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as we}from"./chunk-YKTYVJBN.js";import{b as he,c as ye,d as be,e as Ee,f as _e,p as T}from"./chunk-7N6OCHPC.js";import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-VVOKM2VO.js";import{z as j}from"./chunk-IICT4VOU.js";import{g as N}from"./chunk-RDHWNSDP.js";import{x as ge}from"./chunk-MI6UFDRC.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 we}from"./chunk-YKTYVJBN.js";import{b as he,c as ye,d as be,e as Ee,f as _e,p as T}from"./chunk-7N6OCHPC.js";import{a as J,b as F}from"./chunk-2UIHS2FH.js";import{a as M}from"./chunk-N2P4MI32.js";import{b as B,d as W}from"./chunk-VVOKM2VO.js";import{z as j}from"./chunk-IICT4VOU.js";import{g as N}from"./chunk-RDHWNSDP.js";import{x as ge}from"./chunk-SJZJ7ASF.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(b=>setTimeout(b,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 g=String(w.id);r.has(g)||(r.add(g),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),b=Number(d.id);return Number.isFinite(p)&&Number.isFinite(b)?p-b: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),b=Number(d.id);return Number.isFinite(p)&&Number.isFinite(b)&&p!==b?p-b: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],b=`i${d+1}`,w=`attachment:${p.filename}`,g=v=>`[img#${b}] ${p.filename} (${p.media_type}, ${p.size} bytes${v?"":" \u2014 not delivered"})`,h=(v,R,x)=>{r.push({ref:b,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(g(!1));continue}let _;try{_=await t.fetchAttachment(p.id)}catch{h(p.media_type,"external-image-not-fetched"),i.push(g(!1));continue}let y=_.bytes,m=J(y),f=vt[m.format],I=B(y);if(s.set(I,y),!St.has(m.format)){let v=m.format==="gif"||m.format==="bmp"||m.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(f,v,{blob:I}),i.push(g(!1));continue}if(m.width===void 0||m.height===void 0||m.width*m.height>It){h(f,"undecodable",{blob:I}),i.push(g(!1));continue}let L;if(m.format==="png"||m.format==="jpeg"){let v=F(y,m.format);if(v===null){h(f,"undecodable",{blob:I}),i.push(g(!1));continue}L=M(v.data,{width:v.width,height:v.height,channels:v.channels})}if(m.width<Se||m.height<Se){h(f,"below-dimension-floor",{blob:I,appearance:L}),i.push(g(!1));continue}let O=u.get(I);if(O!==void 0){h(f,"duplicate",{blob:I,appearance:L,duplicate_of:O}),i.push(g(!1));continue}if(y.byteLength>Lt){h(f,"image-too-large",{blob:I,appearance:L}),i.push(g(!1));continue}if(l+y.byteLength>At){h(f,"vision-byte-budget-reached",{blob:I,appearance:L}),i.push(g(!1));continue}if(o.length>=wt){h(f,"image-cap-reached",{blob:I,appearance:L}),i.push(g(!1));continue}u.set(I,b),l+=y.byteLength,o.push(b),h(f,"selected",{blob:I,appearance:L}),i.push(g(!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-CSYBNMIH.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),b=o.site;if(d.host)try{b=new URL(d.host).hostname}catch{b=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:g}=ve(d,b,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 y=te(r,h);if(y!==null&&y!==b)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${y}, but this read serves ${b} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let m=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:f=>l.jiraAttachment(f,i)})}});e.out(U(e.isTTY,m,o.issueKey));for(let f of g)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: jira, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}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],b=`i${d+1}`,w=`attachment:${p.filename}`,g=R=>`[img#${b}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:b,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(g(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let y;try{y=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let m=y.bytes,f=J(m),I=Pt[f.format],L=B(m);if(o.set(L,m),!Ut.has(f.format)){let R=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(g(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Nt){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}let O;if(f.format==="png"||f.format==="jpeg"){let R=F(m,f.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(f.width<Ue||f.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(g(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(g(!1));continue}if(m.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(g(!1));continue}if(u+m.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(g(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(g(!1));continue}i.set(L,b),u+=m.byteLength,l.push(b),h(I,"selected",{blob:L,appearance:O}),c.push(g(!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-5HAY24TN.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),b=o.site;if(d.host)try{b=new URL(d.host).hostname}catch{b=d.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:w,warnings:g}=ve(d,b,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 y=te(r,h);if(y!==null&&y!==b)return(e.err??e.out)(`error: ${t}: source '${h}' was ingested from ${y}, but this read serves ${b} \u2014 retire it first (kane-cli context retire ${h}) or ingest under a different id with --as`),{code:1};let m=await T({contextDir:r,bytes:w,media:he,sourceId:h,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{jira:$e({fetchAttachment:f=>l.jiraAttachment(f,i)})}});e.out(U(e.isTTY,m,o.issueKey));for(let f of g)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: jira, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}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],b=`i${d+1}`,w=`attachment:${p.filename}`,g=R=>`[img#${b}] ${p.filename} (${p.media_type}, ${p.size} bytes${R?"":" \u2014 not delivered"})`,h=(R,x,D)=>{s.push({ref:b,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(g(!1));continue}let _=n.get(p.id);if(!_){h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let y;try{y=await t.fetchAttachment({id:p.id,download:_})}catch{h(p.media_type,"external-image-not-fetched"),c.push(g(!1));continue}let m=y.bytes,f=J(m),I=Pt[f.format],L=B(m);if(o.set(L,m),!Ut.has(f.format)){let R=f.format==="gif"||f.format==="bmp"||f.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";h(I,R,{blob:L}),c.push(g(!1));continue}if(f.width===void 0||f.height===void 0||f.width*f.height>Nt){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}let O;if(f.format==="png"||f.format==="jpeg"){let R=F(m,f.format);if(R===null){h(I,"undecodable",{blob:L}),c.push(g(!1));continue}O=M(R.data,{width:R.width,height:R.height,channels:R.channels})}if(f.width<Ue||f.height<Ue){h(I,"below-dimension-floor",{blob:L,appearance:O}),c.push(g(!1));continue}let v=i.get(L);if(v!==void 0){h(I,"duplicate",{blob:L,appearance:O,duplicate_of:v}),c.push(g(!1));continue}if(m.byteLength>Ot){h(I,"image-too-large",{blob:L,appearance:O}),c.push(g(!1));continue}if(u+m.byteLength>Tt){h(I,"vision-byte-budget-reached",{blob:L,appearance:O}),c.push(g(!1));continue}if(l.length>=Ct){h(I,"image-cap-reached",{blob:L,appearance:O}),c.push(g(!1));continue}i.set(L,b),u+=m.byteLength,l.push(b),h(I,"selected",{blob:L,appearance:O}),c.push(g(!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-CSYBNMIH.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:b,warnings:w}=Pe(d,p),g=n??`page-${o.pageId}`;N(g);let h=P(r,g,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,g);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let y=Object.fromEntries((d.attachments??[]).filter(f=>typeof f.download=="string"&&f.download.length>0).map(f=>[String(f.id),f.download])),m=await T({contextDir:r,bytes:b,media:ye,sourceId:g,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:y,fetchAttachment:f=>u.confluenceAttachment(f.download,c)})}});e.out(U(e.isTTY,m,`${o.spaceKey}/${o.pageId}`));for(let f of w)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: confluence, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}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=f=>`[img#${a}] ${c.label}${f?"":" \u2014 not delivered"}`,p=(f,I,L)=>{e.push({ref:a,loc:c.loc,media_type:f,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},b;try{b=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=b.bytes,g=J(w),h=zt[g.format],_=B(w);if(r.set(_,w),!Xt.has(g.format)){let f=g.format==="gif"||g.format==="bmp"||g.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,f,{blob:_}),u.push(d(!1));continue}if(g.width===void 0||g.height===void 0||g.width*g.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let y;if(g.format==="png"||g.format==="jpeg"){let f=F(w,g.format);if(f===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}y=M(f.data,{width:f.width,height:f.height,channels:f.channels})}if(g.width<Ke||g.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:y}),u.push(d(!1));continue}let m=l.get(_);if(m!==void 0){p(h,"duplicate",{blob:_,appearance:y,duplicate_of:m}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:y}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:y}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:y}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:y}),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-5HAY24TN.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:b,warnings:w}=Pe(d,p),g=n??`page-${o.pageId}`;N(g);let h=P(r,g,"confluence");if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=te(r,g);if(_!==null&&_!==p)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${_}, but this read serves ${p} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let y=Object.fromEntries((d.attachments??[]).filter(f=>typeof f.download=="string"&&f.download.length>0).map(f=>[String(f.id),f.download])),m=await T({contextDir:r,bytes:b,media:ye,sourceId:g,label:t,confirmSameSource:e.isTTY?f=>e.confirm(`identical content already ingested as ${f} \u2014 treat as the same source?`):void 0,converters:{confluence:xe({downloads:y,fetchAttachment:f=>u.confluenceAttachment(f.download,c)})}});e.out(U(e.isTTY,m,`${o.spaceKey}/${o.pageId}`));for(let f of w)e.out(`warning: ${f}`);for(let f of m.warnings??[])e.out(`warning: ${f}`);if(m.composite){let f=m.composite.delivered+m.composite.omitted;e.out(`${m.source_id}: confluence, ${f} attachments, ${m.composite.delivered} images delivered (${m.composite.omitted} omitted)`)}return{code:0,result:{status:m.status,source_id:m.source_id,source_cid:m.cid,...m.gitignore?{gitignore:m.gitignore}:{}}}}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=f=>`[img#${a}] ${c.label}${f?"":" \u2014 not delivered"}`,p=(f,I,L)=>{e.push({ref:a,loc:c.loc,media_type:f,...L?.blob?{blob:L.blob}:{},...L?.appearance?{appearance:L.appearance}:{},delivery:I,...L?.duplicate_of?{duplicate_of:L.duplicate_of}:{}})},b;try{b=await n(c.url)}catch{p("application/octet-stream","external-image-not-fetched"),u.push(d(!1));continue}let w=b.bytes,g=J(w),h=zt[g.format],_=B(w);if(r.set(_,w),!Xt.has(g.format)){let f=g.format==="gif"||g.format==="bmp"||g.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";p(h,f,{blob:_}),u.push(d(!1));continue}if(g.width===void 0||g.height===void 0||g.width*g.height>Kt){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}let y;if(g.format==="png"||g.format==="jpeg"){let f=F(w,g.format);if(f===null){p(h,"undecodable",{blob:_}),u.push(d(!1));continue}y=M(f.data,{width:f.width,height:f.height,channels:f.channels})}if(g.width<Ke||g.height<Ke){p(h,"below-dimension-floor",{blob:_,appearance:y}),u.push(d(!1));continue}let m=l.get(_);if(m!==void 0){p(h,"duplicate",{blob:_,appearance:y,duplicate_of:m}),u.push(d(!1));continue}if(w.byteLength>Yt){p(h,"image-too-large",{blob:_,appearance:y}),u.push(d(!1));continue}if(o+w.byteLength>Wt){p(h,"vision-byte-budget-reached",{blob:_,appearance:y}),u.push(d(!1));continue}if(s.length>=Gt){p(h,"image-cap-reached",{blob:_,appearance:y}),u.push(d(!1));continue}l.set(_,a),o+=w.byteLength,s.push(a),p(h,"selected",{blob:_,appearance:y}),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-CSYBNMIH.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:b,envelope:w,warnings:g}=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 y=await T({contextDir:r,bytes:b,media:Ee,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:{linear:ze({fetchAttachment:m=>l.linearAttachment(m,i)})}});e.out(U(e.isTTY,y,w.issue.key));for(let m of g)e.out(`warning: ${m}`);for(let m of y.warnings??[])e.out(`warning: ${m}`);if(y.composite){let m=y.composite.delivered+y.composite.omitted;e.out(`${y.source_id}: linear, ${m} images, ${y.composite.delivered} delivered (${y.composite.omitted} omitted)`)}return{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid,...y.gitignore?{gitignore:y.gitignore}:{}}}}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-CSYBNMIH.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:b,warnings:w}=Ye(a,d,o.slugId),g=n??`doc-${o.slugId}`;N(g);let h=rt(r,"linear-doc",["document","uuid"],g,b.document.uuid,"document")??P(r,g,"linear-doc")??ot(r,"linear-doc",g,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:g,label:t,confirmSameSource:e.isTTY?y=>e.confirm(`identical content already ingested as ${y} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:y=>l.linearAttachment(y,i)})}});e.out(U(e.isTTY,_,b.title||`document ${o.slugId}`));for(let y of w)e.out(`warning: ${y}`);for(let y of _.warnings??[])e.out(`warning: ${y}`);if(_.composite){let y=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${y} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid,..._.gitignore?{gitignore:_.gitignore}:{}}}}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(b){return(e.err??e.out)(`error: ${t}: ${b instanceof Error?b.message:String(b)}`),{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-YSJNIMNY.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:b}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:b,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()}}),g=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,g));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,...w.gitignore?{gitignore:w.gitignore}:{}}}}catch(b){return(e.err??e.out)(`error: ${t}: ${cn(b instanceof Error?b.message:String(b))}`),{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-5HAY24TN.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:b,envelope:w,warnings:g}=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 y=await T({contextDir:r,bytes:b,media:Ee,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:{linear:ze({fetchAttachment:m=>l.linearAttachment(m,i)})}});e.out(U(e.isTTY,y,w.issue.key));for(let m of g)e.out(`warning: ${m}`);for(let m of y.warnings??[])e.out(`warning: ${m}`);if(y.composite){let m=y.composite.delivered+y.composite.omitted;e.out(`${y.source_id}: linear, ${m} images, ${y.composite.delivered} delivered (${y.composite.omitted} omitted)`)}return{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid,...y.gitignore?{gitignore:y.gitignore}:{}}}}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-5HAY24TN.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:b,warnings:w}=Ye(a,d,o.slugId),g=n??`doc-${o.slugId}`;N(g);let h=rt(r,"linear-doc",["document","uuid"],g,b.document.uuid,"document")??P(r,g,"linear-doc")??ot(r,"linear-doc",g,d);if(h!==null)return(e.err??e.out)(`error: ${t}: ${h}`),{code:1};let _=await T({contextDir:r,bytes:p,media:_e,sourceId:g,label:t,confirmSameSource:e.isTTY?y=>e.confirm(`identical content already ingested as ${y} \u2014 treat as the same source?`):void 0,converters:{linearDoc:Xe({fetchAttachment:y=>l.linearAttachment(y,i)})}});e.out(U(e.isTTY,_,b.title||`document ${o.slugId}`));for(let y of w)e.out(`warning: ${y}`);for(let y of _.warnings??[])e.out(`warning: ${y}`);if(_.composite){let y=_.composite.delivered+_.composite.omitted;e.out(`${_.source_id}: linear document, ${y} images, ${_.composite.delivered} delivered (${_.composite.omitted} omitted)`)}return{code:0,result:{status:_.status,source_id:_.source_id,source_cid:_.cid,..._.gitignore?{gitignore:_.gitignore}:{}}}}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(b){return(e.err??e.out)(`error: ${t}: ${b instanceof Error?b.message:String(b)}`),{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-HZXP66DS.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:b}=lt(o,p.page.projection,p.page.markdown),w=await T({contextDir:r,bytes:b,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()}}),g=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,w,g));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,...w.gitignore?{gitignore:w.gitignore}:{}}}}catch(b){return(e.err??e.out)(`error: ${t}: ${cn(b instanceof Error?b.message:String(b))}`),{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,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as v}from"./chunk-QSCXXNC2.js";import{n as g}from"./chunk-RSSOJ3L2.js";import{a as u,b as d}from"./chunk-MI6UFDRC.js";import{existsSync as F}from"fs";import{join as P}from"path";import{mkdirSync as w,rmSync as b,writeFileSync as h}from"fs";import{join as S,resolve as k}from"path";import{join as W}from"path";function f(){return process.env.KANE_CLI_WIRE_BASE_DIR||d}function B(e){return W(f(),"sessions",`testrun-${e}`)}function E(e=f()){return S(e,"sessions","active")}function y(e,r){return S(E(r),`${e}.json`)}function _(e){let r=e.pid??process.pid,n=y(r,e.baseDir);try{w(E(e.baseDir),{recursive:!0}),h(n,JSON.stringify({pid:r,cwd:process.cwd(),surface:e.surface,session_dir:k(e.sessionDir),started:new Date().toISOString(),cli_version:u,host_agent:v()},null,2)+`
2
+ import{a as v}from"./chunk-QSCXXNC2.js";import{n as g}from"./chunk-RSSOJ3L2.js";import{a as u,b as d}from"./chunk-SJZJ7ASF.js";import{existsSync as F}from"fs";import{join as P}from"path";import{mkdirSync as w,rmSync as b,writeFileSync as h}from"fs";import{join as S,resolve as k}from"path";import{join as W}from"path";function f(){return process.env.KANE_CLI_WIRE_BASE_DIR||d}function B(e){return W(f(),"sessions",`testrun-${e}`)}function E(e=f()){return S(e,"sessions","active")}function y(e,r){return S(E(r),`${e}.json`)}function _(e){let r=e.pid??process.pid,n=y(r,e.baseDir);try{w(E(e.baseDir),{recursive:!0}),h(n,JSON.stringify({pid:r,cwd:process.cwd(),surface:e.surface,session_dir:k(e.sessionDir),started:new Date().toISOString(),cli_version:u,host_agent:v()},null,2)+`
3
3
  `)}catch{}return n}function m(e=process.pid,r){try{b(y(e,r),{force:!0})}catch{}}var R={run:"run_end",testmd:"test_md_done",testrun:"testrun_done"};import{appendFileSync as A,mkdirSync as I}from"fs";import{dirname as N}from"path";function x(e){let r=!1;return{path:e,append(n){try{r||(I(N(e),{recursive:!0}),r=!0),A(e,n+`
4
4
  `)}catch{}}}}function D(e,r=()=>new Date){let{v:n,ts:c,...i}=e;return{...i,v:1,ts:typeof c=="string"?c:r().toISOString()}}function T(e){let r=e.stdout??(t=>{process.stdout.write(t)}),n=R[e.surface],c=!1,i=null,o=null,p=[],l=()=>{if(!(o||!i||!F(i))){o=x(P(i,"events.ndjson"));for(let t of p)o.append(t);p=[];try{e.onAttach?.(i)}catch{}}};return{emit(t){if(c)return;let a=JSON.stringify(D(t,e.now));r(a+`
5
5
  `),l(),o?o.append(a):p.push(a),t.type===n&&(c=!0,p=[])},attachSessionDir(t){i=t,l()},setTerminal(t){n=t},get logPath(){return o?o.path:null}}}var s=null;function V(e){return r=>{_({surface:e,sessionDir:r}),g("wire-active-run",()=>m()),process.once("exit",()=>m())}}function ie(e,r){return s=T({surface:e,cliVersion:u,onAttach:r??V(e)}),s.emit({type:"stream_start",cli_version:u,surface:e,pid:process.pid}),s}function oe(){return s}function se(e){if(s){s.emit(e);return}process.stdout.write(JSON.stringify(D(e))+`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as B,c as S,d as T}from"./chunk-JW7M3ENB.js";import{c as g}from"./chunk-RFHMDQXZ.js";import{a as E}from"./chunk-4HPJ4S6H.js";import{y as n}from"./chunk-MI6UFDRC.js";import{a as h}from"./chunk-HCBYKLMW.js";import{a as i,b as c,c as w,i as x}from"./chunk-C44QQJR4.js";import{a as L}from"./chunk-6YGTRKDT.js";import{e as u}from"./chunk-UR6MHSHU.js";var l=u(L(),1);var r=u(h(),1);function y(e){return new Map(e.map((o,s)=>[`${s}-${o.label}`,o.packPath]))}async function H(e){let o=e.deps?.viewerBase??S(e.env),s=e.deps?.startServer??B,a=e.deps?.openUrl??(m=>g(m).then(()=>{})),t=y(e.rows),d;try{d=await s({packs:t,allowedOrigins:[new URL(o).origin]});let m=d,D=async p=>{let v=[...t.keys()][p];await a(T(m.urlFor(v),o))};if(e.deps?.hold){await e.deps.hold();return}await new Promise(p=>{let v=w(l.default.createElement(P,{rows:e.rows,onOpen:D,onDone:()=>{v.unmount(),p()}}),{stdout:process.stderr,exitOnCtrlC:!1})})}finally{await d?.close()}}function I(e){return e==="passed"?n.green:e==="failed"||e==="broken"||e==="cancelled"?n.red:n.dim}var b=40,R=9,k=20;function f(e,o){return e.length>o?e.slice(0,o-1)+"\u2026":e.padEnd(o)}function O({row:e,selected:o}){let s=e.testId??e.commitId??"";return(0,r.jsxs)(i,{children:[(0,r.jsx)(i,{width:2,flexShrink:0,children:(0,r.jsx)(c,{color:n.orange,children:o?"\u25B8":" "})}),(0,r.jsx)(i,{width:2,flexShrink:0,children:(0,r.jsx)(c,{color:e.kind==="execution"?n.orange:n.muted,children:e.kind==="execution"?"\u25CF":"\u25CB"})}),(0,r.jsx)(i,{width:b,flexShrink:0,children:(0,r.jsx)(c,{color:o?n.orange:void 0,bold:o,wrap:"truncate-end",children:f(e.label,b)})}),(0,r.jsx)(i,{width:R,flexShrink:0,children:(0,r.jsx)(c,{color:I(e.status),bold:o,wrap:"truncate-end",children:f(e.status,R)})}),(0,r.jsx)(i,{width:k,flexShrink:0,children:(0,r.jsx)(c,{color:n.dim,wrap:"truncate-end",children:f(s,k)})})]})}function P(e){let[o,s]=(0,l.useState)(0);return x((a,t)=>{t.upArrow?s(d=>Math.max(0,d-1)):t.downArrow?s(d=>Math.min(e.rows.length-1,d+1)):t.return||a==="o"?e.onOpen(o):(a==="q"||t.escape)&&e.onDone()}),(0,r.jsx)(E,{title:"Evidence",borderColor:n.muted,children:(0,r.jsxs)(i,{flexDirection:"column",children:[e.rows.map((a,t)=>(0,r.jsx)(O,{row:a,selected:t===o},t)),(0,r.jsx)(i,{marginTop:1,children:(0,r.jsx)(c,{color:n.dim,children:"\u2191/\u2193 move \xB7 enter/o open \xB7 q quit"})})]})})}export{y as a,H as b};
2
+ import{b as B,c as S,d as T}from"./chunk-5TQIKRKP.js";import{c as g}from"./chunk-RFHMDQXZ.js";import{a as E}from"./chunk-DZCJE77P.js";import{y as n}from"./chunk-SJZJ7ASF.js";import{a as h}from"./chunk-HCBYKLMW.js";import{a as i,b as c,c as w,i as x}from"./chunk-C44QQJR4.js";import{a as L}from"./chunk-6YGTRKDT.js";import{e as u}from"./chunk-UR6MHSHU.js";var l=u(L(),1);var r=u(h(),1);function y(e){return new Map(e.map((o,s)=>[`${s}-${o.label}`,o.packPath]))}async function H(e){let o=e.deps?.viewerBase??S(e.env),s=e.deps?.startServer??B,a=e.deps?.openUrl??(m=>g(m).then(()=>{})),t=y(e.rows),d;try{d=await s({packs:t,allowedOrigins:[new URL(o).origin]});let m=d,D=async p=>{let v=[...t.keys()][p];await a(T(m.urlFor(v),o))};if(e.deps?.hold){await e.deps.hold();return}await new Promise(p=>{let v=w(l.default.createElement(P,{rows:e.rows,onOpen:D,onDone:()=>{v.unmount(),p()}}),{stdout:process.stderr,exitOnCtrlC:!1})})}finally{await d?.close()}}function I(e){return e==="passed"?n.green:e==="failed"||e==="broken"||e==="cancelled"?n.red:n.dim}var b=40,R=9,k=20;function f(e,o){return e.length>o?e.slice(0,o-1)+"\u2026":e.padEnd(o)}function O({row:e,selected:o}){let s=e.testId??e.commitId??"";return(0,r.jsxs)(i,{children:[(0,r.jsx)(i,{width:2,flexShrink:0,children:(0,r.jsx)(c,{color:n.orange,children:o?"\u25B8":" "})}),(0,r.jsx)(i,{width:2,flexShrink:0,children:(0,r.jsx)(c,{color:e.kind==="execution"?n.orange:n.muted,children:e.kind==="execution"?"\u25CF":"\u25CB"})}),(0,r.jsx)(i,{width:b,flexShrink:0,children:(0,r.jsx)(c,{color:o?n.orange:void 0,bold:o,wrap:"truncate-end",children:f(e.label,b)})}),(0,r.jsx)(i,{width:R,flexShrink:0,children:(0,r.jsx)(c,{color:I(e.status),bold:o,wrap:"truncate-end",children:f(e.status,R)})}),(0,r.jsx)(i,{width:k,flexShrink:0,children:(0,r.jsx)(c,{color:n.dim,wrap:"truncate-end",children:f(s,k)})})]})}function P(e){let[o,s]=(0,l.useState)(0);return x((a,t)=>{t.upArrow?s(d=>Math.max(0,d-1)):t.downArrow?s(d=>Math.min(e.rows.length-1,d+1)):t.return||a==="o"?e.onOpen(o):(a==="q"||t.escape)&&e.onDone()}),(0,r.jsx)(E,{title:"Evidence",borderColor:n.muted,children:(0,r.jsxs)(i,{flexDirection:"column",children:[e.rows.map((a,t)=>(0,r.jsx)(O,{row:a,selected:t===o},t)),(0,r.jsx)(i,{marginTop:1,children:(0,r.jsx)(c,{color:n.dim,children:"\u2191/\u2193 move \xB7 enter/o open \xB7 q quit"})})]})})}export{y as a,H as b};
@@ -1,3 +1,3 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as w}from"./chunk-ZLWURCJ7.js";import{a as O}from"./chunk-QSCXXNC2.js";import{a as I}from"./chunk-KBM3XHAM.js";import{f as L}from"./chunk-5LJRZI7S.js";import{a as N,b as k}from"./chunk-BKM2LWU2.js";import{a as R,b as y,c as T,d as m,e as A,g as b,h as r}from"./chunk-RSSOJ3L2.js";import{b as x}from"./chunk-5EOX4MEY.js";import{a as E}from"./chunk-RZ4F3BHX.js";import{a as g,i as v}from"./chunk-MI6UFDRC.js";import{platform as X,arch as Y}from"os";import P from"fs";import M from"fs";import D from"path";var V=1e3,d=0,j=new Set([130,3]),a=class t{ids;logger;opts;ended=!1;createdAt=Date.now();errorState;constructor(e,n={emitted:!1}){this.ids=e.envelope,this.logger=e.logger,this.opts=e,this.errorState=n}get enabled(){return this.logger!==null}event(e,n={}){if(!this.logger)return;e==="ASR_ERROR"&&(this.errorState.emitted=!0);let i=m(this.ids,e,n);this.logger.log(R[e],e,e,C(i))}error(e,n={}){this.logger&&(this.logger.escalate(d),this.event("ASR_ERROR",{...n,error_code:e}))}child(e,n){return new t({...this.opts,envelope:{...this.ids,operation_id:n,parent_operation_id:this.ids.operation_id,verb:"design"}},this.errorState)}async lateBindContext(e){if(!(!this.logger||this.ids.context_instance_id))try{let{ensureStoreIds:n}=await import("./store-id-EOSGEKVK.js"),{ids:i,cloned:s}=n(e);this.ids.context_lineage_id=i.context_lineage_id,this.ids.context_instance_id=i.context_instance_id,s&&this.event("ASR_CONTEXT_CLONED")}catch{}}agentSession(e){this.ids.agent_session_id=e}spawnEnv(){if(!this.opts.telemetryEnabled)return{};let e={TESTMUAI_USER_SESSION_ID:this.ids.session_id,TESTMUAI_OPERATION_ID:this.ids.operation_id,TESTMUAI_CLIENT_VERSION:this.opts.clientVersion,TESTMUAI_TELEMETRY_PROXY_URL:this.opts.proxyUrl};return this.ids.context_instance_id&&(e.TESTMUAI_CONTEXT_INSTANCE_ID=this.ids.context_instance_id),e}traceTee(){return e=>{if(!this.logger)return;let n=typeof e.kind=="string"?e.kind.slice(0,64):"trace",i={...C(m(this.ids,"ASR_CMD_START",{})),trace_kind:n};typeof e.code=="string"&&(i.trace_code=e.code.slice(0,64)),delete i.event,this.logger.logStep(d,`trace_${n}`,n,i)}}wireTrace(e,n,i){if(!this.logger)return;i&&this.agentSession(i);let s=n&&typeof n=="object"?n:{};switch(e){case"spawn":this.event("ASR_AGENT_SPAWN",{tier:s.tier});break;case"session_paused":this.event("ASR_SESSION_PAUSED",s);break;case"commit":this.event("ASR_COMMIT",s);break;default:this.traceTee()({kind:e,code:typeof s.code=="string"?s.code:void 0})}}banner(){return`session: ${this.ids.session_id}`}supportFooter(){return`if this keeps failing, share this id with support: ${this.ids.session_id}`}async end(e){if(!this.ended){if(this.ended=!0,e.duration_ms===void 0&&(e={...e,duration_ms:Date.now()-this.createdAt}),this.logger)if(e.exit_code===0?this.logger.discardSteps(d):this.logger.escalate(d),e.exit_code>0&&!j.has(e.exit_code)&&!this.errorState.emitted&&this.event("ASR_ERROR",{error_code:e.exit_code===2?"usage_exit_unattributed":`exit_${e.exit_code}_unattributed`,exit_code:e.exit_code}),this.event("ASR_CMD_END",e),this.opts.longSession)await this.logger.shutdown();else{let n=await this.logger.flushOnce(V);(n==="failed"||n==="timeout")&&A(this.logger.drainBuffer())}this.logger&&this.writeManifestLine(e.exit_code),r(null)}}writeManifestLine(e){try{let n=x(this.ids.context_instance_id??null);M.mkdirSync(D.dirname(n),{recursive:!0});let i={ts:new Date().toISOString(),session_id:this.ids.session_id,operation_id:this.ids.operation_id,agent_session_id:this.ids.agent_session_id,verb:this.ids.verb,mode:this.ids.mode,exit_code:e};M.appendFileSync(n,JSON.stringify(i)+`
2
+ import{a as w}from"./chunk-ZLWURCJ7.js";import{a as O}from"./chunk-QSCXXNC2.js";import{a as I}from"./chunk-KBM3XHAM.js";import{f as L}from"./chunk-5LJRZI7S.js";import{a as N,b as k}from"./chunk-BKM2LWU2.js";import{a as R,b as y,c as T,d as m,e as A,g as b,h as r}from"./chunk-RSSOJ3L2.js";import{b as x}from"./chunk-5EOX4MEY.js";import{a as E}from"./chunk-RZ4F3BHX.js";import{a as g,i as v}from"./chunk-SJZJ7ASF.js";import{platform as X,arch as Y}from"os";import P from"fs";import M from"fs";import D from"path";var V=1e3,d=0,j=new Set([130,3]),a=class t{ids;logger;opts;ended=!1;createdAt=Date.now();errorState;constructor(e,n={emitted:!1}){this.ids=e.envelope,this.logger=e.logger,this.opts=e,this.errorState=n}get enabled(){return this.logger!==null}event(e,n={}){if(!this.logger)return;e==="ASR_ERROR"&&(this.errorState.emitted=!0);let i=m(this.ids,e,n);this.logger.log(R[e],e,e,C(i))}error(e,n={}){this.logger&&(this.logger.escalate(d),this.event("ASR_ERROR",{...n,error_code:e}))}child(e,n){return new t({...this.opts,envelope:{...this.ids,operation_id:n,parent_operation_id:this.ids.operation_id,verb:"design"}},this.errorState)}async lateBindContext(e){if(!(!this.logger||this.ids.context_instance_id))try{let{ensureStoreIds:n}=await import("./store-id-EOSGEKVK.js"),{ids:i,cloned:s}=n(e);this.ids.context_lineage_id=i.context_lineage_id,this.ids.context_instance_id=i.context_instance_id,s&&this.event("ASR_CONTEXT_CLONED")}catch{}}agentSession(e){this.ids.agent_session_id=e}spawnEnv(){if(!this.opts.telemetryEnabled)return{};let e={TESTMUAI_USER_SESSION_ID:this.ids.session_id,TESTMUAI_OPERATION_ID:this.ids.operation_id,TESTMUAI_CLIENT_VERSION:this.opts.clientVersion,TESTMUAI_TELEMETRY_PROXY_URL:this.opts.proxyUrl};return this.ids.context_instance_id&&(e.TESTMUAI_CONTEXT_INSTANCE_ID=this.ids.context_instance_id),e}traceTee(){return e=>{if(!this.logger)return;let n=typeof e.kind=="string"?e.kind.slice(0,64):"trace",i={...C(m(this.ids,"ASR_CMD_START",{})),trace_kind:n};typeof e.code=="string"&&(i.trace_code=e.code.slice(0,64)),delete i.event,this.logger.logStep(d,`trace_${n}`,n,i)}}wireTrace(e,n,i){if(!this.logger)return;i&&this.agentSession(i);let s=n&&typeof n=="object"?n:{};switch(e){case"spawn":this.event("ASR_AGENT_SPAWN",{tier:s.tier});break;case"session_paused":this.event("ASR_SESSION_PAUSED",s);break;case"commit":this.event("ASR_COMMIT",s);break;default:this.traceTee()({kind:e,code:typeof s.code=="string"?s.code:void 0})}}banner(){return`session: ${this.ids.session_id}`}supportFooter(){return`if this keeps failing, share this id with support: ${this.ids.session_id}`}async end(e){if(!this.ended){if(this.ended=!0,e.duration_ms===void 0&&(e={...e,duration_ms:Date.now()-this.createdAt}),this.logger)if(e.exit_code===0?this.logger.discardSteps(d):this.logger.escalate(d),e.exit_code>0&&!j.has(e.exit_code)&&!this.errorState.emitted&&this.event("ASR_ERROR",{error_code:e.exit_code===2?"usage_exit_unattributed":`exit_${e.exit_code}_unattributed`,exit_code:e.exit_code}),this.event("ASR_CMD_END",e),this.opts.longSession)await this.logger.shutdown();else{let n=await this.logger.flushOnce(V);(n==="failed"||n==="timeout")&&A(this.logger.drainBuffer())}this.logger&&this.writeManifestLine(e.exit_code),r(null)}}writeManifestLine(e){try{let n=x(this.ids.context_instance_id??null);M.mkdirSync(D.dirname(n),{recursive:!0});let i={ts:new Date().toISOString(),session_id:this.ids.session_id,operation_id:this.ids.operation_id,agent_session_id:this.ids.agent_session_id,verb:this.ids.verb,mode:this.ids.mode,exit_code:e};M.appendFileSync(n,JSON.stringify(i)+`
3
3
  `,{flag:"a",mode:384})}catch{}}};function C(t){let e={event:t.event,session_id:t.session_id,operation_id:t.operation_id,verb:t.verb,mode:t.mode,component:t.component,seq:t.seq,context_lineage_id:t.context_lineage_id,context_instance_id:t.context_instance_id};t.parent_operation_id&&(e.parent_operation_id=t.parent_operation_id),t.agent_session_id&&(e.agent_session_id=t.agent_session_id);for(let[n,i]of Object.entries(t.context))e[n]=i;return e}var u=process.env.KANE_TELEMETRY_URL||v;function B(){return process.env.TESTMUAI_BASE_URL?"custom":process.env.TESTMUAI_ENV==="stage"?"stage":"prod"}function _e(t){let e=process.env.KANE_TELEMETRY!=="0"&&(!process.env.VITEST||process.env.KANE_TELEMETRY==="1"),n=t.env??B(),i=null;if(t.resumeSid&&t.contextRoot)try{let o=L(t.contextRoot,t.resumeSid);o?.user_session_id&&(i=o.user_session_id)}catch{}if(!i&&t.applyPlanPath)try{let o=JSON.parse(P.readFileSync(t.applyPlanPath,"utf8"));o.telemetry?.user_session_id&&(i=o.telemetry.user_session_id)}catch{}let s=i!==null;i||(i=y());let l=null,c=null,f=!1;if(t.contextRoot&&P.existsSync(t.contextRoot))if(t.write&&e){let o=k(t.contextRoot);l=o.ids.context_lineage_id,c=o.ids.context_instance_id,f=o.cloned}else{let o=N(t.contextRoot);l=o?.context_lineage_id??null,c=o?.context_instance_id??null}let h={session_id:i,operation_id:T(),context_lineage_id:l,context_instance_id:c,verb:t.verb,mode:t.mode,component:"kane-cli"},_=null;if(e){let o=I(n),S={org_id:o.org_id??"",user_id:o.user_id??"",machine_id:o.machine_id,email:null,email_domain:"",user_type:o.user_type??"unknown",env:o.env,plan:o.plan??"unknown"},U=t.mode==="interactive"||t.mode==="cli"?"cli":"agent";_=new w({proxyUrl:u,sessionId:i,identity:S,device:{cli_version:g,platform:X(),arch:Y(),host_agent:O(),invocation_mode:U},getToken:async()=>null}),t.longSession&&_.start()}let p=new a({envelope:h,logger:_,longSession:!!t.longSession,proxyUrl:u,clientVersion:`kane-cli/${g}`,telemetryEnabled:e});return e&&(r(h),p.event("ASR_CMD_START",{resumed:s,applied_plan:!!t.applyPlanPath}),f&&p.event("ASR_CONTEXT_CLONED"),b(async o=>{try{return(await E(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)})).ok}catch{return!1}}).catch(()=>{})),p}export{B as a,_e as b};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as j}from"./chunk-RKXHVP2Z.js";import{a as L}from"./chunk-RRY5IXOB.js";import{a as O}from"./chunk-5Y2G4NC7.js";import{a as D}from"./chunk-YCCUBQY4.js";import{y as l}from"./chunk-MI6UFDRC.js";import{a as E}from"./chunk-HCBYKLMW.js";import{a as g,b as s,i as I,k as B}from"./chunk-C44QQJR4.js";import{a as P}from"./chunk-6YGTRKDT.js";import{e as $}from"./chunk-UR6MHSHU.js";var H=$(P(),1);var w=$(E(),1),K=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function J(e){let t=e.replace(/…$/,"");return t&&t.charAt(0).toLowerCase()+t.slice(1)}function N(e,t){if(e.length<=t)return e;if(t<=1)return"\u2026";let r=Math.ceil((t-1)/2),n=Math.floor((t-1)/2);return`${e.slice(0,r)}\u2026${n>0?e.slice(-n):""}`}function Z({status:e,meta:t,tallies:r,keys:n,child:d,cols:c}){let{stdout:h}=B(),m=c??h?.columns??80,f=e.kind==="working"||e.kind==="child-working",[i,b]=(0,H.useState)(0);O(()=>b(a=>a+1),f?120:null);let k=K[i%K.length],u,p;switch(e.kind){case"working":u=`${k} ${e.step}${e.elapsedS!==void 0?` \xB7 ${e.elapsedS}s`:""}`,p=l.assuranceAccent;break;case"waiting":u=`\u25CF waiting on you${e.pending?` \u2014 ${e.pending} question${e.pending===1?"":"s"}`:""}`,p=l.amber;break;case"idle":u="\u25CF idle",p=l.assuranceAccent;break;case"card":u=`\u25CF card ${e.n} of ${e.m}`,p=l.amber;break;case"child-working":u=`${k} child: ${e.step}`,p=l.assuranceAccent;break;case"child-waiting":u="\u25CF child waiting on you",p=l.amber;break}let A=d?`${t.verb} \u25B8 ${d.verb}`:t.verb,S=d?.sid?t.sid?`${N(t.sid,14)} \u25B8 ${d.sid}`:d.sid:t.sid,C=t.env==="prod"?"":t.env,_=[A,S,C].filter(Boolean),v=" \xB7 ",R=u.length+v.length+_.join(v).length,T=t.subject;if(T){let a=m-R-v.length;T=a>=8?N(T,a):void 0}let M=[A,...T?[T]:[],S,C].filter(Boolean).join(v);return(0,w.jsxs)(g,{flexDirection:"column",children:[(0,w.jsx)(s,{color:l.muted,children:"\u2500".repeat(Math.max(1,m))}),(0,w.jsxs)(s,{children:[(0,w.jsx)(s,{color:p,children:u}),(0,w.jsx)(s,{color:l.dim,children:`${v}${M}`})]}),(0,w.jsx)(s,{color:l.dim,children:r.items.length>0?r.items.join(v):" "}),(0,w.jsx)(s,{color:l.muted,children:n.join(v)})]})}var y=$(P(),1);function ne({onToggleThinking:e,onCtrlC:t,explorer:r,panel:n}){let c=(0,y.useRef)(null),h=(0,y.useRef)(""),m=()=>{c.current&&clearTimeout(c.current),c.current=null,h.current=""};return(0,y.useEffect)(()=>m,[]),I((f,i)=>{if(i.ctrl&&f==="t"){e();return}if(i.ctrl&&f==="c"){t();return}if(!i.ctrl&&f.includes("")){t();return}if(!i.ctrl&&f.includes("")){e();return}if(r&&r.isOpen()){let b=()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{m(),r.onBack()},150)};if(c.current){if(i.upArrow||i.downArrow||i.return){m(),i.return?r.onEnter():r.onMove(i.upArrow?-1:1);return}if(h.current+=f,h.current==="["){b();return}let k=h.current;m();let u=/^\[([ABCD])/.exec(k);if(u){(u[1]==="A"||u[1]==="B")&&r.onMove(u[1]==="A"?-1:1);return}r.onBack();return}if(i.upArrow){r.onMove(-1);return}if(i.downArrow){r.onMove(1);return}if(i.return){r.onEnter();return}if(i.escape){h.current="",b();return}return}if(n&&n.isFocused()){let b=()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{m(),n.onBack()},150)};if(c.current){if(i.upArrow||i.downArrow||i.return||i.leftArrow||i.rightArrow){m(),i.return?n.onSelect():i.leftArrow?n.onLeft?.():i.rightArrow?n.onRight?.():n.onMove(i.upArrow?-1:1);return}if(h.current+=f,h.current==="["){b();return}let k=h.current;m();let u=/^\[([ABCD])/.exec(k);if(u){u[1]==="A"||u[1]==="B"?n.onMove(u[1]==="A"?-1:1):u[1]==="C"?n.onRight?.():n.onLeft?.();return}n.onBack();return}if(i.upArrow){n.onMove(-1);return}if(i.downArrow){n.onMove(1);return}if(i.leftArrow){n.onLeft?.();return}if(i.rightArrow){n.onRight?.();return}if(i.return){n.onSelect();return}if(i.escape){h.current="",b();return}if(/^[1-9]$/.test(f)){n.onDigit(Number(f));return}if(i.tab){n.onTab?.();return}if(f===" "&&n.isMulti()){n.onSpace();return}if(f&&!i.ctrl&&!i.meta){n.onType(f);return}return}}),null}var o=$(E(),1);function V(e){return e.kind==="REVIEW"?[{v:"approve",label:"approve",detail:"mark it reviewed and trusted"},{v:"archive",label:"archive",detail:"reject it \u2014 asks for a reason; impact shown above"},{v:"defer",label:"defer",detail:"not now \u2014 stays queued"}]:e.kind==="PAIR"?[{v:"merge",label:"merge",detail:"duplicate \u2014 fold into the older item (it stays unreviewed)"},{v:"keep_both",label:"keep both",detail:"genuinely distinct \u2014 promote both"},{v:"defer",label:"defer",detail:"not now \u2014 stays queued"}]:e.kind==="ARCHIVE"?[{v:"archive",label:"retire",detail:"hidden from now on; history is kept and it can be reverted"},{v:"skip",label:"skip",detail:"keep it \u2014 decided, never re-offered"},{v:"defer",label:"defer",detail:"not now \u2014 the plan re-offers it"}]:e.heldPayload?[{v:"approve",label:"approve update",detail:"commit the held payload \u2014 impact preview above"},{v:"skip",label:"keep current",detail:"drop the held payload (the owner's disk state stays untouched)"},{v:"defer",label:"defer",detail:"not now \u2014 stays held"}]:[{v:"approve",label:"approve",detail:e.kind==="ADD"?"commit + design it":"commit the updated version (old\u2192new redirect)"},{v:"skip",label:e.origin==="content-change"?"reject":"skip",detail:e.origin==="content-change"?"drop the staged proposal \u2014 nothing committed":"leave it as is"},{v:"defer",label:"defer",detail:"not now \u2014 the plan keeps it staged"}]}function F(e){let t=V(e);return e.viewDiff&&t.push({v:"view_diff",label:"view diff",detail:"full old \u2192 new"}),t}function W(e){return e.kind==="ARCHIVE"?null:F(e).length}var q={ADD:{color:l.green??"green"},MODIFY:{color:"yellow"},ARCHIVE:{color:l.red},REVIEW:{color:"cyan"},PAIR:{color:"magenta"}},Q=60;function ce({card:e,position:t,sel:r=0,focused:n=!1,freeText:d=null,editorIntent:c="steer"}){let{stdout:h}=B(),m=h?.columns??80,f=m<Q,i=F(e),b=W(e),k=q[e.kind],u=a=>n&&r===a?(0,o.jsx)(s,{color:l.assuranceAccent,children:"\u276F"}):" ",p=e.impact,A=p&&"stale_refs"in p&&p.stale_refs.length>0?`${e.kind==="ARCHIVE"?"retiring leaves":"approving marks"} ${p.stale_refs.length} item(s) stale`+((p.direct_refs?.length??0)>0?` \u2014 ${p.direct_refs.length} directly touched: ${p.direct_refs.join(", ")}`:""):p&&"design_children"in p?`${e.kind==="REVIEW"?"archiving drops":"merging folds"} ${p.design_children} design child(ren)`:null,S=e.provenance&&e.provenance!==e.why?e.provenance:e.origin??null,C=[{label:"why",text:e.why},...S?[{label:"from",text:S,dimmer:!0}]:[],...e.tier?[{label:"match",text:e.tier,dimmer:!0}]:[],...A?[{label:"impact",text:A}]:[]],_=Math.max(...C.map(a=>a.label.length)),v="? reconcile",R=`item ${t.n} of ${t.of}`,T=(0,o.jsxs)(g,{flexDirection:"column",children:[(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsxs)(s,{bold:!0,children:[(0,o.jsx)(s,{color:k.color,children:`[${e.kind}]`}),` ${L(e.title)}`]})}),C.map((a,x)=>(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsxs)(s,{children:[(0,o.jsx)(s,{color:l.dim,children:`${a.label.padEnd(_)} `}),(0,o.jsx)(s,{color:a.dimmer?l.dim:void 0,children:a.text})]})},`f-${x}`)),e.diffSummary?(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsx)(s,{color:l.dim,children:e.diffSummary})}):(e.diff??[]).map((a,x)=>(0,o.jsx)(g,{paddingLeft:4,children:(0,o.jsx)(s,{color:a.op==="-"?"red":"green",children:`${a.op==="-"?"\u2212":"+"} ${a.field==="criteria"?"criterion":a.field}: ${a.text}`})},`d-${x}`)),(e.citeLines??[]).map((a,x)=>(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsx)(s,{color:l.dim,children:a})},`c-${x}`)),(0,o.jsx)(s,{children:" "}),i.map((a,x)=>(0,o.jsxs)(s,{children:[u(x),` ${x+1}. ${a.label}`,(0,o.jsx)(s,{color:l.dim,children:` \u2014 ${a.detail}`})]},`o-${x}`)),b!==null||d&&c==="because"?d?(0,o.jsxs)(g,{flexDirection:"column",children:[(0,o.jsxs)(g,{children:[(0,o.jsxs)(s,{children:[(0,o.jsx)(s,{color:l.assuranceAccent,children:"\u276F"})," ",(0,o.jsx)(s,{color:l.dim,children:"\u270E "})]}),(0,o.jsx)(D,{value:d.value,onChange:d.onChange,onSubmit:d.onSubmit,onCancel:d.onCancel,placeholder:c==="because"?"why archive it?":"say what to adjust"})]}),(0,o.jsx)(s,{color:l.muted,children:c==="because"?" submits as: archive \xB7 your reason goes on the record":e.kind==="PAIR"?" submits as: defer \xB7 your note parks with the card (it re-offers)":" submits as: approve \xB7 your words steer the re-design"})]}):b!==null?(0,o.jsxs)(s,{children:[u(b)," ",(0,o.jsx)(s,{color:l.dim,children:e.kind==="PAIR"?"\u270E defer with a note \u2014 say what you noticed":"\u270E approve with changes \u2014 say what to adjust"})]}):null:null]});if(f)return(0,o.jsxs)(g,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,o.jsx)(s,{bold:!0,color:l.assuranceAccent,children:v}),(0,o.jsx)(s,{color:l.dim,children:R}),T]});let M=Math.max(2,Math.min(m-1,100)-v.length-R.length);return(0,o.jsxs)(g,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,o.jsxs)(s,{children:[(0,o.jsx)(s,{bold:!0,color:l.assuranceAccent,children:v})," ".repeat(M),(0,o.jsx)(s,{color:l.dim,children:R})]}),(0,o.jsx)(s,{children:" "}),T]})}var Y={"acceptance criteria":1,scenarios:2,"acceptance criteria + exercises":3,"tests + gaps":4};function ue(e,t){let r=[],n=j(e.turns).entries.length;if(t==="design"){let c;for(let m=e.ledger.length-1;m>=0;m--){let f=e.ledger[m];if(f.kind==="banner"&&f.text.startsWith("designing: ")){c=f.text.slice(11);break}}let h=c?Y[c]:void 0;h&&r.push(`phase ${h}/4`),n>0&&r.push(`${n} item${n===1?"":"s"} this session`)}else n>0&&r.push(`${n} saved as draft${n===1?"":"s"}`);let d=e.pending?e.pending.resolution.filter(c=>!c).length:0;return d>0&&r.push(`${d} question${d===1?"":"s"} pending`),e.credits&&r.push(`${e.credits.total.toFixed(1)} credits`),{items:r}}function fe(e,t){let r=[],n=e.applied+e.committed+e.retired;r.push(`${n} applied`),r.push(`${t} to decide`);let d=[];return e.skipped>0&&d.push(`${e.skipped} skipped`),e.deferred>0&&d.push(`${e.deferred} deferred`),e.failed>0&&d.push(`${e.failed} failed`),{items:[...r,...d]}}function he(e,t){let r=["\u2191\u2193 select","\u23CE confirm"];return e.multi_select&&r.push("space toggle"),t.batchCount>1&&r.push("\u2190 \u2192 questions"),(e.allow_free_text||e.options.some(n=>n.input===!0))&&r.push("\u270E type your own"),t.canAttach&&r.push("@ attach a file or URL"),t.escBack&&r.push("esc back"),{keys:r}}function ge(e,t){let r=["\u2191\u2193 select","\u23CE confirm"];return e.some(n=>n.free)&&r.push("\u270E type your own"),t.escBack&&r.push("esc back"),{keys:r}}function be(e){let t=["\u2191\u2193 select","\u23CE confirm","1-9 verdict"];return W(e)!==null&&t.push("type = adjust"),t.push("esc \xB7 nothing to undo"),{keys:t}}export{J as a,Z as b,ne as c,V as d,F as e,W as f,ce as g,ue as h,fe as i,he as j,ge as k,be as l};
2
+ import{d as j}from"./chunk-RKXHVP2Z.js";import{a as L}from"./chunk-RRY5IXOB.js";import{a as O}from"./chunk-5Y2G4NC7.js";import{a as D}from"./chunk-YCCUBQY4.js";import{y as l}from"./chunk-SJZJ7ASF.js";import{a as E}from"./chunk-HCBYKLMW.js";import{a as g,b as s,i as I,k as B}from"./chunk-C44QQJR4.js";import{a as P}from"./chunk-6YGTRKDT.js";import{e as $}from"./chunk-UR6MHSHU.js";var H=$(P(),1);var w=$(E(),1),K=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function J(e){let t=e.replace(/…$/,"");return t&&t.charAt(0).toLowerCase()+t.slice(1)}function N(e,t){if(e.length<=t)return e;if(t<=1)return"\u2026";let r=Math.ceil((t-1)/2),n=Math.floor((t-1)/2);return`${e.slice(0,r)}\u2026${n>0?e.slice(-n):""}`}function Z({status:e,meta:t,tallies:r,keys:n,child:d,cols:c}){let{stdout:h}=B(),m=c??h?.columns??80,f=e.kind==="working"||e.kind==="child-working",[i,b]=(0,H.useState)(0);O(()=>b(a=>a+1),f?120:null);let k=K[i%K.length],u,p;switch(e.kind){case"working":u=`${k} ${e.step}${e.elapsedS!==void 0?` \xB7 ${e.elapsedS}s`:""}`,p=l.assuranceAccent;break;case"waiting":u=`\u25CF waiting on you${e.pending?` \u2014 ${e.pending} question${e.pending===1?"":"s"}`:""}`,p=l.amber;break;case"idle":u="\u25CF idle",p=l.assuranceAccent;break;case"card":u=`\u25CF card ${e.n} of ${e.m}`,p=l.amber;break;case"child-working":u=`${k} child: ${e.step}`,p=l.assuranceAccent;break;case"child-waiting":u="\u25CF child waiting on you",p=l.amber;break}let A=d?`${t.verb} \u25B8 ${d.verb}`:t.verb,S=d?.sid?t.sid?`${N(t.sid,14)} \u25B8 ${d.sid}`:d.sid:t.sid,C=t.env==="prod"?"":t.env,_=[A,S,C].filter(Boolean),v=" \xB7 ",R=u.length+v.length+_.join(v).length,T=t.subject;if(T){let a=m-R-v.length;T=a>=8?N(T,a):void 0}let M=[A,...T?[T]:[],S,C].filter(Boolean).join(v);return(0,w.jsxs)(g,{flexDirection:"column",children:[(0,w.jsx)(s,{color:l.muted,children:"\u2500".repeat(Math.max(1,m))}),(0,w.jsxs)(s,{children:[(0,w.jsx)(s,{color:p,children:u}),(0,w.jsx)(s,{color:l.dim,children:`${v}${M}`})]}),(0,w.jsx)(s,{color:l.dim,children:r.items.length>0?r.items.join(v):" "}),(0,w.jsx)(s,{color:l.muted,children:n.join(v)})]})}var y=$(P(),1);function ne({onToggleThinking:e,onCtrlC:t,explorer:r,panel:n}){let c=(0,y.useRef)(null),h=(0,y.useRef)(""),m=()=>{c.current&&clearTimeout(c.current),c.current=null,h.current=""};return(0,y.useEffect)(()=>m,[]),I((f,i)=>{if(i.ctrl&&f==="t"){e();return}if(i.ctrl&&f==="c"){t();return}if(!i.ctrl&&f.includes("")){t();return}if(!i.ctrl&&f.includes("")){e();return}if(r&&r.isOpen()){let b=()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{m(),r.onBack()},150)};if(c.current){if(i.upArrow||i.downArrow||i.return){m(),i.return?r.onEnter():r.onMove(i.upArrow?-1:1);return}if(h.current+=f,h.current==="["){b();return}let k=h.current;m();let u=/^\[([ABCD])/.exec(k);if(u){(u[1]==="A"||u[1]==="B")&&r.onMove(u[1]==="A"?-1:1);return}r.onBack();return}if(i.upArrow){r.onMove(-1);return}if(i.downArrow){r.onMove(1);return}if(i.return){r.onEnter();return}if(i.escape){h.current="",b();return}return}if(n&&n.isFocused()){let b=()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{m(),n.onBack()},150)};if(c.current){if(i.upArrow||i.downArrow||i.return||i.leftArrow||i.rightArrow){m(),i.return?n.onSelect():i.leftArrow?n.onLeft?.():i.rightArrow?n.onRight?.():n.onMove(i.upArrow?-1:1);return}if(h.current+=f,h.current==="["){b();return}let k=h.current;m();let u=/^\[([ABCD])/.exec(k);if(u){u[1]==="A"||u[1]==="B"?n.onMove(u[1]==="A"?-1:1):u[1]==="C"?n.onRight?.():n.onLeft?.();return}n.onBack();return}if(i.upArrow){n.onMove(-1);return}if(i.downArrow){n.onMove(1);return}if(i.leftArrow){n.onLeft?.();return}if(i.rightArrow){n.onRight?.();return}if(i.return){n.onSelect();return}if(i.escape){h.current="",b();return}if(/^[1-9]$/.test(f)){n.onDigit(Number(f));return}if(i.tab){n.onTab?.();return}if(f===" "&&n.isMulti()){n.onSpace();return}if(f&&!i.ctrl&&!i.meta){n.onType(f);return}return}}),null}var o=$(E(),1);function V(e){return e.kind==="REVIEW"?[{v:"approve",label:"approve",detail:"mark it reviewed and trusted"},{v:"archive",label:"archive",detail:"reject it \u2014 asks for a reason; impact shown above"},{v:"defer",label:"defer",detail:"not now \u2014 stays queued"}]:e.kind==="PAIR"?[{v:"merge",label:"merge",detail:"duplicate \u2014 fold into the older item (it stays unreviewed)"},{v:"keep_both",label:"keep both",detail:"genuinely distinct \u2014 promote both"},{v:"defer",label:"defer",detail:"not now \u2014 stays queued"}]:e.kind==="ARCHIVE"?[{v:"archive",label:"retire",detail:"hidden from now on; history is kept and it can be reverted"},{v:"skip",label:"skip",detail:"keep it \u2014 decided, never re-offered"},{v:"defer",label:"defer",detail:"not now \u2014 the plan re-offers it"}]:e.heldPayload?[{v:"approve",label:"approve update",detail:"commit the held payload \u2014 impact preview above"},{v:"skip",label:"keep current",detail:"drop the held payload (the owner's disk state stays untouched)"},{v:"defer",label:"defer",detail:"not now \u2014 stays held"}]:[{v:"approve",label:"approve",detail:e.kind==="ADD"?"commit + design it":"commit the updated version (old\u2192new redirect)"},{v:"skip",label:e.origin==="content-change"?"reject":"skip",detail:e.origin==="content-change"?"drop the staged proposal \u2014 nothing committed":"leave it as is"},{v:"defer",label:"defer",detail:"not now \u2014 the plan keeps it staged"}]}function F(e){let t=V(e);return e.viewDiff&&t.push({v:"view_diff",label:"view diff",detail:"full old \u2192 new"}),t}function W(e){return e.kind==="ARCHIVE"?null:F(e).length}var q={ADD:{color:l.green??"green"},MODIFY:{color:"yellow"},ARCHIVE:{color:l.red},REVIEW:{color:"cyan"},PAIR:{color:"magenta"}},Q=60;function ce({card:e,position:t,sel:r=0,focused:n=!1,freeText:d=null,editorIntent:c="steer"}){let{stdout:h}=B(),m=h?.columns??80,f=m<Q,i=F(e),b=W(e),k=q[e.kind],u=a=>n&&r===a?(0,o.jsx)(s,{color:l.assuranceAccent,children:"\u276F"}):" ",p=e.impact,A=p&&"stale_refs"in p&&p.stale_refs.length>0?`${e.kind==="ARCHIVE"?"retiring leaves":"approving marks"} ${p.stale_refs.length} item(s) stale`+((p.direct_refs?.length??0)>0?` \u2014 ${p.direct_refs.length} directly touched: ${p.direct_refs.join(", ")}`:""):p&&"design_children"in p?`${e.kind==="REVIEW"?"archiving drops":"merging folds"} ${p.design_children} design child(ren)`:null,S=e.provenance&&e.provenance!==e.why?e.provenance:e.origin??null,C=[{label:"why",text:e.why},...S?[{label:"from",text:S,dimmer:!0}]:[],...e.tier?[{label:"match",text:e.tier,dimmer:!0}]:[],...A?[{label:"impact",text:A}]:[]],_=Math.max(...C.map(a=>a.label.length)),v="? reconcile",R=`item ${t.n} of ${t.of}`,T=(0,o.jsxs)(g,{flexDirection:"column",children:[(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsxs)(s,{bold:!0,children:[(0,o.jsx)(s,{color:k.color,children:`[${e.kind}]`}),` ${L(e.title)}`]})}),C.map((a,x)=>(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsxs)(s,{children:[(0,o.jsx)(s,{color:l.dim,children:`${a.label.padEnd(_)} `}),(0,o.jsx)(s,{color:a.dimmer?l.dim:void 0,children:a.text})]})},`f-${x}`)),e.diffSummary?(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsx)(s,{color:l.dim,children:e.diffSummary})}):(e.diff??[]).map((a,x)=>(0,o.jsx)(g,{paddingLeft:4,children:(0,o.jsx)(s,{color:a.op==="-"?"red":"green",children:`${a.op==="-"?"\u2212":"+"} ${a.field==="criteria"?"criterion":a.field}: ${a.text}`})},`d-${x}`)),(e.citeLines??[]).map((a,x)=>(0,o.jsx)(g,{paddingLeft:2,children:(0,o.jsx)(s,{color:l.dim,children:a})},`c-${x}`)),(0,o.jsx)(s,{children:" "}),i.map((a,x)=>(0,o.jsxs)(s,{children:[u(x),` ${x+1}. ${a.label}`,(0,o.jsx)(s,{color:l.dim,children:` \u2014 ${a.detail}`})]},`o-${x}`)),b!==null||d&&c==="because"?d?(0,o.jsxs)(g,{flexDirection:"column",children:[(0,o.jsxs)(g,{children:[(0,o.jsxs)(s,{children:[(0,o.jsx)(s,{color:l.assuranceAccent,children:"\u276F"})," ",(0,o.jsx)(s,{color:l.dim,children:"\u270E "})]}),(0,o.jsx)(D,{value:d.value,onChange:d.onChange,onSubmit:d.onSubmit,onCancel:d.onCancel,placeholder:c==="because"?"why archive it?":"say what to adjust"})]}),(0,o.jsx)(s,{color:l.muted,children:c==="because"?" submits as: archive \xB7 your reason goes on the record":e.kind==="PAIR"?" submits as: defer \xB7 your note parks with the card (it re-offers)":" submits as: approve \xB7 your words steer the re-design"})]}):b!==null?(0,o.jsxs)(s,{children:[u(b)," ",(0,o.jsx)(s,{color:l.dim,children:e.kind==="PAIR"?"\u270E defer with a note \u2014 say what you noticed":"\u270E approve with changes \u2014 say what to adjust"})]}):null:null]});if(f)return(0,o.jsxs)(g,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,o.jsx)(s,{bold:!0,color:l.assuranceAccent,children:v}),(0,o.jsx)(s,{color:l.dim,children:R}),T]});let M=Math.max(2,Math.min(m-1,100)-v.length-R.length);return(0,o.jsxs)(g,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,o.jsxs)(s,{children:[(0,o.jsx)(s,{bold:!0,color:l.assuranceAccent,children:v})," ".repeat(M),(0,o.jsx)(s,{color:l.dim,children:R})]}),(0,o.jsx)(s,{children:" "}),T]})}var Y={"acceptance criteria":1,scenarios:2,"acceptance criteria + exercises":3,"tests + gaps":4};function ue(e,t){let r=[],n=j(e.turns).entries.length;if(t==="design"){let c;for(let m=e.ledger.length-1;m>=0;m--){let f=e.ledger[m];if(f.kind==="banner"&&f.text.startsWith("designing: ")){c=f.text.slice(11);break}}let h=c?Y[c]:void 0;h&&r.push(`phase ${h}/4`),n>0&&r.push(`${n} item${n===1?"":"s"} this session`)}else n>0&&r.push(`${n} saved as draft${n===1?"":"s"}`);let d=e.pending?e.pending.resolution.filter(c=>!c).length:0;return d>0&&r.push(`${d} question${d===1?"":"s"} pending`),e.credits&&r.push(`${e.credits.total.toFixed(1)} credits`),{items:r}}function fe(e,t){let r=[],n=e.applied+e.committed+e.retired;r.push(`${n} applied`),r.push(`${t} to decide`);let d=[];return e.skipped>0&&d.push(`${e.skipped} skipped`),e.deferred>0&&d.push(`${e.deferred} deferred`),e.failed>0&&d.push(`${e.failed} failed`),{items:[...r,...d]}}function he(e,t){let r=["\u2191\u2193 select","\u23CE confirm"];return e.multi_select&&r.push("space toggle"),t.batchCount>1&&r.push("\u2190 \u2192 questions"),(e.allow_free_text||e.options.some(n=>n.input===!0))&&r.push("\u270E type your own"),t.canAttach&&r.push("@ attach a file or URL"),t.escBack&&r.push("esc back"),{keys:r}}function ge(e,t){let r=["\u2191\u2193 select","\u23CE confirm"];return e.some(n=>n.free)&&r.push("\u270E type your own"),t.escBack&&r.push("esc back"),{keys:r}}function be(e){let t=["\u2191\u2193 select","\u23CE confirm","1-9 verdict"];return W(e)!==null&&t.push("type = adjust"),t.push("esc \xB7 nothing to undo"),{keys:t}}export{J as a,Z as b,ne as c,V as d,F as e,W as f,ce as g,ue as h,fe as i,he as j,ge as k,be as l};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as wr}from"./chunk-NJ4BXZBX.js";import{a as br}from"./chunk-Q4YYAN6E.js";import{a as mr,b as yr}from"./chunk-EVFFDODK.js";import{a as gr}from"./chunk-3VAU3PNU.js";import{a as hr}from"./chunk-WVHMPIDQ.js";import{a as lr,d as pr}from"./chunk-BB2W35TW.js";import{c as ur,d as fr}from"./chunk-V4B5QA3U.js";import{a as ir,g as xt,h as ar,n as dr,p as cr}from"./chunk-7N6OCHPC.js";import{e as ct,f as jt,g as Tt,h as Le}from"./chunk-N6J2YUDC.js";import{A as tr,B as qt,C as te,D as it,E as fe,F as nr,G as ne,H as _e,I as at,J as rr,K as Y,L as Fe,M as dt,N as Re,O as sr,P as or,S as Be,a as Dn,b as Mn,c as Ae,d as Pe,e as le,f as st,g as Gn,h as Vn,i as pe,j as Kn,k as qe,l as je,m as Yn,n as ot,o as ue,p as zn,q as Qn,r as Zn,s as Xn,t as At,u as Pt,v as X,w as Te,x as er,y as Nt,z as xe}from"./chunk-H2VMZL7J.js";import{b as Ln,d as Bn,g as Ct,h as K}from"./chunk-T2ONUKTL.js";import{a as R,b as Hn,d as ee,e as Ne,h as Jn,i as Wn,k as Un}from"./chunk-YLQHY4A7.js";import{a as Tn,b as xn,e as Fn}from"./chunk-WJR2FU7S.js";import{b as sn,f as on,h as an,k as dn,l as cn}from"./chunk-RGRFL7XG.js";import{b as Ot,d as ce}from"./chunk-VVOKM2VO.js";import{A as qn,n as Sn,o as En,p as On,q as Cn,r as An,s as Pn,t as Nn,x as tt,y as nt,z as rt}from"./chunk-IICT4VOU.js";import{a as jn}from"./chunk-CH273NAE.js";import{b as ve}from"./chunk-BKM2LWU2.js";import{B as oe,C as vn,D as $n,F as $e,G as Xe,J as kn,K as Ce,O as _n,P as et,U as Rn,W as In,X as ke,b as rn,c as de,f as Et,h as pn,l as un,m as fn,o as Oe,p as O,q as hn,t as gn,v as mn,x as yn,y as bn,z as wn}from"./chunk-RDHWNSDP.js";import{d as ln,f as Qe,g as Ze}from"./chunk-XLSOQLVT.js";import{existsSync as Ue,readdirSync as os,readFileSync as is,realpathSync as Mo,statSync as Ho,writeFileSync as Go}from"fs";import{basename as Rt,join as Ke,relative as Vo,resolve as tn}from"path";import{randomBytes as _s}from"crypto";var vr=8,De=()=>Un(_s(8).toString("hex")),$r=(e,t)=>e!==null&&Buffer.from(e).equals(Buffer.from(t)),Rs=[["P1 exclusive create",async e=>{for(let t=1;t<=2;t++){let n=De(),r=Buffer.from(`probe ${t} first`);if(await e.putIfAbsent(n,r)!=="created")return"a fresh key was reported as existing";if(await e.putIfAbsent(n,Buffer.from(`probe ${t} second`))!=="exists")return"the second write to one key was not refused";if(!$r(await e.get(n),r))return"the second write replaced the first"}return null}],["P2 contention",async e=>{let t=De(),r=(await Promise.all(Array.from({length:vr},(o,i)=>e.putIfAbsent(t,Buffer.from(`contender ${i}`))))).filter(o=>o==="created").length;return r===1?null:`${r} of ${vr} concurrent writers were told "created"`}],["P3 read-after-write",async e=>{let t=De(),n=Buffer.from("visible");return await e.putIfAbsent(t,n),await e.head(t)?$r(await e.get(t),n)?(await e.list(t)).includes(t)?null:"list does not show a key just created":"get does not return the bytes just created":"head does not see a key just created"}],["P4 definitive absence",async e=>await e.head(De())?"a never-written key was reported present":null]];async function lt(e){if(e.probe){let r=await e.probe();return{tier:Math.max(r.tier,e.ceilingTier),detail:r.detail}}let t=1,n="all probes passed";for(let[r,o]of Rs){let i;try{i=await o(e)}catch(s){if(s instanceof R){if(!(s.code==="SYNC_LOCATION_REFUSED_WRITE"&&r.startsWith("P1")&&await kr(e)))throw s;n=`${r}: ${s.message}`,t=3;break}n=`${r}: ${s instanceof Error?s.message:String(s)}`,t=r.startsWith("P1")&&await kr(e)?3:2;break}if(i!==null){n=`${r}: ${i}`,t=2;break}}return{tier:Math.max(t,e.ceilingTier),detail:n}}async function kr(e){try{return!await e.head(De())}catch(t){if(t instanceof R)throw t;return!1}}import{existsSync as Is,readFileSync as Ir}from"fs";import{join as Ss}from"path";async function Ft(e,t,n,r){let i=le(e).entries[n];if(!i)throw new Error(`no sync state for ${n} \u2014 run kane-cli context sync add ${n} <descriptor> first`);if(i.tier!==1)throw new R("SYNC_READ_ONLY",`${n} is a tier ${i.tier} location: it can be cloned and pulled, never pushed`,"push to a location whose probe reached tier 1, or pull from this one");let s=await qe(e,t,i.witness);switch(s.kind){case"empty-storage":case"ahead":case"up-to-date":break;case"behind":case"empty-local":throw new R("SYNC_BEHIND",`${n} holds ${s.storage.seq} records, this store ${s.local?.seq??0}: it has records this store has not seen`,`kane-cli context pull ${n}`);case"diverged":throw new R("SYNC_DIVERGED",`you and ${n} both added work after position ${s.at-1}; nothing was pushed`,`run kane-cli context pull ${n} --rebase to save your local work, take the team version from ${n}, and then reapply yours`);case"foreign-lineage":throw new R("SYNC_FOREIGN_LINEAGE",`${n} holds a different history (its first record is not this store's)`,`to work on it, clone it: kane-cli context clone <descriptor of ${n}> <dir>; to share this store, add an empty location`)}let d=s.storage,c=wn(e),a;try{mn(e),a=Es(e,d)}catch(F){throw F instanceof gn?new R("SYNC_REBASE_PENDING",`${F.message.split(";")[0]}; nothing was pushed`,F.remedy):F}finally{c()}let l=a.map(F=>Os(e,F)),g=0,p=0,f=0,u=0,y=d,b=null,h=null,m=t.beginTransaction?await t.beginTransaction():void 0,w=m?{...t,head:m.head,get:m.get,list:t.list.bind(t),putIfAbsent:t.putIfAbsent.bind(t)}:t,v=m?m.stageIfAbsent.bind(m):t.putIfAbsent.bind(t),x=[],ae=F=>m?x.push(F):r(F);try{let F=new Set;for(let A of l){for(let $ of A.blobs)if(await v($.key,$.bytes)!=="exists")p++,F.add($.key);else if(!F.has($.key)){let M=await w.get($.key);if(M===null||Ot(Buffer.from(M))!==$.fp){h=new R("SYNC_OBJECT_CORRUPT",`the blob ${$.fp} ${n} already holds does not hash to its name (named by record ${A.seq}); the record was not pushed`,"the storage object needs a human look before anything more is pushed to it");break}F.add($.key)}if(h)break;A.proposal&&await v(A.proposal.key,A.proposal.bytes)!=="exists"&&f++;let Q=Ne(A.seq);if(await v(Q,A.raw)!=="exists")g++;else if((await pe(w,A.seq)).hash===A.hash)ae(`position ${A.seq} is already on ${n}`),u++;else{b=A.seq;break}y={seq:A.seq,hash:A.hash}}if(m||await Rr(t,y,d,n),y&&!await w.head(ee)){let A=await pe(w,1),Q={layout:1,canonicalizer:"v1",genesis_hash:A.hash};await v(ee,Buffer.from(JSON.stringify(Q)+`
2
+ import{a as wr}from"./chunk-NJ4BXZBX.js";import{a as br}from"./chunk-Q4YYAN6E.js";import{a as mr,b as yr}from"./chunk-EVFFDODK.js";import{a as gr}from"./chunk-3VAU3PNU.js";import{a as hr}from"./chunk-WVHMPIDQ.js";import{a as lr,d as pr}from"./chunk-BB2W35TW.js";import{c as ur,d as fr}from"./chunk-V4B5QA3U.js";import{a as ir,g as xt,h as ar,n as dr,p as cr}from"./chunk-7N6OCHPC.js";import{e as ct,f as jt,g as Tt,h as Le}from"./chunk-WRGPMDDE.js";import{A as tr,B as qt,C as te,D as it,E as fe,F as nr,G as ne,H as _e,I as at,J as rr,K as Y,L as Fe,M as dt,N as Re,O as sr,P as or,S as Be,a as Dn,b as Mn,c as Ae,d as Pe,e as le,f as st,g as Gn,h as Vn,i as pe,j as Kn,k as qe,l as je,m as Yn,n as ot,o as ue,p as zn,q as Qn,r as Zn,s as Xn,t as At,u as Pt,v as X,w as Te,x as er,y as Nt,z as xe}from"./chunk-5D6YMG63.js";import{b as Ln,d as Bn,g as Ct,h as K}from"./chunk-T2ONUKTL.js";import{a as R,b as Hn,d as ee,e as Ne,h as Jn,i as Wn,k as Un}from"./chunk-YLQHY4A7.js";import{a as Tn,b as xn,e as Fn}from"./chunk-WJR2FU7S.js";import{b as sn,f as on,h as an,k as dn,l as cn}from"./chunk-RGRFL7XG.js";import{b as Ot,d as ce}from"./chunk-VVOKM2VO.js";import{A as qn,n as Sn,o as En,p as On,q as Cn,r as An,s as Pn,t as Nn,x as tt,y as nt,z as rt}from"./chunk-IICT4VOU.js";import{a as jn}from"./chunk-CH273NAE.js";import{b as ve}from"./chunk-BKM2LWU2.js";import{B as oe,C as vn,D as $n,F as $e,G as Xe,J as kn,K as Ce,O as _n,P as et,U as Rn,W as In,X as ke,b as rn,c as de,f as Et,h as pn,l as un,m as fn,o as Oe,p as O,q as hn,t as gn,v as mn,x as yn,y as bn,z as wn}from"./chunk-RDHWNSDP.js";import{d as ln,f as Qe,g as Ze}from"./chunk-XLSOQLVT.js";import{existsSync as Ue,readdirSync as os,readFileSync as is,realpathSync as Mo,statSync as Ho,writeFileSync as Go}from"fs";import{basename as Rt,join as Ke,relative as Vo,resolve as tn}from"path";import{randomBytes as _s}from"crypto";var vr=8,De=()=>Un(_s(8).toString("hex")),$r=(e,t)=>e!==null&&Buffer.from(e).equals(Buffer.from(t)),Rs=[["P1 exclusive create",async e=>{for(let t=1;t<=2;t++){let n=De(),r=Buffer.from(`probe ${t} first`);if(await e.putIfAbsent(n,r)!=="created")return"a fresh key was reported as existing";if(await e.putIfAbsent(n,Buffer.from(`probe ${t} second`))!=="exists")return"the second write to one key was not refused";if(!$r(await e.get(n),r))return"the second write replaced the first"}return null}],["P2 contention",async e=>{let t=De(),r=(await Promise.all(Array.from({length:vr},(o,i)=>e.putIfAbsent(t,Buffer.from(`contender ${i}`))))).filter(o=>o==="created").length;return r===1?null:`${r} of ${vr} concurrent writers were told "created"`}],["P3 read-after-write",async e=>{let t=De(),n=Buffer.from("visible");return await e.putIfAbsent(t,n),await e.head(t)?$r(await e.get(t),n)?(await e.list(t)).includes(t)?null:"list does not show a key just created":"get does not return the bytes just created":"head does not see a key just created"}],["P4 definitive absence",async e=>await e.head(De())?"a never-written key was reported present":null]];async function lt(e){if(e.probe){let r=await e.probe();return{tier:Math.max(r.tier,e.ceilingTier),detail:r.detail}}let t=1,n="all probes passed";for(let[r,o]of Rs){let i;try{i=await o(e)}catch(s){if(s instanceof R){if(!(s.code==="SYNC_LOCATION_REFUSED_WRITE"&&r.startsWith("P1")&&await kr(e)))throw s;n=`${r}: ${s.message}`,t=3;break}n=`${r}: ${s instanceof Error?s.message:String(s)}`,t=r.startsWith("P1")&&await kr(e)?3:2;break}if(i!==null){n=`${r}: ${i}`,t=2;break}}return{tier:Math.max(t,e.ceilingTier),detail:n}}async function kr(e){try{return!await e.head(De())}catch(t){if(t instanceof R)throw t;return!1}}import{existsSync as Is,readFileSync as Ir}from"fs";import{join as Ss}from"path";async function Ft(e,t,n,r){let i=le(e).entries[n];if(!i)throw new Error(`no sync state for ${n} \u2014 run kane-cli context sync add ${n} <descriptor> first`);if(i.tier!==1)throw new R("SYNC_READ_ONLY",`${n} is a tier ${i.tier} location: it can be cloned and pulled, never pushed`,"push to a location whose probe reached tier 1, or pull from this one");let s=await qe(e,t,i.witness);switch(s.kind){case"empty-storage":case"ahead":case"up-to-date":break;case"behind":case"empty-local":throw new R("SYNC_BEHIND",`${n} holds ${s.storage.seq} records, this store ${s.local?.seq??0}: it has records this store has not seen`,`kane-cli context pull ${n}`);case"diverged":throw new R("SYNC_DIVERGED",`you and ${n} both added work after position ${s.at-1}; nothing was pushed`,`run kane-cli context pull ${n} --rebase to save your local work, take the team version from ${n}, and then reapply yours`);case"foreign-lineage":throw new R("SYNC_FOREIGN_LINEAGE",`${n} holds a different history (its first record is not this store's)`,`to work on it, clone it: kane-cli context clone <descriptor of ${n}> <dir>; to share this store, add an empty location`)}let d=s.storage,c=wn(e),a;try{mn(e),a=Es(e,d)}catch(F){throw F instanceof gn?new R("SYNC_REBASE_PENDING",`${F.message.split(";")[0]}; nothing was pushed`,F.remedy):F}finally{c()}let l=a.map(F=>Os(e,F)),g=0,p=0,f=0,u=0,y=d,b=null,h=null,m=t.beginTransaction?await t.beginTransaction():void 0,w=m?{...t,head:m.head,get:m.get,list:t.list.bind(t),putIfAbsent:t.putIfAbsent.bind(t)}:t,v=m?m.stageIfAbsent.bind(m):t.putIfAbsent.bind(t),x=[],ae=F=>m?x.push(F):r(F);try{let F=new Set;for(let A of l){for(let $ of A.blobs)if(await v($.key,$.bytes)!=="exists")p++,F.add($.key);else if(!F.has($.key)){let M=await w.get($.key);if(M===null||Ot(Buffer.from(M))!==$.fp){h=new R("SYNC_OBJECT_CORRUPT",`the blob ${$.fp} ${n} already holds does not hash to its name (named by record ${A.seq}); the record was not pushed`,"the storage object needs a human look before anything more is pushed to it");break}F.add($.key)}if(h)break;A.proposal&&await v(A.proposal.key,A.proposal.bytes)!=="exists"&&f++;let Q=Ne(A.seq);if(await v(Q,A.raw)!=="exists")g++;else if((await pe(w,A.seq)).hash===A.hash)ae(`position ${A.seq} is already on ${n}`),u++;else{b=A.seq;break}y={seq:A.seq,hash:A.hash}}if(m||await Rr(t,y,d,n),y&&!await w.head(ee)){let A=await pe(w,1),Q={layout:1,canonicalizer:"v1",genesis_hash:A.hash};await v(ee,Buffer.from(JSON.stringify(Q)+`
3
3
  `,"utf8"))!=="exists"&&ae(`wrote ${ee} on ${n}`)}if(m){if(y){let M=await w.get(ee),T=await pe(w,1),be={};try{let Z=JSON.parse(Buffer.from(M??[]).toString("utf8"));Z&&typeof Z=="object"&&!Array.isArray(Z)&&(be=Z)}catch{}if(be.layout!==1||be.canonicalizer!=="v1"||be.genesis_hash!==T.hash)throw new R("SYNC_OBJECT_CORRUPT",`${ee} does not describe this context's verified genesis and format.`,"Ask the location owner to inspect the metadata before publishing.")}if(h)throw h;if(b!==null)throw new R("SYNC_POSITION_TAKEN",`position ${b} on ${n} was taken by another writer; this batch was not published`,_r(n,b));let A=await m.commit(),Q=new Set(A.created),$=l.filter(M=>Q.has(Ne(M.seq))).length;u+=g-$,g=$,p=new Set(l.flatMap(M=>M.blobs.map(T=>T.key)).filter(M=>Q.has(M))).size,f=new Set(l.flatMap(M=>M.proposal?[M.proposal.key]:[]).filter(M=>Q.has(M))).size}m&&await Rr(t,y,d,n);for(let A of x)r(A);let U="";if(y)try{Yn(e,n,y,{forwardOnly:!0})}catch(A){if(b===null||!(A instanceof O))throw A;U=" (the witness was not saved; the next pull records it)"}if(h)throw h;if(b!==null)throw new R("SYNC_POSITION_TAKEN",`position ${b} on ${n} was taken by another writer while this push ran; this store's history through position ${y?.seq??0} is confirmed on ${n}${U}`,_r(n,b))}finally{await m?.abort()}return{pushed:g,from:d?.seq??0,to:y?.seq??0,blobs:p,proposals:f,alreadyThere:u}}function _r(e,t){return t===1?`${e} holds a different history: to work on it, clone it with kane-cli context clone <descriptor of ${e}> <dir>; to share this store, add an empty location`:`kane-cli context pull ${e} --rebase`}async function Rr(e,t,n,r){if(!t||t.seq<=(n?.seq??0))return;let o=await pe(e,t.seq);if(o.hash!==t.hash)throw new R("SYNC_OBJECT_CORRUPT",`${r} answered "created" for position ${t.seq} but serves a record hashing ${o.hash}, not ${t.hash}`,"The location needs inspection before publishing more context.")}function Es(e,t){let{records:n,hashes:r}=Ce(e,t?.seq??0,t?.hash??null);return n.map((o,i)=>{let s=r[i],d=Ir(Ss(e,"commits",`${String(o.seq).padStart(6,"0")}-${s.slice(7,19)}.json`));if(oe(JSON.parse(d.toString("utf8")))!==s)throw new Error(`record ${o.seq} changed on disk while it was being read \u2014 run kane-cli context fsck`);return{rec:o,hash:s,raw:d}})}function Os(e,{rec:t,hash:n,raw:r}){{let o=Dn(t),i=o.blobs.map(s=>{let d=ce(e,s);if(d===null)throw new R("SYNC_CLOSURE_MISSING",`record ${t.seq} names blob ${s}, which this store does not hold`,"restore the blob from a copy of this store, or run kane-cli context fsck");if(Ot(d)!==s)throw new R("SYNC_LOCAL_BLOB_CORRUPT",`record ${t.seq} names blob ${s}, but the local file does not hash to that: it is torn`,"restore the blob from a copy of this store, or run kane-cli context fsck");return{key:Jn(s),fp:s,bytes:d}});return{seq:t.seq,hash:n,raw:new Uint8Array(r),blobs:i,proposal:Cs(e,o.proposalId)}}}function Cs(e,t){if(t===null)return null;let n=pn(e,t);if(!Is(n))return null;let r=Ir(n);return{key:Wn(t,Mn(r.toString("utf8"))),bytes:r}}import{existsSync as As,readdirSync as Ps,readFileSync as Sr}from"fs";import{basename as Ns,join as Lt}from"path";var qs=/^\d{6}-[0-9a-f]{12}\.json$/;function Bt(e,t){let n=Lt(e,"commits"),r=As(n)?Ps(n).filter(s=>qs.test(s)).sort():[],o=t.hash,i=t.seq;return r.map(s=>{let d;try{d=JSON.parse(Sr(Lt(n,s),"utf8"))}catch(a){throw new O(`backup record ${s} is not JSON: ${String(a)}`)}if(i+=1,d.seq!==i||d.prev_hash!==o)throw new O(`backup record ${s} does not continue the chain at ${i} from ${String(o)}`);let c=oe(d);if(!c.slice(7).startsWith(s.slice(7,19)))throw new O(`backup record ${s} does not match its name`);return o=c,{seq:i,hash:c,body:d}})}function pt(e,t){let n=JSON.parse(Sr(Lt(t,"base-witness.json"),"utf8")),r=$e(e),o=r.records.slice(0,n.base.seq),i=Bt(t,n.base),s=[...o,...i.map(f=>f.body)],d=[...r.hashes.slice(0,n.base.seq),...i.map(f=>f.hash)],c=new Map;for(let f of s)for(let u of f.nodes)c.set(u.cid,{label:u.label,content:u.content});let a=Rn();In(e,a,s,d,{writeNodeFiles:!1});let l=qn(e,a,c),g=new Map(i.map(f=>[f.seq,f])),p=f=>l.displayNameOf(f)??f.slice(0,19);return{backupDir:t,backupId:Ns(t),from:n.from,base:n.base,index:a,graph:l,records:i,chain:s,recordAt:f=>g.get(f),resolveName:f=>l.resolve(f)?.cid,nameOf:f=>l.displayNameOf(f)??void 0,displayNameFor:f=>{let u=Dt(t,f),y=Object.keys(f.source_head_moves),b=u==="revert"?String(js(t,f)??""):u==="names"?(f.names??[]).map(h=>h.slug).join(", "):y.length>0?y.join(", "):f.nodes.length>0?[...new Set(f.nodes.map(h=>p(h.cid)))].join(", "):(f.executions?.length??0)>0?[...new Set(f.executions.map(h=>p(h.about)))].join(", "):f.review.length>0?[...new Set(f.review.map(h=>p(h.id)))].join(", "):f.supersessions.length>0?[...new Set(f.supersessions.map(h=>h.kind==="node"?p(h.old):h.ecid.slice(0,19)))].join(", "):y.join(", ");return b?`${u} ${b}`:u}}}function js(e,t){try{let r=Oe(e,oe(t))?.args?.seq;return typeof r=="number"?r:void 0}catch{return}}function Dt(e,t){let n=null;try{n=Oe(e,oe(t))}catch{n=null}if(n)return n.verb;if(t.intent_verb)return t.intent_verb;let r=Object.entries(t.source_head_moves);return(t.executions?.length??0)>0?"execution":t.design_of?"design":t.proposal_id!=null?"extract":t.conv?t.conv.turn===0?"conv-mint":"conv-turn":r.length===1&&r[0][1]===null&&t.supersessions.some(o=>o.kind==="node"&&o.new===null)?"retire":r.length===1&&typeof r[0][1]=="string"&&t.nodes.some(o=>o.label==="source")?"ingest":t.review.some(o=>o.resolution==="reset")||t.supersessions.some(o=>o.kind==="node"&&o.new===o.old||o.kind==="edge"&&o.revoke)?"revert":t.nodes.length===0&&t.edges.length===0&&t.supersessions.length===1&&t.supersessions[0].kind==="node"&&t.supersessions[0].new===null?"archive":t.nodes.length===0&&t.edges.length===0&&t.review.length===0&&(t.names?.length??0)>0?"names":t.nodes.length===0&&t.edges.length===0&&t.supersessions.length===0&&t.review.length>0?"review":"unknown"}import{existsSync as Er,readdirSync as Ts,readFileSync as Mt}from"fs";import{isAbsolute as xs,join as ut,normalize as Fs,relative as Ls,sep as Bs}from"path";var Ds=e=>e===""||xs(e)||e.includes("\\")||Fs(e).split(Bs).some(t=>t==="..")||e.startsWith("./")||e.includes("\0");function He(e){let t=ut(e,"manifest.json");if(!Er(t))throw new O(`backup ${e} has no manifest.json \u2014 it was never completed; kane-cli context sync doctor`);let n;try{n=JSON.parse(Mt(t,"utf8"))}catch(s){throw new O(`backup manifest ${t} is not JSON: ${s instanceof Error?s.message:String(s)}`)}if(!Array.isArray(n))throw new O(`backup manifest ${t} is not a list`);let r=new Set,o=[];for(let s of n){let d=typeof s?.name=="string"?s.name:"";if(Ds(d))throw new O(`backup manifest names an unsafe path ${JSON.stringify(s?.name)} \u2014 the backup is not trusted`);let c=ut(e,d);if(!Er(c))throw new O(`backup file ${d} is missing from ${e}`);let a=Mt(c);if("sha256:"+rn(a)!==s.hash)throw new O(`backup file ${d} does not match its manifest hash \u2014 the backup was changed after it was written`);if(d.startsWith("commits/"))try{r.add(oe(JSON.parse(a.toString("utf8"))))}catch(l){throw new O(`backup record ${d} is not a record: ${l instanceof Error?l.message:String(l)}`)}d.startsWith("intents/")&&o.push(d)}let i=new Set(n.map(s=>s.name));for(let s of Or(e)){let d=Ls(e,s);if(d!=="manifest.json"&&!i.has(d))throw new O(`backup ${e} holds ${d}, which its manifest does not name \u2014 the backup was changed after it was written`)}for(let s of o){let d;try{d=JSON.parse(Mt(ut(e,s),"utf8"))}catch(a){throw new O(`backup envelope ${s} is not JSON: ${a instanceof Error?a.message:String(a)}`)}let c=un(d);if(c!==null)throw new O(`backup envelope ${s} is not a valid intent: ${c}`);if(typeof d.born?.hash!="string"||!r.has(d.born.hash))throw new O(`backup envelope ${s} was born from a record the backup does not hold`)}}function Or(e){let t=[];for(let n of Ts(e,{withFileTypes:!0})){let r=ut(e,n.name);n.isDirectory()?t.push(...Or(r)):t.push(r)}return t}import{basename as lo,join as po}from"path";import{existsSync as uo,readFileSync as fo}from"fs";var G=class extends Error{},B=(e,t)=>({kind:"apply",inputs:e,...t&&t.length>0?{aliases:t}:{}}),J=e=>({kind:"noop",reason:e}),Ht=e=>({kind:"dedupe",as:e}),k=(e,t,n,r,o={})=>({kind:"hold",hold:{kind:e,mine:t,theirs:n,answers:r,detail:o}}),Cr=(e,t)=>{let n=ft(t.label,t.content);return e.graph.byLabel(t.label).filter(r=>!e.graph.superseded.has(r.cid)&&ft(t.label,r.content)===n).map(r=>r.cid)},re=e=>e?e.slice(0,19):"none",H=(e,t)=>e.maps.cid.rewrite(t);function I(e,t,n){if(typeof t!="string")throw new G(`${n} was not pinned`);let r=H(e,t);if(!e.graph.hasNode(r))throw new G(`${n} ${_(e,t)} has no counterpart on ${e.location}`);return r}var j=(e,t)=>e.graph.tipOf(t),Gt=(e,t)=>e.graph.superseded.has(e.graph.tipOf(t)),_=(e,t)=>e.fold.nameOf(t)??re(t),S=(e,t)=>e.graph.displayNameOf(t)??re(t);function Vt(e,t,n,r){let o=r==="fold"?e.fold.graph:e.graph,i=o.displayNameOf(t);if(i!==null&&i!==n)return i;let s=o.tipOf(t);for(let[a,l]of o.heads)if(l===t||l===s)return a;let d=o.getNode(t);if(d?.label==="source"&&typeof d.content.source_id=="string")return d.content.source_id;let c=d?.content.title??d?.content.text??d?.content.statement;return d&&typeof c=="string"&&c!==""?`${d.label} "${z(c,32)}"`:re(t)}var L=e=>e.created_by?.by?.id??e.review[0]?.by.id??e.supersessions[0]?.by.id??e.names?.[0]?.by.id??"someone",P=e=>e.ts;function z(e,t=48){let n=typeof e=="string"?e:JSON.stringify(e);return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function he(e,t,n,r){return`${[...new Set([...Object.keys(e),...Object.keys(t)])].filter(s=>s!=="derived"&&JSON.stringify(e[s])!==JSON.stringify(t[s])).map(s=>`${s} "${z(e[s]??"")}" \u2192 "${z(t[s]??"")}"`).join(", ")||"no field changed"} by ${n} at ${r}`}function ie(e,t){for(let n of e.theirs)for(let r of n.supersessions)if(r.kind==="node"&&r.old===t)return{rec:n,next:r.new}}function Jt(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let[i,s]of e.graph.superseded)typeof s=="string"&&n.has(s)&&!n.has(i)&&(n.add(i),o=!0)}let r=[];for(let o of e.theirs)for(let i of o.review)n.has(i.id)&&i.resolution!=="pending"&&r.push({rec:o,resolution:i.resolution});return r}var Ms=new Set(Object.values(Ze).filter(e=>e!==Ze.DERIVES&&e!==Ze.ANNOTATES));function Wt(e,t){let n=new Set,r=[],o=[t,e.graph.tipOf(t)];for(;o.length>0;){let i=o.pop();if(!n.has(i)){n.add(i);for(let s of e.graph.edgesInto(i))!Ms.has(s.type)||e.graph.superseded.has(s.src)||(!(s.src in e.fold.index.nodeLabel)&&!r.some(d=>d.cid===s.src)&&r.push({cid:s.src,label:e.graph.nodeLabel.get(s.src)??"node"}),o.push(s.src))}}return r}function Ut(e){let t=new Map;for(let n of e)t.set(n.label,(t.get(n.label)??0)+1);return[...t].map(([n,r])=>`${r} ${n}${r===1?"":"s"}`).join(", ")}function ht(e,t,n){if(!e.theirs.some(o=>o.edges.some(i=>i.type===t&&i.src===n)))return;let r=e.graph.edgesFrom(n).find(o=>o.type===t);return r?{live:r.dst}:void 0}function Ie(e,t){let n=t.event_ids??[],r=n.filter(i=>i in e.index.eventDigests);return n.length===0||r.length===0?void 0:r.every(i=>{let s=n.indexOf(i),d=t.event_digests?.[s];return d!==void 0&&d!==""&&e.index.eventDigests[i]===d})&&r.length===n.length?J("already applied: every event id is in the chain with the same intent"):k("ambiguous",`committed ${n.length} event id${n.length===1?"":"s"}`,`${r.length} of them already in the shared chain under another intent`,["keep-theirs"],{event_ids:n})}function Hs(e){return String(e??"").toLowerCase().trim().replace(/\s+/g," ")}function ft(e,t){let n=t.question;return`${e}\0${Hs(t.title??t.text??t.statement??n?.header??t.source_id??"")}`}function Ar(e,t){let n=[],r=new Set;for(let o of e.nodes){let i=ft(o.label,o.content),s=t.nodes.find(d=>!r.has(d.cid)&&ft(d.label,d.content)===i);s&&(r.add(s.cid),n.push([o.cid,s.cid]))}for(let o of e.nodes){if(n.some(([s])=>s===o.cid))continue;let i=t.nodes.find(s=>!r.has(s.cid)&&s.label===o.label);i&&(r.add(i.cid),n.push([o.cid,i.cid]))}return n}function Pr(e,t){let n=[],r=new Set;for(let o of t.names??[]){if(!tt.test(o.slug))continue;let i=t.nodes.find(d=>d.cid===o.cid);if(!i||e.graph.nameOf.has(H(e,o.cid)))continue;let s=nt(i.label,d=>r.has(d),e.graph.names.keys());s!==null&&(r.add(s),s!==o.slug&&n.push({from:o.slug,to:s}))}return n}function Nr(e,t,n){let r=[];for(let o of e.names??[]){let i=n.find(([d])=>d===o.cid)?.[1],s=t.names?.find(d=>d.cid===i);s&&s.slug!==o.slug&&r.push({from:o.slug,to:s.slug})}return r}function qr(e,t,n){let r=e===void 0?void 0:e.split(`
4
4
  `).map(s=>{let d=/^(##\s.*?)\s@verifies\s+(.+?)\s*$/.exec(s);if(d)return`${d[1]} @verifies ${d[2].split(",").map(l=>l.trim()).filter(Boolean).map(n).join(", ")}`;let c=/^(\s*)@import\s+(\S+)\s*$/.exec(s);if(c)return`${c[1]}@import ${n(c[2])}`;let a=/^## Import: (\S+)\s*$/.exec(s);return a?`## Import: ${n(a[1])}`:s}).join(`
5
5
  `),o=!1,i=t===void 0?void 0:t.split(`
@@ -1,9 +1,9 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as Me,h as $e}from"./chunk-AACQE24F.js";import{b as H,c as C,d as K,e as Y}from"./chunk-JW7M3ENB.js";import{b as _,c as B,d as Ae,f as z,g as U}from"./chunk-5GUD3CIH.js";import{c as Ve,d as Be}from"./chunk-WJR2FU7S.js";import{a as A,b as D,d as Pe}from"./chunk-EHN5HTUD.js";import{h as j,k as je,m as Oe,o as Fe}from"./chunk-RGRFL7XG.js";import{d as Te}from"./chunk-VVOKM2VO.js";import{a as N,c as Se,d as Ee,e as Re,f as V}from"./chunk-YFQGOOF7.js";import{z as O}from"./chunk-IICT4VOU.js";import{a as Ne}from"./chunk-CH273NAE.js";import{b as x,c as h}from"./chunk-VZ7KXRXB.js";import{a as De,b as Ce,c as Le}from"./chunk-X3YTLBZR.js";import{a as xe,b as Ie}from"./chunk-P7PDRCQR.js";import{a as ke}from"./chunk-MI6UFDRC.js";function S(e){if(e===null)return"broken";let t=Math.floor(e/100);return t===1?"passed":t===7?"failed":t===2?"skipped":"broken"}var I={failed:3,broken:2,passed:1,skipped:0};function q(e){let t="skipped";for(let r of e)I[r]>I[t]&&(t=r);return t}import{createHash as ft}from"crypto";import{basename as gt}from"path";function W(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return t.length>0?t:"session"}function G(e){return ft("sha256").update(e).digest("hex").slice(0,8)}function J(e){let t=gt(e).replace(/_test\.md$/i,"").replace(/\.md$/i,"");return`${W(t)}-${G(e)}`}function X(e,t){return`${W(e)}-${G(t)}`}function Z(e){let t=e?.trim();return t||void 0}function ze(e=process.env){let t=Z(e.TEST_INSTANCE_ID),r=Z(e.JOB_ID),n=Z(e.TASK_ID);return{...t?{testInstanceId:t}:{},...r?{jobId:r}:{},...n?{taskId:n}:{}}}function Q(e,t=process.env){let r=ze(t),n={...r.testInstanceId?{hyper_test_instance_id:r.testInstanceId}:{},...r.jobId?{hyper_job_id:r.jobId}:{},...r.taskId?{hyper_task_id:r.taskId}:{},...e},i={};for(let[o,s]of Object.entries(n))typeof s=="string"&&s.length>0&&(i[o]=s);return i}function _t(e,t){return{pack_test_dir:e,ordinal_offset:t}}import{promises as w}from"fs";import{join as y}from"path";function ee(e){let t={evidence:"0.1",run_id:e.execution_id,status:"running",title:e.title,started:e.started,environment:{producer:{name:"kane-cli",version:e.producerVersion},...e.surfaces?{surfaces:e.surfaces}:{},run_kind:e.run_kind,origin:e.origin,pid:e.pid},...e.credits!==void 0?{metrics:{credits:{value:e.credits,type:"count"}}}:{}};return h(t,{lineWidth:-1})}async function te(e,t,r,n=process.cwd(),i){let o=i??_(e.execution_id,n),s=y(o,"tests",t);return await w.mkdir(y(o,"coverage"),{recursive:!0}),await w.writeFile(y(o,"coverage",".keep"),""),await w.mkdir(s,{recursive:!0}),await w.writeFile(y(o,"run.yaml"),ee(e)),r&&await w.writeFile(y(s,r.path),r.content),o}async function vt(e,t=process.cwd()){let r=_(e.execution_id,t);await w.mkdir(y(r,"coverage"),{recursive:!0}),await w.writeFile(y(r,"coverage",".keep"),"");let n=x(ee(e));return n.environment&&delete n.environment.run_kind,await w.writeFile(y(r,"run.yaml"),h(n,{lineWidth:-1})),r}async function ht(e,t=process.cwd()){return D(_(e,t),new Date().toISOString())}async function re(e,t=process.cwd()){await w.rm(_(e,t),{recursive:!0,force:!0})}import{promises as ne}from"fs";import{join as ie}from"path";function F(e){let t={evidence:"0.1",test:e.testId,status:e.status,...e.durationMs!==void 0?{duration_ms:e.durationMs}:{},...e.attempts&&e.attempts.length?{attempts:e.attempts}:{},...e.flaky!==void 0?{flaky:e.flaky}:{},...e.adaptiveHeal?{adaptive_heal:e.adaptiveHeal}:{},...e.definitionPath?{definition:{path:e.definitionPath}}:{},...e.definitionId?{definition_id:e.definitionId}:{},...e.assuranceId?{assurance_id:e.assuranceId}:{},...Object.keys(e.externalId).length?{external_id:e.externalId}:{},...e.tags&&e.tags.length?{tags:e.tags}:{},...Object.keys(e.environment).length?{environment:e.environment}:{},steps:e.steps};return h(t,{lineWidth:-1})}function oe(e){return h({logs:e},{lineWidth:-1})}async function se(e,t,r){await ne.writeFile(ie(e,"tests",t,"result.yaml"),r)}async function ae(e,t,r){let n=ie(e,"tests",t,"logs");await ne.mkdir(n,{recursive:!0}),await ne.writeFile(ie(n,"meta.yaml"),r)}import{promises as M}from"fs";import{join as Ue}from"path";function He(e){return Ue(e,".internal","meta.json")}async function Ke(e){let t;try{t=await M.readFile(He(e),"utf8")}catch(n){if(n?.code==="ENOENT")return null;throw n}let r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("meta.json is not a JSON object");return r}async function ce(e,t){let r;try{r=await Ke(e)??{}}catch(s){console.warn(`evidence: meta.json at ${e} unreadable \u2014 skipping execution-pointer append to preserve identity`,s);return}let n=Array.isArray(r.executions)?r.executions:[];n.push(t),r.executions=n,await M.mkdir(Ue(e,".internal"),{recursive:!0});let i=He(e),o=`${i}.tmp-${process.pid}-${Date.now()}`;await M.writeFile(o,JSON.stringify(r,null,2)+`
2
+ import{d as Me,h as $e}from"./chunk-AACQE24F.js";import{b as H,c as C,d as K,e as Y}from"./chunk-5TQIKRKP.js";import{b as _,c as B,d as Ae,f as z,g as U}from"./chunk-5GUD3CIH.js";import{c as Ve,d as Be}from"./chunk-WJR2FU7S.js";import{a as A,b as D,d as Pe}from"./chunk-EHN5HTUD.js";import{h as j,k as je,m as Oe,o as Fe}from"./chunk-RGRFL7XG.js";import{d as Te}from"./chunk-VVOKM2VO.js";import{a as N,c as Se,d as Ee,e as Re,f as V}from"./chunk-YFQGOOF7.js";import{z as O}from"./chunk-IICT4VOU.js";import{a as Ne}from"./chunk-CH273NAE.js";import{b as x,c as h}from"./chunk-VZ7KXRXB.js";import{a as De,b as Ce,c as Le}from"./chunk-PUFZTE6L.js";import{a as xe,b as Ie}from"./chunk-RUSRN7YE.js";import{a as ke}from"./chunk-SJZJ7ASF.js";function S(e){if(e===null)return"broken";let t=Math.floor(e/100);return t===1?"passed":t===7?"failed":t===2?"skipped":"broken"}var I={failed:3,broken:2,passed:1,skipped:0};function q(e){let t="skipped";for(let r of e)I[r]>I[t]&&(t=r);return t}import{createHash as ft}from"crypto";import{basename as gt}from"path";function W(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return t.length>0?t:"session"}function G(e){return ft("sha256").update(e).digest("hex").slice(0,8)}function J(e){let t=gt(e).replace(/_test\.md$/i,"").replace(/\.md$/i,"");return`${W(t)}-${G(e)}`}function X(e,t){return`${W(e)}-${G(t)}`}function Z(e){let t=e?.trim();return t||void 0}function ze(e=process.env){let t=Z(e.TEST_INSTANCE_ID),r=Z(e.JOB_ID),n=Z(e.TASK_ID);return{...t?{testInstanceId:t}:{},...r?{jobId:r}:{},...n?{taskId:n}:{}}}function Q(e,t=process.env){let r=ze(t),n={...r.testInstanceId?{hyper_test_instance_id:r.testInstanceId}:{},...r.jobId?{hyper_job_id:r.jobId}:{},...r.taskId?{hyper_task_id:r.taskId}:{},...e},i={};for(let[o,s]of Object.entries(n))typeof s=="string"&&s.length>0&&(i[o]=s);return i}function _t(e,t){return{pack_test_dir:e,ordinal_offset:t}}import{promises as w}from"fs";import{join as y}from"path";function ee(e){let t={evidence:"0.1",run_id:e.execution_id,status:"running",title:e.title,started:e.started,environment:{producer:{name:"kane-cli",version:e.producerVersion},...e.surfaces?{surfaces:e.surfaces}:{},run_kind:e.run_kind,origin:e.origin,pid:e.pid},...e.credits!==void 0?{metrics:{credits:{value:e.credits,type:"count"}}}:{}};return h(t,{lineWidth:-1})}async function te(e,t,r,n=process.cwd(),i){let o=i??_(e.execution_id,n),s=y(o,"tests",t);return await w.mkdir(y(o,"coverage"),{recursive:!0}),await w.writeFile(y(o,"coverage",".keep"),""),await w.mkdir(s,{recursive:!0}),await w.writeFile(y(o,"run.yaml"),ee(e)),r&&await w.writeFile(y(s,r.path),r.content),o}async function vt(e,t=process.cwd()){let r=_(e.execution_id,t);await w.mkdir(y(r,"coverage"),{recursive:!0}),await w.writeFile(y(r,"coverage",".keep"),"");let n=x(ee(e));return n.environment&&delete n.environment.run_kind,await w.writeFile(y(r,"run.yaml"),h(n,{lineWidth:-1})),r}async function ht(e,t=process.cwd()){return D(_(e,t),new Date().toISOString())}async function re(e,t=process.cwd()){await w.rm(_(e,t),{recursive:!0,force:!0})}import{promises as ne}from"fs";import{join as ie}from"path";function F(e){let t={evidence:"0.1",test:e.testId,status:e.status,...e.durationMs!==void 0?{duration_ms:e.durationMs}:{},...e.attempts&&e.attempts.length?{attempts:e.attempts}:{},...e.flaky!==void 0?{flaky:e.flaky}:{},...e.adaptiveHeal?{adaptive_heal:e.adaptiveHeal}:{},...e.definitionPath?{definition:{path:e.definitionPath}}:{},...e.definitionId?{definition_id:e.definitionId}:{},...e.assuranceId?{assurance_id:e.assuranceId}:{},...Object.keys(e.externalId).length?{external_id:e.externalId}:{},...e.tags&&e.tags.length?{tags:e.tags}:{},...Object.keys(e.environment).length?{environment:e.environment}:{},steps:e.steps};return h(t,{lineWidth:-1})}function oe(e){return h({logs:e},{lineWidth:-1})}async function se(e,t,r){await ne.writeFile(ie(e,"tests",t,"result.yaml"),r)}async function ae(e,t,r){let n=ie(e,"tests",t,"logs");await ne.mkdir(n,{recursive:!0}),await ne.writeFile(ie(n,"meta.yaml"),r)}import{promises as M}from"fs";import{join as Ue}from"path";function He(e){return Ue(e,".internal","meta.json")}async function Ke(e){let t;try{t=await M.readFile(He(e),"utf8")}catch(n){if(n?.code==="ENOENT")return null;throw n}let r=JSON.parse(t);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("meta.json is not a JSON object");return r}async function ce(e,t){let r;try{r=await Ke(e)??{}}catch(s){console.warn(`evidence: meta.json at ${e} unreadable \u2014 skipping execution-pointer append to preserve identity`,s);return}let n=Array.isArray(r.executions)?r.executions:[];n.push(t),r.executions=n,await M.mkdir(Ue(e,".internal"),{recursive:!0});let i=He(e),o=`${i}.tmp-${process.pid}-${Date.now()}`;await M.writeFile(o,JSON.stringify(r,null,2)+`
3
3
  `),await M.rename(o,i)}async function wt(e){try{let t=await Ke(e);return t&&Array.isArray(t.executions)?t.executions:[]}catch{return[]}}async function yt(e,t,r=process.cwd()){let n=await z(e,r);if(!n){let o=`evidence: no pack found for "${e}"`;return t.json?console.log(JSON.stringify({valid:!1,error:"not_found",target:e})):console.error(o),2}let i=await A(n,t.profile??"L1");return t.json?console.log(JSON.stringify({valid:i.valid,status:i.status,diagnostics:i.diagnostics})):console.log(`evidence: ${i.valid?"valid":"INVALID"} (${t.profile??"L1"}, status ${i.status})`),i.valid?0:1}function ue(e){let t=[];for(let r of e){let n=r.perFlow&&r.perFlow.length?r.perFlow.map(i=>i.resultCode):[r.resultCode];for(let i of n)t.push(S(i))}return q(t)}function bt(e){let t=null;for(let r of e){let n=r.perFlow&&r.perFlow.length?r.perFlow.map(i=>i.resultCode):[r.resultCode];for(let i of n)i!=null&&(t==null||I[S(i)]>I[S(t)]||I[S(i)]===I[S(t)]&&i>t)&&(t=i)}return t}import{promises as kt}from"fs";import{extname as Ye,basename as xt}from"path";var It={".ndjson":"ndjson",".log":"log",".json":"json",".har":"har"};async function de(e){let t;try{t=await kt.readdir(e)}catch{return[]}return t.filter(r=>r!=="meta.yaml"&&!r.startsWith(".")).sort().map(r=>({name:xt(r,Ye(r)),file:r,format:It[Ye(r)]??"txt"}))}import{mkdirSync as St,appendFileSync as Et}from"fs";import{join as qe}from"path";function le(e,t){return qe(e,"tests",t,"logs")}function pe(e,t,r,n={},i){try{i?.(t,r,r,n)}catch{}if(e)try{St(e,{recursive:!0});let o=JSON.stringify({ts:new Date().toISOString(),level:t,event:r,...n})+`
4
4
  `;Et(qe(e,"diagnostics.ndjson"),o)}catch{}}import{promises as b}from"fs";import{dirname as Ft,join as E}from"path";import{statSync as Rt}from"fs";import{promises as me}from"fs";import{basename as Pt,join as At}from"path";var Dt=1e6,Ct=2e6;function Lt(){return xe.map(e=>Ie(e))}function We(e=Lt()){return e.map(t=>{let r=0;try{r=Rt(t).size}catch{}return{path:t,offset:r}})}var jt=/\x1b\[[0-9;]*[A-Za-z]/g;async function Ot(e,t,r){let n;try{n=await me.open(e,"r");let i=(await n.stat()).size,o=t<=i?t:0,s=i-o;if(s<=0)return null;let a=s>r?i-r:o,u=Buffer.alloc(Math.min(s,r));return await n.read(u,0,u.length,a),u.toString("utf8")}catch{return null}finally{await n?.close().catch(()=>{})}}async function Ge(e,t){let r=t.caps?.stderr??Dt,n=t.caps?.appium??Ct,i=[];t.runnerStderrPath&&i.push({src:t.runnerStderrPath,from:0,cap:r});for(let o of t.appiumMarks??[])i.push({src:o.path,from:o.offset,cap:n});for(let o of i){let s=await Ot(o.src,o.from,o.cap);if(s===null)continue;let a=s.replace(jt,"");if(a!=="")try{await me.mkdir(e,{recursive:!0}),await me.writeFile(At(e,Pt(o.src)),a)}catch{}}}async function Mt(e){try{let t=E(e,"tests"),r=await b.readdir(t).catch(()=>[]);for(let n of r){let i=E(t,n,"steps"),o=await b.readdir(i).catch(()=>[]);for(let s of o){let a=await b.readFile(E(i,s,"failure.yaml"),"utf8").catch(()=>null);if(a!=null)try{let u=x(a);if(u&&typeof u=="object"&&u.triage)return!0}catch{}}}}catch{}return!1}async function Je(e,t,r,n={}){let i=E(e,"tests",t,"logs");if(r)try{await b.mkdir(i,{recursive:!0}),await b.copyFile(r,E(i,"tui.log"))}catch{}await Ge(i,{runnerStderrPath:r?E(Ft(r),"runner-stderr.log"):void 0,appiumMarks:n.appiumMarks});let o=await de(i);if(!o.length&&n.requireRealLog)throw new Error(`evidence test ${t} has no real log to declare`);o.length&&await ae(e,t,oe(o))}async function fe(e){let t=e.cwd??process.cwd(),r=e.packDir??_(e.executionId,t);if(!e.saved&&!e.packDir)return await re(e.executionId,t),{sealed:!1};await Je(r,e.testId,e.tuiLogPath,{requireRealLog:e.requireRealLog,appiumMarks:e.appiumMarks});let n=E(r,"run.yaml"),i=x(await b.readFile(n,"utf8"));i.environment={...i.environment??{},saved:e.saved,run_kind:e.runKind},await b.writeFile(n,h(i,{lineWidth:-1}));let o=await b.open(n,"r+");try{await o.sync()}finally{await o.close()}let s=await Mt(r);await D(r,new Date().toISOString());let a;try{let c=await A(r,"L1");a=c.valid;let p=(c.diagnostics??[]).filter(l=>String(l?.code??"").includes("failure.status_disagrees"));if(p.length>0)if(e.expectStatusDisagrees||s){let l=e.expectStatusDisagrees?"expected under --bug-detection continue":"self-explained by triaged failure record(s)";console.warn(`evidence: ${p.length} status_disagrees advisory(ies) \u2014 ${l}`)}else console.warn(`evidence: ${p.length} status_disagrees advisory(ies) \u2014 step verdicts disagree with their failure records`,p);if(!c.valid){console.warn(`evidence: sealed pack ${e.executionId} failed L1 validation`,c.diagnostics);let l=String(c.diagnostics?.[0]?.code??"");pe(le(r,e.testId),"warn","EVIDENCE_INVALID",{execution_id:e.executionId,first_code:l,surface:e.surface??"testmd"},e.log)}}catch(c){console.warn(`evidence: validation error for ${e.executionId}`,c)}let u;if(e.saved&&e.packDir)try{u=await Ae(r,e.executionId,t)}catch(c){console.warn(`evidence: store install failed for ${e.executionId}`,c)}if(e.outputStemDir)try{await ce(e.outputStemDir,{execution_id:e.executionId,run_kind:e.runKind,status:e.verdict,valid:a,at:new Date().toISOString()})}catch(c){console.warn(`evidence: execution-pointer append failed for ${e.executionId} (pack is sealed)`,c)}return{sealed:!0,valid:a,storePath:u}}import{release as Xe}from"os";import{execFileSync as $t}from"child_process";var Ze=!1,$;function Tt(){if(!Ze)if(Ze=!0,process.platform==="darwin")try{$=$t("sw_vers",["-productVersion"],{timeout:2e3}).toString().trim()||void 0}catch{$=Xe()||void 0}else $=Xe()||void 0;return $}function ge(e){let t={os:N(process.platform)},r=Tt();if(r&&(t.os_version=r),e.cdpBrowser){let o=/^([A-Za-z]+)\/(\d+)/.exec(e.cdpBrowser);o&&(t.browser=o[1].replace(/^Headless/,""),t.browser_version=o[2])}e.resolution&&(t.resolution=e.resolution);let n=Ee(t,e.runnerEnvironment);if(!n.native_platform)return n;e.deviceName&&(n.device=e.deviceName),!n.os_version&&e.deviceOsVersion&&(n.os_version=e.deviceOsVersion);let i=De(e.deviceApp);if(i&&(n.app=i),e.deviceModel){let o=Ce(e.deviceModel);o&&(n.device_slug=o)}return e.pixelResolution&&(n.viewport=n.resolution??Nt(e.pixelResolution,n.pixel_ratio)??e.pixelResolution,n.resolution=e.pixelResolution),n}function Nt(e,t){if(!t||!Number.isFinite(t)||t<=0)return;let r=/^(\d+)x(\d+)$/.exec(e);if(r)return`${Math.round(Number(r[1])/t)}x${Math.round(Number(r[2])/t)}`}async function Qe(e){if(e)try{let t=await fetch(`${e}/json/version`,{signal:AbortSignal.timeout(2e3)});if(!t.ok)return;let r=await t.json();return typeof r.Browser=="string"?r.Browser:void 0}catch{return}}function Vt(e){let t;return()=>(t||(t=Qe(e)),t)}import{promises as v,existsSync as k,readFileSync as Ht}from"fs";import{basename as Kt,join as m}from"path";import{readFileSync as Bt}from"fs";import{dirname as zt,resolve as Ut}from"path";function et(e,t){let r=Ut(e),n=Bt(r,"utf8");return j(t?je(n,Oe(zt(r),t)):n)}async function tt(e){for(let t of await v.readdir(e,{withFileTypes:!0})){let r=m(e,t.name);if(t.isDirectory()){await tt(r);continue}try{await v.unlink(r)}catch{await v.truncate(r,0)}}await v.rmdir(e).catch(()=>{})}function Yt(e){let t=e.authorBoundary<0||e.authorBoundary>e.totalSteps?e.totalSteps:e.authorBoundary;return{shrink_count:e.shrinkCount,complete_reauthor:t===0&&e.totalSteps>0,author_boundary:t,total_steps:e.totalSteps,reauthored_steps:e.totalSteps-t,credits_consumed:Math.round(e.creditsConsumed*100)/100}}var L=class e{constructor(t){this.opts=t}executionId;testId;definitionPath=null;definitionContent=null;accumulatedSteps=[];maxOrdinal=0;_attempts=[];_packDirOverride;_attached=!1;appiumMarks=We();get attached(){return this._attached}static async attach(t){let r=Kt(t.packDir).replace(/\.evidence$/,""),n=new e({origin:"testrun",runKind:"author",pid:process.pid,title:t.testId,started:new Date().toISOString(),producerVersion:ke,cwd:t.cwd});n.executionId=r,n.testId=t.testId,n._packDirOverride=t.packDir,n._attached=!0;let i=m(t.packDir,"tests",t.testId);return await v.mkdir(i,{recursive:!0}),t.definition&&(await v.writeFile(m(i,t.definition.path),t.definition.content),n.definitionPath=t.definition.path,n.definitionContent=t.definition.content),n}async start(){if(this._attached)throw new Error("attach-mode session is already started");this.executionId=B(),this.testId=this.opts.testmdRelPath?J(this.opts.testmdRelPath):X(this.opts.objectiveOrName??"session",this.opts.sessionId??this.executionId);let t=this.opts.definition??null;return await te({execution_id:this.executionId,title:this.opts.title,started:this.opts.started,producerVersion:this.opts.producerVersion,surfaces:this.opts.surfaces,run_kind:this.opts.runKind,origin:this.opts.origin,pid:this.opts.pid,...this.opts.credits!==void 0?{credits:this.opts.credits}:{}},this.testId,t,this.opts.cwd,this.opts.packRootDir?this.pack:void 0),t&&(this.definitionPath=t.path,this.definitionContent=t.content),{executionId:this.executionId,testId:this.testId,packTestDir:this.packTestDir}}get pack(){return this._packDirOverride?this._packDirOverride:this.opts.packRootDir?m(this.opts.packRootDir,`${this.executionId}.evidence`):_(this.executionId,this.opts.cwd)}get packTestDir(){return m(this.pack,"tests",this.testId)}async writeDefinition(t,r="test.md"){await v.writeFile(m(this.packTestDir,r),t),this.definitionPath=r,this.definitionContent=t}computeAssuranceId(){try{if(this.opts.testmdRelPath&&this.opts.cwd){let t=m(this.opts.cwd,this.opts.testmdRelPath);if(k(t))return Fe(Ht(t,"utf8"))?.id}}catch{}}computeDefinitionId(){try{if(this.opts.testmdRelPath&&this.opts.cwd){let t=m(this.opts.cwd,this.opts.testmdRelPath),r=m(this.opts.cwd,".context"),n=k(r)?O(r):void 0;if(k(t))return et(t,n)}if(this.definitionContent!=null)return j(this.definitionContent)}catch{}}noteSpawn(t){this.accumulatedSteps.push(...t.steps),this.maxOrdinal=Math.max(this.maxOrdinal,t.maxOrdinal)}nextOrdinalOffset(){return this.maxOrdinal}get steps(){return this.accumulatedSteps}get attempts(){return this._attempts}async archiveAttempt(t,r,n={}){let i=this._attempts.length+1,o=m(this.packTestDir,String(i)),s=n.log,a=(c,d)=>s?.("warn","ARCHIVE_ATTEMPT_FAILED",`Attempt ${i}: ${c} could not be archived into ${i}/; the next attempt will mingle with it`,{attempt:i,dir:c,error:String(d)}),u;try{await v.mkdir(o,{recursive:!0})}catch(c){a(`${i}/`,c)}for(let c of["steps","logs","v16-trajectory"]){let d=m(this.packTestDir,c);if(!k(d))continue;let p=m(o,c);try{await v.rename(d,p);continue}catch(l){s?.("warn","ARCHIVE_ATTEMPT_RENAME_FAILED",`Attempt ${i}: rename of ${c}/ refused; copying it into ${i}/ and emptying the originals in place`,{attempt:i,dir:c,error:String(l),fallback:"copy+truncate"})}try{await v.cp(d,p,{recursive:!0}),await tt(d)}catch(l){a(c,l)}}try{this.definitionPath&&k(m(this.packTestDir,this.definitionPath))&&await v.copyFile(m(this.packTestDir,this.definitionPath),m(o,this.definitionPath));let c=m(o,"steps");if(k(c)){for(let d of await v.readdir(c))if(k(m(c,d,"failure.yaml"))){u=`${i}/steps/${d}/failure.yaml`;break}}}catch(c){a("definition + failure pointer",c)}return this._attempts.push({n:i,status:t,steps:this.accumulatedSteps,...r!==void 0?{failedAt:r}:{},...u?{failure:u}:{}}),this.accumulatedSteps=[],this.maxOrdinal=0,i}async writeResult(t){let r=ue(t.spawns),n=this._attempts.length?[...this._attempts.map(g=>({status:g.status})),{status:r,...t.durationMs!==void 0?{duration_ms:t.durationMs}:{}}]:void 0,i=n?new Set(n.map(g=>g.status)).size>1:void 0,o=this._attempts.length>0,s=t.heal,a=o||s?.forced?{triggered:o,...o?{outcome:r==="passed"?"healed":"exhausted"}:{},...s?Yt(s):{},...o?{attempts:this._attempts.map(g=>({n:g.n,status:g.status,failed_at:g.failedAt??-1,...g.failure?{failure:g.failure}:{}}))}:{}}:void 0,u=this.pack,c=Q(t.externalIdInput),d=V(t.runnerEnv,t.intentEnv),p=this.computeDefinitionId(),l=this.computeAssuranceId();await se(u,this.testId,F({testId:this.testId,status:r,durationMs:t.durationMs,definitionPath:this.definitionPath,definitionId:p,assuranceId:l,externalId:c,environment:d,steps:t.steps,tags:t.tags,attempts:n,flaky:i,adaptiveHeal:a}));for(let g of this._attempts){let R=m(this.packTestDir,String(g.n));k(R)&&await v.writeFile(m(R,"result.yaml"),F({testId:this.testId,status:g.status,definitionPath:this.definitionPath,definitionId:p,assuranceId:l,externalId:c,environment:d,steps:g.steps,tags:t.tags}))}let f=t.externalIdInput;return t.log&&(f.commit_id||f.test_id||f.testcase_id)&&t.log("info","EVIDENCE_EXTERNAL_ID","Evidence external-id mapping",{execution_id:this.executionId,commit_id:f.commit_id??null,test_id:f.test_id??null,testcase_id:f.testcase_id??null,tc_id:c.tc_id??null,project_id:f.project_id??null,session_id:f.session_id??null,session_name:f.session_name??null,hyper_test_instance_id:c.hyper_test_instance_id??null,hyper_job_id:c.hyper_job_id??null,hyper_task_id:c.hyper_task_id??null,dataset_id:c.dataset_id??null,dataset_row_id:c.dataset_row_id??null,dataset_version_id:c.dataset_version_id??null}),r}get id(){return this.executionId}get test(){return this.testId}};async function qt(e,t,r=U){try{let n=await r(e);if(n.aborted.length>0||n.removed.length>0)try{t?.("info","EVIDENCE_RECOVERY","Startup evidence recovery swept incomplete packs",{aborted:n.aborted,removed:n.removed,origin:"startup"})}catch{}return n}catch(n){return console.warn("evidence: startup recovery failed",n),{aborted:[],removed:[]}}}import{promises as sr}from"fs";import{existsSync as _e,mkdirSync as Qt,readdirSync as er,readFileSync as tr,rmSync as rr,statSync as nr,writeFileSync as ir}from"fs";import{join as P}from"path";import{mkdirSync as Wt,renameSync as Gt,rmSync as Jt,writeFileSync as Xt}from"fs";import{join as rt}from"path";var Zt=5e6;function nt(e,t,r){let n=rt(e,"coverage","sources"),i=new Map,o=!1;try{for(let s of r.usecases)for(let a of s.sources){if(i.has(a.id)){a.file=i.get(a.id);continue}if(!a.cid)continue;let u=Te(t,a.cid);if(u===null||u.byteLength>Zt)continue;o||(Wt(n,{recursive:!0}),o=!0);let c=rt(n,a.id),d=`${c}.tmp-${process.pid}`;Xt(d,u),Gt(d,c);let p=`coverage/sources/${a.id}`;i.set(a.id,p),a.file=p}}catch{for(let s of r.usecases)for(let a of s.sources)delete a.file;if(o)try{Jt(n,{recursive:!0,force:!0})}catch{}}}var or={passed:"passed",failed:"failed",broken:"blocked",skipped:"not-run"},it=(e,t)=>{try{if(!_e(t))return{status:"skipped",reason:"no context store at the project root"};let r=P(e,"tests");if(!_e(r))return{status:"skipped",reason:"pack has no tests/"};let n=new Map;for(let a of er(r)){let u=P(r,a,"result.yaml");if(!_e(u)||!nr(P(r,a)).isDirectory())continue;let c=x(tr(u,"utf8"));if(!c?.definition_id&&!c?.assurance_id)continue;let d=Ve(c.steps??[]),p={testShortId:String(c.test??a),execution:or[String(c.status)]??"not-run",...d.length?{acs:d}:{}};c.assurance_id&&n.set(`id:${c.assurance_id}`,p),c.definition_id&&n.set(`def:${c.definition_id}`,p)}let i=$e(O(t),n,{scope:"run"}),o=Me(i);nt(e,t,i);let s=h({...i,rollup:o},{lineWidth:-1});return Qt(P(e,"coverage"),{recursive:!0}),ir(P(e,"coverage","usecases.yaml"),s),{status:"written"}}catch(r){try{rr(P(e,"coverage","sources"),{recursive:!0,force:!0})}catch{}return{status:"skipped",reason:r instanceof Error?r.message:String(r)}}};async function ar(e){try{let t=new L({origin:"inline",runKind:"author",pid:e.pid,title:e.title,started:new Date().toISOString(),producerVersion:e.producerVersion,surfaces:e.surfaces,objectiveOrName:e.objectiveOrName,sessionId:e.sessionId,cwd:e.cwd,packRootDir:e.packRootDir}),r=await t.start();return{session:t,...r,packDir:t.pack,spawns:[],startedAtMs:Date.now(),cwd:e.cwd}}catch(t){return console.warn("evidence: inline pack creation failed",t),null}}function cr(e,t,r){if(!e)return;e.session.noteSpawn(t),t.resolution&&(e.resolution=t.resolution),e.runnerEnvironment=Se(e.runnerEnvironment,t.runnerEnvironment);let n=(r?.per_flow_metadata??[]).map(i=>({resultCode:i?.result_code!=null?Number(i.result_code):null}));e.spawns.push({resultCode:r?.result_code!=null?Number(r.result_code):null,...n.length?{perFlow:n}:{}})}function ur(e){if(e)return{packTestDir:e.packTestDir,ordinalOffset:e.session.nextOrdinalOffset()}}async function dr(e,t){if(!e)return null;if(e.finalized)return e.finalized;let r=(n,i,o)=>t.log?t.log("warn",n,i,o):console.warn(`evidence: ${i}`,o??"");try{if(t.recordedTestPath)try{await e.session.writeDefinition(await sr.readFile(t.recordedTestPath,"utf8"))}catch(s){r("EVIDENCE_DEFINITION_FAILED","could not attach synthesized test.md",{error:String(s)})}let n=t.cdpBrowserCapture?await t.cdpBrowserCapture():void 0,i=await e.session.writeResult({steps:e.session.steps,spawns:e.spawns.length?e.spawns:[{resultCode:null}],externalIdInput:{...t.externalIdInput,execution_id:e.executionId},runnerEnv:ge({cdpBrowser:n,resolution:e.resolution,runnerEnvironment:e.runnerEnvironment,deviceName:t.deviceName,deviceModel:t.deviceModel,deviceApp:t.deviceApp,pixelResolution:await Le(e.packTestDir)}),intentEnv:Re(t.model,e.runnerEnvironment),durationMs:t.durationMs??Date.now()-e.startedAtMs,log:t.log});try{if(t.recordedTestPath){let s=Be({cwd:t.cwd??e.cwd??process.cwd(),members:[{path:t.recordedTestPath,verdict:i,executionId:e.executionId,startedAt:new Date(e.startedAtMs).toISOString(),mode:"inline",local:t.local??!1}]});for(let a of s.warnings)r("EXEC_SYNC",a)}}catch(s){r("EXEC_SYNC","exec-sync failed",{error:String(s)})}try{let s=(t.coverageWriter??it)(e.packDir,Ne(t.cwd??e.cwd??process.cwd()));s.status==="skipped"&&r("EVIDENCE_COVERAGE_SKIPPED",`coverage/usecases.yaml not written: ${s.reason}`)}catch(s){r("EVIDENCE_COVERAGE_SKIPPED","coverage writer threw",{error:String(s)})}let o=await fe({executionId:e.executionId,testId:e.testId,saved:t.saved,runKind:"author",verdict:i,cwd:t.cwd??e.cwd,packDir:e.packDir,tuiLogPath:t.tuiLogPath,log:t.log,surface:"inline",requireRealLog:!!e.runnerEnvironment?.native_platform,appiumMarks:e.session.appiumMarks});return e.finalized=o,t.log?.("info","EVIDENCE_SEALED","Inline pack sealed",{execution_id:e.executionId,verdict:i,valid:o.valid,pack:e.packDir,store_copy:o.storePath??null}),o}catch(n){return r("EVIDENCE_SEAL_FAILED","inline pack finalize failed",{error:String(n)}),null}}import{statSync as lr,openSync as pr,readSync as mr,closeSync as fr}from"fs";import{basename as gr,resolve as _r}from"path";async function vr(e,t,r={}){let n=r.out??(d=>process.stdout.write(d+`
5
5
  `)),i=d=>(n(`error: ${d}`),2);if(t.env!=="prod"&&t.env!=="stage")return i(`invalid --env: ${String(t.env)}`);if(t.port!==void 0&&(!Number.isInteger(t.port)||t.port<1||t.port>65535))return i("invalid --port: expected an integer 1-65535");let o;try{o=C(t.env,t.viewerUrl),new URL(o)}catch{return i(`invalid --viewer-url: ${t.viewerUrl}`)}if(e.length===0)return i("no pack paths given");let s=new Map;for(let d of e){let p=_r(d),l;try{l=lr(p)}catch{return i(`${d}: not found`)}if(l.isDirectory())return i(`${d}: is a directory \u2014 packs must be sealed .evidence files (run the execution to completion, or seal it, first)`);if(!l.isFile())return i(`${d}: not a regular file`);let f=Buffer.alloc(2),g=pr(p,"r");try{mr(g,f,0,2,0)}finally{fr(g)}if(f.toString("latin1")!=="PK")return i(`${d}: not a sealed evidence pack (zip magic missing)`);let R=gr(p);if(s.has(R))return i(`duplicate pack basename: ${R} (URL names collide \u2014 rename one)`);s.set(R,p)}let a=r.log??((d,p,l)=>process.stderr.write(`warn: ${p} reason=${l.reason} path=${l.path}
6
- `)),u;try{u=await H({packs:s,allowedOrigins:[new URL(o).origin],port:t.port,log:a})}catch(d){return i(`could not bind 127.0.0.1${t.port?`:${t.port}`:""} \u2014 ${d.message}`)}n(`serving ${s.size} pack${s.size===1?"":"s"} on http://127.0.0.1:${u.port}`);for(let d of s.keys()){let p=u.urlFor(d);n(d),n(` pack ${p}`),n(` viewer ${K(p,o)}`)}return n("press Ctrl-C to stop"),await(r.hold??hr)(),await u.close(),0}function hr(){return new Promise(e=>{let t=process.listeners("SIGINT");process.removeAllListeners("SIGINT"),process.once("SIGINT",()=>{for(let r of t)process.on("SIGINT",r);e()})})}import{promises as T}from"fs";import{tmpdir as kr}from"os";import{join as at,resolve as he}from"path";var wr=["error","prefer_first","prefer_latest","discard"],yr=["external_id.commit_id","external_id.test_id","external_id.dataset_row_id","environment.os","environment.os_version","environment.browser","environment.browser_version","environment.device","environment.app"];function ot(e){let t=e.replace(/-/g,"_");return wr.includes(t)?t:null}function st(e){let t=e==="discard"?{on_collision:"discard"}:{on_collision:"error",identity:{keys:[...yr],on_same:e??"nest",on_different:e?"error":"split"}};return h({packs:{require_status:"finalized",require_valid:"L1",on_ineligible:"abort"},tests:t,rules:[{file:"run.yaml",key:"run_id",must:"different",on_violation:"skip"},{file:"result.yaml",key:"external_id.project_id",must:"same",on_violation:"error"},{file:"result.yaml",key:"external_id.org_id",must:"same",on_violation:"error"}]},{lineWidth:-1})}async function ve(e){try{if(!e.isTTY){e.log(Y(e.packPath));return}let t=C(e.env);await(e.renderPrompt??br)(e.packPath,t)}catch(t){try{e.log(`evidence view failed \u2014 ${t.message}`)}catch{}}}async function br(e,t){let r=await import("./react-QWOAB3TB.js"),{render:n}=await import("./build-JIKYOZUH.js"),{EvidenceViewOffer:i}=await import("./EvidenceViewOffer-GW7XLM45.js");await new Promise(o=>{let s=n(r.default.createElement(i,{packPath:e,viewerBase:t,onDone:()=>{s.unmount(),o()}}),{stdout:process.stderr,exitOnCtrlC:!1})})}async function xr(e,t,r=process.cwd(),n={}){let i=n.out??(l=>process.stdout.write(l+`
6
+ `)),u;try{u=await H({packs:s,allowedOrigins:[new URL(o).origin],port:t.port,log:a})}catch(d){return i(`could not bind 127.0.0.1${t.port?`:${t.port}`:""} \u2014 ${d.message}`)}n(`serving ${s.size} pack${s.size===1?"":"s"} on http://127.0.0.1:${u.port}`);for(let d of s.keys()){let p=u.urlFor(d);n(d),n(` pack ${p}`),n(` viewer ${K(p,o)}`)}return n("press Ctrl-C to stop"),await(r.hold??hr)(),await u.close(),0}function hr(){return new Promise(e=>{let t=process.listeners("SIGINT");process.removeAllListeners("SIGINT"),process.once("SIGINT",()=>{for(let r of t)process.on("SIGINT",r);e()})})}import{promises as T}from"fs";import{tmpdir as kr}from"os";import{join as at,resolve as he}from"path";var wr=["error","prefer_first","prefer_latest","discard"],yr=["external_id.commit_id","external_id.test_id","external_id.dataset_row_id","environment.os","environment.os_version","environment.browser","environment.browser_version","environment.device","environment.app"];function ot(e){let t=e.replace(/-/g,"_");return wr.includes(t)?t:null}function st(e){let t=e==="discard"?{on_collision:"discard"}:{on_collision:"error",identity:{keys:[...yr],on_same:e??"nest",on_different:e?"error":"split"}};return h({packs:{require_status:"finalized",require_valid:"L1",on_ineligible:"abort"},tests:t,rules:[{file:"run.yaml",key:"run_id",must:"different",on_violation:"skip"},{file:"result.yaml",key:"external_id.project_id",must:"same",on_violation:"error"},{file:"result.yaml",key:"external_id.org_id",must:"same",on_violation:"error"}]},{lineWidth:-1})}async function ve(e){try{if(!e.isTTY){e.log(Y(e.packPath));return}let t=C(e.env);await(e.renderPrompt??br)(e.packPath,t)}catch(t){try{e.log(`evidence view failed \u2014 ${t.message}`)}catch{}}}async function br(e,t){let r=await import("./react-QWOAB3TB.js"),{render:n}=await import("./build-JIKYOZUH.js"),{EvidenceViewOffer:i}=await import("./EvidenceViewOffer-XUP44BGJ.js");await new Promise(o=>{let s=n(r.default.createElement(i,{packPath:e,viewerBase:t,onDone:()=>{s.unmount(),o()}}),{stdout:process.stderr,exitOnCtrlC:!1})})}async function xr(e,t,r=process.cwd(),n={}){let i=n.out??(l=>process.stdout.write(l+`
7
7
  `)),o=n.err??(l=>process.stderr.write(l+`
8
8
  `)),s=l=>(o(`evidence merge: ${l}`),2);if(!t.runId)return s("--run-id is required (merged identity is the caller's fact)");if(t.rules&&t.onCollision)return s("--rules and --on-collision are mutually exclusive");let a;if(t.onCollision!==void 0){let l=ot(t.onCollision);if(!l)return s(`invalid --on-collision: ${t.onCollision} (expected error | prefer-first | prefer-latest | discard)`);a=l}let u=[];for(let l of e){let f=await Ir(l,r);if(!f)return s(`no pack found for "${l}"`);u.push(f)}let c=t.out?he(r,t.out):_(t.runId,r),d=null,p;t.rules?p=he(r,t.rules):(d=await T.mkdtemp(at(kr(),"kane-merge-rules-")),p=at(d,"merge-rules.yaml"),await T.writeFile(p,st(a)));try{let l=await(n.mergeFn??Pe)(u,{runId:t.runId,out:c,rulesPath:p,title:t.title,finalize:t.finalize});return t.json?i(JSON.stringify(l)):Sr(i,l),l.output.finalized&&!t.json&&await(n.offer??ve)({packPath:c,env:t.env,isTTY:n.isTTY??(!!process.stdin.isTTY&&!!process.stderr.isTTY),log:o}),0}catch(l){let f=l instanceof Error?l.message:String(l);return l?.code==="ABORT"?(o(`evidence merge: aborted \u2014 ${f}`),1):s(f)}finally{d&&await T.rm(d,{recursive:!0,force:!0}).catch(()=>{})}}async function Ir(e,t){let r=he(t,e);if(await ct(r))return r;let n=_(e,t);return await ct(n)?n:null}async function ct(e){try{return await T.stat(e),!0}catch{return!1}}function Sr(e,t){let{packs:r,tests:n,output:i}=t;e(`evidence: merged ${n.merged} tests from ${r.eligible.length} packs -> ${i.path} (${i.finalized?"sealed":"live"})`);for(let o of r.skipped)e(` skipped ${o.runId}: ${o.rule} \u2014 ${o.reason}`);for(let o of n.collisions){let s;o.action==="nest"?s=`nested into ${o.folder}, latest ${o.winner}`:o.action==="split"?s=`split into ${o.folder}`:s=`winner ${o.winner}`,e(` collision ${o.test}: ${s} (${o.rule})`)}for(let o of n.discarded)e(` discarded ${o}`)}import{copyFileSync as Er,existsSync as we,mkdirSync as Rr}from"fs";import{join as ut}from"path";function Pr(e,t,r){try{let n=ut(e,"auteur","execution.json");if(we(n))return!0;for(let i of t)if(!(!i||!we(i)))return Rr(ut(e,"auteur"),{recursive:!0}),Er(i,n),!0}catch(n){try{r?.("debug","EVIDENCE_BLOB_COPY_FAILED","auteur execution blob copy failed",{operation:"ensureAuteurExecution",source:t.find(i=>i&&we(i))??null,error:n instanceof Error?n.message:String(n)})}catch{}}return!1}import{mkdirSync as Ar,writeFileSync as Dr}from"fs";import{join as dt}from"path";function Cr(e,t,r){try{return Ar(dt(e,"auteur"),{recursive:!0}),Dr(dt(e,"auteur","dataset.json"),JSON.stringify(t,null,2)+`
9
9
  `,"utf8"),!0}catch(n){try{r?.("debug","EVIDENCE_DATASET_WRITE_FAILED","auteur dataset record write failed",{dataset_id:t.dataset_id,error:n instanceof Error?n.message:String(n)})}catch{}}return!1}import{readFileSync as Lr}from"fs";import{join as jr}from"path";var lt="module_block";var Or=new Set(["generative_block",lt]);function be(e){let t=[],r=!0,n=o=>{if(o===null||typeof o!="object")return;let s=o;if(Array.isArray(s.operations))for(let a of s.operations){let u=a?.operation_id;typeof u=="string"&&u&&t.push(u)}if(Array.isArray(s.children)){Or.has(s.content_type)||(r=!1);for(let a of s.children)n(a)}if(Array.isArray(s.branches)){r=!1;for(let a of s.branches){let u=a?.children;if(Array.isArray(u))for(let c of u)n(c)}}},i=e?.instructions;if(Array.isArray(i))for(let o of i)n(o);return{ids:t,linear:r}}function Fr(e){return be(e).ids}function ye(e,t){let r=new Set(t.map(a=>a.action_id).filter(Boolean)),n=-1;for(let a of r){let u=e.indexOf(a);u>n&&(n=u)}let i=t.reduce((a,u)=>Math.max(a,u.ordinal),0),o=new Set,s=[];for(let a of e.slice(n+1))r.has(a)||o.has(a)||(o.add(a),s.push({id:a,ordinal:++i,status:"skipped",action_id:a}));return s}function pt(e,t){let r=new Set(t),n=e.filter(o=>o.action_id);if(n.some(o=>r.has(o.action_id))||n.length>t.length)return null;let i=0;return e.map(o=>o.action_id?{...o,action_id:t[i++]}:o)}function Mr(e,t){if(e.length>t.length)return!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r].action_id)return!1;return!0}function $r(e,t,r,n=!0){if(t.length===0)return{steps:e,tail:[]};let i=(r&&n?pt(e,t):null)??e,o=i.filter(a=>a.action_id),s=new Set(t);return o.length>0&&o.every(a=>s.has(a.action_id))?{steps:i,tail:ye(t,i)}:o.length>0&&!Mr(o,t)?{steps:i,tail:[],unjoined:!0}:{steps:i,tail:ye(t,i)}}function mt(e){try{let t=Lr(jr(e,"auteur","execution.json"),"utf8");return be(JSON.parse(t))}catch{return{ids:[],linear:!0}}}function Tr(e){return mt(e).ids}export{S as a,q as b,W as c,G as d,J as e,X as f,ze as g,Q as h,_t as i,ee as j,te as k,vt as l,ht as m,re as n,F as o,oe as p,se as q,ae as r,ce as s,wt as t,yt as u,ue as v,bt as w,de as x,le as y,pe as z,Je as A,fe as B,ge as C,Qe as D,Vt as E,L as F,qt as G,it as H,ar as I,cr as J,ur as K,dr as L,vr as M,st as N,ve as O,xr as P,Pr as Q,Cr as R,lt as S,be as T,Fr as U,ye as V,pt as W,$r as X,mt as Y,Tr as Z};