@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.894bcbd53d64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) 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 +394 -338
  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 +20 -1
  31. package/dist/cleanup/cleanup.service.js +150 -169
  32. package/dist/cleanup/cleanup.types.d.ts +6 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  36. package/dist/cleanup/host-runtime-ledger.js +130 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +149 -186
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  52. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  53. package/dist/runtime/attempt-process-supervisor.js +12 -6
  54. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  55. package/dist/runtime/docker-engine-probe.js +7 -0
  56. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  57. package/dist/runtime/dotnet-build-outputs.js +402 -0
  58. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  59. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  60. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  61. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  62. package/dist/runtime/host-facts.d.ts +2 -1
  63. package/dist/runtime/host-load-admission.d.ts +18 -3
  64. package/dist/runtime/host-load-admission.js +19 -4
  65. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  66. package/dist/runtime/host-load-child-environment.js +22 -11
  67. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  68. package/dist/runtime/host-load-governor-config.js +37 -0
  69. package/dist/runtime/host-load-governor.d.ts +14 -0
  70. package/dist/runtime/host-load-governor.js +139 -26
  71. package/dist/runtime/host-load-ledger-lock.js +6 -4
  72. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  73. package/dist/runtime/host-load-runtime-settings.js +80 -0
  74. package/dist/runtime/host-load-sampler.d.ts +34 -4
  75. package/dist/runtime/host-load-sampler.js +73 -7
  76. package/dist/runtime/host-load-step-class.d.ts +3 -1
  77. package/dist/runtime/host-load-step-class.js +60 -5
  78. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  79. package/dist/runtime/host-load-test-slot.js +81 -0
  80. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  81. package/dist/runtime/host-load-token-ledger.js +93 -61
  82. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  83. package/dist/runtime/host-load-windows-cpu.js +85 -0
  84. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  85. package/dist/runtime/host-runtime-contract.js +29 -1
  86. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  87. package/dist/runtime/host-runtime-lease.js +212 -61
  88. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  89. package/dist/runtime/host-runtime-promotion.js +36 -0
  90. package/dist/runtime/managed-command-teardown.js +5 -16
  91. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  92. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  93. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  94. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  95. package/dist/runtime/runner-settings.d.ts +104 -0
  96. package/dist/runtime/runner-settings.js +236 -0
  97. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  98. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  99. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  100. package/dist/sandbox/host-capacity-broker.js +27 -6
  101. package/dist/sandbox/managed-branch.d.ts +13 -0
  102. package/dist/sandbox/managed-branch.js +90 -0
  103. package/dist/sandbox/provider-auth/codex.js +11 -11
  104. package/dist/sandbox/runtime.js +2 -6
  105. package/dist/session/architect-waits.d.ts +2 -0
  106. package/dist/session/architect-waits.js +138 -0
  107. package/dist/session/managed-attempt-tools.d.ts +2 -7
  108. package/dist/session/managed-attempt-tools.js +94 -104
  109. package/dist/session/managed-build-coordinator.d.ts +16 -0
  110. package/dist/session/managed-build-coordinator.js +10 -0
  111. package/dist/session/managed-build-receipt.d.ts +5 -0
  112. package/dist/session/managed-build-receipt.js +8 -3
  113. package/dist/session/managed-command-host-load.d.ts +2 -0
  114. package/dist/session/managed-command-host-load.js +2 -1
  115. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  116. package/dist/session/mcp-argument-coercion.js +121 -0
  117. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  118. package/dist/session/phase-completion.artifacts.js +96 -26
  119. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  120. package/dist/session/phase-completion.command-validation.js +77 -0
  121. package/dist/session/phase-completion.d.ts +10 -0
  122. package/dist/session/phase-completion.helpers.js +13 -12
  123. package/dist/session/phase-completion.js +5 -0
  124. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  125. package/dist/session/phase-completion.mcp-args.js +156 -0
  126. package/dist/session/phase-completion.prompts.js +6 -1
  127. package/dist/session/phase-completion.runtime.d.ts +4 -10
  128. package/dist/session/phase-completion.runtime.js +77 -209
  129. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  130. package/dist/session/phase-completion.schema-parts.js +188 -0
  131. package/dist/session/phase-completion.schemas.d.ts +3 -3
  132. package/dist/session/phase-completion.schemas.js +208 -231
  133. package/dist/session/phase-completion.validation.d.ts +2 -3
  134. package/dist/session/phase-completion.validation.js +49 -93
  135. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  136. package/dist/session/pre-publication-native-postgres.js +111 -0
  137. package/dist/session/pre-publication-pass.d.ts +61 -0
  138. package/dist/session/pre-publication-pass.js +148 -0
  139. package/dist/session/pre-publication-process.js +10 -10
  140. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  141. package/dist/session/pre-publication-step-execution.js +6 -5
  142. package/dist/session/pre-publication-validation.d.ts +30 -14
  143. package/dist/session/pre-publication-validation.js +207 -134
  144. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  145. package/dist/session/provider-cli/claude-background-work.js +181 -0
  146. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  147. package/dist/session/provider-cli/host-build-lock.js +30 -0
  148. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  149. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  150. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  151. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  152. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  153. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  154. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  155. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  156. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  157. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  158. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  159. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  160. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  161. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  162. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  163. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  164. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  165. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  166. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  167. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  168. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  169. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  170. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  171. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  172. package/dist/session/provider-cli/provider-output-state.js +6 -0
  173. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  174. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  175. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  176. package/dist/session/qa-sidecar-validation.js +28 -0
  177. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  178. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  179. package/dist/session/session-redaction.js +31 -181
  180. package/dist/session/session.base.d.ts +6 -1
  181. package/dist/session/session.service.d.ts +9 -2
  182. package/dist/session/session.service.js +169 -66
  183. package/dist/session/session.types.js +4 -4
  184. package/dist/session/sidecar-json-shape.d.ts +31 -0
  185. package/dist/session/sidecar-json-shape.js +217 -0
  186. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  187. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  188. package/dist/shared/fs/file-identity.d.ts +10 -0
  189. package/dist/shared/fs/file-identity.js +15 -0
  190. package/dist/shared/fs/replace-file.d.ts +7 -0
  191. package/dist/shared/fs/replace-file.js +33 -0
  192. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  193. package/dist/shared/process/host-process-recovery.js +23 -3
  194. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  195. package/dist/shared/process/host-process-supervisor.js +66 -14
  196. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  197. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  198. package/dist/shared/process/windows-launch.d.ts +18 -0
  199. package/dist/shared/process/windows-launch.js +68 -0
  200. package/dist/shared/provider-capabilities.js +14 -7
  201. package/dist/version.d.ts +1 -1
  202. package/dist/version.js +1 -1
  203. package/dist/worktree/orphan-relink.d.ts +19 -0
  204. package/dist/worktree/orphan-relink.js +106 -0
  205. package/dist/worktree/wip-git.d.ts +33 -0
  206. package/dist/worktree/wip-git.js +122 -0
  207. package/dist/worktree/wip-refs.d.ts +62 -0
  208. package/dist/worktree/wip-refs.js +119 -0
  209. package/dist/worktree/wip-restore.d.ts +38 -0
  210. package/dist/worktree/wip-restore.js +190 -0
  211. package/dist/worktree/wip-snapshot.d.ts +50 -0
  212. package/dist/worktree/wip-snapshot.js +268 -0
  213. package/dist/worktree/worktree-inputs.d.ts +8 -0
  214. package/dist/worktree/worktree-inputs.js +134 -0
  215. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  216. package/dist/worktree/worktree-origin-sync.js +127 -0
  217. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  218. package/dist/worktree/worktree-wip-events.js +98 -0
  219. package/dist/worktree/worktree-wip.d.ts +50 -0
  220. package/dist/worktree/worktree-wip.js +185 -0
  221. package/dist/worktree/worktree.base.d.ts +7 -1
  222. package/dist/worktree/worktree.service.d.ts +31 -5
  223. package/dist/worktree/worktree.service.js +120 -163
  224. package/dist/worktree/worktree.types.d.ts +31 -0
  225. package/package.json +2 -2
@@ -1,12 +1,37 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { resolveLocalConfigPath } from "../cli/local-config.js";
4
+ import { DockerEngineProbe } from "./docker-engine-probe.js";
5
+ import { ephemeralTestPostgresClusterEnvironment } from "./ephemeral-test-postgres.js";
4
6
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "./host-runtime-contract.js";
5
7
  export const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE_TEST_POSTGRES_CONFIG";
6
8
  export const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
7
9
  export const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
10
+ /**
11
+ * The cluster serves the shared test server while Docker is up, so tests that need a
12
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
13
+ * first, which keeps test databases out of the Docker VM and saves RAM.
14
+ */
15
+ export const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
16
+ const nativeTestPostgresUses = ["preferred", "docker_unavailable", "ephemeral"];
8
17
  const defaultPostgresPort = 5432;
9
18
  const loopbackHosts = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
19
+ /**
20
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
21
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
22
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
23
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
24
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
25
+ */
26
+ export function nativeTestPostgresGrant(fallback, dockerAvailable) {
27
+ if (!fallback || (dockerAvailable && fallback.use !== "preferred"))
28
+ return null;
29
+ return {
30
+ connectionString: fallback.connectionString,
31
+ endpoint: fallback.endpoint,
32
+ mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
33
+ };
34
+ }
10
35
  export class NativeTestPostgresFallbackError extends Error {
11
36
  code = "native_test_postgres_fallback_invalid";
12
37
  constructor(detail) {
@@ -46,9 +71,17 @@ export function readNativeTestPostgresFallback(configPath = resolveNativeTestPos
46
71
  if (document.schemaVersion !== 1 || typeof document.connectionString !== "string") {
47
72
  throw new NativeTestPostgresFallbackError(`${configPath} must contain schemaVersion 1 and a connectionString.`);
48
73
  }
49
- return parseNativeTestPostgresFallback(document.connectionString);
74
+ if (document.use !== undefined && !nativeTestPostgresUses.includes(document.use)) {
75
+ throw new NativeTestPostgresFallbackError(`${configPath} 'use' must be 'preferred', 'docker_unavailable' or 'ephemeral'.`);
76
+ }
77
+ if (document.postgresBin !== undefined
78
+ && (typeof document.postgresBin !== "string" || !path.isAbsolute(document.postgresBin))) {
79
+ throw new NativeTestPostgresFallbackError(`${configPath} 'postgresBin' must be an absolute path.`);
80
+ }
81
+ const fallback = parseNativeTestPostgresFallback(document.connectionString, document.use ?? "preferred");
82
+ return typeof document.postgresBin === "string" ? { ...fallback, postgresBin: document.postgresBin } : fallback;
50
83
  }
51
- export function parseNativeTestPostgresFallback(connectionString) {
84
+ export function parseNativeTestPostgresFallback(connectionString, use = "preferred") {
52
85
  const fields = new Map();
53
86
  for (const segment of connectionString.split(";")) {
54
87
  const separator = segment.indexOf("=");
@@ -79,13 +112,32 @@ export function parseNativeTestPostgresFallback(connectionString) {
79
112
  if (!(fields.get("username") ?? fields.get("userid") ?? fields.get("user"))) {
80
113
  throw new NativeTestPostgresFallbackError("the fallback must name a dedicated test role.");
81
114
  }
82
- return { connectionString: connectionString.trim(), endpoint: `${host}:${port}` };
115
+ return { connectionString: connectionString.trim(), endpoint: `${host}:${port}`, use };
83
116
  }
84
- /** Environment for one runner-authored .NET test process using the fallback. */
85
- export function nativeTestPostgresFallbackEnvironment(fallback) {
117
+ /** Environment for one runner-authored .NET test process using the cluster. */
118
+ export function nativeTestPostgresFallbackEnvironment(grant) {
86
119
  return {
87
- [hostRuntimeTestPostgresAdminEnvironment]: fallback.connectionString,
88
- [hostRuntimeLegacyTestPostgresEnvironment]: fallback.connectionString,
89
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: nativeTestPostgresFallbackDatabaseMode,
120
+ [hostRuntimeTestPostgresAdminEnvironment]: grant.connectionString,
121
+ [hostRuntimeLegacyTestPostgresEnvironment]: grant.connectionString,
122
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: grant.mode,
123
+ // The fixtures accept a superuser login only on the cluster that reports this id.
124
+ ...(grant.ephemeralClusterId ? { [ephemeralTestPostgresClusterEnvironment]: grant.ephemeralClusterId } : {}),
90
125
  };
91
126
  }
127
+ /**
128
+ * Runner-authored verification uses the operator-provisioned native test cluster,
129
+ * which holds no real data, whenever its file prefers it (the default); Docker then
130
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
131
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
132
+ * database serves.
133
+ */
134
+ export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
135
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
136
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
137
+ }) {
138
+ const fallback = readFallback();
139
+ if (!fallback)
140
+ return {};
141
+ const grant = nativeTestPostgresGrant(fallback, await dockerAvailable());
142
+ return grant ? nativeTestPostgresFallbackEnvironment(grant) : {};
143
+ }
@@ -28,5 +28,12 @@ export declare class PlaywrightHostRuntimeAdapter {
28
28
  */
29
29
  assertBrowserCacheReady(config: HostRuntimePlaywrightConfig, worktreePath: string): Promise<void>;
30
30
  private readyBrowserCache;
31
+ /**
32
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
33
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
34
+ * provider that remembers the config's path would otherwise run Playwright against that port.
35
+ * The next `prepare` writes a fresh one.
36
+ */
37
+ discardOverlay(temporaryDirectory: string): Promise<void>;
31
38
  prepare(config: HostRuntimePlaywrightConfig, context: PlaywrightHostRuntimeContext): Promise<PreparedPlaywrightHostRuntime>;
32
39
  }
@@ -35,6 +35,17 @@ export class PlaywrightHostRuntimeAdapter {
35
35
  }
36
36
  return { cache: resolution.cache, installCommand };
37
37
  }
38
+ /**
39
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
40
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
41
+ * provider that remembers the config's path would otherwise run Playwright against that port.
42
+ * The next `prepare` writes a fresh one.
43
+ */
44
+ async discardOverlay(temporaryDirectory) {
45
+ if (!await assertCanonicalDirectory(temporaryDirectory, true))
46
+ return;
47
+ await fs.rm(path.join(path.resolve(temporaryDirectory), playwrightOverlayFileName), { force: true });
48
+ }
38
49
  async prepare(config, context) {
39
50
  const { realWorktree, realSource } = await projectConfigLocation(config, context.worktreePath);
40
51
  const sourceConfig = path.resolve(path.resolve(context.worktreePath), config.config);
@@ -62,7 +73,7 @@ export class PlaywrightHostRuntimeAdapter {
62
73
  if (!/^[0-9a-f]{32}$/u.test(context.ownershipToken)) {
63
74
  throw new Error("playwright_runtime_adapter_invalid: ownership token must be a normalized dispatch attempt UUID.");
64
75
  }
65
- const overlayPath = path.join(temporaryDirectory, "forge.playwright.config.mjs");
76
+ const overlayPath = path.join(temporaryDirectory, playwrightOverlayFileName);
66
77
  const { cache: readyCache, installCommand: browserInstallCommand } = await this.readyBrowserCache(context.worktreePath, realWorktree, path.dirname(realSource));
67
78
  const browserCache = readyCache
68
79
  ? { path: readyCache, ready: true }
@@ -135,6 +146,7 @@ async function ensureAttemptWritableDirectories(targets, realWorktree) {
135
146
  for (const target of resolvedTargets)
136
147
  await createPrivateCanonicalDirectory(target);
137
148
  }
149
+ const playwrightOverlayFileName = "forge.playwright.config.mjs";
138
150
  async function writeAttemptOverlay(target, content) {
139
151
  const parent = path.dirname(target);
140
152
  const identity = await assertCanonicalDirectory(parent);
@@ -0,0 +1,104 @@
1
+ import { type HostLoadGovernorMode } from "./host-load-governor-config.js";
2
+ export declare const runnerSettingKeys: readonly ["maxConcurrentAttempts", "cpuBudgetPercent", "yieldCpuBudgetPercent", "memoryReserveBytes", "maxHeavySteps", "yieldToForeground"];
3
+ export type RunnerSettingKey = typeof runnerSettingKeys[number];
4
+ /** The `ApplySettings` hub message. Null numeric fields mean "no server value": keep today's env/default behaviour. */
5
+ export interface RunnerSettingsDocument {
6
+ readonly runnerId: string | null;
7
+ readonly version: number;
8
+ readonly maxConcurrentAttempts: number | null;
9
+ readonly cpuBudgetPercent: number | null;
10
+ readonly yieldCpuBudgetPercent: number | null;
11
+ readonly memoryReserveBytes: number | null;
12
+ readonly maxHeavySteps: number | null;
13
+ readonly yieldToForeground: boolean;
14
+ }
15
+ export interface RunnerSettingsValues {
16
+ readonly maxConcurrentAttempts: number;
17
+ readonly cpuBudgetPercent: number;
18
+ readonly yieldCpuBudgetPercent: number;
19
+ readonly memoryReserveBytes: number;
20
+ /** Null: the governor's budget alone limits heavy steps (no count limit). */
21
+ readonly maxHeavySteps: number | null;
22
+ readonly yieldToForeground: boolean;
23
+ }
24
+ /**
25
+ * Where an effective value came from: the server's value as is, the bridge default,
26
+ * an env var that capped/floored the server value or supplied it, or the host's
27
+ * `forge-bridge yield on` flag.
28
+ */
29
+ export type RunnerSettingSource = "server" | "default" | "host_env" | "host_local";
30
+ export interface RunnerSettingBound {
31
+ readonly key: RunnerSettingKey;
32
+ readonly envVar: string;
33
+ readonly value: number;
34
+ readonly kind: "ceiling" | "floor";
35
+ }
36
+ /**
37
+ * Why a key was rejected. `invalid`: the server value is outside the contract, so
38
+ * the host default applies (version skew; it never holds placement). `apply_failed`:
39
+ * the host could not put the value in force, so the previous value stays in force
40
+ * and the server holds placement until a later apply succeeds. Clamping by an env
41
+ * bound is neither: it is a `bound` and a `host_env` source.
42
+ */
43
+ export type RunnerSettingRejectionKind = "invalid" | "apply_failed";
44
+ export interface RunnerSettingRejection {
45
+ readonly key: RunnerSettingKey;
46
+ readonly reason: string;
47
+ readonly kind: RunnerSettingRejectionKind;
48
+ }
49
+ /** The `SettingsApplied` report; also carried in the capabilities `settings` block (schema 8). */
50
+ export interface RunnerSettingsReport {
51
+ /** The applied document version, or null before any ApplySettings was applied. */
52
+ readonly version: number | null;
53
+ /** FORGE_HOST_LOAD_GOVERNOR: CPU budget, yield budget and heavy steps only take effect when on. */
54
+ readonly governor: HostLoadGovernorMode;
55
+ readonly values: RunnerSettingsValues;
56
+ readonly sources: Readonly<Record<RunnerSettingKey, RunnerSettingSource>>;
57
+ readonly bounds: readonly RunnerSettingBound[];
58
+ readonly rejected: readonly RunnerSettingRejection[];
59
+ }
60
+ /** Today's bridge defaults for the keys whose default depends on the host. */
61
+ export interface RunnerHostDefaults {
62
+ /** floor(threads / 2) capped at 8 (at least 1). */
63
+ readonly maxConcurrentAttempts: number;
64
+ /** The adaptive reserve: 12.5% of RAM within 1–4 GiB, before FORGE_HOST_MEMORY_RESERVE_BYTES. */
65
+ readonly memoryReserveBytes: number;
66
+ }
67
+ export interface EffectiveRunnerSettings {
68
+ readonly report: RunnerSettingsReport;
69
+ /** Effective yield (server OR local flag). */
70
+ readonly yielding: boolean;
71
+ /**
72
+ * The governor CPU budget in force, as a fraction of logical CPUs: the CPU budget,
73
+ * or min(yield budget, CPU budget) while yielding.
74
+ */
75
+ readonly governorCpuBudgetFraction: number;
76
+ }
77
+ export declare const defaultCpuBudgetPercent = 80;
78
+ export declare const defaultYieldCpuBudgetPercent = 50;
79
+ /**
80
+ * Computes every effective value (decision 0014 precedence):
81
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
82
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
83
+ * - yield: server OR the local `forge-bridge yield on` flag.
84
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
85
+ */
86
+ export declare function computeEffectiveRunnerSettings(document: RunnerSettingsDocument | null, environment: Readonly<Record<string, string | undefined>>, hostDefaults: RunnerHostDefaults, localYield: boolean): EffectiveRunnerSettings;
87
+ /**
88
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
89
+ * (the bridge then ignores it); malformed values become null so the host default applies.
90
+ */
91
+ export declare function parseRunnerSettingsDocument(raw: unknown): RunnerSettingsDocument | null;
92
+ /**
93
+ * The report for what is actually in force after an apply in which the host
94
+ * failed to put some keys in force: each failed key keeps the value (and source)
95
+ * that was in force before, and its failure is reported as an `apply_failed`
96
+ * rejection, so the server never reads a desired value as applied.
97
+ */
98
+ export declare function runnerSettingsInForce(report: RunnerSettingsReport, previous: RunnerSettingsReport, failures: readonly RunnerSettingRejection[]): RunnerSettingsReport;
99
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
100
+ export declare function sameRunnerSettingsReport(left: RunnerSettingsReport, right: RunnerSettingsReport): boolean;
101
+ /** The offer refusal message while the runner yields to foreground work. */
102
+ export declare function runnerYieldingMessage(report: RunnerSettingsReport): string;
103
+ /** One line describing the effective settings, for the bridge log. */
104
+ export declare function describeRunnerSettings(report: RunnerSettingsReport): string;
@@ -0,0 +1,236 @@
1
+ import { formatBytes } from "../shared/format/format-bytes.js";
2
+ import { parseHostLoadGovernorMode } from "./host-load-governor-config.js";
3
+ // Decision 0014 §3 "Precedence" and §6 "Bridge hub": the server pushes a runner
4
+ // settings document (`ApplySettings`) and is the source of truth. Host env vars
5
+ // are one-sided safety bounds only: a ceiling on capacity, a floor on reserves.
6
+ // The bridge reports the effective values, their sources and every env bound it
7
+ // saw back to the server (`SettingsApplied`), so a host bound is never silent.
8
+ // Nothing here is persisted to bridge.json (0014 agent constraint).
9
+ export const runnerSettingKeys = [
10
+ "maxConcurrentAttempts",
11
+ "cpuBudgetPercent",
12
+ "yieldCpuBudgetPercent",
13
+ "memoryReserveBytes",
14
+ "maxHeavySteps",
15
+ "yieldToForeground",
16
+ ];
17
+ export const defaultCpuBudgetPercent = 80;
18
+ export const defaultYieldCpuBudgetPercent = 50;
19
+ const MiB = 1024 ** 2;
20
+ const GiB = 1024 ** 3;
21
+ /** The server's ranges (contract); a value outside them is rejected, not clamped, so it is never silent. */
22
+ const serverRanges = {
23
+ maxConcurrentAttempts: { min: 1, max: 32 },
24
+ cpuBudgetPercent: { min: 10, max: 100 },
25
+ yieldCpuBudgetPercent: { min: 10, max: 100 },
26
+ memoryReserveBytes: { min: 512 * MiB, max: 128 * GiB },
27
+ maxHeavySteps: { min: 1, max: 64 },
28
+ };
29
+ /**
30
+ * Computes every effective value (decision 0014 precedence):
31
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
32
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
33
+ * - yield: server OR the local `forge-bridge yield on` flag.
34
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
35
+ */
36
+ export function computeEffectiveRunnerSettings(document, environment, hostDefaults, localYield) {
37
+ const rejected = [];
38
+ const server = (key) => {
39
+ const value = document?.[key] ?? null;
40
+ if (value === null)
41
+ return null;
42
+ const range = serverRanges[key];
43
+ if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
44
+ rejected.push({ key, reason: `${String(value)} is not a whole number; the host default applies.`, kind: "invalid" });
45
+ return null;
46
+ }
47
+ if (value < range.min || value > range.max) {
48
+ rejected.push({ key, reason: `${value} is outside ${range.min}-${range.max}; the host default applies.`, kind: "invalid" });
49
+ return null;
50
+ }
51
+ return value;
52
+ };
53
+ const attemptsCeiling = integerEnv(environment, "FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", 1, 32);
54
+ const cpuCeilings = cpuBudgetCeilings(environment);
55
+ const reserveFloor = integerEnv(environment, "FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * MiB, 128 * GiB);
56
+ const heavyStepsCeiling = integerEnv(environment, "FORGE_HOST_MAX_HEAVY_STEPS", 1, 64);
57
+ const attempts = ceilingValue(server("maxConcurrentAttempts"), lowest(attemptsCeiling), hostDefaults.maxConcurrentAttempts);
58
+ const cpu = ceilingValue(server("cpuBudgetPercent"), lowest(...cpuCeilings), defaultCpuBudgetPercent);
59
+ // The yield budget's ceilings are the CPU budget's. Without a server value they
60
+ // cap its default rather than replace it: a host allowing 90% CPU must not raise
61
+ // the 50% yield default, which no env var sets today.
62
+ const serverYieldCpu = server("yieldCpuBudgetPercent");
63
+ const yieldCpu = ceilingValue(serverYieldCpu ?? defaultYieldCpuBudgetPercent, lowest(...cpuCeilings), defaultYieldCpuBudgetPercent);
64
+ const yieldCpuSource = serverYieldCpu === null && yieldCpu.source === "server" ? "default" : yieldCpu.source;
65
+ const reserve = floorValue(server("memoryReserveBytes"), reserveFloor?.value ?? null, hostDefaults.memoryReserveBytes);
66
+ const heavySteps = ceilingValue(server("maxHeavySteps"), lowest(heavyStepsCeiling), null);
67
+ const serverYield = document?.yieldToForeground === true;
68
+ const yielding = serverYield || localYield;
69
+ // The host's own switch wins the label: turning the server toggle off would not stop it.
70
+ const yieldSource = localYield ? "host_local" : serverYield ? "server" : "default";
71
+ const bounds = [];
72
+ const addCeilings = (key, set) => {
73
+ for (const bound of set)
74
+ if (bound)
75
+ bounds.push({ key, envVar: bound.envVar, value: bound.value, kind: "ceiling" });
76
+ };
77
+ addCeilings("maxConcurrentAttempts", [attemptsCeiling]);
78
+ addCeilings("cpuBudgetPercent", cpuCeilings);
79
+ addCeilings("yieldCpuBudgetPercent", cpuCeilings);
80
+ if (reserveFloor)
81
+ bounds.push({ key: "memoryReserveBytes", envVar: reserveFloor.envVar, value: reserveFloor.value, kind: "floor" });
82
+ addCeilings("maxHeavySteps", [heavyStepsCeiling]);
83
+ const values = {
84
+ maxConcurrentAttempts: attempts.value,
85
+ cpuBudgetPercent: cpu.value,
86
+ yieldCpuBudgetPercent: yieldCpu.value,
87
+ memoryReserveBytes: reserve.value,
88
+ maxHeavySteps: heavySteps.value,
89
+ yieldToForeground: yielding,
90
+ };
91
+ const budgetPercent = yielding ? Math.min(values.yieldCpuBudgetPercent, values.cpuBudgetPercent) : values.cpuBudgetPercent;
92
+ return {
93
+ report: {
94
+ version: null,
95
+ governor: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
96
+ values,
97
+ sources: {
98
+ maxConcurrentAttempts: attempts.source,
99
+ cpuBudgetPercent: cpu.source,
100
+ yieldCpuBudgetPercent: yieldCpuSource,
101
+ memoryReserveBytes: reserve.source,
102
+ maxHeavySteps: heavySteps.source,
103
+ yieldToForeground: yieldSource,
104
+ },
105
+ bounds,
106
+ rejected,
107
+ },
108
+ yielding,
109
+ governorCpuBudgetFraction: budgetPercent / 100,
110
+ };
111
+ }
112
+ /**
113
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
114
+ * (the bridge then ignores it); malformed values become null so the host default applies.
115
+ */
116
+ export function parseRunnerSettingsDocument(raw) {
117
+ if (!raw || typeof raw !== "object")
118
+ return null;
119
+ const record = raw;
120
+ const version = record.version;
121
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 0)
122
+ return null;
123
+ const numeric = (key) => {
124
+ const value = record[key];
125
+ // Kept as-is (even out of range) so computeEffectiveRunnerSettings can report it as rejected.
126
+ return typeof value === "number" ? value : null;
127
+ };
128
+ return {
129
+ runnerId: typeof record.runnerId === "string" ? record.runnerId : null,
130
+ version,
131
+ maxConcurrentAttempts: numeric("maxConcurrentAttempts"),
132
+ cpuBudgetPercent: numeric("cpuBudgetPercent"),
133
+ yieldCpuBudgetPercent: numeric("yieldCpuBudgetPercent"),
134
+ memoryReserveBytes: numeric("memoryReserveBytes"),
135
+ maxHeavySteps: numeric("maxHeavySteps"),
136
+ yieldToForeground: record.yieldToForeground === true,
137
+ };
138
+ }
139
+ /**
140
+ * The report for what is actually in force after an apply in which the host
141
+ * failed to put some keys in force: each failed key keeps the value (and source)
142
+ * that was in force before, and its failure is reported as an `apply_failed`
143
+ * rejection, so the server never reads a desired value as applied.
144
+ */
145
+ export function runnerSettingsInForce(report, previous, failures) {
146
+ if (failures.length === 0)
147
+ return report;
148
+ const values = { ...report.values };
149
+ const sources = { ...report.sources };
150
+ for (const failure of failures) {
151
+ keepPrevious(values, previous.values, failure.key);
152
+ sources[failure.key] = previous.sources[failure.key];
153
+ }
154
+ return { ...report, values, sources, rejected: [...report.rejected, ...failures] };
155
+ }
156
+ function keepPrevious(target, previous, key) {
157
+ target[key] = previous[key];
158
+ }
159
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
160
+ export function sameRunnerSettingsReport(left, right) {
161
+ return JSON.stringify(left) === JSON.stringify(right);
162
+ }
163
+ function ceilingValue(server, ceiling, fallback) {
164
+ if (server !== null) {
165
+ return ceiling && ceiling.value < server
166
+ ? { value: ceiling.value, source: "host_env" }
167
+ : { value: server, source: "server" };
168
+ }
169
+ return ceiling ? { value: ceiling.value, source: "host_env" } : { value: fallback, source: "default" };
170
+ }
171
+ function floorValue(server, floor, fallback) {
172
+ if (server !== null) {
173
+ return floor !== null && floor > server
174
+ ? { value: floor, source: "host_env" }
175
+ : { value: server, source: "server" };
176
+ }
177
+ return floor !== null ? { value: floor, source: "host_env" } : { value: fallback, source: "default" };
178
+ }
179
+ function lowest(...bounds) {
180
+ let result = null;
181
+ for (const bound of bounds) {
182
+ if (bound && (result === null || bound.value < result.value))
183
+ result = bound;
184
+ }
185
+ return result;
186
+ }
187
+ /**
188
+ * Both CPU ceilings: the new FORGE_HOST_CPU_BUDGET_PERCENT (10–100) and the
189
+ * existing FORGE_HOST_LOAD_CPU_BUDGET_FRACTION (0.05–1, the governor's own
190
+ * parse), reported as a percent.
191
+ */
192
+ function cpuBudgetCeilings(environment) {
193
+ const percent = numberEnv(environment, "FORGE_HOST_CPU_BUDGET_PERCENT", 10, 100);
194
+ const fraction = numberEnv(environment, "FORGE_HOST_LOAD_CPU_BUDGET_FRACTION", 0.05, 1);
195
+ return [
196
+ percent,
197
+ fraction ? { envVar: fraction.envVar, value: Math.round(fraction.value * 10_000) / 100 } : null,
198
+ ];
199
+ }
200
+ /** Matches the lease manager's parse (parseInt, clamped); an unparsable value counts as unset. */
201
+ function integerEnv(environment, envVar, minimum, maximum) {
202
+ const raw = environment[envVar];
203
+ if (raw === undefined || raw.trim() === "")
204
+ return null;
205
+ const parsed = Number.parseInt(raw, 10);
206
+ return Number.isFinite(parsed) ? { envVar, value: Math.max(minimum, Math.min(maximum, parsed)) } : null;
207
+ }
208
+ /** Matches the governor config's parse (Number, clamped); an unparsable value counts as unset. */
209
+ function numberEnv(environment, envVar, minimum, maximum) {
210
+ const raw = environment[envVar];
211
+ if (raw === undefined || raw.trim() === "")
212
+ return null;
213
+ const parsed = Number(raw);
214
+ return Number.isFinite(parsed) ? { envVar, value: Math.min(maximum, Math.max(minimum, parsed)) } : null;
215
+ }
216
+ /** The offer refusal message while the runner yields to foreground work. */
217
+ export function runnerYieldingMessage(report) {
218
+ const where = report.sources.yieldToForeground === "host_local" ? "on this host (forge-bridge yield on)" : "in Forge";
219
+ return `runner_yielding: this runner is yielding to foreground work (turned on ${where}); it takes no new attempts until yield is off. Running attempts continue.`;
220
+ }
221
+ /** One line describing the effective settings, for the bridge log. */
222
+ export function describeRunnerSettings(report) {
223
+ const { values } = report;
224
+ const parts = [
225
+ `max attempts ${values.maxConcurrentAttempts}`,
226
+ `CPU budget ${values.cpuBudgetPercent}%`,
227
+ `yield budget ${values.yieldCpuBudgetPercent}%`,
228
+ `memory reserve ${formatBytes(values.memoryReserveBytes)}`,
229
+ `heavy steps ${values.maxHeavySteps ?? "budget only"}`,
230
+ `yield ${values.yieldToForeground ? "on" : "off"}`,
231
+ ];
232
+ const capped = report.bounds
233
+ .filter(bound => report.sources[bound.key] === "host_env")
234
+ .map(bound => `${bound.envVar}=${bound.value}`);
235
+ return `${parts.join(", ")}${capped.length > 0 ? `; host bounds in force: ${[...new Set(capped)].join(", ")}` : ""}`;
236
+ }
@@ -0,0 +1,45 @@
1
+ import { type DotnetPathPlatform, type DotnetProjectFiles } from "./dotnet-build-outputs.js";
2
+ /** What a supervised project runtime runs, recorded in the attempt log directory at launch. */
3
+ export interface SupervisedRuntimeDescriptor {
4
+ readonly schemaVersion: 1;
5
+ /** The runtime contract's port name, for example `api`. */
6
+ readonly role: string;
7
+ /** The attempt supervisor child, for example `project-api`. */
8
+ readonly childName: string;
9
+ readonly command: string;
10
+ readonly args: readonly string[];
11
+ readonly cwd: string;
12
+ }
13
+ export interface SupervisedRuntimeCollision {
14
+ readonly childName: string;
15
+ readonly role: string;
16
+ /** The runtime's supervised process (the `dotnet run` the supervisor started), when recorded. */
17
+ readonly pid: number | null;
18
+ readonly project: string;
19
+ readonly outputDirectory: string;
20
+ /** The running file the build would have to replace. */
21
+ readonly lockedPath: string;
22
+ }
23
+ export interface SupervisedRuntimeBuildCheck {
24
+ readonly command: string;
25
+ readonly args: readonly string[];
26
+ readonly cwd: string;
27
+ readonly worktreePath: string;
28
+ /** The attempt's FORGE_LOG_DIR, which holds the supervisor ledger and runtime descriptors. */
29
+ readonly logDirectory: string;
30
+ /** A runner-authored script that builds the worktree's solution (a managed verification tier). */
31
+ readonly buildsWorktreeSolution?: boolean;
32
+ readonly platform?: DotnetPathPlatform;
33
+ readonly files?: DotnetProjectFiles;
34
+ }
35
+ export declare function supervisedRuntimeDescriptorPath(logDirectory: string, childName: string): string;
36
+ export declare function writeSupervisedRuntimeDescriptor(logDirectory: string, descriptor: Omit<SupervisedRuntimeDescriptor, "schemaVersion">): Promise<void>;
37
+ /**
38
+ * Finds the first running supervised runtime of this attempt whose build output the command
39
+ * would write. Only the project graph and output directory decide a collision: a build of an
40
+ * unrelated project, into another output, or a test run without a build never matches.
41
+ */
42
+ export declare function findSupervisedRuntimeCollision(check: SupervisedRuntimeBuildCheck): Promise<SupervisedRuntimeCollision | null>;
43
+ export declare function supervisedRuntimeCollisionMessage(collision: SupervisedRuntimeCollision): string;
44
+ /** Fails fast, naming the runtime, instead of letting the build hit the runtime's locked files. */
45
+ export declare function assertBuildSparesSupervisedRuntimes(check: SupervisedRuntimeBuildCheck): Promise<void>;
@@ -0,0 +1,112 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { replaceFile } from "../shared/fs/replace-file.js";
5
+ import { attemptProcessSupervisorLedgerPath } from "./attempt-process-supervisor.js";
6
+ import { canonicalExistingPath, fileSystemProjectFiles, findDotnetOutputCollisions, hostPathPlatform, isDotnetExecutable, parseDotnetOutputCommand, } from "./dotnet-build-outputs.js";
7
+ const activeChildStatuses = new Set(["starting", "running", "stopping"]);
8
+ export function supervisedRuntimeDescriptorPath(logDirectory, childName) {
9
+ return path.join(logDirectory, `${childName}.runtime.json`);
10
+ }
11
+ export async function writeSupervisedRuntimeDescriptor(logDirectory, descriptor) {
12
+ const target = supervisedRuntimeDescriptorPath(logDirectory, descriptor.childName);
13
+ const temporary = `${target}.${randomUUID()}.tmp`;
14
+ await fs.writeFile(temporary, `${JSON.stringify({ schemaVersion: 1, ...descriptor })}\n`, { encoding: "utf8", mode: 0o600 });
15
+ try {
16
+ await replaceFile(temporary, target);
17
+ }
18
+ finally {
19
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
20
+ }
21
+ }
22
+ /**
23
+ * Finds the first running supervised runtime of this attempt whose build output the command
24
+ * would write. Only the project graph and output directory decide a collision: a build of an
25
+ * unrelated project, into another output, or a test run without a build never matches.
26
+ */
27
+ export async function findSupervisedRuntimeCollision(check) {
28
+ const platform = check.platform ?? hostPathPlatform();
29
+ const files = check.files ?? fileSystemProjectFiles;
30
+ const writer = await buildingCommand(check, platform);
31
+ if (!writer)
32
+ return null;
33
+ const ledger = await readJson(attemptProcessSupervisorLedgerPath(check.logDirectory));
34
+ for (const child of ledger?.children ?? []) {
35
+ if (!child.name.startsWith("project-") || !activeChildStatuses.has(child.status))
36
+ continue;
37
+ const descriptor = await readJson(supervisedRuntimeDescriptorPath(check.logDirectory, child.name));
38
+ if (descriptor?.schemaVersion !== 1 || !Array.isArray(descriptor.args))
39
+ continue;
40
+ const holder = parseDotnetOutputCommand(descriptor.command, descriptor.args, await canonicalPath(descriptor.cwd), { platform, holder: true });
41
+ if (!holder)
42
+ continue;
43
+ const [collision] = await findDotnetOutputCollisions(writer, holder, files, platform);
44
+ if (!collision)
45
+ continue;
46
+ const metadata = await readJson(child.metadataPath);
47
+ const pid = [metadata?.providerPid, metadata?.rootPid].find(value => Number.isSafeInteger(value) && value > 0);
48
+ // A default output's framework folder is the wildcard `*` until the project names it.
49
+ const framework = await projectTargetFramework(collision.project, files);
50
+ const outputDirectory = framework ? collision.outputDirectory.replace(/(?<=[\\/])\*(?=[\\/]|$)/u, framework) : collision.outputDirectory;
51
+ return {
52
+ childName: child.name,
53
+ role: descriptor.role,
54
+ pid: pid ?? null,
55
+ project: collision.project,
56
+ outputDirectory,
57
+ lockedPath: lockedOutputPath(collision.project, outputDirectory, await runtimeProject(holder, files), platform),
58
+ };
59
+ }
60
+ return null;
61
+ }
62
+ /** A single-targeted project's TargetFramework, which names the default output's framework folder. */
63
+ async function projectTargetFramework(project, files) {
64
+ const content = await files.read(project);
65
+ return content?.match(/<TargetFramework>\s*([^<;\s]+)\s*<\/TargetFramework>/u)?.[1]?.toLowerCase() ?? null;
66
+ }
67
+ async function buildingCommand(check, platform) {
68
+ const parsed = parseDotnetOutputCommand(check.command, check.args, await canonicalPath(check.cwd), { platform });
69
+ if (parsed || isDotnetExecutable(check.command, platform) || !check.buildsWorktreeSolution)
70
+ return parsed;
71
+ // The verification scripts build the worktree's solution with its default output.
72
+ return parseDotnetOutputCommand("dotnet", ["build"], await canonicalPath(check.worktreePath), { platform });
73
+ }
74
+ /** Both sides compare canonical paths: a junction, symlink, or 8.3 alias must not hide a collision. */
75
+ async function canonicalPath(directory) {
76
+ return await canonicalExistingPath(directory);
77
+ }
78
+ /** The project the runtime runs, at its real location like the collision's project. */
79
+ async function runtimeProject(holder, files) {
80
+ const target = holder.targets[0];
81
+ return target === undefined || !files.canonical ? target : await files.canonical(target);
82
+ }
83
+ /** The runtime's own executable when the colliding project is the one it runs, otherwise that project's assembly. */
84
+ function lockedOutputPath(project, outputDirectory, runtimeProject, platform) {
85
+ const p = platform === "win32" ? path.win32 : path.posix;
86
+ const name = p.basename(project).replace(/\.(?:cs|fs|vb)proj$/iu, "");
87
+ const isRuntimeProject = runtimeProject !== undefined
88
+ && (platform === "win32" ? runtimeProject.toLowerCase() === project.toLowerCase() : runtimeProject === project);
89
+ const fileName = isRuntimeProject ? `${name}${platform === "win32" ? ".exe" : ""}` : `${name}.dll`;
90
+ return p.join(outputDirectory, fileName);
91
+ }
92
+ export function supervisedRuntimeCollisionMessage(collision) {
93
+ return `managed_command_runtime_output_collision: this command would build ${collision.project} into ${collision.outputDirectory}, `
94
+ + `the output the attempt's running supervised runtime ${collision.childName} (role ${collision.role}, PID ${collision.pid ?? "unknown"}) `
95
+ + `executes from; ${collision.lockedPath} is in use. Forge refused it before launch, because the build would fail on the locked file `
96
+ + "(MSB3027 on Windows) or replace files under the running runtime. Build into a different output directory: the runtime runs from its "
97
+ + "own output, so the project's default output is free. Forge rebuilds and restarts the runtime from the current source when validation needs it.";
98
+ }
99
+ /** Fails fast, naming the runtime, instead of letting the build hit the runtime's locked files. */
100
+ export async function assertBuildSparesSupervisedRuntimes(check) {
101
+ const collision = await findSupervisedRuntimeCollision(check);
102
+ if (collision)
103
+ throw new Error(supervisedRuntimeCollisionMessage(collision));
104
+ }
105
+ async function readJson(file) {
106
+ try {
107
+ return JSON.parse(await fs.readFile(file, "utf8"));
108
+ }
109
+ catch {
110
+ return null;
111
+ }
112
+ }