@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 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 (152) hide show
  1. package/README.md +41 -3
  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 +63 -101
  6. package/dist/bridge/bridge.types.d.ts +16 -0
  7. package/dist/bridge/bridge.types.js +2 -1
  8. package/dist/bridge/default-session-service.d.ts +13 -0
  9. package/dist/bridge/default-session-service.js +22 -0
  10. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  11. package/dist/bridge/dispatch-offer-policy.js +58 -0
  12. package/dist/bridge/runner-host-capabilities.js +14 -1
  13. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  14. package/dist/bridge/windows-bash-resolution.js +153 -0
  15. package/dist/cleanup/cleanup-wip.js +3 -3
  16. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  17. package/dist/cleanup/forge-owned-paths.js +9 -0
  18. package/dist/cli/cli.help.js +1 -1
  19. package/dist/cli/cli.service.js +11 -43
  20. package/dist/cli/local-config.d.ts +12 -1
  21. package/dist/cli/local-config.js +35 -1
  22. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  23. package/dist/cli/provider-cli-advertising.js +88 -0
  24. package/dist/runtime/host-load-admission.d.ts +5 -0
  25. package/dist/runtime/host-load-capacity.d.ts +198 -0
  26. package/dist/runtime/host-load-capacity.js +353 -0
  27. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  28. package/dist/runtime/host-load-child-environment.js +35 -1
  29. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  30. package/dist/runtime/host-load-governor-config.js +24 -3
  31. package/dist/runtime/host-load-governor.d.ts +89 -2
  32. package/dist/runtime/host-load-governor.js +217 -18
  33. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  34. package/dist/runtime/host-load-live-test-slots.js +193 -0
  35. package/dist/runtime/host-load-sampler.d.ts +17 -0
  36. package/dist/runtime/host-load-sampler.js +24 -0
  37. package/dist/runtime/host-load-step-run.d.ts +37 -3
  38. package/dist/runtime/host-load-step-run.js +63 -7
  39. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  40. package/dist/runtime/host-load-test-slot.js +26 -7
  41. package/dist/runtime/host-runtime-contract.js +6 -4
  42. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  43. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  44. package/dist/sandbox/runtime.d.ts +1 -2
  45. package/dist/sandbox/runtime.js +8 -14
  46. package/dist/sandbox/sandbox-input.d.ts +22 -0
  47. package/dist/sandbox/sandbox-input.js +49 -0
  48. package/dist/sandbox/workspace.service.js +15 -2
  49. package/dist/session/managed-attempt-tools.js +6 -29
  50. package/dist/session/managed-build-receipt.d.ts +3 -1
  51. package/dist/session/managed-build-receipt.js +5 -2
  52. package/dist/session/managed-command-environment.d.ts +8 -0
  53. package/dist/session/managed-command-environment.js +28 -0
  54. package/dist/session/managed-command-host-load.d.ts +10 -5
  55. package/dist/session/managed-command-host-load.js +18 -14
  56. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  57. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  58. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  59. package/dist/session/phase-completion.artifacts.js +63 -165
  60. package/dist/session/phase-completion.d.ts +25 -2
  61. package/dist/session/phase-completion.helpers.js +5 -53
  62. package/dist/session/phase-completion.js +15 -32
  63. package/dist/session/phase-completion.mcp-args.js +69 -2
  64. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  65. package/dist/session/phase-completion.phase-aliases.js +43 -0
  66. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  67. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  68. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  69. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  70. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  71. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  72. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  73. package/dist/session/phase-completion.pr-review.js +294 -0
  74. package/dist/session/phase-completion.prompts.d.ts +1 -1
  75. package/dist/session/phase-completion.prompts.js +14 -0
  76. package/dist/session/phase-completion.runtime.js +9 -3
  77. package/dist/session/phase-completion.schemas.js +12 -2
  78. package/dist/session/phase-completion.validation.d.ts +1 -0
  79. package/dist/session/phase-completion.validation.js +9 -1
  80. package/dist/session/pr-review-diff-base.d.ts +18 -0
  81. package/dist/session/pr-review-diff-base.js +45 -0
  82. package/dist/session/pr-review-placement.d.ts +50 -0
  83. package/dist/session/pr-review-placement.js +91 -0
  84. package/dist/session/pre-publication-change-set.d.ts +62 -0
  85. package/dist/session/pre-publication-change-set.js +166 -0
  86. package/dist/session/pre-publication-host-load.js +6 -5
  87. package/dist/session/pre-publication-process.js +3 -2
  88. package/dist/session/pre-publication-validation.d.ts +2 -1
  89. package/dist/session/pre-publication-validation.js +31 -36
  90. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  91. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  92. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  93. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  94. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  95. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  96. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  97. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  98. package/dist/session/provider-cli/pre-publication-repair.js +8 -3
  99. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  101. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  104. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  105. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -3
  107. package/dist/session/provider-cli/provider-cli.prompts.js +123 -70
  108. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  109. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  110. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  112. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  113. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  115. package/dist/session/provider-cli/provider-cli.service.js +33 -148
  116. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  117. package/dist/session/sandbox-host-capacity-gate.js +29 -7
  118. package/dist/session/session-host-project.d.ts +22 -0
  119. package/dist/session/session-host-project.js +98 -0
  120. package/dist/session/session.parse-helpers.d.ts +10 -0
  121. package/dist/session/session.parse-helpers.js +84 -0
  122. package/dist/session/session.runtime-refresh.d.ts +46 -0
  123. package/dist/session/session.runtime-refresh.js +116 -0
  124. package/dist/session/session.service.d.ts +2 -1
  125. package/dist/session/session.service.js +57 -158
  126. package/dist/session/session.types.d.ts +5 -0
  127. package/dist/session/session.types.js +8 -78
  128. package/dist/session/session.types.pr-review.d.ts +59 -0
  129. package/dist/session/session.types.pr-review.js +53 -0
  130. package/dist/shared/provider-capabilities.d.ts +2 -0
  131. package/dist/shared/provider-capabilities.js +9 -0
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.js +24 -0
  135. package/dist/worktree/wip-git.d.ts +25 -0
  136. package/dist/worktree/wip-git.js +64 -4
  137. package/dist/worktree/wip-refs.d.ts +23 -0
  138. package/dist/worktree/wip-refs.js +52 -2
  139. package/dist/worktree/wip-restore.d.ts +13 -0
  140. package/dist/worktree/wip-restore.js +159 -25
  141. package/dist/worktree/wip-snapshot.d.ts +5 -2
  142. package/dist/worktree/wip-snapshot.js +15 -13
  143. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  144. package/dist/worktree/worktree-origin-sync.js +1 -0
  145. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  146. package/dist/worktree/worktree-wip-events.js +53 -3
  147. package/dist/worktree/worktree-wip.d.ts +7 -0
  148. package/dist/worktree/worktree-wip.js +17 -2
  149. package/dist/worktree/worktree.service.d.ts +23 -1
  150. package/dist/worktree/worktree.service.js +122 -15
  151. package/dist/worktree/worktree.types.d.ts +16 -0
  152. package/package.json +1 -1
@@ -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,
@@ -66,7 +93,7 @@ export class HostLoadGovernor {
66
93
  });
67
94
  }
68
95
  get maxWaitMs() {
69
- return this.config.maxWaitMs;
96
+ return this.config.maxTotalWaitMs;
70
97
  }
71
98
  async acquire(request, options = {}) {
72
99
  if (!this.enabled) {
@@ -79,22 +106,25 @@ 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);
87
114
  return await new Promise((resolve, reject) => {
115
+ const enqueuedAtMs = monotonicNowMs();
88
116
  const waiter = {
89
117
  request,
90
- enqueuedAtMs: monotonicNowMs(),
118
+ enqueuedAtMs,
91
119
  signal,
92
120
  onWaiting: options.onWaiting,
93
121
  resolve,
94
122
  reject,
95
123
  abort: () => this.settle(waiter, () => reject(abortError(signal))),
96
124
  deadline: null,
125
+ progressAtMs: enqueuedAtMs,
97
126
  lastDecision: null,
127
+ notified: Promise.resolve(),
98
128
  settled: false,
99
129
  ticket: this.config.testSlots > 0 && takesHostTestSlot(request.stepClass)
100
130
  ? {
@@ -107,7 +137,8 @@ export class HostLoadGovernor {
107
137
  }
108
138
  : null,
109
139
  };
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);
140
+ // The backstop: even behind healthy holders, a step queues no longer than maxTotalWaitMs.
141
+ waiter.deadline = setTimeout(() => this.timeOut(waiter, `${waiter.lastDecision?.detail ?? "The host stayed at capacity."} It reached the longest a step may queue (${minutes(this.config.maxTotalWaitMs)}).`), this.config.maxTotalWaitMs);
111
142
  waiter.deadline.unref?.();
112
143
  signal?.addEventListener("abort", waiter.abort, { once: true });
113
144
  // Foreground goes ahead of background, except background that has already
@@ -182,6 +213,35 @@ export class HostLoadGovernor {
182
213
  snapshot() {
183
214
  return { waiting: this.waiters.length, held: [...this.held.values()].map(entry => entry.token) };
184
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
+ }
185
245
  async drain() {
186
246
  if (this.draining) {
187
247
  this.drainAgain = true;
@@ -201,18 +261,20 @@ export class HostLoadGovernor {
201
261
  if (this.waiters.length === 0)
202
262
  return;
203
263
  const budget = this.config.mode === "on" ? await this.budgetPass() : null;
264
+ const published = await this.publishedTestSlots();
204
265
  if (this.waiters.length === 0)
205
266
  return;
206
267
  const nowMs = monotonicNowMs();
207
268
  const outcomes = [];
208
269
  const outcome = await this.ledger.transaction(transaction => {
209
270
  const runningMemoryBytes = budget ? this.runningStepsMemoryBytes(transaction.tokens) : 0;
271
+ const testSlots = this.testSlotsInForce(transaction.tokens, published);
210
272
  const head = this.waiters[0];
211
273
  const headStarving = head !== undefined && nowMs - head.enqueuedAtMs >= this.config.antiStarvationMs;
212
274
  for (const waiter of this.waiters) {
213
275
  if (waiter.settled)
214
276
  continue;
215
- const decision = this.decide(waiter, transaction, budget, runningMemoryBytes);
277
+ const decision = this.decide(waiter, transaction, budget, runningMemoryBytes, testSlots);
216
278
  if (decision.admitted && waiter.ticket) {
217
279
  // The ticket leaves the host queue in the same commit that issues the token.
218
280
  transaction.removeTicket(waiter.ticket.ticketId);
@@ -225,14 +287,17 @@ export class HostLoadGovernor {
225
287
  if (waiter === head && headStarving && !decision.admitted && decision.reason !== "host_test_slot")
226
288
  break;
227
289
  }
290
+ // The steps just admitted hold slots for the readings that follow.
291
+ this.liveTestSlots?.noteHolders(slotHolders(transaction.tokens));
228
292
  });
229
293
  this.applyHeldOutcome(outcome);
230
294
  for (const { waiter, token, decision } of outcomes) {
231
295
  if (!token) {
232
- const first = waiter.lastDecision === null;
296
+ const changed = waitChanged(waiter.lastDecision, decision);
233
297
  waiter.lastDecision = decision;
234
- if (first && !waiter.settled)
235
- void Promise.resolve(waiter.onWaiting?.(decision)).catch(() => undefined);
298
+ if (changed && !waiter.settled)
299
+ this.notifyWaiting(waiter, decision);
300
+ this.checkStalled(waiter, decision);
236
301
  continue;
237
302
  }
238
303
  const entry = {
@@ -282,14 +347,82 @@ export class HostLoadGovernor {
282
347
  logicalCpus: this.logicalCpus(),
283
348
  };
284
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
+ }
285
417
  /** The host test slot first (decision 0018), then the budget when it is on. */
286
- decide(waiter, transaction, budget, runningMemoryBytes) {
418
+ decide(waiter, transaction, budget, runningMemoryBytes, testSlots) {
287
419
  const slot = waiter.ticket
288
420
  ? decideHostTestSlot({
289
421
  ticket: waiter.ticket,
290
422
  queue: transaction.queue,
291
423
  tokens: transaction.tokens,
292
- testSlots: this.config.testSlots,
424
+ testSlots: testSlots.slots,
425
+ testSlotsDetail: testSlots.detail,
293
426
  nowMs: this.options.now?.() ?? Date.now(),
294
427
  antiStarvationMs: this.config.antiStarvationMs,
295
428
  })
@@ -310,6 +443,7 @@ export class HostLoadGovernor {
310
443
  return {
311
444
  ...decision,
312
445
  admitted: false,
446
+ progressing: false,
313
447
  reason: "ledger_recovering",
314
448
  detail: `The host load ledger was corrupt and was quarantined; admissions resume at ${transaction.recoveringUntil}, once running steps have restored their reservations.`,
315
449
  };
@@ -365,13 +499,9 @@ export class HostLoadGovernor {
365
499
  * window ago is assumed to hold its reservation. Never above the reservations.
366
500
  */
367
501
  runningStepsMemoryBytes(tokens) {
368
- const snapshot = this.options.load.current();
369
- const ownMemory = snapshot?.ownCgroupDedicated ? snapshot.ownCgroup?.memoryAnonBytes ?? null : null;
370
- if (tokens.length === 0) {
371
- if (ownMemory !== null)
372
- this.idleOwnMemoryBytes = ownMemory;
502
+ const ownMemory = this.observeIdleOwnMemory(tokens);
503
+ if (tokens.length === 0)
373
504
  return 0;
374
- }
375
505
  const reserved = tokens.reduce((sum, token) => sum + token.cost.memoryBytes, 0);
376
506
  if (ownMemory !== null && this.idleOwnMemoryBytes !== null) {
377
507
  return Math.min(reserved, Math.max(0, ownMemory - this.idleOwnMemoryBytes));
@@ -387,6 +517,37 @@ export class HostLoadGovernor {
387
517
  return reported;
388
518
  return Math.max(1, typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length);
389
519
  }
520
+ /**
521
+ * Waiting behind healthy holders of the host test slot is progress: their steps run, and the slot passes
522
+ * down the queue as they finish. Any other wait (a holder past its lease or whose owner is gone, the
523
+ * budget, a recovering ledger) counts toward maxWaitMs from the last time the queue made progress.
524
+ */
525
+ checkStalled(waiter, decision) {
526
+ if (waiter.settled)
527
+ return;
528
+ const nowMs = monotonicNowMs();
529
+ if (decision.reason === "host_test_slot" && decision.progressing === true) {
530
+ waiter.progressAtMs = nowMs;
531
+ return;
532
+ }
533
+ if (nowMs - waiter.progressAtMs < this.config.maxWaitMs)
534
+ return;
535
+ this.timeOut(waiter, `${decision.detail} The queue made no progress for ${minutes(nowMs - waiter.progressAtMs)}.`);
536
+ }
537
+ timeOut(waiter, detail) {
538
+ this.settle(waiter, () => waiter.reject(new HostCapacityTimeoutError(waiter.request.stepClass, waiter.request.label, monotonicNowMs() - waiter.enqueuedAtMs, detail)));
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
+ }
390
551
  settle(waiter, complete) {
391
552
  if (waiter.settled)
392
553
  return;
@@ -403,7 +564,9 @@ export class HostLoadGovernor {
403
564
  if (waiter.ticket)
404
565
  void this.ledger.transaction(() => undefined).then(outcome => this.applyHeldOutcome(outcome), () => undefined);
405
566
  waiter.ticket = null;
406
- 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);
407
570
  }
408
571
  /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
409
572
  applyHeldOutcome(outcome) {
@@ -494,6 +657,7 @@ export class HostLoadGovernor {
494
657
  this.recheckTimer = null;
495
658
  }
496
659
  armRenewal() {
660
+ this.armLiveFeed();
497
661
  if (this.renewTimer)
498
662
  return;
499
663
  this.renewTimer = setInterval(() => void this.renewHeld(), Math.max(10, Math.floor(this.config.leaseMs / 4)));
@@ -586,12 +750,47 @@ export class HostLoadGovernor {
586
750
  }
587
751
  }
588
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
+ }
589
757
  /** The cgroup limit's headroom when one is set, never above host MemAvailable. */
590
758
  function tighterMemory(hostAvailable, cgroupHeadroom) {
591
759
  if (cgroupHeadroom === null)
592
760
  return hostAvailable;
593
761
  return hostAvailable === null ? cgroupHeadroom : Math.min(hostAvailable, cgroupHeadroom);
594
762
  }
763
+ /** Whole minutes for messages (at least 1); sub-minute limits only occur in tests and tuning. */
764
+ function minutes(ms) {
765
+ const whole = Math.max(1, Math.round(ms / 60_000));
766
+ return whole === 1 ? "1 minute" : `${whole} minutes`;
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
+ }
595
794
  function abortError(signal) {
596
795
  if (signal.reason instanceof Error)
597
796
  return signal.reason;
@@ -0,0 +1,61 @@
1
+ import { type HostLiveReading, type HostLiveTestSlots } from "./host-load-capacity.js";
2
+ import type { HostLoadGovernorSource } from "./host-load-sampler.js";
3
+ import { type HostLoadOwnerLiveness } from "./host-load-token-ledger.js";
4
+ /** What hostLiveReadings reads the sampler's history with. */
5
+ export interface HostLiveReadingContext {
6
+ readonly load: HostLoadGovernorSource;
7
+ /** Every CPU on the host: hostCpuPercent's denominator. */
8
+ readonly logicalCpus: number;
9
+ readonly sampleStaleMs: number;
10
+ /** Wall clock, for the staleness of the latest sample. */
11
+ readonly nowMs: number;
12
+ /** The bridge cgroup's anonymous memory with no heavy step running; null when unknown. */
13
+ readonly idleOwnMemoryBytes: number | null;
14
+ }
15
+ /** The sampler's fresh history as host readings; a stale history adds nothing. */
16
+ export declare function hostLiveReadings(context: HostLiveReadingContext): HostLiveReading[];
17
+ export declare function liveTestSlotsDirectory(stateRoot: string): string;
18
+ /** A lowered count is rewritten this often while it holds; readers drop one older than the TTL. */
19
+ export declare const liveTestSlotsRefreshMs = 30000;
20
+ export declare const liveTestSlotsTtlMs = 90000;
21
+ /**
22
+ * This governor's lowered count, shared with every governor on the state root, and theirs read
23
+ * back. Each governor writes a file of its own (no two processes write one file); it is
24
+ * written while the count is lowered (when it changes, and every refresh period while the
25
+ * controller takes in fresh readings) and removed once the count is back. A file whose writer
26
+ * stopped refreshing it lapses after the TTL: a writer whose sampler went quiet stops
27
+ * refreshing, so a reduction nothing confirms any more does not hold every governor back.
28
+ * A reader skips a file another host wrote and removes one whose writer is gone. Times are
29
+ * wall-clock: they are compared across processes.
30
+ */
31
+ export declare class LiveTestSlotsBoard {
32
+ private readonly directory;
33
+ private readonly fileName;
34
+ private readonly now;
35
+ private readonly liveness;
36
+ private readonly hostname;
37
+ private published;
38
+ /** When a pass last took in a fresh reading for this governor's count. */
39
+ private freshAtMs;
40
+ private writing;
41
+ constructor(stateRoot: string, options?: LiveTestSlotsBoardOptions);
42
+ /**
43
+ * Publishes this governor's own count (never one it adopted from another). `freshReading` says
44
+ * whether the pass behind it took in a new reading: an unchanged count is rewritten only while
45
+ * one came in within the TTL, so it lapses once the sampler goes quiet.
46
+ */
47
+ publish(own: HostLiveTestSlots, configured: number, freshReading: boolean): void;
48
+ /** The lowest count another governor on this state root has in force; null when none is lowered. */
49
+ lowest(): Promise<HostLiveTestSlots | null>;
50
+ /** Settles once every publish so far is on disk (tests). */
51
+ flushed(): Promise<void>;
52
+ private enqueue;
53
+ }
54
+ export interface LiveTestSlotsBoardOptions {
55
+ /** Wall clock (tests). */
56
+ readonly now?: () => number;
57
+ /** Whether a writer process still runs; the ledger's OS check by default. */
58
+ readonly liveness?: HostLoadOwnerLiveness;
59
+ /** This host's name; os.hostname() by default. */
60
+ readonly hostname?: string;
61
+ }
@@ -0,0 +1,193 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { reportsAvailableMemory } from "./host-load-capacity.js";
6
+ import { currentHostLoadTokenOwner, processHostLoadOwnerLiveness, } from "./host-load-token-ledger.js";
7
+ /** The sampler's fresh history as host readings; a stale history adds nothing. */
8
+ export function hostLiveReadings(context) {
9
+ const { load } = context;
10
+ const latest = load.current();
11
+ const latestAtMs = latest ? Date.parse(latest.sampledAt) : Number.NaN;
12
+ if (!latest || !Number.isFinite(latestAtMs) || context.nowMs - latestAtMs > context.sampleStaleMs)
13
+ return [];
14
+ const history = load.recent();
15
+ const samples = history.at(-1)?.sampledAt === latest.sampledAt ? history : [...history, latest];
16
+ // Each sample's own attribution, which counts Docker sandboxes as Forge's own CPU too.
17
+ const attributions = new Map();
18
+ for (const attribution of load.recentCpuAttributions?.() ?? [])
19
+ attributions.set(attribution.sampledAt, attribution);
20
+ const latestAttribution = load.cpuAttribution?.() ?? null;
21
+ if (latestAttribution)
22
+ attributions.set(latestAttribution.sampledAt, latestAttribution);
23
+ // macOS reports free pages only, which reads most of its memory as in use.
24
+ const memoryReadable = reportsAvailableMemory(load.facts()?.platform ?? process.platform);
25
+ return samples.flatMap(sample => {
26
+ const reading = liveReading(context, sample, attributions.get(sample.sampledAt) ?? null, memoryReadable);
27
+ return reading ? [reading] : [];
28
+ });
29
+ }
30
+ /**
31
+ * One sample as a host reading, stamped with the sampler's monotonic clock when it keeps one.
32
+ * With a dedicated cgroup, Forge's CPU comes from the sample's attribution (bridge and sandbox
33
+ * cgroups); a sample without one is left out rather than read with its sandboxes counted as
34
+ * other work. Forge's memory is the cgroup's anonymous memory above its idle baseline, when both
35
+ * are known.
36
+ */
37
+ function liveReading(context, sample, attribution, memoryReadable) {
38
+ const dedicated = sample.ownCgroupDedicated;
39
+ if (dedicated && !attribution)
40
+ return null;
41
+ const sampledAtMs = context.load.sampleMonotonicMs
42
+ ? context.load.sampleMonotonicMs(sample.sampledAt)
43
+ : Date.parse(sample.sampledAt);
44
+ if (sampledAtMs === null)
45
+ return null;
46
+ const ownMemory = dedicated ? sample.ownCgroup?.memoryAnonBytes ?? null : null;
47
+ return {
48
+ sampledAtMs,
49
+ hostCoresInUse: sample.hostCpuPercent === null ? null : (sample.hostCpuPercent / 100) * context.logicalCpus,
50
+ externalCoresInUse: dedicated ? attribution?.externalCoresInUse ?? null : null,
51
+ memoryAvailableBytes: memoryReadable ? sample.memoryAvailableBytes : null,
52
+ forgeMemoryBytes: ownMemory === null || context.idleOwnMemoryBytes === null
53
+ ? null
54
+ : Math.max(0, ownMemory - context.idleOwnMemoryBytes),
55
+ };
56
+ }
57
+ export function liveTestSlotsDirectory(stateRoot) {
58
+ return path.join(stateRoot, "host-load-governor", "live-test-slots");
59
+ }
60
+ /** A lowered count is rewritten this often while it holds; readers drop one older than the TTL. */
61
+ export const liveTestSlotsRefreshMs = 30_000;
62
+ export const liveTestSlotsTtlMs = 90_000;
63
+ /** A file this old belongs to a governor that is gone: any reader removes it. */
64
+ const abandonedMs = 10 * 60_000;
65
+ /** The most published counts read in one pass. */
66
+ const maximumEntries = 64;
67
+ /**
68
+ * This governor's lowered count, shared with every governor on the state root, and theirs read
69
+ * back. Each governor writes a file of its own (no two processes write one file); it is
70
+ * written while the count is lowered (when it changes, and every refresh period while the
71
+ * controller takes in fresh readings) and removed once the count is back. A file whose writer
72
+ * stopped refreshing it lapses after the TTL: a writer whose sampler went quiet stops
73
+ * refreshing, so a reduction nothing confirms any more does not hold every governor back.
74
+ * A reader skips a file another host wrote and removes one whose writer is gone. Times are
75
+ * wall-clock: they are compared across processes.
76
+ */
77
+ export class LiveTestSlotsBoard {
78
+ directory;
79
+ fileName = `${randomUUID()}.json`;
80
+ now;
81
+ liveness;
82
+ hostname;
83
+ published = null;
84
+ /** When a pass last took in a fresh reading for this governor's count. */
85
+ freshAtMs = null;
86
+ writing = Promise.resolve();
87
+ constructor(stateRoot, options = {}) {
88
+ this.directory = liveTestSlotsDirectory(stateRoot);
89
+ this.now = options.now ?? Date.now;
90
+ this.liveness = options.liveness ?? processHostLoadOwnerLiveness;
91
+ this.hostname = options.hostname ?? os.hostname();
92
+ }
93
+ /**
94
+ * Publishes this governor's own count (never one it adopted from another). `freshReading` says
95
+ * whether the pass behind it took in a new reading: an unchanged count is rewritten only while
96
+ * one came in within the TTL, so it lapses once the sampler goes quiet.
97
+ */
98
+ publish(own, configured, freshReading) {
99
+ const nowMs = this.now();
100
+ if (freshReading)
101
+ this.freshAtMs = nowMs;
102
+ const filePath = path.join(this.directory, this.fileName);
103
+ if (own.slots >= configured) {
104
+ if (this.published === null)
105
+ return;
106
+ this.published = null;
107
+ this.enqueue(async () => await fs.rm(filePath, { force: true }));
108
+ return;
109
+ }
110
+ const previous = this.published;
111
+ if (previous?.slots === own.slots && previous.detail === own.detail) {
112
+ const confirmed = this.freshAtMs !== null && nowMs - this.freshAtMs <= liveTestSlotsTtlMs;
113
+ if (!confirmed || nowMs - previous.atMs < liveTestSlotsRefreshMs)
114
+ return;
115
+ }
116
+ this.published = { slots: own.slots, detail: own.detail, atMs: nowMs };
117
+ const entry = {
118
+ schemaVersion: 1,
119
+ writer: currentHostLoadTokenOwner(),
120
+ hostname: this.hostname,
121
+ slots: own.slots,
122
+ detail: own.detail,
123
+ writtenAt: new Date(nowMs).toISOString(),
124
+ };
125
+ this.enqueue(async () => {
126
+ await fs.mkdir(this.directory, { recursive: true, mode: 0o700 });
127
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
128
+ try {
129
+ await fs.writeFile(temporary, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
130
+ await fs.rename(temporary, filePath);
131
+ }
132
+ catch (error) {
133
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
134
+ throw error;
135
+ }
136
+ });
137
+ }
138
+ /** The lowest count another governor on this state root has in force; null when none is lowered. */
139
+ async lowest() {
140
+ const names = await fs.readdir(this.directory).catch(() => []);
141
+ const nowMs = this.now();
142
+ let lowest = null;
143
+ for (const name of names.filter(entry => entry.endsWith(".json") && entry !== this.fileName).slice(0, maximumEntries)) {
144
+ const filePath = path.join(this.directory, name);
145
+ const entry = await fs.readFile(filePath, "utf8").then(parseEntry).catch(() => null);
146
+ const ageMs = entry ? nowMs - Date.parse(entry.writtenAt) : Number.NaN;
147
+ // Another host's pid cannot be checked here, and its load is not this host's.
148
+ if (entry && entry.hostname !== this.hostname)
149
+ continue;
150
+ const writerGone = entry !== null && !this.liveness.isLive(entry.writer);
151
+ if (ageMs > abandonedMs || writerGone)
152
+ void fs.rm(filePath, { force: true }).catch(() => undefined);
153
+ // A clock stepped far back makes an entry look written in the future: it is not trusted either.
154
+ if (!entry || writerGone || !(Math.abs(ageMs) <= liveTestSlotsTtlMs))
155
+ continue;
156
+ if (!lowest || entry.slots < lowest.slots)
157
+ lowest = { slots: entry.slots, detail: entry.detail };
158
+ }
159
+ return lowest;
160
+ }
161
+ /** Settles once every publish so far is on disk (tests). */
162
+ async flushed() {
163
+ await this.writing;
164
+ }
165
+ enqueue(write) {
166
+ this.writing = this.writing.then(write).catch(() => undefined);
167
+ }
168
+ }
169
+ function parseEntry(content) {
170
+ const raw = JSON.parse(content);
171
+ if (!raw || raw.schemaVersion !== 1 || typeof raw.writtenAt !== "string" || typeof raw.hostname !== "string")
172
+ return null;
173
+ const writer = parseWriter(raw.writer);
174
+ const slots = raw.slots;
175
+ if (!writer || typeof slots !== "number" || !Number.isInteger(slots) || slots < 1)
176
+ return null;
177
+ return {
178
+ schemaVersion: 1,
179
+ writer,
180
+ hostname: raw.hostname,
181
+ slots: Math.min(8, slots),
182
+ detail: typeof raw.detail === "string" ? raw.detail.slice(0, 500) : "",
183
+ writtenAt: raw.writtenAt,
184
+ };
185
+ }
186
+ function parseWriter(raw) {
187
+ if (!raw || typeof raw !== "object")
188
+ return null;
189
+ const { pid, processIdentity, processInstanceId } = raw;
190
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || typeof processInstanceId !== "string")
191
+ return null;
192
+ return { pid, processIdentity: typeof processIdentity === "string" ? processIdentity : null, processInstanceId };
193
+ }