@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.ec3460040366

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 (212) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +88 -14
  16. package/dist/bridge/bridge.service.js +406 -345
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +62 -4
  83. package/dist/runtime/host-runtime-lease.js +235 -168
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  92. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  93. package/dist/runtime/runner-settings.d.ts +104 -0
  94. package/dist/runtime/runner-settings.js +236 -0
  95. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  96. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  97. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  98. package/dist/sandbox/host-capacity-broker.js +27 -6
  99. package/dist/sandbox/managed-branch.d.ts +13 -0
  100. package/dist/sandbox/managed-branch.js +90 -0
  101. package/dist/sandbox/provider-auth/codex.js +11 -11
  102. package/dist/sandbox/runtime.js +2 -6
  103. package/dist/session/architect-waits.d.ts +2 -0
  104. package/dist/session/architect-waits.js +138 -0
  105. package/dist/session/managed-attempt-tools.d.ts +0 -7
  106. package/dist/session/managed-attempt-tools.js +58 -91
  107. package/dist/session/managed-build-coordinator.d.ts +16 -0
  108. package/dist/session/managed-build-coordinator.js +10 -0
  109. package/dist/session/managed-build-receipt.d.ts +5 -0
  110. package/dist/session/managed-build-receipt.js +8 -3
  111. package/dist/session/managed-command-host-load.d.ts +2 -0
  112. package/dist/session/managed-command-host-load.js +2 -1
  113. package/dist/session/phase-completion.artifacts.js +2 -1
  114. package/dist/session/phase-completion.d.ts +8 -0
  115. package/dist/session/phase-completion.js +1 -0
  116. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  117. package/dist/session/phase-completion.mcp-args.js +156 -0
  118. package/dist/session/phase-completion.runtime.d.ts +0 -8
  119. package/dist/session/phase-completion.runtime.js +43 -197
  120. package/dist/session/phase-completion.schemas.js +25 -23
  121. package/dist/session/phase-completion.validation.js +3 -1
  122. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  123. package/dist/session/pre-publication-native-postgres.js +111 -0
  124. package/dist/session/pre-publication-pass.d.ts +61 -0
  125. package/dist/session/pre-publication-pass.js +148 -0
  126. package/dist/session/pre-publication-process.js +10 -10
  127. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  128. package/dist/session/pre-publication-step-execution.js +6 -5
  129. package/dist/session/pre-publication-validation.d.ts +30 -14
  130. package/dist/session/pre-publication-validation.js +207 -134
  131. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  132. package/dist/session/provider-cli/claude-background-work.js +181 -0
  133. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  134. package/dist/session/provider-cli/host-build-lock.js +30 -0
  135. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  136. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  137. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  138. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  139. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  140. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  141. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  142. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  143. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  144. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  145. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  146. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  147. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  148. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  149. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  150. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  151. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  152. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  153. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  154. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  155. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  156. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  157. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  158. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  159. package/dist/session/provider-cli/provider-output-state.js +6 -0
  160. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  161. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  162. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  163. package/dist/session/qa-sidecar-validation.js +28 -0
  164. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  165. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  166. package/dist/session/session-redaction.js +31 -181
  167. package/dist/session/session.base.d.ts +6 -1
  168. package/dist/session/session.service.d.ts +9 -2
  169. package/dist/session/session.service.js +169 -66
  170. package/dist/session/session.types.js +4 -4
  171. package/dist/session/sidecar-json-shape.d.ts +31 -0
  172. package/dist/session/sidecar-json-shape.js +217 -0
  173. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  174. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  175. package/dist/shared/fs/file-identity.d.ts +10 -0
  176. package/dist/shared/fs/file-identity.js +15 -0
  177. package/dist/shared/fs/replace-file.d.ts +7 -0
  178. package/dist/shared/fs/replace-file.js +33 -0
  179. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  180. package/dist/shared/process/host-process-recovery.js +23 -3
  181. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  182. package/dist/shared/process/host-process-supervisor.js +66 -14
  183. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  184. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  185. package/dist/shared/process/windows-launch.d.ts +18 -0
  186. package/dist/shared/process/windows-launch.js +68 -0
  187. package/dist/shared/provider-capabilities.js +14 -7
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/dist/worktree/orphan-relink.d.ts +19 -0
  191. package/dist/worktree/orphan-relink.js +106 -0
  192. package/dist/worktree/wip-git.d.ts +33 -0
  193. package/dist/worktree/wip-git.js +122 -0
  194. package/dist/worktree/wip-refs.d.ts +62 -0
  195. package/dist/worktree/wip-refs.js +119 -0
  196. package/dist/worktree/wip-restore.d.ts +38 -0
  197. package/dist/worktree/wip-restore.js +190 -0
  198. package/dist/worktree/wip-snapshot.d.ts +50 -0
  199. package/dist/worktree/wip-snapshot.js +268 -0
  200. package/dist/worktree/worktree-inputs.d.ts +8 -0
  201. package/dist/worktree/worktree-inputs.js +134 -0
  202. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  203. package/dist/worktree/worktree-origin-sync.js +127 -0
  204. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  205. package/dist/worktree/worktree-wip-events.js +98 -0
  206. package/dist/worktree/worktree-wip.d.ts +50 -0
  207. package/dist/worktree/worktree-wip.js +185 -0
  208. package/dist/worktree/worktree.base.d.ts +7 -1
  209. package/dist/worktree/worktree.service.d.ts +27 -5
  210. package/dist/worktree/worktree.service.js +110 -181
  211. package/dist/worktree/worktree.types.d.ts +31 -0
  212. package/package.json +2 -2
@@ -0,0 +1,32 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ /**
3
+ * What the attempt's host runtime stack was built and launched from. When the
4
+ * workspace no longer matches, the running API binary and dev server are stale:
5
+ * an uncommitted edit or an in-progress `merge --no-commit` changes the source
6
+ * without moving HEAD.
7
+ */
8
+ export interface WorkspaceRuntimeFingerprint {
9
+ readonly headSha: string;
10
+ /** Contents of MERGE_HEAD while a merge is in progress, else null. */
11
+ readonly mergeHead: string | null;
12
+ /** sha256 of `git diff HEAD --binary` (staged and unstaged changes to tracked files, mode changes included). */
13
+ readonly diffDigest: string;
14
+ /**
15
+ * sha256 over untracked, non-ignored file names, their executable bit, and their contents (or
16
+ * size and mtime for large files).
17
+ */
18
+ readonly untrackedDigest: string;
19
+ /**
20
+ * sha256 over the runtime contract as loaded now and the files its launch commands name. Git's
21
+ * views above skip ignored files, and a project may ignore its contract or a launch script; a
22
+ * change there alters what the stack runs without changing anything git reports.
23
+ */
24
+ readonly runtimeInputsDigest: string;
25
+ /** One digest over every field above. */
26
+ readonly digest: string;
27
+ }
28
+ export type WorkspaceRuntimeFingerprintReader = (worktreePath: string) => Promise<WorkspaceRuntimeFingerprint>;
29
+ export declare function readWorkspaceRuntimeFingerprint(worktreePath: string, git?: Pick<GitClient, "run">): Promise<WorkspaceRuntimeFingerprint>;
30
+ export declare function sameWorkspaceRuntimeFingerprint(left: WorkspaceRuntimeFingerprint | null, right: WorkspaceRuntimeFingerprint | null): boolean;
31
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
32
+ export declare function workspaceRuntimeFingerprintChanges(previous: WorkspaceRuntimeFingerprint | null, current: WorkspaceRuntimeFingerprint): readonly string[];
@@ -0,0 +1,138 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { GitClient } from "../shared/git/git.js";
5
+ import { loadHostRuntimeContract } from "../runtime/host-runtime-contract.js";
6
+ import { hostRuntimeContractFingerprint } from "../runtime/host-runtime-promotion.js";
7
+ import { isRuntimeOnlyPath } from "./publishable-worktree-changes.js";
8
+ /** Untracked files up to this size are hashed by content; larger ones by size and mtime. */
9
+ const untrackedContentHashLimitBytes = 1024 * 1024;
10
+ /**
11
+ * Forge's own runtime output never changes what the application runs, and Forge
12
+ * rewrites some of it (readiness manifests, completion artifacts) between passes.
13
+ */
14
+ const runtimeOnlyPathspecs = [
15
+ ":(exclude).local",
16
+ ":(exclude).forge/work-items",
17
+ ":(exclude).forge/stories",
18
+ ];
19
+ export async function readWorkspaceRuntimeFingerprint(worktreePath, git = new GitClient()) {
20
+ const headSha = (await git.run(worktreePath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim().toLowerCase();
21
+ const mergeHead = await readMergeHead(git, worktreePath);
22
+ // A mode change (chmod +x on a launch script) changes what runs. The repository may set
23
+ // core.fileMode=false, which would drop it from the diff, so this read always records modes.
24
+ const diff = await git.run(worktreePath, ["-c", "core.fileMode=true", "diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv", "--", ".", ...runtimeOnlyPathspecs]);
25
+ const diffDigest = sha256(diff);
26
+ const untracked = (await git.run(worktreePath, [
27
+ "ls-files", "--others", "--exclude-standard", "-z", "--", ".", ...runtimeOnlyPathspecs,
28
+ ]))
29
+ .split("\0")
30
+ .filter(entry => entry.length > 0 && !isRuntimeOnlyPath(entry))
31
+ .sort((left, right) => left.localeCompare(right));
32
+ const untrackedHash = createHash("sha256");
33
+ for (const relative of untracked) {
34
+ untrackedHash.update(relative).update("\0");
35
+ const absolute = path.join(worktreePath, relative);
36
+ const stat = await fs.lstat(absolute).catch(() => null);
37
+ if (!stat) {
38
+ untrackedHash.update("missing\0");
39
+ continue;
40
+ }
41
+ // Like git, record the executable bit: chmod changes what runs without touching content or mtime.
42
+ untrackedHash.update(stat.isFile() && (stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
43
+ if (stat.isFile() && stat.size <= untrackedContentHashLimitBytes) {
44
+ const content = await fs.readFile(absolute).catch(() => null);
45
+ untrackedHash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
46
+ }
47
+ else {
48
+ untrackedHash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
49
+ }
50
+ }
51
+ const untrackedDigest = `sha256:${untrackedHash.digest("hex")}`;
52
+ const runtimeInputsDigest = await readRuntimeInputsDigest(worktreePath);
53
+ const digest = sha256(JSON.stringify({ headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest }));
54
+ return { headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest, digest };
55
+ }
56
+ export function sameWorkspaceRuntimeFingerprint(left, right) {
57
+ return left !== null && right !== null && left.digest === right.digest;
58
+ }
59
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
60
+ export function workspaceRuntimeFingerprintChanges(previous, current) {
61
+ if (!previous)
62
+ return ["unrecorded"];
63
+ const changes = [];
64
+ if (previous.headSha !== current.headSha)
65
+ changes.push("head");
66
+ if (previous.mergeHead !== current.mergeHead)
67
+ changes.push("merge_head");
68
+ if (previous.diffDigest !== current.diffDigest)
69
+ changes.push("tracked_changes");
70
+ if (previous.untrackedDigest !== current.untrackedDigest)
71
+ changes.push("untracked_files");
72
+ if (previous.runtimeInputsDigest !== current.runtimeInputsDigest)
73
+ changes.push("runtime_inputs");
74
+ return changes;
75
+ }
76
+ /**
77
+ * The loaded runtime contract (project file or derived) and each regular file inside the worktree
78
+ * that a configured launch names as its command or an argument, by executable bit and content.
79
+ * Ignored or not: these are exactly what the stack was launched from. Nothing else ignored is read.
80
+ */
81
+ async function readRuntimeInputsDigest(worktreePath) {
82
+ const hash = createHash("sha256");
83
+ let contract;
84
+ try {
85
+ contract = await loadHostRuntimeContract(worktreePath);
86
+ }
87
+ catch (error) {
88
+ // An unloadable contract is a state of its own; the restart reports why it cannot load.
89
+ const message = error instanceof Error ? error.message : String(error);
90
+ return sha256(`unloadable:${message.split(":", 1)[0]}`);
91
+ }
92
+ hash.update(`contract:${hostRuntimeContractFingerprint(contract)}\0`);
93
+ const root = await fs.realpath(worktreePath);
94
+ const named = new Set();
95
+ for (const port of contract.contract.runtime.ports) {
96
+ if (!port.launch)
97
+ continue;
98
+ const workingDirectory = path.resolve(root, port.launch.workingDirectory);
99
+ for (const candidate of [port.launch.command, ...port.launch.args]) {
100
+ if (!candidate || candidate.startsWith("-"))
101
+ continue;
102
+ const absolute = path.resolve(workingDirectory, candidate);
103
+ const relative = path.relative(root, absolute);
104
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative))
105
+ continue;
106
+ named.add(relative);
107
+ }
108
+ }
109
+ for (const relative of [...named].sort((left, right) => left.localeCompare(right))) {
110
+ const stat = await fs.stat(path.join(root, relative)).catch(() => null);
111
+ if (!stat?.isFile())
112
+ continue;
113
+ hash.update(relative).update("\0").update((stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
114
+ if (stat.size <= untrackedContentHashLimitBytes) {
115
+ const content = await fs.readFile(path.join(root, relative)).catch(() => null);
116
+ hash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
117
+ }
118
+ else {
119
+ hash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
120
+ }
121
+ }
122
+ return `sha256:${hash.digest("hex")}`;
123
+ }
124
+ async function readMergeHead(git, worktreePath) {
125
+ const relative = (await git.run(worktreePath, ["rev-parse", "--git-path", "MERGE_HEAD"])).trim();
126
+ if (!relative)
127
+ return null;
128
+ const mergeHeadPath = path.resolve(worktreePath, relative);
129
+ const content = await fs.readFile(mergeHeadPath, "utf8").catch((error) => {
130
+ if (error.code === "ENOENT")
131
+ return null;
132
+ throw error;
133
+ });
134
+ return content === null ? null : content.trim().toLowerCase();
135
+ }
136
+ function sha256(value) {
137
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
138
+ }
@@ -0,0 +1,10 @@
1
+ import type { BigIntStats } from "node:fs";
2
+ export type FileIdentity = Pick<BigIntStats, "dev" | "ino">;
3
+ export declare function sameFileIdentity(left: FileIdentity, right: FileIdentity): boolean;
4
+ /**
5
+ * Whether a path now names a different file than before. A filesystem that reports no
6
+ * identity (a zero device or id) cannot show a change, so none is claimed for it.
7
+ */
8
+ export declare function fileIdentityChanged(before: FileIdentity, after: FileIdentity): boolean;
9
+ /** The identity as text, for keys and records. */
10
+ export declare function fileIdentityKey(identity: FileIdentity): string;
@@ -0,0 +1,15 @@
1
+ export function sameFileIdentity(left, right) {
2
+ return left.dev === right.dev && left.ino === right.ino;
3
+ }
4
+ /**
5
+ * Whether a path now names a different file than before. A filesystem that reports no
6
+ * identity (a zero device or id) cannot show a change, so none is claimed for it.
7
+ */
8
+ export function fileIdentityChanged(before, after) {
9
+ const known = before.dev !== 0n && before.ino !== 0n && after.dev !== 0n && after.ino !== 0n;
10
+ return known && !sameFileIdentity(before, after);
11
+ }
12
+ /** The identity as text, for keys and records. */
13
+ export function fileIdentityKey(identity) {
14
+ return `${identity.dev}:${identity.ino}`;
15
+ }
@@ -0,0 +1,7 @@
1
+ export interface ReplaceFileOptions {
2
+ readonly deadlineMs?: number;
3
+ /** Test support: the rename to retry. */
4
+ readonly rename?: (from: string, to: string) => Promise<void>;
5
+ }
6
+ /** Renames `temporaryPath` over `targetPath`, waiting out a reader that holds the target open. */
7
+ export declare function replaceFile(temporaryPath: string, targetPath: string, options?: ReplaceFileOptions): Promise<void>;
@@ -0,0 +1,33 @@
1
+ import fs from "node:fs/promises";
2
+ import { monotonicNowMs } from "../time/monotonic.js";
3
+ // Windows refuses to rename over a file any other handle has open (EPERM,
4
+ // EBUSY, or EACCES), even one opened to share delete, which is how Node opens
5
+ // every file. A receipt that agents and Forge poll is open for a moment many
6
+ // times a second, and an antivirus scan can hold it longer; fixed-interval
7
+ // retries can also fall into step with a poller of the same period. Replacing
8
+ // it therefore retries with growing, jittered delays until a deadline, so a
9
+ // reader can delay a replace but never fail it.
10
+ const replaceRetryCodes = new Set(["EACCES", "EBUSY", "EPERM"]);
11
+ const defaultReplaceDeadlineMs = 15_000;
12
+ const firstRetryDelayMs = 5;
13
+ const maximumRetryDelayMs = 250;
14
+ /** Renames `temporaryPath` over `targetPath`, waiting out a reader that holds the target open. */
15
+ export async function replaceFile(temporaryPath, targetPath, options = {}) {
16
+ const rename = options.rename ?? fs.rename;
17
+ const deadline = monotonicNowMs() + (options.deadlineMs ?? defaultReplaceDeadlineMs);
18
+ for (let attempt = 0;; attempt += 1) {
19
+ try {
20
+ await rename(temporaryPath, targetPath);
21
+ return;
22
+ }
23
+ catch (error) {
24
+ const code = error?.code;
25
+ const remainingMs = deadline - monotonicNowMs();
26
+ if (!code || !replaceRetryCodes.has(code) || remainingMs <= 0)
27
+ throw error;
28
+ const ceilingMs = Math.min(maximumRetryDelayMs, firstRetryDelayMs * 2 ** Math.min(attempt, 6));
29
+ const delayMs = Math.min(remainingMs, ceilingMs / 2 + Math.random() * ceilingMs / 2);
30
+ await new Promise(resolve => setTimeout(resolve, delayMs));
31
+ }
32
+ }
33
+ }
@@ -1,12 +1,23 @@
1
- import type { HostProcessSupervisorMetadata } from "./host-process-supervisor.js";
1
+ import type { HostProcessSupervisorMetadata, WindowsSupervisorJobGone } from "./host-process-supervisor.js";
2
+ export { waitForWindowsSupervisorJobGone, type WindowsSupervisorJobGone } from "./host-process-supervisor.js";
2
3
  export type HostProcessRecoveryOutcome = "absent" | "terminated" | "pid_reused" | "unverifiable";
3
4
  export interface HostProcessRecovery {
4
5
  recover(metadata: HostProcessSupervisorMetadata): Promise<HostProcessRecoveryOutcome>;
5
6
  }
6
- /** Exact, birth-marker-fenced recovery for a process tree left by an old bridge. */
7
+ /**
8
+ * Exact, birth-marker-fenced recovery for a process tree left by an old bridge.
9
+ *
10
+ * On Windows the recorded root is the job supervisor, which holds the only handle to a
11
+ * kill-on-close Job Object holding the whole tree. The root's exit only starts that job's
12
+ * teardown: Windows reports a process gone once its exit code is set, before its handles
13
+ * are closed, and the members are stopped after that. So a Windows tree is reported gone
14
+ * only once its Job Object no longer exists, which is when no member is left.
15
+ */
7
16
  export declare class ExactHostProcessRecovery implements HostProcessRecovery {
8
17
  private readonly platform;
9
18
  private readonly graceMs;
10
- constructor(platform?: NodeJS.Platform, graceMs?: number);
19
+ private readonly windowsJobGone;
20
+ constructor(platform?: NodeJS.Platform, graceMs?: number, windowsJobGone?: WindowsSupervisorJobGone);
11
21
  recover(metadata: HostProcessSupervisorMetadata): Promise<HostProcessRecoveryOutcome>;
22
+ private stopRoot;
12
23
  }
@@ -1,14 +1,34 @@
1
- import { captureHostProcessIdentity } from "./host-process-supervisor.js";
1
+ import { captureHostProcessIdentity, waitForWindowsSupervisorJobGone } from "./host-process-supervisor.js";
2
2
  import { monotonicNowMs } from "../time/monotonic.js";
3
- /** Exact, birth-marker-fenced recovery for a process tree left by an old bridge. */
3
+ export { waitForWindowsSupervisorJobGone } from "./host-process-supervisor.js";
4
+ /**
5
+ * Exact, birth-marker-fenced recovery for a process tree left by an old bridge.
6
+ *
7
+ * On Windows the recorded root is the job supervisor, which holds the only handle to a
8
+ * kill-on-close Job Object holding the whole tree. The root's exit only starts that job's
9
+ * teardown: Windows reports a process gone once its exit code is set, before its handles
10
+ * are closed, and the members are stopped after that. So a Windows tree is reported gone
11
+ * only once its Job Object no longer exists, which is when no member is left.
12
+ */
4
13
  export class ExactHostProcessRecovery {
5
14
  platform;
6
15
  graceMs;
7
- constructor(platform = process.platform, graceMs = 2_000) {
16
+ windowsJobGone;
17
+ constructor(platform = process.platform, graceMs = 2_000, windowsJobGone = waitForWindowsSupervisorJobGone) {
8
18
  this.platform = platform;
9
19
  this.graceMs = graceMs;
20
+ this.windowsJobGone = windowsJobGone;
10
21
  }
11
22
  async recover(metadata) {
23
+ const outcome = await this.stopRoot(metadata);
24
+ if (outcome === "unverifiable" || this.platform !== "win32" || metadata.strategy !== "windows_job_object")
25
+ return outcome;
26
+ if (!await this.windowsJobGone(metadata.supervisorId, this.graceMs)) {
27
+ throw new Error(`host_process_recovery_degraded: the Job Object of supervisor ${metadata.supervisorId} still holds processes after its root stopped.`);
28
+ }
29
+ return outcome;
30
+ }
31
+ async stopRoot(metadata) {
12
32
  if (!processExists(metadata.rootPid))
13
33
  return "absent";
14
34
  if (!metadata.rootIdentity)
@@ -56,5 +56,17 @@ export declare function persistHostProcessSupervisorMetadata(launch: HostProcess
56
56
  * at an unrelated process.
57
57
  */
58
58
  export declare function captureHostProcessIdentity(pid: number, platform?: NodeJS.Platform): string | null;
59
- export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number): Promise<void>;
59
+ export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number, windowsJobGone?: WindowsSupervisorJobGone): Promise<void>;
60
+ /**
61
+ * Resolves true once a Windows job supervisor's Job Object no longer exists, false when it
62
+ * still does at the timeout or cannot be checked.
63
+ */
64
+ export type WindowsSupervisorJobGone = (supervisorId: string, timeoutMs: number) => Promise<boolean>;
65
+ /**
66
+ * Polls for the job supervisor's named Job Object (runtime/windows-job-supervisor.ps1 names
67
+ * it Local\Forge-<supervisorId>). A job object exists while any handle or member process
68
+ * holds it, and the supervisor's handle closed with it, so its absence means no member is
69
+ * left. Any answer but "not found" (an unreadable job, a failed check) is not proof.
70
+ */
71
+ export declare const waitForWindowsSupervisorJobGone: WindowsSupervisorJobGone;
60
72
  export declare function windowsPowerShellPath(): string;
@@ -1,9 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
- import { execFileSync } from "node:child_process";
2
+ import { execFile, execFileSync } from "node:child_process";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { promisify } from "node:util";
6
7
  import { monotonicNowMs } from "../time/monotonic.js";
8
+ const execFileAsync = promisify(execFile);
7
9
  const windowsJobSupervisorPath = fileURLToPath(new URL("../../../runtime/windows-job-supervisor.ps1", import.meta.url));
8
10
  export function resolveHostProcessSupervisedLaunch(request, resolvedCommand, resolvedArgs, platform = process.platform) {
9
11
  const env = request.env;
@@ -154,7 +156,7 @@ export function captureHostProcessIdentity(pid, platform = process.platform) {
154
156
  return null;
155
157
  }
156
158
  }
157
- export async function terminateHostProcessTree(child, launch, graceMs = 2_000) {
159
+ export async function terminateHostProcessTree(child, launch, graceMs = 2_000, windowsJobGone = waitForWindowsSupervisorJobGone) {
158
160
  if (!launch) {
159
161
  await terminateUnsupervisedProcessTree(child, graceMs);
160
162
  return;
@@ -162,22 +164,19 @@ export async function terminateHostProcessTree(child, launch, graceMs = 2_000) {
162
164
  if (launch.strategy === "windows_job_object") {
163
165
  const rootPid = child.pid ?? 0;
164
166
  const metadata = readSupervisorMetadata(launch.metadataPath);
165
- const rootIdentity = metadata?.rootPid === rootPid
166
- ? metadata.rootIdentity ?? null
167
- : captureHostProcessIdentity(rootPid, "win32");
168
167
  try {
169
168
  child.kill("SIGTERM");
170
169
  }
171
170
  catch {
172
171
  // Closing the launcher is best effort when the Job Object already settled.
173
172
  }
174
- await waitForExactProcessExit(rootPid, rootIdentity, graceMs, "win32");
175
- if (exactProcessExists(rootPid, rootIdentity, "win32")) {
173
+ // The root is this process's own child: its exit is observed through the handle
174
+ // Node holds, not by polling its identity with a PowerShell launch per check.
175
+ if (!await waitForChildExit(child, graceMs)) {
176
176
  forceWindowsProcessTree(rootPid);
177
- await waitForExactProcessExit(rootPid, rootIdentity, graceMs, "win32");
178
- }
179
- if (exactProcessExists(rootPid, rootIdentity, "win32")) {
180
- throw new Error("host_process_supervisor_termination_failed: supervised Windows root did not stop.");
177
+ if (!await waitForChildExit(child, graceMs)) {
178
+ throw new Error("host_process_supervisor_termination_failed: supervised Windows root did not stop.");
179
+ }
181
180
  }
182
181
  const providerPid = metadata?.providerPid ?? 0;
183
182
  const providerIdentity = metadata?.providerIdentity ?? null;
@@ -188,6 +187,12 @@ export async function terminateHostProcessTree(child, launch, graceMs = 2_000) {
188
187
  if (exactProcessExists(providerPid, providerIdentity, "win32")) {
189
188
  throw new Error("host_process_supervisor_termination_failed: supervised Windows provider tree did not stop.");
190
189
  }
190
+ // The root and the provider have exited; the rest of the tree (a descendant that left
191
+ // the provider's process tree, say) is gone only with the Job Object, which outlives
192
+ // its members by no more than a moment unless something still holds it.
193
+ if (!await windowsJobGone(launch.supervisorId, graceMs)) {
194
+ throw new Error(`host_process_supervisor_termination_failed: the Job Object of supervisor ${launch.supervisorId} still holds processes after its root and provider stopped.`);
195
+ }
191
196
  return;
192
197
  }
193
198
  const processGroupId = child.pid;
@@ -218,10 +223,13 @@ async function terminateUnsupervisedProcessTree(child, graceMs) {
218
223
  // root has already exited. Never target a potentially reused Windows PID.
219
224
  if (child.exitCode !== null || child.signalCode !== null)
220
225
  return;
221
- const rootIdentity = captureHostProcessIdentity(rootPid, "win32");
226
+ // Until this child reports its exit, Node still holds its process handle, so
227
+ // its PID cannot name another process. Stop the tree now, rather than after a
228
+ // PowerShell launch to read its identity, during which the provider runs on
229
+ // past the stop (a success ceiling, a cancellation), and observe the exit
230
+ // through that same handle.
222
231
  forceWindowsProcessTree(rootPid);
223
- await waitForExactProcessExit(rootPid, rootIdentity, graceMs, "win32");
224
- if (exactProcessExists(rootPid, rootIdentity, "win32")) {
232
+ if (!await waitForChildExit(child, graceMs)) {
225
233
  throw new Error("host_process_supervisor_termination_failed: unsupervised Windows provider tree did not stop.");
226
234
  }
227
235
  return;
@@ -250,6 +258,34 @@ function assertMetadataPath(logDirectory, metadataPath) {
250
258
  throw new Error("host_process_supervisor_invalid: metadata path must be inside FORGE_LOG_DIR.");
251
259
  }
252
260
  }
261
+ /**
262
+ * Polls for the job supervisor's named Job Object (runtime/windows-job-supervisor.ps1 names
263
+ * it Local\Forge-<supervisorId>). A job object exists while any handle or member process
264
+ * holds it, and the supervisor's handle closed with it, so its absence means no member is
265
+ * left. Any answer but "not found" (an unreadable job, a failed check) is not proof.
266
+ */
267
+ export const waitForWindowsSupervisorJobGone = async (supervisorId, timeoutMs) => {
268
+ if (!/^[A-Za-z0-9._-]{1,200}$/u.test(supervisorId))
269
+ return false;
270
+ const script = [
271
+ "$ErrorActionPreference = 'Stop'",
272
+ "Add-Type -Namespace ForgeRecovery -Name Job -MemberDefinition '[DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr OpenJobObject(uint access, bool inherit, string name); [DllImport(\"kernel32.dll\")] public static extern bool CloseHandle(IntPtr handle);'",
273
+ `$deadline = [DateTime]::UtcNow.AddMilliseconds(${Math.max(0, Math.round(timeoutMs))})`,
274
+ "$result = 'alive'",
275
+ // JOB_OBJECT_QUERY (4); ERROR_FILE_NOT_FOUND (2) is the only answer that proves the job gone.
276
+ "while ($true) { "
277
+ + `$handle = [ForgeRecovery.Job]::OpenJobObject(4, $false, 'Local\\Forge-${supervisorId}'); `
278
+ + "if ($handle -eq [IntPtr]::Zero) { $code = [Runtime.InteropServices.Marshal]::GetLastWin32Error(); "
279
+ + "if ($code -eq 2) { $result = 'gone' } else { $result = \"error:$code\" }; break }; "
280
+ + "[ForgeRecovery.Job]::CloseHandle($handle) | Out-Null; "
281
+ + "if ([DateTime]::UtcNow -ge $deadline) { break }; Start-Sleep -Milliseconds 25 }",
282
+ "Write-Output $result",
283
+ ].join("; ");
284
+ const { stdout } = await execFileAsync(windowsPowerShellPath(), [
285
+ "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script,
286
+ ], { encoding: "utf8", windowsHide: true, timeout: timeoutMs + 60_000 }).catch(() => ({ stdout: "" }));
287
+ return stdout.trim() === "gone";
288
+ };
253
289
  export function windowsPowerShellPath() {
254
290
  const systemRoot = process.env.SystemRoot?.trim() || "C:\\Windows";
255
291
  const candidate = path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
@@ -307,6 +343,22 @@ function processExists(pid) {
307
343
  return error.code === "EPERM";
308
344
  }
309
345
  }
346
+ /** Whether this process's own child reports its exit within `timeoutMs`. */
347
+ async function waitForChildExit(child, timeoutMs) {
348
+ if (child.exitCode !== null || child.signalCode !== null)
349
+ return true;
350
+ return await new Promise(resolve => {
351
+ const onExit = () => {
352
+ clearTimeout(timer);
353
+ resolve(true);
354
+ };
355
+ const timer = setTimeout(() => {
356
+ child.off("exit", onExit);
357
+ resolve(child.exitCode !== null || child.signalCode !== null);
358
+ }, timeoutMs);
359
+ child.once("exit", onExit);
360
+ });
361
+ }
310
362
  async function waitForExactProcessExit(pid, identity, timeoutMs, platform) {
311
363
  const deadline = monotonicNowMs() + timeoutMs;
312
364
  while (monotonicNowMs() < deadline && exactProcessExists(pid, identity, platform)) {
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
3
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
4
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
5
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
6
+ */
7
+ export declare const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS: readonly ["pwsh", "node", "dotnet"];
8
+ export interface AppExecutionAliasFinding {
9
+ readonly tool: string;
10
+ /** The alias the tool's bare name resolves to. */
11
+ readonly aliasPath: string;
12
+ /** The first regular install later on PATH, or null when the alias is the only one. */
13
+ readonly nextInstallPath: string | null;
14
+ }
15
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
16
+ export declare function findAppExecutionAliasTools(pathValue: string, pathExtValue?: string, tools?: readonly string[]): AppExecutionAliasFinding[];
17
+ export declare function describeAppExecutionAliasFindings(findings: readonly AppExecutionAliasFinding[]): string | null;
18
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
19
+ export declare function appExecutionAliasWarning(env: Readonly<Record<string, string | undefined>>, platform?: NodeJS.Platform): string | null;
@@ -0,0 +1,45 @@
1
+ import { isWindowsAppExecutionAliasPath, resolveWindowsCommandFromPath } from "./windows-launch.js";
2
+ /**
3
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
4
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
5
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
6
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
7
+ */
8
+ export const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS = ["pwsh", "node", "dotnet"];
9
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
10
+ export function findAppExecutionAliasTools(pathValue, pathExtValue, tools = APP_EXECUTION_ALIAS_SENSITIVE_TOOLS) {
11
+ const findings = [];
12
+ for (const tool of tools) {
13
+ const aliasPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue);
14
+ if (!aliasPath || !isWindowsAppExecutionAliasPath(aliasPath))
15
+ continue;
16
+ const nextInstallPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue, { skipAppExecutionAliases: true });
17
+ findings.push({ tool, aliasPath, nextInstallPath });
18
+ }
19
+ return findings;
20
+ }
21
+ export function describeAppExecutionAliasFindings(findings) {
22
+ if (findings.length === 0)
23
+ return null;
24
+ const tools = findings.map(finding => `${finding.tool} -> ${finding.aliasPath}${finding.nextInstallPath
25
+ ? ` (a regular install later on PATH: ${finding.nextInstallPath})`
26
+ : " (no regular install on PATH)"}`);
27
+ return "Host readiness warning: on the provider PATH, "
28
+ + `${tools.join("; ")} resolve${findings.length === 1 ? "s" : ""} to a Microsoft Store app-execution alias under WindowsApps. `
29
+ + "A process started through an alias is created outside the provider's Windows Job Object, survives it, "
30
+ + "and can hold the attempt's output pipes open until it exits. Install the tool normally "
31
+ + "(for PowerShell, the MSI under C:\\Program Files\\PowerShell\\7) and put it ahead of WindowsApps on PATH.";
32
+ }
33
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
34
+ export function appExecutionAliasWarning(env, platform = process.platform) {
35
+ if (platform !== "win32")
36
+ return null;
37
+ const pathValue = environmentValue(env, "PATH");
38
+ if (!pathValue)
39
+ return null;
40
+ return describeAppExecutionAliasFindings(findAppExecutionAliasTools(pathValue, environmentValue(env, "PATHEXT")));
41
+ }
42
+ function environmentValue(env, name) {
43
+ const key = Object.keys(env).find(candidate => candidate.toUpperCase() === name);
44
+ return key === undefined ? undefined : env[key];
45
+ }
@@ -6,3 +6,21 @@ export declare function buildWindowsCmdLaunch(command: string, args: readonly st
6
6
  export declare function buildWindowsLaunchCommand(commandPath: string, args: readonly string[]): LaunchCommand;
7
7
  export declare function windowsCommandLine(command: string, args: readonly string[]): string;
8
8
  export declare function quoteWindowsCommandLineArg(value: string): string;
9
+ export interface WindowsCommandPathOptions {
10
+ /**
11
+ * Skip candidates under a `WindowsApps` directory. Those are Microsoft Store app-execution
12
+ * aliases: the process they start is created outside the caller's Job Object, so it survives the
13
+ * job and keeps any inherited pipe open. Resolve the next real install on PATH instead.
14
+ */
15
+ readonly skipAppExecutionAliases?: boolean;
16
+ }
17
+ /**
18
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
19
+ * happen while the machine is under enough process pressure for where.exe to
20
+ * miss its timeout; returning the unresolved package-manager name in that case
21
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
22
+ */
23
+ export declare function resolveWindowsCommandFromPath(command: string, pathValue?: string, pathExtValue?: string, options?: WindowsCommandPathOptions): string | null;
24
+ export declare function chooseWindowsCommandCandidate(candidates: readonly string[]): string | null;
25
+ /** True for a path inside a `WindowsApps` directory, where Store app-execution aliases live. */
26
+ export declare function isWindowsAppExecutionAliasPath(candidate: string): boolean;
@@ -1,3 +1,4 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  export function buildWindowsCmdLaunch(command, args, comSpec = process.env.ComSpec) {
3
4
  const resolvedComSpec = comSpec?.trim();
@@ -39,3 +40,70 @@ function powershellExecutable() {
39
40
  ? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
40
41
  : "powershell.exe";
41
42
  }
43
+ /**
44
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
45
+ * happen while the machine is under enough process pressure for where.exe to
46
+ * miss its timeout; returning the unresolved package-manager name in that case
47
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
48
+ */
49
+ export function resolveWindowsCommandFromPath(command, pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD", options = {}) {
50
+ if (!command || path.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
51
+ return null;
52
+ }
53
+ const hasExtension = path.extname(command).length > 0;
54
+ const extensions = hasExtension
55
+ ? [""]
56
+ : [...new Set([
57
+ "",
58
+ ".exe",
59
+ ".ps1",
60
+ ".cmd",
61
+ ".bat",
62
+ ...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
63
+ ])];
64
+ for (const rawDirectory of pathValue.split(path.delimiter)) {
65
+ const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
66
+ if (!directory)
67
+ continue;
68
+ const candidates = [];
69
+ for (const extension of extensions) {
70
+ const candidate = path.join(directory, `${command}${extension}`);
71
+ if (options.skipAppExecutionAliases && isWindowsAppExecutionAliasPath(candidate))
72
+ continue;
73
+ if (pathEntryExists(candidate))
74
+ candidates.push(candidate);
75
+ }
76
+ const resolved = chooseWindowsCommandCandidate(candidates);
77
+ if (resolved)
78
+ return resolved;
79
+ }
80
+ return null;
81
+ }
82
+ export function chooseWindowsCommandCandidate(candidates) {
83
+ const normalized = candidates
84
+ .map((candidate) => candidate.trim())
85
+ .filter((candidate) => candidate.length > 0);
86
+ if (normalized.length === 0) {
87
+ return null;
88
+ }
89
+ const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
90
+ for (const extension of preferredExtensions) {
91
+ const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
92
+ if (candidate) {
93
+ return candidate;
94
+ }
95
+ }
96
+ return normalized[0];
97
+ }
98
+ /** True for a path inside a `WindowsApps` directory, where Store app-execution aliases live. */
99
+ export function isWindowsAppExecutionAliasPath(candidate) {
100
+ return candidate.split(/[\\/]+/u).some(segment => segment.toLowerCase() === "windowsapps");
101
+ }
102
+ // An app-execution alias is a reparse point that stat() may not open, so an
103
+ // alias is also accepted when only lstat() can see it.
104
+ function pathEntryExists(candidate) {
105
+ if (fs.existsSync(candidate))
106
+ return true;
107
+ return isWindowsAppExecutionAliasPath(candidate)
108
+ && fs.lstatSync(candidate, { throwIfNoEntry: false }) !== undefined;
109
+ }