@loucompanion/forge-bridge 0.1.4-dev.86fc5d1208e6 → 0.1.4-dev.894bcbd53d64

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 (269) hide show
  1. package/README.md +144 -3
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +74 -12
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  103. package/dist/runtime/host-runtime-lease.js +343 -67
  104. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  105. package/dist/runtime/host-runtime-promotion.js +48 -0
  106. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  107. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  108. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  109. package/dist/runtime/host-runtime-requirements.js +117 -0
  110. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  111. package/dist/runtime/managed-command-teardown.js +596 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  113. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  114. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  115. package/dist/runtime/playwright-browser-cache.js +227 -0
  116. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  117. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  118. package/dist/runtime/runner-settings.d.ts +104 -0
  119. package/dist/runtime/runner-settings.js +236 -0
  120. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  121. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  122. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  123. package/dist/sandbox/host-capacity-broker.js +336 -0
  124. package/dist/sandbox/managed-branch.d.ts +13 -0
  125. package/dist/sandbox/managed-branch.js +90 -0
  126. package/dist/sandbox/provider-auth/codex.js +11 -11
  127. package/dist/sandbox/runtime.d.ts +10 -1
  128. package/dist/sandbox/runtime.js +47 -8
  129. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  130. package/dist/sandbox/sandbox-cgroups.js +42 -0
  131. package/dist/session/architect-waits.d.ts +2 -0
  132. package/dist/session/architect-waits.js +138 -0
  133. package/dist/session/managed-attempt-tools.d.ts +27 -7
  134. package/dist/session/managed-attempt-tools.js +406 -123
  135. package/dist/session/managed-build-coordinator.d.ts +17 -1
  136. package/dist/session/managed-build-coordinator.js +14 -1
  137. package/dist/session/managed-build-receipt.d.ts +5 -0
  138. package/dist/session/managed-build-receipt.js +8 -3
  139. package/dist/session/managed-command-host-load.d.ts +47 -0
  140. package/dist/session/managed-command-host-load.js +83 -0
  141. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  142. package/dist/session/mcp-argument-coercion.js +121 -0
  143. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  144. package/dist/session/phase-completion.artifacts.js +100 -26
  145. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  146. package/dist/session/phase-completion.command-validation.js +77 -0
  147. package/dist/session/phase-completion.d.ts +12 -0
  148. package/dist/session/phase-completion.helpers.js +13 -12
  149. package/dist/session/phase-completion.js +5 -0
  150. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  151. package/dist/session/phase-completion.mcp-args.js +156 -0
  152. package/dist/session/phase-completion.prompts.js +6 -1
  153. package/dist/session/phase-completion.runtime.d.ts +5 -11
  154. package/dist/session/phase-completion.runtime.js +111 -230
  155. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  156. package/dist/session/phase-completion.schema-parts.js +188 -0
  157. package/dist/session/phase-completion.schemas.d.ts +3 -3
  158. package/dist/session/phase-completion.schemas.js +208 -231
  159. package/dist/session/phase-completion.validation.d.ts +2 -3
  160. package/dist/session/phase-completion.validation.js +49 -93
  161. package/dist/session/pre-publication-host-load.d.ts +27 -0
  162. package/dist/session/pre-publication-host-load.js +111 -0
  163. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  164. package/dist/session/pre-publication-native-postgres.js +111 -0
  165. package/dist/session/pre-publication-pass.d.ts +61 -0
  166. package/dist/session/pre-publication-pass.js +148 -0
  167. package/dist/session/pre-publication-process.d.ts +23 -0
  168. package/dist/session/pre-publication-process.js +109 -0
  169. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  170. package/dist/session/pre-publication-skipped-tests.js +109 -0
  171. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  172. package/dist/session/pre-publication-step-execution.js +50 -0
  173. package/dist/session/pre-publication-validation.d.ts +37 -21
  174. package/dist/session/pre-publication-validation.js +228 -219
  175. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  176. package/dist/session/provider-cli/claude-background-work.js +181 -0
  177. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  178. package/dist/session/provider-cli/host-build-lock.js +30 -0
  179. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  180. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  181. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  182. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  183. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  184. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  185. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  186. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  187. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  188. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  189. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  190. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  191. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  192. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  193. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  195. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  196. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  197. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  198. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  199. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  200. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  201. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  202. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  203. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  204. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  205. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  206. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  207. package/dist/session/provider-cli/provider-output-state.js +15 -0
  208. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  209. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  210. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  211. package/dist/session/publishable-worktree-changes.js +193 -0
  212. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  213. package/dist/session/qa-sidecar-validation.js +28 -0
  214. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  215. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  216. package/dist/session/session-redaction.js +31 -181
  217. package/dist/session/session.base.d.ts +9 -1
  218. package/dist/session/session.service.d.ts +11 -2
  219. package/dist/session/session.service.js +189 -69
  220. package/dist/session/session.types.d.ts +3 -0
  221. package/dist/session/session.types.js +15 -3
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  225. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  226. package/dist/shared/fs/file-identity.d.ts +10 -0
  227. package/dist/shared/fs/file-identity.js +15 -0
  228. package/dist/shared/fs/replace-file.d.ts +7 -0
  229. package/dist/shared/fs/replace-file.js +33 -0
  230. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  231. package/dist/shared/process/host-process-recovery.js +23 -3
  232. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  233. package/dist/shared/process/host-process-supervisor.js +67 -15
  234. package/dist/shared/process/process-tree.d.ts +52 -0
  235. package/dist/shared/process/process-tree.js +144 -0
  236. package/dist/shared/process/process.d.ts +67 -0
  237. package/dist/shared/process/process.js +213 -11
  238. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  239. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  240. package/dist/shared/process/windows-launch.d.ts +18 -0
  241. package/dist/shared/process/windows-launch.js +68 -0
  242. package/dist/shared/provider-capabilities.js +14 -7
  243. package/dist/version.d.ts +1 -1
  244. package/dist/version.js +1 -1
  245. package/dist/worktree/dependency-warmer.d.ts +25 -0
  246. package/dist/worktree/dependency-warmer.js +120 -10
  247. package/dist/worktree/orphan-relink.d.ts +19 -0
  248. package/dist/worktree/orphan-relink.js +106 -0
  249. package/dist/worktree/wip-git.d.ts +33 -0
  250. package/dist/worktree/wip-git.js +122 -0
  251. package/dist/worktree/wip-refs.d.ts +62 -0
  252. package/dist/worktree/wip-refs.js +119 -0
  253. package/dist/worktree/wip-restore.d.ts +38 -0
  254. package/dist/worktree/wip-restore.js +190 -0
  255. package/dist/worktree/wip-snapshot.d.ts +50 -0
  256. package/dist/worktree/wip-snapshot.js +268 -0
  257. package/dist/worktree/worktree-inputs.d.ts +8 -0
  258. package/dist/worktree/worktree-inputs.js +134 -0
  259. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  260. package/dist/worktree/worktree-origin-sync.js +127 -0
  261. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  262. package/dist/worktree/worktree-wip-events.js +98 -0
  263. package/dist/worktree/worktree-wip.d.ts +50 -0
  264. package/dist/worktree/worktree-wip.js +185 -0
  265. package/dist/worktree/worktree.base.d.ts +7 -1
  266. package/dist/worktree/worktree.service.d.ts +36 -5
  267. package/dist/worktree/worktree.service.js +124 -155
  268. package/dist/worktree/worktree.types.d.ts +38 -0
  269. package/package.json +2 -2
@@ -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,14 @@
1
+ /**
2
+ * Whether this host offers a native test PostgreSQL and whether its role is a superuser
3
+ * (decision 0013 placement). Suites that need `session_replication_role`, `CREATE ROLE` or
4
+ * similar can only run on a superuser test database or on Docker-backed Testcontainers.
5
+ */
6
+ export interface BridgeTestPostgresCapability {
7
+ readonly available: boolean;
8
+ /** Null when the cluster is configured but the role could not be checked. */
9
+ readonly superuser: boolean | null;
10
+ }
11
+ export type PsqlRunner = (args: readonly string[], env: NodeJS.ProcessEnv) => Promise<string>;
12
+ export declare function probeTestPostgresCapability(environment?: NodeJS.ProcessEnv, runPsql?: PsqlRunner, readFallback?: () => string | null): Promise<BridgeTestPostgresCapability>;
13
+ /** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
14
+ export declare function psqlTarget(connection: string): Record<string, string> | null;
@@ -0,0 +1,120 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { hostRuntimeTestPostgresAdminEnvironment } from "../runtime/host-runtime-contract.js";
4
+ import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
5
+ const execFileAsync = promisify(execFile);
6
+ const superuserQuery = "select rolsuper from pg_roles where rolname = current_user";
7
+ export async function probeTestPostgresCapability(environment = process.env, runPsql = defaultPsql, readFallback = configuredFallbackConnection) {
8
+ // Same sources pre-publication validation uses: the environment, else the operator's
9
+ // native test cluster file.
10
+ const connection = environment[hostRuntimeTestPostgresAdminEnvironment]?.trim() || readFallback()?.trim();
11
+ if (!connection)
12
+ return { available: false, superuser: null };
13
+ const target = psqlTarget(connection);
14
+ if (!target)
15
+ return { available: true, superuser: null };
16
+ try {
17
+ // The secret travels only in the child's environment, never in argv or logs.
18
+ const output = await runPsql(["-X", "-A", "-t", "-w", "-c", superuserQuery], { ...process.env, ...target, PGCONNECT_TIMEOUT: "5" });
19
+ const value = output.trim().toLowerCase();
20
+ return { available: true, superuser: value === "t" ? true : value === "f" ? false : null };
21
+ }
22
+ catch {
23
+ return { available: true, superuser: null };
24
+ }
25
+ }
26
+ /** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
27
+ export function psqlTarget(connection) {
28
+ // libpq reads PGDATABASE as a database name only, so a URI is split into PG* variables
29
+ // rather than passed whole (and not as psql's argument, which would put the secret in argv).
30
+ if (/^postgres(?:ql)?:\/\//iu.test(connection))
31
+ return uriTarget(connection);
32
+ const keys = {
33
+ host: "PGHOST", server: "PGHOST", port: "PGPORT", database: "PGDATABASE",
34
+ username: "PGUSER", "user id": "PGUSER", userid: "PGUSER", user: "PGUSER", password: "PGPASSWORD",
35
+ };
36
+ const target = {};
37
+ for (const part of connection.split(";")) {
38
+ const separator = part.indexOf("=");
39
+ if (separator <= 0)
40
+ continue;
41
+ const name = keys[part.slice(0, separator).trim().toLowerCase()];
42
+ const value = part.slice(separator + 1).trim();
43
+ if (name && value)
44
+ target[name] = value;
45
+ }
46
+ return target.PGHOST || target.PGUSER ? target : null;
47
+ }
48
+ /** libpq URI query parameters that have a PG* environment equivalent. */
49
+ const uriParameterEnvironment = {
50
+ host: "PGHOST", hostaddr: "PGHOSTADDR", port: "PGPORT", dbname: "PGDATABASE", user: "PGUSER",
51
+ password: "PGPASSWORD", passfile: "PGPASSFILE", options: "PGOPTIONS", application_name: "PGAPPNAME",
52
+ sslmode: "PGSSLMODE", sslrootcert: "PGSSLROOTCERT", sslcert: "PGSSLCERT", sslkey: "PGSSLKEY",
53
+ sslcrl: "PGSSLCRL", gssencmode: "PGGSSENCMODE", target_session_attrs: "PGTARGETSESSIONATTRS",
54
+ };
55
+ /**
56
+ * Parses `postgres[ql]://[user[:password]@][host[:port][,...]][/dbname][?param=value&...]`
57
+ * (libpq's URI form, including comma-separated hosts, bracketed IPv6 and percent-encoding).
58
+ */
59
+ function uriTarget(connection) {
60
+ const match = /^postgres(?:ql)?:\/\/([^/?#]*)(?:\/([^?#]*))?(?:\?([^#]*))?/iu.exec(connection);
61
+ if (!match)
62
+ return null;
63
+ try {
64
+ const [, authority = "", path, query] = match;
65
+ const target = {};
66
+ const at = authority.lastIndexOf("@");
67
+ if (at >= 0) {
68
+ const userInfo = authority.slice(0, at);
69
+ const colon = userInfo.indexOf(":");
70
+ const user = decodeURIComponent(colon >= 0 ? userInfo.slice(0, colon) : userInfo);
71
+ if (user)
72
+ target.PGUSER = user;
73
+ if (colon >= 0)
74
+ target.PGPASSWORD = decodeURIComponent(userInfo.slice(colon + 1));
75
+ }
76
+ const hosts = [];
77
+ const ports = [];
78
+ for (const entry of authority.slice(at + 1).split(",")) {
79
+ const ipv6 = /^\[([^\]]*)\](?::(.*))?$/u.exec(entry);
80
+ const colon = entry.lastIndexOf(":");
81
+ const host = ipv6 ? ipv6[1] ?? "" : colon >= 0 ? entry.slice(0, colon) : entry;
82
+ const port = ipv6 ? ipv6[2] ?? "" : colon >= 0 ? entry.slice(colon + 1) : "";
83
+ hosts.push(decodeURIComponent(host));
84
+ ports.push(port);
85
+ }
86
+ if (hosts.some(Boolean))
87
+ target.PGHOST = hosts.join(",");
88
+ if (ports.some(Boolean))
89
+ target.PGPORT = ports.join(",");
90
+ const database = path ? decodeURIComponent(path) : "";
91
+ if (database)
92
+ target.PGDATABASE = database;
93
+ for (const parameter of (query ?? "").split("&")) {
94
+ const separator = parameter.indexOf("=");
95
+ if (separator <= 0)
96
+ continue;
97
+ const name = uriParameterEnvironment[decodeURIComponent(parameter.slice(0, separator))];
98
+ const value = decodeURIComponent(parameter.slice(separator + 1));
99
+ if (name && value)
100
+ target[name] = value;
101
+ }
102
+ return target;
103
+ }
104
+ catch {
105
+ // Malformed percent-encoding: the role cannot be checked.
106
+ return null;
107
+ }
108
+ }
109
+ function configuredFallbackConnection() {
110
+ try {
111
+ return readNativeTestPostgresFallback()?.connectionString ?? null;
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ }
117
+ async function defaultPsql(args, env) {
118
+ const result = await execFileAsync("psql", [...args], { encoding: "utf8", timeout: 10_000, env });
119
+ return result.stdout;
120
+ }
@@ -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 { 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: there is no work of anyone's in it.
14
+ if (isRuntimeReadinessName(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,28 @@ 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;
22
+ private sweepReadinessBranches;
23
+ /**
24
+ * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
25
+ * exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
26
+ * Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
27
+ * rather than measured against the wrong base.
28
+ */
29
+ private remoteBaseBranch;
30
+ private remoteBranchExists;
12
31
  private listWorktrees;
13
32
  private staleRuntimeReadinessPaths;
14
33
  private scanManagedCandidates;