@loucompanion/forge-bridge 0.1.4-dev.25308ca4a63d → 0.1.4-dev.297b5afcac9e

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 (126) 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 +2 -0
  7. package/dist/bridge/bridge.service.d.ts +53 -1
  8. package/dist/bridge/bridge.service.js +234 -113
  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/cli/cli.help.js +18 -0
  15. package/dist/cli/cli.service.d.ts +16 -0
  16. package/dist/cli/cli.service.js +122 -13
  17. package/dist/cli/local-config.d.ts +4 -0
  18. package/dist/cli/local-config.js +26 -4
  19. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  20. package/dist/runtime/aspnet-runtime-prebuild.js +44 -0
  21. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  22. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  23. package/dist/runtime/docker-engine-probe.js +7 -0
  24. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  25. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  26. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  27. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  28. package/dist/runtime/host-facts.d.ts +2 -1
  29. package/dist/runtime/host-load-admission.d.ts +18 -3
  30. package/dist/runtime/host-load-admission.js +19 -4
  31. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  32. package/dist/runtime/host-load-child-environment.js +22 -11
  33. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  34. package/dist/runtime/host-load-governor-config.js +37 -0
  35. package/dist/runtime/host-load-governor.d.ts +12 -0
  36. package/dist/runtime/host-load-governor.js +139 -26
  37. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  38. package/dist/runtime/host-load-runtime-settings.js +78 -0
  39. package/dist/runtime/host-load-sampler.d.ts +34 -4
  40. package/dist/runtime/host-load-sampler.js +73 -7
  41. package/dist/runtime/host-load-step-class.d.ts +3 -1
  42. package/dist/runtime/host-load-step-class.js +60 -5
  43. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  44. package/dist/runtime/host-load-test-slot.js +81 -0
  45. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  46. package/dist/runtime/host-load-token-ledger.js +93 -61
  47. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  48. package/dist/runtime/host-load-windows-cpu.js +85 -0
  49. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  50. package/dist/runtime/host-runtime-contract.js +29 -1
  51. package/dist/runtime/host-runtime-lease.d.ts +29 -3
  52. package/dist/runtime/host-runtime-lease.js +83 -63
  53. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  54. package/dist/runtime/host-runtime-promotion.js +36 -0
  55. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  56. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  57. package/dist/runtime/runner-settings.d.ts +100 -0
  58. package/dist/runtime/runner-settings.js +214 -0
  59. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  60. package/dist/sandbox/host-capacity-broker.js +23 -4
  61. package/dist/session/architect-waits.d.ts +2 -0
  62. package/dist/session/architect-waits.js +138 -0
  63. package/dist/session/managed-attempt-tools.d.ts +0 -7
  64. package/dist/session/managed-attempt-tools.js +51 -62
  65. package/dist/session/managed-command-host-load.d.ts +2 -0
  66. package/dist/session/managed-command-host-load.js +2 -1
  67. package/dist/session/phase-completion.artifacts.js +2 -1
  68. package/dist/session/phase-completion.d.ts +8 -0
  69. package/dist/session/phase-completion.js +1 -0
  70. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  71. package/dist/session/phase-completion.mcp-args.js +156 -0
  72. package/dist/session/phase-completion.runtime.d.ts +0 -8
  73. package/dist/session/phase-completion.runtime.js +38 -168
  74. package/dist/session/phase-completion.schemas.js +25 -23
  75. package/dist/session/phase-completion.validation.js +3 -1
  76. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  77. package/dist/session/pre-publication-native-postgres.js +111 -0
  78. package/dist/session/pre-publication-pass.d.ts +61 -0
  79. package/dist/session/pre-publication-pass.js +148 -0
  80. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  81. package/dist/session/pre-publication-step-execution.js +6 -5
  82. package/dist/session/pre-publication-validation.d.ts +30 -14
  83. package/dist/session/pre-publication-validation.js +207 -134
  84. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  85. package/dist/session/provider-cli/claude-background-work.js +180 -0
  86. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  87. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  88. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  89. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  90. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  91. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  92. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  93. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  94. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  95. package/dist/session/provider-cli/provider-cli.prompts.js +58 -8
  96. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  97. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
  98. package/dist/session/provider-cli/provider-cli.service.js +65 -257
  99. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  100. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  101. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  102. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  103. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  104. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  105. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  106. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  107. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  108. package/dist/session/provider-cli/provider-output-state.js +6 -0
  109. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  110. package/dist/session/qa-sidecar-validation.js +28 -0
  111. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  112. package/dist/session/session-redaction.js +31 -181
  113. package/dist/session/session.base.d.ts +6 -1
  114. package/dist/session/session.service.d.ts +4 -1
  115. package/dist/session/session.service.js +6 -0
  116. package/dist/session/session.types.js +3 -3
  117. package/dist/session/sidecar-json-shape.d.ts +31 -0
  118. package/dist/session/sidecar-json-shape.js +217 -0
  119. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  120. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  121. package/dist/shared/process/windows-launch.d.ts +18 -0
  122. package/dist/shared/process/windows-launch.js +68 -0
  123. package/dist/shared/provider-capabilities.js +5 -6
  124. package/dist/version.d.ts +1 -1
  125. package/dist/version.js +1 -1
  126. package/package.json +2 -2
@@ -79,6 +79,8 @@ export interface HostLoadGovernorOptions {
79
79
  * overtake an unfit head until the head has waited past the anti-starvation
80
80
  * window. Running steps are never preempted. Reserved cost comes from the
81
81
  * shared token ledger, so other processes' steps count against the same budget.
82
+ * The host test slot (decision 0018) comes first: a heavy step waits for it in
83
+ * the host-wide queue the ledger keeps, then for the budget when that is on.
82
84
  */
83
85
  export declare class HostLoadGovernor implements HostLoadStepGate {
84
86
  private readonly options;
@@ -93,6 +95,8 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
93
95
  private drainAgain;
94
96
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
95
97
  private idleOwnMemoryBytes;
98
+ /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
99
+ private readonly runtimeSettings;
96
100
  constructor(options: HostLoadGovernorOptions);
97
101
  get maxWaitMs(): number;
98
102
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
@@ -121,6 +125,14 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
121
125
  };
122
126
  private drain;
123
127
  private drainOnce;
128
+ /**
129
+ * Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
130
+ * bridge has in force apply from the next admission; running steps keep theirs.
131
+ * The operator's env ceilings hold with or without the file, and over whatever it says.
132
+ */
133
+ private budgetPass;
134
+ /** The host test slot first (decision 0018), then the budget when it is on. */
135
+ private decide;
124
136
  private readSignals;
125
137
  /**
126
138
  * Consecutive pressured samples ending with the latest one, read from the
@@ -1,9 +1,12 @@
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";
7
10
  import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
8
11
  import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
9
12
  export class HostCapacityTimeoutError extends ForgeFailureError {
@@ -25,6 +28,8 @@ export class HostCapacityTimeoutError extends ForgeFailureError {
25
28
  * overtake an unfit head until the head has waited past the anti-starvation
26
29
  * window. Running steps are never preempted. Reserved cost comes from the
27
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.
28
33
  */
29
34
  export class HostLoadGovernor {
30
35
  options;
@@ -39,10 +44,13 @@ export class HostLoadGovernor {
39
44
  drainAgain = false;
40
45
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
41
46
  idleOwnMemoryBytes = null;
47
+ /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
48
+ runtimeSettings;
42
49
  constructor(options) {
43
50
  this.options = options;
44
51
  this.config = options.config ?? loadHostLoadGovernorConfig();
45
- this.enabled = this.config.mode === "on";
52
+ this.enabled = hostLoadGovernorEnabled(this.config);
53
+ this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
46
54
  this.ledger = new HostLoadTokenLedger({
47
55
  stateRoot: options.stateRoot,
48
56
  leaseMs: this.config.leaseMs,
@@ -53,18 +61,27 @@ export class HostLoadGovernor {
53
61
  suspendedMs: options.suspendedMs,
54
62
  // Every ledger transaction renews the steps this governor is running.
55
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] : []),
56
66
  });
57
67
  }
58
68
  get maxWaitMs() {
59
69
  return this.config.maxWaitMs;
60
70
  }
61
71
  async acquire(request, options = {}) {
62
- if (!this.enabled)
63
- 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
+ }
64
75
  const { signal } = options;
65
76
  if (signal?.aborted)
66
77
  throw abortError(signal);
67
- 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);
68
85
  if (signal?.aborted)
69
86
  throw abortError(signal);
70
87
  return await new Promise((resolve, reject) => {
@@ -79,6 +96,16 @@ export class HostLoadGovernor {
79
96
  deadline: null,
80
97
  lastDecision: null,
81
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,
82
109
  };
83
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);
84
111
  waiter.deadline.unref?.();
@@ -173,36 +200,29 @@ export class HostLoadGovernor {
173
200
  async drainOnce() {
174
201
  if (this.waiters.length === 0)
175
202
  return;
176
- const signals = this.readSignals();
177
- const logicalCpus = this.logicalCpus();
203
+ const budget = this.config.mode === "on" ? await this.budgetPass() : null;
204
+ if (this.waiters.length === 0)
205
+ return;
178
206
  const nowMs = monotonicNowMs();
179
207
  const outcomes = [];
180
208
  const outcome = await this.ledger.transaction(transaction => {
181
- const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
209
+ const runningMemoryBytes = budget ? this.runningStepsMemoryBytes(transaction.tokens) : 0;
182
210
  const head = this.waiters[0];
183
211
  const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
184
212
  for (const waiter of this.waiters) {
185
213
  if (waiter.settled)
186
214
  continue;
187
- const computed = decideHostLoadAdmission({
188
- request: waiter.request.cost,
189
- running: transaction.tokens.map(token => token.cost),
190
- runningMemoryBytes,
191
- logicalCpus,
192
- signals,
193
- config: this.config,
194
- });
195
- const decision = transaction.recoveringUntil
196
- ? {
197
- ...computed,
198
- admitted: false,
199
- reason: "ledger_recovering",
200
- detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
201
- }
202
- : 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
+ }
203
221
  outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
204
- // A starving head blocks the queue so running steps drain and it can start.
205
- 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")
206
226
  break;
207
227
  }
208
228
  });
@@ -247,6 +267,53 @@ export class HostLoadGovernor {
247
267
  }));
248
268
  }
249
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
+ }
250
317
  readSignals() {
251
318
  const snapshot = this.options.load.current();
252
319
  const cpu = snapshot?.systemPressure?.cpu?.some;
@@ -332,6 +399,10 @@ export class HostLoadGovernor {
332
399
  this.waiters.splice(index, 1);
333
400
  if (this.waiters.length === 0)
334
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;
335
406
  complete();
336
407
  }
337
408
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
@@ -447,6 +518,17 @@ export class HostLoadGovernor {
447
518
  // The tree recorded on the token (supervised builds, installs) is stopped and checked.
448
519
  ?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
449
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);
450
532
  }
451
533
  /**
452
534
  * Attempt teardown stopped the attempt's processes (its process supervisor
@@ -517,3 +599,34 @@ function abortError(signal) {
517
599
  error.name = "AbortError";
518
600
  return error;
519
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
+ }
@@ -18,16 +18,34 @@ export interface HostOwnCgroupLoad {
18
18
  /** All memory charged to the unit (`memory.current`), including page cache. */
19
19
  readonly memoryChargedBytes: number | null;
20
20
  }
21
+ /**
22
+ * Where `systemPressure` comes from: Linux PSI, or (decision 0021) an estimate
23
+ * of CPU `some` pressure from whole-host CPU use on Windows, which has no PSI.
24
+ */
25
+ export type HostLoadPressureSource = "psi" | "windows_estimate";
21
26
  /** Live host load. Reported in every heartbeat but never a material capability signal. */
22
27
  export interface HostLoadSnapshot {
23
28
  readonly sampledAt: string;
29
+ /**
30
+ * True when `systemPressure` carries a CPU pressure signal the governor gates on.
31
+ * The wire name predates decision 0021: on Windows the signal is an estimate
32
+ * (see `pressureSource`), and the static host fact `psiAvailable` stays false.
33
+ */
24
34
  readonly psiAvailable: boolean;
35
+ /** Null exactly when `psiAvailable` is false. */
36
+ readonly pressureSource: HostLoadPressureSource | null;
25
37
  readonly systemPressure: HostSystemPressure | null;
26
38
  /** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
27
39
  readonly ownCgroupDedicated: boolean;
28
40
  /** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
29
41
  readonly ownCgroup: HostOwnCgroupLoad | null;
30
42
  readonly memoryAvailableBytes: number | null;
43
+ /**
44
+ * Busy share (0-100) of all logical CPUs over the last sampling window: /proc/stat deltas
45
+ * on Linux, os.cpus() deltas on Windows. Null on the first sample, after a break in
46
+ * readings, and on other platforms. For display only; the governor gates on pressure.
47
+ */
48
+ readonly hostCpuPercent: number | null;
31
49
  }
32
50
  /** What the bridge service needs: static facts plus the latest cached load sample. */
33
51
  export interface HostLoadSource {
@@ -48,7 +66,7 @@ export interface HostLoadSource {
48
66
  */
49
67
  export interface HostCpuAttribution {
50
68
  readonly sampledAt: string;
51
- /** Busy cores on the whole host, from /proc/stat deltas. */
69
+ /** Busy cores on the whole host, from /proc/stat deltas (os.cpus() deltas on Windows). */
52
70
  readonly hostCoresInUse: number;
53
71
  /** Cores used by the bridge's dedicated cgroup; null when the cgroup is not dedicated. */
54
72
  readonly ownCoresInUse: number | null;
@@ -80,8 +98,9 @@ export interface HostLoadSamplerOptions {
80
98
  export declare const defaultHostLoadSampleIntervalMs = 5000;
81
99
  /**
82
100
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
83
- * latest snapshot. Every read is async and failure-tolerant: a host without PSI
84
- * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
101
+ * latest snapshot. Every read is async and failure-tolerant: a Linux host without
102
+ * PSI (old kernel, `psi=0`) or another non-Windows host reports `psiAvailable: false`
103
+ * and no pressure. Windows reports a CPU pressure estimate instead (decision 0021).
85
104
  */
86
105
  export declare class HostLoadSampler implements HostLoadSource {
87
106
  private readonly environment;
@@ -100,6 +119,8 @@ export declare class HostLoadSampler implements HostLoadSource {
100
119
  private hostCpuMark;
101
120
  private latestCpuAttribution;
102
121
  private latestMemoryHeadroom;
122
+ private windowsCpuMark;
123
+ private readonly windowsCpuPressure;
103
124
  private readonly forgeCgroups;
104
125
  private readonly sandboxCpu;
105
126
  constructor(options?: HostLoadSamplerOptions);
@@ -115,11 +136,20 @@ export declare class HostLoadSampler implements HostLoadSource {
115
136
  sample(): Promise<HostLoadSnapshot>;
116
137
  private startOnce;
117
138
  private readSnapshot;
139
+ /**
140
+ * Decision 0021: Windows has no PSI or cgroups. CPU pressure is estimated from
141
+ * whole-host CPU use between samples, and memory is available physical memory.
142
+ * The bridge's own share is not attributed, so external load stays unknown and
143
+ * Forge's work counts through reserved cost and the pressure gate (as on a Linux
144
+ * host whose bridge has no dedicated cgroup).
145
+ */
146
+ private readWindowsSnapshot;
118
147
  private readCgroupMemoryHeadroom;
119
148
  private readSystemPressure;
120
149
  private readOwnCgroup;
121
150
  private coresInUse;
122
- private readHostCoresInUse;
151
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
152
+ private readHostCpuUse;
123
153
  private readMemoryAvailable;
124
154
  private fallbackFreeMemory;
125
155
  private readPressure;
@@ -2,13 +2,15 @@ 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
4
  import { ForgeCgroupCpuMeter, readCgroupMemoryHeadroomBytes, } from "./host-load-forge-cgroups.js";
5
+ import { cpuTimeTotals, cpuUtilisation, WindowsCpuPressureEstimator, } from "./host-load-windows-cpu.js";
5
6
  export const defaultHostLoadSampleIntervalMs = 5_000;
6
7
  /** Samples kept for the governor's pressure streak (FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES is at most 60). */
7
8
  const retainedSampleCount = 64;
8
9
  /**
9
10
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
10
- * latest snapshot. Every read is async and failure-tolerant: a host without PSI
11
- * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
11
+ * latest snapshot. Every read is async and failure-tolerant: a Linux host without
12
+ * PSI (old kernel, `psi=0`) or another non-Windows host reports `psiAvailable: false`
13
+ * and no pressure. Windows reports a CPU pressure estimate instead (decision 0021).
12
14
  */
13
15
  export class HostLoadSampler {
14
16
  environment;
@@ -27,6 +29,8 @@ export class HostLoadSampler {
27
29
  hostCpuMark = null;
28
30
  latestCpuAttribution = null;
29
31
  latestMemoryHeadroom = null;
32
+ windowsCpuMark = null;
33
+ windowsCpuPressure = new WindowsCpuPressureEstimator();
30
34
  forgeCgroups;
31
35
  sandboxCpu;
32
36
  constructor(options = {}) {
@@ -77,6 +81,9 @@ export class HostLoadSampler {
77
81
  sample() {
78
82
  this.inFlight ??= this.readSnapshot()
79
83
  .then(snapshot => {
84
+ // A Windows reading that did not advance the CPU window returns the last snapshot.
85
+ if (snapshot === this.latest)
86
+ return snapshot;
80
87
  this.latest = snapshot;
81
88
  this.history.push(snapshot);
82
89
  if (this.history.length > retainedSampleCount)
@@ -104,13 +111,15 @@ export class HostLoadSampler {
104
111
  async readSnapshot() {
105
112
  const sampledAtMs = this.now();
106
113
  const monotonicMs = this.monotonicNow();
114
+ if (this.environment.platform === "win32")
115
+ return this.readWindowsSnapshot(sampledAtMs, monotonicMs);
107
116
  const linux = this.environment.platform === "linux";
108
- const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes, sandboxCores] = linux
117
+ const [systemPressure, ownCgroup, memoryAvailableBytes, hostCpu, cgroupMemoryHeadroomBytes, sandboxCores] = linux
109
118
  ? await Promise.all([
110
119
  this.readSystemPressure(),
111
120
  this.readOwnCgroup(monotonicMs),
112
121
  this.readMemoryAvailable(),
113
- this.readHostCoresInUse(),
122
+ this.readHostCpuUse(),
114
123
  this.readCgroupMemoryHeadroom(),
115
124
  Promise.resolve(this.forgeCgroups?.paths() ?? [])
116
125
  .then(paths => this.sandboxCpu.coresInUse(paths, monotonicMs)).catch(() => 0),
@@ -120,16 +129,54 @@ export class HostLoadSampler {
120
129
  // Docker sandbox CPU is Forge's own work, already counted through reserved cost.
121
130
  const ownCores = ownCgroup?.cpuCoresInUse ?? null;
122
131
  this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
123
- this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCores === null ? null : ownCores + sandboxCores);
132
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCpu === null ? null : roundCores(hostCpu.utilisation * hostCpu.cpuCount), ownCores === null ? null : ownCores + sandboxCores);
124
133
  return {
125
134
  sampledAt,
126
135
  psiAvailable: systemPressure !== null,
136
+ pressureSource: systemPressure !== null ? "psi" : null,
127
137
  systemPressure,
128
138
  ownCgroupDedicated: ownCgroup !== null,
129
139
  ownCgroup,
130
140
  memoryAvailableBytes,
141
+ hostCpuPercent: hostCpu === null ? null : hostCpuPercent(hostCpu.utilisation),
131
142
  };
132
143
  }
144
+ /**
145
+ * Decision 0021: Windows has no PSI or cgroups. CPU pressure is estimated from
146
+ * whole-host CPU use between samples, and memory is available physical memory.
147
+ * The bridge's own share is not attributed, so external load stays unknown and
148
+ * Forge's work counts through reserved cost and the pressure gate (as on a Linux
149
+ * host whose bridge has no dedicated cgroup).
150
+ */
151
+ readWindowsSnapshot(sampledAtMs, monotonicMs) {
152
+ let totals;
153
+ try {
154
+ totals = cpuTimeTotals(this.environment.cpus());
155
+ }
156
+ catch {
157
+ totals = null;
158
+ }
159
+ const previous = this.windowsCpuMark;
160
+ const sampledAt = new Date(sampledAtMs).toISOString();
161
+ if (this.latest && totals && previous && previous.totals.cpuCount === totals.cpuCount
162
+ && monotonicMs - previous.atMs < minimumWindowsCpuWindowMs) {
163
+ // Too soon after the last reading (start() right after a sample) for a stable delta:
164
+ // the window stays open and the last snapshot is returned as is. sample() does not
165
+ // record it again, so it never counts as another sample in the pressure streak.
166
+ return this.latest;
167
+ }
168
+ this.windowsCpuMark = totals ? { totals, atMs: monotonicMs } : null;
169
+ const elapsedMs = previous ? monotonicMs - previous.atMs : 0;
170
+ const utilisation = previous && elapsedMs > 0 ? cpuUtilisation(previous.totals, totals) : null;
171
+ // The first sample, or a break in readings (no times, a CPU count change, a counter
172
+ // reset), reports no pressure and restarts the averages from the next window.
173
+ if (utilisation === null)
174
+ this.windowsCpuPressure.reset();
175
+ const cpu = utilisation === null ? null : this.windowsCpuPressure.update(utilisation, elapsedMs);
176
+ this.latestMemoryHeadroom = null;
177
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, utilisation !== null && totals ? roundCores(utilisation * totals.cpuCount) : null, null);
178
+ return windowsSnapshot(sampledAt, cpu, this.fallbackFreeMemory(), utilisation === null ? null : hostCpuPercent(utilisation));
179
+ }
133
180
  async readCgroupMemoryHeadroom() {
134
181
  const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
135
182
  const cgroupPath = membership ? parseUnifiedCgroupMembership(membership) : null;
@@ -185,7 +232,8 @@ export class HostLoadSampler {
185
232
  return null;
186
233
  return roundCores(usedUsec / elapsedUsec);
187
234
  }
188
- async readHostCoresInUse() {
235
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
236
+ async readHostCpuUse() {
189
237
  const content = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "stat"));
190
238
  const totals = content ? parseProcStatCpuTotals(content) : null;
191
239
  const previous = this.hostCpuMark;
@@ -196,7 +244,7 @@ export class HostLoadSampler {
196
244
  const busyDelta = totals.busyTicks - previous.busyTicks;
197
245
  if (totalDelta <= 0 || busyDelta < 0)
198
246
  return null;
199
- return roundCores((busyDelta / totalDelta) * totals.cpuCount);
247
+ return { utilisation: Math.min(1, busyDelta / totalDelta), cpuCount: totals.cpuCount };
200
248
  }
201
249
  async readMemoryAvailable() {
202
250
  const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
@@ -216,9 +264,27 @@ export class HostLoadSampler {
216
264
  return content ? parsePressureStall(content) : null;
217
265
  }
218
266
  }
267
+ /** Windows CPU deltas shorter than this are too noisy to fold into the pressure estimate. */
268
+ const minimumWindowsCpuWindowMs = 250;
269
+ function windowsSnapshot(sampledAt, cpu, memoryAvailableBytes, cpuPercent) {
270
+ return {
271
+ sampledAt,
272
+ psiAvailable: cpu !== null,
273
+ pressureSource: cpu !== null ? "windows_estimate" : null,
274
+ systemPressure: cpu ? { cpu, memory: null, io: null } : null,
275
+ ownCgroupDedicated: false,
276
+ ownCgroup: null,
277
+ memoryAvailableBytes,
278
+ hostCpuPercent: cpuPercent,
279
+ };
280
+ }
219
281
  function roundCores(value) {
220
282
  return Math.round(value * 100) / 100;
221
283
  }
284
+ /** A 0-1 busy share as a percentage with two decimals. */
285
+ function hostCpuPercent(utilisation) {
286
+ return Math.round(Math.min(1, Math.max(0, utilisation)) * 10_000) / 100;
287
+ }
222
288
  function hostCpuAttribution(sampledAt, hostCoresInUse, ownCoresInUse) {
223
289
  if (hostCoresInUse === null)
224
290
  return null;
@@ -58,7 +58,9 @@ export interface ManagedCommandStepInput {
58
58
  /**
59
59
  * Maps a managed command to its class: `managed.<profile>` for verification
60
60
  * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
61
- * `managed.build` for build-producing commands, and `managed.command` otherwise.
61
+ * `managed.build` for build-producing commands, `managed.test` for a test run
62
+ * that reuses an earlier build, and `managed.command` otherwise. Only
63
+ * `managed.command` skips the host test slot (decision 0018).
62
64
  */
63
65
  export declare function classifyManagedCommand(input: ManagedCommandStepInput): HostLoadStepClassification;
64
66
  /**