@loucompanion/forge-bridge 0.1.4-dev.bbb61d3d6127 → 0.1.4-dev.bd2cfb6b7438

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 (169) hide show
  1. package/README.md +55 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +71 -2
  8. package/dist/bridge/bridge.service.js +292 -118
  9. package/dist/bridge/bridge.types.d.ts +11 -0
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  13. package/dist/bridge/runner-host-capabilities.js +13 -0
  14. package/dist/cleanup/cleanup.service.d.ts +9 -0
  15. package/dist/cleanup/cleanup.service.js +72 -109
  16. package/dist/cleanup/cleanup.types.d.ts +4 -0
  17. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  18. package/dist/cleanup/forge-owned-paths.js +53 -0
  19. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  20. package/dist/cleanup/host-runtime-ledger.js +109 -0
  21. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  22. package/dist/cleanup/managed-branch-sweep.js +111 -0
  23. package/dist/cli/cli.help.js +18 -0
  24. package/dist/cli/cli.service.d.ts +16 -0
  25. package/dist/cli/cli.service.js +140 -16
  26. package/dist/cli/local-config.d.ts +4 -0
  27. package/dist/cli/local-config.js +26 -4
  28. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  29. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  30. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  31. package/dist/runtime/docker-engine-probe.js +7 -0
  32. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  33. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  34. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  35. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  36. package/dist/runtime/host-facts.d.ts +2 -1
  37. package/dist/runtime/host-load-admission.d.ts +18 -3
  38. package/dist/runtime/host-load-admission.js +19 -4
  39. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  40. package/dist/runtime/host-load-child-environment.js +76 -0
  41. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  42. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  43. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  44. package/dist/runtime/host-load-governor-config.js +37 -0
  45. package/dist/runtime/host-load-governor.d.ts +72 -11
  46. package/dist/runtime/host-load-governor.js +284 -67
  47. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  48. package/dist/runtime/host-load-runtime-settings.js +78 -0
  49. package/dist/runtime/host-load-sampler.d.ts +39 -4
  50. package/dist/runtime/host-load-sampler.js +83 -9
  51. package/dist/runtime/host-load-step-class.d.ts +37 -0
  52. package/dist/runtime/host-load-step-class.js +117 -2
  53. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  54. package/dist/runtime/host-load-step-reaper.js +95 -0
  55. package/dist/runtime/host-load-step-run.d.ts +73 -0
  56. package/dist/runtime/host-load-step-run.js +102 -0
  57. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  58. package/dist/runtime/host-load-test-slot.js +81 -0
  59. package/dist/runtime/host-load-token-ledger.d.ts +82 -17
  60. package/dist/runtime/host-load-token-ledger.js +187 -79
  61. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  62. package/dist/runtime/host-load-windows-cpu.js +85 -0
  63. package/dist/runtime/host-runtime-lease.d.ts +62 -3
  64. package/dist/runtime/host-runtime-lease.js +258 -13
  65. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  66. package/dist/runtime/host-runtime-promotion.js +36 -0
  67. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  68. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  69. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  70. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  71. package/dist/runtime/runner-settings.d.ts +100 -0
  72. package/dist/runtime/runner-settings.js +214 -0
  73. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  74. package/dist/sandbox/host-capacity-broker.js +334 -0
  75. package/dist/sandbox/runtime.d.ts +10 -1
  76. package/dist/sandbox/runtime.js +45 -2
  77. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  78. package/dist/sandbox/sandbox-cgroups.js +42 -0
  79. package/dist/session/architect-waits.d.ts +2 -0
  80. package/dist/session/architect-waits.js +138 -0
  81. package/dist/session/managed-attempt-tools.d.ts +2 -7
  82. package/dist/session/managed-attempt-tools.js +200 -92
  83. package/dist/session/managed-command-host-load.d.ts +47 -0
  84. package/dist/session/managed-command-host-load.js +83 -0
  85. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  86. package/dist/session/mcp-argument-coercion.js +121 -0
  87. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  88. package/dist/session/phase-completion.artifacts.js +96 -26
  89. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  90. package/dist/session/phase-completion.command-validation.js +77 -0
  91. package/dist/session/phase-completion.d.ts +4 -0
  92. package/dist/session/phase-completion.helpers.js +13 -12
  93. package/dist/session/phase-completion.js +4 -0
  94. package/dist/session/phase-completion.prompts.js +6 -1
  95. package/dist/session/phase-completion.runtime.d.ts +5 -3
  96. package/dist/session/phase-completion.runtime.js +50 -20
  97. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  98. package/dist/session/phase-completion.schema-parts.js +188 -0
  99. package/dist/session/phase-completion.schemas.d.ts +3 -3
  100. package/dist/session/phase-completion.schemas.js +208 -231
  101. package/dist/session/phase-completion.validation.d.ts +2 -3
  102. package/dist/session/phase-completion.validation.js +49 -93
  103. package/dist/session/pre-publication-host-load.js +31 -16
  104. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  105. package/dist/session/pre-publication-native-postgres.js +111 -0
  106. package/dist/session/pre-publication-pass.d.ts +61 -0
  107. package/dist/session/pre-publication-pass.js +148 -0
  108. package/dist/session/pre-publication-process.d.ts +3 -0
  109. package/dist/session/pre-publication-process.js +23 -11
  110. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  111. package/dist/session/pre-publication-step-execution.js +6 -5
  112. package/dist/session/pre-publication-validation.d.ts +30 -14
  113. package/dist/session/pre-publication-validation.js +211 -134
  114. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  115. package/dist/session/provider-cli/claude-background-work.js +180 -0
  116. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  117. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  118. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  119. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  120. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  121. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  122. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  123. package/dist/session/provider-cli/provider-cli.process.js +38 -339
  124. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  125. package/dist/session/provider-cli/provider-cli.prompts.js +50 -10
  126. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  127. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  128. package/dist/session/provider-cli/provider-cli.service.js +93 -162
  129. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  130. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  131. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  132. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  133. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  134. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  135. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  136. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  137. package/dist/session/provider-cli/provider-output-state.js +6 -0
  138. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  139. package/dist/session/qa-sidecar-validation.js +28 -0
  140. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  141. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  142. package/dist/session/session-redaction.js +31 -181
  143. package/dist/session/session.base.d.ts +6 -1
  144. package/dist/session/session.service.d.ts +7 -2
  145. package/dist/session/session.service.js +115 -5
  146. package/dist/session/session.types.js +4 -4
  147. package/dist/session/sidecar-json-shape.d.ts +31 -0
  148. package/dist/session/sidecar-json-shape.js +217 -0
  149. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  150. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  151. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  152. package/dist/shared/process/host-process-supervisor.js +1 -1
  153. package/dist/shared/process/process-tree.d.ts +52 -0
  154. package/dist/shared/process/process-tree.js +144 -0
  155. package/dist/shared/process/process.d.ts +67 -0
  156. package/dist/shared/process/process.js +213 -11
  157. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  158. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  159. package/dist/shared/process/windows-launch.d.ts +18 -0
  160. package/dist/shared/process/windows-launch.js +68 -0
  161. package/dist/shared/provider-capabilities.js +5 -6
  162. package/dist/version.d.ts +1 -1
  163. package/dist/version.js +1 -1
  164. package/dist/worktree/dependency-warmer.d.ts +25 -0
  165. package/dist/worktree/dependency-warmer.js +46 -10
  166. package/dist/worktree/worktree.service.d.ts +10 -1
  167. package/dist/worktree/worktree.service.js +42 -2
  168. package/dist/worktree/worktree.types.d.ts +7 -0
  169. package/package.json +2 -2
@@ -1,9 +1,13 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import os from "node:os";
2
3
  import { ForgeFailureError } from "../session/session.types.js";
3
4
  import { monotonicNowMs } from "../shared/time/monotonic.js";
4
5
  import { decideHostLoadAdmission, } from "./host-load-admission.js";
5
- import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
6
+ import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
6
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";
7
11
  import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
8
12
  export class HostCapacityTimeoutError extends ForgeFailureError {
9
13
  stepClass;
@@ -24,6 +28,8 @@ export class HostCapacityTimeoutError extends ForgeFailureError {
24
28
  * overtake an unfit head until the head has waited past the anti-starvation
25
29
  * window. Running steps are never preempted. Reserved cost comes from the
26
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.
27
33
  */
28
34
  export class HostLoadGovernor {
29
35
  options;
@@ -38,28 +44,44 @@ export class HostLoadGovernor {
38
44
  drainAgain = false;
39
45
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
40
46
  idleOwnMemoryBytes = null;
47
+ /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
48
+ runtimeSettings;
41
49
  constructor(options) {
42
50
  this.options = options;
43
51
  this.config = options.config ?? loadHostLoadGovernorConfig();
44
- this.enabled = this.config.mode === "on";
52
+ this.enabled = hostLoadGovernorEnabled(this.config);
53
+ this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
45
54
  this.ledger = new HostLoadTokenLedger({
46
55
  stateRoot: options.stateRoot,
47
56
  leaseMs: this.config.leaseMs,
48
57
  now: options.now,
49
58
  liveness: options.liveness,
50
59
  owner: options.owner,
51
- // Every ledger transaction renews (or restores) the steps this governor is running.
60
+ terminateStep: options.terminateStep,
61
+ suspendedMs: options.suspendedMs,
62
+ // Every ledger transaction renews the steps this governor is running.
52
63
  heldTokens: () => [...this.held.values()].map(entry => entry.token),
53
- onHeldTokens: outcome => this.onHeldTokens(outcome),
64
+ // ...and keeps its waiters' places in the host test slot queue.
65
+ waitingTickets: () => this.waiters.flatMap(waiter => waiter.ticket && !waiter.settled ? [waiter.ticket] : []),
54
66
  });
55
67
  }
68
+ get maxWaitMs() {
69
+ return this.config.maxWaitMs;
70
+ }
56
71
  async acquire(request, options = {}) {
57
- if (!this.enabled)
58
- throw new Error("host_load_governor_disabled: acquire() requires FORGE_HOST_LOAD_GOVERNOR=on.");
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
+ }
59
75
  const { signal } = options;
60
76
  if (signal?.aborted)
61
77
  throw abortError(signal);
62
- await this.options.load.start().catch(() => undefined);
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);
63
85
  if (signal?.aborted)
64
86
  throw abortError(signal);
65
87
  return await new Promise((resolve, reject) => {
@@ -74,6 +96,16 @@ export class HostLoadGovernor {
74
96
  deadline: null,
75
97
  lastDecision: null,
76
98
  settled: false,
99
+ ticket: this.config.testSlots > 0 && takesHostTestSlot(request.stepClass)
100
+ ? {
101
+ ticketId: randomUUID(),
102
+ stepClass: request.stepClass,
103
+ label: request.label,
104
+ dispatchAttemptId: request.dispatchAttemptId,
105
+ priority: request.priority,
106
+ enqueuedAt: new Date(this.options.now?.() ?? Date.now()).toISOString(),
107
+ }
108
+ : null,
77
109
  };
78
110
  waiter.deadline = setTimeout(() => this.settle(waiter, () => reject(new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - waiter.enqueuedAtMs, waiter.lastDecision?.detail ?? "the host stayed at capacity."))), this.config.maxWaitMs);
79
111
  waiter.deadline.unref?.();
@@ -96,22 +128,55 @@ export class HostLoadGovernor {
96
128
  async reclaim() {
97
129
  if (!this.enabled)
98
130
  return [];
99
- const reclaimed = await this.ledger.reclaim();
100
- if (reclaimed.length > 0)
131
+ const outcome = await this.ledger.transaction(() => undefined);
132
+ this.applyHeldOutcome(outcome);
133
+ if (outcome.reclaimed.length > 0)
101
134
  void this.drain();
102
- return reclaimed;
135
+ return outcome.reclaimed;
136
+ }
137
+ /** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
138
+ async releaseOrphaned(belongs) {
139
+ if (!this.enabled)
140
+ return [];
141
+ const released = await this.ledger.releaseOrphaned(belongs);
142
+ if (released.length > 0)
143
+ void this.drain();
144
+ return released;
145
+ }
146
+ /**
147
+ * Attempt teardown: cancels the attempt's queued steps and stops its running
148
+ * ones (their `fenced` signal aborts with dispatch_cancelled). A running step
149
+ * keeps its token, and its cost, until the step itself returns it once its
150
+ * processes are gone, so the capacity is never reused while it still runs.
151
+ */
152
+ stopAttempt(dispatchAttemptId) {
153
+ if (!this.enabled)
154
+ return;
155
+ this.cancelAttemptWaiters(dispatchAttemptId);
156
+ for (const entry of this.held.values()) {
157
+ if (entry.token.dispatchAttemptId !== dispatchAttemptId)
158
+ continue;
159
+ 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"));
160
+ }
103
161
  }
104
- /** Attempt teardown: cancels the attempt's waiters and returns every token it holds. */
162
+ /**
163
+ * Cancels the attempt's queued steps and returns every token it holds at
164
+ * once. Only for callers that know the attempt's steps are no longer running;
165
+ * attempt teardown uses stopAttempt.
166
+ */
105
167
  async releaseAttempt(dispatchAttemptId) {
106
168
  if (!this.enabled)
107
169
  return;
170
+ this.cancelAttemptWaiters(dispatchAttemptId);
171
+ const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
172
+ await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
173
+ }
174
+ cancelAttemptWaiters(dispatchAttemptId) {
108
175
  for (const waiter of [...this.waiters]) {
109
176
  if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
110
177
  continue;
111
178
  this.settle(waiter, () => waiter.reject(new ForgeFailureError("dispatch_cancelled", "dispatch_cancelled: the attempt was torn down while its step waited for host capacity.", "bridge")));
112
179
  }
113
- const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
114
- await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
115
180
  }
116
181
  /** Waiting and admitted steps of this process, for diagnostics. */
117
182
  snapshot() {
@@ -135,39 +200,33 @@ export class HostLoadGovernor {
135
200
  async drainOnce() {
136
201
  if (this.waiters.length === 0)
137
202
  return;
138
- const signals = this.readSignals();
139
- const logicalCpus = this.logicalCpus();
203
+ const budget = this.config.mode === "on" ? await this.budgetPass() : null;
204
+ if (this.waiters.length === 0)
205
+ return;
140
206
  const nowMs = monotonicNowMs();
141
207
  const outcomes = [];
142
- await this.ledger.transaction(transaction => {
143
- const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
208
+ const outcome = await this.ledger.transaction(transaction => {
209
+ const runningMemoryBytes = budget ? this.runningStepsMemoryBytes(transaction.tokens) : 0;
144
210
  const head = this.waiters[0];
145
211
  const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
146
212
  for (const waiter of this.waiters) {
147
213
  if (waiter.settled)
148
214
  continue;
149
- const computed = decideHostLoadAdmission({
150
- request: waiter.request.cost,
151
- running: transaction.tokens.map(token => token.cost),
152
- runningMemoryBytes,
153
- logicalCpus,
154
- signals,
155
- config: this.config,
156
- });
157
- const decision = transaction.recoveringUntil
158
- ? {
159
- ...computed,
160
- admitted: false,
161
- reason: "ledger_recovering",
162
- detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
163
- }
164
- : computed;
215
+ const decision = this.decide(waiter, transaction, budget, runningMemoryBytes);
216
+ if (decision.admitted && waiter.ticket) {
217
+ // The ticket leaves the host queue in the same commit that issues the token.
218
+ transaction.removeTicket(waiter.ticket.ticketId);
219
+ waiter.ticket = null;
220
+ }
165
221
  outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
166
- // A starving head blocks the queue so running steps drain and it can start.
167
- if (waiter === head && headStarving && !decision.admitted)
222
+ // A starving head blocks the budget so running steps drain and it can start. A
223
+ // slot wait does not: the host queue already orders slot waiters, and steps
224
+ // behind this one locally may be ahead of it there, or take no slot.
225
+ if (waiter === head && headStarving && !decision.admitted && decision.reason !== "host_test_slot")
168
226
  break;
169
227
  }
170
228
  });
229
+ this.applyHeldOutcome(outcome);
171
230
  for (const { waiter, token, decision } of outcomes) {
172
231
  if (!token) {
173
232
  const first = waiter.lastDecision === null;
@@ -178,11 +237,14 @@ export class HostLoadGovernor {
178
237
  }
179
238
  const entry = {
180
239
  token,
181
- lost: new AbortController(),
240
+ fencedController: new AbortController(),
241
+ fencedError: null,
182
242
  renewedAtMs: monotonicNowMs(),
183
243
  releasing: false,
184
244
  releaseInFlight: null,
185
245
  gone: false,
246
+ retainedUntil: null,
247
+ retainCheck: null,
186
248
  };
187
249
  this.held.set(token.tokenId, entry);
188
250
  this.armRenewal();
@@ -198,11 +260,60 @@ export class HostLoadGovernor {
198
260
  stepClass: token.stepClass,
199
261
  waitMs,
200
262
  decision,
201
- signal: entry.lost.signal,
263
+ fenced: entry.fencedController.signal,
264
+ attachProcess: stepProcess => this.attachProcess(entry, stepProcess),
202
265
  release: () => this.releaseHeld(entry),
266
+ retainUntilStopped: (stillGone, reason) => this.retainUntilStopped(entry, stillGone, reason),
203
267
  }));
204
268
  }
205
269
  }
270
+ /**
271
+ * Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
272
+ * bridge has in force apply from the next admission; running steps keep theirs.
273
+ * The operator's env ceilings hold with or without the file, and over whatever it says.
274
+ */
275
+ async budgetPass() {
276
+ const overrides = await this.runtimeSettings.read();
277
+ const cpuBudgetFraction = Math.min(overrides?.cpuBudgetFraction ?? this.config.cpuBudgetFraction, this.config.cpuBudgetCeilingFraction ?? 1);
278
+ return {
279
+ config: cpuBudgetFraction === this.config.cpuBudgetFraction ? this.config : { ...this.config, cpuBudgetFraction },
280
+ maxHeavySteps: lowestLimit(overrides?.maxHeavySteps ?? null, this.config.maxHeavyStepsCeiling ?? null),
281
+ signals: this.readSignals(),
282
+ logicalCpus: this.logicalCpus(),
283
+ };
284
+ }
285
+ /** The host test slot first (decision 0018), then the budget when it is on. */
286
+ decide(waiter, transaction, budget, runningMemoryBytes) {
287
+ const slot = waiter.ticket
288
+ ? decideHostTestSlot({
289
+ ticket: waiter.ticket,
290
+ queue: transaction.queue,
291
+ tokens: transaction.tokens,
292
+ testSlots: this.config.testSlots,
293
+ nowMs: this.options.now?.() ?? Date.now(),
294
+ antiStarvationMs: this.config.antiStarvationMs,
295
+ })
296
+ : null;
297
+ const decision = slot && !slot.admitted ? slot : budget
298
+ ? decideHostLoadAdmission({
299
+ request: waiter.request.cost,
300
+ running: transaction.tokens.map(token => token.cost),
301
+ runningMemoryBytes,
302
+ logicalCpus: budget.logicalCpus,
303
+ signals: budget.signals,
304
+ config: budget.config,
305
+ maxHeavySteps: budget.maxHeavySteps,
306
+ })
307
+ : slot ?? slotFreeDecision;
308
+ if (!transaction.recoveringUntil)
309
+ return decision;
310
+ return {
311
+ ...decision,
312
+ admitted: false,
313
+ reason: "ledger_recovering",
314
+ detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
315
+ };
316
+ }
206
317
  readSignals() {
207
318
  const snapshot = this.options.load.current();
208
319
  const cpu = snapshot?.systemPressure?.cpu?.some;
@@ -288,12 +399,59 @@ export class HostLoadGovernor {
288
399
  this.waiters.splice(index, 1);
289
400
  if (this.waiters.length === 0)
290
401
  this.disarmRecheck();
402
+ // A waiter that left without admission gives up its place now, not when its ticket lapses.
403
+ if (waiter.ticket)
404
+ void this.ledger.transaction(() => undefined).then(outcome => this.applyHeldOutcome(outcome), () => undefined);
405
+ waiter.ticket = null;
291
406
  complete();
292
407
  }
408
+ /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
409
+ applyHeldOutcome(outcome) {
410
+ const nowMs = monotonicNowMs();
411
+ for (const token of outcome.renewed) {
412
+ const entry = this.held.get(token.tokenId);
413
+ if (entry?.token.fencingToken === token.fencingToken)
414
+ entry.renewedAtMs = nowMs;
415
+ }
416
+ for (const token of outcome.fenced) {
417
+ const entry = this.held.get(token.tokenId);
418
+ if (!entry || entry.token.fencingToken !== token.fencingToken)
419
+ continue;
420
+ entry.fencedError ??= new HostCapacityTokenFencedError(token.tokenId, "renew");
421
+ this.lose(entry, entry.fencedError);
422
+ }
423
+ }
424
+ /** The step must stop: its reservation is no longer guaranteed. */
425
+ lose(entry, reason) {
426
+ if (entry.gone || entry.releasing || entry.fencedController.signal.aborted)
427
+ return;
428
+ entry.fencedController.abort(reason);
429
+ }
430
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
431
+ failWaiters(error) {
432
+ const failure = error instanceof HostCapacityLedgerUnavailableError
433
+ ? error
434
+ : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
435
+ for (const waiter of [...this.waiters])
436
+ this.settle(waiter, () => waiter.reject(failure));
437
+ }
438
+ async attachProcess(entry, stepProcess) {
439
+ if (entry.fencedError)
440
+ throw entry.fencedError;
441
+ if (entry.gone || entry.releasing)
442
+ return;
443
+ const outcome = await this.ledger.transaction(transaction => transaction.attach(entry.token.tokenId, entry.token.fencingToken, stepProcess));
444
+ this.applyHeldOutcome(outcome);
445
+ if (outcome.result)
446
+ entry.token = outcome.result;
447
+ else
448
+ throw entry.fencedError ?? new HostCapacityTokenFencedError(entry.token.tokenId, "renew");
449
+ }
293
450
  /**
294
451
  * Returns a step's token. It stays held (and renewed) until the ledger takes
295
452
  * it back, so a ledger outage cannot leave it to lapse into a fenced
296
- * reservation; the renewal timer retries the release.
453
+ * reservation; the renewal timer retries the release. A fenced token is
454
+ * removed too (its step is over) and the release reports the fence.
297
455
  */
298
456
  async releaseHeld(entry) {
299
457
  if (entry.gone)
@@ -322,33 +480,6 @@ export class HostLoadGovernor {
322
480
  if (this.held.size === 0)
323
481
  this.disarmRenewal();
324
482
  }
325
- /** The step must stop: its reservation is no longer guaranteed. */
326
- lose(entry, reason) {
327
- if (entry.gone || entry.releasing || entry.lost.signal.aborted)
328
- return;
329
- entry.lost.abort(reason);
330
- }
331
- onHeldTokens(outcome) {
332
- const nowMs = monotonicNowMs();
333
- for (const token of outcome.renewed) {
334
- const entry = this.held.get(token.tokenId);
335
- if (entry?.token.fencingToken === token.fencingToken)
336
- entry.renewedAtMs = nowMs;
337
- }
338
- for (const token of outcome.fenced) {
339
- const entry = this.held.get(token.tokenId);
340
- if (entry?.token.fencingToken === token.fencingToken)
341
- this.lose(entry, new HostCapacityTokenFencedError(token.tokenId, "renew"));
342
- }
343
- }
344
- /** Ledger failures reach every queued step instead of leaving it to time out. */
345
- failWaiters(error) {
346
- const failure = error instanceof HostCapacityLedgerUnavailableError
347
- ? error
348
- : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
349
- for (const waiter of [...this.waiters])
350
- this.settle(waiter, () => waiter.reject(failure));
351
- }
352
483
  armRecheck() {
353
484
  if (this.recheckTimer)
354
485
  return;
@@ -373,6 +504,60 @@ export class HostLoadGovernor {
373
504
  clearInterval(this.renewTimer);
374
505
  this.renewTimer = null;
375
506
  }
507
+ /**
508
+ * The step ended but part of its process tree may still run: its token stays
509
+ * held and renewed, with its cost, and the step's own termination check is
510
+ * retried on every renewal tick until it proves the tree gone.
511
+ */
512
+ retainUntilStopped(entry, stillGone, reason) {
513
+ if (entry.gone || entry.releasing)
514
+ return;
515
+ this.lose(entry, reason);
516
+ const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
517
+ entry.retainedUntil = stillGone
518
+ // The tree recorded on the token (supervised builds, installs) is stopped and checked.
519
+ ?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
520
+ this.armRenewal();
521
+ // Recorded in the ledger so the attempt's own next steps, in any process, do not
522
+ // wait for the slot this token keeps until the step's remains are gone.
523
+ void this.ledger.transaction(transaction => transaction.retain(entry.token.tokenId, entry.token.fencingToken))
524
+ .then(outcome => {
525
+ // Kept on the held entry too: a ledger rebuilt from held tokens must not lose the marker.
526
+ if (outcome.result)
527
+ entry.token = outcome.result;
528
+ this.applyHeldOutcome(outcome);
529
+ void this.drain();
530
+ })
531
+ .catch(() => undefined);
532
+ }
533
+ /**
534
+ * Attempt teardown stopped the attempt's processes (its process supervisor
535
+ * proved them gone): tokens kept for a tree nothing else can check are returned.
536
+ */
537
+ async releaseRetainedAfterTeardown(dispatchAttemptId) {
538
+ if (!this.enabled)
539
+ return;
540
+ const settled = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId && entry.retainedUntil === "attempt_teardown");
541
+ for (const entry of settled)
542
+ entry.retainedUntil = null;
543
+ await Promise.allSettled(settled.map(entry => this.releaseHeld(entry)));
544
+ }
545
+ checkRetained(entry) {
546
+ if (!entry.retainedUntil || entry.retainedUntil === "attempt_teardown" || entry.retainCheck)
547
+ return;
548
+ const stillGone = entry.retainedUntil;
549
+ entry.retainCheck = (async () => {
550
+ try {
551
+ if (await stillGone().catch(() => false)) {
552
+ entry.retainedUntil = null;
553
+ await this.releaseHeld(entry).catch(() => undefined);
554
+ }
555
+ }
556
+ finally {
557
+ entry.retainCheck = null;
558
+ }
559
+ })();
560
+ }
376
561
  async renewHeld() {
377
562
  if (this.held.size === 0)
378
563
  return;
@@ -380,11 +565,12 @@ export class HostLoadGovernor {
380
565
  // A release the ledger could not take is retried until it lands.
381
566
  if (entry.releasing && !entry.releaseInFlight)
382
567
  void this.releaseHeld(entry).catch(() => undefined);
568
+ this.checkRetained(entry);
383
569
  }
384
570
  try {
385
571
  // The ledger renews every held token at the start of each transaction and
386
- // reports the fenced ones through onHeldTokens.
387
- await this.ledger.transaction(() => undefined);
572
+ // reports the fenced ones.
573
+ this.applyHeldOutcome(await this.ledger.transaction(() => undefined));
388
574
  }
389
575
  catch (error) {
390
576
  // A brief outage is retried on the next tick. Once a whole lease passes
@@ -413,3 +599,34 @@ function abortError(signal) {
413
599
  error.name = "AbortError";
414
600
  return error;
415
601
  }
602
+ /** The lower of two optional limits; null when neither is set. */
603
+ function lowestLimit(a, b) {
604
+ if (a === null)
605
+ return b;
606
+ if (b === null)
607
+ return a;
608
+ return Math.min(a, b);
609
+ }
610
+ const slotFreeDecision = {
611
+ admitted: true,
612
+ reason: "admitted",
613
+ cpuBudgetCores: null,
614
+ memoryBudgetBytes: null,
615
+ reservedCpuCores: 0,
616
+ reservedMemoryBytes: 0,
617
+ detail: "The step takes no host test slot and the host budget is off.",
618
+ };
619
+ /** Admits a slot-free step at once, without a ledger token: nothing would count it. */
620
+ function slotFreeAdmission(request) {
621
+ return {
622
+ tokenId: `slot-free-${randomUUID()}`,
623
+ fencingToken: 0,
624
+ stepClass: request.stepClass,
625
+ waitMs: 0,
626
+ decision: slotFreeDecision,
627
+ fenced: new AbortController().signal,
628
+ attachProcess: async () => undefined,
629
+ release: async () => undefined,
630
+ retainUntilStopped: () => undefined,
631
+ };
632
+ }
@@ -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,78 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ export function hostLoadRuntimeSettingsPath(stateRoot) {
5
+ return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
6
+ }
7
+ /** Atomically replaces the overrides every governor on this state root reads. */
8
+ export async function writeHostLoadRuntimeSettings(stateRoot, overrides) {
9
+ const filePath = hostLoadRuntimeSettingsPath(stateRoot);
10
+ const content = {
11
+ schemaVersion: 1,
12
+ cpuBudgetFraction: overrides.cpuBudgetFraction,
13
+ maxHeavySteps: overrides.maxHeavySteps,
14
+ yielding: overrides.yielding,
15
+ writtenAt: new Date().toISOString(),
16
+ writerPid: process.pid,
17
+ };
18
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
19
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
20
+ try {
21
+ await fs.writeFile(temporary, `${JSON.stringify(content)}\n`, { mode: 0o600 });
22
+ await fs.rename(temporary, filePath);
23
+ }
24
+ catch (error) {
25
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
26
+ throw error;
27
+ }
28
+ }
29
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
30
+ export async function resetHostLoadRuntimeSettings(stateRoot) {
31
+ await fs.rm(hostLoadRuntimeSettingsPath(stateRoot), { force: true });
32
+ }
33
+ /**
34
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
35
+ * size, so a governor re-checking its queue every second costs one stat. A
36
+ * missing or unreadable file means no overrides.
37
+ */
38
+ export class HostLoadRuntimeSettingsReader {
39
+ filePath;
40
+ cachedKey = null;
41
+ cached = null;
42
+ constructor(stateRoot) {
43
+ this.filePath = hostLoadRuntimeSettingsPath(stateRoot);
44
+ }
45
+ async read() {
46
+ let key;
47
+ try {
48
+ const stat = await fs.stat(this.filePath);
49
+ key = `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`;
50
+ }
51
+ catch {
52
+ this.cachedKey = null;
53
+ this.cached = null;
54
+ return null;
55
+ }
56
+ if (key === this.cachedKey)
57
+ return this.cached;
58
+ const parsed = await fs.readFile(this.filePath, "utf8").then(parseOverrides).catch(() => null);
59
+ this.cachedKey = key;
60
+ this.cached = parsed;
61
+ return parsed;
62
+ }
63
+ }
64
+ function parseOverrides(content) {
65
+ const raw = JSON.parse(content);
66
+ if (!raw || raw.schemaVersion !== 1)
67
+ return null;
68
+ const fraction = raw.cpuBudgetFraction;
69
+ if (typeof fraction !== "number" || !Number.isFinite(fraction))
70
+ return null;
71
+ const steps = raw.maxHeavySteps;
72
+ return {
73
+ // The governor config's own bounds for the budget fraction.
74
+ cpuBudgetFraction: Math.min(1, Math.max(0.05, fraction)),
75
+ maxHeavySteps: typeof steps === "number" && Number.isInteger(steps) && steps >= 1 ? Math.min(64, steps) : null,
76
+ yielding: raw.yielding === true,
77
+ };
78
+ }