@testmuai/kane-cli 0.8.12 → 0.8.14
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.
- package/dist/{ChatSurface-DALSIICW.js → ChatSurface-AVL3TJA2.js} +3 -3
- package/dist/{ChromeProfilePicker-ZMVZH3AK.js → ChromeProfilePicker-WJZJOZ6Z.js} +1 -1
- package/dist/{CliFeedbackPrompt-K66H7YE6.js → CliFeedbackPrompt-65BQF5G5.js} +1 -1
- package/dist/{CliUploadProgress-5DZHZY4M.js → CliUploadProgress-HEBZYKGN.js} +1 -1
- package/dist/{ConfigView-S5KBV62S.js → ConfigView-JEVQ2SO4.js} +1 -1
- package/dist/EvidenceViewOffer-5MB4ZXKM.js +2 -0
- package/dist/FolderPicker-SYFXH6D5.js +2 -0
- package/dist/{InfoBox-7PAM2FQH.js → InfoBox-KM5DLBCV.js} +1 -1
- package/dist/{LinksBox-2NVZ3FHJ.js → LinksBox-FQA36GTV.js} +1 -1
- package/dist/{ProfilesView-SIUBF7IU.js → ProfilesView-76KGHTMK.js} +1 -1
- package/dist/{ProjectPicker-5NI554X3.js → ProjectPicker-65YOU46H.js} +1 -1
- package/dist/{SaveSessionPrompt-5OULBV5N.js → SaveSessionPrompt-QD6BNTWO.js} +1 -1
- package/dist/ScrollbackTap-QHJOFYMC.js +2 -0
- package/dist/SingleShotApp-U54ETXS3.js +2 -0
- package/dist/{SummaryBox-GTGF3CBO.js → SummaryBox-N2B6DUDD.js} +1 -1
- package/dist/TestMdRunView-WA4TC5PT.js +2 -0
- package/dist/{TestrunEvidenceTable-7WBCOGYW.js → TestrunEvidenceTable-3WLQVTF4.js} +1 -1
- package/dist/{WhoamiView-E2SVBHLC.js → WhoamiView-T26HA4ZZ.js} +1 -1
- package/dist/agent-parse-XMWVKCRD.js +2 -0
- package/dist/{app-download-SAXSYXIV.js → app-download-XKZWFMEK.js} +1 -1
- package/dist/attach-target-V6LECVES.js +2 -0
- package/dist/{auth-3LLVDHOJ.js → auth-PPJANIMZ.js} +1 -1
- package/dist/{binary-WSMIRJNC.js → binary-DKWWODT2.js} +1 -1
- package/dist/bind-62AZYFAY.js +15 -0
- package/dist/{bootstrap-QTVHGL45.js → bootstrap-6IJNZIPT.js} +1 -1
- package/dist/bridge-X5DEJL6F.js +2 -0
- package/dist/{changelog-CNYWOB2V.js → changelog-UTGJ7FSP.js} +1 -1
- package/dist/chat-committer-HDE3TP5I.js +2 -0
- package/dist/chat-controller-3EPK7UZG.js +2 -0
- package/dist/chunk-22QIVSQR.js +29 -0
- package/dist/{chunk-CQ3ZQ5UK.js → chunk-2BFXT7VQ.js} +3 -3
- package/dist/{chunk-AHRL4E3M.js → chunk-2RMHDOP4.js} +1 -1
- package/dist/{chunk-HPUQJRDX.js → chunk-3BHRGHIZ.js} +1 -1
- package/dist/{chunk-EEFZXZTZ.js → chunk-3IXEARDX.js} +1 -1
- package/dist/chunk-3N6IAVD5.js +7 -0
- package/dist/{chunk-3OU2F34I.js → chunk-3SPOJWRA.js} +1 -1
- package/dist/chunk-3YX3RQXO.js +2 -0
- package/dist/chunk-42FHKRPA.js +4 -0
- package/dist/{chunk-FBYB3SRE.js → chunk-4BBDKWM3.js} +1 -1
- package/dist/{chunk-UDFDTFBL.js → chunk-4K5XTIJ6.js} +1 -1
- package/dist/chunk-52WM3XYO.js +4 -0
- package/dist/{chunk-H6VS5RYO.js → chunk-53MPG2J3.js} +1 -1
- package/dist/{chunk-R7QAS6LZ.js → chunk-55YDTPB7.js} +1 -1
- package/dist/{chunk-IDX3TOPY.js → chunk-5LJRZI7S.js} +1 -1
- package/dist/chunk-66MOZKD2.js +2 -0
- package/dist/chunk-6F6YI3ZG.js +2 -0
- package/dist/chunk-6LGED4FC.js +35 -0
- package/dist/chunk-73ULUGBM.js +5 -0
- package/dist/{chunk-X6APRDUM.js → chunk-75I46VTM.js} +2 -2
- package/dist/{chunk-5FYO3PFG.js → chunk-7L25ZNNP.js} +1 -1
- package/dist/chunk-7O54QURK.js +2 -0
- package/dist/{chunk-4T35SA2O.js → chunk-7RAI77XD.js} +1 -1
- package/dist/{chunk-7NXHVC7G.js → chunk-AC7BPO4X.js} +1 -1
- package/dist/chunk-AHXOKBVE.js +7 -0
- package/dist/{chunk-DNNZ353O.js → chunk-ALCE5RLK.js} +1 -1
- package/dist/{chunk-5AHOVOWV.js → chunk-ARG56PJG.js} +1 -1
- package/dist/chunk-B2ZGG7WM.js +2 -0
- package/dist/{chunk-GNAPBOAJ.js → chunk-BAKJPQGU.js} +1 -1
- package/dist/chunk-BJYGWXVP.js +52 -0
- package/dist/chunk-C74ABM24.js +2 -0
- package/dist/chunk-CGT4NFQN.js +8 -0
- package/dist/{chunk-EV64VI66.js → chunk-CRZUBDJ3.js} +1 -1
- package/dist/{chunk-M4WSRYRA.js → chunk-DA57DXCF.js} +1 -1
- package/dist/chunk-DHJSM5DT.js +2 -0
- package/dist/{chunk-UZXCCO7V.js → chunk-EMSLJTYN.js} +1 -1
- package/dist/{chunk-2LXJ2ZM3.js → chunk-FFFB5BXL.js} +1 -1
- package/dist/{chunk-WIAZN7G4.js → chunk-FFVNISYH.js} +1 -1
- package/dist/chunk-FQNQVC5O.js +5 -0
- package/dist/{chunk-NSD2H67E.js → chunk-GESG672R.js} +1 -1
- package/dist/{chunk-FHYG3QLL.js → chunk-GKZ2KVE6.js} +1 -1
- package/dist/chunk-GP7WD4UY.js +4 -0
- package/dist/{chunk-7R5K4IGS.js → chunk-GPIXV7AV.js} +2 -2
- package/dist/chunk-H6TNBKGR.js +5 -0
- package/dist/chunk-HOA4VWSD.js +5 -0
- package/dist/chunk-IE3OO5GI.js +2 -0
- package/dist/chunk-IICQ5KRD.js +5 -0
- package/dist/{chunk-VG7BTA5G.js → chunk-IQ7GPETF.js} +1 -1
- package/dist/{chunk-AFNDJK2A.js → chunk-IQ7NGOAT.js} +1 -1
- package/dist/{chunk-F2CET54H.js → chunk-J7NRD4Q7.js} +1 -1
- package/dist/{chunk-FAREJ4P2.js → chunk-JH6E632O.js} +1 -1
- package/dist/{chunk-L7GAZQYL.js → chunk-JJJSDDQ2.js} +1 -1
- package/dist/{chunk-XWO5MDEU.js → chunk-JKX57HA7.js} +1 -1
- package/dist/{chunk-LLY7TQSI.js → chunk-K7K23DIQ.js} +1 -1
- package/dist/chunk-KN65CUNT.js +15 -0
- package/dist/{chunk-YF26DH4Z.js → chunk-KOL6ZWOQ.js} +1 -1
- package/dist/{chunk-COVIEKZN.js → chunk-KOPP4CJW.js} +1 -1
- package/dist/chunk-KZG4E5RM.js +2 -0
- package/dist/{chunk-GRDYYYIQ.js → chunk-L4M7753M.js} +1 -1
- package/dist/{chunk-ZVJGHQNG.js → chunk-L6MOO4WT.js} +1 -1
- package/dist/chunk-LBNADEQN.js +8 -0
- package/dist/{chunk-HWHLKBUT.js → chunk-LL5DQO6V.js} +1 -1
- package/dist/chunk-LNV7C2YO.js +6 -0
- package/dist/{chunk-3N2YOHD6.js → chunk-LR5DJ6EN.js} +1 -1
- package/dist/{chunk-ZXN67F4U.js → chunk-M7DN6FO3.js} +1 -1
- package/dist/chunk-MLRO7OH3.js +9 -0
- package/dist/{chunk-ZZI4Y3CX.js → chunk-MNE5VMHT.js} +1 -1
- package/dist/{chunk-3G3LY6BM.js → chunk-N7ZRF5K3.js} +1 -1
- package/dist/{chunk-MMQLVGUJ.js → chunk-NBMLBCJ3.js} +1 -1
- package/dist/{chunk-WHYEXCTG.js → chunk-NDCRJXYF.js} +1 -1
- package/dist/{chunk-4E4GJPEM.js → chunk-NOLYYHVG.js} +1 -1
- package/dist/{chunk-IWVA37B6.js → chunk-O25AL4B7.js} +1 -1
- package/dist/{chunk-2MTAXT2U.js → chunk-O2APH6TZ.js} +1 -1
- package/dist/{chunk-KAZGHWGK.js → chunk-O3XBIURC.js} +1 -1
- package/dist/{chunk-APZCLVZD.js → chunk-O5AS2ZIX.js} +1 -1
- package/dist/{chunk-43DM2I6Q.js → chunk-O6U2HU5M.js} +1 -1
- package/dist/{chunk-7KAPHA56.js → chunk-OH2NSBO6.js} +1 -1
- package/dist/{chunk-3CCD434H.js → chunk-OO5GMBVI.js} +1 -1
- package/dist/chunk-OPL2MIQG.js +2 -0
- package/dist/chunk-P3JUE2RM.js +17 -0
- package/dist/{chunk-QZRHXGNI.js → chunk-PGU64EWQ.js} +1 -1
- package/dist/{chunk-24QPDHRD.js → chunk-Q7XBMBMR.js} +1 -1
- package/dist/{chunk-4TZSEC2C.js → chunk-QJ5O27SJ.js} +1 -1
- package/dist/{chunk-YTAAF62A.js → chunk-QPUVOVD7.js} +1 -1
- package/dist/{chunk-5A4QG7ZM.js → chunk-RBHQXWR7.js} +1 -1
- package/dist/{chunk-G52YPXKT.js → chunk-RH6KFHJB.js} +1 -1
- package/dist/{chunk-ASYWKYTQ.js → chunk-RQLU4NDG.js} +12 -12
- package/dist/{chunk-U27OWZPW.js → chunk-SFTFHFG3.js} +7 -7
- package/dist/{chunk-H6NHARB4.js → chunk-SGHP44WS.js} +1 -1
- package/dist/{chunk-U2CIXGZR.js → chunk-SQDQADWD.js} +1 -1
- package/dist/{chunk-IE4BCGUE.js → chunk-SX56MVUO.js} +1 -1
- package/dist/{chunk-O5U6EAL3.js → chunk-TCAHDVII.js} +1 -1
- package/dist/chunk-TNBF5OMZ.js +2 -0
- package/dist/chunk-TU6IMGWO.js +2 -0
- package/dist/{chunk-5G22NOZK.js → chunk-UHT5SVP5.js} +1 -1
- package/dist/{chunk-L2BCQQLJ.js → chunk-UXH3RMQ7.js} +1 -1
- package/dist/{chunk-DYXYNH6X.js → chunk-VNFCX2SH.js} +1 -1
- package/dist/{chunk-O7U5BVX5.js → chunk-WBHSPN55.js} +2 -2
- package/dist/chunk-WILT62DP.js +16 -0
- package/dist/{chunk-I57TM22L.js → chunk-WOA7VCGA.js} +1 -1
- package/dist/{chunk-SA6EDKUF.js → chunk-WR42Q3HU.js} +1 -1
- package/dist/chunk-X5276I5H.js +9 -0
- package/dist/{chunk-75HF3GPO.js → chunk-X74PP5NJ.js} +1 -1
- package/dist/{chunk-3XWKKSIM.js → chunk-XGHMZJGI.js} +2 -2
- package/dist/{chunk-XS2LZFCH.js → chunk-YCH7H7JX.js} +1 -1
- package/dist/{chunk-IGW77FMB.js → chunk-YHR2YAN5.js} +1 -1
- package/dist/chunk-YHVG7V3E.js +21 -0
- package/dist/chunk-YLQHY4A7.js +2 -0
- package/dist/{chunk-KGKJU27A.js → chunk-YYYQ5MVD.js} +1 -1
- package/dist/chunk-ZA4M4O7E.js +27 -0
- package/dist/chunk-ZKEOPIQ3.js +9 -0
- package/dist/chunk-ZUZ6QJRA.js +23 -0
- package/dist/{chunk-4ASRA7CD.js → chunk-ZWHPIR2Z.js} +2 -2
- package/dist/chunk-ZZTZJPT2.js +88 -0
- package/dist/committer-IYQPXG6C.js +2 -0
- package/dist/{config-HUK7V364.js → config-3AKWRTFS.js} +1 -1
- package/dist/{controller-client-OB4WD2C4.js → controller-client-ZF5IXRUV.js} +1 -1
- package/dist/cover-cmd-ZLAWMEC2.js +3 -0
- package/dist/{credentials-6DP4KAMJ.js → credentials-Q4WH5CBN.js} +1 -1
- package/dist/{deps-bundle-PZNXSKLC.js → deps-bundle-RVZK6LZJ.js} +1 -1
- package/dist/{deps-resolve-62XK3LKV.js → deps-resolve-6F2U4TJP.js} +1 -1
- package/dist/design-committer-J57IAAA5.js +2 -0
- package/dist/dispatch-46BETGXY.js +2 -0
- package/dist/{doctor-ZQQ4VMPY.js → doctor-WRPG56HH.js} +1 -1
- package/dist/docx-convert-WPZS6OIC.js +2 -0
- package/dist/{dossier-Y6TJWFZU.js → dossier-UGJMYYAB.js} +1 -1
- package/dist/evidence-XWR32HWP.js +2 -0
- package/dist/evolve-cmd-27ZQN6YB.js +2 -0
- package/dist/explain-H5HJEDEF.js +2 -0
- package/dist/explain-cmd-JCJTXVZY.js +9 -0
- package/dist/{explain-cmd-XCRO4AS6.js → explain-cmd-R45I5MT7.js} +1 -1
- package/dist/extract-bind-D5BYYGYA.js +14 -0
- package/dist/{extract-cmd-IPBCCR3T.js → extract-cmd-CCYW7FIY.js} +3 -3
- package/dist/feeder-RSHMGW6B.js +2 -0
- package/dist/gaps-cmd-3VJKQ25D.js +3 -0
- package/dist/{generate-headless-CLMSXEAS.js → generate-headless-2M6UT3IK.js} +2 -2
- package/dist/headless-io-3A3BZVQ5.js +2 -0
- package/dist/index.js +206 -164
- package/dist/ingest-QGLVY7ND.js +2 -0
- package/dist/ingest-cmd-HVTUK264.js +2 -0
- package/dist/install-5WJLE7XT.js +2 -0
- package/dist/interactive-bind-OJCYNQPI.js +26 -0
- package/dist/lifecycle-cmd-GWFGUGTC.js +2 -0
- package/dist/{list-cmd-V3HJ5K4O.js → list-cmd-AXDW64OY.js} +1 -1
- package/dist/list-commands-YNZ6EFIF.js +2 -0
- package/dist/{locks-cmd-CSVSWY2Y.js → locks-cmd-67OHQZNV.js} +1 -1
- package/dist/logical-ids-DN6IZSUM.js +2 -0
- package/dist/login-flow-PRXFPRYZ.js +2 -0
- package/dist/maintenance-cmd-QEMK6YNV.js +2 -0
- package/dist/{mobile-prompts-WJVFBWW5.js → mobile-prompts-OXHA5GHJ.js} +1 -1
- package/dist/{objective-variable-gate-GCQYYM77.js → objective-variable-gate-76GYUHEP.js} +1 -1
- package/dist/open-provider-E5VUGFNE.js +2 -0
- package/dist/pdf-convert-5H4HQNN3.js +2 -0
- package/dist/{persist-recorded-session-MHLD4A32.js → persist-recorded-session-KWPH37HI.js} +1 -1
- package/dist/phase-seed-HKJ2EF7R.js +2 -0
- package/dist/pipeline-A2OGF4XW.js +2 -0
- package/dist/prepare-target-P6BWJZBZ.js +2 -0
- package/dist/readmodel-IBFRM6EO.js +2 -0
- package/dist/reconcile-cmd-V7TDYETT.js +2 -0
- package/dist/reconcile-deps-X6IGH4CA.js +4 -0
- package/dist/reconcile-engine-OGXSIE7O.js +2 -0
- package/dist/{recording-banner-4H4AL6YN.js → recording-banner-IZWN2XFY.js} +1 -1
- package/dist/records-TJJJWBUD.js +2 -0
- package/dist/registry-GOLIFVK5.js +2 -0
- package/dist/{require-project-folder-G2G4WKWW.js → require-project-folder-PEEUITK6.js} +1 -1
- package/dist/{resolve-run-intent-MZRPYN4V.js → resolve-run-intent-JGXXE45Y.js} +1 -1
- package/dist/{resolver-X5NHNX5O.js → resolver-TY7XLJBN.js} +1 -1
- package/dist/revert-6BBBK3I4.js +2 -0
- package/dist/review-cmd-74YTPT7E.js +5 -0
- package/dist/run-DN4XARP2.js +2 -0
- package/dist/run-GRYWYKIH.js +2 -0
- package/dist/{run-test-md-4VRH7FU5.js → run-test-md-DFCKCQ4T.js} +2 -2
- package/dist/sessions-NH7WQWMX.js +2 -0
- package/dist/{sessions-cmd-VDQGRBEM.js → sessions-cmd-DV442ZCY.js} +1 -1
- package/dist/{skill-installer-WPW6NDCR.js → skill-installer-GRU3HOYF.js} +1 -1
- package/dist/{spawner-R3XOP3GP.js → spawner-LNMD4NJF.js} +1 -1
- package/dist/store-guard-Q4MYZQHF.js +2 -0
- package/dist/structured-answers-NADW6D44.js +5 -0
- package/dist/sync-cmd-H6Y5EB3L.js +2 -0
- package/dist/sync-setup-THGRBKTA.js +2 -0
- package/dist/sync-setup-ui-RC727VK6.js +3 -0
- package/dist/tcg-generate-SZZ7MJXY.js +2 -0
- package/dist/testmd-actions-MRIUOOXO.js +2 -0
- package/dist/testmd-sync-UYVJ47BN.js +2 -0
- package/dist/token-refresh-KN5JK2U4.js +2 -0
- package/dist/{validate-basic-YNGP5JFB.js → validate-basic-RCBEELSB.js} +1 -1
- package/dist/{variable-receipt-2VCUG7NN.js → variable-receipt-JHRW73Z6.js} +1 -1
- package/dist/verdicts-XFXDRND4.js +2 -0
- package/dist/{version-check-GUGRBTIH.js → version-check-Z774UWW3.js} +1 -1
- package/dist/{view-cmd-SXXNDZIC.js → view-cmd-I4LQGJ2X.js} +1 -1
- package/dist/walk-session-FP52IGLB.js +2 -0
- package/dist/with-telemetry-P6RUPWBH.js +2 -0
- package/package.json +12 -11
- package/dist/EvidenceViewOffer-UACWB3YJ.js +0 -2
- package/dist/FolderPicker-YH5TKMX3.js +0 -2
- package/dist/ScrollbackTap-Q3IOKNMS.js +0 -2
- package/dist/SingleShotApp-LA3EMPUK.js +0 -2
- package/dist/TestMdRunView-5MNKJJMS.js +0 -2
- package/dist/bind-A3M4PV4V.js +0 -12
- package/dist/bridge-E2C5VV3H.js +0 -2
- package/dist/chat-committer-RAOIL2T6.js +0 -2
- package/dist/chat-controller-YJCNU76T.js +0 -2
- package/dist/chunk-4O6XBS5G.js +0 -5
- package/dist/chunk-54JZ6VEW.js +0 -4
- package/dist/chunk-5DT7PIGB.js +0 -5
- package/dist/chunk-5KLDW3ZW.js +0 -85
- package/dist/chunk-6A47PRDS.js +0 -4
- package/dist/chunk-6FCPS2VT.js +0 -4
- package/dist/chunk-7RFGO3TH.js +0 -2
- package/dist/chunk-DBIBROYW.js +0 -5
- package/dist/chunk-DPUV6OSP.js +0 -2
- package/dist/chunk-G2Q2TP3O.js +0 -9
- package/dist/chunk-IAHKTEET.js +0 -2
- package/dist/chunk-IVQX3AKL.js +0 -4
- package/dist/chunk-JDGBRACP.js +0 -16
- package/dist/chunk-JOATASPP.js +0 -4
- package/dist/chunk-KRL2BDI5.js +0 -8
- package/dist/chunk-N7Z7BQYO.js +0 -3
- package/dist/chunk-NJJQL54J.js +0 -2
- package/dist/chunk-NP3VGFZM.js +0 -26
- package/dist/chunk-NVGBE2DR.js +0 -2
- package/dist/chunk-OS4VSIHT.js +0 -4
- package/dist/chunk-OZMYKG6E.js +0 -6
- package/dist/chunk-QQ5MHSSY.js +0 -2
- package/dist/chunk-RV7Q4RUV.js +0 -7
- package/dist/chunk-SACCB44S.js +0 -21
- package/dist/chunk-T4OJX2GZ.js +0 -15
- package/dist/chunk-TLFNUXKS.js +0 -2
- package/dist/chunk-UH2ZTX4E.js +0 -2
- package/dist/chunk-VDM3TWF6.js +0 -17
- package/dist/chunk-W3Z7AZNT.js +0 -4
- package/dist/chunk-WMVPJWWA.js +0 -37
- package/dist/chunk-XMTSHHYQ.js +0 -4
- package/dist/chunk-ZVZHE7KH.js +0 -27
- package/dist/committer-C6UCDYMC.js +0 -2
- package/dist/cover-cmd-5LPHIOSI.js +0 -3
- package/dist/design-committer-UPC6NZUF.js +0 -2
- package/dist/dispatch-7JCKGQVC.js +0 -2
- package/dist/docx-convert-BIV5T7F5.js +0 -2
- package/dist/evidence-YAXIWZ6A.js +0 -2
- package/dist/evolve-cmd-5ACHYQPE.js +0 -2
- package/dist/explain-3HAZY7Q6.js +0 -2
- package/dist/explain-cmd-RMJPXD4U.js +0 -9
- package/dist/extract-bind-BF2G6AS6.js +0 -10
- package/dist/feeder-IOR3XRNF.js +0 -2
- package/dist/gaps-cmd-3WXL6PAW.js +0 -3
- package/dist/headless-io-66RG5NN5.js +0 -2
- package/dist/ingest-TTUQ7UDK.js +0 -2
- package/dist/ingest-cmd-KP5M6XTA.js +0 -2
- package/dist/install-5VWCH5GW.js +0 -2
- package/dist/interactive-bind-MOV2VWHJ.js +0 -25
- package/dist/lifecycle-cmd-KSMETBPP.js +0 -2
- package/dist/list-commands-KUDSKVP5.js +0 -2
- package/dist/logical-ids-MLXAH45L.js +0 -2
- package/dist/login-flow-GZ3XHVCS.js +0 -2
- package/dist/maintenance-cmd-VFYGKY3X.js +0 -2
- package/dist/pdf-convert-OZIRUADA.js +0 -2
- package/dist/phase-seed-BMOSAA74.js +0 -2
- package/dist/pipeline-G7KWRK2G.js +0 -2
- package/dist/prepare-target-SQ5IGKXD.js +0 -2
- package/dist/readmodel-TDRFVDVI.js +0 -2
- package/dist/reconcile-cmd-NI3AYU3Y.js +0 -2
- package/dist/reconcile-deps-DCHUFIEC.js +0 -4
- package/dist/reconcile-engine-QXUKUKSL.js +0 -2
- package/dist/records-JLS63SDI.js +0 -2
- package/dist/registry-R6QNPI5E.js +0 -2
- package/dist/revert-PRR3D4XM.js +0 -2
- package/dist/review-cmd-SAGIKWEW.js +0 -4
- package/dist/run-PBS2J4N4.js +0 -2
- package/dist/run-VTUYLPSG.js +0 -2
- package/dist/sessions-GIEXOCE4.js +0 -2
- package/dist/structured-answers-YAVW65G4.js +0 -5
- package/dist/tcg-generate-HIC5AA3L.js +0 -2
- package/dist/testmd-actions-VOSP7L74.js +0 -2
- package/dist/testmd-sync-GNCDKPQN.js +0 -2
- package/dist/token-refresh-GSFVJ6GU.js +0 -2
- package/dist/verdicts-PRXUKSDV.js +0 -2
- package/dist/walk-session-G3DLBR24.js +0 -2
- package/dist/with-telemetry-5Y2CVPXK.js +0 -2
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as j,b as H}from"./chunk-ZWHPIR2Z.js";import{a as B,b as N}from"./chunk-JKX57HA7.js";import{a as se,b as ie,c as ae}from"./chunk-PDXZROJM.js";import{d as ce}from"./chunk-RH6KFHJB.js";import{a as $,b as q,e as M,g as oe}from"./chunk-KN65CUNT.js";import{a as re,b as ne}from"./chunk-LBNADEQN.js";import{a as L}from"./chunk-O5AS2ZIX.js";import{a as te}from"./chunk-RBHQXWR7.js";import{a as X}from"./chunk-OH2NSBO6.js";import{a as ee}from"./chunk-DHJSM5DT.js";import{a as A}from"./chunk-RZ4F3BHX.js";import{a as O}from"./chunk-IQ7NGOAT.js";import{y}from"./chunk-B2ZGG7WM.js";import{a as F}from"./chunk-HCBYKLMW.js";import{a as k,b as p,i as Z}from"./chunk-C44QQJR4.js";import{a as K}from"./chunk-6YGTRKDT.js";import{e as v}from"./chunk-UR6MHSHU.js";var D=v(K(),1);import{existsSync as P,readFileSync as He,rmSync as ye,unlinkSync as Ve}from"fs";import{resolve as Q}from"path";import{promises as le,realpathSync as Ee}from"fs";import{homedir as Se}from"os";import{join as V,parse as ve,relative as ue,resolve as de}from"path";var fe=new Set(["node_modules",".git","dist","build",".next",".venv","venv","target","__pycache__"]),R=class extends Error{constructor(s){super(`refusing to scan '${s}'. Run from your project root, or pass --root <dir>.`);this.cwd=s;this.name="HomeRefusedError"}};function me(e){try{return Ee(de(e))}catch{return de(e)}}function Re(e){let r=me(e),s=me(Se()),n=ve(r).root;if(process.platform==="win32"){let o=t=>t.toLowerCase();return o(r)===o(s)||o(r)===o(n)}return r===s||r===n}async function U(e){if(Re(e.root))throw new R(e.root);let r=e.maxEntries??5e4,s=e.maxResults??5e3,n=new Set(e.ignore??[]),o=[],t=0,i=0,a=!1,u,c=[e.root];for(;c.length>0&&!a;){let l=c.shift(),g;try{g=await le.readdir(l,{withFileTypes:!0})}catch{continue}i++;for(let _ of g){if(t++,t>r){a=!0,u="max_entries";break}let m=_.name,T=V(l,m);if(_.isDirectory()){if(fe.has(m)||m.startsWith(".")||m.startsWith("output-")||n.has(m))continue;c.push(T)}else if(_.isFile()&&m.endsWith("_test.md")&&(o.push({path:T,relPath:ue(e.root,T),source:"cwd"}),o.length>=s)){a=!0,u="max_results";break}}e.onProgress?.(i,o.length)}if(!a){let g=[{dir:V(e.root,".testmuai","tests"),depth:0}];for(;g.length>0&&!a;){let{dir:_,depth:m}=g.shift(),T;try{T=await le.readdir(_,{withFileTypes:!0})}catch{continue}i++;for(let d of T){if(t++,t>r){a=!0,u="max_entries";break}let b=d.name,w=V(_,b);if(d.isDirectory()){if(m>=20||b.startsWith(".")||b.startsWith("output-")||fe.has(b))continue;g.push({dir:w,depth:m+1})}else if(d.isFile()&&b.endsWith("_test.md")&&(o.push({path:w,relPath:ue(e.root,w),source:"tests-dir"}),o.length>=s)){a=!0,u="max_results";break}}}}return{results:o,aborted:a,abortReason:u,dirsScanned:i}}import{readFileSync as Pe}from"fs";function Y(e){let r;try{r=Pe(e,"utf8")}catch{return{tags:[]}}try{let{global:s}=re(e,r),n=ne(s);return{tags:s.tags??[],...n?{mobileTarget:n}:{}}}catch{return{tags:[],...De(r)?{mobileTarget:Me}:{}}}}var Me={platform:"",app:""};function De(e){let r=/^---\r?\n([\s\S]*?)\r?\n---/.exec(e);if(!r)return!1;let s=r[1].split(/\r?\n/);if(s.some(o=>/^target:\s*['"]?(emulator|simulator)['"]?\s*$/.test(o)))return!0;let n=s.findIndex(o=>/^target:\s*$/.test(o));return n<0?!1:s.slice(n+1).some(o=>/^\s+\S/.test(o))}function W(e){return Y(e).tags}import{mkdirSync as Ce,writeFileSync as $e}from"fs";import{join as Ie}from"path";function ge(e,r){return`Basic ${Buffer.from(`${e}:${r}`).toString("base64")}`}async function Fe(e){let r=ie({tmsBaseUrl:e.tmsBaseUrl,testcaseId:e.testcaseId,codeExport:{enabled:!0,language:e.language,skipValidation:e.skipValidation},mobile:e.framework==="appium"}),s=await A(r.url,{method:"POST",headers:{"content-type":"application/json",authorization:ge(e.auth.username,e.auth.access_key)},body:JSON.stringify(r.body)});if(!s.ok)throw new Error(`code-export trigger failed: ${s.status} ${await s.text()}`);e.log("info","CODE_EXPORT_TRIGGERED","Code export triggered",{testcase_id:e.testcaseId})}async function Oe(e){let r=ae({tmsBaseUrl:e.tmsBaseUrl,testcaseId:e.testcaseId}),s=e.pollIntervalMs??5e3,n=e.timeoutMs??3e5,o=Date.now()+n;for(;Date.now()<o;){let t=await A(r,{headers:{authorization:ge(e.auth.username,e.auth.access_key),accept:"application/json"}});if(!t.ok){await new Promise(c=>setTimeout(c,s));continue}let a=(await t.json()).data?.find(c=>c.code_name==="kane-cli-trigger");if(!a){await new Promise(c=>setTimeout(c,s));continue}let u=(a.status??"").toLowerCase();if(u==="in progress"||u==="in_progress"||u==="pending"){await new Promise(c=>setTimeout(c,s));continue}if(!a.url||a.url.length===0)throw new Error(`code-export status=${a.status} but no files returned`);Ce(e.outDir,{recursive:!0});for(let c of a.url){let l=Ie(e.outDir,c.file_name),g=await A(c.file_url);if(!g.ok){e.log("warn","CODE_EXPORT_FILE_FAILED","Failed to download file",{file_name:c.file_name,status:g.status});continue}let _=await g.text();$e(l,_,"utf-8")}return e.log("info","CODE_EXPORT_DOWNLOADED","Code export saved",{out_dir:e.outDir,file_count:a.url.length}),e.outDir}throw new Error("code-export polling timed out")}async function pe(e){return await Fe(e),await Oe(e)}var E=v(K(),1);import{existsSync as Ae,readFileSync as Le}from"fs";var h=v(F(),1);function je(e){j(e);let r=M(e);if(!Ae(r))return null;try{return JSON.parse(Le(r,"utf8"))}catch{return{}}}function Be(e){return e===null?"never_run":e.testcase_id?"synced":"local_only"}function Ne(e){return e==="synced"?"\u2601":e==="local_only"?"\u25A3":"\u25CB"}function Ue(e){return e==="tests-dir"?"\u2726":" "}function We(e,r){return r==="all"?!0:r==="synced"?e.status==="synced":r==="local"?e.status==="local_only":r==="never_run"?e.status==="never_run":r==="cli"?e.source==="tests-dir":r==="hand"?e.source==="cwd":!0}var z=["all","synced","local","never_run","cli","hand"];function Je(e){let r=z.indexOf(e);return z[(r+1)%z.length]}function he({root:e,currentOrgId:r,onSelect:s,onCancel:n}){let[o,t]=(0,E.useState)([]),[i,a]=(0,E.useState)(null),[u,c]=(0,E.useState)(!0),[l,g]=(0,E.useState)("all");(0,E.useEffect)(()=>{(async()=>{try{let d=await U({root:e}),b=[];for(let w of d.results){let G=je(w.path);G?.org_id!==void 0&&G.org_id!==r||b.push({path:w.path,relPath:w.relPath,name:$(w.path),status:Be(G),source:w.source,tags:W(w.path)})}t(b),c(!1)}catch(d){d instanceof R,a(d.message),c(!1)}})()},[e,r]);let _=(0,E.useMemo)(()=>o.filter(d=>We(d,l)).map(d=>({id:d.path,label:`${Ne(d.status)} ${Ue(d.source)} ${d.relPath}${d.tags.length>0?` [${d.tags.join(", ")}]`:""}`})),[o,l]),m=(0,E.useMemo)(()=>Ke(l,o),[l,o]);if(i)return(0,h.jsxs)(k,{flexDirection:"column",borderStyle:"round",borderColor:y.red,paddingX:2,paddingY:1,children:[(0,h.jsx)(p,{color:y.red,bold:!0,children:"testmd"}),(0,h.jsx)(k,{marginTop:1,children:(0,h.jsx)(p,{color:y.red,children:i})})]});let T=l==="all"?"all":Ge(l);return(0,h.jsx)(te,{title:`testmd \xB7 filter: ${T}`,items:_,loading:u,itemNoun:"tests",onSelect:d=>{let b=o.find(w=>w.path===d.id);b&&s(b)},onCancel:n,onTab:()=>g(d=>Je(d)),extraHint:"cycle filter",footer:m})}function Ge(e){return e==="synced"?"synced (\u2601)":e==="local"?"local (\u25A3)":e==="never_run"?"never run (\u25CB)":e==="cli"?"cli-generated (\u2726)":e==="hand"?"hand-written":"all"}function Ke(e,r){let s={synced:r.filter(o=>o.status==="synced").length,local:r.filter(o=>o.status==="local_only").length,never:r.filter(o=>o.status==="never_run").length,cli:r.filter(o=>o.source==="tests-dir").length,hand:r.filter(o=>o.source==="cwd").length},n=o=>o?y.orange:y.dim;return(0,h.jsxs)(k,{flexDirection:"column",children:[(0,h.jsx)(p,{color:y.dim,children:"legend:"}),(0,h.jsxs)(k,{children:[(0,h.jsx)(p,{color:n(e==="synced"),children:` \u2601 synced (${s.synced}) `}),(0,h.jsx)(p,{color:n(e==="local"),children:`\u25A3 local (${s.local}) `}),(0,h.jsx)(p,{color:n(e==="never_run"),children:`\u25CB never run (${s.never})`})]}),(0,h.jsxs)(k,{children:[(0,h.jsx)(p,{color:n(e==="cli"),children:` \u2726 cli-generated (${s.cli}) `}),(0,h.jsx)(p,{color:n(e==="hand"),children:` hand-written (${s.hand})`})]})]})}var I=v(K(),1);import{existsSync as Xe,readFileSync as qe}from"fs";var f=v(F(),1);function _e({path:e,relPath:r,onAction:s,onBack:n,onView:o}){let[t,i]=(0,I.useState)(null),[a,u]=(0,I.useState)(!1);(0,I.useEffect)(()=>{let l=M(e);if(Xe(l))try{i(JSON.parse(qe(l,"utf8")))}catch{i(null)}},[e]),Z((l,g)=>{if(g.escape){if(a){u(!1);return}n();return}if(a){l==="y"||l==="Y"?(u(!1),s("delete")):(l==="n"||l==="N")&&u(!1);return}l==="r"&&s("run"),l==="e"&&t?.testcase_id&&s("export"),l==="d"&&u(!0),l==="v"&&o&&o()});let c=({k:l,v:g})=>g?(0,f.jsxs)(p,{children:[(0,f.jsx)(p,{color:y.dim,children:l.padEnd(14)}),g]}):null;return(0,f.jsxs)(k,{flexDirection:"column",borderStyle:"round",borderColor:y.orange,paddingX:2,paddingY:1,children:[(0,f.jsx)(p,{color:y.orange,bold:!0,children:r}),(0,f.jsx)(k,{marginTop:1,flexDirection:"column",children:t?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(c,{k:"test_id",v:t.test_id}),(0,f.jsx)(c,{k:"testcase_id",v:t.testcase_id}),(0,f.jsx)(c,{k:"project_id",v:t.project_id}),(0,f.jsx)(c,{k:"folder_id",v:t.folder_id}),(0,f.jsx)(c,{k:"org_id",v:t.org_id}),(0,f.jsx)(c,{k:"session_name",v:t.session_name}),(0,f.jsx)(c,{k:"commit_id",v:t.commit_id})]}):(0,f.jsx)(p,{color:y.dim,children:"(never run \u2014 no meta.json)"})}),a?(0,f.jsx)(k,{marginTop:1,children:(0,f.jsxs)(p,{color:y.red,bold:!0,children:["Delete ",r," and its output dir? [y/n]"]})}):(0,f.jsx)(k,{marginTop:1,children:(0,f.jsxs)(p,{color:y.dim,children:["[r] run [e] export",t?.testcase_id?"":" (need testcase_id)"," [d] delete",o?" [v] view":""," [Esc] back"]})})]})}function C(e){j(e);let r=M(e);if(!P(r))return null;try{return JSON.parse(He(r,"utf8"))}catch{return null}}function xe(e,r){return!e||e.org_id===void 0?!0:e.org_id===r}function J(e,r){return xe(e,r)?null:(process.stderr.write(`error: this test belongs to org ${e.org_id}; you are logged in as org ${r}.
|
|
3
|
+
Switch profiles with \`kane-cli profiles switch\` to act on it.
|
|
4
|
+
`),2)}async function Ht(e={}){let r=!!process.stdin.isTTY&&!e.json,s=new O,n=new L;await H({isInteractive:r,creds:s,config:n});let o=s.getDefaultEnv()??"prod";try{let t=await N({creds:s,env:o,log:()=>{}});return t.resolvedCreds?.org_id===void 0?(process.stderr.write("error: TMS did not return an org_id. Run `kane-cli login` again.\n"),{ok:!1,code:2}):{ok:!0,orgId:String(t.resolvedCreds.org_id)}}catch(t){if(t instanceof B)return process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),{ok:!1,code:2};throw t}}async function Vt(e,r){if(process.stdin.isTTY&&!e.json)return await Qe(r,e.root);let s=e.root??process.cwd(),n;try{n=await U({root:s,ignore:e.ignore})}catch(o){if(o instanceof R)return process.stderr.write(`error: ${o.message}
|
|
5
|
+
`),2;throw o}for(let o of n.results){let t=C(o.path);if(!xe(t,r))continue;let i={path:o.relPath.startsWith(".")?o.relPath:`./${o.relPath}`,name:$(o.path),has_meta:t!==null,source:o.source,synced:!!t?.testcase_id,tags:W(o.path)};t&&(t.test_id&&(i.test_id=t.test_id),t.testcase_id&&(i.testcase_id=t.testcase_id),t.org_id&&(i.org_id=t.org_id),t.project_id&&(i.project_id=t.project_id),t.folder_id&&(i.folder_id=t.folder_id)),process.stdout.write(JSON.stringify(i)+`
|
|
6
|
+
`)}return n.aborted&&process.stderr.write(`warn: walk aborted (${n.abortReason}). Pass --root or --ignore to narrow.
|
|
7
|
+
`),0}var we=-1001,be=-1002,ke=-1003,x={action:null,path:null};function Ye(e,r){return x.action=e,x.path=r,e==="run"?we:e==="export"?be:ke}function ze({root:e,currentOrgId:r,onComplete:s}){let[n,o]=D.default.useState({kind:"list"});return D.default.useEffect(()=>{n.kind==="exiting"&&s(n.code)},[n,s]),n.kind==="list"?D.default.createElement(he,{root:e,currentOrgId:r,onSelect:t=>o({kind:"inspect",path:t.path,relPath:t.relPath}),onCancel:()=>o({kind:"exiting",code:0})}):n.kind==="inspect"?D.default.createElement(_e,{path:n.path,relPath:n.relPath,onAction:async t=>{o({kind:"exiting",code:Ye(t,n.path)})},onBack:()=>o({kind:"list"})}):null}async function Qe(e,r){let s=r??process.cwd(),{render:n}=await import("./build-JIKYOZUH.js"),o=await new Promise(t=>{let{unmount:i,waitUntilExit:a}=n(D.default.createElement(ze,{root:s,currentOrgId:e,onComplete:u=>{i(),t(u)}}),{stdout:process.stderr,exitOnCtrlC:!0});a().then(()=>t(0)).catch(()=>t(0))});if(o===we&&x.path){let{runTestMdFile:t}=await import("./run-test-md-DFCKCQ4T.js"),i=await t(x.path,{});return x.action=null,x.path=null,i}if(o===be&&x.path){let t=await et(x.path,{},e);return x.action=null,x.path=null,t}if(o===ke&&x.path){let t=await Ze(x.path,!0,e);return x.action=null,x.path=null,t}return o}async function Yt(e,r){let s=Q(e);if(!P(s))return process.stderr.write(`error: file not found: ${s}
|
|
8
|
+
`),2;let n=C(s),o=J(n,r);if(o!==null)return o;let t={path:s,name:$(s),has_meta:n!==null};return n&&(n.commit_id&&(t.commit_id=n.commit_id),n.test_id&&(t.test_id=n.test_id),n.testcase_id&&(t.testcase_id=n.testcase_id),n.project_id&&(t.project_id=n.project_id),n.folder_id&&(t.folder_id=n.folder_id),n.org_id&&(t.org_id=n.org_id),n.session_name&&(t.session_name=n.session_name)),process.stdout.write(JSON.stringify(t)+`
|
|
9
|
+
`),0}async function Ze(e,r,s){let n=Q(e);if(!P(n))return process.stderr.write(`error: file not found: ${n}
|
|
10
|
+
`),2;let o=C(n),t=J(o,s);if(t!==null)return t;if(!r)return process.stderr.write(`error: refusing to delete without --yes.
|
|
11
|
+
This will remove '${n}' and '${q(n)}/'.
|
|
12
|
+
`),2;let i=q(n);if(P(i))try{ye(i,{recursive:!0,force:!0})}catch(a){return process.stderr.write(`error: failed to remove ${i}: ${a.message}
|
|
13
|
+
`),2}try{Ve(n)}catch(a){return process.stderr.write(`error: failed to remove ${n}: ${a.message}
|
|
14
|
+
`),2}return process.stderr.write(`removed ${n} and ${i}/
|
|
15
|
+
`),0}var S=class extends Error{kind;constructor(r,s){super(s),this.name="ExportError",this.kind=r}};async function zt(e,r){let{codeDir:s}=await Te(e,r);return{codeDir:s}}async function Te(e,r){let s=C(e);if(!s?.testcase_id)throw new S("not-synced","this test has not been synced to TMS \u2014 run `kane-cli testmd run` first.");let n=new L().load(),o=Y(e).mobileTarget!==void 0;if(o&&r.language?.toLowerCase()==="javascript")throw new S("js-on-mobile","--language javascript is not supported on a mobile target \u2014 mobile code export is Appium + Python only. Drop the flag, or pass --language python.");let t=r.language??n.code_export?.language;if(!o&&!t)throw new S("no-language","--language not provided and no default in tui-config.");let{framework:i,language:a}=se(t??"python",o),u=r.output??oe(e,i,a),c=P(u);if(c&&!r.force){let m=!1;try{let{readdirSync:T}=await import("fs");m=T(u).length>0}catch{}if(m)return{kind:"reused",codeDir:u}}c&&r.force&&ye(u,{recursive:!0,force:!0});let l=new O,g=r.env??l.getDefaultEnv()??"prod",_;try{_=await N({creds:l,env:g,log:()=>{}})}catch(m){throw m instanceof B?new S("auth-fail","not authenticated. Run `kane-cli login` first."):m}if(!_.basicAuth)throw new S("auth-incomplete","TMS basic auth could not be resolved. Run `kane-cli login` again.");try{let m=X(g);await pe({tmsBaseUrl:m.tmsBaseUrl,testcaseId:s.testcase_id,auth:_.basicAuth,language:a,framework:i,skipValidation:n.code_export?.skip_validation??!0,outDir:u,log:()=>{}})}catch(m){throw new S("export-fail",`code export failed: ${m.message}`)}return{kind:"exported",codeDir:u}}async function et(e,r,s){let n=Q(e);if(!P(n))return process.stderr.write(`error: file not found: ${n}
|
|
16
|
+
`),2;let o=C(n),t=J(o,s);if(t!==null)return t;try{let i=await Te(n,r);return i.kind==="reused"?process.stderr.write(`reusing existing export at ${i.codeDir}
|
|
17
|
+
`):process.stderr.write(`exported to ${i.codeDir}
|
|
18
|
+
`),0}catch(i){if(i instanceof S)return i.kind==="not-synced"?(process.stderr.write("error: this test has not been synced to TMS \u2014 run `kane-cli testmd run` first.\n"),2):i.kind==="no-language"?(process.stderr.write(`error: --language not provided and no default in tui-config.
|
|
19
|
+
`),2):i.kind==="js-on-mobile"?(process.stderr.write(`error: ${i.message}
|
|
20
|
+
`),2):i.kind==="auth-fail"?(process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),2):i.kind==="auth-incomplete"?(process.stderr.write("error: TMS basic auth could not be resolved. Run `kane-cli login` again.\n"),2):(process.stderr.write(`error: ${i.message}
|
|
21
|
+
`),2);throw i}}async function Qt(e={}){let r=!!process.stdin.isTTY,s=new O,n=new L;await H({isInteractive:r,creds:s,config:n});let o=e.env??s.getDefaultEnv()??"prod";try{let t=await N({creds:s,env:o,usernameFlag:e.username,accessKeyFlag:e.accessKey,log:()=>{}});return t.resolvedCreds?.org_id===void 0||!t.basicAuth?(process.stderr.write("error: could not resolve TMS credentials. Run `kane-cli login` again.\n"),{ok:!1,code:2}):{ok:!0,orgId:String(t.resolvedCreds.org_id),basicAuth:t.basicAuth,controllerBaseUrl:X(o).controllerBaseUrl}}catch(t){if(t instanceof B)return process.stderr.write("error: not authenticated. Run `kane-cli login` first.\n"),{ok:!1,code:2};throw t}}async function Zt(e,r,s=ce){if(!P(e))return process.stderr.write(`error: file not found: ${e}
|
|
22
|
+
`),2;if(!e.endsWith("_test.md"))return process.stderr.write(`error: not a *_test.md file: ${e}
|
|
23
|
+
`),2;let n=C(e),o=J(n,r.orgId);if(o!==null)return o;if(!n?.commit_id||!n?.test_id)return process.stderr.write(`error: ${e} is not authored \u2014 run \`kane-cli testmd run ${e}\` first.
|
|
24
|
+
`),2;let t=await s({sourcePath:e,testId:n.test_id,sessionId:n.commit_id,commitId:n.commit_id,controller:new ee(r.controllerBaseUrl,{username:r.basicAuth.username,accessKey:r.basicAuth.access_key})}),i={type:"test_md_bundle_sync",status:t.ok?"ok":"failed",commit_id:n.commit_id,...t.ok?{bytes:t.bytes}:{stage:t.stage}};return process.stdout.write(JSON.stringify(i)+`
|
|
25
|
+
`),t.ok?(process.stderr.write(`synced: ${n.commit_id}-testmd.zip (${t.bytes} bytes)
|
|
26
|
+
`),0):(process.stderr.write(`error: bundle sync failed at ${t.stage}: ${t.error}
|
|
27
|
+
`),t.stage==="collect"?2:1)}export{U as a,Y as b,he as c,_e as d,C as e,xe as f,J as g,Ht as h,Vt as i,Qe as j,Yt as k,Ze as l,S as m,zt as n,et as o,Qt as p,Zt as q};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as br}from"./chunk-OPL2MIQG.js";import{a as yr}from"./chunk-TU6IMGWO.js";import{a as hr}from"./chunk-TNBF5OMZ.js";import{a as gr,b as mr}from"./chunk-HOA4VWSD.js";import{a as fr}from"./chunk-KZG4E5RM.js";import{c as pr,d as ur}from"./chunk-52WM3XYO.js";import{a as cr,d as lr}from"./chunk-BB2W35TW.js";import{a as or,g as xt,h as ir,n as ar,p as dr}from"./chunk-AHXOKBVE.js";import{e as ct,f as jt,g as Tt,h as Le}from"./chunk-YHVG7V3E.js";import{A as er,B as qt,C as te,D as it,E as fe,F as tr,G as ne,H as _e,I as at,J as nr,K as Y,L as Fe,M as dt,N as Re,O as rr,P as sr,S as Be,a as Bn,b as Dn,c as Ae,d as Pe,e as le,f as st,g as Hn,h as Gn,i as pe,j as Un,k as qe,l as je,m as Kn,n as ot,o as ue,p as Yn,q as zn,r as Qn,s as Zn,t as At,u as Pt,v as X,w as Te,x as Xn,y as Nt,z as xe}from"./chunk-6LGED4FC.js";import{b as Fn,d as Ln,g as Ct,h as K}from"./chunk-H6TNBKGR.js";import{a as R,b as Mn,d as ee,e as Ne,h as Jn,i as Vn,k as Wn}from"./chunk-YLQHY4A7.js";import{a as jn,b as Tn,e as xn}from"./chunk-WILT62DP.js";import{b as sn,f as on,h as an,k as dn,l as cn}from"./chunk-22QIVSQR.js";import{b as Ot,d as ce}from"./chunk-IE3OO5GI.js";import{a as qn}from"./chunk-CH273NAE.js";import{b as ve}from"./chunk-BKM2LWU2.js";import{A as tt,B as nt,C as rt,D as Nn,q as In,r as Sn,s as En,t as On,u as Cn,v as An,w as Pn}from"./chunk-GP7WD4UY.js";import{B as oe,C as wn,D as vn,F as $e,G as Xe,J as $n,K as Ce,O as kn,P as et,U as _n,W as Rn,X as ke,b as rn,c as de,f as Et,h as ln,l as pn,m as un,o as Oe,p as O,q as fn,t as hn,v as gn,x as mn,y as yn,z as bn}from"./chunk-3N6IAVD5.js";import{d as Qe,e as Ze}from"./chunk-AKX4VRRR.js";import{existsSync as Ue,readdirSync as ss,readFileSync as os,realpathSync as Do,statSync as Mo,writeFileSync as Ho}from"fs";import{basename as Rt,join as Ke,relative as Go,resolve as tn}from"path";import{randomBytes as ks}from"crypto";var wr=8,De=()=>Wn(ks(8).toString("hex")),vr=(e,t)=>e!==null&&Buffer.from(e).equals(Buffer.from(t)),_s=[["P1 exclusive create",async e=>{for(let t=1;t<=2;t++){let n=De(),r=Buffer.from(`probe ${t} first`);if(await e.putIfAbsent(n,r)!=="created")return"a fresh key was reported as existing";if(await e.putIfAbsent(n,Buffer.from(`probe ${t} second`))!=="exists")return"the second write to one key was not refused";if(!vr(await e.get(n),r))return"the second write replaced the first"}return null}],["P2 contention",async e=>{let t=De(),r=(await Promise.all(Array.from({length:wr},(o,i)=>e.putIfAbsent(t,Buffer.from(`contender ${i}`))))).filter(o=>o==="created").length;return r===1?null:`${r} of ${wr} concurrent writers were told "created"`}],["P3 read-after-write",async e=>{let t=De(),n=Buffer.from("visible");return await e.putIfAbsent(t,n),await e.head(t)?vr(await e.get(t),n)?(await e.list(t)).includes(t)?null:"list does not show a key just created":"get does not return the bytes just created":"head does not see a key just created"}],["P4 definitive absence",async e=>await e.head(De())?"a never-written key was reported present":null]];async function lt(e){if(e.probe){let r=await e.probe();return{tier:Math.max(r.tier,e.ceilingTier),detail:r.detail}}let t=1,n="all probes passed";for(let[r,o]of _s){let i;try{i=await o(e)}catch(s){if(s instanceof R){if(!(s.code==="SYNC_LOCATION_REFUSED_WRITE"&&r.startsWith("P1")&&await $r(e)))throw s;n=`${r}: ${s.message}`,t=3;break}n=`${r}: ${s instanceof Error?s.message:String(s)}`,t=r.startsWith("P1")&&await $r(e)?3:2;break}if(i!==null){n=`${r}: ${i}`,t=2;break}}return{tier:Math.max(t,e.ceilingTier),detail:n}}async function $r(e){try{return!await e.head(De())}catch(t){if(t instanceof R)throw t;return!1}}import{existsSync as Rs,readFileSync as Rr}from"fs";import{join as Is}from"path";async function Ft(e,t,n,r){let i=le(e).entries[n];if(!i)throw new Error(`no sync state for ${n} \u2014 run kane-cli context sync add ${n} <descriptor> first`);if(i.tier!==1)throw new R("SYNC_READ_ONLY",`${n} is a tier ${i.tier} location: it can be cloned and pulled, never pushed`,"push to a location whose probe reached tier 1, or pull from this one");let s=await qe(e,t,i.witness);switch(s.kind){case"empty-storage":case"ahead":case"up-to-date":break;case"behind":case"empty-local":throw new R("SYNC_BEHIND",`${n} holds ${s.storage.seq} records, this store ${s.local?.seq??0}: it has records this store has not seen`,`kane-cli context pull ${n}`);case"diverged":throw new R("SYNC_DIVERGED",`you and ${n} both added work after position ${s.at-1}; nothing was pushed`,`run kane-cli context pull ${n} --rebase to save your local work, take the team version from ${n}, and then reapply yours`);case"foreign-lineage":throw new R("SYNC_FOREIGN_LINEAGE",`${n} holds a different history (its first record is not this store's)`,`to work on it, clone it: kane-cli context clone <descriptor of ${n}> <dir>; to share this store, add an empty location`)}let d=s.storage,c=bn(e),a;try{gn(e),a=Ss(e,d)}catch(F){throw F instanceof hn?new R("SYNC_REBASE_PENDING",`${F.message.split(";")[0]}; nothing was pushed`,F.remedy):F}finally{c()}let l=a.map(F=>Es(e,F)),g=0,p=0,f=0,u=0,y=d,b=null,h=null,m=t.beginTransaction?await t.beginTransaction():void 0,w=m?{...t,head:m.head,get:m.get,list:t.list.bind(t),putIfAbsent:t.putIfAbsent.bind(t)}:t,v=m?m.stageIfAbsent.bind(m):t.putIfAbsent.bind(t),x=[],ae=F=>m?x.push(F):r(F);try{let F=new Set;for(let A of l){for(let $ of A.blobs)if(await v($.key,$.bytes)!=="exists")p++,F.add($.key);else if(!F.has($.key)){let M=await w.get($.key);if(M===null||Ot(Buffer.from(M))!==$.fp){h=new R("SYNC_OBJECT_CORRUPT",`the blob ${$.fp} ${n} already holds does not hash to its name (named by record ${A.seq}); the record was not pushed`,"the storage object needs a human look before anything more is pushed to it");break}F.add($.key)}if(h)break;A.proposal&&await v(A.proposal.key,A.proposal.bytes)!=="exists"&&f++;let Q=Ne(A.seq);if(await v(Q,A.raw)!=="exists")g++;else if((await pe(w,A.seq)).hash===A.hash)ae(`position ${A.seq} is already on ${n}`),u++;else{b=A.seq;break}y={seq:A.seq,hash:A.hash}}if(m||await _r(t,y,d,n),y&&!await w.head(ee)){let A=await pe(w,1),Q={layout:1,canonicalizer:"v1",genesis_hash:A.hash};await v(ee,Buffer.from(JSON.stringify(Q)+`
|
|
3
|
+
`,"utf8"))!=="exists"&&ae(`wrote ${ee} on ${n}`)}if(m){if(y){let M=await w.get(ee),T=await pe(w,1),be={};try{let Z=JSON.parse(Buffer.from(M??[]).toString("utf8"));Z&&typeof Z=="object"&&!Array.isArray(Z)&&(be=Z)}catch{}if(be.layout!==1||be.canonicalizer!=="v1"||be.genesis_hash!==T.hash)throw new R("SYNC_OBJECT_CORRUPT",`${ee} does not describe this context's verified genesis and format.`,"Ask the location owner to inspect the metadata before publishing.")}if(h)throw h;if(b!==null)throw new R("SYNC_POSITION_TAKEN",`position ${b} on ${n} was taken by another writer; this batch was not published`,kr(n,b));let A=await m.commit(),Q=new Set(A.created),$=l.filter(M=>Q.has(Ne(M.seq))).length;u+=g-$,g=$,p=new Set(l.flatMap(M=>M.blobs.map(T=>T.key)).filter(M=>Q.has(M))).size,f=new Set(l.flatMap(M=>M.proposal?[M.proposal.key]:[]).filter(M=>Q.has(M))).size}m&&await _r(t,y,d,n);for(let A of x)r(A);let U="";if(y)try{Kn(e,n,y,{forwardOnly:!0})}catch(A){if(b===null||!(A instanceof O))throw A;U=" (the witness was not saved; the next pull records it)"}if(h)throw h;if(b!==null)throw new R("SYNC_POSITION_TAKEN",`position ${b} on ${n} was taken by another writer while this push ran; this store's history through position ${y?.seq??0} is confirmed on ${n}${U}`,kr(n,b))}finally{await m?.abort()}return{pushed:g,from:d?.seq??0,to:y?.seq??0,blobs:p,proposals:f,alreadyThere:u}}function kr(e,t){return t===1?`${e} holds a different history: to work on it, clone it with kane-cli context clone <descriptor of ${e}> <dir>; to share this store, add an empty location`:`kane-cli context pull ${e} --rebase`}async function _r(e,t,n,r){if(!t||t.seq<=(n?.seq??0))return;let o=await pe(e,t.seq);if(o.hash!==t.hash)throw new R("SYNC_OBJECT_CORRUPT",`${r} answered "created" for position ${t.seq} but serves a record hashing ${o.hash}, not ${t.hash}`,"The location needs inspection before publishing more context.")}function Ss(e,t){let{records:n,hashes:r}=Ce(e,t?.seq??0,t?.hash??null);return n.map((o,i)=>{let s=r[i],d=Rr(Is(e,"commits",`${String(o.seq).padStart(6,"0")}-${s.slice(7,19)}.json`));if(oe(JSON.parse(d.toString("utf8")))!==s)throw new Error(`record ${o.seq} changed on disk while it was being read \u2014 run kane-cli context fsck`);return{rec:o,hash:s,raw:d}})}function Es(e,{rec:t,hash:n,raw:r}){{let o=Bn(t),i=o.blobs.map(s=>{let d=ce(e,s);if(d===null)throw new R("SYNC_CLOSURE_MISSING",`record ${t.seq} names blob ${s}, which this store does not hold`,"restore the blob from a copy of this store, or run kane-cli context fsck");if(Ot(d)!==s)throw new R("SYNC_LOCAL_BLOB_CORRUPT",`record ${t.seq} names blob ${s}, but the local file does not hash to that: it is torn`,"restore the blob from a copy of this store, or run kane-cli context fsck");return{key:Jn(s),fp:s,bytes:d}});return{seq:t.seq,hash:n,raw:new Uint8Array(r),blobs:i,proposal:Os(e,o.proposalId)}}}function Os(e,t){if(t===null)return null;let n=ln(e,t);if(!Rs(n))return null;let r=Rr(n);return{key:Vn(t,Dn(r.toString("utf8"))),bytes:r}}import{existsSync as Cs,readdirSync as As,readFileSync as Ir}from"fs";import{basename as Ps,join as Lt}from"path";var Ns=/^\d{6}-[0-9a-f]{12}\.json$/;function Bt(e,t){let n=Lt(e,"commits"),r=Cs(n)?As(n).filter(s=>Ns.test(s)).sort():[],o=t.hash,i=t.seq;return r.map(s=>{let d;try{d=JSON.parse(Ir(Lt(n,s),"utf8"))}catch(a){throw new O(`backup record ${s} is not JSON: ${String(a)}`)}if(i+=1,d.seq!==i||d.prev_hash!==o)throw new O(`backup record ${s} does not continue the chain at ${i} from ${String(o)}`);let c=oe(d);if(!c.slice(7).startsWith(s.slice(7,19)))throw new O(`backup record ${s} does not match its name`);return o=c,{seq:i,hash:c,body:d}})}function pt(e,t){let n=JSON.parse(Ir(Lt(t,"base-witness.json"),"utf8")),r=$e(e),o=r.records.slice(0,n.base.seq),i=Bt(t,n.base),s=[...o,...i.map(f=>f.body)],d=[...r.hashes.slice(0,n.base.seq),...i.map(f=>f.hash)],c=new Map;for(let f of s)for(let u of f.nodes)c.set(u.cid,{label:u.label,content:u.content});let a=_n();Rn(e,a,s,d,{writeNodeFiles:!1});let l=Nn(e,a,c),g=new Map(i.map(f=>[f.seq,f])),p=f=>l.displayNameOf(f)??f.slice(0,19);return{backupDir:t,backupId:Ps(t),from:n.from,base:n.base,index:a,graph:l,records:i,chain:s,recordAt:f=>g.get(f),resolveName:f=>l.resolve(f)?.cid,nameOf:f=>l.displayNameOf(f)??void 0,displayNameFor:f=>{let u=Dt(t,f),y=Object.keys(f.source_head_moves),b=u==="revert"?String(qs(t,f)??""):u==="names"?(f.names??[]).map(h=>h.slug).join(", "):y.length>0?y.join(", "):f.nodes.length>0?[...new Set(f.nodes.map(h=>p(h.cid)))].join(", "):(f.executions?.length??0)>0?[...new Set(f.executions.map(h=>p(h.about)))].join(", "):f.review.length>0?[...new Set(f.review.map(h=>p(h.id)))].join(", "):f.supersessions.length>0?[...new Set(f.supersessions.map(h=>h.kind==="node"?p(h.old):h.ecid.slice(0,19)))].join(", "):y.join(", ");return b?`${u} ${b}`:u}}}function qs(e,t){try{let r=Oe(e,oe(t))?.args?.seq;return typeof r=="number"?r:void 0}catch{return}}function Dt(e,t){let n=null;try{n=Oe(e,oe(t))}catch{n=null}if(n)return n.verb;if(t.intent_verb)return t.intent_verb;let r=Object.entries(t.source_head_moves);return(t.executions?.length??0)>0?"execution":t.design_of?"design":t.proposal_id!=null?"extract":t.conv?t.conv.turn===0?"conv-mint":"conv-turn":r.length===1&&r[0][1]===null&&t.supersessions.some(o=>o.kind==="node"&&o.new===null)?"retire":r.length===1&&typeof r[0][1]=="string"&&t.nodes.some(o=>o.label==="source")?"ingest":t.review.some(o=>o.resolution==="reset")||t.supersessions.some(o=>o.kind==="node"&&o.new===o.old||o.kind==="edge"&&o.revoke)?"revert":t.nodes.length===0&&t.edges.length===0&&t.supersessions.length===1&&t.supersessions[0].kind==="node"&&t.supersessions[0].new===null?"archive":t.nodes.length===0&&t.edges.length===0&&t.review.length===0&&(t.names?.length??0)>0?"names":t.nodes.length===0&&t.edges.length===0&&t.supersessions.length===0&&t.review.length>0?"review":"unknown"}import{existsSync as Sr,readdirSync as js,readFileSync as Mt}from"fs";import{isAbsolute as Ts,join as ut,normalize as xs,relative as Fs,sep as Ls}from"path";var Bs=e=>e===""||Ts(e)||e.includes("\\")||xs(e).split(Ls).some(t=>t==="..")||e.startsWith("./")||e.includes("\0");function He(e){let t=ut(e,"manifest.json");if(!Sr(t))throw new O(`backup ${e} has no manifest.json \u2014 it was never completed; kane-cli context sync doctor`);let n;try{n=JSON.parse(Mt(t,"utf8"))}catch(s){throw new O(`backup manifest ${t} is not JSON: ${s instanceof Error?s.message:String(s)}`)}if(!Array.isArray(n))throw new O(`backup manifest ${t} is not a list`);let r=new Set,o=[];for(let s of n){let d=typeof s?.name=="string"?s.name:"";if(Bs(d))throw new O(`backup manifest names an unsafe path ${JSON.stringify(s?.name)} \u2014 the backup is not trusted`);let c=ut(e,d);if(!Sr(c))throw new O(`backup file ${d} is missing from ${e}`);let a=Mt(c);if("sha256:"+rn(a)!==s.hash)throw new O(`backup file ${d} does not match its manifest hash \u2014 the backup was changed after it was written`);if(d.startsWith("commits/"))try{r.add(oe(JSON.parse(a.toString("utf8"))))}catch(l){throw new O(`backup record ${d} is not a record: ${l instanceof Error?l.message:String(l)}`)}d.startsWith("intents/")&&o.push(d)}let i=new Set(n.map(s=>s.name));for(let s of Er(e)){let d=Fs(e,s);if(d!=="manifest.json"&&!i.has(d))throw new O(`backup ${e} holds ${d}, which its manifest does not name \u2014 the backup was changed after it was written`)}for(let s of o){let d;try{d=JSON.parse(Mt(ut(e,s),"utf8"))}catch(a){throw new O(`backup envelope ${s} is not JSON: ${a instanceof Error?a.message:String(a)}`)}let c=pn(d);if(c!==null)throw new O(`backup envelope ${s} is not a valid intent: ${c}`);if(typeof d.born?.hash!="string"||!r.has(d.born.hash))throw new O(`backup envelope ${s} was born from a record the backup does not hold`)}}function Er(e){let t=[];for(let n of js(e,{withFileTypes:!0})){let r=ut(e,n.name);n.isDirectory()?t.push(...Er(r)):t.push(r)}return t}import{basename as co,join as lo}from"path";import{existsSync as po,readFileSync as uo}from"fs";var G=class extends Error{},B=(e,t)=>({kind:"apply",inputs:e,...t&&t.length>0?{aliases:t}:{}}),V=e=>({kind:"noop",reason:e}),Ht=e=>({kind:"dedupe",as:e}),k=(e,t,n,r,o={})=>({kind:"hold",hold:{kind:e,mine:t,theirs:n,answers:r,detail:o}}),Or=(e,t)=>{let n=ft(t.label,t.content);return e.graph.byLabel(t.label).filter(r=>!e.graph.superseded.has(r.cid)&&ft(t.label,r.content)===n).map(r=>r.cid)},re=e=>e?e.slice(0,19):"none",H=(e,t)=>e.maps.cid.rewrite(t);function I(e,t,n){if(typeof t!="string")throw new G(`${n} was not pinned`);let r=H(e,t);if(!e.graph.hasNode(r))throw new G(`${n} ${_(e,t)} has no counterpart on ${e.location}`);return r}var j=(e,t)=>e.graph.tipOf(t),Gt=(e,t)=>e.graph.superseded.has(e.graph.tipOf(t)),_=(e,t)=>e.fold.nameOf(t)??re(t),S=(e,t)=>e.graph.displayNameOf(t)??re(t);function Jt(e,t,n,r){let o=r==="fold"?e.fold.graph:e.graph,i=o.displayNameOf(t);if(i!==null&&i!==n)return i;let s=o.tipOf(t);for(let[a,l]of o.heads)if(l===t||l===s)return a;let d=o.getNode(t);if(d?.label==="source"&&typeof d.content.source_id=="string")return d.content.source_id;let c=d?.content.title??d?.content.text??d?.content.statement;return d&&typeof c=="string"&&c!==""?`${d.label} "${z(c,32)}"`:re(t)}var L=e=>e.created_by?.by?.id??e.review[0]?.by.id??e.supersessions[0]?.by.id??e.names?.[0]?.by.id??"someone",P=e=>e.ts;function z(e,t=48){let n=typeof e=="string"?e:JSON.stringify(e);return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function he(e,t,n,r){return`${[...new Set([...Object.keys(e),...Object.keys(t)])].filter(s=>s!=="derived"&&JSON.stringify(e[s])!==JSON.stringify(t[s])).map(s=>`${s} "${z(e[s]??"")}" \u2192 "${z(t[s]??"")}"`).join(", ")||"no field changed"} by ${n} at ${r}`}function ie(e,t){for(let n of e.theirs)for(let r of n.supersessions)if(r.kind==="node"&&r.old===t)return{rec:n,next:r.new}}function Vt(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let[i,s]of e.graph.superseded)typeof s=="string"&&n.has(s)&&!n.has(i)&&(n.add(i),o=!0)}let r=[];for(let o of e.theirs)for(let i of o.review)n.has(i.id)&&i.resolution!=="pending"&&r.push({rec:o,resolution:i.resolution});return r}var Ds=new Set(Object.values(Ze).filter(e=>e!==Ze.DERIVES&&e!==Ze.ANNOTATES));function Wt(e,t){let n=new Set,r=[],o=[t,e.graph.tipOf(t)];for(;o.length>0;){let i=o.pop();if(!n.has(i)){n.add(i);for(let s of e.graph.edgesInto(i))!Ds.has(s.type)||e.graph.superseded.has(s.src)||(!(s.src in e.fold.index.nodeLabel)&&!r.some(d=>d.cid===s.src)&&r.push({cid:s.src,label:e.graph.nodeLabel.get(s.src)??"node"}),o.push(s.src))}}return r}function Ut(e){let t=new Map;for(let n of e)t.set(n.label,(t.get(n.label)??0)+1);return[...t].map(([n,r])=>`${r} ${n}${r===1?"":"s"}`).join(", ")}function ht(e,t,n){if(!e.theirs.some(o=>o.edges.some(i=>i.type===t&&i.src===n)))return;let r=e.graph.edgesFrom(n).find(o=>o.type===t);return r?{live:r.dst}:void 0}function Ie(e,t){let n=t.event_ids??[],r=n.filter(i=>i in e.index.eventDigests);return n.length===0||r.length===0?void 0:r.every(i=>{let s=n.indexOf(i),d=t.event_digests?.[s];return d!==void 0&&d!==""&&e.index.eventDigests[i]===d})&&r.length===n.length?V("already applied: every event id is in the chain with the same intent"):k("ambiguous",`committed ${n.length} event id${n.length===1?"":"s"}`,`${r.length} of them already in the shared chain under another intent`,["keep-theirs"],{event_ids:n})}function Ms(e){return String(e??"").toLowerCase().trim().replace(/\s+/g," ")}function ft(e,t){let n=t.question;return`${e}\0${Ms(t.title??t.text??t.statement??n?.header??t.source_id??"")}`}function Cr(e,t){let n=[],r=new Set;for(let o of e.nodes){let i=ft(o.label,o.content),s=t.nodes.find(d=>!r.has(d.cid)&&ft(d.label,d.content)===i);s&&(r.add(s.cid),n.push([o.cid,s.cid]))}for(let o of e.nodes){if(n.some(([s])=>s===o.cid))continue;let i=t.nodes.find(s=>!r.has(s.cid)&&s.label===o.label);i&&(r.add(i.cid),n.push([o.cid,i.cid]))}return n}function Ar(e,t){let n=[],r=new Set;for(let o of t.names??[]){if(!tt.test(o.slug))continue;let i=t.nodes.find(d=>d.cid===o.cid);if(!i||e.graph.nameOf.has(H(e,o.cid)))continue;let s=nt(i.label,d=>r.has(d),e.graph.names.keys());s!==null&&(r.add(s),s!==o.slug&&n.push({from:o.slug,to:s}))}return n}function Pr(e,t,n){let r=[];for(let o of e.names??[]){let i=n.find(([d])=>d===o.cid)?.[1],s=t.names?.find(d=>d.cid===i);s&&s.slug!==o.slug&&r.push({from:o.slug,to:s.slug})}return r}function Nr(e,t,n){let r=e===void 0?void 0:e.split(`
|
|
4
|
+
`).map(s=>{let d=/^(##\s.*?)\s@verifies\s+(.+?)\s*$/.exec(s);if(d)return`${d[1]} @verifies ${d[2].split(",").map(l=>l.trim()).filter(Boolean).map(n).join(", ")}`;let c=/^(\s*)@import\s+(\S+)\s*$/.exec(s);if(c)return`${c[1]}@import ${n(c[2])}`;let a=/^## Import: (\S+)\s*$/.exec(s);return a?`## Import: ${n(a[1])}`:s}).join(`
|
|
5
|
+
`),o=!1,i=t===void 0?void 0:t.split(`
|
|
6
|
+
`).map(s=>{let d=/^(\s*verifies:\s*)\[(.*)\]\s*$/.exec(s);if(d)return`${d[1]}[${d[2].split(",").map(a=>a.trim()).filter(Boolean).map(n).join(", ")}]`;if(/^\s*verifies:\s*$/.test(s))return o=!0,s;let c=o?/^(\s*-\s+)(\S+)\s*$/.exec(s):null;return c?`${c[1]}${n(c[2])}`:(o=!1,s)}).join(`
|
|
7
|
+
`);return{md:r,objectives:i}}var N=e=>e.args,q=e=>e.pins,J=e=>e.by,C=["keep-theirs"],W=["keep-theirs","apply-mine"],Hs={verb:"extract",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t),o=structuredClone(n.proposal);o.source.source_cid=I(e,o.source.source_cid,`source ${o.source.source_id}`);for(let a of o.sources??[])a.source_cid=I(e,a.source_cid,`source ${a.source_id}`);for(let a of o.use_cases)a.matches_existing&&(a.matches_existing={...a.matches_existing,cid:I(e,r.matches_existing[a.temp_ref]??a.matches_existing.cid,`${a.temp_ref} matches`)}),a.conflicts_with&&(a.conflicts_with=(r.conflicts_with[a.temp_ref]??[]).flatMap(l=>l?[H(e,l)]:[])),a.depends_on_hint=(r.depends_on_hint[a.temp_ref]??[]).map(l=>H(e,l));let i=new Map;for(let[a,l]of Object.entries(n.verdicts))i.set(a,l.resolution==="supersede"?{...l,supersedeTarget:I(e,r.supersedeTarget[a],`${a} supersede target`)}:l);let s=n.flags,d=n.judgements?.map(a=>({...a,about:H(e,a.about)})),c=n.probeHits?.map(a=>({...a,candidateCid:H(e,a.candidateCid)}));return{proposal:o,proposalId:n.proposalId,verdicts:i,by:J(n),autoName:s.autoName??!1,...s.extractorVersion?{extractorVersion:s.extractorVersion}:{},...s.sid?{sid:s.sid}:{},...d?{judgements:d}:{},...c?{probeHits:c}:{},...n.eventIds?{eventIds:n.eventIds}:{}}},precheck(e,t,n,r){let o=Ie(e,n.body);if(o)return o;let i=q(t).read_basis_heads;for(let[s,d]of Object.entries(i)){let c=e.graph.heads.get(s);if(c!==H(e,d)&&e.answer!=="apply-mine")return k("read-basis",`extracted from ${s} at ${re(d)}`,`${s} is at ${re(c)} on ${e.location}`,W,{source_id:s,mine:d,theirs:c??null})}for(let s of r.proposal.use_cases){let d=r.verdicts.get(s.temp_ref);if(s.matches_existing){let l=s.matches_existing.cid;if(Gt(e,l)){if(e.answer==="apply-mine-as-new"&&e.probe){let f=d?.edit?.title??s.title,u=e.probe(e,{label:Qe.USECASE,content:{title:f}}).filter(y=>y!==l);if(u.length>0)return k("duplicate",`add "${f}" as a new use case`,`${u.map(y=>S(e,y)).join(", ")} already on ${e.location} with the same title`,C,{hits:u});s.matches_existing=null;continue}let p=`${S(e,l)} was retired on ${e.location}`;return k("restore",`matched ${_(e,l)}`,e.probe?p:`${p}; no duplicate check is available here, so it can only be kept as theirs`,e.probe?["keep-theirs","apply-mine-as-new"]:C,{target:l})}let g=j(e,l);if(g!==l){let p=e.graph.getNode(l)?.content??{},f=(s.changed?s.updated:void 0)??{},u=Array.isArray(f.criteria)&&f.criteria.length>0&&typeof f.criteria[0].text=="string"?f.criteria.map(h=>h.text):void 0,y=Et({title:d?.edit?.title??f.title??String(p.title??s.title),...f.description??p.description?{description:f.description??p.description}:{},...d?.edit?.summary??f.summary??p.summary?{summary:d?.edit?.summary??f.summary??p.summary}:{},...f.actors??p.actors?{actors:f.actors??p.actors}:{},...f.value??p.value?{value:f.value??p.value}:{},risk:d?.edit?.risk??f.risk??String(p.risk??s.risk),...u?{criteria:u}:p.criteria?{criteria:p.criteria}:{}});if(de("usecase",y)===g||e.answer==="apply-mine"){s.matches_existing={...s.matches_existing,cid:g};continue}let b=ie(e,l);return k("edit",`${s.changed?"updated":"matched"} ${_(e,l)}: ${he(p,y,L(n.body),P(n.body))}`,he(p,e.graph.getNode(g)?.content??{},b?L(b.rec):"someone",b?P(b.rec):"since the fork"),W,{target:l,tip:g,mine:y,theirs:e.graph.getNode(g)?.content??null})}continue}let c=Et({title:d?.edit?.title??s.title,description:s.description,summary:d?.edit?.summary??s.summary,actors:s.actors,value:s.value,risk:d?.edit?.risk??s.risk,...s.criteria&&s.criteria.length>0?{criteria:s.criteria.map(l=>l.text)}:{}}),a=de("usecase",c);if(e.graph.superseded.get(a)===null)return k("restore",`extracted "${z(s.title)}"`,`the same use case was retired on ${e.location}`,C,{cid:a});if(d?.resolution==="supersede"&&d.supersedeTarget&&Gt(e,d.supersedeTarget))return k("edit",`replaced ${_(e,d.supersedeTarget)} with "${z(s.title)}"`,`${S(e,d.supersedeTarget)} was retired on ${e.location}`,C,{target:d.supersedeTarget})}return B(r)},replay(e,t,n){return In({contextDir:e.contextDir,graph:e.graph,...t,allowStaleBasis:!0,provenance:n})}},Gs={verb:"review",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t),o=new Map;for(let[i,s]of Object.entries(n.verdicts)){if(s.resolution==="skipped")continue;let d=I(e,r.verdicts[i],`review target ${i}`);o.set(d,s.resolution==="supersede"?{...s,supersedeTarget:I(e,r.supersedeTarget[i],`${i} supersede target`)}:s)}return{verdicts:o,by:J(n),...n.holdArchives?{holdArchives:!0}:{}}},precheck(e,t,n,r){let o=new Map,i=P(n.body);for(let[s,d]of r.verdicts){let c=j(e,s);if(e.graph.superseded.has(c))return k("restore",`${d.resolution} ${_(e,s)} at ${i}`,`${S(e,s)} was retired on ${e.location}`,C,{target:s});if(d.resolution==="rejected"&&r.holdArchives){o.set(c,d);continue}if(d.resolution==="approved"||d.resolution==="rejected"){let a=d.resolution==="approved"?"trusted":"archived";if(e.graph.trust.get(c)===a)continue;let l=Vt(e,c).at(-1);if(l&&l.resolution!==d.resolution&&e.answer!=="apply-mine")return k("verdict",`${d.resolution} ${_(e,s)} by ${L(n.body)} at ${i}`,`${l.resolution} by ${L(l.rec)} at ${P(l.rec)}`,W,{target:c,mine:d.resolution,theirs:l.resolution});o.set(c,d)}else if(d.resolution==="edited"){let a=e.graph.getNode(s),l={...a?.content,...d.edit?.title!==void 0?{title:d.edit.title}:{},...d.edit?.summary!==void 0?{summary:d.edit.summary}:{},...d.edit?.risk!==void 0?{risk:d.edit.risk}:{}};if(a&&de(a.label,l)===c)continue;if(c!==s){if(e.answer!=="apply-mine"){let g=ie(e,s),p=e.graph.getNode(c)?.content??{};return k("edit",he(a?.content??{},l,L(n.body),i),g?he(a?.content??{},p,L(g.rec),P(g.rec)):`edited on ${e.location} to "${z(p.title??p.text)}"`,W,{target:s,was:a?.content??{},mine:l,theirs:p})}o.set(c,d);continue}o.set(s,d)}else if(d.resolution==="supersede"&&d.supersedeTarget){let a=d.supersedeTarget;if(e.graph.superseded.get(a)===c)continue;if(e.graph.superseded.has(a))return k("edit",`${_(e,s)} replaces ${_(e,a)}`,`${S(e,a)} was replaced on ${e.location}`,C,{target:a});o.set(c,d)}}return o.size===0?V(`already applied on ${e.location}`):B({...r,verdicts:o})},replay(e,t,n){return Sn({contextDir:e.contextDir,graph:e.graph,...t,provenance:n})}},Js={verb:"pair-merge",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t);return{survivor:I(e,r.survivor,"survivor"),merged:I(e,r.merged,"merged"),...n.reason?{reason:String(n.reason)}:{},by:J(n)}},precheck(e,t,n,r){let o=j(e,r.survivor),i=r.merged;if(e.graph.superseded.get(i)===o||e.graph.superseded.get(i)===r.survivor)return V(`already merged on ${e.location}`);if(e.graph.superseded.has(i))return k("edit",`merged ${_(e,i)} into ${_(e,r.survivor)}`,`${S(e,i)} was changed on ${e.location}`,C,{merged:i});if(e.graph.superseded.has(o))return k("edit",`merged into ${_(e,r.survivor)}`,`${S(e,r.survivor)} was retired on ${e.location}`,C,{survivor:r.survivor});let s=Wt(e,i);return s.length>0?k("destructive",`merged ${_(e,i)} into ${_(e,r.survivor)} at ${P(n.body)}`,`${e.location} built on ${S(e,i)}: ${Ut(s)}`,C,{dependents:s}):B({...r,survivor:o})},replay:(e,t,n)=>En({contextDir:e.contextDir,graph:e.graph,...t,provenance:n})},Vs={verb:"names",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t).refs;return{assignments:n.assignments.map(o=>({ref:I(e,r[o.ref],`name target ${o.ref}`),slug:o.slug})),by:J(n),...Array.isArray(n.reassign)?{reassign:n.reassign}:{}}},precheck(e,t,n,r){let o=[],i=[],s=new Set,d=new Set(r.reassign??[]),c=q(t).refs,a=N(t).assignments.map(l=>c[l.ref]);for(let[l,{ref:g,slug:p}]of r.assignments.entries()){let f=j(e,g);if(e.graph.superseded.has(f))return k("restore",`named ${_(e,g)} "${p}"`,`${S(e,g)} was retired on ${e.location}`,C,{target:g});let u=e.graph.names.get(p);if(u!==void 0&&j(e,u)===f)continue;let y=u!==void 0&&!e.graph.superseded.has(j(e,u));if(y||s.has(p)){if(!tt.test(p)){if(y&&!s.has(p)&&e.answer==="apply-mine"){d.add(p),s.add(p),o.push({ref:f,slug:p});continue}let h=e.theirs.find(m=>(m.names??[]).some(w=>w.slug===p));return k("slug",`named ${Jt(e,a[l]??g,p,"fold")} "${p}" at ${P(n.body)}`,`"${p}" names ${Jt(e,u,p,"live")} on ${e.location}${h?` (by ${L(h)} at ${P(h)})`:""}`,W,{slug:p,mine:g,theirs:u??null})}let b=nt(e.graph.nodeLabel.get(f)??"",h=>s.has(h),e.graph.names.keys());if(b===null)throw new G(`no sequential id for ${_(e,g)}`);s.add(b),i.push({from:p,to:b}),o.push({ref:f,slug:b});continue}s.add(p),o.push({ref:f,slug:p})}return o.length===0?V(`already named on ${e.location}`):B({...r,assignments:o,...d.size>0?{reassign:[...d]}:{}},i)},replay:(e,t,n)=>On({contextDir:e.contextDir,graph:e.graph,...t,provenance:n})},Ws={verb:"retire",accepts:[1,1],rebind(e,t){let n=N(t);return{sourceId:String(n.sourceId),...n.reason?{reason:String(n.reason)}:{},by:J(n)}},precheck(e,t,n,r){let o=e.graph.heads.get(r.sourceId);if(o===null)return V(`already retired: ${r.sourceId}`);if(o===void 0)throw new G(`source ${r.sourceId} is not on ${e.location}`);let i=H(e,String(q(t).head));if(o!==i&&e.answer!=="apply-mine"){let s=e.theirs.find(d=>d.source_head_moves[r.sourceId]===o);return k("head",`retired ${r.sourceId} at ${re(i)} (${P(n.body)})`,`${r.sourceId} was re-ingested on ${e.location}${s?` by ${L(s)} at ${P(s)}`:""}`,W,{source_id:r.sourceId,mine:i,theirs:o})}return B(r)},replay:(e,t,n)=>Cn({contextDir:e.contextDir,graph:e.graph,...t,provenance:n})},Us={verb:"archive",accepts:[1,1],rebind(e,t){let n=N(t);return{ref:I(e,String(q(t).ref),`archive target ${String(n.ref)}`),reason:String(n.reason),by:J(n)}},precheck(e,t,n,r){let o=j(e,r.ref);if(e.graph.superseded.has(o))return V(`already archived: ${S(e,r.ref)}`);if(o!==r.ref){let s=ie(e,r.ref);return k("edit",`archived ${_(e,r.ref)}: ${z(r.reason)} (${L(n.body)}, ${P(n.body)})`,`${S(e,r.ref)} was edited on ${e.location}${s?` by ${L(s.rec)} at ${P(s.rec)}`:""}`,C,{target:r.ref,tip:o})}let i=Wt(e,o);return i.length>0?k("destructive",`archived ${_(e,r.ref)}: ${z(r.reason)} (${L(n.body)}, ${P(n.body)})`,`${e.location} built on ${S(e,r.ref)}: ${Ut(i)}`,C,{target:o,dependents:i}):B({...r,ref:o})},replay:(e,t,n)=>yr(e.contextDir,e.graph,{...t,provenance:n})},Ks={verb:"gap",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t).annotates;return{content:e.maps.cid.rewrite(n.content),...r?{annotates:j(e,I(e,r,"annotated node"))}:{}}},precheck(e,t,n,r){let o=de("gap",r.content);return e.graph.hasNode(o)?e.graph.superseded.has(o)?k("restore",`deferred a gap: ${z(r.content.text)}`,`the same gap was closed on ${e.location}`,C,{cid:o}):Ht(o):r.annotates&&e.graph.superseded.has(r.annotates)?k("restore",`deferred a gap on ${_(e,r.annotates)}`,`${S(e,r.annotates)} was retired on ${e.location}`,C,{target:r.annotates}):B(r)},replay(e,t,n){let r=An({contextDir:e.contextDir,...t,provenance:n});return r.ok?{landed:!0}:{errors:[{code:"GAP_REFUSED",detail:r.refusal}]}}},Ys={verb:"gap-close",accepts:[1,1],rebind(e,t){let n=N(t);return{targetTip:j(e,I(e,String(n.targetTip),"gap target")),resolvedBy:I(e,String(n.resolvedBy),"resolving node"),...n.sourceId?{sourceId:String(n.sourceId)}:{},by:J(n),gaps:q(t).gaps.map(r=>I(e,r,"gap"))}},precheck(e,t,n,r){let o=[];for(let i of r.gaps){let s=e.graph.superseded.get(i);if(s===void 0){o.push(i);continue}if(s!==null&&j(e,s)===j(e,r.resolvedBy))continue;let d=ie(e,i);return k("edit",`closed gap ${_(e,i)} by ${_(e,r.resolvedBy)}`,`closed on ${e.location} by ${s?S(e,s):"a retire"}${d?` (${L(d.rec)}, ${P(d.rec)})`:""}`,C,{gap:i,mine:r.resolvedBy,theirs:s})}return o.length===0?V(`already closed on ${e.location}`):B({...r,gaps:o})},replay(e,t,n){return Pn({contextDir:e.contextDir,graph:e.graph,...t,provenance:n}).resolved>0?{landed:!0}:{errors:[{code:"STALE_BASIS",detail:"concurrent appends kept moving the head \u2014 the gap close did not land"}]}}},zs={verb:"chat",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t),o=structuredClone(n.ops).map(s=>{if("target"in s){let d=I(e,r.targets[s.eventId],`${s.kind} target ${s.target}`),c={...s,target:d,expectedCid:d};if(c.kind==="enhance"&&(c.edges=c.edges.map((a,l)=>({...a,src:I(e,r.enhance[s.eventId]?.[l]?.src,"enhance src"),dst:I(e,r.enhance[s.eventId]?.[l]?.dst,"enhance dst")}))),c.kind==="reject"&&c.redirectTo&&(c.redirectTo=I(e,r.redirectTo[s.eventId],"redirect target")),c.kind==="retract"){let a=r.retract[s.eventId];if(!a?.dst||!c.edgeRef)throw new G("retracted edge was not pinned by endpoints");c.edgeRef={type:c.edgeRef.type,dst:I(e,a.dst,"retract dst"),...a.src?{src:I(e,a.src,"retract src")}:{}},delete c.edgeEcid}return c}return s}),i=n.judgements?.map(s=>({...s,about:H(e,s.about)}));return{ops:o,...i?{judgements:i}:{},by:J(n),...n.mintable?{mintable:n.mintable}:{},...n.sid?{sid:String(n.sid)}:{}}},precheck(e,t,n,r){let o=Ie(e,n.body);if(o)return o;let i=q(t).conv,s=P(n.body),d=`chat turn at ${s}`,c=new Set,a=[],l=(f,u)=>r.ops.some(y=>y.kind==="enhance"&&y.edges.some(b=>b.type===f&&j(e,b.src)===u)),g=(f,u)=>r.ops.some(y=>y.kind==="retract"&&y.edgeRef?.type===f&&j(e,y.target)===u);for(let[f,u]of r.ops.entries()){let y=`op ${f+1} (${u.kind})`;if("target"in u){let b=j(e,u.target);if(e.graph.superseded.has(b))return k("chat",`${d}: ${y} on ${_(e,u.target)}`,`${S(e,u.target)} was retired on ${e.location}`,C,{op:f+1,target:u.target});if(b!==u.target){if(u.kind==="edit"){let h=e.graph.getNode(u.target),m=h?.content??{},w={...m};for(let[v,x]of Object.entries(u.edit))x!==void 0&&(w[v]=x);if(h&&de(h.label,w)===b){c.add(u.eventId);continue}if(e.answer!=="apply-mine"){let v=ie(e,u.target);return k("chat",`${d}: ${y} on ${_(e,u.target)}: ${he(m,w,L(n.body),s)}`,he(m,e.graph.getNode(b)?.content??{},v?L(v.rec):"someone",v?P(v.rec):"since the fork"),W,{op:f+1,target:u.target,tip:b})}}u.target=b,u.expectedCid=b}if(u.kind==="approve"||u.kind==="reject"){let h=u.kind==="approve"?"trusted":"archived";if(e.graph.trust.get(b)===h){c.add(u.eventId);continue}let m=Vt(e,b).at(-1);if(m!==void 0&&(u.kind==="approve"?m.resolution==="rejected":m.resolution==="approved"||m.resolution==="edited")&&e.answer!=="apply-mine")return k("verdict",`${d}: ${y} on ${_(e,u.target)} by ${L(n.body)}`,`${m.resolution} by ${L(m.rec)} at ${P(m.rec)}`,W,{op:f+1,target:b,mine:u.kind,theirs:m.resolution})}if(u.kind==="retract"&&u.edgeRef){let h=u.edgeRef,m=j(e,h.dst);if(!e.graph.edgesFrom(b).find(v=>v.type===h.type&&j(e,v.dst)===m)){let v=ht(e,h.type,b);if(v&&l(h.type,b)){if(e.answer!=="apply-mine")return k("repoint",`${d}: ${y} re-points ${h.type} of ${_(e,u.target)} away from ${_(e,h.dst)}`,`${h.type} of ${S(e,u.target)} now points at ${S(e,v.live)} on ${e.location}`,W,{op:f+1,theirs:v.live});u.edgeRef={...h,dst:v.live}}else c.add(u.eventId)}}if(u.kind==="enhance")for(let h of u.edges){let m=ht(e,h.type,h.src);if(!(!m||e.graph.tipOf(m.live)===e.graph.tipOf(h.dst)||g(h.type,j(e,h.src)))){if(e.answer!=="apply-mine")return k("repoint",`${d}: ${y} points ${h.type} of ${_(e,h.src)} at ${_(e,h.dst)}`,`${h.type} of ${S(e,h.src)} now points at ${S(e,m.live)} on ${e.location}`,W,{op:f+1,edge:h,theirs:m.live});a.push({kind:"retract",target:h.src,expectedCid:j(e,h.src),edgeRef:{type:h.type,dst:m.live},reason:"re-pointed on replay",eventId:`${u.eventId}:repoint`})}}}else if(u.kind==="add"){if(e.graph.heads.get(u.convSourceId)!==H(e,i[u.eventId]))return k("chat",`${d}: ${y} cites turn ${u.cite.turn} of ${u.convSourceId}`,`the conversation ${u.convSourceId} is at another turn on ${e.location}`,C,{op:f+1});let h=de(u.label,{...u.content,derived:!0});if(e.graph.superseded.get(h)===null)return k("restore",`${d}: ${y} adds "${z(u.content.title??u.content.text)}"`,`the same node was retired on ${e.location}`,C,{op:f+1,cid:h})}}let p=[...a,...r.ops.filter(f=>!c.has(f.eventId))];return p.length===0?V(`every op is already on ${e.location}`):B({...r,ops:p})},replay(e,t,n){let r=hr({contextDir:e.contextDir,graph:e.graph,...t,provenance:n});return r.errors?{errors:r.errors}:r.record?{record:r.record}:{reason:"every op already applied"}}},Qs={verb:"design",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t),o=structuredClone(n.sections),i=new Set([...(o.scenarios??[]).map(a=>a.temp_ref),...(o.acs??[]).map(a=>a.temp_ref),...(o.tests??[]).map(a=>a.temp_ref),...(o.gaps??[]).flatMap(a=>a.temp_ref?[a.temp_ref]:[])]),s=(a,l,g)=>i.has(a)?a:I(e,l,g),d=I(e,r.ucRef,`use case ${String(n.ucRef)}`);for(let a of o.scenarios??[])a.depends_on&&(a.depends_on=a.depends_on.map((l,g)=>s(l,r.depends_on[a.temp_ref]?.[g],`${a.temp_ref}.depends_on`)));for(let a of o.acs??[])a.scope?.ref&&(a.scope={...a.scope,ref:s(a.scope.ref,r.scope[a.temp_ref],`${a.temp_ref}.scope`)});o.exercises=(o.exercises??[]).map((a,l)=>({scenario:s(a.scenario,r.exercises[l]?.scenario,"exercises.scenario"),ac:s(a.ac,r.exercises[l]?.ac,"exercises.ac")})),o.scoped_to_repoints=(o.scoped_to_repoints??[]).map((a,l)=>({ac:s(a.ac,r.scoped_to_repoints[l]?.ac,"repoint.ac"),to:s(a.to,r.scoped_to_repoints[l]?.to,"repoint.to")})),o.judgements=(o.judgements??[]).map((a,l)=>a.target&&!i.has(a.target)?{...a,target:I(e,r.judgements[l],"judgement target")}:a);for(let a of o.tests??[]){a.automates=s(a.automates,r.automates[a.temp_ref],`${a.temp_ref}.automates`),a.verifies=a.verifies.map((p,f)=>s(p,r.verifies[a.temp_ref]?.[f],`${a.temp_ref}.verifies`)),a.reuses&&(a.reuses=a.reuses.map((p,f)=>s(p,r.reuses[a.temp_ref]?.[f],`${a.temp_ref}.reuses`)));let l=r.body_tags[a.temp_ref]??{},g=Nr(a.test_md_blob,a.objectives_blob,p=>{if(i.has(p))return p;let f=I(e,l[p],`body tag ${p}`),u=e.graph.displayNameOf(j(e,f));if(!u)throw new G(`body tag ${p} has no name on ${e.location}`);return u});a.test_md_blob=g.md,a.objectives_blob=g.objectives}let c=n.generationTicket;return{ucRef:d,sections:o,by:J(n),engine:String(n.engine),force:!!n.force,...n.forceScope?{forceScope:r.forceScope.map(a=>H(e,a))}:{},...n.reason?{reason:String(n.reason)}:{},...c?{generationTicket:{...c,uc_root:cr(e.graph,d)}}:{},templateVersion:n.templateVersion??null,...n.phase?{phase:String(n.phase)}:{},...n.phaseCompleteness?{phaseCompleteness:n.phaseCompleteness}:{},...n.eventIds?{eventIds:n.eventIds}:{},...n.sid?{sid:String(n.sid)}:{}}},precheck(e,t,n,r){let o=Ie(e,n.body);if(o)return o;let i=c=>`${c.tests?.length??0} tests, ${c.scenarios?.length??0} scenarios, ${c.acs?.length??0} criteria`,s=`designed ${_(e,String(q(t).ucRef))} at ${P(n.body)}: ${i(r.sections)}`,d=j(e,r.ucRef);if(e.graph.superseded.has(d))return k("restore",s,`${S(e,r.ucRef)} was retired on ${e.location}`,C,{target:r.ucRef});if(d!==r.ucRef){let c=ie(e,r.ucRef);return k("edit",s,`${S(e,r.ucRef)} was edited on ${e.location}${c?` by ${L(c.rec)} at ${P(c.rec)}`:""}`,C,{target:r.ucRef,tip:d})}if(r.generationTicket&&lr(e.graph,r.generationTicket)!==null){let a=r.generationTicket.uc_root,l=e.graph.designGenerationOf.get(a)?.gen,g=e.theirs.filter(u=>{let y=u.design_phase;return u.design_generation?.uc_root===a&&u.design_generation.generation===l||y?.uc_root===a&&y.generation===l}),p=u=>g.reduce((y,b)=>y+b.nodes.filter(h=>h.label===u).length,0),f=g.length>0?`${p("test")} tests, ${p("scenario")} scenarios, ${p("ac")} criteria`:"another generation";return k("generation",s,`generation ${String(l)} of ${S(e,r.ucRef)} taken on ${e.location}: ${f}`,C,{uc:r.ucRef,ticket:r.generationTicket})}if(r.force||r.forceScope){let c=new Set(r.forceScope??q(t).forceScope.map(l=>H(e,l))),a=new Set(gr(e.graph,r.ucRef));if(c.size!==a.size||[...c].some(l=>!a.has(l)))return k("generation",`forced a redesign of ${_(e,r.ucRef)} over ${c.size} nodes`,`the scope of ${S(e,r.ucRef)} changed on ${e.location} (${a.size} nodes now)`,C,{mine:[...c],theirs:[...a]})}for(let c of r.sections.scoped_to_repoints??[]){if(!e.graph.hasNode(c.ac))continue;let a=ht(e,"scoped_to",c.ac);if(a&&e.graph.tipOf(a.live)!==(e.graph.hasNode(c.to)?e.graph.tipOf(c.to):c.to)&&e.answer!=="apply-mine")return k("repoint",`re-scoped ${_(e,c.ac)} to ${_(e,c.to)}`,`${S(e,c.ac)} was re-scoped to ${S(e,a.live)} on ${e.location}`,W,{ac:c.ac,mine:c.to,theirs:a.live})}return B(r)},replay(e,t,n){let r=new Map((t.sections.tests??[]).map(i=>[i.temp_ref,i])),o=mr({contextDir:e.contextDir,graph:e.graph,...t,strict:!0,provenance:n,finalizeTestBody:(i,s)=>{if(!i.test_md_blob)return null;let d=new Map;for(let l of i.reuses){let g=s(l);g!==null&&g!==l&&d.set(l,g)}let c=sn(on(i.test_md_blob,d),s).md;if(c===i.test_md_blob)return null;let a=l=>{for(let[g,p]of r)if(s(g)===l&&p.test_md_blob)return{body:p.test_md_blob,cycleKey:`batch:${l}`,next:a};return cn(e.graph)(l)};return{test_md_blob:c,definitionId:an(dn(c,a))}}});return o.errors?{errors:o.errors}:o.record?{record:o.record}:{reason:"everything in this phase is already current"}}},Zs={verb:"execution",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t).facts;return{facts:n.facts.map((i,s)=>({...i,about_cid:I(e,r[s]?.about_cid,`test ${i.ref}`),...i.per_ac?{per_ac:i.per_ac.map((d,c)=>({...d,ac_cid:I(e,r[s]?.per_ac[c],`criterion ${d.ac_ref}`)}))}:{}})),by:J(n),...n.eventIds?{eventIds:n.eventIds}:{}}},precheck(e,t,n,r){let o=Ie(e,n.body);if(o)return o;let i=[];for(let[d,c]of r.facts.entries()){let a=(e.index.exec[c.about_cid]??[]).find(l=>l.execution_id===c.execution_id);if(!a){i.push(d);continue}return k("ambiguous",`run ${c.execution_id} of ${_(e,c.about_cid)}: ${c.verdict}`,`the same run id is on ${e.location} (${a.verdict}) under no matching intent digest`,C,{execution_id:c.execution_id,mine:c,theirs:a})}if(i.length===0)return V(`every run is already on ${e.location}`);let s=r.eventIds&&r.eventIds.length===r.facts.length?r.eventIds.filter((d,c)=>i.includes(c)):r.eventIds;return B({...r,facts:i.map(d=>r.facts[d]),...s?{eventIds:s}:{}})},replay:(e,t,n)=>jn(e.contextDir,e.graph,{...t,pinned:!0,provenance:n})},Xs={verb:"parked",accepts:[1,1],rebind(e,t){let n=structuredClone(N(t).line);return n.facts=n.facts.map(r=>({...r,about_cid:I(e,r.about_cid,`test ${r.ref}`),...r.per_ac?{per_ac:r.per_ac.map(o=>({...o,...o.ac_cid?{ac_cid:H(e,o.ac_cid)}:{}}))}:{}})),{line:n}},precheck:(e,t,n,r)=>Ie(e,n.body)??B(r),replay(e,t,n){let r=Tn(e.contextDir,t.line,{provenance:n});return r.errors?{errors:r.errors}:r.record?{record:r.record}:{reason:"every parked fact already applied"}}},eo={verb:"exec-supersede",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t);return{tip:I(e,r.tip,"edited test"),raw:String(n.raw),fileId:String(n.fileId),by:J(n),imports:Object.fromEntries(Object.entries(r.imports).map(([o,i])=>[o,I(e,i,`import ${o}`)]))}},precheck(e,t,n,r){let o=j(e,r.tip);if(e.graph.superseded.has(o))return k("restore",`edited ${_(e,r.tip)} in its file`,`${S(e,r.tip)} was retired on ${e.location}`,C,{target:r.tip});if(o!==r.tip&&n.body.nodes.some(i=>i.cid===o))return V(`${e.location} has the same edit`);if(o!==r.tip&&e.answer!=="apply-mine"){let i=ie(e,r.tip);return k("edit",`edited ${_(e,r.tip)} in its file at ${P(n.body)}`,`${S(e,r.tip)} was edited on ${e.location}${i?` by ${L(i.rec)} at ${P(i.rec)}`:""}`,W,{target:r.tip,tip:o})}return B({...r,tip:o})},replay(e,t,n){let r=xn(e.contextDir,e.graph,t.tip,t.raw,t.fileId,e.contextDir,t.by,{provenance:n,imports:t.imports,throwTransient:!0});return r.error?{errors:[{code:"SUPERSEDE_REFUSED",detail:r.error}]}:r.newCid===t.tip?{reason:"the file content is already the tip"}:{landed:!0}}},to={verb:"ingest",accepts:[1,1],rebind(e,t){let n=N(t),r=ce(e.contextDir,String(n.blob));if(r===null)throw new G(`the bytes of ${String(n.source_id)} (${re(String(n.blob))}) are not in the blob store`);return{sourceId:String(n.source_id),blob:String(n.blob),bytes:r,label:String(n.label),media:n.media,derived:n.derived_blobs??[],...n.eventIds?{eventIds:n.eventIds}:{}}},precheck(e,t,n,r){let o=e.graph.heads.get(r.sourceId)??null;if(o!==null&&e.graph.getNode(o)?.content.blob===r.blob)return V(`already at that head: ${r.sourceId}`);let i=q(t).prior_head,s=i===null?null:H(e,i);if(o!==s&&e.answer!=="apply-mine"){let d=e.theirs.find(a=>a.source_head_moves[r.sourceId]===o),c=o?ce(e.contextDir,String(e.graph.getNode(o)?.content.blob??"")):null;return k("head",`ingested ${r.sourceId}: ${r.bytes.byteLength} bytes at ${P(n.body)}`,o?`${r.sourceId}: ${c?.byteLength??"?"} bytes ingested on ${e.location}${d?` by ${L(d)} at ${P(d)}`:""}`:`${r.sourceId} was retired on ${e.location}`,W,{source_id:r.sourceId,mine:r.blob,theirs:o})}return B(r)},async replay(e,t,n){let r=xt.find(s=>s.media_type===t.media.media_type&&s.kind===t.media.format)??xt.find(s=>s.kind===t.media.format);if(!r)return{errors:[{code:"MEDIA_UNKNOWN",detail:`no media for ${t.media.format} ${t.media.media_type}`}]};let o=ir[r.kind],i=async()=>{let s=t.media.text_blob?ce(e.contextDir,t.media.text_blob):null;if(s===null)throw new Error(`the projection of ${t.sourceId} is not in the blob store`);let d=new Map;for(let a of t.derived){let l=ce(e.contextDir,a);if(l===null)throw new Error(`derived blob ${re(a)} of ${t.sourceId} is not in the blob store`);d.set(a,l)}let c=t.media.images??[];return{projection:s.toString("utf8"),inventory:c,blobs:d,delivered:c.filter(a=>a.delivery==="selected").map(a=>a.ref),converter:t.media.converter??{name:"replay",version:"0",policy:"recorded"}}};return dr({contextDir:e.contextDir,bytes:t.bytes,media:r,sourceId:t.sourceId,label:t.label,...o?{converters:{[o]:i}}:{},...t.eventIds?{eventIds:t.eventIds}:{},provenance:n}).then(s=>s.status==="unchanged"?{reason:`already at that head: ${t.sourceId}`}:{landed:!0})}},no={verb:"distill",accepts:[1,1],rebind:(e,t)=>({watermark:Number(N(t).watermark),by:J(N(t))}),precheck(e,t,n,r){let o=q(t).events.filter(i=>!e.graph.appliedEvents.has(i));return o.length>0?k("dependency",`distilled ${q(t).events.length} events into style notes`,`${o.length} of those events are not on ${e.location}`,C,{missing:o}):B(r)},replay(e,t,n){let r=fr({contextDir:e.contextDir,graph:e.graph,...t,provenance:n});return r.errors?{errors:r.errors}:r.record?{record:r.record}:{reason:"nothing new to distill"}}},ro={verb:"conv-mint",accepts:[1,1],rebind:(e,t)=>({sessionStamp:String(N(t).sessionStamp),by:J(N(t))}),precheck(e,t,n,r){let o=e.graph.heads.get(`su-conv-${r.sessionStamp}`);return typeof o=="string"?Ht(o):B(r)},replay(e,t,n){let r=pr({contextDir:e.contextDir,graph:e.graph,...t,provenance:n});return r.errors?{errors:r.errors}:{record:r.record}}},so={verb:"conv-turn",accepts:[1,1],rebind:(e,t)=>({sourceId:String(N(t).sourceId),text:String(N(t).text),force:!!N(t).force,by:J(N(t))}),precheck(e,t,n,r){let o=e.graph.heads.get(r.sourceId);if(typeof o!="string")throw new G(`conversation ${r.sourceId} is not on ${e.location}`);let i=H(e,String(q(t).append_of));if(o===i)return B(r);let s=e.graph.convChains.get(r.sourceId)?.chain??[],d=n.body.source_head_moves[r.sourceId];return typeof d=="string"&&s.includes(H(e,d))?V("turn already in the conversation"):k("head",`turn ${n.body.conv?.turn??"?"} of ${r.sourceId}: "${z(r.text)}"`,`${r.sourceId} continued differently on ${e.location}`,C,{source_id:r.sourceId})},replay(e,t,n){let r=ur({contextDir:e.contextDir,graph:e.graph,...t,provenance:n});return r.errors?{errors:r.errors}:r.record?{record:r.record}:{reason:"turn already present"}}},oo={verb:"revert",accepts:[1,1],rebind(e,t){let n=N(t),r=q(t).target,o=e.maps.record.byHash(r.hash),i;if(o===void 0){if(r.seq>=e.fold.from)throw new G(`the reverted record ${r.seq} was not replayed`);let{hashes:s}=$e(e.contextDir);if(s[r.seq-1]!==r.hash)throw new G(`record ${r.seq} is not the one the revert targeted`);i=r.seq}else"dedupedAs"in o?i=-1:i=o.seq;return{seq:i,...n.reason?{reason:String(n.reason)}:{},by:J(n)}},precheck(e,t,n,r){let o=q(t).target;if(r.seq<0){let i=e.maps.record.byHash(o.hash).dedupedAs;return k("revert",`reverted record ${o.seq} (${e.fold.recordAt(o.seq)?e.fold.displayNameFor(e.fold.recordAt(o.seq).body):"moved record"})`,`that record's content is shared: ${S(e,i)} exists on ${e.location}`,C,{target:o,dedupedAs:i})}return B(r)},replay(e,t,n){let r=br({contextDir:e.contextDir,graph:e.graph,...t,provenance:n});return r.errors?r.errors[0]?.code==="NOTHING_TO_REVERT"?{reason:"nothing left to revert"}:{errors:r.errors}:{record:r.record}}},io=[Hs,Gs,Js,Vs,Ws,Ks,Ys,zs,Qs,Zs,Xs,eo,to,no,ro,so,Us,oo];function qr(e,t){let n=io.find(r=>r.verb===e);return n&&t>=n.accepts[0]&&t<=n.accepts[1]?n:void 0}var ao=(e,t)=>({seq:e.seq,hash:t,ts:e.ts,build:"era-0"});function jr(e,t,n){let r=Dt(e.backupDir,t),o=t.created_by?.by??t.review[0]?.by??t.supersessions[0]?.by??t.names?.[0]?.by??{kind:"human",id:"unknown"},i=(s,d,c)=>({envelope:{v:1,verb:s,args:un(d),pins:c,born:ao(t,n)}});switch(r){case"execution":{let s=(t.executions??[]).map(c=>({ref:e.nameOf(c.about)??c.about,definition_id_at_run:c.definition_id_at_run,verdict:c.verdict,...c.per_ac?{per_ac:c.per_ac.map(a=>({ac_ref:a.ac_ref,ac_cid:a.ac_cid??e.resolveName(a.ac_ref)??null,verdict:a.verdict}))}:{},drift_flag:c.drift_flag,oracle_mode:c.oracle_mode,stale_at_run:c.stale_at_run,...c.unresolved_acs?{unresolved_acs:c.unresolved_acs}:{},execution_id:c.execution_id,...c.evidence_id?{evidence_id:c.evidence_id}:{},...c.duration_ms!==void 0?{duration_ms:c.duration_ms}:{},started_at:c.started_at,mode:c.mode,local:c.local,...c.via_parent?{via_parent:c.via_parent}:{},about_cid:c.about})),d=(t.executions??[]).map(c=>({about_cid:c.about,per_ac:(c.per_ac??[]).map(a=>a.ac_cid??e.resolveName(a.ac_ref)??null)}));return d.some(c=>c.per_ac.some(a=>a===null))?{hold:"era-0 execution: a criterion name does not resolve on the pre-reset graph"}:i("execution",{facts:s,by:o,eventIds:t.event_ids??null},{facts:d})}case"review":{let s={},d={},c=new Set(t.nodes.map(a=>a.cid));for(let a of t.supersessions)if(!(a.kind!=="node"||a.new===null||a.new===a.old)){if(c.has(a.new)){let l=e.graph.getNode(a.old)?.content??{},g=t.nodes.find(f=>f.cid===a.new).content,p={};for(let f of["title","summary","risk"])JSON.stringify(l[f])!==JSON.stringify(g[f])&&(p[f]=g[f]);s[a.old]={resolution:"edited",edit:p,reason:a.reason}}else s[a.new]={resolution:"supersede",supersedeTarget:a.old,reason:a.reason},d[a.new]=a.new;d[a.old]=a.old}for(let a of t.review)c.has(a.id)||a.id in s||(a.resolution==="approved"||a.resolution==="rejected"?(s[a.id]={resolution:a.resolution,...a.reason?{reason:a.reason}:{}},d[a.id]=a.id):a.resolution==="pending"&&a.kind==="pending_archive"&&(s[a.id]={resolution:"rejected",...a.reason?{reason:a.reason}:{}},d[a.id]=a.id));return Object.keys(s).length===0?{hold:"era-0 review: no verdict can be read off the record"}:i("review",{verdicts:s,by:o,holdArchives:t.review.some(a=>a.kind==="pending_archive")},{verdicts:d,supersedeTarget:{}})}case"names":return i("names",{assignments:(t.names??[]).map(s=>({ref:s.cid,slug:s.slug})),by:o},{refs:Object.fromEntries((t.names??[]).map(s=>[s.cid,s.cid]))});case"retire":{let[s]=Object.keys(t.source_head_moves),d=t.supersessions.find(c=>c.kind==="node");return i("retire",{sourceId:s,reason:d.reason,by:o},{head:d.kind==="node"?d.old:null})}case"archive":{let s=t.supersessions[0];return s.kind!=="node"?{hold:"era-0 archive: no node tombstone"}:i("archive",{ref:s.old,reason:s.reason,by:o},{ref:s.old})}case"ingest":{let[s,d]=Object.entries(t.source_head_moves)[0],c=t.nodes.find(p=>p.cid===d),a=t.media?.[s];if(!c||!a)return{hold:"era-0 ingest: the record carries no source node or media fact"};let l=null;for(let p of e.chain){if(p.seq>=t.seq)break;s in p.source_head_moves&&(l=p.source_head_moves[s])}let g=[...a.text_blob?[a.text_blob]:[],...(a.images??[]).flatMap(p=>p.blob?[p.blob]:[])];return i("ingest",{source_id:s,blob:String(c.content.blob),label:s,media:a,derived_blobs:g,eventIds:t.event_ids??null},{prior_head:l})}case"revert":return{hold:"era-0 revert: the target record is not named without an envelope"};default:return{hold:`no intent envelope (written before stamps): ${r} holds whole`}}}var Tr=3,fo=/^sha256:[0-9a-f]{64}$/;function gt(e,t=new Set){if(typeof e=="string")fo.test(e)&&t.add(e);else if(Array.isArray(e))for(let n of e)gt(n,t);else if(e&&typeof e=="object")for(let n of Object.values(e))gt(n,t);return t}function xr(e,t){let n;try{n=Oe(e.backupDir,t.hash)}catch(r){return{hold:`unreadable envelope: ${r instanceof Error?r.message:String(r)}`}}return n?{envelope:n}:jr(e,t.body,t.hash)}var ho=e=>{let t=e.design_phase;return t?.uc_root&&typeof t.generation=="number"?`${t.uc_root}@${t.generation}`:e.design_generation?`${e.design_generation.uc_root}@${e.design_generation.generation}`:null};function go(e){let t=[],n=new Map,r=new Map,o=new Map;for(let i of e.records){let s=xr(e,i),d="envelope"in s?s.envelope.verb:e.displayNameFor(i.body).split(" ")[0],c="envelope"in s?gt(s.envelope.pins):gt([i.body.executions?.map(u=>u.about),i.body.supersessions,i.body.review.map(u=>u.id),i.body.names?.map(u=>u.cid)]),a=new Set;for(let u of c){let y=r.get(u);y&&a.add(y)}if("envelope"in s&&s.envelope.verb==="revert"){let u=s.envelope.pins.target?.hash;u&&e.records.some(y=>y.hash===u)&&a.add(u)}if("envelope"in s&&s.envelope.verb==="distill")for(let u of s.envelope.pins.events){let y=o.get(u);y&&a.add(y)}let l=d==="design"?ho(i.body):null,g=l?n.get(l):void 0,p={[i.hash]:i.seq};if(i.body.replayed_from&&(p[i.body.replayed_from.orig.hash]=i.seq),g){g.group.push({seq:i.seq,hash:i.hash}),Object.assign(g.origins,p);for(let u of a)u!==g.k&&!g.deps.includes(u)&&g.deps.push(u);for(let u of i.body.nodes)r.set(u.cid,g.k);continue}let f={k:i.hash,orig:{seq:i.seq,hash:i.hash},verb:d,label:e.displayNameFor(i.body),deps:[...a],origins:p};l&&(f.group=[{seq:i.seq,hash:i.hash}],n.set(l,f)),t.push(f);for(let u of i.body.nodes)r.set(u.cid,f.k);for(let u of i.body.event_ids??[])o.set(u,f.k)}return t}var mo=e=>e instanceof mn||e instanceof yn,Ge=class{constructor(t,n,r,o){this.contextDir=t;this.fold=n;this.ledger=r;this.opts=o;this.chain=it(t)}chain;freshCtx(t){let n=ke(this.contextDir),r=rt(this.contextDir),o=Ce(this.contextDir,this.fold.base.seq,this.fold.base.hash).records.filter(i=>i.replayed_from?.backup!==this.fold.backupId);return{contextDir:this.contextDir,backupDir:this.fold.backupDir,backupId:this.fold.backupId,location:this.ledger.location,fold:this.fold,maps:this.ledger.maps,graph:r,index:n,theirs:o,probe:this.opts.probe===void 0?Or:this.opts.probe,...t?{answer:t}:{}}}recordAt(t){let n=t===1?null:this.chain.hashAt(t-1),r=Ce(this.contextDir,t-1,n).records[0];if(!r)throw new Error(`record ${t} vanished after its append`);return r}emit(t){this.opts.onItem?.(t)}card(t,n){return{holdId:`h${t.orig.seq}`,kind:n.kind,verb:t.verb,orig:t.orig,label:t.label,mine:n.mine,theirs:n.theirs,answers:n.answers,detail:n.detail}}finish(t,n){this.ledger.endItem(t.k,n);let r=this.fold.backupId;if("held"in n){let o=n.held;this.emit({type:"sync_rebase_decision",...te(r,o,this.ledger.location)}),this.emit({type:"sync_rebase_item",rebase_id:r,seq:t.orig.seq,intent:t.verb,outcome:"decision",reason:`${o.kind}: ${o.theirs}`})}else if("applied"in n){let o=this.ledger.aliases.filter(i=>i.k===t.k).map(({from:i,to:s})=>({from:i,to:s}));this.emit({type:"sync_rebase_item",rebase_id:r,seq:t.orig.seq,intent:t.verb,outcome:"reapplied",...o.length>0?{aliases:o}:{}})}else"deduped"in n?this.emit({type:"sync_rebase_item",rebase_id:r,seq:t.orig.seq,intent:t.verb,outcome:"already-present",reason:`already present: ${n.deduped.as.slice(0,19)}`}):this.emit({type:"sync_rebase_item",rebase_id:r,seq:t.orig.seq,intent:t.verb,outcome:"not-reapplied",reason:n.skipped.reason})}async runItem(t,n,r=0){let o=(t.deps??[]).find(c=>{let a=this.ledger.item(c).outcome;return a!==void 0&&"held"in a});if(o){let c=this.ledger.item(o);this.ledger.beginItem(t.k,{seq:0,hash:null}),this.finish(t,{held:this.card(t,{kind:"dependency",mine:t.label,theirs:`depends on decision h${c.orig.seq} (${c.label})`,answers:["keep-theirs"],detail:{depends_on:c.orig.seq}})});return}let i=(t.group??[t.orig]).filter(c=>c.seq>r).map(c=>this.fold.recordAt(c.seq)),s=this.freshCtx(n);r===0&&this.ledger.beginItem(t.k,{seq:s.graph.lastSeq,hash:s.graph.latestHash});let d;for(let c of i){let a=await this.runRecord(s,t,c,n);if("held"in a){this.finish(t,a);return}d=a,s=this.freshCtx(n)}this.finish(t,d??{skipped:{reason:"nothing to replay"}})}async runRecord(t,n,r,o){let i=xr(this.fold,r);if("hold"in i)return{held:this.card(n,{kind:"unreadable",mine:n.label,theirs:i.hold,answers:["keep-theirs"],detail:{record:r.body}})};let s=i.envelope,d=this.opts.registry?.find(c=>c.verb===s.verb)??qr(s.verb,s.v);if(!d)return{held:this.card(n,{kind:"unknown-intent",mine:n.label,theirs:`intent ${s.verb} v${s.v} is not one this build replays`,answers:["keep-theirs"],detail:{envelope:s}})};for(let c=0;;c++){let a;try{a=d.precheck(t,s,r,d.rebind(t,s,r))}catch(u){if(u instanceof G)return{held:this.card(n,{kind:"unmapped",mine:n.label,theirs:u.message,answers:["keep-theirs"],detail:{}})};throw u}if(a.kind==="noop")return{skipped:{reason:a.reason}};if(a.kind==="hold")return{held:this.card(n,a.hold)};if(a.kind==="dedupe")return this.ledger.maps.record.set({seq:r.seq,hash:r.hash},{dedupedAs:a.as}),this.ledger.setMaps(this.ledger.maps),{deduped:{as:a.as}};let l=[...a.aliases??[],...Ar(t,r.body)],g=r.body.replayed_from,p={replayed_from:{backup:this.fold.backupId,orig:g?.orig??{seq:r.seq,hash:r.hash},orig_digests:g?.orig_digests??r.body.event_digests??[],aliases:l}},f;this.opts.failpoint?.("before-append",{seq:r.seq,verb:s.verb});try{f=await d.replay(t,a.inputs,p)}catch(u){if(mo(u)&&c<Tr){t=this.freshCtx(o);continue}let y=this.ledger.reconcile(n.k,this.chain);return y?this.applied(n,r,y):{held:this.card(n,{kind:"refused",mine:n.label,theirs:u instanceof Error?u.message:String(u),answers:["keep-theirs"],detail:{}})}}if(this.opts.failpoint?.("after-append",{seq:r.seq,verb:s.verb}),f.errors&&f.errors.length>0){if(f.errors[0].code==="STALE_BASIS"&&c<Tr){t=this.freshCtx(o);continue}return{held:this.card(n,{kind:"refused",mine:n.label,theirs:f.errors.map(u=>`${u.code}: ${u.detail}`).join("; "),answers:["keep-theirs"],detail:{errors:f.errors}})}}if(f.record)return this.applied(n,r,{seq:f.record.seq,hash:this.chain.hashAt(f.record.seq)},f.record);if(f.landed){let u=this.ledger.reconcile(n.k,this.chain);return u?this.applied(n,r,u):{held:this.card(n,{kind:"refused",mine:n.label,theirs:"the committer reported a write that is not in the chain",answers:["keep-theirs"],detail:{}})}}return{skipped:{reason:f.reason??"nothing to write"}}}}applied(t,n,r,o){let i=o??this.recordAt(r.seq),s=Cr(n.body,i);for(let[c,a]of s)c!==a&&this.ledger.maps.cid.set(c,a);let d=n.body.nodes.length>0&&i.nodes.length===0?this.ledger.maps.cid.rewrite(n.body.nodes[0].cid):null;this.ledger.maps.record.set({seq:n.seq,hash:n.hash},d?{dedupedAs:d}:r),this.ledger.setMaps(this.ledger.maps);for(let c of Pr(n.body,i,s))this.ledger.addAlias({...c,k:t.k});return d?{deduped:{as:d,newSeq:r.seq,newHash:r.hash}}:{applied:{newSeq:r.seq,newHash:r.hash}}}async reconcilePending(t,n){let r,o=0;for(let s of n){let d=this.fold.recordAt(s.member);r=this.applied(t,d,{seq:s.seq,hash:s.hash},this.recordAt(s.seq)),o=Math.max(o,d.seq)}(t.group??[]).some(s=>s.seq>o)?await this.runItem(t,t.answer,o):this.finish(t,r??{skipped:{reason:"nothing to replay"}})}async walk(){for(let t of this.ledger.items)t.outcome===void 0&&await this.runItem(t,t.answer)}async answer(t,n,r){let o=this.ledger.resolveHold(t,n);n==="keep-theirs"?(this.ledger.beginItem(o.k,{seq:0,hash:null}),this.finish(o,{skipped:{reason:`you kept ${this.ledger.location}'s version`}})):await this.runItem(o,n);let i=s=>{let d=this.ledger.item(s).outcome;return d!==void 0&&"held"in d};for(let s=!0;s;){s=!1;for(let d of this.ledger.items){let c=d.outcome;c===void 0||!("held"in c)||c.held.kind!=="dependency"||(d.deps??[]).some(i)||r?.has(c.held.holdId)||(this.ledger.reopenHold(c.held.holdId),await this.runItem(d),s=!0)}}}result(){let t={applied:0,skipped:0,held:0,deduped:0};for(let n of this.ledger.items){let r=n.outcome;r&&("applied"in r?t.applied++:"held"in r?t.held++:"deduped"in r?t.deduped++:t.skipped++)}return{...t,ledger:this.ledger}}async settle(){let t=new Set(Object.keys(this.opts.verdicts??{}));for(let[r,o]of Object.entries(this.opts.verdicts??{}))await this.answer(r,o,t);let n=this.result();return n.held===0&&this.ledger.close("done"),this.emit({type:"sync_rebase_done",rebase_id:this.fold.backupId,reapplied:n.applied,already_present:n.deduped,not_reapplied:n.skipped,decisions_open:n.held,status:n.held===0?"complete":"paused"}),n}};function Fr(e,t){let n=t.answersFor;if(!(n===void 0||e.backupId===n.rebaseId&&e.rev===n.rev))throw new R("SYNC_REBASE_PENDING",e.backupId===n.rebaseId?`rebase ${e.backupId} changed since your answers were checked (revision ${n.rev}, now ${e.rev}); nothing was written`:`your answers were checked against rebase ${n.rebaseId}, but rebase ${e.backupId} is the open one; nothing was written`,"run kane-cli context sync status to read the decisions again, then run the command again with your answers")}var Lr=e=>new O(`rebase ${e} is closed \u2014 kane-cli context sync doctor lists every rebase and what it reapplied`);function Kt(e){let t=lo(e,"base-witness.json");if(po(t))try{let n=JSON.parse(uo(t,"utf8")).name;return typeof n=="string"?n:void 0}catch{return}}async function Br(e,t,n={}){let r=fe(e,co(t));try{He(t);let o=Y(e);if(o)throw new O(`rebase ${o.backupId} is still open \u2014 run kane-cli context sync or kane-cli context pull to finish it, or kane-cli context sync doctor --abort to close it`);let i=pt(e,t),s=tr(e,t,go(i),i.from,n.location??Kt(t)),d=new Ge(e,i,s,n),c=it(e);for(let a of s.items){let l=s.reconcileFrom(a.k,c,i.base);l.length!==0&&(s.beginItem(a.k,{seq:i.base.seq,hash:i.base.hash}),await d.reconcilePending(a,l))}return await d.walk(),await d.settle()}finally{r()}}async function Dr(e,t,n={}){let r=fe(e,t);try{let o=ne(e,t);if(o.state!=="open")throw Lr(t);Fr(o,n),He(o.backup);let i=it(e);if(!o.lastAppliedInChain(i))throw new O(`the last reapplied record of ${t} is no longer in the chain: the store was reset or rebuilt underneath the rebase \u2014 kane-cli context sync doctor --abort closes it; kane-cli context sync doctor --export <dir> --from ${t} builds the saved store beside`);let s=new Ge(e,pt(e,o.backup),o,n),d=o.pendingItem();if(d){let c=o.reconcileAll(d.k,i);c.length>0?await s.reconcilePending(d,c):await s.runItem(d,d.answer)}return await s.walk(),await s.settle()}finally{r()}}function Mr(e,t){let n=fe(e,t);try{let r=ne(e,t);return r.state==="open"&&r.close("abort"),r}finally{n()}}function mt(e){return e.listHolds()}async function Hr(e,t,n,r,o={}){let i=fe(e,t);try{let s=ne(e,t);if(s.state!=="open")throw Lr(t);Fr(s,o);let d=new Ge(e,pt(e,s.backup),s,o);await d.answer(n,r);let c=d.result();return c.held===0&&s.close("done"),c}finally{i()}}import{constants as yo,copyFileSync as bo,existsSync as Ve,lstatSync as zt,mkdirSync as Gr,readdirSync as Jr,readFileSync as wt,realpathSync as Vr}from"fs";import{basename as Wr,dirname as Ur,join as D,relative as wo,resolve as vo,sep as $o}from"path";function Kr(e,t,n){He(t);let r=ko(t),o=JSON.parse(wt(D(t,"base-witness.json"),"utf8")),i=D(n,".context"),s=Vr(e),d=yt(n),c=yt(i),a=yt(ue(n));for(let[h,m]of[["the target",d],[".context there",c],["the tests directory there",a]]){if(bt(m,s))throw new Error(`${h} (${m}) is inside the live store ${e}; export into a directory outside it`);if(bt(m,yt(t)))throw new Error(`${h} (${m}) is inside the backup ${t}; export into a directory outside it`)}if(!bt(c,d))throw new Error(`${i} is a link that leaves ${n} (${c}); export into a directory whose .context is its own`);if(!bt(a,d))throw new Error(`${ue(n)} is a link that leaves ${n} (${a}); export into a directory whose tests directory is its own`);if(o.base.seq>0&&$n(e,o.base.seq)!==o.base.hash)throw new Error(`backup ${Wr(t)} continues position ${o.base.seq} of a chain this store no longer holds (a later rebase replaced it): export from the rebase whose base is current, or clone the location and export there`);if(Ve(i)&&Jr(i).length>0)throw new Error(`${i} already exists and is not empty; export into a fresh directory`);for(let{name:h}of r){if(!h.startsWith("tests/"))continue;let m=D(ue(n),h.slice(6));if(Yt(m))throw new Error(`${m} already exists; export into a fresh directory`)}if(Yt(i)&&zt(i).isSymbolicLink())throw new Error(`${i} is a link; export into a directory whose .context is its own`);Gr(i,{recursive:!0});let{records:l,hashes:g}=$e(e),p=0;for(let h of l){if(h.seq>=o.from)break;let m=g[h.seq-1].slice(7),w=`${String(h.seq).padStart(6,"0")}-${m.slice(0,12)}.json`;Je(D(e,"commits",w),D(i,"commits",w));let v=D("intents",m.slice(0,2),`${m}.json`);Ve(D(e,v))&&Je(D(e,v),D(i,v)),p++}for(let h of["blobs","proposals"])if(Ve(D(e,h)))for(let m of Yr(D(e,h)))Je(m,D(i,wo(e,m)));let f=0,u=0;for(let{name:h}of r){let m=D(t,h);if(h.startsWith("tests/"))Je(m,D(ue(n),h.slice(6))),f++;else{if(h==="base-witness.json"||h==="store.json")continue;h.startsWith("sessions/")&&u++,h.startsWith("commits/")&&p++,_o(m,D(i,h))}}et(D(i,"commits")),ve(i);let y=Xe(i),b=r.filter(h=>h.name.startsWith("commits/")).map(h=>h.name).sort().pop();if(!b||y===null||!b.includes(y.hash.slice(7,19)))throw new Error(`the materialized chain ends at ${y?.seq??0}, not at the backup's last record ${b??"(none)"}`);return ke(i),{contextDir:i,from:o.from,records:p,tests:f,sessions:u,gitignore:or(n)}}function yt(e){let t=vo(e),n=[];for(;!Ve(t);){n.unshift(Wr(t));let r=Ur(t);if(r===t)break;t=r}return D(Vr(t),...n)}var bt=(e,t)=>e===t||e.startsWith(t+$o);function ko(e){let t=D(e,"manifest.json");if(!Ve(t))throw new Error(`${e} has no manifest.json; it is not a complete backup`);return JSON.parse(wt(t,"utf8"))}function Yt(e){try{return zt(e),!0}catch{return!1}}function Je(e,t){Gr(Ur(t),{recursive:!0}),bo(e,t,yo.COPYFILE_EXCL)}function _o(e,t){if(!Yt(t))return Je(e,t);if(!(zt(t).isFile()&&wt(t).equals(wt(e))))throw new Error(`${t} already exists with other content; export into a fresh directory`)}function Yr(e){let t=[];for(let n of Jr(e,{withFileTypes:!0})){let r=D(e,n.name);n.isDirectory()?t.push(...Yr(r)):n.isFile()&&t.push(r)}return t}import{existsSync as Se,readdirSync as Xr,readFileSync as kt}from"fs";import{join as se}from"path";import{existsSync as zr,readdirSync as Ro,readFileSync as Io,rmSync as So}from"fs";import{join as vt}from"path";var Eo=/^@import\s+(\S+)\s*$/,Oo=/\.quarantined-[0-9TZ-]+$/;function Qr(e,t,n,r,o=new Map){let i=ue(t),s={restored:[],held:[],removed:[]},d=r.map(p=>n.nameOf.get(p)).filter(p=>typeof p=="string"),c=new Set,a=Yn(i);for(let p of d){let f=a.get(p)?.[0]??vt(i,`${ot(n,p)}_test.md`);zr(f)&&!(a.get(p)??[]).includes(f)&&(c.add(p),s.held.push({id:p,path:f,reason:`${f} exists with other content`}))}for(let p of d){if(c.has(p))continue;let f=Co(n,p).find(u=>c.has(u));f&&(c.add(p),s.held.push({id:p,path:vt(i,`${ot(n,p)}_test.md`),reason:`imports ${f}, which is held`}))}let l=d.filter(p=>!c.has(p)).map(p=>n.resolve(p).cid);if(l.length>0){let p=zn({graph:n,cids:l,cwd:t});for(let f of p.wrote)s.restored.push({id:f.id,path:f.path});for(let f of p.refused)s.held.push({id:f.id,path:vt(i,`${ot(n,f.id)}_test.md`),reason:f.reason})}let g=new Set(s.restored.map(p=>p.id));if(zr(i))for(let p of Ro(i)){if(!Oo.test(p))continue;let f=vt(i,p),u=$t(f),y=u?o.get(u)??u:null;if(!y||!g.has(y))continue;let b=s.restored.find(h=>h.id===y).path;$t(b)===y&&(So(f),s.removed.push(f))}return s}function Co(e,t){let n=e.resolve(t);return((n?e.getNode(n.tip)?.content.test_md_blob:void 0)??"").split(`
|
|
8
|
+
`).flatMap(o=>{let i=Eo.exec(o.trim());return i?[i[1]]:[]})}function $t(e){try{let t=/^---\n(?:[\s\S]*?\n)?assurance:\n\s+id:\s*(\S+)/.exec(Io(e,"utf8"));return t?t[1]:null}catch{return null}}function es(e,t){if(!t||t.length===0)return;let n=Y(e);if(!n)throw new Error(`no rebase is open, so there is no decision to answer (--answer ${t[0]})`);let r=new Map(n.listHolds().map(i=>[i.holdId,i])),o={};for(let i of t){let s=i.indexOf("=");if(s<=0)throw new Error(`--answer takes <decision id>=<choice>, got '${i}'`);let d=i.slice(0,s),c=i.slice(s+1),a=r.get(d);if(!a)throw new Error(`${d} is not an open decision of rebase ${n.backupId} \u2014 kane-cli context sync status lists them`);if(!qt.includes(c))throw new Error(`'${c}' is not a choice: use ${qt.join(", ")}`);if(!a.answers.includes(c))throw new Error(`${c} is not a choice ${d} accepts (${a.answers.join(", ")})`);o[d]=c}return{rebaseId:n.backupId,rev:n.rev,verdicts:o}}var Zr={reapplied:(e,t)=>`reapplied your ${e} from record ${t}`,"already-present":(e,t)=>`already present: your ${e} from record ${t}`,"not-reapplied":(e,t,n)=>`not reapplied: your ${e} from record ${t}${n?` (${n})`:""}`,decision:(e,t)=>`decision needed on your ${e} from record ${t}`};async function Qt(e,t,n,r,o,i,s,d,c){let a=X(o),l=Kt(o)??c??"the location",g=$=>{$.type==="sync_rebase_item"&&(e.event($),e.out(Zr[String($.outcome)](String($.intent),Number($.seq),$.reason===void 0?void 0:String($.reason))))};if(i&&i.rebaseId!==a)throw new R("SYNC_REBASE_PENDING",`your answers were checked against rebase ${i.rebaseId}, but rebase ${a} is the open one; nothing was written`,"run kane-cli context sync status to read the decisions again, then run the command again with your answers");let p=s==="continue"||Y(n)?.backupId===a?await Dr(n,a,{verdicts:i?.verdicts,answersFor:i?{rebaseId:i.rebaseId,rev:i.rev}:void 0,onItem:g}):await Br(n,o,{onItem:g,location:l}),f=We(n,r,o,p.ledger);Ee(n,p.ledger,f);let u=t.isTTY&&e.encoding!=="ndjson"&&t.walkUI?t.walkUI():null,y=!1,b=$=>y?u.note($):e.out($),h=$=>{$.type==="sync_rebase_item"&&(e.event($),b(Zr[String($.outcome)](String($.intent),Number($.seq),$.reason===void 0?void 0:String($.reason))))},m=new Set,w=new Set,v=new Set,x=new Set,ae=u?mt(ne(n,a)).length:0,F=0;try{for(;u;){let $=ne(n,a),M=mt($).filter(we=>!m.has(we.holdId)&&!w.has(we.holdId));if(M.length===0)break;let T=M[0],be=$.rev;e.event({type:"sync_rebase_decision",...te(a,T,l)}),v.add(T.holdId),F+=1,y=!0;let Z=await u.decide({card:T,index:F,total:Math.max(ae,F),rebaseId:a,location:l,record:Fe($,T.orig.seq)});if(Z==="later-all"){u.note(dt(T,Z,l));break}if(Z==="later"){u.note(dt(T,Z,l)),w.add(T.holdId);continue}await Hr(n,a,T.holdId,Z,{answersFor:{rebaseId:a,rev:be},onItem:h});let ze=ne(n,a),nn=ze.listHolds().find(we=>we.holdId===T.holdId);if(nn?(u.note(`decision ${T.holdId}: held again \u2014 ${nn.theirs}`),x.has(T.holdId)?m.add(T.holdId):(x.add(T.holdId),v.delete(T.holdId))):(u.note(dt(T,Z,l,ze.items.find(we=>we.orig.seq===T.orig.seq)?.outcome)),m.add(T.holdId)),f=We(n,r,o,ze,f),Ee(n,ze,f),u.interrupted?.())break}}finally{u&&await u.close(),y=!1}let U=ne(n,a),A=mt(U).filter($=>!v.has($.holdId));for(let $ of A)e.event({type:"sync_rebase_decision",...te(a,$,l)});if(!u)for(let $ of Zt(A))e.out($);let Q=U.listHolds().length;Q===0&&U.state==="open"&&U.close("done"),Ee(n,U,f);for(let $ of Ao(U,f,d))e.out($);return e.event(Xt(U,Q===0?"complete":"paused")),Q>0?3:0}var ge=(e,t)=>` ${e.padEnd(15)}${t}`;function Ao(e,t,n){let r=me(e),o=`${t.restored.length} restored${t.held.length>0?`, ${t.held.length} waiting: see kane-cli context sync status`:""}`,i=["",`rebase summary \u2014 ${r.decisions===0?"complete":"paused (decisions left)"}`,ge("rebase",e.backupId),ge("reapplied",String(r.reapplied)),ge("already there",String(r.alreadyPresent)),ge("not reapplied",String(r.notReapplied))];return r.decisions>0&&i.push(ge("undecided",String(r.decisions))),i.push(ge("test files",o)),r.decisions>0&&i.push(ge("resume",n)),i}function Zt(e){let t=Math.max(0,...e.map(r=>r.holdId.length)),n=Math.max(0,...e.map(r=>r.verb.length));return e.map(r=>` ${r.holdId.padEnd(t)} ${r.verb.padEnd(n)} ${r.mine} \xB7 ${r.answers.join(" | ")}`)}function Xt(e,t){let n=me(e);return{type:"sync_rebase_done",rebase_id:e.backupId,reapplied:n.reapplied,already_present:n.alreadyPresent,not_reapplied:n.notReapplied,decisions_open:n.decisions,status:t}}function me(e){let t={reapplied:0,alreadyPresent:0,notReapplied:0,decisions:0};for(let n of e.items){let r=n.outcome;r&&("applied"in r?t.reapplied++:"deduped"in r?t.alreadyPresent++:"held"in r?t.decisions++:t.notReapplied++)}return t}var Po=e=>e.items.filter(t=>t.outcome!==void 0&&"applied"in t.outcome),No=e=>e.items.filter(t=>t.outcome!==void 0&&"skipped"in t.outcome),qo=e=>({holdId:e.holdId,kind:e.kind,verb:e.verb,seq:e.orig.seq,label:e.label,mine:e.mine,theirs:e.theirs,answers:e.answers});function We(e,t,n,r,o){ke(e);let i=rt(e),s=new Map(r.aliases.map(h=>[h.from,h.to])),d=new Set(Object.values(r.maps.cid.toJSON())),c=JSON.parse(kt(se(n,"base-witness.json"),"utf8"));for(let h of Bt(n,c.base))for(let m of h.body.nodes)d.add(m.cid);let a=[],l=[],g=se(t,".testmuai","tests");for(let h of Se(g)?Xr(g):[]){if(!/\.quarantined-/.test(h))continue;let m=$t(se(g,h)),w=m?i.resolve(s.get(m)??m):null;!w||i.nodeLabel.get(w.tip)!==Qe.TEST||i.superseded.has(w.tip)||(d.has(w.tip)?a.push(w.tip):l.push({id:m,path:se(g,h),reason:`${m} now names ${r.location}'s test; your copy stays quarantined until its record is reapplied`}))}let p=a.length>0?Qr(e,t,i,a,s):{restored:[],held:[],removed:[]};p.held.push(...l);let f=new Set(i.nodeLabel.keys()),u=er(e,n,new Map(Object.entries(r.maps.cid.toJSON())),f),y=JSON.parse(kt(se(n,"manifest.json"),"utf8")),b=[...new Set(y.map(h=>h.name).filter(h=>h.startsWith("sessions/")).map(h=>h.split("/")[1]))];return{restored:[...o?.restored??[],...p.restored],held:p.held,removed:[...o?.removed??[],...p.removed],reparked:(o?.reparked??0)+u.reparked,unmapped:[...new Set([...o?.unmapped??[],...u.unmapped])],deadSessions:b}}function Ee(e,t,n){let r=Se(Te(e,t.backup))?JSON.parse(kt(Te(e,t.backup),"utf8")):{},o={version:1,backup:t.backupId,from:t.from,moved:t.items.map(i=>({seq:i.orig.seq,verb:i.verb,label:i.label})),applied:Po(t).map(i=>({orig:i.orig.seq,new:i.outcome.applied.newSeq})),held:t.listHolds().map(qo),declined:No(t).map(i=>({seq:i.orig.seq,reason:i.outcome.skipped.reason})),aliases:t.aliases.map(i=>({from:i.from,to:i.to})),quarantined:r.quarantinedTests??[],restored:n.restored,heldFiles:n.held,deadSessions:n.deadSessions,reparked:n.reparked,unmapped:n.unmapped,liveSideQueues:r.liveSideQueues??[],state:t.state};kn(Te(e,t.backup),JSON.stringify(o,null,2)+`
|
|
9
|
+
`),et(Pt(e))}function en(e,t){let n=Te(e,t);return Se(n)?JSON.parse(kt(n,"utf8")):null}function ts(e,t,n){let r=en(e,n.backup);if(!(r===null||r.state!=="closed"||(r.heldFiles??[]).length>0))return null;let i=fe(e,n.backupId);try{let s=We(e,t,n.backup,n);return Ee(e,n,s),s}finally{i()}}function _t(e){let t=se(e,"sync","backups");if(!Se(t))return;let n=xe(e)?.backup;return Xr(t).filter(o=>o.endsWith("-reset")&&Se(se(t,o,"manifest.json"))).sort().reverse().map(o=>se(t,o)).find(o=>o!==n&&!Se(se(Pt(e),`${X(o)}.json`)))}import{lstatSync as jo,realpathSync as To,rmSync as xo,statSync as Fo}from"fs";import{join as Lo}from"path";async function rs(e,t,n,r,o,i=()=>{}){let s=Lo(t,".context");if(ns(s))throw new Error(`${s} already exists \u2014 clone needs a directory without a store; to update this one run kane-cli context pull inside ${t}`);let d=Re(e,n),c=Le(d,"origin",o,{createRoot:!1});i();let a=await lt(c);if(await Bo(c),!await c.head(Ne(1)))throw await Un(c,0),new R("SYNC_LOCATION_EMPTY",`nothing to clone at ${d.location}: it holds no records`,"ask the teammate who shared this address to run kane-cli context push <name> first, then clone again");let l=!ns(t);try{let{gitignore:g}=ar(s),p=ve(s).ids,f=Fo(s);return Pe(s,{version:1,locations:[{name:"origin",kind:d.kind,location:d.location}]}),st(s,{version:1,entries:{origin:{tier:a.tier,probed_at:new Date().toISOString(),witness:null,binding:{instance_id:p.context_instance_id,realpath:To(s),dev:f.dev,ino:f.ino}}}}),r(`bound origin: ${d.kind} tier ${a.tier} (${a.detail})`),a.tier!==1&&r("pull-only: this location can be cloned and pulled, never pushed"),g?.outcome==="added"?r("added .context/ to .gitignore"):g?.outcome==="failed"&&r(`warning: could not add .context/ to .gitignore: ${g.reason}`),{...await je(s,c,"origin",r),probe:{name:"origin",kind:d.kind,tier:a.tier,detail:a.detail},...g?{gitignore:g}:{}}}catch(g){throw xo(l?t:s,{recursive:!0,force:!0}),g}}function ns(e){try{return jo(e),!0}catch{return!1}}async function Bo(e){let t=await e.get(ee);if(t===null)return;let n;try{n=JSON.parse(Buffer.from(t).toString("utf8"))}catch(o){throw new R("SYNC_OBJECT_CORRUPT",`${ee} on the storage is not JSON: ${o instanceof Error?o.message:String(o)}`,"the storage object needs a human look; nothing was created")}if(n.canonicalizer!=="v1")throw new R("SYNC_CLIENT_TOO_OLD",`the storage was written with canonicalizer ${String(n.canonicalizer)}; this kane-cli uses ${"v1"}`,"upgrade kane-cli to a release that uses that canonicalizer, then clone again");let r=await pe(e,1);if(r.hash!==n.genesis_hash)throw new R("SYNC_OBJECT_CORRUPT",`${ee} names genesis ${String(n.genesis_hash)}, but position 1 on the storage hashes ${r.hash}`,"the storage needs a human look; nothing was created")}var is=["interactive","agent","ci","override"],as="usage: kane-cli context sync [name] [--answer <id=choice>] | add <name> <descriptor> | list | remove <name> | status [name] [--show <n>] | doctor [--abort | --export <dir> [--from <rebase-id>]]";function Ye(e,t){return Ln(Fn(e.mode??""),"sync",{stdout:n=>t.out(n.replace(/\n$/,"")),stderr:n=>(t.err??t.out)(n.replace(/\n$/,""))})}function E(e,t,n,r){let o=n instanceof R?n:null,i=n instanceof K?n:null,s=o?Mn(o.code):i||n instanceof O?2:r,d=n instanceof Error?n.message:String(n);if(e.encoding==="ndjson")return o?e.event({type:"sync_error",code:o.code,detail:d,remedy:o.remedy,...o.diagnostic?{diagnostic:o.diagnostic}:{}}):i?e.event({type:"error",code:i.code,message:d,...i.remedy?{remedy:i.remedy}:{}}):e.event({type:"error",message:d}),e.done(s,s===1?"error":"refused");sr(t,d);let c=o?.remedy??i?.remedy;return c&&(t.err??t.out)(`next: ${c}`),s}function It(e,t){return e instanceof R||e instanceof O||e instanceof K||!(e instanceof Error)?e:new K("USAGE",e.message,t)}function ds(e,t){try{return Re(e,t)}catch(n){throw It(n,"check the address, then run the command again")}}function cs(e){let t=e instanceof Error?e.message:"";return t.startsWith("no locations yet")?"kane-cli context sync add <name> <descriptor>":t.startsWith("name a location")?"put the location's name after the command; kane-cli context sync list shows them":"kane-cli context sync list shows this store's locations"}async function ye(e,t,n,r=!0){if(e.mode!==void 0&&!is.includes(e.mode))return Ct(Ye({mode:"agent"},t),`sync: --mode must be interactive | agent | ci | override, got '${e.mode}'`,"MODE_USAGE");let o=Ye(e,t),i=qn(n);if(!Ue(i))return E(o,t,new Error("no context store here (run `kane-cli context ingest <files>` first)"),2);if(r){let s=await ls(o,t,i);if(s!==null)return s}return{hio:o,dir:i}}async function ls(e,t,n){try{let r=await Nt(n,"resume",o=>e.out(o));r.state==="resumed"&&e.event(us(r.result))}catch(r){return E(e,t,r,2)}return null}async function Jo(e,t,n,r,o,i,s){let d,c;try{d=Y(n),c=d?void 0:_t(n)}catch(l){return E(e,t,l,2)}let a=d?.backup??c;if(a){let l=X(a),g=d?.listHolds().length??0;e.out(d?`finishing rebase ${l} first: ${g} decision${g===1?"":"s"} waiting`:`finishing rebase ${l} first: its records were saved but not reapplied yet`);let p=`kane-cli context ${i}${s?` ${s}`:""}`,f;try{f=await Qt(e,t,n,r,a,o,d?"continue":"start",p,s)}catch(u){return E(e,t,u,1)}return f===0?null:(e.out(Vo(i,n,p)),3)}try{for(let l of _e(n).filter(g=>g.state==="closed")){let g=ts(n,r,l);g&&g.restored.length>0&&e.out(`rebase ${l.backupId}: ${g.restored.length} test file${g.restored.length===1?"":"s"} restored`)}}catch(l){return E(e,t,l,2)}return null}function Vo(e,t,n){let r=Y(t)?.listHolds()??[],o=r.length,i=r.length>0?`, or ${n} --answer ${r[0].holdId}=<choice>`:"";return`${e==="sync"?"not synced":"not pulled"}: ${o} decision${o===1?"":"s"} waiting \u2014 run ${n} to answer ${o===1?"it":"them"}${i}`}function ps(e,t){let n=Y(t);if(!n)return;let r=n.listHolds().length,o=n.items.filter(i=>i.outcome===void 0).length;throw e.event({type:"sync_rebase_open",rebase_id:n.backupId,decisions_open:r,pending:o}),new R("SYNC_REBASE_PENDING",`rebase ${n.backupId} is still open: ${r} decision${r===1?"":"s"} unresolved and ${o} local record${o===1?"":"s"} not yet processed; nothing was pushed`,fn)}function us(e){return{type:"sync_rebase_started",name:e.name,rebase_id:X(e.backup),from:e.pulled.from+1,backup_path:e.backup,moved:e.moved,quarantined_tests:e.quarantinedTests}}function fs(e,t){if(e.credentials)return e.credentials;if(e.credentialEnv!==void 0){let n=e.credentialEnv,r=process.env[`${n}_ID`],o=process.env[`${n}_SECRET`],i=r?o?null:`${n}_SECRET`:`${n}_ID`;if(i)throw new K("CREDENTIALS_MISSING",`--credential-env ${n}: ${i} is not set`,`set ${n}_ID and ${n}_SECRET in the environment, then run the command again`);return{accessKeyId:r,secretAccessKey:o}}if(e.credentialFile!==void 0){let n=tn(t,e.credentialFile),r=`write {"accessKeyId": "...", "secretAccessKey": "..."} to ${n}, or pass --credential-env <VAR>`,o;try{o=os(n,"utf-8")}catch(s){let d=s.code;throw d==="ENOENT"||d==="ENOTDIR"?new K("CREDENTIALS_MISSING",`no credential file at ${n}`,r):new K("CREDENTIALS_MISSING",`the credential file at ${n} could not be read`,"check its permissions, then run the command again")}let i;try{i=JSON.parse(o)}catch{i=null}if(typeof i!="object"||i===null||!("accessKeyId"in i)||!("secretAccessKey"in i)||typeof i.accessKeyId!="string"||typeof i.secretAccessKey!="string")throw new K("CREDENTIALS_MISSING",`the credential file at ${n} is not a JSON object with accessKeyId and secretAccessKey`,r);return{accessKeyId:i.accessKeyId,secretAccessKey:i.secretAccessKey}}return null}var hs=e=>`checking ${e}: read access and safe publishing\u2026`;async function Wo(e,t,n,r,o,i){let s=await ye(n,r,o,!1);if(typeof s=="number")return s;let{hio:d,dir:c}=s,a=null,l=null,g=!1;try{let p,f;try{ct(e),p=ds(t,o),p.kind==="s3"&&(a=fs(n,o),a&&(l=vs(e),jt(e,a))),f=Le(p,e,i)}catch(b){return E(d,r,b,2)}let u;try{d.out(hs(e)),d.event({type:"sync_probe_started",name:e,kind:p.kind}),u=await lt(f)}catch(b){return E(d,r,b,1)}let y=null;try{let b=Ae(c),h={name:e,kind:p.kind,location:p.location},m=b.locations.findIndex(U=>U.name===e),w=m===-1?null:b.locations[m].location;m===-1?b.locations.push(h):b.locations[m]=h,Pe(c,b);let v=le(c),x=v.entries[e]?.witness??null,ae=w!==null&&w!==p.location;ae&&x&&(y={witness:x,from:w});let F=Mo(c);v.entries[e]={tier:u.tier,probed_at:new Date().toISOString(),witness:ae?null:x,binding:{instance_id:ve(c).ids.context_instance_id,realpath:Do(c),dev:F.dev,ino:F.ino}},st(c,v),g=!0}catch(b){return E(d,r,b,2)}return d.out(`added ${e}: ${p.kind} tier ${u.tier} (${u.detail})`),y&&(d.out(`dropped the witness at position ${y.witness.seq}: the location changed from ${y.from} to ${p.location}`),d.event({type:"sync_witness_dropped",name:e,witness:y.witness,from:y.from,to:p.location})),u.tier===2&&d.out("pull-only: this storage did not prove atomic create"),u.tier===3&&d.out("read-only: this location can be cloned and pulled, never pushed"),d.event({type:"sync_probe",name:e,kind:p.kind,tier:u.tier,detail:u.detail}),d.done(0)}finally{a&&!g&&$s(e,l)}}async function Uo(e,t,n){let r=await ye(e,t,n,!1);if(typeof r=="number")return r;let{hio:o,dir:i}=r;try{let s=le(i),d=Ae(i).locations.map(c=>({...c,tier:s.entries[c.name]?.tier??null,witness:s.entries[c.name]?.witness??null}));if(e.json)o.out(JSON.stringify(d));else if(d.length===0)o.out("no locations yet \u2014 add one with kane-cli context sync add <name> <descriptor>");else for(let c of d)o.out(`${c.name} ${c.kind} tier ${c.tier??"?"} ${Yo(c.location,n)}`);return o.event({type:"sync_locations",locations:d}),o.done(0)}catch(s){return E(o,t,s,2)}}async function Ko(e,t,n,r){let o=await ye(t,n,r,!1);if(typeof o=="number")return o;let{hio:i,dir:s}=o;try{let d=Ae(s),c=le(s),a=d.locations.find(g=>g.name===e)?.kind,l;try{l=Gn(d,c,e)}catch(g){throw It(g,cs(g))}return Pe(s,d),a==="s3"&&Tt(e),i.out(`removed ${e}`),l&&i.out(`kept its witness at position ${l.seq}: re-adding the same storage keeps its rollback protection`),i.event({type:"sync_removed",name:e,witness:l}),i.done(0)}catch(d){return E(i,n,d,2)}}function Yo(e,t){try{return rr(Re(e,t))}catch{return e}}function zo(e,t,n){switch(n.kind){case"up-to-date":return`up to date with ${e}: position ${n.storage.seq} on both sides`;case"behind":return`behind ${e}: this store is at position ${n.local.seq}, ${e} at ${n.storage.seq} \u2014 run kane-cli context pull ${e}`;case"ahead":return`ahead of ${e}: this store is at position ${n.local.seq}, ${e} at ${n.storage.seq} \u2014 run kane-cli context push ${e}`;case"diverged":return`you and ${e} both added work after position ${n.at-1} \u2014 run kane-cli context pull ${e} --rebase to save your local work, take the team version from ${e}, and then reapply yours`;case"empty-storage":return`${e} is empty: nothing has been pushed there yet \u2014 run kane-cli context push ${e}`;case"empty-local":return`this store is empty; ${e} is at position ${n.storage.seq} \u2014 run kane-cli context pull ${e}`;case"foreign-lineage":return`${e} holds a different history (its first record is not this store's) \u2014 to work on it, clone it: kane-cli context clone ${t} <dir>`}}function Qo(e,t){let n=Y(e);if(t!==void 0){let d=Number(t);if(!Number.isInteger(d)||d<=0)throw new K("USAGE","--show takes the position of a moved record","kane-cli context sync status --show <n>");let c=n??_e(e)[0];if(!c)throw new K("USAGE","no rebase here: nothing to show","kane-cli context sync doctor lists the rebases this store has");if(!c.itemAt(d))throw new K("USAGE",`no record ${d} in rebase ${c.backupId}`,"run kane-cli context sync status to list the records that can be shown");let a=c.listHolds().find(l=>l.orig.seq===d);return{lines:Fe(c,d),rebaseId:n?.backupId??null,decisions:n?n.listHolds().map(l=>te(n.backupId,l,n.location)):[],decision:a?te(c.backupId,a,c.location):null}}if(!n){let d=_e(e)[0];return{lines:((d?en(e,d.backup):null)?.heldFiles??[]).map(l=>`test file waiting: ${l.path} \u2014 ${l.reason}`),rebaseId:null,decisions:[]}}let r=n.listHolds(),o=me(n),i=[`rebase ${n.backupId} open: ${o.decisions} decision${o.decisions===1?"":"s"} waiting`,...Zt(r)],s=r[0];return i.push(`next: kane-cli context sync${s?` \xB7 kane-cli context sync status --show ${s.orig.seq} (one record in full)`:""}`),{lines:i,rebaseId:n.backupId,decisions:r.map(d=>te(n.backupId,d,n.location))}}async function Zo(e,t,n,r,o){let i=await ye(t,n,r,!1);if(typeof i=="number")return i;let{hio:s,dir:d}=i,c=xe(d);if(c)return E(s,n,new O(`a rebase from ${c.name} was interrupted at '${c.state}' \u2014 run kane-cli context sync ${c.name} or kane-cli context pull ${c.name} to finish it, or kane-cli context sync doctor to look`),2);let a;try{a=Qo(d,t.show)}catch(p){return E(s,n,p,2)}if(t.show!==void 0){if(t.json)s.out(JSON.stringify({rebase_id:a.rebaseId,decisions:a.decisions,record:a.lines,decision:a.decision??null}));else for(let p of a.lines)s.out(p);return s.event({type:"sync_status",name:null,relation:null,rebase_id:a.rebaseId,decisions:a.decisions,record:a.lines,decision:a.decision??null}),s.done(0)}let l,g;try{l=St(d,e,r,o),g=await qe(d,l.provider,l.witness)}catch(p){if(!t.json)for(let f of a.lines)s.out(f);return E(s,n,p,p instanceof Error&&!(p instanceof R)&&!(p instanceof O)&&/no sync state|no location/.test(p.message)?2:1)}if(t.json)s.out(JSON.stringify({...g,rebase_id:a.rebaseId,decisions:a.decisions}));else{s.out(zo(l.name,l.location,g));for(let p of a.lines)s.out(p)}return s.event({type:"sync_status",name:l.name,relation:g,rebase_id:a.rebaseId,decisions:a.decisions}),s.done(0)}function St(e,t,n,r){let o;try{o=Hn(Ae(e),t)}catch(s){throw It(s,cs(s))}let i=le(e).entries[o.name];if(!i)throw new Error(`no sync state for ${o.name} \u2014 run kane-cli context sync add ${o.name} <descriptor> first`);return{name:o.name,location:o.location,provider:Le(Re(o.location,n),o.name,r),witness:i.witness}}function gs(e){return`${e.imported} records (${e.from+1}..${e.to}), ${e.blobs} blobs, ${e.proposals} proposals`}function ms(e,t,n){n.imported>0&&e.out(`pulled ${gs(n)}`),e.event({type:"sync_pull_done",name:t,...n})}function ys(e,t,n){e.out(n.pushed>0?`pushed ${n.pushed} records (${n.from+1}..${n.to}), ${n.blobs} blobs, ${n.proposals} proposals`:"up to date"),n.alreadyThere>0&&e.out(`already there: ${n.alreadyThere}`),e.event({type:"sync_push_done",name:t,from:n.from,to:n.to,pushed:n.pushed,blobs:n.blobs,proposals:n.proposals,already_there:n.alreadyThere})}async function bs(e,t,n,r,o){let i=await ye(e,t,n,!1);if(typeof i=="number")return i;let{hio:s,dir:d}=i,c;try{c=es(d,e.answer)}catch(g){return E(s,t,It(g,"kane-cli context sync status lists the open decisions and the choices each accepts"),2)}let a=await ls(s,t,d);if(a!==null)return a;let l=await Jo(s,t,d,n,c,r,o);return l!==null?s.done(l):{hio:s,dir:d,answers:c}}async function Xo(e,t,n,r,o){let i=await bs(t,n,r,"pull",e);if(typeof i=="number")return i;let{hio:s,dir:d}=i,c;try{c=St(d,e,r,o)}catch(y){return E(s,n,y,2)}let{name:a,provider:l,witness:g}=c,p=y=>s.out(y),f,u=null;try{if(t.rebase){let y=await qe(d,l,g);if(y.kind==="diverged"){let b=Zn(),h=y.local.seq-y.at+1,m=`${h} local record${h===1?"":"s"} from position ${y.at}`,w=Qn(d,b);if(!t.yes){if(s.encoding==="ndjson"||!n.isTTY)throw new R("SYNC_DIVERGED",`${m} must be saved in ${w} before this store can take ${a}'s records; no terminal is available`,`kane-cli context pull ${a} --rebase --yes`);if(!(n.walkUI?await n.walkUI().confirm({name:a,count:h,from:y.at,backupPath:Go(r,w),taking:{from:y.at,to:y.storage.seq}}):await n.confirm(`${m} will be saved in ${w}. This store will take ${a}'s records, then try to reapply yours on top; a disagreement may need your decision. No history on ${a} will be rewritten. Continue?`)))return s.out(`no rebase started \u2014 run kane-cli context pull ${a} --rebase when you are ready`),3}u=await Xn(d,l,a,y,p,{ts:b})}}f=u?u.pulled:await je(d,l,a,p)}catch(y){return E(s,n,y,1)}if(u&&s.event(us(u)),ms(s,a,f),!u)return s.done(0);try{return s.done(await Qt(s,n,d,r,u.backup,void 0,"start",`kane-cli context pull ${a}`,a))}catch(y){return E(s,n,y,1)}}async function ei(e,t,n,r,o){let i=await ye(t,n,r);if(typeof i=="number")return i;let{hio:s,dir:d}=i,c;try{c=St(d,e,r,o)}catch(l){return E(s,n,l,2)}let a;try{ps(s,d),a=await Ft(d,c.provider,c.name,l=>s.out(l))}catch(l){return E(s,n,l,1)}return ys(s,c.name,a),s.done(0)}async function ti(e,t,n,r,o){let i=await bs(t,n,r,"sync",e);if(typeof i=="number")return i;let{hio:s,dir:d}=i,c;try{c=St(d,e,r,o)}catch(p){return E(s,n,p,2)}let a=p=>s.out(p),l;try{l=await je(d,c.provider,c.name,p=>{p!=="up to date"&&a(p)},{quietAhead:!0})}catch(p){return E(s,n,p,1)}ms(s,c.name,l);let g;try{ps(s,d),g=await Ft(d,c.provider,c.name,a)}catch(p){return E(s,n,p,1)}return ys(s,c.name,g),s.done(0)}var ws=e=>e.replace(/-reset$/,"").replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})-\d+Z$/,"$1 $2:$3:$4Z");function ni(e){let t=me(e),n=e.state==="open"?"open":e.closedBy==="abort"?"closed (aborted)":"closed";return`rebase ${e.backupId} (${ws(e.backupId)}): ${n}, ${t.reapplied} reapplied, ${t.alreadyPresent} already present, ${t.notReapplied} not reapplied, ${t.decisions} decision${t.decisions===1?"":"s"} open`}function ri(e,t){let n=Ke(e,"sync","backups");if(t!==void 0){let s=Ke(n,t);if(!Ue(Ke(s,"manifest.json")))throw new Error(`no rebase ${t} here \u2014 kane-cli context sync doctor lists them`);return s}let r=Y(e);if(r)return r.backup;let o=_e(e);if(o.length>1)throw new Error(`${o.length} rebases here: name one with --from <rebase-id> (kane-cli context sync doctor lists them)`);if(o.length===1)return o[0].backup;let i=_t(e);if(i)return i;throw new Error("no rebase here: nothing to export")}async function si(e,t,n){let r=await ye(e,t,n,!1);if(typeof r=="number")return r;let{hio:o,dir:i}=r;if(e.abort&&e.export!==void 0)return E(o,t,new Error(as),2);let s=null;if(e.abort)try{let m=await Nt(i,"abort");if(m.state==="refused")throw new R("SYNC_RESET_IMPORTED",m.detail,"run kane-cli context sync or kane-cli context pull to finish the interrupted rebase");if(m.state==="aborted")s={aborted:!0,detail:m.detail};else if(at(i).length>0){let w=at(i).map(v=>nr(i,v));s={aborted:!0,decisionsLeft:1,detail:`set aside ${w.length} unreadable ledger${w.length===1?"":"s"} (${w.map(v=>`sync/replay/${Rt(v)}`).join(", ")}); the backup${w.length===1?" stays":"s stay"} \u2014 the next kane-cli context sync reapplies ${w.length===1?"it":"them"} from the start`}}else{let w=Y(i);if(w){let v=Mr(i,w.backupId);Ee(i,v,We(i,n,v.backup,v));let x=me(v);s={aborted:!0,decisionsLeft:x.decisions,detail:`closed rebase ${v.backupId}: ${x.reapplied} reapplied stay, ${x.decisions} unresolved decision${x.decisions===1?"":"s"} left in the backup (receipt: sync/replay/${v.backupId}.receipt.json)`},o.event(Xt(v,"aborted"))}else s={aborted:!1,detail:"nothing to abort: no interrupted reset and no open rebase"}}e.json||o.out(s.detail)}catch(m){return E(o,t,m,2)}if(e.export!==void 0)try{let m=ri(i,e.from),w=Kr(i,m,tn(n,e.export)),v=X(m),x={type:"sync_rebase_exported",rebase_id:v,dir:w.contextDir,from:w.from,records:w.records,tests:w.tests,sessions:w.sessions};return e.json&&o.encoding!=="ndjson"?o.out(JSON.stringify(x)):o.out(`exported rebase ${v}: ${w.records} records (${w.tests} test files, ${w.sessions} session files) into ${w.contextDir}; it is its own store`),w.gitignore.outcome==="added"?(e.json||o.out("added .context/ to .gitignore"),o.event({type:"gitignore_updated",path:".gitignore"})):w.gitignore.outcome==="failed"&&(e.json||o.out(`warning: could not add .context/ to .gitignore: ${w.gitignore.reason}`),o.event({type:"warning",message:`could not add .context/ to .gitignore: ${w.gitignore.reason}`})),o.event(x),o.done(0)}catch(m){return E(o,t,m,2)}let d=xe(i),c=Ue(Ke(i,"commits",vn)),a=(Ue(At(i))?ss(At(i)):[]).filter(m=>m!==d?.nonce),l;try{l={state:"ok",tail:Xe(i)?.seq??0}}catch(m){l=m instanceof wn?{state:"forked",duplicates:m.duplicates}:{state:"unreadable",detail:m instanceof Error?m.message:String(m)}}let g=_e(i,{tolerant:!0}),p=at(i),f=g.find(m=>m.state==="open"),u=f?void 0:_t(i),y=Ke(i,"sync","backups"),b=Ue(y)?ss(y).filter(m=>m.endsWith(".aborted")):[],h={type:"sync_doctor",journal:d?{state:d.state,at:d.at,backup:d.backup}:null,sentinel:c,chain:l,orphan_incoming:a,rebases:[...u?[{rebase_id:X(u),state:"saved",closed_by:null,reapplied:0,alreadyPresent:0,notReapplied:0,decisions:0}]:[],...g.map(m=>({rebase_id:m.backupId,state:m.state,closed_by:m.closedBy??null,...me(m)}))],open_rebase:f?.backupId??u?.split("/").pop()??null,unreadable_ledgers:p,aborted_leftovers:b,aborted:s?.aborted??!1,...s?{detail:s.detail}:{}};if(e.json&&o.encoding!=="ndjson")return o.out(JSON.stringify(h)),o.event(h),o.done(s?.decisionsLeft?3:0);if(!s){o.out(d?`reset in progress, stopped at '${d.state}': from position ${d.at}, backup ${d.backup} \u2014 kane-cli context sync or kane-cli context pull finishes it; kane-cli context sync doctor --abort undoes it before the import`:"no reset in progress"),o.out(`sentinel: ${c?d?"present":"present with no journal \u2014 a reset lost its journal; the newest sync/backups/*-reset/ holds the moved records \u2014 run kane-cli context fsck and kane-cli context sync doctor --json and share both outputs":"absent"}`),l.state==="ok"?o.out(`chain: ok, tail at position ${l.tail}`):l.state==="forked"?o.out(`chain: FORKED \u2014 ${l.duplicates.join(", ")}; move the foreign files out of commits/, then run kane-cli context rebuild`):o.out(`chain: ${l.detail}`);for(let m of a)o.out(`orphan staging: sync/incoming/${m} \u2014 left by a reset that never wrote its journal; safe to delete`);u&&o.out(`rebase ${X(u)} (${ws(X(u))}): saved, not reapplied yet`);for(let m of g)o.out(ni(m));for(let m of b)o.out(`aborted backup: sync/backups/${m} \u2014 left by an abort that did not finish cleaning up; safe to delete`);for(let m of p)o.out(`unreadable ledger: sync/replay/${m}.json \u2014 every write refuses until it is set aside; its backup sync/backups/${m} stays`);p.length>0?o.out("next: kane-cli context sync doctor --abort sets the unreadable ledger aside; the next kane-cli context sync reapplies its backup from the start"):f?o.out(`next: kane-cli context sync (or kane-cli context pull) to finish rebase ${f.backupId}; kane-cli context sync doctor --abort to close it instead`):u&&o.out(`next: kane-cli context sync (or kane-cli context pull) to reapply the saved records of rebase ${X(u)}`)}return o.event(h),o.done(s?.decisionsLeft?3:0)}async function oi(e,t,n,r,o,i){if(n.mode!==void 0&&!is.includes(n.mode))return Ct(Ye({mode:"agent"},r),`clone: --mode must be interactive | agent | ci | override, got '${n.mode}'`,"MODE_USAGE");let s=Ye(n,r);if(e===void 0)return E(s,r,new K("USAGE","clone needs a location","kane-cli context clone <descriptor> [dir]"),2);let d,c;try{let p=ds(e,o),f=p.kind==="dir"?Rt(p.path):p.kind==="s3"?Rt(p.prefix)||p.bucket:p.kind==="git"?Rt(p.gitUrl).replace(/\.git$/,""):p.location.slice(7);d=tn(o,t??f);let u=p.kind==="s3"?fs(n,o):null,y=u?vs("origin"):null;u&&jt("origin",u);try{c=await rs(e,d,o,b=>s.out(b),i,()=>{s.out(hs("origin")),s.event({type:"sync_probe_started",name:"origin",kind:p.kind})})}catch(b){throw u&&$s("origin",y),b}}catch(p){return E(s,r,p,2)}let{probe:a,gitignore:l,...g}=c;return s.out(`cloned into ${d}: ${gs(c)}`),s.event({type:"sync_probe",...a}),l?.outcome==="added"?s.event({type:"gitignore_updated",path:".gitignore"}):l?.outcome==="failed"&&s.event({type:"warning",message:`could not add .context/ to .gitignore: ${l.reason}`}),s.event({type:"sync_pull_done",name:"origin",dir:d,...g}),s.done(0)}function vs(e,t){try{return os(ct(e,t),"utf-8")}catch{return null}}function $s(e,t,n){t===null?Tt(e,n):Ho(ct(e,n),t,{mode:384})}async function jd(e,t,n){let r=Be(),o=process.cwd();switch(e){case"add":if(t.length===2)return Wo(t[0],t[1],n,r,o);break;case"list":if(t.length===0)return Uo(n,r,o);break;case"remove":if(t.length===1)return Ko(t[0],n,r,o);break;case"status":if(t.length<=1)return Zo(t[0],n,r,o);break;case"doctor":if(t.length===0)return si(n,r,o);break;default:if(t.length===0)return ti(e,n,r,o)}return E(Ye(n,r),r,new Error(as),2)}function Td(e,t){return ei(e,t,Be(),process.cwd())}function xd(e,t){return Xo(e,t,Be(),process.cwd())}function Fd(e,t,n){return oi(e,t,n,Be(),process.cwd())}export{Ye as a,E as b,ye as c,ls as d,Jo as e,fs as f,Wo as g,Uo as h,Ko as i,Zo as j,Xo as k,ei as l,ti as m,si as n,oi as o,vs as p,$s as q,jd as r,Td as s,xd as t,Fd as u};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as A,c as C,e as Z}from"./chunk-UR6MHSHU.js";var b=C(H=>{"use strict";var w=class extends Error{constructor(e,t,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}},x=class extends w{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};H.CommanderError=w;H.InvalidArgumentError=x});var E=C(y=>{"use strict";var{InvalidArgumentError:ee}=b(),v=class{constructor(e,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,e[0]){case"<":this.required=!0,this._name=e.slice(1,-1);break;case"[":this.required=!1,this._name=e.slice(1,-1);break;default:this.required=!0,this._name=e;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new ee(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function te(l){let e=l.name()+(l.variadic===!0?"...":"");return l.required?"<"+e+">":"["+e+"]"}y.Argument=v;y.humanReadableArgName=te});var S=C(M=>{"use strict";var{humanReadableArgName:ie}=E(),V=class{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(e){let t=e.commands.filter(n=>!n._hidden),i=e._getHelpCommand();return i&&!i._hidden&&t.push(i),this.sortSubcommands&&t.sort((n,s)=>n.name().localeCompare(s.name())),t}compareOptions(e,t){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(e).localeCompare(i(t))}visibleOptions(e){let t=e.options.filter(n=>!n.hidden),i=e._getHelpOption();if(i&&!i.hidden){let n=i.short&&e._findOption(i.short),s=i.long&&e._findOption(i.long);!n&&!s?t.push(i):i.long&&!s?t.push(e.createOption(i.long,i.description)):i.short&&!n&&t.push(e.createOption(i.short,i.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(e){if(!this.showGlobalOptions)return[];let t=[];for(let i=e.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);t.push(...n)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(e){return e._argsDescription&&e.registeredArguments.forEach(t=>{t.description=t.description||e._argsDescription[t.name()]||""}),e.registeredArguments.find(t=>t.description)?e.registeredArguments:[]}subcommandTerm(e){let t=e.registeredArguments.map(i=>ie(i)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((i,n)=>Math.max(i,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestGlobalOptionTermLength(e,t){return t.visibleGlobalOptions(e).reduce((i,n)=>Math.max(i,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((i,n)=>Math.max(i,t.argumentTerm(n).length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let i="";for(let n=e.parent;n;n=n.parent)i=n.name()+" "+i;return i+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&t.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&t.push(`env: ${e.envVar}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}argumentDescription(e){let t=[];if(e.argChoices&&t.push(`choices: ${e.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),e.defaultValue!==void 0&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0){let i=`(${t.join(", ")})`;return e.description?`${e.description} ${i}`:i}return e.description}formatHelp(e,t){let i=t.padWidth(e,t),n=t.helpWidth||80,s=2,r=2;function a(d,_){if(_){let $=`${d.padEnd(i+r)}${_}`;return t.wrap($,n-s,i+r)}return d}function o(d){return d.join(`
|
|
3
|
+
`).replace(/^/gm," ".repeat(s))}let h=[`Usage: ${t.commandUsage(e)}`,""],u=t.commandDescription(e);u.length>0&&(h=h.concat([t.wrap(u,n,0),""]));let c=t.visibleArguments(e).map(d=>a(t.argumentTerm(d),t.argumentDescription(d)));c.length>0&&(h=h.concat(["Arguments:",o(c),""]));let p=t.visibleOptions(e).map(d=>a(t.optionTerm(d),t.optionDescription(d)));if(p.length>0&&(h=h.concat(["Options:",o(p),""])),this.showGlobalOptions){let d=t.visibleGlobalOptions(e).map(_=>a(t.optionTerm(_),t.optionDescription(_)));d.length>0&&(h=h.concat(["Global Options:",o(d),""]))}let O=t.visibleCommands(e).map(d=>a(t.subcommandTerm(d),t.subcommandDescription(d)));return O.length>0&&(h=h.concat(["Commands:",o(O),""])),h.join(`
|
|
4
|
+
`)}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestGlobalOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,i,n=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",r=new RegExp(`[\\n][${s}]+`);if(e.match(r))return e;let a=t-i;if(a<n)return e;let o=e.slice(0,i),h=e.slice(i).replace(`\r
|
|
5
|
+
`,`
|
|
6
|
+
`),u=" ".repeat(i),p="\\s\u200B",O=new RegExp(`
|
|
7
|
+
|.{1,${a-1}}([${p}]|$)|[^${p}]+?([${p}]|$)`,"g"),d=h.match(O)||[];return o+d.map((_,$)=>_===`
|
|
8
|
+
`?"":($>0?u:"")+_.trimEnd()).join(`
|
|
9
|
+
`)}};M.Help=V});var F=C(q=>{"use strict";var{InvalidArgumentError:ne}=b(),k=class{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let i=re(e);this.short=i.shortFlag,this.long=i.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;return typeof e=="string"&&(t={[e]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t===this.defaultValue||!Array.isArray(t)?[e]:t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,i)=>{if(!this.argChoices.includes(t))throw new ne(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(t,i):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return se(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},P=class{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i)})}valueFromOption(e,t){let i=t.attributeName();if(!this.dualOptions.has(i))return!0;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:!1;return t.negate===(s===e)}};function se(l){return l.split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}function re(l){let e,t,i=l.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(e=i.shift()),t=i.shift(),!e&&/^-[^-]$/.test(t)&&(e=t,t=void 0),{shortFlag:e,longFlag:t}}q.Option=k;q.DualOptions=P});var U=C(j=>{"use strict";function oe(l,e){if(Math.abs(l.length-e.length)>3)return Math.max(l.length,e.length);let t=[];for(let i=0;i<=l.length;i++)t[i]=[i];for(let i=0;i<=e.length;i++)t[0][i]=i;for(let i=1;i<=e.length;i++)for(let n=1;n<=l.length;n++){let s=1;l[n-1]===e[i-1]?s=0:s=1,t[n][i]=Math.min(t[n-1][i]+1,t[n][i-1]+1,t[n-1][i-1]+s),n>1&&i>1&&l[n-1]===e[i-2]&&l[n-2]===e[i-1]&&(t[n][i]=Math.min(t[n][i],t[n-2][i-2]+1))}return t[l.length][e.length]}function ae(l,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));let t=l.startsWith("--");t&&(l=l.slice(2),e=e.map(r=>r.slice(2)));let i=[],n=3,s=.4;return e.forEach(r=>{if(r.length<=1)return;let a=oe(l,r),o=Math.max(l.length,r.length);(o-a)/o>s&&(a<n?(n=a,i=[r]):a===n&&i.push(r))}),i.sort((r,a)=>r.localeCompare(a)),t&&(i=i.map(r=>`--${r}`)),i.length>1?`
|
|
10
|
+
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
|
|
11
|
+
(Did you mean ${i[0]}?)`:""}j.suggestSimilar=ae});var J=C(B=>{"use strict";var he=A("events").EventEmitter,T=A("child_process"),g=A("path"),D=A("fs"),m=A("process"),{Argument:ue,humanReadableArgName:le}=E(),{CommanderError:N}=b(),{Help:ce}=S(),{Option:L,DualOptions:me}=F(),{suggestSimilar:G}=U(),I=class l extends he{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:t=>m.stdout.write(t),writeErr:t=>m.stderr.write(t),getOutHelpWidth:()=>m.stdout.isTTY?m.stdout.columns:void 0,getErrHelpWidth:()=>m.stderr.isTTY?m.stderr.columns:void 0,outputError:(t,i)=>i(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,i){let n=t,s=i;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,r,a]=e.match(/([^ ]+) *(.*)/),o=this.createCommand(r);return n&&(o.description(n),o._executableHandler=!0),s.isDefault&&(this._defaultCommandName=o._name),o._hidden=!!(s.noHelp||s.hidden),o._executableFile=s.executableFile||null,a&&o.arguments(a),this._registerCommand(o),o.parent=this,o.copyInheritedSettings(this),n?this:o}createCommand(e){return new l(e)}createHelp(){return Object.assign(new ce,this.configureHelp())}configureHelp(e){return e===void 0?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return e===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}showHelpAfterError(e=!0){return typeof e!="string"&&(e=!!e),this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw new Error(`Command passed to .addCommand() must have a name
|
|
12
|
+
- specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new ue(e,t)}argument(e,t,i,n){let s=this.createArgument(e,t);return typeof i=="function"?s.default(n).argParser(i):s.default(i),this.addArgument(s),this}arguments(e){return e.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e=="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,i,n]=e.match(/([^ ]+) *(.*)/),s=t??"display help for command",r=this.createCommand(i);return r.helpOption(!1),n&&r.arguments(n),s&&r.description(s),this._addImplicitHelpCommand=!0,this._helpCommand=r,this}addHelpCommand(e,t){return typeof e!="object"?(this.helpCommand(e,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=e,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(e,t){let i=["preSubcommand","preAction","postAction"];if(!i.includes(e))throw new Error(`Unexpected value for event passed to hook : '${e}'.
|
|
13
|
+
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[e]?this._lifeCycleHooks[e].push(t):this._lifeCycleHooks[e]=[t],this}exitOverride(e){return e?this._exitCallback=e:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(e,t,i){this._exitCallback&&this._exitCallback(new N(e,t,i)),m.exit(e)}action(e){let t=i=>{let n=this.registeredArguments.length,s=i.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=t,this}createOption(e,t){return new L(e,t)}_callParseArg(e,t,i,n){try{return e.parseArg(t,i)}catch(s){if(s.code==="commander.invalidArgument"){let r=`${n} ${s.message}`;this.error(r,{exitCode:s.exitCode,code:s.code})}throw s}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let i=e.long&&this._findOption(e.long)?e.long:e.short;throw new Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'
|
|
14
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=n=>[n.name()].concat(n.aliases()),i=t(e).find(n=>this._findCommand(n));if(i){let n=t(this._findCommand(i)).join("|"),s=t(e).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),i=e.attributeName();if(e.negate){let s=e.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(i,e.defaultValue===void 0?!0:e.defaultValue,"default")}else e.defaultValue!==void 0&&this.setOptionValueWithSource(i,e.defaultValue,"default");let n=(s,r,a)=>{s==null&&e.presetArg!==void 0&&(s=e.presetArg);let o=this.getOptionValue(i);s!==null&&e.parseArg?s=this._callParseArg(e,s,o,r):s!==null&&e.variadic&&(s=e._concatValue(s,o)),s==null&&(e.negate?s=!1:e.isBoolean()||e.optional?s=!0:s=""),this.setOptionValueWithSource(i,s,a)};return this.on("option:"+t,s=>{let r=`error: option '${e.flags}' argument '${s}' is invalid.`;n(s,r,"cli")}),e.envVar&&this.on("optionEnv:"+t,s=>{let r=`error: option '${e.flags}' value '${s}' from env '${e.envVar}' is invalid.`;n(s,r,"env")}),this}_optionEx(e,t,i,n,s){if(typeof t=="object"&&t instanceof L)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(t,i);if(r.makeOptionMandatory(!!e.mandatory),typeof n=="function")r.default(s).argParser(n);else if(n instanceof RegExp){let a=n;n=(o,h)=>{let u=a.exec(o);return u?u[0]:h},r.default(s).argParser(n)}else r.default(n);return this.addOption(r)}option(e,t,i,n){return this._optionEx({},e,t,i,n)}requiredOption(e,t,i,n){return this._optionEx({mandatory:!0},e,t,i,n)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,i){return this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t,this._optionValueSources[e]=i,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(e)!==void 0&&(t=i.getOptionValueSource(e))}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){m.versions?.electron&&(t.from="electron");let n=m.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(t.from="eval")}e===void 0&&(e=m.argv),this.rawArgs=e.slice();let i;switch(t.from){case void 0:case"node":this._scriptPath=e[1],i=e.slice(2);break;case"electron":m.defaultApp?(this._scriptPath=e[1],i=e.slice(2)):i=e.slice(1);break;case"user":i=e.slice(0);break;case"eval":i=e.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(e,t){let i=this._prepareUserArgs(e,t);return this._parseCommand([],i),this}async parseAsync(e,t){let i=this._prepareUserArgs(e,t);return await this._parseCommand([],i),this}_executeSubCommand(e,t){t=t.slice();let i=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,c){let p=g.resolve(u,c);if(D.existsSync(p))return p;if(n.includes(g.extname(c)))return;let O=n.find(d=>D.existsSync(`${p}${d}`));if(O)return`${p}${O}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=D.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=g.resolve(g.dirname(u),a)}if(a){let u=s(a,r);if(!u&&!e._executableFile&&this._scriptPath){let c=g.basename(this._scriptPath,g.extname(this._scriptPath));c!==this._name&&(u=s(a,`${c}-${e._name}`))}r=u||r}i=n.includes(g.extname(r));let o;m.platform!=="win32"?i?(t.unshift(r),t=R(m.execArgv).concat(t),o=T.spawn(m.argv[0],t,{stdio:"inherit"})):o=T.spawn(r,t,{stdio:"inherit"}):(t.unshift(r),t=R(m.execArgv).concat(t),o=T.spawn(m.execPath,t,{stdio:"inherit"})),o.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(c=>{m.on(c,()=>{o.killed===!1&&o.exitCode===null&&o.kill(c)})});let h=this._exitCallback;o.on("close",u=>{u=u??1,h?h(new N(u,"commander.executeSubCommandAsync","(close)")):m.exit(u)}),o.on("error",u=>{if(u.code==="ENOENT"){let c=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",p=`'${r}' does not exist
|
|
15
|
+
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
16
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
17
|
+
- ${c}`;throw new Error(p)}else if(u.code==="EACCES")throw new Error(`'${r}' not executable`);if(!h)m.exit(1);else{let c=new N(1,"commander.executeSubCommandAsync","(error)");c.nestedError=u,h(c)}}),this.runningCommand=o}_dispatchSubcommand(e,t,i){let n=this._findCommand(e);n||this.help({error:!0});let s;return s=this._chainOrCallSubCommandHook(s,n,"preSubcommand"),s=this._chainOrCall(s,()=>{if(n._executableHandler)this._executeSubCommand(n,t.concat(i));else return n._parseCommand(t,i)}),s}_dispatchHelpCommand(e){e||this.help();let t=this._findCommand(e);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((e,t)=>{e.required&&this.args[t]==null&&this.missingArgument(e.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let e=(i,n,s)=>{let r=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;r=this._callParseArg(i,n,s,a)}return r};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce((r,a)=>e(i,a,r),i.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=e(i,s,i.defaultValue))),t[n]=s}),this.processedArgs=t}_chainOrCall(e,t){return e&&e.then&&typeof e.then=="function"?e.then(()=>t()):t()}_chainOrCallHooks(e,t){let i=e,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[t]!==void 0).forEach(s=>{s._lifeCycleHooks[t].forEach(r=>{n.push({hookedCommand:s,callback:r})})}),t==="postAction"&&n.reverse(),n.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this))}),i}_chainOrCallSubCommandHook(e,t,i){let n=e;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{n=this._chainOrCall(n,()=>s(this,t))}),n}_parseCommand(e,t){let i=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(i.operands),t=i.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0])},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(s,e,t)})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent&&this.parent.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(e=>{e.options.forEach(t=>{t.mandatory&&e.getOptionValue(t.attributeName())===void 0&&e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});e.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=e.find(s=>i.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(i,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(e=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],i=[],n=t,s=e.slice();function r(o){return o.length>1&&o[0]==="-"}let a=null;for(;s.length;){let o=s.shift();if(o==="--"){n===i&&n.push(o),n.push(...s);break}if(a&&!r(o)){this.emit(`option:${a.name()}`,o);continue}if(a=null,r(o)){let h=this._findOption(o);if(h){if(h.required){let u=s.shift();u===void 0&&this.optionMissingArgument(h),this.emit(`option:${h.name()}`,u)}else if(h.optional){let u=null;s.length>0&&!r(s[0])&&(u=s.shift()),this.emit(`option:${h.name()}`,u)}else this.emit(`option:${h.name()}`);a=h.variadic?h:null;continue}}if(o.length>2&&o[0]==="-"&&o[1]!=="-"){let h=this._findOption(`-${o[1]}`);if(h){h.required||h.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${h.name()}`,o.slice(2)):(this.emit(`option:${h.name()}`),s.unshift(`-${o.slice(2)}`));continue}}if(/^--[^=]+=/.test(o)){let h=o.indexOf("="),u=this._findOption(o.slice(0,h));if(u&&(u.required||u.optional)){this.emit(`option:${u.name()}`,o.slice(h+1));continue}}if(r(o)&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&i.length===0){if(this._findCommand(o)){t.push(o),s.length>0&&i.push(...s);break}else if(this._getHelpCommand()&&o===this._getHelpCommand().name()){t.push(o),s.length>0&&t.push(...s);break}else if(this._defaultCommandName){i.push(o),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){n.push(o),s.length>0&&n.push(...s);break}n.push(o)}return{operands:t,unknown:i}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let i=0;i<t;i++){let n=this.options[i].attributeName();e[n]=n===this._versionOptionName?this._version:this[n]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){this._outputConfiguration.outputError(`${e}
|
|
18
|
+
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
19
|
+
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
|
|
20
|
+
`),this.outputHelp({error:!0}));let i=t||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,e)}_parseOptionsEnv(){this.options.forEach(e=>{if(e.envVar&&e.envVar in m.env){let t=e.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,m.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new me(this.options),t=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&t(i.attributeName())&&e.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!t(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let i=r=>{let a=r.attributeName(),o=this.getOptionValue(a),h=this.options.find(c=>c.negate&&a===c.attributeName()),u=this.options.find(c=>!c.negate&&a===c.attributeName());return h&&(h.presetArg===void 0&&o===!1||h.presetArg!==void 0&&o===h.presetArg)?h:u||r},n=r=>{let a=i(r),o=a.attributeName();return this.getOptionValueSource(o)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(e)} cannot be used with ${n(t)}`;this.error(s,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let r=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(r),s=s.parent}while(s&&!s._enablePositionalOptions);t=G(e,n)}let i=`error: unknown option '${e}'${t}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,i=t===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${i} but got ${e.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias())}),t=G(e,n)}let i=`error: unknown command '${e}'${t}`;this.error(i,{code:"commander.unknownCommand"})}version(e,t,i){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",i=i||"output the version number";let n=this.createOption(t,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
21
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){return e===void 0&&t===void 0?this._description:(this._description=e,t&&(this._argsDescription=t),this)}summary(e){return e===void 0?this._summary:(this._summary=e,this)}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(e);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${n}'`)}return t._aliases.push(e),this}aliases(e){return e===void 0?this._aliases:(e.forEach(t=>this.alias(t)),this)}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(i=>le(i));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){return e===void 0?this._name:(this._name=e,this)}nameFromFilename(e){return this._name=g.basename(e,g.extname(e)),this}executableDir(e){return e===void 0?this._executableDir:(this._executableDir=e,this)}helpInformation(e){let t=this.createHelp();return t.helpWidth===void 0&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},i;return t.error?i=n=>this._outputConfiguration.writeErr(n):i=n=>this._outputConfiguration.writeOut(n),t.write=e.write||i,t.command=this,t}outputHelp(e){let t;typeof e=="function"&&(t=e,e=void 0);let i=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach(s=>s.emit("beforeAllHelp",i)),this.emit("beforeHelp",i);let n=this.helpInformation(i);if(t&&(n=t(n),typeof n!="string"&&!Buffer.isBuffer(n)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(n),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",i),this._getCommandAndAncestors().forEach(s=>s.emit("afterAllHelp",i))}helpOption(e,t){return typeof e=="boolean"?(e?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=m.exitCode||0;t===0&&e&&typeof e!="function"&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let i=["beforeAll","before","after","afterAll"];if(!i.includes(e))throw new Error(`Unexpected value for position to addHelpText.
|
|
22
|
+
Expecting one of '${i.join("', '")}'`);let n=`${e}Help`;return this.on(n,s=>{let r;typeof t=="function"?r=t({error:s.error,command:s.command}):r=t,r&&s.write(`${r}
|
|
23
|
+
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();t&&e.find(n=>t.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function R(l){return l.map(e=>{if(!e.startsWith("--inspect"))return e;let t,i="127.0.0.1",n="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?t=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=s[1],i=s[3],n=s[4]),t&&n!=="0"?`${t}=${i}:${parseInt(n)+1}`:e})}B.Command=I});var Q=C(f=>{"use strict";var{Argument:K}=E(),{Command:W}=J(),{CommanderError:de,InvalidArgumentError:z}=b(),{Help:pe}=S(),{Option:Y}=F();f.program=new W;f.createCommand=l=>new W(l);f.createOption=(l,e)=>new Y(l,e);f.createArgument=(l,e)=>new K(l,e);f.Command=W;f.Option=Y;f.Argument=K;f.Help=pe;f.CommanderError=de;f.InvalidArgumentError=z;f.InvalidOptionArgumentError=z});var X=Z(Q(),1),{program:we,createCommand:Ee,createArgument:$e,createOption:xe,CommanderError:He,InvalidArgumentError:ve,InvalidOptionArgumentError:ye,Command:Ve,Argument:Se,Option:ke,Help:Pe}=X.default;export{He as a,ve as b,Ve as c,ke as d};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
import{b as y}from"./chunk-WD52ZNQY.js";import{b as l,d,e as m,g,h as S}from"./chunk-
|
|
2
|
+
import{b as y}from"./chunk-WD52ZNQY.js";import{b as l,d,e as m,g,h as S}from"./chunk-KN65CUNT.js";import{a as f}from"./chunk-O5AS2ZIX.js";import{r as u,s as p}from"./chunk-RSSOJ3L2.js";import{existsSync as s,mkdirSync as h,readFileSync as C,renameSync as w,writeFileSync as R}from"fs";import{join as x}from"path";function G(e){y(l(e));let r=l(e);if(!s(r))return;let n=x(r,"meta.json"),o=m(e);if(s(n)&&!s(o))try{h(d(e),{recursive:!0}),w(n,o)}catch(t){process.stderr.write(`warn: meta.json migration failed: ${t.message}
|
|
3
3
|
`)}let a=S(e);if(s(a)){let t="python";try{let i=new f().load();i.code_export?.language&&(t=i.code_export.language)}catch{}let c=g(e,"playwright",t);if(!s(c))try{w(a,c)}catch(i){process.stderr.write(`warn: generated-code migration failed: ${i.message}
|
|
4
4
|
`)}}if(s(o))try{let t=JSON.parse(C(o,"utf8"));"md5sum"in t&&(delete t.md5sum,R(o,JSON.stringify(t,null,2)+`
|
|
5
5
|
`,"utf8"))}catch(t){process.stderr.write(`warn: meta.json md5sum strip failed: ${t.message}
|
|
6
|
-
`)}}async function O(e){if(!e.isInteractive)return{recovered:!1};if(E(e.creds))return{recovered:!1};let{SingleShotApp:r}=await import("./SingleShotApp-
|
|
6
|
+
`)}}async function O(e){if(!e.isInteractive)return{recovered:!1};if(E(e.creds))return{recovered:!1};let{SingleShotApp:r}=await import("./SingleShotApp-U54ETXS3.js"),{ScrollbackProvider:n}=await import("./scrollback-JLPJR25X.js"),{render:o}=await import("./build-JIKYOZUH.js"),a=await import("./react-QWOAB3TB.js"),t={current:null},c={current:!1},{waitUntilExit:i,unmount:v}=o(a.default.createElement(n,null,a.default.createElement(r,{resultRef:t,mode:"login",loginCompleteRef:c})),{exitOnCtrlC:!1});p(()=>v()),await i();try{process.stdin.setRawMode?.(!1)}catch{}return process.stdout.write("\x1B[?25h"),c.current?{recovered:!0}:(u(0,"Startup gate cancelled"),{recovered:!1})}function E(e){let r=e.getActiveProfile(),n=e.getDefaultEnv();if(!r||!!!(e.loadBasicAuth(r,n)||e.loadCredentials(r,n)))return!1;let a=e.loadProfileConfig(r,n)??{};return!!a.project_id&&!!a.folder_id}export{G as a,O as b};
|