@testmuai/kane-cli 0.8.4 → 0.8.5

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 (161) hide show
  1. package/dist/{ChatSurface-H26E7DM6.js → ChatSurface-HAIVTS4J.js} +1 -1
  2. package/dist/{ChromeProfilePicker-USUPENU2.js → ChromeProfilePicker-5ILSVC2K.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-ZIAZ2M2U.js → CliFeedbackPrompt-LFKEYMKP.js} +1 -1
  4. package/dist/{CliUploadProgress-LEOJTXHT.js → CliUploadProgress-Y7ITY2I7.js} +1 -1
  5. package/dist/{ConfigView-JBIQPG7O.js → ConfigView-OECNNCXC.js} +1 -1
  6. package/dist/{EvidenceViewOffer-IWQ6Q2CI.js → EvidenceViewOffer-FODRAS6Z.js} +1 -1
  7. package/dist/FolderPicker-5U3RHHBE.js +2 -0
  8. package/dist/{InfoBox-ORHNXPET.js → InfoBox-HWMHNWPM.js} +1 -1
  9. package/dist/{LinksBox-6SKDUB5T.js → LinksBox-TAGYCFFO.js} +1 -1
  10. package/dist/{ProfilesView-Y5GTLDJY.js → ProfilesView-QJBR3RCM.js} +1 -1
  11. package/dist/{ProjectPicker-WDCMKWNQ.js → ProjectPicker-PP75ILZU.js} +1 -1
  12. package/dist/{SaveSessionPrompt-I4KLFESC.js → SaveSessionPrompt-UCRET3II.js} +1 -1
  13. package/dist/SingleShotApp-XWOPGLKZ.js +2 -0
  14. package/dist/{SummaryBox-QWKW5FHK.js → SummaryBox-SLM3OFS2.js} +1 -1
  15. package/dist/TestMdRunView-6BY3IUH5.js +2 -0
  16. package/dist/{TestrunEvidenceTable-ENJJ2GIW.js → TestrunEvidenceTable-PTIBYAXO.js} +1 -1
  17. package/dist/{WhoamiView-H6M536AY.js → WhoamiView-WPHMNYUV.js} +1 -1
  18. package/dist/{app-download-PSRQWDVW.js → app-download-GYQYLGT3.js} +1 -1
  19. package/dist/{auth-JVH2EHK2.js → auth-3DLNMZC2.js} +1 -1
  20. package/dist/{binary-YTQJP2FG.js → binary-XJ3RF3VO.js} +1 -1
  21. package/dist/{bind-OUXCFLSE.js → bind-2N4Q6YKH.js} +2 -2
  22. package/dist/{bootstrap-3NEI7O6I.js → bootstrap-5IHKW5SE.js} +1 -1
  23. package/dist/bridge-LOBTHY3P.js +2 -0
  24. package/dist/{changelog-WDKG4WCV.js → changelog-WCCTI47M.js} +1 -1
  25. package/dist/{chunk-BXRZGISN.js → chunk-2K2BX23I.js} +1 -1
  26. package/dist/{chunk-W75AVBFG.js → chunk-2WSOPZJU.js} +1 -1
  27. package/dist/{chunk-TXH2KG7U.js → chunk-35EUIBYJ.js} +1 -1
  28. package/dist/{chunk-NEHX45NQ.js → chunk-3AJ3QSF5.js} +11 -11
  29. package/dist/{chunk-66RJPH73.js → chunk-4D3DNCQY.js} +1 -1
  30. package/dist/{chunk-XHNPNYJP.js → chunk-4UMQDH52.js} +1 -1
  31. package/dist/{chunk-5HYXTFGB.js → chunk-5NSYHRDN.js} +1 -1
  32. package/dist/{chunk-BWSL2KQQ.js → chunk-5S46D5AJ.js} +1 -1
  33. package/dist/{chunk-PWFZZWYU.js → chunk-66BSTNLD.js} +1 -1
  34. package/dist/{chunk-UTIGOLON.js → chunk-6BTZ2Q4P.js} +1 -1
  35. package/dist/{chunk-BDUCWZYO.js → chunk-6DTWVLSJ.js} +1 -1
  36. package/dist/{chunk-NDAAY2RL.js → chunk-7JUUNZQP.js} +1 -1
  37. package/dist/chunk-7PADFQ5S.js +71 -0
  38. package/dist/{chunk-RN3YHD4S.js → chunk-AJPLHW4T.js} +1 -1
  39. package/dist/{chunk-DYGUHGZ6.js → chunk-AMULIFC5.js} +1 -1
  40. package/dist/{chunk-A6TJUSOS.js → chunk-BAL7E4OH.js} +1 -1
  41. package/dist/{chunk-7HXZZ3VA.js → chunk-BG66IAO6.js} +1 -1
  42. package/dist/{chunk-QBF5FJVL.js → chunk-BJHII5SD.js} +1 -1
  43. package/dist/chunk-BVKDHHPK.js +5 -0
  44. package/dist/chunk-CCUGKBIH.js +2 -0
  45. package/dist/{chunk-UONRTWLU.js → chunk-CGYSFLM2.js} +1 -1
  46. package/dist/{chunk-7LP4X25A.js → chunk-CNNJ4U2L.js} +1 -1
  47. package/dist/{chunk-QWDFFEEJ.js → chunk-DCUT3GJA.js} +1 -1
  48. package/dist/{chunk-2HT3RYKJ.js → chunk-DJ7T7BMV.js} +1 -1
  49. package/dist/{chunk-PRLTUEKP.js → chunk-E3BXNQYE.js} +1 -1
  50. package/dist/{chunk-U55NUF4E.js → chunk-EFRJNPBZ.js} +2 -2
  51. package/dist/chunk-EKCGZXZE.js +2 -0
  52. package/dist/{chunk-BGMI5PH4.js → chunk-FDWEL5HR.js} +1 -1
  53. package/dist/chunk-FRSHEJUS.js +2 -0
  54. package/dist/{chunk-SFXQFUM6.js → chunk-FTZPWXF7.js} +1 -1
  55. package/dist/{chunk-62WYSEAT.js → chunk-G4AFOZKU.js} +1 -1
  56. package/dist/{chunk-L4EDLDLZ.js → chunk-GYF4CH62.js} +2 -2
  57. package/dist/{chunk-DWWAIXVZ.js → chunk-GZ4X53ZA.js} +2 -2
  58. package/dist/{chunk-PQWSHTSH.js → chunk-HFCDUFV3.js} +1 -1
  59. package/dist/{chunk-YB73T7QH.js → chunk-HQWLSA5M.js} +1 -1
  60. package/dist/{chunk-KAMJ7U4M.js → chunk-JJWQUQJ2.js} +1 -1
  61. package/dist/{chunk-OVLCJ2VX.js → chunk-JN2DP4R2.js} +1 -1
  62. package/dist/{chunk-VYYTENPY.js → chunk-JRQKUQWL.js} +1 -1
  63. package/dist/{chunk-IXTFWIQ6.js → chunk-K2QV7FGP.js} +1 -1
  64. package/dist/{chunk-GJED4QGF.js → chunk-K7UYWAZH.js} +1 -1
  65. package/dist/{chunk-55NSNWM5.js → chunk-KBMQGNKO.js} +9 -9
  66. package/dist/{chunk-35L2QXWP.js → chunk-KWKUMBHS.js} +2 -2
  67. package/dist/{chunk-52GWEKFD.js → chunk-KX2GOJ4C.js} +2 -2
  68. package/dist/{chunk-BCCWICSS.js → chunk-LA2EMSHE.js} +1 -1
  69. package/dist/{chunk-N7N222VC.js → chunk-M335FQYJ.js} +2 -2
  70. package/dist/{chunk-HHHNQW5Z.js → chunk-MJ56GUKS.js} +1 -1
  71. package/dist/{chunk-NEAMQMYH.js → chunk-MUGMUKSZ.js} +1 -1
  72. package/dist/{chunk-HXSEA7JS.js → chunk-NHOHQBIF.js} +1 -1
  73. package/dist/{chunk-KUYJ6FEN.js → chunk-NLECZCMZ.js} +1 -1
  74. package/dist/{chunk-7HPEHQHH.js → chunk-NYSMQ7UY.js} +1 -1
  75. package/dist/{chunk-DXJKMZEC.js → chunk-O3AY6JHJ.js} +1 -1
  76. package/dist/{chunk-OSB32HJE.js → chunk-OWTEHU6B.js} +1 -1
  77. package/dist/{chunk-A3PGLDQY.js → chunk-PB3GADUD.js} +1 -1
  78. package/dist/{chunk-YBX2SQ5R.js → chunk-PCOSE5SW.js} +2 -2
  79. package/dist/{chunk-ZI6W65E3.js → chunk-PEI2566X.js} +1 -1
  80. package/dist/{chunk-PSWB3BWQ.js → chunk-PQUMOFT5.js} +1 -1
  81. package/dist/chunk-PUFJEU46.js +2 -0
  82. package/dist/{chunk-4CHO7SAT.js → chunk-PWYEOBXV.js} +1 -1
  83. package/dist/{chunk-VBCIDWSK.js → chunk-Q6JHBDW2.js} +1 -1
  84. package/dist/{chunk-JR46A564.js → chunk-R7OGNE3W.js} +1 -1
  85. package/dist/{chunk-A4XJUWAQ.js → chunk-RY6TFVAX.js} +1 -1
  86. package/dist/{chunk-ZK57J37M.js → chunk-T3XDMR5B.js} +1 -1
  87. package/dist/{chunk-N5JHMCRU.js → chunk-T5LKD2OB.js} +1 -1
  88. package/dist/{chunk-L77ZOU4N.js → chunk-TCK3QMKY.js} +1 -1
  89. package/dist/{chunk-GSYJUHRK.js → chunk-TJZMYU2W.js} +1 -1
  90. package/dist/{chunk-DZJQNL66.js → chunk-UX3KPYTI.js} +1 -1
  91. package/dist/{chunk-BSCMUMSV.js → chunk-VT2XNEOD.js} +3 -3
  92. package/dist/{chunk-J27JJWMT.js → chunk-W27F2NWA.js} +1 -1
  93. package/dist/{chunk-JT7I6OST.js → chunk-WLOGO44E.js} +1 -1
  94. package/dist/{chunk-6CR2HTIM.js → chunk-WYST42WI.js} +1 -1
  95. package/dist/{chunk-SIH6JG7S.js → chunk-YFLKS4UV.js} +3 -3
  96. package/dist/{chunk-JCILRPOM.js → chunk-Z2T7E5HM.js} +2 -2
  97. package/dist/{chunk-JRADU3PO.js → chunk-ZFZ7YXEU.js} +1 -1
  98. package/dist/{chunk-7VTYRTEJ.js → chunk-ZIRMSWKS.js} +1 -1
  99. package/dist/{config-SFM45WCV.js → config-OKTAPFOT.js} +1 -1
  100. package/dist/{credentials-3CENDBPH.js → credentials-SO3DSQEM.js} +1 -1
  101. package/dist/{deps-bundle-P37ZJDXC.js → deps-bundle-FRM65BQO.js} +1 -1
  102. package/dist/{deps-resolve-VSICFRWU.js → deps-resolve-RPZORKUN.js} +1 -1
  103. package/dist/{dispatch-HDGQAEWN.js → dispatch-OZRMWY25.js} +1 -1
  104. package/dist/doctor-VWGEQYBB.js +2 -0
  105. package/dist/{evidence-ABYJOIV2.js → evidence-5AUZMKE3.js} +1 -1
  106. package/dist/{evolve-cmd-MROTNJIV.js → evolve-cmd-TWYJL4EG.js} +1 -1
  107. package/dist/{extract-bind-LBZMEDUK.js → extract-bind-EW7XUDLQ.js} +2 -2
  108. package/dist/{extract-cmd-K4KBPMB7.js → extract-cmd-HOVGMBGM.js} +1 -1
  109. package/dist/{generate-headless-EBMWSLTR.js → generate-headless-FYTJULPG.js} +2 -2
  110. package/dist/index.js +163 -145
  111. package/dist/{ingest-cmd-ULEWNGCI.js → ingest-cmd-RJLTFNMN.js} +1 -1
  112. package/dist/install-46S4VOZ4.js +2 -0
  113. package/dist/{interactive-bind-IYAJN45L.js → interactive-bind-PSEYAL54.js} +3 -3
  114. package/dist/{list-commands-YPBJNGCE.js → list-commands-2SVSEAP6.js} +1 -1
  115. package/dist/login-flow-U43QVFPH.js +2 -0
  116. package/dist/{mobile-prompts-LHUYRSV7.js → mobile-prompts-T6HZ2YLY.js} +1 -1
  117. package/dist/{persist-recorded-session-KCXYXSQG.js → persist-recorded-session-O2NCYTSD.js} +1 -1
  118. package/dist/pipeline-BHEA7ODT.js +2 -0
  119. package/dist/prepare-target-27UN4KNO.js +2 -0
  120. package/dist/{reconcile-cmd-TSQDYEUT.js → reconcile-cmd-FU3JIHTO.js} +1 -1
  121. package/dist/{reconcile-deps-ETMGIQNM.js → reconcile-deps-SUKZA2FL.js} +2 -2
  122. package/dist/{reconcile-engine-TLFTAOTZ.js → reconcile-engine-ILL4M3NW.js} +1 -1
  123. package/dist/{recording-banner-ACOLKL4K.js → recording-banner-5VXVKCV4.js} +1 -1
  124. package/dist/{registry-3Q6PNWCK.js → registry-BKV3EDTK.js} +1 -1
  125. package/dist/replay-policy-CVQ6OJX5.js +2 -0
  126. package/dist/{require-project-folder-5KWTJAXN.js → require-project-folder-2IO6IX5W.js} +1 -1
  127. package/dist/{resolve-run-intent-L2I7G55O.js → resolve-run-intent-ZML3HKG7.js} +1 -1
  128. package/dist/{resolver-NRU6HGTL.js → resolver-CBTWTZZR.js} +1 -1
  129. package/dist/{run-RHLRZCV5.js → run-EXIYK6PU.js} +1 -1
  130. package/dist/{run-T53Z5TCY.js → run-R7GND73C.js} +1 -1
  131. package/dist/{run-test-md-JYDYT3XF.js → run-test-md-664ASWRQ.js} +2 -2
  132. package/dist/{skill-installer-NWF53JAB.js → skill-installer-QLQK4JJE.js} +1 -1
  133. package/dist/{spawner-LKYUMXSO.js → spawner-ANLF7OX3.js} +1 -1
  134. package/dist/tcg-generate-VBC5ODDI.js +2 -0
  135. package/dist/{testmd-actions-CRRUXYOP.js → testmd-actions-QZD3N4EH.js} +1 -1
  136. package/dist/token-refresh-PIUX5OFA.js +2 -0
  137. package/dist/{validate-basic-X2XPEBFD.js → validate-basic-D7IJUFUQ.js} +1 -1
  138. package/dist/{verdicts-J2SDU4MW.js → verdicts-EO5TZ5BW.js} +1 -1
  139. package/dist/{version-check-DAWGRSJ5.js → version-check-JRLPWQ6T.js} +1 -1
  140. package/dist/{walk-session-D6TCM33V.js → walk-session-IODOH7QU.js} +1 -1
  141. package/dist/{with-telemetry-RXLIXUMR.js → with-telemetry-ASNQQBGP.js} +1 -1
  142. package/package.json +11 -11
  143. package/dist/FolderPicker-G4DT3OEZ.js +0 -2
  144. package/dist/HelpView-I27LWSL5.js +0 -2
  145. package/dist/SingleShotApp-Y77CNTSO.js +0 -2
  146. package/dist/TestMdRunView-PPM6LD3I.js +0 -2
  147. package/dist/bridge-AFQTFWCU.js +0 -2
  148. package/dist/chunk-2PH43Z3P.js +0 -69
  149. package/dist/chunk-3JLWPEQW.js +0 -2
  150. package/dist/chunk-C5UNZ6ZY.js +0 -2
  151. package/dist/chunk-EQSE6NIB.js +0 -5
  152. package/dist/chunk-PH22FRN5.js +0 -2
  153. package/dist/chunk-QDIZQ3ZF.js +0 -2
  154. package/dist/doctor-CPMWU5TL.js +0 -2
  155. package/dist/install-YDH2CORO.js +0 -2
  156. package/dist/login-flow-W5SAB7NN.js +0 -2
  157. package/dist/pipeline-ELIXCTFZ.js +0 -2
  158. package/dist/prepare-target-OU2DQXSW.js +0 -2
  159. package/dist/replay-policy-6USQBT3E.js +0 -2
  160. package/dist/tcg-generate-2PHA7VNL.js +0 -2
  161. package/dist/token-refresh-XKXPM6H3.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as k}from"./chunk-PSWB3BWQ.js";import{y as u}from"./chunk-PH22FRN5.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-PQUMOFT5.js";import{x as u}from"./chunk-CCUGKBIH.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,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as $}from"./chunk-UONRTWLU.js";import{f as D}from"./chunk-DYGUHGZ6.js";import{a as E}from"./chunk-NLCCBXXV.js";function U(e){return["completed","failed","ended","stopped"].includes(e.trim().toLowerCase())}function je(e){return["ended","stopped"].includes(e.trim().toLowerCase())}function q(e){return{requestId:e.requestId,objective:e.objective,status:"",turnActive:!1,scenarios:[],thinking:"",thinkingLog:[],chatLog:[],progress:0}}function Re(e){return e.pendingClarification===void 0?e:{...e,pendingClarification:void 0}}function Ce(e){return{...e,turnActive:!0,error:void 0,thinking:"",thinkingLog:[]}}function P(e,t){switch(t.type){case"thinking":return{...e,status:"thinking",thinking:e.thinking+t.delta};case"thinking_done":return{...e,thinkingLog:[...e.thinkingLog,{text:e.thinking,tookMs:t.tookMs}],thinking:""};case"progress":return{...e,progress:t.pct};case"snapshot":return{...e,scenarios:t.data.scenarios,status:t.data.status,headline:t.data.headline??e.headline};case"chat":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}]};case"clarification":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}],pendingClarification:t.text};case"limit":return{...e,limits:{scenarioLimit:t.scenarioLimit,perScenarioLimit:t.perScenarioLimit}};case"error":return{...e,error:t.message};case"done":return{...e,status:t.status,turnActive:!1,error:t.status==="failed"&&!e.error?"generation failed":e.error}}}function H(e,t){let n=[],i=e.type??"",d=e.status??"";if(i==="ping")return n;switch(i){case"thinking_token":typeof e.data=="string"&&n.push({type:"thinking",delta:e.data});break;case"thinking_stopped":{let r=e.data??{},o=se(r.time_taken);n.push({type:"thinking_done",text:typeof e.data=="string"?e.data:r.message??"",tookMs:o});break}case"progress":{let r=e.data??{};typeof r.progress=="number"&&n.push({type:"progress",pct:r.progress});break}case"clarification":{let r=e.data??{};typeof r.message=="string"&&n.push({type:"clarification",text:r.message});break}case"chatting_stopped":{let r=e.data??{};typeof r.message=="string"&&r.message.length>0&&n.push({type:"chat",text:r.message});break}case"limit_update":{let r=e.data??{},o=r.test_cases_limit??e.test_cases_limit,p=r.per_scenario_test_cases_limit??e.per_scenario_test_cases_limit;n.push({type:"limit",scenarioLimit:o,perScenarioLimit:p});break}case"error":{let r=typeof e.data=="string"?e.data:e.data?.message??"generation error";n.push({type:"error",message:r});break}case"request_cancelled":return n.push({type:"done",status:"stopped"}),n;case"session_ended":return n.push({type:"done",status:"ended"}),n;default:break}if(Array.isArray(e.scenarios)&&n.push({type:"snapshot",data:{requestId:t,status:d,headline:e.headline,scenarios:e.scenarios}}),d&&U(d)){let r=d.trim().toLowerCase();n.push({type:"done",status:r})}return n}function se(e){if(!e)return;let t=/^([\d.]+)(ms|s)?$/.exec(e.trim());if(!t)return;let n=Number(t[1]);if(Number.isFinite(n))return t[2]==="ms"?Math.round(n):Math.round(n*1e3)}var v=class extends Error{constructor(t){super(t),this.name="AuthError"}},M=class extends Error{constructor(t){super(t),this.name="ForbiddenError"}},I=class extends Error{constructor(t){super(t),this.name="InsufficientCreditsError"}},k=class extends Error{constructor(n,i){super(n);this.cause=i;this.name="TransportError"}};function x(e,t){let n=t?.message??t?.error??`HTTP ${e}`;return e===401?new v(n):e===403?t?.key==="insufficient_credits"?new I(n):new M(n):new k(n)}async function*J(e){let t=e.fetchImpl??fetch,n=e.maxRetries??5,i=e.maxBackoffMs??3e4,d=e.connectTimeoutMs??1e4,r=0,o=!1;for(;;){if(e.signal.aborted)return;let p=new AbortController,a=()=>p.abort();e.signal.addEventListener("abort",a,{once:!0});let c=setTimeout(()=>p.abort(),d),g;try{g=await t(e.url,{method:"GET",headers:{Authorization:await e.authHeader(),Accept:"text/event-stream"},signal:p.signal})}catch(w){if(clearTimeout(c),e.signal.removeEventListener("abort",a),e.signal.aborted)return;if(++r>n)throw new k("SSE connect failed",w);await O(F(r,i));continue}if(clearTimeout(c),!g.ok){e.signal.removeEventListener("abort",a);let w=await oe(g);if(g.status===401&&o){if(++r>n)throw x(401,w);await O(F(r,i));continue}throw x(g.status,w)}if(!g.body)throw e.signal.removeEventListener("abort",a),new k("SSE response had no body");o=!0,r=0;let m=g.body.getReader(),h=new TextDecoder("utf-8"),b="";try{for(;;){if(e.signal.aborted){await m.cancel().catch(()=>{});return}let{done:w,value:s}=await m.read();if(w)break;b+=h.decode(s,{stream:!0});let f;for(;(f=b.indexOf(`
2
+ import{a as $}from"./chunk-CGYSFLM2.js";import{f as D}from"./chunk-AMULIFC5.js";import{a as E}from"./chunk-NLCCBXXV.js";function U(e){return["completed","failed","ended","stopped"].includes(e.trim().toLowerCase())}function je(e){return["ended","stopped"].includes(e.trim().toLowerCase())}function q(e){return{requestId:e.requestId,objective:e.objective,status:"",turnActive:!1,scenarios:[],thinking:"",thinkingLog:[],chatLog:[],progress:0}}function Re(e){return e.pendingClarification===void 0?e:{...e,pendingClarification:void 0}}function Ce(e){return{...e,turnActive:!0,error:void 0,thinking:"",thinkingLog:[]}}function P(e,t){switch(t.type){case"thinking":return{...e,status:"thinking",thinking:e.thinking+t.delta};case"thinking_done":return{...e,thinkingLog:[...e.thinkingLog,{text:e.thinking,tookMs:t.tookMs}],thinking:""};case"progress":return{...e,progress:t.pct};case"snapshot":return{...e,scenarios:t.data.scenarios,status:t.data.status,headline:t.data.headline??e.headline};case"chat":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}]};case"clarification":return{...e,turnActive:!1,chatLog:[...e.chatLog,{role:"model",text:t.text}],pendingClarification:t.text};case"limit":return{...e,limits:{scenarioLimit:t.scenarioLimit,perScenarioLimit:t.perScenarioLimit}};case"error":return{...e,error:t.message};case"done":return{...e,status:t.status,turnActive:!1,error:t.status==="failed"&&!e.error?"generation failed":e.error}}}function H(e,t){let n=[],i=e.type??"",d=e.status??"";if(i==="ping")return n;switch(i){case"thinking_token":typeof e.data=="string"&&n.push({type:"thinking",delta:e.data});break;case"thinking_stopped":{let r=e.data??{},o=se(r.time_taken);n.push({type:"thinking_done",text:typeof e.data=="string"?e.data:r.message??"",tookMs:o});break}case"progress":{let r=e.data??{};typeof r.progress=="number"&&n.push({type:"progress",pct:r.progress});break}case"clarification":{let r=e.data??{};typeof r.message=="string"&&n.push({type:"clarification",text:r.message});break}case"chatting_stopped":{let r=e.data??{};typeof r.message=="string"&&r.message.length>0&&n.push({type:"chat",text:r.message});break}case"limit_update":{let r=e.data??{},o=r.test_cases_limit??e.test_cases_limit,p=r.per_scenario_test_cases_limit??e.per_scenario_test_cases_limit;n.push({type:"limit",scenarioLimit:o,perScenarioLimit:p});break}case"error":{let r=typeof e.data=="string"?e.data:e.data?.message??"generation error";n.push({type:"error",message:r});break}case"request_cancelled":return n.push({type:"done",status:"stopped"}),n;case"session_ended":return n.push({type:"done",status:"ended"}),n;default:break}if(Array.isArray(e.scenarios)&&n.push({type:"snapshot",data:{requestId:t,status:d,headline:e.headline,scenarios:e.scenarios}}),d&&U(d)){let r=d.trim().toLowerCase();n.push({type:"done",status:r})}return n}function se(e){if(!e)return;let t=/^([\d.]+)(ms|s)?$/.exec(e.trim());if(!t)return;let n=Number(t[1]);if(Number.isFinite(n))return t[2]==="ms"?Math.round(n):Math.round(n*1e3)}var v=class extends Error{constructor(t){super(t),this.name="AuthError"}},M=class extends Error{constructor(t){super(t),this.name="ForbiddenError"}},I=class extends Error{constructor(t){super(t),this.name="InsufficientCreditsError"}},k=class extends Error{constructor(n,i){super(n);this.cause=i;this.name="TransportError"}};function x(e,t){let n=t?.message??t?.error??`HTTP ${e}`;return e===401?new v(n):e===403?t?.key==="insufficient_credits"?new I(n):new M(n):new k(n)}async function*J(e){let t=e.fetchImpl??fetch,n=e.maxRetries??5,i=e.maxBackoffMs??3e4,d=e.connectTimeoutMs??1e4,r=0,o=!1;for(;;){if(e.signal.aborted)return;let p=new AbortController,a=()=>p.abort();e.signal.addEventListener("abort",a,{once:!0});let c=setTimeout(()=>p.abort(),d),g;try{g=await t(e.url,{method:"GET",headers:{Authorization:await e.authHeader(),Accept:"text/event-stream"},signal:p.signal})}catch(w){if(clearTimeout(c),e.signal.removeEventListener("abort",a),e.signal.aborted)return;if(++r>n)throw new k("SSE connect failed",w);await O(F(r,i));continue}if(clearTimeout(c),!g.ok){e.signal.removeEventListener("abort",a);let w=await oe(g);if(g.status===401&&o){if(++r>n)throw x(401,w);await O(F(r,i));continue}throw x(g.status,w)}if(!g.body)throw e.signal.removeEventListener("abort",a),new k("SSE response had no body");o=!0,r=0;let m=g.body.getReader(),h=new TextDecoder("utf-8"),b="";try{for(;;){if(e.signal.aborted){await m.cancel().catch(()=>{});return}let{done:w,value:s}=await m.read();if(w)break;b+=h.decode(s,{stream:!0});let f;for(;(f=b.indexOf(`
3
3
 
4
4
  `))>=0;){let u=b.slice(0,f);b=b.slice(f+2);let l=ie(u);l&&(yield l)}}}catch(w){if(e.signal.aborted)return;if(++r>n)throw new k("SSE stream dropped",w);await O(F(r,i));continue}finally{e.signal.removeEventListener("abort",a)}return}}function ie(e){let t="message",n="";for(let i of e.split(`
5
5
  `))i.startsWith("event:")?t=i.slice(6).trim():i.startsWith("data:")&&(n+=i.slice(5).trim());if(t!=="message"||!n)return null;try{let i=Buffer.from(n,"base64").toString("utf-8");return JSON.parse(i)}catch{return null}}function F(e,t){return Math.min(t,1e3*2**(e-1))}function O(e){return new Promise(t=>setTimeout(t,e))}async function oe(e){try{return await e.clone().json()}catch{return}}function W(e,t){t?.length&&(e.append("files",t.map(n=>n.fileKey).join(",")),e.append("gemini_metadata",JSON.stringify(t.map(n=>({fileData:{fileUri:n.geminiUri,mimeType:n.mimeType}})))))}function Ue(e,t={}){let n=t.fetchImpl??fetch,i=new Map,d=!0;async function r(){let s=await e.authResolver.resolve();if(!s)throw new v("unauthorized; run `kane-cli login`");return E(s.username,s.access_key)}function o(s){return`${e.baseUrl}${s}`}async function p(s){if(!s.ok){let f;try{f=await s.clone().json()}catch{f=void 0}throw x(s.status,f)}return s.json()}function a(s){let f=s?.data??s;return{request_id:f.request_id??f.id,status:f.status??""}}function c(s,f,u,l){let y=q({requestId:s,objective:f});l&&(y=P(y,{type:"snapshot",data:l}),l.status==="cleaned_up"&&(y={...y,error:"session was reaped (cleaned_up) \u2014 continuing will destructively regenerate"}));let S=new AbortController;u&&(u.aborted?S.abort():u.addEventListener("abort",()=>S.abort(),{once:!0})),i.set(s,S);let A={requestId:s,state:y,events:void 0};return A.events=(async function*(){try{let C=J({url:o(`/requests/${s}/sse`),authHeader:r,signal:S.signal,log:e.log,fetchImpl:n});for await(let L of C)for(let z of H(L,s))A.state=P(A.state,z),yield z}finally{i.delete(s)}})(),A}async function g(s,f){let u=new FormData;u.append("prompt",s.prompt),d=s.memoryEnhancement??!0,u.append("memory_enhancement",String(d)),s.scenarioLimit!==void 0&&u.append("test_scenario_limit",String(s.scenarioLimit)),s.perScenarioLimit!==void 0&&u.append("per_scenario_test_cases_limit",String(s.perScenarioLimit));let l=s.projectId??e.projectId,y=s.folderId??e.folderId;l&&u.append("project_id",l),y&&u.append("folder_id",y),W(u,s.attachments);let S=await n(o("/requests"),{method:"POST",headers:{Authorization:await r()},body:u}),A=await p(S),{request_id:C}=a(A),L=String(C);return c(L,s.prompt,f)}async function m(s,f){let u=await n(o(`/requests/${s}`),{method:"GET",headers:{Authorization:await r()}}),l=await p(u),y=l?.data??l,S={requestId:s,status:y.status??"",headline:y.headline,scenarios:Array.isArray(y.scenarios)?y.scenarios:[]};return c(s,"",f,S)}async function h(s,f,u){let l=new FormData;l.append("prompt",f),l.append("chat_enabled","true"),l.append("memory_enhancement",String(d)),u?.mappings&&l.append("mappings",JSON.stringify(u.mappings)),W(l,u?.attachments);let y=await n(o(`/requests/${s}`),{method:"PUT",headers:{Authorization:await r()},body:l});if(!y.ok){let S;try{S=await y.clone().json()}catch{}throw x(y.status,S)}}async function b(s){i.get(s)?.abort();let u=await n(o(`/requests/${s}/stop`),{method:"DELETE",headers:{Authorization:await r()}});if(!u.ok&&u.status!==404){let l;try{l=await u.clone().json()}catch{}throw x(u.status,l)}}async function w(s){i.get(s)?.abort();let u=await n(o(`/requests/${s}/end`),{method:"DELETE",headers:{Authorization:await r()}});if(!u.ok&&u.status!==404){let l;try{l=await u.clone().json()}catch{}throw x(u.status,l)}}return{start:g,attach:m,chat:h,cancel:b,end:w}}import{statSync as ae,realpathSync as G,existsSync as ce}from"fs";import{extname as ue,resolve as j,isAbsolute as pe}from"path";import{homedir as V}from"os";var de=new Set([".txt",".md",".json",".xml",".jpg",".jpeg",".png",".gif",".bmp",".webp",".pdf",".docx",".csv",".xlsx",".mp3",".wav",".m4a",".webm",".mpeg",".mpga",".mp4",".mov"]),le=50*1024*1024,X=10;function fe(e){return e==="~"?V():e.startsWith("~/")?j(V(),e.slice(2)):e}function Ge(e,t){let n=[],i=[],d=new Set,r=[],o=(()=>{try{return G(j(t))}catch{return j(t)}})(),p=o.endsWith("/")?o:o+"/";for(let a of e){let c=fe(a),g=pe(c)?c:j(t,c);if(!ce(g)){n.push(`Not found: ${a}`);continue}let m;try{m=G(g)}catch{n.push(`Cannot resolve: ${a}`);continue}if(d.has(m))continue;let h;try{h=ae(m)}catch{n.push(`Cannot read: ${a}`);continue}if(!h.isFile()){n.push(`Not a file: ${a}`);continue}if(h.size===0){n.push(`Empty file: ${a}`);continue}let b=ue(m).toLowerCase();if(!de.has(b)){n.push(`Unsupported type ${b||"(none)"}: ${a}`);continue}if(h.size>le){n.push(`Too large (>50MB): ${a}`);continue}m!==o&&!m.startsWith(p)&&i.push(`Outside working dir: ${a}`),d.add(m),r.push(m)}return r.length>X&&n.push(`Too many files: ${r.length} (max ${X})`),{ok:n.length?[]:r,errors:n,warnings:i}}var B=class extends Error{constructor(n){super(n.join("; "));this.errors=n;this.name="AttachmentValidationError"}};async function Xe(e){let{promptText:t,filePaths:n,cwd:i,scenarios:d,isRefine:r,conn:o,deps:p}=e,{ok:a,errors:c,warnings:g}=p.validate(n,i);if(c.length)throw new B(c);e.onValidated?.();let m=a.length?await p.upload(o,a,p.onUpload):[],h=r?p.buildMappings(t,d):void 0;return{promptText:t,mappings:h,attachments:m,warnings:g}}import{readFile as me}from"fs/promises";import{basename as K}from"path";async function ge(e){let t=await e.authResolver.resolve();if(!t)throw new v("unauthorized; run `kane-cli login`");return E(t.username,t.access_key)}async function he(e,t,n={}){let i=n.fetchImpl??fetch,d=await me(t),r=K(t),o=new FormData;o.append("file",new Blob([d]),r),o.append("source","omniBox"),o.append("geminiFileUpload","true");let p=await i(`${e.tmsBaseUrl}/v1/attachment`,{method:"POST",headers:{Authorization:await ge(e)},body:o,signal:n.signal});if(!p.ok){let h;try{h=await p.clone().json()}catch{}throw x(p.status,h)}let a=await p.json(),c=a?.data??a,g=c?.gemini_response?.uri,m=c?.gemini_response?.mimeType;if(!c?.file_key||!g){let h=c&&typeof c=="object"?Object.keys(c).join(","):typeof c,b=(()=>{try{return JSON.stringify(c).slice(0,500)}catch{return"<unserializable>"}})();throw new Error(`attachment upload for ${r} returned no file_key/gemini uri \u2014 status ${p.status}, body keys: [${h}], raw: ${b}`)}return{fileName:c.file_name??r,fileKey:c.file_key,geminiUri:g,mimeType:m??"application/octet-stream"}}async function tt(e,t,n,i={}){let d=[];for(let r=0;r<t.length;r++){if(i.signal?.aborted)throw Object.assign(new Error("upload aborted"),{name:"AbortError"});let o=K(t[r]);n?.({file:o,index:r+1,total:t.length,status:"uploading"});try{d.push(await he(e,t[r],i)),n?.({file:o,index:r+1,total:t.length,status:"done"})}catch(p){throw n?.({file:o,index:r+1,total:t.length,status:"failed"}),p}}return d}var ye=/@([sS])(\d+)\.([cC])(\d+)/g,be=/@([sS])(\d+)(?!\d)(?!\.[cC]\d)/g;function rt(e,t){let n={},i={};for(let d of e.matchAll(ye)){let r=Number(d[2]),o=Number(d[4]),p=t[r-1];if(!p)continue;n[`s${r}`]=String(p.id);let a=p.test_cases??[];if(a[o-1])for(let c=0;c<o;c++){let g=a[c];g&&(i[`s${r}.c${c+1}`]=String(g.id))}}for(let d of e.matchAll(be)){let r=Number(d[2]),o=t[r-1];o&&(n[`s${r}`]=String(o.id))}if(!(Object.keys(n).length===0&&Object.keys(i).length===0))return{scenario:n,testcase:i}}function R(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(n==null||typeof n!="object")return[];let i=n;if(typeof i.step!="string")return[];let d=typeof i.expected_result=="string"?i.expected_result:typeof i.outcome=="string"?i.outcome:"";t.push({step:i.step,expected:d})}return t}var we=30,Se=300;function Z(){return{mode:"testing",max_steps:we,timeout:Se,variables:{}}}function Q(e){return e.title??`Test case ${e.id}`}function ct(e,t){return $({frontmatter:Z(),heading:Q(t),steps:e.sub_objectives.map(n=>n.objective)})}function Y(e){let t=R(e.manual_steps).map(n=>n.step);return $({frontmatter:Z(),heading:Q(e),steps:t})}import{mkdtempSync as xe,mkdirSync as N,writeFileSync as ee,rmSync as te,renameSync as _e,existsSync as ne,readFileSync as ve}from"fs";import{join as _,resolve as ke}from"path";async function ft(e,t,n,i=Y){(n.redirectBareCwd??!0)&&ke(t)===process.cwd()&&(t=_(t,".testmuai","tests"));let d=T(e.objective)??e.headline,r=T(n.suiteName)??`${T(re(d,4))??"tcg"}-${e.requestId}`,o=r,p=_(t,r);ne(p)&&!Te(p,e.requestId)&&(o=`${r}-${e.requestId}`);let a=_(t,o),c=[],g=new Map;for(let h of e.scenarios){let b=(h.test_cases??[]).filter(Ae);if(b.length===0)continue;let w=T(Ee(h.scode))??T(h.sid)??`s${h.id}`,s=g.get(w)??new Set;g.set(w,s);for(let f of b){let u=T(re(f.title,5))??"case",l=`${u}_test.md`;for(let y=2;s.has(l);y++)l=`${u}-${y}_test.md`;s.add(l),c.push({dir:w,file:l,tc:f})}}if(c.length===0)return{suiteDir:a,paths:[],warning:"no functional test cases generated"};N(t,{recursive:!0});let m=xe(_(t,".tcg-tmp-"));try{N(_(m,"helpers"),{recursive:!0}),ee(_(m,".tcg-suite.json"),JSON.stringify({requestId:e.requestId,suiteName:o}));let h=[],b=new Set;for(let s of c){let f=_(m,s.dir);b.has(f)||(N(f,{recursive:!0}),b.add(f));let u=_(f,s.file);ee(u,i(s.tc)),h.push(u)}ne(a)&&te(a,{recursive:!0,force:!0}),_e(m,a);let w=h.map(s=>s.replace(m,a));return{suiteDir:a,paths:w}}catch(h){try{te(m,{recursive:!0,force:!0})}catch{}throw h}}function Ae(e){return(e.category??"").trim().toLowerCase()==="functional"}function Te(e,t){try{return JSON.parse(ve(_(e,".tcg-suite.json"),"utf-8"))?.requestId===t}catch{return!1}}function T(e){return e&&e.length>0?e:void 0}function re(e,t){return e?e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(Boolean).slice(0,t).join("-"):""}function Ee(e){return e?e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,""):""}function ht(e){let t=[];e.title&&t.push(e.title),e.description&&t.push("",e.description);let n=R(e.manual_steps);return n.length>0&&(t.push("","Steps:"),n.forEach((i,d)=>{t.push(`${d+1}. ${i.step}`)})),t.join(`
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f}from"./chunk-7VTYRTEJ.js";import{y as r}from"./chunk-PH22FRN5.js";import{a as g}from"./chunk-HCBYKLMW.js";import{a as i,b as n,i as p}from"./chunk-C44QQJR4.js";import{a as x}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var b=d(x(),1);var e=d(g(),1),v=[{value:"desktop",label:"Desktop",hint:"Chrome on this machine"},{value:"emulator",label:"Emulator",hint:"a virtual Android device"},{value:"simulator",label:"Simulator",hint:"a virtual iOS device"}];function T(a){return a==="all"?v:v.filter(l=>l.value!=="desktop")}function B({mode:a="all",onSelect:l,onCancel:c}){let u=T(a),[h,m]=(0,b.useState)(0);return p((s,o)=>{if(o.escape&&c){c();return}o.upArrow&&m(t=>Math.max(0,t-1)),o.downArrow&&m(t=>Math.min(u.length-1,t+1)),o.return&&l(u[h].value)}),(0,e.jsxs)(i,{flexDirection:"column",borderStyle:"round",borderColor:r.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(n,{color:r.orange,bold:!0,children:a==="all"?"Where should tests run?":"Which kind of device?"}),(0,e.jsx)(i,{marginTop:1,flexDirection:"column",children:u.map((s,o)=>{let t=o===h;return(0,e.jsxs)(i,{children:[(0,e.jsxs)(n,{color:t?r.orange:void 0,children:[t?"\u276F ":" ",s.label]}),(0,e.jsxs)(n,{color:r.dim,children:[" ",s.hint]})]},s.value)})}),(0,e.jsx)(i,{marginTop:1,children:(0,e.jsx)(n,{color:r.dim,children:"You can change this any time with /desktop or /mobile."})}),(0,e.jsx)(f,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],suppressEscBack:!c,escBackLabel:"skip"})]})}export{B as a};
2
+ import{a as f}from"./chunk-ZIRMSWKS.js";import{x as r}from"./chunk-CCUGKBIH.js";import{a as g}from"./chunk-HCBYKLMW.js";import{a as i,b as n,i as p}from"./chunk-C44QQJR4.js";import{a as x}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var b=d(x(),1);var e=d(g(),1),v=[{value:"desktop",label:"Desktop",hint:"Chrome on this machine"},{value:"emulator",label:"Emulator",hint:"a virtual Android device"},{value:"simulator",label:"Simulator",hint:"a virtual iOS device"}];function T(a){return a==="all"?v:v.filter(l=>l.value!=="desktop")}function B({mode:a="all",onSelect:l,onCancel:c}){let u=T(a),[h,m]=(0,b.useState)(0);return p((s,o)=>{if(o.escape&&c){c();return}o.upArrow&&m(t=>Math.max(0,t-1)),o.downArrow&&m(t=>Math.min(u.length-1,t+1)),o.return&&l(u[h].value)}),(0,e.jsxs)(i,{flexDirection:"column",borderStyle:"round",borderColor:r.orange,paddingX:2,paddingY:1,children:[(0,e.jsx)(n,{color:r.orange,bold:!0,children:a==="all"?"Where should tests run?":"Which kind of device?"}),(0,e.jsx)(i,{marginTop:1,flexDirection:"column",children:u.map((s,o)=>{let t=o===h;return(0,e.jsxs)(i,{children:[(0,e.jsxs)(n,{color:t?r.orange:void 0,children:[t?"\u276F ":" ",s.label]}),(0,e.jsxs)(n,{color:r.dim,children:[" ",s.hint]})]},s.value)})}),(0,e.jsx)(i,{marginTop:1,children:(0,e.jsx)(n,{color:r.dim,children:"You can change this any time with /desktop or /mobile."})}),(0,e.jsx)(f,{bindings:[{keys:"\u2191\u2193",label:"navigate"},{keys:"\u21B5",label:"select"}],suppressEscBack:!c,escBackLabel:"skip"})]})}export{B as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as y}from"./chunk-JT7I6OST.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-WLOGO44E.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};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as n}from"./chunk-PH22FRN5.js";import{createHash as _}from"crypto";import{existsSync as m,readFileSync as u}from"fs";import{dirname as T,join as f,resolve as o}from"path";import{fileURLToPath as E}from"url";var s=T(E(import.meta.url)),l=2;function p(e,r){let t=_("sha256");return t.update(`kane-assurance-contract
2
+ import{a as n}from"./chunk-CCUGKBIH.js";import{createHash as _}from"crypto";import{existsSync as m,readFileSync as u}from"fs";import{dirname as T,join as f,resolve as o}from"path";import{fileURLToPath as E}from"url";var s=T(E(import.meta.url)),l=2;function p(e,r){let t=_("sha256");return t.update(`kane-assurance-contract
3
3
  `),t.update(e),t.update(`
4
4
  agent_state_schema=${r}`),"sha256:"+t.digest("hex")}function d(){return[o(s,".."),o(s,"../../..")]}function i(){return"sha256:85dd52f33a9fd9cf22ebb81f04dfd3c05bdbeca2e62e3a7a53e8caaaa4060752"}var a=class extends Error{constructor(t,c){super(`agent/cli contract mismatch (cli ${t||"<unset>"}, agent ${c||"<unset>"}) \u2014 rebuild or reinstall the stale half`);this.expected=t;this.actual=c;this.name="PairMismatchError"}};function I(){return{TESTMUAI_CONTRACT_DIGEST:i(),TESTMUAI_CLIENT_VERSION:process.env.KANE_DEV_FORCE_CLIENT_RELEASE??`kane-cli/${n}`}}export{a,I as b};
@@ -1,10 +1,10 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as D,b as F}from"./chunk-2UIHS2FH.js";import{a as ce}from"./chunk-YKTYVJBN.js";import{a as k,b as se,c as ie,d as ae,k as P}from"./chunk-X2FM67OM.js";import{a as J}from"./chunk-N2P4MI32.js";import{b as B,d as M}from"./chunk-NVGBE2DR.js";import{A as x}from"./chunk-TH47OOBV.js";import{x as oe}from"./chunk-PH22FRN5.js";var v="https://integrations.lambdatest.com",b=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function Re(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${oe[n].shareApiBaseUrl}/lis/api/v1`}function $e(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 $(t){let n=t.split(`
2
+ import{a as D,b as F}from"./chunk-2UIHS2FH.js";import{a as ce}from"./chunk-YKTYVJBN.js";import{a as k,b as se,c as ie,d as ae,k as P}from"./chunk-X2FM67OM.js";import{a as J}from"./chunk-N2P4MI32.js";import{b as B,d as M}from"./chunk-NVGBE2DR.js";import{A as x}from"./chunk-TH47OOBV.js";import{w as oe}from"./chunk-CCUGKBIH.js";var v="https://integrations.lambdatest.com",b=class extends Error{constructor(e,r){super(r);this.code=e;this.name="LisError"}};function Re(t){let n=t.TESTMUAI_ENV==="stage"?"stage":"prod";return`${oe[n].shareApiBaseUrl}/lis/api/v1`}function $e(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 $(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 Te(t,n,e="the issue"){return t===401||t===403?new b("LIS_AUTH","credentials rejected \u2014 run `kane-cli login` and retry"):t>=500?new b("LIS_UNAVAILABLE",`the integrations service returned an error (HTTP ${t}) \u2014 retry later`):new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${e}: ${$(n)||`HTTP ${t}`}`)}function j(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{throw new b("LIS_UNAVAILABLE","the integrations service returned a malformed response \u2014 retry later")}}function ee(t){try{return JSON.parse(t.bytes.toString("utf8"))}catch{return{}}}function ue(t){return ee(t).code}function C(t,n="the issue"){let e=ee(t);switch(e.code){case"TOKEN_EXPIRED":return new b("LIS_SETUP",`your Atlassian connection needs a resync \u2014 reconnect at ${v} and retry`);case"NOT_INSTALLED":return new b("LIS_SETUP",`no Atlassian connection for this account \u2014 create one at ${v} and retry`);case"SCOPE_MISSING":return new b("LIS_SETUP",`the connection has no Confluence access \u2014 reconnect with Confluence at ${v} and retry`);case"FORBIDDEN":return new b("LIS_FORBIDDEN",`you don't have access to ${n}`);case"NOT_FOUND":return new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch ${n}: ${$(e.message??"")||"not found"}`);case"PAYLOAD_TOO_LARGE":return new b("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");case"INVALID_PAYLOAD":return new b("LIS_UNAVAILABLE",`the integrations service rejected the request (${$(e.message??"")||"invalid payload"}) \u2014 retry later`);case"NOT_SUPPORTED":return new b("LIS_UNAVAILABLE","the integrations service does not support this operation yet");case"UPSTREAM_ERROR":case"UPSTREAM_TIMEOUT":return new b("LIS_UNAVAILABLE","Atlassian is not responding through the integrations service \u2014 retry later");default:return Te(t.status,e.message??"",n)}}var Ce=3e4,Oe=5;async function O(t,n,e){let r=e.env??process.env,l=e.fetchImpl??fetch;for(let o=0;;o++){let d=new AbortController,f=setTimeout(()=>d.abort(),Ce);try{let i=await l(`${Re(r)}${t}`,{...n,headers:{"content-type":"application/json",...$e(e),...n.headers??{}},signal:d.signal}),c=await Promise.race([i.arrayBuffer(),new Promise((a,s)=>{d.signal.addEventListener("abort",()=>s(new DOMException("aborted","AbortError")),{once:!0})})]),u={status:i.status,ok:i.ok,headers:i.headers,bytes:Buffer.from(c)};if(u.status===429){if(o>0)throw new b("LIS_RATE_LIMITED","the integrations service is busy \u2014 try again in a moment");let a=ee(u).data?.retry_after_sec,s=Math.min(Math.max(typeof a=="number"&&Number.isFinite(a)?a:1,0),Oe);clearTimeout(f),await new Promise(y=>setTimeout(y,s*1e3));continue}return u}catch(i){throw i instanceof b?i:d.signal.aborted?new b("LIS_UNAVAILABLE","the integrations service did not respond within 30 seconds \u2014 retry later"):new b("LIS_UNAVAILABLE",`could not reach the integrations service (${$(i instanceof Error?i.message:String(i))}) \u2014 check your connection and retry`)}finally{clearTimeout(f)}}}function K(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 V(t={}){let n=await O("/jira/info",{method:"GET"},t);if(!n.ok)throw C(n);let e=j(n),r=(e.data?.SELECTED_PROJECTS??[]).map(l=>l?.key).filter(l=>typeof l=="string"&&l.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 W(t,n={}){let e=await O("/jira/issue?details=true",{method:"POST",body:JSON.stringify({plugin_code:"jira",issueKey:t})},n);if(!e.ok)throw C(e);let r=j(e);if(r.type==="error"||!r.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue: ${$(r.message??"")||"issue not found or not accessible"}`);return r.data}var le=100,Ne=5e3,ke=60;async function G(t,n={}){let e=[],r=new Set,l=null,o=0;for(let d=0;;d++){if(d>=ke)throw new b("LIS_UNAVAILABLE","the integrations service kept returning comment pages without finishing \u2014 retry later");let f=await O("/jira/issue/comments",{method:"POST",body:JSON.stringify({resource_id:t,max_results:le,cursor:l,start_at:o,order_by:"created",fetch_all:!1})},n);if(!f.ok)throw C(f,"the issue's comments");let i=j(f);if(i.type==="error"||!i.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the issue's comments: ${$(i.message??"")||"unavailable"}`);for(let L of i.data.comments??[]){let m=String(L.id);r.has(m)||(r.add(m),e.push(L))}let c=i.data.pagination;if(!c?.has_more)return e;if(e.length>=Ne)throw new b("JIRA_ISSUE_UNAVAILABLE","the issue has more comments than can be ingested \u2014 cannot build a complete identity");let u=c.next_cursor??null,a=c.next_start_at!=null,s=a?c.next_start_at:o+le;if(!(u!=null&&u!==l||u==null&&a&&s!==o))throw new b("LIS_UNAVAILABLE","the integrations service returned a non-advancing comments page \u2014 retry later");l=u,o=s}}async function Y(t,n={}){let e=await O("/jira/attachment",{method:"POST",body:JSON.stringify({attachment_id:t})},n);if(!e.ok){if(ue(e)===void 0){if(e.status===413)throw new b("ATTACHMENT_TOO_LARGE","the attachment exceeds the integrations service's size cap");if(e.status===404)throw new b("JIRA_NOT_CONNECTED",`Jira is not connected for this account \u2014 connect it at ${v} and retry`)}throw C(e,`attachment ${t}`)}return K(e)}var H="kane.source.jira/2";function pe(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(pe).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 de(t,n,e){let r=[],l={},o=t.additional_fields??{};for(let u of Object.keys(o).sort()){let a=pe(o[u]);if(a===null){r.push(`field "${u}" has no stable text form \u2014 dropped from the envelope`);continue}l[u]=a}let d=[...t.attachments??[]].map(u=>({id:String(u.id),filename:u.filename??"",media_type:u.mime_type??"application/octet-stream",size:u.size??0})).sort((u,a)=>{let s=Number(u.id),y=Number(a.id);return Number.isFinite(s)&&Number.isFinite(y)?s-y:u.id<a.id?-1:u.id>a.id?1:0}),f=e.map(u=>({id:String(u.id),author:u.author?.display_name??"",body:u.body??"",created:u.created??""})).sort((u,a)=>{if(u.created!==a.created)return u.created<a.created?-1:1;let s=Number(u.id),y=Number(a.id);return Number.isFinite(s)&&Number.isFinite(y)&&s!==y?s-y:u.id<a.id?-1:u.id>a.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:H,site:n,project:i.slice(0,i.lastIndexOf("-")),issue:{id:t.id,key:i},content:{summary:t.summary??"",description:t.description??"",fields:l},attachments:d,comments:f};return{bytes:Buffer.from(JSON.stringify(c),"utf8"),envelope:c,warnings:r}}var me=64,Pe=16,je=6e6,Ue=5e7,xe=12e6,Be={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"},Me=new Set(["png","jpeg","webp"]);function fe(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!==H)throw new Error(`JIRA_ENVELOPE_SCHEMA: unknown envelope schema "${e.schema}" \u2014 this CLI understands ${H}`);let r=[],l=new Map,o=[],d=0,f=new Map,i=[];for(let a=0;a<e.attachments.length;a++){let s=e.attachments[a],y=`i${a+1}`,L=`attachment:${s.filename}`,m=I=>`[img#${y}] ${s.filename} (${s.media_type}, ${s.size} bytes${I?"":" \u2014 not delivered"})`,g=(I,A,T)=>{r.push({ref:y,loc:L,media_type:I,...T?.blob?{blob:T.blob}:{},...T?.appearance?{appearance:T.appearance}:{},delivery:A,...T?.duplicate_of?{duplicate_of:T.duplicate_of}:{}})};if(!s.media_type.startsWith("image/")){g(s.media_type,"unsupported-vision-media-type"),i.push(m(!1));continue}let S;try{S=await t.fetchAttachment(s.id)}catch{g(s.media_type,"external-image-not-fetched"),i.push(m(!1));continue}let h=S.bytes,p=D(h),_=Be[p.format],E=B(h);if(l.set(E,h),!Me.has(p.format)){let I=p.format==="gif"||p.format==="bmp"||p.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";g(_,I,{blob:E}),i.push(m(!1));continue}if(p.width===void 0||p.height===void 0||p.width*p.height>Ue){g(_,"undecodable",{blob:E}),i.push(m(!1));continue}let w;if(p.format==="png"||p.format==="jpeg"){let I=F(h,p.format);if(I===null){g(_,"undecodable",{blob:E}),i.push(m(!1));continue}w=J(I.data,{width:I.width,height:I.height,channels:I.channels})}if(p.width<me||p.height<me){g(_,"below-dimension-floor",{blob:E,appearance:w}),i.push(m(!1));continue}let R=f.get(E);if(R!==void 0){g(_,"duplicate",{blob:E,appearance:w,duplicate_of:R}),i.push(m(!1));continue}if(h.byteLength>je){g(_,"image-too-large",{blob:E,appearance:w}),i.push(m(!1));continue}if(d+h.byteLength>xe){g(_,"vision-byte-budget-reached",{blob:E,appearance:w}),i.push(m(!1));continue}if(o.length>=Pe){g(_,"image-cap-reached",{blob:E,appearance:w}),i.push(m(!1));continue}f.set(E,y),d+=h.byteLength,o.push(y),g(_,"selected",{blob:E,appearance:w}),i.push(m(!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 u=Object.keys(e.content.fields);return u.length>0&&c.push("","--- fields ---",...u.map(a=>`${a}: ${e.content.fields[a]}`)),i.length>0&&c.push("","--- attachments ---",...i),e.comments.length>0&&(c.push("","--- comments ---"),e.comments.forEach((a,s)=>{s>0&&c.push(""),c.push(`[${s+1}] ${a.author} \xB7 ${a.created}`,...a.body.split(`
5
5
  `))})),{projection:c.join(`
6
6
  `)+`
7
- `,inventory:r,blobs:l,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var Je=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function z(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 l=e[r+1];return Je.test(l)?{site:n.hostname,issueKey:l.toUpperCase()}:null}function X(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return typeof d.site=="string"&&d.site.length>0?d.site:null}catch{return null}}async function De(t,n,e,r,l){let o=z(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 d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G};try{let i={auth:await(l?.authEnv??(await import("./auth-JVH2EHK2.js")).resolveLisAuthEnv)(),env:process.env},c=await d.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${v} 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 ${v} and retry`),{code:1};let u=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(u))return(e.err??e.out)(`error: ${t}: project ${u} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${v}`),{code:1};let a=await d.jiraIssue(o.issueKey,i),s=await d.jiraComments(o.issueKey,i),y=o.site;if(a.host)try{y=new URL(a.host).hostname}catch{y=a.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:L,warnings:m}=de(a,y,s),g=n??o.issueKey.toLowerCase();k(g);let S=X(r,g);if(S!==null&&S!==y)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${S}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let h=await P({contextDir:r,bytes:L,media:se,sourceId:g,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{jira:fe({fetchAttachment:p=>d.jiraAttachment(p,i)})}});e.out(U(e.isTTY,h,o.issueKey));for(let p of m)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: jira, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(f){return f instanceof b?((e.err??e.out)(`error: ${t}: ${f.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${Fe(f instanceof Error?f.message:String(f))}`),{code:1})}}function Fe(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 ge={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>z(t)!==null,ingest:De,sourceIdFor:t=>{let n=z(t);return n?n.issueKey.toLowerCase():null}};async function he(t,n={}){let e=await O("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw C(e,"the page");let r=j(e);if(r.type==="error"||!r.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${$(r.message??"")||"page not found or not accessible"}`);return r.data}async function ye(t,n={}){let e=await O("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw C(e,"the page's attachment");return{bytes:K(e).bytes}}var q="kane.source.confluence/1";function be(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,d)=>o.id<d.id?-1:o.id>d.id?1:0),l={schema:q,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(l),"utf8"),envelope:l,warnings:[]}}var _e=64,Ke=16,Ve=6e6,We=5e7,Ge=12e6,Ye={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"},He=new Set(["png","jpeg","webp"]);function Ee(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!==q)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${q}`);let l=[],o=new Map,d=[],f=0,i=new Map,c=[];for(let a=0;a<r.attachments.length;a++){let s=r.attachments[a],y=`i${a+1}`,L=`attachment:${s.filename}`,m=A=>`[img#${y}] ${s.filename} (${s.media_type}, ${s.size} bytes${A?"":" \u2014 not delivered"})`,g=(A,T,N)=>{l.push({ref:y,loc:L,media_type:A,...N?.blob?{blob:N.blob}:{},...N?.appearance?{appearance:N.appearance}:{},delivery:T,...N?.duplicate_of?{duplicate_of:N.duplicate_of}:{}})};if(!s.media_type.startsWith("image/")){g(s.media_type,"unsupported-vision-media-type"),c.push(m(!1));continue}let S=n.get(s.id);if(!S){g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let h;try{h=await t.fetchAttachment({id:s.id,download:S})}catch{g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let p=h.bytes,_=D(p),E=Ye[_.format],w=B(p);if(o.set(w,p),!He.has(_.format)){let A=_.format==="gif"||_.format==="bmp"||_.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";g(E,A,{blob:w}),c.push(m(!1));continue}if(_.width===void 0||_.height===void 0||_.width*_.height>We){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}let R;if(_.format==="png"||_.format==="jpeg"){let A=F(p,_.format);if(A===null){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}R=J(A.data,{width:A.width,height:A.height,channels:A.channels})}if(_.width<_e||_.height<_e){g(E,"below-dimension-floor",{blob:w,appearance:R}),c.push(m(!1));continue}let I=i.get(w);if(I!==void 0){g(E,"duplicate",{blob:w,appearance:R,duplicate_of:I}),c.push(m(!1));continue}if(p.byteLength>Ve){g(E,"image-too-large",{blob:w,appearance:R}),c.push(m(!1));continue}if(f+p.byteLength>Ge){g(E,"vision-byte-budget-reached",{blob:w,appearance:R}),c.push(m(!1));continue}if(d.length>=Ke){g(E,"image-cap-reached",{blob:w,appearance:R}),c.push(m(!1));continue}i.set(w,y),f+=p.byteLength,d.push(y),g(E,"selected",{blob:w,appearance:R}),c.push(m(!0))}let u=[];return u.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&u.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&u.push("",...r.content.body.split(`
7
+ `,inventory:r,blobs:l,delivered:o,converter:{name:"jira-convert",version:"2",policy:"v1"}}}}var Je=/^[A-Za-z][A-Za-z0-9_]*-\d+$/;function z(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 l=e[r+1];return Je.test(l)?{site:n.hostname,issueKey:l.toUpperCase()}:null}function X(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return typeof d.site=="string"&&d.site.length>0?d.site:null}catch{return null}}async function De(t,n,e,r,l){let o=z(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 d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G};try{let i={auth:await(l?.authEnv??(await import("./auth-3DLNMZC2.js")).resolveLisAuthEnv)(),env:process.env},c=await d.jiraInfo(i);if(!c.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${v} 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 ${v} and retry`),{code:1};let u=o.issueKey.slice(0,o.issueKey.lastIndexOf("-"));if(!c.selectAll&&c.selectedProjects.length>0&&!c.selectedProjects.includes(u))return(e.err??e.out)(`error: ${t}: project ${u} is not in the integration's selected projects (${c.selectedProjects.join(", ")}) \u2014 add it at ${v}`),{code:1};let a=await d.jiraIssue(o.issueKey,i),s=await d.jiraComments(o.issueKey,i),y=o.site;if(a.host)try{y=new URL(a.host).hostname}catch{y=a.host.replace(/^https?:\/\//,"").replace(/[/:].*$/,"")}let{bytes:L,warnings:m}=de(a,y,s),g=n??o.issueKey.toLowerCase();k(g);let S=X(r,g);if(S!==null&&S!==y)return(e.err??e.out)(`error: ${t}: source '${g}' was ingested from ${S}, but this read serves ${y} \u2014 retire it first (kane-cli context retire ${g}) or ingest under a different id with --as`),{code:1};let h=await P({contextDir:r,bytes:L,media:se,sourceId:g,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{jira:fe({fetchAttachment:p=>d.jiraAttachment(p,i)})}});e.out(U(e.isTTY,h,o.issueKey));for(let p of m)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: jira, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(f){return f instanceof b?((e.err??e.out)(`error: ${t}: ${f.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${Fe(f instanceof Error?f.message:String(f))}`),{code:1})}}function Fe(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 ge={name:"jira",hint:"Jira issue URLs (https://<site>/browse/KEY-123)",match:t=>z(t)!==null,ingest:De,sourceIdFor:t=>{let n=z(t);return n?n.issueKey.toLowerCase():null}};async function he(t,n={}){let e=await O("/jira/document",{method:"POST",body:JSON.stringify({resource_id:t,format:"markdown"})},n);if(!e.ok)throw C(e,"the page");let r=j(e);if(r.type==="error"||!r.data)throw new b("JIRA_ISSUE_UNAVAILABLE",`could not fetch the page: ${$(r.message??"")||"page not found or not accessible"}`);return r.data}async function ye(t,n={}){let e=await O("/jira/attachment",{method:"POST",body:JSON.stringify({source:"confluence",download:t})},n);if(!e.ok)throw C(e,"the page's attachment");return{bytes:K(e).bytes}}var q="kane.source.confluence/1";function be(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,d)=>o.id<d.id?-1:o.id>d.id?1:0),l={schema:q,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(l),"utf8"),envelope:l,warnings:[]}}var _e=64,Ke=16,Ve=6e6,We=5e7,Ge=12e6,Ye={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"},He=new Set(["png","jpeg","webp"]);function Ee(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!==q)throw new Error(`CONFLUENCE_ENVELOPE_SCHEMA: unknown envelope schema "${r.schema}" \u2014 this CLI understands ${q}`);let l=[],o=new Map,d=[],f=0,i=new Map,c=[];for(let a=0;a<r.attachments.length;a++){let s=r.attachments[a],y=`i${a+1}`,L=`attachment:${s.filename}`,m=A=>`[img#${y}] ${s.filename} (${s.media_type}, ${s.size} bytes${A?"":" \u2014 not delivered"})`,g=(A,T,N)=>{l.push({ref:y,loc:L,media_type:A,...N?.blob?{blob:N.blob}:{},...N?.appearance?{appearance:N.appearance}:{},delivery:T,...N?.duplicate_of?{duplicate_of:N.duplicate_of}:{}})};if(!s.media_type.startsWith("image/")){g(s.media_type,"unsupported-vision-media-type"),c.push(m(!1));continue}let S=n.get(s.id);if(!S){g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let h;try{h=await t.fetchAttachment({id:s.id,download:S})}catch{g(s.media_type,"external-image-not-fetched"),c.push(m(!1));continue}let p=h.bytes,_=D(p),E=Ye[_.format],w=B(p);if(o.set(w,p),!He.has(_.format)){let A=_.format==="gif"||_.format==="bmp"||_.format==="tiff"?"unsupported-vision-media-type":"unsupported-image-kind";g(E,A,{blob:w}),c.push(m(!1));continue}if(_.width===void 0||_.height===void 0||_.width*_.height>We){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}let R;if(_.format==="png"||_.format==="jpeg"){let A=F(p,_.format);if(A===null){g(E,"undecodable",{blob:w}),c.push(m(!1));continue}R=J(A.data,{width:A.width,height:A.height,channels:A.channels})}if(_.width<_e||_.height<_e){g(E,"below-dimension-floor",{blob:w,appearance:R}),c.push(m(!1));continue}let I=i.get(w);if(I!==void 0){g(E,"duplicate",{blob:w,appearance:R,duplicate_of:I}),c.push(m(!1));continue}if(p.byteLength>Ve){g(E,"image-too-large",{blob:w,appearance:R}),c.push(m(!1));continue}if(f+p.byteLength>Ge){g(E,"vision-byte-budget-reached",{blob:w,appearance:R}),c.push(m(!1));continue}if(d.length>=Ke){g(E,"image-cap-reached",{blob:w,appearance:R}),c.push(m(!1));continue}i.set(w,y),f+=p.byteLength,d.push(y),g(E,"selected",{blob:w,appearance:R}),c.push(m(!0))}let u=[];return u.push(`${r.title} \xB7 ${r.site} \xB7 ${r.space.key}`),r.labels.length>0&&u.push(`labels: ${r.labels.join(", ")}`),r.content.body!==""&&u.push("",...r.content.body.split(`
8
8
  `)),c.length>0&&u.push("","--- attachments ---",...c),{projection:u.join(`
9
9
  `)+`
10
- `,inventory:l,blobs:o,delivered:d,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var ze=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function Z(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 l=e[r+2],o=e[r+4];return l===void 0||o===void 0||!ze.test(l)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:l,pageId:o}}async function Xe(t,n,e,r,l){let o=Z(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 d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G},f=l?.confluence??{confluenceDocument:he,confluenceAttachment:ye};try{let c={auth:await(l?.authEnv??(await import("./auth-JVH2EHK2.js")).resolveLisAuthEnv)(),env:process.env},u=await d.jiraInfo(c);if(!u.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${v} and retry`),{code:1};if(u.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${v} and retry`),{code:1};let a=await f.confluenceDocument(o.pageId,c),s=o.site;if(a.url)try{s=new URL(a.url).hostname}catch{}let{bytes:y,warnings:L}=be(a,s),m=n??`page-${o.pageId}`;k(m);let g=X(r,m);if(g!==null&&g!==s)return(e.err??e.out)(`error: ${t}: source '${m}' was ingested from ${g}, but this read serves ${s} \u2014 retire it first (kane-cli context retire ${m}) or ingest under a different id with --as`),{code:1};let S=Object.fromEntries((a.attachments??[]).filter(p=>typeof p.download=="string"&&p.download.length>0).map(p=>[String(p.id),p.download])),h=await P({contextDir:r,bytes:y,media:ie,sourceId:m,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{confluence:Ee({downloads:S,fetchAttachment:p=>f.confluenceAttachment(p.download,c)})}});e.out(U(e.isTTY,h,`${o.spaceKey}/${o.pageId}`));for(let p of L)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: confluence, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(i){return i instanceof b?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${qe(i instanceof Error?i.message:String(i))}`),{code:1})}}function qe(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 we={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>Z(t)!==null,ingest:Xe,sourceIdFor:t=>{let n=Z(t);return n?`page-${n.pageId}`:null}};var Ze=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 Ie(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,l=ce(e),o={"Content-Type":"application/json"},d=await n.authEnv(),f=d.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=d.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;f?o.Authorization=`Basic ${f}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${l}/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 u;try{u=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let s=u.page;return s===void 0||typeof s.markdown!="string"||s.markdown===""||typeof s.final_url!="string"||s.final_url===""||typeof s.projection?.kind!="string"||typeof s.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:s}}let a=u.code;return typeof a=="string"&&Ze.has(a)?{ok:!1,kind:a}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var te="kane.source.web/1";function Ae(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:te,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var Qe=new Set(["markdown"]);function Le(){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!==te)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!Qe.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 et}from"crypto";function ve(t){return Q(t)!==null}function Q(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 ne(t){let n=Q(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(/-+$/,""),l=et("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${l}`}function tt(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return d.schema!=="kane.source.web/1"?null:typeof d.url=="string"&&d.url.length>0?d.url:null}catch{return null}}function re(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 nt(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 rt(t,n,e,r,l){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};let d=ne(t),f=n??d;if(f===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};try{k(f)}catch(s){return(e.err??e.out)(`error: ${t}: ${s instanceof Error?s.message:String(s)}`),{code:1}}let i=tt(r,f);if(i!==null&&i!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${i} \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 '${f}' was ingested from ${i} \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 c=l?.web?.scrape??Ie,u=l?.authEnv??(async()=>(await import("./spawner-LKYUMXSO.js")).resolveAgentAuthEnv()),a=await c(o,{authEnv:u});if(!a.ok)return(e.err??e.out)(`error: ${t}: ${re(a.kind)}`),{code:1};try{let{bytes:s}=Ae(o,a.page.projection,a.page.markdown),y=await P({contextDir:r,bytes:s,media:ae,sourceId:f,label:o,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{web:Le()}}),L=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,y,L));for(let m of y.warnings??[])e.out(`warning: ${m}`);return e.isTTY&&a.page.title&&e.out(` title: ${a.page.title}`),{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid}}}catch(s){return(e.err??e.out)(`error: ${t}: ${nt(s instanceof Error?s.message:String(s))}`),{code:1}}}var Se={name:"web",hint:"any public web page URL (https://\u2026)",match:ve,ingest:rt,sourceIdFor:ne};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 ot=[ge,we,Se];function _n(t){return/^https?:\/\/.+/i.test(t)}function En(t){return ot.find(n=>n.match(t))??null}export{U as a,ot as b,_n as c,En as d};
10
+ `,inventory:l,blobs:o,delivered:d,converter:{name:"confluence-convert",version:"1",policy:"v1"}}}}var ze=/^[A-Za-z0-9~][A-Za-z0-9._~-]*$/;function Z(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 l=e[r+2],o=e[r+4];return l===void 0||o===void 0||!ze.test(l)||!/^\d+$/.test(o)?null:{site:n.hostname,spaceKey:l,pageId:o}}async function Xe(t,n,e,r,l){let o=Z(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 d=l?.lis??{jiraInfo:V,jiraIssue:W,jiraAttachment:Y,jiraComments:G},f=l?.confluence??{confluenceDocument:he,confluenceAttachment:ye};try{let c={auth:await(l?.authEnv??(await import("./auth-3DLNMZC2.js")).resolveLisAuthEnv)(),env:process.env},u=await d.jiraInfo(c);if(!u.installed)return(e.err??e.out)(`error: ${t}: no Atlassian connection for this account \u2014 create one at ${v} and retry`),{code:1};if(u.capabilities.document===!1)return(e.err??e.out)(`error: ${t}: the connection has no Confluence access \u2014 reconnect with Confluence at ${v} and retry`),{code:1};let a=await f.confluenceDocument(o.pageId,c),s=o.site;if(a.url)try{s=new URL(a.url).hostname}catch{}let{bytes:y,warnings:L}=be(a,s),m=n??`page-${o.pageId}`;k(m);let g=X(r,m);if(g!==null&&g!==s)return(e.err??e.out)(`error: ${t}: source '${m}' was ingested from ${g}, but this read serves ${s} \u2014 retire it first (kane-cli context retire ${m}) or ingest under a different id with --as`),{code:1};let S=Object.fromEntries((a.attachments??[]).filter(p=>typeof p.download=="string"&&p.download.length>0).map(p=>[String(p.id),p.download])),h=await P({contextDir:r,bytes:y,media:ie,sourceId:m,label:t,confirmSameSource:e.isTTY?p=>e.confirm(`identical content already ingested as ${p} \u2014 treat as the same source?`):void 0,converters:{confluence:Ee({downloads:S,fetchAttachment:p=>f.confluenceAttachment(p.download,c)})}});e.out(U(e.isTTY,h,`${o.spaceKey}/${o.pageId}`));for(let p of L)e.out(`warning: ${p}`);for(let p of h.warnings??[])e.out(`warning: ${p}`);if(h.composite){let p=h.composite.delivered+h.composite.omitted;e.out(`${h.source_id}: confluence, ${p} attachments, ${h.composite.delivered} images delivered (${h.composite.omitted} omitted)`)}return{code:0,result:{status:h.status,source_id:h.source_id,source_cid:h.cid}}}catch(i){return i instanceof b?((e.err??e.out)(`error: ${t}: ${i.message}`),{code:1}):((e.err??e.out)(`error: ${t}: ${qe(i instanceof Error?i.message:String(i))}`),{code:1})}}function qe(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 we={name:"confluence",hint:"Confluence page URLs (https://<site>/wiki/spaces/<KEY>/pages/<id>/\u2026)",match:t=>Z(t)!==null,ingest:Xe,sourceIdFor:t=>{let n=Z(t);return n?`page-${n.pageId}`:null}};var Ze=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 Ie(t,n){let e=n.env??process.env,r=n.fetchImpl??fetch,l=ce(e),o={"Content-Type":"application/json"},d=await n.authEnv(),f=d.TESTMUAI_BASIC_AUTH??e.TESTMUAI_BASIC_AUTH,i=d.TESTMUAI_API_KEY??e.TESTMUAI_API_KEY;f?o.Authorization=`Basic ${f}`:i&&(o.Authorization=`Bearer ${i}`);let c;try{c=await r(`${l}/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 u;try{u=await c.json()}catch{return{ok:!1,kind:c.status===404?"route_missing":"malformed_response"}}if(c.ok){let s=u.page;return s===void 0||typeof s.markdown!="string"||s.markdown===""||typeof s.final_url!="string"||s.final_url===""||typeof s.projection?.kind!="string"||typeof s.projection?.version!="string"?{ok:!1,kind:"malformed_response"}:{ok:!0,page:s}}let a=u.code;return typeof a=="string"&&Ze.has(a)?{ok:!1,kind:a}:c.status===404?{ok:!1,kind:"route_missing"}:c.status===403?{ok:!1,kind:"auth_rejected"}:{ok:!1,kind:"malformed_response"}}var te="kane.source.web/1";function Ae(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:te,url:t,projection:{kind:n.kind,version:n.version},content:{markdown:e}};return{bytes:Buffer.from(JSON.stringify(r),"utf8"),envelope:r}}var Qe=new Set(["markdown"]);function Le(){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!==te)throw new Error(`unknown web envelope schema '${String(n.schema)}' \u2014 re-ingest the page with this CLI version`);if(!Qe.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 et}from"crypto";function ve(t){return Q(t)!==null}function Q(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 ne(t){let n=Q(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(/-+$/,""),l=et("sha256").update(n,"utf8").digest("hex").slice(0,8);return`${r||"page"}-${l}`}function tt(t,n){let e=x(t),r=e.heads.get(n);if(r==null)return null;let l=e.getNode(r)?.content?.blob;if(typeof l!="string")return null;let o=M(t,l);if(o===null)return null;try{let d=JSON.parse(o.toString("utf8"));return d.schema!=="kane.source.web/1"?null:typeof d.url=="string"&&d.url.length>0?d.url:null}catch{return null}}function re(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 nt(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 rt(t,n,e,r,l){let o=Q(t);if(o===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};let d=ne(t),f=n??d;if(f===null)return(e.err??e.out)(`error: ${t}: ${re("invalid_url")}`),{code:1};try{k(f)}catch(s){return(e.err??e.out)(`error: ${t}: ${s instanceof Error?s.message:String(s)}`),{code:1}}let i=tt(r,f);if(i!==null&&i!==o){if(!e.isTTY)return(e.err??e.out)(`error: ${t}: source '${f}' was ingested from ${i} \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 '${f}' was ingested from ${i} \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 c=l?.web?.scrape??Ie,u=l?.authEnv??(async()=>(await import("./spawner-ANLF7OX3.js")).resolveAgentAuthEnv()),a=await c(o,{authEnv:u});if(!a.ok)return(e.err??e.out)(`error: ${t}: ${re(a.kind)}`),{code:1};try{let{bytes:s}=Ae(o,a.page.projection,a.page.markdown),y=await P({contextDir:r,bytes:s,media:ae,sourceId:f,label:o,confirmSameSource:e.isTTY?m=>e.confirm(`identical content already ingested as ${m} \u2014 treat as the same source?`):void 0,converters:{web:Le()}}),L=new URL(o).hostname+new URL(o).pathname;e.out(U(e.isTTY,y,L));for(let m of y.warnings??[])e.out(`warning: ${m}`);return e.isTTY&&a.page.title&&e.out(` title: ${a.page.title}`),{code:0,result:{status:y.status,source_id:y.source_id,source_cid:y.cid}}}catch(s){return(e.err??e.out)(`error: ${t}: ${nt(s instanceof Error?s.message:String(s))}`),{code:1}}}var Se={name:"web",hint:"any public web page URL (https://\u2026)",match:ve,ingest:rt,sourceIdFor:ne};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 ot=[ge,we,Se];function _n(t){return/^https?:\/\/.+/i.test(t)}function En(t){return ot.find(n=>n.match(t))??null}export{U as a,ot as b,_n as c,En as d};
@@ -1,3 +1,3 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as X}from"./chunk-BB2W35TW.js";import{a as $}from"./chunk-YKTYVJBN.js";import{A as T,l as z,m as Y,n as H}from"./chunk-TH47OOBV.js";import{b as q,g as N}from"./chunk-DUAXZYAD.js";import{a as W,d as S,f as L}from"./chunk-DBIBROYW.js";import{c as C}from"./chunk-UD7KKHPW.js";import{a as K,c as J}from"./chunk-PH22FRN5.js";var ce=3,de=1e4,Q=()=>new Promise(r=>setTimeout(r,25+Math.floor(Math.random()*50))),Z=r=>r==="design"||r==="maintain"?"session":r==="revert"||r==="shape-op"?"exclusive":"commit";function le(r,e,o){for(let s of r){for(let t of s.supersessions)if(t.kind==="node"&&(o.has(t.old)||t.new!==null&&o.has(t.new)))return!0;for(let t of s.nodes)if(t.label==="usecase"&&e.newBuCandidates.length>0||o.has(t.cid))return!0;if(s.design_generation&&e.generationTicket&&s.design_generation.uc_root===e.generationTicket.uc_root)return!0;for(let t of e.sourcePins)if(Object.prototype.hasOwnProperty.call(s.source_head_moves,t.source_id))return!0}return!1}async function De(r,e,o){let{contextDir:s,locks:t,probe:a}=r,m=r.sid??r.rootSid,f=e.newBuCandidates.map(b=>({tempRef:b.tempRef,probeText:b.probeText})),k=0,g=!0,p={hits:[],degraded:!1,probeBasis:null};for(;;){g&&(f.length>0&&(p=await a.batchSimilar(T(s),f)),g=!1);let b=T(s),_={seq:b.lastSeq,hash:b.latestHash},P=new Map,w=[],v=[],R=new Set;for(let d of e.ucTargets){let c=H(b,d.ref);if(c===null)return{ok:!1,kind:"validation",errors:[{code:"UNKNOWN_REF",detail:`${d.ref}: names no living node (unknown or tombstoned chain)`}]};d.expectedTip!==void 0&&d.expectedTip!==c.cid&&P.set(d.expectedTip,c.cid),R.add(c.cid),v.push(L(b,d.ref).key)}(e.verb==="revert"||e.verb==="shape-op")&&(v.length=0,v.push({kind:"context",mode:"exclusive"}));let y;try{y=t.acquire(S(v),{hold:Z(e.verb),verb:e.verb})}catch(d){if(d instanceof W&&(d.code==="UC_HELD"||d.code==="CONTEXT_HELD"))return{ok:!1,kind:"contended",err:d};throw d}let V=!1,M=!1;try{let d=await t.withKeySerialized(v,async()=>{let c=T(s),O=_.hash===c.latestHash?[]:N(s,_.seq,_.hash).records;for(let n of e.ucTargets){let i=H(c,n.ref);if(i===null){w.push({kind:"supersession",ref:n.ref,detail:`${n.ref} was retired while this commit staged \u2014 re-ground or abandon`});continue}for(let l of R)c.superseded.has(l)&&c.tipOf(l)===i.cid&&P.set(l,i.cid)}for(let n of e.sourcePins){let i=c.heads.get(n.source_id);i!=null&&i!==n.source_cid&&w.push({kind:"pin",ref:n.source_id,detail:`source '${n.source_id}' moved (pinned ${n.source_cid.slice(0,19)}, head ${i.slice(0,19)}) \u2014 re-ground or abandon`})}if(w.length>0)return{ok:!1,kind:"drifted",asks:w};if(e.generationTicket){let n=X(c,e.generationTicket);if(n!==null)return{ok:!1,kind:"validation",errors:[n]}}if(f.length>0&&O.length>0){let n=new Set(p.hits.map(u=>u.candidateCid)),i=a.recheckLocal(c,f,p.probeBasis,O);if(i.hits.some(u=>!n.has(u.candidateCid))||i.uncachedNewNodes.length>0)return M=!0,"restart"}if(e.verb!=="revert"&&e.verb!=="shape-op"){let n=S(e.ucTargets.map(u=>L(c,u.ref).key)),i=S(v);if(!(n.length===i.length&&n.every((u,h)=>JSON.stringify(u)===JSON.stringify(i[h]))))return"restart"}if(e.eventIds&&e.eventIds.length>0&&e.eventIds.every(n=>c.appliedEvents.has(n)))return{ok:!0,skipped:"already-applied"};let ae=Date.now()+de,j=c.latestHash,E=c;for(;;){let n={graph:E,expectPrev:j,redirects:P,probeHits:p.hits,degradedProbe:p.degraded,sid:m,eventIds:(l,u)=>{if(e.eventIds&&e.eventIds.length>0)return e.eventIds.slice(0,u);let h=Y(E,r.rootSid,l,u),U=r.reservedEventIds??[];if(U.length===0)return h;let D=`${r.rootSid}:${l}:`,A=0;for(let F of U){if(!F.startsWith(D))continue;let x=F.slice(D.length);/^\d+$/.test(x)&&(A=Math.max(A,Number.parseInt(x,10)))}if(A===0)return h;let G=Number.parseInt(h[0].slice(D.length),10);return!Number.isInteger(G)||G>A?h:Array.from({length:u},(F,x)=>z(r.rootSid,l,A+1+x))},assertLocks:()=>y.assertHeld()};if(r.revalidate){let l=r.revalidate(n);if(l.length>0)return{ok:!1,kind:"validation",errors:l}}y.assertHeld();let i;try{i=o(n)}catch(l){if(l instanceof q){let u=T(s),h=N(s,E.lastSeq,E.latestHash).records;if(!le(h,e,R)&&Date.now()<ae){await Q(),E=u,j=u.latestHash;continue}return"restart"}throw l}return"errors"in i?{ok:!1,kind:"validation",errors:i.errors}:(Z(e.verb)==="session"&&y.touch(),{ok:!0,result:i.result,record:i.record})}});if(d==="restart")V=!0;else return d}finally{y.release()}if(V){if(k+=1,k>=ce)return{ok:!1,kind:"unsettled",attempts:k};M&&(g=!0),await Q();continue}}}import{readFileSync as ue,writeFileSync as fe,renameSync as me,mkdirSync as pe}from"fs";import{dirname as he,join as ge}from"path";var B=1,be=720*60*1e3;function I(r){return ge(J,"embeddings",`alias-${r}.json`)}function ee(r,e=Date.now()){return r!==null&&e-r.fetchedAt<be}function re(r){try{let e=JSON.parse(ue(r,"utf-8"));return e.wrapperVersion!==B||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:B,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function te(r,e,o=I(r)){let t=re(o)?.purposes?.[e];return!t||typeof t.alias!="string"||typeof t.dims!="number"||typeof t.fetchedAt!="number"?null:{alias:t.alias,dims:t.dims,fetchedAt:t.fetchedAt}}function se(r,e,o,s=I(r)){try{pe(he(s),{recursive:!0});let a=re(s)?.purposes??{};a[e]={alias:o.alias,dims:o.dims,fetchedAt:Date.now()};let m={wrapperVersion:B,writtenByVersion:K,purposes:a},f=`${s}.tmp`;fe(f,JSON.stringify(m,null,2)+`
2
+ import{d as X}from"./chunk-BB2W35TW.js";import{a as $}from"./chunk-YKTYVJBN.js";import{A as T,l as z,m as Y,n as H}from"./chunk-TH47OOBV.js";import{b as q,g as N}from"./chunk-DUAXZYAD.js";import{a as W,d as S,f as L}from"./chunk-DBIBROYW.js";import{c as C}from"./chunk-UD7KKHPW.js";import{a as K,b as J}from"./chunk-CCUGKBIH.js";var ce=3,de=1e4,Q=()=>new Promise(r=>setTimeout(r,25+Math.floor(Math.random()*50))),Z=r=>r==="design"||r==="maintain"?"session":r==="revert"||r==="shape-op"?"exclusive":"commit";function le(r,e,o){for(let s of r){for(let t of s.supersessions)if(t.kind==="node"&&(o.has(t.old)||t.new!==null&&o.has(t.new)))return!0;for(let t of s.nodes)if(t.label==="usecase"&&e.newBuCandidates.length>0||o.has(t.cid))return!0;if(s.design_generation&&e.generationTicket&&s.design_generation.uc_root===e.generationTicket.uc_root)return!0;for(let t of e.sourcePins)if(Object.prototype.hasOwnProperty.call(s.source_head_moves,t.source_id))return!0}return!1}async function De(r,e,o){let{contextDir:s,locks:t,probe:a}=r,m=r.sid??r.rootSid,f=e.newBuCandidates.map(b=>({tempRef:b.tempRef,probeText:b.probeText})),k=0,g=!0,p={hits:[],degraded:!1,probeBasis:null};for(;;){g&&(f.length>0&&(p=await a.batchSimilar(T(s),f)),g=!1);let b=T(s),_={seq:b.lastSeq,hash:b.latestHash},P=new Map,w=[],v=[],R=new Set;for(let d of e.ucTargets){let c=H(b,d.ref);if(c===null)return{ok:!1,kind:"validation",errors:[{code:"UNKNOWN_REF",detail:`${d.ref}: names no living node (unknown or tombstoned chain)`}]};d.expectedTip!==void 0&&d.expectedTip!==c.cid&&P.set(d.expectedTip,c.cid),R.add(c.cid),v.push(L(b,d.ref).key)}(e.verb==="revert"||e.verb==="shape-op")&&(v.length=0,v.push({kind:"context",mode:"exclusive"}));let y;try{y=t.acquire(S(v),{hold:Z(e.verb),verb:e.verb})}catch(d){if(d instanceof W&&(d.code==="UC_HELD"||d.code==="CONTEXT_HELD"))return{ok:!1,kind:"contended",err:d};throw d}let V=!1,M=!1;try{let d=await t.withKeySerialized(v,async()=>{let c=T(s),O=_.hash===c.latestHash?[]:N(s,_.seq,_.hash).records;for(let n of e.ucTargets){let i=H(c,n.ref);if(i===null){w.push({kind:"supersession",ref:n.ref,detail:`${n.ref} was retired while this commit staged \u2014 re-ground or abandon`});continue}for(let l of R)c.superseded.has(l)&&c.tipOf(l)===i.cid&&P.set(l,i.cid)}for(let n of e.sourcePins){let i=c.heads.get(n.source_id);i!=null&&i!==n.source_cid&&w.push({kind:"pin",ref:n.source_id,detail:`source '${n.source_id}' moved (pinned ${n.source_cid.slice(0,19)}, head ${i.slice(0,19)}) \u2014 re-ground or abandon`})}if(w.length>0)return{ok:!1,kind:"drifted",asks:w};if(e.generationTicket){let n=X(c,e.generationTicket);if(n!==null)return{ok:!1,kind:"validation",errors:[n]}}if(f.length>0&&O.length>0){let n=new Set(p.hits.map(u=>u.candidateCid)),i=a.recheckLocal(c,f,p.probeBasis,O);if(i.hits.some(u=>!n.has(u.candidateCid))||i.uncachedNewNodes.length>0)return M=!0,"restart"}if(e.verb!=="revert"&&e.verb!=="shape-op"){let n=S(e.ucTargets.map(u=>L(c,u.ref).key)),i=S(v);if(!(n.length===i.length&&n.every((u,h)=>JSON.stringify(u)===JSON.stringify(i[h]))))return"restart"}if(e.eventIds&&e.eventIds.length>0&&e.eventIds.every(n=>c.appliedEvents.has(n)))return{ok:!0,skipped:"already-applied"};let ae=Date.now()+de,j=c.latestHash,E=c;for(;;){let n={graph:E,expectPrev:j,redirects:P,probeHits:p.hits,degradedProbe:p.degraded,sid:m,eventIds:(l,u)=>{if(e.eventIds&&e.eventIds.length>0)return e.eventIds.slice(0,u);let h=Y(E,r.rootSid,l,u),U=r.reservedEventIds??[];if(U.length===0)return h;let D=`${r.rootSid}:${l}:`,A=0;for(let F of U){if(!F.startsWith(D))continue;let x=F.slice(D.length);/^\d+$/.test(x)&&(A=Math.max(A,Number.parseInt(x,10)))}if(A===0)return h;let G=Number.parseInt(h[0].slice(D.length),10);return!Number.isInteger(G)||G>A?h:Array.from({length:u},(F,x)=>z(r.rootSid,l,A+1+x))},assertLocks:()=>y.assertHeld()};if(r.revalidate){let l=r.revalidate(n);if(l.length>0)return{ok:!1,kind:"validation",errors:l}}y.assertHeld();let i;try{i=o(n)}catch(l){if(l instanceof q){let u=T(s),h=N(s,E.lastSeq,E.latestHash).records;if(!le(h,e,R)&&Date.now()<ae){await Q(),E=u,j=u.latestHash;continue}return"restart"}throw l}return"errors"in i?{ok:!1,kind:"validation",errors:i.errors}:(Z(e.verb)==="session"&&y.touch(),{ok:!0,result:i.result,record:i.record})}});if(d==="restart")V=!0;else return d}finally{y.release()}if(V){if(k+=1,k>=ce)return{ok:!1,kind:"unsettled",attempts:k};M&&(g=!0),await Q();continue}}}import{readFileSync as ue,writeFileSync as fe,renameSync as me,mkdirSync as pe}from"fs";import{dirname as he,join as ge}from"path";var B=1,be=720*60*1e3;function I(r){return ge(J,"embeddings",`alias-${r}.json`)}function ee(r,e=Date.now()){return r!==null&&e-r.fetchedAt<be}function re(r){try{let e=JSON.parse(ue(r,"utf-8"));return e.wrapperVersion!==B||typeof e.purposes!="object"||e.purposes===null?null:{wrapperVersion:B,writtenByVersion:String(e.writtenByVersion??""),purposes:e.purposes}}catch{return null}}function te(r,e,o=I(r)){let t=re(o)?.purposes?.[e];return!t||typeof t.alias!="string"||typeof t.dims!="number"||typeof t.fetchedAt!="number"?null:{alias:t.alias,dims:t.dims,fetchedAt:t.fetchedAt}}function se(r,e,o,s=I(r)){try{pe(he(s),{recursive:!0});let a=re(s)?.purposes??{};a[e]={alias:o.alias,dims:o.dims,fetchedAt:Date.now()};let m={wrapperVersion:B,writtenByVersion:K,purposes:a},f=`${s}.tmp`;fe(f,JSON.stringify(m,null,2)+`
3
3
  `),me(f,s)}catch(t){C(`[embed] Failed to save alias cache: ${t instanceof Error?t.message:String(t)}`,"EMBED_CACHE_WRITE_FAILED")}}function ve(r){return r.TESTMUAI_ENV==="stage"?"stage":"prod"}function oe(r){let e=r.env??process.env,o=r.auth?.TESTMUAI_BASIC_AUTH||e.TESTMUAI_BASIC_AUTH;if(o)return{authorization:`Basic ${o}`};let s=r.auth?.TESTMUAI_API_KEY||e.TESTMUAI_API_KEY;return s?{authorization:`Bearer ${s}`}:{}}async function Oe(r,e={}){let o=e.env??process.env,s=ve(o),t=e.aliasCacheFile??I(s),a=e.now??Date.now,m=te(s,r,t);if(ee(m,a()))return{alias:m.alias,dims:m.dims};let k=`${$(o)}/assurance/embed/alias?purpose=${encodeURIComponent(r)}`,g=await(e.fetchImpl??fetch)(k,{method:"GET",headers:oe(e)});if(!g.ok)throw new Error(`embed alias resolve failed: ${g.status}`);let p=await g.json();return se(s,r,{alias:p.alias,dims:p.dims},t),{alias:p.alias,dims:p.dims}}async function je(r,e,o={}){let s=o.env??process.env,t=$(s),a=await(o.fetchImpl??fetch)(`${t}/assurance/embed`,{method:"POST",headers:{...oe(o),"content-type":"application/json"},body:JSON.stringify({purpose:r,input:e})});if(!a.ok)throw new Error(`embed failed: ${a.status}`);return await a.json()}import{readFileSync as ke,writeFileSync as ye,renameSync as Ee,mkdirSync as Ae}from"fs";import{dirname as Te,join as ne}from"path";function we(r){return ne(r,"embeddings")}function xe(r){let e=r.indexOf(":");return e>=0?r.slice(e+1):r}function ie(r,e,o){let s=xe(o);return ne(we(r),e,s.slice(0,2),`${s.slice(2)}.f32`)}function We(r,e,o){try{let s=ke(ie(r,e,o)),t=new Float32Array(Math.floor(s.length/4));for(let a=0;a<t.length;a++)t[a]=s.readFloatLE(a*4);return t}catch{return null}}function qe(r,e,o,s){try{let t=ie(r,e,o);Ae(Te(t),{recursive:!0});let a=Buffer.alloc(s.length*4);for(let f=0;f<s.length;f++)a.writeFloatLE(s[f],f*4);let m=`${t}.tmp`;ye(m,a),Ee(m,t)}catch(t){C(`[embed] Failed to cache vector: ${t instanceof Error?t.message:String(t)}`,"EMBED_CACHE_WRITE_FAILED")}}export{De as a,Oe as b,je as c,We as d,qe as e};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{x as s}from"./chunk-PH22FRN5.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost,mobileAppBaseUrl:process.env.KANE_STAGE_MOBILE_APP_URL??e.mobileAppBaseUrl}}export{n as a};
2
+ import{w as s}from"./chunk-CCUGKBIH.js";function n(r="prod"){let e=s[r];return r!=="stage"?e:{authBaseUrl:process.env.KANE_STAGE_AUTH_URL??e.authBaseUrl,consentUrl:process.env.KANE_STAGE_CONSENT_URL??e.consentUrl,controllerBaseUrl:process.env.TESTMUAI_BASE_URL??e.controllerBaseUrl,tmsBaseUrl:process.env.KANE_STAGE_TMS_URL??e.tmsBaseUrl,testGeneratorBaseUrl:process.env.KANE_STAGE_TCG_URL??e.testGeneratorBaseUrl,secretsBaseUrl:process.env.KANE_STAGE_SECRETS_URL??e.secretsBaseUrl,testManagerUiUrl:process.env.KANE_STAGE_TEST_MANAGER_UI_URL??e.testManagerUiUrl,shareApiBaseUrl:process.env.KANE_STAGE_SHARE_API_URL??e.shareApiBaseUrl,v16ServerHost:process.env.KANE_STAGE_V16_SERVER_HOST??e.v16ServerHost,evidenceViewerUrl:process.env.KANE_STAGE_EVIDENCE_VIEWER_URL??e.evidenceViewerUrl,mediaArtefactsHost:process.env.KANE_STAGE_MEDIA_ARTEFACTS_HOST??e.mediaArtefactsHost,mobileAppBaseUrl:process.env.KANE_STAGE_MOBILE_APP_URL??e.mobileAppBaseUrl}}export{n as a};
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{e as v,f as l}from"./chunk-BXRZGISN.js";import{a as f,c as m,e as p}from"./chunk-EYOCNMUM.js";var R=["desktop","emulator","simulator"];function k(e,n){return e.kind==="app_id"?!0:n==="emulator"?e.kind==="apk":e.kind==="zip"}function g(e,n,t){let s=l(e);return s?k(s,n)?null:n==="emulator"?`${t} cannot run on an emulator (needs an .apk, or an APP\u2026 id).`:`${t} cannot run on a simulator (needs a .zip of the .app bundle, or an APP\u2026 id).`:`${e}: ${v}`}function b(e){return R.includes(e)?e:null}function T(e){return`--target must be one of desktop, emulator, simulator (got "${e}")`}function h(e){let n=[];for(let[t,s]of[["--device",e.device],["--app",e.app]])s!==void 0&&n.push(`ignored ${t} ${s}: session target is desktop \u2014 set --target emulator|simulator to run on a device`);return n}function I(e){let{flags:n,saved:t}=e,s=[],r;if(n.target!==void 0){let i=b(n.target);if(!i)return{kind:"invalid",message:T(n.target)};r=i}else{let i=f(t?.tui_target,t?.default_target?.kind);if(i.kind==="choose-mobile")return{kind:"choose-mobile-kind"};r=i.kind==="unset"?"desktop":i.kind}if(r==="desktop")return s.push(...h(n)),{kind:"web",warnings:s};if(!e.host.supported)return{kind:"invalid",message:e.host.reason??"this machine cannot run mobile targets."};let a=[],o;n.device!==void 0?o={value:n.device,source:"flag"}:t?.default_target&&t.default_target.kind===r?o={value:t.default_target.id,source:"saved"}:a.push("device");let d;if(n.app!==void 0){let i=g(n.app,r,`--app ${n.app}`);if(i)return{kind:"invalid",message:i};d={value:n.app,source:"flag"}}else{let i=t?.default_app,c=i?l(i):null;c&&k(c,r)&&t?.default_target?.kind===r?d={value:i,source:"saved"}:a.push("app")}return{kind:"mobile",target:r,...o?{device:o}:{},...d?{app:d}:{},missing:a,warnings:s}}function P(e){let{flags:n,file:t}=e,s=[],r=t.target==="emulator"||t.target==="simulator"?t.target:void 0,a;if(n.target!==void 0){let i=b(n.target);if(!i)return{kind:"invalid",message:T(n.target)};a=i,r&&r!==a&&s.push(`--target ${a} overrides the file's \`target: ${r}\` \u2014 steps recorded on ${r==="emulator"?"an emulator":"a simulator"} may not replay here`)}else a=r??"desktop";if(a==="desktop")return s.push(...h(n)),{kind:"web",warnings:s};if(n.app!==void 0){let i=g(n.app,a,`--app ${n.app}`);if(i)return{kind:"invalid",message:i}}else if(t.app){let i=g(t.app,a,`the file's app: ${t.app}`);if(i)return{kind:"invalid",message:i}}let o=n.app??(t.app||void 0),d=n.device?.trim();return{kind:"mobile",target:a,platform:m(a)??"",...d?{device:d}:{},...o?{app:o}:{},...t.no_reset!==void 0?{noReset:t.no_reset}:{},warnings:s}}function _(e){return e.target==="desktop"?"Running on: Desktop \xB7 Chrome":`Running on: ${p(e.target)} \xB7 ${e.deviceLabel} \xB7 ${e.appLabel}`}var u={emulator:"</path/to/app.apk | APPid>",simulator:"</path/to/app.zip | APPid>"};function x(e,n){let t=p(e).toLowerCase();return n==="device"?[`session target is "${t}" but no device is set.`,` See devices: kane-cli devices list --target ${e}`,' Set one: kane-cli config set-device "<name>"',' Or per-run: --device "<name>"'].join(`
2
+ import{e as v,f as l}from"./chunk-2K2BX23I.js";import{a as f,c as m,e as p}from"./chunk-EYOCNMUM.js";var R=["desktop","emulator","simulator"];function k(e,n){return e.kind==="app_id"?!0:n==="emulator"?e.kind==="apk":e.kind==="zip"}function g(e,n,t){let s=l(e);return s?k(s,n)?null:n==="emulator"?`${t} cannot run on an emulator (needs an .apk, or an APP\u2026 id).`:`${t} cannot run on a simulator (needs a .zip of the .app bundle, or an APP\u2026 id).`:`${e}: ${v}`}function b(e){return R.includes(e)?e:null}function T(e){return`--target must be one of desktop, emulator, simulator (got "${e}")`}function h(e){let n=[];for(let[t,s]of[["--device",e.device],["--app",e.app]])s!==void 0&&n.push(`ignored ${t} ${s}: session target is desktop \u2014 set --target emulator|simulator to run on a device`);return n}function I(e){let{flags:n,saved:t}=e,s=[],r;if(n.target!==void 0){let i=b(n.target);if(!i)return{kind:"invalid",message:T(n.target)};r=i}else{let i=f(t?.tui_target,t?.default_target?.kind);if(i.kind==="choose-mobile")return{kind:"choose-mobile-kind"};r=i.kind==="unset"?"desktop":i.kind}if(r==="desktop")return s.push(...h(n)),{kind:"web",warnings:s};if(!e.host.supported)return{kind:"invalid",message:e.host.reason??"this machine cannot run mobile targets."};let a=[],o;n.device!==void 0?o={value:n.device,source:"flag"}:t?.default_target&&t.default_target.kind===r?o={value:t.default_target.id,source:"saved"}:a.push("device");let d;if(n.app!==void 0){let i=g(n.app,r,`--app ${n.app}`);if(i)return{kind:"invalid",message:i};d={value:n.app,source:"flag"}}else{let i=t?.default_app,c=i?l(i):null;c&&k(c,r)&&t?.default_target?.kind===r?d={value:i,source:"saved"}:a.push("app")}return{kind:"mobile",target:r,...o?{device:o}:{},...d?{app:d}:{},missing:a,warnings:s}}function P(e){let{flags:n,file:t}=e,s=[],r=t.target==="emulator"||t.target==="simulator"?t.target:void 0,a;if(n.target!==void 0){let i=b(n.target);if(!i)return{kind:"invalid",message:T(n.target)};a=i,r&&r!==a&&s.push(`--target ${a} overrides the file's \`target: ${r}\` \u2014 steps recorded on ${r==="emulator"?"an emulator":"a simulator"} may not replay here`)}else a=r??"desktop";if(a==="desktop")return s.push(...h(n)),{kind:"web",warnings:s};if(n.app!==void 0){let i=g(n.app,a,`--app ${n.app}`);if(i)return{kind:"invalid",message:i}}else if(t.app){let i=g(t.app,a,`the file's app: ${t.app}`);if(i)return{kind:"invalid",message:i}}let o=n.app??(t.app||void 0),d=n.device?.trim();return{kind:"mobile",target:a,platform:m(a)??"",...d?{device:d}:{},...o?{app:o}:{},...t.no_reset!==void 0?{noReset:t.no_reset}:{},warnings:s}}function _(e){return e.target==="desktop"?"Running on: Desktop \xB7 Chrome":`Running on: ${p(e.target)} \xB7 ${e.deviceLabel} \xB7 ${e.appLabel}`}var u={emulator:"</path/to/app.apk | APPid>",simulator:"</path/to/app.zip | APPid>"};function x(e,n){let t=p(e).toLowerCase();return n==="device"?[`session target is "${t}" but no device is set.`,` See devices: kane-cli devices list --target ${e}`,' Set one: kane-cli config set-device "<name>"',' Or per-run: --device "<name>"'].join(`
3
3
  `):[`session target is "${t}" but no app is set.`,` Set one: kane-cli config set-app ${u[e]}`,` Or per-run: --app ${u[e]}`].join(`
4
4
  `)}function A(e){return[`saved device "${e}" was not found on this machine.`," See devices: kane-cli devices list",' Set one: kane-cli config set-device "<name>"'].join(`
5
5
  `)}function w(e,n){return[`saved app ${e} no longer exists on disk.`," The build may have been moved or cleaned. Set a new one:",` kane-cli config set-app ${u[n]}`].join(`
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{j as Re,k as oe,l as se,m as _e,n as $e,o as ae}from"./chunk-N7N222VC.js";import{a as te,c as re,d as ye,f as ie}from"./chunk-QWDFFEEJ.js";import{a as P,b as we,d as ke}from"./chunk-OS4VSIHT.js";import{d as ve}from"./chunk-6J5T5FEY.js";import{a as S}from"./chunk-CLGC7VEO.js";import{a as X,b as N,c as ee,d as W,e as he,g as O,h as ne}from"./chunk-W5TTF7GB.js";import{a as ge}from"./chunk-JFAFKHDX.js";import{b as Z,c as J,d as Q}from"./chunk-BSCMUMSV.js";import{f as me,h as pe}from"./chunk-X2FM67OM.js";import{A as I}from"./chunk-TH47OOBV.js";import{f as T}from"./chunk-DUAXZYAD.js";import{existsSync as Oe,statSync as Ue}from"fs";import{basename as G,resolve as q}from"path";function Ee(e){if(!e||e.stale_refs.length===0)return"\u2014";let n=e.direct_refs??[];return`${e.stale_refs.length} stale${n.length>0?` \xB7 ${n.length} direct`:""}`}function ce(e,n){let t=[...e.rows.filter(a=>a.kind!=="REMOVE").map(a=>[a.kind,S(a.ref),a.reason,Ee(a.impact)]),...e.archive.map(a=>["ARCHIVE",S(a.ref),a.why,Ee(a.impact)])],r=Math.max(40,n??100),i=[`reconcile ${e.source_id} \u2014 head ${e.head.status} \xB7 ${t.length} decision${t.length===1?"":"s"}`];return t.length>0&&i.push(...ve(["kind","ref","why","impact"],t,r,2)),e.changed&&i.push(e.held?`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i.push("each row becomes a card below \u2014 verdicts commit as they land"),e.planPath&&i.push(`plan: ${e.planPath}`),i}var xe=new Set(["interactive","agent","ci","override"]);function Ae(e,n){if(e.mode!==void 0&&!xe.has(e.mode))return{error:`--mode must be interactive | agent | ci | override, got '${e.mode}'`,code:"MODE_USAGE"};let t=e.mode,r="reconcile without a TTY needs an explicit mode \u2014 pass --mode agent|ci|override, or --plan for a preview";return t==="interactive"&&!n?{error:r}:t||(n?"interactive":e.plan?"override":{error:r})}async function Pe(e){let{makeHeadlessIO:n,agentRefusal:t}=await import("./headless-io-66RG5NN5.js");return t(n("ndjson","reconcile"),e,"MODE_USAGE")}function Me(e,n,t,r){if(J(t)){let v=Q(t),s=v?.sourceIdFor(t)??null;if(v===null||s===null)return{error:`--from '${t}' is not a supported remote URL \u2014 supported: ${Z.map(u=>u.hint).join("; ")}`};if(r!==void 0&&r!==s)return{error:`--source-id '${r}' does not match this URL's own identity '${s}' \u2014 re-run without --source-id. A source adopted with --as updates by re-running context ingest with the same --as; reconcile follows only the URL's own id`};let c=I(e);if(!c.heads.has(s))return{error:`unknown source '${s}' \u2014 see \`kane-cli context list --type source\`. If this URL was ingested under a custom id, update it by re-running context ingest with the same --as`};if(c.heads.get(s)==null)return{error:`source '${s}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let _=z(e,s,{remoteUrl:t});return _!==null?{error:_}:{sourceId:s,remoteUrl:t}}if(r===void 0)return{error:"reconcile needs --from <file> AND --source-id <id> \u2014 see `kane-cli context list --type source` for ids"};let i=q(n,t);if(!Oe(i)||!Ue(i).isFile())return{error:`--from '${t}' is not a file \u2014 pass the changed source document`};let a=me(i);if(!a.ok)return{error:`--from '${t}' is not an ingestable document \u2014 allowed: ${a.allowlist.join(", ")}`};let o=I(e);if(!o.heads.has(r))return{error:`unknown source '${r}' \u2014 see \`kane-cli context list --type source\``};if(o.heads.get(r)==null)return{error:`source '${r}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let w=z(e,r,{filePath:i});if(w!==null)return{error:w};let f=null;try{f=pe(i)}catch{}return f!==null&&f!==r&&o.heads.get(f)!=null?{error:`'${G(i)}' already backs live source '${f}' \u2014 did you mean --source-id ${f}? To truly move these bytes under '${r}', retire '${f}' first`}:{sourceId:r,filePath:i}}function C(e){return e==null?"(none)":e.slice(0,19)}function Y(e,n,t,r=!1,i){if(e.out(`reconcile ${n.source_id}: head ${n.head.status} \u2014 ${C(n.head.before)} \u2192 ${C(n.head.after)}`),r||(e.out(`note: ${n.note}`),e.out(`skipped arms: ${n.skipped_arms}`)),n.changed&&(e.out(n.held?`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i?.({type:"defaults_taken",count:t?.defaultsTaken??0})),r){let a=n.changeset??[],o=(f,v)=>{let s=a.filter(c=>c.kind===f).length;return s>0?`${s} ${v}`:null},w=[o("ADD","add"),o("MODIFY","modify"),o("ARCHIVE","archive")].filter(Boolean);n.changed&&e.out(`changeset: ${a.length} item(s)${w.length?` \u2014 ${w.join(" \xB7 ")}`:""}`),e.out(`plan: ${n.rows.length} row(s) \u2014 each gets a card below`);return}if(n.changed){let a=n.changeset??[];e.out(`changeset: ${a.length} item(s)`);for(let o of a)if(o.kind==="MODIFY")e.out(` [MODIFY] ${S(o.ref)} \u2014 ${o.summary} (${C(o.old_cid)} \u2192 ${o.new_cid===null?"(staged)":C(o.new_cid)})`);else if(o.kind==="ADD")e.out(` [ADD] ${S(o.ref)}`);else{e.out(` [ARCHIVE] ${S(o.ref)} \u2014 ${o.why}`);let w=le(o.impact,"retiring drops");w&&e.out(` ${w}`)}}e.out(`plan: ${n.rows.length} row(s)`);for(let a of n.rows){e.out(` [${a.kind}] ${S(a.ref)} \u2014 ${a.reason}`);let o=le(a.impact,"approving marks");o&&e.out(` ${o}`),e.out(` provenance: ${a.provenance}`),e.out(` action: ${a.action}`)}}function De(e,n){return ce({source_id:e.source_id,head:{status:e.head.status},rows:e.rows,archive:(e.changeset??[]).filter(t=>t.kind==="ARCHIVE"),changed:e.changed,held:!!e.held,defaultsTaken:n?.defaultsTaken},process.stdout.columns)}function le(e,n){if(!e||e.stale_refs.length===0)return null;let t=e.direct_refs??[];return`impact: ${n} ${e.stale_refs.length} item(s) stale`+(t.length>0?` \u2014 ${t.length} directly touched: ${t.join(", ")}`:"")}function D(e){return e==="interactive"?"override":e}async function M(e,n,t,r,i,a,o=[],w="override",f,v,s,c,_,u,E){let m;try{m=ne(e)}catch(d){return P(r,d instanceof Error?d.message:String(d)),1}try{if(!t){let{runWalkSession:d}=await import("./walk-session-D6TCM33V.js"),{telemetryEnvName:R}=await import("./bootstrap-3NEI7O6I.js");return await d({dir:e,rows:n,archive:o,held:f??null,childMode:w,runDesign:c??null,mark:a,markA:s,...v?{archiveState:v}:{},...u?{meta:{verb:"reconcile",sid:u,env:R()}}:{},...E?{resumeCmd:E}:{},signals:b=>U(e,b.ref,b.verdict,b.reason),..._?{script:_}:{}})}return await Te(e,n,t,r,i,a,o,w,f,v)}finally{m()}}var H=(e,n)=>e?`kane-cli maintain reconcile --from ${e} --source-id ${n}`:void 0,He=e=>e===null?void 0:"filePath"in e?e.filePath:e.remoteUrl,V=e=>`${e} high-risk item(s) need a human \u2014 ci mode won't guess. Walk interactively or use --mode agent.`;function F(e,n,t){let r=n.rows;e({type:"reconcile_plan",source_id:n.source_id,plan_path:t,rows:r.map(i=>({kind:i.kind,ref:i.ref,why:i.reason})),archive:n.changeset.filter(i=>i.kind==="ARCHIVE").map(i=>({ref:i.ref,why:i.why}))})}function de(e={}){return{type:"reconcile_summary",applied:0,skipped:0,deferred:0,plan_only:0,failed:0,paused:0,stale_created:0,...e}}var L=de();async function j(e,n,t,r,i,a,o,w,f){F(i,n,t);let v=n.changeset.filter(_=>_.kind==="ARCHIVE"&&f?.[_.ref]===void 0),s=n.rows,c;try{c=ne(e)}catch(_){return i({type:"error",message:_ instanceof Error?_.message:String(_)}),i(de()),2}try{return await Fe(e,n,t,r,i,a,o,s,v,w)}finally{c()}}async function Fe(e,n,t,r,i,a,o,w,f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set,b=(h,p)=>{try{v?.(h,p)}catch{}};for(let[h,p]of w.entries()){i({type:"reconcile_row_start",kind:p.kind,ref:p.ref,...p.impact?{stale:p.impact.stale_refs.length,direct:p.impact.direct_refs?.length??0}:{}});let g=(l,$,x)=>i({type:"reconcile_row_end",kind:p.kind,ref:p.ref,outcome:l,...$!==void 0?{exit_code:$}:{},...x?{detail:x}:{}});if(p.applied){c++,g("skipped");continue}if(p.kind==="REMOVE"){E++,g("plan-only");continue}if(p.held_ref&&n.held){let l=new Set;if(p.kind==="MODIFY"&&p.impact){let x=I(e);for(let A of p.impact.stale_refs){let K=x.resolve(A);K&&x.stale(K.tip)==="fresh"&&l.add(A)}}let $=oe(e,n.held,p.held_ref,ue);if(!$.ok){_++,d===0&&(d=1),g("failed",1,$.message);continue}if($.kind==="ADD"){let x=await r($.ref,{yes:!0,mode:o});if(x!==0){x===3?(u++,d===0&&(d=3),g("paused",3)):(_++,d===0&&(d=1),g("failed",x));continue}}s++,$.kind!=="ADD"&&p.impact&&(m+=l.size),b(h,"approved"),U(e,p.ref,$.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve"),g("applied");continue}let y=te(I(e),p.ref);if(!y.ok){c++,g("skipped");continue}let k=y.target;if(R.has(k.ucTip)){c++,g("skipped");continue}if(p.kind==="ADD"){let l=await r(k.seamRef,{yes:!0,mode:o});if(l===3){u++,d===0&&(d=3),g("paused",3);continue}if(l!==0){_++,d===0&&(d=1),g("failed",l);continue}R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-create"),g("applied")}else{let l=await re(e,k,{yes:!0,mode:o},a,r,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-evolve"),g("applied")):l.outcome==="paused"?(u++,d===0&&(d=l.code),g("paused",l.code)):l.outcome==="failed"?(_++,d===0&&(d=1),g("failed",l.code)):(c++,g("skipped"))}}return f.length>0&&(i({type:"reconcile_paused",plan_path:t,pending:f.map(h=>({ref:h.ref,why:h.why}))}),u+=f.length,d===0&&(d=3)),i(de({applied:s,skipped:c,plan_only:E,failed:_,paused:u,stale_created:m})),d}var ue={kind:"human",id:process.env.USER??"operator"};function U(e,n,t,r){ge(e,{ts:new Date().toISOString(),command:"reconcile-walk",id:n,verdict:t,polarity:"preference",by:ue,target:n,...r!==void 0?{reason:r}:{}})}async function Te(e,n,t,r,i,a,o=[],w="override",f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set;for(let[b,h]of n.entries()){if(h.applied){r.out(`skipped ${h.ref} \u2014 already applied (${h.applied.outcome} at ${h.applied.at})`),c++;continue}let p=l=>{try{a?.(b,l)}catch($){P(r,`could not record applied state for ${h.ref}: ${$ instanceof Error?$.message:String($)}`)}};if(h.kind==="REMOVE"){r.out(`REMOVE ${h.ref} \u2014 plan-only in this release (not executed)`),u++;continue}if(h.held_ref&&f){let l=oe(e,f,h.held_ref,ue);if(!l.ok){P(r,`held ${h.ref}: ${l.message}`),E++,d===0&&(d=1);continue}if(r.out(`committed ${l.ref} (${h.kind==="ADD"?"minted":"updated \u2014 old\u2192new redirect"})`),l.kind==="ADD"){let $=await i(l.ref,{yes:t,mode:w});if($===3){r.out(`design session for ${l.ref} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above`),m++,d===0&&(d=3),p("approved");continue}if($!==0){P(r,`design run for ${l.ref} ended with exit code ${$}`),E++,d===0&&(d=1),p("approved");continue}}s++,p("approved"),U(e,h.ref,h.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve");continue}let g=I(e),y=te(g,h.ref);if(!y.ok){r.out(`skipped ${h.ref} \u2014 ${y.message}`),c++;continue}let k=y.target;if(R.has(k.ucTip)){r.out(`skipped ${h.ref} \u2014 use-case ${k.display} already handled in this walk`),c++;continue}if(h.kind==="ADD"){let l=await i(k.seamRef,{yes:t,mode:w});if(l===3){r.out(`design session for ${k.display} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above; this row lands when that session completes`),m++,d===0&&(d=3);continue}if(l!==0){P(r,`design run for ${k.display} ended with exit code ${l}`),E++,d===0&&(d=1);continue}R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-create")}else{let l=await re(e,k,{yes:!0,mode:w},r,i,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-evolve")):l.outcome==="paused"?(m++,d===0&&(d=l.code)):l.outcome==="failed"?(E++,d===0&&(d=l.code)):c++}}for(let b of o)if(b.kind==="ARCHIVE"&&v?.[b.ref]===void 0){r.out(`[ARCHIVE] ${b.ref} \u2014 ${b.why}`);{let h=le(b.impact,"retiring drops");h&&r.out(` ${h}`)}r.out(" plan-only \u2014 retire belongs to the interactive session (never headless)"),u++}return r.out(`reconcile walk: ${s} applied, ${c} skipped, ${_} deferred, ${u} plan-only`+(E>0?`, ${E} failed`:"")+(m>0?`, ${m} paused`:"")),d}var Be=new Set(Z.map(e=>e.name));function z(e,n,t){let r=I(e),i=r.heads.get(n);if(i==null)return null;let a=r.mediaOf(i);if("remoteUrl"in t){let o=Q(t.remoteUrl)?.name??"remote";return a.format!==o?`source '${n}' is backed by ${a.format} content, not a ${o} source \u2014 reconcile it with the --from it was originally ingested from`:null}return Be.has(a.format)?`source '${n}' is a remote ${a.format} source \u2014 pass its URL to --from, not a file`:null}function fe(e,n,t,r){return"remoteUrl"in n?$e(e,n.remoteUrl,{out:t.out,err:t.err},r.remoteFindProvider):_e(e,n.filePath)}function Ie(e){return e.remote_url!==void 0?{remoteUrl:e.remote_url}:e.backing_path!==void 0?{filePath:e.backing_path}:null}async function Se(e,n,t,r,i,a=!1,o=!1){let w=i.seams??{reingest:fe(e,t,r,i),reextract:ae(e,{stage:a,hostOut:c=>r.out(c),hostEmit:c=>{c.type!=="run_start"&&i.emitEvent?.(c)},...i.emitEvent?{}:{hostProgress:c=>process.stderr.write(c+`
3
- `)}})},f=null,v={reingest:w.reingest,reextract:async c=>f=await w.reextract(c)},s;try{r.out(`reconciling ${n}: re-reading the source and comparing against the graph\u2026`),s=await(i.buildPlan??se)(e,n,v)}catch(c){return P(r,`reconcile failed: ${c instanceof Error?c.message:String(c)}`),null}if(s.changed)if(o)for(let c of De(s,f))r.out(c);else Y(r,s,f,!1,i.emitEvent);return s}async function Ve(e){let[{render:n},t,{ScrollbackProvider:r},{ChatSurface:i},{makeChatController:a},{makeReconcileDeps:o}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-H26E7DM6.js"),import("./chat-controller-R4THYYPU.js"),import("./reconcile-deps-ETMGIQNM.js")]),w=t.default??t,f=a(),v=o({contextDir:e,note:s=>f.note(s)});return new Promise(s=>{let c=n(w.createElement(r,null,w.createElement(i,{controller:f,verb:"extract",reconcile:v,autoReview:!0,onReviewExit:()=>{c.unmount(),s(0)},onCtrlC:()=>{c.unmount(),s(v.pending()?3:0)}})),{exitOnCtrlC:!1})})}async function Le(e,n,t,r,i){let a=N(e,n);if("error"in a)return P(r,a.error),2;let{plan:o,path:w}=a,f=t==="override"||t==="ci";if(n===void 0&&t==="interactive"&&r.isTTY&&!await r.confirm(`apply plan ${G(w)} for ${o.source_id} (created ${o.created})?`))return r.out(`not applying ${G(w)}`),0;let v=i.runDesignForUc??ie,s=i.runDesignForUc??null,c=i.sessionScript,_=(h,p)=>O(w,h,p),u=(h,p)=>W(w,h,p),E=T(e);if(E===o.head_pin){if(t==="agent"){let p=i.emitEvent??(()=>{});return j(e,B(o),w,v,p,r,D(t),_,o.archive_state)}let h=ee(o);if(t==="ci"&&h.length>0)return P(r,V(h.length)),2;if(r.out(`applying stored plan ${G(w)} for ${o.source_id} (${o.rows.length} row(s))`),!f)for(let p of ce({source_id:o.source_id,head:{status:"stored plan"},rows:o.rows,archive:(o.changeset??[]).filter(g=>g.kind==="ARCHIVE"),changed:!1,held:!!o.held},process.stdout.columns))r.out(p);return M(e,o.rows,f,r,v,_,o.changeset??[],D(t),o.held,o.archive_state,u,s,c,o.source_id,H(o.backing_path??o.remote_url,o.source_id))}if(r.out(`graph moved since this plan (${C(o.head_pin)} \u2192 ${C(E)}) \u2014 recomputing`),o.held)return Ce(e,o,r,i,t,v,!1);let m=Ie(o);if(m===null)return P(r,`stored plan for ${o.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let d=z(e,o.source_id,m);if(d!==null)return P(r,`stored plan cannot replay: ${d}`),2;let R=await Se(e,o.source_id,m,r,i,!1,t==="interactive");if(!R)return 1;if(!R.changed)return Y(r,R,null,!1,i.emitEvent),0;if(t==="agent"){let h=i.emitEvent??(()=>{});return j(e,R,null,v,h,r,D(t))}let b=R.changeset.filter(h=>h.kind==="ARCHIVE");return t==="ci"&&b.length>0?(P(r,V(b.length)),2):M(e,R.rows,f,r,v,void 0,R.changeset,D(t),R.held,void 0,void 0,s,c,R.source_id,H(He(m),R.source_id))}function B(e,n=!1){return{source_id:e.source_id,changed:!0,head:{status:"unchanged",before:e.head_pin,after:e.head_pin},note:e.note,skipped_arms:e.skipped_arms,changeset:e.changeset??[],rows:n?e.rows.filter(t=>t.applied===void 0):e.rows,...e.held?{held:e.held}:{}}}async function je(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v=he(e,n);if(v===null)return null;if("error"in v)return P(t,v.error),2;let{plan:s,path:c}=v,_=s.rows.filter(d=>d.applied===void 0),u=ee(s),E=r.emitEvent??(()=>{});if(_.length===0&&u.length===0){t.out(`already reconciled \u2014 plan ${s.created} applied ${s.rows.length} row(s)`);let d=ye(I(e)).staleCount;return d>0&&(t.out(`${d} item(s) still stale \u2014 kane-cli maintain evolve --from-stale`),E({type:"stale_debt",count:d})),i==="agent"&&(F(E,B(s),c),E({...L})),0}let m=T(e);return m!==s.head_pin?(t.out(`plan ${s.created} superseded \u2014 graph moved (${C(s.head_pin)} \u2192 ${C(m)}); recomputing`),Ce(e,s,t,r,i,a,o)):(t.out(`resuming plan ${s.created} \u2014 ${_.length} pending row(s)${u.length>0?`, ${u.length} undecided archive item(s)`:""}`),o?(Y(t,B(s),null,!1,r.emitEvent),t.out(`plan stored: ${c}`),i==="agent"&&(F(E,B(s),c),E({...L})),0):i==="agent"?j(e,B(s),c,a,E,t,D(i),(d,R)=>O(c,d,R),s.archive_state):i==="ci"&&u.length>0?(P(t,V(u.length)),2):M(e,s.rows,i==="override"||i==="ci",t,a,(d,R)=>O(c,d,R),s.changeset??[],D(i),s.held,s.archive_state,(d,R)=>W(c,d,R),w,f,s.source_id,H(s.backing_path??s.remote_url,s.source_id)))}async function Ce(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v;if(n.held){let g=I(e),y=new Set(n.rows.filter(l=>l.held_ref!==void 0&&l.applied!==void 0).map(l=>l.held_ref)),k=[];for(let l of n.held.rows){if(y.has(l.temp_ref))continue;if(!l.matched_cid){k.push(l);continue}let $=g.tipOf(l.matched_cid);if(g.superseded.get($)===null){t.out(`dropped held "${l.title}" \u2014 its use-case was retired meanwhile`),r.emitEvent?.({type:"held_dropped",ref:l.temp_ref,title:l.title,reason:"target_retired"});continue}k.push($===l.matched_cid?l:{...l,matched_cid:$,uc:{...l.uc,matches_existing:{cid:$}}})}v={source_id:n.held.source_id,rows:k}}let s=Ie(n);if(s===null)return P(t,`stored plan for ${n.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let c=z(e,n.source_id,s);if(c!==null)return P(t,`stored plan cannot replay: ${c}`),2;let _=r.seams??{reingest:fe(e,s,t,r),reextract:ae(e,{stage:v!==void 0,hostOut:g=>t.out(g),hostEmit:g=>{g.type!=="run_start"&&r.emitEvent?.(g)},...r.emitEvent?{}:{hostProgress:g=>process.stderr.write(g+`
4
- `)}})},u;try{u=await(r.buildPlan??se)(e,n.source_id,_,{resumeHeld:v})}catch(g){return P(t,`reconcile failed: ${g instanceof Error?g.message:String(g)}`),1}if(i==="interactive"&&!o)for(let g of De(u,null))t.out(g);else Y(t,u,null,!1,r.emitEvent);let E=T(e),m=null;if(E!=null){let g={},y=new Set(u.changeset.filter(k=>k.kind==="ARCHIVE").map(k=>k.ref));for(let[k,l]of Object.entries(n.archive_state??{}))y.has(k)&&(g[k]=l);m=X(e,{version:2,source_id:u.source_id,...n.remote_url!==void 0?{remote_url:n.remote_url}:{backing_path:n.backing_path},head_pin:E,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:u.skipped_arms,note:u.note,changeset:u.changeset,rows:u.rows,...u.held?{held:u.held}:{},...Object.keys(g).length>0?{archive_state:g}:{}}),t.out(`plan stored: ${m}`)}if(o){if(i==="agent"){let g=r.emitEvent??(()=>{});F(g,u,m),g({...L})}return 0}let d=r.emitEvent??(()=>{}),R=m?N(e,m).plan.archive_state:void 0,b=m?(g,y)=>O(m,g,y):void 0,h=m?(g,y)=>W(m,g,y):void 0;if(i==="agent")return j(e,u,m,a,d,t,D(i),b,R);let p=u.changeset.filter(g=>g.kind==="ARCHIVE"&&R?.[g.ref]===void 0);return i==="ci"&&p.length>0?(P(t,V(p.length)),2):M(e,u.rows,i==="override"||i==="ci",t,a,b,u.changeset,D(i),u.held,R,h,w,f,u.source_id,H(n.backing_path??n.remote_url,u.source_id))}async function be(e,n,t={},r=process.cwd()){let{telemetryBootstrap:i,telemetryEnvName:a}=await import("./bootstrap-3NEI7O6I.js"),o=i({verb:"reconcile",mode:typeof e.mode=="string"?e.mode:"interactive",contextRoot:q(r,".context"),env:a(),applyPlanPath:typeof e.apply=="string"?q(r,e.apply):void 0,write:!0,longSession:!0});e.mode==="agent"&&t.emitEvent?.({type:"run_start",session:o.ids.session_id});let w=await Ye(e,n,t,r);return w===1&&e.mode!=="agent"&&(n.err??n.out)(o.supportFooter()),await o.end({exit_code:w}),w}async function Ye(e,n,t={},r=process.cwd()){let i=e.apply!==void 0&&e.apply!==!1,a=typeof e.apply=="string"?e.apply:void 0;if(e.plan&&i)return P(n,"pass --plan OR --apply, not both"),2;let o=e.from!==void 0||!i,w=e.from!==void 0&&J(e.from);if(o&&(!e.from||!e.sourceId&&!w))return P(n,"reconcile needs --from <file|url> AND --source-id <id> (files only \u2014 a URL derives its own id) \u2014 see `kane-cli context list --type source` for ids"),2;if(e.from&&a!==void 0)return P(n,"pass --from OR --apply <path>, not both \u2014 a stored plan names its own source"),2;let f=we(r,n);if(!f)return 2;if(e.mode!==void 0&&!xe.has(e.mode))return Pe(`--mode must be interactive | agent | ci | override, got '${e.mode}'`);let v=e.mode==="agent"||e.mode==="ci"||e.mode==="override";if(i&&!v&&!n.isTTY)return P(n,"refusing to apply without a TTY to confirm \u2014 pass --mode override|ci"),2;let s=!e.plan,c="override";if(e.from){let y=Ae(e,n.isTTY);if(typeof y=="object")return y.code==="MODE_USAGE"?Pe(y.error):(P(n,y.error),2);c=y}let _=c==="override"||c==="ci";if(i&&!e.from){let{makeReconcileDeps:y}=await import("./reconcile-deps-ETMGIQNM.js"),k=a===void 0?y({contextDir:f}).pending():null;if(k?.kind==="cards"){let $=e.mode??"interactive";return!n.isTTY||$!=="interactive"?(P(n,`a held changeset for ${k.source} awaits review (${k.count} change(s)) \u2014 resume in a terminal: kane-cli maintain reconcile --apply [HELD_REVIEW]`),2):(t.cardApplyMount??Ve)(f)}let l=e.mode??"interactive";return Le(f,a===void 0?void 0:q(r,a),l,n,t)}let u=Me(f,r,e.from,e.sourceId);if("error"in u)return P(n,u.error),2;if(!i){let{sessionsHoldingSource:y}=await import("./sessions-GIEXOCE4.js"),{holders:k,corrupt:l}=y(f,u.sourceId);if(l>0)return P(n,`cannot verify review holds \u2014 ${l} session file(s) unreadable; inspect with kane-cli context sessions list, clean with kane-cli context sessions clean, then retry [SESSIONS_UNREADABLE]`),2;if(k.length>0)return P(n,`session ${k[0]} holds item(s) for review pinned to ${u.sourceId} \u2014 finish that review first: kane-cli context extract --resume ${k[0]} [SOURCE_HELD]`),2}if(c==="interactive"&&!e.plan&&!i){let y=t.seams?.reingest??fe(f,u,n,t),k;try{k=await y(u.sourceId)}catch($){return P(n,$ instanceof Error?$.message:String($)),1}let l=k.status==="unchanged"?null:Re(f,u.sourceId);if(k.status!=="unchanged"&&!l)return n.out(`${u.sourceId} landed for the first time \u2014 extract it: kane-cli context extract --source ${u.sourceId}`),0;if(l){let x=await(t.chatMount??(async A=>{let{bindExtractInteractive:K}=await import("./extract-bind-LBZMEDUK.js");return K(A)}))({mode:"interactive",posture:"reconcile",source:u.sourceId,changeContext:l});if(x===3){let{sessionsHoldingSource:A}=await import("./sessions-GIEXOCE4.js");if(A(f,u.sourceId).holders.length===0)return 0}return x}}let E="remoteUrl"in u?{remoteUrl:u.remoteUrl}:{filePath:u.filePath},m=await Se(f,u.sourceId,E,n,t,!!e.plan||c==="interactive",c==="interactive"&&!e.plan);if(!m)return 1;let d=t.runDesignForUc??ie,R=t.runDesignForUc??null,b=t.sessionScript;if(!m.changed){let y=await je(f,u.sourceId,n,t,c,d,!!e.plan);if(y!==null)return y;if(Y(n,m,null,!1,t.emitEvent),c==="agent"){let k=t.emitEvent??(()=>{});F(k,m,null),k({...L})}return 0}let h=T(f),p=null;if(h!=null?p=X(f,{version:2,source_id:m.source_id,..."remoteUrl"in E?{remote_url:E.remoteUrl}:{backing_path:E.filePath},head_pin:h,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:m.skipped_arms,note:m.note,changeset:m.changeset,rows:m.rows,...m.held?{held:m.held}:{}}):P(n,"no chain head after extract \u2014 plan not stored"),c==="agent"){let y=t.emitEvent??(()=>{});if(!s)return F(y,m,p),y({...L}),0;let k=p?(l,$)=>O(p,l,$):void 0;return j(f,m,p,d,y,n,D(c),k)}if(!s)return p&&n.out(`plan stored: ${p}`),0;let g=m.changeset.filter(y=>y.kind==="ARCHIVE");if(c==="ci"&&g.length>0)return p&&n.out(`plan stored: ${p}`),P(n,V(g.length)),2;if(p){n.out(`plan stored: ${p}`);let y=p;return M(f,Ke(f,y)??m.rows,_,n,d,(k,l)=>O(y,k,l),m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}return M(f,m.rows,_,n,d,void 0,m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}function Ke(e,n){let t=N(e,n);return"error"in t?null:t.plan.rows}async function dn(e,n={},t,r=process.cwd()){if(e.mode==="agent"){let{makeHeadlessIO:i}=await import("./headless-io-66RG5NN5.js"),a=t?i("ndjson","reconcile",t):i("ndjson","reconcile"),o={out:a.out,err:v=>a.event({type:"error",message:v}),isTTY:!1,confirm:async()=>!1,ask:async()=>""},{runWithChannel:w}=await import("./run-channel-RGH4WIQX.js"),f=2;try{f=await w({event:v=>a.event(v)},()=>be(e,o,{...n,emitEvent:v=>a.event(v)},r))}catch(v){f=1,a.event({type:"error",message:v instanceof Error?v.message:String(v)})}return a.done(f)}return be(e,ke(),n,r)}export{Ae as a,Me as b,D as c,U as d,be as e,dn as f};
2
+ import{j as Re,k as oe,l as se,m as _e,n as $e,o as ae}from"./chunk-M335FQYJ.js";import{a as te,c as re,d as ye,f as ie}from"./chunk-DCUT3GJA.js";import{a as P,b as we,d as ke}from"./chunk-OS4VSIHT.js";import{d as ve}from"./chunk-6J5T5FEY.js";import{a as S}from"./chunk-CLGC7VEO.js";import{a as X,b as N,c as ee,d as W,e as he,g as O,h as ne}from"./chunk-W5TTF7GB.js";import{a as ge}from"./chunk-JFAFKHDX.js";import{b as Z,c as J,d as Q}from"./chunk-VT2XNEOD.js";import{f as me,h as pe}from"./chunk-X2FM67OM.js";import{A as I}from"./chunk-TH47OOBV.js";import{f as T}from"./chunk-DUAXZYAD.js";import{existsSync as Oe,statSync as Ue}from"fs";import{basename as G,resolve as q}from"path";function Ee(e){if(!e||e.stale_refs.length===0)return"\u2014";let n=e.direct_refs??[];return`${e.stale_refs.length} stale${n.length>0?` \xB7 ${n.length} direct`:""}`}function ce(e,n){let t=[...e.rows.filter(a=>a.kind!=="REMOVE").map(a=>[a.kind,S(a.ref),a.reason,Ee(a.impact)]),...e.archive.map(a=>["ARCHIVE",S(a.ref),a.why,Ee(a.impact)])],r=Math.max(40,n??100),i=[`reconcile ${e.source_id} \u2014 head ${e.head.status} \xB7 ${t.length} decision${t.length===1?"":"s"}`];return t.length>0&&i.push(...ve(["kind","ref","why","impact"],t,r,2)),e.changed&&i.push(e.held?`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${e.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i.push("each row becomes a card below \u2014 verdicts commit as they land"),e.planPath&&i.push(`plan: ${e.planPath}`),i}var xe=new Set(["interactive","agent","ci","override"]);function Ae(e,n){if(e.mode!==void 0&&!xe.has(e.mode))return{error:`--mode must be interactive | agent | ci | override, got '${e.mode}'`,code:"MODE_USAGE"};let t=e.mode,r="reconcile without a TTY needs an explicit mode \u2014 pass --mode agent|ci|override, or --plan for a preview";return t==="interactive"&&!n?{error:r}:t||(n?"interactive":e.plan?"override":{error:r})}async function Pe(e){let{makeHeadlessIO:n,agentRefusal:t}=await import("./headless-io-66RG5NN5.js");return t(n("ndjson","reconcile"),e,"MODE_USAGE")}function Me(e,n,t,r){if(J(t)){let v=Q(t),s=v?.sourceIdFor(t)??null;if(v===null||s===null)return{error:`--from '${t}' is not a supported remote URL \u2014 supported: ${Z.map(u=>u.hint).join("; ")}`};if(r!==void 0&&r!==s)return{error:`--source-id '${r}' does not match this URL's own identity '${s}' \u2014 re-run without --source-id. A source adopted with --as updates by re-running context ingest with the same --as; reconcile follows only the URL's own id`};let c=I(e);if(!c.heads.has(s))return{error:`unknown source '${s}' \u2014 see \`kane-cli context list --type source\`. If this URL was ingested under a custom id, update it by re-running context ingest with the same --as`};if(c.heads.get(s)==null)return{error:`source '${s}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let _=z(e,s,{remoteUrl:t});return _!==null?{error:_}:{sourceId:s,remoteUrl:t}}if(r===void 0)return{error:"reconcile needs --from <file> AND --source-id <id> \u2014 see `kane-cli context list --type source` for ids"};let i=q(n,t);if(!Oe(i)||!Ue(i).isFile())return{error:`--from '${t}' is not a file \u2014 pass the changed source document`};let a=me(i);if(!a.ok)return{error:`--from '${t}' is not an ingestable document \u2014 allowed: ${a.allowlist.join(", ")}`};let o=I(e);if(!o.heads.has(r))return{error:`unknown source '${r}' \u2014 see \`kane-cli context list --type source\``};if(o.heads.get(r)==null)return{error:`source '${r}' is retired \u2014 restore it first with \`kane-cli context revert\`, then reconcile`};let w=z(e,r,{filePath:i});if(w!==null)return{error:w};let f=null;try{f=pe(i)}catch{}return f!==null&&f!==r&&o.heads.get(f)!=null?{error:`'${G(i)}' already backs live source '${f}' \u2014 did you mean --source-id ${f}? To truly move these bytes under '${r}', retire '${f}' first`}:{sourceId:r,filePath:i}}function C(e){return e==null?"(none)":e.slice(0,19)}function Y(e,n,t,r=!1,i){if(e.out(`reconcile ${n.source_id}: head ${n.head.status} \u2014 ${C(n.head.before)} \u2192 ${C(n.head.after)}`),r||(e.out(`note: ${n.note}`),e.out(`skipped arms: ${n.skipped_arms}`)),n.changed&&(e.out(n.held?`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed and new proposals HELD for your verdict (staged \u2014 nothing committed)`:`extract ran in override mode; ${t?.defaultsTaken??0} default(s) auto-taken; matched-but-changed proposals auto-committed as edits`),i?.({type:"defaults_taken",count:t?.defaultsTaken??0})),r){let a=n.changeset??[],o=(f,v)=>{let s=a.filter(c=>c.kind===f).length;return s>0?`${s} ${v}`:null},w=[o("ADD","add"),o("MODIFY","modify"),o("ARCHIVE","archive")].filter(Boolean);n.changed&&e.out(`changeset: ${a.length} item(s)${w.length?` \u2014 ${w.join(" \xB7 ")}`:""}`),e.out(`plan: ${n.rows.length} row(s) \u2014 each gets a card below`);return}if(n.changed){let a=n.changeset??[];e.out(`changeset: ${a.length} item(s)`);for(let o of a)if(o.kind==="MODIFY")e.out(` [MODIFY] ${S(o.ref)} \u2014 ${o.summary} (${C(o.old_cid)} \u2192 ${o.new_cid===null?"(staged)":C(o.new_cid)})`);else if(o.kind==="ADD")e.out(` [ADD] ${S(o.ref)}`);else{e.out(` [ARCHIVE] ${S(o.ref)} \u2014 ${o.why}`);let w=le(o.impact,"retiring drops");w&&e.out(` ${w}`)}}e.out(`plan: ${n.rows.length} row(s)`);for(let a of n.rows){e.out(` [${a.kind}] ${S(a.ref)} \u2014 ${a.reason}`);let o=le(a.impact,"approving marks");o&&e.out(` ${o}`),e.out(` provenance: ${a.provenance}`),e.out(` action: ${a.action}`)}}function De(e,n){return ce({source_id:e.source_id,head:{status:e.head.status},rows:e.rows,archive:(e.changeset??[]).filter(t=>t.kind==="ARCHIVE"),changed:e.changed,held:!!e.held,defaultsTaken:n?.defaultsTaken},process.stdout.columns)}function le(e,n){if(!e||e.stale_refs.length===0)return null;let t=e.direct_refs??[];return`impact: ${n} ${e.stale_refs.length} item(s) stale`+(t.length>0?` \u2014 ${t.length} directly touched: ${t.join(", ")}`:"")}function D(e){return e==="interactive"?"override":e}async function M(e,n,t,r,i,a,o=[],w="override",f,v,s,c,_,u,E){let m;try{m=ne(e)}catch(d){return P(r,d instanceof Error?d.message:String(d)),1}try{if(!t){let{runWalkSession:d}=await import("./walk-session-IODOH7QU.js"),{telemetryEnvName:R}=await import("./bootstrap-5IHKW5SE.js");return await d({dir:e,rows:n,archive:o,held:f??null,childMode:w,runDesign:c??null,mark:a,markA:s,...v?{archiveState:v}:{},...u?{meta:{verb:"reconcile",sid:u,env:R()}}:{},...E?{resumeCmd:E}:{},signals:b=>U(e,b.ref,b.verdict,b.reason),..._?{script:_}:{}})}return await Te(e,n,t,r,i,a,o,w,f,v)}finally{m()}}var H=(e,n)=>e?`kane-cli maintain reconcile --from ${e} --source-id ${n}`:void 0,He=e=>e===null?void 0:"filePath"in e?e.filePath:e.remoteUrl,V=e=>`${e} high-risk item(s) need a human \u2014 ci mode won't guess. Walk interactively or use --mode agent.`;function F(e,n,t){let r=n.rows;e({type:"reconcile_plan",source_id:n.source_id,plan_path:t,rows:r.map(i=>({kind:i.kind,ref:i.ref,why:i.reason})),archive:n.changeset.filter(i=>i.kind==="ARCHIVE").map(i=>({ref:i.ref,why:i.why}))})}function de(e={}){return{type:"reconcile_summary",applied:0,skipped:0,deferred:0,plan_only:0,failed:0,paused:0,stale_created:0,...e}}var L=de();async function j(e,n,t,r,i,a,o,w,f){F(i,n,t);let v=n.changeset.filter(_=>_.kind==="ARCHIVE"&&f?.[_.ref]===void 0),s=n.rows,c;try{c=ne(e)}catch(_){return i({type:"error",message:_ instanceof Error?_.message:String(_)}),i(de()),2}try{return await Fe(e,n,t,r,i,a,o,s,v,w)}finally{c()}}async function Fe(e,n,t,r,i,a,o,w,f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set,b=(h,p)=>{try{v?.(h,p)}catch{}};for(let[h,p]of w.entries()){i({type:"reconcile_row_start",kind:p.kind,ref:p.ref,...p.impact?{stale:p.impact.stale_refs.length,direct:p.impact.direct_refs?.length??0}:{}});let g=(l,$,x)=>i({type:"reconcile_row_end",kind:p.kind,ref:p.ref,outcome:l,...$!==void 0?{exit_code:$}:{},...x?{detail:x}:{}});if(p.applied){c++,g("skipped");continue}if(p.kind==="REMOVE"){E++,g("plan-only");continue}if(p.held_ref&&n.held){let l=new Set;if(p.kind==="MODIFY"&&p.impact){let x=I(e);for(let A of p.impact.stale_refs){let K=x.resolve(A);K&&x.stale(K.tip)==="fresh"&&l.add(A)}}let $=oe(e,n.held,p.held_ref,ue);if(!$.ok){_++,d===0&&(d=1),g("failed",1,$.message);continue}if($.kind==="ADD"){let x=await r($.ref,{yes:!0,mode:o});if(x!==0){x===3?(u++,d===0&&(d=3),g("paused",3)):(_++,d===0&&(d=1),g("failed",x));continue}}s++,$.kind!=="ADD"&&p.impact&&(m+=l.size),b(h,"approved"),U(e,p.ref,$.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve"),g("applied");continue}let y=te(I(e),p.ref);if(!y.ok){c++,g("skipped");continue}let k=y.target;if(R.has(k.ucTip)){c++,g("skipped");continue}if(p.kind==="ADD"){let l=await r(k.seamRef,{yes:!0,mode:o});if(l===3){u++,d===0&&(d=3),g("paused",3);continue}if(l!==0){_++,d===0&&(d=1),g("failed",l);continue}R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-create"),g("applied")}else{let l=await re(e,k,{yes:!0,mode:o},a,r,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,b(h,"approved"),U(e,p.ref,"gap-resolved-evolve"),g("applied")):l.outcome==="paused"?(u++,d===0&&(d=l.code),g("paused",l.code)):l.outcome==="failed"?(_++,d===0&&(d=1),g("failed",l.code)):(c++,g("skipped"))}}return f.length>0&&(i({type:"reconcile_paused",plan_path:t,pending:f.map(h=>({ref:h.ref,why:h.why}))}),u+=f.length,d===0&&(d=3)),i(de({applied:s,skipped:c,plan_only:E,failed:_,paused:u,stale_created:m})),d}var ue={kind:"human",id:process.env.USER??"operator"};function U(e,n,t,r){ge(e,{ts:new Date().toISOString(),command:"reconcile-walk",id:n,verdict:t,polarity:"preference",by:ue,target:n,...r!==void 0?{reason:r}:{}})}async function Te(e,n,t,r,i,a,o=[],w="override",f,v){let s=0,c=0,_=0,u=0,E=0,m=0,d=0,R=new Set;for(let[b,h]of n.entries()){if(h.applied){r.out(`skipped ${h.ref} \u2014 already applied (${h.applied.outcome} at ${h.applied.at})`),c++;continue}let p=l=>{try{a?.(b,l)}catch($){P(r,`could not record applied state for ${h.ref}: ${$ instanceof Error?$.message:String($)}`)}};if(h.kind==="REMOVE"){r.out(`REMOVE ${h.ref} \u2014 plan-only in this release (not executed)`),u++;continue}if(h.held_ref&&f){let l=oe(e,f,h.held_ref,ue);if(!l.ok){P(r,`held ${h.ref}: ${l.message}`),E++,d===0&&(d=1);continue}if(r.out(`committed ${l.ref} (${h.kind==="ADD"?"minted":"updated \u2014 old\u2192new redirect"})`),l.kind==="ADD"){let $=await i(l.ref,{yes:t,mode:w});if($===3){r.out(`design session for ${l.ref} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above`),m++,d===0&&(d=3),p("approved");continue}if($!==0){P(r,`design run for ${l.ref} ended with exit code ${$}`),E++,d===0&&(d=1),p("approved");continue}}s++,p("approved"),U(e,h.ref,h.kind==="ADD"?"gap-resolved-create":"gap-resolved-evolve");continue}let g=I(e),y=te(g,h.ref);if(!y.ok){r.out(`skipped ${h.ref} \u2014 ${y.message}`),c++;continue}let k=y.target;if(R.has(k.ucTip)){r.out(`skipped ${h.ref} \u2014 use-case ${k.display} already handled in this walk`),c++;continue}if(h.kind==="ADD"){let l=await i(k.seamRef,{yes:t,mode:w});if(l===3){r.out(`design session for ${k.display} paused \u2014 resume with the "kane-cli design tests --resume <session>" command printed above; this row lands when that session completes`),m++,d===0&&(d=3);continue}if(l!==0){P(r,`design run for ${k.display} ended with exit code ${l}`),E++,d===0&&(d=1);continue}R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-create")}else{let l=await re(e,k,{yes:!0,mode:w},r,i,"batch");l.outcome==="evolved"?(R.add(k.ucTip),s++,p("approved"),U(e,h.ref,"gap-resolved-evolve")):l.outcome==="paused"?(m++,d===0&&(d=l.code)):l.outcome==="failed"?(E++,d===0&&(d=l.code)):c++}}for(let b of o)if(b.kind==="ARCHIVE"&&v?.[b.ref]===void 0){r.out(`[ARCHIVE] ${b.ref} \u2014 ${b.why}`);{let h=le(b.impact,"retiring drops");h&&r.out(` ${h}`)}r.out(" plan-only \u2014 retire belongs to the interactive session (never headless)"),u++}return r.out(`reconcile walk: ${s} applied, ${c} skipped, ${_} deferred, ${u} plan-only`+(E>0?`, ${E} failed`:"")+(m>0?`, ${m} paused`:"")),d}var Be=new Set(Z.map(e=>e.name));function z(e,n,t){let r=I(e),i=r.heads.get(n);if(i==null)return null;let a=r.mediaOf(i);if("remoteUrl"in t){let o=Q(t.remoteUrl)?.name??"remote";return a.format!==o?`source '${n}' is backed by ${a.format} content, not a ${o} source \u2014 reconcile it with the --from it was originally ingested from`:null}return Be.has(a.format)?`source '${n}' is a remote ${a.format} source \u2014 pass its URL to --from, not a file`:null}function fe(e,n,t,r){return"remoteUrl"in n?$e(e,n.remoteUrl,{out:t.out,err:t.err},r.remoteFindProvider):_e(e,n.filePath)}function Ie(e){return e.remote_url!==void 0?{remoteUrl:e.remote_url}:e.backing_path!==void 0?{filePath:e.backing_path}:null}async function Se(e,n,t,r,i,a=!1,o=!1){let w=i.seams??{reingest:fe(e,t,r,i),reextract:ae(e,{stage:a,hostOut:c=>r.out(c),hostEmit:c=>{c.type!=="run_start"&&i.emitEvent?.(c)},...i.emitEvent?{}:{hostProgress:c=>process.stderr.write(c+`
3
+ `)}})},f=null,v={reingest:w.reingest,reextract:async c=>f=await w.reextract(c)},s;try{r.out(`reconciling ${n}: re-reading the source and comparing against the graph\u2026`),s=await(i.buildPlan??se)(e,n,v)}catch(c){return P(r,`reconcile failed: ${c instanceof Error?c.message:String(c)}`),null}if(s.changed)if(o)for(let c of De(s,f))r.out(c);else Y(r,s,f,!1,i.emitEvent);return s}async function Ve(e){let[{render:n},t,{ScrollbackProvider:r},{ChatSurface:i},{makeChatController:a},{makeReconcileDeps:o}]=await Promise.all([import("./build-JIKYOZUH.js"),import("./react-QWOAB3TB.js"),import("./scrollback-JLPJR25X.js"),import("./ChatSurface-HAIVTS4J.js"),import("./chat-controller-R4THYYPU.js"),import("./reconcile-deps-SUKZA2FL.js")]),w=t.default??t,f=a(),v=o({contextDir:e,note:s=>f.note(s)});return new Promise(s=>{let c=n(w.createElement(r,null,w.createElement(i,{controller:f,verb:"extract",reconcile:v,autoReview:!0,onReviewExit:()=>{c.unmount(),s(0)},onCtrlC:()=>{c.unmount(),s(v.pending()?3:0)}})),{exitOnCtrlC:!1})})}async function Le(e,n,t,r,i){let a=N(e,n);if("error"in a)return P(r,a.error),2;let{plan:o,path:w}=a,f=t==="override"||t==="ci";if(n===void 0&&t==="interactive"&&r.isTTY&&!await r.confirm(`apply plan ${G(w)} for ${o.source_id} (created ${o.created})?`))return r.out(`not applying ${G(w)}`),0;let v=i.runDesignForUc??ie,s=i.runDesignForUc??null,c=i.sessionScript,_=(h,p)=>O(w,h,p),u=(h,p)=>W(w,h,p),E=T(e);if(E===o.head_pin){if(t==="agent"){let p=i.emitEvent??(()=>{});return j(e,B(o),w,v,p,r,D(t),_,o.archive_state)}let h=ee(o);if(t==="ci"&&h.length>0)return P(r,V(h.length)),2;if(r.out(`applying stored plan ${G(w)} for ${o.source_id} (${o.rows.length} row(s))`),!f)for(let p of ce({source_id:o.source_id,head:{status:"stored plan"},rows:o.rows,archive:(o.changeset??[]).filter(g=>g.kind==="ARCHIVE"),changed:!1,held:!!o.held},process.stdout.columns))r.out(p);return M(e,o.rows,f,r,v,_,o.changeset??[],D(t),o.held,o.archive_state,u,s,c,o.source_id,H(o.backing_path??o.remote_url,o.source_id))}if(r.out(`graph moved since this plan (${C(o.head_pin)} \u2192 ${C(E)}) \u2014 recomputing`),o.held)return Ce(e,o,r,i,t,v,!1);let m=Ie(o);if(m===null)return P(r,`stored plan for ${o.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let d=z(e,o.source_id,m);if(d!==null)return P(r,`stored plan cannot replay: ${d}`),2;let R=await Se(e,o.source_id,m,r,i,!1,t==="interactive");if(!R)return 1;if(!R.changed)return Y(r,R,null,!1,i.emitEvent),0;if(t==="agent"){let h=i.emitEvent??(()=>{});return j(e,R,null,v,h,r,D(t))}let b=R.changeset.filter(h=>h.kind==="ARCHIVE");return t==="ci"&&b.length>0?(P(r,V(b.length)),2):M(e,R.rows,f,r,v,void 0,R.changeset,D(t),R.held,void 0,void 0,s,c,R.source_id,H(He(m),R.source_id))}function B(e,n=!1){return{source_id:e.source_id,changed:!0,head:{status:"unchanged",before:e.head_pin,after:e.head_pin},note:e.note,skipped_arms:e.skipped_arms,changeset:e.changeset??[],rows:n?e.rows.filter(t=>t.applied===void 0):e.rows,...e.held?{held:e.held}:{}}}async function je(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v=he(e,n);if(v===null)return null;if("error"in v)return P(t,v.error),2;let{plan:s,path:c}=v,_=s.rows.filter(d=>d.applied===void 0),u=ee(s),E=r.emitEvent??(()=>{});if(_.length===0&&u.length===0){t.out(`already reconciled \u2014 plan ${s.created} applied ${s.rows.length} row(s)`);let d=ye(I(e)).staleCount;return d>0&&(t.out(`${d} item(s) still stale \u2014 kane-cli maintain evolve --from-stale`),E({type:"stale_debt",count:d})),i==="agent"&&(F(E,B(s),c),E({...L})),0}let m=T(e);return m!==s.head_pin?(t.out(`plan ${s.created} superseded \u2014 graph moved (${C(s.head_pin)} \u2192 ${C(m)}); recomputing`),Ce(e,s,t,r,i,a,o)):(t.out(`resuming plan ${s.created} \u2014 ${_.length} pending row(s)${u.length>0?`, ${u.length} undecided archive item(s)`:""}`),o?(Y(t,B(s),null,!1,r.emitEvent),t.out(`plan stored: ${c}`),i==="agent"&&(F(E,B(s),c),E({...L})),0):i==="agent"?j(e,B(s),c,a,E,t,D(i),(d,R)=>O(c,d,R),s.archive_state):i==="ci"&&u.length>0?(P(t,V(u.length)),2):M(e,s.rows,i==="override"||i==="ci",t,a,(d,R)=>O(c,d,R),s.changeset??[],D(i),s.held,s.archive_state,(d,R)=>W(c,d,R),w,f,s.source_id,H(s.backing_path??s.remote_url,s.source_id)))}async function Ce(e,n,t,r,i,a,o){let w=r.runDesignForUc??null,f=r.sessionScript,v;if(n.held){let g=I(e),y=new Set(n.rows.filter(l=>l.held_ref!==void 0&&l.applied!==void 0).map(l=>l.held_ref)),k=[];for(let l of n.held.rows){if(y.has(l.temp_ref))continue;if(!l.matched_cid){k.push(l);continue}let $=g.tipOf(l.matched_cid);if(g.superseded.get($)===null){t.out(`dropped held "${l.title}" \u2014 its use-case was retired meanwhile`),r.emitEvent?.({type:"held_dropped",ref:l.temp_ref,title:l.title,reason:"target_retired"});continue}k.push($===l.matched_cid?l:{...l,matched_cid:$,uc:{...l.uc,matches_existing:{cid:$}}})}v={source_id:n.held.source_id,rows:k}}let s=Ie(n);if(s===null)return P(t,`stored plan for ${n.source_id} names no backing file or URL \u2014 re-run reconcile --from`),2;let c=z(e,n.source_id,s);if(c!==null)return P(t,`stored plan cannot replay: ${c}`),2;let _=r.seams??{reingest:fe(e,s,t,r),reextract:ae(e,{stage:v!==void 0,hostOut:g=>t.out(g),hostEmit:g=>{g.type!=="run_start"&&r.emitEvent?.(g)},...r.emitEvent?{}:{hostProgress:g=>process.stderr.write(g+`
4
+ `)}})},u;try{u=await(r.buildPlan??se)(e,n.source_id,_,{resumeHeld:v})}catch(g){return P(t,`reconcile failed: ${g instanceof Error?g.message:String(g)}`),1}if(i==="interactive"&&!o)for(let g of De(u,null))t.out(g);else Y(t,u,null,!1,r.emitEvent);let E=T(e),m=null;if(E!=null){let g={},y=new Set(u.changeset.filter(k=>k.kind==="ARCHIVE").map(k=>k.ref));for(let[k,l]of Object.entries(n.archive_state??{}))y.has(k)&&(g[k]=l);m=X(e,{version:2,source_id:u.source_id,...n.remote_url!==void 0?{remote_url:n.remote_url}:{backing_path:n.backing_path},head_pin:E,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:u.skipped_arms,note:u.note,changeset:u.changeset,rows:u.rows,...u.held?{held:u.held}:{},...Object.keys(g).length>0?{archive_state:g}:{}}),t.out(`plan stored: ${m}`)}if(o){if(i==="agent"){let g=r.emitEvent??(()=>{});F(g,u,m),g({...L})}return 0}let d=r.emitEvent??(()=>{}),R=m?N(e,m).plan.archive_state:void 0,b=m?(g,y)=>O(m,g,y):void 0,h=m?(g,y)=>W(m,g,y):void 0;if(i==="agent")return j(e,u,m,a,d,t,D(i),b,R);let p=u.changeset.filter(g=>g.kind==="ARCHIVE"&&R?.[g.ref]===void 0);return i==="ci"&&p.length>0?(P(t,V(p.length)),2):M(e,u.rows,i==="override"||i==="ci",t,a,b,u.changeset,D(i),u.held,R,h,w,f,u.source_id,H(n.backing_path??n.remote_url,u.source_id))}async function be(e,n,t={},r=process.cwd()){let{telemetryBootstrap:i,telemetryEnvName:a}=await import("./bootstrap-5IHKW5SE.js"),o=i({verb:"reconcile",mode:typeof e.mode=="string"?e.mode:"interactive",contextRoot:q(r,".context"),env:a(),applyPlanPath:typeof e.apply=="string"?q(r,e.apply):void 0,write:!0,longSession:!0});e.mode==="agent"&&t.emitEvent?.({type:"run_start",session:o.ids.session_id});let w=await Ye(e,n,t,r);return w===1&&e.mode!=="agent"&&(n.err??n.out)(o.supportFooter()),await o.end({exit_code:w}),w}async function Ye(e,n,t={},r=process.cwd()){let i=e.apply!==void 0&&e.apply!==!1,a=typeof e.apply=="string"?e.apply:void 0;if(e.plan&&i)return P(n,"pass --plan OR --apply, not both"),2;let o=e.from!==void 0||!i,w=e.from!==void 0&&J(e.from);if(o&&(!e.from||!e.sourceId&&!w))return P(n,"reconcile needs --from <file|url> AND --source-id <id> (files only \u2014 a URL derives its own id) \u2014 see `kane-cli context list --type source` for ids"),2;if(e.from&&a!==void 0)return P(n,"pass --from OR --apply <path>, not both \u2014 a stored plan names its own source"),2;let f=we(r,n);if(!f)return 2;if(e.mode!==void 0&&!xe.has(e.mode))return Pe(`--mode must be interactive | agent | ci | override, got '${e.mode}'`);let v=e.mode==="agent"||e.mode==="ci"||e.mode==="override";if(i&&!v&&!n.isTTY)return P(n,"refusing to apply without a TTY to confirm \u2014 pass --mode override|ci"),2;let s=!e.plan,c="override";if(e.from){let y=Ae(e,n.isTTY);if(typeof y=="object")return y.code==="MODE_USAGE"?Pe(y.error):(P(n,y.error),2);c=y}let _=c==="override"||c==="ci";if(i&&!e.from){let{makeReconcileDeps:y}=await import("./reconcile-deps-SUKZA2FL.js"),k=a===void 0?y({contextDir:f}).pending():null;if(k?.kind==="cards"){let $=e.mode??"interactive";return!n.isTTY||$!=="interactive"?(P(n,`a held changeset for ${k.source} awaits review (${k.count} change(s)) \u2014 resume in a terminal: kane-cli maintain reconcile --apply [HELD_REVIEW]`),2):(t.cardApplyMount??Ve)(f)}let l=e.mode??"interactive";return Le(f,a===void 0?void 0:q(r,a),l,n,t)}let u=Me(f,r,e.from,e.sourceId);if("error"in u)return P(n,u.error),2;if(!i){let{sessionsHoldingSource:y}=await import("./sessions-GIEXOCE4.js"),{holders:k,corrupt:l}=y(f,u.sourceId);if(l>0)return P(n,`cannot verify review holds \u2014 ${l} session file(s) unreadable; inspect with kane-cli context sessions list, clean with kane-cli context sessions clean, then retry [SESSIONS_UNREADABLE]`),2;if(k.length>0)return P(n,`session ${k[0]} holds item(s) for review pinned to ${u.sourceId} \u2014 finish that review first: kane-cli context extract --resume ${k[0]} [SOURCE_HELD]`),2}if(c==="interactive"&&!e.plan&&!i){let y=t.seams?.reingest??fe(f,u,n,t),k;try{k=await y(u.sourceId)}catch($){return P(n,$ instanceof Error?$.message:String($)),1}let l=k.status==="unchanged"?null:Re(f,u.sourceId);if(k.status!=="unchanged"&&!l)return n.out(`${u.sourceId} landed for the first time \u2014 extract it: kane-cli context extract --source ${u.sourceId}`),0;if(l){let x=await(t.chatMount??(async A=>{let{bindExtractInteractive:K}=await import("./extract-bind-EW7XUDLQ.js");return K(A)}))({mode:"interactive",posture:"reconcile",source:u.sourceId,changeContext:l});if(x===3){let{sessionsHoldingSource:A}=await import("./sessions-GIEXOCE4.js");if(A(f,u.sourceId).holders.length===0)return 0}return x}}let E="remoteUrl"in u?{remoteUrl:u.remoteUrl}:{filePath:u.filePath},m=await Se(f,u.sourceId,E,n,t,!!e.plan||c==="interactive",c==="interactive"&&!e.plan);if(!m)return 1;let d=t.runDesignForUc??ie,R=t.runDesignForUc??null,b=t.sessionScript;if(!m.changed){let y=await je(f,u.sourceId,n,t,c,d,!!e.plan);if(y!==null)return y;if(Y(n,m,null,!1,t.emitEvent),c==="agent"){let k=t.emitEvent??(()=>{});F(k,m,null),k({...L})}return 0}let h=T(f),p=null;if(h!=null?p=X(f,{version:2,source_id:m.source_id,..."remoteUrl"in E?{remote_url:E.remoteUrl}:{backing_path:E.filePath},head_pin:h,created:new Date().toISOString().replace(/[:.]/g,"-"),skipped_arms:m.skipped_arms,note:m.note,changeset:m.changeset,rows:m.rows,...m.held?{held:m.held}:{}}):P(n,"no chain head after extract \u2014 plan not stored"),c==="agent"){let y=t.emitEvent??(()=>{});if(!s)return F(y,m,p),y({...L}),0;let k=p?(l,$)=>O(p,l,$):void 0;return j(f,m,p,d,y,n,D(c),k)}if(!s)return p&&n.out(`plan stored: ${p}`),0;let g=m.changeset.filter(y=>y.kind==="ARCHIVE");if(c==="ci"&&g.length>0)return p&&n.out(`plan stored: ${p}`),P(n,V(g.length)),2;if(p){n.out(`plan stored: ${p}`);let y=p;return M(f,Ke(f,y)??m.rows,_,n,d,(k,l)=>O(y,k,l),m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}return M(f,m.rows,_,n,d,void 0,m.changeset,D(c),m.held,void 0,void 0,R,b,m.source_id,H(e.from,m.source_id))}function Ke(e,n){let t=N(e,n);return"error"in t?null:t.plan.rows}async function dn(e,n={},t,r=process.cwd()){if(e.mode==="agent"){let{makeHeadlessIO:i}=await import("./headless-io-66RG5NN5.js"),a=t?i("ndjson","reconcile",t):i("ndjson","reconcile"),o={out:a.out,err:v=>a.event({type:"error",message:v}),isTTY:!1,confirm:async()=>!1,ask:async()=>""},{runWithChannel:w}=await import("./run-channel-RGH4WIQX.js"),f=2;try{f=await w({event:v=>a.event(v)},()=>be(e,o,{...n,emitEvent:v=>a.event(v)},r))}catch(v){f=1,a.event({type:"error",message:v instanceof Error?v.message:String(v)})}return a.done(f)}return be(e,ke(),n,r)}export{Ae as a,Me as b,D as c,U as d,be as e,dn as f};
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as W}from"./chunk-MSGW4JDG.js";import{d as U,e as F}from"./chunk-4JOD47QI.js";import{a as H}from"./chunk-PH22FRN5.js";import{createHash as Y}from"crypto";import{access as Q,mkdir as S,mkdtemp as Z,readdir as O,readFile as y,rename as N,rm as v,writeFile as x}from"fs/promises";import{homedir as tt}from"os";import{arch as et,platform as st}from"process";import{dirname as C,isAbsolute as nt,join as l,relative as X,resolve as rt,sep as it}from"path";var q=1,ot={emulator:"emulator",simulator:"simulator"};function Pt(i){return ot[i.kind]??null}var j=class extends Error{constructor(s,e,n){super([`Managed mobile dependencies for ${s} are not installed.`,`- kaneai-mobile-deps ${s} ${e.bundleVersion}: ${e.url} (${_(e.bytes)})`,`Destination: ${n}`,`Run \`kane-cli doctor --target ${s} --install\` to download it.`].join(`
3
- `));this.deviceClass=s;this.name="DepsInstallRequiredError"}};function _(i){return i>=1024*1024?`${Math.ceil(i/(1024*1024))} MB`:`${i} bytes`}function at(i){let t=i/1048576;return t>=10?`${Math.round(t)} MB/s`:t>=1?`${t.toFixed(1)} MB/s`:`${Math.max(1,Math.round(i/1024))} KB/s`}function lt(i){let t=Math.max(1,Math.round(i));return t<60?`~${t}s left`:`~${Math.floor(t/60)}m ${t%60}s left`}var K=8*1024*1024,ct=8;function ut(i){if(!Number.isFinite(i)||i<2*K)return null;let t=Math.min(ct,Math.floor(i/K)),s=Math.ceil(i/t),e=[];for(let n=0;n<i;n+=s)e.push({start:n,end:Math.min(n+s,i)-1});return e}async function L(i,t){let s=i.body;if(!s||typeof s.getReader!="function"){let c=new Uint8Array(await i.arrayBuffer());return t?.(c.length),c}let e=s.getReader(),n=[],r=0;for(;;){let{done:c,value:h}=await e.read();if(c)break;h&&(n.push(h),r+=h.length,t?.(h.length))}let o=new Uint8Array(r),a=0;for(let c of n)o.set(c,a),a+=c.length;return o}var z=3,dt=3e4,k=class extends Error{};async function pt(i,t,s,e,n,r=dt){let o=new Uint8Array(s),a=0,c=new AbortController,h=null,b=!1;try{await Promise.all(e.map(async(f,M)=>{let P=0,V=d=>{P+=d,a+=d,n?.(a)},T=()=>{a=Math.max(0,a-P),P=0},R=null;for(let d=0;d<z;d+=1){if(c.signal.aborted)return;let u=new AbortController,m=()=>u.abort();c.signal.addEventListener("abort",m,{once:!0});let w=!1,g=null,$=()=>{g&&clearTimeout(g),g=setTimeout(()=>{w=!0,u.abort()},r)};try{$();let p=await i(t,{headers:{Range:`bytes=${f.start}-${f.end}`},signal:u.signal});if(typeof p.body?.getReader!="function"&&g&&(clearTimeout(g),g=null),!p.ok)throw new k(`Could not download ${t}: HTTP ${p.status}`);if(p.status!==206){b=!0,M===0?h=await L(p,I=>{$(),V(I)}):await(p.body?.cancel().catch(()=>{})??Promise.resolve());return}let D=f.end-f.start+1,E=await L(p,I=>{$(),V(I)});if(E.length!==D)throw new Error(`range ${f.start}-${f.end} returned ${E.length} bytes (expected ${D})`);o.set(E,f.start);return}catch(p){if(p instanceof k)throw p;if(c.signal.aborted)return;T(),R=w?new Error(`no data for ${Math.round(r/1e3)}s`):p instanceof Error?p:new Error(String(p))}finally{g&&clearTimeout(g),c.signal.removeEventListener("abort",m)}}throw new Error(`Could not download ${t}: range ${f.start}-${f.end} failed after ${z} attempts (${R?.message??"unknown error"}) \u2014 check your network and rerun \`kane-cli doctor --target <emulator|simulator> --install\`.`)}))}catch(f){throw c.abort(),f}return h||(b?null:o)}async function ht(i,t,s,e,n){let r=ut(s);if(r){let c=await pt(i,t,s,r,e,n?.stallMs);if(c)return c}let o=await i(t);if(!o.ok)throw new Error(`Could not download ${t}: HTTP ${o.status}`);let a=0;return L(o,e&&(c=>{a+=c,e(a)}))}function ft(i){return Y("sha256").update(i).digest("hex")}function mt(i,t){let s=X(i,t);return s!==""&&!s.startsWith(`..${it}`)&&s!==".."&&!nt(s)}async function A(i){try{return await Q(i),!0}catch{return!1}}function wt(){return{home:tt(),os:st,arch:et,cliVersion:H,nodeModuleVersion:process.versions.modules,fetch,resolveBundle:async i=>(await import("./deps-resolve-VSICFRWU.js")).controllerResolveBundle()(i),exec:U,now:()=>new Date,wait:F,processAlive:i=>{try{return process.kill(i,0),!0}catch{return!1}}}}var B=class extends Error{constructor(s,e,n){super(`No managed mobile dependencies are published for ${s} (kane-cli ${e}).
2
+ import{d as W}from"./chunk-MSGW4JDG.js";import{d as U,e as F}from"./chunk-4JOD47QI.js";import{a as H}from"./chunk-CCUGKBIH.js";import{createHash as Y}from"crypto";import{access as Q,mkdir as S,mkdtemp as Z,readdir as O,readFile as y,rename as N,rm as v,writeFile as x}from"fs/promises";import{homedir as tt}from"os";import{arch as et,platform as st}from"process";import{dirname as C,isAbsolute as nt,join as l,relative as X,resolve as rt,sep as it}from"path";var q=1,ot={emulator:"emulator",simulator:"simulator"};function Pt(i){return ot[i.kind]??null}var j=class extends Error{constructor(s,e,n){super([`Managed mobile dependencies for ${s} are not installed.`,`- kaneai-mobile-deps ${s} ${e.bundleVersion}: ${e.url} (${_(e.bytes)})`,`Destination: ${n}`,`Run \`kane-cli doctor --target ${s} --install\` to download it.`].join(`
3
+ `));this.deviceClass=s;this.name="DepsInstallRequiredError"}};function _(i){return i>=1024*1024?`${Math.ceil(i/(1024*1024))} MB`:`${i} bytes`}function at(i){let t=i/1048576;return t>=10?`${Math.round(t)} MB/s`:t>=1?`${t.toFixed(1)} MB/s`:`${Math.max(1,Math.round(i/1024))} KB/s`}function lt(i){let t=Math.max(1,Math.round(i));return t<60?`~${t}s left`:`~${Math.floor(t/60)}m ${t%60}s left`}var K=8*1024*1024,ct=8;function ut(i){if(!Number.isFinite(i)||i<2*K)return null;let t=Math.min(ct,Math.floor(i/K)),s=Math.ceil(i/t),e=[];for(let n=0;n<i;n+=s)e.push({start:n,end:Math.min(n+s,i)-1});return e}async function L(i,t){let s=i.body;if(!s||typeof s.getReader!="function"){let c=new Uint8Array(await i.arrayBuffer());return t?.(c.length),c}let e=s.getReader(),n=[],r=0;for(;;){let{done:c,value:h}=await e.read();if(c)break;h&&(n.push(h),r+=h.length,t?.(h.length))}let o=new Uint8Array(r),a=0;for(let c of n)o.set(c,a),a+=c.length;return o}var z=3,dt=3e4,k=class extends Error{};async function pt(i,t,s,e,n,r=dt){let o=new Uint8Array(s),a=0,c=new AbortController,h=null,b=!1;try{await Promise.all(e.map(async(f,M)=>{let P=0,V=d=>{P+=d,a+=d,n?.(a)},T=()=>{a=Math.max(0,a-P),P=0},R=null;for(let d=0;d<z;d+=1){if(c.signal.aborted)return;let u=new AbortController,m=()=>u.abort();c.signal.addEventListener("abort",m,{once:!0});let w=!1,g=null,$=()=>{g&&clearTimeout(g),g=setTimeout(()=>{w=!0,u.abort()},r)};try{$();let p=await i(t,{headers:{Range:`bytes=${f.start}-${f.end}`},signal:u.signal});if(typeof p.body?.getReader!="function"&&g&&(clearTimeout(g),g=null),!p.ok)throw new k(`Could not download ${t}: HTTP ${p.status}`);if(p.status!==206){b=!0,M===0?h=await L(p,I=>{$(),V(I)}):await(p.body?.cancel().catch(()=>{})??Promise.resolve());return}let D=f.end-f.start+1,E=await L(p,I=>{$(),V(I)});if(E.length!==D)throw new Error(`range ${f.start}-${f.end} returned ${E.length} bytes (expected ${D})`);o.set(E,f.start);return}catch(p){if(p instanceof k)throw p;if(c.signal.aborted)return;T(),R=w?new Error(`no data for ${Math.round(r/1e3)}s`):p instanceof Error?p:new Error(String(p))}finally{g&&clearTimeout(g),c.signal.removeEventListener("abort",m)}}throw new Error(`Could not download ${t}: range ${f.start}-${f.end} failed after ${z} attempts (${R?.message??"unknown error"}) \u2014 check your network and rerun \`kane-cli doctor --target <emulator|simulator> --install\`.`)}))}catch(f){throw c.abort(),f}return h||(b?null:o)}async function ht(i,t,s,e,n){let r=ut(s);if(r){let c=await pt(i,t,s,r,e,n?.stallMs);if(c)return c}let o=await i(t);if(!o.ok)throw new Error(`Could not download ${t}: HTTP ${o.status}`);let a=0;return L(o,e&&(c=>{a+=c,e(a)}))}function ft(i){return Y("sha256").update(i).digest("hex")}function mt(i,t){let s=X(i,t);return s!==""&&!s.startsWith(`..${it}`)&&s!==".."&&!nt(s)}async function A(i){try{return await Q(i),!0}catch{return!1}}function wt(){return{home:tt(),os:st,arch:et,cliVersion:H,nodeModuleVersion:process.versions.modules,fetch,resolveBundle:async i=>(await import("./deps-resolve-RPZORKUN.js")).controllerResolveBundle()(i),exec:U,now:()=>new Date,wait:F,processAlive:i=>{try{return process.kill(i,0),!0}catch{return!1}}}}var B=class extends Error{constructor(s,e,n){super(`No managed mobile dependencies are published for ${s} (kane-cli ${e}).
4
4
  This is a packaging gap, not something to install locally \u2014 report it, or pass --appium-url to use an Appium server you manage yourself.`);this.coordinate=s;this.cause=n;this.name="NoPublishedBundleError"}},J=class i{deps;constructor(t={}){this.deps={...wt(),...t}}mobileRoot(){return l(this.deps.home,".testmuai","kaneai","mobile")}depsRoot(){return l(this.mobileRoot(),"deps")}classRoot(t,s){return l(this.depsRoot(),s,t)}resolveCacheFile(){return l(this.depsRoot(),"resolve-cache.json")}resolveCacheKey(t){return`${this.deps.cliVersion}|${this.deps.os}-${this.deps.arch}-${t}`}static RESOLVE_CACHE_TTL_MS=1440*60*1e3;async readCachedWantedVersion(t){try{let e=JSON.parse(await y(this.resolveCacheFile(),"utf8"))[this.resolveCacheKey(t)];if(!e?.bundleVersion||!e.fetchedAt)return null;let n=this.deps.now().getTime()-new Date(e.fetchedAt).getTime();return n>=0&&n<i.RESOLVE_CACHE_TTL_MS?e.bundleVersion:null}catch{return null}}async writeResolveCache(t,s){try{let e={};try{e=JSON.parse(await y(this.resolveCacheFile(),"utf8"))}catch{}e[this.resolveCacheKey(t)]={bundleVersion:s,fetchedAt:this.deps.now().toISOString()},await S(this.depsRoot(),{recursive:!0}),await x(this.resolveCacheFile(),`${JSON.stringify(e,null,2)}
5
5
  `)}catch{}}async warmResolveCache(t){if(await this.readCachedWantedVersion(t)===null)try{await this.resolveOrExplain(t)}catch{}}paths(t,s){let e=this.classRoot(t,s);return{root:e,appium:l(e,"appium"),appiumHome:l(e,"appium-home"),platformTools:l(e,"platform-tools"),wdaDir:l(e,"wda","Build","Products","Debug-iphonesimulator"),iwdpBinDir:l(e,"bin"),installManifest:l(e,"install-manifest.json")}}async status(t,s){s||(s=await this.readCachedWantedVersion(t)??void 0);let e=[];try{e=await O(this.depsRoot())}catch{}s&&(e=e.filter(c=>c===s));let n=null;for(let c of e){let h=this.classRoot(t,c),b=null;try{b=JSON.parse(await y(l(h,"install-manifest.json"),"utf8"))}catch{continue}b.schemaVersion===q&&(!s&&b.cliVersion!==this.deps.cliVersion||(!n||b.installedAt>n.manifest.installedAt)&&(n={manifest:b,root:h}))}if(!n)return{class:t,installed:!1};let r=this.paths(t,n.manifest.bundleVersion),o=[l(r.appium,"node_modules","appium","index.js")];t==="emulator"&&o.push(l(r.platformTools,this.deps.os==="win32"?"adb.exe":"adb")),t==="simulator"&&o.push(l(r.wdaDir,"WebDriverAgentRunner-Runner.app"));for(let c of o)if(!await A(c))return{class:t,installed:!1,version:n.manifest.bundleVersion,root:n.root,corrupt:`a bundle component is missing from disk (${X(n.root,c)})`};let a=await this.postInstallDrifted(r);return{class:t,installed:!0,version:n.manifest.bundleVersion,root:n.root,...a?{needsRepair:a}:{}}}async postInstallDrifted(t){let s=l(t.appiumHome,"node_modules",".cache","appium","extensions.yaml");if(!await A(s))return!1;let e=await y(s,"utf8");for(let n of e.split(`
6
6
  `)){let r=/^\s*installPath:\s*(.+?)\s*$/.exec(n);if(r&&!r[1].startsWith(t.appiumHome))return!0}return!1}async environment(t){let s=await this.status(t);if(!s.installed||!s.version)return{dirs:[]};let e=this.paths(t,s.version),n=[],r={dirs:n,appiumHome:e.appiumHome};return t!=="simulator"&&(n.push(e.platformTools),r.platformToolsDir=e.platformTools),n.push(l(e.appium,"node_modules",".bin")),t==="simulator"&&(n.push(e.iwdpBinDir),r.wdaDir=e.wdaDir,r.wdaRoot=l(e.root,"wda"),r.iwdpBinDir=e.iwdpBinDir),r}async ensure(t,s){let e,n;try{e=await this.resolveOrExplain(t)}catch(a){n=a}let r=await this.status(t,e?.bundleVersion);if(r.installed&&!r.needsRepair)return e&&r.version&&await this.adoptInstall(t,r.version),r;if(!e)throw n;if(r.installed&&r.needsRepair&&r.version){let a=this.paths(t,r.version);return await this.withInstallLock(async()=>{await this.postInstall(a.root,a,s.onProgress)}),await this.adoptInstall(t,r.version),this.status(t,e.bundleVersion)}let o=e;if(!s.automatic&&!s.approved)throw new j(t,o,this.classRoot(t,o.bundleVersion));return await this.withInstallLock(async()=>{(await this.status(t,o.bundleVersion)).installed||await this.install(t,o,s.onProgress)}),this.status(t,o.bundleVersion)}async adoptInstall(t,s){try{let e=this.paths(t,s).installManifest,n=JSON.parse(await y(e,"utf8"));if(n.cliVersion===this.deps.cliVersion)return;n.cliVersion=this.deps.cliVersion;let r=l(C(e),`install-manifest-${process.pid}.json`);await x(r,`${JSON.stringify(n,null,2)}
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as t}from"./chunk-A3PGLDQY.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
2
+ import{a as t}from"./chunk-PB3GADUD.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{y as n}from"./chunk-PH22FRN5.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{x as n}from"./chunk-CCUGKBIH.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,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-JT7I6OST.js";import"./chunk-PH22FRN5.js";import"./chunk-UR6MHSHU.js";export{a as getEnvironment};
2
+ import{a}from"./chunk-WLOGO44E.js";import"./chunk-CCUGKBIH.js";import"./chunk-UR6MHSHU.js";export{a as getEnvironment};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a}from"./chunk-XHNPNYJP.js";import"./chunk-PH22FRN5.js";import"./chunk-UR6MHSHU.js";export{a as CredentialsManager};
2
+ import{a}from"./chunk-4UMQDH52.js";import"./chunk-CCUGKBIH.js";import"./chunk-UR6MHSHU.js";export{a as CredentialsManager};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-JCILRPOM.js";import"./chunk-MSGW4JDG.js";import"./chunk-4JOD47QI.js";import"./chunk-PH22FRN5.js";import"./chunk-UR6MHSHU.js";export{a as DEPS_INSTALL_SCHEMA_VERSION,i as DepsBundleResolver,c as DepsInstallRequiredError,h as NoPublishedBundleError,b as classOfTarget,g as downloadPayload,e as formatEta,d as formatRate,j as managedDeps,f as planRangeParts};
2
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-Z2T7E5HM.js";import"./chunk-MSGW4JDG.js";import"./chunk-4JOD47QI.js";import"./chunk-CCUGKBIH.js";import"./chunk-UR6MHSHU.js";export{a as DEPS_INSTALL_SCHEMA_VERSION,i as DepsBundleResolver,c as DepsInstallRequiredError,h as NoPublishedBundleError,b as classOfTarget,g as downloadPayload,e as formatEta,d as formatRate,j as managedDeps,f as planRangeParts};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import"./chunk-UR6MHSHU.js";var c="Mobile dependencies are resolved through your KaneAI account. Run `kane-cli login` first.";function d(l,o,e=process.env){return e.KANE_MOBILE_DEPS_BASE_URL||o(l)}async function u(){let[{CredentialsManager:l},{refreshOAuthToken:o},{getEnvironment:e},{ControllerClient:n}]=await Promise.all([import("./credentials-3CENDBPH.js"),import("./token-refresh-XKXPM6H3.js"),import("./config-SFM45WCV.js"),import("./controller-client-OB4WD2C4.js")]),s=new l;return{creds:s,refresh:r=>o({creds:s,profile:r.profile,env:r.env,credentials:r.credentials}),controllerBaseUrlFor:r=>d(r,t=>e(t).controllerBaseUrl),makeClient:(r,t)=>new n(r,t)}}function p(l){return async o=>{let e=l??await u(),n=e.creds.getActiveProfile();if(!n)throw new Error(c);let s=e.creds.getDefaultEnv(),r=e.controllerBaseUrlFor(s),t=e.creds.loadBasicAuth(n,s);if(t)return e.makeClient(r,{username:t.username,accessKey:t.access_key}).resolveMobileDepsBundle(o);let i=e.creds.loadCredentials(n,s);if(!i)throw new Error(c);try{await e.refresh({creds:e.creds,profile:n,env:s,credentials:i})}catch{}let a=(e.creds.loadCredentials(n,s)??i).access_token;if(typeof a!="string"||!a)throw new Error(c);return e.makeClient(r,a).resolveMobileDepsBundle(o)}}export{p as controllerResolveBundle,d as depsControllerBaseUrl};
2
+ import"./chunk-UR6MHSHU.js";var c="Mobile dependencies are resolved through your KaneAI account. Run `kane-cli login` first.";function d(l,o,e=process.env){return e.KANE_MOBILE_DEPS_BASE_URL||o(l)}async function u(){let[{CredentialsManager:l},{refreshOAuthToken:o},{getEnvironment:e},{ControllerClient:n}]=await Promise.all([import("./credentials-SO3DSQEM.js"),import("./token-refresh-PIUX5OFA.js"),import("./config-OKTAPFOT.js"),import("./controller-client-OB4WD2C4.js")]),s=new l;return{creds:s,refresh:r=>o({creds:s,profile:r.profile,env:r.env,credentials:r.credentials}),controllerBaseUrlFor:r=>d(r,t=>e(t).controllerBaseUrl),makeClient:(r,t)=>new n(r,t)}}function p(l){return async o=>{let e=l??await u(),n=e.creds.getActiveProfile();if(!n)throw new Error(c);let s=e.creds.getDefaultEnv(),r=e.controllerBaseUrlFor(s),t=e.creds.loadBasicAuth(n,s);if(t)return e.makeClient(r,{username:t.username,accessKey:t.access_key}).resolveMobileDepsBundle(o);let i=e.creds.loadCredentials(n,s);if(!i)throw new Error(c);try{await e.refresh({creds:e.creds,profile:n,env:s,credentials:i})}catch{}let a=(e.creds.loadCredentials(n,s)??i).access_token;if(typeof a!="string"||!a)throw new Error(c);return e.makeClient(r,a).resolveMobileDepsBundle(o)}}export{p as controllerResolveBundle,d as depsControllerBaseUrl};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,b,c,d}from"./chunk-BSCMUMSV.js";import"./chunk-2UIHS2FH.js";import"./chunk-YKTYVJBN.js";import"./chunk-X2FM67OM.js";import"./chunk-DNNZ353O.js";import"./chunk-Q2F5QB2W.js";import"./chunk-N2P4MI32.js";import"./chunk-NVGBE2DR.js";import"./chunk-TH47OOBV.js";import"./chunk-VAYBKR76.js";import"./chunk-CUM23TLF.js";import"./chunk-DUAXZYAD.js";import"./chunk-DBIBROYW.js";import"./chunk-WXHQYYD5.js";import"./chunk-IAHKTEET.js";import"./chunk-UD7KKHPW.js";import"./chunk-PH22FRN5.js";import"./chunk-UR6MHSHU.js";export{b as REMOTE_PROVIDERS,d as findProvider,a as landingReceipt,c as looksLikeUrl};
2
+ import{a,b,c,d}from"./chunk-VT2XNEOD.js";import"./chunk-2UIHS2FH.js";import"./chunk-YKTYVJBN.js";import"./chunk-X2FM67OM.js";import"./chunk-DNNZ353O.js";import"./chunk-Q2F5QB2W.js";import"./chunk-N2P4MI32.js";import"./chunk-NVGBE2DR.js";import"./chunk-TH47OOBV.js";import"./chunk-VAYBKR76.js";import"./chunk-CUM23TLF.js";import"./chunk-DUAXZYAD.js";import"./chunk-DBIBROYW.js";import"./chunk-WXHQYYD5.js";import"./chunk-IAHKTEET.js";import"./chunk-UD7KKHPW.js";import"./chunk-CCUGKBIH.js";import"./chunk-UR6MHSHU.js";export{b as REMOTE_PROVIDERS,d as findProvider,a as landingReceipt,c as looksLikeUrl};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a,b,c,d}from"./chunk-35EUIBYJ.js";import"./chunk-BG66IAO6.js";import"./chunk-MMBBQ4OZ.js";import"./chunk-Z2T7E5HM.js";import"./chunk-MSGW4JDG.js";import"./chunk-TZXXJWHA.js";import"./chunk-4JOD47QI.js";import"./chunk-RZ4F3BHX.js";import"./chunk-CCUGKBIH.js";import"./chunk-UR6MHSHU.js";export{d as doctorExitCode,c as doctorPreflightBlocked,b as renderDoctorText,a as runDoctor};