@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.0f8fb73715e8

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 (329) hide show
  1. package/README.md +183 -4
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +40 -0
  5. package/dist/bridge/bridge-chat-provider-command.js +230 -0
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.base.d.ts +9 -0
  17. package/dist/bridge/bridge.service.d.ts +102 -14
  18. package/dist/bridge/bridge.service.js +499 -471
  19. package/dist/bridge/bridge.types.d.ts +37 -0
  20. package/dist/bridge/bridge.types.js +2 -1
  21. package/dist/bridge/default-session-service.d.ts +13 -0
  22. package/dist/bridge/default-session-service.js +22 -0
  23. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  24. package/dist/bridge/dispatch-offer-policy.js +58 -0
  25. package/dist/bridge/in-flight-registry.d.ts +62 -0
  26. package/dist/bridge/in-flight-registry.js +207 -0
  27. package/dist/bridge/local-yield-flag.d.ts +6 -0
  28. package/dist/bridge/local-yield-flag.js +34 -0
  29. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  30. package/dist/bridge/readiness-result-outbox.js +20 -0
  31. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  32. package/dist/bridge/runner-host-capabilities.js +31 -1
  33. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  34. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  35. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  36. package/dist/bridge/test-postgres-capability.js +120 -0
  37. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  38. package/dist/bridge/windows-bash-resolution.js +153 -0
  39. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  40. package/dist/cleanup/cleanup-wip.js +66 -0
  41. package/dist/cleanup/cleanup.service.d.ts +20 -1
  42. package/dist/cleanup/cleanup.service.js +150 -169
  43. package/dist/cleanup/cleanup.types.d.ts +6 -0
  44. package/dist/cleanup/forge-owned-paths.d.ts +11 -0
  45. package/dist/cleanup/forge-owned-paths.js +62 -0
  46. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  47. package/dist/cleanup/host-runtime-ledger.js +130 -0
  48. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  49. package/dist/cleanup/managed-branch-sweep.js +111 -0
  50. package/dist/cli/cli.help.js +75 -13
  51. package/dist/cli/cli.service.d.ts +19 -10
  52. package/dist/cli/cli.service.js +161 -228
  53. package/dist/cli/idle-status.d.ts +84 -0
  54. package/dist/cli/idle-status.js +181 -0
  55. package/dist/cli/local-config.d.ts +18 -1
  56. package/dist/cli/local-config.js +67 -5
  57. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  58. package/dist/cli/provider-cli-advertising.js +88 -0
  59. package/dist/cli/provider-cli-detection.d.ts +10 -0
  60. package/dist/cli/provider-cli-detection.js +160 -0
  61. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  62. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  63. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  64. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  65. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  66. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  67. package/dist/runtime/attempt-process-supervisor.js +12 -6
  68. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  69. package/dist/runtime/docker-engine-probe.js +7 -0
  70. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  71. package/dist/runtime/dotnet-build-outputs.js +402 -0
  72. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  73. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  74. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  75. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  76. package/dist/runtime/host-facts.d.ts +2 -1
  77. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  78. package/dist/runtime/host-listener-inspector.js +84 -3
  79. package/dist/runtime/host-load-admission.d.ts +72 -0
  80. package/dist/runtime/host-load-admission.js +99 -0
  81. package/dist/runtime/host-load-capacity.d.ts +198 -0
  82. package/dist/runtime/host-load-capacity.js +353 -0
  83. package/dist/runtime/host-load-child-environment.d.ts +40 -0
  84. package/dist/runtime/host-load-child-environment.js +110 -0
  85. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  86. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  87. package/dist/runtime/host-load-governor-config.d.ts +82 -0
  88. package/dist/runtime/host-load-governor-config.js +104 -0
  89. package/dist/runtime/host-load-governor.d.ts +273 -0
  90. package/dist/runtime/host-load-governor.js +831 -0
  91. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  92. package/dist/runtime/host-load-ledger-lock.js +187 -0
  93. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  94. package/dist/runtime/host-load-live-test-slots.js +193 -0
  95. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  96. package/dist/runtime/host-load-runtime-settings.js +80 -0
  97. package/dist/runtime/host-load-sampler.d.ts +92 -2
  98. package/dist/runtime/host-load-sampler.js +166 -8
  99. package/dist/runtime/host-load-step-class.d.ts +70 -0
  100. package/dist/runtime/host-load-step-class.js +161 -0
  101. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  102. package/dist/runtime/host-load-step-reaper.js +95 -0
  103. package/dist/runtime/host-load-step-run.d.ts +107 -0
  104. package/dist/runtime/host-load-step-run.js +158 -0
  105. package/dist/runtime/host-load-test-slot.d.ts +46 -0
  106. package/dist/runtime/host-load-test-slot.js +100 -0
  107. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  108. package/dist/runtime/host-load-token-ledger.js +453 -0
  109. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  110. package/dist/runtime/host-load-windows-cpu.js +85 -0
  111. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  112. package/dist/runtime/host-pressure-stall.js +48 -1
  113. package/dist/runtime/host-runtime-contract.d.ts +15 -0
  114. package/dist/runtime/host-runtime-contract.js +39 -6
  115. package/dist/runtime/host-runtime-lease.d.ts +101 -6
  116. package/dist/runtime/host-runtime-lease.js +408 -294
  117. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  118. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  119. package/dist/runtime/host-runtime-promotion.d.ts +101 -2
  120. package/dist/runtime/host-runtime-promotion.js +355 -14
  121. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  122. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  123. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  124. package/dist/runtime/host-runtime-requirements.js +117 -0
  125. package/dist/runtime/managed-command-teardown.js +5 -16
  126. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  127. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  128. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  129. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  130. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  131. package/dist/runtime/prepared-runtime-identity.js +130 -9
  132. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  133. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  134. package/dist/runtime/runner-settings.d.ts +104 -0
  135. package/dist/runtime/runner-settings.js +236 -0
  136. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  137. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  138. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  139. package/dist/sandbox/host-capacity-broker.js +336 -0
  140. package/dist/sandbox/managed-branch.d.ts +13 -0
  141. package/dist/sandbox/managed-branch.js +90 -0
  142. package/dist/sandbox/provider-auth/codex.js +11 -11
  143. package/dist/sandbox/runtime.d.ts +11 -3
  144. package/dist/sandbox/runtime.js +53 -20
  145. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  146. package/dist/sandbox/sandbox-cgroups.js +42 -0
  147. package/dist/sandbox/sandbox-input.d.ts +22 -0
  148. package/dist/sandbox/sandbox-input.js +49 -0
  149. package/dist/sandbox/workspace.service.js +15 -2
  150. package/dist/session/architect-waits.d.ts +2 -0
  151. package/dist/session/architect-waits.js +138 -0
  152. package/dist/session/managed-attempt-tools.d.ts +2 -7
  153. package/dist/session/managed-attempt-tools.js +204 -141
  154. package/dist/session/managed-build-coordinator.d.ts +16 -0
  155. package/dist/session/managed-build-coordinator.js +10 -0
  156. package/dist/session/managed-build-receipt.d.ts +7 -0
  157. package/dist/session/managed-build-receipt.js +11 -3
  158. package/dist/session/managed-command-environment.d.ts +8 -0
  159. package/dist/session/managed-command-environment.js +28 -0
  160. package/dist/session/managed-command-host-load.d.ts +52 -0
  161. package/dist/session/managed-command-host-load.js +87 -0
  162. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  163. package/dist/session/mcp-argument-coercion.js +121 -0
  164. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  165. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  166. package/dist/session/phase-completion.artifacts.d.ts +9 -17
  167. package/dist/session/phase-completion.artifacts.js +158 -190
  168. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  169. package/dist/session/phase-completion.command-validation.js +77 -0
  170. package/dist/session/phase-completion.d.ts +31 -2
  171. package/dist/session/phase-completion.helpers.js +18 -65
  172. package/dist/session/phase-completion.js +19 -32
  173. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  174. package/dist/session/phase-completion.mcp-args.js +195 -0
  175. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  176. package/dist/session/phase-completion.phase-aliases.js +43 -0
  177. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  178. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  179. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  180. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  181. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  182. package/dist/session/phase-completion.pr-review.js +294 -0
  183. package/dist/session/phase-completion.prompts.d.ts +1 -1
  184. package/dist/session/phase-completion.prompts.js +20 -1
  185. package/dist/session/phase-completion.runtime.d.ts +13 -12
  186. package/dist/session/phase-completion.runtime.js +113 -214
  187. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  188. package/dist/session/phase-completion.schema-parts.js +188 -0
  189. package/dist/session/phase-completion.schemas.d.ts +3 -3
  190. package/dist/session/phase-completion.schemas.js +219 -232
  191. package/dist/session/phase-completion.validation.d.ts +3 -3
  192. package/dist/session/phase-completion.validation.js +58 -94
  193. package/dist/session/pr-review-diff-base.d.ts +18 -0
  194. package/dist/session/pr-review-diff-base.js +44 -0
  195. package/dist/session/pr-review-placement.d.ts +50 -0
  196. package/dist/session/pr-review-placement.js +91 -0
  197. package/dist/session/pre-publication-change-set.d.ts +62 -0
  198. package/dist/session/pre-publication-change-set.js +166 -0
  199. package/dist/session/pre-publication-host-load.d.ts +27 -0
  200. package/dist/session/pre-publication-host-load.js +112 -0
  201. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  202. package/dist/session/pre-publication-native-postgres.js +111 -0
  203. package/dist/session/pre-publication-pass.d.ts +61 -0
  204. package/dist/session/pre-publication-pass.js +148 -0
  205. package/dist/session/pre-publication-process.d.ts +3 -0
  206. package/dist/session/pre-publication-process.js +32 -19
  207. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  208. package/dist/session/pre-publication-step-execution.js +50 -0
  209. package/dist/session/pre-publication-validation.d.ts +39 -22
  210. package/dist/session/pre-publication-validation.js +241 -207
  211. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  212. package/dist/session/provider-cli/claude-background-work.js +181 -0
  213. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  214. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  215. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  216. package/dist/session/provider-cli/host-build-lock.js +30 -0
  217. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  218. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  219. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  220. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  221. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  222. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  223. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  224. package/dist/session/provider-cli/pre-publication-repair.js +281 -0
  225. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  226. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  227. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  228. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  229. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  230. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  231. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  232. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  233. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  234. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  235. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  236. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  237. package/dist/session/provider-cli/provider-cli.process.js +41 -432
  238. package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -3
  239. package/dist/session/provider-cli/provider-cli.prompts.js +183 -90
  240. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  241. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  242. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  243. package/dist/session/provider-cli/provider-cli.runtime.js +43 -1
  244. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  245. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  246. package/dist/session/provider-cli/provider-cli.service.d.ts +18 -18
  247. package/dist/session/provider-cli/provider-cli.service.js +127 -317
  248. package/dist/session/provider-cli/provider-cli.types.d.ts +35 -0
  249. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  250. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  251. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  252. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  253. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  254. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  255. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  256. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  257. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  258. package/dist/session/provider-cli/provider-output-state.js +6 -0
  259. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  260. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  261. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  262. package/dist/session/qa-sidecar-validation.js +28 -0
  263. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  264. package/dist/session/sandbox-host-capacity-gate.js +279 -0
  265. package/dist/session/session-host-project.d.ts +22 -0
  266. package/dist/session/session-host-project.js +98 -0
  267. package/dist/session/session-redaction.js +31 -181
  268. package/dist/session/session.base.d.ts +9 -1
  269. package/dist/session/session.parse-helpers.d.ts +10 -0
  270. package/dist/session/session.parse-helpers.js +84 -0
  271. package/dist/session/session.runtime-refresh.d.ts +46 -0
  272. package/dist/session/session.runtime-refresh.js +116 -0
  273. package/dist/session/session.service.d.ts +16 -2
  274. package/dist/session/session.service.js +208 -155
  275. package/dist/session/session.types.d.ts +8 -0
  276. package/dist/session/session.types.js +13 -83
  277. package/dist/session/session.types.pr-review.d.ts +48 -0
  278. package/dist/session/session.types.pr-review.js +51 -0
  279. package/dist/session/sidecar-json-shape.d.ts +31 -0
  280. package/dist/session/sidecar-json-shape.js +217 -0
  281. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  282. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  283. package/dist/shared/fs/file-identity.d.ts +10 -0
  284. package/dist/shared/fs/file-identity.js +15 -0
  285. package/dist/shared/fs/replace-file.d.ts +7 -0
  286. package/dist/shared/fs/replace-file.js +33 -0
  287. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  288. package/dist/shared/process/host-process-recovery.js +23 -3
  289. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  290. package/dist/shared/process/host-process-supervisor.js +67 -15
  291. package/dist/shared/process/process-tree.d.ts +52 -0
  292. package/dist/shared/process/process-tree.js +144 -0
  293. package/dist/shared/process/process.d.ts +67 -0
  294. package/dist/shared/process/process.js +213 -11
  295. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  296. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  297. package/dist/shared/process/windows-launch.d.ts +18 -0
  298. package/dist/shared/process/windows-launch.js +68 -0
  299. package/dist/shared/provider-capabilities.d.ts +2 -0
  300. package/dist/shared/provider-capabilities.js +23 -7
  301. package/dist/version.d.ts +1 -1
  302. package/dist/version.js +1 -1
  303. package/dist/worktree/artifact-injector.js +24 -0
  304. package/dist/worktree/dependency-warmer.d.ts +25 -0
  305. package/dist/worktree/dependency-warmer.js +46 -10
  306. package/dist/worktree/orphan-relink.d.ts +19 -0
  307. package/dist/worktree/orphan-relink.js +106 -0
  308. package/dist/worktree/wip-git.d.ts +58 -0
  309. package/dist/worktree/wip-git.js +182 -0
  310. package/dist/worktree/wip-refs.d.ts +85 -0
  311. package/dist/worktree/wip-refs.js +169 -0
  312. package/dist/worktree/wip-restore.d.ts +51 -0
  313. package/dist/worktree/wip-restore.js +324 -0
  314. package/dist/worktree/wip-snapshot.d.ts +53 -0
  315. package/dist/worktree/wip-snapshot.js +270 -0
  316. package/dist/worktree/worktree-inputs.d.ts +8 -0
  317. package/dist/worktree/worktree-inputs.js +134 -0
  318. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  319. package/dist/worktree/worktree-origin-sync.js +128 -0
  320. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  321. package/dist/worktree/worktree-wip-events.js +148 -0
  322. package/dist/worktree/worktree-wip.d.ts +57 -0
  323. package/dist/worktree/worktree-wip.js +200 -0
  324. package/dist/worktree/worktree.base.d.ts +7 -1
  325. package/dist/worktree/worktree.service.d.ts +58 -5
  326. package/dist/worktree/worktree.service.js +237 -161
  327. package/dist/worktree/worktree.types.d.ts +54 -0
  328. package/package.json +2 -2
  329. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -0,0 +1,831 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import os from "node:os";
3
+ import { ForgeFailureError } from "../session/session.types.js";
4
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
5
+ import { decideHostLoadAdmission, } from "./host-load-admission.js";
6
+ import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
7
+ import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
8
+ import { HostLoadRuntimeSettingsReader } from "./host-load-runtime-settings.js";
9
+ import { decideHostTestSlot, takesHostTestSlot } from "./host-load-test-slot.js";
10
+ import { HostTestSlotController } from "./host-load-capacity.js";
11
+ import { hostLiveReadings, LiveTestSlotsBoard } from "./host-load-live-test-slots.js";
12
+ import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
13
+ import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
14
+ export class HostCapacityTimeoutError extends ForgeFailureError {
15
+ stepClass;
16
+ label;
17
+ waitMs;
18
+ code = "host_capacity_timeout";
19
+ constructor(stepClass, label, waitMs, detail) {
20
+ super("host_capacity_timeout", `host_capacity_timeout: ${label} (${stepClass}) waited ${Math.round(waitMs / 1000)}s for host capacity without being admitted: ${detail} This is a retryable host-load condition, not a test failure.`, "bridge");
21
+ this.stepClass = stepClass;
22
+ this.label = label;
23
+ this.waitMs = waitMs;
24
+ this.name = "HostCapacityTimeoutError";
25
+ }
26
+ }
27
+ /** One log line: "Host test slots: 3 at once (auto-sized from …); lowered while other work needs the host." */
28
+ export function describeHostTestSlotCapacity(capacity) {
29
+ const live = capacity.liveAdjustment
30
+ ? capacity.inForce < capacity.configured
31
+ ? `; ${capacity.inForce} in force now, ${capacity.inForceDetail}`
32
+ : "; lowered while other work on the host needs the machine, raised again slowly"
33
+ : "";
34
+ return `Host test slots: ${capacity.configured} at once (${capacity.detail})${live}.`;
35
+ }
36
+ /**
37
+ * Host-wide admission for heavy steps (decision 0013). Waiters queue
38
+ * foreground before background and FIFO within a class; a waiter that fits may
39
+ * overtake an unfit head until the head has waited past the anti-starvation
40
+ * window. Running steps are never preempted. Reserved cost comes from the
41
+ * shared token ledger, so other processes' steps count against the same budget.
42
+ * The host test slot (decision 0018) comes first: a heavy step waits for it in
43
+ * the host-wide queue the ledger keeps, then for the budget when that is on.
44
+ */
45
+ export class HostLoadGovernor {
46
+ options;
47
+ enabled;
48
+ config;
49
+ ledger;
50
+ waiters = [];
51
+ held = new Map();
52
+ recheckTimer = null;
53
+ renewTimer = null;
54
+ draining = null;
55
+ drainAgain = false;
56
+ /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
57
+ idleOwnMemoryBytes = null;
58
+ /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
59
+ runtimeSettings;
60
+ /** Lowers the host test slot count while other work needs the machine; null when the count is fixed. */
61
+ liveTestSlots;
62
+ /** Lowered counts shared with the other governors on this state root. */
63
+ liveTestSlotsBoard;
64
+ lastLiveTestSlots = null;
65
+ /** Feeds the controller while this governor holds slots or its count is lowered, so no backlog builds up. */
66
+ liveFeedTimer = null;
67
+ constructor(options) {
68
+ this.options = options;
69
+ this.config = options.config ?? loadHostLoadGovernorConfig();
70
+ this.enabled = hostLoadGovernorEnabled(this.config);
71
+ this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
72
+ // With one slot there is nothing to lower: live adjustment never goes below 1.
73
+ this.liveTestSlots = this.config.liveTestSlots === true && this.config.testSlots > 1 && this.config.hostCapacity
74
+ ? new HostTestSlotController(this.config.hostCapacity, this.config.testSlots, {
75
+ sampleGapMs: this.config.sampleIntervalMs * 3,
76
+ ...options.liveTestSlotTiming,
77
+ })
78
+ : null;
79
+ this.liveTestSlotsBoard = this.liveTestSlots ? new LiveTestSlotsBoard(options.stateRoot, { now: options.now, liveness: options.liveness })
80
+ : null;
81
+ this.ledger = new HostLoadTokenLedger({
82
+ stateRoot: options.stateRoot,
83
+ leaseMs: this.config.leaseMs,
84
+ now: options.now,
85
+ liveness: options.liveness,
86
+ owner: options.owner,
87
+ terminateStep: options.terminateStep,
88
+ suspendedMs: options.suspendedMs,
89
+ // Every ledger transaction renews the steps this governor is running.
90
+ heldTokens: () => [...this.held.values()].map(entry => entry.token),
91
+ // ...and keeps its waiters' places in the host test slot queue.
92
+ waitingTickets: () => this.waiters.flatMap(waiter => waiter.ticket && !waiter.settled ? [waiter.ticket] : []),
93
+ });
94
+ }
95
+ get maxWaitMs() {
96
+ return this.config.maxTotalWaitMs;
97
+ }
98
+ async acquire(request, options = {}) {
99
+ if (!this.enabled) {
100
+ throw new Error("host_load_governor_disabled: acquire() requires a host test slot or FORGE_HOST_LOAD_GOVERNOR=on.");
101
+ }
102
+ const { signal } = options;
103
+ if (signal?.aborted)
104
+ throw abortError(signal);
105
+ // With the budget off, a step that takes no slot needs nothing from the ledger:
106
+ // a ledger fault cannot fail a `git status` or a dependency install.
107
+ if (this.config.mode !== "on" && !takesHostTestSlot(request.stepClass))
108
+ return slotFreeAdmission(request);
109
+ // Only the budget and live slot adjustment read load samples.
110
+ if (this.config.mode === "on" || this.liveTestSlots)
111
+ await this.options.load.start().catch(() => undefined);
112
+ if (signal?.aborted)
113
+ throw abortError(signal);
114
+ return await new Promise((resolve, reject) => {
115
+ const enqueuedAtMs = monotonicNowMs();
116
+ const waiter = {
117
+ request,
118
+ enqueuedAtMs,
119
+ signal,
120
+ onWaiting: options.onWaiting,
121
+ resolve,
122
+ reject,
123
+ abort: () => this.settle(waiter, () => reject(abortError(signal))),
124
+ deadline: null,
125
+ progressAtMs: enqueuedAtMs,
126
+ lastDecision: null,
127
+ notified: Promise.resolve(),
128
+ settled: false,
129
+ ticket: this.config.testSlots > 0 && takesHostTestSlot(request.stepClass)
130
+ ? {
131
+ ticketId: randomUUID(),
132
+ stepClass: request.stepClass,
133
+ label: request.label,
134
+ dispatchAttemptId: request.dispatchAttemptId,
135
+ priority: request.priority,
136
+ enqueuedAt: new Date(this.options.now?.() ?? Date.now()).toISOString(),
137
+ }
138
+ : null,
139
+ };
140
+ // The backstop: even behind healthy holders, a step queues no longer than maxTotalWaitMs.
141
+ waiter.deadline = setTimeout(() => this.timeOut(waiter, `${waiter.lastDecision?.detail ?? "The host stayed at capacity."} It reached the longest a step may queue (${minutes(this.config.maxTotalWaitMs)}).`), this.config.maxTotalWaitMs);
142
+ waiter.deadline.unref?.();
143
+ signal?.addEventListener("abort", waiter.abort, { once: true });
144
+ // Foreground goes ahead of background, except background that has already
145
+ // waited past the anti-starvation window: steady foreground load cannot starve it.
146
+ const backgroundIndex = request.priority === "foreground"
147
+ ? this.waiters.findIndex(candidate => candidate.request.priority === "background"
148
+ && waiter.enqueuedAtMs - candidate.enqueuedAtMs < this.config.antiStarvationMs)
149
+ : -1;
150
+ if (backgroundIndex < 0)
151
+ this.waiters.push(waiter);
152
+ else
153
+ this.waiters.splice(backgroundIndex, 0, waiter);
154
+ this.armRecheck();
155
+ void this.drain();
156
+ });
157
+ }
158
+ /** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
159
+ async reclaim() {
160
+ if (!this.enabled)
161
+ return [];
162
+ const outcome = await this.ledger.transaction(() => undefined);
163
+ this.applyHeldOutcome(outcome);
164
+ if (outcome.reclaimed.length > 0)
165
+ void this.drain();
166
+ return outcome.reclaimed;
167
+ }
168
+ /** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
169
+ async releaseOrphaned(belongs) {
170
+ if (!this.enabled)
171
+ return [];
172
+ const released = await this.ledger.releaseOrphaned(belongs);
173
+ if (released.length > 0)
174
+ void this.drain();
175
+ return released;
176
+ }
177
+ /**
178
+ * Attempt teardown: cancels the attempt's queued steps and stops its running
179
+ * ones (their `fenced` signal aborts with dispatch_cancelled). A running step
180
+ * keeps its token, and its cost, until the step itself returns it once its
181
+ * processes are gone, so the capacity is never reused while it still runs.
182
+ */
183
+ stopAttempt(dispatchAttemptId) {
184
+ if (!this.enabled)
185
+ return;
186
+ this.cancelAttemptWaiters(dispatchAttemptId);
187
+ for (const entry of this.held.values()) {
188
+ if (entry.token.dispatchAttemptId !== dispatchAttemptId)
189
+ continue;
190
+ this.lose(entry, new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while this step ran; it was stopped before its host capacity was returned.", "bridge"));
191
+ }
192
+ }
193
+ /**
194
+ * Cancels the attempt's queued steps and returns every token it holds at
195
+ * once. Only for callers that know the attempt's steps are no longer running;
196
+ * attempt teardown uses stopAttempt.
197
+ */
198
+ async releaseAttempt(dispatchAttemptId) {
199
+ if (!this.enabled)
200
+ return;
201
+ this.cancelAttemptWaiters(dispatchAttemptId);
202
+ const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
203
+ await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
204
+ }
205
+ cancelAttemptWaiters(dispatchAttemptId) {
206
+ for (const waiter of [...this.waiters]) {
207
+ if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
208
+ continue;
209
+ this.settle(waiter, () => waiter.reject(new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while its step waited for host capacity.", "bridge")));
210
+ }
211
+ }
212
+ /** Waiting and admitted steps of this process, for diagnostics. */
213
+ snapshot() {
214
+ return { waiting: this.waiters.length, held: [...this.held.values()].map(entry => entry.token) };
215
+ }
216
+ /**
217
+ * The host test slot count and why, for diagnostics: the configured count (auto-sized or the
218
+ * operator's), and the count in force after the last live adjustment, with its reason.
219
+ */
220
+ testSlotCapacity() {
221
+ const configured = this.config.testSlots;
222
+ const live = this.lastLiveTestSlots;
223
+ return {
224
+ configured,
225
+ source: this.config.testSlotsSource ?? "operator",
226
+ detail: this.config.testSlotsDetail ?? `${configured} fixed`,
227
+ liveAdjustment: this.liveTestSlots !== null,
228
+ inForce: live?.slots ?? configured,
229
+ inForceDetail: live?.detail ?? "",
230
+ };
231
+ }
232
+ /**
233
+ * Folds the sampler's new readings into the live count with the holders the ledger has now,
234
+ * without admitting anything (the feed timer, and diagnostics). A no-op without live adjustment.
235
+ */
236
+ async refreshTestSlots() {
237
+ if (this.liveTestSlots) {
238
+ const published = await this.publishedTestSlots();
239
+ this.applyHeldOutcome(await this.ledger.transaction(transaction => {
240
+ this.testSlotsInForce(transaction.tokens, published);
241
+ }));
242
+ }
243
+ return this.testSlotCapacity();
244
+ }
245
+ async drain() {
246
+ if (this.draining) {
247
+ this.drainAgain = true;
248
+ return await this.draining;
249
+ }
250
+ this.draining = (async () => {
251
+ do {
252
+ this.drainAgain = false;
253
+ await this.drainOnce().catch(error => this.failWaiters(error));
254
+ } while (this.drainAgain && this.waiters.length > 0);
255
+ })().finally(() => {
256
+ this.draining = null;
257
+ });
258
+ return await this.draining;
259
+ }
260
+ async drainOnce() {
261
+ if (this.waiters.length === 0)
262
+ return;
263
+ const budget = this.config.mode === "on" ? await this.budgetPass() : null;
264
+ const published = await this.publishedTestSlots();
265
+ if (this.waiters.length === 0)
266
+ return;
267
+ const nowMs = monotonicNowMs();
268
+ const outcomes = [];
269
+ const outcome = await this.ledger.transaction(transaction => {
270
+ const runningMemoryBytes = budget ? this.runningStepsMemoryBytes(transaction.tokens) : 0;
271
+ const testSlots = this.testSlotsInForce(transaction.tokens, published);
272
+ const head = this.waiters[0];
273
+ const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
274
+ for (const waiter of this.waiters) {
275
+ if (waiter.settled)
276
+ continue;
277
+ const decision = this.decide(waiter, transaction, budget, runningMemoryBytes, testSlots);
278
+ if (decision.admitted && waiter.ticket) {
279
+ // The ticket leaves the host queue in the same commit that issues the token.
280
+ transaction.removeTicket(waiter.ticket.ticketId);
281
+ waiter.ticket = null;
282
+ }
283
+ outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
284
+ // A starving head blocks the budget so running steps drain and it can start. A
285
+ // slot wait does not: the host queue already orders slot waiters, and steps
286
+ // behind this one locally may be ahead of it there, or take no slot.
287
+ if (waiter === head && headStarving && !decision.admitted && decision.reason !== "host_test_slot")
288
+ break;
289
+ }
290
+ // The steps just admitted hold slots for the readings that follow.
291
+ this.liveTestSlots?.noteHolders(slotHolders(transaction.tokens));
292
+ });
293
+ this.applyHeldOutcome(outcome);
294
+ for (const { waiter, token, decision } of outcomes) {
295
+ if (!token) {
296
+ const changed = waitChanged(waiter.lastDecision, decision);
297
+ waiter.lastDecision = decision;
298
+ if (changed && !waiter.settled)
299
+ this.notifyWaiting(waiter, decision);
300
+ this.checkStalled(waiter, decision);
301
+ continue;
302
+ }
303
+ const entry = {
304
+ token,
305
+ fencedController: new AbortController(),
306
+ fencedError: null,
307
+ renewedAtMs: monotonicNowMs(),
308
+ releasing: false,
309
+ releaseInFlight: null,
310
+ gone: false,
311
+ retainedUntil: null,
312
+ retainCheck: null,
313
+ };
314
+ this.held.set(token.tokenId, entry);
315
+ this.armRenewal();
316
+ if (waiter.settled) {
317
+ // Cancelled or timed out while the decision was being made.
318
+ void this.releaseHeld(entry).catch(() => undefined);
319
+ continue;
320
+ }
321
+ const waitMs = Math.max(0, monotonicNowMs() - waiter.enqueuedAtMs);
322
+ this.settle(waiter, () => waiter.resolve({
323
+ tokenId: token.tokenId,
324
+ fencingToken: token.fencingToken,
325
+ stepClass: token.stepClass,
326
+ waitMs,
327
+ decision,
328
+ fenced: entry.fencedController.signal,
329
+ attachProcess: stepProcess => this.attachProcess(entry, stepProcess),
330
+ release: () => this.releaseHeld(entry),
331
+ retainUntilStopped: (stillGone, reason) => this.retainUntilStopped(entry, stillGone, reason),
332
+ }));
333
+ }
334
+ }
335
+ /**
336
+ * Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
337
+ * bridge has in force apply from the next admission; running steps keep theirs.
338
+ * The operator's env ceilings hold with or without the file, and over whatever it says.
339
+ */
340
+ async budgetPass() {
341
+ const overrides = await this.runtimeSettings.read();
342
+ const cpuBudgetFraction = Math.min(overrides?.cpuBudgetFraction ?? this.config.cpuBudgetFraction, this.config.cpuBudgetCeilingFraction ?? 1);
343
+ return {
344
+ config: cpuBudgetFraction === this.config.cpuBudgetFraction ? this.config : { ...this.config, cpuBudgetFraction },
345
+ maxHeavySteps: lowestLimit(overrides?.maxHeavySteps ?? null, this.config.maxHeavyStepsCeiling ?? null),
346
+ signals: this.readSignals(),
347
+ logicalCpus: this.logicalCpus(),
348
+ };
349
+ }
350
+ /**
351
+ * The host test slot count for this admission pass: the configured count, lowered while
352
+ * other work on the host needs the machine (host-load-capacity.ts), and never above the
353
+ * lowest count another governor on this state root has published. The controller folds in
354
+ * every sample it has not seen, each judged with the holders of the passes around it, and it
355
+ * is fed while this governor holds slots or has lowered its count (armLiveFeed), so its
356
+ * streaks follow the sampler's clock, not how often steps happen to queue.
357
+ */
358
+ testSlotsInForce(tokens, published) {
359
+ if (!this.liveTestSlots)
360
+ return { slots: this.config.testSlots, detail: "" };
361
+ this.observeIdleOwnMemory(tokens);
362
+ const taken = this.liveTestSlots.readingsTaken;
363
+ const own = this.liveTestSlots.observe(hostLiveReadings({
364
+ load: this.options.load,
365
+ logicalCpus: this.config.hostCapacity?.logicalCpus ?? this.logicalCpus(),
366
+ sampleStaleMs: this.config.sampleStaleMs,
367
+ nowMs: this.options.now?.() ?? Date.now(),
368
+ idleOwnMemoryBytes: this.idleOwnMemoryBytes,
369
+ }), slotHolders(tokens));
370
+ this.liveTestSlotsBoard?.publish(own, this.config.testSlots, this.liveTestSlots.readingsTaken > taken);
371
+ this.lastLiveTestSlots = published && published.slots < own.slots ? published : own;
372
+ this.armLiveFeed();
373
+ return this.lastLiveTestSlots;
374
+ }
375
+ /** The lowest count other governors have published; null without live adjustment or when none is lowered. */
376
+ async publishedTestSlots() {
377
+ return await this.liveTestSlotsBoard?.lowest().catch(() => null) ?? null;
378
+ }
379
+ /** Stops the live slot feed (tests, shutdown); the next pass that needs it arms it again. */
380
+ stopLiveFeed() {
381
+ if (this.liveFeedTimer)
382
+ clearInterval(this.liveFeedTimer);
383
+ this.liveFeedTimer = null;
384
+ }
385
+ /**
386
+ * While this governor holds a slot or its count is lowered, the controller is fed on the
387
+ * sampler's interval even when nothing waits: readings are then judged with the holders of
388
+ * their own time, and a lowered count can grow back (and its published file stay fresh).
389
+ * Waiters' admission passes feed it already.
390
+ */
391
+ armLiveFeed() {
392
+ if (!this.liveTestSlots || this.liveFeedTimer)
393
+ return;
394
+ if (this.held.size === 0 && !this.liveTestSlots.lowered)
395
+ return;
396
+ this.liveFeedTimer = setInterval(() => {
397
+ if (this.held.size === 0 && !this.liveTestSlots?.lowered) {
398
+ this.stopLiveFeed();
399
+ return;
400
+ }
401
+ if (this.waiters.length === 0)
402
+ void this.refreshTestSlots().catch(() => undefined);
403
+ }, this.config.sampleIntervalMs);
404
+ this.liveFeedTimer.unref?.();
405
+ }
406
+ /**
407
+ * The bridge's own cgroup anonymous memory in the latest sample (dedicated cgroup only), and,
408
+ * with no token on the host, its idle baseline: what Forge's steps use is measured above it.
409
+ */
410
+ observeIdleOwnMemory(tokens) {
411
+ const snapshot = this.options.load.current();
412
+ const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
413
+ if (tokens.length === 0 && ownMemory !== null)
414
+ this.idleOwnMemoryBytes = ownMemory;
415
+ return ownMemory;
416
+ }
417
+ /** The host test slot first (decision 0018), then the budget when it is on. */
418
+ decide(waiter, transaction, budget, runningMemoryBytes, testSlots) {
419
+ const slot = waiter.ticket
420
+ ? decideHostTestSlot({
421
+ ticket: waiter.ticket,
422
+ queue: transaction.queue,
423
+ tokens: transaction.tokens,
424
+ testSlots: testSlots.slots,
425
+ testSlotsDetail: testSlots.detail,
426
+ nowMs: this.options.now?.() ?? Date.now(),
427
+ antiStarvationMs: this.config.antiStarvationMs,
428
+ })
429
+ : null;
430
+ const decision = slot && !slot.admitted ? slot : budget
431
+ ? decideHostLoadAdmission({
432
+ request: waiter.request.cost,
433
+ running: transaction.tokens.map(token => token.cost),
434
+ runningMemoryBytes,
435
+ logicalCpus: budget.logicalCpus,
436
+ signals: budget.signals,
437
+ config: budget.config,
438
+ maxHeavySteps: budget.maxHeavySteps,
439
+ })
440
+ : slot ?? slotFreeDecision;
441
+ if (!transaction.recoveringUntil)
442
+ return decision;
443
+ return {
444
+ ...decision,
445
+ admitted: false,
446
+ progressing: false,
447
+ reason: "ledger_recovering",
448
+ detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
449
+ };
450
+ }
451
+ readSignals() {
452
+ const snapshot = this.options.load.current();
453
+ const cpu = snapshot?.systemPressure?.cpu?.some;
454
+ const sampledAtMs = snapshot ? Date.parse(snapshot.sampledAt) : Number.NaN;
455
+ const now = this.options.now?.() ?? Date.now();
456
+ if (!snapshot?.psiAvailable || !cpu || !Number.isFinite(sampledAtMs) || now - sampledAtMs > this.config.sampleStaleMs) {
457
+ return null;
458
+ }
459
+ // Own-cgroup numbers are trusted only for a dedicated cgroup (step 1's ownCgroupDedicated).
460
+ const attribution = snapshot.ownCgroupDedicated ? this.options.load.cpuAttribution?.() ?? null : null;
461
+ return {
462
+ cpuSomeAvg10: cpu.avg10,
463
+ cpuPressuredSamples: this.pressureStreak(sampledAtMs, cpu.avg10),
464
+ memoryFullAvg10: snapshot.systemPressure?.memory?.full?.avg10 ?? null,
465
+ memoryAvailableBytes: tighterMemory(snapshot.memoryAvailableBytes, this.options.load.cgroupMemoryHeadroomBytes?.() ?? null),
466
+ externalCpuCores: attribution?.sampledAt === snapshot.sampledAt ? attribution.externalCoresInUse : null,
467
+ };
468
+ }
469
+ /**
470
+ * Consecutive pressured samples ending with the latest one, read from the
471
+ * sampler's history so samples taken while nothing waited still count. A gap
472
+ * in sampling (sampler stopped, host suspended) breaks the streak.
473
+ */
474
+ pressureStreak(latestAtMs, latestAvg10) {
475
+ if (latestAvg10 < this.config.cpuPressureThreshold)
476
+ return 0;
477
+ let streak = 1;
478
+ let laterAtMs = latestAtMs;
479
+ const history = this.options.load.recent();
480
+ for (let index = history.length - 1; index >= 0 && streak < this.config.backpressureSamples; index -= 1) {
481
+ const sample = history[index];
482
+ const atMs = Date.parse(sample.sampledAt);
483
+ if (!Number.isFinite(atMs) || atMs >= laterAtMs)
484
+ continue;
485
+ if (laterAtMs - atMs > this.config.sampleIntervalMs * 1.5)
486
+ break;
487
+ const avg10 = sample.psiAvailable ? sample.systemPressure?.cpu?.some?.avg10 : undefined;
488
+ if (avg10 === undefined || avg10 < this.config.cpuPressureThreshold)
489
+ break;
490
+ streak += 1;
491
+ laterAtMs = atMs;
492
+ }
493
+ return streak;
494
+ }
495
+ /**
496
+ * Memory the running steps already use, which MemAvailable already reflects,
497
+ * so the budget does not count it twice. Measured from the dedicated cgroup
498
+ * above its idle baseline; without one, a step admitted longer than the ramp
499
+ * window ago is assumed to hold its reservation. Never above the reservations.
500
+ */
501
+ runningStepsMemoryBytes(tokens) {
502
+ const ownMemory = this.observeIdleOwnMemory(tokens);
503
+ if (tokens.length === 0)
504
+ return 0;
505
+ const reserved = tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
506
+ if (ownMemory !== null && this.idleOwnMemoryBytes !== null) {
507
+ return Math.min(reserved, Math.max(0, ownMemory - this.idleOwnMemoryBytes));
508
+ }
509
+ const now = this.options.now?.() ?? Date.now();
510
+ return tokens
511
+ .filter(token => now - Date.parse(token.admittedAt) >= this.config.memoryRampMs)
512
+ .reduce((sum, token) => sum + token.cost.memoryBytes, 0);
513
+ }
514
+ logicalCpus() {
515
+ const reported = this.options.load.facts()?.logicalThreads;
516
+ if (reported && reported > 0)
517
+ return reported;
518
+ return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
519
+ }
520
+ /**
521
+ * Waiting behind healthy holders of the host test slot is progress: their steps run, and the slot passes
522
+ * down the queue as they finish. Any other wait (a holder past its lease or whose owner is gone, the
523
+ * budget, a recovering ledger) counts toward maxWaitMs from the last time the queue made progress.
524
+ */
525
+ checkStalled(waiter, decision) {
526
+ if (waiter.settled)
527
+ return;
528
+ const nowMs = monotonicNowMs();
529
+ if (decision.reason === "host_test_slot" && decision.progressing === true) {
530
+ waiter.progressAtMs = nowMs;
531
+ return;
532
+ }
533
+ if (nowMs - waiter.progressAtMs < this.config.maxWaitMs)
534
+ return;
535
+ this.timeOut(waiter, `${decision.detail} The queue made no progress for ${minutes(nowMs - waiter.progressAtMs)}.`);
536
+ }
537
+ timeOut(waiter, detail) {
538
+ this.settle(waiter, () => waiter.reject(new HostCapacityTimeoutError(waiter.request.stepClass, waiter.request.label, monotonicNowMs() - waiter.enqueuedAtMs, detail)));
539
+ }
540
+ /**
541
+ * Wait reports run one at a time, in order, so a slow report (a dispatch event, a checkpoint) can
542
+ * never land after a newer one. A report still queued when the step is admitted or fails is
543
+ * dropped: it would be stale.
544
+ */
545
+ notifyWaiting(waiter, decision) {
546
+ waiter.notified = waiter.notified
547
+ .then(async () => { if (!waiter.settled)
548
+ await waiter.onWaiting?.(decision); })
549
+ .catch(() => undefined);
550
+ }
551
+ settle(waiter, complete) {
552
+ if (waiter.settled)
553
+ return;
554
+ waiter.settled = true;
555
+ if (waiter.deadline)
556
+ clearTimeout(waiter.deadline);
557
+ waiter.signal?.removeEventListener("abort", waiter.abort);
558
+ const index = this.waiters.indexOf(waiter);
559
+ if (index >= 0)
560
+ this.waiters.splice(index, 1);
561
+ if (this.waiters.length === 0)
562
+ this.disarmRecheck();
563
+ // A waiter that left without admission gives up its place now, not when its ticket lapses.
564
+ if (waiter.ticket)
565
+ void this.ledger.transaction(() => undefined).then(outcome => this.applyHeldOutcome(outcome), () => undefined);
566
+ waiter.ticket = null;
567
+ // The admission or failure lands after a wait report already in flight, never before it; the bound
568
+ // keeps a stuck report from holding the step back.
569
+ void afterNotified(waiter.notified, waitReportDrainMs).then(complete);
570
+ }
571
+ /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
572
+ applyHeldOutcome(outcome) {
573
+ const nowMs = monotonicNowMs();
574
+ for (const token of outcome.renewed) {
575
+ const entry = this.held.get(token.tokenId);
576
+ if (entry?.token.fencingToken === token.fencingToken)
577
+ entry.renewedAtMs = nowMs;
578
+ }
579
+ for (const token of outcome.fenced) {
580
+ const entry = this.held.get(token.tokenId);
581
+ if (!entry || entry.token.fencingToken !== token.fencingToken)
582
+ continue;
583
+ entry.fencedError ??= new HostCapacityTokenFencedError(token.tokenId, "renew");
584
+ this.lose(entry, entry.fencedError);
585
+ }
586
+ }
587
+ /** The step must stop: its reservation is no longer guaranteed. */
588
+ lose(entry, reason) {
589
+ if (entry.gone || entry.releasing || entry.fencedController.signal.aborted)
590
+ return;
591
+ entry.fencedController.abort(reason);
592
+ }
593
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
594
+ failWaiters(error) {
595
+ const failure = error instanceof HostCapacityLedgerUnavailableError
596
+ ? error
597
+ : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
598
+ for (const waiter of [...this.waiters])
599
+ this.settle(waiter, () => waiter.reject(failure));
600
+ }
601
+ async attachProcess(entry, stepProcess) {
602
+ if (entry.fencedError)
603
+ throw entry.fencedError;
604
+ if (entry.gone || entry.releasing)
605
+ return;
606
+ const outcome = await this.ledger.transaction(transaction => transaction.attach(entry.token.tokenId, entry.token.fencingToken, stepProcess));
607
+ this.applyHeldOutcome(outcome);
608
+ if (outcome.result)
609
+ entry.token = outcome.result;
610
+ else
611
+ throw entry.fencedError ?? new HostCapacityTokenFencedError(entry.token.tokenId, "renew");
612
+ }
613
+ /**
614
+ * Returns a step's token. It stays held (and renewed) until the ledger takes
615
+ * it back, so a ledger outage cannot leave it to lapse into a fenced
616
+ * reservation; the renewal timer retries the release. A fenced token is
617
+ * removed too (its step is over) and the release reports the fence.
618
+ */
619
+ async releaseHeld(entry) {
620
+ if (entry.gone)
621
+ return;
622
+ entry.releasing = true;
623
+ entry.releaseInFlight ??= (async () => {
624
+ try {
625
+ await this.ledger.release(entry.token.tokenId, entry.token.fencingToken);
626
+ this.forget(entry);
627
+ }
628
+ catch (error) {
629
+ if (error instanceof HostCapacityTokenFencedError)
630
+ this.forget(entry);
631
+ throw error;
632
+ }
633
+ finally {
634
+ entry.releaseInFlight = null;
635
+ void this.drain();
636
+ }
637
+ })();
638
+ return await entry.releaseInFlight;
639
+ }
640
+ forget(entry) {
641
+ entry.gone = true;
642
+ this.held.delete(entry.token.tokenId);
643
+ if (this.held.size === 0)
644
+ this.disarmRenewal();
645
+ }
646
+ armRecheck() {
647
+ if (this.recheckTimer)
648
+ return;
649
+ // Capacity can return without a local release: another process's token, a
650
+ // new pressure sample, or external load ending.
651
+ this.recheckTimer = setInterval(() => void this.drain(), this.config.recheckIntervalMs);
652
+ this.recheckTimer.unref?.();
653
+ }
654
+ disarmRecheck() {
655
+ if (this.recheckTimer)
656
+ clearInterval(this.recheckTimer);
657
+ this.recheckTimer = null;
658
+ }
659
+ armRenewal() {
660
+ this.armLiveFeed();
661
+ if (this.renewTimer)
662
+ return;
663
+ this.renewTimer = setInterval(() => void this.renewHeld(), Math.max(10, Math.floor(this.config.leaseMs / 4)));
664
+ this.renewTimer.unref?.();
665
+ }
666
+ disarmRenewal() {
667
+ if (this.renewTimer)
668
+ clearInterval(this.renewTimer);
669
+ this.renewTimer = null;
670
+ }
671
+ /**
672
+ * The step ended but part of its process tree may still run: its token stays
673
+ * held and renewed, with its cost, and the step's own termination check is
674
+ * retried on every renewal tick until it proves the tree gone.
675
+ */
676
+ retainUntilStopped(entry, stillGone, reason) {
677
+ if (entry.gone || entry.releasing)
678
+ return;
679
+ this.lose(entry, reason);
680
+ const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
681
+ entry.retainedUntil = stillGone
682
+ // The tree recorded on the token (supervised builds, installs) is stopped and checked.
683
+ ?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
684
+ this.armRenewal();
685
+ // Recorded in the ledger so the attempt's own next steps, in any process, do not
686
+ // wait for the slot this token keeps until the step's remains are gone.
687
+ void this.ledger.transaction(transaction => transaction.retain(entry.token.tokenId, entry.token.fencingToken))
688
+ .then(outcome => {
689
+ // Kept on the held entry too: a ledger rebuilt from held tokens must not lose the marker.
690
+ if (outcome.result)
691
+ entry.token = outcome.result;
692
+ this.applyHeldOutcome(outcome);
693
+ void this.drain();
694
+ })
695
+ .catch(() => undefined);
696
+ }
697
+ /**
698
+ * Attempt teardown stopped the attempt's processes (its process supervisor
699
+ * proved them gone): tokens kept for a tree nothing else can check are returned.
700
+ */
701
+ async releaseRetainedAfterTeardown(dispatchAttemptId) {
702
+ if (!this.enabled)
703
+ return;
704
+ const settled = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId && entry.retainedUntil === "attempt_teardown");
705
+ for (const entry of settled)
706
+ entry.retainedUntil = null;
707
+ await Promise.allSettled(settled.map(entry => this.releaseHeld(entry)));
708
+ }
709
+ checkRetained(entry) {
710
+ if (!entry.retainedUntil || entry.retainedUntil === "attempt_teardown" || entry.retainCheck)
711
+ return;
712
+ const stillGone = entry.retainedUntil;
713
+ entry.retainCheck = (async () => {
714
+ try {
715
+ if (await stillGone().catch(() => false)) {
716
+ entry.retainedUntil = null;
717
+ await this.releaseHeld(entry).catch(() => undefined);
718
+ }
719
+ }
720
+ finally {
721
+ entry.retainCheck = null;
722
+ }
723
+ })();
724
+ }
725
+ async renewHeld() {
726
+ if (this.held.size === 0)
727
+ return;
728
+ for (const entry of this.held.values()) {
729
+ // A release the ledger could not take is retried until it lands.
730
+ if (entry.releasing && !entry.releaseInFlight)
731
+ void this.releaseHeld(entry).catch(() => undefined);
732
+ this.checkRetained(entry);
733
+ }
734
+ try {
735
+ // The ledger renews every held token at the start of each transaction and
736
+ // reports the fenced ones.
737
+ this.applyHeldOutcome(await this.ledger.transaction(() => undefined));
738
+ }
739
+ catch (error) {
740
+ // A brief outage is retried on the next tick. Once a whole lease passes
741
+ // without a renewal, another process may already have fenced the token.
742
+ const nowMs = monotonicNowMs();
743
+ for (const entry of this.held.values()) {
744
+ if (nowMs - entry.renewedAtMs < this.config.leaseMs)
745
+ continue;
746
+ this.lose(entry, error instanceof HostCapacityLedgerUnavailableError
747
+ ? error
748
+ : new HostCapacityLedgerUnavailableError("the host load token could not be renewed.", { cause: error }));
749
+ }
750
+ }
751
+ }
752
+ }
753
+ /** Heavy steps holding a host test slot, in every process on the host. */
754
+ function slotHolders(tokens) {
755
+ return tokens.filter(token => takesHostTestSlot(token.stepClass)).length;
756
+ }
757
+ /** The cgroup limit's headroom when one is set, never above host MemAvailable. */
758
+ function tighterMemory(hostAvailable, cgroupHeadroom) {
759
+ if (cgroupHeadroom === null)
760
+ return hostAvailable;
761
+ return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
762
+ }
763
+ /** Whole minutes for messages (at least 1); sub-minute limits only occur in tests and tuning. */
764
+ function minutes(ms) {
765
+ const whole = Math.max(1, Math.round(ms / 60_000));
766
+ return whole === 1 ? "1 minute" : `${whole} minutes`;
767
+ }
768
+ /**
769
+ * Whether a waiting step should be told about this decision: its first wait, a new reason, or a
770
+ * host test slot wait whose holders or place in the queue moved. Budget and pressure details carry
771
+ * live load figures that change on every recheck, so only their reason counts.
772
+ */
773
+ export function waitChanged(previous, next) {
774
+ if (previous === null || previous.reason !== next.reason)
775
+ return true;
776
+ return next.reason === "host_test_slot" && previous.detail !== next.detail;
777
+ }
778
+ /** The longest a step's admission or failure waits for its in-flight wait report. */
779
+ const waitReportDrainMs = 5_000;
780
+ /** Resolves once `notified` settles, or after `capMs` at the latest. */
781
+ export async function afterNotified(notified, capMs = waitReportDrainMs) {
782
+ let timer;
783
+ const cap = new Promise(resolve => {
784
+ timer = setTimeout(resolve, capMs);
785
+ timer.unref?.();
786
+ });
787
+ try {
788
+ await Promise.race([notified, cap]);
789
+ }
790
+ finally {
791
+ clearTimeout(timer);
792
+ }
793
+ }
794
+ function abortError(signal) {
795
+ if (signal.reason instanceof Error)
796
+ return signal.reason;
797
+ const error = new Error(typeof signal.reason === "string" ? signal.reason : "The host capacity wait was cancelled.");
798
+ error.name = "AbortError";
799
+ return error;
800
+ }
801
+ /** The lower of two optional limits; null when neither is set. */
802
+ function lowestLimit(a, b) {
803
+ if (a === null)
804
+ return b;
805
+ if (b === null)
806
+ return a;
807
+ return Math.min(a, b);
808
+ }
809
+ const slotFreeDecision = {
810
+ admitted: true,
811
+ reason: "admitted",
812
+ cpuBudgetCores: null,
813
+ memoryBudgetBytes: null,
814
+ reservedCpuCores: 0,
815
+ reservedMemoryBytes: 0,
816
+ detail: "The step takes no host test slot and the host budget is off.",
817
+ };
818
+ /** Admits a slot-free step at once, without a ledger token: nothing would count it. */
819
+ function slotFreeAdmission(request) {
820
+ return {
821
+ tokenId: `slot-free-${randomUUID()}`,
822
+ fencingToken: 0,
823
+ stepClass: request.stepClass,
824
+ waitMs: 0,
825
+ decision: slotFreeDecision,
826
+ fenced: new AbortController().signal,
827
+ attachProcess: async () => undefined,
828
+ release: async () => undefined,
829
+ retainUntilStopped: () => undefined,
830
+ };
831
+ }