@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.93045aceba29

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 (72) hide show
  1. package/README.md +33 -0
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +70 -1
  4. package/dist/bridge/bridge.service.js +279 -5
  5. package/dist/bridge/bridge.types.d.ts +11 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/cleanup/cleanup.service.d.ts +9 -0
  9. package/dist/cleanup/cleanup.service.js +72 -109
  10. package/dist/cleanup/cleanup.types.d.ts +4 -0
  11. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  12. package/dist/cleanup/forge-owned-paths.js +53 -0
  13. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  14. package/dist/cleanup/host-runtime-ledger.js +109 -0
  15. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  16. package/dist/cleanup/managed-branch-sweep.js +111 -0
  17. package/dist/cli/cli.help.js +18 -0
  18. package/dist/cli/cli.service.d.ts +16 -0
  19. package/dist/cli/cli.service.js +139 -15
  20. package/dist/cli/local-config.d.ts +4 -0
  21. package/dist/cli/local-config.js +26 -4
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/host-load-admission.d.ts +9 -1
  24. package/dist/runtime/host-load-admission.js +19 -4
  25. package/dist/runtime/host-load-child-environment.js +3 -1
  26. package/dist/runtime/host-load-governor-config.d.ts +9 -0
  27. package/dist/runtime/host-load-governor-config.js +30 -0
  28. package/dist/runtime/host-load-governor.d.ts +2 -0
  29. package/dist/runtime/host-load-governor.js +23 -1
  30. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  31. package/dist/runtime/host-load-runtime-settings.js +78 -0
  32. package/dist/runtime/host-runtime-lease.d.ts +57 -1
  33. package/dist/runtime/host-runtime-lease.js +196 -6
  34. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  35. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  36. package/dist/runtime/runner-settings.d.ts +100 -0
  37. package/dist/runtime/runner-settings.js +214 -0
  38. package/dist/session/managed-attempt-tools.d.ts +2 -0
  39. package/dist/session/managed-attempt-tools.js +36 -13
  40. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  41. package/dist/session/mcp-argument-coercion.js +121 -0
  42. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  43. package/dist/session/phase-completion.artifacts.js +94 -25
  44. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  45. package/dist/session/phase-completion.command-validation.js +77 -0
  46. package/dist/session/phase-completion.d.ts +2 -0
  47. package/dist/session/phase-completion.helpers.js +13 -12
  48. package/dist/session/phase-completion.js +4 -0
  49. package/dist/session/phase-completion.prompts.js +6 -1
  50. package/dist/session/phase-completion.runtime.d.ts +4 -2
  51. package/dist/session/phase-completion.runtime.js +35 -13
  52. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  53. package/dist/session/phase-completion.schema-parts.js +188 -0
  54. package/dist/session/phase-completion.schemas.d.ts +3 -3
  55. package/dist/session/phase-completion.schemas.js +184 -209
  56. package/dist/session/phase-completion.validation.d.ts +2 -3
  57. package/dist/session/phase-completion.validation.js +46 -92
  58. package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
  59. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  60. package/dist/session/provider-cli/provider-cli.service.js +103 -3
  61. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  62. package/dist/session/session.base.d.ts +6 -1
  63. package/dist/session/session.service.d.ts +7 -2
  64. package/dist/session/session.service.js +100 -2
  65. package/dist/session/session.types.js +2 -2
  66. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  67. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/worktree/worktree.service.d.ts +5 -1
  71. package/dist/worktree/worktree.service.js +29 -1
  72. package/package.json +2 -2
@@ -4,6 +4,7 @@ import { monotonicNowMs } from "../shared/time/monotonic.js";
4
4
  import { decideHostLoadAdmission, } from "./host-load-admission.js";
5
5
  import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
6
6
  import { HostCapacityLedgerUnavailableError } from "./host-load-ledger-lock.js";
7
+ import { HostLoadRuntimeSettingsReader } from "./host-load-runtime-settings.js";
7
8
  import { terminateHostLoadStepProcess } from "./host-load-step-reaper.js";
8
9
  import { HostCapacityTokenFencedError, HostLoadTokenLedger, } from "./host-load-token-ledger.js";
9
10
  export class HostCapacityTimeoutError extends ForgeFailureError {
@@ -39,10 +40,13 @@ export class HostLoadGovernor {
39
40
  drainAgain = false;
40
41
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
41
42
  idleOwnMemoryBytes = null;
43
+ /** The bridge's pushed settings (decision 0014), shared with every governor on this state root. */
44
+ runtimeSettings;
42
45
  constructor(options) {
43
46
  this.options = options;
44
47
  this.config = options.config ?? loadHostLoadGovernorConfig();
45
48
  this.enabled = this.config.mode === "on";
49
+ this.runtimeSettings = new HostLoadRuntimeSettingsReader(options.stateRoot);
46
50
  this.ledger = new HostLoadTokenLedger({
47
51
  stateRoot: options.stateRoot,
48
52
  leaseMs: this.config.leaseMs,
@@ -171,6 +175,15 @@ export class HostLoadGovernor {
171
175
  return await this.draining;
172
176
  }
173
177
  async drainOnce() {
178
+ if (this.waiters.length === 0)
179
+ return;
180
+ // Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
181
+ // bridge has in force apply from the next admission; running steps keep theirs.
182
+ // The operator's env ceilings hold with or without the file, and over whatever it says.
183
+ const overrides = await this.runtimeSettings.read();
184
+ const cpuBudgetFraction = Math.min(overrides?.cpuBudgetFraction ?? this.config.cpuBudgetFraction, this.config.cpuBudgetCeilingFraction ?? 1);
185
+ const config = cpuBudgetFraction === this.config.cpuBudgetFraction ? this.config : { ...this.config, cpuBudgetFraction };
186
+ const maxHeavySteps = lowestLimit(overrides?.maxHeavySteps ?? null, this.config.maxHeavyStepsCeiling ?? null);
174
187
  if (this.waiters.length === 0)
175
188
  return;
176
189
  const signals = this.readSignals();
@@ -190,7 +203,8 @@ export class HostLoadGovernor {
190
203
  runningMemoryBytes,
191
204
  logicalCpus,
192
205
  signals,
193
- config: this.config,
206
+ config,
207
+ maxHeavySteps,
194
208
  });
195
209
  const decision = transaction.recoveringUntil
196
210
  ? {
@@ -517,3 +531,11 @@ function abortError(signal) {
517
531
  error.name = "AbortError";
518
532
  return error;
519
533
  }
534
+ /** The lower of two optional limits; null when neither is set. */
535
+ function lowestLimit(a, b) {
536
+ if (a === null)
537
+ return b;
538
+ if (b === null)
539
+ return a;
540
+ return Math.min(a, b);
541
+ }
@@ -0,0 +1,25 @@
1
+ export interface HostLoadRuntimeOverrides {
2
+ /** Share of logical CPUs heavy steps may reserve: the CPU budget, or the yield budget while yielding. */
3
+ readonly cpuBudgetFraction: number;
4
+ /** Host-wide count of heavy steps at once; null means the budget alone limits them. */
5
+ readonly maxHeavySteps: number | null;
6
+ /** For diagnostics: whether the budget above is the yield budget. */
7
+ readonly yielding: boolean;
8
+ }
9
+ export declare function hostLoadRuntimeSettingsPath(stateRoot: string): string;
10
+ /** Atomically replaces the overrides every governor on this state root reads. */
11
+ export declare function writeHostLoadRuntimeSettings(stateRoot: string, overrides: HostLoadRuntimeOverrides): Promise<void>;
12
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
13
+ export declare function resetHostLoadRuntimeSettings(stateRoot: string): Promise<void>;
14
+ /**
15
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
16
+ * size, so a governor re-checking its queue every second costs one stat. A
17
+ * missing or unreadable file means no overrides.
18
+ */
19
+ export declare class HostLoadRuntimeSettingsReader {
20
+ private readonly filePath;
21
+ private cachedKey;
22
+ private cached;
23
+ constructor(stateRoot: string);
24
+ read(): Promise<HostLoadRuntimeOverrides | null>;
25
+ }
@@ -0,0 +1,78 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ export function hostLoadRuntimeSettingsPath(stateRoot) {
5
+ return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
6
+ }
7
+ /** Atomically replaces the overrides every governor on this state root reads. */
8
+ export async function writeHostLoadRuntimeSettings(stateRoot, overrides) {
9
+ const filePath = hostLoadRuntimeSettingsPath(stateRoot);
10
+ const content = {
11
+ schemaVersion: 1,
12
+ cpuBudgetFraction: overrides.cpuBudgetFraction,
13
+ maxHeavySteps: overrides.maxHeavySteps,
14
+ yielding: overrides.yielding,
15
+ writtenAt: new Date().toISOString(),
16
+ writerPid: process.pid,
17
+ };
18
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
19
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
20
+ try {
21
+ await fs.writeFile(temporary, `${JSON.stringify(content)}\n`, { mode: 0o600 });
22
+ await fs.rename(temporary, filePath);
23
+ }
24
+ catch (error) {
25
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
26
+ throw error;
27
+ }
28
+ }
29
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
30
+ export async function resetHostLoadRuntimeSettings(stateRoot) {
31
+ await fs.rm(hostLoadRuntimeSettingsPath(stateRoot), { force: true });
32
+ }
33
+ /**
34
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
35
+ * size, so a governor re-checking its queue every second costs one stat. A
36
+ * missing or unreadable file means no overrides.
37
+ */
38
+ export class HostLoadRuntimeSettingsReader {
39
+ filePath;
40
+ cachedKey = null;
41
+ cached = null;
42
+ constructor(stateRoot) {
43
+ this.filePath = hostLoadRuntimeSettingsPath(stateRoot);
44
+ }
45
+ async read() {
46
+ let key;
47
+ try {
48
+ const stat = await fs.stat(this.filePath);
49
+ key = `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`;
50
+ }
51
+ catch {
52
+ this.cachedKey = null;
53
+ this.cached = null;
54
+ return null;
55
+ }
56
+ if (key === this.cachedKey)
57
+ return this.cached;
58
+ const parsed = await fs.readFile(this.filePath, "utf8").then(parseOverrides).catch(() => null);
59
+ this.cachedKey = key;
60
+ this.cached = parsed;
61
+ return parsed;
62
+ }
63
+ }
64
+ function parseOverrides(content) {
65
+ const raw = JSON.parse(content);
66
+ if (!raw || raw.schemaVersion !== 1)
67
+ return null;
68
+ const fraction = raw.cpuBudgetFraction;
69
+ if (typeof fraction !== "number" || !Number.isFinite(fraction))
70
+ return null;
71
+ const steps = raw.maxHeavySteps;
72
+ return {
73
+ // The governor config's own bounds for the budget fraction.
74
+ cpuBudgetFraction: Math.min(1, Math.max(0.05, fraction)),
75
+ maxHeavySteps: typeof steps === "number" && Number.isInteger(steps) && steps >= 1 ? Math.min(64, steps) : null,
76
+ yielding: raw.yielding === true,
77
+ };
78
+ }
@@ -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>>;
@@ -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;
@@ -147,7 +158,8 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
147
158
  private workspaceAvailableBytes;
148
159
  private readonly portBroker;
149
160
  private readonly nodeAdapter;
150
- private readonly capacityConfiguration;
161
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
162
+ private capacityConfiguration;
151
163
  private readonly memoryAvailability;
152
164
  private readonly executionRoot;
153
165
  /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
@@ -156,6 +168,15 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
156
168
  /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
157
169
  setRequirementsCheck(check: HostRequirementsCheck | null): void;
158
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;
159
180
  hostLoadChildEnvironment(): Readonly<Record<string, string>>;
160
181
  reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
161
182
  snapshot(): HostRuntimeCapacitySnapshot;
@@ -178,6 +199,24 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
178
199
  start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
179
200
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
180
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;
181
220
  providerProcessRunner(dispatchAttemptId: string, fencingToken: string): ProviderProcessRunner | null;
182
221
  private markCapacityReservationRunning;
183
222
  providerMemoryTelemetry(dispatchAttemptId: string, fencingToken: string): AttemptProcessTreeMemoryTelemetry | null;
@@ -228,4 +267,21 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
228
267
  }
229
268
  export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
230
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[];
231
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;
@@ -67,6 +67,7 @@ export class HostRuntimeLeaseManager {
67
67
  workspaceAvailableBytes = Number.MAX_SAFE_INTEGER;
68
68
  portBroker;
69
69
  nodeAdapter;
70
+ /** Rebuilt by applyCapacityLimits (decision 0014); every admission reads the current one. */
70
71
  capacityConfiguration;
71
72
  memoryAvailability;
72
73
  executionRoot;
@@ -97,6 +98,34 @@ export class HostRuntimeLeaseManager {
97
98
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
98
99
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
99
100
  }
101
+ /** Today's defaults for the limits the server can push, before any env bound (decision 0014). */
102
+ capacityLimitDefaults() {
103
+ return {
104
+ maxConcurrentAttempts: this.capacityConfiguration.defaultHardMaxAttempts,
105
+ memoryReserveBytes: this.capacityConfiguration.adaptiveHostReserveBytes,
106
+ };
107
+ }
108
+ /**
109
+ * Decision 0014: the bridge's effective max attempts and memory reserve. They
110
+ * apply from the next attempt admission; admitted attempts keep their
111
+ * reservations and are never preempted, even when the new limit is lower than
112
+ * what already runs. The idle reserve follows the reserve as at startup.
113
+ */
114
+ applyCapacityLimits(limits) {
115
+ const current = this.capacityConfiguration;
116
+ const hardMaxAttempts = Math.max(1, Math.min(32, Math.floor(limits.maxConcurrentAttempts)));
117
+ const hostReserveBytes = Math.max(512 * 1024 ** 2, Math.floor(limits.memoryReserveBytes));
118
+ if (hardMaxAttempts === current.hardMaxAttempts && hostReserveBytes === current.hostReserveBytes)
119
+ return;
120
+ this.capacityConfiguration = {
121
+ ...current,
122
+ hardMaxAttempts,
123
+ hostReserveBytes,
124
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, current),
125
+ };
126
+ // A raised limit may admit queued attempts now rather than at their next recheck.
127
+ this.drainAdmissionWaiters();
128
+ }
100
129
  hostLoadChildEnvironment() {
101
130
  return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
102
131
  }
@@ -1122,6 +1151,8 @@ export class HostRuntimeLeaseManager {
1122
1151
  parallelPromotionEligible: hostRuntimeParallelEligible(runtimeContract) && dispatch.cycleRun.phase !== "prepared_readiness",
1123
1152
  processSupervisor,
1124
1153
  adapterCleanups: [],
1154
+ adapterCleanupsByPort: new Map(),
1155
+ restartingConfiguredProject: false,
1125
1156
  pendingAdapterLaunches: new Map(),
1126
1157
  runtimeResourcesReleased: false,
1127
1158
  releasing: false,
@@ -1184,6 +1215,15 @@ export class HostRuntimeLeaseManager {
1184
1215
  await this.writeLedger(renewed);
1185
1216
  }
1186
1217
  async startConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1218
+ return await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, true);
1219
+ }
1220
+ /**
1221
+ * Launches the configured project. Only the first launch, from the admitted commit's clean
1222
+ * source, may record parallel-safety proof: a restart serves the workspace after the provider
1223
+ * edited it, and a proof observed there would be stored under the admitted commit and could
1224
+ * move this or a later attempt at that commit into shared admission for source it never ran.
1225
+ */
1226
+ async launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, promote) {
1187
1227
  const active = this.active.get(dispatchAttemptId);
1188
1228
  if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1189
1229
  throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
@@ -1304,7 +1344,7 @@ export class HostRuntimeLeaseManager {
1304
1344
  },
1305
1345
  }, launcher, signal);
1306
1346
  }
1307
- const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1347
+ const promotedLease = promote ? await this.promoteVerifiedRuntime(active, active.lease) : active.lease;
1308
1348
  const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1309
1349
  const playwright = active.runtimeContract.contract.runtime.playwright;
1310
1350
  if (!playwright) {
@@ -1343,6 +1383,93 @@ export class HostRuntimeLeaseManager {
1343
1383
  executionClass: active.executionClass,
1344
1384
  };
1345
1385
  }
1386
+ /**
1387
+ * Relaunches the configured project so it serves the current workspace. Every
1388
+ * configured process stops (the API port changes, so the dev server's proxy target
1389
+ * must change with it), its port reservation is released and dropped from the
1390
+ * persisted lease, and the regular start path runs again, including the ASP.NET
1391
+ * prebuild, whose receipt rebuilds only when the sources changed.
1392
+ */
1393
+ async restartConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1394
+ const active = this.active.get(dispatchAttemptId);
1395
+ if (!active || active.lease.fencingToken !== fencingToken || active.lease.state !== "active" || active.releasing) {
1396
+ throw new Error("host_runtime_project_unavailable: an active matching host runtime lease is required.");
1397
+ }
1398
+ if (signal?.aborted)
1399
+ throw new Error(String(signal.reason ?? "Host runtime restart was cancelled."));
1400
+ if (active.restartingConfiguredProject) {
1401
+ throw new Error("host_runtime_project_conflict: a configured project restart is already in progress.");
1402
+ }
1403
+ active.restartingConfiguredProject = true;
1404
+ // Release cancels the whole restart through this controller and waits for it to settle.
1405
+ const controller = linkedAbortController(signal);
1406
+ const promise = this.runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, controller.signal, onProjectCheckpoint);
1407
+ const restart = { controller, promise };
1408
+ active.configuredProjectRestart = restart;
1409
+ try {
1410
+ return await promise;
1411
+ }
1412
+ finally {
1413
+ // The controller is not aborted on settle: adapters this restart launched keep it as their
1414
+ // parent signal for as long as they run, exactly as they would keep the caller's signal.
1415
+ if (active.configuredProjectRestart === restart)
1416
+ active.configuredProjectRestart = null;
1417
+ active.restartingConfiguredProject = false;
1418
+ }
1419
+ }
1420
+ async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1421
+ // The relaunch reuses the contract (commands, ports, environment, concurrency) admitted at
1422
+ // start. If the workspace now declares a different one, a restart would run stale settings;
1423
+ // the attempt fails retryably instead, so a fresh attempt admits the new contract.
1424
+ const currentContract = await loadHostRuntimeContract(active.lease.worktreePath);
1425
+ if (hostRuntimeContractFingerprint(currentContract) !== active.runtimeContractFingerprint) {
1426
+ throw new ForgeFailureError("host_runtime_contract_changed", "host_runtime_contract_changed: the workspace's runtime contract changed after this attempt's runtime was admitted; a fresh attempt is needed to run it.");
1427
+ }
1428
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1429
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1430
+ if (pendingPort) {
1431
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1432
+ }
1433
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1434
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1435
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1436
+ // config may be left pointing at ports another attempt can now be assigned.
1437
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1438
+ }
1439
+ await this.stopConfiguredProject(active, portNames);
1440
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1441
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1442
+ if (active.releasing) {
1443
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1444
+ }
1445
+ return restarted;
1446
+ }
1447
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1448
+ async stopConfiguredProject(active, portNames) {
1449
+ const launched = active.lease.resources.ports
1450
+ .map(port => port.name)
1451
+ .filter(name => portNames.includes(name))
1452
+ .reverse();
1453
+ for (const name of launched) {
1454
+ if (active.releasing) {
1455
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1456
+ }
1457
+ const cleanup = active.adapterCleanupsByPort.get(name);
1458
+ if (!cleanup) {
1459
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1460
+ }
1461
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1462
+ await cleanup();
1463
+ removeCleanup(active.adapterCleanups, cleanup);
1464
+ active.adapterCleanupsByPort.delete(name);
1465
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1466
+ ...active.lease.resources,
1467
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1468
+ });
1469
+ await this.writeLedger(runtimeLease);
1470
+ active.lease = runtimeLease;
1471
+ }
1472
+ }
1346
1473
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1347
1474
  const active = this.active.get(dispatchAttemptId);
1348
1475
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
@@ -1430,6 +1557,7 @@ export class HostRuntimeLeaseManager {
1430
1557
  unlinkAbortController(controller, signal);
1431
1558
  };
1432
1559
  active.adapterCleanups.push(cleanup);
1560
+ active.adapterCleanupsByPort.set(portName, cleanup);
1433
1561
  try {
1434
1562
  if (active.releasing)
1435
1563
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1452,6 +1580,8 @@ export class HostRuntimeLeaseManager {
1452
1580
  try {
1453
1581
  await cleanup();
1454
1582
  removeCleanup(active.adapterCleanups, cleanup);
1583
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1584
+ active.adapterCleanupsByPort.delete(portName);
1455
1585
  }
1456
1586
  catch {
1457
1587
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1497,6 +1627,11 @@ export class HostRuntimeLeaseManager {
1497
1627
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1498
1628
  }
1499
1629
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1630
+ const restart = active.configuredProjectRestart;
1631
+ if (restart) {
1632
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1633
+ await restart.promise.catch(() => undefined);
1634
+ }
1500
1635
  await active.databaseProvision?.catch(() => undefined);
1501
1636
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1502
1637
  active.lease = releasing;
@@ -1514,6 +1649,7 @@ export class HostRuntimeLeaseManager {
1514
1649
  // validation step whose termination failed earlier) return their tokens now.
1515
1650
  await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1516
1651
  await releaseAdapterResources(active.adapterCleanups);
1652
+ active.adapterCleanupsByPort.clear();
1517
1653
  if (active.databaseCapability && this.databaseBroker) {
1518
1654
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1519
1655
  await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
@@ -2213,6 +2349,30 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2213
2349
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2214
2350
  return environment;
2215
2351
  }
2352
+ /**
2353
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2354
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2355
+ * stack is down: after its ports are released another attempt may be assigned them.
2356
+ */
2357
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2358
+ const keys = new Set([
2359
+ "FORGE_E2E_API_URL",
2360
+ "FORGE_E2E_WEB_URL",
2361
+ "FORGE_BASE_URL",
2362
+ "FORGE_PLAYWRIGHT_BASE_URL",
2363
+ // The generated Playwright config embeds the base URL.
2364
+ "FORGE_PLAYWRIGHT_CONFIG",
2365
+ ]);
2366
+ for (const port of runtimeContract.contract.runtime.ports) {
2367
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2368
+ keys.add(port.env);
2369
+ if (port.baseUrlEnv)
2370
+ keys.add(port.baseUrlEnv);
2371
+ keys.add(`FORGE_${normalizedName}_PORT`);
2372
+ keys.add(`FORGE_${normalizedName}_URL`);
2373
+ }
2374
+ return [...keys];
2375
+ }
2216
2376
  function anySignal(...signals) {
2217
2377
  return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2218
2378
  }
@@ -2358,6 +2518,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2358
2518
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2359
2519
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2360
2520
  }
2521
+ /**
2522
+ * Today's max attempts and adaptive memory reserve for this host, before
2523
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2524
+ * (decision 0014 treats those as bounds on the server's values).
2525
+ */
2526
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2527
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2528
+ return {
2529
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2530
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2531
+ };
2532
+ }
2361
2533
  function loadHostCapacityConfiguration(capacityResourceSample) {
2362
2534
  const sampledCpuCount = capacityResourceSample
2363
2535
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2365,23 +2537,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2365
2537
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2366
2538
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2367
2539
  const reserveCeilingBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_CEILING_BYTES", 4 * 1024 ** 3, reserveFloorBytes, 128 * 1024 ** 3);
2368
- const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2369
- explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2540
+ const adaptiveOptions = {
2370
2541
  floorBytes: reserveFloorBytes,
2371
2542
  ceilingBytes: reserveCeilingBytes,
2372
2543
  percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2544
+ };
2545
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2546
+ ...adaptiveOptions,
2547
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2373
2548
  });
2374
- const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2549
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2550
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2551
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2375
2552
  return {
2376
- hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2553
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2377
2554
  hostReserveBytes,
2378
- idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2555
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2556
+ defaultHardMaxAttempts,
2557
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2558
+ reserveFloorBytes,
2559
+ idleReserveOverrideBytes,
2379
2560
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2380
2561
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2381
2562
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2382
2563
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2383
2564
  };
2384
2565
  }
2566
+ /**
2567
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2568
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2569
+ */
2570
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2571
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2572
+ const override = configuration.idleReserveOverrideBytes;
2573
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2574
+ }
2385
2575
  function configuredOptionalInteger(name, minimum, maximum) {
2386
2576
  const raw = process.env[name];
2387
2577
  if (raw === undefined || raw.trim().length === 0)
@@ -28,5 +28,12 @@ export declare class PlaywrightHostRuntimeAdapter {
28
28
  */
29
29
  assertBrowserCacheReady(config: HostRuntimePlaywrightConfig, worktreePath: string): Promise<void>;
30
30
  private readyBrowserCache;
31
+ /**
32
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
33
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
34
+ * provider that remembers the config's path would otherwise run Playwright against that port.
35
+ * The next `prepare` writes a fresh one.
36
+ */
37
+ discardOverlay(temporaryDirectory: string): Promise<void>;
31
38
  prepare(config: HostRuntimePlaywrightConfig, context: PlaywrightHostRuntimeContext): Promise<PreparedPlaywrightHostRuntime>;
32
39
  }
@@ -35,6 +35,17 @@ export class PlaywrightHostRuntimeAdapter {
35
35
  }
36
36
  return { cache: resolution.cache, installCommand };
37
37
  }
38
+ /**
39
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
40
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
41
+ * provider that remembers the config's path would otherwise run Playwright against that port.
42
+ * The next `prepare` writes a fresh one.
43
+ */
44
+ async discardOverlay(temporaryDirectory) {
45
+ if (!await assertCanonicalDirectory(temporaryDirectory, true))
46
+ return;
47
+ await fs.rm(path.join(path.resolve(temporaryDirectory), playwrightOverlayFileName), { force: true });
48
+ }
38
49
  async prepare(config, context) {
39
50
  const { realWorktree, realSource } = await projectConfigLocation(config, context.worktreePath);
40
51
  const sourceConfig = path.resolve(path.resolve(context.worktreePath), config.config);
@@ -62,7 +73,7 @@ export class PlaywrightHostRuntimeAdapter {
62
73
  if (!/^[0-9a-f]{32}$/u.test(context.ownershipToken)) {
63
74
  throw new Error("playwright_runtime_adapter_invalid: ownership token must be a normalized dispatch attempt UUID.");
64
75
  }
65
- const overlayPath = path.join(temporaryDirectory, "forge.playwright.config.mjs");
76
+ const overlayPath = path.join(temporaryDirectory, playwrightOverlayFileName);
66
77
  const { cache: readyCache, installCommand: browserInstallCommand } = await this.readyBrowserCache(context.worktreePath, realWorktree, path.dirname(realSource));
67
78
  const browserCache = readyCache
68
79
  ? { path: readyCache, ready: true }
@@ -135,6 +146,7 @@ async function ensureAttemptWritableDirectories(targets, realWorktree) {
135
146
  for (const target of resolvedTargets)
136
147
  await createPrivateCanonicalDirectory(target);
137
148
  }
149
+ const playwrightOverlayFileName = "forge.playwright.config.mjs";
138
150
  async function writeAttemptOverlay(target, content) {
139
151
  const parent = path.dirname(target);
140
152
  const identity = await assertCanonicalDirectory(parent);