stim 1.37.0 → 1.39.0

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 (183) hide show
  1. package/README.md +7 -1
  2. package/dist/{acquire-artifact-zBUbPuDP.mjs → acquire-artifact-CGg_PlrE.mjs} +2 -2
  3. package/dist/{act-BGAFjY8f.mjs → act-D3hoIhTS.mjs} +968 -902
  4. package/dist/{activity-CdpXXSq2.mjs → activity-BDovGcCm.mjs} +24 -15
  5. package/dist/{agent-device-usage-output-D0582GHy.mjs → agent-device-usage-output-DfFvKC1C.mjs} +5 -5
  6. package/dist/{android-BPBARZMR.mjs → android-BRZYe-0X.mjs} +2 -2
  7. package/dist/{android-CaSsewbu.mjs → android-BTUwxD7X.mjs} +5 -5
  8. package/dist/{android-CGctfYpv.mjs → android-BX5TxF9a.mjs} +8 -8
  9. package/dist/{android-BBwLpxRh.mjs → android-CbGLpUZP.mjs} +95 -48
  10. package/dist/{android-cas-p8gna03x.mjs → android-cas-U4xqUmC0.mjs} +4 -4
  11. package/dist/android-cas-compiler.mjs +1 -1
  12. package/dist/{android-image-DY8KxK2m.mjs → android-image-CTn2h8M-.mjs} +3 -3
  13. package/dist/api.d.mts +100 -10
  14. package/dist/api.mjs +77 -31
  15. package/dist/{apk-signed-tail-BMv-KLcB.mjs → apk-signed-tail-Dwv-JtaG.mjs} +2 -2
  16. package/dist/{artifact-BsimBWxG.mjs → artifact-C8f8ZY6L.mjs} +29 -15
  17. package/dist/{artifact-BrNZTZtA.mjs → artifact-NYyD2Lmq.mjs} +18 -15
  18. package/dist/{artifact-platform-BaGL1i1X.mjs → artifact-platform-BBnu-ucF.mjs} +1 -1
  19. package/dist/{auto-placement-CFKNrWLU.mjs → auto-placement-BcgRfZT4.mjs} +15 -15
  20. package/dist/{browser-web-YFsgCP_a.mjs → browser-web-CJ-zLUhz.mjs} +16 -16
  21. package/dist/{build-DIhuoozz.mjs → build-C56Km3op.mjs} +25 -25
  22. package/dist/{build-cache-Dt-dhCJF.mjs → build-cache-CUe701Cr.mjs} +10 -7
  23. package/dist/{build-plan-CgnLDof9.mjs → build-plan-CRpFO-jP.mjs} +23 -10
  24. package/dist/{cache-manifest-BO0TIcPV.mjs → cache-manifest-BiqA7_oo.mjs} +1 -1
  25. package/dist/cache-manifest.mjs +1 -1
  26. package/dist/{cdp-CgT47_9A.mjs → cdp-BXgx9dPA.mjs} +1 -1
  27. package/dist/{chrome-DL5znvmo.mjs → chrome-Dy-5EmLz.mjs} +1 -1
  28. package/dist/{cli-BGUrlSH3.mjs → cli-In9Zwz0d.mjs} +23 -21
  29. package/dist/cli.mjs +1 -1
  30. package/dist/{client-DU6dnGX1.mjs → client-D_asq_FB.mjs} +18 -15
  31. package/dist/collector-run.d.mts +1 -1
  32. package/dist/collector-run.mjs +7 -7
  33. package/dist/{command-output-ByEmIwur.mjs → command-output-BuFLY9AY.mjs} +1 -1
  34. package/dist/{config-CNmN-ndb.mjs → config-CfWFLi9u.mjs} +3 -3
  35. package/dist/{dependencies-BozoTBqa.mjs → dependencies-CUHi9Z4i.mjs} +90 -47
  36. package/dist/{dependency-state-BQeC4FVn.mjs → dependency-state-DpWvD-VN.mjs} +2 -2
  37. package/dist/{detached-entry-VqFeEE9W.mjs → detached-entry-D0lqSzjf.mjs} +1 -1
  38. package/dist/{dev-client-3SQzMRXZ.mjs → dev-client-fre-u_oX.mjs} +2 -2
  39. package/dist/device-DYk9z-ze.mjs +309 -0
  40. package/dist/device-host-worker.mjs +120 -33
  41. package/dist/{device-pool-B8IqZKqm.mjs → device-pool-D2H3diJh.mjs} +3 -3
  42. package/dist/{device-provision-DWAoSKEw.mjs → device-provision-COwAiJZZ.mjs} +10 -11
  43. package/dist/{device-DGMvzoZZ.mjs → device-tools-Ds0fLZGN.mjs} +20 -321
  44. package/dist/doctor-D21_QLuF.mjs +2 -0
  45. package/dist/{doctor-CPzwqcXY.mjs → doctor-Duz45ro_.mjs} +119 -87
  46. package/dist/{doctor-fingerprint-Bo4z8YNP.mjs → doctor-fingerprint-9-le4Akk.mjs} +1 -1
  47. package/dist/doctor-fingerprint.mjs +1 -1
  48. package/dist/{doctor-Bknt0121.mjs → doctor-kBsu7nNx.mjs} +110 -71
  49. package/dist/{doctor-watchman-CPE4C8KV.mjs → doctor-watchman-CNozKfMG.mjs} +5 -5
  50. package/dist/{eas-build-CwOXKJwa.mjs → eas-build-CZSHVvbv.mjs} +4 -4
  51. package/dist/{eas-fallback-Cnb12a50.mjs → eas-fallback-CNrGzikn.mjs} +6 -6
  52. package/dist/{eas-session-ledger-TE1miVz5.mjs → eas-session-ledger-BLtovvdF.mjs} +6 -6
  53. package/dist/error-diagnostics-CmTt8bKn.mjs +254 -0
  54. package/dist/{exec-L37dbiIb.mjs → exec-CXyR277b.mjs} +40 -18
  55. package/dist/{gc-0jdcnDHs.mjs → gc-CtLMX9Sr.mjs} +121 -47
  56. package/dist/{gc-1ZLq1djg.mjs → gc-DAZqCIr1.mjs} +2 -2
  57. package/dist/{guide-COxIANZu.mjs → guide-DKQ1_77g.mjs} +646 -124
  58. package/dist/{hosted-android-D8JbIzgC.mjs → hosted-android-CjpyVlk-.mjs} +4 -4
  59. package/dist/{hosted-client-BLwuXEZS.mjs → hosted-client-DF0CnyIF.mjs} +4 -4
  60. package/dist/{hosted-logs-BWEQNJx_.mjs → hosted-logs-Q4BtVst3.mjs} +18 -11
  61. package/dist/{hosted-logs-sync-uWSrH2mf.mjs → hosted-logs-sync-UoKTU0HH.mjs} +40 -5
  62. package/dist/{hosted-macos-BnCYAv1y.mjs → hosted-macos-_rQYseT5.mjs} +6 -6
  63. package/dist/{hosted-native-OBT2sJxn.mjs → hosted-native-DqIYS5nr.mjs} +11 -9
  64. package/dist/{idle-C4cZ757K.d.mts → idle-7vnUCtE1.d.mts} +1 -1
  65. package/dist/{ios-2Qr4_Zu2.mjs → ios-B38rVG9h.mjs} +1 -1
  66. package/dist/{ios-BveW7qK1.mjs → ios-BNJVbrgV.mjs} +195 -192
  67. package/dist/{ios-Bjz7aPLy.mjs → ios-BpZEKs9q.mjs} +8 -8
  68. package/dist/{ios-CGyx4PA7.mjs → ios-Deeq7TMb.mjs} +114 -40
  69. package/dist/{ios-CDvlmUs7.d.mts → ios-DgHoKId4.d.mts} +1 -1
  70. package/dist/{ios-device-ByrDWSpC.mjs → ios-device-C_OMN1Lc.mjs} +3 -3
  71. package/dist/{ios-device-ygijU78G.mjs → ios-device-DMdoV2wv.mjs} +1 -1
  72. package/dist/{ios-project-XHg87vyQ.mjs → ios-project-BPpZMSYe.mjs} +12 -9
  73. package/dist/ios-runtime-B56uptkf.mjs +150 -0
  74. package/dist/{ios-signing-CRYQ1W42.mjs → ios-signing-CUZcCxtM.mjs} +3 -3
  75. package/dist/{ios-state-enWc5P6U.mjs → ios-state-Cc4x-VYz.mjs} +1 -1
  76. package/dist/{js-swap-C6vl3vEd.mjs → js-swap-C9i9nhO_.mjs} +7 -7
  77. package/dist/{launch-f3RnbFW5.mjs → launch-yyvPe5DD.mjs} +36 -23
  78. package/dist/{lightened-Cdfmo8MO.mjs → lightened-DaZUxClW.mjs} +5 -5
  79. package/dist/local-server-DIpoG1HX.mjs +207 -0
  80. package/dist/{logs-x3em2-oI.mjs → logs-BCFE6LPk.mjs} +7 -7
  81. package/dist/{logs-DAjxBF3c.mjs → logs-shtGdLSC.mjs} +6 -6
  82. package/dist/{macos-D_LAseN9.mjs → macos-9tpo1TI6.mjs} +139 -56
  83. package/dist/{macos-ZfpWlzBO.mjs → macos-BBmn95eT.mjs} +1 -1
  84. package/dist/macos-run.mjs +1 -1
  85. package/dist/maintenance-run.mjs +7 -7
  86. package/dist/{metro-TIQ1Wft-.mjs → metro-Dxgq11ZB.mjs} +5 -5
  87. package/dist/{metro-request-DcUxyaq8.mjs → metro-request-3nuFGWyE.mjs} +2 -2
  88. package/dist/{device-BIg1iExg.mjs → metro-warmup-DScauES7.mjs} +2 -81
  89. package/dist/{prebuild-BKkj3OyL.mjs → miss-reason-Dczy053A.mjs} +12 -272
  90. package/dist/{named-ports-BfEMi9bK.mjs → named-ports-D7XJOGvY.mjs} +3 -3
  91. package/dist/{native-android-COOrNDk2.mjs → native-android-klhKyT3N.mjs} +20 -19
  92. package/dist/{error-diagnostics-CXTT3bYC.mjs → native-crash-CLuD5SAA.mjs} +40 -283
  93. package/dist/{native-gradle-artifact-inputs-B4Mwydmf.mjs → native-gradle-artifact-inputs-DdUxqT26.mjs} +5 -5
  94. package/dist/{native-runtime-UxUBU8up.mjs → native-runtime-BIi8emgc.mjs} +9 -8
  95. package/dist/{native-source-D2ZfiQ6U.mjs → native-source-Y7a1QSoA.mjs} +1 -1
  96. package/dist/{native-xcode-inputs-DUv7Q3ok.mjs → native-xcode-inputs-sHQc23cZ.mjs} +3 -3
  97. package/dist/{native-xcode-ios-DXcteLVi.mjs → native-xcode-ios-CZvpWpcV.mjs} +18 -18
  98. package/dist/{exec-DnYc4HGH.d.mts → ndjson-zCGEyd24.d.mts} +22 -22
  99. package/dist/offload-worker.d.mts +1 -3
  100. package/dist/offload-worker.mjs +70 -45
  101. package/dist/{operation-exec-DNynwpqO.mjs → operation-exec-Bu59H-c0.mjs} +1 -1
  102. package/dist/{ownership-CQTg6v1d.mjs → ownership-NTsUkOIx.mjs} +3 -3
  103. package/dist/{page-CoN9al_x.mjs → page-OL2fyLkh.mjs} +2 -2
  104. package/dist/{phone-reverses-CHtco460.mjs → phone-reverses-jzm0lpXQ.mjs} +4 -4
  105. package/dist/{placement-log-oQnELAvQ.mjs → placement-log-CSnM6Hjm.mjs} +1 -1
  106. package/dist/{plan-placement-45EOlIG1.mjs → plan-placement-C3m_SezD.mjs} +9 -8
  107. package/dist/{ports-DKO7EUNt.mjs → ports-CXRL-x5l.mjs} +3 -3
  108. package/dist/{android-project-v_1nej_x.d.mts → project-D9YREBT1.d.mts} +52 -52
  109. package/dist/{project-BCtQz48d.mjs → project-DJxUNnBc.mjs} +22 -17
  110. package/dist/{pull-request-m8cMZ3aE.mjs → pull-request-BeKvGb7a.mjs} +2 -2
  111. package/dist/pull-requests.mjs +1 -1
  112. package/dist/{react-native-android-MI4ktuhL.mjs → react-native-android-CAuQvQhE.mjs} +43 -32
  113. package/dist/{react-native-build-dixAL2G8.mjs → react-native-build-CvELkoFQ.mjs} +21 -12
  114. package/dist/{react-native-doctor-CvkWincj.mjs → react-native-doctor-C6ZPLBtx.mjs} +8 -8
  115. package/dist/{react-native-ios-DF5otoBR.mjs → react-native-ios-DHbUvTNT.mjs} +19 -17
  116. package/dist/{recorded-build-CGHGCO8m.mjs → recorded-build-DyTfMDkr.mjs} +5 -1
  117. package/dist/{recordings-BcOzqFD1.mjs → recordings-C6BxkNsM.mjs} +1 -1
  118. package/dist/{registration-C-3PDR3X.mjs → registration-DGbMX7Ej.mjs} +22 -4
  119. package/dist/{reload-DWxmO9dY.mjs → reload-CA7eQ17D.mjs} +1 -1
  120. package/dist/{reload-DGWfNFwQ.mjs → reload-Ce9SKnof.mjs} +21 -19
  121. package/dist/{remote-DWYGW2f5.mjs → remote-BPEqoTLZ.mjs} +4 -4
  122. package/dist/{remote-CV2jBcLv.mjs → remote-CJH2ePbE.mjs} +38 -13
  123. package/dist/{result-CWyxwPvZ.mjs → result-D6jqNdA9.mjs} +18 -18
  124. package/dist/revive-CB45a-jN.mjs +346 -0
  125. package/dist/{run-FZtMQgrx.mjs → run-iuE7G6Ns.mjs} +25 -11
  126. package/dist/{server-bare-Ksh1NKeI.mjs → server-bare-B7Ter9LA.mjs} +2 -2
  127. package/dist/{server-command-BO2DIsJV.mjs → server-command-DCAGX0yL.mjs} +6 -6
  128. package/dist/{server-expo-ZS9_WaNG.mjs → server-expo-BET43DqM.mjs} +10 -8
  129. package/dist/server-expo-Dofg6bae.mjs +2 -0
  130. package/dist/{settings-TYrzDh8T.mjs → settings-D9Pu0JqG.mjs} +2 -2
  131. package/dist/{settings-payload-CUM0DYwz.mjs → settings-payload-CsjV6gk4.mjs} +5 -5
  132. package/dist/{settings-write-D_9_IEx7.mjs → settings-write-CdZgOLiv.mjs} +6 -6
  133. package/dist/{settings-Ag4pbs0z.mjs → settings-y7EU0lpr.mjs} +61 -15
  134. package/dist/settings.schema.json +91 -13
  135. package/dist/share-BHa5PBJq.mjs +183 -0
  136. package/dist/{device-capacity-DWUOvY13.mjs → simslim-CAzgNod3.mjs} +533 -187
  137. package/dist/{slot-launch-DW_29Bmu.mjs → slot-launch-Cif3S7Nb.mjs} +6 -6
  138. package/dist/{settings-D9LtQaUw.mjs → spawn-entry-DU58VFpC.mjs} +18 -1
  139. package/dist/{stage-_8k8p7uq.mjs → stage-Br2YWv_w.mjs} +6 -5
  140. package/dist/{start-CzBB5R7N.mjs → start-BZtZz5yS.mjs} +23 -16
  141. package/dist/{start-CdgtOksb.mjs → start-CTJSips8.mjs} +1 -1
  142. package/dist/{state-DsrFh3yv.mjs → state-D4cIFPiO.mjs} +2 -2
  143. package/dist/{state-CfP-ccP8.mjs → state-DUvNCAJF.mjs} +4 -4
  144. package/dist/{stats-BgTyuzib.mjs → stats-63awt4_M.mjs} +8 -8
  145. package/dist/{stats-report-Ci6TAfFm.mjs → stats-report-hkzt3-fb.mjs} +1 -1
  146. package/dist/{status-Bcdy5eHt.mjs → status-B-xuQoYR.mjs} +56 -39
  147. package/dist/{status-C7Zzb-Eh.mjs → status-C_jsnqvr.mjs} +1 -1
  148. package/dist/{status-C2PdxK6q.mjs → status-Dy8WAp3T.mjs} +2 -2
  149. package/dist/{status-watch-DY0EZcmg.mjs → status-watch-BOjzQZa8.mjs} +5 -5
  150. package/dist/status-worker.mjs +1 -1
  151. package/dist/{stim-desktop-DWGAfaud.mjs → stim-desktop-DgMxYj3j.mjs} +2 -2
  152. package/dist/{stop-CbxsTKyZ.mjs → stop-CXlkz2jh.mjs} +6 -6
  153. package/dist/{stop-iGkvEvDn.mjs → stop-DWURexkh.mjs} +2 -2
  154. package/dist/{stop-CkmBkNyg.mjs → stop-McsnFLo6.mjs} +21 -17
  155. package/dist/supervisor-run.d.mts +16 -8
  156. package/dist/supervisor-run.mjs +35 -24
  157. package/dist/{support-JZ4KRW0C.mjs → support-BqLY845A.mjs} +7 -7
  158. package/dist/{support-CfYmOdQs.mjs → support-D9II3GVw.mjs} +762 -18
  159. package/dist/{swiftpm-artifact-inputs-C1rZDRDs.mjs → swiftpm-artifact-inputs-BLsgttAo.mjs} +4 -4
  160. package/dist/{swiftpm-macos-DRTjC7Ff.mjs → swiftpm-macos-B7qa1L61.mjs} +11 -11
  161. package/dist/toolchain-BTmMQV9o.mjs +2 -0
  162. package/dist/{toolchain-BeD7tbBW.mjs → toolchain-B_9WW_w8.mjs} +49 -19
  163. package/dist/trigger-B2IpxqIg.mjs +2 -0
  164. package/dist/{trigger-G_gbfIVB.mjs → trigger-BJDhQEga.mjs} +3 -4
  165. package/dist/{warm-progress-CJQ8tk5O.mjs → warm-progress-Bk5Fd4vG.mjs} +21 -16
  166. package/dist/web-BHOg40ES.mjs +2 -0
  167. package/dist/{web-BXbmysa1.mjs → web-OjUguG98.mjs} +9 -9
  168. package/dist/web-run.mjs +8 -8
  169. package/dist/windows-report.mjs +1 -1
  170. package/dist/{workspace-state-DOPXG2Gp.mjs → workspace-state-nQ8V5gik.mjs} +3 -3
  171. package/dist/{workspaces-DCzDzydB.mjs → workspaces-CNhDcHDY.mjs} +238 -60
  172. package/dist/{worktree-6ngObKkw.mjs → worktree-CVbcjNxX.mjs} +1 -1
  173. package/dist/{worktree-BAC43Kio.mjs → worktree-fMs9rxUO.mjs} +344 -47
  174. package/package.json +7 -7
  175. package/shim/expo-metro-config.cjs +19 -2
  176. package/dist/device-android-CBat355q.mjs +0 -650
  177. package/dist/doctor-CxgR5vPi.mjs +0 -2
  178. package/dist/server-expo-9hQwyLze.mjs +0 -2
  179. package/dist/simslim-BMgpTRWe.mjs +0 -166
  180. package/dist/spawn-entry-jw19m8Nl.mjs +0 -17
  181. package/dist/toolchain-CNlKc9pH.mjs +0 -2
  182. package/dist/trigger-Bp3lruF2.mjs +0 -2
  183. package/dist/web-BcaySU05.mjs +0 -2
@@ -1,27 +1,27 @@
1
- import { T as process_identity_exports, f as WorkspaceProcessCleanupError, m as workspaceProcessLockError, n as isTimeoutError, p as withWorkspaceProcessLock, t as getExecutor } from "./exec-L37dbiIb.mjs";
2
- import { E as workspaceDir, j as workspaceStateFile$1, k as workspaceLogsDir$1, r as readWorkspaceState$1, u as workspaceLastUsed, w as workspaceAgentDeviceDir } from "./workspace-state-DOPXG2Gp.mjs";
3
- import { o as formatLongDuration, u as plural } from "./command-output-ByEmIwur.mjs";
4
- import { ct as measuredDirectorySizeAsync, gt as projectDeviceSlots, it as formatBytes, m as getProject, ot as isOnMountedVolume, rt as directorySizeAsync, st as listMountedVolumes, v as loadConfig$1 } from "./config-CNmN-ndb.mjs";
5
- import { c as gitQuiet, l as gitQuietAsync, n as runOperationFileQuiet, r as childEnvironment } from "./operation-exec-DNynwpqO.mjs";
6
- import { At as listWorktrees, Et as hasUncommittedWorkAsync, Ft as matchWorktreeEntry, Kt as sourceCheckoutOf, O as maintenanceKeepSetting, Pt as lockReason, Ut as resolveFullRefAsync, Wt as resolveSourceCheckoutAsync, X as resolveProjectSettings, Xt as worktreeLockAsync, Z as resolveProjectSettingsAsync, bt as dirtyPathsAsync, h as deviceIdleShutdownMinutesSetting, it as settingValueAt, jt as listWorktreesAsync, mt as LOCKED_REASON, qt as unpushedCommitsAsync, sn as removeTemporaryEntryAsync, wt as hasPopulatedSubmodulesAsync } from "./settings-Ag4pbs0z.mjs";
7
- import { P as readRemoteSession, i as findProjectRoot$1 } from "./project-BCtQz48d.mjs";
8
- import { A as getAvdNameForSerialAsync, L as listAvds, N as listAdbDevices, P as listAdbDevicesAsync, R as listAvdsAsync, U as ownedAvdDirectory, k as getAvdNameForSerial, q as ownedAvdSerialResolverAsync, xt as readParked } from "./android-CGctfYpv.mjs";
9
- import { c as pidExists } from "./metro-TIQ1Wft-.mjs";
10
- import { At as deleteParkedAvds, B as stopOwnedMetro, Ct as waitForGradleExit, Et as DEVICE_LIST_TIMEOUT_MS, Ft as deviceSweepIsScoped, M as enforceBudget, Mt as deleteProjectDevices, Or as discoverCaches, Ot as collectParkedAvds, P as machineNumber, Q as levelFloors, R as resolveBudget, Tr as phase, Z as diskPressureLevel, _t as collectGradleVersions, b as shutDownIdleDevices, br as memorySweepIsScoped, et as lowestFree, ft as planCacheEmptying, hr as collectMemoryReport, j as cacheLabel, jt as deleteParkedSims, kr as pruneCache, kt as collectParkedSims, ot as emptyCaches, tt as protectWindowMs, vt as deleteGradleVersion, wr as stopIdleGradleDaemons, x as writeIdleShutdownEvent, y as dueIdleDevices, z as trimmableCaches, zt as findStaleProjectDevices } from "./device-capacity-DWUOvY13.mjs";
11
- import { o as readWebRecord, u as webFacts } from "./state-CfP-ccP8.mjs";
12
- import { a as unregister, n as readManifest } from "./cache-manifest-BO0TIcPV.mjs";
13
- import { B as workspaceBuildInProgress, Et as GC_OUTPUT, F as collectOwnedDeviceActivityAsync, Ot as takeGcResults, P as collectOwnedDeviceActivity, a as collectOrphanedWorkspaces, b as workspaceInUseAsync, c as isInsideWorkspaces, d as recentNativeUseReason, g as ARTIFACT_DIRS, h as workspaceDirRemoved, i as clearWorkspaceOutputs, jt as readConcurrency, kt as eachLimited, l as keptByLock, m as workspaceBuildReasons, o as collectWorkspaceOutputs, s as deleteOrphanedWorkspaces, t as LIGHTEN_AFTER_MS, u as listWorkspaceDirs, v as withIdleWorkspace, x as resolveSupervisorTarget, y as workspaceInUse } from "./workspaces-DCzDzydB.mjs";
1
+ import { E as process_identity_exports, h as workspaceProcessLockError, m as withWorkspaceProcessLock, n as isTimeoutError, p as WorkspaceProcessCleanupError, t as getExecutor } from "./exec-CXyR277b.mjs";
2
+ import { E as workspaceDir, j as workspaceStateFile$1, k as workspaceLogsDir$1, r as readWorkspaceState$1, u as workspaceLastUsed, w as workspaceAgentDeviceDir } from "./workspace-state-nQ8V5gik.mjs";
3
+ import { o as formatLongDuration, u as plural } from "./command-output-BuFLY9AY.mjs";
4
+ import { ct as measuredDirectorySizeAsync, gt as projectDeviceSlots, it as formatBytes, m as getProject, ot as isOnMountedVolume, rt as directorySizeAsync, st as listMountedVolumes, v as loadConfig$1 } from "./config-CfWFLi9u.mjs";
5
+ import { c as gitQuiet, l as gitQuietAsync, n as runOperationFileQuiet, r as childEnvironment } from "./operation-exec-Bu59H-c0.mjs";
6
+ import { Dt as hasUncommittedWorkAsync, Ft as lockReason, Gt as resolveSourceCheckoutAsync, It as matchWorktreeEntry, Jt as unpushedCommitsAsync, Mt as listWorktreesAsync, O as maintenanceKeepSetting, Tt as hasPopulatedSubmodulesAsync, Wt as resolveFullRefAsync, X as resolveProjectSettings, Z as resolveProjectSettingsAsync, Zt as worktreeLockAsync, bt as dirtyPathsAsync, cn as removeTemporaryEntryAsync, h as deviceIdleShutdownMinutesSetting, it as settingValueAt, jt as listWorktrees, mt as LOCKED_REASON, qt as sourceCheckoutOf } from "./settings-y7EU0lpr.mjs";
7
+ import { F as readRemoteSession, i as findProjectRoot$1 } from "./project-DJxUNnBc.mjs";
8
+ import { A as getAvdNameForSerialAsync, L as listAvds, N as listAdbDevices, P as listAdbDevicesAsync, R as listAvdsAsync, U as ownedAvdDirectory, k as getAvdNameForSerial, q as ownedAvdSerialResolverAsync, xt as readParked } from "./android-BX5TxF9a.mjs";
9
+ import { c as pidExists } from "./metro-Dxgq11ZB.mjs";
10
+ import { Ar as lowestFree, At as deleteProjectDevices, B as resolveBudget, C as writeIdleShutdownEvent, Dr as diskPressureLevel, Dt as collectParkedSims, Er as stopIdleGradleDaemons, Et as collectParkedAvds, H as stopOwnedMetro, I as machineNumber, Ir as discoverCaches, Lr as pruneCache, Mr as protectWindowMs, N as cacheLabel, Nr as phase, Or as levelFloors, Ot as deleteParkedAvds, P as enforceBudget, Pt as deviceSweepIsScoped, S as shutDownIdleDevices, Sr as memorySweepIsScoped, Tr as runningBuild, V as trimmableCaches, _r as collectMemoryReport, gt as deleteGradleVersion, ht as collectGradleVersions, kt as deleteParkedSims, rt as emptyCaches, ut as planCacheEmptying, wt as DEVICE_LIST_TIMEOUT_MS, x as dueIdleDevices, xt as waitForGradleExit, zt as findStaleProjectDevices } from "./simslim-CAzgNod3.mjs";
11
+ import { o as readWebRecord, u as webFacts } from "./state-DUvNCAJF.mjs";
12
+ import { a as unregister, n as readManifest } from "./cache-manifest-BiqA7_oo.mjs";
13
+ import { At as takeGcResults, Et as listBuildSlots, F as collectOwnedDeviceActivity, I as collectOwnedDeviceActivityAsync, Nt as readConcurrency, Ot as GC_OUTPUT, V as workspaceBuildInProgress, a as collectOrphanedWorkspaces, b as workspaceInUseAsync, c as isInsideWorkspaces, d as recentNativeUseReason, g as ARTIFACT_DIRS, h as workspaceDirRemoved, i as clearWorkspaceOutputs, jt as eachLimited, l as keptByLock, m as workspaceBuildReasons, o as collectWorkspaceOutputs, s as deleteOrphanedWorkspaces, t as LIGHTEN_AFTER_MS, u as listWorkspaceDirs, v as withIdleWorkspace, x as resolveSupervisorTarget, y as workspaceInUse } from "./workspaces-CNhDcHDY.mjs";
14
+ import { n as resolveMaintenanceSettings } from "./spawn-entry-DU58VFpC.mjs";
14
15
  import { t as canonicalPath } from "./paths-BsJMoPP2.mjs";
15
- import { N as listBuildLocks, _ as workspaceDeviceLastUseAt, b as leaseIsExpired, g as workspaceActivity, x as listLeaseFiles } from "./activity-CdpXXSq2.mjs";
16
- import { d as listAllIosSims, f as listAllIosSimsAsync } from "./ios-BveW7qK1.mjs";
16
+ import { N as listBuildLocks, _ as workspaceDeviceLastUseAt, b as leaseIsExpired, g as workspaceActivity, x as listLeaseFiles } from "./activity-BDovGcCm.mjs";
17
+ import { d as listAllIosSims, f as listAllIosSimsAsync } from "./ios-BNJVbrgV.mjs";
17
18
  import { s as metroStoreRoot } from "./errors-DHm_U5gv.mjs";
18
- import { t as resolveMaintenanceSettings } from "./settings-D9LtQaUw.mjs";
19
- import { m as probeHostedSession } from "./hosted-client-BLwuXEZS.mjs";
20
- import { o as runStop } from "./stop-CkmBkNyg.mjs";
21
- import { D as stimCliUseOf, E as stimCliEntries, M as worktreeArchiveLimits, T as serviceRunningFrom, _ as cacheBlocked, a as nestedWorktrees, b as measurePressure, i as excludeWatchmanCookies, o as porcelainPath, p as removeWorktreeTarget, r as excludePodChurn, s as reclaimKeys, v as measureDisk, w as uncommittedActivityOf, x as measurePressureAsync, y as measureDiskAsync } from "./worktree-BAC43Kio.mjs";
22
- import { n as describePullRequest, r as endedPullRequest, s as pullRequestLookups } from "./pull-request-m8cMZ3aE.mjs";
23
- import { a as lastFetchedAtAsync, c as mergeStateAsync, f as recordPullRequestLookup, i as fetchDefaultBranchAsync, o as localDefaultBranchAsync, r as FETCH_FRESH_MS } from "./warm-progress-CJQ8tk5O.mjs";
24
- import { a as restoreProblem, r as recordLightened, t as finishLightened } from "./lightened-Cdfmo8MO.mjs";
19
+ import { m as probeHostedSession } from "./hosted-client-DF0CnyIF.mjs";
20
+ import { o as runStop } from "./stop-McsnFLo6.mjs";
21
+ import { D as stimCliUseOf, E as stimCliEntries, M as worktreeArchiveLimits, T as serviceRunningFrom, _ as cacheBlocked, a as nestedWorktrees, b as measurePressure, i as excludeWatchmanCookies, o as porcelainPath, p as removeWorktreeTarget, r as excludePodChurn, s as reclaimKeys, v as measureDisk, w as uncommittedActivityOf, x as measurePressureAsync, y as measureDiskAsync } from "./worktree-fMs9rxUO.mjs";
22
+ import { n as describePullRequest, r as endedPullRequest, s as pullRequestLookups } from "./pull-request-BeKvGb7a.mjs";
23
+ import { a as lastFetchedAtAsync, c as mergeStateAsync, f as recordPullRequestLookup, i as fetchDefaultBranchAsync, o as localDefaultBranchAsync, r as FETCH_FRESH_MS } from "./warm-progress-Bk5Fd4vG.mjs";
24
+ import { a as restoreProblem, r as recordLightened, t as finishLightened } from "./lightened-DaZUxClW.mjs";
25
25
  import { readClaimSet } from "@stim-cli/core/ownership-claim";
26
26
  import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync } from "node:fs";
27
27
  import { tmpdir } from "node:os";
@@ -129,6 +129,7 @@ function removalBlocker(facts, olderThan, now, noOwnCommitsIdleMs) {
129
129
  if (facts.bare) return skip("bare-repository", "bare repository");
130
130
  if (typeof facts.source === "object") return skip("source-checkout-unknown", `source checkout unknown: ${facts.source.refusal}`);
131
131
  if (facts.source === "source") return skip("source-checkout", "source checkout");
132
+ if (facts.unregistered) return skip("not-registered", "not registered in this Stim home: STIM_HOME scopes this config");
132
133
  if (facts.locked) return skip("locked", LOCKED_REASON);
133
134
  if (facts.nested?.length) return skip("nested-worktree", `contains the worktree ${facts.nested.join(", ")}`);
134
135
  if (facts.inUse.length) return skip("in-use", `in use: ${facts.inUse.join("; ")}`);
@@ -396,14 +397,14 @@ async function porcelainOf(path, gitAnswered, operation) {
396
397
  }), null);
397
398
  return lines?.length ? lines : null;
398
399
  }
399
- function candidateRoots() {
400
+ function listedRoots() {
400
401
  const registered = Object.keys(loadConfig$1()?.projects ?? {}).filter(isAbsolute$1);
401
402
  const recorded = listWorkspaceDirs().flatMap((entry) => entry.projectRoot ? [entry.projectRoot] : []);
402
- return [.../* @__PURE__ */ new Set([
403
- ...registered,
404
- ...recorded,
405
- ...linkedWorktreesOf(registered)
406
- ])].filter((root) => existsSync$1(root)).toSorted();
403
+ return [.../* @__PURE__ */ new Set([...registered, ...recorded])];
404
+ }
405
+ function candidateRoots() {
406
+ const registered = Object.keys(loadConfig$1()?.projects ?? {}).filter(isAbsolute$1);
407
+ return [.../* @__PURE__ */ new Set([...listedRoots(), ...linkedWorktreesOf(registered)])].filter((root) => existsSync$1(root)).toSorted();
407
408
  }
408
409
  async function candidateRootsAsync(operation) {
409
410
  operation?.signal.throwIfAborted();
@@ -546,6 +547,8 @@ async function collectWorktreeSweep({ idle, olderThan, now, graceMs, underPressu
546
547
  }
547
548
  groups.set(entry.path, [...groups.get(entry.path) ?? [], root]);
548
549
  }
550
+ const scoped = deviceSweepIsScoped(operation?.env);
551
+ const registry = new Set(listedRoots());
549
552
  const inspected = [];
550
553
  await eachLimited([...[...groups].entries()], readConcurrency(operation), async ([index, [path, roots]]) => {
551
554
  operation?.signal.throwIfAborted();
@@ -567,6 +570,7 @@ async function collectWorktreeSweep({ idle, olderThan, now, graceMs, underPressu
567
570
  source: "refusal" in source ? source : linked ? "linked" : "source",
568
571
  bare: Boolean(entry?.bare),
569
572
  locked: Boolean(entry?.locked),
573
+ unregistered: scoped && !roots.some((root) => registry.has(root)),
570
574
  nested: entry ? nestedWorktrees(entries, entry.path) : [],
571
575
  porcelain,
572
576
  unpushed: linked ? await unlessTimedOut(() => unpushedCommitsAsync(path, read), null) : null,
@@ -833,7 +837,6 @@ function plan({ pressure, sizes, settings, budget, diskSteps = [], protectedRoot
833
837
  return true;
834
838
  };
835
839
  const floor = Math.max(budget.minFreeDiskMb, budget.hardFloorDiskMb);
836
- const emergency = pressure?.disk.some((disk) => disk.freeMb < budget.hardFloorDiskMb) ?? false;
837
840
  const low = pressure?.disk.filter((disk) => disk.freeMb < floor) ?? [];
838
841
  const reason = low.map((disk) => `free disk ${(disk.freeMb / 1024).toFixed(1)}G on ${disk.volume} under the ${(floor / 1024).toFixed(1)}G floor`).join("; ");
839
842
  const kinds = {
@@ -892,14 +895,7 @@ function plan({ pressure, sizes, settings, budget, diskSteps = [], protectedRoot
892
895
  if (cap === 0 || total <= cap) continue;
893
896
  let remaining = total;
894
897
  const targetBytes = cap * settings.capTargetPercent / 100;
895
- const why = `${category} ${(total / 1024 ** 3).toFixed(1)}G over the ${capGb}G cap; target ${(targetBytes / 1024 ** 3).toFixed(1)}G`;
896
- if (category === "compilation-cache" && !emergency) {
897
- skips.push({
898
- target: entries[0]?.dir ?? category,
899
- reason: `${why}; it can only be emptied whole, which runs only below the ${(budget.hardFloorDiskMb / 1024).toFixed(1)}G hard floor`
900
- });
901
- continue;
902
- }
898
+ const why = `${category} ${(total / 1024 ** 3).toFixed(1)}G over the ${capGb}G cap; ${category === "compilation-cache" ? "emptied whole" : `target ${(targetBytes / 1024 ** 3).toFixed(1)}G`}`;
903
899
  for (const size of entries.toSorted((a, b) => (b.idleDays ?? 0) - (a.idleDays ?? 0))) {
904
900
  if (remaining <= targetBytes) break;
905
901
  const kept = size.workspace === protectedRoot ? "the triggering workspace is protected" : size.blocked;
@@ -926,7 +922,7 @@ function plan({ pressure, sizes, settings, budget, diskSteps = [], protectedRoot
926
922
  }
927
923
  if (pressure?.memory.pressured) skips.push({
928
924
  target: "memory",
929
- reason: "memory pressure observed; automatic maintenance does not stop helpers or idle workspaces yet"
925
+ reason: "memory pressure observed; only idle Gradle and Kotlin daemons are stopped for memory, never devices or dev servers"
930
926
  });
931
927
  return {
932
928
  actions,
@@ -1004,963 +1000,984 @@ function recentUse(workspace, settings, windowMs = settings.protectRecentHours *
1004
1000
  return windowMs < 36e5 ? `used within the last ${Math.round(windowMs / 6e4)} minutes` : `used within the last ${windowMs / 36e5} hours`;
1005
1001
  }
1006
1002
  //#endregion
1007
- //#region src/maintenance/activity.ts
1008
- function readDeviceActivity(withSims, now) {
1009
- const sims = withSims ? listAllIosSims({ timeoutMs: DEVICE_LIST_TIMEOUT_MS }) : [];
1010
- return collectOwnedDeviceActivity(loadConfig$1(), sims, now);
1011
- }
1012
- /** A reader that reads device activity at most once per kind and reuses the answer, including a failure. */
1013
- function cachedDeviceActivity(now) {
1014
- const answers = /* @__PURE__ */ new Map();
1015
- return (withSims) => {
1016
- let answer = answers.get(withSims);
1017
- if (!answer) {
1018
- try {
1019
- answer = { devices: readDeviceActivity(withSims, now) };
1020
- } catch (error) {
1021
- answer = { error };
1022
- }
1023
- answers.set(withSims, answer);
1024
- }
1025
- if ("error" in answer) throw answer.error;
1026
- return answer.devices;
1003
+ //#region src/maintenance/idle-stop.ts
1004
+ const HOUR_MS = 36e5;
1005
+ const SETTING = "maintenance.idleStopHours";
1006
+ const METRO_REQUESTS = /* @__PURE__ */ new Set([
1007
+ "bundle_response_started",
1008
+ "bundle_response_progress",
1009
+ "bundle_response_finished",
1010
+ "bundle_response_failed",
1011
+ "bundle_build_started",
1012
+ "bundle_build_done",
1013
+ "bundle_build_failed",
1014
+ "manifest_request_started",
1015
+ "manifest_request_finished",
1016
+ "manifest_request_failed",
1017
+ "hmr_update"
1018
+ ]);
1019
+ const STIM_SESSION = "stim-teardown-inventory";
1020
+ const AGENT_DEVICE_DRIVERS = /* @__PURE__ */ new Set(["agent-device-claim", "agent-device-lease"]);
1021
+ function decideIdleStop(evidence, { idleMs, now }) {
1022
+ if (!(idleMs > 0)) return {
1023
+ stop: false,
1024
+ reason: `${SETTING} is 0`
1027
1025
  };
1028
- }
1029
- function cachedDeviceActivityAsync(now, env, signal, operation) {
1030
- const answers = /* @__PURE__ */ new Map();
1031
- return (withSims) => {
1032
- let answer = answers.get(withSims);
1033
- if (!answer) {
1034
- answer = (async () => {
1035
- signal?.throwIfAborted();
1036
- const sims = withSims ? await listAllIosSimsAsync({
1037
- timeoutMs: DEVICE_LIST_TIMEOUT_MS,
1038
- signal,
1039
- operation
1040
- }) : [];
1041
- return collectOwnedDeviceActivityAsync(loadConfig$1(), sims, now, env, signal, operation);
1042
- })();
1043
- answers.set(withSims, answer);
1044
- }
1045
- return answer;
1026
+ const last = evidence.activity.filter(({ at }) => Number.isFinite(at)).reduce((best, entry) => !best || entry.at > best.at ? entry : best, null);
1027
+ const idle = last ? now - last.at : NaN;
1028
+ if (last && idle < idleMs) return {
1029
+ stop: false,
1030
+ active: true,
1031
+ reason: `its last ${last.basis} was ${formatLongDuration(Math.max(0, idle))} ago, within ${SETTING}`
1032
+ };
1033
+ if (evidence.keep.length) return {
1034
+ stop: false,
1035
+ reason: evidence.keep.join("; ")
1036
+ };
1037
+ if (!last) return {
1038
+ stop: false,
1039
+ reason: "its last activity is unknown"
1040
+ };
1041
+ return {
1042
+ stop: true,
1043
+ idleMs: idle
1046
1044
  };
1047
1045
  }
1048
- function* workspaceActiveChecks(root, now, windowMs) {
1049
- if (workspaceBuildInProgress(root)) return "a build is in progress";
1050
- const holder = canonicalPath(root);
1051
- for (const { lease } of listLeaseFiles()) if (lease && !leaseIsExpired(lease, now) && canonicalPath(lease.holder) === holder) return `it holds the ${lease.platform} device lease on ${lease.deviceName ?? lease.id}`;
1052
- const owned = ownedPlatforms(root);
1053
- if (owned.ios || owned.android) {
1054
- let devices;
1055
- try {
1056
- devices = yield owned.ios;
1057
- } catch {
1058
- return "its owned devices cannot be listed to prove them idle";
1059
- }
1060
- const busy = devices.find((device) => device.project === root && device.activity.state !== "idle");
1061
- if (busy) return `its owned ${busy.kind} device ${busy.name} is ${busy.activity.state}`;
1062
- }
1063
- const activity = workspaceActivity(root, now);
1064
- if (activity.state !== "idle") return `its activity is ${activity.state}`;
1065
- const known = [Date.parse(activity.lastActivityAt ?? ""), workspaceLastUsed(root)].filter(Number.isFinite);
1066
- if (!known.length) return "its last activity is unknown";
1067
- return now - Math.max(...known) < windowMs ? usedWithin(windowMs) : null;
1068
- }
1069
- /** Why a workspace is not inactive for the pressure window, or null when maintenance may stop it. */
1070
- function workspaceActiveReason(root, now, windowMs, devices = (withSims) => readDeviceActivity(withSims, now)) {
1071
- const checks = workspaceActiveChecks(root, now, windowMs);
1072
- let step = checks.next();
1073
- while (!step.done) try {
1074
- step = checks.next(devices(step.value));
1046
+ async function idleStopHours(root, env, operation) {
1047
+ const setting = settingDefinition(SETTING);
1048
+ if (!setting?.env) return { invalid: `${SETTING} is not in the settings registry` };
1049
+ const raw = env[setting.env];
1050
+ const fromEnv = raw !== void 0 && raw !== "";
1051
+ let value;
1052
+ if (fromEnv) value = coerceSettingText(setting, raw);
1053
+ else try {
1054
+ const resolved = operation ? await resolveProjectSettingsAsync(root, {
1055
+ env,
1056
+ signal: operation.signal,
1057
+ declareFor: operation
1058
+ }) : resolveProjectSettings(root);
1059
+ value = settingValueAt(resolved.settings, SETTING);
1075
1060
  } catch (error) {
1076
- step = checks.throw(error);
1061
+ rethrowCleanup(error, operation?.signal);
1062
+ return { invalid: `${SETTING} cannot be resolved: ${error instanceof Error ? error.message : String(error)}` };
1077
1063
  }
1078
- return step.value;
1064
+ if (value === void 0) return { hours: Number(setting.default) };
1065
+ const error = settingValueError(setting, value);
1066
+ return error || typeof value !== "number" ? { invalid: `${fromEnv ? setting.env : SETTING} is invalid: expected ${error ?? "a number"}` } : { hours: value };
1079
1067
  }
1080
- async function workspaceActiveReasonAsync(root, now, windowMs, devices, signal) {
1081
- const checks = workspaceActiveChecks(root, now, windowMs);
1082
- let step = checks.next();
1083
- while (!step.done) try {
1084
- signal?.throwIfAborted();
1085
- step = checks.next(await devices(step.value));
1086
- } catch (error) {
1087
- if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1088
- signal?.throwIfAborted();
1089
- step = checks.throw(error);
1068
+ function hostedFacts(root) {
1069
+ const placements = [];
1070
+ const unreadable = [];
1071
+ for (const platform of ["ios", "android"]) for (const [slot, record] of Object.entries(hostedNativeRecords(readWorkspaceState$1(root), platform))) {
1072
+ const placement = parseHostedNativePlacement(record, platform);
1073
+ if (placement) {
1074
+ const label = platform === "ios" ? "iOS simulator" : "Android emulator";
1075
+ placements.push({
1076
+ label,
1077
+ machine: placement.machine,
1078
+ session: placement.session,
1079
+ platform
1080
+ });
1081
+ } else unreadable.push(unreadableHostedNative(slot, platform));
1090
1082
  }
1091
- return step.value;
1083
+ const host = readMacosRecord(root)?.host;
1084
+ if (host) placements.push({
1085
+ label: "macOS app",
1086
+ machine: host.machine,
1087
+ session: host.session
1088
+ });
1089
+ return {
1090
+ placements,
1091
+ unreadable
1092
+ };
1092
1093
  }
1093
- function ownedPlatforms(root) {
1094
- try {
1095
- const slots = projectDeviceSlots(loadConfig$1()?.projects?.[root]);
1096
- return {
1097
- ios: slots.some(({ platforms }) => platforms.ios?.owned === true),
1098
- android: slots.some(({ platforms }) => platforms.android?.owned === true)
1099
- };
1100
- } catch {
1101
- return {
1102
- ios: true,
1103
- android: true
1104
- };
1094
+ async function hostedKeepReasons(facts) {
1095
+ const keep = [...facts.unreadable];
1096
+ if (keep.length) return keep;
1097
+ for (const { label, machine, session, platform } of facts.placements) {
1098
+ const probe = await probeHostedSession({
1099
+ machine,
1100
+ session,
1101
+ platform
1102
+ }, { ttlMs: 0 });
1103
+ if (probe.state === "ready" || probe.state === "stopped") continue;
1104
+ const why = probe.state === "unreachable" ? `${machine} did not answer: ${probe.reason.replace(/\.+$/, "")}` : `${machine} cannot confirm it${probe.notice ? `: ${probe.notice.replace(/\.+$/, "")}` : ""}`;
1105
+ keep.push(`its hosted ${label} session ${session} is not confirmed: ${why}`);
1105
1106
  }
1107
+ return keep;
1106
1108
  }
1107
- function hasOwnedDevices(root) {
1109
+ function deviceKeepReason(device, platform) {
1110
+ const { activity } = device;
1111
+ const what = `its ${device.kind === "ios" ? "simulator" : "emulator"} ${device.name}`;
1112
+ if (activity.state === "driven" && !activity.basis.every((basis) => AGENT_DEVICE_DRIVERS.has(basis))) return `${what} is driven by ${activity.driver?.tool ?? "an unknown tool"}`;
1113
+ if (activity.basis.includes("agent-device-claim") && !activity.recent?.["agent-action"]) return `${what} has a live agent-device claim whose session activity cannot be found`;
1114
+ const probed = activity.state === "driven" ? activity.unknown ?? [] : activity.state === "unknown" ? activity.basis : [];
1115
+ const unknown = platform === "win32" ? probed.filter((basis) => basis !== "driver-process") : probed;
1116
+ if (unknown.length) return `${what} has unknown activity (${unknown.join(", ")})`;
1117
+ return null;
1118
+ }
1119
+ function recentAt(activity, basis) {
1120
+ return Date.parse(activity.recent?.[basis] ?? "");
1121
+ }
1122
+ const missing = (error) => error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
1123
+ const message = (error) => error instanceof Error ? error.message : String(error);
1124
+ function agentSessionsActedAt(root) {
1125
+ const dir = join(workspaceAgentDeviceDir(root), "sessions");
1126
+ let names;
1108
1127
  try {
1109
- return projectDeviceSlots(loadConfig$1()?.projects?.[root]).some(({ platforms }) => platforms.ios?.owned === true || platforms.android?.owned === true);
1110
- } catch {
1111
- return false;
1128
+ names = readdirSync(dir);
1129
+ } catch (error) {
1130
+ return missing(error) ? NaN : `its agent-device sessions cannot be read (${message(error)})`;
1131
+ }
1132
+ let latest = NaN;
1133
+ for (const name of names) {
1134
+ if (name === STIM_SESSION) continue;
1135
+ try {
1136
+ const at = statSync(join(dir, name, "events.ndjson")).mtimeMs;
1137
+ if (!(at <= latest)) latest = at;
1138
+ } catch (error) {
1139
+ if (!missing(error)) return `its agent-device session ${name} cannot be read (${message(error)})`;
1140
+ }
1112
1141
  }
1142
+ return latest;
1113
1143
  }
1114
- function usedWithin(windowMs) {
1115
- return `used within the last ${Math.round(windowMs / 6e4)} minutes`;
1144
+ function metroRequestAt(root, since, serving) {
1145
+ const file = join(workspaceLogsDir$1(root), "metro.ndjson");
1146
+ const rotated = rotatedLogPath(file);
1147
+ const records = [];
1148
+ for (const path of [rotated, file]) try {
1149
+ records.push(...parseNdjsonText(readFileSync(path, "utf8")));
1150
+ } catch (error) {
1151
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
1152
+ return `its Metro log cannot be read (${error instanceof Error ? error.message : String(error)})`;
1153
+ }
1154
+ let latest = NaN;
1155
+ let earliest = Infinity;
1156
+ for (const record of records) {
1157
+ if (typeof record.ts !== "number") continue;
1158
+ earliest = Math.min(earliest, record.ts);
1159
+ if (typeof record.event === "string" && METRO_REQUESTS.has(record.event) && !(record.ts <= latest)) latest = record.ts;
1160
+ }
1161
+ if (!Number.isFinite(latest) && earliest > since && existsSync(rotated)) return `its rotated Metro log does not reach back ${SETTING}`;
1162
+ if (serving && earliest === Infinity) return "its dev server runs but its Metro log is missing or empty";
1163
+ return latest;
1116
1164
  }
1117
- //#endregion
1118
- //#region src/maintenance/devices.ts
1119
- const AVD_SIZE_TIMEOUT_MS = 3e4;
1120
- /** The disk of each owned simulator or emulator of a registered workspace and of each parked device. */
1121
- async function ownedDeviceUsage(failure, { sims = () => listAllIosSims({ timeoutMs: DEVICE_LIST_TIMEOUT_MS }), avds = () => listAvds({ timeoutMs: DEVICE_LIST_TIMEOUT_MS }), avdDirectory = ownedAvdDirectory, size = (dir) => measuredDirectorySizeAsync(dir, { timeoutMs: AVD_SIZE_TIMEOUT_MS }) } = {}) {
1122
- const config = loadConfig$1();
1123
- const owned = [];
1124
- for (const [root, project] of Object.entries(config?.projects ?? {})) for (const { platforms } of projectDeviceSlots(project)) {
1125
- if (platforms.ios?.owned && platforms.ios.deviceUdid) owned.push({
1126
- kind: "ios",
1127
- id: platforms.ios.deviceUdid,
1128
- workspace: canonicalPath(root)
1129
- });
1130
- if (platforms.android?.owned && platforms.android.avdName) owned.push({
1131
- kind: "android",
1132
- id: platforms.android.avdName,
1133
- workspace: canonicalPath(root)
1134
- });
1165
+ function unreadableViewers() {
1166
+ const dir = deviceViewersDir();
1167
+ let names;
1168
+ try {
1169
+ names = readdirSync(dir).filter((name) => name.endsWith(".json"));
1170
+ } catch (error) {
1171
+ return missing(error) ? null : `the stim-server viewer records cannot be read (${message(error)})`;
1135
1172
  }
1136
- for (const record of readParked("ios", { config })) owned.push({
1137
- kind: "ios",
1138
- id: record.udid
1173
+ for (const name of names) {
1174
+ const record = readJsonObject(join(dir, name));
1175
+ if (!record) return `the stim-server viewer record ${name} cannot be read`;
1176
+ if ((0, process_identity_exports.inspectProcessIdentity)(record) === "unknown") return `the stim-server behind the viewer record ${name} cannot be verified`;
1177
+ }
1178
+ return null;
1179
+ }
1180
+ async function keepReasons(root, devices, { now, platform, locked, operation }) {
1181
+ const checks = {
1182
+ devServer: false,
1183
+ nativeRun: !locked,
1184
+ hosted: false,
1185
+ hostedMacos: false
1186
+ };
1187
+ const keep = operation ? await workspaceInUseAsync(root, checks, operation.signal, operation) : workspaceInUse(root, checks);
1188
+ if (workspaceBuildInProgress(root)) keep.push("a build is in progress");
1189
+ if (readRemoteSession(root)) keep.push("it has a remote device session");
1190
+ const holder = canonicalPath(root);
1191
+ for (const { lease, path } of listLeaseFiles()) if (!lease) keep.push(`the device lease ${path} cannot be read`);
1192
+ else if (!leaseIsExpired(lease, now) && canonicalPath(lease.holder) === holder) keep.push(`it holds the ${lease.platform} device lease on ${lease.deviceName ?? lease.id}`);
1193
+ const browser = webFacts(readWebRecord(root));
1194
+ if (browser && browser.status !== "stopped") keep.push(`its owned Chrome is ${browser.status}`);
1195
+ for (const device of devices) {
1196
+ const reason = deviceKeepReason(device, platform);
1197
+ if (reason) keep.push(reason);
1198
+ }
1199
+ const viewers = devices.length ? unreadableViewers() : null;
1200
+ if (viewers) keep.push(viewers);
1201
+ return keep;
1202
+ }
1203
+ async function idleStopEvidence(root, devices, { now, idleMs, platform = process.platform, locked = false, serving = false, operation }) {
1204
+ const state = readWorkspaceState$1(root);
1205
+ if (!state && existsSync(workspaceStateFile$1(root))) return {
1206
+ activity: [],
1207
+ keep: ["its state.json cannot be read"]
1208
+ };
1209
+ const sessions = agentSessionsActedAt(root);
1210
+ if (typeof sessions === "string") return {
1211
+ activity: [],
1212
+ keep: [sessions]
1213
+ };
1214
+ const build = state?.lastBuild;
1215
+ const builtAt = Date.parse(String(build?.startedAt ?? "")) + (typeof build?.durationMs === "number" ? build.durationMs : 0);
1216
+ const activity = [
1217
+ {
1218
+ basis: "stim command",
1219
+ at: Date.parse(String(state?.lastUsedAt ?? ""))
1220
+ },
1221
+ {
1222
+ basis: "native run",
1223
+ at: builtAt
1224
+ },
1225
+ {
1226
+ basis: "agent-device command",
1227
+ at: typeof sessions === "number" ? sessions : NaN
1228
+ },
1229
+ ...devices.flatMap(({ activity: device }) => [{
1230
+ basis: "agent-device command",
1231
+ at: recentAt(device, "agent-action")
1232
+ }, {
1233
+ basis: "live view",
1234
+ at: recentAt(device, "viewer")
1235
+ }])
1236
+ ].filter(({ at }) => Number.isFinite(at));
1237
+ if (activity.some(({ at }) => now - at < idleMs)) return {
1238
+ activity,
1239
+ keep: []
1240
+ };
1241
+ const keep = await keepReasons(root, devices, {
1242
+ now,
1243
+ platform,
1244
+ locked,
1245
+ operation
1139
1246
  });
1140
- for (const record of readParked("android", { config })) owned.push({
1141
- kind: "android",
1142
- id: record.name
1247
+ if (keep.length) return {
1248
+ activity,
1249
+ keep
1250
+ };
1251
+ const metro = metroRequestAt(root, now - idleMs, serving);
1252
+ if (typeof metro === "string") return {
1253
+ activity,
1254
+ keep: [metro]
1255
+ };
1256
+ if (Number.isFinite(metro)) activity.push({
1257
+ basis: "Metro request",
1258
+ at: metro
1143
1259
  });
1144
- const listed = (read, label) => {
1145
- if (!owned.length) return [];
1146
- try {
1147
- return read();
1148
- } catch {
1149
- failure(label);
1150
- return null;
1151
- }
1260
+ if (!activity.some(({ at }) => now - at < idleMs)) keep.push(...await hostedKeepReasons(hostedFacts(root)));
1261
+ return {
1262
+ activity,
1263
+ keep
1152
1264
  };
1153
- const iosRecords = owned.some((device) => device.kind === "ios") ? listed(sims, "the simulator list") : [];
1154
- const avdNames = owned.some((device) => device.kind === "android") ? listed(avds, "the emulator list") : [];
1155
- const usage = [];
1156
- for (const device of owned) {
1157
- const workspace = device.workspace ? { workspace: device.workspace } : {};
1158
- if (device.kind === "ios") {
1159
- const sim = iosRecords?.find((record) => record.udid === device.id);
1160
- if (sim && typeof sim.dataPathSize === "number") usage.push({
1161
- kind: "ios",
1162
- name: sim.name,
1163
- dir: sim.dataPath ?? device.id,
1164
- bytes: sim.dataPathSize,
1165
- ...workspace
1166
- });
1167
- continue;
1265
+ }
1266
+ function rethrowCleanup(error, signal) {
1267
+ if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1268
+ signal?.throwIfAborted();
1269
+ }
1270
+ async function unseenEmulatorError(unseen, operation) {
1271
+ try {
1272
+ const signal = operation?.signal;
1273
+ const adb = operation ? await listAdbDevicesAsync({
1274
+ timeoutMs: 5e3,
1275
+ signal,
1276
+ operation
1277
+ }) : listAdbDevices({ timeoutMs: 5e3 });
1278
+ for (const { serial } of [...adb.emulators, ...adb.unhealthy.filter((entry) => entry.kind === "emulator")]) {
1279
+ const name = operation ? await getAvdNameForSerialAsync(serial, {
1280
+ timeoutMs: 5e3,
1281
+ signal,
1282
+ operation
1283
+ }) : getAvdNameForSerial(serial, { timeoutMs: 5e3 });
1284
+ if (name === null) return `its emulators cannot be identified to prove them idle (${serial} gave no AVD name)`;
1285
+ if (unseen.includes(name)) return `its emulator ${name} runs as ${serial}, but its activity could not be read`;
1168
1286
  }
1169
- const dir = avdNames?.includes(device.id) ? avdDirectory(device.id) : null;
1170
- if (!dir) continue;
1171
- const bytes = await size(dir);
1172
- if (bytes === null) failure(dir, device.workspace);
1173
- else usage.push({
1174
- kind: "android",
1175
- name: device.id,
1176
- dir,
1177
- bytes,
1178
- ...workspace
1179
- });
1287
+ return null;
1288
+ } catch (error) {
1289
+ rethrowCleanup(error, operation?.signal);
1290
+ return `its emulators cannot be listed to prove them idle (${error instanceof Error ? error.message : String(error)})`;
1180
1291
  }
1181
- return usage;
1182
1292
  }
1183
- async function measureOwnedDevices(now, failure) {
1184
- return (await ownedDeviceUsage(failure)).map(({ kind, name, dir, bytes, workspace }) => {
1185
- const size = {
1186
- name: `${workspace ? "owned" : "parked"} ${kind === "ios" ? "simulator" : "emulator"} ${name}`,
1187
- category: "owned-devices",
1188
- dir,
1189
- bytes,
1190
- measuredAt: now
1191
- };
1192
- if (workspace) size.workspace = workspace;
1193
- return size;
1293
+ /** Why the dev server a stale supervisor started may still run, or null when it is gone. */
1294
+ function survivingServer(recorded) {
1295
+ const pid = recorded?.serverPid;
1296
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return null;
1297
+ const token = recorded?.serverProcessToken;
1298
+ return (typeof token === "string" ? ["same", "unknown"].includes((0, process_identity_exports.inspectProcessIdentity)({
1299
+ pid,
1300
+ processToken: token
1301
+ })) : pidExists(pid)) ? `its dev server (pid ${pid}) may still run after its supervisor exited; stim stop ends it` : null;
1302
+ }
1303
+ async function candidate(path, env, devices, operation) {
1304
+ const signal = operation?.signal;
1305
+ const project = loadConfig$1()?.projects?.[path];
1306
+ if (!project) return null;
1307
+ const supervisor = resolveSupervisorTarget({
1308
+ state: readWorkspaceState$1(path)?.supervisor,
1309
+ record: project.supervisor,
1310
+ reservedPort: project.metroPort
1194
1311
  });
1312
+ const slots = projectDeviceSlots(project);
1313
+ const ownsIos = slots.some(({ platforms }) => platforms.ios?.owned === true);
1314
+ const owns = ownsIos || slots.some(({ platforms }) => platforms.android?.owned === true);
1315
+ const hosted = hostedFacts(path);
1316
+ const isHosted = hosted.placements.length > 0 || hosted.unreadable.length > 0;
1317
+ if (!owns && !isHosted && (supervisor.status === "none" || supervisor.status === "stale")) return null;
1318
+ const setting = await idleStopHours(path, env, operation);
1319
+ if ("invalid" in setting) return { skip: setting.invalid };
1320
+ if (setting.hours === 0) return null;
1321
+ let booted = [];
1322
+ if (owns) try {
1323
+ booted = (await devices(ownsIos)).filter((device) => device.project === path);
1324
+ } catch (error) {
1325
+ rethrowCleanup(error, signal);
1326
+ return supervisor.status === "none" || supervisor.status === "stale" ? null : { skip: "its owned devices cannot be listed to prove them idle" };
1327
+ }
1328
+ if (supervisor.status === "unverified") return { skip: `its dev server supervisor cannot be verified: ${supervisor.reason ?? "unknown identity"}` };
1329
+ if (supervisor.status === "ours" && readWorkspaceState$1(path)?.supervisor?.mode === "command-child") return { skip: "its dev server runs metro.command, whose bundle and HMR requests Stim cannot see" };
1330
+ if (supervisor.status === "ours" && readWorkspaceState$1(path)?.supervisor?.hmrUpdates !== true) return { skip: "its dev server does not report HMR updates to Stim: an Expo SDK before 54, or a server an older Stim started, which stim stop and stim start restart" };
1331
+ const avdNames = slots.flatMap(({ platforms }) => platforms.android?.owned && platforms.android.avdName ? [platforms.android.avdName] : []);
1332
+ if (supervisor.status !== "ours" && booted.length === 0 && !isHosted) return null;
1333
+ const orphan = supervisor.status === "stale" ? survivingServer(readWorkspaceState$1(path)?.supervisor) : null;
1334
+ if (orphan) return { skip: orphan };
1335
+ const seen = new Set(booted.flatMap((device) => device.kind === "android" ? [device.id] : []));
1336
+ const unseen = avdNames.filter((name) => !seen.has(name));
1337
+ const emulators = unseen.length ? await unseenEmulatorError(unseen, operation) : null;
1338
+ if (emulators) return { skip: emulators };
1339
+ return {
1340
+ path,
1341
+ hours: setting.hours,
1342
+ serving: supervisor.status === "ours",
1343
+ devices: booted
1344
+ };
1195
1345
  }
1196
- function* deviceDeletionChecks({ roots, windowMs, reason, protectedRoot, pinned, sizes, now, extra, env = process.env }) {
1346
+ /**
1347
+ * Plans stopping each workspace, other than `protectedRoot`, whose dev server runs or whose owned simulator or
1348
+ * emulator is booted, once it has had no real activity for its maintenance.idleStopHours.
1349
+ */
1350
+ async function planIdleStop({ protectedRoot, now, devices, env = process.env, platform = process.platform, operation }) {
1197
1351
  const plan = {
1198
1352
  actions: [],
1199
1353
  blocked: [],
1200
1354
  skips: []
1201
1355
  };
1202
1356
  if (deviceSweepIsScoped(env)) return plan;
1203
- for (const entry of roots) {
1204
- const root = canonicalPath(entry.root);
1205
- if (root === protectedRoot || !hasOwnedDevices(root)) continue;
1206
- const kept = pinned(root) ? "pinned by maintenance.keep" : now - workspaceLastUsed(root) < windowMs ? usedWithin(windowMs) : workspaceInUse(root).map((why) => `in use: ${why}`)[0] ?? (yield root);
1207
- if (kept) {
1208
- plan.skips.push({
1209
- target: root,
1210
- reason: kept,
1211
- workspace: root
1357
+ for (const path of Object.keys(loadConfig$1()?.projects ?? {})) {
1358
+ const root = canonicalPath(path);
1359
+ if (root === protectedRoot) continue;
1360
+ operation?.signal.throwIfAborted();
1361
+ const found = await candidate(path, env, devices, operation);
1362
+ if (!found) continue;
1363
+ if ("skip" in found) {
1364
+ plan.skips.push({
1365
+ target: root,
1366
+ reason: found.skip,
1367
+ workspace: root
1212
1368
  });
1213
1369
  continue;
1214
1370
  }
1215
- plan.actions.push({
1216
- kind: "would-delete-devices",
1217
- target: root,
1218
- workspace: root,
1219
- bytes: sizes.filter((size) => size.category === "owned-devices" && size.workspace === root).reduce((sum, size) => sum + size.bytes, 0),
1220
- reason: entry.reason ? `${entry.reason}, ${reason}` : reason,
1221
- ...extra
1222
- });
1223
- }
1224
- return plan;
1225
- }
1226
- function planDeviceDeletion(options) {
1227
- const activity = cachedDeviceActivity(options.now);
1228
- const checks = deviceDeletionChecks(options);
1229
- let step = checks.next();
1230
- while (!step.done) step = checks.next(workspaceActiveReason(step.value, options.now, options.windowMs, activity));
1231
- return step.value;
1232
- }
1233
- async function planDeviceDeletionAsync(options, signal, operation) {
1234
- const activity = cachedDeviceActivityAsync(options.now, options.env ?? process.env, signal, operation);
1235
- const checks = deviceDeletionChecks(options);
1236
- let step = checks.next();
1237
- while (!step.done) {
1238
- signal.throwIfAborted();
1239
- step = checks.next(await workspaceActiveReasonAsync(step.value, options.now, options.windowMs, activity, signal));
1240
- }
1241
- return step.value;
1242
- }
1243
- /**
1244
- * The workspaces of linked worktrees that gc keeps although their branch is merged or their pull request ended,
1245
- * such as a dirty one. A worktree gc removes takes its devices with it.
1246
- */
1247
- function finishedWorkspaces(sweep, now) {
1248
- const kept = /* @__PURE__ */ new Set([
1249
- "not-a-worktree",
1250
- "bare-repository",
1251
- "source-checkout",
1252
- "source-checkout-unknown",
1253
- "locked",
1254
- "nested-worktree",
1255
- "recent-activity",
1256
- "activity-unknown"
1257
- ]);
1258
- if (!sweep) return [];
1259
- return sweep.worktrees.flatMap((worktree) => {
1260
- if (worktree.skipped === null || kept.has(worktree.skipCode ?? "")) return [];
1261
- const merged = worktree.merge?.merged ? worktree.merge.mergedAt : null;
1262
- const ended = endedPullRequest(worktree.pullRequest);
1263
- if (merged === null && !ended) return [];
1264
- if (now - Math.max(merged ?? -Infinity, ended ? ended.endedAt ?? now : -Infinity) < sweep.graceMs) return [];
1265
- const reason = `its worktree is finished (${worktreeRemovalReason(worktree, sweep)}) but kept`;
1266
- return worktree.keys.map((root) => ({
1267
- root: canonicalPath(root),
1268
- reason
1269
- }));
1270
- });
1271
- }
1272
- /** Each workspace's effective devices.idleShutdownMinutes, or 0 when it cannot be resolved. */
1273
- function idleShutdownMinutes(root) {
1274
- try {
1275
- return deviceIdleShutdownMinutesSetting(resolveProjectSettings(root).settings);
1276
- } catch {
1277
- return 0;
1278
- }
1279
- }
1280
- /**
1281
- * Plans shutting down each booted owned simulator and emulator idle for its workspace's devices.idleShutdownMinutes,
1282
- * whether or not a supervisor runs there. The devices are shut down, never deleted.
1283
- */
1284
- function planIdleShutdown({ protectedRoot, now, env = process.env }) {
1285
- const plan = {
1286
- actions: [],
1287
- blocked: [],
1288
- skips: []
1289
- };
1290
- if (deviceSweepIsScoped(env)) return plan;
1291
- const minutes = new Map(Object.entries(loadConfig$1()?.projects ?? {}).flatMap(([root, project]) => {
1292
- const value = !projectDeviceSlots(project).some(({ platforms }) => platforms.ios?.owned === true || platforms.android?.owned === true) || canonicalPath(root) === protectedRoot ? 0 : idleShutdownMinutes(root);
1293
- return value > 0 ? [[root, value]] : [];
1294
- }));
1295
- if (minutes.size === 0) return plan;
1296
- for (const { device, idleForMs } of dueIdleDevices(void 0, Math.min(...minutes.values()) * 6e4, now)) {
1297
- const own = minutes.get(device.project);
1298
- if (own === void 0 || idleForMs < own * 6e4 || now - workspaceDeviceLastUseAt(device.project) < own * 6e4) continue;
1299
- const root = canonicalPath(device.project);
1300
- plan.actions.push({
1301
- kind: "would-shutdown-device",
1302
- target: device.id,
1303
- workspace: root,
1304
- bytes: 0,
1305
- reason: `${device.kind === "ios" ? "simulator" : "emulator"} ${device.name} idle ${formatLongDuration(idleForMs)}, over devices.idleShutdownMinutes ${own}`
1306
- });
1307
- }
1308
- return plan;
1309
- }
1310
- //#endregion
1311
- //#region src/maintenance/sweep.ts
1312
- async function planSweep({ settings, sizes, protectedRoot, pinned, now, devices = true, operation }) {
1313
- const actions = [];
1314
- const skips = [];
1315
- const blocked = [];
1316
- const days = settings.olderThanDays;
1317
- const outputs = days > 0 ? await collectWorkspaceOutputs({
1318
- olderThan: days,
1319
- now,
1320
- measure: false,
1321
- signal: operation?.signal,
1322
- operation
1323
- }) : { workspaces: [] };
1324
- for (const entry of outputs.workspaces) {
1325
- const root = entry.projectRoot === null ? null : canonicalPath(entry.projectRoot);
1326
- if (root !== null && keptByLock(entry) && entry.keptReason) skips.push({
1327
- target: root,
1328
- reason: entry.keptReason,
1329
- workspace: root
1371
+ const idleMs = found.hours * HOUR_MS;
1372
+ const decision = decideIdleStop(await idleStopEvidence(path, found.devices, {
1373
+ now,
1374
+ idleMs,
1375
+ platform,
1376
+ serving: found.serving,
1377
+ operation
1378
+ }), {
1379
+ idleMs,
1380
+ now
1330
1381
  });
1331
- if (root === null || !entry.willClear || root === protectedRoot) continue;
1332
- if (pinned(root)) {
1333
- skips.push({
1382
+ if (!decision.stop) {
1383
+ if (!decision.active) plan.skips.push({
1334
1384
  target: root,
1335
- reason: "pinned by maintenance.keep",
1385
+ reason: decision.reason,
1336
1386
  workspace: root
1337
1387
  });
1338
1388
  continue;
1339
1389
  }
1340
- const size = sizes.find((candidate) => candidate.workspace === root && candidate.category === "workspace-outputs");
1341
- actions.push({
1342
- kind: "would-clear-outputs",
1390
+ plan.actions.push({
1391
+ kind: "would-stop-workspace",
1392
+ check: "idle",
1343
1393
  target: root,
1344
1394
  workspace: root,
1345
- bytes: size?.bytes ?? 0,
1346
- olderThanDays: days,
1347
- reason: `idle ${entry.idleDays} days, older than ${days} days (age sweep)`,
1348
- check: "sweep"
1349
- });
1350
- }
1351
- for (const cache of days > 0 ? trimmableCaches(operation?.env, operation?.cwd).filter((candidate) => !isInsideWorkspaces(candidate.dir)) : []) actions.push({
1352
- kind: "would-trim-cache",
1353
- target: cacheLabel(cache),
1354
- dir: cache.dir,
1355
- bytes: 0,
1356
- olderThanDays: days,
1357
- reason: `entries unused for ${days} days (age sweep)`,
1358
- check: "sweep"
1359
- });
1360
- try {
1361
- const orphans = await collectOrphanedWorkspaces(Object.keys(loadConfig$1()?.projects ?? {}), listMountedVolumes(), {
1362
- measure: false,
1363
- operation
1364
- });
1365
- for (const orphan of orphans.orphaned) actions.push({
1366
- kind: "would-remove-orphan",
1367
- target: orphan.dir,
1368
- bytes: orphan.bytes ?? 0,
1369
- reason: `its project ${orphan.projectRoot} no longer exists`,
1370
- check: "sweep"
1371
- });
1372
- for (const kept of orphans.skipped) skips.push({
1373
- target: kept.dir,
1374
- reason: kept.reason
1375
- });
1376
- } catch (error) {
1377
- if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1378
- operation?.signal.throwIfAborted();
1379
- blocked.push(`Could not look for orphaned workspace directories: ${error instanceof Error ? error.message : error}`);
1380
- }
1381
- if (devices && settings.deviceIdleDays > 0) {
1382
- const options = {
1383
- roots: Object.keys(loadConfig$1()?.projects ?? {}).map((root) => ({ root })),
1384
- windowMs: settings.deviceIdleDays * 864e5,
1385
- reason: `idle for ${settings.deviceIdleDays} days (age sweep)`,
1386
- protectedRoot,
1387
- pinned,
1388
- sizes,
1389
- now,
1390
- extra: {
1391
- check: "sweep",
1392
- olderThanDays: settings.deviceIdleDays
1393
- },
1394
- env: operation?.env
1395
- };
1396
- const reaped = operation ? await planDeviceDeletionAsync(options, operation.signal, operation) : planDeviceDeletion(options);
1397
- actions.push(...reaped.actions);
1398
- skips.push(...reaped.skips);
1399
- }
1400
- if (devices && days > 0 && !deviceSweepIsScoped(operation?.env ?? process.env)) for (const kind of ["ios", "android"]) for (const record of readParked(kind)) {
1401
- const parkedDays = Math.floor((now - Date.parse(record.parkedAt)) / 864e5);
1402
- if (!(parkedDays >= days)) continue;
1403
- const label = `parked ${kind === "ios" ? "simulator" : "emulator"} ${record.name}`;
1404
- actions.push({
1405
- kind: "would-delete-parked-device",
1406
- target: kind === "ios" ? record.udid : record.name,
1407
- bytes: sizes.find((size) => size.category === "owned-devices" && !size.workspace && size.name === label)?.bytes ?? 0,
1408
- olderThanDays: days,
1409
- reason: `${label} unused for ${parkedDays} days, older than ${days} days (age sweep)`,
1410
- check: "sweep"
1411
- });
1412
- }
1413
- const mounted = listMountedVolumes();
1414
- for (const cache of readManifest().caches) {
1415
- if (!isAbsolute(cache.dir) || existsSync(cache.dir) || !isOnMountedVolume(cache.dir, mounted)) continue;
1416
- actions.push({
1417
- kind: "would-unregister-cache",
1418
- target: cache.dir,
1419
- dir: cache.dir,
1420
1395
  bytes: 0,
1421
- reason: "its directory no longer exists",
1422
- check: "sweep"
1396
+ reason: `no real activity for ${formatLongDuration(decision.idleMs)}, over ${SETTING} ${found.hours}`
1423
1397
  });
1424
1398
  }
1425
- return {
1426
- actions,
1427
- blocked,
1428
- skips
1429
- };
1399
+ return plan;
1430
1400
  }
1431
- async function planWorktrees({ protectedRoot, pinned, now, level, graceMs, sizes, protectRecentMs = 0, refresh, idleDays = null, operation }) {
1432
- const sweep = await collectWorktreeSweep({
1433
- idle: idleDays !== null,
1434
- olderThan: idleDays,
1435
- now,
1436
- underPressure: level === 3,
1437
- operation,
1438
- ...graceMs === void 0 ? {} : { graceMs },
1439
- ...refresh === void 0 ? {} : { refresh }
1440
- });
1441
- const actions = [];
1442
- const skips = [];
1443
- const keep = [];
1444
- for (const worktree of sweep.worktrees) {
1445
- if (worktree.skipped) continue;
1446
- const path = canonicalPath(worktree.path);
1447
- const reason = protectedRoot === path || protectedRoot.startsWith(`${path}${sep}`) ? "the command that started this pass runs inside it" : worktree.keys.some(pinned) ? "pinned by maintenance.keep" : null;
1448
- if (reason) {
1449
- skips.push({
1450
- target: worktree.path,
1451
- reason
1452
- });
1453
- continue;
1454
- }
1455
- keep.push(worktree);
1456
- actions.push({
1457
- kind: "would-remove-worktree",
1458
- target: worktree.path,
1459
- bytes: 0,
1460
- reason: worktreeRemovalReason(worktree, sweep),
1461
- check: level === void 0 && idleDays !== null && !worktree.merge?.merged && !endedPullRequest(worktree.pullRequest) ? "sweep" : "worktree",
1462
- ...level ? { level } : {}
1463
- });
1464
- }
1465
- if (sizes) {
1466
- const options = {
1467
- roots: finishedWorkspaces(sweep, now),
1468
- windowMs: Math.max(sweep.graceMs, protectRecentMs),
1469
- reason: "finished-worktree check",
1470
- protectedRoot,
1471
- pinned,
1472
- sizes,
1401
+ const kept$1 = (detail) => ({
1402
+ status: "kept",
1403
+ bytes: 0,
1404
+ detail
1405
+ });
1406
+ /**
1407
+ * Stops a planned idle workspace the way `stim stop` does, under its native-run and metro-start locks, after
1408
+ * deciding again that it is still idle. Physical-device leases stay.
1409
+ */
1410
+ async function stopIdleWorkspace(action, { protectedRoot, devices, operation, env = operation?.env ?? process.env, by = "automatic maintenance" }) {
1411
+ const root = action.workspace ?? action.target;
1412
+ if (root === protectedRoot) return kept$1("the command that started this pass runs in it");
1413
+ if (deviceSweepIsScoped(env)) return kept$1("STIM_HOME scopes this config, and devices are machine-wide");
1414
+ const path = Object.keys(loadConfig$1()?.projects ?? {}).find((entry) => canonicalPath(entry) === root) ?? root;
1415
+ const stillIdle = async () => {
1416
+ const now = Date.now();
1417
+ const found = await candidate(path, env, devices(), operation);
1418
+ if (!found) return "nothing of it runs any more";
1419
+ if ("skip" in found) return found.skip;
1420
+ const idleMs = found.hours * HOUR_MS;
1421
+ const decision = decideIdleStop(await idleStopEvidence(path, found.devices, {
1473
1422
  now,
1474
- extra: { check: "worktree" },
1475
- env: operation?.env
1476
- };
1477
- const devices = operation ? await planDeviceDeletionAsync(options, operation.signal, operation) : planDeviceDeletion(options);
1478
- actions.push(...devices.actions);
1479
- skips.push(...devices.skips);
1480
- }
1481
- return {
1482
- actions,
1483
- blocked: [],
1484
- skips,
1485
- sweep: {
1486
- ...sweep,
1487
- worktrees: keep
1488
- }
1489
- };
1490
- }
1491
- //#endregion
1492
- //#region src/maintenance/idle-stop.ts
1493
- const HOUR_MS = 36e5;
1494
- const SETTING = "maintenance.idleStopHours";
1495
- const METRO_REQUESTS = /* @__PURE__ */ new Set([
1496
- "bundle_response_started",
1497
- "bundle_response_progress",
1498
- "bundle_response_finished",
1499
- "bundle_response_failed",
1500
- "bundle_build_started",
1501
- "bundle_build_done",
1502
- "bundle_build_failed",
1503
- "manifest_request_started",
1504
- "manifest_request_finished",
1505
- "manifest_request_failed",
1506
- "hmr_update"
1507
- ]);
1508
- const STIM_SESSION = "stim-teardown-inventory";
1509
- const AGENT_DEVICE_DRIVERS = /* @__PURE__ */ new Set(["agent-device-claim", "agent-device-lease"]);
1510
- function decideIdleStop(evidence, { idleMs, now }) {
1511
- if (!(idleMs > 0)) return {
1512
- stop: false,
1513
- reason: `${SETTING} is 0`
1514
- };
1515
- const last = evidence.activity.filter(({ at }) => Number.isFinite(at)).reduce((best, entry) => !best || entry.at > best.at ? entry : best, null);
1516
- const idle = last ? now - last.at : NaN;
1517
- if (last && idle < idleMs) return {
1518
- stop: false,
1519
- active: true,
1520
- reason: `its last ${last.basis} was ${formatLongDuration(Math.max(0, idle))} ago, within ${SETTING}`
1521
- };
1522
- if (evidence.keep.length) return {
1523
- stop: false,
1524
- reason: evidence.keep.join("; ")
1525
- };
1526
- if (!last) return {
1527
- stop: false,
1528
- reason: "its last activity is unknown"
1529
- };
1530
- return {
1531
- stop: true,
1532
- idleMs: idle
1423
+ idleMs,
1424
+ locked: true,
1425
+ serving: found.serving,
1426
+ operation
1427
+ }), {
1428
+ idleMs,
1429
+ now
1430
+ });
1431
+ return decision.stop ? null : decision.reason;
1533
1432
  };
1534
- }
1535
- async function idleStopHours(root, env, operation) {
1536
- const setting = settingDefinition(SETTING);
1537
- if (!setting?.env) return { invalid: `${SETTING} is not in the settings registry` };
1538
- const raw = env[setting.env];
1539
- const fromEnv = raw !== void 0 && raw !== "";
1540
- let value;
1541
- if (fromEnv) value = coerceSettingText(setting, raw);
1542
- else try {
1543
- const resolved = operation ? await resolveProjectSettingsAsync(root, {
1544
- env,
1545
- signal: operation.signal,
1546
- declareFor: operation
1547
- }) : resolveProjectSettings(root);
1548
- value = settingValueAt(resolved.settings, SETTING);
1549
- } catch (error) {
1550
- rethrowCleanup(error, operation?.signal);
1551
- return { invalid: `${SETTING} cannot be resolved: ${error instanceof Error ? error.message : String(error)}` };
1552
- }
1553
- if (value === void 0) return { hours: Number(setting.default) };
1554
- const error = settingValueError(setting, value);
1555
- return error || typeof value !== "number" ? { invalid: `${fromEnv ? setting.env : SETTING} is invalid: expected ${error ?? "a number"}` } : { hours: value };
1556
- }
1557
- function hostedFacts(root) {
1558
- const placements = [];
1559
- const unreadable = [];
1560
- for (const platform of ["ios", "android"]) for (const [slot, record] of Object.entries(hostedNativeRecords(readWorkspaceState$1(root), platform))) {
1561
- const placement = parseHostedNativePlacement(record, platform);
1562
- if (placement) {
1563
- const label = platform === "ios" ? "iOS simulator" : "Android emulator";
1564
- placements.push({
1565
- label,
1566
- machine: placement.machine,
1567
- session: placement.session,
1568
- platform
1433
+ const signal = operation?.signal;
1434
+ const run = await withIdleWorkspace(path, async () => {
1435
+ try {
1436
+ return await withWorkspaceProcessLock(workspaceDir(path), "metro-start", async () => {
1437
+ const active = await stillIdle();
1438
+ if (active) return kept$1(active);
1439
+ const stopped = await runStop({
1440
+ root: path,
1441
+ operation,
1442
+ report: () => {},
1443
+ requester: { by: `${by} (${action.reason})` },
1444
+ releaseLeases: () => []
1445
+ });
1446
+ return stopped.ok ? {
1447
+ status: "done",
1448
+ bytes: 0,
1449
+ detail: stopped.summary
1450
+ } : {
1451
+ status: "failed",
1452
+ bytes: 0,
1453
+ detail: stopped.summary
1454
+ };
1455
+ }, {
1456
+ external: true,
1457
+ waitMs: 0,
1458
+ ownerPurpose: "idle stop",
1459
+ signal,
1460
+ declareSpawnsFor: operation
1569
1461
  });
1570
- } else unreadable.push(unreadableHostedNative(slot, platform));
1571
- }
1572
- const host = readMacosRecord(root)?.host;
1573
- if (host) placements.push({
1574
- label: "macOS app",
1575
- machine: host.machine,
1576
- session: host.session
1462
+ } catch (error) {
1463
+ if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1464
+ signal?.throwIfAborted();
1465
+ if (workspaceProcessLockError(error)) return kept$1("a stim start holds its metro-start lock");
1466
+ throw error;
1467
+ }
1468
+ }, {
1469
+ purpose: "automatic maintenance",
1470
+ devServer: false,
1471
+ hosted: false,
1472
+ hostedMacos: false,
1473
+ operation
1577
1474
  });
1578
- return {
1579
- placements,
1580
- unreadable
1581
- };
1475
+ return run.ran ? run.value : kept$1(`in use: ${run.reasons.join("; ")}`);
1582
1476
  }
1583
- async function hostedKeepReasons(facts) {
1584
- const keep = [...facts.unreadable];
1585
- if (keep.length) return keep;
1586
- for (const { label, machine, session, platform } of facts.placements) {
1587
- const probe = await probeHostedSession({
1588
- machine,
1589
- session,
1590
- platform
1591
- }, { ttlMs: 0 });
1592
- if (probe.state === "ready" || probe.state === "stopped") continue;
1593
- const why = probe.state === "unreachable" ? `${machine} did not answer: ${probe.reason.replace(/\.+$/, "")}` : `${machine} cannot confirm it${probe.notice ? `: ${probe.notice.replace(/\.+$/, "")}` : ""}`;
1594
- keep.push(`its hosted ${label} session ${session} is not confirmed: ${why}`);
1595
- }
1596
- return keep;
1477
+ //#endregion
1478
+ //#region src/maintenance/activity.ts
1479
+ function readDeviceActivity(withSims, now) {
1480
+ const sims = withSims ? listAllIosSims({ timeoutMs: DEVICE_LIST_TIMEOUT_MS }) : [];
1481
+ return collectOwnedDeviceActivity(loadConfig$1(), sims, now);
1597
1482
  }
1598
- function deviceKeepReason(device, platform) {
1599
- const { activity } = device;
1600
- const what = `its ${device.kind === "ios" ? "simulator" : "emulator"} ${device.name}`;
1601
- if (activity.state === "driven" && !activity.basis.every((basis) => AGENT_DEVICE_DRIVERS.has(basis))) return `${what} is driven by ${activity.driver?.tool ?? "an unknown tool"}`;
1602
- if (activity.basis.includes("agent-device-claim") && !activity.recent?.["agent-action"]) return `${what} has a live agent-device claim whose session activity cannot be found`;
1603
- const probed = activity.state === "driven" ? activity.unknown ?? [] : activity.state === "unknown" ? activity.basis : [];
1604
- const unknown = platform === "win32" ? probed.filter((basis) => basis !== "driver-process") : probed;
1605
- if (unknown.length) return `${what} has unknown activity (${unknown.join(", ")})`;
1606
- return null;
1483
+ /** A reader that reads device activity at most once per kind and reuses the answer, including a failure. */
1484
+ function cachedDeviceActivity(now) {
1485
+ const answers = /* @__PURE__ */ new Map();
1486
+ return (withSims) => {
1487
+ let answer = answers.get(withSims);
1488
+ if (!answer) {
1489
+ try {
1490
+ answer = { devices: readDeviceActivity(withSims, now) };
1491
+ } catch (error) {
1492
+ answer = { error };
1493
+ }
1494
+ answers.set(withSims, answer);
1495
+ }
1496
+ if ("error" in answer) throw answer.error;
1497
+ return answer.devices;
1498
+ };
1607
1499
  }
1608
- function recentAt(activity, basis) {
1609
- return Date.parse(activity.recent?.[basis] ?? "");
1500
+ function cachedDeviceActivityAsync(now, env, signal, operation) {
1501
+ const answers = /* @__PURE__ */ new Map();
1502
+ return (withSims) => {
1503
+ let answer = answers.get(withSims);
1504
+ if (!answer) {
1505
+ answer = (async () => {
1506
+ signal?.throwIfAborted();
1507
+ const sims = withSims ? await listAllIosSimsAsync({
1508
+ timeoutMs: DEVICE_LIST_TIMEOUT_MS,
1509
+ signal,
1510
+ operation
1511
+ }) : [];
1512
+ return collectOwnedDeviceActivityAsync(loadConfig$1(), sims, now, env, signal, operation);
1513
+ })();
1514
+ answers.set(withSims, answer);
1515
+ }
1516
+ return answer;
1517
+ };
1610
1518
  }
1611
- const missing = (error) => error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR");
1612
- const message = (error) => error instanceof Error ? error.message : String(error);
1613
- function agentSessionsActedAt(root) {
1614
- const dir = join(workspaceAgentDeviceDir(root), "sessions");
1615
- let names;
1616
- try {
1617
- names = readdirSync(dir);
1618
- } catch (error) {
1619
- return missing(error) ? NaN : `its agent-device sessions cannot be read (${message(error)})`;
1620
- }
1621
- let latest = NaN;
1622
- for (const name of names) {
1623
- if (name === STIM_SESSION) continue;
1519
+ function* workspaceActiveChecks(root, now, windowMs) {
1520
+ if (workspaceBuildInProgress(root)) return "a build is in progress";
1521
+ const holder = canonicalPath(root);
1522
+ for (const { lease } of listLeaseFiles()) if (lease && !leaseIsExpired(lease, now) && canonicalPath(lease.holder) === holder) return `it holds the ${lease.platform} device lease on ${lease.deviceName ?? lease.id}`;
1523
+ const owned = ownedPlatforms(root);
1524
+ if (owned.ios || owned.android) {
1525
+ let devices;
1624
1526
  try {
1625
- const at = statSync(join(dir, name, "events.ndjson")).mtimeMs;
1626
- if (!(at <= latest)) latest = at;
1627
- } catch (error) {
1628
- if (!missing(error)) return `its agent-device session ${name} cannot be read (${message(error)})`;
1527
+ devices = yield owned.ios;
1528
+ } catch {
1529
+ return "its owned devices cannot be listed to prove them idle";
1629
1530
  }
1531
+ const busy = devices.find((device) => device.project === root && device.activity.state !== "idle");
1532
+ if (busy) return `its owned ${busy.kind} device ${busy.name} is ${busy.activity.state}`;
1630
1533
  }
1631
- return latest;
1534
+ const activity = workspaceActivity(root, now);
1535
+ if (activity.state !== "idle") return `its activity is ${activity.state}`;
1536
+ const known = [Date.parse(activity.lastActivityAt ?? ""), workspaceLastUsed(root)].filter(Number.isFinite);
1537
+ if (!known.length) return "its last activity is unknown";
1538
+ return now - Math.max(...known) < windowMs ? usedWithin(windowMs) : null;
1632
1539
  }
1633
- function metroRequestAt(root, since, serving) {
1634
- const file = join(workspaceLogsDir$1(root), "metro.ndjson");
1635
- const rotated = rotatedLogPath(file);
1636
- const records = [];
1637
- for (const path of [rotated, file]) try {
1638
- records.push(...parseNdjsonText(readFileSync(path, "utf8")));
1540
+ /** Why a workspace is not inactive for the pressure window, or null when maintenance may stop it. */
1541
+ function workspaceActiveReason(root, now, windowMs, devices = (withSims) => readDeviceActivity(withSims, now)) {
1542
+ const checks = workspaceActiveChecks(root, now, windowMs);
1543
+ let step = checks.next();
1544
+ while (!step.done) try {
1545
+ step = checks.next(devices(step.value));
1639
1546
  } catch (error) {
1640
- if (error instanceof Error && "code" in error && error.code === "ENOENT") continue;
1641
- return `its Metro log cannot be read (${error instanceof Error ? error.message : String(error)})`;
1642
- }
1643
- let latest = NaN;
1644
- let earliest = Infinity;
1645
- for (const record of records) {
1646
- if (typeof record.ts !== "number") continue;
1647
- earliest = Math.min(earliest, record.ts);
1648
- if (typeof record.event === "string" && METRO_REQUESTS.has(record.event) && !(record.ts <= latest)) latest = record.ts;
1547
+ step = checks.throw(error);
1649
1548
  }
1650
- if (!Number.isFinite(latest) && earliest > since && existsSync(rotated)) return `its rotated Metro log does not reach back ${SETTING}`;
1651
- if (serving && earliest === Infinity) return "its dev server runs but its Metro log is missing or empty";
1652
- return latest;
1549
+ return step.value;
1653
1550
  }
1654
- function unreadableViewers() {
1655
- const dir = deviceViewersDir();
1656
- let names;
1657
- try {
1658
- names = readdirSync(dir).filter((name) => name.endsWith(".json"));
1551
+ async function workspaceActiveReasonAsync(root, now, windowMs, devices, signal) {
1552
+ const checks = workspaceActiveChecks(root, now, windowMs);
1553
+ let step = checks.next();
1554
+ while (!step.done) try {
1555
+ signal?.throwIfAborted();
1556
+ step = checks.next(await devices(step.value));
1659
1557
  } catch (error) {
1660
- return missing(error) ? null : `the stim-server viewer records cannot be read (${message(error)})`;
1558
+ if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1559
+ signal?.throwIfAborted();
1560
+ step = checks.throw(error);
1661
1561
  }
1662
- for (const name of names) {
1663
- const record = readJsonObject(join(dir, name));
1664
- if (!record) return `the stim-server viewer record ${name} cannot be read`;
1665
- if ((0, process_identity_exports.inspectProcessIdentity)(record) === "unknown") return `the stim-server behind the viewer record ${name} cannot be verified`;
1562
+ return step.value;
1563
+ }
1564
+ function ownedPlatforms(root) {
1565
+ try {
1566
+ const slots = projectDeviceSlots(loadConfig$1()?.projects?.[root]);
1567
+ return {
1568
+ ios: slots.some(({ platforms }) => platforms.ios?.owned === true),
1569
+ android: slots.some(({ platforms }) => platforms.android?.owned === true)
1570
+ };
1571
+ } catch {
1572
+ return {
1573
+ ios: true,
1574
+ android: true
1575
+ };
1666
1576
  }
1667
- return null;
1668
1577
  }
1669
- async function keepReasons(root, devices, { now, platform, locked, operation }) {
1670
- const checks = {
1671
- devServer: false,
1672
- nativeRun: !locked,
1673
- hosted: false,
1674
- hostedMacos: false
1675
- };
1676
- const keep = operation ? await workspaceInUseAsync(root, checks, operation.signal, operation) : workspaceInUse(root, checks);
1677
- if (workspaceBuildInProgress(root)) keep.push("a build is in progress");
1678
- if (readRemoteSession(root)) keep.push("it has a remote device session");
1679
- const holder = canonicalPath(root);
1680
- for (const { lease, path } of listLeaseFiles()) if (!lease) keep.push(`the device lease ${path} cannot be read`);
1681
- else if (!leaseIsExpired(lease, now) && canonicalPath(lease.holder) === holder) keep.push(`it holds the ${lease.platform} device lease on ${lease.deviceName ?? lease.id}`);
1682
- const browser = webFacts(readWebRecord(root));
1683
- if (browser && browser.status !== "stopped") keep.push(`its owned Chrome is ${browser.status}`);
1684
- for (const device of devices) {
1685
- const reason = deviceKeepReason(device, platform);
1686
- if (reason) keep.push(reason);
1578
+ function hasOwnedDevices(root) {
1579
+ try {
1580
+ return projectDeviceSlots(loadConfig$1()?.projects?.[root]).some(({ platforms }) => platforms.ios?.owned === true || platforms.android?.owned === true);
1581
+ } catch {
1582
+ return false;
1687
1583
  }
1688
- const viewers = devices.length ? unreadableViewers() : null;
1689
- if (viewers) keep.push(viewers);
1690
- return keep;
1691
1584
  }
1692
- async function idleStopEvidence(root, devices, { now, idleMs, platform = process.platform, locked = false, serving = false, operation }) {
1693
- const state = readWorkspaceState$1(root);
1694
- if (!state && existsSync(workspaceStateFile$1(root))) return {
1695
- activity: [],
1696
- keep: ["its state.json cannot be read"]
1697
- };
1698
- const sessions = agentSessionsActedAt(root);
1699
- if (typeof sessions === "string") return {
1700
- activity: [],
1701
- keep: [sessions]
1702
- };
1703
- const build = state?.lastBuild;
1704
- const builtAt = Date.parse(String(build?.startedAt ?? "")) + (typeof build?.durationMs === "number" ? build.durationMs : 0);
1705
- const activity = [
1706
- {
1707
- basis: "stim command",
1708
- at: Date.parse(String(state?.lastUsedAt ?? ""))
1709
- },
1710
- {
1711
- basis: "native run",
1712
- at: builtAt
1713
- },
1714
- {
1715
- basis: "agent-device command",
1716
- at: typeof sessions === "number" ? sessions : NaN
1717
- },
1718
- ...devices.flatMap(({ activity: device }) => [{
1719
- basis: "agent-device command",
1720
- at: recentAt(device, "agent-action")
1721
- }, {
1722
- basis: "live view",
1723
- at: recentAt(device, "viewer")
1724
- }])
1725
- ].filter(({ at }) => Number.isFinite(at));
1726
- if (activity.some(({ at }) => now - at < idleMs)) return {
1727
- activity,
1728
- keep: []
1729
- };
1730
- const keep = await keepReasons(root, devices, {
1731
- now,
1732
- platform,
1733
- locked,
1734
- operation
1585
+ function usedWithin(windowMs) {
1586
+ return `used within the last ${Math.round(windowMs / 6e4)} minutes`;
1587
+ }
1588
+ //#endregion
1589
+ //#region src/maintenance/devices.ts
1590
+ const AVD_SIZE_TIMEOUT_MS = 3e4;
1591
+ /** The disk of each owned simulator or emulator of a registered workspace and of each parked device. */
1592
+ async function ownedDeviceUsage(failure, { sims = () => listAllIosSims({ timeoutMs: DEVICE_LIST_TIMEOUT_MS }), avds = () => listAvds({ timeoutMs: DEVICE_LIST_TIMEOUT_MS }), avdDirectory = ownedAvdDirectory, size = (dir) => measuredDirectorySizeAsync(dir, { timeoutMs: AVD_SIZE_TIMEOUT_MS }) } = {}) {
1593
+ const config = loadConfig$1();
1594
+ const owned = [];
1595
+ for (const [root, project] of Object.entries(config?.projects ?? {})) for (const { platforms } of projectDeviceSlots(project)) {
1596
+ if (platforms.ios?.owned && platforms.ios.deviceUdid) owned.push({
1597
+ kind: "ios",
1598
+ id: platforms.ios.deviceUdid,
1599
+ workspace: canonicalPath(root)
1600
+ });
1601
+ if (platforms.android?.owned && platforms.android.avdName) owned.push({
1602
+ kind: "android",
1603
+ id: platforms.android.avdName,
1604
+ workspace: canonicalPath(root)
1605
+ });
1606
+ }
1607
+ for (const record of readParked("ios", { config })) owned.push({
1608
+ kind: "ios",
1609
+ id: record.udid
1735
1610
  });
1736
- if (keep.length) return {
1737
- activity,
1738
- keep
1739
- };
1740
- const metro = metroRequestAt(root, now - idleMs, serving);
1741
- if (typeof metro === "string") return {
1742
- activity,
1743
- keep: [metro]
1744
- };
1745
- if (Number.isFinite(metro)) activity.push({
1746
- basis: "Metro request",
1747
- at: metro
1611
+ for (const record of readParked("android", { config })) owned.push({
1612
+ kind: "android",
1613
+ id: record.name
1748
1614
  });
1749
- if (!activity.some(({ at }) => now - at < idleMs)) keep.push(...await hostedKeepReasons(hostedFacts(root)));
1750
- return {
1751
- activity,
1752
- keep
1615
+ const listed = (read, label) => {
1616
+ if (!owned.length) return [];
1617
+ try {
1618
+ return read();
1619
+ } catch {
1620
+ failure(label);
1621
+ return null;
1622
+ }
1753
1623
  };
1754
- }
1755
- function rethrowCleanup(error, signal) {
1756
- if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1757
- signal?.throwIfAborted();
1758
- }
1759
- async function unseenEmulatorError(unseen, operation) {
1760
- try {
1761
- const signal = operation?.signal;
1762
- const adb = operation ? await listAdbDevicesAsync({
1763
- timeoutMs: 5e3,
1764
- signal,
1765
- operation
1766
- }) : listAdbDevices({ timeoutMs: 5e3 });
1767
- for (const { serial } of [...adb.emulators, ...adb.unhealthy.filter((entry) => entry.kind === "emulator")]) {
1768
- const name = operation ? await getAvdNameForSerialAsync(serial, {
1769
- timeoutMs: 5e3,
1770
- signal,
1771
- operation
1772
- }) : getAvdNameForSerial(serial, { timeoutMs: 5e3 });
1773
- if (name === null) return `its emulators cannot be identified to prove them idle (${serial} gave no AVD name)`;
1774
- if (unseen.includes(name)) return `its emulator ${name} runs as ${serial}, but its activity could not be read`;
1624
+ const iosRecords = owned.some((device) => device.kind === "ios") ? listed(sims, "the simulator list") : [];
1625
+ const avdNames = owned.some((device) => device.kind === "android") ? listed(avds, "the emulator list") : [];
1626
+ const usage = [];
1627
+ for (const device of owned) {
1628
+ const workspace = device.workspace ? { workspace: device.workspace } : {};
1629
+ if (device.kind === "ios") {
1630
+ const sim = iosRecords?.find((record) => record.udid === device.id);
1631
+ if (sim && typeof sim.dataPathSize === "number") usage.push({
1632
+ kind: "ios",
1633
+ name: sim.name,
1634
+ dir: sim.dataPath ?? device.id,
1635
+ bytes: sim.dataPathSize,
1636
+ ...workspace
1637
+ });
1638
+ continue;
1775
1639
  }
1776
- return null;
1777
- } catch (error) {
1778
- rethrowCleanup(error, operation?.signal);
1779
- return `its emulators cannot be listed to prove them idle (${error instanceof Error ? error.message : String(error)})`;
1640
+ const dir = avdNames?.includes(device.id) ? avdDirectory(device.id) : null;
1641
+ if (!dir) continue;
1642
+ const bytes = await size(dir);
1643
+ if (bytes === null) failure(dir, device.workspace);
1644
+ else usage.push({
1645
+ kind: "android",
1646
+ name: device.id,
1647
+ dir,
1648
+ bytes,
1649
+ ...workspace
1650
+ });
1780
1651
  }
1652
+ return usage;
1781
1653
  }
1782
- function survivingServer(recorded) {
1783
- const pid = recorded?.serverPid;
1784
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return null;
1785
- const token = recorded?.serverProcessToken;
1786
- return (typeof token === "string" ? ["same", "unknown"].includes((0, process_identity_exports.inspectProcessIdentity)({
1787
- pid,
1788
- processToken: token
1789
- })) : pidExists(pid)) ? `its dev server (pid ${pid}) may still run after its supervisor exited; stim stop ends it` : null;
1790
- }
1791
- async function candidate(path, env, devices, operation) {
1792
- const signal = operation?.signal;
1793
- const project = loadConfig$1()?.projects?.[path];
1794
- if (!project) return null;
1795
- const supervisor = resolveSupervisorTarget({
1796
- state: readWorkspaceState$1(path)?.supervisor,
1797
- record: project.supervisor,
1798
- reservedPort: project.metroPort
1654
+ async function measureOwnedDevices(now, failure) {
1655
+ return (await ownedDeviceUsage(failure)).map(({ kind, name, dir, bytes, workspace }) => {
1656
+ const size = {
1657
+ name: `${workspace ? "owned" : "parked"} ${kind === "ios" ? "simulator" : "emulator"} ${name}`,
1658
+ category: "owned-devices",
1659
+ dir,
1660
+ bytes,
1661
+ measuredAt: now
1662
+ };
1663
+ if (workspace) size.workspace = workspace;
1664
+ return size;
1799
1665
  });
1800
- const slots = projectDeviceSlots(project);
1801
- const ownsIos = slots.some(({ platforms }) => platforms.ios?.owned === true);
1802
- const owns = ownsIos || slots.some(({ platforms }) => platforms.android?.owned === true);
1803
- const hosted = hostedFacts(path);
1804
- const isHosted = hosted.placements.length > 0 || hosted.unreadable.length > 0;
1805
- if (!owns && !isHosted && (supervisor.status === "none" || supervisor.status === "stale")) return null;
1806
- const setting = await idleStopHours(path, env, operation);
1807
- if ("invalid" in setting) return { skip: setting.invalid };
1808
- if (setting.hours === 0) return null;
1809
- let booted = [];
1810
- if (owns) try {
1811
- booted = (await devices(ownsIos)).filter((device) => device.project === path);
1812
- } catch (error) {
1813
- rethrowCleanup(error, signal);
1814
- return supervisor.status === "none" || supervisor.status === "stale" ? null : { skip: "its owned devices cannot be listed to prove them idle" };
1815
- }
1816
- if (supervisor.status === "unverified") return { skip: `its dev server supervisor cannot be verified: ${supervisor.reason ?? "unknown identity"}` };
1817
- if (supervisor.status === "ours" && readWorkspaceState$1(path)?.supervisor?.mode === "command-child") return { skip: "its dev server runs metro.command, whose bundle and HMR requests Stim cannot see" };
1818
- if (supervisor.status === "ours" && readWorkspaceState$1(path)?.supervisor?.hmrUpdates !== true) return { skip: "its dev server does not report HMR updates to Stim: an Expo SDK before 54, or a server an older Stim started, which stim stop and stim start restart" };
1819
- const avdNames = slots.flatMap(({ platforms }) => platforms.android?.owned && platforms.android.avdName ? [platforms.android.avdName] : []);
1820
- if (supervisor.status !== "ours" && booted.length === 0 && !isHosted) return null;
1821
- const orphan = supervisor.status === "stale" ? survivingServer(readWorkspaceState$1(path)?.supervisor) : null;
1822
- if (orphan) return { skip: orphan };
1823
- const seen = new Set(booted.flatMap((device) => device.kind === "android" ? [device.id] : []));
1824
- const unseen = avdNames.filter((name) => !seen.has(name));
1825
- const emulators = unseen.length ? await unseenEmulatorError(unseen, operation) : null;
1826
- if (emulators) return { skip: emulators };
1827
- return {
1828
- path,
1829
- hours: setting.hours,
1830
- serving: supervisor.status === "ours",
1831
- devices: booted
1832
- };
1833
1666
  }
1834
- /**
1835
- * Plans stopping each workspace, other than `protectedRoot`, whose dev server runs or whose owned simulator or
1836
- * emulator is booted, once it has had no real activity for its maintenance.idleStopHours.
1837
- */
1838
- async function planIdleStop({ protectedRoot, now, devices, env = process.env, platform = process.platform, operation }) {
1667
+ function* deviceDeletionChecks({ roots, windowMs, reason, protectedRoot, pinned, sizes, now, extra, env = process.env }) {
1839
1668
  const plan = {
1840
1669
  actions: [],
1841
1670
  blocked: [],
1842
1671
  skips: []
1843
1672
  };
1844
1673
  if (deviceSweepIsScoped(env)) return plan;
1845
- for (const path of Object.keys(loadConfig$1()?.projects ?? {})) {
1846
- const root = canonicalPath(path);
1847
- if (root === protectedRoot) continue;
1848
- operation?.signal.throwIfAborted();
1849
- const found = await candidate(path, env, devices, operation);
1850
- if (!found) continue;
1851
- if ("skip" in found) {
1674
+ for (const entry of roots) {
1675
+ const root = canonicalPath(entry.root);
1676
+ if (root === protectedRoot || !hasOwnedDevices(root)) continue;
1677
+ const kept = pinned(root) ? "pinned by maintenance.keep" : now - workspaceLastUsed(root) < windowMs ? usedWithin(windowMs) : workspaceInUse(root).map((why) => `in use: ${why}`)[0] ?? (yield root);
1678
+ if (kept) {
1852
1679
  plan.skips.push({
1853
1680
  target: root,
1854
- reason: found.skip,
1681
+ reason: kept,
1855
1682
  workspace: root
1856
1683
  });
1857
1684
  continue;
1858
1685
  }
1859
- const idleMs = found.hours * HOUR_MS;
1860
- const decision = decideIdleStop(await idleStopEvidence(path, found.devices, {
1861
- now,
1862
- idleMs,
1863
- platform,
1864
- serving: found.serving,
1865
- operation
1866
- }), {
1867
- idleMs,
1868
- now
1686
+ plan.actions.push({
1687
+ kind: "would-delete-devices",
1688
+ target: root,
1689
+ workspace: root,
1690
+ bytes: sizes.filter((size) => size.category === "owned-devices" && size.workspace === root).reduce((sum, size) => sum + size.bytes, 0),
1691
+ reason: entry.reason ? `${entry.reason}, ${reason}` : reason,
1692
+ ...extra
1693
+ });
1694
+ }
1695
+ return plan;
1696
+ }
1697
+ function planDeviceDeletion(options) {
1698
+ const activity = cachedDeviceActivity(options.now);
1699
+ const checks = deviceDeletionChecks(options);
1700
+ let step = checks.next();
1701
+ while (!step.done) step = checks.next(workspaceActiveReason(step.value, options.now, options.windowMs, activity));
1702
+ return step.value;
1703
+ }
1704
+ async function planDeviceDeletionAsync(options, signal, operation) {
1705
+ const activity = cachedDeviceActivityAsync(options.now, options.env ?? process.env, signal, operation);
1706
+ const checks = deviceDeletionChecks(options);
1707
+ let step = checks.next();
1708
+ while (!step.done) {
1709
+ signal.throwIfAborted();
1710
+ step = checks.next(await workspaceActiveReasonAsync(step.value, options.now, options.windowMs, activity, signal));
1711
+ }
1712
+ return step.value;
1713
+ }
1714
+ /**
1715
+ * The workspaces of linked worktrees that gc keeps although their branch is merged or their pull request ended,
1716
+ * such as a dirty one. A worktree gc removes takes its devices with it.
1717
+ */
1718
+ function finishedWorkspaces(sweep, now) {
1719
+ const kept = /* @__PURE__ */ new Set([
1720
+ "not-a-worktree",
1721
+ "bare-repository",
1722
+ "source-checkout",
1723
+ "source-checkout-unknown",
1724
+ "not-registered",
1725
+ "locked",
1726
+ "nested-worktree",
1727
+ "recent-activity",
1728
+ "activity-unknown"
1729
+ ]);
1730
+ if (!sweep) return [];
1731
+ return sweep.worktrees.flatMap((worktree) => {
1732
+ if (worktree.skipped === null || kept.has(worktree.skipCode ?? "")) return [];
1733
+ const merged = worktree.merge?.merged ? worktree.merge.mergedAt : null;
1734
+ const ended = endedPullRequest(worktree.pullRequest);
1735
+ if (merged === null && !ended) return [];
1736
+ if (now - Math.max(merged ?? -Infinity, ended ? ended.endedAt ?? now : -Infinity) < sweep.graceMs) return [];
1737
+ const reason = `its worktree is finished (${worktreeRemovalReason(worktree, sweep)}) but kept`;
1738
+ return worktree.keys.map((root) => ({
1739
+ root: canonicalPath(root),
1740
+ reason
1741
+ }));
1742
+ });
1743
+ }
1744
+ /** Each workspace's effective devices.idleShutdownMinutes, or 0 when it cannot be resolved. */
1745
+ function idleShutdownMinutes(root) {
1746
+ try {
1747
+ return deviceIdleShutdownMinutesSetting(resolveProjectSettings(root).settings);
1748
+ } catch {
1749
+ return 0;
1750
+ }
1751
+ }
1752
+ /**
1753
+ * Whether the workspace's dev server is gone, by the supervisor identity check `status` uses. A supervisor whose
1754
+ * identity cannot be verified, or one that exited while the dev server it started may still run, counts as running.
1755
+ */
1756
+ function metroGone(root) {
1757
+ const project = getProject(root);
1758
+ const state = readWorkspaceState$1(root);
1759
+ const { status } = resolveSupervisorTarget({
1760
+ state: state?.supervisor,
1761
+ record: project?.supervisor,
1762
+ reservedPort: project?.metroPort
1763
+ });
1764
+ return status === "none" || status === "stale" && survivingServer(state?.supervisor) === null;
1765
+ }
1766
+ /**
1767
+ * Plans shutting down each booted owned simulator and emulator idle for its workspace's devices.idleShutdownMinutes,
1768
+ * whether or not a supervisor runs there. Without a supervisor, the device logs of a slot whose last launch needs
1769
+ * Metro do not count as use. The devices are shut down, never deleted.
1770
+ */
1771
+ function planIdleShutdown({ protectedRoot, now, env = process.env }) {
1772
+ const plan = {
1773
+ actions: [],
1774
+ blocked: [],
1775
+ skips: []
1776
+ };
1777
+ if (deviceSweepIsScoped(env)) return plan;
1778
+ const minutes = new Map(Object.entries(loadConfig$1()?.projects ?? {}).flatMap(([root, project]) => {
1779
+ const value = !projectDeviceSlots(project).some(({ platforms }) => platforms.ios?.owned === true || platforms.android?.owned === true) || canonicalPath(root) === protectedRoot ? 0 : idleShutdownMinutes(root);
1780
+ return value > 0 ? [[root, value]] : [];
1781
+ }));
1782
+ if (minutes.size === 0) return plan;
1783
+ const window = Math.min(...minutes.values()) * 6e4;
1784
+ const gone = new Map([...minutes.keys()].map((root) => [root, metroGone(root)]));
1785
+ const metroStopped = (root) => gone.get(root) ?? false;
1786
+ for (const { device, idleForMs } of dueIdleDevices(void 0, window, now, { metroStopped })) {
1787
+ const own = minutes.get(device.project);
1788
+ const usedAt = workspaceDeviceLastUseAt(device.project, { countDeviceLogs: !metroStopped(device.project) });
1789
+ if (own === void 0 || idleForMs < own * 6e4 || now - usedAt < own * 6e4) continue;
1790
+ const root = canonicalPath(device.project);
1791
+ plan.actions.push({
1792
+ kind: "would-shutdown-device",
1793
+ target: device.id,
1794
+ workspace: root,
1795
+ bytes: 0,
1796
+ reason: `${device.kind === "ios" ? "simulator" : "emulator"} ${device.name} idle ${formatLongDuration(idleForMs)}, over devices.idleShutdownMinutes ${own}`
1797
+ });
1798
+ }
1799
+ return plan;
1800
+ }
1801
+ //#endregion
1802
+ //#region src/maintenance/sweep.ts
1803
+ async function planSweep({ settings, sizes, protectedRoot, pinned, now, devices = true, operation }) {
1804
+ const actions = [];
1805
+ const skips = [];
1806
+ const blocked = [];
1807
+ const days = settings.olderThanDays;
1808
+ const outputs = days > 0 ? await collectWorkspaceOutputs({
1809
+ olderThan: days,
1810
+ now,
1811
+ measure: false,
1812
+ signal: operation?.signal,
1813
+ operation
1814
+ }) : { workspaces: [] };
1815
+ for (const entry of outputs.workspaces) {
1816
+ const root = entry.projectRoot === null ? null : canonicalPath(entry.projectRoot);
1817
+ if (root !== null && keptByLock(entry) && entry.keptReason) skips.push({
1818
+ target: root,
1819
+ reason: entry.keptReason,
1820
+ workspace: root
1869
1821
  });
1870
- if (!decision.stop) {
1871
- if (!decision.active) plan.skips.push({
1822
+ if (root === null || !entry.willClear || root === protectedRoot) continue;
1823
+ if (pinned(root)) {
1824
+ skips.push({
1872
1825
  target: root,
1873
- reason: decision.reason,
1826
+ reason: "pinned by maintenance.keep",
1874
1827
  workspace: root
1875
1828
  });
1876
1829
  continue;
1877
1830
  }
1878
- plan.actions.push({
1879
- kind: "would-stop-workspace",
1880
- check: "idle",
1831
+ const size = sizes.find((candidate) => candidate.workspace === root && candidate.category === "workspace-outputs");
1832
+ actions.push({
1833
+ kind: "would-clear-outputs",
1881
1834
  target: root,
1882
1835
  workspace: root,
1883
- bytes: 0,
1884
- reason: `no real activity for ${formatLongDuration(decision.idleMs)}, over ${SETTING} ${found.hours}`
1836
+ bytes: size?.bytes ?? 0,
1837
+ olderThanDays: days,
1838
+ reason: `idle ${entry.idleDays} days, older than ${days} days (age sweep)`,
1839
+ check: "sweep"
1885
1840
  });
1886
1841
  }
1887
- return plan;
1888
- }
1889
- const kept$1 = (detail) => ({
1890
- status: "kept",
1891
- bytes: 0,
1892
- detail
1893
- });
1894
- /**
1895
- * Stops a planned idle workspace the way `stim stop` does, under its native-run and metro-start locks, after
1896
- * deciding again that it is still idle. Physical-device leases stay.
1897
- */
1898
- async function stopIdleWorkspace(action, { protectedRoot, devices, operation, env = operation?.env ?? process.env, by = "automatic maintenance" }) {
1899
- const root = action.workspace ?? action.target;
1900
- if (root === protectedRoot) return kept$1("the command that started this pass runs in it");
1901
- if (deviceSweepIsScoped(env)) return kept$1("STIM_HOME scopes this config, and devices are machine-wide");
1902
- const path = Object.keys(loadConfig$1()?.projects ?? {}).find((entry) => canonicalPath(entry) === root) ?? root;
1903
- const stillIdle = async () => {
1904
- const now = Date.now();
1905
- const found = await candidate(path, env, devices(), operation);
1906
- if (!found) return "nothing of it runs any more";
1907
- if ("skip" in found) return found.skip;
1908
- const idleMs = found.hours * HOUR_MS;
1909
- const decision = decideIdleStop(await idleStopEvidence(path, found.devices, {
1910
- now,
1911
- idleMs,
1912
- locked: true,
1913
- serving: found.serving,
1842
+ for (const cache of days > 0 ? trimmableCaches(operation?.env, operation?.cwd).filter((candidate) => !isInsideWorkspaces(candidate.dir)) : []) actions.push({
1843
+ kind: "would-trim-cache",
1844
+ target: cacheLabel(cache),
1845
+ dir: cache.dir,
1846
+ bytes: 0,
1847
+ olderThanDays: days,
1848
+ reason: `entries unused for ${days} days (age sweep)`,
1849
+ check: "sweep"
1850
+ });
1851
+ try {
1852
+ const orphans = await collectOrphanedWorkspaces(Object.keys(loadConfig$1()?.projects ?? {}), listMountedVolumes(), {
1853
+ measure: false,
1914
1854
  operation
1915
- }), {
1916
- idleMs,
1917
- now
1918
1855
  });
1919
- return decision.stop ? null : decision.reason;
1856
+ for (const orphan of orphans.orphaned) actions.push({
1857
+ kind: "would-remove-orphan",
1858
+ target: orphan.dir,
1859
+ bytes: orphan.bytes ?? 0,
1860
+ reason: orphan.projectRoot === null ? "it is empty and has no workspace.json" : `its project ${orphan.projectRoot} no longer exists`,
1861
+ check: "sweep"
1862
+ });
1863
+ for (const kept of orphans.skipped) skips.push({
1864
+ target: kept.dir,
1865
+ reason: kept.reason
1866
+ });
1867
+ } catch (error) {
1868
+ if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1869
+ operation?.signal.throwIfAborted();
1870
+ blocked.push(`Could not look for orphaned workspace directories: ${error instanceof Error ? error.message : error}`);
1871
+ }
1872
+ if (devices && settings.deviceIdleDays > 0) {
1873
+ const options = {
1874
+ roots: Object.keys(loadConfig$1()?.projects ?? {}).map((root) => ({ root })),
1875
+ windowMs: settings.deviceIdleDays * 864e5,
1876
+ reason: `idle for ${settings.deviceIdleDays} days (age sweep)`,
1877
+ protectedRoot,
1878
+ pinned,
1879
+ sizes,
1880
+ now,
1881
+ extra: {
1882
+ check: "sweep",
1883
+ olderThanDays: settings.deviceIdleDays
1884
+ },
1885
+ env: operation?.env
1886
+ };
1887
+ const reaped = operation ? await planDeviceDeletionAsync(options, operation.signal, operation) : planDeviceDeletion(options);
1888
+ actions.push(...reaped.actions);
1889
+ skips.push(...reaped.skips);
1890
+ }
1891
+ if (devices && days > 0 && !deviceSweepIsScoped(operation?.env ?? process.env)) for (const kind of ["ios", "android"]) for (const record of readParked(kind)) {
1892
+ const parkedDays = Math.floor((now - Date.parse(record.parkedAt)) / 864e5);
1893
+ if (!(parkedDays >= days)) continue;
1894
+ const label = `parked ${kind === "ios" ? "simulator" : "emulator"} ${record.name}`;
1895
+ actions.push({
1896
+ kind: "would-delete-parked-device",
1897
+ target: kind === "ios" ? record.udid : record.name,
1898
+ bytes: sizes.find((size) => size.category === "owned-devices" && !size.workspace && size.name === label)?.bytes ?? 0,
1899
+ olderThanDays: days,
1900
+ reason: `${label} unused for ${parkedDays} days, older than ${days} days (age sweep)`,
1901
+ check: "sweep"
1902
+ });
1903
+ }
1904
+ const mounted = listMountedVolumes();
1905
+ for (const cache of readManifest().caches) {
1906
+ if (!isAbsolute(cache.dir) || existsSync(cache.dir) || !isOnMountedVolume(cache.dir, mounted)) continue;
1907
+ actions.push({
1908
+ kind: "would-unregister-cache",
1909
+ target: cache.dir,
1910
+ dir: cache.dir,
1911
+ bytes: 0,
1912
+ reason: "its directory no longer exists",
1913
+ check: "sweep"
1914
+ });
1915
+ }
1916
+ return {
1917
+ actions,
1918
+ blocked,
1919
+ skips
1920
1920
  };
1921
- const signal = operation?.signal;
1922
- const run = await withIdleWorkspace(path, async () => {
1923
- try {
1924
- return await withWorkspaceProcessLock(workspaceDir(path), "metro-start", async () => {
1925
- const active = await stillIdle();
1926
- if (active) return kept$1(active);
1927
- const stopped = await runStop({
1928
- root: path,
1929
- operation,
1930
- report: () => {},
1931
- requester: { by: `${by} (${action.reason})` },
1932
- releaseLeases: () => []
1933
- });
1934
- return stopped.ok ? {
1935
- status: "done",
1936
- bytes: 0,
1937
- detail: stopped.summary
1938
- } : {
1939
- status: "failed",
1940
- bytes: 0,
1941
- detail: stopped.summary
1942
- };
1943
- }, {
1944
- external: true,
1945
- waitMs: 0,
1946
- ownerPurpose: "idle stop",
1947
- signal,
1948
- declareSpawnsFor: operation
1921
+ }
1922
+ async function planWorktrees({ protectedRoot, pinned, now, level, graceMs, sizes, protectRecentMs = 0, refresh, idleDays = null, operation }) {
1923
+ const sweep = await collectWorktreeSweep({
1924
+ idle: idleDays !== null,
1925
+ olderThan: idleDays,
1926
+ now,
1927
+ underPressure: level === 3,
1928
+ operation,
1929
+ ...graceMs === void 0 ? {} : { graceMs },
1930
+ ...refresh === void 0 ? {} : { refresh }
1931
+ });
1932
+ const actions = [];
1933
+ const skips = [];
1934
+ const keep = [];
1935
+ for (const worktree of sweep.worktrees) {
1936
+ if (worktree.skipped) continue;
1937
+ const path = canonicalPath(worktree.path);
1938
+ const reason = protectedRoot === path || protectedRoot.startsWith(`${path}${sep}`) ? "the command that started this pass runs inside it" : worktree.keys.some(pinned) ? "pinned by maintenance.keep" : null;
1939
+ if (reason) {
1940
+ skips.push({
1941
+ target: worktree.path,
1942
+ reason
1949
1943
  });
1950
- } catch (error) {
1951
- if (error instanceof WorkspaceProcessCleanupError || error instanceof Error && "reportCleanup" in error) throw error;
1952
- signal?.throwIfAborted();
1953
- if (workspaceProcessLockError(error)) return kept$1("a stim start holds its metro-start lock");
1954
- throw error;
1944
+ continue;
1955
1945
  }
1956
- }, {
1957
- purpose: "automatic maintenance",
1958
- devServer: false,
1959
- hosted: false,
1960
- hostedMacos: false,
1961
- operation
1962
- });
1963
- return run.ran ? run.value : kept$1(`in use: ${run.reasons.join("; ")}`);
1946
+ keep.push(worktree);
1947
+ actions.push({
1948
+ kind: "would-remove-worktree",
1949
+ target: worktree.path,
1950
+ bytes: 0,
1951
+ reason: worktreeRemovalReason(worktree, sweep),
1952
+ check: level === void 0 && idleDays !== null && !worktree.merge?.merged && !endedPullRequest(worktree.pullRequest) ? "sweep" : "worktree",
1953
+ ...level ? { level } : {}
1954
+ });
1955
+ }
1956
+ if (sizes) {
1957
+ const options = {
1958
+ roots: finishedWorkspaces(sweep, now),
1959
+ windowMs: Math.max(sweep.graceMs, protectRecentMs),
1960
+ reason: "finished-worktree check",
1961
+ protectedRoot,
1962
+ pinned,
1963
+ sizes,
1964
+ now,
1965
+ extra: { check: "worktree" },
1966
+ env: operation?.env
1967
+ };
1968
+ const devices = operation ? await planDeviceDeletionAsync(options, operation.signal, operation) : planDeviceDeletion(options);
1969
+ actions.push(...devices.actions);
1970
+ skips.push(...devices.skips);
1971
+ }
1972
+ return {
1973
+ actions,
1974
+ blocked: [],
1975
+ skips,
1976
+ sweep: {
1977
+ ...sweep,
1978
+ worktrees: keep
1979
+ }
1980
+ };
1964
1981
  }
1965
1982
  //#endregion
1966
1983
  //#region src/workspace/running-from.ts
@@ -2096,9 +2113,14 @@ function pathExists(path) {
2096
2113
  return false;
2097
2114
  }
2098
2115
  }
2116
+ function scopedRoots(roots, env) {
2117
+ if (!deviceSweepIsScoped(env)) return roots;
2118
+ const registry = new Set(listedRoots());
2119
+ return roots.filter((root) => registry.has(root));
2120
+ }
2099
2121
  function artifactWorktrees() {
2100
2122
  const found = /* @__PURE__ */ new Map();
2101
- for (const root of candidateRoots()) {
2123
+ for (const root of scopedRoots(candidateRoots())) {
2102
2124
  const entry = artifactWorktree(root, listWorktrees(root));
2103
2125
  if (entry) found.set(entry.path, entry);
2104
2126
  }
@@ -2117,7 +2139,7 @@ function artifactWorktree(root, entries, source = sourceCheckoutOf(entries)) {
2117
2139
  }
2118
2140
  async function artifactWorktreesAsync(signal, operation) {
2119
2141
  const found = /* @__PURE__ */ new Map();
2120
- for (const root of await candidateRootsAsync(operation)) {
2142
+ for (const root of scopedRoots(await candidateRootsAsync(operation), operation?.env)) {
2121
2143
  signal.throwIfAborted();
2122
2144
  const { entries, ...source } = await resolveSourceCheckoutAsync(root, {
2123
2145
  env: operation?.env,
@@ -2868,6 +2890,40 @@ async function planGradleDaemonStop(blockers, operation) {
2868
2890
  }
2869
2891
  return { pids: [...blockers] };
2870
2892
  }
2893
+ function daemonsKept(reason) {
2894
+ return {
2895
+ actions: [],
2896
+ blocked: [],
2897
+ skips: [{
2898
+ target: "Gradle daemons",
2899
+ reason
2900
+ }]
2901
+ };
2902
+ }
2903
+ async function planMemoryDaemonStop(operation) {
2904
+ if (memorySweepIsScoped(operation?.env ?? process.env)) return daemonsKept("STIM_HOME scopes this config, so the machine-global Gradle daemons are not stopped");
2905
+ const building = runningBuild(listBuildLocks(), listBuildSlots());
2906
+ if (building) return daemonsKept(building);
2907
+ const pids = (await collectMemoryReport({
2908
+ watchman: false,
2909
+ gradle: true
2910
+ }, false, operation)).processes.filter((entry) => entry.reclaimable && (entry.kind === "gradleDaemon" || entry.kind === "kotlinDaemon")).map((entry) => entry.pid);
2911
+ if (pids.length === 0) return {
2912
+ actions: [],
2913
+ blocked: [],
2914
+ skips: []
2915
+ };
2916
+ return {
2917
+ actions: [{
2918
+ kind: "would-stop-gradle-daemons",
2919
+ target: `pid ${pids.join(", ")}`,
2920
+ bytes: 0,
2921
+ reason: "memory pressure, these Gradle and Kotlin daemons are idle"
2922
+ }],
2923
+ blocked: [],
2924
+ skips: []
2925
+ };
2926
+ }
2871
2927
  async function planLevel3({ settings, sizes, protectedRoot, pinned, now, refresh, operation }) {
2872
2928
  const windowMs = settings.pressureProtectMinutes * 6e4;
2873
2929
  const actions = [];
@@ -3131,6 +3187,11 @@ async function plannedMaintenance(pressure, recordedSizes, settings, { devices =
3131
3187
  });
3132
3188
  merge(pressured);
3133
3189
  if (pressured.pressureSweep) result.pressureSweep = pressured.pressureSweep;
3190
+ if (pressure.memory.pressured && settings.memoryPressureLevel !== "off") {
3191
+ const memory = await planMemoryDaemonStop(operation);
3192
+ if (memory.actions.length) result.actions = result.actions.filter((action) => action.kind !== "would-stop-gradle-daemons");
3193
+ merge(memory);
3194
+ }
3134
3195
  }
3135
3196
  if (low) result.skips.push(...outputs.workspaces.filter((entry) => !entry.willClear && entry.keptReason).map((entry) => ({
3136
3197
  target: entry.dir,
@@ -3282,8 +3343,10 @@ function trimCache(action, context) {
3282
3343
  };
3283
3344
  }
3284
3345
  async function emptyCompilationCache(action, context) {
3285
- const floor = action.level === 3 ? levelFloors(context.budget, context.settings)[3] : context.budget.hardFloorDiskMb;
3286
- if (!measureDisk().some((disk) => disk.freeMb < floor)) return kept(action.level === 3 ? "free disk is back above the level 3 floor, and this cache can only be emptied whole" : "free disk is above budget.hardFloorDiskGb, and this cache can only be emptied whole");
3346
+ if (action.level === 3) {
3347
+ const floor = levelFloors(context.budget, context.settings)[3];
3348
+ if (!measureDisk().some((disk) => disk.freeMb < floor)) return kept("free disk is back above the level 3 floor, and this cache can only be emptied whole");
3349
+ }
3287
3350
  const dir = sharedCompilationCache();
3288
3351
  const blocked = cacheBlocked({
3289
3352
  name: "Swift compilation cache",
@@ -3360,7 +3423,7 @@ async function shutDownIdleDevice(action) {
3360
3423
  const minutes = idleShutdownMinutes(root);
3361
3424
  if (minutes === 0) return kept("devices.idleShutdownMinutes is 0 for this workspace");
3362
3425
  const idleMs = minutes * 6e4;
3363
- const due = dueIdleDevices(root, idleMs).find(({ device }) => device.id === action.target);
3426
+ const due = dueIdleDevices(root, idleMs, Date.now(), { metroStopped: metroGone }).find(({ device }) => device.id === action.target);
3364
3427
  if (!due) return kept(`it is no longer idle for ${minutes} minutes`);
3365
3428
  const failures = [];
3366
3429
  const skips = [];
@@ -3368,7 +3431,10 @@ async function shutDownIdleDevice(action) {
3368
3431
  writeIdleShutdownEvent(root, event);
3369
3432
  if (event.event === "device_idle_shutdown_failed") (event.skipped ? skips : failures).push(event.msg);
3370
3433
  };
3371
- const run = await withIdleWorkspace(root, () => shutDownIdleDevices(root, idleMs, log, Date.now(), { only: due.device }), {
3434
+ const run = await withIdleWorkspace(root, () => shutDownIdleDevices(root, idleMs, log, Date.now(), {
3435
+ only: due.device,
3436
+ metroStopped: metroGone
3437
+ }), {
3372
3438
  purpose: "automatic maintenance idle shutdown",
3373
3439
  supervisor: false,
3374
3440
  managedLocks: false
@@ -3626,4 +3692,4 @@ function diskRecovered(budget) {
3626
3692
  return measureDisk().every((disk) => disk.freeMb >= floor);
3627
3693
  }
3628
3694
  //#endregion
3629
- export { candidateRootsAsync as C, worktreeRemovalReason as D, worktreePullRequestNote as E, maintenancePinned as S, removeWorktrees as T, finishedWorkspaces as _, previewMaintenance as a, cachedDeviceActivity as b, deleteTempLeftovers as c, appRoots as d, artifactWorktrees as f, stopIdleWorkspace as g, planIdleStop as h, plannedMaintenance as i, tempLeftoverLines as l, collectArtifactsAsync as m, diskRecovered as n, triggeringRoot as o, clearArtifact as p, executeAction as r, collectTempLeftovers as s, deleteIdleWorkspaceDevices as t, tempLeftoverSection as u, measureOwnedDevices as v, collectWorktreeSweep as w, cachedDeviceActivityAsync as x, ownedDeviceUsage as y };
3695
+ export { candidateRootsAsync as C, worktreeRemovalReason as D, worktreePullRequestNote as E, maintenancePinned as S, removeWorktrees as T, ownedDeviceUsage as _, previewMaintenance as a, planIdleStop as b, deleteTempLeftovers as c, appRoots as d, artifactWorktrees as f, measureOwnedDevices as g, finishedWorkspaces as h, plannedMaintenance as i, tempLeftoverLines as l, collectArtifactsAsync as m, diskRecovered as n, triggeringRoot as o, clearArtifact as p, executeAction as r, collectTempLeftovers as s, deleteIdleWorkspaceDevices as t, tempLeftoverSection as u, cachedDeviceActivity as v, collectWorktreeSweep as w, stopIdleWorkspace as x, cachedDeviceActivityAsync as y };