@testmuai/kane-cli 0.7.2 → 0.8.2

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 (230) hide show
  1. package/dist/ChatSurface-B3ULYDYC.js +8 -0
  2. package/dist/{ChromeProfilePicker-DGDWGCZD.js → ChromeProfilePicker-T77E7ZSC.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-SYCZXSME.js → CliFeedbackPrompt-FQ2XV5DZ.js} +1 -1
  4. package/dist/{CliUploadProgress-VDEAKXJY.js → CliUploadProgress-TZ55LONO.js} +1 -1
  5. package/dist/ConfigView-WWQMH36G.js +2 -0
  6. package/dist/EvidenceViewOffer-L5FVBQNK.js +2 -0
  7. package/dist/FolderPicker-6Z3CYSHF.js +2 -0
  8. package/dist/{HelpView-ON6BFGJM.js → HelpView-XXPCPJNF.js} +1 -1
  9. package/dist/{InfoBox-B23NZ6IG.js → InfoBox-SHBRHQX5.js} +1 -1
  10. package/dist/{LinksBox-TI26VFFH.js → LinksBox-ENNF7TDJ.js} +1 -1
  11. package/dist/{ProfilesView-CRO5AH3H.js → ProfilesView-CNF2FXF3.js} +1 -1
  12. package/dist/{ProjectPicker-3N7LJOXU.js → ProjectPicker-PVPLS642.js} +1 -1
  13. package/dist/{SaveSessionPrompt-UTOEC5AW.js → SaveSessionPrompt-4QP4GNGO.js} +1 -1
  14. package/dist/SingleShotApp-M3HNSUMZ.js +2 -0
  15. package/dist/{SummaryBox-JK64EKC2.js → SummaryBox-HYNINDNN.js} +1 -1
  16. package/dist/TestMdRunView-ISOVQ7YP.js +2 -0
  17. package/dist/{WhoamiView-6QSLPNF6.js → WhoamiView-NN2HOK6H.js} +1 -1
  18. package/dist/adbkit-apkreader-ORZBGCJQ.js +184 -0
  19. package/dist/app-client-ZCCNE3RV.js +2 -0
  20. package/dist/app-download-5UJMXPF3.js +2 -0
  21. package/dist/{auth-IKFVW3NX.js → auth-QKBTOWQX.js} +1 -1
  22. package/dist/{bind-KCUSVJXG.js → bind-LVGP5KHO.js} +3 -3
  23. package/dist/{bootstrap-NFYYRGGR.js → bootstrap-RUJBMB2P.js} +1 -1
  24. package/dist/bridge-QDPBIIOW.js +2 -0
  25. package/dist/{changelog-AAH2ZBYO.js → changelog-HBPBPR2O.js} +1 -1
  26. package/dist/{chat-committer-UUC6JTRJ.js → chat-committer-ZWWCLJFD.js} +1 -1
  27. package/dist/{chat-controller-T2FAI55V.js → chat-controller-R4THYYPU.js} +1 -1
  28. package/dist/chunk-2E3ZWGIK.js +12 -0
  29. package/dist/chunk-2KH2JUGL.js +13 -0
  30. package/dist/{chunk-VWKVUOXU.js → chunk-2TYCUPCN.js} +1 -1
  31. package/dist/{chunk-GYNTNKNB.js → chunk-2ZZDNPFN.js} +1 -1
  32. package/dist/chunk-3654GK6O.js +66 -0
  33. package/dist/{chunk-M6FKJKC6.js → chunk-3NHO5R4P.js} +3 -3
  34. package/dist/{chunk-SFII7HPP.js → chunk-4II6VDXG.js} +1 -1
  35. package/dist/chunk-4J6DQFPC.js +4 -0
  36. package/dist/chunk-4JOD47QI.js +2 -0
  37. package/dist/{chunk-5FJJJNJK.js → chunk-4U4OSOA4.js} +1 -1
  38. package/dist/{chunk-QIGPXYMF.js → chunk-56PAQAX5.js} +6 -6
  39. package/dist/chunk-5NIYYD7O.js +2 -0
  40. package/dist/chunk-5SNT2MK5.js +2 -0
  41. package/dist/chunk-6IA6QMPH.js +2 -0
  42. package/dist/chunk-6J5T5FEY.js +2 -0
  43. package/dist/chunk-6N726QLP.js +349 -0
  44. package/dist/chunk-7F2ZV46B.js +2 -0
  45. package/dist/{chunk-7OYZR6JA.js → chunk-7S3JZ6FQ.js} +1 -1
  46. package/dist/chunk-A2SQD2AY.js +4 -0
  47. package/dist/chunk-AJQT4IWZ.js +2 -0
  48. package/dist/chunk-AN2ZPHCE.js +2 -0
  49. package/dist/{chunk-7QJ75SYR.js → chunk-ATGRRKEV.js} +2 -2
  50. package/dist/chunk-AXTPNZPX.js +2 -0
  51. package/dist/{chunk-ZRASQ63J.js → chunk-BKVDAZEJ.js} +1 -1
  52. package/dist/{chunk-2WVKOZ6W.js → chunk-BPMSNGXQ.js} +1 -1
  53. package/dist/chunk-BRIEBB2U.js +2 -0
  54. package/dist/chunk-BSYX225I.js +2 -0
  55. package/dist/{chunk-B5RS2XZU.js → chunk-CAMO26QU.js} +3 -3
  56. package/dist/chunk-DPUV6OSP.js +2 -0
  57. package/dist/chunk-ECZMYPLJ.js +19 -0
  58. package/dist/chunk-EYOCNMUM.js +2 -0
  59. package/dist/{chunk-DZPGG4S6.js → chunk-FNS2EAA5.js} +2 -2
  60. package/dist/{chunk-VMM4LC4V.js → chunk-GNIFMQNK.js} +3 -3
  61. package/dist/chunk-GUVM6SZF.js +2 -0
  62. package/dist/{chunk-ZBOWFJB2.js → chunk-HFFPPCZO.js} +2 -2
  63. package/dist/chunk-HRZOFTV7.js +4 -0
  64. package/dist/chunk-HWH3UYD6.js +4 -0
  65. package/dist/{chunk-JKM2PUHI.js → chunk-I7RQS65W.js} +1 -1
  66. package/dist/chunk-IUEEFGEW.js +11 -0
  67. package/dist/{chunk-KWIK22R6.js → chunk-IV76ZXCY.js} +1 -1
  68. package/dist/{chunk-HYSFJSIG.js → chunk-IZ2FJYHG.js} +1 -1
  69. package/dist/{chunk-4NFCAGRK.js → chunk-J7KT44IC.js} +1 -1
  70. package/dist/{chunk-VOOPWFHW.js → chunk-JEDLXUO5.js} +1 -1
  71. package/dist/chunk-JGOZUAMC.js +2 -0
  72. package/dist/{chunk-4LTXE3IX.js → chunk-JHKM7W5X.js} +1 -1
  73. package/dist/chunk-JJN76EXE.js +2 -0
  74. package/dist/{chunk-EOLFTMWF.js → chunk-JUVQQP42.js} +1 -1
  75. package/dist/chunk-KKRNTSLL.js +6 -0
  76. package/dist/chunk-KRKGZ2ZW.js +47 -0
  77. package/dist/{chunk-YTHQNN2L.js → chunk-LDCLZR2U.js} +1 -1
  78. package/dist/chunk-LQQXPY5B.js +4 -0
  79. package/dist/{chunk-UC7MNPIN.js → chunk-LVCY5IYI.js} +1 -1
  80. package/dist/{chunk-O75ZHGJG.js → chunk-LVN6VHFN.js} +1 -1
  81. package/dist/chunk-MMBBQ4OZ.js +2 -0
  82. package/dist/chunk-MSGW4JDG.js +2 -0
  83. package/dist/{chunk-VLWMMOMF.js → chunk-MTIC65NK.js} +1 -1
  84. package/dist/chunk-NHBYZCSX.js +4 -0
  85. package/dist/chunk-NRUD56FY.js +7 -0
  86. package/dist/chunk-NXFAEDHV.js +26 -0
  87. package/dist/{chunk-OIYGGEUL.js → chunk-NXXJ56QA.js} +1 -1
  88. package/dist/{chunk-AXTGYOMK.js → chunk-O3AHFP3K.js} +1 -1
  89. package/dist/chunk-OAVPM6YJ.js +2 -0
  90. package/dist/{chunk-FBHRBFHP.js → chunk-OJTCIZDK.js} +1 -1
  91. package/dist/{chunk-JPWLGHPM.js → chunk-OOEPLMKA.js} +1 -1
  92. package/dist/{chunk-VT54ARGE.js → chunk-PXCMEI73.js} +1 -1
  93. package/dist/{chunk-APPYQZFK.js → chunk-R4UCBA5R.js} +1 -1
  94. package/dist/chunk-RKXHVP2Z.js +2 -0
  95. package/dist/{chunk-AJ56AMT6.js → chunk-RN4PKQFR.js} +1 -1
  96. package/dist/chunk-RUCSRS4C.js +5 -0
  97. package/dist/chunk-TAOHYWEO.js +2 -0
  98. package/dist/chunk-TZXXJWHA.js +2 -0
  99. package/dist/{chunk-VRLUNZAK.js → chunk-U5GHOGLM.js} +1 -1
  100. package/dist/chunk-UJZZDPDY.js +2 -0
  101. package/dist/{chunk-VHZ4S57N.js → chunk-UODLRQQ4.js} +1 -1
  102. package/dist/chunk-VK3NU742.js +21 -0
  103. package/dist/{chunk-FDIPQRX4.js → chunk-VPRNGWIY.js} +1 -1
  104. package/dist/{chunk-RDNFVZEB.js → chunk-WOEQDUJ6.js} +1 -1
  105. package/dist/chunk-WQPQNL4S.js +2 -0
  106. package/dist/{chunk-SL6PCVM2.js → chunk-WV27D55O.js} +1 -1
  107. package/dist/{chunk-2WFZIQ62.js → chunk-WVCH66YH.js} +1 -1
  108. package/dist/{chunk-PLOWZLG5.js → chunk-YCLG3T5E.js} +2 -2
  109. package/dist/chunk-YGMC3FGJ.js +26 -0
  110. package/dist/{chunk-5SXMV66P.js → chunk-YHYTCENI.js} +1 -1
  111. package/dist/{chunk-KQZA2QSC.js → chunk-YSSYT5F5.js} +1 -1
  112. package/dist/{chunk-OR6MCL6Z.js → chunk-YTDSQAYN.js} +1 -1
  113. package/dist/{chunk-XUS4WKDS.js → chunk-ZEDAPY7M.js} +1 -1
  114. package/dist/{chunk-F7ISS545.js → chunk-ZGBSGZZM.js} +1 -1
  115. package/dist/chunk-ZI6UIJUN.js +11 -0
  116. package/dist/{config-CWZV6XPT.js → config-RLDXM5ZH.js} +1 -1
  117. package/dist/{controller-client-RD2YEMAH.js → controller-client-OB4WD2C4.js} +1 -1
  118. package/dist/{cover-cmd-NWIRJY5Z.js → cover-cmd-HDZZWJXG.js} +1 -1
  119. package/dist/{credentials-YHTJGKEO.js → credentials-CALNKQMN.js} +1 -1
  120. package/dist/deps-bundle-GVHIMZ5E.js +2 -0
  121. package/dist/deps-resolve-T6P4EACP.js +2 -0
  122. package/dist/{dispatch-WVNXB7AD.js → dispatch-ECUEAMXS.js} +1 -1
  123. package/dist/doctor-SIBHJVGC.js +2 -0
  124. package/dist/docx-convert-JMUMT5C4.js +2 -0
  125. package/dist/evidence-ZVQHPELX.js +2 -0
  126. package/dist/evolve-cmd-JGCFTXWA.js +2 -0
  127. package/dist/exec-P2IKJRRR.js +2 -0
  128. package/dist/exit-manager-3FVBTNYR.js +2 -0
  129. package/dist/{explain-cmd-IZEHWZV5.js → explain-cmd-3GEKR7O5.js} +1 -1
  130. package/dist/{explain-cmd-75MCF2ZV.js → explain-cmd-EX24XKD6.js} +1 -1
  131. package/dist/extract-bind-EXW32RUY.js +10 -0
  132. package/dist/{extract-cmd-ZRYMJ6IC.js → extract-cmd-7IOLJJCL.js} +2 -2
  133. package/dist/gaps-cmd-WPCJPLGB.js +3 -0
  134. package/dist/{generate-headless-D6BISWDC.js → generate-headless-U4GTG234.js} +3 -3
  135. package/dist/host-7GZPBA74.js +2 -0
  136. package/dist/index.js +84 -67
  137. package/dist/ingest-cmd-YYNAKI2U.js +2 -0
  138. package/dist/interactive-bind-Y65XV4Y5.js +25 -0
  139. package/dist/{lifecycle-cmd-EQSFAZG6.js → lifecycle-cmd-HO5VL7AM.js} +1 -1
  140. package/dist/{list-cmd-IRJSUCM5.js → list-cmd-N4KMA34H.js} +1 -1
  141. package/dist/list-commands-3EROWJWV.js +2 -0
  142. package/dist/login-flow-TRINUSBB.js +2 -0
  143. package/dist/{maintenance-cmd-MVFA6H74.js → maintenance-cmd-6XSVO6FO.js} +1 -1
  144. package/dist/mobile-prompts-TP3ODM5M.js +2 -0
  145. package/dist/persist-recorded-session-EHYT3PVN.js +3 -0
  146. package/dist/pipeline-5GOS2KV2.js +2 -0
  147. package/dist/prepare-target-BUEOZVJV.js +2 -0
  148. package/dist/reconcile-cmd-TY3MWZL3.js +2 -0
  149. package/dist/reconcile-deps-6KTJHBMJ.js +4 -0
  150. package/dist/reconcile-engine-O7QEZVX6.js +2 -0
  151. package/dist/{recording-banner-76GCIPUN.js → recording-banner-BWWFOJCR.js} +1 -1
  152. package/dist/registry-KXEDLM6X.js +2 -0
  153. package/dist/{require-project-folder-ACRDP5ZB.js → require-project-folder-CXDRRWEQ.js} +1 -1
  154. package/dist/resolve-run-intent-PZXEQTHC.js +7 -0
  155. package/dist/{resolver-SRPCFW7P.js → resolver-FTU5KO7H.js} +1 -1
  156. package/dist/{review-cmd-L3V5UP5T.js → review-cmd-DQRKQUMG.js} +1 -1
  157. package/dist/run-CMFBSYWF.js +2 -0
  158. package/dist/run-WKHPVWUN.js +2 -0
  159. package/dist/{run-test-md-KEHSRMCM.js → run-test-md-7HGOZJSU.js} +3 -3
  160. package/dist/session-items-2ATN7VXG.js +2 -0
  161. package/dist/session-target-UWROGOCY.js +2 -0
  162. package/dist/{sessions-cmd-ZVYGSRJ3.js → sessions-cmd-ZZIZN2VB.js} +1 -1
  163. package/dist/{skill-installer-HBN3A35K.js → skill-installer-QNUDLGPD.js} +1 -1
  164. package/dist/spawner-DQZRJIE6.js +2 -0
  165. package/dist/{structured-answers-A43Q25CZ.js → structured-answers-5EY2AZN7.js} +1 -1
  166. package/dist/tcg-generate-XKSTMCOG.js +2 -0
  167. package/dist/testmd-actions-IFRW7NGG.js +2 -0
  168. package/dist/{tms-client-VD3B3SMU.js → tms-client-V3TR4QW3.js} +1 -1
  169. package/dist/token-refresh-FP6JFLXB.js +2 -0
  170. package/dist/types-6E2HTDKJ.js +2 -0
  171. package/dist/{validate-basic-ZGWPBYB6.js → validate-basic-3CNUDDH7.js} +1 -1
  172. package/dist/{verdicts-SCETLY5J.js → verdicts-NYCSBWUC.js} +1 -1
  173. package/dist/{version-check-CJWKDAXV.js → version-check-7TSAVA6V.js} +1 -1
  174. package/dist/{view-cmd-SOVM64L2.js → view-cmd-KPJTP4DI.js} +1 -1
  175. package/dist/walk-session-AINBHZKB.js +2 -0
  176. package/dist/{with-telemetry-E7QWPGL6.js → with-telemetry-3DL7ZEZL.js} +1 -1
  177. package/package.json +12 -6
  178. package/dist/ChatSurface-E7QKI4LA.js +0 -8
  179. package/dist/ConfigView-HPKRQXMC.js +0 -2
  180. package/dist/EvidenceViewOffer-F5YG54OC.js +0 -2
  181. package/dist/FolderPicker-4NSDXQY5.js +0 -2
  182. package/dist/SingleShotApp-Y3YDFQSD.js +0 -2
  183. package/dist/TestMdRunView-O6JTHV5W.js +0 -2
  184. package/dist/bridge-JSKEO4N3.js +0 -2
  185. package/dist/chunk-23VPUWBD.js +0 -23
  186. package/dist/chunk-2WRBTLFN.js +0 -13
  187. package/dist/chunk-53IBTIL3.js +0 -12
  188. package/dist/chunk-5WXGMXGA.js +0 -26
  189. package/dist/chunk-5ZQZOVWY.js +0 -4
  190. package/dist/chunk-74HTO7K3.js +0 -11
  191. package/dist/chunk-AECMF3T2.js +0 -8
  192. package/dist/chunk-AFBKGZFG.js +0 -2
  193. package/dist/chunk-BXYWX4J3.js +0 -2
  194. package/dist/chunk-C3T7TKAC.js +0 -349
  195. package/dist/chunk-DBKNJRJG.js +0 -2
  196. package/dist/chunk-H32GM5G4.js +0 -2
  197. package/dist/chunk-J5FBU425.js +0 -62
  198. package/dist/chunk-KCCSWEGA.js +0 -4
  199. package/dist/chunk-MK7JUOYV.js +0 -6
  200. package/dist/chunk-ORQNKZ2Z.js +0 -5
  201. package/dist/chunk-OUJQVBUT.js +0 -7
  202. package/dist/chunk-QOFZSHSC.js +0 -47
  203. package/dist/chunk-RKWJG3WW.js +0 -19
  204. package/dist/chunk-STVP2XHO.js +0 -2
  205. package/dist/chunk-VFII6C46.js +0 -2
  206. package/dist/chunk-VGFTNLQQ.js +0 -2
  207. package/dist/chunk-WAOCHXJ5.js +0 -2
  208. package/dist/chunk-ZUGCHQFC.js +0 -2
  209. package/dist/docx-convert-CHLJUTFH.js +0 -2
  210. package/dist/evidence-IVDNXWPL.js +0 -2
  211. package/dist/evolve-cmd-XBX4SX5H.js +0 -2
  212. package/dist/exit-manager-XZL4KIJU.js +0 -2
  213. package/dist/extract-bind-5OWELRME.js +0 -10
  214. package/dist/gaps-cmd-XBRXKXDL.js +0 -3
  215. package/dist/ingest-cmd-YTGOICTC.js +0 -2
  216. package/dist/interactive-bind-XSRD36MO.js +0 -25
  217. package/dist/list-commands-RCYHJ5Y3.js +0 -2
  218. package/dist/login-flow-PYAPYCPY.js +0 -2
  219. package/dist/persist-recorded-session-DTYCLXTQ.js +0 -3
  220. package/dist/pipeline-MXFOD6ES.js +0 -2
  221. package/dist/reconcile-cmd-EG6BOU3A.js +0 -2
  222. package/dist/reconcile-deps-HTT6IPHT.js +0 -4
  223. package/dist/reconcile-engine-JQNXALNY.js +0 -2
  224. package/dist/run-GMZCDRDD.js +0 -2
  225. package/dist/run-TFRWPGXP.js +0 -2
  226. package/dist/spawner-GC5CFAJ7.js +0 -2
  227. package/dist/tcg-generate-V7YFNC5O.js +0 -2
  228. package/dist/testmd-actions-MNDOO76O.js +0 -2
  229. package/dist/token-refresh-3UYMCYG3.js +0 -2
  230. package/dist/walk-session-YUYRULPY.js +0 -2
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as V,c as te}from"./chunk-JFAFKHDX.js";import{a as ne}from"./chunk-427OQS2N.js";import{a as k,b as ee}from"./chunk-6KPPGMO2.js";import{d as Z}from"./chunk-NVGBE2DR.js";import{A as X,f as Y,g as z,z as Q}from"./chunk-TH47OOBV.js";import"./chunk-VAYBKR76.js";import{a as j,b as F}from"./chunk-CUM23TLF.js";import{f as J,i as W}from"./chunk-DUAXZYAD.js";import"./chunk-DBIBROYW.js";import{e as L,f as A,g as P,h as x}from"./chunk-WXHQYYD5.js";import"./chunk-IAHKTEET.js";import"./chunk-UD7KKHPW.js";import"./chunk-UR6MHSHU.js";var de=new Set(["approve","edit","reject"]);function ye(m){let{contextDir:f,graph:s,ops:oe,by:l}=m,N=m.mintable??ne(),T=J(f);if(s.latestHash!==T)return{record:null,errors:[{code:"STALE_BASIS",detail:`graph opened at ${String(s.latestHash)} but chain head is ${String(T)} \u2014 re-open and retry`}]};let C=[],h=[],M=new Set;for(let e of oe){if(s.appliedEvents.has(e.eventId)||M.has(e.eventId)){C.push(e.eventId);continue}M.add(e.eventId),h.push(e)}if(h.length===0)return{record:null,errors:null,applied:[],skipped:C,minted:[],staleDelta:[]};let o=[],$=[],I=[],v=[],b=[],O=[],_=[...m.judgements??[]],D=[],q=new Map,B=new Set,G=[],E=new Set,se=new Set(N),H=new Set;for(let e of h){if(!de.has(e.kind))continue;let n=e.target,t=s.resolve(n)?.cid??n;H.has(t)&&o.push({code:"MULTIPLE_TERMINAL_OPS",detail:`${n} has more than one terminal op in this turn \u2014 normalize latest-wins first`}),H.add(t)}let S=(e,n,t)=>{let r=s.resolve(n);if(!r)return o.push({code:"UNKNOWN_NODE",detail:`${e}: ${n} names nothing in the graph`}),null;let p=s.tipOf(r.cid);return p!==t||s.superseded.has(t)?(o.push({code:"EXPECTED_CID_MOVED",detail:`${e}: ${n} moved or was archived since it was displayed`,data:{tip:p}}),null):t};for(let e of h)if(e.kind==="approve"){let n=S("approve",e.target,e.expectedCid);n&&v.push({id:n,kind:"review-item",resolution:"approved",edit:null,reason:null,by:l})}else if(e.kind==="reject"){let n=S("reject",e.target,e.expectedCid);if(!n)continue;if(v.push({id:n,kind:"review-item",resolution:"rejected",edit:null,reason:e.reason,by:l}),e.redirectTo!==void 0){let t=s.resolve(e.redirectTo);if(!t||t.superseded){o.push({code:"UNKNOWN_NODE",detail:`reject.redirectTo: ${e.redirectTo} is not a live node`});continue}b.push({kind:"node",old:n,new:t.cid,reason:e.reason,by:l})}}else if(e.kind==="edit"){let n=S("edit",e.target,e.expectedCid);if(!n)continue;let t=s.getNode(n);if(!t){o.push({code:"UNKNOWN_NODE",detail:`edit: ${e.target} node file unreadable`});continue}let r={...t.content};for(let[c,u]of Object.entries(e.edit))u!==void 0&&(r[c]=u);if(typeof r.title=="string"&&!r.title.trim()){o.push({code:"EMPTY_TITLE",detail:`edit: ${e.target} edited title is empty`});continue}let p=A(t.label,r);if(p.length>0){for(let c of p)o.push({code:c.code,detail:`edit ${e.target}: ${c.detail}`});continue}let d=j(t.label,r);if(d===n){v.push({id:n,kind:"review-item",resolution:"approved",edit:null,reason:null,by:l});continue}$.push({cid:d,label:t.label,content:r}),b.push({kind:"node",old:n,new:d,reason:e.reason??"edited in chat",by:l}),v.push({id:d,kind:"review-item",resolution:"edited",edit:{...e.edit},reason:null,by:l})}else if(e.kind==="enhance"){if(!S("enhance",e.target,e.expectedCid))continue;for(let t of e.edges){let r=s.nodeLabel.get(t.src)??"(unknown)",p=s.nodeLabel.get(t.dst)??"(unknown)";for(let i of x(t.type,r,p,t.props))o.push({code:i.code,detail:`enhance ${e.target}: ${i.detail}`});let d=F(t.type,t.src,t.dst,t.props);if(s.edgesFrom(t.src).some(i=>i.ecid===d)||I.some(i=>i.ecid===d))continue;let c=Y(s,t.type,t.src,t.dst,G);c&&o.push(c);let u=z(s,t.type,t.src,t.dst);u&&o.push(u);let a=P(t.type)?.cardinality;if(a==="one-live-per-src"||a==="one-live-per-src-and-dst"){let i=`${t.type}|${t.src}`;E.has(i)&&o.push({code:"CARDINALITY_VIOLATION",detail:`${t.type} from ${t.src}: two one-live edges in one turn`}),E.add(i)}if(a==="one-live-per-src-and-dst"){let i=`${t.type}|dst|${t.dst}`;E.has(i)&&o.push({code:"CARDINALITY_VIOLATION",detail:`${t.type} onto ${t.dst}: two one-live edges in one turn (strict 1:1)`}),E.add(i)}I.push({ecid:d,type:t.type,src:t.src,dst:t.dst,props:t.props}),G.push({src:t.src,dst:t.dst,type:t.type})}}else if(e.kind==="add"){if(!se.has(e.label)){o.push({code:"GATED_LABEL",detail:`add: ${e.label} is not mintable in v1 (gate: ${N.join("|")})`,data:{gate:[...N]}});continue}let n=s.heads.get(e.convSourceId),t=s.convChains.get(e.convSourceId);if(typeof n!="string"||!t){o.push({code:"CONV_SOURCE_MISSING",detail:`add: ${e.convSourceId} is not a live conversation source`});continue}let r=s.getNode(n)?.content?.blob,p=typeof r=="string"?Z(f,r)?.toString("utf8")??"":"",d=ee(p,e.cite.turn);if(d===null){o.push({code:"BAD_ANCHOR",detail:`add: ${k(e.cite.turn)} does not resolve in ${e.convSourceId}`});continue}if(!d.includes(e.cite.quote)){o.push({code:"QUOTE_MISMATCH",detail:`add: quote is not verbatim within ${k(e.cite.turn)}`});continue}let c={...e.content,derived:!0},u=A(e.label,c);if(u.length>0){for(let g of u)o.push({code:g.code,detail:`add: ${g.detail}`});continue}let a=j(e.label,c),i={source_id:e.convSourceId,source_cid:n,anchor:k(e.cite.turn),quote:e.cite.quote};for(let g of x(L.DERIVES,"source",e.label,i))o.push({code:g.code,detail:`add: ${g.detail}`});$.push({cid:a,label:e.label,content:c}),I.push({ecid:F("DERIVES",n,a,i),type:L.DERIVES,src:n,dst:a,props:i}),e.rationale&&_.push({about:a,rationale:e.rationale,by:l});let y=Q(e.label,g=>B.has(g),s.names.keys());y!==null&&(B.add(y),O.push({cid:a,slug:y,by:l})),D.push({cid:a,...y!==null?{slug:y}:{}}),q.set(e.eventId,a)}if(o.length)return{record:null,errors:o};let U=new Date().toISOString();for(let e of h){if(e.kind==="add"){let n=q.get(e.eventId);n&&V(f,{ts:U,command:"extract-chat",id:n,verdict:"add",polarity:"preference",tag:e.label,by:l,event_id:e.eventId,target:n});continue}for(let n of te(e,{ts:U,command:"extract-chat",by:l}))V(f,n)}let K=h.map(e=>e.eventId).sort(),ie=W(f,{ts:new Date().toISOString(),proposal_id:null,nodes:$,edges:I,review:v,supersessions:b,...O.length>0?{names:O}:{},..._.length>0?{judgements:_}:{},event_ids:K,...m.sid?{sid:m.sid}:{},source_head_moves:{}},{expectPrev:T}),R=X(f),w=new Set;for(let e of b)if(e.kind==="node"){w.add(e.old);for(let n of R.edgesInto(e.old))w.add(n.src)}for(let e of D)w.add(e.cid);let re=[...w].map(e=>({cid:e,state:R.stale(R.tipOf(e))})).filter(e=>e.state!=="fresh");return{record:ie.record,errors:null,applied:K,skipped:C,minted:D,staleDelta:re}}export{ye as commitChatTurn};
2
+ import{a as V,c as te}from"./chunk-JFAFKHDX.js";import{a as k,b as ee}from"./chunk-6KPPGMO2.js";import{a as ne}from"./chunk-427OQS2N.js";import{d as Z}from"./chunk-NVGBE2DR.js";import{A as X,f as Y,g as z,z as Q}from"./chunk-TH47OOBV.js";import"./chunk-VAYBKR76.js";import{a as j,b as F}from"./chunk-CUM23TLF.js";import{f as J,i as W}from"./chunk-DUAXZYAD.js";import"./chunk-DBIBROYW.js";import{e as L,f as A,g as P,h as x}from"./chunk-WXHQYYD5.js";import"./chunk-IAHKTEET.js";import"./chunk-UD7KKHPW.js";import"./chunk-UR6MHSHU.js";var de=new Set(["approve","edit","reject"]);function ye(m){let{contextDir:f,graph:s,ops:oe,by:l}=m,N=m.mintable??ne(),T=J(f);if(s.latestHash!==T)return{record:null,errors:[{code:"STALE_BASIS",detail:`graph opened at ${String(s.latestHash)} but chain head is ${String(T)} \u2014 re-open and retry`}]};let C=[],h=[],M=new Set;for(let e of oe){if(s.appliedEvents.has(e.eventId)||M.has(e.eventId)){C.push(e.eventId);continue}M.add(e.eventId),h.push(e)}if(h.length===0)return{record:null,errors:null,applied:[],skipped:C,minted:[],staleDelta:[]};let o=[],$=[],I=[],v=[],b=[],O=[],_=[...m.judgements??[]],D=[],q=new Map,B=new Set,G=[],E=new Set,se=new Set(N),H=new Set;for(let e of h){if(!de.has(e.kind))continue;let n=e.target,t=s.resolve(n)?.cid??n;H.has(t)&&o.push({code:"MULTIPLE_TERMINAL_OPS",detail:`${n} has more than one terminal op in this turn \u2014 normalize latest-wins first`}),H.add(t)}let S=(e,n,t)=>{let r=s.resolve(n);if(!r)return o.push({code:"UNKNOWN_NODE",detail:`${e}: ${n} names nothing in the graph`}),null;let p=s.tipOf(r.cid);return p!==t||s.superseded.has(t)?(o.push({code:"EXPECTED_CID_MOVED",detail:`${e}: ${n} moved or was archived since it was displayed`,data:{tip:p}}),null):t};for(let e of h)if(e.kind==="approve"){let n=S("approve",e.target,e.expectedCid);n&&v.push({id:n,kind:"review-item",resolution:"approved",edit:null,reason:null,by:l})}else if(e.kind==="reject"){let n=S("reject",e.target,e.expectedCid);if(!n)continue;if(v.push({id:n,kind:"review-item",resolution:"rejected",edit:null,reason:e.reason,by:l}),e.redirectTo!==void 0){let t=s.resolve(e.redirectTo);if(!t||t.superseded){o.push({code:"UNKNOWN_NODE",detail:`reject.redirectTo: ${e.redirectTo} is not a live node`});continue}b.push({kind:"node",old:n,new:t.cid,reason:e.reason,by:l})}}else if(e.kind==="edit"){let n=S("edit",e.target,e.expectedCid);if(!n)continue;let t=s.getNode(n);if(!t){o.push({code:"UNKNOWN_NODE",detail:`edit: ${e.target} node file unreadable`});continue}let r={...t.content};for(let[c,u]of Object.entries(e.edit))u!==void 0&&(r[c]=u);if(typeof r.title=="string"&&!r.title.trim()){o.push({code:"EMPTY_TITLE",detail:`edit: ${e.target} edited title is empty`});continue}let p=A(t.label,r);if(p.length>0){for(let c of p)o.push({code:c.code,detail:`edit ${e.target}: ${c.detail}`});continue}let d=j(t.label,r);if(d===n){v.push({id:n,kind:"review-item",resolution:"approved",edit:null,reason:null,by:l});continue}$.push({cid:d,label:t.label,content:r}),b.push({kind:"node",old:n,new:d,reason:e.reason??"edited in chat",by:l}),v.push({id:d,kind:"review-item",resolution:"edited",edit:{...e.edit},reason:null,by:l})}else if(e.kind==="enhance"){if(!S("enhance",e.target,e.expectedCid))continue;for(let t of e.edges){let r=s.nodeLabel.get(t.src)??"(unknown)",p=s.nodeLabel.get(t.dst)??"(unknown)";for(let i of x(t.type,r,p,t.props))o.push({code:i.code,detail:`enhance ${e.target}: ${i.detail}`});let d=F(t.type,t.src,t.dst,t.props);if(s.edgesFrom(t.src).some(i=>i.ecid===d)||I.some(i=>i.ecid===d))continue;let c=Y(s,t.type,t.src,t.dst,G);c&&o.push(c);let u=z(s,t.type,t.src,t.dst);u&&o.push(u);let a=P(t.type)?.cardinality;if(a==="one-live-per-src"||a==="one-live-per-src-and-dst"){let i=`${t.type}|${t.src}`;E.has(i)&&o.push({code:"CARDINALITY_VIOLATION",detail:`${t.type} from ${t.src}: two one-live edges in one turn`}),E.add(i)}if(a==="one-live-per-src-and-dst"){let i=`${t.type}|dst|${t.dst}`;E.has(i)&&o.push({code:"CARDINALITY_VIOLATION",detail:`${t.type} onto ${t.dst}: two one-live edges in one turn (strict 1:1)`}),E.add(i)}I.push({ecid:d,type:t.type,src:t.src,dst:t.dst,props:t.props}),G.push({src:t.src,dst:t.dst,type:t.type})}}else if(e.kind==="add"){if(!se.has(e.label)){o.push({code:"GATED_LABEL",detail:`add: ${e.label} is not mintable in v1 (gate: ${N.join("|")})`,data:{gate:[...N]}});continue}let n=s.heads.get(e.convSourceId),t=s.convChains.get(e.convSourceId);if(typeof n!="string"||!t){o.push({code:"CONV_SOURCE_MISSING",detail:`add: ${e.convSourceId} is not a live conversation source`});continue}let r=s.getNode(n)?.content?.blob,p=typeof r=="string"?Z(f,r)?.toString("utf8")??"":"",d=ee(p,e.cite.turn);if(d===null){o.push({code:"BAD_ANCHOR",detail:`add: ${k(e.cite.turn)} does not resolve in ${e.convSourceId}`});continue}if(!d.includes(e.cite.quote)){o.push({code:"QUOTE_MISMATCH",detail:`add: quote is not verbatim within ${k(e.cite.turn)}`});continue}let c={...e.content,derived:!0},u=A(e.label,c);if(u.length>0){for(let g of u)o.push({code:g.code,detail:`add: ${g.detail}`});continue}let a=j(e.label,c),i={source_id:e.convSourceId,source_cid:n,anchor:k(e.cite.turn),quote:e.cite.quote};for(let g of x(L.DERIVES,"source",e.label,i))o.push({code:g.code,detail:`add: ${g.detail}`});$.push({cid:a,label:e.label,content:c}),I.push({ecid:F("DERIVES",n,a,i),type:L.DERIVES,src:n,dst:a,props:i}),e.rationale&&_.push({about:a,rationale:e.rationale,by:l});let y=Q(e.label,g=>B.has(g),s.names.keys());y!==null&&(B.add(y),O.push({cid:a,slug:y,by:l})),D.push({cid:a,...y!==null?{slug:y}:{}}),q.set(e.eventId,a)}if(o.length)return{record:null,errors:o};let U=new Date().toISOString();for(let e of h){if(e.kind==="add"){let n=q.get(e.eventId);n&&V(f,{ts:U,command:"extract-chat",id:n,verdict:"add",polarity:"preference",tag:e.label,by:l,event_id:e.eventId,target:n});continue}for(let n of te(e,{ts:U,command:"extract-chat",by:l}))V(f,n)}let K=h.map(e=>e.eventId).sort(),ie=W(f,{ts:new Date().toISOString(),proposal_id:null,nodes:$,edges:I,review:v,supersessions:b,...O.length>0?{names:O}:{},..._.length>0?{judgements:_}:{},event_ids:K,...m.sid?{sid:m.sid}:{},source_head_moves:{}},{expectPrev:T}),R=X(f),w=new Set;for(let e of b)if(e.kind==="node"){w.add(e.old);for(let n of R.edgesInto(e.old))w.add(n.src)}for(let e of D)w.add(e.cid);let re=[...w].map(e=>({cid:e,state:R.stale(R.tipOf(e))})).filter(e=>e.state!=="fresh");return{record:ie.record,errors:null,applied:K,skipped:C,minted:D,staleDelta:re}}export{ye as commitChatTurn};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a,b,c}from"./chunk-KCCSWEGA.js";import"./chunk-VGFTNLQQ.js";import"./chunk-L2TV4G56.js";import"./chunk-6KPPGMO2.js";import"./chunk-NVGBE2DR.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-UR6MHSHU.js";export{c as makeChatController,b as questionStub,a as recommendationPicks};
2
+ import{a,b,c}from"./chunk-LQQXPY5B.js";import"./chunk-AXTPNZPX.js";import"./chunk-L2TV4G56.js";import"./chunk-6KPPGMO2.js";import"./chunk-NVGBE2DR.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-UR6MHSHU.js";export{c as makeChatController,b as questionStub,a as recommendationPicks};
@@ -0,0 +1,12 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as jt}from"./chunk-ZMNJBUAO.js";import{f as tr}from"./chunk-W5TTF7GB.js";import{a as Bt}from"./chunk-I7TIGB7K.js";import{a as te,c as Yt,e as Zt,f as qe,g as Qt,h as nr}from"./chunk-RN4PKQFR.js";import{a as Xt,b as rr,c as sr,d as ir,e as dt,f as or}from"./chunk-ZGBSGZZM.js";import{a as ke,b as qt,c as Gt,d as Lt,e as Vt}from"./chunk-7S3JZ6FQ.js";import{a as zt}from"./chunk-L2TV4G56.js";import{a as Kt,b as Jt}from"./chunk-JFAFKHDX.js";import{c as Wt}from"./chunk-6KPPGMO2.js";import{a as Nt,e as Ht}from"./chunk-GFKCTYCA.js";import{b as Ft}from"./chunk-YKTYVJBN.js";import{a as er}from"./chunk-IMR64OCZ.js";import{e as Ut}from"./chunk-WQPQNL4S.js";import{a as Fe}from"./chunk-4U4OSOA4.js";import{d as Mt}from"./chunk-W4B5LOEX.js";import{a as $e,b as ct}from"./chunk-DNNZ353O.js";import{a as Se}from"./chunk-NVGBE2DR.js";import{b as nt}from"./chunk-IDX3TOPY.js";import{A as ee,k as be,o as Be}from"./chunk-TH47OOBV.js";import{f as It}from"./chunk-DUAXZYAD.js";import{e as at}from"./chunk-DBIBROYW.js";import{d as me}from"./chunk-WXHQYYD5.js";import{b as Ot}from"./chunk-IAHKTEET.js";import{a as At}from"./chunk-5EOX4MEY.js";import{appendFileSync as wr,mkdirSync as ut,rmdirSync as br,writeFileSync as lt}from"fs";import{dirname as mr,extname as Sr,join as ce}from"path";var X=class extends Error{code;constructor(e,a){super(`${e}: ${a}`),this.name="ProposalAdapterError",this.code=e}};function cr(r){return r.version===2}var ar=8;function vr(r){let e=/^extract@(\d+)$/.exec(r??"");return e?Number.parseInt(e[1],10):null}var yr=r=>typeof r=="object"&&r!==null&&"op"in r;function Ge(r,e,a){return{anchor:r.anchor,quote:r.quote,...a||r.source_id!==e?{source_id:r.source_id}:{}}}function dr(r,e,a={}){let m=vr(a.templateVersion),x=m!==null&&m>=5,_=m!==null&&m<5,y=r.archived!=null&&r.archived.length>0&&m!==null&&m<5;if(y&&a.warn?.(`dropped ${r.archived.length} archive op(s): the bound extract template @${m} never described archiving \u2014 nothing was archived; the use-cases still land`),!x&&r.read_basis.length!==1)throw new X("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${r.read_basis.length}`);if(r.read_basis.length===0)throw new X("READ_BASIS_COUNT","read_basis must not be empty");let v=r.read_basis[0],h=r.read_basis.length>1,$=r.use_cases.map(i=>{if(_&&i.cite.length!==1)throw new X("CITE_COUNT",`${i.temp_ref}: cite must have exactly 1 element, got ${i.cite.length}`);if(i.cite.length<1||i.cite.length>ar)throw new X("CITE_COUNT",`${i.temp_ref}: 1..${ar} cites allowed, got ${i.cite.length}`);let M=(f,re)=>{if(!x&&f!==v.source_id)throw new X("SOURCE_MISMATCH",`${re}: cite source ${f} != read_basis source ${v.source_id} (single-source)`)};M(i.cite[0].source_id,i.temp_ref);let P=i.cite.map(f=>(M(f.source_id,i.temp_ref),Ge(f,v.source_id,x&&(h||f.source_id!==v.source_id)))),l=(i.updated?.criteria??[]).some(yr);if(!x&&l)throw new X("CRITERIA_OPS_UNSUPPORTED",`${i.temp_ref}: op-union updated.criteria (keep/set/remove) needs an extract@5+ binding \u2014 this session is bound to ${a.templateVersion??"an unversioned template"}`);return{temp_ref:i.temp_ref,title:i.title,...i.description!==void 0?{description:i.description}:{},...i.summary!==void 0?{summary:i.summary}:{},...i.actors!==void 0?{actors:i.actors}:{},...i.value!==void 0?{value:i.value}:{},risk:i.risk,cite:P[0],...P.length>1?{cites:P}:{},...i.criteria!=null&&i.criteria.length>0?{criteria:i.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{},depends_on_hint:i.depends_on_hint,matches_existing:i.matches_existing,...i.conflicts_with!=null?{conflicts_with:i.conflicts_with}:{},...i.changed?{changed:!0}:{},...i.updated!=null?{updated:{...i.updated.title!=null?{title:i.updated.title}:{},...i.updated.description!=null?{description:i.updated.description}:{},...i.updated.summary!=null?{summary:i.updated.summary}:{},...i.updated.actors!=null?{actors:i.updated.actors}:{},...i.updated.value!=null?{value:i.updated.value}:{},...i.updated.risk!=null?{risk:i.updated.risk}:{},...i.updated.criteria!=null?{criteria:l?i.updated.criteria.map(f=>f.op==="set"?{op:"set",text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}:f.op==="keep"?{op:"keep",ref:f.ref,text:f.text}:{op:"remove",ref:f.ref,text:f.text,reason:f.reason}):i.updated.criteria.map((f,re)=>(M(f.cite.source_id,`${i.temp_ref}.updated.criteria[${re}]`),{text:f.text,cite:Ge(f.cite,v.source_id,x&&f.cite.source_id!==v.source_id)}))}:{}}}:{},...i.change_note!=null?{change_note:i.change_note}:{}}});return{version:1,read_basis:e,source:{source_id:v.source_id,source_cid:v.source_cid},use_cases:$,...h?{sources:r.read_basis.map(i=>({source_id:i.source_id,source_cid:i.source_cid}))}:{},...r.extraction_of!=null&&r.extraction_of.length>0?{extraction_claims:r.extraction_of.map(i=>({source_id:i.source_id,completeness:i.completeness}))}:{},...r.archived!=null&&r.archived.length>0&&!y?{archived:r.archived.map(i=>({target:i.target,reason:i.reason,basis:i.basis}))}:{}}}function ur(r){let{contextDir:e,graph:a}=r,m=r.maxDigestBytes??4096,x={},_=[];for(let[h,$]of a.heads){if(x[h]=$,typeof $!="string")continue;let i=a.mediaOf($),M=a.getNode($)?.content?.blob;if(typeof M=="string")if(i.format==="image")_.push({source_id:h,cid:$,format:"image",blobRef:{path:Se(e,M),cid:M}});else{let P=$e(e,a,$)?.toString("utf8")??"";_.push({source_id:h,cid:$,format:i.format,text:P})}}_.sort((h,$)=>h.source_id<$.source_id?-1:1);let y=[];for(let h of a.byLabel(me.STYLENOTE).sort(($,i)=>$.cid<i.cid?-1:1))a.superseded.has(h.cid)||y.push(`\u2022 ${String(h.content.statement)} [${String(h.content.learned_from_kind)}]`);let v="";for(let h of y){if(Buffer.byteLength(v+h+`
3
+ `,"utf8")>m)break;v+=h+`
4
+ `}return{read_basis:x,sources:_,styleNoteDigest:v}}function lr(r,e){let a=ur({contextDir:r,graph:e}).styleNoteDigest;return a.length>0?a:void 0}function mt(r,e,a,m,x){let _=null,y=()=>_??=x&&Object.keys(x).length>0?Promise.resolve(x):Ut().catch(()=>({}));return{contextDir:r,rootSid:e,locks:at(r,e),probe:m??Bt(r,{resolveAlias:async v=>qt(v,{env:process.env,auth:await y()}),embed:async(v,h)=>Gt(v,h,{env:process.env,auth:await y()}),readVector:(v,h)=>Lt(r,v,h),writeVector:(v,h,$)=>Vt(r,v,h,$)}),...a?.length?{reservedEventIds:a}:{}}}function ht(r,e){let a=[],m=[];for(let x of r.use_cases){let _=x.matches_existing;_?.cid&&e.hasNode(_.cid)?a.push({ref:_.cid,expectedTip:e.tipOf(_.cid)}):m.push({tempRef:x.temp_ref,title:String(x.title??""),probeText:String(x.title??"")})}return{verb:"extract",ucTargets:a,newBuCandidates:m,sourcePins:[{source_id:r.source.source_id,source_cid:r.source.source_cid}],readBasis:r.read_basis??null}}function $r(r,e){let a=(r.images??[]).filter(m=>m.delivery==="selected");if(a.length!==0)return a.map(m=>({ref:m.ref,...m.page!==void 0?{page:m.page}:{},...m.loc!==void 0?{loc:m.loc}:{},media_type:m.media_type,blob_ref:{path:Se(e,m.blob),cid:m.blob}}))}function kr(r){return r.length>8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>12&&r.toString("ascii",0,4)==="RIFF"&&r.toString("ascii",8,12)==="WEBP"?"image/webp":null}function Le(r){return r.toISOString().replace(/[-:]/g,"").slice(0,15)}function hr(r){return r.startsWith("su-conv-")?`conv-${Ot(Buffer.from(r,"utf8")).slice(0,8)}`:r}function pr(r){return r.source_id.startsWith("su-conv-")?"the conversation":r.source_id}function Rr(r,e,a){return`reading ${pr(r)}${a>1?` (source ${e} of ${a})`:""}`}function Re(r){return r.toLowerCase().trim().replace(/\s+/g," ")}function gr(r,e){let a=new Map,m=new Map,x=new Map;for(let{cid:y,content:v}of e.byLabel(me.USECASE)){if(e.superseded.has(y))continue;(e.trust.get(y)==="archived"?x:m).set(Re(String(v.title??"")),y)}let _=y=>e.trust.get(y)==="archived"?{cid:y,archived:!0,reason:e.archivedReason.get(y)}:{cid:y};for(let y of r.use_cases){if(y.matches_existing){let $=y.matches_existing.cid;if(e.superseded.has($)){let i=e.tipOf($);$=e.superseded.has(i)?null:i}if($!==null){a.set(y.temp_ref,_($));continue}}let v=m.get(Re(y.title));if(v){a.set(y.temp_ref,{cid:v});continue}let h=x.get(Re(y.title));h&&a.set(y.temp_ref,_(h))}return a}var fr=/^(\S+)\.criteria\[(\d+)\]/;function Cr(r,e,a){if(e.length===0||!e.every(x=>fr.test(x.detail)))return!1;let m=new Map;for(let x of e){let _=fr.exec(x.detail),y=m.get(_[1])??new Set;y.add(Number(_[2])),m.set(_[1],y)}for(let x of r.use_cases){let _=m.get(x.temp_ref);_?.size&&(x.criteria=(x.criteria??[]).filter((y,v)=>!_.has(v)),a(`${x.temp_ref}: dropped ${_.size} criteria with unverifiable cites \u2014 committed without them (criteria are hints, not oracles)`))}return!0}async function gt(r,e,a,m,x=()=>{},_,y){let v=(h,$)=>x(h,$,r.session_id);return Zt(r,e,a,m,x,{async onProposalEvent(h){let $=h,i=null,M=null;if(cr($))try{i=dr($,r.read_basis,{templateVersion:y?.()??null,warn:P=>{e.out(`warning: ${P}`),v("adapter",{warn:P})}}),v("adapter",{ok:!0,use_cases:i.use_cases.length})}catch(P){M=P instanceof X?P.message:String(P),v("adapter",{ok:!1,error:M})}else i=$;return i&&i.use_cases.length===0&&(e.out("warning: the agent proposed ZERO use-cases for this source"),e.emit?.({type:"warning",code:"ZERO_USE_CASES",message:"the agent proposed ZERO use-cases for this source"})),i&&_&&await _(i),{proposal:i,error:M}}})}var Dr=new Set(["agent","ci","override"]);async function Ss(r,e){let a=`ext-${Le(e.now?.()??new Date)}-lk${Math.random().toString(36).slice(2,8)}`,x=at(e.contextDir,a,e.now?{now:e.now}:void 0).tryAcquire([{kind:"extract"}],{hold:"session",verb:"extract"});if("contended"in x){let _=x.contended.holder,y=`another extraction is running on this context${_?` (pid ${_.pid})`:""} \u2014 retry when it finishes`;return e.out(y),e.emit?.({type:"error",message:y,code:"EXTRACT_LOCKED"}),2}try{return await Er(r,e)}finally{x.release()}}async function Er(r,e){let a=r.mode??"interactive";if(r.posture==="reconcile"){if(r.trust==="hold"){let o="error: --trust hold has no meaning here \u2014 a reconcile IS the review; drop the flag";return e.out(`${o} [TRUST_USAGE]`),e.emit?.({type:"error",message:o,code:"TRUST_USAGE"}),2}if(!r.source||!r.changeContext){let o="reconcile posture needs a pinned source and its change context \u2014 internal wiring fault";return e.out(`error: ${o}`),e.emit?.({type:"error",message:o,code:"POSTURE_USAGE"}),2}if(a==="ci"){let o="reconcile posture is not available under --mode ci \u2014 a held changeset needs a durable session; use --mode agent";return e.out(`error: ${o}`),e.emit?.({type:"error",message:o,code:"POSTURE_USAGE"}),2}}if(r.trust==="hold"&&a==="interactive")return e.out("error: --trust hold only applies to headless runs \u2014 in interactive chat you review items in-session anyway; use --mode agent to hold everything for review"),e.emit?.({type:"error",message:"error: --trust hold only applies to headless runs \u2014 use --mode agent",code:"TRUST_USAGE"}),2;if(a==="interactive"){if(!e.isTTY)return e.out("extract: --mode interactive needs a TTY (use --mode agent|ci|override headless)"),2}else if(!Dr.has(a))return e.out(`extract: unknown mode "${a}" \u2014 interactive | agent | ci | override`),2;if(r.trust!==void 0){if(a==="ci")return e.out("error: --trust is not available under --mode ci (ci is fail-closed \u2014 no trust dials)"),e.emit?.({type:"error",message:"error: --trust is not available under --mode ci",code:"TRUST_UNDER_CI"}),2;if(r.trust!=="auto"&&r.trust!=="hold")return e.out(`error: --trust must be auto | hold, got '${r.trust}'`),e.emit?.({type:"error",message:`error: --trust must be auto | hold, got '${r.trust}'`,code:"TRUST_USAGE"}),2}let m=e.telemetry?.enabled?e.telemetry:void 0,x=Le(e.now?.()??new Date),_=m?At(m.ids.context_instance_id??null,"extract",m.ids.session_id):ce(e.contextDir,"logs",`extract-${x}.log`);ut(mr(_),{recursive:!0});let y=`run-${x}-${Math.random().toString(36).slice(2,8)}`,v=o=>o==="error"||o==="failed_proposal"?"error":o==="repair_respawn"?"warn":"info",h=(o,u,s)=>{try{wr(_,JSON.stringify({ts:new Date().toISOString(),level:v(o),run_id:y,...m?{user_session_id:m.ids.session_id}:{},...s?{session_id:s}:{},kind:o,data:u})+`
5
+ `)}catch{}m?.wireTrace(o,u,s)};{let o=e.out;e.out=u=>{h("transcript",{line:u}),o(u)}}e.chat||e.out(`trace: ${te(_)}`),e.emit?.({type:"run_start",mode:a,trace:_,...m?{session:m.ids.session_id}:{}});let $=Ft();if($&&e.out($),e.preflightTurn){let o=await e.preflightTurn();if(h("preflight",o),!o.ok)return e.out(o.message??"error: turn-endpoint preflight failed"),e.emit?.({type:"error",message:o.message??"error: turn-endpoint preflight failed",code:"PREFLIGHT"}),2}let i=ee(e.contextDir),M=lr(e.contextDir,i),P=r.sources?.length?r.sources:r.source?[r.source]:[];if(P.length>0){if(r.resume){let o="error: --source cannot be combined with --resume (the resumed session already has its scope)";return e.out(o),e.emit?.({type:"error",message:o,code:"SOURCE_WITH_RESUME"}),2}for(let o of P){let u=i.heads.get(o);if(typeof u!="string"){let s=u===null?`error: --source ${o} was ingested but is retired \u2014 re-ingest it to extract again`:`error: --source ${o} is not an ingested source (kane-cli context list shows them)`;return e.out(s),e.emit?.({type:"error",message:s,code:"SOURCE_UNKNOWN"}),2}}}let l=null,f=null;if(r.resume){try{{let c=await or(e.contextDir,r.resume,i,{verb:"extract",deps:{onWarn:C=>e.out(`note: ${C}`)}});{let C=Object.keys(c.handle.state.read_basis??{});if(C.length>1){let B=`error: session ${r.resume} spans ${C.length} sources \u2014 multi-source resume isn't supported yet; committed work is preserved (re-run kane-cli context extract for anything remaining)`;return e.out(B),e.emit?.({type:"error",message:B,code:"MULTI_SOURCE_RESUME"}),c.handle.release(),2}f=c,h("resume_kind",{kind:c.view.pointer===null?"bare-base":c.view.pointer.at==="final"?"pause":"crash"}),l={handle:c.handle,represent:c.represent,questions:c.questions,staleBasis:c.drift.map(B=>B.subject)}}}}catch(c){let C=c instanceof Error?c.message:String(c);return e.out(`error: ${C}`),e.emit?.({type:"error",message:`error: ${C}`,...c instanceof dt?{code:c.code}:{}}),c instanceof dt?2:1}let o=f?null:Xt(l.handle.state.verb,"extract",r.resume);if(o)return e.out(o.message),e.emit?.({type:"error",message:o.message,code:o.code}),l.handle.release(),2;let u=l.handle.state.change_basis;if(u&&(i.heads.get(u.source_id)??null)!==u.new_head){let c=`error: ${u.source_id} moved while this reconcile extraction was paused \u2014 its recorded change context no longer matches; re-run kane-cli maintain reconcile against the current file (session ${r.resume} is defunct and can be ignored)`;return e.out(c),e.emit?.({type:"error",message:c,code:"CHANGE_BASIS_MOVED"}),l.handle.release(),2}if(f&&f.view.pointer!==null&&f.drift.length>0){if(!await e.confirmStale(`changed since the pause: ${f.drift.map(C=>C.subject).join(", ")} \u2014 re-ground and continue against the current versions?`)){let C=`resume aborted: the context moved since the pause (${f.drift.map(B=>B.subject).join(", ")}) \u2014 session ${r.resume} is preserved`;return e.out(C),e.emit?.({type:"error",message:C,code:"RESUME_DRIFT"}),l.handle.release(),2}}else l.staleBasis.length>0&&e.out(`note: changed since the pause: ${l.staleBasis.join(", ")} \u2014 re-presented items may be stale`);let s=[...new Set([...l.handle.state.held_receipts??[],...f?.view.kane?.held_receipts??[]])];if(s.length>0)if(e.chat?.holdReceipt)for(let c of s)e.chat.holdReceipt(c);else e={...e,initialMessage:[s.join(`
6
+
7
+ `),e.initialMessage].filter(Boolean).join(`
8
+
9
+ `)};l.handle.state.assumed.length>0&&e.out(`note: ${l.handle.state.assumed.length} default(s) were assumed while you were away \u2014 kane-cli context sessions show ${r.resume} lists them`)}let re=i.extractedSourceCids,he=!!(r.force||l?.handle.state.force),se=[],oe=[],Ce=P.length>0?new Set(P):null;for(let[o,u]of i.heads.entries())if(u!=null&&!(Ce&&!Ce.has(o))){if(!Ce&&!l&&o.startsWith("su-conv-")){e.out(`skipped ${o} \u2014 conversation source; extract it explicitly with --source ${o}`),oe.push({source_id:o,reason:"conversation"});continue}if(l){let s=o in l.handle.state.read_basis,c=l.handle.state.corpus_cursor.remaining.includes(o);if(!s&&!c)continue;if(c&&!he&&re.has(u)){e.out(`${o} already extracted \u2014 skipped (--force re-runs it)`),oe.push({source_id:o,reason:"cached"});continue}}else if(!he&&re.has(u)){e.out(`${o} already extracted \u2014 skipped (--force re-runs it)`),oe.push({source_id:o,reason:"cached"});continue}se.push({source_id:o,cid:u})}let _r=o=>{let u=tr(e.contextDir,o);u&&e.out(`note: a reconcile plan for ${o} is pending (${u.pending} item(s)) \u2014 resume with \`kane-cli maintain reconcile --apply ${u.path}\``)};for(let o of oe)o.reason==="cached"&&_r(o.source_id);if(e.emit?.({type:"corpus",sources:se,skipped:oe}),se.length===0){if(l){let s=`error: resumed session's paused source (${Object.keys(l.handle.state.read_basis).join(", ")||"unknown"}) is no longer in the corpus \u2014 restore/re-ingest it and re-run --resume ${r.resume}, or discard with: kane-cli context sessions clean ${r.resume}`;return e.out(s),e.emit?.({type:"error",message:s,code:"SOURCE_MISSING"}),l.handle.release(),2}let o=oe.length>0&&oe.every(u=>u.reason==="conversation");return e.out(Ce?`extract: nothing to do \u2014 ${P.join(", ")} ${P.length===1?"is":"are all"} already extracted at the current snapshot (--force to re-run)`:o?"extract: nothing to do \u2014 only conversation sources here (extract one explicitly with --source <id>)":"extract: nothing to do \u2014 every ingested source is already extracted"),0}let ie=!r.plan&&a!=="ci",De=e.now?.()??new Date,Ee=r.resume??`ext-${Le(De)}-${hr(se[0].source_id)}`,T=null,Pe=!1;ie&&!l&&(T=nt(e.contextDir,{sid:Ee,mode:"agent",created_at:De.toISOString(),expires_at:new Date(De.getTime()+1440*60*1e3).toISOString(),agent_state:{schema:2,items:[],provider_state:""},pending:{questions:[],proposals:[]},assumed:[],read_basis:{[se[0].source_id]:se[0].cid},corpus_cursor:{remaining:se.slice(1).map(o=>o.source_id)},conv_source:"",verb:"extract",...he?{force:!0}:{},...r.changeContext?{change_basis:{source_id:r.changeContext.source_id,new_head:r.changeContext.new_head}}:{},...m?{user_session_id:m.ids.session_id}:{}}));let Ve=f?f.represent.map(o=>o.event_id).filter(o=>typeof o=="string"):[],S=l?.handle??T,ft=!1,pt=()=>{try{br(ce(e.contextDir,"sessions"))}catch{}},_t=()=>{if(T){try{T.complete()}catch{T.release()}T=null,S=null,pt()}},Te=new Map;if(l&&l.questions.length>0&&!r.message&&!r.withSource){e.out(`re-presenting ${l.questions.length} unanswered question(s) from the paused session`);let o=await e.ask(l.questions.map(rr));if(Array.isArray(o))for(let u of o)Te.set(u.id,u)}let ge=e.by??{kind:"human",id:"owner"},I=a==="interactive"&&!r.plan&&!!e.chat,Y=0,xt=0,Ae=!1,de=0,We=()=>{Ae||(Ae=!0,e.out("note: duplicate detection is running in a reduced mode this run \u2014 new items will be held for your review instead of committed"),m?.event("ASR_EMBED_DEGRADED",{}),e.emit?.({type:"degraded",reason:"embed_fallback"}))},Oe=null,fe=()=>S??T,ze=(o,u,s)=>{let c=fe();if(!c)return;let C=u.map(w=>({label:"usecase",content:{title:w.title,...w.summary!==void 0?{summary:w.summary}:{},...w.risk!==void 0?{risk:w.risk}:{},derived:!0,_held:{source_id:o.source_id,source_cid:o.cid,anchor:w.cite?.anchor??"L1-L1",quote:w.cite?.quote??""}},rationale:`held (${s==="degraded"?"embed degraded \u2014 lexical dedup only":"--trust hold"}): ${o.source_id} @ ${o.cid.slice(0,19)} ${w.cite?.anchor??""}`,edges:[],tempRef:w.temp_ref})),B=c.state.pending;c.save({pending:{questions:B.questions,proposals:[...B.proposals,...C]}}),de+=C.length,Oe=c.state.sid,e.emit?.({type:"held",source_id:o.source_id,count:C.length,reason:s==="degraded"?"embed_degraded":"trust_hold"})},q=[],vt=!1,U=[...se];try{let o=u=>{let s=S;if(!s)return;let c=s.state.ingest_schedule??[];if(!c.some(w=>w.status==="pending"))return;let C=ee(e.contextDir),B=c.map(w=>w.status!=="pending"?w:(C.heads.get(w.source_id)??null)!==w.cid?(e.out(`note: ${w.source_id} changed after it was added \u2014 skipping its extraction this run; re-run kane-cli context extract to pick up the newer version`),{...w,status:"skipped",note:"head moved since landing"}):C.extractedSourceCids.has(w.cid)||U.some(W=>W.source_id===w.source_id&&W.cid===w.cid)?{...w,status:"done"}:U.some(W=>W.source_id===w.source_id)?(e.out(`note: an older version of ${w.source_id} is already queued this run \u2014 the newly landed version is not extracted; re-run kane-cli context extract to pick it up`),{...w,status:"skipped",note:"an older version of the source was already queued this run"}):(U.push({source_id:w.source_id,cid:w.cid}),e.out(`queued ${w.source_id} for extraction in this run (landed mid-run)`),{...w,status:"done"}));s.save({ingest_schedule:B,corpus_cursor:{remaining:U.slice(u+1).map(w=>w.source_id)}})};for(let u=0;u<U.length;o(u),u++){let s=U[u],c=ee(e.contextDir),C={current:c};e.chat?.attachOnCommitted?.(t=>{C.current=t});let B=c.getNode(s.cid),w=String(B?.content.blob??""),Ie=$e(e.contextDir,c,s.cid);if(!Ie){e.out(`error: ${s.source_id}: its stored content is missing \u2014 re-ingest the file (kane-cli context ingest <file>) [BLOB_MISSING]`),e.emit?.({type:"error",source_id:s.source_id,message:`error: ${s.source_id}: blob ${w} missing from .context/blobs`,code:"BLOB_MISSING"}),q.push(s.source_id);continue}let W=c.mediaOf(s.cid),Ke=W.media_type.startsWith("image/");if(!Ke){let t=kr(Ie);if(t){e.out(`skipping ${s.source_id}: binary ${t} ingested before image support \u2014 re-ingest it (kane-cli context ingest) to extract from it`),e.emit?.({type:"source_skipped",source_id:s.source_id,reason:"binary_pre_media"});continue}}let yt=Ke?`0001| (image source ${s.source_id} \u2014 the content is attached as an image; cite it with anchor img#whole)`:ct(Ie),Me=(t,n)=>{let d=new Map;d.set(s.source_id,{media:W,numberedText:yt});for(let g of n.sources??[]){if(d.has(g.source_id))continue;let D=$e(e.contextDir,t,g.source_cid);if(!D)continue;let k=t.mediaOf(g.source_cid),E=k.media_type.startsWith("image/")?`0001| (image source ${g.source_id} \u2014 the content is attached as an image; cite it with anchor img#whole)`:ct(D);d.set(g.source_id,{media:k,numberedText:E})}return d},wt=Le(e.now?.()??new Date),ne=`${wt}-${s.source_id}`,pe=!!(l&&s.source_id in l.handle.state.read_basis),Ue=S?Ee:`ext-${wt}-${hr(s.source_id)}`,Je=U.slice(u+1).map(t=>t.source_id);S&&ie&&!pe&&S.save({read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:Je}});let ae="";if(I){let t=Wt({contextDir:e.contextDir,graph:ee(e.contextDir),sessionStamp:Ue,by:ge});t.errors===null||t.errors[0]?.code==="CONV_SOURCE_EXISTS"?(ae=t.sourceId,e.chat.attachConversationSource?.(ae),C.current=ee(e.contextDir)):e.out(`warning: notes you add in chat can't be saved to the context this session (${t.errors[0]?.detail})`)}let bt={type:"run_config",version:1,session_id:Ue,mode:a,source:{source_id:s.source_id,source_cid:s.cid,kind:Mt.has(W.format)?W.format:Sr(s.source_id)||"md",numbered_text:yt,...(()=>{let t=$r(W,e.contextDir);return t?{images:t}:{}})()},existing_use_cases:c.byLabel(me.USECASE).filter(({cid:t})=>c.trust.get(t)!=="archived"&&!c.superseded.has(t)).map(({cid:t,content:n})=>({id:t,title:String(n.title??""),summary:String(n.summary??"")})),read_basis:C.current.latestHash,max_free_text_rounds:Yt,graph_reads:!0,verb:"extract",...M!==void 0?{style_note_digest:M}:{},...r.changeContext&&r.changeContext.source_id===s.source_id?{change_context:r.changeContext}:{},topology:er(),...I?{chat:!0}:{},...Ke?{image_sources:[{source_id:s.source_id,source_cid:s.cid,media_type:W.media_type,blob_ref:{path:Se(e.contextDir,w),cid:w}}]}:{},...l&&!f&&s.source_id in l.handle.state.read_basis?{resume:{agent_state:l.handle.state.agent_state}}:{},...ie&&S?{checkpoints:!0}:{}},R=f&&pe?{...f.spawnConfig,mode:a}:bt;if(ie&&S&&!ft){ft=!0;let{resume:t,...n}=bt;Ht(e.contextDir,Ee,{schema:Nt,kind:"base",sid:Ee,verb:"extract",mode:a,created_at:De.toISOString(),run_config:n,conv_source:ae||S.state.conv_source||"",store_watermark:It(e.contextDir)})}let St=f&&pe?0:S?.state.checkpoint?.seq??0,_e={current:null};if(R.resume&&"schema"in R.resume){let t=R.resume.binding?.template_version;typeof t=="string"&&(_e.current=t)}let Xe=ie&&S?ir({contextDir:e.contextDir,handle:S,seqBase:()=>St,peekHeldReceipts:()=>e.chat?.peekHeldReceipts?.()??[],readBasis:()=>({[s.source_id]:s.cid}),corpusCursor:()=>({remaining:Je}),onSoftCap:t=>e.out(t),onStat:t=>h("ckpt_stat",t,R.session_id),...e.now?{now:e.now}:{}}):void 0,ue=Xe?{...Xe,persist:t=>{let n=t.binding?.template_version;return typeof n=="string"&&n&&(_e.current=n),Xe.persist(t)}}:void 0;I||e.out(l&&s.source_id in l.handle.state.read_basis?`resuming: ${s.source_id} (session ${r.resume})`:`reading ${s.source_id} (source ${u+1} of ${U.length})`),e.emit?.({type:"source_start",source_id:s.source_id,cid:s.cid,index:u+1,total:U.length,resumed:!!(l&&s.source_id in l.handle.state.read_basis)}),e.chat?.ledger?.({kind:"banner",text:Rr(s,u+1,U.length)}),e.chat?.setWorking?.(`Reading ${pr(s)}\u2026`);let Ye=new Map;h("spawn",{source_id:s.source_id,source_cid:s.cid,resume:!!l,chat:I},R.session_id);let $t=!1,kt=!1,Ze=!1,Rt=async t=>{let n=ee(e.contextDir),d=be(t,Me(n,t),n);if(h("kane_validate",{errors:d.map(p=>p.code)},R.session_id),d.length>0){if(e.nested){e.chat?.ledger?.({kind:"commit",ok:!1,line:"proposal failed validation \u2014 nothing landed",warnings:d.map(p=>`${p.code}: ${p.detail}`)}),kt=!0;return}e.chat.submit("[auto-repair] the proposal failed validation: "+d.map(p=>`${p.code}: ${p.detail}`).join("; ")+" \u2014 please re-finalize with these fixed.");return}let g=ee(e.contextDir),D=gr(t,g),k=ce(e.contextDir,"proposals",ne);ut(k,{recursive:!0}),lt(ce(k,"proposal.json"),JSON.stringify(t,null,2)+`
10
+ `);let E=new Map(t.use_cases.map(p=>[p.temp_ref,{resolution:"skipped"}])),Q=mt(e.contextDir,R.session_id,Ve,e.probe,e.auth),O=await ke(Q,ht(t,g),p=>{if(p.degradedProbe&&fe()!==null&&t.use_cases.some(ye=>ye.matches_existing==null))return{result:{degradedHold:!0},record:null};let K=Be({contextDir:e.contextDir,graph:p.graph,proposal:t,proposalId:ne,verdicts:E,by:{kind:"ai",id:"extract-agent"},autoName:!0,allowStaleBasis:!0,eventIds:p.eventIds("extract",1),...ie?{sid:p.sid}:{},probeHits:p.probeHits});return K.errors!==null?{errors:K.errors}:{result:K,record:K.record}}),N=O.ok&&"result"in O?O.result:null;if(N!==null&&"degradedHold"in N){We(),ze(s,t.use_cases,"degraded"),Ze=!0,e.chat.ledger?.({kind:"commit",ok:!1,line:`held ${t.use_cases.length} item(s) for review \u2014 semantic dedup ran degraded (embeddings unavailable); nothing saved this turn`});return}let V=N??{record:null,errors:O.ok?null:O.kind==="validation"?O.errors:[{code:O.kind==="contended"?O.err.code:"UNSETTLED",detail:O.kind==="contended"?`held by ${O.err.holder?.owner_sid??"another session"}`:"concurrent activity kept moving the store"}]};if(V.errors){e.chat.ledger?.({kind:"commit",ok:!1,line:"commit failed \u2014 nothing landed",warnings:V.errors.map(p=>`${p.code}: ${p.detail}`)});return}$t=!0,V.record?.event_ids?.length&&S?.markApplied(V.record.event_ids);{let p=V.record.review.filter(K=>K.kind==="pending_update");p.length>0&&(I||e.out(`${p.length} update(s) held for review`),e.emit?.({type:"update_held",count:p.length,targets:p.map(K=>K.id)}),e.chat?.ledger?.({kind:"commit",ok:!0,line:`${p.length} update(s) held for review`}))}let z=V.record.nodes.length;Y+=z;let H=t.use_cases.length-z;{let p=ee(e.contextDir),K=new Map;for(let{cid:j,content:J}of p.byLabel(me.USECASE))p.superseded.has(j)||K.set(Re(String(J.title??"")),j);let ye=[];for(let j of t.use_cases){let J=null;if(j.matches_existing?.cid&&p.hasNode(j.matches_existing.cid)){let we=p.tipOf(j.matches_existing.cid);J=p.superseded.has(we)?null:we}J=J??K.get(Re(j.title))??null,J&&ye.push({ref:j.temp_ref,cid:J,...p.displayNameOf(J)?{id:p.displayNameOf(J)}:{}})}ye.length>0&&e.chat.registerAliases?.(ye),C.current=p;let Pt=j=>{for(let[J,we]of p.names)if(we===j&&!p.superseded.has(we))return J},Tt=zt({verb:"extract",commitN:1,phase:"proposal",committed:V.record.nodes.map(j=>({cid:j.cid,...Pt(j.cid)?{logical_id:Pt(j.cid)}:{}})),reused:H},p);e.emit?.(Tt.event),e.chat.holdReceipt?.(Tt.text)}h("commit",{derived:z,evidence_matched:H,chat:!0},R.session_id),e.chat.ledger?.({kind:"commit",ok:!0,line:z===0&&H>0?`all ${H} matched existing \u2014 nothing new to save`:`saved ${z} use-case${z===1?"":"s"} as drafts`+(H>0?` \xB7 ${H} matched existing`:"")})},Qe=!!(l&&s.source_id in l.handle.state.read_basis),G=Qe&&Te.size>0?{...e,ask:async t=>t.every(n=>Te.has(n.id))?(l.handle.markApplied(t.map(n=>`resolveq:${r.resume}:${n.id}`)),e.out(`answered ${t.length} re-asked question(s) from the held resume answers`),t.map(n=>Te.get(n.id))):e.ask(t)}:e;Qe&&r.message&&(G={...G,initialMessage:r.message}),G={...G,onEmbedDegraded:We};let le,et;if(S){let t=S,n=G.ask,d=Qt({contextDir:e.contextDir,cwd:mr(e.contextDir),handle:t,note:g=>e.chat?e.chat.note(g):e.out(g),schedule:r.trust!=="hold",...r.trust==="hold"?{scheduleRefused:"this run holds items for review, so its extraction is not scheduled \u2014 kane-cli context extract runs it after the review"}:{},graphSlot:C,...e.now?{now:e.now}:{}});if(G={...G,ask:async g=>{let D=await n(g);if(Array.isArray(D)){let k=D.filter(E=>{if(E.free_text==null||E.free_text.trim()==="")return!1;let Q=g.find(O=>O.id===E.id);return E.selected_index!=null&&Q?.options[E.selected_index]?.input===!0}).map(E=>E.free_text.trim());if(k.length>0){let E=t.state.ingest_registry;for(let Q of k)E=qe(E,Q,e.now?.()??new Date);t.save({ingest_registry:E})}}return D},ingest:d},Qe&&r.withSource){let g=(t.state.pending?.proposals??[]).filter(E=>E.content?._held!=null).length;if(r.trust==="hold"||g>0){let E=g>0?`error: --with-source can't add a source to a session holding ${g} item(s) for review \u2014 resume without --with-source to finish the review first, then land it with kane-cli context ingest [HOLD_MULTI_SOURCE]`:"error: --with-source is not available with --trust hold \u2014 held work from a multi-source run can't be resumed yet; drop --trust hold, or land the source separately with kane-cli context ingest [HOLD_MULTI_SOURCE]";return e.out(E),e.emit?.({type:"error",code:"HOLD_MULTI_SOURCE",message:E}),2}let D=r.withSource;t.save({ingest_registry:qe(t.state.ingest_registry,D,e.now?.()??new Date)});let k=await d({id:`withsource-${t.state.sid}`,ref:D,purpose:null});if(!k.ok)return e.out(`error: --with-source: ${k.error.message}`),e.emit?.({type:"error",code:k.error.code,message:`--with-source: ${k.error.message}`}),2;G={...G,pendingDeferral:{ingested:{source_id:k.result.source_id,cid:k.result.cid}}}}et=()=>{if(!e.chat?.attachIngest)return;let g=e.chat;le=g.attachIngest(async D=>{try{t.save({ingest_registry:qe(t.state.ingest_registry,D,e.now?.()??new Date)});let k=await d({id:`attach-${t.state.sid}-${(t.state.ingest_registry??[]).length}`,ref:D,purpose:null});return k.ok?(g.deferBatch({source_id:k.result.source_id,cid:k.result.cid}),{ok:!0}):{ok:!1,error:k.error.message}}catch(k){return{ok:!1,error:k instanceof Error?k.message:String(k)}}})},et()}let b;try{b=await gt(R,{...G,graphSlot:C,...ue?{checkpoint:ue}:{}},Ye,c,h,I?Rt:void 0,()=>_e.current)}catch(t){if(t instanceof Fe)return le?.(),e.chat?.setWorking?.(null),e.out(`error: ${t.message}`),e.emit?.({type:"error",code:"PAIR_MISMATCH",message:t.message}),2;throw t}if(le?.(),e.chat?.setWorking?.(null),b.errorCode==="binding_mismatch"&&f&&pe){let t=await e.ask([{id:"binding-mismatch",text:"this session's saved conversation is no longer accepted by the service \u2014 start the conversation fresh (committed work is kept), or stop and keep the session?",risk:"high",rationale:"the service refused the saved conversation on the first turn after resume",options:[{label:"start fresh",detail:"continue with a fresh conversation \u2014 earlier answers may be re-asked"},{label:"stop",detail:"stop here; the session stays resumable"}],recommended_index:1,allow_free_text:!1}]);if((Array.isArray(t)?t.find(g=>g.id==="binding-mismatch"):void 0)?.selected_index!==0){let g=`resume abandoned: binding mismatch on session ${Ue} \u2014 the session is preserved`;return e.out(g),e.emit?.({type:"error",message:g,code:"BINDING_MISMATCH"}),2}h("binding_migrate",{sid:Ue},R.session_id),et?.();let d=R.resume&&"schema"in R.resume?{...R.resume,binding:{}}:void 0;try{b=await gt({...R,...d?{resume:d}:{}},{...G,graphSlot:C,...ue?{checkpoint:ue}:{}},Ye,c,h,I?Rt:void 0,()=>_e.current)}catch(g){if(g instanceof Fe)return le?.(),e.chat?.setWorking?.(null),e.out(`error: ${g.message}`),e.emit?.({type:"error",code:"PAIR_MISMATCH",message:g.message}),2;throw le?.(),g}le?.(),e.chat?.setWorking?.(null)}if(b.error){let t=b.error.startsWith("proposal failed validation after repair:");t&&h("agent_error_detail",{error:b.error},R.session_id);let n=t?`error: the agent could not produce a valid proposal for ${s.source_id} \u2014 re-run kane-cli context extract to retry`:`error: agent failed for ${s.source_id}: ${b.error}`;e.out(n),e.emit?.({type:"error",source_id:s.source_id,message:n}),q.push(s.source_id);continue}if(b.highRisk)return e.out(`error: ${b.highRisk.length} high-risk decision${b.highRisk.length===1?"":"s"} need a human \u2014 ci mode won't guess. Re-run with --mode agent to pause for review.`),e.emit?.({type:"error",source_id:s.source_id,message:`error: high-risk question(s) in ci mode (fail-closed): ${b.highRisk.map(t=>t.id).join(", ")}`,code:"HIGH_RISK_CI"}),1;if(b.paused){let t=U.slice(u+1).map(D=>D.source_id),n=l?.handle??T,d=n??nt(e.contextDir,{sid:R.session_id,mode:"agent",created_at:(e.now?.()??new Date).toISOString(),expires_at:new Date((e.now?.()??new Date).getTime()+1440*60*1e3).toISOString(),agent_state:b.paused.agent_state,pending:{questions:[],proposals:[]},assumed:[],read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:t},conv_source:ae,verb:"extract",...he?{force:!0}:{},...r.changeContext?{change_basis:{source_id:r.changeContext.source_id,new_head:r.changeContext.new_head}}:{},...m?{user_session_id:m.ids.session_id}:{}});Pe=!0;try{ae&&d.state.conv_source!==ae&&d.save({conv_source:ae});let D=e.chat?.drainHeldReceipts?.()??[];(D.length>0||(d.state.held_receipts?.length??0)>0)&&d.save({held_receipts:D}),n&&d.save({read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:t},...he&&!d.state.force?{force:!0}:{},...m&&d.state.user_session_id!==m.ids.session_id?{user_session_id:m.ids.session_id}:{}}),sr(d,b.paused)}catch(D){let k=d.state.checkpoint,E=`error: couldn't persist the pause for session ${d.state.sid}`+(k?` \u2014 last durable checkpoint: seq ${k.seq} @ ${k.ts}`:" \u2014 no durable checkpoint exists")+` (${D instanceof Error?D.message:String(D)})`;return e.out(E),e.emit?.({type:"error",message:E,code:"PAUSE_PERSIST_FAILED",sid:d.state.sid}),1}h("session_paused",{sid:d.state.sid},R.session_id);let g=`kane-cli context extract --resume ${d.state.sid} --mode ${a}`;if(I||e.out(`paused: session ${d.state.sid} saved \u2014 resume with: ${g}`),e.emit?.({type:"session_paused",sid:d.state.sid,source_id:s.source_id,mode:a,resume:g,expires_at:d.state.expires_at,pending_questions:b.paused.pending.questions}),I){let D=e.chat?.state.credits?.total;e.onSummary?.({state:"paused",reason:"ctrl+c",facts:[`session ${d.state.sid} saved`+(Y>0?` \u2014 ${Y} use-case${Y===1?"":"s"} committed so far`:""),...d.state.expires_at?[`expires: ${d.state.expires_at}`]:[],...D!==void 0?[`credits used: ${D.toFixed(1)}`]:[]],resume:g,resumeMessage:`${g} --message "<your words>"`,tracePath:te(_)})}return 3}if(b.crashed){let t=S?.state.checkpoint;if(S&&t){let n=`kane-cli context extract --resume ${S.state.sid} --mode ${a}`;try{S.save({read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:Je}})}catch{}if(h("agent_crashed_resumable",{sid:S.state.sid,seq:t.seq},R.session_id),I||e.out(`agent crashed \u2014 session ${S.state.sid} is resumable at checkpoint seq ${t.seq} (at most the in-flight turn lost); resume with: ${n}`),e.emit?.({type:"session_paused",sid:S.state.sid,source_id:s.source_id,mode:a,resume:n,expires_at:S.state.expires_at,crashed:!0}),I){let d=e.chat?.state.credits?.total;e.onSummary?.({state:"crashed",facts:[`agent crashed \u2014 session ${S.state.sid} is resumable at checkpoint seq ${t.seq}`,"at most the in-flight turn was lost",...d!==void 0?[`credits used: ${d.toFixed(1)}`]:[]],resume:n,resumeMessage:`${n} --message "<your words>"`,tracePath:te(_)})}return Pe=!0,S.release(),3}e.out(`error: agent crashed for ${s.source_id} with no durable checkpoint`),e.emit?.({type:"error",source_id:s.source_id,message:`error: agent crashed for ${s.source_id} with no durable checkpoint`,code:"AGENT_CRASHED"}),q.push(s.source_id);continue}if(I){if(xt+=b.assumedDefaults??0,b.error||kt)return 1;if(!$t&&!Ze){let t=U.length-u-1,n=`done \u2014 nothing committed for ${s.source_id} (no finalize before the session ended)`+(t>0?`; stopping here \u2014 ${t} remaining source(s) not extracted (re-run kane-cli context extract to continue)`:"");I||e.out(n),e.onSummary?.({state:"complete",facts:[n,...Y>0?[`${Y} use-case${Y===1?"":"s"} saved earlier in this run`]:[]],tracePath:te(_)});{let d=(S?.state.ingest_schedule??[]).filter(g=>g.status==="pending");d.length>0&&e.out(`note: ${d.length} source(s) landed this session (${d.map(g=>g.source_id).join(", ")}) were not extracted \u2014 the session ended first; kane-cli context extract runs them`)}return l&&s.source_id in l.handle.state.read_basis&&(l.handle.complete(),l=null,S=null),_t(),0}l&&s.source_id in l.handle.state.read_basis&&!Ze&&(o(u),l.handle.complete(),l=null,S=null);continue}if(!b.proposal){e.out(`error: agent ended without a proposal for ${s.source_id}`),e.emit?.({type:"error",source_id:s.source_id,message:`error: agent ended without a proposal for ${s.source_id}`}),q.push(s.source_id);continue}let L=be(b.proposal,Me(c,b.proposal),c);if(h("kane_validate",{errors:L.map(t=>t.code)},R.session_id),L.length>0&&Cr(b.proposal,L,t=>e.out(t))&&(h("criteria_dropped",{source_id:s.source_id},R.session_id),L=be(b.proposal,Me(c,b.proposal),c)),L.length>0){e.out("the agent's proposal didn't validate \u2014 retrying once"),e.emit?.({type:"validate_failed",source_id:s.source_id,codes:L.map(t=>t.code),repairing:!0}),h("repair_respawn",{source_id:s.source_id},R.session_id),f&&pe||(St=S?.state.checkpoint?.seq??0);try{b=await gt(R,{...G,graphSlot:C,...ue?{checkpoint:ue}:{}},Ye,c,h,void 0,()=>_e.current)}catch(t){if(t instanceof Fe)return e.out(`error: ${t.message}`),e.emit?.({type:"error",code:"PAIR_MISMATCH",message:t.message}),2;throw t}if(b.error||!b.proposal){e.out(`error: repair run failed for ${s.source_id}`),e.emit?.({type:"error",source_id:s.source_id,message:`error: repair run failed for ${s.source_id}`}),q.push(s.source_id);continue}if(L=be(b.proposal,Me(c,b.proposal),c),L.length>0){h("validation_details",{errors:L.map(t=>({code:t.code,detail:t.detail}))},R.session_id),e.out(`\u2717 validation failed \u2014 ${L.map(t=>t.code).join(", ")} (details: ${te(_)})`),e.emit?.({type:"validate_failed",source_id:s.source_id,codes:L.map(t=>t.code),repairing:!1}),e.emit?.({type:"error",source_id:s.source_id,message:`error: proposal failed validation after repair (${L.map(t=>t.code).join(", ")})`}),q.push(s.source_id);continue}}let A=b.proposal,Ne=gr(A,c),tt=ce(e.contextDir,"proposals",ne);if(ut(tt,{recursive:!0}),lt(ce(tt,"proposal.json"),JSON.stringify(A,null,2)+`
11
+ `),r.plan){e.out(`plan: ${A.use_cases.length} use-case(s) proposed from ${s.source_id} (nothing committed)`);for(let t of A.use_cases){let n=Ne.get(t.temp_ref),d=n?n.archived?` \u2248 matches ARCHIVED ${n.cid.slice(0,19)}${n.reason?` \u2014 previously rejected: "${n.reason}"`:" \u2014 previously rejected"}`:` \u2248 matches ${n.cid.slice(0,19)}`:"";e.out(` [${t.risk}] ${t.title} \u2014 cite ${t.cite.anchor}${d}`)}e.emit?.({type:"plan",source_id:s.source_id,use_cases:A.use_cases.map(t=>{let n=Ne.get(t.temp_ref);return{risk:t.risk,title:t.title,anchor:t.cite.anchor,...n?{match:n.cid,match_archived:!!n.archived}:{}}})}),b.assumedDefaults&&e.out(`assumed: ${b.assumedDefaults} default(s) auto-taken (assumed)`);continue}for(let t of A.use_cases){if(!t.conflicts_with?.length)continue;let n=t.conflicts_with.filter(g=>c.resolve(g)!==null),d=t.conflicts_with.filter(g=>c.resolve(g)===null);d.length>0&&(e.out(`note: ${t.temp_ref}: dropped unresolvable conflict hint(s): ${d.join(", ")}`),t.conflicts_with=n.length>0?n:void 0)}h("review_start",{use_cases:A.use_cases.length,flags:Ne.size},R.session_id);let He=await e.review(A.use_cases,Ne);if(h("review_verdicts",[...He.entries()].map(([t,n])=>({ref:t,resolution:n.resolution})),R.session_id),lt(ce(tt,"review.json"),JSON.stringify(A.use_cases.map(t=>{let n=He.get(t.temp_ref)??{resolution:"skipped"};return{id:t.temp_ref,kind:"review-item",resolution:n.resolution,edit:n.edit??null,reason:n.reason??null,...n.supersedeTarget?{supersede_target:n.supersedeTarget}:{},by:ge}}),null,2)+`
12
+ `),r.posture==="reconcile"){let t=jt(A),n=N=>t.passthrough.use_cases.filter(V=>{let z=V.matches_existing?.cid,H=z?N.resolve(z):null,p=H?N.tipOf(H.cid):null;return p!=null&&(N.trust.get(p)??null)!=="derived"}),d=n(c),g=t.passthrough.use_cases.length-d.length,D=mt(e.contextDir,R.session_id,Ve,e.probe,e.auth),k=new Set(d.map(N=>N.temp_ref));(await ke(D,ht({...t.passthrough,use_cases:d},c),N=>{let V={...t.passthrough,use_cases:n(N.graph).filter(p=>k.has(p.temp_ref))},z=new Map(V.use_cases.map(p=>[p.temp_ref,{resolution:"approved"}])),H=Be({contextDir:e.contextDir,graph:N.graph,proposal:V,proposalId:ne,verdicts:z,by:ge,autoName:!0,allowStaleBasis:!0,eventIds:N.eventIds("extract",1),...ie?{sid:N.sid}:{},probeHits:N.probeHits});return H.errors!==null?{errors:H.errors}:{result:H,record:H.record}})).ok||e.out("note: the unchanged-match evidence attach did not land this run \u2014 the held changeset is unaffected; re-run reconcile to refresh it"),g>0&&e.out(`note: ${g} unchanged match(es) target unreviewed (or no-longer-resolving) item(s) \u2014 evidence not attached (bless them with kane-cli context review; a later reconcile attaches)`);let Q=fe(),O=t.adds.length+t.updates.length+t.archives.length;Q&&O>0&&(Q.save({reconcile:{proposal_id:ne,verdicts:{}}}),de+=O,Oe=Q.state.sid,e.out(`held: ${O} change(s) from ${s.source_id} await your verdicts \u2014 nothing from the changeset committed`),e.emit?.({type:"held",source_id:s.source_id,count:O,reason:"reconcile"}));continue}if((Ae||r.trust==="hold")&&fe()&&A.use_cases.some(t=>t.matches_existing==null)){ze(s,A.use_cases,Ae?"degraded":"trust_hold");continue}let Ct=mt(e.contextDir,R.session_id,Ve,e.probe,e.auth),Dt=t=>{if(t.degradedProbe&&fe()!==null&&A.use_cases.some(d=>d.matches_existing==null))return{result:{degradedHold:!0},record:null};let n=Be({contextDir:e.contextDir,graph:t.graph,proposal:A,proposalId:ne,verdicts:He,by:ge,autoName:!0,allowStaleBasis:!0,eventIds:t.eventIds("extract",1),...ie?{sid:t.sid}:{},probeHits:t.probeHits});return n.errors!==null?{errors:n.errors}:{result:n,record:n.record}},Et=ht(A,c),F=await ke(Ct,Et,Dt);if(!F.ok&&F.kind==="drifted"){if(!await e.confirmStale(`the context changed while you reviewed (${F.asks.map(n=>n.detail).join("; ")}) \u2014 commit against the new head anyway?`)){e.out("aborted: proposal not committed"),e.emit?.({type:"error",source_id:s.source_id,message:"aborted: proposal not committed",code:"STALE_BASIS"}),q.push(s.source_id);continue}F=await ke(Ct,{...Et,sourcePins:[]},Dt)}let rt=F.ok&&"result"in F?F.result:null;if(rt!==null&&"degradedHold"in rt){We(),ze(s,A.use_cases,"degraded");continue}let xe=rt??(F.ok?{record:null,errors:null}:{record:null,errors:F.kind==="validation"?F.errors:F.kind==="contended"?[{code:F.err.code,detail:`a use-case this proposal touches is held by ${F.err.holder?.owner_sid??"another session"} \u2014 try again when it frees`}]:[{code:"UNSETTLED",detail:"concurrent activity kept moving the store \u2014 retry when quieter"}]});if(xe.errors){h("commit_error_details",{errors:xe.errors.map(t=>({code:t.code,detail:t.detail}))},R.session_id),e.out(`\u2717 commit failed \u2014 ${xe.errors.map(t=>t.code).join(", ")} (details: ${te(_)})`),e.emit?.({type:"error",source_id:s.source_id,message:`error: commit failed: ${xe.errors.map(t=>`${t.code}: ${t.detail}`).join("; ")}`}),q.push(s.source_id);continue}let xr=new Date().toISOString();for(let t of A.use_cases){let n=He.get(t.temp_ref)??{resolution:"skipped"};for(let d of Jt({ts:xr,command:"context extract",id:t.temp_ref,by:ge},n.resolution))Kt(e.contextDir,d)}let Z=xe.record;Z.event_ids?.length&&S?.markApplied(Z.event_ids);let st=new Map(Z.review.map(t=>[t.id,t.resolution])),it=[...st.values()].filter(t=>t==="approved"||t==="edited").length,je=[...st.values()].filter(t=>t==="rejected").length,ve=Z.nodes.filter(t=>!st.has(t.cid)).length,ot=Z.supersessions.filter(t=>t.kind==="node"&&t.new!==t.old).length;h("commit",{trusted:it,derived:ve,archived:je},R.session_id),e.out(`saved ${it+ve} use-case(s)`+(ve>0?` \xB7 ${ve} awaiting review`:"")+(je>0?` \xB7 ${je} archived`:"")+(ot>0?` \xB7 ${ot} superseded`:""));{let t=Z.review.filter(n=>n.kind==="pending_update");t.length>0&&(e.out(`${t.length} update(s) held for review`),e.emit?.({type:"update_held",count:t.length,targets:t.map(n=>n.id)}))}b.assumedDefaults&&e.out(`assumed: ${b.assumedDefaults} default(s) auto-taken (assumed)`),e.emit?.({type:"commit",source_id:s.source_id,proposal_id:ne,trusted:it,derived:ve,archived:je,superseded:ot,assumed:b.assumedDefaults??0,evidence_matched:Math.max(0,A.use_cases.length-Z.nodes.length),minted:Z.nodes.map(t=>{let n=Z.names?.find(d=>d.cid===t.cid)?.slug;return{cid:t.cid,...n?{logical_id:n}:{}}})}),l&&s.source_id in l.handle.state.read_basis&&(o(u),l.handle.complete(),e.out(`session ${r.resume} complete`),e.emit?.({type:"session_complete",sid:r.resume,source_id:s.source_id}),m?.event("ASR_SESSION_COMPLETE",{}),l=null,S=null)}if(S){let u=S.state.ingest_schedule??[];u.some(s=>s.status==="pending")&&S.save({ingest_schedule:u.map(s=>s.status==="pending"?{...s,status:"skipped",note:"run ended before its turn \u2014 kane-cli context extract runs it"}:s)})}vt=!0}finally{if(l?.handle.release(),T&&!Pe&&!vt){let o=T.state.checkpoint;if(o){let u=`kane-cli context extract --resume ${T.state.sid} --mode ${a}`;e.out(`session ${T.state.sid} kept its last checkpoint (seq ${o.seq}, ${o.ts}) \u2014 resume with: ${u}`),T.release()}else{try{T.complete()}catch{T.release()}pt()}T=null}}if(I){let o=e.chat?.state.ledger.filter(c=>c.kind==="answer"&&c.receipt.form==="assumed").length??0,u=xt+o,s=e.chat?.state.credits?.total;e.onSummary?.({state:"complete",facts:[`saved ${Y} use-case${Y===1?"":"s"} across ${U.length} source${U.length===1?"":"s"}`,...u>0?[`${u} assumed default(s)`]:[],...s!==void 0?[`credits used: ${s.toFixed(1)}`]:[]],tracePath:te(_)})}if(r.plan||nr(e.contextDir),de>0&&(T||Oe)){Pe=!0;let o=T?.state.sid??Oe,u=`kane-cli context extract --resume ${o} --mode ${a}`;if(I||e.out(`paused: ${de} held item(s) await review \u2014 resume with: ${u}`),e.emit?.({type:"session_paused",sid:o,resume:u,held:de}),I){let s=e.chat?.state.credits?.total;e.onSummary?.({state:"paused",reason:"held for review",facts:[`${de} held item(s) await your review`,...s!==void 0?[`credits used: ${s.toFixed(1)}`]:[]],resume:u,tracePath:te(_)})}return T?.release(),3}return q.length>0&&e.out(`${q.length} of ${U.length} source(s) failed \u2014 re-run kane-cli context extract to retry (${q.join(", ")})`),_t(),q.length>0?1:0}export{mt as a,$r as b,hr as c,pr as d,Rr as e,gr as f,Ss as g};
@@ -0,0 +1,13 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{d as ot,g as st}from"./chunk-5DBK6QNS.js";import{b as w,c as ne,d as Ze,f as ie,g as oe}from"./chunk-CJJXT5DO.js";import{a as Qe,e as P,f as j,g as et,h as U,i as L,j as tt}from"./chunk-ZPDM6FO7.js";import{a as M,b as T,d as qe}from"./chunk-EHN5HTUD.js";import{d as at}from"./chunk-NVGBE2DR.js";import{a as W}from"./chunk-CH273NAE.js";import{a as R,b as _}from"./chunk-L5LI2JF4.js";import{a as te,c as We,d as Je,e as Xe,f as re}from"./chunk-6IA6QMPH.js";import{A as x}from"./chunk-TH47OOBV.js";import{b as K}from"./chunk-VAYBKR76.js";import{a as nt}from"./chunk-CUM23TLF.js";import{b as it,f as G,i as Y}from"./chunk-DUAXZYAD.js";import{d as se,f as rt}from"./chunk-WXHQYYD5.js";import{a as Ye,b as Ke}from"./chunk-NHBYZCSX.js";import{a as Ge}from"./chunk-LVN6VHFN.js";import{a as Ue}from"./chunk-7F2ZV46B.js";function C(t){if(t===null)return"broken";let e=Math.floor(t/100);return e===1?"passed":e===7?"failed":e===2?"skipped":"broken"}var A={failed:3,broken:2,passed:1,skipped:0};function ae(t){let e="skipped";for(let r of t)A[r]>A[e]&&(e=r);return e}import{createHash as Vt}from"crypto";import{basename as Bt}from"path";function ce(t){let e=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40);return e.length>0?e:"session"}function de(t){return Vt("sha256").update(t).digest("hex").slice(0,8)}function ue(t){let e=Bt(t).replace(/_test\.md$/i,"").replace(/\.md$/i,"");return`${ce(e)}-${de(t)}`}function le(t,e){return`${ce(t)}-${de(e)}`}function pe(t){let e={};for(let[r,n]of Object.entries(t))typeof n=="string"&&n.length>0&&(e[r]=n);return e}function Ht(t,e){return{pack_test_dir:t,ordinal_offset:e}}import{promises as k}from"fs";import{join as E}from"path";function fe(t){let e={evidence:"0.1",run_id:t.execution_id,status:"running",title:t.title,started:t.started,environment:{producer:{name:"kane-cli",version:t.producerVersion},...t.surfaces?{surfaces:t.surfaces}:{},run_kind:t.run_kind,origin:t.origin,pid:t.pid},...t.credits!==void 0?{metrics:{credits:{value:t.credits,type:"count"}}}:{}};return _(e,{lineWidth:-1})}async function me(t,e,r,n=process.cwd(),i){let o=i??w(t.execution_id,n),s=E(o,"tests",e);return await k.mkdir(E(o,"coverage"),{recursive:!0}),await k.writeFile(E(o,"coverage",".keep"),""),await k.mkdir(s,{recursive:!0}),await k.writeFile(E(o,"run.yaml"),fe(t)),r&&await k.writeFile(E(s,r.path),r.content),o}async function zt(t,e=process.cwd()){let r=w(t.execution_id,e);await k.mkdir(E(r,"coverage"),{recursive:!0}),await k.writeFile(E(r,"coverage",".keep"),"");let n=R(fe(t));return n.environment&&delete n.environment.run_kind,await k.writeFile(E(r,"run.yaml"),_(n,{lineWidth:-1})),r}async function Ut(t,e=process.cwd()){return T(w(t,e),new Date().toISOString())}async function ge(t,e=process.cwd()){await k.rm(w(t,e),{recursive:!0,force:!0})}import{promises as he}from"fs";import{join as ve}from"path";function J(t){let e={evidence:"0.1",test:t.testId,status:t.status,...t.durationMs!==void 0?{duration_ms:t.durationMs}:{},...t.attempts&&t.attempts.length?{attempts:t.attempts}:{},...t.flaky!==void 0?{flaky:t.flaky}:{},...t.definitionPath?{definition:{path:t.definitionPath}}:{},...t.definitionId?{definition_id:t.definitionId}:{},...t.assuranceId?{assurance_id:t.assuranceId}:{},...Object.keys(t.externalId).length?{external_id:t.externalId}:{},...t.tags&&t.tags.length?{tags:t.tags}:{},...Object.keys(t.environment).length?{environment:t.environment}:{},steps:t.steps};return _(e,{lineWidth:-1})}function ye(t){return _({logs:t},{lineWidth:-1})}async function we(t,e,r){await he.writeFile(ve(t,"tests",e,"result.yaml"),r)}async function _e(t,e,r){let n=ve(t,"tests",e,"logs");await he.mkdir(n,{recursive:!0}),await he.writeFile(ve(n,"meta.yaml"),r)}import{promises as X}from"fs";import{join as ct}from"path";function dt(t){return ct(t,".internal","meta.json")}async function ut(t){let e;try{e=await X.readFile(dt(t),"utf8")}catch(n){if(n?.code==="ENOENT")return null;throw n}let r=JSON.parse(e);if(!r||typeof r!="object"||Array.isArray(r))throw new Error("meta.json is not a JSON object");return r}async function xe(t,e){let r;try{r=await ut(t)??{}}catch(s){console.warn(`evidence: meta.json at ${t} unreadable \u2014 skipping execution-pointer append to preserve identity`,s);return}let n=Array.isArray(r.executions)?r.executions:[];n.push(e),r.executions=n,await X.mkdir(ct(t,".internal"),{recursive:!0});let i=dt(t),o=`${i}.tmp-${process.pid}-${Date.now()}`;await X.writeFile(o,JSON.stringify(r,null,2)+`
3
+ `),await X.rename(o,i)}async function Gt(t){try{let e=await ut(t);return e&&Array.isArray(e.executions)?e.executions:[]}catch{return[]}}async function Yt(t,e,r=process.cwd()){let n=await ie(t,r);if(!n){let o=`evidence: no pack found for "${t}"`;return e.json?console.log(JSON.stringify({valid:!1,error:"not_found",target:t})):console.error(o),2}let i=await M(n,e.profile??"L1");return e.json?console.log(JSON.stringify({valid:i.valid,status:i.status,diagnostics:i.diagnostics})):console.log(`evidence: ${i.valid?"valid":"INVALID"} (${e.profile??"L1"}, status ${i.status})`),i.valid?0:1}function ke(t){let e=[];for(let r of t){let n=r.perFlow&&r.perFlow.length?r.perFlow.map(i=>i.resultCode):[r.resultCode];for(let i of n)e.push(C(i))}return ae(e)}function Kt(t){let e=null;for(let r of t){let n=r.perFlow&&r.perFlow.length?r.perFlow.map(i=>i.resultCode):[r.resultCode];for(let i of n)i!=null&&(e==null||A[C(i)]>A[C(e)]||A[C(i)]===A[C(e)]&&i>e)&&(e=i)}return e}import{promises as Wt}from"fs";import{extname as lt,basename as Jt}from"path";var Xt={".ndjson":"ndjson",".log":"log",".json":"json",".har":"har"};async function be(t){let e;try{e=await Wt.readdir(t)}catch{return[]}return e.filter(r=>r!=="meta.yaml").sort().map(r=>({name:Jt(r,lt(r)),file:r,format:Xt[lt(r)]??"txt"}))}import{mkdirSync as qt,appendFileSync as Zt}from"fs";import{join as pt}from"path";function Se(t,e){return pt(t,"tests",e,"logs")}function Ee(t,e,r,n={},i){try{i?.(e,r,r,n)}catch{}if(t)try{qt(t,{recursive:!0});let o=JSON.stringify({ts:new Date().toISOString(),level:e,event:r,...n})+`
4
+ `;Zt(pt(t,"diagnostics.ndjson"),o)}catch{}}import{promises as I}from"fs";import{dirname as ar,join as D}from"path";import{statSync as Qt}from"fs";import{promises as Ie}from"fs";import{basename as er,join as tr}from"path";var rr=1e6,nr=2e6;function ir(){return Ye.map(t=>Ke(t))}function ft(t=ir()){return t.map(e=>{let r=0;try{r=Qt(e).size}catch{}return{path:e,offset:r}})}var or=/\x1b\[[0-9;]*[A-Za-z]/g;async function sr(t,e,r){let n;try{n=await Ie.open(t,"r");let i=(await n.stat()).size,o=e<=i?e:0,s=i-o;if(s<=0)return null;let a=s>r?i-r:o,c=Buffer.alloc(Math.min(s,r));return await n.read(c,0,c.length,a),c.toString("utf8")}catch{return null}finally{await n?.close().catch(()=>{})}}async function mt(t,e){let r=e.caps?.stderr??rr,n=e.caps?.appium??nr,i=[];e.runnerStderrPath&&i.push({src:e.runnerStderrPath,from:0,cap:r});for(let o of e.appiumMarks??[])i.push({src:o.path,from:o.offset,cap:n});for(let o of i){let s=await sr(o.src,o.from,o.cap);if(s===null)continue;let a=s.replace(or,"");if(a!=="")try{await Ie.mkdir(t,{recursive:!0}),await Ie.writeFile(tr(t,er(o.src)),a)}catch{}}}async function cr(t){try{let e=D(t,"tests"),r=await I.readdir(e).catch(()=>[]);for(let n of r){let i=D(e,n,"steps"),o=await I.readdir(i).catch(()=>[]);for(let s of o){let a=await I.readFile(D(i,s,"failure.yaml"),"utf8").catch(()=>null);if(a!=null)try{let c=R(a);if(c&&typeof c=="object"&&c.triage)return!0}catch{}}}}catch{}return!1}async function gt(t,e,r,n={}){let i=D(t,"tests",e,"logs");if(r)try{await I.mkdir(i,{recursive:!0}),await I.copyFile(r,D(i,"tui.log"))}catch{}await mt(i,{runnerStderrPath:r?D(ar(r),"runner-stderr.log"):void 0,appiumMarks:n.appiumMarks});let o=await be(i);if(!o.length&&n.requireRealLog)throw new Error(`evidence test ${e} has no real log to declare`);o.length&&await _e(t,e,ye(o))}async function Re(t){let e=t.cwd??process.cwd(),r=t.packDir??w(t.executionId,e);if(!t.saved&&!t.packDir)return await ge(t.executionId,e),{sealed:!1};await gt(r,t.testId,t.tuiLogPath,{requireRealLog:t.requireRealLog,appiumMarks:t.appiumMarks});let n=D(r,"run.yaml"),i=R(await I.readFile(n,"utf8"));i.environment={...i.environment??{},saved:t.saved,run_kind:t.runKind},await I.writeFile(n,_(i,{lineWidth:-1}));let o=await I.open(n,"r+");try{await o.sync()}finally{await o.close()}let s=await cr(r);await T(r,new Date().toISOString());let a;try{let d=await M(r,"L1");a=d.valid;let u=(d.diagnostics??[]).filter(p=>String(p?.code??"").includes("failure.status_disagrees"));if(u.length>0)if(t.expectStatusDisagrees||s){let p=t.expectStatusDisagrees?"expected under --bug-detection continue":"self-explained by triaged failure record(s)";console.warn(`evidence: ${u.length} status_disagrees advisory(ies) \u2014 ${p}`)}else console.warn(`evidence: ${u.length} status_disagrees advisory(ies) \u2014 step verdicts disagree with their failure records`,u);if(!d.valid){console.warn(`evidence: sealed pack ${t.executionId} failed L1 validation`,d.diagnostics);let p=String(d.diagnostics?.[0]?.code??"");Ee(Se(r,t.testId),"warn","EVIDENCE_INVALID",{execution_id:t.executionId,first_code:p,surface:t.surface??"testmd"},t.log)}}catch(d){console.warn(`evidence: validation error for ${t.executionId}`,d)}let c;if(t.saved&&t.packDir)try{c=await Ze(r,t.executionId,e)}catch(d){console.warn(`evidence: store install failed for ${t.executionId}`,d)}if(t.outputStemDir)try{await xe(t.outputStemDir,{execution_id:t.executionId,run_kind:t.runKind,status:t.verdict,valid:a,at:new Date().toISOString()})}catch(d){console.warn(`evidence: execution-pointer append failed for ${t.executionId} (pack is sealed)`,d)}return{sealed:!0,valid:a,storePath:c}}import{release as ht}from"os";import{execFileSync as dr}from"child_process";var vt=!1,q;function ur(){if(!vt)if(vt=!0,process.platform==="darwin")try{q=dr("sw_vers",["-productVersion"],{timeout:2e3}).toString().trim()||void 0}catch{q=ht()||void 0}else q=ht()||void 0;return q}function Pe(t){let e={os:te(process.platform)},r=ur();if(r&&(e.os_version=r),t.cdpBrowser){let n=/^([A-Za-z]+)\/(\d+)/.exec(t.cdpBrowser);n&&(e.browser=n[1].replace(/^Headless/,""),e.browser_version=n[2])}return t.resolution&&(e.resolution=t.resolution),Je(e,t.runnerEnvironment)}async function yt(t){if(t)try{let e=await fetch(`${t}/json/version`,{signal:AbortSignal.timeout(2e3)});if(!e.ok)return;let r=await e.json();return typeof r.Browser=="string"?r.Browser:void 0}catch{return}}function lr(t){let e;return()=>(e||(e=yt(t)),e)}import{promises as $,existsSync as O,readFileSync as gr}from"fs";import{basename as hr,join as h}from"path";import{readFileSync as pr}from"fs";import{dirname as fr,resolve as mr}from"path";function wt(t,e){let r=mr(t),n=pr(r,"utf8");return P(e?j(n,U(fr(r),e)):n)}var N=class t{constructor(e){this.opts=e}executionId;testId;definitionPath=null;definitionContent=null;accumulatedSteps=[];maxOrdinal=0;_attempts=[];_packDirOverride;_attached=!1;appiumMarks=ft();get attached(){return this._attached}static async attach(e){let r=hr(e.packDir).replace(/\.evidence$/,""),n=new t({origin:"testrun",runKind:"author",pid:process.pid,title:e.testId,started:new Date().toISOString(),producerVersion:Ue,cwd:e.cwd});n.executionId=r,n.testId=e.testId,n._packDirOverride=e.packDir,n._attached=!0;let i=h(e.packDir,"tests",e.testId);return await $.mkdir(i,{recursive:!0}),e.definition&&(await $.writeFile(h(i,e.definition.path),e.definition.content),n.definitionPath=e.definition.path,n.definitionContent=e.definition.content),n}async start(){if(this._attached)throw new Error("attach-mode session is already started");this.executionId=ne(),this.testId=this.opts.testmdRelPath?ue(this.opts.testmdRelPath):le(this.opts.objectiveOrName??"session",this.opts.sessionId??this.executionId);let e=this.opts.definition??null;return await me({execution_id:this.executionId,title:this.opts.title,started:this.opts.started,producerVersion:this.opts.producerVersion,surfaces:this.opts.surfaces,run_kind:this.opts.runKind,origin:this.opts.origin,pid:this.opts.pid,...this.opts.credits!==void 0?{credits:this.opts.credits}:{}},this.testId,e,this.opts.cwd,this.opts.packRootDir?this.pack:void 0),e&&(this.definitionPath=e.path,this.definitionContent=e.content),{executionId:this.executionId,testId:this.testId,packTestDir:this.packTestDir}}get pack(){return this._packDirOverride?this._packDirOverride:this.opts.packRootDir?h(this.opts.packRootDir,`${this.executionId}.evidence`):w(this.executionId,this.opts.cwd)}get packTestDir(){return h(this.pack,"tests",this.testId)}async writeDefinition(e,r="test.md"){await $.writeFile(h(this.packTestDir,r),e),this.definitionPath=r,this.definitionContent=e}computeAssuranceId(){try{if(this.opts.testmdRelPath&&this.opts.cwd){let e=h(this.opts.cwd,this.opts.testmdRelPath);if(O(e))return L(gr(e,"utf8"))?.id}}catch{}}computeDefinitionId(){try{if(this.opts.testmdRelPath&&this.opts.cwd){let e=h(this.opts.cwd,this.opts.testmdRelPath),r=h(this.opts.cwd,".context"),n=O(r)?x(r):void 0;if(O(e))return wt(e,n)}if(this.definitionContent!=null)return P(this.definitionContent)}catch{}}noteSpawn(e){this.accumulatedSteps.push(...e.steps),this.maxOrdinal=Math.max(this.maxOrdinal,e.maxOrdinal)}nextOrdinalOffset(){return this.maxOrdinal}get steps(){return this.accumulatedSteps}get attempts(){return this._attempts}async archiveAttempt(e,r){let n=this._attempts.length+1,i=h(this.packTestDir,String(n));try{await $.mkdir(i,{recursive:!0});for(let o of["steps","logs","v16-trajectory"]){let s=h(this.packTestDir,o);O(s)&&await $.rename(s,h(i,o))}this.definitionPath&&O(h(this.packTestDir,this.definitionPath))&&await $.copyFile(h(this.packTestDir,this.definitionPath),h(i,this.definitionPath))}catch{}return this._attempts.push({n,status:e,steps:this.accumulatedSteps,...r!==void 0?{durationMs:r}:{}}),this.accumulatedSteps=[],this.maxOrdinal=0,n}async writeResult(e){let r=ke(e.spawns),n=this._attempts.length?[...this._attempts.map(u=>({status:u.status,...u.durationMs!==void 0?{duration_ms:u.durationMs}:{}})),{status:r,...e.durationMs!==void 0?{duration_ms:e.durationMs}:{}}]:void 0,i=n?new Set(n.map(u=>u.status)).size>1:void 0,o=this.pack,s=pe(e.externalIdInput),a=re(e.runnerEnv,e.intentEnv),c=this.computeDefinitionId(),d=this.computeAssuranceId();await we(o,this.testId,J({testId:this.testId,status:r,durationMs:e.durationMs,definitionPath:this.definitionPath,definitionId:c,assuranceId:d,externalId:s,environment:a,steps:e.steps,tags:e.tags,attempts:n,flaky:i}));for(let u of this._attempts){let p=h(this.packTestDir,String(u.n));O(p)&&await $.writeFile(h(p,"result.yaml"),J({testId:this.testId,status:u.status,durationMs:u.durationMs,definitionPath:this.definitionPath,definitionId:c,assuranceId:d,externalId:s,environment:a,steps:u.steps,tags:e.tags}))}let l=e.externalIdInput;return e.log&&(l.commit_id||l.test_id||l.testcase_id)&&e.log("info","EVIDENCE_EXTERNAL_ID","Evidence external-id mapping",{execution_id:this.executionId,commit_id:l.commit_id??null,test_id:l.test_id??null,testcase_id:l.testcase_id??null,project_id:l.project_id??null,session_id:l.session_id??null,session_name:l.session_name??null}),r}get id(){return this.executionId}get test(){return this.testId}};async function vr(t,e,r=oe){try{let n=await r(t);if(n.aborted.length>0||n.removed.length>0)try{e?.("info","EVIDENCE_RECOVERY","Startup evidence recovery swept incomplete packs",{aborted:n.aborted,removed:n.removed,origin:"startup"})}catch{}return n}catch(n){return console.warn("evidence: startup recovery failed",n),{aborted:[],removed:[]}}}import{promises as jr}from"fs";import{existsSync as De,mkdirSync as Dr,readdirSync as $r,readFileSync as Lr,rmSync as Or,statSync as Fr,writeFileSync as Mr}from"fs";import{join as F}from"path";import{mkdirSync as yr,renameSync as wr,rmSync as _r,writeFileSync as xr}from"fs";import{join as _t}from"path";var kr=5e6;function xt(t,e,r){let n=_t(t,"coverage","sources"),i=new Map,o=!1;try{for(let s of r.usecases)for(let a of s.sources){if(i.has(a.id)){a.file=i.get(a.id);continue}if(!a.cid)continue;let c=at(e,a.cid);if(c===null||c.byteLength>kr)continue;o||(yr(n,{recursive:!0}),o=!0);let d=_t(n,a.id),l=`${d}.tmp-${process.pid}`;xr(l,c),wr(l,d);let u=`coverage/sources/${a.id}`;i.set(a.id,u),a.file=u}}catch{for(let s of r.usecases)for(let a of s.sources)delete a.file;if(o)try{_r(n,{recursive:!0,force:!0})}catch{}}}import{existsSync as Ce,readFileSync as V,renameSync as Ir,writeFileSync as Rr}from"fs";import{dirname as It,isAbsolute as Rt,resolve as Pt}from"path";var br=new Set(["inline","testmd","testrun"]),Sr=new Set(["inferred","authored","runtime-derived"]),Ae=new Set(["passed","failed","broken","skipped"]);function kt(t,e,r){if(r.facts.length===0)return{record:null,errors:[{code:"EMPTY_EXECUTIONS",detail:"a run with no designed units attaches no facts \u2014 skip the call"}]};let n=e;for(let i=0;;i++){let o=G(t);if(n.latestHash!==o){if(i>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:`graph opened at ${String(n.latestHash)} but chain head is ${String(o)} \u2014 retry budget exhausted`}]};n=x(t);continue}let s=Er(t,n,r);if(s!=="cas")return s;if(i>=3)return{record:null,errors:[{code:"STALE_BASIS",detail:"concurrent appends kept moving the head \u2014 retry budget exhausted"}]};n=x(t)}}function Er(t,e,r){let n=[],i=[];for(let s of r.facts){let a=`executions[${s.ref}]`,c=e.resolve(s.ref),d=c?e.tipOf(c.cid):null;if(!c||!d||e.superseded.has(d)){n.push({code:"UNKNOWN_REF",detail:`${a}: '${s.ref}' is not a live committed node`});continue}if(e.nodeLabel.get(d)!==se.TEST){n.push({code:"ILLEGAL_TARGET",detail:`${a}: execution facts attach to tests \u2014 '${s.ref}' is a ${e.nodeLabel.get(d)}`});continue}if(!br.has(s.mode)){n.push({code:"BAD_MODE",detail:`${a}: mode '${s.mode}' not in inline|testmd|testrun`});continue}if(!Ae.has(s.verdict)){n.push({code:"BAD_VERDICT",detail:`${a}: verdict '${s.verdict}' not in ${[...Ae].join("|")}`});continue}if(!Sr.has(s.oracle_mode)){n.push({code:"BAD_ORACLE_MODE",detail:`${a}: oracle_mode '${s.oracle_mode}' not in inferred|authored|runtime-derived`});continue}if(typeof s.drift_flag!="boolean"||typeof s.stale_at_run!="boolean"){n.push({code:"MISSING_FIELD",detail:`${a}: drift_flag and stale_at_run are required booleans`});continue}if(!s.execution_id||!s.started_at||!s.definition_id_at_run){n.push({code:"MISSING_FIELD",detail:`${a}: execution_id, started_at and definition_id_at_run are required`});continue}let l=[];for(let u of s.per_ac??[]){let p=e.resolve(u.ac_ref),f=p?e.tipOf(p.cid):null;if(!p||!f||e.superseded.has(f)||e.nodeLabel.get(f)!==se.AC){n.push({code:"UNKNOWN_REF",detail:`${a}.per_ac: '${u.ac_ref}' is not a live AC`});continue}if(!Ae.has(u.verdict)){n.push({code:"BAD_VERDICT",detail:`${a}.per_ac['${u.ac_ref}']: verdict '${u.verdict}'`});continue}l.push({ac_ref:e.nameOf.get(f)??f,verdict:u.verdict})}i.push({about:d,definition_id_at_run:s.definition_id_at_run,verdict:s.verdict,...l.length?{per_ac:l}:{},drift_flag:s.drift_flag,oracle_mode:s.oracle_mode,stale_at_run:s.stale_at_run,...s.unresolved_acs?.length?{unresolved_acs:s.unresolved_acs}:{},execution_id:s.execution_id,...s.evidence_id?{evidence_id:s.evidence_id}:{},...s.duration_ms!==void 0?{duration_ms:s.duration_ms}:{},started_at:s.started_at,mode:s.mode,local:s.local,...s.via_parent?{via_parent:s.via_parent}:{}})}if(n.length>0)return{record:null,errors:n};let o;try{o=Y(t,{ts:new Date().toISOString(),proposal_id:null,nodes:[],edges:[],review:[],supersessions:[],executions:i,...r.eventIds&&r.eventIds.length>0?{event_ids:r.eventIds}:{},source_head_moves:{}},{expectPrev:e.latestHash})}catch(s){if(s instanceof it)return"cas";throw s}return K(t),{record:o.record,errors:null}}function At(t){let e={failed:3,broken:2,skipped:1,passed:0},r=new Map;for(let n of t)for(let i of n.verifies??[]){let o=r.get(i);(o===void 0||(e[n.status]??0)>(e[o]??0))&&r.set(i,n.status)}return[...r.entries()].map(([n,i])=>({ref:n,verdict:i}))}function Ct(t){let e=[],r=W(t.cwd);if(!Ce(r))return{synced:0,superseded:0,skipped:"no-context",warnings:e};let n=t.by??{kind:"ai",id:"exec-sync"},i=x(r),o=[],s=0,a=new Set;for(let d of t.members){let l=Rt(d.path)?d.path:Pt(t.cwd,d.path);for(let u of Pr(l)){if(a.has(u.path))continue;a.add(u.path);let p=u.path===l?void 0:L(V(l,"utf8"))?.id,f=V(u.path,"utf8"),m=L(f);if(!m?.id)continue;let g=i.resolve(m.id),b=g?i.tipOf(g.cid):null;if(!g||!b||i.superseded.has(b)){e.push(`sync: ${m.id} does not resolve to a live test \u2014 skipped (foreign store?)`);continue}let S=P(j(f,U(It(u.path),i))),v=String(i.getNode(b)?.content.test_md_blob??""),H=P(j(v,et(i))),z=!1,ee=b;if(S===H)m.base!==H&&Et(u.path,f,H,e);else if(m.base===H){let y=Ar(r,i,b,f,S,n);y.error?(e.push(`sync: could not supersede ${m.id}: ${y.error}`),z=!0):(s++,ee=y.newCid,z=y.oracleTier,Et(u.path,V(u.path,"utf8"),S,e),i=x(r))}else z=!0,e.push(m.base?`sync: ${m.id} was edited from an older version \u2014 graph kept; reconcile via a redesign or maintain`:`sync: ${m.id} carries no base pin (hand-copied file?) \u2014 fact attached with drift flag`);let Ve=i.getNode(ee)?.content.check,Be=u.path===l?d.acs??[]:[],He=Be.filter(y=>bt(i,y.ref)),ze=Be.filter(y=>!bt(i,y.ref)).map(y=>y.ref);o.push({ref:m.id,definition_id_at_run:S,verdict:d.verdict,...He.length?{per_ac:He.map(y=>({ac_ref:y.ref,verdict:y.verdict}))}:{},drift_flag:z,oracle_mode:Ve?.expected_mode??(Qe(Ve?.operand)?"runtime-derived":"inferred"),stale_at_run:i.stale(ee)!=="fresh",...ze.length?{unresolved_acs:ze}:{},execution_id:d.executionId,...d.evidenceId?{evidence_id:d.evidenceId}:{},...d.durationMs!==void 0?{duration_ms:d.durationMs}:{},started_at:d.startedAt,mode:d.mode,local:d.local,...p?{via_parent:p}:{}})}}if(o.length===0)return{synced:0,superseded:s,warnings:e};let c=kt(r,x(r),{facts:o,by:n});return c.errors?(e.push(...c.errors.map(d=>`sync facts: ${d.code}: ${d.detail}`)),{synced:0,superseded:s,warnings:e}):{synced:o.length,superseded:s,warnings:e}}function Pr(t){let e=[],r=new Set,n=i=>{if(r.has(i)||!Ce(i))return;r.add(i);let o=V(i,"utf8");for(let s of o.split(`
5
+ `)){let a=/^@import\s+(\S+)\s*$/.exec(s.trim());if(!a)continue;let c=Rt(a[1])?a[1]:Pt(It(i),a[1]);Ce(c)&&L(V(c,"utf8"))?.id&&n(c)}e.push({path:i})};return n(t),e}function bt(t,e){let r=t.resolve(e),n=r?t.tipOf(r.cid):null;return!!(r&&n&&!t.superseded.has(n)&&t.nodeLabel.get(n)==="ac")}function Ar(t,e,r,n,i,o){let s=e.getNode(r);if(!s)return{oracleTier:!1,error:"tip unreadable"};let a=tt(n),c=String(s.content.test_md_blob??""),d=/^#\s+(.+?)\s*$/m.exec(a)?.[1]??String(s.content.title??""),l={...s.content,test_md_blob:a,definitionId:i,title:d},u=rt("test",l);if(u.length>0)return{oracleTier:!1,error:u.map(g=>g.detail).join("; ")};let p=nt("test",l);if(p===r)return{newCid:r,oracleTier:!1};let f=St(c)!==St(a),m=G(t);if(e.latestHash!==m)return{oracleTier:f,error:`store advanced under the sync (basis ${String(e.latestHash)} vs head ${String(m)}) \u2014 re-run to retry`};try{Y(t,{ts:new Date().toISOString(),proposal_id:null,nodes:[{cid:p,label:"test",content:l}],edges:[],review:[{id:p,kind:"review-item",resolution:"edited",edit:null,reason:"edited on disk (run sync)",by:o}],supersessions:[{kind:"node",old:r,new:p,reason:"edited on disk (run sync)",by:o}],source_head_moves:{}},{expectPrev:m})}catch(g){return{oracleTier:f,error:g instanceof Error?g.message:String(g)}}return K(t),{newCid:p,oracleTier:f}}var Cr=/\s@verifies\s+(ac-[\w.:\/-]+(?:\s*,\s*ac-[\w.:\/-]+)*)\s*$/;function St(t){let e=[],r=t.split(`
6
+ `),n=!1;for(let i of r){if(/^##\s/.test(i)){n=/\bassert\b/i.test(i);let o=Cr.exec(i);o&&e.push(`v:${o[1].trim()}`);continue}n&&i.trim()!==""&&e.push(i.trim())}return e.join(`
7
+ `)}function Et(t,e,r,n){try{let i=e.split(`
8
+ `),o=-1;if(i[0]?.trim()==="---"){for(let c=1;c<i.length;c++)if(i[c].trim()==="---"){o=c;break}}if(o<0)return;let s=!1;for(let c=1;c<o;c++){if(/^\s+base:\s*sha256:[0-9a-f]+\s*$/.test(i[c])){i[c]=i[c].replace(/sha256:[0-9a-f]+/,r),s=!0;break}if(/^assurance:\s*$/.test(i[c])&&!i.slice(c,Math.min(c+3,o)).some(d=>/^\s+base:/.test(d))){i.splice(c+2,0,` base: ${r}`),s=!0;break}}if(!s)return;let a=`${t}.tmp-sync`;Rr(a,i.join(`
9
+ `)),Ir(a,t)}catch(i){n.push(`sync: pin refresh failed for ${t} (${i instanceof Error?i.message:String(i)}) \u2014 next run self-heals`)}}var Tr={passed:"passed",failed:"failed",broken:"blocked",skipped:"not-run"},Dt=(t,e)=>{try{if(!De(e))return{status:"skipped",reason:"no context store at the project root"};let r=F(t,"tests");if(!De(r))return{status:"skipped",reason:"pack has no tests/"};let n=new Map;for(let a of $r(r)){let c=F(r,a,"result.yaml");if(!De(c)||!Fr(F(r,a)).isDirectory())continue;let d=R(Lr(c,"utf8"));if(!d?.definition_id&&!d?.assurance_id)continue;let l=At(d.steps??[]),u={testShortId:String(d.test??a),execution:Tr[String(d.status)]??"not-run",...l.length?{acs:l}:{}};d.assurance_id&&n.set(`id:${d.assurance_id}`,u),d.definition_id&&n.set(`def:${d.definition_id}`,u)}let i=st(x(e),n,{scope:"run"}),o=ot(i);xt(t,e,i);let s=_({...i,rollup:o},{lineWidth:-1});return Dr(F(t,"coverage"),{recursive:!0}),Mr(F(t,"coverage","usecases.yaml"),s),{status:"written"}}catch(r){try{Or(F(t,"coverage","sources"),{recursive:!0,force:!0})}catch{}return{status:"skipped",reason:r instanceof Error?r.message:String(r)}}};async function Nr(t){try{let e=new N({origin:"inline",runKind:"author",pid:t.pid,title:t.title,started:new Date().toISOString(),producerVersion:t.producerVersion,surfaces:t.surfaces,objectiveOrName:t.objectiveOrName,sessionId:t.sessionId,cwd:t.cwd,packRootDir:t.packRootDir}),r=await e.start();return{session:e,...r,packDir:e.pack,spawns:[],startedAtMs:Date.now(),cwd:t.cwd}}catch(e){return console.warn("evidence: inline pack creation failed",e),null}}function Vr(t,e,r){if(!t)return;t.session.noteSpawn(e),e.resolution&&(t.resolution=e.resolution),t.runnerEnvironment=We(t.runnerEnvironment,e.runnerEnvironment);let n=(r?.per_flow_metadata??[]).map(i=>({resultCode:i?.result_code!=null?Number(i.result_code):null}));t.spawns.push({resultCode:r?.result_code!=null?Number(r.result_code):null,...n.length?{perFlow:n}:{}})}function Br(t){if(t)return{packTestDir:t.packTestDir,ordinalOffset:t.session.nextOrdinalOffset()}}async function Hr(t,e){if(!t)return null;if(t.finalized)return t.finalized;let r=(n,i,o)=>e.log?e.log("warn",n,i,o):console.warn(`evidence: ${i}`,o??"");try{if(e.recordedTestPath)try{await t.session.writeDefinition(await jr.readFile(e.recordedTestPath,"utf8"))}catch(s){r("EVIDENCE_DEFINITION_FAILED","could not attach synthesized test.md",{error:String(s)})}let n=e.cdpBrowserCapture?await e.cdpBrowserCapture():void 0,i=await t.session.writeResult({steps:t.session.steps,spawns:t.spawns.length?t.spawns:[{resultCode:null}],externalIdInput:{...e.externalIdInput,execution_id:t.executionId},runnerEnv:Pe({cdpBrowser:n,resolution:t.resolution,runnerEnvironment:t.runnerEnvironment}),intentEnv:Xe(e.model,t.runnerEnvironment),durationMs:e.durationMs??Date.now()-t.startedAtMs,log:e.log});try{if(e.recordedTestPath){let s=Ct({cwd:e.cwd??t.cwd??process.cwd(),members:[{path:e.recordedTestPath,verdict:i,executionId:t.executionId,startedAt:new Date(t.startedAtMs).toISOString(),mode:"inline",local:e.local??!1}]});for(let a of s.warnings)r("EXEC_SYNC",a)}}catch(s){r("EXEC_SYNC","exec-sync failed",{error:String(s)})}try{let s=(e.coverageWriter??Dt)(t.packDir,W(e.cwd??t.cwd??process.cwd()));s.status==="skipped"&&r("EVIDENCE_COVERAGE_SKIPPED",`coverage/usecases.yaml not written: ${s.reason}`)}catch(s){r("EVIDENCE_COVERAGE_SKIPPED","coverage writer threw",{error:String(s)})}let o=await Re({executionId:t.executionId,testId:t.testId,saved:e.saved,runKind:"author",verdict:i,cwd:e.cwd??t.cwd,packDir:t.packDir,tuiLogPath:e.tuiLogPath,log:e.log,surface:"inline",requireRealLog:!!t.runnerEnvironment?.native_platform,appiumMarks:t.session.appiumMarks});return t.finalized=o,e.log?.("info","EVIDENCE_SEALED","Inline pack sealed",{execution_id:t.executionId,verdict:i,valid:o.valid,pack:t.packDir,store_copy:o.storePath??null}),o}catch(n){return r("EVIDENCE_SEAL_FAILED","inline pack finalize failed",{error:String(n)}),null}}import{statSync as Wr,openSync as Jr,readSync as Xr,closeSync as qr}from"fs";import{basename as Zr,resolve as Qr}from"path";import{createServer as zr}from"http";import{createReadStream as Ur,promises as Gr}from"fs";import{randomBytes as Yr}from"crypto";var Z="127.0.0.1";function $t(t,e){if(!t)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!r)return null;let[,n,i]=r;if(n===""&&i==="")return null;if(n===""){let a=Number(i);return a===0||e===0?"unsatisfiable":{start:Math.max(0,e-a),end:e-1}}let o=Number(n);if(o>=e)return"unsatisfiable";let s=i===""?e-1:Math.min(Number(i),e-1);return s<o?null:{start:o,end:s}}async function $e(t){let e=Yr(16).toString("hex"),r=zr((i,o)=>{Kr(i,o,t,e).catch(()=>o.destroy())});await new Promise((i,o)=>{r.once("error",o),r.listen(t.port??0,Z,()=>{r.removeListener("error",o),i()})});let n=r.address().port;return{port:n,urlFor:i=>`http://${Z}:${n}/${e}/${encodeURIComponent(i)}`,close:()=>new Promise(i=>{r.close(()=>i()),r.closeAllConnections()})}}async function Kr(t,e,r,n){let i=t.url??"/",o=v=>{try{r.log?.("warn","EVIDENCE_SERVE_DENIED",{reason:v,path:i})}catch{}};if(t.headers.host!==`${Z}:${t.socket.localPort}`){o("host_mismatch"),e.writeHead(403).end();return}let s=t.headers.origin;if(s!==void 0&&!r.allowedOrigins.includes(s)){o("origin_denied"),e.writeHead(403).end();return}let a=s?{"Access-Control-Allow-Origin":s,Vary:"Origin","Access-Control-Expose-Headers":"Content-Range, Content-Length"}:{};if(t.method==="OPTIONS"){let v={...a,"Access-Control-Allow-Methods":"GET, HEAD, OPTIONS","Access-Control-Allow-Headers":"range","Access-Control-Max-Age":"86400"};t.headers["access-control-request-private-network"]==="true"&&(v["Access-Control-Allow-Private-Network"]="true"),e.writeHead(204,v).end();return}if(t.method!=="GET"&&t.method!=="HEAD"){e.writeHead(405,a).end();return}let c;try{let v=new URL(t.url??"/",`http://${Z}`).pathname.split("/");if(v.length!==3||v[1]!==n){o("bad_token"),e.writeHead(404,a).end();return}c=decodeURIComponent(v[2])}catch{o("not_found"),e.writeHead(404,a).end();return}let d=r.packs.get(c);if(!d){o("not_found"),e.writeHead(404,a).end();return}let l;try{let v=await Gr.stat(d);if(!v.isFile())throw new Error("not a file");l=v.size}catch{o("not_found"),e.writeHead(404,a).end();return}let u={...a,"Accept-Ranges":"bytes","Content-Type":"application/zip","Cache-Control":"no-store"};if(t.method==="HEAD"){e.writeHead(200,{...u,"Content-Length":String(l)}).end();return}let p=$t(t.headers.range,l);if(p==="unsatisfiable"){o("unsatisfiable"),e.writeHead(416,{...a,"Content-Range":`bytes */${l}`}).end();return}let[f,m,g]=p===null?[0,l-1,200]:[p.start,p.end,206],b={...u,"Content-Length":String(m-f+1)};if(g===206&&(b["Content-Range"]=`bytes ${f}-${m}/${l}`),e.writeHead(g,b),l===0){e.end();return}let S=Ur(d,{start:f,end:m});S.on("error",()=>e.destroy()),e.on("close",()=>S.destroy()),S.pipe(e)}function B(t,e){return(e??Ge(t).evidenceViewerUrl).replace(/\/+$/,"")}function Le(t,e){return`${e}/?pack=${encodeURIComponent(t)}`}function Oe(t){return`evidence: view locally with \`kane-cli evidence serve ${t}\``}async function en(t,e,r={}){let n=r.out??(l=>process.stdout.write(l+`
10
+ `)),i=l=>(n(`error: ${l}`),2);if(e.env!=="prod"&&e.env!=="stage")return i(`invalid --env: ${String(e.env)}`);if(e.port!==void 0&&(!Number.isInteger(e.port)||e.port<1||e.port>65535))return i("invalid --port: expected an integer 1-65535");let o;try{o=B(e.env,e.viewerUrl),new URL(o)}catch{return i(`invalid --viewer-url: ${e.viewerUrl}`)}if(t.length===0)return i("no pack paths given");let s=new Map;for(let l of t){let u=Qr(l),p;try{p=Wr(u)}catch{return i(`${l}: not found`)}if(p.isDirectory())return i(`${l}: is a directory \u2014 packs must be sealed .evidence files (run the execution to completion, or seal it, first)`);if(!p.isFile())return i(`${l}: not a regular file`);let f=Buffer.alloc(2),m=Jr(u,"r");try{Xr(m,f,0,2,0)}finally{qr(m)}if(f.toString("latin1")!=="PK")return i(`${l}: not a sealed evidence pack (zip magic missing)`);let g=Zr(u);if(s.has(g))return i(`duplicate pack basename: ${g} (URL names collide \u2014 rename one)`);s.set(g,u)}let a=r.log??((l,u,p)=>process.stderr.write(`warn: ${u} reason=${p.reason} path=${p.path}
11
+ `)),c;try{c=await $e({packs:s,allowedOrigins:[new URL(o).origin],port:e.port,log:a})}catch(l){return i(`could not bind 127.0.0.1${e.port?`:${e.port}`:""} \u2014 ${l.message}`)}n(`serving ${s.size} pack${s.size===1?"":"s"} on http://127.0.0.1:${c.port}`);for(let l of s.keys()){let u=c.urlFor(l);n(l),n(` pack ${u}`),n(` viewer ${Le(u,o)}`)}return n("press Ctrl-C to stop"),await(r.hold??tn)(),await c.close(),0}function tn(){return new Promise(t=>{let e=process.listeners("SIGINT");process.removeAllListeners("SIGINT"),process.once("SIGINT",()=>{for(let r of e)process.on("SIGINT",r);t()})})}import{promises as Q}from"fs";import{tmpdir as sn}from"os";import{join as Ft,resolve as Me}from"path";var rn=["error","prefer_first","prefer_latest","discard"],nn=["external_id.commit_id","external_id.test_id"];function Lt(t){let e=t.replace(/-/g,"_");return rn.includes(e)?e:null}function Ot(t){let e=t==="discard"?{on_collision:"discard"}:{on_collision:"error",identity:{keys:[...nn],on_same:t??"nest",on_different:t?"error":"split"}};return _({packs:{require_status:"finalized",require_valid:"L1",on_ineligible:"abort"},tests:e,rules:[{file:"run.yaml",key:"run_id",must:"different",on_violation:"skip"},{file:"result.yaml",key:"external_id.project_id",must:"same",on_violation:"error"},{file:"result.yaml",key:"external_id.org_id",must:"same",on_violation:"error"}]},{lineWidth:-1})}async function Fe(t){try{if(!t.isTTY){t.log(Oe(t.packPath));return}let e=B(t.env);await(t.renderPrompt??on)(t.packPath,e)}catch(e){try{t.log(`evidence view failed \u2014 ${e.message}`)}catch{}}}async function on(t,e){let r=await import("./react-QWOAB3TB.js"),{render:n}=await import("./build-JIKYOZUH.js"),{EvidenceViewOffer:i}=await import("./EvidenceViewOffer-L5FVBQNK.js");await new Promise(o=>{let s=n(r.default.createElement(i,{packPath:t,viewerBase:e,onDone:()=>{s.unmount(),o()}}),{stdout:process.stderr,exitOnCtrlC:!1})})}async function an(t,e,r=process.cwd(),n={}){let i=n.out??(p=>process.stdout.write(p+`
12
+ `)),o=n.err??(p=>process.stderr.write(p+`
13
+ `)),s=p=>(o(`evidence merge: ${p}`),2);if(!e.runId)return s("--run-id is required (merged identity is the caller's fact)");if(e.rules&&e.onCollision)return s("--rules and --on-collision are mutually exclusive");let a;if(e.onCollision!==void 0){let p=Lt(e.onCollision);if(!p)return s(`invalid --on-collision: ${e.onCollision} (expected error | prefer-first | prefer-latest | discard)`);a=p}let c=[];for(let p of t){let f=await cn(p,r);if(!f)return s(`no pack found for "${p}"`);c.push(f)}let d=e.out?Me(r,e.out):w(e.runId,r),l=null,u;e.rules?u=Me(r,e.rules):(l=await Q.mkdtemp(Ft(sn(),"kane-merge-rules-")),u=Ft(l,"merge-rules.yaml"),await Q.writeFile(u,Ot(a)));try{let p=await(n.mergeFn??qe)(c,{runId:e.runId,out:d,rulesPath:u,title:e.title,finalize:e.finalize});return e.json?i(JSON.stringify(p)):dn(i,p),p.output.finalized&&!e.json&&await(n.offer??Fe)({packPath:d,env:e.env,isTTY:n.isTTY??(!!process.stdin.isTTY&&!!process.stderr.isTTY),log:o}),0}catch(p){let f=p instanceof Error?p.message:String(p);return p?.code==="ABORT"?(o(`evidence merge: aborted \u2014 ${f}`),1):s(f)}finally{l&&await Q.rm(l,{recursive:!0,force:!0}).catch(()=>{})}}async function cn(t,e){let r=Me(e,t);if(await Mt(r))return r;let n=w(t,e);return await Mt(n)?n:null}async function Mt(t){try{return await Q.stat(t),!0}catch{return!1}}function dn(t,e){let{packs:r,tests:n,output:i}=e;t(`evidence: merged ${n.merged} tests from ${r.eligible.length} packs -> ${i.path} (${i.finalized?"sealed":"live"})`);for(let o of r.skipped)t(` skipped ${o.runId}: ${o.rule} \u2014 ${o.reason}`);for(let o of n.collisions){let s;o.action==="nest"?s=`nested into ${o.folder}, latest ${o.winner}`:o.action==="split"?s=`split into ${o.folder}`:s=`winner ${o.winner}`,t(` collision ${o.test}: ${s} (${o.rule})`)}for(let o of n.discarded)t(` discarded ${o}`)}import{copyFileSync as un,existsSync as Te,mkdirSync as ln}from"fs";import{join as Tt}from"path";function pn(t,e,r){try{let n=Tt(t,"auteur","execution.json");if(Te(n))return!0;for(let i of e)if(!(!i||!Te(i)))return ln(Tt(t,"auteur"),{recursive:!0}),un(i,n),!0}catch(n){try{r?.("debug","EVIDENCE_BLOB_COPY_FAILED","auteur execution blob copy failed",{operation:"ensureAuteurExecution",source:e.find(i=>i&&Te(i))??null,error:n instanceof Error?n.message:String(n)})}catch{}}return!1}import{readFileSync as fn}from"fs";import{join as mn}from"path";function Ne(t){let e=[],r=!0,n=o=>{if(o===null||typeof o!="object")return;let s=o;if(Array.isArray(s.operations))for(let a of s.operations){let c=a?.operation_id;typeof c=="string"&&c&&e.push(c)}if(Array.isArray(s.children)){s.content_type!=="generative_block"&&(r=!1);for(let a of s.children)n(a)}if(Array.isArray(s.branches)){r=!1;for(let a of s.branches){let c=a?.children;if(Array.isArray(c))for(let d of c)n(d)}}},i=t?.instructions;if(Array.isArray(i))for(let o of i)n(o);return{ids:e,linear:r}}function gn(t){return Ne(t).ids}function je(t,e){let r=new Set(e.map(a=>a.action_id).filter(Boolean)),n=-1;for(let a of r){let c=t.indexOf(a);c>n&&(n=c)}let i=e.reduce((a,c)=>Math.max(a,c.ordinal),0),o=new Set,s=[];for(let a of t.slice(n+1))r.has(a)||o.has(a)||(o.add(a),s.push({id:a,ordinal:++i,status:"skipped",action_id:a}));return s}function jt(t,e){let r=new Set(e),n=t.filter(o=>o.action_id);if(n.some(o=>r.has(o.action_id))||n.length>e.length)return null;let i=0;return t.map(o=>o.action_id?{...o,action_id:e[i++]}:o)}function hn(t,e){if(t.length>e.length)return!1;for(let r=0;r<t.length;r++)if(e[r]!==t[r].action_id)return!1;return!0}function vn(t,e,r,n=!0){if(e.length===0)return{steps:t,tail:[]};let i=(r&&n?jt(t,e):null)??t,o=i.filter(a=>a.action_id),s=new Set(e);return o.length>0&&o.every(a=>s.has(a.action_id))?{steps:i,tail:je(e,i)}:o.length>0&&!hn(o,e)?{steps:i,tail:[],unjoined:!0}:{steps:i,tail:je(e,i)}}function Nt(t){try{let e=fn(mn(t,"auteur","execution.json"),"utf8");return Ne(JSON.parse(e))}catch{return{ids:[],linear:!0}}}function yn(t){return Nt(t).ids}export{C as a,ae as b,ce as c,de as d,ue as e,le as f,pe as g,Ht as h,fe as i,me as j,zt as k,Ut as l,ge as m,J as n,ye as o,we as p,_e as q,xe as r,Gt as s,Yt as t,ke as u,Kt as v,be as w,Se as x,Ee as y,gt as z,Re as A,Pe as B,yt as C,lr as D,N as E,vr as F,At as G,Ct as H,Dt as I,Nr as J,Vr as K,Br as L,Hr as M,$t as N,$e as O,B as P,Le as Q,Oe as R,en as S,Fe as T,an as U,pn as V,Ne as W,gn as X,je as Y,jt as Z,vn as _,Nt as $,yn as aa};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as $e}from"./chunk-MK7JUOYV.js";import{a as te}from"./chunk-VHZ4S57N.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-KQZA2QSC.js";import{a as ve}from"./chunk-GYNTNKNB.js";import{b as ye}from"./chunk-DFS4RMVP.js";import{y as i}from"./chunk-ZUGCHQFC.js";import{a as k}from"./chunk-HCBYKLMW.js";import{a as s,b as o,i as Se,j as Te,k as ee}from"./chunk-C44QQJR4.js";import{a as V}from"./chunk-6YGTRKDT.js";import{e as R}from"./chunk-UR6MHSHU.js";var A=R(V(),1);var C=R(V(),1);function de(e){let t=e.flatMap(u=>[u,...u.children??[]]),n=t.filter(u=>u.status==="passed").length,l=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:n,failed:l,total:a}}function we(e){let t=$e(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[n,l]=(0,C.useState)(0),[a,u]=(0,C.useState)("idle"),c=(0,C.useRef)("idle"),v=(0,C.useRef)(0),S=(0,C.useRef)(!1),T=(0,C.useRef)(null),d=(0,C.useRef)(null),L=(0,C.useCallback)(h=>{c.current=h,u(h)},[]),O=(0,C.useCallback)(async h=>{let b=await e.getNextConfig(h);if(!b){L("done"),e.onAllComplete?.();return}let B=h?v.current+1:0;v.current=B,l(B),e.onStepStart?.(b,B),T.current=null,d.current=null,L("running"),await t.startRun(b,e.spawnOpts)},[t,e,L]);(0,C.useEffect)(()=>{S.current||(S.current=!0,O(null))},[]),(0,C.useEffect)(()=>{if(!t.lastRunEnd||t.lastRunEnd===T.current||c.current!=="running")return;T.current=t.lastRunEnd,c.current="transitioning",u("transitioning");let h=t.lastRunEnd,b=de(t.steps),B=t.bifurcationInfo,F={status:h.status==="passed"?"passed":"failed",duration_s:h.duration??0,reason:h.reason,runEnd:h,hadError:!1,stepsPassed:b.passed,stepsFailed:b.failed,stepsTotal:b.total,bifurcationFlows:B&&!B.isSingleFlow?B.flows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(F,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(F)},[t.lastRunEnd]),(0,C.useEffect)(()=>{if(!t.runError||t.runError===d.current||t.lastRunEnd||c.current!=="running")return;d.current=t.runError,c.current="transitioning",u("transitioning");let h=de(t.steps),b={status:"failed",duration_s:0,reason:t.runError,runEnd:null,hadError:!0,stepsPassed:h.passed,stepsFailed:h.failed,stepsTotal:h.total,bifurcationFlows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(b,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(b)},[t.runError,t.lastRunEnd]);let y=(0,C.useCallback)(()=>{t.cancelRun()},[t]);return{runner:t,currentStepIndex:n,phase:a,cancel:y}}var pe=R(V(),1);var ne=R(k(),1),Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function ke({label:e,hasBifurcation:t=!1}){let[n,l]=(0,pe.useState)(0),[a,u]=(0,pe.useState)(0);K(()=>{l(v=>(v+1)%Ee.length)},80),K(()=>{u(v=>(v+1)%4)},400);let c=e??(t?"Planning approach":"Analyzing objective");return(0,ne.jsxs)(s,{marginLeft:1,children:[(0,ne.jsxs)(o,{color:i.orange,children:[Ee[n]," "]}),(0,ne.jsxs)(o,{color:i.dim,children:[c,".".repeat(a+1)]})]})}function Ie(e){if(!e.isRunning||e.replayInfo)return null;let t=e.bifurcationInfo;if(t&&!t.isSingleFlow){let n=e.steps.findIndex(a=>a.status==="running");return(n===-1?e.cmInitCounts.length===0:n>=e.cmInitCounts.length)?{label:n>0?`Planning flow ${n+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(n=>n.children?.length)?null:{hasBifurcation:!!t}}var I=R(V(),1);var Ce=R(V(),1);var re=R(k(),1),He="#ffc580",Ue="#ffd9a8",Le="#ffffff";function oe({text:e,active:t=!0}){let[n,l]=(0,Ce.useState)(0),a=4;if(K(()=>{l(c=>(c+1)%(e.length+a*2))},t?80:null),!t)return(0,re.jsx)(o,{color:Le,children:e});let u=e.split("").map((c,v)=>{let S=n-a,T=Math.abs(v-S-a/2),d;return T<=a/2?d=He:T<=a?d=Ue:d=Le,(0,re.jsx)(o,{color:d,children:c},v)});return(0,re.jsx)(o,{children:u})}var _=R(k(),1),We={starting:i.orange,running:i.orange,passed:i.green,failed:i.red,cancelled:i.dim,timed_out:i.orange};function ie({currentStep:e,maxSteps:t,elapsed:n,status:l}){let a=We[l]??i.orange,u=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`;return(0,_.jsxs)(s,{marginLeft:3,children:[(0,_.jsx)(o,{color:i.dim,children:"Steps "}),(0,_.jsx)(o,{bold:!0,children:e}),(0,_.jsxs)(o,{color:i.dim,children:["/",t]}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Elapsed "}),(0,_.jsx)(o,{bold:!0,children:u}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Status "}),(0,_.jsx)(o,{bold:!0,color:a,children:l})]})}var Ve={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u2299"};function Oe(e){return Ve[e]??"\u25CF"}var q=R(k(),1);function fe({steps:e,flows:t,cmInitCounts:n,renderStep:l}){return(0,q.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,q.jsxs)(o,{color:i.dim,children:["\u2501\u2501 Bifurcated into ",t?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((a,u)=>(0,q.jsxs)(s,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,q.jsxs)(o,{color:i.orange,children:["Flow ",u+1,": ",t?.[u]??a.objective]}),n&&n[u]!=null&&(0,q.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",n[u]," checkpoints"]}),a.children&&a.children.length>0?a.children.map(c=>{let v=!!c.branchObjective,S=`f${u}-${c.childId??"p"}-${c.index}`;return v?(0,q.jsxs)(s,{flexDirection:"column",children:[l({...c,children:void 0},S),(c.children??[]).map(T=>(0,q.jsx)(s,{marginLeft:2,children:l(T,`${S}-${T.childId??"p"}-${T.index}`)},`${S}-${T.childId??"p"}-${T.index}`))]},`${S}-host`):l(c,S)}):a.status==="pending"&&(0,q.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})]},u))]})}var H=R(k(),1);function Pe({label:e,shimmer:t=!1}){return(0,H.jsxs)(s,{marginLeft:6,children:[(0,H.jsx)(te,{}),(0,H.jsx)(o,{children:" "}),t?(0,H.jsx)(oe,{text:e,active:!0}):(0,H.jsx)(o,{color:i.dim,children:e})]})}var De=R(V(),1);var me=R(k(),1);function ze(e,t){let n=[];for(let l of e.split(`
2
+ import{e as $e}from"./chunk-KKRNTSLL.js";import{a as te}from"./chunk-UODLRQQ4.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-YSSYT5F5.js";import{a as ve}from"./chunk-2ZZDNPFN.js";import{y as i}from"./chunk-7F2ZV46B.js";import{b as ye}from"./chunk-DFS4RMVP.js";import{a as k}from"./chunk-HCBYKLMW.js";import{a as s,b as o,i as Se,j as Te,k as ee}from"./chunk-C44QQJR4.js";import{a as V}from"./chunk-6YGTRKDT.js";import{e as R}from"./chunk-UR6MHSHU.js";var A=R(V(),1);var C=R(V(),1);function de(e){let t=e.flatMap(u=>[u,...u.children??[]]),n=t.filter(u=>u.status==="passed").length,l=t.filter(u=>u.status==="failed").length,a=t.filter(u=>u.status==="passed"||u.status==="failed").length;return{passed:n,failed:l,total:a}}function we(e){let t=$e(e.screenshotDispatcher,e.stepLogger,e.onReasoning,e.onStepComplete),[n,l]=(0,C.useState)(0),[a,u]=(0,C.useState)("idle"),c=(0,C.useRef)("idle"),v=(0,C.useRef)(0),S=(0,C.useRef)(!1),T=(0,C.useRef)(null),d=(0,C.useRef)(null),L=(0,C.useCallback)(h=>{c.current=h,u(h)},[]),O=(0,C.useCallback)(async h=>{let b=await e.getNextConfig(h);if(!b){L("done"),e.onAllComplete?.();return}let B=h?v.current+1:0;v.current=B,l(B),e.onStepStart?.(b,B),T.current=null,d.current=null,L("running"),await t.startRun(b,e.spawnOpts)},[t,e,L]);(0,C.useEffect)(()=>{S.current||(S.current=!0,O(null))},[]),(0,C.useEffect)(()=>{if(!t.lastRunEnd||t.lastRunEnd===T.current||c.current!=="running")return;T.current=t.lastRunEnd,c.current="transitioning",u("transitioning");let h=t.lastRunEnd,b=de(t.steps),B=t.bifurcationInfo,F={status:h.status==="passed"?"passed":"failed",duration_s:h.duration??0,reason:h.reason,runEnd:h,hadError:!1,stepsPassed:b.passed,stepsFailed:b.failed,stepsTotal:b.total,bifurcationFlows:B&&!B.isSingleFlow?B.flows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(F,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(F)},[t.lastRunEnd]),(0,C.useEffect)(()=>{if(!t.runError||t.runError===d.current||t.lastRunEnd||c.current!=="running")return;d.current=t.runError,c.current="transitioning",u("transitioning");let h=de(t.steps),b={status:"failed",duration_s:0,reason:t.runError,runEnd:null,hadError:!0,stepsPassed:h.passed,stepsFailed:h.failed,stepsTotal:h.total,bifurcationFlows:null,evidence:t.getEvidenceState()};if(!(e.onStepEnd?.(b,v.current)??!0)){L("done"),e.onAllComplete?.();return}O(b)},[t.runError,t.lastRunEnd]);let y=(0,C.useCallback)(()=>{t.cancelRun()},[t]);return{runner:t,currentStepIndex:n,phase:a,cancel:y}}var pe=R(V(),1);var ne=R(k(),1),Ee=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];function ke({label:e,hasBifurcation:t=!1}){let[n,l]=(0,pe.useState)(0),[a,u]=(0,pe.useState)(0);K(()=>{l(v=>(v+1)%Ee.length)},80),K(()=>{u(v=>(v+1)%4)},400);let c=e??(t?"Planning approach":"Analyzing objective");return(0,ne.jsxs)(s,{marginLeft:1,children:[(0,ne.jsxs)(o,{color:i.orange,children:[Ee[n]," "]}),(0,ne.jsxs)(o,{color:i.dim,children:[c,".".repeat(a+1)]})]})}function Ie(e){if(!e.isRunning||e.replayInfo)return null;let t=e.bifurcationInfo;if(t&&!t.isSingleFlow){let n=e.steps.findIndex(a=>a.status==="running");return(n===-1?e.cmInitCounts.length===0:n>=e.cmInitCounts.length)?{label:n>0?`Planning flow ${n+1}`:void 0,hasBifurcation:!0}:null}return e.cmInitCounts.length>0||e.steps.some(n=>n.children?.length)?null:{hasBifurcation:!!t}}var I=R(V(),1);var Ce=R(V(),1);var re=R(k(),1),He="#ffc580",Ue="#ffd9a8",Le="#ffffff";function oe({text:e,active:t=!0}){let[n,l]=(0,Ce.useState)(0),a=4;if(K(()=>{l(c=>(c+1)%(e.length+a*2))},t?80:null),!t)return(0,re.jsx)(o,{color:Le,children:e});let u=e.split("").map((c,v)=>{let S=n-a,T=Math.abs(v-S-a/2),d;return T<=a/2?d=He:T<=a?d=Ue:d=Le,(0,re.jsx)(o,{color:d,children:c},v)});return(0,re.jsx)(o,{children:u})}var _=R(k(),1),We={starting:i.orange,running:i.orange,passed:i.green,failed:i.red,cancelled:i.dim,timed_out:i.orange};function ie({currentStep:e,maxSteps:t,elapsed:n,status:l}){let a=We[l]??i.orange,u=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`;return(0,_.jsxs)(s,{marginLeft:3,children:[(0,_.jsx)(o,{color:i.dim,children:"Steps "}),(0,_.jsx)(o,{bold:!0,children:e}),(0,_.jsxs)(o,{color:i.dim,children:["/",t]}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Elapsed "}),(0,_.jsx)(o,{bold:!0,children:u}),(0,_.jsx)(o,{children:" "}),(0,_.jsx)(o,{color:i.dim,children:"Status "}),(0,_.jsx)(o,{bold:!0,color:a,children:l})]})}var Ve={click:"\u25CF",type:"\u229E",scroll:"\u2195",navigate:"\u2192",analyze:"\u25CE",assert:"\u25C8","if-else":"\u2442",select:"\u25BC",press_key:"\u21B5",wait:"\u2026",tool_call:"\u2299"};function Oe(e){return Ve[e]??"\u25CF"}var q=R(k(),1);function fe({steps:e,flows:t,cmInitCounts:n,renderStep:l}){return(0,q.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[(0,q.jsxs)(o,{color:i.dim,children:["\u2501\u2501 Bifurcated into ",t?.length??e.length," flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"]}),e.map((a,u)=>(0,q.jsxs)(s,{flexDirection:"column",marginTop:u>0?1:0,children:[(0,q.jsxs)(o,{color:i.orange,children:["Flow ",u+1,": ",t?.[u]??a.objective]}),n&&n[u]!=null&&(0,q.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",n[u]," checkpoints"]}),a.children&&a.children.length>0?a.children.map(c=>{let v=!!c.branchObjective,S=`f${u}-${c.childId??"p"}-${c.index}`;return v?(0,q.jsxs)(s,{flexDirection:"column",children:[l({...c,children:void 0},S),(c.children??[]).map(T=>(0,q.jsx)(s,{marginLeft:2,children:l(T,`${S}-${T.childId??"p"}-${T.index}`)},`${S}-${T.childId??"p"}-${T.index}`))]},`${S}-host`):l(c,S)}):a.status==="pending"&&(0,q.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})]},u))]})}var H=R(k(),1);function Pe({label:e,shimmer:t=!1}){return(0,H.jsxs)(s,{marginLeft:6,children:[(0,H.jsx)(te,{}),(0,H.jsx)(o,{children:" "}),t?(0,H.jsx)(oe,{text:e,active:!0}):(0,H.jsx)(o,{color:i.dim,children:e})]})}var De=R(V(),1);var me=R(k(),1);function ze(e,t){let n=[];for(let l of e.split(`
3
3
  `)){if(l===""){n.push("");continue}let a="";for(let u of l.split(" ")){let c=u;for(;c.length>t;)a&&(n.push(a),a=""),n.push(c.slice(0,t)),c=c.slice(t);a===""?a=c:a.length+1+c.length<=t?a+=" "+c:(n.push(a),a=c)}n.push(a)}return n}function je({text:e,maxLines:t=3}){let{stdout:n}=ee(),l=Math.max(20,(n?.columns??80)-7),a=!e.trim(),[u,c]=(0,De.useState)(!0);K(()=>c(T=>!T),500);let v=(a?"Thinking\u2026":e)+(u?"\u258C":" "),S=ze(v,l).slice(-t);for(;S.length<t;)S.push("");return(0,me.jsx)(s,{borderStyle:"round",borderColor:i.muted,paddingX:1,marginLeft:3,flexDirection:"column",children:S.map((T,d)=>(0,me.jsx)(o,{color:a?i.dim:i.secondary,wrap:"truncate-end",children:T.length?T:" "},d))})}var U=R(k(),1);function se({activity:e,describe:t,describeVisible:n}){return(0,U.jsxs)(U.Fragment,{children:[e?(0,U.jsx)(Pe,{label:e.label,shimmer:e.shimmer}):null,n?(0,U.jsx)(je,{text:t??""}):null]})}var r=R(k(),1);function le(e){for(let t of e){if(t.children&&t.children.length>0){let n=le(t.children);if(n)return n}if(t.status==="running")return t}}function z(e){return e.status==="running"&&!e.branchObjective&&(!e.children||e.children.length===0)}function Fe(e){let t=[];for(let n of e)z(n)||(n.children&&n.children.length>0?t.push({...n,children:Fe(n.children)}):t.push(n));return t}function ge(e,t){if(!e)return null;let n=e.objective??"";return n.length>0&&!/^Step \d+$/.test(n)?{label:n+"\u2026",shimmer:!1}:{label:t?"Looking at the screen\u2026":"Deciding next action\u2026",shimmer:!0}}function P({step:e,indent:t=2}){let n=e.actionType?Oe(e.actionType):null,l=e.status==="running",a=e.status==="passed",u=e.status==="failed",c=e.status==="pending"||e.status==="stopped",{stdout:v}=ee(),S=v?.columns??80,T=Math.max(20,S-t-21),d=e.objective??"",L=d.length>T?d.slice(0,T-1)+"\u2026":d,O=(e.duration??0)*1e3,y=e.duration!=null?O<1e3?`${Math.round(O)}ms`:`${(O/1e3).toFixed(1)}s`:"";return(0,r.jsxs)(s,{flexDirection:"column",children:[(0,r.jsxs)(s,{marginLeft:t,children:[(0,r.jsx)(s,{width:4,children:(0,r.jsxs)(o,{color:i.muted,children:[String(e.index).padStart(2," ")," "]})}),(0,r.jsx)(s,{width:3,children:l?(0,r.jsx)(te,{}):a?(0,r.jsx)(o,{color:i.green,bold:!0,children:"\u2713"}):u?(0,r.jsx)(o,{color:i.red,bold:!0,children:"\u2717"}):(0,r.jsx)(o,{color:i.muted,children:"\u25CB"})}),(0,r.jsx)(s,{flexGrow:1,children:l?(0,r.jsx)(oe,{text:L,active:!0}):u?(0,r.jsx)(o,{color:i.red,children:L}):c?(0,r.jsx)(o,{color:i.dim,children:L}):(0,r.jsx)(o,{color:i.dim,children:L})}),(a||u)&&n?(0,r.jsx)(s,{width:3,marginLeft:1,children:(0,r.jsx)(o,{color:i.muted,children:n})}):(0,r.jsx)(s,{width:3,marginLeft:1}),(0,r.jsx)(s,{width:7,justifyContent:"flex-end",children:(0,r.jsx)(o,{color:i.dim,children:y})})]}),e.children&&e.children.length>0&&(0,r.jsx)(s,{flexDirection:"column",children:e.children.map((h,b)=>(0,r.jsx)(P,{step:h,indent:t+2},`child-${b}`))})]})}function Xe(e){return e.type==="cm_init"?(0,r.jsx)(s,{marginLeft:2,paddingLeft:1,children:(0,r.jsxs)(o,{color:i.dim,children:["\u25AA Generated task with ",e.count," checkpoints"]})}):(0,r.jsx)(s,{marginLeft:2,paddingLeft:1,children:(0,r.jsx)(P,{step:e.step})})}function _e({steps:e,bifurcated:t,flows:n,cmInitCounts:l,maxSteps:a=50,staticSteps:u=!1,onStepCommit:c,describe:v,describeVisible:S,describeRevealing:T}){let d=(0,I.useRef)(new Set),L=(0,I.useRef)(!1),O=(0,I.useRef)(new Set),y=(0,I.useRef)(!1),h=(0,I.useRef)(new Set),b=(0,I.useRef)(0);(0,I.useEffect)(()=>{e.length===0&&b.current>0&&(d.current.clear(),L.current=!1,O.current.clear(),y.current=!1,h.current.clear()),b.current=e.length},[e.length]);let B=e.flatMap(p=>[p,...p.children??[]]),F=B.some(p=>p.status==="running"),M=B.some(p=>p.status==="failed"),X=B.length===0||B.every(p=>p.status==="pending"),Y=B.filter(p=>p.status==="passed"||p.status==="failed").length,N;X?N="starting":F?N="running":M?N="failed":N="passed";let J=(0,I.useRef)(null),[ce,he]=(0,I.useState)(0);(0,I.useEffect)(()=>{B.length===0||X?(J.current=null,he(0)):F&&J.current==null&&(J.current=Date.now())},[F,X,B.length]),(0,I.useEffect)(()=>{if(!F)return;let p=setInterval(()=>{J.current!=null&&he((Date.now()-J.current)/1e3)},500);return()=>clearInterval(p)},[F]);let ae=(0,I.useRef)(new Set),[,xe]=(0,I.useState)(0),be=(0,I.useRef)(!1);(0,I.useEffect)(()=>{if(!c||!u||t)return;let p=[];!be.current&&l&&l[0]!=null&&(be.current=!0,l[0]>0&&p.push({key:"cm_init_0",type:"cm_init",count:l[0]}));for(let g of e)(g.status==="passed"||g.status==="failed")&&!ae.current.has(g.index)&&(ae.current.add(g.index),p.push({key:`step_${g.index}`,type:"step",step:{...g,children:g.children?[...g.children]:void 0}}));if(p.length>0){for(let g of p)c(Xe(g));xe(g=>g+1)}},[e,t,l,u,c]),(0,I.useEffect)(()=>{if(!c||u)return;let p=d.current.size;if(!t&&!y.current&&l&&l[0]!=null&&(y.current=!0,l[0]>0&&c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:["\u25A0 Generated task with ",l[0]," checkpoints"]})}))),t&&n&&!L.current&&(L.current=!0,c((0,r.jsx)(o,{color:i.purple,children:"\u2501\u2501 Bifurcated into "+n.length+" flows \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"}))),t){let g=e.flatMap((x,f)=>{let m=x.children??[];return!O.current.has(f)&&m.length>0&&(O.current.add(f),c((0,r.jsx)(o,{color:i.purple,children:" Flow "+(f+1)+": "+(n?.[f]??"")})),l?.[f]!=null&&l[f]>0&&!h.current.has(f)&&(h.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",l[f]," checkpoints"]})})))),l?.[f]!=null&&l[f]>0&&O.current.has(f)&&!h.current.has(f)&&(h.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsxs)(o,{color:i.dim,children:[" \u25AA Generated task with ",l[f]," checkpoints"]})}))),m});for(let x of g){let f=`${x.childId??"p"}-${x.index}-${x.objective}`;if(!!x.branchObjective){d.current.has(f)||(d.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...x,children:void 0}})})));for(let $ of x.children??[]){let w=`child-${x.childId??"p"}-${x.index}-${$.childId??"p"}-${$.index}-${$.objective}`;d.current.has(w)||($.status==="passed"||$.status==="failed"||$.status==="stopped")&&(d.current.add(w),c((0,r.jsx)(s,{marginLeft:4,children:(0,r.jsx)(P,{step:$})})))}continue}d.current.has(f)||(x.status==="passed"||x.status==="failed"||x.status==="stopped")&&(d.current.add(f),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:x})})))}}else for(let g of e){let x=`${g.index}-${g.objective}`,f=!!g.branchObjective;f&&!d.current.has(x)&&(d.current.add(x),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...g,children:void 0}})})));for(let m of g.children??[]){let $=`child-${g.index}-${m.childId??"p"}-${m.index}-${m.objective}`;d.current.has($)||(m.status==="passed"||m.status==="failed"||m.status==="stopped")&&(d.current.add($),c((0,r.jsx)(s,{marginLeft:4,children:(0,r.jsx)(P,{step:m})})))}!f&&!d.current.has(x)&&(g.status==="passed"||g.status==="failed"||g.status==="stopped")&&(d.current.add(x),c((0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:{...g,children:void 0}})})))}d.current.size>p&&xe(g=>g+1)},[e,c,t,n,l]);let G=[];if(u&&!t)for(let p of e)ae.current.has(p.index)||G.push(p);else if(c&&!u)if(t)for(let p of e){let g=p.children??[],x=[];for(let f of g){let m=`${f.childId??"p"}-${f.index}-${f.objective}`,$=d.current.has(m);if(f.branchObjective){let w=(f.children??[]).filter(Q=>{let ue=`child-${f.childId??"p"}-${f.index}-${Q.childId??"p"}-${Q.index}-${Q.objective}`;return!d.current.has(ue)});(!$||w.length>0)&&x.push({...f,children:w})}else $||x.push(f)}x.length>0&&G.push({...p,children:x})}else for(let p of e){let g=`${p.index}-${p.objective}`,x=d.current.has(g),f=(p.children??[]).filter(m=>{let $=`child-${p.index}-${m.childId??"p"}-${m.index}-${m.objective}`;return!d.current.has($)});x?f.length>0&&G.push({...p,children:f}):G.push({...p,children:f})}if(!u){let p=c?G:e,g=le(p),x=ge(g,T);return(0,r.jsxs)(s,{flexDirection:"column",children:[t?c?p.length>0?(0,r.jsx)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:p.map((m,$)=>(0,r.jsx)(s,{flexDirection:"column",marginTop:$>0?1:0,children:m.children&&m.children.length>0?m.children.map(w=>{if(z(w))return null;let Q=!!w.branchObjective,ue=`${w.childId??"p"}-${w.index}-${w.objective}`,Ke=d.current.has(ue);return Q?(0,r.jsxs)(s,{flexDirection:"column",children:[!Ke&&(0,r.jsx)(P,{step:{...w,children:void 0}}),(w.children??[]).filter(Z=>!z(Z)).map(Z=>(0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:Z})},`f${$}-${w.index}-${Z.childId??"p"}-${Z.index}`))]},`f${$}-host-${w.childId??"p"}-${w.index}`):(0,r.jsx)(P,{step:w},`f${$}-${w.childId??"p"}-${w.index}`)}):m.status==="pending"&&(0,r.jsx)(o,{color:i.dim,children:" \u25CB Waiting..."})},$))}):null:(0,r.jsx)(fe,{steps:e,flows:n,cmInitCounts:l,renderStep:(m,$)=>z(m)?null:(0,r.jsx)(P,{step:m},$)}):(0,r.jsxs)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:[!c&&l&&l[0]!=null&&(0,r.jsxs)(o,{color:i.dim,children:["\u25AA Generated task with ",l[0]," checkpoints"]}),p.filter(m=>!(m.status==="running"&&(!m.children||m.children.length===0))).map(m=>{let $=`${m.index}-${m.objective}`;return c&&d.current.has($)?(0,r.jsx)(s,{flexDirection:"column",children:(m.children??[]).filter(w=>!z(w)).map(w=>(0,r.jsx)(s,{marginLeft:2,children:(0,r.jsx)(P,{step:w})},`${w.childId??"p"}-${w.index}`))},`branch-children-${m.index}`):(0,r.jsx)(P,{step:m},m.index)})]}),(0,r.jsx)(se,{activity:x,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}if(t){let p=le(e),g=ge(p,T);return(0,r.jsxs)(s,{flexDirection:"column",children:[(0,r.jsx)(fe,{steps:e,flows:n,cmInitCounts:l,renderStep:(x,f)=>z(x)?null:(0,r.jsx)(P,{step:x},f)}),(0,r.jsx)(se,{activity:g,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}let Ne=le(G),Ge=ge(Ne,T),Re=Fe(G);return(0,r.jsxs)(s,{flexDirection:"column",children:[Re.length>0&&(0,r.jsx)(s,{flexDirection:"column",marginLeft:2,paddingLeft:1,children:Re.map(p=>(0,r.jsx)(P,{step:p},p.index))}),(0,r.jsx)(se,{activity:Ge,describe:v,describeVisible:S}),B.length>0&&(0,r.jsx)(ie,{currentStep:Y,maxSteps:a,elapsed:ce,status:N})]})}var W=R(k(),1);function Ae({runner:e,runKey:t,onStepCommit:n}){let l=Ie({isRunning:e.isRunning,bifurcationInfo:e.bifurcationInfo,steps:e.steps,cmInitCounts:e.cmInitCounts,replayInfo:e.replayInfo});return(0,W.jsxs)(W.Fragment,{children:[l&&(0,W.jsx)(ke,{label:l.label,hasBifurcation:l.hasBifurcation}),e.isRunning&&e.steps.length>0&&(0,W.jsx)(_e,{steps:e.steps,bifurcated:!!e.bifurcationInfo&&!e.bifurcationInfo.isSingleFlow,flows:e.bifurcationInfo?.flows,cmInitCounts:e.cmInitCounts,maxSteps:e.maxSteps,onStepCommit:n},`run-${t}`)]})}var D=R(k(),1),Ye=64;function Je(e){return e.split(`
4
4
  `).map(t=>t.replace(/^[-–•]\s*/,"").trim()).filter(t=>t.length>0)}function qe({status:e,summary:t,duration:n,steps:l,stepsPassed:a,stepsFailed:u,reason:c,creditsConsumed:v}){let S=e==="passed",T=S?i.green:i.red,d=S?"\u2713":"\u2717",L=e.toUpperCase(),O=a??(S?l:Math.max(0,l-1)),y=u??(S?0:1),h=y>0?`${l} steps (${O} passed, ${y} failed)`:`${l} steps`,b=n<60?`${n.toFixed(1)}s`:`${Math.floor(n/60)}m ${Math.round(n%60)}s`,B=Je(t);return(0,D.jsx)(s,{flexDirection:"column",marginTop:1,children:(0,D.jsxs)(s,{borderStyle:"round",borderColor:T,flexDirection:"column",paddingX:2,paddingY:1,width:Ye+6,children:[(0,D.jsxs)(s,{flexDirection:"column",children:[(0,D.jsxs)(o,{bold:!0,color:T,children:[d," ",L]}),(0,D.jsxs)(o,{color:i.dim,wrap:"wrap",children:[h," \xB7 ",b,typeof v=="number"&&v>0?` \xB7 ${parseFloat(v.toFixed(4))} credits`:""]})]}),B.length>0&&(0,D.jsx)(s,{flexDirection:"column",marginTop:1,marginLeft:1,children:B.map((F,M)=>(0,D.jsxs)(s,{marginBottom:M<B.length-1?1:0,children:[(0,D.jsx)(o,{color:i.orange,children:"\u25CF "}),(0,D.jsx)(s,{flexShrink:1,children:(0,D.jsx)(o,{wrap:"wrap",children:F})})]},M))}),c&&!S&&(0,D.jsx)(s,{marginTop:1,children:(0,D.jsxs)(o,{color:i.red,wrap:"wrap",children:["Reason: ",c]})})]})})}var j=R(k(),1);function Me({message:e,code:t,remediation:n,docsUrl:l}){return(0,j.jsx)(ve,{title:"Error",variant:"error",children:(0,j.jsxs)(s,{flexDirection:"column",paddingY:1,children:[(0,j.jsxs)(o,{color:i.red,bold:!0,children:[" \u2717 ",e]}),t&&(0,j.jsxs)(s,{marginTop:0,marginLeft:5,children:[(0,j.jsx)(o,{color:i.muted,children:"Code: "}),(0,j.jsx)(o,{color:i.dim,children:t})]}),n&&(0,j.jsxs)(s,{flexDirection:"column",marginTop:1,marginLeft:5,children:[(0,j.jsx)(o,{color:i.green,bold:!0,children:"Fix:"}),(0,j.jsxs)(o,{color:i.orange,children:["$ ",n]})]}),l&&(0,j.jsxs)(s,{marginTop:1,marginLeft:5,children:[(0,j.jsx)(o,{color:i.muted,children:"Docs: "}),(0,j.jsx)(o,{color:i.orange,underline:!0,children:l})]})]})})}var E=R(k(),1);function un(e){let{exit:t}=Te(),{append:n}=ye(),l=(0,A.useRef)(!1);(0,A.useEffect)(()=>{l.current||(l.current=!0,n((0,E.jsx)(s,{flexDirection:"column",marginBottom:1,children:(0,E.jsxs)(s,{borderStyle:"round",borderColor:"#dc4e08",paddingX:2,children:[(0,E.jsx)(o,{color:"#ff9500",bold:!0,children:"KaneAI CLI"}),(0,E.jsx)(o,{color:i.dim,children:" \u2502 "}),(0,E.jsx)(o,{color:i.orange,children:e.topBanner.model}),(0,E.jsx)(o,{color:i.dim,children:" \u2502 "}),(0,E.jsx)(o,{color:i.dim,children:e.topBanner.auth})]})})),n((0,E.jsx)(Qe,{data:e.globalConfig})),e.priorAttemptRollup&&n((0,E.jsx)(o,{color:i.dim,children:` \u21B3 replayed ${e.priorAttemptRollup.startIdx}..${e.priorAttemptRollup.endIdx-1} (${e.priorAttemptRollup.count} steps, from prior attempt)`})))},[]);let a=(0,A.useRef)(null),u=(0,A.useCallback)(async y=>{let h=await e.getNextStep(y);return h?(a.current=h,h.config):(a.current=null,null)},[e]),c=(0,A.useCallback)((y,h)=>{let b=a.current;if(!b)return;let B=b.mode==="replay"?"cyan":"#dc4e08",F=b.modeReason?` (${b.modeReason})`:"",M=b.perStepOverrides?Object.entries(b.perStepOverrides):[];n((0,E.jsxs)(s,{flexDirection:"column",marginBottom:0,children:[(0,E.jsxs)(o,{children:[(0,E.jsxs)(o,{color:i.dim,children:[b.banner.stepLabel," "]}),(0,E.jsxs)(o,{color:B,children:["[",b.mode,"]"]}),(0,E.jsx)(o,{color:i.dim,children:F})]}),(0,E.jsx)(o,{color:i.dim,children:b.banner.objective}),M.length>0&&(0,E.jsxs)(o,{color:i.dim,children:["overrides: ",M.map(([X,Y])=>`${X}=${Y}`).join(", ")]})]}))},[n]),v=(0,A.useRef)(0),S=(0,A.useRef)(!1),T=(0,A.useCallback)((y,h)=>(y.hadError?n((0,E.jsx)(Me,{message:y.reason??"Runner error",code:"RUNNER_ERROR"})):n((0,E.jsx)(s,{flexDirection:"column",marginBottom:1,children:(0,E.jsx)(qe,{status:y.status,summary:y.runEnd?.summary??"",duration:y.runEnd?.duration??0,steps:y.stepsTotal,stepsPassed:y.stepsPassed,stepsFailed:y.stepsFailed,reason:y.runEnd?.reason,creditsConsumed:y.runEnd?.credits_consumed})})),e.onStepEnd?.(y,h)??!0),[n,e]),d=we({getNextConfig:u,onStepStart:c,onStepEnd:T,onAllComplete:()=>{e.onAllComplete(),e.exitOnComplete!==!1&&setImmediate(()=>t())},screenshotDispatcher:e.screenshotDispatcher,stepLogger:e.stepLogger,onReasoning:e.onReasoning,onStepComplete:e.onStepComplete,spawnOpts:e.spawnOpts}),L=250,O=5e3;return Se((y,h)=>{if(h.ctrl&&y==="c"){let b=Date.now(),B=b-v.current;if(B<L)return;S.current&&B<O?(d.cancel(),e.onCancel?.(),e.exitOnComplete!==!1&&setImmediate(()=>t())):(S.current=!0,n((0,E.jsx)(o,{color:"yellow",children:"press Ctrl+C again to cancel run"}))),v.current=b}}),(0,E.jsx)(s,{flexDirection:"column",children:d.phase!=="done"&&(0,E.jsx)(Ae,{runner:d.runner,runKey:d.currentStepIndex,onStepCommit:n})})}function Qe({data:e}){return(0,E.jsx)(Be,{title:"test.md run",titleColor:"#ff9500",borderColor:i.dim,rows:[{label:"source",value:e.source},{label:"steps",value:`${e.steps.total} (${e.steps.replay} replay, ${e.steps.author} author per walker)`},{label:"model",value:e.model},{label:"viewport",value:`${e.viewport.width} x ${e.viewport.height}`},{label:"chrome",value:e.chrome},{label:"session",value:e.session},{label:"variables",value:`${e.variables.count} (${e.variables.secrets} secret)`},{label:"flags",value:e.flags.length>0?e.flags.join(" "):"(none)"}]})}export{_e as a,ke as b,Ie as c,de as d,qe as e,Me as f,un as g};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{y as o}from"./chunk-ZUGCHQFC.js";import{a as m}from"./chunk-HCBYKLMW.js";import{a as e,b as i}from"./chunk-C44QQJR4.js";import{e as d}from"./chunk-UR6MHSHU.js";var r=d(m(),1),s={default:o.muted,error:o.red,success:o.green,info:o.orange,warning:o.orange};function h({title:t,titleColor:a,borderColor:l,variant:n="default",children:c,width:u,paddingX:x=2,paddingY:g=0,marginBottom:f=0}){let p=l??s[n],B=a??(n==="default"?o.orange:s[n]);return(0,r.jsxs)(e,{flexDirection:"column",marginBottom:f,children:[t&&(0,r.jsx)(e,{marginBottom:0,children:(0,r.jsxs)(i,{color:B,bold:!0,children:[" ",t]})}),(0,r.jsx)(e,{borderStyle:"round",borderColor:p,flexDirection:"column",paddingX:x,paddingY:g,width:u,children:c})]})}function k({label:t,value:a,labelColor:l=o.dim,valueColor:n,labelWidth:c=14}){return(0,r.jsxs)(e,{children:[(0,r.jsx)(e,{width:c,flexShrink:0,children:(0,r.jsx)(i,{color:l,children:t})}),(0,r.jsx)(e,{flexShrink:1,children:(0,r.jsx)(i,{color:n,wrap:"wrap",children:a})})]})}function I({label:t}){return(0,r.jsx)(e,{marginTop:1,marginBottom:0,children:(0,r.jsx)(i,{bold:!0,children:t})})}export{h as a,k as b,I as c};
2
+ import{y as o}from"./chunk-7F2ZV46B.js";import{a as m}from"./chunk-HCBYKLMW.js";import{a as e,b as i}from"./chunk-C44QQJR4.js";import{e as d}from"./chunk-UR6MHSHU.js";var r=d(m(),1),s={default:o.muted,error:o.red,success:o.green,info:o.orange,warning:o.orange};function h({title:t,titleColor:a,borderColor:l,variant:n="default",children:c,width:u,paddingX:x=2,paddingY:g=0,marginBottom:f=0}){let p=l??s[n],B=a??(n==="default"?o.orange:s[n]);return(0,r.jsxs)(e,{flexDirection:"column",marginBottom:f,children:[t&&(0,r.jsx)(e,{marginBottom:0,children:(0,r.jsxs)(i,{color:B,bold:!0,children:[" ",t]})}),(0,r.jsx)(e,{borderStyle:"round",borderColor:p,flexDirection:"column",paddingX:x,paddingY:g,width:u,children:c})]})}function k({label:t,value:a,labelColor:l=o.dim,valueColor:n,labelWidth:c=14}){return(0,r.jsxs)(e,{children:[(0,r.jsx)(e,{width:c,flexShrink:0,children:(0,r.jsx)(i,{color:l,children:t})}),(0,r.jsx)(e,{flexShrink:1,children:(0,r.jsx)(i,{color:n,wrap:"wrap",children:a})})]})}function I({label:t}){return(0,r.jsx)(e,{marginTop:1,marginBottom:0,children:(0,r.jsx)(i,{bold:!0,children:t})})}export{h as a,k as b,I as c};