@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
@@ -8,6 +8,12 @@ import { requireSandboxProcess, runSandboxProcess } from "./process.js";
8
8
  import { createLeaseUpdate } from "./lease-watchdog.js";
9
9
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
10
10
  import { SandboxEventBudget } from "./event-budget.js";
11
+ import { SandboxHostCapacityBroker, sandboxHostCapacityDeliveryExecArgs, withSandboxHostCapacityBroker, } from "./host-capacity-broker.js";
12
+ import { defaultHostLoadGovernorConfig } from "../runtime/host-load-governor-config.js";
13
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
14
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
15
+ import { trackSandboxCgroups } from "./sandbox-cgroups.js";
16
+ import { runtimeAdmissionPriority } from "../runtime/host-runtime-lease.js";
11
17
  import { RepositoryCoordinatorLock } from "./repository-lock.js";
12
18
  import { redactText } from "../shared/redaction/redaction.js";
13
19
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "../runtime/runtime-isolation-lease.js";
@@ -18,14 +24,21 @@ const bridgeRuntimeDigestLabel = "dev.forge.bridge-runtime-digest";
18
24
  export class DockerSandboxRuntime {
19
25
  config;
20
26
  publicationGrantRedeemer;
27
+ hostLoadGate;
21
28
  active = new Map();
22
29
  degraded = new Set();
23
30
  builds = new Map();
24
31
  verifiedCatalogImages = new Set();
25
32
  buildTail = Promise.resolve();
26
- constructor(config, publicationGrantRedeemer) {
33
+ /** Shared with every sampler on the state root, so sandbox CPU is never external load. */
34
+ forgeCgroups;
35
+ constructor(config, publicationGrantRedeemer,
36
+ /** The host load governor; with it on, the sandbox's validation steps are brokered through it (decision 0013). */
37
+ hostLoadGate) {
27
38
  this.config = config;
28
39
  this.publicationGrantRedeemer = publicationGrantRedeemer;
40
+ this.hostLoadGate = hostLoadGate;
41
+ this.forgeCgroups = new FileForgeCgroupRegistry(config.sandboxStateRoot);
29
42
  }
30
43
  async runOnce(dispatch, sink, signal) {
31
44
  if (!dispatch.sandbox || dispatch.sandbox.executionMode !== "docker" || dispatch.sandbox.runtime !== "docker") {
@@ -153,7 +166,11 @@ export class DockerSandboxRuntime {
153
166
  await this.initializeEgressPolicy(builtImage.helperImageDigest, runtimeDispatch, resources, labels, runtimeSignal);
154
167
  const egressProxy = await this.startEgressProxy(runtimeDispatch, resources, labels, securityOptions, sink, runtimeSignal);
155
168
  const serviceContainers = await this.startServices(validated, runtimeDispatch.sandbox.executionPolicy, resources, labels, securityOptions, sink, runtimeSignal);
156
- const createArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
169
+ const brokered = this.hostLoadGate?.enabled === true;
170
+ const workerArgs = workerCreateArgs(runtimeDispatch, validated, resources, labels, imageDigest, securityOptions);
171
+ const createArgs = brokered
172
+ ? withSandboxHostCapacityBroker(workerArgs, imageDigest, this.hostLoadGate.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs)
173
+ : workerArgs;
157
174
  const createdContainer = await this.docker(createArgs, 60_000, runtimeSignal);
158
175
  const containerId = dockerObjectId(createdContainer.stdout, "container");
159
176
  await this.docker(["cp", prepared.bundlePath, `${containerId}:/control/input/repo.bundle`], 60_000, runtimeSignal);
@@ -183,6 +200,16 @@ export class DockerSandboxRuntime {
183
200
  runtimeLease: active.runtimeLease,
184
201
  }));
185
202
  const eventBudget = new SandboxEventBudget();
203
+ const hostCapacity = brokered
204
+ ? new SandboxHostCapacityBroker(this.hostLoadGate, runtimeDispatch.sandbox.dispatchAttemptId, runtimeAdmissionPriority(runtimeDispatch), async (response) => void await requireSandboxProcess({
205
+ command: this.config.dockerExecutable,
206
+ // As root, into the root-owned reply mount the sandbox user cannot write.
207
+ args: this.dockerArgs(sandboxHostCapacityDeliveryExecArgs(containerId)),
208
+ input: `${JSON.stringify(response)}\n`,
209
+ timeoutMs: 10_000,
210
+ maxOutputBytes: 16 * 1024,
211
+ }), { stepProcess: async () => await this.containerInitProcess(containerId) })
212
+ : null;
186
213
  const startPromise = runSandboxProcess({
187
214
  command: this.config.dockerExecutable,
188
215
  args: this.dockerArgs(["start", "--attach", "--interactive", containerId]),
@@ -198,6 +225,8 @@ export class DockerSandboxRuntime {
198
225
  signal: runtimeSignal,
199
226
  onStdoutLine: async (line) => {
200
227
  eventBudget.accept(line);
228
+ if (hostCapacity?.handleLine(line))
229
+ return;
201
230
  const streamedEvent = parseSandboxEventLine(line);
202
231
  if (streamedEvent) {
203
232
  if (streamedEvent.eventType === "provider_cli_started")
@@ -207,7 +236,14 @@ export class DockerSandboxRuntime {
207
236
  }
208
237
  });
209
238
  const memorySampler = this.startPeakMemorySampler(runtimeContainers);
239
+ // The sandbox's CPU is Forge's own work, not external load, for the governor.
240
+ const untrackCgroups = brokered
241
+ ? trackSandboxCgroups(this.forgeCgroups, runtimeDispatch.sandbox.dispatchAttemptId, runtimeContainers.map(container => container.id), async (ids) => (await this.docker(["inspect", "--format", "{{.State.Pid}}", ...ids], 10_000)).stdout)
242
+ : null;
210
243
  const start = await startPromise.finally(async () => {
244
+ // The worker exited: its queued and admitted host load tokens go back to the budget.
245
+ untrackCgroups?.();
246
+ await hostCapacity?.close();
211
247
  const telemetry = await memorySampler.stop();
212
248
  if (!telemetry)
213
249
  return;
@@ -1105,6 +1141,13 @@ export class DockerSandboxRuntime {
1105
1141
  docker(args, timeoutMs, signal, maxOutputBytes = 1024 * 1024) {
1106
1142
  return requireSandboxProcess({ command: this.config.dockerExecutable, args: this.dockerArgs(args), timeoutMs, maxOutputBytes, signal });
1107
1143
  }
1144
+ /** The container's init process: stopping it stops every process in the sandbox. */
1145
+ async containerInitProcess(containerId) {
1146
+ const pid = Number((await this.docker(["inspect", "--format", "{{.State.Pid}}", containerId], 10_000)).stdout.trim());
1147
+ return Number.isSafeInteger(pid) && pid > 1
1148
+ ? { rootPid: pid, rootIdentity: captureHostProcessIdentity(pid), processGroup: false }
1149
+ : null;
1150
+ }
1108
1151
  dockerArgs(args) { return this.config.dockerContext ? ["--context", this.config.dockerContext, ...args] : [...args]; }
1109
1152
  }
1110
1153
  class HostGit {
@@ -0,0 +1,14 @@
1
+ import type { ForgeCgroupWriter } from "../runtime/host-load-forge-cgroups.js";
2
+ export type DockerInspectPids = (containerIds: readonly string[]) => Promise<string>;
3
+ /** Cgroup paths of the given containers' init processes; containers not yet running are skipped. */
4
+ export declare function sandboxContainerCgroupPaths(inspectPids: DockerInspectPids, containerIds: readonly string[], procRoot?: string): Promise<readonly string[]>;
5
+ /**
6
+ * Registers a sandbox's container cgroups once its containers are running,
7
+ * retrying briefly while the agent container starts. Returns a function that
8
+ * stops the retries and removes the registration.
9
+ */
10
+ export declare function trackSandboxCgroups(registry: ForgeCgroupWriter, owner: string, containerIds: readonly string[], inspectPids: DockerInspectPids, options?: {
11
+ readonly attempts?: number;
12
+ readonly intervalMs?: number;
13
+ readonly procRoot?: string;
14
+ }): () => void;
@@ -0,0 +1,42 @@
1
+ import fs from "node:fs/promises";
2
+ import { parseUnifiedCgroupPath } from "../runtime/host-pressure-stall.js";
3
+ /** Cgroup paths of the given containers' init processes; containers not yet running are skipped. */
4
+ export async function sandboxContainerCgroupPaths(inspectPids, containerIds, procRoot = "/proc") {
5
+ const output = await inspectPids(containerIds);
6
+ const paths = [];
7
+ for (const line of output.split(/\r?\n/u)) {
8
+ const pid = Number(line.trim());
9
+ if (!Number.isSafeInteger(pid) || pid <= 1)
10
+ continue;
11
+ const membership = await fs.readFile(`${procRoot}/${pid}/cgroup`, "utf8").catch(() => null);
12
+ const cgroupPath = membership ? parseUnifiedCgroupPath(membership) : null;
13
+ if (cgroupPath)
14
+ paths.push(cgroupPath);
15
+ }
16
+ return paths;
17
+ }
18
+ /**
19
+ * Registers a sandbox's container cgroups once its containers are running,
20
+ * retrying briefly while the agent container starts. Returns a function that
21
+ * stops the retries and removes the registration.
22
+ */
23
+ export function trackSandboxCgroups(registry, owner, containerIds, inspectPids, options = {}) {
24
+ let stopped = false;
25
+ void (async () => {
26
+ for (let attempt = 0; attempt < (options.attempts ?? 10) && !stopped; attempt += 1) {
27
+ await new Promise(resolve => setTimeout(resolve, options.intervalMs ?? 1_000));
28
+ if (stopped)
29
+ return;
30
+ const paths = await sandboxContainerCgroupPaths(inspectPids, containerIds, options.procRoot).catch(() => []);
31
+ if (stopped)
32
+ return;
33
+ registry.set(owner, paths);
34
+ if (paths.length >= containerIds.length)
35
+ return;
36
+ }
37
+ })();
38
+ return () => {
39
+ stopped = true;
40
+ registry.delete(owner);
41
+ };
42
+ }
@@ -9,6 +9,11 @@ import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-c
9
9
  import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
10
10
  import { redactText } from "../shared/redaction/redaction.js";
11
11
  import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
12
+ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
13
+ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
14
+ import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
15
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
16
+ import { hostLoadGovernorEnvironment, hostLoadStateRootEnvironment } from "../runtime/host-load-child-environment.js";
12
17
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
13
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
14
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
@@ -488,15 +493,66 @@ function optionValue(args, name) {
488
493
  const index = args.indexOf(name);
489
494
  return index >= 0 ? args[index + 1]?.trim() || null : null;
490
495
  }
496
+ function hostCapacityLossReason(reason) {
497
+ if (reason instanceof HostCapacityTokenFencedError)
498
+ return "host_capacity_token_fenced";
499
+ if (reason instanceof HostCapacityLedgerUnavailableError)
500
+ return "host_capacity_ledger_unavailable";
501
+ return null;
502
+ }
491
503
  async function executeManagedCommand(invocation) {
492
- if (!invocation.buildProducing)
493
- return await executeManagedCommandProcess(invocation);
494
504
  let processStarted = false;
505
+ // The per-worktree build slot is taken first: holding a host token while
506
+ // queued behind this worktree's own build would waste host capacity.
507
+ const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
508
+ ...invocation,
509
+ hostLoad,
510
+ timedOut: false,
511
+ status: "waiting_for_host_capacity",
512
+ exitCode: null,
513
+ stdout: "",
514
+ stderr: "",
515
+ launchRequested: false,
516
+ }).structuredContent));
517
+ const launch = async (buildQueueWaitMs) => await hostCapacity.run(invocation.controller.signal, async (hostLoad, control) => {
518
+ processStarted = true;
519
+ // A reclaimed token means this command's capacity is gone: it stops. A fence that
520
+ // landed between admission and here stops it too (a listener added now never fires).
521
+ const stopOnFence = () => invocation.controller.abort(control.fenced.reason);
522
+ if (control.fenced?.aborted)
523
+ stopOnFence();
524
+ else
525
+ control.fenced?.addEventListener("abort", stopOnFence, { once: true });
526
+ try {
527
+ return await executeManagedCommandProcess({
528
+ ...invocation,
529
+ buildQueueWaitMs,
530
+ hostLoad,
531
+ // Recording the tree is part of holding the token: if it fails (the token was
532
+ // fenced meanwhile, or the ledger refused), the command stops instead of
533
+ // running on without a reservation the host can account for.
534
+ // Checked against the tree recorded on the token at launch (null: the governor's own).
535
+ holdHostCapacityUntilStopped: reason => control.holdUntilStopped?.(null, reason),
536
+ onProcessStarted: async () => await attachManagedCommandProcess(control, invocation.metadataPath)
537
+ .catch((error) => {
538
+ invocation.controller.abort(error instanceof HostCapacityTokenFencedError || error instanceof HostCapacityLedgerUnavailableError
539
+ ? error
540
+ : new HostCapacityLedgerUnavailableError(`the managed command's process tree could not be recorded on its host load token: ${error instanceof Error ? error.message : String(error)}`, { cause: error }));
541
+ }),
542
+ });
543
+ }
544
+ finally {
545
+ control.fenced?.removeEventListener("abort", stopOnFence);
546
+ }
547
+ },
548
+ // A fenced release is already the receipt's termination reason; only a ledger fault is noted.
549
+ async (error) => error instanceof HostCapacityTokenFencedError ? undefined : await annotateManagedCommandReceipt(invocation.receiptPath, {
550
+ host_capacity_release_error: redactText(error instanceof Error ? error.message : String(error), []),
551
+ }));
495
552
  try {
496
- return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, async (buildQueueWaitMs) => {
497
- processStarted = true;
498
- return await executeManagedCommandProcess({ ...invocation, buildQueueWaitMs });
499
- }, async () => {
553
+ if (!invocation.buildProducing)
554
+ return await launch();
555
+ return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, launch, async () => {
500
556
  const waiting = managedCommandResult({
501
557
  ...invocation,
502
558
  timedOut: false,
@@ -512,11 +568,12 @@ async function executeManagedCommand(invocation) {
512
568
  catch (error) {
513
569
  if (processStarted)
514
570
  throw error;
515
- // The command never started (its build-slot wait failed or was stopped). Its receipt
516
- // must still become terminal, or a waiting agent sees it queued forever.
571
+ // The command never started (its build-slot or host-capacity wait failed or was
572
+ // stopped). Its receipt must still become terminal, or a waiting agent sees it queued forever.
517
573
  const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
518
574
  const receipt = managedCommandResult({
519
575
  ...invocation,
576
+ hostLoad: await hostCapacity.unadmittedFields(error),
520
577
  timedOut: false,
521
578
  status: "runner_error",
522
579
  exitCode: null,
@@ -642,6 +699,8 @@ async function executeManagedCommandProcess(invocation) {
642
699
  }, {
643
700
  onStarted: async () => {
644
701
  clearTimeout(launchTimer);
702
+ // onProcessStarted stops the command itself when its token cannot be held.
703
+ await invocation.onProcessStarted?.();
645
704
  const running = managedCommandResult({
646
705
  ...invocation,
647
706
  timedOut: false,
@@ -688,13 +747,17 @@ async function executeManagedCommandProcess(invocation) {
688
747
  // Only a stop that interrupted the process relabels it. A command that exited on its own
689
748
  // just before its owner asked for the stop keeps its real result.
690
749
  const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
691
- if (ownerExited) {
692
- stderr = appendBounded(stderr, managedCommandOwnerExitMessage);
750
+ const hostCapacityLoss = !timedOut && !ownerExited && result.cancelled === true
751
+ ? hostCapacityLossReason(controller.signal.reason)
752
+ : null;
753
+ const fenced = hostCapacityLoss !== null;
754
+ if (ownerExited || fenced) {
755
+ stderr = appendBounded(stderr, ownerExited ? managedCommandOwnerExitMessage : controller.signal.reason.message);
693
756
  outputRevision += 1;
694
757
  lastOutputAt = Date.now();
695
758
  lastOutputStream = "stderr";
696
759
  }
697
- const status = timedOut ? "timed_out" : ownerExited ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
760
+ const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
698
761
  const receiptCoverage = managedBuildReceiptCoverage(invocation);
699
762
  const buildReceipt = status === "pass" && receiptCoverage
700
763
  ? await publishManagedBuildReceipt({
@@ -717,9 +780,9 @@ async function executeManagedCommandProcess(invocation) {
717
780
  lastOutputStream,
718
781
  buildReceipt,
719
782
  buildReceiptReused: invocation.buildReceiptReuse !== undefined,
720
- terminationReason: ownerExited ? "owner_exited" : undefined,
783
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
721
784
  // The runner resolves only after the stopped tree is proven gone.
722
- processTreeTerminated: ownerExited ? true : undefined,
785
+ processTreeTerminated: ownerExited || fenced ? true : undefined,
723
786
  });
724
787
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
725
788
  return managedCommandPublicResult(receipt);
@@ -745,11 +808,17 @@ async function executeManagedCommandProcess(invocation) {
745
808
  outputRevision,
746
809
  lastOutputAt,
747
810
  lastOutputStream,
748
- terminationReason: ownerExited ? "owner_exited" : undefined,
811
+ // A host capacity loss before launch (a fence that landed while it was admitted) is named too.
812
+ terminationReason: ownerExited ? "owner_exited" : hostCapacityLossReason(controller.signal.reason) ?? undefined,
749
813
  // The runner rejected, so its tree was not proven stopped; teardown still stops it.
750
814
  processTreeTerminated: false,
751
815
  });
752
816
  await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
817
+ // The runner stops the tree before it rejects; only a failed termination proof means
818
+ // part of it may still run. Its token is then kept, never returned with this receipt.
819
+ if (isProcessTreeTerminationUnproven(error)) {
820
+ invocation.holdHostCapacityUntilStopped?.(error instanceof Error ? error : new Error(String(error)));
821
+ }
753
822
  return managedCommandPublicResult(receipt);
754
823
  }
755
824
  finally {
@@ -773,6 +842,11 @@ async function readManagedCommand(input) {
773
842
  }
774
843
  throw error;
775
844
  }
845
+ // A queued receipt is written once; its wait so far is computed when it is read.
846
+ const hostLoadWaitStartedAt = Date.parse(String(receipt.host_load_wait_started_at));
847
+ if (receipt.status === "waiting_for_host_capacity" && Number.isFinite(hostLoadWaitStartedAt)) {
848
+ receipt = { ...receipt, host_load_wait_ms: Math.max(0, Date.now() - hostLoadWaitStartedAt) };
849
+ }
776
850
  const status = typeof receipt.status === "string" ? receipt.status : "unknown";
777
851
  const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
778
852
  const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
@@ -823,15 +897,18 @@ async function waitManagedCommand(input) {
823
897
  const elapsedMs = receipt.structuredContent.elapsed_ms;
824
898
  const timeoutMs = receipt.structuredContent.timeout_ms;
825
899
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
826
- const progress = receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
827
- ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
828
- + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
829
- + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
830
- // Agents otherwise abandon long verification tiers and record a blocker that is not one.
831
- + (typeof timeoutMs === "number"
832
- ? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
833
- : "")
834
- : "";
900
+ const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
901
+ const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
902
+ ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
903
+ : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
904
+ ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
905
+ + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
906
+ + `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
907
+ // Agents otherwise abandon long verification tiers and record a blocker that is not one.
908
+ + (typeof timeoutMs === "number"
909
+ ? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
910
+ : "")
911
+ : "";
835
912
  return {
836
913
  ...receipt,
837
914
  content: [{
@@ -876,7 +953,9 @@ async function persistManagedCommandReceipt(receiptPath, receipt) {
876
953
  }
877
954
  }
878
955
  function managedCommandResult(values) {
879
- const elapsedMs = Date.now() - values.startedAt;
956
+ // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
957
+ const hostLoad = values.hostLoad;
958
+ const elapsedMs = Date.now() - (hostLoad ? hostLoad.executionStartedAt ?? Date.now() : values.startedAt);
880
959
  const isTerminal = terminalManagedCommandStatuses.has(values.status);
881
960
  const diagnostics = isTerminal
882
961
  ? managedCommandDiagnostics(values.stdout, values.stderr)
@@ -921,6 +1000,7 @@ function managedCommandResult(values) {
921
1000
  build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
922
1001
  build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
923
1002
  build_receipt_reused: values.buildReceiptReused ?? false,
1003
+ ...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
924
1004
  build_receipt: values.buildReceipt ? {
925
1005
  fingerprint: values.buildReceipt.fingerprint,
926
1006
  receipt_path: values.buildReceipt.receiptPath,
@@ -940,6 +1020,18 @@ function managedCommandResult(values) {
940
1020
  isError: isTerminal && values.status !== "pass",
941
1021
  };
942
1022
  }
1023
+ function managedCommandHostLoadReceipt(hostLoad) {
1024
+ const waiting = hostLoad.waitStartedAt !== undefined;
1025
+ return {
1026
+ host_load_step_class: hostLoad.stepClass,
1027
+ host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1028
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString() } : {}),
1029
+ };
1030
+ }
1031
+ async function annotateManagedCommandReceipt(receiptPath, fields) {
1032
+ const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
1033
+ await persistManagedCommandReceipt(receiptPath, { ...receipt, ...fields });
1034
+ }
943
1035
  /** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
944
1036
  function managedCommandOwnerIdentity() {
945
1037
  // Windows identity capture starts PowerShell; the PID check alone is used there.
@@ -1016,6 +1108,10 @@ async function containedWorkingDirectory(worktreePath, input) {
1016
1108
  function inheritedEnvironment(overrides) {
1017
1109
  const env = {};
1018
1110
  for (const [key, value] of Object.entries(process.env)) {
1111
+ // A nested Forge process must not join the host ledger: it would queue behind the
1112
+ // token this command already holds.
1113
+ if (key === hostLoadGovernorEnvironment || key === hostLoadStateRootEnvironment)
1114
+ continue;
1019
1115
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
1020
1116
  env[key] = value;
1021
1117
  }
@@ -0,0 +1,45 @@
1
+ import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import { type HostLoadStepClassification, type ManagedCommandStepInput } from "../runtime/host-load-step-class.js";
3
+ import { type HostLoadStepControl } from "../runtime/host-load-step-run.js";
4
+ /** Host-load facts a managed command receipt carries; absent while the governor is off. */
5
+ export interface ManagedCommandHostLoadFields {
6
+ readonly stepClass: string;
7
+ /** Queue time before admission; never part of elapsed_ms. */
8
+ readonly waitMs: number;
9
+ /** Set while the command is still queued: the receipt reports the wait so far. */
10
+ readonly waitStartedAt?: number;
11
+ /** When the command was admitted; elapsed_ms counts from here. */
12
+ readonly executionStartedAt?: number;
13
+ }
14
+ /** This MCP server's governor, built once from the environment the bridge handed it. */
15
+ export declare function managedCommandHostLoadGate(): HostLoadStepGate | undefined;
16
+ /** Test support: installs a gate (undefined disables it; null rebuilds from the environment). */
17
+ export declare function setManagedCommandHostLoadGateForTesting(value: HostLoadStepGate | undefined | null): void;
18
+ /**
19
+ * Admits one managed command. The waiting receipt is written while the command
20
+ * is queued and always lands before the launch receipts, so a stale "waiting"
21
+ * write can never replace a later status.
22
+ */
23
+ export declare class ManagedCommandHostCapacity {
24
+ private readonly persistWaiting;
25
+ private readonly gateFor;
26
+ readonly classification: HostLoadStepClassification;
27
+ private readonly label;
28
+ private requestedAtMs;
29
+ private waitingWrite;
30
+ constructor(input: ManagedCommandStepInput & {
31
+ readonly label: string;
32
+ }, persistWaiting: (fields: ManagedCommandHostLoadFields) => Promise<void>, gateFor?: () => HostLoadStepGate | undefined);
33
+ /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
34
+ run<T>(signal: AbortSignal, launch: (fields: ManagedCommandHostLoadFields | undefined, control: HostLoadStepControl) => Promise<T>, onReleaseFailed?: (error: unknown) => Promise<void>): Promise<T>;
35
+ /**
36
+ * Host-load facts for a command that was never admitted (it timed out in
37
+ * the queue or was stopped while waiting), once its waiting receipt landed.
38
+ */
39
+ unadmittedFields(error: unknown): Promise<ManagedCommandHostLoadFields | undefined>;
40
+ }
41
+ /**
42
+ * The managed command's process tree as its supervisor recorded it, for its
43
+ * host load token: a reclaim then stops exactly this tree before reuse.
44
+ */
45
+ export declare function attachManagedCommandProcess(control: HostLoadStepControl, metadataPath: string): Promise<void>;
@@ -0,0 +1,82 @@
1
+ import { hostLoadGovernorFromChildEnvironment } from "../runtime/host-load-child-environment.js";
2
+ import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
+ import { classifyManagedCommand } from "../runtime/host-load-step-class.js";
4
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "../runtime/host-load-step-run.js";
5
+ let gate = null;
6
+ /** This MCP server's governor, built once from the environment the bridge handed it. */
7
+ export function managedCommandHostLoadGate() {
8
+ if (gate === null)
9
+ gate = hostLoadGovernorFromChildEnvironment();
10
+ return gate;
11
+ }
12
+ /** Test support: installs a gate (undefined disables it; null rebuilds from the environment). */
13
+ export function setManagedCommandHostLoadGateForTesting(value) {
14
+ gate = value;
15
+ }
16
+ /**
17
+ * Admits one managed command. The waiting receipt is written while the command
18
+ * is queued and always lands before the launch receipts, so a stale "waiting"
19
+ * write can never replace a later status.
20
+ */
21
+ export class ManagedCommandHostCapacity {
22
+ persistWaiting;
23
+ gateFor;
24
+ classification;
25
+ label;
26
+ requestedAtMs = null;
27
+ waitingWrite = Promise.resolve();
28
+ constructor(input, persistWaiting, gateFor = managedCommandHostLoadGate) {
29
+ this.persistWaiting = persistWaiting;
30
+ this.gateFor = gateFor;
31
+ this.classification = classifyManagedCommand(input);
32
+ this.label = input.label;
33
+ }
34
+ /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
35
+ async run(signal, launch, onReleaseFailed) {
36
+ const current = this.gateFor();
37
+ if (current?.enabled)
38
+ this.requestedAtMs = Date.now();
39
+ return await runHostGovernedStep(current, {
40
+ classification: this.classification,
41
+ label: this.label,
42
+ dispatchAttemptId: process.env.FORGE_DISPATCH_ATTEMPT_ID?.trim() || null,
43
+ // An agent waits on its managed commands; readiness probes never start one.
44
+ priority: "foreground",
45
+ signal,
46
+ // The receipt says host_capacity_token_fenced itself (termination_reason).
47
+ reportsOwnFence: true,
48
+ onWaiting: () => {
49
+ this.waitingWrite = this.persistWaiting({
50
+ stepClass: this.classification.stepClass,
51
+ waitMs: 0,
52
+ waitStartedAt: this.requestedAtMs ?? Date.now(),
53
+ }).catch(() => undefined);
54
+ },
55
+ onReleaseFailed,
56
+ }, async (waitMs, control) => {
57
+ await this.waitingWrite;
58
+ // The launch timer and timeout_ms start inside `launch`, after admission.
59
+ return await launch(waitMs === null
60
+ ? undefined
61
+ : { stepClass: this.classification.stepClass, waitMs, executionStartedAt: Date.now() }, control);
62
+ });
63
+ }
64
+ /**
65
+ * Host-load facts for a command that was never admitted (it timed out in
66
+ * the queue or was stopped while waiting), once its waiting receipt landed.
67
+ */
68
+ async unadmittedFields(error) {
69
+ await this.waitingWrite;
70
+ if (this.requestedAtMs === null)
71
+ return undefined;
72
+ const waitMs = error instanceof HostCapacityTimeoutError ? error.waitMs : Date.now() - this.requestedAtMs;
73
+ return { stepClass: this.classification.stepClass, waitMs: Math.round(waitMs), executionStartedAt: Date.now() };
74
+ }
75
+ }
76
+ /**
77
+ * The managed command's process tree as its supervisor recorded it, for its
78
+ * host load token: a reclaim then stops exactly this tree before reuse.
79
+ */
80
+ export async function attachManagedCommandProcess(control, metadataPath) {
81
+ await attachSupervisedStepProcess(control, metadataPath);
82
+ }
@@ -29,6 +29,8 @@ export interface CompletionToolRuntimeOptions {
29
29
  readonly worktree: WorktreeHandle;
30
30
  readonly phase?: CompletionPhase;
31
31
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
32
+ /** Host load governor variables; only the MCP server receives them. */
33
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
32
34
  }
33
35
  export interface CompletionToolServerConfig {
34
36
  readonly worktreePath: string;
@@ -28,7 +28,7 @@ export declare class CompletionToolServerSession {
28
28
  private advanceAfterQaGate;
29
29
  private advanceAfterDebugGate;
30
30
  }
31
- export declare function completionToolRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>, nativeTestPostgresFallbackPath?: string | null): Readonly<Record<string, string>>;
31
+ export declare function completionToolRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>, nativeTestPostgresFallbackPath?: string | null, hostLoadEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
32
32
  /**
33
33
  * A solution-wide Forge test is long enough that a generic provider shell can
34
34
  * expire while VSTest is still healthy. On managed host attempts, only the
@@ -6,6 +6,7 @@ import { completionPhaseFromDispatch, completionPhaseOrder, completionRedactionS
6
6
  import { CompletionPayloadValidationError, asDebugCompletionPhase, asJsonRpcMessage, asMutableRecord, asRecord, artifactOwnerRelativeRoot, decomposeGateFromToolName, draftGateFromToolName, errorMessage, forgeBridgeCliBinPath, isDebugCompletionPhase, isDecomposeDispatch, isDevelopCompletionPhase, normalizedOwnerType, parseCompletionRedactionSecrets, parseOptionalJsonObject, parseStrictCompletionPhase, phaseFromToolName, qaGateFromToolName, requiredString, rpcError, tomlString, tomlStringArray, writeFileAtomic, writeJsonRpc } from "./phase-completion.validation.js";
7
7
  import { completionPromptForDebugCycle, completionPromptForDecomposeCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionToolNextInstruction, completionToolNextInstructionForDebugGate, completionToolNextInstructionForDecomposeGate, completionToolNextInstructionForDraftGate, completionToolNextInstructionForQaGate, nextDebugPhaseAfter, nextPhaseAfter } from "./phase-completion.prompts.js";
8
8
  import { configuredNativeTestPostgresFallbackPath, nativeTestPostgresFallbackConfigEnvironment, } from "../runtime/native-test-postgres-fallback.js";
9
+ import { isHostLoadChildEnvironmentName } from "../runtime/host-load-child-environment.js";
9
10
  import { toolDescription, toolInputSchema } from "./phase-completion.schemas.js";
10
11
  import { writeCompletionArtifact, writeDecomposeGateCompletionArtifact, writeDraftGateCompletionArtifact } from "./phase-completion.artifacts.js";
11
12
  import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, runWithOwnerShutdown, } from "./managed-attempt-tools.js";
@@ -36,7 +37,7 @@ export async function prepareCompletionToolRuntime(options) {
36
37
  serverName: toolServerName,
37
38
  command: process.execPath,
38
39
  args: [forgeBridgeCliBinPath(), ...mcpArgs],
39
- env: completionToolRuntimeEnvironment(options.runtimeEnvironment, configuredNativeTestPostgresFallbackPath()),
40
+ env: completionToolRuntimeEnvironment(options.runtimeEnvironment, configuredNativeTestPostgresFallbackPath(), options.hostLoadEnvironment),
40
41
  cleanup: async () => undefined
41
42
  };
42
43
  const provider = options.dispatch.execution.provider.trim().toLowerCase();
@@ -458,18 +459,25 @@ const completionToolRuntimeEnvironmentNames = [
458
459
  "TMP",
459
460
  "TEMP",
460
461
  ];
461
- export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestPostgresFallbackPath) {
462
- if (!runtimeEnvironment)
463
- return {};
462
+ export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestPostgresFallbackPath, hostLoadEnvironment) {
464
463
  const env = {};
464
+ // Without a runtime environment the server gets nothing from it, but it still
465
+ // joins the host ledger when the bridge handed it the governor's variables.
466
+ if (!runtimeEnvironment && !hostLoadEnvironment)
467
+ return env;
465
468
  for (const name of completionToolRuntimeEnvironmentNames) {
466
- const value = runtimeEnvironment[name]?.trim();
469
+ const value = runtimeEnvironment?.[name]?.trim();
467
470
  if (value)
468
471
  env[name] = value;
469
472
  }
473
+ // The host load governor's flag, state root and tuning: managed commands join its ledger.
474
+ for (const [name, value] of Object.entries(hostLoadEnvironment ?? {})) {
475
+ if (isHostLoadChildEnvironmentName(name) && value.trim())
476
+ env[name] = value.trim();
477
+ }
470
478
  // Managed verification reads the operator's native test cluster only through
471
479
  // this explicit path, and only while Docker is unavailable.
472
- if (nativeTestPostgresFallbackPath) {
480
+ if (runtimeEnvironment && nativeTestPostgresFallbackPath) {
473
481
  env[nativeTestPostgresFallbackConfigEnvironment] = nativeTestPostgresFallbackPath;
474
482
  }
475
483
  return env;