@hostclubeos/miraos 0.0.6-beta → 0.0.8-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/chunks/{MaxSizedBox-CBUPHLMW.js → MaxSizedBox-YR2SA5XW.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-EXZJQKTK.js → StandaloneSessionPicker-VEXSGLU4.js} +1 -1
  3. package/chunks/{acp-subagent-executor-BMIXP52W.js → acp-subagent-executor-ATOLWCVC.js} +1 -1
  4. package/chunks/{acpAgent-OGBFWA5R.js → acpAgent-DN46FTZ2.js} +3 -3
  5. package/chunks/{advisor-5RUG3VFZ.js → advisor-6MI5JQGC.js} +1 -1
  6. package/chunks/{agent-SGQ7AEZI.js → agent-6HPQ4XCT.js} +1 -1
  7. package/chunks/{agent-headless-ZGCZ2DA7.js → agent-headless-KXAJBOPG.js} +1 -1
  8. package/chunks/{agent-host-client-HY5GPSHM.js → agent-host-client-NOZRE2ZR.js} +1 -1
  9. package/chunks/{agent-host-connections-KGTBS37X.js → agent-host-connections-6FOSHEWD.js} +1 -1
  10. package/chunks/{autofix-pr-E62FC67X.js → autofix-pr-IMJA2KZF.js} +1 -1
  11. package/chunks/{batch-OUC6FGCQ.js → batch-L5VJ4XGP.js} +1 -1
  12. package/chunks/{bridge-FLEIBB5V.js → bridge-CCRTJSIM.js} +1 -1
  13. package/chunks/{channel-settings-store-QG6HREVH.js → channel-settings-store-SB7BP6XT.js} +1 -1
  14. package/chunks/{chunk-GPI53DWB.js → chunk-2DPE27WB.js} +1 -1
  15. package/chunks/{chunk-JJDF5FHA.js → chunk-32DLSPV5.js} +1 -1
  16. package/chunks/{chunk-2PB6TEZU.js → chunk-3NA5O4QO.js} +1 -1
  17. package/chunks/{chunk-RBA3TP7L.js → chunk-3VKLOQ2P.js} +1 -1
  18. package/chunks/{chunk-3KFLO5W3.js → chunk-4C5BOFDC.js} +1 -1
  19. package/chunks/{chunk-TFITRCIC.js → chunk-4RRQ7CPF.js} +1 -1
  20. package/chunks/{chunk-YN6WXB6B.js → chunk-5AJKMBPM.js} +1 -1
  21. package/chunks/{chunk-SCHCTQCG.js → chunk-5BWVS5D3.js} +1 -1
  22. package/chunks/{chunk-Y3BCVTFB.js → chunk-5SX4UPMN.js} +1 -1
  23. package/chunks/{chunk-FK5L2WVV.js → chunk-5YULNQF3.js} +1 -1
  24. package/chunks/{chunk-T3A53XMM.js → chunk-66N3SLXJ.js} +1 -1
  25. package/chunks/{chunk-4WYKHP7Q.js → chunk-6AAVML2M.js} +1 -1
  26. package/chunks/{chunk-HHSHBOT7.js → chunk-6STDVRH5.js} +2 -2
  27. package/chunks/{chunk-TI7J4HX2.js → chunk-6TNX3S5H.js} +2 -2
  28. package/chunks/{chunk-ZOWMHZWO.js → chunk-77GGGTWS.js} +1 -1
  29. package/chunks/{chunk-KNW2OD46.js → chunk-7DJYSBNJ.js} +1 -1
  30. package/chunks/{chunk-MYS5NQXO.js → chunk-7EEWU6XO.js} +1 -1
  31. package/chunks/{chunk-VJUTDS6C.js → chunk-7GU7HKIT.js} +1 -1
  32. package/chunks/{chunk-UWMLSAQY.js → chunk-7HO5DQ6V.js} +1 -1
  33. package/chunks/{chunk-SHKSVOTG.js → chunk-7L4MR4QM.js} +1 -1
  34. package/chunks/{chunk-RWFOQXPU.js → chunk-7Q6RNE77.js} +1 -1
  35. package/chunks/{chunk-FC7SJIAS.js → chunk-AHV4IMUX.js} +1 -1
  36. package/chunks/{chunk-2QYFSBJY.js → chunk-ARILWFTZ.js} +1 -1
  37. package/chunks/{chunk-7JT2V4AW.js → chunk-BWFZEDYG.js} +1 -1
  38. package/chunks/chunk-BWLMXGA2.js +13 -0
  39. package/chunks/{chunk-ORVQPZMQ.js → chunk-C3ZJUOTJ.js} +1 -1
  40. package/chunks/{chunk-WJLHLFIR.js → chunk-CEVKKM22.js} +1 -1
  41. package/chunks/{chunk-K7KY7FIB.js → chunk-CJLKKIUW.js} +1 -1
  42. package/chunks/{chunk-HASJX2YS.js → chunk-CLLQQMTU.js} +1 -1
  43. package/chunks/{chunk-7F5IYTVE.js → chunk-CNGBG3X5.js} +1 -1
  44. package/chunks/{chunk-RNPVWQ3V.js → chunk-CNZS2RPX.js} +1 -1
  45. package/chunks/{chunk-WC72OWF2.js → chunk-D4WMUCSK.js} +2 -2
  46. package/chunks/{chunk-W2ZVZ6LS.js → chunk-DNCXESHL.js} +1 -1
  47. package/chunks/{chunk-HSN5QUS7.js → chunk-DNXQKR5E.js} +1 -1
  48. package/chunks/{chunk-H65ZVST6.js → chunk-DTNW2CM3.js} +1 -1
  49. package/chunks/{chunk-BB2C4HKQ.js → chunk-DTRSC73M.js} +3 -3
  50. package/chunks/{chunk-2VW4HXVF.js → chunk-E743PFSX.js} +1 -1
  51. package/chunks/{chunk-P5543CFV.js → chunk-EHM4KL2U.js} +1 -1
  52. package/chunks/{chunk-PQOQONLN.js → chunk-FC5IAX56.js} +1 -1
  53. package/chunks/{chunk-3MBYQYPC.js → chunk-G3COGFSZ.js} +1 -1
  54. package/chunks/{chunk-5JKJSIIP.js → chunk-G4OSEVOV.js} +2 -2
  55. package/chunks/{chunk-SOCXRMZM.js → chunk-G7D42XGP.js} +2 -2
  56. package/chunks/{chunk-IF3SWUYT.js → chunk-GBEQD55S.js} +1 -1
  57. package/chunks/{chunk-EW3EVEYN.js → chunk-GM6YF6IS.js} +1 -1
  58. package/chunks/{chunk-UOYXBAN7.js → chunk-GS4FZF6I.js} +1 -1
  59. package/chunks/{chunk-2ZWVSKPK.js → chunk-HCCONFJY.js} +1 -1
  60. package/chunks/{chunk-GY4ID3EB.js → chunk-HCKF74X7.js} +1 -1
  61. package/chunks/{chunk-6RDYPRV6.js → chunk-IJH5HZTB.js} +1 -1
  62. package/chunks/{chunk-3GA3NTAV.js → chunk-IJIQDCNJ.js} +5 -5
  63. package/chunks/{chunk-TLZM3DMY.js → chunk-IK5TB2CB.js} +1 -1
  64. package/chunks/{chunk-RGVXNWZA.js → chunk-IWIGJDPL.js} +1 -1
  65. package/chunks/{chunk-VBJV7T47.js → chunk-JCWNB45W.js} +1 -1
  66. package/chunks/{chunk-GTQULDIL.js → chunk-JHGMLUAL.js} +1 -1
  67. package/chunks/{chunk-23543L6E.js → chunk-JRIVHFCG.js} +1 -1
  68. package/chunks/{chunk-34YXJ3CX.js → chunk-JT5EN5MI.js} +1 -1
  69. package/chunks/{chunk-JDHMSERR.js → chunk-K2PGOAJP.js} +1 -1
  70. package/chunks/{chunk-O6Z3KO6R.js → chunk-K3RWL2YH.js} +1 -1
  71. package/chunks/{chunk-7W5DOBKY.js → chunk-KZZ5ZQHX.js} +1 -1
  72. package/chunks/{chunk-HMID4D72.js → chunk-LRXYXGMT.js} +1 -1
  73. package/chunks/{chunk-YVN32EUM.js → chunk-LTXZHHNK.js} +1 -1
  74. package/chunks/{chunk-TU5QHOJC.js → chunk-M3IQE5G4.js} +1 -1
  75. package/chunks/{chunk-RRMTSVGU.js → chunk-MCHMWRNO.js} +1 -1
  76. package/chunks/{chunk-SHLTP6ZB.js → chunk-MCY3IS2E.js} +1 -1
  77. package/chunks/{chunk-VGPV5AVJ.js → chunk-MOXZO5PM.js} +1 -1
  78. package/chunks/{chunk-TWJ4XBED.js → chunk-MV7LX23I.js} +1 -1
  79. package/chunks/{chunk-66DZADDA.js → chunk-MXFS555I.js} +1 -1
  80. package/chunks/{chunk-USR2Y7B3.js → chunk-NNYAXFFN.js} +1 -1
  81. package/chunks/{chunk-NGH27AWP.js → chunk-NUDHRTIM.js} +1 -1
  82. package/chunks/{chunk-JRPR5IME.js → chunk-NYGJ53Y7.js} +1 -1
  83. package/chunks/chunk-OHOG4HSN.js +31 -0
  84. package/chunks/{chunk-JQOLNQQN.js → chunk-OPFBBIAQ.js} +1 -1
  85. package/chunks/{chunk-KYK53GFP.js → chunk-OXG4BLFF.js} +1 -1
  86. package/chunks/{chunk-GLQWA4W2.js → chunk-PGKVSOWW.js} +1 -1
  87. package/chunks/{chunk-PFKTTUGS.js → chunk-POMEWCFJ.js} +6 -6
  88. package/chunks/{chunk-YVORE4W4.js → chunk-Q4NEZZ6L.js} +1 -1
  89. package/chunks/{chunk-Z4JY3HGO.js → chunk-QCSGHQ2P.js} +1 -1
  90. package/chunks/{chunk-VF2UWWI2.js → chunk-QWNTORRT.js} +1 -1
  91. package/chunks/{chunk-3GJ56V2J.js → chunk-QZNCYZ7H.js} +1 -1
  92. package/chunks/{chunk-T5PDEAU5.js → chunk-S5NTCBEI.js} +1 -1
  93. package/chunks/{chunk-AIAYQAPA.js → chunk-SK5C26Y6.js} +1 -1
  94. package/chunks/{chunk-ATVRF62A.js → chunk-SMO4PEHK.js} +1 -1
  95. package/chunks/{chunk-AE6E2YKY.js → chunk-SPCIIUIG.js} +1 -1
  96. package/chunks/{chunk-CUY6CVSL.js → chunk-SVNSF5ZH.js} +1 -1
  97. package/chunks/{chunk-K7VOBDFT.js → chunk-UC455ZS7.js} +1 -1
  98. package/chunks/{chunk-J773THNP.js → chunk-UZAFPEVN.js} +1 -1
  99. package/chunks/{chunk-PVHBBTAU.js → chunk-V3ASW57P.js} +1 -1
  100. package/chunks/{chunk-4MGTY3CJ.js → chunk-VAFRD2H4.js} +1 -1
  101. package/chunks/{chunk-F2XELUO3.js → chunk-VOCM2M4K.js} +1 -1
  102. package/chunks/{chunk-W6IOHGWW.js → chunk-VOIC5ZW2.js} +1 -1
  103. package/chunks/{chunk-V5Z6OEKJ.js → chunk-W4M6JXZB.js} +1 -1
  104. package/chunks/{chunk-4KIFAVR2.js → chunk-WJXADORN.js} +1 -1
  105. package/chunks/{chunk-P42MFWO2.js → chunk-WN6Z3J27.js} +1 -1
  106. package/chunks/{chunk-FS67DOZQ.js → chunk-WOMJLK3E.js} +1 -1
  107. package/chunks/{chunk-NVD63O5H.js → chunk-WSXRO2YB.js} +1 -1
  108. package/chunks/{chunk-IC2WDA6V.js → chunk-WUZ53TKN.js} +1 -1
  109. package/chunks/{chunk-724YPZRX.js → chunk-WW43VZ6O.js} +1 -1
  110. package/chunks/{chunk-PFECH6U6.js → chunk-WZAUO3LV.js} +1 -1
  111. package/chunks/{chunk-EF3HUB7S.js → chunk-XGPGIMZK.js} +1 -1
  112. package/chunks/{chunk-PGKFDR73.js → chunk-XJKDC7OE.js} +1 -1
  113. package/chunks/{chunk-HZ4L4MDM.js → chunk-XNP5JXCS.js} +1 -1
  114. package/chunks/{chunk-4346FNTB.js → chunk-YELFN6AG.js} +1 -1
  115. package/chunks/{chunk-WZTO3EYG.js → chunk-YFXKRGHT.js} +1 -1
  116. package/chunks/{chunk-E6LRCLLE.js → chunk-YOBM4ZFW.js} +2 -2
  117. package/chunks/{chunk-7VP4KALB.js → chunk-ZJOVJLIH.js} +1 -1
  118. package/chunks/{chunk-KK6SQPYG.js → chunk-ZQZK267X.js} +1 -1
  119. package/chunks/{codex-subagent-executor-UCDGQFTR.js → codex-subagent-executor-TPO62HU5.js} +1 -1
  120. package/chunks/{config-utils-Z6F4DVLG.js → config-utils-6GWIYBUK.js} +1 -1
  121. package/chunks/{contextCommand-HMVZT56Y.js → contextCommand-WWVGDTOL.js} +1 -1
  122. package/chunks/{core-runtime-AV7CJXOL.js → core-runtime-ASQR33TV.js} +1 -1
  123. package/chunks/{create-sub-session-NNKVHZKT.js → create-sub-session-XY2FXSPE.js} +1 -1
  124. package/chunks/{cron-create-HWZDFVPA.js → cron-create-HY3TLNV2.js} +1 -1
  125. package/chunks/{daemon-git-worktree-guard-Q3C45X7T.js → daemon-git-worktree-guard-ILW3NJJC.js} +1 -1
  126. package/chunks/{daemon-status-provider-FCQ4YYAY.js → daemon-status-provider-JVOGEKWY.js} +1 -1
  127. package/chunks/{daemon-trust-policy-6D4KJANB.js → daemon-trust-policy-XXRBG4JE.js} +1 -1
  128. package/chunks/{daemon-trust-policy-monitor-BZ46W4IA.js → daemon-trust-policy-monitor-UL73ADOZ.js} +1 -1
  129. package/chunks/{deferred-core-runtime-YC5XIWEI.js → deferred-core-runtime-PT747R7S.js} +1 -1
  130. package/chunks/{edit-LOWDEKPX.js → edit-4PJ3NPFA.js} +1 -1
  131. package/chunks/{enterPlanMode-NGSATDRH.js → enterPlanMode-KQ62QN7S.js} +1 -1
  132. package/chunks/{environment-CVIB5DW4.js → environment-H4HADXGA.js} +1 -1
  133. package/chunks/{errors-USKSVZFO.js → errors-OSD4ZZGR.js} +1 -1
  134. package/chunks/{execution-tool-QSJLRU5N.js → execution-tool-PHHGLKWC.js} +1 -1
  135. package/chunks/{execution-worker-TQEIC4AJ.js → execution-worker-MH3CV66T.js} +1 -1
  136. package/chunks/{exitPlanMode-AW2HOTIK.js → exitPlanMode-OU5YP4XN.js} +1 -1
  137. package/chunks/{fast-path-ZBD7IYQM.js → fast-path-WKOMHBWN.js} +1 -1
  138. package/chunks/{glob-7U6FQSWZ.js → glob-FYCOEQPM.js} +1 -1
  139. package/chunks/{goal-tools-5ZB6GPCJ.js → goal-tools-T27GSDNM.js} +1 -1
  140. package/chunks/{handleAutoUpdate-MLUFTWFP.js → handleAutoUpdate-XXCPJLKO.js} +1 -1
  141. package/chunks/{i18n-QAPQLOC3.js → i18n-3B2PRJM2.js} +1 -1
  142. package/chunks/{initializer-B27IZ7K4.js → initializer-HSFVDRTR.js} +1 -1
  143. package/chunks/{installationInfo-SAMHABWV.js → installationInfo-SJJ2DYZ6.js} +1 -1
  144. package/chunks/{interactive-mod-session-7LQ5CYUR.js → interactive-mod-session-BWY2JRSQ.js} +1 -1
  145. package/chunks/{list-TDMJQDQO.js → list-TGCI3MBM.js} +1 -1
  146. package/chunks/{llm-DQNQEAFW.js → llm-FYR73GKD.js} +4 -4
  147. package/chunks/{loadedSettingsAdapter-ZQK5KMEW.js → loadedSettingsAdapter-DUDCINQL.js} +1 -1
  148. package/chunks/{local-ZRC4XZCJ.js → local-7PEOBJKE.js} +1 -1
  149. package/chunks/{local-execution-environment-WJVCE26F.js → local-execution-environment-Q4OOA7BL.js} +1 -1
  150. package/chunks/{loggingContentGenerator-ALSG42YA.js → loggingContentGenerator-VVESQOIQ.js} +1 -1
  151. package/chunks/{loop-wakeup-LFU4LDJM.js → loop-wakeup-M2XLAAKZ.js} +1 -1
  152. package/chunks/{manage-memory-FBL6CHX2.js → manage-memory-FRVWHM2C.js} +1 -1
  153. package/chunks/{managed-execution-engine-FX7FDAWW.js → managed-execution-engine-AVIM6AQU.js} +1 -1
  154. package/chunks/{managed-local-serve-B2KOLPB5.js → managed-local-serve-GIXHGFIU.js} +1 -1
  155. package/chunks/{managed-npm-update-2MKV7UOI.js → managed-npm-update-3QSXGSHW.js} +1 -1
  156. package/chunks/{managed-runtime-attestation-worker-DBAHM5MN.js → managed-runtime-attestation-worker-ML4TCRAW.js} +1 -1
  157. package/chunks/{managed-runtime-bootstrap-MREL5UC2.js → managed-runtime-bootstrap-JWJFGLBM.js} +1 -1
  158. package/chunks/{managed-runtime-session-worker-YN4KML7A.js → managed-runtime-session-worker-4ISKROGZ.js} +1 -1
  159. package/chunks/{managed-runtime-ssh-worker-GUKAZFAJ.js → managed-runtime-ssh-worker-C44V2CPM.js} +1 -1
  160. package/chunks/{managed-session-authority-MFEINLXC.js → managed-session-authority-UJ3FSKMD.js} +1 -1
  161. package/chunks/{mcp-TS5PX5FY.js → mcp-BWCLHHZ6.js} +1 -1
  162. package/chunks/{memory-ZYPCFYPF.js → memory-5XQ2JVNS.js} +1 -1
  163. package/chunks/{model-call-collection-TNBMD3YL.js → model-call-collection-DXK2SIDR.js} +1 -1
  164. package/chunks/{model-configuration-6KTQQTMO.js → model-configuration-6OLZS4C3.js} +1 -1
  165. package/chunks/{modelConfigUtils-LCZZ3EQU.js → modelConfigUtils-5S5PC2RR.js} +1 -1
  166. package/chunks/{monitor-KCCNIKLE.js → monitor-6GKCWWUI.js} +1 -1
  167. package/chunks/{nonInteractiveCli-JG6PKBAD.js → nonInteractiveCli-ROHAB2H7.js} +1 -1
  168. package/chunks/{nonInteractiveToolExecutor-R5CTTWKD.js → nonInteractiveToolExecutor-OWCCSC5Y.js} +1 -1
  169. package/chunks/{notebook-edit-KIWE2XOA.js → notebook-edit-WNRQ3QJZ.js} +1 -1
  170. package/chunks/{omni-IFTMWBMU.js → omni-DJ5RGNKA.js} +1 -1
  171. package/chunks/{openaiContentGenerator-XP3VPU6C.js → openaiContentGenerator-237NVB63.js} +1 -1
  172. package/chunks/{openaiResponsesContentGenerator-ZJ6C22EA.js → openaiResponsesContentGenerator-J33TCZKQ.js} +1 -1
  173. package/chunks/{pidfile-42P24JIA.js → pidfile-F7IYTFLX.js} +1 -1
  174. package/chunks/{processUtils-I2XOO5U2.js → processUtils-C6CSXITS.js} +1 -1
  175. package/chunks/{prompt-terminal-ledger-7EW46VQ4.js → prompt-terminal-ledger-ZGYWPFJF.js} +1 -1
  176. package/chunks/{reactive-degrade-O4JO7MOX.js → reactive-degrade-QKXPZQ3W.js} +1 -1
  177. package/chunks/{read-file-VGC4O7F2.js → read-file-GSNUMHRE.js} +1 -1
  178. package/chunks/{resumeHistoryUtils-QMVIHQRW.js → resumeHistoryUtils-4GUCHQGU.js} +1 -1
  179. package/chunks/{review-N3VFZQMI.js → review-M2QGZFIO.js} +1 -1
  180. package/chunks/{ripGrep-JY4PZABK.js → ripGrep-X4JTJZC6.js} +1 -1
  181. package/chunks/{run-qwen-serve-4MZRQFXK.js → run-qwen-serve-4WW37RL2.js} +1 -1
  182. package/chunks/{runtime-OL7B72CH.js → runtime-EFHJ6REE.js} +1 -1
  183. package/chunks/{sandboxConfig-EJTMWZHD.js → sandboxConfig-5XMIRDS4.js} +1 -1
  184. package/chunks/{scheduled-tasks-XQSZWZXG.js → scheduled-tasks-ZCYM5YQJ.js} +1 -1
  185. package/chunks/{scheduler-3TIRZEVB.js → scheduler-5UAKCD5Z.js} +1 -1
  186. package/chunks/{search-memory-P5KOTUVV.js → search-memory-KKPYK33Q.js} +1 -1
  187. package/chunks/{send-message-KFSKFXLX.js → send-message-KOZRSWXO.js} +1 -1
  188. package/chunks/{serve-EQN6QAXF.js → serve-5HSHEBMT.js} +1 -1
  189. package/chunks/{server-CCEHAI25.js → server-MC6KHP3G.js} +3 -3
  190. package/chunks/{session-HNUJSV5A.js → session-Z5HFG4IQ.js} +1 -1
  191. package/chunks/{session-attachments-root-O3YQ7HWD.js → session-attachments-root-K2E5ETD4.js} +1 -1
  192. package/chunks/{session-execution-engine-selector-LZBHS3UO.js → session-execution-engine-selector-NZA6CAJB.js} +1 -1
  193. package/chunks/{session-pr-refresh-L5Z5WCXS.js → session-pr-refresh-OYJ56U3L.js} +1 -1
  194. package/chunks/{sessionService-MMPZUN5X.js → sessionService-BC56MX3G.js} +1 -1
  195. package/chunks/{settings-7PYHXPN4.js → settings-OHB77GXH.js} +1 -1
  196. package/chunks/{shell-E6QLKRVU.js → shell-VKSH7JVL.js} +1 -1
  197. package/chunks/{skill-55IZUUM5.js → skill-HQ4C2C3X.js} +1 -1
  198. package/chunks/{skill-settings-A2M5BPH7.js → skill-settings-6WPQFE3V.js} +1 -1
  199. package/chunks/{spawnChannel-KWU26CB7.js → spawnChannel-MXKVLS24.js} +1 -1
  200. package/chunks/{standalone-update-32WYZ3BJ.js → standalone-update-NZP3OAZZ.js} +1 -1
  201. package/chunks/{start-opentui-ui-6MCAEWAW.js → start-opentui-ui-25YQQD3O.js} +1 -1
  202. package/chunks/{startInteractiveUI-657JWOTK.js → startInteractiveUI-DWQJNIIV.js} +2 -2
  203. package/chunks/{team-create-ARICYIQB.js → team-create-RSD7IADX.js} +1 -1
  204. package/chunks/{team-plan-approval-JPRE6Q3R.js → team-plan-approval-XAOKZ6BR.js} +1 -1
  205. package/chunks/{terminal-image-renderer-HVIZ2VNE.js → terminal-image-renderer-P5AGEOYS.js} +1 -1
  206. package/chunks/{theme-manager-UEPLIBUP.js → theme-manager-YBKJYPVQ.js} +1 -1
  207. package/chunks/{tool-call-EFJKXI3Z.js → tool-call-HJCSPR6N.js} +1 -1
  208. package/chunks/{tool-result-media-LMIYNXSD.js → tool-result-media-SPWVV3OS.js} +1 -1
  209. package/chunks/{tool-search-D7HQTRQG.js → tool-search-YWCOODLL.js} +1 -1
  210. package/chunks/{total-session-admission-67QMR44O.js → total-session-admission-HKACVEI2.js} +1 -1
  211. package/chunks/{trustedFolders-HARYVS3F.js → trustedFolders-BXLZULWO.js} +1 -1
  212. package/chunks/{update-relaunch-NVNPOK5J.js → update-relaunch-CBJVLG6S.js} +1 -1
  213. package/chunks/{updateCheck-7NMXUCTN.js → updateCheck-2J6RY3L3.js} +1 -1
  214. package/chunks/{upload-config-W2SICJ32.js → upload-config-EN5XYA3V.js} +1 -1
  215. package/chunks/{useAutoAcceptIndicator-ELMIP4TJ.js → useAutoAcceptIndicator-LF7VIUER.js} +1 -1
  216. package/chunks/{validateNonInterActiveAuth-CP5WFNAE.js → validateNonInterActiveAuth-63TR5JOG.js} +1 -1
  217. package/chunks/{version-SIM74L5K.js → version-F22SKNME.js} +1 -1
  218. package/chunks/{web-fetch-537RS6IX.js → web-fetch-ULH7TOLR.js} +1 -1
  219. package/chunks/{web-search-O27MYFSW.js → web-search-C3ORWAWR.js} +1 -1
  220. package/chunks/{workflow-6QF4RMYM.js → workflow-4ATPGZ5N.js} +1 -1
  221. package/chunks/{workflow-ancestor-trust-CABLU3VV.js → workflow-ancestor-trust-AJ27EBZD.js} +1 -1
  222. package/chunks/{workspace-agents-5WP3PY7W.js → workspace-agents-VLAJGYJF.js} +1 -1
  223. package/chunks/{workspace-providers-status-7G2EJJEO.js → workspace-providers-status-TFAXNJ6L.js} +1 -1
  224. package/chunks/{workspace-recovery-worker-ICCIDEWU.js → workspace-recovery-worker-GKYYJPXV.js} +1 -1
  225. package/chunks/{workspace-registration-store-WHXMNQQQ.js → workspace-registration-store-ANR3STGQ.js} +1 -1
  226. package/chunks/{workspace-registry-NXBODLYH.js → workspace-registry-OVHNLVBM.js} +1 -1
  227. package/chunks/{workspace-runtime-coordinator-CJXS273B.js → workspace-runtime-coordinator-IEN2G7JP.js} +1 -1
  228. package/chunks/{workspace-service-HUDE2RXN.js → workspace-service-NISFZTBE.js} +1 -1
  229. package/chunks/{workspace-skills-status-FJC6U62F.js → workspace-skills-status-QRF5ZXMT.js} +1 -1
  230. package/chunks/{workspace-trust-reconciler-ZIQ3A5ZB.js → workspace-trust-reconciler-X3XMX2GJ.js} +1 -1
  231. package/chunks/{write-file-652YGG7I.js → write-file-SF42KZAH.js} +1 -1
  232. package/chunks/{zoom-image-YEH4O74G.js → zoom-image-4UMB6G3P.js} +1 -1
  233. package/cli.js +2 -2
  234. package/execution-worker.js +1 -1
  235. package/package.json +2 -2
  236. package/chunks/chunk-56PVVXUG.js +0 -8
  237. package/chunks/chunk-AJ75BPTA.js +0 -31
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-ORVQPZMQ.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-SHLTP6ZB.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-PFKTTUGS.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
3
+ import{memoryImportReservation,validateMemoryImportBatchProposal}from"./chunk-C3ZJUOTJ.js";import{MEMORY_IMPORT_BUDGET,MemoryImportRequestError,digest,packMemoryImportSections,previewSource}from"./chunk-MCY3IS2E.js";import{rebuildAutoMemoryIndexAtRoot,tokenizeMemoryRecallTerms,tokenizeMemoryRecallText}from"./chunk-POMEWCFJ.js";import{parseAutoMemoryTopicDocument,resolveTrustedMemoryFile,scanAutoMemorySnapshot}from"./chunk-6RGS6DOB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{getImportedProjectMemoryRoot,getMemoryRootTrustedAnchor,getUserAutoMemoryRoot}from"./chunk-CQGP2BAW.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_proper_lockfile=__toESM(require_proper_lockfile(),1);import*as fs from"node:fs/promises";import{constants}from"node:fs";import{randomUUID}from"node:crypto";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";var MemoryImportNotFoundError=class extends Error{static{__name(this,"MemoryImportNotFoundError")}code="ENOENT"};var ImportBudgetError=class extends Error{static{__name(this,"ImportBudgetError")}};var ImportContextError=class extends Error{static{__name(this,"ImportContextError")}};var heldLocks=new AsyncLocalStorage;var exists=__name(async file=>fs.lstat(file).then(()=>true,error=>{if(error.code==="ENOENT")return false;throw error}),"exists");async function privateDirectory(directory,anchor){const relative=path.relative(anchor,directory);if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import path escapes runtime.");let current=anchor;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);await fs.mkdir(current,{mode:448}).catch(error=>{if(error.code!=="EEXIST")throw error});const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Import runtime directory must not be a symlink.")}}__name(privateDirectory,"privateDirectory");async function readJson(file){const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>16*1024*1024)throw new Error("Invalid import state file.");const buffer=Buffer.alloc(stat.size+1);const{bytesRead}=await handle.read(buffer,0,buffer.length,0);if(bytesRead>stat.size)throw new Error("Import state exceeds the supported limit.");return JSON.parse(buffer.subarray(0,bytesRead).toString("utf8"))}finally{await handle.close()}}__name(readJson,"readJson");async function writeJson(file,value){heldLocks.getStore()?.throwIfAborted();const tmp=`${file}.${randomUUID()}.tmp`;await fs.writeFile(tmp,JSON.stringify(value),{mode:384,flag:"wx"});try{heldLocks.getStore()?.throwIfAborted();await fs.rename(tmp,file)}finally{await fs.rm(tmp,{force:true})}}__name(writeJson,"writeJson");async function abortable(signal,work){signal.throwIfAborted();let abort;const cancelled=new Promise((_resolve,reject)=>{abort=__name(()=>reject(new Error("Import cancelled.")),"abort");signal.addEventListener("abort",abort,{once:true})});try{return await Promise.race([work(),cancelled])}finally{signal.removeEventListener("abort",abort)}}__name(abortable,"abortable");function publicTask(task){const{requestDigest:_requestDigest,...result}=task;return structuredClone({...result,usage:task.usage??{modelCalls:0,reservedTokens:0},budget:task.budget??{maxCalls:0,maxReservedTokens:0},result:{sourceSections:task.items.length,newDocuments:task.items.filter(item=>item.status==="added").reduce((n,item)=>n+(item.refs?.length??0),0),duplicateSections:task.items.filter(item=>item.status==="duplicate").length,conflictSections:task.items.filter(item=>item.status==="conflict").length,failedSections:task.items.filter(item=>item.status==="failed").length}})}__name(publicTask,"publicTask");function selectImportContext(existing,sources){const queries=sources.map(source=>({text:source.normalize("NFKC").toLowerCase(),terms:tokenizeMemoryRecallTerms(source)}));const index=existing.map(item=>{const parsed=parseAutoMemoryTopicDocument("existing.md",item.content);if(!parsed)throw new ImportContextError("Existing memory has no bounded metadata index. Repair its native metadata before importing.");const metadata=JSON.stringify({name:parsed.title,description:parsed.description,type:parsed.type,category:parsed.category,keywords:parsed.keywords,usage_scenarios:parsed.usageScenarios});const words=tokenizeMemoryRecallText([parsed.title,...parsed.keywords].join(" "));const anchors=[parsed.title,parsed.description].map(text=>text.normalize("NFKC").toLowerCase().trim()).filter(text=>tokenizeMemoryRecallText(text).length>=2);const body=parsed.body.normalize("NFKC").toLowerCase().trim();const relevant=queries.some(({text,terms})=>{if(anchors.some(anchor=>text.includes(anchor))||body.length>0&&text.includes(body))return true;const shared=words.filter(word=>terms.has(word));return shared.length>=2&&shared.length>=words.length/2});return{ref:item.ref,content:relevant?item.content:metadata,indexOnly:!relevant}});const context=[];let bytes=2;for(const entry of[...index.filter(item=>!item.indexOnly),...index.filter(item=>item.indexOnly)]){const size=Buffer.byteLength(JSON.stringify(entry))+(context.length?1:0);if(bytes+size>MEMORY_IMPORT_BUDGET.contextBytes){if(!entry.indexOnly)throw new ImportContextError("Relevant existing evidence exceeds the 32 KiB import context budget. Select a narrower source group or consolidate existing memory before retrying. No model call was made.");continue}bytes+=size;context.push(entry)}return context}__name(selectImportContext,"selectImportContext");function respectsImportScope(proposal,scope){return scope!=="user"||proposal.documents.every(content=>{const type=parseAutoMemoryTopicDocument("import.md",content)?.type;return type==="user"||type==="feedback"})}__name(respectsImportScope,"respectsImportScope");var MemoryImportService=class{constructor(options){this.options=options;this.owner=digest(path.resolve(options.projectRoot))}static{__name(this,"MemoryImportService")}base=Storage.getRuntimeBaseDir();state=path.join(this.base,"memory-import");owner;workers=new Map;controllers=new Map;async readState(file){const relative=path.relative(this.base,path.dirname(file));if(relative.startsWith("..")||path.isAbsolute(relative))throw new Error("Import state escapes runtime.");let current=this.base;for(const part of["",...relative.split(path.sep).filter(Boolean)]){if(part)current=path.join(current,part);const stat=await fs.lstat(current);if(!stat.isDirectory()||stat.isSymbolicLink())throw new Error("Invalid import state directory.")}return readJson(file)}taskDir(id){if(!/^[a-f0-9]{64}$/.test(id))throw new MemoryImportRequestError("Invalid import batch ID.");return path.join(this.state,"batches",this.owner,id)}async assertRuntimeOutsideGit(){let current=path.resolve(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a runtime directory outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}await fs.mkdir(this.base,{recursive:true,mode:448});current=await fs.realpath(this.base);while(true){if(await exists(path.join(current,".git")))throw new Error("Memory import requires a private runtime outside Git checkouts.");const parent=path.dirname(current);if(parent===current)break;current=parent}}async prepare(){this.options.assertActive();await this.assertRuntimeOutsideGit();await privateDirectory(path.join(this.state,"batches",this.owner),this.base)}async locked(directory,run,signal){await privateDirectory(directory,this.base);const ownership=new AbortController;const parent=heldLocks.getStore();const held=parent?AbortSignal.any([parent,ownership.signal]):ownership.signal;const work=signal?AbortSignal.any([signal,held]):held;let release;while(!release){work.throwIfAborted();this.options.assertActive();try{release=await import_proper_lockfile.default.lock(directory,{realpath:false,stale:12e4,update:1e4,retries:0,onCompromised:__name(()=>{ownership.abort(new Error("Import lock lost."))},"onCompromised")})}catch(error){if(error.code!=="ELOCKED")throw error;await new Promise(resolve=>setTimeout(resolve,250))}}try{work.throwIfAborted();const result=await heldLocks.run(held,()=>run(work));held.throwIfAborted();return result}finally{try{if(!ownership.signal.aborted)await release()}finally{ownership.abort(new Error("Import lock released."))}}}async submit(input,selections,key){this.options.assertActive();const preview=previewSource(input);if(typeof key!=="string"||!/^[\w-]{1,128}$/.test(key)||!Array.isArray(selections)||!selections.length||selections.length>2048)throw new MemoryImportRequestError("Provide an idempotency key and explicit non-empty selection.");const seen=new Set;const selected=selections.map(value=>{if(!value||typeof value!=="object")throw new MemoryImportRequestError("Invalid selection.");const selection=value;const section=preview.sections.find(item=>item.id===selection.id&&item.selectable);if(!section||seen.has(selection.id)||!["project","user"].includes(selection.scope))throw new MemoryImportRequestError("Invalid, duplicate or unavailable section selection.");seen.add(selection.id);return{...section,scope:selection.scope}}).sort((a,b)=>a.id.localeCompare(b.id));const retained=JSON.stringify({sections:selected});if(Buffer.byteLength(retained)>16*1024*1024)throw new MemoryImportRequestError("Selected contextual source exceeds the retained snapshot limit.");const requestDigest=digest(JSON.stringify(selected));const id=digest(`${this.owner}\0${key}`);await this.prepare();const dir=this.taskDir(id);return this.locked(path.join(this.state,"admission",this.owner),async()=>{this.options.assertActive();if(await exists(path.join(dir,"task.json"))){const task2=await this.readState(path.join(dir,"task.json"));if(task2.requestDigest!==requestDigest)throw new MemoryImportRequestError("Idempotency key was already used with a different selection.");this.kick(id);return publicTask(task2)}await privateDirectory(dir,this.base);await writeJson(path.join(dir,"source.json"),{sections:selected});const now=new Date().toISOString();const task={version:1,kind:"task",id,status:"queued",createdAt:now,updatedAt:now,requestDigest,usage:{modelCalls:0,reservedTokens:0},budget:{maxCalls:MEMORY_IMPORT_BUDGET.maxCalls,maxReservedTokens:MEMORY_IMPORT_BUDGET.maxReservedTokens},items:selected.map(section=>({id:section.id,scope:section.scope,status:"pending"}))};await writeJson(path.join(dir,"task.json"),task);this.kick(id);return publicTask(task)})}kick(id){if(this.workers.has(id))return;const worker=heldLocks.exit(()=>this.run(id)).catch(()=>{}).finally(()=>{this.workers.delete(id);this.controllers.delete(id)});this.workers.set(id,worker)}async recover(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return;await this.assertRuntimeOutsideGit();await privateDirectory(root,this.base);for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(()=>void 0);if(task&&(task.status==="running"||task.status==="queued"))this.kick(id)}}async list(){this.options.assertActive();const root=path.join(this.state,"batches",this.owner);if(!await exists(root))return[];await privateDirectory(root,this.base);const result=[];for(const id of(await fs.readdir(root)).filter(id2=>/^[a-f0-9]{64}$/.test(id2))){const task=await this.get(id).catch(()=>void 0);if(task)result.push(task)}return result.sort((a,b)=>b.createdAt.localeCompare(a.createdAt))}async get(id){this.options.assertActive();const task=await this.readState(path.join(this.taskDir(id),"task.json")).catch(cause=>{if(cause.code==="ENOENT")throw new MemoryImportNotFoundError("Import batch not found.",{cause});throw cause});if(task.status!=="completed"&&await exists(path.join(this.taskDir(id),"cancel.json")))task.status="cancelled";return publicTask(task)}async source(id,sectionId){await this.get(id);const source=await this.readState(path.join(this.taskDir(id),"source.json"));const section=source.sections.find(item=>item.id===sectionId);if(!section)throw new MemoryImportRequestError("Source section not found in this batch.");return section}async cancel(id){this.options.assertActive();this.controllers.get(id)?.abort();const task=await this.get(id);if(task.status==="completed")return task;await writeJson(path.join(this.taskDir(id),"cancel.json"),{cancelled:true});this.controllers.get(id)?.abort();await this.workers.get(id);return this.get(id)}async retry(id){await this.get(id);await this.prepare();await this.workers.get(id);const dir=this.taskDir(id);const result=await this.locked(dir,async()=>{const task=await this.readState(path.join(dir,"task.json"));if(task.status==="completed")return publicTask(task);await fs.rm(path.join(dir,"cancel.json"),{force:true});for(const item of task.items)if(item.status==="failed"){item.status="pending";delete item.reason}task.status="queued";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task);return publicTask(task)});this.kick(id);return result}async idle(id){await this.workers.get(id);return this.get(id)}async run(id){const dir=this.taskDir(id);const controller=new AbortController;this.controllers.set(id,controller);await this.locked(dir,async signal=>{const task=await this.readState(path.join(dir,"task.json"));if(!["queued","running"].includes(task.status))return;const source=await this.readState(path.join(dir,"source.json"));if(!task.usage){task.usage={modelCalls:0,reservedTokens:0};task.budget={maxCalls:0,maxReservedTokens:0}}task.budget??={maxCalls:0,maxReservedTokens:0};task.status="running";await writeJson(path.join(dir,"task.json"),task);for(const section of packMemoryImportSections(source.sections).flat()){const item=task.items.find(item2=>item2.id===section.id);if(item.status!=="pending")continue;if(await exists(path.join(dir,"cancel.json")))controller.abort();if(controller.signal.aborted)break;try{this.options.assertActive();Object.assign(item,await this.importSection(section,id,signal,(before,ledger,proposalSignal)=>this.prepareProposal(section,source,task,before,ledger,proposalSignal),async()=>{if(await exists(path.join(dir,"cancel.json")))controller.abort();controller.signal.throwIfAborted();this.options.assertActive()}))}catch(error){if(controller.signal.aborted)break;item.status="failed";item.reason=error instanceof ImportBudgetError||error instanceof ImportContextError?error.message:"Import could not finish. Existing memories were preserved; retry after resolving runtime, model or storage availability."}task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)}task.status=controller.signal.aborted?"cancelled":task.items.some(item=>item.status==="failed")?"partial":"completed";task.updatedAt=new Date().toISOString();await writeJson(path.join(dir,"task.json"),task)},controller.signal)}async prepareProposal(section,source,task,before,ledger,signal){const dir=this.taskDir(task.id);const journalFile=path.join(dir,"proposals.json");const journals=await exists(journalFile)?await this.readState(journalFile):[];let journal=journals.find(entry=>entry.scope===section.scope&&entry.sections.some(item=>item.id===section.id));if(journal&&!respectsImportScope(journal.proposal.items.find(item=>item.id===section.id),section.scope)){journal.sections=journal.sections.filter(item=>item.id!==section.id);journal.proposal.items=journal.proposal.items.filter(item=>item.id!==section.id);if(!journal.sections.length)journals.splice(journals.indexOf(journal),1);await writeJson(journalFile,journals);journal=void 0}if(!journal){const eligible=source.sections.filter(candidate=>candidate.scope===section.scope&&candidate.groupId===section.groupId&&task.items.some(item=>item.id===candidate.id&&item.status==="pending")&&!ledger[candidate.id]&&!journals.some(entry=>entry.sections.some(item=>item.id===candidate.id)));const batch=packMemoryImportSections(eligible).find(items=>items.some(item=>item.id===section.id));if(!batch)throw new Error("Source batch is unavailable.");const input={scope:section.scope,sources:batch.map(({id,content})=>({id,content})),existing:selectImportContext(before.existing,batch.map(item=>item.content))};const reserved=memoryImportReservation(input);if(task.usage.modelCalls>=Math.min(task.budget.maxCalls,MEMORY_IMPORT_BUDGET.maxCalls)||task.usage.reservedTokens+reserved>Math.min(task.budget.maxReservedTokens,MEMORY_IMPORT_BUDGET.maxReservedTokens))throw new ImportBudgetError("Import budget exhausted. Retry preserves this budget; split remaining sources into an explicitly confirmed new task.");signal.throwIfAborted();task.usage.modelCalls++;task.usage.reservedTokens+=reserved;await writeJson(path.join(dir,"task.json"),task);let proposal;try{proposal=validateMemoryImportBatchProposal(await abortable(signal,()=>this.options.propose(input,signal)),batch.map(item=>item.id));if(proposal.items.some(item=>!respectsImportScope(item,section.scope)))throw new ImportContextError("Model returned project knowledge for user memory. Retry to request a scope-valid response; consumed budget is retained.")}catch(error){if(!signal.aborted){for(const item of task.items)if(batch.some(section2=>section2.id===item.id)){item.status="failed";item.reason="Model batch failed validation or execution; explicit retry retains its consumed budget."}}throw error}signal.throwIfAborted();journal={scope:section.scope,sections:batch.map(item=>({id:item.id,key:item.id})),baseline:before.existing.map(item=>({ref:item.ref,digest:digest(item.content)})),proposal};journals.push(journal);await writeJson(journalFile,journals)}const expected=new Map(journal.baseline.map(item=>[item.ref,item.digest]));for(const record of Object.values(ledger)){if(record.phase==="committed")for(const output of record.outputs){const ref=`${section.scope}:${output.relativePath}`;if(!expected.has(ref))expected.set(ref,output.digest)}}if(expected.size!==before.existing.length||before.existing.some(item=>expected.get(item.ref)!==digest(item.content)))return{decision:"conflict",reason:"Existing memory changed since this batch was consolidated; retained proposals cannot overwrite edits or restore forgotten knowledge.",documents:[]};return journal.proposal.items.find(item=>item.id===section.id)}async snapshot(scope){const snapshot=await scanAutoMemorySnapshot(this.options.projectRoot,{scopes:[scope],trustedProject:true,uncapped:true});if(!snapshot.sourceStatus.complete)throw new Error("Existing memory scan is incomplete.");const existing=[];for(const doc of snapshot.docs)existing.push({ref:`${scope}:${doc.relativePath}`,content:await fs.readFile(doc.filePath,"utf8")});existing.sort((a,b)=>a.ref.localeCompare(b.ref));return{version:digest(JSON.stringify(existing)),existing}}async importSection(section,batchId,signal,propose,assertCommit){const root=section.scope==="user"?getUserAutoMemoryRoot():getImportedProjectMemoryRoot(this.options.projectRoot,true);const scopeState=path.join(this.state,"scopes",digest(root));return this.locked(scopeState,async signal2=>{signal2.throwIfAborted();this.options.assertActive();if(await exists(root)&&(await fs.lstat(root)).isSymbolicLink())throw new ImportContextError("Memory import does not support a symlinked memory root. Use a non-symlink memory root before retrying; existing memories were not changed.");const ledgerPath=path.join(scopeState,"ledger.json");const ledger=await exists(ledgerPath)?await this.readState(ledgerPath):{};const key=section.id;let previous=ledger[key];const discardUnpublishedIntent=__name(async stage2=>{signal2.throwIfAborted();this.options.assertActive();delete ledger[key];await writeJson(ledgerPath,ledger);heldLocks.getStore()?.throwIfAborted();await fs.rm(stage2,{recursive:true,force:true})},"discardUnpublishedIntent");const outcome=__name((status,reason)=>({id:section.id,scope:section.scope,status,...reason?{reason}:{}}),"outcome");if(previous?.phase==="intent"){const stage2=path.join(scopeState,previous.stage);if(await exists(stage2)&&!await exists(path.join(root,"imported",key))&&(await this.snapshot(section.scope)).version!==previous.memoryVersion){await discardUnpublishedIntent(stage2);previous=void 0}}if(previous){const stage2=path.join(scopeState,previous.stage);const destination=path.join(root,"imported",key);if(previous.phase==="intent"&&await exists(stage2)&&!await exists(destination)){for(const output of previous.outputs){const file=path.join(stage2,path.basename(output.relativePath));if(digest(await fs.readFile(file,"utf8"))!==output.digest)throw new Error("Invalid staged import.")}signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage2,destination)}for(const output of previous.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously imported memory was edited or forgotten; it will not be restored.")}previous.phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);if(previous.batchId===batchId)return{...previous.outcome,id:section.id,scope:section.scope};return outcome(previous.outcome.status==="added"?"duplicate":previous.outcome.status,"This source has already been processed.")}const before=await this.snapshot(section.scope);const proposal=await propose(before,ledger,signal2);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version)return outcome("conflict","Existing memory changed during consolidation; preview and retry the source.");await assertCommit();if(proposal.decision==="conflict")return outcome("conflict",proposal.reason);if(proposal.decision!=="new"){const result2=outcome(proposal.decision==="skip"?"skipped":"duplicate",proposal.reason);ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const documents=[];for(const content of new Set(proposal.documents)){const parsed=parseAutoMemoryTopicDocument("import.md",content);if(!parsed)throw new Error("Invalid native memory.");if(section.scope==="user"&&parsed.type!=="user"&&parsed.type!=="feedback")throw new Error("Project knowledge cannot be imported into user memory.");const bodyDigest=digest(parsed.body.trim());for(const[sourceId,record]of Object.entries(ledger)){if(record.outputs.some(output=>output.bodyDigest===bodyDigest)){if(record.phase==="intent"&&!await exists(path.join(root,"imported",sourceId)))continue;for(const output of record.outputs){const file=await resolveTrustedMemoryFile(root,getMemoryRootTrustedAnchor(root),output.relativePath);if(!file||digest(await fs.readFile(file,"utf8"))!==output.digest)return outcome("conflict","Previously edited or forgotten imported knowledge cannot be recreated.")}}}if(before.existing.some(existing=>parseAutoMemoryTopicDocument("existing.md",existing.content)?.body.trim()===parsed.body.trim()))continue;if(!documents.some(existing=>parseAutoMemoryTopicDocument("new.md",existing)?.body.trim()===parsed.body.trim()))documents.push(content)}if(!documents.length){const result2=outcome("duplicate","All proposed knowledge already exists.");ledger[key]={batchId,phase:"committed",outputs:[],stage:"",outcome:result2};await writeJson(ledgerPath,ledger);return result2}const stageName=`stage-${key}`;const stage=path.join(scopeState,stageName);if(await exists(stage)){await privateDirectory(stage,this.base);await fs.rm(stage,{recursive:true})}await privateDirectory(stage,this.base);const outputs=[];for(const[index,content]of documents.entries()){const filename=`${index}.md`;await fs.writeFile(path.join(stage,filename),content,{flag:"wx",mode:384});outputs.push({relativePath:`imported/${key}/${filename}`,digest:digest(content),bodyDigest:digest(parseAutoMemoryTopicDocument("import.md",content).body.trim())})}const result={...outcome("added",proposal.reason),refs:outputs.map(output=>`${section.scope}:${output.relativePath}`)};ledger[key]={batchId,phase:"intent",outputs,stage:stageName,memoryVersion:before.version,outcome:result};await writeJson(ledgerPath,ledger);signal2.throwIfAborted();this.options.assertActive();await privateDirectory(path.join(root,"imported"),this.base);signal2.throwIfAborted();this.options.assertActive();if((await this.snapshot(section.scope)).version!==before.version){await discardUnpublishedIntent(stage);return outcome("conflict","Existing memory changed before publication.")}await assertCommit();heldLocks.getStore()?.throwIfAborted();await fs.rename(stage,path.join(root,"imported",key));ledger[key].phase="committed";await writeJson(ledgerPath,ledger);await rebuildAutoMemoryIndexAtRoot(root,section.scope);return result},signal)}};export{MemoryImportNotFoundError,MemoryImportService};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{buildModelReasoningRoutePreview}from"./chunk-JQOLNQQN.js";import{snapshotProcessEnv}from"./chunk-EXVVGGII.js";import{publicAuxModelSelectorValue}from"./chunk-L42NTHIT.js";import{getModelConfigurationKey}from"./chunk-7F5IYTVE.js";import{STATUS_SCHEMA_VERSION}from"./chunk-YCAEGUZI.js";import{loadSettings}from"./chunk-23543L6E.js";import{getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-56PVVXUG.js";import{ACP_ROUTE_ID_PREFIX,buildAcpModelOptions,getCurrentAcpModelId,parseAcpBaseModelId,sanitizeProviderBaseUrl}from"./chunk-YQXX44YA.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ModelsConfig,captureReasoningSnapshot,resolveReasoningForModel}from"./chunk-AJ75BPTA.js";import{tokenLimit}from"./chunk-EV2CXPMN.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("WORKSPACE_PROVIDERS_STATUS");function createWorkspaceProvidersStatusProvider(options={}){return async(workspaceCwd,acpChannelLive)=>buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options)}__name(createWorkspaceProvidersStatusProvider,"createWorkspaceProvidersStatusProvider");function buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options){try{const loaded=loadSettings(workspaceCwd,options.env?{skipLoadEnvironment:true,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted}:{consumeCorruptionEnvVars:true,skipLoadEnvironment:options.workspaceTrusted===false,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted});const settings=loaded.merged;const env=options.env??snapshotProcessEnv();const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);const argv={model:options.argv?.model,openaiApiKey:options.argv?.openaiApiKey,openaiBaseUrl:options.argv?.openaiBaseUrl,openaiLogging:options.argv?.openaiLogging,openaiLoggingDir:options.argv?.openaiLoggingDir};const resolvedCliConfig=resolveCliGenerationConfig({argv,settings,selectedAuthType,env});const modelsConfig=new ModelsConfig({initialAuthType:resolvedCliConfig.authType,modelProvidersConfig:settings.modelProviders,providerProtocolConfig:settings.providerProtocol,generationConfig:resolvedCliConfig.generationConfig,generationConfigSources:resolvedCliConfig.sources});const currentAuth=resolvedCliConfig.authType;let currentModelId=(resolvedCliConfig.model||modelsConfig.getModel()||"").trim();const requestedModelId=currentModelId;if(currentAuth&&!modelsConfig.getResolvedModel(currentAuth,currentModelId)){modelsConfig.syncAfterAuthRefresh(currentAuth,currentModelId);currentModelId=(modelsConfig.getModel()||"").trim()}const usedFallback=currentModelId!==requestedModelId;const hasCurrentModel=currentModelId.length>0;const modelCameFromSettings=!argv.model&&settings.model?.name?.trim()===currentModelId;const currentBaseUrl=usedFallback?modelsConfig.getGenerationConfig().baseUrl:modelCameFromSettings&&settings.model?.baseUrl!==void 0?settings.model.baseUrl||void 0:resolvedCliConfig.sources["baseUrl"]?resolvedCliConfig.baseUrl||void 0:void 0;const currentRegistryBaseUrl=usedFallback?modelsConfig.getCurrentRegistryBaseUrl():modelCameFromSettings&&currentAuth?settings.model?.baseUrl!==void 0?settings.model.baseUrl||null:modelsConfig.getResolvedModel(currentAuth,currentModelId)?.registryBaseUrl??null:void 0;const models=modelsConfig.getAllConfiguredModels();const modelOptions=buildAcpModelOptions(models);const reasoningSnapshot=captureReasoningSnapshot(models);const currentAcpModelId=hasCurrentModel?getCurrentAcpModelId(modelOptions,currentModelId,currentAuth,currentRegistryBaseUrl):void 0;const fastModelId=typeof settings.fastModel==="string"&&settings.fastModel.length>0?settings.fastModel:void 0;const visionModelId=typeof settings.visionModel==="string"&&settings.visionModel.length>0?settings.visionModel:void 0;const approvalMode=resolveApprovalMode(settings);const providers=new Map;for(const option of modelOptions){const{model,effectiveModelId,modelId}=option;if(model.isRuntimeModel)continue;const authType=String(model.authType);let provider=providers.get(authType);if(!provider){provider={kind:"model_provider",status:"ok",authType,current:false,models:[]};providers.set(authType,provider)}const isCurrent=currentAuth===model.authType&&currentAcpModelId===modelId;const resolved=modelsConfig.getResolvedModel(model.authType,model.id,model.registryBaseUrl);const generation={...resolved?.generationConfig,model:model.id,authType:model.authType,baseUrl:resolved?.baseUrl,reasoningSnapshot,reasoningRouteBaseUrl:model.registryBaseUrl??null};const configOptions=buildModelReasoningRoutePreview(generation,resolveReasoningForModel(void 0,generation),settings.model?.reasoningEffort,modelId.startsWith(ACP_ROUTE_ID_PREFIX));const configurationKey=getModelConfigurationKey(loaded,authType,model.id,model.registryBaseUrl);const providerModel={...configurationKey?{configurationKey}:{},modelId,baseModelId:parseAcpBaseModelId(effectiveModelId),name:model.label,...model.description!==void 0?{description:model.description}:{},contextLimit:model.contextWindowSize!==void 0&&model.contextWindowSize>0?model.contextWindowSize:tokenLimit(effectiveModelId),...model.modalities!==void 0?{modalities:model.modalities}:{},...model.baseUrl!==void 0?{baseUrl:sanitizeProviderBaseUrl(model.baseUrl)}:{},...model.envKey!==void 0?{envKey:model.envKey}:{},isCurrent,isRuntime:false,...configOptions?{configOptions}:{}};provider.models.push(providerModel);if(isCurrent)provider.current=true}const current=buildCurrent(currentAuth,currentAcpModelId,currentBaseUrl,fastModelId,visionModelId);return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:true,acpChannelLive,...current?{current}:{},approvalMode,providers:[...providers.values()],...resolvedCliConfig.warnings.length>0?{errors:resolvedCliConfig.warnings.map(warning=>({kind:"providers",status:"warning",error:sanitizeProviderWarning(warning)}))}:{}}}catch(error){return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:false,acpChannelLive,providers:[],errors:[{kind:"providers",status:"error",error:sanitizeProviderWarning(error instanceof Error?error.message:String(error))}]}}}__name(buildWorkspaceProvidersStatus,"buildWorkspaceProvidersStatus");function resolveApprovalMode(settings){const value=settings.tools?.approvalMode;if(typeof value!=="string")return"auto";const normalized=value.trim().toLowerCase().replaceAll("_","-");const mode=normalized==="autoedit"?"auto-edit":normalized;if(APPROVAL_MODES.includes(mode)){return mode}if(value.trim().length>0){debugLogger.warn(`[workspace-providers-status] unrecognized approvalMode "${value}", falling back to auto`)}return"auto"}__name(resolveApprovalMode,"resolveApprovalMode");var URL_LIKE_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\/[^\s'"`<>]+/g;var URL_START_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\//g;function sanitizeProviderWarning(warning){let result="";let index=0;let next=findNextUrlStart(warning,index);while(next){result+=warning.slice(index,next.index);const segmentEnd=findUrlSegmentEnd(warning,next.index,next.marker);const segment=warning.slice(next.index,segmentEnd);result+=sanitizeProviderWarningSegment(segment,next.marker.length);index=segmentEnd;next=findNextUrlStart(warning,index)}return result+warning.slice(index)}__name(sanitizeProviderWarning,"sanitizeProviderWarning");function findNextUrlStart(value,from){URL_START_PATTERN.lastIndex=from;const match=URL_START_PATTERN.exec(value);return match?{index:match.index,marker:match[0]}:void 0}__name(findNextUrlStart,"findNextUrlStart");function findUrlSegmentEnd(value,start,marker){const afterMarker=start+marker.length;const carriageReturn=value.indexOf("\r",afterMarker);const lineFeed=value.indexOf("\n",afterMarker);let lineEnd=value.length;if(carriageReturn!==-1)lineEnd=Math.min(lineEnd,carriageReturn);if(lineFeed!==-1)lineEnd=Math.min(lineEnd,lineFeed);const nextUrl=findNextUrlStart(value,afterMarker);return Math.min(lineEnd,nextUrl?.index??value.length)}__name(findUrlSegmentEnd,"findUrlSegmentEnd");function sanitizeProviderWarningSegment(segment,markerLength){const at=segment.indexOf("@",markerLength);if(at!==-1&&hasCredentialPrefix(segment,markerLength,at)&&segment[at+1]!==void 0&&/[A-Za-z0-9.[\]-]/.test(segment[at+1])){return`${segment.slice(0,markerLength)}${segment.slice(at+1)}`}return segment.replace(URL_LIKE_PATTERN,url=>sanitizeProviderBaseUrl(url))}__name(sanitizeProviderWarningSegment,"sanitizeProviderWarningSegment");function hasCredentialPrefix(segment,markerLength,at){const colon=segment.indexOf(":",markerLength);if(colon===-1||colon>at)return false;const username=segment.slice(markerLength,colon);return!/[/?#\s'"`<>]/.test(username)}__name(hasCredentialPrefix,"hasCredentialPrefix");function buildCurrent(authType,modelId,baseUrl,fastModelId,visionModelId){if(!authType&&!modelId&&!baseUrl&&!fastModelId&&!visionModelId)return void 0;return{...authType?{authType:String(authType)}:{},...modelId?{modelId}:{},...baseUrl?{baseUrl:sanitizeProviderBaseUrl(baseUrl)}:{},...fastModelId?{fastModelId:publicAuxModelSelectorValue(fastModelId)}:{},...visionModelId?{visionModelId:publicAuxModelSelectorValue(visionModelId)}:{}}}__name(buildCurrent,"buildCurrent");export{createWorkspaceProvidersStatusProvider};
3
+ import{buildModelReasoningRoutePreview}from"./chunk-OPFBBIAQ.js";import{snapshotProcessEnv}from"./chunk-EXVVGGII.js";import{publicAuxModelSelectorValue}from"./chunk-L42NTHIT.js";import{getModelConfigurationKey}from"./chunk-CNGBG3X5.js";import{STATUS_SCHEMA_VERSION}from"./chunk-YCAEGUZI.js";import{loadSettings}from"./chunk-JRIVHFCG.js";import{getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-BWLMXGA2.js";import{ACP_ROUTE_ID_PREFIX,buildAcpModelOptions,getCurrentAcpModelId,parseAcpBaseModelId,sanitizeProviderBaseUrl}from"./chunk-YQXX44YA.js";import{APPROVAL_MODES}from"./chunk-JZK2WGXA.js";import{ModelsConfig,captureReasoningSnapshot,resolveReasoningForModel}from"./chunk-OHOG4HSN.js";import{tokenLimit}from"./chunk-EV2CXPMN.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("WORKSPACE_PROVIDERS_STATUS");function createWorkspaceProvidersStatusProvider(options={}){return async(workspaceCwd,acpChannelLive)=>buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options)}__name(createWorkspaceProvidersStatusProvider,"createWorkspaceProvidersStatusProvider");function buildWorkspaceProvidersStatus(workspaceCwd,acpChannelLive,options){try{const loaded=loadSettings(workspaceCwd,options.env?{skipLoadEnvironment:true,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted}:{consumeCorruptionEnvVars:true,skipLoadEnvironment:options.workspaceTrusted===false,skipWorkspaceSettings:options.workspaceTrusted===false,workspaceTrusted:options.workspaceTrusted});const settings=loaded.merged;const env=options.env??snapshotProcessEnv();const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);const argv={model:options.argv?.model,openaiApiKey:options.argv?.openaiApiKey,openaiBaseUrl:options.argv?.openaiBaseUrl,openaiLogging:options.argv?.openaiLogging,openaiLoggingDir:options.argv?.openaiLoggingDir};const resolvedCliConfig=resolveCliGenerationConfig({argv,settings,selectedAuthType,env});const modelsConfig=new ModelsConfig({initialAuthType:resolvedCliConfig.authType,modelProvidersConfig:settings.modelProviders,providerProtocolConfig:settings.providerProtocol,generationConfig:resolvedCliConfig.generationConfig,generationConfigSources:resolvedCliConfig.sources});const currentAuth=resolvedCliConfig.authType;let currentModelId=(resolvedCliConfig.model||modelsConfig.getModel()||"").trim();const requestedModelId=currentModelId;if(currentAuth&&!modelsConfig.getResolvedModel(currentAuth,currentModelId)){modelsConfig.syncAfterAuthRefresh(currentAuth,currentModelId);currentModelId=(modelsConfig.getModel()||"").trim()}const usedFallback=currentModelId!==requestedModelId;const hasCurrentModel=currentModelId.length>0;const modelCameFromSettings=!argv.model&&settings.model?.name?.trim()===currentModelId;const currentBaseUrl=usedFallback?modelsConfig.getGenerationConfig().baseUrl:modelCameFromSettings&&settings.model?.baseUrl!==void 0?settings.model.baseUrl||void 0:resolvedCliConfig.sources["baseUrl"]?resolvedCliConfig.baseUrl||void 0:void 0;const currentRegistryBaseUrl=usedFallback?modelsConfig.getCurrentRegistryBaseUrl():modelCameFromSettings&&currentAuth?settings.model?.baseUrl!==void 0?settings.model.baseUrl||null:modelsConfig.getResolvedModel(currentAuth,currentModelId)?.registryBaseUrl??null:void 0;const models=modelsConfig.getAllConfiguredModels();const modelOptions=buildAcpModelOptions(models);const reasoningSnapshot=captureReasoningSnapshot(models);const currentAcpModelId=hasCurrentModel?getCurrentAcpModelId(modelOptions,currentModelId,currentAuth,currentRegistryBaseUrl):void 0;const fastModelId=typeof settings.fastModel==="string"&&settings.fastModel.length>0?settings.fastModel:void 0;const visionModelId=typeof settings.visionModel==="string"&&settings.visionModel.length>0?settings.visionModel:void 0;const approvalMode=resolveApprovalMode(settings);const providers=new Map;for(const option of modelOptions){const{model,effectiveModelId,modelId}=option;if(model.isRuntimeModel)continue;const authType=String(model.authType);let provider=providers.get(authType);if(!provider){provider={kind:"model_provider",status:"ok",authType,current:false,models:[]};providers.set(authType,provider)}const isCurrent=currentAuth===model.authType&&currentAcpModelId===modelId;const resolved=modelsConfig.getResolvedModel(model.authType,model.id,model.registryBaseUrl);const generation={...resolved?.generationConfig,model:model.id,authType:model.authType,baseUrl:resolved?.baseUrl,reasoningSnapshot,reasoningRouteBaseUrl:model.registryBaseUrl??null};const configOptions=buildModelReasoningRoutePreview(generation,resolveReasoningForModel(void 0,generation),settings.model?.reasoningEffort,modelId.startsWith(ACP_ROUTE_ID_PREFIX));const configurationKey=getModelConfigurationKey(loaded,authType,model.id,model.registryBaseUrl);const providerModel={...configurationKey?{configurationKey}:{},modelId,baseModelId:parseAcpBaseModelId(effectiveModelId),name:model.label,...model.description!==void 0?{description:model.description}:{},contextLimit:model.contextWindowSize!==void 0&&model.contextWindowSize>0?model.contextWindowSize:tokenLimit(effectiveModelId),...model.modalities!==void 0?{modalities:model.modalities}:{},...model.baseUrl!==void 0?{baseUrl:sanitizeProviderBaseUrl(model.baseUrl)}:{},...model.envKey!==void 0?{envKey:model.envKey}:{},isCurrent,isRuntime:false,...configOptions?{configOptions}:{}};provider.models.push(providerModel);if(isCurrent)provider.current=true}const current=buildCurrent(currentAuth,currentAcpModelId,currentBaseUrl,fastModelId,visionModelId);return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:true,acpChannelLive,...current?{current}:{},approvalMode,providers:[...providers.values()],...resolvedCliConfig.warnings.length>0?{errors:resolvedCliConfig.warnings.map(warning=>({kind:"providers",status:"warning",error:sanitizeProviderWarning(warning)}))}:{}}}catch(error){return{v:STATUS_SCHEMA_VERSION,workspaceCwd,initialized:false,acpChannelLive,providers:[],errors:[{kind:"providers",status:"error",error:sanitizeProviderWarning(error instanceof Error?error.message:String(error))}]}}}__name(buildWorkspaceProvidersStatus,"buildWorkspaceProvidersStatus");function resolveApprovalMode(settings){const value=settings.tools?.approvalMode;if(typeof value!=="string")return"auto";const normalized=value.trim().toLowerCase().replaceAll("_","-");const mode=normalized==="autoedit"?"auto-edit":normalized;if(APPROVAL_MODES.includes(mode)){return mode}if(value.trim().length>0){debugLogger.warn(`[workspace-providers-status] unrecognized approvalMode "${value}", falling back to auto`)}return"auto"}__name(resolveApprovalMode,"resolveApprovalMode");var URL_LIKE_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\/[^\s'"`<>]+/g;var URL_START_PATTERN=/\b[A-Za-z][A-Za-z\d+.-]*:\/\//g;function sanitizeProviderWarning(warning){let result="";let index=0;let next=findNextUrlStart(warning,index);while(next){result+=warning.slice(index,next.index);const segmentEnd=findUrlSegmentEnd(warning,next.index,next.marker);const segment=warning.slice(next.index,segmentEnd);result+=sanitizeProviderWarningSegment(segment,next.marker.length);index=segmentEnd;next=findNextUrlStart(warning,index)}return result+warning.slice(index)}__name(sanitizeProviderWarning,"sanitizeProviderWarning");function findNextUrlStart(value,from){URL_START_PATTERN.lastIndex=from;const match=URL_START_PATTERN.exec(value);return match?{index:match.index,marker:match[0]}:void 0}__name(findNextUrlStart,"findNextUrlStart");function findUrlSegmentEnd(value,start,marker){const afterMarker=start+marker.length;const carriageReturn=value.indexOf("\r",afterMarker);const lineFeed=value.indexOf("\n",afterMarker);let lineEnd=value.length;if(carriageReturn!==-1)lineEnd=Math.min(lineEnd,carriageReturn);if(lineFeed!==-1)lineEnd=Math.min(lineEnd,lineFeed);const nextUrl=findNextUrlStart(value,afterMarker);return Math.min(lineEnd,nextUrl?.index??value.length)}__name(findUrlSegmentEnd,"findUrlSegmentEnd");function sanitizeProviderWarningSegment(segment,markerLength){const at=segment.indexOf("@",markerLength);if(at!==-1&&hasCredentialPrefix(segment,markerLength,at)&&segment[at+1]!==void 0&&/[A-Za-z0-9.[\]-]/.test(segment[at+1])){return`${segment.slice(0,markerLength)}${segment.slice(at+1)}`}return segment.replace(URL_LIKE_PATTERN,url=>sanitizeProviderBaseUrl(url))}__name(sanitizeProviderWarningSegment,"sanitizeProviderWarningSegment");function hasCredentialPrefix(segment,markerLength,at){const colon=segment.indexOf(":",markerLength);if(colon===-1||colon>at)return false;const username=segment.slice(markerLength,colon);return!/[/?#\s'"`<>]/.test(username)}__name(hasCredentialPrefix,"hasCredentialPrefix");function buildCurrent(authType,modelId,baseUrl,fastModelId,visionModelId){if(!authType&&!modelId&&!baseUrl&&!fastModelId&&!visionModelId)return void 0;return{...authType?{authType:String(authType)}:{},...modelId?{modelId}:{},...baseUrl?{baseUrl:sanitizeProviderBaseUrl(baseUrl)}:{},...fastModelId?{fastModelId:publicAuxModelSelectorValue(fastModelId)}:{},...visionModelId?{visionModelId:publicAuxModelSelectorValue(visionModelId)}:{}}}__name(buildCurrent,"buildCurrent");export{createWorkspaceProvidersStatusProvider};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{SessionOrganizationService}from"./chunk-PFKTTUGS.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
3
+ import{SessionOrganizationService}from"./chunk-POMEWCFJ.js";import{writeStderrLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function createSessionOrganizationService(workspaceCwd){return new SessionOrganizationService(workspaceCwd,message=>{writeStderrLine(`qwen serve: session-org: ${message}`)})}__name(createSessionOrganizationService,"createSessionOrganizationService");export{createSessionOrganizationService};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{sanitizeFilenameComponent}from"./chunk-PFKTTUGS.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getProjectHash,isSubpath}from"./chunk-2ZK2FGZQ.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-POMEWCFJ.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{getProjectHash,isSubpath}from"./chunk-2ZK2FGZQ.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,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import{remarkParse,unified}from"./chunk-AZ3CKMCT.js";import{estimateTextTokens}from"./chunk-RP57XAJ2.js";import{ignoreBrokenPipe}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{homedir}from"node:os";import path2 from"node:path";import*as fs2 from"node:fs/promises";init_esbuild_shims();init_esbuild_shims();var MEMORY_IMPORT_BUDGET={maxCalls:32,maxReservedTokens:512e3,batchSections:8,sourceBytes:65536,contextBytes:32768,outputTokens:8192,promptBytes:32768};function packMemoryImportSections(sections){const groups=new Map;for(const section of[...sections].sort((a,b)=>a.id.localeCompare(b.id))){const key=`${section.scope??""}:${section.groupId}`;const group=groups.get(key)??[];group.push(section);groups.set(key,group)}const batches=[];for(const group of groups.values()){let batch=[];let bytes=0;for(const section of group){const size=Buffer.byteLength(section.content);if(batch.length&&(batch.length===MEMORY_IMPORT_BUDGET.batchSections||bytes+size>MEMORY_IMPORT_BUDGET.sourceBytes)){batches.push(batch);batch=[];bytes=0}batch.push(section);bytes+=size}if(batch.length)batches.push(batch)}return batches}__name(packMemoryImportSections,"packMemoryImportSections");function estimateMemoryImport(sections){const batches=packMemoryImportSections(sections);const modelCalls=batches.length*2;const sourceTokens=sections.reduce((n,section)=>n+estimateTextTokens(section.content),0);const sourceBytes=Buffer.byteLength(JSON.stringify(sections.map(({id,content})=>({id,content}))));const reservedTokens=modelCalls*(MEMORY_IMPORT_BUDGET.contextBytes+MEMORY_IMPORT_BUDGET.promptBytes+MEMORY_IMPORT_BUDGET.outputTokens+1024)+sourceBytes+modelCalls;return{basis:"source-only-with-context-reserve",modelCalls,sourceTokens,maxOutputTokens:modelCalls*MEMORY_IMPORT_BUDGET.outputTokens,reservedTokens,exceedsBudget:modelCalls>MEMORY_IMPORT_BUDGET.maxCalls||reservedTokens>MEMORY_IMPORT_BUDGET.maxReservedTokens,limits:MEMORY_IMPORT_BUDGET}}__name(estimateMemoryImport,"estimateMemoryImport");import{createHash}from"node:crypto";import*as fs from"node:fs/promises";import path from"node:path";import{constants}from"node:fs";var MemoryImportRequestError=class extends Error{static{__name(this,"MemoryImportRequestError")}};var IMPORT_LIMITS={files:256,fileBytes:512*1024,totalBytes:8*1024*1024,sectionBytes:64*1024,headings:4096,markdownLines:16384,inlineMarkers:4096};function digest(value){return createHash("sha256").update(value).digest("hex")}__name(digest,"digest");function record(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(record,"record");function validSourcePath(value){return value.length<=512&&!/[\\\p{Cc}]/u.test(value)&&!value.startsWith("/")&&!/^[a-z]:/i.test(value)&&value.split("/").every(part=>part!==""&&part!=="."&&part!=="..")&&(/^(?:MEMORY|memory_summary)\.md$/.test(value)||/^rollout_summaries\/[\w.-]+\.md$/.test(value))}__name(validSourcePath,"validSourcePath");function validateSource(value){if(!record(value)||value["version"]!==1||value["source"]!=="codex"||!Array.isArray(value["files"])||value["files"].length===0||value["files"].length>IMPORT_LIMITS.files)throw new MemoryImportRequestError("Invalid version 1 Codex source set.");let bytes=0;const seen=new Set;const files=value["files"].map(file=>{if(!record(file)||typeof file["path"]!=="string"||!validSourcePath(file["path"])||typeof file["content"]!=="string"||file["content"].includes("\0"))throw new MemoryImportRequestError("Invalid Codex Markdown resource. Only memory Markdown and rollout_summaries/*.md are accepted.");const size=Buffer.byteLength(file["content"]);bytes+=size;if(size>IMPORT_LIMITS.fileBytes||bytes>IMPORT_LIMITS.totalBytes||seen.has(file["path"].toLowerCase()))throw new MemoryImportRequestError("Source exceeds limits or contains duplicate paths.");seen.add(file["path"].toLowerCase());return{path:file["path"],content:file["content"]}});if(!files.some(file=>file.path==="MEMORY.md"||file.path==="memory_summary.md"))throw new MemoryImportRequestError("Select the Codex memories folder containing MEMORY.md or memory_summary.md.");return{version:1,source:"codex",files:files.sort((a,b)=>a.path.localeCompare(b.path))}}__name(validateSource,"validateSource");var parser=unified().use(remarkParse);function headingTitle(raw){const atx=raw.match(/^ {0,3}#{1,6}(?:[\t ]+|$)/);if(atx)return raw.slice(atx[0].length).replace(/[\t ]+#+[\t ]*$/,"").trim();return raw.split(/\r\n|[\r\n]/).slice(0,-1).join(" ").trim()}__name(headingTitle,"headingTitle");function scopeFor(content,title,summary){const scopes=[];for(const match of content.matchAll(/(?:^|[\s;(])cwd\s*[=:]\s*(?:`([^`\n]+)`|([^\r\n,;()\s]+))/gim)){if(match[1]!==void 0){scopes.push({value:match[1].trim(),quoted:true,prose:false});continue}const trailing=content.slice(match.index+match[0].length).split(/\r\n|[\r\n]/,1)[0].trim();scopes.push({value:match[2].trim(),quoted:false,prose:/[^\s,;()]/.test(trailing)})}const heading=title.trim();if(/^(?:\/|[A-Za-z]:[\\/])/.test(heading))scopes.push({value:heading.replace(/^`|`$/g,""),quoted:false,prose:false});const strip=__name(value=>value.replace(/[\\/]+$/,"").replace(/[.:!?'"]+$/,""),"strip");const unique=[...new Set(scopes.map(scope=>strip(scope.value)))];if(unique.length===1&&/^(?:\/|[A-Za-z]:[\\/])/.test(unique[0])&&scopes.every(scope=>!scope.prose&&!/[*?{}[\]\p{Cc}]|\bcwd\s*[=:]/u.test(scope.value)&&(scope.quoted||!/\s/.test(scope.value))))return{suggestedScope:"project",sourceProject:unique[0],reason:"Source project hint; explicit target mapping is required."};if(scopes.length)return{suggestedScope:"unassigned",reason:"Ambiguous or unsupported project scope; assign explicitly."};if(summary&&/^(?:user profile|user preferences)$/i.test(title))return{suggestedScope:"user",reason:"Explicit user-level summary section."};return{suggestedScope:"unassigned",reason:"No reliable project scope; assign explicitly."}}__name(scopeFor,"scopeFor");function previewSource(input){const source=validateSource(input);const sections=[];const warnings=[];let headingCount=0;let lineCount=0;let markerCount=0;let expandedBytes=0;const paths=new Set(source.files.map(file=>file.path));const referenced=new Set;for(const file of source.files.filter(f=>!f.path.startsWith("rollout_summaries/"))){for(const match of file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g))referenced.add(match[0])}for(const ref of referenced)if(!paths.has(ref))warnings.push(`Missing referenced Markdown: ${ref}`);for(const file of source.files){if(file.path.startsWith("rollout_summaries/")&&!referenced.has(file.path)){warnings.push(`Unreferenced supporting resource excluded: ${file.path}`);continue}const atxCandidates=file.content.match(/^ {0,3}#{1,6}(?:[\t ]|$)/gm)?.length??0;if(headingCount+atxCandidates>4*IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");for(let i=0;i<file.content.length;i++){const char=file.content[i];if(char==="\n"||char==="\r"&&file.content[i+1]!=="\n")lineCount++;if("*_~[]<>!`&\\".includes(char))markerCount++;if(lineCount>IMPORT_LIMITS.markdownLines||markerCount>IMPORT_LIMITS.inlineMarkers)throw new MemoryImportRequestError("Source exceeds the Markdown complexity limit; split it into smaller source sets before importing.")}const tree=parser.parse(file.content);const headings=tree.children.filter(node=>node.type==="heading").map((node,index,nodes)=>({offset:node.position.start.offset,line:node.position.start.line,depth:node.depth,title:headingTitle(file.content.slice(node.position.start.offset,node.position.end.offset)),preface:file.content.slice(node.position.start.offset,nodes[index+1]?.position.start.offset).trim()}));headingCount+=headings.length;if(headingCount>IMPORT_LIMITS.headings)throw new MemoryImportRequestError("Source exceeds the supported heading limit.");const scopedDepths=headings.filter(heading=>/^(?:`?\/|`?[A-Za-z]:[\\/])/.test(heading.title)||/\bcwd\s*[=:]/i.test(heading.preface)).map(heading=>heading.depth);const minDepth=headings.length?Math.min(...headings.map(h=>h.depth)):1;const depth=Math.max(file.path==="memory_summary.md"?2:minDepth,...scopedDepths);const boundaries=headings.filter(heading=>heading.depth<=depth);if(!boundaries.length||boundaries[0].offset>0)boundaries.unshift({offset:0,line:1,title:file.path,depth:0,preface:""});for(let i=0;i<boundaries.length;i++){const boundary=boundaries[i];const own=file.content.slice(boundary.offset,boundaries[i+1]?.offset).trim();if(!own||/^v\d+$/.test(own)||own.split(/\r\n|[\r\n]/).every(line=>!line.trim()||/^#{1,6}\s/.test(line)))continue;const ancestors=[];for(const heading of headings){if(heading.offset>=boundary.offset)break;while(ancestors.length&&ancestors.at(-1).depth>=heading.depth)ancestors.pop();ancestors.push(heading)}while(ancestors.length&&ancestors.at(-1).depth>=boundary.depth)ancestors.pop();const parts=[...ancestors.map(heading=>heading.preface),own];expandedBytes+=parts.reduce((bytes,part)=>bytes+Buffer.byteLength(part),0)+2*(parts.length-1);if(expandedBytes>IMPORT_LIMITS.totalBytes)throw new MemoryImportRequestError("Source expanded context exceeds 8 MiB; split shared context and project groups before importing.");const content=parts.join("\n\n");let scope=scopeFor(content,boundary.title,file.path==="memory_summary.md");if(scope.suggestedScope==="unassigned"&&!/\bcwd\s*[=:]/i.test(content)){const parent=ancestors.at(-1);if(parent)scope=scopeFor(content,parent.title,file.path==="memory_summary.md")}const references=[...new Set(Array.from(content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0]))];const selectable=Buffer.byteLength(content)<=IMPORT_LIMITS.sectionBytes;if(!selectable)warnings.push(`${file.path}:${boundary.line}: section exceeds ${IMPORT_LIMITS.sectionBytes} bytes; split it before import.`);const id=digest(`${file.path}\0${content}`);if(sections.some(section=>section.id===id))continue;sections.push({id,groupId:digest(`${scope.suggestedScope}\0${scope.sourceProject??""}`),title:boundary.title,path:file.path,line:boundary.line,content,references,...scope,selectable})}}const groups=new Map;for(const section of sections){const group=groups.get(section.groupId)??{id:section.groupId,scope:section.suggestedScope,sourceProject:section.sourceProject,sectionIds:[]};group.sectionIds.push(section.id);groups.set(group.id,group)}return{version:1,kind:"preview",digest:digest(JSON.stringify(source)),groups:[...groups.values()].map(group=>({...group,estimate:estimateMemoryImport(sections.filter(section=>section.selectable&&section.groupId===group.id))})),sections,warnings,estimate:estimateMemoryImport(sections.filter(section=>section.selectable))}}__name(previewSource,"previewSource");async function readLocalSource(directory){const root=await fs.realpath(directory);const files=[];const read=__name(async relative=>{const file=path.join(root,relative);const info=await fs.lstat(file);if(!info.isFile()||info.isSymbolicLink()||info.size>IMPORT_LIMITS.fileBytes)throw new Error("Source must contain regular bounded Markdown files.");const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));try{const opened=await handle.stat();if(!opened.isFile()||opened.size>IMPORT_LIMITS.fileBytes)throw new Error("Source changed while opening.");const buffer=Buffer.alloc(IMPORT_LIMITS.fileBytes+1);let length=0;while(length<buffer.length){const read2=await handle.read(buffer,length,buffer.length-length,null);if(!read2.bytesRead)break;length+=read2.bytesRead}if(length>IMPORT_LIMITS.fileBytes||files.reduce((sum,entry)=>sum+Buffer.byteLength(entry.content),length)>IMPORT_LIMITS.totalBytes)throw new Error("Source exceeds byte limits.");files.push({path:relative,content:buffer.subarray(0,length).toString("utf8")})}finally{await handle.close()}},"read");for(const name of["MEMORY.md","memory_summary.md"]){try{await read(name)}catch(error){if(error.code!=="ENOENT")throw error}}const refs=new Set(files.flatMap(file=>Array.from(file.content.matchAll(/rollout_summaries\/[\w.-]+\.md/g),m=>m[0])));if(refs.size+files.length>IMPORT_LIMITS.files)throw new Error("Too many referenced source files.");if(refs.size){const dir=await fs.lstat(path.join(root,"rollout_summaries")).catch(error=>{if(error.code==="ENOENT")return void 0;throw error});if(dir&&(!dir.isDirectory()||dir.isSymbolicLink()))throw new Error("Supporting resource directory must not be a symlink.");if(dir)for(const ref of refs){try{await read(ref)}catch(error){if(error.code!=="ENOENT")throw error}}}return validateSource({version:1,source:"codex",files})}__name(readLocalSource,"readLocalSource");var writeStdoutLineFlushed=__name(message=>new Promise((resolve,reject)=>process.stdout.write(message.endsWith("\n")?message:`${message}
4
- `,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-ZRC4XZCJ.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
4
+ `,error=>error&&error.code!=="EPIPE"?reject(error):resolve())),"writeStdoutLineFlushed");var memoryCommand={command:"memory",describe:"Preview and import external memories",builder:__name(argv=>argv.command({command:"import codex",describe:"Preview Codex memory; explicitly confirm selected sections to consolidate",builder:__name(args=>args.positional("codex",{type:"string",describe:"External memory source",choices:["codex"]}).option("source",{type:"string",describe:"Codex memories directory"}).option("dry-run",{type:"boolean",default:false,describe:"Offline preview; no model or memory writes"}).option("json",{type:"boolean",default:false}).option("apply",{type:"boolean",default:false,describe:"Authorize model consolidation of an explicit selection"}).option("selection",{type:"string",describe:"JSON array of {id, scope: project|user}"}).option("idempotency-key",{type:"string",describe:"Stable caller key for this selection"}).option("retry",{type:"boolean",default:false,describe:"Retry unfinished items of this submitted batch"}).strict(),"builder"),handler:__name(async args=>{ignoreBrokenPipe();if(args["apply"]&&args["dry-run"])throw new Error("--apply and --dry-run cannot be combined.");if(args["apply"]&&(args["bare"]||args["safeMode"]||args["safe-mode"]))throw new Error("Confirmed memory import is unavailable in bare or safe mode. Offline preview remains available.");if(args["source"]!==void 0&&typeof args["source"]!=="string")throw new Error("Provide a single --source directory.");const directory=typeof args["source"]==="string"?args["source"]:path2.join(process.env["CODEX_HOME"]?.trim()||path2.join(homedir(),".codex"),"memories");const source=await readLocalSource(directory);const preview=previewSource(source);if(!args["apply"]){if(args["json"])await writeStdoutLineFlushed(JSON.stringify(preview));else{const lines=[`Preview only: ${preview.sections.length} source sections. No memory was written.`,...preview.groups.map(group=>`[${group.sectionIds.length} sections] ${group.scope}: ${JSON.stringify(group.sourceProject??"No project hint")}`),`Estimated usage (all selectable sections): ${preview.estimate.modelCalls} model calls, ${preview.estimate.sourceTokens} source tokens, up to ${preview.estimate.maxOutputTokens} output tokens; ${preview.estimate.reservedTokens} reserved token units including context.`,`Task limits: ${preview.estimate.limits.maxCalls} calls / ${preview.estimate.limits.maxReservedTokens} reserved token units. Estimates are not billing quotes; explicit selection and existing context affect usage.`];if(preview.estimate.exceedsBudget)lines.push("Warning: the full selection may exceed the task budget; select fewer sections before confirming.");for(const warning of preview.warnings)lines.push(`Warning: ${JSON.stringify(warning)}`);lines.push("Use --json for section IDs, details and source text. To import, provide --apply --selection <JSON file> --idempotency-key <key>. Unassigned sections require an explicit scope.");await writeStdoutLineFlushed(lines.join("\n"))}return}if(typeof args["selection"]!=="string"||typeof args["idempotency-key"]!=="string")throw new Error("--apply requires --selection and --idempotency-key.");const stat=await fs2.lstat(args["selection"]);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>512*1024)throw new Error("Selection must be a bounded regular JSON file.");const selection=JSON.parse(await fs2.readFile(args["selection"],"utf8"));const{createLocalMemoryImportService}=await import("./local-7PEOBJKE.js");const service=await createLocalMemoryImportService();let task=await service.submit(source,selection,args["idempotency-key"]);if(args["retry"])task=await service.retry(task.id);task=await service.idle(task.id);await writeStdoutLineFlushed(JSON.stringify(task));if(task.status!=="completed"||task.items.some(item=>item.status==="conflict"))process.exitCode=1},"handler")}).demandCommand(1).version(false),"builder"),handler:__name(()=>{},"handler")};export{MEMORY_IMPORT_BUDGET,packMemoryImportSections,MemoryImportRequestError,digest,previewSource,memoryCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{BaseJsonOutputAdapter}from"./chunk-JRPR5IME.js";import{observeHeadlessJsonToolResultWire}from"./chunk-SOCXRMZM.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
3
+ import{BaseJsonOutputAdapter}from"./chunk-NYGJ53Y7.js";import{observeHeadlessJsonToolResultWire}from"./chunk-G7D42XGP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
4
4
  `)}else{process.stdout.write(`${resultMessage.result}
5
5
  `)}}else{const json=JSON.stringify(this.messages);const frame=`${json}
6
6
  `;observeHeadlessJsonToolResultWire(this.messages,frame);process.stdout.write(frame)}}emitMessage(message){this.messages.push(message)}};export{JsonOutputAdapter};