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

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