@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.deb7f72e7930

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 (253) hide show
  1. package/README.md +144 -3
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +92 -15
  16. package/dist/bridge/bridge.service.js +432 -342
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  25. package/dist/bridge/runner-host-capabilities.js +17 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  29. package/dist/bridge/test-postgres-capability.js +120 -0
  30. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  31. package/dist/cleanup/cleanup-wip.js +66 -0
  32. package/dist/cleanup/cleanup.service.d.ts +20 -1
  33. package/dist/cleanup/cleanup.service.js +150 -169
  34. package/dist/cleanup/cleanup.types.d.ts +6 -0
  35. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  36. package/dist/cleanup/forge-owned-paths.js +53 -0
  37. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  38. package/dist/cleanup/host-runtime-ledger.js +130 -0
  39. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  40. package/dist/cleanup/managed-branch-sweep.js +111 -0
  41. package/dist/cli/cli.help.js +74 -12
  42. package/dist/cli/cli.service.d.ts +19 -10
  43. package/dist/cli/cli.service.js +152 -187
  44. package/dist/cli/idle-status.d.ts +84 -0
  45. package/dist/cli/idle-status.js +181 -0
  46. package/dist/cli/local-config.d.ts +6 -0
  47. package/dist/cli/local-config.js +32 -4
  48. package/dist/cli/provider-cli-detection.d.ts +10 -0
  49. package/dist/cli/provider-cli-detection.js +160 -0
  50. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  51. package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
  52. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  53. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  54. package/dist/runtime/docker-engine-probe.js +7 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  60. package/dist/runtime/host-database-capability-boundary.js +1 -0
  61. package/dist/runtime/host-facts.d.ts +36 -0
  62. package/dist/runtime/host-facts.js +95 -0
  63. package/dist/runtime/host-load-admission.d.ts +67 -0
  64. package/dist/runtime/host-load-admission.js +99 -0
  65. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  66. package/dist/runtime/host-load-child-environment.js +76 -0
  67. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  68. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  69. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  70. package/dist/runtime/host-load-governor-config.js +83 -0
  71. package/dist/runtime/host-load-governor.d.ts +186 -0
  72. package/dist/runtime/host-load-governor.js +632 -0
  73. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  74. package/dist/runtime/host-load-ledger-lock.js +187 -0
  75. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  76. package/dist/runtime/host-load-runtime-settings.js +80 -0
  77. package/dist/runtime/host-load-sampler.d.ts +156 -0
  78. package/dist/runtime/host-load-sampler.js +298 -0
  79. package/dist/runtime/host-load-step-class.d.ts +70 -0
  80. package/dist/runtime/host-load-step-class.js +161 -0
  81. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  82. package/dist/runtime/host-load-step-reaper.js +95 -0
  83. package/dist/runtime/host-load-step-run.d.ts +73 -0
  84. package/dist/runtime/host-load-step-run.js +102 -0
  85. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  86. package/dist/runtime/host-load-test-slot.js +81 -0
  87. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  88. package/dist/runtime/host-load-token-ledger.js +453 -0
  89. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  90. package/dist/runtime/host-load-windows-cpu.js +85 -0
  91. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  92. package/dist/runtime/host-pressure-stall.js +168 -0
  93. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  94. package/dist/runtime/host-runtime-contract.js +35 -2
  95. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  96. package/dist/runtime/host-runtime-lease.js +285 -55
  97. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  98. package/dist/runtime/host-runtime-promotion.js +48 -0
  99. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  100. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  101. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  102. package/dist/runtime/host-runtime-requirements.js +117 -0
  103. package/dist/runtime/managed-command-teardown.js +5 -16
  104. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  105. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  106. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  107. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  108. package/dist/runtime/runner-settings.d.ts +104 -0
  109. package/dist/runtime/runner-settings.js +236 -0
  110. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  111. package/dist/sandbox/host-capacity-broker.js +336 -0
  112. package/dist/sandbox/managed-branch.d.ts +13 -0
  113. package/dist/sandbox/managed-branch.js +36 -0
  114. package/dist/sandbox/provider-auth/codex.js +11 -11
  115. package/dist/sandbox/runtime.d.ts +10 -1
  116. package/dist/sandbox/runtime.js +47 -8
  117. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  118. package/dist/sandbox/sandbox-cgroups.js +42 -0
  119. package/dist/session/architect-waits.d.ts +2 -0
  120. package/dist/session/architect-waits.js +138 -0
  121. package/dist/session/managed-attempt-tools.d.ts +2 -7
  122. package/dist/session/managed-attempt-tools.js +202 -116
  123. package/dist/session/managed-build-receipt.d.ts +5 -0
  124. package/dist/session/managed-build-receipt.js +8 -3
  125. package/dist/session/managed-command-host-load.d.ts +47 -0
  126. package/dist/session/managed-command-host-load.js +83 -0
  127. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  128. package/dist/session/mcp-argument-coercion.js +121 -0
  129. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  130. package/dist/session/phase-completion.artifacts.js +100 -26
  131. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  132. package/dist/session/phase-completion.command-validation.js +77 -0
  133. package/dist/session/phase-completion.d.ts +12 -0
  134. package/dist/session/phase-completion.helpers.js +13 -12
  135. package/dist/session/phase-completion.js +5 -0
  136. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  137. package/dist/session/phase-completion.mcp-args.js +156 -0
  138. package/dist/session/phase-completion.prompts.js +6 -1
  139. package/dist/session/phase-completion.runtime.d.ts +5 -11
  140. package/dist/session/phase-completion.runtime.js +91 -215
  141. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  142. package/dist/session/phase-completion.schema-parts.js +188 -0
  143. package/dist/session/phase-completion.schemas.d.ts +3 -3
  144. package/dist/session/phase-completion.schemas.js +208 -231
  145. package/dist/session/phase-completion.validation.d.ts +2 -3
  146. package/dist/session/phase-completion.validation.js +49 -93
  147. package/dist/session/pre-publication-host-load.d.ts +27 -0
  148. package/dist/session/pre-publication-host-load.js +111 -0
  149. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  150. package/dist/session/pre-publication-native-postgres.js +111 -0
  151. package/dist/session/pre-publication-pass.d.ts +61 -0
  152. package/dist/session/pre-publication-pass.js +148 -0
  153. package/dist/session/pre-publication-process.d.ts +3 -0
  154. package/dist/session/pre-publication-process.js +33 -20
  155. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  156. package/dist/session/pre-publication-skipped-tests.js +109 -0
  157. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  158. package/dist/session/pre-publication-step-execution.js +50 -0
  159. package/dist/session/pre-publication-validation.d.ts +37 -21
  160. package/dist/session/pre-publication-validation.js +224 -166
  161. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  162. package/dist/session/provider-cli/claude-background-work.js +181 -0
  163. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  164. package/dist/session/provider-cli/host-build-lock.js +30 -0
  165. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  166. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  167. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  168. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  169. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  170. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  171. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  172. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  173. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  174. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  175. package/dist/session/provider-cli/provider-cli.process.d.ts +41 -31
  176. package/dist/session/provider-cli/provider-cli.process.js +139 -438
  177. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  178. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  179. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  180. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  181. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  182. package/dist/session/provider-cli/provider-cli.service.js +200 -189
  183. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  184. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  185. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  186. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  188. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  189. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  190. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  191. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  192. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  193. package/dist/session/provider-cli/provider-output-state.js +15 -0
  194. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  195. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  196. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  197. package/dist/session/publishable-worktree-changes.js +193 -0
  198. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  199. package/dist/session/qa-sidecar-validation.js +28 -0
  200. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  201. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  202. package/dist/session/session-redaction.js +31 -181
  203. package/dist/session/session.base.d.ts +9 -1
  204. package/dist/session/session.service.d.ts +11 -2
  205. package/dist/session/session.service.js +182 -61
  206. package/dist/session/session.types.d.ts +3 -0
  207. package/dist/session/session.types.js +15 -3
  208. package/dist/session/sidecar-json-shape.d.ts +31 -0
  209. package/dist/session/sidecar-json-shape.js +217 -0
  210. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  211. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  212. package/dist/shared/fs/file-identity.d.ts +10 -0
  213. package/dist/shared/fs/file-identity.js +15 -0
  214. package/dist/shared/fs/replace-file.d.ts +7 -0
  215. package/dist/shared/fs/replace-file.js +33 -0
  216. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  217. package/dist/shared/process/host-process-recovery.js +23 -3
  218. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  219. package/dist/shared/process/host-process-supervisor.js +67 -15
  220. package/dist/shared/process/process-tree.d.ts +52 -0
  221. package/dist/shared/process/process-tree.js +144 -0
  222. package/dist/shared/process/process.d.ts +67 -0
  223. package/dist/shared/process/process.js +213 -11
  224. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  225. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  226. package/dist/shared/process/windows-launch.d.ts +18 -0
  227. package/dist/shared/process/windows-launch.js +68 -0
  228. package/dist/shared/provider-capabilities.js +14 -7
  229. package/dist/version.d.ts +1 -1
  230. package/dist/version.js +1 -1
  231. package/dist/worktree/dependency-warmer.d.ts +25 -0
  232. package/dist/worktree/dependency-warmer.js +46 -10
  233. package/dist/worktree/wip-git.d.ts +33 -0
  234. package/dist/worktree/wip-git.js +122 -0
  235. package/dist/worktree/wip-refs.d.ts +62 -0
  236. package/dist/worktree/wip-refs.js +119 -0
  237. package/dist/worktree/wip-restore.d.ts +38 -0
  238. package/dist/worktree/wip-restore.js +190 -0
  239. package/dist/worktree/wip-snapshot.d.ts +50 -0
  240. package/dist/worktree/wip-snapshot.js +268 -0
  241. package/dist/worktree/worktree-inputs.d.ts +8 -0
  242. package/dist/worktree/worktree-inputs.js +134 -0
  243. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  244. package/dist/worktree/worktree-origin-sync.js +127 -0
  245. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  246. package/dist/worktree/worktree-wip-events.js +98 -0
  247. package/dist/worktree/worktree-wip.d.ts +49 -0
  248. package/dist/worktree/worktree-wip.js +182 -0
  249. package/dist/worktree/worktree.base.d.ts +7 -1
  250. package/dist/worktree/worktree.service.d.ts +36 -5
  251. package/dist/worktree/worktree.service.js +120 -155
  252. package/dist/worktree/worktree.types.d.ts +38 -0
  253. package/package.json +2 -2
@@ -2,21 +2,33 @@ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "./session-
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
- import { GitWorktreeService } from "../worktree/worktree.service.js";
5
+ import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree } 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, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
+ import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
9
10
  const minimumReadinessProbeStartupBudgetMs = 150_000;
10
11
  export class BridgeSessionService {
11
12
  worktrees;
12
13
  providerCli;
13
14
  hostRuntime;
15
+ workspaceFingerprint;
14
16
  constructor(worktrees = process.env.FORGE_SANDBOX_ID
15
17
  ? new SandboxWorkspaceService()
16
- : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime) {
18
+ : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime, workspaceFingerprint = readWorkspaceRuntimeFingerprint) {
17
19
  this.worktrees = worktrees;
18
20
  this.providerCli = providerCli;
19
21
  this.hostRuntime = hostRuntime;
22
+ this.workspaceFingerprint = workspaceFingerprint;
23
+ }
24
+ setHostRequirementsCheck(check) {
25
+ this.hostRuntime?.setRequirementsCheck?.(check);
26
+ }
27
+ runnerLimitDefaults() {
28
+ return this.hostRuntime?.capacityLimitDefaults?.() ?? null;
29
+ }
30
+ applyRunnerLimits(limits) {
31
+ this.hostRuntime?.applyCapacityLimits?.(limits);
20
32
  }
21
33
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
22
34
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
@@ -61,6 +73,8 @@ export class BridgeSessionService {
61
73
  // failed agent worktrees for inspection.
62
74
  cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
63
75
  artifacts: [],
76
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: "background" },
77
+ signal,
64
78
  });
65
79
  assertReadinessProbeStartupBudget(request.expiresAt);
66
80
  let started = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal);
@@ -71,6 +85,7 @@ export class BridgeSessionService {
71
85
  status: "serialized",
72
86
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
73
87
  runtimeContractSource: started.runtimeContract.source,
88
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
74
89
  reasonCode: discovery?.reasonCode ?? "host_runtime_contract_serialized",
75
90
  reasonMessage: discovery?.summary ?? "The detected runtime requires serialized host execution.",
76
91
  checkedAt: new Date().toISOString(),
@@ -87,6 +102,7 @@ export class BridgeSessionService {
87
102
  status: "parallel_ready",
88
103
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
89
104
  runtimeContractSource: started.runtimeContract.source,
105
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
90
106
  reasonCode: null,
91
107
  reasonMessage: null,
92
108
  qaAppLaunchTarget: managedQaLaunchTarget(started.runtimeContract),
@@ -174,6 +190,7 @@ export class BridgeSessionService {
174
190
  let worktree = null;
175
191
  let hostSingletonKeys = null;
176
192
  let hostLease = null;
193
+ let succeeded = false;
177
194
  try {
178
195
  if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
179
196
  const capacity = this.hostRuntime.snapshot?.() ?? null;
@@ -248,7 +265,13 @@ export class BridgeSessionService {
248
265
  qaRework: dispatch.qaRework,
249
266
  warmPathOverrides: dispatch.warmPathOverrides,
250
267
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
251
- preserveExistingState: Boolean(dispatch.session.resumedFromSessionId)
268
+ preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
269
+ sessionId: dispatch.session.id,
270
+ hostLoadOwner: {
271
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
272
+ priority: runtimeAdmissionPriority(dispatch),
273
+ },
274
+ signal,
252
275
  });
253
276
  }
254
277
  catch (error) {
@@ -264,6 +287,7 @@ export class BridgeSessionService {
264
287
  : `Prepared worktree ${worktree.branchName}.`,
265
288
  eventType: dispatch.session.resumedFromSessionId ? "worktree_reattached" : "worktree_prepared"
266
289
  });
290
+ await emitWorktreePreparedEvents(worktree, emit);
267
291
  if ((worktree.hydratedPriorPhaseArtifactCount ?? 0) > 0) {
268
292
  await emit({
269
293
  role: "runner",
@@ -326,7 +350,98 @@ export class BridgeSessionService {
326
350
  });
327
351
  }
328
352
  }
353
+ // The stack was built and launched from this workspace state. Pre-publication
354
+ // validation restarts it when the provider has changed the source since.
355
+ let refreshRuntimeEnvironment;
356
+ const hostRuntime = this.hostRuntime;
357
+ if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
358
+ && hostLease.executionClass === "managed_runtime"
359
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
360
+ const worktreePath = worktree.worktreePath;
361
+ const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
362
+ const fencingToken = dispatch.lease.fencingToken;
363
+ const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
364
+ let launchFingerprint = await this.workspaceFingerprint(worktreePath)
365
+ .catch(() => null);
366
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
367
+ let restartPending = false;
368
+ refreshRuntimeEnvironment = async (refreshSignal) => {
369
+ const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
370
+ if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
371
+ return null;
372
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
373
+ // only when both states were read: an unreadable baseline is not a workspace change.
374
+ const comparable = launchFingerprint !== null && current !== null;
375
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
376
+ const causes = [
377
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
378
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
379
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
380
+ ];
381
+ const reason = causes[0] ?? "workspace_changed";
382
+ const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
383
+ await emitLifecycle({
384
+ role: "runner",
385
+ kind: "checkpoint",
386
+ content: reason === "workspace_changed"
387
+ ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
388
+ : reason === "previous_restart_incomplete"
389
+ ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
390
+ : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
391
+ eventType: "host_runtime_restart_started",
392
+ data: JSON.stringify({
393
+ reason,
394
+ causes,
395
+ changes,
396
+ head_sha: current?.headSha ?? null,
397
+ merge_in_progress: Boolean(current?.mergeHead),
398
+ }),
399
+ });
400
+ restartPending = true;
401
+ let restarted;
402
+ try {
403
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
404
+ await emitLifecycle({
405
+ role: "runner",
406
+ kind: "checkpoint",
407
+ content: checkpoint.message,
408
+ eventType: checkpoint.code,
409
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
410
+ });
411
+ });
412
+ }
413
+ catch (error) {
414
+ await emitLifecycle({
415
+ role: "runner",
416
+ kind: "error",
417
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
418
+ eventType: "host_runtime_restart_failed",
419
+ data: JSON.stringify({ reason, causes, changes }),
420
+ }).catch(() => undefined);
421
+ throw error;
422
+ }
423
+ hostLease = restarted;
424
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
425
+ // keep the pre-restart reading, which is null when it could not be collected; a null
426
+ // baseline never matches, so every later pass would restart and rotate ports again.
427
+ launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
428
+ restartPending = false;
429
+ await emitLifecycle({
430
+ role: "runner",
431
+ kind: "checkpoint",
432
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
433
+ eventType: "host_runtime_restarted",
434
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
435
+ });
436
+ return { environment: restarted.environment, reason, changes };
437
+ };
438
+ }
329
439
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
440
+ const providerEnvironment = {
441
+ runtimeEnvironment: hostLease?.environment,
442
+ // Only the completion MCP server gets these: its managed commands share the host ledger.
443
+ hostLoadEnvironment: hostLease ? this.hostRuntime?.hostLoadChildEnvironment?.() : undefined,
444
+ };
330
445
  if (dispatch.draft) {
331
446
  throwIfAborted(signal);
332
447
  const processRunner = hostLease && dispatch.sandbox
@@ -335,13 +450,14 @@ export class BridgeSessionService {
335
450
  const run = await this.providerCli.runDraft({
336
451
  dispatch: providerDispatch,
337
452
  worktree,
338
- runtimeEnvironment: hostLease?.environment,
453
+ ...providerEnvironment,
339
454
  processRunner,
340
455
  emit,
341
456
  signal
342
457
  });
343
458
  throwIfAborted(signal);
344
459
  const draftArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
460
+ succeeded = true;
345
461
  return redactRunOnceResultPacket({
346
462
  schemaVersion: 2,
347
463
  exitCode: 0,
@@ -363,10 +479,13 @@ export class BridgeSessionService {
363
479
  const context = {
364
480
  dispatch: providerDispatch,
365
481
  worktree,
366
- runtimeEnvironment: hostLease?.environment,
482
+ ...providerEnvironment,
367
483
  processRunner: hostLease && dispatch.sandbox
368
484
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
369
485
  : undefined,
486
+ ...(refreshRuntimeEnvironment && hostLease
487
+ ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
488
+ : {}),
370
489
  emit,
371
490
  signal
372
491
  };
@@ -393,6 +512,7 @@ export class BridgeSessionService {
393
512
  }
394
513
  throwIfAborted(signal);
395
514
  const phaseArtifacts = run.artifacts?.length ? run.artifacts : run.artifact ? [run.artifact] : [];
515
+ succeeded = true;
396
516
  return redactRunOnceResultPacket({
397
517
  schemaVersion: 2,
398
518
  exitCode: 0,
@@ -406,70 +526,75 @@ export class BridgeSessionService {
406
526
  }, redactionSecrets);
407
527
  }
408
528
  finally {
409
- if (hostLease && dispatch.sandbox) {
410
- const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
411
- if (providerMemory) {
412
- await emitLifecycle({
413
- role: "runner",
414
- kind: "checkpoint",
415
- content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
416
- eventType: "sandbox_peak_memory_observed",
417
- occurredAt: providerMemory.observedAt,
418
- data: JSON.stringify({
419
- peakMemoryBytes: providerMemory.peakMemoryBytes,
420
- sampleCount: providerMemory.sampleCount,
421
- source: providerMemory.source,
422
- containers: [{
423
- role: "agent",
424
- peakMemoryBytes: providerMemory.peakMemoryBytes,
425
- }],
426
- }),
427
- }).catch(() => undefined);
428
- }
429
- const teardownAt = new Date().toISOString();
529
+ await this.releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle);
530
+ if (worktree) {
531
+ await settleWorktree(this.worktrees, worktree, sessionWipOutcome(signal, events, succeeded), signal, emitLifecycle);
532
+ }
533
+ }
534
+ }
535
+ /** Reports the provider's peak memory and releases the attempt's host runtime lease. */
536
+ async releaseHostRuntime(dispatch, hostLease, hostSingletonKeys, emitLifecycle) {
537
+ if (hostLease && dispatch.sandbox) {
538
+ const providerMemory = this.hostRuntime?.providerMemoryTelemetry?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
539
+ if (providerMemory) {
430
540
  await emitLifecycle({
431
541
  role: "runner",
432
542
  kind: "checkpoint",
433
- content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
434
- eventType: "sandbox_teardown_started",
435
- occurredAt: teardownAt,
543
+ content: `Observed managed-host provider process-tree peak memory ${formatMemoryBytes(providerMemory.peakMemoryBytes)} from ${providerMemory.sampleCount} sample${providerMemory.sampleCount === 1 ? "" : "s"}.`,
544
+ eventType: "sandbox_peak_memory_observed",
545
+ occurredAt: providerMemory.observedAt,
546
+ data: JSON.stringify({
547
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
548
+ sampleCount: providerMemory.sampleCount,
549
+ source: providerMemory.source,
550
+ containers: [{
551
+ role: "agent",
552
+ peakMemoryBytes: providerMemory.peakMemoryBytes,
553
+ }],
554
+ }),
436
555
  }).catch(() => undefined);
437
- try {
438
- const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
439
- if (!released) {
440
- await emitLifecycle({
441
- role: "runner",
442
- kind: "error",
443
- content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
444
- eventType: "teardown_failed",
445
- occurredAt: new Date().toISOString(),
446
- }).catch(() => undefined);
447
- }
448
- else {
449
- await emitLifecycle({
450
- role: "runner",
451
- kind: "checkpoint",
452
- content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
453
- eventType: "sandbox_teardown_completed",
454
- occurredAt: released.releasedAt,
455
- }).catch(() => undefined);
456
- }
457
- }
458
- catch (error) {
556
+ }
557
+ const teardownAt = new Date().toISOString();
558
+ await emitLifecycle({
559
+ role: "runner",
560
+ kind: "checkpoint",
561
+ content: `Releasing host runtime lease ${hostLease.lease.leaseId}.`,
562
+ eventType: "sandbox_teardown_started",
563
+ occurredAt: teardownAt,
564
+ }).catch(() => undefined);
565
+ try {
566
+ const released = await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken);
567
+ if (!released) {
459
568
  await emitLifecycle({
460
569
  role: "runner",
461
570
  kind: "error",
462
- content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
571
+ content: "Host runtime cleanup requires reconciliation: the runtime lease was not current during release.",
463
572
  eventType: "teardown_failed",
464
573
  occurredAt: new Date().toISOString(),
465
574
  }).catch(() => undefined);
466
575
  }
576
+ else {
577
+ await emitLifecycle({
578
+ role: "runner",
579
+ kind: "checkpoint",
580
+ content: `Released host runtime lease ${released.leaseId}. Diagnostics remain runner-local.`,
581
+ eventType: "sandbox_teardown_completed",
582
+ occurredAt: released.releasedAt,
583
+ }).catch(() => undefined);
584
+ }
467
585
  }
468
- if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
469
- await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
586
+ catch (error) {
587
+ await emitLifecycle({
588
+ role: "runner",
589
+ kind: "error",
590
+ content: `Host runtime cleanup requires reconciliation: ${error instanceof Error ? error.message : String(error)}`,
591
+ eventType: "teardown_failed",
592
+ occurredAt: new Date().toISOString(),
593
+ }).catch(() => undefined);
470
594
  }
471
- if (worktree && !isPauseCancellation(signal))
472
- await this.worktrees.release(worktree);
595
+ }
596
+ if (!hostLease && hostSingletonKeys && dispatch.sandbox) {
597
+ await this.hostRuntime?.release(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken).catch(() => undefined);
473
598
  }
474
599
  }
475
600
  }
@@ -479,10 +604,6 @@ function failureMessage(error) {
479
604
  function formatMemoryBytes(bytes) {
480
605
  return `${(bytes / (1024 ** 2)).toFixed(bytes >= 1024 ** 3 ? 0 : 1)} MiB`;
481
606
  }
482
- function isPauseCancellation(signal) {
483
- return signal?.aborted === true
484
- && String(signal.reason ?? "").trim().toLowerCase() === "session pause requested";
485
- }
486
607
  function readinessProbeDispatch(request) {
487
608
  return {
488
609
  schemaVersion: 2,
@@ -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,18 +469,21 @@ 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", "runner_yielding", "runner_settings_pending", "runner_settings_apply_failed", "runner_tier_light", "runner_project_not_allowed"].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)) {
482
482
  return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
483
483
  }
484
+ if (["comment_repair_changed_files_mismatch", "runner_result_sidecar_malformed"].includes(code)) {
485
+ return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
486
+ }
484
487
  if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
485
488
  return facts(code, "transport", "prepare", source, "retryable", "retry_dispatch");
486
489
  }
@@ -493,7 +496,7 @@ function unvalidatedFailureFactsForCode(code, source) {
493
496
  if (code === "provider_configuration_invalid") {
494
497
  return facts(code, "provider", "prepare", source, "non_retryable", "fix_environment");
495
498
  }
496
- if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
499
+ if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_contract_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
497
500
  return facts(code, "resource", "prepare", source, "retryable", "retry_dispatch");
498
501
  }
499
502
  if (code === "host_runtime_project_start_failed") {
@@ -519,6 +522,12 @@ function unvalidatedFailureFactsForCode(code, source) {
519
522
  if (code === "provider_capacity_unavailable") {
520
523
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
521
524
  }
525
+ if (code === "provider_completion_tool_missing") {
526
+ return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
527
+ }
528
+ if (["provider_terminated_at_turn_ceiling", "provider_turn_ended_with_background_work"].includes(code)) {
529
+ return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
530
+ }
522
531
  if (code === "provider_context_window_exhausted") {
523
532
  return facts(code, "provider", "agent", source, "retryable", "retry_dispatch");
524
533
  }
@@ -563,6 +572,9 @@ function unvalidatedFailureFactsForCode(code, source) {
563
572
  if (code === "worktree_branch_integration_conflict") {
564
573
  return facts(code, "domain", "agent", source, "non_retryable", "fix_input");
565
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
+ }
566
578
  if (stableFailureFamilyCodes.has(code) && code.startsWith("sandbox_")) {
567
579
  return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
568
580
  }
@@ -0,0 +1,31 @@
1
+ export declare const maximumIntegrityJsonBytes: number;
2
+ /** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
3
+ export declare class JsonShapeError extends Error {
4
+ readonly reason: string;
5
+ constructor(reason: string);
6
+ }
7
+ export declare const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
8
+ /**
9
+ * Checks a bounded JSON text and calls `onString` with every decoded string token (property names
10
+ * and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
11
+ */
12
+ export declare function inspectJsonText(value: string, onString?: (decoded: string) => void): void;
13
+ export declare function decodeJsonStringToken(value: string, openingQuoteIndex: number): {
14
+ readonly decoded: string;
15
+ readonly nextIndex: number;
16
+ };
17
+ /**
18
+ * Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
19
+ * plain text that does not start like JSON, or binary content that is not named *.json.
20
+ */
21
+ export declare function sidecarJsonShapeProblem(content: Uint8Array, path: string, onString?: (decoded: string) => void): string | null;
22
+ /** The instruction an agent gets when it records a sidecar that fails the shape check. */
23
+ export declare function sidecarJsonRepairInstruction(path: string, reason: string): string;
24
+ /**
25
+ * Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
26
+ * hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
27
+ */
28
+ export declare function decodeJsonEscapesLeniently(value: string): string;
29
+ export declare function looksLikeJson(value: string, path: string): boolean;
30
+ export declare function isJsonWhitespace(code: number): boolean;
31
+ export declare function isJsonPunctuation(code: number): boolean;