@loucompanion/forge-bridge 0.1.4-dev.e1b4f55fb18d → 0.1.4-dev.e3697e9f5c98

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 (53) hide show
  1. package/README.md +42 -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 +278 -4
  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.js +15 -9
  9. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  10. package/dist/cleanup/forge-owned-paths.js +53 -0
  11. package/dist/cli/cli.help.js +18 -0
  12. package/dist/cli/cli.service.d.ts +16 -0
  13. package/dist/cli/cli.service.js +132 -14
  14. package/dist/cli/local-config.d.ts +4 -0
  15. package/dist/cli/local-config.js +26 -4
  16. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  17. package/dist/runtime/host-load-admission.d.ts +9 -1
  18. package/dist/runtime/host-load-admission.js +19 -4
  19. package/dist/runtime/host-load-child-environment.js +3 -1
  20. package/dist/runtime/host-load-governor-config.d.ts +9 -0
  21. package/dist/runtime/host-load-governor-config.js +30 -0
  22. package/dist/runtime/host-load-governor.d.ts +2 -0
  23. package/dist/runtime/host-load-governor.js +23 -1
  24. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  25. package/dist/runtime/host-load-runtime-settings.js +78 -0
  26. package/dist/runtime/host-runtime-lease.d.ts +58 -2
  27. package/dist/runtime/host-runtime-lease.js +198 -7
  28. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  29. package/dist/runtime/host-runtime-promotion.js +36 -0
  30. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  31. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  32. package/dist/runtime/runner-settings.d.ts +100 -0
  33. package/dist/runtime/runner-settings.js +214 -0
  34. package/dist/session/pre-publication-pass.d.ts +60 -0
  35. package/dist/session/pre-publication-pass.js +145 -0
  36. package/dist/session/pre-publication-validation.d.ts +21 -11
  37. package/dist/session/pre-publication-validation.js +149 -104
  38. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  39. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  40. package/dist/session/provider-cli/provider-cli.prompts.js +4 -1
  41. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  42. package/dist/session/provider-cli/provider-cli.service.js +72 -143
  43. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  44. package/dist/session/session.base.d.ts +6 -1
  45. package/dist/session/session.service.d.ts +7 -2
  46. package/dist/session/session.service.js +100 -2
  47. package/dist/session/session.types.js +2 -2
  48. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  49. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  50. package/dist/shared/provider-capabilities.js +5 -6
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +2 -2
@@ -23,7 +23,7 @@ import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
23
23
  import { HostListenerInspector } from "./host-listener-inspector.js";
24
24
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
25
25
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
26
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
26
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
27
27
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
28
28
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
29
29
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
@@ -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,94 @@ 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 keeps the admission granted at start. A workspace contract that changed only its
1422
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1423
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1424
+ active.runtimeContract = readmitted.runtimeContract;
1425
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1426
+ if (readmitted.changed) {
1427
+ await onProjectCheckpoint?.({ code: "host_runtime_contract_readmitted", message: "The workspace's runtime contract changed only its launch environment; the restart runs it under the admission granted at start." });
1428
+ }
1429
+ const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1430
+ const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
1431
+ if (pendingPort) {
1432
+ throw new Error(`host_runtime_project_conflict: configured port '${pendingPort}' is still launching.`);
1433
+ }
1434
+ const temporaryDirectory = active.lease.resources.paths.find(entry => entry.role === "temporary")?.path;
1435
+ if (active.runtimeContract.contract.runtime.playwright && temporaryDirectory) {
1436
+ // The generated Playwright config targets the stack being stopped. If the restart fails, no
1437
+ // config may be left pointing at ports another attempt can now be assigned.
1438
+ await this.playwrightAdapter.discardOverlay(temporaryDirectory);
1439
+ }
1440
+ await this.stopConfiguredProject(active, portNames);
1441
+ // Keeps whatever admission the attempt holds; see launchConfiguredProject.
1442
+ const restarted = await this.launchConfiguredProject(dispatchAttemptId, fencingToken, signal, onProjectCheckpoint, false);
1443
+ if (active.releasing) {
1444
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1445
+ }
1446
+ return restarted;
1447
+ }
1448
+ /** Stops configured project processes in reverse launch order and releases their ports. */
1449
+ async stopConfiguredProject(active, portNames) {
1450
+ const launched = active.lease.resources.ports
1451
+ .map(port => port.name)
1452
+ .filter(name => portNames.includes(name))
1453
+ .reverse();
1454
+ for (const name of launched) {
1455
+ if (active.releasing) {
1456
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during restart.");
1457
+ }
1458
+ const cleanup = active.adapterCleanupsByPort.get(name);
1459
+ if (!cleanup) {
1460
+ throw new Error(`host_runtime_project_restart_unavailable: configured port '${name}' has no supervised process to stop.`);
1461
+ }
1462
+ // A failed stop keeps the cleanup and the port record for the fenced release retry.
1463
+ await cleanup();
1464
+ removeCleanup(active.adapterCleanups, cleanup);
1465
+ active.adapterCleanupsByPort.delete(name);
1466
+ const runtimeLease = withRuntimeIsolationResources(active.lease, {
1467
+ ...active.lease.resources,
1468
+ ports: active.lease.resources.ports.filter(port => port.name !== name),
1469
+ });
1470
+ await this.writeLedger(runtimeLease);
1471
+ active.lease = runtimeLease;
1472
+ }
1473
+ }
1346
1474
  providerProcessRunner(dispatchAttemptId, fencingToken) {
1347
1475
  const active = this.active.get(dispatchAttemptId);
1348
1476
  if (!active || active.lease.fencingToken !== fencingToken || active.releasing)
@@ -1430,6 +1558,7 @@ export class HostRuntimeLeaseManager {
1430
1558
  unlinkAbortController(controller, signal);
1431
1559
  };
1432
1560
  active.adapterCleanups.push(cleanup);
1561
+ active.adapterCleanupsByPort.set(portName, cleanup);
1433
1562
  try {
1434
1563
  if (active.releasing)
1435
1564
  throw new Error("host_runtime_adapter_cancelled: host runtime release started during launch.");
@@ -1452,6 +1581,8 @@ export class HostRuntimeLeaseManager {
1452
1581
  try {
1453
1582
  await cleanup();
1454
1583
  removeCleanup(active.adapterCleanups, cleanup);
1584
+ if (active.adapterCleanupsByPort.get(portName) === cleanup)
1585
+ active.adapterCleanupsByPort.delete(portName);
1455
1586
  }
1456
1587
  catch {
1457
1588
  // Preserve the cleanup and broker claim for the fenced release retry.
@@ -1497,6 +1628,11 @@ export class HostRuntimeLeaseManager {
1497
1628
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1498
1629
  }
1499
1630
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1631
+ const restart = active.configuredProjectRestart;
1632
+ if (restart) {
1633
+ restart.controller.abort("Host runtime release cancelled the configured project restart.");
1634
+ await restart.promise.catch(() => undefined);
1635
+ }
1500
1636
  await active.databaseProvision?.catch(() => undefined);
1501
1637
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1502
1638
  active.lease = releasing;
@@ -1514,6 +1650,7 @@ export class HostRuntimeLeaseManager {
1514
1650
  // validation step whose termination failed earlier) return their tokens now.
1515
1651
  await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1516
1652
  await releaseAdapterResources(active.adapterCleanups);
1653
+ active.adapterCleanupsByPort.clear();
1517
1654
  if (active.databaseCapability && this.databaseBroker) {
1518
1655
  // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1519
1656
  await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
@@ -2213,6 +2350,30 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2213
2350
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2214
2351
  return environment;
2215
2352
  }
2353
+ /**
2354
+ * Every environment key `hostRuntimeEnvironment` and the Playwright overlay derive from the
2355
+ * configured project's assigned ports. They name a live stack, so they are withheld while the
2356
+ * stack is down: after its ports are released another attempt may be assigned them.
2357
+ */
2358
+ export function hostRuntimeStackEnvironmentKeys(runtimeContract) {
2359
+ const keys = new Set([
2360
+ "FORGE_E2E_API_URL",
2361
+ "FORGE_E2E_WEB_URL",
2362
+ "FORGE_BASE_URL",
2363
+ "FORGE_PLAYWRIGHT_BASE_URL",
2364
+ // The generated Playwright config embeds the base URL.
2365
+ "FORGE_PLAYWRIGHT_CONFIG",
2366
+ ]);
2367
+ for (const port of runtimeContract.contract.runtime.ports) {
2368
+ const normalizedName = port.name.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
2369
+ keys.add(port.env);
2370
+ if (port.baseUrlEnv)
2371
+ keys.add(port.baseUrlEnv);
2372
+ keys.add(`FORGE_${normalizedName}_PORT`);
2373
+ keys.add(`FORGE_${normalizedName}_URL`);
2374
+ }
2375
+ return [...keys];
2376
+ }
2216
2377
  function anySignal(...signals) {
2217
2378
  return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2218
2379
  }
@@ -2358,6 +2519,18 @@ function configuredInteger(name, fallback, minimum, maximum) {
2358
2519
  const parsed = Number.parseInt(process.env[name] ?? "", 10);
2359
2520
  return Number.isFinite(parsed) ? Math.max(minimum, Math.min(maximum, parsed)) : fallback;
2360
2521
  }
2522
+ /**
2523
+ * Today's max attempts and adaptive memory reserve for this host, before
2524
+ * FORGE_HOST_MAX_CONCURRENT_ATTEMPTS and FORGE_HOST_MEMORY_RESERVE_BYTES
2525
+ * (decision 0014 treats those as bounds on the server's values).
2526
+ */
2527
+ export function hostCapacityLimitDefaults(capacityResourceSample) {
2528
+ const configuration = loadHostCapacityConfiguration(capacityResourceSample);
2529
+ return {
2530
+ maxConcurrentAttempts: configuration.defaultHardMaxAttempts,
2531
+ memoryReserveBytes: configuration.adaptiveHostReserveBytes,
2532
+ };
2533
+ }
2361
2534
  function loadHostCapacityConfiguration(capacityResourceSample) {
2362
2535
  const sampledCpuCount = capacityResourceSample
2363
2536
  ? Math.max(1, Math.floor(capacityResourceSample.totalCpuMillis / 1_000))
@@ -2365,23 +2538,41 @@ function loadHostCapacityConfiguration(capacityResourceSample) {
2365
2538
  const totalMemoryBytes = capacityResourceSample?.totalMemoryBytes ?? os.totalmem();
2366
2539
  const reserveFloorBytes = configuredInteger("FORGE_HOST_MEMORY_RESERVE_FLOOR_BYTES", 1024 ** 3, 512 * 1024 ** 2, 128 * 1024 ** 3);
2367
2540
  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),
2541
+ const adaptiveOptions = {
2370
2542
  floorBytes: reserveFloorBytes,
2371
2543
  ceilingBytes: reserveCeilingBytes,
2372
2544
  percent: configuredNumber("FORGE_HOST_MEMORY_RESERVE_PERCENT", 12.5, 1, 50),
2545
+ };
2546
+ const hostReserveBytes = resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, {
2547
+ ...adaptiveOptions,
2548
+ explicitBytes: configuredOptionalInteger("FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * 1024 ** 2, 128 * 1024 ** 3),
2373
2549
  });
2374
- const minimumIdleReserveBytes = Math.min(hostReserveBytes, reserveFloorBytes);
2550
+ const defaultHardMaxAttempts = Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2)));
2551
+ const idleReserveOverride = Number.parseInt(process.env.FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES ?? "", 10);
2552
+ const idleReserveOverrideBytes = Number.isFinite(idleReserveOverride) ? idleReserveOverride : null;
2375
2553
  return {
2376
- hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", Math.max(1, Math.min(8, Math.floor(sampledCpuCount / 2))), 1, 32),
2554
+ hardMaxAttempts: configuredInteger("FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", defaultHardMaxAttempts, 1, 32),
2377
2555
  hostReserveBytes,
2378
- idleHostReserveBytes: configuredInteger("FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES", minimumIdleReserveBytes, 512 * 1024 ** 2, hostReserveBytes),
2556
+ idleHostReserveBytes: idleHostReserveBytesFor(hostReserveBytes, { reserveFloorBytes, idleReserveOverrideBytes }),
2557
+ defaultHardMaxAttempts,
2558
+ adaptiveHostReserveBytes: resolveAdaptiveMemoryReserveBytes(totalMemoryBytes, adaptiveOptions),
2559
+ reserveFloorBytes,
2560
+ idleReserveOverrideBytes,
2379
2561
  cpuReserveMillis: configuredInteger("FORGE_HOST_CPU_RESERVE_MILLIS", 1000, 0, 32_000),
2380
2562
  workspaceReserveBytes: configuredInteger("FORGE_HOST_WORKSPACE_RESERVE_BYTES", 10 * 1024 ** 3, 1024 ** 3, Number.MAX_SAFE_INTEGER),
2381
2563
  memoryRecoverySamples: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLES", 2, 1, 10),
2382
2564
  memoryRecoverySampleIntervalMs: configuredInteger("FORGE_HOST_MEMORY_RECOVERY_SAMPLE_INTERVAL_MS", 1_000, 100, 30_000),
2383
2565
  };
2384
2566
  }
2567
+ /**
2568
+ * The reserve kept while no attempt holds capacity: FORGE_HOST_IDLE_MEMORY_RESERVE_BYTES
2569
+ * clamped to [512 MiB, reserve], else min(reserve, reserve floor). Never above the reserve.
2570
+ */
2571
+ function idleHostReserveBytesFor(hostReserveBytes, configuration) {
2572
+ const fallback = Math.min(hostReserveBytes, configuration.reserveFloorBytes);
2573
+ const override = configuration.idleReserveOverrideBytes;
2574
+ return override === null ? fallback : Math.max(512 * 1024 ** 2, Math.min(hostReserveBytes, override));
2575
+ }
2385
2576
  function configuredOptionalInteger(name, minimum, maximum) {
2386
2577
  const raw = process.env[name];
2387
2578
  if (raw === undefined || raw.trim().length === 0)
@@ -28,5 +28,28 @@ export declare class HostParallelPromotionStore {
28
28
  private recordPath;
29
29
  }
30
30
  export declare function hostRuntimeContractFingerprint(runtimeContract: LoadedHostRuntimeContract): string;
31
+ export interface ReadmittedHostRuntimeContract {
32
+ readonly runtimeContract: LoadedHostRuntimeContract;
33
+ readonly runtimeContractFingerprint: string;
34
+ readonly changed: boolean;
35
+ }
36
+ /**
37
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
38
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
39
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
40
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
41
+ * merging the target branch can rename a variable in a derived launch profile, or change a
42
+ * manifest or project file, without changing anything admission granted. Every other part of the
43
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
44
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
45
+ * profile, singleton resources and declared requirements. Changing any of those throws the
46
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
47
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
48
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
49
+ */
50
+ export declare function readmitHostRuntimeContract(admitted: {
51
+ readonly runtimeContract: LoadedHostRuntimeContract;
52
+ readonly runtimeContractFingerprint: string;
53
+ }, current: LoadedHostRuntimeContract): ReadmittedHostRuntimeContract;
31
54
  export declare function hostRuntimeParallelEligible(runtimeContract: LoadedHostRuntimeContract): boolean;
32
55
  export declare function configuredLaunchPortNames(runtimeContract: LoadedHostRuntimeContract): readonly string[];
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { ForgeFailureError } from "../session/session.types.js";
4
5
  /** Persists only observed, contract-bound host parallel-safety evidence. */
5
6
  export class HostParallelPromotionStore {
6
7
  stateRoot;
@@ -154,6 +155,41 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
154
155
  });
155
156
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
156
157
  }
158
+ /**
159
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
160
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
161
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
162
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
163
+ * merging the target branch can rename a variable in a derived launch profile, or change a
164
+ * manifest or project file, without changing anything admission granted. Every other part of the
165
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
166
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
167
+ * profile, singleton resources and declared requirements. Changing any of those throws the
168
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
169
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
170
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
171
+ */
172
+ export function readmitHostRuntimeContract(admitted, current) {
173
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(current);
174
+ // The fingerprint leaves out the source of a project or default contract, but parallel
175
+ // eligibility depends on it, so an unchanged fingerprint alone does not prove the same admission.
176
+ if (runtimeContractFingerprint === admitted.runtimeContractFingerprint && current.source === admitted.runtimeContract.source) {
177
+ return { runtimeContract: admitted.runtimeContract, runtimeContractFingerprint, changed: false };
178
+ }
179
+ if (hostRuntimeAdmissionShape(current) !== hostRuntimeAdmissionShape(admitted.runtimeContract)) {
180
+ 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.");
181
+ }
182
+ return { runtimeContract: current, runtimeContractFingerprint, changed: true };
183
+ }
184
+ function hostRuntimeAdmissionShape(runtimeContract) {
185
+ const runtime = runtimeContract.contract.runtime;
186
+ return JSON.stringify({
187
+ source: runtimeContract.source,
188
+ schemaVersion: runtimeContract.contract.schemaVersion,
189
+ runtime: { ...runtime, ports: runtime.ports.map(port => ({ ...port, launch: port.launch && { ...port.launch, environment: undefined } })) },
190
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
191
+ });
192
+ }
157
193
  // Cost hints are estimates, not placement constraints: they never change the fingerprint.
158
194
  function requirementsFingerprintPart(requires) {
159
195
  if (!requires)
@@ -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);
@@ -0,0 +1,100 @@
1
+ import { type HostLoadGovernorMode } from "./host-load-governor-config.js";
2
+ export declare const runnerSettingKeys: readonly ["maxConcurrentAttempts", "cpuBudgetPercent", "yieldCpuBudgetPercent", "memoryReserveBytes", "maxHeavySteps", "yieldToForeground"];
3
+ export type RunnerSettingKey = typeof runnerSettingKeys[number];
4
+ /** The `ApplySettings` hub message. Null numeric fields mean "no server value": keep today's env/default behaviour. */
5
+ export interface RunnerSettingsDocument {
6
+ readonly runnerId: string | null;
7
+ readonly version: number;
8
+ readonly maxConcurrentAttempts: number | null;
9
+ readonly cpuBudgetPercent: number | null;
10
+ readonly yieldCpuBudgetPercent: number | null;
11
+ readonly memoryReserveBytes: number | null;
12
+ readonly maxHeavySteps: number | null;
13
+ readonly yieldToForeground: boolean;
14
+ }
15
+ export interface RunnerSettingsValues {
16
+ readonly maxConcurrentAttempts: number;
17
+ readonly cpuBudgetPercent: number;
18
+ readonly yieldCpuBudgetPercent: number;
19
+ readonly memoryReserveBytes: number;
20
+ /** Null: the governor's budget alone limits heavy steps (no count limit). */
21
+ readonly maxHeavySteps: number | null;
22
+ readonly yieldToForeground: boolean;
23
+ }
24
+ /**
25
+ * Where an effective value came from: the server's value as is, the bridge default,
26
+ * an env var that capped/floored the server value or supplied it, or the host's
27
+ * `forge-bridge yield on` flag.
28
+ */
29
+ export type RunnerSettingSource = "server" | "default" | "host_env" | "host_local";
30
+ export interface RunnerSettingBound {
31
+ readonly key: RunnerSettingKey;
32
+ readonly envVar: string;
33
+ readonly value: number;
34
+ readonly kind: "ceiling" | "floor";
35
+ }
36
+ /**
37
+ * Why a key was rejected. `invalid`: the server value is outside the contract, so
38
+ * the host default applies (version skew; it never holds placement). `apply_failed`:
39
+ * the host could not put the value in force, so the previous value stays in force
40
+ * and the server holds placement until a later apply succeeds. Clamping by an env
41
+ * bound is neither: it is a `bound` and a `host_env` source.
42
+ */
43
+ export type RunnerSettingRejectionKind = "invalid" | "apply_failed";
44
+ export interface RunnerSettingRejection {
45
+ readonly key: RunnerSettingKey;
46
+ readonly reason: string;
47
+ readonly kind: RunnerSettingRejectionKind;
48
+ }
49
+ /** The `SettingsApplied` report; also carried in the capabilities `settings` block (schema 8). */
50
+ export interface RunnerSettingsReport {
51
+ /** The applied document version, or null before any ApplySettings was applied. */
52
+ readonly version: number | null;
53
+ /** FORGE_HOST_LOAD_GOVERNOR: CPU budget, yield budget and heavy steps only take effect when on. */
54
+ readonly governor: HostLoadGovernorMode;
55
+ readonly values: RunnerSettingsValues;
56
+ readonly sources: Readonly<Record<RunnerSettingKey, RunnerSettingSource>>;
57
+ readonly bounds: readonly RunnerSettingBound[];
58
+ readonly rejected: readonly RunnerSettingRejection[];
59
+ }
60
+ /** Today's bridge defaults for the keys whose default depends on the host. */
61
+ export interface RunnerHostDefaults {
62
+ /** floor(threads / 2) capped at 8 (at least 1). */
63
+ readonly maxConcurrentAttempts: number;
64
+ /** The adaptive reserve: 12.5% of RAM within 1–4 GiB, before FORGE_HOST_MEMORY_RESERVE_BYTES. */
65
+ readonly memoryReserveBytes: number;
66
+ }
67
+ export interface EffectiveRunnerSettings {
68
+ readonly report: RunnerSettingsReport;
69
+ /** Effective yield (server OR local flag). */
70
+ readonly yielding: boolean;
71
+ /**
72
+ * The governor CPU budget in force, as a fraction of logical CPUs: the CPU budget,
73
+ * or min(yield budget, CPU budget) while yielding.
74
+ */
75
+ readonly governorCpuBudgetFraction: number;
76
+ }
77
+ export declare const defaultCpuBudgetPercent = 80;
78
+ export declare const defaultYieldCpuBudgetPercent = 50;
79
+ /**
80
+ * Computes every effective value (decision 0014 precedence):
81
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
82
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
83
+ * - yield: server OR the local `forge-bridge yield on` flag.
84
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
85
+ */
86
+ export declare function computeEffectiveRunnerSettings(document: RunnerSettingsDocument | null, environment: Readonly<Record<string, string | undefined>>, hostDefaults: RunnerHostDefaults, localYield: boolean): EffectiveRunnerSettings;
87
+ /**
88
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
89
+ * (the bridge then ignores it); malformed values become null so the host default applies.
90
+ */
91
+ export declare function parseRunnerSettingsDocument(raw: unknown): RunnerSettingsDocument | null;
92
+ /**
93
+ * The report for what is actually in force after an apply in which the host
94
+ * failed to put some keys in force: each failed key keeps the value (and source)
95
+ * that was in force before, and its failure is reported as an `apply_failed`
96
+ * rejection, so the server never reads a desired value as applied.
97
+ */
98
+ export declare function runnerSettingsInForce(report: RunnerSettingsReport, previous: RunnerSettingsReport, failures: readonly RunnerSettingRejection[]): RunnerSettingsReport;
99
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
100
+ export declare function sameRunnerSettingsReport(left: RunnerSettingsReport, right: RunnerSettingsReport): boolean;