@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.efc418893964

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 (136) hide show
  1. package/README.md +56 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +71 -2
  8. package/dist/bridge/bridge.service.js +282 -114
  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 +132 -14
  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 +138 -6
  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 +59 -3
  52. package/dist/runtime/host-runtime-lease.js +209 -58
  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/playwright-host-runtime-adapter.d.ts +7 -0
  58. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  59. package/dist/runtime/runner-settings.d.ts +100 -0
  60. package/dist/runtime/runner-settings.js +214 -0
  61. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  62. package/dist/sandbox/host-capacity-broker.js +23 -4
  63. package/dist/session/architect-waits.d.ts +2 -0
  64. package/dist/session/architect-waits.js +138 -0
  65. package/dist/session/managed-attempt-tools.d.ts +0 -7
  66. package/dist/session/managed-attempt-tools.js +51 -62
  67. package/dist/session/managed-command-host-load.d.ts +2 -0
  68. package/dist/session/managed-command-host-load.js +2 -1
  69. package/dist/session/phase-completion.artifacts.js +2 -1
  70. package/dist/session/phase-completion.d.ts +8 -0
  71. package/dist/session/phase-completion.js +1 -0
  72. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  73. package/dist/session/phase-completion.mcp-args.js +156 -0
  74. package/dist/session/phase-completion.runtime.d.ts +0 -8
  75. package/dist/session/phase-completion.runtime.js +43 -197
  76. package/dist/session/phase-completion.schemas.js +25 -23
  77. package/dist/session/phase-completion.validation.js +3 -1
  78. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  79. package/dist/session/pre-publication-native-postgres.js +111 -0
  80. package/dist/session/pre-publication-pass.d.ts +61 -0
  81. package/dist/session/pre-publication-pass.js +148 -0
  82. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  83. package/dist/session/pre-publication-step-execution.js +6 -5
  84. package/dist/session/pre-publication-validation.d.ts +30 -14
  85. package/dist/session/pre-publication-validation.js +207 -134
  86. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  87. package/dist/session/provider-cli/claude-background-work.js +181 -0
  88. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  89. package/dist/session/provider-cli/host-build-lock.js +30 -0
  90. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  91. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  92. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  93. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  94. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  95. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  96. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  97. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  98. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  99. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  100. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  101. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  102. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  103. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  104. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  105. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  106. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  107. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  108. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  109. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  110. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  111. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  112. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  113. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  114. package/dist/session/provider-cli/provider-output-state.js +6 -0
  115. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  116. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  117. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  118. package/dist/session/qa-sidecar-validation.js +28 -0
  119. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  120. package/dist/session/session-redaction.js +31 -181
  121. package/dist/session/session.base.d.ts +6 -1
  122. package/dist/session/session.service.d.ts +7 -2
  123. package/dist/session/session.service.js +100 -2
  124. package/dist/session/session.types.js +4 -4
  125. package/dist/session/sidecar-json-shape.d.ts +31 -0
  126. package/dist/session/sidecar-json-shape.js +217 -0
  127. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  128. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  129. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  130. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  131. package/dist/shared/process/windows-launch.d.ts +18 -0
  132. package/dist/shared/process/windows-launch.js +68 -0
  133. package/dist/shared/provider-capabilities.js +14 -7
  134. package/dist/version.d.ts +1 -1
  135. package/dist/version.js +1 -1
  136. 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,36 +26,43 @@ 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
  }
33
+ // Decision 0014 operator ceilings the child's governor applies itself (host-load-governor-config.ts).
34
+ const hostCeilingEnvironmentNames = new Set(["FORGE_HOST_CPU_BUDGET_PERCENT", "FORGE_HOST_MAX_HEAVY_STEPS"]);
27
35
  export function isHostLoadChildEnvironmentName(name) {
28
- return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment;
36
+ return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment || hostCeilingEnvironmentNames.has(name);
29
37
  }
30
38
  /**
31
- * The variables a child needs to share this bridge's ledger: the flag, the
32
- * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
33
- * 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.
34
43
  */
35
44
  export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
36
- if (loadHostLoadGovernorConfig(environment).mode !== "on")
45
+ const config = loadHostLoadGovernorConfig(environment);
46
+ if (!hostLoadGovernorEnabled(config))
37
47
  return {};
38
48
  const forwarded = {};
39
49
  for (const [name, value] of Object.entries(environment)) {
40
50
  if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
41
51
  forwarded[name] = value;
42
52
  }
43
- forwarded[hostLoadGovernorEnvironment] = "on";
53
+ forwarded[hostLoadGovernorEnvironment] = config.mode;
54
+ forwarded[hostLoadTestSlotsEnvironment] = String(config.testSlots);
44
55
  forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
45
56
  return forwarded;
46
57
  }
47
58
  /**
48
59
  * The governor a child process uses, from the variables above. Undefined when
49
- * 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.
50
61
  */
51
62
  export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
52
63
  const config = loadHostLoadGovernorConfig(environment);
53
64
  const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
54
- if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
65
+ if (!hostLoadGovernorEnabled(config) || !stateRoot || !path.isAbsolute(stateRoot))
55
66
  return undefined;
56
67
  return new HostLoadGovernor({
57
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. */
@@ -28,7 +34,19 @@ export interface HostLoadGovernorConfig {
28
34
  readonly sampleIntervalMs: number;
29
35
  /** Without a dedicated cgroup, a step this old is assumed to use its reserved memory. */
30
36
  readonly memoryRampMs: number;
37
+ /**
38
+ * Decision 0014 operator ceilings, applied by every governor itself so they hold even
39
+ * without the bridge's runtime settings file (before its first write, after a failed
40
+ * write, or a file that can't be read): the lower of FORGE_HOST_CPU_BUDGET_PERCENT (as a
41
+ * fraction) and an explicitly set FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, and
42
+ * FORGE_HOST_MAX_HEAVY_STEPS. Null when unset.
43
+ */
44
+ readonly cpuBudgetCeilingFraction?: number | null;
45
+ readonly maxHeavyStepsCeiling?: number | null;
31
46
  }
47
+ export declare const defaultHostTestSlots = 1;
32
48
  export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
33
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;
34
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),
@@ -36,8 +43,38 @@ export function loadHostLoadGovernorConfig(environment = process.env) {
36
43
  sampleStaleMs: defaults.sampleStaleMs,
37
44
  sampleIntervalMs: defaults.sampleIntervalMs,
38
45
  memoryRampMs: defaults.memoryRampMs,
46
+ cpuBudgetCeilingFraction: lowestFraction(optionalCpuPercentFraction(environment.FORGE_HOST_CPU_BUDGET_PERCENT), optionalFraction(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION)),
47
+ maxHeavyStepsCeiling: optionalHeavySteps(environment.FORGE_HOST_MAX_HEAVY_STEPS),
39
48
  };
40
49
  }
50
+ /** Matches runner-settings' parse of FORGE_HOST_CPU_BUDGET_PERCENT (Number, 10-100); unparsable is unset. */
51
+ function optionalCpuPercentFraction(raw) {
52
+ if (raw === undefined || raw.trim() === "")
53
+ return null;
54
+ const value = Number(raw);
55
+ return Number.isFinite(value) ? Math.min(100, Math.max(10, value)) / 100 : null;
56
+ }
57
+ /** An explicitly set FORGE_HOST_LOAD_CPU_BUDGET_FRACTION is a ceiling too (runner-settings' cpuBudgetCeilings). */
58
+ function optionalFraction(raw) {
59
+ if (raw === undefined || raw.trim() === "")
60
+ return null;
61
+ const value = Number(raw);
62
+ return Number.isFinite(value) ? Math.min(1, Math.max(0.05, value)) : null;
63
+ }
64
+ function lowestFraction(a, b) {
65
+ if (a === null)
66
+ return b;
67
+ if (b === null)
68
+ return a;
69
+ return Math.min(a, b);
70
+ }
71
+ /** Matches runner-settings' parse of FORGE_HOST_MAX_HEAVY_STEPS (parseInt, 1-64); unparsable is unset. */
72
+ function optionalHeavySteps(raw) {
73
+ if (raw === undefined || raw.trim() === "")
74
+ return null;
75
+ const value = Number.parseInt(raw, 10);
76
+ return Number.isFinite(value) ? Math.min(64, Math.max(1, value)) : null;
77
+ }
41
78
  function bounded(raw, fallback, minimum, maximum) {
42
79
  if (raw === undefined || raw.trim() === "")
43
80
  return fallback;
@@ -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;