@testmuai/kane-cli 0.7.1 → 0.8.1

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 (308) hide show
  1. package/dist/ChatSurface-U37VZDCW.js +8 -0
  2. package/dist/{ChromeProfilePicker-4CDSPBWL.js → ChromeProfilePicker-AUU7JF6F.js} +1 -1
  3. package/dist/{CliFeedbackPrompt-TLRVBA4E.js → CliFeedbackPrompt-4W74Y3UF.js} +1 -1
  4. package/dist/{CliUploadProgress-WGGFLUSF.js → CliUploadProgress-6HL7WTEX.js} +1 -1
  5. package/dist/ConfigView-6BSCZP5Y.js +2 -0
  6. package/dist/EvidenceViewOffer-62XHEEGW.js +2 -0
  7. package/dist/FolderPicker-S7U2EN2M.js +2 -0
  8. package/dist/{HelpView-FBCX32U7.js → HelpView-TU7ED43J.js} +1 -1
  9. package/dist/{InfoBox-KK2ICVS4.js → InfoBox-JLTMKVDE.js} +1 -1
  10. package/dist/{LinksBox-KKRANMR3.js → LinksBox-LREUUJDV.js} +1 -1
  11. package/dist/{ProfilesView-DGPXSAQN.js → ProfilesView-W3GX2N2E.js} +1 -1
  12. package/dist/{ProjectPicker-ESQSL4TT.js → ProjectPicker-SYQUJK2J.js} +1 -1
  13. package/dist/{SaveSessionPrompt-AQGP5W6E.js → SaveSessionPrompt-MR5NJMRP.js} +1 -1
  14. package/dist/SingleShotApp-XOKVOM7C.js +2 -0
  15. package/dist/{SummaryBox-BFZJW2KK.js → SummaryBox-UAYSVFB7.js} +1 -1
  16. package/dist/TestMdRunView-7UVSDAF4.js +2 -0
  17. package/dist/{WhoamiView-JABY3I5Q.js → WhoamiView-2YU76ASQ.js} +1 -1
  18. package/dist/adbkit-apkreader-ORZBGCJQ.js +184 -0
  19. package/dist/app-client-OEXESV4U.js +2 -0
  20. package/dist/app-download-AEEFQ63M.js +2 -0
  21. package/dist/{auth-76LVI6B5.js → auth-HET3TBRI.js} +1 -1
  22. package/dist/bind-STKXOUYI.js +12 -0
  23. package/dist/bootstrap-44YKVWWE.js +2 -0
  24. package/dist/bridge-5Z3BIB77.js +2 -0
  25. package/dist/{changelog-PSWPPOAF.js → changelog-7OWRHFHZ.js} +1 -1
  26. package/dist/chat-committer-ZWWCLJFD.js +2 -0
  27. package/dist/chat-controller-T2FAI55V.js +2 -0
  28. package/dist/{chunk-C4G7RVJ6.js → chunk-27U4PLPX.js} +1 -1
  29. package/dist/{chunk-V36ATG7A.js → chunk-2BGUUWNF.js} +2 -2
  30. package/dist/chunk-2KDGIZED.js +4 -0
  31. package/dist/chunk-2UIHS2FH.js +2 -0
  32. package/dist/chunk-2YEHV2CX.js +2 -0
  33. package/dist/{chunk-NRTHYROA.js → chunk-3LJWYRAA.js} +1 -1
  34. package/dist/chunk-3PECJD6S.js +11 -0
  35. package/dist/chunk-3POR47RC.js +8 -0
  36. package/dist/{chunk-KVQOBPAZ.js → chunk-3Q6WAK6P.js} +1 -1
  37. package/dist/chunk-4JOD47QI.js +2 -0
  38. package/dist/chunk-56PAQAX5.js +19 -0
  39. package/dist/{chunk-FCMLIK7P.js → chunk-5DBK6QNS.js} +1 -1
  40. package/dist/chunk-5DT7PIGB.js +5 -0
  41. package/dist/chunk-65ZTD5SJ.js +7 -0
  42. package/dist/chunk-6IA6QMPH.js +2 -0
  43. package/dist/{chunk-5KFS3GAZ.js → chunk-6KPPGMO2.js} +1 -1
  44. package/dist/{chunk-F6ZOJXYU.js → chunk-6O3DDOP2.js} +1 -1
  45. package/dist/chunk-6XX4LEVJ.js +2 -0
  46. package/dist/{chunk-KT6G7AF2.js → chunk-766WGMBU.js} +1 -1
  47. package/dist/chunk-7BZSCUPP.js +10 -0
  48. package/dist/{chunk-UBFKZEX3.js → chunk-7JWKHKFU.js} +2 -2
  49. package/dist/{chunk-PMHJRT3A.js → chunk-7KORP5FF.js} +1 -1
  50. package/dist/chunk-7Q6M6P4X.js +26 -0
  51. package/dist/{chunk-AM5S4KG4.js → chunk-AFPHLUQ5.js} +1 -1
  52. package/dist/chunk-AW2XUHH4.js +2 -0
  53. package/dist/chunk-BKHXPBWN.js +2 -0
  54. package/dist/chunk-BRHNRCEZ.js +3 -0
  55. package/dist/chunk-BRIEBB2U.js +2 -0
  56. package/dist/{chunk-NJPTOKW5.js → chunk-C7HSWZP6.js} +1 -1
  57. package/dist/{chunk-JEUA4UWK.js → chunk-CLGC7VEO.js} +1 -1
  58. package/dist/chunk-CTW2VQKS.js +6 -0
  59. package/dist/{chunk-L4JIMNKW.js → chunk-CUM23TLF.js} +1 -1
  60. package/dist/chunk-DBIBROYW.js +5 -0
  61. package/dist/{chunk-L7VREJTG.js → chunk-DCY6R5DP.js} +1 -1
  62. package/dist/{chunk-X3ICV5M5.js → chunk-DO5HAO3H.js} +1 -1
  63. package/dist/chunk-DPUV6OSP.js +2 -0
  64. package/dist/{chunk-M7WQM4UA.js → chunk-DUAXZYAD.js} +1 -1
  65. package/dist/{chunk-HPMS5KO6.js → chunk-DZGCXKKI.js} +3 -3
  66. package/dist/chunk-EDSZJZFG.js +4 -0
  67. package/dist/{chunk-OIYGGEUL.js → chunk-ELM6MXGJ.js} +1 -1
  68. package/dist/{chunk-R2RGSO4B.js → chunk-EWCAFKLX.js} +1 -1
  69. package/dist/chunk-EYOCNMUM.js +2 -0
  70. package/dist/{chunk-73C4PRYU.js → chunk-FEJXWJ3L.js} +1 -1
  71. package/dist/{chunk-BAL64WSI.js → chunk-FMRSMN34.js} +1 -1
  72. package/dist/chunk-FNH55WSR.js +19 -0
  73. package/dist/chunk-FQLIW3LM.js +2 -0
  74. package/dist/{chunk-JRMDGLLT.js → chunk-G7VQCS4J.js} +1 -1
  75. package/dist/chunk-GCBKDX2J.js +2 -0
  76. package/dist/{chunk-AAONIIQV.js → chunk-GFKCTYCA.js} +1 -1
  77. package/dist/chunk-GKYPNSQP.js +26 -0
  78. package/dist/chunk-GPG3FIN3.js +21 -0
  79. package/dist/chunk-GZPK6FRP.js +7 -0
  80. package/dist/{chunk-NOCIMJSN.js → chunk-HCKH44I2.js} +1 -1
  81. package/dist/chunk-HEAIJCGZ.js +2 -0
  82. package/dist/{chunk-3FN5VJMV.js → chunk-HMYMSRA4.js} +1 -1
  83. package/dist/chunk-I7TIGB7K.js +2 -0
  84. package/dist/chunk-IDX3TOPY.js +6 -0
  85. package/dist/{chunk-CVOGP253.js → chunk-IMR64OCZ.js} +1 -1
  86. package/dist/{chunk-IBNC444G.js → chunk-IOD3HQVW.js} +1 -1
  87. package/dist/chunk-IOFZSQAA.js +2 -0
  88. package/dist/chunk-IP2O264K.js +3 -0
  89. package/dist/{chunk-CSQ46PJ7.js → chunk-JJHG3BWO.js} +1 -1
  90. package/dist/{chunk-5JTUL6XL.js → chunk-JZ26R6UL.js} +1 -1
  91. package/dist/chunk-KBM3XHAM.js +2 -0
  92. package/dist/{chunk-SY3HLQMV.js → chunk-KCCSWEGA.js} +1 -1
  93. package/dist/chunk-KFSUPQAG.js +66 -0
  94. package/dist/chunk-KRKGZ2ZW.js +47 -0
  95. package/dist/chunk-KU6IXFGZ.js +9 -0
  96. package/dist/chunk-L7MXYCD7.js +2 -0
  97. package/dist/chunk-MA34UWKX.js +4 -0
  98. package/dist/chunk-MBF3FP5P.js +5 -0
  99. package/dist/chunk-MSGW4JDG.js +2 -0
  100. package/dist/chunk-MXHHMIO2.js +349 -0
  101. package/dist/chunk-N2P4MI32.js +2 -0
  102. package/dist/{chunk-CDQX6HGJ.js → chunk-NX7TM662.js} +1 -1
  103. package/dist/chunk-OMQCD3KR.js +2 -0
  104. package/dist/{chunk-QROUKGKU.js → chunk-OS4VSIHT.js} +1 -1
  105. package/dist/chunk-OTTGS2TE.js +2 -0
  106. package/dist/chunk-QGKPLOUI.js +2 -0
  107. package/dist/{chunk-JKTFTF24.js → chunk-QRZRSAZH.js} +1 -1
  108. package/dist/{chunk-WJ5HDEVH.js → chunk-QSDH5P7C.js} +1 -1
  109. package/dist/{chunk-322JEJEH.js → chunk-QW6EZC53.js} +1 -1
  110. package/dist/{chunk-2XMJ6YAE.js → chunk-R5T4RLF5.js} +1 -1
  111. package/dist/chunk-R7QAS6LZ.js +4 -0
  112. package/dist/{chunk-LR5XO2KD.js → chunk-RC52N7PC.js} +1 -1
  113. package/dist/{chunk-33QXD75Y.js → chunk-RFR4ZKIC.js} +3 -3
  114. package/dist/{chunk-3LWTUMDG.js → chunk-RLRNLIRS.js} +1 -1
  115. package/dist/{chunk-XDHZMCTA.js → chunk-SDPRO2LE.js} +2 -2
  116. package/dist/chunk-T5Y6MOLM.js +4 -0
  117. package/dist/{chunk-4OPQJ7PE.js → chunk-TFPPEOAK.js} +1 -1
  118. package/dist/chunk-TH47OOBV.js +4 -0
  119. package/dist/{chunk-XVDJ423L.js → chunk-TKGUT425.js} +1 -1
  120. package/dist/{chunk-OHRS3H7Z.js → chunk-TRJUD3XJ.js} +1 -1
  121. package/dist/chunk-TYLYFERW.js +10 -0
  122. package/dist/chunk-TZXXJWHA.js +2 -0
  123. package/dist/chunk-UD7KKHPW.js +5 -0
  124. package/dist/{chunk-APAIWBIH.js → chunk-UDIQOJEL.js} +1 -1
  125. package/dist/chunk-UV462FZR.js +2 -0
  126. package/dist/{chunk-323MLBYA.js → chunk-UXDL4XDL.js} +1 -1
  127. package/dist/chunk-V2R3LCA3.js +12 -0
  128. package/dist/chunk-VAYBKR76.js +4 -0
  129. package/dist/{chunk-AH7ZZIZY.js → chunk-VRVFPMCR.js} +1 -1
  130. package/dist/chunk-W2JFDDIB.js +2 -0
  131. package/dist/chunk-W4B5LOEX.js +4 -0
  132. package/dist/{chunk-36OC3TFE.js → chunk-W5TTF7GB.js} +2 -2
  133. package/dist/chunk-WXHQYYD5.js +2 -0
  134. package/dist/{chunk-6HEGD6H2.js → chunk-XO5ZH3ZR.js} +1 -1
  135. package/dist/chunk-XWKUZJCP.js +2 -0
  136. package/dist/{chunk-2KBD6JZX.js → chunk-YFYCCTSL.js} +1 -1
  137. package/dist/{chunk-ZM5PVRJK.js → chunk-YJELGSKJ.js} +1 -1
  138. package/dist/chunk-YRFMPIU2.js +4 -0
  139. package/dist/{chunk-2XGDWUJ5.js → chunk-ZGBSGZZM.js} +1 -1
  140. package/dist/{chunk-NBKQT7LJ.js → chunk-ZIUAOEUC.js} +1 -1
  141. package/dist/chunk-ZMNJBUAO.js +2 -0
  142. package/dist/chunk-ZVHCQMJ6.js +13 -0
  143. package/dist/committer-SWEWEYNX.js +2 -0
  144. package/dist/{config-R3GF2FZA.js → config-RS47F5SC.js} +1 -1
  145. package/dist/{controller-client-RD2YEMAH.js → controller-client-OB4WD2C4.js} +1 -1
  146. package/dist/{cover-cmd-TXICWHUU.js → cover-cmd-HDZZWJXG.js} +1 -1
  147. package/dist/{credentials-XN4ROCQ3.js → credentials-OH6AVI6N.js} +1 -1
  148. package/dist/deps-resolve-XC5S53DG.js +2 -0
  149. package/dist/descriptor-OEUZZCOK.js +2 -0
  150. package/dist/design-committer-VYT6NU3T.js +2 -0
  151. package/dist/dispatch-SE5GY3Z2.js +2 -0
  152. package/dist/doctor-FSECFZUU.js +2 -0
  153. package/dist/docx-convert-JMUMT5C4.js +2 -0
  154. package/dist/{dossier-QZV74XOS.js → dossier-KTLTGT2X.js} +1 -1
  155. package/dist/evidence-OYPHZUKI.js +2 -0
  156. package/dist/evolve-cmd-BCPNXAMV.js +2 -0
  157. package/dist/exec-P2IKJRRR.js +2 -0
  158. package/dist/exit-manager-3FVBTNYR.js +2 -0
  159. package/dist/explain-UAAQWHYR.js +2 -0
  160. package/dist/{explain-cmd-X7JZLSZZ.js → explain-cmd-3GEKR7O5.js} +1 -1
  161. package/dist/{explain-cmd-RZW6QJYM.js → explain-cmd-EX24XKD6.js} +1 -1
  162. package/dist/extract-bind-LLEASZAK.js +10 -0
  163. package/dist/extract-cmd-UZMEZMGP.js +5 -0
  164. package/dist/feeder-C3TOJPKK.js +2 -0
  165. package/dist/{gaps-cmd-BWCRLLBK.js → gaps-cmd-IVXFPFAQ.js} +1 -1
  166. package/dist/{gate-YHBPWEM5.js → gate-54BRAE7N.js} +1 -1
  167. package/dist/{generate-headless-BSTDLZZY.js → generate-headless-D3SVQ2AI.js} +3 -3
  168. package/dist/{headless-io-BL3TEAX5.js → headless-io-66RG5NN5.js} +1 -1
  169. package/dist/host-7GZPBA74.js +2 -0
  170. package/dist/identity-ADZ4PAJF.js +2 -0
  171. package/dist/index.js +85 -69
  172. package/dist/ingest-EX72IEQT.js +2 -0
  173. package/dist/ingest-cmd-EAE7N5RC.js +2 -0
  174. package/dist/{interactive-bind-43HGDF5K.js → interactive-bind-ORMN2REX.js} +7 -6
  175. package/dist/{lifecycle-cmd-D6TVTYRK.js → lifecycle-cmd-O2324GN6.js} +1 -1
  176. package/dist/{list-cmd-XCAV2FKA.js → list-cmd-N4KMA34H.js} +1 -1
  177. package/dist/list-commands-MRXL5HGS.js +2 -0
  178. package/dist/locks-cmd-CSVSWY2Y.js +2 -0
  179. package/dist/logical-ids-TEBCQJGO.js +2 -0
  180. package/dist/login-flow-QJQM3RHT.js +2 -0
  181. package/dist/maintenance-cmd-6XSVO6FO.js +2 -0
  182. package/dist/mobile-prompts-TOX35ER6.js +2 -0
  183. package/dist/pdf-convert-OZIRUADA.js +2 -0
  184. package/dist/persist-recorded-session-TLDQ5HKP.js +3 -0
  185. package/dist/phase-seed-VFHIH6FL.js +2 -0
  186. package/dist/pipeline-UOM4LNAI.js +2 -0
  187. package/dist/prepare-target-QYWIJIVQ.js +2 -0
  188. package/dist/readmodel-XOYGGQ3S.js +2 -0
  189. package/dist/reconcile-cmd-3H34KVVD.js +2 -0
  190. package/dist/reconcile-deps-XIH75ZLY.js +4 -0
  191. package/dist/reconcile-engine-UKWPG2LV.js +2 -0
  192. package/dist/{recording-banner-TALO7PUR.js → recording-banner-4M7XHVGI.js} +1 -1
  193. package/dist/records-IOZTZUZV.js +2 -0
  194. package/dist/registry-PYOTKZYZ.js +2 -0
  195. package/dist/{require-project-folder-R347LFDQ.js → require-project-folder-4UPQNEBJ.js} +1 -1
  196. package/dist/resolve-run-intent-X72V3KJA.js +7 -0
  197. package/dist/{resolver-IDCGRPFJ.js → resolver-UBOZLFFE.js} +1 -1
  198. package/dist/revert-NQ7GEVSE.js +2 -0
  199. package/dist/review-cmd-DQRKQUMG.js +4 -0
  200. package/dist/run-2COODVX2.js +2 -0
  201. package/dist/run-URPGHOQM.js +2 -0
  202. package/dist/run-channel-RGH4WIQX.js +2 -0
  203. package/dist/{run-test-md-DFNIGYB7.js → run-test-md-76ZPKXO6.js} +3 -3
  204. package/dist/session-target-UWROGOCY.js +2 -0
  205. package/dist/sessions-GIEXOCE4.js +2 -0
  206. package/dist/{sessions-cmd-AQWLL5ZN.js → sessions-cmd-ZZIZN2VB.js} +4 -4
  207. package/dist/{skill-installer-ANXTCXQV.js → skill-installer-CIS6GAYF.js} +1 -1
  208. package/dist/spawner-J67QR4QP.js +2 -0
  209. package/dist/structured-answers-5EY2AZN7.js +5 -0
  210. package/dist/tcg-generate-BDTRKY2A.js +2 -0
  211. package/dist/testmd-actions-77ELR5UU.js +2 -0
  212. package/dist/token-refresh-4BPAPXKK.js +2 -0
  213. package/dist/types-6E2HTDKJ.js +2 -0
  214. package/dist/{validate-basic-O2DP2XJL.js → validate-basic-2GVSQ2R5.js} +1 -1
  215. package/dist/verdicts-TRSTJLCL.js +2 -0
  216. package/dist/{version-check-RNR3JCQ5.js → version-check-O6PYTI4T.js} +1 -1
  217. package/dist/{view-cmd-YSEGA5PI.js → view-cmd-KPJTP4DI.js} +1 -1
  218. package/dist/walk-session-CHJXHZMO.js +2 -0
  219. package/dist/with-telemetry-CQCWLVOC.js +2 -0
  220. package/package.json +12 -6
  221. package/dist/ChatSurface-D66CACLX.js +0 -8
  222. package/dist/ConfigView-DBANTBXC.js +0 -2
  223. package/dist/EvidenceViewOffer-DNCQ3A6R.js +0 -2
  224. package/dist/FolderPicker-W7RCIFEL.js +0 -2
  225. package/dist/SingleShotApp-SMCAIKCE.js +0 -2
  226. package/dist/TestMdRunView-FMKZJ3A3.js +0 -2
  227. package/dist/bind-AACBTSAA.js +0 -12
  228. package/dist/bootstrap-CNOZ5VRB.js +0 -2
  229. package/dist/bridge-T4HL4TG7.js +0 -2
  230. package/dist/chat-committer-4BQBOKI4.js +0 -2
  231. package/dist/chat-controller-NNTMKEPG.js +0 -2
  232. package/dist/chunk-2SREGETM.js +0 -4
  233. package/dist/chunk-3STZLM5J.js +0 -4
  234. package/dist/chunk-5YPBPZUR.js +0 -2
  235. package/dist/chunk-6UJDOAYR.js +0 -26
  236. package/dist/chunk-BQHKBOSF.js +0 -11
  237. package/dist/chunk-DQ54MH7F.js +0 -13
  238. package/dist/chunk-DXV6MBTD.js +0 -8
  239. package/dist/chunk-EV3EHXEI.js +0 -4
  240. package/dist/chunk-F7WKDMX7.js +0 -47
  241. package/dist/chunk-FPFOW6BS.js +0 -2
  242. package/dist/chunk-GVIPTX6T.js +0 -6
  243. package/dist/chunk-GW5DWAXY.js +0 -2
  244. package/dist/chunk-HJERKSBK.js +0 -349
  245. package/dist/chunk-IQDWBTRJ.js +0 -3
  246. package/dist/chunk-IXVOXJP6.js +0 -6
  247. package/dist/chunk-KNDSQ4PS.js +0 -2
  248. package/dist/chunk-KRXSXQBU.js +0 -12
  249. package/dist/chunk-LQZ2BU7Q.js +0 -2
  250. package/dist/chunk-NAC7SFBE.js +0 -5
  251. package/dist/chunk-NAE7MBR2.js +0 -23
  252. package/dist/chunk-NRC2G4Y5.js +0 -5
  253. package/dist/chunk-O56PUUNL.js +0 -9
  254. package/dist/chunk-QM4S2APK.js +0 -2
  255. package/dist/chunk-RKWJG3WW.js +0 -19
  256. package/dist/chunk-RNSSM2BK.js +0 -11
  257. package/dist/chunk-SE6WNCYU.js +0 -4
  258. package/dist/chunk-SRDHPKJT.js +0 -2
  259. package/dist/chunk-SWESH2J7.js +0 -10
  260. package/dist/chunk-T63R6QT4.js +0 -4
  261. package/dist/chunk-UI7KULSI.js +0 -7
  262. package/dist/chunk-UPPEOQJQ.js +0 -3
  263. package/dist/chunk-URQUQWGW.js +0 -62
  264. package/dist/chunk-UX2B7L6K.js +0 -2
  265. package/dist/chunk-VOHQA2SP.js +0 -2
  266. package/dist/chunk-W5DOU2DV.js +0 -2
  267. package/dist/chunk-W6VD2XFO.js +0 -19
  268. package/dist/chunk-WAOCHXJ5.js +0 -2
  269. package/dist/chunk-WWNSD6FA.js +0 -6
  270. package/dist/chunk-ZLCZDAEX.js +0 -6
  271. package/dist/committer-2EJPVVCQ.js +0 -2
  272. package/dist/descriptor-KXDJ4XYD.js +0 -2
  273. package/dist/design-committer-BQUWD6AC.js +0 -2
  274. package/dist/docx-convert-ZBVQO2LG.js +0 -2
  275. package/dist/evidence-V23FPVXQ.js +0 -2
  276. package/dist/evolve-cmd-PZCPXDMR.js +0 -2
  277. package/dist/exit-manager-HNFATGSM.js +0 -2
  278. package/dist/explain-UE4IACQH.js +0 -2
  279. package/dist/extract-bind-BFY7IRL4.js +0 -10
  280. package/dist/extract-cmd-U3MGK2LP.js +0 -6
  281. package/dist/feeder-XGTFV7TZ.js +0 -2
  282. package/dist/ingest-AL6CABJT.js +0 -2
  283. package/dist/ingest-cmd-O6OWWZT4.js +0 -2
  284. package/dist/list-commands-747UTUSS.js +0 -2
  285. package/dist/locks-cmd-QAULI5LV.js +0 -2
  286. package/dist/logical-ids-4G4FAHNJ.js +0 -2
  287. package/dist/login-flow-CV76ENHV.js +0 -2
  288. package/dist/maintenance-cmd-ZRB4NTGG.js +0 -2
  289. package/dist/pdf-convert-S7VYE6AV.js +0 -2
  290. package/dist/persist-recorded-session-MDPWWUA7.js +0 -3
  291. package/dist/phase-seed-52LRE3LH.js +0 -2
  292. package/dist/pipeline-LM5JAK7F.js +0 -2
  293. package/dist/readmodel-X7L7W2BA.js +0 -2
  294. package/dist/reconcile-cmd-DGCSDML6.js +0 -2
  295. package/dist/records-5SVUXJBW.js +0 -2
  296. package/dist/revert-DXXYXJGN.js +0 -2
  297. package/dist/review-cmd-2QF5HTI7.js +0 -4
  298. package/dist/run-52UIBPXD.js +0 -2
  299. package/dist/run-VRVH4VO3.js +0 -2
  300. package/dist/sessions-BLXZVK5U.js +0 -2
  301. package/dist/spawner-AH5FTUYU.js +0 -2
  302. package/dist/structured-answers-QHFGZPSS.js +0 -5
  303. package/dist/tcg-generate-WKCBBKI5.js +0 -2
  304. package/dist/testmd-actions-RPYG6TJG.js +0 -2
  305. package/dist/token-refresh-NIDUOTRM.js +0 -2
  306. package/dist/verdicts-TJH3O5UW.js +0 -2
  307. package/dist/walk-session-HXW4OSA2.js +0 -2
  308. package/dist/with-telemetry-PNP6CAVM.js +0 -2
@@ -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 ke,c as Yt,e as Zt,f as Fe,g as Qt,h as or}from"./chunk-KU6IXFGZ.js";import{a as Xt,b as rr,c as sr,d as ir,e as dt,f as nr}from"./chunk-ZGBSGZZM.js";import{a as Se,b as qt,c as Gt,d as Lt,e as Vt}from"./chunk-BRHNRCEZ.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{d as Mt}from"./chunk-W4B5LOEX.js";import{a as be,b as ct}from"./chunk-DNNZ353O.js";import{e as Ut}from"./chunk-OMQCD3KR.js";import{a as Be}from"./chunk-SDPRO2LE.js";import{a as we}from"./chunk-NVGBE2DR.js";import{b as ot}from"./chunk-IDX3TOPY.js";import{A as Z,k as ye,o as je}from"./chunk-TH47OOBV.js";import{f as It}from"./chunk-DUAXZYAD.js";import{e as at}from"./chunk-DBIBROYW.js";import{d as de}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 oe}from"path";var J=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 qe(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),_=m!==null&&m>=5,x=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`),!_&&r.read_basis.length!==1)throw new J("READ_BASIS_COUNT",`read_basis must have exactly 1 element, got ${r.read_basis.length}`);if(r.read_basis.length===0)throw new J("READ_BASIS_COUNT","read_basis must not be empty");let v=r.read_basis[0],g=r.read_basis.length>1,k=r.use_cases.map(i=>{if(x&&i.cite.length!==1)throw new J("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 J("CITE_COUNT",`${i.temp_ref}: 1..${ar} cites allowed, got ${i.cite.length}`);let I=(h,Q)=>{if(!_&&h!==v.source_id)throw new J("SOURCE_MISMATCH",`${Q}: cite source ${h} != read_basis source ${v.source_id} (single-source)`)};I(i.cite[0].source_id,i.temp_ref);let P=i.cite.map(h=>(I(h.source_id,i.temp_ref),qe(h,v.source_id,_&&(g||h.source_id!==v.source_id)))),u=(i.updated?.criteria??[]).some(yr);if(!_&&u)throw new J("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((h,Q)=>(I(h.cite.source_id,`${i.temp_ref}.criteria[${Q}]`),{text:h.text,cite:qe(h.cite,v.source_id,_&&h.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:u?i.updated.criteria.map(h=>h.op==="set"?{op:"set",text:h.text,cite:qe(h.cite,v.source_id,_&&h.cite.source_id!==v.source_id)}:h.op==="keep"?{op:"keep",ref:h.ref,text:h.text}:{op:"remove",ref:h.ref,text:h.text,reason:h.reason}):i.updated.criteria.map((h,Q)=>(I(h.cite.source_id,`${i.temp_ref}.updated.criteria[${Q}]`),{text:h.text,cite:qe(h.cite,v.source_id,_&&h.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:k,...g?{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[g,k]of a.heads){if(_[g]=k,typeof k!="string")continue;let i=a.mediaOf(k),I=a.getNode(k)?.content?.blob;if(typeof I=="string")if(i.format==="image")x.push({source_id:g,cid:k,format:"image",blobRef:{path:we(e,I),cid:I}});else{let P=be(e,a,k)?.toString("utf8")??"";x.push({source_id:g,cid:k,format:i.format,text:P})}}x.sort((g,k)=>g.source_id<k.source_id?-1:1);let y=[];for(let g of a.byLabel(de.STYLENOTE).sort((k,i)=>k.cid<i.cid?-1:1))a.superseded.has(g.cid)||y.push(`\u2022 ${String(g.content.statement)} [${String(g.content.learned_from_kind)}]`);let v="";for(let g of y){if(Buffer.byteLength(v+g+`
3
+ `,"utf8")>m)break;v+=g+`
4
+ `}return{read_basis:_,sources:x,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,_){let x=null,y=()=>x??=_&&Object.keys(_).length>0?Promise.resolve(_):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,g)=>Gt(v,g,{env:process.env,auth:await y()}),readVector:(v,g)=>Lt(r,v,g),writeVector:(v,g,k)=>Vt(r,v,g,k)}),...a?.length?{reservedEventIds:a}:{}}}function gt(r,e){let a=[],m=[];for(let _ of r.use_cases){let x=_.matches_existing;x?.cid&&e.hasNode(x.cid)?a.push({ref:x.cid,expectedTip:e.tipOf(x.cid)}):m.push({tempRef:_.temp_ref,title:String(_.title??""),probeText:String(_.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 kr(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:we(e,m.blob),cid:m.blob}}))}function $r(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 Ge(r){return r.toISOString().replace(/[-:]/g,"").slice(0,15)}function gr(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 $e(r){return r.toLowerCase().trim().replace(/\s+/g," ")}function hr(r,e){let a=new Map,m=new Map,_=new Map;for(let{cid:y,content:v}of e.byLabel(de.USECASE)){if(e.superseded.has(y))continue;(e.trust.get(y)==="archived"?_:m).set($e(String(v.title??"")),y)}let x=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 k=y.matches_existing.cid;if(e.superseded.has(k)){let i=e.tipOf(k);k=e.superseded.has(i)?null:i}if(k!==null){a.set(y.temp_ref,x(k));continue}}let v=m.get($e(y.title));if(v){a.set(y.temp_ref,{cid:v});continue}let g=_.get($e(y.title));g&&a.set(y.temp_ref,x(g))}return a}var fr=/^(\S+)\.criteria\[(\d+)\]/;function Cr(r,e,a){if(e.length===0||!e.every(_=>fr.test(_.detail)))return!1;let m=new Map;for(let _ of e){let x=fr.exec(_.detail),y=m.get(x[1])??new Set;y.add(Number(x[2])),m.set(x[1],y)}for(let _ of r.use_cases){let x=m.get(_.temp_ref);x?.size&&(_.criteria=(_.criteria??[]).filter((y,v)=>!x.has(v)),a(`${_.temp_ref}: dropped ${x.size} criteria with unverifiable cites \u2014 committed without them (criteria are hints, not oracles)`))}return!0}async function ht(r,e,a,m,_=()=>{},x,y){let v=(g,k)=>_(g,k,r.session_id);return Zt(r,e,a,m,_,{async onProposalEvent(g){let k=g,i=null,I=null;if(cr(k))try{i=dr(k,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){I=P instanceof J?P.message:String(P),v("adapter",{ok:!1,error:I})}else i=k;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&&x&&await x(i),{proposal:i,error:I}}})}var Dr=new Set(["agent","ci","override"]);async function Ss(r,e){let a=`ext-${Ge(e.now?.()??new Date)}-lk${Math.random().toString(36).slice(2,8)}`,_=at(e.contextDir,a,e.now?{now:e.now}:void 0).tryAcquire([{kind:"extract"}],{hold:"session",verb:"extract"});if("contended"in _){let x=_.contended.holder,y=`another extraction is running on this context${x?` (pid ${x.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{_.release()}}async function Er(r,e){let a=r.mode??"interactive";if(r.posture==="reconcile"){if(r.trust==="hold"){let n="error: --trust hold has no meaning here \u2014 a reconcile IS the review; drop the flag";return e.out(`${n} [TRUST_USAGE]`),e.emit?.({type:"error",message:n,code:"TRUST_USAGE"}),2}if(!r.source||!r.changeContext){let n="reconcile posture needs a pinned source and its change context \u2014 internal wiring fault";return e.out(`error: ${n}`),e.emit?.({type:"error",message:n,code:"POSTURE_USAGE"}),2}if(a==="ci"){let n="reconcile posture is not available under --mode ci \u2014 a held changeset needs a durable session; use --mode agent";return e.out(`error: ${n}`),e.emit?.({type:"error",message:n,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,_=Ge(e.now?.()??new Date),x=m?At(m.ids.context_instance_id??null,"extract",m.ids.session_id):oe(e.contextDir,"logs",`extract-${_}.log`);ut(mr(x),{recursive:!0});let y=`run-${_}-${Math.random().toString(36).slice(2,8)}`,v=n=>n==="error"||n==="failed_proposal"?"error":n==="repair_respawn"?"warn":"info",g=(n,d,s)=>{try{wr(x,JSON.stringify({ts:new Date().toISOString(),level:v(n),run_id:y,...m?{user_session_id:m.ids.session_id}:{},...s?{session_id:s}:{},kind:n,data:d})+`
5
+ `)}catch{}m?.wireTrace(n,d,s)};{let n=e.out;e.out=d=>{g("transcript",{line:d}),n(d)}}e.out(`trace: ${ke(x)}`),e.emit?.({type:"run_start",mode:a,trace:x,...m?{session:m.ids.session_id}:{}});let k=Ft();if(k&&e.out(k),e.preflightTurn){let n=await e.preflightTurn();if(g("preflight",n),!n.ok)return e.out(n.message??"error: turn-endpoint preflight failed"),e.emit?.({type:"error",message:n.message??"error: turn-endpoint preflight failed",code:"PREFLIGHT"}),2}let i=Z(e.contextDir),I=lr(e.contextDir,i),P=r.sources?.length?r.sources:r.source?[r.source]:[];if(P.length>0){if(r.resume){let n="error: --source cannot be combined with --resume (the resumed session already has its scope)";return e.out(n),e.emit?.({type:"error",message:n,code:"SOURCE_WITH_RESUME"}),2}for(let n of P){let d=i.heads.get(n);if(typeof d!="string"){let s=d===null?`error: --source ${n} was ingested but is retired \u2014 re-ingest it to extract again`:`error: --source ${n} 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 u=null,h=null;if(r.resume){try{{let c=await nr(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 j=`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(j),e.emit?.({type:"error",message:j,code:"MULTI_SOURCE_RESUME"}),c.handle.release(),2}h=c,g("resume_kind",{kind:c.view.pointer===null?"bare-base":c.view.pointer.at==="final"?"pause":"crash"}),u={handle:c.handle,represent:c.represent,questions:c.questions,staleBasis:c.drift.map(j=>j.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 n=h?null:Xt(u.handle.state.verb,"extract",r.resume);if(n)return e.out(n.message),e.emit?.({type:"error",message:n.message,code:n.code}),u.handle.release(),2;let d=u.handle.state.change_basis;if(d&&(i.heads.get(d.source_id)??null)!==d.new_head){let c=`error: ${d.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"}),u.handle.release(),2}if(h&&h.view.pointer!==null&&h.drift.length>0){if(!await e.confirmStale(`changed since the pause: ${h.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 (${h.drift.map(j=>j.subject).join(", ")}) \u2014 session ${r.resume} is preserved`;return e.out(C),e.emit?.({type:"error",message:C,code:"RESUME_DRIFT"}),u.handle.release(),2}}else u.staleBasis.length>0&&e.out(`note: changed since the pause: ${u.staleBasis.join(", ")} \u2014 re-presented items may be stale`);let s=[...new Set([...u.handle.state.held_receipts??[],...h?.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
+ `)};u.handle.state.assumed.length>0&&e.out(`note: ${u.handle.state.assumed.length} default(s) were assumed while you were away \u2014 kane-cli context sessions show ${r.resume} lists them`)}let Q=i.extractedSourceCids,ue=!!(r.force||u?.handle.state.force),ee=[],se=[],Re=P.length>0?new Set(P):null;for(let[n,d]of i.heads.entries())if(d!=null&&!(Re&&!Re.has(n))){if(!Re&&!u&&n.startsWith("su-conv-")){e.out(`skipped ${n} \u2014 conversation source; extract it explicitly with --source ${n}`),se.push({source_id:n,reason:"conversation"});continue}if(u){let s=n in u.handle.state.read_basis,c=u.handle.state.corpus_cursor.remaining.includes(n);if(!s&&!c)continue;if(c&&!ue&&Q.has(d)){e.out(`${n} already extracted \u2014 skipped (--force re-runs it)`),se.push({source_id:n,reason:"cached"});continue}}else if(!ue&&Q.has(d)){e.out(`${n} already extracted \u2014 skipped (--force re-runs it)`),se.push({source_id:n,reason:"cached"});continue}ee.push({source_id:n,cid:d})}let _r=n=>{let d=tr(e.contextDir,n);d&&e.out(`note: a reconcile plan for ${n} is pending (${d.pending} item(s)) \u2014 resume with \`kane-cli maintain reconcile --apply ${d.path}\``)};for(let n of se)n.reason==="cached"&&_r(n.source_id);if(e.emit?.({type:"corpus",sources:ee,skipped:se}),ee.length===0){if(u){let s=`error: resumed session's paused source (${Object.keys(u.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"}),u.handle.release(),2}let n=se.length>0&&se.every(d=>d.reason==="conversation");return e.out(Re?`extract: nothing to do \u2014 ${P.join(", ")} ${P.length===1?"is":"are all"} already extracted at the current snapshot (--force to re-run)`:n?"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 te=!r.plan&&a!=="ci",Ce=e.now?.()??new Date,De=r.resume??`ext-${Ge(Ce)}-${gr(ee[0].source_id)}`,T=null,Ee=!1;te&&!u&&(T=ot(e.contextDir,{sid:De,mode:"agent",created_at:Ce.toISOString(),expires_at:new Date(Ce.getTime()+1440*60*1e3).toISOString(),agent_state:{schema:2,items:[],provider_state:""},pending:{questions:[],proposals:[]},assumed:[],read_basis:{[ee[0].source_id]:ee[0].cid},corpus_cursor:{remaining:ee.slice(1).map(n=>n.source_id)},conv_source:"",verb:"extract",...ue?{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 Le=h?h.represent.map(n=>n.event_id).filter(n=>typeof n=="string"):[],w=u?.handle??T,ft=!1,pt=()=>{try{br(oe(e.contextDir,"sessions"))}catch{}},_t=()=>{if(T){try{T.complete()}catch{T.release()}T=null,w=null,pt()}},Pe=new Map;if(u&&u.questions.length>0&&!r.message&&!r.withSource){e.out(`re-presenting ${u.questions.length} unanswered question(s) from the paused session`);let n=await e.ask(u.questions.map(rr));if(Array.isArray(n))for(let d of n)Pe.set(d.id,d)}let le=e.by??{kind:"human",id:"owner"},re=a==="interactive"&&!r.plan&&!!e.chat,Ve=0,xt=0,Te=!1,me=0,We=()=>{Te||(Te=!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"}))},Ae=null,ge=()=>w??T,ze=(n,d,s)=>{let c=ge();if(!c)return;let C=d.map(b=>({label:"usecase",content:{title:b.title,...b.summary!==void 0?{summary:b.summary}:{},...b.risk!==void 0?{risk:b.risk}:{},derived:!0,_held:{source_id:n.source_id,source_cid:n.cid,anchor:b.cite?.anchor??"L1-L1",quote:b.cite?.quote??""}},rationale:`held (${s==="degraded"?"embed degraded \u2014 lexical dedup only":"--trust hold"}): ${n.source_id} @ ${n.cid.slice(0,19)} ${b.cite?.anchor??""}`,edges:[],tempRef:b.temp_ref})),j=c.state.pending;c.save({pending:{questions:j.questions,proposals:[...j.proposals,...C]}}),me+=C.length,Ae=c.state.sid,e.emit?.({type:"held",source_id:n.source_id,count:C.length,reason:s==="degraded"?"embed_degraded":"trust_hold"})},F=[],vt=!1,M=[...ee];try{let n=d=>{let s=w;if(!s)return;let c=s.state.ingest_schedule??[];if(!c.some(b=>b.status==="pending"))return;let C=Z(e.contextDir),j=c.map(b=>b.status!=="pending"?b:(C.heads.get(b.source_id)??null)!==b.cid?(e.out(`note: ${b.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`),{...b,status:"skipped",note:"head moved since landing"}):C.extractedSourceCids.has(b.cid)||M.some(V=>V.source_id===b.source_id&&V.cid===b.cid)?{...b,status:"done"}:M.some(V=>V.source_id===b.source_id)?(e.out(`note: an older version of ${b.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`),{...b,status:"skipped",note:"an older version of the source was already queued this run"}):(M.push({source_id:b.source_id,cid:b.cid}),e.out(`queued ${b.source_id} for extraction in this run (landed mid-run)`),{...b,status:"done"}));s.save({ingest_schedule:j,corpus_cursor:{remaining:M.slice(d+1).map(b=>b.source_id)}})};for(let d=0;d<M.length;n(d),d++){let s=M[d],c=Z(e.contextDir),C={current:c};e.chat?.attachOnCommitted?.(t=>{C.current=t});let j=c.getNode(s.cid),b=String(j?.content.blob??""),Oe=be(e.contextDir,c,s.cid);if(!Oe){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 ${b} missing from .context/blobs`,code:"BLOB_MISSING"}),F.push(s.source_id);continue}let V=c.mediaOf(s.cid),Ke=V.media_type.startsWith("image/");if(!Ke){let t=$r(Oe);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(Oe),Ie=(t,o)=>{let l=new Map;l.set(s.source_id,{media:V,numberedText:yt});for(let f of o.sources??[]){if(l.has(f.source_id))continue;let D=be(e.contextDir,t,f.source_cid);if(!D)continue;let $=t.mediaOf(f.source_cid),E=$.media_type.startsWith("image/")?`0001| (image source ${f.source_id} \u2014 the content is attached as an image; cite it with anchor img#whole)`:ct(D);l.set(f.source_id,{media:$,numberedText:E})}return l},wt=Ge(e.now?.()??new Date),ie=`${wt}-${s.source_id}`,he=!!(u&&s.source_id in u.handle.state.read_basis),Me=w?De:`ext-${wt}-${gr(s.source_id)}`,Je=M.slice(d+1).map(t=>t.source_id);w&&te&&!he&&w.save({read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:Je}});let ne="";if(re){let t=Wt({contextDir:e.contextDir,graph:Z(e.contextDir),sessionStamp:Me,by:le});t.errors===null||t.errors[0]?.code==="CONV_SOURCE_EXISTS"?(ne=t.sourceId,e.chat.attachConversationSource?.(ne),C.current=Z(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:Me,mode:a,source:{source_id:s.source_id,source_cid:s.cid,kind:Mt.has(V.format)?V.format:Sr(s.source_id)||"md",numbered_text:yt,...(()=>{let t=kr(V,e.contextDir);return t?{images:t}:{}})()},existing_use_cases:c.byLabel(de.USECASE).filter(({cid:t})=>c.trust.get(t)!=="archived"&&!c.superseded.has(t)).map(({cid:t,content:o})=>({id:t,title:String(o.title??""),summary:String(o.summary??"")})),read_basis:C.current.latestHash,max_free_text_rounds:Yt,graph_reads:!0,verb:"extract",...I!==void 0?{style_note_digest:I}:{},...r.changeContext&&r.changeContext.source_id===s.source_id?{change_context:r.changeContext}:{},topology:er(),...re?{chat:!0}:{},...Ke?{image_sources:[{source_id:s.source_id,source_cid:s.cid,media_type:V.media_type,blob_ref:{path:we(e.contextDir,b),cid:b}}]}:{},...u&&!h&&s.source_id in u.handle.state.read_basis?{resume:{agent_state:u.handle.state.agent_state}}:{},...te&&w?{checkpoints:!0}:{}},R=h&&he?{...h.spawnConfig,mode:a}:bt;if(te&&w&&!ft){ft=!0;let{resume:t,...o}=bt;Ht(e.contextDir,De,{schema:Nt,kind:"base",sid:De,verb:"extract",mode:a,created_at:Ce.toISOString(),run_config:o,conv_source:ne||w.state.conv_source||"",store_watermark:It(e.contextDir)})}let St=h&&he?0:w?.state.checkpoint?.seq??0,fe={current:null};if(R.resume&&"schema"in R.resume){let t=R.resume.binding?.template_version;typeof t=="string"&&(fe.current=t)}let Xe=te&&w?ir({contextDir:e.contextDir,handle:w,seqBase:()=>St,peekHeldReceipts:()=>e.chat?.peekHeldReceipts?.()??[],readBasis:()=>({[s.source_id]:s.cid}),corpusCursor:()=>({remaining:Je}),onSoftCap:t=>e.out(t),onStat:t=>g("ckpt_stat",t,R.session_id),...e.now?{now:e.now}:{}}):void 0,ae=Xe?{...Xe,persist:t=>{let o=t.binding?.template_version;return typeof o=="string"&&o&&(fe.current=o),Xe.persist(t)}}:void 0;re||e.out(u&&s.source_id in u.handle.state.read_basis?`resuming: ${s.source_id} (session ${r.resume})`:`reading ${s.source_id} (source ${d+1} of ${M.length})`),e.emit?.({type:"source_start",source_id:s.source_id,cid:s.cid,index:d+1,total:M.length,resumed:!!(u&&s.source_id in u.handle.state.read_basis)}),e.chat?.ledger?.({kind:"banner",text:Rr(s,d+1,M.length)}),e.chat?.setWorking?.(`Reading ${pr(s)}\u2026`);let Ye=new Map;g("spawn",{source_id:s.source_id,source_cid:s.cid,resume:!!u,chat:re},R.session_id);let kt=!1,$t=!1,Ze=!1,Rt=async t=>{let o=Z(e.contextDir),l=ye(t,Ie(o,t),o);if(g("kane_validate",{errors:l.map(p=>p.code)},R.session_id),l.length>0){if(e.nested){e.chat?.ledger?.({kind:"commit",ok:!1,line:"proposal failed validation \u2014 nothing landed",warnings:l.map(p=>`${p.code}: ${p.detail}`)}),$t=!0;return}e.chat.submit("[auto-repair] the proposal failed validation: "+l.map(p=>`${p.code}: ${p.detail}`).join("; ")+" \u2014 please re-finalize with these fixed.");return}let f=Z(e.contextDir),D=hr(t,f),$=oe(e.contextDir,"proposals",ie);ut($,{recursive:!0}),lt(oe($,"proposal.json"),JSON.stringify(t,null,2)+`
10
+ `);let E=new Map(t.use_cases.map(p=>[p.temp_ref,{resolution:"skipped"}])),Y=mt(e.contextDir,R.session_id,Le,e.probe,e.auth),O=await Se(Y,gt(t,f),p=>{if(p.degradedProbe&&ge()!==null&&t.use_cases.some(xe=>xe.matches_existing==null))return{result:{degradedHold:!0},record:null};let z=je({contextDir:e.contextDir,graph:p.graph,proposal:t,proposalId:ie,verdicts:E,by:{kind:"ai",id:"extract-agent"},autoName:!0,allowStaleBasis:!0,eventIds:p.eventIds("extract",1),...te?{sid:p.sid}:{},probeHits:p.probeHits});return z.errors!==null?{errors:z.errors}:{result:z,record:z.record}}),U=O.ok&&"result"in O?O.result:null;if(U!==null&&"degradedHold"in U){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 L=U??{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(L.errors){e.chat.ledger?.({kind:"commit",ok:!1,line:"commit failed \u2014 nothing landed",warnings:L.errors.map(p=>`${p.code}: ${p.detail}`)});return}kt=!0,L.record?.event_ids?.length&&w?.markApplied(L.record.event_ids);{let p=L.record.review.filter(z=>z.kind==="pending_update");p.length>0&&(e.out(`${p.length} update(s) held for review`),e.emit?.({type:"update_held",count:p.length,targets:p.map(z=>z.id)}),e.chat?.ledger?.({kind:"commit",ok:!0,line:`${p.length} update(s) held for review`}))}let W=L.record.nodes.length;Ve+=W;let N=t.use_cases.length-W;{let p=Z(e.contextDir),z=new Map;for(let{cid:H,content:K}of p.byLabel(de.USECASE))p.superseded.has(H)||z.set($e(String(K.title??"")),H);let xe=[];for(let H of t.use_cases){let K=null;if(H.matches_existing?.cid&&p.hasNode(H.matches_existing.cid)){let ve=p.tipOf(H.matches_existing.cid);K=p.superseded.has(ve)?null:ve}K=K??z.get($e(H.title))??null,K&&xe.push({ref:H.temp_ref,cid:K,...p.displayNameOf(K)?{id:p.displayNameOf(K)}:{}})}xe.length>0&&e.chat.registerAliases?.(xe),C.current=p;let Pt=H=>{for(let[K,ve]of p.names)if(ve===H&&!p.superseded.has(ve))return K},Tt=zt({verb:"extract",commitN:1,phase:"proposal",committed:L.record.nodes.map(H=>({cid:H.cid,...Pt(H.cid)?{logical_id:Pt(H.cid)}:{}})),reused:N},p);e.emit?.(Tt.event),e.chat.holdReceipt?.(Tt.text)}g("commit",{derived:W,evidence_matched:N,chat:!0},R.session_id),e.chat.ledger?.({kind:"commit",ok:!0,line:W===0&&N>0?`all ${N} matched existing \u2014 nothing new to save`:`saved ${W} use-case${W===1?"":"s"} as drafts`+(N>0?` \xB7 ${N} matched existing`:"")})},Qe=!!(u&&s.source_id in u.handle.state.read_basis),q=Qe&&Pe.size>0?{...e,ask:async t=>t.every(o=>Pe.has(o.id))?(u.handle.markApplied(t.map(o=>`resolveq:${r.resume}:${o.id}`)),e.out(`answered ${t.length} re-asked question(s) from the held resume answers`),t.map(o=>Pe.get(o.id))):e.ask(t)}:e;Qe&&r.message&&(q={...q,initialMessage:r.message}),q={...q,onEmbedDegraded:We};let ce,et;if(w){let t=w,o=q.ask,l=Qt({contextDir:e.contextDir,cwd:mr(e.contextDir),handle:t,note:f=>e.chat?e.chat.note(f):e.out(f),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(q={...q,ask:async f=>{let D=await o(f);if(Array.isArray(D)){let $=D.filter(E=>{if(E.free_text==null||E.free_text.trim()==="")return!1;let Y=f.find(O=>O.id===E.id);return E.selected_index!=null&&Y?.options[E.selected_index]?.input===!0}).map(E=>E.free_text.trim());if($.length>0){let E=t.state.ingest_registry;for(let Y of $)E=Fe(E,Y,e.now?.()??new Date);t.save({ingest_registry:E})}}return D},ingest:l},Qe&&r.withSource){let f=(t.state.pending?.proposals??[]).filter(E=>E.content?._held!=null).length;if(r.trust==="hold"||f>0){let E=f>0?`error: --with-source can't add a source to a session holding ${f} 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:Fe(t.state.ingest_registry,D,e.now?.()??new Date)});let $=await l({id:`withsource-${t.state.sid}`,ref:D,purpose:null});if(!$.ok)return e.out(`error: --with-source: ${$.error.message}`),e.emit?.({type:"error",code:$.error.code,message:`--with-source: ${$.error.message}`}),2;q={...q,pendingDeferral:{ingested:{source_id:$.result.source_id,cid:$.result.cid}}}}et=()=>{if(!e.chat?.attachIngest)return;let f=e.chat;ce=f.attachIngest(async D=>{try{t.save({ingest_registry:Fe(t.state.ingest_registry,D,e.now?.()??new Date)});let $=await l({id:`attach-${t.state.sid}-${(t.state.ingest_registry??[]).length}`,ref:D,purpose:null});return $.ok?(f.deferBatch({source_id:$.result.source_id,cid:$.result.cid}),{ok:!0}):{ok:!1,error:$.error.message}}catch($){return{ok:!1,error:$ instanceof Error?$.message:String($)}}})},et()}let S;try{S=await ht(R,{...q,graphSlot:C,...ae?{checkpoint:ae}:{}},Ye,c,g,re?Rt:void 0,()=>fe.current)}catch(t){if(t instanceof Be)return ce?.(),e.chat?.setWorking?.(null),e.out(`error: ${t.message}`),e.emit?.({type:"error",code:"PAIR_MISMATCH",message:t.message}),2;throw t}if(ce?.(),e.chat?.setWorking?.(null),S.errorCode==="binding_mismatch"&&h&&he){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(f=>f.id==="binding-mismatch"):void 0)?.selected_index!==0){let f=`resume abandoned: binding mismatch on session ${Me} \u2014 the session is preserved`;return e.out(f),e.emit?.({type:"error",message:f,code:"BINDING_MISMATCH"}),2}g("binding_migrate",{sid:Me},R.session_id),et?.();let l=R.resume&&"schema"in R.resume?{...R.resume,binding:{}}:void 0;try{S=await ht({...R,...l?{resume:l}:{}},{...q,graphSlot:C,...ae?{checkpoint:ae}:{}},Ye,c,g,re?Rt:void 0,()=>fe.current)}catch(f){if(f instanceof Be)return ce?.(),e.chat?.setWorking?.(null),e.out(`error: ${f.message}`),e.emit?.({type:"error",code:"PAIR_MISMATCH",message:f.message}),2;throw ce?.(),f}ce?.(),e.chat?.setWorking?.(null)}if(S.error){let t=S.error.startsWith("proposal failed validation after repair:");t&&g("agent_error_detail",{error:S.error},R.session_id);let o=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}: ${S.error}`;e.out(o),e.emit?.({type:"error",source_id:s.source_id,message:o}),F.push(s.source_id);continue}if(S.highRisk)return e.out(`error: ${S.highRisk.length} high-risk decision${S.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): ${S.highRisk.map(t=>t.id).join(", ")}`,code:"HIGH_RISK_CI"}),1;if(S.paused){let t=M.slice(d+1).map(D=>D.source_id),o=u?.handle??T,l=o??ot(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:S.paused.agent_state,pending:{questions:[],proposals:[]},assumed:[],read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:t},conv_source:ne,verb:"extract",...ue?{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}:{}});Ee=!0;try{ne&&l.state.conv_source!==ne&&l.save({conv_source:ne});let D=e.chat?.drainHeldReceipts?.()??[];(D.length>0||(l.state.held_receipts?.length??0)>0)&&l.save({held_receipts:D}),o&&l.save({read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:t},...ue&&!l.state.force?{force:!0}:{},...m&&l.state.user_session_id!==m.ids.session_id?{user_session_id:m.ids.session_id}:{}}),sr(l,S.paused)}catch(D){let $=l.state.checkpoint,E=`error: couldn't persist the pause for session ${l.state.sid}`+($?` \u2014 last durable checkpoint: seq ${$.seq} @ ${$.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:l.state.sid}),1}g("session_paused",{sid:l.state.sid},R.session_id);let f=`kane-cli context extract --resume ${l.state.sid} --mode ${a}`;return e.out(`paused: session ${l.state.sid} saved \u2014 resume with: ${f}`),e.emit?.({type:"session_paused",sid:l.state.sid,source_id:s.source_id,mode:a,resume:f,expires_at:l.state.expires_at,pending_questions:S.paused.pending.questions}),e.chat?.ledger?.({kind:"pause",sid:l.state.sid,expires_at:l.state.expires_at,resume:f,messageForm:`${f} --message "<your words>"`}),3}if(S.crashed){let t=w?.state.checkpoint;if(w&&t){let o=`kane-cli context extract --resume ${w.state.sid} --mode ${a}`;try{w.save({read_basis:{[s.source_id]:s.cid},corpus_cursor:{remaining:Je}})}catch{}return g("agent_crashed_resumable",{sid:w.state.sid,seq:t.seq},R.session_id),e.out(`agent crashed \u2014 session ${w.state.sid} is resumable at checkpoint seq ${t.seq} (at most the in-flight turn lost); resume with: ${o}`),e.emit?.({type:"session_paused",sid:w.state.sid,source_id:s.source_id,mode:a,resume:o,expires_at:w.state.expires_at,crashed:!0}),e.chat?.ledger?.({kind:"pause",sid:w.state.sid,expires_at:w.state.expires_at,resume:o,messageForm:`${o} --message "<your words>"`}),Ee=!0,w.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"}),F.push(s.source_id);continue}if(re){if(xt+=S.assumedDefaults??0,S.error||$t)return 1;if(!kt&&!Ze){let t=M.length-d-1;e.out(`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)`:""));{let o=(w?.state.ingest_schedule??[]).filter(l=>l.status==="pending");o.length>0&&e.out(`note: ${o.length} source(s) landed this session (${o.map(l=>l.source_id).join(", ")}) were not extracted \u2014 the session ended first; kane-cli context extract runs them`)}return u&&s.source_id in u.handle.state.read_basis&&(u.handle.complete(),u=null,w=null),_t(),0}u&&s.source_id in u.handle.state.read_basis&&!Ze&&(n(d),u.handle.complete(),u=null,w=null);continue}if(!S.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}`}),F.push(s.source_id);continue}let G=ye(S.proposal,Ie(c,S.proposal),c);if(g("kane_validate",{errors:G.map(t=>t.code)},R.session_id),G.length>0&&Cr(S.proposal,G,t=>e.out(t))&&(g("criteria_dropped",{source_id:s.source_id},R.session_id),G=ye(S.proposal,Ie(c,S.proposal),c)),G.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:G.map(t=>t.code),repairing:!0}),g("repair_respawn",{source_id:s.source_id},R.session_id),h&&he||(St=w?.state.checkpoint?.seq??0);try{S=await ht(R,{...q,graphSlot:C,...ae?{checkpoint:ae}:{}},Ye,c,g,void 0,()=>fe.current)}catch(t){if(t instanceof Be)return e.out(`error: ${t.message}`),e.emit?.({type:"error",code:"PAIR_MISMATCH",message:t.message}),2;throw t}if(S.error||!S.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}`}),F.push(s.source_id);continue}if(G=ye(S.proposal,Ie(c,S.proposal),c),G.length>0){g("validation_details",{errors:G.map(t=>({code:t.code,detail:t.detail}))},R.session_id),e.out(`\u2717 validation failed \u2014 ${G.map(t=>t.code).join(", ")} (details: ${ke(x)})`),e.emit?.({type:"validate_failed",source_id:s.source_id,codes:G.map(t=>t.code),repairing:!1}),e.emit?.({type:"error",source_id:s.source_id,message:`error: proposal failed validation after repair (${G.map(t=>t.code).join(", ")})`}),F.push(s.source_id);continue}}let A=S.proposal,Ue=hr(A,c),tt=oe(e.contextDir,"proposals",ie);if(ut(tt,{recursive:!0}),lt(oe(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 o=Ue.get(t.temp_ref),l=o?o.archived?` \u2248 matches ARCHIVED ${o.cid.slice(0,19)}${o.reason?` \u2014 previously rejected: "${o.reason}"`:" \u2014 previously rejected"}`:` \u2248 matches ${o.cid.slice(0,19)}`:"";e.out(` [${t.risk}] ${t.title} \u2014 cite ${t.cite.anchor}${l}`)}e.emit?.({type:"plan",source_id:s.source_id,use_cases:A.use_cases.map(t=>{let o=Ue.get(t.temp_ref);return{risk:t.risk,title:t.title,anchor:t.cite.anchor,...o?{match:o.cid,match_archived:!!o.archived}:{}}})}),S.assumedDefaults&&e.out(`assumed: ${S.assumedDefaults} default(s) auto-taken (assumed)`);continue}for(let t of A.use_cases){if(!t.conflicts_with?.length)continue;let o=t.conflicts_with.filter(f=>c.resolve(f)!==null),l=t.conflicts_with.filter(f=>c.resolve(f)===null);l.length>0&&(e.out(`note: ${t.temp_ref}: dropped unresolvable conflict hint(s): ${l.join(", ")}`),t.conflicts_with=o.length>0?o:void 0)}g("review_start",{use_cases:A.use_cases.length,flags:Ue.size},R.session_id);let Ne=await e.review(A.use_cases,Ue);if(g("review_verdicts",[...Ne.entries()].map(([t,o])=>({ref:t,resolution:o.resolution})),R.session_id),lt(oe(tt,"review.json"),JSON.stringify(A.use_cases.map(t=>{let o=Ne.get(t.temp_ref)??{resolution:"skipped"};return{id:t.temp_ref,kind:"review-item",resolution:o.resolution,edit:o.edit??null,reason:o.reason??null,...o.supersedeTarget?{supersede_target:o.supersedeTarget}:{},by:le}}),null,2)+`
12
+ `),r.posture==="reconcile"){let t=jt(A),o=U=>t.passthrough.use_cases.filter(L=>{let W=L.matches_existing?.cid,N=W?U.resolve(W):null,p=N?U.tipOf(N.cid):null;return p!=null&&(U.trust.get(p)??null)!=="derived"}),l=o(c),f=t.passthrough.use_cases.length-l.length,D=mt(e.contextDir,R.session_id,Le,e.probe,e.auth),$=new Set(l.map(U=>U.temp_ref));(await Se(D,gt({...t.passthrough,use_cases:l},c),U=>{let L={...t.passthrough,use_cases:o(U.graph).filter(p=>$.has(p.temp_ref))},W=new Map(L.use_cases.map(p=>[p.temp_ref,{resolution:"approved"}])),N=je({contextDir:e.contextDir,graph:U.graph,proposal:L,proposalId:ie,verdicts:W,by:le,autoName:!0,allowStaleBasis:!0,eventIds:U.eventIds("extract",1),...te?{sid:U.sid}:{},probeHits:U.probeHits});return N.errors!==null?{errors:N.errors}:{result:N,record:N.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"),f>0&&e.out(`note: ${f} 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 Y=ge(),O=t.adds.length+t.updates.length+t.archives.length;Y&&O>0&&(Y.save({reconcile:{proposal_id:ie,verdicts:{}}}),me+=O,Ae=Y.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((Te||r.trust==="hold")&&ge()&&A.use_cases.some(t=>t.matches_existing==null)){ze(s,A.use_cases,Te?"degraded":"trust_hold");continue}let Ct=mt(e.contextDir,R.session_id,Le,e.probe,e.auth),Dt=t=>{if(t.degradedProbe&&ge()!==null&&A.use_cases.some(l=>l.matches_existing==null))return{result:{degradedHold:!0},record:null};let o=je({contextDir:e.contextDir,graph:t.graph,proposal:A,proposalId:ie,verdicts:Ne,by:le,autoName:!0,allowStaleBasis:!0,eventIds:t.eventIds("extract",1),...te?{sid:t.sid}:{},probeHits:t.probeHits});return o.errors!==null?{errors:o.errors}:{result:o,record:o.record}},Et=gt(A,c),B=await Se(Ct,Et,Dt);if(!B.ok&&B.kind==="drifted"){if(!await e.confirmStale(`the context changed while you reviewed (${B.asks.map(o=>o.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"}),F.push(s.source_id);continue}B=await Se(Ct,{...Et,sourcePins:[]},Dt)}let rt=B.ok&&"result"in B?B.result:null;if(rt!==null&&"degradedHold"in rt){We(),ze(s,A.use_cases,"degraded");continue}let pe=rt??(B.ok?{record:null,errors:null}:{record:null,errors:B.kind==="validation"?B.errors:B.kind==="contended"?[{code:B.err.code,detail:`a use-case this proposal touches is held by ${B.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(pe.errors){g("commit_error_details",{errors:pe.errors.map(t=>({code:t.code,detail:t.detail}))},R.session_id),e.out(`\u2717 commit failed \u2014 ${pe.errors.map(t=>t.code).join(", ")} (details: ${ke(x)})`),e.emit?.({type:"error",source_id:s.source_id,message:`error: commit failed: ${pe.errors.map(t=>`${t.code}: ${t.detail}`).join("; ")}`}),F.push(s.source_id);continue}let xr=new Date().toISOString();for(let t of A.use_cases){let o=Ne.get(t.temp_ref)??{resolution:"skipped"};for(let l of Jt({ts:xr,command:"context extract",id:t.temp_ref,by:le},o.resolution))Kt(e.contextDir,l)}let X=pe.record;X.event_ids?.length&&w?.markApplied(X.event_ids);let st=new Map(X.review.map(t=>[t.id,t.resolution])),it=[...st.values()].filter(t=>t==="approved"||t==="edited").length,He=[...st.values()].filter(t=>t==="rejected").length,_e=X.nodes.filter(t=>!st.has(t.cid)).length,nt=X.supersessions.filter(t=>t.kind==="node"&&t.new!==t.old).length;g("commit",{trusted:it,derived:_e,archived:He},R.session_id),e.out(`saved ${it+_e} use-case(s)`+(_e>0?` \xB7 ${_e} awaiting review`:"")+(He>0?` \xB7 ${He} archived`:"")+(nt>0?` \xB7 ${nt} superseded`:""));{let t=X.review.filter(o=>o.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(o=>o.id)}))}S.assumedDefaults&&e.out(`assumed: ${S.assumedDefaults} default(s) auto-taken (assumed)`),e.emit?.({type:"commit",source_id:s.source_id,proposal_id:ie,trusted:it,derived:_e,archived:He,superseded:nt,assumed:S.assumedDefaults??0,evidence_matched:Math.max(0,A.use_cases.length-X.nodes.length),minted:X.nodes.map(t=>{let o=X.names?.find(l=>l.cid===t.cid)?.slug;return{cid:t.cid,...o?{logical_id:o}:{}}})}),u&&s.source_id in u.handle.state.read_basis&&(n(d),u.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",{}),u=null,w=null)}if(w){let d=w.state.ingest_schedule??[];d.some(s=>s.status==="pending")&&w.save({ingest_schedule:d.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(u?.handle.release(),T&&!Ee&&!vt){let n=T.state.checkpoint;if(n){let d=`kane-cli context extract --resume ${T.state.sid} --mode ${a}`;e.out(`session ${T.state.sid} kept its last checkpoint (seq ${n.seq}, ${n.ts}) \u2014 resume with: ${d}`),T.release()}else{try{T.complete()}catch{T.release()}pt()}T=null}}if(re){let n=e.chat?.state.ledger.filter(c=>c.kind==="answer"&&c.receipt.form==="assumed").length??0,d=xt+n,s=e.chat?.state.credits?.total;e.chat?.ledger?.({kind:"summary",lines:[`saved ${Ve} use-case${Ve===1?"":"s"} across ${M.length} source${M.length===1?"":"s"}`,...d>0?[`${d} assumed default(s)`]:[],...s!==void 0?[`credits used: ${s.toFixed(1)}`]:[],`trace: ${ke(x)}`]})}if(r.plan||or(e.contextDir),me>0&&(T||Ae)){Ee=!0;let n=T?.state.sid??Ae,d=`kane-cli context extract --resume ${n} --mode ${a}`;return e.out(`paused: ${me} held item(s) await review \u2014 resume with: ${d}`),e.emit?.({type:"session_paused",sid:n,resume:d,held:me}),T?.release(),3}return F.length>0&&e.out(`${F.length} of ${M.length} source(s) failed \u2014 re-run kane-cli context extract to retry (${F.join(", ")})`),_t(),F.length>0?1:0}export{mt as a,kr as b,gr as c,pr as d,Rr as e,hr as f,Ss as g};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as j}from"./chunk-CUM23TLF.js";import{a as v,d as N,g as C}from"./chunk-DUAXZYAD.js";import{a as y,e as S,f as D,g as F,h as L}from"./chunk-WXHQYYD5.js";import{existsSync as b,mkdirSync as V,readFileSync as $,renameSync as G,rmSync as J,writeFileSync as W}from"fs";import{dirname as H,join as w}from"path";var q=i=>w(i,"derived"),M=i=>w(q(i),"index.json");function T(i,s){let t=s.startsWith("sha256:")?s.slice(7):s;return w(q(i),"nodes",t.slice(0,2),t.slice(2)+".json")}function O(){return{applied:{seq:0,hash:null},heads:{},trust:{},nodeLabel:{},forward:{},extracted:[],design_of:{},design_generation:{},exec:{},superseded:{},names:{},archivedReason:{},appliedEvents:[],completeness:{},srcOwner:{},conv:{},media:{},design_phases:{}}}function U(i){let s=M(i);if(!b(s))return null;try{let t=JSON.parse($(s,"utf8"));return t.superseded===void 0||t.names===void 0||t.archivedReason===void 0||t.appliedEvents===void 0||t.conv===void 0||t.media===void 0||t.exec===void 0||t.completeness===void 0||t.srcOwner===void 0||t.design_phases===void 0||t.reverse!==void 0?null:t}catch{return null}}function P(i,s){V(H(i),{recursive:!0});let t=`${i}.tmp-${process.pid}`;W(t,s),G(t,i)}function R(i,s,t,p,_={}){let l=_.writeNodeFiles!==!1,g=new Set(s.extracted),h=new Set(s.appliedEvents);t.forEach((n,E)=>{for(let e of n.nodes){let d=T(i,e.cid);l&&!b(d)&&P(d,JSON.stringify({label:e.label,content:e.content})+`
3
+ `),!(e.cid in s.trust)&&e.content.derived===!0&&(s.trust[e.cid]="derived"),s.nodeLabel[e.cid]=e.label}for(let[e,d]of Object.entries(n.source_head_moves))typeof d=="string"&&(s.srcOwner[d]=e);if(n.proposal_id!=null&&typeof n.extraction_of=="string"){g.add(n.extraction_of);let e=null;for(let d of n.edges)if(d.type===S.DERIVES&&d.props.source_cid===n.extraction_of&&typeof d.props.source_id=="string"){e=d.props.source_id;break}if(e??=s.srcOwner[n.extraction_of]??null,e!==null){let d=s.completeness[e];(!d||n.seq>=d.seq)&&(s.completeness[e]={source_cid:n.extraction_of,completeness:"complete",...n.extractor_version?{extractor_version:n.extractor_version}:{},at:n.ts,seq:n.seq})}else s.completenessSkipped=(s.completenessSkipped??0)+1}else if(n.proposal_id!=null&&Array.isArray(n.extraction_of))for(let e of n.extraction_of){g.add(e.source_cid);let d=s.completeness[e.source_id];(!d||n.seq>=d.seq)&&(s.completeness[e.source_id]={source_cid:e.source_cid,completeness:e.completeness,...e.extractor_version?{extractor_version:e.extractor_version}:{},at:e.at,seq:n.seq})}n.design_of&&((s.design_of??={})[n.design_of.uc_cid]={engine:n.design_of.engine,seq:n.seq}),n.design_generation&&((s.design_generation??={})[n.design_generation.uc_root]={gen:n.design_generation.generation,seq:n.seq});{let e=n.design_phase;e&&typeof e.uc_root=="string"&&typeof e.phase=="string"&&typeof e.generation=="number"&&((s.design_phases??={})[e.uc_root]??=[]).push({phase:e.phase,generation:e.generation,seq:n.seq,completeness:e.completeness==="partial"?"partial":"complete"})}for(let e of n.executions??[])((s.exec??={})[e.about]??=[]).push(e);for(let e of n.edges){let{quote:d,...r}=e.props,o=s.forward[e.src]??=[];o.some(a=>a.ecid===e.ecid)||o.push({...e,props:r}),n.proposal_id!=null&&e.type===S.DERIVES&&typeof e.props.source_cid=="string"&&g.add(e.props.source_cid)}for(let e of n.review)e.resolution==="approved"||e.resolution==="edited"?(s.trust[e.id]="trusted",delete s.archivedReason[e.id]):e.resolution==="rejected"?(s.trust[e.id]="archived",e.reason?s.archivedReason[e.id]=e.reason:delete s.archivedReason[e.id]):e.resolution==="reset"&&(s.trust[e.id]="derived",delete s.archivedReason[e.id]);for(let e of n.supersessions)e.kind==="node"?e.new===e.old?delete s.superseded[e.old]:s.superseded[e.old]=e.new:s.superseded[e.ecid]=null;for(let e of n.names??[])s.names[e.slug]=e.cid;for(let[e,d]of Object.entries(n.source_head_moves))s.heads[e]=d;for(let e of n.event_ids??[])h.add(e);if(n.media)for(let[e,d]of Object.entries(n.media)){let r=n.source_head_moves[e];typeof r=="string"&&(s.media[r]=d)}if(n.conv){let e=n.source_head_moves[n.conv.source_id];if(typeof e=="string"){let d=s.conv[n.conv.source_id],r=d&&d.chain.length>0?d.chain[d.chain.length-1]:null;n.conv.append_of===r?s.conv[n.conv.source_id]={turns:n.conv.turn,chain:[...d?.chain??[],e]}:s.conv[n.conv.source_id]={turns:n.conv.turn,chain:[e]}}}for(let[e,d]of Object.entries(n.source_head_moves))n.conv?.source_id!==e&&s.conv[e]!==void 0&&(s.conv[e]=typeof d=="string"?{turns:s.conv[e].turns,chain:[d]}:{turns:s.conv[e].turns,chain:[]});s.applied={seq:n.seq,hash:p[E]}}),s.extracted=[...g].sort(),s.appliedEvents=[...h].sort()}function x(i,s){P(M(i),JSON.stringify(s)+`
4
+ `)}function K(i){let s=w(i,"meta.json");if(b(s))try{let t=JSON.parse($(s,"utf8"));if(t.schema!==y||t.canonicalizer!=="v1")throw new v(`schema fence: store is ${t.schema}/${t.canonicalizer}, this build is ${y}/${"v1"} \u2014 migrate explicitly (kane-cli context rebuild after upgrading)`)}catch(t){throw t instanceof v?t:new v(`corrupt meta.json in ${i} \u2014 fix or remove it`)}}function Y(i){K(i);let s=U(i);if(s===null){s=O();let{records:_,hashes:l}=N(i);return R(i,s,_,l),x(i,s),s}let{records:t,hashes:p}=C(i,s.applied.seq,s.applied.hash);return t.length>0&&(R(i,s,t,p),x(i,s)),s}function se(i){return J(q(i),{recursive:!0,force:!0}),Y(i)}var z=new Set(["CHAIN_ERROR","DERIVED_MISSING","DERIVED_DRIFT","NODE_FILE_MISSING","NODE_FILE_MISMATCH","NODE_FILE_CORRUPT"]);function ne(i){return z.has(i.code)?i.detail:`${i.code}: ${i.detail}`}function te(i){let s=[],t=(r,o)=>{s.push({code:r,detail:o})},p=[],_=[];try{({records:p,hashes:_}=N(i))}catch(r){return{ok:!1,issues:[{code:"CHAIN_ERROR",detail:r instanceof v?r.message:String(r)}],records:0}}let l=O();R(i,l,p,_,{writeNodeFiles:!1});let g=U(i),h=0,n=l;if(g!==null&&g.applied.seq<p.length){let r=g.applied.seq;g.applied.hash===(r===0?null:_[r-1])&&(h=p.length-r,n=O(),R(i,n,p.slice(0,r),_.slice(0,r),{writeNodeFiles:!1}))}if(g===null)t("DERIVED_MISSING","derived/index.json missing or corrupt (run kane-cli context rebuild)");else{let r=o=>JSON.stringify(k(o));for(let o of["applied","heads","trust","nodeLabel","forward","extracted","superseded","names","archivedReason","appliedEvents","conv","media","design_of","design_generation","design_phases","exec","completeness","srcOwner"])r(n[o])!==r(g[o])&&t("DERIVED_DRIFT",`derived drift in index.${o} (run kane-cli context rebuild)`)}let E=new Set;for(let r of Object.values(l.forward))for(let o of r)E.add(o.ecid);let e=new Set;for(let r of p)for(let o of r.supersessions)o.kind==="node"?(o.old in l.nodeLabel||t("SUPERSEDE_UNKNOWN_OLD",`${o.old} (record ${r.seq})`),o.new!==null&&o.new!==o.old&&!(o.new in l.nodeLabel)&&t("SUPERSEDE_UNKNOWN_NEW",`${String(o.new)} (record ${r.seq})`),o.new===o.old?e.delete(o.old):(e.has(o.old)&&t("DOUBLE_SUPERSEDE",`${o.old} re-superseded while live (record ${r.seq})`),e.add(o.old))):E.has(o.ecid)||t("SUPERSEDE_UNKNOWN_ECID",`${o.ecid} (record ${r.seq})`);for(let r of Object.keys(l.superseded)){let o=new Set,a=r;for(;a!==null&&a in l.superseded;){if(o.has(a)){t("SUPERSEDE_CYCLE",`chain from ${r} revisits ${a}`);break}o.add(a),a=l.superseded[a]}}for(let[r,o]of Object.entries(l.names))o in l.nodeLabel||t("NAME_UNKNOWN_TARGET",`slug ${r} \u2192 ${o} not in the graph`);for(let r of p)for(let o of r.edges){let a=l.nodeLabel[o.src]??"(unknown)",f=l.nodeLabel[o.dst]??"(unknown)";for(let c of L(o.type,a,f,o.props))t(c.code,`${o.ecid} ${c.detail}`)}let d=new Map;for(let r of Object.values(l.forward))for(let o of r){if(o.ecid in l.superseded)continue;let a=d.get(o.type)??[];a.push(o),d.set(o.type,a)}for(let[r,o]of d){let a=F(r);if(a?.acyclic){let f=new Map;for(let u of o)f.set(u.src,[...f.get(u.src)??[],u.dst]);let c=new Map,m=u=>{c.set(u,1);for(let I of f.get(u)??[])if(c.get(I)===1||c.get(I)===void 0&&m(I))return!0;return c.set(u,2),!1};for(let u of f.keys())if(c.get(u)===void 0&&m(u)){t("EDGE_CYCLE",`live ${r} edges form a cycle reachable from ${u}`);break}}if(a?.cardinality==="one-live-per-src"||a?.cardinality==="one-live-per-src-and-dst"){let f=new Map;for(let c of o)c.dst in l.superseded||f.set(c.src,[...f.get(c.src)??[],c]);for(let[c,m]of f)m.length>1&&t("CARDINALITY_VIOLATION",`${m.length} live ${r} edges from ${c} (one-live-per-src): ecids ${m.map(u=>u.ecid).join(",")}`)}if(a?.cardinality==="one-live-per-src-and-dst"){let f=new Map;for(let c of o)c.src in l.superseded||c.dst in l.superseded||f.set(c.dst,[...f.get(c.dst)??[],c]);for(let[c,m]of f)m.length>1&&t("CARDINALITY_VIOLATION",`${m.length} live ${r} edges onto ${c} (one-live-per-dst): ecids ${m.map(u=>u.ecid).join(",")}`)}}for(let[r,o]of Object.entries(n.nodeLabel)){let a=T(i,r);if(!b(a)){t("NODE_FILE_MISSING",`missing node file for ${r} (run kane-cli context rebuild)`);continue}try{let f=JSON.parse($(a,"utf8"));(f.label!==o||j(f.label,f.content)!==r)&&t("NODE_FILE_MISMATCH",`node file content mismatch for ${r} (run kane-cli context rebuild)`);for(let c of D(f.label,f.content))t(c.code,`${r} ${c.detail}`)}catch{t("NODE_FILE_CORRUPT",`corrupt node file for ${r} (run kane-cli context rebuild)`)}}return{ok:s.length===0,issues:s,records:p.length,...h>0?{pending:h}:{}}}function k(i){return Array.isArray(i)?i.map(k):i&&typeof i=="object"?Object.fromEntries(Object.entries(i).sort(([s],[t])=>s<t?-1:1).map(([s,t])=>[s,k(t)])):i}export{T as a,Y as b,se as c,ne as d,te as e};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{g as h}from"./chunk-AAONIIQV.js";import{d as l}from"./chunk-M7WQM4UA.js";import{b as u}from"./chunk-WWNSD6FA.js";import{d as f}from"./chunk-5YPBPZUR.js";import{existsSync as w,readFileSync as _,readdirSync as R}from"fs";import{join as p}from"path";function g(i,r){let{records:t}=l(i),o=new Set;for(let e of t)for(let n of e.review)n.resolution!=="pending"&&o.add(n.id);let s=[],d=new Set;for(let e=t.length-1;e>=0;e--)for(let n of t[e].dedup_hits??[]){if(n.new_cid===void 0)continue;let c=`${n.new_cid}|${n.candidate_cid}`;d.has(c)||(d.add(c),!o.has(n.new_cid)&&(r.superseded.has(n.new_cid)||r.superseded.has(n.candidate_cid)||r.trust.get(n.new_cid)==="derived"&&s.push({new_cid:n.new_cid,candidate_cid:n.candidate_cid,score:n.score,scorer:n.scorer})))}return s}var a=(i,r)=>i.displayNameOf(r)??r.slice(0,19);function m(i,r){return{design_children:i.edgesInto(r).filter(o=>(o.type==="belongs_to"||o.type==="scoped_to")&&!i.superseded.has(o.src)).length}}function v(i,r){let{records:t}=l(i),o=new Set,s=new Map;for(let e of t)for(let n of e.review)n.kind==="pending_archive"?s.set(n.id,n.reason):n.resolution!=="pending"&&o.add(n.id);let d=new Map;for(let[e,n]of s)r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||d.set(e,n);return{all:s,live:d}}function y(i,r){let t=[],o=new Set;for(let e of g(i.contextDir,r)){o.add(e.new_cid);let n=e.scorer==="lexical_fallback"?" (lexical fallback \u2014 the probe ran degraded)":"";t.push({kind:"PAIR",ref:a(r,e.new_cid),title:String(r.getNode(e.new_cid)?.content.title??e.new_cid.slice(0,12)),why:`possible duplicate of ${a(r,e.candidate_cid)} \u2014 score ${e.score}${n}`,pair:{candidate_cid:e.candidate_cid,candidate_ref:a(r,e.candidate_cid),score:e.score,scorer:e.scorer}})}let{all:s,live:d}=v(i.contextDir,r);for(let[e,n]of d)t.push({kind:"REVIEW",ref:a(r,e),title:String(r.getNode(e)?.content.title??e.slice(0,12)),why:`archive held for interactive confirmation${n?` \u2014 ${n}`:""}`,held:!0,impact:m(r,e)});for(let e of k(i.contextDir))t.push({kind:"MODIFY_HELD",ref:`${e.sid}:${e.tempRef}`,title:String(e.content.title??e.tempRef),why:`${e.rationale} \u2014 held by paused/dead session ${e.sid}`,heldPayload:e});for(let{cid:e,content:n}of r.byLabel(f.USECASE))r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||s.has(e)||t.push({kind:"REVIEW",ref:a(r,e),title:String(n.title??e.slice(0,12)),why:"unreviewed \u2014 approve, archive, or defer",impact:m(r,e)});return t}function F(i,r){let t={REVIEW:0,PAIR:0,MODIFY_HELD:0};for(let o of y(i,r))t[o.kind]++;return t}function b(i,r){try{let t=JSON.parse(_(p(i,"sessions",r,".lock"),"utf8"));return typeof t.pid=="number"&&u(t.pid)}catch{return!1}}function k(i){let r=[],t=p(i,"sessions");if(!w(t))return r;let o=[];try{o=R(t)}catch{return r}for(let s of o){if(!w(p(t,s,"state.json"))||b(i,s))continue;let d=[],e=!1;try{let c=h(i,s).kane;c?.pending?.proposals?.length&&(d=c.pending.proposals,e=!0)}catch{e=!1}if(!e)try{d=JSON.parse(_(p(t,s,"state.json"),"utf8")).pending?.proposals??[]}catch{continue}for(let n of d)r.push({sid:s,tempRef:String(n.tempRef??n.temp_ref??"held"),...typeof n.event_id=="string"?{event_id:n.event_id}:{},label:String(n.label??"usecase"),content:n.content??{},rationale:String(n.rationale??"held payload")})}return r}export{m as a,v as b,y as c,F as d};
2
+ import{g as h}from"./chunk-GFKCTYCA.js";import{d as l}from"./chunk-DUAXZYAD.js";import{b as u}from"./chunk-DBIBROYW.js";import{d as f}from"./chunk-WXHQYYD5.js";import{existsSync as w,readFileSync as _,readdirSync as R}from"fs";import{join as p}from"path";function g(i,r){let{records:t}=l(i),o=new Set;for(let e of t)for(let n of e.review)n.resolution!=="pending"&&o.add(n.id);let s=[],d=new Set;for(let e=t.length-1;e>=0;e--)for(let n of t[e].dedup_hits??[]){if(n.new_cid===void 0)continue;let c=`${n.new_cid}|${n.candidate_cid}`;d.has(c)||(d.add(c),!o.has(n.new_cid)&&(r.superseded.has(n.new_cid)||r.superseded.has(n.candidate_cid)||r.trust.get(n.new_cid)==="derived"&&s.push({new_cid:n.new_cid,candidate_cid:n.candidate_cid,score:n.score,scorer:n.scorer})))}return s}var a=(i,r)=>i.displayNameOf(r)??r.slice(0,19);function m(i,r){return{design_children:i.edgesInto(r).filter(o=>(o.type==="belongs_to"||o.type==="scoped_to")&&!i.superseded.has(o.src)).length}}function v(i,r){let{records:t}=l(i),o=new Set,s=new Map;for(let e of t)for(let n of e.review)n.kind==="pending_archive"?s.set(n.id,n.reason):n.resolution!=="pending"&&o.add(n.id);let d=new Map;for(let[e,n]of s)r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||d.set(e,n);return{all:s,live:d}}function y(i,r){let t=[],o=new Set;for(let e of g(i.contextDir,r)){o.add(e.new_cid);let n=e.scorer==="lexical_fallback"?" (lexical fallback \u2014 the probe ran degraded)":"";t.push({kind:"PAIR",ref:a(r,e.new_cid),title:String(r.getNode(e.new_cid)?.content.title??e.new_cid.slice(0,12)),why:`possible duplicate of ${a(r,e.candidate_cid)} \u2014 score ${e.score}${n}`,pair:{candidate_cid:e.candidate_cid,candidate_ref:a(r,e.candidate_cid),score:e.score,scorer:e.scorer}})}let{all:s,live:d}=v(i.contextDir,r);for(let[e,n]of d)t.push({kind:"REVIEW",ref:a(r,e),title:String(r.getNode(e)?.content.title??e.slice(0,12)),why:`archive held for interactive confirmation${n?` \u2014 ${n}`:""}`,held:!0,impact:m(r,e)});for(let e of k(i.contextDir))t.push({kind:"MODIFY_HELD",ref:`${e.sid}:${e.tempRef}`,title:String(e.content.title??e.tempRef),why:`${e.rationale} \u2014 held by paused/dead session ${e.sid}`,heldPayload:e});for(let{cid:e,content:n}of r.byLabel(f.USECASE))r.superseded.has(e)||r.trust.get(e)!=="derived"||o.has(e)||s.has(e)||t.push({kind:"REVIEW",ref:a(r,e),title:String(n.title??e.slice(0,12)),why:"unreviewed \u2014 approve, archive, or defer",impact:m(r,e)});return t}function F(i,r){let t={REVIEW:0,PAIR:0,MODIFY_HELD:0};for(let o of y(i,r))t[o.kind]++;return t}function b(i,r){try{let t=JSON.parse(_(p(i,"sessions",r,".lock"),"utf8"));return typeof t.pid=="number"&&u(t.pid)}catch{return!1}}function k(i){let r=[],t=p(i,"sessions");if(!w(t))return r;let o=[];try{o=R(t)}catch{return r}for(let s of o){if(!w(p(t,s,"state.json"))||b(i,s))continue;let d=[],e=!1;try{let c=h(i,s).kane;c?.pending?.proposals?.length&&(d=c.pending.proposals,e=!0)}catch{e=!1}if(!e)try{d=JSON.parse(_(p(t,s,"state.json"),"utf8")).pending?.proposals??[]}catch{continue}for(let n of d)r.push({sid:s,tempRef:String(n.tempRef??n.temp_ref??"held"),...typeof n.event_id=="string"?{event_id:n.event_id}:{},label:String(n.label??"usecase"),content:n.content??{},rationale:String(n.rationale??"held payload")})}return r}export{m as a,v as b,y as c,F as d};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{a as D}from"./chunk-CLGC7VEO.js";import{a as y}from"./chunk-YCCUBQY4.js";import{y as r}from"./chunk-27U4PLPX.js";import{a as B}from"./chunk-HCBYKLMW.js";import{a as p,b as t,i as _,k as C}from"./chunk-C44QQJR4.js";import{a as W}from"./chunk-6YGTRKDT.js";import{e as $}from"./chunk-UR6MHSHU.js";var a=$(B(),1);function G(e){let c=e.findIndex(d=>d.free);return c>=0?c:null}var F=60,N=100;function J({headline:e,ask:c=!1,rows:d,sel:i,focused:v,legend:s,freeText:f=null,freeTextNote:g,sublines:u=[]}){let{stdout:o}=C(),h=o?.columns??80,A=h<F,m=Math.min(h-1,N),b=l=>v&&i===l?(0,a.jsx)(t,{color:r.assuranceAccent,children:"\u276F"}):" ",x=c?`? ${e}`:e,R=Math.max(4,m-3),w=u.map((l,T)=>(0,a.jsx)(t,{color:r.dim,children:` ${l.length>R?`${l.slice(0,R-1)}\u2026`:l}`},`sub-${T}`)),k=0,E=d.map((l,T)=>l.free?f?(0,a.jsxs)(p,{flexDirection:"column",children:[(0,a.jsxs)(p,{children:[(0,a.jsxs)(t,{children:[(0,a.jsx)(t,{color:r.assuranceAccent,children:"\u276F"})," ",(0,a.jsx)(t,{color:r.dim,children:"\u270E "})]}),(0,a.jsx)(y,{value:f.value,onChange:f.onChange,onSubmit:f.onSubmit,onCancel:f.onCancel,placeholder:l.label})]}),g?(0,a.jsx)(t,{color:r.muted,children:` ${g}`}):null]},l.key):(0,a.jsxs)(t,{children:[b(T)," ",(0,a.jsx)(t,{color:r.dim,children:`\u270E ${l.label}`})]},l.key):(k+=1,(0,a.jsxs)(t,{bold:v&&i===T,children:[b(T),` ${k}. ${l.label}`,l.detail?(0,a.jsx)(t,{color:r.dim,bold:!1,children:` \u2014 ${l.detail}`}):null]},l.key)));if(A)return(0,a.jsxs)(p,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,a.jsx)(t,{bold:!0,color:r.assuranceAccent,children:x}),w,E,(0,a.jsx)(t,{color:r.muted,children:s})]});let M=Math.max(2,m-(3+x.length+1)),L=Math.max(2,m-(3+s.length+1));return(0,a.jsxs)(p,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,a.jsxs)(t,{color:r.assuranceAccent,children:["\u2500\u2500 ",(0,a.jsx)(t,{bold:!0,children:x}),` ${"\u2500".repeat(M)}`]}),w,(0,a.jsx)(t,{children:" "}),E,(0,a.jsx)(t,{children:" "}),(0,a.jsxs)(t,{color:r.assuranceAccent,children:["\u2500\u2500 ",(0,a.jsx)(t,{color:r.muted,children:s}),` ${"\u2500".repeat(L)}`]})]})}var S=$(B(),1),H="ctrl+t thinking \xB7 ctrl+c exit";function I(e,c){if(e.length<=c)return e;if(c<=1)return"\u2026";let d=Math.ceil((c-1)/2),i=Math.floor((c-1)/2);return`${e.slice(0,d)}\u2026${i>0?e.slice(-i):""}`}function te({verb:e,subject:c,pendingCount:d,creditsTotal:i,state:v,hints:s=H}){let{stdout:f}=C(),g=f?.columns??80,u=[];u.push(e),v&&u.push(v),i!==void 0&&u.push(`${i.toFixed(1)} credits`);let o=d?`[${d} pending]`:null,h=" \xB7 ",m=[...u,...o?[o]:[]].join(h).length,b,x=[...u,...c?[c]:[],...o?[o]:[],s].join(h);if(x.length<=g)b=x;else{let R=g-m-(c?h.length:0)-h.length-s.length;if(c&&R>=8)b=[...u,I(c,R),...o?[o]:[],s].join(h);else{let w=g-m-(c?h.length:0);b=[...u,...c&&w>=4?[I(c,w)]:[],...o?[o]:[]].join(h)}}if(v){let R=` \xB7 ${v}`,w=b.indexOf(R);if(w>=0)return(0,S.jsxs)(t,{color:r.dim,children:[b.slice(0,w+3),(0,S.jsx)(t,{color:r.assuranceAccent,children:v}),b.slice(w+R.length)]})}return(0,S.jsx)(t,{color:r.dim,children:b})}var O=$(W(),1);function re({onToggleThinking:e,onCtrlC:c,explorer:d,panel:i}){let s=(0,O.useRef)(null),f=(0,O.useRef)(""),g=()=>{s.current&&clearTimeout(s.current),s.current=null,f.current=""};return(0,O.useEffect)(()=>g,[]),_((u,o)=>{if(o.ctrl&&u==="t"){e();return}if(o.ctrl&&u==="c"){c();return}if(!o.ctrl&&u.includes("")){c();return}if(!o.ctrl&&u.includes("")){e();return}if(d&&d.isOpen()){let h=()=>{s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{g(),d.onBack()},150)};if(s.current){if(o.upArrow||o.downArrow||o.return){g(),o.return?d.onEnter():d.onMove(o.upArrow?-1:1);return}if(f.current+=u,f.current==="["){h();return}let A=f.current;g();let m=/^\[([ABCD])/.exec(A);if(m){(m[1]==="A"||m[1]==="B")&&d.onMove(m[1]==="A"?-1:1);return}d.onBack();return}if(o.upArrow){d.onMove(-1);return}if(o.downArrow){d.onMove(1);return}if(o.return){d.onEnter();return}if(o.escape){f.current="",h();return}return}if(i&&i.isFocused()){let h=()=>{s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{g(),i.onBack()},150)};if(s.current){if(o.upArrow||o.downArrow||o.return||o.leftArrow||o.rightArrow){g(),o.return?i.onSelect():o.leftArrow?i.onLeft?.():o.rightArrow?i.onRight?.():i.onMove(o.upArrow?-1:1);return}if(f.current+=u,f.current==="["){h();return}let A=f.current;g();let m=/^\[([ABCD])/.exec(A);if(m){m[1]==="A"||m[1]==="B"?i.onMove(m[1]==="A"?-1:1):m[1]==="C"?i.onRight?.():i.onLeft?.();return}i.onBack();return}if(o.upArrow){i.onMove(-1);return}if(o.downArrow){i.onMove(1);return}if(o.leftArrow){i.onLeft?.();return}if(o.rightArrow){i.onRight?.();return}if(o.return){i.onSelect();return}if(o.escape){f.current="",h();return}if(/^[1-9]$/.test(u)){i.onDigit(Number(u));return}if(o.tab){i.onTab?.();return}if(u===" "&&i.isMulti()){i.onSpace();return}if(u&&!o.ctrl&&!o.meta){i.onType(u);return}return}}),null}var n=$(B(),1);function V(e){return e.kind==="REVIEW"?[{v:"approve",label:"approve",detail:"mark it reviewed and trusted"},{v:"archive",label:"archive",detail:"reject it \u2014 asks for a reason; impact shown above"},{v:"defer",label:"defer",detail:"not now \u2014 stays queued"}]:e.kind==="PAIR"?[{v:"merge",label:"merge",detail:"duplicate \u2014 fold into the older item (it stays unreviewed)"},{v:"keep_both",label:"keep both",detail:"genuinely distinct \u2014 promote both"},{v:"defer",label:"defer",detail:"not now \u2014 stays queued"}]:e.kind==="ARCHIVE"?[{v:"archive",label:"retire",detail:"hidden from now on; history is kept and it can be reverted"},{v:"skip",label:"skip",detail:"keep it \u2014 decided, never re-offered"},{v:"defer",label:"defer",detail:"not now \u2014 the plan re-offers it"}]:e.heldPayload?[{v:"approve",label:"approve update",detail:"commit the held payload \u2014 impact preview above"},{v:"skip",label:"keep current",detail:"drop the held payload (the owner's disk state stays untouched)"},{v:"defer",label:"defer",detail:"not now \u2014 stays held"}]:[{v:"approve",label:"approve",detail:e.kind==="ADD"?"commit + design it":"commit the updated version (old\u2192new redirect)"},{v:"skip",label:e.origin==="content-change"?"reject":"skip",detail:e.origin==="content-change"?"drop the staged proposal \u2014 nothing committed":"leave it as is"},{v:"defer",label:"defer",detail:"not now \u2014 the plan keeps it staged"}]}function P(e){let c=V(e);return e.viewDiff&&c.push({v:"view_diff",label:"view diff",detail:"full old \u2192 new"}),c}function K(e){return e.kind==="ARCHIVE"?null:P(e).length}var j={ADD:{color:r.green??"green"},MODIFY:{color:"yellow"},ARCHIVE:{color:r.red},REVIEW:{color:"cyan"},PAIR:{color:"magenta"}},q=60,Q=100;function ue({card:e,position:c,sel:d=0,focused:i=!1,freeText:v=null,editorIntent:s="steer"}){let{stdout:f}=C(),g=f?.columns??80,u=g<q,o=Math.min(g-1,Q),h=P(e),A=K(e),m=j[e.kind],b=l=>i&&d===l?(0,n.jsx)(t,{color:r.assuranceAccent,children:"\u276F"}):" ",x=e.impact,R=x&&"stale_refs"in x&&x.stale_refs.length>0?`${e.kind==="ARCHIVE"?"retiring leaves":"approving marks"} ${x.stale_refs.length} item(s) stale`+((x.direct_refs?.length??0)>0?` \u2014 ${x.direct_refs.length} directly touched: ${x.direct_refs.join(", ")}`:""):x&&"design_children"in x?`${e.kind==="REVIEW"?"archiving drops":"merging folds"} ${x.design_children} design child(ren)`:null,w=`? reconcile \u2014 item ${c.n} of ${c.of}`,k=A!==null?"\u2191\u2193 \xB7 \u23CE select \xB7 1-9 \xB7 type = adjust \xB7 esc \xB7 nothing to undo":"\u2191\u2193 \xB7 \u23CE select \xB7 1-9 \xB7 esc \xB7 nothing to undo",E=(0,n.jsxs)(p,{flexDirection:"column",children:[(0,n.jsx)(p,{paddingLeft:2,children:(0,n.jsxs)(t,{bold:!0,children:[(0,n.jsx)(t,{color:m.color,children:`[${e.kind}]`}),` ${D(e.title)}`]})}),(0,n.jsx)(p,{paddingLeft:2,children:(0,n.jsx)(t,{color:r.muted,children:e.why})}),e.diffSummary?(0,n.jsx)(p,{paddingLeft:2,children:(0,n.jsx)(t,{color:r.dim,children:e.diffSummary})}):(e.diff??[]).map((l,T)=>(0,n.jsx)(p,{paddingLeft:4,children:(0,n.jsx)(t,{color:l.op==="-"?"red":"green",children:`${l.op==="-"?"\u2212":"+"} ${l.field==="criteria"?"criterion":l.field}: ${l.text}`})},`d-${T}`)),e.tier?(0,n.jsx)(p,{paddingLeft:2,children:(0,n.jsx)(t,{color:r.dim,children:`match: ${e.tier}`})}):null,(e.citeLines??[]).map((l,T)=>(0,n.jsx)(p,{paddingLeft:2,children:(0,n.jsx)(t,{color:r.dim,children:l})},`c-${T}`)),R?(0,n.jsx)(p,{paddingLeft:2,children:(0,n.jsx)(t,{color:r.muted,children:`impact: ${R}`})}):null,e.kind==="ARCHIVE"&&e.provenance&&e.provenance!==e.why?(0,n.jsx)(p,{paddingLeft:2,children:(0,n.jsx)(t,{color:r.muted,children:e.provenance})}):null,(0,n.jsx)(t,{children:" "}),h.map((l,T)=>(0,n.jsxs)(t,{children:[b(T),` ${T+1}. ${l.label}`,(0,n.jsx)(t,{color:r.dim,children:` \u2014 ${l.detail}`})]},`o-${T}`)),A!==null||v&&s==="because"?v?(0,n.jsxs)(p,{flexDirection:"column",children:[(0,n.jsxs)(p,{children:[(0,n.jsxs)(t,{children:[(0,n.jsx)(t,{color:r.assuranceAccent,children:"\u276F"})," ",(0,n.jsx)(t,{color:r.dim,children:"\u270E "})]}),(0,n.jsx)(y,{value:v.value,onChange:v.onChange,onSubmit:v.onSubmit,onCancel:v.onCancel,placeholder:s==="because"?"why archive it?":"say what to adjust"})]}),(0,n.jsx)(t,{color:r.muted,children:s==="because"?" submits as: archive \xB7 your reason goes on the record":e.kind==="PAIR"?" submits as: defer \xB7 your note parks with the card (it re-offers)":" submits as: approve \xB7 your words steer the re-design"})]}):A!==null?(0,n.jsxs)(t,{children:[b(A)," ",(0,n.jsx)(t,{color:r.dim,children:e.kind==="PAIR"?"\u270E defer with a note \u2014 say what you noticed":"\u270E approve with changes \u2014 say what to adjust"})]}):null:null]});if(u)return(0,n.jsxs)(p,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,n.jsx)(t,{bold:!0,color:r.assuranceAccent,children:w}),E,(0,n.jsx)(t,{color:r.muted,children:k})]});let M=Math.max(2,o-(3+w.length+1)),L=Math.max(2,o-(3+k.length+1));return(0,n.jsxs)(p,{marginTop:1,marginBottom:1,flexDirection:"column",children:[(0,n.jsxs)(t,{color:r.assuranceAccent,children:["\u2500\u2500 ",(0,n.jsx)(t,{bold:!0,children:w}),` ${"\u2500".repeat(M)}`]}),(0,n.jsx)(t,{children:" "}),E,(0,n.jsx)(t,{children:" "}),(0,n.jsxs)(t,{color:r.assuranceAccent,children:["\u2500\u2500 ",(0,n.jsx)(t,{color:r.muted,children:k}),` ${"\u2500".repeat(L)}`]})]})}export{G as a,J as b,te as c,re as d,V as e,P as f,K as g,ue as h};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as U}from"./chunk-DNNZ353O.js";import{a as G}from"./chunk-Q2F5QB2W.js";import{b as B,c as b}from"./chunk-NVGBE2DR.js";import{A as T}from"./chunk-TH47OOBV.js";import{a as L,c as F}from"./chunk-CUM23TLF.js";import{b as P,i as j}from"./chunk-DUAXZYAD.js";import{a as R,d as $,f as D}from"./chunk-WXHQYYD5.js";import{existsSync as ie,mkdirSync as oe,readFileSync as re,writeFileSync as se}from"fs";import{basename as C,extname as H,join as ae}from"path";var K=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function q(e){return typeof e=="string"&&e!=="."&&e!==".."&&K.test(e)}function k(e){if(!q(e))throw new Error(`unsafe logical_id: ${JSON.stringify(e)} \u2014 must match ${String(K)} (no path separators)`)}import{extname as W}from"path";var Q={kind:"jira",media_type:"application/x-kane-jira-envelope",extensions:[],cite:"verbatim",maxBytes:2e6},ee={kind:"confluence",media_type:"application/x-kane-confluence-envelope",extensions:[],cite:"verbatim",maxBytes:2e6},z=[{kind:"text",media_type:"text/plain",extensions:[".txt"],cite:"verbatim",maxBytes:2e6},{kind:"markdown",media_type:"text/markdown",extensions:[".md",".markdown"],cite:"verbatim",maxBytes:2e6},{kind:"image",media_type:"image/png",extensions:[".png"],cite:"anchor-only",maxBytes:5e6},{kind:"image",media_type:"image/jpeg",extensions:[".jpg",".jpeg"],cite:"anchor-only",maxBytes:5e6},{kind:"image",media_type:"image/webp",extensions:[".webp"],cite:"anchor-only",maxBytes:5e6},{kind:"text",media_type:"application/json",extensions:[".json"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"application/yaml",extensions:[".yaml",".yml"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"application/toml",extensions:[".toml"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"application/xml",extensions:[".xml"],cite:"verbatim",maxBytes:2e6},{kind:"text",media_type:"text/plain",extensions:[".log"],cite:"verbatim",maxBytes:2e6},{kind:"pdf",media_type:"application/pdf",extensions:[".pdf"],cite:"verbatim",maxBytes:25e6,sniff:e=>e.subarray(0,5).toString("latin1")==="%PDF-"},{kind:"docx",media_type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],cite:"verbatim",maxBytes:25e6,sniff:e=>e.length>=4&&e[0]===80&&e[1]===75&&e[2]===3&&e[3]===4,sniffFail:e=>e.length>=8&&e.subarray(0,8).equals(te)?"DOCX_ENCRYPTED_OR_LEGACY: password-protected Office file (or a legacy .doc renamed .docx) \u2014 remove the password / save as .docx and re-ingest":void 0},Q,ee],te=Buffer.from([208,207,17,224,161,177,26,225]),S={pdf:"pdf",docx:"docx",jira:"jira",confluence:"confluence"},pe=new Set(Object.keys(S));function J(e){let n=W(e).toLowerCase(),t=z.find(i=>i.extensions.includes(n));return t?{ok:!0,media:t}:{ok:!1,code:"UNSUPPORTED_MEDIA",allowlist:z.flatMap(i=>i.extensions)}}function v(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function de(e,n,t){return G({source_id:e,source_cid:"sha256:".padEnd(71,"0"),doc_kind:n,numbered_text:U(t)})}var Y=2e3;function ce(e){let t=C(e,H(e)).toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[^a-z0-9]+/,"");return k(t),t}function ke(e){let n=/^(.*?)[-_.]?v?\d+$/.exec(e);if(!n)return null;let t=(n[1]??"").replace(/[-_.]+$/,"");return t.length>0&&t!==e?t:null}function X(e){let n=ae(e,"meta.json");ie(n)||(oe(e,{recursive:!0}),se(n,JSON.stringify({schema:R,canonicalizer:"v1"},null,2)+`
3
+ `))}async function Se(e){let{contextDir:n,filePath:t,asId:i,confirmSameSource:y,converters:h}=e;X(n);let o=re(t),s=J(t);if(!s.ok)throw new Error(`${C(t)} is a file type kane can't ingest (${H(t)||"no extension"}) \u2014 supported: ${s.allowlist.join(" ")} [UNSUPPORTED_MEDIA]`);if(o.byteLength>s.media.maxBytes)throw new Error(`${C(t)} is too large \u2014 ${v(o.byteLength)}, the limit for ${s.media.media_type} is ${v(s.media.maxBytes)} [FILE_TOO_LARGE]`);if(s.media.sniff&&!s.media.sniff(o)){let m=s.media.sniffFail?.(o);throw new Error(m??`MEDIA_SNIFF_MISMATCH: ${t} does not look like ${s.media.media_type}`)}let l;return i!==void 0?(k(i),l=i):l=ce(t),le({contextDir:n,bytes:o,media:s.media,sourceId:l,label:t,confirmSameSource:y,converters:h})}async function le(e){let{contextDir:n,bytes:t,media:i,confirmSameSource:y,converters:h}=e,o=e.sourceId,s=e.label??o;if(X(n),t.byteLength>i.maxBytes)throw new Error(`the content is too large \u2014 ${v(t.byteLength)}, the limit for ${i.media_type} is ${v(i.maxBytes)} [FILE_TOO_LARGE]`);let l=[],m=S[i.kind];if(i.cite==="verbatim"&&!m){try{new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new Error(`ENCODING_UNSUPPORTED: ${s} is not valid UTF-8 \u2014 re-save it as UTF-8 and re-ingest`)}t.toString("utf8").split(`
4
+ `).some(p=>p.length>Y)&&l.push(`long line detected (> ${Y} chars) \u2014 anchors lose granularity; consider pretty-printing before ingest`)}let f=B(t),_=new Map,c=null,M=!1;for(let p=0;;p++){let x=T(n),u=x.heads.get(o),Z=u!=null?x.getNode(u)?.content:void 0;if(u!=null&&Z?.blob===f)return{status:"unchanged",source_id:o,cid:u,blob:f};if(u==null){for(let[r,g]of x.heads.entries())if(!(r===o||g==null)&&x.getNode(g)?.content.blob===f){let a;if(_.has(r)?a=_.get(r):p===0&&y?(a=await y(r),_.set(r,a)):(a=!1,_.set(r,a),p>0&&l.push(`same bytes already ingested as '${r}' \u2014 minted under '${o}' anyway (the twin appeared mid-commit; not prompted)`)),a)return{status:"unchanged",source_id:r,cid:g,blob:f};break}}if(c===null){let r={},g,a=null,O=null;if(m){let A=h?.[m];if(!A)throw new Error(`${m.toUpperCase()}_CONVERTER_MISSING: ${m} ingestion requires the converter \u2014 the command layer wires it`);let d=await A(t);a=Buffer.from(d.projection,"utf8");let N=de(o,i.kind,a);if(N>4e5)throw new Error(`PROJECTION_TOO_LARGE: serialized source payload ${N} bytes > ${4e5} \u2014 split the document and re-ingest`);r={text_blob:B(a),...d.inventory.length>0?{images:d.inventory}:{},converter:d.converter},O=d.blobs,g={kind:i.kind,...d.pages!==void 0?{pages:d.pages}:{},delivered:d.delivered.length,omitted:d.inventory.length-d.delivered.length}}c={derived:r,composite:g,projBytes:a,derivedBlobs:O}}if(!M){if(b(n,t),c.projBytes!==null&&b(n,c.projBytes),c.derivedBlobs!==null)for(let[,r]of c.derivedBlobs)b(n,r);M=!0}let w=F(o,f),E=D("source",w);if(E.length>0)throw new Error(`source node fails ${E[0].code}: ${E[0].detail}`);let I=L("source",w);try{j(n,{ts:new Date().toISOString(),proposal_id:null,nodes:[{cid:I,label:$.SOURCE,content:w}],edges:[],review:[],supersessions:[],media:{[o]:{format:i.kind,media_type:i.media_type,anchors_supported:m?["L-L","img#ref"]:i.cite==="verbatim"?["L-L"]:[],...c.derived}},...e.eventIds&&e.eventIds.length>0?{event_ids:e.eventIds}:{},source_head_moves:{[o]:I}},{expectPrev:x.latestHash})}catch(r){if(r instanceof P&&p<3)continue;throw r}return{status:u!=null?"versioned":"created",source_id:o,cid:I,blob:f,...l.length?{warnings:l}:{},...c.composite?{composite:c.composite}:{}}}}export{k as a,Q as b,ee as c,pe as d,J as e,de as f,ce as g,ke as h,Se as i,le as j};
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{closeSync as A,existsSync as $,mkdirSync as h,openSync as k,readFileSync as p,readdirSync as w,renameSync as _,rmSync as g,writeFileSync as m}from"fs";import{join as l}from"path";var a=class extends Error{constructor(r,t){super(`${r}: ${t}`);this.code=r}},d=e=>l(e,"reconcile","plans");function u(e,n){let r=`${e}.tmp-${process.pid}`;m(r,n,{mode:384}),_(r,e)}function N(e,n){let r=d(e);h(r,{recursive:!0});let t=l(r,`${n.created}-${n.source_id}.json`);return u(t,JSON.stringify(n,null,2)+`
2
+ import{closeSync as A,existsSync as $,mkdirSync as h,openSync as _,readFileSync as p,readdirSync as w,renameSync as k,rmSync as g,writeFileSync as m}from"fs";import{join as l}from"path";var a=class extends Error{constructor(r,t){super(`${r}: ${t}`);this.code=r}},d=e=>l(e,"reconcile","plans");function u(e,n){let r=`${e}.tmp-${process.pid}`;m(r,n,{mode:384}),k(r,e)}function N(e,n){let r=d(e);h(r,{recursive:!0});let t=l(r,`${n.created}-${n.source_id}.json`);return u(t,JSON.stringify(n,null,2)+`
3
3
  `),t}function y(e,n){let r=n;if(r===void 0){let o=d(e),c=[];try{c=w(o).filter(P=>P.endsWith(".json")).sort()}catch{}if(c.length===0)return{error:`no stored plans under ${o} \u2014 run reconcile --plan first`};r=l(o,c[c.length-1])}if(!$(r))return{error:`no such plan file: ${r}`};let t;try{t=p(r,"utf8")}catch(o){return{error:`cannot read plan ${r}: ${o instanceof Error?o.message:String(o)}`}}let i;try{i=JSON.parse(t)}catch(o){return{error:`corrupted plan ${r}: ${o instanceof Error?o.message:String(o)}`}}let s=i?.version;return s===1?{error:`plan predates the vocabulary change \u2014 recompute with --from <file> --source-id <id> (${r})`}:s!==2?{error:`unsupported plan version ${String(s)} in ${r} (expected 2)`}:Array.isArray(i.rows)?{plan:i,path:r}:{error:`not a reconcile plan \u2014 ${r} has no rows[] (hand-edited?)`}}function S(e){let n=e.archive_state??{};return(e.changeset??[]).filter(r=>r.kind==="ARCHIVE"&&n[r.ref]===void 0).map(r=>r.ref)}function D(e,n,r){let t=y("",e);if("error"in t)throw new a("PLAN_UNREADABLE",t.error);let i=t.plan,s=i.archive_state??{};if(s[n]!==void 0)throw new a("ROW_ALREADY_APPLIED",`archive ${n} already ${s[n].outcome}`);s[n]={at:new Date().toISOString(),outcome:r},i.archive_state=s,u(e,JSON.stringify(i,null,2)+`
4
4
  `)}function R(e,n){let r=d(e),t=[];try{t=w(r).filter(i=>i.endsWith(`-${n}.json`)).sort()}catch{}return t.length===0?null:y(e,l(r,t[t.length-1]))}function O(e,n){let r=R(e,n);if(r===null||"error"in r)return null;let t=r.plan.rows.filter(i=>i.applied===void 0).length+S(r.plan).length;return t>0?{path:r.path,created:r.plan.created,pending:t}:null}function I(e,n,r){let t;try{t=JSON.parse(p(e,"utf8"))}catch(s){throw new a("PLAN_UNREADABLE",`${e}: ${s instanceof Error?s.message:String(s)}`)}let i=t.rows?.[n];if(!i)throw new a("ROW_MISSING",`${e} has no row ${n}`);if(i.applied)throw new a("ROW_ALREADY_APPLIED",`row ${n} of ${e} was already applied (${i.applied.outcome} at ${i.applied.at})`);i.applied={at:new Date().toISOString(),outcome:r},u(e,JSON.stringify(t,null,2)+`
5
- `)}function x(e){let n=d(e);h(n,{recursive:!0});let r=l(n,".walk-lock");for(let t=0;t<2;t++)try{let i=k(r,"wx");return m(i,`${process.pid}
5
+ `)}function x(e){let n=d(e);h(n,{recursive:!0});let r=l(n,".walk-lock");for(let t=0;t<2;t++)try{let i=_(r,"wx");return m(i,`${process.pid}
6
6
  `),A(i),()=>{try{g(r)}catch{}}}catch(i){if(i.code!=="EEXIST")throw i;let s=f(r);if(!Number.isFinite(s)){let c=Date.now()+50;for(;Date.now()<c;);s=f(r)}if(Number.isFinite(s)&&E(s))throw new a("WALK_LOCKED",`another reconciliation is already running (pid ${s}) \u2014 wait for it to finish; if it appears stuck, stop that process before retrying`);try{g(r)}catch{}}throw new a("WALK_LOCKED",`could not take the walk lock at ${l(n,".walk-lock")}`)}function f(e){try{return parseInt(p(e,"utf8").trim(),10)}catch{return NaN}}function E(e){try{return process.kill(e,0),!0}catch{return!1}}export{N as a,y as b,S as c,D as d,R as e,O as f,I as g,x as h};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ var l="assurance/context@1";var u={source:{hashed:["blob","source_id"],required:["blob","source_id"],enums:{}},usecase:{hashed:["actors","criteria","derived","description","risk","summary","title","value"],required:["derived","risk","title"],enums:{risk:["high","med","low"]}},scenario:{hashed:["case_type","derived","description","intent","parameters","tags","technique_notes","title"],required:["case_type","derived","intent","title"],enums:{case_type:["happy","negative","boundary","edge","security","a11y","perf","i18n"]}},ac:{hashed:["derived","expected_answer","kind","measurable","risk","text"],required:["derived","risk","text"],enums:{risk:["high","med","low"],kind:["presence","forbidden-presence","count","delta","state-transition","absolute","bound","propagation","latency","graded"]}},test:{hashed:["check","config","definitionId","derived","objectives_blob","surface_required","test_md_blob","title"],required:["definitionId","derived","title"],enums:{}},gap:{hashed:["basis","derived","kind","question","ref","risk","risk_rationale","text","uc"],unhashed:["proposal_id","temp_ref"],required:["derived","kind"],enums:{kind:["ambiguous","incomplete","contradictory","unmeasurable","missing-expected-result","budget-evicted","invariant-unexercised","reconcile_deferred"],risk:["high","med","low"]}},stylenote:{hashed:["derived","learned_from_kind","statement","tags","text"],unhashed:["learned_from"],required:["derived","learned_from_kind","statement"],enums:{learned_from_kind:["edit","directed-edit","mistake","usage"]}}},f={DERIVES:{src:["source"],dst:["usecase","ac","scenario","test"],salient:["anchor","source_cid","source_id"],optionalSalient:["claim"],props:["anchor","claim","quote","source_cid","source_id"],pin:{comparesTo:"source_head"},cardinality:"many",acyclic:!1},belongs_to:{src:["scenario"],dst:["usecase"],salient:[],props:[],pin:{comparesTo:"dst_tip"},cardinality:"one-live-per-src",acyclic:!1},scoped_to:{src:["ac"],dst:["scenario","usecase"],salient:[],props:[],pin:{comparesTo:"dst_tip"},cardinality:"one-live-per-src",acyclic:!1},exercises:{src:["scenario"],dst:["ac"],salient:[],props:[],pin:{comparesTo:"dst_tip"},cardinality:"many",acyclic:!1},verifies:{src:["test"],dst:["ac"],salient:[],props:[],pin:{comparesTo:"dst_tip"},cardinality:"many",acyclic:!1},automates:{src:["test"],dst:["scenario"],salient:[],props:[],pin:{comparesTo:"dst_tip"},cardinality:"one-live-per-src-and-dst",acyclic:!1},depends_on:{src:["usecase","scenario"],dst:["usecase","scenario"],salient:[],props:["reason"],pin:{comparesTo:"dst_tip"},cardinality:"many",acyclic:!0},reuses:{src:["test"],dst:["test"],salient:[],props:[],pin:{comparesTo:"dst_tip"},cardinality:"many",acyclic:!0},annotates:{src:["gap","stylenote"],dst:["source","usecase","scenario","ac","test"],salient:[],props:["reason"],pin:{comparesTo:"dst_tip"},cardinality:"many",acyclic:!1}},E=["presence","forbidden-presence","count","delta","state-transition","absolute","bound","propagation","latency","graded"];var g={presence:{operators:["exists","forall"],baseline:"null",requires:[]},"forbidden-presence":{operators:["exists","forall"],baseline:"null",requires:[]},count:{operators:["equals","gte","lte"],baseline:"null",requires:[],operand_forms:["literal","derived"]},delta:{operators:["changed-by"],baseline:"required",requires:[]},"state-transition":{operators:["changed-by","equals"],baseline:"required",requires:[]},absolute:{operators:["equals","contains","gte","lte"],baseline:"null",requires:[]},bound:{operators:["gte","lte"],baseline:"null",requires:[]},propagation:{operators:["exists","equals"],baseline:"null",requires:[]},latency:{operators:["lte"],baseline:"null",requires:["within"]},graded:{operators:["gte"],baseline:"null",requires:["metric","threshold"]}},y=Object.freeze({SOURCE:"source",USECASE:"usecase",SCENARIO:"scenario",AC:"ac",TEST:"test",GAP:"gap",STYLENOTE:"stylenote"}),h=Object.freeze({DERIVES:"DERIVES",BELONGS_TO:"belongs_to",SCOPED_TO:"scoped_to",EXERCISES:"exercises",VERIFIES:"verifies",AUTOMATES:"automates",DEPENDS_ON:"depends_on",REUSES:"reuses",ANNOTATES:"annotates"});function c(n,s,i){let r=[],e=g[n];if(!e)return r.push({code:"BAD_CHECK",detail:`${i}.kind ${JSON.stringify(n)} not in ${E.join("|")}`}),r;let o=s.operator;o!==void 0&&!e.operators.includes(o)&&r.push({code:"BAD_CHECK",detail:`${i}: operator ${JSON.stringify(o)} illegal for kind "${String(n)}" (legal: ${e.operators.join("|")})`});for(let a of e.requires)(s[a]===void 0||s[a]===null||s[a]==="")&&r.push({code:"BAD_CHECK",detail:`${i}: kind "${String(n)}" requires "${a}"`});e.baseline==="null"&&s.baseline!==void 0&&s.baseline!==null&&r.push({code:"BAD_CHECK",detail:`${i}: kind "${String(n)}" must carry baseline null (only delta/state-transition have one)`});let t=s.operand;if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let a=Object.keys(t),d=t.derived;(!(e.operand_forms?.includes("derived")??!1)||a.length!==1||a[0]!=="derived"||typeof d!="string"||!d.trim())&&r.push({code:"BAD_CHECK",detail:`${i}: object operand is only the count derivation form {derived: "<how the runtime value is computed>"}`})}return r}function m(n,s){let i=u[n];if(!i)return[{code:"UNKNOWN_LABEL",detail:`unknown node label ${JSON.stringify(n)}`}];let r=[];for(let e of Object.keys(s))s[e]!==void 0&&!i.hashed.includes(e)&&!(i.unhashed??[]).includes(e)&&r.push({code:"UNKNOWN_FIELD",detail:`${n}.${e} is not in the ${l} schema`});for(let e of i.required)(s[e]===void 0||s[e]===null)&&r.push({code:"MISSING_FIELD",detail:`${n}.${e} is required`});for(let[e,o]of Object.entries(i.enums)){let t=s[e];t!==void 0&&!o.includes(t)&&r.push({code:"BAD_ENUM",detail:`${n}.${e} ${JSON.stringify(t)} not in ${o.join("|")}`})}if(n==="test"&&s.check&&typeof s.check=="object"){let e=s.check;r.push(...c(e.kind,e,"test.check"))}if(n==="ac"&&s.expected_answer&&typeof s.expected_answer=="object"){let e=s.expected_answer;r.push(...c(s.kind??e.kind,e,"ac.expected_answer"))}return r}function p(n){return f[n]}function S(n,s,i,r){let e=p(n);if(!e)return[{code:"UNKNOWN_EDGE_TYPE",detail:`unknown edge type ${JSON.stringify(n)}`}];let o=[];e.src.includes(s)||o.push({code:"ILLEGAL_EDGE",detail:`${n} src must be ${e.src.join("|")}, got ${s}`}),e.dst.includes(i)||o.push({code:"ILLEGAL_EDGE",detail:`${n} dst must be ${e.dst.join("|")}, got ${i}`}),n==="depends_on"&&s!==i&&o.push({code:"ILLEGAL_EDGE",detail:`depends_on links same-label nodes only, got ${s}\u2192${i}`});for(let t of e.salient)(r[t]===void 0||r[t]===null)&&o.push({code:"MISSING_SALIENT",detail:`${n}.props.${t} is salient (inside the ecid) and required`});for(let t of Object.keys(r))r[t]!==void 0&&(e.props.includes(t)||o.push({code:"UNKNOWN_EDGE_PROP",detail:`${n}.props.${t} is not in the ${l} schema`}));return o}function k(n,s){let i=u[n];if(!i)return s;let r={};for(let e of i.hashed)s[e]!==void 0&&(r[e]=s[e]);return r}function N(n,s){let i=p(n);if(!i)return s;let r={};for(let e of i.salient)s[e]!==void 0&&(r[e]=s[e]);for(let e of i.optionalSalient??[])s[e]!==void 0&&(r[e]=s[e]);return r}export{l as a,u as b,f as c,y as d,h as e,m as f,p as g,S as h,k as i,N as j};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as t}from"./chunk-KT6G7AF2.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
2
+ import{a as t}from"./chunk-766WGMBU.js";async function l(e){let o=e.credentials.expires_at,i=e.thresholdSeconds??300;if(o-Date.now()/1e3>=i)return null;let r=e.creds.loadClient(e.profile,e.env);if(!r)return null;let n=await new t(e.env).refreshToken(e.credentials.refresh_token,r.client_id),s=Math.floor(Date.now()/1e3)+n.expires_in;return e.creds.saveCredentials(e.profile,e.env,{access_token:n.access_token,refresh_token:n.refresh_token,expires_at:s,scope:n.scope}),{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:s,scope:n.scope}}export{l as a};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{d,e as f}from"./chunk-WXHQYYD5.js";var G={high:3,med:2,low:1},R={create:0,evolve:1,"reuse-candidate":2},_=.75;function a(e,n){return!e.superseded.has(n)&&e.trust.get(n)!=="archived"}function E(e,n){return e.edgesInto(n).some(t=>t.type===f.VERIFIES&&a(e,t.src))}function m(e,n="med"){let t=e.risk;return t==="high"||t==="med"||t==="low"?t:n}function u(e,n){return e.displayNameOf(n)??n}function y(e,n){return`kane-cli design tests --use-case ${u(e,n)}`}function b(e,n){let t=e.edgesFrom(n).find(i=>i.type===f.SCOPED_TO&&a(e,i.dst));if(!t)return null;let s=e.nodeLabel.get(t.dst);if(s===d.USECASE)return t.dst;if(s===d.SCENARIO){let i=e.edgesFrom(t.dst).find(r=>r.type===f.BELONGS_TO&&a(e,r.dst));return i?i.dst:null}return null}function v(e,n){let t=b(e,n);return t?y(e,t):w(e,n)}function w(e,n){return`kane-cli design explain ${u(e,n)}`}function h(e,n){let t=e.edgesFrom(n).find(i=>i.type===f.AUTOMATES&&a(e,i.dst));if(!t)return null;let s=e.edgesFrom(t.dst).find(i=>i.type===f.BELONGS_TO&&a(e,i.dst));return s?s.dst:null}function x(e){let n=[];for(let{cid:t,content:s}of e.byLabel(d.AC))a(e,t)&&(E(e,t)||n.push({ref:u(e,t),kind:"no-verifies",why:"no live test verifies this acceptance criterion",risk:m(s),stage:"design",tag:"create",ready_command:v(e,t)}));return n}function S(e){let n=[];for(let{cid:t,content:s}of e.byLabel(d.USECASE)){if(!a(e,t))continue;let i=e.edgesInto(t).filter(o=>o.type===f.BELONGS_TO&&a(e,o.src));if(i.length===0){n.push({ref:u(e,t),kind:"zero-scenario",why:"use-case has no scenarios",risk:m(s),stage:"design",tag:"create",ready_command:y(e,t)});continue}i.every(o=>e.getNode(o.src)?.content.case_type==="happy")&&n.push({ref:u(e,t),kind:"happy-only",why:"use-case is exercised by happy-path scenarios only",risk:m(s),stage:"design",tag:"create",ready_command:y(e,t)})}return n}function L(e){let n=[];for(let{cid:t,content:s}of e.byLabel(d.GAP)){if(!a(e,t))continue;let i=s.ref,r=typeof i=="string"?e.resolve(i):null,o=r&&a(e,r.tip)?r.tip:null,l=o?e.nodeLabel.get(o):null,p=s.kind==="reconcile_deferred"?"kane-cli maintain reconcile":l===d.USECASE?y(e,o):l===d.AC?v(e,o):w(e,t),c=s.question&&typeof s.question=="object"?s.question:void 0,g=typeof s.text=="string"&&s.text||(c&&typeof c.header=="string"?c.header:"")||"design gap";n.push({ref:u(e,t),kind:String(s.kind),why:g,risk:m(s),stage:"design",tag:"create",ready_command:p,...typeof s.risk_rationale=="string"?{risk_rationale:s.risk_rationale}:{},...c?{question:c}:{}})}return n}function C(e){let n=[];for(let{cid:t,content:s}of e.byLabel(d.AC)){if(!a(e,t))continue;let i=e.stale(t);i==="fresh"||i==="superseded"||n.push({ref:u(e,t),kind:"stale-ac",why:`acceptance criterion is ${i} \u2014 its source moved since this was authored \xB7 why: kane-cli design explain ${u(e,t)}`,risk:m(s),stage:"design",tag:"evolve",ready_command:"kane-cli maintain reconcile"})}for(let{cid:t,content:s}of e.byLabel(d.TEST)){if(!a(e,t))continue;let i=e.stale(t);if(i==="fresh"||i==="superseded")continue;let r=e.edgesFrom(t).filter(k=>k.type===f.VERIFIES&&a(e,k.dst)),o=r.map(k=>m(e.getNode(k.dst)?.content??{})),l=o.includes("high")?"high":o.includes("med")?"med":o.includes("low")?"low":"med",p=r[0]?.dst??null,c=p?null:h(e,t),g=p?v(e,p):c?y(e,c):w(e,t);n.push({ref:u(e,t),kind:"stale-test",why:`test is ${i} \u2014 its source moved since this was authored`,risk:l,stage:"design",tag:"evolve",ready_command:g})}return n}async function O(e,n,t){for(let s of e)if(s.tag==="create"){if(!t){s.meta={embed_arm:"skipped"};continue}try{let i=n.resolve(s.ref),r=i?n.getNode(i.tip):null,o=r&&(String(r.content.title??"")||String(r.content.text??""))||s.why,l=r?.label===d.USECASE?"scenario":"test",c=(await t.searchSimilar(o,{label:l,k:1}))[0];c&&c.score>=_?(s.tag="reuse-candidate",s.meta={embed_arm:"used",near_hit:{ref:u(n,c.cid),score:c.score}}):s.meta={embed_arm:"used",near_hit:null}}catch{s.meta={embed_arm:"skipped"}}}}function A(e,n){let t=G[n.risk]-G[e.risk];if(t!==0)return t;let s=R[e.tag]-R[n.tag];return s!==0?s:e.ref<n.ref?-1:e.ref>n.ref?1:0}function T(e,n){let t=[],s=r=>{let o=e.resolve(r);return o&&!o.superseded?m(e.getNode(o.tip)?.content??{}):"med"},i=r=>{let o=e.resolve(r),l=o&&!o.superseded?b(e,o.tip):null;return l?u(e,l):r};for(let r of n.usecases??[])for(let o of r.acceptance_criteria??[])(o.covered_by??[]).length>0&&(o.execution==="failed"?t.push({ref:o.id,kind:"execution-failed",stage:"cover",tag:"evolve",risk:s(o.id),why:`covering test failed against this AC (tests: ${(o.covered_by??[]).join(", ")})`,ready_command:`kane-cli maintain evolve ${i(o.id)}`}):o.execution==="blocked"?t.push({ref:o.id,kind:"execution-blocked",stage:"cover",tag:"reuse-candidate",risk:s(o.id),why:"the oracle could not run (infrastructure) \u2014 the covering test exists and is reusable",ready_command:"kane-cli testrun run"}):o.execution==="not-run"&&t.push({ref:o.id,kind:"covered-not-run",stage:"cover",tag:"reuse-candidate",risk:s(o.id),why:"a covering test exists but never joined this pack \u2014 run it",ready_command:"kane-cli testrun run"}));return t}async function N(e,n,t,s){if(n!=="design"&&!s)throw new Error(`gaps-engine: stage "${n}" requires a pack's usecases doc`);let i=[];return(n==="design"||n==="all")&&i.push(...x(e),...S(e),...L(e),...C(e)),(n==="cover"||n==="all")&&i.push(...T(e,s)),await O(i,e,t),i.sort(A),i}export{a,E as b,b as c,N as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{Q as O,S}from"./chunk-DQ54MH7F.js";import{c as L}from"./chunk-RFHMDQXZ.js";import{m as P,n as R}from"./chunk-W6VD2XFO.js";import{y as s}from"./chunk-C4G7RVJ6.js";import{a as y}from"./chunk-HCBYKLMW.js";import{a as E,b as o,i as h}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var n=d(B(),1);import{basename as D}from"path";var r=d(y(),1),U="evidence-view-server";function Q({packPath:m,viewerBase:w,onDone:V,openUrl:k}){let[t,a]=(0,n.useState)("ask"),[g,b]=(0,n.useState)(null),[l,p]=(0,n.useState)(null),f=(0,n.useRef)(null),u=(0,n.useRef)(!1),x=async()=>{let e=f.current;f.current=null,e&&(R(U),await e.close())},v=()=>{u.current||(u.current=!0,V())};return h((e,i)=>{u.current||(t==="ask"?e==="y"||e==="Y"?a("starting"):(e==="n"||e==="N"||i.return||i.escape)&&v():t==="serving"&&(e==="q"||e==="Q"||i.escape)&&x().then(v))}),(0,n.useEffect)(()=>{if(t!=="starting")return;let e=!1;return(async()=>{try{let i=D(m),c=await O({packs:new Map([[i,m]]),allowedOrigins:[new URL(w).origin]});if(e){await c.close();return}f.current=c,P(U,()=>{c.close()});let T=S(c.urlFor(i),w);b(T);try{await(k??(q=>L(q)))(T)}catch{p("could not open browser \u2014 open the URL manually")}a("serving")}catch(i){p(`evidence view failed \u2014 ${i.message}`),a("failed")}})(),()=>{e=!0}},[t]),(0,n.useEffect)(()=>{if(t!=="failed")return;let e=setTimeout(v,0);return()=>clearTimeout(e)},[t]),(0,n.useEffect)(()=>()=>{x()},[]),t==="ask"?(0,r.jsxs)(o,{children:["View evidence in browser? ",(0,r.jsx)(o,{color:s.dim,children:"(y/N)"})]}):t==="serving"||t==="starting"?(0,r.jsxs)(E,{flexDirection:"column",children:[g?(0,r.jsxs)(o,{children:["viewer ",(0,r.jsx)(o,{color:s.orange,children:g})]}):(0,r.jsx)(o,{color:s.dim,children:"starting\u2026"}),l?(0,r.jsx)(o,{color:"yellow",children:l}):null,t==="serving"?(0,r.jsx)(o,{color:s.dim,children:"Press q when done"}):null]}):l?(0,r.jsx)(o,{color:"yellow",children:l}):null}export{Q as a};
2
+ import{O,Q as S}from"./chunk-ZVHCQMJ6.js";import{c as L}from"./chunk-RFHMDQXZ.js";import{m as P,n as R}from"./chunk-56PAQAX5.js";import{y as s}from"./chunk-27U4PLPX.js";import{a as y}from"./chunk-HCBYKLMW.js";import{a as E,b as o,i as h}from"./chunk-C44QQJR4.js";import{a as B}from"./chunk-6YGTRKDT.js";import{e as d}from"./chunk-UR6MHSHU.js";var n=d(B(),1);import{basename as D}from"path";var r=d(y(),1),U="evidence-view-server";function Q({packPath:m,viewerBase:w,onDone:V,openUrl:k}){let[t,a]=(0,n.useState)("ask"),[g,b]=(0,n.useState)(null),[l,p]=(0,n.useState)(null),f=(0,n.useRef)(null),u=(0,n.useRef)(!1),x=async()=>{let e=f.current;f.current=null,e&&(R(U),await e.close())},v=()=>{u.current||(u.current=!0,V())};return h((e,i)=>{u.current||(t==="ask"?e==="y"||e==="Y"?a("starting"):(e==="n"||e==="N"||i.return||i.escape)&&v():t==="serving"&&(e==="q"||e==="Q"||i.escape)&&x().then(v))}),(0,n.useEffect)(()=>{if(t!=="starting")return;let e=!1;return(async()=>{try{let i=D(m),c=await O({packs:new Map([[i,m]]),allowedOrigins:[new URL(w).origin]});if(e){await c.close();return}f.current=c,P(U,()=>{c.close()});let T=S(c.urlFor(i),w);b(T);try{await(k??(q=>L(q)))(T)}catch{p("could not open browser \u2014 open the URL manually")}a("serving")}catch(i){p(`evidence view failed \u2014 ${i.message}`),a("failed")}})(),()=>{e=!0}},[t]),(0,n.useEffect)(()=>{if(t!=="failed")return;let e=setTimeout(v,0);return()=>clearTimeout(e)},[t]),(0,n.useEffect)(()=>()=>{x()},[]),t==="ask"?(0,r.jsxs)(o,{children:["View evidence in browser? ",(0,r.jsx)(o,{color:s.dim,children:"(y/N)"})]}):t==="serving"||t==="starting"?(0,r.jsxs)(E,{flexDirection:"column",children:[g?(0,r.jsxs)(o,{children:["viewer ",(0,r.jsx)(o,{color:s.orange,children:g})]}):(0,r.jsx)(o,{color:s.dim,children:"starting\u2026"}),l?(0,r.jsx)(o,{color:"yellow",children:l}):null,t==="serving"?(0,r.jsx)(o,{color:s.dim,children:"Press q when done"}):null]}):l?(0,r.jsx)(o,{color:"yellow",children:l}):null}export{Q as a};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{a as f}from"./chunk-6HEGD6H2.js";import{a as h}from"./chunk-FPFOW6BS.js";import{a as m}from"./chunk-JRMDGLLT.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:p,log:t}=c,e=null,u=null;if(l&&p)e={username:l,access_key:p},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,g=new h(v.controllerBaseUrl,b,y,t),s=await g.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:g,resolvedCreds:s}}export{o as a,k as b};
2
+ import{a as h}from"./chunk-OTTGS2TE.js";import{a as f}from"./chunk-XO5ZH3ZR.js";import{a as m}from"./chunk-G7VQCS4J.js";var o=class extends Error{constructor(a,l){super(a);this.code=l;this.name="AuthError"}};async function k(c){let{creds:i,env:a,usernameFlag:l,accessKeyFlag:p,log:t}=c,e=null,u=null;if(l&&p)e={username:l,access_key:p},t("info","AUTH_RESOLVE_FLAGS","Auth resolved via CLI flags",{username:l});else{let r=i.resolveAuth();r?.method==="basic"&&(e={username:r.username,access_key:r.access_key},t("info","AUTH_RESOLVE_CONFIG","Auth resolved via config",{username:r.username}))}if(!e){let{credentials:r,profile:E}=i.getActiveCredentials();if(!r)throw new o("Not authenticated \u2014 no credentials found","not_authenticated");if(u=r.access_token,r.expires_at-Date.now()/1e3<300)try{let n=await f({creds:i,profile:E,env:a,credentials:r});n&&(u=n.accessToken,t("info","AUTH_TOKEN_REFRESHED","OAuth token refreshed"))}catch(n){let d=n instanceof Error?n.message:String(n);throw t("error","TOKEN_REFRESH_FAILED","Token refresh failed",{error:d}),new o(`Token refresh failed: ${d}`,"refresh_failed")}}let v=m(a),b=async()=>u,y=e?{username:e.username,access_key:e.access_key}:null,g=new h(v.controllerBaseUrl,b,y,t),s=await g.resolve();return s&&!e&&(e={username:s.username,access_key:s.access_key},t("info","AUTH_RESOLVE_CONTROLLER","Auth resolved via controller",{username:s.username})),{basicAuth:e,token:u,resolver:g,resolvedCreds:s}}export{o as a,k as b};
@@ -0,0 +1,4 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ import{b as u,d as f,e as l}from"./chunk-FNH55WSR.js";import{a as p}from"./chunk-TZXXJWHA.js";function d(t,r,e){return{id:`${t}.internal`,label:r,required:!0,status:"fail",detail:e instanceof Error?e.message:String(e)}}async function $(t,r={}){let e=p();if(!e.supported)return{sections:[{platform:"host",checks:[{id:"host.platform",label:"host",required:!0,status:"fail",detail:e.reason}],targets:[]}]};let n=t?u().filter(s=>s.toLowerCase()===t.toLowerCase()):u(),c=[];for(let s of n){let o=f(s);if(!o)continue;let i;try{i=await o.checks(r)}catch(h){i=[d(s,"toolchain check",h)]}let a=[];if(r.targets)try{a=await l(s)}catch{}c.push({platform:s,checks:i,targets:a})}return{sections:c}}function g(t){return t==="pass"?"\u2713":t==="fail"?"\u2717":"\u2139"}function m(t){return t.charAt(0).toUpperCase()+t.slice(1)}function k(t){if(t.state==="stopped")return`${t.kind==="simulator"?"simulator":"virtual device"}, stopped (bootable)`;let r=t.kind==="simulator"?"simulator":"emulator";return t.state==="ready"?`${r}, ready`:t.state==="unauthorized"?`${r}, UNAUTHORIZED \u2192 accept the USB-debugging prompt on the device`:`${r}, offline \u2192 reconnect the device, then re-run`}function x(t){return t.state==="ready"||t.state==="stopped"?"\u2713":"\u2717"}function y(t,r={}){let e=[];if(t.sections.length===0)return"No mobile platforms are supported on this host.";for(let n of t.sections){e.length>0&&e.push(""),e.push(`${m(n.platform)} toolchain`);let c=r.verbose?n.checks:n.checks.filter(o=>o.status!=="info"),s=new Set;for(let o of c){let i=o.detail?` \u2014 ${o.detail}`:"";if(e.push(` ${g(o.status)} ${o.label}${i}`),o.status==="fail"&&o.fixText&&!s.has(o.fixText)){s.add(o.fixText);for(let a of o.fixText.split(`
3
+ `))e.push(` fix: ${a}`)}}if(n.targets.length>0){e.push(" Targets");for(let o of n.targets){let i=o.id===o.displayName?o.displayName:`${o.displayName} (${o.id})`;e.push(` ${x(o)} ${i} \u2014 ${k(o)}`)}}}return e.join(`
4
+ `)}function T(t){return t.sections.length===0?!0:t.sections.every(r=>r.checks.some(e=>e.required&&e.status==="fail"&&!e.fixedByBundle))}function C(t){for(let r of t.sections)for(let e of r.checks)if(e.required&&e.status!=="pass")return 2;return 0}export{$ as a,y as b,T as c,C as d};
@@ -1,2 +1,2 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{b as N}from"./chunk-L2TV4G56.js";import{b as y,c as E,d as $,f as O,g as A,h as V,i as I,j as T}from"./chunk-AAONIIQV.js";import{c as P}from"./chunk-GVIPTX6T.js";import{a as x,f as C}from"./chunk-M7WQM4UA.js";var G={extract:e=>`kane-cli context extract --resume ${e}`,design:e=>`kane-cli design tests --resume ${e}`};function Q(e,n,s){if(e===void 0||e===n)return null;if(e==="extract"||e==="design"){let a=G[e](s);return{code:"WRONG_VERB",message:`error: session ${s} is a ${e} session \u2014 resume it with ${a}`,next:[{cmd:a,why:`this session belongs to a ${e} run`}]}}return{code:"WRONG_VERB",message:`error: session ${s} belongs to a ${e} run \u2014 this command cannot resume it`,next:[]}}import{existsSync as K}from"fs";import{join as M}from"path";function ne(e){return{id:e.id,text:e.question,risk:["high","med","low"].includes(e.risk)?e.risk:"med",rationale:e.rationale,options:e.options.map(n=>({label:n.label,detail:n.description??""})),recommended_index:e.recommendedOptionIndex,allow_free_text:e.allowFreeText,kind:e.kind,consequence:e.consequence,evidence_count:e.evidence_count,multi_select:e.multiSelect}}function B(e){return{id:e.id,header:e.kind??"question",question:e.text,kind:e.kind??"clarify",multiSelect:e.multi_select??!1,options:e.options.map((n,s)=>({id:`o${s}`,label:n.label,description:n.detail||void 0})),recommendedOptionIndex:e.recommended_index,risk:e.risk,rationale:e.rationale,consequence:e.consequence??"",evidence_count:e.evidence_count,allowFreeText:e.allow_free_text}}function se(e,n){e.save({agent_state:n.agent_state,pending:{questions:n.pending.questions.map(B),proposals:n.pending.proposals??[]},assumed:n.assumed.map(s=>({questionId:s.question_id,optionId:s.option_id,flagged:!0,eventId:`assumed:${n.sid}:${s.question_id}`}))}),e.release(),$(e.state.sid)}function te(e){return{persist(n){let s=e.seqBase(),a={seq:n.seq+s,turn_id:n.turn_id,at:n.at,agent_state_schema:n.agent_state_schema,delta_items:n.delta_items,binding:n.binding,usage_total:n.usage_total,...n.base_fingerprint!==void 0?{base_fingerprint:n.base_fingerprint}:{}},l={applied_events:[...new Set([...e.handle.state.applied_events,...V(e.contextDir,e.handle.state.sid)])].sort(),held_receipts:e.peekHeldReceipts?.()??[],pending:{questions:n.at!=="turn"?(n.pending_questions??[]).map(B):[],proposals:e.stagedProposals?.()??[]},parent_asks:[],read_basis:e.readBasis(),corpus_cursor:e.corpusCursor(),store_watermark:C(e.contextDir),...(()=>{let o=e.ingestRegistry?e.ingestRegistry():e.handle.state.ingest_registry??[],p=e.ingestSchedule?e.ingestSchedule():e.handle.state.ingest_schedule??[];return{...o.length?{ingest_registry:o}:{},...p.length?{ingest_schedule:p}:{}}})()};return O(e.contextDir,e.handle,a,l,{...e.onSoftCap?{onSoftCap:e.onSoftCap}:{},...e.onStat?{onStat:e.onStat}:{},...e.now?{now:e.now}:{}})}}}var m=class extends Error{constructor(s,a,l=[]){super(`${s}: ${a}`);this.code=s;this.next=l}};async function ie(e,n,s,a={}){let l=a.deps??{},o=P(e,n);try{let p=o.state.checkpoint??null,w=K(M(e,"sessions",n,y,E)),j=!p&&o.state.agent_state.items.length>0;if(!p&&!w||j)throw new m("SESSION_V1",`session ${n} predates durable checkpoints \u2014 this build cannot resume it; abandon it with kane-cli context sessions clean ${n} and start a fresh run (committed work is untouched)`,[{cmd:`kane-cli context sessions clean ${n}`,why:"abandon the pre-checkpoint session, then start a fresh run"}]);!p&&w&&l.onWarn?.(`session ${n}: checkpoint chain present with no pointer \u2014 recovering from the chain`);let c=A(e,n);c.orphans.length>0&&T(e,n,c.orphans),c.fallback&&l.onWarn?.(`session ${n}: chain truncated to checkpoint ${c.fallback.resumableAt} \u2014 ${c.fallback.turnsLost} turn(s) lost to a corrupt record`);let r=c.base;if(a.verb){let i=Q(r.verb,a.verb,n);if(i)throw new m("WRONG_VERB",i.message,i.next)}if(a.useCase!==void 0&&a.useCase!==r.use_case&&!await(l.confirmRetarget?.(r.use_case,a.useCase)??!1))throw new m("RESUME_RETARGET_DECLINED",r.use_case?`session ${n} was designing ${r.use_case}; resuming onto ${a.useCase} needs an explicit retarget`:`session ${n} has no recorded use-case; adopting ${a.useCase} needs an explicit retarget`,r.use_case?[{cmd:`kane-cli design tests --resume ${n}`,why:`continue on ${r.use_case} (the session's own subject)`}]:[]);let d=c.kane,f=[],H=d?.read_basis??Object.fromEntries(Object.entries(o.state.read_basis));for(let[i,t]of Object.entries(H)){let u=s.heads.get(i)??null;u!==t&&f.push({subject:i,pinned:t,live:u})}r.uc_tip!==void 0&&l.liveUcTip!==void 0&&l.liveUcTip!==r.uc_tip&&f.push({subject:r.use_case??"use-case",pinned:r.uc_tip,live:l.liveUcTip}),l.locks?.reacquire?.(n);let _={...r.run_config,checkpoints:!0};delete _.resume;let R;if(c.pointer===null||c.agent===null)R=_;else{if(!c.agent.base_fingerprint)throw new m("CHECKPOINT_PROTOCOL",`session ${n}: chain carries no base fingerprint \u2014 cannot attest the seed rebuild`);R={..._,resume:{schema:2,binding:c.agent.binding,base_fingerprint:c.agent.base_fingerprint,delta_items:c.agent.delta_items,last_seq:c.pointer.seq}}}let S=d?.pending.questions??[],b=i=>{let t=`resolveq:${n}:${i}`,u=`assumed:${n}:${i}`;return s.appliedEvents.has(t)||s.appliedEvents.has(u)||o.isApplied(t)||o.isApplied(u)},W=d&&S.length>0?S.filter(i=>!b(i.id)):o.state.pending.questions.filter(i=>!b(i.id)),v={redeliverReceipts:[],recommit:[]},h,k;if(d){let i={...d,applied_events:[...new Set([...d.applied_events,...o.state.applied_events])].sort()},t;try{t=I(e,n,i,s,{verb:r.verb==="design"?"design":"extract",...r.use_case?{ucRef:r.use_case}:{},composeReceipt:(g,q,D)=>N(g,q,D),onNote:l.onWarn})}catch(g){throw g instanceof x?new m("CHECKPOINT_PROTOCOL",`store reconciliation refused: ${g.message}`,[{cmd:`kane-cli context sessions clean ${n}`,why:"abandon the session if the store was rebuilt"}]):g}v={redeliverReceipts:t.redeliverReceipts,recommit:t.recommit},k=t.prunedPending;let u=d.pending.proposals??[];h=(u.length>0?u:o.state.pending.proposals).filter(g=>!(typeof g.event_id=="string"&&s.appliedEvents.has(g.event_id))),(t.newlyApplied.length>0||t.prunedPending.length>0)&&o.reconcileSave({appliedEvents:t.newlyApplied,heldReceipts:[...o.state.held_receipts??[],...t.redeliverReceipts],pending:{questions:o.state.pending.questions,proposals:h}})}else{let i=o.state.pending.proposals;k=i.filter(t=>typeof t.event_id=="string"&&s.appliedEvents.has(t.event_id)),h=i.filter(t=>!(typeof t.event_id=="string"&&s.appliedEvents.has(t.event_id)))}return{kind:"v2",handle:o,base:r,view:c,kane:d,spawnConfig:R,drift:f,reconcile:v,questions:W,represent:h,prunedPending:k}}catch(p){throw o.release(),p}}export{Q as a,ne as b,se as c,te as d,m as e,ie as f};
2
+ import{b as N}from"./chunk-L2TV4G56.js";import{b as y,c as E,d as $,f as O,g as A,h as V,i as I,j as T}from"./chunk-GFKCTYCA.js";import{c as x}from"./chunk-IDX3TOPY.js";import{a as C,f as P}from"./chunk-DUAXZYAD.js";var G={extract:e=>`kane-cli context extract --resume ${e}`,design:e=>`kane-cli design tests --resume ${e}`};function Q(e,n,s){if(e===void 0||e===n)return null;if(e==="extract"||e==="design"){let a=G[e](s);return{code:"WRONG_VERB",message:`error: session ${s} is a ${e} session \u2014 resume it with ${a}`,next:[{cmd:a,why:`this session belongs to a ${e} run`}]}}return{code:"WRONG_VERB",message:`error: session ${s} belongs to a ${e} run \u2014 this command cannot resume it`,next:[]}}import{existsSync as K}from"fs";import{join as M}from"path";function ne(e){return{id:e.id,text:e.question,risk:["high","med","low"].includes(e.risk)?e.risk:"med",rationale:e.rationale,options:e.options.map(n=>({label:n.label,detail:n.description??""})),recommended_index:e.recommendedOptionIndex,allow_free_text:e.allowFreeText,kind:e.kind,consequence:e.consequence,evidence_count:e.evidence_count,multi_select:e.multiSelect}}function B(e){return{id:e.id,header:e.kind??"question",question:e.text,kind:e.kind??"clarify",multiSelect:e.multi_select??!1,options:e.options.map((n,s)=>({id:`o${s}`,label:n.label,description:n.detail||void 0})),recommendedOptionIndex:e.recommended_index,risk:e.risk,rationale:e.rationale,consequence:e.consequence??"",evidence_count:e.evidence_count,allowFreeText:e.allow_free_text}}function se(e,n){e.save({agent_state:n.agent_state,pending:{questions:n.pending.questions.map(B),proposals:n.pending.proposals??[]},assumed:n.assumed.map(s=>({questionId:s.question_id,optionId:s.option_id,flagged:!0,eventId:`assumed:${n.sid}:${s.question_id}`}))}),e.release(),$(e.state.sid)}function te(e){return{persist(n){let s=e.seqBase(),a={seq:n.seq+s,turn_id:n.turn_id,at:n.at,agent_state_schema:n.agent_state_schema,delta_items:n.delta_items,binding:n.binding,usage_total:n.usage_total,...n.base_fingerprint!==void 0?{base_fingerprint:n.base_fingerprint}:{}},l={applied_events:[...new Set([...e.handle.state.applied_events,...V(e.contextDir,e.handle.state.sid)])].sort(),held_receipts:e.peekHeldReceipts?.()??[],pending:{questions:n.at!=="turn"?(n.pending_questions??[]).map(B):[],proposals:e.stagedProposals?.()??[]},parent_asks:[],read_basis:e.readBasis(),corpus_cursor:e.corpusCursor(),store_watermark:P(e.contextDir),...(()=>{let o=e.ingestRegistry?e.ingestRegistry():e.handle.state.ingest_registry??[],p=e.ingestSchedule?e.ingestSchedule():e.handle.state.ingest_schedule??[];return{...o.length?{ingest_registry:o}:{},...p.length?{ingest_schedule:p}:{}}})()};return O(e.contextDir,e.handle,a,l,{...e.onSoftCap?{onSoftCap:e.onSoftCap}:{},...e.onStat?{onStat:e.onStat}:{},...e.now?{now:e.now}:{}})}}}var m=class extends Error{constructor(s,a,l=[]){super(`${s}: ${a}`);this.code=s;this.next=l}};async function ie(e,n,s,a={}){let l=a.deps??{},o=x(e,n);try{let p=o.state.checkpoint??null,w=K(M(e,"sessions",n,y,E)),j=!p&&o.state.agent_state.items.length>0;if(!p&&!w||j)throw new m("SESSION_V1",`session ${n} predates durable checkpoints \u2014 this build cannot resume it; abandon it with kane-cli context sessions clean ${n} and start a fresh run (committed work is untouched)`,[{cmd:`kane-cli context sessions clean ${n}`,why:"abandon the pre-checkpoint session, then start a fresh run"}]);!p&&w&&l.onWarn?.(`session ${n}: checkpoint chain present with no pointer \u2014 recovering from the chain`);let c=A(e,n);c.orphans.length>0&&T(e,n,c.orphans),c.fallback&&l.onWarn?.(`session ${n}: chain truncated to checkpoint ${c.fallback.resumableAt} \u2014 ${c.fallback.turnsLost} turn(s) lost to a corrupt record`);let r=c.base;if(a.verb){let i=Q(r.verb,a.verb,n);if(i)throw new m("WRONG_VERB",i.message,i.next)}if(a.useCase!==void 0&&a.useCase!==r.use_case&&!await(l.confirmRetarget?.(r.use_case,a.useCase)??!1))throw new m("RESUME_RETARGET_DECLINED",r.use_case?`session ${n} was designing ${r.use_case}; resuming onto ${a.useCase} needs an explicit retarget`:`session ${n} has no recorded use-case; adopting ${a.useCase} needs an explicit retarget`,r.use_case?[{cmd:`kane-cli design tests --resume ${n}`,why:`continue on ${r.use_case} (the session's own subject)`}]:[]);let d=c.kane,f=[],H=d?.read_basis??Object.fromEntries(Object.entries(o.state.read_basis));for(let[i,t]of Object.entries(H)){let u=s.heads.get(i)??null;u!==t&&f.push({subject:i,pinned:t,live:u})}r.uc_tip!==void 0&&l.liveUcTip!==void 0&&l.liveUcTip!==r.uc_tip&&f.push({subject:r.use_case??"use-case",pinned:r.uc_tip,live:l.liveUcTip}),l.locks?.reacquire?.(n);let _={...r.run_config,checkpoints:!0};delete _.resume;let R;if(c.pointer===null||c.agent===null)R=_;else{if(!c.agent.base_fingerprint)throw new m("CHECKPOINT_PROTOCOL",`session ${n}: chain carries no base fingerprint \u2014 cannot attest the seed rebuild`);R={..._,resume:{schema:2,binding:c.agent.binding,base_fingerprint:c.agent.base_fingerprint,delta_items:c.agent.delta_items,last_seq:c.pointer.seq}}}let S=d?.pending.questions??[],b=i=>{let t=`resolveq:${n}:${i}`,u=`assumed:${n}:${i}`;return s.appliedEvents.has(t)||s.appliedEvents.has(u)||o.isApplied(t)||o.isApplied(u)},W=d&&S.length>0?S.filter(i=>!b(i.id)):o.state.pending.questions.filter(i=>!b(i.id)),v={redeliverReceipts:[],recommit:[]},h,k;if(d){let i={...d,applied_events:[...new Set([...d.applied_events,...o.state.applied_events])].sort()},t;try{t=I(e,n,i,s,{verb:r.verb==="design"?"design":"extract",...r.use_case?{ucRef:r.use_case}:{},composeReceipt:(g,q,D)=>N(g,q,D),onNote:l.onWarn})}catch(g){throw g instanceof C?new m("CHECKPOINT_PROTOCOL",`store reconciliation refused: ${g.message}`,[{cmd:`kane-cli context sessions clean ${n}`,why:"abandon the session if the store was rebuilt"}]):g}v={redeliverReceipts:t.redeliverReceipts,recommit:t.recommit},k=t.prunedPending;let u=d.pending.proposals??[];h=(u.length>0?u:o.state.pending.proposals).filter(g=>!(typeof g.event_id=="string"&&s.appliedEvents.has(g.event_id))),(t.newlyApplied.length>0||t.prunedPending.length>0)&&o.reconcileSave({appliedEvents:t.newlyApplied,heldReceipts:[...o.state.held_receipts??[],...t.redeliverReceipts],pending:{questions:o.state.pending.questions,proposals:h}})}else{let i=o.state.pending.proposals;k=i.filter(t=>typeof t.event_id=="string"&&s.appliedEvents.has(t.event_id)),h=i.filter(t=>!(typeof t.event_id=="string"&&s.appliedEvents.has(t.event_id)))}return{kind:"v2",handle:o,base:r,view:c,kane:d,spawnConfig:R,drift:f,reconcile:v,questions:W,represent:h,prunedPending:k}}catch(p){throw o.release(),p}}export{Q as a,ne as b,se as c,te as d,m as e,ie as f};
@@ -1,4 +1,4 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- import{d as $e}from"./chunk-IXVOXJP6.js";import{a as te}from"./chunk-R2RGSO4B.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-APAIWBIH.js";import{a as ve}from"./chunk-73C4PRYU.js";import{b as ye}from"./chunk-DFS4RMVP.js";import{y as i}from"./chunk-C4G7RVJ6.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-CTW2VQKS.js";import{a as te}from"./chunk-EWCAFKLX.js";import{a as K}from"./chunk-5Y2G4NC7.js";import{a as Be}from"./chunk-UDIQOJEL.js";import{a as ve}from"./chunk-FEJXWJ3L.js";import{y as i}from"./chunk-27U4PLPX.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};
@@ -0,0 +1,2 @@
1
+ import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
+ function c(t,s){return`${t}:${s}`}function d(t){let s=t.use_cases.filter(e=>!e.matches_existing),r=t.use_cases.filter(e=>e.matches_existing!=null&&(e.changed===!0||e.updated!=null)),n=t.use_cases.filter(e=>e.matches_existing!=null&&!(e.changed===!0||e.updated!=null)),{archived:a,...i}=t;return{adds:s,updates:r,archives:t.archived??[],passthrough:{...i,use_cases:n}}}export{c as a,d as b};
@@ -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-2KDGIZED.js";import{a as Ge}from"./chunk-G7VQCS4J.js";import{a as Ue}from"./chunk-27U4PLPX.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-62XHEEGW.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};