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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/bridge/bridge.service.js +10 -4
  2. package/dist/cli/cli.service.js +1 -1
  3. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  4. package/dist/runtime/host-load-child-environment.js +65 -0
  5. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  6. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  7. package/dist/runtime/host-load-governor.d.ts +60 -11
  8. package/dist/runtime/host-load-governor.js +145 -41
  9. package/dist/runtime/host-load-sampler.d.ts +5 -0
  10. package/dist/runtime/host-load-sampler.js +12 -4
  11. package/dist/runtime/host-load-step-class.d.ts +35 -0
  12. package/dist/runtime/host-load-step-class.js +60 -0
  13. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  14. package/dist/runtime/host-load-step-reaper.js +95 -0
  15. package/dist/runtime/host-load-step-run.d.ts +73 -0
  16. package/dist/runtime/host-load-step-run.js +102 -0
  17. package/dist/runtime/host-load-token-ledger.d.ts +58 -19
  18. package/dist/runtime/host-load-token-ledger.js +111 -35
  19. package/dist/runtime/host-runtime-lease.d.ts +4 -1
  20. package/dist/runtime/host-runtime-lease.js +59 -5
  21. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  22. package/dist/sandbox/host-capacity-broker.js +315 -0
  23. package/dist/sandbox/runtime.d.ts +10 -1
  24. package/dist/sandbox/runtime.js +45 -2
  25. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  26. package/dist/sandbox/sandbox-cgroups.js +42 -0
  27. package/dist/session/managed-attempt-tools.js +120 -24
  28. package/dist/session/managed-command-host-load.d.ts +45 -0
  29. package/dist/session/managed-command-host-load.js +82 -0
  30. package/dist/session/phase-completion.d.ts +2 -0
  31. package/dist/session/phase-completion.runtime.d.ts +1 -1
  32. package/dist/session/phase-completion.runtime.js +14 -6
  33. package/dist/session/pre-publication-host-load.js +31 -16
  34. package/dist/session/pre-publication-process.d.ts +3 -0
  35. package/dist/session/pre-publication-process.js +23 -11
  36. package/dist/session/pre-publication-validation.js +4 -0
  37. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  38. package/dist/session/provider-cli/provider-cli.service.js +20 -12
  39. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  40. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  41. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  42. package/dist/session/session.service.js +16 -4
  43. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  44. package/dist/shared/process/host-process-supervisor.js +1 -1
  45. package/dist/shared/process/process-tree.d.ts +52 -0
  46. package/dist/shared/process/process-tree.js +144 -0
  47. package/dist/shared/process/process.d.ts +67 -0
  48. package/dist/shared/process/process.js +213 -11
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/dist/worktree/dependency-warmer.d.ts +25 -0
  52. package/dist/worktree/dependency-warmer.js +46 -10
  53. package/dist/worktree/worktree.service.d.ts +6 -1
  54. package/dist/worktree/worktree.service.js +14 -2
  55. package/dist/worktree/worktree.types.d.ts +7 -0
  56. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import { monotonicNowMs } from "../shared/time/monotonic.js";
2
2
  import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
3
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
4
+ import { retentionFor, returnHostLoadToken } from "../runtime/host-load-step-run.js";
4
5
  import { classifyValidationStep } from "../runtime/host-load-step-class.js";
5
6
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
6
7
  /**
@@ -48,49 +49,63 @@ export async function runHostGovernedValidationStep(gate, step, run) {
48
49
  await emit("prepublication_host_capacity_admitted", `Pre-publication step '${step.checkId}' (${stepClass}) was admitted after ${waitMs}ms waiting for host capacity.`, { status: "running", reason: admission.decision.reason, host_load_wait_ms: waitMs });
49
50
  // Step timers start here, after admission: a step can never time out because it waited.
50
51
  const startedAtMs = monotonicNowMs();
51
- const runSignal = step.signal ? AbortSignal.any([step.signal, admission.signal]) : admission.signal;
52
+ const runSignal = step.signal ? AbortSignal.any([step.signal, admission.fenced]) : admission.fenced;
52
53
  const reservationLost = async () => {
53
- const reason = admission.signal.reason;
54
+ const reason = admission.fenced.reason;
54
55
  await emit("prepublication_host_capacity_lost", `Pre-publication step '${step.checkId}' (${stepClass}) was stopped because its host capacity reservation was lost: ${reason instanceof Error ? reason.message : String(reason)}`, { status: "host_capacity_lost" }, "error");
55
56
  throw reason;
56
57
  };
58
+ let unstopped = null;
57
59
  try {
58
60
  let result;
59
61
  try {
60
62
  result = await run(runSignal);
61
63
  }
62
64
  catch (error) {
63
- if (admission.signal.aborted)
65
+ // Part of the step may still run: that, not a fence, is what it failed with.
66
+ // Also a supervised runner's failed proof, which arrives sanitized and wrapped.
67
+ const retention = retentionFor(error);
68
+ if (retention) {
69
+ unstopped = retention;
70
+ throw error;
71
+ }
72
+ if (admission.fenced.aborted)
64
73
  return await reservationLost();
65
74
  throw error;
66
75
  }
67
76
  // A result produced after the reservation was lost is not trusted either.
68
- if (admission.signal.aborted)
77
+ if (admission.fenced.aborted)
69
78
  return await reservationLost();
70
79
  return result;
71
80
  }
72
81
  finally {
73
82
  const elapsedMs = Math.round(monotonicNowMs() - startedAtMs);
74
- let failure = null;
75
- try {
76
- await admission.release();
77
- }
78
- catch (error) {
79
- failure = {
83
+ // Assigned in the catch above; widened, since control-flow narrowing does not see it here.
84
+ const treeLeft = unstopped;
85
+ const returned = {
86
+ failure: treeLeft ? { kind: "retained", message: treeLeft.reason.message } : null,
87
+ };
88
+ // The token is kept, with its cost, while part of the step's tree may still run.
89
+ await returnHostLoadToken(admission, treeLeft, error => {
90
+ returned.failure = {
80
91
  kind: error instanceof HostCapacityTokenFencedError ? "fenced" : "ledger_unavailable",
81
92
  message: error instanceof Error ? error.message : String(error),
82
93
  };
83
- }
84
- await emit("prepublication_host_capacity_released", failure?.kind === "fenced"
85
- ? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
86
- : failure
87
- ? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
88
- : `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
94
+ });
95
+ const failure = returned.failure;
96
+ await emit("prepublication_host_capacity_released", failure?.kind === "retained"
97
+ ? `Pre-publication step '${step.checkId}' ended, but part of its process tree did not stop; its host capacity stays reserved until it is gone: ${failure.message}`
98
+ : failure?.kind === "fenced"
99
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
100
+ : failure
101
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
102
+ : `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
89
103
  status: "completed",
90
104
  host_load_wait_ms: waitMs,
91
105
  elapsed_ms: elapsedMs,
92
106
  tokenFenced: failure?.kind === "fenced",
93
107
  releaseFailed: failure?.kind === "ledger_unavailable",
108
+ tokenRetained: failure?.kind === "retained",
94
109
  });
95
110
  }
96
111
  }
@@ -1,7 +1,10 @@
1
1
  import type { PrePublicationCommandResult, PrePublicationCommandRunner } from "./pre-publication-validation.js";
2
+ /** Output kept per stream for one validation step (the tail). */
3
+ export declare const prePublicationOutputLimitChars: number;
2
4
  export declare class ProcessPrePublicationCommandRunner implements PrePublicationCommandRunner {
3
5
  run(command: string, args: readonly string[], cwd: string, signal?: AbortSignal, environment?: Readonly<Record<string, string>>): Promise<PrePublicationCommandResult>;
4
6
  }
7
+ export declare function prePublicationChildEnvironment(environment?: Readonly<Record<string, string>>): NodeJS.ProcessEnv;
5
8
  interface PackageManagerLaunchLocation {
6
9
  readonly args: readonly string[];
7
10
  readonly cwd: string;
@@ -1,10 +1,11 @@
1
- import { execFile } from "node:child_process";
2
1
  import fs from "node:fs/promises";
3
2
  import path from "node:path";
4
- import { promisify } from "node:util";
5
3
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
4
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
6
5
  import { isSubPath } from "../shared/path/path.js";
7
- const execFileAsync = promisify(execFile);
6
+ import { NodeProcessRunner, ProcessTreeTerminationError } from "../shared/process/process.js";
7
+ /** Output kept per stream for one validation step (the tail). */
8
+ export const prePublicationOutputLimitChars = 4 * 1024 * 1024;
8
9
  export class ProcessPrePublicationCommandRunner {
9
10
  async run(command, args, cwd, signal, environment) {
10
11
  try {
@@ -14,18 +15,27 @@ export class ProcessPrePublicationCommandRunner {
14
15
  const commandArgs = windowsBatch
15
16
  ? ["/d", "/s", "/c", [`${command}.cmd`, ...launch.args].map(quoteWindowsCommandArgument).join(" ")]
16
17
  : [...launch.args];
17
- const result = await execFileAsync(executable, commandArgs, {
18
+ // A process group the runner stops as a whole, settling only once it is gone:
19
+ // a validation step's host capacity is never returned while its test hosts,
20
+ // build nodes or browser workers still run.
21
+ const result = await new NodeProcessRunner().run({
22
+ command: executable,
23
+ args: commandArgs,
18
24
  cwd: launch.cwd,
19
- encoding: "utf8",
20
- maxBuffer: 4 * 1024 * 1024,
21
- signal,
22
25
  env: prePublicationChildEnvironment(environment),
26
+ rawOutput: true,
27
+ processGroup: true,
28
+ // The bound execFile had: a noisy step keeps its last 4 MiB (where failures
29
+ // are reported) instead of holding all of its output in the bridge.
30
+ maxOutputChars: prePublicationOutputLimitChars,
31
+ signal,
23
32
  });
24
- return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
33
+ return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
25
34
  }
26
35
  catch (error) {
27
36
  const failure = error;
28
- if (failure.name === "AbortError")
37
+ // Neither is a command result: a stop, or a tree that outlived it.
38
+ if (failure.name === "AbortError" || error instanceof ProcessTreeTerminationError)
29
39
  throw error;
30
40
  if (failure.code === "ENOENT") {
31
41
  return { exitCode: 127, stderr: `executable_not_found: ${command}` };
@@ -41,7 +51,7 @@ export class ProcessPrePublicationCommandRunner {
41
51
  function quoteWindowsCommandArgument(value) {
42
52
  return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
43
53
  }
44
- function prePublicationChildEnvironment(environment) {
54
+ export function prePublicationChildEnvironment(environment) {
45
55
  const child = {};
46
56
  const privilegedNames = new Set([
47
57
  hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
@@ -53,7 +63,9 @@ function prePublicationChildEnvironment(environment) {
53
63
  child[name] = value;
54
64
  }
55
65
  }
56
- return { ...child, ...environment };
66
+ // A validation step must not join the host ledger (it would queue behind its own token)
67
+ // or the sandbox broker, whether the variable is inherited or passed in explicitly.
68
+ return withoutHostLoadGovernorVariables({ ...child, ...environment });
57
69
  }
58
70
  /**
59
71
  * Corepack picks the pnpm version from the nearest package.json `packageManager`
@@ -9,6 +9,7 @@ import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminE
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
11
11
  import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
12
+ import { ProcessTreeTerminationError } from "../shared/process/process.js";
12
13
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
13
14
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
14
15
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
@@ -354,6 +355,9 @@ export class PrePublicationValidator {
354
355
  };
355
356
  }
356
357
  catch (error) {
358
+ // Carries the check its host capacity token waits on; it names only the executable.
359
+ if (error instanceof ProcessTreeTerminationError)
360
+ throw error;
357
361
  throw sanitizeFailureError(error, exactSecrets);
358
362
  }
359
363
  }
@@ -379,7 +379,7 @@ export class StreamingProviderProcessRunner {
379
379
  const childStderr = child.stderr;
380
380
  if (!childStdout || !childStderr) {
381
381
  const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
382
- void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "Provider launch failed and its process tree could not be proven stopped.")));
382
+ void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "host_process_supervisor_termination_failed: Provider launch failed and its process tree could not be proven stopped.")));
383
383
  return;
384
384
  }
385
385
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
@@ -415,7 +415,7 @@ export class StreamingProviderProcessRunner {
415
415
  cleanup();
416
416
  // Do not release the caller's reservation/worktree/port ownership until
417
417
  // descendant termination has completed (or failed with explicit proof).
418
- void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
418
+ void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "host_process_supervisor_termination_failed: Provider process failed and its process tree could not be proven stopped.")));
419
419
  };
420
420
  const abort = () => {
421
421
  if (!closed)
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  import { RepositoryCoordinatorLock } from "../../sandbox/repository-lock.js";
4
4
  import { GitClient } from "../../shared/git/git.js";
5
5
  import { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
6
+ import { sandboxHostLoadGateFromEnvironment } from "../sandbox-host-capacity-gate.js";
6
7
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
7
8
  import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
8
9
  import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
@@ -437,7 +438,8 @@ export class ManagedVerificationProgressEmitter {
437
438
  }
438
439
  }
439
440
  function isManagedVerificationNonterminal(status) {
440
- return status === "starting" || status === "running" || status === "waiting_for_build_slot";
441
+ return status === "starting" || status === "running" || status === "waiting_for_build_slot"
442
+ || status === "waiting_for_host_capacity";
441
443
  }
442
444
  async function parseManagedVerificationSnapshot(receiptPath) {
443
445
  try {
@@ -570,11 +572,11 @@ export class ProcessBackedProviderCliService {
570
572
  publicationCoordinator;
571
573
  prePublicationValidator;
572
574
  constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
573
- // No host load gate here: the Docker sandbox worker (`forge` run-once via
574
- // ForgeBridgeCliService) builds this default, and a container cannot reach the
575
- // host's governor ledger, so Docker-mode validation is not yet governed
576
- // (decision 0013). Only the host bridge wires HostRuntimeLeaseManager's gate.
577
- prePublicationValidator = new PrePublicationValidator()) {
575
+ // The Docker sandbox worker (`forge` run-once via ForgeBridgeCliService) builds
576
+ // this default. A container cannot reach the host ledger, so when the host
577
+ // bridge enabled it, its steps ask the bridge for tokens over the sandbox
578
+ // channel (decision 0013); elsewhere the gate is absent and validation is ungated.
579
+ prePublicationValidator = new PrePublicationValidator(undefined, undefined, undefined, sandboxHostLoadGateFromEnvironment())) {
578
580
  this.processRunner = processRunner;
579
581
  this.git = git;
580
582
  this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
@@ -593,7 +595,7 @@ export class ProcessBackedProviderCliService {
593
595
  await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
594
596
  const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
595
597
  const decomposeDraft = isDecomposeDraftDispatch(dispatch);
596
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment });
598
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
597
599
  const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
598
600
  const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
599
601
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -776,7 +778,7 @@ export class ProcessBackedProviderCliService {
776
778
  const specPath = path.join(metadataRoot, "spec.md");
777
779
  await fs.writeFile(specPath, specBody, "utf8");
778
780
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
779
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment });
781
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
780
782
  const implementationPrompt = debugCycle
781
783
  ? buildDebugCyclePrompt(dispatch, phase)
782
784
  : developCycle
@@ -924,7 +926,7 @@ export class ProcessBackedProviderCliService {
924
926
  const specPath = path.join(metadataRoot, "spec.md");
925
927
  await fs.writeFile(specPath, specBody, "utf8");
926
928
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-lane-command" }) + "\n", "utf8");
927
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment });
929
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
928
930
  const architectPrompt = buildArchitectPrompt(dispatch);
929
931
  const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
930
932
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -1029,7 +1031,7 @@ export class ProcessBackedProviderCliService {
1029
1031
  const specPath = path.join(metadataRoot, "spec.md");
1030
1032
  await fs.writeFile(specPath, specBody, "utf8");
1031
1033
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
1032
- const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment });
1034
+ const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
1033
1035
  const qaPrompt = buildQaPrompt(dispatch, specBody);
1034
1036
  const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
1035
1037
  const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
@@ -1170,7 +1172,9 @@ export class ProcessBackedProviderCliService {
1170
1172
  };
1171
1173
  const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
1172
1174
  repairEnvironment = readiness.environment;
1173
- completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment });
1175
+ completionTools = await prepareCompletionToolRuntime({
1176
+ dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
1177
+ });
1174
1178
  await context.emit({
1175
1179
  role: "runner",
1176
1180
  kind: "checkpoint",
@@ -1185,7 +1189,9 @@ export class ProcessBackedProviderCliService {
1185
1189
  });
1186
1190
  }
1187
1191
  if (addressComments) {
1188
- completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment });
1192
+ completionTools = await prepareCompletionToolRuntime({
1193
+ dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
1194
+ });
1189
1195
  await context.emit({
1190
1196
  role: "runner",
1191
1197
  kind: "checkpoint",
@@ -1394,6 +1400,7 @@ export class ProcessBackedProviderCliService {
1394
1400
  worktree,
1395
1401
  phase: "qa",
1396
1402
  runtimeEnvironment: context.runtimeEnvironment,
1403
+ hostLoadEnvironment: context.hostLoadEnvironment,
1397
1404
  });
1398
1405
  const command = buildProviderCliCommand(recoveryDispatch, {
1399
1406
  worktreePath: worktree.worktreePath,
@@ -1503,6 +1510,7 @@ export class ProcessBackedProviderCliService {
1503
1510
  worktree,
1504
1511
  phase: "comment_repair",
1505
1512
  runtimeEnvironment: repairEnvironment,
1513
+ hostLoadEnvironment: context.hostLoadEnvironment,
1506
1514
  });
1507
1515
  const command = buildProviderCliCommand(recoveryDispatch, {
1508
1516
  worktreePath: worktree.worktreePath,
@@ -5,6 +5,8 @@ export interface ProviderCliRunContext {
5
5
  readonly dispatch: RunOnceDispatchPacket;
6
6
  readonly worktree: WorktreeHandle;
7
7
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
8
+ /** Host load governor variables for the completion MCP server only (decision 0013). */
9
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
8
10
  readonly processRunner?: ProviderProcessRunner;
9
11
  readonly signal?: AbortSignal;
10
12
  emit(event: RunnerDispatchEvent): Promise<void>;
@@ -13,6 +15,8 @@ export interface ProviderCliDraftContext {
13
15
  readonly dispatch: RunOnceDispatchPacket;
14
16
  readonly worktree: WorktreeHandle;
15
17
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
18
+ /** Host load governor variables for the completion MCP server only (decision 0013). */
19
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
16
20
  readonly processRunner?: ProviderProcessRunner;
17
21
  readonly signal?: AbortSignal;
18
22
  emit(event: RunnerDispatchEvent): Promise<void>;
@@ -0,0 +1,30 @@
1
+ import { type HostLoadAcquireOptions, type HostLoadAdmission, type HostLoadStepGate, type HostLoadStepRequest } from "../runtime/host-load-governor.js";
2
+ export interface SandboxHostCapacityGateOptions {
3
+ readonly write?: (line: string) => void;
4
+ readonly responseRoot?: string;
5
+ readonly pollMs?: number;
6
+ /** Fails closed if the bridge never answers (the host enforces its own maximum wait first). */
7
+ readonly maxWaitMs?: number;
8
+ /** Owner of authentic replies (root in the container; tests use their own uid). */
9
+ readonly trustedOwnerUid?: number;
10
+ }
11
+ export declare class SandboxBrokeredHostLoadGate implements HostLoadStepGate {
12
+ readonly enabled = true;
13
+ private readonly write;
14
+ private readonly responseRoot;
15
+ private readonly pollMs;
16
+ private readonly trustedOwnerUid;
17
+ readonly maxWaitMs: number;
18
+ constructor(options?: SandboxHostCapacityGateOptions);
19
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
20
+ private admission;
21
+ private send;
22
+ }
23
+ /**
24
+ * The brokered gate when the host bridge enabled it for this sandbox. The
25
+ * variable is removed once read, so commands the sandbox runs never inherit it
26
+ * (a nested Forge process must not queue behind its parent's token).
27
+ */
28
+ export declare function sandboxHostLoadGateFromEnvironment(environment?: NodeJS.ProcessEnv): HostLoadStepGate | undefined;
29
+ /** Test support: forgets the cached gate. */
30
+ export declare function resetSandboxHostLoadGateForTesting(): void;
@@ -0,0 +1,229 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants as fsConstants } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { HostCapacityTimeoutError, } from "../runtime/host-load-governor.js";
6
+ import { defaultHostLoadGovernorConfig } from "../runtime/host-load-governor-config.js";
7
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
8
+ import { sandboxHostCapacityBrokerEnvironment, sandboxHostCapacityBrokerProtocol, sandboxHostCapacityLineType, sandboxHostCapacityMaxWaitEnvironment, sandboxHostCapacityResponseOwnerUid, sandboxHostCapacityResponseRoot, } from "../sandbox/host-capacity-broker.js";
9
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
10
+ import { ForgeFailureError } from "./session.types.js";
11
+ export class SandboxBrokeredHostLoadGate {
12
+ enabled = true;
13
+ write;
14
+ responseRoot;
15
+ pollMs;
16
+ trustedOwnerUid;
17
+ maxWaitMs;
18
+ constructor(options = {}) {
19
+ this.write = options.write ?? (line => { process.stdout.write(line); });
20
+ this.responseRoot = options.responseRoot ?? sandboxHostCapacityResponseRoot;
21
+ this.pollMs = options.pollMs ?? 250;
22
+ this.trustedOwnerUid = options.trustedOwnerUid ?? sandboxHostCapacityResponseOwnerUid;
23
+ this.maxWaitMs = options.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs + 2 * 60_000;
24
+ }
25
+ async acquire(request, options = {}) {
26
+ const requestId = randomUUID();
27
+ const responsePath = path.join(this.responseRoot, `${requestId}.json`);
28
+ const startedAtMs = monotonicNowMs();
29
+ this.send("acquire", requestId, request);
30
+ let waitingReported = false;
31
+ try {
32
+ while (true) {
33
+ if (options.signal?.aborted)
34
+ throw options.signal.reason ?? new Error("The host capacity wait was cancelled.");
35
+ const response = await readResponse(responsePath, requestId, this.trustedOwnerUid);
36
+ if (response?.status === "waiting" && !waitingReported) {
37
+ waitingReported = true;
38
+ void Promise.resolve(options.onWaiting?.(decision(false, response))).catch(() => undefined);
39
+ }
40
+ if (response?.status === "admitted")
41
+ return this.admission(requestId, responsePath, request, response);
42
+ if (response?.status === "failed" || response?.status === "fenced")
43
+ throw responseError(request, response);
44
+ if (monotonicNowMs() - startedAtMs > this.maxWaitMs) {
45
+ throw new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - startedAtMs, "the host bridge did not answer the sandbox's host capacity request.");
46
+ }
47
+ await delay(this.pollMs);
48
+ }
49
+ }
50
+ catch (error) {
51
+ this.send("release", requestId, request);
52
+ await fs.rm(responsePath, { force: true }).catch(() => undefined);
53
+ throw error;
54
+ }
55
+ }
56
+ admission(requestId, responsePath, request, response) {
57
+ const fenced = new AbortController();
58
+ // The bridge rewrites the response as "fenced" if it lost the token; the step then stops.
59
+ const watch = setInterval(() => {
60
+ void readResponse(responsePath, requestId, this.trustedOwnerUid).then(current => {
61
+ if (current?.status === "fenced" && !fenced.signal.aborted) {
62
+ fenced.abort(new HostCapacityTokenFencedError(requestId, "renew"));
63
+ }
64
+ }, (error) => {
65
+ // A reply that is not the bridge's: the reservation can no longer be trusted.
66
+ if (!fenced.signal.aborted)
67
+ fenced.abort(error);
68
+ });
69
+ }, Math.max(this.pollMs, 1_000));
70
+ watch.unref?.();
71
+ let released = false;
72
+ let holding = false;
73
+ let retainTimer = null;
74
+ const giveBack = async () => {
75
+ if (released)
76
+ return;
77
+ released = true;
78
+ clearInterval(watch);
79
+ if (retainTimer)
80
+ clearInterval(retainTimer);
81
+ this.send("release", requestId, request);
82
+ await fs.rm(responsePath, { force: true }).catch(() => undefined);
83
+ };
84
+ return {
85
+ tokenId: requestId,
86
+ fencingToken: 0,
87
+ stepClass: request.stepClass,
88
+ waitMs: response.waitMs ?? 0,
89
+ decision: decision(true, response),
90
+ fenced: fenced.signal,
91
+ // The container's processes are stopped with the sandbox; nothing to record host-side.
92
+ attachProcess: async () => undefined,
93
+ release: async () => {
94
+ if (released || holding)
95
+ return;
96
+ await giveBack();
97
+ if (fenced.signal.aborted)
98
+ throw fenced.signal.reason;
99
+ },
100
+ // Part of the step's tree may still run in the container: the request stays
101
+ // outstanding, so the bridge keeps the host token, until the check proves it
102
+ // gone. Without a check it is kept until the container exits, which stops every
103
+ // process in it and makes the bridge return the token.
104
+ retainUntilStopped: (stillGone, reason) => {
105
+ if (released || holding)
106
+ return;
107
+ holding = true;
108
+ if (!fenced.signal.aborted)
109
+ fenced.abort(reason);
110
+ if (!stillGone)
111
+ return;
112
+ let checking = false;
113
+ retainTimer = setInterval(() => {
114
+ if (checking)
115
+ return;
116
+ checking = true;
117
+ void stillGone()
118
+ .then(gone => gone ? giveBack() : undefined, () => undefined)
119
+ .finally(() => { checking = false; });
120
+ }, Math.max(this.pollMs, 1_000));
121
+ retainTimer.unref?.();
122
+ },
123
+ };
124
+ }
125
+ send(action, requestId, request) {
126
+ this.write(`${JSON.stringify({
127
+ type: sandboxHostCapacityLineType,
128
+ version: 1,
129
+ action,
130
+ requestId,
131
+ stepClass: request.stepClass,
132
+ label: request.label,
133
+ })}\n`);
134
+ }
135
+ }
136
+ let cachedGate = null;
137
+ /**
138
+ * The brokered gate when the host bridge enabled it for this sandbox. The
139
+ * variable is removed once read, so commands the sandbox runs never inherit it
140
+ * (a nested Forge process must not queue behind its parent's token).
141
+ */
142
+ export function sandboxHostLoadGateFromEnvironment(environment = process.env) {
143
+ if (cachedGate !== null)
144
+ return cachedGate;
145
+ const protocol = environment[sandboxHostCapacityBrokerEnvironment];
146
+ const hostMaxWaitMs = Number(environment[sandboxHostCapacityMaxWaitEnvironment]);
147
+ delete environment[sandboxHostCapacityBrokerEnvironment];
148
+ delete environment[sandboxHostCapacityMaxWaitEnvironment];
149
+ cachedGate = environment.FORGE_RUNTIME_MODE === "docker" && protocol === sandboxHostCapacityBrokerProtocol
150
+ // The host's own maximum wait (the operator may have changed it) plus slack for the reply.
151
+ ? new SandboxBrokeredHostLoadGate(Number.isFinite(hostMaxWaitMs) && hostMaxWaitMs > 0
152
+ ? { maxWaitMs: hostMaxWaitMs + 2 * 60_000 }
153
+ : {})
154
+ : undefined;
155
+ return cachedGate;
156
+ }
157
+ /** Test support: forgets the cached gate. */
158
+ export function resetSandboxHostLoadGateForTesting() {
159
+ cachedGate = null;
160
+ }
161
+ function decision(admitted, response) {
162
+ return {
163
+ admitted,
164
+ reason: (response.reason ?? (admitted ? "admitted" : "cpu_budget")),
165
+ cpuBudgetCores: null,
166
+ memoryBudgetBytes: null,
167
+ reservedCpuCores: 0,
168
+ reservedMemoryBytes: 0,
169
+ detail: response.detail ?? (admitted ? "The host bridge admitted the step." : "The host is at capacity."),
170
+ };
171
+ }
172
+ function responseError(request, response) {
173
+ const message = response.message ?? "The host bridge refused the sandbox's host capacity request.";
174
+ if (response.code === "host_capacity_timeout") {
175
+ return new HostCapacityTimeoutError(request.stepClass, request.label, response.waitMs ?? 0, message);
176
+ }
177
+ return new ForgeFailureError(response.code ?? "host_capacity_broker_failed", message, "bridge");
178
+ }
179
+ /**
180
+ * The bridge's reply, or null while there is none. Only a regular file with a
181
+ * single link, owned by the trusted uid and writable by no one else, is the
182
+ * bridge's: the sandbox user can create none of those (see host-capacity-broker.ts).
183
+ * Anything else fails closed with sandbox_host_capacity_reply_untrusted.
184
+ */
185
+ async function readResponse(responsePath, requestId, trustedOwnerUid) {
186
+ let handle;
187
+ try {
188
+ handle = await fs.open(responsePath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
189
+ }
190
+ catch (error) {
191
+ if (error.code === "ENOENT")
192
+ return null;
193
+ throw untrustedReply(responsePath, `it could not be opened safely (${error.code ?? "error"})`);
194
+ }
195
+ let content;
196
+ try {
197
+ const stat = await handle.stat();
198
+ if (!stat.isFile() || stat.nlink !== 1)
199
+ throw untrustedReply(responsePath, "it is not a regular file with a single link");
200
+ if (stat.uid !== trustedOwnerUid)
201
+ throw untrustedReply(responsePath, `it is owned by uid ${stat.uid}, not the bridge`);
202
+ if ((stat.mode & 0o022) !== 0)
203
+ throw untrustedReply(responsePath, "others can write it");
204
+ content = await handle.readFile("utf8");
205
+ }
206
+ finally {
207
+ await handle.close();
208
+ }
209
+ try {
210
+ const value = JSON.parse(content);
211
+ if (!value || typeof value.status !== "string")
212
+ return null;
213
+ if (value.requestId !== requestId)
214
+ throw untrustedReply(responsePath, "it answers another request");
215
+ return value;
216
+ }
217
+ catch (error) {
218
+ if (error instanceof ForgeFailureError)
219
+ throw error;
220
+ // Mid-write is impossible (replies are renamed into place); treat garbage as no reply yet.
221
+ return null;
222
+ }
223
+ }
224
+ function untrustedReply(responsePath, reason) {
225
+ return new ForgeFailureError("sandbox_host_capacity_reply_untrusted", `sandbox_host_capacity_reply_untrusted: ${path.basename(responsePath)} was not written by the host bridge (${reason}); the step does not run on it.`, "sandbox");
226
+ }
227
+ async function delay(ms) {
228
+ await new Promise(resolve => setTimeout(resolve, ms));
229
+ }