@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0f07274d438b

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 (260) hide show
  1. package/README.md +128 -4
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +29 -12
  17. package/dist/bridge/bridge.service.js +215 -380
  18. package/dist/bridge/bridge.types.d.ts +21 -0
  19. package/dist/bridge/bridge.types.js +2 -1
  20. package/dist/bridge/default-session-service.d.ts +13 -0
  21. package/dist/bridge/default-session-service.js +22 -0
  22. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  23. package/dist/bridge/dispatch-offer-policy.js +58 -0
  24. package/dist/bridge/in-flight-registry.d.ts +62 -0
  25. package/dist/bridge/in-flight-registry.js +207 -0
  26. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  27. package/dist/bridge/readiness-result-outbox.js +20 -0
  28. package/dist/bridge/runner-host-capabilities.js +14 -1
  29. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  30. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  31. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  32. package/dist/bridge/windows-bash-resolution.js +153 -0
  33. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  34. package/dist/cleanup/cleanup-wip.js +66 -0
  35. package/dist/cleanup/cleanup.service.d.ts +11 -1
  36. package/dist/cleanup/cleanup.service.js +80 -62
  37. package/dist/cleanup/cleanup.types.d.ts +2 -0
  38. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  39. package/dist/cleanup/forge-owned-paths.js +9 -0
  40. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  41. package/dist/cleanup/host-runtime-ledger.js +30 -9
  42. package/dist/cli/cli.help.js +57 -13
  43. package/dist/cli/cli.service.d.ts +3 -10
  44. package/dist/cli/cli.service.js +20 -213
  45. package/dist/cli/idle-status.d.ts +84 -0
  46. package/dist/cli/idle-status.js +181 -0
  47. package/dist/cli/local-config.d.ts +14 -1
  48. package/dist/cli/local-config.js +42 -2
  49. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  50. package/dist/cli/provider-cli-advertising.js +88 -0
  51. package/dist/cli/provider-cli-detection.d.ts +10 -0
  52. package/dist/cli/provider-cli-detection.js +160 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  55. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  56. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  57. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  58. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  59. package/dist/runtime/attempt-process-supervisor.js +12 -6
  60. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  61. package/dist/runtime/docker-engine-probe.js +7 -0
  62. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  63. package/dist/runtime/dotnet-build-outputs.js +402 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  66. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  67. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +5 -0
  71. package/dist/runtime/host-load-capacity.d.ts +198 -0
  72. package/dist/runtime/host-load-capacity.js +353 -0
  73. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  74. package/dist/runtime/host-load-child-environment.js +35 -1
  75. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  76. package/dist/runtime/host-load-governor-config.js +24 -3
  77. package/dist/runtime/host-load-governor.d.ts +91 -2
  78. package/dist/runtime/host-load-governor.js +217 -18
  79. package/dist/runtime/host-load-ledger-lock.js +6 -4
  80. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  81. package/dist/runtime/host-load-live-test-slots.js +193 -0
  82. package/dist/runtime/host-load-runtime-settings.js +4 -2
  83. package/dist/runtime/host-load-sampler.d.ts +25 -1
  84. package/dist/runtime/host-load-sampler.js +38 -7
  85. package/dist/runtime/host-load-step-run.d.ts +37 -3
  86. package/dist/runtime/host-load-step-run.js +63 -7
  87. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  88. package/dist/runtime/host-load-test-slot.js +26 -7
  89. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  90. package/dist/runtime/host-runtime-contract.js +35 -5
  91. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  92. package/dist/runtime/host-runtime-lease.js +140 -296
  93. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  94. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  95. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  96. package/dist/runtime/host-runtime-promotion.js +307 -14
  97. package/dist/runtime/managed-command-teardown.js +5 -16
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  101. package/dist/runtime/prepared-runtime-identity.js +130 -9
  102. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  103. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  104. package/dist/runtime/runner-settings.d.ts +4 -0
  105. package/dist/runtime/runner-settings.js +22 -0
  106. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  107. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  108. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  109. package/dist/sandbox/host-capacity-broker.js +4 -2
  110. package/dist/sandbox/managed-branch.d.ts +13 -0
  111. package/dist/sandbox/managed-branch.js +90 -0
  112. package/dist/sandbox/provider-auth/codex.js +11 -11
  113. package/dist/sandbox/runtime.d.ts +1 -2
  114. package/dist/sandbox/runtime.js +9 -19
  115. package/dist/sandbox/sandbox-input.d.ts +22 -0
  116. package/dist/sandbox/sandbox-input.js +49 -0
  117. package/dist/sandbox/workspace.service.js +15 -2
  118. package/dist/session/managed-attempt-tools.d.ts +0 -7
  119. package/dist/session/managed-attempt-tools.js +54 -109
  120. package/dist/session/managed-build-coordinator.d.ts +16 -0
  121. package/dist/session/managed-build-coordinator.js +10 -0
  122. package/dist/session/managed-build-receipt.d.ts +7 -0
  123. package/dist/session/managed-build-receipt.js +11 -3
  124. package/dist/session/managed-command-environment.d.ts +8 -0
  125. package/dist/session/managed-command-environment.js +28 -0
  126. package/dist/session/managed-command-host-load.d.ts +10 -5
  127. package/dist/session/managed-command-host-load.js +18 -14
  128. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  129. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  130. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  131. package/dist/session/phase-completion.artifacts.js +65 -166
  132. package/dist/session/phase-completion.d.ts +27 -2
  133. package/dist/session/phase-completion.helpers.js +5 -53
  134. package/dist/session/phase-completion.js +15 -32
  135. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  136. package/dist/session/phase-completion.mcp-args.js +195 -0
  137. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  138. package/dist/session/phase-completion.phase-aliases.js +43 -0
  139. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  140. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  141. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  142. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  143. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  144. package/dist/session/phase-completion.pr-review.js +294 -0
  145. package/dist/session/phase-completion.prompts.d.ts +1 -1
  146. package/dist/session/phase-completion.prompts.js +14 -0
  147. package/dist/session/phase-completion.runtime.d.ts +8 -9
  148. package/dist/session/phase-completion.runtime.js +65 -196
  149. package/dist/session/phase-completion.schemas.js +12 -2
  150. package/dist/session/phase-completion.validation.d.ts +1 -0
  151. package/dist/session/phase-completion.validation.js +9 -1
  152. package/dist/session/pr-review-diff-base.d.ts +18 -0
  153. package/dist/session/pr-review-diff-base.js +44 -0
  154. package/dist/session/pr-review-placement.d.ts +50 -0
  155. package/dist/session/pr-review-placement.js +91 -0
  156. package/dist/session/pre-publication-change-set.d.ts +62 -0
  157. package/dist/session/pre-publication-change-set.js +166 -0
  158. package/dist/session/pre-publication-host-load.js +6 -5
  159. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  160. package/dist/session/pre-publication-native-postgres.js +111 -0
  161. package/dist/session/pre-publication-process.js +13 -12
  162. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  163. package/dist/session/pre-publication-step-execution.js +6 -5
  164. package/dist/session/pre-publication-validation.d.ts +9 -4
  165. package/dist/session/pre-publication-validation.js +62 -65
  166. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  167. package/dist/session/provider-cli/claude-background-work.js +4 -3
  168. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  169. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  170. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  171. package/dist/session/provider-cli/host-build-lock.js +30 -0
  172. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  173. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  174. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  175. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  176. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  177. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  178. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  179. package/dist/session/provider-cli/pre-publication-repair.js +41 -3
  180. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  181. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  182. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  183. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  184. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  185. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  186. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  189. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +13 -3
  191. package/dist/session/provider-cli/provider-cli.prompts.js +137 -84
  192. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  193. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +37 -2
  196. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  197. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  198. package/dist/session/provider-cli/provider-cli.service.d.ts +15 -18
  199. package/dist/session/provider-cli/provider-cli.service.js +59 -190
  200. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  204. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  205. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  206. package/dist/session/qa-sidecar-validation.js +28 -0
  207. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  208. package/dist/session/sandbox-host-capacity-gate.js +63 -22
  209. package/dist/session/session-host-project.d.ts +22 -0
  210. package/dist/session/session-host-project.js +98 -0
  211. package/dist/session/session-redaction.js +31 -181
  212. package/dist/session/session.parse-helpers.d.ts +10 -0
  213. package/dist/session/session.parse-helpers.js +84 -0
  214. package/dist/session/session.runtime-refresh.d.ts +46 -0
  215. package/dist/session/session.runtime-refresh.js +116 -0
  216. package/dist/session/session.service.d.ts +8 -1
  217. package/dist/session/session.service.js +177 -239
  218. package/dist/session/session.types.d.ts +5 -0
  219. package/dist/session/session.types.js +9 -79
  220. package/dist/session/session.types.pr-review.d.ts +48 -0
  221. package/dist/session/session.types.pr-review.js +51 -0
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/shared/fs/file-identity.d.ts +10 -0
  225. package/dist/shared/fs/file-identity.js +15 -0
  226. package/dist/shared/fs/replace-file.d.ts +7 -0
  227. package/dist/shared/fs/replace-file.js +33 -0
  228. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  229. package/dist/shared/process/host-process-recovery.js +23 -3
  230. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  231. package/dist/shared/process/host-process-supervisor.js +66 -14
  232. package/dist/shared/provider-capabilities.d.ts +2 -0
  233. package/dist/shared/provider-capabilities.js +18 -1
  234. package/dist/version.d.ts +1 -1
  235. package/dist/version.js +1 -1
  236. package/dist/worktree/artifact-injector.js +24 -0
  237. package/dist/worktree/orphan-relink.d.ts +19 -0
  238. package/dist/worktree/orphan-relink.js +106 -0
  239. package/dist/worktree/wip-git.d.ts +58 -0
  240. package/dist/worktree/wip-git.js +182 -0
  241. package/dist/worktree/wip-refs.d.ts +85 -0
  242. package/dist/worktree/wip-refs.js +169 -0
  243. package/dist/worktree/wip-restore.d.ts +51 -0
  244. package/dist/worktree/wip-restore.js +324 -0
  245. package/dist/worktree/wip-snapshot.d.ts +53 -0
  246. package/dist/worktree/wip-snapshot.js +270 -0
  247. package/dist/worktree/worktree-inputs.d.ts +8 -0
  248. package/dist/worktree/worktree-inputs.js +134 -0
  249. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  250. package/dist/worktree/worktree-origin-sync.js +128 -0
  251. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  252. package/dist/worktree/worktree-wip-events.js +148 -0
  253. package/dist/worktree/worktree-wip.d.ts +57 -0
  254. package/dist/worktree/worktree-wip.js +200 -0
  255. package/dist/worktree/worktree.base.d.ts +7 -1
  256. package/dist/worktree/worktree.service.d.ts +49 -5
  257. package/dist/worktree/worktree.service.js +223 -187
  258. package/dist/worktree/worktree.types.d.ts +47 -0
  259. package/package.json +1 -1
  260. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -0,0 +1,150 @@
1
+ import { formatBytes } from "../shared/format/format-bytes.js";
2
+ import { validateSandboxContract } from "../sandbox/contract.js";
3
+ import { runSandboxProcess } from "../sandbox/process.js";
4
+ import { selectSandboxConfigRefs } from "../sandbox/runtime.js";
5
+ import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
6
+ export function canReserveSandboxResources(used, requested, capacity) {
7
+ return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
8
+ && used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
9
+ && used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
10
+ && used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
11
+ && used.pids + requested.pids <= capacity.pids
12
+ && used.buildSlots + requested.buildSlots <= capacity.buildSlots;
13
+ }
14
+ export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
15
+ const ambientCapacity = preflight.availableMemoryBytes
16
+ - preflight.hostReserveBytes
17
+ + activeMemoryBytes;
18
+ const commitmentCapacity = preflight.totalMemoryBytes
19
+ - preflight.hostReserveBytes;
20
+ return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
21
+ }
22
+ export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
23
+ const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
24
+ if (requested.sandboxSlots > availableSlots) {
25
+ return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
26
+ }
27
+ const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
28
+ if (requested.memoryBytes > availableMemoryBytes) {
29
+ return [
30
+ `Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
31
+ `(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
32
+ `but ${formatBytes(availableMemoryBytes)} is available for admission.`,
33
+ `Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
34
+ `Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
35
+ ].join(" ");
36
+ }
37
+ const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
38
+ if (requested.cpuMillis > availableCpuMillis) {
39
+ return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
40
+ }
41
+ const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
42
+ if (requested.workspaceBytes > availableWorkspaceBytes) {
43
+ return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
44
+ }
45
+ const availablePids = Math.max(0, capacity.pids - used.pids);
46
+ if (requested.pids > availablePids) {
47
+ return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
48
+ }
49
+ const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
50
+ return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
51
+ }
52
+ export function sumSandboxResources(resources) {
53
+ return resources.reduce((total, resource) => ({
54
+ sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
55
+ cpuMillis: total.cpuMillis + resource.cpuMillis,
56
+ workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
57
+ serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
58
+ runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
59
+ memoryBytes: total.memoryBytes + resource.memoryBytes,
60
+ workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
61
+ pids: total.pids + resource.pids,
62
+ buildSlots: total.buildSlots + resource.buildSlots
63
+ }), zeroSandboxResources());
64
+ }
65
+ export function zeroSandboxResources() {
66
+ return {
67
+ sandboxSlots: 0,
68
+ cpuMillis: 0,
69
+ workerMemoryLimitBytes: 0,
70
+ serviceMemoryLimitBytes: 0,
71
+ runtimeOverheadBytes: 0,
72
+ memoryBytes: 0,
73
+ workspaceBytes: 0,
74
+ pids: 0,
75
+ buildSlots: 0,
76
+ };
77
+ }
78
+ export function defaultSandboxResources() {
79
+ return {
80
+ sandboxSlots: 1,
81
+ cpuMillis: 2000,
82
+ workerMemoryLimitBytes: 2 * 1024 ** 3,
83
+ serviceMemoryLimitBytes: 0,
84
+ runtimeOverheadBytes: 128 * 1024 ** 2,
85
+ memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
86
+ workspaceBytes: 10 * 1024 ** 3,
87
+ pids: 512,
88
+ buildSlots: 0
89
+ };
90
+ }
91
+ export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
92
+ const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
93
+ const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
94
+ + (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
95
+ return {
96
+ ...requested,
97
+ serviceMemoryLimitBytes,
98
+ runtimeOverheadBytes,
99
+ memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
100
+ };
101
+ }
102
+ export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
103
+ const repoPath = dispatch.repo.serverLocalPath;
104
+ const sandbox = dispatch.sandbox;
105
+ if (!repoPath || !sandbox) {
106
+ throw new Error("Sandbox admission needs a mapped repository.");
107
+ }
108
+ const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
109
+ const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
110
+ if (!configCommitSha) {
111
+ throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
112
+ }
113
+ const contractResult = await runSandboxProcess({
114
+ command: "git",
115
+ args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
116
+ timeoutMs: 30_000,
117
+ maxOutputBytes: 1024 * 1024,
118
+ });
119
+ if (contractResult.exitCode !== 0) {
120
+ throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
121
+ }
122
+ const contract = validateSandboxContract(contractResult.stdout);
123
+ const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
124
+ role: dispatch.execution.role,
125
+ serviceCount: contract.contract.services.length,
126
+ browser: contract.contract.browser,
127
+ });
128
+ return {
129
+ resources: resolveDynamicSandboxResources({
130
+ ...sandbox.requestedResources,
131
+ workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
132
+ }, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
133
+ sandboxConfigCommitSha: configCommitSha,
134
+ };
135
+ }
136
+ async function resolveFirstGitCommit(repoPath, refs) {
137
+ for (const ref of refs) {
138
+ const result = await runSandboxProcess({
139
+ command: "git",
140
+ args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
141
+ timeoutMs: 30_000,
142
+ maxOutputBytes: 1024 * 1024,
143
+ });
144
+ const commitSha = result.stdout.trim().toLowerCase();
145
+ if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
146
+ return commitSha;
147
+ }
148
+ }
149
+ return null;
150
+ }
@@ -0,0 +1,31 @@
1
+ /** Environment variables that name the bash the bridge should use on Windows, in priority order. */
2
+ export declare const WINDOWS_BASH_OVERRIDE_VARIABLES: readonly ["FORGE_BRIDGE_BASH_PATH", "CLAUDE_CODE_GIT_BASH_PATH"];
3
+ export interface BashResolutionInput {
4
+ readonly platform: NodeJS.Platform;
5
+ readonly env: NodeJS.ProcessEnv;
6
+ /** Output of `git --exec-path`, or null when git is unavailable. Called only on Windows. */
7
+ readonly gitExecPath: () => Promise<string | null>;
8
+ readonly fileExists?: (candidate: string) => boolean;
9
+ }
10
+ export interface BashResolution {
11
+ /** What to run: "bash" off Windows, an absolute bash.exe path on Windows, or null when none was found. */
12
+ readonly executable: string | null;
13
+ /** Why the result is not what the host may expect (an override was rejected, nothing was found). */
14
+ readonly warning?: string;
15
+ }
16
+ /**
17
+ * Picks the bash the bridge runs. Off Windows this is plain `bash` from PATH, unchanged.
18
+ *
19
+ * On Windows a bare `bash` is not safe: libuv's executable search looks in the current directory
20
+ * before PATH (unless `NoDefaultCurrentDirectoryInExePath` is set), and a scheduled task with no
21
+ * working directory starts in `C:\Windows\System32`, so `bash` becomes WSL's `System32\bash.exe`
22
+ * even with Git Bash first on PATH. The bridge therefore resolves Git for Windows' bash.exe to an
23
+ * absolute path and never accepts the WSL launcher or a Store app-execution alias.
24
+ */
25
+ export declare function resolveBashExecutable(input: BashResolutionInput): Promise<BashResolution>;
26
+ /** True for WSL's bash.exe launcher (System32, SysWOW64, Sysnative) and for Store app-execution aliases. */
27
+ export declare function isRejectedWindowsBash(candidate: string, env: NodeJS.ProcessEnv): boolean;
28
+ /** `git --exec-path` is `<root>/mingw64/libexec/git-core` (or clangarm64, mingw32) on Git for Windows. */
29
+ export declare function gitRootFromExecPath(execPath: string | null): string | null;
30
+ /** git.exe lives in `<root>\cmd`, `<root>\bin` or `<root>\mingw64\bin` on Git for Windows. */
31
+ export declare function gitRootFromGitExecutable(gitExecutable: string | null): string | null;
@@ -0,0 +1,153 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isWindowsAppExecutionAliasPath } from "../shared/process/windows-launch.js";
4
+ /** Environment variables that name the bash the bridge should use on Windows, in priority order. */
5
+ export const WINDOWS_BASH_OVERRIDE_VARIABLES = ["FORGE_BRIDGE_BASH_PATH", "CLAUDE_CODE_GIT_BASH_PATH"];
6
+ /**
7
+ * Picks the bash the bridge runs. Off Windows this is plain `bash` from PATH, unchanged.
8
+ *
9
+ * On Windows a bare `bash` is not safe: libuv's executable search looks in the current directory
10
+ * before PATH (unless `NoDefaultCurrentDirectoryInExePath` is set), and a scheduled task with no
11
+ * working directory starts in `C:\Windows\System32`, so `bash` becomes WSL's `System32\bash.exe`
12
+ * even with Git Bash first on PATH. The bridge therefore resolves Git for Windows' bash.exe to an
13
+ * absolute path and never accepts the WSL launcher or a Store app-execution alias.
14
+ */
15
+ export async function resolveBashExecutable(input) {
16
+ if (input.platform !== "win32")
17
+ return { executable: "bash" };
18
+ const fileExists = input.fileExists ?? defaultFileExists;
19
+ const env = input.env;
20
+ // Relative candidates (a "." PATH entry, a relative override) would put the cwd lookup back.
21
+ const accept = (candidate) => Boolean(candidate)
22
+ && isAbsoluteWindowsPath(candidate)
23
+ && !isRejectedWindowsBash(candidate, env)
24
+ && fileExists(candidate);
25
+ for (const name of WINDOWS_BASH_OVERRIDE_VARIABLES) {
26
+ const raw = environmentValue(env, name)?.trim().replace(/^"|"$/gu, "");
27
+ if (!raw)
28
+ continue;
29
+ if (accept(raw))
30
+ return { executable: path.win32.normalize(raw) };
31
+ const reason = !isAbsoluteWindowsPath(raw)
32
+ ? "is not an absolute path"
33
+ : isRejectedWindowsBash(raw, env)
34
+ ? "points at the WSL launcher or a Store alias, not Git Bash"
35
+ : "does not exist";
36
+ return { executable: null, warning: `${name}=${raw} ${reason}; bash is reported unavailable.` };
37
+ }
38
+ const pathValue = environmentValue(env, "PATH") ?? "";
39
+ const gitRoots = [
40
+ gitRootFromExecPath(await input.gitExecPath().catch(() => null)),
41
+ gitRootFromGitExecutable(findOnWindowsPath(pathValue, "git.exe", fileExists)),
42
+ ];
43
+ for (const root of gitRoots) {
44
+ if (!root)
45
+ continue;
46
+ for (const candidate of gitBashCandidates(root)) {
47
+ if (accept(candidate))
48
+ return { executable: candidate };
49
+ }
50
+ }
51
+ for (const directory of windowsPathDirectories(pathValue)) {
52
+ const candidate = path.win32.join(directory, "bash.exe");
53
+ if (accept(candidate))
54
+ return { executable: candidate };
55
+ }
56
+ for (const root of standardGitRoots(env)) {
57
+ for (const candidate of gitBashCandidates(root)) {
58
+ if (accept(candidate))
59
+ return { executable: candidate };
60
+ }
61
+ }
62
+ return {
63
+ executable: null,
64
+ warning: "Git Bash (bash.exe from Git for Windows) was not found; bash is reported unavailable. "
65
+ + "Install Git for Windows or set FORGE_BRIDGE_BASH_PATH to its bin\\bash.exe.",
66
+ };
67
+ }
68
+ /** True for WSL's bash.exe launcher (System32, SysWOW64, Sysnative) and for Store app-execution aliases. */
69
+ export function isRejectedWindowsBash(candidate, env) {
70
+ if (isWindowsAppExecutionAliasPath(candidate))
71
+ return true;
72
+ const normalized = path.win32.normalize(candidate).toLowerCase();
73
+ if (path.win32.basename(normalized) !== "bash.exe" && path.win32.basename(normalized) !== "bash")
74
+ return false;
75
+ const directory = path.win32.dirname(normalized);
76
+ const systemRoot = (environmentValue(env, "SystemRoot") ?? environmentValue(env, "windir") ?? "C:\\Windows").toLowerCase();
77
+ const systemDirectories = ["system32", "syswow64", "sysnative"].map(name => path.win32.join(systemRoot, name));
78
+ return systemDirectories.includes(directory) || /\\windows\\(system32|syswow64|sysnative)$/u.test(directory);
79
+ }
80
+ /** `git --exec-path` is `<root>/mingw64/libexec/git-core` (or clangarm64, mingw32) on Git for Windows. */
81
+ export function gitRootFromExecPath(execPath) {
82
+ const trimmed = execPath?.trim();
83
+ if (!trimmed)
84
+ return null;
85
+ const normalized = path.win32.normalize(trimmed);
86
+ const libexec = normalized.toLowerCase().lastIndexOf("\\libexec");
87
+ if (libexec <= 0)
88
+ return null;
89
+ return path.win32.dirname(normalized.slice(0, libexec));
90
+ }
91
+ /** git.exe lives in `<root>\cmd`, `<root>\bin` or `<root>\mingw64\bin` on Git for Windows. */
92
+ export function gitRootFromGitExecutable(gitExecutable) {
93
+ if (!gitExecutable)
94
+ return null;
95
+ const directory = path.win32.dirname(path.win32.normalize(gitExecutable));
96
+ const leaf = path.win32.basename(directory).toLowerCase();
97
+ if (leaf === "cmd")
98
+ return path.win32.dirname(directory);
99
+ if (leaf === "bin") {
100
+ const parent = path.win32.dirname(directory);
101
+ return /^(mingw64|mingw32|clangarm64|usr)$/u.test(path.win32.basename(parent).toLowerCase())
102
+ ? path.win32.dirname(parent)
103
+ : parent;
104
+ }
105
+ return null;
106
+ }
107
+ /** A drive-letter (`C:\...`) or UNC path; rooted-but-driveless (`\bin`) and relative paths are not. */
108
+ function isAbsoluteWindowsPath(candidate) {
109
+ return /^[a-z]:[\\/]/iu.test(candidate) || /^[\\/]{2}[^\\/]/u.test(candidate);
110
+ }
111
+ // path.win32 and ";" rather than the host's path module, so the Windows rules are testable anywhere.
112
+ function windowsPathDirectories(pathValue) {
113
+ return pathValue.split(";").map(entry => entry.trim().replace(/^"|"$/gu, "")).filter(Boolean);
114
+ }
115
+ function findOnWindowsPath(pathValue, fileName, fileExists) {
116
+ for (const directory of windowsPathDirectories(pathValue)) {
117
+ const candidate = path.win32.join(directory, fileName);
118
+ if (!isWindowsAppExecutionAliasPath(candidate) && fileExists(candidate))
119
+ return candidate;
120
+ }
121
+ return null;
122
+ }
123
+ function gitBashCandidates(root) {
124
+ return [path.win32.join(root, "bin", "bash.exe"), path.win32.join(root, "usr", "bin", "bash.exe")];
125
+ }
126
+ function standardGitRoots(env) {
127
+ const roots = [
128
+ environmentValue(env, "ProgramFiles"),
129
+ environmentValue(env, "ProgramW6432"),
130
+ environmentValue(env, "ProgramFiles(x86)"),
131
+ ].filter((value) => Boolean(value)).map(value => path.win32.join(value, "Git"));
132
+ const localAppData = environmentValue(env, "LOCALAPPDATA");
133
+ if (localAppData)
134
+ roots.push(path.win32.join(localAppData, "Programs", "Git"));
135
+ roots.push("C:\\Program Files\\Git");
136
+ const seen = new Set();
137
+ return roots.filter(root => !seen.has(root.toLowerCase()) && Boolean(seen.add(root.toLowerCase())));
138
+ }
139
+ /** Windows environment keys are case-insensitive ("Path"), but a copied env object is not. */
140
+ function environmentValue(env, name) {
141
+ if (env[name] !== undefined)
142
+ return env[name];
143
+ const key = Object.keys(env).find(candidate => candidate.toLowerCase() === name.toLowerCase());
144
+ return key === undefined ? undefined : env[key];
145
+ }
146
+ function defaultFileExists(candidate) {
147
+ try {
148
+ return fs.statSync(candidate).isFile();
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ }
@@ -0,0 +1,12 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ export type CandidateWipOutcome = {
3
+ readonly status: "exempt" | "clean";
4
+ } | {
5
+ readonly status: "saved";
6
+ readonly ref: string;
7
+ } | {
8
+ readonly status: "failed";
9
+ readonly reason: string;
10
+ };
11
+ /** Saves a stale candidate's uncommitted work. Never throws: a failure means "keep the folder". */
12
+ export declare function saveStaleWorktreeWork(git: GitClient, repoPath: string, worktreeRoot: string, candidate: string): Promise<CandidateWipOutcome>;
@@ -0,0 +1,66 @@
1
+ import path from "node:path";
2
+ import { preserveWorktreeWip } from "../worktree/wip-snapshot.js";
3
+ import { isPrReviewWorktreeKey, isRuntimeReadinessName } from "./forge-owned-paths.js";
4
+ import { isForgeManagedWorkBranch } from "./managed-branch-sweep.js";
5
+ // Cleanup removes stale Forge worktrees: folders whose Git registration is gone (or prunable) and
6
+ // that no lease owns. Such a folder can still hold a session's uncommitted work (the #558 loss:
7
+ // six staged review fixes in a story worktree that cleanup deleted). Before one is removed, its
8
+ // work is saved to the branch's WIP ref; when that fails, the folder is kept and the reason given.
9
+ const releaseSuffix = /\.forge-release-[0-9a-f-]{36}$/u;
10
+ /** Saves a stale candidate's uncommitted work. Never throws: a failure means "keep the folder". */
11
+ export async function saveStaleWorktreeWork(git, repoPath, worktreeRoot, candidate) {
12
+ const branchName = candidateBranch(worktreeRoot, candidate);
13
+ // A readiness probe never runs an agent, and a review only reads: there is no work of anyone's in either.
14
+ if (isRuntimeReadinessName(branchName) || isPrReviewWorktreeKey(branchName))
15
+ return { status: "exempt" };
16
+ try {
17
+ const result = await snapshotCandidate(git, repoPath, candidate, branchName);
18
+ return result.status === "clean" ? { status: "clean" } : { status: "saved", ref: result.ref };
19
+ }
20
+ catch (error) {
21
+ return { status: "failed", reason: error instanceof Error ? error.message : String(error) };
22
+ }
23
+ }
24
+ async function snapshotCandidate(git, repoPath, candidate, branchName) {
25
+ const restorable = isForgeManagedWorkBranch(branchName) && /^(?:story|task|bug)\//u.test(branchName);
26
+ // A checkout Git still recognizes (a prunable registration) keeps its own HEAD, index and merge state.
27
+ if (await isOwnGitCheckout(git, candidate)) {
28
+ return await preserveWorktreeWip({
29
+ worktreePath: candidate, branchName, reason: "pre_cleanup", autoRestore: restorable,
30
+ });
31
+ }
32
+ // Otherwise only the files are left; compare them with the branch the folder was created for:
33
+ // its local branch, else its branch on origin. Either way the snapshot is based on the branch's
34
+ // own commit, so a later pass can apply it (restore still requires that exact HEAD). Compared
35
+ // with the repository's HEAD instead, it is saved for inspection only.
36
+ const branchRef = await existingRef(git, repoPath, `refs/heads/${branchName}`)
37
+ ?? await existingRef(git, repoPath, `refs/remotes/origin/${branchName}`);
38
+ const baseRef = branchRef ?? await existingRef(git, repoPath, "HEAD");
39
+ if (!baseRef)
40
+ throw new Error(`no base commit to compare ${candidate} with.`);
41
+ return await preserveWorktreeWip({
42
+ worktreePath: candidate,
43
+ branchName,
44
+ reason: "pre_cleanup",
45
+ autoRestore: restorable && branchRef !== null,
46
+ orphan: { repoPath, baseRef },
47
+ });
48
+ }
49
+ /** The branch Forge created the folder for: its path under the managed root, without a release suffix. */
50
+ function candidateBranch(worktreeRoot, candidate) {
51
+ return path.relative(worktreeRoot, candidate).split(/[\\/]+/u).filter(Boolean).join("/").replace(releaseSuffix, "");
52
+ }
53
+ async function isOwnGitCheckout(git, candidate) {
54
+ const topLevel = await git.run(candidate, ["rev-parse", "--show-toplevel"]).catch(() => "");
55
+ if (!topLevel.trim())
56
+ return false;
57
+ const normalize = (value) => {
58
+ const resolved = path.resolve(value.trim());
59
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
60
+ };
61
+ return normalize(topLevel) === normalize(candidate);
62
+ }
63
+ async function existingRef(git, repoPath, ref) {
64
+ const resolved = await git.run(repoPath, ["rev-parse", "-q", "--verify", `${ref}^{commit}`]).catch(() => "");
65
+ return resolved.trim() ? ref : null;
66
+ }
@@ -6,9 +6,19 @@ export declare class ManagedWorktreeCleanupService implements CleanupService {
6
6
  private readonly stateRoot;
7
7
  private readonly git;
8
8
  private readonly coordinator;
9
- constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
9
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
10
+ private readonly warn;
11
+ constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator,
12
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
13
+ warn?: (message: string) => void);
10
14
  run(request: CleanupRequest): Promise<CleanupResult>;
11
15
  private runLocked;
16
+ /** All mode: removes the managed root itself once nothing in it is active, unowned or unsaved. */
17
+ private removeWholeRoot;
18
+ /** Re-reads registrations and leases: a candidate may have become active since the scan. */
19
+ private isProtectedNow;
20
+ /** Saves each candidate's uncommitted work to a WIP ref; returns how many could not be saved. */
21
+ private saveCandidatesWork;
12
22
  private sweepReadinessBranches;
13
23
  /**
14
24
  * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
@@ -5,18 +5,23 @@ import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
5
5
  import { GitClient } from "../shared/git/git.js";
6
6
  import { isSubPath, resolveExistingDirectoryPath, resolvePathIdentity } from "../shared/path/path.js";
7
7
  import { defaultWorktreeCoordinatorStateRoot, resolveManagedWorktreeRootForRepo, } from "../worktree/worktree-paths.js";
8
+ import { saveStaleWorktreeWork } from "./cleanup-wip.js";
8
9
  import { isForgeOwnedWorktreePath, isForgeWorktreeContainer, isRuntimeReadinessName } from "./forge-owned-paths.js";
9
- import { liveLeaseBranches, readHostRuntimeLeases } from "./host-runtime-ledger.js";
10
+ import { liveLeaseBranches, readHostRuntimeLeases, resolveRuntimeLeasePath } from "./host-runtime-ledger.js";
10
11
  import { sweepManagedBranches } from "./managed-branch-sweep.js";
11
12
  const staleRuntimeReadinessAgeMs = 30 * 60 * 1000;
12
13
  export class ManagedWorktreeCleanupService {
13
14
  stateRoot;
14
15
  git;
15
16
  coordinator;
16
- constructor(stateRoot = defaultWorktreeCoordinatorStateRoot(), git = new GitClient(), coordinator = new RepositoryCoordinatorLock(stateRoot)) {
17
+ warn;
18
+ constructor(stateRoot = defaultWorktreeCoordinatorStateRoot(), git = new GitClient(), coordinator = new RepositoryCoordinatorLock(stateRoot),
19
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
20
+ warn = message => process.stderr.write(`${message}\n`)) {
17
21
  this.stateRoot = stateRoot;
18
22
  this.git = git;
19
23
  this.coordinator = coordinator;
24
+ this.warn = warn;
20
25
  }
21
26
  async run(request) {
22
27
  const [repoPath, allowedRepoRoot] = await Promise.all([
@@ -69,30 +74,7 @@ export class ManagedWorktreeCleanupService {
69
74
  const activeWorktrees = activePaths(listedWorktrees)
70
75
  .filter(activePath => !staleReadinessPaths.some(stalePath => samePath(stalePath, activePath)));
71
76
  if (request.mode === "all") {
72
- const protectedPaths = uniquePaths([
73
- ...activeWorktrees.filter(activePath => isSubPath(safeRoot, activePath)),
74
- ...activeRuntimePaths.filter(activePath => isSubPath(safeRoot, activePath)),
75
- ]);
76
- if (protectedPaths.length > 0) {
77
- throw new Error(`Refusing to remove managed worktree root ${safeRoot}; ${protectedPaths.length} active worktree or runtime lease(s) remain.`);
78
- }
79
- const scan = await this.scanManagedCandidates(metadataRoot, safeRoot, activeWorktrees, activeRuntimePaths);
80
- if (request.force && !scan.rootRemovalSafe) {
81
- throw new Error(`Refusing to remove managed worktree root ${safeRoot}; unowned content remains (${scan.skippedUnownedDirectories} skipped director${scan.skippedUnownedDirectories === 1 ? "y" : "ies"}).`);
82
- }
83
- if (request.force) {
84
- await quarantineAndRemoveRoot(safeRoot);
85
- await this.git.run(repoPath, ["worktree", "prune"]);
86
- }
87
- return {
88
- worktreeRoot: safeRoot,
89
- removedWorktrees: request.force ? scan.candidates.length : 0,
90
- candidateWorktrees: scan.candidates.length,
91
- protectedWorktrees: scan.protectedWorktrees,
92
- skippedUnownedDirectories: scan.skippedUnownedDirectories,
93
- removedRoot: request.force,
94
- dryRun: !request.force,
95
- };
77
+ return await this.removeWholeRoot(repoPath, safeRoot, metadataRoot, activeWorktrees, activeRuntimePaths, request.force);
96
78
  }
97
79
  const scan = await this.scanManagedCandidates(metadataRoot, safeRoot, activeWorktrees, activeRuntimePaths);
98
80
  if (!request.force) {
@@ -107,27 +89,20 @@ export class ManagedWorktreeCleanupService {
107
89
  };
108
90
  }
109
91
  let removedWorktrees = 0;
92
+ let preservedWorktrees = 0;
110
93
  for (const candidate of scan.candidates) {
111
- const [currentWorktrees, currentLeases] = await Promise.all([
112
- this.listWorktrees(repoPath),
113
- this.readRuntimeLeases(),
114
- ]);
115
- const currentRuntimePaths = await Promise.all(currentLeases
116
- .filter(lease => lease.state !== "released")
117
- .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
118
- const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, currentWorktrees, currentRuntimePaths);
119
- const currentlyProtected = [
120
- ...activePaths(currentWorktrees)
121
- .filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
122
- ...currentRuntimePaths,
123
- ];
124
- if (worktreePathState(candidate, currentlyProtected) !== "none") {
94
+ if (await this.isProtectedNow(repoPath, safeRoot, candidate)) {
125
95
  continue;
126
96
  }
127
97
  const candidateIdentity = await forgeManagedCandidateIdentity(metadataRoot, candidate);
128
98
  if (!candidateIdentity) {
129
99
  continue;
130
100
  }
101
+ // Never delete uncommitted work that could not be saved first.
102
+ if (await this.saveCandidatesWork(repoPath, safeRoot, [candidate]) > 0) {
103
+ preservedWorktrees += 1;
104
+ continue;
105
+ }
131
106
  if (await quarantineAndRemoveCandidate(safeRoot, candidate, candidateIdentity)) {
132
107
  removedWorktrees += 1;
133
108
  }
@@ -144,8 +119,73 @@ export class ManagedWorktreeCleanupService {
144
119
  removedRoot: false,
145
120
  dryRun: false,
146
121
  deletedBranches: sweep.deletedBranches.length,
122
+ preservedWorktrees,
123
+ };
124
+ }
125
+ /** All mode: removes the managed root itself once nothing in it is active, unowned or unsaved. */
126
+ async removeWholeRoot(repoPath, safeRoot, metadataRoot, activeWorktrees, activeRuntimePaths, force) {
127
+ const protectedPaths = uniquePaths([
128
+ ...activeWorktrees.filter(activePath => isSubPath(safeRoot, activePath)),
129
+ ...activeRuntimePaths.filter(activePath => isSubPath(safeRoot, activePath)),
130
+ ]);
131
+ if (protectedPaths.length > 0) {
132
+ throw new Error(`Refusing to remove managed worktree root ${safeRoot}; ${protectedPaths.length} active worktree or runtime lease(s) remain.`);
133
+ }
134
+ const scan = await this.scanManagedCandidates(metadataRoot, safeRoot, activeWorktrees, activeRuntimePaths);
135
+ if (force && !scan.rootRemovalSafe) {
136
+ throw new Error(`Refusing to remove managed worktree root ${safeRoot}; unowned content remains (${scan.skippedUnownedDirectories} skipped director${scan.skippedUnownedDirectories === 1 ? "y" : "ies"}).`);
137
+ }
138
+ if (force) {
139
+ // Every candidate's work is saved first; one that can't be saved keeps the whole root.
140
+ const kept = await this.saveCandidatesWork(repoPath, safeRoot, scan.candidates);
141
+ if (kept > 0) {
142
+ throw new Error(`Refusing to remove managed worktree root ${safeRoot}; ${kept} worktree(s) hold uncommitted work that could not be saved to a WIP ref.`);
143
+ }
144
+ await quarantineAndRemoveRoot(safeRoot);
145
+ await this.git.run(repoPath, ["worktree", "prune"]);
146
+ }
147
+ return {
148
+ worktreeRoot: safeRoot,
149
+ removedWorktrees: force ? scan.candidates.length : 0,
150
+ candidateWorktrees: scan.candidates.length,
151
+ protectedWorktrees: scan.protectedWorktrees,
152
+ skippedUnownedDirectories: scan.skippedUnownedDirectories,
153
+ removedRoot: force,
154
+ dryRun: !force,
147
155
  };
148
156
  }
157
+ /** Re-reads registrations and leases: a candidate may have become active since the scan. */
158
+ async isProtectedNow(repoPath, safeRoot, candidate) {
159
+ const [currentWorktrees, currentLeases] = await Promise.all([
160
+ this.listWorktrees(repoPath),
161
+ this.readRuntimeLeases(),
162
+ ]);
163
+ const currentRuntimePaths = await Promise.all(currentLeases
164
+ .filter(lease => lease.state !== "released")
165
+ .map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
166
+ const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, currentWorktrees, currentRuntimePaths);
167
+ const currentlyProtected = [
168
+ ...activePaths(currentWorktrees)
169
+ .filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
170
+ ...currentRuntimePaths,
171
+ ];
172
+ return worktreePathState(candidate, currentlyProtected) !== "none";
173
+ }
174
+ /** Saves each candidate's uncommitted work to a WIP ref; returns how many could not be saved. */
175
+ async saveCandidatesWork(repoPath, safeRoot, candidates) {
176
+ let kept = 0;
177
+ for (const candidate of candidates) {
178
+ const outcome = await saveStaleWorktreeWork(this.git, repoPath, safeRoot, candidate);
179
+ if (outcome.status === "saved") {
180
+ this.warn(`Saved uncommitted work in stale worktree ${candidate} to ${outcome.ref} before removing it.`);
181
+ }
182
+ else if (outcome.status === "failed") {
183
+ kept += 1;
184
+ this.warn(`Kept stale worktree ${candidate}: its uncommitted work could not be saved to a WIP ref (${outcome.reason}).`);
185
+ }
186
+ }
187
+ return kept;
188
+ }
149
189
  async sweepReadinessBranches(repoPath) {
150
190
  return await sweepManagedBranches(this.git, repoPath, {
151
191
  includeMergedWorkBranches: false,
@@ -275,28 +315,6 @@ export class ManagedWorktreeCleanupService {
275
315
  return path.join(await fs.realpath(commonDirPath), "worktrees");
276
316
  }
277
317
  }
278
- async function resolveRuntimeLeasePath(leasePath) {
279
- const resolved = path.resolve(leasePath);
280
- const before = await fs.lstat(resolved).catch(error => {
281
- if (isEnoent(error))
282
- return null;
283
- throw error;
284
- });
285
- if (!before)
286
- return await resolvePathIdentity(resolved);
287
- if (before.isSymbolicLink() || !before.isDirectory()) {
288
- throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} is redirected or is not a directory.`);
289
- }
290
- const real = await fs.realpath(resolved);
291
- const after = await fs.lstat(resolved);
292
- if (after.isSymbolicLink()
293
- || !after.isDirectory()
294
- || (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
295
- && (before.dev !== after.dev || before.ino !== after.ino))) {
296
- throw new Error(`Refusing managed worktree cleanup because runtime lease path ${resolved} changed while being resolved.`);
297
- }
298
- return real;
299
- }
300
318
  function emptyResult(worktreeRoot, force) {
301
319
  return {
302
320
  worktreeRoot: path.resolve(worktreeRoot),
@@ -17,4 +17,6 @@ export interface CleanupResult {
17
17
  readonly deletedBranches?: number;
18
18
  /** Merged mode only: origin/HEAD was unset or stale and origin had none or several of develop, main and master, so merged work branches were left alone. */
19
19
  readonly mergedBaseUnresolved?: boolean;
20
+ /** Stale mode only: stale worktrees kept because their uncommitted work could not be saved first. */
21
+ readonly preservedWorktrees?: number;
20
22
  }
@@ -6,4 +6,6 @@ export declare function isForgeOwnedWorktreePath(relativePath: string, separator
6
6
  export declare function isForgeWorktreeContainer(relativePath: string, separator?: PathSeparator): boolean;
7
7
  /** True for a readiness probe's exact folder or branch name: runtime-readiness-<UUID>. */
8
8
  export declare function isRuntimeReadinessName(name: string): boolean;
9
+ /** True for a Forge PR review's worktree key, pr-review/<12 hex>-<12 hex>: nothing in it is anyone's work. */
10
+ export declare function isPrReviewWorktreeKey(name: string): boolean;
9
11
  export {};