@loucompanion/forge-bridge 0.1.4-dev.c2f22d1dd395 → 0.1.4-dev.e1b4f55fb18d

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 (122) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +2 -0
  3. package/dist/bridge/bridge.service.js +30 -5
  4. package/dist/bridge/bridge.types.d.ts +5 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cleanup/cleanup.service.d.ts +9 -0
  10. package/dist/cleanup/cleanup.service.js +57 -100
  11. package/dist/cleanup/cleanup.types.d.ts +4 -0
  12. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  13. package/dist/cleanup/host-runtime-ledger.js +109 -0
  14. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  15. package/dist/cleanup/managed-branch-sweep.js +111 -0
  16. package/dist/cli/cli.service.js +10 -2
  17. package/dist/runtime/host-load-admission.d.ts +52 -0
  18. package/dist/runtime/host-load-admission.js +84 -0
  19. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  20. package/dist/runtime/host-load-child-environment.js +65 -0
  21. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  22. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  23. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  24. package/dist/runtime/host-load-governor-config.js +46 -0
  25. package/dist/runtime/host-load-governor.d.ts +172 -0
  26. package/dist/runtime/host-load-governor.js +519 -0
  27. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  28. package/dist/runtime/host-load-ledger-lock.js +185 -0
  29. package/dist/runtime/host-load-sampler.d.ts +43 -0
  30. package/dist/runtime/host-load-sampler.js +74 -6
  31. package/dist/runtime/host-load-step-class.d.ts +68 -0
  32. package/dist/runtime/host-load-step-class.js +106 -0
  33. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  34. package/dist/runtime/host-load-step-reaper.js +95 -0
  35. package/dist/runtime/host-load-step-run.d.ts +73 -0
  36. package/dist/runtime/host-load-step-run.js +102 -0
  37. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  38. package/dist/runtime/host-load-token-ledger.js +421 -0
  39. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  40. package/dist/runtime/host-pressure-stall.js +48 -1
  41. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  42. package/dist/runtime/host-runtime-contract.js +4 -1
  43. package/dist/runtime/host-runtime-lease.d.ts +17 -3
  44. package/dist/runtime/host-runtime-lease.js +83 -4
  45. package/dist/runtime/host-runtime-promotion.js +12 -0
  46. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  47. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  48. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  49. package/dist/runtime/host-runtime-requirements.js +117 -0
  50. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  51. package/dist/sandbox/host-capacity-broker.js +315 -0
  52. package/dist/sandbox/runtime.d.ts +10 -1
  53. package/dist/sandbox/runtime.js +45 -2
  54. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  55. package/dist/sandbox/sandbox-cgroups.js +42 -0
  56. package/dist/session/managed-attempt-tools.d.ts +2 -0
  57. package/dist/session/managed-attempt-tools.js +156 -37
  58. package/dist/session/managed-command-host-load.d.ts +45 -0
  59. package/dist/session/managed-command-host-load.js +82 -0
  60. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  61. package/dist/session/mcp-argument-coercion.js +121 -0
  62. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  63. package/dist/session/phase-completion.artifacts.js +94 -25
  64. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  65. package/dist/session/phase-completion.command-validation.js +77 -0
  66. package/dist/session/phase-completion.d.ts +4 -0
  67. package/dist/session/phase-completion.helpers.js +13 -12
  68. package/dist/session/phase-completion.js +4 -0
  69. package/dist/session/phase-completion.prompts.js +6 -1
  70. package/dist/session/phase-completion.runtime.d.ts +5 -3
  71. package/dist/session/phase-completion.runtime.js +49 -19
  72. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  73. package/dist/session/phase-completion.schema-parts.js +188 -0
  74. package/dist/session/phase-completion.schemas.d.ts +3 -3
  75. package/dist/session/phase-completion.schemas.js +184 -209
  76. package/dist/session/phase-completion.validation.d.ts +2 -3
  77. package/dist/session/phase-completion.validation.js +46 -92
  78. package/dist/session/pre-publication-host-load.d.ts +27 -0
  79. package/dist/session/pre-publication-host-load.js +111 -0
  80. package/dist/session/pre-publication-process.d.ts +3 -0
  81. package/dist/session/pre-publication-process.js +23 -11
  82. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  83. package/dist/session/pre-publication-step-execution.js +49 -0
  84. package/dist/session/pre-publication-validation.d.ts +9 -9
  85. package/dist/session/pre-publication-validation.js +21 -55
  86. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  87. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  88. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  89. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  90. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  91. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  92. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  93. package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
  94. package/dist/session/provider-cli/provider-cli.service.js +80 -23
  95. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  96. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  97. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  98. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  99. package/dist/session/provider-cli/provider-output-state.js +9 -0
  100. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  101. package/dist/session/publishable-worktree-changes.js +21 -5
  102. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  103. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  104. package/dist/session/session.base.d.ts +3 -0
  105. package/dist/session/session.service.d.ts +2 -0
  106. package/dist/session/session.service.js +21 -4
  107. package/dist/session/session.types.d.ts +3 -0
  108. package/dist/session/session.types.js +11 -2
  109. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  110. package/dist/shared/process/host-process-supervisor.js +1 -1
  111. package/dist/shared/process/process-tree.d.ts +52 -0
  112. package/dist/shared/process/process-tree.js +144 -0
  113. package/dist/shared/process/process.d.ts +67 -0
  114. package/dist/shared/process/process.js +213 -11
  115. package/dist/version.d.ts +1 -1
  116. package/dist/version.js +1 -1
  117. package/dist/worktree/dependency-warmer.d.ts +25 -0
  118. package/dist/worktree/dependency-warmer.js +46 -10
  119. package/dist/worktree/worktree.service.d.ts +10 -1
  120. package/dist/worktree/worktree.service.js +42 -2
  121. package/dist/worktree/worktree.types.d.ts +7 -0
  122. package/package.json +1 -1
@@ -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
+ }
@@ -1,3 +1,4 @@
1
+ import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
1
2
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket, RunnerDispatchEvent } from "./session.types.js";
2
3
  import type { HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
3
4
  export interface SessionEventSink {
@@ -9,4 +10,6 @@ export interface SessionService {
9
10
  reapHostRuntime?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport | null>;
10
11
  runtimeCapacity?(): HostRuntimeCapacitySnapshot | null;
11
12
  probeHostRuntime?(request: HostRuntimeReadinessProbeRequest, signal?: AbortSignal): Promise<HostRuntimeReadinessProbeResult>;
13
+ /** Decision 0013: host attempts recheck the project's requirements before starting. */
14
+ setHostRequirementsCheck?(check: HostRequirementsCheck | null): void;
12
15
  }
@@ -1,3 +1,4 @@
1
+ import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
1
2
  import type { ProviderCliService } from "./provider-cli/provider-cli.base.js";
2
3
  import type { SessionEventSink, SessionService } from "./session.base.js";
3
4
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket } from "./session.types.js";
@@ -8,6 +9,7 @@ export declare class BridgeSessionService implements SessionService {
8
9
  private readonly providerCli;
9
10
  private readonly hostRuntime?;
10
11
  constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined);
12
+ setHostRequirementsCheck(check: HostRequirementsCheck | null): void;
11
13
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
12
14
  reapHostRuntime(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport | null>;
13
15
  runtimeCapacity(): HostRuntimeCapacitySnapshot | null;
@@ -4,7 +4,7 @@ import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.j
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
5
  import { GitWorktreeService } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
- import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, } from "../runtime/host-runtime-lease.js";
7
+ import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
9
  const minimumReadinessProbeStartupBudgetMs = 150_000;
10
10
  export class BridgeSessionService {
@@ -18,6 +18,9 @@ export class BridgeSessionService {
18
18
  this.providerCli = providerCli;
19
19
  this.hostRuntime = hostRuntime;
20
20
  }
21
+ setHostRequirementsCheck(check) {
22
+ this.hostRuntime?.setRequirementsCheck?.(check);
23
+ }
21
24
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
22
25
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
23
26
  }
@@ -61,6 +64,8 @@ export class BridgeSessionService {
61
64
  // failed agent worktrees for inspection.
62
65
  cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
63
66
  artifacts: [],
67
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: "background" },
68
+ signal,
64
69
  });
65
70
  assertReadinessProbeStartupBudget(request.expiresAt);
66
71
  let started = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal);
@@ -71,6 +76,7 @@ export class BridgeSessionService {
71
76
  status: "serialized",
72
77
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
73
78
  runtimeContractSource: started.runtimeContract.source,
79
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
74
80
  reasonCode: discovery?.reasonCode ?? "host_runtime_contract_serialized",
75
81
  reasonMessage: discovery?.summary ?? "The detected runtime requires serialized host execution.",
76
82
  checkedAt: new Date().toISOString(),
@@ -87,6 +93,7 @@ export class BridgeSessionService {
87
93
  status: "parallel_ready",
88
94
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
89
95
  runtimeContractSource: started.runtimeContract.source,
96
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
90
97
  reasonCode: null,
91
98
  reasonMessage: null,
92
99
  qaAppLaunchTarget: managedQaLaunchTarget(started.runtimeContract),
@@ -248,7 +255,12 @@ export class BridgeSessionService {
248
255
  qaRework: dispatch.qaRework,
249
256
  warmPathOverrides: dispatch.warmPathOverrides,
250
257
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
251
- preserveExistingState: Boolean(dispatch.session.resumedFromSessionId)
258
+ preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
259
+ hostLoadOwner: {
260
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
261
+ priority: runtimeAdmissionPriority(dispatch),
262
+ },
263
+ signal,
252
264
  });
253
265
  }
254
266
  catch (error) {
@@ -327,6 +339,11 @@ export class BridgeSessionService {
327
339
  }
328
340
  }
329
341
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
342
+ const providerEnvironment = {
343
+ runtimeEnvironment: hostLease?.environment,
344
+ // Only the completion MCP server gets these: its managed commands share the host ledger.
345
+ hostLoadEnvironment: hostLease ? this.hostRuntime?.hostLoadChildEnvironment?.() : undefined,
346
+ };
330
347
  if (dispatch.draft) {
331
348
  throwIfAborted(signal);
332
349
  const processRunner = hostLease && dispatch.sandbox
@@ -335,7 +352,7 @@ export class BridgeSessionService {
335
352
  const run = await this.providerCli.runDraft({
336
353
  dispatch: providerDispatch,
337
354
  worktree,
338
- runtimeEnvironment: hostLease?.environment,
355
+ ...providerEnvironment,
339
356
  processRunner,
340
357
  emit,
341
358
  signal
@@ -363,7 +380,7 @@ export class BridgeSessionService {
363
380
  const context = {
364
381
  dispatch: providerDispatch,
365
382
  worktree,
366
- runtimeEnvironment: hostLease?.environment,
383
+ ...providerEnvironment,
367
384
  processRunner: hostLease && dispatch.sandbox
368
385
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
369
386
  : undefined,
@@ -1,3 +1,4 @@
1
+ import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
1
2
  export interface RunOnceDispatchPacket {
2
3
  readonly schemaVersion: 1 | 2;
3
4
  readonly userId: string;
@@ -546,6 +547,8 @@ export interface HostRuntimeReadinessProbeResult {
546
547
  readonly status: "parallel_ready" | "serialized" | "failed";
547
548
  readonly runtimeContractFingerprint?: string | null;
548
549
  readonly runtimeContractSource?: string | null;
550
+ /** Requirements declared by the probed contract (decision 0013); null when none. */
551
+ readonly runtimeRequirements?: HostRuntimeRequirements | null;
549
552
  readonly reasonCode?: string | null;
550
553
  readonly reasonMessage?: string | null;
551
554
  readonly qaAppLaunchTarget?: HostRuntimeReadinessQaLaunchTarget | null;
@@ -469,13 +469,13 @@ function unvalidatedFailureFactsForCode(code, source) {
469
469
  if (code === "bridge.unavailable") {
470
470
  return facts(code, "transport", "offer", source, "retryable", "retry_dispatch");
471
471
  }
472
- if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired"].includes(code)) {
472
+ if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet"].includes(code)) {
473
473
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
474
474
  }
475
475
  if (["bridge.lease_retry_exhausted", "bridge.capacity_wait_exhausted"].includes(code)) {
476
476
  return facts(code, "resource", "offer", source, "non_retryable", "inspect_failure");
477
477
  }
478
- if (["prepublication_infrastructure_failed", "prepublication_capability_unavailable"].includes(code)) {
478
+ if (["prepublication_infrastructure_failed", "prepublication_capability_unavailable", "host_capacity_timeout", "host_capacity_token_fenced", "host_capacity_ledger_unavailable"].includes(code)) {
479
479
  return facts(code, "resource", "validation", source, "retryable", "retry_with_policy");
480
480
  }
481
481
  if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
@@ -522,6 +522,12 @@ function unvalidatedFailureFactsForCode(code, source) {
522
522
  if (code === "provider_capacity_unavailable") {
523
523
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
524
524
  }
525
+ if (code === "provider_completion_tool_missing") {
526
+ return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
527
+ }
528
+ if (code === "provider_terminated_at_turn_ceiling") {
529
+ return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
530
+ }
525
531
  if (code === "provider_context_window_exhausted") {
526
532
  return facts(code, "provider", "agent", source, "retryable", "retry_dispatch");
527
533
  }
@@ -566,6 +572,9 @@ function unvalidatedFailureFactsForCode(code, source) {
566
572
  if (code === "worktree_branch_integration_conflict") {
567
573
  return facts(code, "domain", "agent", source, "non_retryable", "fix_input");
568
574
  }
575
+ if (["merge_resolution_reverts_upstream_changes", "merge_resolution_unresolved_conflict"].includes(code)) {
576
+ return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
577
+ }
569
578
  if (stableFailureFamilyCodes.has(code) && code.startsWith("sandbox_")) {
570
579
  return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
571
580
  }
@@ -57,3 +57,4 @@ export declare function persistHostProcessSupervisorMetadata(launch: HostProcess
57
57
  */
58
58
  export declare function captureHostProcessIdentity(pid: number, platform?: NodeJS.Platform): string | null;
59
59
  export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number): Promise<void>;
60
+ export declare function windowsPowerShellPath(): string;
@@ -250,7 +250,7 @@ function assertMetadataPath(logDirectory, metadataPath) {
250
250
  throw new Error("host_process_supervisor_invalid: metadata path must be inside FORGE_LOG_DIR.");
251
251
  }
252
252
  }
253
- function windowsPowerShellPath() {
253
+ export function windowsPowerShellPath() {
254
254
  const systemRoot = process.env.SystemRoot?.trim() || "C:\\Windows";
255
255
  const candidate = path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
256
256
  return fs.existsSync(candidate) ? candidate : "powershell.exe";
@@ -0,0 +1,52 @@
1
+ export interface WindowsProcessEntry {
2
+ readonly pid: number;
3
+ readonly parentPid: number;
4
+ /** Creation time; a pid with a different one is a different process. */
5
+ readonly createdAt: string;
6
+ }
7
+ /** The process table and termination primitive, injectable for tests. */
8
+ export interface WindowsProcessTable {
9
+ list(): Promise<readonly WindowsProcessEntry[]>;
10
+ /** `taskkill /PID <pid> /T /F`: the process and the descendants Windows still links to it. */
11
+ killTree(pid: number): Promise<void>;
12
+ }
13
+ export declare const systemWindowsProcessTable: WindowsProcessTable;
14
+ /** What is known about the root's creation before it has been seen in the table. */
15
+ export type WindowsRootMarker =
16
+ /** Its recorded birth marker (Get-Process ticks): matched within a millisecond. */
17
+ {
18
+ readonly exactCreatedAt: string;
19
+ }
20
+ /** It was spawned no earlier than this (ticks): set synchronously at spawn. */
21
+ | {
22
+ readonly notBefore: string;
23
+ };
24
+ /** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
25
+ export declare function windowsTicksFromEpochMs(epochMs: number): string;
26
+ /** A Windows command's tracked tree; see the module comment. */
27
+ export declare class WindowsProcessTree {
28
+ private readonly rootPid;
29
+ private readonly table;
30
+ private readonly marker;
31
+ private readonly known;
32
+ /** The root's creation time as the process table reports it, once seen. */
33
+ private observedRoot;
34
+ private rootExited;
35
+ /**
36
+ * The root marker anchors the tree even if the root exits before the first
37
+ * snapshot (or, for a reaped token, before the reaper runs): descendants
38
+ * created after it whose parent was the root are still found. A tree with
39
+ * no marker that never saw its root cannot be proven gone.
40
+ */
41
+ constructor(rootPid: number, table: WindowsProcessTable, marker?: WindowsRootMarker | null);
42
+ /** The root has exited: from now on its pid only names it if its exact creation was seen. */
43
+ markRootExited(): void;
44
+ /** Records the root's current descendants; call while the command runs. */
45
+ track(): Promise<void>;
46
+ /** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
47
+ stop(deadlineMs: number): Promise<boolean>;
48
+ private rootAnchor;
49
+ private isRoot;
50
+ private absorb;
51
+ private alive;
52
+ }
@@ -0,0 +1,144 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { windowsPowerShellPath } from "./host-process-supervisor.js";
4
+ const execFileAsync = promisify(execFile);
5
+ export const systemWindowsProcessTable = {
6
+ async list() {
7
+ const { stdout } = await execFileAsync(windowsPowerShellPath(), [
8
+ "-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
9
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToUniversalTime().Ticks)\" }",
10
+ ], { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout: 30_000 });
11
+ return stdout.split(/\r?\n/u).flatMap(line => {
12
+ const [pid, parentPid, createdAt] = line.trim().split(" ");
13
+ return pid && parentPid && createdAt ? [{ pid: Number(pid), parentPid: Number(parentPid), createdAt }] : [];
14
+ });
15
+ },
16
+ async killTree(pid) {
17
+ await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 30_000 })
18
+ .catch(() => undefined);
19
+ },
20
+ };
21
+ /** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
22
+ export function windowsTicksFromEpochMs(epochMs) {
23
+ return ((BigInt(Math.floor(epochMs)) + 62135596800000n) * 10000n).toString();
24
+ }
25
+ /** A Windows command's tracked tree; see the module comment. */
26
+ export class WindowsProcessTree {
27
+ rootPid;
28
+ table;
29
+ marker;
30
+ known = new Map();
31
+ /** The root's creation time as the process table reports it, once seen. */
32
+ observedRoot = null;
33
+ rootExited = false;
34
+ /**
35
+ * The root marker anchors the tree even if the root exits before the first
36
+ * snapshot (or, for a reaped token, before the reaper runs): descendants
37
+ * created after it whose parent was the root are still found. A tree with
38
+ * no marker that never saw its root cannot be proven gone.
39
+ */
40
+ constructor(rootPid, table, marker = null) {
41
+ this.rootPid = rootPid;
42
+ this.table = table;
43
+ this.marker = marker;
44
+ const anchor = this.rootAnchor();
45
+ if (anchor !== null)
46
+ this.known.set(rootPid, anchor);
47
+ }
48
+ /** The root has exited: from now on its pid only names it if its exact creation was seen. */
49
+ markRootExited() {
50
+ this.rootExited = true;
51
+ }
52
+ /** Records the root's current descendants; call while the command runs. */
53
+ async track() {
54
+ const entries = await this.table.list().catch(() => null);
55
+ if (entries)
56
+ this.absorb(entries);
57
+ }
58
+ /** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
59
+ async stop(deadlineMs) {
60
+ for (;;) {
61
+ const entries = await this.table.list().catch(() => null);
62
+ if (!entries) {
63
+ if (Date.now() >= deadlineMs)
64
+ return false;
65
+ await delay(200);
66
+ continue;
67
+ }
68
+ this.absorb(entries);
69
+ // Without any anchor nothing proves which processes were the root's: fail closed.
70
+ if (!this.known.has(this.rootPid))
71
+ return false;
72
+ const alive = this.alive(entries);
73
+ if (alive.length === 0)
74
+ return true;
75
+ if (Date.now() >= deadlineMs)
76
+ return false;
77
+ for (const pid of alive)
78
+ await this.table.killTree(pid);
79
+ await delay(100);
80
+ }
81
+ }
82
+ rootAnchor() {
83
+ if (this.observedRoot !== null)
84
+ return this.observedRoot;
85
+ if (this.marker === null)
86
+ return null;
87
+ return "exactCreatedAt" in this.marker ? this.marker.exactCreatedAt : this.marker.notBefore;
88
+ }
89
+ isRoot(entry) {
90
+ if (entry.pid !== this.rootPid)
91
+ return false;
92
+ if (this.observedRoot !== null)
93
+ return entry.createdAt === this.observedRoot;
94
+ if (this.marker !== null && "exactCreatedAt" in this.marker)
95
+ return ticksClose(entry.createdAt, this.marker.exactCreatedAt);
96
+ // Before it exits, the root's pid cannot name anyone else.
97
+ if (this.rootExited)
98
+ return false;
99
+ return this.marker === null || compareTicks(entry.createdAt, this.marker.notBefore) >= 0;
100
+ }
101
+ absorb(entries) {
102
+ const root = entries.find(entry => this.isRoot(entry));
103
+ if (root && this.observedRoot === null)
104
+ this.observedRoot = root.createdAt;
105
+ const anchor = this.rootAnchor();
106
+ if (anchor !== null)
107
+ this.known.set(this.rootPid, anchor);
108
+ // Parents first: repeat until no new descendant of a known member appears.
109
+ let added = true;
110
+ while (added) {
111
+ added = false;
112
+ for (const entry of entries) {
113
+ if (this.known.has(entry.pid) || entry.pid === entry.parentPid)
114
+ continue;
115
+ const parentCreatedAt = this.known.get(entry.parentPid);
116
+ // A child is never older than its parent; an older one only reuses the parent's pid as its parent id.
117
+ if (parentCreatedAt === undefined || compareTicks(entry.createdAt, parentCreatedAt) < 0)
118
+ continue;
119
+ this.known.set(entry.pid, entry.createdAt);
120
+ added = true;
121
+ }
122
+ }
123
+ }
124
+ alive(entries) {
125
+ return entries
126
+ .filter(entry => entry.pid === this.rootPid ? this.isRoot(entry) : this.known.get(entry.pid) === entry.createdAt)
127
+ .map(entry => entry.pid);
128
+ }
129
+ }
130
+ function ticksClose(left, right) {
131
+ if (!/^\d+$/u.test(left) || !/^\d+$/u.test(right))
132
+ return left === right;
133
+ const difference = BigInt(left) - BigInt(right);
134
+ return (difference < 0n ? -difference : difference) <= 10000n;
135
+ }
136
+ function compareTicks(left, right) {
137
+ if (/^\d+$/u.test(left) && /^\d+$/u.test(right)) {
138
+ return left.length === right.length ? left.localeCompare(right) : left.length - right.length;
139
+ }
140
+ return left.localeCompare(right);
141
+ }
142
+ async function delay(ms) {
143
+ await new Promise(resolve => setTimeout(resolve, ms));
144
+ }