@testmuai/kane-cli 0.8.14 → 0.8.16

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 (191) hide show
  1. package/dist/{ChatSurface-AVL3TJA2.js → ChatSurface-5JEEFY34.js} +1 -1
  2. package/dist/{ChromeProfilePicker-WJZJOZ6Z.js → ChromeProfilePicker-6IVAYCWJ.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-65BQF5G5.js → CliFeedbackPrompt-K4IN7S6J.js} +1 -1
  4. package/dist/{CliUploadProgress-HEBZYKGN.js → CliUploadProgress-MI4H4LKT.js} +1 -1
  5. package/dist/{ConfigView-JEVQ2SO4.js → ConfigView-CJY5MB6H.js} +1 -1
  6. package/dist/EvidenceViewOffer-ABKTGD4K.js +2 -0
  7. package/dist/FolderPicker-RQIVS7ZR.js +2 -0
  8. package/dist/{InfoBox-KM5DLBCV.js → InfoBox-RP6RDCG7.js} +1 -1
  9. package/dist/{LinksBox-FQA36GTV.js → LinksBox-QOQJ3S2I.js} +1 -1
  10. package/dist/{ProfilesView-76KGHTMK.js → ProfilesView-BZEBT6R5.js} +1 -1
  11. package/dist/{ProjectPicker-65YOU46H.js → ProjectPicker-J42MEJRQ.js} +1 -1
  12. package/dist/{SaveSessionPrompt-QD6BNTWO.js → SaveSessionPrompt-MKAIUVX7.js} +1 -1
  13. package/dist/SingleShotApp-TZZ2J7ZO.js +2 -0
  14. package/dist/{SummaryBox-N2B6DUDD.js → SummaryBox-JQJKGYDM.js} +1 -1
  15. package/dist/TestMdRunView-2YVGGFLU.js +2 -0
  16. package/dist/{TestrunEvidenceTable-3WLQVTF4.js → TestrunEvidenceTable-FYDS3ZVU.js} +1 -1
  17. package/dist/{WhoamiView-T26HA4ZZ.js → WhoamiView-F4PPB7SN.js} +1 -1
  18. package/dist/{app-download-XKZWFMEK.js → app-download-RA4CGTC5.js} +1 -1
  19. package/dist/{auth-PPJANIMZ.js → auth-TAT427C3.js} +1 -1
  20. package/dist/{binary-DKWWODT2.js → binary-OFPMBJ34.js} +1 -1
  21. package/dist/{bind-62AZYFAY.js → bind-LY362KX7.js} +2 -2
  22. package/dist/{bootstrap-6IJNZIPT.js → bootstrap-RCDB5OWA.js} +1 -1
  23. package/dist/bridge-E2NGMJYM.js +2 -0
  24. package/dist/{changelog-UTGJ7FSP.js → changelog-ZC3LHV2Z.js} +1 -1
  25. package/dist/{chunk-O5AS2ZIX.js → chunk-23MVD7GY.js} +1 -1
  26. package/dist/{chunk-X74PP5NJ.js → chunk-2GWMENG5.js} +1 -1
  27. package/dist/{chunk-75I46VTM.js → chunk-3AVBUEBL.js} +2 -2
  28. package/dist/chunk-3LXN6AV5.js +5 -0
  29. package/dist/{chunk-NOLYYHVG.js → chunk-3MVEGB2I.js} +1 -1
  30. package/dist/{chunk-42FHKRPA.js → chunk-4LVZLLTN.js} +3 -3
  31. package/dist/{chunk-73ULUGBM.js → chunk-4PWYSDZR.js} +1 -1
  32. package/dist/{chunk-7RAI77XD.js → chunk-4WEVTED6.js} +1 -1
  33. package/dist/{chunk-CGT4NFQN.js → chunk-5ACSALRU.js} +3 -3
  34. package/dist/{chunk-SX56MVUO.js → chunk-5VZAWKDF.js} +1 -1
  35. package/dist/{chunk-2BFXT7VQ.js → chunk-6HCY5LJO.js} +14 -14
  36. package/dist/{chunk-XGHMZJGI.js → chunk-7P6FSGRD.js} +2 -2
  37. package/dist/{chunk-UXH3RMQ7.js → chunk-7QUFOWMU.js} +1 -1
  38. package/dist/{chunk-O2APH6TZ.js → chunk-7XMDCGIZ.js} +1 -1
  39. package/dist/{chunk-LL5DQO6V.js → chunk-AAT4O22C.js} +1 -1
  40. package/dist/{chunk-FFFB5BXL.js → chunk-AGKE5WF3.js} +1 -1
  41. package/dist/{chunk-OH2NSBO6.js → chunk-BCJNIDS3.js} +1 -1
  42. package/dist/{chunk-3BHRGHIZ.js → chunk-BK42G6RI.js} +1 -1
  43. package/dist/{chunk-YHR2YAN5.js → chunk-BY2MU3ZS.js} +1 -1
  44. package/dist/{chunk-AC7BPO4X.js → chunk-C6JFTSIQ.js} +1 -1
  45. package/dist/chunk-CAOZKSQ3.js +8 -0
  46. package/dist/{chunk-DA57DXCF.js → chunk-CDWUZ54U.js} +1 -1
  47. package/dist/{chunk-3YX3RQXO.js → chunk-CR7UWQ76.js} +1 -1
  48. package/dist/{chunk-LR5DJ6EN.js → chunk-CVNHUDT4.js} +1 -1
  49. package/dist/{chunk-MLRO7OH3.js → chunk-DSWHEEHN.js} +1 -1
  50. package/dist/{chunk-6LGED4FC.js → chunk-E44OHYDS.js} +2 -2
  51. package/dist/{chunk-BJYGWXVP.js → chunk-ECIGXPLN.js} +1 -1
  52. package/dist/{chunk-QJ5O27SJ.js → chunk-EMAKLNDV.js} +1 -1
  53. package/dist/{chunk-B2ZGG7WM.js → chunk-F2XTOZTN.js} +1 -1
  54. package/dist/{chunk-ARG56PJG.js → chunk-FQFVAFWK.js} +1 -1
  55. package/dist/{chunk-SFTFHFG3.js → chunk-FWPRUGJJ.js} +1 -1
  56. package/dist/{chunk-4K5XTIJ6.js → chunk-FYJ62EVY.js} +1 -1
  57. package/dist/{chunk-N7ZRF5K3.js → chunk-G2ZMNVYN.js} +1 -1
  58. package/dist/{chunk-J7NRD4Q7.js → chunk-GCMJDOAE.js} +1 -1
  59. package/dist/{chunk-WBHSPN55.js → chunk-GGD7NKPL.js} +2 -2
  60. package/dist/{chunk-WOA7VCGA.js → chunk-H6S7L2I2.js} +1 -1
  61. package/dist/{chunk-RBHQXWR7.js → chunk-HBMNUT6E.js} +1 -1
  62. package/dist/{chunk-ZWHPIR2Z.js → chunk-HYCOX7AB.js} +2 -2
  63. package/dist/{chunk-RQLU4NDG.js → chunk-ICUTARPB.js} +1 -1
  64. package/dist/{chunk-YHVG7V3E.js → chunk-IJTSA34Q.js} +1 -1
  65. package/dist/chunk-IQDZ6YMY.js +18 -0
  66. package/dist/{chunk-ZA4M4O7E.js → chunk-IYOPWIG4.js} +2 -2
  67. package/dist/{chunk-7L25ZNNP.js → chunk-IZ5CTC6M.js} +1 -1
  68. package/dist/{chunk-GKZ2KVE6.js → chunk-J2LWXO55.js} +1 -1
  69. package/dist/{chunk-BAKJPQGU.js → chunk-KPL2XHYF.js} +1 -1
  70. package/dist/{chunk-WR42Q3HU.js → chunk-KYZKPNPQ.js} +1 -1
  71. package/dist/chunk-L45HDSJ7.js +15 -0
  72. package/dist/{chunk-4BBDKWM3.js → chunk-MD3S2RXN.js} +1 -1
  73. package/dist/{chunk-JH6E632O.js → chunk-MU3I453X.js} +1 -1
  74. package/dist/{chunk-C74ABM24.js → chunk-MZYPDLD3.js} +1 -1
  75. package/dist/{chunk-GESG672R.js → chunk-NADKZKGS.js} +1 -1
  76. package/dist/{chunk-2RMHDOP4.js → chunk-NMBFAIXZ.js} +1 -1
  77. package/dist/chunk-NN6UG2BE.js +11 -0
  78. package/dist/chunk-NPKB7EK3.js +7 -0
  79. package/dist/{chunk-MNE5VMHT.js → chunk-O3ZKP4DY.js} +1 -1
  80. package/dist/{chunk-KOL6ZWOQ.js → chunk-OUWOLCCS.js} +1 -1
  81. package/dist/{chunk-GPIXV7AV.js → chunk-OYY566GN.js} +1 -1
  82. package/dist/{chunk-3SPOJWRA.js → chunk-PDTFQGQF.js} +1 -1
  83. package/dist/{chunk-Q7XBMBMR.js → chunk-Q7LZ5QJV.js} +1 -1
  84. package/dist/{chunk-X5276I5H.js → chunk-QMZLIHBS.js} +2 -2
  85. package/dist/chunk-QXUPBIV3.js +93 -0
  86. package/dist/{chunk-SQDQADWD.js → chunk-RCYYE6ED.js} +1 -1
  87. package/dist/{chunk-6F6YI3ZG.js → chunk-SF5QPR6T.js} +1 -1
  88. package/dist/{chunk-22QIVSQR.js → chunk-SWTJMTBY.js} +1 -1
  89. package/dist/{chunk-O6U2HU5M.js → chunk-TBYYPGHF.js} +1 -1
  90. package/dist/{chunk-SGHP44WS.js → chunk-TGBXIV7O.js} +1 -1
  91. package/dist/{chunk-P3JUE2RM.js → chunk-TWZ6NZWE.js} +4 -4
  92. package/dist/{chunk-L6MOO4WT.js → chunk-U466V5JN.js} +1 -1
  93. package/dist/{chunk-OO5GMBVI.js → chunk-U7BVK5IX.js} +1 -1
  94. package/dist/{chunk-IQ7NGOAT.js → chunk-UAFCBZ3P.js} +1 -1
  95. package/dist/{chunk-JKX57HA7.js → chunk-UEG4LJD6.js} +1 -1
  96. package/dist/{chunk-NBMLBCJ3.js → chunk-ULGFPKC7.js} +1 -1
  97. package/dist/{chunk-KOPP4CJW.js → chunk-V4JR5JCK.js} +1 -1
  98. package/dist/{chunk-ZKEOPIQ3.js → chunk-VATOIZYG.js} +1 -1
  99. package/dist/{chunk-WILT62DP.js → chunk-VOTIGXQ4.js} +1 -1
  100. package/dist/chunk-VWOAEF7J.js +2 -0
  101. package/dist/{chunk-VNFCX2SH.js → chunk-W4Y3PG7F.js} +1 -1
  102. package/dist/{chunk-RH6KFHJB.js → chunk-WECVT7WE.js} +1 -1
  103. package/dist/{chunk-QPUVOVD7.js → chunk-WML5KSGQ.js} +1 -1
  104. package/dist/{chunk-PGU64EWQ.js → chunk-WPNNRMTP.js} +1 -1
  105. package/dist/{chunk-IQ7GPETF.js → chunk-XGL3RSI5.js} +1 -1
  106. package/dist/{chunk-JJJSDDQ2.js → chunk-Z2GDSCPS.js} +1 -1
  107. package/dist/chunk-Z4KRSLAM.js +2 -0
  108. package/dist/{chunk-EMSLJTYN.js → chunk-Z5DGFN7R.js} +1 -1
  109. package/dist/{chunk-NDCRJXYF.js → chunk-ZLIYWELJ.js} +1 -1
  110. package/dist/{chunk-K7K23DIQ.js → chunk-ZYEFWJNZ.js} +1 -1
  111. package/dist/{config-3AKWRTFS.js → config-WETHR632.js} +1 -1
  112. package/dist/{cover-cmd-ZLAWMEC2.js → cover-cmd-J3CTQT3R.js} +1 -1
  113. package/dist/{credentials-Q4WH5CBN.js → credentials-RQPAP5KY.js} +1 -1
  114. package/dist/{deps-bundle-RVZK6LZJ.js → deps-bundle-F47ZDYIM.js} +1 -1
  115. package/dist/{deps-resolve-6F2U4TJP.js → deps-resolve-URKD4QCB.js} +1 -1
  116. package/dist/{dispatch-46BETGXY.js → dispatch-KOZAJQDW.js} +1 -1
  117. package/dist/{doctor-WRPG56HH.js → doctor-J44UKALC.js} +1 -1
  118. package/dist/{evidence-XWR32HWP.js → evidence-KRNDKDCT.js} +1 -1
  119. package/dist/{evolve-cmd-27ZQN6YB.js → evolve-cmd-CEYGGIWA.js} +1 -1
  120. package/dist/{explain-cmd-JCJTXVZY.js → explain-cmd-USGRZFBY.js} +1 -1
  121. package/dist/{extract-bind-D5BYYGYA.js → extract-bind-X4QRQX53.js} +2 -2
  122. package/dist/{extract-cmd-CCYW7FIY.js → extract-cmd-RKEE32FN.js} +1 -1
  123. package/dist/{gaps-cmd-3VJKQ25D.js → gaps-cmd-WL6P6YKS.js} +1 -1
  124. package/dist/{generate-headless-2M6UT3IK.js → generate-headless-LSQHOR3G.js} +2 -2
  125. package/dist/index.js +147 -149
  126. package/dist/{ingest-cmd-HVTUK264.js → ingest-cmd-TQ4ARSDE.js} +1 -1
  127. package/dist/install-47CRHVU6.js +2 -0
  128. package/dist/{interactive-bind-OJCYNQPI.js → interactive-bind-FPC4RYEW.js} +3 -3
  129. package/dist/{lifecycle-cmd-GWFGUGTC.js → lifecycle-cmd-DB5EFO2O.js} +1 -1
  130. package/dist/{list-cmd-AXDW64OY.js → list-cmd-UWGJRGKF.js} +1 -1
  131. package/dist/{list-commands-YNZ6EFIF.js → list-commands-Q77CAQJ2.js} +1 -1
  132. package/dist/login-flow-RSNR5HY2.js +2 -0
  133. package/dist/{maintenance-cmd-QEMK6YNV.js → maintenance-cmd-EJ2RAMWB.js} +1 -1
  134. package/dist/{mobile-prompts-OXHA5GHJ.js → mobile-prompts-PPPPKRS2.js} +1 -1
  135. package/dist/objective-variable-gate-BCKULIFQ.js +2 -0
  136. package/dist/{open-provider-E5VUGFNE.js → open-provider-XIGABCD3.js} +1 -1
  137. package/dist/{persist-recorded-session-KWPH37HI.js → persist-recorded-session-MK4HCDOY.js} +1 -1
  138. package/dist/pipeline-XDWHEZ5S.js +2 -0
  139. package/dist/prepare-target-NR3MTLLI.js +2 -0
  140. package/dist/{reconcile-cmd-V7TDYETT.js → reconcile-cmd-VJPEY7YD.js} +1 -1
  141. package/dist/{reconcile-deps-X6IGH4CA.js → reconcile-deps-T5YX6HRG.js} +2 -2
  142. package/dist/{reconcile-engine-OGXSIE7O.js → reconcile-engine-GELPXSLV.js} +1 -1
  143. package/dist/{recording-banner-IZWN2XFY.js → recording-banner-3ET3PMSV.js} +1 -1
  144. package/dist/registry-3XMA4FOC.js +2 -0
  145. package/dist/{require-project-folder-PEEUITK6.js → require-project-folder-ZLKONKKP.js} +1 -1
  146. package/dist/{resolve-run-intent-JGXXE45Y.js → resolve-run-intent-3SXUS676.js} +1 -1
  147. package/dist/{resolver-TY7XLJBN.js → resolver-G7NGWACO.js} +1 -1
  148. package/dist/{review-cmd-74YTPT7E.js → review-cmd-6DNGXV5E.js} +1 -1
  149. package/dist/{run-DN4XARP2.js → run-MUVZVTTC.js} +1 -1
  150. package/dist/{run-GRYWYKIH.js → run-UJLRTKTO.js} +1 -1
  151. package/dist/{run-test-md-DFCKCQ4T.js → run-test-md-RI5RXVFU.js} +2 -2
  152. package/dist/{skill-installer-GRU3HOYF.js → skill-installer-CAO2NJZP.js} +1 -1
  153. package/dist/{spawner-LNMD4NJF.js → spawner-H6IDWY5U.js} +1 -1
  154. package/dist/{store-guard-Q4MYZQHF.js → store-guard-PIA2DYZX.js} +1 -1
  155. package/dist/{sync-cmd-H6Y5EB3L.js → sync-cmd-VFVTFIIJ.js} +1 -1
  156. package/dist/{sync-setup-THGRBKTA.js → sync-setup-R7BZDE24.js} +1 -1
  157. package/dist/tcg-generate-QADJKNYZ.js +2 -0
  158. package/dist/testmd-actions-EXSVQRHQ.js +2 -0
  159. package/dist/testmd-sync-2CXNIPJ7.js +2 -0
  160. package/dist/token-refresh-5TVNSL4U.js +2 -0
  161. package/dist/{validate-basic-RCBEELSB.js → validate-basic-MN5NDCT2.js} +1 -1
  162. package/dist/{variable-receipt-JHRW73Z6.js → variable-receipt-SIABUC74.js} +1 -1
  163. package/dist/{verdicts-XFXDRND4.js → verdicts-ZXXBKTOZ.js} +1 -1
  164. package/dist/{version-check-Z774UWW3.js → version-check-TDGK5REB.js} +1 -1
  165. package/dist/{view-cmd-I4LQGJ2X.js → view-cmd-RLO7AP4X.js} +1 -1
  166. package/dist/{walk-session-FP52IGLB.js → walk-session-ATWNUGHX.js} +1 -1
  167. package/dist/{with-telemetry-P6RUPWBH.js → with-telemetry-CLSDKQAG.js} +1 -1
  168. package/package.json +11 -11
  169. package/dist/EvidenceViewOffer-5MB4ZXKM.js +0 -2
  170. package/dist/FolderPicker-SYFXH6D5.js +0 -2
  171. package/dist/SingleShotApp-U54ETXS3.js +0 -2
  172. package/dist/TestMdRunView-WA4TC5PT.js +0 -2
  173. package/dist/bridge-X5DEJL6F.js +0 -2
  174. package/dist/chunk-53MPG2J3.js +0 -11
  175. package/dist/chunk-IICQ5KRD.js +0 -5
  176. package/dist/chunk-KN65CUNT.js +0 -15
  177. package/dist/chunk-L4M7753M.js +0 -2
  178. package/dist/chunk-LBNADEQN.js +0 -8
  179. package/dist/chunk-LNV7C2YO.js +0 -6
  180. package/dist/chunk-M7DN6FO3.js +0 -17
  181. package/dist/chunk-ZZTZJPT2.js +0 -88
  182. package/dist/install-5WJLE7XT.js +0 -2
  183. package/dist/login-flow-PRXFPRYZ.js +0 -2
  184. package/dist/objective-variable-gate-76GYUHEP.js +0 -2
  185. package/dist/pipeline-A2OGF4XW.js +0 -2
  186. package/dist/prepare-target-P6BWJZBZ.js +0 -2
  187. package/dist/registry-GOLIFVK5.js +0 -2
  188. package/dist/tcg-generate-SZZ7MJXY.js +0 -2
  189. package/dist/testmd-actions-MRIUOOXO.js +0 -2
  190. package/dist/testmd-sync-UYVJ47BN.js +0 -2
  191. package/dist/token-refresh-KN5JK2U4.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-AHXOKBVE.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-IE3OO5GI.js";import{C as j}from"./chunk-GP7WD4UY.js";import{g as N}from"./chunk-3N6IAVD5.js";import{x as ge}from"./chunk-B2ZGG7WM.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-AHXOKBVE.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-IE3OO5GI.js";import{C as j}from"./chunk-GP7WD4UY.js";import{g as N}from"./chunk-3N6IAVD5.js";import{x as ge}from"./chunk-F2XTOZTN.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-PPJANIMZ.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-TAT427C3.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-PPJANIMZ.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-TAT427C3.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-PPJANIMZ.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-PPJANIMZ.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-LNMD4NJF.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-TAT427C3.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-TAT427C3.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-H6IDWY5U.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{b as Bt}from"./chunk-ZMNJBUAO.js";import{f as tr}from"./chunk-W5TTF7GB.js";import{a as Ft}from"./chunk-I7TIGB7K.js";import{a as te,c as Yt,e as Zt,f as qe,g as Qt,h as nr}from"./chunk-MLRO7OH3.js";import{a as Xt,b as rr,c as sr,d as ir,e as dt,f as or}from"./chunk-UHT5SVP5.js";import{a as ke,b as qt,c as Gt,d as Lt,e as Vt}from"./chunk-FFFB5BXL.js";import{a as zt}from"./chunk-L2TV4G56.js";import{a as Kt,b as Jt}from"./chunk-BZAGVBCX.js";import{c as Wt}from"./chunk-52WM3XYO.js";import{b as Nt}from"./chunk-YKTYVJBN.js";import{a as Ht,e as jt}from"./chunk-CRZUBDJ3.js";import{a as er}from"./chunk-GX3FPJUG.js";import{i as Mt}from"./chunk-AHXOKBVE.js";import{a as $e,b as ct}from"./chunk-ALCE5RLK.js";import{e as Ut}from"./chunk-4K5XTIJ6.js";import{a as Fe}from"./chunk-J7NRD4Q7.js";import{a as Se}from"./chunk-IE3OO5GI.js";import{c as nt}from"./chunk-5LJRZI7S.js";import{C as ee,m as be,q as Be}from"./chunk-GP7WD4UY.js";import{H as It,b as Ot}from"./chunk-3N6IAVD5.js";import{f as at}from"./chunk-FQNQVC5O.js";import{d as me}from"./chunk-AKX4VRRR.js";import{a as At}from"./chunk-5EOX4MEY.js";import{appendFileSync as wr,mkdirSync as ut,rmdirSync as br,writeFileSync as lt}from"fs";import{dirname as mr,extname as Sr,join as ce}from"path";var X=class extends Error{code;constructor(e,a){super(`${e}: ${a}`),this.name="ProposalAdapterError",this.code=e}};function cr(r){return r.version===2}var ar=8;function vr(r){let e=/^extract@(\d+)$/.exec(r??"");return e?Number.parseInt(e[1],10):null}var yr=r=>typeof r=="object"&&r!==null&&"op"in r;function Ge(r,e,a){return{anchor:r.anchor,quote:r.quote,...a||r.source_id!==e?{source_id:r.source_id}:{}}}function dr(r,e,a={}){let m=vr(a.templateVersion),x=m!==null&&m>=5,_=m!==null&&m<5,y=r.archived!=null&&r.archived.length>0&&m!==null&&m<5;if(y&&a.warn?.(`dropped ${r.archived.length} archive op(s): the bound extract template @${m} never described archiving \u2014 nothing was archived; the use-cases still land`),!x&&r.read_basis.length!==1)throw new X("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${r.read_basis.length}`);if(r.read_basis.length===0)throw new X("READ_BASIS_COUNT","read_basis must not be empty");let v=r.read_basis[0],h=r.read_basis.length>1,$=r.use_cases.map(i=>{if(_&&i.cite.length!==1)throw new X("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);if(i.cite.length<1||i.cite.length>ar)throw new X("CITE_COUNT",`${i.temp_ref}: 1..${ar} cites allowed, got ${i.cite.length}`);let M=(f,re)=>{if(!x&&f!==v.source_id)throw new X("SOURCE_MISMATCH",`${re}: cite source ${f} != read_basis source ${v.source_id} (single-source)`)};M(i.cite[0].source_id,i.temp_ref);let P=i.cite.map(f=>(M(f.source_id,i.temp_ref),Ge(f,v.source_id,x&&(h||f.source_id!==v.source_id)))),l=(i.updated?.criteria??[]).some(yr);if(!x&&l)throw new X("CRITERIA_OPS_UNSUPPORTED",`${i.temp_ref}: op-union updated.criteria (keep/set/remove) needs an extract@5+ binding \u2014 this session is bound to ${a.templateVersion??"an unversioned template"}`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:P[0],...P.length>1?{cites:P}:{},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:{...i.updated.title!=null?{title:i.updated.title}:{},...i.updated.description!=null?{description:i.updated.description}:{},...i.updated.summary!=null?{summary:i.updated.summary}:{},...i.updated.actors!=null?{actors:i.updated.actors}:{},...i.updated.value!=null?{value:i.updated.value}:{},...i.updated.risk!=null?{risk:i.updated.risk}:{},...i.updated.criteria!=null?{criteria:l?i.updated.criteria.map(f=>f.op==="set"?{op:"set",text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}:f.op==="keep"?{op:"keep",ref:f.ref,text:f.text}:{op:"remove",ref:f.ref,text:f.text,reason:f.reason}):i.updated.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.updated.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{}}}:{},...i.change_note!=null?{change_note:i.change_note}:{}}});return{version:1,read_basis:e,source:{source_id:v.source_id,source_cid:v.source_cid},use_cases:$,...h?{sources:r.read_basis.map(i=>({source_id:i.source_id,source_cid:i.source_cid}))}:{},...r.extraction_of!=null&&r.extraction_of.length>0?{extraction_claims:r.extraction_of.map(i=>({source_id:i.source_id,completeness:i.completeness}))}:{},...r.archived!=null&&r.archived.length>0&&!y?{archived:r.archived.map(i=>({target:i.target,reason:i.reason,basis:i.basis}))}:{}}}function ur(r){let{contextDir:e,graph:a}=r,m=r.maxDigestBytes??4096,x={},_=[];for(let[h,$]of a.heads){if(x[h]=$,typeof $!="string")continue;let i=a.mediaOf($),M=a.getNode($)?.content?.blob;if(typeof M=="string")if(i.format==="image")_.push({source_id:h,cid:$,format:"image",blobRef:{path:Se(e,M),cid:M}});else{let P=$e(e,a,$)?.toString("utf8")??"";_.push({source_id:h,cid:$,format:i.format,text:P})}}_.sort((h,$)=>h.source_id<$.source_id?-1:1);let y=[];for(let h of a.byLabel(me.STYLENOTE).sort(($,i)=>$.cid<i.cid?-1:1))a.superseded.has(h.cid)||y.push(`\u2022 ${String(h.content.statement)} [${String(h.content.learned_from_kind)}]`);let v="";for(let h of y){if(Buffer.byteLength(v+h+`
2
+ import{b as Bt}from"./chunk-ZMNJBUAO.js";import{f as tr}from"./chunk-W5TTF7GB.js";import{a as Ft}from"./chunk-I7TIGB7K.js";import{a as te,c as Yt,e as Zt,f as qe,g as Qt,h as nr}from"./chunk-DSWHEEHN.js";import{a as Xt,b as rr,c as sr,d as ir,e as dt,f as or}from"./chunk-UHT5SVP5.js";import{a as ke,b as qt,c as Gt,d as Lt,e as Vt}from"./chunk-AGKE5WF3.js";import{a as zt}from"./chunk-L2TV4G56.js";import{a as Kt,b as Jt}from"./chunk-BZAGVBCX.js";import{c as Wt}from"./chunk-52WM3XYO.js";import{b as Nt}from"./chunk-YKTYVJBN.js";import{a as Ht,e as jt}from"./chunk-CRZUBDJ3.js";import{a as er}from"./chunk-GX3FPJUG.js";import{i as Mt}from"./chunk-AHXOKBVE.js";import{a as $e,b as ct}from"./chunk-ALCE5RLK.js";import{e as Ut}from"./chunk-FYJ62EVY.js";import{a as Fe}from"./chunk-GCMJDOAE.js";import{a as Se}from"./chunk-IE3OO5GI.js";import{c as nt}from"./chunk-5LJRZI7S.js";import{C as ee,m as be,q as Be}from"./chunk-GP7WD4UY.js";import{H as It,b as Ot}from"./chunk-3N6IAVD5.js";import{f as at}from"./chunk-FQNQVC5O.js";import{d as me}from"./chunk-AKX4VRRR.js";import{a as At}from"./chunk-5EOX4MEY.js";import{appendFileSync as wr,mkdirSync as ut,rmdirSync as br,writeFileSync as lt}from"fs";import{dirname as mr,extname as Sr,join as ce}from"path";var X=class extends Error{code;constructor(e,a){super(`${e}: ${a}`),this.name="ProposalAdapterError",this.code=e}};function cr(r){return r.version===2}var ar=8;function vr(r){let e=/^extract@(\d+)$/.exec(r??"");return e?Number.parseInt(e[1],10):null}var yr=r=>typeof r=="object"&&r!==null&&"op"in r;function Ge(r,e,a){return{anchor:r.anchor,quote:r.quote,...a||r.source_id!==e?{source_id:r.source_id}:{}}}function dr(r,e,a={}){let m=vr(a.templateVersion),x=m!==null&&m>=5,_=m!==null&&m<5,y=r.archived!=null&&r.archived.length>0&&m!==null&&m<5;if(y&&a.warn?.(`dropped ${r.archived.length} archive op(s): the bound extract template @${m} never described archiving \u2014 nothing was archived; the use-cases still land`),!x&&r.read_basis.length!==1)throw new X("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${r.read_basis.length}`);if(r.read_basis.length===0)throw new X("READ_BASIS_COUNT","read_basis must not be empty");let v=r.read_basis[0],h=r.read_basis.length>1,$=r.use_cases.map(i=>{if(_&&i.cite.length!==1)throw new X("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);if(i.cite.length<1||i.cite.length>ar)throw new X("CITE_COUNT",`${i.temp_ref}: 1..${ar} cites allowed, got ${i.cite.length}`);let M=(f,re)=>{if(!x&&f!==v.source_id)throw new X("SOURCE_MISMATCH",`${re}: cite source ${f} != read_basis source ${v.source_id} (single-source)`)};M(i.cite[0].source_id,i.temp_ref);let P=i.cite.map(f=>(M(f.source_id,i.temp_ref),Ge(f,v.source_id,x&&(h||f.source_id!==v.source_id)))),l=(i.updated?.criteria??[]).some(yr);if(!x&&l)throw new X("CRITERIA_OPS_UNSUPPORTED",`${i.temp_ref}: op-union updated.criteria (keep/set/remove) needs an extract@5+ binding \u2014 this session is bound to ${a.templateVersion??"an unversioned template"}`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:P[0],...P.length>1?{cites:P}:{},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:{...i.updated.title!=null?{title:i.updated.title}:{},...i.updated.description!=null?{description:i.updated.description}:{},...i.updated.summary!=null?{summary:i.updated.summary}:{},...i.updated.actors!=null?{actors:i.updated.actors}:{},...i.updated.value!=null?{value:i.updated.value}:{},...i.updated.risk!=null?{risk:i.updated.risk}:{},...i.updated.criteria!=null?{criteria:l?i.updated.criteria.map(f=>f.op==="set"?{op:"set",text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}:f.op==="keep"?{op:"keep",ref:f.ref,text:f.text}:{op:"remove",ref:f.ref,text:f.text,reason:f.reason}):i.updated.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.updated.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{}}}:{},...i.change_note!=null?{change_note:i.change_note}:{}}});return{version:1,read_basis:e,source:{source_id:v.source_id,source_cid:v.source_cid},use_cases:$,...h?{sources:r.read_basis.map(i=>({source_id:i.source_id,source_cid:i.source_cid}))}:{},...r.extraction_of!=null&&r.extraction_of.length>0?{extraction_claims:r.extraction_of.map(i=>({source_id:i.source_id,completeness:i.completeness}))}:{},...r.archived!=null&&r.archived.length>0&&!y?{archived:r.archived.map(i=>({target:i.target,reason:i.reason,basis:i.basis}))}:{}}}function ur(r){let{contextDir:e,graph:a}=r,m=r.maxDigestBytes??4096,x={},_=[];for(let[h,$]of a.heads){if(x[h]=$,typeof $!="string")continue;let i=a.mediaOf($),M=a.getNode($)?.content?.blob;if(typeof M=="string")if(i.format==="image")_.push({source_id:h,cid:$,format:"image",blobRef:{path:Se(e,M),cid:M}});else{let P=$e(e,a,$)?.toString("utf8")??"";_.push({source_id:h,cid:$,format:i.format,text:P})}}_.sort((h,$)=>h.source_id<$.source_id?-1:1);let y=[];for(let h of a.byLabel(me.STYLENOTE).sort(($,i)=>$.cid<i.cid?-1:1))a.superseded.has(h.cid)||y.push(`\u2022 ${String(h.content.statement)} [${String(h.content.learned_from_kind)}]`);let v="";for(let h of y){if(Buffer.byteLength(v+h+`
3
3
  `,"utf8")>m)break;v+=h+`
4
4
  `}return{read_basis:x,sources:_,styleNoteDigest:v}}function lr(r,e){let a=ur({contextDir:r,graph:e}).styleNoteDigest;return a.length>0?a:void 0}function mt(r,e,a,m,x){let _=null,y=()=>_??=x&&Object.keys(x).length>0?Promise.resolve(x):Ut().catch(()=>({}));return{contextDir:r,rootSid:e,locks:at(r,e),probe:m??Ft(r,{resolveAlias:async v=>qt(v,{env:process.env,auth:await y()}),embed:async(v,h)=>Gt(v,h,{env:process.env,auth:await y()}),readVector:(v,h)=>Lt(r,v,h),writeVector:(v,h,$)=>Vt(r,v,h,$)}),...a?.length?{reservedEventIds:a}:{}}}function ht(r,e){let a=[],m=[];for(let x of r.use_cases){let _=x.matches_existing;_?.cid&&e.hasNode(_.cid)?a.push({ref:_.cid,expectedTip:e.tipOf(_.cid)}):m.push({tempRef:x.temp_ref,title:String(x.title??""),probeText:String(x.title??"")})}return{verb:"extract",ucTargets:a,newBuCandidates:m,sourcePins:[{source_id:r.source.source_id,source_cid:r.source.source_cid}],readBasis:r.read_basis??null}}function $r(r,e){let a=(r.images??[]).filter(m=>m.delivery==="selected");if(a.length!==0)return a.map(m=>({ref:m.ref,...m.page!==void 0?{page:m.page}:{},...m.loc!==void 0?{loc:m.loc}:{},media_type:m.media_type,blob_ref:{path:Se(e,m.blob),cid:m.blob}}))}function kr(r){return r.length>8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>12&&r.toString("ascii",0,4)==="RIFF"&&r.toString("ascii",8,12)==="WEBP"?"image/webp":null}function Le(r){return r.toISOString().replace(/[-:]/g,"").slice(0,15)}function hr(r){return r.startsWith("su-conv-")?`conv-${Ot(Buffer.from(r,"utf8")).slice(0,8)}`:r}function pr(r){return r.source_id.startsWith("su-conv-")?"the conversation":r.source_id}function Rr(r,e,a){return`reading ${pr(r)}${a>1?` (source ${e} of ${a})`:""}`}function Re(r){return r.toLowerCase().trim().replace(/\s+/g," ")}function gr(r,e){let a=new Map,m=new Map,x=new Map;for(let{cid:y,content:v}of e.byLabel(me.USECASE)){if(e.superseded.has(y))continue;(e.trust.get(y)==="archived"?x:m).set(Re(String(v.title??"")),y)}let _=y=>e.trust.get(y)==="archived"?{cid:y,archived:!0,reason:e.archivedReason.get(y)}:{cid:y};for(let y of r.use_cases){if(y.matches_existing){let $=y.matches_existing.cid;if(e.superseded.has($)){let i=e.tipOf($);$=e.superseded.has(i)?null:i}if($!==null){a.set(y.temp_ref,_($));continue}}let v=m.get(Re(y.title));if(v){a.set(y.temp_ref,{cid:v});continue}let h=x.get(Re(y.title));h&&a.set(y.temp_ref,_(h))}return a}var fr=/^(\S+)\.criteria\[(\d+)\]/;function Cr(r,e,a){if(e.length===0||!e.every(x=>fr.test(x.detail)))return!1;let m=new Map;for(let x of e){let _=fr.exec(x.detail),y=m.get(_[1])??new Set;y.add(Number(_[2])),m.set(_[1],y)}for(let x of r.use_cases){let _=m.get(x.temp_ref);_?.size&&(x.criteria=(x.criteria??[]).filter((y,v)=>!_.has(v)),a(`${x.temp_ref}: dropped ${_.size} criteria with unverifiable cites \u2014 committed without them (criteria are hints, not oracles)`))}return!0}async function gt(r,e,a,m,x=()=>{},_,y){let v=(h,$)=>x(h,$,r.session_id);return Zt(r,e,a,m,x,{async onProposalEvent(h){let $=h,i=null,M=null;if(cr($))try{i=dr($,r.read_basis,{templateVersion:y?.()??null,warn:P=>{e.out(`warning: ${P}`),v("adapter",{warn:P})}}),v("adapter",{ok:!0,use_cases:i.use_cases.length})}catch(P){M=P instanceof X?P.message:String(P),v("adapter",{ok:!1,error:M})}else i=$;return i&&i.use_cases.length===0&&(e.out("warning: the agent proposed ZERO use-cases for this source"),e.emit?.({type:"warning",code:"ZERO_USE_CASES",message:"the agent proposed ZERO use-cases for this source"})),i&&_&&await _(i),{proposal:i,error:M}}})}var Dr=new Set(["agent","ci","override"]);async function Ss(r,e){let a=`ext-${Le(e.now?.()??new Date)}-lk${Math.random().toString(36).slice(2,8)}`,x=at(e.contextDir,a,e.now?{now:e.now}:void 0).tryAcquire([{kind:"extract"}],{hold:"session",verb:"extract"});if("contended"in x){let _=x.contended.holder,y=`another extraction is running on this context${_?` (pid ${_.pid})`:""} \u2014 retry when it finishes`;return e.out(y),e.emit?.({type:"error",message:y,code:"EXTRACT_LOCKED"}),2}try{return await Er(r,e)}finally{x.release()}}async function Er(r,e){let a=r.mode??"interactive";if(r.posture==="reconcile"){if(r.trust==="hold"){let o="error: --trust hold has no meaning here \u2014 a reconcile IS the review; drop the flag";return e.out(`${o} [TRUST_USAGE]`),e.emit?.({type:"error",message:o,code:"TRUST_USAGE"}),2}if(!r.source||!r.changeContext){let o="reconcile posture needs a pinned source and its change context \u2014 internal wiring fault";return e.out(`error: ${o}`),e.emit?.({type:"error",message:o,code:"POSTURE_USAGE"}),2}if(a==="ci"){let o="reconcile posture is not available under --mode ci \u2014 a held changeset needs a durable session; use --mode agent";return e.out(`error: ${o}`),e.emit?.({type:"error",message:o,code:"POSTURE_USAGE"}),2}}if(r.trust==="hold"&&a==="interactive")return e.out("error: --trust hold only applies to headless runs \u2014 in interactive chat you review items in-session anyway; use --mode agent to hold everything for review"),e.emit?.({type:"error",message:"error: --trust hold only applies to headless runs \u2014 use --mode agent",code:"TRUST_USAGE"}),2;if(a==="interactive"){if(!e.isTTY)return e.out("extract: --mode interactive needs a TTY (use --mode agent|ci|override headless)"),2}else if(!Dr.has(a))return e.out(`extract: unknown mode "${a}" \u2014 interactive | agent | ci | override`),2;if(r.trust!==void 0){if(a==="ci")return e.out("error: --trust is not available under --mode ci (ci is fail-closed \u2014 no trust dials)"),e.emit?.({type:"error",message:"error: --trust is not available under --mode ci",code:"TRUST_UNDER_CI"}),2;if(r.trust!=="auto"&&r.trust!=="hold")return e.out(`error: --trust must be auto | hold, got '${r.trust}'`),e.emit?.({type:"error",message:`error: --trust must be auto | hold, got '${r.trust}'`,code:"TRUST_USAGE"}),2}let m=e.telemetry?.enabled?e.telemetry:void 0,x=Le(e.now?.()??new Date),_=m?At(m.ids.context_instance_id??null,"extract",m.ids.session_id):ce(e.contextDir,"logs",`extract-${x}.log`);ut(mr(_),{recursive:!0});let y=`run-${x}-${Math.random().toString(36).slice(2,8)}`,v=o=>o==="error"||o==="failed_proposal"?"error":o==="repair_respawn"?"warn":"info",h=(o,u,s)=>{try{wr(_,JSON.stringify({ts:new Date().toISOString(),level:v(o),run_id:y,...m?{user_session_id:m.ids.session_id}:{},...s?{session_id:s}:{},kind:o,data:u})+`
5
5
  `)}catch{}m?.wireTrace(o,u,s)};{let o=e.out;e.out=u=>{h("transcript",{line:u}),o(u)}}e.chat||e.out(`trace: ${te(_)}`),e.emit?.({type:"run_start",mode:a,trace:_,...m?{session:m.ids.session_id}:{}});let $=Nt();if($&&e.out($),e.preflightTurn){let o=await e.preflightTurn();if(h("preflight",o),!o.ok)return e.out(o.message??"error: turn-endpoint preflight failed"),e.emit?.({type:"error",message:o.message??"error: turn-endpoint preflight failed",code:"PREFLIGHT"}),2}let i=ee(e.contextDir),M=lr(e.contextDir,i),P=r.sources?.length?r.sources:r.source?[r.source]:[];if(P.length>0){if(r.resume){let o="error: --source cannot be combined with --resume (the resumed session already has its scope)";return e.out(o),e.emit?.({type:"error",message:o,code:"SOURCE_WITH_RESUME"}),2}for(let o of P){let u=i.heads.get(o);if(typeof u!="string"){let s=u===null?`error: --source ${o} was ingested but is retired \u2014 re-ingest it to extract again`:`error: --source ${o} is not an ingested source (kane-cli context list shows them)`;return e.out(s),e.emit?.({type:"error",message:s,code:"SOURCE_UNKNOWN"}),2}}}let l=null,f=null;if(r.resume){try{{let c=await or(e.contextDir,r.resume,i,{verb:"extract",deps:{onWarn:C=>e.out(`note: ${C}`)}});{let C=Object.keys(c.handle.state.read_basis??{});if(C.length>1){let B=`error: session ${r.resume} spans ${C.length} sources \u2014 multi-source resume isn't supported yet; committed work is preserved (re-run kane-cli context extract for anything remaining)`;return e.out(B),e.emit?.({type:"error",message:B,code:"MULTI_SOURCE_RESUME"}),c.handle.release(),2}f=c,h("resume_kind",{kind:c.view.pointer===null?"bare-base":c.view.pointer.at==="final"?"pause":"crash"}),l={handle:c.handle,represent:c.represent,questions:c.questions,staleBasis:c.drift.map(B=>B.subject)}}}}catch(c){let C=c instanceof Error?c.message:String(c);return e.out(`error: ${C}`),e.emit?.({type:"error",message:`error: ${C}`,...c instanceof dt?{code:c.code}:{}}),c instanceof dt?2:1}let o=f?null:Xt(l.handle.state.verb,"extract",r.resume);if(o)return e.out(o.message),e.emit?.({type:"error",message:o.message,code:o.code}),l.handle.release(),2;let u=l.handle.state.change_basis;if(u&&(i.heads.get(u.source_id)??null)!==u.new_head){let c=`error: ${u.source_id} moved while this reconcile extraction was paused \u2014 its recorded change context no longer matches; re-run kane-cli maintain reconcile against the current file (session ${r.resume} is defunct and can be ignored)`;return e.out(c),e.emit?.({type:"error",message:c,code:"CHANGE_BASIS_MOVED"}),l.handle.release(),2}if(f&&f.view.pointer!==null&&f.drift.length>0){if(!await e.confirmStale(`changed since the pause: ${f.drift.map(C=>C.subject).join(", ")} \u2014 re-ground and continue against the current versions?`)){let C=`resume aborted: the context moved since the pause (${f.drift.map(B=>B.subject).join(", ")}) \u2014 session ${r.resume} is preserved`;return e.out(C),e.emit?.({type:"error",message:C,code:"RESUME_DRIFT"}),l.handle.release(),2}}else l.staleBasis.length>0&&e.out(`note: changed since the pause: ${l.staleBasis.join(", ")} \u2014 re-presented items may be stale`);let s=[...new Set([...l.handle.state.held_receipts??[],...f?.view.kane?.held_receipts??[]])];if(s.length>0)if(e.chat?.holdReceipt)for(let c of s)e.chat.holdReceipt(c);else e={...e,initialMessage:[s.join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{y as n}from"./chunk-B2ZGG7WM.js";import{a as s}from"./chunk-HCBYKLMW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
2
+ import{y as n}from"./chunk-F2XTOZTN.js";import{a as s}from"./chunk-HCBYKLMW.js";import{a,b as i}from"./chunk-C44QQJR4.js";import{e as r}from"./chunk-UR6MHSHU.js";var o=r(s(),1);function g({bindings:c,suppressEscBack:p=!1,escBackLabel:m="back to chat"}){let e=c.map(t=>`${t.keys} ${t.label}`);return p||e.push(`esc \xB7 ${m}`),(0,o.jsx)(a,{marginTop:1,children:(0,o.jsx)(i,{color:n.dim,children:e.join(" \xB7 ")})})}export{g as a};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as g}from"./chunk-B2ZGG7WM.js";import{readFileSync as o,writeFileSync as h,mkdirSync as u,readdirSync as a,unlinkSync as s,existsSync as l,chmodSync as f}from"fs";import{join as n,dirname as P}from"path";var d=class{baseDir;profilesDir;configFile;constructor(t=g){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(o(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){u(this.baseDir,{recursive:!0,mode:448}),h(this.configFile,JSON.stringify(t,null,2)+`
2
+ import{b as g}from"./chunk-F2XTOZTN.js";import{readFileSync as o,writeFileSync as h,mkdirSync as u,readdirSync as a,unlinkSync as s,existsSync as l,chmodSync as f}from"fs";import{join as n,dirname as P}from"path";var d=class{baseDir;profilesDir;configFile;constructor(t=g){this.baseDir=t,this.profilesDir=n(t,"profiles"),this.configFile=n(t,"config.json")}readConfig(){try{return JSON.parse(o(this.configFile,"utf-8"))}catch{return{}}}writeConfig(t){u(this.baseDir,{recursive:!0,mode:448}),h(this.configFile,JSON.stringify(t,null,2)+`
3
3
  `),f(this.configFile,384)}getActiveProfile(){return this.readConfig().active_profile??null}setActiveProfile(t){let i=this.readConfig();i.active_profile=t,this.writeConfig(i)}getDefaultEnv(){return this.readConfig().default_env??"prod"}setDefaultEnv(t){let i=this.readConfig();i.default_env=t,this.writeConfig(i)}credentialsPath(t,i){return n(this.profilesDir,t,i,"credentials")}clientPath(t,i){return n(this.profilesDir,t,i,"client.json")}basicAuthPath(t,i){return n(this.profilesDir,t,i,"basic-auth")}profileConfigPath(t,i){return n(this.profilesDir,t,i,"profile-config.json")}saveProfileConfig(t,i,r){let e=this.loadProfileConfig(t,i)??{};this.writeSecure(this.profileConfigPath(t,i),{...e,...r})}loadProfileConfig(t,i){try{return JSON.parse(o(this.profileConfigPath(t,i),"utf-8"))}catch{return null}}writeSecure(t,i){try{u(P(t),{recursive:!0,mode:448}),h(t,JSON.stringify(i,null,2)+`
4
4
  `),f(t,384)}catch(r){let e=r instanceof Error?r.message:String(r);process.stderr.write(`[auth] Failed to save credentials: ${e}
5
5
  `)}}saveCredentials(t,i,r){this.writeSecure(this.credentialsPath(t,i),r)}loadCredentials(t,i){try{return JSON.parse(o(this.credentialsPath(t,i),"utf-8"))}catch{return null}}saveClient(t,i,r){this.writeSecure(this.clientPath(t,i),r)}loadClient(t,i){try{return JSON.parse(o(this.clientPath(t,i),"utf-8"))}catch{return null}}getActiveCredentials(){let t=this.getActiveProfile();if(!t)return{credentials:null,profile:null,env:null};let i=this.getDefaultEnv();return{credentials:this.loadCredentials(t,i),profile:t,env:i}}saveBasicAuth(t,i,r){this.writeSecure(this.basicAuthPath(t,i),r)}loadBasicAuth(t,i){try{return JSON.parse(o(this.basicAuthPath(t,i),"utf-8"))}catch{return null}}deleteBasicAuth(t,i){try{s(this.basicAuthPath(t,i))}catch{}}resolveAuth(){let t=this.getActiveProfile();if(!t)return null;let i=this.getDefaultEnv(),r=this.loadBasicAuth(t,i);return r?{method:"basic",...r,profile:t,env:i}:this.loadCredentials(t,i)?{method:"oauth",profile:t,env:i}:null}listProfiles(){let t=[];try{for(let i of a(this.profilesDir)){let r=n(this.profilesDir,i);try{for(let e of a(r)){let c=n(r,e),v=l(n(c,"credentials")),p=l(n(c,"client.json")),y=l(n(c,"basic-auth"));(v||p||y)&&t.push({profile:i,env:e})}}catch{}}}catch{}return t}deleteProfile(t,i){try{s(this.credentialsPath(t,i))}catch{}if(this.getActiveProfile()===t){let r=this.readConfig();delete r.active_profile,this.writeConfig(r)}}deleteProfileFull(t,i){if(i){try{s(this.credentialsPath(t,i))}catch{}try{s(this.clientPath(t,i))}catch{}try{s(this.basicAuthPath(t,i))}catch{}try{s(this.profileConfigPath(t,i))}catch{}}else try{let r=n(this.profilesDir,t);for(let e of a(r)){try{s(n(r,e,"credentials"))}catch{}try{s(n(r,e,"client.json"))}catch{}try{s(n(r,e,"basic-auth"))}catch{}try{s(n(r,e,"profile-config.json"))}catch{}}}catch{}}};export{d as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as h}from"./chunk-4BBDKWM3.js";import{a as f}from"./chunk-N7ZRF5K3.js";import{a as m}from"./chunk-OH2NSBO6.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:g,log:t}=c,e=null,u=null;if(l&&g)e={username:l,access_key:g},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,p=new h(v.controllerBaseUrl,b,y,t),s=await p.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:p,resolvedCreds:s}}export{o as a,k as b};
2
+ import{a as h}from"./chunk-MD3S2RXN.js";import{a as f}from"./chunk-G2ZMNVYN.js";import{a as m}from"./chunk-BCJNIDS3.js";var i=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:o,env:a,usernameFlag:l,accessKeyFlag:g,log:t}=c,e=null,u=null;if(l&&g)e={username:l,access_key:g},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=o.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=o.getActiveCredentials();if(!r)throw new i("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:o,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new i(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,p=new h(v.controllerBaseUrl,b,y,t),s=await p.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:p,resolvedCreds:s}}export{i as a,k as b};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as k}from"./chunk-ARG56PJG.js";import{y as u}from"./chunk-B2ZGG7WM.js";import{a as f}from"./chunk-HCBYKLMW.js";import{a as m,b as s,k as b}from"./chunk-C44QQJR4.js";import{e as p}from"./chunk-UR6MHSHU.js";function B(t){let e=t;return e=e.replace(/@TS\{([^}]+)\}/g,"@S{$1}"),e=e.replace(/@TS-(\d+)/g,(o,i)=>`@S${parseInt(i,10)}.C1`),e=e.replace(/@TS(\d+)/g,(o,i)=>`@S${parseInt(i,10)}`),e=e.replace(/\\n/g,`
2
+ import{a as k}from"./chunk-FQFVAFWK.js";import{y as u}from"./chunk-F2XTOZTN.js";import{a as f}from"./chunk-HCBYKLMW.js";import{a as m,b as s,k as b}from"./chunk-C44QQJR4.js";import{e as p}from"./chunk-UR6MHSHU.js";function B(t){let e=t;return e=e.replace(/@TS\{([^}]+)\}/g,"@S{$1}"),e=e.replace(/@TS-(\d+)/g,(o,i)=>`@S${parseInt(i,10)}.C1`),e=e.replace(/@TS(\d+)/g,(o,i)=>`@S${parseInt(i,10)}`),e=e.replace(/\\n/g,`
3
3
  `),e}var c=p(f(),1),S=t=>t!==void 0&&/[A-Za-z0-9]/.test(t);function x(t){let e=[],o="",i=()=>{o&&(e.push({text:o}),o="")},d=(a,l,r)=>(a===0||!S(t[a-1]))&&(l+r>=t.length||!S(t[l+r])),n=0;for(;n<t.length;){let a=t.slice(n,n+2),l=t[n];if(a==="**"||a==="__"){let r=t.indexOf(a,n+2);if(r!==-1&&r>n+2&&(a==="**"||d(n,r,2))){i(),e.push({text:t.slice(n+2,r),bold:!0}),n=r+2;continue}}if(l==="`"){let r=t.indexOf("`",n+1);if(r!==-1&&r>n+1){i(),e.push({text:t.slice(n+1,r),code:!0}),n=r+1;continue}}if(l==="*"||l==="_"){let r=t.indexOf(l,n+1);if(r!==-1&&r>n+1&&(l==="*"||d(n,r,1))){i(),e.push({text:t.slice(n+1,r),italic:!0}),n=r+1;continue}}o+=l,n+=1}return i(),e.length===0&&e.push({text:""}),e}function h(t){return t.map((e,o)=>(0,c.jsx)(s,{bold:e.bold,italic:e.italic,color:e.code?u.dim:void 0,children:e.text},o))}function T(t){return t.split(`
4
4
  `).map(e=>{if(e.trim()==="")return{kind:"blank"};let o=e.match(/^\s*[-*+]\s+(.*)$/);if(o)return{kind:"bullet",segs:x(o[1])};let i=e.match(/^\s*(\d+)\.\s+(.*)$/);if(i)return{kind:"numbered",n:i[1],segs:x(i[2])};let d=e.match(/^#{1,6}\s+(.*)$/);return d?{kind:"heading",segs:x(d[1])}:{kind:"para",segs:x(e)}})}function R(t,e,o=""){switch(t.kind){case"blank":return(0,c.jsx)(s,{children:o||" "},e);case"heading":return(0,c.jsxs)(s,{bold:!0,children:[o,h(t.segs)]},e);case"bullet":return(0,c.jsx)(m,{marginLeft:1,children:(0,c.jsxs)(s,{children:[o,"\u2022 ",h(t.segs)]})},e);case"numbered":return(0,c.jsx)(m,{marginLeft:1,children:(0,c.jsxs)(s,{children:[o,`${t.n}. `,h(t.segs)]})},e);default:return(0,c.jsxs)(s,{children:[o,h(t.segs)]},e)}}function $({text:t,accent:e=u.generateAccent}){let o=T(B(t)),{stdout:i}=b(),d=i?.columns??80;return(0,c.jsxs)(m,{marginBottom:1,children:[(0,c.jsx)(m,{width:2,flexShrink:0,children:(0,c.jsx)(s,{color:e,children:"\u2503"})}),(0,c.jsx)(m,{flexDirection:"column",width:d-2,children:o.map((n,a)=>R(n,a))})]})}var g=p(f(),1),I=5;function C({thinking:t,expanded:e,thinkingDone:o,maxLines:i=I}){if(!e)return(0,g.jsxs)(m,{paddingX:1,children:[(0,g.jsx)(s,{color:u.dim,children:o?"\u2237 thinking complete ":"\u2237 thinking\u2026 "}),(0,g.jsx)(s,{color:u.muted,children:o?"(ctrl+t to view)":"(ctrl+t to show)"})]});let d=t.split(`
5
5
  `),n=Math.max(0,d.length-i),a=n>0?d.slice(-i).join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as C}from"./chunk-X74PP5NJ.js";import{k as Z}from"./chunk-6F6YI3ZG.js";import{a as D}from"./chunk-YCCUBQY4.js";import{a as M}from"./chunk-RBHQXWR7.js";import{a as z}from"./chunk-RQLU4NDG.js";import{b as W}from"./chunk-AC7BPO4X.js";import{a as B}from"./chunk-OO5GMBVI.js";import{e as V}from"./chunk-Z7S3IWUX.js";import{y as o}from"./chunk-B2ZGG7WM.js";import{a as A}from"./chunk-HCBYKLMW.js";import{a as n,b as t,i as L}from"./chunk-C44QQJR4.js";import{a as N}from"./chunk-6YGTRKDT.js";import{e as g}from"./chunk-UR6MHSHU.js";var T=g(A(),1);function te(e){let i=e.kind==="simulator";switch(e.state){case"ready":return i?"Booted":"Running";case"stopped":return i?"Shutdown":"Stopped";case"unauthorized":return"UNAUTHORIZED";case"offline":return"Offline"}}function re(e){switch(e.state){case"unauthorized":return"accept the authorisation prompt on the device, then reopen this list";case"offline":return e.kind==="simulator"?"not responding \u2014 open Simulator.app to inspect it":"not responding \u2014 reconnect it, or restart the emulator";default:return}}function ne(e,i){let m=i.id!==void 0?{...i,id:z(i.id)}:i,c=e.virtualName!==void 0?{...e,virtualName:z(e.virtualName)}:e;return V(c,m)}function ie(e){return e.virtualName??e.displayName}function ae(e,i){let m=e.state==="ready"||e.state==="stopped",c=re(e),b=e.osVersion?` (${e.osVersion})`:"";return{id:e.id,label:`${ie(e)}${b} \xB7 ${te(e)}`,...i&&ne(e,i)?{isActive:!0}:{},...m?{}:{disabled:!0},...!m&&c?{disabledHint:c}:{}}}function le(e){return e==="emulator"?"No Android emulator found. Make sure an emulator exists on this machine (Android Studio \u2192 Device Manager), then reopen this list.":e==="simulator"?"No iOS simulator found. Make sure a simulator exists on this machine (Xcode \u2192 Windows \u2192 Devices and Simulators), then reopen this list.":"No emulator or simulator found. Make sure one exists on this machine, then reopen this list."}function he({targets:e,preselectedTarget:i,preselectedId:m,busyMessage:c,onSelect:b,onCancel:f,kind:l}){if(c)return(0,T.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,T.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,T.jsxs)(n,{marginTop:1,children:[(0,T.jsx)(C,{}),(0,T.jsxs)(t,{color:o.secondary,children:[" ",c]})]})]});if(e.length===0)return(0,T.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,T.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,T.jsx)(n,{marginTop:1,children:(0,T.jsx)(t,{color:o.dim,children:le(l)})})]});let d=e.map(r=>ae(r,i)),p=i?d.find(r=>r.isActive)?.id??null:m?e.find(r=>r.id===m||r.virtualName===m)?.id??null:null,a=new Map(e.map(r=>[r.id,r]));return(0,T.jsx)(M,{title:"Device",items:d,itemNoun:"devices",defaultActiveId:p,preserveSelectionById:!0,onSelect:r=>{let y=a.get(r.id);y&&b(y)},onCancel:f})}var x=g(N(),1);var u=g(A(),1),q=50,G=500;function pe(e){return`${e.name} (${e.appId})`}function Pe({kind:e,listApps:i,onSelect:m,onManualEntry:c,onCancel:b,busyMessage:f}){let[l,d]=(0,x.useState)([]),[p,a]=(0,x.useState)(!0),[r,y]=(0,x.useState)(!1),[Q,O]=(0,x.useState)(!1),[E,H]=(0,x.useState)(null),[w,J]=(0,x.useState)(""),[j,U]=(0,x.useState)(!1),$=(0,x.useRef)(!0),R=(0,x.useRef)(0);if((0,x.useEffect)(()=>{let h=++R.current,k=w.trim();$.current?a(!0):k&&O(!0),y(!0),H(null),U(!1),(async()=>{let I=[];try{for(let P=0;;P+=q){let X=await i({limit:q,offset:P,search:k});if(h!==R.current)return;if(I.push(...X.apps),d([...I]),$.current&&(a(!1),$.current=!1),O(!1),X.apps.length===0||I.length>=X.total)break;if(I.length>=G){U(!0);break}}}catch(P){if(h!==R.current)return;H(P instanceof Error?P.message:String(P)),a(!1),O(!1)}finally{h===R.current&&y(!1)}})()},[w,i]),L((h,k)=>{if(k.tab){c();return}k.escape&&b()},{isActive:!!E&&!f}),f)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,u.jsxs)(n,{marginTop:1,children:[(0,u.jsx)(C,{}),(0,u.jsxs)(t,{color:o.secondary,children:[" ",f]})]})]});if(E)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.red,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.red,bold:!0,children:"App under test"}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.red,children:"Could not load your uploads."})}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.dim,children:E})}),(0,u.jsx)(B,{bindings:[{keys:"tab",label:"tab to enter an app id"}],escBackLabel:"back to chat"})]});let ee=new Map(l.map(h=>[h.appId,h])),oe=l.map(h=>({id:h.appId,label:pe(h)})),_=!p&&!r&&l.length===0&&!w.trim()?e==="simulator"?"No simulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":"No emulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":null;return(0,u.jsx)(M,{title:"App under test",items:oe,loading:p,loadingText:"Loading your uploads\u2026",loadingMore:r,searching:Q,itemNoun:"uploads",preserveSelectionById:!0,onSearch:J,onTab:c,extraHint:"tab to enter an id",footer:_?(0,u.jsx)(t,{color:o.dim,children:_}):j?(0,u.jsx)(t,{color:o.dim,children:`Showing the first ${G} \u2014 type to search the rest.`}):void 0,onSelect:h=>{let k=ee.get(h.id);k&&m({appId:k.appId,name:k.name})},onCancel:b})}var Y=g(N(),1);var S=g(A(),1),se={emulator:["apk"],simulator:["zip"]};function ce(e){return Z(e.trim())}function Oe({kind:e,onBack:i,onSelect:m,onCancel:c}){let[b,f]=(0,Y.useState)(""),[l,d]=(0,Y.useState)(null),p=e==="emulator"?".apk":".zip";return(0,S.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,S.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,S.jsx)(n,{marginTop:1,children:(0,S.jsx)(t,{color:o.dim,children:`Path to a build (${p}): `})}),(0,S.jsxs)(n,{marginTop:1,children:[(0,S.jsx)(t,{color:o.dim,children:" "}),(0,S.jsx)(D,{value:b,onChange:a=>{f(a),l&&d(null)},onSubmit:a=>{let r=ce(a);if(!r){d(a.trim()?`Not a build \u2014 expected ${p}.`:"Enter the path to a build.");return}if(!se[e].includes(r.kind)){d(`${r.kind} builds don't run on a ${e} \u2014 expected ${p}.`);return}d(null),m(r).then(y=>{!y.ok&&y.error&&d(y.error)})},onCancel:i,placeholder:e==="emulator"?"/path/to/app-debug.apk":"/path/to/MyApp.zip"})]}),l&&(0,S.jsx)(n,{marginTop:1,children:(0,S.jsx)(t,{color:o.red,children:l})}),(0,S.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this build"}],escBackLabel:"back"})]})}var F=g(N(),1);var v=g(A(),1);function de(e){return[{value:"local",label:"Local build",hint:e==="emulator"?".apk":".zip",available:!0},{value:"uploaded",label:"Uploaded app",hint:"an app id from your cloud uploads",available:!0}]}function Ye({kind:e,onSelect:i,onCancel:m}){let c=de(e),[b,f]=(0,F.useState)(0),[l,d]=(0,F.useState)(null);return L((p,a)=>{if(a.escape){m();return}if(a.upArrow&&f(r=>Math.max(0,r-1)),a.downArrow&&f(r=>Math.min(c.length-1,r+1)),a.return){let r=c[b];if(!r.available){d("That source isn't available \u2014 choose a local build for now.");return}d(null),i(r.value)}}),(0,v.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,v.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,v.jsx)(n,{marginTop:1,flexDirection:"column",children:c.map((p,a)=>{let r=a===b,y=p.available?r?o.orange:void 0:o.muted;return(0,v.jsxs)(n,{children:[(0,v.jsxs)(t,{color:y,children:[r?"\u276F ":" ",p.label]}),(0,v.jsxs)(t,{color:o.dim,children:[" ",p.hint]})]},p.value)})}),l&&(0,v.jsx)(n,{marginTop:1,children:(0,v.jsx)(t,{color:o.red,children:l})}),(0,v.jsx)(B,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}var K=g(N(),1);var s=g(A(),1);function qe({busyMessage:e,onSubmit:i,onBack:m}){let[c,b]=(0,K.useState)(""),[f,l]=(0,K.useState)(null);return e?(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(C,{}),(0,s.jsxs)(t,{color:o.secondary,children:[" ",e]})]})]}):(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsx)(n,{marginTop:1,children:(0,s.jsx)(t,{color:o.dim,children:"App id from your cloud uploads:"})}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(t,{color:o.dim,children:" "}),(0,s.jsx)(D,{value:c,onChange:d=>{b(d),f&&l(null)},onSubmit:d=>{let p=d.trim();if(!p){l("Enter an app id.");return}if(!W(p)){l("That doesn't look like an app id \u2014 they start with APP.");return}l(null),i(p).then(a=>{!a.ok&&a.error&&l(a.error)})},onCancel:m,placeholder:"APP1016032231178585590501450"})]}),f&&(0,s.jsxs)(n,{marginTop:1,flexDirection:"column",children:[(0,s.jsx)(t,{color:o.red,children:f}),(0,s.jsx)(t,{color:o.dim,children:"Enter a valid app id \u2014 copy it from your cloud uploads."})]}),(0,s.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this app"}],escBackLabel:"back"})]})}export{he as a,Pe as b,Oe as c,Ye as d,qe as e};
2
+ import{a as C}from"./chunk-2GWMENG5.js";import{k as Z}from"./chunk-SF5QPR6T.js";import{a as D}from"./chunk-YCCUBQY4.js";import{a as M}from"./chunk-HBMNUT6E.js";import{a as z}from"./chunk-ICUTARPB.js";import{b as W}from"./chunk-C6JFTSIQ.js";import{a as B}from"./chunk-U7BVK5IX.js";import{e as V}from"./chunk-Z7S3IWUX.js";import{y as o}from"./chunk-F2XTOZTN.js";import{a as A}from"./chunk-HCBYKLMW.js";import{a as n,b as t,i as L}from"./chunk-C44QQJR4.js";import{a as N}from"./chunk-6YGTRKDT.js";import{e as g}from"./chunk-UR6MHSHU.js";var T=g(A(),1);function te(e){let i=e.kind==="simulator";switch(e.state){case"ready":return i?"Booted":"Running";case"stopped":return i?"Shutdown":"Stopped";case"unauthorized":return"UNAUTHORIZED";case"offline":return"Offline"}}function re(e){switch(e.state){case"unauthorized":return"accept the authorisation prompt on the device, then reopen this list";case"offline":return e.kind==="simulator"?"not responding \u2014 open Simulator.app to inspect it":"not responding \u2014 reconnect it, or restart the emulator";default:return}}function ne(e,i){let m=i.id!==void 0?{...i,id:z(i.id)}:i,c=e.virtualName!==void 0?{...e,virtualName:z(e.virtualName)}:e;return V(c,m)}function ie(e){return e.virtualName??e.displayName}function ae(e,i){let m=e.state==="ready"||e.state==="stopped",c=re(e),b=e.osVersion?` (${e.osVersion})`:"";return{id:e.id,label:`${ie(e)}${b} \xB7 ${te(e)}`,...i&&ne(e,i)?{isActive:!0}:{},...m?{}:{disabled:!0},...!m&&c?{disabledHint:c}:{}}}function le(e){return e==="emulator"?"No Android emulator found. Make sure an emulator exists on this machine (Android Studio \u2192 Device Manager), then reopen this list.":e==="simulator"?"No iOS simulator found. Make sure a simulator exists on this machine (Xcode \u2192 Windows \u2192 Devices and Simulators), then reopen this list.":"No emulator or simulator found. Make sure one exists on this machine, then reopen this list."}function he({targets:e,preselectedTarget:i,preselectedId:m,busyMessage:c,onSelect:b,onCancel:f,kind:l}){if(c)return(0,T.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,T.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,T.jsxs)(n,{marginTop:1,children:[(0,T.jsx)(C,{}),(0,T.jsxs)(t,{color:o.secondary,children:[" ",c]})]})]});if(e.length===0)return(0,T.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,T.jsx)(t,{color:o.orange,bold:!0,children:"Device"}),(0,T.jsx)(n,{marginTop:1,children:(0,T.jsx)(t,{color:o.dim,children:le(l)})})]});let d=e.map(r=>ae(r,i)),p=i?d.find(r=>r.isActive)?.id??null:m?e.find(r=>r.id===m||r.virtualName===m)?.id??null:null,a=new Map(e.map(r=>[r.id,r]));return(0,T.jsx)(M,{title:"Device",items:d,itemNoun:"devices",defaultActiveId:p,preserveSelectionById:!0,onSelect:r=>{let y=a.get(r.id);y&&b(y)},onCancel:f})}var x=g(N(),1);var u=g(A(),1),q=50,G=500;function pe(e){return`${e.name} (${e.appId})`}function Pe({kind:e,listApps:i,onSelect:m,onManualEntry:c,onCancel:b,busyMessage:f}){let[l,d]=(0,x.useState)([]),[p,a]=(0,x.useState)(!0),[r,y]=(0,x.useState)(!1),[Q,O]=(0,x.useState)(!1),[E,H]=(0,x.useState)(null),[w,J]=(0,x.useState)(""),[j,U]=(0,x.useState)(!1),$=(0,x.useRef)(!0),R=(0,x.useRef)(0);if((0,x.useEffect)(()=>{let h=++R.current,k=w.trim();$.current?a(!0):k&&O(!0),y(!0),H(null),U(!1),(async()=>{let I=[];try{for(let P=0;;P+=q){let X=await i({limit:q,offset:P,search:k});if(h!==R.current)return;if(I.push(...X.apps),d([...I]),$.current&&(a(!1),$.current=!1),O(!1),X.apps.length===0||I.length>=X.total)break;if(I.length>=G){U(!0);break}}}catch(P){if(h!==R.current)return;H(P instanceof Error?P.message:String(P)),a(!1),O(!1)}finally{h===R.current&&y(!1)}})()},[w,i]),L((h,k)=>{if(k.tab){c();return}k.escape&&b()},{isActive:!!E&&!f}),f)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,u.jsxs)(n,{marginTop:1,children:[(0,u.jsx)(C,{}),(0,u.jsxs)(t,{color:o.secondary,children:[" ",f]})]})]});if(E)return(0,u.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.red,paddingX:2,paddingY:1,children:[(0,u.jsx)(t,{color:o.red,bold:!0,children:"App under test"}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.red,children:"Could not load your uploads."})}),(0,u.jsx)(n,{marginTop:1,children:(0,u.jsx)(t,{color:o.dim,children:E})}),(0,u.jsx)(B,{bindings:[{keys:"tab",label:"tab to enter an app id"}],escBackLabel:"back to chat"})]});let ee=new Map(l.map(h=>[h.appId,h])),oe=l.map(h=>({id:h.appId,label:pe(h)})),_=!p&&!r&&l.length===0&&!w.trim()?e==="simulator"?"No simulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":"No emulator builds uploaded to this account yet \u2014 press Tab to enter an app id.":null;return(0,u.jsx)(M,{title:"App under test",items:oe,loading:p,loadingText:"Loading your uploads\u2026",loadingMore:r,searching:Q,itemNoun:"uploads",preserveSelectionById:!0,onSearch:J,onTab:c,extraHint:"tab to enter an id",footer:_?(0,u.jsx)(t,{color:o.dim,children:_}):j?(0,u.jsx)(t,{color:o.dim,children:`Showing the first ${G} \u2014 type to search the rest.`}):void 0,onSelect:h=>{let k=ee.get(h.id);k&&m({appId:k.appId,name:k.name})},onCancel:b})}var Y=g(N(),1);var S=g(A(),1),se={emulator:["apk"],simulator:["zip"]};function ce(e){return Z(e.trim())}function Oe({kind:e,onBack:i,onSelect:m,onCancel:c}){let[b,f]=(0,Y.useState)(""),[l,d]=(0,Y.useState)(null),p=e==="emulator"?".apk":".zip";return(0,S.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,S.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,S.jsx)(n,{marginTop:1,children:(0,S.jsx)(t,{color:o.dim,children:`Path to a build (${p}): `})}),(0,S.jsxs)(n,{marginTop:1,children:[(0,S.jsx)(t,{color:o.dim,children:" "}),(0,S.jsx)(D,{value:b,onChange:a=>{f(a),l&&d(null)},onSubmit:a=>{let r=ce(a);if(!r){d(a.trim()?`Not a build \u2014 expected ${p}.`:"Enter the path to a build.");return}if(!se[e].includes(r.kind)){d(`${r.kind} builds don't run on a ${e} \u2014 expected ${p}.`);return}d(null),m(r).then(y=>{!y.ok&&y.error&&d(y.error)})},onCancel:i,placeholder:e==="emulator"?"/path/to/app-debug.apk":"/path/to/MyApp.zip"})]}),l&&(0,S.jsx)(n,{marginTop:1,children:(0,S.jsx)(t,{color:o.red,children:l})}),(0,S.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this build"}],escBackLabel:"back"})]})}var F=g(N(),1);var v=g(A(),1);function de(e){return[{value:"local",label:"Local build",hint:e==="emulator"?".apk":".zip",available:!0},{value:"uploaded",label:"Uploaded app",hint:"an app id from your cloud uploads",available:!0}]}function Ye({kind:e,onSelect:i,onCancel:m}){let c=de(e),[b,f]=(0,F.useState)(0),[l,d]=(0,F.useState)(null);return L((p,a)=>{if(a.escape){m();return}if(a.upArrow&&f(r=>Math.max(0,r-1)),a.downArrow&&f(r=>Math.min(c.length-1,r+1)),a.return){let r=c[b];if(!r.available){d("That source isn't available \u2014 choose a local build for now.");return}d(null),i(r.value)}}),(0,v.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,v.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,v.jsx)(n,{marginTop:1,flexDirection:"column",children:c.map((p,a)=>{let r=a===b,y=p.available?r?o.orange:void 0:o.muted;return(0,v.jsxs)(n,{children:[(0,v.jsxs)(t,{color:y,children:[r?"\u276F ":" ",p.label]}),(0,v.jsxs)(t,{color:o.dim,children:[" ",p.hint]})]},p.value)})}),l&&(0,v.jsx)(n,{marginTop:1,children:(0,v.jsx)(t,{color:o.red,children:l})}),(0,v.jsx)(B,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],escBackLabel:"back"})]})}var K=g(N(),1);var s=g(A(),1);function qe({busyMessage:e,onSubmit:i,onBack:m}){let[c,b]=(0,K.useState)(""),[f,l]=(0,K.useState)(null);return e?(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(C,{}),(0,s.jsxs)(t,{color:o.secondary,children:[" ",e]})]})]}):(0,s.jsxs)(n,{flexDirection:"column",borderStyle:"round",borderColor:o.orange,paddingX:2,paddingY:1,children:[(0,s.jsx)(t,{color:o.orange,bold:!0,children:"App under test"}),(0,s.jsx)(n,{marginTop:1,children:(0,s.jsx)(t,{color:o.dim,children:"App id from your cloud uploads:"})}),(0,s.jsxs)(n,{marginTop:1,children:[(0,s.jsx)(t,{color:o.dim,children:" "}),(0,s.jsx)(D,{value:c,onChange:d=>{b(d),f&&l(null)},onSubmit:d=>{let p=d.trim();if(!p){l("Enter an app id.");return}if(!W(p)){l("That doesn't look like an app id \u2014 they start with APP.");return}l(null),i(p).then(a=>{!a.ok&&a.error&&l(a.error)})},onCancel:m,placeholder:"APP1016032231178585590501450"})]}),f&&(0,s.jsxs)(n,{marginTop:1,flexDirection:"column",children:[(0,s.jsx)(t,{color:o.red,children:f}),(0,s.jsx)(t,{color:o.dim,children:"Enter a valid app id \u2014 copy it from your cloud uploads."})]}),(0,s.jsx)(B,{bindings:[{keys:"\u21B5",label:"use this app"}],escBackLabel:"back"})]})}export{he as a,Pe as b,Oe as c,Ye as d,qe as e};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as br}from"./chunk-OPL2MIQG.js";import{a as yr}from"./chunk-TU6IMGWO.js";import{a as hr}from"./chunk-TNBF5OMZ.js";import{a as gr,b as mr}from"./chunk-HOA4VWSD.js";import{a as fr}from"./chunk-KZG4E5RM.js";import{c as pr,d as ur}from"./chunk-52WM3XYO.js";import{a as cr,d as lr}from"./chunk-BB2W35TW.js";import{a as or,g as xt,h as ir,n as ar,p as dr}from"./chunk-AHXOKBVE.js";import{e as ct,f as jt,g as Tt,h as Le}from"./chunk-YHVG7V3E.js";import{A as er,B as qt,C as te,D as it,E as fe,F as tr,G as ne,H as _e,I as at,J as nr,K as Y,L as Fe,M as dt,N as Re,O as rr,P as sr,S as Be,a as Bn,b as Dn,c as Ae,d as Pe,e as le,f as st,g as Hn,h as Gn,i as pe,j as Un,k as qe,l as je,m as Kn,n as ot,o as ue,p as Yn,q as zn,r as Qn,s as Zn,t as At,u as Pt,v as X,w as Te,x as Xn,y as Nt,z as xe}from"./chunk-6LGED4FC.js";import{b as Fn,d as Ln,g as Ct,h as K}from"./chunk-H6TNBKGR.js";import{a as R,b as Mn,d as ee,e as Ne,h as Jn,i as Vn,k as Wn}from"./chunk-YLQHY4A7.js";import{a as jn,b as Tn,e as xn}from"./chunk-WILT62DP.js";import{b as sn,f as on,h as an,k as dn,l as cn}from"./chunk-22QIVSQR.js";import{b as Ot,d as ce}from"./chunk-IE3OO5GI.js";import{a as qn}from"./chunk-CH273NAE.js";import{b as ve}from"./chunk-BKM2LWU2.js";import{A as tt,B as nt,C as rt,D as Nn,q as In,r as Sn,s as En,t as On,u as Cn,v as An,w as Pn}from"./chunk-GP7WD4UY.js";import{B as oe,C as wn,D as vn,F as $e,G as Xe,J as $n,K as Ce,O as kn,P as et,U as _n,W as Rn,X as ke,b as rn,c as de,f as Et,h as ln,l as pn,m as un,o as Oe,p as O,q as fn,t as hn,v as gn,x as mn,y as yn,z as bn}from"./chunk-3N6IAVD5.js";import{d as Qe,e as Ze}from"./chunk-AKX4VRRR.js";import{existsSync as Ue,readdirSync as ss,readFileSync as os,realpathSync as Do,statSync as Mo,writeFileSync as Ho}from"fs";import{basename as Rt,join as Ke,relative as Go,resolve as tn}from"path";import{randomBytes as ks}from"crypto";var wr=8,De=()=>Wn(ks(8).toString("hex")),vr=(e,t)=>e!==null&&Buffer.from(e).equals(Buffer.from(t)),_s=[["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(!vr(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:wr},(o,i)=>e.putIfAbsent(t,Buffer.from(`contender ${i}`))))).filter(o=>o==="created").length;return r===1?null:`${r} of ${wr} 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)?vr(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 _s){let i;try{i=await o(e)}catch(s){if(s instanceof R){if(!(s.code==="SYNC_LOCATION_REFUSED_WRITE"&&r.startsWith("P1")&&await $r(e)))throw s;n=`${r}: ${s.message}`,t=3;break}n=`${r}: ${s instanceof Error?s.message:String(s)}`,t=r.startsWith("P1")&&await $r(e)?3:2;break}if(i!==null){n=`${r}: ${i}`,t=2;break}}return{tier:Math.max(t,e.ceilingTier),detail:n}}async function $r(e){try{return!await e.head(De())}catch(t){if(t instanceof R)throw t;return!1}}import{existsSync as Rs,readFileSync as Rr}from"fs";import{join as Is}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=bn(e),a;try{gn(e),a=Ss(e,d)}catch(F){throw F instanceof hn?new R("SYNC_REBASE_PENDING",`${F.message.split(";")[0]}; nothing was pushed`,F.remedy):F}finally{c()}let l=a.map(F=>Es(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 _r(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 br}from"./chunk-OPL2MIQG.js";import{a as yr}from"./chunk-TU6IMGWO.js";import{a as hr}from"./chunk-TNBF5OMZ.js";import{a as gr,b as mr}from"./chunk-HOA4VWSD.js";import{a as fr}from"./chunk-KZG4E5RM.js";import{c as pr,d as ur}from"./chunk-52WM3XYO.js";import{a as cr,d as lr}from"./chunk-BB2W35TW.js";import{a as or,g as xt,h as ir,n as ar,p as dr}from"./chunk-AHXOKBVE.js";import{e as ct,f as jt,g as Tt,h as Le}from"./chunk-IJTSA34Q.js";import{A as er,B as qt,C as te,D as it,E as fe,F as tr,G as ne,H as _e,I as at,J as nr,K as Y,L as Fe,M as dt,N as Re,O as rr,P as sr,S as Be,a as Bn,b as Dn,c as Ae,d as Pe,e as le,f as st,g as Hn,h as Gn,i as pe,j as Un,k as qe,l as je,m as Kn,n as ot,o as ue,p as Yn,q as zn,r as Qn,s as Zn,t as At,u as Pt,v as X,w as Te,x as Xn,y as Nt,z as xe}from"./chunk-E44OHYDS.js";import{b as Fn,d as Ln,g as Ct,h as K}from"./chunk-H6TNBKGR.js";import{a as R,b as Mn,d as ee,e as Ne,h as Jn,i as Vn,k as Wn}from"./chunk-YLQHY4A7.js";import{a as jn,b as Tn,e as xn}from"./chunk-VOTIGXQ4.js";import{b as sn,f as on,h as an,k as dn,l as cn}from"./chunk-SWTJMTBY.js";import{b as Ot,d as ce}from"./chunk-IE3OO5GI.js";import{a as qn}from"./chunk-CH273NAE.js";import{b as ve}from"./chunk-BKM2LWU2.js";import{A as tt,B as nt,C as rt,D as Nn,q as In,r as Sn,s as En,t as On,u as Cn,v as An,w as Pn}from"./chunk-GP7WD4UY.js";import{B as oe,C as wn,D as vn,F as $e,G as Xe,J as $n,K as Ce,O as kn,P as et,U as _n,W as Rn,X as ke,b as rn,c as de,f as Et,h as ln,l as pn,m as un,o as Oe,p as O,q as fn,t as hn,v as gn,x as mn,y as yn,z as bn}from"./chunk-3N6IAVD5.js";import{d as Qe,e as Ze}from"./chunk-AKX4VRRR.js";import{existsSync as Ue,readdirSync as ss,readFileSync as os,realpathSync as Do,statSync as Mo,writeFileSync as Ho}from"fs";import{basename as Rt,join as Ke,relative as Go,resolve as tn}from"path";import{randomBytes as ks}from"crypto";var wr=8,De=()=>Wn(ks(8).toString("hex")),vr=(e,t)=>e!==null&&Buffer.from(e).equals(Buffer.from(t)),_s=[["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(!vr(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:wr},(o,i)=>e.putIfAbsent(t,Buffer.from(`contender ${i}`))))).filter(o=>o==="created").length;return r===1?null:`${r} of ${wr} 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)?vr(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 _s){let i;try{i=await o(e)}catch(s){if(s instanceof R){if(!(s.code==="SYNC_LOCATION_REFUSED_WRITE"&&r.startsWith("P1")&&await $r(e)))throw s;n=`${r}: ${s.message}`,t=3;break}n=`${r}: ${s instanceof Error?s.message:String(s)}`,t=r.startsWith("P1")&&await $r(e)?3:2;break}if(i!==null){n=`${r}: ${i}`,t=2;break}}return{tier:Math.max(t,e.ceilingTier),detail:n}}async function $r(e){try{return!await e.head(De())}catch(t){if(t instanceof R)throw t;return!1}}import{existsSync as Rs,readFileSync as Rr}from"fs";import{join as Is}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=bn(e),a;try{gn(e),a=Ss(e,d)}catch(F){throw F instanceof hn?new R("SYNC_REBASE_PENDING",`${F.message.split(";")[0]}; nothing was pushed`,F.remedy):F}finally{c()}let l=a.map(F=>Es(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 _r(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`,kr(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 _r(t,y,d,n);for(let A of x)r(A);let U="";if(y)try{Kn(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}`,kr(n,b))}finally{await m?.abort()}return{pushed:g,from:d?.seq??0,to:y?.seq??0,blobs:p,proposals:f,alreadyThere:u}}function kr(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 _r(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 Ss(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=Rr(Is(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 Es(e,{rec:t,hash:n,raw:r}){{let o=Bn(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:Os(e,o.proposalId)}}}function Os(e,t){if(t===null)return null;let n=ln(e,t);if(!Rs(n))return null;let r=Rr(n);return{key:Vn(t,Dn(r.toString("utf8"))),bytes:r}}import{existsSync as Cs,readdirSync as As,readFileSync as Ir}from"fs";import{basename as Ps,join as Lt}from"path";var Ns=/^\d{6}-[0-9a-f]{12}\.json$/;function Bt(e,t){let n=Lt(e,"commits"),r=Cs(n)?As(n).filter(s=>Ns.test(s)).sort():[],o=t.hash,i=t.seq;return r.map(s=>{let d;try{d=JSON.parse(Ir(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(Ir(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=_n();Rn(e,a,s,d,{writeNodeFiles:!1});let l=Nn(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:Ps(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(qs(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 qs(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 Sr,readdirSync as js,readFileSync as Mt}from"fs";import{isAbsolute as Ts,join as ut,normalize as xs,relative as Fs,sep as Ls}from"path";var Bs=e=>e===""||Ts(e)||e.includes("\\")||xs(e).split(Ls).some(t=>t==="..")||e.startsWith("./")||e.includes("\0");function He(e){let t=ut(e,"manifest.json");if(!Sr(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(Bs(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(!Sr(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 Er(e)){let d=Fs(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=pn(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 Er(e){let t=[];for(let n of js(e,{withFileTypes:!0})){let r=ut(e,n.name);n.isDirectory()?t.push(...Er(r)):t.push(r)}return t}import{basename as co,join as lo}from"path";import{existsSync as po,readFileSync as uo}from"fs";var G=class extends Error{},B=(e,t)=>({kind:"apply",inputs:e,...t&&t.length>0?{aliases:t}:{}}),V=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}}),Or=(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 Jt(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 Vt(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 Ds=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))!Ds.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?V("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 Ms(e){return String(e??"").toLowerCase().trim().replace(/\s+/g," ")}function ft(e,t){let n=t.question;return`${e}\0${Ms(t.title??t.text??t.statement??n?.header??t.source_id??"")}`}function Cr(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 Ar(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 Pr(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 Nr(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,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as ee,d as te,h as D,i as ne,j as re,k as U,l as ie,m as se,n as oe,o as R,p as ae,q as H,r as he,s as ge,t as _e}from"./chunk-22QIVSQR.js";import{a as me}from"./chunk-CH273NAE.js";import{d as V}from"./chunk-LBNADEQN.js";import{C as $,e as pe,f as fe}from"./chunk-GP7WD4UY.js";import{H as M,M as T,P as le,X as O,c as de,m as L,u as ue,x as I,z as P}from"./chunk-3N6IAVD5.js";import{d as x,f as ce}from"./chunk-AKX4VRRR.js";import{appendFileSync as Ie,closeSync as Oe,existsSync as S,fsyncSync as Ce,openSync as Ne,readdirSync as je,readFileSync as k,renameSync as Fe,writeFileSync as J}from"fs";import{dirname as Q,isAbsolute as G,join as F,resolve as q}from"path";var Re=new Set(["inline","testmd","testrun"]),Le=new Set(["inferred","authored","runtime-derived"]),B=new Set(["passed","failed","broken","skipped"]);function ye(t,e,n){if(n.facts.length===0)return{record:null,errors:[{code:"EMPTY_EXECUTIONS",detail:"a run with no designed units attaches no facts \u2014 skip the call"}]};let o=e;for(let a=0;;a++){let c=M(t);if(o.latestHash!==c){if(a>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:`graph opened at ${String(o.latestHash)} but chain head is ${String(c)} \u2014 retry budget exhausted`}]};o=$(t);continue}let d=Te(t,o,n);if(d!=="cas")return d;if(a>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:"concurrent appends kept moving the head \u2014 retry budget exhausted"}]};o=$(t)}}function ve(t,e){return Re.has(t.mode)?B.has(t.verdict)?Le.has(t.oracle_mode)?typeof t.drift_flag!="boolean"||typeof t.stale_at_run!="boolean"?[{code:"MISSING_FIELD",detail:`${e}: drift_flag and stale_at_run are required booleans`}]:!t.execution_id||!t.started_at||!t.definition_id_at_run?[{code:"MISSING_FIELD",detail:`${e}: execution_id, started_at and definition_id_at_run are required`}]:[]:[{code:"BAD_ORACLE_MODE",detail:`${e}: oracle_mode '${t.oracle_mode}' not in inferred|authored|runtime-derived`}]:[{code:"BAD_VERDICT",detail:`${e}: verdict '${t.verdict}' not in ${[...B].join("|")}`}]:[{code:"BAD_MODE",detail:`${e}: mode '${t.mode}' not in inline|testmd|testrun`}]}function be(t,e,n,o){return{about:e,definition_id_at_run:t.definition_id_at_run,verdict:t.verdict,...n&&n.length?{per_ac:n}:{},drift_flag:t.drift_flag,oracle_mode:t.oracle_mode,stale_at_run:t.stale_at_run,...o.length?{unresolved_acs:o}:{},execution_id:t.execution_id,...t.evidence_id?{evidence_id:t.evidence_id}:{},...t.duration_ms!==void 0?{duration_ms:t.duration_ms}:{},started_at:t.started_at,mode:t.mode,local:t.local,...t.via_parent?{via_parent:t.via_parent}:{}}}function Ee(t,e,n={}){if(!Array.isArray(e.facts)||e.facts.length===0)return{record:null,errors:[{code:"EMPTY_EXECUTIONS",detail:"parked line carries no facts"}]};for(let o=0;;o++){let a=$(t),c=e.facts.filter(s=>a.appliedEvents.has(s.event_id)).map(s=>s.event_id),d=e.facts.filter(s=>!a.appliedEvents.has(s.event_id));if(d.length===0)return{record:null,errors:null,applied:[],skipped:c,rejected:[]};let l=[],i=[],g=[],m=[];for(let s of d){let r=`executions[${s.ref}]`,u=[];if(!s.about_cid||!a.hasNode(s.about_cid))u.push({code:"UNKNOWN_REF",detail:`${r}: about_cid '${String(s.about_cid)}' is not in the graph \u2014 the pinned run-time target is gone`});else if(a.nodeLabel.get(s.about_cid)!==x.TEST)u.push({code:"ILLEGAL_TARGET",detail:`${r}: execution facts attach to tests \u2014 '${s.about_cid}' is a ${a.nodeLabel.get(s.about_cid)}`});else if(!s.event_id)u.push({code:"MISSING_FIELD",detail:`${r}: parked facts require event_id`});else{u.push(...ve(s,r));for(let h of s.per_ac??[])B.has(h.verdict)||u.push({code:"BAD_VERDICT",detail:`${r}.per_ac['${h.ac_ref}']: verdict '${h.verdict}'`})}if(u.length>0){l.push({event_id:s.event_id??"",errors:u});continue}let p=[],f=[],_=[...s.unresolved_acs??[]];for(let h of s.per_ac??[]){let b=h.ac_cid&&a.hasNode(h.ac_cid)&&a.nodeLabel.get(h.ac_cid)===x.AC?h.ac_cid:null,y=b?null:a.resolve(h.ac_ref),E=b??(y?a.tipOf(y.cid):null);if(!E||!b&&(a.superseded.has(E)||a.nodeLabel.get(E)!==x.AC)){_.push(h.ac_ref);continue}p.push({ac_ref:a.nameOf.get(E)??h.ac_ref,ac_cid:E,verdict:h.verdict}),f.push(E)}i.push(be(s,s.about_cid,p,_)),m.push({about_cid:s.about_cid,per_ac:f}),g.push(s.event_id)}if(i.length===0)return{record:null,errors:null,applied:[],skipped:c,rejected:l};try{let s=T(t,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[],executions:i,event_ids:[...g].sort(),source_head_moves:{}},{expectPrev:a.latestHash,intent:{v:1,verb:"parked",args:L({line:e}),pins:{facts:m}},busyRetry:{deadlineMs:5e3},provenance:n.provenance}),r;try{O(t)}catch(u){r=`parked facts committed, but the projection refresh failed (${u instanceof Error?u.message:String(u)}) \u2014 read state rebuilds on the next open`}return{record:s.record,errors:null,applied:g,skipped:c,rejected:l,...r?{warnings:[r]}:{}}}catch(s){if(!(s instanceof I))throw s;if(o>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:"concurrent appends kept moving the head \u2014 parked replay retry budget exhausted (line stays queued)"}]}}}}function Te(t,e,n){let o=[],a=[],c=[];for(let i of n.facts){let g=`executions[${i.ref}]`,m=n.pinned?null:e.resolve(i.ref),s=n.pinned?i.about_cid&&e.hasNode(i.about_cid)?i.about_cid:null:m?e.tipOf(m.cid):null;if(!s||!n.pinned&&e.superseded.has(s)){o.push({code:"UNKNOWN_REF",detail:`${g}: '${n.pinned?String(i.about_cid):i.ref}' is not a ${n.pinned?"":"live "}committed node`});continue}if(e.nodeLabel.get(s)!==x.TEST){o.push({code:"ILLEGAL_TARGET",detail:`${g}: execution facts attach to tests \u2014 '${i.ref}' is a ${e.nodeLabel.get(s)}`});continue}let r=ve(i,g);if(r.length>0){o.push(...r);continue}let u=[],p=[];for(let f of i.per_ac??[]){let _=n.pinned?null:e.resolve(f.ac_ref),h=n.pinned?f.ac_cid&&e.hasNode(f.ac_cid)?f.ac_cid:null:_?e.tipOf(_.cid):null;if(!h||!n.pinned&&e.superseded.has(h)||e.nodeLabel.get(h)!==x.AC){o.push({code:"UNKNOWN_REF",detail:`${g}.per_ac: '${n.pinned?String(f.ac_cid):f.ac_ref}' is not a${n.pinned?"n":" live"} AC`});continue}if(!B.has(f.verdict)){o.push({code:"BAD_VERDICT",detail:`${g}.per_ac['${f.ac_ref}']: verdict '${f.verdict}'`});continue}u.push({ac_ref:e.nameOf.get(h)??h,ac_cid:h,verdict:f.verdict}),p.push(h)}a.push(be(i,s,u,i.unresolved_acs??[])),c.push({about_cid:s,per_ac:p})}if(o.length>0)return{record:null,errors:o};let d;try{d=T(t,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[],executions:a,...n.eventIds&&n.eventIds.length>0?{event_ids:n.eventIds}:{},source_head_moves:{}},{expectPrev:e.latestHash,intent:{v:1,verb:"execution",args:L({facts:n.facts,by:n.by,eventIds:n.eventIds??null}),pins:{facts:c}},busyRetry:{deadlineMs:n.lockDeadlineMs??5e3},provenance:n.provenance})}catch(i){if(i instanceof I)return"cas";throw i}let l;try{O(t)}catch(i){l=`facts committed, but the projection refresh failed (${i instanceof Error?i.message:String(i)}) \u2014 read state rebuilds on the next open`}return{record:d.record,errors:null,...l?{warnings:[l]}:{}}}function pt(t){let e={failed:3,broken:2,skipped:1,passed:0},n=new Map;for(let o of t)for(let a of o.verifies??[]){let c=n.get(a);(c===void 0||(e[o.status]??0)>(e[c]??0))&&n.set(a,o.status)}return[...n.entries()].map(([o,a])=>({ref:o,verdict:a}))}function ft(t){let e=[],n=me(t.cwd);if(!S(n))return{synced:0,superseded:0,skipped:"no-context",warnings:e};let o=t.by??{kind:"ai",id:"exec-sync"},a=t.lockDeadlineMs;try{Pe(n,e,a)}catch(r){e.push(`sync: parked-facts replay failed (${r instanceof Error?r.message:String(r)}) \u2014 queue intact, retrying next sync`)}let c=$(n),d=[],l=0,i=new Set,g=new Set(t.members.map(r=>G(r.path)?r.path:q(t.cwd,r.path))),m=new Map;for(let r of t.members){let u=G(r.path)?r.path:q(t.cwd,r.path);if(!S(u)){e.push(`sync: member file missing: ${u} \u2014 skipped, no fact attached`);continue}for(let p of Me(u,e))if(!i.has(p.path))try{let f=p.path===u,_=!f&&g.has(p.path),h=f?void 0:R(k(u,"utf8"))?.id,b=k(p.path,"utf8"),y=R(b);if(!y?.id){i.add(p.path);continue}let E=c.resolve(y.id),w=E?c.tipOf(E.cid):null;if(!E||!w||c.superseded.has(w)){i.add(p.path),e.push(`sync: ${y.id} does not resolve to a live test \u2014 skipped (foreign store?)`);continue}let C=D(U(b,se(Q(p.path),c))),Ae=String(c.getNode(w)?.content.test_md_blob??""),N=D(U(Ae,ie(c))),A=!1,j=w;if(C===N)y.base!==N&&xe(p.path,b,N,e);else if(y.base===N){let v=Ge(n,c,w,b,C,Q(p.path),o);v.error?(e.push(`sync: could not supersede ${y.id}: ${v.error}`),A=!0):(l++,j=v.newCid,A=v.oracleTier,xe(p.path,k(p.path,"utf8"),C,e),c=$(n))}else A=!0,e.push(y.base?`sync: ${y.id} was edited from an older version \u2014 graph kept; reconcile via a redesign or maintain`:`sync: ${y.id} carries no base pin (hand-copied file?) \u2014 fact attached with drift flag`);if(_){A&&m.set(p.path,!0);continue}i.add(p.path);let K=c.getNode(j)?.content.check,z=f?r.acs??[]:[],X=z.filter(v=>Se(c,v.ref)),Y=z.filter(v=>!Se(c,v.ref)).map(v=>v.ref);d.push({ref:y.id,about_cid:j,definition_id_at_run:C,verdict:r.verdict,...X.length?{per_ac:X.map(v=>{let Z=we(c,v.ref);return{ac_ref:v.ref,...Z?{ac_cid:Z}:{},verdict:v.verdict}})}:{},drift_flag:A||m.get(p.path)===!0||f&&r.driftFlag===!0,oracle_mode:K?.expected_mode??(ee(K?.operand)?"runtime-derived":"inferred"),stale_at_run:c.stale(j)!=="fresh",...Y.length?{unresolved_acs:Y}:{},execution_id:r.executionId,...r.evidenceId?{evidence_id:r.evidenceId}:{},...r.durationMs!==void 0?{duration_ms:r.durationMs}:{},started_at:r.startedAt,mode:r.mode,local:r.local,...h?{via_parent:h}:{}})}catch(f){p.path!==u&&g.has(p.path)||i.add(p.path),e.push(`sync: ${p.path} failed to sync (${f instanceof Error?f.message:String(f)}) \u2014 skipped; other members unaffected`)}}if(d.length===0)return{synced:0,superseded:l,warnings:e};let s;try{s=ye(n,$(n),{facts:d,by:o,eventIds:d.map(r=>`exec-fact:${r.execution_id}:${r.ref}`),lockDeadlineMs:a})}catch(r){return e.push(`sync facts: commit threw: ${r instanceof Error?r.message:String(r)}`),$e(n,d,o,e,a),{synced:0,superseded:l,warnings:e}}return s.errors?($e(n,d,o,e,a),e.push(...s.errors.map(r=>`sync facts: ${r.code}: ${r.detail}`)),{synced:0,superseded:l,warnings:e}):(s.warnings&&e.push(...s.warnings.map(r=>`sync facts: ${r}`)),{synced:d.length,superseded:l,warnings:e})}var W=".pending-facts.bad";function $e(t,e,n,o,a){try{let c={by:n,ts:new Date().toISOString(),facts:e.map(i=>({...i,about_cid:i.about_cid??"",event_id:`exec-fact:${i.execution_id}:${i.ref}`}))},d=null;try{d=P(t,{deadlineMs:a??5e3})}catch{d=null}let l=F(t,H);try{if(d)Ie(l,JSON.stringify(c)+`
2
+ import{a as ee,d as te,h as D,i as ne,j as re,k as U,l as ie,m as se,n as oe,o as R,p as ae,q as H,r as he,s as ge,t as _e}from"./chunk-SWTJMTBY.js";import{a as me}from"./chunk-CH273NAE.js";import{d as V}from"./chunk-CAOZKSQ3.js";import{C as $,e as pe,f as fe}from"./chunk-GP7WD4UY.js";import{H as M,M as T,P as le,X as O,c as de,m as L,u as ue,x as I,z as P}from"./chunk-3N6IAVD5.js";import{d as x,f as ce}from"./chunk-AKX4VRRR.js";import{appendFileSync as Ie,closeSync as Oe,existsSync as S,fsyncSync as Ce,openSync as Ne,readdirSync as je,readFileSync as k,renameSync as Fe,writeFileSync as J}from"fs";import{dirname as Q,isAbsolute as G,join as F,resolve as q}from"path";var Re=new Set(["inline","testmd","testrun"]),Le=new Set(["inferred","authored","runtime-derived"]),B=new Set(["passed","failed","broken","skipped"]);function ye(t,e,n){if(n.facts.length===0)return{record:null,errors:[{code:"EMPTY_EXECUTIONS",detail:"a run with no designed units attaches no facts \u2014 skip the call"}]};let o=e;for(let a=0;;a++){let c=M(t);if(o.latestHash!==c){if(a>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:`graph opened at ${String(o.latestHash)} but chain head is ${String(c)} \u2014 retry budget exhausted`}]};o=$(t);continue}let d=Te(t,o,n);if(d!=="cas")return d;if(a>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:"concurrent appends kept moving the head \u2014 retry budget exhausted"}]};o=$(t)}}function ve(t,e){return Re.has(t.mode)?B.has(t.verdict)?Le.has(t.oracle_mode)?typeof t.drift_flag!="boolean"||typeof t.stale_at_run!="boolean"?[{code:"MISSING_FIELD",detail:`${e}: drift_flag and stale_at_run are required booleans`}]:!t.execution_id||!t.started_at||!t.definition_id_at_run?[{code:"MISSING_FIELD",detail:`${e}: execution_id, started_at and definition_id_at_run are required`}]:[]:[{code:"BAD_ORACLE_MODE",detail:`${e}: oracle_mode '${t.oracle_mode}' not in inferred|authored|runtime-derived`}]:[{code:"BAD_VERDICT",detail:`${e}: verdict '${t.verdict}' not in ${[...B].join("|")}`}]:[{code:"BAD_MODE",detail:`${e}: mode '${t.mode}' not in inline|testmd|testrun`}]}function be(t,e,n,o){return{about:e,definition_id_at_run:t.definition_id_at_run,verdict:t.verdict,...n&&n.length?{per_ac:n}:{},drift_flag:t.drift_flag,oracle_mode:t.oracle_mode,stale_at_run:t.stale_at_run,...o.length?{unresolved_acs:o}:{},execution_id:t.execution_id,...t.evidence_id?{evidence_id:t.evidence_id}:{},...t.duration_ms!==void 0?{duration_ms:t.duration_ms}:{},started_at:t.started_at,mode:t.mode,local:t.local,...t.via_parent?{via_parent:t.via_parent}:{}}}function Ee(t,e,n={}){if(!Array.isArray(e.facts)||e.facts.length===0)return{record:null,errors:[{code:"EMPTY_EXECUTIONS",detail:"parked line carries no facts"}]};for(let o=0;;o++){let a=$(t),c=e.facts.filter(s=>a.appliedEvents.has(s.event_id)).map(s=>s.event_id),d=e.facts.filter(s=>!a.appliedEvents.has(s.event_id));if(d.length===0)return{record:null,errors:null,applied:[],skipped:c,rejected:[]};let l=[],i=[],g=[],m=[];for(let s of d){let r=`executions[${s.ref}]`,u=[];if(!s.about_cid||!a.hasNode(s.about_cid))u.push({code:"UNKNOWN_REF",detail:`${r}: about_cid '${String(s.about_cid)}' is not in the graph \u2014 the pinned run-time target is gone`});else if(a.nodeLabel.get(s.about_cid)!==x.TEST)u.push({code:"ILLEGAL_TARGET",detail:`${r}: execution facts attach to tests \u2014 '${s.about_cid}' is a ${a.nodeLabel.get(s.about_cid)}`});else if(!s.event_id)u.push({code:"MISSING_FIELD",detail:`${r}: parked facts require event_id`});else{u.push(...ve(s,r));for(let h of s.per_ac??[])B.has(h.verdict)||u.push({code:"BAD_VERDICT",detail:`${r}.per_ac['${h.ac_ref}']: verdict '${h.verdict}'`})}if(u.length>0){l.push({event_id:s.event_id??"",errors:u});continue}let p=[],f=[],_=[...s.unresolved_acs??[]];for(let h of s.per_ac??[]){let b=h.ac_cid&&a.hasNode(h.ac_cid)&&a.nodeLabel.get(h.ac_cid)===x.AC?h.ac_cid:null,y=b?null:a.resolve(h.ac_ref),E=b??(y?a.tipOf(y.cid):null);if(!E||!b&&(a.superseded.has(E)||a.nodeLabel.get(E)!==x.AC)){_.push(h.ac_ref);continue}p.push({ac_ref:a.nameOf.get(E)??h.ac_ref,ac_cid:E,verdict:h.verdict}),f.push(E)}i.push(be(s,s.about_cid,p,_)),m.push({about_cid:s.about_cid,per_ac:f}),g.push(s.event_id)}if(i.length===0)return{record:null,errors:null,applied:[],skipped:c,rejected:l};try{let s=T(t,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[],executions:i,event_ids:[...g].sort(),source_head_moves:{}},{expectPrev:a.latestHash,intent:{v:1,verb:"parked",args:L({line:e}),pins:{facts:m}},busyRetry:{deadlineMs:5e3},provenance:n.provenance}),r;try{O(t)}catch(u){r=`parked facts committed, but the projection refresh failed (${u instanceof Error?u.message:String(u)}) \u2014 read state rebuilds on the next open`}return{record:s.record,errors:null,applied:g,skipped:c,rejected:l,...r?{warnings:[r]}:{}}}catch(s){if(!(s instanceof I))throw s;if(o>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:"concurrent appends kept moving the head \u2014 parked replay retry budget exhausted (line stays queued)"}]}}}}function Te(t,e,n){let o=[],a=[],c=[];for(let i of n.facts){let g=`executions[${i.ref}]`,m=n.pinned?null:e.resolve(i.ref),s=n.pinned?i.about_cid&&e.hasNode(i.about_cid)?i.about_cid:null:m?e.tipOf(m.cid):null;if(!s||!n.pinned&&e.superseded.has(s)){o.push({code:"UNKNOWN_REF",detail:`${g}: '${n.pinned?String(i.about_cid):i.ref}' is not a ${n.pinned?"":"live "}committed node`});continue}if(e.nodeLabel.get(s)!==x.TEST){o.push({code:"ILLEGAL_TARGET",detail:`${g}: execution facts attach to tests \u2014 '${i.ref}' is a ${e.nodeLabel.get(s)}`});continue}let r=ve(i,g);if(r.length>0){o.push(...r);continue}let u=[],p=[];for(let f of i.per_ac??[]){let _=n.pinned?null:e.resolve(f.ac_ref),h=n.pinned?f.ac_cid&&e.hasNode(f.ac_cid)?f.ac_cid:null:_?e.tipOf(_.cid):null;if(!h||!n.pinned&&e.superseded.has(h)||e.nodeLabel.get(h)!==x.AC){o.push({code:"UNKNOWN_REF",detail:`${g}.per_ac: '${n.pinned?String(f.ac_cid):f.ac_ref}' is not a${n.pinned?"n":" live"} AC`});continue}if(!B.has(f.verdict)){o.push({code:"BAD_VERDICT",detail:`${g}.per_ac['${f.ac_ref}']: verdict '${f.verdict}'`});continue}u.push({ac_ref:e.nameOf.get(h)??h,ac_cid:h,verdict:f.verdict}),p.push(h)}a.push(be(i,s,u,i.unresolved_acs??[])),c.push({about_cid:s,per_ac:p})}if(o.length>0)return{record:null,errors:o};let d;try{d=T(t,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[],executions:a,...n.eventIds&&n.eventIds.length>0?{event_ids:n.eventIds}:{},source_head_moves:{}},{expectPrev:e.latestHash,intent:{v:1,verb:"execution",args:L({facts:n.facts,by:n.by,eventIds:n.eventIds??null}),pins:{facts:c}},busyRetry:{deadlineMs:n.lockDeadlineMs??5e3},provenance:n.provenance})}catch(i){if(i instanceof I)return"cas";throw i}let l;try{O(t)}catch(i){l=`facts committed, but the projection refresh failed (${i instanceof Error?i.message:String(i)}) \u2014 read state rebuilds on the next open`}return{record:d.record,errors:null,...l?{warnings:[l]}:{}}}function pt(t){let e={failed:3,broken:2,skipped:1,passed:0},n=new Map;for(let o of t)for(let a of o.verifies??[]){let c=n.get(a);(c===void 0||(e[o.status]??0)>(e[c]??0))&&n.set(a,o.status)}return[...n.entries()].map(([o,a])=>({ref:o,verdict:a}))}function ft(t){let e=[],n=me(t.cwd);if(!S(n))return{synced:0,superseded:0,skipped:"no-context",warnings:e};let o=t.by??{kind:"ai",id:"exec-sync"},a=t.lockDeadlineMs;try{Pe(n,e,a)}catch(r){e.push(`sync: parked-facts replay failed (${r instanceof Error?r.message:String(r)}) \u2014 queue intact, retrying next sync`)}let c=$(n),d=[],l=0,i=new Set,g=new Set(t.members.map(r=>G(r.path)?r.path:q(t.cwd,r.path))),m=new Map;for(let r of t.members){let u=G(r.path)?r.path:q(t.cwd,r.path);if(!S(u)){e.push(`sync: member file missing: ${u} \u2014 skipped, no fact attached`);continue}for(let p of Me(u,e))if(!i.has(p.path))try{let f=p.path===u,_=!f&&g.has(p.path),h=f?void 0:R(k(u,"utf8"))?.id,b=k(p.path,"utf8"),y=R(b);if(!y?.id){i.add(p.path);continue}let E=c.resolve(y.id),w=E?c.tipOf(E.cid):null;if(!E||!w||c.superseded.has(w)){i.add(p.path),e.push(`sync: ${y.id} does not resolve to a live test \u2014 skipped (foreign store?)`);continue}let C=D(U(b,se(Q(p.path),c))),Ae=String(c.getNode(w)?.content.test_md_blob??""),N=D(U(Ae,ie(c))),A=!1,j=w;if(C===N)y.base!==N&&xe(p.path,b,N,e);else if(y.base===N){let v=Ge(n,c,w,b,C,Q(p.path),o);v.error?(e.push(`sync: could not supersede ${y.id}: ${v.error}`),A=!0):(l++,j=v.newCid,A=v.oracleTier,xe(p.path,k(p.path,"utf8"),C,e),c=$(n))}else A=!0,e.push(y.base?`sync: ${y.id} was edited from an older version \u2014 graph kept; reconcile via a redesign or maintain`:`sync: ${y.id} carries no base pin (hand-copied file?) \u2014 fact attached with drift flag`);if(_){A&&m.set(p.path,!0);continue}i.add(p.path);let K=c.getNode(j)?.content.check,z=f?r.acs??[]:[],X=z.filter(v=>Se(c,v.ref)),Y=z.filter(v=>!Se(c,v.ref)).map(v=>v.ref);d.push({ref:y.id,about_cid:j,definition_id_at_run:C,verdict:r.verdict,...X.length?{per_ac:X.map(v=>{let Z=we(c,v.ref);return{ac_ref:v.ref,...Z?{ac_cid:Z}:{},verdict:v.verdict}})}:{},drift_flag:A||m.get(p.path)===!0||f&&r.driftFlag===!0,oracle_mode:K?.expected_mode??(ee(K?.operand)?"runtime-derived":"inferred"),stale_at_run:c.stale(j)!=="fresh",...Y.length?{unresolved_acs:Y}:{},execution_id:r.executionId,...r.evidenceId?{evidence_id:r.evidenceId}:{},...r.durationMs!==void 0?{duration_ms:r.durationMs}:{},started_at:r.startedAt,mode:r.mode,local:r.local,...h?{via_parent:h}:{}})}catch(f){p.path!==u&&g.has(p.path)||i.add(p.path),e.push(`sync: ${p.path} failed to sync (${f instanceof Error?f.message:String(f)}) \u2014 skipped; other members unaffected`)}}if(d.length===0)return{synced:0,superseded:l,warnings:e};let s;try{s=ye(n,$(n),{facts:d,by:o,eventIds:d.map(r=>`exec-fact:${r.execution_id}:${r.ref}`),lockDeadlineMs:a})}catch(r){return e.push(`sync facts: commit threw: ${r instanceof Error?r.message:String(r)}`),$e(n,d,o,e,a),{synced:0,superseded:l,warnings:e}}return s.errors?($e(n,d,o,e,a),e.push(...s.errors.map(r=>`sync facts: ${r.code}: ${r.detail}`)),{synced:0,superseded:l,warnings:e}):(s.warnings&&e.push(...s.warnings.map(r=>`sync facts: ${r}`)),{synced:d.length,superseded:l,warnings:e})}var W=".pending-facts.bad";function $e(t,e,n,o,a){try{let c={by:n,ts:new Date().toISOString(),facts:e.map(i=>({...i,about_cid:i.about_cid??"",event_id:`exec-fact:${i.execution_id}:${i.ref}`}))},d=null;try{d=P(t,{deadlineMs:a??5e3})}catch{d=null}let l=F(t,H);try{if(d)Ie(l,JSON.stringify(c)+`
3
3
  `);else{l=F(t,ge());let i=Ne(l,"wx");try{J(i,JSON.stringify(c)+`
4
4
  `),Ce(i)}finally{Oe(i)}le(t),o.push(`sync facts: store lock busy \u2014 parked to ${l}; it drains on the next sync`)}}finally{d?.()}o.push(`sync facts: commit failed \u2014 ${e.length} fact(s) parked to ${l}; they replay on the next sync`)}catch(c){o.push(`sync facts: could not park the failed batch (${c instanceof Error?c.message:String(c)}) \u2014 this run's facts are LOST`)}}function Pe(t,e,n){let o=F(t,H);if(!S(o)&&!je(t).some(m=>he.test(m)))return;let a=ue(t);if(a){e.push(`sync: parked facts stay queued while rebase ${a.id} is open \u2014 they drain on the first sync after it is finished`);return}let c;{let m=P(t,{deadlineMs:n??5e3});try{_e(t),c=S(o)?k(o,"utf8"):""}finally{m()}}let d=c.split(`
5
5
  `).filter(m=>m.trim()!=="");if(d.length===0)return;let l=new Set,i=[],g=[];for(let m of d){let s=null;try{let u=JSON.parse(m);u&&Array.isArray(u.facts)&&(s=u)}catch{}if(!s){i.push(m),l.add(m);continue}let r=Ee(t,s);if(r.errors){if(r.errors.some(u=>u.code==="STALE_BASIS")){e.push(`sync: parked facts replay deferred (${r.errors[0].detail}) \u2014 retrying next sync`);continue}i.push(m),l.add(m),e.push(`sync: parked facts line quarantined to ${F(t,W)} (${r.errors.map(u=>`${u.code}: ${u.detail}`).join("; ")})`);continue}for(let u of r.rejected){let p=s.facts.find(f=>f.event_id===u.event_id);g.push({parent:m,line:JSON.stringify({...p??{event_id:u.event_id},_reason:u.errors})})}r.rejected.length>0&&e.push(`sync: ${r.rejected.length} parked fact(s) quarantined to ${F(t,W)} (${r.rejected.map(u=>u.errors.map(p=>`${p.code}: ${p.detail}`).join("; ")).join(" | ")})`),l.add(m),r.warnings&&e.push(...r.warnings.map(u=>`sync: ${u}`)),r.applied.length>0&&e.push(`sync: replayed ${r.applied.length} parked fact(s) from a previous run`)}if(l.size!==0)try{let m=P(t,{deadlineMs:n??5e3});try{let r=(S(o)?k(o,"utf8"):"").split(`
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ var f=/^\d+$/;function c(t){if(t.type==="parameter")return!0;let e=t.syntax?.trim()??"";return e.startsWith("${")&&e.endsWith("}")}function a(t){if(!t)throw new Error("--dataset-row needs the row's _id (as Test Manager shows it)");if(f.test(t))throw new Error(`row positions are not supported: pass the row's _id (--dataset-row <_id>), got: ${JSON.stringify(t)}`)}function w(t){let e=t.rows.map(n=>typeof n._id=="string"?n._id:"(no _id)"),r=e.slice(0,20).join(", ");return e.length>20?`${r}, \u2026 (${e.length} rows)`:r}function u(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object")try{return JSON.stringify(t)}catch{return String(t)}return String(t)}function g(t,e){if(t.rows.length===0)throw new Error("the dataset has no rows");let r=e?.trim();if(!r)throw new Error(`pick a row with --dataset-row <_id> \u2014 this dataset has rows: ${w(t)}`);a(r);let n=t.rows.findIndex(i=>i._id===r);if(n===-1)throw new Error(`no row with _id ${r} in the dataset \u2014 it has rows: ${w(t)}`);return{row:t.rows[n],id:r,index:n+1}}function l(t,e){let r={};for(let n of t.headers)!n.name||n.name==="_id"||(r[n.name]={value:u(e[n.name]),syntax:"${"+n.name+"}",type:"parameter",secret:!1});return r}function m(t,e){return t.headers.filter(r=>r.name&&r.name!=="_id").map(r=>({name:r.name,type:r.type,value:u(e[r.name])}))}function p(t,e){let r=typeof t.datasetId=="string"&&t.datasetId.trim()?t.datasetId.trim():null,n=t.datasetRow===void 0||t.datasetRow===null||t.datasetRow===""?null:String(t.datasetRow).trim();n!==null&&a(n);let i=(s,d)=>d?{id:s,row:d}:{id:s};if(r)return i(r,n);let o=e?.id?.trim();if(o){let s=typeof e?.row=="string"&&e.row.trim()?e.row.trim():null;return s!==null&&a(s),i(o,n??s)}if(n!==null)throw new Error("--dataset-row needs a dataset: pass --dataset-id or set dataset: in the frontmatter");return null}function _(t,e){return{id:t,row:e}}function h(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>c(e)))}function y(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>!c(e)))}function x(t,e,r){return{dataset_id:t,dataset_row_id:e,...r?{dataset_version_id:r}:{}}}export{c as a,g as b,l as c,m as d,p as e,_ as f,h as g,y as h,x as i};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as y}from"./chunk-OH2NSBO6.js";import{createServer as b}from"http";import{createReadStream as C,promises as S}from"fs";import{randomBytes as R}from"crypto";var u="127.0.0.1";function A(n,e){if(!n)return null;let o=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!o)return null;let[,a,r]=o;if(a===""&&r==="")return null;if(a===""){let i=Number(r);return i===0||e===0?"unsatisfiable":{start:Math.max(0,e-i),end:e-1}}let t=Number(a);if(t>=e)return"unsatisfiable";let c=r===""?e-1:Math.min(Number(r),e-1);return c<t?null:{start:t,end:c}}async function I(n){let e=R(16).toString("hex"),o=b((r,t)=>{H(r,t,n,e).catch(()=>t.destroy())});await new Promise((r,t)=>{o.once("error",t),o.listen(n.port??0,u,()=>{o.removeListener("error",t),r()})});let a=o.address().port;return{port:a,urlFor:r=>`http://${u}:${a}/${e}/${encodeURIComponent(r)}`,close:()=>new Promise(r=>{o.close(()=>r()),o.closeAllConnections()})}}async function H(n,e,o,a){let r=n.url??"/",t=s=>{try{o.log?.("warn","EVIDENCE_SERVE_DENIED",{reason:s,path:r})}catch{}};if(n.headers.host!==`${u}:${n.socket.localPort}`){t("host_mismatch"),e.writeHead(403).end();return}let c=n.headers.origin;if(c!==void 0&&!o.allowedOrigins.includes(c)){t("origin_denied"),e.writeHead(403).end();return}let i=c?{"Access-Control-Allow-Origin":c,Vary:"Origin","Access-Control-Expose-Headers":"Content-Range, Content-Length"}:{};if(n.method==="OPTIONS"){let s={...i,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range","Access-Control-Max-Age":"86400"};n.headers["access-control-request-private-network"]==="true"&&(s["Access-Control-Allow-Private-Network"]="true"),e.writeHead(204,s).end();return}if(n.method!=="GET"&&n.method!=="HEAD"){e.writeHead(405,i).end();return}let v;try{let s=new URL(n.url??"/",`http://${u}`).pathname.split("/");if(s.length!==3||s[1]!==a){t("bad_token"),e.writeHead(404,i).end();return}v=decodeURIComponent(s[2])}catch{t("not_found"),e.writeHead(404,i).end();return}let g=o.packs.get(v);if(!g){t("not_found"),e.writeHead(404,i).end();return}let d;try{let s=await S.stat(g);if(!s.isFile())throw new Error("not a file");d=s.size}catch{t("not_found"),e.writeHead(404,i).end();return}let h={...i,"Accept-Ranges":"bytes","Content-Type":"application/zip","Cache-Control":"no-store"};if(n.method==="HEAD"){e.writeHead(200,{...h,"Content-Length":String(d)}).end();return}let l=A(n.headers.range,d);if(l==="unsatisfiable"){t("unsatisfiable"),e.writeHead(416,{...i,"Content-Range":`bytes */${d}`}).end();return}let[m,p,w]=l===null?[0,d-1,200]:[l.start,l.end,206],E={...h,"Content-Length":String(p-m+1)};if(w===206&&(E["Content-Range"]=`bytes ${m}-${p}/${d}`),e.writeHead(w,E),d===0){e.end();return}let f=C(g,{start:m,end:p});f.on("error",()=>e.destroy()),e.on("close",()=>f.destroy()),f.pipe(e)}function O(n,e){return(e??y(n).evidenceViewerUrl).replace(/\/+$/,"")}function k(n,e){return`${e}/?pack=${encodeURIComponent(n)}`}function P(n){return`evidence: view locally with \`kane-cli evidence serve ${n}\``}export{A as a,I as b,O as c,k as d,P as e};
2
+ import{a as y}from"./chunk-BCJNIDS3.js";import{createServer as b}from"http";import{createReadStream as C,promises as S}from"fs";import{randomBytes as R}from"crypto";var u="127.0.0.1";function A(n,e){if(!n)return null;let o=/^bytes=(\d*)-(\d*)$/.exec(n.trim());if(!o)return null;let[,a,r]=o;if(a===""&&r==="")return null;if(a===""){let i=Number(r);return i===0||e===0?"unsatisfiable":{start:Math.max(0,e-i),end:e-1}}let t=Number(a);if(t>=e)return"unsatisfiable";let c=r===""?e-1:Math.min(Number(r),e-1);return c<t?null:{start:t,end:c}}async function I(n){let e=R(16).toString("hex"),o=b((r,t)=>{H(r,t,n,e).catch(()=>t.destroy())});await new Promise((r,t)=>{o.once("error",t),o.listen(n.port??0,u,()=>{o.removeListener("error",t),r()})});let a=o.address().port;return{port:a,urlFor:r=>`http://${u}:${a}/${e}/${encodeURIComponent(r)}`,close:()=>new Promise(r=>{o.close(()=>r()),o.closeAllConnections()})}}async function H(n,e,o,a){let r=n.url??"/",t=s=>{try{o.log?.("warn","EVIDENCE_SERVE_DENIED",{reason:s,path:r})}catch{}};if(n.headers.host!==`${u}:${n.socket.localPort}`){t("host_mismatch"),e.writeHead(403).end();return}let c=n.headers.origin;if(c!==void 0&&!o.allowedOrigins.includes(c)){t("origin_denied"),e.writeHead(403).end();return}let i=c?{"Access-Control-Allow-Origin":c,Vary:"Origin","Access-Control-Expose-Headers":"Content-Range, Content-Length"}:{};if(n.method==="OPTIONS"){let s={...i,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range","Access-Control-Max-Age":"86400"};n.headers["access-control-request-private-network"]==="true"&&(s["Access-Control-Allow-Private-Network"]="true"),e.writeHead(204,s).end();return}if(n.method!=="GET"&&n.method!=="HEAD"){e.writeHead(405,i).end();return}let v;try{let s=new URL(n.url??"/",`http://${u}`).pathname.split("/");if(s.length!==3||s[1]!==a){t("bad_token"),e.writeHead(404,i).end();return}v=decodeURIComponent(s[2])}catch{t("not_found"),e.writeHead(404,i).end();return}let g=o.packs.get(v);if(!g){t("not_found"),e.writeHead(404,i).end();return}let d;try{let s=await S.stat(g);if(!s.isFile())throw new Error("not a file");d=s.size}catch{t("not_found"),e.writeHead(404,i).end();return}let h={...i,"Accept-Ranges":"bytes","Content-Type":"application/zip","Cache-Control":"no-store"};if(n.method==="HEAD"){e.writeHead(200,{...h,"Content-Length":String(d)}).end();return}let l=A(n.headers.range,d);if(l==="unsatisfiable"){t("unsatisfiable"),e.writeHead(416,{...i,"Content-Range":`bytes */${d}`}).end();return}let[m,p,w]=l===null?[0,d-1,200]:[l.start,l.end,206],E={...h,"Content-Length":String(p-m+1)};if(w===206&&(E["Content-Range"]=`bytes ${m}-${p}/${d}`),e.writeHead(w,E),d===0){e.end();return}let f=C(g,{start:m,end:p});f.on("error",()=>e.destroy()),e.on("close",()=>f.destroy()),f.pipe(e)}function O(n,e){return(e??y(n).evidenceViewerUrl).replace(/\/+$/,"")}function k(n,e){return`${e}/?pack=${encodeURIComponent(n)}`}function P(n){return`evidence: view locally with \`kane-cli evidence serve ${n}\``}export{A as a,I as b,O as c,k as d,P as e};