@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c1ae24134918

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 (131) hide show
  1. package/README.md +3 -3
  2. package/dist/bridge/bridge.service.d.ts +14 -1
  3. package/dist/bridge/bridge.service.js +81 -9
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  8. package/dist/bridge/runner-host-capabilities.js +4 -0
  9. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  10. package/dist/bridge/test-postgres-capability.js +120 -0
  11. package/dist/cli/cli.help.js +2 -2
  12. package/dist/cli/cli.service.js +3 -1
  13. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  14. package/dist/runtime/attempt-database-broker.js +390 -0
  15. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  16. package/dist/runtime/attempt-process-supervisor.js +77 -3
  17. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  18. package/dist/runtime/host-database-capability-boundary.js +1 -0
  19. package/dist/runtime/host-diagnostics.js +4 -3
  20. package/dist/runtime/host-facts.d.ts +35 -0
  21. package/dist/runtime/host-facts.js +95 -0
  22. package/dist/runtime/host-load-admission.d.ts +52 -0
  23. package/dist/runtime/host-load-admission.js +84 -0
  24. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  25. package/dist/runtime/host-load-child-environment.js +65 -0
  26. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  27. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  28. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  29. package/dist/runtime/host-load-governor-config.js +46 -0
  30. package/dist/runtime/host-load-governor.d.ts +172 -0
  31. package/dist/runtime/host-load-governor.js +519 -0
  32. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  33. package/dist/runtime/host-load-ledger-lock.js +185 -0
  34. package/dist/runtime/host-load-sampler.d.ts +126 -0
  35. package/dist/runtime/host-load-sampler.js +232 -0
  36. package/dist/runtime/host-load-step-class.d.ts +68 -0
  37. package/dist/runtime/host-load-step-class.js +106 -0
  38. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  39. package/dist/runtime/host-load-step-reaper.js +95 -0
  40. package/dist/runtime/host-load-step-run.d.ts +73 -0
  41. package/dist/runtime/host-load-step-run.js +102 -0
  42. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  43. package/dist/runtime/host-load-token-ledger.js +421 -0
  44. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  45. package/dist/runtime/host-pressure-stall.js +168 -0
  46. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  47. package/dist/runtime/host-runtime-contract.js +75 -11
  48. package/dist/runtime/host-runtime-lease.d.ts +19 -3
  49. package/dist/runtime/host-runtime-lease.js +188 -25
  50. package/dist/runtime/host-runtime-promotion.js +12 -0
  51. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  52. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  53. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  54. package/dist/runtime/host-runtime-requirements.js +117 -0
  55. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  56. package/dist/runtime/managed-command-teardown.js +607 -0
  57. package/dist/runtime/node-host-runtime-adapter.js +5 -4
  58. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  59. package/dist/runtime/playwright-browser-cache.js +227 -0
  60. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  61. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  62. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  63. package/dist/sandbox/host-capacity-broker.js +315 -0
  64. package/dist/sandbox/repository-lock.js +3 -2
  65. package/dist/sandbox/runtime.d.ts +10 -1
  66. package/dist/sandbox/runtime.js +50 -6
  67. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  68. package/dist/sandbox/sandbox-cgroups.js +42 -0
  69. package/dist/session/managed-attempt-tools.d.ts +25 -0
  70. package/dist/session/managed-attempt-tools.js +330 -32
  71. package/dist/session/managed-build-coordinator.d.ts +1 -1
  72. package/dist/session/managed-build-coordinator.js +8 -4
  73. package/dist/session/managed-command-host-load.d.ts +45 -0
  74. package/dist/session/managed-command-host-load.js +82 -0
  75. package/dist/session/phase-completion.artifacts.js +4 -0
  76. package/dist/session/phase-completion.d.ts +2 -0
  77. package/dist/session/phase-completion.runtime.d.ts +1 -1
  78. package/dist/session/phase-completion.runtime.js +44 -24
  79. package/dist/session/pre-publication-host-load.d.ts +27 -0
  80. package/dist/session/pre-publication-host-load.js +111 -0
  81. package/dist/session/pre-publication-process.d.ts +23 -0
  82. package/dist/session/pre-publication-process.js +109 -0
  83. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  84. package/dist/session/pre-publication-skipped-tests.js +109 -0
  85. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  86. package/dist/session/pre-publication-step-execution.js +49 -0
  87. package/dist/session/pre-publication-validation.d.ts +9 -9
  88. package/dist/session/pre-publication-validation.js +53 -113
  89. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  90. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  91. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  92. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  93. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  94. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  95. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  96. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  97. package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
  98. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  99. package/dist/session/provider-cli/provider-cli.service.js +144 -35
  100. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  101. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  102. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  103. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  104. package/dist/session/provider-cli/provider-output-state.js +9 -0
  105. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  106. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  107. package/dist/session/publishable-worktree-changes.js +193 -0
  108. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  109. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  110. package/dist/session/session.base.d.ts +3 -0
  111. package/dist/session/session.service.d.ts +2 -0
  112. package/dist/session/session.service.js +21 -4
  113. package/dist/session/session.types.d.ts +3 -0
  114. package/dist/session/session.types.js +14 -2
  115. package/dist/shared/process/host-process-recovery.js +3 -2
  116. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  117. package/dist/shared/process/host-process-supervisor.js +6 -5
  118. package/dist/shared/process/process-tree.d.ts +52 -0
  119. package/dist/shared/process/process-tree.js +144 -0
  120. package/dist/shared/process/process.d.ts +67 -0
  121. package/dist/shared/process/process.js +213 -11
  122. package/dist/shared/time/monotonic.d.ts +1 -0
  123. package/dist/shared/time/monotonic.js +8 -0
  124. package/dist/version.d.ts +1 -1
  125. package/dist/version.js +1 -1
  126. package/dist/worktree/dependency-warmer.d.ts +25 -0
  127. package/dist/worktree/dependency-warmer.js +120 -10
  128. package/dist/worktree/worktree.service.d.ts +6 -1
  129. package/dist/worktree/worktree.service.js +14 -2
  130. package/dist/worktree/worktree.types.d.ts +7 -0
  131. package/package.json +1 -1
@@ -7,14 +7,18 @@ import { assertHostAttemptRootIdentity, retainHostDiagnostics } from "./host-dia
7
7
  import { assertHostExecutionRoot, compactHostAttemptId } from "./host-execution-root.js";
8
8
  import { PreparedRuntimeReadiness } from "./prepared-runtime-readiness.js";
9
9
  import { preparedRuntimeIdentity } from "./prepared-runtime-identity.js";
10
+ import { ForgeFailureError } from "../session/session.types.js";
10
11
  import { resolveExistingDirectoryPath } from "../shared/path/path.js";
11
12
  import { formatBytes } from "../shared/format/format-bytes.js";
13
+ import { redactText } from "../shared/redaction/redaction.js";
12
14
  import { StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.process.js";
13
15
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "./runtime-isolation-lease.js";
14
16
  import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-contract.js";
15
17
  import { HostPortBroker, } from "./host-port-broker.js";
16
18
  import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
17
19
  import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
20
+ import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
21
+ import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
18
22
  import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
19
23
  import { HostListenerInspector } from "./host-listener-inspector.js";
20
24
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
@@ -27,6 +31,11 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
27
31
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
28
32
  import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
29
33
  import { createAspNetRuntimePrebuildPlan, ensureAspNetRuntimePrebuilt, resolveWorktreeCommitSha, } from "./aspnet-runtime-prebuild.js";
34
+ import { HostLoadGovernor } from "./host-load-governor.js";
35
+ import { hostLoadChildEnvironment } from "./host-load-child-environment.js";
36
+ import { aspNetPrebuildStepClass } from "./host-load-step-class.js";
37
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "./host-load-step-run.js";
38
+ import { HostLoadSampler } from "./host-load-sampler.js";
30
39
  const hostCapacityWaiterScanLimit = 64;
31
40
  const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
32
41
  export class HostRuntimeLeaseManager {
@@ -38,6 +47,7 @@ export class HostRuntimeLeaseManager {
38
47
  playwrightAdapter;
39
48
  processRecovery;
40
49
  capacityResourceSample;
50
+ databaseBroker;
41
51
  preparedReadiness;
42
52
  active = new Map();
43
53
  pendingRenewals = new Map();
@@ -60,7 +70,14 @@ export class HostRuntimeLeaseManager {
60
70
  capacityConfiguration;
61
71
  memoryAvailability;
62
72
  executionRoot;
63
- constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot) {
73
+ /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
74
+ hostLoadGovernor;
75
+ requirementsCheck = null;
76
+ /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
77
+ setRequirementsCheck(check) {
78
+ this.requirementsCheck = check;
79
+ }
80
+ constructor(stateRoot, portBroker = new HostPortBroker(), nodeAdapter, processSupervisors = new AttemptProcessSupervisorRegistry(), processRunner = new StreamingProviderProcessRunner(), listenerInspector = new HostListenerInspector(), promotionStore = new HostParallelPromotionStore(stateRoot), playwrightAdapter = new PlaywrightHostRuntimeAdapter(), processRecovery = new ExactHostProcessRecovery(), capacityResourceSample, executionRoot, databaseBroker = null, hostLoad = null) {
64
81
  this.stateRoot = stateRoot;
65
82
  this.processSupervisors = processSupervisors;
66
83
  this.processRunner = processRunner;
@@ -69,6 +86,8 @@ export class HostRuntimeLeaseManager {
69
86
  this.playwrightAdapter = playwrightAdapter;
70
87
  this.processRecovery = processRecovery;
71
88
  this.capacityResourceSample = capacityResourceSample;
89
+ this.databaseBroker = databaseBroker;
90
+ this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
72
91
  this.executionRoot = path.resolve(executionRoot ?? stateRoot);
73
92
  if (executionRoot !== undefined)
74
93
  assertHostExecutionRoot(this.executionRoot);
@@ -78,7 +97,12 @@ export class HostRuntimeLeaseManager {
78
97
  this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
79
98
  this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
80
99
  }
100
+ hostLoadChildEnvironment() {
101
+ return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
102
+ }
81
103
  async reap(options) {
104
+ // Heavy-step tokens whose owner died or whose lease lapsed are returned first.
105
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
82
106
  await this.refreshKnownPromotions();
83
107
  const recoveredAttempts = [];
84
108
  const report = {
@@ -199,6 +223,15 @@ export class HostRuntimeLeaseManager {
199
223
  report.degraded += 1;
200
224
  }
201
225
  }
226
+ // Databases issued to attempts that ended without a clean release (a Bridge crash, or a
227
+ // drop that met a lingering session) are removed once no live lease holds them.
228
+ // A degraded lease may still own running processes after a restart, so its database is kept.
229
+ await this.databaseBroker?.reapOrphans(id => this.active.has(id) || this.degraded.has(id)).catch(() => undefined);
230
+ // Heavy-step tokens of a dead owner with no recorded process tree (an attempt that
231
+ // ended with a crashed bridge or MCP server) are returned once no live lease holds
232
+ // their attempt; a degraded lease may still own the running step, so its tokens stay.
233
+ await this.hostLoadGovernor.releaseOrphaned(token => !token.dispatchAttemptId
234
+ || (!this.active.has(token.dispatchAttemptId) && !this.degraded.has(token.dispatchAttemptId))).catch(() => undefined);
202
235
  return report;
203
236
  }
204
237
  snapshot() {
@@ -887,7 +920,7 @@ export class HostRuntimeLeaseManager {
887
920
  }
888
921
  return {
889
922
  lease: existing.lease,
890
- environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass),
923
+ environment: hostRuntimeEnvironment(dispatch.session.id, existing.lease, existing.runtimeContract, existing.executionClass, existing.databaseCapability),
891
924
  runtimeContract: existing.runtimeContract,
892
925
  executionClass: existing.executionClass,
893
926
  };
@@ -916,6 +949,15 @@ export class HostRuntimeLeaseManager {
916
949
  let attemptRootIdentity = null;
917
950
  try {
918
951
  const runtimeContract = await loadHostRuntimeContract(normalizedWorktreePath);
952
+ // Decision 0013 accept-time recheck. Readiness probes are exempt: they are how the
953
+ // API learns the requirements in the first place.
954
+ const unmetRequirements = dispatch.workItem.kind === "runtime_readiness"
955
+ ? []
956
+ : this.requirementsCheck?.(runtimeContract.contract.requires) ?? [];
957
+ if (unmetRequirements.length > 0) {
958
+ // Typed, so the API receives the retryable code and re-places the work (not bridge.execution_failed).
959
+ throw new ForgeFailureError("placement_requirements_unmet", `placement_requirements_unmet: this host does not meet the project's requirements: ${unmetRequirements.join("; ")}.`);
960
+ }
919
961
  if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
920
962
  throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
921
963
  }
@@ -1149,7 +1191,7 @@ export class HostRuntimeLeaseManager {
1149
1191
  if (active.executionClass === "analysis_only") {
1150
1192
  return {
1151
1193
  lease: active.lease,
1152
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1194
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1153
1195
  runtimeContract: active.runtimeContract,
1154
1196
  executionClass: active.executionClass,
1155
1197
  };
@@ -1158,21 +1200,49 @@ export class HostRuntimeLeaseManager {
1158
1200
  if (configuredPorts.length === 0) {
1159
1201
  return {
1160
1202
  lease: active.lease,
1161
- environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1203
+ environment: hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1162
1204
  runtimeContract: active.runtimeContract,
1163
1205
  executionClass: active.executionClass,
1164
1206
  };
1165
1207
  }
1208
+ const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
1209
+ // A host without the project's pinned browsers fails here, before any database,
1210
+ // build, launch, or promotion work that the attempt would otherwise waste.
1211
+ if (playwrightConfig)
1212
+ await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
1166
1213
  const owner = hostPortOwner(active.lease);
1167
1214
  const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
1168
1215
  if (!logDirectory)
1169
1216
  throw new Error("host_runtime_project_invalid: attempt log directory is unavailable.");
1170
- const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector);
1217
+ if (this.databaseBroker && !active.databaseCapability
1218
+ && configuredPorts.some(port => /^dotnet(?:\.exe)?$/iu.test(path.basename(port.launch.command)))) {
1219
+ // An ASP.NET runtime may require an isolated database (Forge.Api refuses to start in a
1220
+ // managed host attempt without one). Issue it before the first launch. Release waits for
1221
+ // an in-flight provision, so a database issued during release is still dropped.
1222
+ const provision = this.databaseBroker.provision(dispatchAttemptId, fencingToken, signal)
1223
+ .then(capability => {
1224
+ active.databaseCapability = capability;
1225
+ return capability;
1226
+ });
1227
+ active.databaseProvision = provision;
1228
+ await provision;
1229
+ if (active.releasing) {
1230
+ throw new Error("host_runtime_project_unavailable: the host runtime lease was released during database provisioning.");
1231
+ }
1232
+ await onProjectCheckpoint?.({
1233
+ code: "host_runtime_database_provisioned",
1234
+ message: `Provisioned isolated attempt database ${active.databaseCapability.databaseName} on the native test cluster.`,
1235
+ data: { database: active.databaseCapability.databaseName },
1236
+ });
1237
+ }
1238
+ // Runtime output is persisted to attempt logs; the database login it may print is redacted.
1239
+ const capabilitySecrets = attemptDatabaseCapabilitySecrets(active.databaseCapability?.connectionString);
1240
+ const launcher = new AttemptNodeRuntimeLauncher(active.processSupervisor, owner, logDirectory, this.listenerInspector, capabilitySecrets);
1171
1241
  for (const configuredPort of configuredPorts) {
1172
1242
  const workingDirectory = await containedWorkingDirectory(active.lease.worktreePath, configuredPort.launch.workingDirectory);
1173
1243
  const buildEnvironment = {
1174
1244
  ...configuredPort.launch.environment,
1175
- ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass),
1245
+ ...hostRuntimeEnvironment(active.sessionId, active.lease, active.runtimeContract, active.executionClass, active.databaseCapability),
1176
1246
  };
1177
1247
  const prebuild = createAspNetRuntimePrebuildPlan({
1178
1248
  command: configuredPort.launch.command,
@@ -1189,7 +1259,29 @@ export class HostRuntimeLeaseManager {
1189
1259
  message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
1190
1260
  data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
1191
1261
  });
1192
- const build = await ensureAspNetRuntimePrebuilt(prebuild, async (plan, buildSignal) => await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, buildSignal), signal);
1262
+ let hostLoadWaitMs = null;
1263
+ const build = await ensureAspNetRuntimePrebuilt(prebuild,
1264
+ // Only a real build (not a verified cache hit) takes a host load token.
1265
+ async (plan, buildSignal) => await runHostGovernedStep(this.hostLoadGovernor, {
1266
+ classification: aspNetPrebuildStepClass,
1267
+ label: prebuild.projectPath,
1268
+ dispatchAttemptId,
1269
+ priority: this.admissions.get(dispatchAttemptId)?.priority ?? "foreground",
1270
+ signal: buildSignal,
1271
+ onWaiting: async (decision) => await onProjectCheckpoint?.({
1272
+ code: "host_runtime_build_waiting_for_host_capacity",
1273
+ message: `The ASP.NET runtime build is waiting for host capacity: ${decision.detail}`,
1274
+ data: { status: "waiting_for_host_capacity", step_class: aspNetPrebuildStepClass.stepClass, reason: decision.reason },
1275
+ }),
1276
+ }, async (waitMs, control) => {
1277
+ hostLoadWaitMs = waitMs;
1278
+ // A reclaimed token stops the build: its capacity is no longer reserved. So does a
1279
+ // build whose process tree cannot be recorded on its token (a reclaim could not stop it).
1280
+ const unrecorded = new AbortController();
1281
+ const stepSignal = anySignal(buildSignal, control.fenced, unrecorded.signal);
1282
+ return await executeAspNetRuntimeBuild(active.processSupervisor, logDirectory, plan, stepSignal, capabilitySecrets, async (metadataPath) => await attachSupervisedStepProcess(control, metadataPath)
1283
+ .catch((error) => { unrecorded.abort(error); }));
1284
+ }), signal);
1193
1285
  await onProjectCheckpoint?.({
1194
1286
  code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
1195
1287
  message: build.cacheHit
@@ -1199,6 +1291,7 @@ export class HostRuntimeLeaseManager {
1199
1291
  input_commit_sha: active.inputCommitSha,
1200
1292
  build_fingerprint: build.fingerprint,
1201
1293
  receipt_path: build.receiptPath,
1294
+ ...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
1202
1295
  },
1203
1296
  });
1204
1297
  }
@@ -1212,7 +1305,7 @@ export class HostRuntimeLeaseManager {
1212
1305
  }, launcher, signal);
1213
1306
  }
1214
1307
  const promotedLease = await this.promoteVerifiedRuntime(active, active.lease);
1215
- const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass);
1308
+ const runtimeEnvironment = hostRuntimeEnvironment(active.sessionId, promotedLease, active.runtimeContract, active.executionClass, active.databaseCapability);
1216
1309
  const playwright = active.runtimeContract.contract.runtime.playwright;
1217
1310
  if (!playwright) {
1218
1311
  return {
@@ -1383,6 +1476,9 @@ export class HostRuntimeLeaseManager {
1383
1476
  if (!preservePreparation)
1384
1477
  this.pendingRenewals.delete(dispatchAttemptId);
1385
1478
  if (!active) {
1479
+ // Queued steps are cancelled and running ones stopped; each returns its own
1480
+ // token once its processes are gone (never before, or capacity is reused early).
1481
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1386
1482
  this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
1387
1483
  this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
1388
1484
  this.releaseParallelProjects(dispatchAttemptId, fencingToken);
@@ -1392,17 +1488,36 @@ export class HostRuntimeLeaseManager {
1392
1488
  if (active.lease.fencingToken !== fencingToken)
1393
1489
  return null;
1394
1490
  active.releasing = true;
1491
+ // Attempt teardown cancels the attempt's queued heavy steps and stops its running
1492
+ // ones. Each running step (an ASP.NET prebuild, an install, a validation step)
1493
+ // returns its own token only after its processes have exited, so the capacity is
1494
+ // not reused while, say, a build is still being terminated.
1495
+ this.hostLoadGovernor.stopAttempt(dispatchAttemptId);
1395
1496
  for (const pending of active.pendingAdapterLaunches.values()) {
1396
1497
  pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
1397
1498
  }
1398
1499
  await Promise.allSettled([...active.pendingAdapterLaunches.values()].map(pending => pending.promise));
1500
+ await active.databaseProvision?.catch(() => undefined);
1399
1501
  let releasing = transitionRuntimeIsolationLease(active.lease, "releasing");
1400
1502
  active.lease = releasing;
1401
1503
  await this.writeLedger(releasing);
1402
1504
  try {
1403
1505
  if (!active.runtimeResourcesReleased) {
1404
1506
  await active.processSupervisor.stopAll(fencingToken, "Host runtime lease released.");
1507
+ // The attempt's MCP servers and process trees are stopped now; tokens they held
1508
+ // belong to dead owners and go back to the host budget at once, including any
1509
+ // without a recorded process tree (their steps were inside the stopped trees).
1510
+ await this.hostLoadGovernor.reclaim().catch(() => undefined);
1511
+ await this.hostLoadGovernor.releaseOrphaned(token => token.dispatchAttemptId === dispatchAttemptId)
1512
+ .catch(() => undefined);
1513
+ // This bridge's own steps whose trees only stopAll could prove gone (a supervised
1514
+ // validation step whose termination failed earlier) return their tokens now.
1515
+ await this.hostLoadGovernor.releaseRetainedAfterTeardown(dispatchAttemptId).catch(() => undefined);
1405
1516
  await releaseAdapterResources(active.adapterCleanups);
1517
+ if (active.databaseCapability && this.databaseBroker) {
1518
+ // A database the broker cannot drop now is reaped later; it must not hold host capacity.
1519
+ await this.databaseBroker.release(dispatchAttemptId, fencingToken).catch(() => "retained");
1520
+ }
1406
1521
  active.runtimeResourcesReleased = true;
1407
1522
  // Runtime admission protects live processes, listeners, ports, and their
1408
1523
  // memory commitment. Once exact process and adapter cleanup succeeds,
@@ -1496,18 +1611,46 @@ export class HostRuntimeLeaseManager {
1496
1611
  if (logsEntry.kind !== "directory") {
1497
1612
  throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
1498
1613
  }
1499
- const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1500
1614
  const outcomes = [];
1501
- for (const entry of entries) {
1502
- if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1503
- continue;
1504
- const metadataPath = path.join(logsRoot, entry.name);
1505
- const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1506
- if (!validHostProcessSupervisorMetadata(value, lease)) {
1507
- throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1615
+ const failures = [];
1616
+ try {
1617
+ const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
1618
+ for (const entry of entries) {
1619
+ if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
1620
+ continue;
1621
+ const metadataPath = path.join(logsRoot, entry.name);
1622
+ const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
1623
+ if (!validHostProcessSupervisorMetadata(value, lease)) {
1624
+ throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
1625
+ }
1626
+ outcomes.push(await this.processRecovery.recover(value));
1627
+ }
1628
+ }
1629
+ catch (error) {
1630
+ failures.push(error);
1631
+ }
1632
+ // Managed commands run in their own process groups and record their ownership apart
1633
+ // from the attempt's supervised children. They are recovered even when recovering a
1634
+ // supervised child failed, and both failures are reported together.
1635
+ try {
1636
+ const managed = await terminateAttemptManagedCommands({
1637
+ logDirectory: logsRoot,
1638
+ dispatchAttemptId: lease.dispatchAttemptId,
1639
+ runtimeLeaseId: lease.executionLeaseId,
1640
+ pinnedLogDirectory: logsEntry.identity,
1641
+ }, { reason: "attempt_teardown" });
1642
+ for (const command of managed) {
1643
+ if (command.outcome === "terminated" || command.outcome === "pid_reused")
1644
+ outcomes.push(command.outcome);
1508
1645
  }
1509
- outcomes.push(await this.processRecovery.recover(value));
1510
1646
  }
1647
+ catch (error) {
1648
+ failures.push(error);
1649
+ }
1650
+ if (failures.length === 1)
1651
+ throw failures[0];
1652
+ if (failures.length > 1)
1653
+ throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
1511
1654
  return outcomes;
1512
1655
  }
1513
1656
  async markLedgerDegraded(ledger) {
@@ -1883,6 +2026,18 @@ class AttemptSupervisedProviderProcessRunner {
1883
2026
  : new Set();
1884
2027
  const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
1885
2028
  this.onProcessTreeStarted();
2029
+ try {
2030
+ return await this.awaitProviderResult(child, baselineListeners, signal);
2031
+ }
2032
+ finally {
2033
+ // The provider tree, and the MCP server inside it, is gone. A managed command that
2034
+ // server started now has no supervisor and no receipt writer, so it must not keep
2035
+ // running into the next provider generation. This never rejects; a command it
2036
+ // cannot prove stopped is left to attempt teardown, which fails closed.
2037
+ await this.supervisor.stopOrphanedManagedCommands();
2038
+ }
2039
+ }
2040
+ async awaitProviderResult(child, baselineListeners, signal) {
1886
2041
  if (!this.enforceNoListeners)
1887
2042
  return await child.result;
1888
2043
  let settled = false;
@@ -1993,7 +2148,7 @@ export function hostRuntimeEventResources(lease, runtimeContract, executionClass
1993
2148
  export function hostRuntimeSingletonKeys(dispatch) {
1994
2149
  return [projectHostRuntimeSingletonKey(dispatch.repo.id)];
1995
2150
  }
1996
- function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass) {
2151
+ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClass, databaseCapability) {
1997
2152
  const pathFor = (role) => lease.resources.paths.find(entry => entry.role === role)?.path ?? "";
1998
2153
  const environment = {
1999
2154
  FORGE_SESSION_ID: sessionId,
@@ -2032,6 +2187,8 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2032
2187
  };
2033
2188
  if (lease.resources.singletonKeys.length === 0)
2034
2189
  delete environment.FORGE_SINGLETON_KEYS;
2190
+ if (databaseCapability)
2191
+ environment[attemptDatabaseCapabilityEnvironment] = databaseCapability.connectionString;
2035
2192
  const resolvedBaseUrls = [];
2036
2193
  for (const assigned of lease.resources.ports) {
2037
2194
  const configured = runtimeContract.contract.runtime.ports.find(port => port.name === assigned.name);
@@ -2056,14 +2213,19 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
2056
2213
  environment.FORGE_BASE_URL = resolvedBaseUrls[0];
2057
2214
  return environment;
2058
2215
  }
2059
- async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal) {
2216
+ function anySignal(...signals) {
2217
+ return AbortSignal.any(signals.filter((signal) => signal !== undefined));
2218
+ }
2219
+ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
2220
+ /** Once the build's supervised tree is up: records it on the build's host load token. */
2221
+ onStarted) {
2060
2222
  const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
2061
2223
  const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
2062
2224
  const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
2063
2225
  let stdoutTail = "";
2064
2226
  let stderrTail = "";
2065
2227
  const append = async (target, line) => {
2066
- await fs.appendFile(target, `${line}\n`, { encoding: "utf8", mode: 0o600 });
2228
+ await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
2067
2229
  };
2068
2230
  const child = await supervisor.startChildReady(childName, {
2069
2231
  command: plan.command,
@@ -2073,19 +2235,20 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal)
2073
2235
  captureOutput: false,
2074
2236
  }, {
2075
2237
  onStdoutLine: async (line) => {
2076
- stdoutTail = appendRuntimeBuildTail(stdoutTail, line);
2238
+ stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
2077
2239
  await append(stdoutLogPath, line);
2078
2240
  },
2079
2241
  onStderrLine: async (line) => {
2080
- stderrTail = appendRuntimeBuildTail(stderrTail, line);
2242
+ stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
2081
2243
  await append(stderrLogPath, line);
2082
2244
  },
2083
2245
  }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
2246
+ await onStarted?.(child.metadataPath);
2084
2247
  const result = await child.result;
2085
2248
  return {
2086
2249
  exitCode: result.exitCode,
2087
- stdoutTail: appendRuntimeBuildTail(stdoutTail, result.stdout),
2088
- stderrTail: appendRuntimeBuildTail(stderrTail, result.stderr),
2250
+ stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
2251
+ stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
2089
2252
  stdoutLogPath,
2090
2253
  stderrLogPath,
2091
2254
  };
@@ -2123,7 +2286,7 @@ function runtimeExecutionClass(dispatch) {
2123
2286
  ? "analysis_only"
2124
2287
  : "managed_runtime";
2125
2288
  }
2126
- function runtimeAdmissionPriority(dispatch) {
2289
+ export function runtimeAdmissionPriority(dispatch) {
2127
2290
  return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
2128
2291
  || dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
2129
2292
  ? "background"
@@ -145,12 +145,24 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
145
145
  const canonical = JSON.stringify({
146
146
  schemaVersion: runtimeContract.contract.schemaVersion,
147
147
  runtime: runtimeContract.contract.runtime,
148
+ // Requirements join the fingerprint only when declared, so fingerprints of contracts
149
+ // written before decision 0013 (and their stored promotions) stay unchanged.
150
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
148
151
  derivedCandidateFingerprint: runtimeContract.source === "derived"
149
152
  ? runtimeContract.discovery?.candidateFingerprint ?? null
150
153
  : null,
151
154
  });
152
155
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
153
156
  }
157
+ // Cost hints are estimates, not placement constraints: they never change the fingerprint.
158
+ function requirementsFingerprintPart(requires) {
159
+ if (!requires)
160
+ return {};
161
+ const { costHints: _costHints, ...constraints } = requires;
162
+ const declared = constraints.minThreads !== null || constraints.minMemoryGiB !== null || constraints.toolchains.length > 0
163
+ || constraints.docker || constraints.playwright !== null || constraints.testPostgres !== null;
164
+ return declared ? { requires: constraints } : {};
165
+ }
154
166
  export function hostRuntimeParallelEligible(runtimeContract) {
155
167
  const runtime = runtimeContract.contract.runtime;
156
168
  const launchedPorts = runtime.ports.filter(port => port.launch !== null);
@@ -0,0 +1,17 @@
1
+ import type { HostRuntimeRequirements } from "./host-runtime-requirements.js";
2
+ /** What this bridge host offers, for the accept-time requirements recheck (decision 0013). */
3
+ export interface HostRequirementFacts {
4
+ readonly logicalThreads: number;
5
+ readonly totalMemoryBytes: number;
6
+ readonly availableToolchains: readonly string[];
7
+ readonly dockerAvailable: boolean;
8
+ readonly browserLaunch: boolean;
9
+ readonly testPostgresSuperuser: boolean | null;
10
+ }
11
+ export type HostRequirementsCheck = (requires: HostRuntimeRequirements | null | undefined) => readonly string[];
12
+ /**
13
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
14
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
15
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
16
+ */
17
+ export declare function unmetHostRuntimeRequirements(requires: HostRuntimeRequirements | null | undefined, facts: HostRequirementFacts): readonly string[];
@@ -0,0 +1,29 @@
1
+ const gib = 1024 * 1024 * 1024;
2
+ /**
3
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
4
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
5
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
6
+ */
7
+ export function unmetHostRuntimeRequirements(requires, facts) {
8
+ if (!requires)
9
+ return [];
10
+ const unmet = [];
11
+ if (requires.minThreads !== null && facts.logicalThreads < requires.minThreads) {
12
+ unmet.push(`needs ≥ ${requires.minThreads} threads; this host has ${facts.logicalThreads}`);
13
+ }
14
+ if (requires.minMemoryGiB !== null && facts.totalMemoryBytes / gib < requires.minMemoryGiB) {
15
+ unmet.push(`needs ≥ ${requires.minMemoryGiB} GiB; this host has ${(Math.floor(facts.totalMemoryBytes / gib * 100) / 100)}`);
16
+ }
17
+ const available = new Set(facts.availableToolchains.map(name => name.toLowerCase()));
18
+ const missing = requires.toolchains.filter(name => !available.has(name));
19
+ if (missing.length > 0)
20
+ unmet.push(`needs ${missing.join(", ")}; this host does not have ${missing.length === 1 ? "it" : "them"}`);
21
+ if (requires.docker && !facts.dockerAvailable)
22
+ unmet.push("needs Docker; this host does not have it");
23
+ if (requires.testPostgres?.superuser && !facts.dockerAvailable && facts.testPostgresSuperuser !== true) {
24
+ unmet.push("needs Docker or a superuser test database; this host has neither");
25
+ }
26
+ if (requires.playwright && !facts.browserLaunch)
27
+ unmet.push("needs Playwright browsers; this host cannot launch them");
28
+ return unmet;
29
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Project host requirements declared in `.forge/forge.runtime.yml` (decision 0013 §3).
3
+ *
4
+ * The bridge parses them with the runtime contract and reports them, with the contract
5
+ * fingerprint, in its readiness payload. The API stores them per fingerprint and uses them
6
+ * as hard placement filters. A contract without a `requires` section has no requirements.
7
+ */
8
+ export interface HostRuntimePlaywrightRequirement {
9
+ /** Pinned Playwright revision. Recorded; enforced once bridges probe browser revisions. */
10
+ readonly revision: string | null;
11
+ }
12
+ export interface HostRuntimeTestPostgresRequirement {
13
+ readonly extensions: readonly string[];
14
+ /** Suites need a superuser role (or Docker-backed Testcontainers). */
15
+ readonly superuser: boolean;
16
+ }
17
+ export interface HostRuntimeCostHint {
18
+ readonly cores: number | null;
19
+ readonly memoryGiB: number | null;
20
+ }
21
+ export interface HostRuntimeRequirements {
22
+ readonly minThreads: number | null;
23
+ readonly minMemoryGiB: number | null;
24
+ readonly toolchains: readonly string[];
25
+ /** Suites need a Docker engine (for example Testcontainers). */
26
+ readonly docker: boolean;
27
+ readonly playwright: HostRuntimePlaywrightRequirement | null;
28
+ readonly testPostgres: HostRuntimeTestPostgresRequirement | null;
29
+ /** Accepted and reported, not yet used for placement. */
30
+ readonly costHints: Readonly<Record<string, HostRuntimeCostHint>>;
31
+ }
32
+ /**
33
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
34
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
35
+ */
36
+ export declare function parseHostRuntimeRequirements(requires: unknown, costHints: unknown): HostRuntimeRequirements | null;
@@ -0,0 +1,117 @@
1
+ const requiresKeys = new Set(["minThreads", "minMemoryGiB", "toolchains", "docker", "playwright", "testPostgres"]);
2
+ const playwrightKeys = new Set(["revision"]);
3
+ const testPostgresKeys = new Set(["extensions", "superuser"]);
4
+ const costHintKeys = new Set(["cores", "memoryGiB"]);
5
+ const toolchainPattern = /^[a-z][a-z0-9_.-]{0,63}$/u;
6
+ const extensionPattern = /^[a-z][a-z0-9_]{0,62}$/u;
7
+ const stepClassPattern = /^[a-z][a-z0-9_.:-]{0,127}$/u;
8
+ const revisionPattern = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/u;
9
+ /**
10
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
11
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
12
+ */
13
+ export function parseHostRuntimeRequirements(requires, costHints) {
14
+ if (isAbsent(requires) && isAbsent(costHints))
15
+ return null;
16
+ const section = isAbsent(requires) ? {} : object(requires, "requires");
17
+ rejectUnknownKeys(section, requiresKeys, "requires");
18
+ return {
19
+ minThreads: optionalNumber(section.minThreads, "requires.minThreads", 1, 1024, true),
20
+ minMemoryGiB: optionalNumber(section.minMemoryGiB, "requires.minMemoryGiB", 0.125, 4096, false),
21
+ toolchains: nameList(section.toolchains, "requires.toolchains", toolchainPattern, 32),
22
+ docker: optionalBoolean(section.docker, "requires.docker"),
23
+ playwright: parsePlaywright(section.playwright),
24
+ testPostgres: parseTestPostgres(section.testPostgres),
25
+ costHints: parseCostHints(costHints),
26
+ };
27
+ }
28
+ function parsePlaywright(value) {
29
+ if (isAbsent(value) || value === false)
30
+ return null;
31
+ if (value === true)
32
+ return { revision: null };
33
+ const playwright = object(value, "requires.playwright");
34
+ rejectUnknownKeys(playwright, playwrightKeys, "requires.playwright");
35
+ if (isAbsent(playwright.revision))
36
+ return { revision: null };
37
+ if (typeof playwright.revision !== "string" || !revisionPattern.test(playwright.revision.trim())) {
38
+ throw invalid("requires.playwright.revision must be a version or revision string.");
39
+ }
40
+ return { revision: playwright.revision.trim() };
41
+ }
42
+ function parseTestPostgres(value) {
43
+ if (isAbsent(value))
44
+ return null;
45
+ const testPostgres = object(value, "requires.testPostgres");
46
+ rejectUnknownKeys(testPostgres, testPostgresKeys, "requires.testPostgres");
47
+ return {
48
+ extensions: nameList(testPostgres.extensions, "requires.testPostgres.extensions", extensionPattern, 16),
49
+ superuser: optionalBoolean(testPostgres.superuser, "requires.testPostgres.superuser"),
50
+ };
51
+ }
52
+ function parseCostHints(value) {
53
+ if (isAbsent(value))
54
+ return {};
55
+ const hints = object(value, "costHints");
56
+ const entries = Object.entries(hints);
57
+ if (entries.length > 32)
58
+ throw invalid("costHints may declare at most 32 step classes.");
59
+ const parsed = {};
60
+ for (const [stepClass, hint] of entries.sort(([left], [right]) => left.localeCompare(right))) {
61
+ if (!stepClassPattern.test(stepClass))
62
+ throw invalid(`costHints step class '${stepClass}' is invalid.`);
63
+ const entry = object(hint, `costHints.${stepClass}`);
64
+ rejectUnknownKeys(entry, costHintKeys, `costHints.${stepClass}`);
65
+ parsed[stepClass] = {
66
+ cores: optionalNumber(entry.cores, `costHints.${stepClass}.cores`, 0.01, 1024, false),
67
+ memoryGiB: optionalNumber(entry.memoryGiB, `costHints.${stepClass}.memoryGiB`, 0.01, 4096, false),
68
+ };
69
+ }
70
+ return parsed;
71
+ }
72
+ function optionalNumber(value, label, minimum, maximum, integer) {
73
+ if (isAbsent(value))
74
+ return null;
75
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum
76
+ || (integer && !Number.isSafeInteger(value))) {
77
+ throw invalid(`${label} must be ${integer ? "an integer" : "a number"} between ${minimum} and ${maximum}.`);
78
+ }
79
+ return value;
80
+ }
81
+ function nameList(value, label, pattern, maximum) {
82
+ if (isAbsent(value))
83
+ return [];
84
+ if (!Array.isArray(value) || value.length > maximum) {
85
+ throw invalid(`${label} must be a list with at most ${maximum} entries.`);
86
+ }
87
+ const names = value.map((entry, index) => {
88
+ const name = typeof entry === "string" ? entry.trim().toLowerCase() : "";
89
+ if (!pattern.test(name))
90
+ throw invalid(`${label}[${index}] is invalid.`);
91
+ return name;
92
+ });
93
+ return [...new Set(names)].sort((left, right) => left.localeCompare(right));
94
+ }
95
+ function optionalBoolean(value, label) {
96
+ if (isAbsent(value))
97
+ return false;
98
+ if (typeof value !== "boolean")
99
+ throw invalid(`${label} must be true or false.`);
100
+ return value;
101
+ }
102
+ function isAbsent(value) {
103
+ return value === undefined || value === null;
104
+ }
105
+ function object(value, label) {
106
+ if (!value || typeof value !== "object" || Array.isArray(value))
107
+ throw invalid(`${label} must be an object.`);
108
+ return value;
109
+ }
110
+ function rejectUnknownKeys(value, allowed, label) {
111
+ const unknown = Object.keys(value).find(key => !allowed.has(key));
112
+ if (unknown)
113
+ throw invalid(`unknown ${label} key '${unknown}'.`);
114
+ }
115
+ function invalid(message) {
116
+ return new Error(`runtime_contract_invalid: ${message}`);
117
+ }