@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.4-dev.028808a841c8

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