@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.8901ba056f68
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.
- package/README.md +2 -2
- package/dist/bridge/bridge.service.d.ts +14 -1
- package/dist/bridge/bridge.service.js +80 -9
- package/dist/bridge/bridge.types.d.ts +11 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cli/cli.service.js +3 -1
- package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
- package/dist/runtime/attempt-process-supervisor.js +50 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-admission.d.ts +52 -0
- package/dist/runtime/host-load-admission.js +84 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +65 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +34 -0
- package/dist/runtime/host-load-governor-config.js +46 -0
- package/dist/runtime/host-load-governor.d.ts +172 -0
- package/dist/runtime/host-load-governor.js +519 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-sampler.d.ts +126 -0
- package/dist/runtime/host-load-sampler.js +232 -0
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -0
- package/dist/runtime/host-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +4 -0
- package/dist/runtime/host-runtime-contract.js +6 -1
- package/dist/runtime/host-runtime-lease.d.ts +17 -3
- package/dist/runtime/host-runtime-lease.js +138 -13
- package/dist/runtime/host-runtime-promotion.js +12 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +320 -27
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/phase-completion.artifacts.js +4 -0
- package/dist/session/phase-completion.d.ts +2 -0
- package/dist/session/phase-completion.runtime.d.ts +1 -1
- package/dist/session/phase-completion.runtime.js +36 -23
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-process.d.ts +23 -0
- package/dist/session/pre-publication-process.js +109 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +9 -9
- package/dist/session/pre-publication-validation.js +48 -112
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
- package/dist/session/provider-cli/provider-cli.process.js +299 -25
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
- package/dist/session/provider-cli/provider-cli.service.js +141 -33
- package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +3 -0
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +21 -4
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +14 -2
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +6 -1
- package/dist/worktree/worktree.service.js +14 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -4,9 +4,12 @@ import path from "node:path";
|
|
|
4
4
|
import { isAlias, parseDocument, visit } from "yaml";
|
|
5
5
|
import { readCanonicalSourceFile } from "./canonical-source-file.js";
|
|
6
6
|
import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
|
|
7
|
+
import { parseHostRuntimeRequirements } from "./host-runtime-requirements.js";
|
|
7
8
|
export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
|
|
8
9
|
export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
|
|
9
10
|
export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
|
|
11
|
+
// Optional superuser login for operator-run .NET fixtures. Never reaches attempt, validation or provider processes.
|
|
12
|
+
export const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
|
|
10
13
|
const maximumContractBytes = 64 * 1024;
|
|
11
14
|
const maximumDepth = 12;
|
|
12
15
|
// Every discovery scan stops after this many directory entries. A monorepo needs a few
|
|
@@ -45,7 +48,7 @@ const ignoredDiscoveryDirectories = new Set([
|
|
|
45
48
|
"vendor",
|
|
46
49
|
"venv",
|
|
47
50
|
]);
|
|
48
|
-
const topLevelKeys = new Set(["schemaVersion", "runtime"]);
|
|
51
|
+
const topLevelKeys = new Set(["schemaVersion", "runtime", "requires", "costHints"]);
|
|
49
52
|
const runtimeKeys = new Set(["hostConcurrency", "ports", "playwright", "browserProfile", "singletonResources"]);
|
|
50
53
|
const portKeys = new Set(["adapter", "launch", "env", "baseUrlEnv", "format"]);
|
|
51
54
|
const launchKeys = new Set(["command", "args", "workingDirectory", "environment"]);
|
|
@@ -547,6 +550,7 @@ export function validateHostRuntimeContract(source) {
|
|
|
547
550
|
throw new Error("runtime_contract_invalid: runtime.browserProfile must be isolated.");
|
|
548
551
|
}
|
|
549
552
|
const ports = parsePorts(runtime.ports);
|
|
553
|
+
const requires = parseHostRuntimeRequirements(root.requires, root.costHints);
|
|
550
554
|
return {
|
|
551
555
|
schemaVersion: 1,
|
|
552
556
|
runtime: {
|
|
@@ -556,6 +560,7 @@ export function validateHostRuntimeContract(source) {
|
|
|
556
560
|
browserProfile,
|
|
557
561
|
singletonResources: parseSingletonResources(runtime.singletonResources),
|
|
558
562
|
},
|
|
563
|
+
...(requires ? { requires } : {}),
|
|
559
564
|
};
|
|
560
565
|
}
|
|
561
566
|
function parsePlaywright(value, ports) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { HostRequirementsCheck } from "./host-runtime-requirements-check.js";
|
|
2
|
+
import { type RunOnceDispatchPacket } from "../session/session.types.js";
|
|
2
3
|
import { type ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
|
|
3
4
|
import { type RuntimeIsolationLease } from "./runtime-isolation-lease.js";
|
|
4
5
|
import { type LoadedHostRuntimeContract } from "./host-runtime-contract.js";
|
|
@@ -12,6 +13,8 @@ import { type MemoryAdmissionDiagnostics } from "./memory-capacity.js";
|
|
|
12
13
|
import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
|
|
13
14
|
import { HostParallelPromotionStore } from "./host-runtime-promotion.js";
|
|
14
15
|
import { type HostProcessRecovery } from "../shared/process/host-process-recovery.js";
|
|
16
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
17
|
+
import { type HostLoadGovernorSource } from "./host-load-sampler.js";
|
|
15
18
|
export interface HostRuntimeLeaseStart {
|
|
16
19
|
readonly lease: RuntimeIsolationLease;
|
|
17
20
|
readonly environment: Readonly<Record<string, string>>;
|
|
@@ -25,7 +28,7 @@ export interface HostRuntimeAdmissionCheckpoint {
|
|
|
25
28
|
}
|
|
26
29
|
export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
|
|
27
30
|
export interface HostRuntimeProjectCheckpoint {
|
|
28
|
-
readonly code: "host_runtime_build_started" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
|
|
31
|
+
readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
|
|
29
32
|
readonly message: string;
|
|
30
33
|
readonly data?: Readonly<Record<string, unknown>>;
|
|
31
34
|
}
|
|
@@ -92,6 +95,7 @@ export interface HostNodeRuntimeLaunch<T> extends NodeRuntimeAdapterLaunch<T> {
|
|
|
92
95
|
readonly runtimeLease: RuntimeIsolationLease;
|
|
93
96
|
}
|
|
94
97
|
export interface HostRuntimeLeaseRuntime {
|
|
98
|
+
setRequirementsCheck?(check: HostRequirementsCheck | null): void;
|
|
95
99
|
acquirePreparation?(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
|
|
96
100
|
acquire(dispatch: RunOnceDispatchPacket, signal?: AbortSignal): Promise<readonly string[]>;
|
|
97
101
|
start(dispatch: RunOnceDispatchPacket, worktreePath: string, signal?: AbortSignal, onAdmissionCheckpoint?: HostRuntimeAdmissionCheckpointHandler): Promise<HostRuntimeLeaseStart>;
|
|
@@ -104,7 +108,10 @@ export interface HostRuntimeLeaseRuntime {
|
|
|
104
108
|
hasForegroundDemand?(): boolean;
|
|
105
109
|
reap?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
|
|
106
110
|
snapshot?(): HostRuntimeCapacitySnapshot;
|
|
111
|
+
/** Variables that let the completion MCP server share this host's load governor. */
|
|
112
|
+
hostLoadChildEnvironment?(): Readonly<Record<string, string>>;
|
|
107
113
|
}
|
|
114
|
+
export type HostRuntimeAdmissionPriority = "foreground" | "background";
|
|
108
115
|
export interface HostCapacityResourceSample {
|
|
109
116
|
readonly totalMemoryBytes: number;
|
|
110
117
|
readonly availableMemoryBytes: number;
|
|
@@ -143,7 +150,13 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
|
|
|
143
150
|
private readonly capacityConfiguration;
|
|
144
151
|
private readonly memoryAvailability;
|
|
145
152
|
private readonly executionRoot;
|
|
146
|
-
|
|
153
|
+
/** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
|
|
154
|
+
readonly hostLoadGovernor: HostLoadGovernor;
|
|
155
|
+
private requirementsCheck;
|
|
156
|
+
/** Installs the decision 0013 accept-time requirements recheck for host attempts. */
|
|
157
|
+
setRequirementsCheck(check: HostRequirementsCheck | null): void;
|
|
158
|
+
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);
|
|
159
|
+
hostLoadChildEnvironment(): Readonly<Record<string, string>>;
|
|
147
160
|
reap(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport>;
|
|
148
161
|
snapshot(): HostRuntimeCapacitySnapshot;
|
|
149
162
|
hasForegroundDemand(): boolean;
|
|
@@ -215,3 +228,4 @@ export declare class HostRuntimeCapacityRequestImpossibleError extends Error {
|
|
|
215
228
|
}
|
|
216
229
|
export declare function hostRuntimeEventResources(lease: RuntimeIsolationLease, runtimeContract?: LoadedHostRuntimeContract, executionClass?: HostRuntimeExecutionClass): Record<string, unknown>;
|
|
217
230
|
export declare function hostRuntimeSingletonKeys(dispatch: RunOnceDispatchPacket): readonly string[];
|
|
231
|
+
export declare function runtimeAdmissionPriority(dispatch: RunOnceDispatchPacket): HostRuntimeAdmissionPriority;
|
|
@@ -7,6 +7,7 @@ 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";
|
|
12
13
|
import { redactText } from "../shared/redaction/redaction.js";
|
|
@@ -16,6 +17,7 @@ import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-co
|
|
|
16
17
|
import { HostPortBroker, } from "./host-port-broker.js";
|
|
17
18
|
import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
|
|
18
19
|
import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
|
|
20
|
+
import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
|
|
19
21
|
import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
|
|
20
22
|
import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
|
|
21
23
|
import { HostListenerInspector } from "./host-listener-inspector.js";
|
|
@@ -29,6 +31,11 @@ import { readCanonicalSourceFile } from "./canonical-source-file.js";
|
|
|
29
31
|
import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
|
|
30
32
|
import { architectMinimumWorkspaceEstimateBytes } from "./workspace-resource-estimator.js";
|
|
31
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";
|
|
32
39
|
const hostCapacityWaiterScanLimit = 64;
|
|
33
40
|
const maximumProcessRecoveryMetadataBytes = 1024 * 1024;
|
|
34
41
|
export class HostRuntimeLeaseManager {
|
|
@@ -63,7 +70,14 @@ export class HostRuntimeLeaseManager {
|
|
|
63
70
|
capacityConfiguration;
|
|
64
71
|
memoryAvailability;
|
|
65
72
|
executionRoot;
|
|
66
|
-
|
|
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) {
|
|
67
81
|
this.stateRoot = stateRoot;
|
|
68
82
|
this.processSupervisors = processSupervisors;
|
|
69
83
|
this.processRunner = processRunner;
|
|
@@ -73,6 +87,7 @@ export class HostRuntimeLeaseManager {
|
|
|
73
87
|
this.processRecovery = processRecovery;
|
|
74
88
|
this.capacityResourceSample = capacityResourceSample;
|
|
75
89
|
this.databaseBroker = databaseBroker;
|
|
90
|
+
this.hostLoadGovernor = new HostLoadGovernor({ stateRoot, load: hostLoad ?? new HostLoadSampler() });
|
|
76
91
|
this.executionRoot = path.resolve(executionRoot ?? stateRoot);
|
|
77
92
|
if (executionRoot !== undefined)
|
|
78
93
|
assertHostExecutionRoot(this.executionRoot);
|
|
@@ -82,7 +97,12 @@ export class HostRuntimeLeaseManager {
|
|
|
82
97
|
this.capacityConfiguration = loadHostCapacityConfiguration(capacityResourceSample);
|
|
83
98
|
this.memoryAvailability = new RecoveryStabilizedMemory(this.capacityConfiguration.memoryRecoverySamples, this.capacityConfiguration.memoryRecoverySampleIntervalMs);
|
|
84
99
|
}
|
|
100
|
+
hostLoadChildEnvironment() {
|
|
101
|
+
return this.hostLoadGovernor.enabled ? hostLoadChildEnvironment(this.stateRoot) : {};
|
|
102
|
+
}
|
|
85
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);
|
|
86
106
|
await this.refreshKnownPromotions();
|
|
87
107
|
const recoveredAttempts = [];
|
|
88
108
|
const report = {
|
|
@@ -207,6 +227,11 @@ export class HostRuntimeLeaseManager {
|
|
|
207
227
|
// drop that met a lingering session) are removed once no live lease holds them.
|
|
208
228
|
// A degraded lease may still own running processes after a restart, so its database is kept.
|
|
209
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);
|
|
210
235
|
return report;
|
|
211
236
|
}
|
|
212
237
|
snapshot() {
|
|
@@ -924,6 +949,15 @@ export class HostRuntimeLeaseManager {
|
|
|
924
949
|
let attemptRootIdentity = null;
|
|
925
950
|
try {
|
|
926
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
|
+
}
|
|
927
961
|
if (runtimeContract.contract.runtime.hostConcurrency === "disabled") {
|
|
928
962
|
throw new Error("host_runtime_disabled: project runtime configuration requires Docker execution.");
|
|
929
963
|
}
|
|
@@ -1171,6 +1205,11 @@ export class HostRuntimeLeaseManager {
|
|
|
1171
1205
|
executionClass: active.executionClass,
|
|
1172
1206
|
};
|
|
1173
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);
|
|
1174
1213
|
const owner = hostPortOwner(active.lease);
|
|
1175
1214
|
const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
|
|
1176
1215
|
if (!logDirectory)
|
|
@@ -1220,7 +1259,29 @@ export class HostRuntimeLeaseManager {
|
|
|
1220
1259
|
message: `Preparing the ASP.NET runtime for commit ${active.inputCommitSha.slice(0, 12)} before binding its assigned port.`,
|
|
1221
1260
|
data: { input_commit_sha: active.inputCommitSha, project_path: prebuild.projectPath },
|
|
1222
1261
|
});
|
|
1223
|
-
|
|
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);
|
|
1224
1285
|
await onProjectCheckpoint?.({
|
|
1225
1286
|
code: build.cacheHit ? "host_runtime_build_cached" : "host_runtime_build_completed",
|
|
1226
1287
|
message: build.cacheHit
|
|
@@ -1230,6 +1291,7 @@ export class HostRuntimeLeaseManager {
|
|
|
1230
1291
|
input_commit_sha: active.inputCommitSha,
|
|
1231
1292
|
build_fingerprint: build.fingerprint,
|
|
1232
1293
|
receipt_path: build.receiptPath,
|
|
1294
|
+
...(hostLoadWaitMs === null ? {} : { host_load_wait_ms: hostLoadWaitMs }),
|
|
1233
1295
|
},
|
|
1234
1296
|
});
|
|
1235
1297
|
}
|
|
@@ -1414,6 +1476,9 @@ export class HostRuntimeLeaseManager {
|
|
|
1414
1476
|
if (!preservePreparation)
|
|
1415
1477
|
this.pendingRenewals.delete(dispatchAttemptId);
|
|
1416
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);
|
|
1417
1482
|
this.cancelAdmissionWaiters(dispatchAttemptId, fencingToken, "Managed host admission was released before acquisition.");
|
|
1418
1483
|
this.releaseSingletonKeys(dispatchAttemptId, fencingToken);
|
|
1419
1484
|
this.releaseParallelProjects(dispatchAttemptId, fencingToken);
|
|
@@ -1423,6 +1488,11 @@ export class HostRuntimeLeaseManager {
|
|
|
1423
1488
|
if (active.lease.fencingToken !== fencingToken)
|
|
1424
1489
|
return null;
|
|
1425
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);
|
|
1426
1496
|
for (const pending of active.pendingAdapterLaunches.values()) {
|
|
1427
1497
|
pending.controller.abort("Host runtime release cancelled the pending adapter launch.");
|
|
1428
1498
|
}
|
|
@@ -1434,6 +1504,15 @@ export class HostRuntimeLeaseManager {
|
|
|
1434
1504
|
try {
|
|
1435
1505
|
if (!active.runtimeResourcesReleased) {
|
|
1436
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);
|
|
1437
1516
|
await releaseAdapterResources(active.adapterCleanups);
|
|
1438
1517
|
if (active.databaseCapability && this.databaseBroker) {
|
|
1439
1518
|
// A database the broker cannot drop now is reaped later; it must not hold host capacity.
|
|
@@ -1532,18 +1611,46 @@ export class HostRuntimeLeaseManager {
|
|
|
1532
1611
|
if (logsEntry.kind !== "directory") {
|
|
1533
1612
|
throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
|
|
1534
1613
|
}
|
|
1535
|
-
const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
|
|
1536
1614
|
const outcomes = [];
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
const
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
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));
|
|
1544
1627
|
}
|
|
1545
|
-
outcomes.push(await this.processRecovery.recover(value));
|
|
1546
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);
|
|
1645
|
+
}
|
|
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");
|
|
1547
1654
|
return outcomes;
|
|
1548
1655
|
}
|
|
1549
1656
|
async markLedgerDegraded(ledger) {
|
|
@@ -1919,6 +2026,18 @@ class AttemptSupervisedProviderProcessRunner {
|
|
|
1919
2026
|
: new Set();
|
|
1920
2027
|
const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
|
|
1921
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) {
|
|
1922
2041
|
if (!this.enforceNoListeners)
|
|
1923
2042
|
return await child.result;
|
|
1924
2043
|
let settled = false;
|
|
@@ -2094,7 +2213,12 @@ function hostRuntimeEnvironment(sessionId, lease, runtimeContract, executionClas
|
|
|
2094
2213
|
environment.FORGE_BASE_URL = resolvedBaseUrls[0];
|
|
2095
2214
|
return environment;
|
|
2096
2215
|
}
|
|
2097
|
-
|
|
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) {
|
|
2098
2222
|
const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
|
|
2099
2223
|
const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
|
|
2100
2224
|
const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
|
|
@@ -2119,6 +2243,7 @@ async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal,
|
|
|
2119
2243
|
await append(stderrLogPath, line);
|
|
2120
2244
|
},
|
|
2121
2245
|
}, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
|
|
2246
|
+
await onStarted?.(child.metadataPath);
|
|
2122
2247
|
const result = await child.result;
|
|
2123
2248
|
return {
|
|
2124
2249
|
exitCode: result.exitCode,
|
|
@@ -2161,7 +2286,7 @@ function runtimeExecutionClass(dispatch) {
|
|
|
2161
2286
|
? "analysis_only"
|
|
2162
2287
|
: "managed_runtime";
|
|
2163
2288
|
}
|
|
2164
|
-
function runtimeAdmissionPriority(dispatch) {
|
|
2289
|
+
export function runtimeAdmissionPriority(dispatch) {
|
|
2165
2290
|
return dispatch.execution.lane.trim().toLowerCase() === "runtime_readiness"
|
|
2166
2291
|
|| dispatch.cycleRun.phase.trim().toLowerCase() === "readiness_probe"
|
|
2167
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
|
+
}
|