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