@loucompanion/forge-bridge 0.1.4-dev.138b79c6feb3 → 0.1.4-dev.176dfdaf5020

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 (207) 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 +87 -14
  16. package/dist/bridge/bridge.service.js +393 -337
  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 +104 -26
  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 +32 -4
  83. package/dist/runtime/host-runtime-lease.js +109 -173
  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/runner-settings.d.ts +104 -0
  92. package/dist/runtime/runner-settings.js +236 -0
  93. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  94. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  95. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  96. package/dist/sandbox/host-capacity-broker.js +27 -6
  97. package/dist/sandbox/managed-branch.d.ts +13 -0
  98. package/dist/sandbox/managed-branch.js +90 -0
  99. package/dist/sandbox/provider-auth/codex.js +11 -11
  100. package/dist/sandbox/runtime.js +2 -6
  101. package/dist/session/architect-waits.d.ts +2 -0
  102. package/dist/session/architect-waits.js +138 -0
  103. package/dist/session/managed-attempt-tools.d.ts +0 -7
  104. package/dist/session/managed-attempt-tools.js +58 -91
  105. package/dist/session/managed-build-coordinator.d.ts +16 -0
  106. package/dist/session/managed-build-coordinator.js +10 -0
  107. package/dist/session/managed-build-receipt.d.ts +5 -0
  108. package/dist/session/managed-build-receipt.js +8 -3
  109. package/dist/session/managed-command-host-load.d.ts +2 -0
  110. package/dist/session/managed-command-host-load.js +2 -1
  111. package/dist/session/phase-completion.artifacts.js +2 -1
  112. package/dist/session/phase-completion.d.ts +8 -0
  113. package/dist/session/phase-completion.js +1 -0
  114. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  115. package/dist/session/phase-completion.mcp-args.js +156 -0
  116. package/dist/session/phase-completion.runtime.d.ts +0 -8
  117. package/dist/session/phase-completion.runtime.js +43 -197
  118. package/dist/session/phase-completion.schemas.js +25 -23
  119. package/dist/session/phase-completion.validation.js +3 -1
  120. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  121. package/dist/session/pre-publication-native-postgres.js +111 -0
  122. package/dist/session/pre-publication-pass.d.ts +61 -0
  123. package/dist/session/pre-publication-pass.js +148 -0
  124. package/dist/session/pre-publication-process.js +10 -10
  125. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  126. package/dist/session/pre-publication-step-execution.js +6 -5
  127. package/dist/session/pre-publication-validation.d.ts +30 -14
  128. package/dist/session/pre-publication-validation.js +207 -134
  129. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  130. package/dist/session/provider-cli/claude-background-work.js +181 -0
  131. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  132. package/dist/session/provider-cli/host-build-lock.js +30 -0
  133. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  134. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  135. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  136. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  137. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  138. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  139. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  140. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  141. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  142. package/dist/session/provider-cli/provider-cli.prompts.js +68 -31
  143. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  144. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  145. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
  146. package/dist/session/provider-cli/provider-cli.service.js +70 -263
  147. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  148. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  149. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  150. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  151. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  152. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  153. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  154. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  155. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  156. package/dist/session/provider-cli/provider-output-state.js +6 -0
  157. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  158. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  159. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  160. package/dist/session/qa-sidecar-validation.js +28 -0
  161. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  162. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  163. package/dist/session/session-redaction.js +31 -181
  164. package/dist/session/session.base.d.ts +6 -1
  165. package/dist/session/session.service.d.ts +6 -1
  166. package/dist/session/session.service.js +75 -64
  167. package/dist/session/session.types.js +3 -3
  168. package/dist/session/sidecar-json-shape.d.ts +31 -0
  169. package/dist/session/sidecar-json-shape.js +217 -0
  170. package/dist/shared/fs/file-identity.d.ts +10 -0
  171. package/dist/shared/fs/file-identity.js +15 -0
  172. package/dist/shared/fs/replace-file.d.ts +7 -0
  173. package/dist/shared/fs/replace-file.js +33 -0
  174. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  175. package/dist/shared/process/host-process-recovery.js +23 -3
  176. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  177. package/dist/shared/process/host-process-supervisor.js +66 -14
  178. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  179. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  180. package/dist/shared/process/windows-launch.d.ts +18 -0
  181. package/dist/shared/process/windows-launch.js +68 -0
  182. package/dist/shared/provider-capabilities.js +14 -7
  183. package/dist/version.d.ts +1 -1
  184. package/dist/version.js +1 -1
  185. package/dist/worktree/orphan-relink.d.ts +19 -0
  186. package/dist/worktree/orphan-relink.js +106 -0
  187. package/dist/worktree/wip-git.d.ts +33 -0
  188. package/dist/worktree/wip-git.js +122 -0
  189. package/dist/worktree/wip-refs.d.ts +62 -0
  190. package/dist/worktree/wip-refs.js +119 -0
  191. package/dist/worktree/wip-restore.d.ts +38 -0
  192. package/dist/worktree/wip-restore.js +190 -0
  193. package/dist/worktree/wip-snapshot.d.ts +50 -0
  194. package/dist/worktree/wip-snapshot.js +268 -0
  195. package/dist/worktree/worktree-inputs.d.ts +8 -0
  196. package/dist/worktree/worktree-inputs.js +134 -0
  197. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  198. package/dist/worktree/worktree-origin-sync.js +127 -0
  199. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  200. package/dist/worktree/worktree-wip-events.js +98 -0
  201. package/dist/worktree/worktree-wip.d.ts +50 -0
  202. package/dist/worktree/worktree-wip.js +185 -0
  203. package/dist/worktree/worktree.base.d.ts +7 -1
  204. package/dist/worktree/worktree.service.d.ts +27 -5
  205. package/dist/worktree/worktree.service.js +110 -181
  206. package/dist/worktree/worktree.types.d.ts +31 -0
  207. package/package.json +2 -2
@@ -0,0 +1,402 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, readlinkSync, realpathSync } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ /**
6
+ * Where a supervised ASP.NET runtime builds and runs from, relative to each project in its
7
+ * graph. Agent builds keep the default `bin/<Configuration>/<TargetFramework>/` output, so they
8
+ * never overwrite (or, on Windows, fail on the locks of) the files a running runtime executes.
9
+ */
10
+ export const supervisedRuntimeOutputRoot = "bin/forge-runtime";
11
+ // More links than this on one path is a loop (Linux gives up at 40 too).
12
+ const maxPathLinks = 40;
13
+ /**
14
+ * Where a path really is, existing or not yet: its deepest existing ancestor resolved through every
15
+ * symlink and junction, with the rest appended. A lexical path alone lets a link alias another directory.
16
+ * A link whose target does not exist yet still leads to that target, so it is followed by its
17
+ * link text, never taken as its own location; a link loop fails with `path_link_unresolvable`.
18
+ */
19
+ export async function canonicalExistingPath(target) {
20
+ return await canonicalPathThroughLinks(target, 0);
21
+ }
22
+ async function canonicalPathThroughLinks(target, links) {
23
+ const resolved = path.resolve(target);
24
+ const real = await fs.realpath(resolved).catch(() => null);
25
+ if (real !== null)
26
+ return real;
27
+ if ((await fs.lstat(resolved).catch(() => null))?.isSymbolicLink()) {
28
+ const linkTarget = path.resolve(path.dirname(resolved), await fs.readlink(resolved));
29
+ return await canonicalPathThroughLinks(linkTarget, countedLink(resolved, links));
30
+ }
31
+ const parent = path.dirname(resolved);
32
+ return parent === resolved ? resolved : path.join(await canonicalPathThroughLinks(parent, links), path.basename(resolved));
33
+ }
34
+ /** canonicalExistingPath, for synchronous planning. */
35
+ export function canonicalExistingPathSync(target) {
36
+ return canonicalPathThroughLinksSync(target, 0);
37
+ }
38
+ function canonicalPathThroughLinksSync(target, links) {
39
+ const resolved = path.resolve(target);
40
+ const real = attempt(() => realpathSync.native(resolved));
41
+ if (real !== null)
42
+ return real;
43
+ if (attempt(() => lstatSync(resolved))?.isSymbolicLink()) {
44
+ const linkTarget = path.resolve(path.dirname(resolved), readlinkSync(resolved));
45
+ return canonicalPathThroughLinksSync(linkTarget, countedLink(resolved, links));
46
+ }
47
+ const parent = path.dirname(resolved);
48
+ return parent === resolved ? resolved : path.join(canonicalPathThroughLinksSync(parent, links), path.basename(resolved));
49
+ }
50
+ function attempt(read) {
51
+ try {
52
+ return read();
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ function countedLink(link, links) {
59
+ if (links >= maxPathLinks) {
60
+ throw new Error(`path_link_unresolvable: ${link} leads through more than ${maxPathLinks} links, so Forge cannot tell where it points.`);
61
+ }
62
+ return links + 1;
63
+ }
64
+ export const fileSystemProjectFiles = {
65
+ read: async (file) => await fs.readFile(file, "utf8").catch(() => null),
66
+ list: async (directory) => await fs.readdir(directory).catch(() => null),
67
+ canonical: canonicalExistingPath,
68
+ };
69
+ // Verbs that write (or, for clean, delete) a project's build output.
70
+ const outputWritingVerbs = new Set(["build", "test", "publish", "pack", "run", "msbuild", "clean"]);
71
+ const releaseByDefaultVerbs = new Set(["publish", "pack"]);
72
+ const optionsWithValues = new Set([
73
+ "-c", "--configuration", "-f", "--framework", "-r", "--runtime", "-o", "--output", "-a", "--arch", "--os",
74
+ "-v", "--verbosity", "-s", "--source", "--artifacts-path", "--project", "--solution", "-e", "--environment",
75
+ "-lp", "--launch-profile", "-l", "--logger", "--filter", "--settings", "--results-directory", "--collect",
76
+ "-d", "--diag", "--test-adapter-path", "--version-suffix", "--blame-hang-timeout", "--blame-crash-dump-type",
77
+ "--blame-hang-dump-type", "--max-parallel-test-modules", "--report-trx-filename",
78
+ ]);
79
+ const projectFilePattern = /\.(?:cs|fs|vb)proj$/iu;
80
+ const solutionFilePattern = /\.slnx?$/iu;
81
+ function pathApi(platform) {
82
+ return platform === "win32" ? path.win32 : path.posix;
83
+ }
84
+ export function hostPathPlatform() {
85
+ return process.platform === "win32" ? "win32" : "posix";
86
+ }
87
+ export function isDotnetExecutable(command, platform = hostPathPlatform()) {
88
+ const executable = pathApi(platform).basename(command).toLowerCase();
89
+ return executable === "dotnet" || executable === "dotnet.exe";
90
+ }
91
+ /**
92
+ * Reads a dotnet command's build-output intent: its verb, target candidates, and output
93
+ * settings. Returns null when the command writes no build output. With `holder`, the command is
94
+ * a running runtime's `dotnet run`: `--no-build` does not matter, it executes from the output.
95
+ */
96
+ export function parseDotnetOutputCommand(command, args, cwd, options = {}) {
97
+ const platform = options.platform ?? hostPathPlatform();
98
+ if (!isDotnetExecutable(command, platform))
99
+ return null;
100
+ const separator = args.indexOf("--");
101
+ const commandArgs = separator < 0 ? args : args.slice(0, separator);
102
+ const verbIndex = commandArgs.findIndex(argument => !argument.startsWith("-"));
103
+ const verb = commandArgs[verbIndex]?.toLowerCase() ?? "";
104
+ if (options.holder ? verb !== "run" : !outputWritingVerbs.has(verb))
105
+ return null;
106
+ const parsed = parseArguments(commandArgs.slice(verbIndex + 1));
107
+ if (!options.holder && verb !== "build" && verb !== "msbuild" && verb !== "clean" && parsed.flags.has("--no-build"))
108
+ return null;
109
+ if (verb === "msbuild" && parsed.msbuildTargets.length > 0
110
+ && parsed.msbuildTargets.every(target => target.toLowerCase() === "restore"))
111
+ return null;
112
+ const p = pathApi(platform);
113
+ const resolvedCwd = p.resolve(cwd);
114
+ const explicitTargets = ["--project", "--solution"].flatMap(name => parsed.values.get(name) ?? []);
115
+ // `dotnet run` hands positional arguments to the application; other verbs take them as targets.
116
+ const candidates = verb === "run" ? explicitTargets : [...explicitTargets, ...parsed.positionals];
117
+ return {
118
+ verb,
119
+ cwd: resolvedCwd,
120
+ targets: candidates.map(candidate => p.resolve(resolvedCwd, normalizeSeparators(candidate, platform))),
121
+ settings: outputSettings(verb, parsed, resolvedCwd, platform),
122
+ };
123
+ }
124
+ function parseArguments(args) {
125
+ const parsed = { flags: new Set(), values: new Map(), properties: new Map(), msbuildTargets: [], positionals: [] };
126
+ for (let index = 0; index < args.length; index += 1) {
127
+ const argument = args[index];
128
+ if (readMsbuildSwitch(argument, parsed))
129
+ continue;
130
+ if (!argument.startsWith("-")) {
131
+ parsed.positionals.push(argument);
132
+ continue;
133
+ }
134
+ const inline = /^(--?[A-Za-z][\w-]*)[=:](.*)$/u.exec(argument);
135
+ const name = (inline?.[1] ?? argument).toLowerCase();
136
+ if (inline && optionsWithValues.has(name))
137
+ parsed.values.set(name, inline[2]);
138
+ else if (optionsWithValues.has(name) && index + 1 < args.length)
139
+ parsed.values.set(name, args[++index]);
140
+ else
141
+ parsed.flags.add(name);
142
+ }
143
+ return parsed;
144
+ }
145
+ /** `-p:`/`-property:` assignments and `-t:`/`-target:` lists, in any of MSBuild's prefix spellings. */
146
+ function readMsbuildSwitch(argument, parsed) {
147
+ const property = /^(?:-{1,2}|\/)(?:p|property):(.+)$/iu.exec(argument);
148
+ if (property) {
149
+ for (const assignment of property[1].split(/[;,]/u)) {
150
+ const equals = assignment.indexOf("=");
151
+ if (equals > 0)
152
+ parsed.properties.set(assignment.slice(0, equals).trim().toLowerCase(), assignment.slice(equals + 1).trim());
153
+ }
154
+ return true;
155
+ }
156
+ const target = /^(?:-{1,2}|\/)(?:t|target):(.+)$/iu.exec(argument);
157
+ if (target) {
158
+ parsed.msbuildTargets.push(...target[1].split(/[;,]/u).map(value => value.trim()).filter(Boolean));
159
+ return true;
160
+ }
161
+ return false;
162
+ }
163
+ function outputSettings(verb, parsed, cwd, platform) {
164
+ const p = pathApi(platform);
165
+ const property = (name) => parsed.properties.get(name.toLowerCase()) || null;
166
+ const perProject = (value) => value ? { path: normalizeSeparators(value, platform), perProject: true } : null;
167
+ const fromCwd = (value) => value ? { path: p.resolve(cwd, normalizeSeparators(value, platform)), perProject: false } : null;
168
+ const os = parsed.values.get("--os");
169
+ const arch = parsed.values.get("-a") ?? parsed.values.get("--arch");
170
+ return {
171
+ configuration: parsed.values.get("-c") ?? parsed.values.get("--configuration") ?? property("Configuration")
172
+ ?? (releaseByDefaultVerbs.has(verb) ? "Release" : "Debug"),
173
+ framework: parsed.values.get("-f") ?? parsed.values.get("--framework") ?? property("TargetFramework"),
174
+ runtime: parsed.values.get("-r") ?? parsed.values.get("--runtime") ?? property("RuntimeIdentifier")
175
+ ?? (os || arch ? `${os ?? "*"}-${arch ?? "*"}` : null),
176
+ outDir: perProject(property("OutDir") ?? property("OutputPath")),
177
+ output: fromCwd(parsed.values.get("-o") ?? parsed.values.get("--output")),
178
+ baseOutputPath: perProject(property("BaseOutputPath")),
179
+ artifactsPath: fromCwd(parsed.values.get("--artifacts-path")) ?? perProject(property("ArtifactsPath")),
180
+ };
181
+ }
182
+ function normalizeSeparators(value, platform) {
183
+ return platform === "win32" ? value : value.replaceAll("\\", "/");
184
+ }
185
+ /** True when the arguments already choose where the build output goes. */
186
+ export function declaresDotnetOutput(settings) {
187
+ return Boolean(settings.outDir ?? settings.output ?? settings.baseOutputPath ?? settings.artifactsPath);
188
+ }
189
+ /** True when a project file multi-targets (`<TargetFrameworks>`, even with one entry). */
190
+ export function isMultiTargetedProject(projectXml) {
191
+ return /<TargetFrameworks>\s*[^<\s]/u.test(projectXml.replaceAll(/<!--[\s\S]*?-->/gu, ""));
192
+ }
193
+ /**
194
+ * The directory a project's primary output lands in under these settings. An unknown target
195
+ * framework is the wildcard `*`, which matches any framework in sameOutputDirectory.
196
+ */
197
+ export function projectOutputDirectory(projectFile, settings, platform = hostPathPlatform(), layout = {}) {
198
+ const p = pathApi(platform);
199
+ const projectDirectory = p.dirname(projectFile);
200
+ const at = (location) => location.perProject ? p.resolve(projectDirectory, location.path) : location.path;
201
+ // OutDir wins over the OutputPath that `-o` sets; a global OutputPath is used as given.
202
+ const explicit = settings.outDir ?? settings.output;
203
+ if (explicit)
204
+ return p.resolve(at(explicit));
205
+ if (settings.artifactsPath) {
206
+ // The SDK's ArtifactsPivots: the configuration, the framework only when the project
207
+ // multi-targets, then an explicit RID, lowercased and joined by `_`.
208
+ const pivot = [
209
+ settings.configuration,
210
+ ...(layout.multiTargeted ? [settings.framework ?? "*"] : []),
211
+ ...(settings.runtime ? [settings.runtime] : []),
212
+ ].join("_").toLowerCase();
213
+ return p.join(artifactsProjectRoot(projectFile, at(settings.artifactsPath), platform), pivot);
214
+ }
215
+ const base = settings.baseOutputPath ? at(settings.baseOutputPath) : p.join(projectDirectory, "bin");
216
+ return p.join(base, settings.configuration, settings.framework ?? "*", ...(settings.runtime ? [settings.runtime] : []));
217
+ }
218
+ function artifactsProjectRoot(projectFile, artifactsPath, platform) {
219
+ const p = pathApi(platform);
220
+ return p.join(artifactsPath, "bin", p.basename(projectFile).replace(projectFilePattern, ""));
221
+ }
222
+ /**
223
+ * The one directory holding every build output of a project under these settings, whatever
224
+ * configuration or framework they leave open: what a runtime's build receipt verifies. Without
225
+ * the project file's name, an artifacts layout's root is its `bin`, above every project's folder.
226
+ */
227
+ export function projectOutputRoot(projectDirectory, projectFile, settings, platform = hostPathPlatform()) {
228
+ const p = pathApi(platform);
229
+ const at = (location) => p.resolve(location.perProject ? p.resolve(projectDirectory, location.path) : location.path);
230
+ const explicit = settings.outDir ?? settings.output;
231
+ if (explicit)
232
+ return at(explicit);
233
+ if (settings.artifactsPath) {
234
+ const artifactsPath = at(settings.artifactsPath);
235
+ return projectFile ? artifactsProjectRoot(projectFile, artifactsPath, platform) : p.join(artifactsPath, "bin");
236
+ }
237
+ return settings.baseOutputPath ? at(settings.baseOutputPath) : p.join(projectDirectory, "bin");
238
+ }
239
+ /**
240
+ * Compares two output directories segment by segment. `*` matches any run of characters inside
241
+ * one segment: `*` is any framework folder, and `debug_*` any framework pivot.
242
+ */
243
+ export function sameOutputDirectory(left, right, platform = hostPathPlatform()) {
244
+ const segments = (value) => {
245
+ const resolved = pathApi(platform).resolve(value);
246
+ return (platform === "win32" ? resolved.toLowerCase() : resolved).split(/[\\/]+/u).filter(Boolean);
247
+ };
248
+ const a = segments(left);
249
+ const b = segments(right);
250
+ return a.length === b.length && a.every((segment, index) => sameSegment(segment, b[index]));
251
+ }
252
+ function sameSegment(left, right) {
253
+ if (left === right)
254
+ return true;
255
+ const leftOpen = left.includes("*");
256
+ const rightOpen = right.includes("*");
257
+ // `*` never crosses `_`, so two open pivots meet only with the same parts, each pair able to name one value.
258
+ if (leftOpen && rightOpen) {
259
+ const leftParts = left.split("_");
260
+ const rightParts = right.split("_");
261
+ return leftParts.length === rightParts.length && leftParts.every((part, index) => samePivotPart(part, rightParts[index]));
262
+ }
263
+ if (leftOpen)
264
+ return matchesWildcard(left, right);
265
+ return rightOpen && matchesWildcard(right, left);
266
+ }
267
+ /** One `_`-free pivot part: both open ones share a value when their literal start and end agree. */
268
+ function samePivotPart(left, right) {
269
+ if (left === right)
270
+ return true;
271
+ if (!left.includes("*"))
272
+ return matchesWildcard(right, left);
273
+ if (!right.includes("*"))
274
+ return matchesWildcard(left, right);
275
+ const [leftStart, rightStart] = [left.slice(0, left.indexOf("*")), right.slice(0, right.indexOf("*"))];
276
+ const [leftEnd, rightEnd] = [left.slice(left.lastIndexOf("*") + 1), right.slice(right.lastIndexOf("*") + 1)];
277
+ return (leftStart.startsWith(rightStart) || rightStart.startsWith(leftStart))
278
+ && (leftEnd.endsWith(rightEnd) || rightEnd.endsWith(leftEnd));
279
+ }
280
+ /** `*` stands for one framework or RID value, which never contains the pivot separator `_`. */
281
+ function matchesWildcard(pattern, value) {
282
+ const expression = pattern.split("*").map(part => part.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&")).join("[^_]*");
283
+ return new RegExp(`^${expression}$`, "u").test(value);
284
+ }
285
+ /** ProjectReference Include values of a project file, ignoring commented-out references. */
286
+ export function projectReferenceIncludes(projectXml) {
287
+ const withoutComments = projectXml.replaceAll(/<!--[\s\S]*?-->/gu, "");
288
+ const includes = [];
289
+ for (const match of withoutComments.matchAll(/<ProjectReference\b[^>]*?\bInclude\s*=\s*(?:"([^"]*)"|'([^']*)')/giu)) {
290
+ for (const part of (match[1] ?? match[2] ?? "").split(";")) {
291
+ const trimmed = part.trim();
292
+ if (trimmed)
293
+ includes.push(trimmed);
294
+ }
295
+ }
296
+ return includes;
297
+ }
298
+ /** Project paths a .sln or .slnx lists. */
299
+ export function solutionProjectPaths(solution, content) {
300
+ const pattern = /\.slnx$/iu.test(solution)
301
+ ? /<Project\b[^>]*?\bPath\s*=\s*"([^"]+)"/giu
302
+ : /^Project\("\{[^}]*\}"\)\s*=\s*"[^"]*"\s*,\s*"([^"]+)"/gmu;
303
+ return [...content.matchAll(pattern)].map(match => match[1].trim()).filter(entry => projectFilePattern.test(entry));
304
+ }
305
+ /** Every project file a command builds: its targets, solution members, and their ProjectReference closure. */
306
+ export async function dotnetCommandProjects(command, files = fileSystemProjectFiles, platform = hostPathPlatform()) {
307
+ const p = pathApi(platform);
308
+ const queue = [...await targetProjectFiles(command, files, platform)];
309
+ const visited = new Map();
310
+ while (queue.length > 0) {
311
+ const projectFile = queue.shift();
312
+ const key = platform === "win32" ? projectFile.toLowerCase() : projectFile;
313
+ if (visited.has(key))
314
+ continue;
315
+ const content = await files.read(projectFile);
316
+ if (content === null)
317
+ continue;
318
+ visited.set(key, projectFile);
319
+ for (const include of projectReferenceIncludes(content)) {
320
+ // An MSBuild property cannot be resolved here.
321
+ if (!include.includes("$("))
322
+ queue.push(p.resolve(p.dirname(projectFile), normalizeSeparators(include, platform)));
323
+ }
324
+ }
325
+ return [...visited.values()];
326
+ }
327
+ async function targetProjectFiles(command, files, platform) {
328
+ const fromCandidates = async (candidates) => {
329
+ const found = [];
330
+ for (const candidate of candidates) {
331
+ if (projectFilePattern.test(candidate) || solutionFilePattern.test(candidate))
332
+ found.push(candidate);
333
+ else
334
+ found.push(...((await files.list(candidate)) ?? [])
335
+ .filter(entry => projectFilePattern.test(entry) || solutionFilePattern.test(entry))
336
+ .map(entry => pathApi(platform).join(candidate, entry)));
337
+ }
338
+ return found;
339
+ };
340
+ // A positional value that is no target (an unlisted option's value) leaves the working directory as the target.
341
+ const explicit = await fromCandidates(command.targets);
342
+ const targets = explicit.length > 0 ? explicit : await fromCandidates([command.cwd]);
343
+ const projects = [];
344
+ for (const target of targets) {
345
+ if (!solutionFilePattern.test(target)) {
346
+ projects.push(target);
347
+ continue;
348
+ }
349
+ const content = await files.read(target);
350
+ const p = pathApi(platform);
351
+ for (const entry of content ? solutionProjectPaths(target, content) : []) {
352
+ projects.push(p.resolve(p.dirname(target), normalizeSeparators(entry, platform)));
353
+ }
354
+ }
355
+ return projects;
356
+ }
357
+ /**
358
+ * The projects whose output a build (`writer`) would write while a runtime (`holder`) executes
359
+ * from that same output, in the runtime's graph order (its own project first).
360
+ */
361
+ export async function findDotnetOutputCollisions(writer, holder, files = fileSystemProjectFiles, platform = hostPathPlatform()) {
362
+ const key = (value) => platform === "win32" ? value.toLowerCase() : value;
363
+ // Projects and outputs compare by real location: a link to the worktree or to an output is the same place.
364
+ const real = files.canonical ?? (async (value) => value);
365
+ const written = new Set(await Promise.all((await dotnetCommandProjects(writer, files, platform))
366
+ .map(async (project) => key(await real(project)))));
367
+ const collisions = [];
368
+ for (const project of await dotnetCommandProjects(holder, files, platform)) {
369
+ const realProject = await real(project);
370
+ if (!written.has(key(realProject)))
371
+ continue;
372
+ const layout = { multiTargeted: isMultiTargetedProject((await files.read(project)) ?? "") };
373
+ const held = await real(projectOutputDirectory(project, holder.settings, platform, layout));
374
+ if (sameOutputDirectory(await real(projectOutputDirectory(project, writer.settings, platform, layout)), held, platform)) {
375
+ collisions.push({ project: realProject, outputDirectory: held });
376
+ }
377
+ }
378
+ return collisions;
379
+ }
380
+ /** A runtime role as a directory name: kept when it is already safe, otherwise a stable digest. */
381
+ export function runtimeOutputName(role) {
382
+ return /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/u.test(role)
383
+ ? role
384
+ : createHash("sha256").update(role).digest("hex").slice(0, 16);
385
+ }
386
+ /**
387
+ * Gives a supervised `dotnet run` its own build output, `bin/forge-runtime/<role>/` under each
388
+ * project, unless the configured arguments already choose one. The ASP.NET prebuild forwards the
389
+ * same property to its `dotnet build`, so the runtime builds and runs from that directory.
390
+ */
391
+ export function isolatedRuntimeOutputArguments(command, args, role, platform = hostPathPlatform()) {
392
+ const runtime = parseDotnetOutputCommand(command, args, ".", { platform, holder: true });
393
+ if (!runtime || declaresDotnetOutput(runtime.settings))
394
+ return args;
395
+ const separator = args.indexOf("--");
396
+ const insertionIndex = separator < 0 ? args.length : separator;
397
+ return [
398
+ ...args.slice(0, insertionIndex),
399
+ `-p:OutDir=${supervisedRuntimeOutputRoot}/${runtimeOutputName(role)}/`,
400
+ ...args.slice(insertionIndex),
401
+ ];
402
+ }
@@ -0,0 +1,37 @@
1
+ import { type EphemeralTestPostgresCluster, type EphemeralTestPostgresOptions } from "./ephemeral-test-postgres.js";
2
+ import { type NativeTestPostgresFallback, type NativeTestPostgresGrant } from "./native-test-postgres-fallback.js";
3
+ export type StartEphemeralTestPostgres = (options: EphemeralTestPostgresOptions) => Promise<EphemeralTestPostgresCluster>;
4
+ /** The bin directory an ephemeral cluster runs from: the file's `postgresBin`, else the one holding psql. */
5
+ export declare function ephemeralTestPostgresBinDirectory(fallback: Pick<NativeTestPostgresFallback, "postgresBin">, psqlPath?: () => string | null): string;
6
+ /**
7
+ * Starts a throwaway cluster for one check and returns its grant. The grant's mode keeps the
8
+ * Docker semantics of the shared cluster: with Docker up, pinned-engine tests still start their
9
+ * own containers; with Docker down, they are skipped. The caller must call `release`.
10
+ */
11
+ export declare function startEphemeralTestPostgresGrant(fallback: Pick<NativeTestPostgresFallback, "postgresBin">, dockerAvailable: boolean, start?: StartEphemeralTestPostgres): Promise<NativeTestPostgresGrant>;
12
+ /** A managed verification command's database environment, and what to release when the command ends. */
13
+ export interface ManagedVerificationDatabase {
14
+ readonly environment: Readonly<Record<string, string>>;
15
+ /** The connection strings and their passwords, for redaction; never the mode or the cluster id. */
16
+ readonly secrets: readonly string[];
17
+ readonly release: () => Promise<void>;
18
+ }
19
+ /** A command that runs no verification profile gets no database. */
20
+ export declare const noManagedVerificationDatabase: ManagedVerificationDatabase;
21
+ /**
22
+ * Builds a command's setup from its database. If the setup throws, the command never starts and
23
+ * no caller holds the database, so it is released here before the error is rethrown.
24
+ */
25
+ export declare function setUpWithManagedVerificationDatabase<T>(database: Pick<ManagedVerificationDatabase, "release">, setUp: () => T): Promise<T>;
26
+ /**
27
+ * Releases a command's database once the command has ended. A cluster that would not stop is left
28
+ * disowned for the next start's reap; the failure goes to `report` instead of being dropped.
29
+ */
30
+ export declare function releaseManagedVerificationDatabase(database: Pick<ManagedVerificationDatabase, "release">, report: (message: string) => Promise<void>): Promise<void>;
31
+ /**
32
+ * Managed verification on an `ephemeral` host gets a throwaway cluster for the command's
33
+ * lifetime; every other host keeps managedVerificationDatabaseEnvironment's rules. A cluster
34
+ * that cannot start fails the command rather than silently handing it Docker or the shared
35
+ * cluster's narrower login.
36
+ */
37
+ export declare function managedVerificationDatabase(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null, start?: StartEphemeralTestPostgres): Promise<ManagedVerificationDatabase>;
@@ -0,0 +1,85 @@
1
+ import path from "node:path";
2
+ import { attemptDatabaseCapabilitySecrets, resolvePsqlPath } from "./attempt-database-broker.js";
3
+ import { EphemeralTestPostgresError, ephemeralTestPostgresClusterEnvironment, startEphemeralTestPostgres, } from "./ephemeral-test-postgres.js";
4
+ import { DockerEngineProbe } from "./docker-engine-probe.js";
5
+ import { managedVerificationDatabaseEnvironment, nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, nativeTestPostgresPreferredDatabaseMode, readNativeTestPostgresFallback, } from "./native-test-postgres-fallback.js";
6
+ /** The bin directory an ephemeral cluster runs from: the file's `postgresBin`, else the one holding psql. */
7
+ export function ephemeralTestPostgresBinDirectory(fallback, psqlPath = resolvePsqlPath) {
8
+ if (fallback.postgresBin)
9
+ return fallback.postgresBin;
10
+ const psql = psqlPath();
11
+ if (!psql) {
12
+ throw new EphemeralTestPostgresError("no PostgreSQL install was found; set 'postgresBin' in native-test-postgres.json or FORGE_NATIVE_TEST_POSTGRES_PSQL.");
13
+ }
14
+ return path.dirname(psql);
15
+ }
16
+ /**
17
+ * Starts a throwaway cluster for one check and returns its grant. The grant's mode keeps the
18
+ * Docker semantics of the shared cluster: with Docker up, pinned-engine tests still start their
19
+ * own containers; with Docker down, they are skipped. The caller must call `release`.
20
+ */
21
+ export async function startEphemeralTestPostgresGrant(fallback, dockerAvailable, start = startEphemeralTestPostgres) {
22
+ const cluster = await start({ binDirectory: ephemeralTestPostgresBinDirectory(fallback) });
23
+ return {
24
+ connectionString: cluster.connectionString,
25
+ endpoint: cluster.endpoint,
26
+ mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
27
+ ephemeralClusterId: cluster.id,
28
+ release: cluster.release,
29
+ };
30
+ }
31
+ /** A command that runs no verification profile gets no database. */
32
+ export const noManagedVerificationDatabase = {
33
+ environment: {},
34
+ secrets: [],
35
+ release: async () => undefined,
36
+ };
37
+ /**
38
+ * Builds a command's setup from its database. If the setup throws, the command never starts and
39
+ * no caller holds the database, so it is released here before the error is rethrown.
40
+ */
41
+ export async function setUpWithManagedVerificationDatabase(database, setUp) {
42
+ try {
43
+ return setUp();
44
+ }
45
+ catch (error) {
46
+ await database.release().catch(() => undefined);
47
+ throw error;
48
+ }
49
+ }
50
+ /**
51
+ * Releases a command's database once the command has ended. A cluster that would not stop is left
52
+ * disowned for the next start's reap; the failure goes to `report` instead of being dropped.
53
+ */
54
+ export async function releaseManagedVerificationDatabase(database, report) {
55
+ try {
56
+ await database.release();
57
+ }
58
+ catch (error) {
59
+ await report(error instanceof Error ? error.message : String(error)).catch(() => undefined);
60
+ }
61
+ }
62
+ function databaseSecrets(environment) {
63
+ return Object.entries(environment)
64
+ .filter(([name]) => name !== "FORGE_MANAGED_VERIFICATION_DATABASE_MODE" && name !== ephemeralTestPostgresClusterEnvironment)
65
+ .flatMap(([, value]) => attemptDatabaseCapabilitySecrets(value));
66
+ }
67
+ /**
68
+ * Managed verification on an `ephemeral` host gets a throwaway cluster for the command's
69
+ * lifetime; every other host keeps managedVerificationDatabaseEnvironment's rules. A cluster
70
+ * that cannot start fails the command rather than silently handing it Docker or the shared
71
+ * cluster's narrower login.
72
+ */
73
+ export async function managedVerificationDatabase(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
74
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
75
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
76
+ }, start = startEphemeralTestPostgres) {
77
+ const fallback = readFallback();
78
+ if (fallback?.use !== "ephemeral") {
79
+ const environment = await managedVerificationDatabaseEnvironment(dockerAvailable, () => fallback);
80
+ return { environment, secrets: databaseSecrets(environment), release: async () => undefined };
81
+ }
82
+ const grant = await startEphemeralTestPostgresGrant(fallback, await dockerAvailable(), start);
83
+ const environment = nativeTestPostgresFallbackEnvironment(grant);
84
+ return { environment, secrets: databaseSecrets(environment), release: grant.release ?? (async () => undefined) };
85
+ }
@@ -0,0 +1,57 @@
1
+ /** Set for a test run on an ephemeral cluster: its id, which the server reports as `forge.ephemeral_cluster`. */
2
+ export declare const ephemeralTestPostgresClusterEnvironment = "FORGE_TEST_POSTGRES_EPHEMERAL_CLUSTER";
3
+ export declare const ephemeralTestPostgresMarkerSetting = "forge.ephemeral_cluster";
4
+ export declare class EphemeralTestPostgresError extends Error {
5
+ readonly code = "ephemeral_test_postgres_unavailable";
6
+ constructor(detail: string);
7
+ }
8
+ export interface EphemeralTestPostgresCluster {
9
+ readonly id: string;
10
+ readonly connectionString: string;
11
+ readonly endpoint: string;
12
+ readonly password: string;
13
+ /**
14
+ * Stops the server and deletes its directory. Safe to call more than once. Rejects, keeping the
15
+ * directory, when the server is still running after the stop.
16
+ */
17
+ release(): Promise<void>;
18
+ }
19
+ export interface ToolResult {
20
+ readonly code: number | null;
21
+ readonly output: string;
22
+ }
23
+ /** Runs one PostgreSQL program. `detached` programs (pg_ctl start) leave a server running, so their output goes to its log. */
24
+ export type EphemeralToolRunner = (file: string, args: readonly string[], options: {
25
+ readonly env: Readonly<Record<string, string>>;
26
+ readonly timeoutMs: number;
27
+ readonly detached?: boolean;
28
+ }) => Promise<ToolResult>;
29
+ export interface EphemeralTestPostgresOptions {
30
+ /** The directory holding initdb, pg_ctl and psql of the PostgreSQL install to run. */
31
+ readonly binDirectory: string;
32
+ readonly root?: string;
33
+ readonly ownerPid?: number;
34
+ readonly runTool?: EphemeralToolRunner;
35
+ readonly isProcessAlive?: (pid: number) => boolean;
36
+ readonly freePort?: () => Promise<number>;
37
+ readonly now?: () => number;
38
+ }
39
+ export declare function defaultEphemeralTestPostgresRoot(): string;
40
+ /**
41
+ * A superuser of a cluster run by the `postgres` OS user can read every cluster that user runs,
42
+ * including live ones (Debian and Ubuntu packages run them all as `postgres`). An ephemeral
43
+ * cluster therefore runs only as an ordinary user, the same one that already runs the attempt.
44
+ */
45
+ export declare function assertEphemeralClusterOsUser(userName?: string, uid?: number | undefined): void;
46
+ /** Creates, starts and prepares one cluster. On any failure nothing of it is left behind. */
47
+ export declare function startEphemeralTestPostgres(options: EphemeralTestPostgresOptions): Promise<EphemeralTestPostgresCluster>;
48
+ /**
49
+ * Removes clusters whose owning Bridge process is gone. Only directories named like a cluster
50
+ * id inside the root are considered, and a live owner's clusters are never touched.
51
+ */
52
+ export declare function reapEphemeralTestPostgres(options: EphemeralTestPostgresOptions): Promise<readonly string[]>;
53
+ /**
54
+ * On Windows a started postgres inherits pg_ctl's standard handles, so a pipe would stay open for
55
+ * the server's lifetime; a detached program gets no pipes and settles when it exits.
56
+ */
57
+ export declare const runPostgresTool: EphemeralToolRunner;