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

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,69 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ /** Who holds the ledger lock; liveness is judged by the ledger's owner rules. */
3
+ export interface HostLoadLockHolder {
4
+ readonly pid: number;
5
+ readonly processInstanceId: string;
6
+ readonly processIdentity: string | null;
7
+ }
8
+ export interface HostLoadLedgerLockOptions {
9
+ readonly lockPath: string;
10
+ readonly holder: () => HostLoadLockHolder;
11
+ readonly isLive: (holder: HostLoadLockHolder) => boolean;
12
+ readonly timeoutMs: number;
13
+ /** A lock with no readable holder is broken only after this age. */
14
+ readonly unreadableStaleAfterMs?: number;
15
+ /** Test seam: runs after a lock was judged stale and before it is broken. */
16
+ readonly beforeStaleBreak?: () => Promise<void>;
17
+ }
18
+ export declare class HostCapacityLedgerUnavailableError extends ForgeFailureError {
19
+ readonly code = "host_capacity_ledger_unavailable";
20
+ constructor(detail: string, options?: ErrorOptions);
21
+ }
22
+ /**
23
+ * Cross-process exclusive lock file for the host load ledger.
24
+ *
25
+ * Every lock file, and every break lock, is claimed with a complete
26
+ * `{ token, holder }` record: written to a private temporary file and
27
+ * hard-linked into place, which fails if the path exists. No path is ever
28
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
29
+ *
30
+ * A lock is broken only when its holder is provably dead (or it has no readable
31
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
32
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
33
+ * A breaker claims the first link it can; it moves on to the next only when the
34
+ * holder of the current one is dead, and never removes it. Under its link it
35
+ * re-judges the lock and unlinks it only if the path still holds that same stale
36
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
37
+ * it exists nobody can create a new lock; so at most one live breaker can ever
38
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
39
+ */
40
+ export declare class HostLoadLedgerLock {
41
+ private readonly options;
42
+ constructor(options: HostLoadLedgerLockOptions);
43
+ acquire(): Promise<string>;
44
+ /**
45
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
46
+ * EEXIST. `link` never replaces an existing path, and the record is fully
47
+ * written before the path appears.
48
+ */
49
+ private claim;
50
+ /** True while `token` still owns the lock file. */
51
+ holds(token: string): Promise<boolean>;
52
+ release(token: string): Promise<void>;
53
+ private breakIfStale;
54
+ /**
55
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
56
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
57
+ * there is none, or null if it is live or too young to judge.
58
+ */
59
+ private judgeStale;
60
+ /**
61
+ * Claims the next free link of the stale lock's break chain, held only for the
62
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
63
+ * live means another breaker is on it; a dead holder's link is skipped, never
64
+ * removed or replaced.
65
+ */
66
+ private acquireBreaker;
67
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
68
+ private releaseOwn;
69
+ }
@@ -0,0 +1,187 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import { ForgeFailureError } from "../session/session.types.js";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
5
+ export class HostCapacityLedgerUnavailableError extends ForgeFailureError {
6
+ code = "host_capacity_ledger_unavailable";
7
+ constructor(detail, options) {
8
+ super("host_capacity_ledger_unavailable", `host_capacity_ledger_unavailable: ${detail}`, "bridge", options);
9
+ this.name = "HostCapacityLedgerUnavailableError";
10
+ }
11
+ }
12
+ /**
13
+ * Cross-process exclusive lock file for the host load ledger.
14
+ *
15
+ * Every lock file, and every break lock, is claimed with a complete
16
+ * `{ token, holder }` record: written to a private temporary file and
17
+ * hard-linked into place, which fails if the path exists. No path is ever
18
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
19
+ *
20
+ * A lock is broken only when its holder is provably dead (or it has no readable
21
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
22
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
23
+ * A breaker claims the first link it can; it moves on to the next only when the
24
+ * holder of the current one is dead, and never removes it. Under its link it
25
+ * re-judges the lock and unlinks it only if the path still holds that same stale
26
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
27
+ * it exists nobody can create a new lock; so at most one live breaker can ever
28
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
29
+ */
30
+ export class HostLoadLedgerLock {
31
+ options;
32
+ constructor(options) {
33
+ this.options = options;
34
+ }
35
+ async acquire() {
36
+ const token = randomUUID();
37
+ const started = Date.now();
38
+ for (;;) {
39
+ try {
40
+ await this.claim(this.options.lockPath, token);
41
+ return token;
42
+ }
43
+ catch (error) {
44
+ if (error.code !== "EEXIST")
45
+ throw error;
46
+ if (await this.breakIfStale())
47
+ continue;
48
+ if (Date.now() - started >= this.options.timeoutMs) {
49
+ throw new HostCapacityLedgerUnavailableError("the host load ledger lock could not be acquired.", { cause: error });
50
+ }
51
+ await new Promise(resolve => setTimeout(resolve, 10));
52
+ }
53
+ }
54
+ }
55
+ /**
56
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
57
+ * EEXIST. `link` never replaces an existing path, and the record is fully
58
+ * written before the path appears.
59
+ */
60
+ async claim(target, token) {
61
+ const temporary = `${target}.${randomUUID()}.claim`;
62
+ try {
63
+ const handle = await fs.open(temporary, "wx", 0o600);
64
+ try {
65
+ await handle.writeFile(JSON.stringify({ token, holder: this.options.holder() }));
66
+ }
67
+ finally {
68
+ await handle.close();
69
+ }
70
+ await fs.link(temporary, target);
71
+ }
72
+ finally {
73
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
74
+ }
75
+ }
76
+ /** True while `token` still owns the lock file. */
77
+ async holds(token) {
78
+ return (await readLock(this.options.lockPath))?.token === token;
79
+ }
80
+ async release(token) {
81
+ // Only a breaker removes a lock it did not take, and only a stale one: a live
82
+ // holder's file cannot change between this check and the removal.
83
+ if (await this.holds(token))
84
+ await fs.rm(this.options.lockPath, { force: true });
85
+ }
86
+ async breakIfStale() {
87
+ const observed = await this.judgeStale(this.options.lockPath);
88
+ if (observed === "absent")
89
+ return true;
90
+ if (!observed)
91
+ return false;
92
+ await this.options.beforeStaleBreak?.();
93
+ const breaker = await this.acquireBreaker(observed.identity);
94
+ if (!breaker)
95
+ return false;
96
+ let broken = false;
97
+ try {
98
+ // Re-judged under the break lock: the path must still hold the same stale lock.
99
+ const current = await this.judgeStale(this.options.lockPath);
100
+ if (current === "absent")
101
+ return true;
102
+ if (!current || current.identity !== observed.identity)
103
+ return false;
104
+ await fs.unlink(this.options.lockPath).catch(error => {
105
+ if (error.code !== "ENOENT")
106
+ throw error;
107
+ });
108
+ broken = true;
109
+ return true;
110
+ }
111
+ finally {
112
+ // Once the stale lock is gone its chain is never needed again: dead breakers'
113
+ // links are cleared too. Otherwise only this breaker's own link is returned.
114
+ const links = broken ? breaker.chain : [breaker.path];
115
+ await Promise.all(links.map(link => this.releaseOwn(link, broken ? null : breaker.token)));
116
+ }
117
+ }
118
+ /**
119
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
120
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
121
+ * there is none, or null if it is live or too young to judge.
122
+ */
123
+ async judgeStale(lockPath) {
124
+ // Exact (bigint) stats: a rounded Windows file id could name a different lock file.
125
+ const stat = await fs.lstat(lockPath, { bigint: true }).catch(() => null);
126
+ if (!stat)
127
+ return "absent";
128
+ const observed = stat.isFile() && stat.size <= 16n * 1024n ? await readLock(lockPath) : null;
129
+ if (observed?.holder && validHolder(observed.holder) && typeof observed.token === "string") {
130
+ // A live holder keeps its lock however old it is.
131
+ if (this.options.isLive(observed.holder))
132
+ return null;
133
+ return { identity: `t-${observed.token}` };
134
+ }
135
+ // Unreadable (claims are atomic, so this is corruption): give it until the stale age.
136
+ if (Date.now() - Number(stat.mtimeMs) < (this.options.unreadableStaleAfterMs ?? 30_000))
137
+ return null;
138
+ return { identity: `i-${fileIdentityKey(stat).replace(":", "-")}-${stat.mtimeNs}-${stat.size}` };
139
+ }
140
+ /**
141
+ * Claims the next free link of the stale lock's break chain, held only for the
142
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
143
+ * live means another breaker is on it; a dead holder's link is skipped, never
144
+ * removed or replaced.
145
+ */
146
+ async acquireBreaker(identity) {
147
+ const base = `${this.options.lockPath}.break-${identity.replace(/[^A-Za-z0-9-]/gu, "_")}`;
148
+ const token = randomUUID();
149
+ const chain = [];
150
+ for (let generation = 1; generation <= maximumBreakGenerations; generation += 1) {
151
+ const link = `${base}.${generation}`;
152
+ chain.push(link);
153
+ try {
154
+ await this.claim(link, token);
155
+ return { path: link, token, chain };
156
+ }
157
+ catch (error) {
158
+ if (error.code !== "EEXIST")
159
+ throw error;
160
+ }
161
+ const holder = await this.judgeStale(link);
162
+ // Live (or just written): another breaker is on it. Gone: retry from the start later.
163
+ if (holder === null || holder === "absent")
164
+ return null;
165
+ }
166
+ return null;
167
+ }
168
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
169
+ async releaseOwn(link, token) {
170
+ if (token === null || (await readLock(link))?.token === token)
171
+ await fs.rm(link, { force: true }).catch(() => undefined);
172
+ }
173
+ }
174
+ /** A chain longer than this means breakers keep dying; the acquire times out instead. */
175
+ const maximumBreakGenerations = 16;
176
+ async function readLock(lockPath) {
177
+ return await fs.readFile(lockPath, "utf8")
178
+ .then(value => JSON.parse(value))
179
+ .catch(() => null);
180
+ }
181
+ function validHolder(value) {
182
+ const holder = value;
183
+ return Boolean(holder)
184
+ && Number.isSafeInteger(holder.pid) && holder.pid > 0
185
+ && typeof holder.processInstanceId === "string"
186
+ && (holder.processIdentity === null || typeof holder.processIdentity === "string");
187
+ }
@@ -0,0 +1,61 @@
1
+ import { type HostLiveReading, type HostLiveTestSlots } from "./host-load-capacity.js";
2
+ import type { HostLoadGovernorSource } from "./host-load-sampler.js";
3
+ import { type HostLoadOwnerLiveness } from "./host-load-token-ledger.js";
4
+ /** What hostLiveReadings reads the sampler's history with. */
5
+ export interface HostLiveReadingContext {
6
+ readonly load: HostLoadGovernorSource;
7
+ /** Every CPU on the host: hostCpuPercent's denominator. */
8
+ readonly logicalCpus: number;
9
+ readonly sampleStaleMs: number;
10
+ /** Wall clock, for the staleness of the latest sample. */
11
+ readonly nowMs: number;
12
+ /** The bridge cgroup's anonymous memory with no heavy step running; null when unknown. */
13
+ readonly idleOwnMemoryBytes: number | null;
14
+ }
15
+ /** The sampler's fresh history as host readings; a stale history adds nothing. */
16
+ export declare function hostLiveReadings(context: HostLiveReadingContext): HostLiveReading[];
17
+ export declare function liveTestSlotsDirectory(stateRoot: string): string;
18
+ /** A lowered count is rewritten this often while it holds; readers drop one older than the TTL. */
19
+ export declare const liveTestSlotsRefreshMs = 30000;
20
+ export declare const liveTestSlotsTtlMs = 90000;
21
+ /**
22
+ * This governor's lowered count, shared with every governor on the state root, and theirs read
23
+ * back. Each governor writes a file of its own (no two processes write one file); it is
24
+ * written while the count is lowered (when it changes, and every refresh period while the
25
+ * controller takes in fresh readings) and removed once the count is back. A file whose writer
26
+ * stopped refreshing it lapses after the TTL: a writer whose sampler went quiet stops
27
+ * refreshing, so a reduction nothing confirms any more does not hold every governor back.
28
+ * A reader skips a file another host wrote and removes one whose writer is gone. Times are
29
+ * wall-clock: they are compared across processes.
30
+ */
31
+ export declare class LiveTestSlotsBoard {
32
+ private readonly directory;
33
+ private readonly fileName;
34
+ private readonly now;
35
+ private readonly liveness;
36
+ private readonly hostname;
37
+ private published;
38
+ /** When a pass last took in a fresh reading for this governor's count. */
39
+ private freshAtMs;
40
+ private writing;
41
+ constructor(stateRoot: string, options?: LiveTestSlotsBoardOptions);
42
+ /**
43
+ * Publishes this governor's own count (never one it adopted from another). `freshReading` says
44
+ * whether the pass behind it took in a new reading: an unchanged count is rewritten only while
45
+ * one came in within the TTL, so it lapses once the sampler goes quiet.
46
+ */
47
+ publish(own: HostLiveTestSlots, configured: number, freshReading: boolean): void;
48
+ /** The lowest count another governor on this state root has in force; null when none is lowered. */
49
+ lowest(): Promise<HostLiveTestSlots | null>;
50
+ /** Settles once every publish so far is on disk (tests). */
51
+ flushed(): Promise<void>;
52
+ private enqueue;
53
+ }
54
+ export interface LiveTestSlotsBoardOptions {
55
+ /** Wall clock (tests). */
56
+ readonly now?: () => number;
57
+ /** Whether a writer process still runs; the ledger's OS check by default. */
58
+ readonly liveness?: HostLoadOwnerLiveness;
59
+ /** This host's name; os.hostname() by default. */
60
+ readonly hostname?: string;
61
+ }
@@ -0,0 +1,193 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { reportsAvailableMemory } from "./host-load-capacity.js";
6
+ import { currentHostLoadTokenOwner, processHostLoadOwnerLiveness, } from "./host-load-token-ledger.js";
7
+ /** The sampler's fresh history as host readings; a stale history adds nothing. */
8
+ export function hostLiveReadings(context) {
9
+ const { load } = context;
10
+ const latest = load.current();
11
+ const latestAtMs = latest ? Date.parse(latest.sampledAt) : Number.NaN;
12
+ if (!latest || !Number.isFinite(latestAtMs) || context.nowMs - latestAtMs > context.sampleStaleMs)
13
+ return [];
14
+ const history = load.recent();
15
+ const samples = history.at(-1)?.sampledAt === latest.sampledAt ? history : [...history, latest];
16
+ // Each sample's own attribution, which counts Docker sandboxes as Forge's own CPU too.
17
+ const attributions = new Map();
18
+ for (const attribution of load.recentCpuAttributions?.() ?? [])
19
+ attributions.set(attribution.sampledAt, attribution);
20
+ const latestAttribution = load.cpuAttribution?.() ?? null;
21
+ if (latestAttribution)
22
+ attributions.set(latestAttribution.sampledAt, latestAttribution);
23
+ // macOS reports free pages only, which reads most of its memory as in use.
24
+ const memoryReadable = reportsAvailableMemory(load.facts()?.platform ?? process.platform);
25
+ return samples.flatMap(sample => {
26
+ const reading = liveReading(context, sample, attributions.get(sample.sampledAt) ?? null, memoryReadable);
27
+ return reading ? [reading] : [];
28
+ });
29
+ }
30
+ /**
31
+ * One sample as a host reading, stamped with the sampler's monotonic clock when it keeps one.
32
+ * With a dedicated cgroup, Forge's CPU comes from the sample's attribution (bridge and sandbox
33
+ * cgroups); a sample without one is left out rather than read with its sandboxes counted as
34
+ * other work. Forge's memory is the cgroup's anonymous memory above its idle baseline, when both
35
+ * are known.
36
+ */
37
+ function liveReading(context, sample, attribution, memoryReadable) {
38
+ const dedicated = sample.ownCgroupDedicated;
39
+ if (dedicated && !attribution)
40
+ return null;
41
+ const sampledAtMs = context.load.sampleMonotonicMs
42
+ ? context.load.sampleMonotonicMs(sample.sampledAt)
43
+ : Date.parse(sample.sampledAt);
44
+ if (sampledAtMs === null)
45
+ return null;
46
+ const ownMemory = dedicated ? sample.ownCgroup?.memoryAnonBytes ?? null : null;
47
+ return {
48
+ sampledAtMs,
49
+ hostCoresInUse: sample.hostCpuPercent === null ? null : (sample.hostCpuPercent / 100) * context.logicalCpus,
50
+ externalCoresInUse: dedicated ? attribution?.externalCoresInUse ?? null : null,
51
+ memoryAvailableBytes: memoryReadable ? sample.memoryAvailableBytes : null,
52
+ forgeMemoryBytes: ownMemory === null || context.idleOwnMemoryBytes === null
53
+ ? null
54
+ : Math.max(0, ownMemory - context.idleOwnMemoryBytes),
55
+ };
56
+ }
57
+ export function liveTestSlotsDirectory(stateRoot) {
58
+ return path.join(stateRoot, "host-load-governor", "live-test-slots");
59
+ }
60
+ /** A lowered count is rewritten this often while it holds; readers drop one older than the TTL. */
61
+ export const liveTestSlotsRefreshMs = 30_000;
62
+ export const liveTestSlotsTtlMs = 90_000;
63
+ /** A file this old belongs to a governor that is gone: any reader removes it. */
64
+ const abandonedMs = 10 * 60_000;
65
+ /** The most published counts read in one pass. */
66
+ const maximumEntries = 64;
67
+ /**
68
+ * This governor's lowered count, shared with every governor on the state root, and theirs read
69
+ * back. Each governor writes a file of its own (no two processes write one file); it is
70
+ * written while the count is lowered (when it changes, and every refresh period while the
71
+ * controller takes in fresh readings) and removed once the count is back. A file whose writer
72
+ * stopped refreshing it lapses after the TTL: a writer whose sampler went quiet stops
73
+ * refreshing, so a reduction nothing confirms any more does not hold every governor back.
74
+ * A reader skips a file another host wrote and removes one whose writer is gone. Times are
75
+ * wall-clock: they are compared across processes.
76
+ */
77
+ export class LiveTestSlotsBoard {
78
+ directory;
79
+ fileName = `${randomUUID()}.json`;
80
+ now;
81
+ liveness;
82
+ hostname;
83
+ published = null;
84
+ /** When a pass last took in a fresh reading for this governor's count. */
85
+ freshAtMs = null;
86
+ writing = Promise.resolve();
87
+ constructor(stateRoot, options = {}) {
88
+ this.directory = liveTestSlotsDirectory(stateRoot);
89
+ this.now = options.now ?? Date.now;
90
+ this.liveness = options.liveness ?? processHostLoadOwnerLiveness;
91
+ this.hostname = options.hostname ?? os.hostname();
92
+ }
93
+ /**
94
+ * Publishes this governor's own count (never one it adopted from another). `freshReading` says
95
+ * whether the pass behind it took in a new reading: an unchanged count is rewritten only while
96
+ * one came in within the TTL, so it lapses once the sampler goes quiet.
97
+ */
98
+ publish(own, configured, freshReading) {
99
+ const nowMs = this.now();
100
+ if (freshReading)
101
+ this.freshAtMs = nowMs;
102
+ const filePath = path.join(this.directory, this.fileName);
103
+ if (own.slots >= configured) {
104
+ if (this.published === null)
105
+ return;
106
+ this.published = null;
107
+ this.enqueue(async () => await fs.rm(filePath, { force: true }));
108
+ return;
109
+ }
110
+ const previous = this.published;
111
+ if (previous?.slots === own.slots && previous.detail === own.detail) {
112
+ const confirmed = this.freshAtMs !== null && nowMs - this.freshAtMs <= liveTestSlotsTtlMs;
113
+ if (!confirmed || nowMs - previous.atMs < liveTestSlotsRefreshMs)
114
+ return;
115
+ }
116
+ this.published = { slots: own.slots, detail: own.detail, atMs: nowMs };
117
+ const entry = {
118
+ schemaVersion: 1,
119
+ writer: currentHostLoadTokenOwner(),
120
+ hostname: this.hostname,
121
+ slots: own.slots,
122
+ detail: own.detail,
123
+ writtenAt: new Date(nowMs).toISOString(),
124
+ };
125
+ this.enqueue(async () => {
126
+ await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
127
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
128
+ try {
129
+ await fs.writeFile(temporary, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
130
+ await fs.rename(temporary, filePath);
131
+ }
132
+ catch (error) {
133
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
134
+ throw error;
135
+ }
136
+ });
137
+ }
138
+ /** The lowest count another governor on this state root has in force; null when none is lowered. */
139
+ async lowest() {
140
+ const names = await fs.readdir(this.directory).catch(() => []);
141
+ const nowMs = this.now();
142
+ let lowest = null;
143
+ for (const name of names.filter(entry => entry.endsWith(".json") && entry !== this.fileName).slice(0, maximumEntries)) {
144
+ const filePath = path.join(this.directory, name);
145
+ const entry = await fs.readFile(filePath, "utf8").then(parseEntry).catch(() => null);
146
+ const ageMs = entry ? nowMs - Date.parse(entry.writtenAt) : Number.NaN;
147
+ // Another host's pid cannot be checked here, and its load is not this host's.
148
+ if (entry && entry.hostname !== this.hostname)
149
+ continue;
150
+ const writerGone = entry !== null && !this.liveness.isLive(entry.writer);
151
+ if (ageMs > abandonedMs || writerGone)
152
+ void fs.rm(filePath, { force: true }).catch(() => undefined);
153
+ // A clock stepped far back makes an entry look written in the future: it is not trusted either.
154
+ if (!entry || writerGone || !(Math.abs(ageMs) <= liveTestSlotsTtlMs))
155
+ continue;
156
+ if (!lowest || entry.slots < lowest.slots)
157
+ lowest = { slots: entry.slots, detail: entry.detail };
158
+ }
159
+ return lowest;
160
+ }
161
+ /** Settles once every publish so far is on disk (tests). */
162
+ async flushed() {
163
+ await this.writing;
164
+ }
165
+ enqueue(write) {
166
+ this.writing = this.writing.then(write).catch(() => undefined);
167
+ }
168
+ }
169
+ function parseEntry(content) {
170
+ const raw = JSON.parse(content);
171
+ if (!raw || raw.schemaVersion !== 1 || typeof raw.writtenAt !== "string" || typeof raw.hostname !== "string")
172
+ return null;
173
+ const writer = parseWriter(raw.writer);
174
+ const slots = raw.slots;
175
+ if (!writer || typeof slots !== "number" || !Number.isInteger(slots) || slots < 1)
176
+ return null;
177
+ return {
178
+ schemaVersion: 1,
179
+ writer,
180
+ hostname: raw.hostname,
181
+ slots: Math.min(8, slots),
182
+ detail: typeof raw.detail === "string" ? raw.detail.slice(0, 500) : "",
183
+ writtenAt: raw.writtenAt,
184
+ };
185
+ }
186
+ function parseWriter(raw) {
187
+ if (!raw || typeof raw !== "object")
188
+ return null;
189
+ const { pid, processIdentity, processInstanceId } = raw;
190
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || typeof processInstanceId !== "string")
191
+ return null;
192
+ return { pid, processIdentity: typeof processIdentity === "string" ? processIdentity : null, processInstanceId };
193
+ }
@@ -0,0 +1,25 @@
1
+ export interface HostLoadRuntimeOverrides {
2
+ /** Share of logical CPUs heavy steps may reserve: the CPU budget, or the yield budget while yielding. */
3
+ readonly cpuBudgetFraction: number;
4
+ /** Host-wide count of heavy steps at once; null means the budget alone limits them. */
5
+ readonly maxHeavySteps: number | null;
6
+ /** For diagnostics: whether the budget above is the yield budget. */
7
+ readonly yielding: boolean;
8
+ }
9
+ export declare function hostLoadRuntimeSettingsPath(stateRoot: string): string;
10
+ /** Atomically replaces the overrides every governor on this state root reads. */
11
+ export declare function writeHostLoadRuntimeSettings(stateRoot: string, overrides: HostLoadRuntimeOverrides): Promise<void>;
12
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
13
+ export declare function resetHostLoadRuntimeSettings(stateRoot: string): Promise<void>;
14
+ /**
15
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
16
+ * size, so a governor re-checking its queue every second costs one stat. A
17
+ * missing or unreadable file means no overrides.
18
+ */
19
+ export declare class HostLoadRuntimeSettingsReader {
20
+ private readonly filePath;
21
+ private cachedKey;
22
+ private cached;
23
+ constructor(stateRoot: string);
24
+ read(): Promise<HostLoadRuntimeOverrides | null>;
25
+ }
@@ -0,0 +1,80 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
5
+ export function hostLoadRuntimeSettingsPath(stateRoot) {
6
+ return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
7
+ }
8
+ /** Atomically replaces the overrides every governor on this state root reads. */
9
+ export async function writeHostLoadRuntimeSettings(stateRoot, overrides) {
10
+ const filePath = hostLoadRuntimeSettingsPath(stateRoot);
11
+ const content = {
12
+ schemaVersion: 1,
13
+ cpuBudgetFraction: overrides.cpuBudgetFraction,
14
+ maxHeavySteps: overrides.maxHeavySteps,
15
+ yielding: overrides.yielding,
16
+ writtenAt: new Date().toISOString(),
17
+ writerPid: process.pid,
18
+ };
19
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
20
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
21
+ try {
22
+ await fs.writeFile(temporary, `${JSON.stringify(content)}\n`, { mode: 0o600 });
23
+ await fs.rename(temporary, filePath);
24
+ }
25
+ catch (error) {
26
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
27
+ throw error;
28
+ }
29
+ }
30
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
31
+ export async function resetHostLoadRuntimeSettings(stateRoot) {
32
+ await fs.rm(hostLoadRuntimeSettingsPath(stateRoot), { force: true });
33
+ }
34
+ /**
35
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
36
+ * size, so a governor re-checking its queue every second costs one stat. A
37
+ * missing or unreadable file means no overrides.
38
+ */
39
+ export class HostLoadRuntimeSettingsReader {
40
+ filePath;
41
+ cachedKey = null;
42
+ cached = null;
43
+ constructor(stateRoot) {
44
+ this.filePath = hostLoadRuntimeSettingsPath(stateRoot);
45
+ }
46
+ async read() {
47
+ let key;
48
+ try {
49
+ // Exact (bigint) stats: a replaced file whose rounded Windows id matched would read as unchanged.
50
+ const stat = await fs.stat(this.filePath, { bigint: true });
51
+ key = `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${fileIdentityKey(stat)}`;
52
+ }
53
+ catch {
54
+ this.cachedKey = null;
55
+ this.cached = null;
56
+ return null;
57
+ }
58
+ if (key === this.cachedKey)
59
+ return this.cached;
60
+ const parsed = await fs.readFile(this.filePath, "utf8").then(parseOverrides).catch(() => null);
61
+ this.cachedKey = key;
62
+ this.cached = parsed;
63
+ return parsed;
64
+ }
65
+ }
66
+ function parseOverrides(content) {
67
+ const raw = JSON.parse(content);
68
+ if (!raw || raw.schemaVersion !== 1)
69
+ return null;
70
+ const fraction = raw.cpuBudgetFraction;
71
+ if (typeof fraction !== "number" || !Number.isFinite(fraction))
72
+ return null;
73
+ const steps = raw.maxHeavySteps;
74
+ return {
75
+ // The governor config's own bounds for the budget fraction.
76
+ cpuBudgetFraction: Math.min(1, Math.max(0.05, fraction)),
77
+ maxHeavySteps: typeof steps === "number" && Number.isInteger(steps) && steps >= 1 ? Math.min(64, steps) : null,
78
+ yielding: raw.yielding === true,
79
+ };
80
+ }