@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.0098fdb4e213

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 (332) hide show
  1. package/README.md +232 -5
  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 +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  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 +13 -1
  15. package/dist/bridge/bridge.service.d.ts +169 -14
  16. package/dist/bridge/bridge.service.js +1868 -330
  17. package/dist/bridge/bridge.types.d.ts +73 -1
  18. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  19. package/dist/bridge/dispatch-result-outbox.js +87 -0
  20. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  21. package/dist/bridge/dispatch-result-worker.js +122 -0
  22. package/dist/bridge/in-flight-registry.d.ts +62 -0
  23. package/dist/bridge/in-flight-registry.js +207 -0
  24. package/dist/bridge/internals.d.ts +2 -0
  25. package/dist/bridge/internals.js +1 -0
  26. package/dist/bridge/local-yield-flag.d.ts +6 -0
  27. package/dist/bridge/local-yield-flag.js +34 -0
  28. package/dist/bridge/readiness-result-outbox.d.ts +25 -0
  29. package/dist/bridge/readiness-result-outbox.js +74 -0
  30. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  31. package/dist/bridge/readiness-result-worker.js +121 -0
  32. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  33. package/dist/bridge/runner-host-capabilities.js +110 -0
  34. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  35. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  36. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  37. package/dist/bridge/test-postgres-capability.js +120 -0
  38. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  39. package/dist/cleanup/cleanup-wip.js +66 -0
  40. package/dist/cleanup/cleanup.service.d.ts +21 -1
  41. package/dist/cleanup/cleanup.service.js +185 -143
  42. package/dist/cleanup/cleanup.types.d.ts +6 -0
  43. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  44. package/dist/cleanup/forge-owned-paths.js +53 -0
  45. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  46. package/dist/cleanup/host-runtime-ledger.js +130 -0
  47. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  48. package/dist/cleanup/managed-branch-sweep.js +111 -0
  49. package/dist/cli/cli.help.js +78 -16
  50. package/dist/cli/cli.service.d.ts +32 -15
  51. package/dist/cli/cli.service.js +206 -182
  52. package/dist/cli/idle-status.d.ts +84 -0
  53. package/dist/cli/idle-status.js +181 -0
  54. package/dist/cli/local-config.d.ts +7 -0
  55. package/dist/cli/local-config.js +36 -4
  56. package/dist/cli/provider-cli-detection.d.ts +10 -0
  57. package/dist/cli/provider-cli-detection.js +160 -0
  58. package/dist/runtime/aspnet-runtime-prebuild.d.ts +41 -0
  59. package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
  60. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  61. package/dist/runtime/attempt-database-broker.js +390 -0
  62. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  63. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  64. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  65. package/dist/runtime/attempt-path-operation.js +94 -0
  66. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  67. package/dist/runtime/attempt-private-directory.js +54 -0
  68. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  69. package/dist/runtime/attempt-process-supervisor.js +144 -23
  70. package/dist/runtime/canonical-source-file.d.ts +3 -0
  71. package/dist/runtime/canonical-source-file.js +54 -0
  72. package/dist/runtime/docker-engine-probe.d.ts +95 -0
  73. package/dist/runtime/docker-engine-probe.js +340 -0
  74. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  75. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  76. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  77. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  78. package/dist/runtime/generated-output-reset.d.ts +10 -0
  79. package/dist/runtime/generated-output-reset.js +62 -8
  80. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  81. package/dist/runtime/host-database-capability-boundary.js +63 -0
  82. package/dist/runtime/host-diagnostics.d.ts +11 -0
  83. package/dist/runtime/host-diagnostics.js +192 -0
  84. package/dist/runtime/host-execution-root.d.ts +4 -0
  85. package/dist/runtime/host-execution-root.js +39 -0
  86. package/dist/runtime/host-facts.d.ts +36 -0
  87. package/dist/runtime/host-facts.js +95 -0
  88. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  89. package/dist/runtime/host-listener-inspector.js +121 -60
  90. package/dist/runtime/host-load-admission.d.ts +67 -0
  91. package/dist/runtime/host-load-admission.js +99 -0
  92. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  93. package/dist/runtime/host-load-child-environment.js +76 -0
  94. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  95. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  96. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  97. package/dist/runtime/host-load-governor-config.js +83 -0
  98. package/dist/runtime/host-load-governor.d.ts +186 -0
  99. package/dist/runtime/host-load-governor.js +632 -0
  100. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  101. package/dist/runtime/host-load-ledger-lock.js +187 -0
  102. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  103. package/dist/runtime/host-load-runtime-settings.js +80 -0
  104. package/dist/runtime/host-load-sampler.d.ts +156 -0
  105. package/dist/runtime/host-load-sampler.js +298 -0
  106. package/dist/runtime/host-load-step-class.d.ts +70 -0
  107. package/dist/runtime/host-load-step-class.js +161 -0
  108. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  109. package/dist/runtime/host-load-step-reaper.js +95 -0
  110. package/dist/runtime/host-load-step-run.d.ts +73 -0
  111. package/dist/runtime/host-load-step-run.js +102 -0
  112. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  113. package/dist/runtime/host-load-test-slot.js +81 -0
  114. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  115. package/dist/runtime/host-load-token-ledger.js +453 -0
  116. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  117. package/dist/runtime/host-load-windows-cpu.js +85 -0
  118. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  119. package/dist/runtime/host-pressure-stall.js +168 -0
  120. package/dist/runtime/host-runtime-contract.d.ts +28 -1
  121. package/dist/runtime/host-runtime-contract.js +203 -57
  122. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  123. package/dist/runtime/host-runtime-lease.js +1427 -124
  124. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  125. package/dist/runtime/host-runtime-promotion.js +107 -12
  126. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  127. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  128. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  129. package/dist/runtime/host-runtime-requirements.js +117 -0
  130. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  131. package/dist/runtime/managed-command-teardown.js +596 -0
  132. package/dist/runtime/memory-capacity.d.ts +70 -0
  133. package/dist/runtime/memory-capacity.js +123 -0
  134. package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
  135. package/dist/runtime/native-test-postgres-fallback.js +143 -0
  136. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  137. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  138. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  139. package/dist/runtime/pinned-directory-process.js +61 -0
  140. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  141. package/dist/runtime/pinned-source-directory.js +94 -0
  142. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  143. package/dist/runtime/playwright-browser-cache.js +227 -0
  144. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  145. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  146. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  147. package/dist/runtime/prepared-runtime-identity.js +218 -0
  148. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  149. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  150. package/dist/runtime/runner-settings.d.ts +104 -0
  151. package/dist/runtime/runner-settings.js +236 -0
  152. package/dist/runtime/runtime-isolation-lease.js +4 -1
  153. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  154. package/dist/runtime/workspace-resource-estimator.js +174 -0
  155. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  156. package/dist/sandbox/host-capacity-broker.js +336 -0
  157. package/dist/sandbox/managed-branch.d.ts +13 -0
  158. package/dist/sandbox/managed-branch.js +36 -0
  159. package/dist/sandbox/preflight.d.ts +31 -1
  160. package/dist/sandbox/preflight.js +237 -51
  161. package/dist/sandbox/provider-auth/codex.js +11 -11
  162. package/dist/sandbox/repository-lock.d.ts +2 -1
  163. package/dist/sandbox/repository-lock.js +19 -9
  164. package/dist/sandbox/runtime.d.ts +16 -2
  165. package/dist/sandbox/runtime.js +183 -114
  166. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  167. package/dist/sandbox/sandbox-cgroups.js +42 -0
  168. package/dist/sandbox/sandbox.types.d.ts +7 -0
  169. package/dist/sandbox/workspace.service.js +2 -0
  170. package/dist/session/architect-waits.d.ts +2 -0
  171. package/dist/session/architect-waits.js +138 -0
  172. package/dist/session/managed-attempt-tools.d.ts +37 -1
  173. package/dist/session/managed-attempt-tools.js +822 -84
  174. package/dist/session/managed-build-coordinator.d.ts +5 -0
  175. package/dist/session/managed-build-coordinator.js +109 -0
  176. package/dist/session/managed-build-receipt.d.ts +26 -0
  177. package/dist/session/managed-build-receipt.js +342 -0
  178. package/dist/session/managed-command-host-load.d.ts +47 -0
  179. package/dist/session/managed-command-host-load.js +83 -0
  180. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  181. package/dist/session/managed-verification-timeouts.js +17 -0
  182. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  183. package/dist/session/mcp-argument-coercion.js +121 -0
  184. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  185. package/dist/session/phase-completion.artifacts.js +321 -45
  186. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  187. package/dist/session/phase-completion.command-validation.js +77 -0
  188. package/dist/session/phase-completion.d.ts +23 -1
  189. package/dist/session/phase-completion.helpers.d.ts +5 -0
  190. package/dist/session/phase-completion.helpers.js +43 -19
  191. package/dist/session/phase-completion.js +19 -3
  192. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  193. package/dist/session/phase-completion.mcp-args.js +156 -0
  194. package/dist/session/phase-completion.prompts.js +22 -18
  195. package/dist/session/phase-completion.runtime.d.ts +6 -10
  196. package/dist/session/phase-completion.runtime.js +214 -224
  197. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  198. package/dist/session/phase-completion.schema-parts.js +188 -0
  199. package/dist/session/phase-completion.schemas.d.ts +3 -3
  200. package/dist/session/phase-completion.schemas.js +250 -226
  201. package/dist/session/phase-completion.validation.d.ts +3 -3
  202. package/dist/session/phase-completion.validation.js +135 -89
  203. package/dist/session/pre-publication-host-load.d.ts +27 -0
  204. package/dist/session/pre-publication-host-load.js +111 -0
  205. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  206. package/dist/session/pre-publication-native-postgres.js +111 -0
  207. package/dist/session/pre-publication-pass.d.ts +61 -0
  208. package/dist/session/pre-publication-pass.js +148 -0
  209. package/dist/session/pre-publication-process.d.ts +23 -0
  210. package/dist/session/pre-publication-process.js +109 -0
  211. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  212. package/dist/session/pre-publication-skipped-tests.js +109 -0
  213. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  214. package/dist/session/pre-publication-step-execution.js +50 -0
  215. package/dist/session/pre-publication-validation.d.ts +91 -0
  216. package/dist/session/pre-publication-validation.js +670 -0
  217. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  218. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  219. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  220. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  221. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  222. package/dist/session/provider-cli/claude-background-work.js +181 -0
  223. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  224. package/dist/session/provider-cli/host-build-lock.js +30 -0
  225. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  226. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  227. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  228. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  229. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  230. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  231. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  232. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  233. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  234. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  235. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  236. package/dist/session/provider-cli/provider-cli.process.d.ts +85 -19
  237. package/dist/session/provider-cli/provider-cli.process.js +566 -283
  238. package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -0
  239. package/dist/session/provider-cli/provider-cli.prompts.js +211 -36
  240. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  241. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  242. package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -1
  243. package/dist/session/provider-cli/provider-cli.runtime.js +83 -4
  244. package/dist/session/provider-cli/provider-cli.service.d.ts +36 -5
  245. package/dist/session/provider-cli/provider-cli.service.js +818 -99
  246. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  247. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  248. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  249. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  250. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  251. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  252. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  253. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  254. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  255. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  256. package/dist/session/provider-cli/provider-output-state.js +376 -17
  257. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  258. package/dist/session/provider-cli/provider-usage.js +28 -5
  259. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  260. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  261. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  262. package/dist/session/publishable-worktree-changes.js +193 -0
  263. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  264. package/dist/session/qa-sidecar-validation.js +28 -0
  265. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  266. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  267. package/dist/session/session-redaction.js +284 -9
  268. package/dist/session/session.base.d.ts +9 -1
  269. package/dist/session/session.service.d.ts +11 -2
  270. package/dist/session/session.service.js +301 -58
  271. package/dist/session/session.types.d.ts +150 -2
  272. package/dist/session/session.types.js +599 -7
  273. package/dist/session/sidecar-json-shape.d.ts +31 -0
  274. package/dist/session/sidecar-json-shape.js +217 -0
  275. package/dist/session/unreferenced-exports.d.ts +12 -0
  276. package/dist/session/unreferenced-exports.js +59 -0
  277. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  278. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  279. package/dist/shared/format/format-bytes.d.ts +1 -0
  280. package/dist/shared/format/format-bytes.js +9 -0
  281. package/dist/shared/fs/file-identity.d.ts +10 -0
  282. package/dist/shared/fs/file-identity.js +15 -0
  283. package/dist/shared/fs/replace-file.d.ts +7 -0
  284. package/dist/shared/fs/replace-file.js +33 -0
  285. package/dist/shared/git/git.js +2 -1
  286. package/dist/shared/path/path.d.ts +1 -0
  287. package/dist/shared/path/path.js +18 -0
  288. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  289. package/dist/shared/process/dotnet-toolchain.js +307 -0
  290. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  291. package/dist/shared/process/host-process-recovery.js +26 -5
  292. package/dist/shared/process/host-process-supervisor.d.ts +16 -1
  293. package/dist/shared/process/host-process-supervisor.js +124 -23
  294. package/dist/shared/process/process-tree.d.ts +52 -0
  295. package/dist/shared/process/process-tree.js +144 -0
  296. package/dist/shared/process/process.d.ts +69 -0
  297. package/dist/shared/process/process.js +223 -16
  298. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  299. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  300. package/dist/shared/process/windows-launch.d.ts +18 -0
  301. package/dist/shared/process/windows-launch.js +68 -0
  302. package/dist/shared/provider-capabilities.d.ts +3 -0
  303. package/dist/shared/provider-capabilities.js +92 -0
  304. package/dist/shared/redaction/redaction.d.ts +1 -0
  305. package/dist/shared/redaction/redaction.js +39 -3
  306. package/dist/shared/time/monotonic.d.ts +1 -0
  307. package/dist/shared/time/monotonic.js +8 -0
  308. package/dist/version.d.ts +1 -1
  309. package/dist/version.js +1 -1
  310. package/dist/worktree/dependency-warmer.d.ts +66 -9
  311. package/dist/worktree/dependency-warmer.js +609 -24
  312. package/dist/worktree/index.d.ts +1 -1
  313. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  314. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  315. package/dist/worktree/wip-git.d.ts +33 -0
  316. package/dist/worktree/wip-git.js +122 -0
  317. package/dist/worktree/wip-refs.d.ts +62 -0
  318. package/dist/worktree/wip-refs.js +119 -0
  319. package/dist/worktree/wip-restore.d.ts +38 -0
  320. package/dist/worktree/wip-restore.js +190 -0
  321. package/dist/worktree/wip-snapshot.d.ts +50 -0
  322. package/dist/worktree/wip-snapshot.js +268 -0
  323. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  324. package/dist/worktree/worktree-wip-events.js +98 -0
  325. package/dist/worktree/worktree-wip.d.ts +49 -0
  326. package/dist/worktree/worktree-wip.js +182 -0
  327. package/dist/worktree/worktree.base.d.ts +7 -1
  328. package/dist/worktree/worktree.service.d.ts +22 -2
  329. package/dist/worktree/worktree.service.js +302 -25
  330. package/dist/worktree/worktree.types.d.ts +36 -1
  331. package/package.json +8 -6
  332. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -1,10 +1,17 @@
1
+ import { createHash, randomUUID } from "node:crypto";
1
2
  import { existsSync, realpathSync } from "node:fs";
2
3
  import fs from "node:fs/promises";
3
4
  import os from "node:os";
4
5
  import path from "node:path";
6
+ import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
7
+ import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
5
8
  import { NodeProcessRunner } from "../shared/process/process.js";
6
9
  import { buildWindowsCmdLaunch } from "../shared/process/windows-launch.js";
7
10
  import { isSubPath } from "../shared/path/path.js";
11
+ import { defaultWorktreeCoordinatorStateRoot } from "./worktree-paths.js";
12
+ import { dependencyInstallStepClass } from "../runtime/host-load-step-class.js";
13
+ import { runHostGovernedStep } from "../runtime/host-load-step-run.js";
14
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
8
15
  const SKIP_DIR_NAMES = new Set([
9
16
  ".git",
10
17
  "node_modules",
@@ -24,9 +31,15 @@ const NATIVE_MODULE_HINTS = [
24
31
  "@swc/core"
25
32
  ];
26
33
  const MAX_COMMAND_FAILURE_OUTPUT_LENGTH = 8_000;
34
+ const DEPENDENCY_RECEIPT_SCHEMA_VERSION = 1;
35
+ const DEPENDENCY_PREPARATION_CONTRACT = "managed-worktree-isolated-v1";
36
+ const WINDOWS_COMMAND_ENVIRONMENT_PATH_LIMIT = 8_191;
37
+ const WINDOWS_PACKAGE_MANAGER_INTERNAL_PATH_RESERVE = 512;
38
+ const dependencyPreparationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot());
27
39
  export async function detectWarmPaths(repoRoot, warmPathOverrides = []) {
28
40
  const entries = new Map();
29
41
  await collectDetectedPaths(repoRoot, repoRoot, entries, 0);
42
+ await collectSolutionProjectRestores(repoRoot, entries);
30
43
  for (const override of warmPathOverrides) {
31
44
  const normalized = normalizeRelativePath(override);
32
45
  if (!normalized) {
@@ -51,6 +64,7 @@ export async function warmWorktreeDependencies(request, executor = defaultComman
51
64
  const linked = [];
52
65
  const skipped = [];
53
66
  const fallbacks = [];
67
+ const receipts = [];
54
68
  const restoredDotNetRoots = new Set();
55
69
  const installedNodeRoots = new Set();
56
70
  for (const entry of warmPaths) {
@@ -67,8 +81,10 @@ export async function warmWorktreeDependencies(request, executor = defaultComman
67
81
  continue;
68
82
  }
69
83
  installedNodeRoots.add(packageKey);
70
- const install = await runInstallFallback({ ...entry, packageRoot: installPackageRoot }, worktreePath, "Managed worktrees require isolated Node dependencies.", executor);
71
- fallbacks.push(install);
84
+ const preparation = await ensureInstallFallback({ ...entry, packageRoot: installPackageRoot }, worktreePath, "Managed worktrees require isolated Node dependencies.", executor, request.preparationPolicy, request.hostLoad, request.signal);
85
+ receipts.push(preparation.receipt);
86
+ if (preparation.install)
87
+ fallbacks.push(preparation.install);
72
88
  continue;
73
89
  }
74
90
  if (entry.ecosystem === "dotnet") {
@@ -80,15 +96,19 @@ export async function warmWorktreeDependencies(request, executor = defaultComman
80
96
  continue;
81
97
  }
82
98
  restoredDotNetRoots.add(packageKey);
83
- const install = await runInstallFallback(entry, worktreePath, "Managed worktrees require isolated .NET build outputs.", executor);
84
- fallbacks.push(install);
99
+ const preparation = await ensureInstallFallback(entry, worktreePath, "Managed worktrees require isolated .NET build outputs.", executor, request.preparationPolicy, request.hostLoad, request.signal);
100
+ receipts.push(preparation.receipt);
101
+ if (preparation.install)
102
+ fallbacks.push(preparation.install);
85
103
  continue;
86
104
  }
87
105
  const sourceExists = await directoryExists(sourcePath);
88
106
  const fallbackReason = await resolveFallbackReason(entry, baseCheckoutPath, worktreePath, sourceExists);
89
107
  if (fallbackReason) {
90
- const install = await runInstallFallback(entry, worktreePath, fallbackReason, executor);
91
- fallbacks.push(install);
108
+ const preparation = await ensureInstallFallback(entry, worktreePath, fallbackReason, executor, request.preparationPolicy, request.hostLoad, request.signal);
109
+ receipts.push(preparation.receipt);
110
+ if (preparation.install)
111
+ fallbacks.push(preparation.install);
92
112
  continue;
93
113
  }
94
114
  if (!sourceExists) {
@@ -98,7 +118,7 @@ export async function warmWorktreeDependencies(request, executor = defaultComman
98
118
  await createDirectoryLink(sourcePath, targetPath, allowedRoot);
99
119
  linked.push(entry.relativePath);
100
120
  }
101
- return { linked, skipped, fallbacks };
121
+ return { linked, skipped, fallbacks, receipts };
102
122
  }
103
123
  async function removeLegacyDirectoryLink(targetPath, allowedRoot) {
104
124
  const resolvedTarget = path.resolve(targetPath);
@@ -225,28 +245,276 @@ export async function lockfilesDiffer(baseCheckoutPath, worktreePath, packageRoo
225
245
  }
226
246
  return false;
227
247
  }
228
- async function runInstallFallback(entry, worktreePath, reason, executor) {
248
+ async function ensureInstallFallback(entry, worktreePath, reason, executor, policy, hostLoad, signal) {
249
+ const startedAt = performance.now();
250
+ const cwd = path.resolve(worktreePath, entry.packageRoot === "." ? "" : entry.packageRoot);
251
+ assertWithinRoot(path.resolve(worktreePath), cwd, "Dependency package root");
252
+ const command = await installFallbackCommand(entry, cwd);
253
+ const outputMarker = dependencyOutputMarker(entry.ecosystem, cwd);
254
+ const receiptPath = path.join(outputMarker, ".forge-dependency-preparation.json");
255
+ const fingerprint = await dependencyPreparationFingerprint(entry, worktreePath, cwd, command, policy);
256
+ return await dependencyPreparationCoordinator.withLock(receiptPath, async () => {
257
+ const existing = await readDependencyPreparationReceipt(receiptPath);
258
+ if (existing?.fingerprint === fingerprint
259
+ && existing.ecosystem === entry.ecosystem
260
+ && existing.packageRoot === entry.packageRoot
261
+ && existing.command === command
262
+ && await directoryExists(outputMarker)) {
263
+ await markNpmCiRestored(outputMarker, command);
264
+ return {
265
+ install: null,
266
+ receipt: {
267
+ ecosystem: entry.ecosystem,
268
+ packageRoot: entry.packageRoot,
269
+ command,
270
+ cacheHit: true,
271
+ fingerprint,
272
+ receiptPath,
273
+ durationMs: elapsedMilliseconds(startedAt),
274
+ },
275
+ };
276
+ }
277
+ // Inside the per-root lock, and only on a real install: a verified receipt never queues.
278
+ const install = await runHostGovernedStep(hostLoad?.gate, {
279
+ classification: dependencyInstallStepClass,
280
+ label: `${command} (${entry.packageRoot})`,
281
+ dispatchAttemptId: hostLoad?.dispatchAttemptId ?? null,
282
+ priority: hostLoad?.priority ?? "foreground",
283
+ // Attempt cancellation ends the wait for capacity too.
284
+ signal,
285
+ }, async (_waitMs, hostLoadControl) => {
286
+ // The install stops when the attempt is cancelled, its token is lost, or its
287
+ // process group cannot be recorded on the token. The runner settles only once
288
+ // the whole group is gone, so the token is never returned while it still runs.
289
+ const unrecorded = new AbortController();
290
+ const stop = [signal, hostLoadControl.fenced, unrecorded.signal].filter((value) => value !== undefined);
291
+ return await runInstallFallback(entry, worktreePath, reason, executor, {
292
+ signal: AbortSignal.any(stop),
293
+ processGroup: true,
294
+ onSpawn: hostLoadControl.attachProcess
295
+ ? pid => void hostLoadControl.attachProcess({
296
+ rootPid: pid,
297
+ rootIdentity: captureHostProcessIdentity(pid),
298
+ processGroup: process.platform !== "win32",
299
+ }).catch((error) => unrecorded.abort(error))
300
+ : undefined,
301
+ });
302
+ });
303
+ // npm is allowed to omit node_modules when the package graph is empty. Keep
304
+ // an isolated, ignored output directory so the durable receipt still has a
305
+ // concrete marker whose removal invalidates reuse.
306
+ if (entry.ecosystem === "node") {
307
+ await fs.mkdir(outputMarker, { recursive: true });
308
+ }
309
+ if (!(await directoryExists(outputMarker))) {
310
+ throw new Error(`dependency_preparation_output_missing: ${install.command} succeeded without creating ${outputMarker}.`);
311
+ }
312
+ const receipt = {
313
+ schemaVersion: DEPENDENCY_RECEIPT_SCHEMA_VERSION,
314
+ fingerprint,
315
+ ecosystem: entry.ecosystem,
316
+ packageRoot: entry.packageRoot,
317
+ command,
318
+ outputMarker: path.relative(cwd, outputMarker).replaceAll("\\", "/"),
319
+ completedAt: new Date().toISOString(),
320
+ };
321
+ await persistDependencyPreparationReceipt(receiptPath, receipt);
322
+ await markNpmCiRestored(outputMarker, command);
323
+ return {
324
+ install,
325
+ receipt: {
326
+ ecosystem: entry.ecosystem,
327
+ packageRoot: entry.packageRoot,
328
+ command,
329
+ cacheHit: false,
330
+ fingerprint,
331
+ receiptPath,
332
+ durationMs: elapsedMilliseconds(startedAt),
333
+ },
334
+ };
335
+ });
336
+ }
337
+ async function markNpmCiRestored(outputMarker, command) {
338
+ if (command !== "npm ci")
339
+ return;
340
+ // Forge.Api's RestoreForgeBridge target uses this stamp as its incremental
341
+ // output. Worktree preparation has already installed and verified the same
342
+ // package graph, so an immediate dotnet build must not repeat npm ci.
343
+ await fs.writeFile(path.join(outputMarker, ".forge-restore.stamp"), "", { mode: 0o600 });
344
+ }
345
+ function elapsedMilliseconds(startedAt) {
346
+ return Math.max(0, Math.round((performance.now() - startedAt) * 1000) / 1000);
347
+ }
348
+ async function installFallbackCommand(entry, cwd) {
349
+ if (entry.ecosystem === "node") {
350
+ if (await pathExists(path.join(cwd, "pnpm-lock.yaml")))
351
+ return "pnpm install --frozen-lockfile";
352
+ return await pathExists(path.join(cwd, "package-lock.json")) ? "npm ci" : "npm install";
353
+ }
354
+ if (entry.ecosystem === "python") {
355
+ return await pathExists(path.join(cwd, "requirements.txt"))
356
+ ? "python -m venv .venv && pip install -r requirements.txt"
357
+ : "python -m venv .venv";
358
+ }
359
+ return "dotnet restore";
360
+ }
361
+ function dependencyOutputMarker(ecosystem, cwd) {
362
+ if (ecosystem === "node")
363
+ return path.join(cwd, "node_modules");
364
+ if (ecosystem === "python")
365
+ return path.join(cwd, ".venv");
366
+ return path.join(cwd, "obj");
367
+ }
368
+ async function dependencyPreparationFingerprint(entry, worktreePath, cwd, command, policy) {
369
+ const inputFiles = await dependencyInputFiles(entry.ecosystem, worktreePath, cwd);
370
+ const inputDigests = await Promise.all(inputFiles.map(async (file) => ({
371
+ path: path.relative(worktreePath, file).replaceAll("\\", "/"),
372
+ digest: await sha256File(file),
373
+ })));
374
+ const toolchainVersion = await dependencyToolchainVersion(entry.ecosystem, cwd, policy);
375
+ const trustDomain = policy?.trustDomain ?? process.env.FORGE_TRUST_DOMAIN_ID ?? "default";
376
+ const invalidationEpoch = policy?.invalidationEpoch ?? process.env.FORGE_DEPENDENCY_CACHE_EPOCH ?? "default";
377
+ const contract = {
378
+ schemaVersion: DEPENDENCY_RECEIPT_SCHEMA_VERSION,
379
+ preparationContract: DEPENDENCY_PREPARATION_CONTRACT,
380
+ ecosystem: entry.ecosystem,
381
+ packageRoot: entry.packageRoot.replaceAll("\\", "/"),
382
+ command,
383
+ inputDigests,
384
+ toolchainVersion,
385
+ nodeRuntime: process.version,
386
+ platform: process.platform,
387
+ architecture: process.arch,
388
+ osRelease: os.release(),
389
+ isolation: policy?.isolation ?? process.env.FORGE_RUNTIME_MODE ?? "managed_host_process",
390
+ trustDomainFingerprint: sha256Text(trustDomain),
391
+ invalidationEpochFingerprint: sha256Text(invalidationEpoch),
392
+ };
393
+ return `sha256:${sha256Text(JSON.stringify(contract))}`;
394
+ }
395
+ async function dependencyInputFiles(ecosystem, worktreePath, cwd) {
396
+ const result = new Set();
397
+ const directNames = ecosystem === "node"
398
+ ? ["package.json", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "pnpm-workspace.yaml", "yarn.lock", ".npmrc", ".yarnrc", ".yarnrc.yml", ".nvmrc", ".node-version"]
399
+ : ecosystem === "python"
400
+ ? ["pyproject.toml", "requirements.txt", "requirements-dev.txt", "poetry.lock", "Pipfile", "Pipfile.lock", "uv.lock", "pip.conf", "pyvenv.cfg"]
401
+ : ["global.json", "NuGet.Config", "nuget.config", "Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props", "packages.lock.json"];
402
+ let current = cwd;
403
+ const root = path.resolve(worktreePath);
404
+ while (isSubPath(root, current)) {
405
+ for (const name of directNames) {
406
+ const candidate = path.join(current, name);
407
+ if (await pathExists(candidate))
408
+ result.add(candidate);
409
+ }
410
+ if (ecosystem === "dotnet" && current === cwd) {
411
+ const entries = await fs.readdir(current, { withFileTypes: true }).catch(() => []);
412
+ for (const item of entries) {
413
+ if (item.isFile() && (/\.(?:csproj|fsproj|vbproj|sln|slnx)$/iu.test(item.name))) {
414
+ result.add(path.join(current, item.name));
415
+ }
416
+ }
417
+ }
418
+ if (current === root)
419
+ break;
420
+ current = path.dirname(current);
421
+ }
422
+ return [...result].sort((left, right) => left.localeCompare(right));
423
+ }
424
+ async function dependencyToolchainVersion(ecosystem, cwd, policy) {
425
+ if (ecosystem === "node") {
426
+ const manager = await pathExists(path.join(cwd, "pnpm-lock.yaml")) ? "pnpm" : "npm";
427
+ const override = policy?.toolchainVersions?.[manager];
428
+ if (override)
429
+ return `${manager}@${override};node@${process.version}`;
430
+ const launch = manager === "pnpm" ? resolvePnpmLaunch(["--version"]) : resolveNpmLaunch(["--version"]);
431
+ return `${manager}@${await readToolVersion(cwd, launch.command, launch.args)};node@${process.version}`;
432
+ }
433
+ const override = policy?.toolchainVersions?.[ecosystem];
434
+ if (override)
435
+ return `${ecosystem}@${override}`;
436
+ const launch = ecosystem === "dotnet"
437
+ ? { command: "dotnet", args: ["--version"] }
438
+ : { command: "python", args: ["--version"] };
439
+ return `${ecosystem}@${await readToolVersion(cwd, launch.command, launch.args)}`;
440
+ }
441
+ async function readToolVersion(cwd, command, args) {
442
+ return await defaultProcessRunner.run({ command, cwd, args })
443
+ .then(result => result.exitCode === 0
444
+ ? (result.stdout.trim() || result.stderr.trim() || "unknown").slice(0, 256)
445
+ : `unavailable:${result.exitCode}`)
446
+ .catch(() => "unavailable");
447
+ }
448
+ async function readDependencyPreparationReceipt(receiptPath) {
449
+ try {
450
+ const parsed = JSON.parse(await fs.readFile(receiptPath, "utf8"));
451
+ return parsed.schemaVersion === DEPENDENCY_RECEIPT_SCHEMA_VERSION
452
+ && typeof parsed.fingerprint === "string"
453
+ && typeof parsed.ecosystem === "string"
454
+ && typeof parsed.packageRoot === "string"
455
+ && typeof parsed.command === "string"
456
+ && typeof parsed.outputMarker === "string"
457
+ ? parsed
458
+ : null;
459
+ }
460
+ catch (error) {
461
+ if (error.code === "ENOENT" || error instanceof SyntaxError)
462
+ return null;
463
+ throw error;
464
+ }
465
+ }
466
+ async function persistDependencyPreparationReceipt(receiptPath, receipt) {
467
+ await fs.mkdir(path.dirname(receiptPath), { recursive: true });
468
+ const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
469
+ await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
470
+ try {
471
+ await fs.rename(temporaryPath, receiptPath);
472
+ }
473
+ finally {
474
+ await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
475
+ }
476
+ }
477
+ function sha256Text(value) {
478
+ return createHash("sha256").update(value).digest("hex");
479
+ }
480
+ async function runInstallFallback(entry, worktreePath, reason, executor, control = {}) {
481
+ assertHostDatabaseCapabilityBoundary();
229
482
  const cwd = path.join(worktreePath, entry.packageRoot === "." ? "" : entry.packageRoot);
230
483
  if (entry.ecosystem === "node") {
231
484
  const pnpmLockPath = path.join(cwd, "pnpm-lock.yaml");
232
485
  if (await pathExists(pnpmLockPath)) {
233
486
  const args = ["install", "--frozen-lockfile"];
234
487
  const launch = resolvePnpmLaunch(args);
235
- await executor.run(cwd, launch.command, launch.args, { env: unattendedPackageManagerEnvironment() });
488
+ await executor.run(cwd, launch.command, launch.args, {
489
+ env: unattendedPackageManagerEnvironment(process.env, {
490
+ packageRoot: cwd,
491
+ requiredPathDirectories: launch.requiredPathDirectories,
492
+ }),
493
+ windowsVerbatimArguments: launch.windowsVerbatimArguments,
494
+ ...control,
495
+ });
236
496
  return { ecosystem: entry.ecosystem, packageRoot: entry.packageRoot, reason, command: `pnpm ${args.join(" ")}` };
237
497
  }
238
498
  const lockPath = path.join(cwd, "package-lock.json");
239
499
  const args = (await pathExists(lockPath)) ? ["ci"] : ["install"];
240
500
  const launch = resolveNpmLaunch(args);
241
- await executor.run(cwd, launch.command, launch.args, { env: unattendedPackageManagerEnvironment() });
501
+ await executor.run(cwd, launch.command, launch.args, {
502
+ env: unattendedPackageManagerEnvironment(process.env, {
503
+ packageRoot: cwd,
504
+ requiredPathDirectories: launch.requiredPathDirectories,
505
+ }),
506
+ windowsVerbatimArguments: launch.windowsVerbatimArguments,
507
+ ...control,
508
+ });
242
509
  return { ecosystem: entry.ecosystem, packageRoot: entry.packageRoot, reason, command: `npm ${args.join(" ")}` };
243
510
  }
244
511
  if (entry.ecosystem === "python") {
245
- await executor.run(cwd, "python", ["-m", "venv", ".venv"]);
512
+ const environment = unattendedDependencyEnvironment();
513
+ await executor.run(cwd, "python", ["-m", "venv", ".venv"], { env: environment, ...control });
246
514
  const requirements = path.join(cwd, "requirements.txt");
247
515
  if (await pathExists(requirements)) {
248
516
  const pip = process.platform === "win32" ? path.join(".venv", "Scripts", "pip") : path.join(".venv", "bin", "pip");
249
- await executor.run(cwd, pip, ["install", "-r", "requirements.txt"]);
517
+ await executor.run(cwd, pip, ["install", "-r", "requirements.txt"], { env: environment, ...control });
250
518
  return {
251
519
  ecosystem: entry.ecosystem,
252
520
  packageRoot: entry.packageRoot,
@@ -261,7 +529,7 @@ async function runInstallFallback(entry, worktreePath, reason, executor) {
261
529
  command: "python -m venv .venv"
262
530
  };
263
531
  }
264
- await executor.run(cwd, "dotnet", ["restore"]);
532
+ await executor.run(cwd, "dotnet", ["restore"], { env: unattendedDependencyEnvironment(), ...control });
265
533
  return {
266
534
  ecosystem: entry.ecosystem,
267
535
  packageRoot: entry.packageRoot,
@@ -302,6 +570,79 @@ async function hasPythonMarker(dir) {
302
570
  return (await pathExists(path.join(dir, "pyproject.toml")))
303
571
  || (await pathExists(path.join(dir, "requirements.txt")));
304
572
  }
573
+ const solutionProjectPattern = /^Project\("\{[0-9A-Fa-f-]+\}"\)\s*=\s*"[^"]*"\s*,\s*"([^"]+\.(?:cs|fs|vb)proj)"/gimu;
574
+ const slnxProjectPattern = /<Project\b[^>]*\bPath\s*=\s*"([^"]+\.(?:cs|fs|vb)proj)"/giu;
575
+ const projectFilePattern = /\.(?:cs|fs|vb)proj$/iu;
576
+ const solutionFilePattern = /\.(?:sln|slnx|slnf)$/iu;
577
+ /**
578
+ * A worktree built from a never-built base checkout (a fresh runner clone has no bin/ or obj/)
579
+ * still needs its .NET projects restored, or the --no-restore runtime build fails with NETSDK1004.
580
+ * Restore exactly the projects the root solution(s) (.sln, .slnx, .slnf) list, or a lone root
581
+ * project when there is no solution. Other projects (fixtures, samples) keep the base-checkout
582
+ * output heuristic above.
583
+ */
584
+ async function collectSolutionProjectRestores(repoRoot, entries) {
585
+ const rootNames = await fs.readdir(repoRoot).catch(() => []);
586
+ const solutions = rootNames.filter((name) => solutionFilePattern.test(name));
587
+ if (solutions.length === 0) {
588
+ const rootProjects = rootNames.filter((name) => name.toLowerCase().endsWith(".csproj"));
589
+ if (rootProjects.length === 1) {
590
+ addEntry(entries, repoRoot, "", "obj", "dotnet", "obj");
591
+ }
592
+ return;
593
+ }
594
+ for (const solution of solutions) {
595
+ for (const listed of await readSolutionProjectPaths(repoRoot, solution)) {
596
+ const projectPath = path.posix.normalize(normalizeRelativePath(listed));
597
+ if (!projectPath || projectPath === ".." || projectPath.startsWith("../") || path.posix.isAbsolute(projectPath)) {
598
+ continue;
599
+ }
600
+ const absoluteProject = path.resolve(repoRoot, ...projectPath.split("/"));
601
+ if (!isSubPath(repoRoot, absoluteProject) || !(await pathExists(absoluteProject))) {
602
+ continue;
603
+ }
604
+ const projectDir = path.posix.dirname(projectPath);
605
+ // The fallback runs a bare `dotnet restore` in the project's directory. Beside the solution,
606
+ // or next to another project file, that restore is ambiguous (MSB1011); leave those layouts
607
+ // to the base-checkout output heuristic.
608
+ if (projectDir === "." || (await countProjectFiles(path.dirname(absoluteProject))) !== 1) {
609
+ continue;
610
+ }
611
+ addEntry(entries, repoRoot, projectDir, "obj", "dotnet", joinRelative(projectDir, "obj"));
612
+ }
613
+ }
614
+ }
615
+ /** Project paths a root solution lists, relative to the repo root (forward slashes). */
616
+ async function readSolutionProjectPaths(repoRoot, solution) {
617
+ const text = await fs.readFile(path.join(repoRoot, solution), "utf8").catch(() => "");
618
+ const lower = solution.toLowerCase();
619
+ if (lower.endsWith(".sln")) {
620
+ return [...text.matchAll(solutionProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
621
+ }
622
+ if (lower.endsWith(".slnx")) {
623
+ return [...text.matchAll(slnxProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
624
+ }
625
+ // .slnf: {"solution": {"path": "<solution>", "projects": [...]}}, projects relative to that solution.
626
+ let filter;
627
+ try {
628
+ filter = JSON.parse(text.replace(/^\uFEFF/u, ""));
629
+ }
630
+ catch {
631
+ return [];
632
+ }
633
+ const body = filter?.solution;
634
+ if (!body || typeof body.path !== "string" || !Array.isArray(body.projects)) {
635
+ return [];
636
+ }
637
+ const solutionDir = path.posix.dirname(body.path.replace(/\\/g, "/"));
638
+ return body.projects
639
+ .filter((project) => typeof project === "string" && projectFilePattern.test(project))
640
+ .map((project) => path.posix.join(solutionDir, project.replace(/\\/g, "/")));
641
+ }
642
+ async function countProjectFiles(dir) {
643
+ const names = await fs.readdir(dir).catch(() => []);
644
+ return names.filter((name) => projectFilePattern.test(name)).length;
645
+ }
305
646
  async function hasDotNetMarker(dir) {
306
647
  const entries = await fs.readdir(dir).catch(() => []);
307
648
  return entries.some((name) => name.endsWith(".csproj") || name.endsWith(".sln"));
@@ -360,14 +701,37 @@ async function sha256File(filePath) {
360
701
  export function resolveNpmLaunch(args, options = {}) {
361
702
  const env = options.env ?? process.env;
362
703
  const execPath = options.execPath ?? process.execPath;
704
+ const platform = options.platform ?? process.platform;
705
+ const pathExists = options.pathExists ?? existsSync;
363
706
  const npmExecPath = env.npm_execpath;
364
- if (npmExecPath) {
707
+ const npmExecPathIsAbsolute = platform === "win32"
708
+ ? path.win32.isAbsolute(npmExecPath ?? "")
709
+ : path.posix.isAbsolute(npmExecPath ?? "");
710
+ const npmExecPathBaseName = platform === "win32"
711
+ ? path.win32.basename(npmExecPath ?? "")
712
+ : path.posix.basename(npmExecPath ?? "");
713
+ if (npmExecPath
714
+ && npmExecPathIsAbsolute
715
+ && npmExecPathBaseName.toLowerCase() === "npm-cli.js"
716
+ && pathExists(npmExecPath)) {
365
717
  return { command: execPath, args: [npmExecPath, ...args] };
366
718
  }
367
- const platform = options.platform ?? process.platform;
368
719
  if (platform === "win32") {
369
- const comSpec = options.env ? env.ComSpec ?? "cmd.exe" : env.ComSpec;
370
- return buildWindowsCmdLaunch("npm.cmd", args, comSpec);
720
+ const command = resolveWindowsPackageManagerCommand("npm.cmd", env, pathExists, [path.win32.dirname(execPath)]);
721
+ if (!command) {
722
+ throw new Error("Windows npm launcher could not be resolved before PATH compaction.");
723
+ }
724
+ const cli = resolveWindowsPackageManagerCli("npm", command, execPath, pathExists);
725
+ if (cli)
726
+ return { command: execPath, args: [cli, ...args] };
727
+ const comSpec = options.env
728
+ ? windowsEnvironmentValue(env, "ComSpec") ?? "cmd.exe"
729
+ : windowsEnvironmentValue(env, "ComSpec");
730
+ return {
731
+ ...buildWindowsCmdLaunch(command, args, comSpec),
732
+ requiredPathDirectories: [path.win32.dirname(command)],
733
+ windowsVerbatimArguments: true,
734
+ };
371
735
  }
372
736
  for (const candidate of options.candidates ?? defaultNpmCliCandidates(execPath, options.homeDir ?? os.homedir())) {
373
737
  const resolvedCandidate = tryResolveNpmCandidate(candidate);
@@ -377,9 +741,26 @@ export function resolveNpmLaunch(args, options = {}) {
377
741
  }
378
742
  return { command: "npm", args };
379
743
  }
380
- export function resolvePnpmLaunch(args) {
381
- if (process.platform === "win32") {
382
- return buildWindowsCmdLaunch("pnpm.cmd", args, process.env.ComSpec);
744
+ export function resolvePnpmLaunch(args, options = {}) {
745
+ const platform = options.platform ?? process.platform;
746
+ if (platform === "win32") {
747
+ const env = options.env ?? process.env;
748
+ const execPath = options.execPath ?? process.execPath;
749
+ const command = resolveWindowsPackageManagerCommand("pnpm.cmd", env, options.pathExists ?? existsSync, [path.win32.dirname(execPath)]);
750
+ if (!command) {
751
+ throw new Error("Windows pnpm launcher could not be resolved before PATH compaction.");
752
+ }
753
+ const cli = resolveWindowsPackageManagerCli("pnpm", command, execPath, options.pathExists ?? existsSync);
754
+ if (cli)
755
+ return { command: execPath, args: [cli, ...args] };
756
+ const comSpec = options.env
757
+ ? windowsEnvironmentValue(env, "ComSpec") ?? "cmd.exe"
758
+ : windowsEnvironmentValue(env, "ComSpec");
759
+ return {
760
+ ...buildWindowsCmdLaunch(command, args, comSpec),
761
+ requiredPathDirectories: [path.win32.dirname(command)],
762
+ windowsVerbatimArguments: true,
763
+ };
383
764
  }
384
765
  return { command: "pnpm", args };
385
766
  }
@@ -394,8 +775,200 @@ export function formatCommandFailureOutput(stdout, stderr) {
394
775
  }
395
776
  return `[last ${MAX_COMMAND_FAILURE_OUTPUT_LENGTH} characters]\n${output.slice(-MAX_COMMAND_FAILURE_OUTPUT_LENGTH)}`;
396
777
  }
397
- export function unattendedPackageManagerEnvironment(env = process.env) {
398
- return { ...env, CI: "true" };
778
+ export function unattendedPackageManagerEnvironment(env = process.env, options = {}) {
779
+ const result = { ...unattendedDependencyEnvironment(env), CI: "true" };
780
+ if ((options.platform ?? process.platform) !== "win32")
781
+ return result;
782
+ const pathValue = windowsEnvironmentValues(env, "Path").join(";");
783
+ for (const key of Object.keys(result)) {
784
+ if (key.toLowerCase() === "path")
785
+ delete result[key];
786
+ }
787
+ result.PATH = compactWindowsPackageManagerPath(pathValue, env, options);
788
+ return result;
789
+ }
790
+ const dependencyEnvironmentAllowlist = new Set([
791
+ "appdata",
792
+ "comspec",
793
+ "corepack_home",
794
+ "dotnet_cli_home",
795
+ "dotnet_root",
796
+ "home",
797
+ "homedrive",
798
+ "homepath",
799
+ "http_proxy",
800
+ "https_proxy",
801
+ "localappdata",
802
+ "no_proxy",
803
+ "npm_config_cache",
804
+ "nuget_http_cache_path",
805
+ "nuget_packages",
806
+ "path",
807
+ "pathext",
808
+ "programdata",
809
+ "programfiles",
810
+ "programfiles(x86)",
811
+ "programw6432",
812
+ "ssl_cert_dir",
813
+ "ssl_cert_file",
814
+ "systemdrive",
815
+ "systemroot",
816
+ "temp",
817
+ "tmp",
818
+ "tmpdir",
819
+ "userdomain",
820
+ "username",
821
+ "userprofile",
822
+ "windir",
823
+ ]);
824
+ export function unattendedDependencyEnvironment(env = process.env) {
825
+ return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string"
826
+ && (dependencyEnvironmentAllowlist.has(name.toLowerCase()) || name.toUpperCase().startsWith("LC_"))));
827
+ }
828
+ export function compactWindowsPackageManagerPath(pathValue, env = process.env, options = {}) {
829
+ const pathExists = options.pathExists ?? existsSync;
830
+ const maximumPathLength = options.maximumPathLength
831
+ ?? windowsPackageManagerPathBudget(options.packageRoot ?? process.cwd());
832
+ const execPath = options.execPath ?? process.execPath;
833
+ if (!Number.isSafeInteger(maximumPathLength) || maximumPathLength < 1) {
834
+ throw new Error(`Windows package-manager PATH budget is exhausted before launch (${maximumPathLength}).`);
835
+ }
836
+ const normalize = windowsPathNormalizer(env);
837
+ const inherited = [];
838
+ const seen = new Set();
839
+ for (const candidate of pathValue.split(";").map(normalize)) {
840
+ if (candidate.length === 0 || !path.win32.isAbsolute(candidate) || !pathExists(candidate))
841
+ continue;
842
+ const key = candidate.toLowerCase();
843
+ if (seen.has(key))
844
+ continue;
845
+ inherited.push(candidate);
846
+ seen.add(key);
847
+ }
848
+ const nodeDirectory = normalize(path.win32.dirname(execPath));
849
+ if (!nodeDirectory || !path.win32.isAbsolute(nodeDirectory) || !pathExists(nodeDirectory)) {
850
+ throw new Error(`Windows Node runtime directory is unavailable: ${nodeDirectory || "<empty>"}.`);
851
+ }
852
+ const systemRoot = normalize(windowsEnvironmentValue(env, "SystemRoot") ?? "");
853
+ const requiredCandidates = [
854
+ nodeDirectory,
855
+ normalize(path.win32.dirname(windowsEnvironmentValue(env, "ComSpec") ?? "")),
856
+ systemRoot ? path.win32.join(systemRoot, "System32") : "",
857
+ systemRoot,
858
+ ].filter(candidate => candidate.length > 0
859
+ && path.win32.isAbsolute(candidate)
860
+ && pathExists(candidate));
861
+ const explicitRequired = (options.requiredPathDirectories ?? []).map(normalize);
862
+ for (const candidate of explicitRequired) {
863
+ if (!candidate || !path.win32.isAbsolute(candidate) || !pathExists(candidate)) {
864
+ throw new Error(`Windows package-manager required PATH directory is unavailable: ${candidate || "<empty>"}.`);
865
+ }
866
+ requiredCandidates.push(candidate);
867
+ }
868
+ const required = new Map();
869
+ for (const candidate of requiredCandidates)
870
+ required.set(candidate.toLowerCase(), candidate);
871
+ const ordered = [...inherited];
872
+ for (const candidate of required.values()) {
873
+ if (!seen.has(candidate.toLowerCase()))
874
+ ordered.push(candidate);
875
+ }
876
+ const requiredLength = joinedWindowsPathLength([...required.values()]);
877
+ if (requiredLength > maximumPathLength) {
878
+ throw new Error(`Windows package-manager PATH cannot retain required runtime directories within ${maximumPathLength} characters.`);
879
+ }
880
+ const selected = new Set(required.keys());
881
+ let selectedLength = requiredLength;
882
+ for (const candidate of inherited) {
883
+ const key = candidate.toLowerCase();
884
+ if (selected.has(key))
885
+ continue;
886
+ const nextLength = selectedLength + (selected.size === 0 ? 0 : 1) + candidate.length;
887
+ if (nextLength > maximumPathLength)
888
+ continue;
889
+ selected.add(key);
890
+ selectedLength = nextLength;
891
+ }
892
+ return ordered.filter(candidate => selected.has(candidate.toLowerCase())).join(";");
893
+ }
894
+ export function windowsPackageManagerLifecyclePathPrefix(packageRoot) {
895
+ const entries = [];
896
+ let current = path.win32.resolve(packageRoot);
897
+ while (true) {
898
+ entries.push(path.win32.join(current, "node_modules", ".bin"));
899
+ const parent = path.win32.dirname(current);
900
+ if (parent === current)
901
+ break;
902
+ current = parent;
903
+ }
904
+ return entries.join(";");
905
+ }
906
+ export function windowsPackageManagerPathBudget(packageRoot) {
907
+ const lifecyclePrefix = windowsPackageManagerLifecyclePathPrefix(packageRoot);
908
+ return WINDOWS_COMMAND_ENVIRONMENT_PATH_LIMIT
909
+ - lifecyclePrefix.length
910
+ - 1
911
+ - WINDOWS_PACKAGE_MANAGER_INTERNAL_PATH_RESERVE;
912
+ }
913
+ function resolveWindowsPackageManagerCommand(commandName, env, pathExists, fallbackDirectories) {
914
+ const normalize = windowsPathNormalizer(env);
915
+ const directories = [
916
+ ...windowsEnvironmentValues(env, "Path").flatMap(value => value.split(";")),
917
+ ...fallbackDirectories,
918
+ ].map(normalize);
919
+ const seen = new Set();
920
+ for (const directory of directories) {
921
+ if (!directory || !path.win32.isAbsolute(directory))
922
+ continue;
923
+ const key = directory.toLowerCase();
924
+ if (seen.has(key))
925
+ continue;
926
+ seen.add(key);
927
+ const candidate = path.win32.join(directory, commandName);
928
+ if (pathExists(candidate))
929
+ return candidate;
930
+ }
931
+ return null;
932
+ }
933
+ function resolveWindowsPackageManagerCli(manager, commandPath, execPath, pathExists) {
934
+ const commandDirectory = path.win32.dirname(commandPath);
935
+ const execDirectory = path.win32.dirname(execPath);
936
+ const candidates = manager === "npm"
937
+ ? [
938
+ path.win32.join(commandDirectory, "node_modules", "npm", "bin", "npm-cli.js"),
939
+ path.win32.join(execDirectory, "node_modules", "npm", "bin", "npm-cli.js"),
940
+ path.win32.join(execDirectory, "node_modules", "corepack", "dist", "npm.js"),
941
+ ]
942
+ : [
943
+ path.win32.join(commandDirectory, "node_modules", "pnpm", "bin", "pnpm.mjs"),
944
+ path.win32.join(execDirectory, "node_modules", "pnpm", "bin", "pnpm.mjs"),
945
+ path.win32.join(execDirectory, "node_modules", "corepack", "dist", "pnpm.js"),
946
+ ];
947
+ return candidates.find(pathExists) ?? null;
948
+ }
949
+ function windowsPathNormalizer(env) {
950
+ const environment = new Map(Object.entries(env).map(([key, value]) => [key.toLowerCase(), value ?? ""]));
951
+ return (value) => {
952
+ const trimmed = value.trim();
953
+ const unquoted = trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')
954
+ ? trimmed.slice(1, -1).trim()
955
+ : trimmed;
956
+ return unquoted.replace(/%([^%]+)%/gu, (match, name) => environment.get(name.toLowerCase()) || match);
957
+ };
958
+ }
959
+ function windowsEnvironmentValues(env, name) {
960
+ const normalized = name.toLowerCase();
961
+ return Object.entries(env)
962
+ .filter(([key, value]) => key.toLowerCase() === normalized && Boolean(value))
963
+ .map(([, value]) => value);
964
+ }
965
+ function windowsEnvironmentValue(env, name) {
966
+ return windowsEnvironmentValues(env, name)[0];
967
+ }
968
+ function joinedWindowsPathLength(entries) {
969
+ return entries.length === 0
970
+ ? 0
971
+ : entries.reduce((total, entry) => total + entry.length, entries.length - 1);
399
972
  }
400
973
  function tryResolveNpmCandidate(candidate) {
401
974
  try {
@@ -417,9 +990,21 @@ function defaultNpmCliCandidates(execPath, homeDir) {
417
990
  candidates.push("/usr/bin/npm", "/usr/local/bin/npm", path.join(homeDir, ".npm-global", "bin", "npm"), path.join(homeDir, ".npm-global", "lib", "node_modules", "npm", "bin", "npm-cli.js"));
418
991
  return candidates;
419
992
  }
420
- const defaultCommandExecutor = {
993
+ /** Runs dependency installs; exported for tests. */
994
+ export const defaultCommandExecutor = {
421
995
  async run(cwd, command, args, options) {
422
- const result = await defaultProcessRunner.run({ command, cwd, args, env: options?.env });
996
+ const result = await defaultProcessRunner.run({
997
+ command,
998
+ cwd,
999
+ args,
1000
+ env: options?.env,
1001
+ windowsVerbatimArguments: options?.windowsVerbatimArguments,
1002
+ signal: options?.signal,
1003
+ onSpawn: options?.onSpawn,
1004
+ processGroup: options?.processGroup,
1005
+ // Only a failure excerpt is ever reported; a noisy install keeps its last 1 MiB.
1006
+ maxOutputChars: 1024 * 1024,
1007
+ });
423
1008
  if (result.exitCode !== 0) {
424
1009
  const output = formatCommandFailureOutput(result.stdout, result.stderr);
425
1010
  const details = output.length > 0 ? `\n${output}` : " no output was captured";