stim 1.17.2 → 1.19.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 (162) hide show
  1. package/README.md +50 -1
  2. package/dist/{activity-IRvJY_ru.mjs → activity-BSw0x84R.mjs} +4 -4
  3. package/dist/{agent-device-usage-output-BK41vnzN.mjs → agent-device-usage-output-Bjxu_VmX.mjs} +8 -8
  4. package/dist/{android-B9yaNKwa.mjs → android-BXc6BmEi.mjs} +658 -404
  5. package/dist/{android-B_YNZy61.mjs → android-BdQC6zs1.mjs} +9 -9
  6. package/dist/android-BvV1gGdN.mjs +4 -0
  7. package/dist/{android-DE4v59Mb.mjs → android-DE5g_5gv.mjs} +2 -2
  8. package/dist/{android-cas-ZFpjJBL_.mjs → android-cas-C87geAg-.mjs} +5 -5
  9. package/dist/android-cas-compiler.mjs +2 -2
  10. package/dist/api-DIf_s86s.mjs +150 -0
  11. package/dist/api-run.d.mts +1 -0
  12. package/dist/api-run.mjs +145 -0
  13. package/dist/api.d.mts +218 -0
  14. package/dist/api.mjs +2 -0
  15. package/dist/{app-install-VPkI5WEg.mjs → app-install-CFI4ptUL.mjs} +33 -13
  16. package/dist/{attempt-Bk2ouQVL.mjs → attempt-DW-mQqM7.mjs} +14 -4
  17. package/dist/{web-Dl0KSRHf.mjs → browser-web-CDhqQxhv.mjs} +138 -176
  18. package/dist/{budget-DfcgFdQB.mjs → budget-Dz-kyXLv.mjs} +1391 -58
  19. package/dist/build-facts-B87vo-Im.d.mts +142 -0
  20. package/dist/{cache-manifest-DnUHBJaU.mjs → cache-manifest-DiwKSyv9.mjs} +3 -3
  21. package/dist/cache-manifest.mjs +1 -1
  22. package/dist/{chrome-BrcVWQyD.mjs → chrome-BTUOo8p2.mjs} +1 -1
  23. package/dist/cli-C9Zvgbdc.mjs +68 -0
  24. package/dist/cli.mjs +1 -1
  25. package/dist/{client-SvBdgObD.mjs → client-CuUo8Nvg.mjs} +381 -49
  26. package/dist/collector-run.d.mts +6 -0
  27. package/dist/collector-run.mjs +9 -9
  28. package/dist/{command-output-CDAIFD-8.mjs → command-output-Bt8ygHE7.mjs} +2 -2
  29. package/dist/{config-D0DbpZtM.mjs → config-DC5jEtd1.mjs} +9 -5
  30. package/dist/{created-devices-CpvzBL25.mjs → created-devices-D0s26Hx5.mjs} +2 -2
  31. package/dist/{dependency-state-CLcBHH2M.mjs → dependency-state-DKaS1OM9.mjs} +2 -2
  32. package/dist/{detached-entry-CiTEgMR1.mjs → detached-entry-pB_IPfV4.mjs} +1 -1
  33. package/dist/{dev-client-B-XC4uRH.mjs → dev-client-CDY_zAmD.mjs} +2 -2
  34. package/dist/{device-C8IOoJPv.mjs → device-BHw0WlHl.mjs} +8 -8
  35. package/dist/{device-capacity-ZC4XSZ4R.mjs → device-capacity-BoN1jQkO.mjs} +25 -14
  36. package/dist/device-host-worker.mjs +19 -19
  37. package/dist/{gradle-dJpre3Yn.mjs → device-ios-B2ruohE-.mjs} +661 -107
  38. package/dist/{device-lease-DpoS36_u.mjs → device-lease-Cu7PtQpZ.mjs} +9 -9
  39. package/dist/{device-lease-run-B8YltIH_.mjs → device-lease-run-D38SnZtt.mjs} +4 -4
  40. package/dist/{device-pool-3o7s5lo4.mjs → device-pool-CP4rAsHx.mjs} +3 -3
  41. package/dist/{device-remote-hFSkpfQu.mjs → device-remote-B5GiUifk.mjs} +15 -16
  42. package/dist/{doctor-CFv1fCrF.mjs → doctor-PRJH94v6.mjs} +61 -34
  43. package/dist/doctor-watchman-wZhyTdp4.mjs +259 -0
  44. package/dist/{error-diagnostics-C-NMnhrk.mjs → error-diagnostics--v5HGOU0.mjs} +11 -11
  45. package/dist/{exec-CaErVv7t.mjs → exec-i8GDPwq9.mjs} +93 -6
  46. package/dist/{gc-DEmkg3Xh.mjs → gc-CyHMcKcn.mjs} +25 -471
  47. package/dist/{guide-CSmhMTf8.mjs → guide-dRaQJJk9.mjs} +681 -507
  48. package/dist/{hosted-android-E1Heoqnv.mjs → hosted-android-Bs7fytj7.mjs} +3 -3
  49. package/dist/{hosted-client-Bp4knSwu.mjs → hosted-client-C5G4h_OJ.mjs} +2 -2
  50. package/dist/{hosted-ios-BnbeYOUD.mjs → hosted-ios-Bik035eL.mjs} +1 -1
  51. package/dist/{hosted-logs-OcgIBvCT.mjs → hosted-logs-CI9Az9a4.mjs} +9 -9
  52. package/dist/{hosted-macos-DcxKjtfH.mjs → hosted-macos-DABm3ScO.mjs} +5 -5
  53. package/dist/{hosted-native-1Ebbig4w.mjs → hosted-native-DbV2aUVw.mjs} +13 -9
  54. package/dist/{idle-shutdown-IGyNV8Cr.mjs → idle-shutdown-DYiMBn34.mjs} +7 -8
  55. package/dist/{ios-DSfnPfse.mjs → ios-BWbHFZVz.mjs} +19 -7
  56. package/dist/{ios-Cr1h5gnO.mjs → ios-DCrkgXEM.mjs} +1 -1
  57. package/dist/ios-DYUr9LGc.mjs +8 -0
  58. package/dist/ios-ITYno9rO.mjs +2241 -0
  59. package/dist/{ios-device-pAN4t54-.mjs → ios-device-CJ_ZOGky.mjs} +3 -3
  60. package/dist/{ios-device-Ee7sDXfp.mjs → ios-device-CrW8aMb5.mjs} +1 -1
  61. package/dist/{ios-state-8L3lgum6.mjs → ios-state-By0XuLTQ.mjs} +1 -1
  62. package/dist/{launch-verify-lTnWZikR.mjs → launch-verify-DCveSE6d.mjs} +5 -5
  63. package/dist/{logs-BAaS7gS2.mjs → logs-Bao1HOMy.mjs} +13 -13
  64. package/dist/{macos-BIRQS90f.mjs → macos-ciyBdTY5.mjs} +194 -132
  65. package/dist/macos-nIOATJmR.mjs +2 -0
  66. package/dist/macos-run.mjs +1 -1
  67. package/dist/maintenance-run.mjs +349 -47
  68. package/dist/manifest-CX0d1IkZ.mjs +148 -0
  69. package/dist/{metro-g8NqiJp-.mjs → metro-DI2AjPF_.mjs} +196 -43
  70. package/dist/{metro-gateway-C-ijGI2F.mjs → metro-gateway-BxpJLIwh.mjs} +4 -4
  71. package/dist/{metro-store-CDDZHtPl.mjs → metro-store-BAHFcJm6.mjs} +16 -2
  72. package/dist/{build-plan-BDsSi09V.mjs → miss-reason-CjQCOKqq.mjs} +207 -249
  73. package/dist/{named-ports-C8m8EQs2.mjs → named-ports-B4iWH4E-.mjs} +70 -8
  74. package/dist/{native-runtime-BEK171xQ.mjs → native-runtime-BGxsbfny.mjs} +6 -6
  75. package/dist/{ndjson-PclOIwVY.mjs → ndjson-LGZAMsqa.mjs} +8 -4
  76. package/dist/offload-worker.d.mts +3 -45
  77. package/dist/offload-worker.mjs +11 -11
  78. package/dist/{ownership-DyRQru0q.mjs → ownership-EB0ySdGK.mjs} +3 -3
  79. package/dist/{page-QF_Ke10s.mjs → page-Bv9s2KwY.mjs} +1 -1
  80. package/dist/placement-log-Dxe34rJm.mjs +88 -0
  81. package/dist/plan-placement-BVY59qa8.mjs +290 -0
  82. package/dist/{ports-4nYqxPWC.mjs → ports-ByPc0_97.mjs} +3 -3
  83. package/dist/{prebuild-D7RUMkwN.mjs → prebuild-BKJ3wJI1.mjs} +5 -5
  84. package/dist/preview-BbSottmO.mjs +986 -0
  85. package/dist/{rolldown-runtime-BsOwBuO_.mjs → process-identity-Biv3arCO.mjs} +11 -1
  86. package/dist/project-B5eQ1USs.mjs +612 -0
  87. package/dist/{pull-request-pxnDCQzn.mjs → pull-request-IHNdMnG8.mjs} +1 -1
  88. package/dist/pull-requests.mjs +1 -1
  89. package/dist/react-native-ios-BMh2i25I.mjs +2 -0
  90. package/dist/react-native-ios-CSpIxexZ.mjs +2083 -0
  91. package/dist/{recordings-BNgsD1Tr.mjs → recordings-Bv8McZN4.mjs} +1 -1
  92. package/dist/{reload-DcRxj3qG.mjs → reload-rAPdqeRR.mjs} +14 -15
  93. package/dist/{remote-cache-Ci4DQYYj.mjs → remote-cache-N3hAEaAL.mjs} +5 -5
  94. package/dist/{run-CkE9y0nc.mjs → run-lAkle1-c.mjs} +5 -5
  95. package/dist/{server-bare-BkrSxSsZ.mjs → server-bare-CkIjnegq.mjs} +5 -6
  96. package/dist/server-expo-DGsdUGX2.mjs +2 -0
  97. package/dist/{server-expo-CHTyXD0G.mjs → server-expo-n3tUi3Em.mjs} +5 -6
  98. package/dist/{settings-SR9OmW9h.mjs → settings-2am7TSxp.mjs} +5 -5
  99. package/dist/{settings-Cfd-0r2d.mjs → settings-CxgngUZk.mjs} +116 -103
  100. package/dist/{settings-BBpMcDbD.mjs → settings-Djl-mpjX.mjs} +1 -1
  101. package/dist/settings.schema.json +198 -9
  102. package/dist/{simslim-BWNrc3M3.mjs → simslim-D9LkJxIO.mjs} +7 -7
  103. package/dist/{slot-launch-DmjBmpQV.mjs → slot-launch-HV_KtPIw.mjs} +6 -6
  104. package/dist/{spawn-claims-D0XfSe8u.mjs → spawn-claims-Kqiifsk2.mjs} +1 -1
  105. package/dist/{spawn-entry-jw19m8Nl.mjs → spawn-entry-Dcb7sDUz.mjs} +1 -0
  106. package/dist/{stage-CzaiwFsI.mjs → stage-BgaZJVZY.mjs} +14 -3
  107. package/dist/{start-AlfCPRVU.mjs → start-D8NbxNBb.mjs} +1 -1
  108. package/dist/{start-DUz3mYdb.mjs → start-DtxthMfI.mjs} +34 -27
  109. package/dist/{state-PeQiJuIu.mjs → state-D2KtnALG.mjs} +4 -4
  110. package/dist/{state-DyaNTgfR.mjs → state-Tp4uImDS.mjs} +5 -3
  111. package/dist/{state-B4PQFXMW.d.mts → state-lKh8shBp.d.mts} +2 -3
  112. package/dist/{stats-Bq4fJOdB.mjs → stats-8EJ5ivFT.mjs} +6 -6
  113. package/dist/{status-DlKvVJBE.mjs → status-BEeL6IKz.mjs} +6 -4
  114. package/dist/{status-BA2pehwf.mjs → status-BOyp0CUl.mjs} +31 -34
  115. package/dist/{stim-desktop-Cnz8CPnl.mjs → stim-desktop-C65jk_q2.mjs} +1 -1
  116. package/dist/{stim-installations-QMEI32v1.mjs → stim-installations-DbmUjsLv.mjs} +1 -1
  117. package/dist/stop-D0UIpZuh.mjs +72 -0
  118. package/dist/{stop-zF1y04f2.mjs → stop-DRipAg-e.mjs} +2 -2
  119. package/dist/{stop-DQIasgKp.mjs → stop-zDlknFoz.mjs} +79 -33
  120. package/dist/supervisor-run.d.mts +24 -22
  121. package/dist/supervisor-run.mjs +21 -22
  122. package/dist/{support-CsJNVfOc.mjs → support-CNqYkV0y.mjs} +7 -7
  123. package/dist/{support-WvD__tSV.mjs → support-DsNaFg6D.mjs} +5 -5
  124. package/dist/swiftpm-macos-aJzPAj1t.mjs +119 -0
  125. package/dist/{toolchain-DNyR3NPq.mjs → toolchain-C3xSoyUl.mjs} +475 -269
  126. package/dist/{trigger-Bemu8ytw.mjs → trigger-CAhmG-4s.mjs} +6 -6
  127. package/dist/trigger-CoalsMTV.mjs +2 -0
  128. package/dist/{warm-progress-DF4JRvYI.mjs → warm-progress-pFLB2e6P.mjs} +135 -38
  129. package/dist/{status-CzS4bPO9.mjs → watchman-BL1IdOtq.mjs} +75 -7
  130. package/dist/web-DFpFeZu5.mjs +2 -0
  131. package/dist/web-DbbrPUn0.mjs +127 -0
  132. package/dist/web-run.mjs +10 -10
  133. package/dist/{workspace-state-DqcCbpE7.mjs → workspace-state-CR9X86xJ.mjs} +3 -3
  134. package/dist/{ownership-BMLqyBgJ.mjs → workspaces-Djb2gfi9.mjs} +661 -23
  135. package/dist/{worktree-Be_7NLKy.mjs → worktree-BL4M1rhB.mjs} +252 -50
  136. package/dist/{worktree-j3IcFAI5.mjs → worktree-DV-A0LNL.mjs} +1 -1
  137. package/package.json +10 -5
  138. package/shim/bundle-response.cjs +2 -1
  139. package/shim/bundle-response.d.cts +1 -1
  140. package/shim/expo-metro-config.cjs +1 -1
  141. package/dist/build-progress-D0WkjCPd.mjs +0 -1036
  142. package/dist/build-slots-41v_d2x9.mjs +0 -142
  143. package/dist/cli-CYXb29oE.mjs +0 -51
  144. package/dist/deps-iKw0eD4P.mjs +0 -438
  145. package/dist/device-ios-C2Um-XUR.mjs +0 -412
  146. package/dist/errors-B6W7FkxQ.mjs +0 -15
  147. package/dist/guide-status-Du-ZQ3FD.mjs +0 -125
  148. package/dist/idle-BXG__1BA.mjs +0 -176
  149. package/dist/in-use-CvGOUn-x.mjs +0 -130
  150. package/dist/ios-BJ4XUSe1.mjs +0 -3867
  151. package/dist/native-run-D1Q56rAD.mjs +0 -158
  152. package/dist/preview-B-g9d7kV.mjs +0 -318
  153. package/dist/process-identity-BmRm1qV0.mjs +0 -12
  154. package/dist/project-D47Rh0ly.mjs +0 -276
  155. package/dist/server-expo-CeakhI8P.mjs +0 -2
  156. package/dist/state-BKa8wNN5.mjs +0 -148
  157. package/dist/stop-BIiM49EY.mjs +0 -48
  158. package/dist/stop-cause-rhmGfwvt.mjs +0 -97
  159. package/dist/trigger-CXts6qt1.mjs +0 -2
  160. package/dist/watchman-APYjXSQa.mjs +0 -48
  161. package/dist/workspace-process-lock-2mNzOlaB.mjs +0 -58
  162. package/dist/workspaces-Bcib97-6.mjs +0 -306
@@ -0,0 +1,986 @@
1
+ import { t as getExecutor } from "./exec-i8GDPwq9.mjs";
2
+ import { o as formatLongDuration, u as plural } from "./command-output-Bt8ygHE7.mjs";
3
+ import { H as projectDeviceSlots, M as isOnMountedVolume, N as listMountedVolumes, P as measuredDirectorySize, _ as loadConfig$1, p as getProject } from "./config-DC5jEtd1.mjs";
4
+ import { C as workspaceStateFile, r as readWorkspaceState$1, s as workspaceLastUsed, x as workspaceLogsDir$1 } from "./workspace-state-CR9X86xJ.mjs";
5
+ import { r as findProjectRoot } from "./project-B5eQ1USs.mjs";
6
+ import { D as projectMaintenancePinned, ht as resolveFullRef, it as hasPopulatedSubmodules, lt as listWorktrees, ot as hasUncommittedWork, tt as dirtyPaths, vt as sourceCheckoutOf, yt as unpushedCommits } from "./settings-CxgngUZk.mjs";
7
+ import { n as readManifest } from "./cache-manifest-DiwKSyv9.mjs";
8
+ import { At as phase, G as DEVICE_LIST_TIMEOUT_MS, Nt as discoverCaches, c as readVolumeSpace, i as enforceBudget, l as resolveBudget, o as machineNumber, pt as planCacheEmptying, r as cacheLabel, u as trimmableCaches } from "./budget-Dz-kyXLv.mjs";
9
+ import { F as recordGcResult, L as canonicalPath, N as listBuildSlots, a as collectWorkspaceOutputs, c as listWorkspaceDirs, i as collectOrphanedWorkspaces, p as workspaceInUse, s as isInsideWorkspaces } from "./workspaces-Djb2gfi9.mjs";
10
+ import { h as listBuildLocks, i as listLeaseFiles, r as leaseIsExpired } from "./device-lease-Cu7PtQpZ.mjs";
11
+ import { pt as readParked, z as ownedAvdSerialResolver } from "./android-BdQC6zs1.mjs";
12
+ import { M as readHostMemoryPressure, d as listAllIosSims } from "./ios-BWbHFZVz.mjs";
13
+ import { a as metroStoreRoot } from "./metro-store-BAHFcJm6.mjs";
14
+ import { n as describePullRequest, o as pullRequestLookups, r as endedPullRequest } from "./pull-request-IHNdMnG8.mjs";
15
+ import { t as resolveMaintenanceSettings } from "./settings-Djl-mpjX.mjs";
16
+ import { o as fetchDefaultBranch, s as mergeState } from "./warm-progress-pFLB2e6P.mjs";
17
+ import { f as removeWorktreeTarget, i as matchWorktreeEntry, n as excludePodChurn, o as reclaimKeys, r as excludeWatchmanCookies } from "./worktree-BL4M1rhB.mjs";
18
+ import { existsSync } from "node:fs";
19
+ import { basename, isAbsolute, join, sep } from "node:path";
20
+ import { isAbsolute as isAbsolute$1, join as join$1 } from "path";
21
+ import { LAST_BUILD_KEYS, MAINTENANCE_LOG_NAME, buildWorkerRoot, loadConfig, readMaintenanceState, settingDefinition, sharedCcache, sharedCompilationCache } from "@stim-cli/core/state";
22
+ import { cpus, freemem, loadavg, totalmem } from "node:os";
23
+ import chalk from "chalk";
24
+ import { existsSync as existsSync$1, readdirSync as readdirSync$1, statSync as statSync$1 } from "fs";
25
+ import { buildCacheRoot, configDir, metroCacheRoot } from "@stim-cli/core";
26
+ //#region src/maintenance/measure.ts
27
+ function measureDisk() {
28
+ return readVolumeSpace([
29
+ configDir(),
30
+ ...Object.keys(loadConfig()?.projects ?? {}),
31
+ buildWorkerRoot(loadConfig())
32
+ ]);
33
+ }
34
+ function measurePressure(settings, previous, now) {
35
+ const level = readHostMemoryPressure();
36
+ const availableBytes = process.platform === "darwin" ? null : freemem();
37
+ const warningSince = level === "warning" ? previous?.warningSince ?? now : null;
38
+ const pressured = settings.memoryPressureLevel !== "off" && (level === "critical" || settings.memoryPressureLevel === "warning" && warningSince !== null && now - warningSince >= settings.memoryWarningMinutes * 6e4 || availableBytes !== null && availableBytes < (settings.minAvailableMemoryGb === void 0 ? totalmem() * .1 : settings.minAvailableMemoryGb * 1024 ** 3));
39
+ return {
40
+ disk: measureDisk(),
41
+ memory: {
42
+ level,
43
+ availableBytes,
44
+ pressured
45
+ },
46
+ warningSince
47
+ };
48
+ }
49
+ function sizeScanDeferred(settings) {
50
+ return loadavg()[0] / Math.max(1, cpus().length) > settings.maxLoadPerCore;
51
+ }
52
+ function cacheBlocked(entry, discovered = discoverCaches()) {
53
+ return planCacheEmptying([{
54
+ ...entry,
55
+ note: "",
56
+ prune: "entries",
57
+ ...discovered.some((cache) => canonicalPath(cache.dir) === canonicalPath(entry.dir) && cache.source === "registered") ? { source: "registered" } : {}
58
+ }], false)[0]?.machineGlobal ?? (entry.category === "compilation-cache" && [...listBuildLocks(), ...listBuildSlots()].some((item) => item.alive || item.unresolved) ? "a build lock or slot is live or unresolved" : void 0);
59
+ }
60
+ function measureSizes(now, failure) {
61
+ const sizes = [];
62
+ const outputs = collectWorkspaceOutputs({
63
+ olderThan: null,
64
+ now,
65
+ sizeTimeoutMs: 12e4
66
+ });
67
+ for (const entry of outputs.workspaces) {
68
+ if (entry.bytes === null) {
69
+ failure(entry.dir, entry.projectRoot ?? void 0);
70
+ continue;
71
+ }
72
+ sizes.push({
73
+ name: "workspace build outputs",
74
+ category: "workspace-outputs",
75
+ dir: entry.dir,
76
+ bytes: entry.bytes,
77
+ measuredAt: now,
78
+ ...entry.projectRoot ? { workspace: canonicalPath(entry.projectRoot) } : {},
79
+ idleDays: entry.idleDays,
80
+ ...!entry.willClear ? { blocked: entry.keptReason ?? "workspace ownership is unresolved" } : {}
81
+ });
82
+ }
83
+ const known = [
84
+ {
85
+ name: "shared build cache",
86
+ dir: buildCacheRoot(),
87
+ category: "build-cache"
88
+ },
89
+ {
90
+ name: "Metro transform caches",
91
+ dir: metroCacheRoot(),
92
+ category: "metro-cache"
93
+ },
94
+ {
95
+ name: "ccache",
96
+ dir: sharedCcache(),
97
+ category: "ccache"
98
+ },
99
+ {
100
+ name: "Swift compilation cache",
101
+ dir: sharedCompilationCache(),
102
+ category: "compilation-cache"
103
+ }
104
+ ];
105
+ const discovered = discoverCaches();
106
+ for (const cache of discovered) {
107
+ if (cache.source !== "registered" && !canonicalPath(cache.dir).startsWith(`${canonicalPath(configDir())}/`)) continue;
108
+ if (cache.prune === "report-only") continue;
109
+ const dir = canonicalPath(cache.dir);
110
+ if (known.some((item) => dir === canonicalPath(item.dir) || dir.startsWith(`${canonicalPath(item.dir)}/`))) continue;
111
+ const category = cache.name.startsWith("Metro transform cache") ? "metro-cache" : /^(Expo build cache|native build cache|Build cache)$/.test(cache.name) ? "build-cache" : "other";
112
+ known.push({
113
+ name: cache.name,
114
+ dir: cache.dir,
115
+ category
116
+ });
117
+ }
118
+ for (const entry of known) {
119
+ if (!existsSync(entry.dir)) continue;
120
+ const bytes = measuredDirectorySize(entry.dir, { timeoutMs: 12e4 });
121
+ if (bytes === null) {
122
+ failure(entry.dir);
123
+ continue;
124
+ }
125
+ const blocked = cacheBlocked(entry, discovered);
126
+ sizes.push({
127
+ ...entry,
128
+ bytes,
129
+ measuredAt: now,
130
+ ...blocked ? { blocked } : {}
131
+ });
132
+ }
133
+ return sizes;
134
+ }
135
+ //#endregion
136
+ //#region src/commands/gc/worktrees.ts
137
+ const DEFAULT_WORKTREE_IDLE_DAYS = 7;
138
+ const DAY_MS = 864e5;
139
+ const MINUTE_MS = 6e4;
140
+ const GRACE_SETTING = "gc.worktreeGraceMinutes";
141
+ const MERGE_DECIDES = /* @__PURE__ */ new Set([
142
+ "unpushed",
143
+ "not-merged",
144
+ "last-use-unknown",
145
+ "recently-used"
146
+ ]);
147
+ function skip(code, text) {
148
+ return {
149
+ code,
150
+ text
151
+ };
152
+ }
153
+ function pullRequestNote(lookup) {
154
+ const pr = lookup && "pullRequest" in lookup ? lookup.pullRequest : null;
155
+ if (!pr) return null;
156
+ return pr.containsHead ? describePullRequest(pr) : `${describePullRequest(pr)}, and HEAD has commits it does not`;
157
+ }
158
+ /**
159
+ * Why gc keeps a worktree, or null when it removes it. A worktree that would be removed is still kept while its last
160
+ * activity, or its merge into the default branch, is less than `grace.ms` old, and kept when that activity is unknown.
161
+ */
162
+ function worktreeSkipReason(facts, olderThan, grace = {
163
+ ms: 0,
164
+ now: 0
165
+ }) {
166
+ return removalBlocker(facts, olderThan) ?? graceBlocker(facts, grace);
167
+ }
168
+ function graceBlocker(facts, grace) {
169
+ if (grace.ms <= 0) return null;
170
+ if (!facts.activity) return skip("activity-unknown", "its last activity could not be read");
171
+ const merged = facts.merge?.merged ? facts.merge : null;
172
+ const ended = endedPullRequest(facts.pullRequest);
173
+ const events = [facts.activity];
174
+ if (merged) events.push({
175
+ at: merged.mergedAt,
176
+ basis: `merged into ${merged.into}`
177
+ });
178
+ if (ended?.endedAt) events.push({
179
+ at: ended.endedAt,
180
+ basis: describePullRequest(ended)
181
+ });
182
+ const latest = events.reduce((a, b) => b.at > a.at ? b : a);
183
+ const eligibleAt = latest.at + grace.ms;
184
+ if (grace.now >= eligibleAt) return null;
185
+ const ago = formatLongDuration(Math.max(0, grace.now - latest.at));
186
+ return {
187
+ code: "recent-activity",
188
+ text: `recent activity: ${latest.basis} ${ago} ago; removable after ${new Date(eligibleAt).toISOString()}`,
189
+ eligibleAt
190
+ };
191
+ }
192
+ function removalBlocker(facts, olderThan) {
193
+ if (facts.bare) return skip("bare-repository", "bare repository");
194
+ if (typeof facts.source === "object") return skip("source-checkout-unknown", `source checkout unknown: ${facts.source.refusal}`);
195
+ if (facts.source === "source") return skip("source-checkout", "source checkout");
196
+ if (facts.locked) return skip("locked", "locked with git worktree lock");
197
+ if (facts.inUse.length) return skip("in-use", `in use: ${facts.inUse.join("; ")}`);
198
+ if (facts.porcelain === null) return skip("status-unreadable", "git status could not be read");
199
+ const dirty = excludePodChurn(excludeWatchmanCookies(facts.porcelain).lines).lines.length;
200
+ if (dirty) return skip("dirty", `dirty: ${plural(dirty, "uncommitted or untracked file")}`);
201
+ if (facts.unpushed === null) return skip("unpushed-unchecked", "unpushed commits could not be checked");
202
+ const merged = facts.merge?.merged ? facts.merge : null;
203
+ const ended = endedPullRequest(facts.pullRequest);
204
+ if (facts.unpushed.length && !merged?.coversUnpushed && ended?.state !== "merged") return skip("unpushed", `unpushed: ${plural(facts.unpushed.length, "commit")} on no remote or other branch`);
205
+ if (facts.submodules) return skip("submodules", "initialized submodules");
206
+ if (merged || ended) return null;
207
+ const notMerged = facts.merge && !facts.merge.merged ? facts.merge : null;
208
+ const details = [notMerged?.detail, pullRequestNote(facts.pullRequest)].filter(Boolean);
209
+ if (olderThan === null) return skip(notMerged?.unknown ? "merge-unknown" : "not-merged", details.join("; ") || "not merged");
210
+ const also = details.map((detail) => `; ${detail}`).join("");
211
+ if (facts.idleDays === null) return skip("last-use-unknown", `recently used: its last use is unknown${also}`);
212
+ if (facts.idleDays < olderThan) return skip("recently-used", `recently used ${facts.idleDays}d ago${also}`);
213
+ return null;
214
+ }
215
+ /** Why gc removes a worktree it did not skip: `merged into origin/main`, `PR #12 closed` or `idle 9d`. */
216
+ function worktreeRemovalReason(candidate) {
217
+ if (candidate.merge?.merged) return `merged into ${candidate.merge.into}`;
218
+ const ended = endedPullRequest(candidate.pullRequest);
219
+ return ended ? describePullRequest(ended) : `idle ${candidate.idleDays ?? 0}d`;
220
+ }
221
+ /** The pull request note a kept worktree's report line carries, such as `PR #12 merged`, or null. */
222
+ function worktreePullRequestNote(candidate) {
223
+ return pullRequestNote(candidate.pullRequest);
224
+ }
225
+ function lastUsedOf(keys) {
226
+ const times = keys.map(workspaceLastUsed).filter(Number.isFinite);
227
+ return times.length ? Math.max(...times) : NaN;
228
+ }
229
+ function idleDaysOf(keys, now) {
230
+ const last = lastUsedOf(keys);
231
+ return Number.isFinite(last) ? Math.max(0, Math.floor((now - last) / DAY_MS)) : null;
232
+ }
233
+ function deviceReads() {
234
+ let sims;
235
+ let resolver;
236
+ return {
237
+ sims: () => {
238
+ if (sims === void 0) try {
239
+ sims = listAllIosSims({ timeoutMs: DEVICE_LIST_TIMEOUT_MS });
240
+ } catch {
241
+ sims = null;
242
+ }
243
+ return sims;
244
+ },
245
+ avdSerial: (avdName) => (resolver ??= ownedAvdSerialResolver({ timeoutMs: DEVICE_LIST_TIMEOUT_MS }))(avdName)
246
+ };
247
+ }
248
+ function inUseOf(keys, checks, devices = deviceReads()) {
249
+ return [.../* @__PURE__ */ new Set([...keys.flatMap((key) => workspaceInUse(key, checks)), ...deviceUseOf(keys, devices)])];
250
+ }
251
+ function deviceUseOf(keys, devices) {
252
+ const reasons = [];
253
+ for (const key of keys) {
254
+ let slots;
255
+ try {
256
+ slots = projectDeviceSlots(getProject(key));
257
+ } catch (error) {
258
+ reasons.push(`its device records cannot be read: ${error.message}`);
259
+ continue;
260
+ }
261
+ for (const { platforms } of slots) {
262
+ const ios = platforms.ios;
263
+ if (ios?.owned && ios.deviceUdid) {
264
+ const sims = devices.sims();
265
+ const sim = sims?.find((entry) => entry.udid === ios.deviceUdid);
266
+ if (sims === null) reasons.push(`the state of its owned simulator ${ios.deviceUdid} cannot be read`);
267
+ else if (sim && sim.state !== "Shutdown") reasons.push(`its owned simulator ${sim.name} is ${sim.state}; \`stim stop\` in ${key} shuts it down`);
268
+ }
269
+ const android = platforms.android;
270
+ if (android?.owned && android.avdName) try {
271
+ if (devices.avdSerial(android.avdName).serial) reasons.push(`its owned emulator ${android.avdName} is running; \`stim stop\` in ${key} shuts it down`);
272
+ } catch {
273
+ reasons.push(`the state of its owned emulator ${android.avdName} cannot be read`);
274
+ }
275
+ }
276
+ }
277
+ const holders = new Set(keys.map(canonicalPath));
278
+ const now = Date.now();
279
+ for (const { lease } of listLeaseFiles()) if (lease && !leaseIsExpired(lease, now) && holders.has(canonicalPath(lease.holder))) reasons.push(`it holds the ${lease.platform} device lease on ${lease.deviceName ?? lease.id}`);
280
+ return reasons;
281
+ }
282
+ function newestMtime(paths) {
283
+ let newest = null;
284
+ for (const { path, basis } of paths) {
285
+ let mtime;
286
+ try {
287
+ mtime = statSync$1(path).mtimeMs;
288
+ } catch (error) {
289
+ if (error.code === "ENOENT") continue;
290
+ return "unreadable";
291
+ }
292
+ if (!newest || mtime > newest.at) newest = {
293
+ at: mtime,
294
+ basis
295
+ };
296
+ }
297
+ return newest;
298
+ }
299
+ function logFiles$1(key) {
300
+ const dir = workspaceLogsDir$1(key);
301
+ try {
302
+ return readdirSync$1(dir).filter((name) => !name.startsWith(MAINTENANCE_LOG_NAME)).map((name) => ({
303
+ path: join$1(dir, name),
304
+ basis: "a Stim log write"
305
+ }));
306
+ } catch (error) {
307
+ return error.code === "ENOENT" ? [] : null;
308
+ }
309
+ }
310
+ function worktreeActivityOf(path, keys) {
311
+ const gitDir = getExecutor().runFileQuiet("git", [
312
+ "--no-optional-locks",
313
+ "-C",
314
+ path,
315
+ "rev-parse",
316
+ "--path-format=absolute",
317
+ "--git-dir"
318
+ ])?.trim();
319
+ if (!gitDir) return null;
320
+ const paths = [
321
+ {
322
+ path: join$1(gitDir, "index"),
323
+ basis: "a git index write"
324
+ },
325
+ {
326
+ path: join$1(gitDir, "HEAD"),
327
+ basis: "a git HEAD change"
328
+ },
329
+ {
330
+ path: join$1(gitDir, "logs", "HEAD"),
331
+ basis: "a git reflog entry"
332
+ }
333
+ ];
334
+ for (const key of keys) {
335
+ const logs = logFiles$1(key);
336
+ if (logs === null) return null;
337
+ paths.push({
338
+ path: workspaceStateFile(key),
339
+ basis: "a Stim workspace state write"
340
+ }, ...logs);
341
+ }
342
+ const newest = newestMtime(paths);
343
+ return newest === "unreadable" ? null : newest;
344
+ }
345
+ function graceMsSetting() {
346
+ const { value, error } = machineNumber(GRACE_SETTING, loadConfig$1(), process.env);
347
+ if (error) {
348
+ const fallback = Number(settingDefinition(GRACE_SETTING)?.default);
349
+ console.error(chalk.yellow(`${error} gc uses the default of ${fallback} minutes.`));
350
+ return fallback * MINUTE_MS;
351
+ }
352
+ return (value ?? 0) * MINUTE_MS;
353
+ }
354
+ function porcelainOf(path, gitAnswered) {
355
+ if (gitAnswered === null) return null;
356
+ if (!gitAnswered) return [];
357
+ const lines = dirtyPaths(path, { limit: Infinity });
358
+ return lines.length ? lines : null;
359
+ }
360
+ function candidateRoots() {
361
+ const registered = Object.keys(loadConfig$1()?.projects ?? {}).filter(isAbsolute$1);
362
+ const recorded = listWorkspaceDirs().flatMap((entry) => entry.projectRoot ? [entry.projectRoot] : []);
363
+ return [.../* @__PURE__ */ new Set([...registered, ...recorded])].filter((root) => existsSync$1(root)).toSorted();
364
+ }
365
+ function checkMergeStates(pending, idle, grace) {
366
+ const repos = /* @__PURE__ */ new Map();
367
+ for (const entry of pending) repos.set(entry.repo, [...repos.get(entry.repo) ?? [], entry]);
368
+ for (const [repo, entries] of repos) {
369
+ const target = fetchDefaultBranch(repo, grace.now);
370
+ for (const { candidate, facts } of entries) {
371
+ const merge = "error" in target ? {
372
+ merged: false,
373
+ unknown: true,
374
+ detail: `merge state unknown: ${target.error}`
375
+ } : mergeState(candidate.path, target);
376
+ const verdict = worktreeSkipReason({
377
+ ...facts,
378
+ merge
379
+ }, idle, grace);
380
+ Object.assign(candidate, {
381
+ merge,
382
+ skipCode: verdict?.code ?? null,
383
+ skipped: verdict?.text ?? null,
384
+ eligibleAt: verdict?.eligibleAt ?? null
385
+ });
386
+ }
387
+ }
388
+ }
389
+ /**
390
+ * Classifies each Stim-managed linked worktree. A merged one is removable; with `idle`, so is one unused for
391
+ * `olderThan` days. Device use is read last, in one pass against one simulator list and one AVD resolver, so
392
+ * the resolver's time budget covers only device reads. Pull requests are asked once per repository, all
393
+ * repositories at once. Merge state is checked only where it decides the verdict, after one fetch per repository.
394
+ */
395
+ async function collectWorktreeSweep({ idle, olderThan, now }) {
396
+ const days = idle ? olderThan ?? DEFAULT_WORKTREE_IDLE_DAYS : null;
397
+ const grace = {
398
+ ms: graceMsSetting(),
399
+ now
400
+ };
401
+ const groups = /* @__PURE__ */ new Map();
402
+ const outside = [];
403
+ const candidates = candidateRoots();
404
+ if (candidates.length) phase("worktrees", `checking ${plural(candidates.length, "project")} for merged or idle worktrees`);
405
+ for (const root of candidates) {
406
+ const entry = matchWorktreeEntry(listWorktrees(root), root);
407
+ if (!entry) {
408
+ outside.push({
409
+ path: root,
410
+ keys: [root],
411
+ idleDays: null,
412
+ merge: null,
413
+ head: null,
414
+ pullRequest: null,
415
+ skipCode: "not-a-worktree",
416
+ skipped: "not inside a git worktree",
417
+ eligibleAt: null
418
+ });
419
+ continue;
420
+ }
421
+ groups.set(entry.path, [...groups.get(entry.path) ?? [], root]);
422
+ }
423
+ const inspected = [];
424
+ for (const [path, roots] of groups) {
425
+ const entries = listWorktrees(path);
426
+ const entry = matchWorktreeEntry(entries, path);
427
+ const source = sourceCheckoutOf(entries);
428
+ const keys = [.../* @__PURE__ */ new Set([...roots, ...reclaimKeys(path)])];
429
+ const idleDays = idleDaysOf(keys, now);
430
+ const linked = !("refusal" in source) && entry !== null && source.path !== entry.path;
431
+ const activity = linked && grace.ms > 0 ? worktreeActivityOf(path, keys) : null;
432
+ const gitAnswered = linked ? hasUncommittedWork(path) : null;
433
+ const head = linked ? resolveFullRef(path, "HEAD") : null;
434
+ const facts = {
435
+ source: "refusal" in source ? source : linked ? "linked" : "source",
436
+ bare: Boolean(entry?.bare),
437
+ locked: Boolean(entry?.locked),
438
+ porcelain: porcelainOf(path, gitAnswered),
439
+ unpushed: linked ? unpushedCommits(path) : null,
440
+ submodules: linked && hasPopulatedSubmodules(path),
441
+ inUse: [],
442
+ idleDays,
443
+ merge: null,
444
+ pullRequest: null,
445
+ activity
446
+ };
447
+ inspected.push({
448
+ candidate: {
449
+ path,
450
+ keys,
451
+ idleDays,
452
+ merge: null,
453
+ head,
454
+ pullRequest: null,
455
+ skipCode: null,
456
+ skipped: null,
457
+ eligibleAt: null
458
+ },
459
+ facts,
460
+ repo: "refusal" in source ? null : source.path,
461
+ branch: head && entry?.branch ? entry.branch : null
462
+ });
463
+ }
464
+ const linked = inspected.filter(({ facts }) => facts.source === "linked");
465
+ for (const { candidate, facts } of linked) facts.inUse = candidate.keys.flatMap((key) => workspaceInUse(key, { managedLocks: true }));
466
+ const devices = deviceReads();
467
+ for (const { candidate, facts } of linked) facts.inUse = [.../* @__PURE__ */ new Set([...facts.inUse, ...deviceUseOf(candidate.keys, devices)])];
468
+ await lookUpPullRequests(inspected);
469
+ const worktrees = [];
470
+ const pending = [];
471
+ for (const { candidate, facts, repo } of inspected) {
472
+ const verdict = worktreeSkipReason(facts, days, grace);
473
+ Object.assign(candidate, {
474
+ pullRequest: facts.pullRequest,
475
+ skipCode: verdict?.code ?? null,
476
+ skipped: verdict?.text ?? null,
477
+ eligibleAt: verdict?.eligibleAt ?? null
478
+ });
479
+ if (verdict && MERGE_DECIDES.has(verdict.code) && repo !== null) pending.push({
480
+ candidate,
481
+ facts,
482
+ repo
483
+ });
484
+ worktrees.push(candidate);
485
+ }
486
+ checkMergeStates(pending, days, grace);
487
+ const listed = [...worktrees, ...outside].filter((w) => idle || w.skipCode !== "not-a-worktree" && w.skipCode !== "source-checkout");
488
+ return {
489
+ idle: days === null ? null : {
490
+ olderThan: days,
491
+ defaulted: olderThan === null
492
+ },
493
+ graceMs: grace.ms,
494
+ worktrees: listed
495
+ };
496
+ }
497
+ async function lookUpPullRequests(inspected) {
498
+ const repos = /* @__PURE__ */ new Map();
499
+ for (const { candidate, facts, repo, branch } of inspected) {
500
+ if (repo === null || branch === null || candidate.head === null) continue;
501
+ const query = {
502
+ cwd: candidate.path,
503
+ branch,
504
+ head: candidate.head
505
+ };
506
+ repos.set(repo, [...repos.get(repo) ?? [], {
507
+ facts,
508
+ query
509
+ }]);
510
+ }
511
+ const lookup = pullRequestLookups();
512
+ await Promise.all([...repos].map(async ([repo, entries]) => {
513
+ const answers = await lookup(repo, entries.map(({ query }) => query));
514
+ entries.forEach(({ facts }, i) => facts.pullRequest = answers[i] ?? null);
515
+ }));
516
+ }
517
+ async function removeWorktrees(sweep, { now = Date.now() } = {}) {
518
+ let failures = 0;
519
+ for (const candidate of sweep.worktrees) {
520
+ if (candidate.skipped) continue;
521
+ let kept = [];
522
+ const guard = (lockedKeys) => {
523
+ const keys = [.../* @__PURE__ */ new Set([...candidate.keys, ...lockedKeys])];
524
+ const unlocked = keys.filter((key) => !lockedKeys.includes(key));
525
+ const reasons = [...inUseOf(lockedKeys, { managedLocks: false }), ...inUseOf(unlocked, { managedLocks: true })].map((r) => `in use: ${r}`);
526
+ const mergedHead = candidate.merge?.merged ? candidate.merge.head : endedPullRequest(candidate.pullRequest) ? candidate.head : null;
527
+ if (mergedHead) {
528
+ if (resolveFullRef(candidate.path, "HEAD") !== mergedHead) reasons.push("its HEAD moved since gc checked it");
529
+ } else {
530
+ const idleDays = idleDaysOf(keys, now);
531
+ if (idleDays === null || !sweep.idle || idleDays < sweep.idle.olderThan) reasons.push(`used ${idleDays === null ? "at an unknown time" : `${idleDays}d ago`} since gc checked it`);
532
+ }
533
+ if (sweep.graceMs > 0) {
534
+ const recent = graceBlocker({
535
+ merge: candidate.merge,
536
+ pullRequest: candidate.pullRequest,
537
+ activity: worktreeActivityOf(candidate.path, keys)
538
+ }, {
539
+ ms: sweep.graceMs,
540
+ now: Date.now()
541
+ });
542
+ if (recent) reasons.push(recent.text);
543
+ }
544
+ kept = reasons;
545
+ return reasons;
546
+ };
547
+ let removed = false;
548
+ let error = null;
549
+ try {
550
+ const ended = endedPullRequest(candidate.pullRequest);
551
+ const mergedHead = candidate.merge?.merged && candidate.merge.coversUnpushed ? candidate.merge.head : ended?.state === "merged" ? candidate.head ?? void 0 : void 0;
552
+ removed = await removeWorktreeTarget(candidate.path, {
553
+ linkedOnly: true,
554
+ guard,
555
+ mergedHead
556
+ });
557
+ } catch (thrown) {
558
+ error = thrown?.message || String(thrown);
559
+ console.error(chalk.red(`Could not remove ${candidate.path}: ${error}`));
560
+ }
561
+ if (removed) {
562
+ console.log(chalk.green(`Removed the worktree ${candidate.path} (${worktreeRemovalReason(candidate)})`));
563
+ recordGcResult("worktree", "done", candidate.path, { detail: worktreeRemovalReason(candidate) });
564
+ } else if (kept.length) {
565
+ console.log(chalk.yellow(`Kept the worktree ${candidate.path}: ${kept.join("; ")}`));
566
+ recordGcResult("worktree", "kept", candidate.path, { detail: kept.join("; ") });
567
+ } else {
568
+ failures++;
569
+ console.error(chalk.yellow(`Kept the worktree ${candidate.path}; see the lines above for why.`));
570
+ recordGcResult("worktree", "failed", candidate.path, { detail: error ?? "stim worktree remove did not remove it; see the details" });
571
+ }
572
+ }
573
+ return failures;
574
+ }
575
+ //#endregion
576
+ //#region src/maintenance/protect.ts
577
+ const BUILD_RECORDS = ["lastBuild", ...Object.values(LAST_BUILD_KEYS)];
578
+ function recordKeys(record) {
579
+ if (record === null || typeof record !== "object") return [];
580
+ const value = record;
581
+ return [value.cacheKey, value.missReason?.baseline?.cacheKey].filter((key) => typeof key === "string");
582
+ }
583
+ function protectedCacheKeys(config = loadConfig$1()) {
584
+ const keys = /* @__PURE__ */ new Set();
585
+ for (const root of Object.keys(config?.projects ?? {})) {
586
+ const state = readWorkspaceState$1(root);
587
+ for (const name of BUILD_RECORDS) for (const key of recordKeys(state?.[name])) keys.add(key);
588
+ }
589
+ for (const platform of ["ios", "android"]) for (const record of readParked(platform, { config })) if (record.cacheKey) keys.add(record.cacheKey);
590
+ for (const lock of listBuildLocks()) if ((lock.alive || lock.unresolved) && lock.key) keys.add(lock.key);
591
+ return keys;
592
+ }
593
+ function liveMetroStores(config = loadConfig$1()) {
594
+ return Object.keys(config?.projects ?? {}).filter((root) => workspaceInUse(root, {
595
+ managedLocks: false,
596
+ hosted: false,
597
+ nativeRun: false
598
+ }).length > 0).map((root) => canonicalPath(metroStoreRoot(root)));
599
+ }
600
+ function cacheEntryProtection(config = loadConfig$1()) {
601
+ try {
602
+ const keys = protectedCacheKeys(config);
603
+ const stores = liveMetroStores(config);
604
+ return (entry) => {
605
+ if (keys.has(basename(entry))) return "a project, parked device or running build still uses this build";
606
+ const path = canonicalPath(entry);
607
+ if (stores.some((store) => path === store || path.startsWith(`${store}${sep}`))) return "its project has a running or unverifiable dev server";
608
+ return null;
609
+ };
610
+ } catch (error) {
611
+ const reason = `cache protection could not be read: ${error instanceof Error ? error.message : String(error)}`;
612
+ return () => reason;
613
+ }
614
+ }
615
+ function recentUse(workspace, settings) {
616
+ const since = Date.now() - workspaceLastUsed(workspace);
617
+ return Number.isFinite(since) && since < settings.protectRecentHours * 36e5 ? `used within the last ${settings.protectRecentHours} hours` : null;
618
+ }
619
+ //#endregion
620
+ //#region src/maintenance/plan.ts
621
+ function plan({ pressure, sizes, settings, budget, diskSteps = [], protectedRoot, scoped = false, projects = [], pinned = () => false, recentlyUsed = () => null }) {
622
+ const actions = [];
623
+ const blocked = [];
624
+ const skips = [];
625
+ const add = (action) => {
626
+ if (action.kind === "would-clear-outputs" && action.workspace && pinned(action.workspace)) {
627
+ skips.push({
628
+ target: action.workspace,
629
+ reason: "pinned by maintenance.keep",
630
+ workspace: action.workspace
631
+ });
632
+ return false;
633
+ }
634
+ const recent = action.kind === "would-clear-outputs" && action.workspace ? recentlyUsed(action.workspace) : null;
635
+ if (recent) {
636
+ skips.push({
637
+ target: action.workspace,
638
+ reason: recent,
639
+ workspace: action.workspace
640
+ });
641
+ return false;
642
+ }
643
+ if (actions.some((entry) => entry.kind === action.kind && entry.target === action.target)) return false;
644
+ actions.push(action);
645
+ return true;
646
+ };
647
+ const floor = Math.max(budget.minFreeDiskMb, budget.hardFloorDiskMb);
648
+ const emergency = pressure?.disk.some((disk) => disk.freeMb < budget.hardFloorDiskMb) ?? false;
649
+ const low = pressure?.disk.filter((disk) => disk.freeMb < floor) ?? [];
650
+ 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("; ");
651
+ const kinds = {
652
+ "idle-devices": "would-shutdown-device",
653
+ "idle-dev-servers": "would-stop-workspace",
654
+ "workspace-outputs": "would-clear-outputs",
655
+ "stale-cache-entries": "would-trim-cache"
656
+ };
657
+ if (low.length) {
658
+ for (const step of diskSteps) {
659
+ if (scoped && step.step === "idle-devices") continue;
660
+ for (const target of step.targets) {
661
+ const workspace = projects.find((root) => root === target || target.endsWith(` in ${root}`)) ?? (step.step === "idle-dev-servers" || step.step === "workspace-outputs" ? target : void 0);
662
+ if (workspace === protectedRoot || target === protectedRoot) continue;
663
+ const size = workspace && step.step !== "idle-devices" ? sizes.find((entry) => entry.workspace === workspace && entry.category === "workspace-outputs") : void 0;
664
+ add({
665
+ kind: kinds[step.step],
666
+ target,
667
+ bytes: step.step === "workspace-outputs" ? size?.bytes ?? 0 : 0,
668
+ reason: `${size?.idleDays == null ? "" : `idle ${size.idleDays} days, `}${reason}`,
669
+ ...workspace ? { workspace } : {},
670
+ check: "disk",
671
+ ...step.step === "stale-cache-entries" ? { olderThanDays: 14 } : {}
672
+ });
673
+ }
674
+ if (step.failures) blocked.push(`Could not plan ${step.step}: ${step.failures} failures`);
675
+ }
676
+ if (actions.length === 0) blocked.push(`${reason}; no reclaimable disk targets`);
677
+ }
678
+ const caps = [
679
+ [
680
+ "workspace-outputs",
681
+ settings.workspaceOutputsMaxGb,
682
+ "would-clear-outputs"
683
+ ],
684
+ [
685
+ "build-cache",
686
+ settings.buildCacheMaxGb,
687
+ "would-trim-cache"
688
+ ],
689
+ [
690
+ "metro-cache",
691
+ settings.metroCacheMaxGb,
692
+ "would-trim-cache"
693
+ ],
694
+ [
695
+ "compilation-cache",
696
+ settings.swiftCompilationCacheMaxGb,
697
+ "would-empty-cache"
698
+ ]
699
+ ];
700
+ for (const [category, capGb, kind] of caps) {
701
+ const entries = sizes.filter((size) => size.category === category);
702
+ const total = entries.reduce((sum, size) => sum + size.bytes, 0);
703
+ const cap = capGb * 1024 ** 3;
704
+ if (cap === 0 || total <= cap) continue;
705
+ let remaining = total;
706
+ const targetBytes = cap * settings.capTargetPercent / 100;
707
+ const why = `${category} ${(total / 1024 ** 3).toFixed(1)}G over the ${capGb}G cap; target ${(targetBytes / 1024 ** 3).toFixed(1)}G`;
708
+ if (category === "compilation-cache" && !emergency) {
709
+ skips.push({
710
+ target: entries[0]?.dir ?? category,
711
+ reason: `${why}; it can only be emptied whole, which runs only below the ${(budget.hardFloorDiskMb / 1024).toFixed(1)}G hard floor`
712
+ });
713
+ continue;
714
+ }
715
+ for (const size of entries.toSorted((a, b) => (b.idleDays ?? 0) - (a.idleDays ?? 0))) {
716
+ if (remaining <= targetBytes) break;
717
+ const kept = size.workspace === protectedRoot ? "the triggering workspace is protected" : size.blocked;
718
+ if (kept) {
719
+ skips.push({
720
+ target: size.dir,
721
+ reason: kept,
722
+ ...size.workspace ? { workspace: size.workspace } : {}
723
+ });
724
+ continue;
725
+ }
726
+ const bytes = kind === "would-trim-cache" ? Math.round(Math.min(size.bytes, remaining - targetBytes)) : size.bytes;
727
+ if (!add({
728
+ kind,
729
+ target: size.workspace ?? size.dir,
730
+ bytes,
731
+ reason: `${!size.workspace || size.idleDays == null ? "" : `idle ${size.idleDays} days, `}${why}`,
732
+ ...size.workspace ? { workspace: size.workspace } : {},
733
+ ...kind === "would-clear-outputs" ? {} : { dir: size.dir }
734
+ })) continue;
735
+ remaining -= bytes;
736
+ }
737
+ if (remaining > targetBytes) blocked.push(`${why}; eligible targets cannot reach the target`);
738
+ }
739
+ if (pressure?.memory.pressured) skips.push({
740
+ target: "memory",
741
+ reason: "memory pressure observed; automatic maintenance does not stop helpers or idle workspaces yet"
742
+ });
743
+ return {
744
+ actions,
745
+ blocked,
746
+ skips
747
+ };
748
+ }
749
+ //#endregion
750
+ //#region src/maintenance/sweep.ts
751
+ function planSweep({ settings, sizes, protectedRoot, pinned, now }) {
752
+ const actions = [];
753
+ const skips = [];
754
+ const blocked = [];
755
+ const days = settings.olderThanDays;
756
+ for (const entry of collectWorkspaceOutputs({
757
+ olderThan: days,
758
+ now,
759
+ measure: false
760
+ }).workspaces) {
761
+ const root = entry.projectRoot === null ? null : canonicalPath(entry.projectRoot);
762
+ if (root === null || !entry.willClear || root === protectedRoot) continue;
763
+ if (pinned(root)) {
764
+ skips.push({
765
+ target: root,
766
+ reason: "pinned by maintenance.keep",
767
+ workspace: root
768
+ });
769
+ continue;
770
+ }
771
+ const size = sizes.find((candidate) => candidate.workspace === root && candidate.category === "workspace-outputs");
772
+ actions.push({
773
+ kind: "would-clear-outputs",
774
+ target: root,
775
+ workspace: root,
776
+ bytes: size?.bytes ?? 0,
777
+ olderThanDays: days,
778
+ reason: `idle ${entry.idleDays} days, older than ${days} days (age sweep)`,
779
+ check: "sweep"
780
+ });
781
+ }
782
+ for (const cache of trimmableCaches().filter((candidate) => !isInsideWorkspaces(candidate.dir))) actions.push({
783
+ kind: "would-trim-cache",
784
+ target: cacheLabel(cache),
785
+ dir: cache.dir,
786
+ bytes: 0,
787
+ olderThanDays: days,
788
+ reason: `entries unused for ${days} days (age sweep)`,
789
+ check: "sweep"
790
+ });
791
+ try {
792
+ const orphans = collectOrphanedWorkspaces(Object.keys(loadConfig$1()?.projects ?? {}), listMountedVolumes(), { measure: false });
793
+ for (const orphan of orphans.orphaned) actions.push({
794
+ kind: "would-remove-orphan",
795
+ target: orphan.dir,
796
+ bytes: orphan.bytes ?? 0,
797
+ reason: `its project ${orphan.projectRoot} no longer exists`,
798
+ check: "sweep"
799
+ });
800
+ for (const kept of orphans.skipped) skips.push({
801
+ target: kept.dir,
802
+ reason: kept.reason
803
+ });
804
+ } catch (error) {
805
+ blocked.push(`Could not look for orphaned workspace directories: ${error instanceof Error ? error.message : error}`);
806
+ }
807
+ const mounted = listMountedVolumes();
808
+ for (const cache of readManifest().caches) {
809
+ if (!isAbsolute(cache.dir) || existsSync(cache.dir) || !isOnMountedVolume(cache.dir, mounted)) continue;
810
+ actions.push({
811
+ kind: "would-unregister-cache",
812
+ target: cache.dir,
813
+ dir: cache.dir,
814
+ bytes: 0,
815
+ reason: "its directory no longer exists",
816
+ check: "sweep"
817
+ });
818
+ }
819
+ return {
820
+ actions,
821
+ blocked,
822
+ skips
823
+ };
824
+ }
825
+ async function planWorktrees({ protectedRoot, pinned, now }) {
826
+ const sweep = await collectWorktreeSweep({
827
+ idle: false,
828
+ olderThan: null,
829
+ now
830
+ });
831
+ const actions = [];
832
+ const skips = [];
833
+ const keep = [];
834
+ for (const worktree of sweep.worktrees) {
835
+ if (worktree.skipped) continue;
836
+ const path = canonicalPath(worktree.path);
837
+ 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;
838
+ if (reason) {
839
+ skips.push({
840
+ target: worktree.path,
841
+ reason
842
+ });
843
+ continue;
844
+ }
845
+ keep.push(worktree);
846
+ actions.push({
847
+ kind: "would-remove-worktree",
848
+ target: worktree.path,
849
+ bytes: 0,
850
+ reason: worktreeRemovalReason(worktree),
851
+ check: "worktree"
852
+ });
853
+ }
854
+ return {
855
+ actions,
856
+ blocked: [],
857
+ skips,
858
+ sweep: {
859
+ ...sweep,
860
+ worktrees: keep
861
+ }
862
+ };
863
+ }
864
+ //#endregion
865
+ //#region src/maintenance/preview.ts
866
+ function triggeringRoot() {
867
+ return canonicalPath(findProjectRoot(process.cwd()) ?? join(configDir(), "maintenance", "no-project"));
868
+ }
869
+ async function plannedMaintenance(pressure, sizes, settings, { devices = true, sweep = false, worktrees = false } = {}) {
870
+ const resolved = resolveBudget();
871
+ if (resolved.error) throw new Error(resolved.error);
872
+ const budget = {
873
+ ...resolved.budget,
874
+ maxCommittedMemoryMb: 0,
875
+ maxLiveWorkspaces: 0
876
+ };
877
+ const root = triggeringRoot();
878
+ const floor = Math.max(budget.minFreeDiskMb, budget.hardFloorDiskMb);
879
+ const low = pressure?.disk.some((disk) => disk.freeMb < floor);
880
+ const outcome = low ? await enforceBudget({
881
+ root,
882
+ note: () => {},
883
+ dryRun: true,
884
+ budget
885
+ }, { volumes: () => pressure.disk }) : null;
886
+ if (outcome && outcome.status !== "ok") throw new Error(outcome.refusal.message);
887
+ const outputs = collectWorkspaceOutputs({
888
+ olderThan: null,
889
+ now: Date.now(),
890
+ measure: false
891
+ });
892
+ const result = plan({
893
+ pressure,
894
+ sizes: sizes.map((size) => {
895
+ if (size.category === "compilation-cache") return {
896
+ ...size,
897
+ blocked: cacheBlocked(size)
898
+ };
899
+ if (!size.workspace) return size;
900
+ const current = outputs.workspaces.find((entry) => entry.projectRoot && canonicalPath(entry.projectRoot) === size.workspace);
901
+ return Object.assign({}, size, { blocked: current?.willClear ? void 0 : current?.keptReason ?? "workspace outputs cannot be resolved" });
902
+ }),
903
+ settings,
904
+ budget,
905
+ diskSteps: outcome?.status === "ok" ? outcome.reclaimed.filter((step) => devices || step.step !== "idle-devices") : [],
906
+ protectedRoot: root,
907
+ scoped: Boolean(process.env.STIM_HOME),
908
+ projects: Object.keys(loadConfig()?.projects ?? {}).map(canonicalPath),
909
+ pinned: projectMaintenancePinned,
910
+ recentlyUsed: (workspace) => recentUse(workspace, settings)
911
+ });
912
+ const merge = (extra) => {
913
+ for (const action of extra.actions) if (!result.actions.some((entry) => entry.kind === action.kind && entry.target === action.target)) result.actions.push(action);
914
+ result.blocked.push(...extra.blocked);
915
+ result.skips.push(...extra.skips);
916
+ };
917
+ if (sweep) merge(planSweep({
918
+ settings,
919
+ sizes,
920
+ protectedRoot: root,
921
+ pinned: projectMaintenancePinned,
922
+ now: Date.now()
923
+ }));
924
+ if (worktrees) {
925
+ const planned = await planWorktrees({
926
+ protectedRoot: root,
927
+ pinned: projectMaintenancePinned,
928
+ now: Date.now()
929
+ });
930
+ merge(planned);
931
+ result.worktreeSweep = planned.sweep;
932
+ }
933
+ if (low) result.skips.push(...outputs.workspaces.filter((entry) => !entry.willClear && entry.keptReason).map((entry) => ({
934
+ target: entry.dir,
935
+ reason: entry.keptReason,
936
+ workspace: entry.projectRoot ?? void 0
937
+ })));
938
+ return result;
939
+ }
940
+ async function previewMaintenance({ devices = true } = {}) {
941
+ let settings;
942
+ try {
943
+ settings = resolveMaintenanceSettings();
944
+ const state = readMaintenanceState();
945
+ if (settings.invalid && settings.mode === "off") return {
946
+ mode: "off",
947
+ pressure: null,
948
+ actions: [],
949
+ blocked: [],
950
+ skips: [],
951
+ invalid: settings.invalid,
952
+ note: settings.invalid
953
+ };
954
+ if (settings.mode === "off") return {
955
+ mode: "off",
956
+ pressure: null,
957
+ actions: [],
958
+ blocked: [],
959
+ skips: [],
960
+ note: "maintenance.mode is off"
961
+ };
962
+ const pressure = measurePressure(settings, state?.pressure ?? null, Date.now());
963
+ return {
964
+ ...await plannedMaintenance(pressure, state?.sizes ?? [], settings, {
965
+ devices,
966
+ sweep: true
967
+ }),
968
+ mode: settings.mode,
969
+ ...settings.invalid ? { invalid: settings.invalid } : {},
970
+ pressure,
971
+ note: settings.invalid ?? (state === null ? "no pass has run yet; sizes have not been measured" : null)
972
+ };
973
+ } catch (error) {
974
+ return {
975
+ mode: settings?.mode ?? "off",
976
+ ...settings?.invalid ? { invalid: settings.invalid } : {},
977
+ pressure: null,
978
+ actions: [],
979
+ blocked: [String(error)],
980
+ skips: [],
981
+ note: "maintenance preview failed"
982
+ };
983
+ }
984
+ }
985
+ //#endregion
986
+ export { recentUse as a, worktreePullRequestNote as c, measureDisk as d, measurePressure as f, cacheEntryProtection as i, worktreeRemovalReason as l, sizeScanDeferred as m, previewMaintenance as n, collectWorktreeSweep as o, measureSizes as p, triggeringRoot as r, removeWorktrees as s, plannedMaintenance as t, cacheBlocked as u };