@loucompanion/forge-bridge 0.1.3-dev.b3bce6ba65a6 → 0.1.3-dev.ba293ccf876b

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 (189) hide show
  1. package/README.md +127 -0
  2. package/dist/bridge/bridge.base.d.ts +8 -1
  3. package/dist/bridge/bridge.service.d.ts +98 -3
  4. package/dist/bridge/bridge.service.js +1425 -45
  5. package/dist/bridge/bridge.types.d.ts +205 -1
  6. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  7. package/dist/bridge/readiness-result-outbox.js +54 -0
  8. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  9. package/dist/bridge/readiness-result-worker.js +100 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +15 -0
  11. package/dist/bridge/runner-host-capabilities.js +93 -0
  12. package/dist/cleanup/cleanup.service.d.ts +14 -2
  13. package/dist/cleanup/cleanup.service.js +496 -3
  14. package/dist/cleanup/cleanup.types.d.ts +10 -0
  15. package/dist/cleanup/index.d.ts +1 -1
  16. package/dist/cleanup/index.js +1 -1
  17. package/dist/cleanup/internals.d.ts +2 -2
  18. package/dist/cleanup/internals.js +1 -1
  19. package/dist/cli/cli.help.js +47 -1
  20. package/dist/cli/cli.service.d.ts +45 -2
  21. package/dist/cli/cli.service.js +377 -27
  22. package/dist/cli/local-config.d.ts +5 -0
  23. package/dist/cli/local-config.js +45 -1
  24. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  25. package/dist/runtime/aspnet-runtime-prebuild.js +340 -0
  26. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  27. package/dist/runtime/attempt-node-runtime-launcher.js +105 -0
  28. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  29. package/dist/runtime/attempt-path-operation.js +94 -0
  30. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  31. package/dist/runtime/attempt-private-directory.js +54 -0
  32. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  33. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  34. package/dist/runtime/attempt-process-supervisor.d.ts +97 -0
  35. package/dist/runtime/attempt-process-supervisor.js +386 -0
  36. package/dist/runtime/canonical-source-file.d.ts +3 -0
  37. package/dist/runtime/canonical-source-file.js +54 -0
  38. package/dist/runtime/docker-engine-probe.d.ts +83 -0
  39. package/dist/runtime/docker-engine-probe.js +300 -0
  40. package/dist/runtime/generated-output-reset.d.ts +10 -0
  41. package/dist/runtime/generated-output-reset.js +103 -0
  42. package/dist/runtime/host-diagnostics.d.ts +4 -0
  43. package/dist/runtime/host-diagnostics.js +95 -0
  44. package/dist/runtime/host-listener-inspector.d.ts +46 -0
  45. package/dist/runtime/host-listener-inspector.js +349 -0
  46. package/dist/runtime/host-port-broker.d.ts +76 -0
  47. package/dist/runtime/host-port-broker.js +333 -0
  48. package/dist/runtime/host-runtime-contract.d.ts +56 -0
  49. package/dist/runtime/host-runtime-contract.js +709 -0
  50. package/dist/runtime/host-runtime-lease.d.ts +201 -0
  51. package/dist/runtime/host-runtime-lease.js +2314 -0
  52. package/dist/runtime/host-runtime-promotion.d.ts +32 -0
  53. package/dist/runtime/host-runtime-promotion.js +206 -0
  54. package/dist/runtime/memory-capacity.d.ts +68 -0
  55. package/dist/runtime/memory-capacity.js +121 -0
  56. package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
  57. package/dist/runtime/node-host-runtime-adapter.js +284 -0
  58. package/dist/runtime/pinned-directory-process.d.ts +4 -0
  59. package/dist/runtime/pinned-directory-process.js +20 -0
  60. package/dist/runtime/pinned-source-directory.d.ts +9 -0
  61. package/dist/runtime/pinned-source-directory.js +56 -0
  62. package/dist/runtime/playwright-host-runtime-adapter.d.ts +21 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.js +268 -0
  64. package/dist/runtime/prepared-runtime-identity.d.ts +3 -0
  65. package/dist/runtime/prepared-runtime-identity.js +191 -0
  66. package/dist/runtime/prepared-runtime-readiness.d.ts +22 -0
  67. package/dist/runtime/prepared-runtime-readiness.js +191 -0
  68. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  69. package/dist/runtime/runtime-isolation-lease.js +158 -0
  70. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  71. package/dist/runtime/workspace-resource-estimator.js +174 -0
  72. package/dist/sandbox/command-runner.d.ts +4 -0
  73. package/dist/sandbox/command-runner.js +47 -0
  74. package/dist/sandbox/contract.d.ts +5 -0
  75. package/dist/sandbox/contract.js +276 -0
  76. package/dist/sandbox/event-budget.d.ts +11 -0
  77. package/dist/sandbox/event-budget.js +27 -0
  78. package/dist/sandbox/image-policy.d.ts +35 -0
  79. package/dist/sandbox/image-policy.js +247 -0
  80. package/dist/sandbox/index.d.ts +5 -0
  81. package/dist/sandbox/index.js +5 -0
  82. package/dist/sandbox/lease-watchdog.d.ts +18 -0
  83. package/dist/sandbox/lease-watchdog.js +67 -0
  84. package/dist/sandbox/preflight.d.ts +84 -0
  85. package/dist/sandbox/preflight.js +521 -0
  86. package/dist/sandbox/process.d.ts +20 -0
  87. package/dist/sandbox/process.js +209 -0
  88. package/dist/sandbox/provider-auth/codex.d.ts +26 -0
  89. package/dist/sandbox/provider-auth/codex.js +212 -0
  90. package/dist/sandbox/repository-lock.d.ts +5 -0
  91. package/dist/sandbox/repository-lock.js +121 -0
  92. package/dist/sandbox/runtime.d.ts +297 -0
  93. package/dist/sandbox/runtime.js +2338 -0
  94. package/dist/sandbox/sandbox.types.d.ts +93 -0
  95. package/dist/sandbox/sandbox.types.js +1 -0
  96. package/dist/sandbox/smoke.d.ts +76 -0
  97. package/dist/sandbox/smoke.js +380 -0
  98. package/dist/sandbox/worker-supervisor.d.ts +13 -0
  99. package/dist/sandbox/worker-supervisor.js +36 -0
  100. package/dist/sandbox/worker.d.ts +1 -0
  101. package/dist/sandbox/worker.js +225 -0
  102. package/dist/sandbox/workspace.service.d.ts +13 -0
  103. package/dist/sandbox/workspace.service.js +72 -0
  104. package/dist/session/managed-attempt-tools.d.ts +21 -0
  105. package/dist/session/managed-attempt-tools.js +912 -0
  106. package/dist/session/managed-build-coordinator.d.ts +5 -0
  107. package/dist/session/managed-build-coordinator.js +105 -0
  108. package/dist/session/managed-build-receipt.d.ts +21 -0
  109. package/dist/session/managed-build-receipt.js +335 -0
  110. package/dist/session/phase-completion.artifacts.d.ts +17 -0
  111. package/dist/session/phase-completion.artifacts.js +256 -26
  112. package/dist/session/phase-completion.d.ts +12 -2
  113. package/dist/session/phase-completion.helpers.d.ts +5 -0
  114. package/dist/session/phase-completion.helpers.js +51 -10
  115. package/dist/session/phase-completion.js +14 -3
  116. package/dist/session/phase-completion.prompts.d.ts +3 -3
  117. package/dist/session/phase-completion.prompts.js +24 -8
  118. package/dist/session/phase-completion.runtime.d.ts +13 -1
  119. package/dist/session/phase-completion.runtime.js +189 -8
  120. package/dist/session/phase-completion.schemas.js +117 -4
  121. package/dist/session/phase-completion.validation.d.ts +4 -1
  122. package/dist/session/phase-completion.validation.js +153 -22
  123. package/dist/session/pre-publication-validation.d.ts +47 -0
  124. package/dist/session/pre-publication-validation.js +249 -0
  125. package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
  126. package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
  127. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +3 -2
  128. package/dist/session/provider-cli/provider-cli.artifacts.js +65 -7
  129. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  130. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +2 -0
  131. package/dist/session/provider-cli/provider-cli.deterministic.js +68 -9
  132. package/dist/session/provider-cli/provider-cli.process.d.ts +26 -0
  133. package/dist/session/provider-cli/provider-cli.process.js +474 -23
  134. package/dist/session/provider-cli/provider-cli.prompts.d.ts +14 -2
  135. package/dist/session/provider-cli/provider-cli.prompts.js +147 -25
  136. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
  137. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  138. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  139. package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
  140. package/dist/session/provider-cli/provider-cli.runtime.js +6 -3
  141. package/dist/session/provider-cli/provider-cli.service.d.ts +25 -2
  142. package/dist/session/provider-cli/provider-cli.service.js +636 -84
  143. package/dist/session/provider-cli/provider-cli.types.d.ts +5 -0
  144. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  145. package/dist/session/provider-cli/provider-output-state.js +91 -16
  146. package/dist/session/provider-cli/provider-usage.d.ts +7 -0
  147. package/dist/session/provider-cli/provider-usage.js +28 -5
  148. package/dist/session/session-redaction.d.ts +3 -0
  149. package/dist/session/session-redaction.js +38 -0
  150. package/dist/session/session.base.d.ts +6 -1
  151. package/dist/session/session.service.d.ts +8 -2
  152. package/dist/session/session.service.js +531 -42
  153. package/dist/session/session.types.d.ts +115 -1
  154. package/dist/session/session.types.js +194 -3
  155. package/dist/shared/format/format-bytes.d.ts +1 -0
  156. package/dist/shared/format/format-bytes.js +9 -0
  157. package/dist/shared/git/git.js +2 -1
  158. package/dist/shared/path/path.d.ts +1 -0
  159. package/dist/shared/path/path.js +21 -1
  160. package/dist/shared/process/dotnet-toolchain.d.ts +14 -0
  161. package/dist/shared/process/dotnet-toolchain.js +179 -0
  162. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  163. package/dist/shared/process/host-process-recovery.js +78 -0
  164. package/dist/shared/process/host-process-supervisor.d.ts +59 -0
  165. package/dist/shared/process/host-process-supervisor.js +330 -0
  166. package/dist/shared/process/process.d.ts +2 -0
  167. package/dist/shared/process/process.js +11 -6
  168. package/dist/shared/provider-capabilities.d.ts +1 -0
  169. package/dist/shared/provider-capabilities.js +3 -0
  170. package/dist/shared/redaction/redaction.js +12 -2
  171. package/dist/version.d.ts +1 -1
  172. package/dist/version.js +1 -1
  173. package/dist/worktree/artifact-injector.d.ts +3 -2
  174. package/dist/worktree/artifact-injector.js +43 -4
  175. package/dist/worktree/dependency-warmer.d.ts +28 -1
  176. package/dist/worktree/dependency-warmer.js +308 -9
  177. package/dist/worktree/index.d.ts +2 -1
  178. package/dist/worktree/index.js +1 -0
  179. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  180. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  181. package/dist/worktree/worktree-paths.d.ts +4 -0
  182. package/dist/worktree/worktree-paths.js +30 -0
  183. package/dist/worktree/worktree.base.d.ts +3 -0
  184. package/dist/worktree/worktree.service.d.ts +14 -2
  185. package/dist/worktree/worktree.service.js +296 -47
  186. package/dist/worktree/worktree.types.d.ts +5 -1
  187. package/package.json +8 -4
  188. package/runtime/windows-job-supervisor.ps1 +444 -0
  189. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -1,12 +1,127 @@
1
- import { redactSecrets } from "../shared/redaction/redaction.js";
1
+ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "./session-redaction.js";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
3
4
  import { GitWorktreeService } from "../worktree/worktree.service.js";
5
+ import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
6
+ import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, } from "../runtime/host-runtime-lease.js";
7
+ import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
8
+ const minimumReadinessProbeStartupBudgetMs = 150_000;
4
9
  export class BridgeSessionService {
5
10
  worktrees;
6
11
  providerCli;
7
- constructor(worktrees = new GitWorktreeService(), providerCli = new RoutingProviderCliService()) {
12
+ hostRuntime;
13
+ constructor(worktrees = process.env.FORGE_SANDBOX_ID
14
+ ? new SandboxWorkspaceService()
15
+ : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime) {
8
16
  this.worktrees = worktrees;
9
17
  this.providerCli = providerCli;
18
+ this.hostRuntime = hostRuntime;
19
+ }
20
+ async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
21
+ await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
22
+ }
23
+ async reapHostRuntime(options) {
24
+ return await this.hostRuntime?.reap?.(options) ?? null;
25
+ }
26
+ runtimeCapacity() {
27
+ return this.hostRuntime?.snapshot?.() ?? null;
28
+ }
29
+ async probeHostRuntime(request, signal) {
30
+ if (!this.hostRuntime) {
31
+ return failedProbe("host_runtime_unavailable", "This bridge does not provide managed host runtime isolation.");
32
+ }
33
+ const dispatch = readinessProbeDispatch(request);
34
+ let worktree = null;
35
+ let admissionAcquired = false;
36
+ let runtimeStarted = false;
37
+ let result;
38
+ let cleanupFailure = null;
39
+ try {
40
+ throwIfAborted(signal);
41
+ await this.hostRuntime.acquire(dispatch, signal);
42
+ admissionAcquired = true;
43
+ // Readiness probes acquire background-exclusive project admission. Only
44
+ // invalidate the prior proof after that fence is held so a user lane can
45
+ // never observe the proof disappear underneath shared admission.
46
+ await this.hostRuntime.invalidatePromotion?.(request.repoId, "discovery");
47
+ assertReadinessProbeStartupBudget(request.expiresAt);
48
+ worktree = await this.worktrees.prepare({
49
+ repo: dispatch.repo,
50
+ workItem: dispatch.workItem,
51
+ baseBranch: request.revision,
52
+ worktreeKey: dispatch.lease.worktreeKey,
53
+ ownerType: "project",
54
+ ownerId: request.projectId,
55
+ lane: "runtime_readiness",
56
+ phase: "readiness_probe",
57
+ allowedRepoRoot: request.repoRoot,
58
+ // Readiness probes are disposable infrastructure checks, not agent lanes.
59
+ // Always remove their worktree even when the bridge is configured to retain
60
+ // failed agent worktrees for inspection.
61
+ cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
62
+ artifacts: [],
63
+ });
64
+ assertReadinessProbeStartupBudget(request.expiresAt);
65
+ let started = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal);
66
+ runtimeStarted = true;
67
+ const discovery = started.runtimeContract.discovery;
68
+ if (!hostRuntimeParallelEligible(started.runtimeContract)) {
69
+ result = {
70
+ status: "serialized",
71
+ runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
72
+ runtimeContractSource: started.runtimeContract.source,
73
+ reasonCode: discovery?.reasonCode ?? "host_runtime_contract_serialized",
74
+ reasonMessage: discovery?.summary ?? "The detected runtime requires serialized host execution.",
75
+ checkedAt: new Date().toISOString(),
76
+ };
77
+ }
78
+ else {
79
+ assertReadinessProbeStartupBudget(request.expiresAt);
80
+ started = await this.hostRuntime.startConfiguredProject(request.requestId, request.fencingToken, signal);
81
+ const requiredPorts = configuredLaunchPortNames(started.runtimeContract);
82
+ const verifiedPorts = started.lease.resources.ports.map(port => port.name);
83
+ const verified = requiredPorts.length > 0 && requiredPorts.every(name => verifiedPorts.includes(name));
84
+ result = verified
85
+ ? {
86
+ status: "parallel_ready",
87
+ runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
88
+ runtimeContractSource: started.runtimeContract.source,
89
+ reasonCode: null,
90
+ reasonMessage: null,
91
+ qaAppLaunchTarget: managedQaLaunchTarget(started.runtimeContract),
92
+ checkedAt: new Date().toISOString(),
93
+ }
94
+ : failedProbe("host_runtime_probe_unverified", "The application did not prove ownership and readiness on every Forge-assigned port.");
95
+ }
96
+ }
97
+ catch (error) {
98
+ result = failedProbe(probeFailureCode(error), probeFailureMessage(error));
99
+ }
100
+ finally {
101
+ if (runtimeStarted || admissionAcquired) {
102
+ try {
103
+ const released = await this.hostRuntime.release(request.requestId, request.fencingToken);
104
+ if (runtimeStarted && !released)
105
+ cleanupFailure = new Error("The runtime lease was no longer current during cleanup.");
106
+ }
107
+ catch (error) {
108
+ cleanupFailure = error instanceof Error ? error : new Error(String(error));
109
+ }
110
+ }
111
+ if (worktree) {
112
+ try {
113
+ await this.worktrees.release(worktree);
114
+ }
115
+ catch (error) {
116
+ cleanupFailure ??= error instanceof Error ? error : new Error(String(error));
117
+ }
118
+ }
119
+ }
120
+ if (cleanupFailure) {
121
+ await this.hostRuntime.invalidatePromotion?.(request.repoId).catch(() => undefined);
122
+ return failedProbe("host_runtime_cleanup_degraded", `Forge could not prove exact readiness cleanup: ${cleanupFailure.message}`);
123
+ }
124
+ return result;
10
125
  }
11
126
  async runOnce(dispatch, sink, signal) {
12
127
  validateApiKeySecretGrant(dispatch);
@@ -16,7 +131,14 @@ export class BridgeSessionService {
16
131
  if (signal?.aborted) {
17
132
  return;
18
133
  }
19
- const redacted = redactSecrets(event, redactionSecrets);
134
+ const redacted = redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets);
135
+ if (redacted.eventType !== "provider_tool_heartbeat") {
136
+ events.push(redacted);
137
+ }
138
+ await sink.emit(redacted);
139
+ };
140
+ const emitLifecycle = async (event) => {
141
+ const redacted = redactRunnerDispatchEvent({ ...event, eventId: event.eventId ?? randomUUID() }, redactionSecrets);
20
142
  events.push(redacted);
21
143
  await sink.emit(redacted);
22
144
  };
@@ -27,44 +149,168 @@ export class BridgeSessionService {
27
149
  content: "forge-bridge accepted run-once dispatch.",
28
150
  eventType: "dispatch_accepted"
29
151
  });
30
- const worktree = await this.worktrees.prepare({
31
- repo: dispatch.repo,
32
- workItem: dispatch.workItem,
33
- baseBranch: dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase,
34
- worktreeKey: dispatch.lease.worktreeKey,
35
- ownerType: dispatch.cycleRun.ownerType ?? dispatch.lease.ownerType ?? null,
36
- ownerId: dispatch.cycleRun.ownerId ?? dispatch.lease.ownerId ?? null,
37
- lane: dispatch.execution.lane,
38
- phase: dispatch.cycleRun.phase,
39
- allowedRepoRoot: dispatch.serverLocal.repoRoot,
40
- cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
41
- artifacts: dispatch.artifacts,
42
- qaRework: dispatch.qaRework,
43
- warmPathOverrides: dispatch.warmPathOverrides
44
- });
45
- const providerDispatch = withPreparedQaReworkPacket(dispatch, worktree.qaReworkPacketPath);
46
- throwIfAborted(signal);
47
- await emit({
48
- role: "runner",
49
- kind: "checkpoint",
50
- content: `Prepared worktree ${worktree.branchName}.`,
51
- eventType: "worktree_prepared"
52
- });
53
- if (worktree.dependencyWarm) {
54
- await emitDependencyWarmEvents(worktree.dependencyWarm, emit);
55
- }
152
+ let worktree = null;
153
+ let hostSingletonKeys = null;
154
+ let hostLease = null;
56
155
  try {
156
+ if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
157
+ const capacity = this.hostRuntime.snapshot?.() ?? null;
158
+ const projectCapacity = capacity?.projects.find(project => project.repoId === dispatch.repo.id) ?? null;
159
+ await emitLifecycle({
160
+ role: "runner",
161
+ kind: "checkpoint",
162
+ content: capacity
163
+ ? `Waiting for host-runtime admission before preparing the worktree (queue position ${capacity.waitingAttempts + 1}; runner ${capacity.activeAttempts} active, ${capacity.reservedAttempts} reserved; project ${projectCapacity?.activeAttempts ?? 0} active, ${projectCapacity?.waitingAttempts ?? 0} already waiting). This wait can be caused by the project serialization policy, readiness proof, or resource headroom; Forge will continue automatically when admission is available.`
164
+ : "Waiting for host-runtime admission before preparing the worktree. Forge will continue automatically when admission is available.",
165
+ eventType: "host_runtime_admission_waiting",
166
+ data: capacity ? JSON.stringify({
167
+ queue_position: capacity.waitingAttempts + 1,
168
+ runner_active_attempts: capacity.activeAttempts,
169
+ runner_reserved_attempts: capacity.reservedAttempts,
170
+ runner_waiting_attempts: capacity.waitingAttempts,
171
+ project_active_attempts: projectCapacity?.activeAttempts ?? 0,
172
+ project_reserved_attempts: projectCapacity?.reservedAttempts ?? 0,
173
+ project_waiting_attempts: projectCapacity?.waitingAttempts ?? 0,
174
+ project_safety_class: projectCapacity?.safetyClass ?? "unknown",
175
+ }) : undefined,
176
+ });
177
+ try {
178
+ hostSingletonKeys = await (this.hostRuntime.acquirePreparation?.(dispatch, signal)
179
+ ?? this.hostRuntime.acquire(dispatch, signal));
180
+ }
181
+ catch (error) {
182
+ if (error instanceof HostRuntimeAdmissionExpiredError) {
183
+ await emitLifecycle({
184
+ role: "runner",
185
+ kind: "error",
186
+ content: "Managed host admission expired while the project singleton remained busy; no worktree or runtime resources were created.",
187
+ eventType: "host_runtime_admission_expired",
188
+ }).catch(() => undefined);
189
+ }
190
+ throw error;
191
+ }
192
+ throwIfAborted(signal);
193
+ await emitLifecycle({
194
+ role: "runner",
195
+ kind: "checkpoint",
196
+ content: this.hostRuntime.acquirePreparation
197
+ ? "Acquired worktree-preparation capacity. Prepared runtime verification must finish before agent admission."
198
+ : hostSingletonKeys.length > 0
199
+ ? `Acquired managed host singleton ${hostSingletonKeys.join(", ")}.`
200
+ : "Observed assigned-port evidence permits provisional parallel host admission; the prepared runtime contract must still match before launch.",
201
+ eventType: "host_runtime_admission_acquired",
202
+ });
203
+ }
204
+ try {
205
+ worktree = await this.worktrees.prepare({
206
+ repo: dispatch.repo,
207
+ workItem: dispatch.workItem,
208
+ baseBranch: dispatch.cycleRun.baseBranch || dispatch.cycleRun.requestedBase,
209
+ worktreeKey: dispatch.lease.worktreeKey,
210
+ ownerType: dispatch.cycleRun.ownerType ?? dispatch.lease.ownerType ?? null,
211
+ ownerId: dispatch.cycleRun.ownerId ?? dispatch.lease.ownerId ?? null,
212
+ lane: dispatch.execution.lane,
213
+ phase: dispatch.cycleRun.phase,
214
+ allowedRepoRoot: dispatch.serverLocal.repoRoot,
215
+ cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
216
+ artifacts: dispatch.artifacts,
217
+ priorPhaseArtifacts: dispatch.priorPhaseArtifacts,
218
+ qaRework: dispatch.qaRework,
219
+ warmPathOverrides: dispatch.warmPathOverrides,
220
+ applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
221
+ preserveExistingState: Boolean(dispatch.session.resumedFromSessionId)
222
+ });
223
+ }
224
+ catch (error) {
225
+ throw new Error(`worktree_prepare_failed: ${failureMessage(error)}`, { cause: error });
226
+ }
227
+ let providerDispatch = withPreparedQaReworkPacket(dispatch, worktree.qaReworkPacketPath);
228
+ throwIfAborted(signal);
229
+ await emit({
230
+ role: "runner",
231
+ kind: "checkpoint",
232
+ content: dispatch.session.resumedFromSessionId
233
+ ? `Reattached to worktree ${worktree.branchName} without resetting source or clearing attempt artifacts.`
234
+ : `Prepared worktree ${worktree.branchName}.`,
235
+ eventType: dispatch.session.resumedFromSessionId ? "worktree_reattached" : "worktree_prepared"
236
+ });
237
+ if ((worktree.hydratedPriorPhaseArtifactCount ?? 0) > 0) {
238
+ await emit({
239
+ role: "runner",
240
+ kind: "checkpoint",
241
+ content: `Hydrated ${worktree.hydratedPriorPhaseArtifactCount} persisted prior-phase artifact(s) into the prepared worktree.`,
242
+ eventType: "prior_phase_artifacts_hydrated"
243
+ });
244
+ }
245
+ if (worktree.dependencyWarm) {
246
+ await emitDependencyWarmEvents(worktree.dependencyWarm, emit);
247
+ }
248
+ if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
249
+ hostLease = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal, async (checkpoint) => {
250
+ await emitLifecycle({
251
+ role: "runner",
252
+ kind: "checkpoint",
253
+ content: checkpoint.message,
254
+ eventType: checkpoint.code,
255
+ data: JSON.stringify({ expires_at: checkpoint.expiresAt }),
256
+ });
257
+ });
258
+ await emitLifecycle({
259
+ role: "runner",
260
+ kind: "checkpoint",
261
+ content: `Host runtime lease ${hostLease.lease.leaseId} is active for this worktree.`,
262
+ eventType: "sandbox_started",
263
+ occurredAt: hostLease.lease.stateChangedAt,
264
+ data: JSON.stringify(hostRuntimeEventResources(hostLease.lease, hostLease.runtimeContract, hostLease.executionClass)),
265
+ });
266
+ await emitLifecycle({
267
+ role: "runner",
268
+ kind: "checkpoint",
269
+ content: "Managed host fallback isolates the worktree, attempt paths, assigned loopback ports, and supervised process trees, but not the host filesystem, network, credentials, or kernel. Serialized projects also hold a runner-local singleton. Enable Run in Docker in Project Settings when stronger isolation is required.",
270
+ eventType: "host_runtime_isolation_notice",
271
+ data: JSON.stringify({
272
+ isolationStrength: "managed_host_process",
273
+ remediation: "Enable Run in Docker in Project Settings.",
274
+ }),
275
+ });
276
+ const unconfiguredPortCount = hostLease.lease.resources.ports.length;
277
+ hostLease = await this.hostRuntime.startConfiguredProject(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken, signal, async (checkpoint) => {
278
+ await emitLifecycle({
279
+ role: "runner",
280
+ kind: "checkpoint",
281
+ content: checkpoint.message,
282
+ eventType: checkpoint.code,
283
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
284
+ });
285
+ });
286
+ if (hostLease.lease.resources.ports.length > unconfiguredPortCount) {
287
+ const assigned = hostLease.lease.resources.ports.at(-1);
288
+ await emitLifecycle({
289
+ role: "runner",
290
+ kind: "checkpoint",
291
+ content: `Verified supervised project runtime ${assigned.name} on ${assigned.hostIp}:${assigned.hostPort}.`,
292
+ eventType: "host_runtime_project_ready",
293
+ data: JSON.stringify(hostRuntimeEventResources(hostLease.lease, hostLease.runtimeContract, hostLease.executionClass)),
294
+ });
295
+ }
296
+ }
297
+ providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
57
298
  if (dispatch.draft) {
58
299
  throwIfAborted(signal);
300
+ const processRunner = hostLease && dispatch.sandbox
301
+ ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
302
+ : undefined;
59
303
  const run = await this.providerCli.runDraft({
60
304
  dispatch: providerDispatch,
61
305
  worktree,
306
+ runtimeEnvironment: hostLease?.environment,
307
+ processRunner,
62
308
  emit,
63
309
  signal
64
310
  });
65
311
  throwIfAborted(signal);
66
312
  const draftArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
67
- return redactSecrets({
313
+ return redactRunOnceResultPacket({
68
314
  schemaVersion: 1,
69
315
  exitCode: 0,
70
316
  summary: run.summary,
@@ -75,27 +321,46 @@ export class BridgeSessionService {
75
321
  }, redactionSecrets);
76
322
  }
77
323
  throwIfAborted(signal);
78
- const lane = dispatch.execution.lane.toLowerCase();
79
- const role = dispatch.execution.role.toLowerCase();
324
+ const lane = dispatch.execution.lane.trim().toLowerCase();
325
+ const role = dispatch.execution.role.trim().toLowerCase();
326
+ const cycleKind = dispatch.cycleRun.kind.trim().toLowerCase();
80
327
  const isQa = role === "qa" || lane === "qa";
81
- const isArchitect = role === "architect" || lane === "architect" || dispatch.cycleRun.kind.toLowerCase() === "architect";
328
+ const isArchitect = role === "architect" || lane === "architect" || cycleKind === "architect";
329
+ const isCiRepair = role === "ci_repair" || lane === "ci_repair" || cycleKind === "pr_checks";
82
330
  const isConflictResolve = role === "conflict_resolve" || lane === "conflict_resolve";
83
331
  const context = {
84
332
  dispatch: providerDispatch,
85
333
  worktree,
334
+ runtimeEnvironment: hostLease?.environment,
335
+ processRunner: hostLease && dispatch.sandbox
336
+ ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
337
+ : undefined,
86
338
  emit,
87
339
  signal
88
340
  };
89
- const run = isQa
90
- ? await this.providerCli.runQa(context)
91
- : isArchitect
92
- ? await this.providerCli.runArchitect(context)
93
- : isConflictResolve
94
- ? await this.providerCli.runConflictResolve(context)
95
- : await this.providerCli.runImplementation(context);
341
+ let run;
342
+ try {
343
+ run = isQa
344
+ ? await this.providerCli.runQa(context)
345
+ : isArchitect
346
+ ? await this.providerCli.runArchitect(context)
347
+ : isCiRepair
348
+ ? await this.providerCli.runCiRepair(context)
349
+ : isConflictResolve
350
+ ? await this.providerCli.runConflictResolve(context)
351
+ : await this.providerCli.runImplementation(context);
352
+ }
353
+ catch (error) {
354
+ const message = failureMessage(error);
355
+ if (message.includes("attempt_process_supervisor_start_")
356
+ || message.includes("host_process_supervisor_start_")) {
357
+ throw new Error(`provider_start_unavailable: ${message}`, { cause: error });
358
+ }
359
+ throw error;
360
+ }
96
361
  throwIfAborted(signal);
97
362
  const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
98
- return redactSecrets({
363
+ return redactRunOnceResultPacket({
99
364
  schemaVersion: 1,
100
365
  exitCode: 0,
101
366
  summary: run.summary,
@@ -106,10 +371,217 @@ export class BridgeSessionService {
106
371
  }, redactionSecrets);
107
372
  }
108
373
  finally {
109
- await this.worktrees.release(worktree);
374
+ if (hostLease && dispatch.sandbox) {
375
+ const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
376
+ if (providerMemory) {
377
+ await emitLifecycle({
378
+ role: "runner",
379
+ kind: "checkpoint",
380
+ content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
381
+ eventType: "sandbox_peak_memory_observed",
382
+ occurredAt: providerMemory.observedAt,
383
+ data: JSON.stringify({
384
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
385
+ sampleCount: providerMemory.sampleCount,
386
+ source: providerMemory.source,
387
+ containers: [{
388
+ role: "agent",
389
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
390
+ }],
391
+ }),
392
+ }).catch(() => undefined);
393
+ }
394
+ const teardownAt = new Date().toISOString();
395
+ await emitLifecycle({
396
+ role: "runner",
397
+ kind: "checkpoint",
398
+ content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
399
+ eventType: "sandbox_teardown_started",
400
+ occurredAt: teardownAt,
401
+ }).catch(() => undefined);
402
+ try {
403
+ const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
404
+ if (!released) {
405
+ await emitLifecycle({
406
+ role: "runner",
407
+ kind: "error",
408
+ content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
409
+ eventType: "teardown_failed",
410
+ occurredAt: new Date().toISOString(),
411
+ }).catch(() => undefined);
412
+ }
413
+ else {
414
+ await emitLifecycle({
415
+ role: "runner",
416
+ kind: "checkpoint",
417
+ content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
418
+ eventType: "sandbox_teardown_completed",
419
+ occurredAt: released.releasedAt,
420
+ }).catch(() => undefined);
421
+ }
422
+ }
423
+ catch (error) {
424
+ await emitLifecycle({
425
+ role: "runner",
426
+ kind: "error",
427
+ content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
428
+ eventType: "teardown_failed",
429
+ occurredAt: new Date().toISOString(),
430
+ }).catch(() => undefined);
431
+ }
432
+ }
433
+ if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
434
+ await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
435
+ }
436
+ if (worktree && !isPauseCancellation(signal))
437
+ await this.worktrees.release(worktree);
110
438
  }
111
439
  }
112
440
  }
441
+ function failureMessage(error) {
442
+ return error instanceof Error ? error.message : String(error);
443
+ }
444
+ function formatMemoryBytes(bytes) {
445
+ return `${(bytes / (1024 ** 2)).toFixed(bytes >= 1024 ** 3 ? 0 : 1)} MiB`;
446
+ }
447
+ function isPauseCancellation(signal) {
448
+ return signal?.aborted === true
449
+ && String(signal.reason ?? "").trim().toLowerCase() === "session pause requested";
450
+ }
451
+ function readinessProbeDispatch(request) {
452
+ return {
453
+ schemaVersion: 2,
454
+ userId: request.userId,
455
+ workItem: {
456
+ id: request.projectId,
457
+ kind: "runtime_readiness",
458
+ title: "Automatic host-isolation readiness check",
459
+ description: "Internal readiness proof without a provider agent.",
460
+ acceptanceCriteria: "",
461
+ reproSteps: "",
462
+ systemInfo: "",
463
+ },
464
+ repo: {
465
+ id: request.repoId,
466
+ name: request.repoName,
467
+ remoteUrl: request.remoteUrl,
468
+ defaultBranch: request.defaultBranch,
469
+ cloneOnDemand: request.cloneOnDemand,
470
+ serverLocalPath: request.runnerRepoLocalPath,
471
+ },
472
+ cycleRun: {
473
+ id: request.requestId,
474
+ ownerType: "project",
475
+ ownerId: request.projectId,
476
+ kind: "runtime_readiness",
477
+ phase: "readiness_probe",
478
+ requestedBase: request.revision,
479
+ baseBranch: request.revision,
480
+ attempt: request.attempt,
481
+ model: "none",
482
+ },
483
+ session: { id: request.requestId, model: "none", lane: "runtime_readiness" },
484
+ lease: {
485
+ id: request.requestId,
486
+ ownerType: "project",
487
+ ownerId: request.projectId,
488
+ worktreeKey: `runtime-readiness-${request.requestId}`,
489
+ lane: "runtime_readiness",
490
+ fencingToken: request.fencingToken,
491
+ expiresAt: request.expiresAt,
492
+ },
493
+ execution: {
494
+ provider: "none",
495
+ model: "none",
496
+ authKind: "none",
497
+ location: "bridge",
498
+ runnerId: request.runnerId,
499
+ repoId: request.repoId,
500
+ role: "runtime_readiness",
501
+ lane: "runtime_readiness",
502
+ requiresApiKeySecretGrant: false,
503
+ runnerRepoLocalPath: request.runnerRepoLocalPath,
504
+ },
505
+ runtimeIntent: { executionClass: "managed_runtime", applicationRuntimeRequired: true },
506
+ serverLocal: { repoRoot: request.repoRoot, cleanupWorktrees: true },
507
+ sandbox: {
508
+ dispatchAttemptId: request.requestId,
509
+ executionLeaseId: request.requestId,
510
+ runnerInstanceId: request.runnerInstanceId,
511
+ executionMode: "host",
512
+ executionPolicy: "host_allowed",
513
+ networkPolicy: { mode: "offline", allowedHosts: [] },
514
+ requestedResources: {
515
+ sandboxSlots: 1,
516
+ cpuMillis: 2000,
517
+ workerMemoryLimitBytes: 1024 * 1024 * 1024,
518
+ serviceMemoryLimitBytes: 1024 * 1024 * 1024,
519
+ runtimeOverheadBytes: 256 * 1024 * 1024,
520
+ memoryBytes: 2 * 1024 * 1024 * 1024,
521
+ workspaceBytes: 10 * 1024 * 1024 * 1024,
522
+ pids: 512,
523
+ buildSlots: 1,
524
+ },
525
+ publicationMode: "shared_filesystem",
526
+ },
527
+ artifacts: [],
528
+ };
529
+ }
530
+ function failedProbe(reasonCode, reasonMessage) {
531
+ return { status: "failed", reasonCode, reasonMessage, checkedAt: new Date().toISOString() };
532
+ }
533
+ function assertReadinessProbeStartupBudget(expiresAt) {
534
+ const remainingMs = Date.parse(expiresAt) - Date.now();
535
+ if (!Number.isFinite(remainingMs) || remainingMs < minimumReadinessProbeStartupBudgetMs) {
536
+ throw new Error("host_runtime_probe_deadline_insufficient: readiness admission completed too close to the probe deadline; Forge released the reservation before launching the application.");
537
+ }
538
+ }
539
+ function managedQaLaunchTarget(runtimeContract) {
540
+ const playwright = runtimeContract.contract.runtime.playwright;
541
+ if (!playwright)
542
+ return null;
543
+ const port = runtimeContract.contract.runtime.ports.find(candidate => candidate.name === playwright.baseUrlPort);
544
+ return port?.launch && port.baseUrlEnv && port.format
545
+ ? { managedRuntimePort: port.name, routes: ["/"] }
546
+ : null;
547
+ }
548
+ function withMaterializedManagedQaTarget(dispatch, hostLease) {
549
+ const target = dispatch.qaBrowser?.launchTarget;
550
+ const portName = target?.managed_runtime_port?.trim().toLowerCase();
551
+ if (!target || !portName)
552
+ return dispatch;
553
+ if (!hostLease) {
554
+ throw new Error("qa_managed_runtime_unavailable: Browser QA requires the verified managed host runtime selected during readiness.");
555
+ }
556
+ const normalizedName = portName.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
557
+ const url = hostLease.environment[`FORGE_${normalizedName}_URL`];
558
+ if (!url) {
559
+ throw new Error(`qa_managed_runtime_unavailable: verified runtime port '${portName}' was not launched for this attempt.`);
560
+ }
561
+ return {
562
+ ...dispatch,
563
+ qaBrowser: dispatch.qaBrowser ? {
564
+ ...dispatch.qaBrowser,
565
+ launchTarget: {
566
+ ...target,
567
+ url: target.url ?? url,
568
+ ready_url: target.ready_url ?? url,
569
+ notes: [target.notes, "Forge launched and verified this URL inside the current fenced attempt."]
570
+ .filter(Boolean)
571
+ .join(" "),
572
+ },
573
+ } : dispatch.qaBrowser,
574
+ };
575
+ }
576
+ function probeFailureCode(error) {
577
+ const message = error instanceof Error ? error.message : String(error);
578
+ const candidate = message.split(":", 1)[0]?.trim().toLowerCase() ?? "";
579
+ return /^[a-z][a-z0-9_.-]{2,159}$/u.test(candidate) ? candidate : "host_runtime_probe_failed";
580
+ }
581
+ function probeFailureMessage(error) {
582
+ const message = error instanceof Error ? error.message : String(error);
583
+ return message.length > 1000 ? `${message.slice(0, 997)}...` : message;
584
+ }
113
585
  function throwIfAborted(signal) {
114
586
  if (signal?.aborted) {
115
587
  throw new Error(String(signal.reason ?? "Dispatch cancelled."));
@@ -150,6 +622,23 @@ function withPreparedQaReworkPacket(dispatch, packetPath) {
150
622
  };
151
623
  }
152
624
  async function emitDependencyWarmEvents(warm, emit) {
625
+ for (const receipt of warm.receipts) {
626
+ await emit({
627
+ role: "runner",
628
+ kind: "checkpoint",
629
+ content: receipt.cacheHit
630
+ ? `Reused verified ${receipt.ecosystem} dependency preparation receipt ${receipt.fingerprint} in ${receipt.packageRoot}.`
631
+ : `Published ${receipt.ecosystem} dependency preparation receipt ${receipt.fingerprint} in ${receipt.packageRoot}.`,
632
+ eventType: receipt.cacheHit ? "dependencies_preparation_cached" : "dependencies_preparation_receipt_published",
633
+ data: JSON.stringify({
634
+ ecosystem: receipt.ecosystem,
635
+ package_root: receipt.packageRoot,
636
+ cache_hit: receipt.cacheHit,
637
+ fingerprint: receipt.fingerprint,
638
+ receipt_path: receipt.receiptPath,
639
+ }),
640
+ });
641
+ }
153
642
  if (warm.linked.length > 0) {
154
643
  await emit({
155
644
  role: "runner",