@loucompanion/forge-bridge 0.1.3-dev.b6be5e7f9668 → 0.1.3-dev.bca7d0ccee53

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