@loucompanion/forge-bridge 0.1.4-dev.9ddc336f8a9d → 0.1.4-dev.a5a3a7ab2f02

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 (142) hide show
  1. package/README.md +35 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +72 -1
  4. package/dist/bridge/bridge.service.js +308 -9
  5. package/dist/bridge/bridge.types.d.ts +16 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.help.js +18 -0
  22. package/dist/cli/cli.service.d.ts +16 -0
  23. package/dist/cli/cli.service.js +142 -16
  24. package/dist/cli/local-config.d.ts +4 -0
  25. package/dist/cli/local-config.js +26 -4
  26. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  27. package/dist/runtime/host-load-admission.d.ts +60 -0
  28. package/dist/runtime/host-load-admission.js +99 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +67 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  34. package/dist/runtime/host-load-governor-config.js +76 -0
  35. package/dist/runtime/host-load-governor.d.ts +174 -0
  36. package/dist/runtime/host-load-governor.js +541 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  40. package/dist/runtime/host-load-runtime-settings.js +78 -0
  41. package/dist/runtime/host-load-sampler.d.ts +43 -0
  42. package/dist/runtime/host-load-sampler.js +74 -6
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  52. package/dist/runtime/host-pressure-stall.js +48 -1
  53. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  54. package/dist/runtime/host-runtime-contract.js +4 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  56. package/dist/runtime/host-runtime-lease.js +281 -11
  57. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  58. package/dist/runtime/host-runtime-promotion.js +48 -0
  59. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  60. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  61. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  62. package/dist/runtime/host-runtime-requirements.js +117 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  64. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  65. package/dist/runtime/runner-settings.d.ts +100 -0
  66. package/dist/runtime/runner-settings.js +214 -0
  67. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  68. package/dist/sandbox/host-capacity-broker.js +315 -0
  69. package/dist/sandbox/runtime.d.ts +10 -1
  70. package/dist/sandbox/runtime.js +45 -2
  71. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  72. package/dist/sandbox/sandbox-cgroups.js +42 -0
  73. package/dist/session/managed-attempt-tools.d.ts +2 -0
  74. package/dist/session/managed-attempt-tools.js +156 -37
  75. package/dist/session/managed-command-host-load.d.ts +45 -0
  76. package/dist/session/managed-command-host-load.js +82 -0
  77. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  78. package/dist/session/mcp-argument-coercion.js +121 -0
  79. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  80. package/dist/session/phase-completion.artifacts.js +98 -25
  81. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  82. package/dist/session/phase-completion.command-validation.js +77 -0
  83. package/dist/session/phase-completion.d.ts +4 -0
  84. package/dist/session/phase-completion.helpers.js +13 -12
  85. package/dist/session/phase-completion.js +4 -0
  86. package/dist/session/phase-completion.prompts.js +6 -1
  87. package/dist/session/phase-completion.runtime.d.ts +5 -3
  88. package/dist/session/phase-completion.runtime.js +49 -19
  89. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  90. package/dist/session/phase-completion.schema-parts.js +188 -0
  91. package/dist/session/phase-completion.schemas.d.ts +3 -3
  92. package/dist/session/phase-completion.schemas.js +184 -209
  93. package/dist/session/phase-completion.validation.d.ts +2 -3
  94. package/dist/session/phase-completion.validation.js +46 -92
  95. package/dist/session/pre-publication-host-load.d.ts +27 -0
  96. package/dist/session/pre-publication-host-load.js +111 -0
  97. package/dist/session/pre-publication-process.d.ts +3 -0
  98. package/dist/session/pre-publication-process.js +23 -11
  99. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  100. package/dist/session/pre-publication-step-execution.js +49 -0
  101. package/dist/session/pre-publication-validation.d.ts +9 -9
  102. package/dist/session/pre-publication-validation.js +21 -55
  103. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  104. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  105. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  106. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  107. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  108. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  109. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  110. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  111. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  112. package/dist/session/provider-cli/provider-cli.service.js +237 -33
  113. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  114. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  115. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  116. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  117. package/dist/session/provider-cli/provider-output-state.js +9 -0
  118. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  119. package/dist/session/publishable-worktree-changes.js +193 -0
  120. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  121. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  122. package/dist/session/session.base.d.ts +9 -1
  123. package/dist/session/session.service.d.ts +9 -2
  124. package/dist/session/session.service.js +120 -5
  125. package/dist/session/session.types.d.ts +3 -0
  126. package/dist/session/session.types.js +15 -3
  127. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  128. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  129. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  130. package/dist/shared/process/host-process-supervisor.js +1 -1
  131. package/dist/shared/process/process-tree.d.ts +52 -0
  132. package/dist/shared/process/process-tree.js +144 -0
  133. package/dist/shared/process/process.d.ts +67 -0
  134. package/dist/shared/process/process.js +213 -11
  135. package/dist/version.d.ts +1 -1
  136. package/dist/version.js +1 -1
  137. package/dist/worktree/dependency-warmer.d.ts +25 -0
  138. package/dist/worktree/dependency-warmer.js +46 -10
  139. package/dist/worktree/worktree.service.d.ts +10 -1
  140. package/dist/worktree/worktree.service.js +42 -2
  141. package/dist/worktree/worktree.types.d.ts +7 -0
  142. package/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { ForgeFailureError } from "../session/session.types.js";
4
5
  /** Persists only observed, contract-bound host parallel-safety evidence. */
5
6
  export class HostParallelPromotionStore {
6
7
  stateRoot;
@@ -145,12 +146,59 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
145
146
  const canonical = JSON.stringify({
146
147
  schemaVersion: runtimeContract.contract.schemaVersion,
147
148
  runtime: runtimeContract.contract.runtime,
149
+ // Requirements join the fingerprint only when declared, so fingerprints of contracts
150
+ // written before decision 0013 (and their stored promotions) stay unchanged.
151
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
148
152
  derivedCandidateFingerprint: runtimeContract.source === "derived"
149
153
  ? runtimeContract.discovery?.candidateFingerprint ?? null
150
154
  : null,
151
155
  });
152
156
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
153
157
  }
158
+ /**
159
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
160
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
161
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
162
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
163
+ * merging the target branch can rename a variable in a derived launch profile, or change a
164
+ * manifest or project file, without changing anything admission granted. Every other part of the
165
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
166
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
167
+ * profile, singleton resources and declared requirements. Changing any of those throws the
168
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
169
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
170
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
171
+ */
172
+ export function readmitHostRuntimeContract(admitted, current) {
173
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(current);
174
+ // The fingerprint leaves out the source of a project or default contract, but parallel
175
+ // eligibility depends on it, so an unchanged fingerprint alone does not prove the same admission.
176
+ if (runtimeContractFingerprint === admitted.runtimeContractFingerprint && current.source === admitted.runtimeContract.source) {
177
+ return { runtimeContract: admitted.runtimeContract, runtimeContractFingerprint, changed: false };
178
+ }
179
+ if (hostRuntimeAdmissionShape(current) !== hostRuntimeAdmissionShape(admitted.runtimeContract)) {
180
+ throw new ForgeFailureError("host_runtime_contract_changed", "host_runtime_contract_changed: the workspace's runtime contract changed after this attempt's runtime was admitted; a fresh attempt is needed to run it.");
181
+ }
182
+ return { runtimeContract: current, runtimeContractFingerprint, changed: true };
183
+ }
184
+ function hostRuntimeAdmissionShape(runtimeContract) {
185
+ const runtime = runtimeContract.contract.runtime;
186
+ return JSON.stringify({
187
+ source: runtimeContract.source,
188
+ schemaVersion: runtimeContract.contract.schemaVersion,
189
+ runtime: { ...runtime, ports: runtime.ports.map(port => ({ ...port, launch: port.launch && { ...port.launch, environment: undefined } })) },
190
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
191
+ });
192
+ }
193
+ // Cost hints are estimates, not placement constraints: they never change the fingerprint.
194
+ function requirementsFingerprintPart(requires) {
195
+ if (!requires)
196
+ return {};
197
+ const { costHints: _costHints, ...constraints } = requires;
198
+ const declared = constraints.minThreads !== null || constraints.minMemoryGiB !== null || constraints.toolchains.length > 0
199
+ || constraints.docker || constraints.playwright !== null || constraints.testPostgres !== null;
200
+ return declared ? { requires: constraints } : {};
201
+ }
154
202
  export function hostRuntimeParallelEligible(runtimeContract) {
155
203
  const runtime = runtimeContract.contract.runtime;
156
204
  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
+ }
@@ -28,5 +28,12 @@ export declare class PlaywrightHostRuntimeAdapter {
28
28
  */
29
29
  assertBrowserCacheReady(config: HostRuntimePlaywrightConfig, worktreePath: string): Promise<void>;
30
30
  private readyBrowserCache;
31
+ /**
32
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
33
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
34
+ * provider that remembers the config's path would otherwise run Playwright against that port.
35
+ * The next `prepare` writes a fresh one.
36
+ */
37
+ discardOverlay(temporaryDirectory: string): Promise<void>;
31
38
  prepare(config: HostRuntimePlaywrightConfig, context: PlaywrightHostRuntimeContext): Promise<PreparedPlaywrightHostRuntime>;
32
39
  }
@@ -35,6 +35,17 @@ export class PlaywrightHostRuntimeAdapter {
35
35
  }
36
36
  return { cache: resolution.cache, installCommand };
37
37
  }
38
+ /**
39
+ * Removes the generated config, which names the base URL of the stack it was prepared for. A
40
+ * stopped stack's config must not survive: its port may be reassigned to another attempt, and a
41
+ * provider that remembers the config's path would otherwise run Playwright against that port.
42
+ * The next `prepare` writes a fresh one.
43
+ */
44
+ async discardOverlay(temporaryDirectory) {
45
+ if (!await assertCanonicalDirectory(temporaryDirectory, true))
46
+ return;
47
+ await fs.rm(path.join(path.resolve(temporaryDirectory), playwrightOverlayFileName), { force: true });
48
+ }
38
49
  async prepare(config, context) {
39
50
  const { realWorktree, realSource } = await projectConfigLocation(config, context.worktreePath);
40
51
  const sourceConfig = path.resolve(path.resolve(context.worktreePath), config.config);
@@ -62,7 +73,7 @@ export class PlaywrightHostRuntimeAdapter {
62
73
  if (!/^[0-9a-f]{32}$/u.test(context.ownershipToken)) {
63
74
  throw new Error("playwright_runtime_adapter_invalid: ownership token must be a normalized dispatch attempt UUID.");
64
75
  }
65
- const overlayPath = path.join(temporaryDirectory, "forge.playwright.config.mjs");
76
+ const overlayPath = path.join(temporaryDirectory, playwrightOverlayFileName);
66
77
  const { cache: readyCache, installCommand: browserInstallCommand } = await this.readyBrowserCache(context.worktreePath, realWorktree, path.dirname(realSource));
67
78
  const browserCache = readyCache
68
79
  ? { path: readyCache, ready: true }
@@ -135,6 +146,7 @@ async function ensureAttemptWritableDirectories(targets, realWorktree) {
135
146
  for (const target of resolvedTargets)
136
147
  await createPrivateCanonicalDirectory(target);
137
148
  }
149
+ const playwrightOverlayFileName = "forge.playwright.config.mjs";
138
150
  async function writeAttemptOverlay(target, content) {
139
151
  const parent = path.dirname(target);
140
152
  const identity = await assertCanonicalDirectory(parent);
@@ -0,0 +1,100 @@
1
+ import { type HostLoadGovernorMode } from "./host-load-governor-config.js";
2
+ export declare const runnerSettingKeys: readonly ["maxConcurrentAttempts", "cpuBudgetPercent", "yieldCpuBudgetPercent", "memoryReserveBytes", "maxHeavySteps", "yieldToForeground"];
3
+ export type RunnerSettingKey = typeof runnerSettingKeys[number];
4
+ /** The `ApplySettings` hub message. Null numeric fields mean "no server value": keep today's env/default behaviour. */
5
+ export interface RunnerSettingsDocument {
6
+ readonly runnerId: string | null;
7
+ readonly version: number;
8
+ readonly maxConcurrentAttempts: number | null;
9
+ readonly cpuBudgetPercent: number | null;
10
+ readonly yieldCpuBudgetPercent: number | null;
11
+ readonly memoryReserveBytes: number | null;
12
+ readonly maxHeavySteps: number | null;
13
+ readonly yieldToForeground: boolean;
14
+ }
15
+ export interface RunnerSettingsValues {
16
+ readonly maxConcurrentAttempts: number;
17
+ readonly cpuBudgetPercent: number;
18
+ readonly yieldCpuBudgetPercent: number;
19
+ readonly memoryReserveBytes: number;
20
+ /** Null: the governor's budget alone limits heavy steps (no count limit). */
21
+ readonly maxHeavySteps: number | null;
22
+ readonly yieldToForeground: boolean;
23
+ }
24
+ /**
25
+ * Where an effective value came from: the server's value as is, the bridge default,
26
+ * an env var that capped/floored the server value or supplied it, or the host's
27
+ * `forge-bridge yield on` flag.
28
+ */
29
+ export type RunnerSettingSource = "server" | "default" | "host_env" | "host_local";
30
+ export interface RunnerSettingBound {
31
+ readonly key: RunnerSettingKey;
32
+ readonly envVar: string;
33
+ readonly value: number;
34
+ readonly kind: "ceiling" | "floor";
35
+ }
36
+ /**
37
+ * Why a key was rejected. `invalid`: the server value is outside the contract, so
38
+ * the host default applies (version skew; it never holds placement). `apply_failed`:
39
+ * the host could not put the value in force, so the previous value stays in force
40
+ * and the server holds placement until a later apply succeeds. Clamping by an env
41
+ * bound is neither: it is a `bound` and a `host_env` source.
42
+ */
43
+ export type RunnerSettingRejectionKind = "invalid" | "apply_failed";
44
+ export interface RunnerSettingRejection {
45
+ readonly key: RunnerSettingKey;
46
+ readonly reason: string;
47
+ readonly kind: RunnerSettingRejectionKind;
48
+ }
49
+ /** The `SettingsApplied` report; also carried in the capabilities `settings` block (schema 8). */
50
+ export interface RunnerSettingsReport {
51
+ /** The applied document version, or null before any ApplySettings was applied. */
52
+ readonly version: number | null;
53
+ /** FORGE_HOST_LOAD_GOVERNOR: CPU budget, yield budget and heavy steps only take effect when on. */
54
+ readonly governor: HostLoadGovernorMode;
55
+ readonly values: RunnerSettingsValues;
56
+ readonly sources: Readonly<Record<RunnerSettingKey, RunnerSettingSource>>;
57
+ readonly bounds: readonly RunnerSettingBound[];
58
+ readonly rejected: readonly RunnerSettingRejection[];
59
+ }
60
+ /** Today's bridge defaults for the keys whose default depends on the host. */
61
+ export interface RunnerHostDefaults {
62
+ /** floor(threads / 2) capped at 8 (at least 1). */
63
+ readonly maxConcurrentAttempts: number;
64
+ /** The adaptive reserve: 12.5% of RAM within 1–4 GiB, before FORGE_HOST_MEMORY_RESERVE_BYTES. */
65
+ readonly memoryReserveBytes: number;
66
+ }
67
+ export interface EffectiveRunnerSettings {
68
+ readonly report: RunnerSettingsReport;
69
+ /** Effective yield (server OR local flag). */
70
+ readonly yielding: boolean;
71
+ /**
72
+ * The governor CPU budget in force, as a fraction of logical CPUs: the CPU budget,
73
+ * or min(yield budget, CPU budget) while yielding.
74
+ */
75
+ readonly governorCpuBudgetFraction: number;
76
+ }
77
+ export declare const defaultCpuBudgetPercent = 80;
78
+ export declare const defaultYieldCpuBudgetPercent = 50;
79
+ /**
80
+ * Computes every effective value (decision 0014 precedence):
81
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
82
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
83
+ * - yield: server OR the local `forge-bridge yield on` flag.
84
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
85
+ */
86
+ export declare function computeEffectiveRunnerSettings(document: RunnerSettingsDocument | null, environment: Readonly<Record<string, string | undefined>>, hostDefaults: RunnerHostDefaults, localYield: boolean): EffectiveRunnerSettings;
87
+ /**
88
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
89
+ * (the bridge then ignores it); malformed values become null so the host default applies.
90
+ */
91
+ export declare function parseRunnerSettingsDocument(raw: unknown): RunnerSettingsDocument | null;
92
+ /**
93
+ * The report for what is actually in force after an apply in which the host
94
+ * failed to put some keys in force: each failed key keeps the value (and source)
95
+ * that was in force before, and its failure is reported as an `apply_failed`
96
+ * rejection, so the server never reads a desired value as applied.
97
+ */
98
+ export declare function runnerSettingsInForce(report: RunnerSettingsReport, previous: RunnerSettingsReport, failures: readonly RunnerSettingRejection[]): RunnerSettingsReport;
99
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
100
+ export declare function sameRunnerSettingsReport(left: RunnerSettingsReport, right: RunnerSettingsReport): boolean;
@@ -0,0 +1,214 @@
1
+ import { parseHostLoadGovernorMode } from "./host-load-governor-config.js";
2
+ // Decision 0014 §3 "Precedence" and §6 "Bridge hub": the server pushes a runner
3
+ // settings document (`ApplySettings`) and is the source of truth. Host env vars
4
+ // are one-sided safety bounds only: a ceiling on capacity, a floor on reserves.
5
+ // The bridge reports the effective values, their sources and every env bound it
6
+ // saw back to the server (`SettingsApplied`), so a host bound is never silent.
7
+ // Nothing here is persisted to bridge.json (0014 agent constraint).
8
+ export const runnerSettingKeys = [
9
+ "maxConcurrentAttempts",
10
+ "cpuBudgetPercent",
11
+ "yieldCpuBudgetPercent",
12
+ "memoryReserveBytes",
13
+ "maxHeavySteps",
14
+ "yieldToForeground",
15
+ ];
16
+ export const defaultCpuBudgetPercent = 80;
17
+ export const defaultYieldCpuBudgetPercent = 50;
18
+ const MiB = 1024 ** 2;
19
+ const GiB = 1024 ** 3;
20
+ /** The server's ranges (contract); a value outside them is rejected, not clamped, so it is never silent. */
21
+ const serverRanges = {
22
+ maxConcurrentAttempts: { min: 1, max: 32 },
23
+ cpuBudgetPercent: { min: 10, max: 100 },
24
+ yieldCpuBudgetPercent: { min: 10, max: 100 },
25
+ memoryReserveBytes: { min: 512 * MiB, max: 128 * GiB },
26
+ maxHeavySteps: { min: 1, max: 64 },
27
+ };
28
+ /**
29
+ * Computes every effective value (decision 0014 precedence):
30
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
31
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
32
+ * - yield: server OR the local `forge-bridge yield on` flag.
33
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
34
+ */
35
+ export function computeEffectiveRunnerSettings(document, environment, hostDefaults, localYield) {
36
+ const rejected = [];
37
+ const server = (key) => {
38
+ const value = document?.[key] ?? null;
39
+ if (value === null)
40
+ return null;
41
+ const range = serverRanges[key];
42
+ if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
43
+ rejected.push({ key, reason: `${String(value)} is not a whole number; the host default applies.`, kind: "invalid" });
44
+ return null;
45
+ }
46
+ if (value < range.min || value > range.max) {
47
+ rejected.push({ key, reason: `${value} is outside ${range.min}-${range.max}; the host default applies.`, kind: "invalid" });
48
+ return null;
49
+ }
50
+ return value;
51
+ };
52
+ const attemptsCeiling = integerEnv(environment, "FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", 1, 32);
53
+ const cpuCeilings = cpuBudgetCeilings(environment);
54
+ const reserveFloor = integerEnv(environment, "FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * MiB, 128 * GiB);
55
+ const heavyStepsCeiling = integerEnv(environment, "FORGE_HOST_MAX_HEAVY_STEPS", 1, 64);
56
+ const attempts = ceilingValue(server("maxConcurrentAttempts"), lowest(attemptsCeiling), hostDefaults.maxConcurrentAttempts);
57
+ const cpu = ceilingValue(server("cpuBudgetPercent"), lowest(...cpuCeilings), defaultCpuBudgetPercent);
58
+ // The yield budget's ceilings are the CPU budget's. Without a server value they
59
+ // cap its default rather than replace it: a host allowing 90% CPU must not raise
60
+ // the 50% yield default, which no env var sets today.
61
+ const serverYieldCpu = server("yieldCpuBudgetPercent");
62
+ const yieldCpu = ceilingValue(serverYieldCpu ?? defaultYieldCpuBudgetPercent, lowest(...cpuCeilings), defaultYieldCpuBudgetPercent);
63
+ const yieldCpuSource = serverYieldCpu === null && yieldCpu.source === "server" ? "default" : yieldCpu.source;
64
+ const reserve = floorValue(server("memoryReserveBytes"), reserveFloor?.value ?? null, hostDefaults.memoryReserveBytes);
65
+ const heavySteps = ceilingValue(server("maxHeavySteps"), lowest(heavyStepsCeiling), null);
66
+ const serverYield = document?.yieldToForeground === true;
67
+ const yielding = serverYield || localYield;
68
+ // The host's own switch wins the label: turning the server toggle off would not stop it.
69
+ const yieldSource = localYield ? "host_local" : serverYield ? "server" : "default";
70
+ const bounds = [];
71
+ const addCeilings = (key, set) => {
72
+ for (const bound of set)
73
+ if (bound)
74
+ bounds.push({ key, envVar: bound.envVar, value: bound.value, kind: "ceiling" });
75
+ };
76
+ addCeilings("maxConcurrentAttempts", [attemptsCeiling]);
77
+ addCeilings("cpuBudgetPercent", cpuCeilings);
78
+ addCeilings("yieldCpuBudgetPercent", cpuCeilings);
79
+ if (reserveFloor)
80
+ bounds.push({ key: "memoryReserveBytes", envVar: reserveFloor.envVar, value: reserveFloor.value, kind: "floor" });
81
+ addCeilings("maxHeavySteps", [heavyStepsCeiling]);
82
+ const values = {
83
+ maxConcurrentAttempts: attempts.value,
84
+ cpuBudgetPercent: cpu.value,
85
+ yieldCpuBudgetPercent: yieldCpu.value,
86
+ memoryReserveBytes: reserve.value,
87
+ maxHeavySteps: heavySteps.value,
88
+ yieldToForeground: yielding,
89
+ };
90
+ const budgetPercent = yielding ? Math.min(values.yieldCpuBudgetPercent, values.cpuBudgetPercent) : values.cpuBudgetPercent;
91
+ return {
92
+ report: {
93
+ version: null,
94
+ governor: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
95
+ values,
96
+ sources: {
97
+ maxConcurrentAttempts: attempts.source,
98
+ cpuBudgetPercent: cpu.source,
99
+ yieldCpuBudgetPercent: yieldCpuSource,
100
+ memoryReserveBytes: reserve.source,
101
+ maxHeavySteps: heavySteps.source,
102
+ yieldToForeground: yieldSource,
103
+ },
104
+ bounds,
105
+ rejected,
106
+ },
107
+ yielding,
108
+ governorCpuBudgetFraction: budgetPercent / 100,
109
+ };
110
+ }
111
+ /**
112
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
113
+ * (the bridge then ignores it); malformed values become null so the host default applies.
114
+ */
115
+ export function parseRunnerSettingsDocument(raw) {
116
+ if (!raw || typeof raw !== "object")
117
+ return null;
118
+ const record = raw;
119
+ const version = record.version;
120
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 0)
121
+ return null;
122
+ const numeric = (key) => {
123
+ const value = record[key];
124
+ // Kept as-is (even out of range) so computeEffectiveRunnerSettings can report it as rejected.
125
+ return typeof value === "number" ? value : null;
126
+ };
127
+ return {
128
+ runnerId: typeof record.runnerId === "string" ? record.runnerId : null,
129
+ version,
130
+ maxConcurrentAttempts: numeric("maxConcurrentAttempts"),
131
+ cpuBudgetPercent: numeric("cpuBudgetPercent"),
132
+ yieldCpuBudgetPercent: numeric("yieldCpuBudgetPercent"),
133
+ memoryReserveBytes: numeric("memoryReserveBytes"),
134
+ maxHeavySteps: numeric("maxHeavySteps"),
135
+ yieldToForeground: record.yieldToForeground === true,
136
+ };
137
+ }
138
+ /**
139
+ * The report for what is actually in force after an apply in which the host
140
+ * failed to put some keys in force: each failed key keeps the value (and source)
141
+ * that was in force before, and its failure is reported as an `apply_failed`
142
+ * rejection, so the server never reads a desired value as applied.
143
+ */
144
+ export function runnerSettingsInForce(report, previous, failures) {
145
+ if (failures.length === 0)
146
+ return report;
147
+ const values = { ...report.values };
148
+ const sources = { ...report.sources };
149
+ for (const failure of failures) {
150
+ keepPrevious(values, previous.values, failure.key);
151
+ sources[failure.key] = previous.sources[failure.key];
152
+ }
153
+ return { ...report, values, sources, rejected: [...report.rejected, ...failures] };
154
+ }
155
+ function keepPrevious(target, previous, key) {
156
+ target[key] = previous[key];
157
+ }
158
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
159
+ export function sameRunnerSettingsReport(left, right) {
160
+ return JSON.stringify(left) === JSON.stringify(right);
161
+ }
162
+ function ceilingValue(server, ceiling, fallback) {
163
+ if (server !== null) {
164
+ return ceiling && ceiling.value < server
165
+ ? { value: ceiling.value, source: "host_env" }
166
+ : { value: server, source: "server" };
167
+ }
168
+ return ceiling ? { value: ceiling.value, source: "host_env" } : { value: fallback, source: "default" };
169
+ }
170
+ function floorValue(server, floor, fallback) {
171
+ if (server !== null) {
172
+ return floor !== null && floor > server
173
+ ? { value: floor, source: "host_env" }
174
+ : { value: server, source: "server" };
175
+ }
176
+ return floor !== null ? { value: floor, source: "host_env" } : { value: fallback, source: "default" };
177
+ }
178
+ function lowest(...bounds) {
179
+ let result = null;
180
+ for (const bound of bounds) {
181
+ if (bound && (result === null || bound.value < result.value))
182
+ result = bound;
183
+ }
184
+ return result;
185
+ }
186
+ /**
187
+ * Both CPU ceilings: the new FORGE_HOST_CPU_BUDGET_PERCENT (10–100) and the
188
+ * existing FORGE_HOST_LOAD_CPU_BUDGET_FRACTION (0.05–1, the governor's own
189
+ * parse), reported as a percent.
190
+ */
191
+ function cpuBudgetCeilings(environment) {
192
+ const percent = numberEnv(environment, "FORGE_HOST_CPU_BUDGET_PERCENT", 10, 100);
193
+ const fraction = numberEnv(environment, "FORGE_HOST_LOAD_CPU_BUDGET_FRACTION", 0.05, 1);
194
+ return [
195
+ percent,
196
+ fraction ? { envVar: fraction.envVar, value: Math.round(fraction.value * 10_000) / 100 } : null,
197
+ ];
198
+ }
199
+ /** Matches the lease manager's parse (parseInt, clamped); an unparsable value counts as unset. */
200
+ function integerEnv(environment, envVar, minimum, maximum) {
201
+ const raw = environment[envVar];
202
+ if (raw === undefined || raw.trim() === "")
203
+ return null;
204
+ const parsed = Number.parseInt(raw, 10);
205
+ return Number.isFinite(parsed) ? { envVar, value: Math.max(minimum, Math.min(maximum, parsed)) } : null;
206
+ }
207
+ /** Matches the governor config's parse (Number, clamped); an unparsable value counts as unset. */
208
+ function numberEnv(environment, envVar, minimum, maximum) {
209
+ const raw = environment[envVar];
210
+ if (raw === undefined || raw.trim() === "")
211
+ return null;
212
+ const parsed = Number(raw);
213
+ return Number.isFinite(parsed) ? { envVar, value: Math.min(maximum, Math.max(minimum, parsed)) } : null;
214
+ }