@loucompanion/forge-bridge 0.1.4-dev.04a1e5b9e484 → 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 (272) hide show
  1. package/README.md +145 -4
  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 +101 -15
  16. package/dist/bridge/bridge.service.js +472 -345
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  19. package/dist/bridge/dispatch-result-outbox.js +31 -6
  20. package/dist/bridge/in-flight-registry.d.ts +62 -0
  21. package/dist/bridge/in-flight-registry.js +207 -0
  22. package/dist/bridge/local-yield-flag.d.ts +6 -0
  23. package/dist/bridge/local-yield-flag.js +34 -0
  24. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  25. package/dist/bridge/readiness-result-outbox.js +20 -0
  26. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  27. package/dist/bridge/runner-host-capabilities.js +17 -0
  28. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  29. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  30. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  31. package/dist/bridge/test-postgres-capability.js +120 -0
  32. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  33. package/dist/cleanup/cleanup-wip.js +66 -0
  34. package/dist/cleanup/cleanup.service.d.ts +20 -1
  35. package/dist/cleanup/cleanup.service.js +150 -169
  36. package/dist/cleanup/cleanup.types.d.ts +6 -0
  37. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  38. package/dist/cleanup/forge-owned-paths.js +53 -0
  39. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  40. package/dist/cleanup/host-runtime-ledger.js +130 -0
  41. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  42. package/dist/cleanup/managed-branch-sweep.js +111 -0
  43. package/dist/cli/cli.help.js +76 -14
  44. package/dist/cli/cli.service.d.ts +19 -10
  45. package/dist/cli/cli.service.js +152 -187
  46. package/dist/cli/idle-status.d.ts +84 -0
  47. package/dist/cli/idle-status.js +181 -0
  48. package/dist/cli/local-config.d.ts +6 -0
  49. package/dist/cli/local-config.js +32 -4
  50. package/dist/cli/provider-cli-detection.d.ts +10 -0
  51. package/dist/cli/provider-cli-detection.js +160 -0
  52. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  54. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  55. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  56. package/dist/runtime/attempt-process-supervisor.d.ts +21 -0
  57. package/dist/runtime/attempt-process-supervisor.js +62 -6
  58. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  59. package/dist/runtime/docker-engine-probe.js +7 -0
  60. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  61. package/dist/runtime/dotnet-build-outputs.js +402 -0
  62. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  63. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  64. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  65. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  66. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  67. package/dist/runtime/host-database-capability-boundary.js +1 -0
  68. package/dist/runtime/host-facts.d.ts +36 -0
  69. package/dist/runtime/host-facts.js +95 -0
  70. package/dist/runtime/host-load-admission.d.ts +67 -0
  71. package/dist/runtime/host-load-admission.js +99 -0
  72. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  73. package/dist/runtime/host-load-child-environment.js +76 -0
  74. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  75. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  76. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  77. package/dist/runtime/host-load-governor-config.js +83 -0
  78. package/dist/runtime/host-load-governor.d.ts +186 -0
  79. package/dist/runtime/host-load-governor.js +632 -0
  80. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  81. package/dist/runtime/host-load-ledger-lock.js +187 -0
  82. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  83. package/dist/runtime/host-load-runtime-settings.js +80 -0
  84. package/dist/runtime/host-load-sampler.d.ts +156 -0
  85. package/dist/runtime/host-load-sampler.js +298 -0
  86. package/dist/runtime/host-load-step-class.d.ts +70 -0
  87. package/dist/runtime/host-load-step-class.js +161 -0
  88. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  89. package/dist/runtime/host-load-step-reaper.js +95 -0
  90. package/dist/runtime/host-load-step-run.d.ts +73 -0
  91. package/dist/runtime/host-load-step-run.js +102 -0
  92. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  93. package/dist/runtime/host-load-test-slot.js +81 -0
  94. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  95. package/dist/runtime/host-load-token-ledger.js +453 -0
  96. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  97. package/dist/runtime/host-load-windows-cpu.js +85 -0
  98. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  99. package/dist/runtime/host-pressure-stall.js +168 -0
  100. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  101. package/dist/runtime/host-runtime-contract.js +35 -2
  102. package/dist/runtime/host-runtime-lease.d.ts +77 -5
  103. package/dist/runtime/host-runtime-lease.js +328 -136
  104. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  105. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  106. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  107. package/dist/runtime/host-runtime-promotion.js +48 -0
  108. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  109. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  110. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  111. package/dist/runtime/host-runtime-requirements.js +117 -0
  112. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  113. package/dist/runtime/managed-command-teardown.js +596 -0
  114. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  115. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  116. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  117. package/dist/runtime/playwright-browser-cache.js +227 -0
  118. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  119. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  120. package/dist/runtime/runner-settings.d.ts +104 -0
  121. package/dist/runtime/runner-settings.js +236 -0
  122. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  123. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  124. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  125. package/dist/sandbox/host-capacity-broker.js +336 -0
  126. package/dist/sandbox/managed-branch.d.ts +13 -0
  127. package/dist/sandbox/managed-branch.js +90 -0
  128. package/dist/sandbox/provider-auth/codex.js +11 -11
  129. package/dist/sandbox/runtime.d.ts +10 -1
  130. package/dist/sandbox/runtime.js +47 -8
  131. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  132. package/dist/sandbox/sandbox-cgroups.js +42 -0
  133. package/dist/session/architect-waits.d.ts +2 -0
  134. package/dist/session/architect-waits.js +138 -0
  135. package/dist/session/managed-attempt-tools.d.ts +27 -7
  136. package/dist/session/managed-attempt-tools.js +406 -123
  137. package/dist/session/managed-build-coordinator.d.ts +17 -1
  138. package/dist/session/managed-build-coordinator.js +14 -1
  139. package/dist/session/managed-build-receipt.d.ts +5 -0
  140. package/dist/session/managed-build-receipt.js +8 -3
  141. package/dist/session/managed-command-host-load.d.ts +47 -0
  142. package/dist/session/managed-command-host-load.js +83 -0
  143. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  144. package/dist/session/mcp-argument-coercion.js +121 -0
  145. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  146. package/dist/session/phase-completion.artifacts.js +100 -26
  147. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  148. package/dist/session/phase-completion.command-validation.js +77 -0
  149. package/dist/session/phase-completion.d.ts +12 -0
  150. package/dist/session/phase-completion.helpers.js +13 -12
  151. package/dist/session/phase-completion.js +5 -0
  152. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  153. package/dist/session/phase-completion.mcp-args.js +156 -0
  154. package/dist/session/phase-completion.prompts.js +6 -1
  155. package/dist/session/phase-completion.runtime.d.ts +5 -11
  156. package/dist/session/phase-completion.runtime.js +111 -230
  157. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  158. package/dist/session/phase-completion.schema-parts.js +188 -0
  159. package/dist/session/phase-completion.schemas.d.ts +3 -3
  160. package/dist/session/phase-completion.schemas.js +208 -231
  161. package/dist/session/phase-completion.validation.d.ts +2 -3
  162. package/dist/session/phase-completion.validation.js +49 -93
  163. package/dist/session/pre-publication-host-load.d.ts +27 -0
  164. package/dist/session/pre-publication-host-load.js +111 -0
  165. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  166. package/dist/session/pre-publication-native-postgres.js +111 -0
  167. package/dist/session/pre-publication-pass.d.ts +61 -0
  168. package/dist/session/pre-publication-pass.js +148 -0
  169. package/dist/session/pre-publication-process.d.ts +23 -0
  170. package/dist/session/pre-publication-process.js +109 -0
  171. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  172. package/dist/session/pre-publication-skipped-tests.js +109 -0
  173. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  174. package/dist/session/pre-publication-step-execution.js +50 -0
  175. package/dist/session/pre-publication-validation.d.ts +37 -21
  176. package/dist/session/pre-publication-validation.js +228 -219
  177. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  178. package/dist/session/provider-cli/claude-background-work.js +181 -0
  179. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  180. package/dist/session/provider-cli/host-build-lock.js +30 -0
  181. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  182. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  183. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  184. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  185. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  186. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  187. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  188. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  189. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  190. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  191. package/dist/session/provider-cli/provider-cli.process.d.ts +46 -31
  192. package/dist/session/provider-cli/provider-cli.process.js +286 -403
  193. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  194. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  195. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  196. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  197. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  198. package/dist/session/provider-cli/provider-cli.service.js +207 -192
  199. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  200. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  201. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  203. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  204. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  205. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  206. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  207. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  208. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  209. package/dist/session/provider-cli/provider-output-state.js +15 -0
  210. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  211. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  212. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  213. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  214. package/dist/session/publishable-worktree-changes.js +193 -0
  215. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  216. package/dist/session/qa-sidecar-validation.js +28 -0
  217. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  218. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  219. package/dist/session/session-redaction.js +31 -181
  220. package/dist/session/session.base.d.ts +9 -1
  221. package/dist/session/session.service.d.ts +11 -2
  222. package/dist/session/session.service.js +189 -69
  223. package/dist/session/session.types.d.ts +3 -0
  224. package/dist/session/session.types.js +15 -3
  225. package/dist/session/sidecar-json-shape.d.ts +31 -0
  226. package/dist/session/sidecar-json-shape.js +217 -0
  227. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  228. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  229. package/dist/shared/fs/file-identity.d.ts +10 -0
  230. package/dist/shared/fs/file-identity.js +15 -0
  231. package/dist/shared/fs/replace-file.d.ts +7 -0
  232. package/dist/shared/fs/replace-file.js +33 -0
  233. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  234. package/dist/shared/process/host-process-recovery.js +23 -3
  235. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  236. package/dist/shared/process/host-process-supervisor.js +67 -15
  237. package/dist/shared/process/process-tree.d.ts +52 -0
  238. package/dist/shared/process/process-tree.js +144 -0
  239. package/dist/shared/process/process.d.ts +67 -0
  240. package/dist/shared/process/process.js +213 -11
  241. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  242. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  243. package/dist/shared/process/windows-launch.d.ts +18 -0
  244. package/dist/shared/process/windows-launch.js +68 -0
  245. package/dist/shared/provider-capabilities.js +14 -7
  246. package/dist/version.d.ts +1 -1
  247. package/dist/version.js +1 -1
  248. package/dist/worktree/dependency-warmer.d.ts +25 -0
  249. package/dist/worktree/dependency-warmer.js +120 -10
  250. package/dist/worktree/orphan-relink.d.ts +19 -0
  251. package/dist/worktree/orphan-relink.js +106 -0
  252. package/dist/worktree/wip-git.d.ts +33 -0
  253. package/dist/worktree/wip-git.js +122 -0
  254. package/dist/worktree/wip-refs.d.ts +62 -0
  255. package/dist/worktree/wip-refs.js +119 -0
  256. package/dist/worktree/wip-restore.d.ts +38 -0
  257. package/dist/worktree/wip-restore.js +190 -0
  258. package/dist/worktree/wip-snapshot.d.ts +50 -0
  259. package/dist/worktree/wip-snapshot.js +268 -0
  260. package/dist/worktree/worktree-inputs.d.ts +8 -0
  261. package/dist/worktree/worktree-inputs.js +134 -0
  262. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  263. package/dist/worktree/worktree-origin-sync.js +127 -0
  264. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  265. package/dist/worktree/worktree-wip-events.js +98 -0
  266. package/dist/worktree/worktree-wip.d.ts +50 -0
  267. package/dist/worktree/worktree-wip.js +185 -0
  268. package/dist/worktree/worktree.base.d.ts +7 -1
  269. package/dist/worktree/worktree.service.d.ts +36 -5
  270. package/dist/worktree/worktree.service.js +124 -155
  271. package/dist/worktree/worktree.types.d.ts +38 -0
  272. package/package.json +2 -2
@@ -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
+ }
@@ -0,0 +1,115 @@
1
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import type { HostLoadStepProcess } from "../runtime/host-load-step-reaper.js";
3
+ import type { HostLoadTokenPriority } from "../runtime/host-load-token-ledger.js";
4
+ export declare const sandboxHostCapacityBrokerEnvironment = "FORGE_HOST_LOAD_BROKER";
5
+ export declare const sandboxHostCapacityBrokerProtocol = "stdout-v1";
6
+ export declare const sandboxHostCapacityLineType = "forge_host_capacity";
7
+ export declare const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity";
8
+ /** Owner of authentic replies inside the container: root, via `docker exec --user 0`. */
9
+ export declare const sandboxHostCapacityResponseOwnerUid = 0;
10
+ export declare const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
11
+ export interface SandboxHostCapacityRequest {
12
+ readonly action: "acquire" | "release" | "retain";
13
+ readonly requestId: string;
14
+ readonly stepClass: string;
15
+ readonly label: string;
16
+ }
17
+ export interface SandboxHostCapacityResponse {
18
+ readonly requestId: string;
19
+ /** Rises with every reply the broker sends; the container keeps only the newest. */
20
+ readonly sequence: number;
21
+ readonly status: "waiting" | "admitted" | "failed" | "fenced";
22
+ readonly waitMs?: number;
23
+ readonly reason?: string;
24
+ readonly detail?: string;
25
+ readonly code?: string;
26
+ readonly message?: string;
27
+ }
28
+ export type SandboxHostCapacityDelivery = (response: SandboxHostCapacityResponse) => Promise<void>;
29
+ /** Parses one stdout line; null when it is not a well-formed broker request. */
30
+ export declare function parseSandboxHostCapacityRequest(line: string): SandboxHostCapacityRequest | null;
31
+ export interface SandboxHostCapacityBrokerOptions {
32
+ /** Requests (acquire or release) one sandbox may hold or start at once. */
33
+ readonly maximumOutstanding?: number;
34
+ /** Request lines allowed in a burst, and their sustained rate. */
35
+ readonly burst?: number;
36
+ readonly refillPerSecond?: number;
37
+ /** The sandbox's process tree (its container's init), recorded on each brokered token. */
38
+ readonly stepProcess?: () => Promise<HostLoadStepProcess | null>;
39
+ /** Delay before retrying a failed delivery; doubles up to a few seconds. */
40
+ readonly retryMs?: number;
41
+ readonly now?: () => number;
42
+ }
43
+ /**
44
+ * One sandbox's brokered tokens. The sandbox never chooses the cost or the
45
+ * attempt. Replies for one request go out one at a time, newest state only,
46
+ * each with a rising sequence the container-side writer uses to refuse an
47
+ * older reply; a failed delivery is retried until a newer state replaces it
48
+ * or the broker closes. A sandbox that floods requests or exceeds its
49
+ * outstanding limit stops the broker and fails its attempt.
50
+ */
51
+ export declare class SandboxHostCapacityBroker {
52
+ private readonly gate;
53
+ private readonly dispatchAttemptId;
54
+ private readonly priority;
55
+ private readonly deliver;
56
+ private readonly options;
57
+ private readonly tokens;
58
+ private readonly deliveries;
59
+ private readonly work;
60
+ private readonly maximumOutstanding;
61
+ private readonly burst;
62
+ private readonly refillPerSecond;
63
+ private readonly retryMs;
64
+ private readonly now;
65
+ private sequence;
66
+ private allowance;
67
+ private allowanceAtMs;
68
+ private closed;
69
+ private abuse;
70
+ constructor(gate: HostLoadStepGate, dispatchAttemptId: string, priority: HostLoadTokenPriority, deliver: SandboxHostCapacityDelivery, options?: SandboxHostCapacityBrokerOptions);
71
+ /**
72
+ * True when the line was a broker request; such a line is never a runner
73
+ * event. Throws sandbox_host_capacity_abuse once the sandbox breaks its
74
+ * limits: its tokens are returned and the attempt fails with that reason.
75
+ */
76
+ handleLine(line: string): boolean;
77
+ /** The sandbox exited: cancel its waits and return every token it holds. */
78
+ close(): Promise<void>;
79
+ /** Requests waiting or admitted, for diagnostics and tests. */
80
+ outstanding(): number;
81
+ private stop;
82
+ private takeAllowance;
83
+ private track;
84
+ private acquire;
85
+ /**
86
+ * The sandbox's step ended but part of its tree may still run: the host token is
87
+ * kept, marked retained (so the attempt's own next step does not wait for it),
88
+ * until the sandbox releases the request or exits.
89
+ */
90
+ private retain;
91
+ private release;
92
+ /** Queues the newest state for a request; at most one delivery per request is in flight. */
93
+ private respond;
94
+ private pump;
95
+ }
96
+ /**
97
+ * Adds the broker variables to a worker `docker create` command, just before
98
+ * its image: the protocol, and the host's maximum queue wait so the
99
+ * container's own fail-safe never fires before the host answers.
100
+ */
101
+ export declare function withSandboxHostCapacityBroker(createArgs: readonly string[], image: string, maxWaitMs: number): string[];
102
+ /** `docker exec` arguments that write one reply into the container as root. */
103
+ export declare function sandboxHostCapacityDeliveryExecArgs(container: string): string[];
104
+ /**
105
+ * The `node -e` script that writes one response file inside the container, run
106
+ * as root. It keeps the newest reply: one with a lower or equal sequence than
107
+ * the file already holds is dropped, so a late delivery can never replace a
108
+ * newer state. Replies are world-readable but owned by the writer (root, via
109
+ * `docker exec --user 0`). The directory must already be owned by that same uid
110
+ * and writable by no one else, i.e. the root-owned reply mount; it is never
111
+ * created here, where it could turn out to be the sandbox's own directory. A
112
+ * runtime without POSIX user ids (Windows) cannot prove that, so the script
113
+ * writes nothing there (exit 3), as for any directory it cannot trust.
114
+ */
115
+ export declare const sandboxHostCapacityResponseScript: string;