@loucompanion/forge-bridge 0.1.4-dev.bbb61d3d6127 → 0.1.4-dev.bd2cfb6b7438

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 (169) hide show
  1. package/README.md +55 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +71 -2
  8. package/dist/bridge/bridge.service.js +292 -118
  9. package/dist/bridge/bridge.types.d.ts +11 -0
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  13. package/dist/bridge/runner-host-capabilities.js +13 -0
  14. package/dist/cleanup/cleanup.service.d.ts +9 -0
  15. package/dist/cleanup/cleanup.service.js +72 -109
  16. package/dist/cleanup/cleanup.types.d.ts +4 -0
  17. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  18. package/dist/cleanup/forge-owned-paths.js +53 -0
  19. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  20. package/dist/cleanup/host-runtime-ledger.js +109 -0
  21. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  22. package/dist/cleanup/managed-branch-sweep.js +111 -0
  23. package/dist/cli/cli.help.js +18 -0
  24. package/dist/cli/cli.service.d.ts +16 -0
  25. package/dist/cli/cli.service.js +140 -16
  26. package/dist/cli/local-config.d.ts +4 -0
  27. package/dist/cli/local-config.js +26 -4
  28. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  29. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  30. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  31. package/dist/runtime/docker-engine-probe.js +7 -0
  32. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  33. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  34. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  35. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  36. package/dist/runtime/host-facts.d.ts +2 -1
  37. package/dist/runtime/host-load-admission.d.ts +18 -3
  38. package/dist/runtime/host-load-admission.js +19 -4
  39. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  40. package/dist/runtime/host-load-child-environment.js +76 -0
  41. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  42. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  43. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  44. package/dist/runtime/host-load-governor-config.js +37 -0
  45. package/dist/runtime/host-load-governor.d.ts +72 -11
  46. package/dist/runtime/host-load-governor.js +284 -67
  47. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  48. package/dist/runtime/host-load-runtime-settings.js +78 -0
  49. package/dist/runtime/host-load-sampler.d.ts +39 -4
  50. package/dist/runtime/host-load-sampler.js +83 -9
  51. package/dist/runtime/host-load-step-class.d.ts +37 -0
  52. package/dist/runtime/host-load-step-class.js +117 -2
  53. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  54. package/dist/runtime/host-load-step-reaper.js +95 -0
  55. package/dist/runtime/host-load-step-run.d.ts +73 -0
  56. package/dist/runtime/host-load-step-run.js +102 -0
  57. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  58. package/dist/runtime/host-load-test-slot.js +81 -0
  59. package/dist/runtime/host-load-token-ledger.d.ts +82 -17
  60. package/dist/runtime/host-load-token-ledger.js +187 -79
  61. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  62. package/dist/runtime/host-load-windows-cpu.js +85 -0
  63. package/dist/runtime/host-runtime-lease.d.ts +62 -3
  64. package/dist/runtime/host-runtime-lease.js +258 -13
  65. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  66. package/dist/runtime/host-runtime-promotion.js +36 -0
  67. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  68. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  69. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  70. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  71. package/dist/runtime/runner-settings.d.ts +100 -0
  72. package/dist/runtime/runner-settings.js +214 -0
  73. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  74. package/dist/sandbox/host-capacity-broker.js +334 -0
  75. package/dist/sandbox/runtime.d.ts +10 -1
  76. package/dist/sandbox/runtime.js +45 -2
  77. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  78. package/dist/sandbox/sandbox-cgroups.js +42 -0
  79. package/dist/session/architect-waits.d.ts +2 -0
  80. package/dist/session/architect-waits.js +138 -0
  81. package/dist/session/managed-attempt-tools.d.ts +2 -7
  82. package/dist/session/managed-attempt-tools.js +200 -92
  83. package/dist/session/managed-command-host-load.d.ts +47 -0
  84. package/dist/session/managed-command-host-load.js +83 -0
  85. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  86. package/dist/session/mcp-argument-coercion.js +121 -0
  87. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  88. package/dist/session/phase-completion.artifacts.js +96 -26
  89. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  90. package/dist/session/phase-completion.command-validation.js +77 -0
  91. package/dist/session/phase-completion.d.ts +4 -0
  92. package/dist/session/phase-completion.helpers.js +13 -12
  93. package/dist/session/phase-completion.js +4 -0
  94. package/dist/session/phase-completion.prompts.js +6 -1
  95. package/dist/session/phase-completion.runtime.d.ts +5 -3
  96. package/dist/session/phase-completion.runtime.js +50 -20
  97. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  98. package/dist/session/phase-completion.schema-parts.js +188 -0
  99. package/dist/session/phase-completion.schemas.d.ts +3 -3
  100. package/dist/session/phase-completion.schemas.js +208 -231
  101. package/dist/session/phase-completion.validation.d.ts +2 -3
  102. package/dist/session/phase-completion.validation.js +49 -93
  103. package/dist/session/pre-publication-host-load.js +31 -16
  104. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  105. package/dist/session/pre-publication-native-postgres.js +111 -0
  106. package/dist/session/pre-publication-pass.d.ts +61 -0
  107. package/dist/session/pre-publication-pass.js +148 -0
  108. package/dist/session/pre-publication-process.d.ts +3 -0
  109. package/dist/session/pre-publication-process.js +23 -11
  110. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  111. package/dist/session/pre-publication-step-execution.js +6 -5
  112. package/dist/session/pre-publication-validation.d.ts +30 -14
  113. package/dist/session/pre-publication-validation.js +211 -134
  114. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  115. package/dist/session/provider-cli/claude-background-work.js +180 -0
  116. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  117. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  118. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  119. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  120. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  121. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  122. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  123. package/dist/session/provider-cli/provider-cli.process.js +38 -339
  124. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  125. package/dist/session/provider-cli/provider-cli.prompts.js +50 -10
  126. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  127. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  128. package/dist/session/provider-cli/provider-cli.service.js +93 -162
  129. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  130. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  131. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  132. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  133. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  134. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  135. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  136. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  137. package/dist/session/provider-cli/provider-output-state.js +6 -0
  138. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  139. package/dist/session/qa-sidecar-validation.js +28 -0
  140. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  141. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  142. package/dist/session/session-redaction.js +31 -181
  143. package/dist/session/session.base.d.ts +6 -1
  144. package/dist/session/session.service.d.ts +7 -2
  145. package/dist/session/session.service.js +115 -5
  146. package/dist/session/session.types.js +4 -4
  147. package/dist/session/sidecar-json-shape.d.ts +31 -0
  148. package/dist/session/sidecar-json-shape.js +217 -0
  149. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  150. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  151. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  152. package/dist/shared/process/host-process-supervisor.js +1 -1
  153. package/dist/shared/process/process-tree.d.ts +52 -0
  154. package/dist/shared/process/process-tree.js +144 -0
  155. package/dist/shared/process/process.d.ts +67 -0
  156. package/dist/shared/process/process.js +213 -11
  157. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  158. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  159. package/dist/shared/process/windows-launch.d.ts +18 -0
  160. package/dist/shared/process/windows-launch.js +68 -0
  161. package/dist/shared/provider-capabilities.js +5 -6
  162. package/dist/version.d.ts +1 -1
  163. package/dist/version.js +1 -1
  164. package/dist/worktree/dependency-warmer.d.ts +25 -0
  165. package/dist/worktree/dependency-warmer.js +46 -10
  166. package/dist/worktree/worktree.service.d.ts +10 -1
  167. package/dist/worktree/worktree.service.js +42 -2
  168. package/dist/worktree/worktree.types.d.ts +7 -0
  169. package/package.json +2 -2
@@ -1,11 +1,16 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
2
3
  import fs from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import { ForgeFailureError } from "../session/session.types.js";
5
6
  import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
6
7
  import { HostCapacityLedgerUnavailableError, HostLoadLedgerLock } from "./host-load-ledger-lock.js";
8
+ import { validHostTestSlotTicket } from "./host-load-test-slot.js";
9
+ import { terminateHostLoadStepProcess, validHostLoadStepProcess, } from "./host-load-step-reaper.js";
7
10
  const processInstanceId = randomUUID();
8
11
  const maximumLedgerBytes = 1024 * 1024;
12
+ /** A degraded token's tree is retried at most this often, so a stuck process cannot stall every admission. */
13
+ const degradedRetryMs = 30_000;
9
14
  export class HostCapacityTokenFencedError extends ForgeFailureError {
10
15
  tokenId;
11
16
  code = "host_capacity_token_fenced";
@@ -52,6 +57,30 @@ export const processHostLoadOwnerLiveness = {
52
57
  function linuxProcessIdentity(pid) {
53
58
  return process.platform === "linux" ? captureHostProcessIdentity(pid, "linux") : null;
54
59
  }
60
+ /** Lapsed: past its lease even after taking away the time the host was suspended since renewal. */
61
+ function leaseLapsed(token, nowMs, suspendedMs) {
62
+ const expiresAtMs = Date.parse(token.expiresAt);
63
+ if (!Number.isFinite(expiresAtMs))
64
+ return true;
65
+ const asleepMs = Math.max(0, suspendedMs - (token.suspendedMsAtRenewal ?? suspendedMs));
66
+ return expiresAtMs + asleepMs <= nowMs;
67
+ }
68
+ /**
69
+ * Total time the host has been suspended (Linux: boot-time uptime minus the
70
+ * monotonic clock, which stops while suspended). Zero where it is unknown.
71
+ */
72
+ export function hostSuspendedMs() {
73
+ if (process.platform !== "linux")
74
+ return 0;
75
+ try {
76
+ const uptimeMs = Number(readFileSync("/proc/uptime", "utf8").split(/\s+/u)[0]) * 1000;
77
+ const monotonicMs = Number(process.hrtime.bigint() / 1000000n);
78
+ return Number.isFinite(uptimeMs) ? Math.max(0, Math.round(uptimeMs - monotonicMs)) : 0;
79
+ }
80
+ catch {
81
+ return 0;
82
+ }
83
+ }
55
84
  export class HostLoadTokenLedger {
56
85
  options;
57
86
  root;
@@ -76,6 +105,9 @@ export class HostLoadTokenLedger {
76
105
  beforeStaleBreak: options.beforeStaleLockBreak,
77
106
  });
78
107
  }
108
+ suspendedMs() {
109
+ return (this.options.suspendedMs ?? hostSuspendedMs)();
110
+ }
79
111
  get owner() {
80
112
  this.resolvedOwner ??= currentHostLoadTokenOwner();
81
113
  return this.resolvedOwner;
@@ -129,107 +161,179 @@ export class HostLoadTokenLedger {
129
161
  const { ledger, quarantined } = await this.read();
130
162
  const nowMs = this.now();
131
163
  const nowIso = new Date(nowMs).toISOString();
132
- const expiresAt = () => new Date(this.now() + this.options.leaseMs).toISOString();
164
+ const suspendedMs = this.suspendedMs();
165
+ // Each lease records the host's suspend counter, so time asleep never counts as a missed renewal.
166
+ const lease = () => ({ expiresAt: new Date(this.now() + this.options.leaseMs).toISOString(), suspendedMsAtRenewal: suspendedMs });
133
167
  const recoveringUntil = ledger.recoveringUntil && Date.parse(ledger.recoveringUntil) > nowMs
134
168
  ? ledger.recoveringUntil
135
169
  : null;
170
+ // Running steps of this owner are renewed before anything is reclaimed.
136
171
  const key = (token) => `${token.tokenId}:${token.fencingToken}`;
137
- // Running steps of this owner are renewed (or restored) before anything is reclaimed.
138
172
  const held = this.options.heldTokens?.() ?? [];
139
- const heldKeys = new Set(held.map(key));
140
- const ledgerKeys = new Set(ledger.tokens.map(key));
173
+ const heldIds = new Set(held.map(key));
174
+ const ledgerIds = new Set(ledger.tokens.map(key));
141
175
  // A held token missing from the ledger keeps its cost. While a quarantined
142
176
  // ledger is recovering no step was admitted against the gap, so it is put
143
177
  // back as is; otherwise capacity may have been reused, so it comes back fenced.
144
178
  const restored = held
145
- .filter(token => !ledgerKeys.has(key(token)))
146
- .map(token => ({
147
- ...token,
148
- expiresAt: expiresAt(),
149
- fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso),
150
- }));
179
+ .filter(token => !ledgerIds.has(key(token)))
180
+ .map(token => ({ ...token, ...lease(), fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso) }));
151
181
  const current = [
152
- ...ledger.tokens.map(token => heldKeys.has(key(token)) && !token.fencedAt ? { ...token, expiresAt: expiresAt() } : token),
182
+ ...ledger.tokens.map(token => heldIds.has(key(token)) && !token.fencedAt ? { ...token, ...lease() } : token),
153
183
  ...restored,
154
184
  ];
155
- // Only a provably gone owner frees capacity. A lapsed lease with a live owner
156
- // fences the token and keeps its cost: its step may still be running.
157
- const reclaimed = current.filter(token => !this.liveness.isLive(token.owner));
158
- let fencedNow = 0;
159
- let tokens = current
160
- .filter(token => !reclaimed.includes(token))
161
- .map(token => {
162
- if (token.fencedAt || !leaseLapsed(token, nowMs))
163
- return token;
164
- fencedNow += 1;
165
- return { ...token, fencedAt: nowIso };
166
- });
167
- let nextFencingToken = Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1));
168
- let changed = quarantined || reclaimed.length > 0 || fencedNow > 0 || held.length > 0
169
- || (ledger.recoveringUntil !== undefined && recoveringUntil === null);
170
- const transaction = {
171
- get tokens() { return tokens; },
172
- recoveringUntil,
173
- issue: request => {
174
- const token = {
175
- tokenId: randomUUID(),
176
- fencingToken: nextFencingToken,
177
- stepClass: request.stepClass,
178
- label: request.label,
179
- cost: { cpuCores: request.cost.cpuCores, memoryBytes: request.cost.memoryBytes },
180
- dispatchAttemptId: request.dispatchAttemptId,
181
- priority: request.priority,
182
- owner: this.owner,
183
- admittedAt: new Date(this.now()).toISOString(),
184
- expiresAt: expiresAt(),
185
- };
186
- nextFencingToken += 1;
187
- tokens = [...tokens, token];
188
- changed = true;
189
- return token;
190
- },
191
- renew: (tokenId, fencingToken) => {
192
- const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
193
- if (index < 0 || tokens[index].fencedAt)
194
- return null;
195
- const renewed = { ...tokens[index], expiresAt: expiresAt() };
196
- tokens = tokens.map((token, position) => position === index ? renewed : token);
197
- changed = true;
198
- return renewed;
199
- },
200
- remove: (tokenId, fencingToken) => {
201
- const before = tokens.length;
202
- tokens = tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
203
- changed ||= tokens.length !== before;
204
- return tokens.length !== before;
205
- },
185
+ const { reclaimed, degraded, fencedNow } = await this.reapExpired(current, nowMs, suspendedMs, nowIso);
186
+ const queue = this.liveQueue(ledger.slotQueue ?? [], nowMs, lease().expiresAt);
187
+ const state = {
188
+ tokens: current
189
+ .filter(token => !reclaimed.includes(token))
190
+ .map(token => degraded.get(token) ?? fencedNow.get(token) ?? token),
191
+ queue: queue.tickets,
192
+ nextFencingToken: Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1)),
193
+ changed: quarantined || reclaimed.length > 0 || degraded.size > 0 || fencedNow.size > 0 || held.length > 0
194
+ || queue.changed || (ledger.recoveringUntil !== undefined && recoveringUntil === null),
206
195
  };
207
- const result = await action(transaction);
208
- if (changed) {
196
+ const result = await action(this.transactionView(state, recoveringUntil, lease));
197
+ if (state.changed) {
209
198
  // A lock broken under us (a stalled holder taken for dead) must not commit.
210
199
  if (!await this.lock.holds(lockToken)) {
211
200
  throw new HostCapacityLedgerUnavailableError("the ledger lock was lost before the update could be written.");
212
201
  }
213
202
  await this.write({
214
203
  schemaVersion: 1,
215
- nextFencingToken,
216
- tokens,
204
+ nextFencingToken: state.nextFencingToken,
205
+ tokens: state.tokens,
206
+ ...state.queue.length > 0 ? { slotQueue: state.queue } : {},
217
207
  ...recoveringUntil ? { recoveringUntil } : {},
218
208
  });
219
209
  }
220
- if (held.length > 0) {
221
- const heldNow = tokens.filter(token => heldKeys.has(key(token)));
222
- this.options.onHeldTokens?.({
223
- renewed: heldNow.filter(token => !token.fencedAt),
224
- fenced: heldNow.filter(token => Boolean(token.fencedAt)),
225
- });
226
- }
227
- return { result, reclaimed };
210
+ const heldNow = state.tokens.filter(token => heldIds.has(key(token)));
211
+ return {
212
+ result,
213
+ reclaimed,
214
+ fenced: heldNow.filter(token => Boolean(token.fencedAt)),
215
+ renewed: heldNow.filter(token => !token.fencedAt),
216
+ };
228
217
  }
229
218
  finally {
230
219
  await this.lock.release(lockToken);
231
220
  }
232
221
  }
222
+ /** The live token set and host test slot queue one locked transaction reads and changes. */
223
+ transactionView(state, recoveringUntil, lease) {
224
+ const replace = (tokenId, fencingToken, change, evenFenced = false) => {
225
+ const index = state.tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
226
+ if (index < 0 || (state.tokens[index].fencedAt && !evenFenced))
227
+ return null;
228
+ const changed = change(state.tokens[index]);
229
+ state.tokens = state.tokens.map((token, position) => position === index ? changed : token);
230
+ state.changed = true;
231
+ return changed;
232
+ };
233
+ return {
234
+ get tokens() { return state.tokens; },
235
+ get queue() { return state.queue; },
236
+ recoveringUntil,
237
+ issue: request => {
238
+ const token = {
239
+ tokenId: randomUUID(),
240
+ fencingToken: state.nextFencingToken,
241
+ stepClass: request.stepClass,
242
+ label: request.label,
243
+ cost: { cpuCores: request.cost.cpuCores, memoryBytes: request.cost.memoryBytes },
244
+ dispatchAttemptId: request.dispatchAttemptId,
245
+ priority: request.priority,
246
+ owner: this.owner,
247
+ admittedAt: new Date(this.now()).toISOString(),
248
+ ...lease(),
249
+ };
250
+ state.nextFencingToken += 1;
251
+ state.tokens = [...state.tokens, token];
252
+ state.changed = true;
253
+ return token;
254
+ },
255
+ renew: (tokenId, fencingToken) => replace(tokenId, fencingToken, token => ({ ...token, ...lease() })),
256
+ attach: (tokenId, fencingToken, stepProcess) => replace(tokenId, fencingToken, token => ({ ...token, stepProcess })),
257
+ // A fenced token's step can end unproven too: the marker is metadata, not a renewal.
258
+ retain: (tokenId, fencingToken) => replace(tokenId, fencingToken, token => ({ ...token, retainedAt: new Date(this.now()).toISOString() }), true),
259
+ remove: (tokenId, fencingToken) => {
260
+ const before = state.tokens.length;
261
+ state.tokens = state.tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
262
+ state.changed ||= state.tokens.length !== before;
263
+ return state.tokens.length !== before;
264
+ },
265
+ removeTicket: ticketId => {
266
+ const before = state.queue.length;
267
+ state.queue = state.queue.filter(ticket => ticket.ticketId !== ticketId);
268
+ state.changed ||= state.queue.length !== before;
269
+ },
270
+ };
271
+ }
272
+ /**
273
+ * The host test slot queue (decision 0018): other owners' tickets while their owner
274
+ * lives and renews them, and this owner's current waiters, renewed. A ticket this
275
+ * owner no longer waits on (admitted, cancelled, timed out) leaves the queue here.
276
+ */
277
+ liveQueue(stored, nowMs, expiresAt) {
278
+ const owner = this.owner;
279
+ const mine = (ticket) => ticket.owner.pid === owner.pid
280
+ && ticket.owner.processInstanceId === owner.processInstanceId;
281
+ const others = stored.filter(ticket => !mine(ticket)
282
+ && Date.parse(ticket.expiresAt) > nowMs
283
+ && this.liveness.isLive(ticket.owner));
284
+ const waiting = (this.options.waitingTickets?.() ?? []).map(ticket => ({ ...ticket, owner, expiresAt }));
285
+ return {
286
+ tickets: [...others, ...waiting],
287
+ changed: waiting.length > 0 || others.length + waiting.length !== stored.length,
288
+ };
289
+ }
290
+ /**
291
+ * Decides every token another owner can no longer vouch for (decision 0013):
292
+ * - owner alive but its lease lapsed (it stalled): the token is fenced, never
293
+ * killed, and keeps its cost; the owner stops its own step when it next
294
+ * touches the ledger and returns the capacity when it releases the token;
295
+ * - owner gone with a recorded process tree: the tree is stopped and confirmed
296
+ * gone first, otherwise the token stays degraded and keeps its cost;
297
+ * - owner gone with no recorded tree: degraded, keeping its cost, until the
298
+ * attempt's teardown or the bridge's restart reap proves the step stopped
299
+ * (releaseOrphaned).
300
+ */
301
+ async reapExpired(current, nowMs, suspendedMs, nowIso) {
302
+ const reclaimed = [];
303
+ const degraded = new Map();
304
+ const fencedNow = new Map();
305
+ const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
306
+ for (const token of current) {
307
+ if (this.liveness.isLive(token.owner)) {
308
+ // Its step may still be running: fence it, but never free its capacity.
309
+ if (!token.fencedAt && leaseLapsed(token, nowMs, suspendedMs))
310
+ fencedNow.set(token, { ...token, fencedAt: nowIso });
311
+ continue;
312
+ }
313
+ const lastDegraded = token.degradedAt ? Date.parse(token.degradedAt) : Number.NaN;
314
+ if (Number.isFinite(lastDegraded) && nowMs - lastDegraded < degradedRetryMs)
315
+ continue;
316
+ const gone = Boolean(token.stepProcess) && await terminate(token.stepProcess).catch(() => false);
317
+ if (gone)
318
+ reclaimed.push(token);
319
+ else
320
+ degraded.set(token, { ...token, degradedAt: new Date(nowMs).toISOString() });
321
+ }
322
+ return { reclaimed, degraded, fencedNow };
323
+ }
324
+ /**
325
+ * Returns dead owners' tokens that have no recorded process tree once the
326
+ * caller has proven their steps stopped (attempt teardown after its process
327
+ * trees are stopped, or the restart reap after attempt recovery).
328
+ */
329
+ async releaseOrphaned(belongs) {
330
+ return (await this.transaction(transaction => {
331
+ const orphaned = transaction.tokens.filter(token => !token.stepProcess && belongs(token) && !this.liveness.isLive(token.owner));
332
+ for (const token of orphaned)
333
+ transaction.remove(token.tokenId, token.fencingToken);
334
+ return orphaned;
335
+ })).result;
336
+ }
233
337
  async read() {
234
338
  let content;
235
339
  try {
@@ -265,6 +369,7 @@ export class HostLoadTokenLedger {
265
369
  schemaVersion: 1,
266
370
  nextFencingToken,
267
371
  tokens: parsed.tokens,
372
+ slotQueue: Array.isArray(parsed.slotQueue) ? parsed.slotQueue.filter(validHostTestSlotTicket) : [],
268
373
  ...parsed.recoveringUntil !== undefined ? { recoveringUntil: parsed.recoveringUntil } : {},
269
374
  },
270
375
  quarantined: false,
@@ -306,10 +411,6 @@ export class HostLoadTokenLedger {
306
411
  }
307
412
  }
308
413
  }
309
- function leaseLapsed(token, nowMs) {
310
- const expiresAtMs = Date.parse(token.expiresAt);
311
- return !Number.isFinite(expiresAtMs) || expiresAtMs <= nowMs;
312
- }
313
414
  function emptyLedger() {
314
415
  return { schemaVersion: 1, nextFencingToken: 1, tokens: [] };
315
416
  }
@@ -341,5 +442,12 @@ function validToken(value) {
341
442
  && validOwner(token.owner)
342
443
  && typeof token.admittedAt === "string"
343
444
  && typeof token.expiresAt === "string"
344
- && (token.fencedAt === undefined || token.fencedAt === null || typeof token.fencedAt === "string");
445
+ && validOptionalTokenFields(token);
446
+ }
447
+ /** The fields a token gains as its step runs, ends or loses its owner. */
448
+ function validOptionalTokenFields(token) {
449
+ const optionalTime = (time) => time === undefined || time === null || typeof time === "string";
450
+ return (token.stepProcess === undefined || token.stepProcess === null || validHostLoadStepProcess(token.stepProcess))
451
+ && (token.suspendedMsAtRenewal === undefined || Number.isFinite(token.suspendedMsAtRenewal))
452
+ && optionalTime(token.degradedAt) && optionalTime(token.fencedAt) && optionalTime(token.retainedAt);
345
453
  }
@@ -0,0 +1,34 @@
1
+ import type os from "node:os";
2
+ import type { PressureStallResource } from "./host-pressure-stall.js";
3
+ /** Host CPU time summed over every logical CPU, in milliseconds, from os.cpus(). */
4
+ export interface CpuTimeTotals {
5
+ readonly busyMs: number;
6
+ readonly totalMs: number;
7
+ readonly cpuCount: number;
8
+ }
9
+ export type CpuTimesSource = readonly Partial<Pick<os.CpuInfo, "times">>[];
10
+ /**
11
+ * Host CPU use at which the estimate starts to report pressure. Waits for a CPU
12
+ * are rare below it on a many-core host. 0.6 puts the default backpressure
13
+ * threshold (50%) at 80% host CPU use, the default CPU budget.
14
+ */
15
+ export declare const windowsCpuPressureKnee = 0.6;
16
+ /** Busy is user + nice + sys + irq; idle is not busy. Null when any CPU lacks its times. */
17
+ export declare function cpuTimeTotals(cpus: CpuTimesSource): CpuTimeTotals | null;
18
+ /** Busy share of all logical CPUs (0-1) between two readings; null across a CPU count change or a counter reset. */
19
+ export declare function cpuUtilisation(previous: CpuTimeTotals | null, current: CpuTimeTotals | null): number | null;
20
+ /** Estimated share of wall time (percent) some runnable thread waited for a CPU, for one window. */
21
+ export declare function estimatedCpuStallPercent(utilisation: number): number;
22
+ /**
23
+ * Keeps 10/60/300-second exponentially decaying averages of the estimate, the
24
+ * way the kernel keeps PSI averages, so the governor's threshold and pressure
25
+ * streak read it exactly like PSI. The first window seeds every average, so a
26
+ * host already busy when the bridge starts reports pressure at once.
27
+ */
28
+ export declare class WindowsCpuPressureEstimator {
29
+ private averages;
30
+ /** Folds in one window of host CPU use lasting `elapsedMs`. */
31
+ update(utilisation: number, elapsedMs: number): PressureStallResource;
32
+ current(): PressureStallResource | null;
33
+ reset(): void;
34
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Host CPU use at which the estimate starts to report pressure. Waits for a CPU
3
+ * are rare below it on a many-core host. 0.6 puts the default backpressure
4
+ * threshold (50%) at 80% host CPU use, the default CPU budget.
5
+ */
6
+ export const windowsCpuPressureKnee = 0.6;
7
+ /** Busy is user + nice + sys + irq; idle is not busy. Null when any CPU lacks its times. */
8
+ export function cpuTimeTotals(cpus) {
9
+ if (cpus.length === 0)
10
+ return null;
11
+ let busyMs = 0;
12
+ let idleMs = 0;
13
+ for (const cpu of cpus) {
14
+ const times = cpu.times;
15
+ if (!times)
16
+ return null;
17
+ const values = [times.user, times.nice, times.sys, times.irq, times.idle];
18
+ if (!values.every(value => Number.isFinite(value) && value >= 0))
19
+ return null;
20
+ busyMs += times.user + times.nice + times.sys + times.irq;
21
+ idleMs += times.idle;
22
+ }
23
+ return { busyMs, totalMs: busyMs + idleMs, cpuCount: cpus.length };
24
+ }
25
+ /** Busy share of all logical CPUs (0-1) between two readings; null across a CPU count change or a counter reset. */
26
+ export function cpuUtilisation(previous, current) {
27
+ if (!previous || !current || previous.cpuCount !== current.cpuCount)
28
+ return null;
29
+ const totalDelta = current.totalMs - previous.totalMs;
30
+ const busyDelta = current.busyMs - previous.busyMs;
31
+ if (totalDelta <= 0 || busyDelta < 0)
32
+ return null;
33
+ return Math.min(1, busyDelta / totalDelta);
34
+ }
35
+ /** Estimated share of wall time (percent) some runnable thread waited for a CPU, for one window. */
36
+ export function estimatedCpuStallPercent(utilisation) {
37
+ const share = (utilisation - windowsCpuPressureKnee) / (1 - windowsCpuPressureKnee);
38
+ return Math.min(1, Math.max(0, share)) * 100;
39
+ }
40
+ const averageWindowsSeconds = { avg10: 10, avg60: 60, avg300: 300 };
41
+ /**
42
+ * Keeps 10/60/300-second exponentially decaying averages of the estimate, the
43
+ * way the kernel keeps PSI averages, so the governor's threshold and pressure
44
+ * streak read it exactly like PSI. The first window seeds every average, so a
45
+ * host already busy when the bridge starts reports pressure at once.
46
+ */
47
+ export class WindowsCpuPressureEstimator {
48
+ averages = null;
49
+ /** Folds in one window of host CPU use lasting `elapsedMs`. */
50
+ update(utilisation, elapsedMs) {
51
+ const stall = estimatedCpuStallPercent(utilisation);
52
+ const previous = this.averages;
53
+ this.averages = previous === null
54
+ ? { avg10: stall, avg60: stall, avg300: stall }
55
+ : {
56
+ avg10: decay(previous.avg10, stall, elapsedMs, averageWindowsSeconds.avg10),
57
+ avg60: decay(previous.avg60, stall, elapsedMs, averageWindowsSeconds.avg60),
58
+ avg300: decay(previous.avg300, stall, elapsedMs, averageWindowsSeconds.avg300),
59
+ };
60
+ return this.current();
61
+ }
62
+ current() {
63
+ if (!this.averages)
64
+ return null;
65
+ return {
66
+ some: {
67
+ avg10: roundPercent(this.averages.avg10),
68
+ avg60: roundPercent(this.averages.avg60),
69
+ avg300: roundPercent(this.averages.avg300),
70
+ },
71
+ // `full` (every runnable thread stalled) is not meaningful for CPU and is not estimated.
72
+ full: null,
73
+ };
74
+ }
75
+ reset() {
76
+ this.averages = null;
77
+ }
78
+ }
79
+ function decay(previous, sample, elapsedMs, windowSeconds) {
80
+ const weight = Math.exp(-Math.max(0, elapsedMs) / (windowSeconds * 1_000));
81
+ return sample + (previous - sample) * weight;
82
+ }
83
+ function roundPercent(value) {
84
+ return Math.round(value * 100) / 100;
85
+ }
@@ -15,6 +15,7 @@ import { HostParallelPromotionStore } from "./host-runtime-promotion.js";
15
15
  import { type HostProcessRecovery } from "../shared/process/host-process-recovery.js";
16
16
  import { HostLoadGovernor } from "./host-load-governor.js";
17
17
  import { type HostLoadGovernorSource } from "./host-load-sampler.js";
18
+ import type { RunnerHostDefaults } from "./runner-settings.js";
18
19
  export interface HostRuntimeLeaseStart {
19
20
  readonly lease: RuntimeIsolationLease;
20
21
  readonly environment: Readonly<Record<string, string>>;
@@ -28,7 +29,7 @@ export interface HostRuntimeAdmissionCheckpoint {
28
29
  }
29
30
  export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
30
31
  export interface HostRuntimeProjectCheckpoint {
31
- readonly code: "host_runtime_build_started" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
32
+ readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned" | "host_runtime_contract_readmitted";
32
33
  readonly message: string;
33
34
  readonly data?: Readonly<Record<string, unknown>>;
34
35
  }
@@ -96,10 +97,20 @@ export interface HostNodeRuntimeLaunch<T> extends NodeRuntimeAdapterLaunch<T> {
96
97
  }
97
98
  export interface HostRuntimeLeaseRuntime {
98
99
  setRequirementsCheck?(check: HostRequirementsCheck | null): void;
100
+ /** Decision 0014: today's max attempts and memory reserve defaults, before env bounds. */
101
+ capacityLimitDefaults?(): RunnerHostDefaults;
102
+ /** Decision 0014: the effective max attempts and memory reserve, from the next attempt admission. */
103
+ applyCapacityLimits?(limits: HostCapacityLimits): void;
99
104
  acquirePreparation?(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
100
105
  acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
101
106
  start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
102
107
  startConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
108
+ /**
109
+ * Stops the attempt's configured project processes, releases their ports, and
110
+ * starts them again (rebuilding when sources changed) so the stack serves the
111
+ * current workspace. Returns the environment with the newly assigned URLs.
112
+ */
113
+ restartConfiguredProject?(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
103
114
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
104
115
  providerProcessRunner?(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
105
116
  providerMemoryTelemetry?(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
@@ -108,6 +119,8 @@ export interface HostRuntimeLeaseRuntime {
108
119
  hasForegroundDemand?(): boolean;
109
120
  reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
110
121
  snapshot?(): HostRuntimeCapacitySnapshot;
122
+ /** Variables that let the completion MCP server share this host's load governor. */
123
+ hostLoadChildEnvironment?(): Readonly<Record<string, string>>;
111
124
  }
112
125
  export type HostRuntimeAdmissionPriority = "foreground" | "background";
113
126
  export interface HostCapacityResourceSample {
@@ -145,15 +158,26 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
145
158
  private workspaceAvailableBytes;
146
159
  private readonly portBroker;
147
160
  private readonly nodeAdapter;
148
- private readonly capacityConfiguration;
161
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
162
+ private capacityConfiguration;
149
163
  private readonly memoryAvailability;
150
164
  private readonly executionRoot;
151
- /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
165
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
152
166
  readonly hostLoadGovernor: HostLoadGovernor;
153
167
  private requirementsCheck;
154
168
  /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
155
169
  setRequirementsCheck(check: HostRequirementsCheck | null): void;
156
170
  constructor(stateRoot: string, portBroker?: HostPortBroker, nodeAdapter?: NodeHostRuntimeAdapter, processSupervisors?: AttemptProcessSupervisorRegistry, processRunner?: ProviderProcessRunner, listenerInspector?: HostListenerInspector, promotionStore?: HostParallelPromotionStore, playwrightAdapter?: PlaywrightHostRuntimeAdapter, processRecovery?: HostProcessRecovery, capacityResourceSample?: HostCapacityResourceSample | undefined, executionRoot?: string, databaseBroker?: AttemptDatabaseBroker | null, hostLoad?: HostLoadGovernorSource | null);
171
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
172
+ capacityLimitDefaults(): RunnerHostDefaults;
173
+ /**
174
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
175
+ * apply from the next attempt admission; admitted attempts keep their
176
+ * reservations and are never preempted, even when the new limit is lower than
177
+ * what already runs. The idle reserve follows the reserve as at startup.
178
+ */
179
+ applyCapacityLimits(limits: HostCapacityLimits): void;
180
+ hostLoadChildEnvironment(): Readonly<Record<string, string>>;
157
181
  reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
158
182
  snapshot(): HostRuntimeCapacitySnapshot;
159
183
  hasForegroundDemand(): boolean;
@@ -175,6 +199,24 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
175
199
  start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
176
200
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
177
201
  startConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
202
+ /**
203
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
204
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
205
+ * edited it, and a proof observed there would be stored under the admitted commit and could
206
+ * move this or a later attempt at that commit into shared admission for source it never ran.
207
+ */
208
+ private launchConfiguredProject;
209
+ /**
210
+ * Relaunches the configured project so it serves the current workspace. Every
211
+ * configured process stops (the API port changes, so the dev server's proxy target
212
+ * must change with it), its port reservation is released and dropped from the
213
+ * persisted lease, and the regular start path runs again, including the ASP.NET
214
+ * prebuild, whose receipt rebuilds only when the sources changed.
215
+ */
216
+ restartConfiguredProject(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal, onProjectCheckpoint?: HostRuntimeProjectCheckpointHandler): Promise<HostRuntimeLeaseStart>;
217
+ private runConfiguredProjectRestart;
218
+ /** Stops configured project processes in reverse launch order and releases their ports. */
219
+ private stopConfiguredProject;
178
220
  providerProcessRunner(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
179
221
  private markCapacityReservationRunning;
180
222
  providerMemoryTelemetry(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
@@ -225,4 +267,21 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
225
267
  }
226
268
  export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
227
269
  export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket): readonly string[];
270
+ /**
271
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
272
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
273
+ * stack is down: after its ports are released another attempt may be assigned them.
274
+ */
275
+ export declare function hostRuntimeStackEnvironmentKeys(runtimeContract: LoadedHostRuntimeContract): readonly string[];
228
276
  export declare function runtimeAdmissionPriority(dispatch: RunOnceDispatchPacket): HostRuntimeAdmissionPriority;
277
+ /** The pushed attempt limits (decision 0014), already resolved against host env bounds. */
278
+ export interface HostCapacityLimits {
279
+ readonly maxConcurrentAttempts: number;
280
+ readonly memoryReserveBytes: number;
281
+ }
282
+ /**
283
+ * Today's max attempts and adaptive memory reserve for this host, before
284
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
285
+ * (decision 0014 treats those as bounds on the server's values).
286
+ */
287
+ export declare function hostCapacityLimitDefaults(capacityResourceSample?: HostCapacityResourceSample): RunnerHostDefaults;