@loucompanion/forge-bridge 0.1.4-dev.138b79c6feb3 → 0.1.4-dev.176dfdaf5020

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 (207) hide show
  1. package/README.md +142 -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-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +393 -337
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +11 -1
  31. package/dist/cleanup/cleanup.service.js +80 -62
  32. package/dist/cleanup/cleanup.types.d.ts +2 -0
  33. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  34. package/dist/cleanup/host-runtime-ledger.js +30 -9
  35. package/dist/cli/cli.help.js +74 -12
  36. package/dist/cli/cli.service.d.ts +19 -10
  37. package/dist/cli/cli.service.js +142 -185
  38. package/dist/cli/idle-status.d.ts +84 -0
  39. package/dist/cli/idle-status.js +181 -0
  40. package/dist/cli/local-config.d.ts +6 -0
  41. package/dist/cli/local-config.js +32 -4
  42. package/dist/cli/provider-cli-detection.d.ts +10 -0
  43. package/dist/cli/provider-cli-detection.js +160 -0
  44. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  45. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  46. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  47. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  48. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  49. package/dist/runtime/attempt-process-supervisor.js +12 -6
  50. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  51. package/dist/runtime/docker-engine-probe.js +7 -0
  52. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  53. package/dist/runtime/dotnet-build-outputs.js +402 -0
  54. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  56. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  57. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  58. package/dist/runtime/host-facts.d.ts +2 -1
  59. package/dist/runtime/host-load-admission.d.ts +18 -3
  60. package/dist/runtime/host-load-admission.js +19 -4
  61. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  62. package/dist/runtime/host-load-child-environment.js +22 -11
  63. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  64. package/dist/runtime/host-load-governor-config.js +37 -0
  65. package/dist/runtime/host-load-governor.d.ts +14 -0
  66. package/dist/runtime/host-load-governor.js +139 -26
  67. package/dist/runtime/host-load-ledger-lock.js +6 -4
  68. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  69. package/dist/runtime/host-load-runtime-settings.js +80 -0
  70. package/dist/runtime/host-load-sampler.d.ts +34 -4
  71. package/dist/runtime/host-load-sampler.js +73 -7
  72. package/dist/runtime/host-load-step-class.d.ts +3 -1
  73. package/dist/runtime/host-load-step-class.js +60 -5
  74. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  75. package/dist/runtime/host-load-test-slot.js +81 -0
  76. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  77. package/dist/runtime/host-load-token-ledger.js +93 -61
  78. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  79. package/dist/runtime/host-load-windows-cpu.js +85 -0
  80. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  81. package/dist/runtime/host-runtime-contract.js +29 -1
  82. package/dist/runtime/host-runtime-lease.d.ts +32 -4
  83. package/dist/runtime/host-runtime-lease.js +109 -173
  84. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  85. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  86. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  87. package/dist/runtime/host-runtime-promotion.js +36 -0
  88. package/dist/runtime/managed-command-teardown.js +5 -16
  89. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  90. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  91. package/dist/runtime/runner-settings.d.ts +104 -0
  92. package/dist/runtime/runner-settings.js +236 -0
  93. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  94. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  95. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  96. package/dist/sandbox/host-capacity-broker.js +27 -6
  97. package/dist/sandbox/managed-branch.d.ts +13 -0
  98. package/dist/sandbox/managed-branch.js +90 -0
  99. package/dist/sandbox/provider-auth/codex.js +11 -11
  100. package/dist/sandbox/runtime.js +2 -6
  101. package/dist/session/architect-waits.d.ts +2 -0
  102. package/dist/session/architect-waits.js +138 -0
  103. package/dist/session/managed-attempt-tools.d.ts +0 -7
  104. package/dist/session/managed-attempt-tools.js +58 -91
  105. package/dist/session/managed-build-coordinator.d.ts +16 -0
  106. package/dist/session/managed-build-coordinator.js +10 -0
  107. package/dist/session/managed-build-receipt.d.ts +5 -0
  108. package/dist/session/managed-build-receipt.js +8 -3
  109. package/dist/session/managed-command-host-load.d.ts +2 -0
  110. package/dist/session/managed-command-host-load.js +2 -1
  111. package/dist/session/phase-completion.artifacts.js +2 -1
  112. package/dist/session/phase-completion.d.ts +8 -0
  113. package/dist/session/phase-completion.js +1 -0
  114. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  115. package/dist/session/phase-completion.mcp-args.js +156 -0
  116. package/dist/session/phase-completion.runtime.d.ts +0 -8
  117. package/dist/session/phase-completion.runtime.js +43 -197
  118. package/dist/session/phase-completion.schemas.js +25 -23
  119. package/dist/session/phase-completion.validation.js +3 -1
  120. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  121. package/dist/session/pre-publication-native-postgres.js +111 -0
  122. package/dist/session/pre-publication-pass.d.ts +61 -0
  123. package/dist/session/pre-publication-pass.js +148 -0
  124. package/dist/session/pre-publication-process.js +10 -10
  125. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  126. package/dist/session/pre-publication-step-execution.js +6 -5
  127. package/dist/session/pre-publication-validation.d.ts +30 -14
  128. package/dist/session/pre-publication-validation.js +207 -134
  129. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  130. package/dist/session/provider-cli/claude-background-work.js +181 -0
  131. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  132. package/dist/session/provider-cli/host-build-lock.js +30 -0
  133. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  134. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  135. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  136. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  137. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  138. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  139. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  140. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  141. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  142. package/dist/session/provider-cli/provider-cli.prompts.js +68 -31
  143. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  144. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  145. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
  146. package/dist/session/provider-cli/provider-cli.service.js +70 -263
  147. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  148. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  149. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  150. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  151. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  152. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  153. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  154. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  155. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  156. package/dist/session/provider-cli/provider-output-state.js +6 -0
  157. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  158. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  159. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  160. package/dist/session/qa-sidecar-validation.js +28 -0
  161. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  162. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  163. package/dist/session/session-redaction.js +31 -181
  164. package/dist/session/session.base.d.ts +6 -1
  165. package/dist/session/session.service.d.ts +6 -1
  166. package/dist/session/session.service.js +75 -64
  167. package/dist/session/session.types.js +3 -3
  168. package/dist/session/sidecar-json-shape.d.ts +31 -0
  169. package/dist/session/sidecar-json-shape.js +217 -0
  170. package/dist/shared/fs/file-identity.d.ts +10 -0
  171. package/dist/shared/fs/file-identity.js +15 -0
  172. package/dist/shared/fs/replace-file.d.ts +7 -0
  173. package/dist/shared/fs/replace-file.js +33 -0
  174. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  175. package/dist/shared/process/host-process-recovery.js +23 -3
  176. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  177. package/dist/shared/process/host-process-supervisor.js +66 -14
  178. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  179. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  180. package/dist/shared/process/windows-launch.d.ts +18 -0
  181. package/dist/shared/process/windows-launch.js +68 -0
  182. package/dist/shared/provider-capabilities.js +14 -7
  183. package/dist/version.d.ts +1 -1
  184. package/dist/version.js +1 -1
  185. package/dist/worktree/orphan-relink.d.ts +19 -0
  186. package/dist/worktree/orphan-relink.js +106 -0
  187. package/dist/worktree/wip-git.d.ts +33 -0
  188. package/dist/worktree/wip-git.js +122 -0
  189. package/dist/worktree/wip-refs.d.ts +62 -0
  190. package/dist/worktree/wip-refs.js +119 -0
  191. package/dist/worktree/wip-restore.d.ts +38 -0
  192. package/dist/worktree/wip-restore.js +190 -0
  193. package/dist/worktree/wip-snapshot.d.ts +50 -0
  194. package/dist/worktree/wip-snapshot.js +268 -0
  195. package/dist/worktree/worktree-inputs.d.ts +8 -0
  196. package/dist/worktree/worktree-inputs.js +134 -0
  197. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  198. package/dist/worktree/worktree-origin-sync.js +127 -0
  199. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  200. package/dist/worktree/worktree-wip-events.js +98 -0
  201. package/dist/worktree/worktree-wip.d.ts +50 -0
  202. package/dist/worktree/worktree-wip.js +185 -0
  203. package/dist/worktree/worktree.base.d.ts +7 -1
  204. package/dist/worktree/worktree.service.d.ts +27 -5
  205. package/dist/worktree/worktree.service.js +110 -181
  206. package/dist/worktree/worktree.types.d.ts +31 -0
  207. package/package.json +2 -2
@@ -4,6 +4,8 @@ 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
6
  import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
7
+ /** What HostLoadStepGate.attachProcess takes, so a gate's callers need only this module. */
8
+ export type { HostLoadStepProcess } from "./host-load-step-reaper.js";
7
9
  import { type HostLoadOwnerLiveness, type HostLoadToken, type HostLoadTokenOwner, type HostLoadTokenPriority } from "./host-load-token-ledger.js";
8
10
  export interface HostLoadStepRequest {
9
11
  readonly stepClass: string;
@@ -79,6 +81,8 @@ export interface HostLoadGovernorOptions {
79
81
  * overtake an unfit head until the head has waited past the anti-starvation
80
82
  * window. Running steps are never preempted. Reserved cost comes from the
81
83
  * shared token ledger, so other processes' steps count against the same budget.
84
+ * The host test slot (decision 0018) comes first: a heavy step waits for it in
85
+ * the host-wide queue the ledger keeps, then for the budget when that is on.
82
86
  */
83
87
  export declare class HostLoadGovernor implements HostLoadStepGate {
84
88
  private readonly options;
@@ -93,6 +97,8 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
93
97
  private drainAgain;
94
98
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
95
99
  private idleOwnMemoryBytes;
100
+ /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
101
+ private readonly runtimeSettings;
96
102
  constructor(options: HostLoadGovernorOptions);
97
103
  get maxWaitMs(): number;
98
104
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
@@ -121,6 +127,14 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
121
127
  };
122
128
  private drain;
123
129
  private drainOnce;
130
+ /**
131
+ * Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
132
+ * bridge has in force apply from the next admission; running steps keep theirs.
133
+ * The operator's env ceilings hold with or without the file, and over whatever it says.
134
+ */
135
+ private budgetPass;
136
+ /** The host test slot first (decision 0018), then the budget when it is on. */
137
+ private decide;
124
138
  private readSignals;
125
139
  /**
126
140
  * 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
+ }
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import { ForgeFailureError } from "../session/session.types.js";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
4
5
  export class HostCapacityLedgerUnavailableError extends ForgeFailureError {
5
6
  code = "host_capacity_ledger_unavailable";
6
7
  constructor(detail, options) {
@@ -120,10 +121,11 @@ export class HostLoadLedgerLock {
120
121
  * there is none, or null if it is live or too young to judge.
121
122
  */
122
123
  async judgeStale(lockPath) {
123
- const stat = await fs.lstat(lockPath).catch(() => null);
124
+ // Exact (bigint) stats: a rounded Windows file id could name a different lock file.
125
+ const stat = await fs.lstat(lockPath, { bigint: true }).catch(() => null);
124
126
  if (!stat)
125
127
  return "absent";
126
- const observed = stat.isFile() && stat.size <= 16 * 1024 ? await readLock(lockPath) : null;
128
+ const observed = stat.isFile() && stat.size <= 16n * 1024n ? await readLock(lockPath) : null;
127
129
  if (observed?.holder && validHolder(observed.holder) && typeof observed.token === "string") {
128
130
  // A live holder keeps its lock however old it is.
129
131
  if (this.options.isLive(observed.holder))
@@ -131,9 +133,9 @@ export class HostLoadLedgerLock {
131
133
  return { identity: `t-${observed.token}` };
132
134
  }
133
135
  // Unreadable (claims are atomic, so this is corruption): give it until the stale age.
134
- if (Date.now() - stat.mtimeMs < (this.options.unreadableStaleAfterMs ?? 30_000))
136
+ if (Date.now() - Number(stat.mtimeMs) < (this.options.unreadableStaleAfterMs ?? 30_000))
135
137
  return null;
136
- return { identity: `i-${stat.dev}-${stat.ino}-${Math.trunc(stat.mtimeMs)}-${stat.size}` };
138
+ return { identity: `i-${fileIdentityKey(stat).replace(":", "-")}-${stat.mtimeNs}-${stat.size}` };
137
139
  }
138
140
  /**
139
141
  * Claims the next free link of the stale lock's break chain, held only for the
@@ -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,80 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { fileIdentityKey } from "../shared/fs/file-identity.js";
5
+ export function hostLoadRuntimeSettingsPath(stateRoot) {
6
+ return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
7
+ }
8
+ /** Atomically replaces the overrides every governor on this state root reads. */
9
+ export async function writeHostLoadRuntimeSettings(stateRoot, overrides) {
10
+ const filePath = hostLoadRuntimeSettingsPath(stateRoot);
11
+ const content = {
12
+ schemaVersion: 1,
13
+ cpuBudgetFraction: overrides.cpuBudgetFraction,
14
+ maxHeavySteps: overrides.maxHeavySteps,
15
+ yielding: overrides.yielding,
16
+ writtenAt: new Date().toISOString(),
17
+ writerPid: process.pid,
18
+ };
19
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
20
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
21
+ try {
22
+ await fs.writeFile(temporary, `${JSON.stringify(content)}\n`, { mode: 0o600 });
23
+ await fs.rename(temporary, filePath);
24
+ }
25
+ catch (error) {
26
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
27
+ throw error;
28
+ }
29
+ }
30
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
31
+ export async function resetHostLoadRuntimeSettings(stateRoot) {
32
+ await fs.rm(hostLoadRuntimeSettingsPath(stateRoot), { force: true });
33
+ }
34
+ /**
35
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
36
+ * size, so a governor re-checking its queue every second costs one stat. A
37
+ * missing or unreadable file means no overrides.
38
+ */
39
+ export class HostLoadRuntimeSettingsReader {
40
+ filePath;
41
+ cachedKey = null;
42
+ cached = null;
43
+ constructor(stateRoot) {
44
+ this.filePath = hostLoadRuntimeSettingsPath(stateRoot);
45
+ }
46
+ async read() {
47
+ let key;
48
+ try {
49
+ // Exact (bigint) stats: a replaced file whose rounded Windows id matched would read as unchanged.
50
+ const stat = await fs.stat(this.filePath, { bigint: true });
51
+ key = `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}:${fileIdentityKey(stat)}`;
52
+ }
53
+ catch {
54
+ this.cachedKey = null;
55
+ this.cached = null;
56
+ return null;
57
+ }
58
+ if (key === this.cachedKey)
59
+ return this.cached;
60
+ const parsed = await fs.readFile(this.filePath, "utf8").then(parseOverrides).catch(() => null);
61
+ this.cachedKey = key;
62
+ this.cached = parsed;
63
+ return parsed;
64
+ }
65
+ }
66
+ function parseOverrides(content) {
67
+ const raw = JSON.parse(content);
68
+ if (!raw || raw.schemaVersion !== 1)
69
+ return null;
70
+ const fraction = raw.cpuBudgetFraction;
71
+ if (typeof fraction !== "number" || !Number.isFinite(fraction))
72
+ return null;
73
+ const steps = raw.maxHeavySteps;
74
+ return {
75
+ // The governor config's own bounds for the budget fraction.
76
+ cpuBudgetFraction: Math.min(1, Math.max(0.05, fraction)),
77
+ maxHeavySteps: typeof steps === "number" && Number.isInteger(steps) && steps >= 1 ? Math.min(64, steps) : null,
78
+ yielding: raw.yielding === true,
79
+ };
80
+ }
@@ -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;