@loucompanion/forge-bridge 0.1.4-dev.8f4846c6e7a9 → 0.1.4-dev.93045aceba29

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 (109) hide show
  1. package/README.md +33 -0
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +70 -1
  4. package/dist/bridge/bridge.service.js +288 -8
  5. package/dist/bridge/bridge.types.d.ts +11 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/cleanup/cleanup.service.d.ts +9 -0
  9. package/dist/cleanup/cleanup.service.js +72 -109
  10. package/dist/cleanup/cleanup.types.d.ts +4 -0
  11. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  12. package/dist/cleanup/forge-owned-paths.js +53 -0
  13. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  14. package/dist/cleanup/host-runtime-ledger.js +109 -0
  15. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  16. package/dist/cleanup/managed-branch-sweep.js +111 -0
  17. package/dist/cli/cli.help.js +18 -0
  18. package/dist/cli/cli.service.d.ts +16 -0
  19. package/dist/cli/cli.service.js +140 -16
  20. package/dist/cli/local-config.d.ts +4 -0
  21. package/dist/cli/local-config.js +26 -4
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/host-load-admission.d.ts +9 -1
  24. package/dist/runtime/host-load-admission.js +19 -4
  25. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  26. package/dist/runtime/host-load-child-environment.js +67 -0
  27. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  28. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  29. package/dist/runtime/host-load-governor-config.d.ts +9 -0
  30. package/dist/runtime/host-load-governor-config.js +30 -0
  31. package/dist/runtime/host-load-governor.d.ts +62 -11
  32. package/dist/runtime/host-load-governor.js +168 -42
  33. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  34. package/dist/runtime/host-load-runtime-settings.js +78 -0
  35. package/dist/runtime/host-load-sampler.d.ts +5 -0
  36. package/dist/runtime/host-load-sampler.js +12 -4
  37. package/dist/runtime/host-load-step-class.d.ts +35 -0
  38. package/dist/runtime/host-load-step-class.js +60 -0
  39. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  40. package/dist/runtime/host-load-step-reaper.js +95 -0
  41. package/dist/runtime/host-load-step-run.d.ts +73 -0
  42. package/dist/runtime/host-load-step-run.js +102 -0
  43. package/dist/runtime/host-load-token-ledger.d.ts +58 -19
  44. package/dist/runtime/host-load-token-ledger.js +111 -35
  45. package/dist/runtime/host-runtime-lease.d.ts +61 -2
  46. package/dist/runtime/host-runtime-lease.js +255 -11
  47. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  48. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  49. package/dist/runtime/runner-settings.d.ts +100 -0
  50. package/dist/runtime/runner-settings.js +214 -0
  51. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  52. package/dist/sandbox/host-capacity-broker.js +315 -0
  53. package/dist/sandbox/runtime.d.ts +10 -1
  54. package/dist/sandbox/runtime.js +45 -2
  55. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  56. package/dist/sandbox/sandbox-cgroups.js +42 -0
  57. package/dist/session/managed-attempt-tools.d.ts +2 -0
  58. package/dist/session/managed-attempt-tools.js +156 -37
  59. package/dist/session/managed-command-host-load.d.ts +45 -0
  60. package/dist/session/managed-command-host-load.js +82 -0
  61. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  62. package/dist/session/mcp-argument-coercion.js +121 -0
  63. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  64. package/dist/session/phase-completion.artifacts.js +94 -25
  65. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  66. package/dist/session/phase-completion.command-validation.js +77 -0
  67. package/dist/session/phase-completion.d.ts +4 -0
  68. package/dist/session/phase-completion.helpers.js +13 -12
  69. package/dist/session/phase-completion.js +4 -0
  70. package/dist/session/phase-completion.prompts.js +6 -1
  71. package/dist/session/phase-completion.runtime.d.ts +5 -3
  72. package/dist/session/phase-completion.runtime.js +49 -19
  73. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  74. package/dist/session/phase-completion.schema-parts.js +188 -0
  75. package/dist/session/phase-completion.schemas.d.ts +3 -3
  76. package/dist/session/phase-completion.schemas.js +184 -209
  77. package/dist/session/phase-completion.validation.d.ts +2 -3
  78. package/dist/session/phase-completion.validation.js +46 -92
  79. package/dist/session/pre-publication-host-load.js +31 -16
  80. package/dist/session/pre-publication-process.d.ts +3 -0
  81. package/dist/session/pre-publication-process.js +23 -11
  82. package/dist/session/pre-publication-validation.js +4 -0
  83. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  84. package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
  85. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  86. package/dist/session/provider-cli/provider-cli.service.js +123 -15
  87. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  88. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  89. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  90. package/dist/session/session.base.d.ts +6 -1
  91. package/dist/session/session.service.d.ts +7 -2
  92. package/dist/session/session.service.js +115 -5
  93. package/dist/session/session.types.js +2 -2
  94. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  95. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  96. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  97. package/dist/shared/process/host-process-supervisor.js +1 -1
  98. package/dist/shared/process/process-tree.d.ts +52 -0
  99. package/dist/shared/process/process-tree.js +144 -0
  100. package/dist/shared/process/process.d.ts +67 -0
  101. package/dist/shared/process/process.js +213 -11
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/dist/worktree/dependency-warmer.d.ts +25 -0
  105. package/dist/worktree/dependency-warmer.js +46 -10
  106. package/dist/worktree/worktree.service.d.ts +10 -1
  107. package/dist/worktree/worktree.service.js +42 -2
  108. package/dist/worktree/worktree.types.d.ts +7 -0
  109. package/package.json +2 -2
@@ -4,6 +4,8 @@ import { monotonicNowMs } from "../shared/time/monotonic.js";
4
4
  import { decideHostLoadAdmission, } from "./host-load-admission.js";
5
5
  import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
6
6
  import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
7
+ import { HostLoadRuntimeSettingsReader } from "./host-load-runtime-settings.js";
8
+ import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
7
9
  import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
8
10
  export class HostCapacityTimeoutError extends ForgeFailureError {
9
11
  stepClass;
@@ -38,21 +40,28 @@ export class HostLoadGovernor {
38
40
  drainAgain = false;
39
41
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
40
42
  idleOwnMemoryBytes = null;
43
+ /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
44
+ runtimeSettings;
41
45
  constructor(options) {
42
46
  this.options = options;
43
47
  this.config = options.config ?? loadHostLoadGovernorConfig();
44
48
  this.enabled = this.config.mode === "on";
49
+ this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
45
50
  this.ledger = new HostLoadTokenLedger({
46
51
  stateRoot: options.stateRoot,
47
52
  leaseMs: this.config.leaseMs,
48
53
  now: options.now,
49
54
  liveness: options.liveness,
50
55
  owner: options.owner,
51
- // Every ledger transaction renews (or restores) the steps this governor is running.
56
+ terminateStep: options.terminateStep,
57
+ suspendedMs: options.suspendedMs,
58
+ // Every ledger transaction renews the steps this governor is running.
52
59
  heldTokens: () => [...this.held.values()].map(entry => entry.token),
53
- onHeldTokens: outcome => this.onHeldTokens(outcome),
54
60
  });
55
61
  }
62
+ get maxWaitMs() {
63
+ return this.config.maxWaitMs;
64
+ }
56
65
  async acquire(request, options = {}) {
57
66
  if (!this.enabled)
58
67
  throw new Error("host_load_governor_disabled: acquire() requires FORGE_HOST_LOAD_GOVERNOR=on.");
@@ -96,22 +105,55 @@ export class HostLoadGovernor {
96
105
  async reclaim() {
97
106
  if (!this.enabled)
98
107
  return [];
99
- const reclaimed = await this.ledger.reclaim();
100
- if (reclaimed.length > 0)
108
+ const outcome = await this.ledger.transaction(() => undefined);
109
+ this.applyHeldOutcome(outcome);
110
+ if (outcome.reclaimed.length > 0)
111
+ void this.drain();
112
+ return outcome.reclaimed;
113
+ }
114
+ /** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
115
+ async releaseOrphaned(belongs) {
116
+ if (!this.enabled)
117
+ return [];
118
+ const released = await this.ledger.releaseOrphaned(belongs);
119
+ if (released.length > 0)
101
120
  void this.drain();
102
- return reclaimed;
121
+ return released;
122
+ }
123
+ /**
124
+ * Attempt teardown: cancels the attempt's queued steps and stops its running
125
+ * ones (their `fenced` signal aborts with dispatch_cancelled). A running step
126
+ * keeps its token, and its cost, until the step itself returns it once its
127
+ * processes are gone, so the capacity is never reused while it still runs.
128
+ */
129
+ stopAttempt(dispatchAttemptId) {
130
+ if (!this.enabled)
131
+ return;
132
+ this.cancelAttemptWaiters(dispatchAttemptId);
133
+ for (const entry of this.held.values()) {
134
+ if (entry.token.dispatchAttemptId !== dispatchAttemptId)
135
+ continue;
136
+ 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"));
137
+ }
103
138
  }
104
- /** Attempt teardown: cancels the attempt's waiters and returns every token it holds. */
139
+ /**
140
+ * Cancels the attempt's queued steps and returns every token it holds at
141
+ * once. Only for callers that know the attempt's steps are no longer running;
142
+ * attempt teardown uses stopAttempt.
143
+ */
105
144
  async releaseAttempt(dispatchAttemptId) {
106
145
  if (!this.enabled)
107
146
  return;
147
+ this.cancelAttemptWaiters(dispatchAttemptId);
148
+ const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
149
+ await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
150
+ }
151
+ cancelAttemptWaiters(dispatchAttemptId) {
108
152
  for (const waiter of [...this.waiters]) {
109
153
  if (waiter.request.dispatchAttemptId !== dispatchAttemptId)
110
154
  continue;
111
155
  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
156
  }
113
- const owned = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId);
114
- await Promise.allSettled(owned.map(entry => this.releaseHeld(entry)));
115
157
  }
116
158
  /** Waiting and admitted steps of this process, for diagnostics. */
117
159
  snapshot() {
@@ -133,13 +175,22 @@ export class HostLoadGovernor {
133
175
  return await this.draining;
134
176
  }
135
177
  async drainOnce() {
178
+ if (this.waiters.length === 0)
179
+ return;
180
+ // Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
181
+ // bridge has in force apply from the next admission; running steps keep theirs.
182
+ // The operator's env ceilings hold with or without the file, and over whatever it says.
183
+ const overrides = await this.runtimeSettings.read();
184
+ const cpuBudgetFraction = Math.min(overrides?.cpuBudgetFraction ?? this.config.cpuBudgetFraction, this.config.cpuBudgetCeilingFraction ?? 1);
185
+ const config = cpuBudgetFraction === this.config.cpuBudgetFraction ? this.config : { ...this.config, cpuBudgetFraction };
186
+ const maxHeavySteps = lowestLimit(overrides?.maxHeavySteps ?? null, this.config.maxHeavyStepsCeiling ?? null);
136
187
  if (this.waiters.length === 0)
137
188
  return;
138
189
  const signals = this.readSignals();
139
190
  const logicalCpus = this.logicalCpus();
140
191
  const nowMs = monotonicNowMs();
141
192
  const outcomes = [];
142
- await this.ledger.transaction(transaction => {
193
+ const outcome = await this.ledger.transaction(transaction => {
143
194
  const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
144
195
  const head = this.waiters[0];
145
196
  const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
@@ -152,7 +203,8 @@ export class HostLoadGovernor {
152
203
  runningMemoryBytes,
153
204
  logicalCpus,
154
205
  signals,
155
- config: this.config,
206
+ config,
207
+ maxHeavySteps,
156
208
  });
157
209
  const decision = transaction.recoveringUntil
158
210
  ? {
@@ -168,6 +220,7 @@ export class HostLoadGovernor {
168
220
  break;
169
221
  }
170
222
  });
223
+ this.applyHeldOutcome(outcome);
171
224
  for (const { waiter, token, decision } of outcomes) {
172
225
  if (!token) {
173
226
  const first = waiter.lastDecision === null;
@@ -178,11 +231,14 @@ export class HostLoadGovernor {
178
231
  }
179
232
  const entry = {
180
233
  token,
181
- lost: new AbortController(),
234
+ fencedController: new AbortController(),
235
+ fencedError: null,
182
236
  renewedAtMs: monotonicNowMs(),
183
237
  releasing: false,
184
238
  releaseInFlight: null,
185
239
  gone: false,
240
+ retainedUntil: null,
241
+ retainCheck: null,
186
242
  };
187
243
  this.held.set(token.tokenId, entry);
188
244
  this.armRenewal();
@@ -198,8 +254,10 @@ export class HostLoadGovernor {
198
254
  stepClass: token.stepClass,
199
255
  waitMs,
200
256
  decision,
201
- signal: entry.lost.signal,
257
+ fenced: entry.fencedController.signal,
258
+ attachProcess: stepProcess => this.attachProcess(entry, stepProcess),
202
259
  release: () => this.releaseHeld(entry),
260
+ retainUntilStopped: (stillGone, reason) => this.retainUntilStopped(entry, stillGone, reason),
203
261
  }));
204
262
  }
205
263
  }
@@ -290,10 +348,53 @@ export class HostLoadGovernor {
290
348
  this.disarmRecheck();
291
349
  complete();
292
350
  }
351
+ /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
352
+ applyHeldOutcome(outcome) {
353
+ const nowMs = monotonicNowMs();
354
+ for (const token of outcome.renewed) {
355
+ const entry = this.held.get(token.tokenId);
356
+ if (entry?.token.fencingToken === token.fencingToken)
357
+ entry.renewedAtMs = nowMs;
358
+ }
359
+ for (const token of outcome.fenced) {
360
+ const entry = this.held.get(token.tokenId);
361
+ if (!entry || entry.token.fencingToken !== token.fencingToken)
362
+ continue;
363
+ entry.fencedError ??= new HostCapacityTokenFencedError(token.tokenId, "renew");
364
+ this.lose(entry, entry.fencedError);
365
+ }
366
+ }
367
+ /** The step must stop: its reservation is no longer guaranteed. */
368
+ lose(entry, reason) {
369
+ if (entry.gone || entry.releasing || entry.fencedController.signal.aborted)
370
+ return;
371
+ entry.fencedController.abort(reason);
372
+ }
373
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
374
+ failWaiters(error) {
375
+ const failure = error instanceof HostCapacityLedgerUnavailableError
376
+ ? error
377
+ : new HostCapacityLedgerUnavailableError(`the admission decision failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
378
+ for (const waiter of [...this.waiters])
379
+ this.settle(waiter, () => waiter.reject(failure));
380
+ }
381
+ async attachProcess(entry, stepProcess) {
382
+ if (entry.fencedError)
383
+ throw entry.fencedError;
384
+ if (entry.gone || entry.releasing)
385
+ return;
386
+ const outcome = await this.ledger.transaction(transaction => transaction.attach(entry.token.tokenId, entry.token.fencingToken, stepProcess));
387
+ this.applyHeldOutcome(outcome);
388
+ if (outcome.result)
389
+ entry.token = outcome.result;
390
+ else
391
+ throw entry.fencedError ?? new HostCapacityTokenFencedError(entry.token.tokenId, "renew");
392
+ }
293
393
  /**
294
394
  * Returns a step's token. It stays held (and renewed) until the ledger takes
295
395
  * it back, so a ledger outage cannot leave it to lapse into a fenced
296
- * reservation; the renewal timer retries the release.
396
+ * reservation; the renewal timer retries the release. A fenced token is
397
+ * removed too (its step is over) and the release reports the fence.
297
398
  */
298
399
  async releaseHeld(entry) {
299
400
  if (entry.gone)
@@ -322,33 +423,6 @@ export class HostLoadGovernor {
322
423
  if (this.held.size === 0)
323
424
  this.disarmRenewal();
324
425
  }
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
426
  armRecheck() {
353
427
  if (this.recheckTimer)
354
428
  return;
@@ -373,6 +447,49 @@ export class HostLoadGovernor {
373
447
  clearInterval(this.renewTimer);
374
448
  this.renewTimer = null;
375
449
  }
450
+ /**
451
+ * The step ended but part of its process tree may still run: its token stays
452
+ * held and renewed, with its cost, and the step's own termination check is
453
+ * retried on every renewal tick until it proves the tree gone.
454
+ */
455
+ retainUntilStopped(entry, stillGone, reason) {
456
+ if (entry.gone || entry.releasing)
457
+ return;
458
+ this.lose(entry, reason);
459
+ const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
460
+ entry.retainedUntil = stillGone
461
+ // The tree recorded on the token (supervised builds, installs) is stopped and checked.
462
+ ?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
463
+ this.armRenewal();
464
+ }
465
+ /**
466
+ * Attempt teardown stopped the attempt's processes (its process supervisor
467
+ * proved them gone): tokens kept for a tree nothing else can check are returned.
468
+ */
469
+ async releaseRetainedAfterTeardown(dispatchAttemptId) {
470
+ if (!this.enabled)
471
+ return;
472
+ const settled = [...this.held.values()].filter(entry => entry.token.dispatchAttemptId === dispatchAttemptId && entry.retainedUntil === "attempt_teardown");
473
+ for (const entry of settled)
474
+ entry.retainedUntil = null;
475
+ await Promise.allSettled(settled.map(entry => this.releaseHeld(entry)));
476
+ }
477
+ checkRetained(entry) {
478
+ if (!entry.retainedUntil || entry.retainedUntil === "attempt_teardown" || entry.retainCheck)
479
+ return;
480
+ const stillGone = entry.retainedUntil;
481
+ entry.retainCheck = (async () => {
482
+ try {
483
+ if (await stillGone().catch(() => false)) {
484
+ entry.retainedUntil = null;
485
+ await this.releaseHeld(entry).catch(() => undefined);
486
+ }
487
+ }
488
+ finally {
489
+ entry.retainCheck = null;
490
+ }
491
+ })();
492
+ }
376
493
  async renewHeld() {
377
494
  if (this.held.size === 0)
378
495
  return;
@@ -380,11 +497,12 @@ export class HostLoadGovernor {
380
497
  // A release the ledger could not take is retried until it lands.
381
498
  if (entry.releasing && !entry.releaseInFlight)
382
499
  void this.releaseHeld(entry).catch(() => undefined);
500
+ this.checkRetained(entry);
383
501
  }
384
502
  try {
385
503
  // 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);
504
+ // reports the fenced ones.
505
+ this.applyHeldOutcome(await this.ledger.transaction(() => undefined));
388
506
  }
389
507
  catch (error) {
390
508
  // A brief outage is retried on the next tick. Once a whole lease passes
@@ -413,3 +531,11 @@ function abortError(signal) {
413
531
  error.name = "AbortError";
414
532
  return error;
415
533
  }
534
+ /** The lower of two optional limits; null when neither is set. */
535
+ function lowestLimit(a, b) {
536
+ if (a === null)
537
+ return b;
538
+ if (b === null)
539
+ return a;
540
+ return Math.min(a, b);
541
+ }
@@ -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
+ }
@@ -1,5 +1,6 @@
1
1
  import { type HostEnvironment, type HostFacts } from "./host-facts.js";
2
2
  import { type PressureStallResource } from "./host-pressure-stall.js";
3
+ import { type ForgeCgroupSource } from "./host-load-forge-cgroups.js";
3
4
  export interface HostSystemPressure {
4
5
  readonly cpu: PressureStallResource | null;
5
6
  readonly memory: PressureStallResource | null;
@@ -73,6 +74,8 @@ export interface HostLoadSamplerOptions {
73
74
  readonly monotonicNow?: () => number;
74
75
  /** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
75
76
  readonly cgroupUnit?: string | null;
77
+ /** Docker sandbox cgroups whose CPU time is Forge's own, not external load. */
78
+ readonly forgeCgroups?: ForgeCgroupSource;
76
79
  }
77
80
  export declare const defaultHostLoadSampleIntervalMs = 5000;
78
81
  /**
@@ -97,6 +100,8 @@ export declare class HostLoadSampler implements HostLoadSource {
97
100
  private hostCpuMark;
98
101
  private latestCpuAttribution;
99
102
  private latestMemoryHeadroom;
103
+ private readonly forgeCgroups;
104
+ private readonly sandboxCpu;
100
105
  constructor(options?: HostLoadSamplerOptions);
101
106
  facts(): HostFacts | null;
102
107
  current(): HostLoadSnapshot | null;
@@ -1,7 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
3
3
  import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseProcStatCpuTotals, parseUnifiedCgroupMembership, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
4
- import { readCgroupMemoryHeadroomBytes } from "./host-load-forge-cgroups.js";
4
+ import { ForgeCgroupCpuMeter, readCgroupMemoryHeadroomBytes, } from "./host-load-forge-cgroups.js";
5
5
  export const defaultHostLoadSampleIntervalMs = 5_000;
6
6
  /** Samples kept for the governor's pressure streak (FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES is at most 60). */
7
7
  const retainedSampleCount = 64;
@@ -27,6 +27,8 @@ export class HostLoadSampler {
27
27
  hostCpuMark = null;
28
28
  latestCpuAttribution = null;
29
29
  latestMemoryHeadroom = null;
30
+ forgeCgroups;
31
+ sandboxCpu;
30
32
  constructor(options = {}) {
31
33
  this.environment = options.environment ?? defaultHostEnvironment();
32
34
  this.intervalMs = options.intervalMs !== undefined && Number.isFinite(options.intervalMs) && options.intervalMs > 0
@@ -37,6 +39,8 @@ export class HostLoadSampler {
37
39
  this.cgroupUnit = options.cgroupUnit !== undefined
38
40
  ? options.cgroupUnit
39
41
  : process.env.FORGE_BRIDGE_CGROUP_UNIT?.trim() || null;
42
+ this.forgeCgroups = options.forgeCgroups ?? null;
43
+ this.sandboxCpu = new ForgeCgroupCpuMeter(this.environment);
40
44
  }
41
45
  facts() {
42
46
  return this.hostFacts;
@@ -101,18 +105,22 @@ export class HostLoadSampler {
101
105
  const sampledAtMs = this.now();
102
106
  const monotonicMs = this.monotonicNow();
103
107
  const linux = this.environment.platform === "linux";
104
- const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes] = linux
108
+ const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes, sandboxCores] = linux
105
109
  ? await Promise.all([
106
110
  this.readSystemPressure(),
107
111
  this.readOwnCgroup(monotonicMs),
108
112
  this.readMemoryAvailable(),
109
113
  this.readHostCoresInUse(),
110
114
  this.readCgroupMemoryHeadroom(),
115
+ Promise.resolve(this.forgeCgroups?.paths() ?? [])
116
+ .then(paths => this.sandboxCpu.coresInUse(paths, monotonicMs)).catch(() => 0),
111
117
  ])
112
- : [null, null, this.fallbackFreeMemory(), null, null];
118
+ : [null, null, this.fallbackFreeMemory(), null, null, 0];
113
119
  const sampledAt = new Date(sampledAtMs).toISOString();
120
+ // Docker sandbox CPU is Forge's own work, already counted through reserved cost.
121
+ const ownCores = ownCgroup?.cpuCoresInUse ?? null;
114
122
  this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
115
- this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCgroup?.cpuCoresInUse ?? null);
123
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCores === null ? null : ownCores + sandboxCores);
116
124
  return {
117
125
  sampledAt,
118
126
  psiAvailable: systemPressure !== null,
@@ -25,9 +25,44 @@ export declare const defaultHostLoadStepCosts: {
25
25
  readonly cpuCores: 1;
26
26
  readonly memoryBytes: number;
27
27
  };
28
+ /** A `dotnet build` (or test with its build) started as a managed command. */
29
+ readonly managedBuild: {
30
+ readonly cpuCores: 2;
31
+ readonly memoryBytes: number;
32
+ };
33
+ readonly aspnetPrebuild: {
34
+ readonly cpuCores: 2;
35
+ readonly memoryBytes: number;
36
+ };
37
+ /** Dependency installs are mostly network and disk bound, so they cost less than a build. */
38
+ readonly dependencyInstall: {
39
+ readonly cpuCores: 0.5;
40
+ readonly memoryBytes: number;
41
+ };
28
42
  };
43
+ export declare const aspNetPrebuildStepClass: HostLoadStepClassification;
44
+ export declare const dependencyInstallStepClass: HostLoadStepClassification;
29
45
  /**
30
46
  * Maps a pre-publication validation step to its class: `dotnet.tier.<tier>`,
31
47
  * `vitest.<suite>`, `playwright.e2e`, or `generic` for everything else.
32
48
  */
33
49
  export declare function classifyValidationStep(checkId: string, command: string, args: readonly string[]): HostLoadStepClassification;
50
+ export interface ManagedCommandStepInput {
51
+ readonly command: string;
52
+ readonly args: readonly string[];
53
+ /** The runner-authored verification profile, when the command is one. */
54
+ readonly verificationProfile?: string;
55
+ /** Whether the command builds (see isBuildProducingManagedCommand). */
56
+ readonly buildProducing: boolean;
57
+ }
58
+ /**
59
+ * Maps a managed command to its class: `managed.<profile>` for verification
60
+ * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
61
+ * `managed.build` for build-producing commands, and `managed.command` otherwise.
62
+ */
63
+ export declare function classifyManagedCommand(input: ManagedCommandStepInput): HostLoadStepClassification;
64
+ /**
65
+ * The default cost of a step class, for a step whose cost the requester does
66
+ * not get to choose (a Docker sandbox asking the host bridge for admission).
67
+ */
68
+ export declare function hostLoadStepCostForClass(stepClass: string): HostLoadStepCost;
@@ -6,6 +6,19 @@ export const defaultHostLoadStepCosts = {
6
6
  vitest: { cpuCores: 1, memoryBytes: 1.5 * gib },
7
7
  playwright: { cpuCores: 2, memoryBytes: 2 * gib },
8
8
  generic: { cpuCores: 1, memoryBytes: 1 * gib },
9
+ /** A `dotnet build` (or test with its build) started as a managed command. */
10
+ managedBuild: { cpuCores: 2, memoryBytes: 2 * gib },
11
+ aspnetPrebuild: { cpuCores: 2, memoryBytes: 2 * gib },
12
+ /** Dependency installs are mostly network and disk bound, so they cost less than a build. */
13
+ dependencyInstall: { cpuCores: 0.5, memoryBytes: 0.75 * gib },
14
+ };
15
+ export const aspNetPrebuildStepClass = {
16
+ stepClass: "aspnet.prebuild",
17
+ cost: defaultHostLoadStepCosts.aspnetPrebuild,
18
+ };
19
+ export const dependencyInstallStepClass = {
20
+ stepClass: "deps.install",
21
+ cost: defaultHostLoadStepCosts.dependencyInstall,
9
22
  };
10
23
  const dotnetTierScripts = ["scripts/run-dotnet-test-tier.ps1", "scripts/run-dotnet-test-tier-set.ps1"];
11
24
  const affectedDotnetScript = "scripts/run-affected-dotnet-tests.mjs";
@@ -44,3 +57,50 @@ function stepClassSegment(value) {
44
57
  const segment = value.trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "");
45
58
  return segment || "unknown";
46
59
  }
60
+ /**
61
+ * Maps a managed command to its class: `managed.<profile>` for verification
62
+ * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
63
+ * `managed.build` for build-producing commands, and `managed.command` otherwise.
64
+ */
65
+ export function classifyManagedCommand(input) {
66
+ if (input.verificationProfile) {
67
+ const parallelism = maxParallelismArgument(input.args);
68
+ const tier = defaultHostLoadStepCosts.dotnetTier;
69
+ return {
70
+ stepClass: `managed.${stepClassSegment(input.verificationProfile)}`,
71
+ cost: {
72
+ cpuCores: tier.cpuCores * parallelism,
73
+ memoryBytes: tier.memoryBytes + (parallelism - 1) * 1.5 * gib,
74
+ },
75
+ };
76
+ }
77
+ const invocation = [input.command, ...input.args].map(argument => argument.toLowerCase());
78
+ if (invocation.some(argument => argument.includes("playwright"))) {
79
+ return { stepClass: "managed.playwright", cost: defaultHostLoadStepCosts.playwright };
80
+ }
81
+ if (input.buildProducing)
82
+ return { stepClass: "managed.build", cost: defaultHostLoadStepCosts.managedBuild };
83
+ return { stepClass: "managed.command", cost: defaultHostLoadStepCosts.generic };
84
+ }
85
+ /**
86
+ * The default cost of a step class, for a step whose cost the requester does
87
+ * not get to choose (a Docker sandbox asking the host bridge for admission).
88
+ */
89
+ export function hostLoadStepCostForClass(stepClass) {
90
+ if (stepClass.startsWith("dotnet.tier."))
91
+ return defaultHostLoadStepCosts.dotnetTier;
92
+ if (stepClass.startsWith("vitest."))
93
+ return defaultHostLoadStepCosts.vitest;
94
+ if (stepClass === "playwright.e2e")
95
+ return defaultHostLoadStepCosts.playwright;
96
+ if (stepClass === aspNetPrebuildStepClass.stepClass)
97
+ return defaultHostLoadStepCosts.aspnetPrebuild;
98
+ if (stepClass === dependencyInstallStepClass.stepClass)
99
+ return defaultHostLoadStepCosts.dependencyInstall;
100
+ return defaultHostLoadStepCosts.generic;
101
+ }
102
+ function maxParallelismArgument(args) {
103
+ const index = args.findIndex(argument => argument.toLowerCase() === "-maxparallelism");
104
+ const value = index >= 0 ? Number(args[index + 1]) : 1;
105
+ return Number.isSafeInteger(value) && value >= 1 ? Math.min(value, 32) : 1;
106
+ }
@@ -0,0 +1,27 @@
1
+ import { type WindowsProcessTable } from "../shared/process/process-tree.js";
2
+ /** The process tree a governed step runs in, recorded on its token once it launches. */
3
+ export interface HostLoadStepProcess {
4
+ readonly rootPid: number;
5
+ /** OS birth marker of the root, so a reused pid is never signalled. Null where unsupported. */
6
+ readonly rootIdentity: string | null;
7
+ /** The root leads its own process group (Unix): the whole group is stopped and checked. */
8
+ readonly processGroup: boolean;
9
+ }
10
+ /** Stops a step's process tree; resolves true only when no member is left. */
11
+ export type HostLoadStepTerminator = (step: HostLoadStepProcess) => Promise<boolean>;
12
+ /**
13
+ * Stops the recorded tree with SIGTERM, then SIGKILL, and confirms it is gone.
14
+ * A root that cannot be identified (no birth marker) is never signalled and
15
+ * counts as not confirmed, so its token keeps its reserved cost.
16
+ */
17
+ export declare const terminateHostLoadStepProcess: HostLoadStepTerminator;
18
+ /**
19
+ * Windows has no process groups and does not reparent orphans. A root with a
20
+ * recorded birth marker is stopped together with every descendant created
21
+ * after it (found through parent ids, even if the root already exited), and
22
+ * the reservation is reused only once none is left. Without a birth marker the
23
+ * root cannot be told from a reused pid, so it is never signalled and only its
24
+ * absence counts.
25
+ */
26
+ export declare function windowsStepTerminator(table: WindowsProcessTable, waitMs?: number): HostLoadStepTerminator;
27
+ export declare function validHostLoadStepProcess(value: unknown): value is HostLoadStepProcess;