@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
@@ -211,7 +211,7 @@ async function aspNetBuildInputs(plan) {
211
211
  const projectDirectory = path.extname(plan.projectPath).toLowerCase() === ".csproj"
212
212
  ? path.dirname(plan.projectPath)
213
213
  : plan.projectPath;
214
- const sourceDigest = await directoryContentDigest(projectDirectory);
214
+ const sourceDigest = await projectSourceDigest(plan, projectDirectory);
215
215
  const dependencyReceipt = path.join(projectDirectory, "obj", ".forge-dependency-preparation.json");
216
216
  const dependencyContent = await fs.readFile(dependencyReceipt).catch(() => null);
217
217
  const globalJson = await findAncestorFile(projectDirectory, plan.worktreePath, "global.json");
@@ -225,18 +225,106 @@ async function aspNetBuildInputs(plan) {
225
225
  sdkVersion: await dotnetSdkVersion(plan.cwd),
226
226
  };
227
227
  }
228
- async function directoryContentDigest(directory) {
229
- const files = [];
230
- await collectInputFiles(directory, directory, files);
228
+ /**
229
+ * Digest of everything the project build compiles from inside the worktree: the
230
+ * project directory, every project it references (transitively, through
231
+ * ProjectReference), and the Directory.Build/Directory.Packages files above them.
232
+ * A change in a referenced project must invalidate the receipt, or the launch
233
+ * reuses a binary built from the previous source.
234
+ */
235
+ async function projectSourceDigest(plan, projectDirectory) {
236
+ const worktree = path.resolve(plan.worktreePath);
237
+ const directories = await projectSourceDirectories(plan, projectDirectory);
238
+ const files = new Set();
239
+ for (const directory of directories) {
240
+ const collected = [];
241
+ await collectInputFiles(directory, directory, collected);
242
+ for (const file of collected)
243
+ files.add(file);
244
+ for (const buildFile of await ancestorBuildFiles(directory, worktree))
245
+ files.add(buildFile);
246
+ }
231
247
  const hash = createHash("sha256");
232
- for (const file of files.sort((left, right) => left.localeCompare(right))) {
233
- hash.update(path.relative(directory, file).replaceAll("\\", "/"));
248
+ for (const file of [...files].sort((left, right) => left.localeCompare(right))) {
249
+ hash.update(path.relative(worktree, file).replaceAll("\\", "/"));
234
250
  hash.update("\0");
235
251
  hash.update(await fs.readFile(file));
236
252
  hash.update("\0");
237
253
  }
238
254
  return `sha256:${hash.digest("hex")}`;
239
255
  }
256
+ const msbuildProjectExtensions = new Set([".csproj", ".fsproj", ".vbproj"]);
257
+ const msbuildDirectoryFiles = ["Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props"];
258
+ /** The project directory and the directories of the projects it references inside the worktree. */
259
+ async function projectSourceDirectories(plan, projectDirectory) {
260
+ const worktree = path.resolve(plan.worktreePath);
261
+ const directories = new Set([path.resolve(projectDirectory)]);
262
+ const queue = msbuildProjectExtensions.has(path.extname(plan.projectPath).toLowerCase())
263
+ ? [path.resolve(plan.projectPath)]
264
+ : await projectFilesIn(projectDirectory);
265
+ const visited = new Set();
266
+ while (queue.length > 0) {
267
+ const projectFile = queue.shift();
268
+ if (visited.has(projectFile))
269
+ continue;
270
+ visited.add(projectFile);
271
+ const content = await fs.readFile(projectFile, "utf8").catch(() => null);
272
+ if (content === null)
273
+ continue;
274
+ for (const include of projectReferenceIncludes(content)) {
275
+ // An MSBuild property cannot be resolved here; the referenced source stays outside the digest.
276
+ if (include.includes("$("))
277
+ continue;
278
+ const referenced = path.resolve(path.dirname(projectFile), include.replaceAll("\\", "/"));
279
+ if (!containedIn(worktree, referenced))
280
+ continue;
281
+ directories.add(path.dirname(referenced));
282
+ queue.push(referenced);
283
+ }
284
+ }
285
+ return [...directories];
286
+ }
287
+ async function projectFilesIn(directory) {
288
+ const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []);
289
+ return entries
290
+ .filter(entry => entry.isFile() && msbuildProjectExtensions.has(path.extname(entry.name).toLowerCase()))
291
+ .map(entry => path.join(directory, entry.name));
292
+ }
293
+ function projectReferenceIncludes(projectXml) {
294
+ const withoutComments = projectXml.replaceAll(/<!--[\s\S]*?-->/gu, "");
295
+ const includes = [];
296
+ for (const match of withoutComments.matchAll(/<ProjectReference\b[^>]*?\bInclude\s*=\s*(?:"([^"]*)"|'([^']*)')/giu)) {
297
+ const value = match[1] ?? match[2] ?? "";
298
+ for (const part of value.split(";")) {
299
+ const trimmed = part.trim();
300
+ if (trimmed)
301
+ includes.push(trimmed);
302
+ }
303
+ }
304
+ return includes;
305
+ }
306
+ async function ancestorBuildFiles(directory, worktree) {
307
+ const found = [];
308
+ let current = path.resolve(directory);
309
+ while (containedIn(worktree, current)) {
310
+ for (const name of msbuildDirectoryFiles) {
311
+ const candidate = path.join(current, name);
312
+ if (await fs.stat(candidate).then(stat => stat.isFile()).catch(() => false))
313
+ found.push(candidate);
314
+ }
315
+ if (current === worktree)
316
+ break;
317
+ const parent = path.dirname(current);
318
+ if (parent === current)
319
+ break;
320
+ current = parent;
321
+ }
322
+ return found;
323
+ }
324
+ function containedIn(root, candidate) {
325
+ const relative = path.relative(root, candidate);
326
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
327
+ }
240
328
  async function collectInputFiles(root, directory, files) {
241
329
  const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []);
242
330
  for (const entry of entries) {
@@ -0,0 +1,60 @@
1
+ import type { HostLoadGovernorConfig } from "./host-load-governor-config.js";
2
+ import type { HostLoadStepCost } from "./host-load-step-class.js";
3
+ /** Measured host load the admission rule reads. Null means PSI is unavailable or stale. */
4
+ export interface HostLoadSignals {
5
+ /** Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). */
6
+ readonly cpuSomeAvg10: number;
7
+ /** Consecutive samples, ending with the latest, at or above the CPU pressure threshold. */
8
+ readonly cpuPressuredSamples: number;
9
+ /** Host-wide memory PSI `full avg10`; a hard stop above its threshold. */
10
+ readonly memoryFullAvg10: number | null;
11
+ readonly memoryAvailableBytes: number | null;
12
+ /**
13
+ * Host CPU from /proc/stat minus the bridge's dedicated cgroup over the same
14
+ * window. Null when the bridge's cgroup is not dedicated: Forge's own work is
15
+ * then counted only through reserved cost and the host PSI gate.
16
+ */
17
+ readonly externalCpuCores: number | null;
18
+ }
19
+ export type HostLoadAdmissionReason = "admitted" | "admitted_alone" | "admitted_fallback" | "cpu_budget" | "memory_budget" | "cpu_pressure" | "memory_pressure" | "fallback_slots"
20
+ /** Decision 0014: the host already runs the owner's maximum number of heavy steps. */
21
+ | "heavy_step_limit"
22
+ /** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
23
+ | "ledger_recovering";
24
+ export interface HostLoadAdmissionInput {
25
+ readonly request: HostLoadStepCost;
26
+ /** Reserved cost of every live token on this host (all processes). */
27
+ readonly running: readonly HostLoadStepCost[];
28
+ /**
29
+ * Memory the running steps already use. MemAvailable already excludes it, so
30
+ * it is added back to the budget (capped at their reservations) instead of
31
+ * being counted twice.
32
+ */
33
+ readonly runningMemoryBytes?: number;
34
+ readonly logicalCpus: number;
35
+ readonly signals: HostLoadSignals | null;
36
+ readonly config: Pick<HostLoadGovernorConfig, "cpuBudgetFraction" | "memoryReserveBytes" | "cpuPressureThreshold" | "backpressureSamples" | "memoryFullThreshold" | "fallbackSlots">;
37
+ /**
38
+ * Decision 0014 "Max concurrent heavy steps": a host-wide count limit on top of
39
+ * the budget. Null or absent means the budget alone decides.
40
+ */
41
+ readonly maxHeavySteps?: number | null;
42
+ }
43
+ export interface HostLoadAdmissionDecision {
44
+ readonly admitted: boolean;
45
+ readonly reason: HostLoadAdmissionReason;
46
+ readonly cpuBudgetCores: number | null;
47
+ readonly memoryBudgetBytes: number | null;
48
+ readonly reservedCpuCores: number;
49
+ readonly reservedMemoryBytes: number;
50
+ readonly detail: string;
51
+ }
52
+ /**
53
+ * Decision 0013 admission rule. A step is admitted when the reserved cost of
54
+ * running steps plus its own cost fits the budget and host pressure is under
55
+ * the backpressure threshold. Memory `full` pressure is a hard stop. A step
56
+ * too large for the budget on its own runs only when nothing else does. An
57
+ * optional count limit (decision 0014) caps how many heavy steps run at once.
58
+ * Without PSI, a simple per-host semaphore applies instead.
59
+ */
60
+ export declare function decideHostLoadAdmission(input: HostLoadAdmissionInput): HostLoadAdmissionDecision;
@@ -0,0 +1,99 @@
1
+ const epsilon = 1e-9;
2
+ /**
3
+ * Decision 0013 admission rule. A step is admitted when the reserved cost of
4
+ * running steps plus its own cost fits the budget and host pressure is under
5
+ * the backpressure threshold. Memory `full` pressure is a hard stop. A step
6
+ * too large for the budget on its own runs only when nothing else does. An
7
+ * optional count limit (decision 0014) caps how many heavy steps run at once.
8
+ * Without PSI, a simple per-host semaphore applies instead.
9
+ */
10
+ export function decideHostLoadAdmission(input) {
11
+ const { request, running, signals, config } = input;
12
+ const reservedCpuCores = running.reduce((sum, cost) => sum + cost.cpuCores, 0);
13
+ const reservedMemoryBytes = running.reduce((sum, cost) => sum + cost.memoryBytes, 0);
14
+ const base = { reservedCpuCores, reservedMemoryBytes };
15
+ const maxHeavySteps = input.maxHeavySteps ?? null;
16
+ if (!signals) {
17
+ // The count limit narrows the semaphore: min(fallback slots, max heavy steps).
18
+ const limited = maxHeavySteps !== null && maxHeavySteps < config.fallbackSlots;
19
+ const slots = limited ? maxHeavySteps : config.fallbackSlots;
20
+ const admitted = running.length < slots;
21
+ return {
22
+ ...base,
23
+ admitted,
24
+ reason: admitted ? "admitted_fallback" : limited ? "heavy_step_limit" : "fallback_slots",
25
+ cpuBudgetCores: null,
26
+ memoryBudgetBytes: null,
27
+ detail: admitted
28
+ ? "Host pressure data is unavailable; admitted under the per-host step semaphore."
29
+ : limited
30
+ ? `Host pressure data is unavailable; ${running.length} of ${slots} heavy step(s) allowed at once are running (max heavy steps).`
31
+ : `Host pressure data is unavailable; ${running.length} of ${config.fallbackSlots} heavy step slot(s) are in use.`,
32
+ };
33
+ }
34
+ const cpuBudgetCores = Math.max(0, input.logicalCpus * config.cpuBudgetFraction - (signals.externalCpuCores ?? 0));
35
+ const usedByRunning = Math.min(reservedMemoryBytes, Math.max(0, input.runningMemoryBytes ?? 0));
36
+ const memoryBudgetBytes = signals.memoryAvailableBytes === null
37
+ ? null
38
+ : Math.max(0, signals.memoryAvailableBytes + usedByRunning - config.memoryReserveBytes);
39
+ const budget = { ...base, cpuBudgetCores, memoryBudgetBytes };
40
+ if (signals.memoryFullAvg10 !== null && signals.memoryFullAvg10 > config.memoryFullThreshold) {
41
+ return {
42
+ ...budget,
43
+ admitted: false,
44
+ reason: "memory_pressure",
45
+ detail: `Host memory pressure (full avg10 ${signals.memoryFullAvg10}%) is above ${config.memoryFullThreshold}%; no heavy step may start.`,
46
+ };
47
+ }
48
+ if (signals.cpuPressuredSamples >= config.backpressureSamples) {
49
+ return {
50
+ ...budget,
51
+ admitted: false,
52
+ reason: "cpu_pressure",
53
+ detail: `Host CPU pressure (some avg10 ${signals.cpuSomeAvg10}%) has been at or above ${config.cpuPressureThreshold}% for ${signals.cpuPressuredSamples} sample(s).`,
54
+ };
55
+ }
56
+ if (maxHeavySteps !== null && running.length >= maxHeavySteps) {
57
+ return {
58
+ ...budget,
59
+ admitted: false,
60
+ reason: "heavy_step_limit",
61
+ detail: `${running.length} heavy step(s) are running and the host allows at most ${maxHeavySteps} at once.`,
62
+ };
63
+ }
64
+ if (running.length === 0) {
65
+ const oversize = request.cpuCores > cpuBudgetCores + epsilon
66
+ || (memoryBudgetBytes !== null && request.memoryBytes > memoryBudgetBytes + epsilon);
67
+ return {
68
+ ...budget,
69
+ admitted: true,
70
+ reason: oversize ? "admitted_alone" : "admitted",
71
+ detail: oversize
72
+ ? "The step exceeds the host budget on its own and runs alone because nothing else is running."
73
+ : "The step fits the host budget.",
74
+ };
75
+ }
76
+ if (reservedCpuCores + request.cpuCores > cpuBudgetCores + epsilon) {
77
+ return {
78
+ ...budget,
79
+ admitted: false,
80
+ reason: "cpu_budget",
81
+ detail: `Reserved ${round(reservedCpuCores)} + requested ${round(request.cpuCores)} cores exceed the ${round(cpuBudgetCores)}-core budget${signals.externalCpuCores ? ` (${round(signals.externalCpuCores)} cores of external load)` : ""}.`,
82
+ };
83
+ }
84
+ if (memoryBudgetBytes !== null && reservedMemoryBytes + request.memoryBytes > memoryBudgetBytes + epsilon) {
85
+ return {
86
+ ...budget,
87
+ admitted: false,
88
+ reason: "memory_budget",
89
+ detail: `Reserved ${gib(reservedMemoryBytes)} + requested ${gib(request.memoryBytes)} GiB exceed the ${gib(memoryBudgetBytes)} GiB memory budget.`,
90
+ };
91
+ }
92
+ return { ...budget, admitted: true, reason: "admitted", detail: "The step fits the host budget." };
93
+ }
94
+ function round(value) {
95
+ return Math.round(value * 100) / 100;
96
+ }
97
+ function gib(bytes) {
98
+ return round(bytes / 1024 ** 3);
99
+ }
@@ -0,0 +1,22 @@
1
+ import { HostLoadGovernor } from "./host-load-governor.js";
2
+ export declare const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
3
+ export declare const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
4
+ /** True for the variables that carry the governor into a child process. */
5
+ /**
6
+ * A process environment with every host load governor variable removed
7
+ * (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
8
+ * the host ledger, or broker control, that their step's token is held in.
9
+ */
10
+ export declare function withoutHostLoadGovernorVariables<T extends Readonly<Record<string, string | undefined>>>(environment: T): T;
11
+ export declare function isHostLoadChildEnvironmentName(name: string): boolean;
12
+ /**
13
+ * The variables a child needs to share this bridge's ledger: the flag, the
14
+ * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
15
+ * unit. Empty with the governor off, so the child stays ungoverned.
16
+ */
17
+ export declare function hostLoadChildEnvironment(stateRoot: string, environment?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
18
+ /**
19
+ * The governor a child process uses, from the variables above. Undefined when
20
+ * the flag is off or no state root was handed over: the child is ungoverned.
21
+ */
22
+ export declare function hostLoadGovernorFromChildEnvironment(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernor | undefined;
@@ -0,0 +1,67 @@
1
+ import path from "node:path";
2
+ import { HostLoadGovernor } from "./host-load-governor.js";
3
+ import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
4
+ import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
5
+ import { HostLoadSampler } from "./host-load-sampler.js";
6
+ // How a process the bridge starts (the completion MCP server, which runs
7
+ // managed commands) joins the bridge's host load governor (decision 0013).
8
+ // The ledger is file-backed, so the child builds its own governor on the
9
+ // bridge's state root and every token counts against one host budget.
10
+ export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
11
+ export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
12
+ const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
13
+ /** True for the variables that carry the governor into a child process. */
14
+ /**
15
+ * A process environment with every host load governor variable removed
16
+ * (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
17
+ * the host ledger, or broker control, that their step's token is held in.
18
+ */
19
+ export function withoutHostLoadGovernorVariables(environment) {
20
+ const kept = {};
21
+ for (const [name, value] of Object.entries(environment)) {
22
+ if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
23
+ kept[name] = value;
24
+ }
25
+ return kept;
26
+ }
27
+ // Decision 0014 operator ceilings the child's governor applies itself (host-load-governor-config.ts).
28
+ const hostCeilingEnvironmentNames = new Set(["FORGE_HOST_CPU_BUDGET_PERCENT", "FORGE_HOST_MAX_HEAVY_STEPS"]);
29
+ export function isHostLoadChildEnvironmentName(name) {
30
+ return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment || hostCeilingEnvironmentNames.has(name);
31
+ }
32
+ /**
33
+ * The variables a child needs to share this bridge's ledger: the flag, the
34
+ * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
35
+ * unit. Empty with the governor off, so the child stays ungoverned.
36
+ */
37
+ export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
38
+ if (loadHostLoadGovernorConfig(environment).mode !== "on")
39
+ return {};
40
+ const forwarded = {};
41
+ for (const [name, value] of Object.entries(environment)) {
42
+ if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
43
+ forwarded[name] = value;
44
+ }
45
+ forwarded[hostLoadGovernorEnvironment] = "on";
46
+ forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
47
+ return forwarded;
48
+ }
49
+ /**
50
+ * The governor a child process uses, from the variables above. Undefined when
51
+ * the flag is off or no state root was handed over: the child is ungoverned.
52
+ */
53
+ export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
54
+ const config = loadHostLoadGovernorConfig(environment);
55
+ const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
56
+ if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
57
+ return undefined;
58
+ return new HostLoadGovernor({
59
+ stateRoot,
60
+ config,
61
+ load: new HostLoadSampler({
62
+ cgroupUnit: environment[cgroupUnitEnvironment]?.trim() || null,
63
+ // The bridge registers its Docker sandboxes here: their CPU is Forge's own here too.
64
+ forgeCgroups: new FileForgeCgroupRegistry(stateRoot),
65
+ }),
66
+ });
67
+ }
@@ -0,0 +1,49 @@
1
+ import { type HostEnvironment } from "./host-facts.js";
2
+ /** Where a sampler learns which cgroups hold Forge's own Docker sandbox work. */
3
+ export interface ForgeCgroupSource {
4
+ paths(): readonly string[] | Promise<readonly string[]>;
5
+ }
6
+ /** Where the sandbox runtime records the cgroups of the containers it launched. */
7
+ export interface ForgeCgroupWriter {
8
+ set(owner: string, cgroupPaths: readonly string[]): void;
9
+ delete(owner: string): void;
10
+ }
11
+ /** Cgroups of Docker sandbox containers this bridge launched (paths below the cgroup root). */
12
+ export declare class ForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
13
+ private readonly entries;
14
+ set(owner: string, cgroupPaths: readonly string[]): void;
15
+ delete(owner: string): void;
16
+ paths(): readonly string[];
17
+ }
18
+ /**
19
+ * The registry shared by every process on the governor's state root: the
20
+ * bridge's sandbox runtime writes it, and both the bridge's and the MCP
21
+ * servers' samplers read it, so all of them count sandbox CPU as Forge's own.
22
+ */
23
+ export declare class FileForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
24
+ private readonly filePath;
25
+ private readonly registered;
26
+ private writing;
27
+ constructor(stateRoot: string);
28
+ set(owner: string, cgroupPaths: readonly string[]): void;
29
+ delete(owner: string): void;
30
+ paths(): Promise<readonly string[]>;
31
+ /** Settles once every registration so far is on disk (tests). */
32
+ flushed(): Promise<void>;
33
+ private persist;
34
+ }
35
+ /** CPU cores used by a changing set of cgroups, from `cpu.stat usage_usec` deltas. */
36
+ export declare class ForgeCgroupCpuMeter {
37
+ private readonly environment;
38
+ private marks;
39
+ constructor(environment: HostEnvironment);
40
+ /** Cores used since the previous call; a cgroup seen for the first time contributes from the next window. */
41
+ coresInUse(cgroupPaths: readonly string[], atMs: number): Promise<number>;
42
+ }
43
+ /**
44
+ * Free memory under the tightest `memory.max` from the cgroup up to and
45
+ * including the root (`memory.max − memory.current`), or null when no limit is
46
+ * set on the path. Inside a container the root is the container's own cgroup,
47
+ * whose `memory.max` is the container limit.
48
+ */
49
+ export declare function readCgroupMemoryHeadroomBytes(environment: HostEnvironment, cgroupPath: string): Promise<number | null>;
@@ -0,0 +1,140 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { readOptional } from "./host-facts.js";
5
+ import { parseCgroupCpuUsageUsec, parseNonNegativeInteger } from "./host-pressure-stall.js";
6
+ /** Cgroups of Docker sandbox containers this bridge launched (paths below the cgroup root). */
7
+ export class ForgeCgroupRegistry {
8
+ entries = new Map();
9
+ set(owner, cgroupPaths) {
10
+ if (cgroupPaths.length === 0)
11
+ this.entries.delete(owner);
12
+ else
13
+ this.entries.set(owner, [...cgroupPaths]);
14
+ }
15
+ delete(owner) {
16
+ this.entries.delete(owner);
17
+ }
18
+ paths() {
19
+ return [...new Set([...this.entries.values()].flat())];
20
+ }
21
+ }
22
+ /**
23
+ * The registry shared by every process on the governor's state root: the
24
+ * bridge's sandbox runtime writes it, and both the bridge's and the MCP
25
+ * servers' samplers read it, so all of them count sandbox CPU as Forge's own.
26
+ */
27
+ export class FileForgeCgroupRegistry {
28
+ filePath;
29
+ registered = new ForgeCgroupRegistry();
30
+ writing = Promise.resolve();
31
+ constructor(stateRoot) {
32
+ this.filePath = path.join(stateRoot, "host-load-governor", "forge-cgroups.v1.json");
33
+ }
34
+ set(owner, cgroupPaths) {
35
+ this.registered.set(owner, cgroupPaths);
36
+ this.persist();
37
+ }
38
+ delete(owner) {
39
+ this.registered.delete(owner);
40
+ this.persist();
41
+ }
42
+ paths() {
43
+ return fs.readFile(this.filePath, "utf8")
44
+ .then(content => {
45
+ const parsed = JSON.parse(content);
46
+ return Array.isArray(parsed.paths)
47
+ ? parsed.paths.filter((entry) => typeof entry === "string").slice(0, 256)
48
+ : [];
49
+ })
50
+ .catch(() => []);
51
+ }
52
+ /** Settles once every registration so far is on disk (tests). */
53
+ async flushed() {
54
+ await this.writing;
55
+ }
56
+ persist() {
57
+ const snapshot = JSON.stringify({ schemaVersion: 1, paths: this.registered.paths() });
58
+ this.writing = this.writing.then(async () => {
59
+ await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 0o700 });
60
+ const temporary = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
61
+ await fs.writeFile(temporary, snapshot, { mode: 0o600 });
62
+ await fs.rename(temporary, this.filePath);
63
+ }).catch(() => undefined);
64
+ }
65
+ }
66
+ /** CPU cores used by a changing set of cgroups, from `cpu.stat usage_usec` deltas. */
67
+ export class ForgeCgroupCpuMeter {
68
+ environment;
69
+ marks = new Map();
70
+ constructor(environment) {
71
+ this.environment = environment;
72
+ }
73
+ /** Cores used since the previous call; a cgroup seen for the first time contributes from the next window. */
74
+ async coresInUse(cgroupPaths, atMs) {
75
+ const next = new Map();
76
+ let cores = 0;
77
+ for (const cgroupPath of cgroupPaths) {
78
+ const directory = cgroupDirectory(this.environment, cgroupPath);
79
+ if (!directory)
80
+ continue;
81
+ const content = await readOptional(this.environment, path.posix.join(directory, "cpu.stat"));
82
+ const usageUsec = content ? parseCgroupCpuUsageUsec(content) : null;
83
+ if (usageUsec === null)
84
+ continue;
85
+ next.set(cgroupPath, { usageUsec, atMs });
86
+ const previous = this.marks.get(cgroupPath);
87
+ const elapsedUsec = previous ? (atMs - previous.atMs) * 1_000 : 0;
88
+ if (previous && elapsedUsec > 0 && usageUsec >= previous.usageUsec) {
89
+ cores += (usageUsec - previous.usageUsec) / elapsedUsec;
90
+ }
91
+ }
92
+ this.marks = next;
93
+ return cores;
94
+ }
95
+ }
96
+ /**
97
+ * Free memory under the tightest `memory.max` from the cgroup up to and
98
+ * including the root (`memory.max − memory.current`), or null when no limit is
99
+ * set on the path. Inside a container the root is the container's own cgroup,
100
+ * whose `memory.max` is the container limit.
101
+ */
102
+ export async function readCgroupMemoryHeadroomBytes(environment, cgroupPath) {
103
+ let tightest = null;
104
+ for (const current of cgroupPathAndAncestors(cgroupPath)) {
105
+ const directory = cgroupDirectory(environment, current);
106
+ if (!directory)
107
+ return null;
108
+ const [maximum, used] = await Promise.all([
109
+ readOptional(environment, path.posix.join(directory, "memory.max")),
110
+ readOptional(environment, path.posix.join(directory, "memory.current")),
111
+ ]);
112
+ const limit = maximum ? parseNonNegativeInteger(maximum) : null;
113
+ const usage = used ? parseNonNegativeInteger(used) : null;
114
+ if (limit === null || usage === null)
115
+ continue;
116
+ const headroom = Math.max(0, limit - usage);
117
+ tightest = tightest === null ? headroom : Math.min(tightest, headroom);
118
+ }
119
+ return tightest;
120
+ }
121
+ /** `/a/b/c`, `/a/b`, `/a`, `/`; nothing for a relative or traversing path. */
122
+ function cgroupPathAndAncestors(cgroupPath) {
123
+ if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
124
+ return [];
125
+ const paths = [];
126
+ for (let current = path.posix.normalize(cgroupPath);; current = path.posix.dirname(current)) {
127
+ paths.push(current);
128
+ if (current === "/")
129
+ return paths;
130
+ }
131
+ }
132
+ function cgroupDirectory(environment, cgroupPath) {
133
+ if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
134
+ return null;
135
+ const root = environment.cgroupRoot.replace(/\/+$/u, "");
136
+ if (cgroupPath === "/")
137
+ return root;
138
+ const directory = path.posix.join(root, cgroupPath);
139
+ return directory.startsWith(`${root}/`) ? directory : null;
140
+ }
@@ -0,0 +1,43 @@
1
+ export type HostLoadGovernorMode = "on" | "off";
2
+ export interface HostLoadGovernorConfig {
3
+ /** FORGE_HOST_LOAD_GOVERNOR. Off by default in this step; `off` is the operator override. */
4
+ readonly mode: HostLoadGovernorMode;
5
+ /** Share of logical CPUs Forge may reserve for heavy steps. */
6
+ readonly cpuBudgetFraction: number;
7
+ /** Memory kept free for the rest of the host, taken off MemAvailable. */
8
+ readonly memoryReserveBytes: number;
9
+ /** Host CPU PSI `some avg10` (percent) at or above which a sample counts as pressured. */
10
+ readonly cpuPressureThreshold: number;
11
+ /** Consecutive pressured samples that stop new admissions (backpressure). */
12
+ readonly backpressureSamples: number;
13
+ /** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
14
+ readonly memoryFullThreshold: number;
15
+ /** Maximum queue wait before a retryable host_capacity_timeout. */
16
+ readonly maxWaitMs: number;
17
+ /** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
18
+ readonly fallbackSlots: number;
19
+ /** After this long at the head of the queue, later waiters may no longer overtake it. */
20
+ readonly antiStarvationMs: number;
21
+ /** Token lease; the owner renews well before it expires. */
22
+ readonly leaseMs: number;
23
+ /** How often waiters are re-evaluated against fresh samples and the shared ledger. */
24
+ readonly recheckIntervalMs: number;
25
+ /** A load sample older than this is treated as missing PSI. */
26
+ readonly sampleStaleMs: number;
27
+ /** The sampler's interval; a longer gap between samples resets the pressure streak. */
28
+ readonly sampleIntervalMs: number;
29
+ /** Without a dedicated cgroup, a step this old is assumed to use its reserved memory. */
30
+ readonly memoryRampMs: number;
31
+ /**
32
+ * Decision 0014 operator ceilings, applied by every governor itself so they hold even
33
+ * without the bridge's runtime settings file (before its first write, after a failed
34
+ * write, or a file that can't be read): the lower of FORGE_HOST_CPU_BUDGET_PERCENT (as a
35
+ * fraction) and an explicitly set FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, and
36
+ * FORGE_HOST_MAX_HEAVY_STEPS. Null when unset.
37
+ */
38
+ readonly cpuBudgetCeilingFraction?: number | null;
39
+ readonly maxHeavyStepsCeiling?: number | null;
40
+ }
41
+ export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
42
+ export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
43
+ export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;