@loucompanion/forge-bridge 0.2.1-dev.573a8a5fa582 → 0.2.1-dev.7171bf414613

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 (121) hide show
  1. package/README.md +38 -2
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +62 -92
  6. package/dist/bridge/bridge.types.d.ts +6 -0
  7. package/dist/bridge/default-session-service.d.ts +13 -0
  8. package/dist/bridge/default-session-service.js +22 -0
  9. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  10. package/dist/bridge/dispatch-offer-policy.js +58 -0
  11. package/dist/cleanup/cleanup-wip.js +3 -3
  12. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  13. package/dist/cleanup/forge-owned-paths.js +9 -0
  14. package/dist/cli/cli.help.js +1 -1
  15. package/dist/cli/cli.service.js +3 -3
  16. package/dist/cli/local-config.d.ts +2 -0
  17. package/dist/cli/local-config.js +3 -0
  18. package/dist/runtime/host-load-capacity.d.ts +198 -0
  19. package/dist/runtime/host-load-capacity.js +353 -0
  20. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  21. package/dist/runtime/host-load-child-environment.js +35 -1
  22. package/dist/runtime/host-load-governor-config.d.ts +23 -2
  23. package/dist/runtime/host-load-governor-config.js +20 -2
  24. package/dist/runtime/host-load-governor.d.ts +81 -1
  25. package/dist/runtime/host-load-governor.js +184 -15
  26. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  27. package/dist/runtime/host-load-live-test-slots.js +193 -0
  28. package/dist/runtime/host-load-sampler.d.ts +17 -0
  29. package/dist/runtime/host-load-sampler.js +24 -0
  30. package/dist/runtime/host-load-step-run.d.ts +37 -3
  31. package/dist/runtime/host-load-step-run.js +63 -7
  32. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  33. package/dist/runtime/host-load-test-slot.js +19 -7
  34. package/dist/sandbox/runtime.d.ts +1 -2
  35. package/dist/sandbox/runtime.js +7 -13
  36. package/dist/sandbox/sandbox-input.d.ts +22 -0
  37. package/dist/sandbox/sandbox-input.js +49 -0
  38. package/dist/sandbox/workspace.service.js +15 -2
  39. package/dist/session/managed-attempt-tools.js +6 -29
  40. package/dist/session/managed-build-receipt.d.ts +3 -1
  41. package/dist/session/managed-build-receipt.js +5 -2
  42. package/dist/session/managed-command-environment.d.ts +8 -0
  43. package/dist/session/managed-command-environment.js +28 -0
  44. package/dist/session/managed-command-host-load.d.ts +10 -5
  45. package/dist/session/managed-command-host-load.js +18 -14
  46. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  47. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  48. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  49. package/dist/session/phase-completion.artifacts.js +63 -165
  50. package/dist/session/phase-completion.d.ts +25 -2
  51. package/dist/session/phase-completion.helpers.js +5 -53
  52. package/dist/session/phase-completion.js +15 -32
  53. package/dist/session/phase-completion.mcp-args.js +69 -2
  54. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  55. package/dist/session/phase-completion.phase-aliases.js +43 -0
  56. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  57. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  58. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  59. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  60. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  61. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  62. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  63. package/dist/session/phase-completion.pr-review.js +294 -0
  64. package/dist/session/phase-completion.prompts.d.ts +1 -1
  65. package/dist/session/phase-completion.prompts.js +14 -0
  66. package/dist/session/phase-completion.runtime.js +9 -3
  67. package/dist/session/phase-completion.schemas.js +12 -2
  68. package/dist/session/phase-completion.validation.d.ts +1 -0
  69. package/dist/session/phase-completion.validation.js +9 -1
  70. package/dist/session/pr-review-diff-base.d.ts +18 -0
  71. package/dist/session/pr-review-diff-base.js +45 -0
  72. package/dist/session/pr-review-placement.d.ts +50 -0
  73. package/dist/session/pr-review-placement.js +91 -0
  74. package/dist/session/pre-publication-change-set.d.ts +62 -0
  75. package/dist/session/pre-publication-change-set.js +166 -0
  76. package/dist/session/pre-publication-host-load.js +6 -5
  77. package/dist/session/pre-publication-process.js +3 -2
  78. package/dist/session/pre-publication-validation.d.ts +2 -1
  79. package/dist/session/pre-publication-validation.js +31 -36
  80. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  81. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  82. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  83. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  84. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  85. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  86. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  87. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  88. package/dist/session/provider-cli/pre-publication-repair.js +7 -3
  89. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  90. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  91. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  92. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  93. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  94. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -13
  95. package/dist/session/provider-cli/provider-cli.prompts.js +123 -107
  96. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  97. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  98. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  99. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  100. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  101. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  102. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  103. package/dist/session/provider-cli/provider-cli.service.js +24 -139
  104. package/dist/session/sandbox-host-capacity-gate.js +28 -6
  105. package/dist/session/session.parse-helpers.d.ts +10 -0
  106. package/dist/session/session.parse-helpers.js +84 -0
  107. package/dist/session/session.runtime-refresh.d.ts +46 -0
  108. package/dist/session/session.runtime-refresh.js +116 -0
  109. package/dist/session/session.service.d.ts +2 -1
  110. package/dist/session/session.service.js +40 -95
  111. package/dist/session/session.types.d.ts +4 -0
  112. package/dist/session/session.types.js +7 -77
  113. package/dist/session/session.types.pr-review.d.ts +59 -0
  114. package/dist/session/session.types.pr-review.js +53 -0
  115. package/dist/version.d.ts +1 -1
  116. package/dist/version.js +1 -1
  117. package/dist/worktree/artifact-injector.js +24 -0
  118. package/dist/worktree/worktree.service.d.ts +22 -0
  119. package/dist/worktree/worktree.service.js +116 -12
  120. package/dist/worktree/worktree.types.d.ts +7 -0
  121. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import path from "node:path";
2
+ import { detectHostCapacitySpec, testParallelClassesPerSlot } from "./host-load-capacity.js";
2
3
  import { HostLoadGovernor } from "./host-load-governor.js";
3
4
  import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
4
5
  import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
@@ -51,10 +52,43 @@ export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
51
52
  forwarded[name] = value;
52
53
  }
53
54
  forwarded[hostLoadGovernorEnvironment] = config.mode;
54
- forwarded[hostLoadTestSlotsEnvironment] = String(config.testSlots);
55
+ // The operator's count is handed over as resolved. An auto-sized count is not: the child
56
+ // sizes the same host itself and keeps it labelled auto, with live adjustment of its own.
57
+ if (config.testSlotsSource === "auto")
58
+ delete forwarded[hostLoadTestSlotsEnvironment];
59
+ else
60
+ forwarded[hostLoadTestSlotsEnvironment] = String(config.testSlots);
55
61
  forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
56
62
  return forwarded;
57
63
  }
64
+ export const testMaxParallelClassesEnvironment = "FORGE_TEST_MAX_PARALLEL_CLASSES";
65
+ // hostRuntimeTestPostgresAdminEnvironment (host-runtime-contract.ts): set when the step's tests use
66
+ // the native PostgreSQL fallback, whose classes cost more memory each.
67
+ const testPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
68
+ /**
69
+ * A governed step's environment plus FORGE_TEST_MAX_PARALLEL_CLASSES sized for one host test
70
+ * slot's share of the machine, when the host runs more than one heavy step at once: two .NET
71
+ * suites must not each size their test-class parallelism for the whole host. A value the step
72
+ * or the operator set is kept, and with one slot nothing is added (the framework's own default
73
+ * already fits). The share uses the configured slot count, not the live one: a suite keeps the
74
+ * parallelism it started with, and a busy host is no reason to give it more.
75
+ *
76
+ * @param governorEnvironment where the slot count is read (the bridge's or MCP server's own).
77
+ */
78
+ export function withHostTestParallelism(environment, governorEnvironment = process.env, host = detectHostCapacitySpec()) {
79
+ if (namedValue(environment, testMaxParallelClassesEnvironment) !== undefined || !host)
80
+ return environment;
81
+ const config = loadHostLoadGovernorConfig(governorEnvironment, host);
82
+ // The step's own environment decides: prePublicationChildEnvironment strips the admin connection
83
+ // from a step that runs in container mode, even when the governor's process has one.
84
+ const native = namedValue(environment, testPostgresAdminEnvironment) !== undefined;
85
+ const classes = config.testSlots > 1 ? testParallelClassesPerSlot(host, config.testSlots, native) : null;
86
+ return classes === null ? environment : { ...environment, [testMaxParallelClassesEnvironment]: String(classes) };
87
+ }
88
+ /** A non-empty variable, matched without case (Windows environment names are case-insensitive). */
89
+ function namedValue(environment, wanted) {
90
+ return Object.entries(environment).find(([name, value]) => name.toUpperCase() === wanted && Boolean(value?.trim()))?.[1];
91
+ }
58
92
  /**
59
93
  * The governor a child process uses, from the variables above. Undefined when
60
94
  * the governor is off or no state root was handed over: the child is ungoverned.
@@ -1,3 +1,4 @@
1
+ import { type HostCapacitySpec, type HostTestSlotsSource } from "./host-load-capacity.js";
1
2
  export type HostLoadGovernorMode = "on" | "off";
2
3
  export interface HostLoadGovernorConfig {
3
4
  /** FORGE_HOST_LOAD_GOVERNOR: the CPU and memory budget. Off by default; `off` is the operator override. */
@@ -5,9 +6,21 @@ export interface HostLoadGovernorConfig {
5
6
  /**
6
7
  * FORGE_HOST_LOAD_TEST_SLOTS (decision 0018): how many heavy steps (builds, test runs,
7
8
  * 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
+ * Unset, it is sized from the host's CPUs and memory (1 to 4); an explicit value is the
10
+ * operator's override. 0 turns the slot off, and with the budget off too the governor is off.
9
11
  */
10
12
  readonly testSlots: number;
13
+ /** Where testSlots came from, and how it was chosen (for logs and wait messages). Absent: a fixed count. */
14
+ readonly testSlotsSource?: HostTestSlotsSource;
15
+ readonly testSlotsDetail?: string;
16
+ /** The host the slots were sized for; live adjustment reads it too. */
17
+ readonly hostCapacity?: HostCapacitySpec | null;
18
+ /**
19
+ * Lower the slot count while other work on the host needs the machine, and raise it again
20
+ * slowly (host-load-capacity.ts). loadHostLoadGovernorConfig turns it on unless
21
+ * FORGE_HOST_LOAD_LIVE_SLOTS=off; absent means off.
22
+ */
23
+ readonly liveTestSlots?: boolean;
11
24
  /** Share of logical CPUs Forge may reserve for heavy steps. */
12
25
  readonly cpuBudgetFraction: number;
13
26
  /** Memory kept free for the rest of the host, taken off MemAvailable. */
@@ -53,9 +66,17 @@ export interface HostLoadGovernorConfig {
53
66
  readonly cpuBudgetCeilingFraction?: number | null;
54
67
  readonly maxHeavyStepsCeiling?: number | null;
55
68
  }
69
+ /**
70
+ * The fixed count in defaultHostLoadGovernorConfig, which is not sized for any host: a running
71
+ * governor's config comes from loadHostLoadGovernorConfig, which sizes the slots from the host.
72
+ */
56
73
  export declare const defaultHostTestSlots = 1;
57
74
  export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
58
75
  export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
59
76
  /** The governor admits steps when either rule is on: the host test slot or the budget. */
60
77
  export declare function hostLoadGovernorEnabled(config: Pick<HostLoadGovernorConfig, "mode" | "testSlots">): boolean;
61
- export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;
78
+ /**
79
+ * @param host the host the test slots are sized for, detected from this machine by default.
80
+ * Null means it could not be read: an unset FORGE_HOST_LOAD_TEST_SLOTS then means 1.
81
+ */
82
+ export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>, host?: HostCapacitySpec | null): HostLoadGovernorConfig;
@@ -1,4 +1,9 @@
1
+ import { detectHostCapacitySpec, resolveHostTestSlots, } from "./host-load-capacity.js";
1
2
  import { defaultHostLoadSampleIntervalMs } from "./host-load-sampler.js";
3
+ /**
4
+ * The fixed count in defaultHostLoadGovernorConfig, which is not sized for any host: a running
5
+ * governor's config comes from loadHostLoadGovernorConfig, which sizes the slots from the host.
6
+ */
2
7
  export const defaultHostTestSlots = 1;
3
8
  export const defaultHostLoadGovernorConfig = {
4
9
  mode: "off",
@@ -26,12 +31,21 @@ export function parseHostLoadGovernorMode(value) {
26
31
  export function hostLoadGovernorEnabled(config) {
27
32
  return config.mode === "on" || config.testSlots > 0;
28
33
  }
29
- export function loadHostLoadGovernorConfig(environment = process.env) {
34
+ /**
35
+ * @param host the host the test slots are sized for, detected from this machine by default.
36
+ * Null means it could not be read: an unset FORGE_HOST_LOAD_TEST_SLOTS then means 1.
37
+ */
38
+ export function loadHostLoadGovernorConfig(environment = process.env, host = detectHostCapacitySpec()) {
30
39
  const defaults = defaultHostLoadGovernorConfig;
31
40
  const maxWaitMs = bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000);
41
+ const testSlots = resolveHostTestSlots(environment.FORGE_HOST_LOAD_TEST_SLOTS, host);
32
42
  return {
33
43
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
34
- testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
44
+ testSlots: testSlots.slots,
45
+ testSlotsSource: testSlots.source,
46
+ testSlotsDetail: testSlots.detail,
47
+ hostCapacity: host,
48
+ liveTestSlots: !isOff(environment.FORGE_HOST_LOAD_LIVE_SLOTS),
35
49
  cpuBudgetFraction: bounded(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, defaults.cpuBudgetFraction, 0.05, 1),
36
50
  memoryReserveBytes: bounded(environment.FORGE_HOST_LOAD_MEMORY_RESERVE_BYTES, defaults.memoryReserveBytes, 0, 1024 ** 4),
37
51
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
@@ -78,6 +92,10 @@ function optionalHeavySteps(raw) {
78
92
  const value = Number.parseInt(raw, 10);
79
93
  return Number.isFinite(value) ? Math.min(64, Math.max(1, value)) : null;
80
94
  }
95
+ function isOff(raw) {
96
+ const normalized = raw?.trim().toLowerCase() ?? "";
97
+ return normalized === "off" || normalized === "false" || normalized === "0";
98
+ }
81
99
  function bounded(raw, fallback, minimum, maximum) {
82
100
  if (raw === undefined || raw.trim() === "")
83
101
  return fallback;
@@ -3,6 +3,7 @@ import { type HostLoadAdmissionDecision } from "./host-load-admission.js";
3
3
  import { type HostLoadGovernorConfig } from "./host-load-governor-config.js";
4
4
  import type { HostLoadGovernorSource } from "./host-load-sampler.js";
5
5
  import type { HostLoadStepCost } from "./host-load-step-class.js";
6
+ import { type HostTestSlotControllerOptions } from "./host-load-capacity.js";
6
7
  import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
7
8
  /** What HostLoadStepGate.attachProcess takes, so a gate's callers need only this module. */
8
9
  export type { HostLoadStepProcess } from "./host-load-step-reaper.js";
@@ -17,7 +18,10 @@ export interface HostLoadStepRequest {
17
18
  }
18
19
  export interface HostLoadAcquireOptions {
19
20
  readonly signal?: AbortSignal;
20
- /** Called once, when the first admission decision says the step must wait. */
21
+ /**
22
+ * Called when the first admission decision says the step must wait, and again whenever the
23
+ * wait changes (see `waitChanged`), so a waiting receipt never names a holder that is gone.
24
+ */
21
25
  readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
22
26
  }
23
27
  export interface HostLoadAdmission {
@@ -62,6 +66,24 @@ export declare class HostCapacityTimeoutError extends ForgeFailureError {
62
66
  readonly code = "host_capacity_timeout";
63
67
  constructor(stepClass: string, label: string, waitMs: number, detail: string);
64
68
  }
69
+ /** The host test slot count a governor works with, and why (HostLoadGovernor.testSlotCapacity). */
70
+ export interface HostTestSlotCapacity {
71
+ /** FORGE_HOST_LOAD_TEST_SLOTS, or the auto size when it is unset. */
72
+ readonly configured: number;
73
+ readonly source: "auto" | "operator";
74
+ readonly detail: string;
75
+ /** Whether live load lowers the count (FORGE_HOST_LOAD_LIVE_SLOTS, and more than one slot). */
76
+ readonly liveAdjustment: boolean;
77
+ /**
78
+ * The count at the last admission or refresh pass, with the lowest count another governor on
79
+ * the state root published; the configured count before the first pass.
80
+ */
81
+ readonly inForce: number;
82
+ /** Why inForce is below configured; empty when it is not. */
83
+ readonly inForceDetail: string;
84
+ }
85
+ /** One log line: "Host test slots: 3 at once (auto-sized from …); lowered while other work needs the host." */
86
+ export declare function describeHostTestSlotCapacity(capacity: HostTestSlotCapacity): string;
65
87
  export interface HostLoadGovernorOptions {
66
88
  readonly stateRoot: string;
67
89
  readonly load: HostLoadGovernorSource;
@@ -74,6 +96,8 @@ export interface HostLoadGovernorOptions {
74
96
  readonly terminateStep?: HostLoadStepTerminator;
75
97
  /** Test seam for the host suspend counter. */
76
98
  readonly suspendedMs?: () => number;
99
+ /** Test seam for live slot adjustment's shrink streak and grow settle period. */
100
+ readonly liveTestSlotTiming?: Pick<HostTestSlotControllerOptions, "shrinkSamples" | "growSettleMs">;
77
101
  }
78
102
  /**
79
103
  * Host-wide admission for heavy steps (decision 0013). Waiters queue
@@ -99,6 +123,13 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
99
123
  private idleOwnMemoryBytes;
100
124
  /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
101
125
  private readonly runtimeSettings;
126
+ /** Lowers the host test slot count while other work needs the machine; null when the count is fixed. */
127
+ private readonly liveTestSlots;
128
+ /** Lowered counts shared with the other governors on this state root. */
129
+ private readonly liveTestSlotsBoard;
130
+ private lastLiveTestSlots;
131
+ /** Feeds the controller while this governor holds slots or its count is lowered, so no backlog builds up. */
132
+ private liveFeedTimer;
102
133
  constructor(options: HostLoadGovernorOptions);
103
134
  get maxWaitMs(): number;
104
135
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
@@ -125,6 +156,16 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
125
156
  readonly waiting: number;
126
157
  readonly held: readonly HostLoadToken[];
127
158
  };
159
+ /**
160
+ * The host test slot count and why, for diagnostics: the configured count (auto-sized or the
161
+ * operator's), and the count in force after the last live adjustment, with its reason.
162
+ */
163
+ testSlotCapacity(): HostTestSlotCapacity;
164
+ /**
165
+ * Folds the sampler's new readings into the live count with the holders the ledger has now,
166
+ * without admitting anything (the feed timer, and diagnostics). A no-op without live adjustment.
167
+ */
168
+ refreshTestSlots(): Promise<HostTestSlotCapacity>;
128
169
  private drain;
129
170
  private drainOnce;
130
171
  /**
@@ -133,6 +174,31 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
133
174
  * The operator's env ceilings hold with or without the file, and over whatever it says.
134
175
  */
135
176
  private budgetPass;
177
+ /**
178
+ * The host test slot count for this admission pass: the configured count, lowered while
179
+ * other work on the host needs the machine (host-load-capacity.ts), and never above the
180
+ * lowest count another governor on this state root has published. The controller folds in
181
+ * every sample it has not seen, each judged with the holders of the passes around it, and it
182
+ * is fed while this governor holds slots or has lowered its count (armLiveFeed), so its
183
+ * streaks follow the sampler's clock, not how often steps happen to queue.
184
+ */
185
+ private testSlotsInForce;
186
+ /** The lowest count other governors have published; null without live adjustment or when none is lowered. */
187
+ private publishedTestSlots;
188
+ /** Stops the live slot feed (tests, shutdown); the next pass that needs it arms it again. */
189
+ stopLiveFeed(): void;
190
+ /**
191
+ * While this governor holds a slot or its count is lowered, the controller is fed on the
192
+ * sampler's interval even when nothing waits: readings are then judged with the holders of
193
+ * their own time, and a lowered count can grow back (and its published file stay fresh).
194
+ * Waiters' admission passes feed it already.
195
+ */
196
+ private armLiveFeed;
197
+ /**
198
+ * The bridge's own cgroup anonymous memory in the latest sample (dedicated cgroup only), and,
199
+ * with no token on the host, its idle baseline: what Forge's steps use is measured above it.
200
+ */
201
+ private observeIdleOwnMemory;
136
202
  /** The host test slot first (decision 0018), then the budget when it is on. */
137
203
  private decide;
138
204
  private readSignals;
@@ -157,6 +223,12 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
157
223
  */
158
224
  private checkStalled;
159
225
  private timeOut;
226
+ /**
227
+ * Wait reports run one at a time, in order, so a slow report (a dispatch event, a checkpoint) can
228
+ * never land after a newer one. A report still queued when the step is admitted or fails is
229
+ * dropped: it would be stale.
230
+ */
231
+ private notifyWaiting;
160
232
  private settle;
161
233
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
162
234
  private applyHeldOutcome;
@@ -191,3 +263,11 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
191
263
  private checkRetained;
192
264
  private renewHeld;
193
265
  }
266
+ /**
267
+ * Whether a waiting step should be told about this decision: its first wait, a new reason, or a
268
+ * host test slot wait whose holders or place in the queue moved. Budget and pressure details carry
269
+ * live load figures that change on every recheck, so only their reason counts.
270
+ */
271
+ export declare function waitChanged(previous: HostLoadAdmissionDecision | null, next: HostLoadAdmissionDecision): boolean;
272
+ /** Resolves once `notified` settles, or after `capMs` at the latest. */
273
+ export declare function afterNotified(notified: Promise<void>, capMs?: number): Promise<void>;
@@ -7,6 +7,8 @@ import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load
7
7
  import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
8
8
  import { HostLoadRuntimeSettingsReader } from "./host-load-runtime-settings.js";
9
9
  import { decideHostTestSlot, takesHostTestSlot } from "./host-load-test-slot.js";
10
+ import { HostTestSlotController } from "./host-load-capacity.js";
11
+ import { hostLiveReadings, LiveTestSlotsBoard } from "./host-load-live-test-slots.js";
10
12
  import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
11
13
  import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
12
14
  export class HostCapacityTimeoutError extends ForgeFailureError {
@@ -22,6 +24,15 @@ export class HostCapacityTimeoutError extends ForgeFailureError {
22
24
  this.name = "HostCapacityTimeoutError";
23
25
  }
24
26
  }
27
+ /** One log line: "Host test slots: 3 at once (auto-sized from …); lowered while other work needs the host." */
28
+ export function describeHostTestSlotCapacity(capacity) {
29
+ const live = capacity.liveAdjustment
30
+ ? capacity.inForce < capacity.configured
31
+ ? `; ${capacity.inForce} in force now, ${capacity.inForceDetail}`
32
+ : "; lowered while other work on the host needs the machine, raised again slowly"
33
+ : "";
34
+ return `Host test slots: ${capacity.configured} at once (${capacity.detail})${live}.`;
35
+ }
25
36
  /**
26
37
  * Host-wide admission for heavy steps (decision 0013). Waiters queue
27
38
  * foreground before background and FIFO within a class; a waiter that fits may
@@ -46,11 +57,27 @@ export class HostLoadGovernor {
46
57
  idleOwnMemoryBytes = null;
47
58
  /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
48
59
  runtimeSettings;
60
+ /** Lowers the host test slot count while other work needs the machine; null when the count is fixed. */
61
+ liveTestSlots;
62
+ /** Lowered counts shared with the other governors on this state root. */
63
+ liveTestSlotsBoard;
64
+ lastLiveTestSlots = null;
65
+ /** Feeds the controller while this governor holds slots or its count is lowered, so no backlog builds up. */
66
+ liveFeedTimer = null;
49
67
  constructor(options) {
50
68
  this.options = options;
51
69
  this.config = options.config ?? loadHostLoadGovernorConfig();
52
70
  this.enabled = hostLoadGovernorEnabled(this.config);
53
71
  this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
72
+ // With one slot there is nothing to lower: live adjustment never goes below 1.
73
+ this.liveTestSlots = this.config.liveTestSlots === true && this.config.testSlots > 1 && this.config.hostCapacity
74
+ ? new HostTestSlotController(this.config.hostCapacity, this.config.testSlots, {
75
+ sampleGapMs: this.config.sampleIntervalMs * 3,
76
+ ...options.liveTestSlotTiming,
77
+ })
78
+ : null;
79
+ this.liveTestSlotsBoard = this.liveTestSlots ? new LiveTestSlotsBoard(options.stateRoot, { now: options.now, liveness: options.liveness })
80
+ : null;
54
81
  this.ledger = new HostLoadTokenLedger({
55
82
  stateRoot: options.stateRoot,
56
83
  leaseMs: this.config.leaseMs,
@@ -79,8 +106,8 @@ export class HostLoadGovernor {
79
106
  // a ledger fault cannot fail a `git status` or a dependency install.
80
107
  if (this.config.mode !== "on" && !takesHostTestSlot(request.stepClass))
81
108
  return slotFreeAdmission(request);
82
- // Only the budget reads load samples.
83
- if (this.config.mode === "on")
109
+ // Only the budget and live slot adjustment read load samples.
110
+ if (this.config.mode === "on" || this.liveTestSlots)
84
111
  await this.options.load.start().catch(() => undefined);
85
112
  if (signal?.aborted)
86
113
  throw abortError(signal);
@@ -97,6 +124,7 @@ export class HostLoadGovernor {
97
124
  deadline: null,
98
125
  progressAtMs: enqueuedAtMs,
99
126
  lastDecision: null,
127
+ notified: Promise.resolve(),
100
128
  settled: false,
101
129
  ticket: this.config.testSlots > 0 && takesHostTestSlot(request.stepClass)
102
130
  ? {
@@ -185,6 +213,35 @@ export class HostLoadGovernor {
185
213
  snapshot() {
186
214
  return { waiting: this.waiters.length, held: [...this.held.values()].map(entry => entry.token) };
187
215
  }
216
+ /**
217
+ * The host test slot count and why, for diagnostics: the configured count (auto-sized or the
218
+ * operator's), and the count in force after the last live adjustment, with its reason.
219
+ */
220
+ testSlotCapacity() {
221
+ const configured = this.config.testSlots;
222
+ const live = this.lastLiveTestSlots;
223
+ return {
224
+ configured,
225
+ source: this.config.testSlotsSource ?? "operator",
226
+ detail: this.config.testSlotsDetail ?? `${configured} fixed`,
227
+ liveAdjustment: this.liveTestSlots !== null,
228
+ inForce: live?.slots ?? configured,
229
+ inForceDetail: live?.detail ?? "",
230
+ };
231
+ }
232
+ /**
233
+ * Folds the sampler's new readings into the live count with the holders the ledger has now,
234
+ * without admitting anything (the feed timer, and diagnostics). A no-op without live adjustment.
235
+ */
236
+ async refreshTestSlots() {
237
+ if (this.liveTestSlots) {
238
+ const published = await this.publishedTestSlots();
239
+ this.applyHeldOutcome(await this.ledger.transaction(transaction => {
240
+ this.testSlotsInForce(transaction.tokens, published);
241
+ }));
242
+ }
243
+ return this.testSlotCapacity();
244
+ }
188
245
  async drain() {
189
246
  if (this.draining) {
190
247
  this.drainAgain = true;
@@ -204,18 +261,20 @@ export class HostLoadGovernor {
204
261
  if (this.waiters.length === 0)
205
262
  return;
206
263
  const budget = this.config.mode === "on" ? await this.budgetPass() : null;
264
+ const published = await this.publishedTestSlots();
207
265
  if (this.waiters.length === 0)
208
266
  return;
209
267
  const nowMs = monotonicNowMs();
210
268
  const outcomes = [];
211
269
  const outcome = await this.ledger.transaction(transaction => {
212
270
  const runningMemoryBytes = budget ? this.runningStepsMemoryBytes(transaction.tokens) : 0;
271
+ const testSlots = this.testSlotsInForce(transaction.tokens, published);
213
272
  const head = this.waiters[0];
214
273
  const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
215
274
  for (const waiter of this.waiters) {
216
275
  if (waiter.settled)
217
276
  continue;
218
- const decision = this.decide(waiter, transaction, budget, runningMemoryBytes);
277
+ const decision = this.decide(waiter, transaction, budget, runningMemoryBytes, testSlots);
219
278
  if (decision.admitted && waiter.ticket) {
220
279
  // The ticket leaves the host queue in the same commit that issues the token.
221
280
  transaction.removeTicket(waiter.ticket.ticketId);
@@ -228,14 +287,16 @@ export class HostLoadGovernor {
228
287
  if (waiter === head && headStarving && !decision.admitted && decision.reason !== "host_test_slot")
229
288
  break;
230
289
  }
290
+ // The steps just admitted hold slots for the readings that follow.
291
+ this.liveTestSlots?.noteHolders(slotHolders(transaction.tokens));
231
292
  });
232
293
  this.applyHeldOutcome(outcome);
233
294
  for (const { waiter, token, decision } of outcomes) {
234
295
  if (!token) {
235
- const first = waiter.lastDecision === null;
296
+ const changed = waitChanged(waiter.lastDecision, decision);
236
297
  waiter.lastDecision = decision;
237
- if (first && !waiter.settled)
238
- void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
298
+ if (changed && !waiter.settled)
299
+ this.notifyWaiting(waiter, decision);
239
300
  this.checkStalled(waiter, decision);
240
301
  continue;
241
302
  }
@@ -286,14 +347,82 @@ export class HostLoadGovernor {
286
347
  logicalCpus: this.logicalCpus(),
287
348
  };
288
349
  }
350
+ /**
351
+ * The host test slot count for this admission pass: the configured count, lowered while
352
+ * other work on the host needs the machine (host-load-capacity.ts), and never above the
353
+ * lowest count another governor on this state root has published. The controller folds in
354
+ * every sample it has not seen, each judged with the holders of the passes around it, and it
355
+ * is fed while this governor holds slots or has lowered its count (armLiveFeed), so its
356
+ * streaks follow the sampler's clock, not how often steps happen to queue.
357
+ */
358
+ testSlotsInForce(tokens, published) {
359
+ if (!this.liveTestSlots)
360
+ return { slots: this.config.testSlots, detail: "" };
361
+ this.observeIdleOwnMemory(tokens);
362
+ const taken = this.liveTestSlots.readingsTaken;
363
+ const own = this.liveTestSlots.observe(hostLiveReadings({
364
+ load: this.options.load,
365
+ logicalCpus: this.config.hostCapacity?.logicalCpus ?? this.logicalCpus(),
366
+ sampleStaleMs: this.config.sampleStaleMs,
367
+ nowMs: this.options.now?.() ?? Date.now(),
368
+ idleOwnMemoryBytes: this.idleOwnMemoryBytes,
369
+ }), slotHolders(tokens));
370
+ this.liveTestSlotsBoard?.publish(own, this.config.testSlots, this.liveTestSlots.readingsTaken > taken);
371
+ this.lastLiveTestSlots = published && published.slots < own.slots ? published : own;
372
+ this.armLiveFeed();
373
+ return this.lastLiveTestSlots;
374
+ }
375
+ /** The lowest count other governors have published; null without live adjustment or when none is lowered. */
376
+ async publishedTestSlots() {
377
+ return await this.liveTestSlotsBoard?.lowest().catch(() => null) ?? null;
378
+ }
379
+ /** Stops the live slot feed (tests, shutdown); the next pass that needs it arms it again. */
380
+ stopLiveFeed() {
381
+ if (this.liveFeedTimer)
382
+ clearInterval(this.liveFeedTimer);
383
+ this.liveFeedTimer = null;
384
+ }
385
+ /**
386
+ * While this governor holds a slot or its count is lowered, the controller is fed on the
387
+ * sampler's interval even when nothing waits: readings are then judged with the holders of
388
+ * their own time, and a lowered count can grow back (and its published file stay fresh).
389
+ * Waiters' admission passes feed it already.
390
+ */
391
+ armLiveFeed() {
392
+ if (!this.liveTestSlots || this.liveFeedTimer)
393
+ return;
394
+ if (this.held.size === 0 && !this.liveTestSlots.lowered)
395
+ return;
396
+ this.liveFeedTimer = setInterval(() => {
397
+ if (this.held.size === 0 && !this.liveTestSlots?.lowered) {
398
+ this.stopLiveFeed();
399
+ return;
400
+ }
401
+ if (this.waiters.length === 0)
402
+ void this.refreshTestSlots().catch(() => undefined);
403
+ }, this.config.sampleIntervalMs);
404
+ this.liveFeedTimer.unref?.();
405
+ }
406
+ /**
407
+ * The bridge's own cgroup anonymous memory in the latest sample (dedicated cgroup only), and,
408
+ * with no token on the host, its idle baseline: what Forge's steps use is measured above it.
409
+ */
410
+ observeIdleOwnMemory(tokens) {
411
+ const snapshot = this.options.load.current();
412
+ const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
413
+ if (tokens.length === 0 && ownMemory !== null)
414
+ this.idleOwnMemoryBytes = ownMemory;
415
+ return ownMemory;
416
+ }
289
417
  /** The host test slot first (decision 0018), then the budget when it is on. */
290
- decide(waiter, transaction, budget, runningMemoryBytes) {
418
+ decide(waiter, transaction, budget, runningMemoryBytes, testSlots) {
291
419
  const slot = waiter.ticket
292
420
  ? decideHostTestSlot({
293
421
  ticket: waiter.ticket,
294
422
  queue: transaction.queue,
295
423
  tokens: transaction.tokens,
296
- testSlots: this.config.testSlots,
424
+ testSlots: testSlots.slots,
425
+ testSlotsDetail: testSlots.detail,
297
426
  nowMs: this.options.now?.() ?? Date.now(),
298
427
  antiStarvationMs: this.config.antiStarvationMs,
299
428
  })
@@ -370,13 +499,9 @@ export class HostLoadGovernor {
370
499
  * window ago is assumed to hold its reservation. Never above the reservations.
371
500
  */
372
501
  runningStepsMemoryBytes(tokens) {
373
- const snapshot = this.options.load.current();
374
- const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
375
- if (tokens.length === 0) {
376
- if (ownMemory !== null)
377
- this.idleOwnMemoryBytes = ownMemory;
502
+ const ownMemory = this.observeIdleOwnMemory(tokens);
503
+ if (tokens.length === 0)
378
504
  return 0;
379
- }
380
505
  const reserved = tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
381
506
  if (ownMemory !== null && this.idleOwnMemoryBytes !== null) {
382
507
  return Math.min(reserved, Math.max(0, ownMemory - this.idleOwnMemoryBytes));
@@ -412,6 +537,17 @@ export class HostLoadGovernor {
412
537
  timeOut(waiter, detail) {
413
538
  this.settle(waiter, () => waiter.reject(new HostCapacityTimeoutError(waiter.request.stepClass, waiter.request.label, monotonicNowMs() - waiter.enqueuedAtMs, detail)));
414
539
  }
540
+ /**
541
+ * Wait reports run one at a time, in order, so a slow report (a dispatch event, a checkpoint) can
542
+ * never land after a newer one. A report still queued when the step is admitted or fails is
543
+ * dropped: it would be stale.
544
+ */
545
+ notifyWaiting(waiter, decision) {
546
+ waiter.notified = waiter.notified
547
+ .then(async () => { if (!waiter.settled)
548
+ await waiter.onWaiting?.(decision); })
549
+ .catch(() => undefined);
550
+ }
415
551
  settle(waiter, complete) {
416
552
  if (waiter.settled)
417
553
  return;
@@ -428,7 +564,9 @@ export class HostLoadGovernor {
428
564
  if (waiter.ticket)
429
565
  void this.ledger.transaction(() => undefined).then(outcome => this.applyHeldOutcome(outcome), () => undefined);
430
566
  waiter.ticket = null;
431
- complete();
567
+ // The admission or failure lands after a wait report already in flight, never before it; the bound
568
+ // keeps a stuck report from holding the step back.
569
+ void afterNotified(waiter.notified, waitReportDrainMs).then(complete);
432
570
  }
433
571
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
434
572
  applyHeldOutcome(outcome) {
@@ -519,6 +657,7 @@ export class HostLoadGovernor {
519
657
  this.recheckTimer = null;
520
658
  }
521
659
  armRenewal() {
660
+ this.armLiveFeed();
522
661
  if (this.renewTimer)
523
662
  return;
524
663
  this.renewTimer = setInterval(() => void this.renewHeld(), Math.max(10, Math.floor(this.config.leaseMs / 4)));
@@ -611,6 +750,10 @@ export class HostLoadGovernor {
611
750
  }
612
751
  }
613
752
  }
753
+ /** Heavy steps holding a host test slot, in every process on the host. */
754
+ function slotHolders(tokens) {
755
+ return tokens.filter(token => takesHostTestSlot(token.stepClass)).length;
756
+ }
614
757
  /** The cgroup limit's headroom when one is set, never above host MemAvailable. */
615
758
  function tighterMemory(hostAvailable, cgroupHeadroom) {
616
759
  if (cgroupHeadroom === null)
@@ -622,6 +765,32 @@ function minutes(ms) {
622
765
  const whole = Math.max(1, Math.round(ms / 60_000));
623
766
  return whole === 1 ? "1 minute" : `${whole} minutes`;
624
767
  }
768
+ /**
769
+ * Whether a waiting step should be told about this decision: its first wait, a new reason, or a
770
+ * host test slot wait whose holders or place in the queue moved. Budget and pressure details carry
771
+ * live load figures that change on every recheck, so only their reason counts.
772
+ */
773
+ export function waitChanged(previous, next) {
774
+ if (previous === null || previous.reason !== next.reason)
775
+ return true;
776
+ return next.reason === "host_test_slot" && previous.detail !== next.detail;
777
+ }
778
+ /** The longest a step's admission or failure waits for its in-flight wait report. */
779
+ const waitReportDrainMs = 5_000;
780
+ /** Resolves once `notified` settles, or after `capMs` at the latest. */
781
+ export async function afterNotified(notified, capMs = waitReportDrainMs) {
782
+ let timer;
783
+ const cap = new Promise(resolve => {
784
+ timer = setTimeout(resolve, capMs);
785
+ timer.unref?.();
786
+ });
787
+ try {
788
+ await Promise.race([notified, cap]);
789
+ }
790
+ finally {
791
+ clearTimeout(timer);
792
+ }
793
+ }
625
794
  function abortError(signal) {
626
795
  if (signal.reason instanceof Error)
627
796
  return signal.reason;