@loucompanion/forge-bridge 0.1.4-dev.83728c550770 → 0.1.4-dev.866b33be3065

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 (104) hide show
  1. package/README.md +32 -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.service.d.ts +1 -1
  7. package/dist/bridge/bridge.service.js +4 -110
  8. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  9. package/dist/bridge/runner-host-capabilities.js +13 -0
  10. package/dist/cli/cli.service.d.ts +11 -0
  11. package/dist/cli/cli.service.js +80 -12
  12. package/dist/cli/local-config.d.ts +2 -0
  13. package/dist/cli/local-config.js +19 -3
  14. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  15. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  16. package/dist/runtime/docker-engine-probe.js +7 -0
  17. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  18. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  19. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  20. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  21. package/dist/runtime/host-facts.d.ts +2 -1
  22. package/dist/runtime/host-load-admission.d.ts +9 -2
  23. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  24. package/dist/runtime/host-load-child-environment.js +19 -10
  25. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  26. package/dist/runtime/host-load-governor-config.js +7 -0
  27. package/dist/runtime/host-load-governor.d.ts +10 -0
  28. package/dist/runtime/host-load-governor.js +125 -34
  29. package/dist/runtime/host-load-sampler.d.ts +34 -4
  30. package/dist/runtime/host-load-sampler.js +73 -7
  31. package/dist/runtime/host-load-step-class.d.ts +3 -1
  32. package/dist/runtime/host-load-step-class.js +60 -5
  33. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  34. package/dist/runtime/host-load-test-slot.js +81 -0
  35. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  36. package/dist/runtime/host-load-token-ledger.js +93 -61
  37. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  38. package/dist/runtime/host-load-windows-cpu.js +85 -0
  39. package/dist/runtime/host-runtime-lease.d.ts +2 -2
  40. package/dist/runtime/host-runtime-lease.js +9 -8
  41. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  42. package/dist/runtime/host-runtime-promotion.js +36 -0
  43. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  44. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  45. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  46. package/dist/sandbox/host-capacity-broker.js +23 -4
  47. package/dist/session/architect-waits.d.ts +2 -0
  48. package/dist/session/architect-waits.js +138 -0
  49. package/dist/session/managed-attempt-tools.d.ts +0 -7
  50. package/dist/session/managed-attempt-tools.js +51 -62
  51. package/dist/session/managed-command-host-load.d.ts +2 -0
  52. package/dist/session/managed-command-host-load.js +2 -1
  53. package/dist/session/phase-completion.artifacts.js +2 -1
  54. package/dist/session/phase-completion.runtime.js +1 -1
  55. package/dist/session/phase-completion.schemas.js +25 -23
  56. package/dist/session/phase-completion.validation.js +3 -1
  57. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  58. package/dist/session/pre-publication-native-postgres.js +111 -0
  59. package/dist/session/pre-publication-pass.d.ts +61 -0
  60. package/dist/session/pre-publication-pass.js +148 -0
  61. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  62. package/dist/session/pre-publication-step-execution.js +6 -5
  63. package/dist/session/pre-publication-validation.d.ts +30 -14
  64. package/dist/session/pre-publication-validation.js +207 -134
  65. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  66. package/dist/session/provider-cli/claude-background-work.js +180 -0
  67. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  68. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  69. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  70. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  71. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  72. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  73. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  74. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  75. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  76. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  77. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  78. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -7
  79. package/dist/session/provider-cli/provider-cli.service.js +66 -243
  80. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  81. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  82. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  83. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  84. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  85. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  86. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  87. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  88. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  89. package/dist/session/provider-cli/provider-output-state.js +6 -0
  90. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  91. package/dist/session/qa-sidecar-validation.js +28 -0
  92. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  93. package/dist/session/session-redaction.js +31 -181
  94. package/dist/session/session.types.js +3 -3
  95. package/dist/session/sidecar-json-shape.d.ts +31 -0
  96. package/dist/session/sidecar-json-shape.js +217 -0
  97. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  98. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  99. package/dist/shared/process/windows-launch.d.ts +18 -0
  100. package/dist/shared/process/windows-launch.js +68 -0
  101. package/dist/shared/provider-capabilities.js +5 -6
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { HostLoadGovernor } from "./host-load-governor.js";
3
- import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
3
+ import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
4
4
  import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
5
5
  import { HostLoadSampler } from "./host-load-sampler.js";
6
6
  // How a process the bridge starts (the completion MCP server, which runs
@@ -9,12 +9,16 @@ import { HostLoadSampler } from "./host-load-sampler.js";
9
9
  // bridge's state root and every token counts against one host budget.
10
10
  export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
11
11
  export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
12
+ export const hostLoadTestSlotsEnvironment = "FORGE_HOST_LOAD_TEST_SLOTS";
12
13
  const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
13
14
  /** True for the variables that carry the governor into a child process. */
14
15
  /**
15
16
  * A process environment with every host load governor variable removed
16
- * (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
17
- * the host ledger, or broker control, that their step's token is held in.
17
+ * (FORGE_HOST_LOAD_*, any case) and the governor turned off explicitly. A governed
18
+ * step's own processes must never join the host ledger, or broker control, that
19
+ * their step's token is held in; since the host test slot is on by default
20
+ * (decision 0018), removing the variables alone would not keep a nested Forge
21
+ * process out.
18
22
  */
19
23
  export function withoutHostLoadGovernorVariables(environment) {
20
24
  const kept = {};
@@ -22,6 +26,8 @@ export function withoutHostLoadGovernorVariables(environment) {
22
26
  if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
23
27
  kept[name] = value;
24
28
  }
29
+ kept[hostLoadGovernorEnvironment] = "off";
30
+ kept[hostLoadTestSlotsEnvironment] = "0";
25
31
  return kept;
26
32
  }
27
33
  // Decision 0014 operator ceilings the child's governor applies itself (host-load-governor-config.ts).
@@ -30,30 +36,33 @@ export function isHostLoadChildEnvironmentName(name) {
30
36
  return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment || hostCeilingEnvironmentNames.has(name);
31
37
  }
32
38
  /**
33
- * The variables a child needs to share this bridge's ledger: the flag, the
34
- * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
35
- * unit. Empty with the governor off, so the child stays ungoverned.
39
+ * The variables a child needs to share this bridge's ledger: the budget flag and
40
+ * the host test slot count as this bridge resolved them, the state root, the
41
+ * operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup unit. Empty with
42
+ * the governor off, so the child stays ungoverned.
36
43
  */
37
44
  export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
38
- if (loadHostLoadGovernorConfig(environment).mode !== "on")
45
+ const config = loadHostLoadGovernorConfig(environment);
46
+ if (!hostLoadGovernorEnabled(config))
39
47
  return {};
40
48
  const forwarded = {};
41
49
  for (const [name, value] of Object.entries(environment)) {
42
50
  if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
43
51
  forwarded[name] = value;
44
52
  }
45
- forwarded[hostLoadGovernorEnvironment] = "on";
53
+ forwarded[hostLoadGovernorEnvironment] = config.mode;
54
+ forwarded[hostLoadTestSlotsEnvironment] = String(config.testSlots);
46
55
  forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
47
56
  return forwarded;
48
57
  }
49
58
  /**
50
59
  * The governor a child process uses, from the variables above. Undefined when
51
- * the flag is off or no state root was handed over: the child is ungoverned.
60
+ * the governor is off or no state root was handed over: the child is ungoverned.
52
61
  */
53
62
  export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
54
63
  const config = loadHostLoadGovernorConfig(environment);
55
64
  const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
56
- if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
65
+ if (!hostLoadGovernorEnabled(config) || !stateRoot || !path.isAbsolute(stateRoot))
57
66
  return undefined;
58
67
  return new HostLoadGovernor({
59
68
  stateRoot,
@@ -1,7 +1,13 @@
1
1
  export type HostLoadGovernorMode = "on" | "off";
2
2
  export interface HostLoadGovernorConfig {
3
- /** FORGE_HOST_LOAD_GOVERNOR. Off by default in this step; `off` is the operator override. */
3
+ /** FORGE_HOST_LOAD_GOVERNOR: the CPU and memory budget. Off by default; `off` is the operator override. */
4
4
  readonly mode: HostLoadGovernorMode;
5
+ /**
6
+ * FORGE_HOST_LOAD_TEST_SLOTS (decision 0018): how many heavy steps (builds, test runs,
7
+ * Playwright, the runtime build) run at once on the host, whatever the budget says.
8
+ * 1 by default; 0 turns the slot off, and with the budget off too the governor is off.
9
+ */
10
+ readonly testSlots: number;
5
11
  /** Share of logical CPUs Forge may reserve for heavy steps. */
6
12
  readonly cpuBudgetFraction: number;
7
13
  /** Memory kept free for the rest of the host, taken off MemAvailable. */
@@ -38,6 +44,9 @@ export interface HostLoadGovernorConfig {
38
44
  readonly cpuBudgetCeilingFraction?: number | null;
39
45
  readonly maxHeavyStepsCeiling?: number | null;
40
46
  }
47
+ export declare const defaultHostTestSlots = 1;
41
48
  export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
42
49
  export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
50
+ /** The governor admits steps when either rule is on: the host test slot or the budget. */
51
+ export declare function hostLoadGovernorEnabled(config: Pick<HostLoadGovernorConfig, "mode" | "testSlots">): boolean;
43
52
  export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;
@@ -1,6 +1,8 @@
1
1
  import { defaultHostLoadSampleIntervalMs } from "./host-load-sampler.js";
2
+ export const defaultHostTestSlots = 1;
2
3
  export const defaultHostLoadGovernorConfig = {
3
4
  mode: "off",
5
+ testSlots: defaultHostTestSlots,
4
6
  cpuBudgetFraction: 0.8,
5
7
  memoryReserveBytes: 1024 ** 3,
6
8
  cpuPressureThreshold: 50,
@@ -19,10 +21,15 @@ export function parseHostLoadGovernorMode(value) {
19
21
  const normalized = value?.trim().toLowerCase() ?? "";
20
22
  return normalized === "on" || normalized === "true" || normalized === "1" ? "on" : "off";
21
23
  }
24
+ /** The governor admits steps when either rule is on: the host test slot or the budget. */
25
+ export function hostLoadGovernorEnabled(config) {
26
+ return config.mode === "on" || config.testSlots > 0;
27
+ }
22
28
  export function loadHostLoadGovernorConfig(environment = process.env) {
23
29
  const defaults = defaultHostLoadGovernorConfig;
24
30
  return {
25
31
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
32
+ testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
26
33
  cpuBudgetFraction: bounded(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, defaults.cpuBudgetFraction, 0.05, 1),
27
34
  memoryReserveBytes: bounded(environment.FORGE_HOST_LOAD_MEMORY_RESERVE_BYTES, defaults.memoryReserveBytes, 0, 1024 ** 4),
28
35
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
@@ -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;
@@ -123,6 +125,14 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
123
125
  };
124
126
  private drain;
125
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;
126
136
  private readSignals;
127
137
  /**
128
138
  * Consecutive pressured samples ending with the latest one, read from the
@@ -1,10 +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";
7
8
  import { HostLoadRuntimeSettingsReader } from "./host-load-runtime-settings.js";
9
+ import { decideHostTestSlot, takesHostTestSlot } from "./host-load-test-slot.js";
8
10
  import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
9
11
  import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
10
12
  export class HostCapacityTimeoutError extends ForgeFailureError {
@@ -26,6 +28,8 @@ export class HostCapacityTimeoutError extends ForgeFailureError {
26
28
  * overtake an unfit head until the head has waited past the anti-starvation
27
29
  * window. Running steps are never preempted. Reserved cost comes from the
28
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.
29
33
  */
30
34
  export class HostLoadGovernor {
31
35
  options;
@@ -45,7 +49,7 @@ export class HostLoadGovernor {
45
49
  constructor(options) {
46
50
  this.options = options;
47
51
  this.config = options.config ?? loadHostLoadGovernorConfig();
48
- this.enabled = this.config.mode === "on";
52
+ this.enabled = hostLoadGovernorEnabled(this.config);
49
53
  this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
50
54
  this.ledger = new HostLoadTokenLedger({
51
55
  stateRoot: options.stateRoot,
@@ -57,18 +61,27 @@ export class HostLoadGovernor {
57
61
  suspendedMs: options.suspendedMs,
58
62
  // Every ledger transaction renews the steps this governor is running.
59
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] : []),
60
66
  });
61
67
  }
62
68
  get maxWaitMs() {
63
69
  return this.config.maxWaitMs;
64
70
  }
65
71
  async acquire(request, options = {}) {
66
- if (!this.enabled)
67
- 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
+ }
68
75
  const { signal } = options;
69
76
  if (signal?.aborted)
70
77
  throw abortError(signal);
71
- 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);
72
85
  if (signal?.aborted)
73
86
  throw abortError(signal);
74
87
  return await new Promise((resolve, reject) => {
@@ -83,6 +96,16 @@ export class HostLoadGovernor {
83
96
  deadline: null,
84
97
  lastDecision: null,
85
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,
86
109
  };
87
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);
88
111
  waiter.deadline.unref?.();
@@ -177,46 +200,29 @@ export class HostLoadGovernor {
177
200
  async drainOnce() {
178
201
  if (this.waiters.length === 0)
179
202
  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);
203
+ const budget = this.config.mode === "on" ? await this.budgetPass() : null;
187
204
  if (this.waiters.length === 0)
188
205
  return;
189
- const signals = this.readSignals();
190
- const logicalCpus = this.logicalCpus();
191
206
  const nowMs = monotonicNowMs();
192
207
  const outcomes = [];
193
208
  const outcome = await this.ledger.transaction(transaction => {
194
- const runningMemoryBytes = this.runningStepsMemoryBytes(transaction.tokens);
209
+ const runningMemoryBytes = budget ? this.runningStepsMemoryBytes(transaction.tokens) : 0;
195
210
  const head = this.waiters[0];
196
211
  const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
197
212
  for (const waiter of this.waiters) {
198
213
  if (waiter.settled)
199
214
  continue;
200
- const computed = decideHostLoadAdmission({
201
- request: waiter.request.cost,
202
- running: transaction.tokens.map(token => token.cost),
203
- runningMemoryBytes,
204
- logicalCpus,
205
- signals,
206
- config,
207
- maxHeavySteps,
208
- });
209
- const decision = transaction.recoveringUntil
210
- ? {
211
- ...computed,
212
- admitted: false,
213
- reason: "ledger_recovering",
214
- detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
215
- }
216
- : 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
+ }
217
221
  outcomes.push({ waiter, decision, token: decision.admitted ? transaction.issue(waiter.request) : null });
218
- // A starving head blocks the queue so running steps drain and it can start.
219
- 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")
220
226
  break;
221
227
  }
222
228
  });
@@ -261,6 +267,53 @@ export class HostLoadGovernor {
261
267
  }));
262
268
  }
263
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
+ }
264
317
  readSignals() {
265
318
  const snapshot = this.options.load.current();
266
319
  const cpu = snapshot?.systemPressure?.cpu?.some;
@@ -346,6 +399,10 @@ export class HostLoadGovernor {
346
399
  this.waiters.splice(index, 1);
347
400
  if (this.waiters.length === 0)
348
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;
349
406
  complete();
350
407
  }
351
408
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
@@ -461,6 +518,17 @@ export class HostLoadGovernor {
461
518
  // The tree recorded on the token (supervised builds, installs) is stopped and checked.
462
519
  ?? (entry.token.stepProcess ? async () => await terminate(entry.token.stepProcess) : "attempt_teardown");
463
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);
464
532
  }
465
533
  /**
466
534
  * Attempt teardown stopped the attempt's processes (its process supervisor
@@ -539,3 +607,26 @@ function lowestLimit(a, b) {
539
607
  return a;
540
608
  return Math.min(a, b);
541
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
+ }
@@ -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
  /**