gerege-cli 0.26.6 → 0.26.8
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/bundled/gerege-video/SKILL.md +22 -0
- package/bundled/gerege-video/scripts/video.js +137 -0
- package/chunks/{MaxSizedBox-QCIXIS4P.js → MaxSizedBox-LUINLOQW.js} +1 -1
- package/chunks/{StandaloneSessionPicker-BAFAIRT7.js → StandaloneSessionPicker-B7N4QO5D.js} +1 -1
- package/chunks/{acp-subagent-executor-TPVXURLW.js → acp-subagent-executor-J6H6FKUT.js} +1 -1
- package/chunks/{acpAgent-67UN66PB.js → acpAgent-XG6SM2VU.js} +3 -3
- package/chunks/{advisor-SAXMI4QZ.js → advisor-SZVPQNPA.js} +1 -1
- package/chunks/{agent-KV7BXY6C.js → agent-N7QF7BJS.js} +1 -1
- package/chunks/{agent-headless-FQX3JGG6.js → agent-headless-GLP5GUEX.js} +1 -1
- package/chunks/{agent-host-client-L5EHC4AC.js → agent-host-client-H4VOB3M6.js} +1 -1
- package/chunks/{agent-host-connections-EDBMCVQF.js → agent-host-connections-E4C3OC4M.js} +1 -1
- package/chunks/{anthropicContentGenerator-V7TX2NXP.js → anthropicContentGenerator-5VTWQLT5.js} +1 -1
- package/chunks/{autofix-pr-WP34NYHL.js → autofix-pr-HDYQDJS4.js} +1 -1
- package/chunks/{batch-XFVQ4BLM.js → batch-3CRVN5VJ.js} +1 -1
- package/chunks/{bridge-AE7AFEXB.js → bridge-NZ6WVBLQ.js} +1 -1
- package/chunks/{channel-settings-store-X63P5OVT.js → channel-settings-store-Z7I2JI6M.js} +1 -1
- package/chunks/{chunk-BCI62WSL.js → chunk-236DHGNH.js} +1 -1
- package/chunks/{chunk-JRTOPEM3.js → chunk-2M3ND5WN.js} +1 -1
- package/chunks/{chunk-LBLLWAKK.js → chunk-36A6EXHB.js} +1 -1
- package/chunks/{chunk-H3IR3GIE.js → chunk-3ANIQTDT.js} +1 -1
- package/chunks/{chunk-GSPGIGO5.js → chunk-3QTR2HAE.js} +3 -3
- package/chunks/{chunk-32XHDDIA.js → chunk-3TTHYXT3.js} +1 -1
- package/chunks/{chunk-MTDBCIDA.js → chunk-4CE4GMDL.js} +1 -1
- package/chunks/{chunk-T2YTHAJW.js → chunk-4FVT657Y.js} +1 -1
- package/chunks/{chunk-CGDFZEER.js → chunk-4HSISRRA.js} +1 -1
- package/chunks/{chunk-7453BHJO.js → chunk-4SZUJ5RT.js} +1 -1
- package/chunks/{chunk-B37YY4XU.js → chunk-57D2OB3I.js} +1 -1
- package/chunks/{chunk-WGFX3EL3.js → chunk-5FGBLIXB.js} +1 -1
- package/chunks/{chunk-I6PUY2T3.js → chunk-5HX2QGVR.js} +1 -1
- package/chunks/{chunk-BPFFRPWE.js → chunk-5ZNXAWOG.js} +6 -6
- package/chunks/{chunk-BHIDG6VZ.js → chunk-6CKX56LJ.js} +1 -1
- package/chunks/{chunk-GRAECADD.js → chunk-6NIQFWXP.js} +1 -1
- package/chunks/{chunk-ELDZ4MNL.js → chunk-6PC6MZHL.js} +1 -1
- package/chunks/{chunk-FEP6W4NJ.js → chunk-6VQKGKMJ.js} +1 -1
- package/chunks/{chunk-GBSRWT7J.js → chunk-6ZEMLEK2.js} +1 -1
- package/chunks/{chunk-4NDJKNN6.js → chunk-72VY2PJA.js} +1 -1
- package/chunks/{chunk-BAUMVH4Q.js → chunk-75I3NYBD.js} +1 -1
- package/chunks/{chunk-YH2XRWRF.js → chunk-76L7ZDEK.js} +1 -1
- package/chunks/{chunk-2JGTWRZJ.js → chunk-7XQ5D34E.js} +6 -6
- package/chunks/{chunk-DA6LOBSB.js → chunk-AYX75VXG.js} +1 -1
- package/chunks/{chunk-G6DALGGS.js → chunk-BBDFEMCF.js} +1 -1
- package/chunks/{chunk-VD2GSW64.js → chunk-BOTX7S66.js} +1 -1
- package/chunks/{chunk-M6KB5RVD.js → chunk-CY2QKKZA.js} +1 -1
- package/chunks/{chunk-HTAUIJB4.js → chunk-D5JWQUID.js} +1 -1
- package/chunks/{chunk-P3JEEDQZ.js → chunk-DMIPB7RZ.js} +1 -1
- package/chunks/{chunk-CF6SZJNP.js → chunk-DSKA3P2C.js} +1 -1
- package/chunks/{chunk-LTE4N6L3.js → chunk-DVC65H4X.js} +1 -1
- package/chunks/{chunk-W5Z4BWWA.js → chunk-DVJSDCMX.js} +1 -1
- package/chunks/{chunk-65ME4BOH.js → chunk-E6CPFQX2.js} +1 -1
- package/chunks/{chunk-JEDL4IKF.js → chunk-EIFBGEXJ.js} +1 -1
- package/chunks/{chunk-AYVCT5FF.js → chunk-EQOHDAYU.js} +1 -1
- package/chunks/{chunk-2TAJ5STJ.js → chunk-EZPM4DLR.js} +1 -1
- package/chunks/{chunk-JWNKPINR.js → chunk-F6U6T7QD.js} +1 -1
- package/chunks/{chunk-ET5M5WFN.js → chunk-FCGFBUHS.js} +1 -1
- package/chunks/{chunk-OU7CEG7Q.js → chunk-G2LTZU67.js} +1 -1
- package/chunks/{chunk-2N3NBTYJ.js → chunk-GMJSEK4V.js} +1 -1
- package/chunks/{chunk-NA4ZF2FE.js → chunk-HJMUBVXZ.js} +2 -2
- package/chunks/{chunk-AFO5ER23.js → chunk-HQZTAA2U.js} +1 -1
- package/chunks/{chunk-OK7LBM5G.js → chunk-I63TIQOI.js} +1 -1
- package/chunks/{chunk-OJ4K62S2.js → chunk-I65LBJN7.js} +1 -1
- package/chunks/{chunk-GHIFIXNX.js → chunk-IBDOC27R.js} +1 -1
- package/chunks/{chunk-2LWJGXTW.js → chunk-IKF2HWEV.js} +1 -1
- package/chunks/{chunk-AEZYXPFS.js → chunk-K6NS2HXT.js} +1 -1
- package/chunks/{chunk-T5DKF33F.js → chunk-KTRNYPQP.js} +1 -1
- package/chunks/{chunk-SKGJ26HQ.js → chunk-L3ANU5JZ.js} +1 -1
- package/chunks/{chunk-U3Q72OGV.js → chunk-LKPMADUO.js} +1 -1
- package/chunks/{chunk-MYV7GY3H.js → chunk-M56Y2B6N.js} +1 -1
- package/chunks/{chunk-34HC2AXI.js → chunk-N5KRBAK5.js} +2 -2
- package/chunks/{chunk-EXIFPXMB.js → chunk-NA2WJPOU.js} +1 -1
- package/chunks/{chunk-7RNOS7R4.js → chunk-NGOWLXYK.js} +1 -1
- package/chunks/{chunk-IZ5MWA6E.js → chunk-NL7P73ZP.js} +1 -1
- package/chunks/{chunk-FYBJGRX7.js → chunk-NS3QR7D3.js} +1 -1
- package/chunks/{chunk-XISR37DQ.js → chunk-O5JCCBMQ.js} +1 -1
- package/chunks/{chunk-FKL3V5BO.js → chunk-OOKFFZHF.js} +1 -1
- package/chunks/{chunk-VRKYBH5G.js → chunk-OTYPLLMT.js} +5 -5
- package/chunks/{chunk-W66WWTOP.js → chunk-P7NHWX27.js} +1 -1
- package/chunks/{chunk-AEKEZRIU.js → chunk-PC5QZUKR.js} +1 -1
- package/chunks/{chunk-NEKPQLFY.js → chunk-PS7MQL57.js} +2 -2
- package/chunks/{chunk-TB4AUC2L.js → chunk-PXWHOFAA.js} +1 -1
- package/chunks/{chunk-OOJ2AQT3.js → chunk-Q65LVCDR.js} +1 -1
- package/chunks/{chunk-EFIRES46.js → chunk-QDUDLELH.js} +1 -1
- package/chunks/{chunk-KZNYALFU.js → chunk-QF22ILPV.js} +1 -1
- package/chunks/{chunk-MGATL4OA.js → chunk-QW7MAG2E.js} +1 -1
- package/chunks/{chunk-KJGRCIVY.js → chunk-RXK6XD6F.js} +1 -1
- package/chunks/{chunk-W2RQIZ6B.js → chunk-SVDFCWS7.js} +1 -1
- package/chunks/{chunk-P62S5JGM.js → chunk-TKP3GAUI.js} +1 -1
- package/chunks/{chunk-BQZF3UKI.js → chunk-TUS74LFI.js} +1 -1
- package/chunks/{chunk-JH3V5SPA.js → chunk-U7YGHPSL.js} +1 -1
- package/chunks/{chunk-NONBHCXP.js → chunk-UB37RBSK.js} +1 -1
- package/chunks/{chunk-T53VMDXH.js → chunk-UK5SIRH4.js} +1 -1
- package/chunks/{chunk-3W32X2DH.js → chunk-UTTSBCFR.js} +1 -1
- package/chunks/{chunk-RSLTOIG5.js → chunk-UYV4ZVXY.js} +2 -2
- package/chunks/{chunk-FKZ46GKL.js → chunk-VC3JJL7E.js} +1 -1
- package/chunks/{chunk-SP6CQ3MO.js → chunk-VKWVIWLK.js} +1 -1
- package/chunks/{chunk-N7PWZBXV.js → chunk-VUI6STKU.js} +1 -1
- package/chunks/{chunk-5EXL4TKQ.js → chunk-W3YXE55M.js} +1 -1
- package/chunks/{chunk-NVOI6UDQ.js → chunk-WAIPC47V.js} +1 -1
- package/chunks/{chunk-QDCUR3JB.js → chunk-WMJ6UHDP.js} +1 -1
- package/chunks/{chunk-CBE6ZIHU.js → chunk-WZU2ECUD.js} +1 -1
- package/chunks/{chunk-ZENMAISJ.js → chunk-XAGIZY2Y.js} +1 -1
- package/chunks/{chunk-RXN7DUMP.js → chunk-XGZYVULJ.js} +2 -2
- package/chunks/{chunk-HOG66S6K.js → chunk-XJIHDVPX.js} +1 -1
- package/chunks/{chunk-UKLXKJKL.js → chunk-XVDIHFRH.js} +1 -1
- package/chunks/{chunk-76FSYQTG.js → chunk-YMEW4TTT.js} +1 -1
- package/chunks/{chunk-EYPLBTMI.js → chunk-Z32URWBG.js} +1 -1
- package/chunks/{chunk-CUP2TNJK.js → chunk-Z6HRXHJP.js} +1 -1
- package/chunks/{chunk-MPVQDYPH.js → chunk-ZO4F6ZWR.js} +1 -1
- package/chunks/{codex-subagent-executor-OLMGVPVS.js → codex-subagent-executor-DDKYNU42.js} +1 -1
- package/chunks/{config-utils-OWY5G5Y2.js → config-utils-S7Z2ZZ2E.js} +1 -1
- package/chunks/{contextCommand-IXFUZH65.js → contextCommand-7F4PGV2A.js} +1 -1
- package/chunks/{core-runtime-O4LC4NY3.js → core-runtime-LBH3U7ZF.js} +1 -1
- package/chunks/{create-sub-session-6F7C3TMT.js → create-sub-session-56DS2T6L.js} +1 -1
- package/chunks/{cron-create-2422NBSJ.js → cron-create-PBP3C46Q.js} +1 -1
- package/chunks/{daemon-git-worktree-guard-EWPQA6NO.js → daemon-git-worktree-guard-WJS6FBDA.js} +1 -1
- package/chunks/{daemon-status-provider-FAHOXNFW.js → daemon-status-provider-UPPAEHJ6.js} +1 -1
- package/chunks/{daemon-trust-policy-L3DM6AI5.js → daemon-trust-policy-4Z5HSNUX.js} +1 -1
- package/chunks/{daemon-trust-policy-monitor-HNPY5KJ4.js → daemon-trust-policy-monitor-WFWDOYX3.js} +1 -1
- package/chunks/{deferred-core-runtime-JF42NQJK.js → deferred-core-runtime-MJYNEA4N.js} +1 -1
- package/chunks/{edit-E5LEI2LL.js → edit-U7TGKKK3.js} +1 -1
- package/chunks/{enterPlanMode-3COTUV5V.js → enterPlanMode-27HC5AXN.js} +1 -1
- package/chunks/{environment-XBBIB3VA.js → environment-PHWY6C4P.js} +1 -1
- package/chunks/{errors-LNMQ7TUK.js → errors-F2EYYFI3.js} +1 -1
- package/chunks/{execution-tool-QDDKJD2K.js → execution-tool-O4KJ5SMM.js} +1 -1
- package/chunks/{execution-worker-TXGZRZXE.js → execution-worker-AMFXZ7JD.js} +1 -1
- package/chunks/{exitPlanMode-Z7QEMWPE.js → exitPlanMode-LDYL43PB.js} +1 -1
- package/chunks/{fast-path-M6K2RACY.js → fast-path-HTODEVOR.js} +1 -1
- package/chunks/{glob-N2QT4U7U.js → glob-NKQJJZND.js} +1 -1
- package/chunks/{goal-tools-CUSQD3DG.js → goal-tools-47I455VV.js} +1 -1
- package/chunks/{handleAutoUpdate-QF2YQHF6.js → handleAutoUpdate-MJKTDJUO.js} +1 -1
- package/chunks/{i18n-AGOA6MUI.js → i18n-TCOB4TC5.js} +1 -1
- package/chunks/{initializer-FRKYDUSX.js → initializer-NLYOGZZS.js} +1 -1
- package/chunks/{installationInfo-OKA4WXAS.js → installationInfo-TF2RSJOG.js} +1 -1
- package/chunks/{interactive-mod-session-MWYN5IFK.js → interactive-mod-session-5F7R3KSA.js} +1 -1
- package/chunks/{list-DE7VUIR2.js → list-U2AEVLFP.js} +1 -1
- package/chunks/{llm-N3JGJHYC.js → llm-EV2QTQBU.js} +4 -4
- package/chunks/{llm-content-generator-VMUBA7OJ.js → llm-content-generator-ZXUSPPG2.js} +1 -1
- package/chunks/{loadedSettingsAdapter-5C36OZ7N.js → loadedSettingsAdapter-TLRI22X7.js} +1 -1
- package/chunks/{local-BE624O3A.js → local-ZTSBSKWV.js} +1 -1
- package/chunks/{local-execution-environment-OPGM7Y6L.js → local-execution-environment-F263PSIM.js} +1 -1
- package/chunks/{loggingContentGenerator-2MHAI6JR.js → loggingContentGenerator-2XHSIJQD.js} +1 -1
- package/chunks/{loop-wakeup-BDLATBXH.js → loop-wakeup-5ET3JHUT.js} +1 -1
- package/chunks/{manage-memory-BBCEIIWB.js → manage-memory-MJEQ47H2.js} +1 -1
- package/chunks/{managed-execution-engine-SRFALTCX.js → managed-execution-engine-ODPR5OEH.js} +1 -1
- package/chunks/{managed-local-serve-ICNAS3E6.js → managed-local-serve-S5R4Z5OL.js} +1 -1
- package/chunks/managed-npm-update-BUI5APGY.js +8 -0
- package/chunks/{managed-runtime-attestation-worker-ZRDWKXCI.js → managed-runtime-attestation-worker-BQP4E7LQ.js} +1 -1
- package/chunks/{managed-runtime-bootstrap-6NTGZXQL.js → managed-runtime-bootstrap-SRBDFSKK.js} +1 -1
- package/chunks/{managed-runtime-session-worker-RKQBBFR6.js → managed-runtime-session-worker-UI23BTYJ.js} +1 -1
- package/chunks/{managed-runtime-ssh-worker-FCGV6FSW.js → managed-runtime-ssh-worker-HU4CIJRK.js} +1 -1
- package/chunks/{managed-session-authority-C7IW6TJX.js → managed-session-authority-XSSTLAEY.js} +1 -1
- package/chunks/{mcp-VC4CJPE5.js → mcp-WLHDOKP7.js} +1 -1
- package/chunks/{memory-S6OJA3ZD.js → memory-OUUHPSDD.js} +1 -1
- package/chunks/{model-call-collection-MJZWRQSU.js → model-call-collection-4A2EB76B.js} +1 -1
- package/chunks/{model-configuration-SKU6L3QI.js → model-configuration-4CGUFKEP.js} +1 -1
- package/chunks/{modelConfigUtils-TJCB6NXT.js → modelConfigUtils-HUEERWBA.js} +1 -1
- package/chunks/{monitor-M3PNLCYP.js → monitor-FXL5UNMP.js} +1 -1
- package/chunks/{nonInteractiveCli-MR7JLAWU.js → nonInteractiveCli-W7M2O43W.js} +1 -1
- package/chunks/{nonInteractiveToolExecutor-YKA6JMTY.js → nonInteractiveToolExecutor-EMLI363Q.js} +1 -1
- package/chunks/{notebook-edit-ENTFB5D7.js → notebook-edit-R5RSLSSH.js} +1 -1
- package/chunks/{omni-6YBX4R6K.js → omni-DNZGITTE.js} +1 -1
- package/chunks/{openaiContentGenerator-XRXX33FY.js → openaiContentGenerator-PKOPYMHR.js} +1 -1
- package/chunks/{openaiResponsesContentGenerator-L6ONEHMR.js → openaiResponsesContentGenerator-MHH2MF3V.js} +1 -1
- package/chunks/{pidfile-XR4JF2Z6.js → pidfile-5ZNJWMKG.js} +1 -1
- package/chunks/{processUtils-GQYNJRBJ.js → processUtils-JIHQDASW.js} +1 -1
- package/chunks/{prompt-terminal-ledger-7BM7YDLG.js → prompt-terminal-ledger-L3LZ5SLR.js} +1 -1
- package/chunks/{qwenContentGenerator-QSA32XEL.js → qwenContentGenerator-QCZL7HJJ.js} +1 -1
- package/chunks/{reactive-degrade-TFNBAAPZ.js → reactive-degrade-YUXOUQG4.js} +1 -1
- package/chunks/{read-file-VD7OFO2E.js → read-file-FBNU3AVX.js} +1 -1
- package/chunks/{resumeHistoryUtils-2B4KPI7G.js → resumeHistoryUtils-5FPRTI4A.js} +1 -1
- package/chunks/{review-C365WGCW.js → review-NLFYSNM3.js} +1 -1
- package/chunks/{ripGrep-D7WPMBXR.js → ripGrep-JUAPC5LD.js} +1 -1
- package/chunks/{run-qwen-serve-NZWQHWQA.js → run-qwen-serve-JP64UQ3Y.js} +1 -1
- package/chunks/{runtime-J6SPBSCS.js → runtime-D2QUYM6U.js} +1 -1
- package/chunks/{sandboxConfig-QS2XBPZG.js → sandboxConfig-7VZJQV6H.js} +1 -1
- package/chunks/{scheduled-tasks-YNNIOOPM.js → scheduled-tasks-PC6EH75E.js} +1 -1
- package/chunks/{scheduler-KCMSPHON.js → scheduler-RUV2FNDR.js} +1 -1
- package/chunks/{search-memory-EUBJ7IAV.js → search-memory-YJTJ7BRU.js} +1 -1
- package/chunks/{send-message-CWWZUPSK.js → send-message-EEEFFTHX.js} +1 -1
- package/chunks/{serve-4CB4BWJ5.js → serve-KMIZDYON.js} +1 -1
- package/chunks/{server-JNANUIGC.js → server-DUPK3V7B.js} +3 -3
- package/chunks/{session-3LQLXPUA.js → session-CW5YMFMP.js} +1 -1
- package/chunks/{session-attachments-root-BWIVWFHJ.js → session-attachments-root-5H5GFHLI.js} +1 -1
- package/chunks/{session-execution-engine-selector-5OLRX57L.js → session-execution-engine-selector-MVXM2HZW.js} +1 -1
- package/chunks/{session-pr-refresh-RLF3EXS3.js → session-pr-refresh-4UPONX4L.js} +1 -1
- package/chunks/{sessionService-U7ACD2HP.js → sessionService-GGCYISSL.js} +1 -1
- package/chunks/{settings-FTGWYTUH.js → settings-AASJCESS.js} +1 -1
- package/chunks/{shell-E4RENYQC.js → shell-V4WWLW3Q.js} +1 -1
- package/chunks/{skill-OLNPHRWB.js → skill-NDEBB7VX.js} +1 -1
- package/chunks/{skill-settings-R2BV2GEK.js → skill-settings-YAI3GYU5.js} +1 -1
- package/chunks/{spawnChannel-LOPAR5T2.js → spawnChannel-6JKVJAXZ.js} +1 -1
- package/chunks/{standalone-update-IGDX2RGN.js → standalone-update-NJP5OCKJ.js} +1 -1
- package/chunks/{start-opentui-ui-33QLBNRC.js → start-opentui-ui-M4B4SXRM.js} +1 -1
- package/chunks/{startInteractiveUI-RQKHD7MM.js → startInteractiveUI-O4JUDEAU.js} +1 -1
- package/chunks/{team-create-HAVKHNU5.js → team-create-NLJ7QBLD.js} +1 -1
- package/chunks/{team-plan-approval-7MCQX67C.js → team-plan-approval-XKYPVWNG.js} +1 -1
- package/chunks/{terminal-image-renderer-XT5JVEO6.js → terminal-image-renderer-47TD747D.js} +1 -1
- package/chunks/{theme-manager-DR5EYGLT.js → theme-manager-AANEBPLJ.js} +1 -1
- package/chunks/{tool-call-LZHZ5RVH.js → tool-call-ETH3LS7Y.js} +1 -1
- package/chunks/{tool-result-media-XCXCF4YC.js → tool-result-media-EFOEPAF2.js} +1 -1
- package/chunks/{tool-search-K6S3ON7M.js → tool-search-J3CF5PRN.js} +1 -1
- package/chunks/{total-session-admission-LGSS2VWS.js → total-session-admission-3DC52PLQ.js} +1 -1
- package/chunks/{trustedFolders-IIR2UZRL.js → trustedFolders-4KPWZZKB.js} +1 -1
- package/chunks/{update-relaunch-WVIFX5CN.js → update-relaunch-A67BS7QS.js} +1 -1
- package/chunks/{updateCheck-CMEWLLZJ.js → updateCheck-X623JRSY.js} +1 -1
- package/chunks/{upload-config-TCCFCNCD.js → upload-config-X2CR3F26.js} +1 -1
- package/chunks/{useAutoAcceptIndicator-5RTTH3OW.js → useAutoAcceptIndicator-INIOQGJH.js} +1 -1
- package/chunks/{validateNonInterActiveAuth-AO336KDX.js → validateNonInterActiveAuth-XJ2U5CLB.js} +1 -1
- package/chunks/{version-JYWKKMNP.js → version-MFHRMM7W.js} +1 -1
- package/chunks/{web-fetch-HWTAWXFM.js → web-fetch-3GEJ62DH.js} +1 -1
- package/chunks/{web-search-HAI5LW3G.js → web-search-WJZO3Q3A.js} +1 -1
- package/chunks/{workflow-BZ2YFGF6.js → workflow-ML7ITCMH.js} +1 -1
- package/chunks/{workflow-ancestor-trust-26TFXFPO.js → workflow-ancestor-trust-M3VFMS73.js} +1 -1
- package/chunks/{workspace-agents-DLI4JQJZ.js → workspace-agents-YFZMV7EF.js} +1 -1
- package/chunks/{workspace-providers-status-64C7DJZU.js → workspace-providers-status-3COKLBCI.js} +1 -1
- package/chunks/{workspace-recovery-worker-IFRT3KKP.js → workspace-recovery-worker-QURA3WFZ.js} +1 -1
- package/chunks/{workspace-registration-store-MYKJM2SK.js → workspace-registration-store-F3AGIOBW.js} +1 -1
- package/chunks/{workspace-registry-GZJRONAY.js → workspace-registry-QUBL3RW6.js} +1 -1
- package/chunks/{workspace-runtime-coordinator-44KW6HSN.js → workspace-runtime-coordinator-22TSDHXX.js} +1 -1
- package/chunks/{workspace-service-YHTSZYYD.js → workspace-service-UUENTHNO.js} +1 -1
- package/chunks/{workspace-skills-status-NEB62X24.js → workspace-skills-status-NNQQBBCJ.js} +1 -1
- package/chunks/{workspace-trust-reconciler-HZLOOZWM.js → workspace-trust-reconciler-3CMMNCGG.js} +1 -1
- package/chunks/{write-file-HD5LHXGL.js → write-file-DEAFIK4C.js} +1 -1
- package/chunks/{zoom-image-W4BMRC5T.js → zoom-image-YYO22PQG.js} +1 -1
- package/cli-entry.js +2 -3
- package/cli.js +2 -2
- package/execution-worker.js +1 -1
- package/export-transcript-document.js +1 -1
- package/gerege.mjs +11 -0
- package/package.json +2 -12
- package/chunks/managed-npm-update-CTL6LH5Z.js +0 -8
- package/opentui-assets/@opentui/core/assets/javascript/highlights.scm +0 -205
- package/opentui-assets/@opentui/core/assets/javascript/tree-sitter-javascript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown/highlights.scm +0 -150
- package/opentui-assets/@opentui/core/assets/markdown/injections.scm +0 -27
- package/opentui-assets/@opentui/core/assets/markdown/tree-sitter-markdown.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/markdown_inline/highlights.scm +0 -115
- package/opentui-assets/@opentui/core/assets/markdown_inline/tree-sitter-markdown_inline.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/typescript/highlights.scm +0 -604
- package/opentui-assets/@opentui/core/assets/typescript/tree-sitter-typescript.wasm +0 -0
- package/opentui-assets/@opentui/core/assets/zig/highlights.scm +0 -284
- package/opentui-assets/@opentui/core/assets/zig/tree-sitter-zig.wasm +0 -0
- package/opentui-assets/@opentui/core/parser.worker.js +0 -4566
- package/opentui-assets/@opentui/core-darwin-arm64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-darwin-x64/libopentui.dylib +0 -0
- package/opentui-assets/@opentui/core-linux-arm64/libopentui.so +0 -0
- package/opentui-assets/@opentui/core-linux-x64/libopentui.so +0 -0
- package/opentui-assets/web-tree-sitter/tree-sitter.wasm +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{sanitizeFilenameComponent}from"./chunk-2JGTWRZJ.js";import{Storage}from"./chunk-EPODBRBP.js";import{getProjectHash,isSubpath}from"./chunk-OKN3Z5C5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function safeTarget(target){if(/^[A-Za-z0-9._-]{55}~[0-9a-f]{8}$/.test(target))return target;const flat=target.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_");const stem=flat.replace(/^[._]+/,"")||"target";if(stem.length<=SAFE_TARGET_MAX)return stem;return`${stem.slice(0,SAFE_TARGET_MAX-9)}~${createHash("sha256").update(stem).digest("hex").slice(0,8)}`}__name(safeTarget,"safeTarget");var SAFE_TARGET_MAX=64;init_esbuild_shims();var CONTROL=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;var NEEDS_PRE_ESCAPE=/[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;function inertText(value,maxChars=200){const clipped=value.length>maxChars?value.slice(0,maxChars):value;const rendered=CONTROL.test(clipped)?JSON.stringify(clipped.replace(NEEDS_PRE_ESCAPE,c=>{const hex=c.codePointAt(0).toString(16).padStart(4,"0");return`\\u${hex}`})):clipped;return clipped.length<value.length?`${rendered}\u2026`:rendered}__name(inertText,"inertText");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,readdirSync as readdirSync3,realpathSync as realpathSync4,statSync as statSync3}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute3,join as join3,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";init_esbuild_shims();import{execFileSync,spawnSync as spawnSync2}from"node:child_process";init_esbuild_shims();import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,lstatSync,mkdirSync,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,rmSync,statSync as statSync2,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname,isAbsolute as isAbsolute2,join as join2,resolve,sep}from"node:path";init_esbuild_shims();import{existsSync,readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";init_esbuild_shims();var MAX_OLD_SPACE_FLAG="--max[-_]old[-_]space[-_]size";var HEAP_TOKEN_RE=new RegExp(`(?:^|\\s)${MAX_OLD_SPACE_FLAG}(?:=(\\d*)|\\s+(\\d+))?(?=\\s|$)`,"g");function heapFlagMb(options){let mb;for(const m of options.matchAll(HEAP_TOKEN_RE)){const value=m[1]||m[2];if(value)mb=Number(value)}return mb}__name(heapFlagMb,"heapFlagMb");function withoutHeapFlag(options){return options.replace(HEAP_TOKEN_RE,"").trim()}__name(withoutHeapFlag,"withoutHeapFlag");function raiseHeap(options,mb){if((heapFlagMb(options)??0)>=mb)return void 0;return`${withoutHeapFlag(options)} --max-old-space-size=${mb}`.trim()}__name(raiseHeap,"raiseHeap");var NPM_ENV_REF_RE=/(?<!\\)(\\*)\$\{([^${}]+)\}/g;function raiseNpmHeap(options,mb){return raiseHeap(options,mb)?.replace(NPM_ENV_REF_RE,(_,esc,name)=>`${esc}${esc}\\\${${name}}`)}__name(raiseNpmHeap,"raiseNpmHeap");var HEAP_BANNER_RE=/^FATAL ERROR: [^\n]*JavaScript heap out of memory/m;function heapBannerIn(raw){return HEAP_BANNER_RE.test(raw)}__name(heapBannerIn,"heapBannerIn");function ranOutOfHeap(r){return r.exitCode!==0&&(r.heapExhausted??heapBannerIn(r.output))}__name(ranOutOfHeap,"ranOutOfHeap");function killedFromOutside(r){return!r.timedOut&&r.spawnError===void 0&&(r.exitCode===137||r.exitCode===null&&r.signal==="SIGKILL")}__name(killedFromOutside,"killedFromOutside");init_esbuild_shims();function stripComments(src){return src.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,m=>m.startsWith("/")?" ":m)}__name(stripComments,"stripComments");function isWorkspaceMember(filePath,workspaceGlobs){return workspaceDirFor(filePath,workspaceGlobs)!==null}__name(isWorkspaceMember,"isWorkspaceMember");function workspaceDirFor(filePath,workspaceGlobs){const norm=filePath.replace(/^\.\//,"");let owner=null;const previous=[];for(const glob of workspaceGlobs){const negated=glob.startsWith("!");const g=glob.replace(/^!/,"").replace(/^\.\//,"").replace(/\/$/,"");let dir=null;if(g.endsWith("/*")){const base=g.slice(0,-2);if(norm.startsWith(`${base}/`)){const seg=norm.slice(base.length+1).split("/")[0];if(seg)dir=`${base}/${seg}`}}else if(norm===g||norm.startsWith(`${g}/`)){dir=g}if(dir===null)continue;if(!negated){if(dir!==owner){previous.push(owner);owner=dir}}else if(dir===owner){owner=previous.pop()??null}}return owner}__name(workspaceDirFor,"workspaceDirFor");function isNegationExcluded(filePath,workspaceGlobs){if(workspaceDirFor(filePath,workspaceGlobs)!==null)return false;const positives=workspaceGlobs.filter(g=>!g.startsWith("!"));return workspaceDirFor(filePath,positives)!==null}__name(isNegationExcluded,"isNegationExcluded");function hasUnmodeledWorkspaceGlob(globs){return globs.some(glob=>{const g=glob.replace(/^!/,"").replace(/^\.\//,"");if(!g.includes("*"))return false;return!/^[^*]+\/\*$/.test(g)})}__name(hasUnmodeledWorkspaceGlob,"hasUnmodeledWorkspaceGlob");function readWorkspaceGlobs(root){try{const pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const ws=pkg.workspaces;const globs=Array.isArray(ws)?ws:Array.isArray(ws?.packages)?ws.packages:[];return globs.filter(g=>typeof g==="string")}catch{return[]}}__name(readWorkspaceGlobs,"readWorkspaceGlobs");function readRootPackage(root){let pkg;try{pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"))}catch{return null}if(pkg===null)return null;const scripts=Object.keys(pkg.scripts??{});if(!scripts.includes("build")&&!scripts.includes("test"))return null;const scriptsText={};for(const[k,v]of Object.entries(pkg.scripts??{})){if(typeof v==="string")scriptsText[k]=v}return{dir:".",name:typeof pkg.name==="string"&&pkg.name?pkg.name:"root",scripts,deps:declaredDeps(pkg),scriptsText}}__name(readRootPackage,"readRootPackage");function scriptFansOut(text){return typeof text==="string"&&(/(^|\s)(--workspaces|--?ws)(?=[\s'"`]|$)/.test(text)||/\bpnpm\s+(-r|--recursive)(?=[\s'"`]|$)/.test(text))}__name(scriptFansOut,"scriptFansOut");var COMMAND_SEPARATOR_RE=/[;&|\n]+/;function chainsCommands(text){return text.split(COMMAND_SEPARATOR_RE).filter(c=>c.trim()!=="").length>1}__name(chainsCommands,"chainsCommands");var NODE_VALUE_FLAGS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--env-file-if-exists","--input-type","--title","--redirect-warnings","--watch-path","--diagnostic-dir","--report-dir","--cpu-prof-dir","--heap-prof-dir","--icu-data-dir","--openssl-config"]);var SCRIPT_RUNNERS=new Set(["node","tsx"]);var NODE_INLINE_FLAGS=new Set(["-e","--eval","-p","--print","-"]);function nodeScripts(text){const files=[];for(const command of text.split(COMMAND_SEPARATOR_RE)){const words=command.trim().split(/\s+/);const runner=words.findIndex(w=>SCRIPT_RUNNERS.has(w));for(let i=runner+1;i>0&&i<words.length;i++){const word=words[i];if(NODE_INLINE_FLAGS.has(word))break;if(word.startsWith("-")){if(NODE_VALUE_FLAGS.has(word))i++;continue}if(/^[\w@./-]+\.[cm]?[jt]s$/.test(word))files.push(word);break}}return files}__name(nodeScripts,"nodeScripts");function childProcessCommands(src){const commands=[];for(const m of stripComments(src).matchAll(/\b(?:exec|execSync|execFile|execFileSync|spawn|spawnSync)\s*\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g)){commands.push(m[1].slice(1,-1))}return commands}__name(childProcessCommands,"childProcessCommands");var MAX_HAND_OFF_SCRIPT_BYTES=1024*1024;function rootBuildFanOutScript(root,text){if(typeof text!=="string")return void 0;for(const file of nodeScripts(text)){try{const path=realpathSync(join(root,file));const inRoot=relative(realpathSync(root),path);if(inRoot.startsWith("..")||isAbsolute(inRoot))continue;const stat=statSync(path);if(!stat.isFile()||stat.size>MAX_HAND_OFF_SCRIPT_BYTES)continue;if(childProcessCommands(readFileSync(path,"utf8")).some(scriptFansOut))return file}catch{}}return void 0}__name(rootBuildFanOutScript,"rootBuildFanOutScript");function declaredBuildHeapMb(root){const text=readRootPackage(root)?.scriptsText["build"];if(typeof text!=="string")return void 0;let declared;for(const m of text.matchAll(/\bNODE_OPTIONS=(?:"([^"]*)"|'([^']*)'|(\S*))/g)){const mb=heapFlagMb(m[1]??m[2]??m[3]??"");if(mb!==void 0)declared=Math.max(declared??0,mb)}return declared}__name(declaredBuildHeapMb,"declaredBuildHeapMb");function declaredDeps(pkg){return[...Object.keys(pkg.dependencies??{}),...Object.keys(pkg.devDependencies??{}),...Object.keys(pkg.peerDependencies??{}),...Object.keys(pkg.optionalDependencies??{})]}__name(declaredDeps,"declaredDeps");function workspaceDirCandidates(root,globs){const dirs=new Set;for(const glob of globs){if(glob.startsWith("!"))continue;const g=glob.replace(/^\.\//,"").replace(/\/$/,"");if(g.endsWith("/*")){const base=g.slice(0,-2);let entries;try{entries=readdirSync(join(root,base),{withFileTypes:true}).filter(e=>e.isDirectory()||e.isSymbolicLink()&&existsSync(join(root,base,e.name,"package.json"))).map(e=>e.name)}catch{continue}for(const e of entries)dirs.add(`${base}/${e}`)}else{dirs.add(g)}}return[...dirs].sort()}__name(workspaceDirCandidates,"workspaceDirCandidates");function readWorkspacePackages(root){const globs=readWorkspaceGlobs(root);const packages=[];const skipped=[];for(const dir of workspaceDirCandidates(root,globs)){const manifest=join(root,dir,"package.json");if(!existsSync(manifest))continue;if(workspaceDirFor(`${dir}/package.json`,globs)!==dir){const positives=globs.filter(g=>!g.startsWith("!"));if(workspaceDirFor(`${dir}/package.json`,positives)===dir)continue;skipped.push(dir);continue}let pkg;try{pkg=JSON.parse(readFileSync(manifest,"utf8"))}catch{skipped.push(dir);continue}if(pkg===null||typeof pkg.name!=="string"||!pkg.name){skipped.push(dir);continue}packages.push({dir,name:pkg.name,scripts:Object.keys(pkg.scripts??{}),deps:declaredDeps(pkg)})}packages.sort((a,b)=>a.dir.localeCompare(b.dir));skipped.sort();return{packages,skipped}}__name(readWorkspacePackages,"readWorkspacePackages");function affectedWorkspaces(changedFiles,workspaceGlobs){const dirs=new Set;for(const f of changedFiles){const d=workspaceDirFor(f,workspaceGlobs);if(d)dirs.add(d)}return[...dirs].sort()}__name(affectedWorkspaces,"affectedWorkspaces");function dependencyEdges(packages){const byName=new Map;for(const p of packages){if(p.dir!=="."||!byName.has(p.name))byName.set(p.name,p)}const dependsOn=new Map;for(const p of packages){dependsOn.set(p.dir,p.deps.map(d=>byName.get(d)?.dir).filter(d=>!!d&&d!==p.dir))}return dependsOn}__name(dependencyEdges,"dependencyEdges");function dependencyClosure(dirs,packages){const dependsOn=dependencyEdges(packages);const closure=new Set;const add=__name(dir=>{if(closure.has(dir))return;closure.add(dir);for(const d of dependsOn.get(dir)??[])add(d)},"add");dirs.forEach(add);return[...closure].sort()}__name(dependencyClosure,"dependencyClosure");function reverseDependencyClosure(affected,packages){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=new Set(affected.filter(a=>byDir.has(a)));let grew=true;while(grew){grew=false;for(const p of packages){if(consumers.has(p.dir))continue;if((dependsOn.get(p.dir)??[]).some(d=>consumers.has(d))){consumers.add(p.dir);grew=true}}}return[...consumers].sort()}__name(reverseDependencyClosure,"reverseDependencyClosure");function buildSetFor(affected,packages,alsoBuild=[]){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=reverseDependencyClosure(affected,packages);const wanted=new Set;const addDeps=__name(dir=>{if(wanted.has(dir))return;wanted.add(dir);for(const d of dependsOn.get(dir)??[])addDeps(d)},"addDeps");for(const c of consumers)addDeps(c);for(const extra of alsoBuild)if(byDir.has(extra))addDeps(extra);const order=[];const seen=new Set;const visit=__name(dir=>{if(seen.has(dir))return;seen.add(dir);for(const d of dependsOn.get(dir)??[]){if(wanted.has(d))visit(d)}order.push(dir)},"visit");for(const dir of alsoBuild.filter(d=>wanted.has(d)).sort())visit(dir);for(const dir of[...wanted].sort())visit(dir);return order}__name(buildSetFor,"buildSetFor");var GIT_ENV_REDIRECTS=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_COMMON_DIR"];var GIT_ENV_CONFIG=["GIT_CONFIG_COUNT","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_PARAMETERS","GIT_DEFAULT_HASH"];var GIT_ENV_EXEC=["GIT_SSH_COMMAND","GIT_SSH","GIT_EXEC_PATH","GIT_TEMPLATE_DIR","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_EDITOR","GIT_SEQUENCE_EDITOR","GIT_EXTERNAL_DIFF","XDG_CONFIG_HOME"];function mountRootFor(cwd){return mountRootVerdict(cwd).root}__name(mountRootFor,"mountRootFor");function mountNullKind(cwd){return mountRootVerdict(cwd).nullKind??"refused"}__name(mountNullKind,"mountNullKind");function mountRootVerdict(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).lastIndexOf(marker);if(at<0)return{root:null,nullKind:"outside"};const root=resolved.slice(0,at+marker.length-1);const outermost=outermostReviewTmpRoot(root);const bound=outermost===root?resolve(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync2(root);if(unmountableRootSpelling(real)){return{root:null,nullKind:"unmountable"}}return{root:real,nullKind:null}}catch{return{root:null,nullKind:"refused"}}}__name(mountRootVerdict,"mountRootVerdict");function unmountableRootSpelling(root){return root.includes(":")||root.startsWith("\\\\")}__name(unmountableRootSpelling,"unmountableRootSpelling");function insideReviewTmpLexically(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;return(resolved+sep).lastIndexOf(marker)>=0}__name(insideReviewTmpLexically,"insideReviewTmpLexically");function resolvedGitDir(cwd){return revParse(cwd,"--absolute-git-dir")}__name(resolvedGitDir,"resolvedGitDir");function resolvedCommonDir(cwd){return revParse(cwd,"--path-format=absolute","--git-common-dir")}__name(resolvedCommonDir,"resolvedCommonDir");function revParse(cwd,...flags){const resolved=spawnSync("git",["-c","core.hooksPath=/dev/null/no-hooks","-c","core.fsmonitor=","rev-parse",...flags],{cwd,encoding:"utf8",timeout:3e4,env:{...sanitizedGitEnv(),LC_ALL:"C"}});const value=resolved.error||resolved.status!==0||!resolved.stdout?null:resolved.stdout.replace(/\n$/,"");return{value:value!==null&&value.includes("\uFFFD")?null:value,notARepository:resolved.status===128&&resolved.stderr.includes("not a git repository")}}__name(revParse,"revParse");function untrustedPointer(dir,gitDir,expectedOwner,root){if(adminEntryInsideReviewTmp(gitDir,root,dir)){return"resolves to an admin entry inside the review temp dir, where the reviewed code can rewrite it"}const common=resolvedCommonDir(dir);if(common.value===null&&!common.notARepository){return"git could not resolve its own common dir from this tree, so whether the pointer names the main repository instead of a linked worktree's admin entry is unknown"}if(common.value!==null&&common.value===gitDir){return"resolves to the repository's own common dir rather than a linked worktree's admin entry, so every command through it acts on the main repository instead of this tree"}let backpointer;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname(resolve(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync2(ownerSpelled)}catch{ownerTree=null}const writableRoot=outermostReviewTmpRoot(root);if(ownerSpelled===writableRoot||isSubpath(writableRoot,ownerSpelled)){const redirect=redirectedAncestor(ownerSpelled,writableRoot);if(redirect!==null){return`resolves to a different tree's admin entry \u2014 the owner its gitdir backpointer names resolves through a symlink inside the review temp dir (${redirect}), so the round trip would agree with whatever the link points at`}}let expectedReal;try{expectedReal=realpathSync2(expectedOwner)}catch{return"could not resolve the tree the entry must belong to"}if(ownerTree===null){return"resolves to an admin entry that does not point back at this tree \u2014 the owner its backpointer names cannot be resolved, so the commands this gates would measure whichever repository it does name"}if(ownerTree!==expectedReal){return"resolves to a different tree's admin entry \u2014 its gitdir backpointer names that tree, not this one, so every command through it would measure and mutate the tree it actually belongs to"}return null}__name(untrustedPointer,"untrustedPointer");function untrustedRepositoryFrom(cwd,mountRoot=mountRootFor){const root=mountRoot(cwd);if(root===null){if(mountNullKind(cwd)!=="refused")return null;return`${cwd}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command run from here would land is unmeasured`}if(!existsSync2(cwd)){if(!insideReviewTmpLexically(cwd))return null;return`${cwd}: no directory exists at this spelling inside the review temp dir \u2014 an ancestor was renamed out from under it, so where a command run from here would land is unmeasured`}const target=resolvedGitDir(cwd);if(target.value===null){return target.notARepository?null:`${cwd}: git could not resolve its own git dir, so where a command run from here would land is unmeasured`}const toplevel=revParse(cwd,"--show-toplevel");if(toplevel.value===null){return`${cwd}: git could not resolve its own top-level directory, so where a command run from here would land is unmeasured`}const why=untrustedPointer(cwd,target.value,toplevel.value,root);return why===null?null:`${cwd} ${why}`}__name(untrustedRepositoryFrom,"untrustedRepositoryFrom");function untrustedGitfile(tree,mountRoot=mountRootFor){if(!existsSync2(tree))return null;const root=mountRoot(tree);if(root===null){if(mountNullKind(tree)!=="refused")return null;return`${tree}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command through its .git would land is unmeasured`}const dotGit=join2(tree,".git");let stat;try{stat=lstatSync(dotGit)}catch{return`${tree} has no .git to resolve`}if(!stat.isFile()){return`${tree}'s .git is not the gitfile the pipeline created, and the tree is inside the review temp dir`}const target=resolvedGitDir(tree);if(target.value===null){return`${tree}: git could not resolve its own git dir`}const why=untrustedPointer(tree,target.value,tree,root);return why===null?null:`${tree} ${why}`}__name(untrustedGitfile,"untrustedGitfile");function adminEntryInsideReviewTmp(gitDir,root,tree){if(root===null)return mountNullKind(tree)==="refused";let real;let realRoot;try{const canonical=realpathSync2.native??realpathSync2;real=canonical(resolve(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=root.indexOf(marker);return at<0?root:root.slice(0,at+marker.length-1)}__name(outermostReviewTmpRoot,"outermostReviewTmpRoot");function redirectedAncestor(dir,stopAt=process.cwd()){try{const stop=resolve(stopAt);let stopReal=stop;try{stopReal=realpathSync2(stopAt)}catch{}for(let cur=resolve(dir);;cur=dirname(cur)){let isLink;try{isLink=lstatSync(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync2(cur)===stopReal)return null}catch{}if(dirname(cur)===cur)return null}}catch{return null}}__name(redirectedAncestor,"redirectedAncestor");function sanitizedGitEnv(){const env={...process.env};const drop=new Set([...GIT_ENV_REDIRECTS,...GIT_ENV_CONFIG,...GIT_ENV_EXEC].map(k=>k.toLowerCase()));for(const key of Object.keys(env)){const lower=key.toLowerCase();if(drop.has(lower)||/^git_config_(key|value)_\d+$/.test(lower)){delete env[key]}}env["GIT_NO_REPLACE_OBJECTS"]="1";env["GIT_GRAFT_FILE"]="/dev/null/grafts";return env}__name(sanitizedGitEnv,"sanitizedGitEnv");var MAX_INCLUDE_DEPTH=10;var MAX_INCLUDE_FILES=64;var FILTER_SCREEN_NAMED=12;var SCREEN_KEYS="^filter\\..*\\.(smudge|clean|process)$|^include\\.path$|^includeif\\..*\\.path$";function filterCommandsIn(commonDir,gitDir){const candidates=[join2(commonDir,"config"),join2(gitDir,"config.worktree")];try{for(const entry of readdirSync2(join2(commonDir,"worktrees"))){candidates.push(join2(commonDir,"worktrees",entry,"config.worktree"))}}catch{}const filters=new Set;const unread=new Set;const dangling=new Set;const visited=new Set;const read=__name(file=>{const r=spawnSync("git",["config","--file",file,"-z","--get-regexp",SCREEN_KEYS],{cwd:commonDir,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error){return{unreadable:r.error.code??r.error.message}}if(r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return{unreadable:`git config exited ${r.status}`}}const records=[];for(const rec of r.stdout.split("\0")){if(!rec)continue;const nl=rec.indexOf("\n");records.push(nl===-1?[rec,""]:[rec.slice(0,nl),rec.slice(nl+1)])}return{records}},"read");const visit=__name((file,depth,via)=>{let real;try{real=realpathSync2.native(file)}catch(e){if(via!==null){const code=e?.code;if(code==="ENOENT"){dangling.add(`${via} -> ${file} (missing \u2014 git ignores it)`)}else{unread.add(`${via} -> ${file} (could not be resolved: ${code??"unknown"} \u2014 not screened)`)}}return}if(visited.has(real))return;if(visited.size>=MAX_INCLUDE_FILES){unread.add(`${via??file} -> ${file} (include fan-out past ${MAX_INCLUDE_FILES} files \u2014 not screened)`);return}visited.add(real);try{if(!statSync2(real).isFile()){unread.add(`${via??file} -> ${file} (not a regular file \u2014 not screened)`);return}accessSync(real,constants.R_OK)}catch{unread.add(`${via??file} -> ${file} (could not be read)`);return}if(depth>MAX_INCLUDE_DEPTH){unread.add(`${via} -> ${file} (nested past git's include limit \u2014 not screened)`);return}const r=read(file);if("unreadable"in r){unread.add(`${file} (could not be read: ${r.unreadable})`);return}for(const[key,value]of r.records){if(key.startsWith("filter.")){filters.add(key);continue}let target;if(value.startsWith("~/")){target=`${process.env["HOME"]||homedir()}${sep}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute2(value)?value:`${dirname(file)}${sep}${value}`}visit(target,depth+1,`${key} (in ${file})`)}},"visit");for(const candidate of candidates)visit(candidate,0,null);return{filters:[...filters],unread:[...unread],dangling:[...dangling]}}__name(filterCommandsIn,"filterCommandsIn");function describeFilterScreen(hits){const named=hits.slice(0,FILTER_SCREEN_NAMED);const rest=hits.length-named.length;return rest>0?`${named.join(", ")}, and ${rest} more`:named.join(", ")}__name(describeFilterScreen,"describeFilterScreen");function filterBlankEnv(filterKeys){const names=new Set;for(const key of filterKeys){const m=/^filter\.(.+)\.(?:smudge|clean|process)$/.exec(key);if(m)names.add(m[1])}const env={};let n=0;for(const name of names){for(const[key,value]of[["clean",""],["smudge",""],["process",""],["required","false"]]){env[`GIT_CONFIG_KEY_${n}`]=`filter.${name}.${key}`;env[`GIT_CONFIG_VALUE_${n}`]=value;n++}}if(n>0)env["GIT_CONFIG_COUNT"]=String(n);return env}__name(filterBlankEnv,"filterBlankEnv");var UNRESOLVED_REPO="the repository's git directories could not be resolved (git rev-parse failed) \u2014 not screened";function screenForTree(worktree){const discover=__name(flag=>{const r=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return null}return r.stdout.endsWith("\n")?r.stdout.slice(0,-1):r.stdout},"discover");const commonDir=discover("--git-common-dir");const gitDir=discover("--git-dir");if(commonDir===null||gitDir===null)return null;return filterCommandsIn(commonDir,gitDir)}__name(screenForTree,"screenForTree");function localFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread,...screen.dangling]}__name(localFilterCommands,"localFilterCommands");function filterScreenForTree(worktree){return screenForTree(worktree)}__name(filterScreenForTree,"filterScreenForTree");function resolvedContentTransformForTree(worktree){const r=spawnSync("git",["config","--get-regexp","^filter\\..*\\.(smudge|clean|process)$|^core\\.(autocrlf|eol)$"],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.status!==0||typeof r.stdout!=="string")return false;for(const line of r.stdout.split("\n")){const space=line.indexOf(" ");const key=(space===-1?line:line.slice(0,space)).toLowerCase();const value=space===-1?"true":line.slice(space+1).trim().toLowerCase();if(key.startsWith("filter."))return true;if(key==="core.autocrlf"&&(value==="true"||value==="input")){return true}if(key==="core.eol"&&(value==="crlf"||value==="native"&&process.platform==="win32")){return true}}return false}__name(resolvedContentTransformForTree,"resolvedContentTransformForTree");function checkoutFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread]}__name(checkoutFilterCommands,"checkoutFilterCommands");function discardWorktree(cwd,tree){let symlink=false;try{symlink=lstatSync(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync(tree,{recursive:true,force:true});dropWorktreeRegistration(cwd,tree,ownAdminDir);if(sweep!==void 0&&sweep.status!==0){dropWorktreeRegistration(cwd,tree,null)}return sweep}__name(discardWorktree,"discardWorktree");function dropWorktreeRegistration(cwd,tree,adminDir){if(adminDir!==null){try{rmSync(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(common.status!==0||typeof common.stdout!=="string")return;const dir=join2(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync2(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join2(dir,id,"gitdir"),"utf8").trim();const named=dirname(gitdir);if(samePath(named)!==wanted)continue;if(existsSync2(named))continue;rmSync(join2(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join2(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve(dirname(resolve(tree)),match[1].trim());const back=readFileSync2(join2(dir,"gitdir"),"utf8").trim();return samePath(dirname(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve(p);try{return join2(realpathSync2(dirname(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join2(mkdtempSync(join2(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep).join("/");writeFileSync(file,"node_modules/\ndist/\n",{flag:"wx",mode:384});pipelineExcludesFile=file}catch{pipelineExcludesFile=""}}return pipelineExcludesFile===""?[]:["-c",`core.excludesFile=${pipelineExcludesFile}`]}__name(pipelineExcludeArgs,"pipelineExcludeArgs");function inPipelineFootprint(rec){const parts=rec.split("/");for(let i=0;i<parts.length-1;i++){if(parts[i]==="node_modules"||parts[i]==="dist")return true;if(parts[i]===".husky"&&parts[i+1]==="_"&&i+1<parts.length-1)return true}return false}__name(inPipelineFootprint,"inPipelineFootprint");function ignoreSourcesOf(cwd,paths,anchor=[]){const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"check-ignore","-z","-v","--stdin"],{cwd,input:`${paths.join("\0")}\0`,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return null}const fields=r.stdout.split("\0");const rules=new Map;for(let i=0;i+3<fields.length;i+=4){rules.set(fields[i+3],{source:fields[i],pattern:fields[i+2]})}return rules}__name(ignoreSourcesOf,"ignoreSourcesOf");function hidesEverything(pattern){const core=pattern.replace(/^\//,"").replace(/\/$/,"");if(core.length===0)return false;const segments=core.split("/");return core.includes("*")&&segments.every(seg=>/^[*?]+$/.test(seg))}__name(hidesEverything,"hidesEverything");function trackedIgnoreSources(cwd,sources,anchor=[]){const inside=[...sources].filter(s=>s.length>0&&!isAbsolute2(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync("git",[...anchor,"ls-files","-z","--",...inside],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return new Set}return new Set(r.stdout.split("\0").filter(p=>p.length>0))}__name(trackedIgnoreSources,"trackedIgnoreSources");var RESIDUE_PATH_CAP=12;function worktreeResidue(cwd,cap=RESIDUE_PATH_CAP,expectedHeadSha){try{if(!lstatSync(join2(cwd,".git")).isFile()){return{paths:[],total:0,unmeasured:".git is not a gitfile (a planted repository?) \u2014 a repo stood up at this path answers a clean status for a dirty tree, and the probe cannot tell the two apart"}}}catch{}const root=mountRootFor(cwd);if(root===null){if(mountNullKind(cwd)==="refused"){return{paths:[],total:0,unmeasured:"the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, and the status below would measure whichever repository the pointer here names"}}}else{const target=resolvedGitDir(cwd);let why;if(target.value!==null){why=untrustedPointer(cwd,target.value,cwd,root)}else{why=target.notARepository?null:"git could not resolve its own git dir"}if(why!==null){return{paths:[],total:0,unmeasured:`the .git gitfile ${why} \u2014 the status below would measure whichever repository it names, and refresh that index through whatever filters it configures`}}}const discover=__name(flag=>{const r2=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(r2.error||r2.status!==0||typeof r2.stdout!=="string"){return null}return r2.stdout.endsWith("\n")?r2.stdout.slice(0,-1):r2.stdout},"discover");const toplevel=discover("--show-toplevel");const gitDir=discover("--git-dir");const commonDir=discover("--git-common-dir");let isWorktree=false;let anchor=[];let filterBlanks={};try{if(toplevel!==null&&gitDir!==null&&commonDir!==null&&realpathSync2(toplevel)===realpathSync2(cwd)){isWorktree=true;if(lstatSync(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve(cwd);const bound=dirname(commonDir);const redirected=redirectedAncestor(dirname(spelled),bound);if(redirected!==null){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${redirected}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}let backpointer=null;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").trim()}catch{}if(backpointer===null){return{paths:[],total:0,unmeasured:"the .git gitfile names a repository with no admin entry for this tree \u2014 a standalone repository answering for this path, whose index the commands below would measure"}}let pointsBack=false;try{pointsBack=realpathSync2(dirname(resolve(gitDir,backpointer)))===realpathSync2(cwd)}catch{}if(!pointsBack){return{paths:[],total:0,unmeasured:"the .git gitfile names an admin entry that does not point back at this tree \u2014 the commands below would measure whichever repository it does name"}}anchor=[`--git-dir=${realpathSync2(gitDir)}`,`--work-tree=${realpathSync2(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync("git",[...anchor,"rev-parse","HEAD"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});const got=head.error||head.status!==0||typeof head.stdout!=="string"?null:head.stdout.trim();if(got===null||got.toLowerCase()!==expectedHeadSha.toLowerCase()){return{paths:[],total:0,unmeasured:got===null?"the pinned identity could not read its own HEAD \u2014 the commands below would have measured a repository git cannot read":`the pinned identity is checked out at ${got}, not the fetched PR head ${expectedHeadSha} \u2014 the gitfile names a repository answering for this path, and its index is what the commands below would measure`}}}const screen=filterCommandsIn(commonDir,realpathSync2(gitDir));const notReadToTheBottom=[...screen.unread,...screen.dangling];if(notReadToTheBottom.length>0){return{paths:[],total:0,unmeasured:`the residue measurement would run under repo-local config this screen could not read to the bottom: ${describeFilterScreen(notReadToTheBottom)} \u2014 a content filter reached that way would execute on the index refresh, and a filter the screen cannot see it cannot blank; remove the include, or the file it names, if it is not yours`}}filterBlanks=filterBlankEnv(screen.filters)}}catch{isWorktree=false}if(!isWorktree){return{paths:[],total:0,unmeasured:"the path is not a git worktree (repository discovery walks up into the enclosing checkout)"}}const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"-c","core.fsmonitor=","-c","core.hooksPath=/dev/null/no-hooks","status","--porcelain","--untracked-files=all","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:{...sanitizedGitEnv(),...filterBlanks}});if(r.error||r.status!==0||typeof r.stdout!=="string"){const why=r.error?r.error.code??r.error.message:`git status exited ${r.status}`;return{paths:[],total:0,unmeasured:why}}const records=r.stdout.split("\0").filter(rec=>rec.length>0);const paths=[];for(let i=0;i<records.length;i++){const rec=records[i];const status=rec.slice(0,2);paths.push(rec.slice(3));if((status.includes("R")||status.includes("C"))&&i+1<records.length){paths.push(records[++i])}}const others=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","--others","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(others.error||others.status!==0||typeof others.stdout!=="string"){const why=others.error?others.error.code??others.error.message:`git ls-files exited ${others.status}`;return{paths:[],total:0,unmeasured:why}}const seen=new Set(paths);const editedFromHead=new Set(paths);const extras=[];for(const rec of others.stdout.split("\0")){if(rec.length===0||seen.has(rec))continue;if(inPipelineFootprint(rec))continue;seen.add(rec);extras.push(rec)}if(extras.length>0){const hiddenBy=ignoreSourcesOf(cwd,extras,anchor);if(hiddenBy===null){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the ignore rules hiding this tree's untracked files could not be attributed, so `git status` cannot be trusted to have seen them"}}const fromTheCommit=trackedIgnoreSources(cwd,new Set([...hiddenBy.values()].map(rule=>rule.source)),anchor);for(const rec of extras){const rule=hiddenBy.get(rec);if(rule!==void 0&&fromTheCommit.has(rule.source)&&!editedFromHead.has(rule.source)&&!hidesEverything(rule.pattern)){continue}paths.push(rec)}}const stage=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-s","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(stage.error||stage.status!==0||typeof stage.stdout!=="string"){const why=stage.error?stage.error.code??stage.error.message:`git ls-files exited ${stage.status}`;return{paths:[],total:0,unmeasured:why}}const blind=stage.stdout.split("\0").filter(rec=>rec.startsWith("160000 ")).map(rec=>rec.slice(rec.indexOf(" ")+1)).filter(gitlink=>{if(gitlink.includes("\uFFFD"))return true;try{return readdirSync2(join2(cwd,gitlink)).length>0}catch(err){return err.code!=="ENOENT"}});if(blind.length>0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"git status cannot see inside the committed submodule path(s) "+blind.join(", ")}}const bits=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-v","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(bits.error||bits.status!==0||typeof bits.stdout!=="string"){const why=bits.error?bits.error.code??bits.error.message:`git ls-files exited ${bits.status}`;return{paths:paths.slice(0,cap),total:paths.length,unmeasured:why}}if(bits.stdout.split("\0").some(rec=>/^[a-zS]/.test(rec))){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the index carries skip-worktree or assume-unchanged bits, so `git status` cannot see edits to the tracked files they cover"}}if(expectedHeadSha===void 0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the caller brought no record of the commit this tree must hold, and a status measured through an unanchored identity would certify whichever index the .git gitfile names \u2014 a forged pair answers clean \u2014 so the measurement is refused rather than certified"}}return{paths:paths.slice(0,cap),total:paths.length}}__name(worktreeResidue,"worktreeResidue");function exposeDependencies(probeTree,dependencyRoot,opts={}){const done={linked:0,failed:0,alreadyPresent:false,selfLinked:0};if(probeTree===dependencyRoot)return done;let members=[];try{const graph=readWorkspacePackages(dependencyRoot);members=[...graph.packages.map(p=>p.dir),...graph.skipped]}catch{}const memberSources=members.map(dir=>({dir,source:containedIn(dependencyRoot,dir)})).filter(m=>{if(m.source===null)return true;try{return realpathSync2(m.source)!==realpathSync2(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join2(dependencyRoot,"node_modules");if(lstatSync(nm).isDirectory())rootNm=realpathSync2(nm)}catch{}const containment={rootNm,selfLinks:new Set(memberSources.flatMap(m=>m.source===null?[]:[m.source]))};farmNodeModules(dependencyRoot,probeTree,done,containment,opts.rebuild===true);const owned=new Set([join2(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync2(join2(dependencyRoot,dir)))done.failed++;continue}if(!existsSync2(target))continue;owned.add(join2(target,"node_modules"));try{farmNodeModules(source,target,done,containment,opts.rebuild===true)}catch{done.failed++}}if(opts.rebuild===true){for(const path of[...owned]){try{owned.add(realpathSync2(path))}catch{}}removeUnownedNodeModules(probeTree,owned,done)}return done}__name(exposeDependencies,"exposeDependencies");function removeUnownedNodeModules(tree,owned,done){const inTreeLinks=[];const walk=__name(dir=>{let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync2(full);const root=realpathSync2(tree);if(!statSync2(full).isDirectory()){}else if(real===root||real.startsWith(root+sep)){inTreeLinks.push(real)}else{done.failed++}}catch{}continue}if(!entry.isDirectory())continue;walk(full)}},"walk");walk(tree);for(const real of inTreeLinks){if(isOwned(owned,real))continue;if(holdsNodeModules(real,owned))done.failed++}}__name(removeUnownedNodeModules,"removeUnownedNodeModules");function isOwned(owned,path){if(owned.has(path))return true;try{return owned.has(realpathSync2(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full))return true;continue}if(entry.isSymbolicLink()||!entry.isDirectory())continue;if(entry.name===".git")continue;if(holdsNodeModules(full,owned))return true}return false}__name(holdsNodeModules,"holdsNodeModules");function containedIn(root,dir){try{const base=realpathSync2(resolve(root));const full=resolve(base,dir);const real=existsSync2(full)?realpathSync2(full):full;return real===base||real.startsWith(base+sep)?real:null}catch{return null}}__name(containedIn,"containedIn");var FARM_MARKER=".qwen-review-farm";function farmLinkVerdict(real,sourceNm,containment){if(insideDir(sourceNm,real))return"internal";if(containment.rootNm!==null&&insideDir(containment.rootNm,real)){return"internal"}for(const member of containment.selfLinks){if(insideDir(member,real))return"self"}return null}__name(farmLinkVerdict,"farmLinkVerdict");function insideDir(base,real){return real===base||real.startsWith(base+sep)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join2(target,FARM_MARKER),"utf8").trim()===resolve(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join2(sourceDir,"node_modules");const target=join2(targetDir,"node_modules");if(!existsSync2(source)){if(rebuild){try{lstatSync(target);rmSync(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync2(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync2(source,{withFileTypes:true})}catch{done.failed++;return}const before=done.linked;for(const entry of entries){if(entry.name===".vite"||entry.name===".vite-temp")continue;const sourceEntry=join2(source,entry.name);const targetEntry=join2(target,entry.name);let sourceStats;try{sourceStats=lstatSync(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync2(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync(targetEntry);pkgs=readdirSync2(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join2(sourceEntry,pkg);let real;try{real=realpathSync2(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join2(targetEntry,pkg),linkType);done.linked++}catch{done.failed++}}}else{try{symlinkSync(sourceEntry,targetEntry,linkType);done.linked++}catch{done.failed++}}}if(done.linked>before){try{writeFileSync(join2(target,FARM_MARKER),`${resolve(sourceDir)}
|
|
3
|
+
import{sanitizeFilenameComponent}from"./chunk-7XQ5D34E.js";import{Storage}from"./chunk-EPODBRBP.js";import{getProjectHash,isSubpath}from"./chunk-OKN3Z5C5.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function safeTarget(target){if(/^[A-Za-z0-9._-]{55}~[0-9a-f]{8}$/.test(target))return target;const flat=target.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_");const stem=flat.replace(/^[._]+/,"")||"target";if(stem.length<=SAFE_TARGET_MAX)return stem;return`${stem.slice(0,SAFE_TARGET_MAX-9)}~${createHash("sha256").update(stem).digest("hex").slice(0,8)}`}__name(safeTarget,"safeTarget");var SAFE_TARGET_MAX=64;init_esbuild_shims();var CONTROL=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;var NEEDS_PRE_ESCAPE=/[\u007f-\u009f\p{Cf}\p{Zl}\p{Zp}]/gu;function inertText(value,maxChars=200){const clipped=value.length>maxChars?value.slice(0,maxChars):value;const rendered=CONTROL.test(clipped)?JSON.stringify(clipped.replace(NEEDS_PRE_ESCAPE,c=>{const hex=c.codePointAt(0).toString(16).padStart(4,"0");return`\\u${hex}`})):clipped;return clipped.length<value.length?`${rendered}\u2026`:rendered}__name(inertText,"inertText");init_esbuild_shims();import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync4,lstatSync as lstatSync3,mkdirSync as mkdirSync2,readdirSync as readdirSync3,realpathSync as realpathSync4,statSync as statSync3}from"node:fs";import{dirname as dirname3,isAbsolute as isAbsolute3,join as join3,relative as relative2,resolve as resolve3,sep as sep2}from"node:path";init_esbuild_shims();import{execFileSync,spawnSync as spawnSync2}from"node:child_process";init_esbuild_shims();import{spawnSync}from"node:child_process";import{accessSync,constants,existsSync as existsSync2,lstatSync,mkdirSync,mkdtempSync,readdirSync as readdirSync2,readFileSync as readFileSync2,realpathSync as realpathSync2,rmSync,statSync as statSync2,symlinkSync,writeFileSync}from"node:fs";import{homedir,tmpdir}from"node:os";import{basename,dirname,isAbsolute as isAbsolute2,join as join2,resolve,sep}from"node:path";init_esbuild_shims();import{existsSync,readFileSync,readdirSync,realpathSync,statSync}from"node:fs";import{isAbsolute,join,relative}from"node:path";init_esbuild_shims();var MAX_OLD_SPACE_FLAG="--max[-_]old[-_]space[-_]size";var HEAP_TOKEN_RE=new RegExp(`(?:^|\\s)${MAX_OLD_SPACE_FLAG}(?:=(\\d*)|\\s+(\\d+))?(?=\\s|$)`,"g");function heapFlagMb(options){let mb;for(const m of options.matchAll(HEAP_TOKEN_RE)){const value=m[1]||m[2];if(value)mb=Number(value)}return mb}__name(heapFlagMb,"heapFlagMb");function withoutHeapFlag(options){return options.replace(HEAP_TOKEN_RE,"").trim()}__name(withoutHeapFlag,"withoutHeapFlag");function raiseHeap(options,mb){if((heapFlagMb(options)??0)>=mb)return void 0;return`${withoutHeapFlag(options)} --max-old-space-size=${mb}`.trim()}__name(raiseHeap,"raiseHeap");var NPM_ENV_REF_RE=/(?<!\\)(\\*)\$\{([^${}]+)\}/g;function raiseNpmHeap(options,mb){return raiseHeap(options,mb)?.replace(NPM_ENV_REF_RE,(_,esc,name)=>`${esc}${esc}\\\${${name}}`)}__name(raiseNpmHeap,"raiseNpmHeap");var HEAP_BANNER_RE=/^FATAL ERROR: [^\n]*JavaScript heap out of memory/m;function heapBannerIn(raw){return HEAP_BANNER_RE.test(raw)}__name(heapBannerIn,"heapBannerIn");function ranOutOfHeap(r){return r.exitCode!==0&&(r.heapExhausted??heapBannerIn(r.output))}__name(ranOutOfHeap,"ranOutOfHeap");function killedFromOutside(r){return!r.timedOut&&r.spawnError===void 0&&(r.exitCode===137||r.exitCode===null&&r.signal==="SIGKILL")}__name(killedFromOutside,"killedFromOutside");init_esbuild_shims();function stripComments(src){return src.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g,m=>m.startsWith("/")?" ":m)}__name(stripComments,"stripComments");function isWorkspaceMember(filePath,workspaceGlobs){return workspaceDirFor(filePath,workspaceGlobs)!==null}__name(isWorkspaceMember,"isWorkspaceMember");function workspaceDirFor(filePath,workspaceGlobs){const norm=filePath.replace(/^\.\//,"");let owner=null;const previous=[];for(const glob of workspaceGlobs){const negated=glob.startsWith("!");const g=glob.replace(/^!/,"").replace(/^\.\//,"").replace(/\/$/,"");let dir=null;if(g.endsWith("/*")){const base=g.slice(0,-2);if(norm.startsWith(`${base}/`)){const seg=norm.slice(base.length+1).split("/")[0];if(seg)dir=`${base}/${seg}`}}else if(norm===g||norm.startsWith(`${g}/`)){dir=g}if(dir===null)continue;if(!negated){if(dir!==owner){previous.push(owner);owner=dir}}else if(dir===owner){owner=previous.pop()??null}}return owner}__name(workspaceDirFor,"workspaceDirFor");function isNegationExcluded(filePath,workspaceGlobs){if(workspaceDirFor(filePath,workspaceGlobs)!==null)return false;const positives=workspaceGlobs.filter(g=>!g.startsWith("!"));return workspaceDirFor(filePath,positives)!==null}__name(isNegationExcluded,"isNegationExcluded");function hasUnmodeledWorkspaceGlob(globs){return globs.some(glob=>{const g=glob.replace(/^!/,"").replace(/^\.\//,"");if(!g.includes("*"))return false;return!/^[^*]+\/\*$/.test(g)})}__name(hasUnmodeledWorkspaceGlob,"hasUnmodeledWorkspaceGlob");function readWorkspaceGlobs(root){try{const pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"));const ws=pkg.workspaces;const globs=Array.isArray(ws)?ws:Array.isArray(ws?.packages)?ws.packages:[];return globs.filter(g=>typeof g==="string")}catch{return[]}}__name(readWorkspaceGlobs,"readWorkspaceGlobs");function readRootPackage(root){let pkg;try{pkg=JSON.parse(readFileSync(join(root,"package.json"),"utf8"))}catch{return null}if(pkg===null)return null;const scripts=Object.keys(pkg.scripts??{});if(!scripts.includes("build")&&!scripts.includes("test"))return null;const scriptsText={};for(const[k,v]of Object.entries(pkg.scripts??{})){if(typeof v==="string")scriptsText[k]=v}return{dir:".",name:typeof pkg.name==="string"&&pkg.name?pkg.name:"root",scripts,deps:declaredDeps(pkg),scriptsText}}__name(readRootPackage,"readRootPackage");function scriptFansOut(text){return typeof text==="string"&&(/(^|\s)(--workspaces|--?ws)(?=[\s'"`]|$)/.test(text)||/\bpnpm\s+(-r|--recursive)(?=[\s'"`]|$)/.test(text))}__name(scriptFansOut,"scriptFansOut");var COMMAND_SEPARATOR_RE=/[;&|\n]+/;function chainsCommands(text){return text.split(COMMAND_SEPARATOR_RE).filter(c=>c.trim()!=="").length>1}__name(chainsCommands,"chainsCommands");var NODE_VALUE_FLAGS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--env-file-if-exists","--input-type","--title","--redirect-warnings","--watch-path","--diagnostic-dir","--report-dir","--cpu-prof-dir","--heap-prof-dir","--icu-data-dir","--openssl-config"]);var SCRIPT_RUNNERS=new Set(["node","tsx"]);var NODE_INLINE_FLAGS=new Set(["-e","--eval","-p","--print","-"]);function nodeScripts(text){const files=[];for(const command of text.split(COMMAND_SEPARATOR_RE)){const words=command.trim().split(/\s+/);const runner=words.findIndex(w=>SCRIPT_RUNNERS.has(w));for(let i=runner+1;i>0&&i<words.length;i++){const word=words[i];if(NODE_INLINE_FLAGS.has(word))break;if(word.startsWith("-")){if(NODE_VALUE_FLAGS.has(word))i++;continue}if(/^[\w@./-]+\.[cm]?[jt]s$/.test(word))files.push(word);break}}return files}__name(nodeScripts,"nodeScripts");function childProcessCommands(src){const commands=[];for(const m of stripComments(src).matchAll(/\b(?:exec|execSync|execFile|execFileSync|spawn|spawnSync)\s*\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*`)/g)){commands.push(m[1].slice(1,-1))}return commands}__name(childProcessCommands,"childProcessCommands");var MAX_HAND_OFF_SCRIPT_BYTES=1024*1024;function rootBuildFanOutScript(root,text){if(typeof text!=="string")return void 0;for(const file of nodeScripts(text)){try{const path=realpathSync(join(root,file));const inRoot=relative(realpathSync(root),path);if(inRoot.startsWith("..")||isAbsolute(inRoot))continue;const stat=statSync(path);if(!stat.isFile()||stat.size>MAX_HAND_OFF_SCRIPT_BYTES)continue;if(childProcessCommands(readFileSync(path,"utf8")).some(scriptFansOut))return file}catch{}}return void 0}__name(rootBuildFanOutScript,"rootBuildFanOutScript");function declaredBuildHeapMb(root){const text=readRootPackage(root)?.scriptsText["build"];if(typeof text!=="string")return void 0;let declared;for(const m of text.matchAll(/\bNODE_OPTIONS=(?:"([^"]*)"|'([^']*)'|(\S*))/g)){const mb=heapFlagMb(m[1]??m[2]??m[3]??"");if(mb!==void 0)declared=Math.max(declared??0,mb)}return declared}__name(declaredBuildHeapMb,"declaredBuildHeapMb");function declaredDeps(pkg){return[...Object.keys(pkg.dependencies??{}),...Object.keys(pkg.devDependencies??{}),...Object.keys(pkg.peerDependencies??{}),...Object.keys(pkg.optionalDependencies??{})]}__name(declaredDeps,"declaredDeps");function workspaceDirCandidates(root,globs){const dirs=new Set;for(const glob of globs){if(glob.startsWith("!"))continue;const g=glob.replace(/^\.\//,"").replace(/\/$/,"");if(g.endsWith("/*")){const base=g.slice(0,-2);let entries;try{entries=readdirSync(join(root,base),{withFileTypes:true}).filter(e=>e.isDirectory()||e.isSymbolicLink()&&existsSync(join(root,base,e.name,"package.json"))).map(e=>e.name)}catch{continue}for(const e of entries)dirs.add(`${base}/${e}`)}else{dirs.add(g)}}return[...dirs].sort()}__name(workspaceDirCandidates,"workspaceDirCandidates");function readWorkspacePackages(root){const globs=readWorkspaceGlobs(root);const packages=[];const skipped=[];for(const dir of workspaceDirCandidates(root,globs)){const manifest=join(root,dir,"package.json");if(!existsSync(manifest))continue;if(workspaceDirFor(`${dir}/package.json`,globs)!==dir){const positives=globs.filter(g=>!g.startsWith("!"));if(workspaceDirFor(`${dir}/package.json`,positives)===dir)continue;skipped.push(dir);continue}let pkg;try{pkg=JSON.parse(readFileSync(manifest,"utf8"))}catch{skipped.push(dir);continue}if(pkg===null||typeof pkg.name!=="string"||!pkg.name){skipped.push(dir);continue}packages.push({dir,name:pkg.name,scripts:Object.keys(pkg.scripts??{}),deps:declaredDeps(pkg)})}packages.sort((a,b)=>a.dir.localeCompare(b.dir));skipped.sort();return{packages,skipped}}__name(readWorkspacePackages,"readWorkspacePackages");function affectedWorkspaces(changedFiles,workspaceGlobs){const dirs=new Set;for(const f of changedFiles){const d=workspaceDirFor(f,workspaceGlobs);if(d)dirs.add(d)}return[...dirs].sort()}__name(affectedWorkspaces,"affectedWorkspaces");function dependencyEdges(packages){const byName=new Map;for(const p of packages){if(p.dir!=="."||!byName.has(p.name))byName.set(p.name,p)}const dependsOn=new Map;for(const p of packages){dependsOn.set(p.dir,p.deps.map(d=>byName.get(d)?.dir).filter(d=>!!d&&d!==p.dir))}return dependsOn}__name(dependencyEdges,"dependencyEdges");function dependencyClosure(dirs,packages){const dependsOn=dependencyEdges(packages);const closure=new Set;const add=__name(dir=>{if(closure.has(dir))return;closure.add(dir);for(const d of dependsOn.get(dir)??[])add(d)},"add");dirs.forEach(add);return[...closure].sort()}__name(dependencyClosure,"dependencyClosure");function reverseDependencyClosure(affected,packages){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=new Set(affected.filter(a=>byDir.has(a)));let grew=true;while(grew){grew=false;for(const p of packages){if(consumers.has(p.dir))continue;if((dependsOn.get(p.dir)??[]).some(d=>consumers.has(d))){consumers.add(p.dir);grew=true}}}return[...consumers].sort()}__name(reverseDependencyClosure,"reverseDependencyClosure");function buildSetFor(affected,packages,alsoBuild=[]){const byDir=new Map(packages.map(p=>[p.dir,p]));const dependsOn=dependencyEdges(packages);const consumers=reverseDependencyClosure(affected,packages);const wanted=new Set;const addDeps=__name(dir=>{if(wanted.has(dir))return;wanted.add(dir);for(const d of dependsOn.get(dir)??[])addDeps(d)},"addDeps");for(const c of consumers)addDeps(c);for(const extra of alsoBuild)if(byDir.has(extra))addDeps(extra);const order=[];const seen=new Set;const visit=__name(dir=>{if(seen.has(dir))return;seen.add(dir);for(const d of dependsOn.get(dir)??[]){if(wanted.has(d))visit(d)}order.push(dir)},"visit");for(const dir of alsoBuild.filter(d=>wanted.has(d)).sort())visit(dir);for(const dir of[...wanted].sort())visit(dir);return order}__name(buildSetFor,"buildSetFor");var GIT_ENV_REDIRECTS=["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_COMMON_DIR"];var GIT_ENV_CONFIG=["GIT_CONFIG_COUNT","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_CONFIG_PARAMETERS","GIT_DEFAULT_HASH"];var GIT_ENV_EXEC=["GIT_SSH_COMMAND","GIT_SSH","GIT_EXEC_PATH","GIT_TEMPLATE_DIR","GIT_ASKPASS","GIT_PROXY_COMMAND","GIT_EDITOR","GIT_SEQUENCE_EDITOR","GIT_EXTERNAL_DIFF","XDG_CONFIG_HOME"];function mountRootFor(cwd){return mountRootVerdict(cwd).root}__name(mountRootFor,"mountRootFor");function mountNullKind(cwd){return mountRootVerdict(cwd).nullKind??"refused"}__name(mountNullKind,"mountNullKind");function mountRootVerdict(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=(resolved+sep).lastIndexOf(marker);if(at<0)return{root:null,nullKind:"outside"};const root=resolved.slice(0,at+marker.length-1);const outermost=outermostReviewTmpRoot(root);const bound=outermost===root?resolve(root,".."):outermost;try{if(redirectedAncestor(root,bound)!==null){return{root:null,nullKind:"refused"}}const real=realpathSync2(root);if(unmountableRootSpelling(real)){return{root:null,nullKind:"unmountable"}}return{root:real,nullKind:null}}catch{return{root:null,nullKind:"refused"}}}__name(mountRootVerdict,"mountRootVerdict");function unmountableRootSpelling(root){return root.includes(":")||root.startsWith("\\\\")}__name(unmountableRootSpelling,"unmountableRootSpelling");function insideReviewTmpLexically(cwd){const resolved=resolve(cwd);const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;return(resolved+sep).lastIndexOf(marker)>=0}__name(insideReviewTmpLexically,"insideReviewTmpLexically");function resolvedGitDir(cwd){return revParse(cwd,"--absolute-git-dir")}__name(resolvedGitDir,"resolvedGitDir");function resolvedCommonDir(cwd){return revParse(cwd,"--path-format=absolute","--git-common-dir")}__name(resolvedCommonDir,"resolvedCommonDir");function revParse(cwd,...flags){const resolved=spawnSync("git",["-c","core.hooksPath=/dev/null/no-hooks","-c","core.fsmonitor=","rev-parse",...flags],{cwd,encoding:"utf8",timeout:3e4,env:{...sanitizedGitEnv(),LC_ALL:"C"}});const value=resolved.error||resolved.status!==0||!resolved.stdout?null:resolved.stdout.replace(/\n$/,"");return{value:value!==null&&value.includes("\uFFFD")?null:value,notARepository:resolved.status===128&&resolved.stderr.includes("not a git repository")}}__name(revParse,"revParse");function untrustedPointer(dir,gitDir,expectedOwner,root){if(adminEntryInsideReviewTmp(gitDir,root,dir)){return"resolves to an admin entry inside the review temp dir, where the reviewed code can rewrite it"}const common=resolvedCommonDir(dir);if(common.value===null&&!common.notARepository){return"git could not resolve its own common dir from this tree, so whether the pointer names the main repository instead of a linked worktree's admin entry is unknown"}if(common.value!==null&&common.value===gitDir){return"resolves to the repository's own common dir rather than a linked worktree's admin entry, so every command through it acts on the main repository instead of this tree"}let backpointer;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").replace(/\n$/,"")}catch{return null}const ownerSpelled=dirname(resolve(gitDir,backpointer));let ownerTree;try{ownerTree=realpathSync2(ownerSpelled)}catch{ownerTree=null}const writableRoot=outermostReviewTmpRoot(root);if(ownerSpelled===writableRoot||isSubpath(writableRoot,ownerSpelled)){const redirect=redirectedAncestor(ownerSpelled,writableRoot);if(redirect!==null){return`resolves to a different tree's admin entry \u2014 the owner its gitdir backpointer names resolves through a symlink inside the review temp dir (${redirect}), so the round trip would agree with whatever the link points at`}}let expectedReal;try{expectedReal=realpathSync2(expectedOwner)}catch{return"could not resolve the tree the entry must belong to"}if(ownerTree===null){return"resolves to an admin entry that does not point back at this tree \u2014 the owner its backpointer names cannot be resolved, so the commands this gates would measure whichever repository it does name"}if(ownerTree!==expectedReal){return"resolves to a different tree's admin entry \u2014 its gitdir backpointer names that tree, not this one, so every command through it would measure and mutate the tree it actually belongs to"}return null}__name(untrustedPointer,"untrustedPointer");function untrustedRepositoryFrom(cwd,mountRoot=mountRootFor){const root=mountRoot(cwd);if(root===null){if(mountNullKind(cwd)!=="refused")return null;return`${cwd}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command run from here would land is unmeasured`}if(!existsSync2(cwd)){if(!insideReviewTmpLexically(cwd))return null;return`${cwd}: no directory exists at this spelling inside the review temp dir \u2014 an ancestor was renamed out from under it, so where a command run from here would land is unmeasured`}const target=resolvedGitDir(cwd);if(target.value===null){return target.notARepository?null:`${cwd}: git could not resolve its own git dir, so where a command run from here would land is unmeasured`}const toplevel=revParse(cwd,"--show-toplevel");if(toplevel.value===null){return`${cwd}: git could not resolve its own top-level directory, so where a command run from here would land is unmeasured`}const why=untrustedPointer(cwd,target.value,toplevel.value,root);return why===null?null:`${cwd} ${why}`}__name(untrustedRepositoryFrom,"untrustedRepositoryFrom");function untrustedGitfile(tree,mountRoot=mountRootFor){if(!existsSync2(tree))return null;const root=mountRoot(tree);if(root===null){if(mountNullKind(tree)!=="refused")return null;return`${tree}: the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, so where a command through its .git would land is unmeasured`}const dotGit=join2(tree,".git");let stat;try{stat=lstatSync(dotGit)}catch{return`${tree} has no .git to resolve`}if(!stat.isFile()){return`${tree}'s .git is not the gitfile the pipeline created, and the tree is inside the review temp dir`}const target=resolvedGitDir(tree);if(target.value===null){return`${tree}: git could not resolve its own git dir`}const why=untrustedPointer(tree,target.value,tree,root);return why===null?null:`${tree} ${why}`}__name(untrustedGitfile,"untrustedGitfile");function adminEntryInsideReviewTmp(gitDir,root,tree){if(root===null)return mountNullKind(tree)==="refused";let real;let realRoot;try{const canonical=realpathSync2.native??realpathSync2;real=canonical(resolve(gitDir));realRoot=canonical(root)}catch{return true}return isSubpath(outermostReviewTmpRoot(realRoot),real)}__name(adminEntryInsideReviewTmp,"adminEntryInsideReviewTmp");function outermostReviewTmpRoot(root){const marker=`${sep}${REVIEW_TMP_DIR}${sep}`;const at=root.indexOf(marker);return at<0?root:root.slice(0,at+marker.length-1)}__name(outermostReviewTmpRoot,"outermostReviewTmpRoot");function redirectedAncestor(dir,stopAt=process.cwd()){try{const stop=resolve(stopAt);let stopReal=stop;try{stopReal=realpathSync2(stopAt)}catch{}for(let cur=resolve(dir);;cur=dirname(cur)){let isLink;try{isLink=lstatSync(cur).isSymbolicLink()}catch{isLink=false}if(isLink)return cur;if(cur===stop)return null;try{if(realpathSync2(cur)===stopReal)return null}catch{}if(dirname(cur)===cur)return null}}catch{return null}}__name(redirectedAncestor,"redirectedAncestor");function sanitizedGitEnv(){const env={...process.env};const drop=new Set([...GIT_ENV_REDIRECTS,...GIT_ENV_CONFIG,...GIT_ENV_EXEC].map(k=>k.toLowerCase()));for(const key of Object.keys(env)){const lower=key.toLowerCase();if(drop.has(lower)||/^git_config_(key|value)_\d+$/.test(lower)){delete env[key]}}env["GIT_NO_REPLACE_OBJECTS"]="1";env["GIT_GRAFT_FILE"]="/dev/null/grafts";return env}__name(sanitizedGitEnv,"sanitizedGitEnv");var MAX_INCLUDE_DEPTH=10;var MAX_INCLUDE_FILES=64;var FILTER_SCREEN_NAMED=12;var SCREEN_KEYS="^filter\\..*\\.(smudge|clean|process)$|^include\\.path$|^includeif\\..*\\.path$";function filterCommandsIn(commonDir,gitDir){const candidates=[join2(commonDir,"config"),join2(gitDir,"config.worktree")];try{for(const entry of readdirSync2(join2(commonDir,"worktrees"))){candidates.push(join2(commonDir,"worktrees",entry,"config.worktree"))}}catch{}const filters=new Set;const unread=new Set;const dangling=new Set;const visited=new Set;const read=__name(file=>{const r=spawnSync("git",["config","--file",file,"-z","--get-regexp",SCREEN_KEYS],{cwd:commonDir,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error){return{unreadable:r.error.code??r.error.message}}if(r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return{unreadable:`git config exited ${r.status}`}}const records=[];for(const rec of r.stdout.split("\0")){if(!rec)continue;const nl=rec.indexOf("\n");records.push(nl===-1?[rec,""]:[rec.slice(0,nl),rec.slice(nl+1)])}return{records}},"read");const visit=__name((file,depth,via)=>{let real;try{real=realpathSync2.native(file)}catch(e){if(via!==null){const code=e?.code;if(code==="ENOENT"){dangling.add(`${via} -> ${file} (missing \u2014 git ignores it)`)}else{unread.add(`${via} -> ${file} (could not be resolved: ${code??"unknown"} \u2014 not screened)`)}}return}if(visited.has(real))return;if(visited.size>=MAX_INCLUDE_FILES){unread.add(`${via??file} -> ${file} (include fan-out past ${MAX_INCLUDE_FILES} files \u2014 not screened)`);return}visited.add(real);try{if(!statSync2(real).isFile()){unread.add(`${via??file} -> ${file} (not a regular file \u2014 not screened)`);return}accessSync(real,constants.R_OK)}catch{unread.add(`${via??file} -> ${file} (could not be read)`);return}if(depth>MAX_INCLUDE_DEPTH){unread.add(`${via} -> ${file} (nested past git's include limit \u2014 not screened)`);return}const r=read(file);if("unreadable"in r){unread.add(`${file} (could not be read: ${r.unreadable})`);return}for(const[key,value]of r.records){if(key.startsWith("filter.")){filters.add(key);continue}let target;if(value.startsWith("~/")){target=`${process.env["HOME"]||homedir()}${sep}${value.slice(2)}`}else if(value.startsWith("~")){unread.add(`${key} -> ${value} (another user's home \u2014 not resolved here)`);continue}else{target=isAbsolute2(value)?value:`${dirname(file)}${sep}${value}`}visit(target,depth+1,`${key} (in ${file})`)}},"visit");for(const candidate of candidates)visit(candidate,0,null);return{filters:[...filters],unread:[...unread],dangling:[...dangling]}}__name(filterCommandsIn,"filterCommandsIn");function describeFilterScreen(hits){const named=hits.slice(0,FILTER_SCREEN_NAMED);const rest=hits.length-named.length;return rest>0?`${named.join(", ")}, and ${rest} more`:named.join(", ")}__name(describeFilterScreen,"describeFilterScreen");function filterBlankEnv(filterKeys){const names=new Set;for(const key of filterKeys){const m=/^filter\.(.+)\.(?:smudge|clean|process)$/.exec(key);if(m)names.add(m[1])}const env={};let n=0;for(const name of names){for(const[key,value]of[["clean",""],["smudge",""],["process",""],["required","false"]]){env[`GIT_CONFIG_KEY_${n}`]=`filter.${name}.${key}`;env[`GIT_CONFIG_VALUE_${n}`]=value;n++}}if(n>0)env["GIT_CONFIG_COUNT"]=String(n);return env}__name(filterBlankEnv,"filterBlankEnv");var UNRESOLVED_REPO="the repository's git directories could not be resolved (git rev-parse failed) \u2014 not screened";function screenForTree(worktree){const discover=__name(flag=>{const r=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return null}return r.stdout.endsWith("\n")?r.stdout.slice(0,-1):r.stdout},"discover");const commonDir=discover("--git-common-dir");const gitDir=discover("--git-dir");if(commonDir===null||gitDir===null)return null;return filterCommandsIn(commonDir,gitDir)}__name(screenForTree,"screenForTree");function localFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread,...screen.dangling]}__name(localFilterCommands,"localFilterCommands");function filterScreenForTree(worktree){return screenForTree(worktree)}__name(filterScreenForTree,"filterScreenForTree");function resolvedContentTransformForTree(worktree){const r=spawnSync("git",["config","--get-regexp","^filter\\..*\\.(smudge|clean|process)$|^core\\.(autocrlf|eol)$"],{cwd:worktree,encoding:"utf8",env:sanitizedGitEnv()});if(r.status!==0||typeof r.stdout!=="string")return false;for(const line of r.stdout.split("\n")){const space=line.indexOf(" ");const key=(space===-1?line:line.slice(0,space)).toLowerCase();const value=space===-1?"true":line.slice(space+1).trim().toLowerCase();if(key.startsWith("filter."))return true;if(key==="core.autocrlf"&&(value==="true"||value==="input")){return true}if(key==="core.eol"&&(value==="crlf"||value==="native"&&process.platform==="win32")){return true}}return false}__name(resolvedContentTransformForTree,"resolvedContentTransformForTree");function checkoutFilterCommands(worktree){const screen=screenForTree(worktree);if(screen===null)return[UNRESOLVED_REPO];return[...screen.filters,...screen.unread]}__name(checkoutFilterCommands,"checkoutFilterCommands");function discardWorktree(cwd,tree){let symlink=false;try{symlink=lstatSync(tree).isSymbolicLink()}catch{}const ownAdminDir=adminDirOf(tree);let sweep;if(!symlink){sweep=spawnSync("git",["worktree","remove","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(sweep.status!==0){spawnSync("git",["worktree","unlock",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()});sweep=spawnSync("git",["worktree","remove","--force","--force",tree],{cwd,encoding:"utf8",env:sanitizedGitEnv()})}}rmSync(tree,{recursive:true,force:true});dropWorktreeRegistration(cwd,tree,ownAdminDir);if(sweep!==void 0&&sweep.status!==0){dropWorktreeRegistration(cwd,tree,null)}return sweep}__name(discardWorktree,"discardWorktree");function dropWorktreeRegistration(cwd,tree,adminDir){if(adminDir!==null){try{rmSync(adminDir,{recursive:true,force:true})}catch{}return}const common=spawnSync("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(common.status!==0||typeof common.stdout!=="string")return;const dir=join2(common.stdout.trim(),"worktrees");let ids;try{ids=readdirSync2(dir)}catch{return}const wanted=samePath(tree);const ownId=basename(resolve(tree));const ownIdPattern=new RegExp(`^${ownId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\d*$`);for(const id of ids){if(!ownIdPattern.test(id))continue;try{const gitdir=readFileSync2(join2(dir,id,"gitdir"),"utf8").trim();const named=dirname(gitdir);if(samePath(named)!==wanted)continue;if(existsSync2(named))continue;rmSync(join2(dir,id),{recursive:true,force:true})}catch{}}}__name(dropWorktreeRegistration,"dropWorktreeRegistration");function adminDirOf(tree){try{const pointer=readFileSync2(join2(tree,".git"),"utf8").trim();const match=/^gitdir:\s*(.+)$/.exec(pointer);if(!match)return null;const dir=resolve(dirname(resolve(tree)),match[1].trim());const back=readFileSync2(join2(dir,"gitdir"),"utf8").trim();return samePath(dirname(back))===samePath(tree)?dir:null}catch{return null}}__name(adminDirOf,"adminDirOf");function samePath(p){const abs=resolve(p);try{return join2(realpathSync2(dirname(abs)),basename(abs))}catch{return abs}}__name(samePath,"samePath");var pipelineExcludesFile=null;function pipelineExcludeArgs(){if(pipelineExcludesFile===null){try{const file=join2(mkdtempSync(join2(tmpdir(),"qwen-review-excludes-")),"excludes").split(sep).join("/");writeFileSync(file,"node_modules/\ndist/\n",{flag:"wx",mode:384});pipelineExcludesFile=file}catch{pipelineExcludesFile=""}}return pipelineExcludesFile===""?[]:["-c",`core.excludesFile=${pipelineExcludesFile}`]}__name(pipelineExcludeArgs,"pipelineExcludeArgs");function inPipelineFootprint(rec){const parts=rec.split("/");for(let i=0;i<parts.length-1;i++){if(parts[i]==="node_modules"||parts[i]==="dist")return true;if(parts[i]===".husky"&&parts[i+1]==="_"&&i+1<parts.length-1)return true}return false}__name(inPipelineFootprint,"inPipelineFootprint");function ignoreSourcesOf(cwd,paths,anchor=[]){const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"check-ignore","-z","-v","--stdin"],{cwd,input:`${paths.join("\0")}\0`,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0&&r.status!==1||typeof r.stdout!=="string"){return null}const fields=r.stdout.split("\0");const rules=new Map;for(let i=0;i+3<fields.length;i+=4){rules.set(fields[i+3],{source:fields[i],pattern:fields[i+2]})}return rules}__name(ignoreSourcesOf,"ignoreSourcesOf");function hidesEverything(pattern){const core=pattern.replace(/^\//,"").replace(/\/$/,"");if(core.length===0)return false;const segments=core.split("/");return core.includes("*")&&segments.every(seg=>/^[*?]+$/.test(seg))}__name(hidesEverything,"hidesEverything");function trackedIgnoreSources(cwd,sources,anchor=[]){const inside=[...sources].filter(s=>s.length>0&&!isAbsolute2(s)&&!s.split("/").some(p=>p===".."));if(inside.length===0)return new Set;const r=spawnSync("git",[...anchor,"ls-files","-z","--",...inside],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(r.error||r.status!==0||typeof r.stdout!=="string"){return new Set}return new Set(r.stdout.split("\0").filter(p=>p.length>0))}__name(trackedIgnoreSources,"trackedIgnoreSources");var RESIDUE_PATH_CAP=12;function worktreeResidue(cwd,cap=RESIDUE_PATH_CAP,expectedHeadSha){try{if(!lstatSync(join2(cwd,".git")).isFile()){return{paths:[],total:0,unmeasured:".git is not a gitfile (a planted repository?) \u2014 a repo stood up at this path answers a clean status for a dirty tree, and the probe cannot tell the two apart"}}}catch{}const root=mountRootFor(cwd);if(root===null){if(mountNullKind(cwd)==="refused"){return{paths:[],total:0,unmeasured:"the path is inside the review temp dir by spelling, but no mount root answered for it \u2014 a redirect or a root that vanished mid-check refused it, and the status below would measure whichever repository the pointer here names"}}}else{const target=resolvedGitDir(cwd);let why;if(target.value!==null){why=untrustedPointer(cwd,target.value,cwd,root)}else{why=target.notARepository?null:"git could not resolve its own git dir"}if(why!==null){return{paths:[],total:0,unmeasured:`the .git gitfile ${why} \u2014 the status below would measure whichever repository it names, and refresh that index through whatever filters it configures`}}}const discover=__name(flag=>{const r2=spawnSync("git",["rev-parse","--path-format=absolute",flag],{cwd,encoding:"utf8",env:sanitizedGitEnv()});if(r2.error||r2.status!==0||typeof r2.stdout!=="string"){return null}return r2.stdout.endsWith("\n")?r2.stdout.slice(0,-1):r2.stdout},"discover");const toplevel=discover("--show-toplevel");const gitDir=discover("--git-dir");const commonDir=discover("--git-common-dir");let isWorktree=false;let anchor=[];let filterBlanks={};try{if(toplevel!==null&&gitDir!==null&&commonDir!==null&&realpathSync2(toplevel)===realpathSync2(cwd)){isWorktree=true;if(lstatSync(cwd).isSymbolicLink()){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${resolve(cwd)}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}const spelled=resolve(cwd);const bound=dirname(commonDir);const redirected=redirectedAncestor(dirname(spelled),bound);if(redirected!==null){return{paths:[],total:0,unmeasured:`the path resolves through a symlink (${redirected}) \u2014 every identity check resolves through it and agrees with itself, while the commands below would measure wherever it points`}}let backpointer=null;try{backpointer=readFileSync2(join2(gitDir,"gitdir"),"utf8").trim()}catch{}if(backpointer===null){return{paths:[],total:0,unmeasured:"the .git gitfile names a repository with no admin entry for this tree \u2014 a standalone repository answering for this path, whose index the commands below would measure"}}let pointsBack=false;try{pointsBack=realpathSync2(dirname(resolve(gitDir,backpointer)))===realpathSync2(cwd)}catch{}if(!pointsBack){return{paths:[],total:0,unmeasured:"the .git gitfile names an admin entry that does not point back at this tree \u2014 the commands below would measure whichever repository it does name"}}anchor=[`--git-dir=${realpathSync2(gitDir)}`,`--work-tree=${realpathSync2(toplevel)}`];if(expectedHeadSha!==void 0){const head=spawnSync("git",[...anchor,"rev-parse","HEAD"],{cwd,encoding:"utf8",env:sanitizedGitEnv()});const got=head.error||head.status!==0||typeof head.stdout!=="string"?null:head.stdout.trim();if(got===null||got.toLowerCase()!==expectedHeadSha.toLowerCase()){return{paths:[],total:0,unmeasured:got===null?"the pinned identity could not read its own HEAD \u2014 the commands below would have measured a repository git cannot read":`the pinned identity is checked out at ${got}, not the fetched PR head ${expectedHeadSha} \u2014 the gitfile names a repository answering for this path, and its index is what the commands below would measure`}}}const screen=filterCommandsIn(commonDir,realpathSync2(gitDir));const notReadToTheBottom=[...screen.unread,...screen.dangling];if(notReadToTheBottom.length>0){return{paths:[],total:0,unmeasured:`the residue measurement would run under repo-local config this screen could not read to the bottom: ${describeFilterScreen(notReadToTheBottom)} \u2014 a content filter reached that way would execute on the index refresh, and a filter the screen cannot see it cannot blank; remove the include, or the file it names, if it is not yours`}}filterBlanks=filterBlankEnv(screen.filters)}}catch{isWorktree=false}if(!isWorktree){return{paths:[],total:0,unmeasured:"the path is not a git worktree (repository discovery walks up into the enclosing checkout)"}}const r=spawnSync("git",[...anchor,...pipelineExcludeArgs(),"-c","core.fsmonitor=","-c","core.hooksPath=/dev/null/no-hooks","status","--porcelain","--untracked-files=all","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:{...sanitizedGitEnv(),...filterBlanks}});if(r.error||r.status!==0||typeof r.stdout!=="string"){const why=r.error?r.error.code??r.error.message:`git status exited ${r.status}`;return{paths:[],total:0,unmeasured:why}}const records=r.stdout.split("\0").filter(rec=>rec.length>0);const paths=[];for(let i=0;i<records.length;i++){const rec=records[i];const status=rec.slice(0,2);paths.push(rec.slice(3));if((status.includes("R")||status.includes("C"))&&i+1<records.length){paths.push(records[++i])}}const others=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","--others","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(others.error||others.status!==0||typeof others.stdout!=="string"){const why=others.error?others.error.code??others.error.message:`git ls-files exited ${others.status}`;return{paths:[],total:0,unmeasured:why}}const seen=new Set(paths);const editedFromHead=new Set(paths);const extras=[];for(const rec of others.stdout.split("\0")){if(rec.length===0||seen.has(rec))continue;if(inPipelineFootprint(rec))continue;seen.add(rec);extras.push(rec)}if(extras.length>0){const hiddenBy=ignoreSourcesOf(cwd,extras,anchor);if(hiddenBy===null){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the ignore rules hiding this tree's untracked files could not be attributed, so `git status` cannot be trusted to have seen them"}}const fromTheCommit=trackedIgnoreSources(cwd,new Set([...hiddenBy.values()].map(rule=>rule.source)),anchor);for(const rec of extras){const rule=hiddenBy.get(rec);if(rule!==void 0&&fromTheCommit.has(rule.source)&&!editedFromHead.has(rule.source)&&!hidesEverything(rule.pattern)){continue}paths.push(rec)}}const stage=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-s","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(stage.error||stage.status!==0||typeof stage.stdout!=="string"){const why=stage.error?stage.error.code??stage.error.message:`git ls-files exited ${stage.status}`;return{paths:[],total:0,unmeasured:why}}const blind=stage.stdout.split("\0").filter(rec=>rec.startsWith("160000 ")).map(rec=>rec.slice(rec.indexOf(" ")+1)).filter(gitlink=>{if(gitlink.includes("\uFFFD"))return true;try{return readdirSync2(join2(cwd,gitlink)).length>0}catch(err){return err.code!=="ENOENT"}});if(blind.length>0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"git status cannot see inside the committed submodule path(s) "+blind.join(", ")}}const bits=spawnSync("git",[...anchor,"-c","core.fsmonitor=","ls-files","-v","-z"],{cwd,encoding:"utf8",maxBuffer:64*1024*1024,env:sanitizedGitEnv()});if(bits.error||bits.status!==0||typeof bits.stdout!=="string"){const why=bits.error?bits.error.code??bits.error.message:`git ls-files exited ${bits.status}`;return{paths:paths.slice(0,cap),total:paths.length,unmeasured:why}}if(bits.stdout.split("\0").some(rec=>/^[a-zS]/.test(rec))){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the index carries skip-worktree or assume-unchanged bits, so `git status` cannot see edits to the tracked files they cover"}}if(expectedHeadSha===void 0){return{paths:paths.slice(0,cap),total:paths.length,unmeasured:"the caller brought no record of the commit this tree must hold, and a status measured through an unanchored identity would certify whichever index the .git gitfile names \u2014 a forged pair answers clean \u2014 so the measurement is refused rather than certified"}}return{paths:paths.slice(0,cap),total:paths.length}}__name(worktreeResidue,"worktreeResidue");function exposeDependencies(probeTree,dependencyRoot,opts={}){const done={linked:0,failed:0,alreadyPresent:false,selfLinked:0};if(probeTree===dependencyRoot)return done;let members=[];try{const graph=readWorkspacePackages(dependencyRoot);members=[...graph.packages.map(p=>p.dir),...graph.skipped]}catch{}const memberSources=members.map(dir=>({dir,source:containedIn(dependencyRoot,dir)})).filter(m=>{if(m.source===null)return true;try{return realpathSync2(m.source)!==realpathSync2(dependencyRoot)}catch{return true}});let rootNm=null;try{const nm=join2(dependencyRoot,"node_modules");if(lstatSync(nm).isDirectory())rootNm=realpathSync2(nm)}catch{}const containment={rootNm,selfLinks:new Set(memberSources.flatMap(m=>m.source===null?[]:[m.source]))};farmNodeModules(dependencyRoot,probeTree,done,containment,opts.rebuild===true);const owned=new Set([join2(probeTree,"node_modules")]);for(const{dir,source}of memberSources){const target=containedIn(probeTree,dir);if(!source||!target){if(existsSync2(join2(dependencyRoot,dir)))done.failed++;continue}if(!existsSync2(target))continue;owned.add(join2(target,"node_modules"));try{farmNodeModules(source,target,done,containment,opts.rebuild===true)}catch{done.failed++}}if(opts.rebuild===true){for(const path of[...owned]){try{owned.add(realpathSync2(path))}catch{}}removeUnownedNodeModules(probeTree,owned,done)}return done}__name(exposeDependencies,"exposeDependencies");function removeUnownedNodeModules(tree,owned,done){const inTreeLinks=[];const walk=__name(dir=>{let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{done.failed++;return}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full)){try{rmSync(full,{recursive:true,force:true})}catch{done.failed++}}continue}if(entry.name===".git")continue;if(entry.isSymbolicLink()){try{const real=realpathSync2(full);const root=realpathSync2(tree);if(!statSync2(full).isDirectory()){}else if(real===root||real.startsWith(root+sep)){inTreeLinks.push(real)}else{done.failed++}}catch{}continue}if(!entry.isDirectory())continue;walk(full)}},"walk");walk(tree);for(const real of inTreeLinks){if(isOwned(owned,real))continue;if(holdsNodeModules(real,owned))done.failed++}}__name(removeUnownedNodeModules,"removeUnownedNodeModules");function isOwned(owned,path){if(owned.has(path))return true;try{return owned.has(realpathSync2(path))}catch{return false}}__name(isOwned,"isOwned");function holdsNodeModules(dir,owned){let entries;try{entries=readdirSync2(dir,{withFileTypes:true})}catch{return false}for(const entry of entries){const full=join2(dir,entry.name);if(entry.name.toLowerCase()==="node_modules"){if(!isOwned(owned,full))return true;continue}if(entry.isSymbolicLink()||!entry.isDirectory())continue;if(entry.name===".git")continue;if(holdsNodeModules(full,owned))return true}return false}__name(holdsNodeModules,"holdsNodeModules");function containedIn(root,dir){try{const base=realpathSync2(resolve(root));const full=resolve(base,dir);const real=existsSync2(full)?realpathSync2(full):full;return real===base||real.startsWith(base+sep)?real:null}catch{return null}}__name(containedIn,"containedIn");var FARM_MARKER=".qwen-review-farm";function farmLinkVerdict(real,sourceNm,containment){if(insideDir(sourceNm,real))return"internal";if(containment.rootNm!==null&&insideDir(containment.rootNm,real)){return"internal"}for(const member of containment.selfLinks){if(insideDir(member,real))return"self"}return null}__name(farmLinkVerdict,"farmLinkVerdict");function insideDir(base,real){return real===base||real.startsWith(base+sep)}__name(insideDir,"insideDir");function marksOurFarm(target,sourceDir){try{return readFileSync2(join2(target,FARM_MARKER),"utf8").trim()===resolve(sourceDir)}catch{return false}}__name(marksOurFarm,"marksOurFarm");function farmNodeModules(sourceDir,targetDir,done,containment,rebuild=false){const source=join2(sourceDir,"node_modules");const target=join2(targetDir,"node_modules");if(!existsSync2(source)){if(rebuild){try{lstatSync(target);rmSync(target,{recursive:true,force:true})}catch(err){if(err.code!=="ENOENT")done.failed++}}return}try{if(!lstatSync(source).isDirectory()){done.failed++;return}}catch{done.failed++;return}let sourceNm;try{sourceNm=realpathSync2(source)}catch{done.failed++;return}let targetPresent=true;try{lstatSync(target)}catch{targetPresent=false}if(targetPresent){if(!rebuild&&marksOurFarm(target,sourceDir)){done.alreadyPresent=true;return}try{rmSync(target,{recursive:true,force:true})}catch{done.failed++;return}}try{mkdirSync(target)}catch{done.failed++;return}const linkType=process.platform==="win32"?"junction":"dir";let entries;try{entries=readdirSync2(source,{withFileTypes:true})}catch{done.failed++;return}const before=done.linked;for(const entry of entries){if(entry.name===".vite"||entry.name===".vite-temp")continue;const sourceEntry=join2(source,entry.name);const targetEntry=join2(target,entry.name);let sourceStats;try{sourceStats=lstatSync(sourceEntry)}catch{done.failed++;continue}if(!sourceStats.isDirectory()&&!sourceStats.isSymbolicLink()){continue}if(sourceStats.isSymbolicLink()){let real;try{real=realpathSync2(sourceEntry)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(sourceEntry).isDirectory())continue}catch{done.failed++;continue}}if(entry.name.startsWith("@")){let pkgs;try{mkdirSync(targetEntry);pkgs=readdirSync2(sourceEntry)}catch{done.failed++;continue}for(const pkg of pkgs){const scopedSource=join2(sourceEntry,pkg);let real;try{real=realpathSync2(scopedSource)}catch{done.failed++;continue}const verdict=farmLinkVerdict(real,sourceNm,containment);if(verdict===null){done.failed++;continue}if(verdict==="self")done.selfLinked++;try{if(!statSync2(scopedSource).isDirectory())continue}catch{done.failed++;continue}try{symlinkSync(scopedSource,join2(targetEntry,pkg),linkType);done.linked++}catch{done.failed++}}}else{try{symlinkSync(sourceEntry,targetEntry,linkType);done.linked++}catch{done.failed++}}}if(done.linked>before){try{writeFileSync(join2(target,FARM_MARKER),`${resolve(sourceDir)}
|
|
4
4
|
`)}catch{}}}__name(farmNodeModules,"farmNodeModules");function worktreeCreateFailureDetail(label,err,sweepStderr){const sweepErr=sweepStderr.trim();return`${label} worktree could not be created: ${err instanceof Error?err.message:String(err)}`+(sweepErr?` (stale-tree sweep also reported: ${sweepErr})`:"")}__name(worktreeCreateFailureDetail,"worktreeCreateFailureDetail");import{existsSync as existsSync3,lstatSync as lstatSync2,realpathSync as realpathSync3,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,resolve as resolve2}from"node:path";var GIT_TIMEOUT_MS=12e4;function gitOpts(){return{timeout:GIT_TIMEOUT_MS,env:{...sanitizedGitEnv(),GIT_TERMINAL_PROMPT:"0"}}}__name(gitOpts,"gitOpts");var trustedLaunchDir=null;function kernelCwd(){try{const r=spawnSync2("/bin/pwd",["-P"],{encoding:"utf8",timeout:5e3,env:sanitizedGitEnv()});if(r.error||r.status!==0||!r.stdout)return null;return r.stdout.replace(/\n$/,"")}catch{return null}}__name(kernelCwd,"kernelCwd");function launchDirRefusal(){const cwd=process.cwd();if(trustedLaunchDir===cwd)return null;if(!insideReviewTmpLexically(cwd)){trustedLaunchDir=cwd;return null}if(process.platform!=="win32"){const kernel=kernelCwd();if(kernel===null){return`the kernel-resolved working directory could not be determined (cwd ${cwd}), so where a command run from here would land is unmeasured`}if(!insideReviewTmpLexically(kernel)){return`the process's working directory was renamed mid-run: the spelling ${cwd} is inside the review temp dir but the kernel reports ${kernel} \u2014 where every command would actually run`}let cachedReal;try{cachedReal=realpathSync3(cwd)}catch{cachedReal=null}if(cachedReal!==kernel){return`the process's working directory spelling ${cwd} resolves to ${cachedReal??"a path that no longer exists"} while the kernel reports ${kernel}: a rename mid-run split them, and every command runs at the kernel's answer`}return untrustedRepositoryFrom(kernel)}return untrustedRepositoryFrom(cwd)}__name(launchDirRefusal,"launchDirRefusal");function assertTrustedLaunchDir(){const refusal=launchDirRefusal();if(refusal!==null){throw new Error(`refusing to run git from this directory: ${refusal}. The command would resolve through that pointer and act on whatever repository it names. Run the review from a checkout outside the review temp dir.`)}}__name(assertTrustedLaunchDir,"assertTrustedLaunchDir");function git(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(git,"git");function gitWithEnv(extraEnv,args){assertTrustedLaunchDir();const opts=gitOpts();return execFileSync("git",args,{...opts,env:{...opts.env,...extraEnv},maxBuffer:512*1024*1024,encoding:"utf8"}).replace(/\r\n/g,"\n").trim()}__name(gitWithEnv,"gitWithEnv");function gitWithInput(input,args){return gitWithInputRaw(input,args).replace(/\r\n/g,"\n").trim()}__name(gitWithInput,"gitWithInput");function gitWithInputRaw(input,args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),encoding:"utf8",input,maxBuffer:512*1024*1024})}__name(gitWithInputRaw,"gitWithInputRaw");function gitOpt(...args){return gitProbe(...args).out}__name(gitOpt,"gitOpt");function gitProbe(...args){try{const refusal=launchDirRefusal();if(refusal!==null)return{out:null,status:null,refusal};return{out:execFileSync("git",args,{...gitOpts(),encoding:"utf8",stdio:["ignore","pipe","pipe"]}).replace(/\r\n/g,"\n").trim(),status:0,refusal:null}}catch(err){const status=err.status;return{out:null,status:typeof status==="number"?status:null,refusal:null}}}__name(gitProbe,"gitProbe");function repoRoot(){const first=git("worktree","list","--porcelain").split("\n")[0]??"";if(!first.startsWith("worktree ")){throw new Error(`cannot find the main worktree in: ${first}`)}return first.slice("worktree ".length)}__name(repoRoot,"repoRoot");function refExists(ref){return gitOpt("rev-parse","--verify","--quiet",ref)!==null}__name(refExists,"refExists");function worktreeReleaseResult(existed,stillThere,removeError){const freed=existed&&!stillThere;if(!existed||freed){return{existed,freed,reason:void 0}}return{existed,freed,reason:removeError?removeError instanceof Error?removeError.message:String(removeError):"the path is still there after `git worktree remove --force` and `rm -rf`"}}__name(worktreeReleaseResult,"worktreeReleaseResult");function releaseWorktree(worktreePath2){let redirected;try{redirected=redirectedAncestor(dirname2(resolve2(worktreePath2)))}catch(err){return worktreeReleaseResult(true,true,err)}if(redirected!==null){return worktreeReleaseResult(true,true,new Error(`refusing to release through a symlink: ${redirected} is a symlink, so the removal would land wherever it points`))}try{if(lstatSync2(worktreePath2).isSymbolicLink()){let removeError2;try{rmSync2(worktreePath2,{force:true})}catch(e){removeError2=e}const pruned2=gitProbe("worktree","prune");let stillThere2=false;try{lstatSync2(worktreePath2);stillThere2=true}catch{}return worktreeReleaseResult(true,stillThere2||pruned2.refusal!==null||pruned2.status===null,removeError2??refusalError(pruned2.refusal)??(pruned2.status===null?couldNotRunError():void 0))}}catch{}const existed=existsSync3(worktreePath2);let removeError;const removed=existed?gitProbe("worktree","remove",worktreePath2,"--force"):null;if(existed){try{rmSync2(worktreePath2,{recursive:true,force:true})}catch(e){removeError=e}}const pruned=gitProbe("worktree","prune");const refusal=removed?.refusal??pruned.refusal;const couldNotRun=removed?.status!==0&&pruned.status===null;const stillThere=existsSync3(worktreePath2);return worktreeReleaseResult(existed,stillThere||existed&&couldNotRun,removeError??(couldNotRun?refusalError(refusal)??couldNotRunError():void 0))}__name(releaseWorktree,"releaseWorktree");function couldNotRunError(){return new Error('the `git worktree prune` that frees the registration and the branch could not be run at all (a spawn failure or the timeout kill), so both survive \u2014 the next `git worktree add` over the path will still fail with "missing but already registered". Re-run `qwen review cleanup`.')}__name(couldNotRunError,"couldNotRunError");function refusalError(refusal){if(refusal===null)return void 0;return new Error(`git could not run from this directory \u2014 ${refusal}. The directory is cleared but this worktree's registration and branch were not, so the next \`git worktree add\` over it will still fail. Run \`qwen review cleanup\` from a checkout outside the review temp dir.`)}__name(refusalError,"refusalError");function gitRaw(...args){assertTrustedLaunchDir();return execFileSync("git",args,{...gitOpts(),maxBuffer:512*1024*1024,stdio:["ignore","pipe","pipe"]})}__name(gitRaw,"gitRaw");function gitRawTolerateDiff(...args){try{return gitRaw(...args)}catch(err){const e=err;if(e.status===1&&e.stdout&&e.stdout.length>0)return e.stdout;throw err}}__name(gitRawTolerateDiff,"gitRawTolerateDiff");function assertWritableOutPath(out){if(typeof out!=="string"){throw new TypeError(Array.isArray(out)?"--out must be given once, as a file path":"--out must name a file path")}if(out.trim()===""){throw new TypeError("--out must name a file path")}if(/[/\\]$/.test(out.trim())){throw new TypeError(`--out names a directory, not a file: ${out}`)}const resolved=resolve3(out);if(existsSync4(resolved)&&statSync3(resolved).isDirectory()){throw new TypeError(`--out names a directory, not a file: ${out}`)}}__name(assertWritableOutPath,"assertWritableOutPath");var REVIEW_TMP_DIR=join3(".qwen","tmp");var RETIRED_REVIEW_LEASE_DIR=join3(".qwen","review-leases");var REVIEW_TRUST_STATE_DIR="review-state";var REVIEWS_DIR=join3(".qwen","reviews");var REVIEW_CACHE_DIR=join3(".qwen","review-cache");function outermostReviewRepositoryRoot(repositoryRoot){const resolved=resolve3(repositoryRoot);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=(resolved+sep2).indexOf(marker);return at<0?resolved:resolved.slice(0,at)}__name(outermostReviewRepositoryRoot,"outermostReviewRepositoryRoot");function canonicalReviewRepositoryRoot(repositoryRoot){let canonical=outermostReviewRepositoryRoot(repositoryRoot);try{canonical=realpathSync4.native(canonical)}catch(error){if(error.code!=="ENOENT")throw error}canonical=outermostReviewRepositoryRoot(canonical);return canonical}__name(canonicalReviewRepositoryRoot,"canonicalReviewRepositoryRoot");function reviewTrustStateDir(repositoryRoot){const digest=getProjectHash(canonicalReviewRepositoryRoot(repositoryRoot));return join3(Storage.getGlobalQwenDir(),REVIEW_TRUST_STATE_DIR,digest)}__name(reviewTrustStateDir,"reviewTrustStateDir");function reviewRepositoryRootForWorktree(worktree){const resolved=resolve3(worktree);const marker=`${sep2}${REVIEW_TMP_DIR}${sep2}`;const at=resolved.indexOf(marker);if(at<0){throw new Error(`cannot place the base-tree trust artifact for ${worktree}: the worktree is not shaped like <root>/.qwen/tmp/<name>, so there is no host-side review directory to key it under`)}return resolved.slice(0,at)}__name(reviewRepositoryRootForWorktree,"reviewRepositoryRootForWorktree");var GENERATED_WORKFLOWS_SUBDIR=join3("workflows","generated");var REVIEW_WORKFLOWS_SUBDIR="review";var REVIEW_WORKFLOW_PREFIX="qwen-review-";var GeneratedWorkflowDirUnavailableError=class extends Error{static{__name(this,"GeneratedWorkflowDirUnavailableError")}};function projectDirFromEnv(env){const projectDir=env["QWEN_CODE_PROJECT_DIR"]?.trim();if(!projectDir){throw new GeneratedWorkflowDirUnavailableError("the CLI did not export QWEN_CODE_PROJECT_DIR, so there is no directory the Workflow tool would load a generated script from. Run this command from inside a qwen session.")}return projectDir}__name(projectDirFromEnv,"projectDirFromEnv");function reviewSessionDirName(session){const digest=createHash2("sha256").update(session).digest("hex").slice(0,8);return`${sanitizeFilenameComponent(session)}-${digest}`}__name(reviewSessionDirName,"reviewSessionDirName");function reviewWorkflowsDir(env=process.env){const session=env["QWEN_CODE_SESSION_ID"]?.trim();return join3(projectDirFromEnv(env),GENERATED_WORKFLOWS_SUBDIR,REVIEW_WORKFLOWS_SUBDIR,session?reviewSessionDirName(session):"no-session")}__name(reviewWorkflowsDir,"reviewWorkflowsDir");function ensureWritableReviewWorkflowsDir(env=process.env){const projectDir=projectDirFromEnv(env);const dir=reviewWorkflowsDir(env);const root=join3(projectDir,GENERATED_WORKFLOWS_SUBDIR);for(const component of[root,join3(root,REVIEW_WORKFLOWS_SUBDIR),dir]){let isLink=false;try{isLink=lstatSync3(component).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`refusing to write a generated review script through the symlinked directory '${component}' \u2014 it would land outside the generated-workflows root the Workflow loader trusts.`)}}mkdirSync2(dir,{recursive:true});const realDir=realpathSync4(dir);const realRoot=realpathSync4(root);if(realDir!==realRoot&&!realDir.startsWith(realRoot+sep2)){throw new Error(`refusing to write a generated review script: the canonical session directory '${realDir}' escapes the canonical generated-workflows root '${realRoot}'.`)}return dir}__name(ensureWritableReviewWorkflowsDir,"ensureWritableReviewWorkflowsDir");function reviewWorkflowScriptPath(planPath,script,env=process.env){const resolved=resolve3(planPath);let canonical=resolved;try{canonical=realpathSync4(resolved)}catch{}const digest=createHash2("sha256").update(canonical).digest("hex").slice(0,10);const contentDigest=createHash2("sha256").update(script).digest("hex");return join3(reviewWorkflowsDir(env),`${REVIEW_WORKFLOW_PREFIX}${digest}-${contentDigest}.js`)}__name(reviewWorkflowScriptPath,"reviewWorkflowScriptPath");var LEASE_PREFIX="qwen-review-lease-";var PARSE_ARGS_REPORT=join3(REVIEW_TMP_DIR,"qwen-review-parse-args.json");function lastReviewEffortPath(projectRoot,sessionProjectDir){const owner=sessionProjectDir?.trim()?resolve3(sessionProjectDir):new Storage(projectRoot).getProjectDir();return join3(owner,"review-last-effort")}__name(lastReviewEffortPath,"lastReviewEffortPath");function worktreePath(prNumber){return join3(REVIEW_TMP_DIR,`review-pr-${prNumber}`)}__name(worktreePath,"worktreePath");function probeWorktreePath(worktree){return`${resolve3(worktree)}-probe`}__name(probeWorktreePath,"probeWorktreePath");function baseWorktreePath(worktree){return`${resolve3(worktree)}-base`}__name(baseWorktreePath,"baseWorktreePath");var SCRATCH_INFIX="-scratch-";function scratchWorktreePath(worktree,label){const safe=scratchLabel(label);if(!safe){throw new TypeError(`scratch label ${JSON.stringify(label)} keeps no path-safe character (A-Za-z0-9._-); a tree cannot be named for it`)}return`${resolve3(worktree)}${SCRATCH_INFIX}${safe}`}__name(scratchWorktreePath,"scratchWorktreePath");function scratchWorktreePrefix(worktree){return`${resolve3(worktree)}${SCRATCH_INFIX}`}__name(scratchWorktreePrefix,"scratchWorktreePrefix");function scratchLabel(label){return label.replace(/[^A-Za-z0-9._-]/g,"_").replace(/\.\.+/g,"_").replace(/^[._-]+/,"").slice(0,64)}__name(scratchLabel,"scratchLabel");function reviewBranch(prNumber){return`qwen-review/pr-${prNumber}`}__name(reviewBranch,"reviewBranch");function tmpFile(target,suffix){return join3(REVIEW_TMP_DIR,`qwen-review-${safeTarget(target)}-${suffix}`)}__name(tmpFile,"tmpFile");function tmpPrefix(target){return`qwen-review-${safeTarget(target)}-`}__name(tmpPrefix,"tmpPrefix");function ensureReviewTmpDir(command){for(const dir of[dirname3(REVIEW_TMP_DIR),REVIEW_TMP_DIR]){let isLink=false;try{isLink=lstatSync3(dir).isSymbolicLink()}catch(err){if(err.code!=="ENOENT")throw err;break}if(isLink){throw new Error(`${command}: ${dir} is a symbolic link \u2014 every file this review writes (plan, diff, candidate, stop sidecar, worktree) would land wherever it points, and the plan would be read back from there. Refusing to run; nothing here can tell your own link from a committed one. If it is YOURS \u2014 this directory holds a full worktree per PR, so redirecting it onto other storage is a reasonable thing to have done \u2014 neither ${dirname3(REVIEW_TMP_DIR)} nor ${REVIEW_TMP_DIR} can be one: redirect the checkout itself, or a directory the review never names.`)}}let listing;try{listing=gitRaw("ls-files","-s","-z").toString("utf8")}catch(err){if(insideRepository()){throw new Error(`${command}: could not list the tracked entries under ${REVIEW_TMP_DIR} (${inertText(err.message,2e3)}) \u2014 refusing to run rather than write through a link the listing might have named. Lightweight mode (\`fetch-diff\`) is the one flow that could otherwise proceed without git; every other one needs it for the diff itself.`)}listing=""}const scratch=REVIEW_TMP_DIR.split(sep2).join("/").toLowerCase();const planted=listing.split("\0").find(entry=>{const gitlink=entry.startsWith("160000 ");if(!entry.startsWith("120000 ")&&!gitlink)return false;const path=entry.slice(entry.indexOf(" ")+1).toLowerCase();if(path===dirname3(scratch)||path===scratch)return true;if(!path.startsWith(`${scratch}/`))return false;return!gitlink||!isReviewWorktreeName(path.slice(scratch.length+1))});if(planted!==void 0){const path=planted.slice(planted.indexOf(" ")+1);const what=planted.startsWith("160000 ")?"a submodule":"a symbolic link";throw new Error(`${command}: the workspace tracks ${what} at ${inertText(path)} \u2014 on the scratch directory ${REVIEW_TMP_DIR} or a path through it \u2014 and a plain write to that name would follow it out of the tree. Refusing to run; remove it from the index AND the working tree (\`git rm -f -- <path>\`) and retry.`)}const onDisk=roundOwnedLinkOnDisk(command);if(onDisk!==null){throw new Error(`${command}: ${inertText(onDisk)} is a symbolic link on disk, at a name this review writes \u2014 a plain write to it would follow the link out of the tree. Refusing to run; delete the link and retry.`)}mkdirSync2(REVIEW_TMP_DIR,{recursive:true})}__name(ensureReviewTmpDir,"ensureReviewTmpDir");function roundOwnedLinkOnDisk(command){const list=__name(dir=>{try{return readdirSync3(dir,{withFileTypes:true})}catch(err){const code=err.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw new Error(`${command}: could not list ${inertText(dir)} (${inertText(err.message)}) \u2014 refusing to run rather than write through a link the listing might have named.`)}},"list");const walk=__name(dir=>{for(const entry of list(dir)){const path=join3(dir,entry.name);if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}return null},"walk");for(const entry of list(REVIEW_TMP_DIR)){const path=join3(REVIEW_TMP_DIR,entry.name);const name=entry.name.toLowerCase();if(name.startsWith("qwen-review-")){if(entry.isSymbolicLink())return path;if(entry.isDirectory()){const hit=walk(path);if(hit!==null)return hit}}else if(isReviewWorktreeName(name)&&entry.isSymbolicLink()){return path}}return null}__name(roundOwnedLinkOnDisk,"roundOwnedLinkOnDisk");function commandPrefixed(command,message){const prefix=`${command}: `;return message.startsWith(prefix)?message:`${prefix}${message}`}__name(commandPrefixed,"commandPrefixed");function writesIntoReviewTmp(out){const scratch=resolve3(REVIEW_TMP_DIR).toLowerCase();const target=resolve3(out).toLowerCase();return target===scratch||target.startsWith(scratch+sep2)}__name(writesIntoReviewTmp,"writesIntoReviewTmp");function isReviewWorktreeName(name){return/^review-pr-\d+(-probe|-base|-scratch-[^/]*)?$/.test(name)}__name(isReviewWorktreeName,"isReviewWorktreeName");function insideRepository(){let dir=resolve3(".");for(;;){if(existsSync4(join3(dir,".git")))return true;const parent=dirname3(dir);if(parent===dir)return false;dir=parent}}__name(insideRepository,"insideRepository");function inertPath(p){return p.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\u2500`]+/gu," ")}__name(inertPath,"inertPath");function canonicalise(abs){const walked=[];let cur=abs;for(;;){try{const real=realpathSync4(cur);return walked.length===0?real:join3(real,...walked.reverse())}catch{const parent=resolve3(cur,"..");if(parent===cur)return abs;walked.push(cur.slice(parent.length).replace(sep2==="/"?/^\/+/:/^[\\/]+/,""));cur=parent}}}__name(canonicalise,"canonicalise");function repoRelativeOf(repoRoot2,file,from=process.cwd()){const abs=canonicalise(resolve3(from,file));const rel=relative2(repoRoot2,abs);const escapes=rel===".."||rel.startsWith(".."+sep2)||isAbsolute3(rel);return{rel:sep2==="/"?rel:rel.split(sep2).join("/"),abs,escapes}}__name(repoRelativeOf,"repoRelativeOf");function assertUnredirectedParent(target,what,command){const parent=resolve3(dirname3(target));let real;try{real=realpathSync4(parent)}catch(err){throw new Error(`${command}: cannot resolve the ${what} directory ${inertText(parent)}: `+inertText(err.message))}if(real!==parent){throw new Error(`${command}: the ${what} directory ${inertText(parent)} resolves to ${inertText(real)} \u2014 a symlink in the path would redirect this write outside the tree it names. Refusing.`)}}__name(assertUnredirectedParent,"assertUnredirectedParent");export{safeTarget,CONTROL,inertText,assertWritableOutPath,REVIEW_TMP_DIR,RETIRED_REVIEW_LEASE_DIR,REVIEWS_DIR,REVIEW_CACHE_DIR,reviewTrustStateDir,reviewRepositoryRootForWorktree,ensureWritableReviewWorkflowsDir,reviewWorkflowScriptPath,LEASE_PREFIX,PARSE_ARGS_REPORT,lastReviewEffortPath,worktreePath,probeWorktreePath,baseWorktreePath,scratchWorktreePath,scratchWorktreePrefix,scratchLabel,reviewBranch,tmpFile,tmpPrefix,ensureReviewTmpDir,commandPrefixed,writesIntoReviewTmp,inertPath,repoRelativeOf,assertUnredirectedParent,raiseHeap,raiseNpmHeap,heapBannerIn,ranOutOfHeap,killedFromOutside,isWorkspaceMember,workspaceDirFor,isNegationExcluded,hasUnmodeledWorkspaceGlob,readWorkspaceGlobs,readRootPackage,scriptFansOut,chainsCommands,rootBuildFanOutScript,declaredBuildHeapMb,readWorkspacePackages,affectedWorkspaces,dependencyClosure,reverseDependencyClosure,buildSetFor,mountRootFor,untrustedRepositoryFrom,untrustedGitfile,redirectedAncestor,sanitizedGitEnv,describeFilterScreen,filterBlankEnv,localFilterCommands,filterScreenForTree,resolvedContentTransformForTree,checkoutFilterCommands,discardWorktree,RESIDUE_PATH_CAP,worktreeResidue,exposeDependencies,worktreeCreateFailureDetail,GIT_TIMEOUT_MS,git,gitWithEnv,gitWithInput,gitWithInputRaw,gitOpt,gitProbe,repoRoot,refExists,releaseWorktree,gitRaw,gitRawTolerateDiff};
|
|
5
5
|
/**
|
|
6
6
|
* @license
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{t}from"./chunk-NO7VTKRL.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-
|
|
3
|
+
import{t}from"./chunk-NO7VTKRL.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-7XQ5D34E.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{isMediaPolicyToolHiddenFromModel}from"./chunk-S2ZKZXHX.js";import{DiscoveredMCPTool,uiTelemetryService}from"./chunk-ZWPSBU7K.js";import{getAllMemoryFilenames}from"./chunk-Y6HHV4LC.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{DEFAULT_TOKEN_LIMIT}from"./chunk-GOR7FFVE.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,buildAvailableSkillsReminder,getStartupContextLength,isSkillListingReminder}from"./chunk-B3ZFUGTC.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();import*as fs from"node:fs/promises";var EXTENSION_REF_PREFIX="ext:";var EXTENSION_CONTEXT_BUDGET=2e5;var EXTENSION_CONTEXT_FILE_CAP=5e4;function parseExtensionRef(pathName){if(!pathName.startsWith(EXTENSION_REF_PREFIX))return null;const name=pathName.slice(EXTENSION_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseExtensionRef,"parseExtensionRef");function buildExtensionRef(extensionName){return`${EXTENSION_REF_PREFIX}${extensionName}`}__name(buildExtensionRef,"buildExtensionRef");function matchExtensionByRef(name,extensions){const lower=name.toLowerCase();return extensions.find(ext=>ext.name.toLowerCase()===lower||ext.config.name.toLowerCase()===lower)}__name(matchExtensionByRef,"matchExtensionByRef");var BIDI_CONTROL_RE=/[]/g;function sanitizeDisplayText(raw){const stripped=stripTerminalControlSequences(raw).replace(BIDI_CONTROL_RE,"").replace(/\s+/g," ").trim();return stripped.length>0?stripped:null}__name(sanitizeDisplayText,"sanitizeDisplayText");function getSanitizedExtensionDisplayName(extension){return sanitizeDisplayText(extension.displayName||extension.name)||extension.name}__name(getSanitizedExtensionDisplayName,"getSanitizedExtensionDisplayName");function buildExtensionContextText(extension){const displayName=getSanitizedExtensionDisplayName(extension);const lines=[];lines.push(`--- Extension: ${displayName} (untrusted third-party content) ---`);if(extension.config.description){const desc=sanitizeDisplayText(extension.config.description);if(desc){lines.push(desc);lines.push("")}}const capabilities=[];if(extension.skills&&extension.skills.length>0){const skillNames=extension.skills.map(s=>sanitizeDisplayText(qualifySkillName(extension.name,s.name))||s.name).join(", ");capabilities.push(`- Skills: ${skillNames} (invoke via /<skill-name>)`)}if(extension.mcpServers&&Object.keys(extension.mcpServers).length>0){const serverNames=Object.keys(extension.mcpServers).map(n=>sanitizeDisplayText(n)||n).join(", ");capabilities.push(`- MCP Servers: ${serverNames}`)}if(extension.agents&&extension.agents.length>0){const agentNames=extension.agents.map(a=>sanitizeDisplayText(a.name)||a.name).join(", ");capabilities.push(`- Agents: ${agentNames}`)}if(capabilities.length>0){lines.push("Available capabilities from this extension:");lines.push(...capabilities);lines.push("")}lines.push(`--- End Extension: ${displayName} ---`);return lines.join("\n")}__name(buildExtensionContextText,"buildExtensionContextText");async function buildExtensionMentionContext(extension,options){let contextText=buildExtensionContextText(extension);let remainingBudget=options.remainingBudget;if(extension.contextFiles.length===0){return{text:contextText,remainingBudget}}const fileReads=await Promise.allSettled(extension.contextFiles.map(async contextFilePath=>{let realPath;let realExtPath;try{realPath=await fs.realpath(contextFilePath);realExtPath=await fs.realpath(extension.path)}catch{options.onDebugMessage?.(`Skipping unreadable context file: ${contextFilePath}`);return null}if(!isSubpath(realExtPath,realPath)){options.onDebugMessage?.(`Skipping context file outside extension directory: ${contextFilePath}`);return null}return fs.readFile(realPath,{encoding:"utf-8",signal:options.signal})}));for(let i=0;i<fileReads.length;i++){const outcome=fileReads[i];if(outcome.status==="rejected"){options.onDebugMessage?.(`Failed to read extension context file ${extension.contextFiles[i]}: ${getErrorMessage(outcome.reason)}`);continue}const content=outcome.value;if(!content||!content.trim())continue;if(remainingBudget<=0){options.onDebugMessage?.("Extension context budget exhausted, skipping remaining files.");break}const cap=Math.min(EXTENSION_CONTEXT_FILE_CAP,remainingBudget);const cappedContent=content.length>cap?content.slice(0,cap)+"\n... (truncated)":content;contextText+=`
|
|
4
4
|
|
|
5
5
|
${cappedContent}`;remainingBudget-=cappedContent.length}return{text:contextText,remainingBudget}}__name(buildExtensionMentionContext,"buildExtensionMentionContext");function currentTier(tokens,thresholds){if(tokens>=thresholds.hard)return"hard";if(tokens>=thresholds.auto)return"auto";if(tokens>=thresholds.warn)return"warn";return"safe"}__name(currentTier,"currentTier");function extensionContextFileOwners(config,workingDir){const owners=new Map;for(const extension of config.getActiveExtensions?.()??[]){const displayName=getSanitizedExtensionDisplayName(extension);for(const contextFile of extension.contextFiles??[]){const absolutePath=path.resolve(workingDir,contextFile);const fileLabel=formatContextFileDisplayPath(absolutePath,extension.path);owners.set(absolutePath,`${t("Extension")}: ${displayName} \xB7 ${fileLabel}`)}}return owners}__name(extensionContextFileOwners,"extensionContextFileOwners");function parseMemoryFiles(memoryContent,workingDir,extensionOwners=new Map,admissionRoot=workingDir){if(!memoryContent||memoryContent.trim().length===0)return[];const results=[];const root=path.resolve(admissionRoot);const globalDir=path.resolve(Storage.getGlobalQwenDir());const memoryFilenames=new Set(getAllMemoryFilenames());const openablePath=__name(absolutePath=>isSubpath(root,absolutePath)||path.resolve(path.dirname(absolutePath))===globalDir&&memoryFilenames.has(path.basename(absolutePath))?absolutePath:void 0,"openablePath");const regex=/--- Context from: (.+?) ---\n([\s\S]*?)--- End of Context from: \1 ---/g;let match;while((match=regex.exec(memoryContent))!==null){const filePath=match[1];const content=match[2];const absolutePath=path.resolve(workingDir,filePath);const owner=extensionOwners.get(absolutePath);const openPath=openablePath(absolutePath);results.push({path:owner??formatContextFileDisplayPath(absolutePath,workingDir),tokens:estimateContextTextTokens(content),...openPath!==void 0?{absolutePath:openPath}:{}})}if(results.length===0&&memoryContent.trim().length>0){results.push({path:t("memory"),tokens:estimateContextTextTokens(memoryContent)})}return results}__name(parseMemoryFiles,"parseMemoryFiles");function unescapeXml(text){return text.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}__name(unescapeXml,"unescapeXml");var SKILL_LISTING_ENTRY=/<skill>\n<name>\n([\s\S]*?)\n<\/name>[\s\S]*?<\/skill>/g;function measureSkillListing(text){const byName=new Map;for(const match of text.matchAll(SKILL_LISTING_ENTRY)){const name=unescapeXml(match[1]);byName.set(name.toLowerCase(),{name,tokens:estimateContextTextTokens(match[0])})}return{tokens:estimateContextTextTokens(text),byName}}__name(measureSkillListing,"measureSkillListing");function mergeSkillListing(into,from){into.tokens+=from.tokens;for(const[name,entry]of from.byName){into.byName.set(name,entry)}}__name(mergeSkillListing,"mergeSkillListing");function measureTailSkillListings(conversation){const listing={tokens:0,byName:new Map};const billedTexts=new Set;for(const content of conversation){for(const part of content.parts??[]){const text=part.text;if(typeof text!=="string"||!isSkillListingReminder(text))continue;const measured=measureSkillListing(text);if(measured.byName.size===0)continue;mergeSkillListing(listing,measured);billedTexts.add(text)}}return{listing,billedTexts}}__name(measureTailSkillListings,"measureTailSkillListings");function measureStartupPrelude(prelude){const skillListing={tokens:0,byName:new Map};let startupContextTokens=0;for(const content of prelude){for(const part of content.parts??[]){if(typeof part.text!=="string")continue;if(isSkillListingReminder(part.text)){mergeSkillListing(skillListing,measureSkillListing(part.text))}else{startupContextTokens+=estimateContextTextTokens(part.text)}}}return{skillListing,startupContextTokens}}__name(measureStartupPrelude,"measureStartupPrelude");function estimateFunctionResponseTokens(part,imageTokenEstimate){const response=part.functionResponse;let tokens=estimateContextTextTokens(JSON.stringify({id:response.id,name:response.name,response:response.response}));const nested=response.parts;if(Array.isArray(nested)){for(const inner of nested){if(inner.inlineData||inner.fileData){tokens+=imageTokenEstimate}else if(typeof inner.text==="string"){tokens+=estimateContextTextTokens(inner.text)}}}return tokens}__name(estimateFunctionResponseTokens,"estimateFunctionResponseTokens");function consumeBilledSkillBody(part,billedSkillBodies){if(billedSkillBodies.size===0)return false;const output=part.functionResponse?.response?.output;if(typeof output!=="string")return false;if(billedSkillBodies.delete(output))return true;for(const body of billedSkillBodies){if(output.startsWith(`${body}
|
|
6
6
|
`)){billedSkillBodies.delete(body);return true}}return false}__name(consumeBilledSkillBody,"consumeBilledSkillBody");function estimateConversationTokens(conversation,billing){let tokens=0;const remainingSkillBodies=new Set(billing.billedSkillBodies);for(const content of conversation){for(const part of content.parts??[]){if(typeof part.text==="string"){if(billing.billedListingTexts.has(part.text))continue;tokens+=estimateContextTextTokens(part.text)}else if(part.inlineData||part.fileData){tokens+=billing.imageTokenEstimate}else if(part.functionCall){tokens+=estimateContextTextTokens(JSON.stringify(part.functionCall))}else if(part.functionResponse){if(part.functionResponse.name===ToolNames.SKILL&&consumeBilledSkillBody(part,remainingSkillBodies)){continue}tokens+=estimateFunctionResponseTokens(part,billing.imageTokenEstimate)}}}return tokens}__name(estimateConversationTokens,"estimateConversationTokens");async function collectContextData(config,showDetails){const modelName=config.getModel()||"unknown";const contentGeneratorConfig=config.getContentGeneratorConfig();const contextWindowSize=contentGeneratorConfig.contextWindowSize??DEFAULT_TOKEN_LIMIT;const llmClient=config.getLlmClient?.();const activeChat=llmClient?.isInitialized?.()?llmClient.getChat():void 0;const apiTotalTokens=activeChat?activeChat.getLastPromptTokenCount():uiTelemetryService.getLastPromptTokenCount();const apiCachedTokens=activeChat?.getLastCachedContentTokenCount?.()??uiTelemetryService.getLastCachedContentTokenCount();const history=activeChat?.getHistoryShallow?.()??activeChat?.getHistory?.()??[];const preludeLength=getStartupContextLength(history);const prelude=measureStartupPrelude(withoutAutoMemorySnapshots(history.slice(0,preludeLength)));const conversationHistory=withoutAutoMemorySnapshots(history.slice(preludeLength));const tailSkillListings=measureTailSkillListings(conversationHistory);let conversationTokens=0;const systemPromptText=getMainSessionBaseSystemPrompt(config);const systemPromptTokens=estimateContextTextTokens(systemPromptText);const toolRegistry=config.getToolRegistry();const allTools=toolRegistry?toolRegistry.getAllTools():[];const toolDeclarations=toolRegistry?toolRegistry.getFunctionDeclarations():[];const toolsJsonStr=JSON.stringify(toolDeclarations);const allToolsTokens=estimateContextTextTokens(toolsJsonStr);const builtinTools=[];const mcpTools=[];for(const tool of allTools){if(toolRegistry?.isDeferredAndHidden(tool.name)){continue}if(isMediaPolicyToolHiddenFromModel(config,tool)){continue}const toolJsonStr=JSON.stringify(tool.schema);const tokens=estimateContextTextTokens(toolJsonStr);if(tool instanceof DiscoveredMCPTool){mcpTools.push({name:`${tool.serverName}__${tool.serverToolName||tool.name}`,tokens})}else if(tool.name!==ToolNames.SKILL){builtinTools.push({name:tool.name,tokens})}}const memoryContent=config.getUserMemory();const instructionFiles=parseMemoryFiles(memoryContent,config.getWorkingDir(),extensionContextFileOwners(config,config.getWorkingDir()),config.storage.getProjectRoot());const memoryFiles=[];const instructionFilesTokens=instructionFiles.reduce((sum,f)=>sum+f.tokens,0);const catalog=config.getAutoMemoryContext?.()??"";const snapshots=catalog?history.flatMap(content=>(content.parts??[]).filter(part=>part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true)):[];const pendingSnapshot=getAutoMemorySnapshot(history,catalog);if(pendingSnapshot)snapshots.push(pendingSnapshot);const autoMemoryTokens=estimateContextTextTokens(config.getAutoMemoryPrompt())+snapshots.reduce((sum,part)=>sum+estimateContextTextTokens(part.text??""),0);if(autoMemoryTokens>0){memoryFiles.push({path:t("auto memory"),tokens:autoMemoryTokens})}const memoryFilesTokens=memoryFiles.reduce((sum,f)=>sum+f.tokens,0);const skillTool=allTools.find(tool=>tool.name===ToolNames.SKILL);const skillToolDefinitionTokens=skillTool?estimateContextTextTokens(JSON.stringify(skillTool.schema)):0;const loadedContentNames=skillTool&&"getLoadedSkillContentNames"in skillTool?skillTool.getLoadedSkillContentNames():new Map;const bodyTokensByName=new Map;for(const[content,name]of loadedContentNames){bodyTokensByName.set(name,(bodyTokensByName.get(name)??0)+estimateContextTextTokens(content))}const loadedBodiesTokens=[...bodyTokensByName.values()].reduce((sum,tokens)=>sum+tokens,0);const skillManager=config.getSkillManager();const skillConfigs=skillManager?await skillManager.listSkills():[];const enabledSkillNames=new Set(skillConfigs.filter(skill=>config.isSkillEnabled(skill)).map(skill=>skill.name.toLowerCase()));let skillListing=prelude.skillListing;if(!activeChat){const reminder=await buildAvailableSkillsReminder(config);if(reminder){skillListing=measureSkillListing(reminder.reminder)}}mergeSkillListing(skillListing,tailSkillListings.listing);const billedSkillBodies=new Set(loadedContentNames.keys());const skills=skillConfigs.map(skill=>{const listingTokens=skillListing.byName.get(skill.name.toLowerCase())?.tokens??0;const bodyTokens=bodyTokensByName.get(skill.name);const isLoaded=bodyTokens!==void 0;return{name:skill.name,tokens:listingTokens,loaded:isLoaded,bodyTokens}});const discoveredNames=new Set(skillConfigs.map(skill=>skill.name));for(const[name,bodyTokens]of bodyTokensByName){if(!discoveredNames.has(name)){skills.push({name,tokens:skillListing.byName.get(name.toLowerCase())?.tokens??0,loaded:true,bodyTokens})}}const rowedNames=new Set(skills.map(s=>s.name.toLowerCase()));for(const[key,entry]of skillListing.byName){enabledSkillNames.add(key);if(rowedNames.has(key))continue;rowedNames.add(key);skills.push({name:entry.name,tokens:entry.tokens,loaded:false})}conversationTokens=estimateConversationTokens(conversationHistory,{imageTokenEstimate:resolveSlimmingConfig(config.getChatCompression?.()).imageTokenEstimate,billedSkillBodies,billedListingTexts:tailSkillListings.billedTexts});const skillsTokens=skillToolDefinitionTokens+skillListing.tokens+loadedBodiesTokens;const startupContextTokens=prelude.startupContextTokens;const thresholds=computeThresholds(contextWindowSize,config.getAutoCompactThreshold());const autocompactBuffer=Math.max(0,Math.round(contextWindowSize-thresholds.auto));const rawOverhead=systemPromptTokens+allToolsTokens+instructionFilesTokens+memoryFilesTokens+skillListing.tokens+loadedBodiesTokens+startupContextTokens;const rawContent=rawOverhead+conversationTokens;const hasTokenCount=apiTotalTokens>0;const isEstimated=!hasTokenCount||activeChat?.isLastPromptTokenCountEstimated()===true;const mcpToolsTotalTokens=mcpTools.reduce((sum,tool)=>sum+tool.tokens,0);let totalTokens;let displaySystemPrompt;let displayBuiltinTools;let displayMcpTools;let displayInstructionFiles;let displayMemoryFiles;let displaySkills;let displayStartupContext;let messagesTokens;let unattributedTokens=0;let freeSpace;let detailBuiltinTools;let detailMcpTools;let detailInstructionFiles;let detailMemoryFiles;let detailSkills;const clampDeficit=Math.max(0,skillToolDefinitionTokens+mcpToolsTotalTokens-allToolsTokens);const clampedMcpTools=Math.max(0,mcpToolsTotalTokens-clampDeficit);const clampedSkills=skillsTokens-Math.max(0,clampDeficit-mcpToolsTotalTokens);const clampedBuiltinTools=Math.max(0,allToolsTokens-skillToolDefinitionTokens-clampedMcpTools);const mcpDetailShare=mcpToolsTotalTokens>0?clampedMcpTools/mcpToolsTotalTokens:1;const scaleTokens=__name((items,factor)=>factor<1?items.map(item=>({...item,tokens:Math.round(item.tokens*factor)})):items,"scaleTokens");if(!hasTokenCount){totalTokens=0;displaySystemPrompt=systemPromptTokens;displaySkills=clampedSkills;displayStartupContext=startupContextTokens;displayBuiltinTools=clampedBuiltinTools;displayMcpTools=clampedMcpTools;displayInstructionFiles=instructionFilesTokens;displayMemoryFiles=memoryFilesTokens;messagesTokens=conversationTokens;freeSpace=Math.max(0,contextWindowSize-rawContent-autocompactBuffer);detailBuiltinTools=builtinTools;detailMcpTools=scaleTokens(mcpTools,mcpDetailShare);detailInstructionFiles=instructionFiles;detailMemoryFiles=memoryFiles;detailSkills=skills}else{totalTokens=apiTotalTokens;const scale=rawOverhead>totalTokens?totalTokens/rawOverhead:1;displaySystemPrompt=Math.floor(systemPromptTokens*scale);displayBuiltinTools=Math.floor(clampedBuiltinTools*scale);displayMcpTools=Math.floor(clampedMcpTools*scale);displayInstructionFiles=Math.floor(instructionFilesTokens*scale);displayMemoryFiles=Math.floor(memoryFilesTokens*scale);displaySkills=Math.floor(clampedSkills*scale);displayStartupContext=Math.floor(startupContextTokens*scale);const attributedOverhead=displaySystemPrompt+displayBuiltinTools+displayMcpTools+displayInstructionFiles+displayMemoryFiles+displaySkills+displayStartupContext;if(scale<1){messagesTokens=Math.max(0,totalTokens-attributedOverhead)}else{messagesTokens=Math.min(conversationTokens,Math.max(0,totalTokens-attributedOverhead));unattributedTokens=Math.max(0,totalTokens-attributedOverhead-messagesTokens)}freeSpace=Math.max(0,contextWindowSize-totalTokens-autocompactBuffer);detailBuiltinTools=scaleTokens(builtinTools,scale);detailMcpTools=scaleTokens(mcpTools,scale*mcpDetailShare);detailInstructionFiles=scaleTokens(instructionFiles,scale);detailMemoryFiles=scaleTokens(memoryFiles,scale);detailSkills=scale<1?skills.map(item=>({...item,tokens:Math.round(item.tokens*scale),bodyTokens:item.bodyTokens?Math.round(item.bodyTokens*scale):void 0})):skills}const tierTokens=hasTokenCount?apiTotalTokens:rawContent;const breakdown={systemPrompt:displaySystemPrompt,builtinTools:displayBuiltinTools,mcpTools:displayMcpTools,instructionFiles:displayInstructionFiles,memoryFiles:displayMemoryFiles,skills:displaySkills,startupContext:displayStartupContext,messages:messagesTokens,unattributed:unattributedTokens,cachedTokens:hasTokenCount?apiCachedTokens:0,freeSpace,autocompactBuffer,thresholds,currentTier:currentTier(tierTokens,thresholds)};return{type:"context_usage",modelName,totalTokens,contextWindowSize,breakdown,builtinTools:showDetails?detailBuiltinTools:[],mcpTools:showDetails?detailMcpTools:[],instructionFiles:showDetails?detailInstructionFiles:[],memoryFiles:showDetails?detailMemoryFiles:[],skills:showDetails?detailSkills.filter(skill=>skill.loaded||enabledSkillNames.has(skill.name.toLowerCase())):[],isEstimated,showDetails}}__name(collectContextData,"collectContextData");function fmtTokens(tokens){if(tokens>=999950){return`${(tokens/1e6).toFixed(1)}m`}if(tokens>=1e3){return`${(tokens/1e3).toFixed(1)}k`}return`${tokens}`}__name(fmtTokens,"fmtTokens");function fmtCategoryRow(label,tokens,contextWindowSize,indent=" "){const percentage=contextWindowSize>0?(tokens/contextWindowSize*100).toFixed(1):"0.0";const right=`${fmtTokens(tokens)} tokens (${percentage}%)`;const leftPart=`${indent}${label}`;const totalWidth=56;const dots=Math.max(1,totalWidth-leftPart.length-right.length);return`${leftPart}${" ".repeat(dots)}${right}`}__name(fmtCategoryRow,"fmtCategoryRow");function formatNum(n){return Math.round(n).toLocaleString("en-US")}__name(formatNum,"formatNum");function formatContextUsageText(data){const{modelName,totalTokens,contextWindowSize,breakdown,builtinTools,mcpTools,instructionFiles=[],memoryFiles,skills,isEstimated,showDetails}=data;const hasTokenCount=totalTokens>0;const memoryLabel=breakdown.instructionFiles===void 0?"Memory files":"Auto memory";const lines=[];lines.push("## Context Usage");lines.push("");if(!hasTokenCount){const includesConversation=breakdown.messages>0;lines.push(includesConversation?"*No provider usage yet. These are local estimates, including the conversation.*":"*No API response yet. Send a message to see actual usage.*");lines.push("");lines.push(includesConversation?"**Estimated usage, including the conversation**":"**Estimated pre-conversation overhead**");lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("")}else{lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("");if(isEstimated){lines.push("*Token usage is estimated until provider usage is received.*");lines.push("")}lines.push(fmtCategoryRow("Used",totalTokens,contextWindowSize));if((breakdown.cachedTokens??0)>0){lines.push(fmtCategoryRow("Cached prefix",breakdown.cachedTokens,contextWindowSize," \u2514 "))}lines.push(fmtCategoryRow("Free",breakdown.freeSpace,contextWindowSize));lines.push("");lines.push("**Compaction thresholds**");lines.push(` Effective window: ${formatNum(breakdown.thresholds.effectiveWindow)} (window \u2212 ${formatNum(contextWindowSize-breakdown.thresholds.effectiveWindow)} reserve)`);lines.push(` Warn threshold: ${formatNum(breakdown.thresholds.warn)}`);lines.push(` Auto threshold: ${formatNum(breakdown.thresholds.auto)}`);lines.push(` Hard threshold: ${formatNum(breakdown.thresholds.hard)}`);lines.push(` Current tier: ${breakdown.currentTier}`);lines.push("");lines.push("**Usage by category**")}lines.push(fmtCategoryRow("System prompt",breakdown.systemPrompt,contextWindowSize));lines.push(fmtCategoryRow("Built-in tools",breakdown.builtinTools,contextWindowSize));if(breakdown.mcpTools>0){lines.push(fmtCategoryRow("MCP tools",breakdown.mcpTools,contextWindowSize))}if(breakdown.instructionFiles!==void 0){lines.push(fmtCategoryRow("Instruction files",breakdown.instructionFiles,contextWindowSize))}lines.push(fmtCategoryRow(memoryLabel,breakdown.memoryFiles,contextWindowSize));lines.push(fmtCategoryRow("Skills",breakdown.skills,contextWindowSize));if((breakdown.startupContext??0)>0){lines.push(fmtCategoryRow("Startup context",breakdown.startupContext,contextWindowSize))}if(hasTokenCount||breakdown.messages>0){lines.push(fmtCategoryRow("Messages",breakdown.messages,contextWindowSize));if((breakdown.unattributed??0)>0){lines.push(fmtCategoryRow("Unattributed",breakdown.unattributed,contextWindowSize))}}if(showDetails){const sortedBuiltin=[...builtinTools].sort((a,b)=>b.tokens-a.tokens);const sortedMcp=[...mcpTools].sort((a,b)=>b.tokens-a.tokens);const sortedMemory=[...memoryFiles].sort((a,b)=>b.tokens-a.tokens);const sortedSkills=[...skills].sort((a,b)=>{if(!a.loaded!==!b.loaded)return a.loaded?-1:1;return b.tokens+(b.bodyTokens??0)-(a.tokens+(a.bodyTokens??0))});if(sortedBuiltin.length>0){lines.push("");lines.push("**Built-in tools**");for(const tool of sortedBuiltin){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(sortedMcp.length>0){lines.push("");lines.push("**MCP tools**");for(const tool of sortedMcp){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(instructionFiles.length>0){lines.push("","**Instruction files**");for(const file of[...instructionFiles].sort((a,b)=>b.tokens-a.tokens)){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedMemory.length>0){lines.push("");lines.push("**"+memoryLabel+"**");for(const file of sortedMemory){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedSkills.length>0){lines.push("");lines.push("**Skills**");for(const skill of sortedSkills){lines.push(fmtCategoryRow(skill.name,skill.tokens,contextWindowSize," \u2514 "));if(skill.loaded&&skill.bodyTokens&&skill.bodyTokens>0){lines.push(fmtCategoryRow("body loaded",skill.bodyTokens,contextWindowSize," \u2514 "))}}}}else{lines.push("");lines.push("*Run /context detail for per-item breakdown.*")}return lines.join("\n")}__name(formatContextUsageText,"formatContextUsageText");var contextCommand={name:"context",get description(){return t('Show context window usage breakdown. Use "/context detail" for per-item breakdown.')},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,args)=>{const normalizedArgs=args?.trim().toLowerCase();const showDetails=normalizedArgs==="detail"||normalizedArgs==="-d";const executionMode=context.executionMode??"interactive";const{config}=context.services;if(!config){if(executionMode==="interactive"){context.ui.addItem({type:"error",text:t("Config not loaded.")},Date.now());return}return{type:"message",messageType:"error",content:t("Config not loaded.")}}const contextUsageItem=await collectContextData(config,showDetails);if(executionMode==="interactive"){context.ui.addItem(contextUsageItem,Date.now());return}return{type:"message",messageType:"info",content:formatContextUsageText(contextUsageItem)}},"action"),subCommands:[{name:"detail",get description(){return t("Show per-item context usage breakdown.")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async context=>{await contextCommand.action(context,"detail")},"action")}]};export{EXTENSION_CONTEXT_BUDGET,parseExtensionRef,buildExtensionRef,matchExtensionByRef,sanitizeDisplayText,getSanitizedExtensionDisplayName,buildExtensionMentionContext,collectContextData,formatContextUsageText,contextCommand};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{appEvents}from"./chunk-
|
|
3
|
+
import{appEvents}from"./chunk-OTYPLLMT.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{CUSTOM_SANDBOX_IMAGE_ENV_VAR,HOST_UPDATE_RELAUNCH_ENV_VAR,SKIP_UPDATE_CHECK_ENV_VAR,requestUpdateOnExit}from"./chunk-CY2QKKZA.js";import{IdeClient}from"./chunk-7XQ5D34E.js";import{getAllProviderBaseUrls}from"./chunk-ET2Z7ZGF.js";import{detectRuntime,getOrCreateSharedDispatcher,preloadRuntimeFetchModule,redactProxyCredentials}from"./chunk-ZZZAYAJW.js";import{initializeTelemetry}from"./chunk-3XVPZY7X.js";import{recordStartupEvent}from"./chunk-H4XFFVZ2.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var debugLogger=createDebugLogger("PRECONNECT");var preconnectFired=false;var preconnectInFlight;var DEFAULT_BASE_URLS={openai:"https://api.openai.com","qwen-oauth":"https://coding.dashscope.aliyuncs.com",anthropic:"https://api.anthropic.com",dashscope:"https://dashscope.aliyuncs.com"};var ALL_DEFAULT_URLS=[...Object.values(DEFAULT_BASE_URLS),...getAllProviderBaseUrls()];function shouldSkipPreconnect(){if(process.env["NODE_EXTRA_CA_CERTS"]){debugLogger.debug("Skipping preconnect: custom CA certificate configured");return true}return false}__name(shouldSkipPreconnect,"shouldSkipPreconnect");function isInSandboxMode(){return process.env["SANDBOX"]!==void 0}__name(isInSandboxMode,"isInSandboxMode");function isDefaultBaseUrl(baseUrl){const normalizedInput=baseUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return ALL_DEFAULT_URLS.some(defaultUrl=>{const normalizedDefault=defaultUrl.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return normalizedInput===normalizedDefault||normalizedInput.startsWith(normalizedDefault+"/")})}__name(isDefaultBaseUrl,"isDefaultBaseUrl");function getPreconnectTargetUrl(authType,resolvedBaseUrl){if(resolvedBaseUrl&&/^https?:\/\//i.test(resolvedBaseUrl)){if(isDefaultBaseUrl(resolvedBaseUrl)){return resolvedBaseUrl}debugLogger.debug("Skipping preconnect: resolved baseUrl is not a default URL");return void 0}if(authType&&DEFAULT_BASE_URLS[authType]){return DEFAULT_BASE_URLS[authType]}return void 0}__name(getPreconnectTargetUrl,"getPreconnectTargetUrl");function preconnectApi(authType,options={}){if(preconnectFired){return}if(process.env["QWEN_CODE_DISABLE_PRECONNECT"]==="1"){debugLogger.debug("Preconnect disabled by environment variable");preconnectFired=true;return}if(isInSandboxMode()){debugLogger.debug("Skipping preconnect: sandbox mode detected");preconnectFired=true;return}if(shouldSkipPreconnect()){preconnectFired=true;return}if(detectRuntime()!=="node"){debugLogger.debug("Skipping preconnect: unsupported runtime");preconnectFired=true;return}if(!options.proxy){debugLogger.debug("Skipping preconnect dispatcher: no proxy configured");return}const proxy=options.proxy;const targetUrl=getPreconnectTargetUrl(authType,options.resolvedBaseUrl);if(!targetUrl){debugLogger.debug("No target URL for preconnect");return}preconnectFired=true;debugLogger.debug(`Preconnecting to: ${targetUrl}`);preconnectInFlight=(async()=>{await preloadRuntimeFetchModule();const dispatcher=getOrCreateSharedDispatcher(proxy);const{fetch:undiciFetch}=await loadUndici();await undiciFetch(targetUrl,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"QwenCode-Preconnect/1.0"},dispatcher});debugLogger.debug("Preconnect completed")})().catch(error=>{const redactedError=redactProxyCredentials(String(error));debugLogger.debug(`Preconnect failed (ignored): ${redactedError}`)})}__name(preconnectApi,"preconnectApi");var debugLogger2=createDebugLogger("STARTUP_PREFETCH");var DEFERRED_IDE_CONNECT_TIMEOUT_MS=15e3;var earlyStarted=new WeakSet;var postRenderStarted=new WeakSet;function withTimeout(promise,name,timeoutMs,onTimeout=()=>{}){let timeoutId;let timedOut=false;const runTimeoutCleanup=__name(()=>{void Promise.resolve().then(onTimeout).catch(err=>{debugLogger2.debug(`${name} timeout cleanup failed:`,err)})},"runTimeoutCleanup");const timeout=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{timedOut=true;runTimeoutCleanup();reject(new Error(`${name} timed out after ${timeoutMs}ms`))},timeoutMs);timeoutId.unref?.()});void promise.then(()=>{if(timedOut){runTimeoutCleanup()}},err=>{if(timedOut){debugLogger2.debug(`${name} underlying error after timeout:`,err)}});return Promise.race([promise,timeout]).finally(()=>{if(timeoutId){clearTimeout(timeoutId)}})}__name(withTimeout,"withTimeout");function runDeferredTask(name,task){recordStartupEvent("startup_prefetch_started",{name});void Promise.resolve().then(task).then(()=>{recordStartupEvent("startup_prefetch_completed",{name})}).catch(err=>{recordStartupEvent("startup_prefetch_failed",{name});debugLogger2.warn(`${name} failed:`,err)})}__name(runDeferredTask,"runDeferredTask");async function disconnectIdeAfterDeferredTimeout(){const ideClient=await IdeClient.getInstance();await ideClient.disconnect()}__name(disconnectIdeAfterDeferredTimeout,"disconnectIdeAfterDeferredTimeout");function startEarlyStartupPrefetches(config){if(earlyStarted.has(config))return;earlyStarted.add(config);try{const modelsConfig=config.getModelsConfig();const authType=modelsConfig.getCurrentAuthType();const resolvedBaseUrl=modelsConfig.getGenerationConfig().baseUrl;const proxy=config.getProxy();preconnectApi(authType,{resolvedBaseUrl,proxy})}catch(error){debugLogger2.debug(`Preconnect skipped due to error getting authType: ${error}`)}}__name(startEarlyStartupPrefetches,"startEarlyStartupPrefetches");var UPDATE_CHECK_DELAY_MS=3e3;function startPostRenderPrefetches(config,settings,options={}){if(postRenderStarted.has(config))return;postRenderStarted.add(config);if(settings.merged.general?.enableAutoUpdate!==false&&process.env[SKIP_UPDATE_CHECK_ENV_VAR]!=="true"&&!process.env[CUSTOM_SANDBOX_IMAGE_ENV_VAR]){runDeferredTask("update_check",async()=>{await new Promise(resolve=>{setTimeout(resolve,UPDATE_CHECK_DELAY_MS).unref?.()});const[{checkForUpdatesDetailed,describeUpdateCheckFailure},{handleAutoUpdate},{getInstallationInfo},{updateEventEmitter},{t}]=await Promise.all([import("./updateCheck-X623JRSY.js"),import("./handleAutoUpdate-MJKTDJUO.js"),import("./installationInfo-TF2RSJOG.js"),import("./updateEventEmitter-HCGBOCP2.js"),import("./i18n-TCOB4TC5.js")]);const updateCheckSkippedMessage=__name(error=>t("Update check skipped ({{reason}}) \u2014 run /update to retry.",{reason:describeUpdateCheckFailure(error)}),"updateCheckSkippedMessage");try{const result=await checkForUpdatesDetailed();if(result.status==="update"){const projectRoot=config.getProjectRoot();const hostUpdateRelaunch=process.env[HOST_UPDATE_RELAUNCH_ENV_VAR];if(hostUpdateRelaunch==="true"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
|
|
4
4
|
${t("Run /update to install the update on the host.")}`});return}if(hostUpdateRelaunch==="false"){updateEventEmitter.emit("update-info",{message:`${result.info.message}
|
|
5
5
|
${t("Update Qwen Code on the host, then restart the sandbox.")}`});return}const installationInfo=getInstallationInfo(projectRoot,true);if(installationInfo.packageManager==="npm"){void handleAutoUpdate(result.info,settings,projectRoot);return}if(installationInfo.updateCommand||installationInfo.isStandalone&&installationInfo.standaloneDir){if(requestUpdateOnExit()){updateEventEmitter.emit("update-info",{message:`${result.info.message}
|
|
6
6
|
${t("The update will be installed after you exit this session.")}`})}else{updateEventEmitter.emit("update-info",{message:`${result.info.message}
|
|
7
|
-
${t("Run /update to install the update.")}`})}}else{void handleAutoUpdate(result.info,settings,projectRoot)}}else if(result.status==="error"){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(result.error),severity:"warning"})}}catch(error){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(error),severity:"warning"});throw error}})}if(options.connectIde&&config.getIdeMode()){runDeferredTask("ide_connect",async()=>{appEvents.emit("startup-ide-connection-status-changed",{state:"connecting"});try{const{connectIdeForStartup}=await import("./initializer-
|
|
7
|
+
${t("Run /update to install the update.")}`})}}else{void handleAutoUpdate(result.info,settings,projectRoot)}}else if(result.status==="error"){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(result.error),severity:"warning"})}}catch(error){updateEventEmitter.emit("update-failed",{message:updateCheckSkippedMessage(error),severity:"warning"});throw error}})}if(options.connectIde&&config.getIdeMode()){runDeferredTask("ide_connect",async()=>{appEvents.emit("startup-ide-connection-status-changed",{state:"connecting"});try{const{connectIdeForStartup}=await import("./initializer-NLYOGZZS.js");await withTimeout(connectIdeForStartup(config),"ide_connect",DEFERRED_IDE_CONNECT_TIMEOUT_MS,disconnectIdeAfterDeferredTimeout);appEvents.emit("startup-ide-connection-status-changed",{state:"connected"})}catch(err){appEvents.emit("startup-ide-connection-status-changed",{state:"failed",message:err instanceof Error?err.message:String(err)});throw err}})}if(options.initializeTelemetry){runDeferredTask("telemetry_init",()=>initializeTelemetry(config))}if(config.isInteractive()&&settings.merged.general?.batchAutoCollect!==false){runDeferredTask("batch_auto_collect",async()=>{const[{startBatchAutoCollect},{resolveEndpoint},{updateEventEmitter}]=await Promise.all([import("./batch-auto-collect-ANURZLEZ.js"),import("./batch-3CRVN5VJ.js"),import("./updateEventEmitter-HCGBOCP2.js")]);startBatchAutoCollect({projectRoot:config.getWorkingDir(),notify:__name(message=>updateEventEmitter.emit("update-info",{message}),"notify"),resolveEndpoint:__name(()=>resolveEndpoint(process.env,{settings:settings.merged,warn:__name(message=>debugLogger2.debug(message),"warn")}),"resolveEndpoint"),log:__name(message=>debugLogger2.debug(message),"log")})})}if(config.isInteractive()){runDeferredTask("background_housekeeping",async()=>{const{startBackgroundHousekeeping}=await import("./scheduler-RUV2FNDR.js");startBackgroundHousekeeping(config,settings)})}}__name(startPostRenderPrefetches,"startPostRenderPrefetches");export{startEarlyStartupPrefetches,startPostRenderPrefetches};
|
|
8
8
|
/**
|
|
9
9
|
* @license
|
|
10
10
|
* Copyright 2026 Qwen Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-
|
|
3
|
+
import{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-7XQ5D34E.js";import{scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments}from"./chunk-FUBDS3AV.js";import{getAutoMemoryRoot,getUserAutoMemoryRoot}from"./chunk-KVA6DHHF.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import path from"node:path";var debugLogger=createDebugLogger("AUTO_MEMORY_REMEMBER");function buildManagedRememberPrompt(fact,projectRoot,options={}){const trimmed=fact.trim();const projectDir=projectRoot?getAutoMemoryRoot(projectRoot):void 0;const userDir=getUserAutoMemoryRoot();const dirHint=projectDir===void 0?"":options.scope==="project"?` Store this memory only in PROJECT memory at \`${projectDir}\`. This explicit project target overrides the memory type's default destination; do not read or write USER memory at \`${userDir}\`.`:options.scope==="user"?` Store this memory only in USER memory at \`${userDir}\`. This explicit user target overrides the memory type's default destination; do not read or write PROJECT memory at \`${projectDir}\`.`:` Choose the destination directory by the type's \`<scope>\`: USER memory at \`${userDir}\` for cross-project facts, PROJECT memory at \`${projectDir}\` for this-project-only facts.`;const content=options.wrapUserContent?`<user-content>
|
|
4
4
|
${trimmed}
|
|
5
5
|
</user-content>`:trimmed;return`Please save the following to your memory system.${dirHint} Choose the most appropriate memory type (user, feedback, project, or reference) based on the content:
|
|
6
6
|
|